From de80616b4d0ca6cb9cf7616e33997001b7640791 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:54 +0100 Subject: [PATCH 0001/1514] dt-bindings: apple: Add the T8152 AOP and its audio service The T8152 (M6) Always-On Processor differs from the T8140 one: its setup port is not reachable from the AP, so it has one mailbox, and its audio service uses six serializer power domains and the jack, speaker and speaker-sense ADMAC channels. Signed-off-by: Thomas Glanzmann --- .../bindings/soc/apple/apple,t8152-aop.yaml | 80 ++++++++++++++++++ .../bindings/sound/apple,t8152-aop-audio.yaml | 82 +++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml create mode 100644 Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml new file mode 100644 index 00000000000000..de41937be02590 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,t8152-aop.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 Always-On Processor + +maintainers: + - Thomas Glanzmann + +description: + The Always-On Processor provides audio services through firmware loaded by + the bootloader. Unlike on T8140, its setup port is not reachable from the + application processor, so only the primary mailbox is described. + +properties: + compatible: + const: apple,t8152-aop + + reg: + items: + - description: AOP register and boot-argument window + - description: ASC wrapper and processor control registers + + reg-names: + items: + - const: mmio + - const: asc + + mboxes: + maxItems: 1 + + mbox-names: + items: + - const: mbox + + iommus: + maxItems: 1 + + apple,dma-range: + $ref: /schemas/types.yaml#/definitions/uint64-array + minItems: 2 + maxItems: 2 + description: + Host DMA allocation window as a base and nonzero size. The window must + occupy root slots available to the host on this AOP DART stream. + + audio: + type: object + $ref: /schemas/sound/apple,t8152-aop-audio.yaml# + +required: + - compatible + - reg + - reg-names + - mboxes + - mbox-names + - iommus + - apple,dma-range + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + aop@310c00000 { + compatible = "apple,t8152-aop"; + reg = <0x3 0x10c00000 0x0 0x1e0000>, + <0x3 0x10600000 0x0 0x4000>; + reg-names = "mmio", "asc"; + mboxes = <&aop_mbox>; + mbox-names = "mbox"; + iommus = <&sbr_dart 0>; + apple,dma-range = <0x110 0x0 0x10 0x0>; + }; + }; diff --git a/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml new file mode 100644 index 00000000000000..fa643fe62a9df9 --- /dev/null +++ b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/sound/apple,t8152-aop-audio.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 AOP audio + +maintainers: + - Thomas Glanzmann + +description: + Audio services of the T8152 Always-On Processor firmware, a child of the + AOP node. The firmware owns the audio fabric; the host feeds and drains the + serializers through ADMAC channels. + +allOf: + - $ref: dai-common.yaml# + +properties: + compatible: + const: apple,t8152-aop-audio + + dmas: + items: + - description: Headset jack output + - description: Headset microphone input + - description: Internal speaker output + - description: Speaker sense input + + dma-names: + items: + - const: cout + - const: cin + - const: spkr + - const: sense + + power-domains: + items: + - description: Serializer 0 + - description: Serializer 1 + - description: Serializer 2 + - description: Serializer 3 + - description: Serializer 4 + - description: Serializer 5 + + power-domain-names: + items: + - const: mca0 + - const: mca1 + - const: mca2 + - const: mca3 + - const: mca4 + - const: mca5 + + "#sound-dai-cells": + const: 1 + description: + AOP audio DAI identifier. 0 is the headset back-end, 3 the speaker + back-end. + +required: + - compatible + - dmas + - dma-names + - power-domains + - power-domain-names + - "#sound-dai-cells" + +unevaluatedProperties: false + +examples: + - | + audio { + compatible = "apple,t8152-aop-audio"; + dmas = <&admac 10>, <&admac 11>, <&admac 2>, <&admac 3>; + dma-names = "cout", "cin", "spkr", "sense"; + power-domains = <&ps_mca0>, <&ps_mca1>, <&ps_mca2>, + <&ps_mca3>, <&ps_mca4>, <&ps_mca5>; + power-domain-names = "mca0", "mca1", "mca2", "mca3", "mca4", "mca5"; + #sound-dai-cells = <1>; + }; From 3fd4c1beb0192540dcdb4439c99ef69be930200c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:54 +0100 Subject: [PATCH 0002/1514] dt-bindings: sound: apple,macaudio: Add J873 Add the Mac mini M6 (J873) sound card. Signed-off-by: Thomas Glanzmann --- Documentation/devicetree/bindings/sound/apple,macaudio.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml index e593b7b6d68c4d..4ce5f8f2f0a8b8 100644 --- a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml @@ -27,6 +27,7 @@ properties: - apple,j700-macaudio - apple,j713-macaudio - apple,j713-macaudio-jack + - apple,j873-macaudio - const: apple,macaudio "#address-cells": From 8dd4d517119dd14590ab7dd61e575144ef9f08c9 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:31 +0100 Subject: [PATCH 0003/1514] soc: apple: aop: support T8152 The J873 (Mac mini M6) AOP runs the same firmware generation as T8140 (EPIC v4, iBoot-loaded, started by the AP), but the T8140 "setup port" is not reachable from the AP: mailbox 1 of the AOP's mailbox bank and the ADT aop-exclave-mailbox both bus-error. The firmware boots without it: RTKit protocol 12, then its "audio" EPIC service. Add apple,t8152-aop with the T8140 configuration minus the setup port, starting every advertised endpoint. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/aop.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 20e78e2b542cb9..73df7cf27deaab 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -2665,6 +2665,20 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, }; +/// T8152: like T8140, but the setup port (mailbox 1 of the AOP bank, and the +/// ADT aop-exclave-mailbox) is not reachable from the AP: both bus-error. +const HW_CFG_T8152: AopHwConfig = AopHwConfig { + ec0p: 0, + aopt: 0, + alig: 0, + patch_bootargs: false, + epic_v4: true, + setup_port: false, + quiesce_on_unbind: true, + required_endpoints: &[], + fw_regions: false, + halt_on_failed_start: false, +}; kernel::of_device_table!( OF_TABLE, @@ -2677,6 +2691,7 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6040), (of::DeviceId::new(c_str!("apple,t8132-aop")), &HW_CFG_T8132), + (of::DeviceId::new(c_str!("apple,t8152-aop")), &HW_CFG_T8152), ] ); From 53a18f3f84a740088484f9670f5d3d4a8201b464 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:16:38 +0100 Subject: [PATCH 0004/1514] dt-bindings: sound: ti,tas27xx: add ti,bclk-ratio The Mac mini (M6, J873) speaker runs a 250-BCLK TDM frame, which the SN012776's ratio auto-detection rejects. Describe the property that fixes the ratio instead. Signed-off-by: Thomas Glanzmann --- Documentation/devicetree/bindings/sound/ti,tas27xx.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/ti,tas27xx.yaml b/Documentation/devicetree/bindings/sound/ti,tas27xx.yaml index e9a7e873254487..2a02a98ae7ce91 100644 --- a/Documentation/devicetree/bindings/sound/ti,tas27xx.yaml +++ b/Documentation/devicetree/bindings/sound/ti,tas27xx.yaml @@ -122,6 +122,14 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: TDM TX voltage sense time slot. + ti,bclk-ratio: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [250] + description: + Fixed BCLK/FS ratio of the TDM frame, for a frame the amplifier's ratio + auto-detection does not accept (250 BCLKs on the Mac mini (M6, J873) + speaker). + '#sound-dai-cells': # The codec has a single DAI, the #sound-dai-cells=<1>; case is left in for backward # compatibility but is deprecated. From 9415ba9f8d608f35770436be3013fd82a3c0266d Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:31 +0100 Subject: [PATCH 0005/1514] ASoC: tas2764: support a fixed BCLK/FS ratio The J873 (Mac mini M6) AOP runs the speaker frame at 250 BCLKs of 12 MHz. The SN012776 cannot auto-detect that ratio and mutes with "fault: bad TDM clock". With TAS2764_CLK_CFG (register 0x60) set to 0x30 and TDM_CFG0 bit 6 set it accepts the frame and plays. Do that when the new ti,bclk-ratio property names the ratio; only this one ratio is supported. Source of the value: the register write was first seen in the macOS SN012776 driver; it is a single register value, and its effect (no fault, correct playback) was verified on J873 hardware. No table or code was taken from macOS. The field is initialised in probe, so non-OF matches keep auto-detection. Signed-off-by: Thomas Glanzmann --- sound/soc/codecs/tas2764.c | 41 ++++++++++++++++++++++++++++++++++++++ sound/soc/codecs/tas2764.h | 8 ++++++++ 2 files changed, 49 insertions(+) diff --git a/sound/soc/codecs/tas2764.c b/sound/soc/codecs/tas2764.c index c7886269a2dd4b..3cec2ba9da4303 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -66,6 +66,8 @@ struct tas2764_priv { int v_sense_slot; int i_sense_slot; + /* TAS2764_CLK_CFG value for a fixed BCLK/FS ratio, or -1 to auto-detect */ + int bclk_ratio_code; bool dac_powered; bool unmuted; @@ -1155,6 +1157,19 @@ static int tas2764_codec_probe(struct snd_soc_component *component) break; } + if (tas2764->bclk_ratio_code >= 0) { + ret = snd_soc_component_write(component, TAS2764_CLK_CFG, + tas2764->bclk_ratio_code); + if (ret < 0) + return ret; + + ret = snd_soc_component_update_bits(component, TAS2764_TDM_CFG0, + TAS2764_TDM_CFG0_FIXED_RATIO, + TAS2764_TDM_CFG0_FIXED_RATIO); + if (ret < 0) + return ret; + } + /* * Last, so that no failure leaves the handler behind. The component owns the IRQ and * the remove frees it; not a devres of the I2C device, which outlives the component @@ -1407,9 +1422,24 @@ static int tas2764_parse_tx_zd_config(struct device *dev, struct tas2764_priv *t return 0; } +/* + * BCLK/FS ratios and the TAS2764_CLK_CFG value that makes the amplifier + * accept them. Only the J873 speaker frame (250 BCLKs, which the ratio + * auto-detection rejects with "bad TDM clock") is verified on hardware; + * other ratios are left to the auto-detection. + */ +static const struct { + u16 ratio; + u8 code; +} tas2764_bclk_ratio_codes[] = { + { 250, 0x30 }, +}; + static int tas2764_parse_dt(struct device *dev, struct tas2764_priv *tas2764) { + u32 ratio; int ret = 0; + int i; /* * The SDZ supply is optional: most boards drive SDZ from a GPIO @@ -1467,6 +1497,15 @@ static int tas2764_parse_dt(struct device *dev, struct tas2764_priv *tas2764) if (ret) return ret; + if (!fwnode_property_read_u32(dev->fwnode, "ti,bclk-ratio", &ratio)) { + for (i = 0; i < ARRAY_SIZE(tas2764_bclk_ratio_codes); i++) + if (tas2764_bclk_ratio_codes[i].ratio == ratio) + tas2764->bclk_ratio_code = tas2764_bclk_ratio_codes[i].code; + if (tas2764->bclk_ratio_code < 0) + return dev_err_probe(dev, -EINVAL, + "unsupported ti,bclk-ratio %u\n", ratio); + } + return tas2764_group_join(dev, tas2764); } @@ -1488,6 +1527,8 @@ static int tas2764_i2c_probe(struct i2c_client *client) result = devm_mutex_init(&client->dev, &tas2764->fault_lock); if (result) return result; + /* Auto-detect the ratio unless the firmware node sets one. */ + tas2764->bclk_ratio_code = -1; i2c_set_clientdata(client, tas2764); dev_set_drvdata(&client->dev, tas2764); diff --git a/sound/soc/codecs/tas2764.h b/sound/soc/codecs/tas2764.h index e6c6b064d6cc21..7f72f997345128 100644 --- a/sound/soc/codecs/tas2764.h +++ b/sound/soc/codecs/tas2764.h @@ -58,6 +58,12 @@ #define TAS2764_TDM_CFG0_44_1_48KHZ BIT(3) #define TAS2764_TDM_CFG0_88_2_96KHZ (BIT(3) | BIT(1)) #define TAS2764_TDM_CFG0_FRAME_START BIT(0) +/* + * Set by the macOS SN012776 driver together with an explicit BCLK/FS + * ratio in TAS2764_CLK_CFG; without it the ratio is auto-detected, which + * fails ("bad TDM clock") for frames such as 250 BCLKs. + */ +#define TAS2764_TDM_CFG0_FIXED_RATIO BIT(6) /* TDM Configuration Reg1 */ #define TAS2764_TDM_CFG1 TAS2764_REG(0X0, 0x09) @@ -123,6 +129,8 @@ /* Clock/IRQ Settings */ #define TAS2764_INT_CLK_CFG TAS2764_REG(0x0, 0x5c) +/* BCLK/FS ratio code, written by macOS for the J873 speaker frame */ +#define TAS2764_CLK_CFG TAS2764_REG(0x0, 0x60) #define TAS2764_INT_CLK_CFG_IRQZ_CLR BIT(2) #define TAS2764_BOP_CFG0 TAS2764_REG(0X0, 0x1d) From 4579f2e7936b7f504e754a6c2881ef0f1f439041 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 1 Nov 2026 21:36:59 +0100 Subject: [PATCH 0006/1514] ASoC: cs42l84: Route SDOUT1 from the ASP input The SDOUT1 mux offers the ASP receive channels as a source, but no DAPM route connected them, so selecting "ASP RX CH1" or "ASP RX CH2" left the capture path without an input. The J873 and J813 AOP audio services use it to loop the playback stream back. Signed-off-by: Thomas Glanzmann --- sound/soc/codecs/cs42l84.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 022420be6bfb58..07a47433ef4d91 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -279,6 +279,8 @@ static const struct snd_soc_dapm_route cs42l84_audio_map[] = { {"ADC", NULL, "HS"}, {"SDOUT1 Select", "ADC", "ADC"}, + {"SDOUT1 Select", "ASP RX CH1", "SDIN1"}, + {"SDOUT1 Select", "ASP RX CH2", "SDIN2"}, {"SDOUT1", NULL, "SDOUT1 Select"}, {"Capture", NULL, "SDOUT1"}, From 7981f33f77bd186b4b68fb1e22e74eb3aaa4594c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:31 +0100 Subject: [PATCH 0007/1514] ASoC: apple: add the T8152 AOP audio driver On T8152 (J873, Mac mini M6) the AOP firmware owns the audio fabric, as on T8140. Its "audio" EPIC service offers cout/cin (the CS42L84 jack, base-ns ADMAC TX5/RX5, MCA4) and spkr (the SN012776 speaker, TX1, MCA0). Each service is an ASoC back-end DAI: startup attaches it, requests pw0 (which raises the audio fabric) and powers the MCA leaves, all of which are required. pwrd starts the serializer clocks at prepare, before ASoC unmutes the codecs: the jack codec locks its PLL to the bit clock, and the speaker amplifier reports "bad TDM clock" whenever it runs without one. The jack restarts its clocks on every prepare so that a stream restarted after an underrun begins on a frame boundary; the mono speaker (one slot per frame) keeps them running. The front-ends are dmaengine PCMs on the base-ns channels: the jack in stereo, the speaker in mono (its serializer runs one 32-bit slot; stereo frames play at half pitch). The firmware's serializer configuration (property 701) is byte-identical to the one macOS publishes, so the driver leaves it alone. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/Kconfig | 11 + sound/soc/apple/Makefile | 3 + sound/soc/apple/t8152_aop_audio.rs | 995 +++++++++++++++++++++++++++++ 3 files changed, 1009 insertions(+) create mode 100644 sound/soc/apple/t8152_aop_audio.rs diff --git a/sound/soc/apple/Kconfig b/sound/soc/apple/Kconfig index 92ffcb60737971..74ea1fe4de8e8a 100644 --- a/sound/soc/apple/Kconfig +++ b/sound/soc/apple/Kconfig @@ -14,6 +14,17 @@ config SND_SOC_APPLE_AOP_AUDIO machines, and on T8140 the back-end DAIs for the headphone jack and the internal speaker, which the macaudio driver links into its card. +config SND_SOC_APPLE_T8152_AOP_AUDIO + tristate "Apple T8152 AOP audio driver" + depends on ARCH_APPLE || COMPILE_TEST + depends on RUST + select APPLE_AOP + select SND_DMAENGINE_PCM + help + This option enables a driver for the audio paths owned by the AOP + co-processor on Apple T8152 SoCs (Mac mini M6): the headphone jack + and the internal speaker. + config SND_SOC_APPLE_MCA tristate "Apple Silicon MCA driver" depends on ARCH_APPLE || COMPILE_TEST diff --git a/sound/soc/apple/Makefile b/sound/soc/apple/Makefile index 52d4abf30916b1..71885319572cf2 100644 --- a/sound/soc/apple/Makefile +++ b/sound/soc/apple/Makefile @@ -3,6 +3,9 @@ snd-soc-aop-y := aop_audio.o obj-$(CONFIG_SND_SOC_APPLE_AOP_AUDIO) += snd-soc-aop.o +snd-soc-t8152-aop-audio-y := t8152_aop_audio.o +obj-$(CONFIG_SND_SOC_APPLE_T8152_AOP_AUDIO) += snd-soc-t8152-aop-audio.o + snd-soc-apple-mca-y := mca.o obj-$(CONFIG_SND_SOC_APPLE_MCA) += snd-soc-apple-mca.o diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs new file mode 100644 index 00000000000000..31f562e7fc64d1 --- /dev/null +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -0,0 +1,995 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Apple T8152 (J873, Mac mini M6) AOP audio +//! +//! The AOP firmware owns the audio fabric, as on T8140. The ADT +//! (/arm-io/iop-audio-controller) names its services; all of them run on the +//! base-ns ADMAC: +//! +//! * `cout`/`cin`: the CS42L84 headphone jack, base-ns TX5/RX5 (Linux +//! channels 10 and 11). +//! * `spkr`: the SN012776 speaker amplifier, base-ns TX1 (channel 2), its +//! sense data on RX1. +//! +//! Each service is an ASoC back-end DAI: startup attaches it and requests +//! `pw0 ` (which also brings up the audio fabric), prepare requests `pwrd` +//! (the firmware then runs the serializer and its clocks) and shutdown goes +//! back to `pw0 `. The serializer (MCA) leaves are the AP's to power. The +//! front-end PCMs are plain dmaengine PCMs on the base-ns channels; macaudio +//! links them to the codecs. +//! +//! Copyright (C) The Asahi Linux Contributors +//! Copyright (C) 2026 The Aurora Silicon Contributors + +use core::{mem, ptr, slice}; + +use kernel::{ + bindings, c_str, + device, + device::Core, + error::from_err_ptr, + module_platform_driver, of, platform, + prelude::*, + soc::apple::aop::{from_fourcc, EPICService, AOP}, + sync::{ + aref::ARef, + atomic::{Atomic, AtomicFlag, Relaxed}, + Arc, + }, + types::Opaque, +}; + +const EPIC_SUBTYPE_WRAPPED_CALL: u16 = 0x20; +const CALLTYPE_AUDIO_ATTACH_DEVICE: u32 = 0xc3000002; +const CALLTYPE_AUDIO_GET_PROP: u32 = 0xc3000004; +const CALLTYPE_AUDIO_SET_PROP: u32 = 0xc3000005; +const PROP_POWER_STATE: u32 = 200; +const PROP_POWER_REQUEST: u32 = 202; +const POWER_STATE_PW0: u32 = from_fourcc(b"pw0 "); +const POWER_STATE_PWRD: u32 = from_fourcc(b"pwrd"); +/// kIOReturnBusy: the device is already attached (a module reload). +const AUDIO_RET_BUSY: u32 = 0xe00002d5; +const AOP_TIMEBASE_HZ: u64 = 24_000_000; + +/// Leaf power-up attempts while the firmware raises the fabric after `pw0 `. +const PD_GET_ATTEMPTS: u32 = 60; +const PD_GET_RETRY_MS: i64 = 10; +/// The MCA serializer leaves (audio_mca0_m .. audio_mca5_m). +const MCA_COUNT: usize = 6; +const MCA_NAMES: [&CStr; MCA_COUNT] = [c"mca0", c"mca1", c"mca2", c"mca3", c"mca4", c"mca5"]; + +fn aop_timestamp() -> u64 { + // SAFETY: both helpers read the architected timer and take no arguments. + let (counter, rate) = + unsafe { (bindings::arch_timer_counter(), bindings::arch_timer_rate()) }; + let rate = u64::from(rate); + (counter / rate) * AOP_TIMEBASE_HZ + (counter % rate) * AOP_TIMEBASE_HZ / rate +} + +fn le_u32(buf: &[u8], off: usize) -> Result { + let b = buf.get(off..off + 4).ok_or(EINVAL)?; + Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) +} + +#[repr(C, packed(4))] +#[derive(Clone, Copy, Default)] +struct AudioAttachDevice { + _zero0: u32, + unk0: u32, + calltype: u32, + _zero1: [u8; 16], + cookie: u32, + len: u64, + dev_id: u32, + _zero2: u32, +} + +#[repr(C, packed(4))] +#[derive(Clone, Copy, Default)] +struct AudioGetDeviceProp { + _zero0: u32, + unk0: u32, + calltype: u32, + _zero1: [u8; 16], + _pad0: u32, + len: u64, + dev_id: u32, + modifier: u32, + unk6: u32, +} + +#[repr(C, packed(4))] +#[derive(Clone, Copy, Default)] +struct AudioSetDeviceProp { + _zero0: u32, + unk0: u32, + calltype: u32, + _zero1: [u8; 16], + _pad0: u32, + len: u64, + dev_id: u32, + modifier: u32, + len2: u32, + data: T, +} + +/// Property 202: the device, a per-device sequence, the request time in the +/// firmware's 24 MHz timebase and the target state. +#[repr(C, packed(4))] +#[derive(Clone, Copy, Default)] +struct PowerRequest { + dev_id: u32, + sequence: u32, + timestamp: u64, + _zero0: u32, + state: u32, + param: u32, + _zero1: [u8; 20], +} + +/// A named power domain of this device, runtime-powered around the streams +/// that need it. +struct PowerDomain { + dev: ptr::NonNull, +} + +// SAFETY: the virtual domain device belongs to the PM core, which serializes +// its runtime-PM state; this handle only passes the pointer to those calls. +unsafe impl Send for PowerDomain {} +// SAFETY: as for `Send`. +unsafe impl Sync for PowerDomain {} + +impl PowerDomain { + fn attach(dev: &device::Device, name: &CStr) -> Result> { + // SAFETY: `dev` is live for the call and `name` is NUL-terminated. + let pd = from_err_ptr(unsafe { + bindings::dev_pm_domain_attach_by_name(dev.as_raw(), name.as_char_ptr()) + })?; + Ok(ptr::NonNull::new(pd).map(|dev| PowerDomain { dev })) + } + + /// Takes a runtime-PM reference, retrying while the parent fabric that + /// the firmware brings up after `pw0 ` is still off. + fn get(&self) -> Result<()> { + let mut rc = 0; + for _ in 0..PD_GET_ATTEMPTS { + // SAFETY: the domain device stays attached for the lifetime of `self`. + rc = unsafe { bindings::pm_runtime_get_sync(self.dev.as_ptr()) }; + if rc >= 0 { + return Ok(()); + } + // SAFETY: as above; undo the usage count and the error state. + unsafe { + bindings::pm_runtime_put_noidle(self.dev.as_ptr()); + bindings::__pm_runtime_set_status( + self.dev.as_ptr(), + bindings::rpm_status_RPM_SUSPENDED as u32, + ); + } + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(PD_GET_RETRY_MS)); + } + Err(Error::from_errno(rc)) + } + + fn put(&self) { + // SAFETY: the domain device stays attached for the lifetime of `self`. + unsafe { bindings::pm_runtime_put_sync(self.dev.as_ptr()) }; + } +} + +impl Drop for PowerDomain { + fn drop(&mut self) { + // SAFETY: attached in `attach`; every `get` has been balanced by then. + unsafe { bindings::dev_pm_domain_detach(self.dev.as_ptr(), true) }; + } +} + +/// One firmware audio service driven as an ASoC back-end. +struct Service { + dev_id: u32, + name: &'static str, + sequence: Atomic, + /// In `pwrd`. + running: AtomicFlag, + /// Stop and restart the serializer on every prepare, so that a stream + /// restarted after an underrun begins on a frame boundary. The mono + /// speaker has one slot per frame and keeps its clocks running instead: + /// its amplifier stays unmuted between prepares and reports "bad TDM + /// clock" whenever the bit clock stops under it. + restart_on_prepare: bool, +} + +impl Service { + const fn new(dev_id: u32, name: &'static str, restart_on_prepare: bool) -> Service { + Service { + dev_id, + name, + sequence: Atomic::new(0), + running: AtomicFlag::new(false), + restart_on_prepare, + } + } +} + +#[pin_data] +struct T8152AopAudio { + dev: ARef, + adata: Arc, + service: EPICService, + cout: Service, + cin: Service, + spkr: Service, + mca: KVec, +} + +impl T8152AopAudio { + fn call_ret(&self, data: &T, ret_len: usize) -> Result<(u32, KVec)> { + // SAFETY: T is a plain packed firmware record. + let msg = unsafe { + slice::from_raw_parts(ptr::from_ref(data).cast::(), mem::size_of::()) + }; + self.adata + .epic_call_ret(&self.service, EPIC_SUBTYPE_WRAPPED_CALL, msg, ret_len) + } + + fn call(&self, data: &T) -> Result { + // SAFETY: T is a plain packed firmware record. + let msg = unsafe { + slice::from_raw_parts(ptr::from_ref(data).cast::(), mem::size_of::()) + }; + self.adata + .epic_call(&self.service, EPIC_SUBTYPE_WRAPPED_CALL, msg) + } + + /// The firmware keeps attachments for its lifetime, so a module reload + /// sees kIOReturnBusy. + fn attach(&self, svc: &Service) -> Result<()> { + let ret = self.call(&AudioAttachDevice { + unk0: 0xffffffff, + calltype: CALLTYPE_AUDIO_ATTACH_DEVICE, + len: 0x2c, + dev_id: svc.dev_id, + ..Default::default() + })?; + match ret { + 0 | AUDIO_RET_BUSY => Ok(()), + _ => { + dev_err!(self.dev, "unable to attach {}: {:#x}\n", svc.name, ret); + Err(EIO) + } + } + } + + fn power_state(&self, svc: &Service) -> Result { + let (ret, data) = self.call_ret( + &AudioGetDeviceProp { + unk0: 0xffffffff, + calltype: CALLTYPE_AUDIO_GET_PROP, + len: 0x30, + dev_id: svc.dev_id, + modifier: PROP_POWER_STATE, + unk6: 1, + ..Default::default() + }, + 8, + )?; + if ret != 0 { + return Err(EIO); + } + le_u32(&data, 4) + } + + fn set_power(&self, svc: &Service, state: u32) -> Result<()> { + let req = PowerRequest { + dev_id: svc.dev_id, + sequence: svc.sequence.fetch_add(1, Relaxed) + 1, + timestamp: aop_timestamp(), + state, + ..Default::default() + }; + let ret = self.call(&AudioSetDeviceProp { + unk0: 0xffffffff, + calltype: CALLTYPE_AUDIO_SET_PROP, + len: mem::size_of::() as u64 + 0x30, + dev_id: svc.dev_id, + modifier: PROP_POWER_REQUEST, + len2: mem::size_of::() as u32, + data: req, + ..Default::default() + })?; + if ret != 0 { + dev_err!( + self.dev, + "{}: power request {:#x} rejected: {:#x}\n", + svc.name, + state, + ret + ); + return Err(EIO); + } + let now = self.power_state(svc)?; + if now != state { + dev_err!( + self.dev, + "{}: power state {:#x} after requesting {:#x}\n", + svc.name, + now, + state + ); + return Err(EIO); + } + Ok(()) + } + + fn mca_up(&self) -> Result<()> { + for (i, pd) in self.mca.iter().enumerate() { + if let Err(e) = pd.get() { + dev_err!(self.dev, "MCA leaf {} did not power up: {:?}\n", i, e); + for pd in self.mca[..i].iter().rev() { + pd.put(); + } + return Err(e); + } + } + Ok(()) + } + + fn mca_down(&self) { + for pd in self.mca.iter().rev() { + pd.put(); + } + } + + /// Back-end startup: attach, `pw0 ` (which raises the fabric), then the + /// serializer leaves. + fn startup(&self, svc: &Service) -> Result<()> { + self.attach(svc)?; + self.set_power(svc, POWER_STATE_PW0)?; + if let Err(e) = self.mca_up() { + let _ = self.set_power(svc, POWER_STATE_PW0); + return Err(e); + } + svc.running.store(false, Relaxed); + Ok(()) + } + + /// `pwrd`: the firmware starts the serializer clocks and the stream. + fn run(&self, svc: &Service) -> Result<()> { + if svc.running.load(Relaxed) { + return Ok(()); + } + self.set_power(svc, POWER_STATE_PWRD)?; + svc.running.store(true, Relaxed); + Ok(()) + } + + /// The clocks run from prepare on: the codecs see a bit clock as soon + /// as ASoC powers and unmutes them. A PCM underrun stops the DMA + /// without closing the back-end; a service that restarts on prepare + /// retires its run so that the next start begins afresh. + fn prepare(&self, svc: &Service) -> Result<()> { + if svc.restart_on_prepare && svc.running.load(Relaxed) { + self.set_power(svc, POWER_STATE_PW0)?; + svc.running.store(false, Relaxed); + } + self.run(svc) + } + + fn shutdown(&self, svc: &Service) { + if svc.running.load(Relaxed) { + if let Err(e) = self.set_power(svc, POWER_STATE_PW0) { + dev_err!(self.dev, "{}: pw0 failed: {:?}\n", svc.name, e); + } + svc.running.store(false, Relaxed); + } + self.mca_down(); + } +} + +// ---- the ASoC component ---- + +/// Front-end index of a runtime by CPU DAI id; back-ends have none. +const FE_DAI_ID_BASE: u32 = 1; +const FE_COUNT: usize = 3; +const BE_DAI_ID_COUT: u32 = 10; +const BE_DAI_ID_SPKR: u32 = 11; +/// DMA channel names (dma-names on the audio node) per front-end, [playback, +/// capture]: the jack, the speaker and the speaker's sense data. +const FE_DMA_NAMES: [[Option<&CStr>; 2]; FE_COUNT] = [ + [Some(c"cout"), Some(c"cin")], + [Some(c"spkr"), None], + [None, Some(c"sense")], +]; + +const PCM_BUFFER_MAX: usize = 1024 * 1024; +const PCM_PERIOD_BYTES_MIN: usize = 256; +const PCM_PERIOD_BYTES_MAX: usize = 0x10000; + +/// The AOP-run serializers take 24-bit samples in 32-bit words. +const FORMATS: u64 = bindings::BINDINGS_SNDRV_PCM_FMTBIT_S24_LE; + +/// # Safety +/// +/// `substream` must be live and belong to one of this component's links. +unsafe fn substream_rtd( + substream: *mut bindings::snd_pcm_substream, +) -> *mut bindings::snd_soc_pcm_runtime { + // SAFETY: by the caller's contract. + unsafe { (*substream).private_data.cast() } +} + +/// # Safety +/// +/// `rtd` must be a live ASoC runtime. +unsafe fn rtd_is_be(rtd: *mut bindings::snd_soc_pcm_runtime) -> bool { + // SAFETY: by the caller's contract. + unsafe { (*(*rtd).dai_link).no_pcm() != 0 } +} + +/// # Safety +/// +/// `rtd` must be a live ASoC runtime of one of this component's links. +unsafe fn fe_index(rtd: *mut bindings::snd_soc_pcm_runtime) -> Option { + // SAFETY: by the caller's contract. + let id = unsafe { (**(*rtd).dais).id } as u32; + if (FE_DAI_ID_BASE..FE_DAI_ID_BASE + FE_COUNT as u32).contains(&id) { + Some((id - FE_DAI_ID_BASE) as usize) + } else { + None + } +} + +/// # Safety +/// +/// `substream` must be live. +unsafe fn is_playback(substream: *mut bindings::snd_pcm_substream) -> bool { + // SAFETY: by the caller's contract. + unsafe { (*substream).stream == bindings::SNDRV_PCM_STREAM_PLAYBACK as i32 } +} + +/// The context behind the component's descriptor (its first field). +#[repr(C)] +struct AsocContext { + component: bindings::snd_soc_component_driver, + data: Arc, + dais: KBox>, + _ops: KBox, +} + +const _: () = assert!(mem::offset_of!(AsocContext, component) == 0); + +/// # Safety +/// +/// `component` must be this driver's live registered component. +unsafe fn component_data<'a>(component: *mut bindings::snd_soc_component) -> &'a T8152AopAudio { + // SAFETY: by the caller's contract; C keeps the descriptor pointer we + // registered, which is the start of the `AsocContext`. + unsafe { &(*(*component).driver.cast::()).data } +} + +/// # Safety +/// +/// `dai` must be a live DAI of this driver's registered component. +unsafe fn dai_data<'a>(dai: *mut bindings::snd_soc_dai) -> &'a T8152AopAudio { + // SAFETY: by the caller's contract. + unsafe { component_data((*dai).component) } +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_open( + component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { component_data(component) }; + // SAFETY: as above. + let rtd = unsafe { substream_rtd(substream) }; + // SAFETY: as above. + if unsafe { rtd_is_be(rtd) } { + return 0; + } + // SAFETY: as above. + let Some(fe) = (unsafe { fe_index(rtd) }) else { + return EINVAL.to_errno(); + }; + // SAFETY: as above. + let playback = unsafe { is_playback(substream) }; + let Some(name) = FE_DMA_NAMES[fe][usize::from(!playback)] else { + return ENODEV.to_errno(); + }; + // SAFETY: the device is live and the name is NUL-terminated. + let chan = match from_err_ptr(unsafe { + bindings::dma_request_chan(data.dev.as_raw(), name.as_char_ptr()) + }) { + Ok(chan) => chan, + Err(e) => { + dev_err!(data.dev, "DMA channel {:?} unavailable: {:?}\n", name, e); + return e.to_errno(); + } + }; + let mut hw = bindings::snd_pcm_hardware { + info: bindings::SNDRV_PCM_INFO_MMAP + | bindings::SNDRV_PCM_INFO_MMAP_VALID + | bindings::SNDRV_PCM_INFO_INTERLEAVED, + buffer_bytes_max: PCM_BUFFER_MAX, + period_bytes_min: PCM_PERIOD_BYTES_MIN, + period_bytes_max: PCM_PERIOD_BYTES_MAX, + periods_min: 2, + periods_max: (PCM_BUFFER_MAX / PCM_PERIOD_BYTES_MIN) as u32, + fifo_size: 16, + ..Default::default() + }; + // SAFETY: the substream and the channel are live. + let ret = unsafe { + let mut ret = 0; + if (*substream).dma_buffer.dev.type_ == bindings::SNDRV_DMA_TYPE_UNKNOWN as i32 { + ret = bindings::snd_pcm_set_managed_buffer( + substream, + bindings::SNDRV_DMA_TYPE_DEV as i32, + (*(*chan).device).dev, + 0, + 0, + ); + } + if ret == 0 { + let mut dma_data = bindings::snd_dmaengine_dai_dma_data::default(); + ret = bindings::snd_dmaengine_pcm_refine_runtime_hwparams( + substream, + &mut dma_data, + &mut hw, + chan, + ); + } + if ret == 0 { + hw.formats &= FORMATS; + (*(*substream).runtime).hw = hw; + ret = bindings::snd_dmaengine_pcm_open(substream, chan); + } + ret + }; + if ret < 0 { + // SAFETY: the open failed, so the channel is still ours. + unsafe { bindings::dma_release_channel(chan) }; + } + ret +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_close( + _component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> i32 { + // SAFETY: by the caller's contract. + if unsafe { rtd_is_be(substream_rtd(substream)) } { + return 0; + } + // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. + unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) } +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_hw_params( + _component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, + params: *mut bindings::snd_pcm_hw_params, +) -> i32 { + // SAFETY: by the caller's contract. + if unsafe { rtd_is_be(substream_rtd(substream)) } { + return 0; + } + // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. + let chan = unsafe { bindings::snd_dmaengine_pcm_get_chan(substream) }; + let mut cfg = bindings::dma_slave_config::default(); + // SAFETY: the substream and the parameters are live for the op. + let rc = unsafe { bindings::snd_hwparams_to_dma_slave_config(substream, params, &mut cfg) }; + if rc < 0 { + return rc; + } + // SAFETY: ASoC calls hw_params with live parameters. + let channels = unsafe { + (*params).intervals[(bindings::SNDRV_PCM_HW_PARAM_CHANNELS + - bindings::SNDRV_PCM_HW_PARAM_FIRST_INTERVAL) as usize] + .min + }; + // One frame per burst, up to four words. + let window = core::cmp::min(channels, 4); + // SAFETY: the substream is live. + if unsafe { is_playback(substream) } { + cfg.dst_port_window_size = window; + } else { + cfg.src_port_window_size = window; + } + // SAFETY: `chan` is the live channel behind the substream. + unsafe { + match (*(*chan).device).device_config { + Some(f) => f(chan, &mut cfg), + None => ENOSYS.to_errno(), + } + } +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_trigger( + _component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, + cmd: i32, +) -> i32 { + // SAFETY: by the caller's contract. + if unsafe { rtd_is_be(substream_rtd(substream)) } { + return 0; + } + // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. + unsafe { bindings::snd_dmaengine_pcm_trigger(substream, cmd) } +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_pointer( + _component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> bindings::snd_pcm_uframes_t { + // SAFETY: by the caller's contract. + if unsafe { rtd_is_be(substream_rtd(substream)) } { + return (-i64::from(bindings::ENOTSUPP)) as bindings::snd_pcm_uframes_t; + } + // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. + unsafe { bindings::snd_dmaengine_pcm_pointer(substream) } +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component. +unsafe extern "C" fn dai_accept_fmt(_dai: *mut bindings::snd_soc_dai, _fmt: u32) -> i32 { + // The firmware runs the serializers; format, slots and clocks are its. + 0 +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component. +unsafe extern "C" fn dai_accept_sysclk( + _dai: *mut bindings::snd_soc_dai, + _id: i32, + _freq: u32, + _dir: i32, +) -> i32 { + 0 +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component. +unsafe extern "C" fn dai_accept_bclk_ratio(_dai: *mut bindings::snd_soc_dai, _ratio: u32) -> i32 { + 0 +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component. +unsafe extern "C" fn dai_accept_tdm_slot( + _dai: *mut bindings::snd_soc_dai, + _tx_mask: u32, + _rx_mask: u32, + _slots: i32, + _slot_width: i32, +) -> i32 { + 0 +} + +/// The back-end's service for a stream; `None` for the speaker's sense +/// capture, which runs with the speaker's playback. +/// +/// # Safety +/// +/// `dai` must be a live DAI of this component, `substream` live. +unsafe fn be_service<'a>( + dai: *mut bindings::snd_soc_dai, + substream: *mut bindings::snd_pcm_substream, +) -> Option<(&'a T8152AopAudio, &'a Service)> { + // SAFETY: by the caller's contract. + let (data, id, playback) = unsafe { (dai_data(dai), (*dai).id as u32, is_playback(substream)) }; + let svc = match (id, playback) { + (BE_DAI_ID_COUT, true) => &data.cout, + (BE_DAI_ID_COUT, false) => &data.cin, + (BE_DAI_ID_SPKR, true) => &data.spkr, + _ => return None, + }; + Some((data, svc)) +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component and a live substream. +unsafe extern "C" fn be_startup( + substream: *mut bindings::snd_pcm_substream, + dai: *mut bindings::snd_soc_dai, +) -> i32 { + // SAFETY: by the caller's contract. + let Some((data, svc)) = (unsafe { be_service(dai, substream) }) else { + return 0; + }; + match data.startup(svc) { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component and a live substream. +unsafe extern "C" fn be_prepare( + substream: *mut bindings::snd_pcm_substream, + dai: *mut bindings::snd_soc_dai, +) -> i32 { + // SAFETY: by the caller's contract. + let Some((data, svc)) = (unsafe { be_service(dai, substream) }) else { + return 0; + }; + match data.prepare(svc) { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +/// # Safety +/// +/// Called by ASoC with a live DAI of this component and a live substream. +unsafe extern "C" fn be_shutdown( + substream: *mut bindings::snd_pcm_substream, + dai: *mut bindings::snd_soc_dai, +) { + // SAFETY: by the caller's contract. + if let Some((data, svc)) = unsafe { be_service(dai, substream) } { + data.shutdown(svc); + } +} + +struct DaiOps { + be: bindings::snd_soc_dai_ops, + fe: bindings::snd_soc_dai_ops, +} + +impl DaiOps { + fn new() -> Self { + let fe = bindings::snd_soc_dai_ops { + set_fmt: Some(dai_accept_fmt), + set_sysclk: Some(dai_accept_sysclk), + set_bclk_ratio: Some(dai_accept_bclk_ratio), + set_tdm_slot: Some(dai_accept_tdm_slot), + ..Default::default() + }; + DaiOps { + be: bindings::snd_soc_dai_ops { + startup: Some(be_startup), + prepare: Some(be_prepare), + shutdown: Some(be_shutdown), + ..fe + }, + fe, + } + } +} + +fn pcm_stream(name: &'static CStr, channels: u32) -> bindings::snd_soc_pcm_stream { + bindings::snd_soc_pcm_stream { + stream_name: name.as_char_ptr(), + formats: FORMATS, + rates: bindings::SNDRV_PCM_RATE_48000, + rate_min: 48000, + rate_max: 48000, + channels_min: channels, + channels_max: channels, + ..Default::default() + } +} + +/// The DAI table, indexed by `sound-dai = <&aop_audio N>` in the DTS: +/// 0 cout (jack back-end), 1 and 2 the playback front-ends, 3 spkr (speaker +/// back-end), 4 the sense front-end. +const DAI_COUNT: usize = 2 + FE_COUNT; + +fn dai_drivers(ops: &DaiOps) -> [bindings::snd_soc_dai_driver; DAI_COUNT] { + [ + bindings::snd_soc_dai_driver { + name: c"cout".as_char_ptr(), + id: BE_DAI_ID_COUT, + ops: &ops.be, + playback: pcm_stream(c"COUT TX", 2), + capture: pcm_stream(c"CIN RX", 1), + ..Default::default() + }, + bindings::snd_soc_dai_driver { + name: c"j873-pcm-0".as_char_ptr(), + id: FE_DAI_ID_BASE, + ops: &ops.fe, + playback: pcm_stream(c"PCM0 TX", 2), + capture: pcm_stream(c"PCM0 RX", 1), + ..Default::default() + }, + // The speaker: one 32-bit slot per frame (the firmware's spkr + // serializer runs a single channel). + bindings::snd_soc_dai_driver { + name: c"j873-pcm-1".as_char_ptr(), + id: FE_DAI_ID_BASE + 1, + ops: &ops.fe, + playback: pcm_stream(c"PCM1 TX", 1), + ..Default::default() + }, + bindings::snd_soc_dai_driver { + name: c"spkr".as_char_ptr(), + id: BE_DAI_ID_SPKR, + ops: &ops.be, + playback: pcm_stream(c"SPKR TX", 1), + capture: pcm_stream(c"SPKR RX", 2), + ..Default::default() + }, + bindings::snd_soc_dai_driver { + name: c"j873-pcm-2".as_char_ptr(), + id: FE_DAI_ID_BASE + 2, + ops: &ops.fe, + capture: pcm_stream(c"PCM2 RX", 2), + ..Default::default() + }, + ] +} + +impl AsocContext { + fn new(data: Arc) -> Result> { + let ops = KBox::new(DaiOps::new(), GFP_KERNEL)?; + let dais = KBox::new(Opaque::new(dai_drivers(&ops)), GFP_KERNEL)?; + let component = bindings::snd_soc_component_driver { + name: c"t8152-aop-audio".as_char_ptr(), + open: Some(asoc_pcm_open), + close: Some(asoc_pcm_close), + hw_params: Some(asoc_pcm_hw_params), + trigger: Some(asoc_pcm_trigger), + pointer: Some(asoc_pcm_pointer), + ..Default::default() + }; + Ok(KBox::new( + Self { + component, + data, + dais, + _ops: ops, + }, + GFP_KERNEL, + )?) + } +} + +struct T8152AopAudioDriver { + dev: ARef, + asoc: KBox, + registered: AtomicFlag, +} + +// SAFETY: the ASoC context is only touched by ASoC callbacks and by probe and +// remove, which the driver core serializes. +unsafe impl Send for T8152AopAudioDriver {} +// SAFETY: as for `Send`. +unsafe impl Sync for T8152AopAudioDriver {} + +impl T8152AopAudioDriver { + /// Unregisters the component. Must run from unbind: the component is + /// device-managed and freed with the device's resources after unbind. + fn unregister(&self) { + if !self.registered.xchg(false, Relaxed) { + return; + } + // SAFETY: registered in probe; the context outlives the unregister. + unsafe { + bindings::snd_soc_unregister_component_by_driver( + self.dev.as_raw(), + &self.asoc.component, + ) + }; + } +} + +kernel::of_device_table!( + OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c_str!("apple,t8152-aop-audio")), ())] +); + +impl platform::Driver for T8152AopAudioDriver { + type IdInfo = (); + type Data<'bound> = Self; + + const OF_ID_TABLE: Option> = Some(&OF_TABLE); + + fn probe<'bound>( + pdev: &'bound platform::Device>, + _info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound { + let dev = ARef::::from(pdev.as_ref()); + // SAFETY: this is a service device the AOP core registered. + let adata = unsafe { ::from_child(pdev.as_ref()) }?; + // SAFETY: the AOP core sets the child's platform data to its EPIC service. + let service = unsafe { (*dev.as_raw()).platform_data as *const EPICService }; + if service.is_null() { + return Err(ENODEV); + } + // SAFETY: checked above; it lives as long as the child. + let service = unsafe { *service }; + + // Every serializer leaf is required: the firmware's streams run on + // them, so the driver must not bind without one (or before its + // provider has probed). + let mut mca = KVec::new(); + for name in MCA_NAMES { + match PowerDomain::attach(&dev, name) { + Ok(Some(pd)) => mca.push(pd, GFP_KERNEL)?, + Ok(None) => { + dev_err!(dev, "power domain {:?} is missing\n", name); + return Err(ENODEV); + } + Err(e) => { + if e != EPROBE_DEFER { + dev_err!(dev, "power domain {:?}: {:?}\n", name, e); + } + return Err(e); + } + } + } + + let data_dev = dev.clone(); + let data = Arc::pin_init( + pin_init!(T8152AopAudio { + dev: data_dev, + adata, + service, + cout: Service::new(from_fourcc(b"cout"), "cout", true), + cin: Service::new(from_fourcc(b"cin "), "cin", true), + spkr: Service::new(from_fourcc(b"spkr"), "spkr", false), + mca, + }), + GFP_KERNEL, + )?; + for svc in [&data.cout, &data.cin, &data.spkr] { + data.attach(svc)?; + } + + let asoc = AsocContext::new(data)?; + // SAFETY: the descriptor and the DAI table are heap allocations owned + // by `asoc`, which the driver data keeps until after unregister. + let ret = unsafe { + bindings::snd_soc_register_component_d( + dev.as_raw(), + &asoc.component, + asoc.dais.get().cast(), + DAI_COUNT as i32, + ) + }; + if ret < 0 { + dev_err!(dev, "unable to register the ASoC component: {}\n", ret); + return Err(Error::from_errno(ret)); + } + Ok(Self { + dev, + asoc, + registered: AtomicFlag::new(true), + }) + } + + fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { + this.unregister(); + } +} + +module_platform_driver! { + type: T8152AopAudioDriver, + name: "snd_soc_t8152_aop_audio", + description: "Apple T8152 AOP audio: headphone jack and speaker", + license: "Dual MIT/GPL", +} From 5aa269280d70ec7b21d523b3a0a77e6bad1c3f84 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:32 +0100 Subject: [PATCH 0008/1514] ASoC: apple: macaudio: add J873 The J873 (Mac mini M6) uses the T8152 AOP audio driver as its CPU component: the CS42L84 jack on "cout" (DSP_A | IB_NF, one-BCLK sync pulse) and one SN012776 on "spkr" (I2S, NB_IF: data sampled on the rising edge, as macOS programs the amp). Each AOP front-end owns the DMA channel of one serializer, so the speaker can only be fed from the secondary front-end; the new spk_secondary_only sets the speaker mux accordingly, and spk_dai_fmt gives the speaker link its own format. There is no qualified speaker protection for J873 yet (no verified sense path, thermal model or power budget), so the speaker fails closed: it is only enabled with please_blow_up_my_speakers. Opted in, it runs as macOS runs it: amp gain 15 (ADT speaker-config) and no volume lock (safe_vol 0), since there is no sense stream for a protection daemon. The jack is not affected. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/macaudio.c | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index ba04b1eec61412..4743ba5db026be 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -136,6 +136,13 @@ struct macaudio_platform_cfg { * keep the first slots in codec order; the others carry silence. */ unsigned int speaker_fe_channels; + /* The speaker links' DAI format, if not dai_fmt */ + unsigned int spk_dai_fmt; + /* + * The speakers can only be fed from the secondary front-end: each + * front-end owns the DMA channel of one serializer (AOP-fed models). + */ + bool spk_secondary_only; }; static const char *volume_control_names[] = { @@ -1215,6 +1222,8 @@ static int macaudio_parse_of(struct macaudio_snd_data *ma) link_props->is_speakers = speakers; link_props->is_headphones = !speakers; + if (speakers && ma->cfg->spk_dai_fmt) + link->dai_fmt = ma->cfg->spk_dai_fmt; link_props->codecs = devm_kcalloc(dev, ncodecs_per_cpu, sizeof(struct ma_codec_idle), GFP_KERNEL); @@ -2035,6 +2044,9 @@ static int macaudio_fixup_controls(struct snd_soc_card *card) return ret; } + if (ma->cfg->spk_secondary_only) + CHECK(snd_soc_set_enum_kctl, "Speaker Playback Mux", "Secondary", 1); + /* * This needs some care to avoid matches against cs42l84's * "Jack HPF Corner Frequency". @@ -2353,6 +2365,39 @@ struct macaudio_platform_cfg macaudio_j700_cfg = { .primary_bclk_ratio = 125, }; +/* + * J873 (T8152, Mac mini M6): as on J700, the AOP firmware owns the audio + * fabric and the CPU component is the T8152 AOP audio driver. The jack is a + * CS42L84 on the AOP's "cout" back-end, the speaker one SN012776 on "spkr"; + * both serializers run on the firmware's clocks. The speaker frame is 250 + * BCLKs of 12 MHz (the amp is told so by its ti,bclk-ratio), with the data + * sampled on the rising edge, as macOS programs the amp. + */ +struct macaudio_platform_cfg macaudio_j873_cfg = { + /* + * No qualified speaker protection exists for J873 yet (no verified + * sense path, thermal model or power budget), so the speaker stays off + * unless please_blow_up_my_speakers is set; the jack is unaffected. + */ + .enable_speakers = false, + .amp = AMP_SN012776, + .speakers = SPKR_1W, + .stereo = false, + /* + * With the speaker opted in, as macOS runs it: ADT speaker-config + * amp_gain 15, and no volume lock (safe_vol 0), since there is no + * sense stream for a protection daemon to unlock it from. + */ + .amp_gain = 15, + .safe_vol = 0, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + /* jack: a one-BCLK sync pulse, data launched on the rising edge */ + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + struct macaudio_platform_cfg macaudio_j314_cfg = { true, AMP_SN012776, SPKR_2W1T, true, 0, -20, }; @@ -2539,6 +2584,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j713-macaudio", .data = &macaudio_j713_cfg }, /* The J713 jack runs on the AOP like the J616s one. */ { .compatible = "apple,j713-macaudio-jack", .data = &macaudio_j616_jack_cfg }, + /* j873 AID48 sn012776 15 1x 1W (AOP-fed, no protection) */ + { .compatible = "apple,j873-macaudio", .data = &macaudio_j873_cfg }, /* Fallback, jack only */ { .compatible = "apple,macaudio"}, { } From 7c876b1bdf9f509757fb70733434647456f58ddc Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 1 Nov 2026 21:39:33 +0100 Subject: [PATCH 0009/1514] soc: apple: rtkit: Take a crash buffer the firmware maps itself The T8142 AOP keeps its crash buffer in its own slot of its DART stream and asks for it on endpoint 1 with that IOVA. A client without shmem_setup refused the request, so the firmware never got its crash buffer acknowledged. APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG takes such a buffer as the firmware's, without a CPU mapping, and acknowledges the request unchanged; a later crash is reported without a log. RtKit::new_with_firmware_crashlog() selects it at runtime, so a driver can use it for one SoC only. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/rtkit.c | 15 +++++++++++++++ include/linux/soc/apple/rtkit.h | 7 +++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/soc/apple/rtkit.rs | 16 ++++++++++++++++ 4 files changed, 39 insertions(+) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index d352083aaa26c5..9eaa28d16c46d3 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -410,6 +410,13 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, dev_dbg(rtk->dev, "RTKit: buffer request for 0x%zx bytes at %pad\n", request.size, &request.iova); + if ((rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG) && + ep == APPLE_RTKIT_EP_CRASHLOG && request.iova) { + *buffer = request; + buffer->is_mapped = true; + return apple_rtkit_send_message(rtk, ep, msg, NULL, false); + } + if (request.iova && !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep) { err = -EINVAL; goto error; @@ -734,6 +741,14 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) dev_err(rtk->dev, "RTKit: co-processor has crashed\n"); + /* A firmware-owned crash buffer has no CPU mapping to read the log from. */ + if (!rtk->crashlog_buffer.buffer && !rtk->crashlog_buffer.iomem) { + rtk->crashed = true; + if (rtk->ops->crashed) + rtk->ops->crashed(rtk->cookie, NULL, 0); + return; + } + /* * create a shadow copy here to make sure the co-processor isn't able * to change the log while we're dumping it. this also ensures diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 65bd28a6f0240e..4c27e012c2c75d 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -57,6 +57,13 @@ struct apple_rtkit_inherited_buffer { /* This client requires endpoint 7 setup before IOP power can be acknowledged. */ #define APPLE_RTKIT_NEEDS_COREANALYTICS BIT(1) +/* + * The co-processor keeps its crash buffer in memory it maps itself (the T8142 + * AOP) and asks for it with that IOVA: take the buffer as the firmware's, + * without a CPU mapping, and acknowledge the request unchanged. + */ +#define APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG BIT(2) + /* * Struct to represent implementation-specific RTKit operations. * diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 56f9f846898044..2731a39a0255c7 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -158,6 +158,7 @@ const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL const fop_flags_t RUST_CONST_HELPER_FOP_UNSIGNED_OFFSET = FOP_UNSIGNED_OFFSET; const u32 RUST_CONST_HELPER_APPLE_RTKIT_COPROC_PLACES_BUFFERS = APPLE_RTKIT_COPROC_PLACES_BUFFERS; const u32 RUST_CONST_HELPER_APPLE_RTKIT_NEEDS_COREANALYTICS = APPLE_RTKIT_NEEDS_COREANALYTICS; +const u32 RUST_CONST_HELPER_APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG = APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG; const u64 BINDINGS_SNDRV_PCM_FMTBIT_FLOAT_LE = SNDRV_PCM_FMTBIT_FLOAT_LE; const u64 BINDINGS_SNDRV_PCM_FMTBIT_S32_LE = SNDRV_PCM_FMTBIT_S32_LE; diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index 73896fea53e00f..ef9c9e7f27b0fd 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -245,6 +245,11 @@ impl RtKit { ..Self::VTABLE }; + const FIRMWARE_CRASHLOG_VTABLE: bindings::apple_rtkit_ops = bindings::apple_rtkit_ops { + flags: Self::VTABLE.flags | bindings::APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG, + ..Self::VTABLE + }; + /// Creates a new RTKit client for a given device and optional mailbox name or index. pub fn new( dev: &device::Device, @@ -268,6 +273,17 @@ impl RtKit { Self::new_with_ops(dev, mbox_name, mbox_idx, data, &Self::COREANALYTICS_VTABLE) } + /// Creates a client whose co-processor keeps its crash buffer in memory it + /// maps itself and asks for it with that IOVA (the T8142 AOP). + pub fn new_with_firmware_crashlog( + dev: &device::Device, + mbox_name: Option<&'static CStr>, + mbox_idx: usize, + data: T::Data, + ) -> Result { + Self::new_with_ops(dev, mbox_name, mbox_idx, data, &Self::FIRMWARE_CRASHLOG_VTABLE) + } + fn new_with_ops( dev: &device::Device, mbox_name: Option<&'static CStr>, From faa5ea2e77b24ce198cfad1e79975671b2d54bc6 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 31 Oct 2026 22:14:50 +0100 Subject: [PATCH 0010/1514] soc: apple: aop: Boot the T8142 (M5) AOP through its setup port The T8142 AOP (MacBook Air J813) waits for the host on a setup port, as the T8140 one does: the ADT's aop-exclave-mailbox at 0x3d067c000 (AOP ASC + 0x4007c000, not behind the arm-io translation). Its EPMAP announces other service endpoints than T8140's fixed set (0x4, 0x20, 0x23 and 0x32 on J813), so take the endpoints that must get buffers from the EPMAP when the match data says so. The firmware places its own crash log buffer in its firmware-mapped DART slot; accept it as the firmware's, as for G17P. After the setup boot all AFK endpoints start, and with the audio fabric left to the firmware (see the J813 device tree) the firmware announces its "audio" EPIC service. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/aop.rs | 87 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 79 insertions(+), 8 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 73df7cf27deaab..eb99bc46521753 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -169,6 +169,8 @@ const SETUP_BUFFER_ENTRY_SIZE: usize = 16; /// The service endpoints that request buffers; boot completes once all of /// them have theirs. const SETUP_ENDPOINTS: [u8; 5] = [0x20, 0x21, 0x23, 0x30, 0x32]; +/// Service endpoints a setup port may announce in its EPMAP. +const SETUP_MAX_ENDPOINTS: usize = 16; const SETUP_BOOT_TIMEOUT_MS: u32 = 15000; // A request to a service endpoint: the payload goes into the endpoint's // message page, (3 << 60) | length announces it, the firmware answers with a @@ -1021,7 +1023,12 @@ struct SetupState { arena: Option>, /// The next unassigned page of the arena. next_page: usize, - endpoints: [Option; SETUP_ENDPOINTS.len()], + endpoints: [Option; SETUP_MAX_ENDPOINTS], + /// The service endpoints that must get buffers: T8140's fixed set, or + /// those the EPMAP announces. + expected: [u8; SETUP_MAX_ENDPOINTS], + expected_count: usize, + epmap_endpoints: bool, map_done: bool, ap_ready: bool, power_sent: bool, @@ -1030,12 +1037,21 @@ struct SetupState { } impl SetupState { - fn new() -> SetupState { + fn new(epmap_endpoints: bool) -> SetupState { + let mut expected = [0; SETUP_MAX_ENDPOINTS]; + let mut expected_count = 0; + if !epmap_endpoints { + expected[..SETUP_ENDPOINTS.len()].copy_from_slice(&SETUP_ENDPOINTS); + expected_count = SETUP_ENDPOINTS.len(); + } SetupState { mbox: None, arena: None, next_page: 0, - endpoints: [None; SETUP_ENDPOINTS.len()], + endpoints: [None; SETUP_MAX_ENDPOINTS], + expected, + expected_count, + epmap_endpoints, map_done: false, ap_ready: false, power_sent: false, @@ -1077,7 +1093,8 @@ impl SetupState { /// Boot is complete once the AP power state is on and every service /// endpoint has its buffers. fn ready(&self) -> bool { - self.ap_ready && self.endpoint_count() == SETUP_ENDPOINTS.len() + self.ap_ready && self.expected_count != 0 + && self.endpoint_count() == self.expected_count } /// Sends one word to a setup-port endpoint. Callers run in process @@ -1375,7 +1392,7 @@ impl AopData { required_endpoints: cfg.required_endpoints, setup_queue, setup_lost: Atomic::new(false), - setup <- new_mutex!(SetupState::new()), + setup <- new_mutex!(SetupState::new(cfg.setup_epmap_endpoints)), setup_cv <- new_condvar!(), rtkit <- new_mutex!(None), endpoints <- pin_init::pin_init_array_from_fn(|i| { @@ -2188,6 +2205,24 @@ impl AopData { // Each fragment of the endpoint map is acknowledged by // echoing it. st.send(SETUP_MGMT_EP, word)?; + if st.epmap_endpoints { + // RTKit layout: a 32-endpoint bitmap, its base in + // bits 32..34. Endpoint 0 is this management one. + let base = ((word >> 32) & 7) as u8 * 32; + dev_dbg!(self.dev, "setup port: EPMAP {:#x}\n", word); + for bit in 0..32u8 { + let ep = base + bit; + if word & (1 << bit) != 0 && ep != SETUP_MGMT_EP + && !st.expected[..st.expected_count].contains(&ep) + { + if st.expected_count == SETUP_MAX_ENDPOINTS { + return Err(ENOSPC); + } + st.expected[st.expected_count] = ep; + st.expected_count += 1; + } + } + } if word & SETUP_EPMAP_LAST != 0 { st.map_done = true; } @@ -2244,7 +2279,7 @@ impl AopData { /// from the arena. fn setup_endpoint_request(&self, st: &mut SetupState, ep: u8, word: u64) -> Result<()> { let requested = (word & 0xffff_ffff) as usize; - let slot = SETUP_ENDPOINTS + let slot = st.expected[..st.expected_count] .iter() .position(|e| *e == ep) .ok_or(EINVAL)?; @@ -2485,7 +2520,7 @@ impl AopData { "setup port: boot incomplete (AP power on: {}, endpoints: {}/{}): {:?}", st.ap_ready, st.endpoint_count(), - SETUP_ENDPOINTS.len(), + st.expected_count, e ); return Err(e); @@ -2553,6 +2588,8 @@ struct AopHwConfig { epic_v4: bool, /// The firmware boots through a second, "setup", mailbox as well. setup_port: bool, + /// Its service endpoints are the ones its EPMAP announces, not T8140's. + setup_epmap_endpoints: bool, /// Shut the co-processor down on unbind and retain its buffers if the /// shutdown cannot be confirmed. quiesce_on_unbind: bool, @@ -2575,6 +2612,7 @@ const HW_CFG_T8103: AopHwConfig = AopHwConfig { patch_bootargs: true, epic_v4: false, setup_port: false, + setup_epmap_endpoints: false, quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, @@ -2589,6 +2627,7 @@ const HW_CFG_T8112: AopHwConfig = AopHwConfig { patch_bootargs: true, epic_v4: false, setup_port: false, + setup_epmap_endpoints: false, quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, @@ -2603,6 +2642,7 @@ const HW_CFG_T6000: AopHwConfig = AopHwConfig { patch_bootargs: true, epic_v4: false, setup_port: false, + setup_epmap_endpoints: false, quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, @@ -2617,6 +2657,7 @@ const HW_CFG_T6020: AopHwConfig = AopHwConfig { patch_bootargs: true, epic_v4: false, setup_port: false, + setup_epmap_endpoints: false, quiesce_on_unbind: false, required_endpoints: &[], fw_regions: false, @@ -2636,6 +2677,7 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { patch_bootargs: true, epic_v4: false, setup_port: false, + setup_epmap_endpoints: false, quiesce_on_unbind: true, required_endpoints: &[], fw_regions: true, @@ -2659,6 +2701,7 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { patch_bootargs: false, epic_v4: true, setup_port: true, + setup_epmap_endpoints: false, quiesce_on_unbind: true, required_endpoints: &[0x20, 0x21, 0x22, 0x23, 0x2b], fw_regions: false, @@ -2674,6 +2717,26 @@ const HW_CFG_T8152: AopHwConfig = AopHwConfig { patch_bootargs: false, epic_v4: true, setup_port: false, + setup_epmap_endpoints: false, + quiesce_on_unbind: true, + required_endpoints: &[], + fw_regions: false, + halt_on_failed_start: false, +}; + +/// T8142 (M5): booted through a setup port as on T8140, at the ADT's +/// aop-exclave-mailbox (0x3d067c000, AOP ASC + 0x4007c000, untranslated), +/// whose EPMAP names the service endpoints (0x4, 0x20, 0x23 and 0x32 on the +/// MacBook Air J813, not T8140's set). EPIC and AFK as on T8152; the +/// firmware runs with the boot arguments iBoot left. +const HW_CFG_T8142: AopHwConfig = AopHwConfig { + ec0p: 0, + aopt: 0, + alig: 0, + patch_bootargs: false, + epic_v4: true, + setup_port: true, + setup_epmap_endpoints: true, quiesce_on_unbind: true, required_endpoints: &[], fw_regions: false, @@ -2691,6 +2754,7 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6040), (of::DeviceId::new(c_str!("apple,t8132-aop")), &HW_CFG_T8132), + (of::DeviceId::new(c_str!("apple,t8142-aop")), &HW_CFG_T8142), (of::DeviceId::new(c_str!("apple,t8152-aop")), &HW_CFG_T8152), ] ); @@ -2741,7 +2805,14 @@ impl platform::Driver for AopDriver { cfg.bootargs_word_access, )?; } - let rtkit = rtkit::RtKit::::new(pdev.as_ref(), None, 0, data.clone())?; + // The T8142 AOP places its own crashlog buffer in its firmware-mapped + // DART slot and asks for it on endpoint 1 with that IOVA; take it as + // the firmware's instead of refusing the request. + let rtkit = if cfg.setup_epmap_endpoints { + rtkit::RtKit::::new_with_firmware_crashlog(pdev.as_ref(), None, 0, data.clone())? + } else { + rtkit::RtKit::::new(pdev.as_ref(), None, 0, data.clone())? + }; data.rtkit.lock().as_mut().set(Some(rtkit)); if cfg.setup_port { AopData::setup_open(&data, pdev.as_ref())?; From b91f6a984cf0fae18d69f546c6d0f2f8438e92a4 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 31 Oct 2026 22:15:04 +0100 Subject: [PATCH 0011/1514] dmaengine: apple-admac: Restart a paused capture at a frame boundary Behind an AOP the serializer feeding a capture channel is the firmware's, and it stops in the middle of a frame whenever it likes. A capture that stays open across such stops (the speaker V/I sense, which a protection daemon reads for as long as it runs) then carries the partial frame forward: every later frame is off by its words, and the samples of one amplifier are read as another's. On the MacBook Air J813 one restart in three slipped by one 16-bit word. Let a client pass the frame size in bytes as a u32 in dma_slave_config.peripheral_config. A paused cyclic capture on such a channel resumes at the next frame boundary of its current period: the reports completed before the pause are accounted for, the rings are reset and the rest of the period is submitted from the aligned address, then whole periods as before. Without a frame size nothing changes. Signed-off-by: Thomas Glanzmann --- drivers/dma/apple-admac.c | 93 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 86 insertions(+), 7 deletions(-) diff --git a/drivers/dma/apple-admac.c b/drivers/dma/apple-admac.c index 90d51641a6a352..741d1e27f893d0 100644 --- a/drivers/dma/apple-admac.c +++ b/drivers/dma/apple-admac.c @@ -128,6 +128,8 @@ struct admac_chan { spinlock_t lock; struct admac_tx *current_tx; int nperiod_acks; + /* frame size a paused capture restarts aligned to on resume, or 0 */ + u32 realign_bytes; /* * We maintain a 'submitted' and 'issued' list mainly for interface @@ -337,6 +339,21 @@ static struct dma_async_tx_descriptor *admac_prep_dma_cyclic( return &adtx->tx; } +/* + * Write one hardware descriptor. + */ +static void admac_write_hw_desc(struct admac_data *ad, int channo, + dma_addr_t addr, size_t len) +{ + dev_dbg(ad->dev, "ch%d descriptor: addr=0x%pad len=0x%zx flags=0x%lx\n", + channo, &addr, len, FLAG_DESC_NOTIFY); + + writel_relaxed(lower_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); + writel_relaxed(upper_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); + writel_relaxed(len, ad->base + REG_DESC_WRITE(channo)); + writel_relaxed(FLAG_DESC_NOTIFY, ad->base + REG_DESC_WRITE(channo)); +} + /* * Write one hardware descriptor for a dmaengine cyclic transaction. */ @@ -353,13 +370,7 @@ static bool admac_cyclic_write_one_desc(struct admac_data *ad, int channo, /* If happens means we have buggy code */ WARN_ON_ONCE(addr + tx->period_len > tx->buf_end); - dev_dbg(ad->dev, "ch%d descriptor: addr=0x%pad len=0x%zx flags=0x%lx\n", - channo, &addr, tx->period_len, FLAG_DESC_NOTIFY); - - writel_relaxed(lower_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); - writel_relaxed(upper_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); - writel_relaxed(tx->period_len, ad->base + REG_DESC_WRITE(channo)); - writel_relaxed(FLAG_DESC_NOTIFY, ad->base + REG_DESC_WRITE(channo)); + admac_write_hw_desc(ad, channo, addr, tx->period_len); /* Include a descriptor already consumed while the ring is refilled. */ tx->nperiods_outstanding++; @@ -609,6 +620,62 @@ static int admac_pause(struct dma_chan *chan) return 0; } +static int admac_drain_reports(struct admac_data *ad, int channo); + +/* + * Restart a paused cyclic capture at the next frame boundary of the current + * period. A source that stopped in the middle of a frame (a serializer that + * firmware stops whenever it likes) leaves a partial frame in the buffer, and + * without this every later frame would be off by its words. Called with the + * channel stopped and the lock held. + */ +static void admac_cyclic_realign(struct admac_chan *adchan) +{ + struct admac_data *ad = adchan->host; + struct admac_tx *tx = adchan->current_tx; + int ch = adchan->no; + size_t done, aligned; + int nreports; + + /* Periods completed before the pause */ + nreports = admac_drain_reports(ad, ch); + tx->nperiods_outstanding -= min_t(unsigned int, nreports, tx->nperiods_outstanding); + adchan->nperiod_acks += nreports; + tx->reclaimed_pos += nreports * tx->period_len; + tx->reclaimed_pos %= 2 * tx->buf_len; + + done = tx->period_len - + min_t(size_t, readl_relaxed(ad->base + REG_RESIDUE(ad, ch)), tx->period_len); + aligned = roundup(done, adchan->realign_bytes); + if (aligned >= tx->period_len) { + adchan->nperiod_acks++; + tx->reclaimed_pos += tx->period_len; + tx->reclaimed_pos %= 2 * tx->buf_len; + aligned = 0; + } + if (adchan->nperiod_acks) + tasklet_schedule(&adchan->tasklet); + + dev_dbg(ad->dev, "ch%d realign: %zu bytes into the period, restart at %zu\n", + ch, done, aligned); + + admac_reset_rings(adchan); + writel_relaxed(0, ad->base + REG_CHAN_CTL(ad, ch)); + /* The reset dropped every descriptor still in the ring. */ + tx->nperiods_outstanding = 0; + + /* The rest of the current period, then whole periods as before */ + tx->submitted_pos = tx->reclaimed_pos; + admac_write_hw_desc(ad, ch, tx->buf_addr + (tx->submitted_pos % tx->buf_len) + aligned, + tx->period_len - aligned); + tx->nperiods_outstanding++; + tx->submitted_pos += tx->period_len; + tx->submitted_pos %= 2 * tx->buf_len; + + admac_start_chan(adchan); + admac_cyclic_write_desc(ad, ch, tx); +} + static int admac_resume(struct dma_chan *chan) { struct admac_chan *adchan = to_admac_chan(chan); @@ -618,6 +685,9 @@ static int admac_resume(struct dma_chan *chan) spin_lock_irqsave(&adchan->lock, flags); if (adchan->current_tx && adchan->current_tx->error) ret = -EIO; + else if (adchan->realign_bytes && adchan->current_tx && + admac_chan_direction(adchan->no) == DMA_DEV_TO_MEM) + admac_cyclic_realign(adchan); else admac_start_chan(adchan); spin_unlock_irqrestore(&adchan->lock, flags); @@ -971,6 +1041,15 @@ static int admac_device_config(struct dma_chan *chan, writel_relaxed(bus_width, ad->base + REG_BUS_WIDTH(ad, adchan->no)); + /* + * Optional: a u32 frame size in bytes, which a paused capture is + * restarted aligned to on resume (see admac_cyclic_realign()). + */ + if (config->peripheral_config && config->peripheral_size == sizeof(u32)) + adchan->realign_bytes = *(u32 *)config->peripheral_config; + else + adchan->realign_bytes = 0; + /* * By FIFOCTL_LIMIT we seem to set the maximal number of bytes allowed to be * held in controller's per-channel FIFO. Transfers seem to be triggered From 06f1b4a8027408b3b76ea2a27fa04be64ecca7d3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 31 Oct 2026 22:15:04 +0100 Subject: [PATCH 0012/1514] ASoC: apple: t8152-aop-audio: Add T8142 (MacBook Air J813) The J813 speaker stream (ADT iop-audio-controller/audio-speaker) differs from J873's: four SN012776 in 32-bit playback slots 0-3, and their voltage and current sense back on the same stream's RX side (base-ns RX0) as eight 16-bit slots. Make the speaker and sense shapes per-SoC match data: J873 keeps one playback channel; T8142 gets four, and an 8-channel S16_LE "Speaker Sense" front-end. The sense capture is the speaker serializer's RX, which the firmware stops anywhere in a frame. Before every `pwrd` of the speaker, restart a running sense capture at a frame boundary (apple-admac realignment, the partial frame reads as zeros), so that a protection daemon that keeps it open attributes each amplifier's voltage and current to the right one. The sense back-end also attaches the speaker service and requests `pw0 ` at startup: its front-end requests the ADMAC channel next, and the ADMAC only answers while the firmware holds the audio fabric up. Opening the sense before any other stream since the AOP started (speakersafetyd at boot) otherwise faults the bus. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/t8152_aop_audio.rs | 160 ++++++++++++++++++++++++++--- 1 file changed, 144 insertions(+), 16 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 31f562e7fc64d1..4c61092d0cea1e 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Apple T8152 (J873, Mac mini M6) AOP audio +//! Apple T8152 (J873, Mac mini M6) and T8142 (J813, MacBook Air M5) AOP audio //! //! The AOP firmware owns the audio fabric, as on T8140. The ADT //! (/arm-io/iop-audio-controller) names its services; all of them run on the @@ -220,6 +220,9 @@ struct T8152AopAudio { cin: Service, spkr: Service, mca: KVec, + cfg: &'static HwConfig, + /// The open sense capture front-end, if any. + sense: Atomic<*mut bindings::snd_pcm_substream>, } impl T8152AopAudio { @@ -353,16 +356,68 @@ impl T8152AopAudio { Ok(()) } + /// The sense capture's back-end. Its front-end requests the ADMAC + /// channel next, and the ADMAC only answers while the firmware holds + /// the audio fabric up, which it does while a service is in `pw0 ` or + /// `pwrd`. Opening the sense before any other stream since boot (as + /// speakersafetyd does) otherwise faults the bus (SError). Shutdown + /// leaves the service in `pw0 `, as the other streams do. + fn sense_startup(&self) -> Result<()> { + self.attach(&self.spkr)?; + if !self.spkr.running.load(Relaxed) { + self.set_power(&self.spkr, POWER_STATE_PW0)?; + } + Ok(()) + } + /// `pwrd`: the firmware starts the serializer clocks and the stream. fn run(&self, svc: &Service) -> Result<()> { if svc.running.load(Relaxed) { return Ok(()); } + if ptr::eq(svc, &self.spkr) && self.cfg.realign_sense { + self.realign_sense(); + } self.set_power(svc, POWER_STATE_PWRD)?; svc.running.store(true, Relaxed); Ok(()) } + /// Before the speaker's serializer starts, restart a running sense + /// capture at a frame boundary. The sense words are the serializer's RX, + /// which the firmware stops anywhere in a frame; a capture that stays + /// open across speaker streams (speakersafetyd keeps it) would carry + /// the partial frame forward and attribute one amplifier's voltage and + /// current to another. Nothing flows while the serializer is stopped, + /// so this loses no data; the partial frame reads as zeros. + fn realign_sense(&self) { + let ss = self.sense.load(Relaxed); + if ss.is_null() { + return; + } + // SAFETY: the sense front-end's open and close and this back-end's + // prepare all run under the card's DPCM mutex, so `ss` is live; its + // stream lock orders this against the front-end's trigger. + unsafe { + bindings::snd_pcm_stream_lock_irq(ss); + let rt = (*ss).runtime; + if !rt.is_null() && (*rt).state == SNDRV_PCM_STATE_RUNNING { + let chan = bindings::snd_dmaengine_pcm_get_chan(ss); + let ops = &*(*chan).device; + if let (Some(pause), Some(resume)) = (ops.device_pause, ops.device_resume) { + pause(chan); + let frame = ((*rt).frame_bits / 8) as usize; + let pos = bindings::snd_dmaengine_pcm_pointer(ss) as usize; + if frame != 0 && pos < (*rt).buffer_size as usize && !(*rt).dma_area.is_null() { + ptr::write_bytes((*rt).dma_area.add(pos * frame), 0, frame); + } + resume(chan); + } + } + bindings::snd_pcm_stream_unlock_irq(ss); + } + } + /// The clocks run from prepare on: the codecs see a bit clock as soon /// as ASoC powers and unmutes them. A PCM underrun stops the DMA /// without closing the back-end; a service that restarts on prepare @@ -407,6 +462,42 @@ const PCM_PERIOD_BYTES_MAX: usize = 0x10000; /// The AOP-run serializers take 24-bit samples in 32-bit words. const FORMATS: u64 = bindings::BINDINGS_SNDRV_PCM_FMTBIT_S24_LE; +/// SNDRV_PCM_FMTBIT_S16_LE (1 << SNDRV_PCM_FORMAT_S16_LE), which the +/// bindings do not export. +const FMTBIT_S16_LE: u64 = 1 << 2; +/// SNDRV_PCM_STATE_RUNNING, likewise. +const SNDRV_PCM_STATE_RUNNING: bindings::snd_pcm_state_t = 3; + +/// What differs between the machines: the shape of the firmware's `spkr` +/// stream (ADT iop-audio-controller/audio-speaker). +struct HwConfig { + /// Speaker slots (one per amplifier). + spkr_channels: u32, + /// Words the amplifiers send back on the stream's RX side (V/I sense). + sense_channels: u32, + sense_formats: u64, + /// The sense capture is the speaker stream's RX: restart it at a frame + /// boundary whenever the speaker starts (see `realign_sense`). + realign_sense: bool, +} + +/// J873: one amplifier in one 32-bit slot, nothing sent back. +static HW_CFG_T8152: HwConfig = HwConfig { + spkr_channels: 1, + sense_channels: 2, + sense_formats: FORMATS, + realign_sense: false, +}; + +/// J813: four amplifiers (left woofer, left tweeter, right woofer, right +/// tweeter) in 32-bit slots 0-3, their voltage and current sense back as +/// eight 16-bit slots (V, I per amplifier) on the stream's RX (base-ns RX0). +static HW_CFG_T8142: HwConfig = HwConfig { + spkr_channels: 4, + sense_channels: 8, + sense_formats: FMTBIT_S16_LE, + realign_sense: true, +}; /// # Safety /// @@ -543,7 +634,7 @@ unsafe extern "C" fn asoc_pcm_open( ); } if ret == 0 { - hw.formats &= FORMATS; + hw.formats &= if fe == 2 { data.cfg.sense_formats } else { FORMATS }; (*(*substream).runtime).hw = hw; ret = bindings::snd_dmaengine_pcm_open(substream, chan); } @@ -552,6 +643,8 @@ unsafe extern "C" fn asoc_pcm_open( if ret < 0 { // SAFETY: the open failed, so the channel is still ours. unsafe { bindings::dma_release_channel(chan) }; + } else if fe == 2 && !playback { + data.sense.store(substream, Relaxed); } ret } @@ -560,13 +653,18 @@ unsafe extern "C" fn asoc_pcm_open( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_close( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, ) -> i32 { // SAFETY: by the caller's contract. if unsafe { rtd_is_be(substream_rtd(substream)) } { return 0; } + // SAFETY: as above. + let data = unsafe { component_data(component) }; + if data.sense.load(Relaxed) == substream { + data.sense.store(ptr::null_mut(), Relaxed); + } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) } } @@ -575,7 +673,7 @@ unsafe extern "C" fn asoc_pcm_close( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_hw_params( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, params: *mut bindings::snd_pcm_hw_params, ) -> i32 { @@ -605,6 +703,15 @@ unsafe extern "C" fn asoc_pcm_hw_params( } else { cfg.src_port_window_size = window; } + // The sense capture: the frame size its channel restarts aligned to + // (apple-admac reads a u32 here; see `realign_sense`). + // SAFETY: by the caller's contract. + let data = unsafe { component_data(component) }; + let mut frame_bytes = channels * cfg.src_addr_width as u32; + if ptr::eq(substream, data.sense.load(Relaxed)) && data.cfg.realign_sense { + cfg.peripheral_config = ptr::from_mut(&mut frame_bytes).cast(); + cfg.peripheral_size = mem::size_of::(); + } // SAFETY: `chan` is the live channel behind the substream. unsafe { match (*(*chan).device).device_config { @@ -715,6 +822,14 @@ unsafe extern "C" fn be_startup( ) -> i32 { // SAFETY: by the caller's contract. let Some((data, svc)) = (unsafe { be_service(dai, substream) }) else { + // SAFETY: as above. + let (data, id) = unsafe { (dai_data(dai), (*dai).id as u32) }; + if id == BE_DAI_ID_SPKR { + return match data.sense_startup() { + Ok(()) => 0, + Err(e) => e.to_errno(), + }; + } return 0; }; match data.startup(svc) { @@ -780,9 +895,17 @@ impl DaiOps { } fn pcm_stream(name: &'static CStr, channels: u32) -> bindings::snd_soc_pcm_stream { + pcm_stream_fmt(name, channels, FORMATS) +} + +fn pcm_stream_fmt( + name: &'static CStr, + channels: u32, + formats: u64, +) -> bindings::snd_soc_pcm_stream { bindings::snd_soc_pcm_stream { stream_name: name.as_char_ptr(), - formats: FORMATS, + formats, rates: bindings::SNDRV_PCM_RATE_48000, rate_min: 48000, rate_max: 48000, @@ -797,7 +920,7 @@ fn pcm_stream(name: &'static CStr, channels: u32) -> bindings::snd_soc_pcm_strea /// back-end), 4 the sense front-end. const DAI_COUNT: usize = 2 + FE_COUNT; -fn dai_drivers(ops: &DaiOps) -> [bindings::snd_soc_dai_driver; DAI_COUNT] { +fn dai_drivers(ops: &DaiOps, cfg: &HwConfig) -> [bindings::snd_soc_dai_driver; DAI_COUNT] { [ bindings::snd_soc_dai_driver { name: c"cout".as_char_ptr(), @@ -815,28 +938,27 @@ fn dai_drivers(ops: &DaiOps) -> [bindings::snd_soc_dai_driver; DAI_COUNT] { capture: pcm_stream(c"PCM0 RX", 1), ..Default::default() }, - // The speaker: one 32-bit slot per frame (the firmware's spkr - // serializer runs a single channel). + // The speaker: one 32-bit slot per amplifier. bindings::snd_soc_dai_driver { name: c"j873-pcm-1".as_char_ptr(), id: FE_DAI_ID_BASE + 1, ops: &ops.fe, - playback: pcm_stream(c"PCM1 TX", 1), + playback: pcm_stream(c"PCM1 TX", cfg.spkr_channels), ..Default::default() }, bindings::snd_soc_dai_driver { name: c"spkr".as_char_ptr(), id: BE_DAI_ID_SPKR, ops: &ops.be, - playback: pcm_stream(c"SPKR TX", 1), - capture: pcm_stream(c"SPKR RX", 2), + playback: pcm_stream(c"SPKR TX", cfg.spkr_channels), + capture: pcm_stream_fmt(c"SPKR RX", cfg.sense_channels, cfg.sense_formats), ..Default::default() }, bindings::snd_soc_dai_driver { name: c"j873-pcm-2".as_char_ptr(), id: FE_DAI_ID_BASE + 2, ops: &ops.fe, - capture: pcm_stream(c"PCM2 RX", 2), + capture: pcm_stream_fmt(c"PCM2 RX", cfg.sense_channels, cfg.sense_formats), ..Default::default() }, ] @@ -845,7 +967,7 @@ fn dai_drivers(ops: &DaiOps) -> [bindings::snd_soc_dai_driver; DAI_COUNT] { impl AsocContext { fn new(data: Arc) -> Result> { let ops = KBox::new(DaiOps::new(), GFP_KERNEL)?; - let dais = KBox::new(Opaque::new(dai_drivers(&ops)), GFP_KERNEL)?; + let dais = KBox::new(Opaque::new(dai_drivers(&ops, data.cfg)), GFP_KERNEL)?; let component = bindings::snd_soc_component_driver { name: c"t8152-aop-audio".as_char_ptr(), open: Some(asoc_pcm_open), @@ -899,20 +1021,24 @@ impl T8152AopAudioDriver { kernel::of_device_table!( OF_TABLE, ::IdInfo, - [(of::DeviceId::new(c_str!("apple,t8152-aop-audio")), ())] + [ + (of::DeviceId::new(c_str!("apple,t8142-aop-audio")), &HW_CFG_T8142), + (of::DeviceId::new(c_str!("apple,t8152-aop-audio")), &HW_CFG_T8152), + ] ); impl platform::Driver for T8152AopAudioDriver { - type IdInfo = (); + type IdInfo = &'static HwConfig; type Data<'bound> = Self; const OF_ID_TABLE: Option> = Some(&OF_TABLE); fn probe<'bound>( pdev: &'bound platform::Device>, - _info: Option<&'bound Self::IdInfo>, + info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let dev = ARef::::from(pdev.as_ref()); + let cfg: &'static HwConfig = info.copied().unwrap_or(&HW_CFG_T8152); // SAFETY: this is a service device the AOP core registered. let adata = unsafe { ::from_child(pdev.as_ref()) }?; // SAFETY: the AOP core sets the child's platform data to its EPIC service. @@ -953,6 +1079,8 @@ impl platform::Driver for T8152AopAudioDriver { cin: Service::new(from_fourcc(b"cin "), "cin", true), spkr: Service::new(from_fourcc(b"spkr"), "spkr", false), mca, + cfg, + sense: Atomic::new(ptr::null_mut()), }), GFP_KERNEL, )?; From 9bee3709a110999cc0bbf33ed340bef21f814301 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 31 Oct 2026 22:15:04 +0100 Subject: [PATCH 0013/1514] ASoC: apple: macaudio: Add J813 MacBook Air 13" M5 (T8142): as on J873 the AOP firmware owns the audio fabric and the CPU component is the T8152-style AOP audio driver. The jack is a CS42L84 on "cout", the speakers four SN012776 (one woofer and one tweeter per side) on "spkr", with their V/I sense on the same stream. As on the other SN012776 laptops the speaker volume stays locked until a protection daemon (speakersafetyd) holds it. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/macaudio.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index 4743ba5db026be..58ecbf21e31528 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -2398,6 +2398,29 @@ struct macaudio_platform_cfg macaudio_j873_cfg = { .spk_secondary_only = true, }; +/* + * J813 (T8142, MacBook Air M5 13"): as on J873, the AOP firmware owns the + * audio fabric and the CPU component is the T8152-style AOP audio driver. + * The jack is a CS42L84 on "cout"; the speakers are four SN012776 (one + * woofer and one tweeter per side) on "spkr", whose voltage and current + * sense return on the same stream. As on the other SN012776 laptops, the + * speaker volume stays locked until a protection daemon (speakersafetyd) + * holds it. + */ +struct macaudio_platform_cfg macaudio_j813_cfg = { + .enable_speakers = true, + .amp = AMP_SN012776, + .speakers = SPKR_1W1T, + .stereo = true, + .amp_gain = 15, + .safe_vol = -20, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + struct macaudio_platform_cfg macaudio_j314_cfg = { true, AMP_SN012776, SPKR_2W1T, true, 0, -20, }; @@ -2586,6 +2609,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j713-macaudio-jack", .data = &macaudio_j616_jack_cfg }, /* j873 AID48 sn012776 15 1x 1W (AOP-fed, no protection) */ { .compatible = "apple,j873-macaudio", .data = &macaudio_j873_cfg }, + /* j813 AID? sn012776 15 2x 1W+1T (AOP-fed, V/I sense) */ + { .compatible = "apple,j813-macaudio", .data = &macaudio_j813_cfg }, /* Fallback, jack only */ { .compatible = "apple,macaudio"}, { } From c69b295447bb26fd843235c65f7f348d67ea2338 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 31 Oct 2026 23:44:39 +0100 Subject: [PATCH 0014/1514] ASoC: apple: t8152-aop-audio: Add the J813 microphone array The MacBook Air J813's three microphones are the AOP's "hpai" service (ADT iop-audio-controller/audio-hp-mic): the firmware runs the PDM part and delivers 48 kHz float32 frames of three channels (the ADT's audio-hp-mic-proxy description: 12 bytes per frame) on leap-s ADMAC RX0. There is no codec, so it gets a card of its own with one capture PCM, named like the other AOP microphone cards (AppleJ813HPAI, "MacBook Air J813 High-Power Audio Interface", driver aop_audio) so that the existing UCM and DSP configurations for those apply. As on T8140: open attaches the service and requests pw0 (which raises the LEAP fabric), powers the LEAP leaves (leap-s ADMAC, RX0, LEAP MCA), and only then requests the channel, whose registers fault without them. The trigger starts the DMA and queues pwrd behind it; started earlier, the LEAP produces into a channel nobody services. Close releases the channel, then pw0 and the leaves. The card exists only where the DT gives the LEAP power domains (all three); J873 is unchanged. The dmaengine substream setup moves into a helper shared with the ASoC front-ends. Tested on J813: a tone from the speakers reads -44 to -49 dBFS on all three channels, 70 dB over the quiet floor, exactly while it plays; PipeWire picks up the card with asahi-audio's J613 beamformer graph. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/t8152_aop_audio.rs | 478 ++++++++++++++++++++++++++--- 1 file changed, 429 insertions(+), 49 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 4c61092d0cea1e..9976684a8d7d85 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -10,6 +10,9 @@ //! channels 10 and 11). //! * `spkr`: the SN012776 speaker amplifier, base-ns TX1 (channel 2), its //! sense data on RX1. +//! * `hpai` (J813): the microphone array, three PDM microphones the firmware +//! delivers as float32 on leap-s ADMAC RX0. It has no codec, so it is the +//! capture PCM of a small card of its own. //! //! Each service is an ASoC back-end DAI: startup attaches it and requests //! `pw0 ` (which also brings up the audio fabric), prepare requests `pwrd` @@ -31,12 +34,14 @@ use kernel::{ module_platform_driver, of, platform, prelude::*, soc::apple::aop::{from_fourcc, EPICService, AOP}, + str::CString, sync::{ aref::ARef, atomic::{Atomic, AtomicFlag, Relaxed}, - Arc, + Arc, ArcBorrow, }, - types::Opaque, + types::{ForeignOwnable, Opaque}, + workqueue::{self, impl_has_work, new_work, Work, WorkItem}, }; const EPIC_SUBTYPE_WRAPPED_CALL: u16 = 0x20; @@ -57,6 +62,15 @@ const PD_GET_RETRY_MS: i64 = 10; /// The MCA serializer leaves (audio_mca0_m .. audio_mca5_m). const MCA_COUNT: usize = 6; const MCA_NAMES: [&CStr; MCA_COUNT] = [c"mca0", c"mca1", c"mca2", c"mca3", c"mca4", c"mca5"]; +/// The microphone array's LEAP leaves: the leap-s ADMAC, its RX0 channel and +/// the LEAP serializer. A LEAP ADMAC's channel registers only answer with +/// these powered (an access without them faults the bus). +const LEAP_NAMES: [&CStr; 3] = [c"leap_s_a", c"leap_rx0", c"leap_mca"]; +/// The microphone array's stream (ADT audio-hp-mic-proxy physical +/// description): 48 kHz, three float32 channels. +const HPAI_RATE: u32 = 48000; +const HPAI_CHANNELS: u32 = 3; +const HPAI_START_WORK: u64 = 1; fn aop_timestamp() -> u64 { // SAFETY: both helpers read the architected timer and take no arguments. @@ -223,6 +237,30 @@ struct T8152AopAudio { cfg: &'static HwConfig, /// The open sense capture front-end, if any. sense: Atomic<*mut bindings::snd_pcm_substream>, + hpai: Service, + /// The microphone array's leaves (`LEAP_NAMES`); empty without one. + leap: KVec, + /// The microphone capture is triggered. + hpai_want_run: AtomicFlag, + #[pin] + hpai_start_work: Work, +} + +impl_has_work! { + impl HasWork for T8152AopAudio { self.hpai_start_work } +} + +/// The microphone array's `pwrd`, queued by the capture trigger (a sleeping +/// firmware call). The ADMAC is running by then: started before it, the LEAP +/// produces into a channel nobody services and the capture stays noise. +impl WorkItem for T8152AopAudio { + type Pointer = Arc; + + fn run(this: Arc) { + if let Err(e) = this.hpai_go() { + dev_err!(this.dev, "hpai: start failed: {:?}\n", e); + } + } } impl T8152AopAudio { @@ -324,11 +362,11 @@ impl T8152AopAudio { Ok(()) } - fn mca_up(&self) -> Result<()> { - for (i, pd) in self.mca.iter().enumerate() { + fn leaves_up(&self, pds: &[PowerDomain], what: &str) -> Result<()> { + for (i, pd) in pds.iter().enumerate() { if let Err(e) = pd.get() { - dev_err!(self.dev, "MCA leaf {} did not power up: {:?}\n", i, e); - for pd in self.mca[..i].iter().rev() { + dev_err!(self.dev, "{} leaf {} did not power up: {:?}\n", what, i, e); + for pd in pds[..i].iter().rev() { pd.put(); } return Err(e); @@ -337,12 +375,20 @@ impl T8152AopAudio { Ok(()) } - fn mca_down(&self) { - for pd in self.mca.iter().rev() { + fn leaves_down(pds: &[PowerDomain]) { + for pd in pds.iter().rev() { pd.put(); } } + fn mca_up(&self) -> Result<()> { + self.leaves_up(&self.mca, "MCA") + } + + fn mca_down(&self) { + Self::leaves_down(&self.mca) + } + /// Back-end startup: attach, `pw0 ` (which raises the fabric), then the /// serializer leaves. fn startup(&self, svc: &Service) -> Result<()> { @@ -439,6 +485,39 @@ impl T8152AopAudio { } self.mca_down(); } + + /// Microphone open: attach, `pw0 ` (which raises the fabric), then the + /// LEAP leaves, before the capture requests its ADMAC channel. + fn hpai_startup(&self) -> Result<()> { + self.attach(&self.hpai)?; + self.set_power(&self.hpai, POWER_STATE_PW0)?; + self.leaves_up(&self.leap, "LEAP")?; + self.hpai.running.store(false, Relaxed); + Ok(()) + } + + fn hpai_go(&self) -> Result<()> { + if !self.hpai_want_run.load(Relaxed) { + return Ok(()); + } + self.run(&self.hpai) + } + + /// Microphone close, after the channel is released: a queued start + /// finishes first, then `pw0 ` and the leaves. + fn hpai_shutdown(&self) { + self.hpai_want_run.store(false, Relaxed); + // SAFETY: the work item lives in `self`; flushing waits for a queued + // `hpai_go`. + unsafe { bindings::flush_work(Work::raw_get(&self.hpai_start_work)) }; + if self.hpai.running.load(Relaxed) { + if let Err(e) = self.set_power(&self.hpai, POWER_STATE_PW0) { + dev_err!(self.dev, "hpai: pw0 failed: {:?}\n", e); + } + self.hpai.running.store(false, Relaxed); + } + Self::leaves_down(&self.leap); + } } // ---- the ASoC component ---- @@ -566,41 +645,11 @@ unsafe fn dai_data<'a>(dai: *mut bindings::snd_soc_dai) -> &'a T8152AopAudio { unsafe { component_data((*dai).component) } } -/// # Safety -/// -/// Called by ASoC on this driver's component with live arguments. -unsafe extern "C" fn asoc_pcm_open( - component: *mut bindings::snd_soc_component, - substream: *mut bindings::snd_pcm_substream, -) -> i32 { - // SAFETY: by the caller's contract. - let data = unsafe { component_data(component) }; - // SAFETY: as above. - let rtd = unsafe { substream_rtd(substream) }; - // SAFETY: as above. - if unsafe { rtd_is_be(rtd) } { - return 0; - } - // SAFETY: as above. - let Some(fe) = (unsafe { fe_index(rtd) }) else { - return EINVAL.to_errno(); - }; - // SAFETY: as above. - let playback = unsafe { is_playback(substream) }; - let Some(name) = FE_DMA_NAMES[fe][usize::from(!playback)] else { - return ENODEV.to_errno(); - }; - // SAFETY: the device is live and the name is NUL-terminated. - let chan = match from_err_ptr(unsafe { - bindings::dma_request_chan(data.dev.as_raw(), name.as_char_ptr()) - }) { - Ok(chan) => chan, - Err(e) => { - dev_err!(data.dev, "DMA channel {:?} unavailable: {:?}\n", name, e); - return e.to_errno(); - } - }; - let mut hw = bindings::snd_pcm_hardware { +/// The dmaengine PCMs' common description: mmap-able, interleaved, periods +/// from 256 bytes to the ADMAC's segment size. Rates, channels and formats +/// are left to the caller (for a front-end, ASoC fills them in from the DAI). +fn pcm_hw() -> bindings::snd_pcm_hardware { + bindings::snd_pcm_hardware { info: bindings::SNDRV_PCM_INFO_MMAP | bindings::SNDRV_PCM_INFO_MMAP_VALID | bindings::SNDRV_PCM_INFO_INTERLEAVED, @@ -611,9 +660,25 @@ unsafe extern "C" fn asoc_pcm_open( periods_max: (PCM_BUFFER_MAX / PCM_PERIOD_BYTES_MIN) as u32, fifo_size: 16, ..Default::default() - }; - // SAFETY: the substream and the channel are live. - let ret = unsafe { + } +} + +/// Sets up a dmaengine substream on `chan`: a managed buffer on the DMA +/// device (once per substream), `hw` refined by the channel and narrowed to +/// `formats`, then the dmaengine runtime. On failure the channel is still +/// the caller's. +/// +/// # Safety +/// +/// `substream` must be live and `chan` a channel the caller requested. +unsafe fn dmaengine_open( + substream: *mut bindings::snd_pcm_substream, + chan: *mut bindings::dma_chan, + mut hw: bindings::snd_pcm_hardware, + formats: u64, +) -> i32 { + // SAFETY: by the caller's contract. + unsafe { let mut ret = 0; if (*substream).dma_buffer.dev.type_ == bindings::SNDRV_DMA_TYPE_UNKNOWN as i32 { ret = bindings::snd_pcm_set_managed_buffer( @@ -634,12 +699,51 @@ unsafe extern "C" fn asoc_pcm_open( ); } if ret == 0 { - hw.formats &= if fe == 2 { data.cfg.sense_formats } else { FORMATS }; + hw.formats &= formats; (*(*substream).runtime).hw = hw; ret = bindings::snd_dmaengine_pcm_open(substream, chan); } ret + } +} + +/// # Safety +/// +/// Called by ASoC on this driver's component with live arguments. +unsafe extern "C" fn asoc_pcm_open( + component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { component_data(component) }; + // SAFETY: as above. + let rtd = unsafe { substream_rtd(substream) }; + // SAFETY: as above. + if unsafe { rtd_is_be(rtd) } { + return 0; + } + // SAFETY: as above. + let Some(fe) = (unsafe { fe_index(rtd) }) else { + return EINVAL.to_errno(); + }; + // SAFETY: as above. + let playback = unsafe { is_playback(substream) }; + let Some(name) = FE_DMA_NAMES[fe][usize::from(!playback)] else { + return ENODEV.to_errno(); }; + // SAFETY: the device is live and the name is NUL-terminated. + let chan = match from_err_ptr(unsafe { + bindings::dma_request_chan(data.dev.as_raw(), name.as_char_ptr()) + }) { + Ok(chan) => chan, + Err(e) => { + dev_err!(data.dev, "DMA channel {:?} unavailable: {:?}\n", name, e); + return e.to_errno(); + } + }; + let formats = if fe == 2 { data.cfg.sense_formats } else { FORMATS }; + // SAFETY: the substream is live and the channel was requested above. + let ret = unsafe { dmaengine_open(substream, chan, pcm_hw(), formats) }; if ret < 0 { // SAFETY: the open failed, so the channel is still ours. unsafe { bindings::dma_release_channel(chan) }; @@ -989,14 +1093,256 @@ impl AsocContext { } } +// ---- the microphone array's card ---- + +/// # Safety +/// +/// `substream` must be a live substream of the microphone PCM, whose private +/// data is the `Arc` leaked into it by `MicCard::new` (released in +/// `mic_pcm_free` after the last op). +unsafe fn mic_data<'a>(substream: *mut bindings::snd_pcm_substream) -> ArcBorrow<'a, T8152AopAudio> { + // SAFETY: by the caller's contract. + unsafe { Arc::::borrow((*(*substream).pcm).private_data.cast()) } +} + +/// The LEAP produces float32 into the channel requested here; the channel's +/// registers only answer with the LEAP leaves up, so the service (and with +/// it the leaves) comes up before the request and goes down after the +/// release. +/// +/// # Safety +/// +/// Called by ALSA with a live substream of the microphone PCM. +unsafe extern "C" fn mic_pcm_open(substream: *mut bindings::snd_pcm_substream) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { mic_data(substream) }; + // A failed startup has undone its leaves; the service stays in `pw0 `. + if let Err(e) = data.hpai_startup() { + return e.to_errno(); + } + // SAFETY: the device is live and the name is NUL-terminated. + let chan = match from_err_ptr(unsafe { + bindings::dma_request_chan(data.dev.as_raw(), c"hpai".as_char_ptr()) + }) { + Ok(chan) => chan, + Err(e) => { + dev_err!(data.dev, "hpai: DMA channel unavailable: {:?}\n", e); + data.hpai_shutdown(); + return e.to_errno(); + } + }; + let hw = bindings::snd_pcm_hardware { + rates: bindings::SNDRV_PCM_RATE_48000, + rate_min: HPAI_RATE, + rate_max: HPAI_RATE, + channels_min: HPAI_CHANNELS, + channels_max: HPAI_CHANNELS, + ..pcm_hw() + }; + // SAFETY: the substream is live and the channel was requested above. + let ret = unsafe { + dmaengine_open(substream, chan, hw, bindings::BINDINGS_SNDRV_PCM_FMTBIT_FLOAT_LE) + }; + if ret < 0 { + // SAFETY: the open failed, so the channel is still ours. + unsafe { bindings::dma_release_channel(chan) }; + data.hpai_shutdown(); + } + ret +} + +/// # Safety +/// +/// Called by ALSA with a live substream of the microphone PCM. +unsafe extern "C" fn mic_pcm_close(substream: *mut bindings::snd_pcm_substream) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { mic_data(substream) }; + // SAFETY: the dmaengine runtime was set up in `mic_pcm_open`. + let ret = unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) }; + data.hpai_shutdown(); + ret +} + +/// # Safety +/// +/// Called by ALSA with a live substream of the microphone PCM and live +/// parameters. +unsafe extern "C" fn mic_pcm_hw_params( + substream: *mut bindings::snd_pcm_substream, + params: *mut bindings::snd_pcm_hw_params, +) -> i32 { + // SAFETY: the dmaengine runtime was set up in `mic_pcm_open`. + let chan = unsafe { bindings::snd_dmaengine_pcm_get_chan(substream) }; + let mut cfg = bindings::dma_slave_config::default(); + // SAFETY: the substream and the parameters are live for the op. + let rc = unsafe { bindings::snd_hwparams_to_dma_slave_config(substream, params, &mut cfg) }; + if rc < 0 { + return rc; + } + // Three words per frame, which the ADMAC cannot mark (it frames 2 or 4): + // a plain word stream. + // SAFETY: `chan` is the live channel behind the substream. + unsafe { + match (*(*chan).device).device_config { + Some(f) => f(chan, &mut cfg), + None => ENOSYS.to_errno(), + } + } +} + +/// ALSA calls prepare unconditionally. Nothing to arm: the DMA start and +/// the queued firmware run belong to trigger. +/// +/// # Safety +/// +/// Called by ALSA with a live substream of the microphone PCM. +unsafe extern "C" fn mic_pcm_prepare(_substream: *mut bindings::snd_pcm_substream) -> i32 { + 0 +} + +/// With the stream lock held: the DMA first, then the firmware's `pwrd` +/// queued behind it. +/// +/// # Safety +/// +/// Called by ALSA with a live substream of the microphone PCM. +unsafe extern "C" fn mic_pcm_trigger(substream: *mut bindings::snd_pcm_substream, cmd: i32) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { mic_data(substream) }; + // SAFETY: the dmaengine runtime was set up in `mic_pcm_open`. + let ret = unsafe { bindings::snd_dmaengine_pcm_trigger(substream, cmd) }; + if ret < 0 { + return ret; + } + match cmd as u32 { + bindings::SNDRV_PCM_TRIGGER_START + | bindings::SNDRV_PCM_TRIGGER_RESUME + | bindings::SNDRV_PCM_TRIGGER_PAUSE_RELEASE => { + data.hpai_want_run.store(true, Relaxed); + // Err: already queued, and that run sees `hpai_want_run`. + let _ = workqueue::system().enqueue::<_, HPAI_START_WORK>(Arc::from(data)); + } + _ => data.hpai_want_run.store(false, Relaxed), + } + 0 +} + +/// # Safety +/// +/// Called once by ALSA when the PCM goes away. +unsafe extern "C" fn mic_pcm_free(pcm: *mut bindings::snd_pcm) { + // SAFETY: the `Arc` leaked into the private data by `MicCard::new`. + drop(unsafe { Arc::::from_foreign((*pcm).private_data.cast()) }); +} + +static MIC_PCM_OPS: bindings::snd_pcm_ops = bindings::snd_pcm_ops { + open: Some(mic_pcm_open), + close: Some(mic_pcm_close), + ioctl: None, + hw_params: Some(mic_pcm_hw_params), + hw_free: None, + prepare: Some(mic_pcm_prepare), + trigger: Some(mic_pcm_trigger), + sync_stop: None, + pointer: Some(bindings::snd_dmaengine_pcm_pointer), + get_time_info: None, + fill_silence: None, + copy: None, + page: None, + mmap: None, + ack: None, +}; + +/// Copies a NUL-terminated string into a fixed-size field, truncated to fit. +fn copy_str(target: &mut [u8], source: &CStr) { + let b = source.to_bytes(); + let n = b.len().min(target.len() - 1); + target[..n].copy_from_slice(&b[..n]); + target[n] = 0; +} + +/// The microphone array's card: one capture PCM, named like the other AOP +/// microphone cards (AppleJxxxHPAI) so that the UCM and DSP configurations +/// for those find it. +struct MicCard(*mut bindings::snd_card); + +impl MicCard { + fn new(data: &Arc) -> Result { + let fwnode = data.dev.fwnode().ok_or(ENODEV)?; + let chassis = fwnode + .property_read::(c_str!("apple,chassis-name")) + .required_by(&data.dev)?; + let kind = fwnode + .property_read::(c_str!("apple,machine-kind")) + .required_by(&data.dev)?; + let id = CString::try_from_fmt(fmt!("Apple{}HPAI", *chassis))?; + let shortname = CString::try_from_fmt(fmt!("{} {} HPAI", *kind, *chassis))?; + let longname = + CString::try_from_fmt(fmt!("{} {} High-Power Audio Interface", *kind, *chassis))?; + let mut card = ptr::null_mut(); + // SAFETY: the device and the module are live; `card` receives the card. + let ret = unsafe { + bindings::snd_card_new( + data.dev.as_raw(), + -1, + ptr::null(), + kernel::module::this_module::().as_ptr(), + 0, + &mut card, + ) + }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + // From here on, dropping `this` frees the card. + let this = MicCard(card); + // SAFETY: the card is new and unregistered. + unsafe { + copy_str(&mut (*card).driver, c"aop_audio"); + copy_str(&mut (*card).id, &id); + copy_str(&mut (*card).shortname, &shortname); + copy_str(&mut (*card).longname, &longname); + } + let mut pcm = ptr::null_mut(); + // SAFETY: the card is live; `pcm` receives the PCM. + let ret = unsafe { bindings::snd_pcm_new(card, c"hpai".as_char_ptr(), 0, 0, 1, &mut pcm) }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + // SAFETY: `pcm` is live; the ops are static and the private data is + // an `Arc` that `mic_pcm_free` releases. + unsafe { + bindings::snd_pcm_set_ops(pcm, bindings::SNDRV_PCM_STREAM_CAPTURE as i32, &MIC_PCM_OPS); + (*pcm).private_data = data.clone().into_foreign().cast(); + (*pcm).private_free = Some(mic_pcm_free); + copy_str(&mut (*pcm).name, c"Microphone Array"); + } + // SAFETY: the card is live and complete. + let ret = unsafe { bindings::snd_card_register(card) }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + Ok(this) + } +} + +impl Drop for MicCard { + fn drop(&mut self) { + // SAFETY: created by `snd_card_new`; this waits for open files. + unsafe { bindings::snd_card_free(self.0) }; + } +} + struct T8152AopAudioDriver { dev: ARef, asoc: KBox, registered: AtomicFlag, + /// Held for its drop, which frees the card after unbind. + _mic: Option, } -// SAFETY: the ASoC context is only touched by ASoC callbacks and by probe and -// remove, which the driver core serializes. +// SAFETY: the ASoC context and the card are only touched by ALSA/ASoC +// callbacks and by probe and remove, which the driver core serializes. unsafe impl Send for T8152AopAudioDriver {} // SAFETY: as for `Send`. unsafe impl Sync for T8152AopAudioDriver {} @@ -1069,6 +1415,21 @@ impl platform::Driver for T8152AopAudioDriver { } } + // The microphone array, where the DT describes it: all of its leaves + // or none. + let mut leap = KVec::new(); + for name in LEAP_NAMES { + match PowerDomain::attach(&dev, name) { + Ok(Some(pd)) => leap.push(pd, GFP_KERNEL)?, + Ok(None) => {} + Err(e) => return Err(e), + } + } + if !leap.is_empty() && leap.len() != LEAP_NAMES.len() { + dev_err!(dev, "incomplete microphone power domains\n"); + return Err(ENODEV); + } + let data_dev = dev.clone(); let data = Arc::pin_init( pin_init!(T8152AopAudio { @@ -1081,6 +1442,10 @@ impl platform::Driver for T8152AopAudioDriver { mca, cfg, sense: Atomic::new(ptr::null_mut()), + hpai: Service::new(from_fourcc(b"hpai"), "hpai", false), + leap, + hpai_want_run: AtomicFlag::new(false), + hpai_start_work <- new_work!("T8152AopAudio::hpai_start_work"), }), GFP_KERNEL, )?; @@ -1088,6 +1453,20 @@ impl platform::Driver for T8152AopAudioDriver { data.attach(svc)?; } + // The microphones are optional: the speakers and the jack stay + // usable without them. + let mic = if data.leap.is_empty() { + None + } else { + match MicCard::new(&data) { + Ok(card) => Some(card), + Err(e) => { + dev_err!(dev, "microphone card: {:?}\n", e); + None + } + } + }; + let asoc = AsocContext::new(data)?; // SAFETY: the descriptor and the DAI table are heap allocations owned // by `asoc`, which the driver data keeps until after unregister. @@ -1107,6 +1486,7 @@ impl platform::Driver for T8152AopAudioDriver { dev, asoc, registered: AtomicFlag::new(true), + _mic: mic, }) } From e42e2b87695ab30e8793dd6c26c332c5d2b2fc01 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 5 Nov 2026 20:11:17 +0100 Subject: [PATCH 0015/1514] soc: apple: aop: Set the T8152 and T8142 boot-argument fields integration/aurora added the nCal boot argument and word-wise boot-argument access to AopHwConfig. Both machine configurations keep the firmware's own boot arguments unchanged, so set ncal to zero and leave word access off. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/aop.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index eb99bc46521753..ec863dfde8feb9 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -2712,6 +2712,7 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { /// ADT aop-exclave-mailbox) is not reachable from the AP: both bus-error. const HW_CFG_T8152: AopHwConfig = AopHwConfig { ec0p: 0, + ncal: 0, aopt: 0, alig: 0, patch_bootargs: false, @@ -2721,6 +2722,7 @@ const HW_CFG_T8152: AopHwConfig = AopHwConfig { quiesce_on_unbind: true, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; @@ -2731,6 +2733,7 @@ const HW_CFG_T8152: AopHwConfig = AopHwConfig { /// firmware runs with the boot arguments iBoot left. const HW_CFG_T8142: AopHwConfig = AopHwConfig { ec0p: 0, + ncal: 0, aopt: 0, alig: 0, patch_bootargs: false, @@ -2740,6 +2743,7 @@ const HW_CFG_T8142: AopHwConfig = AopHwConfig { quiesce_on_unbind: true, required_endpoints: &[], fw_regions: false, + bootargs_word_access: false, halt_on_failed_start: false, }; From f03c37323e5c1dc1352985fde73cc67035eead39 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 7 Nov 2026 01:13:12 +1100 Subject: [PATCH 0016/1514] arm64: dts: apple: t604x-j614-j616: Describe the boot NOR flash supply Every boot on the J616s logged "spi-nor spi0.0: supply vcc not found, using dummy regulator". The M1, M2, M3, J713 and J700 trees describe the flash's always-on PMU rail as a fixed regulator; the M4 Pro/Max tree came later and has none. Add the same regulator and point the flash at it. Signed-off-by: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Assisted-by: LLM --- arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi index 7f12ea2491967c..9453cd912127b4 100644 --- a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi @@ -1625,6 +1625,16 @@ }; }; + /* + * The boot NOR runs from a PMU rail that is on whenever the SoC is + * and that no OS switches. The ADT gives the flash no supply. + */ + nor_flash_vcc: regulator-nor-flash-vcc { + compatible = "regulator-fixed"; + regulator-name = "nor-flash-vcc"; + regulator-always-on; + }; + /* * The speaker amps' shared shutdown line (SDZ, AP pin 54, low = * shutdown). One fixed regulator, the SDZ supply of all six, not @@ -1756,6 +1766,7 @@ spi-max-frequency = <10000000>; spi-rx-bus-width = <1>; spi-tx-bus-width = <1>; + vcc-supply = <&nor_flash_vcc>; partitions { compatible = "fixed-partitions"; From 12165bc25529cb20f8fa1a93c996b5b313e40437 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Fri, 6 Nov 2026 12:40:04 -0500 Subject: [PATCH 0017/1514] ASoC: apple: initialize J813 output standby before microphone registration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test whether COUT standby supplies the missing cold-boot fabric setup. A muted zero-data jack stream permitted HPAI capture and subsequent capture-only opens on J813; standby without any playback is the next hardware qualification step. Preserve Thomas Glanzmann’s driver and adapt the T8140 DMA sync-stop pattern from Ryan Murray, also flushing queued HPAI work before DMA teardown. No LPAI buffer binding or codec unmute is performed. --- sound/soc/apple/t8152_aop_audio.rs | 34 +++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 9976684a8d7d85..9aad831ad7a610 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -503,13 +503,17 @@ impl T8152AopAudio { self.run(&self.hpai) } - /// Microphone close, after the channel is released: a queued start - /// finishes first, then `pw0 ` and the leaves. - fn hpai_shutdown(&self) { + /// Finish a queued firmware start before retiring the DMA runtime. + fn flush_hpai_start(&self) { self.hpai_want_run.store(false, Relaxed); // SAFETY: the work item lives in `self`; flushing waits for a queued // `hpai_go`. unsafe { bindings::flush_work(Work::raw_get(&self.hpai_start_work)) }; + } + + /// Microphone close, after the channel is released: `pw0 ` then leaves. + fn hpai_shutdown(&self) { + self.flush_hpai_start(); if self.hpai.running.load(Relaxed) { if let Err(e) = self.set_power(&self.hpai, POWER_STATE_PW0) { dev_err!(self.dev, "hpai: pw0 failed: {:?}\n", e); @@ -1157,12 +1161,27 @@ unsafe extern "C" fn mic_pcm_open(substream: *mut bindings::snd_pcm_substream) - unsafe extern "C" fn mic_pcm_close(substream: *mut bindings::snd_pcm_substream) -> i32 { // SAFETY: by the caller's contract. let data = unsafe { mic_data(substream) }; + data.flush_hpai_start(); // SAFETY: the dmaengine runtime was set up in `mic_pcm_open`. let ret = unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) }; data.hpai_shutdown(); ret } +/// Finish queued firmware work and asynchronous DMA termination before ALSA +/// reuses or frees the capture buffer, as in the T8140 capture path. +/// +/// # Safety +/// +/// Called by ALSA with a live microphone substream and dmaengine runtime. +unsafe extern "C" fn mic_pcm_sync_stop(substream: *mut bindings::snd_pcm_substream) -> i32 { + // SAFETY: by the caller's contract. + let data = unsafe { mic_data(substream) }; + data.flush_hpai_start(); + // SAFETY: the runtime remains live until close. + unsafe { bindings::snd_dmaengine_pcm_sync_stop(substream) } +} + /// # Safety /// /// Called by ALSA with a live substream of the microphone PCM and live @@ -1243,7 +1262,7 @@ static MIC_PCM_OPS: bindings::snd_pcm_ops = bindings::snd_pcm_ops { hw_free: None, prepare: Some(mic_pcm_prepare), trigger: Some(mic_pcm_trigger), - sync_stop: None, + sync_stop: Some(mic_pcm_sync_stop), pointer: Some(bindings::snd_dmaengine_pcm_pointer), get_time_info: None, fill_silence: None, @@ -1458,7 +1477,12 @@ impl platform::Driver for T8152AopAudioDriver { let mic = if data.leap.is_empty() { None } else { - match MicCard::new(&data) { + // Initialize the shared output service before exposing HPAI. + // This is standby only: no DMA, running state or codec unmute. + // No userspace stream can race this before card registration. + match data.set_power(&data.cout, POWER_STATE_PW0) + .and_then(|_| MicCard::new(&data)) + { Ok(card) => Some(card), Err(e) => { dev_err!(dev, "microphone card: {:?}\n", e); From ad4910ce6ec1aef2b663e9f6fc8af2436a739742 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Fri, 6 Nov 2026 12:44:24 -0500 Subject: [PATCH 0018/1514] ASoC: apple: validate J813 audio topology and use the default worker queue Describe the T8142 microphone DMA and LEAP power domains and card names in the shared audio binding. Queue sleeping firmware power requests on system_dfl instead of the deprecated system workqueue, as directed by the runtime warning observed during hardware capture tests. --- .../bindings/sound/apple,t8152-aop-audio.yaml | 56 ++++++++++++++++++- sound/soc/apple/t8152_aop_audio.rs | 7 ++- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml index fa643fe62a9df9..b067077a213a13 100644 --- a/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,t8152-aop-audio.yaml @@ -4,7 +4,7 @@ $id: http://devicetree.org/schemas/sound/apple,t8152-aop-audio.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple T8152 AOP audio +title: Apple T8142 and T8152 AOP audio maintainers: - Thomas Glanzmann @@ -16,26 +16,63 @@ description: allOf: - $ref: dai-common.yaml# + - if: + properties: + compatible: + contains: + const: apple,t8142-aop-audio + then: + properties: + dmas: + minItems: 5 + dma-names: + minItems: 5 + power-domains: + minItems: 9 + power-domain-names: + minItems: 9 + required: + - apple,chassis-name + - apple,machine-kind + else: + properties: + dmas: + maxItems: 4 + dma-names: + maxItems: 4 + power-domains: + maxItems: 6 + power-domain-names: + maxItems: 6 properties: compatible: - const: apple,t8152-aop-audio + oneOf: + - const: apple,t8152-aop-audio + - items: + - const: apple,t8142-aop-audio + - const: apple,t8152-aop-audio dmas: + minItems: 4 items: - description: Headset jack output - description: Headset microphone input - description: Internal speaker output - description: Speaker sense input + - description: Internal microphone array input dma-names: + minItems: 4 items: - const: cout - const: cin - const: spkr - const: sense + - const: hpai power-domains: + minItems: 6 items: - description: Serializer 0 - description: Serializer 1 @@ -43,8 +80,12 @@ properties: - description: Serializer 3 - description: Serializer 4 - description: Serializer 5 + - description: Secure LEAP ADMAC + - description: LEAP receive channel 0 + - description: LEAP serializer power-domain-names: + minItems: 6 items: - const: mca0 - const: mca1 @@ -52,6 +93,17 @@ properties: - const: mca3 - const: mca4 - const: mca5 + - const: leap_s_a + - const: leap_rx0 + - const: leap_mca + + apple,chassis-name: + $ref: /schemas/types.yaml#/definitions/string + description: Chassis identifier used to name the microphone card + + apple,machine-kind: + $ref: /schemas/types.yaml#/definitions/string + description: Human-readable machine family used to name the microphone card "#sound-dai-cells": const: 1 diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 9aad831ad7a610..81a224f6974914 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -1239,7 +1239,7 @@ unsafe extern "C" fn mic_pcm_trigger(substream: *mut bindings::snd_pcm_substream | bindings::SNDRV_PCM_TRIGGER_PAUSE_RELEASE => { data.hpai_want_run.store(true, Relaxed); // Err: already queued, and that run sees `hpai_want_run`. - let _ = workqueue::system().enqueue::<_, HPAI_START_WORK>(Arc::from(data)); + let _ = workqueue::system_dfl().enqueue::<_, HPAI_START_WORK>(Arc::from(data)); } _ => data.hpai_want_run.store(false, Relaxed), } @@ -1477,7 +1477,8 @@ impl platform::Driver for T8152AopAudioDriver { let mic = if data.leap.is_empty() { None } else { - // Initialize the shared output service before exposing HPAI. + // J813 needs an output service initialized before HPAI can raise + // the shared fabric, even when no playback stream is requested. // This is standby only: no DMA, running state or codec unmute. // No userspace stream can race this before card registration. match data.set_power(&data.cout, POWER_STATE_PW0) @@ -1485,7 +1486,7 @@ impl platform::Driver for T8152AopAudioDriver { { Ok(card) => Some(card), Err(e) => { - dev_err!(dev, "microphone card: {:?}\n", e); + dev_err!(dev, "microphone initialization: {:?}\n", e); None } } From 9b4cf0e9aff84039c9ba2cd83c909c4151d89db1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:06:54 +0100 Subject: [PATCH 0019/1514] dt-bindings: iommu: apple,sart: Add T8152 compatible The T8152 (M6) SART (ADT sart-version 4) keeps the per-entry configuration, address and size registers in three separate arrays, so it is not compatible with the earlier SARTs. Add apple,t8152-sart. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/iommu/apple,sart.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Documentation/devicetree/bindings/iommu/apple,sart.yaml b/Documentation/devicetree/bindings/iommu/apple,sart.yaml index e6482453d6dacb..021fb3eb5b8f52 100644 --- a/Documentation/devicetree/bindings/iommu/apple,sart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,sart.yaml @@ -26,6 +26,9 @@ description: SART3, first seen in M1 Pro/Max, extends both the address space and filter entry size to 42 bit. + SART4, found in T8152 (M6), moves the configuration, address and size + registers into separate arrays. + properties: compatible: oneOf: @@ -45,6 +48,7 @@ properties: - apple,t6000-sart - apple,t8015-sart - apple,t8103-sart + - apple,t8152-sart reg: maxItems: 1 From b16eae52b77a9fdc9d32b0a62597fe2c73e184b1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:06:54 +0100 Subject: [PATCH 0020/1514] dt-bindings: nvme: apple,nvme-ans: Add T8152 compatible T8152 (M6) uses the secure ANS2 register layout and is not compatible with the earlier controllers. There is no T8152 PMGR provider yet; the loader leaves ANS powered and the driver treats the reset as optional, so do not require resets and power domains for apple,t8152-nvme-ans2. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- .../devicetree/bindings/nvme/apple,nvme-ans.yaml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml index a6dafcf5942890..b0f21ee126b015 100644 --- a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml +++ b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml @@ -22,6 +22,7 @@ properties: - apple,t8122-nvme-ans2 - const: apple,t8103-nvme-ans2 - const: apple,t8132-nvme-ans2 + - const: apple,t8152-nvme-ans2 - items: - const: apple,t8132-nvme-ans2 - const: apple,t8103-nvme-ans2 @@ -110,6 +111,18 @@ properties: buffers must remain reserved and protected by the SART. allOf: + - if: + properties: + compatible: + not: + contains: + const: apple,t8152-nvme-ans2 + then: + required: + - resets + - power-domains + - power-domain-names + - if: properties: compatible: @@ -170,9 +183,6 @@ required: - compatible - reg - reg-names - - resets - - power-domains - - power-domain-names - mboxes - interrupts - apple,sart From 359d13aada8142ec35896d9030aa50ba99ddbb32 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:06:54 +0100 Subject: [PATCH 0021/1514] dt-bindings: mailbox: apple,mailbox: Add T8152 ANS mailbox The T8152 (M6) ANS co-processor is reached through a 0x80 window in the post-office mailbox bank. No interrupts are described for it and the host polls it. Add apple,t8152-ans-mailbox and only require interrupts for the other mailboxes. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- .../bindings/mailbox/apple,mailbox.yaml | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index cd19124e724c3f..1a40e2e38786b8 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -75,6 +75,11 @@ properties: AOP setup-port mailbox with a separate register layout. const: apple,t8140-aop-setup-mailbox + - description: + T8152 ANS post-office mailbox, a 0x80 window in the post-office + bank. No interrupts are described for it; the host polls it. + const: apple,t8152-ans-mailbox + - description: An older ASC mailbox interface found on T2 and A11 that is also used for the NVMe coprocessor and the system management @@ -148,6 +153,20 @@ allOf: - const: send-empty - const: recv-not-empty + - if: + properties: + compatible: + contains: + const: apple,t8152-ans-mailbox + then: + properties: + interrupts: false + interrupt-names: false + else: + required: + - interrupts + - interrupt-names + - if: properties: compatible: @@ -211,8 +230,6 @@ allOf: required: - compatible - reg - - interrupts - - interrupt-names - "#mbox-cells" additionalProperties: false From 2c87179a0c0888cb5d9d4b80c2df50754662d93f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 13:30:24 +0200 Subject: [PATCH 0022/1514] soc: apple: sart: add the T8152 coastguard SART (sart-version 4) Config, paddr and size registers at 0x00, 0x60 and 0xc0 per entry, in 4 KiB units, as m1n1 src/sart.c. Needed by ANS2 on the M6 Mac mini. Signed-off-by: Thomas Glanzmann [Acelogic: Exercised on the ported code by a read-only probe on the M6; write testing was done on Thomas Glanzmann's original J873 series.] Signed-off-by: Acelogic --- drivers/soc/apple/sart.c | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/drivers/soc/apple/sart.c b/drivers/soc/apple/sart.c index 6cedcb867c61b5..c44b14c655be82 100644 --- a/drivers/soc/apple/sart.c +++ b/drivers/soc/apple/sart.c @@ -195,6 +195,43 @@ static void sart3_set_entry(struct apple_sart *sart, int index, u8 flags, writel(flags, sart->regs + APPLE_SART3_CONFIG(index)); } +#define APPLE_SART4_CONFIG(idx) (0x00 + 4 * (idx)) +#define APPLE_SART4_PADDR(idx) (0x60 + 4 * (idx)) +#define APPLE_SART4_PADDR_SHIFT 12 +#define APPLE_SART4_SIZE(idx) (0xc0 + 4 * (idx)) +#define APPLE_SART4_SIZE_SHIFT 12 +#define APPLE_SART4_SIZE_MAX GENMASK(29, 0) +#define APPLE_SART4_FLAGS_ALLOW 0xff + +/* T8152 "coastguard" SART (ADT sart-version 4), layout as m1n1 src/sart.c. */ +static void sart4_get_entry(struct apple_sart *sart, int index, u8 *flags, + phys_addr_t *paddr, size_t *size) +{ + phys_addr_t paddr_ = readl(sart->regs + APPLE_SART4_PADDR(index)); + size_t size_ = readl(sart->regs + APPLE_SART4_SIZE(index)); + + *flags = readl(sart->regs + APPLE_SART4_CONFIG(index)); + *size = size_ << APPLE_SART4_SIZE_SHIFT; + *paddr = paddr_ << APPLE_SART4_PADDR_SHIFT; +} + +static void sart4_set_entry(struct apple_sart *sart, int index, u8 flags, + phys_addr_t paddr_shifted, size_t size_shifted) +{ + writel(paddr_shifted, sart->regs + APPLE_SART4_PADDR(index)); + writel(size_shifted, sart->regs + APPLE_SART4_SIZE(index)); + writel(flags, sart->regs + APPLE_SART4_CONFIG(index)); +} + +static struct apple_sart_ops sart_ops_v4 = { + .get_entry = sart4_get_entry, + .set_entry = sart4_set_entry, + .flags_allow = APPLE_SART4_FLAGS_ALLOW, + .size_shift = APPLE_SART4_SIZE_SHIFT, + .paddr_shift = APPLE_SART4_PADDR_SHIFT, + .size_max = APPLE_SART4_SIZE_MAX, +}; + static struct apple_sart_ops sart_ops_v3 = { .get_entry = sart3_get_entry, .set_entry = sart3_set_entry, @@ -409,6 +446,10 @@ static void apple_sart_shutdown(struct platform_device *pdev) } static const struct of_device_id apple_sart_of_match[] = { + { + .compatible = "apple,t8152-sart", + .data = &sart_ops_v4, + }, { .compatible = "apple,t6000-sart", .data = &sart_ops_v3, From 83e97d02765cd2e67204615e97a732c3a681fec5 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 13:30:24 +0200 Subject: [PATCH 0023/1514] soc: apple: mailbox: add the J873 ANS post-office mailbox Add a polled, interrupt-free provider for the ANS post-office window. ANS uses mailbox 3 of the non-alias post-office bank (0x316010300), a 0x80-byte window with the same counted-FIFO layout as the T8152 SMC mailbox. No interrupt is described for it, so the provider claims none: receive runs on the receive poller of the GFX ASCWrap v8 provider, send polls the FIFO status, and the receive hold/release hooks do nothing for it. It binds only on the J873, at exactly that window. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, which has no PMP post-office provider: the original made the PMP provider's J873 window check per hardware entry and added ANS next to PMP; here the polled mode is added for the ANS entry alone. Exercised on the ported code by a read-only probe on the M6; write testing was done on Thomas Glanzmann's original J873 series.] Co-developed-by: Acelogic Signed-off-by: Acelogic --- drivers/soc/apple/mailbox.c | 63 +++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index c13c03f9d92ab6..8e864229d5efe1 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -220,6 +220,10 @@ struct apple_mbox_hw { unsigned int num_ascwrap_v6_roles; /* T8152 GPU ASCWrap v8: wrapper + iop-vbar + post-office window + PSD. */ bool is_ascwrap_v8; + /* No interrupts are described; receive and send are polled. */ + bool rx_poll_required; + /* J873 post-office window a polled provider must sit at. */ + u64 j873_window; /* Status word counts RX occupancy and free TX slots; paired transfers. */ bool counted_fifo; bool ap_initializes_mailboxes; @@ -251,7 +255,7 @@ struct apple_mbox_priv { struct apple_mbox mbox; /* ASCWrap v8 only: the provider's PMGR2 PSD service block (read-only). */ void __iomem *psd_regs; - /* ASCWrap v8 only: receive by polling; fixed at probe. */ + /* ASCWrap v8 and polled providers: receive by polling; fixed at probe. */ bool rx_poll_only; /* rx_lock: recv interrupt enabled and not yet disabled again. */ bool rx_irq_live; @@ -270,7 +274,7 @@ static struct apple_mbox_priv *apple_mbox_to_priv(struct apple_mbox *mbox) /* Only providers allocated by apple_mbox_probe() have a receive poller. */ static bool apple_mbox_has_rx_poller(const struct apple_mbox *mbox) { - return mbox->hw->is_ascwrap_v8; + return mbox->hw->is_ascwrap_v8 || mbox->hw->rx_poll_required; } /* Both ASCWrap generations share the consumer lifecycle API below. */ @@ -1038,12 +1042,17 @@ EXPORT_SYMBOL(apple_mbox_stop); void apple_mbox_hold_rx(struct apple_mbox *mbox) { + /* A polled provider claims no receive interrupt. */ + if (mbox->hw->rx_poll_required) + return; disable_irq(mbox->irq_recv_not_empty); } EXPORT_SYMBOL(apple_mbox_hold_rx); void apple_mbox_release_rx(struct apple_mbox *mbox) { + if (mbox->hw->rx_poll_required) + return; enable_irq(mbox->irq_recv_not_empty); } EXPORT_SYMBOL(apple_mbox_release_rx); @@ -1105,7 +1114,8 @@ static void apple_mbox_quiesce(void *data) if (mbox->irq_send_empty >= 0) synchronize_irq(mbox->irq_send_empty); complete_all(&mbox->tx_empty); - synchronize_irq(mbox->irq_recv_not_empty); + if (mbox->irq_recv_not_empty >= 0) + synchronize_irq(mbox->irq_recv_not_empty); spin_lock_irqsave(&mbox->rx_lock, flags); had_rx = mbox->rx; @@ -1369,6 +1379,16 @@ static int apple_mbox_probe(struct platform_device *pdev) return ret; } else { res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + /* + * A polled provider must be exactly its own 0x80-byte window of + * the J873 post-office bank; the rest belongs to other roles. + */ + if (mbox->hw->rx_poll_required && + (!of_machine_is_compatible("apple,j873g") || !res || + res->start != mbox->hw->j873_window || + resource_size(res) != APPLE_ASCWRAP_V8_MBOX_SIZE)) + return dev_err_probe(dev, -EINVAL, + "post-office window does not match the J873 profile\n"); if (!res || resource_size(res) < mbox->hw->reg_offset + mbox->hw->i2a_recv1 + sizeof(u64)) return dev_err_probe(dev, -EINVAL, @@ -1380,6 +1400,21 @@ static int apple_mbox_probe(struct platform_device *pdev) mbox->regs = (u8 __iomem *)mbox->regs + mbox->hw->reg_offset; } + if (mbox->hw->rx_poll_required) { + mbox->rx_util_min = -1; + mbox->rx_util_min_applied = -1; + spin_lock_init(&mbox->rx_lock); + spin_lock_init(&mbox->tx_lock); + mutex_init(&mbox->lifecycle_lock); + init_completion(&mbox->tx_empty); + priv->rx_poll_only = true; + INIT_DELAYED_WORK(&priv->rx_poll_work, apple_mbox_v8_rx_poll_work); + mbox->irq_recv_not_empty = -ENXIO; + mbox->irq_send_empty = -ENXIO; + dev_info(dev, "J873 post-office: paired transfers, bounded polling, no IRQ claim\n"); + goto setup_pm; + } + mbox->irq_recv_not_empty = platform_get_irq_byname(pdev, "recv-not-empty"); if (mbox->irq_recv_not_empty < 0) @@ -1431,6 +1466,7 @@ static int apple_mbox_probe(struct platform_device *pdev) return ret; } +setup_pm: ret = devm_pm_runtime_enable(dev); if (ret) return ret; @@ -1706,8 +1742,29 @@ static const struct apple_mbox_hw apple_mbox_t8152_smc_hw = { .has_irq_controls = false, }; +/* + * T8152 ANS: msgbox-mailbox-num 3 in the non-alias post-office bank, the + * same counted FIFO as the SMC mailbox. Its interrupt ordering is not known, + * so no interrupt is described and both directions are polled. + */ +static const struct apple_mbox_hw apple_mbox_t8152_ans_hw = { + .rx_poll_required = true, + .j873_window = 0x316010300ULL, + .counted_fifo = true, + .control_full = GENMASK(11, 8), /* free TX slots */ + .control_empty = GENMASK(3, 0), /* RX occupancy */ + .a2i_control = 0x20, + .a2i_send0 = 0x10, + .a2i_send1 = 0x18, + .i2a_control = 0x20, + .i2a_recv0 = 0x00, + .i2a_recv1 = 0x08, + .has_irq_controls = false, +}; + static const struct of_device_id apple_mbox_of_match[] = { { .compatible = "apple,t8152-smc-mailbox", .data = &apple_mbox_t8152_smc_hw }, + { .compatible = "apple,t8152-ans-mailbox", .data = &apple_mbox_t8152_ans_hw }, { .compatible = "apple,t6031-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8122-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8152-gfx-ascwrap-v8", .data = &apple_mbox_t8152_gfx_ascwrap_v8_hw }, From 81bc2a911813a8367a10fde004b7eb2bce28625c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 13:30:25 +0200 Subject: [PATCH 0024/1514] nvme: apple: add T8152 (M6) with the secure register layout The M6 ADT marks ANS2 with nvme-secure-reg-layout: as in macOS AppleANS2NVMeController with its 0x92a flag, AQA/ASQ/ACQ and the I/O queue registers move up by 0x4000 and LINEAR_SQ_CTRL moves to 0x2813c; CC/CSTS, doorbells and NVMMU stay. NVMe and NVMMU share one window, and there is no reset provider yet. Reads and writes verified on J873. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the T8152 entry joins the T8142 and T6040 ones and sets NVME_QUIRK_BROKEN_FUA like the T8132, T8140 and T8142 entries, and the moved LINEAR_SQ_CTRL is used inside the existing lsq_in_nvmmu check. The read and write verification above was on Thomas Glanzmann's original J873 series; the ported code is exercised by a read-only probe on the M6.] Signed-off-by: Acelogic --- drivers/nvme/host/apple.c | 68 ++++++++++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 12 deletions(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index e4c9a1ccd38a02..08ec93ad927806 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -65,6 +65,15 @@ #define APPLE_ANS_LINEAR_ASQ_DB 0x2490c #define APPLE_ANS_LINEAR_IOSQ_DB 0x24910 +/* + * ADT nvme-secure-reg-layout (T8152, macOS AppleANS2NVMeController with its + * 0x92a flag set): AQA/ASQ/ACQ and the I/O queue registers move up by + * 0x4000 and LINEAR_SQ_CTRL moves into the NVMMU block. CC/CSTS, the + * doorbells and the NVMMU TCB registers stay where they are. + */ +#define APPLE_ANS_SECURE_QREG_SHIFT 0x4000 +#define APPLE_ANS_SECURE_LINEAR_SQ_CTRL 0x2813c + #define APPLE_NVMMU_NUM_TCBS 0x28100 #define APPLE_NVMMU_ASQ_TCB_BASE 0x28108 #define APPLE_NVMMU_IOSQ_TCB_BASE 0x28110 @@ -208,6 +217,9 @@ struct apple_nvme_hw { bool needs_ioq_registers; /* T8132 needs a PMGR reset when starting a stopped coprocessor. */ bool cold_reset; + /* No reset provider yet; only an adopted live session can come up. */ + bool optional_reset; + bool secure_reg_layout; u32 max_queue_depth; unsigned long quirks; }; @@ -377,6 +389,17 @@ static int apple_nvme_read_handoff(struct apple_nvme *anv) return apple_nvme_can_adopt_rtkit(anv) ? 0 : -EIO; } +static u32 apple_nvme_qreg(const struct apple_nvme *anv, u32 reg) +{ + return anv->hw->secure_reg_layout ? reg + APPLE_ANS_SECURE_QREG_SHIFT : reg; +} + +static u32 apple_nvme_lsq_ctrl(const struct apple_nvme *anv) +{ + return anv->hw->secure_reg_layout ? APPLE_ANS_SECURE_LINEAR_SQ_CTRL : + APPLE_ANS_LINEAR_SQ_CTRL; +} + static inline struct apple_nvme *queue_to_apple_nvme(struct apple_nvme_queue *q) { if (q->is_adminq) @@ -1786,10 +1809,10 @@ static void apple_nvme_reset_work(struct work_struct *work) */ if (!anv->hw->lsq_in_nvmmu) { writel(APPLE_ANS_LINEAR_SQ_EN, - anv->mmio_nvme + APPLE_ANS_LINEAR_SQ_CTRL); + anv->mmio_nvme + apple_nvme_lsq_ctrl(anv)); if (anv->hw->needs_ioq_registers) { u32 lsq_ctrl = readl(anv->mmio_nvme + - APPLE_ANS_LINEAR_SQ_CTRL); + apple_nvme_lsq_ctrl(anv)); if (!(lsq_ctrl & APPLE_ANS_LINEAR_SQ_EN)) { dev_err(anv->dev, @@ -1812,9 +1835,11 @@ static void apple_nvme_reset_work(struct work_struct *work) if (anv->hw->needs_ioq_registers) ioqa_depth--; ioqa = ioqa_depth | (ioqa_depth << 16); - writel(ioqa, anv->mmio_nvme + APPLE_ANS_MAX_PEND_CMDS_CTRL); + writel(ioqa, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_MAX_PEND_CMDS_CTRL)); if (anv->hw->needs_ioq_registers && - readl(anv->mmio_nvme + APPLE_ANS_MAX_PEND_CMDS_CTRL) != ioqa) { + readl(anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_MAX_PEND_CMDS_CTRL)) != ioqa) { dev_err(anv->dev, "failed to program I/O queue aperture\n"); ret = -EIO; goto out; @@ -1828,11 +1853,11 @@ static void apple_nvme_reset_work(struct work_struct *work) /* Setup the admin queue */ aqa = APPLE_NVME_AQ_DEPTH - 1; aqa |= aqa << 16; - writel(aqa, anv->mmio_nvme + NVME_REG_AQA); + writel(aqa, anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_AQA)); apple_nvme_writeq(anv, anv->adminq.sq_dma_addr, - anv->mmio_nvme + NVME_REG_ASQ); + anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_ASQ)); apple_nvme_writeq(anv, anv->adminq.cq_dma_addr, - anv->mmio_nvme + NVME_REG_ACQ); + anv->mmio_nvme + apple_nvme_qreg(anv, NVME_REG_ACQ)); if (anv->hw->has_lsq_nvmmu) { /* Setup NVMMU for both queues */ @@ -1899,10 +1924,10 @@ static void apple_nvme_reset_work(struct work_struct *work) * dedicated registers. Without them it crashes and its crash log * reports null I/O SQ and CQ addresses. */ - apple_nvme_writeq(anv, anv->ioq.cq_dma_addr, - anv->mmio_nvme + APPLE_ANS_IOCQ_REGISTER); - apple_nvme_writeq(anv, anv->ioq.sq_dma_addr, - anv->mmio_nvme + APPLE_ANS_IOSQ_REGISTER); + apple_nvme_writeq(anv, anv->ioq.cq_dma_addr, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_IOCQ_REGISTER)); + apple_nvme_writeq(anv, anv->ioq.sq_dma_addr, anv->mmio_nvme + + apple_nvme_qreg(anv, APPLE_ANS_IOSQ_REGISTER)); } nr_io_queues = 1; if (anv->hw->has_queue_count) { @@ -2393,7 +2418,10 @@ static struct apple_nvme *apple_nvme_alloc(struct platform_device *pdev) goto out_detach_genpd; } - anv->reset = devm_reset_control_array_get_exclusive(anv->dev); + if (anv->hw->optional_reset) + anv->reset = devm_reset_control_array_get_optional_exclusive(anv->dev); + else + anv->reset = devm_reset_control_array_get_exclusive(anv->dev); if (IS_ERR(anv->reset)) { ret = dev_err_probe(dev, PTR_ERR(anv->reset), "Failed to get reset control"); @@ -2754,6 +2782,21 @@ static const struct apple_nvme_hw apple_nvme_t6040_hw = { .quirks = NVME_QUIRK_NO_APST, }; +/* + * T8152 uses the post-M4 queue setup, but its NVMe registers and NVMMU share + * one window (0x325cc0000 on J873) like T8103, with the secure register + * layout. There is no T8152 PMGR driver yet, so the controller has no reset + * line in the DT. + */ +static const struct apple_nvme_hw apple_nvme_t8152_hw = { + .has_lsq_nvmmu = true, + .needs_ioq_registers = true, + .optional_reset = true, + .secure_reg_layout = true, + .max_queue_depth = 64, + .quirks = NVME_QUIRK_BROKEN_FUA, +}; + static const struct of_device_id apple_nvme_of_match[] = { { .compatible = "apple,t6041-nvme-ans2", .data = &apple_nvme_t6040_hw }, { .compatible = "apple,t8015-nvme-ans2", .data = &apple_nvme_t8015_hw }, @@ -2761,6 +2804,7 @@ static const struct of_device_id apple_nvme_of_match[] = { { .compatible = "apple,t8132-nvme-ans2", .data = &apple_nvme_t8132_hw }, { .compatible = "apple,t8140-nvme-ans2", .data = &apple_nvme_t8140_hw }, { .compatible = "apple,t8142-nvme-ans2", .data = &apple_nvme_t8142_hw }, + { .compatible = "apple,t8152-nvme-ans2", .data = &apple_nvme_t8152_hw }, { .compatible = "apple,nvme-ans2", .data = &apple_nvme_t8103_hw }, {}, }; From a400e257002e585430953a2a24082acd1c716f7f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 15:11:45 +0100 Subject: [PATCH 0025/1514] nvme: apple: send the shutdown notification on T8152 The post-M4 disable path only clears CC.EN, so the ANS firmware treats every system shutdown as unclean: on the next boot it logs "uncleanReboot yes" and abandons its open bands (host SLC, parity, CLOG). On T8152, send the NVMe shutdown notification (CC.SHN normal, wait for CSTS.SHST complete) before the CC.EN clear on system shutdown. The RTKit co-processor is still left running, as before. Tested on a J873 (Mac mini M6): after a reboot the firmware no longer reports an unclean reboot (0 instead of 4 "uncleanReboot yes" messages). Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, which already sends the notification at the final system shutdown of every post-M4 controller: T8152 also sends it when the driver is removed, as the original did, but not for system sleep. The test above was on Thomas Glanzmann's original J873 series; the ported code is exercised by a read-only probe on the M6.] Signed-off-by: Acelogic --- drivers/nvme/host/apple.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 08ec93ad927806..5d59726edeb137 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -220,6 +220,8 @@ struct apple_nvme_hw { /* No reset provider yet; only an adopted live session can come up. */ bool optional_reset; bool secure_reg_layout; + /* Also send the NVMe shutdown notification (CC.SHN) on removal. */ + bool shutdown_notify; u32 max_queue_depth; unsigned long quirks; }; @@ -1376,10 +1378,13 @@ static int apple_nvme_disable_locked(struct apple_nvme *anv, bool shutdown) * The final system shutdown is the exception for SHN: without it the * controller counts every Linux shutdown as unsafe (SMART * unsafe_shutdowns) and recovers on the next start, which slows the - * loader and the first seconds of I/O. A failed SHN changes nothing: - * the CC.EN clear below still runs. + * loader and the first seconds of I/O. Where the firmware handles it, + * removal sends it too. A failed SHN changes nothing: the CC.EN clear + * below still runs. */ - if (READ_ONCE(anv->final_shutdown) && !apple_rtkit_is_crashed(anv->rtk)) { + if ((READ_ONCE(anv->final_shutdown) || + (shutdown && anv->hw->shutdown_notify && READ_ONCE(anv->removing))) && + !apple_rtkit_is_crashed(anv->rtk)) { ret = nvme_disable_ctrl(&anv->ctrl, true); if (ret) dev_warn(anv->dev, "shutdown notification failed: %d\n", ret); @@ -2793,6 +2798,7 @@ static const struct apple_nvme_hw apple_nvme_t8152_hw = { .needs_ioq_registers = true, .optional_reset = true, .secure_reg_layout = true, + .shutdown_notify = true, .max_queue_depth = 64, .quirks = NVME_QUIRK_BROKEN_FUA, }; From 8eb5187fd12c0b3798aa3a5ca1c9381c662484f1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 13:30:25 +0200 Subject: [PATCH 0026/1514] arm64: dts: apple: j873: ANS2 NVMe Mailbox, SART and NVMe nodes for the internal SSD. The driver wakes iBoot's running ANS firmware with a fresh RTKit handshake. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the nodes go into t8152-j873-nvme.dtsi, which t8152-j873g.dts includes, instead of a separate t8152-j873-nvme.dtb layered on the USB tree. Exercised on the ported code by a read-only probe on the M6; write testing was done on Thomas Glanzmann's original J873 series.] Signed-off-by: Acelogic --- .../arm64/boot/dts/apple/t8152-j873-nvme.dtsi | 35 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 36 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi new file mode 100644 index 00000000000000..c53059ab55d34c --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g ANS2 NVMe. + * iBoot leaves the ANS firmware running with the NVMe controller disabled; + * the driver wakes it with a fresh RTKit handshake (as m1n1 does). NVMe + * registers and NVMMU share the 0x325cc0000 window. The mailbox is the ANS + * post-office window (msgbox-mailbox-num 3, no alias: 0x316000000 + + * 0x10300). No PMGR power or reset yet. + * Resources are from the 26A434 ADT: ans, sart-ans. + */ + +/ { + soc { + ans_mbox: mailbox@316010300 { + compatible = "apple,t8152-ans-mailbox"; + reg = <0x3 0x16010300 0x0 0x80>; + #mbox-cells = <0>; + }; + + sart: iommu@325c50000 { + compatible = "apple,t8152-sart"; + reg = <0x3 0x25c50000 0x0 0xc000>; + }; + + nvme: nvme@325cc0000 { + compatible = "apple,t8152-nvme-ans2"; + reg = <0x3 0x25cc0000 0x0 0x60000>, + <0x3 0x21600000 0x0 0x4000>; + reg-names = "nvme", "ans"; + interrupts = ; + mboxes = <&ans_mbox>; + apple,sart = <&sart>; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 1513a2abbc83ff..77e5e1abdf18a3 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -286,3 +286,4 @@ #include "t8152-j873-pmc.dtsi" #include "t8152-j873-qspi.dtsi" +#include "t8152-j873-nvme.dtsi" From 9c56293bc07aab63f5b09dd1502bf5e35f0c0425 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 12:35:44 +0200 Subject: [PATCH 0027/1514] arm64: dts: apple: j873: USB1 (back-left) USB2 host bring-up Describe usb-drd1 as a plain DWC3 host behind its two T8110-style DARTs. The loader powers the controller, wakes the port's HPM (SSPS 0) and initialises the eUSB2 PHY in host mode before Linux starts. Resources are from the 26A434 ADT. A USB keyboard enumerates. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the nodes go into t8152-j873-usb.dtsi, which t8152-j873g.dts includes, instead of a separate t8152-j873-usb.dtb. dtbs_check warns that the snps,dwc3 binding allows one iommus entry; the controller sits behind two DARTs, as described here.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 37 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 38 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi new file mode 100644 index 00000000000000..59f0dcf3946179 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g USB1 (usb-drd1, back-left port) USB2 host bring-up. + * The loader powers the controller and initialises the eUSB2 PHY in host + * mode before Linux starts (no PMGR, PHY or Type-C driver yet), so the + * controller is described as a plain DWC3 host behind its two DARTs. + * Resources are from the 26A434 ADT: dart-usb1, usb-drd1. + */ + +/ { + soc { + usb1_dart0: iommu@40b020000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b020000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + usb1_dart1: iommu@40b040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + usb1: usb@40a430000 { + compatible = "snps,dwc3"; + reg = <0x4 0x0a430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&usb1_dart0 0>, <&usb1_dart1 1>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 77e5e1abdf18a3..ac38151e0acb00 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -287,3 +287,4 @@ #include "t8152-j873-pmc.dtsi" #include "t8152-j873-qspi.dtsi" #include "t8152-j873-nvme.dtsi" +#include "t8152-j873-usb.dtsi" From 7c13f45712128843ebce56d9238330339162c627 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 12:42:59 +0200 Subject: [PATCH 0028/1514] arm64: dts: apple: j873: USB2 host for the front ports (usb-drd2) usb-drd2 feeds the on-board VL822 hub (05ac:800f) behind the two front USB-C ports. Describe it like usb-drd1: plain DWC3 host behind its two DARTs (0x383020000/0x383040000, IRQ 1750), controller IRQ 1763. The loader also releases the hub from reset (nub-gpio 39). Signed-off-by: Thomas Glanzmann [Acelogic: the nodes go into t8152-j873-usb.dtsi; dtbs_check gives the same snps,dwc3 iommus warning as for usb-drd1.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 59f0dcf3946179..e5cd25e427fe4a 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -1,10 +1,11 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * J873g USB1 (usb-drd1, back-left port) USB2 host bring-up. - * The loader powers the controller and initialises the eUSB2 PHY in host + * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 + * (front ports via the on-board hub). + * The loader powers the controllers and initialises the eUSB2 PHYs in host * mode before Linux starts (no PMGR, PHY or Type-C driver yet), so the - * controller is described as a plain DWC3 host behind its two DARTs. - * Resources are from the 26A434 ADT: dart-usb1, usb-drd1. + * controllers are described as plain DWC3 hosts behind their two DARTs. + * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2. */ / { @@ -33,5 +34,31 @@ snps,dis_u2_susphy_quirk; snps,dis_u3_susphy_quirk; }; + + usb2_dart0: iommu@383020000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83020000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + usb2_dart1: iommu@383040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ + usb2: usb@382430000 { + compatible = "snps,dwc3"; + reg = <0x3 0x82430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&usb2_dart0 0>, <&usb2_dart1 1>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; }; }; From 199c58c9e45672d45f34bbfe12d4b4f737fa3e59 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 09:45:57 +0100 Subject: [PATCH 0029/1514] PCI: apple: keep T8152 endpoints at the reset Max_Read_Request_Size On T8152 (J873) the on-board RTL8127A transmits much slower with large read requests: r8169 sets MRRS to 4096, which limits 9000-byte frames to 7.0 Gbit/s (UDP, iperf3 to an ixgbe peer). At 2048 it reaches 7.9, at 1024, 512 or 256 the full 9.93 Gbit/s; at MTU 1500 TCP Tx goes from 9.1 to 9.4 Gbit/s and UDP Tx from 7.9 to 9.5. Set no_inc_mrrs on the T8152 host bridge so devices keep the 512-byte reset value and drivers cannot raise it. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- drivers/pci/controller/pcie-apple.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 3173186c852098..a378955bb922cd 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -224,6 +224,12 @@ struct hw_info { * lane PIPE reset status, then release PORT_T8152_PIPE_RST. */ bool pipe_rst; + /* + * Keep endpoints at their reset Max_Read_Request_Size (512 bytes). + * On T8152 an RTL8127 at MRRS 4096 (what r8169 asks for) transmits + * 9000-byte frames at 7.0 Gbit/s; at 512 it reaches 9.93. + */ + bool no_inc_mrrs; }; static const struct hw_info t8103_hw = { @@ -279,6 +285,7 @@ static const struct hw_info t8152_hw = { .max_rid2sid = 512, .refbuf_off = true, .pipe_rst = true, + .no_inc_mrrs = true, }; static const struct hw_info t8103_pciec_hw = { @@ -3116,6 +3123,7 @@ static int apple_pcie_probe(struct platform_device *pdev) pcie = pci_host_bridge_priv(bridge); pcie->dev = dev; pcie->hw = hw; + bridge->no_inc_mrrs = hw->no_inc_mrrs; if (of_property_present(dev->of_node, "apple,managed-sids")) { u32 ids[15]; int count = of_property_count_u32_elems(dev->of_node, "apple,managed-sids"); From 1ef5ecd7bc670f4a678d4698e36ae8a017da7552 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 24 Oct 2026 14:58:10 +0200 Subject: [PATCH 0030/1514] arm64: dts: apple: j873: apcie port 2 with the on-board 10GbE NIC Describe apcie port 2 next to port 0 (N1): its DART (dart-apcie2), the port with PERST# on AP GPIO 5 and its INTx controller and bus range like the other Apple root ports, and the NIC (MAC address filled in by the loader). The ADT names an aqc107 there; the device has PCI ID 10ec:8127 and is driven by r8169. pcie-apple brings the port up with the T602x port layout plus two steps from macOS: clear PHY_LANE_CFG bit 4 in the refclk handshake (AppleT8152PCIePort::_initializeRefclkBuffer), and after PERST# wait for the lane PIPE reset status (port 0xa8) and clear port 0x82c bit 16 (APCIECoreRCGen5Port::enablePortHardware). The loader must first ungate the AUS5 PHY and write lane-cfg to RC reg 4. Link: Gen3 x1, 10Gbps. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, where the T8152 hw entry, both macOS steps, the AP GPIO controller and port 0 (N1) already exist: only the device tree part remains, in t8152-j873-ethernet.dtsi, squashed with the original follow-up that describes the port per the binding, and the subject changed to match. Port 2 is bus 2 (RID 0x200 to dart-apcie2 stream 1), and the per-port interrupts are listed up to port 2. A port 2 setup failure (lanes stuck in PIPE reset, for example) fails the whole host, port 0 included, so the aura loader's j873_pcie_prep() (PHY tunables, AUS5 ungate, lane-cfg, dart-apcie0/2 tunables) must run before Linux starts. At runtime the NIC identifies as RTL8125CP (XID 0x708).] Signed-off-by: Acelogic --- .../boot/dts/apple/t8152-j873-ethernet.dtsi | 67 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 68 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi new file mode 100644 index 00000000000000..a2350ed7bee4ee --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g internal PCIe (apcie) port 2: the on-board 10GbE NIC (ADT + * /arm-io/apcie/pci-bridge2/lan0; the ADT names an aqc107, the device has + * PCI ID 10ec:8127 and identifies as a Realtek RTL8125CP, XID 0x708). + * iBoot leaves the APCIE power domains on and + * the root complex enabled, but the AUS5 PHY gated and the lanes assigned + * to port 0; the loader ungates the PHY, writes the ADT lane-cfg and applies + * the dart-apcie2 tunables first. Port setup follows the T602x/T8122 + * register layout. Port 0 (N1) is bus 1, port 2 is bus 2. + * Resources are from the 26A434 ADT: apcie, dart-apcie2, gpio0. + */ +#include + +/ { + soc { + pcie2_dart: iommu@38a000000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x8a000000 0x0 0xc000>; + #iommu-cells = <1>; + interrupts = ; + }; + }; +}; + +&pcie { + reg = <0x1c 0xb0000000 0x0 0x1000000>, /* config */ + <0x3 0x8c000000 0x0 0x4000>, /* rc */ + <0x3 0x88028000 0x0 0x4000>, /* port0 */ + <0x3 0x8f010000 0x0 0x4000>, /* phy0 */ + <0x3 0x8a028000 0x0 0x4000>, /* port2 */ + <0x3 0x8f018000 0x0 0x4000>; /* phy2 */ + reg-names = "config", "rc", "port0", "phy0", "port2", "phy2"; + /* One per root port, indexed by the port number. */ + interrupts = , + , + ; + iommu-map = <0x100 &pcie0_dart 1 1>, + <0x101 &pcie0_dart 2 1>, + <0x102 &pcie0_dart 3 1>, + <0x200 &pcie2_dart 1 1>; + bus-range = <0 7>; + + port02: pci@2,0 { + device_type = "pci"; + reg = <0x1000 0x0 0x0 0x0 0x0>; + reset-gpios = <&pinctrl_ap 5 GPIO_ACTIVE_LOW>; + bus-range = <2 2>; + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port02 0 0 0 0>, + <0 0 0 2 &port02 0 0 0 1>, + <0 0 0 3 &port02 0 0 0 2>, + <0 0 0 4 &port02 0 0 0 3>; + + ethernet0: ethernet@0,0 { + reg = <0x20000 0x0 0x0 0x0 0x0>; + /* Filled in by the loader from the ADT. */ + local-mac-address = [00 00 00 00 00 00]; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index ac38151e0acb00..67c7c9c0d4f448 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -288,3 +288,4 @@ #include "t8152-j873-qspi.dtsi" #include "t8152-j873-nvme.dtsi" #include "t8152-j873-usb.dtsi" +#include "t8152-j873-ethernet.dtsi" From cef0a05d16eccf6b7f4394d66f4666953eb7b6e8 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 22:53:27 +0100 Subject: [PATCH 0031/1514] arm64: dts: apple: j873: ethernet0 alias Boot loaders (m1n1, aura) fill in the on-board NIC's MAC address through the ethernet0 alias, as on the other Apple machines. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the alias goes into t8152-j873-ethernet.dtsi.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi index a2350ed7bee4ee..66965f04af13db 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi @@ -13,6 +13,10 @@ #include / { + aliases { + ethernet0 = ðernet0; + }; + soc { pcie2_dart: iommu@38a000000 { compatible = "apple,t8152-dart", "apple,t8110-dart"; From 4d0152993810f42ce8b172ec5484ce2397ce4d15 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:19:57 +0100 Subject: [PATCH 0032/1514] dt-bindings: watchdog: apple,wdt: Add T8152 compatible The T8152 (M6) watchdog is compatible with the T8103 one. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/watchdog/apple,wdt.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml index 00b0f2ec2bdb44..0a21eb27ad0834 100644 --- a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml +++ b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml @@ -24,6 +24,7 @@ properties: - apple,t8122-wdt - apple,t8132-wdt - apple,t8140-wdt + - apple,t8152-wdt - const: apple,t8103-wdt - items: - enum: From c9eeda6528376098cc38f3c5ad4cb3ee41c7a0a1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:19:57 +0100 Subject: [PATCH 0033/1514] dt-bindings: spmi: apple,spmi: Add T8152 compatible The T8152 (M6) SPMI controller is a fourth generation with its FIFO registers moved to 0x200, so it is not compatible with the T8103 one. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, which already describes the gen-4 T8142 controller and drives its layout: T8152 takes an apple,t8142-spmi fallback instead of a driver match of its own.] Signed-off-by: Acelogic --- Documentation/devicetree/bindings/spmi/apple,spmi.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml index ac2e7407ef780c..e504ed9a8871a2 100644 --- a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml +++ b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml @@ -38,6 +38,11 @@ properties: - apple,t8132-spmi - apple,t8140-spmi - const: apple,t8103-spmi + - description: + The gen-4 controller of T8152, with its FIFO registers at 0x200. + items: + - const: apple,t8152-spmi + - const: apple,t8142-spmi reg: minItems: 1 From 8c011c1b0d126d784645a3a7f737e614b43df44c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:19:57 +0100 Subject: [PATCH 0034/1514] dt-bindings: nvmem: apple,spmi-nvmem: Add woodcote PMIC The primary PMU of T8152 (M6) machines is "woodcote" (ADT pmu-main), with the boot flags in the same scratchpad layout as the other Apple PMICs. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml index fe8b2001f4fa56..4a2ba5158b0f64 100644 --- a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml +++ b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml @@ -28,6 +28,7 @@ properties: - apple,simetra-pmic - apple,stowe-pmic - apple,vale-pmic + - apple,woodcote-pmic - const: apple,spmi-nvmem reg: From 5ba4dea4e64d6eeed57f7409999f37a87e10e976 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 14:56:45 +0100 Subject: [PATCH 0035/1514] mfd: macsmc: register macsmc-reboot on T8152 T8152 registers only macsmc-hwmon. The reboot function only writes the MBSE key, and key writes already work on this SMC. Register macsmc-reboot as well; notifications, GPIO and the power supply stay unregistered. On a J873 (Mac mini M6), reboot then sends MBSE = rest, then phra, and the machine restarts with the boot chime; poweroff sends offw, then off1, and it switches off. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, whose T8152 hwmon leaves fan control to the firmware: its fan keys are read-only unless the unsafe fan_control parameter is set (in the original, macsmc-hwmon drove the fan through F0md/F0Tg), and the comment says so. The reboot and power off test above was on Thomas Glanzmann's original J873 series.] Signed-off-by: Acelogic --- drivers/mfd/macsmc.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 546e5cdbb72add..2050127a98c573 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -63,9 +63,15 @@ static const struct mfd_cell apple_smc_devs[] = { static const struct mfd_cell apple_smc_low_gpio_dev = MFD_CELL_OF("macsmc-low-gpio", NULL, NULL, 0, 0, "apple,smc-low-gpio"); -/* T8152 currently exposes read-only telemetry; firmware owns fan control. */ +/* + * T8152: temperatures and fans (hwmon; the fan keys are read-only unless the + * unsafe fan_control parameter is set) and power off/restart (reboot, which + * only writes the MBSE key). Notifications, GPIO and the power supply are not + * qualified there yet. + */ static const struct mfd_cell apple_smc_telemetry_devs[] = { MFD_CELL_OF("macsmc-hwmon", NULL, NULL, 0, 0, "apple,smc-hwmon"), + MFD_CELL_OF("macsmc-reboot", NULL, NULL, 0, 0, "apple,smc-reboot"), }; static void apple_smc_read_sram(struct apple_smc *smc, void *buf, size_t size) @@ -546,7 +552,7 @@ static int apple_smc_probe(struct platform_device *pdev) return dev_err_probe(smc->dev, ret, "Failed to get key count"); smc->key_count = be32_to_cpu(count); - /* Notifications, GPIO and power management are not qualified on T8152. */ + /* T8152: key reads and writes are qualified; notifications and GPIO are not. */ if (of_device_is_compatible(dev->of_node, "apple,t8152-smc")) return devm_mfd_add_devices(smc->dev, PLATFORM_DEVID_NONE, apple_smc_telemetry_devs, From 0c2a84ea8f8df23b8318f8b491ac94c0407a482e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 14:56:45 +0100 Subject: [PATCH 0036/1514] arm64: dts: apple: j873: SMC power off/restart and the watchdog Describe the SMC reboot function (apple,smc-reboot) and the watchdog (ADT /arm-io/wdt, wdt,t8152, IRQ 447), with a 24 MHz clkref (the ADT timebase-frequency) as on T8103. The PMU NVMEM boot flags are not described yet; macsmc-reboot treats them as optional. The watchdog registers at 24 MHz and provides /dev/watchdog and a restart fallback. Signed-off-by: Thomas Glanzmann [Acelogic: the nodes use the labels of t8152-j873g.dts.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873g.dts | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 67c7c9c0d4f448..36c14293fb6db5 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -205,6 +205,15 @@ opp-level = <3>; }; }; + + /* The 24 MHz timebase (ADT timebase-frequency), as on T8103. */ + clkref: clock-ref { + compatible = "fixed-clock"; + #clock-cells = <0>; + clock-frequency = <24000000>; + clock-output-names = "clkref"; + }; + timer { compatible = "arm,armv8-timer"; interrupts = , @@ -241,6 +250,14 @@ #performance-domain-cells = <0>; }; + /* ADT /arm-io/wdt (wdt,t8152): restart fallback and /dev/watchdog. */ + wdt: watchdog@3082b0000 { + compatible = "apple,t8152-wdt", "apple,t8103-wdt"; + reg = <3 0x082b0000 0 0x4000>; + clocks = <&clkref>; + interrupts = ; + }; + smc_mbox: mailbox@30c710080 { compatible = "apple,t8152-smc-mailbox"; reg = <3 0x0c710080 0 0x80>; @@ -257,6 +274,15 @@ reg-names = "smc", "sram"; mboxes = <&smc_mbox>; + /* + * Power off (MBSE = off1) and restart (MBSE = phra). The + * PMU NVMEM boot flags are not described yet; the driver + * treats them as optional. + */ + smc_reboot: reboot { + compatible = "apple,smc-reboot"; + }; + hwmon { compatible = "apple,smc-hwmon"; apple,discover-temperatures; From 6061934c7964cea3f15b6c06498e511d847abfa3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 15:11:45 +0100 Subject: [PATCH 0037/1514] arm64: dts: apple: j873: PMU boot flags on SPMI for power off 'off1' only keeps the machine off when the PMU shutdown flag is set; without it the J873 powered back on into m1n1 at once. Describe nub-spmi0 (gen 4, 0x308714000, 16 KiB) and its primary PMU (pmu-main, "woodcote", slave 0xe) as an apple,spmi-nvmem with the boot flags in its legacy scratchpad (ADT info-leg_scrpad = 0xf800, laid out as on T8103 and T8140): boot_stage 0xf801 (read 0x30, kernel started), boot_error_count and panic_count 0xf802, shutdown_flag 0xf80f bit 3. Hand them to macsmc-reboot. Tested: poweroff now leaves the Mac mini off; reboot still restarts. Signed-off-by: Thomas Glanzmann [Acelogic: the controller takes the apple,t8142-spmi fallback of the aurora-wip binding.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873g.dts | 59 +++++++++++++++++++++-- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 36c14293fb6db5..180b435f1d9695 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -10,6 +10,7 @@ #include #include +#include / { compatible = "apple,j873g", "apple,t8152", "apple,arm-platform"; @@ -250,6 +251,54 @@ #performance-domain-cells = <0>; }; + /* + * ADT /arm-io/nub-spmi0 (gen 4) and its primary PMU, pmu-main + * ("woodcote", slave 0xe). The boot flags live in the legacy + * scratchpad (info-leg_scrpad = 0xf800), laid out as on T8103 + * and T8140; boot_stage read 0x30 (kernel started) here. + */ + nub_spmi0: spmi@308714000 { + /* + * Gen 4: FIFO registers at 0x200 (the block is 0x4000 + * long); polled, so no interrupts are described yet. + */ + compatible = "apple,t8152-spmi", "apple,t8142-spmi"; + reg = <0x3 0x08714000 0x0 0x4000>; + #address-cells = <2>; + #size-cells = <0>; + + pmic@e { + compatible = "apple,woodcote-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + + nvmem-layout { + compatible = "fixed-layout"; + #address-cells = <1>; + #size-cells = <1>; + + boot_stage: boot-stage@f801 { + reg = <0xf801 0x1>; + }; + + boot_error_count: boot-error-count@f802,0 { + reg = <0xf802 0x1>; + bits = <0 4>; + }; + + panic_count: panic-count@f802,4 { + reg = <0xf802 0x1>; + bits = <4 4>; + }; + + /* Set before off1, or the machine powers back on. */ + shutdown_flag: shutdown-flag@f80f,3 { + reg = <0xf80f 0x1>; + bits = <3 1>; + }; + }; + }; + }; + /* ADT /arm-io/wdt (wdt,t8152): restart fallback and /dev/watchdog. */ wdt: watchdog@3082b0000 { compatible = "apple,t8152-wdt", "apple,t8103-wdt"; @@ -274,13 +323,13 @@ reg-names = "smc", "sram"; mboxes = <&smc_mbox>; - /* - * Power off (MBSE = off1) and restart (MBSE = phra). The - * PMU NVMEM boot flags are not described yet; the driver - * treats them as optional. - */ + /* Power off (MBSE = off1) and restart (MBSE = phra). */ smc_reboot: reboot { compatible = "apple,smc-reboot"; + nvmem-cells = <&shutdown_flag>, <&boot_stage>, + <&boot_error_count>, <&panic_count>; + nvmem-cell-names = "shutdown_flag", "boot_stage", + "boot_error_count", "panic_count"; }; hwmon { From edd345ad332ce915af32cbb99ae537c50e635fbf Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:53 +0100 Subject: [PATCH 0038/1514] dt-bindings: arm: apple: apple,pmgr: Add T8152 compatible The T8152 (M6) PMGR blocks are compatible with the T8103 ones. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml b/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml index 5d9f55c3e5899a..b059430cee63dd 100644 --- a/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml +++ b/Documentation/devicetree/bindings/arm/apple/apple,pmgr.yaml @@ -45,6 +45,7 @@ properties: - apple,t8132-pmgr - apple,t8140-pmgr - apple,t8142-pmgr + - apple,t8152-pmgr - const: apple,t8103-pmgr - const: syscon - const: simple-mfd From 2c943f48e8d467f0f8119f61fcdddae8c2270fb0 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:53 +0100 Subject: [PATCH 0039/1514] dt-bindings: power: apple,pmgr-pwrstate: Add T8152 compatible The T8152 (M6) PMGR power state registers are compatible with the T8103 ones. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml index 1c3bd5a5b5d2cb..eeaf5f20827f94 100644 --- a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml @@ -69,6 +69,7 @@ properties: - apple,t8132-pmgr-pwrstate - apple,t8140-pmgr-pwrstate - apple,t8142-pmgr-pwrstate + - apple,t8152-pmgr-pwrstate - const: apple,t8103-pmgr-pwrstate reg: From 5e49fec7858a20e35fcf5c9c335c265aecec3513 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:54 +0100 Subject: [PATCH 0040/1514] dt-bindings: i2c: apple,i2c: Add T8152 compatible The T8152 (M6) I2C controllers are compatible with the T8103 ones. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/i2c/apple,i2c.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/i2c/apple,i2c.yaml b/Documentation/devicetree/bindings/i2c/apple,i2c.yaml index 5c827af153cb56..f117341886ca5f 100644 --- a/Documentation/devicetree/bindings/i2c/apple,i2c.yaml +++ b/Documentation/devicetree/bindings/i2c/apple,i2c.yaml @@ -30,6 +30,7 @@ properties: - apple,t8122-i2c - apple,t8132-i2c - apple,t8140-i2c + - apple,t8152-i2c - const: apple,t8103-i2c - items: - enum: From 523a1caa53ea200de6bdd23aebf912d8149f26af Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:53 +0100 Subject: [PATCH 0041/1514] dt-bindings: mailbox: apple,mailbox: Add T8152 ASC wrapper mailbox The T8152 (M6) SMC and AOP mailboxes are ASC wrapper v8 instances, described with two interrupts (send-empty, recv-not-empty) like the T8140 AOP setup port, but without an IOMMU or DMA window. Add apple,t8152-ascwrap-v8-mailbox and split the conditions into interrupt layout and setup-port resources. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, where the SMC mailbox already has its own apple,t8152-smc-mailbox compatible with this interrupt layout: the new compatible is described for the AOP mailbox and joins that interrupt condition. The T8140 setup-port conditions are unchanged.] Signed-off-by: Acelogic --- .../devicetree/bindings/mailbox/apple,mailbox.yaml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 1a40e2e38786b8..5c112f77a53a2b 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -27,6 +27,12 @@ properties: masking provided by the interrupt controller. const: apple,t8152-smc-mailbox + - description: + T8152 ASC wrapper (v8) mailbox of the AOP, with the counted + FIFOs of the SMC mailbox, described with its send-empty and + recv-not-empty interrupts. + const: apple,t8152-ascwrap-v8-mailbox + - description: ASC mailboxes are the most common variant found on the M1 used for example for the display controller, the system management @@ -142,7 +148,9 @@ allOf: properties: compatible: contains: - const: apple,t8152-smc-mailbox + enum: + - apple,t8152-ascwrap-v8-mailbox + - apple,t8152-smc-mailbox then: properties: interrupts: @@ -215,6 +223,8 @@ allOf: - apple,t6021-ane-mailbox - apple,t8112-ane-mailbox - apple,t8140-aop-setup-mailbox + - apple,t8152-ans-mailbox + - apple,t8152-ascwrap-v8-mailbox - apple,t8152-smc-mailbox then: properties: From d237a9aa748912da5ce1d383decb585bf2639026 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:44:53 +0100 Subject: [PATCH 0042/1514] dt-bindings: dma: apple,admac: Add T8152 compatible The T8152 (M6) ADMAC (ADT admac-evolution,t8152) has its own register layout, so it is not compatible with the earlier ones. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- Documentation/devicetree/bindings/dma/apple,admac.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/dma/apple,admac.yaml b/Documentation/devicetree/bindings/dma/apple,admac.yaml index 64d80cd5f4bcdf..17e3f37e673c5d 100644 --- a/Documentation/devicetree/bindings/dma/apple,admac.yaml +++ b/Documentation/devicetree/bindings/dma/apple,admac.yaml @@ -44,6 +44,7 @@ properties: - items: - const: apple,t6041-admac - const: apple,t8132-admac + - const: apple,t8152-admac reg: maxItems: 1 From f1ce875e034a3449bf08a60b2e29729f6826c738 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 21:16:37 +0100 Subject: [PATCH 0043/1514] dt-bindings: iommu: apple,dart: add apple,retain-translation On T8152 iBoot hands dart-sbr over translating for the AOP and the audio ADMAC without setting the lock bit, and the AOP firmware keeps using the inherited mappings. Describe the property that tells the OS to inherit such a DART instead of resetting it, and who owns which root entries. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- .../devicetree/bindings/iommu/apple,dart.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index 514b17641bf5ba..9968b519a6db78 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -169,6 +169,17 @@ properties: and filtering state without a separate page-table root. Source and destination must differ, and both must exist on the controller. + apple,retain-translation: + type: boolean + description: > + The bootloader hands this DART over translating, with stream page + tables that a co-processor's firmware keeps using, but without setting + the hardware lock. The operating system then treats the DART as locked: + it does not reset it or replace the inherited stream roots, adds its + own mappings only in root entries that are empty at handoff, and on + detach clears only the entries it added. The entries present at handoff + stay owned by the firmware, which may keep using them at any time. + required: - compatible - reg From 76188ec353b94e2274566d0f736954897d8c54a9 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sat, 7 Nov 2026 21:53:37 -0500 Subject: [PATCH 0044/1514] soc: apple: mailbox: match the T8152 AOP ASC wrapper mailbox The T8152 AOP mailbox (ADT aop, iop,ascwrap-v8, mailbox 0 of the bank at 0x310740000) is the same counted FIFO as the SMC mailbox, with the same send-empty and recv-not-empty interrupts. Match apple,t8152-ascwrap-v8-mailbox, the compatible of the J873 AOP mailbox node, to the SMC mailbox layout. Signed-off-by: Acelogic --- drivers/soc/apple/mailbox.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 8e864229d5efe1..4f39be303968aa 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -1764,6 +1764,8 @@ static const struct apple_mbox_hw apple_mbox_t8152_ans_hw = { static const struct of_device_id apple_mbox_of_match[] = { { .compatible = "apple,t8152-smc-mailbox", .data = &apple_mbox_t8152_smc_hw }, + /* The AOP's ASC wrapper mailbox has the SMC mailbox's counted FIFOs. */ + { .compatible = "apple,t8152-ascwrap-v8-mailbox", .data = &apple_mbox_t8152_smc_hw }, { .compatible = "apple,t8152-ans-mailbox", .data = &apple_mbox_t8152_ans_hw }, { .compatible = "apple,t6031-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8122-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, From 613be379ab9198402eecc007409a65e6c29fad81 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:31 +0100 Subject: [PATCH 0045/1514] iommu: apple-dart: inherit an unlocked bootloader translation on request On T8152 iBoot leaves dart-sbr translating for the AOP and the audio ADMAC: streams 0, 1 and 42 have live page tables, and the firmware's own mappings sit in root slot 16 of each. Unlike the DARTs SPTM locks, the lock bit is not set, so the driver would reset the DART and pull the tables out from under the AOP firmware. With apple,retain-translation the DART is treated as locked: the inherited roots are kept and Linux publishes its mappings into vacant root slots. Signed-off-by: Thomas Glanzmann Signed-off-by: Acelogic --- drivers/iommu/apple-dart.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index d39ee78d9d73c5..94c79671db6fda 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -3976,6 +3976,14 @@ static irqreturn_t apple_dart_irq(int irq, void *dev) static bool apple_dart_is_locked(struct apple_dart *dart) { + /* + * apple,retain-translation: the bootloader left live stream tables + * that a co-processor's firmware depends on, but did not set the lock + * bit (T8152 dart-sbr: AOP and audio ADMAC streams). Treat it as + * locked so the tables are inherited rather than reset. + */ + if (of_property_read_bool(dart->dev->of_node, "apple,retain-translation")) + return true; return !!(apple_dart_readl(dart, dart->hw->lock) & dart->hw->lock_bit); } From 5bef582af4beafab3bd4c02e85ec133253f0111c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:31 +0100 Subject: [PATCH 0046/1514] dmaengine: apple-admac: support the T8152 layout The T8152 ADMAC (ADT admac-evolution,t8152; worked out from the macOS AudioDMAController-T8152 driver and on hardware) keeps the per-channel register block and the global start/stop/interrupt registers, but: - the channel blocks are 0x4000 apart, TX n at 0x40000 + 0x4000 n and RX n at 0x80000 + 0x4000 n; - a channel is put in state 2 (+0x30 bits 3:0) and +0x4 is written 0x029b0000 before it is started, as macOS does; - the last descriptor word carries a descriptor id 1..255 in its low byte, which macOS never leaves at 0; - the SRAM size registers carry the channel count in bits 31:24, and the AP's carveouts start above the firmware's (base 0x1000, 1 KiB blocks); - only the word size is set in the bus width register. The descriptor and report FIFO ports are the legacy ones: the RX descriptor port answers at 0x14000 + 4n, not at the 0x10040 + 4n the ADT lists. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the descriptor id is set in admac_write_hw_desc(), which writes every descriptor there, the SRAM carveout bounds combine with the T8132 split-channel handling, and the state register is the +0x30 one that aurora-wip programs as REG_CHAN_BURST on T8132.] Signed-off-by: Acelogic --- drivers/dma/apple-admac.c | 80 +++++++++++++++++++++++++++++++++++---- 1 file changed, 72 insertions(+), 8 deletions(-) diff --git a/drivers/dma/apple-admac.c b/drivers/dma/apple-admac.c index 60b8c045306340..bdafb0ff4aecb5 100644 --- a/drivers/dma/apple-admac.c +++ b/drivers/dma/apple-admac.c @@ -70,13 +70,29 @@ */ #define REG_CHAN_BASE_LEGACY(ch) (0x8000 + (ch) * 0x200) #define REG_CHAN_BASE_EVOLVED(ch) (((ch) & 1 ? 0xc000 : 0x8000) + ((ch) / 2) * 0x200) -#define REG_CHAN_BASE(ad, ch) ((ad)->evolved_layout ? \ +/* + * T8152 (ADT admac-evolution,t8152; the macOS AudioDMAController-T8152 + * driver): the same per-channel block, 0x4000 apart, TX at 0x40000 and RX + * at 0x80000, and a channel has to be put in state 2 (+0x30 bits 3:0) + * before it is started. The descriptor and report FIFO ports are the legacy + * ones (the RX descriptor port answers at 0x14000 + 4n, not at the ADT's + * 0x10040 + 4n). + */ +#define REG_CHAN_BASE_T8152(ch) (((ch) & 1 ? 0x80000 : 0x40000) + ((ch) / 2) * 0x4000) +#define REG_CHAN_BASE(ad, ch) ((ad)->t8152_layout ? REG_CHAN_BASE_T8152(ch) : \ + (ad)->evolved_layout ? \ REG_CHAN_BASE_EVOLVED(ch) : REG_CHAN_BASE_LEGACY(ch)) #define REG_CHAN_CTL(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x00) #define REG_CHAN_CTL_RST_RINGS BIT(0) #define REG_CHAN_CONFIG(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x04) +/* macOS writes this for the T8152 base-ns channels before every start */ +#define CHAN_CONFIG_T8152 0x029b0000 #define REG_CHAN_BURST(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x30) +/* T8152: the low nibble of the same register is the channel state */ +#define REG_CHAN_STATE(ad, ch) REG_CHAN_BURST(ad, ch) +#define CHAN_STATE_MASK GENMASK(3, 0) +#define CHAN_STATE_READY 2 #define REG_DESC_RING(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x70) #define REG_REPORT_RING(ad, ch) (REG_CHAN_BASE(ad, ch) + 0x74) @@ -104,6 +120,11 @@ #define REG_DESC_WRITE(ch) (0x10000 + ((ch) / 2) * 0x4 + ((ch) & 1) * 0x4000) #define REG_REPORT_READ(ch) (0x10100 + ((ch) / 2) * 0x4 + ((ch) & 1) * 0x4000) +/* T8152: the AP's share of each SRAM pool starts above the firmware's. */ +#define T8152_SRAM_BASE 0x1000 +#define T8152_SRAM_BLOCK 1024 +#define SRAM_SIZE_MASK GENMASK(15, 0) + #define REG_TX_INTSTATE(idx) (0x0030 + (idx) * 4) #define REG_RX_INTSTATE(idx) (0x0040 + (idx) * 4) #define REG_GLOBAL_INTSTATE(idx) (0x0050 + (idx) * 4) @@ -124,6 +145,8 @@ struct admac_chan { struct tasklet_struct tasklet; u32 carveout; + /* T8152: transfer descriptor id, 1..255 */ + u8 desc_id; spinlock_t lock; struct admac_tx *current_tx; @@ -164,6 +187,7 @@ struct admac_data { bool set_unk28; bool evolved_layout; bool split_channels; + bool t8152_layout; bool ctl_programmed; int irq; int irq_index; @@ -193,6 +217,7 @@ struct admac_hw { bool set_unk28; bool evolved_layout; bool split_channels; + bool t8152_layout; }; static int admac_alloc_sram_carveout(struct admac_data *ad, @@ -201,6 +226,8 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, { struct admac_sram *sram; int i, ret = 0, nblocks; + u32 first = 0, block = SRAM_BLOCK; + ad->txcache.size = readl_relaxed(ad->base + REG_TX_SRAM_SIZE); ad->rxcache.size = readl_relaxed(ad->base + REG_RX_SRAM_SIZE); /* T8132 reports channel metadata in the upper half of these words. */ @@ -208,6 +235,13 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, ad->txcache.size &= GENMASK(15, 0); ad->rxcache.size &= GENMASK(15, 0); } + if (ad->t8152_layout) { + /* bits 31:24 are the channel count */ + ad->txcache.size &= SRAM_SIZE_MASK; + ad->rxcache.size &= SRAM_SIZE_MASK; + first = T8152_SRAM_BASE; + block = T8152_SRAM_BLOCK; + } if (dir == DMA_MEM_TO_DEV) sram = &ad->txcache; @@ -216,14 +250,14 @@ static int admac_alloc_sram_carveout(struct admac_data *ad, mutex_lock(&ad->cache_alloc_lock); - nblocks = sram->size / SRAM_BLOCK; + nblocks = sram->size > first ? (sram->size - first) / block : 0; for (i = ad->split_channels ? 1 : 0; i < nblocks; i++) if (!(sram->allocated & BIT(i))) break; if (i < nblocks) { - *out = FIELD_PREP(CHAN_SRAM_CARVEOUT_BASE, i * SRAM_BLOCK) | - FIELD_PREP(CHAN_SRAM_CARVEOUT_SIZE, SRAM_BLOCK); + *out = FIELD_PREP(CHAN_SRAM_CARVEOUT_BASE, first + i * block) | + FIELD_PREP(CHAN_SRAM_CARVEOUT_SIZE, block); sram->allocated |= BIT(i); } else { ret = -EBUSY; @@ -240,18 +274,24 @@ static void admac_free_sram_carveout(struct admac_data *ad, { struct admac_sram *sram; u32 base = FIELD_GET(CHAN_SRAM_CARVEOUT_BASE, carveout); + u32 first = 0, block = SRAM_BLOCK; int i; + if (ad->t8152_layout) { + first = T8152_SRAM_BASE; + block = T8152_SRAM_BLOCK; + } + if (dir == DMA_MEM_TO_DEV) sram = &ad->txcache; else sram = &ad->rxcache; - if (WARN_ON(base >= sram->size)) + if (WARN_ON(base < first || base >= sram->size)) return; mutex_lock(&ad->cache_alloc_lock); - i = base / SRAM_BLOCK; + i = (base - first) / block; sram->allocated &= ~BIT(i); mutex_unlock(&ad->cache_alloc_lock); } @@ -354,7 +394,19 @@ static void admac_write_hw_desc(struct admac_data *ad, int channo, writel_relaxed(lower_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); writel_relaxed(upper_32_bits(addr), ad->base + REG_DESC_WRITE(channo)); writel_relaxed(len, ad->base + REG_DESC_WRITE(channo)); - writel_relaxed(FLAG_DESC_NOTIFY, ad->base + REG_DESC_WRITE(channo)); + if (ad->t8152_layout) { + /* + * T8152: the low byte of the last word is a descriptor id, + * which macOS counts 1..255 and never leaves at 0. + */ + struct admac_chan *adchan = &ad->channels[channo]; + + adchan->desc_id = adchan->desc_id == 255 ? 1 : adchan->desc_id + 1; + writel_relaxed(FLAG_DESC_NOTIFY | adchan->desc_id, + ad->base + REG_DESC_WRITE(channo)); + } else { + writel_relaxed(FLAG_DESC_NOTIFY, ad->base + REG_DESC_WRITE(channo)); + } } /* @@ -570,6 +622,11 @@ static void admac_start_chan(struct admac_chan *adchan) ad->base + REG_CHAN_INTSTATUS(ad, adchan->no, ad->irq_index)); writel_relaxed(STATUS_DESC_DONE | STATUS_ERR, ad->base + REG_CHAN_INTMASK(ad, adchan->no, ad->irq_index)); + if (ad->t8152_layout) { + writel_relaxed(CHAN_CONFIG_T8152, ad->base + REG_CHAN_CONFIG(ad, adchan->no)); + admac_modify(ad, REG_CHAN_STATE(ad, adchan->no), CHAN_STATE_MASK, + CHAN_STATE_READY); + } switch (admac_chan_direction(adchan->no)) { case DMA_MEM_TO_DEV: @@ -1091,7 +1148,8 @@ static int admac_device_config(struct dma_chan *chan, * of words position in a frame. That's where the importance of this control * comes from. */ - switch (is_tx ? config->dst_port_window_size : config->src_port_window_size) { + switch (ad->t8152_layout ? 0 : + is_tx ? config->dst_port_window_size : config->src_port_window_size) { case 0 ... 1: break; case 2: @@ -1202,6 +1260,7 @@ static int admac_probe(struct platform_device *pdev) ad->set_unk28 = hw->set_unk28; ad->evolved_layout = hw->evolved_layout; ad->split_channels = hw->split_channels; + ad->t8152_layout = hw->t8152_layout; mutex_init(&ad->cache_alloc_lock); /* @@ -1353,7 +1412,12 @@ static const struct admac_hw admac_t8140_hw = { .evolved_layout = true, }; +static const struct admac_hw admac_t8152_hw = { + .t8152_layout = true, +}; + static const struct of_device_id admac_of_match[] = { + { .compatible = "apple,t8152-admac", .data = &admac_t8152_hw }, { .compatible = "apple,t8140-admac", .data = &admac_t8140_hw }, { .compatible = "apple,t8132-admac", .data = &admac_t8132_hw }, { .compatible = "apple,t8122-admac", .data = &admac_t8122_hw }, From dd923f2443834d36260286aeb9c27355db9aae05 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 20:17:32 +0100 Subject: [PATCH 0047/1514] arm64: dts: apple: j873: audio Describe the J873 (Mac mini M6) audio: the AOP (mailbox 0x310740080, firmware started by Linux), dart-sbr (shared with the PMP; apple,retain-translation for the firmware's tables), the base-ns ADMAC, the AOP audio node with its DMA channels and MCA power leaves, the I2C1/I2C3 power states and buses with the CS42L84 jack codec and the SN012776 speaker amp (ti,bclk-ratio = <250>), and the macaudio card. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip: the nodes go into t8152-j873-audio.dtsi, which t8152-j873g.dts includes. There is no PMP device tree here, so dart-sbr is described directly (as an apple,t8152-dart with apple,t8110-dart fallback, like the other J873 DARTs), and the I2C power states join the PMGR node that t8152-j873-qspi.dtsi already describes. The speaker stays off by default: the J873 macaudio configuration does not admit it.] Signed-off-by: Acelogic --- .../boot/dts/apple/t8152-j873-audio.dtsi | 261 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 262 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi new file mode 100644 index 00000000000000..0ecfd9746beb98 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-audio.dtsi @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g audio: the AOP (always-on processor) owns the audio fabric, as + * on T8140. iBoot loads the AOP firmware (j873gaop) and leaves the CPU + * stopped; Linux starts it. The jack codec (CS42L84) and the speaker amp + * (SN012776) are on AP I2C buses; their data goes through AOP services on + * the base-ns ADMAC. Resources are from the 26A434 ADT: aop, dart-sbr, + * admac-base-ns, iop-audio-controller, i2c1, i2c3, pmgr. + */ +#include + +/ { + soc { + /* + * ADT aop: iop,ascwrap-v8, msgbox-mailbox-num 0, using-alias, + * not post-office: mailbox 0, aperture 1 of the bank at reg[2] + * (0x310740000) = 0x310740080. ADT interrupts [627, 626, 628]; + * the first two in the SMC order (send-empty, recv-not-empty). + */ + aop_mbox: mailbox@310740080 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x10740080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* + * ADT dart-sbr, shared with the PMP: mapper-aop 0, + * mapper-admac-base-ns 42. iBoot leaves streams 0, 1 and 42 + * translating (root slot 16 owned by the firmware) without + * setting the lock bit. + */ + sbr_dart: iommu@318100000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x18100000 0x0 0xc000>; + #iommu-cells = <1>; + interrupts = ; + apple,retain-translation; + }; + + /* + * ADT admac-base-ns (admac-evolution,t8152): 13 TX and 13 RX + * channels, interrupt destination 0, dart-sbr stream 42. + */ + admac_base_ns: dma-controller@313900000 { + compatible = "apple,t8152-admac"; + reg = <0x3 0x13900000 0x0 0xb4000>; + dma-channels = <26>; + interrupts-extended = <&aic AIC_IRQ 640 IRQ_TYPE_LEVEL_HIGH>, + <0>, <0>, <0>; + #dma-cells = <1>; + iommus = <&sbr_dart 42>; + /* slot 17: slot 16 of stream 42 belongs to the firmware */ + apple,dma-range = <0x110 0x0 0x0 0x10000000>; + }; + + /* + * The AOP's PMGR (ADT pmgr devices AUDIO_MCA0_M..AUDIO_MCA5_M at + * 0x308284400 + 0x20 * N). Their parent audio_p is the + * firmware's: it is up while a service is in pw0 or pwrd. + */ + pmgr_aop: power-management@308284000 { + compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", + "syscon", "simple-mfd"; + #address-cells = <1>; + #size-cells = <1>; + reg = <0x3 0x08284000 0x0 0x1000>; + + ps_audio_mca0_m: power-controller@400 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x400 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca0_m"; + }; + + ps_audio_mca1_m: power-controller@420 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x420 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca1_m"; + }; + + ps_audio_mca2_m: power-controller@440 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x440 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca2_m"; + }; + + ps_audio_mca3_m: power-controller@460 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x460 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca3_m"; + }; + + ps_audio_mca4_m: power-controller@480 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x480 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca4_m"; + }; + + ps_audio_mca5_m: power-controller@4a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x4a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "audio_mca5_m"; + }; + }; + + /* ADT i2c1: the CS42L84 jack codec (and the aqc NIC's EEPROM). */ + i2c1: i2c@331014000 { + compatible = "apple,t8152-i2c", "apple,t8103-i2c"; + reg = <0x3 0x31014000 0x0 0x4000>; + clocks = <&clkref>; + interrupts = ; + #address-cells = <1>; + #size-cells = <0>; + power-domains = <&ps_i2c1>; + + /* + * ADT audio-codec-output: function-reset GPIO 0xcc, + * interrupt on gpio0 pin 203. + */ + jack_codec: codec@4b { + compatible = "cirrus,cs42l84"; + reg = <0x4b>; + reset-gpios = <&pinctrl_ap 204 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 203 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + sound-name-prefix = "Jack"; + }; + }; + + /* ADT i2c3: the SN012776 speaker amplifier. */ + i2c3: i2c@33101c000 { + compatible = "apple,t8152-i2c", "apple,t8103-i2c"; + reg = <0x3 0x3101c000 0x0 0x4000>; + clocks = <&clkref>; + interrupts = ; + #address-cells = <1>; + #size-cells = <0>; + power-domains = <&ps_i2c3>; + + /* + * ADT audio-speaker: function-reset GPIO 0xca, interrupt + * on gpio0 pin 193, speaker-config rx_slot 0, + * vsense_slot 0, isense_slot 2. + */ + speaker_amp: codec@38 { + compatible = "ti,sn012776", "ti,tas2764"; + reg = <0x38>; + shutdown-gpios = <&pinctrl_ap 202 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 193 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + ti,imon-slot-no = <2>; + ti,vmon-slot-no = <0>; + /* the AOP's speaker frame: 250 BCLKs at 12 MHz */ + ti,bclk-ratio = <250>; + }; + }; + + aop: aop@310c00000 { + compatible = "apple,t8152-aop"; + reg = <0x3 0x10c00000 0x0 0x1e0000>, + <0x3 0x10600000 0x0 0x4000>; + reg-names = "mmio", "asc"; + mboxes = <&aop_mbox>; + mbox-names = "mbox"; + iommus = <&sbr_dart 0>; + /* slot 17: slot 16 belongs to the firmware */ + apple,dma-range = <0x110 0x0 0x10 0x0>; + + /* + * Bound by name to the firmware's "audio" EPIC service. + * ADT iop-audio-controller: cout/cin on base-ns TX5/RX5, + * spkr on TX1 with its sense data on RX1; Linux ADMAC + * channel = 2 * N for TX N, 2 * N + 1 for RX N. + */ + aop_audio: audio { + compatible = "apple,t8152-aop-audio"; + dmas = <&admac_base_ns 10>, <&admac_base_ns 11>, + <&admac_base_ns 2>, <&admac_base_ns 3>; + dma-names = "cout", "cin", "spkr", "sense"; + power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, + <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, + <&ps_audio_mca4_m>, <&ps_audio_mca5_m>; + power-domain-names = "mca0", "mca1", "mca2", + "mca3", "mca4", "mca5"; + #sound-dai-cells = <1>; + }; + }; + }; + + sound { + compatible = "apple,j873-macaudio", "apple,macaudio"; + model = "Mac mini J873"; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Headphone Jack"; + + cpu { + sound-dai = <&aop_audio 0>; + }; + codec { + sound-dai = <&jack_codec>; + }; + }; + + dai-link@1 { + reg = <1>; + link-name = "Speaker"; + + cpu { + sound-dai = <&aop_audio 3>; + }; + codec { + sound-dai = <&speaker_amp>; + }; + }; + }; +}; + +/* The I2C power states (PMGR, parent SIO_CPU is always on). */ +&pmgr { + ps_i2c1: power-controller@cc0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xcc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c1"; + }; + + ps_i2c3: power-controller@d00 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xd00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c3"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 180b435f1d9695..2da1a88dc8cf18 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -364,3 +364,4 @@ #include "t8152-j873-nvme.dtsi" #include "t8152-j873-usb.dtsi" #include "t8152-j873-ethernet.dtsi" +#include "t8152-j873-audio.dtsi" From bc141c0a6c9bf48786169920cd2f6ddb74e647e5 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 25 Oct 2026 10:31:26 +0100 Subject: [PATCH 0048/1514] arm64: dts: apple: j873: describe the fan target and mode keys The J873 SMC has F0Tg (target, flt) and F0md (mode, ui8; lowercase, unlike the F0Md of other machines). With them macsmc_hwmon exposes fan1_target; with fan_control=1 the fan follows it (2500 -> 2499 RPM within 3 s). In automatic mode the SMC keeps the fan at its 1000 RPM minimum even at 93 C under full load, so the OS has to drive it. Signed-off-by: Thomas Glanzmann [Acelogic: adapted for aurora-wip, whose T8152 hwmon leaves fan control to the firmware: the fan node has no apple,fan-manual-control, so the keys only add a read-only fan1_target. The target becomes writable only with the fan_control module parameter (unsafe, off by default); nothing in the kernel writes F0md or F0Tg by itself.] Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873g.dts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 2da1a88dc8cf18..db37673de92bb7 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -340,6 +340,8 @@ apple,key-id = "F0Ac"; apple,fan-minimum = "F0Mn"; apple,fan-maximum = "F0Mx"; + apple,fan-target = "F0Tg"; + apple,fan-mode = "F0md"; label = "Fan"; }; }; From 6962da594d81907a7a1445db331fa95c322ec5ef Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 8 Nov 2026 02:04:43 -0500 Subject: [PATCH 0049/1514] arm64: dts: apple: j873: leave the USB 2 hosts to a follow-up The J873g USB 2 host nodes describe the back-left (usb-drd1) and front (usb-drd2) controllers as plain "snps,dwc3" with both DART instances in iommus. The generic dwc3 binding allows a single iommu, so these nodes add two dtbs_check warnings. The Apple dwc3 binding, which does allow two DARTs, needs resets, a USB role switch and PHY descriptions that the J873g does not have yet. Return the J873g USB description to the shared, disabled state that aurora-wip has, until the M6 USB controllers can be described properly: - drop t8152-j873-usb.dtsi and its include; - restore aurora-wip's dwc3_1_dart and dwc3_2_dart overrides. The USB 2 hosts worked on the M6 with the earlier description (both xHCI hosts and the front-port hub enumerated), and they will come back in a follow-up together with the binding work. Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 67 ------------------- arch/arm64/boot/dts/apple/t8152-j873g.dts | 17 ++++- 2 files changed, 15 insertions(+), 69 deletions(-) delete mode 100644 arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi deleted file mode 100644 index 5ecd42f9e7135c..00000000000000 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* - * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 - * (front ports via the on-board hub). - * The loader powers the controllers and initialises the eUSB2 PHYs in host - * mode before Linux starts (no PMGR, PHY or Type-C driver yet), so the - * controllers are described as plain DWC3 hosts behind their two DARTs. - * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2. - * - * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and - * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists - * both windows on one node (dwc3_1_dart, dwc3_2_dart), but the DART driver - * drives one instance per node and the binding reads a second reg entry as - * DAPF or auxiliary registers. Keep instance 0 on the shared node, with its - * own window only, and describe instance 1 as a node of its own. - */ - -&dwc3_1_dart { - reg = <0x4 0x0b020000 0x0 0xc000>; - status = "okay"; -}; - -&dwc3_2_dart { - reg = <0x3 0x83020000 0x0 0xc000>; - status = "okay"; -}; - -/ { - soc { - dwc3_1_dart_1: iommu@40b040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x4 0x0b040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - }; - - usb1: usb@40a430000 { - compatible = "snps,dwc3"; - reg = <0x4 0x0a430000 0x0 0xcd00>; - interrupts = ; - dr_mode = "host"; - maximum-speed = "high-speed"; - iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; - snps,dis_u2_susphy_quirk; - snps,dis_u3_susphy_quirk; - }; - - dwc3_2_dart_1: iommu@383040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x3 0x83040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - }; - - /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ - usb2: usb@382430000 { - compatible = "snps,dwc3"; - reg = <0x3 0x82430000 0x0 0xcd00>; - interrupts = ; - dr_mode = "host"; - maximum-speed = "high-speed"; - iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; - snps,dis_u2_susphy_quirk; - snps,dis_u3_susphy_quirk; - }; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 0f98b07748b016..d4900374f1470d 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -372,6 +372,12 @@ <0x4 0x3040000 0x0 0xc000>; }; +/* Retain the register view published by this board's live hardware capture. */ +&dwc3_1_dart { + reg = <0x4 0xb020000 0x0 0xc000>, + <0x4 0xb040000 0x0 0xc000>; +}; + /* Retain the register view published by this board's live hardware capture. */ &dwc3_3_dart { reg = <0x4 0x13020000 0x0 0xc000>, @@ -494,11 +500,18 @@ <0x3 0xa0000000 0x0 0x8000>; }; +/* Unexposed chassis port instances remain described and disabled. */ + +/* Retain the register view published by this board's live hardware capture. */ +&dwc3_2_dart { + reg = <0x3 0x83020000 0x0 0xc000>, + <0x3 0x83040000 0x0 0xc000>; +}; + /* * The J873g fragments enable and refine nodes of t8152-peripherals.dtsi - * (the USB, apcie port 2 and dart-sbr DARTs), so they come after it. + * (the apcie port 2 and dart-sbr DARTs), so they come after it. */ #include "t8152-j873-nvme.dtsi" -#include "t8152-j873-usb.dtsi" #include "t8152-j873-ethernet.dtsi" #include "t8152-j873-audio.dtsi" From e5ac50732aac6366a90bc9c8e9307cb10e37f20b Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 8 Nov 2026 02:33:35 -0500 Subject: [PATCH 0050/1514] arm64: dts: apple: j873: bring back the USB 2 hosts Restore the J873g USB 2 host description that linux#1197 set aside: the back-left controller (usb-drd1) and the front ports (usb-drd2, behind the on-board hub), each behind its two DART instances. aura prepares these ports before Linux starts (j873_usb_prep()). This is the description that worked on the M6, where both xHCI hosts and the front-port hub enumerated. It still describes the controllers as plain "snps,dwc3" with two iommus, which the generic dwc3 binding rejects. Before it can merge, the nodes need to move to the Apple dwc3 binding, or the binding needs an M6 USB 2 host variant. Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 67 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 17 +---- 2 files changed, 69 insertions(+), 15 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi new file mode 100644 index 00000000000000..5ecd42f9e7135c --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 + * (front ports via the on-board hub). + * The loader powers the controllers and initialises the eUSB2 PHYs in host + * mode before Linux starts (no PMGR, PHY or Type-C driver yet), so the + * controllers are described as plain DWC3 hosts behind their two DARTs. + * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2. + * + * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and + * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists + * both windows on one node (dwc3_1_dart, dwc3_2_dart), but the DART driver + * drives one instance per node and the binding reads a second reg entry as + * DAPF or auxiliary registers. Keep instance 0 on the shared node, with its + * own window only, and describe instance 1 as a node of its own. + */ + +&dwc3_1_dart { + reg = <0x4 0x0b020000 0x0 0xc000>; + status = "okay"; +}; + +&dwc3_2_dart { + reg = <0x3 0x83020000 0x0 0xc000>; + status = "okay"; +}; + +/ { + soc { + dwc3_1_dart_1: iommu@40b040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + usb1: usb@40a430000 { + compatible = "snps,dwc3"; + reg = <0x4 0x0a430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + + dwc3_2_dart_1: iommu@383040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + }; + + /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ + usb2: usb@382430000 { + compatible = "snps,dwc3"; + reg = <0x3 0x82430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index d4900374f1470d..0f98b07748b016 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -372,12 +372,6 @@ <0x4 0x3040000 0x0 0xc000>; }; -/* Retain the register view published by this board's live hardware capture. */ -&dwc3_1_dart { - reg = <0x4 0xb020000 0x0 0xc000>, - <0x4 0xb040000 0x0 0xc000>; -}; - /* Retain the register view published by this board's live hardware capture. */ &dwc3_3_dart { reg = <0x4 0x13020000 0x0 0xc000>, @@ -500,18 +494,11 @@ <0x3 0xa0000000 0x0 0x8000>; }; -/* Unexposed chassis port instances remain described and disabled. */ - -/* Retain the register view published by this board's live hardware capture. */ -&dwc3_2_dart { - reg = <0x3 0x83020000 0x0 0xc000>, - <0x3 0x83040000 0x0 0xc000>; -}; - /* * The J873g fragments enable and refine nodes of t8152-peripherals.dtsi - * (the apcie port 2 and dart-sbr DARTs), so they come after it. + * (the USB, apcie port 2 and dart-sbr DARTs), so they come after it. */ #include "t8152-j873-nvme.dtsi" +#include "t8152-j873-usb.dtsi" #include "t8152-j873-ethernet.dtsi" #include "t8152-j873-audio.dtsi" From 26670aa724b0ebf60114629d9c67e52e6180d588 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 8 Nov 2026 03:58:53 -0500 Subject: [PATCH 0051/1514] dt-bindings: usb: apple,dwc3: Add T8152 The T8152 (M6) USB-C controllers are Apple DWC3 DRD controllers like those on earlier SoCs, each with its own ATC PHY. There is no T8152 USB power-domain, ATC PHY or Type-C support yet. Instead, the bootloader can hand a controller over already running: powered, with the USB2 side of its ATC PHY set up for host mode. Add a standalone "apple,t8152-dwc3" compatible for such a controller, following the T8132 exception already in this binding. It is described by its DWC3 core region, as a host, so dr_mode = "host" is required. The PHY reset and power domain, and on a Type-C port the USB role switch, exist on T8152 but are left to the bootloader, so they are optional there. Every other compatible still requires reg-names, resets, usb-role-switch and two reg entries. There is no apple,t8103-dwc3 fallback: the T8152 layout of the Apple region is not established, and without its ATC PHY the controller cannot switch roles, so the Apple dwc3 glue must not bind it. When T8152 ATC PHY and Type-C support lands, full Type-C operation can key on resets and usb-role-switch being present, so these minimal descriptions stay valid and the dr_mode rule can be relaxed. Signed-off-by: Acelogic --- .../devicetree/bindings/usb/apple,dwc3.yaml | 54 ++++++++++++++++--- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/Documentation/devicetree/bindings/usb/apple,dwc3.yaml b/Documentation/devicetree/bindings/usb/apple,dwc3.yaml index d68a4b68d77caa..df755601429cd0 100644 --- a/Documentation/devicetree/bindings/usb/apple,dwc3.yaml +++ b/Documentation/devicetree/bindings/usb/apple,dwc3.yaml @@ -13,6 +13,12 @@ description: Apple Silicon SoCs use a Synopsys DesignWare DWC3 based controller for each of their Type-C ports. + On T8152 the bootloader can hand a controller over already running, powered + and with the USB2 side of its ATC PHY set up for host mode. Such a controller + is described by its DWC3 core region, as a host. Its PHY reset and power + domain, and on a Type-C port its USB role switch, exist but are left to the + bootloader, so they are optional. + allOf: - $ref: snps,dwc3-common.yaml# - if: @@ -20,10 +26,33 @@ allOf: compatible: not: contains: - const: apple,t8132-dwc3 + enum: + - apple,t8132-dwc3 + - apple,t8152-dwc3 then: required: - power-domains + - if: + properties: + compatible: + contains: + const: apple,t8152-dwc3 + then: + properties: + dr_mode: + const: host + required: + - dr_mode + else: + properties: + reg: + minItems: 2 + reg-names: + minItems: 2 + required: + - reg-names + - resets + - usb-role-switch $defs: apple,tunable: @@ -56,16 +85,17 @@ properties: - const: apple,t8103-dwc3 - const: apple,t8103-dwc3 - const: apple,t8132-dwc3 + - const: apple,t8152-dwc3 reg: - minItems: 2 + minItems: 1 items: - description: Core DWC3 region - description: Apple-specific DWC3 region - description: Controller configuration block (T6040) reg-names: - minItems: 2 + minItems: 1 items: - const: dwc3-core - const: dwc3-apple @@ -106,11 +136,8 @@ properties: required: - compatible - reg - - reg-names - interrupts - iommus - - resets - - usb-role-switch unevaluatedProperties: false @@ -131,3 +158,18 @@ examples: usb-role-switch; }; + + - | + #include + #include + + usb@82430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x82430000 0xcd00>; + interrupts = ; + iommus = <&dwc3_2_dart_0 0>, <&dwc3_2_dart_1 1>; + dr_mode = "host"; + maximum-speed = "high-speed"; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; From 846d101cb4c7be32b91ece8890a7965ce3bfd030 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 8 Nov 2026 03:58:53 -0500 Subject: [PATCH 0052/1514] usb: dwc3: core: Bind the Apple T8152 controller On T8152 (M6) the Apple dwc3 glue cannot drive the controller yet: it needs the ATC PHY as reset provider and a Type-C role switch, and T8152 has no driver for either. The bootloader powers the controller, sets up the USB2 side of its ATC PHY for host mode and selects the host role before the kernel starts, which leaves only the DWC3 core to the kernel. Match "apple,t8152-dwc3" in the dwc3 core driver. dwc3_probe() uses no match data, so the controller probes exactly as a "snps,dwc3" node does, and dr_mode, maximum-speed and the quirks are read from the node as before. dwc3-apple does not match this compatible, so only the core binds it. This entry is to move to dwc3-apple once that driver supports the T8152 ATC PHY and Type-C role switch, so that the two never match the same compatible. Signed-off-by: Acelogic --- drivers/usb/dwc3/core.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/usb/dwc3/core.c b/drivers/usb/dwc3/core.c index 7f68eba95e1f1b..3566533dda5a27 100644 --- a/drivers/usb/dwc3/core.c +++ b/drivers/usb/dwc3/core.c @@ -2962,6 +2962,10 @@ static const struct of_device_id of_dwc3_match[] = { { .compatible = "synopsys,dwc3" }, + { + /* Handed over in host mode by the bootloader, see apple,dwc3.yaml */ + .compatible = "apple,t8152-dwc3" + }, { }, }; MODULE_DEVICE_TABLE(of, of_dwc3_match); From 35833f6358e400ef01d27c4ef38fb7ecf9b8d88d Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 8 Nov 2026 03:58:53 -0500 Subject: [PATCH 0053/1514] arm64: dts: apple: j873: Describe the USB 2 hosts as T8152 DWC3 The back-left (usb-drd1) and front (usb-drd2) USB 2 host nodes are "snps,dwc3" with two iommus, one per DART instance. The generic dwc3 binding allows a single iommu, so dtbs_check rejects both nodes. Use the T8152 Apple dwc3 compatible instead. It allows both DART instances and documents the bootloader handover these nodes rely on. Nothing else changes: the nodes keep their core region, interrupt, DARTs, host mode, speed limit and SUSPHY quirks, and the same dwc3 core driver binds them. Signed-off-by: Acelogic --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 5ecd42f9e7135c..6f1a956bd68e3e 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -2,9 +2,12 @@ /* * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 * (front ports via the on-board hub). - * The loader powers the controllers and initialises the eUSB2 PHYs in host - * mode before Linux starts (no PMGR, PHY or Type-C driver yet), so the - * controllers are described as plain DWC3 hosts behind their two DARTs. + * The loader powers the controllers and sets up the USB2 side of their ATC + * PHYs for host mode before Linux starts (there is no T8152 USB power-domain, + * ATC PHY or Type-C support yet). + * The controllers are described by their DWC3 core region, as hosts behind + * their two DARTs (apple,t8152-dwc3); their PHY reset and power domain, and on + * the Type-C port the role switch, exist but are left to the loader. * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2. * * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and @@ -35,7 +38,7 @@ }; usb1: usb@40a430000 { - compatible = "snps,dwc3"; + compatible = "apple,t8152-dwc3"; reg = <0x4 0x0a430000 0x0 0xcd00>; interrupts = ; dr_mode = "host"; @@ -54,7 +57,7 @@ /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ usb2: usb@382430000 { - compatible = "snps,dwc3"; + compatible = "apple,t8152-dwc3"; reg = <0x3 0x82430000 0x0 0xcd00>; interrupts = ; dr_mode = "host"; From f8c95e25fc069253e1e3baf42d6cd22ff8b6dfab Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:40:58 +1100 Subject: [PATCH 0054/1514] dt-bindings: nvme: apple,nvme-ans: exempt T6050 and T8152 from one rule The integration merge brought in two rules for the required resets and power domains. aurora-wip had "required unless T8152", and integration had "forbidden on T6050, else required". Together they required the properties on T6050 nodes that must not have them, and on T8152 nodes where they are optional. dt-checks flagged that on every T6050 board and on J873g. Keep one rule: required unless T6050 or T8152. T6050 still forbids them. Signed-off-by: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Assisted-by: LLM --- .../devicetree/bindings/nvme/apple,nvme-ans.yaml | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml index 326d8d538947b8..b7fcf03af696f5 100644 --- a/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml +++ b/Documentation/devicetree/bindings/nvme/apple,nvme-ans.yaml @@ -117,7 +117,9 @@ allOf: compatible: not: contains: - const: apple,t8152-nvme-ans2 + enum: + - apple,t6050-nvme-ans2 + - apple,t8152-nvme-ans2 then: required: - resets @@ -195,11 +197,6 @@ allOf: resets: false power-domains: false power-domain-names: false - else: - required: - - resets - - power-domains - - power-domain-names required: - compatible From 210c8f6e6ffd28d41fdf688ab5e3f7ecb674272f Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:42:07 -0600 Subject: [PATCH 0055/1514] ASoC: apple: t8152-aop-audio: Match the T6050 AOP audio node (#1410) The binding and the J714c device tree name the AOP audio service "apple,t6050-aop-audio", but the driver matched only t8142 and t8152, so that node never bound. Add a T6050 hardware config. The J714c ADT audio-speaker stream header (DeviceTree.j714cap) has the same layout as J813's with six amplifiers in place of four: 6 speaker slots and 12 sense words (V, I per amplifier), at 16 bits, on slots vsense 0,4,..20 / isense 2,6,..22. J813's header has 4 slots, 8 sense words and vsense 0..12 / isense 2..14. HW_CFG_T8152 (one amplifier, two sense words) would expose the wrong channel counts, so it is not reused. The sense width and the sense realignment are taken from J813's config by analogy; they are not tested on a J714c. Tested: builds as a module with Rust enabled (clang 19, arm64 defconfig plus CONFIG_RUST, CONFIG_SND_SOC_APPLE_T8152_AOP_AUDIO=m); the object carries the apple,t6050-aop-audio match string. Not tested: no J714c boot, no sound. --- sound/soc/apple/t8152_aop_audio.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 81a224f6974914..f0080ccb506694 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Apple T8152 (J873, Mac mini M6) and T8142 (J813, MacBook Air M5) AOP audio +//! Apple T8152 (J873, Mac mini M6), T8142 (J813, MacBook Air M5) and T6050 +//! (J714c, MacBook Pro 14-inch M5 Max) AOP audio //! //! The AOP firmware owns the audio fabric, as on T8140. The ADT //! (/arm-io/iop-audio-controller) names its services; all of them run on the @@ -582,6 +583,17 @@ static HW_CFG_T8142: HwConfig = HwConfig { realign_sense: true, }; +/// J714c: six amplifiers (left and right woofer 1, woofer 2 and tweeter) in +/// 32-bit slots 0-5, their voltage and current sense back as twelve 16-bit +/// slots (V, I per amplifier) on the stream's RX, as on J813. The ADT +/// audio-speaker stream header gives 6 amplifier slots and 12 sense words. +static HW_CFG_T6050: HwConfig = HwConfig { + spkr_channels: 6, + sense_channels: 12, + sense_formats: FMTBIT_S16_LE, + realign_sense: true, +}; + /// # Safety /// /// `substream` must be live and belong to one of this component's links. @@ -1389,6 +1401,7 @@ kernel::of_device_table!( [ (of::DeviceId::new(c_str!("apple,t8142-aop-audio")), &HW_CFG_T8142), (of::DeviceId::new(c_str!("apple,t8152-aop-audio")), &HW_CFG_T8152), + (of::DeviceId::new(c_str!("apple,t6050-aop-audio")), &HW_CFG_T6050), ] ); From ad10208a01c67742900c2516a646d635bc56a333 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 12 Nov 2026 11:16:19 -0700 Subject: [PATCH 0056/1514] ASoC: tas2764: keep the bus quiet while the amp is in hardware shutdown The hwmon device is registered in the I2C probe, but the amp's SDZ line is only raised in the component probe, when the sound card binds. In between the amp is in hardware shutdown and does not acknowledge its address, and a read of temp1_input or temp1_fault goes to the bus all the same. On the 16-inch M5 Pro MacBook Pro (K116s), lm-sensors.service runs "sensors" at boot; when it lands in that window, each of the six amps fails two reads with EIO and the two speaker buses log i2c-apple 50501c000.i2c: Bus stuck, status 0x10210106 i2c-apple 50501c000.i2c: Issuing reset due to status 0x08210106 (xfstatus 0x00000000) six times each (status: NACK on the address byte). Whether it happens depends on when the codec module's probe and the service meet, which is why only some boots show it. The same holds after the component is removed, when the amp's SDZ vote is dropped again. Make the regmap cache-only from the I2C probe until the component probe has raised SDZ, and again when the component probe fails or the component is removed. A read of the volatile temperature register then returns -EBUSY without a transfer; report that as "no data", like the reading of an amp in software shutdown, so temp1_fault reads 1 instead of failing. System sleep, where the regmap is cache-only as well, gets the same answer. Signed-off-by: Jens Axboe Signed-off-by: Thomas Glanzmann --- sound/soc/codecs/tas2764.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/sound/soc/codecs/tas2764.c b/sound/soc/codecs/tas2764.c index 887de369816535..5a96c84e4cfaed 100644 --- a/sound/soc/codecs/tas2764.c +++ b/sound/soc/codecs/tas2764.c @@ -981,6 +981,13 @@ static int tas2764_read_die_temp(struct tas2764_priv *tas2764, long *result) int ret, reg; ret = regmap_read(tas2764->regmap, TAS2764_TEMP, ®); + /* + * The regmap is cache-only while the amp cannot be reached (SDZ low + * before the component probe and after its removal, system sleep): + * there is no reading then, as in software shutdown below. + */ + if (ret == -EBUSY) + return -ENODATA; if (ret) return ret; /* @@ -1108,6 +1115,9 @@ static int tas2764_codec_probe(struct snd_soc_component *component) usleep_range(1000, 2000); + /* SDZ is high: the amp answers on the bus from here on */ + regcache_cache_only(tas2764->regmap, false); + tas2764_reset(tas2764); regmap_reinit_cache(tas2764->regmap, &tas2764_i2c_regmap); @@ -1230,6 +1240,7 @@ static int tas2764_codec_probe(struct snd_soc_component *component) err_sdz: /* Undo the power-up: ASoC doesn't call the remove after a failed probe */ + regcache_cache_only(tas2764->regmap, true); if (tas2764->sdz_gpio) gpiod_set_value_cansleep(tas2764->sdz_gpio, 0); /* As in the remove: no supply to drop with a GPIO SDZ, none left in a failed group */ @@ -1249,6 +1260,9 @@ static void tas2764_codec_remove(struct snd_soc_component *component) tas2764_flush_shutdown(tas2764); + /* As before the probe: nothing reaches the amp once its SDZ vote is gone */ + regcache_cache_only(tas2764->regmap, true); + /* A failed group's supply was forced off: there is no enable left to balance. */ if (tas2764_group_failed(tas2764)) return; @@ -1658,6 +1672,14 @@ static int tas2764_i2c_probe(struct i2c_client *client) return result; } + /* + * The amp is held in hardware shutdown (SDZ low) until the component + * probe and does not acknowledge its address: keep everything that can + * run before that, such as a read of the hwmon device registered below, + * off the bus. + */ + regcache_cache_only(tas2764->regmap, true); + if (client->dev.of_node) { result = tas2764_parse_dt(&client->dev, tas2764); if (result) From a1efa1537025b4354d68f2b7d6a6219c0217751f Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 14 Nov 2026 23:13:54 -0500 Subject: [PATCH 0057/1514] drm/asahi: g17: run J716C tiling kicks ungated J716C does not require an entry-signal event on a tiling kick. Avoid the redundant firmware round trip, matching the already-qualified zero-event form used by candidate 44 on this board. Keep the event on other M5 variants. A fresh J775c boot with upstream Mesa B reduced render submit time from 257.754 to 244.798 us (-5.03%); opaque and blended fill were unchanged. In the final two-patch series, render measured 242.033 us/submit. The final J775c no-retry gate passed alone6 90/90 and synchronization 2880/2880. Synchronization2 recorded 49144 Pass, 32467 NotSupported, 3 DeviceLost and 3 Crash, improving the upstream baseline of 49109 Pass, 31 Fail, 6 DeviceLost, 3 Crash and 1 ResourceError. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/queue/render.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 77fa9947f6ac67..5920c7d1457e47 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -1032,8 +1032,11 @@ impl Pair { }, mcache, // M5 tiling kicks also retain the last event of the mask, except on the J813, whose - // macOS 27.0 TA and 3D kicks name no event at all. - event_mask: if m5 && stage == 0 && !j813 { + // macOS 27.0 TA and 3D kicks name no event at all. The J716C also runs its tiling + // kick ungated: the redundant entry-signal event adds a firmware round trip to a + // lone render and candidate 44 has qualified the zero-event form on this board. + event_mask: if m5 && stage == 0 && !j813 + && !self.board.is_some_and(|board| board.clusters == 4) { [0, 0, 0, 1u64 << 62] } else { abi::RENDER_KICK_EVENT_MASK From 000b48471371f37c91e8d86b87eb0b42c41dccb3 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 14 Nov 2026 23:13:54 -0500 Subject: [PATCH 0058/1514] drm/asahi: g17: omit redundant J716C render notifications An installed J716C render pair with another pass in flight needs no new queue configuration, lead command, or item-ring notification. Keep the previous item targets and publish only the new kick through the existing host-port transaction in that steady state. Retain the ordinary item windows for first use, drained restarts, rebinds, priority changes, configuration updates, and lead commands. Zero-length retirement windows still retain pass stamps, pool accounting, job-list state, and every other completion witness. On a fresh J775c boot with upstream Mesa B, the two-patch series measured 79.792 us opaque fill, 306.905 us blended fill, 242.033 us render, and 211.089 us/queue hop. A separate fresh boot of this stage measured 230.645 us render; both runs improve on the 244.798 us tiling-only result. The no-retry gate passed alone6 90/90 and synchronization 2880/2880. Synchronization2 recorded 49144 Pass, 32467 NotSupported, 3 DeviceLost and 3 Crash, improving the upstream baseline of 49109 Pass, 31 Fail, 6 DeviceLost, 3 Crash and 1 ResourceError. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/queue/render.rs | 15 +++++++++++ .../drm/asahi/g17/queue/render/publication.rs | 25 ++++++++++++++++--- .../drm/asahi/g17/queue/render/retirement.rs | 2 +- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 5920c7d1457e47..1aaa02f91b12bf 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -1093,6 +1093,17 @@ impl Pair { let tiling_kick = tiling_kick.prepare_entry(&ta_args)?; let fragment_kick = fragment_kick.prepare_entry(&fragment_args)?; let memory = &mut *self.memory; + // J716C retains an installed render pair while work is already in + // flight. In that steady state the host-port kick is sufficient: + // another item-ring notification has no new configuration or lead + // command to publish. Keep the ordinary inner publication for the + // first command, a drained restart, a rebind, and a class change. + let sparse_inner = m5 && !j813 + && self.board.is_some_and(|board| board.clusters == 4) + && self.active.front().is_some() && self.previous.is_none() + && self.registered == Some(policy.priority()) && !self.context_update + && !self.identity_update && !present.into_iter().any(|value| value) + && !leads.into_iter().any(|value| value); let lanes = [ publication::Lane::new( &memory.graph, @@ -1103,6 +1114,7 @@ impl Pair { present[0], kicks[0], leads[0], + sparse_inner, )?, publication::Lane::new( &memory.graph, @@ -1113,6 +1125,7 @@ impl Pair { present[1], kicks[1], leads[1], + sparse_inner, )?, ]; let windows = [lanes[0].window, lanes[1].window]; @@ -1333,6 +1346,7 @@ impl Pair { true, kicks[0], false, + false, )?, publication::Lane::new( &self.memory.graph, @@ -1343,6 +1357,7 @@ impl Pair { true, kicks[1], false, + false, )?, ]; let ends = self.cursors.map(|base| (base + 1) % ITEM_RING_ENTRIES); diff --git a/drivers/gpu/drm/asahi/g17/queue/render/publication.rs b/drivers/gpu/drm/asahi/g17/queue/render/publication.rs index 9ee23de8924011..e5cce1631f25a7 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/publication.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/publication.rs @@ -46,6 +46,7 @@ pub(super) struct Lane<'a> { prefix: usize, prefix_end: u32, pub(super) window: Window, + retained: bool, } impl<'a> Lane<'a> { #[expect( @@ -61,6 +62,7 @@ impl<'a> Lane<'a> { present: bool, timestamp: KickTimestamp, lead: bool, + retained: bool, ) -> Result { // macOS 27.0 on the J813 (common 26A428 interface) publishes the Neo form: its // TA, 3D and compute item rings carry [configuration], descriptor, KickAnnounce (tag 0xe) @@ -68,7 +70,11 @@ impl<'a> Lane<'a> { let j813 = crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed); let m5 = graph.is_m5() && !j813; // M5 items carry no descriptor: [configuration], notification. - let count = u32::from(present) + u32::from(lead) + if m5 { 1 } else { 2 }; + let count = if retained { + 0 + } else { + u32::from(present) + u32::from(lead) + if m5 { 1 } else { 2 } + }; let window = Window::new(base, count, ITEM_RING_ENTRIES)?; let offset = ordinal as usize % memory::RECORDS; let config_offset = memory::CONFIG[stage] + offset * memory::CONFIG_STRIDE; @@ -138,9 +144,10 @@ impl<'a> Lane<'a> { )?) }, announce_destination, - prefix: count as usize - 1, - prefix_end: (base + count - 1) % ITEM_RING_ENTRIES, + prefix: count.saturating_sub(1) as usize, + prefix_end: (base + count.saturating_sub(1)) % ITEM_RING_ENTRIES, window, + retained, }) } fn items(&self, range: core::ops::Range) { @@ -179,17 +186,26 @@ impl<'a> Lane<'a> { /// Fill the retained records without advancing the firmware-visible cursor. /// M5's host-port transaction must occur between this and publish_kick. pub(super) fn prepare(&self) { + if self.retained { + return; + } self.items(0..self.prefix + 1); self.config(); self.announce(); } pub(super) fn publish_prefix(&self) { + if self.retained { + return; + } self.items(0..self.prefix); self.config(); fence(Ordering::SeqCst); self.producer.store(self.prefix_end, Ordering::Relaxed); } pub(super) fn publish_kick(&self) { + if self.retained { + return; + } self.announce(); self.items(self.prefix..self.prefix + 1); fence(Ordering::SeqCst); @@ -202,6 +218,9 @@ impl<'a> Lane<'a> { inner: &AtomicU32, next_inner: u32, ) { + if self.retained { + return; + } self.items(0..self.prefix + 1); self.config(); self.announce(); diff --git a/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs b/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs index 19a2caabe68e10..1083aaa96d1e8d 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/retirement.rs @@ -39,7 +39,7 @@ pub(crate) struct Window { impl Window { pub(crate) fn new(base: u32, count: u32, capacity: u32) -> Result { - if base >= capacity || !(1..=MAX_GROUP_ITEMS).contains(&count) || count >= capacity { + if base >= capacity || count > MAX_GROUP_ITEMS || count >= capacity { return Err(EINVAL); } Ok(Self { From a02fd54ef1ffc3192141af0795ba94f344f4b4ec Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Sat, 31 Oct 2026 10:27:58 -0400 Subject: [PATCH 0059/1514] dt-bindings: display: apple: describe a common scanout aperture Document the display consumer's optional DMA aperture, which can differ from the defaults of individual scanout DARTs. Include the T8122 display subsystem compatible so its shared aperture is checked by this binding. Signed-off-by: DjDeveloperr Signed-off-by: Scott Jones --- .../bindings/display/apple,display-subsystem.yaml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml index ac106575a96724..d2f0438188560e 100644 --- a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml +++ b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml @@ -19,6 +19,7 @@ properties: - enum: - apple,display-subsystem - apple,t6031-display-subsystem + - apple,t8122-display-subsystem - apple,t8132-display-subsystem - const: apple,t8132-display-diagnostics deprecated: true @@ -50,6 +51,15 @@ properties: type: boolean description: The loader validated the inherited J713 SID0 scanout mapping. + apple,dma-range: + $ref: /schemas/types.yaml#/definitions/uint64-array + minItems: 2 + maxItems: 2 + description: + Common scanout DMA aperture, encoded as a base and nonzero size. This + overrides the default aperture of each referenced DART stream. Other + consumers of the same DART retain their own apertures. + required: - compatible - iommus From 6245efd7da261637c86da04a3628b7357769a99c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Sat, 31 Oct 2026 10:27:58 -0400 Subject: [PATCH 0060/1514] iommu/apple-dart: honor consumer apertures before intersecting streams Domain allocation already lets a consumer specify apple,dma-range, but of_xlate intersects the provider defaults before that override is read. A consumer with a common scanout alias and DARTs with disjoint defaults therefore fails configuration before its domain can be allocated. Apply the same consumer aperture while parsing each specifier, retaining validation of both explicit five-cell windows and the override. Share the alignment, overflow and alias-width checks. Consumers without an override keep their existing windows. Add KUnit cases for the J613 high scanout alias across internal/external DART defaults, independent low PIODMA, malformed overrides and invalid five-cell specifiers. An ASAN/UBSAN fixture executing the production parser and of_xlate reproduces the old rejection and accepts the common window. Signed-off-by: DjDeveloperr Signed-off-by: Scott Jones --- drivers/iommu/apple-dart-test.c | 104 ++++++++++++++++++++++++++++++++ drivers/iommu/apple-dart.c | 81 +++++++++++++++---------- 2 files changed, 153 insertions(+), 32 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index dcb65db633d80d..f5c8efc52e7f9e 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -90,6 +90,108 @@ static void apple_dart_test_iommu_specifiers(struct kunit *test) } } +static void apple_dart_test_consumer_window(struct kunit *test) +{ + __be32 value[] = { cpu_to_be32(0x100), 0, cpu_to_be32(0x10), 0 }; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + int i, ret; + + dev = kunit_device_register(test, "apple-dart-consumer-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + + /* J613's common scanout aperture must survive both DART defaults. */ + for (i = 0; i < 2; i++) { + dart->dma_min = i ? 0 : 0x10000000000; + dart->dma_max = i ? 0xffffeffff : 0x10fffffffff; + ret = apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10fffffffff); + } + + /* Domain allocation gives the consumer priority over five-cell args too. */ + args.args_count = 5; + args.args[3] = 0xf; + args.args[4] = 0xffff0000; + ret = apple_dart_parse_dma_window(dev, dart, &args, &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10fffffffff); + + /* An override must not make a malformed stream specifier acceptable. */ + args.args[3] = 0; + args.args[4] = 0; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* PIODMA is a different consumer of the same external display DART. */ + dev->of_node = NULL; + args.args_count = 1; + args.args[0] = 4; + ret = apple_dart_parse_dma_window(dev, dart, &args, &dma_min, &dma_max); + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0xffffeffff); +} + +static void apple_dart_test_invalid_consumer_window(struct kunit *test) +{ + static const struct { + u64 base, size; + } windows[] = { + { 0, 0 }, + { U64_MAX - SZ_16K + 1, 2 * SZ_16K }, + { 1, SZ_16K }, + { 0, SZ_16K + 1 }, + { 0, BIT_ULL(37) }, + }; + __be64 value[2]; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + int i; + + dev = kunit_device_register(test, "apple-dart-invalid-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + for (i = 0; i < ARRAY_SIZE(windows); i++) { + value[0] = cpu_to_be64(windows[i].base); + value[1] = cpu_to_be64(windows[i].size); + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + } + property.length = sizeof(__be32); + KUNIT_EXPECT_LT(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), 0); + dev->of_node = NULL; +} + static void apple_dart_test_before_attach(struct kunit *test) { struct apple_dart_master_cfg master = {}; @@ -1174,6 +1276,8 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_strict_engines), KUNIT_CASE(apple_dart_test_topology), KUNIT_CASE(apple_dart_test_iommu_specifiers), + KUNIT_CASE(apple_dart_test_consumer_window), + KUNIT_CASE(apple_dart_test_invalid_consumer_window), KUNIT_CASE(apple_dart_test_independent_remap_roots), KUNIT_CASE(apple_dart_test_before_attach), KUNIT_CASE(apple_dart_test_locked_handoff), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index b97b0c3378e45e..c7ebb762d515ed 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -3849,10 +3849,37 @@ static void apple_dart_domain_free(struct iommu_domain *domain) kfree(dart_domain); } +static int apple_dart_validate_dma_window(struct device *dev, + const struct apple_dart *dart, + dma_addr_t dma_min, dma_addr_t length, + dma_addr_t *dma_max) +{ + if (!length) + return -EINVAL; + if (!IS_ALIGNED(dma_min, dart->pgsize) || !IS_ALIGNED(length, dart->pgsize)) { + dev_err(dev, "Unaligned DMA window %pad, %pad (0x%x)\n", + &dma_min, &length, dart->pgsize); + return -EINVAL; + } + if (check_add_overflow(dma_min, length - 1, dma_max)) { + dev_err(dev, "DMA window length (%pad) overflows range for start %pad\n", + &length, &dma_min); + return -EINVAL; + } + + /* High bits may select an alias, but the window must fit within it. */ + if ((dma_min ^ *dma_max) & ~DMA_BIT_MASK(dart->ias)) { + dev_err(dev, "Invalid DMA window for ias=%d\n", dart->ias); + return -EINVAL; + } + return 0; +} + /* * Work out the DMA window of one "iommus" specifier. One cell is the stream * ID alone and keeps the window of the DART node. Five cells add the 64-bit - * start and length of the window that the device uses. + * start and length of the window that the device uses. A consumer's + * apple,dma-range overrides either default, as it does at domain allocation. */ static int apple_dart_parse_dma_window(struct device *dev, const struct apple_dart *dart, @@ -3861,43 +3888,33 @@ static int apple_dart_parse_dma_window(struct device *dev, dma_addr_t *dma_max) { dma_addr_t length; + u64 window[2]; + int ret; + if (args->args_count != 1 && args->args_count != 5) + return -EINVAL; *dma_min = dart->dma_min; *dma_max = dart->dma_max; - if (args->args_count == 1) - return 0; - if (args->args_count != 5) - return -EINVAL; - - length = ((dma_addr_t)args->args[3] << 32) | args->args[4]; - if (!length) - return -EINVAL; - - if (*dma_min != 0 || *dma_max != DMA_BIT_MASK(dart->ias)) - dev_err(dev, "still using legacy \"apple,dma-range\" property\n"); - - *dma_min = ((dma_addr_t)args->args[1] << 32) | args->args[2]; - - if (!IS_ALIGNED(*dma_min, dart->pgsize) || - !IS_ALIGNED(length, dart->pgsize)) { - dev_err(dev, "Unaligned DMA window %pad, %pad (0x%x)\n", - dma_min, &length, dart->pgsize); - return -EINVAL; - } - if (check_add_overflow(*dma_min, length - 1, dma_max)) { - dev_err(dev, "DMA window length (%pad) overflows range for start %pad\n", - &length, dma_min); - return -EINVAL; - } - - /* Ensure that the DMA window does not exceed the DART's ias. */ - if ((*dma_min ^ *dma_max) & ~DMA_BIT_MASK(dart->ias)) { - dev_err(dev, "Invalid DMA window for ias=%d\n", dart->ias); - return -EINVAL; + if (args->args_count == 5) { + if (*dma_min != 0 || *dma_max != DMA_BIT_MASK(dart->ias)) + dev_err(dev, "still using legacy \"apple,dma-range\" property\n"); + *dma_min = ((dma_addr_t)args->args[1] << 32) | args->args[2]; + length = ((dma_addr_t)args->args[3] << 32) | args->args[4]; + ret = apple_dart_validate_dma_window(dev, dart, *dma_min, length, dma_max); + if (ret) + return ret; } - return 0; + /* Apply the consumer aperture before intersecting its DART windows. */ + if (!of_property_present(dev->of_node, "apple,dma-range")) + return 0; + ret = of_property_read_u64_array(dev->of_node, "apple,dma-range", + window, ARRAY_SIZE(window)); + if (ret) + return ret; + *dma_min = window[0]; + return apple_dart_validate_dma_window(dev, dart, *dma_min, window[1], dma_max); } static int apple_dart_of_xlate(struct device *dev, From 36a5f137b1ef3137ff20044472dd9ec5aa744ec7 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Sat, 31 Oct 2026 10:27:59 -0400 Subject: [PATCH 0061/1514] arm64: dts: apple: t8122: retain the common scanout DMA alias The display gate adds the external display DART to the shared display subsystem. Its low PIODMA default does not overlap the internal display's inherited 1 TiB alias, so their defaults cannot be intersected for scanout. Describe the subsystem's common scanout aperture explicitly, matching the internal DART. The external PIODMA consumer retains its existing low aperture and the external processor still requires the firmware-ready gate. This is a software-validated candidate; hardware external-display qualification remains pending. Signed-off-by: DjDeveloperr Signed-off-by: Scott Jones --- arch/arm64/boot/dts/apple/t8122-dcp.dtsi | 2 ++ 1 file changed, 2 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-dcp.dtsi b/arch/arm64/boot/dts/apple/t8122-dcp.dtsi index 8d812eae377e8a..59233e5138ed4b 100644 --- a/arch/arm64/boot/dts/apple/t8122-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-dcp.dtsi @@ -33,6 +33,8 @@ display: display-subsystem { compatible = "apple,t8122-display-subsystem"; iommus = <&disp0_dart 0>; + /* Keep the inherited scanout alias when adding external streams. */ + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; status = "disabled"; }; }; From c268dc5b7a035a90e8af35801c49ae3e09e5ddc0 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sat, 14 Nov 2026 08:26:20 -0500 Subject: [PATCH 0062/1514] drm/asahi: admit a fourth loaded T6040 25G83 image A 16-inch M4 Pro (J616s) with 26.6.2 boot firmware (25G83, iBoot mBoot-18000.161.10) loads a fourth normalized T6040 TEXT identity: TEXT 0x60000, DATA 0x138000, the same entropy offsets, sha256 19d997493e00763de31f400a592d8aeae6bd1172c5859661781b4215debc870b. Without it the GPU probe stops with "GPU firmware image not admitted" and the Mac has no render node. Add the digest to the 26.6.2 T6040 image list next to the three existing identities, and to the KUnit test that runs every listed image through the lookup identify() uses. Signed-off-by: Scott Jones --- drivers/gpu/drm/asahi/fwid.rs | 5 +++++ drivers/gpu/drm/asahi/hw/t6040.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index c7d2e84797cfba..c55704d544aff2 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -458,6 +458,11 @@ mod tests { 0xb5, 0xcd, 0xfb, 0xd6, 0xd7, 0xcb, 0xc7, 0xf1, 0xba, 0xa2, 0xcc, 0x8b, 0x37, 0xee, 0x5d, 0x6e, 0x5e, 0x98, ], + [ + 0x19, 0xd9, 0x97, 0x49, 0x3e, 0x00, 0x76, 0x3d, 0xe3, 0x1f, 0x40, 0x0a, 0x59, 0x2d, + 0x8a, 0xea, 0xe6, 0xbd, 0x11, 0x72, 0xc5, 0x85, 0x96, 0x61, 0x78, 0x1b, 0x42, 0x15, + 0xde, 0xbc, 0x87, 0x0b, + ], ]; for (i, digest) in digests.into_iter().enumerate() { let found = measured(build.images, 0x138000, &[[0x59839, 0x5991c]], digest).unwrap(); diff --git a/drivers/gpu/drm/asahi/hw/t6040.rs b/drivers/gpu/drm/asahi/hw/t6040.rs index cfb369da993e9b..8b0ec17044b032 100644 --- a/drivers/gpu/drm/asahi/hw/t6040.rs +++ b/drivers/gpu/drm/asahi/hw/t6040.rs @@ -106,6 +106,18 @@ pub(crate) const CONFIG: Config = Config { 0x37, 0xee, 0x5d, 0x6e, 0x5e, 0x98, ], }, + crate::fwid::FirmwareBuild { + name: "Apple GFX 25G83 for T6040 (normalized loaded image, third alternate J616s fill)", + text_size: 0x60000, + data_size: 0x138000, + entropy: &[[0x59839, 0x5991c]], + boot_filled: &[], + text_sha256: [ + 0x19, 0xd9, 0x97, 0x49, 0x3e, 0x00, 0x76, 0x3d, 0xe3, 0x1f, 0x40, 0x0a, 0x59, + 0x2d, 0x8a, 0xea, 0xe6, 0xbd, 0x11, 0x72, 0xc5, 0x85, 0x96, 0x61, 0x78, 0x1b, + 0x42, 0x15, 0xde, 0xbc, 0x87, 0x0b, + ], + }, ], variant: &fw::variant::V25G83, config: None, From 7e752ab08f012633dbf2b904840c9cb8d6afd2db Mon Sep 17 00:00:00 2001 From: Eryk Wieliczko Date: Mon, 9 Nov 2026 17:47:44 +0100 Subject: [PATCH 0063/1514] drm/apple: v14.7: take primary planes that reach past the mode's edge The 14.7 presenter scans out one unscaled image of the mode's size from the top-left of the framebuffer, and iomfb_v14_7_atomic_check() admitted only planes that describe exactly that. It compared the plane's raw src_* and crtc_* fields with the mode, so it rejected a plane whose destination reaches past the right or bottom edge of the CRTC with -EINVAL. The DRM uAPI allows such a plane: apple_plane_atomic_check() has already clipped it with drm_atomic_helper_check_plane_state() (can_position is true), and the part left on the mode is what the presenter shows. KWin puts up such a plane when it mirrors one output on another. On a J514S (M3 Pro), with the 3024x1964 panel at scale 1.7 mirrored onto an XREAL One (1920x1080 over DisplayPort alt mode), it centres a 1663-pixel wide picture and rounds the 128.5-pixel border up on both sides, so the external primary plane is 1921x1080 on a 1920x1080 mode. Every frame on the glasses then failed its commit, and they showed nothing. Once the glasses dropped and asserted HPD again, the connector's link-status went bad and KWin forced a modeset that included the panel. That commit failed on the same plane, and KWin retried it on every frame, so the panel froze too, with the pointer: around 350 failed commits a second until the mirror was turned off. Judge the plane by its clipped rectangles instead: the clipped source must start at the framebuffer's origin and, like the clipped destination, be of the mode's size. Hand the presenter the clipped source size on external pipes. Planes that start left of or above the mode, are offset into the framebuffer, are scaled or do not cover the mode are still rejected, and the panel still takes only a framebuffer of its mode's size, as before. A plane that the old check admitted has clipped rectangles equal to its raw ones, so it is judged and shown as before. The new KUnit suite runs drm_atomic_helper_check_plane_state() with the limits apple_plane_atomic_check() passes it, and checks which planes are admitted and, through the helper flush uses, what size the presenter is given. Fixes: 98d767ecf921 ("drm/apple, media: apple: avd: T6030 internal panel, external display and AVD fixes") Signed-off-by: Eryk Wieliczko Signed-off-by: Scott Jones --- drivers/gpu/drm/apple/Makefile | 1 + drivers/gpu/drm/apple/iomfb_v14_7.c | 16 +-- drivers/gpu/drm/apple/iomfb_v14_7_plane.h | 65 ++++++++++ drivers/gpu/drm/apple/v14-plane-test.c | 146 ++++++++++++++++++++++ 4 files changed, 218 insertions(+), 10 deletions(-) create mode 100644 drivers/gpu/drm/apple/iomfb_v14_7_plane.h create mode 100644 drivers/gpu/drm/apple/v14-plane-test.c diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index 8b2d7288b5639b..37023630559b27 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -50,4 +50,5 @@ obj-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += afkv2-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += parser-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += hotplug-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += v14-board-test.o +appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += v14-plane-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += audio-no-sio-test.dtbo.o diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index a99bfed67183fd..4e753210d957f3 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -42,6 +42,7 @@ #include "iomfb_v14_7.h" #include "iomfb_v14_7_backlight.h" #include "iomfb_v14_7_board.h" +#include "iomfb_v14_7_plane.h" #include "iomfb_v14_7_link.h" #include "iomfb_v14_7_swap.h" #include "av.h" @@ -3085,12 +3086,7 @@ int iomfb_v14_7_atomic_check(struct apple_dcp *dcp, struct drm_crtc *crtc, if (fb->modifier != DRM_FORMAT_MOD_LINEAR || fb->offsets[0] || fb->pitches[0] < width * 4 || (fb->pitches[0] & 63)) return -EINVAL; - /* An external pipe may show the top-left of a larger framebuffer. */ - if (p->src_x || p->src_y || p->crtc_x || p->crtc_y || - p->src_w != width << 16 || p->src_h != height << 16 || - p->crtc_w != width || p->crtc_h != height || - (dcp->external ? fb->width < width || fb->height < height : - fb->width != width || fb->height != height)) + if (!dcp_v14_plane_fits_mode(p, width, height, dcp->external)) return -EINVAL; obj = drm_fb_dma_get_gem_obj(fb, 0); if (!obj || !obj->dma_addr || (u64)fb->pitches[0] * height > obj->base.size) @@ -3344,12 +3340,15 @@ void iomfb_v14_7_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_plane_state *p = drm_atomic_get_new_plane_state(state, crtc->primary); struct drm_crtc_state *cs = drm_atomic_get_new_crtc_state(state, crtc); struct drm_framebuffer *fb; + u32 width = 0, height = 0; if (!p) p = crtc->primary->state; if (!cs) cs = crtc->state; fb = p && p->visible ? p->fb : NULL; + if (fb) + dcp_v14_plane_scanout_size(p, dcp->external, &width, &height); /* * No swaps while an external display is off, unset, unplugged, or * being described again. @@ -3364,10 +3363,7 @@ void iomfb_v14_7_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, if (!dcp->external) dcp_v14_configure_backlight(dcp); dcp->swap_start = ktime_get(); - if (dcp->v14 && dcp_v14_present(dcp->v14, fb, - fb ? (dcp->external ? p->src_w >> 16 : fb->width) : 0, - fb ? (dcp->external ? p->src_h >> 16 : fb->height) : 0, - dcp->notch_height, cs)) { + if (dcp->v14 && dcp_v14_present(dcp->v14, fb, width, height, dcp->notch_height, cs)) { dcp_drm_crtc_page_flip(dcp, ktime_get()); /* * The swap completed: the framebuffers this commit and earlier diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_plane.h b/drivers/gpu/drm/apple/iomfb_v14_7_plane.h new file mode 100644 index 00000000000000..d330d38ca6d015 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_v14_7_plane.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ + +#ifndef __APPLE_IOMFB_V14_7_PLANE_H__ +#define __APPLE_IOMFB_V14_7_PLANE_H__ + +#include + +#include +#include +#include + +/* + * The 14.7 presenter scans out one unscaled image of the mode's size from + * the top-left corner of the framebuffer. Judge a plane by its clipped + * rectangles, which drm_atomic_helper_check_plane_state() has set by the + * time the CRTC is checked: a plane that reaches past the right or bottom + * edge of the mode is clipped there, and what remains is exactly what the + * presenter scans out. Compositors put up such planes, for example when they + * centre a mirrored output and round its borders up on both sides. + * + * A plane that starts left of or above the mode, or that is scaled, starts + * its clipped source inside the framebuffer or differs in size from the + * mode, which the presenter cannot show. Clipping rounds the source toward + * 1:1, so a plane that reaches past the edge with a source less than a pixel + * off unscaled may clip to exactly the mode's size; it is then taken and + * shown unscaled. + * + * An external pipe may show the top-left of a larger framebuffer; the panel + * takes only a framebuffer of its mode's size. + */ +static inline bool dcp_v14_plane_fits_mode(const struct drm_plane_state *p, + u32 width, u32 height, bool external) +{ + const struct drm_framebuffer *fb = p->fb; + + if (p->src.x1 || p->src.y1 || p->dst.x1 || p->dst.y1) + return false; + if (drm_rect_width(&p->src) != (int)(width << 16) || + drm_rect_height(&p->src) != (int)(height << 16) || + drm_rect_width(&p->dst) != (int)width || + drm_rect_height(&p->dst) != (int)height) + return false; + if (external) + return fb->width >= width && fb->height >= height; + return fb->width == width && fb->height == height; +} + +/* + * The size of the image the presenter scans out for a visible plane that + * dcp_v14_plane_fits_mode() took: its clipped source on an external pipe, + * where the framebuffer may be larger, and the framebuffer on the panel. + */ +static inline void dcp_v14_plane_scanout_size(const struct drm_plane_state *p, + bool external, u32 *width, u32 *height) +{ + if (external) { + *width = drm_rect_width(&p->src) >> 16; + *height = drm_rect_height(&p->src) >> 16; + } else { + *width = p->fb->width; + *height = p->fb->height; + } +} + +#endif /* __APPLE_IOMFB_V14_7_PLANE_H__ */ diff --git a/drivers/gpu/drm/apple/v14-plane-test.c b/drivers/gpu/drm/apple/v14-plane-test.c new file mode 100644 index 00000000000000..2527b6726c7595 --- /dev/null +++ b/drivers/gpu/drm/apple/v14-plane-test.c @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Which primary planes the 14.7 presenter takes: one unscaled image of the + * mode's size from the top-left of the framebuffer, judged on the rectangles + * drm_atomic_helper_check_plane_state() clips to the mode, with the scaling + * limits apple_plane_atomic_check() passes it. A plane that reaches past the + * right or bottom edge of the mode is clipped there and taken; one that is + * offset into the mode, starts left of or above it, or is scaled is not. For + * a plane it takes, check the size iomfb_v14_7_flush() hands the presenter. + */ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "iomfb_v14_7_plane.h" + +struct v14_plane_case { + const char *name; + u16 hdisplay, vdisplay; /* the mode */ + u32 fb_w, fb_h; + int crtc_x, crtc_y; + u32 crtc_w, crtc_h; + u32 src_x, src_y, src_w, src_h; /* whole pixels */ + bool external; + bool fits; + u32 shown_w, shown_h; /* clipped source, when it fits */ + u32 src_w_frac; /* 16.16 fraction added to src_w */ +}; + +static const struct v14_plane_case v14_plane_cases[] = { + { "external, exact", 1920, 1080, 1920, 1080, 0, 0, 1920, 1080, + 0, 0, 1920, 1080, true, true, 1920, 1080 }, + /* + * KWin mirroring a 3024x1964 panel at scale 1.7 onto a 1920x1080 + * display: 1663 columns of picture and 129 of border on each side. + */ + { "external, one column past the right edge", 1920, 1080, 1921, 1080, + 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, true, 1920, 1080 }, + { "external, one row past the bottom edge", 1920, 1080, 1920, 1081, + 0, 0, 1920, 1081, 0, 0, 1920, 1081, true, true, 1920, 1080 }, + { "external, past the right and bottom edges", 1920, 1080, 1921, 1081, + 0, 0, 1921, 1081, 0, 0, 1921, 1081, true, true, 1920, 1080 }, + /* + * Clipping rounds the source toward 1:1: 1921 + 1/65536 columns on + * 1921 clip to exactly 1920 << 16, while 1921.5 on 1921 clip to + * (1920 << 16) + 32750, which is scaled. + */ + { "external, past the edge, source a 65536th over 1:1", 1920, 1080, + 1922, 1080, 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, true, + 1920, 1080, .src_w_frac = 1 }, + { "external, past the edge, source half a pixel over 1:1", 1920, 1080, + 1922, 1080, 0, 0, 1921, 1080, 0, 0, 1921, 1080, true, false, + .src_w_frac = 0x8000 }, + { "external, top-left of a larger framebuffer", 1920, 1080, 2560, 1440, + 0, 0, 1920, 1080, 0, 0, 1920, 1080, true, true, 1920, 1080 }, + { "external, starts left of the mode", 1920, 1080, 1921, 1080, + -1, 0, 1921, 1080, 0, 0, 1921, 1080, true, false }, + { "external, starts above the mode", 1920, 1080, 1920, 1081, + 0, -1, 1920, 1081, 0, 0, 1920, 1081, true, false }, + { "external, offset into the framebuffer", 1920, 1080, 1921, 1080, + 0, 0, 1920, 1080, 1, 0, 1920, 1080, true, false }, + { "external, scaled to the mode", 1920, 1080, 1921, 1080, + 0, 0, 1920, 1080, 0, 0, 1921, 1080, true, false }, + { "external, narrower than the mode", 1920, 1080, 1919, 1080, + 0, 0, 1919, 1080, 0, 0, 1919, 1080, true, false }, + { "external, positioned inside the mode", 1920, 1080, 1920, 1080, + 1, 0, 1919, 1080, 0, 0, 1919, 1080, true, false }, + { "panel, exact", 3024, 1964, 3024, 1964, 0, 0, 3024, 1964, + 0, 0, 3024, 1964, false, true, 3024, 1964 }, + { "panel, larger framebuffer", 3024, 1964, 3025, 1964, 0, 0, 3025, 1964, + 0, 0, 3025, 1964, false, false }, +}; + +static void v14_plane_case_desc(const struct v14_plane_case *c, char *desc) +{ + strscpy(desc, c->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(v14_plane, v14_plane_cases, v14_plane_case_desc); + +static void v14_plane_fits_mode(struct kunit *test) +{ + const struct v14_plane_case *c = test->param_value; + struct drm_plane *plane = kunit_kzalloc(test, sizeof(*plane), GFP_KERNEL); + struct drm_crtc *crtc = kunit_kzalloc(test, sizeof(*crtc), GFP_KERNEL); + struct drm_framebuffer *fb = kunit_kzalloc(test, sizeof(*fb), GFP_KERNEL); + struct drm_crtc_state *crtc_state = + kunit_kzalloc(test, sizeof(*crtc_state), GFP_KERNEL); + struct drm_plane_state p; + u32 shown_w, shown_h; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, plane); + KUNIT_ASSERT_NOT_NULL(test, crtc); + KUNIT_ASSERT_NOT_NULL(test, fb); + KUNIT_ASSERT_NOT_NULL(test, crtc_state); + fb->width = c->fb_w; + fb->height = c->fb_h; + crtc_state->crtc = crtc; + crtc_state->enable = true; + crtc_state->mode.hdisplay = c->hdisplay; + crtc_state->mode.vdisplay = c->vdisplay; + p = (struct drm_plane_state) { + .plane = plane, .crtc = crtc, .fb = fb, + .rotation = DRM_MODE_ROTATE_0, + .crtc_x = c->crtc_x, .crtc_y = c->crtc_y, + .crtc_w = c->crtc_w, .crtc_h = c->crtc_h, + .src_x = c->src_x << 16, .src_y = c->src_y << 16, + .src_w = (c->src_w << 16) + c->src_w_frac, + .src_h = c->src_h << 16, + }; + /* As apple_plane_atomic_check() runs it, before the CRTC is checked. */ + ret = drm_atomic_helper_check_plane_state(&p, crtc_state, + DRM_PLANE_NO_SCALING / 2, + DRM_PLANE_NO_SCALING * 4, + true, true); + KUNIT_ASSERT_EQ(test, ret, 0); + KUNIT_ASSERT_TRUE(test, p.visible); + + KUNIT_EXPECT_EQ(test, dcp_v14_plane_fits_mode(&p, c->hdisplay, c->vdisplay, + c->external), c->fits); + if (!c->fits) + return; + /* What iomfb_v14_7_flush() hands the presenter. */ + dcp_v14_plane_scanout_size(&p, c->external, &shown_w, &shown_h); + KUNIT_EXPECT_EQ(test, shown_w, c->shown_w); + KUNIT_EXPECT_EQ(test, shown_h, c->shown_h); +} + +static struct kunit_case v14_plane_test_cases[] = { + KUNIT_CASE_PARAM(v14_plane_fits_mode, v14_plane_gen_params), + {} +}; + +static struct kunit_suite v14_plane_test_suite = { + .name = "apple-dcp-v14-plane", + .test_cases = v14_plane_test_cases, +}; + +kunit_test_suite(v14_plane_test_suite); From dcc48475a5c263c30dea7cdb9a95539d051eeff9 Mon Sep 17 00:00:00 2001 From: Chris Kearney <303316+chriskearney@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:20:28 -0700 Subject: [PATCH 0064/1514] mesa-m3: allow checked system Mesa after a file opt-out Keep qualified native /usr Mesa usable when the legacy mesa-m3 hook is still installed. Admit only J613/T8122 and J516S/T6030 after display, render-node, journal, user-setup and previous-login checks, followed by a bounded no-draw EGL device/context and implementation-path check. Keep kernel recovery flags and all failed admissions on the existing fallback. Preserve active legacy profiles and their attempt markers. Add host refusal controls and document the remaining packaged login test. Signed-off-by: Chris Kearney <303316+chriskearney@users.noreply.github.com> Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 15 +- .../recipes/mesa-m3/mesa-m3-session-env | 226 +++++++++++++----- .../recipes/mesa-m3/mesa-m3-system-check.c | 221 +++++++++++++++++ .../recipes/mesa-m3/mesa-m3-user-setup | 21 +- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 46 ++++ .../recipes/mesa-m3/tests/test-session-env.sh | 151 ++++++++++++ .../recipes/mesa-m3/tests/test-system-board.c | 32 +++ .../mesa-m3/tests/test-system-provider.py | 79 ++++++ 8 files changed, 729 insertions(+), 62 deletions(-) create mode 100644 tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c create mode 100644 tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md create mode 100644 tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c create mode 100644 tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index e9ea066a21b461..a120de243b1e1f 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -10,7 +10,7 @@ # No profile selection substitutes another Mac's firmware or calibration. pkgname=mesa-m3 pkgver=26.1.4.m3.2 -pkgrel=5 +pkgrel=6 _commit=7ff89a4da387bd561b78efd5f09c98ca8ae18538 pkgdesc="Mesa in /opt/mesa-m3 for the M3 Pro (G15S) and M3 (G15G) GPUs; used by uwsm sessions on T6030, and on T8122 when opted in" arch=('aarch64') @@ -65,7 +65,8 @@ source=("mesa-m3-src-${_commit:0:11}.tar.zst" 72-mesa-m3-render-node.rules mesa-m3-session-confirm mesa-m3-session-confirm.service - mesa-m3-wlcheck.c) + mesa-m3-wlcheck.c + mesa-m3-system-check.c) sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '535e26266e1d173bfd2f73e63be07eccf32eb9cb329ea8955e32a4fa45278ce8' '9be098fc0a1ec38632678ece7d6d7b743d25df4a1af59ce3d17ba3a4eed34db7' @@ -84,18 +85,19 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '10abda78df16e650a77443f50cc46a15e418c42d4d9680c6a61616b232c9bdef' '6c98fab6f9d70449bd7f5258c34eac773836908e060ce5bef86dc5b0ce595e61' '826016665cd0424a614b67add921c0c79c3c698a4d104ea5712518449b75f27c' - '2b2eb627459f73aa596812503c48fc64331e925015bb7121e1888d18cac65b5e' + '444fd73d505c3ffa7252bb44845457deac2550a411464bbcec075e14f21b2063' '6144af8b2e0f04ea615e8c4149e69c45ac49e630c46b2a58f0d1095d977798b2' '530948fc1a124de21c030a497e2ef5351742ba4ad4653484fe30fd1697ad7141' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '7e7914877c5f1ccc85b985b071c838271608c78f858489d69b7a3ba64c4f51f0' + 'a446e2b3fa075a1ef239439539119eb12472b372a84ecb9411c4e65ca3112999' '8f19ebea2b8e669a764d7c4b40ecbc11e8234acfc3a2bfe7910e22de0b64a49d' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' - 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051') + 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051' + 'e80947130044c2dc3671c24c7bff4f523dcc033f7e96f71e334d89a663e2742e') # The qualified M3 Pro build's generated kernel files and libclc. build() stops # when one of ours differs. libagx_shaders.c is compared through kernel-digest.py: @@ -296,6 +298,8 @@ EOF ${CC:-cc} ${CFLAGS} -Wall -I. -o mesa-m3-probe mesa-m3-probe.c ${LDFLAGS} \ -lEGL -lGLESv2 -lvulkan -lwayland-client -lwayland-egl ${CC:-cc} ${CFLAGS} -Wall -o mesa-m3-loadcheck mesa-m3-loadcheck.c ${LDFLAGS} + ${CC:-cc} ${CFLAGS} -std=c11 -Wall -Wextra -Werror -I"$_src/include" \ + -o mesa-m3-system-check mesa-m3-system-check.c ${LDFLAGS} -ldl ${CC:-cc} ${CFLAGS} -Wall -I"$_src/include" $(pkg-config --cflags libdrm) \ -o mesa-m3-abi-check mesa-m3-abi-check.c ${LDFLAGS} $(pkg-config --libs libdrm) ${CC:-cc} ${CFLAGS} -Wall -DMESA_M3_GL_ONLY -I. -o mesa-m3-native-probe mesa-m3-probe.c ${LDFLAGS} \ @@ -341,6 +345,7 @@ package_mesa-m3() { install -Dm755 gpu-heat "${pkgdir}${_prefix}/bin/gpu-heat" install -Dm755 mesa-m3-probe "${pkgdir}${_prefix}/bin/mesa-m3-probe" install -Dm755 mesa-m3-loadcheck "${pkgdir}${_prefix}/libexec/mesa-m3-loadcheck" + install -Dm755 mesa-m3-system-check "${pkgdir}${_prefix}/libexec/mesa-m3-system-check" install -Dm644 mesa-m3-session-env "${pkgdir}${_prefix}/libexec/mesa-m3-session-env" install -Dm755 mesa-m3-user-setup "${pkgdir}${_prefix}/libexec/mesa-m3-user-setup" install -Dm644 user-setup.list "${pkgdir}${_prefix}/share/mesa-m3/user-setup.list" diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env index 5abbf89f8567f8..3308a963e8f1ba 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env @@ -68,6 +68,12 @@ # user-setup it exports nothing: the session's own Mesa setup, which it uses, # decides. The state file says which (fallback=software|none). # +# A file opt-out (/etc/mesa-m3/disable or the user's mesa-m3/disable) on a +# J613 (T8122) or a J516S (T6030) is the exception: when the same node, +# display, kernel-log, user-setup and same-boot attempt checks pass and +# mesa-m3-system-check admits /usr, the session keeps system Mesa +# (fallback=none, no new attempt). mesa_m3=off stays on the software fallback. +# # Each login writes /run/user//mesa-m3-session.state (atomically, 0644, # key=value lines, first line schema=aurora.mesa-m3-session/2) and logs one # journal line (tag mesa-m3) with the same decision, reason and login identity, @@ -133,16 +139,9 @@ mesa_m3_gate() { echo "no-gpu render node ${_mm3_node##*/} is not the $_mm3_name GPU (apple,agx-$_mm3_soc)"; return 1 fi - _mm3_dcp= - for _mm3_c in "$_mm3_root"/sys/class/drm/card*; do - case "${_mm3_c##*/}" in *-*) continue ;; esac - if tr '\0' '\n' 2>/dev/null < "$_mm3_c/device/of_node/compatible" | grep -qx "apple,$_mm3_soc-display-subsystem"; then - _mm3_dcp=${_mm3_c##*/} - fi - done - if [ -z "$_mm3_dcp" ]; then + _mm3_dcp=$(_mm3_native_display "$_mm3_root" "$_mm3_soc") || { echo "no-display no native display card (apple,$_mm3_soc-display-subsystem)"; return 1 - fi + } _mm3_dev="$_mm3_root/dev/dri/${_mm3_node##*/}" if [ ! -r "$_mm3_dev" ] || [ ! -w "$_mm3_dev" ]; then @@ -250,53 +249,19 @@ mesa_m3_gate() { echo "load-failed mesa-m3-loadcheck exit $_mm3_rc: ${_mm3_out:-no output}"; return 1 fi - # The kernel log of this boot must be readable (a user without journal - # access would otherwise see no faults) and must show no fault of the M3 - # GPU or of the display. journalctl exits 1 both for "no match" and for - # errors, so the log is read whole and searched with grep: a failed read, - # an empty log or a grep error refuses (fail closed). The failure state of - # the M3 GPU is sticky for the boot, so a fault means software rendering - # until reboot. - _mm3_out=$(journalctl -k -b -q --no-pager -o cat 2>/dev/null) - _mm3_rc=$? - if [ "$_mm3_rc" -ne 0 ] || [ -z "$_mm3_out" ]; then - echo "log-unreadable this user cannot read this boot's kernel log (only root and the wheel, adm and systemd-journal groups can), so GPU faults cannot be ruled out; to allow GPU acceleration, add the user to the adm group and log in again" - return 1 - fi - _mm3_faults=$(printf '%s\n' "$_mm3_out" | grep -E \ - -e 'M3 scheduler: execution failed|M3 G15[SG]: firmware crashed|M3 firmware error|M3 bank [0-9]|native DCP flip failed|DCP firmware crashed' \ - -e 'M3 G15G verdict: (firmware-running-check-failed|initdata-rejected|cap-violated|job-failed-before-wait|job-faulted|job-ran-completion-missed|job-accepted-never-dispatched|job-timed-out)') - _mm3_rc=$? - if [ "$_mm3_rc" -eq 0 ]; then - echo "gpu-fault the M3 GPU or the display failed this boot, so GPU acceleration is off until reboot: $(printf '%s\n' "$_mm3_faults" | tail -n 1 | tr -d '\r')" - return 1 - elif [ "$_mm3_rc" -ne 1 ]; then - echo "log-unreadable this boot's kernel log could not be searched (grep exit $_mm3_rc)"; return 1 - fi + # The kernel log of this boot must be readable and must show no fault of + # the M3 GPU or of the display. The same fail-closed read is what a file + # opt-out uses before it will leave the system Mesa in place. + _mm3_klog=$(_mm3_kernel_log) || { echo "$_mm3_klog"; return 1; } # A login that chose /opt/mesa-m3 earlier this boot must have a success # marker bound to it (same boot_id, session_id and hook_run_id), written by # mesa-m3-session-confirm.service only after its compositor was alive and # answering on its Wayland socket after the settle time. Otherwise this # login stays off it: no login loop when the compositor cannot run on it. - _mm3_att="$_mm3_root${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/attempt" - _mm3_ok="$_mm3_root${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/session-ok" - if [ -f "$_mm3_att" ]; then - _mm3_boot= - [ -r "$_mm3_root/proc/sys/kernel/random/boot_id" ] && - IFS= read -r _mm3_boot < "$_mm3_root/proc/sys/kernel/random/boot_id" - if [ "$(sed -n 's/^boot_id=//p' "$_mm3_att" 2>/dev/null | head -n 1)" = "$_mm3_boot" ]; then - _mm3_v=$(sed -n 's/^hook_run_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) - _mm3_val=$(sed -n 's/^session_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) - if [ -z "$_mm3_v" ] || [ ! -f "$_mm3_ok" ] || - [ "$(head -n 1 "$_mm3_ok" 2>/dev/null)" != schema=aurora.mesa-m3-session-ok/1 ] || - [ "$(sed -n 's/^boot_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_boot" ] || - [ "$(sed -n 's/^hook_run_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_v" ] || - [ "$(sed -n 's/^session_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_val" ]; then - echo "previous-failed the last login with /opt/mesa-m3 this boot (hook_run_id ${_mm3_v:-unknown}) has no success marker: its compositor was not seen alive and answering, so this login renders in software; to try the GPU again: rm $_mm3_att, then log out and in (or reboot)" - return 1 - fi - fi + if ! _mm3_legacy_attempt_clear "$_mm3_root"; then + echo "previous-failed the last login with /opt/mesa-m3 this boot (hook_run_id ${_mm3_v:-unknown}) has no success marker: its compositor was not seen alive and answering, so this login renders in software; to try the GPU again: rm $_mm3_att, then log out and in (or reboot)" + return 1 fi if [ "${_mm3_ign:-0}" -gt 0 ]; then @@ -354,6 +319,137 @@ _mm3_node_open() { return 1 } +# _mm3_native_display ROOT SOC: the card name of this SoC's native display, +# or nothing. A connector name (card2-eDP-1) is not a card. The last match +# wins, as the gate's own walk did. +_mm3_native_display() { + _mm3_dcp= + for _mm3_c in "$1"/sys/class/drm/card*; do + case "${_mm3_c##*/}" in *-*) continue ;; esac + if tr '\0' '\n' 2>/dev/null < "$_mm3_c/device/of_node/compatible" | grep -qx "apple,$2-display-subsystem"; then + _mm3_dcp=${_mm3_c##*/} + fi + done + [ -n "$_mm3_dcp" ] || return 1 + printf '%s\n' "$_mm3_dcp" +} + +# Fail closed. Prints one "log-unreadable ..." or "gpu-fault ..." line and +# returns 1 unless this boot's kernel log was read and contains none of the +# M3 GPU or display faults. journalctl exits 1 both for "no match" and for +# errors, so the log is read whole and searched with grep. A failed read, an +# empty log or a grep error refuses. The GPU failure state is sticky for the +# boot. +_mm3_kernel_log() { + _mm3_out=$(journalctl -k -b -q --no-pager -o cat 2>/dev/null) + _mm3_rc=$? + if [ "$_mm3_rc" -ne 0 ] || [ -z "$_mm3_out" ]; then + echo "log-unreadable this user cannot read this boot's kernel log (only root and the wheel, adm and systemd-journal groups can), so GPU faults cannot be ruled out; to allow GPU acceleration, add the user to the adm group and log in again" + return 1 + fi + _mm3_faults=$(printf '%s\n' "$_mm3_out" | grep -E \ + -e 'M3 scheduler: execution failed|M3 G15[SG]: firmware crashed|M3 firmware error|M3 bank [0-9]|native DCP flip failed|DCP firmware crashed' \ + -e 'M3 G15G verdict: (firmware-running-check-failed|initdata-rejected|cap-violated|job-failed-before-wait|job-faulted|job-ran-completion-missed|job-accepted-never-dispatched|job-timed-out)') + _mm3_rc=$? + if [ "$_mm3_rc" -eq 0 ]; then + echo "gpu-fault the M3 GPU or the display failed this boot, so GPU acceleration is off until reboot: $(printf '%s\n' "$_mm3_faults" | tail -n 1 | tr -d '\r')" + return 1 + elif [ "$_mm3_rc" -ne 1 ]; then + echo "log-unreadable this boot's kernel log could not be searched (grep exit $_mm3_rc)"; return 1 + fi + return 0 +} + +# Return 0 when this boot has no unmatched /opt/mesa-m3 attempt. Return 1 +# when an attempt for this boot_id has no success marker bound to its +# hook_run_id and session_id. Never creates, deletes or rewrites either file. +# On failure, _mm3_att and _mm3_v are the attempt path and its hook_run_id. +_mm3_legacy_attempt_clear() { + _mm3_att="$1${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/attempt" + _mm3_ok="$1${XDG_STATE_HOME:-$HOME/.local/state}/mesa-m3/session-ok" + [ -f "$_mm3_att" ] || return 0 + _mm3_boot= + [ -r "$1/proc/sys/kernel/random/boot_id" ] && + IFS= read -r _mm3_boot < "$1/proc/sys/kernel/random/boot_id" + [ "$(sed -n 's/^boot_id=//p' "$_mm3_att" 2>/dev/null | head -n 1)" = "$_mm3_boot" ] || return 0 + _mm3_v=$(sed -n 's/^hook_run_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) + _mm3_val=$(sed -n 's/^session_id=//p' "$_mm3_att" 2>/dev/null | head -n 1) + if [ -z "$_mm3_v" ] || [ ! -f "$_mm3_ok" ] || + [ "$(head -n 1 "$_mm3_ok" 2>/dev/null)" != schema=aurora.mesa-m3-session-ok/1 ] || + [ "$(sed -n 's/^boot_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_boot" ] || + [ "$(sed -n 's/^hook_run_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_v" ] || + [ "$(sed -n 's/^session_id=//p' "$_mm3_ok" 2>/dev/null | head -n 1)" != "$_mm3_val" ]; then + return 1 + fi + return 0 +} + +# File opt-out on J613/T8122 or J516S/T6030 may keep the system Mesa. Prints +# one detail line and returns 0 only when every check below passes. A helper +# exit of 0 is not enough on its own. Does not write an attempt or touch a +# marker. mesa_m3=off is not a file opt-out. +_mm3_system_admit() { + case ${XDG_CURRENT_DESKTOP:-} in Hyprland|hyprland) ;; *) return 1 ;; esac + _mm3_cmdline=$(cat "$1/proc/cmdline" 2>/dev/null) || return 1 + case " $_mm3_cmdline " in + *" mesa_m3=off "*|*" nomodeset "*) return 1 ;; + esac + if [ ! -e "$1/etc/mesa-m3/disable" ] && + [ ! -e "$1${XDG_CONFIG_HOME:-$HOME/.config}/mesa-m3/disable" ]; then + return 1 + fi + _mm3_dt=$(tr '\0' '\n' 2>/dev/null < "$1/proc/device-tree/compatible") + _mm3_soc=$(_mm3_soc_of "$1") + _mm3_chip= + _mm3_identity=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,j') + _mm3_socs=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,t') + case "$_mm3_soc:$_mm3_identity:$_mm3_socs" in + t8122:apple,j613:apple,t8122) _mm3_chip=t8122 ;; + t6030:apple,j516s:apple,t6030) _mm3_chip=t6030 ;; + *) return 1 ;; + esac + # Exactly one render node, and it is this SoC's asahi GPU, and this user + # can open it. An any-node match is not enough. + _mm3_nodes=0 + _mm3_node= + for _mm3_n in "$1"/sys/class/drm/renderD*; do + [ -e "$_mm3_n" ] || continue + _mm3_nodes=$((_mm3_nodes + 1)) + _mm3_node=$_mm3_n + done + [ "$_mm3_nodes" -eq 1 ] || return 1 + _mm3_drv=$(basename "$(readlink -f "$_mm3_node/device/driver" 2>/dev/null)" 2>/dev/null) + [ "$_mm3_drv" = asahi ] || return 1 + tr '\0' '\n' 2>/dev/null < "$_mm3_node/device/of_node/compatible" | grep -qx "apple,agx-$_mm3_chip" || return 1 + _mm3_dev="$1/dev/dri/${_mm3_node##*/}" + [ -r "$_mm3_dev" ] && [ -w "$_mm3_dev" ] || return 1 + _mm3_dcp=$(_mm3_native_display "$1" "$_mm3_chip") || return 1 + _mm3_legacy_attempt_clear "$1" || return 1 + _mm3_klog=$(_mm3_kernel_log) || return 1 + if [ -n "$1" ]; then + _mm3_out=$("$1$_mm3_p/libexec/mesa-m3-user-setup" --home "$HOME" \ + --config-home "${XDG_CONFIG_HOME:-$HOME/.config}" --env --system-provider \ + --session-desktops "${XDG_CURRENT_DESKTOP:-}" --root "$1" 2>&1) + else + _mm3_out=$("$_mm3_p/libexec/mesa-m3-user-setup" --home "$HOME" \ + --config-home "${XDG_CONFIG_HOME:-$HOME/.config}" --env --system-provider \ + --session-desktops "${XDG_CURRENT_DESKTOP:-}" 2>&1) + fi + [ "$?" -eq 0 ] || return 1 + if [ -n "$1" ]; then + _mm3_helper=$1/opt/mesa-m3/libexec/mesa-m3-system-check + else + _mm3_helper=/opt/mesa-m3/libexec/mesa-m3-system-check + fi + [ -x "$_mm3_helper" ] || return 1 + # The helper sees a clean environment: a leaked GL preload or path must + # not decide /usr's renderer. Five seconds, then kill. + timeout -k 2 5 env -i PATH=/usr/bin:/bin "$_mm3_helper" \ + "/dev/dri/${_mm3_node##*/}" "$_mm3_chip" >/dev/null 2>&1 + [ "$?" -eq 0 ] || return 1 + printf '%s\n' "system Mesa on /usr admits /dev/dri/${_mm3_node##*/} ($_mm3_chip); /opt/mesa-m3 stays inactive" +} + # _mm3_state ROOT DECISION REASON DETAIL FALLBACK: write the state file and the journal # line. A value holding a newline or carriage return is refused. _mm3_state() { @@ -455,23 +551,43 @@ mesa_m3_session_env() { _mm3_attempt "${1:-}" else # Never the system Mesa on an M3 render node it can open (Hyprland - # would stop at start), except where this session's own setup chose. + # would stop at start), except where this session's own setup chose, + # or a file opt-out whose system-Mesa handoff passed. _mm3_fb=none - if [ "${_mm3_decision%% *}" != user-setup ] && _mm3_node_open "${1:-}"; then + _mm3_detail=${_mm3_decision#* } + _mm3_admitted=0 + if [ "${_mm3_decision%% *}" = opt-out ]; then + _mm3_sys=$(_mm3_system_admit "${1:-}") + if [ "$?" -eq 0 ]; then + _mm3_admitted=1 + _mm3_detail="$_mm3_detail; $_mm3_sys" + # Only the pair this hook itself exports. Anything else in the + # environment, including a user's own LIBGL_ALWAYS_SOFTWARE + # without this marker, stays. + if [ "${LIBGL_ALWAYS_SOFTWARE:-}" = 1 ] && [ "${MESA_M3_FALLBACK:-}" = software ]; then + unset LIBGL_ALWAYS_SOFTWARE + unset MESA_M3_FALLBACK + fi + fi + fi + if [ "$_mm3_admitted" -eq 0 ] && [ "${_mm3_decision%% *}" != user-setup ] && _mm3_node_open "${1:-}"; then export LIBGL_ALWAYS_SOFTWARE=1 export MESA_M3_FALLBACK=software _mm3_fb=software fi - _mm3_state "${1:-}" inactive "${_mm3_decision%% *}" "${_mm3_decision#* }" "$_mm3_fb" + _mm3_state "${1:-}" inactive "${_mm3_decision%% *}" "$_mm3_detail" "$_mm3_fb" fi } if [ -z "${MESA_M3_SESSION_ENV_NO_RUN:-}" ]; then mesa_m3_session_env - unset -f mesa_m3_gate mesa_m3_session_env _mm3_init _mm3_state _mm3_node_open _mm3_attempt _mm3_soc_of _mm3_25g83_board + unset -f mesa_m3_gate mesa_m3_session_env _mm3_init _mm3_state _mm3_node_open _mm3_attempt \ + _mm3_soc_of _mm3_25g83_board _mm3_native_display _mm3_kernel_log \ + _mm3_legacy_attempt_clear _mm3_system_admit fi unset _mm3_root _mm3_p _mm3_nodes _mm3_node _mm3_n _mm3_drv _mm3_dcp _mm3_c _mm3_dev _mm3_f _mm3_v \ _mm3_val _mm3_ifs _mm3_d _mm3_out _mm3_rc _mm3_decision _mm3_on \ _mm3_so _mm3_uid _mm3_sid _mm3_inv _mm3_ver _mm3_boot _mm3_cr _mm3_nl \ _mm3_body _mm3_kv _mm3_dir _mm3_tmp _mm3_fb _mm3_run _mm3_att _mm3_ok _mm3_faults _mm3_ign _mm3_igd \ - _mm3_soc _mm3_name _mm3_dt _mm3_base _mm3_profile _mm3_requested _mm3_files _mm3_gate_ifs _mm3_board _mm3_note + _mm3_soc _mm3_name _mm3_dt _mm3_base _mm3_profile _mm3_requested _mm3_files _mm3_gate_ifs _mm3_board _mm3_note \ + _mm3_klog _mm3_sys _mm3_admitted _mm3_detail _mm3_helper _mm3_chip _mm3_identity _mm3_socs _mm3_cmdline diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c new file mode 100644 index 00000000000000..8f6177750196d5 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c @@ -0,0 +1,221 @@ +/* SPDX-License-Identifier: MIT */ +/* Check system Mesa admission for one M3 render node, without drawing. + * This helper never selects /opt/mesa-m3 or enables an experimental GPU. + * The session hook invokes it with an empty environment and a timeout. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool +board_compat_matches(const char *bytes, size_t length, const char *soc) +{ + const char *board = !strcmp(soc, "t8122") ? "apple,j613" : + !strcmp(soc, "t6030") ? "apple,j516s" : NULL; + if (!board || !length || bytes[length - 1] != '\0') + return false; + unsigned boards = 0, socs = 0; + size_t offset = 0; + while (offset < length) { + size_t remaining = length - offset; + size_t size = strnlen(bytes + offset, remaining); + if (!size || size == remaining) + return false; + const char *value = bytes + offset; + if (!strncmp(value, "apple,j", 7)) { + if (strcmp(value, board)) + return false; + boards++; + } else if (!strncmp(value, "apple,t", 7)) { + if (strncmp(value + 6, soc, strlen(soc) + 1)) + return false; + socs++; + } + offset += size + 1; + } + return boards == 1 && socs == 1; +} + +static bool +qualified_board(const char *soc) +{ + FILE *file = fopen("/proc/device-tree/compatible", "rb"); + if (!file) + return false; + char bytes[4096]; + size_t length = fread(bytes, 1, sizeof(bytes), file); + bool complete = !ferror(file) && length < sizeof(bytes); + fclose(file); + return complete && board_compat_matches(bytes, length, soc); +} + +static bool +symbol(void *library, const char *name, void *destination, size_t size) +{ + void *address = dlsym(library, name); + if (!address || size != sizeof(address)) + return false; + memcpy(destination, &address, size); + return true; +} + +/* Check what actually loaded, rather than trusting a version or a package name. + * A role supplied through a legacy prefix, or a deleted implementation, fails. + */ +static bool +system_implementation(void) +{ + FILE *maps = fopen("/proc/self/maps", "r"); + if (!maps) + return false; + char line[8192]; + bool egl = false, gallium = false, invalid = false; + while (fgets(line, sizeof(line), maps)) { + char *path = strchr(line, '/'); + if (!path) + continue; + bool is_egl = strstr(path, "libEGL_mesa.so") != NULL; + bool is_gallium = strstr(path, "libgallium-") != NULL; + bool is_asahi = strstr(path, "/dri/asahi_dri.so") != NULL; + if (!is_egl && !is_gallium && !is_asahi) + continue; + if (strncmp(path, "/usr/lib/", 9) || strstr(path, " (deleted)")) + invalid = true; + egl |= is_egl; + gallium |= is_gallium || is_asahi; + } + bool complete = !ferror(maps); + fclose(maps); + return complete && !invalid && egl && gallium; +} + +int +main(int argc, char **argv) +{ + if (argc != 3) { + fprintf(stderr, "usage: mesa-m3-system-check /dev/dri/renderD t8122|t6030\n"); + return 2; + } + const char *expected = !strcmp(argv[2], "t8122") ? "Apple M3 (G15G C0)" : + !strcmp(argv[2], "t6030") ? "Apple M3 Pro (G15S B1)" : NULL; + if (!expected) + return 2; + const char *node_prefix = "/dev/dri/renderD"; + size_t prefix_length = strlen(node_prefix); + if (strncmp(argv[1], node_prefix, prefix_length) || + !argv[1][prefix_length] || + strspn(argv[1] + prefix_length, "0123456789") != strlen(argv[1] + prefix_length)) + return 2; + if (!qualified_board(argv[2])) + return 1; + struct stat st; + if (lstat(argv[1], &st) || !S_ISCHR(st.st_mode)) + return 1; + + /* env -i at exec is also necessary: clearenv cannot undo LD_PRELOAD that + * the dynamic linker processed before main. Do not inherit opt-in flags. + */ + if (clearenv() || + setenv("__EGL_VENDOR_LIBRARY_FILENAMES", + "/usr/share/glvnd/egl_vendor.d/50_mesa.json", 1) || + setenv("LIBGL_DRIVERS_PATH", "/usr/lib/dri", 1) || + setenv("MESA_SHADER_CACHE_DISABLE", "true", 1)) + return 1; + alarm(8); + void *egl_library = dlopen("/usr/lib/libEGL.so.1", RTLD_NOW | RTLD_LOCAL); + void *gles_library = dlopen("/usr/lib/libGLESv2.so.2", RTLD_NOW | RTLD_LOCAL); + if (!egl_library || !gles_library) + return 1; + + PFNEGLGETPROCADDRESSPROC get_proc = NULL; + PFNEGLINITIALIZEPROC initialize = NULL; + PFNEGLBINDAPIPROC bind_api = NULL; + PFNEGLCHOOSECONFIGPROC choose_config = NULL; + PFNEGLCREATECONTEXTPROC create_context = NULL; + PFNEGLMAKECURRENTPROC make_current = NULL; + PFNEGLDESTROYCONTEXTPROC destroy_context = NULL; + PFNEGLTERMINATEPROC terminate = NULL; + const GLubyte *(*get_string)(GLenum) = NULL; +#define LOAD(library, function, name) \ + if (!symbol(library, name, &function, sizeof(function))) return 1 + LOAD(egl_library, get_proc, "eglGetProcAddress"); + LOAD(egl_library, initialize, "eglInitialize"); + LOAD(egl_library, bind_api, "eglBindAPI"); + LOAD(egl_library, choose_config, "eglChooseConfig"); + LOAD(egl_library, create_context, "eglCreateContext"); + LOAD(egl_library, make_current, "eglMakeCurrent"); + LOAD(egl_library, destroy_context, "eglDestroyContext"); + LOAD(egl_library, terminate, "eglTerminate"); + LOAD(gles_library, get_string, "glGetString"); +#undef LOAD + + PFNEGLQUERYDEVICESEXTPROC query_devices = NULL; + PFNEGLQUERYDEVICESTRINGEXTPROC device_string = NULL; + PFNEGLGETPLATFORMDISPLAYEXTPROC platform_display = NULL; +#define EXT(function, name) do { \ + __eglMustCastToProperFunctionPointerType address = get_proc(name); \ + if (!address || sizeof(address) != sizeof(function)) return 1; \ + memcpy(&function, &address, sizeof(function)); \ +} while (0) + EXT(query_devices, "eglQueryDevicesEXT"); + EXT(device_string, "eglQueryDeviceStringEXT"); + EXT(platform_display, "eglGetPlatformDisplayEXT"); +#undef EXT + EGLint count = 0; + EGLDeviceEXT devices[16]; + if (!query_devices(0, NULL, &count) || count < 1 || count > 16 || + !query_devices(count, devices, &count) || count < 1 || count > 16) + return 1; + EGLDeviceEXT selected = EGL_NO_DEVICE_EXT; + for (EGLint i = 0; i < count; ++i) { + const char *path = device_string(devices[i], EGL_DRM_RENDER_NODE_FILE_EXT); + if (path && !strcmp(path, argv[1])) { + if (selected != EGL_NO_DEVICE_EXT) + return 1; + selected = devices[i]; + } + } + if (selected == EGL_NO_DEVICE_EXT) + return 1; + + EGLDisplay display = platform_display(EGL_PLATFORM_DEVICE_EXT, selected, NULL); + if (display == EGL_NO_DISPLAY || !initialize(display, NULL, NULL)) + return 1; + EGLContext context = EGL_NO_CONTEXT; + bool accepted = false; + EGLConfig config; + EGLint matches = 0; + const EGLint attributes[] = { + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR, + EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE, + }; + const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; + if (!bind_api(EGL_OPENGL_ES_API) || + !choose_config(display, attributes, &config, 1, &matches) || matches != 1) + goto done; + context = create_context(display, config, EGL_NO_CONTEXT, context_attributes); + if (context == EGL_NO_CONTEXT || + !make_current(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) + goto done; + const char *renderer = (const char *)get_string(GL_RENDERER); + accepted = renderer && !strcmp(renderer, expected) && + system_implementation(); + if (accepted) + printf("system-mesa=available renderer=%s\n", renderer); +done: + make_current(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + if (context != EGL_NO_CONTEXT) + destroy_context(display, context); + terminate(display); + dlclose(gles_library); + dlclose(egl_library); + return accepted ? 0 : 1; +} diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index a581853b1404d0..80a459b2c2551b 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -4,6 +4,7 @@ mesa-m3-user-setup --home HOME [--config-home DIR] [--env | --environ FILE] [--session-desktops NAMES] [--list FILE] [--root DIR] + [--system-provider] The one definition of "the user's own M3 Mesa setup", used by the mesa-m3 session hook at every login and by the installer. What counts is listed in @@ -20,6 +21,8 @@ see the comments there. as in XDG_CURRENT_DESKTOP (uwsm exports them before it reads any environment file); empty or absent: unknown --root DIR prefix every path with DIR (tests) + --system-provider also refuse legacy /opt selectors and session flags when + checking whether the real desktop will use system Mesa Nothing is sourced or evaluated. Files are read as text and split into words the way a POSIX shell would (quotes, backslashes, comments, ";"), with no @@ -79,10 +82,14 @@ def fail(msg): def parse_args(argv): opts = {'home': None, 'config': None, 'env': False, 'environ': None, 'list': DEFAULT_LIST, 'root': '', - 'desktops': None} + 'desktops': None, 'system_provider': False} i = 0 while i < len(argv): a = argv[i] + if a == '--system-provider': + opts['system_provider'] = True + i += 1 + continue if a == '--env': opts['env'] = True i += 1 @@ -248,6 +255,14 @@ class Finder: for k, i in items: if k in ('variable', 'flag', 'prefix', 'ldpath'): self.kind[i] = k + if opts['system_provider']: + # These may be left over from an active legacy session. The + # admission helper's clean environment cannot prove that the + # real desktop will use /usr while these remain in its setup. + for name in ('LD_PRELOAD', 'LD_AUDIT', 'MESA_M3_SESSION', 'MESA_M3_PROFILE', + 'ASAHI_M3_EXPERIMENTAL', 'AGX_MESA_DEBUG', 'HK_DEBUG_LOG', + 'VK_LOADER_LAYERS_DISABLE', 'QSG_RHI_BACKEND'): + self.kind[name] = 'flag' def real(self, p): return self.o['root'] + p @@ -297,7 +312,9 @@ class Finder: def ours(self, path): p = os.path.normpath(path) if path.startswith('/') else path - return p == PREFIX or p.startswith(PREFIX + '/') + # A system-Mesa handoff must also detect the old prefix. The normal + # legacy gate deliberately accepts it and keeps its original behavior. + return not self.o['system_provider'] and (p == PREFIX or p.startswith(PREFIX + '/')) def holds_mesa(self, d): r = self.real(d) diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md new file mode 100644 index 00000000000000..dbe150d387dc08 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -0,0 +1,46 @@ +# Legacy mesa-m3 to system Mesa + +With native Mesa installed in `/usr`, the legacy file opt-out still forced +`LIBGL_ALWAYS_SOFTWARE=1`. This prevented an accelerated login even when the +system driver worked. The legacy package owns this hook, so the native Mesa +package must not overwrite it or add an unconditional late unset. + +This change allows a file opt-out on J613/T8122 and J516S/T6030 to leave system +Mesa selected. It requires one accessible Asahi render node, the matching +native display, a readable healthy kernel journal, no unmatched same-boot +legacy login attempt, and no conflicting environment or later user settings. +A bounded helper then opens the exact EGL device using only `/usr` libraries +and verifies its native renderer and loaded implementation paths. It creates +a context but makes no draw, swap or compute calls. + +A failed check keeps the existing software fallback. `mesa_m3=off` and +`nomodeset` remain recovery choices. Other boards, including J615, remain +outside this system handoff. Explicit legacy profile selection is unchanged. +No opt-in flags, attempt records or success markers are added or removed. +Only the exact software-fallback pair previously exported by this hook can +be cleared. The state remains `inactive`, `reason=opt-out`, `fallback=none` +when system Mesa admission succeeds. + +Run the host checks from this directory (a writable TMPDIR may be needed): + +```sh +sh test-session-env.sh +bash test-session-env.sh +sh test-user-setup.sh +python3 test-system-provider.py +cc -std=c11 -Wall -Wextra -Werror -pedantic -O2 test-system-board.c -ldl -o /tmp/test-system-board +/tmp/test-system-board +``` + +Validation on J516S with kernel `7.2.11-mixtape-77648eb77168-g15` and the native +Mesa source `97a65d845f39418aecc693dcaf9dcb14a05849f6`: the helper ran as the +desktop user without opt-in variables and returned +`Apple M3 Pro (G15S B1)`, exit 0. No new kernel log messages, package changes +or reboot. This is device/context admission, not a packaged login test, +rendering qualification, CTS result or support claim for other boards. + +Before an image cutover, build the updated legacy package and verify a fresh +login alongside the actual pinned Omacom Mesa packages. Existing legacy users +and unqualified profiles must retain their recovery path; clean system-Mesa +images can omit the legacy package. The Mesa source and package PRs remain +separate from this hook update. diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh index 44f25289927084..6c7b2eb659b6fc 100755 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh @@ -665,5 +665,156 @@ echo j613-25g83-hal200 > "$J516S/etc/mesa-m3/t8122-profile" expect "$J516S" profile-mismatch J613 rm "$J516S/etc/mesa-m3/t8122-profile" + +# System Mesa handoff: opt-out must not strand a qualified native /usr +# installation in software rendering. Every failed admission retains recovery. +# The helper is a stub here; its real board/renderer/provenance tests are separate. +system_root() { + case "$2" in + air) _hd="apple,j613 apple,t8122"; _hg=$G15G ;; + *) _hd="apple,j516s apple,t6030"; _hg=$G15S ;; + esac + _hr=$(mkroot "handoff-$1" "$_hd" "$_hg" yes 1 yes) + mkdir -p "$_hr/etc/mesa-m3" + : > "$_hr/etc/mesa-m3/disable" + cat > "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" <<'H' +#!/bin/sh +here=${0%/*} +printf '%s\n' "$@" > "$here/system-check.args" +env | sort > "$here/system-check.env" +[ ! -e "$here/system-check.sleep" ] || sleep 8 +[ ! -e "$here/system-check.fail" ] +H + chmod +x "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" + echo "$_hr" +} +handoff() { # ROOT FALLBACK HELPER_CALLED [VAR=value...] + _hr=$1 _hfb=$2 _hc=$3 + shift 3 + rm -f "$_hr/opt/mesa-m3/libexec/system-check.args" + _ha="$_hr$T/home/.local/state/mesa-m3/attempt" + _hbefore=missing + [ ! -f "$_ha" ] || _hbefore=$(sha256sum "$_ha" | cut -d' ' -f1) + _ho=$(env -i PATH="$T/bin:/usr/bin:/bin" HOME="$T/home" FAKE_LOG="$T/log" \ + XDG_CURRENT_DESKTOP=Hyprland "$@" sh -c ' + MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" + mesa_m3_session_env "$2" + printf "software=%s\nmarker=%s\nlegacy=%s\n" "${LIBGL_ALWAYS_SOFTWARE:-}" "${MESA_M3_FALLBACK:-}" "${MESA_M3_SESSION:-}" + cat "$2/run/user/$(id -u)/mesa-m3-session.state" + ' sh "$ENVFILE" "$_hr") + _hafter=missing + [ ! -f "$_ha" ] || _hafter=$(sha256sum "$_ha" | cut -d' ' -f1) + _hcalled=no + [ ! -e "$_hr/opt/mesa-m3/libexec/system-check.args" ] || _hcalled=yes + if printf '%s\n' "$_ho" | grep -qx "fallback=$_hfb" && + printf '%s\n' "$_ho" | grep -qx 'decision=inactive' && + printf '%s\n' "$_ho" | grep -qx 'reason=opt-out' && + printf '%s\n' "$_ho" | grep -qx 'legacy=' && + [ "$_hc" = "$_hcalled" ] && [ "$_hbefore" = "$_hafter" ]; then + echo "ok ${_hr##*/}: fallback=$_hfb helper=$_hc, legacy attempt unchanged" + else + echo "FAIL ${_hr##*/}: want fallback=$_hfb helper=$_hc; got helper=$_hcalled attempt=$_hbefore/$_hafter: $_ho" + fail=1 + fi + if [ "$_hfb" = none ]; then + if ! printf '%s\n' "$_ho" | grep -qx 'software=' || + ! printf '%s\n' "$_ho" | grep -qx 'marker=' || + ! printf '%s\n' "$_ho" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "FAIL ${_hr##*/}: system admission exports or state detail: $_ho"; fail=1 + fi + else + if ! printf '%s\n' "$_ho" | grep -qx 'software=1' || + ! printf '%s\n' "$_ho" | grep -qx 'marker=software' || + printf '%s\n' "$_ho" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "FAIL ${_hr##*/}: recovery exports or state detail: $_ho"; fail=1 + fi + fi +} +HRA=$(system_root user-optout air) +rm "$HRA/etc/mesa-m3/disable" +mkdir -p "$HRA$T/home/.config/mesa-m3" +: > "$HRA$T/home/.config/mesa-m3/disable" +handoff "$HRA" none yes +if [ "$(cat "$HRA/opt/mesa-m3/libexec/system-check.args")" = "$(printf '/dev/dri/renderD128\nt8122')" ] && + grep -qx 'PATH=/usr/bin:/bin' "$HRA/opt/mesa-m3/libexec/system-check.env" && + [ -z "$(grep -vE '^(PATH=/usr/bin:/bin|PWD=.*|SHLVL=[0-9]+|_=.*)$' "$HRA/opt/mesa-m3/libexec/system-check.env")" ]; then + echo 'ok handoff: helper receives exact device/SoC and empty selector environment' +else echo 'FAIL handoff: helper argv/environment'; fail=1; fi +HRP=$(system_root root-optout pro) +handoff "$HRP" none yes +handoff "$HRP" none yes LIBGL_ALWAYS_SOFTWARE=1 MESA_M3_FALLBACK=software +for mode in fail sleep; do + HR=$(system_root "probe-$mode" pro) + : > "$HR/opt/mesa-m3/libexec/system-check.$mode" + handoff "$HR" software yes +done +for mode in missing not-executable; do + HR=$(system_root "probe-$mode" pro) + if [ "$mode" = missing ]; then rm "$HR/opt/mesa-m3/libexec/mesa-m3-system-check"; + else chmod 600 "$HR/opt/mesa-m3/libexec/mesa-m3-system-check"; fi + handoff "$HR" software no +done +for mode in missing-cmdline missing-detector; do + HR=$(system_root "$mode" pro) + if [ "$mode" = missing-cmdline ]; then rm "$HR/proc/cmdline"; + else rm "$HR/opt/mesa-m3/libexec/mesa-m3-user-setup"; fi + handoff "$HR" software no +done +for flag in mesa_m3=off nomodeset; do + HR=$(system_root "kernel-$flag" pro) + echo "root=UUID=x rw $flag quiet" > "$HR/proc/cmdline" + handoff "$HR" software no +done +for journal in noperm error match bank dcp g15g verdict; do + HR=$(system_root "journal-$journal" pro) + handoff "$HR" software no FAKE_JOURNAL="$journal" +done +for dt in 'apple,j615 apple,t8122' 'apple,j514s apple,t6030' \ + 'apple,j614s apple,t6030' 'apple,j613 apple,j615 apple,t8122' \ + 'apple,j613 apple,t6030' 'apple,j516s apple,t6030 apple,t8122'; do + HR=$(system_root "board-$(printf '%s' "$dt" | tr ' ,' '--')" pro) + nul $dt > "$HR/proc/device-tree/compatible" + # Match the GPU to the ambiguous board's first SoC so the old fallback + # remains observable; the system handoff must still refuse it. + case "$dt" in *t8122*) nul apple,agx-t8122 apple,agx-t6030 > "$HR/sys/devices/platform/gpu0/of_node/compatible" ;; esac + handoff "$HR" software no +done +HR=$(system_root no-display pro) +rm "$HR/sys/class/drm/card2/device" +handoff "$HR" software no +HR=$(system_root wrong-display pro) +nul apple,t8122-display-subsystem > "$HR/sys/devices/platform/display/of_node/compatible" +handoff "$HR" software no +HR=$(system_root two-nodes pro) +mkdir "$HR/sys/class/drm/renderD129" +handoff "$HR" software no +for variable in LIBGL_ALWAYS_SOFTWARE=1 \ + LD_LIBRARY_PATH=/opt/mesa-m3/lib \ + VK_DRIVER_FILES=/opt/mesa-m3/share/vulkan/icd.d/asahi_icd.aarch64.json \ + __EGL_VENDOR_LIBRARY_FILENAMES=/opt/mesa-m3/share/glvnd/egl_vendor.d/50_mesa.json \ + ASAHI_M3_EXPERIMENTAL=1 XDG_CURRENT_DESKTOP=chonkstep; do + HR=$(system_root "override-${variable%%=*}" pro) + handoff "$HR" software no "$variable" +done +for value in 'LIBGL_DRIVERS_PATH=/opt/mesa-m3/lib/dri' 'VK_DRIVER_FILES=$UNKNOWN'; do + HR=$(system_root "late-${value%%=*}" pro) + mkdir -p "$HR$T/home/.config/uwsm" + printf '%s\n' "$value" > "$HR$T/home/.config/uwsm/env" + handoff "$HR" software no +done +HR=$(system_root failed-legacy-login pro) +HATT="$HR$T/home/.local/state/mesa-m3/attempt" +HOK="$HR$T/home/.local/state/mesa-m3/session-ok" +mkdir -p "${HATT%/*}" +printf 'schema=aurora.mesa-m3-attempt/2\nboot_id=boot-a\nsession_id=5\nhook_run_id=old-run\n' > "$HATT" +handoff "$HR" software no +printf 'schema=aurora.mesa-m3-session-ok/1\nboot_id=boot-a\nsession_id=wrong\nhook_run_id=old-run\n' > "$HOK" +handoff "$HR" software no +sed -i 's/session_id=wrong/session_id=5/' "$HOK" +handoff "$HR" none yes +rm "$HOK" +sed -i 's/boot_id=boot-a/boot_id=old-boot/' "$HATT" +handoff "$HR" none yes + [ "$fail" = 0 ] && echo "ALL PASS" || echo "SOME FAILED" exit "$fail" diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c new file mode 100644 index 00000000000000..1aa86befdcdba2 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: MIT */ +/* Pure board-parser controls: no device opening or EGL calls. */ +#define main system_check_main +#include "../mesa-m3-system-check.c" +#undef main +#include + +#define CHECK(expected, soc, bytes) \ + assert(board_compat_matches(bytes, sizeof(bytes) - 1, soc) == (expected)) + +int main(void) +{ + CHECK(true, "t8122", "apple,j613\0apple,t8122\0apple,arm-platform\0"); + CHECK(true, "t6030", "apple,j516s\0apple,t6030\0apple,arm-platform\0"); + CHECK(true, "t6030", "apple,arm-platform\0apple,t6030\0apple,j516s\0"); + CHECK(false, "t8122", "apple,j615\0apple,t8122\0"); + CHECK(false, "t6030", "apple,j514s\0apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6031\0"); + CHECK(false, "t8122", "apple,j613\0apple,j615\0apple,t8122\0"); + CHECK(false, "t8122", "apple,j613\0apple,j613\0apple,t8122\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6030\0apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0apple,t6030\0apple,t8122\0"); + CHECK(false, "t8122", "apple,j613\0apple,t8122-extra\0"); + CHECK(false, "t8122", "apple,j613\0apple,t8122"); + CHECK(false, "t8122", "apple,j613\0\0apple,t8122\0"); + CHECK(false, "t6030", "apple,t6030\0"); + CHECK(false, "t6030", "apple,j516s\0"); + CHECK(false, "t8140", "apple,j516s\0apple,t6030\0"); + CHECK(false, "t6030", ""); + puts("17 board parser controls passed"); + return 0; +} diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py new file mode 100644 index 00000000000000..5efc680580b867 --- /dev/null +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""The system-provider decision must see legacy selectors as overrides.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +RECIPE = Path(__file__).resolve().parents[1] + + +class SystemProviderTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.home = "/home/tester" + (self.root / "home/tester/.config").mkdir(parents=True) + prefix = self.root / "opt/mesa-m3/lib" + prefix.mkdir(parents=True) + (prefix / "libgallium-26.1.4.so").touch() + + def run_detector(self, environment=None, system=True): + command = [str(RECIPE / "mesa-m3-user-setup"), "--home", self.home, + "--root", str(self.root), "--list", str(RECIPE / "user-setup.list"), + "--session-desktops", "Hyprland", "--env"] + if system: + command.append("--system-provider") + return subprocess.run(command, env={"PATH": "/usr/bin:/bin", "HOME": self.home, + **(environment or {})}, + capture_output=True, text=True, timeout=10) + + def test_clean_setup(self): + self.assertEqual(self.run_detector().returncode, 0) + + def test_legacy_path_default_stays_accepted(self): + value = {"VK_DRIVER_FILES": "/opt/mesa-m3/share/vulkan/icd.d/asahi.json"} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_legacy_loader_path_is_not_system_mesa(self): + value = {"LD_LIBRARY_PATH": "/opt/mesa-m3/lib"} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_later_config_can_reselect_legacy_mesa(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("export LIBGL_DRIVERS_PATH=/opt/mesa-m3/lib/dri\n") + self.assertEqual(self.run_detector(system=False).returncode, 0) + self.assertEqual(self.run_detector().returncode, 1) + + def test_explicit_software_choice(self): + self.assertEqual(self.run_detector({"LIBGL_ALWAYS_SOFTWARE": "1"}).returncode, 1) + + def test_only_owned_software_pair_is_ignored(self): + self.assertEqual(self.run_detector({"LIBGL_ALWAYS_SOFTWARE": "1", + "MESA_M3_FALLBACK": "software"}).returncode, 0) + + def test_preload_and_legacy_flags_are_not_clean_system_environment(self): + for variable in ("LD_PRELOAD", "LD_AUDIT", "MESA_M3_SESSION", + "ASAHI_M3_EXPERIMENTAL", "AGX_MESA_DEBUG"): + with self.subTest(variable=variable): + # File assignments avoid loading a preload into the test + # interpreter itself while exercising the same detector. + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(exist_ok=True) + (folder / "env").write_text(variable + "=/opt/mesa-m3/choice\n") + self.assertEqual(self.run_detector().returncode, 1) + + def test_missing_file_does_not_mask_unresolved_choice(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("VK_DRIVER_FILES=$OTHER_MESA\n") + result = self.run_detector() + self.assertNotEqual(result.returncode, 0, result.stdout) + + +if __name__ == "__main__": + unittest.main() From a2be09cbc13042caf67bb34733f93e030d7d6439 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 18:55:36 +1000 Subject: [PATCH 0065/1514] mesa-m3: refuse hidden providers and bound the system-Mesa handoff The handoff probe runs in a clean environment against /usr, but the desktop keeps the session's own setup. Under --system-provider, also refuse an LD_LIBRARY_PATH entry that holds its own libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm, treat a relative entry as unknown, and refuse GBM_BACKEND, __GLX_VENDOR_LIBRARY_NAME and the Mesa GL/GLES/GLSL version overrides. The legacy gate keeps its existing rules. Run the whole admission in its own sh under one 20-second timeout, so a stalled journal, home directory or scanner refuses and keeps the software fallback instead of holding the login. Run the handoff cases under the suite's own shell so the bash run covers the new path, add stall and override cases, document that the helper does not render and that a later failure is not recorded, and bump pkgrel to 7 with the new checksums. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 8 ++-- .../recipes/mesa-m3/mesa-m3-session-env | 20 ++++++++-- .../recipes/mesa-m3/mesa-m3-user-setup | 19 +++++++++- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 16 ++++++++ .../recipes/mesa-m3/tests/test-session-env.sh | 30 ++++++++++++++- .../mesa-m3/tests/test-system-provider.py | 37 +++++++++++++++++++ .../recipes/mesa-m3/user-setup.list | 3 ++ 7 files changed, 122 insertions(+), 11 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index a120de243b1e1f..aca33a6c849525 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -10,7 +10,7 @@ # No profile selection substitutes another Mac's firmware or calibration. pkgname=mesa-m3 pkgver=26.1.4.m3.2 -pkgrel=6 +pkgrel=7 _commit=7ff89a4da387bd561b78efd5f09c98ca8ae18538 pkgdesc="Mesa in /opt/mesa-m3 for the M3 Pro (G15S) and M3 (G15G) GPUs; used by uwsm sessions on T6030, and on T8122 when opted in" arch=('aarch64') @@ -85,14 +85,14 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '10abda78df16e650a77443f50cc46a15e418c42d4d9680c6a61616b232c9bdef' '6c98fab6f9d70449bd7f5258c34eac773836908e060ce5bef86dc5b0ce595e61' '826016665cd0424a614b67add921c0c79c3c698a4d104ea5712518449b75f27c' - '444fd73d505c3ffa7252bb44845457deac2550a411464bbcec075e14f21b2063' + '9cbc38f4bee27ab72d4a288f2741ab1eeb70112ca473a5c98a9695cdfcbe56f7' '6144af8b2e0f04ea615e8c4149e69c45ac49e630c46b2a58f0d1095d977798b2' '530948fc1a124de21c030a497e2ef5351742ba4ad4653484fe30fd1697ad7141' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - 'a446e2b3fa075a1ef239439539119eb12472b372a84ecb9411c4e65ca3112999' - '8f19ebea2b8e669a764d7c4b40ecbc11e8234acfc3a2bfe7910e22de0b64a49d' + '5052ece23b7b028e8762fbf0322a967237861da504cb4dd95fa7f3aace1fd6fe' + '4cae43d33e9fd8b7f703d433b74814968662982c7342c60f059c32eb45648f8a' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env index 3308a963e8f1ba..a90c3b5d2bc143 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env @@ -72,7 +72,8 @@ # J613 (T8122) or a J516S (T6030) is the exception: when the same node, # display, kernel-log, user-setup and same-boot attempt checks pass and # mesa-m3-system-check admits /usr, the session keeps system Mesa -# (fallback=none, no new attempt). mesa_m3=off stays on the software fallback. +# (fallback=none, no new attempt). The whole check runs in its own sh and is +# refused after 20 seconds. mesa_m3=off stays on the software fallback. # # Each login writes /run/user//mesa-m3-session.state (atomically, 0644, # key=value lines, first line schema=aurora.mesa-m3-session/2) and logs one @@ -450,6 +451,16 @@ _mm3_system_admit() { printf '%s\n' "system Mesa on /usr admits /dev/dri/${_mm3_node##*/} ($_mm3_chip); /opt/mesa-m3 stays inactive" } +# _mm3_system_admit in its own sh, under one timeout for the whole check. A +# stalled journal, home directory or scanner would otherwise hold this login +# before any fallback is exported. A timeout refuses, as any failure does. +_mm3_system_admit_bounded() { + _mm3_self=${1:-}/opt/mesa-m3/libexec/mesa-m3-session-env + [ -r "$_mm3_self" ] || return 1 + timeout -k 2 20 sh -c 'MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" && _mm3_p=$3 && _mm3_system_admit "$2"' \ + sh "$_mm3_self" "${1:-}" "$_mm3_p" +} + # _mm3_state ROOT DECISION REASON DETAIL FALLBACK: write the state file and the journal # line. A value holding a newline or carriage return is refused. _mm3_state() { @@ -557,7 +568,7 @@ mesa_m3_session_env() { _mm3_detail=${_mm3_decision#* } _mm3_admitted=0 if [ "${_mm3_decision%% *}" = opt-out ]; then - _mm3_sys=$(_mm3_system_admit "${1:-}") + _mm3_sys=$(_mm3_system_admit_bounded "${1:-}") if [ "$?" -eq 0 ]; then _mm3_admitted=1 _mm3_detail="$_mm3_detail; $_mm3_sys" @@ -583,11 +594,12 @@ if [ -z "${MESA_M3_SESSION_ENV_NO_RUN:-}" ]; then mesa_m3_session_env unset -f mesa_m3_gate mesa_m3_session_env _mm3_init _mm3_state _mm3_node_open _mm3_attempt \ _mm3_soc_of _mm3_25g83_board _mm3_native_display _mm3_kernel_log \ - _mm3_legacy_attempt_clear _mm3_system_admit + _mm3_legacy_attempt_clear _mm3_system_admit _mm3_system_admit_bounded fi unset _mm3_root _mm3_p _mm3_nodes _mm3_node _mm3_n _mm3_drv _mm3_dcp _mm3_c _mm3_dev _mm3_f _mm3_v \ _mm3_val _mm3_ifs _mm3_d _mm3_out _mm3_rc _mm3_decision _mm3_on \ _mm3_so _mm3_uid _mm3_sid _mm3_inv _mm3_ver _mm3_boot _mm3_cr _mm3_nl \ _mm3_body _mm3_kv _mm3_dir _mm3_tmp _mm3_fb _mm3_run _mm3_att _mm3_ok _mm3_faults _mm3_ign _mm3_igd \ _mm3_soc _mm3_name _mm3_dt _mm3_base _mm3_profile _mm3_requested _mm3_files _mm3_gate_ifs _mm3_board _mm3_note \ - _mm3_klog _mm3_sys _mm3_admitted _mm3_detail _mm3_helper _mm3_chip _mm3_identity _mm3_socs _mm3_cmdline + _mm3_klog _mm3_sys _mm3_admitted _mm3_detail _mm3_helper _mm3_chip _mm3_identity _mm3_socs _mm3_cmdline \ + _mm3_self diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index 80a459b2c2551b..5df557a1102198 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -22,7 +22,10 @@ see the comments there. any environment file); empty or absent: unknown --root DIR prefix every path with DIR (tests) --system-provider also refuse legacy /opt selectors and session flags when - checking whether the real desktop will use system Mesa + checking whether the real desktop will use system Mesa; + an LD_LIBRARY_PATH entry then also counts when it holds + only libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm, + and a relative entry makes the result "unknown" Nothing is sourced or evaluated. Files are read as text and split into words the way a POSIX shell would (quotes, backslashes, comments, ";"), with no @@ -259,9 +262,13 @@ class Finder: # These may be left over from an active legacy session. The # admission helper's clean environment cannot prove that the # real desktop will use /usr while these remain in its setup. + # The rest choose the desktop's GL/GBM provider or its version, + # which the clean-environment helper never sees. for name in ('LD_PRELOAD', 'LD_AUDIT', 'MESA_M3_SESSION', 'MESA_M3_PROFILE', 'ASAHI_M3_EXPERIMENTAL', 'AGX_MESA_DEBUG', 'HK_DEBUG_LOG', - 'VK_LOADER_LAYERS_DISABLE', 'QSG_RHI_BACKEND'): + 'VK_LOADER_LAYERS_DISABLE', 'QSG_RHI_BACKEND', + 'GBM_BACKEND', '__GLX_VENDOR_LIBRARY_NAME', 'MESA_GL_VERSION_OVERRIDE', + 'MESA_GLES_VERSION_OVERRIDE', 'MESA_GLSL_VERSION_OVERRIDE'): self.kind[name] = 'flag' def real(self, p): @@ -319,6 +326,11 @@ class Finder: def holds_mesa(self, d): r = self.real(d) pats = ('libgallium*', 'libEGL_mesa*', 'libvulkan_asahi*', 'dri/*_dri.so') + if self.o['system_provider']: + # Any of these replaces what the desktop loads from /usr, even + # without a Mesa driver of its own next to it. + pats += ('libEGL.so*', 'libEGL_*', 'libGLESv2.so*', 'libGL.so*', 'libGLX*', + 'libglapi.so*', 'libgbm.so*', 'gbm/*') return any(glob.glob(os.path.join(glob.escape(r), p)) for p in pats) def expand_home(self, s): @@ -361,6 +373,9 @@ class Finder: continue if '$' in comp or '`' in comp: note(place, f'{label} puts an unresolved entry in {name} ({comp})', sure=False) + elif not comp.startswith('/') and self.o['system_provider']: + # Resolved against whatever directory the desktop starts in. + note(place, f'{label} puts a relative entry in {name} ({comp})', sure=False) elif comp.startswith('/') and not self.ours(comp) and self.holds_mesa(os.path.normpath(comp)): note(place, f'{label} puts another Mesa in {name} ({os.path.normpath(comp)})') return diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md index dbe150d387dc08..e24eeed6f15864 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -13,6 +13,14 @@ A bounded helper then opens the exact EGL device using only `/usr` libraries and verifies its native renderer and loaded implementation paths. It creates a context but makes no draw, swap or compute calls. +With `--system-provider`, the user-setup check also refuses settings the +clean-environment helper cannot see: an `LD_LIBRARY_PATH` entry holding its +own libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm (relative entries +are unknown), and `GBM_BACKEND`, `__GLX_VENDOR_LIBRARY_NAME` and the Mesa +GL/GLES/GLSL version overrides. The whole admission runs in its own `sh` +under a 20-second timeout, so a stalled journal, home directory or scanner +refuses instead of holding the login. + A failed check keeps the existing software fallback. `mesa_m3=off` and `nomodeset` remain recovery choices. Other boards, including J615, remain outside this system handoff. Explicit legacy profile selection is unchanged. @@ -21,6 +29,14 @@ Only the exact software-fallback pair previously exported by this hook can be cleared. The state remains `inactive`, `reason=opt-out`, `fallback=none` when system Mesa admission succeeds. +The helper proves only that the system EGL device and a context open. It does +not allocate GBM buffers, render or present. A system-Mesa login that passes +admission and then fails later is not recorded: this path writes no attempt, +so the legacy success-marker check cannot see it, and the next login is +admitted again. Recover with `mesa_m3=off` on the kernel command line or by +removing the opt-out file. Separate system-Mesa attempt and success markers +would make that recovery automatic. + Run the host checks from this directory (a writable TMPDIR may be needed): ```sh diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh index 6c7b2eb659b6fc..c23665597b6e34 100755 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh @@ -10,6 +10,9 @@ T=$(mktemp -d) trap 'rm -rf "$T"' EXIT fail=0 UID_=$(id -u) +# The shell this suite runs under, for the cases that must exercise it. +TSH=sh +[ -z "${BASH_VERSION:-}" ] || TSH=bash mkdir -p "$T/bin" "$T/home" # journalctl, as the hook calls it (the whole kernel log of this boot): @@ -36,6 +39,7 @@ verdictok) normal; echo "asahi 292400000.gpu: M3 G15G verdict: firmware-running: g15g) normal; echo "asahi 292400000.gpu: M3 G15G: firmware crashed, retained crashlog bytes=4096" ;; noperm) : ;; error) echo "Failed to open journal: Permission denied" >&2; exit 1 ;; +stall) sleep 60; normal ;; esac exit 0 J @@ -686,6 +690,8 @@ env | sort > "$here/system-check.env" [ ! -e "$here/system-check.fail" ] H chmod +x "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" + # The bounded admission sources the installed hook again in its own sh. + cp "$ENVFILE" "$_hr/opt/mesa-m3/libexec/mesa-m3-session-env" echo "$_hr" } handoff() { # ROOT FALLBACK HELPER_CALLED [VAR=value...] @@ -696,7 +702,7 @@ handoff() { # ROOT FALLBACK HELPER_CALLED [VAR=value...] _hbefore=missing [ ! -f "$_ha" ] || _hbefore=$(sha256sum "$_ha" | cut -d' ' -f1) _ho=$(env -i PATH="$T/bin:/usr/bin:/bin" HOME="$T/home" FAKE_LOG="$T/log" \ - XDG_CURRENT_DESKTOP=Hyprland "$@" sh -c ' + XDG_CURRENT_DESKTOP=Hyprland "$@" "$TSH" -c ' MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" mesa_m3_session_env "$2" printf "software=%s\nmarker=%s\nlegacy=%s\n" "${LIBGL_ALWAYS_SOFTWARE:-}" "${MESA_M3_FALLBACK:-}" "${MESA_M3_SESSION:-}" @@ -802,6 +808,28 @@ for value in 'LIBGL_DRIVERS_PATH=/opt/mesa-m3/lib/dri' 'VK_DRIVER_FILES=$UNKNOWN printf '%s\n' "$value" > "$HR$T/home/.config/uwsm/env" handoff "$HR" software no done +for variable in GBM_BACKEND=nvidia-drm MESA_GL_VERSION_OVERRIDE=4.6; do + HR=$(system_root "override-${variable%%=*}" pro) + handoff "$HR" software no "$variable" +done +HR=$(system_root no-installed-hook pro) +rm "$HR/opt/mesa-m3/libexec/mesa-m3-session-env" +handoff "$HR" software no +# A stalled journal or scanner refuses within the bound (20 s, then 2 s to +# kill) and keeps the software fallback, instead of holding the login. +HR=$(system_root stalled-journal pro) +_hstart=$(date +%s) +handoff "$HR" software no FAKE_JOURNAL=stall +_hspent=$(( $(date +%s) - _hstart )) +if [ "$_hspent" -le 30 ]; then echo "ok stalled-journal: refused after ${_hspent}s" +else echo "FAIL stalled-journal: took ${_hspent}s"; fail=1; fi +HR=$(system_root stalled-detector pro) +printf '#!/bin/sh\nsleep 60\n' > "$HR/opt/mesa-m3/libexec/mesa-m3-user-setup" +_hstart=$(date +%s) +handoff "$HR" software no +_hspent=$(( $(date +%s) - _hstart )) +if [ "$_hspent" -le 30 ]; then echo "ok stalled-detector: refused after ${_hspent}s" +else echo "FAIL stalled-detector: took ${_hspent}s"; fail=1; fi HR=$(system_root failed-legacy-login pro) HATT="$HR$T/home/.local/state/mesa-m3/attempt" HOK="$HR$T/home/.local/state/mesa-m3/session-ok" diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 5efc680580b867..1d6b99eaea314d 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -67,6 +67,43 @@ def test_preload_and_legacy_flags_are_not_clean_system_environment(self): (folder / "env").write_text(variable + "=/opt/mesa-m3/choice\n") self.assertEqual(self.run_detector().returncode, 1) + def test_loader_only_directories_are_another_provider(self): + for library in ("libEGL.so.1", "libGLESv2.so.2", "libGL.so.1", "libGLX_mesa.so.0", + "libglapi.so.0", "libgbm.so.1", "gbm/dri_gbm.so"): + with self.subTest(library=library): + folder = self.root / "provider" / library.replace("/", "-") + (folder / library).parent.mkdir(parents=True, exist_ok=True) + (folder / library).touch() + value = {"LD_LIBRARY_PATH": "/provider/" + library.replace("/", "-")} + self.assertEqual(self.run_detector(value, system=False).returncode, 0) + self.assertEqual(self.run_detector(value).returncode, 1) + + def test_unrelated_library_directory_stays_clean(self): + (self.root / "provider/other").mkdir(parents=True) + (self.root / "provider/other/libfoo.so.1").touch() + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/provider/other"}).returncode, 0) + + def test_relative_loader_entry_is_unknown(self): + for value in ("lib", "./lib", "/usr/lib/extra:lib"): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}, system=False).returncode, 0) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + + def test_provider_and_version_overrides(self): + for variable, value in (("GBM_BACKEND", "nvidia-drm"), + ("__GLX_VENDOR_LIBRARY_NAME", "nvidia"), + ("MESA_GL_VERSION_OVERRIDE", "4.6"), + ("MESA_GLES_VERSION_OVERRIDE", "3.2"), + ("MESA_GLSL_VERSION_OVERRIDE", "460")): + with self.subTest(variable=variable): + self.assertEqual(self.run_detector({variable: value}, system=False).returncode, 0) + self.assertEqual(self.run_detector({variable: value}).returncode, 1) + folder = self.root / "home/tester/.config/hypr" + folder.mkdir(parents=True, exist_ok=True) + (folder / "env.conf").write_text(f"env = {variable},{value}\n") + self.assertEqual(self.run_detector().returncode, 1) + (folder / "env.conf").unlink() + def test_missing_file_does_not_mask_unresolved_choice(self): folder = self.root / "home/tester/.config/uwsm" folder.mkdir() diff --git a/tools/aurora-sep/recipes/mesa-m3/user-setup.list b/tools/aurora-sep/recipes/mesa-m3/user-setup.list index 0bd73c8f394f6c..6661c1dd5b8cfc 100644 --- a/tools/aurora-sep/recipes/mesa-m3/user-setup.list +++ b/tools/aurora-sep/recipes/mesa-m3/user-setup.list @@ -15,6 +15,9 @@ # file, for an assignment that replaces it (does not keep # $LD_LIBRARY_PATH), since that drops /opt/mesa-m3/lib after the # session hook ran. Unrelated entries added to it are no finding. +# With --system-provider, an entry holding libEGL, libGLESv2, libGL, +# libGLX, libglapi, libgbm or a gbm/ directory is a finding too, and +# a relative entry is unknown. # envfile a file that sets session variables, searched for the variables # above. Shell, environment.d and /etc/environment lines are split # like a POSIX shell (quotes, comments, "export", ";"); Hyprland From c957b4449c6ca089055f7ec4f8430db9fa41a23c Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 19:05:04 +1000 Subject: [PATCH 0066/1514] mesa-m3: parse LD_LIBRARY_PATH like glibc for the system handoff glibc also splits LD_LIBRARY_PATH on ";" and reads an empty entry as the current directory, so ":", "/a:" or "/a;/b" could still hide another provider from --system-provider. Split on both and treat a real empty entry as unknown. A reference to the previous value still counts as no entry. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 4 ++-- .../recipes/mesa-m3/mesa-m3-user-setup | 20 ++++++++++++---- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 12 ++++++---- .../mesa-m3/tests/test-system-provider.py | 23 +++++++++++++++++++ .../recipes/mesa-m3/user-setup.list | 5 ++-- 5 files changed, 50 insertions(+), 14 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index aca33a6c849525..0e9b7b2b0a7c92 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -91,8 +91,8 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '5052ece23b7b028e8762fbf0322a967237861da504cb4dd95fa7f3aace1fd6fe' - '4cae43d33e9fd8b7f703d433b74814968662982c7342c60f059c32eb45648f8a' + '3a04f0b3fd3e137b5b12fba73f41cbc6d4a5935c61145d9738bb4e0e8ee09bf0' + 'c9c37dead02e3098e69e85a1f0fea73b6244ce2b497e57e85127ea9341b91664' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index 5df557a1102198..0f1db53250cfd3 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -24,8 +24,9 @@ see the comments there. --system-provider also refuse legacy /opt selectors and session flags when checking whether the real desktop will use system Mesa; an LD_LIBRARY_PATH entry then also counts when it holds - only libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm, - and a relative entry makes the result "unknown" + only libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm; + entries split on ":" and ";", and a relative or empty + entry makes the result "unknown" Nothing is sourced or evaluated. Files are read as text and split into words the way a POSIX shell would (quotes, backslashes, comments, ";"), with no @@ -365,10 +366,19 @@ class Finder: note(place, f'{label} replaces {name} (without ${name})') return # Drop the references to the previous value (also ${NAME:+:$NAME}). + # For a system-provider check they leave a mark instead, so that + # an empty entry left by the removal is not taken for a real one. + strict = self.o['system_provider'] + prev = '\0' if strict else '' rest = re.sub(r'\$\{' + re.escape(name) + r'(?::?[-+=?][^}]*)?\}|\$' + re.escape(name) + r'(?![A-Za-z0-9_])', - '', value) - for comp in rest.split(':'): - comp = self.expand_home(comp.strip()) + prev, value) + # glibc's loader also splits on ";" and reads an empty entry as + # the current directory. + for comp in (re.split('[:;]', rest) if strict else rest.split(':')): + if strict and comp.strip() == '': + note(place, f'{label} puts an empty entry in {name} (the current directory)', sure=False) + continue + comp = self.expand_home(comp.replace('\0', '').strip()) if comp == '': continue if '$' in comp or '`' in comp: diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md index e24eeed6f15864..ddfa0afa41cd97 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -15,11 +15,13 @@ a context but makes no draw, swap or compute calls. With `--system-provider`, the user-setup check also refuses settings the clean-environment helper cannot see: an `LD_LIBRARY_PATH` entry holding its -own libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm (relative entries -are unknown), and `GBM_BACKEND`, `__GLX_VENDOR_LIBRARY_NAME` and the Mesa -GL/GLES/GLSL version overrides. The whole admission runs in its own `sh` -under a 20-second timeout, so a stalled journal, home directory or scanner -refuses instead of holding the login. +own libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm, and +`GBM_BACKEND`, `__GLX_VENDOR_LIBRARY_NAME` and the Mesa GL/GLES/GLSL version +overrides. It splits `LD_LIBRARY_PATH` on `:` and `;` as glibc does, and a +relative or empty entry (the current directory) is unknown. The admission +returns within a 20-second timeout, so a stalled journal, home directory or +scanner refuses instead of holding the login. The helper keeps its own +5-second timeout. A failed check keeps the existing software fallback. `mesa_m3=off` and `nomodeset` remain recovery choices. Other boards, including J615, remain diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 1d6b99eaea314d..8aecf03d92dd83 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -89,6 +89,29 @@ def test_relative_loader_entry_is_unknown(self): self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}, system=False).returncode, 0) self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + def test_loader_path_parsed_like_glibc(self): + (self.root / "provider/other").mkdir(parents=True) + (self.root / "provider/evil").mkdir(parents=True) + (self.root / "provider/evil/libEGL.so.1").touch() + for value, code in ((":", 3), ("/provider/other:", 3), (":/provider/other", 3), + ("/provider/other::/usr/lib/extra", 3), + ("/provider/other;/provider/evil", 1)): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, code) + + def test_previous_value_reference_is_not_an_empty_entry(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + (self.root / "provider/other").mkdir(parents=True) + for line in ("export LD_LIBRARY_PATH=/provider/other:$LD_LIBRARY_PATH\n", + "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n", + "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/provider/other\n"): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector().returncode, 0) + (folder / "env").write_text("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\n") + self.assertEqual(self.run_detector().returncode, 3) + def test_provider_and_version_overrides(self): for variable, value in (("GBM_BACKEND", "nvidia-drm"), ("__GLX_VENDOR_LIBRARY_NAME", "nvidia"), diff --git a/tools/aurora-sep/recipes/mesa-m3/user-setup.list b/tools/aurora-sep/recipes/mesa-m3/user-setup.list index 6661c1dd5b8cfc..1a6e6bd888f4cd 100644 --- a/tools/aurora-sep/recipes/mesa-m3/user-setup.list +++ b/tools/aurora-sep/recipes/mesa-m3/user-setup.list @@ -16,8 +16,9 @@ # $LD_LIBRARY_PATH), since that drops /opt/mesa-m3/lib after the # session hook ran. Unrelated entries added to it are no finding. # With --system-provider, an entry holding libEGL, libGLESv2, libGL, -# libGLX, libglapi, libgbm or a gbm/ directory is a finding too, and -# a relative entry is unknown. +# libGLX, libglapi, libgbm or a gbm/ directory is a finding too; +# entries split on ":" and ";" as glibc does, and a relative or +# empty entry (the current directory) is unknown. # envfile a file that sets session variables, searched for the variables # above. Shell, environment.d and /etc/environment lines are split # like a POSIX shell (quotes, comments, "export", ";"); Hyprland From f8b900f2dd25024200006a67eebce89677684ec0 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 19:14:27 +1000 Subject: [PATCH 0067/1514] mesa-m3: expand LD_LIBRARY_PATH references with the inherited value A placeholder for $LD_LIBRARY_PATH hid the current-directory entry that "/a:$LD_LIBRARY_PATH" or "${LD_LIBRARY_PATH}:/a" leave when the inherited value is unset or empty. For --system-provider, expand plain references with the inherited value and ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} as the shell does, treat any other form as unknown, and ignore a wholly empty value as glibc does. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 2 +- .../recipes/mesa-m3/mesa-m3-user-setup | 42 ++++++++++++++----- .../mesa-m3/tests/test-system-provider.py | 30 +++++++++---- 3 files changed, 53 insertions(+), 21 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index 0e9b7b2b0a7c92..da82358e9202de 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -91,7 +91,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '3a04f0b3fd3e137b5b12fba73f41cbc6d4a5935c61145d9738bb4e0e8ee09bf0' + 'f89871d26ee542df9ba41ffa42aceebe48f8fd7fe7d82cd1d4ed1b51d019a2d4' 'c9c37dead02e3098e69e85a1f0fea73b6244ce2b497e57e85127ea9341b91664' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index 0f1db53250cfd3..a09a558aabbda2 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -255,6 +255,7 @@ class Finder: self.paths, self.details, self.findings = [], [], [] self.present = self.unknown = False self.cur_kind = None + self.env = None self.kind = {} for k, i in items: if k in ('variable', 'flag', 'prefix', 'ldpath'): @@ -365,20 +366,38 @@ class Finder: # while the other Mesa variables still point into the prefix. note(place, f'{label} replaces {name} (without ${name})') return - # Drop the references to the previous value (also ${NAME:+:$NAME}). - # For a system-provider check they leave a mark instead, so that - # an empty entry left by the removal is not taken for a real one. + ref = r'\$\{' + re.escape(name) + r'(?::?[-+=?][^}]*)?\}|\$' + re.escape(name) + r'(?![A-Za-z0-9_])' strict = self.o['system_provider'] - prev = '\0' if strict else '' - rest = re.sub(r'\$\{' + re.escape(name) + r'(?::?[-+=?][^}]*)?\}|\$' + re.escape(name) + r'(?![A-Za-z0-9_])', - prev, value) - # glibc's loader also splits on ";" and reads an empty entry as - # the current directory. - for comp in (re.split('[:;]', rest) if strict else rest.split(':')): + if not strict: + # Drop the references to the previous value (also ${NAME:+:$NAME}). + rest = re.sub(ref, '', value) + comps = rest.split(':') + else: + # Expand them with the inherited value instead: "/a:$NAME" with + # NAME unset leaves "/a:", whose empty entry glibc's loader + # reads as the current directory. Only plain references and + # ${NAME:+:$NAME} have a known result. glibc also splits on ";" + # and ignores a wholly empty value. + prev = (self.env or {}).get(name, '') + plain = ('$' + name, '${' + name + '}') + cond = tuple('${' + name + ':+:' + r + '}' for r in plain) + def expand(m): + t = m.group(0) + if t in plain: + return prev + if t in cond: + return ':' + prev if prev else '' + return '\0' + rest = re.sub(ref, expand, value) + comps = re.split('[:;]', rest) if rest.strip() else [] + for comp in comps: + if strict and '\0' in comp: + note(place, f'{label} uses {name} in a form whose result is not known', sure=False) + continue if strict and comp.strip() == '': - note(place, f'{label} puts an empty entry in {name} (the current directory)', sure=False) + note(place, f'{label} leaves an empty entry in {name} (the current directory)', sure=False) continue - comp = self.expand_home(comp.replace('\0', '').strip()) + comp = self.expand_home(comp.strip()) if comp == '': continue if '$' in comp or '`' in comp: @@ -522,6 +541,7 @@ class Finder: 'uses its own default prefix') def run(self, env): + self.env = env if env is not None: self.check_env(env, 'the environment') env_prefix = env.get('CHONKSTEP_M3_MESA_PREFIX') if env else None diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 8aecf03d92dd83..40841a56153a3c 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -99,18 +99,30 @@ def test_loader_path_parsed_like_glibc(self): with self.subTest(value=value): self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, code) - def test_previous_value_reference_is_not_an_empty_entry(self): + def test_previous_value_expands_like_the_shell(self): folder = self.root / "home/tester/.config/uwsm" folder.mkdir(parents=True) (self.root / "provider/other").mkdir(parents=True) - for line in ("export LD_LIBRARY_PATH=/provider/other:$LD_LIBRARY_PATH\n", - "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n", - "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/provider/other\n"): - with self.subTest(line=line): - (folder / "env").write_text(line) - self.assertEqual(self.run_detector().returncode, 0) - (folder / "env").write_text("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:\n") - self.assertEqual(self.run_detector().returncode, 3) + plain_after = "export LD_LIBRARY_PATH=/provider/other:$LD_LIBRARY_PATH\n" + plain_before = "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/provider/other\n" + conditional = "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n" + other_form = "export LD_LIBRARY_PATH=/provider/other:${LD_LIBRARY_PATH:-/x}\n" + # inherited value: unset, empty, set + for inherited, expect in ((None, {plain_after: 3, plain_before: 3, conditional: 0}), + ("", {plain_after: 3, plain_before: 3, conditional: 0}), + ("/usr/lib/extra", {plain_after: 0, plain_before: 0, conditional: 0})): + environment = {} if inherited is None else {"LD_LIBRARY_PATH": inherited} + for line, code in expect.items(): + with self.subTest(inherited=inherited, line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector(environment).returncode, code) + (folder / "env").write_text(other_form) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/usr/lib/extra"}).returncode, 3) + (folder / "env").write_text(conditional) + self.assertEqual(self.run_detector(system=False).returncode, 0) + + def test_empty_inherited_value_is_no_entry(self): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": ""}).returncode, 0) def test_provider_and_version_overrides(self): for variable, value in (("GBM_BACKEND", "nvidia-drm"), From 6d31ee13cda1ed74b823c521dddc5615d0fd17b3 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 19:19:37 +1000 Subject: [PATCH 0068/1514] mesa-m3: count a plain LD_LIBRARY_PATH reference as possibly empty An earlier file can unset LD_LIBRARY_PATH, so its inherited value does not show what "/a:$LD_LIBRARY_PATH" expands to. For --system-provider, take a plain reference as empty, accept ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} and its ${...} spelling, keep spaces in an entry as glibc does, and treat only a truly empty value as no entry. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 4 +-- .../recipes/mesa-m3/mesa-m3-user-setup | 34 ++++++++----------- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 4 ++- .../mesa-m3/tests/test-system-provider.py | 14 +++++--- .../recipes/mesa-m3/user-setup.list | 4 ++- 5 files changed, 32 insertions(+), 28 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index da82358e9202de..3b356fe63d475d 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -91,8 +91,8 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - 'f89871d26ee542df9ba41ffa42aceebe48f8fd7fe7d82cd1d4ed1b51d019a2d4' - 'c9c37dead02e3098e69e85a1f0fea73b6244ce2b497e57e85127ea9341b91664' + 'e1b592b6c0981627f2c0649294cbf41c703cc29f3e2c95e67771524e6cfc592d' + '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index a09a558aabbda2..b092a7e0de82e5 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -255,7 +255,6 @@ class Finder: self.paths, self.details, self.findings = [], [], [] self.present = self.unknown = False self.cur_kind = None - self.env = None self.kind = {} for k, i in items: if k in ('variable', 'flag', 'prefix', 'ldpath'): @@ -366,38 +365,34 @@ class Finder: # while the other Mesa variables still point into the prefix. note(place, f'{label} replaces {name} (without ${name})') return - ref = r'\$\{' + re.escape(name) + r'(?::?[-+=?][^}]*)?\}|\$' + re.escape(name) + r'(?![A-Za-z0-9_])' + n = re.escape(name) + ref = (r'\$\{' + n + r':\+:\$\{' + n + r'\}\}|\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + + r'(?![A-Za-z0-9_])') strict = self.o['system_provider'] if not strict: # Drop the references to the previous value (also ${NAME:+:$NAME}). rest = re.sub(ref, '', value) comps = rest.split(':') else: - # Expand them with the inherited value instead: "/a:$NAME" with - # NAME unset leaves "/a:", whose empty entry glibc's loader - # reads as the current directory. Only plain references and - # ${NAME:+:$NAME} have a known result. glibc also splits on ";" - # and ignores a wholly empty value. - prev = (self.env or {}).get(name, '') + # The previous value may be empty here (unset, or cleared by an + # earlier file), and then "/a:$NAME" leaves "/a:", whose empty + # entry glibc's loader reads as the current directory. So a + # plain reference counts as empty; ${NAME:+:$NAME} adds nothing + # then and is the safe form. Any other form is unknown. glibc + # also splits on ";" and ignores a wholly empty value. plain = ('$' + name, '${' + name + '}') cond = tuple('${' + name + ':+:' + r + '}' for r in plain) - def expand(m): - t = m.group(0) - if t in plain: - return prev - if t in cond: - return ':' + prev if prev else '' - return '\0' - rest = re.sub(ref, expand, value) - comps = re.split('[:;]', rest) if rest.strip() else [] + rest = re.sub(ref, lambda m: '' if m.group(0) in plain + cond else '\0', value) + comps = re.split('[:;]', rest) if rest != '' else [] for comp in comps: if strict and '\0' in comp: note(place, f'{label} uses {name} in a form whose result is not known', sure=False) continue - if strict and comp.strip() == '': + if strict and comp == '': note(place, f'{label} leaves an empty entry in {name} (the current directory)', sure=False) continue - comp = self.expand_home(comp.strip()) + # glibc takes an entry as written, spaces included. + comp = self.expand_home(comp if strict else comp.strip()) if comp == '': continue if '$' in comp or '`' in comp: @@ -541,7 +536,6 @@ class Finder: 'uses its own default prefix') def run(self, env): - self.env = env if env is not None: self.check_env(env, 'the environment') env_prefix = env.get('CHONKSTEP_M3_MESA_PREFIX') if env else None diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md index ddfa0afa41cd97..c5b7c978049197 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -18,7 +18,9 @@ clean-environment helper cannot see: an `LD_LIBRARY_PATH` entry holding its own libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm, and `GBM_BACKEND`, `__GLX_VENDOR_LIBRARY_NAME` and the Mesa GL/GLES/GLSL version overrides. It splits `LD_LIBRARY_PATH` on `:` and `;` as glibc does, and a -relative or empty entry (the current directory) is unknown. The admission +relative or empty entry (the current directory) is unknown. A plain +`$LD_LIBRARY_PATH` reference counts as empty, because an earlier file may +have cleared it; `${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}` passes. The admission returns within a 20-second timeout, so a stalled journal, home directory or scanner refuses instead of holding the login. The helper keeps its own 5-second timeout. diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 40841a56153a3c..4b051e34ff2f4d 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -107,10 +107,11 @@ def test_previous_value_expands_like_the_shell(self): plain_before = "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/provider/other\n" conditional = "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n" other_form = "export LD_LIBRARY_PATH=/provider/other:${LD_LIBRARY_PATH:-/x}\n" - # inherited value: unset, empty, set - for inherited, expect in ((None, {plain_after: 3, plain_before: 3, conditional: 0}), - ("", {plain_after: 3, plain_before: 3, conditional: 0}), - ("/usr/lib/extra", {plain_after: 0, plain_before: 0, conditional: 0})): + nested = "export LD_LIBRARY_PATH=/provider/other${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n" + # An earlier file can clear the inherited value, so a plain reference + # counts as possibly empty even when the session inherits one. + for inherited in (None, "", "/usr/lib/extra"): + expect = {plain_after: 3, plain_before: 3, conditional: 0, nested: 0} environment = {} if inherited is None else {"LD_LIBRARY_PATH": inherited} for line, code in expect.items(): with self.subTest(inherited=inherited, line=line): @@ -124,6 +125,11 @@ def test_previous_value_expands_like_the_shell(self): def test_empty_inherited_value_is_no_entry(self): self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": ""}).returncode, 0) + def test_spaces_are_a_relative_entry(self): + for value in (" ", "/usr/lib/extra: "): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + def test_provider_and_version_overrides(self): for variable, value in (("GBM_BACKEND", "nvidia-drm"), ("__GLX_VENDOR_LIBRARY_NAME", "nvidia"), diff --git a/tools/aurora-sep/recipes/mesa-m3/user-setup.list b/tools/aurora-sep/recipes/mesa-m3/user-setup.list index 1a6e6bd888f4cd..31f55e501f0885 100644 --- a/tools/aurora-sep/recipes/mesa-m3/user-setup.list +++ b/tools/aurora-sep/recipes/mesa-m3/user-setup.list @@ -18,7 +18,9 @@ # With --system-provider, an entry holding libEGL, libGLESv2, libGL, # libGLX, libglapi, libgbm or a gbm/ directory is a finding too; # entries split on ":" and ";" as glibc does, and a relative or -# empty entry (the current directory) is unknown. +# empty entry (the current directory) is unknown. A plain reference +# to the previous value counts as empty, since an earlier file can +# clear it; ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} is the safe form. # envfile a file that sets session variables, searched for the variables # above. Shell, environment.d and /etc/environment lines are split # like a POSIX shell (quotes, comments, "export", ";"); Hyprland From a32b265d83234cadff64af9cfae9360aa6a37853 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 19:24:56 +1000 Subject: [PATCH 0069/1514] mesa-m3: refuse LD_LIBRARY_PATH references joined to other text "${LD_LIBRARY_PATH}/x" or "/a$LD_LIBRARY_PATH" name a directory the detector cannot see, so for --system-provider a reference counts only when it stands alone between separators; anything else is unknown. Take the environment's own value literally, and keep the legacy gate's parsing exactly as it was. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 2 +- .../recipes/mesa-m3/mesa-m3-user-setup | 26 ++++++++++++----- .../mesa-m3/tests/test-system-provider.py | 28 +++++++++++++++++++ 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index 3b356fe63d475d..8b0f9912be7c36 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -91,7 +91,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - 'e1b592b6c0981627f2c0649294cbf41c703cc29f3e2c95e67771524e6cfc592d' + '263c17b51d750d3bee1329e2e57ab806ab06f652fd65580443c32e37c2114736' '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index b092a7e0de82e5..75c3ecc37809c6 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -366,23 +366,35 @@ class Finder: note(place, f'{label} replaces {name} (without ${name})') return n = re.escape(name) - ref = (r'\$\{' + n + r':\+:\$\{' + n + r'\}\}|\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + - r'(?![A-Za-z0-9_])') strict = self.o['system_provider'] if not strict: # Drop the references to the previous value (also ${NAME:+:$NAME}). - rest = re.sub(ref, '', value) + rest = re.sub(r'\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + r'(?![A-Za-z0-9_])', '', value) comps = rest.split(':') + elif place.startswith('environment:'): + # Already expanded: taken literally, as glibc does. + comps = re.split('[:;]', value) if value != '' else [] else: # The previous value may be empty here (unset, or cleared by an # earlier file), and then "/a:$NAME" leaves "/a:", whose empty # entry glibc's loader reads as the current directory. So a - # plain reference counts as empty; ${NAME:+:$NAME} adds nothing - # then and is the safe form. Any other form is unknown. glibc - # also splits on ";" and ignores a wholly empty value. + # plain reference counts as empty, and ${NAME:+:$NAME} (which + # then adds nothing) is the safe form. A reference must stand + # alone between separators: "${NAME}/x" names a directory we + # cannot see. Anything else is unknown. glibc also splits on + # ";" and ignores a wholly empty value. + ref = (r'\$\{' + n + r':\+:\$\{' + n + r'\}\}|\$\{' + n + r'(?::?[-+=?][^}]*)?\}|\$' + n + + r'(?![A-Za-z0-9_])') plain = ('$' + name, '${' + name + '}') cond = tuple('${' + name + ':+:' + r + '}' for r in plain) - rest = re.sub(ref, lambda m: '' if m.group(0) in plain + cond else '\0', value) + sep = (':', ';') + rest, at = '', 0 + for m in re.finditer(ref, value): + t, before, after = m.group(0), value[m.start() - 1:m.start()], value[m.end():m.end() + 1] + alone = (after in ('',) + sep) and (t in cond or before in ('',) + sep) + rest += value[at:m.start()] + ('' if alone and t in plain + cond else '\0') + at = m.end() + rest += value[at:] comps = re.split('[:;]', rest) if rest != '' else [] for comp in comps: if strict and '\0' in comp: diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 4b051e34ff2f4d..565f288e98fd6a 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -125,6 +125,34 @@ def test_previous_value_expands_like_the_shell(self): def test_empty_inherited_value_is_no_entry(self): self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": ""}).returncode, 0) + def test_reference_with_a_suffix_is_unknown(self): + (self.root / "provider/suffix").mkdir(parents=True) + (self.root / "provider/suffix/libEGL.so.1").touch() + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line in ("export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}/suffix\n", + "export LD_LIBRARY_PATH=/a${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}/suffix\n", + "export LD_LIBRARY_PATH=/prefix$LD_LIBRARY_PATH\n"): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/provider"}).returncode, 3) + + def test_environment_value_is_literal(self): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "$LD_LIBRARY_PATH"}).returncode, 3) + + def test_legacy_ldpath_rules_are_unchanged(self): + (self.root / "provider/mesa").mkdir(parents=True) + (self.root / "provider/mesa/libgallium-26.so").touch() + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line, code in (("export LD_LIBRARY_PATH=/x:$LD_LIBRARY_PATH\n", 0), + ("export LD_LIBRARY_PATH=/provider/mesa:$LD_LIBRARY_PATH\n", 1), + ("export LD_LIBRARY_PATH=lib:$LD_LIBRARY_PATH\n", 0), + ("export LD_LIBRARY_PATH=/x::$LD_LIBRARY_PATH\n", 0)): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector(system=False).returncode, code) + def test_spaces_are_a_relative_entry(self): for value in (" ", "/usr/lib/extra: "): with self.subTest(value=value): From dacd5ca0e34341ff3472568af20ca68676599426 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Sun, 25 Oct 2026 19:29:53 +1000 Subject: [PATCH 0070/1514] mesa-m3: no empty entry from a leading conditional LD_LIBRARY_PATH append "${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" with nothing before it expands to ":/prev", a current-directory entry, so for --system-provider a conditional append needs an entry before it. Do not expand ~ or $HOME in the environment's own value either; glibc does not. Signed-off-by: Marcelo Alcantara Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 2 +- .../recipes/mesa-m3/mesa-m3-user-setup | 13 ++++++++++--- .../mesa-m3/tests/test-system-provider.py | 16 +++++++++++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index 8b0f9912be7c36..bfae006a487842 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -91,7 +91,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '263c17b51d750d3bee1329e2e57ab806ab06f652fd65580443c32e37c2114736' + '093a9029dbc6cb43e1c2997baa9c591f29df86d6b242f7f36dbf32add29ba103' '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index 75c3ecc37809c6..f06c5d9f6312d9 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -391,7 +391,10 @@ class Finder: rest, at = '', 0 for m in re.finditer(ref, value): t, before, after = m.group(0), value[m.start() - 1:m.start()], value[m.end():m.end() + 1] - alone = (after in ('',) + sep) and (t in cond or before in ('',) + sep) + # A conditional append needs an entry before it, or it + # starts the value with an empty entry. + edge = ('',) + sep + alone = after in edge and ((before not in edge) if t in cond else (before in edge)) rest += value[at:m.start()] + ('' if alone and t in plain + cond else '\0') at = m.end() rest += value[at:] @@ -403,8 +406,12 @@ class Finder: if strict and comp == '': note(place, f'{label} leaves an empty entry in {name} (the current directory)', sure=False) continue - # glibc takes an entry as written, spaces included. - comp = self.expand_home(comp if strict else comp.strip()) + # glibc takes an entry as written, spaces included, and an + # environment value has no ~ or $HOME left to expand. + if not strict: + comp = self.expand_home(comp.strip()) + elif not place.startswith('environment:'): + comp = self.expand_home(comp) if comp == '': continue if '$' in comp or '`' in comp: diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index 565f288e98fd6a..f66a74c4dfffad 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -138,7 +138,21 @@ def test_reference_with_a_suffix_is_unknown(self): self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/provider"}).returncode, 3) def test_environment_value_is_literal(self): - self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "$LD_LIBRARY_PATH"}).returncode, 3) + (self.root / "home/tester/provider").mkdir(parents=True) + (self.root / "home/tester/provider/libEGL.so.1").touch() + for value in ("$LD_LIBRARY_PATH", "$HOME/provider", "~/provider"): + with self.subTest(value=value): + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": value}).returncode, 3) + + def test_conditional_append_needs_an_entry_before_it(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir(parents=True) + for line in ("export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n", + "export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n", + "export LD_LIBRARY_PATH=/x:${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\n"): + with self.subTest(line=line): + (folder / "env").write_text(line) + self.assertEqual(self.run_detector({"LD_LIBRARY_PATH": "/usr/lib/extra"}).returncode, 3) def test_legacy_ldpath_rules_are_unchanged(self): (self.root / "provider/mesa").mkdir(parents=True) From b2e162ffae554041e2a29b05fe72fc8686524666 Mon Sep 17 00:00:00 2001 From: Chris Kearney <303316+chriskearney@users.noreply.github.com> Date: Sun, 25 Oct 2026 04:05:04 -0700 Subject: [PATCH 0071/1514] mesa-m3: refuse unresolved Bash append overrides Bash accepts NAME+=VALUE in POSIX mode, but the scanner only recognizes NAME=VALUE. A late uwsm export such as LIBGL_ALWAYS_SOFTWARE+=1 therefore passes the system-provider check before selecting software rendering. Report tracked append assignments as unknown in system-provider mode, keeping the software recovery path. Leave the default legacy scanner unchanged. Exercise Bash's actual result and the complete handoff under both shells, and bump the package release with its updated checksum. Signed-off-by: Chris Kearney <303316+chriskearney@users.noreply.github.com> Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 4 +-- .../recipes/mesa-m3/mesa-m3-user-setup | 18 ++++++++--- .../recipes/mesa-m3/tests/test-session-env.sh | 3 +- .../mesa-m3/tests/test-system-provider.py | 32 +++++++++++++++++++ 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index bfae006a487842..2c80497680e0af 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -10,7 +10,7 @@ # No profile selection substitutes another Mac's firmware or calibration. pkgname=mesa-m3 pkgver=26.1.4.m3.2 -pkgrel=7 +pkgrel=8 _commit=7ff89a4da387bd561b78efd5f09c98ca8ae18538 pkgdesc="Mesa in /opt/mesa-m3 for the M3 Pro (G15S) and M3 (G15G) GPUs; used by uwsm sessions on T6030, and on T8122 when opted in" arch=('aarch64') @@ -91,7 +91,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' '9a26a232fd050b6207bd0d385035723f72ffd2b6b72a25d6ac92ae2f99ea5b66' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' - '093a9029dbc6cb43e1c2997baa9c591f29df86d6b242f7f36dbf32add29ba103' + '04fae9bf32a09a574b6ed9ab9d7afb97340df252b9269ed789303e8561a61a21' '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup index f06c5d9f6312d9..7291099ff7cb18 100755 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-user-setup @@ -26,7 +26,8 @@ see the comments there. an LD_LIBRARY_PATH entry then also counts when it holds only libEGL, libGLESv2, libGL, libGLX, libglapi or libgbm; entries split on ":" and ";", and a relative or empty - entry makes the result "unknown" + entry makes the result "unknown"; Bash += assignments + to tracked variables are unknown too Nothing is sourced or evaluated. Files are read as text and split into words the way a POSIX shell would (quotes, backslashes, comments, ";"), with no @@ -189,9 +190,11 @@ def shell_words(line): return words -def shell_assignments(line): +def shell_assignments(line, *, append_unknown=False): """The NAME=VALUE words of one line of shell, environment.d or - /etc/environment text. None when the line cannot be split.""" + /etc/environment text. None when the line cannot be split. With + append_unknown, a Bash NAME+=VALUE word is emitted with a None value, + since its resulting value depends on earlier assignments.""" words = shell_words(line) if words is None: return None @@ -200,6 +203,13 @@ def shell_assignments(line): m = re.match(r'([A-Za-z_][A-Za-z0-9_]*)=(.*)$', w, re.S) if m: out.append((m.group(1), m.group(2))) + elif append_unknown: + # Arch's sh is Bash, which accepts += even in POSIX mode. Its + # value depends on earlier assignments; do not silently ignore + # a late provider override when admitting system Mesa. + m = re.match(r'([A-Za-z_][A-Za-z0-9_]*)\+=(.*)$', w, re.S) + if m: + out.append((m.group(1), None)) return out @@ -523,7 +533,7 @@ class Finder: elif is_hypr: found = hyprlang_assignments(line) else: - found = shell_assignments(line) + found = shell_assignments(line, append_unknown=self.o['system_provider']) if found is None: if any(re.search(rf'(? "$HR$T/home/.config/uwsm/env" diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py index f66a74c4dfffad..e528270b7c9444 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-provider.py @@ -29,6 +29,38 @@ def run_detector(self, environment=None, system=True): **(environment or {})}, capture_output=True, text=True, timeout=10) + def test_bash_append_cannot_override_system_admission_silently(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + config = folder / "env" + cases = (("LIBGL_ALWAYS_SOFTWARE", "1"), + ("LD_LIBRARY_PATH", "/opt/custom/lib")) + for name, value in cases: + with self.subTest(variable=name): + config.write_text("export " + name + "+=" + value + "\n") + # The target's sh is Bash. This is a real assignment in + # POSIX mode, although the legacy parser ignores it. + shell = subprocess.run( + ["bash", "--posix", "-c", + 'unset LIBGL_ALWAYS_SOFTWARE LD_LIBRARY_PATH; . "$1"; ' + 'printf "%s" "${!2}"', "bash", str(config), name], + env={"PATH": "/usr/bin:/bin"}, capture_output=True, + text=True, timeout=10) + self.assertEqual(shell.returncode, 0, shell.stderr) + self.assertEqual(shell.stdout, value) + result = self.run_detector() + self.assertEqual(result.returncode, 3, result.stdout) + self.assertIn(name, result.stdout) + self.assertIn("user_setup=unknown", result.stdout) + # Keep the default legacy decision unchanged. + self.assertEqual(self.run_detector(system=False).returncode, 0) + + def test_unrelated_bash_append_is_not_a_mesa_choice(self): + folder = self.root / "home/tester/.config/uwsm" + folder.mkdir() + (folder / "env").write_text("export MY_TOOLS_PATH+=/tools\n") + self.assertEqual(self.run_detector().returncode, 0) + def test_clean_setup(self): self.assertEqual(self.run_detector().returncode, 0) From 4718d69becb1ed50d0351264a2280fc64ae65d3a Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:55:14 -0600 Subject: [PATCH 0072/1514] soc: apple: show the fabric and DCS clock-generator words in debugfs Read only: apple-pmgr-misc gets one debugfs directory with the whole clock-generator word of the fabric and DCS system devices (fabric_ps and dcs_ps, mode 0400, the desired state in bits 3:0 and the actual state in bits 7:4). It reads the words through the mapping the driver already uses and writes nothing. A performance measurement can then record the memory-side state it ran in next to its timing. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> (cherry picked from commit b50e681fb588da49c7fcbf71bd6a7b499600a6c4; include conflict resolved keeping the regmap include aurora-edge added) --- drivers/soc/apple/apple-pmgr-misc.c | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/drivers/soc/apple/apple-pmgr-misc.c b/drivers/soc/apple/apple-pmgr-misc.c index d18f4ed07d8bb5..41b6befe9432df 100644 --- a/drivers/soc/apple/apple-pmgr-misc.c +++ b/drivers/soc/apple/apple-pmgr-misc.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -701,6 +703,37 @@ static int apple_pmgr_init_device(struct apple_pmgr_misc *misc, return 0; } +/* Read only: the whole clock-generator word of one system device (the desired state is bits 3:0, the actual state bits 7:4), no side effect. */ +static int apple_pmgr_misc_ps_show(struct seq_file *s, void *unused) +{ + const struct apple_pmgr_sys_device *d = s->private; + + seq_printf(s, "%#010x\n", readl_relaxed(d->base + APPLE_CLKGEN_PSTATE)); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(apple_pmgr_misc_ps); + +static void apple_pmgr_misc_debugfs_remove(void *dir) +{ + debugfs_remove(dir); +} + +static void apple_pmgr_misc_debugfs_init(struct apple_pmgr_misc *misc) +{ + static const char * const names[DEV_MAX] = { "fabric_ps", "dcs_ps" }; + char *dirname = devm_kasprintf(misc->dev, GFP_KERNEL, "apple-pmgr-misc-%s", dev_name(misc->dev)); + struct dentry *dir; + int i; + + if (!dirname) + return; + dir = debugfs_create_dir(dirname, NULL); + for (i = 0; i < DEV_MAX; i++) + if (misc->devices[i].base) + debugfs_create_file(names[i], 0400, dir, &misc->devices[i], &apple_pmgr_misc_ps_fops); + devm_add_action_or_reset(misc->dev, apple_pmgr_misc_debugfs_remove, dir); +} + static int apple_pmgr_misc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -728,6 +761,9 @@ static int apple_pmgr_misc_probe(struct platform_device *pdev) platform_set_drvdata(pdev, misc); + if (!ret) + apple_pmgr_misc_debugfs_init(misc); + /* * With PMP enabled its firmware owns the fabric and DCS p-states. * Writing them for suspend as well leaves the system unable to resume From c3688c88f187b1771757f3566cca023608539608 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:10:56 +0000 Subject: [PATCH 0073/1514] arm64: dts: apple: t6050-k114c: the SD card reader (PCIe port 1) The M5 Max MacBook Pro (K114c) has the same SD card reader as the J714s: a GL9755 behind pci-bridge1. Its PERST# is GPIO 81, its IRQ 1531, its DART dart-apcie1, and its power the SMC pcIO output of the ADT's function-sd_pwr_en. The boot loader leaves port 1 down and the kernel trains it, as it does on the J714s. All values are the K114c ADT's and equal the J714s ones. Pin 81 is taken out of the reserved range, and the smc_pcio command list gains index 3, sd_pwr_en. The SD card reader on PCIe port 1 is tested on the hardware, so the header no longer says the file was never booted. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-k114c.dts | 95 ++++++++++++++++++++--- 1 file changed, 86 insertions(+), 9 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 13ea865ba58e14..f9ae02fb85b15d 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -4,7 +4,8 @@ * * target-type: K114c (Mac17,11) * - * Preliminary: described from the ADT only, not yet booted on the hardware. + * Boots on the hardware; the SD card reader (PCIe port 1) is tested. The other + * blocks are described from the ADT. * * Copyright The Asahi Linux Contributors */ @@ -43,14 +44,23 @@ <0x4 0x14000000 0x0 0x4000>, <0x4 0x10028000 0x0 0x8000>, <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0"; - interrupts = ; - interrupt-names = "port0"; + <0x4 0x10024000 0x0 0x4000>, + <0x4 0x11028000 0x0 0x8000>, + <0x4 0x17014000 0x0 0x4000>, + <0x4 0x11024000 0x0 0x4000>, + <0x4 0x17020000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", + "phy-shared"; + interrupts = , + ; + interrupt-names = "port0", "port1"; /* The N1's three functions are on DART streams 1-3 */ - iommu-map = <0x100 &dart_apcie0 1 3>; + iommu-map = <0x100 &dart_apcie0 1 3>, + <0x200 &dart_apcie1 1 1>; bus-range = <0 4>; + /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ + post-init-providers = <&dart_apcie1>; status = "okay"; port00: pci@0,0 { @@ -95,16 +105,83 @@ local-bd-address = [00 00 00 00 00 00]; }; }; + + /* + * PCIe port 1: the SD card reader (ADT pci-bridge1/pcie-sdreader, a GL9755), as on + * J714s. The boot loader leaves it down, so the kernel trains it: power is the SMC + * pcIO output of function-sd_pwr_en (index 3 below), PERST# GPIO 81, IRQ 1531. It is + * on stream 1 of dart-apcie1. The link tunables are pci-bridge1's, as on port 0. + */ + port01: pci@1,0 { + device_type = "pci"; + reg = <0x800 0 0 0 0>; + bus-range = <2 2>; + apple,link-trained-by-bootloader; + pwren-gpios = <&smc_pcio 3 GPIO_ACTIVE_HIGH>; + reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; + apple,apcie-config-tunables = <0x140 4 0x1 0x1>, + <0x144 4 0xffffff 0x253770>, + <0x8a8 4 0x1 0x1>, + <0x8ac 4 0x1 0x1>; + apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, + <0x194 4 0x2 0x2>, + <0xb80 4 0x7f3f3f 0x7f1e1e>, + <0xb88 4 0x7f3f3f 0x7f1e1e>; + apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, + <0x890 4 0x3000000 0x0>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x1000000>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x2000000>, + <0x8a8 4 0xffff0f 0x1>; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port01 0 0 0 0>, + <0 0 0 2 &port01 0 0 0 1>, + <0 0 0 3 &port01 0 0 0 2>, + <0 0 0 4 &port01 0 0 0 3>; + + /* The GL9755; card detect and write protect active high (ADT *-polarity = 1) */ + sdhci0: mmc@0,0 { + compatible = "pci17a0,9755"; + reg = <0x20000 0x0 0x0 0x0 0x0>; + cd-inverted; + wp-inverted; + }; + }; }; /* * Pin 112's register takes an SError when read, so only the pins a node here - * names are exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' - * interrupt and shutdown line; 134 and 139, the jack codec's interrupt and + * names are exposed: 80 and 81 (PCIe ports 0 and 1's PERST#); 106 and 107, the speaker + * amps' interrupt and shutdown line; 134 and 139, the jack codec's interrupt and * reset; 136 and 137, the speaker ID. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; +}; + +/* It answers only once port 1's root complex is up: pcie-apple then enables it */ +&dart_apcie1 { + apple,manual-availability; + status = "okay"; +}; + +/* + * The board's pcIO outputs (t6050-k114-k116.dtsi lists indices 0 to 2), plus index 3, + * sd_pwr_en pKW8('pcIO', 0x0, 0x190000): ADT pcie-sdreader function-sd_pwr_en. + */ +&smc_pcio { + apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 + 0x011c000000010000 0x0019000000000000>; }; #include "t6050-k114c-gpu.dtsi" From b9a7edd802939e1648e535cf9d43f50b8d0f5dea Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:42:53 -0600 Subject: [PATCH 0074/1514] power: supply: macsmc: skip an unreadable manufacture date quietly macsmc_battery_get_date() returns -EOPNOTSUPP when the SMC manufacture date (BMDT) holds no digits. The power supply core skips a property only for -ENODEV, -ENODATA or -EINVAL. For -EOPNOTSUPP it logs an error and aborts, so reading the battery uevent file fails. On a 14-inch M5 Max MacBook Pro the uevent read printed nothing, dmesg held 44 "driver failed to report 'manufacture_year' property: -95" lines, and the synthetic uevent failed with -95. Return -ENODATA so the core treats the date as absent. Add the 1992 year offset only when the date was read. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/power/supply/macsmc-power.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index 5bd714eaf1b276..174ab5138fb645 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -560,7 +560,7 @@ static int macsmc_battery_set_charge_behaviour(struct macsmc_power *power, int v static int macsmc_battery_get_date(const char *s, int *out) { if (!isdigit(s[0]) || !isdigit(s[1])) - return -EOPNOTSUPP; + return -ENODATA; *out = (s[0] - '0') * 10 + s[1] - '0'; return 0; @@ -760,7 +760,8 @@ static int macsmc_battery_get_property(struct power_supply *psy, case POWER_SUPPLY_PROP_MANUFACTURE_YEAR: ret = macsmc_battery_get_date(&power->mfg_date[0], &val->intval); /* The SMC reports the manufacture year as an offset from 1992. */ - val->intval += 1992; + if (!ret) + val->intval += 1992; break; case POWER_SUPPLY_PROP_MANUFACTURE_MONTH: ret = macsmc_battery_get_date(&power->mfg_date[2], &val->intval); From 6bf80ea19a6bdb4e168d2551f282d4d7a18cdfba Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 09:46:28 -0700 Subject: [PATCH 0075/1514] arm64: dts: apple: t6050-k116s: Add the Touch ID sensor The K116s has the J714s's Mesa sensor: spi2, chip select 0, 8 MHz, sensor-id 0x3356, powered by NUB GPIO 21, data ready on AP GPIO 138 (ADT /arm-io/spi2/mesa). Describe it as on the J714s and take pin 138 out of the reserved ranges. The node is Thomas Glanzmann's, from his K116s notes. Suggested-by: Thomas Glanzmann Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-k116s.dts | 41 +++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index fe6468edc72c10..aa78a49f37b0e3 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -37,9 +37,10 @@ /* * Pin 112 takes an SError when read, so only the pins a node names are * exposed: 80/81 (PCIe ports 0 and 1's PERST#), 106/107 (amp fault, amp - * shutdown), 134/139 (jack codec interrupt, reset) and 136/137 (speaker ID). + * shutdown), 134/139 (jack codec interrupt, reset), 136/137 (speaker ID) + * and 138 (Touch ID data ready). */ - gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <140 81>; }; /* @@ -913,3 +914,39 @@ &avd { status = "okay"; }; + +/* + * Touch ID (ADT spi2/mesa): the Mesa sensor on spi2 at 8 MHz, chip select 0, + * powered by NUB GPIO 21 (function-mesa_pwr), data ready on AP GPIO 138, as + * on the J714s. spi2 runs from the 24 MHz reference (ADT clock-ids 451). + */ +&ps_nub_gpio { + status = "okay"; +}; + +&nub_gpio0 { + status = "okay"; +}; + +&ps_spi2 { + status = "okay"; +}; + +&spi2 { + clocks = <&clkref>; + status = "okay"; + + mesa: fingerprint@0 { + compatible = "apple,mesa-fingerprint"; + reg = <0>; + spi-max-frequency = <8000000>; + spi-cpol; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <138 IRQ_TYPE_EDGE_RISING>; + /* Per-device factory data from this Mac's own iBoot system container */ + firmware-name = "apple/mesacal-k116s.bin", "apple/msrk-k116s.bin"; + }; +}; From efbb40ec725d01b8aee91c75856019cb71067e11 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Thu, 19 Nov 2026 06:31:19 -0500 Subject: [PATCH 0076/1514] drm/asahi: g17: select host-only render kicks by firmware capability Use the GPU ID-selected firmware configuration to opt into ungated tiling kicks and host-port-only publication for retained render pairs. The G17C image supports both forms. Keep the established publication for G17S, G17D and the common 26A428 interface pending qualification. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 10 ++++++++++ drivers/gpu/drm/asahi/g17/queue/render.rs | 17 +++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index e4de37f639579b..12248eb88c455a 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -2165,6 +2165,9 @@ pub(crate) struct Board { /// Whether explicit waits on other kicks take the completion class /// ([`Board::completion_inputs`]). completion_inputs: bool, + /// Whether firmware accepts tiling kicks without an entry signal and retained + /// render pairs kicked through the host port alone. + pub(crate) host_only_render_kicks: bool, } /// M5 Pro: two clusters of ten cores. @@ -2195,6 +2198,7 @@ pub(crate) const J714: Board = Board { fan_curve_start_mc: 84_000, g17d_forms: false, completion_inputs: true, + host_only_render_kicks: false, }; /// M5 Max: four clusters of ten cores. @@ -2227,6 +2231,10 @@ pub(crate) const J716C: Board = Board { fan_curve_start_mc: 84_000, g17d_forms: false, completion_inputs: false, + // Qualified on G17C's 26A428 image. G17S uses completion-class inputs, + // G17D has distinct kick encodings, and common 26A428 publishes descriptors + // on the item ring. Qualify those interfaces separately. + host_only_render_kicks: true, }; /// J775D's performance controllers run from P3. @@ -2269,6 +2277,7 @@ pub(crate) const J775D: Board = Board { fan_curve_start_mc: 97_000, g17d_forms: true, completion_inputs: false, + host_only_render_kicks: false, }; /// M5 (T8142, MacBook Air J813): one cluster of ten core slots, eight enabled. Values from the @@ -2309,6 +2318,7 @@ pub(crate) const J813: Board = Board { fan_curve_start_mc: 84_000, g17d_forms: false, completion_inputs: false, + host_only_render_kicks: false, }; const _: () = { diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 1aaa02f91b12bf..b67be9ea29752c 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -906,6 +906,8 @@ impl Pair { // The J813's (common 26A428) items carry configuration, descriptor and announcement in // one publication; macOS 27.0 never publishes a configuration alone there. let j813 = crate::g17::J813_FORMS.load(Ordering::Relaxed); + let host_only_render_kicks = + m5 && !j813 && self.board.is_some_and(|board| board.host_only_render_kicks); if m5 && !j813 && self.registered.is_none() { if self.installed == [true; 2] { // The cold-install configuration pair must be consumed first. @@ -1031,12 +1033,8 @@ impl Pair { }, }, mcache, - // M5 tiling kicks also retain the last event of the mask, except on the J813, whose - // macOS 27.0 TA and 3D kicks name no event at all. The J716C also runs its tiling - // kick ungated: the redundant entry-signal event adds a firmware round trip to a - // lone render and candidate 44 has qualified the zero-event form on this board. - event_mask: if m5 && stage == 0 && !j813 - && !self.board.is_some_and(|board| board.clusters == 4) { + // Common 26A428 and the host-only form use an empty tiling event mask. + event_mask: if m5 && stage == 0 && !j813 && !host_only_render_kicks { [0, 0, 0, 1u64 << 62] } else { abi::RENDER_KICK_EVENT_MASK @@ -1093,13 +1091,12 @@ impl Pair { let tiling_kick = tiling_kick.prepare_entry(&ta_args)?; let fragment_kick = fragment_kick.prepare_entry(&fragment_args)?; let memory = &mut *self.memory; - // J716C retains an installed render pair while work is already in - // flight. In that steady state the host-port kick is sufficient: + // For a firmware that supports host-only kicks, an installed render + // pair with work in flight can use the host-port kick alone: // another item-ring notification has no new configuration or lead // command to publish. Keep the ordinary inner publication for the // first command, a drained restart, a rebind, and a class change. - let sparse_inner = m5 && !j813 - && self.board.is_some_and(|board| board.clusters == 4) + let sparse_inner = host_only_render_kicks && self.active.front().is_some() && self.previous.is_none() && self.registered == Some(policy.priority()) && !self.context_update && !self.identity_update && !present.into_iter().any(|value| value) From 4974acb2234679ece45b4e436d0fa38b60dca8f6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 22:40:05 +1100 Subject: [PATCH 0077/1514] wifi: brcmfmac: report HE 160 MHz only when the firmware can use it brcmf_update_he_cap() fills one fixed HE capability template into every band. It always sets the 160 MHz channel width bit, the 160 MHz HE-MCS map and the 20/80-in-160 MHz PPDU bits, and it sets the 2.4 GHz and the 5/6 GHz width bits on all bands, although IEEE 802.11ax defines them per band. The firmware reports the supported widths per band through the "bw_cap" iovar. brcmf_update_vht_cap() already uses it for VHT 160 MHz, so on a chip without 160 MHz (BCM4387 on the M1 Pro and the M2 Air) the 5 GHz band says "neither 160 nor 80+80" for VHT and "HE160/5GHz" for HE at the same time, and the 2.4 GHz band claims HE160 too. Select the 160 MHz bits and the 160 MHz HE-MCS map from the per-band bw_cap 160 MHz bit, set only the 2.4 GHz width bit on 2.4 GHz and only the 5/6 GHz width bits on 5 GHz and 6 GHz, and set the 20 MHz in 40 MHz 2.4 GHz PPDU bit only on 2.4 GHz. 40/80 MHz on 5 GHz and 6 GHz is kept as before. Chips whose firmware reports 160 MHz keep reporting it. Fixes: 38e7179b37092 ("[brcmfmac] Add support for 6G bands and HE") Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/cfg80211.c | 51 ++++++++++++++----- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c index b61a51dbbce1a3..38d7518645cc77 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c @@ -8565,8 +8565,11 @@ static void brcmf_update_vht_cap(struct ieee80211_supported_band *band, } static void brcmf_update_he_cap(struct ieee80211_supported_band *band, - struct ieee80211_sband_iftype_data *data) + struct ieee80211_sband_iftype_data *data, + u32 bw_cap[4]) { + bool has_160 = band->band != NL80211_BAND_2GHZ && + (bw_cap[band->band] & WLC_BW_160MHZ_BIT); int idx = 1; struct ieee80211_sta_he_cap *he_cap = &data->he_cap; struct ieee80211_he_cap_elem *he_cap_elem = &he_cap->he_cap_elem; @@ -8600,12 +8603,27 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, he_cap_elem->mac_cap_info[4] = IEEE80211_HE_MAC_CAP4_AMSDU_IN_AMPDU; - /* HE PHY Capabilities Information */ - he_cap_elem->phy_cap_info[0] = - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G; - ; + /* + * HE PHY Capabilities Information. + * + * The channel width set is per band (IEEE 802.11ax 9.4.2.248.3): + * B0 is the 2.4 GHz bit, B1 and B2 apply to 5 GHz and 6 GHz. + * 40/80 MHz stays on in 5 GHz and 6 GHz as before (80 MHz is + * mandatory there, see brcmf_update_vht_cap()). 160 MHz follows the + * firmware's per-band "bw_cap", the same source the VHT capability + * uses, so it is only reported when the radio can use it. This runs + * again when the wiphy bands are rebuilt, so set the field whole. + */ + if (band->band == NL80211_BAND_2GHZ) { + he_cap_elem->phy_cap_info[0] = + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G; + } else { + he_cap_elem->phy_cap_info[0] = + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G; + if (has_160) + he_cap_elem->phy_cap_info[0] |= + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G; + } he_cap_elem->phy_cap_info[1] = IEEE80211_HE_PHY_CAP1_LDPC_CODING_IN_PAYLOAD; @@ -8646,10 +8664,14 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, IEEE80211_HE_PHY_CAP7_MAX_NC_1; he_cap_elem->phy_cap_info[8] = - IEEE80211_HE_PHY_CAP8_HE_ER_SU_PPDU_4XLTF_AND_08_US_GI | - IEEE80211_HE_PHY_CAP8_20MHZ_IN_40MHZ_HE_PPDU_IN_2G | - IEEE80211_HE_PHY_CAP8_20MHZ_IN_160MHZ_HE_PPDU | - IEEE80211_HE_PHY_CAP8_80MHZ_IN_160MHZ_HE_PPDU; + IEEE80211_HE_PHY_CAP8_HE_ER_SU_PPDU_4XLTF_AND_08_US_GI; + if (band->band == NL80211_BAND_2GHZ) + he_cap_elem->phy_cap_info[8] |= + IEEE80211_HE_PHY_CAP8_20MHZ_IN_40MHZ_HE_PPDU_IN_2G; + if (has_160) + he_cap_elem->phy_cap_info[8] |= + IEEE80211_HE_PHY_CAP8_20MHZ_IN_160MHZ_HE_PPDU | + IEEE80211_HE_PHY_CAP8_80MHZ_IN_160MHZ_HE_PPDU; he_cap_elem->phy_cap_info[9] = IEEE80211_HE_PHY_CAP9_TX_1024_QAM_LESS_THAN_242_TONE_RU | @@ -8660,8 +8682,9 @@ static void brcmf_update_he_cap(struct ieee80211_supported_band *band, /* HE Supported MCS and NSS Set */ he_mcs->rx_mcs_80 = cpu_to_le16(0xfffa); he_mcs->tx_mcs_80 = cpu_to_le16(0xfffa); - he_mcs->rx_mcs_160 = cpu_to_le16(0xfffa); - he_mcs->tx_mcs_160 = cpu_to_le16(0xfffa); + /* 0xffff: no spatial stream is supported at 160 MHz */ + he_mcs->rx_mcs_160 = cpu_to_le16(has_160 ? 0xfffa : 0xffff); + he_mcs->tx_mcs_160 = cpu_to_le16(has_160 ? 0xfffa : 0xffff); /* HE 6 GHz band capabilities */ if (band->band == NL80211_BAND_6GHZ) { u16 capa = 0; @@ -8790,7 +8813,7 @@ static int brcmf_setup_wiphybands(struct brcmf_cfg80211_info *cfg) txbf_bfe_cap, txbf_bfr_cap, ldpc_cap, stbc_rx, stbc_tx); if (he_enable) - brcmf_update_he_cap(band, &sdata[band->band]); + brcmf_update_he_cap(band, &sdata[band->band], bw_cap); } return 0; From fabc6f24d2bb203a1d38b5ada55bc7f9c3f8e0c7 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:45:00 +1100 Subject: [PATCH 0078/1514] HID: let hid-generic take Apple internal interfaces no driver wants The internal keyboard controllers on Apple laptops (SPI and DockChannel) give every interface the same vendor and product ID. hid-apple, hid-magicmouse and hid-apple-mtp-haptic list that ID with HID_ANY_ID, and each probe returns -ENODEV for the interfaces it does not drive. hid-generic then refuses them too, because __check_hid_generic() only looks at the other drivers' ID tables. So the extra interfaces stay unbound. On the M2 MacBook Air the DockChannel "tp_accel" interface binds to hid-generic during boot (hidraw4) and is unbound again once hid_apple and hid_magicmouse load and the bus reprobes it. On the M4 Pro MacBook Pro "tp-accel" and "mtp" never bind at all. Make __check_hid_generic() ask a driver's match callback, so a driver can decline a device its table covers. Give hid-apple and hid-magicmouse callbacks that keep only the keyboard and trackpad interface types of these controllers; hid-apple-mtp-haptic already has one. Every other device matches as before. Signed-off-by: Ryan Murray --- drivers/hid/hid-apple.c | 19 +++++++++++++++++++ drivers/hid/hid-generic.c | 10 +++++++++- drivers/hid/hid-magicmouse.c | 19 +++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/drivers/hid/hid-apple.c b/drivers/hid/hid-apple.c index 817907dcfa9d9f..72cd46be9a9c82 100644 --- a/drivers/hid/hid-apple.c +++ b/drivers/hid/hid-apple.c @@ -1295,9 +1295,28 @@ static const struct hid_device_id apple_devices[] = { }; MODULE_DEVICE_TABLE(hid, apple_devices); +/* + * Every interface of an internal SPI or DockChannel controller carries the + * controller's IDs. Only the keyboard is ours; leave the others to their own + * driver or to hid-generic. + */ +static bool apple_match(struct hid_device *hdev, bool ignore_special_driver) +{ + if (ignore_special_driver || + (hdev->quirks & HID_QUIRK_IGNORE_SPECIAL_DRIVER)) + return false; + + if ((hdev->bus == BUS_SPI || hdev->bus == BUS_HOST) && + hdev->vendor == SPI_VENDOR_ID_APPLE) + return hdev->type == HID_TYPE_SPI_KEYBOARD; + + return true; +} + static struct hid_driver apple_driver = { .name = "apple", .id_table = apple_devices, + .match = apple_match, .report_fixup = apple_report_fixup, .probe = apple_probe, .remove = apple_remove, diff --git a/drivers/hid/hid-generic.c b/drivers/hid/hid-generic.c index c2de916747dec8..2982206654b278 100644 --- a/drivers/hid/hid-generic.c +++ b/drivers/hid/hid-generic.c @@ -31,7 +31,15 @@ static int __check_hid_generic(struct device_driver *drv, void *data) if (hdrv == &hid_generic) return 0; - return hid_match_device(hdev, hdrv) != NULL; + if (!hid_match_device(hdev, hdrv)) + return 0; + + /* + * A driver with a match callback can decline a device its table + * covers. Ask it, so that a device no other driver will take is not + * left unbound. + */ + return !hdrv->match || hdrv->match(hdev, false); } static bool hid_generic_match(struct hid_device *hdev, diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index cc079c42c58036..f6213895030495 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -2953,9 +2953,28 @@ static const struct hid_device_id magic_mice[] = { }; MODULE_DEVICE_TABLE(hid, magic_mice); +/* + * Every interface of an internal SPI or DockChannel controller carries the + * controller's IDs. Only the trackpad is ours; leave the others to their own + * driver or to hid-generic. + */ +static bool magicmouse_match(struct hid_device *hdev, bool ignore_special_driver) +{ + if (ignore_special_driver || + (hdev->quirks & HID_QUIRK_IGNORE_SPECIAL_DRIVER)) + return false; + + if ((hdev->bus == BUS_SPI || hdev->bus == BUS_HOST) && + hdev->vendor == SPI_VENDOR_ID_APPLE) + return hdev->type == HID_TYPE_SPI_MOUSE; + + return true; +} + static struct hid_driver magicmouse_driver = { .name = "magicmouse", .id_table = magic_mice, + .match = magicmouse_match, .probe = magicmouse_probe, .remove = magicmouse_remove, .report_fixup = magicmouse_report_fixup, From 6bc339728336f4b131fa9dfc6bb86306e243aa54 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:41:48 +1100 Subject: [PATCH 0079/1514] arm64: dts: apple: t6040: enable the ProRes encoder on every M4 Pro The ProRes encoder (ADT apr0), its DART and its SCODEC power domains are SoC blocks with no board wiring, but only t6040-j616s.dts enabled them. The 14-inch MacBook Pro (J614s) and the Mac mini (J773s) have the same T6040 engine, so move the enable into t6040.dtsi. The J616s DTB is byte-identical before and after; the J614s and J773s DTBs gain only the apr0, apr0 DART and three power-domain status lines. Signed-off-by: Ryan --- arch/arm64/boot/dts/apple/t6040-j616s.dts | 25 ---------------------- arch/arm64/boot/dts/apple/t6040.dtsi | 26 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6040-j616s.dts b/arch/arm64/boot/dts/apple/t6040-j616s.dts index e81fb8b6b5d0d7..c6f0778f31500b 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j616s.dts @@ -204,31 +204,6 @@ status = "okay"; }; -/* - * ProRes encoder and its DART. The engine runs with SCODEC_STREAMING (and so - * SCODEC) powered. The driver has built-in power-up rows for it; an optional - * apple/prores-t6041-init.bin replaces them. - */ -&ps_fab1_soc { - status = "okay"; -}; - -&ps_scodec { - status = "okay"; -}; - -&ps_scodec_streaming { - status = "okay"; -}; - -&apr0_dart { - status = "okay"; -}; - -&apr0 { - status = "okay"; -}; - /* * USB4/Thunderbolt on all three Type-C ports: typec0 (left back, ACIO0), * typec1 (left front, ACIO1) and typec2 (right, ACIO2). The loader hands diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index 27fc991fdcc96e..11aad394d3b9b5 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t6040.dtsi @@ -673,4 +673,30 @@ 0x5003c0000 0x5003e4000>; }; +/* + * The ProRes encoder (ADT apr0) and its DART. It has no board wiring, so it + * is enabled on every M4 Pro. The engine runs with SCODEC_STREAMING (and so + * SCODEC) powered. The driver has built-in power-up rows for it; an optional + * apple/prores-t6041-init.bin replaces them. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; + #include "t6040-usb4.dtsi" From 6eb742c264c2ffb2ae6fad0006614b1d32627577 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:39:26 +1100 Subject: [PATCH 0080/1514] arm64: dts: apple: t8122: describe the USB-C dcpext routes on every board The external DCP and its USB-C routes were described only in the shared J613/J615 tree, so the J504 MacBook Pro and the J433/J434 iMacs had no way to drive an external display over USB-C. The hardware is the same on all five T8122 boards: the dcpext, dispext0, ATC display crossbars and DP PHYs sit at the same addresses with the same wiring in each board's device tree, and every board's two USB-C ports are ATC0 and ATC1. Move the dcpext alias, the dcpext node properties and the typec port@3 endpoints to t8122-jxxx.dtsi. The routes stay disabled, as before; the display gate enables them only once the boot loader has readied the external DCP firmware, so boards without that handoff are unchanged at runtime. The J613 and J615 DTBs are identical before and after. Signed-off-by: Ryan --- .../arm64/boot/dts/apple/t8122-j613-j615.dtsi | 71 ------------------- arch/arm64/boot/dts/apple/t8122-jxxx.dtsi | 71 +++++++++++++++++++ 2 files changed, 71 insertions(+), 71 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index dbb9da8d4e36b3..adf676e65cac0e 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -17,7 +17,6 @@ chassis-type = "laptop"; aliases { - dcpext = &dcpext; keyboard = &keyboard; sep = &sep; }; @@ -128,73 +127,3 @@ }; #include "hwmon-laptop.dtsi" - -/* - * One external display on either USB-C port: dcpext is crossbar state 2 of - * each ATC and its DPTX target is the ATC index. The display gate enables it - * and the routes once the boot loader has readied its firmware. - */ -&dcpext { - apple,connector-type = "USB-C"; - phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>; - phy-names = "typec0", "typec1"; - mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>; - mux-control-names = "typec0", "typec1"; - apple,typec-mux-indices = <2 2>; - apple,typec-dptx-phys = <0 1>; - /* RTKit quirks of AsahiLinux/linux#607 (syslog/ioreport acks, kdebug). */ - apple,sync-syslog-ack; - - typec-routes { - #address-cells = <1>; - #size-cells = <0>; - - route@0 { - reg = <0>; - mode-switch; - status = "disabled"; - - port { - dcpext_typec0: endpoint { - remote-endpoint = <&typec0_dcpext>; - }; - }; - }; - - route@1 { - reg = <1>; - mode-switch; - status = "disabled"; - - port { - dcpext_typec1: endpoint { - remote-endpoint = <&typec1_dcpext>; - }; - }; - }; - }; -}; - -&typec0 { - ports { - port@3 { - reg = <3>; - - typec0_dcpext: endpoint { - remote-endpoint = <&dcpext_typec0>; - }; - }; - }; -}; - -&typec1 { - ports { - port@3 { - reg = <3>; - - typec1_dcpext: endpoint { - remote-endpoint = <&dcpext_typec1>; - }; - }; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi index b6cd4ee1c40873..111a31ffb50942 100644 --- a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi @@ -14,6 +14,7 @@ atcphy0 = &atcphy0; atcphy1 = &atcphy1; bluetooth0 = &bluetooth0; + dcpext = &dcpext; serial0 = &serial0; wifi0 = &wifi0; @@ -265,3 +266,73 @@ status = "disabled"; }; }; + +/* + * One external display on either USB-C port: dcpext is crossbar state 2 of + * each ATC and its DPTX target is the ATC index. The display gate enables it + * and the routes once the boot loader has readied its firmware. + */ +&dcpext { + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>; + phy-names = "typec0", "typec1"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>; + mux-control-names = "typec0", "typec1"; + apple,typec-mux-indices = <2 2>; + apple,typec-dptx-phys = <0 1>; + /* RTKit quirks of AsahiLinux/linux#607 (syslog/ioreport acks, kdebug). */ + apple,sync-syslog-ack; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext_typec0: endpoint { + remote-endpoint = <&typec0_dcpext>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext_typec1: endpoint { + remote-endpoint = <&typec1_dcpext>; + }; + }; + }; + }; +}; + +&typec0 { + ports { + port@3 { + reg = <3>; + + typec0_dcpext: endpoint { + remote-endpoint = <&dcpext_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + reg = <3>; + + typec1_dcpext: endpoint { + remote-endpoint = <&dcpext_typec1>; + }; + }; + }; +}; From 13939bca123947d51ed258f9d91afef55ce9d96f Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:42:06 +1100 Subject: [PATCH 0081/1514] arm64: dts: apple: t6040: enable the MSR scaler on every M4 Pro The scaler/CSC block (ADT scaler0, MSR), its DART and its two power domains have no board wiring, but only t6040-j616s.dts enabled them. The J614s and J773s have the same T6040 block, so move the enable into t6040.dtsi. The J616s DTB is byte-identical before and after; the J614s and J773s DTBs gain only the scaler0, scaler0 DART and two power-domain status lines. Signed-off-by: Ryan --- arch/arm64/boot/dts/apple/t6040-j616s.dts | 17 ----------------- arch/arm64/boot/dts/apple/t6040.dtsi | 20 ++++++++++++++++++++ 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6040-j616s.dts b/arch/arm64/boot/dts/apple/t6040-j616s.dts index c6f0778f31500b..135bb71155c2d5 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j616s.dts @@ -187,23 +187,6 @@ }; }; -/* Scaler/CSC (MSR) and its DART, proven on this board. */ -&ps_msr0 { - status = "okay"; -}; - -&ps_msr0_ase_core { - status = "okay"; -}; - -&scaler0_dart { - status = "okay"; -}; - -&scaler0 { - status = "okay"; -}; - /* * USB4/Thunderbolt on all three Type-C ports: typec0 (left back, ACIO0), * typec1 (left front, ACIO1) and typec2 (right, ACIO2). The loader hands diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index 11aad394d3b9b5..bd938aaaba81c2 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t6040.dtsi @@ -673,6 +673,26 @@ 0x5003c0000 0x5003e4000>; }; +/* + * The scaler/CSC (ADT scaler0, MSR) and its DART. It has no board wiring, + * so it is enabled on every M4 Pro. + */ +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + /* * The ProRes encoder (ADT apr0) and its DART. It has no board wiring, so it * is enabled on every M4 Pro. The engine runs with SCODEC_STREAMING (and so From d673241248d63397c6289274b54ddb4a7507457b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 22:50:34 +1100 Subject: [PATCH 0082/1514] iio: aop_sensors: bind als-temp and devmotion6 wherever the AOP offers them The AOP core creates a platform device for every sensor service its firmware announces, named after the service. The als-temp and devmotion6 drivers only matched the device tree compatibles "apple,aop-als-temp" and "apple,aop-devmotion6", and only the T6040/T6041 and T8132 device trees describe those services. On the M1 Pro (T6000) and the M2 (T8112) the firmware announces both services, so als-temp.N.auto and devmotion6.N.auto are created, but nothing binds to them. Register each platform driver under the name of its AOP service. The platform bus then binds it by name to the device the AOP core created, so the firmware's announcement of the service decides whether the driver binds, not a list of device trees. The module aliases change to the device's modalias (platform:als-temp, platform:devmotion6) so that the module loads automatically. The OF match tables stay, so machines whose device tree describes the services bind as before. devmotion6 needs nothing from the device tree. The temperature sensor reads optional calibration from its node; without a node it now uses the sensor defaults, which is what it does today when the bootloader supplies no calibration. The drivers and the T6040/T6041 description come from linux#1054 and linux#1247. Signed-off-by: Ryan Murray --- .../iio/common/aop_sensors/aop_devmotion.rs | 29 ++++++-- drivers/iio/common/aop_sensors/aop_temp.rs | 66 +++++++++++++------ 2 files changed, 72 insertions(+), 23 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_devmotion.rs b/drivers/iio/common/aop_sensors/aop_devmotion.rs index e392c1435bbd4d..44d5a88cd7902f 100644 --- a/drivers/iio/common/aop_sensors/aop_devmotion.rs +++ b/drivers/iio/common/aop_sensors/aop_devmotion.rs @@ -18,7 +18,7 @@ use kernel::{ bindings, c_str, device::{self, Core}, dma::Coherent, - module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform, + driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, AOP}, sync::{ @@ -29,6 +29,7 @@ use kernel::{ time::{self, delay::fsleep, Delta}, types::{ForeignOwnable, Opaque}, workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, + ThisModule, }; const SUBTYPE_GET_PROPERTY: u16 = 10; @@ -989,10 +990,30 @@ impl platform::Driver for IIOAopDevMotionDriver { } } -module_platform_driver! { - type: IIOAopDevMotionDriver, +/// The AOP core creates the device of a service, named after the service, +/// whenever the firmware announces that service. Registering the driver under +/// the same name lets the platform bus bind it on every machine whose AOP +/// offers the service, with or without a device tree node for it. +const SERVICE_NAME: &CStr = c_str!("devmotion6"); + +#[pin_data] +struct IIOAopDevMotionModule { + #[pin] + _driver: driver::Registration>, +} + +impl kernel::InPlaceModule for IIOAopDevMotionModule { + fn init(module: &'static ThisModule) -> impl PinInit { + try_pin_init!(Self { + _driver <- driver::Registration::new(SERVICE_NAME, module), + }) + } +} + +module! { + type: IIOAopDevMotionModule, name: "iio_aop_devmotion", description: "AOP device-motion fusion driver", license: "Dual MIT/GPL", - alias: ["platform:iio_aop_devmotion"], + alias: ["platform:devmotion6"], } diff --git a/drivers/iio/common/aop_sensors/aop_temp.rs b/drivers/iio/common/aop_sensors/aop_temp.rs index e74ddb231ec4ab..af4ba06224e523 100644 --- a/drivers/iio/common/aop_sensors/aop_temp.rs +++ b/drivers/iio/common/aop_sensors/aop_temp.rs @@ -6,6 +6,10 @@ //! Its fake-HID report carries a signed Q16.16 Celsius value and an AOP //! timestamp. Calibration data, when supplied by the bootloader, is sent //! unchanged before reports are enabled. +//! +//! The AOP core creates a device for the service whenever the firmware +//! announces it, and the driver binds to that device by name. A device tree +//! node for the service is optional; it only carries the calibration. use core::{ ffi::{c_int, c_void}, @@ -16,7 +20,7 @@ use core::{ use kernel::{ bindings, c_str, device::{self, Core}, - module_platform_driver, new_spinlock, of, platform, + driver, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ @@ -25,6 +29,7 @@ use kernel::{ Arc, SpinLock, }, types::{ForeignOwnable, Opaque}, + ThisModule, }; const SUBTYPE_SET_PROPERTY: u16 = 4; @@ -81,23 +86,26 @@ struct Control { impl Control { fn new(dev: &device::Device, aop: Arc, service: EPICService) -> Result> { - let node = dev.fwnode().ok_or(ENODEV)?; let mut packets = KVec::new(); - for (prop, name) in CALIBRATION { - if !node.property_present(name) { - continue; + // Without a device tree node for the service there is no calibration + // to send; the sensor then runs on its defaults. + if let Some(node) = dev.fwnode() { + for (prop, name) in CALIBRATION { + if !node.property_present(name) { + continue; + } + let len = node.property_count_elem::(name)?; + let data = node + .property_read_array_vec::(name, len)? + .required_by(dev)?; + let Some(packet) = location0_packet(&data) else { + dev_err!(dev, "{:?} holds no calibration for location 0\n", name); + return Err(EINVAL); + }; + let mut owned = KVec::new(); + owned.extend_from_slice(packet, GFP_KERNEL)?; + packets.push((prop, owned), GFP_KERNEL)?; } - let len = node.property_count_elem::(name)?; - let data = node - .property_read_array_vec::(name, len)? - .required_by(dev)?; - let Some(packet) = location0_packet(&data) else { - dev_err!(dev, "{:?} holds no calibration for location 0\n", name); - return Err(EINVAL); - }; - let mut owned = KVec::new(); - owned.extend_from_slice(packet, GFP_KERNEL)?; - packets.push((prop, owned), GFP_KERNEL)?; } if packets.is_empty() { dev_dbg!( @@ -562,10 +570,30 @@ impl platform::Driver for IIOAopTempDriver { } } -module_platform_driver! { - type: IIOAopTempDriver, +/// The AOP core creates the device of a service, named after the service, +/// whenever the firmware announces that service. Registering the driver under +/// the same name lets the platform bus bind it on every machine whose AOP +/// offers the service, with or without a device tree node for it. +const SERVICE_NAME: &CStr = c_str!("als-temp"); + +#[pin_data] +struct IIOAopTempModule { + #[pin] + _driver: driver::Registration>, +} + +impl kernel::InPlaceModule for IIOAopTempModule { + fn init(module: &'static ThisModule) -> impl PinInit { + try_pin_init!(Self { + _driver <- driver::Registration::new(SERVICE_NAME, module), + }) + } +} + +module! { + type: IIOAopTempModule, name: "iio_aop_temp", description: "AOP temperature sensor driver", license: "Dual MIT/GPL", - alias: ["platform:iio_aop_temp"], + alias: ["platform:als-temp"], } From 2108db4f492d05262d2fd057bd111464998f06b6 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:55:21 +1100 Subject: [PATCH 0083/1514] arm64: dts: apple: t8132-laptop: describe the trackpad actuator on every M4 laptop The MTP firmware on every M4 MacBook offers the trackpad's haptic engine as its "actuator" interface (ADT /arm-io/dockchannel-mtp/mtp-transport/ actuator on the J604, J713 and J715). Only the J604's tree described it, so on the MacBook Airs the click stays firmware-driven and there is no Force Touch stage. Describe it in the shared laptop file and drop the J604 copy. The J604 tree is unchanged; the J713 and J715 gain the actuator node. Signed-off-by: Ryan --- arch/arm64/boot/dts/apple/t8132-j604.dts | 4 ---- arch/arm64/boot/dts/apple/t8132-laptop.dtsi | 9 +++++++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j604.dts b/arch/arm64/boot/dts/apple/t8132-j604.dts index 0bbf299e6afca6..9d3b772eebdfdc 100644 --- a/arch/arm64/boot/dts/apple/t8132-j604.dts +++ b/arch/arm64/boot/dts/apple/t8132-j604.dts @@ -327,10 +327,6 @@ multi-touch { firmware-name = "apple/tpmtfw-j604.bin"; }; - - /* J604 ADT /arm-io/dockchannel-mtp/mtp-transport/actuator: Force Touch */ - actuator { - }; }; /* diff --git a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi index c6a1a5ee78297e..1b14a5f06dd34d 100644 --- a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi @@ -141,6 +141,15 @@ stm { }; + + /* + * Force Touch: the trackpad's haptic engine, ADT + * /arm-io/dockchannel-mtp/mtp-transport/actuator on every M4 laptop. + * Without it the click stays firmware-driven and there is no Force + * Touch stage. + */ + actuator { + }; }; /* Mesa fingerprint sensor: power on nub GPIO 28, data-ready on AP GPIO 199. */ From 8d81c7a11d13912baf5266449877d962c4b6faaa Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:04:55 +1100 Subject: [PATCH 0084/1514] arm64: dts: apple: t6050: describe the J873s Ethernet, N1 and rear USB-C The Mac mini (M5 Pro, J873s) had PCIe disabled and no USB-C connectors: no Ethernet, no Wi-Fi/Bluetooth and no rear Thunderbolt ports. The board's ADT gives the J775d's layout for the parts the two desktops share: the onboard Ethernet on PCIe port 2, the N1 on port 0 (PERST# GPIO 80, DART streams 1-3), and rear USB-C ports 1-3 on ATC0-2 with their PD controllers on nub-spmi-a0 at SPMI addresses 0xc, 0xa and 0x8. Move the J775d's Ethernet root port, its DART enable and rear ports 1-3 (HPM0 reserved for the debug link, HPM1 on ATC1, HPM2 on ATC2 with the dcpext0 Type-C route) into a new t6050-desktop.dtsi, with each board giving its own connector labels. The J775d DTB is byte-identical. The J873s then adds its own apcie0 registers and interrupts for ports 2 and 0 (it has no port 1 or 3), the bus numbering the boot loader starts from, and the N1 node with its platform ID, board 0x02 << 16 | 0x6050, and its firmware name, disabled until the boot loader trains the port. Values are from the board's ADT. The front USB-C ports sit behind a fixed hub on ATC3 with no PD controller and are left undescribed. The other T6050 boards are unchanged. The Ethernet port and rear USB-C ports were written for the J775d by Jeff Queisser. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-desktop.dtsi | 189 +++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-j775d.dts | 178 +---------------- arch/arm64/boot/dts/apple/t6050-j873s.dts | 113 ++++++++++- 3 files changed, 308 insertions(+), 172 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-desktop.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-desktop.dtsi b/arch/arm64/boot/dts/apple/t6050-desktop.dtsi new file mode 100644 index 00000000000000..41cbd32d3b431d --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-desktop.dtsi @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * What the T6050 desktops (Mac Studio J775d, Mac mini J873s) share on die 0: the onboard + * Ethernet on PCIe port 2, and rear USB-C ports 1-3 (ATC0-2, their PD controllers on + * nub-spmi-a0 at SPMI addresses 0xc, 0xa and 0x8). Each board's ADT gives the same port, + * bridge, PHY and HPM layout for these; only the connectors' places differ. + * + * The board file includes this before its own &pcie0 and &nub_spmi_a0 nodes (its other root + * ports and HPMs follow these) and defines first: + * T6050_DESKTOP_HPM1_LABEL the label of rear port 2's connector (HPM1, ATC1) + * T6050_DESKTOP_HPM2_LABEL the label of rear port 3's connector (HPM2, ATC2) + * The board sets &pcie0's registers, interrupts, iommu-map and bus-range, and the + * ethernet0 alias through which the boot loader fills the MAC address. + * + * Copyright The Asahi Linux Contributors + */ + +/* + * PCIe port 2: the onboard Ethernet (ADT apcie0/pci-bridge2/lan0). The boot loader powers and + * trains the link and numbers its secondary bus 1. + */ +&pcie0 { + port02: pci@2,0 { + device_type = "pci"; + reg = <0x1000 0 0 0 0>; + bus-range = <1 1>; + apple,link-trained-by-bootloader; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port02 0 0 0 0>, + <0 0 0 2 &port02 0 0 0 1>, + <0 0 0 3 &port02 0 0 0 2>, + <0 0 0 4 &port02 0 0 0 3>; + + /* The controller keeps no MAC address of its own */ + ethernet0: ethernet@0,0 { + reg = <0x10000 0x0 0x0 0x0 0x0>; + /* To be filled by the loader */ + local-mac-address = [00 00 00 00 00 00]; + }; + }; +}; + +&dart_apcie2 { + status = "okay"; +}; + +&nub_spmi_a0 { + /* + * /arm-io/nub-spmi-a0/hpm0: SN201202x (ACE3), SPMI address 0xc, port-number 1. + * Reserved: rear port 1 carries the DFU cable, the host's VDM reboot path and the + * debug console (KIS) through usb-drd0; a probe wakes the controller and sets its + * power state even when polled. No ATC0, usb-drd0 or dart-usb0 node either. + */ + hpm0: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + status = "disabled"; + }; + + /* /arm-io/nub-spmi-a0/hpm1: SN201202x (ACE3), SPMI address 0xa, port-number 2 */ + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = T6050_DESKTOP_HPM1_LABEL; + power-role = "dual"; + data-role = "host"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm1_hs: endpoint { + remote-endpoint = <&usb_drd1_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm1_ss: endpoint { + remote-endpoint = <&atc1_phy_ep>; + }; + }; + }; + }; + }; + + /* /arm-io/nub-spmi-a0/hpm2: SN201202x (ACE3), SPMI address 8, port-number 3 */ + hpm2: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + status = "disabled"; + + connector { + compatible = "usb-c-connector"; + label = T6050_DESKTOP_HPM2_LABEL; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm2_hs: endpoint { + remote-endpoint = <&usb_drd2_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm2_ss: endpoint { + remote-endpoint = <&atc2_phy_ep>; + }; + }; + + port@2 { + reg = <2>; + hpm2_dp: endpoint { + remote-endpoint = <&dcpext0_typec>; + }; + }; + }; + }; + }; +}; + +/* Rear USB-C port 2 (HPM1), USB data: ATC1's combo PHY, usb-drd1 and dart-usb1 */ +&atc1_phy { + port { + atc1_phy_ep: endpoint { + remote-endpoint = <&hpm1_ss>; + }; + }; +}; + +&usb_drd1 { + port { + usb_drd1_hs: endpoint { + remote-endpoint = <&hpm1_hs>; + }; + }; +}; + +/* + * Rear USB-C port 3 (HPM2): DisplayPort out from dcpext0 through ATC2, and USB beside it + * (usb-drd2, dart-usb2). The chain stays disabled: Aura's T6050 display handoff enables what + * dcpext0 references (phys, mux-controls, the PHY's mailbox and power domains, the typec + * route's HPM and its SPMI bus). + */ +&atc2_phy { + port { + atc2_phy_ep: endpoint { + remote-endpoint = <&hpm2_ss>; + }; + }; +}; + +&usb_drd2 { + port { + usb_drd2_hs: endpoint { + remote-endpoint = <&hpm2_hs>; + }; + }; +}; + +&dcpext0 { + typec-routes { + route@0 { + port { + dcpext0_typec: endpoint { + remote-endpoint = <&hpm2_dp>; + }; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index 68b4c324aca025..6db3de2d1b26f1 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -86,9 +86,18 @@ }; }; +/* + * Shared with the Mac mini: the onboard Ethernet (PCIe port 2, an RTL8127A here) and rear + * USB-C ports 1-3. Port 1 (HPM0, "back-right") is reserved for the debug link. + */ +#define T6050_DESKTOP_HPM1_LABEL "USB-C Back-right-middle" +#define T6050_DESKTOP_HPM2_LABEL "USB-C Back-left-middle" +#include "t6050-desktop.dtsi" + /* * PCIe ports 2 (the onboard 10 Gb Ethernet) and 3 (the rear USB-A xHCI). The boot loader * powers and trains both links; it disables a port, and its DART, whose link did not come up. + * Port 2's node is in t6050-desktop.dtsi. * * Port 0 carries the N1 (Wi-Fi and Bluetooth), described disabled until the boot loader trains * it (pci@0,0 below). @@ -124,32 +133,6 @@ <0x300 &dart_apcie0 1 3>; bus-range = <0 3>; - port02: pci@2,0 { - device_type = "pci"; - reg = <0x1000 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port02 0 0 0 0>, - <0 0 0 2 &port02 0 0 0 1>, - <0 0 0 3 &port02 0 0 0 2>, - <0 0 0 4 &port02 0 0 0 3>; - - /* The RTL8127A keeps no MAC address of its own */ - ethernet0: ethernet@0,0 { - reg = <0x10000 0x0 0x0 0x0 0x0>; - /* To be filled by the loader */ - local-mac-address = [00 00 00 00 00 00]; - }; - }; - port03: pci@3,0 { device_type = "pci"; reg = <0x1800 0 0 0 0>; @@ -276,10 +259,6 @@ status = "okay"; }; -&dart_apcie2 { - status = "okay"; -}; - &dart_apcie3 { status = "okay"; }; @@ -360,92 +339,9 @@ /* * The USB-C ports: rear ports 1-4 on ATC0-3 of die 0, front ports 5 and 6 on ATC0 and ATC1 of * die 1. The HPMs of the rear ports are on nub-spmi-a0, those of the front ports on nub-spmi-a2. + * Rear ports 1-3 are in t6050-desktop.dtsi; rear port 4 and the front ports follow. */ &nub_spmi_a0 { - /* - * /arm-io/nub-spmi-a0/hpm0: SN201202x (ACE3), SPMI address 0xc, port-number 1 (back-right). - * Reserved: rear port 1 carries the DFU cable, the host's VDM reboot path and the - * debug console (KIS) through usb-drd0; a probe wakes the controller and sets its - * power state even when polled. No ATC0, usb-drd0 or dart-usb0 node either. - */ - hpm0: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - status = "disabled"; - }; - - /* /arm-io/nub-spmi-a0/hpm1: SN201202x (ACE3), SPMI address 0xa, port-number 2 */ - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Back-right-middle"; - power-role = "dual"; - data-role = "host"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm1_ss: endpoint { - remote-endpoint = <&atc1_phy_ep>; - }; - }; - }; - }; - }; - - /* /arm-io/nub-spmi-a0/hpm2: SN201202x (ACE3), SPMI address 8, port-number 3 */ - hpm2: usb-pd@8 { - compatible = "apple,sn201202x"; - reg = <0x8 SPMI_USID>; - status = "disabled"; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Back-left-middle"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm2_ss: endpoint { - remote-endpoint = <&atc2_phy_ep>; - }; - }; - - port@2 { - reg = <2>; - hpm2_dp: endpoint { - remote-endpoint = <&dcpext0_typec>; - }; - }; - }; - }; - }; - /* /arm-io/nub-spmi-a0/hpm3: SN201202x (ACE3), SPMI address 6, port-number 4 */ hpm3: usb-pd@6 { compatible = "apple,sn201202x"; @@ -553,60 +449,6 @@ }; }; -/* - * Rear USB-C port 2 (HPM1, "back-right-middle"), USB data: ATC1's combo PHY, usb-drd1 and - * dart-usb1. - */ -&atc1_phy { - port { - atc1_phy_ep: endpoint { - remote-endpoint = <&hpm1_ss>; - }; - }; -}; - -&usb_drd1 { - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&hpm1_hs>; - }; - }; -}; - -/* - * Rear USB-C port 3 (HPM2, "back-left-middle", the display port): DisplayPort out from dcpext0 - * through ATC2, and USB beside it (usb-drd2, dart-usb2). The chain stays disabled: Aura's T6050 - * display handoff enables what dcpext0 references (phys, mux-controls, the PHY's mailbox and - * power domains, the typec route's HPM and its SPMI bus). - */ -&atc2_phy { - port { - atc2_phy_ep: endpoint { - remote-endpoint = <&hpm2_ss>; - }; - }; -}; - -&usb_drd2 { - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&hpm2_hs>; - }; - }; -}; - -&dcpext0 { - typec-routes { - route@0 { - port { - dcpext0_typec: endpoint { - remote-endpoint = <&hpm2_dp>; - }; - }; - }; - }; -}; - /* Rear USB-C port 4 (HPM3, "back-left"): ATC3, and its USB4/Thunderbolt router */ &atc3_phy { port { diff --git a/arch/arm64/boot/dts/apple/t6050-j873s.dts b/arch/arm64/boot/dts/apple/t6050-j873s.dts index 0a7976e50230f5..9c2e2a12c54352 100644 --- a/arch/arm64/boot/dts/apple/t6050-j873s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j873s.dts @@ -5,8 +5,10 @@ * target-type: J873s * * One T6050 die (t6050-max.dtsi). Nobody has booted Linux on this board - * yet: beyond the SoC this file only adds the board's hardware inventory - * (t6050-peripherals.dtsi), all of it disabled, from the board's ADT. + * yet. Beyond the SoC this file adds the board's hardware inventory + * (t6050-peripherals.dtsi, all of it disabled), the onboard Ethernet and + * the N1 (Wi-Fi and Bluetooth) on PCIe, and rear USB-C ports 1-3, from + * the board's ADT. * * Copyright The Asahi Linux Contributors */ @@ -20,6 +22,14 @@ model = "Apple Mac mini (M5 Pro, 2026)"; chassis-type = "desktop"; + aliases { + /* the boot loader fills in the MAC address through this alias */ + ethernet0 = ðernet0; + /* kboot fills the N1's factory addresses from /chosen through these */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; + }; + chosen { #address-cells = <2>; #size-cells = <2>; @@ -27,10 +37,105 @@ }; }; -/* PCIe port 0 is not described for this board yet */ +/* + * Shared with the Mac Studio: the onboard Ethernet (PCIe port 2) and rear USB-C ports 1-3, the + * three Thunderbolt ports. Port 1 (HPM0, "back-middle") is reserved for the debug link. + */ +#define T6050_DESKTOP_HPM1_LABEL "USB-C Back-left" +#define T6050_DESKTOP_HPM2_LABEL "USB-C Back-right" +#include "t6050-desktop.dtsi" + +/* + * PCIe ports 2 (the onboard Ethernet) and 0 (the N1). The board's ADT has bridges for these two + * ports only: no SD reader (port 1) and no USB-A xHCI (port 3). Port 0 is described disabled + * until the boot loader trains it (pci@0,0 below). + */ &pcie0 { - status = "disabled"; + reg = <0x1c 0xb0000000 0x0 0x10000000>, + <0x4 0x14000000 0x0 0x4000>, + <0x4 0x12028000 0x0 0x8000>, + <0x4 0x17018000 0x0 0x4000>, + <0x4 0x12024000 0x0 0x4000>, + <0x4 0x10028000 0x0 0x8000>, + <0x4 0x17010000 0x0 0x4000>, + <0x4 0x10024000 0x0 0x4000>; + reg-names = "config", "rc", "port2", "phy2", "intr2axi2", + "port0", "phy0", "intr2axi0"; + interrupts = , + ; + interrupt-names = "port2", "port0"; + + /* + * The boot loader numbers port 2's secondary bus 1; port 0's is 2 + * until a boot loader that trains it renumbers both in the PCI core's + * order. The N1's three functions are on DART streams 1-3. + */ + iommu-map = <0x100 &dart_apcie2 1 1>, + <0x200 &dart_apcie0 1 3>; + bus-range = <0 2>; + + /* + * The N1 Wi-Fi/Bluetooth (106b:1900, its ROM), trained by the bootloader after the SMC + * releases its reset. Its driver boots the firmware and has this port reset after the ROM + * stage; Control, Alpha (Wi-Fi) and Beta (Bluetooth) then answer at functions 0-2. + * Disabled with its DART: a bootloader that trains the port enables both and renumbers the + * buses here (bus-range, reg, iommu-map) to the PCI core's order, port 0 first. + */ + port00: pci@0,0 { + device_type = "pci"; + reg = <0x0 0 0 0 0>; + bus-range = <2 2>; + apple,link-trained-by-bootloader; + /* + * Its PERST# (pci-bridge0 function-perst): /arm-io/gpio0 pin 0x50, pad + * register 0x140 of pinctrl_ap. Driven only by the root-port reset after + * the N1's ROM stage. + */ + reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; + status = "disabled"; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port00 0 0 0 0>, + <0 0 0 2 &port00 0 0 0 1>, + <0 0 0 3 &port00 0 0 0 2>, + <0 0 0 4 &port00 0 0 0 3>; + + /* The firmware: the chip's image with this board's ticket; platform ID is + * (board 0x02 << 16) | chip 0x6050 */ + n1_control: control@0,0 { + compatible = "pci106b,1900"; + reg = <0x20000 0x0 0x0 0x0 0x0>; + firmware-name = "apple/centauri/j873s-ftab.bin"; + apple,centauri-platform-id = <0x00026050>; + apple,centauri-protocol = <27>; + }; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x20100 0x0 0x0 0x0 0x0>; + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x20200 0x0 0x0 0x0 0x0>; + local-bd-address = [00 00 00 00 00 00]; + }; + }; }; +/* + * The front USB-C ports (ADT port-numbers 9 and 10, USB 3 only) sit behind a fixed USB hub on + * ATC3 (atc-phy3, usb-drd3), which has no PD controller. They are not described yet: the + * combo PHY starts USB only on a Type-C mux and orientation event, which a hub port without + * an HPM never gets. + */ + #define T6050_J873S #include "t6050-peripherals.dtsi" From 4fe837a0bc1de589191df428144f44ea75b4ff58 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:11:41 +1100 Subject: [PATCH 0085/1514] usb: dwc3: apple: Select idle runtime PM by the power domains in the device tree An idle controller, whose core is down because no cable is connected, could runtime-suspend only on T6040 and T8132 ("the PHY driver and the DARTs follow runtime PM on these SoCs"). A port that never saw a cable could do so only on T8132 and on T6041 machines. The glue, the DARTs' runtime PM and the way the PHYs use the controller's power domain are the same on every SoC, so these lists record where it was tried, not a hardware difference. On T6000, T8112, T8140 and the others an idle controller stayed runtime-active for good after its first cable, and with it its DARTs. Select it from the device tree instead: the controller, every DART in its iommus and every PHY provider in its phys must name a power domain. That is the condition for a domain drop to be safe: - a DART is resumed before its consumer, and so before the consumer's domain is on. A DART outside any domain would be restored into a block that is still off; - a PHY in the domain either keeps it on (an ATC PHY without idle power-off has runtime PM disabled, so genpd counts it as in use), follows it and restores its state (T8132), or holds it while it is started (the T6050 combo PHY). Every enabled Apple DWC3 node in the tree meets this: 179 nodes in 135 DTBs, on T8103, T6000, T8112, T6020, T8122, T6030, T6031, T6040, T8132, T8140, T8142 and T6050. Where the ATC PHY has no idle power-off, the PHY keeps the domain on, so an idle controller now suspends the glue and its DARTs only. The PHY is not power-cycled by this, and the base M1 USB3 handoff path is not reached by it. The never-plugged path uses the same property. It stays off only for a fixed-hub host, which starts at probe and never waits for a cable. This builds on the idle runtime PM work of Jonathan Goyvaerts (T6040), Erik Bourget (T8132) and AxxzyWasTaken (T6041), which this only widens. Fixes: 4cacc48c78a9 ("usb: dwc3: apple: Let an idle T8132 controller runtime-suspend") Fixes: dcb1f4fa2448 ("usb: dwc3: apple: Let a never-plugged T6041 port runtime-suspend") Signed-off-by: Ryan Murray --- drivers/usb/dwc3/dwc3-apple.c | 52 +++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 4d9b4ac0d83467..27ca453caca95e 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -695,7 +695,8 @@ static int dwc3_apple_core_probe(struct dwc3_apple *appledwc, enum dwc3_apple_st * dwc3_core_probe() enabled runtime PM with the device active and forbade it, for the * dwc3 platform driver's own callbacks, which this glue does not use. The core is being * brought up now, so take the glue's reference (see dwc3_apple_core_start()) and, where - * that is tested, allow runtime PM so the reference alone decides. + * the power domain may drop under an idle controller (see dwc3_apple_idle_rpm()), allow + * runtime PM so the reference alone decides. */ pm_runtime_get_noresume(appledwc->dev); appledwc->rpm_held = true; @@ -1822,6 +1823,45 @@ static bool dwc3_apple_has_fixed_hub(struct device *dev, u32 *port) return hub; } +/* + * Whether an idle controller may runtime-suspend and let its power domain drop. Everything + * that keeps state in that domain must be known to it: + * - the controller itself, which has no state of its own while its core is down; + * - its DARTs, which save and restore their state in their runtime PM callbacks. They are + * resumed before the controller, so a DART outside any domain would be written while the + * controller's domain is still off and come back empty; + * - its PHYs, which hold the domain while they have state in it, or follow it and restore + * that state once it is on again. + * The device tree says this with power-domains on all of them. + */ +static bool dwc3_apple_idle_rpm(struct device_node *np) +{ + static const struct { + const char *list; + const char *cells; + } suppliers[] = { + { "iommus", "#iommu-cells" }, + { "phys", "#phy-cells" }, + }; + struct of_phandle_iterator it; + int i, err; + + if (!of_property_present(np, "power-domains")) + return false; + for (i = 0; i < ARRAY_SIZE(suppliers); i++) { + of_for_each_phandle(&it, err, np, suppliers[i].list, suppliers[i].cells, 0) { + if (!of_property_present(it.node, "power-domains")) { + of_node_put(it.node); + return false; + } + } + if (err != -ENOENT) + return false; + } + + return true; +} + static int dwc3_apple_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -1837,9 +1877,7 @@ static int dwc3_apple_probe(struct platform_device *pdev) appledwc->host_only = dwc3_apple_host_only(dev); appledwc->dt_dis_u3_susphy = device_property_read_bool(dev, "snps,dis_u3_susphy_quirk"); appledwc->sleep_ddr = device_property_read_bool(dev, "apple,sleep-ddr"); - /* The PHY driver and the DARTs follow runtime PM on these SoCs. */ - appledwc->idle_rpm = of_device_is_compatible(dev->of_node, "apple,t6040-dwc3") || - of_device_is_compatible(dev->of_node, "apple,t8132-dwc3"); + appledwc->idle_rpm = dwc3_apple_idle_rpm(dev->of_node); mutex_init(&appledwc->lock); spin_lock_init(&appledwc->sleep_pm_lock); /* A never-connected port has no generic core probe to publish this. */ @@ -1929,11 +1967,9 @@ static int dwc3_apple_probe(struct platform_device *pdev) /* * Until the first cable there is no core to keep powered: let the controller * runtime-suspend, and its DARTs with it, so that its power domain can drop. - * Tested on T8132; on the T6041 (M4 Max) the never-plugged ports are the usual case. + * A fixed-hub host starts below, so it never waits for a cable. */ - if (appledwc->idle_rpm && !appledwc->fixed_hub && - (of_device_is_compatible(dev->of_node, "apple,t8132-dwc3") || - of_machine_is_compatible("apple,t6041"))) { + if (appledwc->idle_rpm && !appledwc->fixed_hub) { pm_runtime_set_active(dev); pm_runtime_enable(dev); appledwc->pre_core_rpm = true; From 93bd6e7e2cdcc8c2a00dcf82dfbd7bcbff83c206 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:12:24 +1100 Subject: [PATCH 0086/1514] usb: dwc3: apple: Take the USB3 PHY as optional on every SoC The USB3 PHY was optional only for T8132 and T6040 controllers. Whether a port has a USB3 PHY is what its device tree says in phys/phy-names, and the glue already handles a NULL PHY everywhere (phy_set_mode() on NULL is a no-op and the USB3 paths check for it). Look it up as optional on every SoC. A device tree that names the PHY behaves as before, including probe deferral. One that does not name it now gets a USB2-only port instead of a failed probe, which is what the two listed SoCs already got. Fixes: a50abc4f7b41 ("usb: dwc3-apple: support host-only T6040 ports with a USB2 PHY only") Signed-off-by: Ryan Murray --- drivers/usb/dwc3/dwc3-apple.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 27ca453caca95e..400ec09ce744fa 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -1895,17 +1895,15 @@ static int dwc3_apple_probe(struct platform_device *pdev) "Failed to get the USB2 PHY\n"); /* - * Older T8132 device trees and the T6040 ports without a USB3 PHY - * expose only USB2; a NULL PHY is a no-op. + * A port whose device tree names no USB3 PHY (the USB2-only T6040 ports, older T8132 + * device trees) exposes only USB2; a NULL PHY is a no-op. */ - if (of_device_is_compatible(dev->of_node, "apple,t8132-dwc3") || - of_device_is_compatible(dev->of_node, "apple,t6040-dwc3")) - appledwc->usb3_phy = devm_phy_optional_get(dev, "usb3-phy"); - else - appledwc->usb3_phy = devm_phy_get(dev, "usb3-phy"); + appledwc->usb3_phy = devm_phy_optional_get(dev, "usb3-phy"); if (IS_ERR(appledwc->usb3_phy)) return dev_err_probe(dev, PTR_ERR(appledwc->usb3_phy), "Failed to get the USB3 PHY\n"); + if (!appledwc->usb3_phy) + dev_dbg(dev, "no USB3 PHY in the device tree: USB2 only\n"); ret = reset_control_assert(appledwc->reset); if (ret) { From 0d8e6bde9b2825732574b0147500afa1b1726e52 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:12:39 +1100 Subject: [PATCH 0087/1514] usb: dwc3: apple: Say why the hibernation setup stays T8140-only dwc3_apple_setup_hibernation() sets GCTL's hibernation enable and a power-down scale on T8140 only. Keep that scope and write down the reason: the power-down scale is the number of suspend clock periods in one 16 kHz period, so it depends on the SoC's suspend clock rate, and T8140 is the only SoC whose value is known. Another SoC that keeps its core through a deep sleep needs its own scale first. No functional change. Signed-off-by: Ryan Murray --- drivers/usb/dwc3/dwc3-apple.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index 400ec09ce744fa..a696fe5a2b369c 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -306,6 +306,10 @@ static inline void dwc3_apple_mask(struct dwc3_apple *appledwc, u32 offset, u32 * of 0xd. Without the enable the core's power management accepts a * D0/D3 request but saves and restores nothing, so the PHY's hibernation for a sleep * needs it. + * This stays on T8140: the power-down scale is the number of suspend clock periods + * in one 16 kHz period, so it follows the SoC's suspend clock rate, and T8140 is the + * only SoC whose value is known. Another SoC that keeps its core through a deep sleep + * needs its own scale before it can set the enable. */ #define DWC3_APPLE_T8140_PWRDNSCALE 0xd From 71f922ac227ff7f4795a313a67432c73fc039caa Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:15:23 +1100 Subject: [PATCH 0088/1514] arm64: dts: apple: t6040: set up the SIO coprocessor on every M4 Pro The SIO coprocessor is part of the T6040 and has no board wiring; the J773s device tree has the same /arm-io/sio as the MacBook Pros. Its DART, mailbox, CPU power state (with the SPI, UART and DP audio parents its firmware needs) and the alias the boot loader uses to find and enable the SIO node were only set in the MacBook Pros' DP audio file, so the J773s never got a running SIO, nor the AES engine behind its DART. Move them to t6040.dtsi. The DP audio file keeps DPA1, DPA2 and their clients. The J614s and J616s decompile unchanged; the J773s gains only these nodes' status, the SIO_CPU parents and the sio alias. Signed-off-by: Ryan --- .../boot/dts/apple/t6040-j616s-dpaudio.dtsi | 43 ++----------------- arch/arm64/boot/dts/apple/t6040.dtsi | 40 +++++++++++++++++ 2 files changed, 44 insertions(+), 39 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi b/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi index e406a733c350d4..d00c7aa805c1e4 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-j616s-dpaudio.dtsi @@ -3,20 +3,13 @@ * DPA1 and DPA2 belong to DCPEXT0 and DCPEXT1, respectively. SIO supplies * their sample streams; neither interface has AP-side registers. * - * Both chains are enabled: the SIO DART, mailbox and CPU domain, DPA1 and - * DPA2 and their clients. The SIO itself stays disabled here: iBoot has - * loaded its firmware, and the boot loader enables the node once it has - * reserved that firmware and published the T6041 boot tables (it finds it - * by the alias). Without a T6041-aware loader DPA1 and DPA2 wait for their - * DMA channels and nothing else changes. The DCP side starts unless - * appledrm.hdmi_audio=0. + * Both chains are enabled: DPA1 and DPA2 and their clients. The SIO, its + * DART, mailbox and CPU domain are set up in t6040.dtsi. Without a + * T6041-aware loader DPA1 and DPA2 wait for their DMA channels and nothing + * else changes. The DCP side starts unless appledrm.hdmi_audio=0. */ / { - aliases { - sio = &sio; - }; - dpaudio1: audio-controller-1 { compatible = "apple,t6041-dpaudio", "apple,dpaudio"; dmas = <&sio 0x66>; @@ -86,34 +79,6 @@ }; }; -/* - * The SIO firmware drives the SPI, UART and DP audio shims, so keep their - * parents on while it runs, as on T6000, T8112 and T8140. The ADT lists - * only SIO as SIO_CPU's parent. Without this, SPI_P stays on only because - * the QSPI controller never runtime-suspends, and UART_P is left as iBoot - * set it; a T8140 SIO with SPI_P/UART_P off crashes at boot. - */ -&ps_sio_cpu { - power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; - status = "okay"; -}; - -&ps_uart_p { - status = "okay"; -}; - -&sio_dart { - status = "okay"; -}; - -&sio_mbox { - status = "okay"; -}; - -&ps_dpa_p { - status = "okay"; -}; - &ps_dpa1 { status = "okay"; }; diff --git a/arch/arm64/boot/dts/apple/t6040.dtsi b/arch/arm64/boot/dts/apple/t6040.dtsi index 27fc991fdcc96e..70d95e4d0d331f 100644 --- a/arch/arm64/boot/dts/apple/t6040.dtsi +++ b/arch/arm64/boot/dts/apple/t6040.dtsi @@ -674,3 +674,43 @@ }; #include "t6040-usb4.dtsi" + +/* + * The SIO coprocessor is part of every T6040 and has no board wiring: iBoot + * loads its firmware on every board, and the boot loader enables the SIO + * node, which it finds by the alias, once it has reserved that firmware and + * published the T6041 boot tables. The SIO AES engine sits behind its DART. + */ +/ { + aliases { + sio = &sio; + }; +}; + +/* + * The SIO firmware drives the SPI, UART and DP audio shims, so keep their + * parents on while it runs, as on T6000, T8112 and T8140. The ADT lists + * only SIO as SIO_CPU's parent. Without this, SPI_P stays on only because + * the QSPI controller never runtime-suspends, and UART_P is left as iBoot + * set it; a T8140 SIO with SPI_P/UART_P off crashes at boot. + */ +&ps_sio_cpu { + power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&ps_uart_p { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + +&sio_dart { + status = "okay"; +}; + +&sio_mbox { + status = "okay"; +}; From a364edbf4c6d11b764a93a39936bf105be7be84a Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:13:13 +1100 Subject: [PATCH 0089/1514] arm64: dts: apple: t6040: enable the SIO AES engine on every M4 Pro The AES engine is part of the T6040 SIO block and has no board wiring: the J614s and J773s device trees have the same /arm-io/aes node as the J616s. Only the J616s enabled it and its power state, so the other M4 Pro boards never probed apple-aes. Enable the engine and its power state in the SoC files and drop the J616s copy. The J616s decompiles unchanged; the J614s and J773s gain only these two status changes. On the J773s the engine probes once the SIO DART is enabled there too. Signed-off-by: Ryan --- arch/arm64/boot/dts/apple/t6040-j616s.dts | 9 --------- arch/arm64/boot/dts/apple/t6040-peripherals.dtsi | 4 ++-- arch/arm64/boot/dts/apple/t6040-pmgr.dtsi | 2 +- 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6040-j616s.dts b/arch/arm64/boot/dts/apple/t6040-j616s.dts index e81fb8b6b5d0d7..0f26d840498ed9 100644 --- a/arch/arm64/boot/dts/apple/t6040-j616s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j616s.dts @@ -379,12 +379,3 @@ &ps_uart0 { status = "okay"; }; - -/* SIO AES engine, software keys only. */ -&ps_aes { - status = "okay"; -}; - -&aes { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi index f59b3f0a8fbd81..babbb53ec09914 100644 --- a/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-peripherals.dtsi @@ -25,7 +25,7 @@ power-domains = <&ps_dwi>; }; - /* ADT /arm-io/aes. */ + /* ADT /arm-io/aes: the SIO AES engine, software keys only. */ aes: crypto@42900c000 { compatible = "apple,t6041-aes", "apple,aes"; reg = <0x4 0x2900c000 0x0 0x4000>, @@ -35,7 +35,7 @@ interrupts = ; power-domains = <&ps_aes>; iommus = <&sio_dart 1>; - status = "disabled"; + status = "okay"; }; /* ADT /arm-io/aon-ptd. */ diff --git a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi index 75650445572b10..380d9ed3576b51 100644 --- a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi @@ -107,7 +107,7 @@ label = "aes"; power-domains = <&ps_sio>; apple,always-on; - status = "disabled"; + status = "okay"; }; ps_spi0: power-controller@1b8 { From c50248ea66d01d1fefb2d4ce1dc2f9b72d98db16 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:17:59 +1100 Subject: [PATCH 0090/1514] arm64: dts: apple: t6041: set up the SIO coprocessor on every M4 Max The SIO coprocessor is part of the T6041 and has no board wiring; the J575c device tree has the same /arm-io/sio as the MacBook Pros. Its DART, mailbox, CPU power state (with the SPI, UART and DP audio parents its firmware needs), the UART_P and DPA_P power states and the alias the boot loader uses to find and enable the SIO node were only described in the MacBook Pros' shared file, so the J575c never got a running SIO. Move them to t6041.dtsi. The MacBook Pros' file keeps DPA1, DPA2 and their DP audio clients. The J614c and J616c decompile unchanged (phandle values aside); the J575c gains only these nodes, their status, the SIO_CPU parents and the sio alias. Signed-off-by: Ryan --- .../boot/dts/apple/t6041-j614c-j616c.dtsi | 43 +---------------- arch/arm64/boot/dts/apple/t6041.dtsi | 48 +++++++++++++++++++ 2 files changed, 50 insertions(+), 41 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index 8e2b49a4567ea9..c9f27b55b9b3cf 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -2731,31 +2731,10 @@ /* * DisplayPort/HDMI audio, as on the M4 Pro boards (t6040-j616s-dpaudio.dtsi). * The J614c's ADT has the J616s's: dcpext0's audio is dp-audio1 (SIO DMA - * channel 0x66) and dcpext1's is dp-audio2 (0x68), and the PMGR has UART_P - * (0x1a0) and DPA_P (0x1a8) under SIO, and DPA1 (0x238) and DPA2 (0x240) - * under DPA_P. The SIO stays disabled here: the loader enables it once it has - * reserved the firmware iBoot loaded (it finds it by the alias). + * channel 0x66) and dcpext1's is dp-audio2 (0x68), and the PMGR has DPA1 + * (0x238) and DPA2 (0x240) under DPA_P. The SIO is set up in t6041.dtsi. */ &pmgr { - ps_uart_p: power-controller@1a0 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a0 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "uart_p"; - power-domains = <&ps_sio>; - }; - - ps_dpa_p: power-controller@1a8 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a8 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa_p"; - power-domains = <&ps_sio>; - apple,always-on; - }; - ps_dpa1: power-controller@238 { compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x238 4>; @@ -2776,10 +2755,6 @@ }; / { - aliases { - sio = &sio; - }; - dpaudio1: audio-controller-1 { compatible = "apple,t6041-dpaudio", "apple,dpaudio"; dmas = <&sio 0x66>; @@ -2847,20 +2822,6 @@ }; }; -/* The SIO firmware drives the SPI, UART and DP audio shims: keep their parents on. */ -&ps_sio_cpu { - power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; - status = "okay"; -}; - -&sio_dart { - status = "okay"; -}; - -&sio_mbox { - status = "okay"; -}; - /* * The Neural Engine, as on the M4 Pro boards. The J614c's ADT has ane0 with * pre-loaded firmware (__TEXT;__DATA); the loader fills the reservations of diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index be2b09cc1dfd55..65ee08150126f7 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -485,3 +485,51 @@ 0x228004000 0x2281d62fc 0x22a004000 0x22a1d62fc>; }; + +/* + * The SIO coprocessor is part of every T6041 and has no board wiring: iBoot + * loads its firmware on every board, and the boot loader enables the SIO + * node, which it finds by the alias, once it has reserved that firmware and + * published the T6041 boot tables. The PMGR has UART_P (0x1a0) and DPA_P + * (0x1a8) under SIO. + */ +/ { + aliases { + sio = &sio; + }; +}; + +&pmgr { + ps_uart_p: power-controller@1a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart_p"; + power-domains = <&ps_sio>; + }; + + ps_dpa_p: power-controller@1a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa_p"; + power-domains = <&ps_sio>; + apple,always-on; + }; +}; + +/* The SIO firmware drives the SPI, UART and DP audio shims: keep their parents on. */ +&ps_sio_cpu { + power-domains = <&ps_sio>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&sio_dart { + status = "okay"; +}; + +&sio_mbox { + status = "okay"; +}; From 4ad124bcf9a5ac445edf10410a21fa18546ebb59 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:19:20 +1100 Subject: [PATCH 0091/1514] arm64: dts: apple: t6041: enable the Neural Engine on every M4 Max The Neural Engine is part of the T6041 and has no board wiring. The J575c device tree has the same ane0 and dart-ane0 as the MacBook Pros, and the J575c already includes the firmware reservations and the ane alias the boot loader fills, but only the MacBook Pros' shared file enabled the engine and its three DARTs. Enable them in t6041.dtsi and drop the MacBook Pros' copy. The J614c and J616c decompile unchanged; the J575c gains only these four status changes. Signed-off-by: Ryan --- .../boot/dts/apple/t6041-j614c-j616c.dtsi | 21 ------------------ arch/arm64/boot/dts/apple/t6041.dtsi | 22 +++++++++++++++++++ 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index c9f27b55b9b3cf..9fcd4470cfa0cf 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -2822,27 +2822,6 @@ }; }; -/* - * The Neural Engine, as on the M4 Pro boards. The J614c's ADT has ane0 with - * pre-loaded firmware (__TEXT;__DATA); the loader fills the reservations of - * t6041-j616c-ane.dtsi and the firmware IOVAs from it. - */ -&ane0_dart0 { - status = "okay"; -}; - -&ane0_dart1 { - status = "okay"; -}; - -&ane0_dart2 { - status = "okay"; -}; - -&ane { - status = "okay"; -}; - /* Both JPEG engines, as on the M4 Pro boards; they have no board wiring. */ &ps_jpg { status = "okay"; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 65ee08150126f7..dea6821738369d 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -12,6 +12,28 @@ power-domains = <&ps_avd_sys>; }; +/* + * The Neural Engine, as on the M4 Pro boards. Every T6041 has it: the J575c, + * J614c and J616c ADTs have ane0 with pre-loaded firmware (__TEXT;__DATA); + * the loader fills the reservations of t6041-j616c-ane.dtsi and the firmware + * IOVAs from it. + */ +&ane0_dart0 { + status = "okay"; +}; + +&ane0_dart1 { + status = "okay"; +}; + +&ane0_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; +}; + /* * The main PMIC is a Chapel at 0xb (ADT nub-spmi0 spmi-chapelL1-b), not the * J616s's Abbey at 0xe. Its nvmem cells and RTC alarm registers are at the From 79be7f191ef4f7e3d8846e3c468f7372c161f2ca Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:28:47 +1100 Subject: [PATCH 0092/1514] arm64: dts: apple: t8142: share the AOP and its sensors with every board The AOP core, its mailboxes and dart-aop were described in the J813/J815 sound file (t8142-j813-audio.dtsi) and the ambient light and lid angle services in each board file, so the MacBook Pro J704 had none of them. The J704, J813 and J815 ADTs agree on /arm-io/aop (reg, interrupts 490-493, iop,ascwrap-v6), aop-exclave-mailbox (0x3d067c000, interrupts 497/494), dart-aop (0x390fc0000, interrupt 528) and every /arm-io/aop/iop-aop-nub service, als included, and all three carry the lid angle sensor's i2c1 "mogul-las" authentication chip. Move aop_mbox, aop_setup_mbox, the aop node and its als and las services to t8142-peripherals.dtsi and enable aop_dart in t8142.dtsi, so every T8142 board gets them. The AOP core runs without its audio child (J815 runs so today), and aop registers a service child only when its firmware announces the service. t8142-j813-audio.dtsi keeps only &aop { aop_audio }. dart-aop and aop have no ADT power-gates: AOP_DART sits in the AOP's own always-on power tree, so the DART names no power domain (the AOP DARTs are exempt from the DART power-domain rule). J813 and J815 compile to the same tree apart from node order, phandle numbers and aop_dart losing its now redundant status = "okay". J704 gains the AOP, both mailboxes, dart-aop, als and las. The moved nodes are Thomas Glanzmann's (AOP, mailboxes, dart-aop: "t8142-j813: Sound through the AOP"), Diljit Singh's and Nick's (als), and Nick's (las). Signed-off-by: Ryan Murray --- .../boot/dts/apple/t8142-j813-audio.dtsi | 98 +++++-------------- arch/arm64/boot/dts/apple/t8142-j813.dts | 20 ---- arch/arm64/boot/dts/apple/t8142-j815.dts | 23 ----- .../boot/dts/apple/t8142-peripherals.dtsi | 84 ++++++++++++++++ arch/arm64/boot/dts/apple/t8142.dtsi | 7 +- 5 files changed, 113 insertions(+), 119 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi index c345bc3ff50acd..9bcdf37f2c60ea 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-audio.dtsi @@ -6,8 +6,8 @@ * runs the MCA serializers: "cout"/"cin" (CS42L84 headphone jack) on * admac-base-ns TX2/RX2 and "spkr" (four SN012776) on TX0, their V/I sense * on RX0 (ADT iop-audio-controller; RX1 is the firmware's speaker tap). - * The AOP itself is laid out like T8140's (ascwrap-v6, asc-mailbox-v4), - * including the setup port. + * The AOP core, its mailboxes and dart-aop are shared by every T8142 board + * (t8142-peripherals.dtsi); this file adds only its audio service. * Addresses are from the J813 ADT (arm-io offset 0x210000000). */ @@ -172,45 +172,6 @@ }; }; - aop_mbox: mailbox@390608000 { - compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; - reg = <0x3 0x90608000 0x0 0x4000>; - interrupt-parent = <&aic>; - interrupts = , - , - , - ; - interrupt-names = "send-empty", "send-not-empty", - "recv-empty", "recv-not-empty"; - #mbox-cells = <0>; - }; - - /* - * The ADT's aop-exclave-mailbox, flagged exclave-assigned as on T8140, - * is the AOP setup port the host drives. Its ADT reg (0x3d067c000) is - * not behind the arm-io translation: AOP ASC + 0x4007c000, as on - * T8140. ADT interrupts [497, 494], T8140's +100. - */ - aop_setup_mbox: mailbox@3d067c000 { - compatible = "apple,t8142-aop-setup-mailbox", "apple,t8140-aop-setup-mailbox"; - reg = <0x3 0xd067c000 0x0 0x4000>; - interrupt-parent = <&aic>; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - /* dart-aop stream 1: ADT vm-base-1 0x20000000000, as on T8140. */ - iommus = <&aop_dart 1>; - apple,dma-range = <0x200 0x0 0x10 0x0>; - #mbox-cells = <0>; - }; - - /* - * dart-aop: streams 0 (AOP), 3, 8 (admac-base-ns), 10 and 16 are the - * AP's; 1, 9 and 11 are exclave streams, of which the host drives 1 - * (setup port) and 11 (admac-leap-s) on the raw boot. As on T8140, the - * firmware's own mappings own the first slot, host buffers go above it. - */ - admac_base_ns: dma-controller@393800000 { compatible = "apple,t8140-admac"; reg = <0x3 0x93800000 0x0 0x34000>; @@ -330,37 +291,28 @@ ti,bclk-ratio = <250>; }; }; +}; - aop: aop@390c00000 { - compatible = "apple,t8142-aop", "apple,t8152-aop"; - reg = <0x3 0x90c00000 0x0 0x1e0000>, - <0x3 0x90600000 0x0 0x4000>; - reg-names = "mmio", "asc"; - mboxes = <&aop_mbox>, <&aop_setup_mbox>; - mbox-names = "mbox", "setup"; - iommus = <&aop_dart 0>; - apple,dma-range = <0x110 0x0 0x10 0x0>; - - aop_audio: audio { - compatible = "apple,t8142-aop-audio", "apple,t8152-aop-audio"; - /* The microphone card's name: AppleJ813HPAI. */ - apple,chassis-name = "J813"; - apple,machine-kind = "MacBook Air"; - /* hpai: leap-s RX0 (Linux channel 1, odd = DEV_TO_MEM). */ - dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, - <&admac_base_ns 0>, <&admac_base_ns 1>, - <&admac_leap_s 1>; - dma-names = "cout", "cin", "spkr", "sense", "hpai"; - power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, - <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, - <&ps_audio_mca4_m>, <&ps_audio_mca5_m>, - <&ps_audio_leap_s_a>, <&ps_audio_leap_rx0>, - <&ps_audio_leap_mca>; - power-domain-names = "mca0", "mca1", "mca2", - "mca3", "mca4", "mca5", - "leap_s_a", "leap_rx0", "leap_mca"; - #sound-dai-cells = <1>; - }; +&aop { + aop_audio: audio { + compatible = "apple,t8142-aop-audio", "apple,t8152-aop-audio"; + /* The microphone card's name: AppleJ813HPAI. */ + apple,chassis-name = "J813"; + apple,machine-kind = "MacBook Air"; + /* hpai: leap-s RX0 (Linux channel 1, odd = DEV_TO_MEM). */ + dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, + <&admac_base_ns 0>, <&admac_base_ns 1>, + <&admac_leap_s 1>; + dma-names = "cout", "cin", "spkr", "sense", "hpai"; + power-domains = <&ps_audio_mca0_m>, <&ps_audio_mca1_m>, + <&ps_audio_mca2_m>, <&ps_audio_mca3_m>, + <&ps_audio_mca4_m>, <&ps_audio_mca5_m>, + <&ps_audio_leap_s_a>, <&ps_audio_leap_rx0>, + <&ps_audio_leap_mca>; + power-domain-names = "mca0", "mca1", "mca2", + "mca3", "mca4", "mca5", + "leap_s_a", "leap_rx0", "leap_mca"; + #sound-dai-cells = <1>; }; }; @@ -408,7 +360,3 @@ }; }; }; - -&aop_dart { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index fe9e3b8ce77dbc..6cffcb3ab39e5d 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -127,26 +127,6 @@ #include "t8142-j813-n1.dtsi" #include "t8142-j813-audio.dtsi" -/* - * Ambient light sensor, the AOP's "als" service: an ST VD6286, as on J815 - * (same ADT node, /arm-io/aop/iop-aop-nub/als). aop_als sends it the - * per-device calibration (apple/aop-als-cal.bin). No firmware-name: that - * names the CT817 setup-port message, which this sensor does not take. - */ -&aop { - aop_als: als { - compatible = "apple,t8142-aop-als", "apple,aop-als"; - }; - - /* - * Lid angle: the J813 AOP firmware announces a "las" service, as the - * J815's does, and aop_las reads the hinge angle from it. - */ - aop_las: las { - compatible = "apple,t8142-aop-las", "apple,aop-las"; - }; -}; - /* * N1 functions behind apcie port 0 (0000:00:00.0 -> 01:00.{0,1,2}), so the * loader has somewhere to put the factory addresses: it copies ADT /chosen diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index c45d185c87c4c6..67f0a9894010ed 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -156,29 +156,6 @@ apple,platform-id = <0x72>; }; -/* - * Ambient light sensor, the AOP's "als" service: an ST VD6286, as on the - * M4 Pro, not T8140's CT817. aop_als sends it the per-device calibration - * (apple/aop-als-cal.bin) as its calibration property. There is no - * firmware-name: that names the CT817 setup-port message, which this sensor - * does not take. - */ -&aop { - aop_als: als { - compatible = "apple,t8142-aop-als", "apple,aop-als"; - }; - - /* - * Lid angle: the J815 AOP firmware announces a "las" service, which - * macOS 27.2 on this machine binds as an AppleSPUHIDDevice (usage page - * 0x20, usage 0x8a), as on T6050. The ADT's i2c1 "mogul-las" is the - * sensor's authentication chip, not the angle. - */ - aop_las: las { - compatible = "apple,t8142-aop-las", "apple,aop-las"; - }; -}; - /* * N1 functions behind apcie port 0 (0000:00:00.0 -> 01:00.{0,1,2}), so the * loader has somewhere to put the factory addresses: it copies ADT /chosen diff --git a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi index 949f6da167a896..5704217c983115 100644 --- a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi @@ -806,3 +806,87 @@ status = "disabled"; }; }; + +/* + * The AOP (always-on processor), laid out like T8140's (ascwrap-v6, + * asc-mailbox-v4), including the setup port. Its /arm-io/aop, + * aop-exclave-mailbox and dart-aop nodes and its iop-aop-nub services are + * the same in the J704, J813 and J815 ADTs (arm-io offset 0x210000000), so + * every T8142 board gets the AOP and its sensor services here; a board adds + * only its audio service. The AOP core needs no power-domains: the ADT gives + * it no power-gates and the AP never switches its states off. + */ +&{/soc} { + aop_mbox: mailbox@390608000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x90608000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* + * The ADT's aop-exclave-mailbox, flagged exclave-assigned as on T8140, + * is the AOP setup port the host drives. Its ADT reg (0x3d067c000) is + * not behind the arm-io translation: AOP ASC + 0x4007c000, as on + * T8140. ADT interrupts [497, 494], T8140's +100. + */ + aop_setup_mbox: mailbox@3d067c000 { + compatible = "apple,t8142-aop-setup-mailbox", "apple,t8140-aop-setup-mailbox"; + reg = <0x3 0xd067c000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + /* dart-aop stream 1: ADT vm-base-1 0x20000000000, as on T8140. */ + iommus = <&aop_dart 1>; + apple,dma-range = <0x200 0x0 0x10 0x0>; + #mbox-cells = <0>; + }; + + /* + * dart-aop: streams 0 (AOP), 3, 8 (admac-base-ns), 10 and 16 are the + * AP's; 1, 9 and 11 are exclave streams, of which the host drives 1 + * (setup port) and 11 (admac-leap-s) on the raw boot. As on T8140, the + * firmware's own mappings own the first slot, host buffers go above it. + */ + aop: aop@390c00000 { + compatible = "apple,t8142-aop", "apple,t8152-aop"; + reg = <0x3 0x90c00000 0x0 0x1e0000>, + <0x3 0x90600000 0x0 0x4000>; + reg-names = "mmio", "asc"; + mboxes = <&aop_mbox>, <&aop_setup_mbox>; + mbox-names = "mbox", "setup"; + iommus = <&aop_dart 0>; + apple,dma-range = <0x110 0x0 0x10 0x0>; + + /* + * Ambient light sensor, the AOP's "als" service + * (iop-aop-nub/als): an ST VD6286, as on the M4 Pro, not + * T8140's CT817. aop_als sends it the per-device calibration + * (apple/aop-als-cal.bin). There is no firmware-name: that + * names the CT817 setup-port message, which this sensor does + * not take. + */ + aop_als: als { + compatible = "apple,t8142-aop-als", "apple,aop-als"; + }; + + /* + * Lid angle: the AOP firmware announces a "las" service, which + * macOS binds as an AppleSPUHIDDevice (usage page 0x20, usage + * 0x8a), as on T6050. The ADT's i2c1 "mogul-las" is the + * sensor's authentication chip, not the angle; every T8142 + * laptop has it. The AOP registers the child only for a + * service its firmware announces. + */ + aop_las: las { + compatible = "apple,t8142-aop-las", "apple,aop-las"; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8142.dtsi b/arch/arm64/boot/dts/apple/t8142.dtsi index 11bddbb4ed3504..5c18e999ede264 100644 --- a/arch/arm64/boot/dts/apple/t8142.dtsi +++ b/arch/arm64/boot/dts/apple/t8142.dtsi @@ -223,7 +223,12 @@ reg = <0x3 0x90fc0000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; - status = "disabled"; + /* + * No power-domains: AOP_DART is in the AOP's own power tree + * (pmgr AOP_FILTER), which runs from before the handoff and + * which the AP never switches off; the ADT gives dart-aop and + * aop no power-gates. + */ }; pmp_dart: iommu@380300000 { From 022bc851762c25e486e964bd16ef09450bc2032f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:34:05 +1100 Subject: [PATCH 0093/1514] Bluetooth: btcentauri: Select the transport by PCIe host, not by machine cen_probe() binds only when the machine compatible is apple,j813, apple,j815 or apple,j873g. The list grew one board at a time as each N1 machine came up; no board has a hardware reason to be refused. The one real split is between two transports for the same N1 Beta function (106b:1903): on T6050 the functions belong to btcentauri_t6050.c, which binds only behind an "apple,t6050-pcie" host bridge. Use that same selector here, as the generic Centauri Wi-Fi driver already does in centauri_pci.c: refuse a function whose host bridge parent node is "apple,t6050-pcie", keep the function 2 check, and leave the firmware state check (execution stage 2, unowned IPC) as the gate for whether there is anything to talk to. On the device trees in the tree today the result is the same: the only boards with an N1 behind a non-T6050 host are j813 and j815 (generic ECAM host) and j873g (apple,t8152-pcie); every T6050 board has its N1 behind apple,t6050-pcie and stays refused. A later board whose device tree describes its N1 port gets Bluetooth without a driver change. Fixes: a03e01fbb531 ("Bluetooth: add J813 N1 native transport and encrypted connection bring-up") Cc: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Cc: Nick Cc: Thomas Glanzmann Signed-off-by: Ryan Murray --- drivers/bluetooth/btcentauri.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/bluetooth/btcentauri.c b/drivers/bluetooth/btcentauri.c index 11bbc9d0cc6d1e..7ae66124aa7ce2 100644 --- a/drivers/bluetooth/btcentauri.c +++ b/drivers/bluetooth/btcentauri.c @@ -1007,9 +1007,15 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) struct cen_bt *bt; struct hci_dev *hdev; int ret; + struct pci_host_bridge *bridge = pci_find_host_bridge(pdev->bus); - if (!(of_machine_is_compatible("apple,j813") || of_machine_is_compatible("apple,j815") || - of_machine_is_compatible("apple,j873g")) || + /* + * The T6050 transport (btcentauri_t6050.c) owns every N1 function behind + * an "apple,t6050-pcie" host, as in centauri_pci.c. Any other host is + * ours; the firmware and IPC state are checked below. + */ + if ((bridge && bridge->dev.parent && + of_device_is_compatible(bridge->dev.parent->of_node, "apple,t6050-pcie")) || PCI_FUNC(pdev->devfn) != 2) return -ENODEV; bt = devm_kzalloc(&pdev->dev, sizeof(*bt), GFP_KERNEL); From 1f4da1ec68eef4aeb9d766570f308756b5e8b26f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:34:07 +1100 Subject: [PATCH 0094/1514] arm64: dts: apple: t8142: Neural Engine, video encoder and JPEG on every M5 The Neural Engine (with its three DARTs and ANE_SYS power state), the video encoder (two DARTs, VENC power tree) and both JPEG engines (DART, JPG power state) are SoC blocks: the J704, J813 and J815 ADTs give the same addresses, interrupts and power gates for ane, dart-ane, ave, dart-ave, jpeg0, jpeg1 and dart-jpeg. Only the J815 enabled all three and the J813 only the encoder (twice); the J704 had none of them. Turn them on in t8142-peripherals.dtsi and drop the per-board enables. The ANE and the encoder run firmware that iBoot preloads: the boot loader hands the preload over by compatible and disables the node when the ADT has none, so a board without a preload keeps them off. Every DART keeps its engine's power domain. The JPEG engines need no firmware. J815: no change in the built tree beyond status "okay" becoming implicit. J813: gains the Neural Engine and both JPEG engines. J704: gains all three. The ANE and JPEG enables on J815 come from m0d16l14n1's 33d8f13414be9 and c3c1417eadb1c. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8142-j813.dts | 82 ------------------- arch/arm64/boot/dts/apple/t8142-j815.dts | 82 ------------------- .../boot/dts/apple/t8142-peripherals.dtsi | 30 +++---- 3 files changed, 10 insertions(+), 184 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index fe9e3b8ce77dbc..5dc6ebcb4d2d3f 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -253,47 +253,6 @@ }; }; -/* - * The video encoder, its two DARTs and the VENC power tree. The J813 ADT has - * the same ave and dart-ave as the J815. The boot loader hands over iBoot's - * preloaded firmware, or disables the encoder when there is none. - */ -&ps_venc_sys { - status = "okay"; -}; - -&ps_venc_dma { - status = "okay"; -}; - -&ps_venc_pipe4 { - status = "okay"; -}; - -&ps_venc_pipe5 { - status = "okay"; -}; - -&ps_venc_me0 { - status = "okay"; -}; - -&ps_venc_me1 { - status = "okay"; -}; - -&ave_dart0 { - status = "okay"; -}; - -&ave_dart1 { - status = "okay"; -}; - -&ave { - status = "okay"; -}; - /* Unexposed chassis port instances remain described and disabled. */ /* @@ -304,47 +263,6 @@ status = "okay"; }; -/* - * Video encoder: ADT ave ("ave2", pre-loaded) behind dart-ave, the same - * addresses, interrupts and power states as on the J815. aura hands over the - * preloaded firmware or disables the node. - */ -&ps_venc_sys { - status = "okay"; -}; - -&ps_venc_dma { - status = "okay"; -}; - -&ps_venc_pipe4 { - status = "okay"; -}; - -&ps_venc_pipe5 { - status = "okay"; -}; - -&ps_venc_me0 { - status = "okay"; -}; - -&ps_venc_me1 { - status = "okay"; -}; - -&ave_dart0 { - status = "okay"; -}; - -&ave_dart1 { - status = "okay"; -}; - -&ave { - status = "okay"; -}; - #include "t8142-j813-sep.dtsi" #include "t8142-j813-j815-sleep.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index c45d185c87c4c6..6906adcc56eb86 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -389,85 +389,3 @@ &mcc { status = "okay"; }; - -/* - * Video encoder: ADT ave behind dart-ave (DART + CPUDART). aura hands over the - * preloaded 26A428 firmware (memory regions, CRCs in /chosen) or disables the - * node when the ADT has no preload. - */ -&ps_venc_sys { - status = "okay"; -}; - -&ps_venc_dma { - status = "okay"; -}; - -&ps_venc_pipe4 { - status = "okay"; -}; - -&ps_venc_pipe5 { - status = "okay"; -}; - -&ps_venc_me0 { - status = "okay"; -}; - -&ps_venc_me1 { - status = "okay"; -}; - -&ave_dart0 { - status = "okay"; -}; - -&ave_dart1 { - status = "okay"; -}; - -&ave { - status = "okay"; -}; - -/* - * The Neural Engine. It stays off until the first request: the firmware is - * started then, from the preload, and system sleep cycles it cold. - */ -&ps_ane_sys { - status = "okay"; -}; - -&ane_dart0 { - status = "okay"; -}; - -&ane_dart1 { - status = "okay"; -}; - -&ane_dart2 { - status = "okay"; -}; - -&ane { - status = "okay"; -}; - -/* Both JPEG engines and their DART. */ -&ps_jpg { - status = "okay"; -}; - -&jpeg_dart { - status = "okay"; -}; - -&jpeg0 { - status = "okay"; -}; - -&jpeg1 { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi index 949f6da167a896..bb0d0599a4fb2a 100644 --- a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi @@ -164,7 +164,6 @@ power-domains = <&ps_ane_sys>; /* The firmware DVAs reach 0x100_xxxx_xxxx. */ apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; ane_dart1: iommu@421820000 { @@ -175,7 +174,6 @@ interrupts = ; power-domains = <&ps_ane_sys>; apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; ane_dart2: iommu@421840000 { @@ -186,7 +184,6 @@ interrupts = ; power-domains = <&ps_ane_sys>; apple,dma-range = <0x0 0x0 0x400 0x0>; - status = "disabled"; }; /* @@ -195,6 +192,9 @@ * boot loader hands the preload over as firmware-text and firmware-data. * PWGATE is the ADT's reg[2] (PMGR +0x24000) + 0x3640, measured under * macOS 27.2.1. + * Every T8142 board has it (same ane/dart-ane in the J704, J813 and J815 + * ADTs), so it is on by default; the boot loader hands the preload over + * by this compatible and disables the node when the ADT has none. */ ane: ane@420000000 { compatible = "apple,t8142-ane"; @@ -213,7 +213,6 @@ 0x3807002e8 0x3807002eb 0x38070c008 0x38070c00b 0x582668000 0x582668003>; - status = "disabled"; }; scaler0_dart: iommu@305260000 { @@ -226,7 +225,10 @@ status = "disabled"; }; - /* ADT dart-jpeg: one DART for both engines, jpeg0 on SID 0, jpeg1 on SID 1. */ + /* + * ADT dart-jpeg: one DART for both engines, jpeg0 on SID 0, jpeg1 on SID 1. + * The JPEG engines need no firmware and are on every T8142 board. + */ jpeg_dart: iommu@301020000 { compatible = "apple,t8142-dart", "apple,t8110-dart"; reg = <0x3 0x1020000 0x0 0xc000>; @@ -235,7 +237,6 @@ /* ADT vm-base 0x100_0000_0000, vm-size 0x300_0000_0000 */ apple,dma-range = <0x100 0x0 0x300 0x0>; power-domains = <&ps_jpg>; - status = "disabled"; }; /* @@ -248,7 +249,6 @@ interrupts = ; iommus = <&jpeg_dart 0>; power-domains = <&ps_jpg>; - status = "disabled"; }; jpeg1: jpeg@301060000 { @@ -257,7 +257,6 @@ interrupts = ; iommus = <&jpeg_dart 1>; power-domains = <&ps_jpg>; - status = "disabled"; }; apr_dart: iommu@3a1020000 { @@ -562,7 +561,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "jpg"; - status = "disabled"; }; /* ADT pmgr device ANE_SYS (id 73), parent AFISOCNI3 (no power state). */ @@ -572,7 +570,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "ane_sys"; - status = "disabled"; }; ps_msr: power-controller@2a8 { @@ -604,7 +601,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "venc_sys"; - status = "disabled"; }; ps_venc_dma: power-controller@8000 { @@ -614,7 +610,6 @@ #reset-cells = <0>; label = "venc_dma"; power-domains = <&ps_venc_sys>; - status = "disabled"; }; ps_venc_pipe4: power-controller@8008 { @@ -624,7 +619,6 @@ #reset-cells = <0>; label = "venc_pipe4"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_pipe5: power-controller@8010 { @@ -634,7 +628,6 @@ #reset-cells = <0>; label = "venc_pipe5"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_me0: power-controller@8018 { @@ -644,7 +637,6 @@ #reset-cells = <0>; label = "venc_me0"; power-domains = <&ps_venc_dma>; - status = "disabled"; }; ps_venc_me1: power-controller@8020 { @@ -654,7 +646,6 @@ #reset-cells = <0>; label = "venc_me1"; power-domains = <&ps_venc_me0>; - status = "disabled"; }; }; @@ -726,7 +717,9 @@ * preloaded by iBoot and handed over by the boot loader, which adds the * memory regions. dart-ave is two DARTs (DART and CPUDART) on one IRQ; * stream 12 carries the temporal filter engines and must translate - * through the encoder's domain, not bypass. + * through the encoder's domain, not bypass. On by default (same ave and + * dart-ave in the J704, J813 and J815 ADTs); the boot loader disables + * the encoder when the ADT has no preload. */ ave_dart0: iommu@281080000 { compatible = "apple,t8142-dart", "apple,t8110-dart"; @@ -735,7 +728,6 @@ power-domains = <&ps_venc_sys>; #iommu-cells = <1>; apple,dma-range = <0x100 0x00004000 0x0 0xffffc000>; - status = "disabled"; }; ave_dart1: iommu@2810a0000 { @@ -745,7 +737,6 @@ power-domains = <&ps_venc_sys>; #iommu-cells = <1>; apple,dma-range = <0x100 0x00004000 0x0 0xffffc000>; - status = "disabled"; }; ave: video-codec@281100000 { @@ -764,7 +755,6 @@ power-domain-names = "dma", "pipe4", "pipe5", "me0", "me1"; iommus = <&ave_dart0 0>, <&ave_dart0 12>, <&ave_dart1 0>, <&ave_dart1 12>; - status = "disabled"; }; scaler0: scaler@305000000 { From 052aa1022b4af60522a1f0462df0edebc9a84147 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:40:14 +1100 Subject: [PATCH 0095/1514] dt-bindings: media: apple,prores: allow reg-names and resets on T6032 The T6032 branch of the schema lists reg, interrupts, power-domains and iommus only, so a T6032 ProRes node that names its windows or points at its reset fails validation under unevaluatedProperties. Every other variant already allows both. Allow the same core/wrapper/aux reg-names and a single reset as the T6030/T6031/T8122 branch. The second engine on each die (apr1/apr3) has only the core and wrapper windows, so reg-names keeps minItems 2. Signed-off-by: Ryan Murray --- .../devicetree/bindings/media/apple,prores.yaml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Documentation/devicetree/bindings/media/apple,prores.yaml b/Documentation/devicetree/bindings/media/apple,prores.yaml index 69be59afd4e70c..59de428584e077 100644 --- a/Documentation/devicetree/bindings/media/apple,prores.yaml +++ b/Documentation/devicetree/bindings/media/apple,prores.yaml @@ -123,12 +123,22 @@ allOf: minItems: 2 maxItems: 3 + reg-names: + minItems: 2 + items: + - const: core + - const: wrapper + - const: aux + interrupts: maxItems: 1 power-domains: maxItems: 1 + resets: + maxItems: 1 + iommus: minItems: 1 maxItems: 2 From 53f5d6c4e625c4dcf0ae6f5d909721ffb05b4140 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:33:55 +1100 Subject: [PATCH 0096/1514] spmi: apple: recover every generation 4 controller from a failed exchange After a failed exchange a generation 4 controller (apple,t8142-spmi: T8142 and T6050) has no known FIFO flush, so the driver reads the late or stray reply words out before the next command. That recovery ran only on a board list (J714s, J716c, J813, J815); every other generation 4 board refused all later commands on the bus for the rest of the boot, the PMU's RTC among them. The reply FIFO and its read-out are the controller's, the same on every board with it, and the recovery is bounded: it waits one command timeout, reads at most SPMI_GEN4_REPLY_DRAIN_MAX words, and keeps the failure if the FIFO does not empty. Run it for every generation 4 controller. The earlier generations keep their FIFO flush; the generation is the match data (!legacy_irqs), as before. The recovery was written by Diljit Singh and extended by Nick and Erik Bourget. Fixes: e6b75c3cfd5b0 ("spmi: apple: J714s: recover from a failed exchange on a generation 4 controller") Signed-off-by: Ryan Murray --- drivers/spmi/spmi-apple-controller.c | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index c5f8829cfeb455..0e862bb578defc 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -235,23 +235,13 @@ static int apple_spmi_wait_rx_not_empty(struct spmi_controller *ctrl) * late, or the stray one that was read in a reply's place, is read out instead: the bus gets a * command's whole timeout to finish, then the reply FIFO is read until it is empty. Nothing of * an old exchange can then answer a new command. A FIFO that does not empty keeps the failure. - * On the J714s, J716c, J813 and J815, whose deep sleep writes the PMU on this queue. - * Other generation 4 machines keep refusing later commands after a failed exchange. + * This is the controller's own reply FIFO, so it applies to every generation 4 controller + * (apple,t8142-spmi: T8142 and T6050), on every board. */ -static bool apple_spmi_gen4_recovers(void) -{ - return of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c") || - of_machine_is_compatible("apple,j813") || - of_machine_is_compatible("apple,j815"); -} - static int apple_spmi_gen4_recover(struct spmi_controller *ctrl, struct apple_spmi *spmi) { unsigned int i; - if (!apple_spmi_gen4_recovers()) - return -EIO; usleep_range(REG_POLL_TIMEOUT_US, 2 * REG_POLL_TIMEOUT_US); for (i = 0; i < SPMI_GEN4_REPLY_DRAIN_MAX; i++) { if (readl(spmi->regs + spmi->hw->status) & spmi->hw->rx_empty) { From 6f0ce9838d5b314b0151900d14d42078818479f1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:33:46 +1100 Subject: [PATCH 0097/1514] soc: apple: rtkit-helper: adopt the T6040/T6041 MTP by its compatible The retained live MTP handoff (buffer inventory required, the session marked preserved, no buffer allocation after adoption) was taken only when the machine was a J614s and the MTP was apple,t6041-mtp. The DART behind it was kept in bypass by the same machine check, a fixed MMIO address and a fixed node path. The handoff form belongs to the MTP firmware, which cannot be restarted once used, not to the board: every T6040 and T6041 board has the same MTP (apple,t6041-mtp in t604x.dtsi), and the boot loader picks the retained form by the MTP compatible alone (apple,t8132-mtp or apple,t6041-mtp). Key both sides on that: - rtkit-helper: the inventory and strict-buffer rules and the preserved flag follow apple,t6041-mtp, as they already follow apple,t8132-mtp. - apple-dart: an apple,t6041-dart that the apple,t6041-mtp's iommus points to keeps its bypass for an advertised mtp-live-v1 session and refuses an invalid one, on every board. Without a handoff in the device tree nothing changes: the J616s and the T6041 boards cold-start the MTP as before. With a boot loader that hands the MTP over on those boards, Linux now adopts it instead of resetting the DART under a firmware that cannot be restarted. The J614s handoff this generalizes was written by Michal S. Fixes: 49d9477d44060 ("soc: apple: retain the live J614s MTP handoff") Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 23 +++++++++++++---------- drivers/soc/apple/rtkit-helper.c | 25 +++++++++++++++++-------- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 4bb6491eedb8c4..71786f8a5ae5ce 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -5875,33 +5875,36 @@ static int apple_dart_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8140-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-dart")); /* - * J614s may arrive with the MTP live after the boot keyboard used it. - * Do not reset its DART unless there is no advertised handoff. + * A T6040/T6041 MTP (apple,t6041-mtp on both) may arrive live after the + * boot keyboard used it; its firmware cannot be restarted. Do not reset + * the DART it sits behind unless there is no advertised handoff. This + * follows the MTP node and its iommus link, so it holds on every board + * with that MTP. */ - if (of_machine_is_compatible("apple,j614s") && - res->start == 0x514800000ULL) { + if (of_device_is_compatible(dev->of_node, "apple,t6041-dart")) { struct device_node *mtp, *iommu; const char *handoff; bool live, advertised; - mtp = of_find_node_by_path("/mtp@514600000"); + mtp = of_find_compatible_node(NULL, NULL, "apple,t6041-mtp"); iommu = mtp ? of_parse_phandle(mtp, "iommus", 0) : NULL; - advertised = mtp && of_find_property(mtp, "apple,rtkit-handoff", NULL); - live = advertised && of_device_is_compatible(mtp, "apple,t6041-mtp") && + advertised = iommu == dev->of_node && + of_find_property(mtp, "apple,rtkit-handoff", NULL); + live = advertised && !of_property_read_string(mtp, "apple,rtkit-handoff", &handoff) && !strcmp(handoff, "mtp-live-v1"); - if (advertised && (!live || iommu != dev->of_node || dart->hw->type != DART_T8110 || + if (advertised && (!live || dart->hw->type != DART_T8110 || dart->locked || tunneled || !dart->supports_bypass || !apple_dart_streams_bypassed(dart))) { of_node_put(iommu); of_node_put(mtp); - dev_err(dev, "Refusing invalid J614s live MTP DART handoff\n"); + dev_err(dev, "Refusing invalid live MTP DART handoff\n"); ret = -EINVAL; goto err_clk_disable; } if (live) { dart->retained_mtp = true; - dev_info(dev, "Retaining the live J614s MTP bypass\n"); + dev_info(dev, "Retaining the live MTP bypass\n"); } of_node_put(iommu); of_node_put(mtp); diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 8d2b45d4cb26bc..30170eb1067ee4 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -185,6 +185,20 @@ static bool apple_rtkit_helper_reserved(struct device_node *np, return false; } +/* + * The MTPs whose live handoff uses the retained form: the boot loader always + * publishes the buffer inventory with the session, and no buffer may be + * allocated after adoption. That form belongs to the MTP firmware, so it is + * keyed on the MTP's compatible: every T8132 MTP and every T6040/T6041 MTP + * (both use apple,t6041-mtp), whichever board it sits in. The boot loader + * picks the form by the same compatibles. + */ +static bool apple_rtkit_helper_retained_mtp(struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t8132-mtp") || + of_device_is_compatible(np, "apple,t6041-mtp"); +} + static int apple_rtkit_helper_inherit_buffers( struct apple_rtkit_helper *helper, struct apple_rtkit_inherited_buffer *buffers) @@ -197,9 +211,7 @@ static int apple_rtkit_helper_inherit_buffers( /* T8140 producers predating the buffer inventory remain compatible. */ inventory = of_find_property(np, "apple,rtkit-buffers", &length); if (!inventory) { - if (of_device_is_compatible(np, "apple,t8132-mtp") || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(np, "apple,t6041-mtp"))) + if (apple_rtkit_helper_retained_mtp(np)) return -EINVAL; return 0; } @@ -293,8 +305,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) return dev_err_probe(dev, count, "Invalid inherited RTKit buffers\n"); if ((apple_t8132_live_mtp() && of_device_is_compatible(dev->of_node, "apple,t8132-mtp")) || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(dev->of_node, "apple,t6041-mtp")) || + of_device_is_compatible(dev->of_node, "apple,t6041-mtp") || of_device_is_compatible(dev->of_node, "apple,t8142-mtp")) helper->preserved = true; } @@ -341,9 +352,7 @@ static int apple_rtkit_helper_probe(struct platform_device *pdev) */ helper->adopted = true; helper->strict_buffers = count > 0 || - of_device_is_compatible(dev->of_node, "apple,t8132-mtp") || - (of_machine_is_compatible("apple,j614s") && - of_device_is_compatible(dev->of_node, "apple,t6041-mtp")); + apple_rtkit_helper_retained_mtp(dev->of_node); helper->rtk = apple_rtkit_init_adopted_with_buffers( dev, helper, NULL, 0, &apple_rtkit_helper_ops, buffers, count); if (IS_ERR(helper->rtk)) From 3b5e96ddbd07fa60c121eaacf0ae216717059d94 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:41:54 +1100 Subject: [PATCH 0098/1514] arm64: dts: apple: t8122, t603x: complete the ProRes node descriptions The disabled ProRes nodes and their DARTs on T8122, T6030, T6031 and T6032 came with the M3 resource inventory, both by Ryan Murray: commit 982f3305722c ("arm64: dts: apple: describe disabled M3 peripheral resources") commit 4c28191ae7b9 ("arm64: dts: apple: describe disabled T6032 package resources") Checked against the ADT of every M3 board (J613, J615, J433, J434, J504, J514s/c/m, J516s/c/m, J575d) and our own IODeviceTree capture of a J615 under macOS 27.2, their reg, interrupts, DART SIDs and power domains are right, but three things are missing: - reg-names. The driver maps its windows by name (core, wrapper, aux), so without them no variant could ever map these nodes. apr0 on each die has all three windows; apr1 on T6031/T6032 has core and wrapper only, as in the ADT. - resets. The ADT's device_reset function for each engine points at the same PMGR device as its power domain (SCODEC for apr/apr0/apr2, PRORES for apr1/apr3), so the engine is reset through that domain. - power-domains on the T8122, T6030 and T6032 DARTs. The DART sits in the engine's domain; T6031 already says so, the others did not. All nodes stay disabled: the driver has no match data for these engines yet (see the PR for why). Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6030-peripherals.dtsi | 4 ++++ arch/arm64/boot/dts/apple/t6031-peripherals.dtsi | 4 ++++ arch/arm64/boot/dts/apple/t6032-peripherals.dtsi | 14 ++++++++++++++ arch/arm64/boot/dts/apple/t8122-peripherals.dtsi | 4 ++++ 4 files changed, 26 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi index 358413f654dff5..872a11ccf4639d 100644 --- a/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-peripherals.dtsi @@ -77,6 +77,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -86,6 +87,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -503,10 +505,12 @@ reg = <0x3 0x0d000000 0x0 0x4000>, <0x3 0x0c000000 0x0 0x8000>, <0x3 0x0d078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = , ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr0 1>, <&dart_apr1 1>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi index 62fe3bdf6a9097..8e41876a9055bc 100644 --- a/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6031-peripherals.dtsi @@ -801,9 +801,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr00 1>, <&dart_apr01 1>; status = "disabled"; }; @@ -812,9 +814,11 @@ compatible = "apple,t6031-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores>; + resets = <&ps_prores>; iommus = <&dart_apr1 0>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi index 1404caaefeb416..6e9282fcbb50a4 100644 --- a/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6032-peripherals.dtsi @@ -37,6 +37,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -46,6 +47,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -55,6 +57,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_prores>; status = "disabled"; }; @@ -439,9 +442,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&ultra_dart_apr00 1>, <&ultra_dart_apr01 1>; status = "disabled"; }; @@ -450,9 +455,11 @@ compatible = "apple,t6032-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores>; + resets = <&ps_prores>; iommus = <&ultra_dart_apr10 0>; status = "disabled"; }; @@ -544,6 +551,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec_die1>; status = "disabled"; }; @@ -553,6 +561,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec_die1>; status = "disabled"; }; @@ -562,6 +571,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_prores_die1>; status = "disabled"; }; @@ -754,9 +764,11 @@ reg = <0x2 0xc5000000 0x0 0x4000>, <0x2 0xc4000000 0x0 0x1000000>, <0x2 0xc5078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_scodec_die1>; + resets = <&ps_scodec_die1>; iommus = <&ultra_dart_apr20 1>, <&ultra_dart_apr21 1>; status = "disabled"; }; @@ -765,9 +777,11 @@ compatible = "apple,t6032-prores", "apple,prores"; reg = <0x2 0x87000000 0x0 0x4000>, <0x2 0x86000000 0x0 0x1000000>; + reg-names = "core", "wrapper"; interrupt-parent = <&aic>; interrupts = ; power-domains = <&ps_prores_die1>; + resets = <&ps_prores_die1>; iommus = <&ultra_dart_apr30 0>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi index 11d4fbcfba8df6..0d52039bf47274 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi @@ -77,6 +77,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -86,6 +87,7 @@ interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_scodec>; status = "disabled"; }; @@ -429,10 +431,12 @@ reg = <0x3 0x21000000 0x0 0x4000>, <0x3 0x20000000 0x0 0x8000>, <0x3 0x21078000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; interrupt-parent = <&aic>; interrupts = , ; power-domains = <&ps_scodec>; + resets = <&ps_scodec>; iommus = <&dart_apr0 1>, <&dart_apr1 1>; status = "disabled"; }; From 5b9abded85e3437f11013d80715ce1e603ffd6d5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:15:56 +1100 Subject: [PATCH 0099/1514] drm/apple: process the start's hotplug reports instead of sleeping 100 ms apple_drm_init_dcp() sleeps 100 ms once every display processor is ready, "to settle before a modeset". It came with commit 8d9bd6112604 ("drm: apple: Adjust startup sequence and timing for dptx"), which also slept 500 ms in dcp_start() so that a DPTX link could deliver its timing modes. A week later commit 1a9051d4c67d ("drm: apple: dptx: Wait for link config on connect") replaced that start-time sleep with a wait for the link configuration, which the connect at start still does. What can still be pending when the last processor reports ready is the hotplug work its firmware queued during the start: the connection state and modes the first modeset reads. Flush each connector's pending hotplug work instead. A report queued during the start is processed before the device registers, as the sleep intended, and nothing is waited for when there is none. A report that comes later reaches DRM as a hotplug event, as one after the 100 ms does today. The DRM device registers about 115 ms after the last "DCP booted" on the J616s, M1 Pro and M2, and the boot waits for that device in the initramfs, so all of the sleep was on the boot path. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index dddbacc0cf41a9..de7f2091de4137 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -1493,6 +1492,22 @@ static void apple_drm_quiesce_connectors(struct drm_device *drm) drm_connector_list_iter_end(&iter); } +/* Process the hotplug reports queued while the display processors started. */ +static void apple_drm_flush_start_reports(struct drm_device *drm) +{ + struct drm_connector_list_iter iter; + struct drm_connector *connector; + + drm_connector_list_iter_begin(drm, &iter); + drm_for_each_connector_iter(connector, &iter) { + /* A T8132 external output has no DCP hotplug work. */ + if (t8132_ext_connector(connector)) + continue; + flush_work(&to_apple_connector(connector)->hotplug_wq); + } + drm_connector_list_iter_end(&iter); +} + /* * Each display processor runs its own RTKit firmware, and starting one waits * for its firmware: a T6041 external processor takes 0.6 to 1.6 s to bring up @@ -1650,8 +1665,12 @@ static int apple_drm_init_dcp(struct device *dev) return -ENODEV; } - /* HACK: Wait for dcp* to settle before a modeset */ - msleep(100); + /* + * What the firmware reported while its processor started (connection, + * modes) is processed before the device registers, so the first + * modeset sees it. Later reports arrive as hotplug events. + */ + apple_drm_flush_start_reports(&apple->drm); return 0; } From 1fb8a583775e77c7d436aebed282d1b6a8df4c0f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:32:16 +1100 Subject: [PATCH 0100/1514] drm/apple: explain why external pipes skip the opaque X property The comment in iomfb_enqueue_opaque_x() called the opaque X property a "panel-only workaround". It is not a workaround: commit 394bab2e9eee ("drm: apple: configure opaque X formats on H17P") sends it because H17P blends the stored X byte of an XRGB surface as alpha, and the property makes the firmware treat it as opaque. Commit 8eb1d0408511 ("drm/apple: keep opaque X property off experimental DCPEXT") keeps it off the H17P external controller because that firmware answers it with status 4, which the completion treats as fatal. Commit 9649e5974600 ("drm/apple: support retained J613 native26 external displays") keeps native26 external pipes off it as well. Say that instead. No code change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1f3e97e6c5e9f0..6b95e755e1c012 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -397,7 +397,13 @@ static int iomfb_enqueue_opaque_x(struct apple_dcp *dcp) struct iomfb_opaque_x_transaction *opaque; lockdep_assert_held(&dcp->iomfb.lock); - /* DCPEXT rejects enableGPAlphaDiv; retain the panel-only workaround. */ + /* + * H17P blends the X byte of an XRGB surface as alpha; this property + * makes the panel pipe take it as opaque. It is sent to panels only: + * the H17P external controller answers it with status 4, which + * iomfb_opaque_x_complete() treats as fatal, and native26 external + * pipes keep their own presentation path. + */ if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || dcp_is_ext26(dcp)) return 0; From 683090e37481890dca9de38fd6b7b40c423c864a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:34:30 +1100 Subject: [PATCH 0101/1514] drm/apple: remove the orphan dcp_trace.c dcp_trace.c only defines CREATE_TRACE_POINTS and includes dcp_trace.h, a header that does not exist. Neither the apple nor the drm Makefile builds it, and it has been unbuilt since it came in with the DPTX support in 4c8a6375f79b5. The driver's tracepoints live in trace.c and trace.h. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp_trace.c | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 drivers/gpu/drm/apple/dcp_trace.c diff --git a/drivers/gpu/drm/apple/dcp_trace.c b/drivers/gpu/drm/apple/dcp_trace.c deleted file mode 100644 index d18e71af73a74d..00000000000000 --- a/drivers/gpu/drm/apple/dcp_trace.c +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -#define CREATE_TRACE_POINTS -#include "dcp_trace.h" \ No newline at end of file From 3b528f1eec8f4b8787344fc1a86c9c854dd72b46 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:34:58 +1100 Subject: [PATCH 0102/1514] drm/apple: drop the 13.3 firmware-compat fallback for 13.5 dcp_check_firmware_version() maps firmware-compat 13.3.0 with firmware 13.5.0 to the 13.5 interface. The comment says this lasts until m1n1 reports 13.5 as firmware-compat. m1n1 has done that since e4ea2d53 ("kboot: dcp: Use OS firmware 13.5 as compat version", 2023-11-06), and aura carries it (src/kboot.c, V13_5B4/V13_5/V13_6_1 all report 13.5 compat), so every boot path we ship reaches the 13.5.0 branch directly. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 7cde46e009096f..4d908cf3d2d79b 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5934,16 +5934,6 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) if (strncmp(compat_str, "12.3.0", sizeof(compat_str)) == 0) return DCP_FIRMWARE_V_12_3; - /* - * m1n1 reports firmware version 13.5 as compatible with 13.3. This is - * only true for the iomfb endpoint. The interface for the dptx-port - * endpoint changed between 13.3 and 13.5. The driver will only support - * firmware 13.5. Check the actual firmware version for compat version - * 13.3 until m1n1 reports 13.5 as "firmware-compat". - */ - else if ((strncmp(compat_str, "13.3.0", sizeof(compat_str)) == 0) && - (strncmp(fw_str, "13.5.0", sizeof(compat_str)) == 0)) - return DCP_FIRMWARE_V_13_5; else if (strncmp(compat_str, "13.5.0", sizeof(compat_str)) == 0) return DCP_FIRMWARE_V_13_5; else if (strncmp(compat_str, "14.7.0", sizeof(compat_str)) == 0 && From 1a9583e603a29facc19bad64418ee765dc9a8687 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:36:11 +1100 Subject: [PATCH 0103/1514] ASoC: apple: aop_audio: leave out T6040 microphones the firmware did not set up On the T6040 flow (apple,t6041-aop-audio: J614s, J616s) the probe sends the low-power microphone's channel masks (lpai property 300), the PDM configuration (property 200) and the high-frequency decimator configuration (property 212), and on a refusal or a failed call logs "... refused, continuing" and registers both microphone PCMs anyway. The same PDM and decimator calls fail the probe on every other SoC this driver serves. The T6040 exception was made during bring-up so that each later step's answer could still be seen; it leaves a capture that starts on whatever configuration the firmware held, silence or garbage with nothing in the log at the time of the capture. Make each refusal cost what it configures. Without the PDM or decimator setup no microphone is offered: the probe registers only the speaker and jack streams the node lists, as it does on a Mac without microphones, and fails with the error when it lists none. Without the channel masks the low-power microphone PCM is left out and the array stays. Each failure is logged with its return code. A firmware that accepts all three, as the J616s one does, sees no change. Fixes: 2ba1e89d9d6b ("ASoC: apple: aop_audio: configure the T6040 microphones as macOS does") Cc: Jonathan Goyvaerts Signed-off-by: Ryan Murray --- sound/soc/apple/aop_audio.rs | 78 ++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 25 deletions(-) diff --git a/sound/soc/apple/aop_audio.rs b/sound/soc/apple/aop_audio.rs index 113b0ea6db869e..e52a22c1518658 100644 --- a/sound/soc/apple/aop_audio.rs +++ b/sound/soc/apple/aop_audio.rs @@ -540,8 +540,8 @@ struct SndSocAopHwConfig { bytes_per_sample: u32, hf_decimator: bool, // The T6040 firmware takes the microphone setup macOS sends. LPAI property 301 is the - // read-only stream description; the channel masks are property 300 (12 bytes). A refusal of - // any of the configuration steps is logged and not fatal, so the next step's answer is seen. + // read-only stream description; the channel masks are property 300 (12 bytes). A refused + // step leaves out the microphones it sets up (see the probe), not the speaker or jack. t6040_flow: bool, } @@ -695,8 +695,12 @@ impl SndSocAopData { }; let msg = AudioSetDeviceProp::new(AUDIO_DEV_LPAI, 300, ctl); let ret = self.epic_wrapped_call(&msg)?; - dev_dbg!(self.dev, "lpai channel control (prop 300): {:#x}\n", ret); if ret != 0 { + dev_err!( + self.dev, + "Unable to set lpai channel masks, return code {:#x}\n", + ret + ); return Err(EIO); } Ok(()) @@ -1176,6 +1180,23 @@ impl platform::Driver for AopAudio { } impl SndSocAopDriver { + /// Registers only the speaker and jack streams the node lists, for a + /// machine whose microphones are absent or could not be set up; `err` + /// when it lists none either. + fn without_microphones(data: Arc, streams: bool, err: Error) -> Result { + if !streams { + return Err(err); + } + let mut this = SndSocAopDriver { + card: ptr::null_mut(), + mic: aop_lid::MicLid::new()?, + spkr: None, + lpai: None, + }; + this.spkr = Some(aop_spkr::SpeakerComponent::register(data)?); + Ok(this) + } + fn probe( pdev: &platform::Device>, info: &'static SndSocAopHwConfig, @@ -1213,17 +1234,7 @@ impl SndSocAopDriver { // channel: its firmware has no PDM devices, so attach only the // speaker and jack streams. if info.t6040_flow && !listed(c_str!("dma")) { - if !streams { - return Err(ENODEV); - } - let mut this = SndSocAopDriver { - card: ptr::null_mut(), - mic: aop_lid::MicLid::new()?, - spkr: None, - lpai: None, - }; - this.spkr = Some(aop_spkr::SpeakerComponent::register(data)?); - return Ok(this); + return Self::without_microphones(data, streams, ENODEV); } for dev in [AUDIO_DEV_PDM0, AUDIO_DEV_HPAI, AUDIO_DEV_LPAI] { data.audio_attach_device(dev)?; @@ -1233,20 +1244,37 @@ impl SndSocAopDriver { } if info.t6040_flow { // Property 301 is the read-only stream description on this firmware (writing it - // returns 0xE00002CF, kIOReturnNotWritable). Follow macOS: channel masks are property - // 300. A refusal is reported and does not stop the probe. - if data.set_lpai_channel_control().is_err() { - dev_warn!(data.dev, "lpai channel control refused, continuing\n"); - } - if data.set_pdm_config().is_err() { - dev_warn!(data.dev, "pdm config refused, continuing\n"); - } - if data.set_decimator_config_hf().is_err() { - dev_warn!(data.dev, "decimator config refused, continuing\n"); + // returns 0xE00002CF, kIOReturnNotWritable); the channel masks are property 300. + // The masks are the low-power microphone's: without them the card offers the + // array alone. Without the PDM and decimator setup the array would capture + // from whatever the firmware held, so no microphone is offered; the speaker + // and jack streams do not depend on it and are still registered. + let lpai_masks = data + .set_lpai_channel_control() + .inspect_err(|e| { + dev_err!( + data.dev, + "lpai channel masks not set ({:?}): no low-power microphone\n", + e + ); + }) + .is_ok(); + if let Err(e) = data + .set_pdm_config() + .and_then(|()| data.set_decimator_config_hf()) + { + dev_err!( + data.dev, + "microphone setup failed ({:?}): no microphones\n", + e + ); + return Self::without_microphones(data, streams, e); } // The low-power microphone's ring goes through the audio node's // own DART stream; a node without one has the array only. - let lpai = if data.fwnode.property_present(c_str!("iommus")) { + let lpai = if !lpai_masks { + None + } else if data.fwnode.property_present(c_str!("iommus")) { // SAFETY: no DMA is in flight on this device yet. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::<42>())? }; aop_lpai::LpaiCapture::new_ring( From 919919922046616e1afdee66b116f0e5da6b2f50 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:38:21 +1100 Subject: [PATCH 0104/1514] ASoC: apple: aop_t8140: say when a leaf power-up needed a retry PowerDomain::get() retries a serializer leaf's runtime-PM resume up to 60 times, 10 ms apart, when the PMGR driver times out with the audio fabric still coming up. Since 07084c352b61 every leaf request runs only after the low-power microphone's first report, which proves the fabric up, and the retry stayed as a fallback. A retry that then succeeded was silent in this driver, so nothing showed whether the fallback still fires; and the error gate still compared against PD_GET_ATTEMPTS, the count of a blind pass that no longer exists, so it was always true. Return the attempts a domain took and warn with the count when it took more than one: that is a fabric the report did not prove up. Log every final failure, and drop PD_GET_ATTEMPTS. The retry and the error-state reset stay until the warning has been seen not to fire (#2345). Signed-off-by: Ryan Murray --- sound/soc/apple/aop_t8140.rs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/sound/soc/apple/aop_t8140.rs b/sound/soc/apple/aop_t8140.rs index 751cde0c4eb8ed..b58896f348719e 100644 --- a/sound/soc/apple/aop_t8140.rs +++ b/sound/soc/apple/aop_t8140.rs @@ -130,9 +130,9 @@ const AUDIO_RET_BUSY: u32 = 0xe00002d5; const SPKR_POWER_STATE_PW0: u32 = from_fourcc(b"pw0 "); const SPKR_POWER_STATE_PWRD: u32 = from_fourcc(b"pwrd"); -/// Leaf power-up retries while the firmware raises the fabric (see `PowerDomain::get`). -/// Blind attempts before the fabric is raised, and attempts while it rises. -const PD_GET_ATTEMPTS: u32 = 3; +/// Leaf power-up attempts with the fabric raised (see `PowerDomain::get`): a +/// fallback, since the low-power microphone's first report already proves +/// the fabric up. Any retry is logged with the attempts it took. const PD_GET_RAISED_ATTEMPTS: u32 = 60; const PD_GET_RETRY_MS: i64 = 10; /// The fabric comes up some tens to hundreds of milliseconds after the @@ -359,14 +359,15 @@ impl PowerDomain { /// the PMGR driver's poll window with the parent still coming up. A /// failed resume leaves the virtual domain device in the runtime-PM error /// state, where every later request fails with EINVAL; clear that state - /// and retry a bounded number of times before giving up. - fn get(&self, attempts: u32) -> Result<()> { + /// and retry a bounded number of times before giving up. Returns the + /// attempts the domain took. + fn get(&self, attempts: u32) -> Result { let mut rc = 0; for attempt in 0..attempts { // SAFETY: the domain device stays attached for the lifetime of `self`. rc = unsafe { bindings::pm_runtime_get_sync(self.dev.as_ptr()) }; if rc >= 0 { - return Ok(()); + return Ok(attempt + 1); } // SAFETY: as above; a failed resume still took the usage count. unsafe { bindings::pm_runtime_put_noidle(self.dev.as_ptr()) }; @@ -803,8 +804,20 @@ impl SndSocT8140AopData { self.power_down(&pds[..i]); return Err(ENODEV); }; - if let Err(e) = pd.get(attempts) { - if e != ETIMEDOUT || attempts > PD_GET_ATTEMPTS { + match pd.get(attempts) { + Ok(1) => {} + Ok(n) => { + // The fabric was not up after the low-power + // microphone's report: the retry hid a slow fabric. + dev_warn!( + self.dev, + "{}: power domain {} up after {} attempts\n", + name, + pd.name, + n + ); + } + Err(e) => { dev_err!( self.dev, "{}: power domain {} did not power up: {:?}\n", @@ -812,9 +825,9 @@ impl SndSocT8140AopData { pd.name, e ); + self.power_down(&pds[..i]); + return Err(e); } - self.power_down(&pds[..i]); - return Err(e); } } Ok(()) From e5c3b1515d42bc58d222f58f6ee034278d7ce1c2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:39:11 +1100 Subject: [PATCH 0105/1514] soc: apple: aop: explain the AFK init resend after a full mailbox The single resend of an AFK init request whose send found the mailbox full for the whole send timeout said the firmware "can still be busy finishing its own boot". That is not what the code waits for: the send already waits on the mailbox's send-empty interrupt, start_afk() runs only after the RTKit power handshake, and the firmware sends no other event when it reads its inbound FIFO again. Say so, point at the J616s report the resend came from, and at the issue that tracks why the FIFO stays full. No functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/aop.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 3df2214e6db638..af99b2972e948e 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -1566,9 +1566,14 @@ impl AopData { let mut init = ep_guard.start(rtk.as_mut()); if init == Err(ETIMEDOUT) { // The mailbox stayed full for the whole send timeout, - // so the request was never written. The firmware can - // still be busy finishing its own boot: send it once - // more, which checks the mailbox again first. + // so the request was never written and a resend is + // safe. The send already waits on the mailbox's + // send-empty interrupt, and the firmware sends no + // other event when it reads its inbound FIFO again. + // Seen on a J616s warm boot with a slow firmware + // start (#547); why the FIFO stays full after the + // power handshake is open (#2344). Resend once, + // logged, then fail the endpoint. dev_warn!( self.dev, "Endpoint {:#04x}: AFK init not sent (mailbox full); retrying", From 09e5ad591293e80cb2f9930312ed166d5d45c317 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:48:19 +1100 Subject: [PATCH 0106/1514] scripts/dtc: fail the DT check when BASE cannot be checked apple-dt-check.sh compares the CHECK_DTBS warnings of HEAD against those of BASE and fails on any warning BASE does not have. When the BASE worktree cannot be added or its defconfig fails, warnings() returns before it writes base.warn. The script only logged "base build failed" and went on: comm then failed on the missing file, wrote an empty new.warn, and the run reported "new warnings: 0" and passed, whatever HEAD added. Treat a missing BASE list as an empty one and fail the run with a message that says BASE was not checked, so every HEAD warning is shown as new instead of none. warnings() also removes a stale list before it starts, so a reused work directory cannot stand in for a failed run. A BASE that configures but does not fully build keeps its current handling: its partial warning list still counts. Fixes: 43f2e230f081 ("ci: check every Apple device tree against its bindings") Signed-off-by: Ryan Murray --- scripts/dtc/apple-dt-check.sh | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index 820d8dc2daf418..0efba9a6fb9cd9 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -12,6 +12,7 @@ export ARCH=arm64 LLVM=1 mkdir -p "$W" warnings() { # rev tag local t=$W/src-$2 o=$W/out-$2 + rm -f "$W/$2.warn" git worktree add -q --detach "$t" "$1" || return 1 make -s -C "$t" O="$o" defconfig >/dev/null || return 1 local dtbs; dtbs=$(cd "$t/arch/arm64/boot/dts" && ls apple/*.dts | sed 's/dts$/dtb/') @@ -24,12 +25,18 @@ warnings() { # rev tag echo "$2: make rc=$rc, $(wc -l < "$W/$2.warn") warning lines, $(echo $dtbs | wc -w) DTBs" return $rc } +fail=0 warnings "$BASE" base || echo "base build failed (its warnings still count)" +if [ ! -f "$W/base.warn" ]; then + # No list to compare against: every HEAD warning counts as new. + echo "BASE $BASE could not be checked out or configured" + : > "$W/base.warn" + fail=1 +fi warnings "$HEAD" head; hrc=$? comm -13 "$W/base.warn" "$W/head.warn" > "$W/new.warn" comm -23 "$W/base.warn" "$W/head.warn" > "$W/gone.warn" echo "new warnings: $(wc -l < "$W/new.warn"), removed: $(wc -l < "$W/gone.warn")" -fail=0 [ $hrc = 0 ] || { echo "HEAD device trees do not build"; fail=1; } if [ -s "$W/new.warn" ]; then echo "--- new CHECK_DTBS warnings"; cat "$W/new.warn"; fail=1; fi b=$(git diff --name-only --diff-filter=AM "$BASE" "$HEAD" -- 'Documentation/devicetree/bindings/*.yaml') From f2190d9f08b0bb714d5d1073acc2f625a8042c51 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:49:49 +1100 Subject: [PATCH 0107/1514] drm/apple: fabric test: drop the always-skipped S35 scenario The apple-dcp-fabric suite lists S35_dual_retry_off as a scenario, but its case only calls kunit_skip() with "TB match-data retry policy is tested by W3". No W3 test and no match-data retry policy exist in this tree: the commit that added the suite notes that "S35 remains TB policy coverage" and that this tree has no fabric retrain work. Every run therefore reports one skipped case that can never run, and the skip reads as coverage that does not exist. Remove the S35 row and its case, and narrow the dual-stream fixture range to the S30..S34 scenarios that remain. Add a default case that fails a scenario id with no case of its own, so a placeholder row cannot pass with no checks again. Fixes: 75a28393599b ("drm/apple: isolate display fabric decisions and add KUnit coverage") Cc: Chris Kearney <303316+iconidentify@users.noreply.github.com> Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-fabric-test.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric-test.c b/drivers/gpu/drm/apple/dcp-fabric-test.c index 254b1bb74358d5..730ca0832d2d81 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-test.c @@ -242,7 +242,6 @@ static const struct fabric_scenario scenarios[] = { { "S32_dual_hdmi_reclaim_core", 32 }, { "S33_dual_scores", 33 }, { "S34_dual_park_reselect", 34 }, - { "S35_dual_retry_off", 35 }, { "S40_desktop_promotion", 40 }, { "S41_dedicated_hdmi", 41 }, { "S50a_panel_has_no_routes_core", 50 }, @@ -269,7 +268,7 @@ static void fabric_scenario_test(struct kunit *test) enum dcp_fabric_fixed_step steps[2]; unsigned int count, order; - fabric_init(&f, scenario->id >= 30 && scenario->id <= 35); + fabric_init(&f, scenario->id >= 30 && scenario->id <= 34); switch (scenario->id) { case 1: f.port[0].preferred = &f.route[0][0]; @@ -438,9 +437,6 @@ static void fabric_scenario_test(struct kunit *test) f.pipeline[0].presence = DCP_FABRIC_SETTLING; KUNIT_EXPECT_EQ(test, fabric_tunnel(&f, 1, 0), 0); break; - case 35: - kunit_skip(test, "TB match-data retry policy is tested by W3"); - break; case 50: f.port[0].routes = NULL; KUNIT_EXPECT_PTR_EQ(test, @@ -481,6 +477,9 @@ static void fabric_scenario_test(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp_fabric_tunnel_request(f.port, 1, DCP_FABRIC_DPIN_MAX, &found), -EINVAL); break; + default: + KUNIT_FAIL(test, "scenario %u has no checks", scenario->id); + break; } } From b66c454609e3e4817a34b506c1791bbe05de3f1d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:50:48 +1100 Subject: [PATCH 0108/1514] drm/apple: iomfb: answer D134 by the H17P external firmware, not the board dcp_external_zero_reply() answered the async D134 record with a zero reply only when the method profile was H17P external and the machine was apple,j700 and the node apple,t8140-dcpext. D134 is a record of the H17P external firmware ABI. The method profile already names that ABI: only the apple,t8140-dcpext match data sets it, and probe admits such a processor only when its apple,firmware-version and apple,firmware-compat name the supported release (dcp_h17p_external_supported()). The machine and compatible checks decided nothing more. Key the reply on the method profile alone. No change on J700, the only board with this processor. The apple-dcp host selftest now expects the reply from the method profile alone. Fixes: 08b540f0caba ("drm/apple: answer the measured J700 external D134 record") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb.c | 13 +++++++------ .../selftests/drivers/gpu/apple-dcp/lifecycle.py | 9 ++++++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1f3e97e6c5e9f0..2b362b15121c36 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -2048,9 +2048,12 @@ void dcp_hotplug(struct work_struct *work) } /* - * J700/25G83 asks D134 after publishing its external video interface. - * The observed async record has no input and a four-byte result. Use the - * existing zero reply for this record only; its feature remains unsupported. + * The H17P external firmware (26.6.2) asks D134 after publishing its + * external video interface. The observed async record has no input and a + * four-byte result. Use the existing zero reply for this record only; its + * feature remains unsupported. The record belongs to the firmware ABI: the + * method profile is only set for that firmware, which probe has already + * checked against apple,firmware-version (dcp_h17p_external_supported()). */ static bool dcp_external_zero_reply(struct apple_dcp *dcp, int tag, enum dcp_context_id context, @@ -2059,9 +2062,7 @@ static bool dcp_external_zero_reply(struct apple_dcp *dcp, int tag, return tag == 134 && context == DCP_CONTEXT_ASYNC && in_len == 0 && out_len == sizeof(u32) && dcp->hw.iomfb_method_profile == - DCP_IOMFB_METHODS_H17P_EXTERNAL && - of_machine_is_compatible("apple,j700") && - of_device_is_compatible(dcp->dev->of_node, "apple,t8140-dcpext"); + DCP_IOMFB_METHODS_H17P_EXTERNAL; } static void dcpep_handle_cb(struct apple_dcp *dcp, enum dcp_context_id context, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 9aa4f2041961b6..a32560259111dd 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -2100,8 +2100,10 @@ def dispatcher(root): static struct dcp_channel *dcp_get_channel(struct apple_dcp *d, enum dcp_context_id c) { (void)c; return &d->channel; } static int dcp_parse_tag(char *p) { (void)p; return case_tag; } -static bool of_machine_is_compatible(const char *n) { (void)n; return machine; } -static bool of_device_is_compatible(struct device_node *n, const char *s) +/* Neither the board nor the node decides the D134 reply any more. */ +static __attribute__((unused)) bool of_machine_is_compatible(const char *n) +{ (void)n; return machine; } +static __attribute__((unused)) bool of_device_is_compatible(struct device_node *n, const char *s) { (void)s; return n->external; } static bool iomfb_check_callback_h17p(struct apple_dcp *d, int t, u32 i, u32 o) { (void)d; (void)t; (void)i; (void)o; return true; } @@ -2140,7 +2142,8 @@ def dispatcher(root): d.hw.iomfb_method_profile = 0; case_tag = tag; acks = 0; dcpep_handle_cb(&d, context, h, sizeof(*h) + in + out, 0); - bool accepted = scope == 7 && tag == 134 && context == 3 && !in && out == 4; + /* Only the H17P external method profile (scope bit 2) decides. */ + bool accepted = (scope & 4) && tag == 134 && context == 3 && !in && out == 4; if (scope & 4) { assert(acks == accepted && d.crashed != accepted); for (unsigned i = 0; i < out; i++) From 89d2a67a18de1b997420dd9dfcc269c4014fe097 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:50:58 +1100 Subject: [PATCH 0109/1514] drm/apple: dcp: admit the H17P external path by its firmware, not the board dcp_h17p_external_supported() returned false unless the machine was apple,j700, before checking the processor's compatible and its apple,firmware-version/apple,firmware-compat against the supported firmware release. The external H17P path depends on the display processor (the apple,t8140-dcpext compatible, whose match data selects the H17P external method profile) and on the firmware release the loader describes in the device tree. The board is not part of either. Drop the machine check and keep the compatible and firmware checks, so the firmware table is what admits the path. No change on J700, the only board with this processor. The apple-dcp host selftest now checks that the machine is never consulted. Fixes: a7a7e2f37796 ("drm/apple: Compose the qualified J700 external display path") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 9 +++++++-- .../selftests/drivers/gpu/apple-dcp/lifecycle.py | 10 ++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 7cde46e009096f..59be549319d464 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -329,13 +329,18 @@ static void dcp_release_rtkit(void *data) #define DCP_BOOT_TIMEOUT msecs_to_jiffies(1000) +/* + * The H17P external display path is admitted by the processor and its + * firmware: an apple,t8140-dcpext node (the H17P external method profile) + * whose apple,firmware-version and apple,firmware-compat name the one + * firmware release that path speaks. The board does not enter into it. + */ bool dcp_h17p_external_supported(struct device_node *np) { u32 firmware[DCP_EXTERNAL_FW_CELLS], compat[DCP_EXTERNAL_FW_CELLS]; int firmware_cells, compat_cells; - if (!of_machine_is_compatible("apple,j700") || - !of_device_is_compatible(np, "apple,t8140-dcpext")) + if (!of_device_is_compatible(np, "apple,t8140-dcpext")) return false; firmware_cells = of_property_read_variable_u32_array( np, "apple,firmware-version", firmware, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index a32560259111dd..ecdc9be6b0f2e3 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1554,8 +1554,9 @@ def function(source, marker): static unsigned int references, released, node_puts, probes[2], bind_attempts, disables; static int preflight_error, external_probe_error, bind_result; static void try_bind(void); -static bool of_machine_is_compatible(const char *s) -{ assert(!strcmp(s,"apple,j700")); return machine_supported; } +/* The board must not enter into admission: any call fails the test. */ +static __attribute__((unused)) bool of_machine_is_compatible(const char *s) +{ (void)s; assert(false); return machine_supported; } static int of_property_read_variable_u32_array(struct device_node *n,const char *s,u32 *v,int min,int max) { assert(min==3 && max==3); @@ -1679,10 +1680,11 @@ def function(source, marker): { assert(apple_dcp_external_bw_valid(0xbc000,0x28000,0x70000)); assert(apple_dcp_external_clock_window(0x302800000ULL,0xbc000,0x302800000ULL,0xbc000)); - /* No command line state: exact J700 firmware selects the external profile. */ + /* No command line state: the exact firmware selects the external profile. */ initial(true); assert(dcp_h17p_external_supported(&nodes[1])); + /* The board does not: the same node and firmware on any machine. */ machine_supported=false; - assert(!dcp_h17p_external_supported(&nodes[1]) && match_providers()==1); + assert(dcp_h17p_external_supported(&nodes[1])); for(unsigned i=0;i<3;i++) { initial(true); nodes[1].firmware[i]++; assert(!dcp_h17p_external_supported(&nodes[1]) && match_providers()==1); From 03f5ad5410b911ac02b64144dc51546f9a3303de Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:51:04 +1100 Subject: [PATCH 0110/1514] phy: apple: atc: load the DisplayPort tunables by PHY and DT data, not the board atcphy_load_t8140_dp() returned -EOPNOTSUPP unless the machine was apple,j700. The caller only runs it for a PHY whose match data has has_t8140_dp (apple,t8140-atcphy), and the lists it applies are device tree properties passed by the bootloader. A node without them already fails the length check with -EINVAL, the caller warns, and dp_tunables stays false. Drop the machine check: the PHY compatible and the presence of the DT lists decide. The function keeps its name because has_t8140_dp, not a board, selects it. No change on J700, the only board with this PHY. Fixes: 7f67eba0ba5f ("phy: apple: apply the T8140 DisplayPort setup lists") Signed-off-by: Ryan Murray --- drivers/phy/apple/atc.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..c254a1f5e3df63 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -6220,8 +6220,12 @@ static int atcphy_load_t8140_dp(struct apple_atcphy *atcphy) { "apple,tunable-dp-common-post", atcphy->res.core, &atcphy->tunables.dp_common_post }, }; - if (!of_machine_is_compatible("apple,j700")) - return -EOPNOTSUPP; + + /* + * Only the PHY's compatible (has_t8140_dp) and the bootloader's DT + * data select this bundle. A node without the lists fails below, the + * caller warns, and dp_tunables stays false. + */ for (unsigned int i = 0; i < ARRAY_SIZE(lists); i++) { struct property *property = of_find_property(atcphy->np, lists[i].name, NULL); From 3719db6faf644dd9b143c325fc23535989f216d1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:51:07 +1100 Subject: [PATCH 0111/1514] drm/apple: iomfb: say why the external HDR hints follow the firmware The comment above dcp_external_hdr_hints() said only the H17P external path sends the hints "for now". The call site has since added unpaired firmware 27 external processors, and the reason the hints are not sent everywhere is the firmware ABI: every firmware has set_parameter_dcp, but the parameter numbers are defined by each firmware build, and macOS was seen sending these two only on the H17P external firmware (26.6.2) and on firmware 27. Say so. No functional change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_template.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 066c7a5f1cfdda..91d87ccacc9b6f 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -669,9 +669,15 @@ static void dcp_external_hint_done(struct apple_dcp *dcp, void *out, void *cooki /* * After every mode set on an external display macOS sends IOMFB * parameters 3 and 6 (16.16): 3 at 1.0, and 6 at 1.0 for an SDR colour - * mode or 2.0 for a PQ one. Send the same, after the mode set. Only the - * H17P external path does so for now: the desktop 26.x external processors - * have not been checked with an HDR display yet. + * mode or 2.0 for a PQ one. Send the same, after the mode set. + * + * Every firmware has set_parameter_dcp, but the parameter numbers are the + * firmware's own, so the hints follow the firmware ABI rather than the + * method's presence: the H17P external firmware (26.6.2) and an unpaired + * external firmware 27 processor, the two on which macOS was seen sending + * them (iomfb_modeset()). The desktop 26.6 firmware is built without + * them, and older firmware is not sent them: no macOS trace shows what + * those builds take under these numbers. */ static void dcp_external_hdr_hints(struct apple_dcp *dcp, bool pq) { From 969abb49d0662bd805b7152b99080c7b8287d38c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:52:05 +1100 Subject: [PATCH 0112/1514] power: supply: macsmc: report the adapter's input power as power_now The AC supply tells how much the adapter may deliver (input_power_limit, from ACPW) but not how much the system takes from it now. The SMC has that too: PDTR is the DC-in power in watts, the "In" value of the driver's own log_power debug output. On a 16-inch MacBook Pro (M4 Pro, J616s) on a 15 W USB-C source, PDTR read 12.92 W while the SMC's system power read 6.2 W and the battery took 6.7 W, so PDTR is the input that feeds both. Report it as power_now on the AC supply when the key exists. With the battery's own power_now this gives the adapter's headroom and the charge rate without the debug log. Read it through a helper and test the float conversion with KUnit. Signed-off-by: Ryan Murray --- drivers/power/supply/macsmc-power-test.c | 68 +++++++++++++++++++++++- drivers/power/supply/macsmc-power.c | 16 ++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/drivers/power/supply/macsmc-power-test.c b/drivers/power/supply/macsmc-power-test.c index e3cf46b0f8d6f9..40993afb2be420 100644 --- a/drivers/power/supply/macsmc-power-test.c +++ b/drivers/power/supply/macsmc-power-test.c @@ -807,4 +807,70 @@ static struct kunit_suite macsmc_charge_test_suite = { .test_cases = macsmc_charge_test_cases, }; -kunit_test_suites(&macsmc_power_test_suite, &macsmc_charge_test_suite); +/* The adapter's input power, PDTR, a float in watts reported in microwatts */ +struct macsmc_ac_test { + struct apple_smc smc; + struct macsmc_power power; + u32 pdtr; + int err; +}; + +static int ac_test_read(struct apple_smc *smc, smc_key key, void *buf, size_t size) +{ + struct macsmc_ac_test *t = container_of(smc, struct macsmc_ac_test, smc); + + if (key != SMC_KEY(PDTR) || size != sizeof(u32)) + return -EINVAL; + if (t->err) + return t->err; + memcpy(buf, &t->pdtr, size); + return size; +} + +static int macsmc_ac_test_init(struct kunit *test) +{ + struct macsmc_ac_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + if (!t) + return -ENOMEM; + t->power.smc = &t->smc; + test->priv = t; + kunit_activate_static_stub(test, apple_smc_read, ac_test_read); + return 0; +} + +static void macsmc_ac_power_now_test(struct kunit *test) +{ + struct macsmc_ac_test *t = test->priv; + int uw = -1; + + t->pdtr = 0x414eb021; /* 12.918 W */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 12918000); + + t->pdtr = 0x430b8000; /* 139.5 W */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 139500000); + + t->pdtr = 0; /* adapter idle or unplugged */ + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), 0); + KUNIT_EXPECT_EQ(test, uw, 0); + + t->err = -EIO; + KUNIT_EXPECT_EQ(test, macsmc_ac_read_power_now(&t->power, &uw), -EIO); +} + +static struct kunit_case macsmc_ac_test_cases[] = { + KUNIT_CASE(macsmc_ac_power_now_test), + {} +}; + +static struct kunit_suite macsmc_ac_test_suite = { + .name = "macsmc-power-ac", + .init = macsmc_ac_test_init, + .test_cases = macsmc_ac_test_cases, +}; + +kunit_test_suites(&macsmc_power_test_suite, &macsmc_charge_test_suite, + &macsmc_ac_test_suite); diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index 5bd714eaf1b276..6cf63817dafe9e 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -895,6 +895,16 @@ static const struct power_supply_desc macsmc_battery_desc_template = { .property_is_writeable = macsmc_battery_property_is_writeable, }; +/* + * PDTR is the power the system takes from the adapter (DC in) now, in watts. + * With ACPW (what the adapter may deliver) it tells how much of the adapter is + * in use; the battery's own power_now tells how much of that goes to charging. + */ +static int macsmc_ac_read_power_now(struct macsmc_power *power, int *uw) +{ + return apple_smc_read_f32_scaled(power->smc, SMC_KEY(PDTR), uw, 1000000); +} + static int macsmc_ac_get_property(struct power_supply *psy, enum power_supply_property psp, union power_supply_propval *val) @@ -921,6 +931,9 @@ static int macsmc_ac_get_property(struct power_supply *psy, ret = apple_smc_read_u32(power->smc, SMC_KEY(ACPW), &vu32); val->intval = vu32 * 1000; break; + case POWER_SUPPLY_PROP_POWER_NOW: + ret = macsmc_ac_read_power_now(power, &val->intval); + break; default: return -EINVAL; } @@ -1283,6 +1296,9 @@ static int macsmc_power_probe(struct platform_device *pdev) if (apple_smc_key_exists(power->smc, SMC_KEY(ACPW))) props[nprops++] = POWER_SUPPLY_PROP_INPUT_POWER_LIMIT; + if (apple_smc_key_exists(power->smc, SMC_KEY(PDTR))) + props[nprops++] = POWER_SUPPLY_PROP_POWER_NOW; + /* macOS 15.4+ firmware dropped legacy AC keys (AC-n, AC-i) */ if (apple_smc_read_u16(power->smc, SMC_KEY(AC-n), &vu16) >= 0) { props[nprops++] = POWER_SUPPLY_PROP_VOLTAGE_NOW; From bc852111ba048d40a2f3a3576f63d37a178296ba Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:05:04 +1100 Subject: [PATCH 0113/1514] HID: spi-hid-apple: count GETs recovered after a bad status The M1 Pro trackpad answers the first sensor dimensions GET (report 0xd9) after the multitouch SET with the write status 9c 17 e5 f8 on about one boot in four. Since commit c48d1d05ae0f ("HID: spi-hid-apple: retry GETs after transient bad status") the GET is retried with a fresh ID within three attempts, and the retry has recovered every case, but the comment presented the rejection as expected and nothing kept count of how often the retry hides it. The cause is not established. The same status is what the controller returned for report 0x21, which the actuator does not have, in commit fcc170020a1c ("HID: spi-hid-apple: stop status mismatches on boot and suspend"). So the trackpad may switch to multitouch mode only after it has acknowledged the SET, and answer a GET that arrives first as for a missing report. SETs wait for nothing after their write status, and a reply to them is dropped at debug level, so the driver cannot tell. Keep the bounded retry. Describe the cause hypothesis at the retry, with the issue that tracks it, and count the GETs a retry recovered over the life of the device; the existing info line now carries the running total. Which requests are sent or retried, their timing and the log levels are unchanged. Link: https://github.com/aurora-silicon/linux/issues/2316 Signed-off-by: Ryan Murray --- drivers/hid/spi-hid/spi-hid-apple-core.c | 25 ++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/drivers/hid/spi-hid/spi-hid-apple-core.c b/drivers/hid/spi-hid/spi-hid-apple-core.c index d2b62f57cd8c0b..5e9882ff6a4f4b 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-core.c +++ b/drivers/hid/spi-hid/spi-hid-apple-core.c @@ -105,6 +105,8 @@ struct spihid_apple { wait_queue_head_t wait; struct mutex tx_lock; //< protects against concurrent SPI writes struct mutex get_report_lock; /* serializes synchronous GET_REPORTs */ + /* GETs a retry recovered after a bad status; get_report_lock */ + unsigned int get_report_recovered; spinlock_t reply_lock; /* protects reply state shared with the IRQ thread */ struct spi_message rx_msg; @@ -440,7 +442,7 @@ static int spihid_get_report(struct spihid_apple *spihid, { unsigned long flags; int attempt, ret; - unsigned int rejected = 0; + unsigned int rejected = 0, recovered = 0; bool bad_status, timed_out; ret = mutex_lock_interruptible(&spihid->get_report_lock); @@ -471,11 +473,16 @@ static int spihid_get_report(struct spihid_apple *spihid, /* * RX CRC validation can discard a reply even after a valid - * write status. A valid GET can also receive a bad status, - * including the first dimensions query after enabling MT. - * Retry either with a fresh ID, sharing the attempt limit. - * Keep SPI errors (even -EPROTO) and signals distinct from - * status mismatches so they are never replayed. + * write status. A valid GET can also receive a bad status: + * the M1 Pro trackpad answers 9c 17 e5 f8 to the first + * dimensions query after the multitouch SET on about one boot + * in four. That is the status a report the device does not + * have gets, so the mode switch may complete only after the + * SET is acknowledged; nothing here waits for it. The cause is + * not established (aurora-silicon/linux#2316), so retry either + * case with a fresh ID, sharing the attempt limit, and count + * the recoveries. Keep SPI errors (even -EPROTO) and signals + * distinct from status mismatches so they are never replayed. */ if (!timed_out && !bad_status) break; @@ -483,6 +490,8 @@ static int spihid_get_report(struct spihid_apple *spihid, rejected++; } + if (ret >= 0 && rejected) + recovered = ++spihid->get_report_recovered; mutex_unlock(&spihid->get_report_lock); if (ret < 0 && rejected) dev_err(&spihid->spidev->dev, @@ -493,8 +502,8 @@ static int spihid_get_report(struct spihid_apple *spihid, "get report %02x failed: %d\n", reportnum, ret); else if (rejected) dev_info_ratelimited(&spihid->spidev->dev, - "get report %02x recovered by retry (bad status: %u)\n", - reportnum, rejected); + "get report %02x recovered by retry (bad status: %u; %u GETs recovered since probe)\n", + reportnum, rejected, recovered); return ret; } From e2fac9f101ff54aa0e78d6c5015705f8d3a26955 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:22:17 +1100 Subject: [PATCH 0114/1514] arm64: dts: apple: t8132-laptop: describe the MagSafe 3 PD controller The M4 laptops (J604, J713, J715) have a third SN201202x on nub-spmi-a0 for the MagSafe 3 port (hpm5). It is not described, so there is no Type-C port and no tps6598x power supply for MagSafe; only the SMC sees the charger. Each board's ADT gives the same values: SID 8 on nub-spmi-a0, event, sleep and wake interrupts 63, 69 and 71 (the order of hpm0's 11, 17, 19), port-type 0x11, and features-supported <3> ("Power In" only). Add it once to t8132-laptop.dtsi, which all three include, with the T8132 compatible (selection is polled, event/sleep/wake use interrupts), no connector node (no USB data path) and apple,no-liquid-detection, as the J714s and the J815 MagSafe nodes do. The J604's comment that said hpm5 is not wired now points at the shared node. The desktops (J623, J624, J773g) do not include t8132-laptop.dtsi and build to identical DTBs. The node follows the J815 MagSafe node by Nick (m0d16l14n1) and the J714s one. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j604.dts | 2 +- arch/arm64/boot/dts/apple/t8132-laptop.dtsi | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j604.dts b/arch/arm64/boot/dts/apple/t8132-j604.dts index 0bbf299e6afca6..9bf5f08b5289bd 100644 --- a/arch/arm64/boot/dts/apple/t8132-j604.dts +++ b/arch/arm64/boot/dts/apple/t8132-j604.dts @@ -199,7 +199,7 @@ label = "USB-C Left Rear"; }; -/* hpm3 is ATC3's port controller; hpm5, the MagSafe port's, is not wired. */ +/* hpm3 is ATC3's port controller. The MagSafe port's, hpm5, is in t8132-laptop.dtsi. */ &nub_spmi_a1 { status = "okay"; diff --git a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi index c6a1a5ee78297e..23b87b0b64e317 100644 --- a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi @@ -156,3 +156,23 @@ spi-cs-hold-delay-ns = <20>; status = "okay"; }; + +/* + * The MagSafe 3 port's PD controller, on nub-spmi-a0 next to ATC0 and ATC1's + * (SID 8, port-type 0x11, the same in each laptop's ADT). It has no USB data + * path, so it gets no connector node; tipd registers a Type-C port and a power + * supply for it. Its event, sleep and wake interrupts are 63, 69 and 71 in the + * same order as hpm0's. Its ADT features-supported is <3>, "Power In" only: no + * liquid detection. + */ +&nub_spmi_a0 { + hpm5: usb-pd@8 { + compatible = "apple,t8132-sn201202x", "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + interrupts = <63 IRQ_TYPE_EDGE_RISING>, + <69 IRQ_TYPE_EDGE_RISING>, + <71 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + apple,no-liquid-detection; + }; +}; From 76a8a2a1a2e11c027f29be3d532e10acde274e17 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:19:22 +1100 Subject: [PATCH 0115/1514] iommu/apple-dart: gate the firmware table handoff on its DT property apple_dart_fw_handoff_enabled() required the DART to be locked, to carry apple,firmware-root-handoff = <1>, and to be an apple,t8140-dart. The property is the boot loader's statement that it reserved the locked root and leaf table pages; the compatible check added nothing a loader could not already say, and it would silently drop the handoff on any other SoC whose loader sets the property. Gate on the property and on the one hardware condition the table walker depends on: the DART uses the APPLE_DART2 page-table format, which apple_dart_pte_to_paddr() decodes. T8103-format DARTs never take the handoff. No in-tree DT sets the property; only the boot loader adds it, so DARTs without it are unchanged. The host fixture replaces its "other SoC" case with a DART1-format case. Fixes: e47d06ceb56f ("iommu/apple-dart: reserve retained firmware tables and root slots") Suggested-by: Chris Kearney <303316+iconidentify@users.noreply.github.com> Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 9 +++++++-- tools/asahi/apple-dart-fw-tests.py | 2 +- tools/asahi/apple-dart-fw/fixture.c | 8 ++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 4bb6491eedb8c4..4d996498e467dc 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -1034,13 +1034,18 @@ static phys_addr_t apple_dart_pte_to_paddr(const struct apple_dart *dart, return (pte & GENMASK_ULL(37, 10)) << 4; } -/* Firmware table pages must remain outside Linux's page allocator. */ +/* + * Firmware table pages must remain outside Linux's page allocator. The boot + * loader says it reserved them with apple,firmware-root-handoff; the walker + * decodes them in the APPLE_DART2 PTE layout, so that is the only other + * condition. + */ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) { struct device_node *np = dart->dev->of_node; u32 handoff; - return dart->locked && of_device_is_compatible(np, "apple,t8140-dart") && + return dart->locked && dart->hw->fmt == APPLE_DART2 && of_property_count_u32_elems(np, "apple,firmware-root-handoff") == 1 && !of_property_read_u32(np, "apple,firmware-root-handoff", &handoff) && handoff == 1; diff --git a/tools/asahi/apple-dart-fw-tests.py b/tools/asahi/apple-dart-fw-tests.py index 4541dc295bd4e1..281b11f9b47926 100644 --- a/tools/asahi/apple-dart-fw-tests.py +++ b/tools/asahi/apple-dart-fw-tests.py @@ -5,7 +5,7 @@ import argparse, hashlib, json, re, subprocess ROOT=Path(__file__).resolve().parents[2] NAMES=('apple_dart_fw_handoff_enabled','apple_dart_pte_to_paddr','apple_dart_fw_table_page','apple_dart_fw_table_ram','apple_dart_fw_table_pte','apple_dart_fw_table_decode','apple_dart_fw_tree_table','apple_dart_fw_slot_owned','apple_dart_fw_leaf_decode','apple_dart_fw_mapping_matches','apple_dart_fw_page_matches','apple_dart_fw_slot_mirrors','apple_dart_publish_root','apple_dart_retire_root','apple_dart_free_fw_root','apple_dart_snapshot_fw_root','apple_dart_free_fw_tree','apple_dart_fw_tree_phys','apple_dart_fw_slot_foreign','apple_dart_domain_uses_fw','apple_dart_check_fw_map','apple_dart_inherited_phys_prot','apple_dart_inherited_phys','apple_dart_fw_slot_range','apple_dart_get_fw_resv_regions','apple_dart_fw_invalidate','apple_dart_hw_unmap_locked_ttbr','apple_dart_retire_error','apple_dart_t8110_hw_invalidate_tlb','apple_dart_release_device','apple_dart_domain_free') -CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-other-soc','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') +CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') def function(s,name): match=re.search(r'^static[^;{}]*\b'+re.escape(name)+r'\([^;{}]*\)\s*\{',s,re.M) if not match:return None diff --git a/tools/asahi/apple-dart-fw/fixture.c b/tools/asahi/apple-dart-fw/fixture.c index f8fd490ddc306c..d566daa80bc16e 100644 --- a/tools/asahi/apple-dart-fw/fixture.c +++ b/tools/asahi/apple-dart-fw/fixture.c @@ -14,6 +14,7 @@ typedef uint8_t u8;typedef uint32_t u32;typedef uint64_t u64;typedef uint64_t ph #define IOMMU_WRITE 2 #define IOMMU_CACHE 4 #define APPLE_DART_PTE_VALID 1 +#define APPLE_DART 1 #define APPLE_DART2 2 #define GFP_KERNEL 0 #define MEMREMAP_WB 0 @@ -83,9 +84,8 @@ static int commands,command_error;static u64 command_start[8],command_end[8]; static int apple_dart_t8110_hw_tlb_command_range(struct apple_dart_stream_map*m,int op,bool range,u64 lo,u64 hi){assert(op==1&&range&&commands<8);command_start[commands]=lo;command_end[commands++]=hi;return command_error;} struct list_head {int count;}; struct iommu_resv_region {u64 start,length,dva;int prot,type;struct list_head list;}; -struct device_node {int count;u32 value;bool t8140;}; +struct device_node {int count;u32 value;}; struct iommu_device;struct device {struct device_node*of_node;struct apple_dart_master_cfg*cfg;struct iommu_device*iommu;}; -static int of_device_is_compatible(struct device_node*np,const char*s){assert(!strcmp(s,"apple,t8140-dart"));return np->t8140;} static int of_property_count_u32_elems(struct device_node*np,const char*s){assert(!strcmp(s,"apple,firmware-root-handoff"));return np->count;} static int of_property_read_u32(struct device_node*np,const char*s,u32*v){assert(!strcmp(s,"apple,firmware-root-handoff"));*v=np->value;return np->count<1?-EINVAL:0;} #define dev_iommu_priv_get(d) ((d)->cfg) @@ -188,7 +188,7 @@ int main(int argc,char**argv){ firmware_leaf[0]=leaf(0x8000);ours_leaf[0]=leaf(0x8000);phys_addr_t phys; struct apple_dart_domain domain={0};domain.stream_maps[0].dart=&d;domain.fw_sidmap[0][0]=1; struct apple_dart_master_cfg cfg={0};cfg.stream_maps[0].dart=&d;cfg.stream_maps[0].sidmap[0]=1; - struct iommu_device io={0};struct device_node node={1,1,true};struct device dev={&node,&cfg,&io};d.dev=&dev;struct list_head head={0}; + struct iommu_device io={0};struct device_node node={1,1};struct device dev={&node,&cfg,&io};d.dev=&dev;struct list_head head={0}; d.locked_ttbr[0][0]=root;static u64 shadow[2048];d.locked_owned[0][0]=shadow;d.locked_fw[0][0]=&fw; if(!strncmp(c,"legacy-",7)){ d.fw_handoff=0;d.fw_mirror=1;root[0]=0x1401; @@ -207,7 +207,7 @@ int main(int argc,char**argv){ if(!strcmp(c,"handoff-duplicate"))node.count=2; if(!strcmp(c,"handoff-zero"))node.value=0; if(!strcmp(c,"handoff-unlocked"))d.locked=0; - if(!strcmp(c,"handoff-other-soc"))node.t8140=false; + if(!strcmp(c,"handoff-dart1-format"))hw.fmt=APPLE_DART; assert(apple_dart_fw_handoff_enabled(&d)==!strcmp(c,"handoff-matched")); } else if(!strncmp(c,"core-",5)){ From 2561bf89b40816e78eea2049bff57eae5a0872ac Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:19:41 +1100 Subject: [PATCH 0116/1514] iommu/apple-dart: drop T8132 machine checks the DART match already makes Three probe-time conditions tested of_machine_is_compatible("apple,t8132") next to a check that already implies it: - the J713 radio DART and the off-qualified-firmware display DARTs also require an apple,t8132-dart node, which only T8132 device trees have; - the live MTP bypass retention also requires apple_t8132_live_mtp(), which is true only on T8132 boards (J713, J715, J604). Drop the machine checks. No behaviour change. Credit to Eryk Wieliczko and Diljit Singh, who wrote the conditions. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 4d996498e467dc..71412d018389e5 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -5374,7 +5374,6 @@ static int apple_dart_probe(struct platform_device *pdev) (res->start == 0x286300000ULL || res->start == 0x48a300000ULL); /* The radio DART's fault interrupt is not described by the loader. */ j713_radio = res && !tunneled && apple_t8132_managed_radio() && - of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && res->start == 0x490000000ULL; /* @@ -5382,7 +5381,6 @@ static int apple_dart_probe(struct platform_device *pdev) * over, but the running DCP still uses them: never reset them. */ if (res && !tunneled && !apple_t8132_firmware_path() && - of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { dev_info(dev, "Leaving inherited display DART untouched off the qualified firmware\n"); @@ -5913,7 +5911,7 @@ static int apple_dart_probe(struct platform_device *pdev) } dart->fw_tree = dart->fw_mirror && of_device_is_compatible(dev->of_node, "apple,t6050-dart"); - if (apple_t8132_live_mtp() && of_machine_is_compatible("apple,t8132") && + if (apple_t8132_live_mtp() && res->start == 0x394800000ULL && dart->hw->type == DART_T8110 && !dart->locked && !tunneled && dart->supports_bypass && apple_dart_streams_bypassed(dart)) { From 34ffc9fdc3d969b7645d61053dd65c63d9c68a21 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:21:54 +1100 Subject: [PATCH 0117/1514] wifi: brcmfmac: drop the T8132-only DMA mask; the IOMMU aperture sets it brcmf_pcie_probe() set a 42-bit DMA mask for any BCM4388 on an apple,t8132 machine, before the chip was attached. Right after the chip attach, brcmf_pcie_set_dma_mask() already raises the streaming and coherent masks to 42 bits for BCM4388 revisions 4 and 6 whenever the attached IOMMU domain's aperture starts above 4 GiB and ends within 42 bits, which is the T8132 case (the radio's aperture starts above 1 TiB). Nothing between the two allocates DMA memory. So the machine check repeated, for one SoC, a decision the aperture already makes for every Apple BCM4388. Remove it. Other Apple machines with a BCM4388 (T6020/T6030/T6040/T8122 boards) keep their behaviour: their apertures start below 4 GiB, and the helper leaves the mask alone. Fixes: ca550d3170f3 ("wifi: brcmfmac: use the T8132 radio DMA aperture") Suggested-by: Eryk Wieliczko Signed-off-by: Ryan Murray --- .../wireless/broadcom/brcm80211/brcmfmac/pcie.c | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 2bfee245f43312..fb6789f4636bd7 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -3103,22 +3103,6 @@ brcmf_pcie_probe(struct pci_dev *pdev, const struct pci_device_id *id) brcmf_dbg(PCIE, "Enter %x:%x\n", pdev->vendor, pdev->device); - /* - * T8132's BCM4388 IOVA aperture starts above 1 TiB and the message-buffer - * ABI carries full 64-bit host addresses, so do not retain PCI's - * conservative 32-bit default DMA mask on this platform. - */ - if (pdev->device == BRCM_PCIE_4388_DEVICE_ID && - of_machine_is_compatible("apple,t8132")) { - ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(42)); - if (ret) { - pci_err(pdev, "failed to enable 42-bit DMA: %d\n", ret); - return ret; - } - pci_info(pdev, "using 42-bit DMA addresses\n"); - } - - ret = -ENOMEM; devinfo = kzalloc_obj(*devinfo); if (devinfo == NULL) From 521a6bf80912e97287a4d60bc806bce7cb0285bf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:21:59 +1100 Subject: [PATCH 0118/1514] wifi: mt7932: bind by the radio's DT node, not the board mt_probe() required the machine to be apple,j700 and apple,t8140, and also required the function's DT node to be pci14c3,7932 behind an apple,t8140-pcie host bridge. The DT node and host checks already decide where the radio is; the board check only blocks another board with the same radio and host. Drop it. Today only the J700 device tree has a pci14c3,7932 node, so nothing changes on any machine. Suggested-by: Chris Kearney <303316+iconidentify@users.noreply.github.com> Signed-off-by: Ryan Murray --- drivers/net/wireless/mediatek/mt7932/mt7932.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/net/wireless/mediatek/mt7932/mt7932.c b/drivers/net/wireless/mediatek/mt7932/mt7932.c index 6ee30c04d8e640..d319cf497f5d2a 100644 --- a/drivers/net/wireless/mediatek/mt7932/mt7932.c +++ b/drivers/net/wireless/mediatek/mt7932/mt7932.c @@ -1233,8 +1233,8 @@ static int mt_probe(struct pci_dev *pdev, const struct pci_device_id *id) struct iommu_domain *domain; int ret; - if (!of_machine_is_compatible("apple,j700") || - !of_machine_is_compatible("apple,t8140") || pdev->devfn != 0 || + /* The radio's DT node, behind a T8140 PCIe host. */ + if (pdev->devfn != 0 || !of_device_is_compatible(pdev->dev.of_node, "pci14c3,7932") || !bridge->dev.parent || !of_device_is_compatible(bridge->dev.parent->of_node, From 42eb9603b99cf109e7217bc66e175bb50b9c9a2e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:25:51 +1100 Subject: [PATCH 0119/1514] arm64: dts: apple: t600x-j314-j316: drop the repeated USB4 aliases The aliases node lists usb4_{0,1,2}_rc and usb4_{0,1,2}_nhi twice with the same targets: once in the per-port groups and again at the end of the node (the alias commit was merged twice, dc2a2853446fc and 63e8f49b4e554). dtc keeps one copy, so the J314s/c and J316s/c DTBs are unchanged. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi | 7 ------- 1 file changed, 7 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi b/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi index f9bb3d9d034975..0d249725947b01 100644 --- a/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi +++ b/arch/arm64/boot/dts/apple/t600x-j314-j316.dtsi @@ -57,13 +57,6 @@ usb4_2_pcie = &apciec2; usb4-3-pcie = &apciec3; wifi0 = &wifi0; - - usb4_0_rc = &usb4_0_acio; - usb4_0_nhi = &usb4_0_nhi; - usb4_1_rc = &usb4_1_acio; - usb4_1_nhi = &usb4_1_nhi; - usb4_2_rc = &usb4_2_acio; - usb4_2_nhi = &usb4_2_nhi; }; chosen { From 8af6c2c1323feeb3dfe962da5c576e887c715d45 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:25:53 +1100 Subject: [PATCH 0120/1514] arm64: dts: apple: t8132: drop the unread disk-boot chosen flag /chosen/linux-enablement-mac,disk-boot came in with the J713 PMGR ownership policy (332eea1e9005b). Nothing reads it: no kernel code, script or document, nothing in aura or U-Boot, and nothing in our distro or platform packages. Its dapf-handoff and dapf-power-on-handoff siblings are read by aura (src/dapf.c, src/kboot.c) and stay. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-jxxx.dtsi | 1 - 1 file changed, 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index 03a129758b10b9..f471c65f7c413d 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -39,7 +39,6 @@ stdout-path = "serial0"; - linux-enablement-mac,disk-boot; linux-enablement-mac,dapf-handoff = "/arm-io/aop", "/arm-io/pmp"; linux-enablement-mac,dapf-power-on-handoff = "/arm-io/pmp"; From 3c53d3e2095c8f8b831e5db9f93367d565af369c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 01:28:56 +1100 Subject: [PATCH 0121/1514] drm/asahi: g17: M5: drop the unreachable EAGAIN retry of a host-port submission Firmware::submit_m5_render_pair() wrote a render pair's records, then the transaction through the M5 host command port, and on EAGAIN dropped the pair view, took the registration power hold and tried once more. Firmware::submit_m5_work() had the same retry for a single transaction. Both were added with the M5 host-port submission. G17Resources::submit_m5_work() cannot return EAGAIN: it returns Ok on a J813 forms boot, ENODEV once the register mapping is revoked, and otherwise only the result of try_write64(), which fails with EINVAL for an offset outside the mapping. The host command port needs no core power ("Core activity is not a prerequisite"), so no powered-state check exists that could refuse the transaction. The retry branch has never run, and the hold it would have taken is a no-op on M5 anyway: the V26A428_M5 variant has registration_power_hold false, since its firmware powers the cores for work by its own policy. Firmware::submit_m5_work() has no caller. Write the pair and submit once; any error propagates as before. Remove the uncalled single-transaction wrapper. Behaviour is unchanged on every SoC: the removed branch was unreachable. Fixes: 9b1f7788a69e ("drm/asahi: g17: M5: install M5 queues and submit through the host command port") Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g17/mod.rs | 43 +++++++------------------------- 1 file changed, 9 insertions(+), 34 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..e19cd54cd15bb5 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -900,21 +900,10 @@ impl Firmware { power::release(self) } - /// Retry a temporarily unavailable transaction once under a registration - /// power hold. Other access errors propagate to the retained owner. - fn submit_m5_work(&mut self, submission: &fw::m5::queue::HardwareSubmission) -> Result { - match self.bridge.regs.submit_m5_work(submission) { - Err(error) if error == EAGAIN => { - self.acquire_registration_power()?; - self.bridge.regs.submit_m5_work(submission) - } - result => result, - } - } - /// Both outer slots and their capacity are checked before any host-port - /// write. An EAGAIN retry drops the old views and revalidates them under a - /// power hold. After a successful transaction, publication is infallible. + /// write. The host command port needs no core power, and its transaction + /// fails only once the register mapping is gone; the error propagates. + /// After a successful transaction, publication is infallible. fn submit_m5_render_pair( &mut self, priority: u8, @@ -925,26 +914,12 @@ impl Firmware { deferred: bool, cursors: Option<[u32; 3]>, ) -> Result<[u32; 2]> { - let mut commit_accounting = Some(commit_accounting); - let mut publish_inner = Some(publish_inner); - let mut cursors = cursors; - for attempt in 0..2 { - let pair = self.init.m5_work_pair(priority, &records[0], &records[1], cursors.take())?; - pair.prepare(); - if let Some(commit) = commit_accounting.take() { commit()?; } - match self.bridge.regs.submit_m5_work(submission) { - Err(error) if error == EAGAIN && attempt == 0 => { - drop(pair); - self.acquire_registration_power()?; - } - Err(error) => return Err(error), - Ok(()) => { - if let Some(publish) = publish_inner.take() { publish(); } - return Ok(if deferred { pair.next() } else { pair.publish() }); - } - } - } - Err(EAGAIN) + let pair = self.init.m5_work_pair(priority, &records[0], &records[1], cursors)?; + pair.prepare(); + commit_accounting()?; + self.bridge.regs.submit_m5_work(submission)?; + publish_inner(); + Ok(if deferred { pair.next() } else { pair.publish() }) } /// Called at actual submission publication, not while a queued job is merely being built. From c0a9372ff7ff89b4a2341e0f83bf6fbb8a75dfcd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:00:21 +1100 Subject: [PATCH 0122/1514] drm/asahi: remove the vm module that is never built asahi_core.rs only declares mod vm under CONFIG_DRM_ASAHI_MAPLE_TREE, and no Kconfig defines that symbol, so vm/mod.rs and vm/range.rs (a copy of tyr's VM range code, dd23475817d47) have never been compiled. The driver's live VM code is in g15/vm.rs and the per-generation backends. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/asahi_core.rs | 2 - drivers/gpu/drm/asahi/vm/mod.rs | 5 -- drivers/gpu/drm/asahi/vm/range.rs | 125 ---------------------------- 3 files changed, 132 deletions(-) delete mode 100644 drivers/gpu/drm/asahi/vm/mod.rs delete mode 100644 drivers/gpu/drm/asahi/vm/range.rs diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b9706916510321..22ec0927272d3f 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -49,8 +49,6 @@ mod sysfs_exports; mod timestamp; mod usage; mod util; -#[cfg(CONFIG_DRM_ASAHI_MAPLE_TREE)] -mod vm; mod workqueue; use kernel::prelude::*; diff --git a/drivers/gpu/drm/asahi/vm/mod.rs b/drivers/gpu/drm/asahi/vm/mod.rs deleted file mode 100644 index 63cf8a76cd5ce4..00000000000000 --- a/drivers/gpu/drm/asahi/vm/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT - -//! Virtual address space management - -mod range; diff --git a/drivers/gpu/drm/asahi/vm/range.rs b/drivers/gpu/drm/asahi/vm/range.rs deleted file mode 100644 index 727d29a5cccf02..00000000000000 --- a/drivers/gpu/drm/asahi/vm/range.rs +++ /dev/null @@ -1,125 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 or MIT - -// Copied from tyr's mmu/vm/range.rs - -//! Range allocator. -//! -//! This module allows you to search for unused ranges to store GEM objects. - -use kernel::alloc::Flags; -use kernel::maple_tree::MapleTreeAlloc; -use kernel::prelude::*; -use kernel::sync::Arc; - -use core::ops::Range; - -/// The actual storage for the ranges. -/// -/// All ranges must fit within the `range` field. -/// -/// The implementation is different on 32-bit and 64-bit cpus. On 64-bit, the 64-bit addresses are -/// stored directly in the maple tree, but on 32-bit, the maple tree stores the ranges translated -/// in the range zero until `range.end-range.start`. This is done because the maple tree uses -/// unsigned long as its address type, which is too small to store the 64-bit address directly on -/// 32-bit machines. -#[pin_data] -struct RangeAllocInner { - #[pin] - maple: MapleTreeAlloc<()>, - range: Range, -} - -/// This object allows you to allocate ranges on the inner maple tree. -pub(crate) struct RangeAlloc { - inner: Arc, -} - -/// Represents a live range in the maple tree. -/// -/// The destructor removes the range from the maple tree, allowing others to allocate it in the -/// future. -pub(crate) struct LiveRange { - inner: Arc, - offset: u64, - size: usize, -} - -impl RangeAlloc { - pub(crate) fn new(start: u64, end: u64, gfp: Flags) -> Result { - if end < start { - return Err(EINVAL); - } - - let inner = Arc::pin_init( - try_pin_init!(RangeAllocInner { - maple <- MapleTreeAlloc::new(), - range: start..end, - }), - gfp, - )?; - - Ok(RangeAlloc { inner }) - } - - pub(crate) fn allocate(&self, size: usize, gfp: Flags) -> Result { - let maple_start = self.inner.range.start as usize; - let maple_end = self.inner.range.end as usize; - - let offset = self - .inner - .maple - .alloc_range(size, (), maple_start..maple_end, gfp)?; - - Ok(LiveRange { - inner: self.inner.clone(), - offset: offset as u64, - size, - }) - } - - pub(crate) fn insert(&self, start: u64, end: u64, gfp: Flags) -> Result { - if end < start { - return Err(EINVAL); - } - if start < self.inner.range.start { - return Err(EINVAL); - } - if end > self.inner.range.end { - return Err(EINVAL); - } - - self.inner - .maple - .insert_range(start as usize..end as usize, (), gfp)?; - - Ok(LiveRange { - inner: self.inner.clone(), - offset: start, - size: (end - start) as usize, - }) - } -} - -impl LiveRange { - pub(crate) fn size(&self) -> usize { - self.size - } - - pub(crate) fn start(&self) -> u64 { - self.offset - } - - pub(crate) fn end(&self) -> u64 { - self.offset + self.size as u64 - } - - pub(crate) fn range(&self) -> Range { - self.start()..self.end() - } -} - -impl Drop for LiveRange { - fn drop(&mut self) { - self.inner.maple.erase(self.offset as usize); - } -} From d65142bedebc4ba3cbe259accd1a6de6ca0c4218 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:00:29 +1100 Subject: [PATCH 0123/1514] drm/asahi: drop the 4K-page TLB invalidation guess tlbi_range() scales the page count by four under CONFIG_ARM64_4K_PAGES, with a comment that this is a guess. DRM_ASAHI depends on PAGE_SIZE_16KB, so a 4K-page kernel can never build this file. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/mem.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/mem.rs b/drivers/gpu/drm/asahi/mem.rs index 79071cbc434a04..1f4518be0bf29a 100644 --- a/drivers/gpu/drm/asahi/mem.rs +++ b/drivers/gpu/drm/asahi/mem.rs @@ -120,11 +120,6 @@ pub(crate) fn tlbi_range(asid: Asid, va: usize, len: usize) { let mut val: u64 = (u64::from(asid) << 48) | (2 << 46) | (start_pg as u64 & BADDR_MASK); let pages = end_pg - start_pg; - // Guess? It's possible that the page count is in terms of 4K pages - // when the CPU is in 4K mode... - #[cfg(CONFIG_ARM64_4K_PAGES)] - let pages = 4 * pages; - if pages == 1 { tlbi_page(asid, va); return; From 2e07e1b6b4fb8298b5e1cbe5eacd343e45ebece1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:00:52 +1100 Subject: [PATCH 0124/1514] drm/asahi: m3: remove the orphan agx3, agx_status and m3_coverage modules These three m3 modules are declared but nothing uses them; the crate-wide allow(dead_code) in m3/mod.rs hid that. The only other agx3 tables in the driver are g18's and hw::t8152's own, and the two m3 comments that cited hw::agx3::T8122 now state the value directly. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/agx_status.rs | 34 -------------- drivers/gpu/drm/asahi/m3/hw.rs | 1 - drivers/gpu/drm/asahi/m3/hw/agx3.rs | 59 ------------------------- drivers/gpu/drm/asahi/m3/hw/t8122.rs | 2 +- drivers/gpu/drm/asahi/m3/m3_coverage.rs | 45 ------------------- drivers/gpu/drm/asahi/m3/m3_soc.rs | 14 +++--- drivers/gpu/drm/asahi/m3/mod.rs | 4 -- 7 files changed, 8 insertions(+), 151 deletions(-) delete mode 100644 drivers/gpu/drm/asahi/m3/agx_status.rs delete mode 100644 drivers/gpu/drm/asahi/m3/hw/agx3.rs delete mode 100644 drivers/gpu/drm/asahi/m3/m3_coverage.rs diff --git a/drivers/gpu/drm/asahi/m3/agx_status.rs b/drivers/gpu/drm/asahi/m3/agx_status.rs deleted file mode 100644 index 1d83086a1d155f..00000000000000 --- a/drivers/gpu/drm/asahi/m3/agx_status.rs +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -//! CPU-owned sticky VM failure reporting. No GPU mapping or firmware access. -use core::sync::atomic::{AtomicI32, Ordering}; - -pub(crate) const PARAM_GROUP_VM_STATUS: u32 = 1; -pub(crate) const FEATURE_VM_STATUS: u64 = 1 << 1; -pub(crate) const VM_STATUS_SIZE: usize = 16; - -/// Shared by the VM and accepted jobs; never cleared by queue destruction or -/// successful work. A newly created VM receives a new status object. -pub(crate) struct VmStatus { error: AtomicI32 } -impl VmStatus { - pub(crate) fn new() -> Self { Self { error: AtomicI32::new(0) } } - pub(crate) fn record(&self, error: i32) { - if error < 0 { - let _ = self.error.compare_exchange(0, error, Ordering::AcqRel, Ordering::Acquire); - } - } - pub(crate) fn get(&self) -> i32 { self.error.load(Ordering::Acquire) } -} - -/// GET_PARAMS group 1 is an in/out request: vm_id, flags=0, error(out), pad=0. -/// Decode once, before lookup, so a racing userspace edit cannot change owner. -pub(crate) fn decode_request(bytes: &[u8; VM_STATUS_SIZE]) -> Option { - let word = |i| u32::from_ne_bytes(bytes[i..i+4].try_into().unwrap()); - if word(4) != 0 || word(12) != 0 { return None; } - Some(word(0)) -} -pub(crate) fn encode_response(vm_id: u32, error: i32) -> [u8; VM_STATUS_SIZE] { - let mut bytes = [0; VM_STATUS_SIZE]; - bytes[0..4].copy_from_slice(&vm_id.to_ne_bytes()); - bytes[8..12].copy_from_slice(&error.to_ne_bytes()); - bytes -} diff --git a/drivers/gpu/drm/asahi/m3/hw.rs b/drivers/gpu/drm/asahi/m3/hw.rs index a774f5de6573f5..ae1041d70c3ec7 100644 --- a/drivers/gpu/drm/asahi/m3/hw.rs +++ b/drivers/gpu/drm/asahi/m3/hw.rs @@ -15,7 +15,6 @@ const MAX_POWERZONES: usize = 5; /// J516S runtime ADT perf-states-sram table floors SRAM at 810 mV (7.1.12 `hw::t6030`). const G15_MIN_SRAM_MICROVOLT: u32 = 810_000; -pub(crate) mod agx3; pub(crate) mod t8122; /// GPU revision enumeration. Note: Part of the UABI. diff --git a/drivers/gpu/drm/asahi/m3/hw/agx3.rs b/drivers/gpu/drm/asahi/m3/hw/agx3.rs deleted file mode 100644 index f5e6ad607ec25d..00000000000000 --- a/drivers/gpu/drm/asahi/m3/hw/agx3.rs +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT - - -#[cfg(not(test))] -use crate::m3::identity::{GpuGen, GpuVariant}; -#[cfg(test)] -#[path = "../identity.rs"] -mod identity; -#[cfg(test)] -use identity::{GpuGen, GpuVariant}; - -/// Identification-only configuration for one AGX3 SoC. -#[derive(Debug)] -pub(crate) struct SocConfig { - /// Chip ID in hex format (e.g. 0x6050 for t6050). - pub(crate) chip_id: u32, - /// Decoded design generation for this chip. - pub(crate) gpu_gen: GpuGen, - /// Decoded variant for this chip. - pub(crate) gpu_variant: GpuVariant, - /// Hardware family byte expected at `0xd04000[31:24]`. - pub(crate) hw_family: u8, - /// Hardware variant byte expected at `0xd04000[23:16]`. - pub(crate) hw_variant: u8, - /// Die count expected at `0xd04010[19:16]`. - pub(crate) num_dies: u32, - /// Input-address bits per UAT root (42 on every AGX3 part). - pub(crate) uat_ias: u8, - /// Output address space (42-bit on every AGX3 part). - pub(crate) uat_oas: u32, -} - -const fn agx3( - chip_id: u32, - gpu_gen: GpuGen, - gpu_variant: GpuVariant, - hw_family: u8, - hw_variant: u8, - num_dies: u32, -) -> SocConfig { - SocConfig { - chip_id, - gpu_gen, - gpu_variant, - hw_family, - hw_variant, - num_dies, - uat_ias: 42, - uat_oas: 42, - } -} - -pub(crate) const T8122: SocConfig = agx3(0x8122, GpuGen::G15, GpuVariant::G, 0x7, 2, 1); -/// Apple M3 Pro (G15S). -pub(crate) const T6030: SocConfig = agx3(0x6030, GpuGen::G15, GpuVariant::S, 0x7, 3, 1); -/// Apple M3 Max (G15C). -pub(crate) const T6031: SocConfig = agx3(0x6031, GpuGen::G15, GpuVariant::C, 0x7, 4, 1); -/// Apple M3 Ultra (G15D, two dies). -pub(crate) const T6032: SocConfig = agx3(0x6032, GpuGen::G15, GpuVariant::D, 0x7, 4, 2); diff --git a/drivers/gpu/drm/asahi/m3/hw/t8122.rs b/drivers/gpu/drm/asahi/m3/hw/t8122.rs index 5ba6b0ef6acd6f..555c65834fe1d4 100644 --- a/drivers/gpu/drm/asahi/m3/hw/t8122.rs +++ b/drivers/gpu/drm/asahi/m3/hw/t8122.rs @@ -76,7 +76,7 @@ pub(crate) const HWCONFIG_T8122: super::HwConfig = HwConfig { // The 24 MHz reference clock (HwDataB base_clock_khz = 24000). base_clock_hz: 24_000_000, - // 42-bit UAT roots and output addresses, as on every AGX3 part (hw::agx3::T8122). + // 42-bit UAT roots and output addresses, as on every AGX3 part. uat_ias: 42, uat_oas: 42, num_dies: 1, // ID_COUNTS_1[19:16] diff --git a/drivers/gpu/drm/asahi/m3/m3_coverage.rs b/drivers/gpu/drm/asahi/m3/m3_coverage.rs deleted file mode 100644 index 3ec1fac6834922..00000000000000 --- a/drivers/gpu/drm/asahi/m3/m3_coverage.rs +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Positive page-coverage results for one exclusively host-owned page table. -//! The page-table owner must invalidate before every possible table mutation. -//! This stores permissions only; it never proves physical backing identity. - -#[derive(Clone, Copy)] -struct Entry { start: u64, end: u64, read: bool, write: bool } -pub(crate) struct Cache { entries: [Option; 32], next: usize } -impl Cache { - pub(crate) const fn new() -> Self { Self { entries: [None; 32], next: 0 } } - pub(crate) fn invalidate(&mut self) { self.entries.fill(None); self.next = 0; } - pub(crate) fn covers(&self, start: u64, end: u64, read: bool, write: bool) -> bool { - start < end && self.entries.iter().flatten().any(|e| - e.start <= start && end <= e.end && (!read || e.read) && (!write || e.write)) - } - pub(crate) fn remember(&mut self, start: u64, end: u64, read: bool, write: bool) { - if start >= end { return; } - self.entries[self.next] = Some(Entry { start, end, read, write }); - self.next = (self.next + 1) % self.entries.len(); - } -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn permissions_holes_and_mutations() { - let mut c = Cache::new(); - c.remember(0x4000, 0x8000, true, false); - c.remember(0xc000, 0x10000, true, true); - assert!(c.covers(0x4001, 0x7fff, true, false)); - assert!(!c.covers(0x4000, 0x8000, false, true)); - assert!(!c.covers(0x4000, 0x10000, true, false)); - assert!(!c.covers(0x8000, 0x8000, false, false)); - assert!(!c.covers(u64::MAX, 0, false, false)); - assert!(c.covers(0xc000, 0x10000, true, true)); - // An unmap/remap or permission downgrade must discard all old proof. - c.invalidate(); - assert!(!c.covers(0xc000, 0x10000, false, true)); - c.remember(0xc000, 0x10000, true, false); - assert!(!c.covers(0xc000, 0x10000, false, true)); - for i in 0..100 { c.remember(0x20000+i*0x4000, 0x24000+i*0x4000, true, true); } - assert!(!c.covers(0xc000, 0x10000, true, false)); - } -} diff --git a/drivers/gpu/drm/asahi/m3/m3_soc.rs b/drivers/gpu/drm/asahi/m3/m3_soc.rs index 7500822c4124c5..9cb132b26aa923 100644 --- a/drivers/gpu/drm/asahi/m3/m3_soc.rs +++ b/drivers/gpu/drm/asahi/m3/m3_soc.rs @@ -268,13 +268,13 @@ pub(crate) fn by_chip(chip_id: u32) -> Option<&'static Soc> { /// T8122 (M3, G15G): one die, one cluster of ten core slots (eight or ten of them active). /// -/// The compatibles, the mailbox and its interrupts are the T8122 device tree's. The identity is -/// the one the T8122 identity gate admits (`t8122_admission`: family 7, variant 2, revision 0x20, -/// core slots in the first core-mask word only), with the die count of the AGX3 identification -/// table (`hw::agx3::T8122`). The hardware configuration is `hw::t8122`; power configuration -/// comes from the boot loader. Startup uses the guarded `t8122_start` path, which selects this -/// table's values by default on admitted Air boards and adds a performance-state cap. Explicit -/// `asahi.t8122_start=0` disables startup; firmware, board and resource admission still apply. +/// The compatibles, the mailbox and its interrupts are the T8122 device tree's. The identity is the +/// one the T8122 identity gate admits (`t8122_admission`: family 7, variant 2, revision 0x20, core +/// slots in the first core-mask word only), with one die. The hardware configuration is +/// `hw::t8122`; power configuration comes from the boot loader. Startup uses the guarded +/// `t8122_start` path, which selects this table's values by default on admitted Air boards and adds +/// a performance-state cap. Explicit `asahi.t8122_start=0` disables startup; firmware, board and +/// resource admission still apply. pub(crate) static T8122: Soc = Soc { name: "T8122", gpu_name: "G15G", diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eafd5732bceac8..96398ae42387f1 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -79,8 +79,6 @@ mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_status; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; @@ -141,8 +139,6 @@ mod m3_compute_sequence; mod m3_compute_storage; -mod m3_coverage; - mod m3_init_layout; mod m3_init_storage; From 244e25770857a5c8550dde8f717b2ad67cb22958 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:00:56 +1100 Subject: [PATCH 0125/1514] rust: remove three unused downstream wrappers of::find_node_by_phandle(), RtKit::mailbox_off() and OwnedQueue::new_unbound() were added to our rust/kernel tree but no Rust code calls them. The C apple_rtkit_mailbox_off() stays; dcp and apple-cio-sleep call it. Signed-off-by: Ryan Murray --- rust/kernel/of.rs | 15 --------------- rust/kernel/soc/apple/rtkit.rs | 7 ------- rust/kernel/workqueue.rs | 7 ------- 3 files changed, 29 deletions(-) diff --git a/rust/kernel/of.rs b/rust/kernel/of.rs index cacbc55c28dc5c..04f04496633c75 100644 --- a/rust/kernel/of.rs +++ b/rust/kernel/of.rs @@ -536,21 +536,6 @@ pub fn stdout() -> Option { } } -#[allow(unused_variables)] -/// Looks up a node in the device tree by phandle. -pub fn find_node_by_phandle(handle: PHandle) -> Option { - #[cfg(not(CONFIG_OF))] - { - None - } - #[cfg(CONFIG_OF)] - // SAFETY: bindings::of_find_node_by_phandle always returns a valid pointer or NULL - unsafe { - #[allow(dead_code)] - Node::from_raw(bindings::of_find_node_by_phandle(handle)) - } -} - impl Clone for Node { fn clone(&self) -> Node { // SAFETY: `raw_node` is valid and non-NULL per the type invariant, diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index f6ae2c60da979c..5866ba29d79836 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -380,13 +380,6 @@ impl RtKit { to_result(unsafe { bindings::apple_rtkit_idle(self.rtk) }) } - /// Turns the mailbox off for a coprocessor that has acknowledged idle, before its run bit and - /// power state go. Only [`Self::warm_restart`] follows this. - pub fn mailbox_off(self: Pin<&mut Self>) { - // SAFETY: `rtk` is valid per the type invariant. - unsafe { bindings::apple_rtkit_mailbox_off(self.rtk) }; - } - /// Prepares for HELLO from firmware restarting warm, which keeps its buffers and rings. The /// caller then sets the run bit and calls [`Self::boot`]. pub fn warm_restart(self: Pin<&mut Self>) -> Result { diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 3e4d97583073ab..230c2281c96f7f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -497,13 +497,6 @@ impl OwnedQueue { }) } - /// Allocates an unbound workqueue named `name`, with high-priority workers if `highpri`. - /// - /// Its work items run concurrently, each in the affinity pod of the CPU it is queued for. - pub fn new_unbound(name: &CStr, highpri: bool) -> Result { - Self::flags(name, true, highpri, 0) - } - /// Allocates an unbound workqueue named `name` that may be used on the memory reclaim path /// (`WQ_MEM_RECLAIM`), with high-priority workers if `highpri`. pub fn new_unbound_reclaim(name: &CStr, highpri: bool) -> Result { From 28c5bc35d3d08aab4a44ca713e952f36d65288c2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:03:04 +1100 Subject: [PATCH 0126/1514] selftests: apple-dcp: match the current DP guard in usb-retention-control The negative control looks for the DP-preservation guard in atcphy_usb3_power_off() by its exact text. The guard became a two-line condition (it now skips T8132), so the assert failed before any unit ran. Match the current text. With it, the production unit passes and the mutant that removes the guard is rejected again. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/apple-dcp/usb-retention-control.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py b/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py index ca9fb3f6e39a95..65e6b636468d34 100755 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/usb-retention-control.py @@ -19,7 +19,8 @@ def main(): parts = phy.parking(args.source) production = parts["production"] original = block(production, "static int atcphy_usb3_power_off(") - guard = "if (atcphy_modes[atcphy->mode].enable_dp_aux)\n\t\treturn 0;" + guard = ("if (atcphy_modes[atcphy->mode].enable_dp_aux &&\n" + "\t atcphy->hw->gen != ATCPHY_GENERATION_T8132)\n\t\treturn 0;") assert original.count(guard) == 1 mutant = original.replace(guard, "/* negative control: incorrectly cut a live DP link */") units = { From 12d0c22327a5819ce29eccc8d528110b63518789 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:03:06 +1100 Subject: [PATCH 0127/1514] Remove the top-level GAPS.md audit snapshot GAPS.md is a T6040 GPU parity audit pinned to integration/aurora at 9cbdd0734d9e and a wip branch. It records the state of one review on 2026-10-27; nothing in the tree, Documentation or CI links to it, and it does not belong at the top of a kernel tree. It stays in history (1214a925dbee5). Signed-off-by: Ryan Murray --- GAPS.md | 1302 ------------------------------------------------------- 1 file changed, 1302 deletions(-) delete mode 100644 GAPS.md diff --git a/GAPS.md b/GAPS.md deleted file mode 100644 index c8d2c7c753261c..00000000000000 --- a/GAPS.md +++ /dev/null @@ -1,1302 +0,0 @@ -# T6040 GPU parity audit - -Audit baseline: `integration/aurora` at -`9cbdd0734d9e`, with GPU integration #463 (`a0a9485847f8`), the -r5 display series (`905dff774561`), camera #462 (`2114ed0c6245`), and the -two r6 display patches. The reconstructed r6 branch is -`wip/j616s-display-r6` at `af0a664046fb`. - -This series repairs regression coverage and a shared KUNIT=m WERROR build defect, -ports GPU-driven memory/fabric demand and PMP voter cooperation using -T6040 data, honors the existing DT idle-delay policy, and closes a compute -release-witness gap across recovery. GPU voltages, firmware features and the submission algorithm remain -unchanged from the reconstructed base. The major -T6040 calibration and image-admission changes requested by this audit are -already in the baseline. Software parity does not establish all-workload benchmark or CTS -parity. The operator has selected g3 as the measured J616s baseline; g4 -retains it and adds the qualified shared ports and diagnostics below. - -## Gap table - -| Gap | Neo behavior | T6040 before this series | After this series | Evidence / remaining gate | -| --- | --- | --- | --- | --- | -| Per-chip leakage and power ceiling | T8140 has its own platform data | #463 requires a versioned DT handoff, finite positive leakage, a power ceiling and the measured core mask; no single-unit fallback | Same runtime behavior | `g17/calibration.rs`, `g17/initdata/v25g83.rs`; #463 commits `a8fb1380b414`, `53877eaebd4b`, `415fd2e6ee2d` | -| Raw OPP count versus logical states | Firmware consumes 11 logical states | 16 raw GPU OPPs; 11 selectors in each A/B map; both end at raw OPP 15; unused handoff slots must be zero | KUnit now uses valid complete maps and checks the final state's second voltage lane | `g17/calibration.rs`; a count of 15 in an ADT property is not evidence for expanding this firmware layout | -| Full clock eligibility | Platform OPPs feed firmware performance tables | DT supplies both cluster voltages and GPU/CS/AFR frequencies; maps and relative-B are checked against the GPU OPP table | Same runtime behavior | `g17/initdata/v25g83.rs`, `g17/fw/initdata/v25g83.rs`; confirm sustained clocks and limiting reasons on hardware | -| DVFS ramp / effort | Full effort on publication, cleared after 16 ms of continuous idle | Same `Firmware::note_submission`, direct-port accounting and race-checked idle clear | Same runtime behavior | `g17/mod.rs`, `g17/port.rs`, `g17/power.rs`; opaque firmware power words are not a documented ramp control | -| GPU-driven fabric/memory floor | #440 uses an activity-following graphics PMGR input | T6040 CPU-only demand; g3 port sampled the firmware-lifetime GFX supplier | g4 uses DT-selected publication/continuous-idle demand, preserving DCS 5/fabric 2 and 32 ms CLPC hold | `clpc.c`, `g17/power.rs`, `g17/port.rs`, T6040 DT; blank-panel release and bandwidth retention require hardware qualification | -| PMP PMC vote cooperation | PMP/CLPC/AP agents enabled | T6040 static voters omit PMP 0 from pre-working-PMP bring-up | Port 772a9d3104ff adds the existing PMP supplier dependency and voter 0 on T6040 DCS/SOC rails | pmc.c and T6040 DT; live votes, idle release and thermal qualification required | -| Idle / off policy | Shared host hold and firmware device-control path | Same host implementation; source documents a 25G83 effective 2 ms off delay and approximately 1 ms wake cost | J616s requests a bounded 16 ms host hold through existing `apple,idle-off-delay-ms`; absent policy retains 2 ms | `g17/power.rs`, `g17/mod.rs`, J616s DT and binding; compare short/long gaps, depth-one latency and idle power | -| Fast-die / PMP | Platform-specific firmware power graph | 25G83 AON table and separate power-state target/release (101/96 C) are already populated; DT enables the GFX suppliers | Same runtime behavior | `g17/fw/initdata/v25g83.rs::POWER_STATE_WORDS`, `g17/initdata/v25g83.rs`, J616s DT; verify clocks with PMP running | -| Periodic preemption | Context-switch timer mask is zero | Same zero mask; two-cluster operand-state allocation differs by hardware layout | Same runtime behavior | `g17/fw/initdata.rs::CONTEXT_SWITCH_TIMER_MASK`, `g17/fw/compute.rs::OperandState`; no evidence supports changing the mask | -| High-priority queues | HIGH / MEDIUM / LOW firmware scheduling profiles | Same scheduling-policy selector and priority work rings | Same runtime behavior | `g17/mod.rs::scheduling_policy`, `g17/fw/channels.rs`, `g17/qos.rs` | -| Timestamp publication | Retains one CPU mapping for each firmware timestamp buffer | Same shared timestamp buffer and completion publication | Host timestamp suite again compiles and executes the production retained-mapping writer | `timestamp.rs`, `mmu.rs::TimestampVmap`, `tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py` | -| Statistics | Drains firmware statistics; no decoded `agx_stats` snapshot | Same; payloads discarded | g4 preserves full per-type/per-role raw snapshots and static-key report tracing | `g17/reports.rs`, `g17/channel.rs`, `g17/trace.*`; achieved-frequency/power decoding remains gated on firmware semantics | -| Firmware startup / registration | Two instances, message acknowledgement, POWER_ON_DONE and MMIO render-pair registration; no lead commands | One merged 25G83 graph, status acknowledgement, no POWER_ON_DONE, no MMIO pair registration; lead commands required | Same runtime behavior | `g17/fw/variant.rs`, `g17/initdata/v25g83.rs`; startup differences are ABI requirements, while MMIO pair registration on 25G83 remains unqualified | -| Queue pointer / restart layout | Producer at +0x40, recovery target at +0x50 | Producer at +0x50, no recovery-target word | Same runtime behavior | `g17/fw/variant.rs::PointerLayout`, `g17/fw/queue.rs`; do not copy another firmware build's offsets | -| Core topology / mapping ownership | One six-core cluster; two firmware roots and fabric bridge | Qualified two-cluster, 20-core layout; reserved firmware tables, one root and no fabric bridge | Same runtime behavior | `hw/t6040.rs`, `hw/t8140.rs`, `g17/mod.rs`; other fused core counts are still refused, and this audit does not expand that admission | -| Alternate loaded image | T8140 uses fixed firmware selection | Both exact T6040 normalized TEXT digests are admitted in one `Build.images` slice | Same runtime behavior | #453 (`26f5eb68dbce`), #463 (`804bba86ca55`), `hw/t6040.rs`, `g17/fw/variant.rs`, `fwid.rs`; unknown images remain refused | -| Submission/completion improvements | #423 shared G17 runtime | #423 is already an ancestor of the baseline; direct compute/render publication, admission domains and completion collection are shared | Same runtime behavior | #423; `g17/runtime.rs`, `g17/runtime/render/direct.rs`, `g17/port.rs`, `g17/completion.rs` | -| G13/G14 `submit.empty` regressions | Neo uses the G17 runtime | G16S uses that same G17 runtime, not the maintained G13/G14 workqueue | Same runtime behavior | `driver.rs`, `file.rs`, `g17/queue/mod.rs`; user-space empty submits may never reach this ioctl; trace and benchmark the paired Mesa stack | -| G13/G14 idle wake regressions | Firmware-specific cost plus shared host overhead | G16S shares common ioctl/GEM/sync infrastructure, but has different firmware, power handling and queue backend | Same runtime behavior | `driver.rs`, `g17/power.rs`; G13/G14 benchmark ratios cannot be transferred to G16S | -| QID capacity | Firmware floor 0; reserve protects dedicated render pairs | 25G83 reserves QIDs 0..31; public queue limit is reduced accordingly | KUnit checks floor 32 in dynamic growth and full logical queue budget tests; host resource runner follows current reserve helper | `g17/kick.rs`, `g17/runtime.rs`, `tools/asahi/g17-resource-tests.py` | -| KUnit / WERROR config matrix | Shared test modules require KUNIT=y | Four G17 test helpers used the broader CONFIG_KUNIT guard and failed WERROR with the shipping KUNIT=m config | Helpers now use CONFIG_KUNIT = "y", matching the Rust macro; config and warning policy unchanged | `rust/macros/kunit.rs`, `g17/kick.rs`, `g17/preparation.rs`, `g17/queue/admission.rs`, `g17/runtime.rs`; verify both KUNIT=m release and KUNIT=y QEMU builds | -| Compute ownership / retained mappings | Recovery and retirement witnesses protect mapping lifetime | Same production queue ownership, source loans, growth rollback and deferred release | Aged-record fallback now requires the original recovery generation; source loans and host negative controls remain | `tools/asahi/g17-capacity-fault-tests.py`, constructor/growth/pool/release-order fixtures | -| Restart and fault classification | Shared recovery handshake plus validated T8140 per-slot keys | Shared handshake uses 25G83 status offsets; `recovery_slot_keys=None` preserves firmware blame when keys are unknown | Bounded generation/slot/progress diagnostics retain unknown ownership; any missing selected key preserves firmware blame | `hw/t6040.rs`, `g17/initdata.rs`, `g17/recovery/attribution.rs`; successful 25G83 fault/restart qualification is still required | -| DART / UAT | Shared mapping ownership and checked page-table borrowing | Shared MMU, with T6040 reserved tables, PoC cleaning, per-page TLBI and native GPU permission quirks | Same runtime behavior | `hw/t6040.rs`, `mmu.rs`, `pgtable.rs`; do not remove coherency or handoff requirements for a benchmark | -| Memory accounting | Creator-attributed committed/resident GEM accounting and capacity admission | Same `memacct::Client`, `File::memory_stats` and shared capacity machinery | Same runtime behavior | `file.rs`, `gem.rs`, `memacct.rs`, `g17/capacity.rs`; verify multi-client high-water and post-close behavior on hardware | -| MCache / few-primitives / ray traversal | Enabled by the 26A428 variant | Disabled by 25G83 variant; source records hangs for few-primitives and stalled ray traversal, while MCache is unqualified | Same runtime behavior | `g17/fw/variant.rs::V25G83`; enabling these requires independent ABI evidence and hardware tests | -| M5 Pro comparison | No M5 Pro hardware configuration exists in this public baseline | No T605x/G17S KMD path to compare | No claim of M5 parity | Pinned public tree contains T6040 and T8140; a licensed public M5 Pro reference is required | -| CTS and Linux/macOS performance ratio | Hardware results belong to their exact kernel/Mesa pair | No result for this candidate | Pending hardware agent | Run gpubench with matching suite, configuration and conditions; review CTS failures and kernel faults before claiming parity | - -## GPU memory demand and interactive latency - -The GFX PMP report entry and PMC performance votes are separate mechanisms. -The existing T6040 `pmp_gfx` soc-device 13 entry follows the powered GPU domain; -`apple_pmp_report_set_state()` publishes a power-state request bit and waits -for its acknowledgement. It does not encode a DCS/fabric performance request. -The GPU firmware owns the PMP's performance demand. Before this series, PMC's -static voter list omitted PMP agent 0, and CLPC lacked a GPU power-state input. -The two existing ports enable PMP agent 0 on T6040's DCS/SOC rails and make -CLPC request the already qualified DCS 5 / fabric 2 floor. G3 incorrectly -used the T6040 supplier lifetime as activity. G4 replaces that input with -DT-selected publication/continuous-idle demand and preserves the existing -32 ms memory-floor release. Prove live -request, enabled-agent and actual-state agreement; supplier binding alone -is not proof of an honoured vote. - -For dispatch latency, G17 now reads the existing `apple,idle-off-delay-ms` DT -policy, validates the existing 2..1000 ms bounds, and starts the existing host -hold with that policy. J616s selects 16 ms, matching the existing effort-idle -interval; other boards without the property retain the native 2 ms behavior. -This avoids power-off across short interactive gaps and releases after real -idle, without changing firmware layout or adding a parameter/platform flag. -KUnit covers absent/valid/invalid policy and repeated depth-one gaps followed -by idle release. A shorter software delay is not itself a measured latency -win: compare actual power transitions, firmware execution, IRQ/retirement and -fence wakeup boundaries. Keep empty CPU fence transfers separate from GPU -round trips and require low-duty/long-idle power acceptance. - -## Remaining 25G83 facts and recovery qualification - -No firmware capability is inferred from another GPU's successful CTS result. -The following are the exact T6040/25G83 facts needed to open the remaining -paths. A reference capture of achieved frequency establishes a target, not -an offset, voltage, descriptor ABI, or Linux residency measurement. - -| Gated path | Exact facts needed for T6040/25G83 | Current evidence and disposition | -| --- | --- | --- | -| Sustained top clock | DT OPP count, both voltage lanes, hardware A/B selector maps, selected logical-state limit; independently decoded achieved frequency or residency, counter units/timebase/wrap, request versus achieved-state semantics and limiting reason under sustained load | Per-chip DT handoff and maps are already mandatory; both maps select the final raw OPP. `max_frequency_khz` is an advertised maximum, not achieved telemetry. G17 `stats_snapshot()` returns None; g4 raw `firmware_reports` and `asahi_g17_report` preserve payloads but establish no decoded residency. Keep voltages/maps unchanged and require a measured Linux load trace. | -| Raw versus logical state count | Meaning of the ADT count properties for this firmware, both SGX map banks and number of entries actually consumed by the 25G83 power tables | Public `HwData25G83`, calibration validation and loader handoff select eleven logical states from sixteen raw OPPs. Do not resize the firmware structure from the ADT property name or discard its unsorted OPPs. Compare actual top selection and achieved clock. | -| DVFS ramp / idle / fast-die | 25G83 meaning and units of ramp/effort controls, idle/off delays, temperature limits and hysteresis; PMP/AP/CLPC request ownership, achieved floors and release under idle and load | Existing shared submission/idle policy, DT suppliers and T6040 power-state graph are enabled. Power-state presence is not proof of load tracking. Require live requests, actual floor release and thermal traces; opaque power words are not tunable parameters. | -| Recovery slot attribution | Exact 25G83 slot-key storage range, lifetime, cache policy and slot stride; key QID/stamp bit fields; slot-mask meanings, progress monitor semantics and association with an actual started render | `recovery_slot_keys=None`; never copy T8140's physical address. Preserve firmware blame. Progress-view reads no longer depend on knowing the key address; bounded diagnostics report unknown ownership explicitly. | -| Recovery table / reason | 25G83 recovery-info offset/extent, valid/guilty/cancelled bits, stamp sequence encoding; reason-code semantics; ordering and reset of records relative to states 1/2/3/0; interrupted-command drain and visibility guarantees | Existing checked 256-entry table and handshake remain unchanged. Reason 3 is treated as page fault by existing attribution. New generation/slot diagnostics aid qualification; missing key evidence cannot clear blame. An aged compute record may no longer substitute for a stamp across recovery. | -| Compute completion / visibility | Exact compute record identity and timestamp fields, stamp write/cache-maintenance order, ring consumption during restart, late/missing-stamp behavior and a release witness for interrupted work | Same-generation 50 ms fallback retained. Crossing recovery now requires a covering stamp for ordinary retirement; quarantine, kill/drain and processor-stop ownership remain. A completion record plus elapsed time after restart is not independent visibility evidence. | -| MMIO pair registration | 25G83 MMIO port addresses and access-power witness; pair registration write order, ACK and coexistence with lead commands/bootstrap QID reservation | Keep disabled. The 26A428 sequence, POWER_ON_DONE message and recovery-target pointer are distinct ABI facts. | -| MCache | 25G83 table-entry format, sizes/alignment, descriptor pointers and enable bits, ownership/coherency rules, partial-render/restart behavior | Keep disabled until a licensed public implementation or independently supplied facts establish the whole contract and tests validate it. | -| Few-primitives | T6040 enable-bit semantics, required auxiliary buffer sizes/registers and partial-store/load/resume handling for all tiling/fragment paths | Keep disabled; previously observed hangs are not grounds to enable it for performance. | -| Ray traversal / preemption | T6040 register program, scratch sizing/alignment by enabled cores/clusters, saved operand-state layout, resume/checkpoint semantics, kill/restart contract, scheduler timer mask and priority profiles | Existing two-by-ten operand layout and priorities retained; periodic timer mask remains zero on both variants. Native traversal remains disabled pending bounded execution/fault/recovery qualification. | -| TLB range operations | T6040 opcode/operand encoding, VA/ASID granules, ordering, completion and negative-translation invalidation across every mapping alias | Existing page TLBI and PoC table cleaning retained. Copying Neo range encoding cannot close a performance gap safely. | -| Large vertex/barrier and tess/geometry faults | Faulting engine/access/VA/VM, exact bound intervals/backings and mapping lifetime; render/compute descriptor identity, TVB/GTP capacities, pass-start/stamp state and recovery reason before acknowledgment | Isolate exact public CTS names with one process and compare kernels with the same Mesa. Buffer size alone does not establish VM-bind, timeout or TVB causality. Retention fix is independently justified, not a claim to have cured a CTS fault. | - -The compute stamp-wait KUnit suite now checks that an aged exact record and -consumed items cannot retire a pre-recovery kick without its stamp, while an -exact/later stamp, busy-ring control and same-generation fallback retain their -expected behavior. Recovery-source tests cover unknown keys, incomplete reads -and page-fault fallback. Diagnostic counters explicitly identify lifetime -stampless totals; they are not a count of commands retired by one restart. - - -## g5 large-target capacity correction - -Public CTS `vulkan-cts-1.4.6.2` uses a 10240-square framebuffer for -`rasterization.primitive_size.points.point_size_10000`. The existing 25G83 -GTP layout appends a sub-buffer of 64 times the tile map after the TPC. -Applying the inherited 32 MiB cache bound to this combined allocation rejects -that valid target with ERANGE, despite its cache and tile record each fitting -their original limits. This is reproducible in the production layout code -without GPU execution. The normalized hardware summary contains ERANGE and -reason-2 recoveries but cannot establish their order or one-to-one association. - -G5 applies the original TPC_MAX to the aligned cache, preserving the original -tile-record bound before allocation or growth. The tile-map bound also caps -the derived auxiliary extent. It changes no firmware buffer-sizing formula, -numeric limit, VA window, generation/retention rule or allocation accounting. -Neo has no auxiliary tail and keeps the same policy. KUnit covers both utile -shapes at the CTS target size, oversized cache/layered-record rejection and -Neo capacity. Fresh and growing targets use the same preflight. Large targets -need their full required metadata through the existing memory/VA mechanisms; -allocation failure still propagates. Hardware execution/readback and post-close -memory/capacity baselines are mandatory acceptance gates. - -The separate 1 MiB vertex/barrier case uses a 256-square target, not a large -framebuffer. Its point count is actual vertex-buffer bytes divided by stride. -It cannot be explained by the large-target capacity guard. Preserve its first -operation/exception, generated sequence and the halted-state TVB/growth/pass -snapshots before choosing a coherence, VM-bind or firmware-timeout fix. The -point-target correction is not a claim that firmware reason 2 is decoded. - -## g5 recovery evidence and host-hop timing - -The shared recovery service previously captured slot keys and monitors at -halted state 1, then called `render_pass_started()` during classification -after acknowledging state 3 to 0. A resumed render could change that pass -state. G5 computes attribution from the state-1 pass snapshot and carries -only that result through the handshake. KUnit drives the real service and -rejects any pass read after the first acknowledgement. Unknown 25G83 keys -still retain firmware blame. This is an independently demonstrated ordering -fix; it does not establish the cause of either deterministic reason-2 fault. - -G5 adds the existing declared TVB state (inventory, page capacity, producer, -consumer, high-water and reset) to the halted snapshot without resetting any -counter. The blamed pair's first four commands include render geometry and -the computed GTP layout, alongside the existing pass/cursor/stamp records. -Pending/active growth and its reply remain visible. The next isolated run -can distinguish exhausted inventory or delayed growth from a pass that never -started; no buffer enlargement or firmware timeout change is justified yet. - -Static-key `asahi_g17_inputs` records compute input conversion entry/result, -source count and publication waits. `asahi_g17_schedule` records enqueue, -inline/fallback, preparation and run boundaries. Together with the existing -publish/complete, DMA-fence and scheduler tracepoints these split host cost -per hop into input resolution, scheduler setup/wait/dispatch and firmware -execution. They make no timing claim until a matched trace is captured. - -The available macOS reference uses 26A428 on T6040 and reports a software -request P10 while hardware residency is 1578 MHz at raw state 14. Linux runs -the admitted 25G83 image. Thus neither a literal P10 conversion nor copying -another firmware's statistics layout proves achieved MHz. The reference -contains aggregate frequency/residency and public DT/calibration facts, -not a Linux 25G83 tag/field decoder. The inspected licensed public G17 source -at `jgoyvaerts/linux` `cc32473a09dd` also has no decoded statistics adapter. -Required input remains a fresh Linux raw report series under labeled idle, -ALU and fill load, and independently established field/timebase/achieved-state -semantics for that exact firmware. No captured raw payload has been promoted -to public implementation data. Achieved clock/power and the CTS cure remain -open; g3's measured memory/latency policy is preserved. - -## g4 shared runtime ports and observability - -The operator has selected g3 as the hardware baseline. This follow-on retains -its CLPC/PMP ports, DT idle hold and recovery-generation release guard. -Individual hardware records remain in the private qualification workspace; -no raw lab capture is a public implementation source. - -| Gap | Public source behavior | T6040 g4 disposition | Qualification | -| --- | --- | --- | --- | -| #504 fragment notification | `de0b22a8370e` selects a render pair on its fragment notification; final retirement still requires both stored stamps | Included for both firmware graphs; KUnit covers each mask bank and unrelated queues | Render-light latency/IRQ rate, growth/partial renders, recovery and CTS | -| #504 tiling first-kick | `5073eac15192` changes the word only for the 26A428 register program | Included unchanged; 25G83 retains 1 on every kick | No T6040 notification-halving claim; requires 25G83 descriptor/notification facts and controlled qualification | -| #496 compute-fault witness | `9a76756bf2d7` uses event 7 words 3/4 as QID/stamp on Neo, with consumed-ring guard | Imported prerequisite, but the existing firmware graph keeps 25G83 event 7 unknown | Exact 25G83 layout, queue identity, stamp semantics and DMA/ring visibility must be established before it can release memory | -| #505 closed-context teardown | `078d744a260c` kills before freeing executed unstamped render graphs, retains firmware-linked work storage, and reuses killed pairs last with QID capacity | Shared safety/retention paths included; compute-fault-driven kill depends on the graph-qualified #496 witness | Closed mixed compute/render faults, acknowledgement ordering, memory pressure and slot/QID reuse; does not claim to cure a live render's first fault | -| #499 long-job sharing | `3db24da5c830` recognizes another published, unobserved long compute job as sharing, without changing numeric renewal bounds | Included in the shared host path; T6040 bounded AS-build classification can use it, while native traversal remains gated | KUnit verifies renewals stop at the existing bound; no claim that this cures a firmware reason-2 render fault or makes skipped traversal CTS pass | -| First fault | Reason and blame alone cannot identify engine progress | At halted state 1, before acknowledgement, g4 logs the blamed pair's stored stamps, free-list balance and up to four commands' pass/cursor snapshots; borrowed pairs are explicitly unavailable | Correlate exact CTS operation and original error with raw event report and snapshots; do not label reason 2 as page fault without semantics | -| Raw firmware statistics | Complete 18-word statistics records already have checked ring geometry | Read-only `firmware_reports` exposes last full sample, count and host monotonic time for each role/type. Static-key `asahi_g17_report` copies trace/statistics/event words before slot return | Match payloads to independently decoded achieved-clock/power/residency and freshness/units; legacy statistics tags are a different ABI | -| Idle memory floor | Neo graphics PMGR follows activity; T6040 GFX is held for firmware lifetime | g4 replaces T6040 PMGR demand with a DT-linked CLPC request, asserted at publication and released by the existing race-checked 16 ms continuous-idle clear; 32 ms CLPC hold remains | Read-only last vote/reason/time, host request and last submission, safe core power/host hold; require blank-panel quiet release and load/release cycles | - -Remaining exact facts for telemetry are the 25G83/26A428 tag-to-layout map, -field width/signedness/endianness, sample/timebase/wrap and freshness, -power units/averaging interval, logical/raw/cluster pstate selection, requested -versus achieved-state semantics, and limiting/thermal reason meanings. Raw -samples and the DT maximum are not MHz. Reads issue no firmware request and -never touch gated core registers. `agx_stats` remains unsupported for decoded -G17 data until those semantics are established. - -For the two deterministic CTS cases, retain the first failing operation before -cleanup, full unnormalized recovery logs, raw event trace, and pre-ack render -snapshots. The large-buffer and extreme-point-size cases can stress tiling, -but neither case name proves a TLB, timeout or TVB cause. No timeout, voltage, -feature-enable or buffer-size guess is included in g4. Multi-queue sync needs -its publish/GPU-span/event/fence timeline; #504's compute control does not -promise to halve that path's latency. - -### T6040 idle-floor release correction - -The PMGR DT explicitly documents that GFX cannot power down while firmware -runs. This is a source-established difference from the Neo CLPC input, so -using GFX as T6040 work demand can never establish idle release. G4 removes -that input on T6040 and adds `apple,clpc` from the GPU consumer to the existing -host performance controller. This is a provider relationship, not a feature -flag or user knob. A requested but unavailable provider defers GPU probe. - -Publication asserts the independent, refcounted request through a leaf lock; -o sleeping callback or allocation runs at submission. Both mutex-backed and -off-lock direct paths are covered. The existing effort clear checks in-flight -work and 16 ms continuous idle, withdraws its flag, then rechecks the direct -submission counter. A racing publisher reasserts demand. The CLPC vote keeps -its existing 32 ms hold; CPU arbitration and Neo's PMGR input are unchanged. -Firmware stop and request destruction clear demand. Provider removal cannot -free storage retained by a late consumer, and a device link orders dependencies. - -CLPC status now shows the last requested floor, reason bits and monotonic -time, plus the host request's activity/update sequence. Actual PMC readback -and write errors remain distinct. Read-only `asahi-g17/power` reports the -existing always-accessible core power witness, host hold, effort and last -publication time, without waking firmware. Generic runtime PM may remain -unsupported because autonomous core gating is firmware-managed; no fictitious -runtime-suspend implementation is enabled. Raw stats still do not decode MHz. - -The production CLPC host suite tests an always-powered supplier with absent, -busy and ended GPU demand, 32 ms hold, CPU coexistence, reason/time and legacy -Neo behavior; removing demand or idle release fails its negative controls. -C KUnit checks actual request lifetime and a late consumer after provider -removal. Hardware acceptance requires a locked/blank panel with publications -observably quiet, release after the hold, then three load/idle cycles and -retention of g3's benchmark gains. An active compositor alone proves neither -quiescence nor a latch. Keep failed measurements and rollback candidates. - -## Source and validation boundaries - -The implementation references are the licensed public Aurora/Asahi kernel and -loader history. Existing Gravity Linux-derived layouts and attribution remain -unchanged. The public Gravity Linux `gravity-m4` reference inspected at -`4fc326f6c25ccceb7515e2635c22e01fde5d3bac` was checked in `g16.rs`, -`g16_runtime.rs` and `g16_power.rs`. Those files do not supply validated -T6040 recovery slot keys; that G16 runtime explicitly leaves compute -non-preemptible. No private implementation, firmware bytes, voltage table or -lab record is included here. - -The build handoff must identify the exact tested source and loader, verify boot -payload checksums, retain r6g rollback, and distinguish CPU/QEMU tests from GPU -execution. Missing J616s measurements are not passing results. - -## Neo KMD improvements on T6040 - -This ledger audits refinements and handling, not just feature parity. It uses -`integration/aurora` at `9cbdd0734d9e186c5f5f5949a21b909d10c2571b` and -`aurora-wip` at `927a4a4480cf90ce8e3b4ab1d1ce58d84bf32fd4`. The conservative -history window starts 2026-09-26 (Neo platform prerequisites), before the public -T8140 firmware interface of 2026-10-03 and hardware bring-up of 2026-10-06. -Committer dates retain rebased older-author changes. The inventory also includes -the complete 105-commit public #171 history, all 65 commits of #423, and the -related PR versions used to identify original contributions and later ports. - -The path log covers `drivers/gpu/drm/asahi`, Apple PMP/PMGR/PMC/CLPC/MCC, -RTKit/mailbox, CPU-frequency/thermal and DART code, related AIC and DRM -scheduler/fence support, Rust DRM interfaces, and Neo DT dependencies. Broad -path/PR neighbors and imported baseline changes are explicitly marked N/A; -they are not represented as measured Neo optimizations. Old/rebased hashes are -listed as encountered aliases of the same subject/class, not asserted to be -byte-identical. The coverage inventory lists 1,551 physical commits (including -imported neighbors and PR-original versions), with 851 distinct subjects; all -65 #423 commits have separate rows. **Active** describes the surviving mechanism on T6040, including -its 7.3 port/refinement, rather than claiming that every historical SHA is an -ancestor. Multi-purpose firmware-introduction records retain their shared -parts while explicitly identifying dormant MCache/native-feature portions. A commit link is its exact diff; the evidence key states the current -reachability/gate. No per-commit speedup is invented from a stack measurement. - -### Applicable ports found by the commit audit - -| Neo mechanism | T6040 in g1 | g2 port and per-chip data | Required acceptance | -| --- | --- | --- | --- | -| #440 GPU-driven CLPC memory/fabric floor | CPU demand only; `gpu_demand=false`, no GPU power-state phandle | `0d63308820ab`: existing GPU-demand mechanism and DT phandle, T6040 DCS 5/fabric 2 and existing 32 ms release; CPU sustain=3 retained | C/R/H/I/P; actual PMGR tracking, floor release, video/browsing and sustained-load power | -| #219 PMP voter cooperation | Static voters 1/3 omit PMP 0 from pre-working-PMP bring-up | `772a9d3104ff`: existing `apple,pmp` supplier dependency, voters 0/1/3, existing T6040 DCS/SOC rail mask; no display rail or voltage change | P/B; PMP bound/ready, live request/honoured floors, idle and thermal behavior | - -Other audited gated paths are listed explicitly below. The T8140 lazy CPU -verification cost is absent on T6040's already-fast-switch profile. MMIO pair -registration, range-only TLB encoding, native RT/few-primitives and optional DCS -cooling cannot be enabled by copying a different firmware/hardware protocol. -The recovery slot-key attribution gate still needs validated 25G83 identity -facts; shared recovery, deadlines and retirement handling remain enabled. - -### Reported measurements and their scope - -These are public PR results, not new J616s measurements. Private qualification -reports were checked for scope and regressions; raw lab records are not copied -here. The older GPU profiling report's cost estimates are not measurements. - -| Evidence | Relevant commits/mechanism | Reported Neo result | J616s confirmation | -| --- | --- | --- | --- | -| [#171](https://github.com/aurora-silicon/linux/pull/171) | Retention, off-lock cleanup, reclaim quiet window and shared lifetime stack | Cold first-submit median 224 to 194–198 us, p99 338 to 295–305 us; menu-launch stalls below 100 ms versus 260–280 ms before quiet-window work. Stack results, not isolated gains. | B/M/C/R, repeated fresh contexts and foreground launch under bounded pressure | -| [#171](https://github.com/aurora-silicon/linux/pull/171) | Completion/recovery isolation | Earlier mixed render/compute lost its device within 2 s; later fixture ran over 568k verified checks in 60 s. Historical 1 ms stamp fallback was subsequently refined to 50 ms. | F/H/T; exact data and fences, peer liveness and no premature mapping release | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | Cumulative scopes and submission stack | Same-boot submit API elapsed roughly 14 to 10 us; throughput stayed near 20 us. Combined candidate C-d64 19.44 us, R-d32 41.48 us, hop 42.12 us; workload/Mesa dependent. | C/R/H; preserve wall-time versus thread-CPU distinction | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `9bf3039873a1`, completion identity index | Scanner self samples 4.87% to 2.24% at depth 64, 3.16% to 1.93% on hops. CPU profile result. | O/C/H | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `26446182da3a`, 128-interval validation working set | C-d64 API elapsed 10.06 to 7.46 us; R-d32 12.29 to 8.16 us. Not a thread-CPU clock measurement. | C/R/D with rotating 64 buffers and remap/permission invalidation | -| [#423](https://github.com/aurora-silicon/linux/pull/423) | `b6248acf900c`, private-fence fast status | Submit API median 7.52 to 5.79 us; frontier samples 1.83% to 0.25%; throughput remained near 19.5 us. | C/H/O; errors, foreign inputs and delayed host publication | -| [#440](https://github.com/aurora-silicon/linux/pull/440) | `d69f14f4e4fb`, GPU fabric floor | C-d1 158.9 to 108.2 us; C-d64 19.3 to 14.7 us; R-d32 42.7 to 29.7 us; hop 42.2 to 31.9 us. Same driver/Mesa. | P/C/R/H, compare g1/g2 and keep heavy/idle checks | -| [#219](https://github.com/aurora-silicon/linux/pull/219) | GFX report/PMP vote and PMC enables | Short manual-bit glmark2 build experiment: 1453 with GFX report off to 2199 with it on; 2218 with all interface enables. Single-run 7–10 s experiment, not an isolated final-kernel A/B. | P/R; distinguish reported request, enabled agent and honoured floor | -| [#443](https://github.com/aurora-silicon/linux/pull/443) | Lazy verification and fast switch | C-d2 58.8–59.7 to 46.4–47.3 us; C-d1 107.8–108.4 to 102.6–102.7 us. T8140-specific spin removed. | C/I observation only: T6040 already lacks that spin | -| [#413](https://github.com/aurora-silicon/linux/pull/413) | Existing optional idle hold | The roughly 1.1 ms wake and 1.2–1.4 ms tiny-render-after-gap observations are **M4 Pro**, not Neo measurements. Default 2 ms adds no extended hold. | I at defaults; optional hold is a separate policy experiment | - -The provided current Neo Linux/macOS report has no completed paired Linux -record, so an overall Neo margin is still undefined. Historical PR ratios do -not establish the requested current all-workload margin. Use matched suite, -Mesa, clock/power conditions and repeats. Run only workloads admitted by the -controller; queue depth is not permission for extra process workers. - -### Reachability and gate evidence keys - -| Key | Current source/gate and interpretation | -| --- | --- | -| SHARED — Shared G17 execution | driver.rs selects g17::Gpu for T6040. g17/queue/mod.rs, runtime.rs, port.rs, runtime/render/direct.rs and runtime/render/submit.rs have no T8140-only gate on these mechanisms. The variant supplies QID floor 32, producer +0x50, two-cluster operands and 25G83 lead commands. | -| DRM — Shared DRM/scheduler/fences | G17 queues use job.rs, fence.rs and the common DRM scheduler/syncobj/GPUVM/shmem interfaces. CPU_FREQ and UCLAMP_TASK are enabled in the release config. Private cumulative scopes are advertised on both G17-backend targets at feature bit 29; foreign fences retain generic handling. | -| MEM — Common memory and lifetime | file.rs::memory_stats, gem.rs, memacct.rs, cleanup.rs, pgtable.rs and mmu.rs serve the T6040 G17 backend. Creator accounting, pins, revocable backing, canonical bindings and deferred destruction are not gated to T8140. T6040 keeps its explicit UAT coherency policy. | -| GMEM — Shared retained GPU resources | g17/freelist.rs, context.rs, object.rs, queue/compute.rs and runtime/render/pools.rs retain and reclaim the same resource owners. Allocations use T6040 core-layout sizes and its reduced QID budget; no Neo-only admission branch disables them. | -| REC — Shared recovery and deadlines | g17/recovery.rs, recovery/safety.rs, timeout.rs and runtime/events.rs serve both firmware variants. T6040 uses its status-B base and one firmware role. Exact retirement, interrupted-work failure, withheld-doorbell replay, progress-aware budgets and sticky VM reporting remain active. Current missing-stamp fallback is 50 ms, not the historical 1 ms. | -| POWER — Shared feed/effort/idle code | g17/feed.rs is instantiated for T6040 and derives CPU floors from each discovered policy maximum. g17/mod.rs::note_submission/idle_check and power.rs share effort 1.0 while work streams and a 16 ms idle clear. The existing optional idle hold is available on T6040 but its default 2 ms adds no extended hold. | -| TIMESTAMP — Shared timestamp publication | timestamp.rs::FirmwareBuffer retains a CPU vmap for the buffer lifetime; g17 completion publishes through it before signalling. T6040 uses this shared firmware-buffer path and its 24 MHz timestamp conversion, not a per-command vmap. | -| PRIORITY — Shared firmware priority profiles | g17/mod.rs::scheduling_policy selects HIGH/MEDIUM/LOW profiles for both targets; file.rs checks CAP_SYS_NICE or DRM master for HIGH and refuses REALTIME. Priority work-ring selection and QoS ownership are shared. | -| FW — Per-chip firmware adaptation | hw/t6040.rs selects V25G83. g17/initdata/v25g83.rs supplies one merged root and status acknowledgement, per-chip OPP/calibration input, separate views and no POWER_ON_DONE. Pointer and operand layouts are selected from Config/Variant rather than copied from the two-instance 26A428 graph. MCache is explicitly gated by V25G83.mcache=false; its firmware table/protocol is not part of admitted T6040 support. | -| PMGR — Shared PMGR state handling | pmdomain/apple/pmgr-pwrstate.c binds T6041 states through the t8103-compatible state protocol. BUSY masking, timeout unwind and firmware-owned/no-auto-PM properties apply through DT; no T8140-only register address is copied. | -| PMP — PMP/report per-chip data | soc/apple/pmp.rs and pmdomain/apple/pmp-report.c already contain T6041 match data: 42-bit DMA, version-5 bootargs checks, CoreAnalytics EP7, T6041 report offsets and three fast-die lanes. T6040 DT supplies the bootargs/report entries and CPU effort phandles. T8132/J713-only telemetry policy is excluded separately. | -| PMC — Shared PMC, T6040 rail mask | pmdomain/apple/pmc.c::apple_pmc_probe/agent_enable use T6040 agent stride, DCS maximum 5 and agent_rails=GENMASK(1,0). CPU/CLPC/AP voting already worked. Port 772a9d3104ff adds apple,pmp and static voter 0 after its supplier binds; display rails remain excluded. | -| CLPC — Shared CLPC, T6040 demand data | soc/apple/clpc.c uses T6040 DCS {1,2,5,5}, fabric {0,1,2,2}, sustain=3, 4 ms sampling and 32 ms hold. CPU demand/lifecycle refinements are shared. GPU demand was missing and is enabled by 0d63308820ab with the existing apple,gpu-power-state phandle. | -| GPUFLOOR — Applicable gate ported | Before g2, apple_clpc_hw_t6040.gpu_demand was false and its CLPC DT node had no apple,gpu-power-state. Port 0d63308820ab enables the same mechanism as #440 with T6040 DCS 5/fabric 2, not Neo 4/3. Hardware gain and idle/PMP cooperation remain unqualified. | -| MCC — MCC translated to 16 planes | soc/apple/mcc.c accepts the T6041/T8140-compatible controller; T6040 DT describes 16 planes and its display boot-DMA dependency. The J616s enables this node. Generic partial-enable unwind, lifetime and SLC allocation rules apply with that data. | -| CPU — Shared CPU frequency/limit handling | T6041 CPU nodes bind the t8112 fallback profile. Generic OPP cleanup, fast-switch and PMP effort QoS use its DT frequencies and three effort lanes. No Neo frequency or thermal curve is copied. | -| LAZY — Different CPU verification protocol | The lazy_verify refinements are T8140-only. T6040 binds soc_t8112_info, whose verify_transition is false; policy->fast_switch_possible is already true. It does not pay the T8140 blocking verification loop that these commits remove. Adding lazy verification would not port a missing gain. | -| DART — Related DARTs; native GPU uses UAT | iommu/apple-dart.c common publication/error/resume/stream logic is used by T6041 DARTs where their DT ownership mode selects it. T6040 display mirroring uses its own compatible/data. Native GFX translations use asahi/mmu.rs UAT, so this is related PMP/display robustness, not a claim that Neo DART addresses fit the G16 GPU. | -| RTKIT — Shared RTKit transport/lifetime | G17 Coprocessor uses the Rust RTKit wrapper over soc/apple/rtkit.c. Shared buffer retention, barriers, crash handling, bounded logs and shutdown ownership apply. T6040 supplies its firmware-data crash buffers and one ASC instance; MTP/J713-only adoption is excluded. | -| MBOX — ASCWrap transport, per-chip registers | soc/apple/mailbox.c and rust/kernel/soc/apple/mailbox.rs provide the common queue, IRQ and receiver ownership rules. T6040 binds its ASCWrap-v6 data; its wrapper/VBAR windows and IRQs come from DT. Neo-specific mailbox addresses are not reused. | -| AIC — Shared effective-affinity reporting | irq-apple-aic.c applies AICv2+ reporting to the T6041 AIC3 compatible too. It reports actual effective routing rather than manufacturing CPU migration. Record the IRQ/worker CPU on J616s; no isolated throughput gain is claimed. | -| DISPLAY — Related shared display hardening | Generic apple/dcp.c, parser and AFK lifecycle/bounds fixes are inherited by the reconstructed display stack where those helpers are used. They protect the display consumer of GPU buffers; they are not standalone compute performance claims. | -| OBS — Observability only when selected | Existing G17 tracepoints/diagnostics and first-failure logging are shared. Trace register sampling is conditional on the tracepoint being enabled; disabled tracing is not a new runtime policy or a measured throughput gain. | -| MMIO — Different registration ABI | runtime/render.rs::install_pair returns before registration power holds when V25G83.mmio_pair_registration=false. 25G83 installs from queue configuration and uses lead commands; 26A428 uses MMIO pair registration. Do not add its two control round trips or register writes to the admitted 25G83 protocol. | -| FEW — 25G83 rejects this fast path | V25G83.few_primitives=false; command.rs and feature reporting enforce it. The supported-source comment records a fragment hang with the flag. It is not an applicable refinement of the admitted 25G83 render ABI without new validated facts. | -| RT — RT specialization not admitted | V25G83.ray_traversal=false; command.rs rejects native scratch/intersection programs and get_params omits the feature. Generic watchdog/recovery infrastructure remains shared, but native RT pools/kill guards/RT-specific long-job use are dormant on the admitted 25G83 path. | -| KEY — Missing validated recovery identities | hw/t6040.rs has recovery_slot_keys=None. recovery/attribution.rs falls back to firmware blame when slot identity evidence is incomplete. Neo slot-key addresses must not be invented for 25G83; this specific attribution refinement remains gated pending validated T6040 facts. | -| UAT — Qualified alternate invalidation policy | hw/t6040.rs keeps reserved_tables, clean_tables and page_tlbi=true. mem.rs::tlbi_range takes the page/ASID alternative before its range encoder. The range-only field fix is dormant; per-SoC coherency/ownership support is active. Removing these working firmware-table requirements is not a justified performance port. | -| DCS — Optional cooling actor, no T6040 curve | PMC cooling/IPA paths require #cooling-cells and power-model DT data. J616s does not select them, and the Neo DCS thermal zone was subsequently removed because it throttled unrelated GPU/CPU heat. No T6040 power curve is invented to re-enable that policy. | -| DCSOFF — Already equivalent inactive zone | Neo removed its oscillating DCS thermal zone. J616s has no such zone to remove. Its PMP CPU/GPU limits remain; this does not justify disabling thermal protection. | -| IRQENTRY — DT-selected report context | IRQ-safe report entries are selected by apple,irq-safe for PMGR-parent use. GFX report consumption does not require copying the external-display parent topology; use the actual T6040 entry/consumer hierarchy. | -| STAT — Not the Neo backend | StatsChannel/GpuManager agx_stats decoding belongs to the maintained backend. g17::Gpu::stats_snapshot returns None on both Neo and T6040. It is not a Neo optimization waiting to be ported to G16S. | -| G15 — Different backend/hardware | T6030/T6031/T8122/G15 and M3-only runtime commits do not execute in T6040 g17::Gpu. Their firmware records, generation-specific power policy and native-G15 admission cannot be copied into G16S/25G83. | -| G16 — Different G16 backend/owner ABI | T8132/J713 uses the separate g16 backend and retained-owner PMP/TVM protocol. T6040 is G16S but dispatches to the g17 backend with V25G83, not that G16G runtime. Match/board gates and firmware ownership differ. | -| LEGACY — Maintained G13/G14 path | The workqueue/manager/versioned AGX firmware path is not T6040's G17 backend. G13/G14 automatic preemption, timestamp-copy and old InitData changes are not missing G16S mechanisms. | -| OTHERCHIP — Other CPU/guest hardware | T8142/T8152/T6050-specific transition, ownership or guest-timer data is not selected by T6041 CPU/GPU match data. No unsupported register/profile change is ported. | -| TUNNEL — Other peripheral topology | M1 tunneled PCIe/Thunderbolt recovery is not a Neo native-GPU improvement. T6040 has its own topology; these records are retained for coverage, not presented as a gated G16S optimization. | -| PERIPH — Not a GPU refinement | This scoped-history/PR neighbor concerns NVMe, HID, audio, SEP, USB, RTC or another peripheral, not a Neo native-GPU performance/handling mechanism. No port is implied. | -| BOARD — Neo-specific board route | The literal J700 topology/display source/domain-cell fix is not T6040 board data. Its independent J616s display/PMP/GPU composition is retained; copying a Neo route or physical address would be wrong. | -| RAWDIAG — Superseded raw diagnostics | The raw T8140 PMP DVFS debugfs dump was later removed. Current reporting uses validated per-SoC fields; no new raw interface or platform knob is added. | -| OLDTHERMAL — Superseded thermal policy | The interim J700 SMC CPU policy was removed/replaced by thermal-framework and PMP handling. It is not the policy selected for T6040 and no Neo temperature/power curve is copied. | -| SUPERSEDED — Superseded inside the series | The unconditional-doorbell/unbound-inline policies were refined by later #423 commits; the early disabled-J616s admission was replaced by calibrated #463 enablement. Current code preserves low-pressure probes and defers/coalesces eligible doorbells with explicit release/stall/recovery handling; do not reapply the obsolete intermediate policy. | -| VERIFY — Build/test/documentation only | This record changes tests, descriptions, bindings, layout/build checks or source style rather than a runtime performance mechanism. Its contract is retained where applicable; there is no isolated hardware speedup or new platform behavior to port. | -| MERGE — Integration record | This merge is provenance/composition, not an isolated performance mechanism. Its parent changes are enumerated below, including variant preservation and subsequent fixes; no separate speedup is assigned to a merge. | - -### Hardware measurements referenced by each commit - -All hardware actions require the controller's explicit J616s identity, policy -approval and ownership/session/resource gates. These are a measurement plan, -not permission to bypass them. Pair g1/g2 with the same loader and Mesa and -preserve failed runs, logs and r6g rollback. - -| Code | Measurement | -| --- | --- | -| C | compute.light d1/d2/d64; submit API wall and thread-CPU time, scheduler hops, faults and CPU-frequency/IRQ context; matching Mesa/suite. | -| R | render.light d1/d2/d32 and 8 queues, first render, heavy fill and tiler growth; API p50/p99, throughput and memory high-water. | -| H | same/cross-queue binary and timeline hops; p50/p95/p99, doorbells per command and 100k order/data checks; include eligible and fallback dependencies. | -| I | idle.wake after 2/20/100 ms, default policy, first-frame latency and clocks; 60/120 Hz frame pacing and idle power. Keep optional hold experiments separate. | -| F | controller-approved bounded stall/fault/long-job stress with innocent peers; no wrong data or false successful fence, recovery phase/time, VM errors and post-close reuse. | -| M | multi-client create/close/rearm and approved bounded pressure; committed/resident bytes, retained pools/QIDs, restoration time and leak slope. | -| P | PMP readiness, PMC per-agent requests/honoured floors and CLPC readbacks during GPU-only, mixed CPU/GPU, 90 s heavy load, idle, video and browsing; verify idle release and no sustained thermal regression. | -| T | timestamp/query correctness, 24 MHz conversion, aligned/unaligned publication where supported, buffer-map reuse and query CPU cost. | -| Q | privileged/unprivileged priority admission and concurrent LOW/MEDIUM/HIGH progress, global-priority transition cases and timeout attribution. | -| D | approved bounded VM_BIND/unmap/remap and DART ownership/resume boundaries; CPU cost, invalidation errors and zero unexpected DART/UAT faults. | -| B | exact boot/kernel/loader/Mesa pins, firmware admission, first queue/install, panel/display regression, supplier readiness and rollback. | -| O | existing tracepoints/counters under approved instrumentation; IRQ and event-worker CPU, pass duration, notifications and failure site. Tracing off remains the reference. | -| V | static/build/contract or capability-refusal check; no isolated hardware improvement claimed. | - -### Every commit in #423 - -All 65 entries are retained, including intermediate policies, tests and the -integration merge. Superseded steps are not mistaken for current behavior. - -| Commit | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [ad691cd5e9f7](https://github.com/aurora-silicon/linux/commit/ad691cd5e9f76aa9e486d93b560c58d5c8ff88c4) | DjDeveloperr | drm/asahi: publish bound G17 compute work without the admission passes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,H | -| [1121ae36b8d4](https://github.com/aurora-silicon/linux/commit/1121ae36b8d426be24c41ae360281b5f0709a69d) | DjDeveloperr | drm/asahi: wake G17 render publication when its pair is returned [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | R,H | -| [abd85935bd4d](https://github.com/aurora-silicon/linux/commit/abd85935bd4db7db6be23b8194b1173c9a8988c5) | DjDeveloperr | drm/asahi: clear each G17 compute descriptor only once [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/compute.rs` | C,H | -| [3ef3720890f8](https://github.com/aurora-silicon/linux/commit/3ef3720890f8c085f18e4f5e35db6853075b121c) | DjDeveloperr | drm/asahi: retain compute pool backing through pending channel admission [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — GMEM; `drivers/gpu/drm/asahi/g17/capacity.rs` | M,C,R | -| [f35d7ea1b373](https://github.com/aurora-silicon/linux/commit/f35d7ea1b37395a9bc1241d0fafcb698e0c12d46) | DjDeveloperr | dma-buf: stop polling an array after its first pending member [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — DRM; `drivers/dma-buf/dma-fence-array.c` | C,H,M,F | -| [319805fed41b](https://github.com/aurora-silicon/linux/commit/319805fed41bb181db8e90378beaf905f38f6297) | DjDeveloperr | drm/asahi: avoid unbound compute inline attempts on compute-only queues [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — SUPERSEDED; `drivers/gpu/drm/asahi/g17/context.rs` | C,H | -| [5a4822c6fb3d](https://github.com/aurora-silicon/linux/commit/5a4822c6fb3d1fc0a83d9b754b477bf1db35d782) | DjDeveloperr | drm/asahi: preserve low-pressure compute inline probes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,H | -| [026065c43526](https://github.com/aurora-silicon/linux/commit/026065c435260844e39d05a182e99b128c5f9b2d) | DjDeveloperr | drm/asahi: submit same-VM compute input waits through firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/capacity.rs` | C,H | -| [89c8873651b7](https://github.com/aurora-silicon/linux/commit/89c8873651b729fdd4e981e87b9d0df0d0ad0017) | DjDeveloperr | drm/asahi: treat a firmware source as complete once its retirement is queued [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [3ff4f4baa05a](https://github.com/aurora-silicon/linux/commit/3ff4f4baa05a88d5f99d2fee76089cf72b5617a4) | DjDeveloperr | drm/asahi: publish G17 commands from the ioctl at any queue depth [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [a0dfc3c0b5a4](https://github.com/aurora-silicon/linux/commit/a0dfc3c0b5a4fced66119fded07ed141990a9025) | DjDeveloperr | drm/asahi: map G17 compute descriptors cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [a36e352d8564](https://github.com/aurora-silicon/linux/commit/a36e352d8564947071fef7e11dba709f399cd106) | DjDeveloperr | drm/asahi: size the G17 compute QID budget by open logical queues [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/kick.rs` | C,H | -| [b141ca9b16c3](https://github.com/aurora-silicon/linux/commit/b141ca9b16c33abb26238782cd7c0b751b5f52fe) | DjDeveloperr | drm/asahi: order same-VM render attachment overlaps in firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | R,H | -| [a475f4f9f1f7](https://github.com/aurora-silicon/linux/commit/a475f4f9f1f721b6636a4147dacbcf9f6224763b) | DjDeveloperr | drm/asahi: map G17 compute command records cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [ca71e4449b4a](https://github.com/aurora-silicon/linux/commit/ca71e4449b4a23d5f4e0149db76cf5198bfa7e5f) | DjDeveloperr | drm/asahi: stop the G17 compute completion scan once every record is found [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [1cdac9ba0ddd](https://github.com/aurora-silicon/linux/commit/1cdac9ba0dddec96f59eb02a5067ee343aae43f4) | DjDeveloperr | drm/asahi: publish G17 compute into a bound queue without the device mutex [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/context.rs` | C,H | -| [7242bf87efd2](https://github.com/aurora-silicon/linux/commit/7242bf87efd2b3f4f8bf2a31fadb79b3e687f195) | DjDeveloperr | drm/asahi: send a G17 compute queue configuration only when it changes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [014605a36795](https://github.com/aurora-silicon/linux/commit/014605a3679581351913c3ab137653297f7a0cf7) | DjDeveloperr | drm/asahi: add G17 resource wait domains and use them for queue creation [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/availability.rs` | C,R,H | -| [64f717dcfd1e](https://github.com/aurora-silicon/linux/commit/64f717dcfd1e4aa5856882181f5c2ac040c5ce4e) | DjDeveloperr | drm/asahi: wait for G17 compute capacity on the release that frees it [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/availability.rs` | C,H | -| [327e50fc45b5](https://github.com/aurora-silicon/linux/commit/327e50fc45b57acf1954e8c2d78977198286feb0) | DjDeveloperr | drm/asahi: wait for a G17 compute source only through its completion record [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,H | -| [6f4d3bbb47c1](https://github.com/aurora-silicon/linux/commit/6f4d3bbb47c1a7b19abef118b41b131440a8f414) | DjDeveloperr | drm/asahi: add G17 command lifecycle tracepoints [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/mod.rs` | O,F | -| [e24e3bad9e7d](https://github.com/aurora-silicon/linux/commit/e24e3bad9e7d3c6cf7079d683c9364d619cd3a55) | DjDeveloperr | drm/asahi: ring the G17 compute pipe doorbell for every publication [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — SUPERSEDED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [94c66ecf24e6](https://github.com/aurora-silicon/linux/commit/94c66ecf24e6d931a434914d6a513ee36ff6ffd7) | DjDeveloperr | drm/asahi: map the G17 compute queue graph cached for the firmware [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [db365ecc299f](https://github.com/aurora-silicon/linux/commit/db365ecc299f0663db8a629e70dfdb4d117eb95e) | DjDeveloperr | drm/asahi: wait for G17 render capacity on the release that frees it [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/context.rs` | R,H | -| [06bc290c266a](https://github.com/aurora-silicon/linux/commit/06bc290c266abcb8b0d45f75c3369e231ae8c4a7) | DjDeveloperr | drm/asahi: give the G17 render scheduler the pair's depth as credits [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | R,H | -| [3d1f2047766c](https://github.com/aurora-silicon/linux/commit/3d1f2047766c2d6e8d165a4af2cfe4adc0edd366) | DjDeveloperr | drm/asahi: keep a G17 render free list registered while the firmware is busy [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | R,H | -| [b7fa0d482eea](https://github.com/aurora-silicon/linux/commit/b7fa0d482eea670f9004422eaf57703a7ec8d4e5) | DjDeveloperr | drm/asahi: take the G17 device mutex less often to publish a render [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | R,H | -| [d272a7060d20](https://github.com/aurora-silicon/linux/commit/d272a7060d20a0beb635ca8426c8822b8e823a43) | DjDeveloperr | drm/asahi: publish a G17 render into its pair without the device mutex [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | R,H | -| [6428f7fd42fe](https://github.com/aurora-silicon/linux/commit/6428f7fd42fe075981984da569b0fa076f59a127) | DjDeveloperr | drm/asahi: lend a G17 render pair without the identity check first [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | R,H | -| [8cf02f589bce](https://github.com/aurora-silicon/linux/commit/8cf02f589bce34b13002cbdf0f3b0361c4a8e66b) | DjDeveloperr | drm/asahi: wait for G17 render admission before run_job [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | R,H | -| [550fb355e9a3](https://github.com/aurora-silicon/linux/commit/550fb355e9a30c0db9c59fe35a931f1db9c6b5c4) | DjDeveloperr | drm/asahi: trace the G17 core power state at each work doorbell [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/mod.rs` | O,F | -| [f381ac9b71eb](https://github.com/aurora-silicon/linux/commit/f381ac9b71ebcb70eb72497ec4115553856a31fc) | DjDeveloperr | drm/asahi: trace G17 host-to-firmware messages [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — OBS; `drivers/gpu/drm/asahi/g17/channel.rs` | O,F | -| [adcd56e02036](https://github.com/aurora-silicon/linux/commit/adcd56e020362664c7bc3af288e1ad812df7b4c7) | DjDeveloperr | drm/asahi: maintain cumulative completion scopes without repeated fence merges [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — DRM; `drivers/gpu/drm/asahi/g17/fence.rs` | C,H,M,F | -| [bcdfdafd80cf](https://github.com/aurora-silicon/linux/commit/bcdfdafd80cf93fadc79df688dd0109b9c4ae8d2) | DjDeveloperr | drm/asahi: test G17 queue budgets with firmware-reserved identities [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/kick.rs` | V | -| [971d4316d91c](https://github.com/aurora-silicon/linux/commit/971d4316d91cce97b92db72c4f29e5155b76d626) | DjDeveloperr | drm/asahi: size cached compute records for every native wait [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [9bf3039873a1](https://github.com/aurora-silicon/linux/commit/9bf3039873a1e241991b5999aceff5610c660ade) | DjDeveloperr | drm/asahi: index pending compute completion identities before reading payloads [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs` | C,H | -| [26446182da3a](https://github.com/aurora-silicon/linux/commit/26446182da3aa8d98ce799478a025117b021eaba) | DjDeveloperr | drm/asahi: retain a deep working set of validated GPU page ranges [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/validation.rs` | C,R,D | -| [b6248acf900c](https://github.com/aurora-silicon/linux/commit/b6248acf900c1cf30deac52791c2c50d10055d7b) | DjDeveloperr | drm/asahi: avoid locking pending private completion fences [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | C,R,H | -| [b08c81722d89](https://github.com/aurora-silicon/linux/commit/b08c81722d896eee8da9771e99e38e6986a2a806) | DjDeveloperr | drm/asahi: give G17 firmware restarts time to drain long work [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/recovery.rs` | F,Q | -| [f1db16a83586](https://github.com/aurora-silicon/linux/commit/f1db16a83586e4bec596a71e12e0d8b87dd3b16c) | DjDeveloperr | drm/asahi: fail commands a GPU restart interrupted instead of completing them [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [30f85560fd28](https://github.com/aurora-silicon/linux/commit/30f85560fd28ce05151c16eab7a58433d125a81e) | DjDeveloperr | drm/asahi: stop the G17 device on a watchdog storm only without progress [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [2c0abe2d090a](https://github.com/aurora-silicon/linux/commit/2c0abe2d090a9701b13b22d5ac56fb24d87cfe12) | DjDeveloperr | drm/asahi: scan only the G17 compute completion records written since the last pass [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [39bdd5b8e2d5](https://github.com/aurora-silicon/linux/commit/39bdd5b8e2d584fff0d342a71a8945e64c8a9673) | DjDeveloperr | drm/asahi: release pruned G17 frontier entries after the ioctl publishes [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [b41ecb56c077](https://github.com/aurora-silicon/linux/commit/b41ecb56c0775a43b747adaa37661b353651dbff) | DjDeveloperr | drm/asahi: publish both G17 render QoS owners in one pass [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | R,H | -| [b86c445ba282](https://github.com/aurora-silicon/linux/commit/b86c445ba2829f644075ca663217abe65844e8c0) | DjDeveloperr | drm/asahi: stop copying G17 fragment registers to the unused client page [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | C,R,H | -| [5a55068193e2](https://github.com/aurora-silicon/linux/commit/5a55068193e213d7115a63f2222ffc304a4ced98) | DjDeveloperr | drm/asahi: read the G17 render work rings once per direct publication [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | R,H | -| [b67018ed5974](https://github.com/aurora-silicon/linux/commit/b67018ed5974069c13c13249834dbc3b84e806ed) | DjDeveloperr | drm/asahi: request the G17 tiling descriptor slot before preparing a render [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [4d0362d0c18d](https://github.com/aurora-silicon/linux/commit/4d0362d0c18d288d3bd520fdfb69c2e7624cf6b0) | DjDeveloperr | drm/asahi: store G17 register arrays without an intermediate copy [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/kick.rs` | C,R,H | -| [861b39d948f6](https://github.com/aurora-silicon/linux/commit/861b39d948f6c0588b3646e1246e660b52230e5b) | DjDeveloperr | drm/asahi: also request the G17 queue configuration records early [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | C,R,H | -| [66ef051d8bd4](https://github.com/aurora-silicon/linux/commit/66ef051d8bd4e66bdc145eb7fb7a920235a8e668) | DjDeveloperr | drm/asahi: scan only render pool slots for G17 free-list leases [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — GMEM; `drivers/gpu/drm/asahi/g17/runtime/render/pools.rs` | M,C,R | -| [1aec5be232da](https://github.com/aurora-silicon/linux/commit/1aec5be232da7bacbbe38b7f9b22c27906eac8c6) | DjDeveloperr | drm/asahi: omit G17 render queue configurations that only reload the held completion [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [d0df244b8f02](https://github.com/aurora-silicon/linux/commit/d0df244b8f023037bb0f9cc9793f1d0f285cfc87) | DjDeveloperr | drm/asahi: keep one CPU mapping per G17 timestamp buffer [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [3ff8c49c5f12](https://github.com/aurora-silicon/linux/commit/3ff8c49c5f12b908a72e6c076ff0d7336ffddcb8) | DjDeveloperr | drm/asahi: withhold G17 compute doorbells behind two unretired commands [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [b1f5dc6df0ba](https://github.com/aurora-silicon/linux/commit/b1f5dc6df0ba5650c8424027a025db233c6544c4) | DjDeveloperr | drm/asahi: drop G17 compute doorbells that another doorbell announced [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/port.rs` | C,H | -| [d38cce2d8be5](https://github.com/aurora-silicon/linux/commit/d38cce2d8be54bdbc01e90e1a92ef3dd65ac0640) | DjDeveloperr | drm/asahi: announce withheld G17 compute doorbells whenever retirement stalls [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [2d8286101c86](https://github.com/aurora-silicon/linux/commit/2d8286101c8631939cb13ce1b7b14c9041856ca6) | DjDeveloperr | drm/asahi: build the G17 driver without warnings [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | V | -| [9a0ed807e4d3](https://github.com/aurora-silicon/linux/commit/9a0ed807e4d3691a5ea46fce2a2424295f8af6ea) | DjDeveloperr | drm/asahi: renew G17 job deadlines while the GPU keeps retiring work [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [afbfbc0b89ca](https://github.com/aurora-silicon/linux/commit/afbfbc0b89ca4779b13cefff5bed0b4036751b2c) | DjDeveloperr | drm/asahi: kill closed G17 contexts only while no other work runs [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs` | F,Q | -| [31279abf0648](https://github.com/aurora-silicon/linux/commit/31279abf0648c00e454b181f01d65b277a32fb90) | DjDeveloperr | drm/asahi: fail G17 render groups a recovery dropped out of order at once [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [7012a59ed129](https://github.com/aurora-silicon/linux/commit/7012a59ed129baf969d83a3aa4d90f2a6cb410f2) | DjDeveloperr | drm/asahi: announce withheld G17 compute doorbells after a recovery [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — REC; `drivers/gpu/drm/asahi/g17/recovery.rs` | F,Q | -| [8e257af33a6c](https://github.com/aurora-silicon/linux/commit/8e257af33a6c4036ee56bc8a628e733dba2bd525) | DjDeveloperr | drm/asahi: move the G17 cumulative-signals feature to bit 29 [#423](https://github.com/aurora-silicon/linux/pull/423) | Active — SHARED; `drivers/gpu/drm/asahi/g17/sync_output.rs` | C,R,H | -| [76d4e880149e](https://github.com/aurora-silicon/linux/commit/76d4e880149e5592396001f728f7803efb616377) | DjDeveloperr | drm/asahi: build the G17 compute QID budget test against the variant constructor [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/runtime.rs` | V | -| [d0da7e79dc9c](https://github.com/aurora-silicon/linux/commit/d0da7e79dc9c99020d109e95d18256cd5b3d6bc2) | DjDeveloperr | drm/asahi: check the G17 QID floor test against the open-queue compute budget [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/runtime.rs` | V | -| [18b408b7368b](https://github.com/aurora-silicon/linux/commit/18b408b7368b9470c22d92c9afe1991d0fe608ba) | DjDeveloperr | drm/asahi: check the G17 admission churn test against its deadline, not the clock [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/preparation.rs` | V | -| [de1be1b4b5b1](https://github.com/aurora-silicon/linux/commit/de1be1b4b5b110ae60877f77aa1637a920333579) | DjDeveloperr | Merge integration/aurora into fix/g17-recovery-dropped-groups-20261025 [#423](https://github.com/aurora-silicon/linux/pull/423) | Not applicable — MERGE | V | - -### Other Neo and shared-support commits - -Each listed alias has the stated current mechanism/gate. Device-specific data -uses the T6040 counterpart, not literal Neo register/DT values. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [6a5d96e61fa5](https://github.com/aurora-silicon/linux/commit/6a5d96e61fa52810e709a0b8bb5e9988df78a7d7) | Sasha Finkelstein | cpufreq: apple-soc: Calculate frequency as a 64-bit value | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [a861779b92c2](https://github.com/aurora-silicon/linux/commit/a861779b92c259c0a5ba7ec3fd512ad7bda1b8d4) | Asahi Lina | rust: soc: apple: rtkit: Add Apple RTKit abstraction | Active — RTKIT; `drivers/soc/apple/Kconfig` | B,F | -| [4b42187aef53](https://github.com/aurora-silicon/linux/commit/4b42187aef53c266b472e731e4f8e0a1fe0de3a7) | Janne Grunau | rust: soc: apple: rtkit: Add ASC CPU control register | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [6a2c57b5a719](https://github.com/aurora-silicon/linux/commit/6a2c57b5a719f7c71fe6252865e4f036f6d27a64) | Sasha Finkelstein | soc: apple: rtkit: Add apple_rtkit_has_endpoint() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [b7fbb2fde4ea](https://github.com/aurora-silicon/linux/commit/b7fbb2fde4eaa0ac53e46dcb76a835fdc9cd9477) | Sasha Finkelstein | rust: soc: apple: rtkit: Add apple_rtkit_has_endpoint | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [bba00880a59b](https://github.com/aurora-silicon/linux/commit/bba00880a59b144155716928066b12cc5751dd52) | Sasha Finkelstein | rust: soc: apple: Add Apple mailbox abstractions | Active — MBOX; `drivers/soc/apple/Kconfig` | B,O | -| [883657fe64b3](https://github.com/aurora-silicon/linux/commit/883657fe64b3a62fa36c90666b0a00a4e5093166) | Sasha Finkelstein | soc: apple: Add support for the PMP co-processor | Active — PMP; `drivers/soc/apple/Kconfig` | P,B | -| [fccd1dbe8ba8](https://github.com/aurora-silicon/linux/commit/fccd1dbe8ba820d4d9f5d1a624987e2820035204), [04841b120bbf](https://github.com/aurora-silicon/linux/commit/04841b120bbf7a2fb454cbfa984647e867b64848), [da7aa98b1aae](https://github.com/aurora-silicon/linux/commit/da7aa98b1aae834db5f7f4a8396afc39099d1b2f) | Janne Grunau | fixup! soc: apple: Add support for the PMP co-processor | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [c81971a6c4c7](https://github.com/aurora-silicon/linux/commit/c81971a6c4c706b2f5783653a2df8d79782d4efe) | Asahi Lina | drm/scheduler: Fix UAF in drm_sched_fence_get_timeline_name | Active — DRM; `drivers/gpu/drm/scheduler/sched_entity.c` | C,H,M,F | -| [94bfb56baeeb](https://github.com/aurora-silicon/linux/commit/94bfb56baeeb02bc9c9ce8616aef0bd72a5de3f2) | Asahi Lina | rust: drm: sched: Add GPU scheduler abstraction | Active — DRM; `rust/kernel/drm/mod.rs` | B,M | -| [1340031e447c](https://github.com/aurora-silicon/linux/commit/1340031e447c56ec9d0f8ea7a68436a623fafc91) | Asahi Lina | drm/asahi: Add the Asahi driver for Apple AGX GPUs | Active — MEM; `drivers/gpu/drm/Kconfig` | M,D | -| [af74e2af96bc](https://github.com/aurora-silicon/linux/commit/af74e2af96bc483417f5015f98f4aa54e355851d) | Janne Grunau | drm/asahi: v6.19 probe change | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [8c048a0ab849](https://github.com/aurora-silicon/linux/commit/8c048a0ab84971117a5f641ba2185b51e0b12059) | Janne Grunau | drm/asahi: Move unsafe data initialization to driver code | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [a95f0620d24c](https://github.com/aurora-silicon/linux/commit/a95f0620d24c456c74d11261e329df054bf70e7b) | Janne Grunau | drm/asahi: RiiR page tables | Active — MEM; `drivers/gpu/drm/asahi/alloc.rs` | M,D | -| [19e9dc7ccb94](https://github.com/aurora-silicon/linux/commit/19e9dc7ccb9499ac3c92e7764edc2312656dc9d5) | Janne Grunau | drm/asahi: Implement ASAHI_BIND_SINGLE_PAGE (mmu/pgtbl) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [96ce16e432a2](https://github.com/aurora-silicon/linux/commit/96ce16e432a213f7ae185870826697900c9acc60) | Asahi Lina | drm/asahi: pgtable: Add dumper | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [ad2fb060c5dc](https://github.com/aurora-silicon/linux/commit/ad2fb060c5dcce503bc099062ff54c237b6866d0) | Asahi Lina | drm/asahi: pgtable: Add helpers for decoding PTE perms | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [7b55670c3a59](https://github.com/aurora-silicon/linux/commit/7b55670c3a59219e37192a1f5771a86217008808) | Janne Grunau | drm/asahi: Copy tyr's mmu/vm/range.rs | Active — MEM; `drivers/gpu/drm/asahi/asahi.rs` | M,D | -| [9d16f582e208](https://github.com/aurora-silicon/linux/commit/9d16f582e2085935f893f99326fbcc0346c998bb) | Janne Grunau | drm/asahi: Switch gpuvm to DRM_GPUVM_IMMEDIATE_MODE | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [829551e64f1a](https://github.com/aurora-silicon/linux/commit/829551e64f1a350adddb71751be16a0243e1b666) | Janne Grunau | drm/asahi: MemFlag change in v6.19 | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [f5b02e71cd67](https://github.com/aurora-silicon/linux/commit/f5b02e71cd671ac4e3ceff54bbd1b25e7f20ae9d) | Janne Grunau | drm/asahi: rtkit pin adaptation | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [4220285e8415](https://github.com/aurora-silicon/linux/commit/4220285e8415cc772736b57f0dface3dcdbbee4f) | Janne Grunau | drm/asahi: select APPLE_PMP_REPORT | Active — PMP; `drivers/gpu/drm/asahi/Kconfig` | P,B | -| [30d957799282](https://github.com/aurora-silicon/linux/commit/30d9577992828e8d2f8345cc4b34a19098ca068c) | Janne Grunau | drm/asahi: Improve VM bind performance for large BOs | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [22e9a0b69598](https://github.com/aurora-silicon/linux/commit/22e9a0b69598bc23e66d72d1e51bd40396966dc1) | Janne Grunau | drm/asahi: `use` formatting annd rename changes | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [f014fcba9d71](https://github.com/aurora-silicon/linux/commit/f014fcba9d71972198f28c3d5315605669073bea) | Janne Grunau | drm/asahi: v7.1 Mmio relaxed changes | Active — MEM; `drivers/gpu/drm/asahi/regs.rs` | M,D | -| [20dec7b1eaa9](https://github.com/aurora-silicon/linux/commit/20dec7b1eaa9a31dc67a8216d338bb10a452659d) | DesktopECHO | drm/asahi: Clean up deferred BOs when dropping a VM | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M | -| [e07ff81ee812](https://github.com/aurora-silicon/linux/commit/e07ff81ee812fd84603a498beaa1bb25eb629caa) | Janne Grunau | fixup! rust: soc: apple: rtkit: Add Apple RTKit abstraction | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [44a01c258b11](https://github.com/aurora-silicon/linux/commit/44a01c258b111368f3c75848553ae1a658f46013) | Janne Grunau | drm/asahi: Adjustment for v7.2 + partial drm-rust v7.3 | Active — MEM; `drivers/gpu/drm/asahi/alloc.rs` | M,D | -| [23b564dd6c09](https://github.com/aurora-silicon/linux/commit/23b564dd6c09982106e2b5cc5ce80c25010c354a) | Janne Grunau | drm/asahi: pgtable: Drop more dev coredump related code | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [b7f0faf4da36](https://github.com/aurora-silicon/linux/commit/b7f0faf4da367be4a29146f5eb82b795dc2f270d), [afffea42ac29](https://github.com/aurora-silicon/linux/commit/afffea42ac29a1f6f8b3ef3819691c1d7b0a259a) | Hojun Cho | pmdomain: apple: Add missing spin_lock_init | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [0de0a3740a9a](https://github.com/aurora-silicon/linux/commit/0de0a3740a9a26973e7e49ad1cd87981914c457a), [919b934ff719](https://github.com/aurora-silicon/linux/commit/919b934ff7191fa72fab73ecf4ac785dd570c3c3), [ae512e4edf8b](https://github.com/aurora-silicon/linux/commit/ae512e4edf8b96d5eacd79b11fb190837d311b1b) | Ryan Murray | arm64: dts: apple: t8140-pmgr: Add ANS, SPMI, PMP and SMC I2C domains | Active — PMP | P,B | -| [2740578bc68c](https://github.com/aurora-silicon/linux/commit/2740578bc68c410528172a54f9e2e19d35c255d1), [c96a7ffae393](https://github.com/aurora-silicon/linux/commit/c96a7ffae39306507c405d49a3a19927eab289fe), [5578a4e73d10](https://github.com/aurora-silicon/linux/commit/5578a4e73d10d63615ed1eaaf5a7215310df19b8) | Ryan Murray | arm64: dts: apple: t8140: Add CPU frequency scaling | Active translated data — FW | B,P | -| [e7e641d03183](https://github.com/aurora-silicon/linux/commit/e7e641d03183aa76578a1504a4758da6b71c968f), [b58c399f44d7](https://github.com/aurora-silicon/linux/commit/b58c399f44d7499ed62c907efda7b0017f421baf), [f9ec3820d63d](https://github.com/aurora-silicon/linux/commit/f9ec3820d63d57ddb9790ac168a5642efc11f21c) | Ryan Murray | arm64: dts: apple: t8140: Use the Tahiti CPU compatibles and L1 cache sizes | Active translated data — FW | B,P | -| [c702ccc166bb](https://github.com/aurora-silicon/linux/commit/c702ccc166bbe593718a8b4d8a51063e6c5bc102), [f104bb09ce2a](https://github.com/aurora-silicon/linux/commit/f104bb09ce2abf48baa4cf5028b9224141cfdd00), [118ffba5b7b0](https://github.com/aurora-silicon/linux/commit/118ffba5b7b06b9786e24dfab819caa1fb1a2333) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable ANS, SMC and CPU frequency scaling | Active translated data — FW | B,P | -| [5e5d5289f17e](https://github.com/aurora-silicon/linux/commit/5e5d5289f17ede272d495e7e4db117d47c6523a3), [dd366e9d3a8e](https://github.com/aurora-silicon/linux/commit/dd366e9d3a8e05ab209c7ebe1b28413820f018d4) | Marcelo Alcantara | iommu: apple-dart: raise MAX_DARTS_PER_DEVICE to 8 | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e1817d4152f5](https://github.com/aurora-silicon/linux/commit/e1817d4152f57baca92148c8bbc48fe9b0a8e9f9), [97cdb08431f3](https://github.com/aurora-silicon/linux/commit/97cdb08431f3eef20c2e24c41166bc5dee9e9976), [162b64627bbc](https://github.com/aurora-silicon/linux/commit/162b64627bbcb2fa0ae83cbb6cbf86825ced3e33), [70dfd8f93d3c](https://github.com/aurora-silicon/linux/commit/70dfd8f93d3cac6d6ac7ad26909ca6378fd6a2b4) | Ryan Murray | iommu/apple-dart: Check devm_memremap() for an error pointer | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [f57d90040433](https://github.com/aurora-silicon/linux/commit/f57d9004043387ed6c437ddf0afcfcc1bb49f2fd), [6fa300933bb1](https://github.com/aurora-silicon/linux/commit/6fa300933bb1f05c9a49bddc05f8ea3b42c47d35), [79379798f12f](https://github.com/aurora-silicon/linux/commit/79379798f12fdb32ba79f74b0524cfc4f0170471) | Ryan Murray | iommu/apple-dart: Support T8140 DARTs and firmware-owned stream roots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [6ec845b2f381](https://github.com/aurora-silicon/linux/commit/6ec845b2f3812090ed39893f8e26999c757950c9), [3bd878053ca7](https://github.com/aurora-silicon/linux/commit/3bd878053ca7aed1e4af56bc14c339b8bddc6d9c), [6898f34ac7bd](https://github.com/aurora-silicon/linux/commit/6898f34ac7bd349ce29b60fb9785168950c5ed69), [fb7b8edf4ee1](https://github.com/aurora-silicon/linux/commit/fb7b8edf4ee19a35c07c1a2c6aa6b8e65c71777b) | DjDeveloperr | arm64: dts: apple: t8140-pmgr: Add the GPU power domains [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [cc2d03580b0a](https://github.com/aurora-silicon/linux/commit/cc2d03580b0a68ca0f9779adebd646645813d673), [ea4abd222b2f](https://github.com/aurora-silicon/linux/commit/ea4abd222b2fa2473dba79ca4a91a220e8cb20ba), [52fac306b907](https://github.com/aurora-silicon/linux/commit/52fac306b90783087af17af7ba3e2fc6570122e5), [e77d74a6be76](https://github.com/aurora-silicon/linux/commit/e77d74a6be7645e64b9b50bb51713e72a08c9520) | DjDeveloperr | arm64: dts: apple: t8140: Add the GPU [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [8284bd4d3914](https://github.com/aurora-silicon/linux/commit/8284bd4d3914ce296a83c38753a69b07e1c10a0e), [29b0b3a54664](https://github.com/aurora-silicon/linux/commit/29b0b3a546641438b14da95054ae136540465de8), [54124e3efacb](https://github.com/aurora-silicon/linux/commit/54124e3efacba7ba530e742cb2f297bbdeb719fa), [f4a46cd97b2a](https://github.com/aurora-silicon/linux/commit/f4a46cd97b2a3e70875d76e3cf2b82f3959fd0f5) | DjDeveloperr | arm64: dts: apple: t8140-j700: Enable the GPU [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW | B,P | -| [31ee8e23124d](https://github.com/aurora-silicon/linux/commit/31ee8e23124d77700e47cabc0e8645404187fd74), [5b85b301d4ee](https://github.com/aurora-silicon/linux/commit/5b85b301d4ee38256c757299a0c58c4a79a531a7), [727284277d33](https://github.com/aurora-silicon/linux/commit/727284277d335215edd48b5f74a6f4d4e949ff3a), [9c10d7198c8e](https://github.com/aurora-silicon/linux/commit/9c10d7198c8e56b16da35914ffde0eecb6bfb525) | DjDeveloperr | arm64: dts: apple: t8140: describe the GPU mailboxes as ASCWrap v6 [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MBOX | B | -| [dbc9f011ec91](https://github.com/aurora-silicon/linux/commit/dbc9f011ec91fb72089a45487891bfd7c5a8939d), [86fba21bf7c9](https://github.com/aurora-silicon/linux/commit/86fba21bf7c926033306cb2dc5b6d5bcfbbe30ce), [018ab982644a](https://github.com/aurora-silicon/linux/commit/018ab982644a6eff94a6020d8910e9c8c187d6a2) | Ryan Murray | arm64: dts: apple: t8140: Add CPU energy model and thermal sensor cells | Active translated data — FW | B,P | -| [b15c2faba082](https://github.com/aurora-silicon/linux/commit/b15c2faba08274f02bf9a11e0e15eef470017dbd), [d693f725d774](https://github.com/aurora-silicon/linux/commit/d693f725d77422774ae683701732562a84789439), [d69c31212d2b](https://github.com/aurora-silicon/linux/commit/d69c31212d2b93b6396775c7890d5734f962c486) | Ryan Murray | arm64: dts: apple: t8140-j700: Add CPU thermal zones | Active translated data — FW | B,P | -| [25b99e9b6a75](https://github.com/aurora-silicon/linux/commit/25b99e9b6a75a9e783d7b5f04ee60b4f97fe24ed), [1ffe37e7af24](https://github.com/aurora-silicon/linux/commit/1ffe37e7af241fb91ecd7a8d17c946fd0a5d8ecc), [64eff8a46206](https://github.com/aurora-silicon/linux/commit/64eff8a46206613ff354cbeaff49d1354e4c1f52) | Ryan Murray | arm64: dts: apple: t8140: Drop the J700 CPU thermal policy property | Active translated data — FW | B,P | -| [db87f30fa4e7](https://github.com/aurora-silicon/linux/commit/db87f30fa4e7a322d655989316aef41a00fc46e5), [cf7dc9d0474c](https://github.com/aurora-silicon/linux/commit/cf7dc9d0474cc53e3716948365b72bacc848d5e9), [8ba3c01c426a](https://github.com/aurora-silicon/linux/commit/8ba3c01c426a8efd643289689493835c51b8937d) | Ryan Murray | arm64: dts: apple: t8140: Add measured CPU capacity values | Active translated data — FW | B,P | -| [6bb7669702ed](https://github.com/aurora-silicon/linux/commit/6bb7669702edf26c05f2be84f303d0fd612487b2), [2623391b533d](https://github.com/aurora-silicon/linux/commit/2623391b533de7f038408e57e3084a75f765b56c), [3dd2554de0c5](https://github.com/aurora-silicon/linux/commit/3dd2554de0c5b6e9d16a3809186872847987de6a) | Ryan Murray | arm64: dts: apple: enable the PMP fast-die limiter on J700 [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP | P,B | -| [47ed624515f4](https://github.com/aurora-silicon/linux/commit/47ed624515f40f37b39230c3b1b20bb6678c788a), [66988937c0d6](https://github.com/aurora-silicon/linux/commit/66988937c0d62aeb1ed828379cb83bbc68581afc), [39a036ead934](https://github.com/aurora-silicon/linux/commit/39a036ead934c701af76e05eebd72b102810861c) | Ryan Murray | arm64: dts: apple: t8140-j700: enable the PMP nodes once | Active — PMP | P,B | -| [a539d62f765f](https://github.com/aurora-silicon/linux/commit/a539d62f765fb0e8153f2be0fa8fb33058f6df9a), [c1af50661b44](https://github.com/aurora-silicon/linux/commit/c1af50661b44940df0c5747ae7dfca25c871bbcb), [d30b0dfcf358](https://github.com/aurora-silicon/linux/commit/d30b0dfcf35813ce52d935e24e7e6d46349ec3cd) | Ryan Murray | arm64: dts: apple: t8140-j700: Keep the idle E cluster out of its lowest OPP | Active translated data — FW | B,P | -| [fb68b124b886](https://github.com/aurora-silicon/linux/commit/fb68b124b8865e39b72b2387e7f739856f72cc26), [76dd6fb9e643](https://github.com/aurora-silicon/linux/commit/76dd6fb9e643747eb61c3b409c93b1ce2975184e), [2d51c6aada40](https://github.com/aurora-silicon/linux/commit/2d51c6aada40a6c97ae81464eea6935ebf70ba95) | Ryan Murray | arm64: dts: apple: t8140: Describe the memory cache controller | Active — MCC | M,P | -| [5811648de37d](https://github.com/aurora-silicon/linux/commit/5811648de37d1bcd66a5294f44191da8880947b2), [840606faf824](https://github.com/aurora-silicon/linux/commit/840606faf824b4f6ea862f8475e7edaff9af4150), [b5b71dfc50b2](https://github.com/aurora-silicon/linux/commit/b5b71dfc50b2bfbf5800a76c540f878924a678cb), [ed31b37fb032](https://github.com/aurora-silicon/linux/commit/ed31b37fb0327ee7c20961fce2785ed3d4ddb154) | DjDeveloperr | arm64: dts: apple: t8140: describe the PMC and report GFX to the PMP [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active after port — PMC | P,C,R | -| [15f21cbc0d4b](https://github.com/aurora-silicon/linux/commit/15f21cbc0d4bbbc901454d1e69f53084e1c5dc18), [6cab4decfb66](https://github.com/aurora-silicon/linux/commit/6cab4decfb664524936da59558bc39407b633b9a), [0272b63e30f0](https://github.com/aurora-silicon/linux/commit/0272b63e30f07b8c1a496cb01f5aa74e2cc1ff93) | Ryan Murray | arm64: dts: apple: t8140: keep the GPU on its PMGR state [#219](https://github.com/aurora-silicon/linux/pull/219) | Active translated data — FW | B,P | -| [0a44c956dde2](https://github.com/aurora-silicon/linux/commit/0a44c956dde28aad0bd37b66c6ff5d8096e5676d), [8fa836c5de81](https://github.com/aurora-silicon/linux/commit/8fa836c5de8111ab90d8f2a746526d2cd487afb7), [ae8e780a5b7d](https://github.com/aurora-silicon/linux/commit/ae8e780a5b7dedcb4a31adbd106fb9f9dbff8be0) | Ryan Murray | arm64: dts: apple: t8140: describe the PMC's DCS limit [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [84eb6b53da34](https://github.com/aurora-silicon/linux/commit/84eb6b53da3453d7c2838bd2a41779e0a9bce181), [f01e1cde7d9f](https://github.com/aurora-silicon/linux/commit/f01e1cde7d9f270e156ee77c6819466757b938f6), [a037985ac960](https://github.com/aurora-silicon/linux/commit/a037985ac9605eb76fe51a05b172b022ac1f0005) | Ryan Murray | arm64: dts: apple: t8140-j700: limit the DCS vote when the die runs hot [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [4f6bac29d934](https://github.com/aurora-silicon/linux/commit/4f6bac29d9349ced88686239f259ab2747207708), [e10ab48a4590](https://github.com/aurora-silicon/linux/commit/e10ab48a4590c23c664546f524650310222b3a35), [c1bae63595e8](https://github.com/aurora-silicon/linux/commit/c1bae63595e8fc7b18e79664ee6aa6b4536f5d95) | Ryan Murray | arm64: dts: apple: t8140: Keep the GPU power state on across sleep | Active translated data — FW | B,P | -| [01d1be596840](https://github.com/aurora-silicon/linux/commit/01d1be596840358a7258d87fc91d3201a3287313), [8b6371b5500d](https://github.com/aurora-silicon/linux/commit/8b6371b5500d062c00f71d46a0bccbcbed111edd) | Ryan Murray | iommu: apple-dart: Program T8140 and T8142 streams individually | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [2398a03f445e](https://github.com/aurora-silicon/linux/commit/2398a03f445e8f9f65fa9f86748a3deeab3e1b1f), [69c39f85461e](https://github.com/aurora-silicon/linux/commit/69c39f85461e8944dff387eab703c58ea6c6ed49), [1d2904fd3301](https://github.com/aurora-silicon/linux/commit/1d2904fd3301c63620f07c81ae79f2486a81a9a6) | Dj | iommu/apple-dart: defer locked root publication until attach | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ae5849165749](https://github.com/aurora-silicon/linux/commit/ae58491657494b0f56ec0113a3aa43612648e242), [44c7f32baad0](https://github.com/aurora-silicon/linux/commit/44c7f32baad0511e6f3ae5c2ffdd863eec8e5d23), [dc9d13edb0e5](https://github.com/aurora-silicon/linux/commit/dc9d13edb0e5b18c61d25240ed4ba532afb8d11f) | Acelogic | iommu/apple-dart: accept T8142 firmware slots that mirror Linux mappings | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [1917cbce81cb](https://github.com/aurora-silicon/linux/commit/1917cbce81cb806498b0a5a3f5e636c851255408), [61dfeb8f659d](https://github.com/aurora-silicon/linux/commit/61dfeb8f659d36149d3dc6162d304136b108c5b9), [c361702757bf](https://github.com/aurora-silicon/linux/commit/c361702757bfccb9183ed79be0c6200fb3722e6f) | Ryan Murray | iommu/apple-dart: defer publication until locked roots are known | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [c74dc14619ec](https://github.com/aurora-silicon/linux/commit/c74dc14619ec5467789855d89c0ef224a3655093), [35f59a797e91](https://github.com/aurora-silicon/linux/commit/35f59a797e914308f4ae289e87551ad97997a497), [d957b0bd713b](https://github.com/aurora-silicon/linux/commit/d957b0bd713bbf4617f54f5ed0d274964e9af6c9) | Ryan Murray | iommu/apple-dart: validate software mappings against inherited slots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [f89a3c873999](https://github.com/aurora-silicon/linux/commit/f89a3c87399911e0faa4f66091b2e7dcc1145825), [64013b9557ab](https://github.com/aurora-silicon/linux/commit/64013b9557abadab17883a7e697f32f32e0c4160), [707f28a4c399](https://github.com/aurora-silicon/linux/commit/707f28a4c399092ba01bd281a3f0b6623f7bb223) | Ryan Murray | iommu/apple-dart: import firmware translations on T8140 | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [99633bd5454e](https://github.com/aurora-silicon/linux/commit/99633bd5454eac0e455812358be63b4f08d78a98), [c29b618f6340](https://github.com/aurora-silicon/linux/commit/c29b618f6340b4ede94747a266f86a844344e769), [ebcff4ba64dd](https://github.com/aurora-silicon/linux/commit/ebcff4ba64dd90983cc8150b0f46fda82b5fb9f0) | Ryan Murray | iommu: apple-dart: retain inherited translations before reservation setup | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [8d2d7790d8d5](https://github.com/aurora-silicon/linux/commit/8d2d7790d8d552f01ce2bf10f922aaccbf7918aa), [dbd410951406](https://github.com/aurora-silicon/linux/commit/dbd4109514067a2ed8140d8138bee68453272f02), [8478ae014201](https://github.com/aurora-silicon/linux/commit/8478ae0142014d170a62df6dd94cc66bd989627b) | Chris Kearney | iommu/apple-dart: restore legacy locked display domain handoff | Active — DART; `drivers/iommu/Kconfig` | D,B | -| [0297adcecc72](https://github.com/aurora-silicon/linux/commit/0297adcecc72a563b5cfb3ca3e483f71422fb77c), [b71446526889](https://github.com/aurora-silicon/linux/commit/b71446526889b27c60461685c3c320b7e123155d), [2bad3dba632f](https://github.com/aurora-silicon/linux/commit/2bad3dba632ff85537392b79255fc527baf01746) | Ryan Murray | iommu: apple-dart: keep inherited firmware translations visible before attach | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [80ce713f5251](https://github.com/aurora-silicon/linux/commit/80ce713f52511abe4d35b35bfac0f10f9072d401), [8ece17f482f1](https://github.com/aurora-silicon/linux/commit/8ece17f482f11da6e81915b98fc8b93ed796504a), [a64a4771b276](https://github.com/aurora-silicon/linux/commit/a64a4771b27602bf5a72b413b6bc9a868892992a) | Ryan Murray | iommu: apple-dart: invalidate T8110 ranges by device DVA [#221](https://github.com/aurora-silicon/linux/pull/221) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [cef9a23aa45e](https://github.com/aurora-silicon/linux/commit/cef9a23aa45e3ac6b352e6c2bd839935374ae351), [253ba9bebf47](https://github.com/aurora-silicon/linux/commit/253ba9bebf470c0d78845103c93b937f2d9cdfb3), [dd5ac6fdffb0](https://github.com/aurora-silicon/linux/commit/dd5ac6fdffb03d048df510198af6e8d53dceb17d) | Ryan Murray | iommu: apple-dart: leave live firmware translations out of invalidates [#221](https://github.com/aurora-silicon/linux/pull/221) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [0a73b0299574](https://github.com/aurora-silicon/linux/commit/0a73b0299574da4c42659024b4a0e8390c36d2d8), [bc6682c215ad](https://github.com/aurora-silicon/linux/commit/bc6682c215adc6febfb86c9fa2ed0fb69657dcc2), [9c512b25f55e](https://github.com/aurora-silicon/linux/commit/9c512b25f55eaf6332b590e5a205ca7d55de12c8) | Ryan Murray | iommu: apple-dart: invalidate client-ranged T8140 streams again [#232](https://github.com/aurora-silicon/linux/pull/232) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ae812d47ea17](https://github.com/aurora-silicon/linux/commit/ae812d47ea176c9bb0b4ddccc17349fee5afbf1a), [fe15676f6e03](https://github.com/aurora-silicon/linux/commit/fe15676f6e03395f4947cbffb2d49fbee17ea5f9), [4ca4ba380552](https://github.com/aurora-silicon/linux/commit/4ca4ba3805528f5370bbe6bab3d8dbb8f7f9226c) | Ryan Murray | iommu: apple-dart: invalidate four-level T8140 streams by DVA range [#237](https://github.com/aurora-silicon/linux/pull/237) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [a17634424697](https://github.com/aurora-silicon/linux/commit/a17634424697b082221d141ef61d9689460eebf8), [d1a5c65245b8](https://github.com/aurora-silicon/linux/commit/d1a5c65245b87c457a8fc4b4190d440e9bc38b8d) | Sasha Finkelstein | soc: apple: rtkit: Add tracekit endpoint. | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [ff7d81511780](https://github.com/aurora-silicon/linux/commit/ff7d81511780770e944ebe6e66ed56a06b497a31) | Ryan Murray | drm/asahi: Adapt to the Linux 7.3 Rust APIs [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/debug.rs` | M,D | -| [588c231eaa54](https://github.com/aurora-silicon/linux/commit/588c231eaa54f4a34872519517fbbcc079b41175) | Ryan Murray | soc: apple: Adapt the Rust SEP, PMP and AOP drivers to Linux 7.3 | Active — PMP; `drivers/soc/apple/aop.rs` | P,B | -| [c025e6cd0615](https://github.com/aurora-silicon/linux/commit/c025e6cd0615e416e0a06ba997e8d9f417a3e185), [af0890cf33cf](https://github.com/aurora-silicon/linux/commit/af0890cf33cf899cf0005daf6138da1dfe573c19) | Ryan Murray | soc: apple: rtkit: Harden syslog buffer handling | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [3a8760c28c33](https://github.com/aurora-silicon/linux/commit/3a8760c28c3341380e105c75bb48e76c895d3f3d), [c01af1b31c52](https://github.com/aurora-silicon/linux/commit/c01af1b31c523b09106c4bed43f8bb7cba65cbfc) | Ryan Murray | soc: apple: rtkit: Keep a live shared buffer on a repeated request | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [495b2f037c28](https://github.com/aurora-silicon/linux/commit/495b2f037c284f4b7b10f54c90a7d34fbf5e99fa), [6b7e37786882](https://github.com/aurora-silicon/linux/commit/6b7e37786882db803e9de1352a2af623044f9237), [1fc9ea993905](https://github.com/aurora-silicon/linux/commit/1fc9ea9939058bc1307565f036506da30dd62908) | Ryan Murray | soc: apple: rtkit: Serialize receiver ownership through teardown | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [335eaeb9b9f1](https://github.com/aurora-silicon/linux/commit/335eaeb9b9f147230f464a140287e820b1d78518), [0593ad398a6e](https://github.com/aurora-silicon/linux/commit/0593ad398a6eb83e2e2ce9dd25bf1fd0768e5bcd) | Ryan Murray | soc: apple: rtkit: Add apple_rtkit_free_retaining_buffers() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e796f5fbaf06](https://github.com/aurora-silicon/linux/commit/e796f5fbaf0698b478c43ba6eb15e046c9cc6244), [8527354650e8](https://github.com/aurora-silicon/linux/commit/8527354650e810479ceb0a58417e683b2dee852c) | Ryan Murray | soc: apple: rtkit: Allow streaming-mapped shared buffers | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [9191296f1898](https://github.com/aurora-silicon/linux/commit/9191296f1898d1acf2d0cd500230ae80c9e3e0ca), [88e3c5c07943](https://github.com/aurora-silicon/linux/commit/88e3c5c07943fedf73e45f88b270f8550d7691ae) | Ryan Murray | soc: apple: rtkit: Support adopting a running co-processor | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [1932e1e1b184](https://github.com/aurora-silicon/linux/commit/1932e1e1b18437408e77dcc1d23d6d966b0fdb98), [f232f22bef54](https://github.com/aurora-silicon/linux/commit/f232f22bef54eb6fbd848a1374e49fe91035b397) | Ryan Murray | soc: apple: rtkit: Report crashes of an adopted co-processor | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [b38944203ab0](https://github.com/aurora-silicon/linux/commit/b38944203ab0ad8ec01c26bd67df67455fcc98c3), [4f0416f2c43b](https://github.com/aurora-silicon/linux/commit/4f0416f2c43ba895b3c34a263cf5d0e070095a55), [2768025e0f1d](https://github.com/aurora-silicon/linux/commit/2768025e0f1d9792f84e9fbb99f6c0b155c0a22a), [35b2acbf474d](https://github.com/aurora-silicon/linux/commit/35b2acbf474d8505c3edc1a2749a8d6fbfaf7a09) | Ryan Murray | pmdomain: apple: Print the read-back state on a power state timeout | Active — OBS; `drivers/pmdomain/apple/pmgr-pwrstate.c` | O,F | -| [768a665d0ca1](https://github.com/aurora-silicon/linux/commit/768a665d0ca138d0f2c80029fd1d272c11468e2e), [9c5b8fe6d6d6](https://github.com/aurora-silicon/linux/commit/9c5b8fe6d6d6a93f7c4bbbd14026fd93d5f6aa73), [afe19efeff9c](https://github.com/aurora-silicon/linux/commit/afe19efeff9c466486fb723f7066f86b9a3e71d5), [9dc79fb25c92](https://github.com/aurora-silicon/linux/commit/9dc79fb25c9294bd7a8ecb00acc9bcea379c3d1a) | Ryan Murray | pmdomain: apple: Mask BUSY in power state writes and ratelimit errors | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [a6aa625a9b35](https://github.com/aurora-silicon/linux/commit/a6aa625a9b35b96ba4ffc0749d55a0f21fe9e426), [03f4792761f4](https://github.com/aurora-silicon/linux/commit/03f4792761f42c3a4581be4b585a479cfc65bfc3), [f82e88f4049e](https://github.com/aurora-silicon/linux/commit/f82e88f4049ed6ea278717be6d922f8e347aab13), [928641d26be3](https://github.com/aurora-silicon/linux/commit/928641d26be3083dc06c0de072ce99537fa059b7) | DjDeveloperr | soc: apple: rtkit: Support co-processors that place their own buffers [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e52b589758bd](https://github.com/aurora-silicon/linux/commit/e52b589758bd9c72db728ef41947aadc2d1eec3f), [a8e468104169](https://github.com/aurora-silicon/linux/commit/a8e46810416977c034c45d805c0b504cfdab9a6a), [c07d044a0311](https://github.com/aurora-silicon/linux/commit/c07d044a03117705721c78500bc36489ea34e6c4) | Ryan Murray | soc: apple: rtkit: recognise an initial crash log in adopted sessions | Active — RTKIT; `drivers/soc/apple/rtkit-crashlog.c` | B,F | -| [8420f4272083](https://github.com/aurora-silicon/linux/commit/8420f42720830b9e5bad37647b6eead5303bc566), [352b68249894](https://github.com/aurora-silicon/linux/commit/352b682498947d0062635916a9d6902165ab38b5), [2f434459eb09](https://github.com/aurora-silicon/linux/commit/2f434459eb094edc046cd2ff71f1901302d7ef3d) | Ryan Murray | soc: apple: rtkit: reject an already owned mailbox receiver | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [791f8c37bad3](https://github.com/aurora-silicon/linux/commit/791f8c37bad39ada4186e7db9efb74472ef1670b), [44a668c87df1](https://github.com/aurora-silicon/linux/commit/44a668c87df18147ca0c9ace22e897e4c65b7620), [41e7892e40eb](https://github.com/aurora-silicon/linux/commit/41e7892e40eb21ddb08b2391a7940ed6499daf8d) | Ryan Murray | soc: apple: pmp: use a 42-bit DMA mask on T8140 [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [7a9913ea25e2](https://github.com/aurora-silicon/linux/commit/7a9913ea25e2d95d3ebe8f0392fec92979d08728), [493080d07b91](https://github.com/aurora-silicon/linux/commit/493080d07b918a2025fb79ff987d0dc9aeb294fe), [f69f1b76fcb0](https://github.com/aurora-silicon/linux/commit/f69f1b76fcb04e6bd7d7d066654e612be9761af0) | Ryan Murray | pmdomain: apple: pmp-report: expose T8140 fast-die effort [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [1a665f53f540](https://github.com/aurora-silicon/linux/commit/1a665f53f540a523d8df2c11d11a824f933b0d14), [8410c0eac2d9](https://github.com/aurora-silicon/linux/commit/8410c0eac2d9419a33c6a8d4a00bd14059f94610), [4f3e0ed14a9c](https://github.com/aurora-silicon/linux/commit/4f3e0ed14a9c280aafb3642619e7335413592e06) | Ryan Murray | pmdomain: apple: drain PMP report users before teardown | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [50b59e9b8f43](https://github.com/aurora-silicon/linux/commit/50b59e9b8f43e49c14a8a5e426f7891ac5f5e8c7), [061cf8fae73f](https://github.com/aurora-silicon/linux/commit/061cf8fae73f12de8d6720602ccac2aec250a20f), [f4ec00ff19db](https://github.com/aurora-silicon/linux/commit/f4ec00ff19dbfdc6d9bdbf03e8d7ec2798502f1a) | Ryan Murray | soc: apple: Enable T8140 system level cache allocation | Active — MCC; `drivers/soc/apple/Kconfig` | M,P | -| [628dbbe941d2](https://github.com/aurora-silicon/linux/commit/628dbbe941d25e5153dc62cb04104f846f3ffc48), [af915d02f5f6](https://github.com/aurora-silicon/linux/commit/af915d02f5f6022114a46e302642e915f9b22a01), [8b7d7f837ff6](https://github.com/aurora-silicon/linux/commit/8b7d7f837ff68f7fa37f6aaae55114bbd15efb43), [132cee4161dc](https://github.com/aurora-silicon/linux/commit/132cee4161dcff4307c55314f2a6189a00e7b0df) | DjDeveloperr | pmdomain: apple: add PMC voter interface driver [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active after port — PMC; `drivers/pmdomain/apple/Kconfig` | P,C,R | -| [698f429f4256](https://github.com/aurora-silicon/linux/commit/698f429f42566c059e7788e4efd44978a5db33a9), [9e840cf32336](https://github.com/aurora-silicon/linux/commit/9e840cf323360eabdb61223cf73198f4f4f3179d), [6454e02db2a5](https://github.com/aurora-silicon/linux/commit/6454e02db2a562d82adfbc4447ffe093f43dae0a), [5bd867f5c339](https://github.com/aurora-silicon/linux/commit/5bd867f5c33919ed65c81ead1e31595bb6bb91c5) | DjDeveloperr | soc: apple: add host performance controller floors [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [faff1f7acf75](https://github.com/aurora-silicon/linux/commit/faff1f7acf752284972af5d469f91186c1e28552), [1c69f57e2c3e](https://github.com/aurora-silicon/linux/commit/1c69f57e2c3e5ba7cea2db4708242b7b538b15b2), [e736b2a049bf](https://github.com/aurora-silicon/linux/commit/e736b2a049bf708512f845093f712c431c20da3b) | Ryan Murray | pmdomain: apple: pmc: report the honoured floor of each agent [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — PMC; `drivers/pmdomain/apple/pmc.c` | P,C,R | -| [9afc8195e8e2](https://github.com/aurora-silicon/linux/commit/9afc8195e8e2b3b4da25805f0b0c53baac16f1de), [e3f7747b88a3](https://github.com/aurora-silicon/linux/commit/e3f7747b88a38a8f2db51a63b323bb6fe3a25157), [cf8edfc522ce](https://github.com/aurora-silicon/linux/commit/cf8edfc522ce82871acc421119e324b56ab2813f) | Ryan Murray | pmdomain: apple: pmc: limit the DCS rail as a cooling device [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS; `drivers/pmdomain/apple/pmc.c` | P | -| [c809017f2926](https://github.com/aurora-silicon/linux/commit/c809017f2926613cc9b683189c5e37aa6236c647), [bbbc7f0f2526](https://github.com/aurora-silicon/linux/commit/bbbc7f0f2526501df99e7d40c7a14a5bcb3c168d), [99bf4fc4c39c](https://github.com/aurora-silicon/linux/commit/99bf4fc4c39cbe59493531b7682f0a7eb60ac2e0) | Ryan Murray | pmdomain: apple: build the PMC driver by default [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — PMC; `drivers/pmdomain/apple/Kconfig` | P,C,R | -| [413512c8c6c7](https://github.com/aurora-silicon/linux/commit/413512c8c6c7503e21b2d845b7072f3e67985e80), [afbf48da68ef](https://github.com/aurora-silicon/linux/commit/afbf48da68ef244414db4e174b630cf95ed33bd2), [d0f012d7b92f](https://github.com/aurora-silicon/linux/commit/d0f012d7b92f9967d42c35a70bc09c2b87274c0b) | Ryan Murray | soc: apple: clpc: do not count offline CPUs as busy [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [a1517450f0d6](https://github.com/aurora-silicon/linux/commit/a1517450f0d6afa99ed5a5f2acbbc46350fdccd5), [a0301cd2e0fb](https://github.com/aurora-silicon/linux/commit/a0301cd2e0fb788836d8ef4d09b397a478891a72), [ddc216cd42cb](https://github.com/aurora-silicon/linux/commit/ddc216cd42cb7c7ebc831d3fafca17df244b280e) | Ryan Murray | soc: apple: clpc: stop waking idle CPUs and release the floor in sleep [#219](https://github.com/aurora-silicon/linux/pull/219) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [17c6097b09dd](https://github.com/aurora-silicon/linux/commit/17c6097b09ddd81a31a618e1d2447c3fdfed87ce), [ebd97e7441ff](https://github.com/aurora-silicon/linux/commit/ebd97e7441ff7ca5f7169f6e2bf550e7fb1438e0), [4f13ab717cb3](https://github.com/aurora-silicon/linux/commit/4f13ab717cb3a5ab19e5c097084ff2c676457f37) | Ryan Murray | pmdomain: apple: pmp-report: keep entry domains bound [#223](https://github.com/aurora-silicon/linux/pull/223) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [bd2a439af1fe](https://github.com/aurora-silicon/linux/commit/bd2a439af1feefbb19cec4af61a28ae81a7fe479), [6733b19981f1](https://github.com/aurora-silicon/linux/commit/6733b19981f1d70f51264f609582025889e083db), [59540c7f72b3](https://github.com/aurora-silicon/linux/commit/59540c7f72b3721d293fb36cc5fd5bf79e1f47bc) | Ryan Murray | pmdomain: apple: Undo a power state transition that times out | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [afa52a4aacd2](https://github.com/aurora-silicon/linux/commit/afa52a4aacd24be61e6963bcfa96a673fcd0f7fd), [b1dadbe56c1a](https://github.com/aurora-silicon/linux/commit/b1dadbe56c1ac98c1687aacd6f9a4ffd45d44802) | Acelogic | soc: apple: rtkit: Allow AP readiness before the IOP power acknowledgement | Active — RTKIT; `drivers/soc/apple/rtkit-helper.c` | B,F | -| [80223777e1c0](https://github.com/aurora-silicon/linux/commit/80223777e1c0fcdd18cdf7dbb693389f18bffe66), [7de139272456](https://github.com/aurora-silicon/linux/commit/7de1392724567cdab869ed7102a23642d6e64320), [b5c2960b4b44](https://github.com/aurora-silicon/linux/commit/b5c2960b4b441fa51b7f0ccdbaa17eae8a9de4bc) | Ryan Murray | soc: apple: rtkit: identify failed boot handshake stages | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e02a7f13d77d](https://github.com/aurora-silicon/linux/commit/e02a7f13d77d0c450e6e663da89160b8e2e6a9de), [3a165a5f418d](https://github.com/aurora-silicon/linux/commit/3a165a5f418df4ca2445c14657bdc6dbe39bb223), [50a711417171](https://github.com/aurora-silicon/linux/commit/50a711417171e48a07340999bf43bb8c281b14d7) | Eryk Wieliczko | pmdomain: apple: leave firmware-owned power domains untouched | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [15a254a94f16](https://github.com/aurora-silicon/linux/commit/15a254a94f1685a5550aec6c99a3270bfb389951), [e271de959b7d](https://github.com/aurora-silicon/linux/commit/e271de959b7de2e436f15415329d175e2e158517) | Ryan Murray | soc: apple: rtkit: Recognise opaque OSLog events 3 to 5 | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [faadb28854ca](https://github.com/aurora-silicon/linux/commit/faadb28854caaf534df60f6d629eca87c963344f), [aa486de92319](https://github.com/aurora-silicon/linux/commit/aa486de923198c933849bb2172f5ddad4f4710b6), [6559da7d50ab](https://github.com/aurora-silicon/linux/commit/6559da7d50ab10da722b3719f447836b12427159), [7810f444ae5a](https://github.com/aurora-silicon/linux/commit/7810f444ae5a403773baf8d4f460e29cb2375cf5) | Ryan Murray | cpufreq: apple-soc: Use related_cpus when removing OPP tables at exit | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [f630f4e6a724](https://github.com/aurora-silicon/linux/commit/f630f4e6a724b62182875eeb75e3559f6304b286), [4df394b4c36b](https://github.com/aurora-silicon/linux/commit/4df394b4c36be04ca63fabae2c630bfdda20188a), [31ce0bec7173](https://github.com/aurora-silicon/linux/commit/31ce0bec7173eb3fbc1067e6dba46c2ca2f4dc8e) | Ryan Murray | cpufreq: apple-soc: Add T8140 support | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [116ec26bc074](https://github.com/aurora-silicon/linux/commit/116ec26bc074456b670823002c81ccffc5fbbecc), [2e97d372534e](https://github.com/aurora-silicon/linux/commit/2e97d372534e73b72b9b36b9debaa3caa9ae5ab6), [b0a02dcbfded](https://github.com/aurora-silicon/linux/commit/b0a02dcbfded7f1485db7f37694712892025a4d9) | Ryan Murray | cpufreq: apple-soc: enforce PMP fast-die limits through QoS [#179](https://github.com/aurora-silicon/linux/pull/179) | Active — PMP; `drivers/cpufreq/apple-soc-cpufreq.c` | P,B | -| [3a1ff1c99f6a](https://github.com/aurora-silicon/linux/commit/3a1ff1c99f6a35163c77f9c2cc5f6b19d4fe6242), [9d74a86460df](https://github.com/aurora-silicon/linux/commit/9d74a86460df995f3522f3267c3f3fa34d79a47e) | Ryan Murray | cpufreq: apple-soc: keep required fallback limits with an older DT | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [1248cb920813](https://github.com/aurora-silicon/linux/commit/1248cb9208135326d9724eb1a83e3c67d25c3664), [a40bdafc42e5](https://github.com/aurora-silicon/linux/commit/a40bdafc42e5dcf8c0c4bc728f883c7e3d48bffe), [a61bca6382a7](https://github.com/aurora-silicon/linux/commit/a61bca6382a765f5b74134dea3b094039f2a15bd) | Ryan Murray | cpufreq: apple-soc: tidy includes and the ->exit() callback [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,P | -| [c52554b353b4](https://github.com/aurora-silicon/linux/commit/c52554b353b4fcecf684ea648e4b1ab5f896b677), [143dc7bec441](https://github.com/aurora-silicon/linux/commit/143dc7bec44131ac467fa21049f2d63c52783d52), [e7d3d687d207](https://github.com/aurora-silicon/linux/commit/e7d3d687d20745259fcb83af83c9ed377ff6a1f3) | Ryan Murray | cpufreq: apple-soc: describe the unmanaged P-state ceiling as data [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,P | -| [e71cc1ccab4e](https://github.com/aurora-silicon/linux/commit/e71cc1ccab4eaefdf63d66104107c9604ab04121), [cd8875cfd1bf](https://github.com/aurora-silicon/linux/commit/cd8875cfd1bfaa80b1b1dbd7e27ea234d129471b), [cfe897d4abac](https://github.com/aurora-silicon/linux/commit/cfe897d4abac70a3d9703ea7f4c082ed89da7a96) | Ryan Murray | rust: soc: apple: rtkit: Add shutdown() and a buffer-retaining drop | Active — RTKIT; `rust/kernel/soc/apple/rtkit.rs` | B,F | -| [10dd5c21ef72](https://github.com/aurora-silicon/linux/commit/10dd5c21ef7211836beaa47f6f3fd3e250d36866), [8779ecb38c89](https://github.com/aurora-silicon/linux/commit/8779ecb38c89c103617c4ea24207fef96472ebc4), [06914e1d4995](https://github.com/aurora-silicon/linux/commit/06914e1d499555a96e0beccccc0b5485051108cd) | Ryan Murray | soc: apple: rtkit: Handle oslog notifications quietly | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [9a4cf171ba9e](https://github.com/aurora-silicon/linux/commit/9a4cf171ba9edabdd0f0f715468d42689791adb7), [aa18e91ac6fc](https://github.com/aurora-silicon/linux/commit/aa18e91ac6fce29dcc8e69aac619fab3fda7ee85), [904945425463](https://github.com/aurora-silicon/linux/commit/904945425463c0450cb19582afeb4b935175ae51), [201afd84ae50](https://github.com/aurora-silicon/linux/commit/201afd84ae50008095068d028af22ecf4c1356c5) | DjDeveloperr | drm/asahi: use const float bit conversion supported by Rust minimum [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/float.rs` | M,D | -| [c9be90533ae0](https://github.com/aurora-silicon/linux/commit/c9be90533ae06ac64dfe5e35b121cf30a1cc37f0), [6b610ee95063](https://github.com/aurora-silicon/linux/commit/6b610ee95063a8d047c1ee49c65ee3599ee24a92), [94b86f96bd9e](https://github.com/aurora-silicon/linux/commit/94b86f96bd9ef2275c99ddf5238374e615b2f510), [12f0a07a6166](https://github.com/aurora-silicon/linux/commit/12f0a07a61666305a1efe1a1f4c4c88a013abafb) | DjDeveloperr | rust: drm: sched: Fix job accounting when cancelling jobs [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [7ba04b60d2ca](https://github.com/aurora-silicon/linux/commit/7ba04b60d2caf298bb9119b359629feedfec38c5), [43d53c0d4f56](https://github.com/aurora-silicon/linux/commit/43d53c0d4f5660bc6d300e6626d1f9a05d832c79), [15a7eae7964f](https://github.com/aurora-silicon/linux/commit/15a7eae7964f94a16fd273fc3b25a22ad2c27bab), [f8102be460b6](https://github.com/aurora-silicon/linux/commit/f8102be460b66b12af865d6250e73ffc6f99c73a) | DjDeveloperr | rust: drm: sched: Keep the scheduler alive while jobs reference it [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [d1ebc542fe8e](https://github.com/aurora-silicon/linux/commit/d1ebc542fe8e1082a1c6e311b72d4d6c609c940d), [e4c63b3dbab0](https://github.com/aurora-silicon/linux/commit/e4c63b3dbab04bda2a798b913dd5e46b8799290a), [7d650853ea8e](https://github.com/aurora-silicon/linux/commit/7d650853ea8e5de3f512a36b69f8653014de83b4), [f1f985d57681](https://github.com/aurora-silicon/linux/commit/f1f985d576810c7183ea9bcd1b701cb284927ac6) | DjDeveloperr | rust: drm: sched: Do not stop the scheduler before tearing it down [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [45ade507d593](https://github.com/aurora-silicon/linux/commit/45ade507d593cb69929a4daf5d1d50159d729126), [1bc200c44668](https://github.com/aurora-silicon/linux/commit/1bc200c446687bc2eb2b6abc19f1d9b5a3ad59ee), [9171e855e6d5](https://github.com/aurora-silicon/linux/commit/9171e855e6d58a12059e265a7e3907f44ffa70a9), [14d7b3c379da](https://github.com/aurora-silicon/linux/commit/14d7b3c379da4c764581d4c34aff495d7346af72) | DjDeveloperr | rust: drm: sched: let drivers handle timeouts without a reset [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [996d255ea104](https://github.com/aurora-silicon/linux/commit/996d255ea104c999554b5c5584d2b59c6eed3cd9), [59b1e2a30011](https://github.com/aurora-silicon/linux/commit/59b1e2a300116dec7170b0b4a44e4b94a39c372b), [630c43dac20e](https://github.com/aurora-silicon/linux/commit/630c43dac20e9621d3c2cd687c98ab85d51c8b9e), [e0a5c5ad84cb](https://github.com/aurora-silicon/linux/commit/e0a5c5ad84cbc6e48c0194882b8c1c67d72538a8) | DjDeveloperr | drm/asahi: uapi: Add the G17 additions [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data — FW; `drivers/gpu/drm/asahi/file.rs` | B,C,R | -| [2f298100e9d5](https://github.com/aurora-silicon/linux/commit/2f298100e9d59b05f3c71d9e27d8079a63a0b6bc), [4a9cf4453a2d](https://github.com/aurora-silicon/linux/commit/4a9cf4453a2d0349848c89bd2028e8e6757263a7), [e46d8cfd391b](https://github.com/aurora-silicon/linux/commit/e46d8cfd391b00b302d5a9ff4608b82c3714c910), [aae9f7d3525f](https://github.com/aurora-silicon/linux/commit/aae9f7d3525f93a7a5b5ae0529f8e85219735d08) | DjDeveloperr | drm/asahi: separate DRM-facing GPU operations from the firmware manager [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,D | -| [3291ed172be2](https://github.com/aurora-silicon/linux/commit/3291ed172be2a63252d34367f8f5d8baebf2e537), [cac96891a49f](https://github.com/aurora-silicon/linux/commit/cac96891a49fd1416cb3bb0f68922cbebb7618c1), [54721b0f0bee](https://github.com/aurora-silicon/linux/commit/54721b0f0bee7be5b3094112ffcfa36e76dec7ed), [7d3ddb6c35e1](https://github.com/aurora-silicon/linux/commit/7d3ddb6c35e1c478f68c78ac8bb8b3ee9d314e58) | DjDeveloperr | drm/asahi: mmu: support per-SoC UAT geometry and user VA range [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [a0ae891ae8a0](https://github.com/aurora-silicon/linux/commit/a0ae891ae8a00e183ddbc753347a7ea2ef26d7dc), [79aa2038d24c](https://github.com/aurora-silicon/linux/commit/79aa2038d24c495775338c6d72b638885e2cd5e1), [49e3d35945c3](https://github.com/aurora-silicon/linux/commit/49e3d35945c397f7af5a6477540e2ee254b3bd76), [5e21536704b5](https://github.com/aurora-silicon/linux/commit/5e21536704b56c38b478516d1f65bdcfef748a17) | DjDeveloperr | drm/asahi: pgtable: track ownership below firmware-shared roots [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [524c57538f14](https://github.com/aurora-silicon/linux/commit/524c57538f142ef38c8b081f5148ffb515e96266), [52ef95b9e763](https://github.com/aurora-silicon/linux/commit/52ef95b9e7635d564449ec08b33a62c6ed26dd12), [87cab74a2498](https://github.com/aurora-silicon/linux/commit/87cab74a2498f5df62f7697786a2743e84125b99), [c0e36ff2a57f](https://github.com/aurora-silicon/linux/commit/c0e36ff2a57f2a461a96b80cebb741f5b76de7ad) | DjDeveloperr | drm/asahi: add the T8140 firmware interface [#171](https://github.com/aurora-silicon/linux/pull/171) | Active translated data; MCache gated by V25G83.mcache=false — FW; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,C,R | -| [ed303abfff0f](https://github.com/aurora-silicon/linux/commit/ed303abfff0fd9e29e8094b828cd3054969bcf97), [0386eb2184a2](https://github.com/aurora-silicon/linux/commit/0386eb2184a268ed6178a6a93a12880806a8022f), [d7d77474e459](https://github.com/aurora-silicon/linux/commit/d7d77474e4590fcd9c1d0e30ab16dc9ca0c73346), [bc4c50abf8ed](https://github.com/aurora-silicon/linux/commit/bc4c50abf8ede16fec7f2a79546a310134b208df) | DjDeveloperr | drm/asahi: request temporary CPU capacity for sustained GPU feeds [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/completion.rs` | I,C,R,P | -| [4a77604eb003](https://github.com/aurora-silicon/linux/commit/4a77604eb003ed141f28781769b28953fdabfb1f), [9fdd32f35641](https://github.com/aurora-silicon/linux/commit/9fdd32f3564105f1d012ef20e1c64de912cade1d), [15d553b170f1](https://github.com/aurora-silicon/linux/commit/15d553b170f157558da0343d477c39161f9870f1), [e1e0c5c90faf](https://github.com/aurora-silicon/linux/commit/e1e0c5c90faf0307f95374c83efe3009d58f0bdb) | DjDeveloperr | drm/asahi: observe compute completions without a queue mask [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/events.rs` | C,H | -| [593e44ca35f7](https://github.com/aurora-silicon/linux/commit/593e44ca35f708e48e0d9b9efde35bfe1052ef35), [e32d6efe3891](https://github.com/aurora-silicon/linux/commit/e32d6efe3891821dce2e6c0e27219ed676ea4f2f), [7dcd8d1467e2](https://github.com/aurora-silicon/linux/commit/7dcd8d1467e2bc1e90eeb04489d4ab7b392351e8), [0c69741cdc26](https://github.com/aurora-silicon/linux/commit/0c69741cdc26f2dbb26754e87f1b53db1f4bed38) | DjDeveloperr | drm/asahi: avoid repeated submission bookkeeping [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [0ee6827563de](https://github.com/aurora-silicon/linux/commit/0ee6827563deb2e2519534dd938334c90606fb33), [ce33535500cc](https://github.com/aurora-silicon/linux/commit/ce33535500cc78ed2f6695050ce21487902806bc), [ffa3234a92d7](https://github.com/aurora-silicon/linux/commit/ffa3234a92d789514f3e6b05213f417454b73639), [e0d2761bd854](https://github.com/aurora-silicon/linux/commit/e0d2761bd854136076d642b614c9b6078699243e) | DjDeveloperr | drm/asahi: settle unpublished jobs discarded by entity teardown [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/job.rs` | C,R,H | -| [7eb278622690](https://github.com/aurora-silicon/linux/commit/7eb27862269055d524de513e380572b59171a390), [aa659e9a3710](https://github.com/aurora-silicon/linux/commit/aa659e9a3710765dc87d06e50227bdd8476cbd72), [0a72b08543fd](https://github.com/aurora-silicon/linux/commit/0a72b08543fdec99aa8117c8b4983eeee9b8c856), [d41b760af0bc](https://github.com/aurora-silicon/linux/commit/d41b760af0bcc10744b4145cfdbc19dab7625e8e) | DjDeveloperr | drm/asahi: reserve completion capacity for global compute replay [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [06c4e4a3193e](https://github.com/aurora-silicon/linux/commit/06c4e4a3193e5b0630e343d9730cad097471440a), [1a53f784e14f](https://github.com/aurora-silicon/linux/commit/1a53f784e14f219a44f5faa7a33947c3f4dedcb1), [945285b800d3](https://github.com/aurora-silicon/linux/commit/945285b800d30fcc9a60461b70249b96b4c053ad), [868c80c92152](https://github.com/aurora-silicon/linux/commit/868c80c921527154df5e73a271583a4b0b63fdeb) | DjDeveloperr | drm/asahi: filter compute completion identities before payload reads [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,H | -| [304da56f2b1b](https://github.com/aurora-silicon/linux/commit/304da56f2b1b927ac837671897273835eeccb91b), [dc74efcea722](https://github.com/aurora-silicon/linux/commit/dc74efcea72275420878d60c358b3af182006eef), [513f7568ad7e](https://github.com/aurora-silicon/linux/commit/513f7568ad7eb30b97ac1309f37bbb3a11229409), [f61c86ab2830](https://github.com/aurora-silicon/linux/commit/f61c86ab28302e46cba8fbdbaa8339aaa4e17b40) | DjDeveloperr | drm/asahi: sample opening counters at the polling deadline [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/mod.rs` | F,Q | -| [d012beaabd09](https://github.com/aurora-silicon/linux/commit/d012beaabd0985acd8fa07a5e605f9d0c5b50590), [ff5769e16bea](https://github.com/aurora-silicon/linux/commit/ff5769e16bea501f52ff724effb309f107da39e9), [26ba1aa06add](https://github.com/aurora-silicon/linux/commit/26ba1aa06add76aa7e97a843d752fe0d08afd617), [99dd8deec12f](https://github.com/aurora-silicon/linux/commit/99dd8deec12fe28abb844854059bce6a87764199) | DjDeveloperr | drm/asahi: commit canonical binding metadata with each user mapping [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [fef7f56d2bb3](https://github.com/aurora-silicon/linux/commit/fef7f56d2bb33e5bb627a6dc8872b271a5c504cd), [6753db1b2896](https://github.com/aurora-silicon/linux/commit/6753db1b289605b5cc007a8dd8912d948897f86b), [906cacc20dfc](https://github.com/aurora-silicon/linux/commit/906cacc20dfcccb95c6ba7809f8d3ccac4624791), [11b50b74597c](https://github.com/aurora-silicon/linux/commit/11b50b74597c2c3e1f5687d5db50ce0eaa103c21) | DjDeveloperr | drm/asahi: order canonical object invalidation with mapping removal [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [31b8abbea796](https://github.com/aurora-silicon/linux/commit/31b8abbea79664748c2e8a17745bda9e82b119d0), [477cea7fca6e](https://github.com/aurora-silicon/linux/commit/477cea7fca6eab5f5460c2c5e2459fa9cf6e1fa4), [eb1d380fc62d](https://github.com/aurora-silicon/linux/commit/eb1d380fc62d3f8febbcf3a19d173eca44e49f19), [f594e2be7f49](https://github.com/aurora-silicon/linux/commit/f594e2be7f492d0cb4fdbdf5197122418f330036) | DjDeveloperr | drm/asahi: advertise G17 queue and input-sync capabilities [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [ee8060be8a84](https://github.com/aurora-silicon/linux/commit/ee8060be8a84b43d483ac9d4f76d51f1f5a5e35c), [80c1cad754d8](https://github.com/aurora-silicon/linux/commit/80c1cad754d8711b46ece6be4d7e00c6fd27b6df), [4810fcc3be49](https://github.com/aurora-silicon/linux/commit/4810fcc3be491f1eaa0c78a183c800d08fecbc1d), [98783a0fc38d](https://github.com/aurora-silicon/linux/commit/98783a0fc38dbac9eecb4164ed6c090e3adf591d) | DjDeveloperr | drm/asahi: acquire event records after observing their producer [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/channel.rs` | C,R,H | -| [eaebe2b1f691](https://github.com/aurora-silicon/linux/commit/eaebe2b1f691e89c991bafee6013b2e0d0b5070d), [63c2157467ec](https://github.com/aurora-silicon/linux/commit/63c2157467ec2530afd39ac823a75b74c5d210c9), [7703d07ccd6d](https://github.com/aurora-silicon/linux/commit/7703d07ccd6dbb8c50cbd993a325e0d6a61cad33), [267dc9ba9ea8](https://github.com/aurora-silicon/linux/commit/267dc9ba9ea8e068a3d9d0683a58b72a51291ece) | DjDeveloperr | drm/asahi: discard partial G17 mappings when binding fails [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [7f498ba60f1a](https://github.com/aurora-silicon/linux/commit/7f498ba60f1a44401e434975d8d9433f57212539), [56d0e6d6c8b3](https://github.com/aurora-silicon/linux/commit/56d0e6d6c8b340a20cab5869ab6c516170614aa4), [bdfbf517e1fb](https://github.com/aurora-silicon/linux/commit/bdfbf517e1fb478c202e1531a8a084dc7557d4c5), [9f204371cd61](https://github.com/aurora-silicon/linux/commit/9f204371cd6118ecaa4635b76a763e6c4d53b728) | DjDeveloperr | drm/asahi: reuse the reserved output fence for submitted work [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fence.rs` | C,R,H | -| [1c200975b7c1](https://github.com/aurora-silicon/linux/commit/1c200975b7c1ccbe890e6bdeb097fb9c5d59bfac), [7c55851883a6](https://github.com/aurora-silicon/linux/commit/7c55851883a670690b2e354802b0e265c0430930), [c97c4be0ce4e](https://github.com/aurora-silicon/linux/commit/c97c4be0ce4e1a265fa915b9ec4e634a7db2c3af), [fa771fbd7629](https://github.com/aurora-silicon/linux/commit/fa771fbd7629800795268b560e9e2ff1b0cb806c) | DjDeveloperr | drm/asahi: wake render growth when its prerequisites become ready [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/events.rs` | R,H | -| [3b92fcd8c068](https://github.com/aurora-silicon/linux/commit/3b92fcd8c068445739b69393a29c7ee7de0bc5b4), [7d4176528d08](https://github.com/aurora-silicon/linux/commit/7d4176528d08bba02e84e23f43b006a7fdbda51f), [4fe42ca7a853](https://github.com/aurora-silicon/linux/commit/4fe42ca7a85341ec777ca2f19e5ed0eb8fdafa82), [956a8e2fd2dd](https://github.com/aurora-silicon/linux/commit/956a8e2fd2ddcb7e9dc596796b79f62b4e017c55) | DjDeveloperr | drm/asahi: skip frontier scans without a cross-engine prefix [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [cc1601720b58](https://github.com/aurora-silicon/linux/commit/cc1601720b58ceedb0a76606922d7a554da13e17), [63a3c2d02dac](https://github.com/aurora-silicon/linux/commit/63a3c2d02dac4acb23d299c6a00d096f04bf5520), [75ea155f8b2e](https://github.com/aurora-silicon/linux/commit/75ea155f8b2ed4da38c39179a9a653fec0eb1c37), [5026a187d811](https://github.com/aurora-silicon/linux/commit/5026a187d811c441374d11c71a3fa0df58e118fd) | DjDeveloperr | drm/asahi: track CPU feed requests through policy lifetime [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/feed.rs` | I,C,R,P | -| [848b36596112](https://github.com/aurora-silicon/linux/commit/848b36596112673711945126a51efd79d0cfa625), [547707b268e9](https://github.com/aurora-silicon/linux/commit/547707b268e96ecff8cadbc6f8b78652ab52d0ba), [a23fed471fe1](https://github.com/aurora-silicon/linux/commit/a23fed471fe1d97b7d75c738cb63d045ad434754), [c42fd8c45c3a](https://github.com/aurora-silicon/linux/commit/c42fd8c45c3a20ed2ec94c40bf5fbcf782220e7c) | DjDeveloperr | drm/asahi: bound dependency scans to the ordered command prefix [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [7a205aa6b8eb](https://github.com/aurora-silicon/linux/commit/7a205aa6b8eb17488b9882f49beece4f24b49030), [b1087fb75ab1](https://github.com/aurora-silicon/linux/commit/b1087fb75ab153f2cb017c3a08922ece0da18ca7), [b42e20b3a8d3](https://github.com/aurora-silicon/linux/commit/b42e20b3a8d3e03bdf184be067a0149ed6fbee79), [e4d41aaa9c0c](https://github.com/aurora-silicon/linux/commit/e4d41aaa9c0cdd145d5d07fe0b3d0eb209bf0879) | DjDeveloperr | drm/asahi: wait for host timestamp writes in compute prefixes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | T,C | -| [23e316ffe7e5](https://github.com/aurora-silicon/linux/commit/23e316ffe7e5a3fa108eb271778222bdc7f21ee0), [2a2aff37cd8e](https://github.com/aurora-silicon/linux/commit/2a2aff37cd8e3771dea46ebdc3e45dc7b4415b4c), [55df4049246b](https://github.com/aurora-silicon/linux/commit/55df4049246b6da9482b15411e173a11cc7f04e8), [81d324022d0f](https://github.com/aurora-silicon/linux/commit/81d324022d0f97346639b06a6abaa8b86d480ead) | DjDeveloperr | drm/asahi: release successful submission work-state ownership [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [18ef3a813070](https://github.com/aurora-silicon/linux/commit/18ef3a813070620821371e437d1557a1dd1c79cf), [cfe7880a5d16](https://github.com/aurora-silicon/linux/commit/cfe7880a5d167059b871475fbc5abe60248fcf3f), [1660e75c7e3c](https://github.com/aurora-silicon/linux/commit/1660e75c7e3ccb4b906662db275d6c5ccaebd452), [e0f7410fd5b3](https://github.com/aurora-silicon/linux/commit/e0f7410fd5b368d06ab17d802720f9d76e12880c) | DjDeveloperr | drm/asahi: preserve exact historical command prefixes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/command.rs` | C,R,H | -| [5c02e806d300](https://github.com/aurora-silicon/linux/commit/5c02e806d3004d2bb01706362298d8a6802e7433), [6507ba3ca670](https://github.com/aurora-silicon/linux/commit/6507ba3ca670d34720c6c8bfea44836b8228772b), [c7986b27e066](https://github.com/aurora-silicon/linux/commit/c7986b27e066b3d3b4fd81e95b6e174cd6c21807), [fbfb5d96f25e](https://github.com/aurora-silicon/linux/commit/fbfb5d96f25efbf2b1571ca635b195e0ad4a54be) | DjDeveloperr | drm/asahi: bring the cleanroom driver up on Neo hardware [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/buffer.rs` | C,R,H | -| [d0b66e8a8778](https://github.com/aurora-silicon/linux/commit/d0b66e8a877898097d40a380483c09e6be471532), [5fa0b934070c](https://github.com/aurora-silicon/linux/commit/5fa0b934070c615c3c745f5759d2fb7f90eaee09), [01d0b0bed7a7](https://github.com/aurora-silicon/linux/commit/01d0b0bed7a763fa775654a0a115c01f38b34584), [66af386568f7](https://github.com/aurora-silicon/linux/commit/66af386568f748d2499be3e3587ce1e7ca0ae9cd) | Ryan Murray | drm/asahi: report live GEM object accounting [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/asahi.rs` | M,D | -| [722064f1be0d](https://github.com/aurora-silicon/linux/commit/722064f1be0d171bc5d496cca352f2db6285c6c0), [f313fc4bd1a1](https://github.com/aurora-silicon/linux/commit/f313fc4bd1a1c91bad6657f7a136cc7b0f88dbe4), [2c076e0de6fe](https://github.com/aurora-silicon/linux/commit/2c076e0de6fe0a0a38a2041b02d5b9e75347375a), [f7fcc50568b9](https://github.com/aurora-silicon/linux/commit/f7fcc50568b9467f241a425b20b92ff1de10f641) | Ryan Murray | drm/asahi: port j700 queue accounting and compute recovery isolation [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — REC; `drivers/gpu/drm/asahi/g17/context.rs` | F,Q | -| [b1e288fb887d](https://github.com/aurora-silicon/linux/commit/b1e288fb887dc74d1b428d478493c6c568d3b02d), [b3b17a139f25](https://github.com/aurora-silicon/linux/commit/b3b17a139f25e8164dfdfe31d7a0c03fc2a4fa85), [2d84d7470c0f](https://github.com/aurora-silicon/linux/commit/2d84d7470c0f0d60c11c9df9e9665ee6a6a2bf71), [3c65418ee698](https://github.com/aurora-silicon/linux/commit/3c65418ee698735d33f299fe208aa8c22ff310a4) | DjDeveloperr | drm/asahi: account once per compute queue transition [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [4273fb6241bb](https://github.com/aurora-silicon/linux/commit/4273fb6241bb6f9083dd8feb263fee0924fffa94), [fa2e76747a7f](https://github.com/aurora-silicon/linux/commit/fa2e76747a7f3e264fc9c8dfaaa616627cf4e70f), [2ebb1eb92796](https://github.com/aurora-silicon/linux/commit/2ebb1eb927960a96456df1369294d3d6e392a591), [982df2dcc66e](https://github.com/aurora-silicon/linux/commit/982df2dcc66e2cb2012df476c4325c8fce016dda) | DjDeveloperr | drm: carry shared GPUVM and scheduler interfaces used by the G17 review [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/drm_gpuvm.c` | C,H,M,F | -| [c163a8df57f9](https://github.com/aurora-silicon/linux/commit/c163a8df57f986f9cb2f3c3275a1dd2b627d7dba), [751ee0b363e7](https://github.com/aurora-silicon/linux/commit/751ee0b363e7d2733cb452989b6c5fcca182f087), [84f4e1fd0eaf](https://github.com/aurora-silicon/linux/commit/84f4e1fd0eaf13c985e6535d2906b68f1c519947), [ca389fba9b6c](https://github.com/aurora-silicon/linux/commit/ca389fba9b6c7c9354c2f765fe81c5ef5f069f3b) | DjDeveloperr | drm/asahi: correct reviewed lifetime, failure and submission paths [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — RTKIT; `drivers/gpu/drm/asahi/g17/channel.rs` | B,F | -| [3a61b700f19d](https://github.com/aurora-silicon/linux/commit/3a61b700f19d1b2a63017c02359a0eb30360c496), [d297d20ba207](https://github.com/aurora-silicon/linux/commit/d297d20ba207abd5b9c4d7b80aa370dd5a379a4f), [ceb8f96ba823](https://github.com/aurora-silicon/linux/commit/ceb8f96ba8232067893d3956bcc4c335bda7e268), [d9b7b82975e2](https://github.com/aurora-silicon/linux/commit/d9b7b82975e2dad4b9a5941ade2f4debadd61c6c) | DjDeveloperr | drm/asahi: order render timestamp publication independently of GPU retirement [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [0f89327272be](https://github.com/aurora-silicon/linux/commit/0f89327272be80ecf44b643c4198614255024367), [212a7b2ccc2d](https://github.com/aurora-silicon/linux/commit/212a7b2ccc2d7a972478f4feed4c19d77cf7e01d), [3bf578fd8958](https://github.com/aurora-silicon/linux/commit/3bf578fd8958a40af5ab8b3ea892749a1dc5b4bf), [e22376a0ca67](https://github.com/aurora-silicon/linux/commit/e22376a0ca679b5359fdef009b2479616619677b) | DjDeveloperr | drm/sched: separate Rust job timeout state from submission state [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/g17/job.rs` | C,H,M,F | -| [ca7ec4ac8767](https://github.com/aurora-silicon/linux/commit/ca7ec4ac8767714b3a4c28a8bc4e3121e5a346bf), [3810bcb5e35c](https://github.com/aurora-silicon/linux/commit/3810bcb5e35cb34abd3e80d5998c94ddc747cb34), [20560fe15a23](https://github.com/aurora-silicon/linux/commit/20560fe15a23c2dd8db188a074e245c20bcf9858), [3e464649d372](https://github.com/aurora-silicon/linux/commit/3e464649d37234b0f47dfe3c22d3f73cbb6ef45b) | DjDeveloperr | drm/asahi: observe completed render work before a deferred VM failure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render/submit.rs` | R,H | -| [6a57525c17e8](https://github.com/aurora-silicon/linux/commit/6a57525c17e8cdf0fcb5965e367c8bca29f6a2f4), [7b30ae9dd4eb](https://github.com/aurora-silicon/linux/commit/7b30ae9dd4eb5a5da852deae9709ef4c10ac09c8), [d20cdd0dba5a](https://github.com/aurora-silicon/linux/commit/d20cdd0dba5a51899ea79cb8ac2df9e14cd3cd8a), [83cf9f5ad0ba](https://github.com/aurora-silicon/linux/commit/83cf9f5ad0baf71001cc0aa9c25c83f27f4a219a) | DjDeveloperr | drm/asahi: publish child page tables before linking them [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/pgtable.rs` | M,D | -| [c6754b181576](https://github.com/aurora-silicon/linux/commit/c6754b181576b5fb5467f9735e7abe4451271681), [03f169480b45](https://github.com/aurora-silicon/linux/commit/03f169480b452a052c707ddc07b36c2be478d645), [da35a7e8b950](https://github.com/aurora-silicon/linux/commit/da35a7e8b9502f0afb30feac9aa41b03b0b7d080), [b321f0e70539](https://github.com/aurora-silicon/linux/commit/b321f0e7053949d9144028d0a465a4f03eb6cc83) | DjDeveloperr | drm/asahi: retire deferred mapping cleanup without allocating [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/mmu.rs` | C,H,M,F | -| [26b6f8056c9a](https://github.com/aurora-silicon/linux/commit/26b6f8056c9a913656c75753e1d719f5771a2496), [85b9304050b9](https://github.com/aurora-silicon/linux/commit/85b9304050b9331ed8206ab69532c1bb42fe9582), [982da05e5f83](https://github.com/aurora-silicon/linux/commit/982da05e5f831a54800a778df91464ab6d6372b2), [7d57556a8962](https://github.com/aurora-silicon/linux/commit/7d57556a8962dd49aadbb24af772ee5240b8c1c1) | DjDeveloperr | drm/asahi: keep compute timestamps outside shared queue aliases [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [a244ed25307c](https://github.com/aurora-silicon/linux/commit/a244ed25307c3d03df0a57def5fffa80d19209fa), [ee1b5a0211c1](https://github.com/aurora-silicon/linux/commit/ee1b5a0211c14b5a799304948bd91fbfebaed35c), [733634bcb0c4](https://github.com/aurora-silicon/linux/commit/733634bcb0c4de6e9885878dc8b1aad744353c83), [e3cfe6674874](https://github.com/aurora-silicon/linux/commit/e3cfe66748744b6aadf6b863b57818adb0721cdd) | DjDeveloperr | drm/shmem-helper: add revocable CPU mappings and idle backing release [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/gem.rs` | C,H,M,F | -| [9afbd440e531](https://github.com/aurora-silicon/linux/commit/9afbd440e5316ca0831289cd5dec955003554737), [97bab816b9d2](https://github.com/aurora-silicon/linux/commit/97bab816b9d20dc0b7433baf2077bc2225d9e36a), [449bb6888c6f](https://github.com/aurora-silicon/linux/commit/449bb6888c6feeb79e6390cfe00dd7d4d58b6261), [e2b08ebbcadc](https://github.com/aurora-silicon/linux/commit/e2b08ebbcadc3a9ebe2733140e1a88c62af87ba1) | DjDeveloperr | drm/asahi: reclaim idle private VM backing under memory pressure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [18e1bce60e1a](https://github.com/aurora-silicon/linux/commit/18e1bce60e1a82f3872012d13fe6f5b51684eb38), [babe2ba0c5a6](https://github.com/aurora-silicon/linux/commit/babe2ba0c5a68f0d3b81085736f52f57f32cbbfe), [717d6fe9e152](https://github.com/aurora-silicon/linux/commit/717d6fe9e152af9bdda4a73a81151145cb2681ca), [e82b27902f91](https://github.com/aurora-silicon/linux/commit/e82b27902f91d8c833395a966366d0ffc30769c3) | DjDeveloperr | drm/asahi: free a closed context's render pool once its release is consumed [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,C,R | -| [177e22791d7c](https://github.com/aurora-silicon/linux/commit/177e22791d7cfecb3b6c6b6315adf674ef1c9b30), [431b18cf9072](https://github.com/aurora-silicon/linux/commit/431b18cf9072a8618cbab77cfcbde3952cdb5623), [20a55bacd2fb](https://github.com/aurora-silicon/linux/commit/20a55bacd2fb91e52b6bb5cbb3e88e5218b2f726), [fa210660c43c](https://github.com/aurora-silicon/linux/commit/fa210660c43c1e8ffc4c0705792febb70c29e779) | DjDeveloperr | drm/asahi: hold idle descent for every first render pair install [#171](https://github.com/aurora-silicon/linux/pull/171) | Gated — MMIO; `drivers/gpu/drm/asahi/g17/runtime/render.rs` | B,I | -| [06175c4cc1bc](https://github.com/aurora-silicon/linux/commit/06175c4cc1bccd44765a75a70278fedb27ed9fe5), [2f10cc462301](https://github.com/aurora-silicon/linux/commit/2f10cc462301b9d1a1e64bd31468268d90a5d96d), [e94491e80ac1](https://github.com/aurora-silicon/linux/commit/e94491e80ac12de2fb9b741739b560ab17ecbb34), [d7715ebbd2d3](https://github.com/aurora-silicon/linux/commit/d7715ebbd2d3397958f08442d096a2476d32cb6a) | DjDeveloperr | drm/asahi: add GEM_MADVISE and purge advised objects under memory pressure [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/asahi/driver.rs` | C,H,M,F | -| [f338bb052975](https://github.com/aurora-silicon/linux/commit/f338bb05297509f7b87714c5727fb99a8fea373a), [c2e8f1ce84f1](https://github.com/aurora-silicon/linux/commit/c2e8f1ce84f1f72a14e6395fa5246a133211432c), [85271d321506](https://github.com/aurora-silicon/linux/commit/85271d321506ec35cc7e6a82665649e7fd2e4f8c), [c8c442ae6a83](https://github.com/aurora-silicon/linux/commit/c8c442ae6a83502a90fca56d1b8e08e669ce03cb) | DjDeveloperr | drm/asahi: drop the sysfs object and queue-slot counters [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,D | -| [3bb318ea84a1](https://github.com/aurora-silicon/linux/commit/3bb318ea84a1cd2d7661948b347270c8eaf71931), [8b1bcc708f82](https://github.com/aurora-silicon/linux/commit/8b1bcc708f820baa04c2998acf8513a0146d59cf), [ed235501b653](https://github.com/aurora-silicon/linux/commit/ed235501b6531eb218d3b058bab11a807ae17713), [152092e32a7f](https://github.com/aurora-silicon/linux/commit/152092e32a7fd7a7b3a96b8e45be7db78934b7d8) | DjDeveloperr | drm/asahi: drop the stalled scheduler-release warning [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/teardown.rs` | C,R,H | -| [110dd19ab7e0](https://github.com/aurora-silicon/linux/commit/110dd19ab7e0263538c8301f903471b1700eac12), [815912e331c3](https://github.com/aurora-silicon/linux/commit/815912e331c32ab6468a108ab34c6b26d60faecb), [9d8357e27590](https://github.com/aurora-silicon/linux/commit/9d8357e275907651adbb7022b812f789ece7d040), [24ce1bcdd8eb](https://github.com/aurora-silicon/linux/commit/24ce1bcdd8ebf0f8664c043a639c0201286f94e5) | DjDeveloperr | drm/asahi: build constant firmware objects from word tables [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [b5a72b8cb8a5](https://github.com/aurora-silicon/linux/commit/b5a72b8cb8a581d84a4c35c2b4ecc11cd50fabfb), [cea457b72a30](https://github.com/aurora-silicon/linux/commit/cea457b72a308addcffbef0555408e3c2f021c7b), [8e98d0432927](https://github.com/aurora-silicon/linux/commit/8e98d0432927d780061fcc55516769f3d830291f), [7e317cd1218e](https://github.com/aurora-silicon/linux/commit/7e317cd1218e5461124fbfc8db7dd72e71253f8e) | DjDeveloperr | drm/asahi: grow the scheduler-release table instead of failing a close [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/teardown.rs` | C,R,H | -| [8afbe186d27a](https://github.com/aurora-silicon/linux/commit/8afbe186d27aab81bc71008838387799f1d9d4df), [c4f9aff1f720](https://github.com/aurora-silicon/linux/commit/c4f9aff1f720075ed3b059e6d82a5d8be5663768), [be6a3b5d938f](https://github.com/aurora-silicon/linux/commit/be6a3b5d938f2c51ef5b6d60990dcefd64cb677f), [18dbc2de6f21](https://github.com/aurora-silicon/linux/commit/18dbc2de6f21c92c49ffafce39a38c8d6439a5b5) | DjDeveloperr | drm/asahi: add a render flag for passes with at most four known primitives [#171](https://github.com/aurora-silicon/linux/pull/171) | Gated — FEW; `drivers/gpu/drm/asahi/g17/command.rs` | R | -| [7d34f2f65865](https://github.com/aurora-silicon/linux/commit/7d34f2f658658c1fd829700f2e14211a1b150ccd), [b1ec7881bf69](https://github.com/aurora-silicon/linux/commit/b1ec7881bf69ab6b1678761dec5552b28aa414e1), [3318d3e23f8e](https://github.com/aurora-silicon/linux/commit/3318d3e23f8e49a5721f9e2da0eea674eece1d2e), [c00f3a06ed2d](https://github.com/aurora-silicon/linux/commit/c00f3a06ed2d0400a5ec210c856f3a382971f033) | DjDeveloperr | drm/asahi: add a render flag that orders only the fragment stage on barriers [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/command.rs` | R,H | -| [e2b1485ec599](https://github.com/aurora-silicon/linux/commit/e2b1485ec599011654ac1f6ccc4dc78350b50566), [763771c2f3d0](https://github.com/aurora-silicon/linux/commit/763771c2f3d0613ecacaeb20d1cfd21809ead7d5), [0751d1c543c9](https://github.com/aurora-silicon/linux/commit/0751d1c543c933f65ec2ce2606d5effd25206721), [64820e0cb952](https://github.com/aurora-silicon/linux/commit/64820e0cb952592fff5708712a4b4766a8a12f4c) | DjDeveloperr | drm/asahi: give back the USC backing of idle retained compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/freelist.rs` | I,C,R,P | -| [6825b2e8b6f7](https://github.com/aurora-silicon/linux/commit/6825b2e8b6f7d51be5f21a46821541ae8828c6e5), [9e693050e446](https://github.com/aurora-silicon/linux/commit/9e693050e44633bcf0503ec5b864a292d513b563), [ffbf4b465de9](https://github.com/aurora-silicon/linux/commit/ffbf4b465de966c4a5bf3b2e2881fd5678f98bfa), [3db48c0ac600](https://github.com/aurora-silicon/linux/commit/3db48c0ac600b5e919c4d2713dbd84e9b12b4ec4) | DjDeveloperr | drm/asahi: drop an exited owner's context from idle retained compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/context.rs` | I,C,R,P | -| [dbea31c253f3](https://github.com/aurora-silicon/linux/commit/dbea31c253f3d1845a4998abed2db88177e82d54), [e85d3c35771a](https://github.com/aurora-silicon/linux/commit/e85d3c35771a27fc3721f13d572c2538e898837f), [9964d01e50ad](https://github.com/aurora-silicon/linux/commit/9964d01e50add98a41985adc69ace3bc5dc867f1), [5427403e7135](https://github.com/aurora-silicon/linux/commit/5427403e7135dd886ee52a78d73639bd5a2ccb17) | DjDeveloperr | drm/asahi: keep reclaim away from VMs that are in use or were just restored [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/lifetime.rs` | M,D | -| [34de15489113](https://github.com/aurora-silicon/linux/commit/34de15489113f71dd93695681d735afaddef10db), [c5fdbf93b7c8](https://github.com/aurora-silicon/linux/commit/c5fdbf93b7c8280dd1d266df8b4298b6b5c0645c), [5eb07ab2539b](https://github.com/aurora-silicon/linux/commit/5eb07ab2539bf7628366644c96a4742c934b9a78), [1c62cd0853b6](https://github.com/aurora-silicon/linux/commit/1c62cd0853b670104424bcfddeee7f7d9279304e) | DjDeveloperr | drm/asahi: count bindings and VM creation as reclaim activity [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/lifetime.rs` | M,D | -| [9bca711b6542](https://github.com/aurora-silicon/linux/commit/9bca711b65427b7dc0c384e6de2a783cde6e0160), [84e172f23883](https://github.com/aurora-silicon/linux/commit/84e172f23883c27a8eb0cdc85fa81de9c8879eb1), [3202a8b8912f](https://github.com/aurora-silicon/linux/commit/3202a8b8912f39ff7b7c06acc5fd604d5d0c4769), [dec3bc9eb622](https://github.com/aurora-silicon/linux/commit/dec3bc9eb622df05eca30716834c35506ee31f9f) | DjDeveloperr | drm/asahi: set the idle-VM reclaim quiet window to 2000 ms [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu/residency.rs` | M,D | -| [f1018934472b](https://github.com/aurora-silicon/linux/commit/f1018934472b655ba44f1fcbfa2f3be2fdedb1fd), [d2046dcecf61](https://github.com/aurora-silicon/linux/commit/d2046dcecf61aceec6af3d013da811e147e3c410), [4963fa334b24](https://github.com/aurora-silicon/linux/commit/4963fa334b2439a0fc831ee3a5a8db008712a307), [1c1abce16316](https://github.com/aurora-silicon/linux/commit/1c1abce16316282e15f5e471b8ef0b5a33acc038) | DjDeveloperr | drm/asahi: release the VM status mirror object when the VM handle closes [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/status.rs` | M,D | -| [cc0e08ecbe61](https://github.com/aurora-silicon/linux/commit/cc0e08ecbe61eae09d5be1619a0e6373888f7d02), [503bc0e39d66](https://github.com/aurora-silicon/linux/commit/503bc0e39d665ac97ac53e0b78b2851ca61d2242), [8057982690f1](https://github.com/aurora-silicon/linux/commit/8057982690f1f1954a83f62382873a8baf03bb8e), [6af79e6e57ef](https://github.com/aurora-silicon/linux/commit/6af79e6e57ef80d2b93d4c428956ec6cdfb11a3a) | DjDeveloperr | drm/asahi: unmap detached compute owners and free vacated pools off-lock [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,C,R | -| [90e691e8fe49](https://github.com/aurora-silicon/linux/commit/90e691e8fe49fa13756b6a64d22074c6e4e4a6cb), [b00ba3dcbfeb](https://github.com/aurora-silicon/linux/commit/b00ba3dcbfebf63d761a8018109bef6067a2cf8b), [6f6bef1b9fd7](https://github.com/aurora-silicon/linux/commit/6f6bef1b9fd7c46f0885eea0ece01a811e08c7d1), [0b4bd1537cc7](https://github.com/aurora-silicon/linux/commit/0b4bd1537cc71a1796b976c05cdab24e76549303) | DjDeveloperr | drm/asahi: retire a compute command on its record when its stamp never follows [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [f227c7671c0f](https://github.com/aurora-silicon/linux/commit/f227c7671c0fa54ab73b1477aaf6bbc482e29b8b), [2ceb94e6a1a7](https://github.com/aurora-silicon/linux/commit/2ceb94e6a1a7939d520401fcbb0f41ce5ce9f47a), [e978503f0047](https://github.com/aurora-silicon/linux/commit/e978503f00475864733aefc433d758f0254f401f), [f647d69cc504](https://github.com/aurora-silicon/linux/commit/f647d69cc5043bf1d3389c8e250e78935e5afa24) | DjDeveloperr | drm/asahi: log the first GPU work failure reported to each G17 VM [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — OBS; `drivers/gpu/drm/asahi/g17/status.rs` | O,F | -| [0685cf3905b7](https://github.com/aurora-silicon/linux/commit/0685cf3905b73081560c7c1adc28f76efda774fa), [e8e17790b150](https://github.com/aurora-silicon/linux/commit/e8e17790b150da70debb5e9a1c31027883ad90d3), [85ab080b193f](https://github.com/aurora-silicon/linux/commit/85ab080b193fa481276ebcb9393a93b25024384f), [c8ea00a9ed62](https://github.com/aurora-silicon/linux/commit/c8ea00a9ed621e2e5c7c84461091fda3a9b7cb7b) | DjDeveloperr | drm/asahi: name the completion path in the first-failure log line [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — OBS; `drivers/gpu/drm/asahi/g17/completion.rs` | O,F | -| [ef4fa278cd1a](https://github.com/aurora-silicon/linux/commit/ef4fa278cd1abc81d229ec5853175c35537a962c), [bbbbb8aba0a3](https://github.com/aurora-silicon/linux/commit/bbbbb8aba0a3a08da0b31f31dd0fa1655089c2b0), [ec743d4d34f8](https://github.com/aurora-silicon/linux/commit/ec743d4d34f89fa2ea639801062c957f807c54aa), [5d2a444327af](https://github.com/aurora-silicon/linux/commit/5d2a444327afc38543beb78a252e23661e4d4ecc) | DjDeveloperr | drm/asahi: use one monotonic clock helper across the G17 runtime [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [860e86da2994](https://github.com/aurora-silicon/linux/commit/860e86da2994a4584ba5ce013c5ef5d79cbda111), [bca35f80a993](https://github.com/aurora-silicon/linux/commit/bca35f80a99330132651e21c61f4d0e5da583cd9), [388a083cca9a](https://github.com/aurora-silicon/linux/commit/388a083cca9a1ff7b98f14dc0e598a63494e7d89), [6850c91310a9](https://github.com/aurora-silicon/linux/commit/6850c91310a913b5ff9646261250e62b129f4ce8) | DjDeveloperr | drm/asahi: grow the scheduler-release table silently [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/teardown.rs` | C,R,H | -| [3cd28842a502](https://github.com/aurora-silicon/linux/commit/3cd28842a502864d73cbfeb7018d6f6e2e00dcdc), [033ec9a3b717](https://github.com/aurora-silicon/linux/commit/033ec9a3b71756814007305dfaf437f3e26c1195), [0c8194353943](https://github.com/aurora-silicon/linux/commit/0c8194353943469158f8651c5ec51723e130afa3), [e60f49eede0e](https://github.com/aurora-silicon/linux/commit/e60f49eede0ecf38cb206c4f59ff832b2aacc1d6) | DjDeveloperr | drm/asahi: give back the descriptor ring of vacated compute queues [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [5a98c966960a](https://github.com/aurora-silicon/linux/commit/5a98c966960a4310f741538fea1fc04724acffdb), [c9c1859181ab](https://github.com/aurora-silicon/linux/commit/c9c1859181ab17b15b76c74dc36ef00ad7cac96e), [75535b36cc0e](https://github.com/aurora-silicon/linux/commit/75535b36cc0ea75d394b20e11b993bf22e1efe20), [5d630414e13f](https://github.com/aurora-silicon/linux/commit/5d630414e13f4e017628430820fff73a86e97de9) | DjDeveloperr | drm/asahi: return killed compute queues to service with fresh backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [6cae1d77a10a](https://github.com/aurora-silicon/linux/commit/6cae1d77a10aee3e2cd7f52c92eb62b957f6e7ff), [b138b1c78a0e](https://github.com/aurora-silicon/linux/commit/b138b1c78a0ebbba6cef6b3976fc39bfd8b1e3d4), [4457298833f1](https://github.com/aurora-silicon/linux/commit/4457298833f1001a90c15d9277dee87ad6e11927), [16822976f9d3](https://github.com/aurora-silicon/linux/commit/16822976f9d375ddbdc788d968077a15660be5d7) | DjDeveloperr | drm/asahi: give back the render pool backing of evicted idle clients [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/g17/context.rs` | M,D | -| [8d77b4f20652](https://github.com/aurora-silicon/linux/commit/8d77b4f20652f18c7fb4e6ae9184eb88ab7e779e), [39c1fc51692c](https://github.com/aurora-silicon/linux/commit/39c1fc51692c3bfcb37c274ce84dfe812bceaaae), [7e8fe19766fd](https://github.com/aurora-silicon/linux/commit/7e8fe19766fd1b895120a8e7bd5fe78f7aca2a7c), [bff3853f260b](https://github.com/aurora-silicon/linux/commit/bff3853f260b02bdd9605bc6690905cb70aca29f) | DjDeveloperr | drm/asahi: carry a scheduling profile from DRM queue priority to firmware [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — PRIORITY; `drivers/gpu/drm/asahi/g17/context.rs` | Q | -| [a15128aa41ec](https://github.com/aurora-silicon/linux/commit/a15128aa41ecb760c5669ec03d8ffee55213bd6c), [87744d8c30b2](https://github.com/aurora-silicon/linux/commit/87744d8c30b28d86a4cc2c45b2e5009b730ed6b4), [fe676c6f4915](https://github.com/aurora-silicon/linux/commit/fe676c6f4915ec15bb3ea0880101eb5b29cfc255), [009b0fb93ba3](https://github.com/aurora-silicon/linux/commit/009b0fb93ba35380563055aa8bc725f36c505262) | DjDeveloperr | drm/asahi: drop two defensive clippy allowances in the VM binding paths [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [1567322c2517](https://github.com/aurora-silicon/linux/commit/1567322c251710c365592380a195ceb22979d781), [408df60b8f35](https://github.com/aurora-silicon/linux/commit/408df60b8f35a1f510750df51f5e46bfb51d51a4), [3d1be9ce9669](https://github.com/aurora-silicon/linux/commit/3d1be9ce966988190d72dcad1d0fa4dd1b9204c9), [410d8f80e9ab](https://github.com/aurora-silicon/linux/commit/410d8f80e9ab6b405d7f918901fcbe883bb2d9b2) | DjDeveloperr | drm/asahi: build the G17 boot objects region by region [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/initdata.rs` | C,R,H | -| [0e3bd3afd897](https://github.com/aurora-silicon/linux/commit/0e3bd3afd897637d7c42d54c8ca9adc25e5a691c), [2fa38fc95677](https://github.com/aurora-silicon/linux/commit/2fa38fc956777c4e357d44db60d1b7aafaac273f), [456e6601e69d](https://github.com/aurora-silicon/linux/commit/456e6601e69d15067bcccde93498fd58e22977a1), [f5bd61786e3b](https://github.com/aurora-silicon/linux/commit/f5bd61786e3b537fd811f0ea27d2ec33874232b0) | DjDeveloperr | drm/asahi: split the G17 render pair install paths out of build_render_pair [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs` | R,H | -| [fe926de1f191](https://github.com/aurora-silicon/linux/commit/fe926de1f191b798b49cbe57e36dfba0e0cc4ac7), [e89e97a5241c](https://github.com/aurora-silicon/linux/commit/e89e97a5241cd22b95cb60304f1e2426698c45af), [ef1251b62428](https://github.com/aurora-silicon/linux/commit/ef1251b62428a647c7ed4311cc6223ca1c8fc80a), [e0fa28b70ca9](https://github.com/aurora-silicon/linux/commit/e0fa28b70ca92d7942809827a7cff7e230d68826) | DjDeveloperr | drm/asahi: split the G17 render publication into preflight, barriers and announce [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [311b9ea8bf83](https://github.com/aurora-silicon/linux/commit/311b9ea8bf835bc7a53866f34b8520ffdc17ef01), [1235a9ee13fe](https://github.com/aurora-silicon/linux/commit/1235a9ee13fe9ed0bf846970e5f5cf9a3049e290), [f76a38f8511f](https://github.com/aurora-silicon/linux/commit/f76a38f8511fd9df3d53e30b899a780c17353d28), [74bc2f09ab74](https://github.com/aurora-silicon/linux/commit/74bc2f09ab74832be661557cacf374ee5fff11d7) | DjDeveloperr | drm/asahi: split the G17 compute publication preflight and queue configuration [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [f22f4cfb5b97](https://github.com/aurora-silicon/linux/commit/f22f4cfb5b97b17cf49e7ca9feb877313156f246), [74e91a7f9ad5](https://github.com/aurora-silicon/linux/commit/74e91a7f9ad5d2f61bd5846713e27838c6f5324a), [49e9337b68a4](https://github.com/aurora-silicon/linux/commit/49e9337b68a41b5f9a3a26d8d72e8b0eecc16844), [5ad7b191f7e6](https://github.com/aurora-silicon/linux/commit/5ad7b191f7e698e3ef140163c6ecf15d3e57ff85) | DjDeveloperr | drm/asahi: size the compute descriptor ring to the kicks that can be in flight [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | M,C,R | -| [bb5149df6a74](https://github.com/aurora-silicon/linux/commit/bb5149df6a74ead7da49be6953c63f4033229ff3), [9d92af630ad2](https://github.com/aurora-silicon/linux/commit/9d92af630ad2f55fe898d653e29c363c131ee4e3), [6d54c0fd885c](https://github.com/aurora-silicon/linux/commit/6d54c0fd885ceded70867de874f27987fc8f69b4), [5f6490414a68](https://github.com/aurora-silicon/linux/commit/5f6490414a683eef149ba6de38cbc27ba62f9a26) | DjDeveloperr | drm/asahi: pack G17 tiler heap blocks contiguously in their backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/buffer.rs` | M,C,R | -| [46c70ecebde4](https://github.com/aurora-silicon/linux/commit/46c70ecebde4be2fbd3e82e8311946a156504bf1), [f024202d33e8](https://github.com/aurora-silicon/linux/commit/f024202d33e8832b01e0cff6006fbb9e2b1178a3), [29ff1f70b488](https://github.com/aurora-silicon/linux/commit/29ff1f70b4880e79a8b980adc4d44d4eacb7c7e1), [d2a2c2fa97b9](https://github.com/aurora-silicon/linux/commit/d2a2c2fa97b994595209843720ad78b99b93f16a) | DjDeveloperr | drm/asahi: allocate only the G17 boot pool blocks that are used [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — GMEM; `drivers/gpu/drm/asahi/g17/initdata.rs` | M,C,R | -| [56b8769a1364](https://github.com/aurora-silicon/linux/commit/56b8769a1364bc6c46ab48463afa203a5aec92bb), [614f11f2eb30](https://github.com/aurora-silicon/linux/commit/614f11f2eb30471e02d42f7eab08e9bf4ec4cd41), [c304acb009f0](https://github.com/aurora-silicon/linux/commit/c304acb009f0264d1485596f651495d66efb0fec), [272955b009fe](https://github.com/aurora-silicon/linux/commit/272955b009fe844d4d06361365f166d75b6b451b) | DjDeveloperr | drm/asahi: give back idle G17 tiler heap growth beyond recent use [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — POWER; `drivers/gpu/drm/asahi/g17/buffer.rs` | I,C,R,P | -| [3434c1aab8a6](https://github.com/aurora-silicon/linux/commit/3434c1aab8a6c5d305198347040b8237c4bdce06), [35fe32db0e80](https://github.com/aurora-silicon/linux/commit/35fe32db0e806643f201fc6871095da0e68cfaf8), [1464c4bb1ade](https://github.com/aurora-silicon/linux/commit/1464c4bb1ade2f3fe0625eb93776b26a7f91db96), [c01af7a9e73c](https://github.com/aurora-silicon/linux/commit/c01af7a9e73c789c6a9f98547585a7048927af30) | DjDeveloperr | drm/asahi: give back warm G17 compute pools after ten idle seconds | Active — POWER; `drivers/gpu/drm/asahi/g17/runtime.rs` | I,C,R,P | -| [43a409830c67](https://github.com/aurora-silicon/linux/commit/43a409830c673f190213d2643d50f7500bbf69ab), [882abd400823](https://github.com/aurora-silicon/linux/commit/882abd400823eedce71e3def3c17a3143cd7318b), [57e6637d9f08](https://github.com/aurora-silicon/linux/commit/57e6637d9f087775ee87dcab22dd6c4bb0d4f685), [2d7de7690cc0](https://github.com/aurora-silicon/linux/commit/2d7de7690cc0f9c8d3a74b08c33999593b720aac) | DjDeveloperr | drm/asahi: keep compaction away from GEM pages held for the GPU | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [dd109eec40ac](https://github.com/aurora-silicon/linux/commit/dd109eec40ace8e09c436eed1997e302e2b26842), [8bc791526797](https://github.com/aurora-silicon/linux/commit/8bc791526797872caece1891ed792e69dce48438), [76b1755a0610](https://github.com/aurora-silicon/linux/commit/76b1755a06109a66416af0282ec8310dc8a3292b), [6dd0f73fd3b2](https://github.com/aurora-silicon/linux/commit/6dd0f73fd3b2bade5415b31346aadeb2f38d446e) | DjDeveloperr | drm/asahi: complete page-table stores before GPU TLB invalidation | Active — MEM; `drivers/gpu/drm/asahi/g17/kick.rs` | M,D | -| [bec1201676a6](https://github.com/aurora-silicon/linux/commit/bec1201676a6f3b073e8d93791d8c9c7e6c99d7f), [36b80077e7c4](https://github.com/aurora-silicon/linux/commit/36b80077e7c45c57469f9d8cd6ba3e0aa6007cd6), [91e15ed8e7a6](https://github.com/aurora-silicon/linux/commit/91e15ed8e7a681ca293f94e337f59563cd03879d), [019ad857ddfa](https://github.com/aurora-silicon/linux/commit/019ad857ddfa08ed2473eae34db5b8b8d98b068e) | DjDeveloperr | drm/asahi: remove tiler-shrink diagnostic logging | Active — OBS; `drivers/gpu/drm/asahi/g17/buffer.rs` | O,F | -| [692752fb7bf6](https://github.com/aurora-silicon/linux/commit/692752fb7bf60c9e5f83e80dba56779fa48961c1), [3f6a8c31626f](https://github.com/aurora-silicon/linux/commit/3f6a8c31626fc077dbfcea147cd6e30cb28c5e70), [27178c4e373a](https://github.com/aurora-silicon/linux/commit/27178c4e373a23ba1015647f774a3102265c1b27), [d128b5e48465](https://github.com/aurora-silicon/linux/commit/d128b5e484658066c82504df550f6f13abcbd1cc) | DjDeveloperr | drm/asahi: reuse the render state mapping for auxiliary framebuffers | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/memory.rs` | R,H | -| [a2e5af9f5f03](https://github.com/aurora-silicon/linux/commit/a2e5af9f5f0334dbcdd069cc2944f11313f5d67c), [54101717e1de](https://github.com/aurora-silicon/linux/commit/54101717e1dee1b6fd64f32ae8888ec8429b821e), [c0e47197c71c](https://github.com/aurora-silicon/linux/commit/c0e47197c71c80b57974130a06386e101bbdc7ee) | Ryan Murray | drm/asahi: allocate imported and dumb GEM objects as asahi objects | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [c29c639e0934](https://github.com/aurora-silicon/linux/commit/c29c639e09349ce24a2bf768c33476e2e27b2512), [c3a21491589b](https://github.com/aurora-silicon/linux/commit/c3a21491589bb62b2279867805b8e87fd2629e4d), [f2760d2f42ec](https://github.com/aurora-silicon/linux/commit/f2760d2f42ec4ede63abb18918ef4abeb4b3de35) | Dj | drm/asahi: preserve TA prefix dependencies across render pairs | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render.rs` | R,H | -| [7598420667b6](https://github.com/aurora-silicon/linux/commit/7598420667b6be8788d768316e4218ff3c3fc1ff), [d2f283ac0589](https://github.com/aurora-silicon/linux/commit/d2f283ac058952ea84da562a7f6e6a911ebf879a), [1af8de012d22](https://github.com/aurora-silicon/linux/commit/1af8de012d2221144395f900729619b5065b14fd) | Dj | drm/asahi: provision G17P ray traversal pools from Gen1 SCS demand | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [e864801fe49c](https://github.com/aurora-silicon/linux/commit/e864801fe49c9dc6d1fd6e4d1b6c2a607e672f71), [a075a1fab446](https://github.com/aurora-silicon/linux/commit/a075a1fab446a49270d387274f7793d3e9ee6560), [6ffb2dc7a658](https://github.com/aurora-silicon/linux/commit/6ffb2dc7a658e2e6bcaf48a75461b8d7e84549bf) | DjDeveloperr | drm/asahi: recycle settled quarantined G17 compute queues [#305](https://github.com/aurora-silicon/linux/pull/305) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [ae76590d6ea0](https://github.com/aurora-silicon/linux/commit/ae76590d6ea0313a4741fdce5025f6c336eaf90c), [b9fd334a9c96](https://github.com/aurora-silicon/linux/commit/b9fd334a9c96f58640e0ef6ce2010749b85e7c4f), [8ad79fc25869](https://github.com/aurora-silicon/linux/commit/8ad79fc25869a9a5cd36262cc8a702b4327cf437) | DjDeveloperr | drm/asahi: g17: replay render groups firmware retired without executing [#307](https://github.com/aurora-silicon/linux/pull/307) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [41786756b43d](https://github.com/aurora-silicon/linux/commit/41786756b43da732fa85c6ac3e23a33e3baa9335), [0a2cdd456013](https://github.com/aurora-silicon/linux/commit/0a2cdd456013347efd1bc2a73d79e291d2d77fbc), [167852510065](https://github.com/aurora-silicon/linux/commit/1678525100652694b0aaee977ea2012b487d6a51) | DjDeveloperr | drm/asahi: g17: never kill compute commands with ray traversal scratch [#308](https://github.com/aurora-silicon/linux/pull/308) | Gated — RT; `drivers/gpu/drm/asahi/g17/queue/compute/exit.rs` | F | -| [d3f4f5dd1b59](https://github.com/aurora-silicon/linux/commit/d3f4f5dd1b592ba925f469133ebac876a101ddb7), [ec3aa2ff51b8](https://github.com/aurora-silicon/linux/commit/ec3aa2ff51b8ad6f9f39c70bf563866ee81baecb), [48b2631fdaab](https://github.com/aurora-silicon/linux/commit/48b2631fdaab66dc7bd850b3006c0f85a73aba0e) | DjDeveloperr | drm/asahi: g17: ray queries in render stages [#309](https://github.com/aurora-silicon/linux/pull/309) | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [079f81d5a637](https://github.com/aurora-silicon/linux/commit/079f81d5a637e459a33e8f75a97b91f2454f1499), [2d1fcbe1a980](https://github.com/aurora-silicon/linux/commit/2d1fcbe1a9808f52f2427e4c1237b2b0eba7b7fb), [03426fb46c9c](https://github.com/aurora-silicon/linux/commit/03426fb46c9ce29e5b58db52cfefd09fac156fea) | Ryan Murray | soc: apple: mailbox, rtkit: Allow holding received messages | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [a98bb5de4b2e](https://github.com/aurora-silicon/linux/commit/a98bb5de4b2e6dd5d54150008bd322f97c8dbd0d), [c623f821fdfa](https://github.com/aurora-silicon/linux/commit/c623f821fdfaada5df34d2a79fcc4586b0d7323b), [23b2b6f4a1c9](https://github.com/aurora-silicon/linux/commit/23b2b6f4a1c93dbc90768e271c92bc914e5d676f) | Ryan Murray | soc: apple: pmp: log tunables the boot loader does not provide at debug level [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [689592f3219f](https://github.com/aurora-silicon/linux/commit/689592f3219f4733c038cdf72e5a911084d22521), [bc1d13129d6d](https://github.com/aurora-silicon/linux/commit/bc1d13129d6d88ee93515eb547967d87170e5da3), [f80758084279](https://github.com/aurora-silicon/linux/commit/f80758084279064eb1c60e6bfa56f7649bb86a4d) | Ryan Murray | iommu: apple-dart: Demote informational probe messages to debug [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e28469b8a38e](https://github.com/aurora-silicon/linux/commit/e28469b8a38e4102fd5c5b877bf51439fc00fca3), [00baae48e464](https://github.com/aurora-silicon/linux/commit/00baae48e464c44cb754d52552d3bd1f431d52f7) | Ryan Murray | iommu: apple-dart: Invalidate every stream in a domain bitmap | Active — DART; `drivers/iommu/Kconfig` | D,B | -| [aade7be0a12a](https://github.com/aurora-silicon/linux/commit/aade7be0a12a38ae8bb276fac80df27eaea97e32), [b13ede3059b0](https://github.com/aurora-silicon/linux/commit/b13ede3059b0bc51bca6033e405606e525ec2259), [4cf2113dc363](https://github.com/aurora-silicon/linux/commit/4cf2113dc36329544edc54b09dc775c5888c3975) | Ryan Murray | soc: apple: mcc: factor out disabling and flushing planes [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [ef010a009b3f](https://github.com/aurora-silicon/linux/commit/ef010a009b3ffb15af9794ed37083d1ad2c4facb), [0cba4dd60674](https://github.com/aurora-silicon/linux/commit/0cba4dd60674aa9ded2c27eaae1ff7bf4f1e243e), [8bf158a74ea7](https://github.com/aurora-silicon/linux/commit/8bf158a74ea7e2a5a7e42082fc882d3508119a09) | Ryan Murray | soc: apple: mcc: disable the planes already enabled when enabling fails [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [a099186592d6](https://github.com/aurora-silicon/linux/commit/a099186592d6aa010ab7da6d71c7c88d1801345d), [e46e30ff7457](https://github.com/aurora-silicon/linux/commit/e46e30ff7457d01b6e9cb97e8d7a5b0fd8fe20e6), [4653ef5a873f](https://github.com/aurora-silicon/linux/commit/4653ef5a873f16c68a1e9e9080a41395628ca9d4) | Ryan Murray | pmdomain: apple: pmc: undo a partial agent enable [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMC; `drivers/pmdomain/apple/pmc.c` | P,C,R | -| [49bb592b9e9f](https://github.com/aurora-silicon/linux/commit/49bb592b9e9f626d06af3296172be8d3aa99a320), [43f4894e7c18](https://github.com/aurora-silicon/linux/commit/43f4894e7c18a46f5e379dd994f0fbd5def67ed7), [a86e8e5637c0](https://github.com/aurora-silicon/linux/commit/a86e8e5637c07504ca09b7bfa5639492af065d8c) | Ryan Murray | pmdomain: apple: pmc: restore the AP's own DCS vote when a limit is lifted [#317](https://github.com/aurora-silicon/linux/pull/317) | Gated — DCS; `drivers/pmdomain/apple/Kconfig` | P | -| [75984fc70c8f](https://github.com/aurora-silicon/linux/commit/75984fc70c8f252d96910dad4cd8635f4977b74f), [6351fe2e5e29](https://github.com/aurora-silicon/linux/commit/6351fe2e5e29f4447d997214d785f10885ef7538), [dba445e67326](https://github.com/aurora-silicon/linux/commit/dba445e6732685313e036e73dc2753c7ed8cbcb6) | Ryan Murray | soc: apple: clpc: remove the debugfs override of the floor [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [9e4e936ed101](https://github.com/aurora-silicon/linux/commit/9e4e936ed10105188f37f3f8b2c27042e2e2ec58), [c47472a2343b](https://github.com/aurora-silicon/linux/commit/c47472a2343b6c35235e48db178cf76ae94c1f73), [9dfd51203aa8](https://github.com/aurora-silicon/linux/commit/9dfd51203aa80ce8867d98ba03c79fbb283039c2) | Ryan Murray | soc: apple: clpc: make the demand policy per-SoC data, drop the GPU input [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [64290b216821](https://github.com/aurora-silicon/linux/commit/64290b21682151a3eb4c93d5f666d07f56aae87c), [d19ce09e3508](https://github.com/aurora-silicon/linux/commit/d19ce09e35089ec81bcc82f55198498901df10ac), [10e182579152](https://github.com/aurora-silicon/linux/commit/10e1825791523747c5f0d4ac44570fe4418ff586) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: log always-on domains left off at info level [#317](https://github.com/aurora-silicon/linux/pull/317) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [57dafd4b412f](https://github.com/aurora-silicon/linux/commit/57dafd4b412f8b49be5362a98503be11138cd388), [f86db4089cee](https://github.com/aurora-silicon/linux/commit/f86db4089cee44d2f54de73f60aa32c8a07ffd3a), [1ef9c2113ecd](https://github.com/aurora-silicon/linux/commit/1ef9c2113ecdf2851908e4bd9793876d92152d27) | Ryan Murray | soc: apple: rtkit: Do not warn when buffers are retained on purpose [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [5ebe92d17a32](https://github.com/aurora-silicon/linux/commit/5ebe92d17a32112b13e74553bab5b0e0b7c0e147), [7b29e7caccc4](https://github.com/aurora-silicon/linux/commit/7b29e7caccc4896949b0dff4dd8caf7c5fa3f0c0), [9779b2457e8f](https://github.com/aurora-silicon/linux/commit/9779b2457e8f13b0f257964570c9883f079e65f6) | Ryan Murray | pmdomain: apple: pmc: keep the DCS limit state when the rail enable fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Gated — DCS; `drivers/pmdomain/apple/pmc.c` | P | -| [962dacdbb6ad](https://github.com/aurora-silicon/linux/commit/962dacdbb6ad38d9fc723d9f8ea3b3d8dee0e6a9), [4209657d7d94](https://github.com/aurora-silicon/linux/commit/4209657d7d948671c9872e1cbb53f66774793607), [1c797d3eb5cb](https://github.com/aurora-silicon/linux/commit/1c797d3eb5cb79f7e80696b4d7c93800172771c0) | Ryan Murray | cpufreq: apple-soc: say why a cluster with verified transitions fails init [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [854b2e6ec82e](https://github.com/aurora-silicon/linux/commit/854b2e6ec82ea030f3dcfd8ff024393019dd3818), [5a02a0cd2865](https://github.com/aurora-silicon/linux/commit/5a02a0cd28651e4eb3f2eede40af991d8d265a51), [13857139ed46](https://github.com/aurora-silicon/linux/commit/13857139ed4643ef532281808bc8035ad64c9a10) | Ryan Murray | soc: apple: mcc: print the boot DMA device before dropping its node [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — MCC; `drivers/soc/apple/mcc.c` | M,P | -| [e157c990ad98](https://github.com/aurora-silicon/linux/commit/e157c990ad98e3008b552e45d0c85448f95e4266), [ec4fc264985c](https://github.com/aurora-silicon/linux/commit/ec4fc264985c5505be71434f96cc949d0037801f), [0b65493ccd0f](https://github.com/aurora-silicon/linux/commit/0b65493ccd0f4a779e592258032cb40ce03d1a1c) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: tidy the rate-limited error messages [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [3a9f56606ec3](https://github.com/aurora-silicon/linux/commit/3a9f56606ec3001c7cd7df137cf49a6ae2db0157), [3762bb8f345d](https://github.com/aurora-silicon/linux/commit/3762bb8f345de262f1efca74de864457a3adc9aa), [a516c3f7c3f8](https://github.com/aurora-silicon/linux/commit/a516c3f7c3f85aeb05efe5e3aff5b7890c7d022c) | Ryan Murray | iommu: apple-dart: Invalidate every DART even if a TLB sync step fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [8a2875a6789d](https://github.com/aurora-silicon/linux/commit/8a2875a6789d2a4f1452beafd50e4de134b30683), [0f997e1c9354](https://github.com/aurora-silicon/linux/commit/0f997e1c9354b9aa18c7ae13cdf61328b1f50d9d), [df5213734e31](https://github.com/aurora-silicon/linux/commit/df5213734e31c372fc36a2375539e4d69b5f815a) | Ryan Murray | soc: apple: rtkit: Only parse an initial crash log in inherited sessions [#345](https://github.com/aurora-silicon/linux/pull/345) | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [d6caa25b65d2](https://github.com/aurora-silicon/linux/commit/d6caa25b65d2ca7fc7315ee568e0cbd250a9593c), [f501cf5f491d](https://github.com/aurora-silicon/linux/commit/f501cf5f491da7527d71b86cd164e094aac050fd), [82494bf5c6b0](https://github.com/aurora-silicon/linux/commit/82494bf5c6b07739782eeac837b9f6a96c70ca36) | Ryan Murray | iommu/apple-dart: Do not reset a DART that kept its state across sleep [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [91d9f93cf842](https://github.com/aurora-silicon/linux/commit/91d9f93cf842a892913e7ce56218ddc27292a6c1), [dc02d89a1465](https://github.com/aurora-silicon/linux/commit/dc02d89a1465719e6ab3b3a5e31dbea08e1a8f68), [39bc76211b30](https://github.com/aurora-silicon/linux/commit/39bc76211b30ca23b29eb740ffdf0ae8cf2ed5d3) | Ryan Murray | iommu/apple-dart: Keep a retained DART in bypass from being reset [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [b6b28c111cff](https://github.com/aurora-silicon/linux/commit/b6b28c111cff20b5312fee34ca544ce6f7fd00a5), [469fd41db0a3](https://github.com/aurora-silicon/linux/commit/469fd41db0a33df014d0523648c5e1f052895c9a), [d9fc21447419](https://github.com/aurora-silicon/linux/commit/d9fc214474191909db140a5ba565a014819bd6de) | Ryan Murray | iommu/apple-dart: Restore the translations when the reset on resume fails [#336](https://github.com/aurora-silicon/linux/pull/336) | Active — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [4bfe19d0ad80](https://github.com/aurora-silicon/linux/commit/4bfe19d0ad8042e95b784fe2e439e15c8f869ac5), [cd1ff978d660](https://github.com/aurora-silicon/linux/commit/cd1ff978d6600a354b93fd829d9c9588715c44f1), [43c7fc8f82a6](https://github.com/aurora-silicon/linux/commit/43c7fc8f82a65f2e3807f41f03421df2b27ed3de) | Ryan Murray | irqchip/apple-aic: Allow interrupts to wake the system | Active — AIC; `drivers/irqchip/irq-apple-aic.c` | O,C,I | -| [345f6329c88b](https://github.com/aurora-silicon/linux/commit/345f6329c88b1ea97ecf1c373bc573a9c20947e7), [eee098196369](https://github.com/aurora-silicon/linux/commit/eee098196369f3a2aebe4f99333c53d538caa1c5) | Ryan Murray | drm/asahi: queue background work on system_dfl_wq | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [e04141b6136c](https://github.com/aurora-silicon/linux/commit/e04141b6136c63f61679eda781cabe349297d58e), [a741120e3ca0](https://github.com/aurora-silicon/linux/commit/a741120e3ca0d349dffab6cc32086935ecb98d81) | Chris Kearney | soc: apple: validate PMP boot arguments before patching | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [8a74c2db9581](https://github.com/aurora-silicon/linux/commit/8a74c2db9581fd106dc90be11fb1a1e075bf07fa), [d67dbeedca63](https://github.com/aurora-silicon/linux/commit/d67dbeedca63d1389fb5754d419fffae0c678155) | Chris Kearney | soc: apple: bound PMP arguments by the mapped SRAM size | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [6c53c0ff9715](https://github.com/aurora-silicon/linux/commit/6c53c0ff9715f055de8af928ed57277f1f0f30a2), [687f1c4f2190](https://github.com/aurora-silicon/linux/commit/687f1c4f21906c698f38c29c467f4aa74425509e) | Eryk Wieliczko | soc: apple: acknowledge serialized PMP device power commands | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [5a68774e87a8](https://github.com/aurora-silicon/linux/commit/5a68774e87a8baa711c211757b709966b2193be5), [fefec69b9fca](https://github.com/aurora-silicon/linux/commit/fefec69b9fca69f98a026a4dbdf9bde89b64544b) | Chris Kearney | soc: apple: retry unsent RTKit endpoint starts once | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [dc7d0b49a07d](https://github.com/aurora-silicon/linux/commit/dc7d0b49a07df88aab2ee9cbb3fae17db8694f2b), [5bd0a91f565c](https://github.com/aurora-silicon/linux/commit/5bd0a91f565cf815b9f999b3e704edba2563aac8) | Marius Gehrmann | soc: apple: rtkit: Honour apple,sync-syslog-ack | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [d67d380d1519](https://github.com/aurora-silicon/linux/commit/d67d380d1519babe4b9d080830e31bca56da4d8f), [9d0290148561](https://github.com/aurora-silicon/linux/commit/9d029014856181eb6190324b8300d82590ab2e8b) | Chris Kearney | soc: apple: rtkit: cap the kdebug buffer, and take a late completion | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [1369d18b4ec7](https://github.com/aurora-silicon/linux/commit/1369d18b4ec7bf0a631bc68fbdf7d894f2a4c542), [0d9ac5799dd4](https://github.com/aurora-silicon/linux/commit/0d9ac5799dd4dffe26513b100e93930bb3833a53) | Eryk Wieliczko | soc: apple: acknowledge OSLog progress in negotiated and inherited sessions | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [e47d06ceb56f](https://github.com/aurora-silicon/linux/commit/e47d06ceb56fd73444f3e17954f961dce5edfdcf), [47e137e98667](https://github.com/aurora-silicon/linux/commit/47e137e986675ca44843155e66b731c167932749) | Chris Kearney | iommu/apple-dart: reserve retained firmware tables and root slots | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [e663049674c8](https://github.com/aurora-silicon/linux/commit/e663049674c81f6818a88b594f029d0bf9f45ccc), [058d2b7355cf](https://github.com/aurora-silicon/linux/commit/058d2b7355cffe72dad9053486a26ae2822d51a2) | DjDeveloperr | soc: apple: finish the merge of DART, QSPI and SMC hwmon | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [d97a27e94fd8](https://github.com/aurora-silicon/linux/commit/d97a27e94fd8967ce1c3846dcc71628a8b39db36), [6dbfbcb21eb0](https://github.com/aurora-silicon/linux/commit/6dbfbcb21eb09d07ae59037a1ceca8cc3500841f) | Eryk Wieliczko | drm/asahi: validate GEM size before page rounding | Active — MEM; `drivers/gpu/drm/asahi/gem.rs` | M,D | -| [6d457ae0a70c](https://github.com/aurora-silicon/linux/commit/6d457ae0a70c583dc760d05ac552829d7370060f), [b038d2767d6e](https://github.com/aurora-silicon/linux/commit/b038d2767d6e08c0dae43c87da89dfd77d719f7c) | Chris Kearney | arm64: dts: apple: t8140: drop the t6000 fallback from the GFX report | Active translated data — FW | B,P | -| [496040e469aa](https://github.com/aurora-silicon/linux/commit/496040e469aa1ea3457c89cbd677d9f964614cca), [17bf156987c5](https://github.com/aurora-silicon/linux/commit/17bf156987c5f7be583bd5efc86430b1055efc36) | Chris Kearney | pmdomain: apple: pmp-report: match T8140 report entries by compatible | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [e033fe71b24d](https://github.com/aurora-silicon/linux/commit/e033fe71b24da2b2aabc90b9c5faa5bd0f497d9f), [5f7925d83ca6](https://github.com/aurora-silicon/linux/commit/5f7925d83ca680ba7760dbd16b9e0cb61029161a) | Chris Kearney | drm/asahi: keep the range TLBI base address in its field | Gated — UAT; `drivers/gpu/drm/asahi/mem.rs` | D | -| [6582e3d5ef6f](https://github.com/aurora-silicon/linux/commit/6582e3d5ef6f47ff7e0a11d3fffa47f15ef22a44), [f7132eb38e81](https://github.com/aurora-silicon/linux/commit/f7132eb38e81e5af14711b3da87aa6cf96b3ba98) | Ryan Murray | iommu: apple-dart: Factor out the DT DMA window parse | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [fc7981e78871](https://github.com/aurora-silicon/linux/commit/fc7981e78871a2ec91b38835bc84e03611b4e860), [ff11ec1083af](https://github.com/aurora-silicon/linux/commit/ff11ec1083af04c76c1d91fcebc78333681cf519) | Chris Kearney | pmdomain: apple: validate PMP startup tables before seeding | Active — PMP; `drivers/pmdomain/apple/.kunitconfig.apple-pmp` | P,B | -| [4c673adf2c11](https://github.com/aurora-silicon/linux/commit/4c673adf2c110c8264da8b0130eaf181fd6bd560), [782906a65540](https://github.com/aurora-silicon/linux/commit/782906a65540c569f6afa8b49b8c6ac22c9e8dc5) | Ryan Murray | pmdomain: apple: pmp-report: select OF_DYNAMIC | Active — PMP; `drivers/pmdomain/apple/Kconfig` | P,B | -| [f78d7690bfd2](https://github.com/aurora-silicon/linux/commit/f78d7690bfd2d927462c7af34242d6476a0cf59c), [a41d634596e5](https://github.com/aurora-silicon/linux/commit/a41d634596e536031e719b5ea8a3082220e8ec61) | Ryan Murray | drm/asahi: mmu: preallocate enough GPUVAs to unmap across two mappings | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [10fc7af5e0b8](https://github.com/aurora-silicon/linux/commit/10fc7af5e0b897112afaa5fc9ab791f241244969), [755ac9ed1425](https://github.com/aurora-silicon/linux/commit/755ac9ed142576a6e27da54a39b68290e861b34b) | DjDeveloperr | drm/asahi: g17: move the G17P UAPI past the M3 and J613 numbers | Active translated data — FW; `drivers/gpu/drm/asahi/g17/command.rs` | B,C,R | -| [6d5b51d6e818](https://github.com/aurora-silicon/linux/commit/6d5b51d6e818fc0b8915b43a030854d6d96ff330), [62aae2f0f8cb](https://github.com/aurora-silicon/linux/commit/62aae2f0f8cb52a40b2cf4ea21212ad2badd267c) | Ryan Murray | drm/asahi: uapi: use integration/aurora's wording | Active translated data — FW | B,C,R | -| [ff25cb1691ff](https://github.com/aurora-silicon/linux/commit/ff25cb1691ffa6e285dbcb014992e3838f4ad6fe) | Ryan Murray | drm/asahi: Adapt the lifetime and module-ownership changes to Linux 7.3 [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — DRM; `drivers/gpu/drm/asahi/g17/job.rs` | C,H,M,F | -| [2348e8c3acd2](https://github.com/aurora-silicon/linux/commit/2348e8c3acd2920ca583d801645e8387fd80c7f2) | Ryan Murray | drm/asahi: regs: Hold the G17 SGX mapping as a DevresIoMem [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/regs.rs` | M,D | -| [d4128b7c28ce](https://github.com/aurora-silicon/linux/commit/d4128b7c28ce177d227ff5488145e8eedd970610) | Ryan Murray | drm/asahi: make SG backing leases revocable [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — DRM; `drivers/gpu/drm/asahi/gem.rs` | C,H,M,F | -| [464cb2e30ae3](https://github.com/aurora-silicon/linux/commit/464cb2e30ae395d13723d161f2aef41066dbb79d) | Ryan Murray | drm/asahi: attribute GPU memory to its creator and limit it [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/asahi_core.rs` | M,D | -| [47f408da5996](https://github.com/aurora-silicon/linux/commit/47f408da5996da161de66282da83550bf436450e) | Ryan Murray | drm/asahi: clean up Clippy diagnostics in Aurora additions [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — OBS; `drivers/gpu/drm/asahi/g17/command.rs` | O,F | -| [e44a6b59f5d2](https://github.com/aurora-silicon/linux/commit/e44a6b59f5d248ee1a026b9dbb6dbd244e35a1d7) | Ryan Murray | soc: apple: pmp: use lossless command and bootargs conversions | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [761626d47af3](https://github.com/aurora-silicon/linux/commit/761626d47af3eb6da3ff8c998373646349aa7169) | Ryan Murray | drm/apple: quiet routine H17P external run-mode syslog records | Active — DISPLAY; `drivers/gpu/drm/apple/Makefile` | B | -| [ac38eb0f57a1](https://github.com/aurora-silicon/linux/commit/ac38eb0f57a17f59eb2ce8158df1fb81aeff2955) | Ryan Murray | drm/asahi: g17: wait for a compute command's stamp before releasing it [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [1e3b9caebc7b](https://github.com/aurora-silicon/linux/commit/1e3b9caebc7b1924acc3643222ff95b85e62bdb7) | Ryan Murray | drm/asahi: memacct: Read the module parameters by value on Linux 7.3 [#375](https://github.com/aurora-silicon/linux/pull/375) | Active — MEM; `drivers/gpu/drm/asahi/memacct.rs` | M,D | -| [db2943a27f88](https://github.com/aurora-silicon/linux/commit/db2943a27f88dcd011ae97498cbf2250a4245463) | Jonathan Goyvaerts | soc: apple: rtkit: Log unknown oslog messages at debug level | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [1797c344df7f](https://github.com/aurora-silicon/linux/commit/1797c344df7f7631b2f9be7c9be1a55d8852b164) | Jonathan Goyvaerts | pmdomain: apple: pmp-report: Add T6040 support [#374](https://github.com/aurora-silicon/linux/pull/374) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [927c31856676](https://github.com/aurora-silicon/linux/commit/927c318566760e7b4845d36904022c38271b925d) | Jonathan Goyvaerts | soc: apple: pmp: Add T6040 support [#374](https://github.com/aurora-silicon/linux/pull/374) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [7fcc7fd38c43](https://github.com/aurora-silicon/linux/commit/7fcc7fd38c43b6aa64ea2270dcd32cdd57d19f37) | Ryan Murray | drm/asahi: carry G17 admission prerequisites to 7.3 [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,D | -| [c9f72dc51116](https://github.com/aurora-silicon/linux/commit/c9f72dc51116c12b3aa840185eee5a45f4b298b5) | Ryan Murray | drm/asahi: carry G17 pool-release recovery and stamp-wait fixup to 7.3 [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [10e9da2303fc](https://github.com/aurora-silicon/linux/commit/10e9da2303fc79dc205989075855350020bf115b) | Ryan Murray | drm/asahi: hand abandoned compute growth back to witness settlement [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | C,H | -| [e933ad436de0](https://github.com/aurora-silicon/linux/commit/e933ad436de06981d95e9de6ce5626f4ba99e6ff) | Ryan Murray | drm/asahi: borrow the compute pool mutably for header replacement [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — GMEM; `drivers/gpu/drm/asahi/g17/freelist.rs` | M,C,R | -| [04358c1ebe86](https://github.com/aurora-silicon/linux/commit/04358c1ebe86cfbfdc926cfb41ff3e3549248279) | Ryan Murray | drm/asahi: hold failed growth reservations until aliases have gone [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,R,H | -| [d765e50ada90](https://github.com/aurora-silicon/linux/commit/d765e50ada90e7f00a4ad608c9ff027d0a07a82a) | Ryan Murray | drm/asahi: drop tentative growth aliases before returning a fresh QID [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime.rs` | C,R,H | -| [780956abdb5f](https://github.com/aurora-silicon/linux/commit/780956abdb5fe59c76ca7343bc7f19770df658dd) | Ryan Murray | drm/asahi: compose shared capacity admission with accepted recovery port [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MEM; `drivers/gpu/drm/asahi/g17/buffer.rs` | M,D | -| [b52bd36805e0](https://github.com/aurora-silicon/linux/commit/b52bd36805e0c35bac5c8255aae8cfad7cce5dd7) | Ryan Murray | drm/asahi: give native ray-query jobs a bounded execution allowance [#377](https://github.com/aurora-silicon/linux/pull/377) | Gated — RT; `drivers/gpu/drm/asahi/g17/job.rs` | F | -| [a5bc25b2ce19](https://github.com/aurora-silicon/linux/commit/a5bc25b2ce1997452676894fc8c9b401c7396e6c) | Ryan Murray | drm/asahi: cover render helpers and AS builds with bounded execution [#377](https://github.com/aurora-silicon/linux/pull/377) | Gated — RT; `drivers/gpu/drm/asahi/g17/command.rs` | F | -| [9827b6bb277a](https://github.com/aurora-silicon/linux/commit/9827b6bb277af5912490229f6fe56d3c575dafe3) | Ryan Murray | drm/asahi: bound repeated timeout recovery and G17 mailbox stalls [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — MBOX; `drivers/gpu/drm/asahi/g17/dependency.rs` | B,O | -| [c314dbb5bd42](https://github.com/aurora-silicon/linux/commit/c314dbb5bd4284697bd065db87eb038021b18125) | Ryan Murray | drm/asahi: expire background pool-release and render-replay polls [#377](https://github.com/aurora-silicon/linux/pull/377) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [6c2d17ff4079](https://github.com/aurora-silicon/linux/commit/6c2d17ff40796899d7190580cabaeea749c73d0a) | Ryan Murray | drm/sched: initialise free_guilty in drm_sched_init() [#381](https://github.com/aurora-silicon/linux/pull/381) | Active — DRM; `drivers/gpu/drm/scheduler/sched_main.c` | C,H,M,F | -| [0d1871c3cfde](https://github.com/aurora-silicon/linux/commit/0d1871c3cfde9cc45b8bc244dde4775dbf4e05c6) | Ryan Murray | rust: drm: sched: zero the scheduler before drm_sched_init() [#381](https://github.com/aurora-silicon/linux/pull/381) | Active — DRM; `rust/kernel/drm/sched.rs` | C,H,M,F | -| [24399672582c](https://github.com/aurora-silicon/linux/commit/24399672582c155df35cadf8cb81a3397958f9e2) | Ryan Murray | drm/asahi: retry G17 retained compute publication pressure [#382](https://github.com/aurora-silicon/linux/pull/382) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,H | -| [5ae95851753d](https://github.com/aurora-silicon/linux/commit/5ae95851753d377e13b7e3ac9012452a7fdaccc9) | Jonathan Goyvaerts | pmdomain: apple: pmc: Add the T6040 voter interface [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — PMC; `drivers/pmdomain/apple/pmc-test.c` | P,C,R | -| [7bbd2ad37554](https://github.com/aurora-silicon/linux/commit/7bbd2ad375543683c070aca6487fae75a79fc747) | Jonathan Goyvaerts | soc: apple: clpc: Add the T6040 demand table [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [b3765bd38ecb](https://github.com/aurora-silicon/linux/commit/b3765bd38ecbfaa5368b760c9d908964abf8c7a5) | Jonathan Goyvaerts | soc: apple: mcc: Allow up to 16 cache planes [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — MCC; `drivers/soc/apple/Kconfig` | M,P | -| [f236c33daca6](https://github.com/aurora-silicon/linux/commit/f236c33daca696a326bd652799bd189ac2b6421f) | Jonathan Goyvaerts | soc: apple: clpc: Request a state only after sustained load [#385](https://github.com/aurora-silicon/linux/pull/385) | Active — CLPC; `drivers/soc/apple/clpc.c` | P,C,R,I | -| [32960bbd0e9c](https://github.com/aurora-silicon/linux/commit/32960bbd0e9cf24931f18d25131eef24f74f3d31) | Jonathan Goyvaerts | iommu/apple-dart: Mirror the firmware's display mappings on T6040 [#386](https://github.com/aurora-silicon/linux/pull/386) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [833c6ed10ffc](https://github.com/aurora-silicon/linux/commit/833c6ed10ffc2ac2d38b7bbb0d85dcc2b8e171df) | DjDeveloperr | drm/asahi: reduce minimum G17 target record backing [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — MEM; `drivers/gpu/drm/asahi/hw/t8140.rs` | M,D | -| [145361fdc90e](https://github.com/aurora-silicon/linux/commit/145361fdc90e82f4bddf6234ec46d0e023f41f86) | DjDeveloperr | drm/asahi: order G17 queue owner changes after scheduler releases [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | C,R,H | -| [1d478ee6c06b](https://github.com/aurora-silicon/linux/commit/1d478ee6c06b56b48782d08b693d9aa9e5c43435) | DjDeveloperr | drm/asahi: keep G17 render kick ring storage for the life of the device [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/kick.rs` | R,H | -| [7304ddbf6d4d](https://github.com/aurora-silicon/linux/commit/7304ddbf6d4d47b7976efcd20623524c9c53b0b1) | DjDeveloperr | drm/asahi: keep G17 render capacity waits from stopping the runtime [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/freelist.rs` | R,H | -| [72d57c0b9ac9](https://github.com/aurora-silicon/linux/commit/72d57c0b9ac9b8d5fcd58c59eebfa7f9c605399c) | DjDeveloperr | drm/asahi: wait for G17 contexts of closing queues at queue creation [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — REC; `drivers/gpu/drm/asahi/g17/capacity.rs` | F,Q | -| [a4351b50cd8d](https://github.com/aurora-silicon/linux/commit/a4351b50cd8d6f194bb71252acf9c9e2cf636db4) | DjDeveloperr | drm/asahi: keep G17 publication waits out of the submit ioctl [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/completion.rs` | C,R,H | -| [c556dacd085b](https://github.com/aurora-silicon/linux/commit/c556dacd085b148da86b47792dc34d14f02ace86) | DjDeveloperr | drm/asahi: rerun the G17 event pass for completions missed while a pair is borrowed [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/render.rs` | C,R,H | -| [8744e9417249](https://github.com/aurora-silicon/linux/commit/8744e9417249175511480765dbcc99f0a09c0fb9) | DjDeveloperr | drm/asahi: reuse G17 compute timestamp pages within a context [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — TIMESTAMP; `drivers/gpu/drm/asahi/g17/completion.rs` | T,C | -| [6f7faeecea0e](https://github.com/aurora-silicon/linux/commit/6f7faeecea0eccc8ee317ba163867df339d54fa5) | Jonathan Goyvaerts | drm/asahi: g17: do not advertise soft faults [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [b0912f542fd0](https://github.com/aurora-silicon/linux/commit/b0912f542fd0655f10631977a8c63abc51a85ada) | Jonathan Goyvaerts | drm/asahi: g17: reread a torn borrowed render snapshot [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/render/retirement.rs` | R,H | -| [30ea4b130473](https://github.com/aurora-silicon/linux/commit/30ea4b13047377972cb75b78a4cbe5885cf46d1d) | Jonathan Goyvaerts | drm/asahi: g17: do not fail a blamed render that attribution cleared [#391](https://github.com/aurora-silicon/linux/pull/391) | Gated — KEY; `drivers/gpu/drm/asahi/g17/recovery.rs` | F | -| [e3d8d1b2fc1f](https://github.com/aurora-silicon/linux/commit/e3d8d1b2fc1feada69ec028203f727f642a150ac) | Jonathan Goyvaerts | drm/asahi: g17: skip already-signalled successful input fences [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — SHARED; `drivers/gpu/drm/asahi/g17/queue/mod.rs` | C,R,H | -| [2321a1bc6ea6](https://github.com/aurora-silicon/linux/commit/2321a1bc6ea6c8a62a275685c0542a293c9b5438) | Jonathan Goyvaerts | drm/asahi: allow HIGH queue priority with CAP_SYS_NICE or DRM master [#391](https://github.com/aurora-silicon/linux/pull/391) | Active — DRM; `drivers/gpu/drm/asahi/g17/mod.rs` | B,M | -| [77a2bbe1a951](https://github.com/aurora-silicon/linux/commit/77a2bbe1a9512960e8c9ba17b466b2c9ab51fb5f) | Ryan Murray | soc: apple: rtkit: Keep warning about unknown oslog messages | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [b2adcfc94046](https://github.com/aurora-silicon/linux/commit/b2adcfc94046a10a989c6fd61fdb1bf7131ef78a) | Ryan Murray | drm/asahi: fail large G17 backing population without direct reclaim [#397](https://github.com/aurora-silicon/linux/pull/397) | Active — DRM; `drivers/gpu/drm/asahi/file.rs` | C,H,M,F | -| [632e4676500b](https://github.com/aurora-silicon/linux/commit/632e4676500bab6fd88817b1cf767afb1bf5da52) | Ryan Murray | drm/asahi: expose memory admission capacities in GET_PARAMS [#397](https://github.com/aurora-silicon/linux/pull/397) | Active — MEM; `drivers/gpu/drm/asahi/file.rs` | M,D | -| [ffe8011a479c](https://github.com/aurora-silicon/linux/commit/ffe8011a479ccd74dde747225c9baf67e2a02ba6) | Chris Kearney | drm/asahi: g15: reject errored input dependencies before publication [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [faef7fd12e22](https://github.com/aurora-silicon/linux/commit/faef7fd12e22a4d56873b91981d412fd981cfd21) | Chris Kearney | drm/asahi: expose the inherited-error policy only for native G15 [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — SHARED; `drivers/gpu/drm/asahi/g17/mod.rs` | C,R,H | -| [8736001f2b13](https://github.com/aurora-silicon/linux/commit/8736001f2b130a9e477fdef7d1db45f31591bfec) | Eryk Wieliczko | pmdomain: apple: pmgr-pwrstate: Honour apple,no-auto-pm [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — PMGR; `drivers/pmdomain/apple/pmgr-pwrstate.c` | B,F | -| [2aff1b95c550](https://github.com/aurora-silicon/linux/commit/2aff1b95c55039846beb6451c737154254aa3ae0) | Eryk Wieliczko | soc: apple: rtkit: describe and adopt retained system buffers | Active — RTKIT; `drivers/soc/apple/rtkit-internal.h` | B,F | -| [71500694f45b](https://github.com/aurora-silicon/linux/commit/71500694f45b1fd27b05c9ed030b2cc803fb0f2f) | Eryk Wieliczko | drm/asahi: share tracked VM lifetime and native query support [#400](https://github.com/aurora-silicon/linux/pull/400) | Active — MEM; `drivers/gpu/drm/asahi/g17/completion.rs` | M,D | -| [444c52644826](https://github.com/aurora-silicon/linux/commit/444c52644826e99eecf65e9f643744c9e380bca9) | Ryan Murray | soc: apple: pmp: Keep power commands after an unhandled message on other boards | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [76c60f146885](https://github.com/aurora-silicon/linux/commit/76c60f1468853b4d28e3fed6e9c207c8a2f28410) | Ryan Murray | iommu/apple-dart: Map retained DARTs non-posted like every other DART [#400](https://github.com/aurora-silicon/linux/pull/400) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [d5df65ffcf66](https://github.com/aurora-silicon/linux/commit/d5df65ffcf66e54d9f23de05635512a2cf0ad41d) | Jonathan Goyvaerts | soc: apple: rtkit: add apple_rtkit_resume_idle() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [f82267ce1172](https://github.com/aurora-silicon/linux/commit/f82267ce117278fb915879abbbd0f355286cecf3) | Jonathan Goyvaerts | soc: apple: rtkit: resume the AP power state before the IOP's | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [e772e7f87659](https://github.com/aurora-silicon/linux/commit/e772e7f87659243ab7b94c2b5bb77ab485dc1128) | DjDeveloperr | iommu/apple-dart: accept mirrored pages in handed-off firmware slots [#404](https://github.com/aurora-silicon/linux/pull/404) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [ff5c39ae1782](https://github.com/aurora-silicon/linux/commit/ff5c39ae1782cd1d826eddf48e0b08b1b2af61eb) | DjDeveloperr | iommu/apple-dart: keep stream invalidates out of handed-off slots [#404](https://github.com/aurora-silicon/linux/pull/404) | Active — DART; `drivers/iommu/apple-dart.c` | D,B | -| [c2bace5bb285](https://github.com/aurora-silicon/linux/commit/c2bace5bb28512471318d71abd5073b2bc7e2af1) | Ryan Murray | soc: apple: pmp: start endpoint 7 on every T6041 PMP [#402](https://github.com/aurora-silicon/linux/pull/402) | Active — PMP; `drivers/soc/apple/pmp.rs` | P,B | -| [2d8c0fe879e2](https://github.com/aurora-silicon/linux/commit/2d8c0fe879e26583b62655534a3aba86b1dfc80f) | Jonathan Goyvaerts | drm/asahi: mmu: make the secondary root of PublishedRoots optional [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MEM; `drivers/gpu/drm/asahi/g17/mod.rs` | M,D | -| [40507bad232c](https://github.com/aurora-silicon/linux/commit/40507bad232c7539f3c7c2540bac818a7aa90f26) | Jonathan Goyvaerts | drm/asahi: g17: support a single firmware coprocessor [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/event.rs` | C,R,H | -| [750dd1a8e590](https://github.com/aurora-silicon/linux/commit/750dd1a8e5902e4e7478ce9213278b2131b63266) | Jonathan Goyvaerts | drm/asahi: g17: describe the firmware build in a variant table [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data; MCache gated by V25G83.mcache=false — FW; `drivers/gpu/drm/asahi/g17/command.rs` | B,C,R | -| [9038ef8d328c](https://github.com/aurora-silicon/linux/commit/9038ef8d328cef14e038513ccaf55dc03869006b) | Jonathan Goyvaerts | drm/asahi: g17: take the per-SoC tables from Config [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/initdata.rs` | B,C,R | -| [24d1e5f4d8d3](https://github.com/aurora-silicon/linux/commit/24d1e5f4d8d31dd320048546cd53230a61203a9f) | Jonathan Goyvaerts | drm/asahi: g17: operating points with one voltage per cluster [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [1ef423a08b3c](https://github.com/aurora-silicon/linux/commit/1ef423a08b3cbc81856afbe3c5854ac25b0893b6) | Jonathan Goyvaerts | drm/asahi: g17: register windows with several instances [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | C,R,H | -| [f23df96e697b](https://github.com/aurora-silicon/linux/commit/f23df96e697bc05a47029efd4fe786f900b08a83) | Jonathan Goyvaerts | drm/asahi: g17: let the variant choose the init acknowledgement [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [39e990b44482](https://github.com/aurora-silicon/linux/commit/39e990b44482f46fb6bed6c3b7eb2413e0f0331a) | Jonathan Goyvaerts | drm/asahi: mmu: firmware tables in no-map reserved memory [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MEM; `drivers/gpu/drm/asahi/g17/mod.rs` | M,D | -| [54eccc50cc77](https://github.com/aurora-silicon/linux/commit/54eccc50cc770bdbe9306be4337c548f399e2eb8) | Jonathan Goyvaerts | drm/asahi: mmu: per-SoC UAT cache, TLB and handoff policy [#420](https://github.com/aurora-silicon/linux/pull/420) | Gated — UAT; `drivers/gpu/drm/asahi/mem.rs` | D | -| [abb36e8aa320](https://github.com/aurora-silicon/linux/commit/abb36e8aa3203f4cb28c1b2498d636617d01111d) | Jonathan Goyvaerts | drm/asahi: g17: 25G83 initialization layout [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | B,C,R | -| [0d9efa515188](https://github.com/aurora-silicon/linux/commit/0d9efa515188d93cd775e240b20bf4ad29a258c8) | Jonathan Goyvaerts | drm/asahi: g17: render lead commands for the 25G83 firmware [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,C,R | -| [f8dc19862078](https://github.com/aurora-silicon/linux/commit/f8dc19862078a7ad72cd3e10fe22052a02609e76) | Jonathan Goyvaerts | drm/asahi: g17: 25G83 render and compute commands [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/buffer/target.rs` | B,C,R | -| [20e51646e036](https://github.com/aurora-silicon/linux/commit/20e51646e036432fa9498a24e5330b8d02068612) | Jonathan Goyvaerts | drm/asahi: g17: add the T6040 (M4 Pro) [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [244f347d7dee](https://github.com/aurora-silicon/linux/commit/244f347d7deedb8a67eda1f0175ce001a5e7509c) | Jonathan Goyvaerts | soc: apple: rtkit: drop apple_rtkit_resume_idle() | Active — RTKIT; `drivers/soc/apple/rtkit.c` | B,F | -| [a214e242a034](https://github.com/aurora-silicon/linux/commit/a214e242a03404fc7324ff0efdc595a6b37a53c5) | Jonathan Goyvaerts | drm/asahi: g17: bounded cross-VM grace for render timeouts [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/job.rs` | F,Q | -| [24349f4a4593](https://github.com/aurora-silicon/linux/commit/24349f4a4593fa4e02ce731f5e73a228aa27aed8) | Jonathan Goyvaerts | drm/asahi: g17: retire abandoned spared renders without failing clients [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [9af21ada7212](https://github.com/aurora-silicon/linux/commit/9af21ada7212737042705f3081d153332516a182) | Jonathan Goyvaerts | drm/asahi: g17: spare innocent renders once the cross-VM grace runs out [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — SHARED; `drivers/gpu/drm/asahi/g17/runtime/backend.rs` | R,H | -| [29f38d83f6a6](https://github.com/aurora-silicon/linux/commit/29f38d83f6a6208d4ff3c4187042b3b0b476d242) | Jonathan Goyvaerts | drm/asahi: g17: keep a VM usable behind its spared render quarantine [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [c71f1177e773](https://github.com/aurora-silicon/linux/commit/c71f1177e7730db49e9a7ec9cdf150a0feeb05ab) | Jonathan Goyvaerts | drm/asahi: g17: hold the GPU powered for idle_off_delay_ms after work [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — POWER; `drivers/gpu/drm/asahi/g17/mod.rs` | I,C,R,P | -| [645b4e55cf16](https://github.com/aurora-silicon/linux/commit/645b4e55cf16c1cedffba87258bdaafd5b15dcd8) | Jonathan Goyvaerts | drm/asahi: g17: replay every render group firmware dropped unexecuted [#413](https://github.com/aurora-silicon/linux/pull/413) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [94e719a0cec2](https://github.com/aurora-silicon/linux/commit/94e719a0cec2a65502ce5413d2ee9a105c1cc8d9) | Ryan Murray | drm/asahi: g17: never replay a render group a recovery blamed [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/completion.rs` | F,Q | -| [1054f6763014](https://github.com/aurora-silicon/linux/commit/1054f6763014fe4b4032a08ae7ccce721be4d385) | Ryan Murray | drm/asahi: g17: fix the render timeout head and replay documentation [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [45ac35fa2796](https://github.com/aurora-silicon/linux/commit/45ac35fa279642f98ea7326144716755fb3a39a2) | Ryan Murray | drm/asahi: g17: move the fw-data crash log mapping to its own file [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/data_segment.rs` | C,R,H | -| [fd21bf6faed6](https://github.com/aurora-silicon/linux/commit/fd21bf6faed6f978223e61444424ee918c199838) | Ryan Murray | drm/asahi: g17: take the core-layout buffers from Config [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/compute.rs` | B,C,R | -| [c0b9fbfa9fb0](https://github.com/aurora-silicon/linux/commit/c0b9fbfa9fb048d5bc67ffb9e17168b686b1962d) | Ryan Murray | drm/asahi: g17: check the voltage cells of the GPU operating points [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/initdata.rs` | B,C,R | -| [1c5a2ef5783a](https://github.com/aurora-silicon/linux/commit/1c5a2ef5783a565e6b27da871d30e4e637e1ce69) | Ryan Murray | drm/asahi: g17: accept only the two host words of a pointer block [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/queue.rs` | B,C,R | -| [df6b70b85cbf](https://github.com/aurora-silicon/linux/commit/df6b70b85cbfada36604f511b9ba8da21b13eb7d) | Ryan Murray | drm/asahi: g17: pass the fragment ID to the barrier unchanged [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — SHARED; `drivers/gpu/drm/asahi/g17/fw/queue.rs` | C,R,H | -| [496a59f89601](https://github.com/aurora-silicon/linux/commit/496a59f8960191dc511b92328b13ccc7e31ad1ff) | Ryan Murray | drm/asahi: g17: do not spare a timeout behind work that already failed [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [fc1a16b4722c](https://github.com/aurora-silicon/linux/commit/fc1a16b4722ce9a9eb6b77fc0af4163873cacc9e) | Ryan Murray | drm/asahi: g17: name the blocking work in the watchdog lines [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — OBS; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | O,F | -| [894ec76dc892](https://github.com/aurora-silicon/linux/commit/894ec76dc89219caae27f9d6845521337b16e8bf) | Ryan Murray | drm/asahi: g17: treat a torn render sample in the timeout fallback as no proof [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [7d167e382f40](https://github.com/aurora-silicon/linux/commit/7d167e382f40542b25ffceb596d0982ee002b7ca) | Ryan Murray | drm/asahi: g17: fail the dropped successors of an exhausted render replay [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/queue/render.rs` | F,Q | -| [5ee97891f61f](https://github.com/aurora-silicon/linux/commit/5ee97891f61f552c8c1d677db50725c413fb3ed7) | Ryan Murray | drm/asahi: g17: retire finished renders before attributing a render timeout [#418](https://github.com/aurora-silicon/linux/pull/418) | Active — REC; `drivers/gpu/drm/asahi/g17/runtime/backend.rs` | F,Q | -| [25f4c6c3ab18](https://github.com/aurora-silicon/linux/commit/25f4c6c3ab18f329ba2af41b102c30d53e361ae6) | Ryan Murray | thermal: apple: Describe the PMP policy KUnit test module [#417](https://github.com/aurora-silicon/linux/pull/417) | Active — PMP; `drivers/thermal/apple-pmp-policy-test.c` | P,B | -| [b9a8f3938f3d](https://github.com/aurora-silicon/linux/commit/b9a8f3938f3daf5926b7c86204113f6730aec136) | Ryan Murray | drm/asahi: g17: pass the queue count to Pool::new() in the fault admission test [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — GMEM; `drivers/gpu/drm/asahi/g17/queue/admission.rs` | M,C,R | -| [bec833e0bc58](https://github.com/aurora-silicon/linux/commit/bec833e0bc581f74744265f0613832e8291db0cc) | Jonathan Goyvaerts | drm/asahi: pgtable: check the struct page of a table outside the reserved regions [#427](https://github.com/aurora-silicon/linux/pull/427) | Active — MEM; `drivers/gpu/drm/asahi/mmu.rs` | M,D | -| [a335c77de52a](https://github.com/aurora-silicon/linux/commit/a335c77de52a274029bb4e42f96d6afde5712a2f) | Jonathan Goyvaerts | drm/asahi: identify the T6040 GPU firmware by its loaded text [#428](https://github.com/aurora-silicon/linux/pull/428) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [d69f14f4e4fb](https://github.com/aurora-silicon/linux/commit/d69f14f4e4fbe9af21b70ee5c1b3ff9125c7a9cf) | DjDeveloperr | soc: apple: clpc: raise the T8140 fabric floor for GPU work [#440](https://github.com/aurora-silicon/linux/pull/440) | Active after port; 0d63308820ab — GPUFLOOR; `drivers/soc/apple/clpc.c` | P,C,R,H,I | -| [d1468a5f9a50](https://github.com/aurora-silicon/linux/commit/d1468a5f9a50a23cf741f56d83e6690441b90482) | Ryan | drm/asahi: gpu: drop the unused module_parameters import [#395](https://github.com/aurora-silicon/linux/pull/395) | Active — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [26f5eb68dbce](https://github.com/aurora-silicon/linux/commit/26f5eb68dbce039de470b789d754d2ec3541c15e) | Ryan Murray | drm/asahi: admit the alternate T6040 loaded 25G83 image [#453](https://github.com/aurora-silicon/linux/pull/453) | Active translated data — FW; `drivers/gpu/drm/asahi/g17/fw/variant.rs` | B,C,R | -| [88aebfe0c656](https://github.com/aurora-silicon/linux/commit/88aebfe0c656676c530faa8f85df8d7b69a7ddb0) | DjDeveloperr | irqchip/apple-aic: Report the effective affinity of AICv2+ IRQs [#447](https://github.com/aurora-silicon/linux/pull/447) | Active — AIC; `drivers/irqchip/irq-apple-aic.c` | O,C,I | -| [eb346c1a25d8](https://github.com/aurora-silicon/linux/commit/eb346c1a25d813a1411a34fafc7d4bdee418e0d4), [42a176b951d9](https://github.com/aurora-silicon/linux/commit/42a176b951d90e746e33d27d6eb06a1773579afe) | Haoxiang Li | cpufreq: apple-soc: Fix OPP table cleanup | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [ae37f03d4163](https://github.com/aurora-silicon/linux/commit/ae37f03d4163df8143b2144e742916b91bf90654) | Ryan Murray | thermal: apple-smc-cpu: Add the J700 CPU thermal policy [#22](https://github.com/aurora-silicon/linux/pull/22) | Active — CPU; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I,P | -| [583b9fa52fbf](https://github.com/aurora-silicon/linux/commit/583b9fa52fbf6a47f150736ad4a1aaa0d616ac02), [a8872354b695](https://github.com/aurora-silicon/linux/commit/a8872354b695a066ac6411791a691f26fcde55bf) | Oliver Lukschander | pmdomain: apple: pmp-report: initialize the report lock [#56](https://github.com/aurora-silicon/linux/pull/56) | Active — PMP; `drivers/pmdomain/apple/pmp-report.c` | P,B | -| [8ca5289bec3a](https://github.com/aurora-silicon/linux/commit/8ca5289bec3a2b6f3629c9df516b357778273a72) | Joshua Warren | drm/asahi: connect the snapshot pointer to the C sysfs static [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/gpu.rs` | M,D | -| [628bf1df4312](https://github.com/aurora-silicon/linux/commit/628bf1df43123ead994b028fd7b82a209e67aa30), [983575d7b492](https://github.com/aurora-silicon/linux/commit/983575d7b492f6824401cd21fe02278812211e27) | Ryan Murray | drm/asahi: initialize driver data before claiming destructor ownership [#171](https://github.com/aurora-silicon/linux/pull/171) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,B | -| [b10d60ce3916](https://github.com/aurora-silicon/linux/commit/b10d60ce3916c44dfb19b1f1b197bdca40bbac34) | Ryan Murray | drm/asahi: retain two-phase data ownership with stats registration [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MEM; `drivers/gpu/drm/asahi/driver.rs` | M,B | -| [9266541b8d35](https://github.com/aurora-silicon/linux/commit/9266541b8d35c1cd7146eec9a9b31b39fb7f29cc) | Ryan Murray | treewide: describe hardware behaviour in comments [#233](https://github.com/aurora-silicon/linux/pull/233) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — MBOX; `drivers/gpu/drm/asahi/g17/buffer.rs` | B,O | -| [8533f072dc30](https://github.com/aurora-silicon/linux/commit/8533f072dc30e076206631f68f41fb4f8d7512a7) | Janne Grunau | iommu: apple-dart: Support specifying the DMA aperture in the DT | Active; carried/refined form — DART; `drivers/iommu/apple-dart.c` | D,B | -| [a9e24ae824ec](https://github.com/aurora-silicon/linux/commit/a9e24ae824ec205cf90f3545b0125631adf1326a) | Ryan Murray | merge: retain the 7.3 implementations where older ports duplicate them [#470](https://github.com/aurora-silicon/linux/pull/470) | Active; carried/refined form — PMGR; `drivers/bluetooth/hci_bcm4377.c` | B,F | -| [00248157ec1f](https://github.com/aurora-silicon/linux/commit/00248157ec1fc4e6369cd26cb8304bb56df7415d), [b2258cfadd69](https://github.com/aurora-silicon/linux/commit/b2258cfadd697cbe10c1e29b54f512c8f297bbe6) | Joshua Warren | soc: apple: mailbox: Make the send-empty IRQ optional (poll TX) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [00e21c12c05a](https://github.com/aurora-silicon/linux/commit/00e21c12c05af1d540a2dc256a8cea3d17d63edc) | Lyude Paul | rust: drm: gem: Add export() callback | Active — DRM; `drivers/gpu/drm/nova/gem.rs` | C,H,M,F | -| [03329eff23bd](https://github.com/aurora-silicon/linux/commit/03329eff23bd3a72bdcfa09a3b98d0ac15107e6e), [35b057e57222](https://github.com/aurora-silicon/linux/commit/35b057e572224c39f79367df9e7c464f1822d15a), [e68c60f81285](https://github.com/aurora-silicon/linux/commit/e68c60f81285248fb50578f268343b06a6452a67) | DjDeveloperr | rust: drm: gpuvm: add non-blocking private mapping traversal [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `rust/kernel/drm/gpuvm.rs` | C,H,M,F | -| [033943b2b6ed](https://github.com/aurora-silicon/linux/commit/033943b2b6edb176aaebffa917e2273c3bf8f625) | Ryan Murray | drm: apple: parser: cap the number of timing modes [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/parser.c` | B | -| [08e4dd7596c9](https://github.com/aurora-silicon/linux/commit/08e4dd7596c91cdb5b761a0d272e40d75320306b), [29db1d8ab517](https://github.com/aurora-silicon/linux/commit/29db1d8ab517933c2e0114fb3c6bf9beda5417aa), [437f51c11728](https://github.com/aurora-silicon/linux/commit/437f51c11728f3183b0c17af6264547e44a60c26) | Ryan Murray | soc: apple: synchronize the ASCWrap mailbox provider with j700 [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [0db024825eb1](https://github.com/aurora-silicon/linux/commit/0db024825eb15d5ffd51ae6bb6b71ea4899ff3c2) | Ryan Murray | rust: drm: update shmem KUnit fixtures for the 7.2 file API | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [17f9a8193f55](https://github.com/aurora-silicon/linux/commit/17f9a8193f553f12afb69a14c849e12889842e8b) | Ryan Murray | rust: drm: gem: shmem: leave an imported object's SG table to the attachment | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [1f6c1fbb7057](https://github.com/aurora-silicon/linux/commit/1f6c1fbb7057db9206dce7187cfd3ec73233cd67) | Ryan Murray | drm/apple: dcp: Release the fixed display route with the device [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [29a2e2acec42](https://github.com/aurora-silicon/linux/commit/29a2e2acec42f8361d72bfd9506e3a0527afaf40) | DjDeveloperr | sched/core: add scoped utilization floors for kernel waiters [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM | C,H,M,F | -| [29a913a5c222](https://github.com/aurora-silicon/linux/commit/29a913a5c222f2bec2ecae62a4dc4af223e5962d) | Jonathan Goyvaerts | soc: apple: mailbox: support the T6040 ASCWrap v6 [#420](https://github.com/aurora-silicon/linux/pull/420) | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [2b59aed7191c](https://github.com/aurora-silicon/linux/commit/2b59aed7191cccf0f6239e50e9a165f49b649529) | Ryan Murray | drm/asahi: avoid fence locks when pruning G17 frontiers [#201](https://github.com/aurora-silicon/linux/pull/201) | Active; carried/refined form — SHARED; `drivers/gpu/drm/asahi/g17/fence.rs` | C,R,H | -| [2dc22a191a5c](https://github.com/aurora-silicon/linux/commit/2dc22a191a5cf3109fb18dcfda0fec94bd4df18b), [a45a44cc6e2b](https://github.com/aurora-silicon/linux/commit/a45a44cc6e2b6bbdb189debda045a2174d07e039) | Ryan Murray | rust: drm: gem: shmem: let drivers allocate the objects the core creates | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [32418c60d4cd](https://github.com/aurora-silicon/linux/commit/32418c60d4cdd6b37e2e9c7e88c7e299d473cf19) | Ryan Murray | drm/apple: dcp: Do not hold the mailbox of an unbound DCP for sleep [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [351fc1af825c](https://github.com/aurora-silicon/linux/commit/351fc1af825c49264de7e171a983d2c0c83f1601) | Ryan Murray | dt-bindings: power: apple,pmc: describe the DCS limit [#219](https://github.com/aurora-silicon/linux/pull/219) | Gated — DCS | P | -| [3b9a0383f589](https://github.com/aurora-silicon/linux/commit/3b9a0383f589ebaaa5bcd5c3242e294d6051f0e0) | Janne Grunau | FIXME: drm/gpuvm: Add DRM_GPUVA_REPEAT flag and logic | Active — DRM; `rust/kernel/drm/gpuvm/sm_ops.rs` | C,H,M,F | -| [3c102dba66df](https://github.com/aurora-silicon/linux/commit/3c102dba66df1119625c11c80dca301fb308563c) | Asahi Lina | rust: drm: mm: Add DRM MM Range Allocator abstraction | Active — DRM; `rust/kernel/drm/mm.rs` | C,H,M,F | -| [3d0c9c889919](https://github.com/aurora-silicon/linux/commit/3d0c9c8899198a8ad6d0d0241283ba04d2286fd7) | Ryan Murray | drm: apple: parser: bound the timing catalog allocation [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/parser.c` | B | -| [3d3fe96509d1](https://github.com/aurora-silicon/linux/commit/3d3fe96509d102770f72ce5f7829baa3c0f7d1ce), [df2e3cd3b778](https://github.com/aurora-silicon/linux/commit/df2e3cd3b77882ec523b42184d05596e60094072) | Ryan Murray | rust: soc: apple: mailbox: Fix receiver teardown and expose the device | Active — MBOX; `rust/kernel/soc/apple/mailbox.rs` | B,O | -| [3fd71b22d86c](https://github.com/aurora-silicon/linux/commit/3fd71b22d86c3e2397ed1da8a15123053d46a423), [536484539477](https://github.com/aurora-silicon/linux/commit/53648453947771b7ca24a61a585bffdbe1853242) | Ryan Murray | soc: apple: mailbox: Add T8140 ASC and AOP setup mailboxes | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [43fc98be783b](https://github.com/aurora-silicon/linux/commit/43fc98be783b0e9833242c1d8d111b49366b134b), [7c99d8debcc5](https://github.com/aurora-silicon/linux/commit/7c99d8debcc54ebf3f76ede14ced9b845db18215), [b0cc4eeb554a](https://github.com/aurora-silicon/linux/commit/b0cc4eeb554a74c2db220e35ceb14955142a79ed) | DjDeveloperr | drm/syncobj: apply expiring capacity hints during blocking waits [#171](https://github.com/aurora-silicon/linux/pull/171) | Active — DRM; `drivers/gpu/drm/drm_syncobj.c` | C,H,M,F | -| [4a577fcddddb](https://github.com/aurora-silicon/linux/commit/4a577fcddddbefec7d13bfd4ae3503893602d29b) | DjDeveloperr | rust: expose the DRM duplicate-reservation flag used by GPUVM [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM | B,M | -| [4aa16bb5021e](https://github.com/aurora-silicon/linux/commit/4aa16bb5021e427507e15a9a48848d0484a4f3d6) | Eryk Wieliczko | rust: expose fence and DRM lifecycle helpers for native GPU backends | Active — DRM; `rust/kernel/dma_fence.rs` | C,H,M,F | -| [4f7a3272df96](https://github.com/aurora-silicon/linux/commit/4f7a3272df9627d98bc11a7da0c8189ca4aba196) | DjDeveloperr | drm/shmem-helper: populate revocable CPU mappings one page at a time [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [5443fc6aeb7a](https://github.com/aurora-silicon/linux/commit/5443fc6aeb7a0fc574805b8b0b1513bbd02dcab4) | Ryan Murray | soc: apple: mailbox: only include reachable KUnit tests | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [5611637f6851](https://github.com/aurora-silicon/linux/commit/5611637f685115048c64231e7ac729f23ab20001), [5eff5323da02](https://github.com/aurora-silicon/linux/commit/5eff5323da0282c8fb9adfc57acdc9217e6d7995) | Ryan Murray | soc: apple: mailbox: drain only a present send-empty IRQ | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [56920e3e6752](https://github.com/aurora-silicon/linux/commit/56920e3e675230ced9a2ccab81bb7e9aa9c2ccf0) | Janne Grunau | rust: drm: gpuvm: Add sm_can_merge_flags | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | C,H,M,F | -| [6154ed6d0f41](https://github.com/aurora-silicon/linux/commit/6154ed6d0f410dd69cbb3e218981b6dc549ac5df) | Janne Grunau | rust: drm: file: Use Registered device in DriverFile::open trait | Active — DRM; `drivers/gpu/drm/nova/file.rs` | C,H,M,F | -| [63d3b0f41939](https://github.com/aurora-silicon/linux/commit/63d3b0f419399d027c865d4ccffa12e3617a73b8) | Ryan Murray | drm: apple: afk: factor the receive bounds check into a helper [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [6740c25f03c1](https://github.com/aurora-silicon/linux/commit/6740c25f03c1f552b0bdc0ad5b02926d96dd99ad) | Ryan Murray | drm/asahi: Log G17 firmware recovery causes before acknowledgement [#200](https://github.com/aurora-silicon/linux/pull/200) | Active; carried/refined form — OBS; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | O,F | -| [6803b9328c48](https://github.com/aurora-silicon/linux/commit/6803b9328c483c492e0a26fadf0a7cd03a5fe7cc) | Janne Grunau | rust: drm: gpuvm: GpuVa flags and REPEAT logic | Active — DRM; `rust/kernel/drm/gpuvm/sm_ops.rs` | C,H,M,F | -| [6a127c6ff62c](https://github.com/aurora-silicon/linux/commit/6a127c6ff62cde78267225a7094cda2771504c28) | Janne Grunau | rust: drm: file: Add as_raw() | Active — DRM; `drivers/gpu/drm/nova/file.rs` | C,H,M,F | -| [6db05cf4b231](https://github.com/aurora-silicon/linux/commit/6db05cf4b231f020020f31a479bd45ccff83520f) | DjDeveloperr | drm/shmem-helper: index fault pages by object offset [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [70d9b6f64ee7](https://github.com/aurora-silicon/linux/commit/70d9b6f64ee76e9da96b752ee3933e2d0a66af0b) | Ryan Murray | drm: apple: free property dictionaries the connector does not keep [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/connector.c` | B | -| [72c42b6ddae6](https://github.com/aurora-silicon/linux/commit/72c42b6ddae68c8c58c5f5d720fda5079ae24302) | Janne Grunau | rust: drm: driver: Add feature flags used by asahi | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [765577e012da](https://github.com/aurora-silicon/linux/commit/765577e012da1ee83e6eb56029bdbb9f1f799dce) | Ryan Murray | drm/apple: dptxep: Remove call counters and tidy tunnel comments [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dptxep.c` | B | -| [77a9ab842a02](https://github.com/aurora-silicon/linux/commit/77a9ab842a02e980873a2298caa4dfe8d56faaff) | Ryan Murray | rust: drm: gpuvm: do not leak the VM when exec_lock() fails | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | C,H,M,F | -| [7a155e383d2d](https://github.com/aurora-silicon/linux/commit/7a155e383d2d8e70fd76075ffb7427f4c7a3c326), [c98d2b872a2b](https://github.com/aurora-silicon/linux/commit/c98d2b872a2b02241ce4a34d9fe6841cd32b38c3) | Ryan Murray | soc: apple: mailbox: Keep the send-empty IRQ enable balanced | Active — MBOX; `drivers/soc/apple/mailbox.c` | B,O | -| [7c57598ac57c](https://github.com/aurora-silicon/linux/commit/7c57598ac57cb7804a9f2e89d0975e2005985b96) | Janne Grunau | rust: drm: gem: Support locking gpuva.lock | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [7dce231ad73d](https://github.com/aurora-silicon/linux/commit/7dce231ad73d98e102b4b9e0b362cbab21750854) | DjDeveloperr | drm/syncobj: skip wait hint lookup for ineligible waits [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_syncobj.c` | C,H,M,F | -| [7ed160b9b5f2](https://github.com/aurora-silicon/linux/commit/7ed160b9b5f28df712e98088d4368188b2e28072), [c7df21582810](https://github.com/aurora-silicon/linux/commit/c7df2158281045e6fa9bfa6b7c170910f1089d2e) | Ryan Murray | soc: apple: mailbox: Tidy T8140 comments and resume error logging [#314](https://github.com/aurora-silicon/linux/pull/314) | Active — OBS; `drivers/soc/apple/mailbox.c` | O,F | -| [887533ef3bd8](https://github.com/aurora-silicon/linux/commit/887533ef3bd88de5ec05f93be23d2fefd3570cb5) | Ryan Murray | rust: drm: gem: shmem: wait for backing release instead of failing a lease | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [8cdeb29b542a](https://github.com/aurora-silicon/linux/commit/8cdeb29b542af3cd5ffb3b535330ad4fd67b97a7) | Janne Grunau | HACK: rust: drm: gem: shmem: Make VMap.ptr pub | Active — DRM; `rust/kernel/drm/gem/shmem.rs` | C,H,M,F | -| [9142d428cb69](https://github.com/aurora-silicon/linux/commit/9142d428cb6956aeb36ffebabe42e1a5c2396c2c) | Ryan Murray | drm: apple: afk: bound received queue entries without 32-bit wrap [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [92d02170df1e](https://github.com/aurora-silicon/linux/commit/92d02170df1ecf2273d13ba63c0cedbb891996d3) | Jonathan Goyvaerts | arm64: dts: apple: t6040: Add the GPU [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW | B,P | -| [9429b186dc3e](https://github.com/aurora-silicon/linux/commit/9429b186dc3edb6658bcdd02e451a5cb1c5f0844) | Ryan Murray | rust: drm: report client memory in fdinfo | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [9523159a7288](https://github.com/aurora-silicon/linux/commit/9523159a72886c5169e7bfd566de9c0aa545ba85) | Ryan Murray | soc: apple: clpc: drop the syscon select and the GPU from Kconfig [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [a3828ea8a63d](https://github.com/aurora-silicon/linux/commit/a3828ea8a63d2488f2080dd1f4f6ce8ebd133623) | Asahi Lina | rust: drm: syncobj: Add DRM Sync Object abstraction | Active — DRM; `rust/kernel/drm/mod.rs` | B,M | -| [a6f8817ebbf6](https://github.com/aurora-silicon/linux/commit/a6f8817ebbf6c420aee66897f717ab4e94a4a717) | Ryan Murray | drm/asahi: Reuse fully retired guilty G17 compute queues [#200](https://github.com/aurora-silicon/linux/pull/200) | Active; carried/refined form — REC; `drivers/gpu/drm/asahi/g17/queue/compute.rs` | F,Q | -| [b147e1f460b5](https://github.com/aurora-silicon/linux/commit/b147e1f460b56e398bc085b2457b1ba163cf4505) | Jonathan Goyvaerts | arm64: dts: apple: t6040-j616s: Add the gpu alias [#420](https://github.com/aurora-silicon/linux/pull/420) | Active translated data — FW | B,P | -| [b1f7d09dcf33](https://github.com/aurora-silicon/linux/commit/b1f7d09dcf33e3bb06e81d846783b698d604be5b) | Ryan Murray | drm/apple: dcp: Initialise the start completion before checking RTKit [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [b965be95b07f](https://github.com/aurora-silicon/linux/commit/b965be95b07f46ef0be02f47a3a02017d912e4cc) | Asahi Lina | rust: drm: gpuvm: Add part of the asahi downstream gpuvm abstractions | Active — DRM; `rust/kernel/drm/gpuvm/mod.rs` | B,M | -| [ba69d4dde975](https://github.com/aurora-silicon/linux/commit/ba69d4dde9751976c323055ef683d76febf82a2b) | Ryan Murray | drm: apple: afk: validate the receive write pointer and bound a drain [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/afk.c` | B | -| [c0e5730f8058](https://github.com/aurora-silicon/linux/commit/c0e5730f8058f14c8fdeb5cd96213e57822f7bbb) | Ryan Murray | drm/apple: dcp: Tidy RTKit start-up logging [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [c4722f38cdcc](https://github.com/aurora-silicon/linux/commit/c4722f38cdccca6dbbbc446dfa2d715ab96e9554) | Ryan Murray | arm64: dts: apple: t6040: Do not claim the GPU's PMP report entry at boot [#402](https://github.com/aurora-silicon/linux/pull/402) | Active — PMP | P,B | -| [cd71c1e7ff90](https://github.com/aurora-silicon/linux/commit/cd71c1e7ff901c3c35492ebe5b8bebb0702e5480) | Jonathan Goyvaerts | arm64: dts: apple: t6040-j616s: describe the GPU firmware text segment [#428](https://github.com/aurora-silicon/linux/pull/428) | Active translated data — FW | B,P | -| [d50642d23a7e](https://github.com/aurora-silicon/linux/commit/d50642d23a7edb9ace6837d6471981e84d0d4ef6) | Ryan Murray | iommu: apple-dart: Fix the KUnit test after deferred root publication [#314](https://github.com/aurora-silicon/linux/pull/314) | Active; carried/refined form — DART; `drivers/iommu/apple-dart-test.c` | D,B | -| [d6799a78db13](https://github.com/aurora-silicon/linux/commit/d6799a78db13ad06a2f26b66aad97c7e7626714d) | Ryan Murray | drm/apple: dcp: Initialise work items at probe [#345](https://github.com/aurora-silicon/linux/pull/345) | Active; carried/refined form — DISPLAY; `drivers/gpu/drm/apple/dcp.c` | B | -| [d8b45282c1e7](https://github.com/aurora-silicon/linux/commit/d8b45282c1e70cb4b947d2aadfb2636fd4ee763a) | Lyude Paul | rust: drm: gem: Add BaseObject::prime_export() | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [defdcb801774](https://github.com/aurora-silicon/linux/commit/defdcb8017744fe0aa57061ed304e793935b52bc) | Ryan Murray | soc: apple: build the CLPC floors by default [#219](https://github.com/aurora-silicon/linux/pull/219) | Active; carried/refined form — CLPC; `drivers/soc/apple/Kconfig` | P,C,R,I | -| [e1468f83c1da](https://github.com/aurora-silicon/linux/commit/e1468f83c1daf236b69c6868a3a05a9d6f994f9b) | Janne Grunau | rust: drm: gem: Add missing trailing '//' for kernel vertical style | Active — DRM; `rust/kernel/drm/gem/mod.rs` | C,H,M,F | -| [e6d369606edf](https://github.com/aurora-silicon/linux/commit/e6d369606edff3c24dc3b1f5dda036cc77a8887c) | Ryan Murray | drm/shmem: revoke CPU PFNs before releasing purge backing [#171](https://github.com/aurora-silicon/linux/pull/171) | Active; carried/refined form — DRM; `drivers/gpu/drm/drm_gem_shmem_helper.c` | C,H,M,F | -| [f0a8afc04957](https://github.com/aurora-silicon/linux/commit/f0a8afc0495743e502fc860fa2bc0fc96e95b22a) | Sami Tolvanen | rust: drm: add a registration guard for the Normal device context | Active — DRM; `rust/kernel/drm/device.rs` | C,H,M,F | -| [fd2a0321db11](https://github.com/aurora-silicon/linux/commit/fd2a0321db11572ac201663697c83c9330ef65a3) | DjDeveloperr | driver core: track devres node membership for direct removal [#390](https://github.com/aurora-silicon/linux/pull/390) | Active — DRM; `drivers/base/base.h` | B,M | - -### N/A, superseded, other-backend and imported-neighbor records - -These scoped candidates are included to make exclusions reviewable. A shared -path query or an omnibus PR is not evidence of a Neo performance improvement. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [4f772d2c2d6c](https://github.com/aurora-silicon/linux/commit/4f772d2c2d6cb336d4df08ae6c554b8387510c20) | Janne Grunau | drm/asahi: initdata: Fold GlobalsSub struct into Globals | Not applicable — LEGACY; `drivers/gpu/drm/asahi/fw/initdata.rs` | V | -| [532ac90e08af](https://github.com/aurora-silicon/linux/commit/532ac90e08affc3bbcf59e273e00f1573b7a05d0) | Janne Grunau | drm/asahi: Avoid variable/field ref shadowing in pin-init | Not applicable — LEGACY; `drivers/gpu/drm/asahi/initdata.rs` | V | -| [253d85ab9854](https://github.com/aurora-silicon/linux/commit/253d85ab98543f838ecc6be70edb7a43d966d505) | Sasha Finkelstein | drm/asahi: starlight-debug | Not applicable — LEGACY; `drivers/gpu/drm/asahi/gpu.rs` | V | -| [83526ea43d4f](https://github.com/aurora-silicon/linux/commit/83526ea43d4fffdb10a3dff36a37a587ffaa6c14) | Janne Grunau | drm/asahi: workqueue: Drop completed work items | Not applicable — LEGACY; `drivers/gpu/drm/asahi/workqueue.rs` | V | -| [b1e32124e9e9](https://github.com/aurora-silicon/linux/commit/b1e32124e9e94ebd3e1345eb54f687fcfbfee509) | Janne Grunau | drm/asahi: rustfmt | Not applicable — VERIFY; `drivers/gpu/drm/asahi/mmu.rs` | V | -| [8508e5105997](https://github.com/aurora-silicon/linux/commit/8508e5105997a43be75e8a3ffe0c3d8ddc00155c), [e092d51bc9d7](https://github.com/aurora-silicon/linux/commit/e092d51bc9d773f7058fe578515c5f915c0adf2c) | Yureka Lilian | pmdomain: add pmp-report offsets for t6030,t8122 | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [357978884c89](https://github.com/aurora-silicon/linux/commit/357978884c895e5fc35af84fed8adf0583bc3353), [a89f7da611ad](https://github.com/aurora-silicon/linux/commit/a89f7da611ade4b9d5f40dd45fe5b41d059e3399) | Yureka Lilian | arm64: dts: apple: add minimal MacBook Neo device tree | Not applicable — PERIPH | V | -| [dfe1431f40cf](https://github.com/aurora-silicon/linux/commit/dfe1431f40cf15ec4aebd1864b4c69707b3c43c2), [b796a047ec25](https://github.com/aurora-silicon/linux/commit/b796a047ec253074e2cd6b5f38a8f19949b50271), [9359ea48b718](https://github.com/aurora-silicon/linux/commit/9359ea48b7184cdee39b7c76b5f0d4a923807cf3) | Ryan Murray | arm64: dts: apple: Add T8140/J700 device trees with audio and camera | Not applicable — PERIPH | V | -| [0d31fa4418ec](https://github.com/aurora-silicon/linux/commit/0d31fa4418ec7c18ab984d6cfb0c4d10b80a0af1), [bffb1ed450d5](https://github.com/aurora-silicon/linux/commit/bffb1ed450d58d0c19f9e312c8b0c2314b9f1c53), [d575cca893bc](https://github.com/aurora-silicon/linux/commit/d575cca893bce9bedb5375be6bb8c209991faec6) | Ryan Murray | arm64: dts: apple: t8140: Add SPMI controller and PMIC NVMEM cells | Not applicable — PERIPH | V | -| [780ab337fd92](https://github.com/aurora-silicon/linux/commit/780ab337fd92e4511f4e4ee698820ae15d007cbc), [368b5343b9f7](https://github.com/aurora-silicon/linux/commit/368b5343b9f7c69683ee5a0c5239a6f96e8177fd), [c3874394cec6](https://github.com/aurora-silicon/linux/commit/c3874394cec613afc6b5c8615eae5cdd013e558c) | Ryan Murray | arm64: dts: apple: t8140: Add SMC node | Not applicable — PERIPH | V | -| [53296a0f9b6e](https://github.com/aurora-silicon/linux/commit/53296a0f9b6eae07ebce8a55c8b16309d87b2656), [985ee0213ef3](https://github.com/aurora-silicon/linux/commit/985ee0213ef3154c4d8c9763157f9620a7ce0243), [b8850ad18ff8](https://github.com/aurora-silicon/linux/commit/b8850ad18ff8d0a489c810fdafece6b8349f8694) | Ryan Murray | arm64: dts: apple: t8140: Add ANS2 NVMe controller | Not applicable — PERIPH | V | -| [4767bc0b221c](https://github.com/aurora-silicon/linux/commit/4767bc0b221cce5fb0c20dbacffe6f6bca7bc4a0), [5b9145de86c1](https://github.com/aurora-silicon/linux/commit/5b9145de86c13364ed3b9d465334674e7dc87083), [0b9461d4be5a](https://github.com/aurora-silicon/linux/commit/0b9461d4be5a77c0c74138900b8b92a7e193f8bb) | Ryan Murray | arm64: dts: apple: t8140-j700: Name the ALS calibration file | Not applicable — PERIPH | V | -| [2b45c6011879](https://github.com/aurora-silicon/linux/commit/2b45c601187962fca0b9289fdb1408e36ef5f838), [613b821cb4bb](https://github.com/aurora-silicon/linux/commit/613b821cb4bb48ccb999f75c4d5815f094f095be), [aefc56975b57](https://github.com/aurora-silicon/linux/commit/aefc56975b57d0e07a4a3e92d7e7af85f0a45cb4) | Ryan Murray | arm64: dts: apple: t8140-pmgr: Add ATC0 and nub SPMI A0 power domains | Not applicable — PERIPH | V | -| [e5992bd6f02c](https://github.com/aurora-silicon/linux/commit/e5992bd6f02c42e2e7404be54a41d8acaf685bb4), [dc6bc1f1613f](https://github.com/aurora-silicon/linux/commit/dc6bc1f1613f7e836b9514f40c07cb424622fca1), [0e335bcc4a79](https://github.com/aurora-silicon/linux/commit/0e335bcc4a799cc546ff5a6e9d5cdde644a53eea) | Ryan Murray | arm64: dts: apple: t8140: Add the MTP coprocessor and DockChannel HID nodes | Not applicable — PERIPH | V | -| [601fe7359e94](https://github.com/aurora-silicon/linux/commit/601fe7359e94f9f527487f2d1725cbfad8ea1ff2), [2d6ae0d0f507](https://github.com/aurora-silicon/linux/commit/2d6ae0d0f5073b6e29cb970926855de13d24a770), [895980a58c46](https://github.com/aurora-silicon/linux/commit/895980a58c46a6a1ec2a4e2bb2d5b9e815d4b349) | Ryan Murray | arm64: dts: apple: t8140: Add the USB-C controller, ATC PHY and SPMI A0 bus | Not applicable — PERIPH | V | -| [addbb17c2a81](https://github.com/aurora-silicon/linux/commit/addbb17c2a810bcaa1d68f6f9bc8e7fb401a508a), [7d1387799cba](https://github.com/aurora-silicon/linux/commit/7d1387799cba4442ba7ea99a95a962535cf26fc2), [7ded6b918bd3](https://github.com/aurora-silicon/linux/commit/7ded6b918bd3436fa2dc81b8b65f336bbe66ae85) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the keyboard and trackpad | Not applicable — PERIPH | V | -| [70f40a78d8ea](https://github.com/aurora-silicon/linux/commit/70f40a78d8ea8db8b300d3d084b4228b3e172f19), [c94e793fea2a](https://github.com/aurora-silicon/linux/commit/c94e793fea2ad398c3aade3d3649ebc377189ec2), [b8f170b9347b](https://github.com/aurora-silicon/linux/commit/b8f170b9347ba943a11a30f6642a9532758965e4) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the USB-C ports | Not applicable — PERIPH | V | -| [ea013658bf93](https://github.com/aurora-silicon/linux/commit/ea013658bf93d944617d01034cd7a5a3ece105a8), [e5a7b83611cc](https://github.com/aurora-silicon/linux/commit/e5a7b83611ccc434923524ea7bfb27f4e9c2a2ec), [09b788437876](https://github.com/aurora-silicon/linux/commit/09b788437876d50bf0d13d0d8cf7bfe9487a934b) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the USB DARTs | Not applicable — PERIPH | V | -| [a97766963d24](https://github.com/aurora-silicon/linux/commit/a97766963d247d039cd76be83fd896b895e1ad2b), [e499013c56ad](https://github.com/aurora-silicon/linux/commit/e499013c56ad475dd45866c64e28dd33f95235c3), [d880e057bc1e](https://github.com/aurora-silicon/linux/commit/d880e057bc1e250d54a0b7dc2db23928f802a1d0) | Ryan Murray | arm64: dts: apple: t8140: Add the SMC RTC | Not applicable — PERIPH | V | -| [50e24690d43e](https://github.com/aurora-silicon/linux/commit/50e24690d43e525c1b2b217aa828a18e4c6503b9), [21ab6edf3da3](https://github.com/aurora-silicon/linux/commit/21ab6edf3da3111ed771155a9dbd2c83118cd0dc), [e90d32748ea7](https://github.com/aurora-silicon/linux/commit/e90d32748ea7857d242afc714365949e9ad86a3b) | Ryan Murray | arm64: dts: apple: t8140-j700: Describe the remaining SMC temperatures | Not applicable — PERIPH | V | -| [2cb796ddf423](https://github.com/aurora-silicon/linux/commit/2cb796ddf423b6d76e9d2ab1231f0b48ddbc2614), [e8d16b77d690](https://github.com/aurora-silicon/linux/commit/e8d16b77d6901f18a468d3d1b636990aa97f89cd), [23b613dfe8e7](https://github.com/aurora-silicon/linux/commit/23b613dfe8e757e1b599dc7cdfb7f9717687dc21) | Ryan Murray | arm64: dts: apple: t8140-j700: Describe the SMC current, power and voltage rails | Not applicable — PERIPH | V | -| [0cd1a28f2113](https://github.com/aurora-silicon/linux/commit/0cd1a28f2113c72a53052fb2733c2aced2f54476), [c2845ec53a91](https://github.com/aurora-silicon/linux/commit/c2845ec53a915dcadc4e68bbd59f97ca0764ddd6) | DjDeveloperr | iommu: apple-dart: support tunneled PCIe-C DMA aliases | Not applicable — TUNNEL; `drivers/iommu/Kconfig` | V | -| [6ff009379755](https://github.com/aurora-silicon/linux/commit/6ff00937975526780a22aa763211ba612f042997), [ee60f6cdcff8](https://github.com/aurora-silicon/linux/commit/ee60f6cdcff8561bff5ec48b10ba2a536a23ed9f) | DjDeveloperr | iommu: apple-dart: support retained PCIe-C tunnel domains | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [05ae2b2dfc28](https://github.com/aurora-silicon/linux/commit/05ae2b2dfc2853d7ae0f797d6299661e957116f3), [5987e8a08203](https://github.com/aurora-silicon/linux/commit/5987e8a08203974fe539aed3ce2de8ad5a3990a7) | Ryan Murray | arm64: dts: apple: t8140: Describe observed behaviour, not other implementations | Not applicable — VERIFY | V | -| [61f979fc1825](https://github.com/aurora-silicon/linux/commit/61f979fc18256a03db72933dde7f356a44f31eb2), [bf3cb50f012f](https://github.com/aurora-silicon/linux/commit/bf3cb50f012f9ecaeb465e861d8e896e580a69a0), [4fa6c2b053a6](https://github.com/aurora-silicon/linux/commit/4fa6c2b053a65088ca20641480fd9ed8da55716e) | Ace | arm64: dts: apple: Add diagnostic J700 PCIe root-port topology | Not applicable — PERIPH | V | -| [c309c0ebb058](https://github.com/aurora-silicon/linux/commit/c309c0ebb058bf6cd1df2503d121ace539448ecc), [5a4974fde407](https://github.com/aurora-silicon/linux/commit/5a4974fde40748a151a4c23c0df730f1148bc2df) | Ace | arm64: dts: apple: t8140-j700: enable bounded PCIe endpoint bootstrap and enumeration | Not applicable — PERIPH | V | -| [56e442c7cbbe](https://github.com/aurora-silicon/linux/commit/56e442c7cbbe49c2613a5209fbcf772e90bec10e), [716b60de9620](https://github.com/aurora-silicon/linux/commit/716b60de96207e43d3c06eeb9c424f147a5d16a3), [8a03c5341e27](https://github.com/aurora-silicon/linux/commit/8a03c5341e27e9066e15f924e88aa44f848b5294) | DjDeveloperr | arm64: dts: apple: enable AVD on T8140 | Not applicable — PERIPH | V | -| [2b9ef0954320](https://github.com/aurora-silicon/linux/commit/2b9ef0954320320edbee5b75e742176aef3ee8b3), [6f57627a710e](https://github.com/aurora-silicon/linux/commit/6f57627a710e655f30ec73ece845d18c52663d78), [4088c3b1854c](https://github.com/aurora-silicon/linux/commit/4088c3b1854cdbaf106d8bfe72510551bf9fd43c) | Ryan Murray | arm64: dts: apple: t8140: add disabled display power domains | Not applicable — PERIPH | V | -| [7e14b8e9e9a2](https://github.com/aurora-silicon/linux/commit/7e14b8e9e9a2bcb983725fc9a0cb3c016a5ed12b), [1b05c65c4276](https://github.com/aurora-silicon/linux/commit/1b05c65c42763d955c7ca69ef849d6bf5fac7355), [004200ec1cc8](https://github.com/aurora-silicon/linux/commit/004200ec1cc8005fa692d797d2c5fb009ec9e05a) | Ryan Murray | arm64: dts: apple: t8140: add disabled internal display DARTs | Not applicable — PERIPH | V | -| [d7de8bb51e4f](https://github.com/aurora-silicon/linux/commit/d7de8bb51e4f654b1c1d33c8cabd3290a9e231ea), [0c29d4d4a4ea](https://github.com/aurora-silicon/linux/commit/0c29d4d4a4ea28e024596f605676dc0d1d1e3ba0), [d2f162f6d7c2](https://github.com/aurora-silicon/linux/commit/d2f162f6d7c24ed783657112086f7b56e1fb0cbe) | Ryan Murray | arm64: dts: apple: t8140: add disabled external display DARTs | Not applicable — PERIPH | V | -| [7a28ede30a1f](https://github.com/aurora-silicon/linux/commit/7a28ede30a1ff3894d8f2407ba657d51e8d9bd95), [042b2a224bf6](https://github.com/aurora-silicon/linux/commit/042b2a224bf671bacb56b6e5345b3eb399c7ec02), [aec8cb1999f7](https://github.com/aurora-silicon/linux/commit/aec8cb1999f731bbe1895509dbcc6e2fed977348) | Ryan Murray | arm64: dts: apple: t8140: Add the SEP, its DART and mailbox, and SPI2 | Not applicable — PERIPH | V | -| [07029412ae8d](https://github.com/aurora-silicon/linux/commit/07029412ae8d5832c1323d3eeb8a08b09f7b5be0), [1eb7bfe18b01](https://github.com/aurora-silicon/linux/commit/1eb7bfe18b01c0a088dd8e25a72ee5af3a09531a), [29987787b923](https://github.com/aurora-silicon/linux/commit/29987787b9238b15b41b92da87e5fcbf8a571e8c) | Ryan Murray | arm64: dts: apple: t8140-j700: Enable the SEP and the Touch ID sensor | Not applicable — PERIPH | V | -| [7d84216f74e8](https://github.com/aurora-silicon/linux/commit/7d84216f74e8e9e5827eabc9f173524ce5520c9b), [6049af950206](https://github.com/aurora-silicon/linux/commit/6049af950206644d95b8cd3ca11fe0722ff71257), [52f1ba512244](https://github.com/aurora-silicon/linux/commit/52f1ba51224431d256250c69784e1996f6ee63cc) | Acelogic | arm64: dts: apple: wire the J700 AVE encoder | Not applicable — PERIPH | V | -| [5f1fbb7bd670](https://github.com/aurora-silicon/linux/commit/5f1fbb7bd670ca8a26c303594f9ed54535e51f02), [519558a43644](https://github.com/aurora-silicon/linux/commit/519558a43644d79c2cc15135554748ffe6fadc81), [f898b116beaa](https://github.com/aurora-silicon/linux/commit/f898b116beaaab7add264a0f074b21743875d3ae) | Ryan Murray | arm64: dts: apple: Describe additional T8140 peripheral power states | Not applicable — PERIPH | V | -| [555932c62f03](https://github.com/aurora-silicon/linux/commit/555932c62f03ec2833c5db9b39e2d2dc956501cb), [ed2ef28706b7](https://github.com/aurora-silicon/linux/commit/ed2ef28706b7c2ed13aef2f90eb7191b4e34338e), [f75a1041fca4](https://github.com/aurora-silicon/linux/commit/f75a1041fca487774f29b133f736296f4d73a4e3) | Ryan Murray | arm64: dts: apple: Wire up remaining supported J700 peripherals | Not applicable — PERIPH | V | -| [a3d7465380ff](https://github.com/aurora-silicon/linux/commit/a3d7465380ffbf5f9cb4eddb550fabfdd71d3a17), [49fdcbcee4f4](https://github.com/aurora-silicon/linux/commit/49fdcbcee4f4569e6b65f7912e05502a38299743) | Ryan Murray | arm64: dts: apple: describe the J700 PMU alarm function | Not applicable — PERIPH | V | -| [d810cb82e82d](https://github.com/aurora-silicon/linux/commit/d810cb82e82de69013754b6031d00a83a6d15e41), [4e0543ee6caf](https://github.com/aurora-silicon/linux/commit/4e0543ee6cafb4250aaf332f894773412b86dfe2), [b9a339703e95](https://github.com/aurora-silicon/linux/commit/b9a339703e95a6a65e0e4515caa4c4f6afb0d9ce) | Ryan Murray | arm64: dts: apple: describe the disabled T8140 Neural Engine | Not applicable — PERIPH | V | -| [19f7cbdd84fe](https://github.com/aurora-silicon/linux/commit/19f7cbdd84fef12ca56aad9b654b46465cc2e198), [6b57d5423048](https://github.com/aurora-silicon/linux/commit/6b57d5423048ac4c70cd99d7473494ac3d37b2db), [93bc234385f5](https://github.com/aurora-silicon/linux/commit/93bc234385f5bf51b276e9d2e5abe8280e2ff92c) | Ryan Murray | arm64: dts: apple: t8140: Leave display coprocessor power to firmware | Not applicable — PERIPH | V | -| [0f5548d142b1](https://github.com/aurora-silicon/linux/commit/0f5548d142b1d73c44d270c91d5c359272dae499), [7c3c5ee5a070](https://github.com/aurora-silicon/linux/commit/7c3c5ee5a0702bb5b9f0ae4cde6b837cbafa3485), [9e6acbbd21ba](https://github.com/aurora-silicon/linux/commit/9e6acbbd21ba92409dd4f24074532b0bad997792) | Ryan Murray | arm64: dts: apple: t8140: Describe the internal display coprocessor | Not applicable — PERIPH | V | -| [100ff1ebedd3](https://github.com/aurora-silicon/linux/commit/100ff1ebedd337758a4ff3ba3fd3f2f46a9f5be9), [45ae8211efea](https://github.com/aurora-silicon/linux/commit/45ae8211efeafe3bff64b569370942c5218f1fec), [061370b4c70f](https://github.com/aurora-silicon/linux/commit/061370b4c70fd888ea6dc520a8988208f4aebca8) | Ryan Murray | arm64: dts: apple: t8140: Hand the J700 panel over to the DCP | Not applicable — PERIPH | V | -| [29f8091fe351](https://github.com/aurora-silicon/linux/commit/29f8091fe351a0cdb781cf18ac5748ca15feca42), [4f3906d225f4](https://github.com/aurora-silicon/linux/commit/4f3906d225f44739df672ac0b76715407f52e586), [a7fa3d8fbf56](https://github.com/aurora-silicon/linux/commit/a7fa3d8fbf5690df6553896a4f984b8cdc8069c2) | Ryan Murray | arm64: dts: apple: t8140: describe each power state once | Not applicable — PERIPH | V | -| [89c54797ae77](https://github.com/aurora-silicon/linux/commit/89c54797ae77fea8e8878a68e0b56f382cfb0409), [07969983cb1e](https://github.com/aurora-silicon/linux/commit/07969983cb1edefaec1b4b0aabb2307b0b14dacd), [953220ab6d74](https://github.com/aurora-silicon/linux/commit/953220ab6d748bd05db3854f374b701696f6c795) | Ryan Murray | arm64: dts: apple: t8140: describe the external display DARTs once | Not applicable — PERIPH | V | -| [55a5beb425ae](https://github.com/aurora-silicon/linux/commit/55a5beb425ae7c901851c2185e3219d8c0348fcb), [f0234a79d172](https://github.com/aurora-silicon/linux/commit/f0234a79d172479cb7dbcdb713daa5739ad87f74), [c80113dfaab9](https://github.com/aurora-silicon/linux/commit/c80113dfaab9e985b9f617bfde06c481fd17376c) | Ryan Murray | arm64: dts: apple: t8140-j700: give the two RTCs fixed numbers | Not applicable — PERIPH | V | -| [9e1fb240e1df](https://github.com/aurora-silicon/linux/commit/9e1fb240e1df4064a9232007daa5c8797dfbcda4), [19e2b5adfe69](https://github.com/aurora-silicon/linux/commit/19e2b5adfe6905ab2f3fff6ad1a12801d711c607), [ea044d49c76c](https://github.com/aurora-silicon/linux/commit/ea044d49c76c18079848672c2779c7521a6b8fc3) | Ryan Murray | arm64: dts: apple: t8140: Keep the GPIO power state on for the SEP | Not applicable — PERIPH | V | -| [4334bbd7162a](https://github.com/aurora-silicon/linux/commit/4334bbd7162af085ed1c8c7b63859bed8c6646ef), [f1c076a9bf8a](https://github.com/aurora-silicon/linux/commit/f1c076a9bf8a850bec0140fb3e91a9607aadcf4e), [30812f491575](https://github.com/aurora-silicon/linux/commit/30812f491575ede27e5be059fd6afc4e985166f1) | DjDeveloperr | arm64: dts: apple: t8140-j700: keep the DCS rail out of thermal control | Not applicable — DCSOFF | P,R | -| [baacaf604632](https://github.com/aurora-silicon/linux/commit/baacaf60463212b2270f0ad0b50cdabe4e27ab6d), [071651bd5c30](https://github.com/aurora-silicon/linux/commit/071651bd5c30330ecb9980c3c1f2cc4e2f04d1a6), [40a9c929c55f](https://github.com/aurora-silicon/linux/commit/40a9c929c55f2b13c39e732fc2ae3f10e1506634) | Ryan Murray | arm64: dts: apple: describe disabled J700 external resources | Not applicable — PERIPH | V | -| [13af1cb29b95](https://github.com/aurora-silicon/linux/commit/13af1cb29b95b1fc260870868d3c54a596cc483d), [f284458cdfc3](https://github.com/aurora-silicon/linux/commit/f284458cdfc33d2746bb4ede9174adc3afaa2f7f) | Ryan Murray | arm64: dts: apple: t8140: describe the external binding the display master recognizes | Not applicable — PERIPH | V | -| [a7f9b86ea187](https://github.com/aurora-silicon/linux/commit/a7f9b86ea18778f313b73cd174debe54e4dbc09c), [cffe838aca8e](https://github.com/aurora-silicon/linux/commit/cffe838aca8e275526730bd6f3fee5ebcaec0c47), [205a56d33cb0](https://github.com/aurora-silicon/linux/commit/205a56d33cb07184d7dfe17ab8aba0996cff3efe) | Ryan Murray | arm64: dts: apple: retain the inherited external display supply | Not applicable — PERIPH | V | -| [328dacb9d1ad](https://github.com/aurora-silicon/linux/commit/328dacb9d1adcbc1be84e8dae660c72bc12a3005), [3d16013f9795](https://github.com/aurora-silicon/linux/commit/3d16013f979572f7f7f6d1573f2af739e8ac25b4), [2e6003f6db07](https://github.com/aurora-silicon/linux/commit/2e6003f6db07b0e0a6b2bf2b977753bee47556b0) | Ryan Murray | arm64: dts: apple: add an explicit external display trial tree | Not applicable — PERIPH | V | -| [6b82a41053b8](https://github.com/aurora-silicon/linux/commit/6b82a41053b87c8bd0917f72f71778293aa7f276), [70cce5cd20ef](https://github.com/aurora-silicon/linux/commit/70cce5cd20efb8a71d49563b45481c32e0de23a6), [0a0d25f4a99b](https://github.com/aurora-silicon/linux/commit/0a0d25f4a99b66a08a2ab4a22314782aaad7b3e2) | DjDeveloperr | arm64: dts: apple: t8140-j700: drive the SPI NOR on a single data line | Not applicable — PERIPH | V | -| [d56b7ce044f2](https://github.com/aurora-silicon/linux/commit/d56b7ce044f274b153a3b1f9192d3fd4c7cb2d85), [df94160d7567](https://github.com/aurora-silicon/linux/commit/df94160d756756e14d4bc818fe0652bcdb9adc30) | DjDeveloperr | arm64: dts: apple: t8140-j700: enable the validated external display profile by default | Not applicable — PERIPH | V | -| [f9e24b02bc85](https://github.com/aurora-silicon/linux/commit/f9e24b02bc8547acba1453cf462f0f210e707ba7), [be5f3162c985](https://github.com/aurora-silicon/linux/commit/be5f3162c9854d6b5ea8ca9e8f29f764b2c6251b) | Eryk Wieliczko | arm64: dts: apple: t8140: mark firmware-owned power domains | Not applicable — PERIPH | V | -| [7df682a70733](https://github.com/aurora-silicon/linux/commit/7df682a707337025aad3c093252ea7f8504e8345), [b0714e8783f6](https://github.com/aurora-silicon/linux/commit/b0714e8783f685f213c15890c7942c1c03d6c1e3) | Chris Kearney | PCI: apple: enumerate Thunderbolt PCIe on t8103 | Not applicable — LEGACY; `drivers/iommu/apple-dart.c` | V | -| [4c02ff022799](https://github.com/aurora-silicon/linux/commit/4c02ff022799be8aef47108a61671a6a6cd86038), [b388a175a612](https://github.com/aurora-silicon/linux/commit/b388a175a612be6c5d10056c6a10a7219030272d) | Chris Kearney | PCI: apple: finish tunneled IOMMU commands before the port clock stops | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [9e8a900fee27](https://github.com/aurora-silicon/linux/commit/9e8a900fee275872aa1019df27a4944b73c8940a), [a2b13c1f0369](https://github.com/aurora-silicon/linux/commit/a2b13c1f03696ae69101c8ed51b8901d32dffcd4), [5a7b76f31c3a](https://github.com/aurora-silicon/linux/commit/5a7b76f31c3a8ccdc48fd586e5b646fa0c49499d) | Chris Kearney | iommu/apple-dart: enforce command gating during tunnel teardown | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [39e90a052954](https://github.com/aurora-silicon/linux/commit/39e90a052954d1305a45ca0065eda42ec4aff639), [d15623fd3261](https://github.com/aurora-silicon/linux/commit/d15623fd32614870a9eb62d25afdd823a39bcde7), [65e3e0ed688a](https://github.com/aurora-silicon/linux/commit/65e3e0ed688a5a933a60d92ca79b6136c357b876) | Chris Kearney | iommu/apple-dart: report tunnel command-resume failures | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [3a94483e259c](https://github.com/aurora-silicon/linux/commit/3a94483e259cbc8d0aab638eaa4af5b72c4db6e6), [6e0c3cdf7855](https://github.com/aurora-silicon/linux/commit/6e0c3cdf78550987513b0d4c15ffec90b442b787), [64dfa24ca989](https://github.com/aurora-silicon/linux/commit/64dfa24ca989fec06367a7199164a70de7d99e35) | Chris Kearney | PCI: apple: describe tunneled PM ordering by Linux dependencies | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [5d4dd51e2769](https://github.com/aurora-silicon/linux/commit/5d4dd51e27695b5d9570e56b050e3574dfc1fd38), [e7292daedcaa](https://github.com/aurora-silicon/linux/commit/e7292daedcaa2186e5b8b484343dc3ec239b2805), [615be505e22c](https://github.com/aurora-silicon/linux/commit/615be505e22c592c1a87c193b22c58dc4c064840) | Chris Kearney | thunderbolt: restore M1 tunneled PCIe state and recover late link loss | Not applicable — TUNNEL; `drivers/iommu/apple-dart-test.c` | V | -| [95caa2cf7ac7](https://github.com/aurora-silicon/linux/commit/95caa2cf7ac7244080527b90da0d43ec917e1513), [92f33b680514](https://github.com/aurora-silicon/linux/commit/92f33b6805149c955b543a6e2c29f88c42886f6d), [fc559d251fca](https://github.com/aurora-silicon/linux/commit/fc559d251fcac7e904607a36fb4b17770e29f239) | Acelogic | irqchip/apple-aic: use architectural guest timer masks on T8142 | Not applicable — OTHERCHIP; `drivers/irqchip/irq-apple-aic.c` | V | -| [4d1bcf62c1af](https://github.com/aurora-silicon/linux/commit/4d1bcf62c1af6fa29a32e94d821f4174098cbd29), [4ae1f9604a1a](https://github.com/aurora-silicon/linux/commit/4ae1f9604a1aa503dd1b452578bf694dbadaca25), [40bc3b97c1d6](https://github.com/aurora-silicon/linux/commit/40bc3b97c1d6a75ff5f8af9bc75322388a5381e1) | DjDeveloperr | soc: apple: rtkit-helper: adopt a running T8140 MTP session | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [ad7993e04cd2](https://github.com/aurora-silicon/linux/commit/ad7993e04cd2e39c4fe011740268a537868bb8c0), [58a792863c4f](https://github.com/aurora-silicon/linux/commit/58a792863c4fdd79342e5e83ece8f652993084ab), [80cabfefcdc5](https://github.com/aurora-silicon/linux/commit/80cabfefcdc52036a7902268ff42f2a9370fe5c2) | Acelogic | cpufreq: apple: Add bounded T8152 E and P/M performance domains | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [81aefe80b586](https://github.com/aurora-silicon/linux/commit/81aefe80b586fa545b20eb90090202cde51718e7), [48f073156423](https://github.com/aurora-silicon/linux/commit/48f0731564236dc79c43bbcdadf6b05cfd807e8a), [296dbb45adff](https://github.com/aurora-silicon/linux/commit/296dbb45adff8654c6f1f8029e7b6b567f990e0b) | Acelogic | cpufreq: apple: add T8142 command-state transitions | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [4c3405d11d29](https://github.com/aurora-silicon/linux/commit/4c3405d11d29ec8a49a14bdc546cef4411153b32), [b08be27ef235](https://github.com/aurora-silicon/linux/commit/b08be27ef235dfedb3d18cf4a91a821be8a7effc) | Ryan Murray | cpufreq: apple: retain the unmanaged P-state ceiling on T8152 | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [24f4a32e8ec9](https://github.com/aurora-silicon/linux/commit/24f4a32e8ec9438b198e7ca97658154bcaedc6f7), [129471fc83b8](https://github.com/aurora-silicon/linux/commit/129471fc83b89e08275048a812779583ef197a93), [c0bd8b9fec16](https://github.com/aurora-silicon/linux/commit/c0bd8b9fec163274b9e6056ae94fe54d53b565fb), [b4ee9bd8d923](https://github.com/aurora-silicon/linux/commit/b4ee9bd8d923949b19cc22484262670948cafc57) | DjDeveloperr | drm/asahi: clarify the opening polling budget [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/mod.rs` | V | -| [52f6e8610625](https://github.com/aurora-silicon/linux/commit/52f6e86106255b26e84671649c5f4acb0f434cde), [840488b0b60d](https://github.com/aurora-silicon/linux/commit/840488b0b60d3162e92f050cc59a2b3967036544), [66631bc63295](https://github.com/aurora-silicon/linux/commit/66631bc632956bb7dfd1b4fb44e48ae90a10140e), [d0aadc1e99e6](https://github.com/aurora-silicon/linux/commit/d0aadc1e99e6f11a54bbca5ee685d7c015866789) | DjDeveloperr | drm/asahi: describe the G17 word tables without their generation history [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/fw/initdata.rs` | V | -| [1c771d73ac6c](https://github.com/aurora-silicon/linux/commit/1c771d73ac6c5e953be9582f1b74ccb358e6322d), [d24b1a49853f](https://github.com/aurora-silicon/linux/commit/d24b1a49853fe6949b44790761678cd2d38e623e), [a6e06b47b49d](https://github.com/aurora-silicon/linux/commit/a6e06b47b49d2666a53b5bc45ba8e0fa22e74944) | Joshua Warren | drm/asahi: Add stats_export module parameter | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [3f096100f658](https://github.com/aurora-silicon/linux/commit/3f096100f658c1563dafaa0f0ca8b77ea2a87fe3), [f436b4da5480](https://github.com/aurora-silicon/linux/commit/f436b4da5480140e5ba95d68e46f1e7dd7615db8) | Ryan Murray | drm/asahi: tie stats registration to a per-device snapshot owner | Not applicable — STAT; `drivers/gpu/drm/asahi/g17/mod.rs` | T | -| [fd13851e08b6](https://github.com/aurora-silicon/linux/commit/fd13851e08b689661332ee823ad65eafd4418c1a), [c91a9274e4b2](https://github.com/aurora-silicon/linux/commit/c91a9274e4b2736d5589826b07c8dc54c0e35055) | Ryan Murray | drm/asahi: describe the G17 tiler-heap shrink policy in hardware terms | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/buffer.rs` | V | -| [af5c7b24a0e5](https://github.com/aurora-silicon/linux/commit/af5c7b24a0e5932026c8cbab8633f2563bf761ba), [f0ec35d78e5a](https://github.com/aurora-silicon/linux/commit/f0ec35d78e5adf9988c1bc71418d0a764c8d4ba3), [337b14463d50](https://github.com/aurora-silicon/linux/commit/337b14463d5010296efb0b17dfaa11b8f7601aae) | Ryan Murray | arm64: dts: apple: t8140: Fold the trailing soc override into the soc node [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH | V | -| [3cd89c634a60](https://github.com/aurora-silicon/linux/commit/3cd89c634a60071014683a27d497e46b8e2e2fc5), [f5ba7b6ee41c](https://github.com/aurora-silicon/linux/commit/f5ba7b6ee41ca4545745bfcc312fdbc0abf3e491), [6f1b4ab6f2f0](https://github.com/aurora-silicon/linux/commit/6f1b4ab6f2f036dedd104b83df774d6284ecab74) | Ryan Murray | arm64: dts: apple: t8140: Tidy the mailbox and pinctrl comments [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH | V | -| [553e961d56c9](https://github.com/aurora-silicon/linux/commit/553e961d56c9ecbf6d58561c98468496955ad1d3), [38dd24cdc5a3](https://github.com/aurora-silicon/linux/commit/38dd24cdc5a3e13555afcac85f28d8ca3fc77a8e), [742366203cc8](https://github.com/aurora-silicon/linux/commit/742366203cc8a1f9356d82a43d52e2cb6fa97621) | Ryan Murray | pmdomain: apple: pmp-report: remove the raw DVFS debugfs dump [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — RAWDIAG; `drivers/pmdomain/apple/pmp-report.c` | O | -| [d04cbb892d26](https://github.com/aurora-silicon/linux/commit/d04cbb892d26dca250de4ff6f8c6cde5446682fb), [34754dd5bf3b](https://github.com/aurora-silicon/linux/commit/34754dd5bf3bd3d21b3409b6768af8b8fa38a045), [21c1d3f21ac4](https://github.com/aurora-silicon/linux/commit/21c1d3f21ac49f4223993ed1beefca1d6d6e89cd) | Ryan Murray | arm64: dts: apple: t8140: state why PMGR domains off at boot are always-on [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH | V | -| [c3760b2f1cbd](https://github.com/aurora-silicon/linux/commit/c3760b2f1cbd4e17586ced9ac0d9ae7e8fe7d024), [732facd15036](https://github.com/aurora-silicon/linux/commit/732facd1503659e30fb096e0276e2efcdfa41ed7), [0d1799c7c179](https://github.com/aurora-silicon/linux/commit/0d1799c7c179d3b6e914eeaee59da7529e824565) | Ryan Murray | arm64: dts: apple: t8140-j700: trim measurement notes from comments [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH | V | -| [ac9e0f78ef56](https://github.com/aurora-silicon/linux/commit/ac9e0f78ef560ef9d7a5c5655c7253e938b08d71), [f2928aa2ef66](https://github.com/aurora-silicon/linux/commit/f2928aa2ef662ff9045367ee9910a62a0f0b4e4b) | Ryan Murray | pmdomain: apple: pmc: Test partial enables and probe unwind | Not applicable — VERIFY; `drivers/pmdomain/apple/pmc-test.c` | V | -| [e8e0eae211f9](https://github.com/aurora-silicon/linux/commit/e8e0eae211f9d97ad777522ac8bf0c331ebf20f8), [a20499ed1321](https://github.com/aurora-silicon/linux/commit/a20499ed1321d5e5054d0f3dfd3f3a622e2938be) | Ryan Murray | soc: apple: mcc: Test partial allocation enable and cache handoff | Not applicable — VERIFY; `drivers/soc/apple/Kconfig` | V | -| [f2669637e7a6](https://github.com/aurora-silicon/linux/commit/f2669637e7a6c7e24f8eac823097156728ce64a8), [e3d59133d7a7](https://github.com/aurora-silicon/linux/commit/e3d59133d7a793ac15e3fa7328d11dafff8d8c92), [d6094473be4c](https://github.com/aurora-silicon/linux/commit/d6094473be4ceae69e8385ffb03891a22c60c3e4) | Ryan Murray | soc: apple: rtkit-helper: Terminate log messages [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [8a83508a3870](https://github.com/aurora-silicon/linux/commit/8a83508a3870e8dd8d15ade42c759ed1be8fc9c1), [bee2492c2bac](https://github.com/aurora-silicon/linux/commit/bee2492c2bac7c4cf6022cffadd92b1e4fae2f54), [0afefd991028](https://github.com/aurora-silicon/linux/commit/0afefd9910288c1783a2756c4240dfc80ee8470f) | Ryan Murray | iommu: apple-dart: Return IOMEM_ERR_PTR() from the tunneled MMIO helper [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — TUNNEL; `drivers/iommu/apple-dart.c` | V | -| [d970f88dd819](https://github.com/aurora-silicon/linux/commit/d970f88dd819b24905808cac119647625e382303), [6b8a1244cb2c](https://github.com/aurora-silicon/linux/commit/6b8a1244cb2c8e0da6290fe794fb442b5cb9404e), [27da3a5d53ca](https://github.com/aurora-silicon/linux/commit/27da3a5d53ca11f2aeff4916d25f40308c378a07) | Eryk Wieliczko | arm64: dts: apple: t8140-j700: give the boot framebuffer its panel | Not applicable — PERIPH | V | -| [8a9127fdd1f5](https://github.com/aurora-silicon/linux/commit/8a9127fdd1f54bfe2913e7996073a994eb41ff04), [8feaf5d2fa71](https://github.com/aurora-silicon/linux/commit/8feaf5d2fa714a11984b1eeafd5dd2e076ec4af6), [748b2a25f2ca](https://github.com/aurora-silicon/linux/commit/748b2a25f2ca960017eef868e2323a27e07f0fe2) | Ryan Murray | drm/asahi: clean up the statistics Rust style | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [c987a1793e75](https://github.com/aurora-silicon/linux/commit/c987a1793e759da730ff84384a601d9d96d916d3), [37b3b1f7de85](https://github.com/aurora-silicon/linux/commit/37b3b1f7de8547eca29a4414465b5b4d705d413d) | Chris Kearney | drm/apple: wait for T6030 RTKit callbacks before a DCP is freed | Not applicable — G15; `drivers/gpu/drm/apple/dcp.c` | V | -| [9639e3803ffb](https://github.com/aurora-silicon/linux/commit/9639e3803ffb7f73c58dbbacad17a6e40b7596ac), [346fd6083ab2](https://github.com/aurora-silicon/linux/commit/346fd6083ab2d45a079fe512c6b3e68affd4cc6f) | Ryan Murray | drm/asahi: free completed commands on system_dfl_wq | Not applicable — LEGACY; `drivers/gpu/drm/asahi/workqueue.rs` | V | -| [3e6775c52948](https://github.com/aurora-silicon/linux/commit/3e6775c52948793951b618817b3715eec5f91924), [b9527e10b2b6](https://github.com/aurora-silicon/linux/commit/b9527e10b2b683dff7d4b718e9af6f93fb0a005f) | Ryan Murray | arm64: add an isolated T8140 graphics and power profile | Not applicable — PERIPH | V | -| [7f40cd79f058](https://github.com/aurora-silicon/linux/commit/7f40cd79f0582c4ca1abbad36f1e923d8163779f), [58db6bfedcec](https://github.com/aurora-silicon/linux/commit/58db6bfedcec7cb4a2be3843c5d3665b4680553e) | Chris Kearney | soc: apple: test every PMP integer replacement width | Not applicable — VERIFY; `drivers/soc/apple/pmp_bootargs.rs` | V | -| [0a1f130cd042](https://github.com/aurora-silicon/linux/commit/0a1f130cd0427037fc94a4ad39e54a3c66d5dbac), [f11518fc495d](https://github.com/aurora-silicon/linux/commit/f11518fc495d51dc3c5d8f67cc10d7cb02a4d739) | Eryk Wieliczko | pmdomain: apple: add the GFX TVM gate | Not applicable — G16; `drivers/pmdomain/apple/Makefile` | V | -| [4e7c8a74e4a5](https://github.com/aurora-silicon/linux/commit/4e7c8a74e4a5ef03a1d06b5cd73f01c68b75a63d), [fe7d063e4cee](https://github.com/aurora-silicon/linux/commit/fe7d063e4cee437b5196c438f9f19a6ad7e22afc) | Satya Benson | pmdomain: apple: gfx-tvm: accept the T8122 | Not applicable — G15; `drivers/pmdomain/apple/gfx-tvm.c` | V | -| [460c0a77ca86](https://github.com/aurora-silicon/linux/commit/460c0a77ca860aef48d7ed449d65a878cffab9ed), [c8aed729e9bf](https://github.com/aurora-silicon/linux/commit/c8aed729e9bf8d23f0adabff999aa16d34201d76) | Joshua Warren | gpu: let the firmware preempt compute work on G14X | Not applicable — LEGACY; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [80797e4f1b2b](https://github.com/aurora-silicon/linux/commit/80797e4f1b2bbde71964ea2253553d2c2dbbe379), [9c7ab8b412a5](https://github.com/aurora-silicon/linux/commit/9c7ab8b412a50123bf7dbc642368aa7f930d2d41) | Ryan Murray | drm/asahi: gate compile-only M3 backends before resource setup | Not applicable — G15; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [700bfca794e5](https://github.com/aurora-silicon/linux/commit/700bfca794e50093c6e4d2b4231aca6252451a41), [860d185ccc57](https://github.com/aurora-silicon/linux/commit/860d185ccc575a47df4962cb1cf32da8f27ff35f) | Chris Kearney | drm/asahi: add the M3 (G15S) GPU runtime (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_layout.rs` | V | -| [01680f395e55](https://github.com/aurora-silicon/linux/commit/01680f395e557e93b331ad510fbf255e6622c2a0), [a846942e367d](https://github.com/aurora-silicon/linux/commit/a846942e367dade6002d2d456ae6249c50d04d39) | Eryk Wieliczko | drm/asahi: share M3 M4 host retirement accounting (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [9593d5f2498f](https://github.com/aurora-silicon/linux/commit/9593d5f2498f3243100c828cc7bbf7ecdaddb861), [4bcb6f1acab4](https://github.com/aurora-silicon/linux/commit/4bcb6f1acab42a1772bf62aaae00c5fb1f6007cd) | Eryk Wieliczko | drm/asahi: account M3 GEM and coherent firmware backing lifetimes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_memory_stats.rs` | V | -| [bba3fa8f4562](https://github.com/aurora-silicon/linux/commit/bba3fa8f4562761864f8f57b1a461bcd50ec3d64), [3e963ea31aca](https://github.com/aurora-silicon/linux/commit/3e963ea31acaad3e4a78dc137f12339fa8ebb5ee) | Chris Kearney | drm/asahi: expose bounded native retirement timing snapshots (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_timing_stats.rs` | V | -| [6d24d16ce24c](https://github.com/aurora-silicon/linux/commit/6d24d16ce24c8af1902191781e1255807ccd8aae), [1324a0258bb0](https://github.com/aurora-silicon/linux/commit/1324a0258bb0d0987993a3c34c2a74b0f2093cce) | Chris Kearney | drm/asahi: expose host-tracked pending GPU activity separately from completions (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [a4bbcd4baf93](https://github.com/aurora-silicon/linux/commit/a4bbcd4baf933a15e5bc75b2c7c5603d8b1b6998), [8faa4de3948b](https://github.com/aurora-silicon/linux/commit/8faa4de3948b0795c068eeeb0456a6a7dfc45077) | Chris Kearney | drm/asahi: avoid repeated activity fences while GPU work is pending (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_host_progress.rs` | V | -| [2397ac8a0861](https://github.com/aurora-silicon/linux/commit/2397ac8a086119bba90f6fc0d8d430e035d27f30), [b62d349e0fc6](https://github.com/aurora-silicon/linux/commit/b62d349e0fc6e160b9dabd167166a2d87ecfdbce) | Eryk Wieliczko | drm/asahi: remove M3 lifetime submission cap with wrapping wire stamps (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_timeline.rs` | V | -| [ce78a5b0c517](https://github.com/aurora-silicon/linux/commit/ce78a5b0c5173dbb9b5d7d0017488c43a07f222f), [578aa862e357](https://github.com/aurora-silicon/linux/commit/578aa862e357f0f61e18dc8e26181eeb5c0b9d7b) | Eryk Wieliczko | drm/asahi: preserve nonzero M3 stamps and dependencies through rollover (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_timeline.rs` | V | -| [646db65b2128](https://github.com/aurora-silicon/linux/commit/646db65b212826a29bd969332760722077926d61), [1d6a90b4117f](https://github.com/aurora-silicon/linux/commit/1d6a90b4117fe9cb84aa7863f491d18d37fcf0c5) | Chris Kearney | drm/asahi: remove unused backend helpers and narrow layout visibility (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_storage.rs` | V | -| [a91573de916a](https://github.com/aurora-silicon/linux/commit/a91573de916a12ddc980c75d977567e57725e449), [f939d03f703f](https://github.com/aurora-silicon/linux/commit/f939d03f703fe760f413a87d435769b3aa970d21) | Chris Kearney | treewide: apple: reword M3 comments and messages as plain technical statements (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_sequence.rs` | V | -| [997a7dba8158](https://github.com/aurora-silicon/linux/commit/997a7dba81582c94d1bdcc26aaae6031a486390c), [262009a6c7f9](https://github.com/aurora-silicon/linux/commit/262009a6c7f9dc7b6ca4abb158b669870a6180c5) | Chris Kearney | drm/asahi: select M3 runtime configuration per SoC (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [a8065eb937ce](https://github.com/aurora-silicon/linux/commit/a8065eb937cee67032a68207827419c515e52e11), [d16a8c32954b](https://github.com/aurora-silicon/linux/commit/d16a8c32954b412bb3bf9f61a7c48a68dc9303b1) | Chris Kearney | drm/asahi: m3: derive runtime IO maps from IO mappings (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [c3d978ed0793](https://github.com/aurora-silicon/linux/commit/c3d978ed0793058248d9994e868f5c1043cc18f7), [7f04f81b5a19](https://github.com/aurora-silicon/linux/commit/7f04f81b5a191b8ff9b1a3d454656af3993b47be) | Satya Benson | drm/asahi: m3: size render TPC and preemption storage by cluster count (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_pass_layout.rs` | V | -| [4287d2b5166b](https://github.com/aurora-silicon/linux/commit/4287d2b5166bb92f791ae652dba8361cfc732aeb), [d94dcc88b26c](https://github.com/aurora-silicon/linux/commit/d94dcc88b26ca0e964b5298ee1298ed068cbf6eb) | Satya Benson | drm/asahi: m3: publish queued packets from the completion worker (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [6046b500e687](https://github.com/aurora-silicon/linux/commit/6046b500e6872cfe56d53cb65e9b0619cb1f066c), [6787ae6d5717](https://github.com/aurora-silicon/linux/commit/6787ae6d57170ef75c454f6f744d4c4d557cb9a7) | Satya Benson | drm/asahi: m3: bound overlapping render batches to free pass slots (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [4ea0ea7df543](https://github.com/aurora-silicon/linux/commit/4ea0ea7df5437fad2829ec8eb68be6e9f3544591), [ce9df27fd4b6](https://github.com/aurora-silicon/linux/commit/ce9df27fd4b67bd47194655b57efecdec2321081) | Satya Benson | drm/asahi: m3: budget render coalescing by measured per-VM GPU time (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [b877dfb7e3e8](https://github.com/aurora-silicon/linux/commit/b877dfb7e3e89e31fef97057c68581660b6f256e), [d57591e332b4](https://github.com/aurora-silicon/linux/commit/d57591e332b49cafc12aaf8af77845525dda760b) | Chris Kearney | drm/asahi: m3: compare waiting urgency with the active render batch (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [f9ede2dda5dd](https://github.com/aurora-silicon/linux/commit/f9ede2dda5dd7a0fa8ce0e1143724e7be01b31a0), [7c912ffa2635](https://github.com/aurora-silicon/linux/commit/7c912ffa2635dd08673a43c09442a143a39b624d) | Chris Kearney | drm/asahi: retain full firmware-log payloads and use ring entry sizes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_layout.rs` | V | -| [02e89516c254](https://github.com/aurora-silicon/linux/commit/02e89516c254d55b4ae686ccae460af8ddd30901), [e2bbe50fc3fd](https://github.com/aurora-silicon/linux/commit/e2bbe50fc3fd42e5dfbd74e5aff9181af86bb096) | Chris Kearney | drm/asahi: keep firmware-log payload clear of render counter pages (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_init_storage.rs` | V | -| [eb1dec967643](https://github.com/aurora-silicon/linux/commit/eb1dec967643c6b4fbbd528812befd07434951d8), [11896702843e](https://github.com/aurora-silicon/linux/commit/11896702843eb979e00beb871090800d9c53a4e0) | Chris Kearney | drm/asahi: coalesce eligible T6030 render completion stamp flushes (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [407c4ba9d5c8](https://github.com/aurora-silicon/linux/commit/407c4ba9d5c8f14292a7ba75afdc929475a0e40c), [7feec149fdc7](https://github.com/aurora-silicon/linux/commit/7feec149fdc7795ff82698683c86dc4b3a2a486b) | Chris Kearney | drm/asahi: order opt-in T6030 mixed batches with firmware barriers (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [d8c059ddae69](https://github.com/aurora-silicon/linux/commit/d8c059ddae697f618e0b70b4b2ddee103ba9a1eb), [0377e6c2e9ad](https://github.com/aurora-silicon/linux/commit/0377e6c2e9ad549130015a52de84c0c24e47a343) | Chris Kearney | drm/asahi: make T6030 internal render measurements optional (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_batch_policy.rs` | V | -| [ad54cf1de60e](https://github.com/aurora-silicon/linux/commit/ad54cf1de60ea638b0ab96e80d9bea7d7fc726ea), [cd13ef870e00](https://github.com/aurora-silicon/linux/commit/cd13ef870e00dd86aed1b582b393c6a697bec326) | Chris Kearney | drm/asahi: use stage-specific render sequence length fields (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_command_layout.rs` | V | -| [16fef343da41](https://github.com/aurora-silicon/linux/commit/16fef343da414828fe4098a566951945838bb370), [689764765782](https://github.com/aurora-silicon/linux/commit/68976476578273e77d0d5f05f77f437f610dbee8) | Chris Kearney | drm/asahi: add bounded T6030 active power-state sampling (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_active_power.rs` | V | -| [019434491afe](https://github.com/aurora-silicon/linux/commit/019434491afe2cd57bc001515778d9412c9b0747), [cd09499b2a78](https://github.com/aurora-silicon/linux/commit/cd09499b2a78ce5e0ca1b628af94403c56467256) | Chris Kearney | drm/asahi: add opt-in T6030 consistent performance requests (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_active_power.rs` | V | -| [b09e6d9fca33](https://github.com/aurora-silicon/linux/commit/b09e6d9fca33c554a597774f1a6cd4c4ca54622b), [263fd8538d83](https://github.com/aurora-silicon/linux/commit/263fd8538d83cca3809589da9b78cb1d982c0a21) | Chris Kearney | drm/asahi: refresh an opt-in T6030 busy performance request (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_consistent_perf.rs` | V | -| [9bc784357fe8](https://github.com/aurora-silicon/linux/commit/9bc784357fe8affe0875fb911be88ac953ca30db), [db732ce1f244](https://github.com/aurora-silicon/linux/commit/db732ce1f24488887872abc3b61b45de95285252) | Chris Kearney | drm/asahi: add an opt-in T6030 Globals debug-word clear (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_globals_debug.rs` | V | -| [02bde1b70c31](https://github.com/aurora-silicon/linux/commit/02bde1b70c312f6d4d964c7a2b1737be0de5a909), [651fbc49524d](https://github.com/aurora-silicon/linux/commit/651fbc49524d677ff86766dd2d85bb1bbf6ab3eb) | Chris Kearney | drm/asahi: m3: groundwork for more than two clusters and T6031 tables (M3-only split) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_pass_layout.rs` | V | -| [0f47fbf31934](https://github.com/aurora-silicon/linux/commit/0f47fbf31934d0b1684b5412e235315304687d4a), [783f9478d373](https://github.com/aurora-silicon/linux/commit/783f9478d3737cfae945aad01e02e9dea30c2249) | Chris Kearney | drm/asahi: reject unsupported command fields on the M1/M2 queue path | Not applicable — LEGACY; `drivers/gpu/drm/asahi/queue/mod.rs` | V | -| [1de2dbd89acb](https://github.com/aurora-silicon/linux/commit/1de2dbd89acb80f37aec08fa897374dfebe56b10), [294e9f9ebfb4](https://github.com/aurora-silicon/linux/commit/294e9f9ebfb42dbc77a85f635b5bfabaa9315003) | Chris Kearney | drm/asahi: excise unbound G16 and G17 runtimes (M3-only split: TA/3D command encoders) | Not applicable — G15; `drivers/gpu/drm/asahi/m3/agx_render.rs` | V | -| [fd1a2a3d4e60](https://github.com/aurora-silicon/linux/commit/fd1a2a3d4e60ce3f3965d2a47d1904ce3a6ed158), [e91bc024eef8](https://github.com/aurora-silicon/linux/commit/e91bc024eef8a6fde320f7fa062a034a2fe0bccb) | Eryk Wieliczko | drm/asahi: carry validated M3 depth compression bindings | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [bc0a841680f3](https://github.com/aurora-silicon/linux/commit/bc0a841680f3b36193e83e18c339d269d142de03), [2c301fab2412](https://github.com/aurora-silicon/linux/commit/2c301fab241280c36f20c57d7d240ff0f48ad88f) | garymeyerca | drm/asahi: gate T8122 G15G identity before startup | Not applicable — G15; `drivers/gpu/drm/asahi/m3/mod.rs` | V | -| [e10c013299bf](https://github.com/aurora-silicon/linux/commit/e10c013299bf639ca0c8f08574150970e381f203), [be90c110d9df](https://github.com/aurora-silicon/linux/commit/be90c110d9dfcae3918efad4ba9a3d5015bb5bf4) | Chris Kearney | drm/asahi: select M3 runtime configuration per SoC | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [ed90e7bfde51](https://github.com/aurora-silicon/linux/commit/ed90e7bfde5160c20b1e4165f577e874e60fc102), [a6b472702f24](https://github.com/aurora-silicon/linux/commit/a6b472702f24666ee52febc1c2eb93bf21c8d44a) | Satya Benson | drm/asahi: m3: T8122: the G15G compute register list | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_compute_layout.rs` | V | -| [278d0abfc612](https://github.com/aurora-silicon/linux/commit/278d0abfc6128a83aa00d9181bdf2c716b608c89), [7949c0d6139c](https://github.com/aurora-silicon/linux/commit/7949c0d6139c53f8e016cd773744386407a8c9cf) | Satya Benson | drm/asahi: m3: T8122: the G15G TA and 3D register lists | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [7231c0beb83e](https://github.com/aurora-silicon/linux/commit/7231c0beb83ec1976716d28456e09df3e159f2e5), [bfd3e0bf0bbc](https://github.com/aurora-silicon/linux/commit/bfd3e0bf0bbc64ee99213b4b5b3824b588411bba) | Satya Benson | drm/asahi: m3: T8122: the runtime HwDataB words | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [6ad35705d81d](https://github.com/aurora-silicon/linux/commit/6ad35705d81dd1e65f8ef9e1f4136a0080ead760), [f6e58511c69a](https://github.com/aurora-silicon/linux/commit/f6e58511c69ae5cdef73b3ba0d87de8de9a74e01) | Chris Kearney | drm/asahi: m3: T8122: the remaining runtime InitData words | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_soc.rs` | V | -| [2a8cdd0ce1d4](https://github.com/aurora-silicon/linux/commit/2a8cdd0ce1d4a8ceef673922b9517e4780996a0c), [d109a5c9e597](https://github.com/aurora-silicon/linux/commit/d109a5c9e59768669f2d1750ab1abd4560a42e28) | Chris Kearney | drm/asahi: coalesce eligible T6030 render completion stamp flushes | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [bb1f75a18b32](https://github.com/aurora-silicon/linux/commit/bb1f75a18b3265ab5e4a06e424df43ed0371c002), [d4dba3df31cf](https://github.com/aurora-silicon/linux/commit/d4dba3df31cff8f96ddeafad6a4b2709fe942d62) | Chris Kearney | drm/asahi: use stage-specific render sequence length fields | Not applicable — G15; `drivers/gpu/drm/asahi/m3/m3_fragment_command.rs` | V | -| [1e8f813be7c6](https://github.com/aurora-silicon/linux/commit/1e8f813be7c681b558ffcd501ea278d6848099f4), [3d7945cbbd0f](https://github.com/aurora-silicon/linux/commit/3d7945cbbd0f9dd9d7806c402e70a53815c30738) | Satya Benson | drm/asahi: m3: T8122: write the HwDataA +0x418c block on 14.8.3 | Not applicable — G15; `drivers/gpu/drm/asahi/m3/mod.rs` | V | -| [8730d3dce2b7](https://github.com/aurora-silicon/linux/commit/8730d3dce2b7e8d9f05ad437c4cf89169e0c5b78), [453d66a437b0](https://github.com/aurora-silicon/linux/commit/453d66a437b02027ad0b6fb194242dd29bb0d31d) | Chris Kearney | pmdomain: apple: pmp-report: add the T6031 report | Not applicable — G15; `drivers/pmdomain/apple/pmp-report-test.c` | V | -| [a66386d03830](https://github.com/aurora-silicon/linux/commit/a66386d03830555c976850001c12644921b0a028), [a8e5d3a57a0e](https://github.com/aurora-silicon/linux/commit/a8e5d3a57a0e19360cffa4dc04ae500ba832e0ea) | Marius Gehrmann | pmdomain: apple: pmp-report: Request T8122 devices by soc-device record | Not applicable — G15; `drivers/pmdomain/apple/pmp-report-test.c` | V | -| [3b9bb4563bb8](https://github.com/aurora-silicon/linux/commit/3b9bb4563bb8b9f16761fe5842ff3bb6a09d8661), [c7bbd7faf778](https://github.com/aurora-silicon/linux/commit/c7bbd7faf778be8ab87515e81caf06571e527ad8) | Chris Kearney | pmdomain: apple: pmp-report: start a handed-over T8122 or T6031 PMP | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [3157c614a661](https://github.com/aurora-silicon/linux/commit/3157c614a66119b47100a6a8ac1ad9232bacbf81), [2b115cc04222](https://github.com/aurora-silicon/linux/commit/2b115cc04222553f4bcde86a70f5a2f9c8f5d086) | Ryan Murray | pmdomain: apple: pmp-report: document a failed PMP start and its recovery | Not applicable — VERIFY; `drivers/pmdomain/apple/Kconfig` | V | -| [c332c6fbd56a](https://github.com/aurora-silicon/linux/commit/c332c6fbd56adddb1f6d5635b4010a940c780e7e), [54b90aaf82e9](https://github.com/aurora-silicon/linux/commit/54b90aaf82e9aa7241747d747a5e79c46841a2dd) | Ryan Murray | pmdomain: apple: pmp-report: add KUnit fault injection for the PMP start | Not applicable — VERIFY; `drivers/pmdomain/apple/.kunitconfig.apple-pmp-start` | V | -| [7d101f700326](https://github.com/aurora-silicon/linux/commit/7d101f7003268e2e459ed86b07c9bc3ec5a000f2), [ac234af7c851](https://github.com/aurora-silicon/linux/commit/ac234af7c851e08e6da06a4dffeb912786611ed8) | Chris Kearney | drm/asahi: uapi: add the M3 (G15S) runtime numbers | Not applicable — G15 | V | -| [70f4bebd69b0](https://github.com/aurora-silicon/linux/commit/70f4bebd69b070d37022bca55228879bb7ec4e32), [577249de3221](https://github.com/aurora-silicon/linux/commit/577249de322139ceb84aea9daffcf54d437da52b) | Eryk Wieliczko | drm/asahi: uapi: add the J613 25G83 runtime numbers | Not applicable — G15 | V | -| [f3de3ac043ac](https://github.com/aurora-silicon/linux/commit/f3de3ac043acd22bf4ded712f2999b5693d824ae), [744d0129b6c0](https://github.com/aurora-silicon/linux/commit/744d0129b6c008708c2d9d019ca0a95ee1c04874) | Ryan Murray | drm/asahi: reject timestamp copies on M1 and M2 | Not applicable — LEGACY; `drivers/gpu/drm/asahi/queue/mod.rs` | V | -| [d2cdf2ff6b35](https://github.com/aurora-silicon/linux/commit/d2cdf2ff6b353a72f5f33239a4a7f2b7d87e8cf4), [1e52a05edada](https://github.com/aurora-silicon/linux/commit/1e52a05edadad288cfc17120f37c721f506abcd5) | Chris Kearney | gpu: preserve compute overrides and limit automatic preemption to M2 Max | Not applicable — LEGACY; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [a22a6bfc2fa0](https://github.com/aurora-silicon/linux/commit/a22a6bfc2fa049f249effd677a512d682870b171) | Ryan Murray | rust: drm: document Aurora ownership and simplify pointer conversions | Not applicable — VERIFY; `rust/kernel/drm/gpuvm/mod.rs` | V | -| [e8f94ff7af1c](https://github.com/aurora-silicon/linux/commit/e8f94ff7af1cd4104091ac851109fdae946aa585) | Ryan Murray | arm64: dts: apple: j700: Use the raw xHCI SuperSpeed port number | Not applicable — PERIPH | V | -| [58d75c388d55](https://github.com/aurora-silicon/linux/commit/58d75c388d55030f432e93f42ff8871ffe9390f3) | Chris Kearney | soc: apple: opt native T6030 GPUs into the admitted PMP supplier [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [19538d922267](https://github.com/aurora-silicon/linux/commit/19538d9222679bc5ff3f17da845a10f60591e82c) | Chris Kearney | pmdomain: apple: read readiness from the passive T6030 report [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [1633fb96515e](https://github.com/aurora-silicon/linux/commit/1633fb96515e3b733a0e3514e17f841ef344ab4c) | Eryk Wieliczko | drm/asahi: g15: Add the UAPI glue and register the G15 generation [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [4d6d40767ae2](https://github.com/aurora-silicon/linux/commit/4d6d40767ae2a1cdbb697d3471dbb2c4a7ef9f9d) | Naeem Malik | drm/asahi: g15: Add the T6031 (M3 Max, G15C) configuration row [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [99a4031d5828](https://github.com/aurora-silicon/linux/commit/99a4031d58282e9d2d0f9211b3ba50547d4fc643) | Naeem Malik | drm/asahi: g15: Pin the J516C GPU firmware build [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [4abf7048277d](https://github.com/aurora-silicon/linux/commit/4abf7048277dd6ec8364811002adeafe326046d6) | Naeem Malik | drm/asahi: g15: Build the J516C initdata from its board images [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [5fc412af6085](https://github.com/aurora-silicon/linux/commit/5fc412af608586b6beb6a567544f3440f42fe7eb) | Naeem Malik | drm/asahi: g15: Encode compute commands with the G15C register values [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [377ce9d4f32a](https://github.com/aurora-silicon/linux/commit/377ce9d4f32a42a3b87e0885f48777140c4a2488) | Naeem Malik | drm/asahi: g15: Admit and map UAT regions that are reserved System RAM [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [3a5c855a7219](https://github.com/aurora-silicon/linux/commit/3a5c855a7219aaf45d18a3449bfd4a263ed781c2) | Naeem Malik | drm/asahi: g15: Accept the J516C 14.8 GPU firmware build [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw/t6031.rs` | V | -| [f0d7c15b4769](https://github.com/aurora-silicon/linux/commit/f0d7c15b47696e3bbf168f1c8bce9c4817ea28da) | DjDeveloperr | drm/asahi: g15: Reject a scissor base that overflows the address space [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/command.rs` | V | -| [2510cc337f15](https://github.com/aurora-silicon/linux/commit/2510cc337f1551b53e9de38b5c69d6d365e373f3) | DjDeveloperr | drm/asahi: g15: Do not fail a published prefix on a group allocation failure [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/engine.rs` | V | -| [5a592f22b23a](https://github.com/aurora-silicon/linux/commit/5a592f22b23a83ec106b50d5f9ec88f9d885e980) | DjDeveloperr | drm/asahi: g15: Release a closed VM's state when its handle goes [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [e2b962c42e40](https://github.com/aurora-silicon/linux/commit/e2b962c42e40c5ee92b81495436c11b5832d056c) | DjDeveloperr | drm/asahi: g15: Release the power hold and the PMP vote when a start fails early [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [c4d01d363c1d](https://github.com/aurora-silicon/linux/commit/c4d01d363c1d25c33fee168114f369288e24e55d) | DjDeveloperr | drm/asahi: g15: Only mark used pass slots dirty on release [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/slots.rs` | V | -| [35bbcb1bca7a](https://github.com/aurora-silicon/linux/commit/35bbcb1bca7a9dac71f9785aed900d4cf6665d9f) | DjDeveloperr | tools/asahi: Drop the removed T6031 knobs from the M3 runtime tests [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/glue.c` | V | -| [f6da2c8fd38a](https://github.com/aurora-silicon/linux/commit/f6da2c8fd38a75723a7569ff6046d08572900559) | Chris Kearney | drm/asahi-m3: adapt the native G15 driver to the 7.2 driver core and DRM device API [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [42f91c2f9eae](https://github.com/aurora-silicon/linux/commit/42f91c2f9eae615bc12335e37f2016ec09398f63) | Naeem Malik | drm/asahi: g15: Say what to report when the GPU firmware build is unknown [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/identity.rs` | V | -| [f3b867b04c1a](https://github.com/aurora-silicon/linux/commit/f3b867b04c1a50f46d034844754e39f8031ffae3) | Naeem Malik | drm/asahi: g15: Move the board template fill into a core-only submodule [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [7375309d764f](https://github.com/aurora-silicon/linux/commit/7375309d764f899d8eb4328e30447ec2959efa02) | Naeem Malik | drm/asahi: g15: t6031: Build Globals and Power from the device tree [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [b840b9944ad9](https://github.com/aurora-silicon/linux/commit/b840b9944ad9e171cf5b13b4e0e0fe8d018778c9) | Naeem Malik | drm/asahi: g15: board: Review fixes for the device-tree Globals and Power [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/words.rs` | V | -| [3f02f6c358ab](https://github.com/aurora-silicon/linux/commit/3f02f6c358abd1630f1342cbd4dbca755c78023c) | Naeem Malik | drm/asahi: g15: t6031: Build the hardware record from the device tree [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [f1f5a81b756f](https://github.com/aurora-silicon/linux/commit/f1f5a81b756f99b30baefcd967a924167b2a0c12) | Naeem Malik | drm/asahi: t6031: take the idle standby time from the GPU node [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/hw.rs` | V | -| [de646267a725](https://github.com/aurora-silicon/linux/commit/de646267a725f94ea67864c2695eb1082f60dc33) | Chris Kearney | drm/asahi: g15: t6031: refuse board-data values that do not fit in u32 [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [a9a0e4be0546](https://github.com/aurora-silicon/linux/commit/a9a0e4be0546ee7876924cee8e3478727f89cb41) | Chris Kearney | selftests: asahi-g15: run the T6031 board-data and firmware-lookup tests [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [0b06992d812c](https://github.com/aurora-silicon/linux/commit/0b06992d812ce75667740514a5a472fc8d0e091b) | Chris Kearney | drm/asahi: g15: t6031: test that no GPU node value panics the record builder [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [68b780fc7ced](https://github.com/aurora-silicon/linux/commit/68b780fc7ced9e39a5d4573993564ebda26f3649) | Naeem Malik | drm/asahi: g15: Read back the GPU's performance state in debugfs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board.rs` | V | -| [cd970562fa97](https://github.com/aurora-silicon/linux/commit/cd970562fa979059c6dea0e7f0a7f9df63c3b1c7) | Naeem Malik | drm/asahi: g15: t6031: Leave the 42 record words the firmware does not need zero [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/board/record.rs` | V | -| [2a0319927108](https://github.com/aurora-silicon/linux/commit/2a0319927108ee823a82bb1884d2cc6512b515bb) | Chris Kearney | drm/asahi: g15: m3: complete the stats record loads before consuming them [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/channel.rs` | V | -| [73047c7ee59e](https://github.com/aurora-silicon/linux/commit/73047c7ee59e45b8d16e8ec308fb15683caefc6e) | Naeem Malik | drm/asahi: g15: Seed the compute UMA freelist with every pool [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/graph.rs` | V | -| [345f1d8467a4](https://github.com/aurora-silicon/linux/commit/345f1d8467a46f679eb2f2fc2852adb844911033) | Naeem Malik | drm/asahi: g15: Leave PB growth requests unanswered after two refusals at the maximum [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/params.rs` | V | -| [bd0201fad2e0](https://github.com/aurora-silicon/linux/commit/bd0201fad2e02429de6e265c51a223e4209920fe) | Naeem Malik | drm/asahi: g15: Keep PB blocks above the firmware's growth maximum for partial renders [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/params.rs` | V | -| [ff0d1cd692b8](https://github.com/aurora-silicon/linux/commit/ff0d1cd692b838934972a646fa7d1411c54b4864) | Naeem Malik | drm/asahi: g15: Map a 512 MiB parameter buffer heap [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/buffer.rs` | V | -| [e1cdc12eeb97](https://github.com/aurora-silicon/linux/commit/e1cdc12eeb97fc9f4da88343054e6a964e8d2e40) | Chris Kearney | drm/asahi: g15: m3: keep every PB ledger below the block list's K [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/pools.rs` | V | -| [b1adafb49e1c](https://github.com/aurora-silicon/linux/commit/b1adafb49e1c49b71221f7c069dde6045ccce32c) | Chris Kearney | drm/asahi: g15: m3: say what a PB refusal does and size the heap right [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/fw/buffer.rs` | V | -| [3ea5cb6af82b](https://github.com/aurora-silicon/linux/commit/3ea5cb6af82bda7fca665b0902b22275ae02d996) | Chris Kearney | drm/asahi: g15: m3: check firmware-object backing geometry with checked arithmetic [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/object.rs` | V | -| [1eced02cd6c3](https://github.com/aurora-silicon/linux/commit/1eced02cd6c3efe9c43cfc9cf0993ee427e849b9) | Chris Kearney | drm/asahi: g15: m3: map the PB backing into each VM when it first runs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/engine.rs` | V | -| [73b9ade12e01](https://github.com/aurora-silicon/linux/commit/73b9ade12e0123ef2168abd7eb4969d6865622a3) | Chris Kearney | drm/asahi: g15: m3: back the PB on demand, before an answer posts it [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/pools.rs` | V | -| [716d2fbe9254](https://github.com/aurora-silicon/linux/commit/716d2fbe9254f5ba13a8bd6a6ac687f5904a2f8a) | Chris Kearney | drm/asahi: adapt retained-G15 hooks to the maintained shared APIs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/file.rs` | V | -| [a4000925920a](https://github.com/aurora-silicon/linux/commit/a4000925920a0e338e0bfa2b726f3b4de90b8cd7) | Chris Kearney | drm/asahi: port the native G15 adapter onto maintained DRM registration [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/Kconfig` | V | -| [23ae3eaf8377](https://github.com/aurora-silicon/linux/commit/23ae3eaf8377dbbd5c51541d77fb4a542fdb384b) | Chris Kearney | drm/asahi: g15: allocate driver data before touching firmware [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [a8289266db94](https://github.com/aurora-silicon/linux/commit/a8289266db94cf7069ab26420bd9d6b60a92dce6) | Chris Kearney | drm/asahi: g15: defer firmware start until module registration completes [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/asahi_core.rs` | V | -| [bc962412f16e](https://github.com/aurora-silicon/linux/commit/bc962412f16e1ca6d93ababf971c68011294c5e3) | Chris Kearney | drm/asahi: g15: make maintained loader contracts independent of SF profiles [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/adt.rs` | V | -| [6c6f0e62156c](https://github.com/aurora-silicon/linux/commit/6c6f0e62156cd9e35f5db47af226dd9821a26b0f) | Chris Kearney | drm/asahi: use the native private wire in G15 command consumers [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [627c501db65e](https://github.com/aurora-silicon/linux/commit/627c501db65ed9bbe22e853f37f247dc579db4af) | Chris Kearney | drm/asahi: isolate the native G15 command ABI behind a private facade [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/wire.rs` | V | -| [9d5c0ee71512](https://github.com/aurora-silicon/linux/commit/9d5c0ee715129fda8cbb8a1420315cf6a7d25cc4) | Chris Kearney | drm/asahi: g15: bound device-wide live logical queue capacity [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [4f6aba6a3598](https://github.com/aurora-silicon/linux/commit/4f6aba6a35980bf152ce5803d7bb5940a2cb11a2) | Chris Kearney | pmdomain: apple: pmgr-pwrstate: Test apple,no-auto-pm on power on and off [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — VERIFY; `drivers/pmdomain/apple/Kconfig` | V | -| [b9d3cf70f1e8](https://github.com/aurora-silicon/linux/commit/b9d3cf70f1e8b488a9ad032dadad7cbe432e164c) | Chris Kearney | drm/asahi: export a T6030 module alias for the native G15 driver [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/mod.rs` | V | -| [af2c5c09ba9f](https://github.com/aurora-silicon/linux/commit/af2c5c09ba9fae7fbf9f165fc6aad73e9aadce0b) | Chris K | pmdomain: apple: restore gated T6030 managed PMP startup [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/pmp-report.c` | V | -| [2a182741b7f7](https://github.com/aurora-silicon/linux/commit/2a182741b7f7d80a7a743eafbf57bd9dbca3c6b4) | Chris Kearney | test: exercise the actual T6030 halted-PMP consumer graph [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/pmdomain/apple/Kconfig` | V | -| [70f41a7944ee](https://github.com/aurora-silicon/linux/commit/70f41a7944eeaf9afdd63f9246ebc5bc41df23f1) | Chris Kearney | drm/apple: admit T6030 G15 only after native display registration [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/apple/apple_drv.c` | V | -| [9632ccd283f9](https://github.com/aurora-silicon/linux/commit/9632ccd283f96ad98321238b6da4718b62f7671a) | Chris Kearney | drm/asahi: require a callable native display provider for G15 [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/Kconfig` | V | -| [e9d92ce6a5c2](https://github.com/aurora-silicon/linux/commit/e9d92ce6a5c27b36266de99d252db029476cb3f1) | Chris Kearney | drm/asahi: retain live G15 storage after allocation failures [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [fc13d05b1db9](https://github.com/aurora-silicon/linux/commit/fc13d05b1db9515fa9481d1362ff530fbeb01ca4) | DjDeveloperr | drm/asahi: g15: adapt the native G15 backend to the Linux 7.3 Rust APIs [#395](https://github.com/aurora-silicon/linux/pull/395) | Not applicable — G15; `drivers/gpu/drm/asahi/g15/boot.rs` | V | -| [0ffd22188c3d](https://github.com/aurora-silicon/linux/commit/0ffd22188c3dbb2e8bb2df216ee8e03d71e14bfb) | Ryan Murray | drm/asahi: Keep refusing HIGH queue priority on G13 and G14 [#399](https://github.com/aurora-silicon/linux/pull/399) | Not applicable — LEGACY; `drivers/gpu/drm/asahi/file.rs` | V | -| [1fac0605f061](https://github.com/aurora-silicon/linux/commit/1fac0605f061ce757917781940a5e0aec1225019) | Eryk Wieliczko | soc: apple: rtkit-helper: preserve the inherited J713 input session | Not applicable — G16; `drivers/soc/apple/rtkit-helper.c` | V | -| [751b9e08ca3d](https://github.com/aurora-silicon/linux/commit/751b9e08ca3d8fa673927984d45b22697cc26edf) | Eryk Wieliczko | iommu: apple-dart: retain J713 input and radio ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/iommu/apple-dart.c` | V | -| [939a993d46dd](https://github.com/aurora-silicon/linux/commit/939a993d46dd36392155cc05f692472d2d1c881e) | Eryk Wieliczko | pmdomain: apple: pmc: support T8132 floor requests [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmc-test.c` | V | -| [c26dfe75ac9b](https://github.com/aurora-silicon/linux/commit/c26dfe75ac9be0fb75dfe937a15246b4e12bc84a) | Eryk Wieliczko | soc: apple: clpc: retain qualified T8132 memory floors | Not applicable — G16; `drivers/soc/apple/clpc.c` | V | -| [15e0eb00b83b](https://github.com/aurora-silicon/linux/commit/15e0eb00b83b783d7fca9720530942020722cd6a) | Eryk Wieliczko | soc: apple: mcc: support the T8132 memory controller | Not applicable — G16; `drivers/soc/apple/mcc.c` | V | -| [df3e4970e686](https://github.com/aurora-silicon/linux/commit/df3e4970e68677d56eca3e9e9608c338abe52cdd) | Eryk Wieliczko | soc: apple: pmp: publish owner-managed T8132 telemetry [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmp-report.c` | V | -| [f1b75932e61d](https://github.com/aurora-silicon/linux/commit/f1b75932e61d7d193801a7f22ea628cb94d9dd56) | Eryk Wieliczko | cpufreq: apple: track T8132 thermal ownership per policy | Not applicable — G16; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [1e23ae3aee82](https://github.com/aurora-silicon/linux/commit/1e23ae3aee824c65cbb6d3c94780e44a2e3fc6c2) | Eryk Wieliczko | thermal: apple: add the J713 PMP CPU policy [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/thermal/Kconfig` | V | -| [332eea1e9005](https://github.com/aurora-silicon/linux/commit/332eea1e9005b0cf731a16695c9c87c34e8f13aa) | Eryk Wieliczko | arm64: apple: activate J713 with its PMGR ownership policy [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmgr-pwrstate.c` | V | -| [3949e3640d94](https://github.com/aurora-silicon/linux/commit/3949e3640d94d2b5434c84e9e1f6d7b81f650b70) | Eryk Wieliczko | arm64: apple: enable qualified J713 SuperSpeed host support [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/phy/apple/atc.c` | V | -| [0877cd766126](https://github.com/aurora-silicon/linux/commit/0877cd766126503ad02cc11565b85be37517a62c) | Eryk Wieliczko | arm64: apple: enable J713 Bluetooth with scoped radio DMA [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/bluetooth/hci_bcm4377.c` | V | -| [1ae4d49f3592](https://github.com/aurora-silicon/linux/commit/1ae4d49f35921f356d831da974c43dd5fb67f5d7) | Eryk Wieliczko | soc: apple: expose retained PMP display and GPU ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmp-report.c` | V | -| [a5f2ee806da2](https://github.com/aurora-silicon/linux/commit/a5f2ee806da2931b10d69044e4a40609d4924201) | Eryk Wieliczko | thermal: apple: integrate J713 measured-rail GPU budgets [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/thermal/Kconfig` | V | -| [52d846f6b8d3](https://github.com/aurora-silicon/linux/commit/52d846f6b8d3664ea6135a660c0b3ece39937209) | Eryk Wieliczko | iommu/apple-dart: adopt J713 display streams with retained ownership [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/iommu/Kconfig` | V | -| [24f67337c9d5](https://github.com/aurora-silicon/linux/commit/24f67337c9d586100ca4a4f438e83310644c1903) | Eryk Wieliczko | drm/asahi: add the T8132 G16 firmware backend [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/gpu/drm/asahi/Kconfig` | V | -| [fb96882f6cb4](https://github.com/aurora-silicon/linux/commit/fb96882f6cb4ce464fcf3f8b3f27f0c3eba891ed) | Ryan Murray | soc: apple: rtkit-helper: Keep serving buffer requests on T8140 adopted sessions | Not applicable — PERIPH; `drivers/soc/apple/rtkit-helper.c` | V | -| [4d88194af46e](https://github.com/aurora-silicon/linux/commit/4d88194af46e4eec12e57c3e7ff8bbcf7ac5b856) | Ryan Murray | pmdomain: apple: pmgr-pwrstate: Honour apple,inherited-on only on T8132 [#400](https://github.com/aurora-silicon/linux/pull/400) | Not applicable — G16; `drivers/pmdomain/apple/pmgr-pwrstate.c` | V | -| [d14b566cc309](https://github.com/aurora-silicon/linux/commit/d14b566cc309cf6840199c6394dc8f5f75f82f54) | Ryan Murray | drm/asahi: g17: describe the 25G83 barrier and parameter block plainly [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/g17/buffer/target.rs` | V | -| [f0f00dca4b09](https://github.com/aurora-silicon/linux/commit/f0f00dca4b09c9caf6f379928827e0d10451c66b) | Ryan Murray | drm/asahi: mem: document that page-by-page invalidation is global [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/mem.rs` | V | -| [8eacef90ff89](https://github.com/aurora-silicon/linux/commit/8eacef90ff8952b6fc75a85cb20abce488bcd4ed) | Erik Bourget | drm/asahi: g16: accept the 8-core J713 loaded 25G83 image [#442](https://github.com/aurora-silicon/linux/pull/442) | Not applicable — G16; `drivers/gpu/drm/asahi/g16/hw.rs` | V | -| [da42c7cf4fc8](https://github.com/aurora-silicon/linux/commit/da42c7cf4fc83e68261f1c238b2a3b870f94a128) | Ryan Murray | drm/asahi: test shared firmware identity normalization [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — VERIFY; `drivers/gpu/drm/asahi/fwid.rs` | V | -| [b11a5e9e8cd8](https://github.com/aurora-silicon/linux/commit/b11a5e9e8cd83d4ac3ac40bc620de254b095c75d) | DjDeveloperr | cpufreq: apple: verify T8140 transitions on the next request [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [e2a2d8ecbb24](https://github.com/aurora-silicon/linux/commit/e2a2d8ecbb24146ff61e1649ff503f234e846b30) | DjDeveloperr | cpufreq: apple: verify T8140 fast-switch requests from a timer [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [b7ea3ca9de07](https://github.com/aurora-silicon/linux/commit/b7ea3ca9de073d66f0e031013b7853c3e5702479) | DjDeveloperr | cpufreq: apple: settle T8140 lazy requests before suspend [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | C,I | -| [6f5d208b4ce0](https://github.com/aurora-silicon/linux/commit/6f5d208b4ce01ff8cfea04fa21f14ac9a7cb610c) | DjDeveloperr | cpufreq: apple: apply a lowered T8140 fast die limit at once [#443](https://github.com/aurora-silicon/linux/pull/443) | Not applicable — LAZY; `drivers/cpufreq/apple-soc-cpufreq.c` | P | -| [b884471f5b13](https://github.com/aurora-silicon/linux/commit/b884471f5b13e62de9105bb0f06362fe01663a75) | Ryan Murray | thermal: apple-smc-cpu-thermal: walk the OPP table by die temperature | Not applicable — OLDTHERMAL; `drivers/thermal/apple-smc-cpu-thermal.c` | P | -| [ca1dab3dde89](https://github.com/aurora-silicon/linux/commit/ca1dab3dde89c57cc0b111fd096478241e6565e5) | Ryan Murray | cpufreq: apple-soc: Drop the SMC CPU thermal policy hooks | Not applicable — OLDTHERMAL; `drivers/cpufreq/apple-soc-cpufreq.c` | P | -| [52006c8e0bc5](https://github.com/aurora-silicon/linux/commit/52006c8e0bc5750331643c2f36ebad06ef300079) | Ryan Murray | thermal: Remove the Apple SMC CPU thermal policy [#43](https://github.com/aurora-silicon/linux/pull/43) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — OLDTHERMAL; `drivers/thermal/Kconfig` | P | -| [1ce75ee9e797](https://github.com/aurora-silicon/linux/commit/1ce75ee9e797c296f742abf955764fa00b77e03d) | Ryan Murray | treewide: apple: t8140: Describe observed behaviour, not other implementations | Not applicable — VERIFY; `drivers/media/platform/apple/isp/isp-cam.c` | V | -| [3b0af1da96c2](https://github.com/aurora-silicon/linux/commit/3b0af1da96c28777073ebf99d65f1498a5f9fe94) | Ace | PCI: apple: enable bounded J700 endpoint bootstrap and enumeration | Not applicable — PERIPH; `drivers/pci/controller/Kconfig` | V | -| [e179042ff067](https://github.com/aurora-silicon/linux/commit/e179042ff0673c4b5adc749cb0fc3fcb0f909106) | Acelogic | HID: dockchannel: support firmware-managed M5 trackpad power | Not applicable — OTHERCHIP; `drivers/hid/dockchannel-hid/dockchannel-hid.c` | V | -| [f19bcf1a1e37](https://github.com/aurora-silicon/linux/commit/f19bcf1a1e373fb5bae2c9a5a0153d7820b13645) | Joshua Warren | drm/asahi: stats: Add StatsSnapshot and firmware-stats decoder [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/stats.rs` | T | -| [72d21d654534](https://github.com/aurora-silicon/linux/commit/72d21d654534decaecc58af0f8fc813064e6f500) | Joshua Warren | drm/asahi: Wire StatsSnapshot into StatsChannel and GpuManager [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [e8c789f9f77b](https://github.com/aurora-silicon/linux/commit/e8c789f9f77baf73f21857ca29a527930ed12aab) | Joshua Warren | drm/asahi: Add sysfs shim for agx_stats [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [1b02b0b40af3](https://github.com/aurora-silicon/linux/commit/1b02b0b40af3822e16b5842e21964be40a42025f) | Joshua Warren | drm/asahi: Register agx_stats sysfs file on probe and unregister on drop [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/driver.rs` | T | -| [742f54c4855d](https://github.com/aurora-silicon/linux/commit/742f54c4855d0e3b4db54da4663d421f63d1165a) | Joshua Warren | drm/asahi: count completed submissions in agx_stats jobs [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/gpu.rs` | T | -| [bbfb96f309c8](https://github.com/aurora-silicon/linux/commit/bbfb96f309c8dd264540281469bba6c4a48ee789) | Joshua Warren | drm/asahi: link the sysfs shim into the driver module correctly [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/Makefile` | T | -| [01d19b8a4f55](https://github.com/aurora-silicon/linux/commit/01d19b8a4f55bb202b5c9d85a36996a90537602c) | Joshua Warren | drm/asahi: propagate the stats snapshot allocation result [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/gpu.rs` | T | -| [91c24dc11b09](https://github.com/aurora-silicon/linux/commit/91c24dc11b093be4868234ac2e00eed670d1e741) | Joshua Warren | drm/asahi: decode the stats messages where StatsMsg is nameable [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [dbc8b48aeb06](https://github.com/aurora-silicon/linux/commit/dbc8b48aeb06f85c9e7f9b63be9db7afef074580) | Joshua Warren | drm/asahi: qualify the versioned StatsMsg variant patterns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [4189501b643f](https://github.com/aurora-silicon/linux/commit/4189501b643f404faa0ea37fc3bb379226300aa9) | Joshua Warren | drm/asahi: fix the agx_stats readout layout and the off-arm string [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/driver.rs` | T | -| [0b923fb29c84](https://github.com/aurora-silicon/linux/commit/0b923fb29c840b9bb675ba8ad9e81c513903b516) | Joshua Warren | drm/asahi: integrate utilization-weighted time into agx_stats busy_ns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [9250872b1f33](https://github.com/aurora-silicon/linux/commit/9250872b1f33f357c01ccd3bf79be7835fc5c982) | Joshua Warren | drm/asahi: convert stats timestamps from base-clock ticks to ns [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [993288b37ec4](https://github.com/aurora-silicon/linux/commit/993288b37ec4368bbf2debbbd73124d8a2652410) | Joshua Warren | drm/asahi: split the tick window to avoid 128-bit division [#197](https://github.com/aurora-silicon/linux/pull/197) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — STAT; `drivers/gpu/drm/asahi/channel.rs` | T | -| [9aebc2952fb5](https://github.com/aurora-silicon/linux/commit/9aebc2952fb51f6b0b9c03222109fe7f0ac107c2) | Ryan Murray | arm64: dts: apple: retain the T8140 P-cluster domain cells [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — BOARD | B | -| [e3163ca622d6](https://github.com/aurora-silicon/linux/commit/e3163ca622d6c55979d963929edbdf47f2c4c38c) | Ryan Murray | soc: apple: expose the T8140 PMP DVFS report for diagnosis [#182](https://github.com/aurora-silicon/linux/pull/182) [#380](https://github.com/aurora-silicon/linux/pull/380) [#470](https://github.com/aurora-silicon/linux/pull/470) | Not applicable — RAWDIAG; `drivers/pmdomain/apple/pmp-report.c` | O | -| [14e101ee2b8b](https://github.com/aurora-silicon/linux/commit/14e101ee2b8b599cf627015368e16ff8b3d2b95f) | Ryan Murray | cpufreq: apple: retain the unmanaged T8152 P-state ceiling | Not applicable — OTHERCHIP; `drivers/cpufreq/apple-soc-cpufreq.c` | V | -| [19d6664ea33a](https://github.com/aurora-silicon/linux/commit/19d6664ea33affcceef42d5deef488ce1ba7d50d) | Ryan Murray | arm64: dts: apple: retain a single J700 PMP alias | Not applicable — BOARD | B | -| [98038492dc48](https://github.com/aurora-silicon/linux/commit/98038492dc481d784c76fb2c52f3dd030dfad8f5) | Ryan Murray | drm: apple: recognize the T8140 external binding in the display master | Not applicable — BOARD; `drivers/gpu/drm/apple/apple_drv.c` | B | -| [78fc11047efa](https://github.com/aurora-silicon/linux/commit/78fc11047efa814a238113c46b4bb07aa7d641fb) | Ryan Murray | arm64: dts: apple: give the external J700 trial its firmware DMA window | Not applicable — PERIPH | V | -| [bc3b8aaa560f](https://github.com/aurora-silicon/linux/commit/bc3b8aaa560f23e069a7ea2d774645ea5fec39cc) | Ryan Murray | arm64: dts: apple: select the second external DCP source on J700 | Not applicable — PERIPH | V | -| [d08fd52e1619](https://github.com/aurora-silicon/linux/commit/d08fd52e161953a481a464716dd68aae85338044) | DjDeveloperr | drm/apple: enable the validated J700 external display profile by default | Not applicable — BOARD; `drivers/gpu/drm/apple/dcp-external-bw.h` | B | -| [01c8fe5e98f4](https://github.com/aurora-silicon/linux/commit/01c8fe5e98f4ab8805957ca3206d6d46a65b62e7) | Ryan Murray | soc: apple: aop: Do not overrun unread entries in the transmit ring [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [02694d65655b](https://github.com/aurora-silicon/linux/commit/02694d65655baae0536d47beef4f0356145069f4) | Ryan Murray | spi: apple-qspi: Resume the controller even if its reset fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [033fa5e3c095](https://github.com/aurora-silicon/linux/commit/033fa5e3c0959f772e8464a25b8b93773f39b5b9) | Ryan Murray | soc: apple: aop: Accept a transmit entry at a write pointer of zero [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop_ring.rs` | V | -| [0790f8a546fe](https://github.com/aurora-silicon/linux/commit/0790f8a546fea7ae46871d857643568c1b3c0c64) | Ryan Murray | hwmon: macsmc: drop the check for the undefined apple,cpu-thermal-policy [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/macsmc-hwmon.c` | V | -| [0943ae25f9bd](https://github.com/aurora-silicon/linux/commit/0943ae25f9bd82917a7a4813962d624d22056fd3) | Ryan Murray | HID: dockchannel-hid: Reject unaligned packet lengths before checksumming [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c` | V | -| [0c55425a8157](https://github.com/aurora-silicon/linux/commit/0c55425a8157326aa0bafd20a1c30a0f34af8650) | Ryan Murray | dt-bindings: gpu: apple,agx: Require three cells in apple,firmware-version [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [152cc6b4d737](https://github.com/aurora-silicon/linux/commit/152cc6b4d737c3523b56d1c4b0b4cd3928e514b5) | Ryan Murray | spi: apple-qspi: Do not print a banner on probe [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [1baee970e0a9](https://github.com/aurora-silicon/linux/commit/1baee970e0a9d5bf0343f72eed61badfc5918159) | Jonathan Goyvaerts | dt-bindings: mailbox: apple,ascwrap-v6: Add the T6040 [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [1df5bd529669](https://github.com/aurora-silicon/linux/commit/1df5bd529669987e8804b6ab38dbd1d5175f508d) | Ryan Murray | HID: dockchannel-hid: Test MTP message bounds with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [1f7383d5a281](https://github.com/aurora-silicon/linux/commit/1f7383d5a2811b99a9f2950581ec392837bfc469) | DjDeveloperr | rust: check generated layouts and provide corrected private bindgen [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [232faf36664c](https://github.com/aurora-silicon/linux/commit/232faf36664c7e23aa9950bc3019dbf6ba534ee8) | Ryan Murray | HID: dockchannel-hid: Keep parser tests in the subsystem menu [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [2d5c7b6bc705](https://github.com/aurora-silicon/linux/commit/2d5c7b6bc705f0ba8eef8f3d1ea23a53d4248eba) | Ryan Murray | ASoC: apple: t8140-aop-audio: Refuse card names that do not fit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH | V | -| [3006ca1a3835](https://github.com/aurora-silicon/linux/commit/3006ca1a383525a092ad1cbe9c268786292a32de) | Ryan Murray | mfd: macsmc: Test key and fixed-width readers with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/mfd/Kconfig` | V | -| [3024185f2efa](https://github.com/aurora-silicon/linux/commit/3024185f2efa34c4ea8ac9eebebf06b921795f0b), [aaea0b3a4fcf](https://github.com/aurora-silicon/linux/commit/aaea0b3a4fcf5cb371b735c6b595a2919a6a4d07) | DjDeveloperr | dt-bindings: power: add Apple PMC voter interface [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Not applicable — VERIFY | V | -| [3132675b256e](https://github.com/aurora-silicon/linux/commit/3132675b256e07ad782280c42c853c63f6d18ef1) | Ryan Murray | selftests: apple-dcp: Run the queue recovery control through the RX drain [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [315f6dc9944d](https://github.com/aurora-silicon/linux/commit/315f6dc9944de65990476dae34079d3e1313d605) | Chris Kearney | soc: apple: mailbox: match the T8122 GPU mailbox without the v4 fallback | Not applicable — G15; `drivers/soc/apple/mailbox.c` | V | -| [3407efe83df6](https://github.com/aurora-silicon/linux/commit/3407efe83df680534e10c0e66ffa36b75cae69ba) | Jonathan Goyvaerts | dt-bindings: soc: apple,t8140-mcc: Add the T6040 MCC [#385](https://github.com/aurora-silicon/linux/pull/385) | Not applicable — VERIFY | V | -| [35d6b26e5c9d](https://github.com/aurora-silicon/linux/commit/35d6b26e5c9d8bf22ce6284bf0594084ffd2dcdf) | Ryan Murray | soc: apple: aop: Test that a wrapped entry is refused below the read pointer [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/soc/apple/aop_ring.rs` | V | -| [4b8d29e13da6](https://github.com/aurora-silicon/linux/commit/4b8d29e13da638bf7ba7f532844c5e368505bf20) | Jonathan Goyvaerts | dt-bindings: gpu: apple,agx: allow a fw-text region on the T6040 [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — VERIFY | V | -| [4c5aad430f62](https://github.com/aurora-silicon/linux/commit/4c5aad430f6283d1d6b3b961a87d1629b397f22f) | DjDeveloperr | dt-bindings: mailbox: apple,mailbox: Add the T8140 GPU mailboxes [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [543ac70dce46](https://github.com/aurora-silicon/linux/commit/543ac70dce46b749f1a446cb80d4e63cf08949cd) | Ryan Murray | drm: apple: parser: add KUnit tests for malformed dictionaries [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/gpu/drm/apple/Makefile` | V | -| [5b62d0c81387](https://github.com/aurora-silicon/linux/commit/5b62d0c81387e8d0d68f2a88244eeb7a618f9ec1) | Ryan Murray | mfd: macsmc: Preserve the key output on lookup failure [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [5e03e15dae17](https://github.com/aurora-silicon/linux/commit/5e03e15dae1740326b41df4777a5ee4b7502c02e), [94f215eaa642](https://github.com/aurora-silicon/linux/commit/94f215eaa6424e8f077f1447e78e35b3ebeb6542) | DjDeveloperr | dt-bindings: power: apple,t8140-pmp-report: describe report entries [#212](https://github.com/aurora-silicon/linux/pull/212) [#219](https://github.com/aurora-silicon/linux/pull/219) | Not applicable — VERIFY | V | -| [66db357bd614](https://github.com/aurora-silicon/linux/commit/66db357bd614c7f8e25dab080574c31dab6c0ed2) | Ryan Murray | tools/asahi: measure CPU cost of small render submissions [#201](https://github.com/aurora-silicon/linux/pull/201) | Not applicable — VERIFY | V | -| [6e2835ae7bd6](https://github.com/aurora-silicon/linux/commit/6e2835ae7bd6d16570464106bdfb740b6fed27c4) | Naeem Malik | soc: apple: mailbox: match the T6031 GPU mailbox without the v4 fallback | Not applicable — G15; `drivers/soc/apple/mailbox.c` | V | -| [712530b9753f](https://github.com/aurora-silicon/linux/commit/712530b9753fd8692b31382b3e9c6aaaa720ffe0) | Ryan Murray | gpio: macsmc: tidy the J700 pcIO helpers [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/gpio/gpio-macsmc.c` | V | -| [7a6e327251cc](https://github.com/aurora-silicon/linux/commit/7a6e327251cc51d0a483483f0b81dda99a811791) | Ryan Murray | soc: apple: aop: Validate the receive ring before taking entries [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [807cb8976697](https://github.com/aurora-silicon/linux/commit/807cb8976697ff272433278b272444ced7e91d57) | Ryan Murray | hwmon: macsmc: account for temperature channels in one helper [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/macsmc-hwmon.c` | V | -| [83039e319faf](https://github.com/aurora-silicon/linux/commit/83039e319faf3e49ceabc424c7c69180ac997dfd) | Ryan Murray | dt-bindings: apple: use the canonical SPDX form in PMP, PMC and report bindings [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — VERIFY | V | -| [87314d48cc08](https://github.com/aurora-silicon/linux/commit/87314d48cc080bcf535291dc636f1ec6164a06f9) | Ryan Murray | drm/apple: Test firmware message bounds with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/gpu/drm/apple/Kconfig` | V | -| [910327707f85](https://github.com/aurora-silicon/linux/commit/910327707f852c060b5ada81e64a2a4563cb64b4) | Ryan Murray | ASoC: apple: Test T8140 AOP producer reports with KUnit [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [95b26591a1c4](https://github.com/aurora-silicon/linux/commit/95b26591a1c4b446656c3bc8a257a17792917a78) | Ryan Murray | spi: apple: Reword the hardware CS delay comment [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — VERIFY; `drivers/spi/spi-apple.c` | V | -| [966e777fd568](https://github.com/aurora-silicon/linux/commit/966e777fd568565b88c5f8ba4acb36463ae31e47) | Ryan Murray | MAINTAINERS: keep T8140 PMP coverage under Aurora [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — VERIFY | V | -| [a1f9aabbe6a9](https://github.com/aurora-silicon/linux/commit/a1f9aabbe6a9771a4dbf3259bc808713f0daac46) | Ryan Murray | dt-bindings: apple: describe PMP fast-die reporting on T8140 [#179](https://github.com/aurora-silicon/linux/pull/179) | Not applicable — VERIFY | V | -| [a239464d233d](https://github.com/aurora-silicon/linux/commit/a239464d233d2e94b89dea159f298b70e015b6a6) | Ryan Murray | kunit: Add an Apple firmware parser test configuration [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [a27007e6ace3](https://github.com/aurora-silicon/linux/commit/a27007e6ace3815d11c340c25a3ee90cfb2981b0) | Ryan Murray | HID: dockchannel: Log routine interface set-up at debug level [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/dockchannel-hid.c` | V | -| [a494d618f5a9](https://github.com/aurora-silicon/linux/commit/a494d618f5a9af40ae466166176ae36476b4638a) | Ryan Murray | mfd: macsmc: Hold the mutex while decoding key metadata [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [b8f892b79561](https://github.com/aurora-silicon/linux/commit/b8f892b79561ea085c0ab2e44368f873f15b9183) | Ryan Murray | soc: apple: aop: Decode ring entry headers without pointer casts [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/soc/apple/aop.rs` | V | -| [ba6eb20e2ed9](https://github.com/aurora-silicon/linux/commit/ba6eb20e2ed9065a2925d0f16ae030acfaeceefe) | Ryan Murray | soc: apple: mailbox: Describe the ASCWrap v6 CPU start and stop in hardware terms | Not applicable — VERIFY; `drivers/soc/apple/mailbox.c` | V | -| [bc7394673cbe](https://github.com/aurora-silicon/linux/commit/bc7394673cbed4ef22971a49926be6070a7312be) | DjDeveloperr | tools: preserve bindgen recipe validation across Python modes [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [bd7739d6232e](https://github.com/aurora-silicon/linux/commit/bd7739d6232e818ef7cf30acbcc50d24723e061c) | Ryan Murray | mfd: macsmc: Reject short fixed-width replies [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [c49ab96deb3c](https://github.com/aurora-silicon/linux/commit/c49ab96deb3c378015d1db27bf2122c837fd3bc0) | DjDeveloperr | dt-bindings: gpu: apple,agx: Add apple,agx-t8140 [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — VERIFY | V | -| [c9c779d6a2ba](https://github.com/aurora-silicon/linux/commit/c9c779d6a2bae406a9d48b7f733b16fd253730c7) | Jonathan Goyvaerts | dt-bindings: soc: apple,pmp: Add the T6040 PMP [#374](https://github.com/aurora-silicon/linux/pull/374) | Not applicable — VERIFY | V | -| [cbd157ef2a12](https://github.com/aurora-silicon/linux/commit/cbd157ef2a12a46e3caf5367de912a525d8d4874) | Ryan Murray | hwmon: macsmc: keep the channel of a temperature sensor that fails to set up [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/hwmon/Kconfig` | V | -| [cf4ce5f41f4b](https://github.com/aurora-silicon/linux/commit/cf4ce5f41f4b86c4084b49ec6585377e16fd53b7) | Chris Kearney | thunderbolt, phy, soc: apple: T6030 USB4/Thunderbolt, Type-C and DP tunnel support | Not applicable — G15; `drivers/iommu/of_iommu.c` | V | -| [d36196335065](https://github.com/aurora-silicon/linux/commit/d36196335065346ef57a323e483002151670320c) | Ryan Murray | arm64: dts: apple: t6040-j616s: Keep the GPU disabled [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — SUPERSEDED | B | -| [d717a601430a](https://github.com/aurora-silicon/linux/commit/d717a601430aea6711ffc7486f5edb16ca7e7f66) | Jonathan Goyvaerts | dt-bindings: gpu: apple,agx: Add apple,agx-t6040 [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — VERIFY | V | -| [d90daf04de84](https://github.com/aurora-silicon/linux/commit/d90daf04de8431f70eed8b590a532f38a6249095) | Ryan Murray | media: apple: isp: Do not trust the batch count when a batch fails [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/media/platform/apple/isp/isp-v4l2.c` | V | -| [d9aface7ea85](https://github.com/aurora-silicon/linux/commit/d9aface7ea8533965e33476631c8dbc44dfeb439) | Ryan Murray | HID: dockchannel: Build the protocol KUnit test only with the driver [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hid/dockchannel-hid/Kconfig` | V | -| [e65283c42678](https://github.com/aurora-silicon/linux/commit/e65283c426783b12298f72896ef6f0dc33c4222c) | Ryan Murray | ASoC: apple: t8140-aop-audio: Let power request sequences wrap [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH | V | -| [e666e50ccfe8](https://github.com/aurora-silicon/linux/commit/e666e50ccfe8c58e8fa72bdf7ef6bedffec6551a) | Ryan Murray | rtc: macsmc: correct the comment on the whole-second offset [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — PERIPH; `drivers/rtc/rtc-macsmc.c` | V | -| [e99a6adbeba7](https://github.com/aurora-silicon/linux/commit/e99a6adbeba77b7ed032ef61f864afb3da8fe3a9) | Ryan Murray | dt-bindings: hwmon: apple,smc-hwmon: drop apple,cpu-thermal-policy [#317](https://github.com/aurora-silicon/linux/pull/317) | Not applicable — VERIFY | V | -| [ec34fb1f2835](https://github.com/aurora-silicon/linux/commit/ec34fb1f2835b291f978bd091ed73347cba7ceae) | Ryan Murray | mfd: macsmc: Reject out-of-range key indices [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/mfd/macsmc.c` | V | -| [ed0925cdf091](https://github.com/aurora-silicon/linux/commit/ed0925cdf091083ba1efee97bbb288e9c331f812) | Ryan Murray | spi: apple-qspi: Restore the controller configuration after system sleep [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/spi/spi-apple-qspi.c` | V | -| [ee6f48ce60bd](https://github.com/aurora-silicon/linux/commit/ee6f48ce60bdf68d596c4bedd31e35f55cd6bb03) | Ryan Murray | MAINTAINERS: Cover Apple firmware parser tests [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY | V | -| [f3324e0de0e2](https://github.com/aurora-silicon/linux/commit/f3324e0de0e26bd43df402001c2e3f0f16821520) | Jonathan Goyvaerts | dt-bindings: power: apple,pmc: Add the T6040 PMC and CLPC [#385](https://github.com/aurora-silicon/linux/pull/385) | Not applicable — VERIFY | V | -| [f52e01d6925d](https://github.com/aurora-silicon/linux/commit/f52e01d6925de5022176c5038ff13cc9ad17559b) | Ryan Murray | dt-bindings: gpu: apple,agx: Match the T8140 register layout [#314](https://github.com/aurora-silicon/linux/pull/314) | Not applicable — VERIFY | V | -| [fdd138bbc722](https://github.com/aurora-silicon/linux/commit/fdd138bbc7228b8b1a232268e2a02cc126b24d95) | Ryan Murray | hwmon: macsmc: move the module help text back to its option [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — PERIPH; `drivers/hwmon/Kconfig` | V | -| [fec5e40ebade](https://github.com/aurora-silicon/linux/commit/fec5e40ebade9f7cf3684acfbb9d603d5b82127a) | Jonathan Goyvaerts | dt-bindings: power: apple,t8140-pmp-report: Add the T6040 aperture [#374](https://github.com/aurora-silicon/linux/pull/374) | Not applicable — VERIFY | V | -| [ff3ebdbad58c](https://github.com/aurora-silicon/linux/commit/ff3ebdbad58c1c50dadbf9cecd7f67aada516dc1) | Ryan Murray | nvme-apple: Reword two post-M4 handoff comments [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — VERIFY; `drivers/nvme/host/apple.c` | V | - -### Merge/provenance records - -Parent mechanisms are listed above; no isolated speedup is assigned here. - -| Commits / encountered aliases | Author | Improvement / record | T6040 after ports — evidence key and changed source | Measurement | -| --- | --- | --- | --- | --- | -| [00463d1d4031](https://github.com/aurora-silicon/linux/commit/00463d1d40317155246a13573aeab60ff773b51b), [f566e6098c67](https://github.com/aurora-silicon/linux/commit/f566e6098c676566b02a191eb58e5783fa7bf0b6) | Janne Grunau | Merge branch 'bits/010-soc' into asahi-wip | Not applicable — MERGE | V | -| [80390ef034fc](https://github.com/aurora-silicon/linux/commit/80390ef034fcfaf212674bc53b0a91e596409bcf), [5e35a79dac7f](https://github.com/aurora-silicon/linux/commit/5e35a79dac7f0958af6bd3ae9ea4517d22769cb2) | Janne Grunau | Merge branch 'bits/020-dart' into asahi-wip | Not applicable — MERGE | V | -| [4eea6c6d47ba](https://github.com/aurora-silicon/linux/commit/4eea6c6d47bab3a334b9c1633279c4392e2a4de7), [57710743dc8c](https://github.com/aurora-silicon/linux/commit/57710743dc8c0e9286115f38ad19a298cd36cc50) | Janne Grunau | Merge branch 'bits/030-misc' into asahi-wip | Not applicable — MERGE | V | -| [59f7e8be4e3b](https://github.com/aurora-silicon/linux/commit/59f7e8be4e3b693a96a1dd3b2355aa65dd784b0e), [466efd223bbf](https://github.com/aurora-silicon/linux/commit/466efd223bbf43f9e0f4f7065c67d6d4e97fc04c) | Janne Grunau | Merge branch 'bits/090-spi-hid' into asahi-wip | Not applicable — MERGE | V | -| [2871ed01752e](https://github.com/aurora-silicon/linux/commit/2871ed01752ef74924608f23b5edd7927ae4b71c), [f55090a2d12a](https://github.com/aurora-silicon/linux/commit/f55090a2d12a6fd3dad485a7621392b8f508f8a8) | Janne Grunau | Merge branch 'bits/190-rust' into asahi-wip | Not applicable — MERGE | V | -| [cd36abb1e1d2](https://github.com/aurora-silicon/linux/commit/cd36abb1e1d2bcead322aedaed3cab7cbbab5d4b), [3f3dfd6ef171](https://github.com/aurora-silicon/linux/commit/3f3dfd6ef171f4c3801e1bd8b7c880774e17f1ad) | Janne Grunau | Merge branch 'bits/210-gpu' into asahi-wip | Not applicable — MERGE | V | -| [d6c7409e354f](https://github.com/aurora-silicon/linux/commit/d6c7409e354fee96c74a0aa68c5cbd0cdc0b8d92), [39b401626267](https://github.com/aurora-silicon/linux/commit/39b4016262672c0f87d7e5af835f42b9632dcc6c) | Janne Grunau | Merge branch 'bits/250-aop' into asahi-wip | Not applicable — MERGE | V | -| [072195f87df8](https://github.com/aurora-silicon/linux/commit/072195f87df8ca94580cf5ca0d9a801e5bd217e4), [11ee430b3cf2](https://github.com/aurora-silicon/linux/commit/11ee430b3cf20a6611bea0462335f0ae975a40d7) | Janne Grunau | Merge branch 'bits/500-backports' into asahi-wip | Not applicable — MERGE | V | -| [fe8324184dd8](https://github.com/aurora-silicon/linux/commit/fe8324184dd8c6d3b09a532a9cb6a533c561a324) | Ryan Murray | Merge tag 'v7.3' into unified-7.3/base | Not applicable — MERGE | V | -| [cb8e5e495b88](https://github.com/aurora-silicon/linux/commit/cb8e5e495b88f638c22782136a8721a4f26f4346) | Ryan Murray | Merge branch 'unified/bits/010-soc' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [6de20e534e47](https://github.com/aurora-silicon/linux/commit/6de20e534e473dd9efd9e14c727883df6036d60b) | Ryan Murray | Merge branch 'unified/bits/020-dart' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [15fe1cbe72df](https://github.com/aurora-silicon/linux/commit/15fe1cbe72df8d8eb79b2dec500e58bbc5f57647) | Ryan Murray | Merge branch 'unified/bits/060-power-thermal' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [939cccf33380](https://github.com/aurora-silicon/linux/commit/939cccf333802c32a319f0ddb4b0d01c85aab990) | Ryan Murray | Merge branch 'unified/bits/070-audio' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [2409e9da1efb](https://github.com/aurora-silicon/linux/commit/2409e9da1efb9494fc9437ce9f3bd909c0f7dd36) | Ryan Murray | Merge branch 'unified/bits/100-sep' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [2bc8aa67f178](https://github.com/aurora-silicon/linux/commit/2bc8aa67f17817c22c6bacaecd7ecf4df8e8c63d) | Ryan Murray | Merge branch 'unified/bits/200-dcp' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [c00586c09e2b](https://github.com/aurora-silicon/linux/commit/c00586c09e2bab26f92ddd5b943cbcc66c047ff5) | Ryan Murray | Merge branch 'unified/bits/210-gpu' into rebase-wip/7.2.10-unified | Not applicable — MERGE | V | -| [14ca49f98175](https://github.com/aurora-silicon/linux/commit/14ca49f98175b54c37fa16af766e11f163d3a80f) | Ryan Murray | Merge branch 'unified-7.3/bits/010-soc' into unified-7.3/canonical | Not applicable — MERGE | V | -| [665a5ca84508](https://github.com/aurora-silicon/linux/commit/665a5ca845081049335f69d0bf27c66c90898b7b) | Ryan Murray | Merge branch 'unified-7.3/bits/020-dart' into unified-7.3/canonical | Not applicable — MERGE | V | -| [c217f4f47bf0](https://github.com/aurora-silicon/linux/commit/c217f4f47bf003c8fb39400d1af8179b552c497e) | Ryan Murray | Merge branch 'unified-7.3/bits/060-power-thermal' into unified-7.3/canonical | Not applicable — MERGE | V | -| [5bdd6c5b2c80](https://github.com/aurora-silicon/linux/commit/5bdd6c5b2c80a6f16c8835a57a5d56d26af67839) | Ryan Murray | Merge branch 'unified-7.3/bits/070-audio' into unified-7.3/canonical | Not applicable — MERGE | V | -| [f3c8cf25dd5d](https://github.com/aurora-silicon/linux/commit/f3c8cf25dd5d01f3871267c1b77df343dbef045d) | Ryan Murray | Merge branch 'unified-7.3/bits/100-sep' into unified-7.3/canonical | Not applicable — MERGE | V | -| [c15790e20e01](https://github.com/aurora-silicon/linux/commit/c15790e20e01e8562e0b54a00bee8a8ef9ded84b) | Ryan Murray | Merge branch 'unified-7.3/bits/200-dcp' into unified-7.3/canonical | Not applicable — MERGE | V | -| [ea36d4240e40](https://github.com/aurora-silicon/linux/commit/ea36d4240e40fc7607d568a8fa56f1fa5cf01c03) | Ryan Murray | Merge branch 'unified-7.3/bits/210-gpu' into unified-7.3/canonical | Not applicable — MERGE | V | -| [94141d397eae](https://github.com/aurora-silicon/linux/commit/94141d397eaede2ba95eab7279f4bc18f75bb9d1) | Ryan | Merge pull request #374 from jgoyvaerts/m4pro/pmp-t6041 | Not applicable — MERGE | V | -| [4e5eea54ce7e](https://github.com/aurora-silicon/linux/commit/4e5eea54ce7e1c9d21867d81c5e5672e1cbd1c34) | Ryan | Merge pull request #368 from jgoyvaerts/m4pro/small-fixes | Not applicable — MERGE | V | -| [815438428a9e](https://github.com/aurora-silicon/linux/commit/815438428a9e45f0facbb10c4f9bd77047ef7282) | Ryan | Merge pull request #385 from jgoyvaerts/m4pro/pmc-clpc-mcc-t6040 | Not applicable — MERGE | V | -| [49273fd6921c](https://github.com/aurora-silicon/linux/commit/49273fd6921c9b39101cd1ee8c8d2f2ca0153440) | Ryan | Merge pull request #386 from jgoyvaerts/m4pro/apple-dart-t6040 | Not applicable — MERGE | V | -| [50a912fe81fc](https://github.com/aurora-silicon/linux/commit/50a912fe81fcdbd770d231db8eda856a1678c194) | Ryan | Merge pull request #391 from jgoyvaerts/m4pro/g17-generic | Not applicable — MERGE | V | -| [311471f73e99](https://github.com/aurora-silicon/linux/commit/311471f73e9919764bfb24acfe7eeb7c5230795a) | Ryan | Merge pull request #402 from aurora-silicon/j616s/pmp-ep7-20261024 | Not applicable — MERGE | V | -| [1aa2857509d5](https://github.com/aurora-silicon/linux/commit/1aa2857509d50f7f787541280aba7b274721919c) | Ryan | Merge pull request #403 from aurora-silicon/j616s/usb-20261023 | Not applicable — MERGE | V | -| [04231230fd76](https://github.com/aurora-silicon/linux/commit/04231230fd76fadd12a8b44707159f37f0e498b1), [e9a9b647d0f3](https://github.com/aurora-silicon/linux/commit/e9a9b647d0f36e222f16de732f78f2d77ea2d661), [b9a73d410ff4](https://github.com/aurora-silicon/linux/commit/b9a73d410ff48c65624c9283c634b4d06f4dfc6a), [4433181e4eb6](https://github.com/aurora-silicon/linux/commit/4433181e4eb649033f07751001fbb72621752647) | Jonathan Goyvaerts, Ryan Murray | Merge integration/aurora into the T6040 GPU series [#420](https://github.com/aurora-silicon/linux/pull/420) | Not applicable — MERGE | V | -| [2a868cf22d90](https://github.com/aurora-silicon/linux/commit/2a868cf22d90f0de72b2ad3c339b93460fdb9927) | Ryan | Merge pull request #413 from jgoyvaerts/m4pro/g17-robustness | Not applicable — MERGE | V | -| [2e9e457c922d](https://github.com/aurora-silicon/linux/commit/2e9e457c922d799dcc27975ff6f5d114d2719f3f) | Ryan | Merge pull request #418 from aurora-silicon/ryan/g17-innocent-clients-413 | Not applicable — MERGE | V | -| [127df1be31af](https://github.com/aurora-silicon/linux/commit/127df1be31af90613079dcedaeaf0a2aa9ae7d10) | Ryan Murray | Merge integration/aurora into aurora-wip-sync-177 | Not applicable — MERGE | V | -| [e5dad6df06f6](https://github.com/aurora-silicon/linux/commit/e5dad6df06f66b944037770e81e6a481a0b8302f), [d1b62dc403c6](https://github.com/aurora-silicon/linux/commit/d1b62dc403c6f9ed534850f204f069befca149f1) | Ryan Murray | Merge integration/aurora into m4pro/g17-t6040-text-identity [#428](https://github.com/aurora-silicon/linux/pull/428) | Not applicable — MERGE | V | -| [a1b269f79e35](https://github.com/aurora-silicon/linux/commit/a1b269f79e35844660892b9779adb2f68abc38b7) | Ryan | Merge pull request #395: sync omacom #177 (G15, T6030 dock, platform fixes) onto 7.3 | Not applicable — MERGE | V | -| [8bc8f12e95ed](https://github.com/aurora-silicon/linux/commit/8bc8f12e95edbbd5b7d5431973eb1f08c872e87c) | Ryan | Merge pull request #427 from jgoyvaerts/m4pro/asahi-pgtable-checked-borrow | Not applicable — MERGE | V | -| [18012befd69c](https://github.com/aurora-silicon/linux/commit/18012befd69ceed9892c28291132ebd4c05a6076) | Ryan | Merge pull request #428 from jgoyvaerts/m4pro/g17-t6040-text-identity | Not applicable — MERGE | V | -| [41ef596ab373](https://github.com/aurora-silicon/linux/commit/41ef596ab3731ef695fcce2fdfb666bc47da21b7) | Dj | Merge pull request #443 from aurora-silicon/fix/t8140-cpufreq-lazy-verify-20261025 | Not applicable — MERGE | V | -| [af80fbe9094b](https://github.com/aurora-silicon/linux/commit/af80fbe9094b631c5d734883bd259ad0925e88ba) | Dj | Merge pull request #447 from aurora-silicon/fix/aic2-effective-affinity-20261025 | Not applicable — MERGE | V | -| [67fdc27bdadb](https://github.com/aurora-silicon/linux/commit/67fdc27bdadb58520839376a2b85d1265c3fa78f), [b4e5e4cff710](https://github.com/aurora-silicon/linux/commit/b4e5e4cff710c9961a05d4ba6c16f0f8c47c3776) | Chris Kearney | Merge current aurora-wip into the combined Thunderbolt series | Not applicable — MERGE | V | -| [99a554596d0a](https://github.com/aurora-silicon/linux/commit/99a554596d0a4960120b78f9a09ab30ffd4d0fc1) | Chris Kearney | Merge aurora-wip 3bb0a6104a11 into tb-dp-tunnel-t8103 | Not applicable — MERGE | V | -| [5b55206ca89b](https://github.com/aurora-silicon/linux/commit/5b55206ca89bbeb8bb54a208a9b9a36b80d6360b) | Acelogic | Merge M5 CPU support while retaining per-chip frequency safeguards | Not applicable — MERGE | V | -| [95f70d759093](https://github.com/aurora-silicon/linux/commit/95f70d7590935fdfb63c889d73598996dbf6c695) | Ryan Murray | Merge pull request #172 from aurora-silicon/j700-dcp-foundation | Not applicable — MERGE | V | -| [b37df4bdd552](https://github.com/aurora-silicon/linux/commit/b37df4bdd552dca6fa180e7826d0ec22b5e264f4) | Ryan Murray | Merge pull request #8 from iconidentify/tb-dp-tunnel-t8103 | Not applicable — MERGE | V | -| [c9a55efdff8f](https://github.com/aurora-silicon/linux/commit/c9a55efdff8f9505114fab2c89e934ce363e9b3b) | Ryan Murray | Merge pull request #42 from aurora-silicon/feat/sep-neo-rebase | Not applicable — MERGE | V | -| [026b4131cf05](https://github.com/aurora-silicon/linux/commit/026b4131cf0506b0974e6a0ad0b13cfa15f80cc6) | Ryan Murray | Merge pull request #43 from aurora-silicon/feat/j700-thermal-framework-v2 | Not applicable — MERGE | V | -| [e9c631c62252](https://github.com/aurora-silicon/linux/commit/e9c631c6225261125aae251b6a0b743e0663ed37) | Ryan Murray | Merge pull request #46 from aurora-silicon/fix/j414s-dual-dock-dp | Not applicable — MERGE | V | -| [b8fef4b5b0b5](https://github.com/aurora-silicon/linux/commit/b8fef4b5b0b5d1ed5401db1249fc230fc9ce3f60) | Ryan Murray | Merge pull request #156 from aurora-silicon/codex/neo-ave-bringup | Not applicable — MERGE | V | -| [527179cf0856](https://github.com/aurora-silicon/linux/commit/527179cf085663164d17e4d8e8abf2c3e33b5070) | Ryan Murray | Merge pull request #168 from joshuaswarren/agent/jw16-agx-stats4 | Not applicable — MERGE | V | -| [918c0ff6270c](https://github.com/aurora-silicon/linux/commit/918c0ff6270c673e67067453a2e727b5f3e26331) | Ryan Murray | Merge pull request #55 from aurora-silicon/t8140-cpu-capacity | Not applicable — MERGE | V | -| [db4752825c93](https://github.com/aurora-silicon/linux/commit/db4752825c935257fb77f6b8aacf3b4ee003e9fa) | Ryan Murray | Merge pull request #174 from aurora-silicon/j700/t8140-dt-complete | Not applicable — MERGE | V | -| [d8ad51f6b8c8](https://github.com/aurora-silicon/linux/commit/d8ad51f6b8c809444fe4e3f1ef0a1ebb3ba6af5e) | Ryan Murray | Merge pull request #179 from aurora-silicon/j700/pmp-mcc-thermal | Not applicable — MERGE | V | -| [5de43d36cd52](https://github.com/aurora-silicon/linux/commit/5de43d36cd520eaf5df6fc16d047ee413ac54968) | Ryan Murray | Merge pull request #181 from aurora-silicon/j700/t8140-ane-topology | Not applicable — MERGE | V | -| [564976d8e4a6](https://github.com/aurora-silicon/linux/commit/564976d8e4a60dd64a4dc77b2b82f2a0f25f3f45) | Ryan Murray | Merge pull request #182 from aurora-silicon/j700/mcc-telemetry | Not applicable — MERGE | V | -| [4f3a64e7baa9](https://github.com/aurora-silicon/linux/commit/4f3a64e7baa91c6616ae955695e8a5c847dff968) | Ryan | Merge pull request #215 from aurora-silicon/j700/t8140-slc-allocation | Not applicable — MERGE | V | -| [ccedac0c6a30](https://github.com/aurora-silicon/linux/commit/ccedac0c6a30b11b9b1926522a98d4079c9acbf1) | Ryan | Merge pull request #221 from aurora-silicon/j700/display-handoff-race | Not applicable — MERGE | V | -| [123c0d909a8a](https://github.com/aurora-silicon/linux/commit/123c0d909a8af07363e3e885691f0e9feb10c9bc) | Ryan | Merge pull request #223 from aurora-silicon/apple/sashiko-pmp-entry-unbind | Not applicable — MERGE | V | -| [1702229de78f](https://github.com/aurora-silicon/linux/commit/1702229de78f1acd92808b228034839fb7e6c0bc) | Ryan | Merge pull request #232 from aurora-silicon/j700/aop-dart-invalidate | Not applicable — MERGE | V | -| [5c06b1998b8e](https://github.com/aurora-silicon/linux/commit/5c06b1998b8eefdf785b5320a6f8cec31f8da29a) | Ryan | Merge pull request #272 from aurora-silicon/j700/pmgr-failed-power-on | Not applicable — MERGE | V | -| [92ad2a772af8](https://github.com/aurora-silicon/linux/commit/92ad2a772af82a81fc3c73c915a48b9b611db55b) | Ryan Murray | Merge public J700 DP Alt qualification stack into current aurora-wip | Not applicable — MERGE | V | -| [f5afac94ca29](https://github.com/aurora-silicon/linux/commit/f5afac94ca2999c858fb61ebab0bf4b4c168fc6d) | Ryan Murray | drm/apple: compose lean J700 display and automatic recovery candidate | Not applicable — MERGE | V | -| [08e0d0a90be3](https://github.com/aurora-silicon/linux/commit/08e0d0a90be3bb6d777cc1a285ba22bfce12a4d9) | Ryan Murray | drm/apple: integrate reviewed fixed-host lifecycle and scoped boot fixes | Not applicable — MERGE | V | -| [47c99edf4878](https://github.com/aurora-silicon/linux/commit/47c99edf48782ec6078624f579108e243f8cbb4c) | Ryan | Merge pull request #342 from aurora-silicon/cleanup/rust-clippy-20261017 | Not applicable — MERGE | V | -| [3abf4a56b59e](https://github.com/aurora-silicon/linux/commit/3abf4a56b59e323026f9a6e2fe9a0d4307c251d5) | Ryan | Merge pull request #345 from aurora-silicon/fix/harden-all-20261017 | Not applicable — MERGE | V | -| [c20b9d96ba77](https://github.com/aurora-silicon/linux/commit/c20b9d96ba77da9a32c751ab0e63f283d10eea4a) | Ryan Murray | Merge branch 'integration/aurora' into aurora-wip | Not applicable — MERGE | V | -| [8080772b8377](https://github.com/aurora-silicon/linux/commit/8080772b83773a6ca224718de3fdb8bddc1b8511) | Ryan Murray | Merge branch 'integration/aurora' at a1b269f7 into aurora-wip | Not applicable — MERGE | V | -| [42c59170fe98](https://github.com/aurora-silicon/linux/commit/42c59170fe98eb0266c4ca5ea5e1abd0cbac97aa) | Ryan Murray | Merge integration/aurora at 3b77f0f9 into aurora-wip | Not applicable — MERGE | V | -| [1a3c5ca41f8f](https://github.com/aurora-silicon/linux/commit/1a3c5ca41f8f0215a355625ad7c4d456c78f2802) | Ryan Murray | Merge branch 'unified-7.3/bits/170-usb' into unified-7.3/canonical | Not applicable — MERGE | V | -| [2e1656f93c27](https://github.com/aurora-silicon/linux/commit/2e1656f93c27f76171fa265dadcb5ba019bce421) | Ryan Murray | Merge pull request #65 from joshuaswarren/ane-dt-polltx-aurora | Not applicable — MERGE | V | -| [9dbd46baf1b2](https://github.com/aurora-silicon/linux/commit/9dbd46baf1b289a30b5f9be6c4b5f6341135d7ce) | Ryan | Merge pull request #198 from aurora-silicon/fix/pr171-review [#171](https://github.com/aurora-silicon/linux/pull/171) | Not applicable — MERGE | V | -| [f1f334c2ec72](https://github.com/aurora-silicon/linux/commit/f1f334c2ec724b8c96f534a561df9480aa4310ee) | Ryan Murray | Merge branch 'backlog/kunit-parsers-fixes-20261017' into backlog/harden-all-20261017 [#345](https://github.com/aurora-silicon/linux/pull/345) | Not applicable — MERGE | V | - -### Public measured follow-ups outside the audited branch heads - -[#464](https://github.com/aurora-silicon/linux/pull/464), -[#468](https://github.com/aurora-silicon/linux/pull/468) and -[#494](https://github.com/aurora-silicon/linux/pull/494) were also read. Their -heads are not in either pinned branch snapshot; they are not silently counted -as inherited or qualified ports. They remain separate proposals for review: - -- #464 limits the T8140 GPU floor to streams and yields to PMP demand. Its - reported video power is 5.151 to 4.975 W, with light-submit gains retained. - Check the same video/browsing/heavy-load failure modes on g2, including actual - T6040 PMP voter behavior, before accepting its unconditional powered floor. -- #468 reports 7409 to 4625 doorbells in a traced hop, slow hops 19.6% to 13.9%, - and C-d64 13.89 to 13.11 us. Its shared compute-doorbell mechanism would need - no T6040 feature gate; it is an additional unmerged source dependency. -- #494 reports event passes 8.2 to 6.2 us and submit.empty d2 1.78 to 1.69 us. - Its shared event housekeeping change is another unmerged source dependency; - it is not evidence that the audited branches already provide those gains. - -No register, voltage, slot-key address, power curve, module parameter or new -platform option is invented to close an evidence gap. Applicability of dormant -25G83-specific feature/identity paths must come from validated facts; successful -compilation is not that qualification. From 754f5fccc070b0b6c43a7ceb6abe28ffcfa85eba Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 02:09:43 +1100 Subject: [PATCH 0128/1514] btrfs: don't split COW direct writes at old extent boundaries btrfs_dio_iomap_begin() trims every mapping to the extent map found at the start of the range. That is required for reads and for NOCOW writes, which use the existing extent, but a COW write allocates a new extent for its whole range and the extents it overwrites are dropped when the ordered extent completes. Trimming a COW write to the old extent only splits it. On a file fragmented by small random overwrites, a 1 MiB O_DIRECT write is therefore turned into one iomap iteration per old extent, each with its own extent reservation, ordered extent, bio and file extent item, and the new extents copy the old boundaries. A sequential rewrite never defragments such a file and runs at small-write speed. Extend the mapping of a COW write over the following extent maps that a direct write would COW as well. Stop at anything that is not a plain COW: NODATACOW inodes, preallocated extents, compressed and inline extents keep their current per-extent handling, so NOCOW writes and the buffered fallback are unchanged. The extent range is already locked for the whole write, and the allocator may still return a shorter extent, which the existing code handles. Signed-off-by: Ryan Murray --- fs/btrfs/direct-io.c | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index 3075d79927130d..561d4bc3b51b52 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -366,6 +366,58 @@ static int btrfs_get_blocks_direct_write(struct extent_map **map, return ret; } +/* + * Return true if a direct write to the range of @em allocates a new extent + * (COW): it is not a NOCOW write into an existing or preallocated extent and it + * does not fall back to buffered IO. + */ +static bool btrfs_dio_write_is_cow(const struct btrfs_inode *inode, + const struct extent_map *em) +{ + if (inode->flags & BTRFS_INODE_NODATACOW) + return false; + if (em->flags & EXTENT_FLAG_PREALLOC) + return false; + if (btrfs_extent_map_is_compressed(em) || + em->disk_bytenr == EXTENT_MAP_INLINE) + return false; + return true; +} + +/* + * A COW write replaces everything mapped in its range with one newly allocated + * extent, so the boundaries of the extents it overwrites do not matter. Extend + * the mapping [@start, @start + @len) over the following extent maps that a + * direct write would COW as well, up to @length. Without this, a sequential + * rewrite of a fragmented range allocates one new extent (and ordered extent, + * file extent item and bio) per old extent, so the file stays as fragmented as + * it was and the rewrite runs at small-write speed. + */ +static u64 btrfs_dio_cow_write_len(struct btrfs_inode *inode, u64 start, + u64 len, u64 length) +{ + const u64 limit = start + length; + u64 end = start + len; + + while (end < limit) { + struct extent_map *em; + u64 em_end; + bool cow; + + em = btrfs_get_extent(inode, NULL, end, limit - end); + if (IS_ERR(em)) + break; + cow = btrfs_dio_write_is_cow(inode, em); + em_end = btrfs_extent_map_end(em); + btrfs_free_extent_map(em); + if (!cow) + break; + end = min(em_end, limit); + } + + return end - start; +} + static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, loff_t length, unsigned int flags, struct iomap *iomap, struct iomap *srcmap) @@ -508,6 +560,8 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, } len = min(len, em->len - (start - em->start)); + if (write && btrfs_dio_write_is_cow(BTRFS_I(inode), em)) + len = btrfs_dio_cow_write_len(BTRFS_I(inode), start, len, length); /* * If we have a NOWAIT request and the range contains multiple extents From ef444990b5ea0a519985779dd0896299ac86cb18 Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:24:12 +1100 Subject: [PATCH 0129/1514] arm64: dts: apple: t6001: include the t6000 aux SPMI set instead of a copy t6001-aux-spmi.dtsi repeated all of t6000-aux-spmi.dtsi line for line and added two CLVR SPMI buses (clvr_spmi3, clvr_spmi4). Include the t6000 file and keep only the two additions. dtc merges them into /soc after the primary SPMI monitor, as before, so every Apple DTB is byte-identical. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi | 141 +----------------- 1 file changed, 6 insertions(+), 135 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi b/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi index 563c2abd706f88..92ddad6eed9c97 100644 --- a/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi +++ b/arch/arm64/boot/dts/apple/t6001-aux-spmi.dtsi @@ -1,20 +1,12 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* Disabled auxiliary SPMI resources; primary polled PMIC access is retained. */ +/* + * Disabled auxiliary SPMI resources; primary polled PMIC access is retained. + * T6001 has the T6000 set plus CLVR SPMI buses 3 and 4. + */ -&{/soc} { - primary_spmi_monitor: spmi-monitor@2920a0e00 { - compatible = "apple,t6000-spmi-monitor", "apple,spmi-monitor"; - reg = <0x2 0x920a0e00 0x0 0x100>, - <0x2 0x920a0400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - apple,controller = <&nub_spmi0>; - interrupt-controller; - #interrupt-cells = <2>; - #address-cells = <0>; - status = "okay"; - }; +#include "t6000-aux-spmi.dtsi" +&{/soc} { clvr_spmi3: spmi@28e519100 { compatible = "apple,t6000-spmi", "apple,spmi"; reg = <0x2 0x8e519100 0x0 0x100>, @@ -53,124 +45,3 @@ }; }; }; - -&pmic1 { - battery_monitor: battery-monitor { - compatible = "apple,t6000-battery-monitor", "apple,battery-monitor"; - interrupt-parent = <&primary_spmi_monitor>; - interrupts = <62 IRQ_TYPE_NONE>; - status = "disabled"; - }; -}; - -&nub_spmi1 { - reg = <0x2 0x920a9300 0x0 0x100>, - <0x2 0x920a8e00 0x0 0x100>, - <0x2 0x920a8400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@e { - compatible = "apple,maverick-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; - spmi-device@d { - compatible = "apple,t6000-viper-spmi", "apple,viper-spmi"; - reg = <0xd SPMI_USID>; - status = "disabled"; - }; -}; - -&clvr_spmi0 { - reg = <0x2 0x8e501100 0x0 0x100>, - <0x2 0x8e500e00 0x0 0x100>, - <0x2 0x8e500400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&clvr_spmi1 { - reg = <0x2 0x8e509100 0x0 0x100>, - <0x2 0x8e508e00 0x0 0x100>, - <0x2 0x8e508400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&clvr_spmi2 { - reg = <0x2 0x8e511100 0x0 0x100>, - <0x2 0x8e510e00 0x0 0x100>, - <0x2 0x8e510400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - pmic@f { - compatible = "apple,monaco-pmic", "apple,spmi-nvmem"; - reg = <0xf SPMI_USID>; - read-only; - status = "disabled"; - }; -}; - -&aop_spmi0 { - reg = <0x2 0x93829300 0x0 0x100>, - <0x2 0x93828e00 0x0 0x100>, - <0x2 0x93828400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - spmi-device@e { - compatible = "apple,t6000-wifibt-pmu", "apple,radio-pmu"; - reg = <0xe SPMI_USID>; - status = "disabled"; - }; - spmi-device@f { - compatible = "apple,t6000-uwb-pmu", "apple,radio-pmu"; - reg = <0xf SPMI_USID>; - status = "disabled"; - }; -}; - -&aop_spmi1 { - reg = <0x2 0x9382d300 0x0 0x100>, - <0x2 0x9382ce00 0x0 0x100>, - <0x2 0x9382c400 0x0 0x78>; - interrupt-parent = <&aic>; - interrupts = ; - interrupt-controller; - #interrupt-cells = <2>; - stockholm: nfc@c { - compatible = "apple,t6000-stockholm-spmi", "apple,stockholm-spmi"; - reg = <0xc SPMI_USID>; - interrupt-parent = <&aop_spmi1>; - interrupts = <160 IRQ_TYPE_NONE>, - <161 IRQ_TYPE_NONE>, - <162 IRQ_TYPE_NONE>, - <163 IRQ_TYPE_NONE>, - <164 IRQ_TYPE_NONE>, - <165 IRQ_TYPE_NONE>, - <166 IRQ_TYPE_NONE>; - status = "disabled"; - }; -}; From 0fce0023fc18e77d56cf3142d0e544e1473f78cc Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:37:01 +1100 Subject: [PATCH 0130/1514] thunderbolt: remove the dp_video_counter diagnostic dp_video_counter enabled path counter 0 on the DP IN hop and the far ingress hop of DP video tunnels on the right-hand USB-C route of the M2 Pro and M2 Max laptops, to show whether DP traffic crossed into a dock. It came in with 7db6aa0e0a40c ("thunderbolt: apple: protect diagnostics and apply host DP credits") as a load-time diagnostic, defaults to off, and nothing we ship sets it (kernel configs, distro packages, boot loader, lab kits). Remove the parameter, its check and its kernel-parameters.txt entry. The route helper stays; the DP credit policy uses it. Signed-off-by: Ryan Murray --- .../admin-guide/kernel-parameters.txt | 8 ----- drivers/thunderbolt/tunnel.c | 34 ------------------- 2 files changed, 42 deletions(-) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 2e6fa8b49752ec..c11741b7d063f7 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -7627,14 +7627,6 @@ Kernel parameters See Documentation/admin-guide/mm/transhuge.rst for more details. - thunderbolt.dp_video_counter= - [HW,ARM64] - Format: - Enable diagnostic counter 0 on the DP video path's - host and downstream ingress hops on the right-hand - USB-C route of the Apple M2 Pro and M2 Max laptops. Read counters through Thunderbolt - debugfs. This is a load-time setting. Default: false. - thunderbolt_apple.dp_display= [HW,ARM64] Format: diff --git a/drivers/thunderbolt/tunnel.c b/drivers/thunderbolt/tunnel.c index dac96ef66149ea..b6c9bd987566c2 100644 --- a/drivers/thunderbolt/tunnel.c +++ b/drivers/thunderbolt/tunnel.c @@ -107,11 +107,6 @@ module_param(bw_alloc_mode, bool, 0444); MODULE_PARM_DESC(bw_alloc_mode, "enable bandwidth allocation mode if supported (default: true)"); -static bool dp_video_counter; -module_param(dp_video_counter, bool, 0444); -MODULE_PARM_DESC(dp_video_counter, - "diagnostic: count packets on the DP video path's DP IN hop and its downstream (hub-side) hop (Apple M2 Pro/Max laptop right ACIO route only; read via debugfs port counters); default: false"); - static void tb_dp_dump_apple(struct tb_tunnel *tunnel); static int tb_apple_nhi_typec_index(struct tb_nhi *nhi); @@ -2029,14 +2024,6 @@ static int tb_dp_init_video_credits(struct tb_path_hop *hop) return 0; } -static bool tb_dp_video_counter_wanted(const struct tb_path *path) -{ - if (!dp_video_counter || !path->path_length) - return false; - - return tb_dp_is_apple_t602x_right_dpin(path->hops[0].in_port); -} - static int tb_dp_init_video_path(struct tb_path *path, bool pm_support) { struct tb_path_hop *hop; @@ -2048,27 +2035,6 @@ static int tb_dp_init_video_path(struct tb_path *path, bool pm_support) path->priority = TB_DP_VIDEO_PRIORITY; path->weight = TB_DP_VIDEO_WEIGHT; - if (tb_dp_video_counter_wanted(path)) { - struct tb_path_hop *last = &path->hops[path->path_length - 1]; - - path->hops[0].in_counter_index = 0; - tb_port_dbg(path->hops[0].in_port, - "dp_video_counter: enabling counter 0 on DP IN hop\n"); - - /* - * Second checkpoint: the downstream router's ingress side of - * the same path (e.g. the hub's upstream link), so comparing - * its counter against the first checkpoint can show whether - * DP-IN traffic actually crosses into the far end, not just - * leaves the host. - */ - if (last != &path->hops[0]) { - last->in_counter_index = 0; - tb_port_dbg(last->in_port, - "dp_video_counter: enabling counter 0 on downstream hop\n"); - } - } - tb_path_for_each_hop(path, hop) { int ret; From 6b67ea0f415e850fb3331f1d13910a3c243b3d6b Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:46:54 -0600 Subject: [PATCH 0131/1514] soc: apple: pmgr-misc: drop tautological debugfs init guard ret is always 0 after the DCS init succeeds. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/soc/apple/apple-pmgr-misc.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/soc/apple/apple-pmgr-misc.c b/drivers/soc/apple/apple-pmgr-misc.c index 41b6befe9432df..57cc95e355fdc2 100644 --- a/drivers/soc/apple/apple-pmgr-misc.c +++ b/drivers/soc/apple/apple-pmgr-misc.c @@ -761,8 +761,7 @@ static int apple_pmgr_misc_probe(struct platform_device *pdev) platform_set_drvdata(pdev, misc); - if (!ret) - apple_pmgr_misc_debugfs_init(misc); + apple_pmgr_misc_debugfs_init(misc); /* * With PMP enabled its firmware owns the fabric and DCS p-states. From f4db4c48daf11ba68bffabcae9271db0f266372b Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:00:08 +1100 Subject: [PATCH 0132/1514] drm/asahi: remove the items rustc reports as never used With every GPU backend enabled (G15, G16, G18, M5, M3_T8122), rustc reports 14 dead_code items in the driver. Eleven of them have no user in any build: CrashBuffers::Fixed (no table constructs it) and its match arm, Gpu::submit_m5_work, RenderIds::availability, ComputePool::completed_submissions, Lease::needs_release_observation, InitData::publish_work, InitData::m5_policy_telemetry_word, the render generation's retire, render_pool_owner, UatPageTable::visit_runs and m5_queue_configurations. Remove them. Three stay because a build outside the fleet config uses them: QueueSlot::cancel and Availability::notify_own (a KUnit test, built with CONFIG_KUNIT=y) and g16 board data::select (the asahi-m4 host selftest compiles that file). Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g17/freelist.rs | 11 ---------- drivers/gpu/drm/asahi/g17/initdata.rs | 12 ++-------- drivers/gpu/drm/asahi/g17/initdata/m5.rs | 11 ---------- drivers/gpu/drm/asahi/g17/mod.rs | 22 +++---------------- .../drm/asahi/g17/queue/render/generation.rs | 6 ----- drivers/gpu/drm/asahi/g17/runtime.rs | 2 +- drivers/gpu/drm/asahi/mmu/lifetime.rs | 18 --------------- drivers/gpu/drm/asahi/mmu/table.rs | 9 -------- drivers/gpu/drm/asahi/regs.rs | 17 -------------- 9 files changed, 6 insertions(+), 102 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index ff8592f2f9b18c..cf9e729dad36a9 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -78,10 +78,6 @@ impl RenderIds { }), GFP_KERNEL) } - pub(crate) fn availability(&self) -> &Arc { - &self.available - } - fn pin(self: &Arc, cell: &Arc, assigned: impl FnOnce()) -> Result { let mut state = self.state.lock(); let slot = cell.slot.load(Ordering::Acquire); @@ -1116,9 +1112,6 @@ impl ComputePool { pub(crate) fn descriptor(&self) -> Result { self.pages.as_ref().ok_or(EAGAIN)?.descriptor(self.id) } - pub(crate) fn completed_submissions(&self) -> Result { - Ok(u64::from_le_bytes(self.completed_bytes()?)) - } fn completed_bytes(&self) -> Result<[u8; 8]> { let offset = if self.m5 { super::fw::m5::pool::completed_offset() } else { FreeListControl::COMPLETED }; let pointer = self.control.pointer(offset, 8)?; @@ -1391,10 +1384,6 @@ impl Lease { self.phase = LeasePhase::ReleaseSent(cursor); Ok(()) } - /// Only sent releases and inherited release witnesses consume cursors. - pub(crate) fn needs_release_observation(&self) -> bool { - self.previous_release.is_some() || matches!(self.phase, LeasePhase::ReleaseSent(_)) - } /// Observes all older release records passed by one consumer snapshot. /// A sent release whose consumption [`Self::observe_releases`] has yet to witness. diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index c505bbd5b3b45a..69cb9399fb758a 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -844,16 +844,8 @@ impl InitData { Ok(values) } - /// Publishes an M5 compute record on the shared compute ring under the device mutex. - pub(super) fn publish_work( - &self, - priority: u8, - record: &super::fw::channels::WorkSlot, - ) -> Result { - self.publish_work_at(priority, record, None) - } - - /// [`Self::publish_work`] against the cursors of a room check made earlier under the same + /// Publishes an M5 compute record on the shared compute ring under the device mutex, + /// against the cursors of a room check made earlier under the same /// hold of the device mutex ([`Self::m5_compute_room`]), or a fresh read for None. pub(super) fn publish_work_at( &self, diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index 7b641965cdc701..2c0981746e0286 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -52,17 +52,6 @@ impl InitData { ring(0), ring(1), ring(2), ring(3), page(canonical.start)] } - /// Diagnostic-only read of an aligned word within the existing policy allocation. - /// Callers hold the device state mutex, retaining this mapping for the entire sample. - pub(crate) fn m5_policy_telemetry_word(&self, offset: usize) -> Result { - if !self.m5 || offset & 3 != 0 - || offset.checked_add(4).is_none_or(|end| end > self.graph.policy_size) { - return Err(EINVAL); - } - let at = self.graph.shared.policy.checked_add(offset).ok_or(EINVAL)?; - Ok(self.object(self.bundle)?.word(at)?.load(Ordering::Relaxed)) - } - /// Counts `submissions` in the firmware's submission history, in the slot of this moment. pub(crate) fn note_m5_submission_history(&self, submissions: u8) -> Result { if !self.m5 { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..7f090a5dd7ffbf 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -273,15 +273,12 @@ pub(crate) struct CoreLayout { /// Where a G17 target's crash log buffers live. pub(crate) enum CrashBuffers { - /// One buffer per [`Role`] that the firmware requests at a fixed address of the kernel - /// lower root, mapped by the driver before the coprocessors start. - Fixed([FixedBuffer; 2]), /// The firmware places its crash log in its own data segment, the `fw-data` reserved /// region, and asks for it there by physical address. FirmwareData, /// As [`CrashBuffers::FirmwareData`] when the boot loader describes the data segment as - /// the `fw-data` region. A boot loader that does not gets the driver's own buffers, as - /// [`CrashBuffers::Fixed`], at the low bits of the physical address the firmware asks for; + /// the `fw-data` region. A boot loader that does not gets the driver's own buffers, one per + /// [`Role`], at the low bits of the physical address the firmware asks for; /// the firmware does not write its crash log there. FirmwareDataOrFixed([FixedBuffer; 2]), } @@ -369,7 +366,7 @@ pub(crate) struct CrashLog { /// The CPU mapping of a crash log buffer. enum CrashLogMap { - /// The driver's buffer ([`CrashBuffers::Fixed`]). + /// The driver's buffer ([`CrashBuffers::FirmwareDataOrFixed`]). Object(shmem::VMapOwned), /// A buffer in the firmware's data segment ([`CrashBuffers::FirmwareData`]). FirmwareData(data_segment::DataSegmentLog), @@ -562,7 +559,6 @@ impl Coprocessor { ) -> Result { let index = role as usize; let fixed = match &cfg.crash_buffers { - CrashBuffers::Fixed(buffers) => Some(buffers), CrashBuffers::FirmwareData => None, CrashBuffers::FirmwareDataOrFixed(buffers) => { let described = data_segment::described(dev.as_ref().as_ref()); @@ -900,18 +896,6 @@ impl Firmware { power::release(self) } - /// Retry a temporarily unavailable transaction once under a registration - /// power hold. Other access errors propagate to the retained owner. - fn submit_m5_work(&mut self, submission: &fw::m5::queue::HardwareSubmission) -> Result { - match self.bridge.regs.submit_m5_work(submission) { - Err(error) if error == EAGAIN => { - self.acquire_registration_power()?; - self.bridge.regs.submit_m5_work(submission) - } - result => result, - } - } - /// Both outer slots and their capacity are checked before any host-port /// write. An EAGAIN retry drops the old views and revalidates them under a /// power hold. After a successful transaction, publication is infallible. diff --git a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index 4ebe4220921c0b..fb4be12b71f6a8 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -168,10 +168,4 @@ impl Generation { } } } - - pub(in crate::g17) fn retire(&mut self, ordinal: u64) -> Result { - if self.ordinal != Some(ordinal) { return Err(EIO); } - self.ordinal = None; - Ok(()) - } } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93b..cb8be443c64896 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1750,7 +1750,7 @@ impl super::Firmware { } // No descriptor, accounting or inner producer changes precede this // reservation; dropping it unused returns the work-ring slot. M5 compute takes its - // slot on the work ring M5 render shares, under this mutex (InitData::publish_work): + // slot on the work ring M5 render shares, under this mutex (InitData::publish_work_at): // a full ring is refused here, before a queue install or kick changes any state. let mut outer_cursors = None; let outer = if self.init.is_m5() { diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 9da7820dd92f65..54f639394b6413 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -201,24 +201,6 @@ impl Vm { Ok(()) } - /// The graph identity whose pool mappings occupy `slot` in this - /// VM (0 when free). A second graph cannot install there until it leaves. - pub(crate) fn render_pool_owner(&self, slot: u8) -> u64 { - self.lifetime - .as_ref() - .and_then(|lifetime| { - lifetime - .driver - .lock() - .as_ref()? - .render - .get(usize::from(slot))? - .as_ref() - .map(|pool| pool.id) - }) - .unwrap_or(0) - } - pub(crate) fn render_pool_tvb_blocks(&self, slot: u8, id: u64) -> Option { if id == 0 { return None; diff --git a/drivers/gpu/drm/asahi/mmu/table.rs b/drivers/gpu/drm/asahi/mmu/table.rs index 53d6c30273b5e4..3f8a476ecb1587 100644 --- a/drivers/gpu/drm/asahi/mmu/table.rs +++ b/drivers/gpu/drm/asahi/mmu/table.rs @@ -7,15 +7,6 @@ use core::ops::Range; use kernel::{addr::PhysicalAddr, prelude::*, sync::Arc}; impl UatPageTable { - pub(super) fn visit_runs( - &self, - range: Range, - visit: impl FnMut(u64, u64, u8) -> Result, - ) -> Result { - let _ = (range, visit); - Err(EOPNOTSUPP) - } - /// Fill `range` from a sparse tile: its first (zeroed) page repeats across /// the range, as a SINGLE_PAGE bind repeats its GEM's first page. pub(super) fn map_tiled(&mut self, range: Range, tile: &Arc, prot: Prot) -> Result { diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 1fde883e6c6df4..7c50ceb4f36c8b 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -718,23 +718,6 @@ impl G17Resources { ]) } - /// Sample only the two owned queue configuration words through the - /// host tag/data port. The caller holds the device mutex and power hold. - pub(crate) fn m5_queue_configurations(&self, qids: [u8; 2]) -> Result<[u64; 2]> { - let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - if sgx.relaxed().read32(G17_HOST_IRQ_SUMMARY) & G17_HOST_POWERED == 0 { - return Err(EAGAIN); - } - let mut values = [0; 2]; - for (value, qid) in values.iter_mut().zip(qids) { - let tag = crate::g17::fw::m5::queue::HardwareSubmission::configuration_tag(qid)?; - sgx.try_write64(tag, 0x4090)?; - *value = sgx.try_read64(0x4098)?; - } - Ok(values) - } - /// Registers a queue KSM slot through the firmware mailbox. pub(crate) fn register_ksm_queue(&self, qid: u8, descriptor: u64) -> Result { if qid > 127 { From 9b3ae0e0514c7109fdd06a883f3b2ff0dd0f313b Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:11:16 +1100 Subject: [PATCH 0133/1514] soc: apple: mailbox: remove the unused T6050 alias-window GPU profile mailbox.c has two T6050 ascwrap-v6 GPU profiles: the original one, which reaches the wrapper and VBAR through the T8140 addresses plus an alias delta, and the physical-address profile behind apple,t6050-j775d-ascwrap-v6. Every T6050 GPU node in the tree (J714s, J716c, K114c, K116s and the boards that include them) uses the physical-address profile. No device tree has ever used apple,t6050-ascwrap-v6 or apple,t6050-x1n1-ascwrap-v6. Remove those two match entries and their binding enum values, the alias profile's role table and hw struct, and APPLE_T6050_ASCWRAP_BASE_DELTA. Signed-off-by: Ryan Murray --- .../bindings/mailbox/apple,ascwrap-v6.yaml | 2 -- drivers/soc/apple/mailbox.c | 31 +------------------ 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml b/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml index 349d6930d07e02..0bf483a096e1ee 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,ascwrap-v6.yaml @@ -24,8 +24,6 @@ properties: - apple,t6040-ascwrap-v6 - apple,t8140-ascwrap-v6 - apple,t8142-ascwrap-v6 - - apple,t6050-ascwrap-v6 - - apple,t6050-x1n1-ascwrap-v6 - apple,t6050-j775d-ascwrap-v6 reg: diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 689d79858ab2b9..261a8b1b7d8de7 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -68,7 +68,6 @@ #define APPLE_T8140_GFX1_IOP_VBAR_BASE 0x482850000ULL #define APPLE_T6040_GFX_WRAPPER_BASE 0x28a600000ULL #define APPLE_T6040_GFX_IOP_VBAR_BASE 0x28a050000ULL -#define APPLE_T6050_ASCWRAP_BASE_DELTA 0x380000000ULL /* T8142 (M5) moves T8140's 0x4... GPU ASC bank to 0x5.... */ #define APPLE_T8142_ASCWRAP_BASE_DELTA 0x100000000ULL @@ -1881,19 +1880,9 @@ static const struct apple_mbox_hw apple_mbox_t8152_gfx_ascwrap_v8_hw = { static_assert(0x20 + sizeof(u32) <= APPLE_ASCWRAP_V8_MBOX_SIZE); -/* Retained T6050 wrapper/VBAR alias profile. */ -static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_ascwrap_v6_roles[] = { - { "GFX", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX, - APPLE_T8140_GFX_WRAPPER_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA, - APPLE_T8140_GFX_IOP_VBAR_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA }, - { "GFX1", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1, - APPLE_T8140_GFX1_WRAPPER_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA, - APPLE_T8140_GFX1_IOP_VBAR_BASE + APPLE_T6050_ASCWRAP_BASE_DELTA }, -}; - /* * T6050 at its physical addresses, with both roles in the GPU aperture at - * 0x2300000000 on die 0. The other T6050 profiles retain their alias windows. + * 0x2300000000 on die 0. */ static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_j775d_ascwrap_v6_roles[] = { { "GFX", APPLE_MBOX_ASCWRAP_V6_ROLE_GFX, @@ -1902,22 +1891,6 @@ static const struct apple_mbox_ascwrap_v6_role_desc apple_mbox_t6050_j775d_ascwr APPLE_J775D_GFX1_WRAPPER_BASE, APPLE_J775D_GFX1_IOP_VBAR_BASE }, }; -static const struct apple_mbox_hw apple_mbox_t6050_ascwrap_v6_hw = { - .reg_offset = APPLE_ASCWRAP_V6_MBOX_OFFSET, - .is_ascwrap_v6 = true, - .ascwrap_v6_roles = apple_mbox_t6050_ascwrap_v6_roles, - .num_ascwrap_v6_roles = ARRAY_SIZE(apple_mbox_t6050_ascwrap_v6_roles), - .control_full = APPLE_ASC_MBOX_CONTROL_FULL, - .control_empty = APPLE_ASC_MBOX_CONTROL_EMPTY, - .a2i_control = APPLE_ASC_MBOX_A2I_CONTROL, - .a2i_send0 = APPLE_ASC_MBOX_A2I_SEND0, - .a2i_send1 = APPLE_ASC_MBOX_A2I_SEND1, - .i2a_control = APPLE_ASC_MBOX_I2A_CONTROL, - .i2a_recv0 = APPLE_ASC_MBOX_I2A_RECV0, - .i2a_recv1 = APPLE_ASC_MBOX_I2A_RECV1, - .has_irq_controls = false, -}; - static const struct apple_mbox_hw apple_mbox_t6050_j775d_ascwrap_v6_hw = { .reg_offset = APPLE_ASCWRAP_V6_MBOX_OFFSET, .is_ascwrap_v6 = true, @@ -1959,8 +1932,6 @@ static const struct of_device_id apple_mbox_of_match[] = { { .compatible = "apple,t6040-ascwrap-v6", .data = &apple_mbox_t6040_ascwrap_v6_hw }, { .compatible = "apple,t8140-ascwrap-v6", .data = &apple_mbox_t8140_ascwrap_v6_hw }, { .compatible = "apple,t8142-ascwrap-v6", .data = &apple_mbox_t8142_ascwrap_v6_hw }, - { .compatible = "apple,t6050-ascwrap-v6", .data = &apple_mbox_t6050_ascwrap_v6_hw }, - { .compatible = "apple,t6050-x1n1-ascwrap-v6", .data = &apple_mbox_t6050_ascwrap_v6_hw }, { .compatible = "apple,t6050-j775d-ascwrap-v6", .data = &apple_mbox_t6050_j775d_ascwrap_v6_hw }, { .compatible = "apple,t8140-asc-mailbox", .data = &apple_mbox_t8140_asc_hw }, From c96f8d562763abe640920b2011cdfe1a97fd7679 Mon Sep 17 00:00:00 2001 From: LiamRay11 <228416644+LiamRay11@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:35:22 -0800 Subject: [PATCH 0134/1514] dt-bindings: mailbox: apple,mailbox: add the other T8152 post-office mailboxes On T8152 the NVMe (ANS), display (DCP), keyboard and trackpad (MTP) and SEP coprocessors talk through windows of the same post-office block as the SMC: counted FIFOs sharing one status register, with interrupt masking left to the interrupt controller. The register layout is the one apple,t8152-smc-mailbox already describes. Add a compatible per coprocessor, each with apple,t8152-smc-mailbox as its fallback, so the existing driver match serves them without a code change and a later difference can still be keyed on the specific compatible. All four carry traffic on a MacBook Pro (M6, J804), with the single-compatible form of these nodes: NVMe, the keyboard and trackpad, and Touch ID run through them, and the DCP driver exchanges its messages through the DCP window. Signed-off-by: LiamRay11 <228416644+LiamRay11@users.noreply.github.com> [Thomas: taken from aurora-silicon/linux#2105 for the J873g ANS node; placed before the T8152 ASCWrap v8 entry this branch adds] Signed-off-by: Thomas Glanzmann --- .../bindings/mailbox/apple,mailbox.yaml | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 9dc9c7d7f0b88b..a00459b368cfa9 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -27,6 +27,17 @@ properties: masking provided by the interrupt controller. const: apple,t8152-smc-mailbox + - description: + The other T8152 post-office mailboxes. Each coprocessor has its own + window of the same counted-FIFO block as the SMC's. + items: + - enum: + - apple,t8152-ans-mailbox + - apple,t8152-dcp-mailbox + - apple,t8152-mtp-mailbox + - apple,t8152-sep-mailbox + - const: apple,t8152-smc-mailbox + - description: T8152 ASC wrapper (v8) mailbox of the AOP, with the counted FIFOs of the SMC mailbox, described with its send-empty and @@ -270,6 +281,20 @@ required: additionalProperties: false examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + mailbox@316020300 { + compatible = "apple,t8152-ans-mailbox", "apple,t8152-smc-mailbox"; + reg = <0x3 0x16020300 0x0 0x80>; + interrupts = <1 302 4>, <1 262 4>; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + }; + - | mailbox@77408000 { compatible = "apple,t8103-asc-mailbox", "apple,asc-mailbox-v4"; From 04b191eacf20900ac0555af5cdc8f662888cbf3f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:21:18 +0100 Subject: [PATCH 0135/1514] arm64: dts: apple: j873: describe the ANS mailbox like the J804's Describe the J873g ANS post-office mailbox as the J804 does: with apple,t8152-smc-mailbox as the fallback compatible and the window's send-empty and recv-not-empty interrupts. The ADT's ans node lists interrupts 302, 262, 222 and 1349 (the last is NVMe's, nvme-interrupt-idx 3). Every post-office mailbox's list starts with 299 + its msgbox-mailbox-num and 259 + that number, and for the SMC (760, 759) and the DCP (304, 264) mailboxes, which run on their interrupts on the J873g, the first is send-empty and the second recv-not-empty. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi index c53059ab55d34c..741162fe483ff1 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-nvme.dtsi @@ -5,15 +5,21 @@ * the driver wakes it with a fresh RTKit handshake (as m1n1 does). NVMe * registers and NVMMU share the 0x325cc0000 window. The mailbox is the ANS * post-office window (msgbox-mailbox-num 3, no alias: 0x316000000 + - * 0x10300). No PMGR power or reset yet. + * 0x10300), the SMC mailbox's counted FIFO. Its interrupts are the first two + * of the ADT's ans list, in the order the SMC and DCP mailboxes' ADT lists + * give theirs: send-empty, recv-not-empty. No PMGR power or reset yet. * Resources are from the 26A434 ADT: ans, sart-ans. */ / { soc { ans_mbox: mailbox@316010300 { - compatible = "apple,t8152-ans-mailbox"; + compatible = "apple,t8152-ans-mailbox", + "apple,t8152-smc-mailbox"; reg = <0x3 0x16010300 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; #mbox-cells = <0>; }; From e6f059aab51f554c2850e33855b99a33d3ce4894 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:21:42 +0100 Subject: [PATCH 0136/1514] soc: apple: mailbox: drop the polled T8152 ANS profile The J873g ANS node now carries apple,t8152-smc-mailbox as its fallback and describes its interrupts, so the SMC mailbox's match data serves it on its interrupts, as it serves the J804's. Remove the profile that polled both directions without interrupts: its match entry, the rx_poll_required and j873_window fields, and the machine and fixed address check in probe. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/mailbox.c | 55 ++----------------------------------- 1 file changed, 2 insertions(+), 53 deletions(-) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index c0d245339de887..5b5b69500db348 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -227,10 +227,6 @@ struct apple_mbox_hw { unsigned int num_ascwrap_v6_roles; /* T8152 GPU ASCWrap v8: wrapper + iop-vbar + post-office window + PSD. */ bool is_ascwrap_v8; - /* No interrupts are described; receive and send are polled. */ - bool rx_poll_required; - /* J873 post-office window a polled provider must sit at. */ - u64 j873_window; /* Status word counts RX occupancy and free TX slots; paired transfers. */ bool counted_fifo; bool ap_initializes_mailboxes; @@ -264,7 +260,7 @@ struct apple_mbox_priv { struct apple_mbox mbox; /* ASCWrap v8 only: the provider's PMGR2 PSD service block (read-only). */ void __iomem *psd_regs; - /* ASCWrap v8 and polled providers: receive by polling; fixed at probe. */ + /* ASCWrap v8 only: receive by polling; fixed at probe. */ bool rx_poll_only; /* rx_lock: recv interrupt enabled and not yet disabled again. */ bool rx_irq_live; @@ -283,7 +279,7 @@ static struct apple_mbox_priv *apple_mbox_to_priv(struct apple_mbox *mbox) /* Only providers allocated by apple_mbox_probe() have a receive poller. */ static bool apple_mbox_has_rx_poller(const struct apple_mbox *mbox) { - return mbox->hw->is_ascwrap_v8 || mbox->hw->rx_poll_required; + return mbox->hw->is_ascwrap_v8; } /* Both ASCWrap generations share the consumer lifecycle API below. */ @@ -1592,16 +1588,6 @@ static int apple_mbox_probe(struct platform_device *pdev) return ret; } else { res = platform_get_resource(pdev, IORESOURCE_MEM, 0); - /* - * A polled provider must be exactly its own 0x80-byte window of - * the J873 post-office bank; the rest belongs to other roles. - */ - if (mbox->hw->rx_poll_required && - (!of_machine_is_compatible("apple,j873g") || !res || - res->start != mbox->hw->j873_window || - resource_size(res) != APPLE_ASCWRAP_V8_MBOX_SIZE)) - return dev_err_probe(dev, -EINVAL, - "post-office window does not match the J873 profile\n"); if (!res || resource_size(res) < mbox->hw->reg_offset + mbox->hw->i2a_recv1 + sizeof(u64)) return dev_err_probe(dev, -EINVAL, @@ -1613,21 +1599,6 @@ static int apple_mbox_probe(struct platform_device *pdev) mbox->regs = (u8 __iomem *)mbox->regs + mbox->hw->reg_offset; } - if (mbox->hw->rx_poll_required) { - mbox->rx_util_min = -1; - mbox->rx_util_min_applied = -1; - spin_lock_init(&mbox->rx_lock); - spin_lock_init(&mbox->tx_lock); - mutex_init(&mbox->lifecycle_lock); - init_completion(&mbox->tx_empty); - priv->rx_poll_only = true; - INIT_DELAYED_WORK(&priv->rx_poll_work, apple_mbox_v8_rx_poll_work); - mbox->irq_recv_not_empty = -ENXIO; - mbox->irq_send_empty = -ENXIO; - dev_info(dev, "J873 post-office: paired transfers, bounded polling, no IRQ claim\n"); - goto setup_pm; - } - if (mbox->hw->polled) { mbox->irq_recv_not_empty = -ENXIO; mbox->irq_send_empty = -ENXIO; @@ -1687,7 +1658,6 @@ static int apple_mbox_probe(struct platform_device *pdev) return ret; } -setup_pm: ret = devm_pm_runtime_enable(dev); if (ret) return ret; @@ -1981,31 +1951,10 @@ static const struct apple_mbox_hw apple_mbox_t8152_smc_hw = { .has_irq_controls = false, }; -/* - * T8152 ANS: msgbox-mailbox-num 3 in the non-alias post-office bank, the - * same counted FIFO as the SMC mailbox. Its interrupt ordering is not known, - * so no interrupt is described and both directions are polled. - */ -static const struct apple_mbox_hw apple_mbox_t8152_ans_hw = { - .rx_poll_required = true, - .j873_window = 0x316010300ULL, - .counted_fifo = true, - .control_full = GENMASK(11, 8), /* free TX slots */ - .control_empty = GENMASK(3, 0), /* RX occupancy */ - .a2i_control = 0x20, - .a2i_send0 = 0x10, - .a2i_send1 = 0x18, - .i2a_control = 0x20, - .i2a_recv0 = 0x00, - .i2a_recv1 = 0x08, - .has_irq_controls = false, -}; - static const struct of_device_id apple_mbox_of_match[] = { { .compatible = "apple,t8152-smc-mailbox", .data = &apple_mbox_t8152_smc_hw }, /* The AOP's ASC wrapper mailbox has the SMC mailbox's counted FIFOs. */ { .compatible = "apple,t8152-ascwrap-v8-mailbox", .data = &apple_mbox_t8152_smc_hw }, - { .compatible = "apple,t8152-ans-mailbox", .data = &apple_mbox_t8152_ans_hw }, { .compatible = "apple,t6031-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8122-agx-asc-mailbox", .data = &apple_mbox_asc_hw }, { .compatible = "apple,t8152-gfx-ascwrap-v8", .data = &apple_mbox_t8152_gfx_ascwrap_v8_hw }, From f01787dfe1a5fbf4e14d1329f86e89df93e34988 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:21:51 +0100 Subject: [PATCH 0137/1514] dt-bindings: mailbox: apple,mailbox: drop the standalone T8152 ANS mailbox The J873g ANS mailbox is now described with the apple,t8152-smc-mailbox fallback and its interrupts. Remove the standalone, interrupt-less apple,t8152-ans-mailbox entry and its conditions. Signed-off-by: Thomas Glanzmann --- .../bindings/mailbox/apple,mailbox.yaml | 20 +------------------ 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index a00459b368cfa9..7626c8afcedbd6 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -109,11 +109,6 @@ properties: - apple,t8142-aop-setup-mailbox - const: apple,t8140-aop-setup-mailbox - - description: - T8152 ANS post-office mailbox, a 0x80 window in the post-office - bank. No interrupts are described for it; the host polls it. - const: apple,t8152-ans-mailbox - - description: An older ASC mailbox interface found on T2 and A11 that is also used for the NVMe coprocessor and the system management @@ -177,9 +172,7 @@ allOf: properties: compatible: contains: - enum: - - apple,secure-rtbuddy-proxy - - apple,t8152-ans-mailbox + const: apple,secure-rtbuddy-proxy then: required: - interrupts @@ -201,16 +194,6 @@ allOf: - const: send-empty - const: recv-not-empty - - if: - properties: - compatible: - contains: - const: apple,t8152-ans-mailbox - then: - properties: - interrupts: false - interrupt-names: false - - if: properties: compatible: @@ -259,7 +242,6 @@ allOf: - apple,t6021-ane-mailbox - apple,t8112-ane-mailbox - apple,t8140-aop-setup-mailbox - - apple,t8152-ans-mailbox - apple,t8152-ascwrap-v8-mailbox - apple,t8152-smc-mailbox then: From 9271a5454a01a92c6d460eb310de8ce55730e080 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 05:51:00 +1100 Subject: [PATCH 0138/1514] media: apple: avd: Drop the unused queue pacing quirk, document the others AVD_QUIRK_V5_QUEUE_PACING was set on T8140 to keep the old firmware's segment FIFO pacing: the legacy transport slept between instruction segments (100-150 us with the quirk, 500-650 us without) so that it did not overrun the VP FIFO. Commit 9043840b67a0 ("media: apple: avd: harden decoder access against machine-wide hangs") replaced that sleep with a check of the FIFO level before every word, and removed the last reader of the flag. Since then the flag is set and never read; on a T8140 the open-queue transport is flow-controlled by the SRAM ring pointers, the inbox EMPTY bit and its in-flight limit, and a stress sweep of VP9, AV1 and H.264 decodes up to 16 frames deep reproduced no reset. Drop it. The remaining flags said little about what they switch. Describe them from the code that reads them: AVD_QUIRK_LSR is the shifted addressing of the T8103, T6000 and T8112 decoders (addresses as one word in 256- or 128-byte units, the FIFO base in one register, pitches in 16-byte units); AVD_QUIRK_NO_PIPE_STATE leaves the pipe state buffer out of the frame header on T8103 and T6000. AVD_QUIRK_NO_RECOVERY_RESET and the 38- and 42-bit DMA masks have no known cause or source yet; point their comments at the issues that track them. No functional change. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-drv.c | 8 +++++++- drivers/media/platform/apple/avd/avd-pm.c | 3 ++- drivers/media/platform/apple/avd/avd.h | 23 ++++++++++++++++++---- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index b0ad4b2e261b2c..8d444a66730573 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -468,7 +468,7 @@ static const struct avd_variant avd_t8140_variant = { .submit_offset = 0x40, .submit_queue_max_offset = 0x44, .submit_queue_status_offset = 0x7c, - .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_V5_QUEUE_PACING, + .quirks = AVD_QUIRK_HEVC_V5_HEADER, }; static const struct avd_variant avd_t8132_variant = { @@ -715,6 +715,12 @@ static int avd_probe(struct platform_device *pdev) if (ret) return ret; + /* + * Neither width has a named source: the LSR encodings would allow 39 + * bits (compressed-plane addresses, addr >> 7 in one word) and 42 is + * unexplained for the Apple backend. See + * https://github.com/aurora-silicon/linux/issues/2451. + */ ret = dma_set_mask_and_coherent(avd->dev, DMA_BIT_MASK(avd_backend_is_apple(avd) ? 42 : (avd->variant->quirks & AVD_QUIRK_LSR) ? 38 : 64)); diff --git a/drivers/media/platform/apple/avd/avd-pm.c b/drivers/media/platform/apple/avd/avd-pm.c index d6b45ba78e8443..4b60ce60ea4e87 100644 --- a/drivers/media/platform/apple/avd/avd-pm.c +++ b/drivers/media/platform/apple/avd/avd-pm.c @@ -339,7 +339,8 @@ int avd_pm_recover(struct avd_dev *avd) /* * On the J616C the machine hangs right after this reset, while the * decoder's DART domain is restored. The cause is not known yet, so - * stay parked: players fall back to software. + * stay parked: players fall back to software. Tracked in + * https://github.com/aurora-silicon/linux/issues/2450. */ if (avd->variant && avd->variant->quirks & AVD_QUIRK_NO_RECOVERY_RESET) { dev_err(avd->dev, "recover: staying parked, no reset on this SoC\n"); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 568cbfc6d06f8d..022022016794cf 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -34,16 +34,31 @@ #define AVD_CAPABILITY_VP9 BIT(2) #define AVD_CAPABILITY_AV1 BIT(3) -/* Shifts addreses right and bytesperline?? */ +/* + * Shifted addressing of the first decoders (T8103, T6000, T8112): every + * address in the instruction stream is one word in 256-byte units (addr >> 8), + * a compressed-plane address one word in 128-byte units (addr >> 7), the + * instruction FIFO base one register (addr >> 8, no IOVA_HI), and + * a plane pitch is in 16-byte units (bytesperline >> 4). Later decoders take + * byte addresses as two words and byte pitches. + */ #define AVD_QUIRK_LSR BIT(0) +/* + * The decoder takes no pipe state buffer (T8103, T6000): the frame header + * carries no pipe_state address, its PIPE_STATE op flag and H.264/HEVC + * PIPE_STATE_EN feature field stay clear, and H.264 and VP9 allocate no + * pipe_state buffer. + */ #define AVD_QUIRK_NO_PIPE_STATE BIT(1) /* HEVC DMA configuration and extended scratch-address table. */ #define AVD_QUIRK_HEVC_V5_HEADER BIT(2) -/* T8140: pace only HEVC submissions, with a shorter back-off. */ -#define AVD_QUIRK_V5_QUEUE_PACING BIT(3) /* H.264 co-located motion vectors take 128 bytes per macroblock, not 64. */ #define AVD_QUIRK_H264_MV_128 BIT(4) -/* A reset after a timeout hangs the machine: stay parked and retire the decoder */ +/* + * A reset after a timeout hangs the machine: stay parked and retire the + * decoder. Cause unknown, see avd_pm_recover() and + * https://github.com/aurora-silicon/linux/issues/2450. + */ #define AVD_QUIRK_NO_RECOVERY_RESET BIT(5) #define VP_SLOT_NONE 255 From bdf631d7bcfc1b83bc679510ea0c9c813be40c40 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 05:51:49 +1100 Subject: [PATCH 0139/1514] usb: pci-quirks: Name the shortest valid xHCI capability length The xHCI early handoff refuses a capability length below 0x10 or not dword-aligned, so that an all-ones BAR (length 0xff) does not make the operational-register read fault. The 0x10 had no source and is shorter than the capability registers themselves: HCCPARAMS sits at 0x10 and DBOFF and RTSOFF follow, which every xHCI revision defines (xHCI 1.2, section 5.3). The operational registers can start no earlier than 0x1c, on a dword boundary (section 5.4). Name that minimum XHCI_MIN_CAP_LENGTH and check against it. A length of 0x10 to 0x1b, which no conforming controller reports, is now refused like the all-ones case; every length the old check refused is still refused, and every real controller keeps its handoff. Fixes: 57b3f3af33bc ("PCI: apple: enumerate Thunderbolt PCIe on t8103") Cc: Chris Kearney <303316+iconidentify@users.noreply.github.com> Signed-off-by: Ryan Murray --- drivers/usb/host/pci-quirks.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index 26bba2d42b1bbd..29f1e4ac0d09d7 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1147,6 +1147,14 @@ void usb_disable_xhci_ports(struct pci_dev *xhci_pdev) } EXPORT_SYMBOL_GPL(usb_disable_xhci_ports); +/* + * The capability registers that every xHCI revision defines end with RTSOFF + * at offset 0x18 (xHCI 1.2, section 5.3), so the operational registers that + * CAPLENGTH points to start at 0x1c or later, on a dword boundary (section + * 5.4). + */ +#define XHCI_MIN_CAP_LENGTH 0x1c + /* * PCI Quirks for xHCI. * @@ -1227,11 +1235,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) /* * A dead or unprogrammed BAR reads as all-ones. The capability * length is then 0xff, and the operational-register read below is - * not 4-byte aligned and faults. A real xHCI length is at least - * 0x10 and dword-aligned. + * not 4-byte aligned and faults. A real xHCI length covers the + * capability registers and is dword-aligned, see XHCI_MIN_CAP_LENGTH. */ val = readl(base); - if (XHCI_HC_LENGTH(val) < 0x10 || (XHCI_HC_LENGTH(val) & 3)) { + if (XHCI_HC_LENGTH(val) < XHCI_MIN_CAP_LENGTH || (XHCI_HC_LENGTH(val) & 3)) { dev_warn(&pdev->dev, "xHCI capability length %#x unusable, skipping handoff\n", XHCI_HC_LENGTH(val)); From ab4cea3795f35e3676a8b783c5f1b98196de0b04 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 14:11:27 -0500 Subject: [PATCH 0140/1514] thermal: apple-pmp: stop the power reader at shutdown A reboot or power-off tells the SMC the system is going down and then puts it in atomic mode, which fails every ordinary SMC read with -EIO. The power telemetry reader has no shutdown hook and keeps reading the SMC rails every 500 ms, so a shutdown that stalls fills the console with "power telemetry error -5" until the machine resets, burying whatever stalled it. Stop the reader from a shutdown callback, after any pending setup. Its budgets then go stale exactly as they do after failed reads, so the CPU and GPU fall back to their minimum ceilings, and the die sampler keeps running while devices shut down. Signed-off-by: Erik Bourget --- drivers/thermal/apple-pmp-thermal.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index ceac085e3004d5..7558293d826439 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -843,9 +843,24 @@ static void apple_pmp_thermal_remove(struct platform_device *pdev) apple_pmp_thermal_cleanup(); } +/* + * A reboot or power-off tells the SMC the system is going down and then puts it + * in atomic mode, which fails every ordinary read with -EIO. Left running, the + * power reader logs an error every 500 ms until the machine resets, burying + * whatever a stalled shutdown printed. Stop the reader. Its budgets go stale as + * they would after failed reads, so the CPU/GPU fall back to their minimum + * ceilings; the die sampler keeps running. + */ +static void apple_pmp_thermal_shutdown(struct platform_device *pdev) +{ + cancel_delayed_work_sync(&pmp_thermal.setup_work); + cancel_delayed_work_sync(&pmp_thermal.power_work); +} + static struct platform_driver apple_pmp_thermal_driver = { .probe = apple_pmp_thermal_probe, .remove = apple_pmp_thermal_remove, + .shutdown = apple_pmp_thermal_shutdown, .driver = { .name = "apple-pmp-thermal", .pm = pm_sleep_ptr(&apple_pmp_thermal_pm_ops), From a2f28690466e216a0ed5805b1ce9f502d21ff18b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 20:56:43 +0100 Subject: [PATCH 0141/1514] arm64: dts: apple: j873: note the USB DARTs' power domains The J873g USB controllers and their DARTs are powered by PMGR2 PSD services 175 (usb-drd1) and 176 (usb-drd2). Say so on the DART nodes, and that the domain waits on the T8152 PSD provider and has to stay on until Linux can restore the USB2 PHY setup the loader leaves. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 6f1a956bd68e3e..dc4b2fb720f894 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -18,6 +18,11 @@ * own window only, and describe instance 1 as a node of its own. */ +/* + * The USB DARTs' power domain is PSD service 175 (usb-drd1) and 176 (usb-drd2). + * It waits on the T8152 PSD provider (aurora-silicon/linux#2459), and must stay + * on until Linux can restore the USB2 PHY setup the loader leaves behind. + */ &dwc3_1_dart { reg = <0x4 0x0b020000 0x0 0xc000>; status = "okay"; @@ -30,6 +35,7 @@ / { soc { + /* Power domain: PSD service 175, see dwc3_1_dart above. */ dwc3_1_dart_1: iommu@40b040000 { compatible = "apple,t8152-dart", "apple,t8110-dart"; reg = <0x4 0x0b040000 0x0 0xc000>; @@ -48,6 +54,7 @@ snps,dis_u3_susphy_quirk; }; + /* Power domain: PSD service 176, see dwc3_1_dart above. */ dwc3_2_dart_1: iommu@383040000 { compatible = "apple,t8152-dart", "apple,t8110-dart"; reg = <0x3 0x83040000 0x0 0xc000>; From 16903ef04779a1ba18767e5759a2f149dc860016 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 07:17:49 +1100 Subject: [PATCH 0142/1514] btrfs: always propagate the saved status of split bios btrfs_bio_end_io() saves the first error of all parts of a split btrfs_bio in orig_bbio->status, but loads it into the bi_status of the original bio only if the part that completes last succeeded: if (atomic_dec_and_test(&bbio->pending_ios)) { /* Load split bio's error which might be set above. */ if (status == BLK_STS_OK) bbio->bio.bi_status = READ_ONCE(bbio->status); That is only correct when the last completion is the original bbio itself, because then "bbio->bio.bi_status = status" at the top of the function has already stored the error in the original bio. When the last completion is a split (cloned) bbio, that assignment went to the clone, which is freed, while the original bio's bi_status still holds the status of its own earlier completion. For reads that is BLK_STS_OK, as btrfs_check_read_bio() clears bi_status before the checksum verification. So if a failed split part is the last part to complete, the error is lost and the read succeeds. This happens for every read that is split across stripes, e.g. data RAID0 with 64K stripes, where a 1MiB read is split into 16 parts that complete in any order. If one part fails the checksum and there is no other copy, repair_one_sector() sets BLK_STS_IOERR on that part, and the csum failure is logged and counted in the device stats, but end_bbio_data_read() marks all folios uptodate, including the one with the corrupted block, and btrfs_dio_end_io() completes a direct read successfully. The application gets the corrupted data without an error, and for buffered reads the corrupted data also stays in the page cache. Always load the saved status when the last part completes. It is BLK_STS_OK only if no part failed, and the first error otherwise. Reproducer: data raid0 / metadata raid1 on two devices, 64MiB file, one 4K block corrupted in each even MiB, every MiB read 3 times with 1MiB reads (O_DIRECT with a prefaulted buffer, O_DIRECT with an untouched buffer, buffered). Out of 96 reads of corrupted MiBs per mode, 3 runs each: O_DIRECT O_DIRECT (fresh buf) buffered before (WRONG DATA) 11, 10, 8 1, 4, 0 0, 5, 0 after (EIO) 96, 96, 96 96, 96, 96 96, 96, 96 The 96 reads of clean MiBs returned correct data on both kernels, and data raid1 still repairs all corrupted blocks. Fixes: d48e1dea3931 ("btrfs: fix error propagation of split bios") Signed-off-by: Ryan Murray --- fs/btrfs/bio.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c index cc0bd03048bae6..0ce6c8bb5d0441 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -137,9 +137,14 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status) cmpxchg(&bbio->status, BLK_STS_OK, status); if (atomic_dec_and_test(&bbio->pending_ios)) { - /* Load split bio's error which might be set above. */ - if (status == BLK_STS_OK) - bbio->bio.bi_status = READ_ONCE(bbio->status); + /* + * Load the first error of all split bios. This must be done + * unconditionally: if the last completion is a split bio, the + * error passed in was only stored in the split bio, while the + * original bio's bi_status still holds the status of its own + * earlier (possibly successful) completion. + */ + bbio->bio.bi_status = READ_ONCE(bbio->status); if (bbio_has_ordered_extent(bbio)) { struct btrfs_ordered_extent *ordered = bbio->ordered; From a921ce196095632a64584202071caa4d6af5d948 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 10:04:58 +1100 Subject: [PATCH 0143/1514] wifi: brcmfmac: pcie: restore the function's config after the watchdog reset On chipcommon rev >= 65 brcmf_pcie_reset_device() resets the chip with CC_WD_SSRESET_PCIE_F0_EN set, so PCIe function 0 is reset too and its config space returns to the chip defaults. The driver only puts config registers back for PCIe core rev <= 13, so on newer chips the function keeps the defaults while the PCI core still holds the values it assigned. On BCM4387 and BCM4388 this is visible in the resizable BAR: the PCI core sizes BAR 2 at 16 MiB during enumeration, and after every probe or remove reset the function decodes only 8 MiB. The next pci_restore_state() then writes the assigned size back. On system resume that happens with the function in D0, firmware running and bus mastering on (WoWLAN and the s2idle path keep it there), so BAR 2 changes size under live firmware. Save the config space before the reset, before the driver turns ASPM off for it, and restore it once the chip is out of reset whenever the function was part of the reset. Measured with lspci and iperf3 on production kernels: - Stock: BAR 2 decodes 8MB after probe on the MacBook Pro M4 Pro (J616s, BCM4388), MacBook Pro M1 Pro (J316s, BCM4387) and MacBook Air M2 (J413, BCM4387), against a 16M PCI core resource. On the J616s, two s2idle cycles change exactly one config byte, the ReBAR size (03 -> 04). - With this change on the J413 (runtime module swap): 16MB after probe; all other config registers, including ASPM, match stock; the function's and the Bluetooth function's config are identical before and after two s2idle cycles; iperf3 RX is unchanged. Fixes: 9284bb69ed79 ("wifi: brcmfmac: Handle watchdog properly in newer cores") Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/pcie.c | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 2bfee245f43312..f97aaf324db14e 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -779,6 +779,7 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) BRCMF_PCIE_CFGREG_REG_BAR2_CONFIG, BRCMF_PCIE_CFGREG_REG_BAR3_CONFIG }; + bool fn_reset = false; u32 i; u32 val; u32 lsc; @@ -786,6 +787,15 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) if (!devinfo->ci) return; + /* + * On chipcommon rev >= 65 the watchdog below also resets PCIe function + * 0 (CC_WD_SSRESET_PCIE_F0_EN), which puts its config space back to the + * chip defaults: e.g. the resizable BAR 2 drops from the size the PCI + * core assigned to 8 MiB. Save what the PCI core programmed, before + * ASPM is turned off for the reset, so it can be put back afterwards. + */ + pci_save_state(devinfo->pdev); + /* Disable ASPM */ brcmf_pcie_select_core(devinfo, BCMA_CORE_PCIE2); pci_read_config_dword(devinfo->pdev, BRCMF_PCIE_REG_LINK_STATUS_CTRL, @@ -801,6 +811,8 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) if (core->rev >= 65) { u32 mask = CC_WD_SSRESET_PCIE_F0_EN; + fn_reset = true; + core = brcmf_chip_get_core(devinfo->ci, BCMA_CORE_PCIE2); if (core->rev < 66) mask |= CC_WD_SSRESET_PCIE_ALL_FN_EN; @@ -826,6 +838,16 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) pci_write_config_dword(devinfo->pdev, BRCMF_PCIE_REG_LINK_STATUS_CTRL, lsc); + /* + * Put the PCI core's configuration back. Otherwise the function runs + * with the reset defaults while the core still holds the assigned + * values, and the next pci_restore_state() (system resume) rewrites + * them on a live, bus-mastering function: BAR 2 changes size under + * running firmware. + */ + if (fn_reset) + pci_restore_state(devinfo->pdev); + core = brcmf_chip_get_core(devinfo->ci, BCMA_CORE_PCIE2); if (core->rev <= 13) { for (i = 0; i < ARRAY_SIZE(cfg_offset); i++) { From 0c4f184c1c54155c02e8cdede82a55463d2cc3b5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 00:57:54 +1100 Subject: [PATCH 0144/1514] arm64/fpsimd: Skip SMSTOP when streaming mode and ZA are already off fpsimd_flush_cpu_state() issues SMSTOP unconditionally on SME capable CPUs. It runs on every kernel_neon_begin(), so every short kernel-mode NEON section (a 4 KiB CRC32C, a single AES block chain) pays for it, even though in kernel context PSTATE.SM and PSTATE.ZA are almost always already clear. Read SVCR first and only stop streaming mode / ZA when one of them is actually enabled. Reading SVCR is cheap; writing SVCR via SMSTOP is a context synchronising mode change. On an SME capable M4 Pro (T6040), verifying the checksums of 1 MiB of btrfs data on a P core, 256 kernel-mode NEON sections, takes 216 us instead of 255 us, and queue-depth-1 reads through the file system are 3-5 % faster. CPUs without SME are unaffected. Signed-off-by: Ryan Murray --- arch/arm64/kernel/fpsimd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/kernel/fpsimd.c b/arch/arm64/kernel/fpsimd.c index e7f1682a3059b5..aad17c3b44430a 100644 --- a/arch/arm64/kernel/fpsimd.c +++ b/arch/arm64/kernel/fpsimd.c @@ -1571,7 +1571,7 @@ static void fpsimd_flush_cpu_state(void) * NEON and leaving streaming mode or ZA enabled may increase power * consumption. */ - if (system_supports_sme()) + if (system_supports_sme() && read_sysreg_s(SYS_SVCR)) sme_smstop(); set_thread_flag(TIF_FOREIGN_FPSTATE); From f8c5e2794d0da7a3cb5389c1106d377f8a3cb27b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 14:38:04 +1100 Subject: [PATCH 0145/1514] arm64: dts: apple: t8132, t8142: describe the USB-C ports as dual-role The USB-C ports of the T8132 and T8142 Macs are dual-role: each port's controller is the dwc3 behind an ATC PHY, with a role switch driven by the port controller, and the T8132 SoC .dtsi already describes these controllers as dr_mode = "otg" with usb-role-switch. Several board files override that with dr_mode = "host" (T8132: t8132-jxxx.dtsi ports 0 and 1, J604 port 3, J624 ports 2 and 3, J773g port 3), and the T8142 J704 and J813 USB files describe every USB-C controller as host-only and every connector with data-role = "host". Nothing depends on the host-only values: dwc3-apple sets the controller's mode itself on every role change, and the port controller drivers do not read the connector's data-role. They only misdescribe the hardware. Drop the T8132 overrides, so the SoC's "otg" applies, and describe the T8142 controllers as "otg" and their connectors as "dual", as on the T8132 boards. The J773g's port 2, which feeds a fixed USB hub, stays host-only. Every T8132 and T8142 DTB changes only in these properties. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j604.dts | 1 - arch/arm64/boot/dts/apple/t8132-j624.dts | 2 -- arch/arm64/boot/dts/apple/t8132-j773g.dts | 1 - arch/arm64/boot/dts/apple/t8132-jxxx.dtsi | 2 -- arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi | 12 ++++++------ arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi | 8 ++++---- 6 files changed, 10 insertions(+), 16 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j604.dts b/arch/arm64/boot/dts/apple/t8132-j604.dts index 0bbf299e6afca6..03d9457bf80d89 100644 --- a/arch/arm64/boot/dts/apple/t8132-j604.dts +++ b/arch/arm64/boot/dts/apple/t8132-j604.dts @@ -266,7 +266,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; diff --git a/arch/arm64/boot/dts/apple/t8132-j624.dts b/arch/arm64/boot/dts/apple/t8132-j624.dts index 042e9a66cbf4e5..69e0ae99ce818d 100644 --- a/arch/arm64/boot/dts/apple/t8132-j624.dts +++ b/arch/arm64/boot/dts/apple/t8132-j624.dts @@ -135,7 +135,6 @@ }; &dwc3_2 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy2 PHY_TYPE_USB2>, <&atcphy2 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -179,7 +178,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; diff --git a/arch/arm64/boot/dts/apple/t8132-j773g.dts b/arch/arm64/boot/dts/apple/t8132-j773g.dts index baf3e3ffcfecb9..2a8ca64d3a6385 100644 --- a/arch/arm64/boot/dts/apple/t8132-j773g.dts +++ b/arch/arm64/boot/dts/apple/t8132-j773g.dts @@ -155,7 +155,6 @@ }; &dwc3_3 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy3 PHY_TYPE_USB2>, <&atcphy3 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index 03a129758b10b9..eac1ad36714c16 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -362,7 +362,6 @@ }; &dwc3_0 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy0 PHY_TYPE_USB2>, <&atcphy0 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; @@ -416,7 +415,6 @@ }; &dwc3_1 { - dr_mode = "host"; maximum-speed = "super-speed"; phys = <&atcphy1 PHY_TYPE_USB2>, <&atcphy1 PHY_TYPE_USB3>; phy-names = "usb2-phy", "usb3-phy"; diff --git a/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi index 09c51e0888aa2f..fac15e4d4099f2 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j704-usb.dtsi @@ -77,7 +77,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-front"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -106,7 +106,7 @@ reg = <4 0x02280000 0 0xcd00>, <4 0x0228cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_0_dart 0>, <&dwc3_0_dart_1 1>; @@ -213,7 +213,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-rear"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -243,7 +243,7 @@ reg = <4 0x0a280000 0 0xcd00>, <4 0x0a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; @@ -365,7 +365,7 @@ compatible = "usb-c-connector"; label = "USB-C Right"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -394,7 +394,7 @@ reg = <4 0x1a280000 0 0xcd00>, <4 0x1a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_3_dart 0>, <&dwc3_3_dart_1 1>; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi index 2eb0b1f16af473..bf81e9b35ce21a 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-usb.dtsi @@ -69,7 +69,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-front"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -98,7 +98,7 @@ reg = <4 0x02280000 0 0xcd00>, <4 0x0228cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_0_dart_0 0>, <&dwc3_0_dart_1 1>; @@ -215,7 +215,7 @@ compatible = "usb-c-connector"; label = "USB-C Left-rear"; power-role = "dual"; - data-role = "host"; + data-role = "dual"; ports { #address-cells = <1>; @@ -245,7 +245,7 @@ reg = <4 0x0a280000 0 0xcd00>, <4 0x0a28cd00 0 0x4b00>; reg-names = "dwc3-core", "dwc3-apple"; interrupts = ; - dr_mode = "host"; + dr_mode = "otg"; usb-role-switch; role-switch-default-mode = "host"; iommus = <&dwc3_1_dart_0 0>, <&dwc3_1_dart_1 1>; From ebc0f1bd6a73da510d10d95e72229bc4454c8a9f Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 01:22:15 -0500 Subject: [PATCH 0146/1514] iio: aop_als: arm the CT817 again after system sleep On the J700 (T8140) the light sensor stops reporting at the first system sleep of a boot and never starts again. Every read of in_illuminance_input after that wake returns the last sample from before the sleep, usually taken as the panel went dark, for the rest of the boot. Measured 2026-11-19 on integration/aurora 1473d156 and on the 7.3.0-41 RPM alike: 26 boots, 72 deep sleeps, on both the DRAM-kept and the deep path. Before the first sleep, five reads over 5 s gave 20.55 20.55 20.55 19.36 20.55 lx. After the first and second wakes the same boot read 1.453372 five times each, with the room and the backlight unchanged. Each boot froze on its own value, between 0.000000 and 6.628011 lx. The firmware stops the sensor's reports for system sleep; the lid angle driver's comment notes the same. The CT817 starts reporting only on a zero to non-zero transition of its report interval, which enable_als() writes once, at probe. Register a PM notifier, as aop_las does. At PM_POST_SUSPEND it writes the interval to zero and then repeats the probe's CT817 arming: verbosity, batch and raw interval, then the interval. Only the CT817 gets the hook; the other parts are unchanged. Tested on the J700 with 1473d156 plus this patch, built as a test kit: 2 boots, 6 DRAM-kept deep sleeps. After every wake the sensor reported again and followed the light. It read 18.23-18.61 lx with the panel on, and fell to 5.17-6.37 lx, still varying from read to read, when the lock screen dimmed the backlight to 121. The sleeps, GPU, Wi-Fi, BT and the AOP mics behaved as on the tip, and the patch logged no warning. Signed-off-by: Diljit Singh --- drivers/iio/common/aop_sensors/aop_als.rs | 173 ++++++++++++++++++++-- 1 file changed, 161 insertions(+), 12 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index e64f7ff26a6e05..cefd01640bc963 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -4,15 +4,25 @@ //! //! Copyright (C) The Asahi Linux Contributors +use core::{ + ffi::{c_int, c_void}, + ptr, +}; + use kernel::{ bindings, c_str, - device::Core, + device::{self, Core}, firmware::Firmware, iio::common::aop_sensors::{AopSensorData, IIORegistration, MessageProcessor, MICRO}, module_platform_driver, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidRegistration, AOP}, - sync::Arc, + sync::{ + aref::ARef, + atomic::{Atomic, Relaxed}, + Arc, + }, + types::Opaque, }; const EPIC_SUBTYPE_GET_AOP_PROPERTY: u16 = 0xa; @@ -97,6 +107,11 @@ fn enable_als( return Ok(()); } + arm_ct817(aop, dev.as_ref(), svc) +} + +/// Arms the CT817: its configuration, then the interval that starts the reports. +fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<()> { // The CT817 gets its calibration from the AOP driver over the setup port, // not as an ALS property. Only the transport can fail here; the sensor's // status words are logged, see the property comments above. Do not fetch @@ -105,13 +120,7 @@ fn enable_als( // wedges the AOP for the rest of the boot. let set = |tag: u32, val: u32, what: &str| -> Result<()> { let status = set_als_property(aop, svc, tag, &val.to_le_bytes())?; - dev_dbg!( - dev.as_ref(), - "{} = {:#x}: status {:#x}\n", - what, - val, - status - ); + dev_dbg!(dev, "{} = {:#x}: status {:#x}\n", what, val, status); Ok(()) }; set(ALS_PROP_VERBOSITY, ALS_VERBOSITY, "verbosity")?; @@ -121,11 +130,140 @@ fn enable_als( "batch interval", )?; set(ALS_PROP_RAW_INTERVAL, ALS_RAW_INTERVAL, "raw interval")?; - // The interval is zero at probe, so this is the transition that arms the - // sensor. + // The interval is zero at probe, and the wake writes it to zero first, so + // this is the transition that arms the sensor. set(ALS_PROP_INTERVAL, ALS_INTERVAL_US, "interval") } +/// Arms the CT817 again after system sleep. +/// +/// The firmware stops the light sensor's reports for system sleep and does not +/// start them again: on the J700 every read after the first wake of a boot +/// returned the last sample from before that sleep, while the room's light +/// changed. The sensor starts reporting only on a zero to non-zero transition +/// of its interval, so the wake writes the interval to zero and then repeats +/// the arming of the probe. +#[repr(C)] +struct PmHook { + /// First, so that the callback finds the hook from it. + nb: Opaque, + dev: ARef, + aop: Arc, + service: EPICService, + registered: Atomic, +} + +/// The PM notifier callback. +/// +/// # Safety +/// +/// `nb` is the notifier block of a registered [`PmHook`]. +unsafe extern "C" fn pm_event( + nb: *mut bindings::notifier_block, + action: usize, + _data: *mut c_void, +) -> c_int { + if action as u32 != bindings::PM_POST_SUSPEND { + return bindings::NOTIFY_DONE as c_int; + } + // SAFETY: `nb` is the first field of a registered `PmHook`. + let hook = unsafe { &*nb.cast::() }; + let aop = hook.aop.as_ref(); + let rearm = set_als_property(aop, &hook.service, ALS_PROP_INTERVAL, &0u32.to_le_bytes()) + .and_then(|_| arm_ct817(aop, &hook.dev, &hook.service)); + match rearm { + Ok(()) => dev_dbg!(hook.dev, "reports armed again after sleep\n"), + Err(e) => dev_warn!(hook.dev, "reports not armed again after sleep: {:?}\n", e), + } + bindings::NOTIFY_OK as c_int +} + +/// # Safety +/// +/// `nb` stays valid and pinned until [`pm_unregister`] is called on it. +#[cfg(CONFIG_PM_SLEEP)] +unsafe fn pm_register(nb: *mut bindings::notifier_block) -> c_int { + // SAFETY: By the caller's contract. + unsafe { bindings::register_pm_notifier(nb) } +} + +/// # Safety +/// +/// `nb` was registered by [`pm_register`]. +#[cfg(CONFIG_PM_SLEEP)] +unsafe fn pm_unregister(nb: *mut bindings::notifier_block) { + // SAFETY: By the caller's contract. + unsafe { bindings::unregister_pm_notifier(nb) }; +} + +/// Without system sleep there is nothing to arm again. +/// +/// # Safety +/// +/// None; the signature matches the one with system sleep. +#[cfg(not(CONFIG_PM_SLEEP))] +unsafe fn pm_register(_nb: *mut bindings::notifier_block) -> c_int { + 0 +} + +/// # Safety +/// +/// None; the signature matches the one with system sleep. +#[cfg(not(CONFIG_PM_SLEEP))] +unsafe fn pm_unregister(_nb: *mut bindings::notifier_block) {} + +// SAFETY: The notifier block is only touched by the PM core, which +// serializes registration, removal and the callbacks itself. +unsafe impl Send for PmHook {} +// SAFETY: See above; the other fields are `Sync`. +unsafe impl Sync for PmHook {} + +impl PmHook { + fn new( + dev: &device::Device, + aop: Arc, + service: EPICService, + ) -> Result>> { + let hook = KBox::pin( + Self { + nb: Opaque::new(bindings::notifier_block { + notifier_call: Some(pm_event), + next: ptr::null_mut(), + priority: 0, + }), + dev: dev.into(), + aop, + service, + registered: Atomic::new(false), + }, + GFP_KERNEL, + )?; + // SAFETY: The block is pinned inside the hook, which unregisters it + // before it goes. + let ret = unsafe { pm_register(hook.nb.get()) }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + hook.registered.store(true, Relaxed); + Ok(hook) + } + + /// Returns once no callback is running any more; repeated calls do + /// nothing. + fn unregister(&self) { + if self.registered.xchg(false, Relaxed) { + // SAFETY: `nb` was registered by `new()`. + unsafe { pm_unregister(self.nb.get()) }; + } + } +} + +impl Drop for PmHook { + fn drop(&mut self) { + self.unregister(); + } +} + fn get_aop_property( aop: &dyn AOP, svc: &EPICService, @@ -206,7 +344,9 @@ enum AlsIio { } struct IIOAopAlsDriver { - /// Declared first: the subscription ends before the IIO device goes. + /// Fields are declared in teardown order: the wake hook (CT817 only) + /// first, then the subscription, which ends before the IIO device goes. + pm: Option>>, listener: FakehidRegistration, _iio: AlsIio, } @@ -285,13 +425,22 @@ impl platform::Driver for IIOAopAlsDriver { }, ) }; + let pm = if offset == LUX_OFFSET_CT817 { + Some(PmHook::new(dev, adata, service)?) + } else { + None + }; Ok(IIOAopAlsDriver { + pm, listener, _iio: iio, }) } fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { + if let Some(pm) = &this.pm { + pm.unregister(); + } this.listener.unregister(); } } From 3fa618e415f61b8b167c74ac60903e808a17d3a3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 13:44:07 +0100 Subject: [PATCH 0147/1514] ASoC: apple: macaudio: lift a fixed ceiling only for a speaker lease A machine with spk_fixed_ceiling has no sense path, so no protection daemon can hold its speakers. Its SN012776 volumes have sat at safe_vol in the locked state as well, so raw ALSA could drive the speaker at that level with no daemon running. Every other SN012776 speaker stays at the floor until a protection daemon unlocks it or a "Speaker Protection" lease is granted. Keep these speakers at the floor while locked, and leave them there for "Speaker Volume Unlock": only a "Speaker Protection" lease lifts the limit, and only to safe_vol, which a grant already uses as the operating gain. macaudio_sn012776_vlimit() computes the limit. The admission KUnit suite checks it, and the fixed-ceiling protection case now also checks that an unlock leaves the amps at the floor. No machine sets spk_fixed_ceiling yet. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/macaudio-admission-test.h | 20 ++++++++++++ sound/soc/apple/macaudio-protection-test.h | 14 +++++++- sound/soc/apple/macaudio.c | 38 +++++++++++++++++----- 3 files changed, 62 insertions(+), 10 deletions(-) diff --git a/sound/soc/apple/macaudio-admission-test.h b/sound/soc/apple/macaudio-admission-test.h index fa5e9f4df00c75..17c7f19c9cd988 100644 --- a/sound/soc/apple/macaudio-admission-test.h +++ b/sound/soc/apple/macaudio-admission-test.h @@ -32,8 +32,28 @@ static void macaudio_admission_needs_a_safe_level(struct kunit *test) KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&cfg)); } +/* Without sense, only a lease lifts the amps, and only to safe_vol */ +static void macaudio_admission_fixed_ceiling_is_lease_only(struct kunit *test) +{ + struct macaudio_platform_cfg cfg = macaudio_j813_cfg; + + /* A protection daemon unlocks the J813's amps to 0 dB */ + KUNIT_EXPECT_FALSE(test, macaudio_spk_lease_only(&cfg)); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, false), SN012776_0DB); + + cfg.safe_vol = -16; + cfg.spk_fixed_ceiling = true; + KUNIT_EXPECT_TRUE(test, macaudio_spk_lease_only(&cfg)); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, false), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, false, true), 1); + KUNIT_EXPECT_EQ(test, macaudio_sn012776_vlimit(&cfg, true, true), SN012776_DB(-16)); +} + static struct kunit_case macaudio_admission_cases[] = { KUNIT_CASE(macaudio_admission_needs_a_safe_level), + KUNIT_CASE(macaudio_admission_fixed_ceiling_is_lease_only), {} }; diff --git a/sound/soc/apple/macaudio-protection-test.h b/sound/soc/apple/macaudio-protection-test.h index d8ef1db227eb5b..1f6cd5ddb987d7 100644 --- a/sound/soc/apple/macaudio-protection-test.h +++ b/sound/soc/apple/macaudio-protection-test.h @@ -1028,7 +1028,10 @@ static void macaudio_spk_j700_does_not_ramp(struct kunit *test) KUNIT_EXPECT_EQ(test, macaudio_test_vol(t.vols[0])->hist[0], (long)MAX98360A_DB(-20)); } -/* A fixed ceiling: the grant runs the amps at it, the ramp starts below it */ +/* + * A fixed ceiling: an unlock leaves the amps at the floor, the lease's grant + * runs them at the ceiling, the ramp starts below it. + */ static void macaudio_spk_fixed_ceiling(struct kunit *test) { struct macaudio_platform_cfg *cfg = kunit_kzalloc(test, sizeof(*cfg), GFP_KERNEL); @@ -1043,6 +1046,15 @@ static void macaudio_spk_fixed_ceiling(struct kunit *test) cfg->spk_fixed_ceiling = true; macaudio_test_spk_card(test, &t, cfg, SN012776_0DB); + /* "Speaker Volume Unlock" lifts nothing: the limit stays at the floor */ + mutex_lock(&t.ma->volume_lock_mutex); + WRITE_ONCE(t.ma->spk_iface, MACAUDIO_SPK_IFACE_UNLOCK); + macaudio_vlimit_unlock(t.ma, true); + WRITE_ONCE(t.ma->spk_iface, MACAUDIO_SPK_IFACE_LEASE); + mutex_unlock(&t.ma->volume_lock_mutex); + for (i = 0; i < MACAUDIO_TEST_NR_SPK; i++) + KUNIT_EXPECT_EQ(test, (long)macaudio_test_vol(t.vols[i])->mc.platform_max, 1L); + /* The limit the lease leaves on the volumes (macaudio_spk_enter_lease()) */ mutex_lock(&t.ma->volume_lock_mutex); macaudio_vlimit_unlock(t.ma, true); diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index b05d60bc0451a0..1b3b8fd0293b63 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -185,9 +185,10 @@ struct macaudio_platform_cfg { bool spk_secondary_only; /* * No voltage or current sense reaches the AP, so no protection daemon - * can govern the speakers: their SN012776 volumes stay under safe_vol, - * locked, unlocked or granted alike, and there is no sense PCM. A - * granted lease runs them at safe_vol, its operating gain. + * can govern the speakers, and there is no sense PCM. "Speaker Volume + * Unlock" does not apply: the SN012776 volumes stay at the floor until + * a "Speaker Protection" lease is granted, which runs them at + * safe_vol, its operating gain and their ceiling. */ bool spk_fixed_ceiling; }; @@ -408,6 +409,26 @@ static bool macaudio_spk_leased(const struct macaudio_snd_data *ma) return READ_ONCE(ma->spk_iface) == MACAUDIO_SPK_IFACE_LEASE; } +/* Only a "Speaker Protection" lease may lift these speakers (spk_fixed_ceiling) */ +static bool macaudio_spk_lease_only(const struct macaudio_platform_cfg *cfg) +{ + return cfg->spk_fixed_ceiling; +} + +/* + * The SN012776 volumes' limit: the floor while locked; unlocked, 0 dB, or + * on a lease-only machine safe_vol, and there only under the lease. + */ +static int macaudio_sn012776_vlimit(const struct macaudio_platform_cfg *cfg, + bool unlock, bool leased) +{ + if (macaudio_spk_lease_only(cfg)) + return unlock && leased ? SN012776_DB(cfg->safe_vol) : 1; + if (unlock) + return SN012776_0DB; + return 1; //SN012776_DB(cfg->safe_vol); +} + SND_SOC_DAILINK_DEFS(primary, DAILINK_COMP_ARRAY(COMP_CPU("mca-pcm-0")), // CPU @@ -534,12 +555,7 @@ static void macaudio_vlimit_unlock(struct macaudio_snd_data *ma, bool unlock) max = 1; //TAS5770_DB(ma->cfg->safe_vol); break; case AMP_SN012776: - if (ma->cfg->spk_fixed_ceiling) - max = SN012776_DB(ma->cfg->safe_vol); - else if (unlock) - max = SN012776_0DB; - else - max = 1; //SN012776_DB(ma->cfg->safe_vol); + max = macaudio_sn012776_vlimit(ma->cfg, unlock, macaudio_spk_leased(ma)); break; case AMP_SSM3515: if (unlock) @@ -768,6 +784,10 @@ static void macaudio_vlimit_update(struct macaudio_snd_data *ma) if (macaudio_spk_leased(ma)) return; + /* No protection daemon can hold these speakers: nothing to unlock */ + if (macaudio_spk_lease_only(ma->cfg)) + return; + /* Check that someone is holding the main lock */ if (!ma->speaker_lock_owner) { reason = "Main control not locked"; From f34b611b138d1a61705bdda8b72e9995e682ee3a Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 06:11:32 -0500 Subject: [PATCH 0148/1514] soc: apple: aop: take the setup-port boot only with a "setup" mailbox The T8142 and T6050 configurations boot the AOP through a second mailbox, named "setup", as well as the RTKit one. Take that boot only when the device tree gives the AOP a mailbox of that name. A device tree that lists only "mbox" gets the boot without the setup port, which is the one the AOP takes where no setup mailbox is described. Signed-off-by: Satya Benson --- drivers/soc/apple/aop.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index fd1e2be06e832b..96e647bd628621 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -1475,7 +1475,11 @@ impl AopData { order.extend_from_slice(default, GFP_KERNEL)?; Ok(order) } - fn new(dev: &platform::Device>, cfg: &AopHwConfig) -> Result> { + fn new( + dev: &platform::Device>, + cfg: &AopHwConfig, + setup_port: bool, + ) -> Result> { let sleep_endpoints = Self::endpoint_order( dev.as_ref(), c_str!("apple,sleep-endpoints"), @@ -1487,7 +1491,7 @@ impl AopData { cfg.wake_endpoints, )?; let registration_queue = OwnedQueue::new_ordered(c_str!("apple-aop"))?; - let setup_queue = if cfg.setup_port { + let setup_queue = if setup_port { Some(OwnedQueue::new_ordered(c_str!("apple-aop-setup"))?) } else { None @@ -3281,7 +3285,14 @@ impl platform::Driver for AopDriver { } else { None }; - let data = AopData::new(pdev, cfg)?; + // The setup-port boot opens the mailbox named "setup"; a device tree + // that gives the AOP no such mailbox gets the boot without it. + let setup_port = cfg.setup_port + && pdev.as_ref().fwnode().is_some_and(|node| { + node.property_match_string(c_str!("mbox-names"), c_str!("setup")) + .is_ok() + }); + let data = AopData::new(pdev, cfg, setup_port)?; // Whatever fails below leaves the AOP running and its children // registering; the same teardown as unbind's cleans that up. let probe_guard = ScopeGuard::new_with_data(data.clone(), |data| data.remove()); @@ -3307,12 +3318,12 @@ impl platform::Driver for AopDriver { rtkit::RtKit::::new(pdev.as_ref(), None, 0, data.clone())? }; data.rtkit.lock().as_mut().set(Some(rtkit)); - if cfg.setup_port { + if setup_port { AopData::setup_open(&data, pdev.as_ref())?; } asc_mmio.update(ASC_CPU_CONTROL, |r| r.with_const_cpu_run::<1>()); data.cpu_started.store(true, Release); - let started = if cfg.setup_port { + let started = if setup_port { // The RTKit handshake up to AP power on comes first, then the // setup port's own power state and endpoint buffers, and only // then the AFK endpoints. From d5cc1f60ea32eb6cd2e5c25ff0b0b38a43144f30 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 02:02:07 +1100 Subject: [PATCH 0149/1514] arm64: dts: apple: t8122-j615: hand the MTP over running, two-stage trackpad power The J615's MTP firmware cannot be restarted once quiesced, as on the J613. After U-Boot used it for the boot keyboard and stopped it, Linux restarted it, the coprocessor crashed (data abort in its first epoch), the helper failed with -ETIME and the internal keyboard and trackpad never appeared. Mark the MTP apple,rtkit-keep-running so a boot stage hands its first epoch over running and Linux adopts it. On the 27.2 firmware the trackpad answers the one-stage power command with 0xe00002c2 and never becomes ready ("multi-touch start timed out"). It accepts the two-stage command, so set apple,power-method = <2>. The 25G83 variant already sets <2> itself (as on the J613 25G83) and now also inherits the keep-running handoff, as the J613 25G83 does. Tested on a J615 on the 27.2 stub, Stage 2 aura 1.0.0b13.1 with this DTB and U-Boot with the keep-running handoff: the session is adopted (4 retained buffers), keyboard, trackpad, STM and actuator interfaces report ready, no dockchannel-hid errors. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615.dts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index 8c3add040f8d9f..3961ac35e65de4 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -146,6 +146,13 @@ &mtp_mt { firmware-name = "apple/tpmtfw-j615.bin"; + /* The 27.x trackpad firmware answers only the two-stage power command. */ + apple,power-method = <2>; +}; + +/* The J615 MTP firmware cannot be restarted once quiesced: hand it over running. */ +&mtp { + apple,rtkit-keep-running; }; &mesa { From 86809d345169d649b4df860bb9067722975ecaf4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 05:02:16 +1100 Subject: [PATCH 0150/1514] spi: apple-qspi: read the T8122 QSPIMC NOR on any board that describes it The probe refuses an apple,t8122-qspi controller unless the machine is the J613, so on another M3 Mac whose device tree describes the boot NOR on QSPIMC (the 15-inch Air, J615) the NOR never probes and there is no nvram device. Drop the board check. The device tree decides whether the controller exists; writes are unchanged: they still need a qualified board entry (apple_qspi_boards[]: machine, aperture, nvram window, JEDEC), so a board without one only reads, whatever its partition says. Tested on the J615 with its NOR described on QSPIMC: JEDEC ef6517 (the J613's W25Q64), the 1 MiB nvram partition reads back with an NVRAM v3 store header, asahi-bless lists the boot volumes; writes are refused. tools/asahi/qspi-nvram-tests.py passes. Signed-off-by: Ryan Murray --- drivers/spi/spi-apple-qspi.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/drivers/spi/spi-apple-qspi.c b/drivers/spi/spi-apple-qspi.c index 06e2d356dcbec3..d3af8452c9aad3 100644 --- a/drivers/spi/spi-apple-qspi.c +++ b/drivers/spi/spi-apple-qspi.c @@ -1017,9 +1017,6 @@ static int apple_qspi_probe(struct platform_device *pdev) qspi->nvram_policy = true; qspi->nvram_window = soc->multi_io_reads; apple_qspi_nvram_window(dev, qspi); - if (of_device_is_compatible(dev->of_node, "apple,t8122-qspi") && - !of_machine_is_compatible("apple,j613")) - return -ENODEV; init_completion(&qspi->done); spin_lock_init(&qspi->lock); From d7e3179f110ec48da78a9e39066100ea5eb0d34d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 05:02:16 +1100 Subject: [PATCH 0151/1514] arm64: dts: apple: t8122-j615: describe the NVRAM NOR on QSPIMC The J615 includes the J613/J615 common tree, which places the NVRAM on SPI1 as on the M1 and M2 Macs. The J615's ADT has its boot NOR on QSPIMC instead, with nvram at 0x700000 (1 MiB), the layout t8122-j613-qspi.dtsi describes. Probing SPI1 finds nothing ("unrecognized JEDEC id bytes: 00"), so the J615 has no nvram device and cannot read or select its boot volume. Include t8122-j613-qspi.dtsi in the J615 tree and keep the partition read-only: there is no NVRAM write entry for this board. The 25G83 variant got both from its own lines, which go now that it inherits them; its DTB is unchanged, as is the J613's. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615-25g83.dts | 6 ------ arch/arm64/boot/dts/apple/t8122-j615.dts | 9 +++++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts index 7aef84a8e34940..af4143bd3efe08 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts @@ -5,7 +5,6 @@ */ #include "t8122-j615.dts" #include "t8122-j613-dcp-25g83.dtsi" -#include "t8122-j613-qspi.dtsi" /* As on the J613 25G83. */ &mtp { @@ -16,8 +15,3 @@ &mtp_mt { apple,power-method = <2>; }; - -/* Keep the J615 NVRAM partition read-only. */ -&nvram_qspi { - read-only; -}; diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index fdb511bd9a4e7c..13336309977be8 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -11,6 +11,7 @@ #include "t8122.dtsi" #include "t8122-j613-j615.dtsi" +#include "t8122-j613-qspi.dtsi" / { compatible = "apple,j615", "apple,t8122", "apple,arm-platform"; @@ -161,3 +162,11 @@ /* Per-device factory data from this Mac's own iBoot system container. */ firmware-name = "apple/mesacal-j615.bin"; }; + +/* + * The J615 ADT puts the boot NOR and its nvram on QSPIMC, as on the J613. + * No NVRAM write entry exists for this board yet: keep it read-only. + */ +&nvram_qspi { + read-only; +}; From 02e85f129073c9bb3ac8b704bfec2c6b47b6cb00 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 6 Nov 2026 12:54:40 -0300 Subject: [PATCH 0152/1514] drm/asahi: g17: blame a page fault on the VM the MMU fault record names On a page fault, recovery kept the queue the firmware blamed, which can be a bystander. On 2026-11-06 a compute test's write fault (units CMP(2) and CMP(0), UAT slot 17 in both fault banks) was blamed on a render queue of another VM (context 19). That render failed with EIO and its client lost the device, while the test's interrupted compute was spared, replayed and faulted again 0.3 ms later. The MMU fault banks name the UAT slot of each faulting access, and every in-flight packet carries the context ID of the slot it runs in. Collect the faulting slots while the firmware is halted. When the in-flight work in those slots does not include the blamed queue, blame that work instead, so classification spares the bystander's VM and fails the faulting one. Without a decodable fault, without in-flight work in the faulting slots, or when the blamed queue is among that work, the firmware's blame stands. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 6 + drivers/gpu/drm/asahi/g17/queue/render.rs | 6 + drivers/gpu/drm/asahi/g17/recovery.rs | 14 ++- .../gpu/drm/asahi/g17/recovery/attribution.rs | 108 ++++++++++++++++++ drivers/gpu/drm/asahi/g17/runtime/events.rs | 30 +++-- .../drm/asahi/g17/runtime/render/recovery.rs | 14 +++ 6 files changed, 163 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 5492a740759e56..afc1ee221567ab 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -962,6 +962,12 @@ impl Queue { visit(active.packet.completion.status()); } } + /// The context ID (UAT slot) of every in-flight packet. + pub(crate) fn visit_contexts(&self, visit: &mut dyn FnMut(u32)) { + for active in self.active.iter() { + visit(active.packet.context.id()); + } + } /// A recovery record names this queue and the completion stamp of the /// command it interrupted, `kick << 8` like the queue's stamp. Without a /// stamp match the oldest published command is marked. diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 4273f178bf602f..47a4e1d1c0c5f4 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -1898,6 +1898,12 @@ impl Pair { visit(active.packet.completion.status()); } } + /// The context ID (UAT slot) of every in-flight packet. + pub(crate) fn visit_contexts(&self, visit: &mut dyn FnMut(u32)) { + for active in self.active.iter() { + visit(active.packet.context.id()); + } + } pub(crate) fn classify(&self, classify: &dyn Fn(&Arc) -> recovery::Class) { for active in self.active.iter() { active diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 7bb3e339cfbb1b..3c59030544d5ed 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -11,7 +11,7 @@ mod attribution; mod slot; mod safety; pub(crate) use safety::{note_retired, since_retired}; -pub(crate) use attribution::{Record, Sources, PAGE_FAULT}; +pub(crate) use attribution::{fault_qids, Record, Sources, PAGE_FAULT}; use attribution::Attribution; pub(super) fn slot_key(slot: usize, slot_keys: Option) -> Option { @@ -116,8 +116,12 @@ pub(super) trait Queues { fn note_interrupted(&mut self, qid: u8, stamp: u32) -> Interrupted; /// Optional diagnostics only; absence cannot alter attribution or release. fn report_blamed_render(&self, _qid: u8) {} - /// Optional diagnostics: logs the MMU fault banks while the firmware is halted. - fn report_mmu_fault(&self) {} + /// Logs the MMU fault banks while the firmware is halted and returns the UAT slots + /// (context IDs) of the faulting accesses as a mask; 0 without a decodable user fault. + fn report_mmu_fault(&self) -> u64 { 0 } + /// Read while firmware is halted, like `render_pass_started`. The QIDs of every queue with + /// an in-flight packet whose context is in `slots`; None if there is none. + fn fault_culprit(&self, _slots: u64) -> Option { None } fn settle_blamed_render(&mut self, qid: u8, error: Error); fn settle_cancelled_renders(&mut self, qids: u128); fn rescan_compute(&mut self) -> Result; @@ -269,7 +273,7 @@ pub(super) fn service( let mut sources = host.fault_sources()?; sources.report(request.generation, super::queue::compute::retirement::stampless_total(), request.blamed); - host.report_mmu_fault(); + let fault_slots = host.report_mmu_fault(); if let Some(qid) = request.blamed { host.report_blamed_render(qid); } @@ -280,6 +284,8 @@ pub(super) fn service( |qid, stamp| host.render_pass_started(qid, stamp)); let attribution = sources.host_fallback(attribution, || host.render_culprit(request.blamed?)); + let attribution = sources.fault_override(attribution, request.blamed, fault_slots, + |slots| host.fault_culprit(slots)); if let Attribution::Queues(qids) = attribution { pr_warn!("G17: recovery gen {} blames queues {:#x}\n", request.generation, qids); } diff --git a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs index c9572ff4561e09..8047cfa31620b9 100644 --- a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs +++ b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs @@ -193,6 +193,42 @@ impl Sources { } culprit().map_or(Attribution::Firmware, Attribution::Queues) } + + /// A page fault's MMU record names the UAT slots of the faulting accesses. Firmware blames + /// a queue it chose, which can be a bystander's (a compute write fault blamed on a render + /// queue of another VM). When the in-flight work of those slots (`culprit`) does not include + /// the blamed queue, that work is blamed instead; without such evidence the firmware's blame + /// stands. + pub(super) fn fault_override( + &self, + attribution: Attribution, + blamed: Option, + slots: u64, + culprit: impl FnOnce(u64) -> Option, + ) -> Attribution { + if self.reason != Some(PAGE_FAULT) || attribution != Attribution::Firmware || slots == 0 { + return attribution; + } + let Some(blamed) = blamed else { + return attribution; + }; + match culprit(slots) { + Some(qids) if qids != 0 && qids & (1u128 << blamed) == 0 => Attribution::Queues(qids), + _ => attribution, + } + } +} + +/// The QIDs of every queue with an in-flight packet in one of the UAT `slots`. `visit` reports +/// each in-flight packet as its queue's QIDs and its context ID (the UAT slot it runs in). +pub(crate) fn fault_qids(slots: u64, visit: impl FnOnce(&mut dyn FnMut(u128, u32))) -> Option { + let mut qids = 0; + visit(&mut |queue, context| { + if 1u64.checked_shl(context).is_some_and(|bit| bit & slots != 0) { + qids |= queue; + } + }); + (qids != 0).then_some(qids) } #[kernel::macros::kunit_tests(asahi_g17_recovery_sources)] @@ -290,4 +326,76 @@ mod tests { assert_eq!(sources.host_fallback(Attribution::NoCulprit, || panic!("slot evidence")), Attribution::NoCulprit); } + + /// The in-flight work of 2026-11-06 12:37:58: WoW's render pair (QIDs 65 and 66, four + /// renders in context 19) and a compute test's queue 60 in context 17. + fn incident(slots: u64) -> Option { + fault_qids(slots, |visit| { + for _ in 0..4 { + visit(3 << 65, 19); + } + visit(1 << 60, 17); + }) + } + + #[test] + fn a_page_fault_in_another_vm_moves_firmware_blame() { + // Both MMU banks: write ReadOnly, units CMP(2)/CMP(0), vm_slot 17. Firmware blamed + // queue 66; slot 5's key read 0, so slot identity could not check it. + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + let attribution = sources.attribute(Some(66), |_, _| panic!("unknown key")); + assert_eq!(attribution, Attribution::Firmware); + let attribution = sources.host_fallback(attribution, || panic!("page fault")); + assert_eq!(sources.fault_override(attribution, Some(66), 1 << 17, incident), + Attribution::Queues(1 << 60)); + } + + #[test] + fn a_page_fault_in_the_blamed_vm_keeps_firmware_blame() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 19, incident), + Attribution::Firmware); + // Both VMs faulted: the blamed queue is among the culprits. + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), (1 << 17) | (1 << 19), + incident), Attribution::Firmware); + } + + #[test] + fn a_page_fault_without_slot_evidence_keeps_firmware_blame() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(PAGE_FAULT); + // No decodable fault in either bank (reason 3 with clear status words). + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 0, |_| panic!("no fault")), + Attribution::Firmware); + // No in-flight work runs in the faulting slot. + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 23, incident), + Attribution::Firmware); + // Firmware blamed no queue: the recovery table alone decides, as before. + assert_eq!(sources.fault_override(Attribution::Firmware, None, 1 << 17, |_| panic!("no blame")), + Attribution::Firmware); + } + + #[test] + fn fault_slots_never_override_a_timeout_or_slot_evidence() { + let mut sources = Sources::sample(1 << 5, |_| Some((0, 0))); + sources.reason = Some(2); + assert_eq!(sources.fault_override(Attribution::Firmware, Some(66), 1 << 17, |_| panic!("timeout")), + Attribution::Firmware); + sources.reason = Some(PAGE_FAULT); + assert_eq!(sources.fault_override(Attribution::NoCulprit, Some(66), 1 << 17, |_| panic!("slots")), + Attribution::NoCulprit); + assert_eq!(sources.fault_override(Attribution::Queues(1 << 38), Some(66), 1 << 17, + |_| panic!("slots")), Attribution::Queues(1 << 38)); + } + + #[test] + fn fault_qids_match_contexts_by_uat_slot() { + assert_eq!(incident(1 << 17), Some(1 << 60)); + assert_eq!(incident(1 << 19), Some(3 << 65)); + assert_eq!(incident(0), None); + // A context ID beyond the mask's 64 slots never matches. + assert_eq!(fault_qids(u64::MAX, |visit| visit(1 << 7, 64)), None); + } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 0dcc97ba9b3c83..24bf7c382ecf46 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -197,6 +197,9 @@ impl recovery::Queues for Service<'_> { fn render_culprit(&self, blamed: u8) -> Option { self.firmware.queues.render_culprit(blamed) } + fn fault_culprit(&self, slots: u64) -> Option { + self.firmware.queues.fault_culprit(slots) + } fn publish_recovery_targets(&self) -> Option { let mut failure = self.firmware.queues.publish_render_recovery_targets(); for queue in self @@ -278,27 +281,32 @@ impl recovery::Queues for Service<'_> { .queues .report_render_recovery(qid, &self.firmware.port); } - fn report_mmu_fault(&self) { + fn report_mmu_fault(&self) -> u64 { let banks = match self.firmware.port.fault_banks() { Ok(banks) => banks, Err(error) => { pr_warn!("G17: recovery MMU fault banks unreadable: {:?}\n", error); - return; + return 0; } }; + let mut slots = 0u64; for (bank, &(status, address)) in banks.iter().enumerate() { match crate::regs::decode_fault(status, address, true) { - Some(info) => pr_warn!( - "G17: recovery MMU fault bank {}: address {:#x} {} {:?} unit {:?} ({:#x}) level {} vm_slot {} sideband {:#x} (status {:#x})\n", - bank, info.address, if info.read { "read" } else { "write" }, info.reason, - info.unit, info.unit_code, info.level, info.vm_slot, info.sideband, status - ), - None => pr_info!( - "G17: recovery MMU fault bank {}: no fault (status {:#x})\n", - bank, status - ), + Some(info) => { + pr_warn!( + "G17: recovery MMU fault bank {}: address {:#x} {} {:?} unit {:?} ({:#x}) level {} vm_slot {} sideband {:#x} (status {:#x})\n", + bank, info.address, if info.read { "read" } else { "write" }, info.reason, + info.unit, info.unit_code, info.level, info.vm_slot, info.sideband, status + ); + // Slot 0 is the firmware's own context, never a client's. + if info.vm_slot != 0 { + slots |= 1u64.checked_shl(info.vm_slot).unwrap_or(0); + } + } + None => pr_info!("G17: recovery MMU fault bank {}: no fault (status {:#x})\n", bank, status), } } + slots } fn settle_blamed_render(&mut self, qid: u8, error: Error) { let result = self diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs index 02ece8cf4025b7..5a65182f02e00a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs @@ -46,6 +46,20 @@ impl Registry { }) } + /// See `recovery::Queues::fault_culprit`. + pub(in crate::g17::runtime) fn fault_culprit(&self, slots: u64) -> Option { + crate::g17::recovery::fault_qids(slots, |visit| { + for pair in self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()) { + let qids = pair.qids().into_iter().fold(0, |mask, qid| mask | 1u128 << qid); + pair.visit_contexts(&mut |context| visit(qids, context)); + } + for queue in self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) { + let qid = 1u128 << queue.qid(); + queue.visit_contexts(&mut |context| visit(qid, context)); + } + }) + } + pub(in crate::g17::runtime) fn publish_render_recovery_targets(&self) -> Option { let mut failure = None; for pair in self.render.entries.iter().flatten() From d4ca66d0aed0964068e813bf96e1b2e4b545d4d8 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 16:27:09 -0300 Subject: [PATCH 0153/1514] selftests: apple-dcp: follow a port that does not wait for its router The probe fixture stubs cd321x_tbt_switch_keep_waiting() and expects a CD321x port whose USB4/Thunderbolt router has not registered to defer its probe until the driver core stops waiting. A port that takes the router late at once has no such helper: the stub is then an unused static function, which -Werror turns into a build failure of the typec-probe and probe-mux-pm-dispatch units. When core.c has no cd321x_tbt_switch_keep_waiting(), drop the stub and expect the port to probe without the router on the first try, watching for it as before. Trees that still wait keep the old check. Signed-off-by: Jonathan Goyvaerts --- .../selftests/drivers/gpu/apple-dcp/pm.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py index 0c403fa4e7c0d1..87a44b8242897f 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py @@ -783,6 +783,24 @@ def function(text, name): assert controls.count(probed) == 1 controls = controls.replace(probed, probed + ' assert(reboots==1&&c.reboot_nb_registered&&c.reboot_nb.notifier_call==cd321x_reboot_notify);\n', 1) + # Newer trees do not wait for the driver core to give up on a missing router. + if 'cd321x_tbt_switch_keep_waiting(' not in core: + assert late_watch + stub = 'static bool keep_waiting=true;\nstatic bool cd321x_tbt_switch_keep_waiting(struct device *d) { (void)d;return keep_waiting; }\n' + assert mocks.count(stub) == 1 + mocks = mocks.replace(stub, '', 1) + wait = r''' /* Missing router defers while suppliers may still bind, then is optional. */ + reset(&c);switch_error=-EPROBE_DEFER; + assert(cd321x_register_port(&c.tps,&connector)==-EPROBE_DEFER);balanced(); + reset(&c);switch_error=-EPROBE_DEFER;keep_waiting=false; +''' + assert controls.count(wait) == 1 + controls = controls.replace(wait, ''' /* A missing router is optional at once. */ + reset(&c);switch_error=-EPROBE_DEFER; +''', 1) + controls = controls.replace('keep_waiting=true;', '').replace('keep_waiting=false;', '') + assert 'keep_waiting' not in controls + return prefix + pm + mocks + production + '\n#define TEST_DEFER 1\n#define TEST_FWNODE 1\n' + controls From 066899a22db7f24537b05f6086172d1b4d5a1b3f Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 12:30:24 -0300 Subject: [PATCH 0154/1514] usb: typec: tipd: don't wait for a USB4 router at probe Since commit 6c3055be2e02 ("usb: typec: tipd: take a USB4 router that binds after the port"), a CD321x/SN201202x port that probed without its USB4/Thunderbolt router watches for the router and takes it whenever it registers, reapplying the cable state through it. The probe still defers while the driver core waits for missing dependencies, though, so a port whose router never registers waits for the deferred probe timeout. The USB controllers wait with it, because they need the port's role switch and mux. That happens on every boot of a kernel without CONFIG_USB4, and of any Mac whose router has no driver. On a J616s (M4 Pro, T6040) with USB4 off, all three ports log [16.361798] sn201202x 1-0a: deferred probe timeout, ignoring dependency dwc3 binds at 16.9 s and a USB disk attached at boot appears at 22 s. The wait buys nothing: a router that binds before the port probes is taken at probe, and one that binds later is taken by the watch, exactly as when the port gave up after the timeout. Take the late path as soon as the lookup finds a router that has not registered its switch, and drop cd321x_tbt_switch_keep_waiting(). Power delivery, USB and DisplayPort then start at once, with and without a router driver. The KUnit test for a pending router now expects the port to probe without it and to watch for it. Signed-off-by: Jonathan Goyvaerts --- drivers/usb/typec/tipd/Kconfig | 2 +- drivers/usb/typec/tipd/cd321x-tbt-test.c | 44 +++--------------------- drivers/usb/typec/tipd/core.c | 24 +++++-------- drivers/usb/typec/tipd/tps6598x.h | 1 - 4 files changed, 13 insertions(+), 58 deletions(-) diff --git a/drivers/usb/typec/tipd/Kconfig b/drivers/usb/typec/tipd/Kconfig index 40e55777c62831..cbc177901c71e9 100644 --- a/drivers/usb/typec/tipd/Kconfig +++ b/drivers/usb/typec/tipd/Kconfig @@ -56,7 +56,7 @@ config TYPEC_TIPD_KUNIT_TEST Also test that interrupt events which could not be read or cleared are still acknowledged, however long that keeps failing, so that the controller keeps raising its interrupt. - Also test that a USB4/Thunderbolt router which never registers its + Also test that a USB4/Thunderbolt router which has not registered its switch does not keep the port from probing. Also test that a Type-C state which a mux provider with transient timeouts holds up is applied again until it goes through, for up to diff --git a/drivers/usb/typec/tipd/cd321x-tbt-test.c b/drivers/usb/typec/tipd/cd321x-tbt-test.c index 8e1d83d18546c5..ebf27926171df4 100644 --- a/drivers/usb/typec/tipd/cd321x-tbt-test.c +++ b/drivers/usb/typec/tipd/cd321x-tbt-test.c @@ -4,7 +4,6 @@ */ #include -#include #include #include #include @@ -100,21 +99,10 @@ static const struct software_node * const cd321x_test_nodes[] = { struct cd321x_tbt_test { struct device *dev; - bool keep_waiting; - unsigned int keep_waiting_calls; unsigned int set_calls; int last_state; }; -/* Stands in for the driver core's answer on whether to keep waiting. */ -static bool cd321x_tbt_test_keep_waiting(struct device *dev) -{ - struct cd321x_tbt_test *ctx = kunit_get_current_test()->priv; - - ctx->keep_waiting_calls++; - return ctx->keep_waiting; -} - static void cd321x_tbt_test_unregister_nodes(void *unused) { software_node_unregister_node_group(cd321x_test_nodes); @@ -137,9 +125,6 @@ static int cd321x_tbt_test_init(struct kunit *test) ctx->dev = kunit_device_register(test, "cd321x"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); - - kunit_activate_static_stub(test, cd321x_tbt_switch_keep_waiting, - cd321x_tbt_test_keep_waiting); return 0; } @@ -170,7 +155,6 @@ static void cd321x_tbt_no_router_test(struct kunit *test) &late); KUNIT_EXPECT_NULL(test, sw); KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 0); } /* A router whose driver has registered its switch is used. */ @@ -203,44 +187,25 @@ static void cd321x_tbt_router_bound_test(struct kunit *test) &late); KUNIT_EXPECT_NOT_ERR_OR_NULL(test, sw); KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 0); typec_thunderbolt_switch_put(sw); } -/* A router that has not registered its switch yet defers the port. */ -static void cd321x_tbt_router_pending_test(struct kunit *test) -{ - struct cd321x_tbt_test *ctx = test->priv; - struct typec_thunderbolt_switch *sw; - bool late = true; - - ctx->keep_waiting = true; - sw = cd321x_tbt_switch_get(ctx->dev, - software_node_fwnode(&cd321x_test_connector), - &late); - KUNIT_EXPECT_PTR_EQ(test, sw, ERR_PTR(-EPROBE_DEFER)); - KUNIT_EXPECT_FALSE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 1); -} - /* - * Once the driver core stops waiting for missing dependencies, a router that - * has not registered its switch no longer keeps the port from probing, and the - * port is told to take the router if it binds later. + * A router that has not registered its switch does not keep the port from + * probing, even while the driver core still waits for missing dependencies: + * the port is told to take the router when it binds. */ -static void cd321x_tbt_router_never_binds_test(struct kunit *test) +static void cd321x_tbt_router_pending_test(struct kunit *test) { struct cd321x_tbt_test *ctx = test->priv; struct typec_thunderbolt_switch *sw; bool late = false; - ctx->keep_waiting = false; sw = cd321x_tbt_switch_get(ctx->dev, software_node_fwnode(&cd321x_test_connector), &late); KUNIT_EXPECT_NULL(test, sw); KUNIT_EXPECT_TRUE(test, late); - KUNIT_EXPECT_EQ(test, ctx->keep_waiting_calls, 1); } static int cd321x_tbt_test_notify(struct notifier_block *nb, @@ -458,7 +423,6 @@ static struct kunit_case cd321x_tbt_cases[] = { KUNIT_CASE(cd321x_tbt_no_router_test), KUNIT_CASE(cd321x_tbt_router_bound_test), KUNIT_CASE(cd321x_tbt_router_pending_test), - KUNIT_CASE(cd321x_tbt_router_never_binds_test), KUNIT_CASE(cd321x_tbt_router_binds_late_test), KUNIT_CASE(cd321x_tbt_router_bound_before_watch_test), KUNIT_CASE(cd321x_tbt_other_router_binds_test), diff --git a/drivers/usb/typec/tipd/core.c b/drivers/usb/typec/tipd/core.c index b31a15f3dcf460..abd4d2c19007f7 100644 --- a/drivers/usb/typec/tipd/core.c +++ b/drivers/usb/typec/tipd/core.c @@ -2647,21 +2647,13 @@ VISIBLE_IF_KUNIT int cd321x_reboot_notify(struct notifier_block *nb, } EXPORT_SYMBOL_IF_KUNIT(cd321x_reboot_notify); -/* Separate so that the KUnit tests can choose the driver core's answer. */ -VISIBLE_IF_KUNIT bool cd321x_tbt_switch_keep_waiting(struct device *dev) -{ - KUNIT_STATIC_STUB_REDIRECT(cd321x_tbt_switch_keep_waiting, dev); - - return driver_deferred_probe_check_state(dev) == -EPROBE_DEFER; -} -EXPORT_SYMBOL_IF_KUNIT(cd321x_tbt_switch_keep_waiting); - /* * The USB4/Thunderbolt router is only needed once a USB4 or Thunderbolt link * comes up. If its driver is not built or has not bound yet, do not leave power - * delivery, USB and DisplayPort on this port without a driver as well: stop - * waiting for the router when the driver core stops waiting for missing - * dependencies. The router can still bind later, so set @late to take it then. + * delivery, USB and DisplayPort on this port without a driver as well. The port + * takes the router whenever it binds (set @late), so it does not wait for it: + * waiting for the driver core to give up on a router that is not built delays + * every port by the deferred probe timeout. */ VISIBLE_IF_KUNIT struct typec_thunderbolt_switch * cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, @@ -2671,7 +2663,7 @@ cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, *late = false; sw = fwnode_typec_thunderbolt_switch_get(fwnode); - if (sw != ERR_PTR(-EPROBE_DEFER) || cd321x_tbt_switch_keep_waiting(dev)) + if (sw != ERR_PTR(-EPROBE_DEFER)) return sw; dev_info(dev, "USB4/Thunderbolt router unavailable, continuing without it until it binds\n"); @@ -2681,9 +2673,9 @@ cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, EXPORT_SYMBOL_IF_KUNIT(cd321x_tbt_switch_get); /* - * Take a router that bound after the port gave up on it, or that unbound and - * bound again. An attached cable raises no new event, so reapply it through - * the router as after system sleep. + * Take a router that bound after the port probed without it, or that unbound + * and bound again. An attached cable raises no new event, so reapply it + * through the router as after system sleep. */ static void cd321x_tbt_attach_work(struct work_struct *work) { diff --git a/drivers/usb/typec/tipd/tps6598x.h b/drivers/usb/typec/tipd/tps6598x.h index abd1705ee6fe58..bb280a7795ccdf 100644 --- a/drivers/usb/typec/tipd/tps6598x.h +++ b/drivers/usb/typec/tipd/tps6598x.h @@ -584,7 +584,6 @@ void cd321x_stop_work(struct cd321x *cd321x); int cd321x_reboot_close(struct cd321x *cd321x); int cd321x_reboot_notify(struct notifier_block *nb, unsigned long action, void *data); -bool cd321x_tbt_switch_keep_waiting(struct device *dev); struct typec_thunderbolt_switch * cd321x_tbt_switch_get(struct device *dev, struct fwnode_handle *fwnode, bool *late); From 3676688b7560a57d5a1b22aa8aab44469f09720c Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:28:32 +1100 Subject: [PATCH 0155/1514] tools: aurora-sep: install the logind drop-in ahead of the distribution's The packages install logind-aurora-sep.conf as /usr/lib/systemd/logind.conf.d/50-aurora-sep.conf. logind reads the drop-ins of /etc and /usr/lib in one list sorted by file name, and the last setting wins, so the file overrode every distribution or administrator drop-in that sorts before "50-". Omarchy ships /etc/systemd/logind.conf.d/10-ignore-power-button.conf with HandlePowerKey=ignore and binds the key to its own power menu; with aurora-sep installed a short press suspended instead, and pressing the Touch ID button to unlock after opening the lid put the Mac back to sleep. The drop-in only exists to replace logind's built-in poweroff. Install it as 05-aurora-sep.conf so that it still does that, and any drop-in a distribution or administrator adds takes precedence. The README's manual install uses the same name, and the file says why. systemd-analyze cat-config with Omarchy's drop-in in /etc: as 50-aurora-sep.conf the last HandlePowerKey is suspend, as 05-aurora-sep.conf it is ignore. Without another drop-in it stays suspend. Reported-by: gig3m Fixes: 700c97c09d72 ("tools: aurora-sep: suspend rather than power off on the Touch ID button") Link: https://github.com/aurora-silicon/linux/issues/1877 Signed-off-by: Ryan Murray --- tools/aurora-sep/README.md | 9 +++++++-- tools/aurora-sep/logind-aurora-sep.conf | 6 ++++++ tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD | 4 ++-- tools/aurora-sep/packaging/fedora/aurora-sep.spec | 10 +++++++--- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/tools/aurora-sep/README.md b/tools/aurora-sep/README.md index c422501e579baa..b408ac8f724139 100644 --- a/tools/aurora-sep/README.md +++ b/tools/aurora-sep/README.md @@ -338,10 +338,15 @@ suspend instead, so pressing while authenticating loses nothing and the next press wakes the machine, and holding the button for 5 s powers off cleanly. GNOME sessions and the GDM login screen handle a short press themselves (`power-button-action`, `suspend` by default); the setting covers consoles -and other desktops. It takes effect at the next boot. By hand: +and other desktops. It takes effect at the next boot. The packages install it +as `05-aurora-sep.conf`: logind sorts the drop-ins of `/etc` and `/usr/lib` by +file name and the last one wins, so it only replaces logind's own default, +and a distribution or administrator drop-in (`HandlePowerKey=ignore` where a +compositor shows its own power menu, for example) still takes precedence. By +hand: ```sh -install -Dm644 logind-aurora-sep.conf /etc/systemd/logind.conf.d/aurora-sep.conf +install -Dm644 logind-aurora-sep.conf /etc/systemd/logind.conf.d/05-aurora-sep.conf ``` GNOME Shell 51 offers fingerprint only on the lock screen, never on the diff --git a/tools/aurora-sep/logind-aurora-sep.conf b/tools/aurora-sep/logind-aurora-sep.conf index a175c39f6ca73c..eb7d219ac7a259 100644 --- a/tools/aurora-sep/logind-aurora-sep.conf +++ b/tools/aurora-sep/logind-aurora-sep.conf @@ -6,6 +6,12 @@ # 5 s still powers off, cleanly. GNOME sessions and the GDM login screen # handle a short press themselves (power-button-action, suspend by default); # this covers everything else. +# +# Installed as 05-aurora-sep.conf. logind reads the drop-ins of /etc and +# /usr/lib in one list sorted by file name, and a later file wins, so this +# only replaces logind's built-in poweroff: a distribution's or an +# administrator's drop-in (HandlePowerKey=ignore for a compositor's power +# menu, for example) still decides. [Login] HandlePowerKey=suspend HandlePowerKeyLongPress=poweroff diff --git a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD index b9dc8bc9b33184..d9bc8e61c35303 100644 --- a/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD +++ b/tools/aurora-sep/packaging/arch/aurora-sep/PKGBUILD @@ -7,7 +7,7 @@ pkgname=aurora-sep pkgver=1 -pkgrel=18 +pkgrel=19 pkgdesc="Loader and desktop integration for the Apple SEP (Touch ID) driver" url="https://github.com/aurora-silicon/linux/tree/aurora-wip/tools/aurora-sep" arch=(any) @@ -101,7 +101,7 @@ package() { sed 's|@FPRINTD@|/usr/lib/fprintd|' fprintd-no-timeout.conf.in \ >"$pkgdir/usr/lib/systemd/system/fprintd.service.d/50-aurora-sep-no-timeout.conf" install -Dm644 logind-aurora-sep.conf \ - "$pkgdir/usr/lib/systemd/logind.conf.d/50-aurora-sep.conf" + "$pkgdir/usr/lib/systemd/logind.conf.d/05-aurora-sep.conf" install -Dm755 sep-bio-identities "$pkgdir/usr/bin/sep-bio-identities" install -Dm755 aurora-sep "$pkgdir/usr/bin/aurora-sep" sed -i "s|^\(Exec[A-Za-z]*=\)/usr/local/sbin/|\1/usr/lib/aurora-sep/|" \ diff --git a/tools/aurora-sep/packaging/fedora/aurora-sep.spec b/tools/aurora-sep/packaging/fedora/aurora-sep.spec index 7a1ba80b0514d6..7cec78c374413c 100644 --- a/tools/aurora-sep/packaging/fedora/aurora-sep.spec +++ b/tools/aurora-sep/packaging/fedora/aurora-sep.spec @@ -8,7 +8,7 @@ Name: aurora-sep Version: 1 -Release: 13%{?dist} +Release: 14%{?dist} Summary: Loader and desktop integration for the Apple SEP fingerprint driver License: GPL-2.0-only @@ -108,7 +108,7 @@ grep -qx 'ExecStart=%{_libexecdir}/fprintd' %{_unitdir}/fprintd.service sed 's|@FPRINTD@|%{_libexecdir}/fprintd|' %{SOURCE7} \ >%{buildroot}%{_unitdir}/fprintd.service.d/50-aurora-sep-no-timeout.conf install -Dpm 0644 %{SOURCE8} \ - %{buildroot}%{_prefix}/lib/systemd/logind.conf.d/50-aurora-sep.conf + %{buildroot}%{_prefix}/lib/systemd/logind.conf.d/05-aurora-sep.conf install -Dpm 0755 %{SOURCE16} %{buildroot}%{_bindir}/sep-bio-identities install -Dpm 0755 %{SOURCE26} %{buildroot}%{_bindir}/aurora-sep sed -i "s|^\(Exec[A-Za-z]*=\)/usr/local/sbin/|\1%{_libexecdir}/|" \ @@ -189,7 +189,7 @@ fi %dir %{_unitdir}/fprintd.service.d %{_unitdir}/fprintd.service.d/aurora-sep.conf %{_unitdir}/fprintd.service.d/50-aurora-sep-no-timeout.conf -%{_prefix}/lib/systemd/logind.conf.d/50-aurora-sep.conf +%{_prefix}/lib/systemd/logind.conf.d/05-aurora-sep.conf %{_presetdir}/80-aurora-sep.preset %files selinux @@ -197,6 +197,10 @@ fi %ghost %verify(not md5 size mode mtime) %{_sharedstatedir}/selinux/%{selinuxtype}/active/modules/200/%{modulename} %changelog +* Sat Nov 21 2026 Ryan Murray - 1-14 +- Install the logind drop-in as 05-aurora-sep.conf, so that a distribution's + or an administrator's power key setting overrides it + * Fri Nov 20 2026 Diljit Singh - 1-13 - SEP writes are always on: aurora-sep-load runs modprobe apple_sep with no options, since the driver no longer has xart_writes or provision_keybag From 52dabe33448bc2a3b9f6b04375c27ae8420b0a99 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:35:32 +1100 Subject: [PATCH 0156/1514] soc: apple: sep: select the platform profile by SoC On T8122, T6040, T6041, T6050, T8132 and T8142 the SEP profile was chosen only for the boards it had been tried on (J613, J615, J614s, J616s, J614c, J616c, J714s, K116s, J716c, J713, J715, J813, J815). Every other board with the same SoC got no profile, and so no SEP and no Touch ID, although each profile holds only SoC facts: the SEP's shared memory and handshake, its DART window, and the SPI controller the SoC wires to the sensor. Select by the SoC compatible, as T8103, T8112, T6000/T6001, T6020/T6021 and T8140 already are. A board without a built-in sensor has nothing on that bus: the sensor probe finds no part and the SEP runs without biometrics, as on the M1 and M2 Mac minis. A device tree that does not describe the SEP at all (the T8142 J704 has no apple,sep node yet) now gets no profile, so module init keeps saying the SEP stays disabled instead of failing on the missing node. The KUnit selection test now checks that the board compatible does not matter, and the Touch ID list covers the boards this admits. The profiles were written by Scott Jones (T8122), Michal S. (J614s), Artyom Astafurov and Jos Dehaes (T6041), Diljit Singh (T6050), Jens Axboe (K116s), Erik Bourget (J713, J716c) and Nick (T8142). Fixes: 64ff4f1a3f3ec ("soc: apple: sep: add a T8122 (MacBook Air M3) platform profile") Signed-off-by: Ryan Murray --- drivers/soc/apple/profile.rs | 85 +++++++++++++++++++++--------------- 1 file changed, 51 insertions(+), 34 deletions(-) diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 29e74e2df0c57d..92fc7e03777c0c 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -648,8 +648,12 @@ fn t6020_profile() -> &'static PlatformProfile { /// Select the profile for the running machine. An unsupported SoC is refused /// rather than guessed at, so the driver cannot run a handshake with the wrong -/// geometry. +/// geometry. A device tree that does not describe the SEP (no `apple,sep` +/// node) gets no profile either: there is nothing to enable or bind. pub(crate) fn detect() -> Result<&'static PlatformProfile> { + if crate::dt::sep_node().is_none() { + return Err(ENODEV); + } select(&machine_has, &t6020_profile) } @@ -692,30 +696,31 @@ fn select( if has(b"apple,t8112") { return Ok(&T8112); } - // Only the boards whose ADTs were read: the other T8122 Macs (J433, J434, - // J504) share the SoC but their sensor wiring is unchecked. - if has(b"apple,t8122") && (has(b"apple,j613") || has(b"apple,j615")) { + // Every profile below is SoC facts: the SEP, its DART window and + // handshake, and the SPI controller the SoC wires to the Touch ID + // sensor. They hold on every board with the SoC, as they do for the + // SoCs above. Whether a board has a built-in sensor is not decided here: + // a sensor node the board's device tree describes is used as it is, and + // a board without a sensor (a Mac mini, Studio or iMac) has nothing on + // that bus, so the sensor probe finds no part and the SEP runs without + // biometrics, as on the M1 and M2 Mac minis. + if has(b"apple,t8122") { return Ok(&T8122); } - // The T6040 profile is tested on J614s and J616s. - if has(b"apple,t6040") && (has(b"apple,j616s") || has(b"apple,j614s")) { + if has(b"apple,t6040") { return Ok(&T6040); } - if has(b"apple,t6041") && (has(b"apple,j616c") || has(b"apple,j614c")) { + if has(b"apple,t6041") { return Ok(&T6041); } - if has(b"apple,t6050") - && (has(b"apple,j714s") || has(b"apple,k116s") || has(b"apple,j716c")) - { + if has(b"apple,t6050") { return Ok(&T6050); } - // Only the M4 MacBook Airs: the other T8132 Macs are unread. - if has(b"apple,t8132") && (has(b"apple,j713") || has(b"apple,j715")) { + if has(b"apple,t8132") { return Ok(&T8132); } - // The J815 and the J813, whose ADTs were read: both have the sensor (mesa) on spi2 - // at 0x3a5108000. - if has(b"apple,t8142") && (has(b"apple,j815") || has(b"apple,j813")) { + // The J815 and J813 ADTs have the sensor (mesa) on spi2 at 0x3a5108000. + if has(b"apple,t8142") { return Ok(&T8142); } Err(ENODEV) @@ -732,9 +737,9 @@ mod tests { let cases: [(&[u8], &[u8], bool); 8] = [ (b"apple,t8142", b"apple,j813", true), (b"apple,t8142", b"apple,j815", true), - (b"apple,t8142", b"apple,j814", false), - (b"apple,t8142", b"apple,j704", false), - (b"apple,t8142", b"", false), + (b"apple,t8142", b"apple,j814", true), + (b"apple,t8142", b"apple,j704", true), + (b"apple,t8142", b"", true), (b"", b"apple,j813", false), (b"apple,t8132", b"apple,j813", false), (b"apple,t6050", b"apple,j815", false), @@ -742,11 +747,10 @@ mod tests { for (soc, board, admitted) in cases { let has = |c: &[u8]| c == soc || c == board; let selected = select(&has, &|| &T6020); - if admitted { - assert!(matches!(selected, Ok(profile) if profile.name == T8142.name)); - } else { - assert!(selected.is_err()); - } + assert_eq!( + matches!(selected, Ok(profile) if profile.name == T8142.name), + admitted + ); } } @@ -805,28 +809,34 @@ mod tests { select(&has, &|| &T6020).ok().map(|p| p.name) } + /// The profile follows the SoC compatible alone; the board compatible + /// next to it changes nothing. #[test] - fn t8132_selection_is_limited_to_the_m4_airs() { + fn selection_follows_the_soc() { assert_eq!(picked(&[b"apple,j713", b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,j715", b"apple,t8132"]), Some(T8132.name)); - assert_eq!(picked(&[b"apple,j604", b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,j613", b"apple,t8132"]), None); - assert_eq!(picked(&[b"apple,j713", b"apple,t8122"]), None); + assert_eq!(picked(&[b"apple,j604", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j713", b"apple,t8122"]), Some(T8122.name)); assert_eq!(picked(&[b"apple,j613", b"apple,t8122"]), Some(T8122.name)); + assert_eq!(picked(&[b"apple,j504", b"apple,t8122"]), Some(T8122.name)); assert_eq!(picked(&[b"apple,j700", b"apple,t8140"]), Some(T8140.name)); assert_eq!(picked(&[b"apple,j616s", b"apple,t6040"]), Some(T6040.name)); - assert_eq!(picked(&[b"apple,t6040"]), None); assert_eq!(picked(&[b"apple,j614s", b"apple,t6040"]), Some(T6040.name)); + assert_eq!(picked(&[b"apple,j773s", b"apple,t6040"]), Some(T6040.name)); + assert_eq!(picked(&[b"apple,t6040"]), Some(T6040.name)); assert_eq!(picked(&[b"apple,j616c", b"apple,t6041"]), Some(T6041.name)); assert_eq!(picked(&[b"apple,j614c", b"apple,t6041"]), Some(T6041.name)); - assert_eq!(picked(&[b"apple,t6041"]), None); - assert_eq!(picked(&[b"apple,j713", b"apple,t6041"]), None); + assert_eq!(picked(&[b"apple,j713", b"apple,t6041"]), Some(T6041.name)); assert_eq!(picked(&[b"apple,j714s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,k116s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,j716c", b"apple,t6050"]), Some(T6050.name)); - assert_eq!(picked(&[b"apple,j716c", b"apple,t6041"]), None); - assert_eq!(picked(&[b"apple,t6050"]), None); + assert_eq!(picked(&[b"apple,j716s", b"apple,t6050"]), Some(T6050.name)); + assert_eq!(picked(&[b"apple,j716c", b"apple,t6041"]), Some(T6041.name)); + assert_eq!(picked(&[b"apple,j813", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j704", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j713"]), None); + assert_eq!(picked(&[b"apple,t6002"]), None); } /// Touch ID has one path for every Mac. The retry limits, the lock @@ -837,7 +847,7 @@ mod tests { /// profile naming one of the known Mesa revisions. #[test] fn every_touch_id_mac_gets_a_sensor_the_shared_path_decodes() { - let macs: [&[&[u8]]; 18] = [ + let macs: [&[&[u8]]; 25] = [ &[b"apple,j313", b"apple,t8103"], &[b"apple,j316s", b"apple,t6000"], &[b"apple,j316c", b"apple,t6001"], @@ -850,10 +860,17 @@ mod tests { &[b"apple,j614s", b"apple,t6040"], &[b"apple,j616s", b"apple,t6040"], &[b"apple,j616c", b"apple,t6041"], + &[b"apple,j504", b"apple,t8122"], + &[b"apple,j614c", b"apple,t6041"], &[b"apple,j713", b"apple,t8132"], + &[b"apple,j715", b"apple,t8132"], + &[b"apple,j604", b"apple,t8132"], &[b"apple,j700", b"apple,t8140"], &[b"apple,j714s", b"apple,t6050"], + &[b"apple,j716s", b"apple,t6050"], &[b"apple,j716c", b"apple,t6050"], + &[b"apple,k116s", b"apple,t6050"], + &[b"apple,j704", b"apple,t8142"], &[b"apple,j813", b"apple,t8142"], &[b"apple,j815", b"apple,t8142"], ]; From 4ae8c061c84aa3030c9b563743bfcf75fc1127fe Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 14:37:31 +1100 Subject: [PATCH 0157/1514] soc: apple: sep: leave the SEP off where the board keeps its mailbox disabled With the profile picked by SoC alone, select() now also returns a profile on boards whose device tree describes no usable enclave, and the warm attach then enables the SEP node and its DART at module load. Most device trees leave both disabled for that path, so their status cannot say whether a board has an enclave. The SEP mailbox's status does: the SEP cannot be reached without it, and the device tree enables it (in the board file, or in the SoC .dtsi for every board of that SoC) where the SEP is described for the machine. enable_sep_and_dart() now leaves the SEP and its DART disabled when the mailbox is disabled. From the compiled DTBs of this tree: J773s (T6040), J575c (T6041), and J714c, J716s, J775c, J775d, J873s, K114c, K114s and K116c (T6050) keep the SEP mailbox disabled, so nothing is enabled or bound there. Every board whose mailbox is enabled attaches as before. The selection KUnit test also covers J773g, J815, K114s, J316s and J413, and checks that SoCs without a profile (T6002, T6031, T8152) are refused. Signed-off-by: Ryan Murray --- drivers/soc/apple/dt.rs | 21 +++++++++++++++++++++ drivers/soc/apple/profile.rs | 20 +++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/dt.rs b/drivers/soc/apple/dt.rs index d6f83b55862351..02f68e36ea0ec5 100644 --- a/drivers/soc/apple/dt.rs +++ b/drivers/soc/apple/dt.rs @@ -11,6 +11,7 @@ use kernel::prelude::*; const SEP_COMPATIBLE: &CStr = c"apple,sep"; const IOMMUS_PROP: &CStr = c"iommus"; +const MBOXES_PROP: &CStr = c"mboxes"; const STATUS_PROP: &CStr = c"status"; const STATUS_OKAY: &CStr = c"okay"; @@ -185,6 +186,16 @@ pub(crate) fn preboot_uuid() -> Option<[u8; 16]> { Some(uuid.b) } +/// Enables the SEP and its DART for a warm attach, on boards whose device +/// tree describes a usable enclave. +/// +/// Most device trees leave the SEP node and its DART `disabled` for this +/// function to enable, so their status cannot say whether a board has a +/// usable enclave. The SEP mailbox's status does: the SEP cannot be reached +/// without it, and the device tree enables it (in the board file, or in the +/// SoC .dtsi for every board of that SoC) where the SEP is described for the +/// machine. A board that keeps the mailbox disabled is left untouched and the +/// module probes nothing. pub(crate) fn enable_sep_and_dart(window: &crate::profile::DartWindow) -> Result<()> { let sep = sep_node().ok_or_else(|| { pr_err!( @@ -194,6 +205,16 @@ pub(crate) fn enable_sep_and_dart(window: &crate::profile::DartWindow) -> Result ENODEV })?; + if !sep + .parse_phandle(MBOXES_PROP, 0) + .is_some_and(|mbox| mbox.is_available()) + { + pr_info!( + "apple_sep: the device tree leaves the SEP mailbox disabled on this board; the SEP stays disabled\n" + ); + return Ok(()); + } + let dart = sep.parse_phandle(IOMMUS_PROP, 0).ok_or_else(|| { pr_err!( "apple_sep: SEP node has no '{}' phandle; cannot find its DART\n", diff --git a/drivers/soc/apple/profile.rs b/drivers/soc/apple/profile.rs index 92fc7e03777c0c..c3f3630e0b4d35 100644 --- a/drivers/soc/apple/profile.rs +++ b/drivers/soc/apple/profile.rs @@ -703,7 +703,10 @@ fn select( // a sensor node the board's device tree describes is used as it is, and // a board without a sensor (a Mac mini, Studio or iMac) has nothing on // that bus, so the sensor probe finds no part and the SEP runs without - // biometrics, as on the M1 and M2 Mac minis. + // biometrics, as on the M1 and M2 Mac minis. Whether a board has an + // enclave to attach to is the board device tree's call: + // `dt::enable_sep_and_dart` leaves the SEP disabled where the board keeps + // the SEP mailbox disabled. if has(b"apple,t8122") { return Ok(&T8122); } @@ -816,6 +819,8 @@ mod tests { assert_eq!(picked(&[b"apple,j713", b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,j715", b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,j604", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j773g", b"apple,t8132"]), Some(T8132.name)); + assert_eq!(picked(&[b"apple,j613", b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,t8132"]), Some(T8132.name)); assert_eq!(picked(&[b"apple,j713", b"apple,t8122"]), Some(T8122.name)); assert_eq!(picked(&[b"apple,j613", b"apple,t8122"]), Some(T8122.name)); @@ -832,13 +837,26 @@ mod tests { assert_eq!(picked(&[b"apple,k116s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,j716c", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,j716s", b"apple,t6050"]), Some(T6050.name)); + assert_eq!(picked(&[b"apple,k114s", b"apple,t6050"]), Some(T6050.name)); assert_eq!(picked(&[b"apple,j716c", b"apple,t6041"]), Some(T6041.name)); assert_eq!(picked(&[b"apple,j813", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j815", b"apple,t8142"]), Some(T8142.name)); assert_eq!(picked(&[b"apple,j704", b"apple,t8142"]), Some(T8142.name)); + assert_eq!(picked(&[b"apple,j316s", b"apple,t6000"]), Some(T6000.name)); + assert_eq!(picked(&[b"apple,j413", b"apple,t8112"]), Some(T8112.name)); assert_eq!(picked(&[b"apple,j713"]), None); assert_eq!(picked(&[b"apple,t6002"]), None); } + /// SoCs without a profile are still refused, whatever the board. + #[test] + fn unprofiled_socs_are_refused() { + assert_eq!(picked(&[b"apple,j375d", b"apple,t6002"]), None); + assert_eq!(picked(&[b"apple,j514c", b"apple,t6031"]), None); + assert_eq!(picked(&[b"apple,j804", b"apple,t8152"]), None); + assert_eq!(picked(&[]), None); + } + /// Touch ID has one path for every Mac. The retry limits, the lock /// states, the password re-arm and the lift-gated capture read nothing /// from the profile; only the transport underneath (bus, nonce session, From ce650ca27bec6c0998d2533372a5fce17f572a0b Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 18:13:56 -0500 Subject: [PATCH 0158/1514] rtc: macsmc: return 0, not the byte count, from a successful set_time macsmc_rtc_set_time() ends with "return nvmem_cell_write(...)", which returns the number of bytes written (6) on success. rtc_set_time() passes that on, and the NTP sync path (sync_hw_clock() via update_rtc()) treats any non-zero result as a failure and retries: with CONFIG_RTC_SYSTOHC=y every successful write is retried at once, so the PMU's RTC offset cell is rewritten in a loop instead of once per 11 minutes. The offset_in_seconds path and the alarm writes already return 0 on success; do the same here. On J775c (T6050), traced at the sync_hw_clock() decisions: without: 3774 timer re-arms in 60 s, rtc_set_time returning 6, retried every ~0.8 ms inside the write window; with: one write per 658 s (3 in 35 min), 2 retries in all, and the RTC's second at +4 ms from CLOCK_REALTIME at its tick. Signed-off-by: Satya Benson --- drivers/rtc/rtc-macsmc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/rtc/rtc-macsmc.c b/drivers/rtc/rtc-macsmc.c index 690a4a84ff90e5..94852fac217d34 100644 --- a/drivers/rtc/rtc-macsmc.c +++ b/drivers/rtc/rtc-macsmc.c @@ -149,7 +149,8 @@ static int macsmc_rtc_set_time(struct device *dev, struct rtc_time *tm) /* This sets the offset such that the set second begins now */ off = (rtc_tm_to_time64(tm) << RTC_SEC_SHIFT) - ctr; - return nvmem_cell_write(rtc->rtc_offset, &off, RTC_BYTES); + ret = nvmem_cell_write(rtc->rtc_offset, &off, RTC_BYTES); + return ret < 0 ? ret : 0; } From 078f441ec922e0c45de1ae3cefade2244390638a Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 18:13:56 -0500 Subject: [PATCH 0159/1514] power: reset: macsmc-reboot: return 0 from a successful nvmem_cell_set_u8() nvmem_cell_set_u8() returns nvmem_cell_write()'s byte count (1) on success. Its callers test "< 0", except ac_power_mode_store(), whose "if (!ret && new != val)" never logs the "PM setting %02x => %02x" line after a successful change. Return 0 on success, as the rtc-macsmc helpers do. Signed-off-by: Satya Benson --- drivers/power/reset/macsmc-reboot.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/power/reset/macsmc-reboot.c b/drivers/power/reset/macsmc-reboot.c index a2e1422e05bd82..9ad57b9d89d7a5 100644 --- a/drivers/power/reset/macsmc-reboot.c +++ b/drivers/power/reset/macsmc-reboot.c @@ -98,7 +98,9 @@ static int nvmem_cell_get_u8(struct nvmem_cell *cell) static int nvmem_cell_set_u8(struct nvmem_cell *cell, u8 val) { - return nvmem_cell_write(cell, &val, sizeof(val)); + int ret = nvmem_cell_write(cell, &val, sizeof(val)); + + return ret < 0 ? ret : 0; } /* From 518837631c0ef4c9a847c5564aa284ed3b86fe4d Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Sat, 21 Nov 2026 01:19:17 +0000 Subject: [PATCH 0160/1514] soc: apple: sleep: take the radio's PERST# from its own port node The commit stops the radio's port with its PERST# asserted, and took that line from whichever port of the PCIe host had a reset-gpios property. A radio port without one, released by the port's own PERST register as on the J604, then got a sibling port's line: on the J604 the SD card reader's, on port 2, so the commit toggled the reader's reset while stopping the radio. Take the line only from the radio's own port node, device 0 of the host. Signed-off-by: Dylan Ironside --- drivers/soc/apple/sleep.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 87d2c593f4e00e..bd87fe933a49c0 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -58,7 +58,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -7200,11 +7202,16 @@ static void apple_sleep_map_apcie(struct apple_sleep *s) of_node_put(np); } -/* The radio port's PERST# on the AP pins @np, from the ports of the SoC's enabled PCIe host. */ +/* + * The radio port's PERST# on the AP pins @np, from the radio's own port node (device 0) of the + * SoC's enabled PCIe host. A radio port without the line (released by the port's own PERST + * register) has none, whatever its sibling ports carry. + */ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_node *np) { struct device_node *host, *port; struct of_phandle_args args; + int devfn; host = of_parse_phandle(s->dev->of_node, "apple,apcie", 0); if (!host) @@ -7214,8 +7221,10 @@ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_no if (of_parse_phandle_with_args(port, "reset-gpios", "#gpio-cells", 0, &args)) continue; + devfn = of_pci_get_devfn(port); if (args.np == np && args.args_count >= 2 && args.args[0] < s->npins && - !test_bit(args.args[0], s->pins_skip)) { + !test_bit(args.args[0], s->pins_skip) && devfn >= 0 && + PCI_SLOT(devfn) == 0) { s->radio_perst = args.args[0]; s->radio_perst_low = args.args[1] & GPIO_ACTIVE_LOW; } From 3a9590adfbee95db04f7f5118e34e5655f604807 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 12:55:22 +1100 Subject: [PATCH 0161/1514] drm/asahi: g17p: take the firmware DATA base from the bound GPU The g17p_diag_knobs and g17p_fw_peek module parameters, and the e2e power samples, translate fixed G17P firmware DATA LINK addresses with g17p_gfx_link_to_physical(), which adds a hard-coded physical base: the start of the J700 (MacBook Neo, T8140) GFX data segment. The parameters exist on every Mac that loads aurora.ko, so reading them maps and reads that address whatever GPU is bound. On an M2 (G14) reading g17p_diag_knobs oopses in diag_get+0x208, and any other SoC whose firmware data lives elsewhere would read unrelated memory. Publish the base from the bound GPU instead. When a G17P GPU probes, take the start of its fw-data reserved-memory region, which the loader fills with the data segments of both firmware roles, GFX (ADT sgx gfx-data) first, if the region is page aligned and holds the whole 0x134000-byte GFX DATA segment. A J700 boot whose device tree has no fw-data region falls back to the address its loader is known to use, which is the old constant, so the diagnostics keep working there. Withdraw the base on unbind. g17p_gfx_link_to_physical() now returns None while nothing is published or for a LINK address outside the DATA segment, and no caller touches memory then: diag_get still prints the knobs and reports each firmware word as "none (no G17P bound)", and peek_get prints "error: no G17P bound". Fixes: b2e300ad24ad ("drm/asahi: g18: import the G18G (T8152) backend") Closes: https://github.com/aurora-silicon/linux/issues/2627 Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 14 +++++ drivers/gpu/drm/asahi/g18/compat/e2e.rs | 6 +- drivers/gpu/drm/asahi/g18/compat/g17p.rs | 55 +++++++++++++++++-- .../gpu/drm/asahi/g18/compat/timing_buffer.rs | 12 +++- 4 files changed, 76 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2b..0546a854ad02fd 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -330,6 +330,8 @@ impl platform::Driver for AsahiPlatformDriver { // parameter set it; a no-op everywhere else. unsafe { bindings::apple_pmp_agx_activity_release() }; if let Some(gpu) = this.g17.as_ref() { + #[cfg(CONFIG_DRM_ASAHI_G18)] + crate::g18::compat::g17p::g17p_unpublish_gfx_data(); // Driver data is dropped after devres, so CPU control must happen in unbind. gpu.shutdown(); } @@ -599,6 +601,16 @@ impl AsahiPlatformDriver { error ); } + // The G17P firmware DATA diagnostics read only the bound GPU's own data segment. + #[cfg(CONFIG_DRM_ASAHI_G18)] + if cfg.identity.gpu_variant == hw::GpuVariant::P { + let fixed = if cfg.chip_id == hw::t8140::CHIP_ID { + crate::g18::compat::g17p::G17P_J700_GFX_DATA_FIXED + } else { + 0 + }; + crate::g18::compat::g17p::g17p_publish_gfx_data(pdev.as_ref(), fixed); + } Ok(AsahiPlatformDriverData { binding, _device: reg.device().into(), @@ -773,6 +785,8 @@ impl Drop for AsahiPlatformDriverData<'_> { } drop(self.stats.take()); if let Some(gpu) = self.g17.as_ref() { + #[cfg(CONFIG_DRM_ASAHI_G18)] + crate::g18::compat::g17p::g17p_unpublish_gfx_data(); // Also covers failure to allocate platform driver data after the probe body returned. gpu.shutdown(); } diff --git a/drivers/gpu/drm/asahi/g18/compat/e2e.rs b/drivers/gpu/drm/asahi/g18/compat/e2e.rs index d189df3eca289f..4c1b74c1801dd0 100644 --- a/drivers/gpu/drm/asahi/g18/compat/e2e.rs +++ b/drivers/gpu/drm/asahi/g18/compat/e2e.rs @@ -209,7 +209,9 @@ const PAGE: u64 = crate::pgtable::UAT_PGSZ as u64; fn map_power_sources() -> bool { let map_page = |slot: &AtomicPtr, link: u64| -> bool { if !slot.load(Ordering::Acquire).is_null() { return true; } - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link); + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link) else { + return false; + }; // SAFETY: same page as the existing bounded diag_knobs probe; WB // read-only use; retained until module unload. let ptr = unsafe { bindings::memremap(physical & !(PAGE - 1), PAGE as usize, @@ -232,7 +234,7 @@ fn map_power_sources() -> bool { fn read_firmware_word(page: &AtomicPtr, link: u64) -> Option { let base = page.load(Ordering::Acquire); if base.is_null() { return None; } - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link); + let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link)?; let offset = (physical & (PAGE - 1)) as usize; // SAFETY: `base` maps the whole containing page for the module lifetime; // `offset` is 8-aligned (both links are) and below the page size. The diff --git a/drivers/gpu/drm/asahi/g18/compat/g17p.rs b/drivers/gpu/drm/asahi/g18/compat/g17p.rs index c1b26631234776..fb37f009665079 100644 --- a/drivers/gpu/drm/asahi/g18/compat/g17p.rs +++ b/drivers/gpu/drm/asahi/g18/compat/g17p.rs @@ -11,7 +11,7 @@ use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use core::ptr::NonNull; #[cfg(CONFIG_DEV_COREDUMP)] use kernel::{bindings, ffi::c_void}; -use kernel::{addr::PhysicalAddr, prelude::*}; +use kernel::{addr::PhysicalAddr, c_str, device, prelude::*}; use crate::pgtable::{UAT_PGMSK, UAT_PGSZ}; // diagnostic_accounting_clocks names the probe as `pgtable::LiveFirmwareU64Probe`. use crate::g18::compat::g17p as pgtable; @@ -25,12 +25,55 @@ const G17P_GFX_LINK_DATA_BASE: u64 = 0xffff_fc00_0004_c000; const G17P_GFX_LINK_DATA_END: u64 = 0xffff_fc00_0018_0000; -const G17P_GFX_PHYSICAL_DATA_BASE: u64 = 0x0000_0100_01d7_c000; +/// Physical base of the bound G17P GPU's GFX DATA segment, 0 while none is +/// bound. The module parameters that read firmware DATA exist on every Mac. +static G17P_GFX_PHYSICAL_DATA_BASE: AtomicU64 = AtomicU64::new(0); + +/// Where the J700's boot loader places the GFX DATA segment (T8140), for a +/// boot whose device tree has no `fw-data` region. +pub(crate) const G17P_J700_GFX_DATA_FIXED: u64 = 0x0000_0100_01d7_c000; + +/// The `fw-data` region's start, if it holds the whole GFX DATA segment. The +/// region holds the data segments of both firmware roles, GFX (ADT sgx +/// gfx-data) first. +fn g17p_fw_data_start(dev: &device::Device) -> Option { + let resource = dev + .of_node()? + .reserved_mem_region_to_resource_byname(c_str!("fw-data")) + .ok()?; + let start = resource.start(); + if start == 0 + || start & (UAT_PGMSK as u64) != 0 + || resource.size() < G17P_GFX_LINK_DATA_END - G17P_GFX_LINK_DATA_BASE + { + return None; + } + Some(start) +} + +/// Publish the GFX DATA base of a probed G17P GPU: its `fw-data` region, or +/// else `fixed`, the address its boot loader is known to use (0 = none). +pub(crate) fn g17p_publish_gfx_data(dev: &device::Device, fixed: u64) { + let base = g17p_fw_data_start(dev).unwrap_or(fixed); + G17P_GFX_PHYSICAL_DATA_BASE.store(base, Ordering::Release); +} + +/// Withdraw the published GFX DATA base when the G17P GPU is unbound. +pub(crate) fn g17p_unpublish_gfx_data() { + G17P_GFX_PHYSICAL_DATA_BASE.store(0, Ordering::Release); +} /// Translate a GFX firmware LINK address into the physical address the host -/// can map. Same arithmetic the render status-page probes use. -pub(crate) fn g17p_gfx_link_to_physical(link: u64) -> u64 { - G17P_GFX_PHYSICAL_DATA_BASE + (link - G17P_GFX_LINK_DATA_BASE) +/// can map. Same arithmetic the render status-page probes use. None while no +/// G17P GPU is bound or for a LINK address outside the DATA segment. +pub(crate) fn g17p_gfx_link_to_physical(link: u64) -> Option { + if !(G17P_GFX_LINK_DATA_BASE..G17P_GFX_LINK_DATA_END).contains(&link) { + return None; + } + match G17P_GFX_PHYSICAL_DATA_BASE.load(Ordering::Acquire) { + 0 => None, + base => Some(base + (link - G17P_GFX_LINK_DATA_BASE)), + } } fn g17p_binding_row_address(base: u64, id: u32, stride: u64) -> Option { @@ -55,7 +98,7 @@ pub(crate) fn diagnostic_accounting_clocks() -> Result<[u64; 8]> { let read = |index: usize| -> Result { let link = 0xffff_fc00_0000_0000u64.checked_add(OFFSETS[index]).ok_or(EOVERFLOW)?; let start = g17p_binding_row_address(link, 0, 8).ok_or(EINVAL)?; - pgtable::LiveFirmwareU64Probe::new(g17p_gfx_link_to_physical(start)) + pgtable::LiveFirmwareU64Probe::new(g17p_gfx_link_to_physical(start).ok_or(ENODEV)?) .and_then(|probe| probe.observe_mask(u64::MAX, 1)) .map(|sample| sample.first) }; diff --git a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs index 98a6c23df9670e..f378116ca5ecfc 100644 --- a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs +++ b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs @@ -395,8 +395,11 @@ unsafe extern "C" fn diag_get(buf: *mut core::ffi::c_char, // 177838 idle-off policy (RegionC+0x30 copy), 128a68 keep-on bits. for (name, link) in [("powerups", 0xffff_fc00_0012_4ba0u64), ("state", 0xffff_fc00_0017_71f8), ("idleoff", 0xffff_fc00_0017_7838), ("keepon", 0xffff_fc00_0012_8a68)] { - let value = crate::g18::compat::g17p::LiveFirmwareU64Probe::new( - crate::g18::compat::g17p::g17p_gfx_link_to_physical(link)) + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link) else { + let _ = writeln!(out, "{} none (no G17P bound)", name); + continue; + }; + let value = crate::g18::compat::g17p::LiveFirmwareU64Probe::new(physical) .and_then(|probe| probe.observe_mask(u64::MAX, 1)) .map(|sample| sample.first); let _ = writeln!(out, "{} {:x?}", name, value); @@ -437,7 +440,10 @@ unsafe extern "C" fn peek_get(buf: *mut core::ffi::c_char, let address = PEEK_ADDR.load(Ordering::Relaxed); if address < PEEK_DATA_START { return 0; } let page = crate::pgtable::UAT_PGSZ as u64; - let physical = crate::g18::compat::g17p::g17p_gfx_link_to_physical(address); + let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(address) else { + let _ = writeln!(out, "error: no G17P bound"); + return out.used as core::ffi::c_int; + }; let room = ((page - (physical & (page - 1))) / 8).min(64) as usize; let room = room.min(((PEEK_DATA_END - address) / 8) as usize); let mut values = [0u64; 64]; From 604194261dd6448f3bb33e29b7337119d32d0001 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 13:11:11 +1100 Subject: [PATCH 0162/1514] arm64: dts: apple: t8132-j713-j715: enable WLAN wake The BCM4388 in the M4 MacBook Airs wakes the host the way it does in the 15-inch M3 Air: brcmfmac arms the PCIe endpoint's MSI as the wake interrupt, and only when the WLAN node is a wakeup source. The J713's node is not one, so a magic packet cannot end s2idle even with WoWLAN enabled. Mark the node as a wakeup source, as t8112-j413/j415 and t8122-j615 already do. The board also routes a WLAN WAKE# line to AP GPIO 16, as the J615 does; it is left undescribed here, like on the J615. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi index 98aa89e1ecc77c..691408046b0233 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi @@ -53,6 +53,7 @@ /* The radio's firmware island: the J713's here, the J715 overrides it. */ &wifi0 { brcm,board-type = "apple,garden"; + wakeup-source; }; &bluetooth0 { From b5f37f8d53bf3a3414a93b7b8edda70f77f61497 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 15:22:01 +1100 Subject: [PATCH 0163/1514] wifi: brcmfmac: sleep without WoWLAN when only s2idle can wake On the Apple laptops brcmfmac arms the PCIe endpoint's MSI as the Wake-on-WLAN interrupt when the WLAN node is a DT wakeup source. That MSI can only wake the host while the link stays up, so the PCIe suspend callback refuses every system sleep other than suspend-to-idle with -EOPNOTSUPP once WoWLAN is configured. With magic-packet WoWLAN enabled, as user space does by default, that refusal fails the whole suspend-to-RAM (and hibernation) attempt. Mark such a bus as s2idle-only and, in the cfg80211 suspend callback, handle any other target like a suspend without WoWLAN: leave the network and let the firmware power down. Suspend-to-idle keeps WoWLAN as before. The PCIe refusal stays as a guard. Signed-off-by: Ryan Murray --- .../net/wireless/broadcom/brcm80211/brcmfmac/bus.h | 3 +++ .../wireless/broadcom/brcm80211/brcmfmac/cfg80211.c | 12 ++++++++++++ .../net/wireless/broadcom/brcm80211/brcmfmac/pcie.c | 2 ++ 3 files changed, 17 insertions(+) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h index 840f81ff6c7ff2..4a0148d6aed04d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/bus.h @@ -165,6 +165,8 @@ struct brcmf_bus_stats { * @always_use_fws_queue: bus wants use queue also when fwsignal is inactive. * @wowl_transport: bus can keep the firmware running during system sleep. * @wowl_wake: platform can route a wake signal from the device. + * @wowl_s2idle_only: the wake signal only works while the link stays up (in-band + * MSI): there is no WoWLAN in a system sleep deeper than suspend-to-idle. * @ops: callbacks for this bus instance. * @msgbuf: msgbuf protocol parameters provided by bus layer. * @list: member used to add this bus instance to linked list. @@ -187,6 +189,7 @@ struct brcmf_bus { bool always_use_fws_queue; bool wowl_transport; bool wowl_wake; + bool wowl_s2idle_only; bool removing; /* device removal in progress; quiesce async work */ struct mutex bus_reset_lock; diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c index eac1261258c45d..ac8e58be31690b 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -5264,6 +5265,17 @@ static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy, if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) brcmf_abort_scanning(cfg); + /* An in-band MSI cannot wake the host once the link goes down, so a + * deeper sleep than suspend-to-idle leaves the network, as without + * WoWLAN, instead of failing the whole system suspend. + */ + if (wowl && cfg->pub->bus_if->wowl_s2idle_only && + pm_suspend_target_state != PM_SUSPEND_TO_IDLE) { + bphy_info_once(cfg->pub, + "WoWLAN wakes only from suspend-to-idle here, sleeping without it\n"); + wowl = NULL; + } + if (wowl == NULL) { brcmf_bus_wowl_config(cfg->pub->bus_if, false); list_for_each_entry(vif, &cfg->vif_list, list) { diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 2bfee245f43312..b53a413d73d393 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1320,6 +1320,7 @@ static int brcmf_pcie_request_irq(struct brcmf_pciedev_info *devinfo) } devinfo->wowl_irq = true; bus->wowl_wake = true; + bus->wowl_s2idle_only = true; } devinfo->irq_allocated = true; return 0; @@ -1351,6 +1352,7 @@ static void brcmf_pcie_release_irq(struct brcmf_pciedev_info *devinfo) devinfo->wakeup_created = false; } devinfo->wowl_irq = false; + bus->wowl_s2idle_only = false; brcmf_pcie_intr_disable(devinfo); free_irq(pdev->irq, devinfo); pci_disable_msi(pdev); From b8c76132e5cf6715859de3363369fc05edc6b41e Mon Sep 17 00:00:00 2001 From: Kazuhide Takahashi Date: Sat, 21 Nov 2026 13:25:45 +0900 Subject: [PATCH 0164/1514] arm64: configs: asahi: enable Bluetooth RFCOMM, BNEP and LE Merged over the ARM64 defconfig, asahi.config builds Bluetooth without RFCOMM, without BNEP and with CONFIG_BT_LE off. The defconfig does not set RFCOMM or BNEP and sets "# CONFIG_BT_LE is not set", and nothing in asahi.config turns them back on. Without RFCOMM, bluetoothd cannot set up HFP/HSP. A headset that offers HFP fails to connect: bluetoothd logs Unable to connect Hands-Free Voice gateway: socket(STREAM, RFCOMM): Protocol not supported (93) and the link drops about two seconds later, so A2DP does not come up either. Without LE, BLE devices and LE pairing are unavailable. Enable RFCOMM (with the TTY layer), BNEP (with its filters) and the LE features. They are all modules or features of the bluetooth module (CONFIG_BT=m), so the kernel image is unchanged. Signed-off-by: Kazuhide Takahashi --- arch/arm64/configs/asahi.config | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index 3173021d4f19d8..9cc1cc362265b1 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -20,6 +20,14 @@ CONFIG_THERMAL_GOV_POWER_ALLOCATOR=y # CONFIG_THERMAL_DEFAULT_GOV_STEP_WISE is not set CONFIG_THERMAL_DEFAULT_GOV_POWER_ALLOCATOR=y CONFIG_BT_BRCMEXT=y +# Classic Bluetooth headsets need RFCOMM for HFP/HSP, and the LE features are +# needed for BLE devices and LE pairing; the ARM64 defconfig leaves them out. +CONFIG_BT_RFCOMM=m +CONFIG_BT_RFCOMM_TTY=y +CONFIG_BT_BNEP=m +CONFIG_BT_BNEP_MC_FILTER=y +CONFIG_BT_BNEP_PROTO_FILTER=y +CONFIG_BT_LE=y CONFIG_BT_HCIBCM4377=m CONFIG_BT_MTK7932_PCIE=m CONFIG_BT_CENTAURI=m From 00ef86dba90ca74638c67b052bf487632788032a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 16:04:11 +1100 Subject: [PATCH 0165/1514] arm64: dts: apple: t6030-j514s: route the speaker amp fault IRQ to pin 195 The six speaker amps on the J514s (14-inch MacBook Pro, M3 Pro) inherit pinctrl_ap 29 as their fault interrupt from t603x-j514-j516.dtsi. That is the M3 Max routing. On the J514s the device tree the bootloader passes in places the audio-speaker interrupt on gpio0 pin 0xc3 (195), on the same controller whose pin 171 (0xab) drives the amps' shutdown line in this file. As a result, over-temperature and over-current fault reports from the amps never reach Linux. Point all six amps' interrupts-extended at pinctrl_ap 195. Shutdown, reset and the rest of the amp setup are unchanged. Reported-by: knalekar <53238848+knalekar@users.noreply.github.com> Link: https://github.com/aurora-silicon/linux/issues/2443 Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6030-j514s.dts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6030-j514s.dts b/arch/arm64/boot/dts/apple/t6030-j514s.dts index 1ccf2f1294d6b3..4f5826b44e2080 100644 --- a/arch/arm64/boot/dts/apple/t6030-j514s.dts +++ b/arch/arm64/boot/dts/apple/t6030-j514s.dts @@ -43,32 +43,32 @@ &speaker_left_tweet { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &speaker_left_woof1 { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &speaker_left_woof2 { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &speaker_right_tweet { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &speaker_right_woof1 { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &speaker_right_woof2 { shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; }; &jack_codec { From 67b0890bd3081e1006311a09c70016c5d43a1940 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 17:38:51 +1100 Subject: [PATCH 0166/1514] arm64: dts: apple: t8122-j613-j615: describe the Touch ID data-ready line The J613/J615 Mesa sensor raises its data-ready line on AP GPIO 199. The ADT's /arm-io/spi2/mesa node gives it as interrupts = <199 3> on gpio0, the same encoding as J713 (199) and J616c (116), whose device trees describe it as IRQ_TYPE_EDGE_RISING and capture on the interrupt. Without the line the driver polls the SPI status every 2 ms while a capture is armed. On a J615 waiting for a finger that is about 1450 spi2 interrupts a second; with the line described it is 16 a second, the 250 ms status backstop. Describe the line so the J613/J615 capture is interrupt driven like the other Mesa sensors, and update the T8122 SEP device tree test. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi | 4 +++- tools/aurora-sep/tests/test_t8122_sep.py | 9 +++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index dbb9da8d4e36b3..9359b01f4e0bb1 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -115,7 +115,7 @@ apple,temporal-filter = <1>; }; -/* Touch ID; its data-ready line (AP GPIO 199) is left out, so it polls. */ +/* Touch ID */ &spi2 { status = "okay"; }; @@ -123,6 +123,8 @@ &mesa { status = "okay"; enable-gpios = <&pinctrl_nub 29 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <199 IRQ_TYPE_EDGE_RISING>; spi-cs-setup-delay-ns = <20>; spi-cs-hold-delay-ns = <20>; }; diff --git a/tools/aurora-sep/tests/test_t8122_sep.py b/tools/aurora-sep/tests/test_t8122_sep.py index f1588a962091cc..986e2d8c357107 100644 --- a/tools/aurora-sep/tests/test_t8122_sep.py +++ b/tools/aurora-sep/tests/test_t8122_sep.py @@ -22,9 +22,12 @@ BUS = "/soc/spi@2a1108000" SENSOR = BUS + "/fingerprint@0" PINCTRL_NUB = "/soc/pinctrl@2e41f0000" +PINCTRL_AP = "/soc/pinctrl@2c7100000" MBOX = "/soc/mbox@29e408000" # AIC_IRQ cells: , IRQ_TYPE_LEVEL_HIGH = 4. LEVEL_HIGH = 4 +# GPIO interrupt cells: , IRQ_TYPE_EDGE_RISING = 1. +EDGE_RISING = 1 @unittest.skipUnless(all(shutil.which(tool) for tool in ("cpp", DTC, "fdtget")), @@ -82,8 +85,10 @@ def test_air_boards_describe_sep_and_sensor(self): properties = self.props(dtb, SENSOR) self.assertIn("spi-cpha", properties) self.assertNotIn("spi-cpol", properties) - self.assertNotIn("interrupts", properties) - self.assertNotIn("interrupts-extended", properties) + # Data-ready on AP GPIO 199, rising edge, as on J713 and J616s. + ap = int(self.prop(dtb, PINCTRL_AP, "phandle")[0], 16) + self.assertEqual(self.cells(dtb, SENSOR, "interrupt-parent"), [ap]) + self.assertEqual(self.cells(dtb, SENSOR, "interrupts"), [199, EDGE_RISING]) self.assertNotIn("cs-gpios", self.props(dtb, BUS)) def cells(self, dtb, node, name): From cf3fae5d99aa0ca5733ce99093d4450cee6d1adb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 18:03:17 +1100 Subject: [PATCH 0167/1514] tools/asahi: brcmf-suspend-tests: model the s2idle-only WoWLAN bus The brcmfmac suspend harness no longer compiled against the driver: struct brcmf_bus gained wowl_s2idle_only and brcmf_cfg80211_suspend() now logs through bphy_info_once(), whose stub referenced a drvr the extracted function does not have. Even the control case failed. Add the field to the stub bus, give bphy_info_once() the driver's argument shape, and cover the new behaviour: with magic-packet WoWLAN on an s2idle-only bus, a deeper sleep target leaves the network as a suspend without WoWLAN does, while suspend-to-idle, or a bus with a real wake line, keeps WoWLAN. A new wowl-s2idle-only mutation, which drops that check, must be killed. Signed-off-by: Ryan Murray --- tools/asahi/brcmf-suspend-tests.py | 23 ++++++++++++++++++++--- tools/asahi/run-host-tests.py | 3 ++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/tools/asahi/brcmf-suspend-tests.py b/tools/asahi/brcmf-suspend-tests.py index e255d1ca0336b0..5d5d934946c33d 100644 --- a/tools/asahi/brcmf-suspend-tests.py +++ b/tools/asahi/brcmf-suspend-tests.py @@ -43,7 +43,7 @@ def function(source, name): #define smp_load_acquire(p) (*(p)) #define brcmf_dbg(...) ((void)0) #define bphy_err(...) ((void)drvr) -#define bphy_info_once(...) ((void)drvr) +#define bphy_info_once(d, ...) ((void)(d)) #define brcmf_info(...) ((void)0) #define brcmf_err(...) ((void)0) #define __brcmf_err(...) ((void)0) @@ -72,6 +72,7 @@ def function(source, name): struct { int intmask, mailboxmask; } *reginfo; }; struct pcie_priv { struct brcmf_pciedev_info *devinfo; }; struct brcmf_bus { enum brcmf_bus_state state; struct brcmf_pub *drvr; bool wowl_transport, wowl_wake; + bool wowl_s2idle_only; struct { struct pcie_priv *pcie; } bus_priv; }; struct brcmf_proto { void *pd; }; struct brcmf_pub { struct brcmf_bus *bus_if; struct brcmf_if *iflist[BRCMF_MAX_IFS]; @@ -219,7 +220,8 @@ def function(source, name): static void brcmf_fweh_unregister(struct brcmf_pub *p,int e) {(void)p;(void)e;} #define brcmf_fweh_register(p,e,f) ((void)(p),(void)(e)) static void brcmf_abort_scanning(struct brcmf_cfg80211_info *c) {(void)c;can_command();} -static void brcmf_bus_wowl_config(struct brcmf_bus *b,bool e) {(void)b;(void)e;} +static unsigned wowl_offs; +static void brcmf_bus_wowl_config(struct brcmf_bus *b,bool e) {(void)b;if(!e)wowl_offs++;} static void brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();} static void brcmf_delay(int t) {(void)t;} static void brcmf_set_mpc(struct brcmf_if *i,int v) {(void)i;(void)v;can_command();} @@ -351,6 +353,18 @@ def function(source, name): assert(msgbuf.flowring_work.queued && msgbuf.txflow_work.queued); assert(!d0_informs && !removes && !probes);cases++; } + /* WoWLAN over an in-band MSI only wakes from s2idle: a deeper target sleeps + * as without WoWLAN (network left, WoWLAN off on the bus) instead of + * failing the suspend; s2idle, and a bus with a real wake line, keep it. */ + for(int only=0;only<2;only++)for(int deep=0;deep<2;deep++) { + static struct cfg80211_wowlan magic={.magic_pkt=true}; + reset();vif_up=true;wowl_offs=0;bus.wowl_s2idle_only=only; + pm_suspend_target_state=deep?PM_SUSPEND_ON:PM_SUSPEND_TO_IDLE; + int ret=brcmf_cfg80211_suspend(&wiphy,&magic); + if(only&&deep)assert(!ret && cfg.suspended && wowl_offs==1); + else assert(ret==1 && !cfg.suspended && !wowl_offs); + cases++; + } /* Outside s2idle (hibernation) Apple firmware still gets the D3 handshake. */ reset();devinfo.fwseed=true;pm_suspend_target_state=PM_SUSPEND_ON; assert(!brcmf_pcie_pm_enter_D3(&device) && d3_informs==1 && !devinfo.s2idle_d0); @@ -373,7 +387,7 @@ def main(): parser.add_argument('--out', type=Path) parser.add_argument('--mutation', choices=['country-gate', 'queue-reasons', 'worker-gate', 'resume-order', 'tx-drain', 'lpas-resume', - 's2idle-d3']) + 's2idle-d3', 'wowl-s2idle-only']) args = parser.parse_args() sources = {name: (DRIVER / (name + '.c')).read_text() for name in ('cfg80211', 'core', 'pcie', 'msgbuf')} @@ -407,6 +421,9 @@ def main(): elif args.mutation == 's2idle-d3': body = body.replace('if (devinfo->fwseed && pm_suspend_target_state == PM_SUSPEND_TO_IDLE)', 'if (false)') + elif args.mutation == 'wowl-s2idle-only': + body = body.replace('if (wowl && cfg->pub->bus_if->wowl_s2idle_only &&\n\t pm_suspend_target_state != PM_SUSPEND_TO_IDLE)', + 'if (false)') elif args.mutation == 'tx-drain': body = body.replace('netif_tx_disable(ifp->ndev);', '(void)ifp;') code = PREFIX.replace('/* STOP_REASONS */', reasons) + CALLBACK_STUBS + body + MAIN diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 350e45f0d663e1..4515173b0c67f5 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -160,7 +160,8 @@ def mutations(flag, names, base, expect=KILL): + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], 'brcmf-suspend-tests.py': [(out(), PASS)] + mutations('--mutation', ('country-gate', 'queue-reasons', 'worker-gate', - 'resume-order', 'tx-drain', 'lpas-resume'), out()), + 'resume-order', 'tx-drain', 'lpas-resume', + 'wowl-s2idle-only'), out()), 'brcmf-wowl-filter-tests.py': [(out(), PASS)] + mutations('--mutation', ('base-order', 'mask-last', 'totsize', 'no-track'), out()), 'brcmfmac-scan-timeout-tests.py': [(out('--output'), PASS)], From c927146f266e0e365633bb1b0b7cab0469a35891 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 04:16:04 -0500 Subject: [PATCH 0168/1514] selftests: asahi-m4: Remove the suite's own output after a clean run Run without --output or ASAHI_M4_OUTPUT, the asahi-m4 host suite made a fresh asahi-m4-suite-* directory in the default temporary directory and never removed it. Each run left about 80 MB behind, and where /tmp is a RAM-backed tmpfs that is memory, not disk. Put the suite's own output under $TMPDIR when the caller sets one (the umbrella tools/asahi runner does), else under the kernel tree's hidden .asahi-m4-suite/, and remove it when every test passed. A failed run keeps it and prints where. Each test's own temporary files now go in its output directory, so they leave with it. An output directory the caller names is kept as before. Signed-off-by: Diljit Singh --- .../drivers/gpu/asahi-m4/run-host-tests.py | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py b/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py index ca3b57018a8ea3..37e1382a3230a5 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/run-host-tests.py @@ -29,8 +29,16 @@ def main(): print(f'1..0 # SKIP missing host prerequisite: {variable}={executable}') return 4 verify_fixtures() - output = args.output or (Path(os.environ['ASAHI_M4_OUTPUT']) if os.environ.get('ASAHI_M4_OUTPUT') - else Path(tempfile.mkdtemp(prefix='asahi-m4-suite-'))) + # With no output directory given, the suite makes its own and removes it when every test + # passed. It goes under $TMPDIR when the caller set one (the umbrella runner does), else + # under the kernel tree's hidden .asahi-m4-suite/, never in a RAM-backed /tmp by default. + owned = not args.output and not os.environ.get('ASAHI_M4_OUTPUT') + if owned: + parent = Path(os.environ['TMPDIR']) if os.environ.get('TMPDIR') else root / '.asahi-m4-suite' + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix='asahi-m4-suite-', dir=parent)) + else: + output = args.output or Path(os.environ['ASAHI_M4_OUTPUT']) output = output.resolve() output.mkdir(parents=True, exist_ok=True) tests = sorted(HERE.glob('test-*.py')) @@ -44,6 +52,9 @@ def main(): environment['ASAHI_M4_OUTPUT'] = str(directory) environment['ASAHI_M4_KERNEL'] = str(root) environment['PYTHONDONTWRITEBYTECODE'] = '1' + # A test's own temporary files live in its output directory and go with it. + (directory / 'tmp').mkdir(exist_ok=True) + environment['TMPDIR'] = str(directory / 'tmp') command = [sys.executable, str(test)] # Resource allocator predates the shared output environment option. if test.name == 'test-resources.py': @@ -68,7 +79,11 @@ def main(): report = {'cpu_only': True, 'hardware_execution': False, 'passed': all(x['returncode'] in (0, 4) for x in results), 'kernel_source': str(root), 'fixture_manifest_sha256': sha(HERE / 'fixtures/manifest.json'), 'tests': results} (output / 'host-tests.json').write_text(json.dumps(report, indent=2)+'\n') - print('# Results: ' + str(output / 'host-tests.json'), flush=True) + if owned and report['passed']: + shutil.rmtree(output) + print('# All passed; removed ' + str(output), flush=True) + else: + print('# Results: ' + str(output / 'host-tests.json'), flush=True) return 0 if report['passed'] else 1 From 2eb9771ea2a24cb0fe06a29536f5094f6da22d4a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:29:39 +1100 Subject: [PATCH 0169/1514] arm64: dts: apple: t8132: keep the USB4 router DARTs out of the router's power state Since the USB4 NHI DARTs were given power-domains = <&ps_atcN_cio>, every deep sleep of an M4 MacBook Air with a USB4 partner attached hangs: the DART, a supplier of the NHI, suspends after the NHI's noirq suspend, so the native CIO sleep, which powers the router's states off from that noirq suspend, finds ATCN_CIO still held on, unwinds, and fails again in its recovery. The SoC watchdog then resets the machine. The DART does not need the state named: the router populates it only after powering its own states, and the native CIO sleep saves and restores it across their power cycle. Drop the property again on both routers and say why. Fixes: 202ede05e539 ("arm64: dts: apple: t8122/t8132/t603x: give the remaining DARTs their power domains") Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-usb4.dtsi | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-usb4.dtsi b/arch/arm64/boot/dts/apple/t8132-usb4.dtsi index be35c15c9e9ba0..7a800738401f8f 100644 --- a/arch/arm64/boot/dts/apple/t8132-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-usb4.dtsi @@ -77,13 +77,18 @@ nonposted-mmio; status = "disabled"; + /* + * No power-domains: the router populates its DART after it has powered + * its own states, and the native CIO sleep powers them off with the DART + * saved. A DART in ps_atc0_cio would hold that state on through the + * NHI's noirq suspend (it suspends after the NHI), and the sleep fails. + */ usb4_0_dart: iommu@a80000 { compatible = "apple,t8132-dart", "apple,t8110-dart"; reg = <0xa80000 0x20000>; interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <5>; - power-domains = <&ps_atc0_cio>; }; usb4_0_nhi: nhi@f00000 { @@ -194,13 +199,18 @@ nonposted-mmio; status = "disabled"; + /* + * No power-domains: the router populates its DART after it has powered + * its own states, and the native CIO sleep powers them off with the DART + * saved. A DART in ps_atc1_cio would hold that state on through the + * NHI's noirq suspend (it suspends after the NHI), and the sleep fails. + */ usb4_1_dart: iommu@a80000 { compatible = "apple,t8132-dart", "apple,t8110-dart"; reg = <0xa80000 0x20000>; interrupt-parent = <&aic>; interrupts = ; #iommu-cells = <5>; - power-domains = <&ps_atc1_cio>; }; usb4_1_nhi: nhi@f00000 { From 23f33fc765c0f49e21241433c27cc61242b0af02 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 06:29:45 -0500 Subject: [PATCH 0170/1514] dt-bindings: soc: apple: document the AOP setup boot selector Describe when the setup mailbox must be listed and what its omission means for the firmware boot protocol. Signed-off-by: Satya Benson --- .../devicetree/bindings/soc/apple/apple,t8152-aop.yaml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml index 624e29d66f2cf3..bf23db0f389207 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8152-aop.yaml @@ -12,9 +12,9 @@ maintainers: description: The Always-On Processor on T8142, T8152 and T6050 runs firmware that the boot loader loads and leaves halted. It owns the audio and sensor services. - The host boots it over its RTKit mailbox, on T8142 together with a - separate setup-port mailbox, and shares buffers through one stream of the - AOP DART. + The host boots it over its RTKit mailbox, using a separate setup-port + mailbox when the firmware's boot protocol requires it, and shares buffers + through one stream of the AOP DART. properties: compatible: @@ -43,6 +43,9 @@ properties: - description: Firmware setup-port transport mbox-names: + description: + Include setup when the firmware uses the setup-port boot protocol. + Omitting setup selects boot over the primary RTKit mailbox alone. minItems: 1 items: - const: mbox From 46ff84f8d7e5c304ac8e9d777c4dcc5e1f5072fe Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:40:27 +1100 Subject: [PATCH 0171/1514] drm/apple: Offer internal-panel HDR only on panels with EDR headroom Every internal panel on firmware 27 (and desktop 26.x) got a Colorspace and HDR_OUTPUT_METADATA property, and on firmware 27 a peak from the ADT's LmaxProduct, which also put PQ into the panel's EDID-equivalent metadata. The choice was made by firmware version alone, so an SDR panel such as the M4 Air's (525 nit LmaxProduct, no EDR headroom) showed an HDR switch in the desktop and could be driven into EDR it does not have. Take the decision from the machine instead: the ADT backlight node of an XDR panel carries EDRPotentialHeadroom above 1.0 (16.0 on the M1 Pro and M4 Pro), an SDR panel has none. The panel's EDR ceiling is now read on every firmware, and a panel without one gets no peak (neither from the ADT nor from res_max_panel_brightness()), no PQ metadata and no HDR connector properties. The firmware check stays only for what it really describes, the swap interface the EDR path is written for (dcp_fw_swap_has_edr()). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 8 ++++---- drivers/gpu/drm/apple/dcp-edr.h | 3 ++- drivers/gpu/drm/apple/dcp-internal.h | 16 ++++++++++++++-- drivers/gpu/drm/apple/dcp.c | 25 ++++++++++++++++++------- drivers/gpu/drm/apple/dcp.h | 2 +- drivers/gpu/drm/apple/iomfb.c | 10 +++++----- drivers/gpu/drm/apple/iomfb_template.c | 8 ++++++-- 7 files changed, 50 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index b6ec46a7902590..c88d920c59bba7 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -982,8 +982,9 @@ static int apple_connector_attach_pq_reference(struct drm_connector *connector) /* * External displays can take a PQ BT.2020 signal where the firmware - * offers one, and a desktop 26.x panel PQ content it shows as EDR; - * dcp_crtc_atomic_check() refuses it elsewhere. + * offers one, and an internal panel with EDR headroom PQ content it shows + * as EDR (dcp_panel_edr()); dcp_crtc_atomic_check() refuses it elsewhere. + * An SDR panel offers no HDR at all. */ static int apple_connector_attach_hdr(struct drm_connector *connector, bool panel_edr) @@ -1057,8 +1058,7 @@ static int apple_connector_create(struct drm_device *drm, ret = drm_connector_attach_vrr_capable_property(&connector->base); if (ret) goto err_cleanup; - ret = apple_connector_attach_hdr(&connector->base, - dcp_fw_compat_panel_edr(dcp)); + ret = apple_connector_attach_hdr(&connector->base, dcp_panel_edr(dcp)); if (ret) goto err_cleanup; diff --git a/drivers/gpu/drm/apple/dcp-edr.h b/drivers/gpu/drm/apple/dcp-edr.h index 0bfb0bf72660db..c5ec2d763f6318 100644 --- a/drivers/gpu/drm/apple/dcp-edr.h +++ b/drivers/gpu/drm/apple/dcp-edr.h @@ -35,7 +35,8 @@ /* * The panel's potential headroom, the ADT backlight node's * EDRPotentialHeadroom (16.16), as a ceiling x1000. macOS never gives the - * panel more. 0: no ceiling, for a value that is missing or not above 1.0. + * panel more. 0: the panel has no EDR headroom (a value missing or not + * above 1.0); dcp_edr_target() then takes the peak alone. */ static inline u32 dcp_edr_ceiling(u32 fixed) { diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index e5dd066b69e804..1ff6fc07742d1f 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -220,9 +220,9 @@ struct dcp_panel { int height_mm; /// panel has a mini-LED backlight bool has_mini_led; - /// peak panel luminance in nits, for EDR (desktop 26.x; 0 if unknown) + /// peak panel luminance in nits, for EDR (0 if unknown or no EDR headroom) u32 peak_nits; - /// EDR headroom ceiling x1000 from the ADT (desktop 26.x; 0 if none) + /// EDR headroom ceiling x1000 from the ADT (0: the panel has no EDR headroom) u32 edr_ceiling; /// calibrated colour target from the raw ADT; NULL if not given const struct dcp_color_space *color_target; @@ -1296,6 +1296,18 @@ static inline void dcp_takeover_adopt_proven(struct apple_dcp *dcp) WRITE_ONCE(dcp->desktop->takeover_adopted, false); } +/* + * Firmware interfaces whose swaps carry EDR, i.e. that the driver's EDR path + * implements (dcp_edr_prepare()): desktop 26.x and firmware 27. This is the + * interface ABI, not the panel: whether a panel has EDR headroom comes from + * its ADT (dcp_panel_edr()). + */ +static inline bool dcp_fw_swap_has_edr(struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || + dcp->fw_compat == DCP_FIRMWARE_V_27_0; +} + static inline bool dcp_vrr_live(struct apple_dcp *dcp) { return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->main_display && diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 7d0dc3acaae688..3f48efc95333a9 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1293,14 +1293,20 @@ static void dcp_panel_read_adt(struct apple_dcp *dcp) if (dcp->panel_identity) dcp->panel_identity->adt = panel.identity; dcp->panel.color_target = ret ? NULL : dcp_panel_gamut_color_space(panel.gamut); - if (desktop || dcp->fw_compat == DCP_FIRMWARE_V_27_0) - dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); + /* + * Whether the panel has EDR headroom at all is the machine's to say: an + * XDR panel's backlight node carries EDRPotentialHeadroom above 1.0 + * (16.0 on the M1 Pro and M4 Pro XDR panels), an SDR panel such as the + * M3/M4 Air's has none. Without it the panel gets no peak, so it shows + * no PQ content as EDR and offers userspace no HDR (dcp_panel_edr()). + */ + dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); /* * Firmware 27 reports no peak (desktop 26.x: res_max_panel_brightness()). * The ADT's LmaxProduct gives it (1600 nits on the M5 Pro). Only a peak * above the SDR range gives headroom. */ - if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) { + if (dcp->panel.edr_ceiling && dcp->fw_compat == DCP_FIRMWARE_V_27_0) { u32 peak = panel.lmax_product >> 16; if (peak > dcp->brightness.maximum && peak <= 10000) { @@ -4107,13 +4113,18 @@ bool dcp_fw_compat_is_desktop(struct platform_device *pdev) return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; } -/* Firmware whose panel shows PQ content as EDR (dcp_panel_edr_supported()). */ -bool dcp_fw_compat_panel_edr(struct platform_device *pdev) +/* + * Whether @pdev's internal panel can show PQ content as EDR: the panel has + * EDR headroom (the ADT's EDRPotentialHeadroom, see dcp_panel_read_adt()), + * and the firmware interface is one whose swaps carry EDR, which the driver + * implements for desktop 26.x and firmware 27 (dcp_panel_edr_supported()). + */ +bool dcp_panel_edr(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0; + return dcp_fw_swap_has_edr(dcp) && dcp_has_panel(dcp) && + dcp->panel.edr_ceiling; } bool dcp_fw_compat_is_14_7(struct platform_device *pdev) diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f1d0f49026d601..b7beac2805100a 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -90,7 +90,7 @@ int dcp_get_connector_type(struct platform_device *pdev); bool dcp_fw_compat_is_12_x(struct platform_device *pdev); bool dcp_fw_compat_is_14_7(struct platform_device *pdev); bool dcp_fw_compat_is_desktop(struct platform_device *pdev); -bool dcp_fw_compat_panel_edr(struct platform_device *pdev); +bool dcp_panel_edr(struct platform_device *pdev); unsigned int dcp_gamma_lut_size(struct platform_device *pdev); /* T6041 external display processors may join the DRM device. */ bool dcp_t6041_ext_enabled(void); diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index b01746bdb09b10..1d7009fa1cfb0e 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3194,14 +3194,14 @@ static bool dcp_hdr_output_supported(struct apple_dcp *dcp) } /* - * A desktop 26.x or firmware 27 panel keeps its SDR link and shows PQ - * content as EDR, given the panel's peak (see res_max_panel_brightness()). + * A desktop 26.x or firmware 27 panel with EDR headroom (dcp_panel_edr()) + * keeps its SDR link and shows PQ content as EDR, given the panel's peak + * (see res_max_panel_brightness()). */ static bool dcp_panel_edr_supported(struct apple_dcp *dcp) { - return (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0) && - dcp_has_panel(dcp) && READ_ONCE(dcp->panel.peak_nits); + return dcp_fw_swap_has_edr(dcp) && dcp_has_panel(dcp) && + dcp->panel.edr_ceiling && READ_ONCE(dcp->panel.peak_nits); } /* The state of the connector on @crtc that @commit sets up. */ diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 13b2fc197e4ec3..24623e2932bc8a 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4706,8 +4706,12 @@ static void res_max_panel_brightness(struct apple_dcp *dcp, void *out, void *coo { u32 peak = out ? get_unaligned_le32(out) >> 16 : 0; - /* Only a peak above the SDR range gives EDR headroom. */ - if (peak > dcp->brightness.maximum && peak <= 10000) { + /* + * Only a panel with EDR headroom (the ADT's EDRPotentialHeadroom) and a + * peak above the SDR range shows PQ content as EDR. + */ + if (dcp->panel.edr_ceiling && peak > dcp->brightness.maximum && + peak <= 10000) { dev_info(dcp->dev, "panel peak luminance %u nits\n", peak); WRITE_ONCE(dcp->panel.peak_nits, peak); } From 10c9d219e2cd0439378d48b136afb0cf58723798 Mon Sep 17 00:00:00 2001 From: Dylan Ironside Date: Sat, 21 Nov 2026 01:19:17 +0000 Subject: [PATCH 0172/1514] soc: apple: sleep: stop the endpoint on port 2 at the commit A deep sleep's commit stops the radio's port 0 in macOS's order (the link into L2, PERST# asserted, the PHY glue's clocks and the port's application clock off) before the APCIe block loses its power. A host that also runs port 2 (the SD card reader on the J604, the Ethernet on the J773g) had the block go down with that link up while the endpoint's own rail stayed on. Stop port 2 the same way when its link is up, with its own PERST#, once per commit with its own flag. Its host trains it again after the wake. Port 2 is mapped only when the host has an enabled pci@2,0 child, so a host that names port2/phy2 without using the port (the T8140's lists ports 0-2, the Neo uses port 0 only) never has its registers read. A port 2 with its link down or never clocked is left as it is. Signed-off-by: Dylan Ironside --- drivers/soc/apple/sleep.c | 88 ++++++++++++++++++++++++++++++++------- 1 file changed, 72 insertions(+), 16 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index bd87fe933a49c0..72b764fe64b44a 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -961,10 +961,14 @@ struct apple_sleep { void __iomem *apcie_phy; void __iomem *apcie_rc; bool apcie_port_stopped; + bool apcie_port2_stopped; /* A real sleep left the radio's port down, until its host sets it up again */ bool apcie_port_down; void __iomem *apcie_port; void __iomem *apcie_port_phy; + /* Port 2 and its PHY glue, when the host has an enabled pci@2,0, or NULL */ + void __iomem *apcie_port2; + void __iomem *apcie_port2_phy; void __iomem *apcie_engine; void __iomem *apcie_fabric; struct apple_tunable *apcie_axi_tunable; @@ -1002,6 +1006,9 @@ struct apple_sleep { /* The radio port's PERST# among them, or -1 */ int radio_perst; bool radio_perst_low; + /* The PERST# of the endpoint on port 2, or -1 */ + int port2_perst; + bool port2_perst_low; bool returned; /* This wake came back down the deep path, not the DRAM-kept one. */ bool deep_ran; @@ -3784,10 +3791,9 @@ EXPORT_SYMBOL_GPL(apple_sleep_debug_link_cut_wake); * the link untouched. A link that's down or a radio that's gone only makes the poll time * out, and the power goes next either way. */ -static void sleep_apcie_port_stop(struct apple_sleep *s) +static void sleep_apcie_port_stop(struct apple_sleep *s, void __iomem *port, + void __iomem *phy, int perst, bool perst_low, bool radio) { - void __iomem *port = s->apcie_port; - void __iomem *phy = s->apcie_port_phy; u32 val; writel(readl(port + APCIE_PORT_INTMSK) | APCIE_PORT_INT_LINK, port + APCIE_PORT_INTMSK); @@ -3800,16 +3806,16 @@ static void sleep_apcie_port_stop(struct apple_sleep *s) readl_poll_timeout_atomic(port + APCIE_PORT_L2, val, !(val & APCIE_PORT_L2_BUSY), 10, APCIE_PORT_STOP_US); } - /* The radio keeps its power and firmware, in reset until its host releases it. */ - if (s->radio_perst >= 0 && sleep_ps_on(s, s->soc->ps.gpio)) { - void __iomem *reg = s->pins + PIN_REG(s->radio_perst); + /* The endpoint keeps its power, in reset until its host releases it. */ + if (perst >= 0 && sleep_ps_on(s, s->soc->ps.gpio)) { + void __iomem *reg = s->pins + PIN_REG(perst); val = readl(reg); - writel(s->radio_perst_low ? val & ~PIN_DATA : val | PIN_DATA, reg); + writel(perst_low ? val & ~PIN_DATA : val | PIN_DATA, reg); } writel(readl(phy) & ~APCIE_PORT_PHY_LINK, phy); - if (s->apcie_engine && s->apcie_fabric) { + if (radio && s->apcie_engine && s->apcie_fabric) { writel(0, s->apcie_engine + APCIE_ENGINE_IRQ_MASK); writel(3, s->apcie_fabric + APCIE_FABRIC_STOP); writel(readl(s->apcie_engine + APCIE_ENGINE_CTRL) | APCIE_ENGINE_STOP, @@ -3833,14 +3839,37 @@ static void sleep_apcie_port_stop(struct apple_sleep *s) writel(readl(port + APCIE_PORT_INTSTAT), port + APCIE_PORT_INTSTAT); } +/* + * The endpoint on port 2, stopped as the radio's port is, so that the block's power doesn't go + * with its link up while the endpoint's own rail stays on. Its host trains it again after the + * wake. Only a host that describes and enables port 2 has it mapped. A port with its link down + * or never clocked is left as it is: the power going takes nothing from it. + */ +static void sleep_apcie_port2_stop_once(struct apple_sleep *s) +{ + void __iomem *port = s->apcie_port2; + + if (s->apcie_port2_stopped || !port || !s->apcie_port2_phy) + return; + s->apcie_port2_stopped = true; + if (!(readl(port + APCIE_PORT_APPCLK) & APCIE_PORT_APPCLK_EN) || + !(readl(port + APCIE_PORT_LINKSTS) & APCIE_PORT_LINKSTS_UP)) + return; + sleep_apcie_port_stop(s, port, s->apcie_port2_phy, s->port2_perst, s->port2_perst_low, + false); +} + static void sleep_apcie_port_stop_once(struct apple_sleep *s) { + if (!sleep_ps_on(s, s->soc->ps.apcie_gp) || !sleep_ps_on(s, s->soc->ps.apcie_phy_sw)) + return; + sleep_apcie_port2_stop_once(s); /* Only with the port set up, by the loader or by its host after a wake, or it aborts. */ - if (s->apcie_port_stopped || s->apcie_port_down || !s->apcie_port || !s->apcie_port_phy || - !sleep_ps_on(s, s->soc->ps.apcie_gp) || !sleep_ps_on(s, s->soc->ps.apcie_phy_sw)) + if (s->apcie_port_stopped || s->apcie_port_down || !s->apcie_port || !s->apcie_port_phy) return; s->apcie_port_stopped = true; - sleep_apcie_port_stop(s); + sleep_apcie_port_stop(s, s->apcie_port, s->apcie_port_phy, s->radio_perst, + s->radio_perst_low, true); } /* A poll here only paces the steps: the power goes next whatever it reads. */ @@ -6384,6 +6413,7 @@ static int apple_sleep_begin(suspend_state_t state) if (apple_sleep) { apple_sleep->apcie_port_stopped = false; + apple_sleep->apcie_port2_stopped = false; apple_sleep->usb_down_ran = false; apple_sleep->smc_woke_alone = false; sleep_pins_save(apple_sleep); @@ -7147,6 +7177,22 @@ static void __iomem *apple_sleep_apcie_block(struct apple_sleep *s, struct devic return of_iomap(np, idx); } +/* Whether the PCIe host @np describes and enables a port at device @slot (a pci@slot,0 child). */ +static bool apple_sleep_apcie_has_port(struct device_node *np, unsigned int slot) +{ + struct device_node *port; + int devfn; + + for_each_available_child_of_node(np, port) { + devfn = of_pci_get_devfn(port); + if (devfn >= 0 && PCI_SLOT(devfn) == slot) { + of_node_put(port); + return true; + } + } + return false; +} + /* * Its registers go with PCIe's node, which a test tree may have disabled, and a loader * publishes the tunables there. Missing ones only refuse a real sleep with ANS stopped. @@ -7193,6 +7239,10 @@ static void apple_sleep_map_apcie(struct apple_sleep *s) s->apcie_port = apple_sleep_apcie_block(s, np, "port0", NULL, NULL); s->apcie_port_phy = apple_sleep_apcie_block(s, np, "phy0", NULL, NULL); + if (of_device_is_available(np) && apple_sleep_apcie_has_port(np, 2)) { + s->apcie_port2 = apple_sleep_apcie_block(s, np, "port2", NULL, NULL); + s->apcie_port2_phy = apple_sleep_apcie_block(s, np, "phy2", NULL, NULL); + } engine = of_parse_phandle(np, "apple,piodma", 0); if (engine) { s->apcie_engine = apple_sleep_apcie_block(s, engine, "engine", NULL, NULL); @@ -7204,13 +7254,15 @@ static void apple_sleep_map_apcie(struct apple_sleep *s) /* * The radio port's PERST# on the AP pins @np, from the radio's own port node (device 0) of the - * SoC's enabled PCIe host. A radio port without the line (released by the port's own PERST - * register) has none, whatever its sibling ports carry. + * SoC's enabled PCIe host, and the one of the endpoint on port 2 from that port's node. A port + * without the line (released by the port's own PERST register) has none, whatever its sibling + * ports carry. */ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_node *np) { struct device_node *host, *port; struct of_phandle_args args; + bool usable; int devfn; host = of_parse_phandle(s->dev->of_node, "apple,apcie", 0); @@ -7222,11 +7274,14 @@ static void apple_sleep_find_radio_perst(struct apple_sleep *s, struct device_no &args)) continue; devfn = of_pci_get_devfn(port); - if (args.np == np && args.args_count >= 2 && args.args[0] < s->npins && - !test_bit(args.args[0], s->pins_skip) && devfn >= 0 && - PCI_SLOT(devfn) == 0) { + usable = args.np == np && args.args_count >= 2 && args.args[0] < s->npins && + !test_bit(args.args[0], s->pins_skip) && devfn >= 0; + if (usable && PCI_SLOT(devfn) == 0) { s->radio_perst = args.args[0]; s->radio_perst_low = args.args[1] & GPIO_ACTIVE_LOW; + } else if (usable && PCI_SLOT(devfn) == 2) { + s->port2_perst = args.args[0]; + s->port2_perst_low = args.args[1] & GPIO_ACTIVE_LOW; } of_node_put(args.np); } @@ -7242,6 +7297,7 @@ static void apple_sleep_map_pins(struct apple_sleep *s) int i, n; s->radio_perst = -1; + s->port2_perst = -1; if (!np) return; if (!of_device_is_available(np) || of_property_read_u32(np, "apple,npins", &npins) || From 2fa243c99e6464e1aa70ea08f1e5a5374c445537 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 23:01:44 +1100 Subject: [PATCH 0173/1514] scripts/dtc: apple-dart-pd-check: a DART its powered parent populates is covered A USB4 router's DARTs are children of the router node, which names the router's power states. The router driver populates them only after it has powered those states, so they are never probed while the block is off, and naming the same states on the DART holds them on through the native CIO sleep. The check counted such a DART as a new gap. Treat a DART without power-domains as covered when its parent is a device node (not a simple-bus or similar, which platform code populates) with power-domains of its own, and require the parent's domains to be enabled. This is read from the tree's structure, not from a list of boards. On today's integration DTBs it exempts nothing new; it accepts the four T8132 router DARTs once they drop their domains. Signed-off-by: Ryan Murray --- scripts/dtc/apple-dart-pd-check-test.py | 43 +++++++++++++++++++++++++ scripts/dtc/apple-dart-pd-check.py | 36 ++++++++++++++++++++- 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/scripts/dtc/apple-dart-pd-check-test.py b/scripts/dtc/apple-dart-pd-check-test.py index adab86a6e6657b..00737ba3444cf9 100755 --- a/scripts/dtc/apple-dart-pd-check-test.py +++ b/scripts/dtc/apple-dart-pd-check-test.py @@ -174,6 +174,49 @@ def test_disabled_dart_of_an_enabled_user_fails(self): self.assertIn("t8112-j413 /soc/iommu@5000 dart_x apple,t8110-dart disabled: " "power domain /soc/power-controller@3000 is disabled (new)", result.stdout) + ROUTER = ('acio@5000 { compatible = "apple,t8103-usb4-acio"; %s ' + '#address-cells = <1>; #size-cells = <0>; ' + 'dart_x: iommu@a00 { compatible = "apple,t8110-dart"; #iommu-cells = <1>; }; ' + 'nhi@b00 { iommus = <&dart_x 0>; }; };') + + def test_dart_inside_a_powered_device_is_exempt(self): + # A USB4 router's DART: its driver populates it after powering its domains. + router = self.ROUTER % "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("new: 0", result.stderr) + report = self.check("--report") + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "exempt (inside /soc/acio@5000)", report.stdout) + + def test_dart_inside_a_device_without_domains_fails(self): + router = self.ROUTER % "" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "no power-domains (new)", result.stdout) + + def test_dart_inside_a_device_on_a_disabled_domain_fails(self): + disabled = DOMAIN.replace("{", '{ status = "disabled";') + router = self.ROUTER % "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", disabled, GAP, router)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("/soc/acio@5000/iommu@a00 dart_x apple,t8110-dart okay: " + "parent's power domain /soc/power-controller@3000 is disabled (new)", + result.stdout) + + def test_dart_inside_a_powered_bus_is_not_exempt(self): + # A simple-bus is populated by platform code, not by a driver. + bus = self.ROUTER.replace('"apple,t8103-usb4-acio"', '"simple-bus"') % \ + "power-domains = <&ps_x>;" + self.dtb(self.head, "t8112-j413", dts("j413", "t8112", DOMAIN, GAP, bus)) + result = self.check() + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn("no power-domains (new)", result.stdout) + def test_without_baseline_every_gap_fails(self): result = subprocess.run([sys.executable, str(CHECKER), "--dtb-dir", str(self.head)], text=True, capture_output=True) diff --git a/scripts/dtc/apple-dart-pd-check.py b/scripts/dtc/apple-dart-pd-check.py index 59aa7e64947a03..18d50c87985f1f 100755 --- a/scripts/dtc/apple-dart-pd-check.py +++ b/scripts/dtc/apple-dart-pd-check.py @@ -14,7 +14,11 @@ block is off as a whole, which is consistent. Exempt: the DARTs of the SEP and of the AOP. Those coprocessors run from -before the handoff on states the AP never switches off. +before the handoff on states the AP never switches off. Also exempt: a DART +that is a child of a device node (not a bus) with power-domains of its own, +such as a USB4 router's. Its parent's driver populates it after powering the +parent's domains, so it is covered by them; the parent's domains must then be +enabled. Install python3-libfdt (or pylibfdt) to read DTBs. Labels are shown when the DTBs were built with DTC_FLAGS=-@. @@ -36,6 +40,7 @@ DART = re.compile(r"apple,.*dart") SOC = re.compile(r"apple,[st]\d{4}$") +BUSES = ("simple-bus", "simple-pm-bus", "simple-mfd", "isa") EXEMPT = ( (re.compile(r"apple,sep$"), "SEP"), (re.compile(r"apple,(t\d+-)?aop$"), "AOP"), @@ -115,6 +120,28 @@ def iommu_cells(offset): consumers.setdefault(phandles[spec[i + 1]], []).append(offset) i += 3 + iommu_cells(phandles[spec[i + 1]]) + def domain_providers(offset): + domains = cells(prop(offset, "power-domains")) + i = 0 + while i < len(domains): + provider = phandles.get(domains[i]) + if provider is None: + break + yield provider + n = cells(prop(provider, "#power-domain-cells")) + i += 1 + (n[0] if n else 0) + + def disabled_domains(offset): + return [nodes[p] for p in domain_providers(offset) if status(p) != "okay"] + + def powered_device(offset): + """A device node (not a bus) with power domains of its own: platform + code does not populate its children, its driver does.""" + compatible = strings(prop(offset, "compatible")) + return (offset != 0 and bool(compatible) and + not any(c in BUSES for c in compatible) and + bool(cells(prop(offset, "power-domains")))) + for offset, path in nodes.items(): compatible = strings(prop(offset, "compatible")) if not any(DART.match(c) for c in compatible): @@ -130,6 +157,13 @@ def iommu_cells(offset): for c in strings(prop(o, "compatible"))] why = [name for pattern, name in EXEMPT if any(pattern.match(c) for c in users)] problem = "exempt (%s)" % why[0] if why else "no power-domains" + parent = offsets[path.rsplit("/", 1)[0] or "/"] + if not why and powered_device(parent): + # The parent device's driver populates this DART once it has + # powered its own domains; it is never probed on its own. + bad = disabled_domains(parent) + problem = ("parent's power domain %s is disabled" % bad[0] if bad else + "exempt (inside %s)" % nodes[parent]) yield path, label, compatible[0], status(offset), problem continue i = 0 From d7e25fedf0e422cb2f4fd57faa0a6c80a14ac1f0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 07:30:52 -0500 Subject: [PATCH 0174/1514] aio: sleep as iowait while io_getevents() waits for completions A task waiting in io_getevents() for AIO completions sleeps in plain schedule(), so it never wakes with in_iowait set and schedutil's iowait boost never applies to it. Synchronous direct I/O waits in io_schedule() and io_uring sets in_iowait while the waiter has requests in flight ("turns out to be important for low QD IO"), so a libaio loop is the one common low queue depth path the boost misses. On a T6050 (M5 Max) the difference is large because an idle cluster drops to 300 MHz, and a task that sleeps most of the time keeps the utilization of its CPU too low for schedutil to raise the clock. 4 KiB O_DIRECT random reads at queue depth 1 (fio 3.43, ext4 on the internal ANS SSD), the fio job pinned to an S core at the default governor: ioengine IOPS mean latency libaio 11,146 87.4 us pvsync2 16,553 60.2 us (io_schedule(): boosted) posixaio 16,103 61.9 us (glibc helpers in pread(): boosted) libaio, cluster at top clock 16,885 59.0 us Use io_schedule() in read_events() when the context has a request in flight. Count accepted request slots until completion is posted or submission fails. This also covers I/O submitted by another thread sharing the context. An idle context uses schedule() so a parked event loop incurs no iowait accounting or iowait boost. Signed-off-by: Satya Benson --- fs/aio.c | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/fs/aio.c b/fs/aio.c index d78acc69f48701..77bc01fd013353 100644 --- a/fs/aio.c +++ b/fs/aio.c @@ -142,6 +142,9 @@ struct kioctx { * We batch accesses to it with a percpu version. */ atomic_t reqs_available; + + /* Requests whose completion has yet to be posted. */ + atomic_t reqs_in_flight; } ____cacheline_aligned_in_smp; struct { @@ -847,6 +850,7 @@ static struct kioctx *ioctx_alloc(unsigned nr_events) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); + atomic_set(&ctx->reqs_in_flight, 0); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; @@ -1118,6 +1122,7 @@ static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx) } percpu_ref_get(&ctx->reqs); + atomic_inc(&ctx->reqs_in_flight); req->ki_ctx = ctx; INIT_LIST_HEAD(&req->ki_list); refcount_set(&req->ki_refcnt, 2); @@ -1206,6 +1211,7 @@ static void aio_complete(struct aio_kiocb *iocb) /* after flagging the request as done, we * must never even look at it again */ + atomic_dec(&ctx->reqs_in_flight); smp_wmb(); /* make event visible before updating tail */ ctx->tail = tail; @@ -1408,8 +1414,17 @@ static long read_events(struct kioctx *ctx, long min_nr, long nr, if (aio_read_events(ctx, min_nr, nr, event, &ret) || ret2) break; - if (nr_got == ret) - schedule(); + if (nr_got == ret) { + /* + * Mark the wait as iowait when this context has a + * request in flight, even if another thread submitted + * it. An idle event loop sleeps normally. + */ + if (atomic_read(&ctx->reqs_in_flight)) + io_schedule(); + else + schedule(); + } } finish_wait(&ctx->wait, &w.w); @@ -2114,6 +2129,7 @@ static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb, * means that we need to destroy req ourselves. */ if (unlikely(err)) { + atomic_dec(&ctx->reqs_in_flight); iocb_destroy(req); put_reqs_available(ctx, 1); } From c75d3841c769a262f64347141a2ed53104727946 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Thu, 19 Nov 2026 23:42:24 -0500 Subject: [PATCH 0175/1514] perf: apple_m1: map the generic L1D read-miss event on M4 and T6050 The Apple CPU PMU drivers pass no cache map to armpmu_map_event(), so the generic PERF_TYPE_HW_CACHE event L1D | OP_READ | RESULT_MISS is refused on every Apple core. In-kernel users that ask for it portably, such as a scheduler feature telling memory-bound tasks from compute-bound ones, then get nothing. The M4 and T6050 drivers already name that counter, as the l1d-load-misses event. Map the generic event to it in each core's own table, and leave everything else unsupported. Signed-off-by: Satya Benson --- drivers/perf/apple_m1_cpu_pmu.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/drivers/perf/apple_m1_cpu_pmu.c b/drivers/perf/apple_m1_cpu_pmu.c index d1aadc27164fb9..9009c24226c276 100644 --- a/drivers/perf/apple_m1_cpu_pmu.c +++ b/drivers/perf/apple_m1_cpu_pmu.c @@ -273,6 +273,24 @@ static const unsigned int t6050_pmu_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_BRANCH_MISSES] = T6050_PMU_PERFCTR_BRANCH_MISPRED_NONSPEC, }; +/* + * The generic L1D read-miss event, for in-kernel users such as the + * scheduler: the same counter as each core's l1d-load-misses event. + */ +static const unsigned int t6050_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = T6050_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + +static const unsigned int m4_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = M4_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + static const unsigned int m4_pmu_perf_map[PERF_COUNT_HW_MAX] = { PERF_MAP_ALL_UNSUPPORTED, [PERF_COUNT_HW_CPU_CYCLES] = M4_PMU_PERFCTR_CORE_ACTIVE_CYCLE, @@ -806,13 +824,15 @@ static int m4_pmu_map_event(struct perf_event *event) { /* 64bit counters, overflow flag on bit 63, as on M2. */ event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &m4_pmu_perf_map, NULL, M4_PMU_CFG_EVENT); + return armpmu_map_event(event, &m4_pmu_perf_map, &m4_pmu_cache_map, + M4_PMU_CFG_EVENT); } static int t6050_pmu_map_event(struct perf_event *event) { event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &t6050_pmu_perf_map, NULL, M4_PMU_CFG_EVENT); + return armpmu_map_event(event, &t6050_pmu_perf_map, &t6050_pmu_cache_map, + M4_PMU_CFG_EVENT); } static int __m1_pmu_map_pmuv3_event(const u16 *map, unsigned int eventsel) From 6fcc45d80590e6c2a5917df7e34831b53aa4f63a Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 01:01:46 -0500 Subject: [PATCH 0176/1514] perf: apple_m1: map the generic L1D read-miss event on M1 and M2 Do for the M1 and M2 cores what the previous commit did for M4 and T6050: map L1D | OP_READ | RESULT_MISS to their L1D load-miss event, M1_PMU_PERFCTR_L1D_CACHE_MISS_LD (0xa3), the same kind of event as the M4 and T6050 entries. It takes the default counter placement (any counter but 0 and 1). Everything else stays unsupported. Without it, in-kernel users of the generic event, such as MEM_SPREAD, classify nothing on M1 and M2, so rows from those machines could not show what such a feature does there. Signed-off-by: Satya Benson --- drivers/perf/apple_m1_cpu_pmu.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/drivers/perf/apple_m1_cpu_pmu.c b/drivers/perf/apple_m1_cpu_pmu.c index 9009c24226c276..f2592ca86713fc 100644 --- a/drivers/perf/apple_m1_cpu_pmu.c +++ b/drivers/perf/apple_m1_cpu_pmu.c @@ -299,6 +299,19 @@ static const unsigned int m4_pmu_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_BRANCH_MISSES] = M4_PMU_PERFCTR_BRANCH_MISPRED, }; +/* + * As above, for M1 and M2: their L1D load-miss event, 0xa3 in the M1 event + * list above (M1_PMU_PERFCTR_L1D_CACHE_MISS_LD), which came with this + * driver from the Asahi Linux project's public event documentation. M2 + * uses the same table. + */ +static const unsigned int m1_pmu_cache_map[PERF_COUNT_HW_CACHE_MAX] + [PERF_COUNT_HW_CACHE_OP_MAX] + [PERF_COUNT_HW_CACHE_RESULT_MAX] = { + PERF_CACHE_MAP_ALL_UNSUPPORTED, + [C(L1D)][C(OP_READ)][C(RESULT_MISS)] = M1_PMU_PERFCTR_L1D_CACHE_MISS_LD, +}; + static const unsigned m1_pmu_perf_map[PERF_COUNT_HW_MAX] = { PERF_MAP_ALL_UNSUPPORTED, [PERF_COUNT_HW_CPU_CYCLES] = M1_PMU_PERFCTR_CORE_ACTIVE_CYCLE, @@ -806,7 +819,7 @@ static int m1_pmu_map_event(struct perf_event *event) * being 47bit wide to mimick the behaviour of the ARM PMU. */ event->hw.flags |= ARMPMU_EVT_47BIT; - return armpmu_map_event(event, &m1_pmu_perf_map, NULL, M1_PMU_CFG_EVENT); + return armpmu_map_event(event, &m1_pmu_perf_map, &m1_pmu_cache_map, M1_PMU_CFG_EVENT); } static int m2_pmu_map_event(struct perf_event *event) @@ -817,7 +830,7 @@ static int m2_pmu_map_event(struct perf_event *event) * Yes, this is getting awkward. */ event->hw.flags |= ARMPMU_EVT_63BIT; - return armpmu_map_event(event, &m1_pmu_perf_map, NULL, M1_PMU_CFG_EVENT); + return armpmu_map_event(event, &m1_pmu_perf_map, &m1_pmu_cache_map, M1_PMU_CFG_EVENT); } static int m4_pmu_map_event(struct perf_event *event) From e6fdaf6d4b2324620c838d04c4578044219273e9 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Thu, 19 Nov 2026 23:48:26 -0500 Subject: [PATCH 0177/1514] soc: apple: mcc: let the T6050 system level cache allocate The T6050 memory cache controller has up to 64 planes: eight AMCCs of four planes per die, on up to two dies. The binding already describes this layout, but apple-mcc has no match for the controller. The boot loader leaves the ways enabled and powered with allocation disabled, so a miss in an agent's own caches goes to DRAM. T6050 uses the T8140 sequence: check each plane's ways and flush engine, clear the allocation-disable word and read it back. On shutdown, removal or deep sleep, disable allocation and flush. Add the match and raise MCC_MAX_PLANES to the binding's limit of 64. Wait for a driver to take over every client the DT lists in apple,boot-dma-devices. A disabled display node can still be scanning out the boot framebuffer, so its status cannot establish that it is safe to enable allocation. The loader must drop a client from the list only once it knows that client's boot DMA is quiescent. Based on #896 by Jeff Queisser, which measured the effect on J775D. Signed-off-by: Satya Benson --- drivers/soc/apple/Kconfig | 12 ++++++------ drivers/soc/apple/mcc.c | 5 ++++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a0c18035d21682..33644e1d08bf97 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -47,17 +47,17 @@ config APPLE_MAILBOX Say Y here if you have an Apple SoC. config APPLE_MCC - tristate "Apple T8140 and T6040 system level cache" + tristate "Apple T8140, T6040 and T6050 system level cache" depends on ARCH_APPLE || COMPILE_TEST depends on OF default ARCH_APPLE help - The boot firmware of the Apple T8140 and T6040 SoCs enables the - system level cache without letting it allocate. This driver allows - allocation once the devices that took over DMA from the bootloader - are bound. + The boot firmware of the Apple T8140, T6040 and T6050 SoCs enables + the system level cache without letting it allocate. This driver + allows allocation once the devices that took over DMA from the + bootloader are bound. - Say 'y' or 'm' here if you have an Apple T8140 or T6040 SoC. + Say 'y' or 'm' here if you have an Apple T8140, T6040 or T6050 SoC. config APPLE_MCC_KUNIT_TEST bool "KUnit tests for Apple MCC allocation and unwind" if !KUNIT_ALL_TESTS diff --git a/drivers/soc/apple/mcc.c b/drivers/soc/apple/mcc.c index ae15c4ea54e1bb..dcc36d303f652a 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -33,7 +33,8 @@ #define MCC_CACHE_FLUSH 0x2844 #define MCC_CACHE_FLUSH_BUSY BIT(0) -#define MCC_MAX_PLANES 32 +/* T6050: eight AMCCs of four planes on each die, 64 planes on two dies. */ +#define MCC_MAX_PLANES 64 #define MCC_FLUSH_TIMEOUT_US 100000 struct apple_mcc { @@ -146,6 +147,7 @@ static int apple_mcc_wait_boot_dma(struct device *dev) if (pdev) put_device(&pdev->dev); + /* A disabled DT node can still have DMA left running. */ if (!bound) { ret = dev_err_probe(dev, -EPROBE_DEFER, "waiting for %pOF to bind\n", it.node); @@ -387,6 +389,7 @@ static const struct of_device_id apple_mcc_of_match[] = { { .compatible = "apple,t8132-mcc" }, { .compatible = "apple,t8140-mcc" }, { .compatible = "apple,t8142-mcc" }, + { .compatible = "apple,t6050-mcc" }, {} }; MODULE_DEVICE_TABLE(of, apple_mcc_of_match); From e7fe7f3b4c69c4c389986436c53cfb9766e0ab80 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Thu, 19 Nov 2026 20:16:49 -0500 Subject: [PATCH 0178/1514] drm/apple: set the mode of an HDMI display once its DCP has it plugged in After a system resume the DCP of the HDMI output on J775c reports the display plugged in (VideoInterface::Plug, then the hotplug callback) only about 1.2 s after dcp_poweron() brought its link up, as the DP-to-HDMI converter and the display wake up. The restore commit sets the mode right after the link is up, so the firmware fails it after a 200 ms wait: setmode failed ERROR: Modeset done, but pipe not enabled: fSoftPowerState=1, fDisplayPowerState=0, fHardPowerState=1 set_digital_out_mode returned 80000104 on every resume. The display still comes back: the hotplug that connects it finds the mode invalid with the CRTC active and sets it again (dcp_hotplug()), and that mode set works. Don't send a mode set the firmware can only fail: while the connector of an HDMI output is not connected, leave the mode invalid and fail the mode set as the firmware would have, without asking it. The hotplug then sets the mode as before. This saves the 200 ms and the firmware error, and the restore after a resume no longer waits for them. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/iomfb.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1f3e97e6c5e9f0..4d06289059ab67 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3590,6 +3590,22 @@ int dcp_crtc_atomic_modeset(struct drm_crtc *crtc, if (crtc_state->mode.hdisplay == 0 && crtc_state->mode.vdisplay == 0) return 0; + /* + * The DCP of an HDMI output plugs the display in only some time after + * its link came up (dcp_poweron() connects it): a second or more after + * a system resume, as the converter and the display wake up. A mode set + * before that fails in the firmware ("setmode failed", the pipe not + * enabled) after a 200 ms wait. Leave the mode unset instead: the + * hotplug that connects the display finds the mode invalid with the + * CRTC active, and sets it again (dcp_hotplug()). + */ + if (dcp->hdmi_hpd && !dcp_is_typec_output(dcp) && dcp->connector && + !READ_ONCE(dcp->connector->connected)) { + dev_dbg(dcp->dev, "HDMI display not plugged in yet: mode set deferred to its hotplug\n"); + dcp_mode_set_valid(&dcp->mode_state, false); + return -EAGAIN; + } + dcp->pq_requested = dcp_crtc_eotf(dcp, crtc, commit) == HDMI_EOTF_SMPTE_ST2084; dcp->output_edr = dcp->pq_requested && dcp_panel_edr_supported(dcp) && dcp_crtc_bt2020(dcp, crtc, commit); From c5daf572c69cf596d254050089476e9793f67e53 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 18 Nov 2026 16:02:05 +0700 Subject: [PATCH 0179/1514] arm64: spin table: close the holding pen behind each released CPU secondary_holding_pen_release is written with a CPU's MPIDR to let it out of the pen and never reset, so after boot it still names the last CPU released. secondary_data.task likewise keeps that CPU's idle task: __cpu_up() only clears it on failure. With the restartable spin table (aurora,rvbar-spin-table) a CPU comes back through the pen whenever the SoC restarts it at its reset vector: after a system sleep's commit, and at the wake. The CPU whose MPIDR is still in the pen walks straight through into secondary_startup, ahead of its own bring-up, and runs secondary_start_kernel() as that CPU with the stale task. The hotplug state machine has not started it, so no STARTING callback runs (no arch timer, no tick device), yet it marks itself online and completes cpu_running, so the real bring-up returns at once. It idles quietly while cpuidle is paused and faults at the first menu_select() after cpuidle_resume(): Unable to handle kernel NULL pointer dereference at virtual address 0000000000000020 CPU: 9 UID: 0 PID: 0 Comm: swapper/9 pc : tick_nohz_get_sleep_length+0x68/0xd4 Call trace: tick_nohz_get_sleep_length+0x68/0xd4 (P) menu_select+0x414/0x774 cpuidle_select+0x1c/0x28 do_idle+0x1e8/0x310 cpu_startup_entry+0x34/0x38 secondary_start_kernel+0x198/0x1bc Kernel panic - not syncing: Attempted to kill the idle task! Seen on a J815 (MacBook Air 15" M5) when every core was started at the end of the wake, as macOS does, instead of one by one at its bring-up. Reset the release to INVALID_HWID in the released CPU's cpu_postboot, which runs before complete(&cpu_running), so it can't race with the next bring-up; and again before a suspend's hold and after the wake, before any CPU is started. Clear secondary_data.task after a successful bring-up too, as kernels before 5.x did, so a core that still reaches __secondary_switched without a bring-up of its own waits in __secondary_too_slow instead of running as another CPU. Tested on J815: two real deep sleeps (256 s and 172 s) with all nine secondary cores started together at the wake, all back online, where the same kernel without this change panicked on the first wake. Signed-off-by: Nick --- arch/arm64/kernel/smp.c | 11 ++++++++++- arch/arm64/kernel/smp_spin_table.c | 13 +++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/arch/arm64/kernel/smp.c b/arch/arm64/kernel/smp.c index f6b5decff53da5..f383d15a104cf0 100644 --- a/arch/arm64/kernel/smp.c +++ b/arch/arm64/kernel/smp.c @@ -139,8 +139,17 @@ int __cpu_up(unsigned int cpu, struct task_struct *idle) */ wait_for_completion_timeout(&cpu_running, msecs_to_jiffies(5000)); - if (cpu_online(cpu)) + if (cpu_online(cpu)) { + /* + * The CPU has taken its task. Cleared, as kernels before 5.x did, so a core that + * reaches __secondary_switched without a bring-up of its own waits in + * __secondary_too_slow instead of running as this CPU a second time. + */ + WRITE_ONCE(secondary_data.task, NULL); + dcache_clean_inval_poc((unsigned long)&secondary_data, + (unsigned long)&secondary_data + sizeof(secondary_data)); return 0; + } pr_crit("CPU%u: failed to come online\n", cpu); secondary_data.task = NULL; diff --git a/arch/arm64/kernel/smp_spin_table.c b/arch/arm64/kernel/smp_spin_table.c index e66806dbbf9c5d..0d0f200e3de6a8 100644 --- a/arch/arm64/kernel/smp_spin_table.c +++ b/arch/arm64/kernel/smp_spin_table.c @@ -222,6 +222,9 @@ int spin_table_hold_parked(void) int us, ret; unsigned int cpu; + /* No CPU restarted from here to the wake may pass the pen without its own bring-up. */ + write_pen_release(INVALID_HWID); + for_each_present_cpu(cpu) WRITE_ONCE(spin_table_hold_error[cpu], 0); WRITE_ONCE(spin_table_hold_generation, READ_ONCE(spin_table_hold_generation) + 1); @@ -331,6 +334,8 @@ void spin_table_stop_finished(void) /* Before any CPU is started again: the pen must let them boot. */ if (secondary_pen_deep) spin_table_pen_deep_set(0); + /* ...but only the one its bring-up releases (cores started early wait in the pen). */ + write_pen_release(INVALID_HWID); WRITE_ONCE(spin_table_hold_requested, false); WRITE_ONCE(spin_table_stop_requested, false); WRITE_ONCE(spin_table_stop_released, false); @@ -473,6 +478,14 @@ static int smp_rvbar_spin_table_cpu_kill(unsigned int cpu) static void smp_rvbar_spin_table_postboot(void) { + /* + * Close the pen behind this CPU. Left at its MPIDR, the next restart at the reset vector + * (after a sleep's commit, or a platform that starts every core at once at the wake) + * lets it straight through the pen into secondary_startup ahead of its own bring-up, + * with the secondary_data of its last boot: it then runs as that CPU with no STARTING + * callbacks run, e.g. without a tick device. + */ + write_pen_release(INVALID_HWID); cpumask_clear_cpu(smp_processor_id(), &spin_table_cpus_off); if (READ_ONCE(spin_table_power) && spin_table_power->cpu_restore) spin_table_power->cpu_restore(read_cpuid_mpidr() & MPIDR_HWID_BITMASK); From 751b6d509fb2f3458f3bc3b25c74cba9e1652154 Mon Sep 17 00:00:00 2001 From: Kyle Arrington Date: Mon, 16 Nov 2026 21:41:48 -0600 Subject: [PATCH 0180/1514] HID: magicmouse: report the J813 trackpad's palms The J813 (MacBook Air 13" M5) trackpad sends the standard MTP report and classes its contacts like the T6041 and J616s ones: low byte of a record's second word, 2 and 3 for fingers, 6 and above for palms. Most J813 palms stay below the classed tool area of 1400 that the T6041 rule needs: recorded in normal use and while typing, 221 of 370 palm-classed contacts never passed it, and fingers reached 1560, so lowering it would not separate them. The class flickers to a palm for single reports on fingers (4 of 868), so on the J813 a contact also counts as a palm once two consecutive reports class it as one. That caught all 370 palms by their second report, and one finger, classed a palm for its last reports while lifting. As on the J616s, the J813 trackpad now also advertises ABS_MT_TOOL_TYPE and the full 16-bit range of its touch and width areas. Other machines are unchanged. Signed-off-by: Kyle Arrington --- drivers/hid/hid-magicmouse.c | 40 ++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 4d8ffa36d77004..16f7f1a4643a38 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -273,9 +273,13 @@ struct effect_job { * @tp26_button: Button state of the last Trackpad26 frame. * @mtp_c1fe: Whether the MTP trackpad sends the J700 C1FE report layout. * @mtp_palms: Whether the controller's contact classes are trusted for palms - * on the standard MTP report (T6041, J616s). + * on the standard MTP report (T6041, J616s, J813). * @mtp_palm_size: Whether a tool area alone marks an MTP contact as a palm. * @mtp_palm_ids: MTP contact IDs reported as palms until they lift. + * @mtp_palm_debounce: Whether two consecutive palm classes mark an MTP contact + * as a palm whatever its tool area (J813). + * @mtp_palm_classed: MTP contact IDs the controller classed as palms in the + * previous report. * @ntouches: Number of touches in most recent touch report. * @scroll_accel: Number of consecutive scroll motions. * @scroll_jiffies: Time of last scroll motion. @@ -310,6 +314,8 @@ struct magicmouse_sc { bool mtp_palms; bool mtp_palm_size; DECLARE_BITMAP(mtp_palm_ids, U8_MAX + 1); + bool mtp_palm_debounce; + DECLARE_BITMAP(mtp_palm_classed, U8_MAX + 1); int ntouches; int scroll_accel; @@ -1008,27 +1014,46 @@ static u8 magicmouse_mtp_contact_id(const struct tp_finger *f) return le16_to_cpu(f->unknown1) & 0xff; } +/* + * The J813 (MacBook Air 13" M5) controller classes contacts the same way, but + * most of its palms stay below the classed tool area above: recorded on a J813 + * in normal use and while typing, 221 of 370 palm-classed contacts never passed + * 1400, and fingers reached 1560. Its class flickers to a palm for single + * reports on a finger (4 of 868 finger contacts), so there a contact also + * counts as a palm once two consecutive reports class it as one. That caught + * all 370 palms by their second report, and one finger, classed a palm for its + * last reports while lifting. + */ static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, const u8 *records, int count) { DECLARE_BITMAP(palms, U8_MAX + 1); + DECLARE_BITMAP(classed, U8_MAX + 1); const struct tp_finger *f; + bool palm_class; int i, tool; u8 id, class; bitmap_zero(palms, U8_MAX + 1); + bitmap_zero(classed, U8_MAX + 1); for (i = 0; i < count; i++) { f = (const struct tp_finger *)(records + i * sizeof(*f)); id = magicmouse_mtp_contact_id(f); class = le16_to_cpu(f->unknown2) & 0xff; tool = le16_to_int(f->tool_major); + palm_class = class >= MAGICMOUSE_MTP_PALM_CLASS_MIN; + if (palm_class) + __set_bit(id, classed); if ((msc->mtp_palm_size && tool > MAGICMOUSE_MTP_PALM_TOOL_MAJOR) || - (class >= MAGICMOUSE_MTP_PALM_CLASS_MIN && + (palm_class && tool > MAGICMOUSE_MTP_CLASSED_PALM_TOOL_MAJOR) || + (msc->mtp_palm_debounce && palm_class && + test_bit(id, msc->mtp_palm_classed)) || test_bit(id, msc->mtp_palm_ids)) __set_bit(id, palms); } bitmap_copy(msc->mtp_palm_ids, palms, U8_MAX + 1); + bitmap_copy(msc->mtp_palm_classed, classed, U8_MAX + 1); } static void report_finger_data(struct input_dev *input, int slot, @@ -1735,7 +1760,7 @@ static int magicmouse_setup_input_mtp(struct input_dev *input, /* * A palm's tool area on the T6041 and J616s trackpads exceeds * 5000 once scaled, so allow the full range of the record's - * 16-bit fields there. + * 16-bit fields on every trackpad whose palms are classed. */ int area_max = msc->mtp_palms ? 2 * S16_MAX : 5000; @@ -1762,7 +1787,7 @@ static int magicmouse_setup_input_mtp(struct input_dev *input, J314_TP_MAX_FINGER_ORIENTATION, 0, 0); } - /* The T6041, J616s and Trackpad26 controllers classify palms. */ + /* The T6041, J616s, J813 and Trackpad26 controllers classify palms. */ if (msc->mtp_palms || msc->mtp_tp26) input_set_abs_params(input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); @@ -2877,12 +2902,19 @@ static int magicmouse_probe(struct hid_device *hdev, msc->mtp_c1fe = of_device_is_compatible(np, "apple,j700-multitouch"); msc->mtp_palm_size = !msc->mtp_c1fe && of_machine_is_compatible("apple,t6041"); + /* + * The J813 controller classes contacts the same way, and two + * consecutive palm classes mark its palms. + */ + msc->mtp_palm_debounce = !msc->mtp_c1fe && + of_machine_is_compatible("apple,j813"); /* * The J616s controller classes contacts the same way, but its * fingers reach a tool area of 2475, so only the class marks its * palms there. */ msc->mtp_palms = msc->mtp_palm_size || + msc->mtp_palm_debounce || (!msc->mtp_c1fe && of_machine_is_compatible("apple,j616s")); of_node_put(np); From 6bfbc9981bb54e5a7ccd8e331de0ffd8e6254308 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 17 Nov 2026 15:06:47 +0700 Subject: [PATCH 0181/1514] HID: magicmouse: report the J815 trackpad's palms too The J815 (MacBook Air 15" M5) has the J813's T8142 and MTP transport, and its trackpad sends the standard MTP report the previous commit reads on the J813, with the same contact classes. Take the J813's rule there as well: the controller's palm classes are trusted, and two consecutive palm classes mark a palm whatever its tool area. The pads differ: the J813 ADT's multi-touch hid-merge-personality is C1FD1,4, the J815's C1FD3,3 (a larger pad, firmware tpmtfw-j815.bin), so the rule was checked on a J815 recording (one contact line per lift): 30 s typing with both palms resting on the pad: 77 contacts the controller classed as palms, all 77 marked (36 by their second report); 15 short contacts with fewer palm classes, 11 of them marked, all with large tool areas (up to 5245) at the palms' edges. 30 s pointing, tapping and two-finger scrolling: 54 finger contacts, none marked and none with a palm class; the largest finger tool area was 1028, below the 1400 the area rule needs. (6 more contacts lifted in the first second: palms still resting from the typing phase, all classed as palms.) Signed-off-by: Nick Signed-off-by: Kyle Arrington --- drivers/hid/hid-magicmouse.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 16f7f1a4643a38..712c3ae5d78acd 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -277,7 +277,7 @@ struct effect_job { * @mtp_palm_size: Whether a tool area alone marks an MTP contact as a palm. * @mtp_palm_ids: MTP contact IDs reported as palms until they lift. * @mtp_palm_debounce: Whether two consecutive palm classes mark an MTP contact - * as a palm whatever its tool area (J813). + * as a palm whatever its tool area (J813, J815). * @mtp_palm_classed: MTP contact IDs the controller classed as palms in the * previous report. * @ntouches: Number of touches in most recent touch report. @@ -2904,10 +2904,12 @@ static int magicmouse_probe(struct hid_device *hdev, of_machine_is_compatible("apple,t6041"); /* * The J813 controller classes contacts the same way, and two - * consecutive palm classes mark its palms. + * consecutive palm classes mark its palms. The J815 (15-inch) + * sends the same standard report from its own, larger pad. */ msc->mtp_palm_debounce = !msc->mtp_c1fe && - of_machine_is_compatible("apple,j813"); + (of_machine_is_compatible("apple,j813") || + of_machine_is_compatible("apple,j815")); /* * The J616s controller classes contacts the same way, but its * fingers reach a tool area of 2475, so only the class marks its From fcbf48afad78bf98ee0890ef3175b8bd1ef00de9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 23:47:16 +1100 Subject: [PATCH 0182/1514] Bluetooth: hci_bcm4377: don't report a deferred reprobe as a failure A command timeout queues a rebind of the driver. When the timeout comes from the resume commands (a J615 s2idle resume: 'command 0x0c01 tx timeout'), the rebind runs while the driver core still blocks probing for the system sleep, so device_reprobe() returns -EPROBE_DEFER and the driver logs 'reprobe after command timeout failed'. The device is on the deferred list by then and binds as soon as resume completes; on the J615 hci0 was back and registered with mgmt about a second later. The error line made a recovered controller look dead. Log a deferred reprobe as such, and give the real failure its error code. Signed-off-by: Ryan Murray --- drivers/bluetooth/hci_bcm4377.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 02cc8fccbc27c2..3f875ac518dfc9 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -2770,14 +2770,20 @@ static void bcm4377_reset_work(struct work_struct *work) { struct bcm4377_reset_work *rw = container_of(work, struct bcm4377_reset_work, work); + int ret; /* * Remove and probe again: probe resets the function and boots the * firmware from scratch. device_reprobe() frees the old bcm4377_data, * which is why this work and its device reference live outside it. + * A timeout during system resume gets here while the driver core + * blocks probing: the probe is deferred and runs once resume completes. */ - if (device_reprobe(&rw->pdev->dev)) - dev_err(&rw->pdev->dev, "reprobe after command timeout failed\n"); + ret = device_reprobe(&rw->pdev->dev); + if (ret == -EPROBE_DEFER) + dev_info(&rw->pdev->dev, "reprobe after command timeout deferred\n"); + else if (ret) + dev_err(&rw->pdev->dev, "reprobe after command timeout failed: %d\n", ret); pci_dev_put(rw->pdev); kfree(rw); From bc4aece44de45610be8b173a2277296eb2bb6392 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 12 Nov 2026 11:16:19 -0700 Subject: [PATCH 0183/1514] i2c: pasemi: report a NACK as a NACK while the STOP is still going out With the interrupt enabled for MTN, the transfer wait returns as soon as the device has not acknowledged a byte. The controller has not put the STOP on the bus yet at that point, so SMSTA usually still has XIP set (0x10210106: XIP, MTN, MTE), and since XIP is tested first the transfer is reported as "Bus stuck" and fails with -EIO. Read a little later the same event gives 0x08210106 and "NACK"; both were seen for the same unpowered device within one boot of an M5 Pro MacBook Pro. Nothing is stuck there: the controller finishes the STOP by itself and the next transfer waits for the bus to go idle, resetting the controller if it does not. Test MTN (and arbitration loss) before XIP so that an unanswered address is logged as what it is and returns -ENXIO, which is what clients probing for a device expect. A transfer that ends with XIP set and no NACK is still reported as stuck. This reverses mainline's order of the two tests. Both are early returns whose error path resets the controller, so only the errno and the message change for a transfer that has both bits set. Cc: Sven Peter Cc: Janne Grunau Cc: Neal Gompa Cc: Andi Shyti Cc: linux-i2c@vger.kernel.org Signed-off-by: Jens Axboe Signed-off-by: Thomas Glanzmann --- drivers/i2c/busses/i2c-pasemi-core.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/drivers/i2c/busses/i2c-pasemi-core.c b/drivers/i2c/busses/i2c-pasemi-core.c index 7105fc46064509..38bddbbcefd3b1 100644 --- a/drivers/i2c/busses/i2c-pasemi-core.c +++ b/drivers/i2c/busses/i2c-pasemi-core.c @@ -196,24 +196,29 @@ static int pasemi_smb_waitready(struct pasemi_smbus *smbus) return -ETIME; } - /* Still stuck in a transaction? */ - if (status & SMSTA_XIP) { - dev_err(smbus->dev, "Bus stuck, status 0x%08x\n", status); - return -EIO; - } - /* Arbitration loss? */ if (status & SMSTA_MTA) { dev_err(smbus->dev, "Arbitration loss, status 0x%08x\n", status); return -EBUSY; } - /* Got NACK? */ + /* + * Got NACK? The interrupt comes with the NACK, before the controller + * has put the STOP on the bus, so XIP is usually still set here: this + * is checked before XIP, and the transfer is over once the STOP is out + * (the next transfer waits for that). + */ if (status & SMSTA_MTN) { dev_err(smbus->dev, "NACK, status 0x%08x\n", status); return -ENXIO; } + /* Still stuck in a transaction? */ + if (status & SMSTA_XIP) { + dev_err(smbus->dev, "Bus stuck, status 0x%08x\n", status); + return -EIO; + } + /* Clear XEN */ reg_write(smbus, REG_SMSTA, SMSTA_XEN); From 32e89725ccc913f0345744025ca414ed7a1777ce Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:49:22 +0000 Subject: [PATCH 0184/1514] arm64: dts: apple: t6050-k114c: enable the Neural Engine J714s already includes t6050-j714s-ane.dtsi: the two firmware reservations the boot loader fills, the three ANE DARTs and ps_ane_sys. K114c, the same T6050 ANE, enables none of it, so ane0 stays disabled. Include the same file after t6050-peripherals.dtsi. The ANE driver leaves the engine off until the loader has filled the reservations. Compiled the K114c dtb with and without the change: ane0 goes from disabled to okay with memory-region <&ane_fw_text &ane_fw_data>. Not booted with the ANE started. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-k114c.dts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 6100f9d1cf80c4..95196a83f5c1b7 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -24,6 +24,9 @@ #include "t6050-peripherals.dtsi" +/* The Neural Engine, started only after the boot loader's preload hand-off */ +#include "t6050-j714s-ane.dtsi" + / { aliases { /* kboot fills the N1's factory addresses from /chosen through these */ From be91b867b18cf452b88b419b936f8ebb9dcd8701 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:33:39 -0600 Subject: [PATCH 0185/1514] arm64: dts: apple: t6050-k114c: enable the ANE's fabric power domains The t6050-j714s-ane.dtsi include sets ps_ane_sys okay, but ANE_SYS's suppliers stayed disabled on the K114c: ps_fab8_soc and ps_fab9_soc (parents of ANE_SYS in t6050-peripherals.dtsi) and their shared parent ps_fab0_piogw. A disabled power-controller registers no provider, so the pmgr driver's parent lookup defers and ANE_SYS never registers, leaving ane0 and its three DARTs deferred too. Enable the chain the way the J714s does: ps_fab0_piogw and ps_fab8_soc firmware-owned and okay as in t6050-j714s.dts, and ps_fab9_soc in the t6050-j716c-isp.dtsi form (parent edge dropped, no-auto-pm, firmware-owned, okay), since the fabric domains are powered by the boot firmware rather than by Linux. Compiled the K114c dtb and ran the schema check: only the pre-existing apple,t6050-pciec port0 finding, identical without the change. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-k114c.dts | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 95196a83f5c1b7..ed1f3ec3036a6b 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -27,6 +27,30 @@ /* The Neural Engine, started only after the boot loader's preload hand-off */ #include "t6050-j714s-ane.dtsi" +/* + * ANE_SYS's declared suppliers are the fabric domains: enabled here the way + * the J714s enables them (t6050-j714s.dts for fab8/fab0, + * t6050-j716c-isp.dtsi for fab9). Left disabled they never register a + * provider and the enabled ps_ane_sys defers forever, taking ane0 and its + * three DARTs with it. + */ +&ps_fab0_piogw { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab8_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab9_soc { + /delete-property/ power-domains; + apple,no-auto-pm; + apple,firmware-owned; + status = "okay"; +}; + / { aliases { /* kboot fills the N1's factory addresses from /chosen through these */ From 754b649d8e78eebf736c55aacedb896d3cddc9c5 Mon Sep 17 00:00:00 2001 From: Jos Dehaes Date: Thu, 12 Nov 2026 13:53:24 +0100 Subject: [PATCH 0186/1514] arm64: dts: apple: t6041-j614c-j616c: dcpext3 for a third USB-C display With dcpext1 and dcpext2, two of the three USB-C ports can drive a display at the same time. Describe dcpext3 as dcpext2, so that each port can: iBoot preloads and starts it too (iop-dcpext3-nub pre-loaded 1, running 1). Its block is dcpext2's moved from 0x6xxxxxxxx to 0x3xxxxxxxx, interrupts +0x48, external-index 4, crossbar state 6 (2 * dp-switch-ufp-endpoint 3 + port 0). The ADT pmgr bwr-agent table gives DISP_EXT3 slot 6, so its bandwidth scratch is 0x38000, by the rule dcpext1 (slot 4, 0x30000) and dcpext2 (slot 5, 0x34000) follow. The display gate enables dcpext3's chain as dcpext2's, and the KUnit tree and cases cover it. Signed-off-by: Jos Dehaes --- .../boot/dts/apple/t6041-j614c-j616c.dtsi | 1 + .../dts/apple/t6041-j616c-usbc-dcpext3.dtsi | 194 ++++++++++++++++++ drivers/soc/apple/display-gate-test.c | 16 ++ drivers/soc/apple/display-gate.c | 12 ++ drivers/soc/apple/t6041-gate-test.dtso | 56 ++++- 5 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index 8e2b49a4567ea9..938a0ecd8a80da 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -2547,6 +2547,7 @@ #include "t6041-j616c-hdmi.dtsi" #include "t6041-j616c-usbc.dtsi" #include "t6041-j616c-usbc-dcpext2.dtsi" +#include "t6041-j616c-usbc-dcpext3.dtsi" /* * Keyboard backlight, as on the M4 Pro boards: the ADT /arm-io/pwm0 has one diff --git a/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi b/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi new file mode 100644 index 00000000000000..6257843799f9d3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j616c-usbc-dcpext3.dtsi @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * A third USB-C DisplayPort processor on the J614c and J616c: dcpext3, with + * a route to each of the three USB-C ports (typec0-2), next to dcpext1 and + * dcpext2. Each USB-C port can then drive a display of its own. + * + * dcpext3 is dcpext2's block moved from 0x6xxxxxxxx to 0x3xxxxxxxx (ADT + * /arm-io/dcpext3 at 0x106e00000 + 0x2_0000_0000, interrupts +0x48, + * external-index 4). iBoot preloads and starts it on the M4 Max + * (iop-dcpext3-nub pre-loaded 1, running 1). As dcpext1 and dcpext2 on this + * SoC, no PMP and no DISPEXT3 power domain is described. + * + * Everything here is disabled. The boot loader fills dcpext3's firmware + * memory from this boot's ADT (aura t6041_exts) and the display gate enables + * the chain once it has. + */ + +/ { + aliases { + dcpext3 = &dcpext3; + }; + + reserved-memory { + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; + + dcpext3: dcp@306e00000 { + compatible = "apple,t6041-dcpext", "apple,dcpext"; + reg = <0x3 0x06e00000 0x0 0x4000>, + <0x3 0x04000000 0x0 0x4000000>, + <0x3 0x06240000 0x0 0x10000>, + <0x3 0x063a8000 0x0 0x4000>, + <0x3 0x06800000 0x0 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext3_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext3_dart 23>; + /* + * PMGR bandwidth agent scratch: the bwr-agent the ADT dispext3 + * function-bw_req_interrupt0 (0x4f) names: ADT + * pmgr bwr-agent DISP_EXT3, slot 6, so 0x20000 + 6 * 0x4000. + */ + apple,bw-scratch = <&pmgr_dcp 0 4 0x38000>; + /* ADT iop-dcpext3-nub external-index */ + apple,dcp-endpoint = <4>; + /* as dcpext0/1: without it apple-dcp's probe fails with -EINVAL */ + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>, <&atcphy2 PHY_TYPE_DP>; + phy-names = "typec0", "typec1", "typec2"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, <&atcphy2_xbar 0>; + mux-control-names = "typec0", "typec1", "typec2"; + /* + * indexed by route; crossbar state = 2 * dp-switch-ufp-endpoint + * (3) + port (0) + */ + apple,typec-dptx-phys = <0 1 2>; + apple,typec-mux-indices = <6 6 6>; + memory-region = <&dcpext3_text>, <&dcpext3_data>, <&dcpext3_heap>; + memory-region-names = "text", "data", "heap"; + status = "disabled"; + + dispext3_piodma: piodma { + iommus = <&dispext3_dart 16>; + }; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec0: endpoint { + remote-endpoint = <&typec0_dcpext3>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec1: endpoint { + remote-endpoint = <&typec1_dcpext3>; + }; + }; + }; + + route@2 { + reg = <2>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec2: endpoint { + remote-endpoint = <&typec2_dcpext3>; + }; + }; + }; + }; + }; + + dcpext3_mbox: mailbox@306e08000 { + compatible = "apple,t6041-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x06e08000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06300000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; + + dcpext3_dart: iommu@306340000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06340000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; +}; + +&typec0 { + ports { + port@3 { + typec0_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + typec1_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec1>; + }; + }; + }; +}; + +&typec2 { + ports { + port@3 { + typec2_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec2>; + }; + }; + }; +}; diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index 3b0b162ed6799a..d83933c87fb32a 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -1154,6 +1154,7 @@ static void __init gate_t6041_max_no_memory(struct kunit *test) gt_max_expect_chain(test, 0, false); gt_max_expect_chain(test, 1, false); gt_max_expect_chain(test, 2, false); + gt_max_expect_chain(test, 3, false); gt_max_expect_display(test, 0); } @@ -1167,9 +1168,23 @@ static void __init gate_t6041_max_second_usbc(struct kunit *test) gt_max_expect_chain(test, 0, true); gt_max_expect_chain(test, 1, true); gt_max_expect_chain(test, 2, true); + gt_max_expect_chain(test, 3, false); gt_max_expect_display(test, BIT(0) | BIT(1) | BIT(2)); } +/* With all four filled, every external chain comes up, dcpext3's last. */ +static void __init gate_t6041_max_all_externals(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < 4; i++) + gt_max_fill(test, i); + gt_max_run(test); + for (i = 0; i < 4; i++) + gt_max_expect_chain(test, i, true); + gt_max_expect_display(test, BIT(0) | BIT(1) | BIT(2) | BIT(3)); +} + /* The other processor's chain does not wait for one that was refused. */ static void __init gate_t6041_max_one_processor(struct kunit *test) { @@ -1237,6 +1252,7 @@ static struct kunit_case gate_t6041_max_cases[] __refdata = { KUNIT_CASE(gate_t6041_max_enabled), KUNIT_CASE(gate_t6041_max_no_memory), KUNIT_CASE(gate_t6041_max_second_usbc), + KUNIT_CASE(gate_t6041_max_all_externals), KUNIT_CASE(gate_t6041_max_one_processor), KUNIT_CASE(gate_t6041_max_partial_memory), KUNIT_CASE(gate_t6041_max_enabled_by_loader), diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index cde6d7c835d31f..825e0d02480f44 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -3129,10 +3129,22 @@ static const char *const t6041_max_usbc2_nodes[] = { "/dcp@606e00000", }; +/* The third USB-C processor of the J614c/J616c, dcpext3, as dcpext2's chain. */ +static const char *const t6041_max_usbc3_nodes[] = { + "/iommu@306340000", + "/iommu@306300000", + "/mailbox@306e08000", + "/dcp@306e00000/typec-routes/route@0", + "/dcp@306e00000/typec-routes/route@1", + "/dcp@306e00000/typec-routes/route@2", + "/dcp@306e00000", +}; + static const struct gate_staged t6041_max_stages[] = { { "/iommu@3a2300000", t6041_max_hdmi_nodes, ARRAY_SIZE(t6041_max_hdmi_nodes) }, { "/iommu@602300000", t6041_max_usbc_nodes, ARRAY_SIZE(t6041_max_usbc_nodes) }, { "/iommu@606300000", t6041_max_usbc2_nodes, ARRAY_SIZE(t6041_max_usbc2_nodes) }, + { "/iommu@306300000", t6041_max_usbc3_nodes, ARRAY_SIZE(t6041_max_usbc3_nodes) }, }; /* diff --git a/drivers/soc/apple/t6041-gate-test.dtso b/drivers/soc/apple/t6041-gate-test.dtso index e77e3415199a32..9519dad0eea4a9 100644 --- a/drivers/soc/apple/t6041-gate-test.dtso +++ b/drivers/soc/apple/t6041-gate-test.dtso @@ -2,7 +2,8 @@ /* * Test device tree for the display gate KUnit test: the J616c's external * display chains at their real paths (t604x-extdisp.dtsi, - * t6041-j616c-hdmi.dtsi, t6041-j616c-usbc.dtsi, t6041-j616c-usbc-dcpext2.dtsi), + * t6041-j616c-hdmi.dtsi, t6041-j616c-usbc.dtsi, t6041-j616c-usbc-dcpext2.dtsi, + * t6041-j616c-usbc-dcpext3.dtsi), * disabled, and the display * subsystem with the internal display's DART. There is no PMP. The data and * heap regions of both processors are the boot loader's disabled @@ -63,6 +64,20 @@ compatible = "apple,asc-mem"; status = "disabled"; }; + + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + status = "disabled"; + }; }; power-management@502800000 { @@ -224,6 +239,45 @@ }; }; + dcpext3_dart: iommu@306340000 { + #iommu-cells = <1>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + #iommu-cells = <1>; + status = "disabled"; + }; + + mailbox@306e08000 { + status = "disabled"; + }; + + dcp@306e00000 { + compatible = "apple,t6041-dcpext"; + iommus = <&dcpext3_dart 23>; + memory-region = <&dcpext3_data>, <&dcpext3_heap>, <&dcpext3_text>; + status = "disabled"; + + typec-routes { + route@0 { + status = "disabled"; + }; + + route@1 { + status = "disabled"; + }; + + route@2 { + status = "disabled"; + }; + }; + + piodma { + iommus = <&dispext3_dart 16>; + }; + }; + disp_dart: iommu@a00000000 { #iommu-cells = <1>; }; From 3d969657663738b87739591337c6ff04504374ff Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 01:17:21 +1100 Subject: [PATCH 0187/1514] soc: apple: display-gate, drm/apple: start the T8122 external DCP on its 27.2 image On the macOS 27.2 (26B123) system firmware the boot loader can reserve the T8122 external display processor's firmware (chosen asahi,t8122-dcpext): it marks dcp@31ac00000 firmware-ready and publishes firmware version and compatibility 27.2.0, but no image UUID. The gate then refuses it ("its firmware-compat is not 14.7.0"), so neither USB-C port gets DisplayPort alt mode. The processor runs the internal DCP's 27.2 image: the first region the boot loader reserves for it is the internal DCP's text region. Its DISPEXT power domains are off at handoff, so nothing is running there to adopt; Linux starts it, as it does the 14.7 one. Add apple_t8122_dcpext_v27_2(): a T8122 dcpext whose firmware version and compatibility are 27.2.0, beside an internal DCP handed over on the 27.2 image. The gate admits it alongside 14.7.0, and the DCP driver runs it on the firmware-27 backend with the 27.2 table, with the firmware-27 endpoints, both DPTX port services, no live-session adoption, and without a firmware clock table, as the T6041 dcpext (it has no apple,clock-ids; counting them failed the bind with -EINVAL). On that image the processor and its scanout also use the panel's DMA window, the 1 TiB alias. The display subsystem takes the window all its display DARTs share, and the device tree's 14.7 windows for the external DARTs (from 0) share none with the panel's: once the external processor joined, the internal DCP lost its scanout mappings (DART translation faults, no modes). When it admits the 27.2 image, the gate copies the internal DCP DART's apple,dma-range onto both external DARTs, as the J613 native 26.x device tree does for that firmware; the device tree keeps the 14.7 windows. The 14.7 and native 26.x paths are unchanged. Tested on the J615 (MacBook Air 15", M3), 27.2 stub, stock command line, its unchanged device tree and a boot loader that reserves the dcpext by default: before, the gate refused the dcpext; with this change it starts (RTKit, "firmware 27: DPTX controller on 0x24, ports on 0x2a", both DPTX port services, "DCP booted"), DRM gains DP-1 and DP-2 for the two USB-C ports, the internal panel stays connected, s2idle resumes, no DART faults. No external monitor was attached. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 22 +++++++++++-- drivers/soc/apple/display-gate.c | 51 +++++++++++++++++++++++++++++-- include/linux/soc/apple/display.h | 28 +++++++++++++++++ 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 379eb39d949947..860ad5fc61669d 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6007,11 +6007,15 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) /* * The T8122 external processor: Linux starts it and drives 14.7 - * firmware through the classic IOMFB template, as on M1/M2. + * firmware through the classic IOMFB template, as on M1/M2. On the + * 27.2 image it runs the firmware-27 backend with the 27.2 table, as + * the internal processor does. */ if (of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { if (dcp_ext26_admitted(dev->of_node)) return DCP_FIRMWARE_H17P; + if (apple_t8122_dcpext_v27_2(dev->of_node)) + return dcp_v27_method_table(dev, compat_str); if (!strcmp(compat_str, "14.7.0")) return DCP_FIRMWARE_V_14_7_TEMPLATE; dev_err(dev, "T8122 external display not started: DCP firmware-compat %s is not 14.7.0\n", @@ -6215,8 +6219,10 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) dcp->num_firmware_clocks = 2; return 0; } + /* External processors without a provider clock table (T6041, T8122). */ if (!of_property_present(dev->of_node, "apple,clock-ids") && - of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) + (of_device_is_compatible(dev->of_node, "apple,t6041-dcpext") || + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext"))) return 0; clocks = of_property_count_u32_elems(dev->of_node, "apple,clock-ids"); if (clocks == -ENODATA && @@ -7269,6 +7275,18 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->hw.num_dptx_ports = 0; dcp->hw.adopt_live_session = true; } + /* + * The T8122 external processor on firmware 27: the boot loader leaves + * it unpowered (its DISPEXT domains are off at handoff), so Linux + * starts it as on 14.7, with the firmware-27 endpoints and both DPTX + * port services. Its DART window is the one the device tree describes. + */ + if (fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { + dcp->hw.num_dptx_ports = 2; + dcp->hw.fw_14_7_endpoints = false; + dcp->hw.adopt_live_session = false; + } if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) { dcp->hw.firmware_dma_bits = 41; diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 2830a17ae6cafc..2fb625de5b2b61 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -1883,6 +1883,51 @@ static bool __init gate_node_in(struct device_node *const *nodes, int n, return false; } +/* + * On the 27.2 image the T8122 external processor and its scanout use the + * panel's DMA window (the 1 TiB alias): the display subsystem takes the + * window all its display DARTs share, and the device tree's 14.7 windows for + * the external DARTs (from 0) share none with the panel's. Give @dart and + * @disp_dart the window of the internal processor's DART. + */ +static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, + struct device_node *dart, + struct device_node *disp_dart) +{ + struct device_node *dcp, *panel_dart; + struct device_node *targets[] = { dart, disp_dart }; + const struct property *window; + int i, ret = 0; + + dcp = of_find_compatible_node(NULL, NULL, "apple,t8122-dcp"); + panel_dart = dcp ? of_parse_phandle(dcp, "iommus", 0) : NULL; + of_node_put(dcp); + window = panel_dart ? of_find_property(panel_dart, "apple,dma-range", NULL) : NULL; + if (!window || !window->length) { + of_node_put(panel_dart); + return -ENODEV; + } + + for (i = 0; i < ARRAY_SIZE(targets) && !ret; i++) { + /* Kept for good: the live tree refers to it once applied. */ + struct property *prop = kzalloc_obj(*prop); + void *value = kmemdup(window->value, window->length, GFP_KERNEL); + + if (!prop || !value) { + kfree(prop); + kfree(value); + ret = -ENOMEM; + break; + } + prop->name = "apple,dma-range"; + prop->length = window->length; + prop->value = value; + ret = of_changeset_update_property(cs, targets[i], prop); + } + of_node_put(panel_dart); + return ret; +} + static void __init gate_t8122_dcpext_one(struct device_node *np) { struct device_node *dart = NULL, *mbox = NULL, *piodma = NULL; @@ -1904,8 +1949,8 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) gate_ext_refuse(np, "the boot loader did not reserve its firmware"); return; } - if (!gate_ext_firmware_ok(np)) { - gate_ext_refuse(np, "its firmware-compat is not 14.7.0"); + if (!gate_ext_firmware_ok(np) && !apple_t8122_dcpext_v27_2(np)) { + gate_ext_refuse(np, "its firmware is neither 14.7.0 nor the 27.2 image"); return; } if (!of_property_present(np, "memory-region")) { @@ -1987,6 +2032,8 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) ret = gate_add_bool(cs, entry, "apple,soc-device-record"); if (!ret) ret = gate_add_bool(cs, entry, "apple,defer-startup-ack"); + if (!ret && apple_t8122_dcpext_v27_2(np)) + ret = gate_t8122_dcpext_alias(cs, dart, disp_dart); if (!ret) ret = of_changeset_update_prop_string(cs, dart, "status", "okay"); if (!ret) diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index aa7266693ace87..c0ae42df744cd5 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -86,4 +86,32 @@ static inline bool apple_t8122_dcp_v27_2(const struct device_node *np) APPLE_T8122_DCP_26B123_UUID); } +/* + * The T8122 external display processor on the 27.2 image. The boot loader + * publishes its firmware version and compatibility but no image UUID; it + * runs the internal processor's image (its text segment is the internal + * DCP's region). So it qualifies when both of its own are 27.2.0 and the + * internal DCP was handed over on the 27.2 image. + */ +static inline bool apple_t8122_dcpext_v27_2(const struct device_node *np) +{ + struct device_node *dcp; + u32 fw[3], compat[3]; + bool internal; + + if (!np || !of_device_is_compatible(np, "apple,t8122-dcpext") || + of_property_count_u32_elems(np, "apple,firmware-version") != 3 || + of_property_count_u32_elems(np, "apple,firmware-compat") != 3 || + of_property_read_u32_array(np, "apple,firmware-version", fw, 3) || + of_property_read_u32_array(np, "apple,firmware-compat", compat, 3) || + fw[0] != 27 || fw[1] != 2 || fw[2] != 0 || + compat[0] != 27 || compat[1] != 2 || compat[2] != 0) + return false; + + dcp = of_find_compatible_node(NULL, NULL, "apple,t8122-dcp"); + internal = apple_t8122_dcp_v27_2(dcp); + of_node_put(dcp); + return internal; +} + #endif From ced0f429efaa828400112b14b62256a36066dc52 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 02:40:14 +1100 Subject: [PATCH 0188/1514] drm/apple: Tighten the EDR headroom comments A panel without EDR headroom never gets a peak, so the EDR path does not run for it at all; say that rather than how dcp_edr_target() would treat a zero ceiling. Drop the per-model values from the ADT comment: the code does not depend on them. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-edr.h | 2 +- drivers/gpu/drm/apple/dcp.c | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-edr.h b/drivers/gpu/drm/apple/dcp-edr.h index c5ec2d763f6318..fc5dc03e6f53f7 100644 --- a/drivers/gpu/drm/apple/dcp-edr.h +++ b/drivers/gpu/drm/apple/dcp-edr.h @@ -36,7 +36,7 @@ * The panel's potential headroom, the ADT backlight node's * EDRPotentialHeadroom (16.16), as a ceiling x1000. macOS never gives the * panel more. 0: the panel has no EDR headroom (a value missing or not - * above 1.0); dcp_edr_target() then takes the peak alone. + * above 1.0), so it gets no peak and the EDR path never runs for it. */ static inline u32 dcp_edr_ceiling(u32 fixed) { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 3f48efc95333a9..ba49f83b71c7f3 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1295,10 +1295,9 @@ static void dcp_panel_read_adt(struct apple_dcp *dcp) dcp->panel.color_target = ret ? NULL : dcp_panel_gamut_color_space(panel.gamut); /* * Whether the panel has EDR headroom at all is the machine's to say: an - * XDR panel's backlight node carries EDRPotentialHeadroom above 1.0 - * (16.0 on the M1 Pro and M4 Pro XDR panels), an SDR panel such as the - * M3/M4 Air's has none. Without it the panel gets no peak, so it shows - * no PQ content as EDR and offers userspace no HDR (dcp_panel_edr()). + * XDR panel's backlight node carries EDRPotentialHeadroom above 1.0, an + * SDR panel none. Without it the panel gets no peak, so it shows no PQ + * content as EDR and offers userspace no HDR (dcp_panel_edr()). */ dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); /* From 8596997cbfa070a0f18f6e7ff08ecd842b9db1cf Mon Sep 17 00:00:00 2001 From: Sasha Levin Date: Tue, 13 Oct 2026 08:15:01 -0400 Subject: [PATCH 0189/1514] docs: remove Assisted-by references Commit 78d979db6cef ("docs: add AI Coding Assistants documentation") asked contributors to add an Assisted-by tag to patches developed with help from an LLM, and commit 816d9992d9ed ("coding-assistants: simplify attribution") later reduced the tag to "Assisted-by: LLM". A proposal to drop the tag was turned down in July [1]. The main argument for keeping it was that maintainers wanted a signal that a patch was LLM-assisted, so that they could review it accordingly. The tag came up again at the 2026 Maintainers Summit [2]. Roughly 10% of the 18,533 non-merge commits in 7.3 through -rc7 carry an Assisted-by tag, while actual LLM use is far more widespread. Some contributors do not know about the rule, others leave the tag off on purpose, and few maintainers ask about it. As a result, the tag does not provide the signal it was kept for: its absence says nothing about how a patch was made, and for developers who use these tools for almost everything, its presence says little more. The choice was between finding a way to enforce the requirement and dropping it, and there was a strong, though not unanimous, consensus in the room to drop it. Greg Kroah-Hartman, who argued for keeping the tag in July, supports removing it now [3]. Maintainers do still want to know how a patch was created, but the view at the Summit was that this belongs in the cover letter, where it can describe how the tools were used, rather than in the changelog. Documentation/process/generated-content.rst already asks contributors to be transparent about tool use and is not changed here. The rules on the DCO and on the submitter's responsibility for the patch stay as they are. Remove the Assisted-by sections from coding-assistants.rst, submitting-patches.rst, and the Italian, Brazilian Portuguese and Traditional Chinese translations, and drop the handling of the tag from checkpatch. [1] https://lore.kernel.org/workflows/2026070224-unholy-commode-cf45@gregkh/ [2] https://lwn.net/Articles/1099594/ [3] https://lore.kernel.org/all/2026101327-cupid-legal-6cf6@gregkh/ Acked-by: Lorenzo Stoakes (ARM) Reviewed-by: Kees Cook Reviewed-by: Greg Kroah-Hartman Signed-off-by: Sasha Levin Reviewed-by: Jeff Layton Reviewed-by: Jori Koolstra Acked-by: Krzysztof Kozlowski Acked-by: SJ Park Acked-by: David Hildenbrand (Arm) Acked-by: Mark Brown Acked-by: Daniel Pereira Acked-by: Shuah Khan Acked-by: Weijie Yuan Reviewed-by: Miguel Ojeda Signed-off-by: Jonathan Corbet Message-ID: <20261013121501.3738437-1-sashal@kernel.org> [ Backport to the 7.3 base: the pt_BR files and the zh_TW Assisted-by section are not in 7.3, so those hunks are dropped. ] (cherry picked from commit 1e035297ffdadf2184c3c773b8c098e372324aaf) Signed-off-by: Kyle Arrington --- Documentation/process/coding-assistants.rst | 21 +------------------ Documentation/process/submitting-patches.rst | 10 --------- .../it_IT/process/submitting-patches.rst | 10 --------- scripts/checkpatch.pl | 11 ---------- 4 files changed, 1 insertion(+), 51 deletions(-) diff --git a/Documentation/process/coding-assistants.rst b/Documentation/process/coding-assistants.rst index 051f0d819f68e4..509dbf23a099bd 100644 --- a/Documentation/process/coding-assistants.rst +++ b/Documentation/process/coding-assistants.rst @@ -40,24 +40,6 @@ is responsible for: * Adding their own Signed-off-by tag to certify the DCO * Taking full responsibility for the contribution -Attribution -=========== - -When AI tools contribute to kernel development, proper attribution -helps track the evolving role of AI in the development process. -Contributions should include an Assisted-by tag in the following format:: - - Assisted-by: LLM [TOOL1] [TOOL2] - -* ``[TOOL1] [TOOL2]`` are optional specialized analysis tools used - (e.g., coccinelle, sparse, smatch, clang-tidy) - -Basic development tools (git, gcc, make, editors) should not be listed. - -Example:: - - Assisted-by: LLM coccinelle sparse - Procedure for finding and fixing bugs ===================================== @@ -82,8 +64,7 @@ these steps: another one. The fix must not add build warnings and must pass the checkpatch.pl checks (see submitting-patches.rst). 6. Commit the working fix with a detailed message describing the problem, the - solution and a Fixes tag. Do not add a Signed-off-by tag, and add an - Assisted-by tag, as described above. + solution and a Fixes tag. Do not add a Signed-off-by tag. 7. Identify the maintainers and lists using scripts/get_maintainer.pl. Documentation/process/security-bugs.rst shows how to do that. 8. Indicate what could not be done. If the fix could not be built or tested, or diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index 7ae79452e1b46d..5f4e0156cca786 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -632,16 +632,6 @@ bugzilla.kernel.org is a public place in this sense, but email addresses used there are private; so do not expose them in tags, unless the person used them in earlier contributions. -Using Assisted-by: ------------------- - -If you used any sort of advanced coding tool in the creation of your patch, -you need to acknowledge that use by adding an Assisted-by tag. Failure to -do so may impede the acceptance of your work. Please see -Documentation/process/coding-assistants.rst for details regarding the -acknowledgment of coding assistants. - - .. _the_canonical_patch_format: The canonical patch format diff --git a/Documentation/translations/it_IT/process/submitting-patches.rst b/Documentation/translations/it_IT/process/submitting-patches.rst index a742610cb0709f..d0e0d6c9ecc2e5 100644 --- a/Documentation/translations/it_IT/process/submitting-patches.rst +++ b/Documentation/translations/it_IT/process/submitting-patches.rst @@ -691,16 +691,6 @@ un luogo pubblico, ma gli indirizzi email usati lì sono privati; quindi non esponeteli nelle etichette, a meno che la persona non li abbia già usati in contributi precedenti. -Usare Assisted-by: -------------------- - -Se avete usato un qualsiasi tipo di strumento di assistenza avanzata alla -scrittura del codice per la creazione della vostra patch, dovete darne atto -aggiungendo un'etichetta Assisted-by. Non farlo può ostacolare -l'accettazione del vostro lavoro. Fate riferimento a -Documentation/process/coding-assistants.rst per i dettagli su come dare -atto dell'uso di assistenti alla scrittura del codice. - .. _it_the_canonical_patch_format: Il formato canonico delle patch diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl index 8a7787d228a63d..c9840f5219c2a9 100755 --- a/scripts/checkpatch.pl +++ b/scripts/checkpatch.pl @@ -655,7 +655,6 @@ sub hash_show_words { Reviewed-by:| Reported-by:| Suggested-by:| - Assisted-by:| To:| Cc: )}; @@ -3124,16 +3123,6 @@ sub process { } } - # Assisted-by uses a free-form value (e.g. "LLM"), not an - # email address, so skip the email format checks below. - if ($sign_off =~ /^Assisted-by:/i) { - if ($email =~ /^\s*$/) { - WARN("BAD_SIGN_OFF", - "Assisted-by requires a value\n" . $herecurr); - } - next; - } - my ($email_name, $name_comment, $email_address, $comment) = parse_email($email); my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment)); if ($suggested_email eq "") { From 1b775b3b098215aa980613c02314b5849b017b8f Mon Sep 17 00:00:00 2001 From: Kyle Arrington Date: Sat, 21 Nov 2026 10:49:45 -0600 Subject: [PATCH 0190/1514] CONTRIBUTING: say where an LLM's help is disclosed Reviews here ask for the disclosure as the last line of the pull request description, in the form "Assisted-by: LLM (:)", and for commits that carry only the human Signed-off-by. Nothing in the tree said so: until the previous commit, coding-assistants.rst asked for an Assisted-by tag in the commit itself. Mainline now leaves the disclosure to the cover letter, and a pull request description is this tree's cover letter. Write down the form reviews use. Signed-off-by: Kyle Arrington --- CONTRIBUTING.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f20ec244cf27c7..dfcc3235129d40 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -79,3 +79,17 @@ or sensitive, say so rather than substituting data from another Mac. For kernel patches, also follow the existing [kernel submission guidance](Documentation/process/submitting-patches.rst). + +## Pull requests made with an LLM + +Say in the pull request description how an LLM or other tool helped (see +[generated-content.rst](Documentation/process/generated-content.rst)), and end +the description with one line: + +``` +Assisted-by: LLM (:) +``` + +Commits carry only the human author's `Signed-off-by`, with no `Assisted-by`, +`Co-developed-by` or `Co-Authored-By` for a tool: only a human can certify the +DCO ([coding-assistants.rst](Documentation/process/coding-assistants.rst)). From 6ff796772cc1797c2e6cc26f8aa88110c4e94a07 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 18 Nov 2026 14:12:59 -0300 Subject: [PATCH 0191/1514] drm/asahi: g17: handle GPU completions in the submitter's cluster on every G17 On the M4 Pro (T6040) the GPU's mailbox IRQ is taken on CPU0 and its thread stays in P-cluster 0 (cpus 0,5-8). The event work ran on that thread's CPU, so an app on P-cluster 1 or the E-cores had every completion handled in another cluster. A depth-1 compute submit ioctl took 9 us from P-cluster 0, 12 us from P-cluster 1 and 16 us from an E-core, and an unpinned app hardly ever ran on P-cluster 0. Queue the event work at the CPU that last published work when that CPU is in another cluster than the one queueing it, and on the queueing CPU otherwise. Moving it unconditionally, to an unbound queue's worker in the submitter's L2 as the M5 does, took the IRQ-to-event-work time from 4 to 9-12 us even with everything in P-cluster 0, since a worker had to be woken elsewhere for each completion. Record the publishing CPU in the direct compute and render publishers too: most G17P work is published there, and only the device-mutex publishers did, from the scheduler's workers. Give every G17 the M5's scheduler queues restricted to their creator's cluster. The cluster is the one the device tree's cpu-map describes. t8142.dtsi (J704; only t8142-j813-j815.dtsi has one) and t6050-ultra.dtsi (J775d) have no cpu-map, so there each CPU is its own cluster. A scheduler queue then stays unrestricted instead of being tied to the one CPU that created it, as the M5 path did before, and the event work moves to the submitting CPU whenever another CPU queues it. The M5's unbound queue already ran the work in the queueing CPU's pod when that is the submitter's, so it behaves as before. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 9 ++++- drivers/gpu/drm/asahi/g17/mod.rs | 37 +++++++++---------- drivers/gpu/drm/asahi/g17/runtime.rs | 1 + drivers/gpu/drm/asahi/g17/runtime/backend.rs | 2 +- .../drm/asahi/g17/runtime/render/direct.rs | 1 + 5 files changed, 27 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index f5ddc1419361a8..adc3582b68180e 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -323,7 +323,7 @@ pub(crate) trait Backend: Send + Sync { /// The device accepts command submission (an M5 GPU before its queues take submission /// does not). fn supports_submission(&self) -> bool { true } - /// Whether this backend's scheduler workers run in their queue creator's cluster (M5). + /// Whether this backend's scheduler workers run in their queue creator's cluster. fn creator_cluster_scheduling(&self) -> bool { false } /// Whether to keep compute input completion waits and wait on the host for other-engine /// prefix producers: without the G17D forms an M5 kick may start while its ring @@ -560,7 +560,12 @@ impl Scheduler { // The run and free work stays in the creating CPU's cluster, as the event work // follows the submitter, instead of wherever an unbound worker last ran. let queue = workqueue::OwnedQueue::new_ordered_reclaim(name)?; - queue.restrict(Cpumask::cluster_of(CpuId::current()))?; + let cluster = Cpumask::cluster_of(CpuId::current()); + // Without a cpu-map in the device tree each CPU is its own cluster: the queue then + // stays unrestricted rather than tied to the one CPU that created it. + if cluster.weight() > 1 { + queue.restrict(cluster)?; + } Some(queue) } else { // drm_sched allocates its own ordered reclaim-safe queue. diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..881b09d9536551 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1259,15 +1259,12 @@ struct Shared { /// step). Publishers without the device mutex set it too. governor_activity_ns: AtomicU64, /// The queue of all work that signals job fences: the event work, and every scheduler's - /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe. On M5 it is - /// unbound, so the event work runs in the affinity pod (the L2) of the CPU that last - /// published work, not on whichever CPU the completion IRQ thread first ran on; on a two-die - /// part that keeps completion processing on the submitter's die. Elsewhere it is per-CPU and - /// high priority, as `system_highpri_wq`. + /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe, and high + /// priority. The event work runs in the cluster of the CPU that last published work, not + /// wherever the completion IRQ thread first ran (see `queue_event_records`). On M5 it is + /// unbound, so a worker of that CPU's affinity pod (its L2) runs it; elsewhere it is per-CPU. events: Arc, - /// M5: the event work and the scheduler workers follow the submitting CPU. - follows_submitter: bool, - /// M5: the CPU of the last publication, `u32::MAX` before the first. + /// The CPU of the last publication, `u32::MAX` before the first. submitter: AtomicU32, #[pin] grow: Work, @@ -1445,10 +1442,14 @@ impl Shared { if !self.submission_enabled { return; } - // Already queued if this fails, which is just as good. + // Here when the submitter shares this CPU's cluster: waking a worker elsewhere would only + // add a wakeup to every completion. Already queued if this fails, which is just as good. + let here = kernel::cpu::CpuId::current(); let _ = match self.submitter() { - Some(cpu) => self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone()), - None => self.events.enqueue::, EVENT_WORK>(self.clone()), + Some(cpu) if !kernel::cpumask::Cpumask::cluster_of(here).test(cpu) => { + self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone()) + } + _ => self.events.enqueue::, EVENT_WORK>(self.clone()), }; } @@ -1457,15 +1458,12 @@ impl Shared { self.events.clone() } - /// Whether the event work and the scheduler workers follow the submitting CPU (M5). - pub(super) fn follows_submitter(&self) -> bool { - self.follows_submitter - } - - /// Records the publishing CPU for the event work's placement (M5). + /// Records the publishing CPU for the event work's placement. fn note_submitter(&self) { - if self.follows_submitter { - self.submitter.store(kernel::cpu::CpuId::current().as_u32(), Ordering::Relaxed); + let cpu = kernel::cpu::CpuId::current().as_u32(); + // The completion side reads this line; write it only when the submitter moves. + if self.submitter.load(Ordering::Relaxed) != cpu { + self.submitter.store(cpu, Ordering::Relaxed); } } @@ -1795,7 +1793,6 @@ impl Gpu { governor_armed: AtomicBool::new(false), governor_activity_ns: AtomicU64::new(0), events, - follows_submitter: m5, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), reclaim_work <- new_work!("g17::Shared::reclaim_work"), diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93b..2f836e454f2b1c 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2062,6 +2062,7 @@ impl Backend { if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Compute) { Ok(_) => {} diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 278534899b570a..96a612877583f9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -123,7 +123,7 @@ impl Backend { impl job::Backend for Backend { fn creator_cluster_scheduling(&self) -> bool { - self.shared.follows_submitter() + true } fn host_producer_waits(&self) -> bool { self.shared.m5_board.is_some_and(|board| !board.g17d_forms() && !board.completion_inputs()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 117edccb28e350..03daa3a31341c1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -303,6 +303,7 @@ impl Backend { if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Render) { Ok(_) => {} From e2ef1ab403d7d2e767ca80ee36842fa4a14b0faa Mon Sep 17 00:00:00 2001 From: Kyle Arrington Date: Sat, 21 Nov 2026 11:22:04 -0600 Subject: [PATCH 0192/1514] CONTRIBUTING: link the organisation's pull request rules The rules the previous commit wrote down are kept for every Aurora Silicon repository in aurora-silicon/agent-guidelines, with the pre-PR checklist the reviews apply. Link them instead of keeping a copy that can drift. Signed-off-by: Kyle Arrington --- CONTRIBUTING.md | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dfcc3235129d40..40d5801accfcee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -80,16 +80,10 @@ or sensitive, say so rather than substituting data from another Mac. For kernel patches, also follow the existing [kernel submission guidance](Documentation/process/submitting-patches.rst). -## Pull requests made with an LLM +## Pull request rules -Say in the pull request description how an LLM or other tool helped (see -[generated-content.rst](Documentation/process/generated-content.rst)), and end -the description with one line: - -``` -Assisted-by: LLM (:) -``` - -Commits carry only the human author's `Signed-off-by`, with no `Assisted-by`, -`Co-developed-by` or `Co-Authored-By` for a tool: only a human can certify the -DCO ([coding-assistants.rst](Documentation/process/coding-assistants.rst)). +Aurora Silicon's rules for pull requests, including how to disclose an LLM's +help and what commits carry, are in +[aurora-silicon/agent-guidelines](https://github.com/aurora-silicon/agent-guidelines). +Run its [pre-PR checklist](https://github.com/aurora-silicon/agent-guidelines/blob/main/pre-pr-checklist.md) +before opening one. From 45b05cdbf811c6fdfee92bdb0b5aa85f2aba2ce2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 13:01:05 -0500 Subject: [PATCH 0193/1514] 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 368b56149acc78..5adb19bb3d8202 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 529f9826e1635e..9e39f1e63b474a 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 afc8a973f77130..aab0cb7da89638 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 e65effb337aa82..a532b1c25864e6 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 0194/1514] 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 f9525c0c08f306..62dc0452e78183 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 9d005164e6de82..cdc4f27d19528c 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 6d18386727a7f3..fe5a7f2404a86e 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 f7f2cb25c56eab..91de8189abd8a2 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 9acbb4ac763a5a..0083f5cad939e1 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 353199dea75a1b..a55d7c9bd03083 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 ecdde0579133ab..f022689ad08789 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 5e3346e3cf1e23..ae07876b3b45bf 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 0d127b8a5f8175..d1d34b6245f522 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 36574512d4298f..0daa8ffdcd8d81 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 0195/1514] 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 a2b329789444cc..ea6f6882eff6a1 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 5ee33d71432d1a..c431061332cecd 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 813e52d886fdcb..07317ee4663dc1 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 31f06c80ab8bf5..d79d5892d31f49 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 f161b218a0d06b..b3dbc6bd3c73b8 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 d2ef01e26b3a3d..bcf52a272ca928 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 4e9bfaef02e12f..e384e30a024116 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 d4a85cc6f3d361..739cfd1510de4b 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 baf623b2722d78..2f156546ab3077 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 41da5b94c7c500..ada1946bb79835 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 b0fc2ed96976cc..18975b812e2768 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 77c47f0770492f..63238572b27eee 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 b4a48ed2907ae1..f04d6add674f89 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 5bb4f434454ccc..0367a4421554c0 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 a048447b1436a7..01e6176bdea5ec 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 add96b48bb3357..96d3238471635f 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 0196/1514] 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 804703b19cecc7..d885732c02194f 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 1824cd255358ab..7c64913aa69bf0 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 91de8189abd8a2..fdef6c7c908dad 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 7e67501a4c8c75..b01a419641a027 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 a9bf84943b8054..af7c52237c5cd6 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 08a4f9ee9cefd9..fe307dcfce52c8 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 b054ec08198b74..d949013e462060 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 c431061332cecd..691fc1dc42a59c 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 9b5ae1e7c4b08c..395b82134bcdb6 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 344dd3da370615..e3c95e27567209 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 0083f5cad939e1..3b74ce8736f4a7 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 77984b8cb57856..eaa924962befea 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 ef54552540d7b5..faa407bceb4c46 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 d7d9b40438b2e8..c45d6772038f82 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 5adb19bb3d8202..80bf1ff79a2b4f 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 00000000000000..fb788f85fce967 --- /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 19405185174d16..43e3bf90e24cd5 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 a55d7c9bd03083..4c30ad932be62b 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 f022689ad08789..01861b790a62d1 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 0f26cb32767384..24b8dd2de3fb03 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 e384e30a024116..d9dabde95472b9 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 ae07876b3b45bf..1de8da0bdcc4c9 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 18975b812e2768..f1aa0f417c028f 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 4d8bcb716eda5b..413c2be0ecef23 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 e264e319c2a649..74b8fd7a434178 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 72ca9cb94b8467..b49944399e8a4d 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 2a18ebbeb5d9cc..7118cffde33013 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 0197/1514] 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 00000000000000..2ef40886e69c55 --- /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 29b51ee5cefafc..52787524d33f41 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 97d526fbf504f8..03ab056cc5e465 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 00000000000000..fa6239d6f8a7ac --- /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 0daa8ffdcd8d81..667b38a0998d6a 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 6f388b4693fd41..d59521d36719bc 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 36f4cdeac268e4..031d918925c002 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 fc1682600f23f3..41a8c1a9dd217d 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 9a159e849e86b5..2abd69cf194e18 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 2c98ab19a751af..7553c91f4ffc8f 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 99caca85e8631c70dedabf14ec3377bf4c2445fb Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 10 Nov 2026 23:52:03 -0800 Subject: [PATCH 0198/1514] arm64: dts: apple: t6050-ultra: Describe the CPU clusters, so the scheduler gets the M5 Ultra's M and P core capacities (754 and 1024, not 1024 on all thirty) The M5 Ultra's CPU nodes have no cpu-map, so Linux sees thirty CPUs in one package with no clusters. parse_dt_topology() reads capacity-dmips-mhz only while it walks cpu-map, so the M and P core capacities that t6050-base.dtsi gives every T6050 CPU (dj's #1399) never reach the scheduler: on the J775D (Mac Studio) every CPU reports cpu_capacity 1024, and cluster_cpus_list reads thirty clusters of one. Describe the six clusters the way the one-die description does, commit 68c10dd872af ("arm64: dts: apple: t6050: Describe the CPU clusters"): MPIDR Aff1 0, 1 and 2 are die 0's M0, M1 and P clusters and 0x10, 0x11 and 0x12 are die 1's, five cores each, as the ADT's cluster-id and die-id give them. The clusters are listed flat, cluster0-2 on die 0 and cluster3-5 on die 1, as the M1 and M2 Ultra descriptions (t6002.dtsi, t6022.dtsi) list theirs; the topology parser does not support clusters of clusters. The boot loader prunes the entries of cores it did not start. The capacities in t6050-base.dtsi are kept as they are. The caches are described already: dj's commit 1bd5f40e4f29 ("arm64: dts: apple: t6050: Describe the CPU caches") gives each cluster its L2 and points each CPU's next-level-cache at it, and each cluster here is the set of CPUs that share one of those L2s. Only t6050-j775d.dts includes t6050-ultra.dtsi, so the J775D is the only board whose device tree changes: the ten other T6050 board device trees (J714c, J714s, J716c, J716s, J775c, J873s, K114c, K114s, K116c, K116s) are byte-identical with and without the series. The one-die description (t6050-max.dtsi) has its cpu-map already; this commit leaves it unchanged. Testing, on J775D, integration/aurora's head of 2026-11-21 (a84637dc, the merge of #2654), one boot with and one without the series, both with a local display fix that is not part of it: cpu_capacity reads 754 on the twenty M cores and 1024 on the ten P cores (1024 on all thirty without), and cluster_cpus_list reads six lists of five (thirty lists of one without). Each CPU's L2 reads the same either way: 8 MiB or 16 MiB, shared by its own cluster's five. Signed-off-by: Jeff Queisser --- arch/arm64/boot/dts/apple/t6050-ultra.dtsi | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi index e9f0279e9373db..449708caa229b3 100644 --- a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi @@ -57,6 +57,121 @@ T6050_P_CPU(cpu32, 11202, cpufreq_pc_die1, l2_cache_pc_die1); T6050_P_CPU(cpu33, 11203, cpufreq_pc_die1, l2_cache_pc_die1); T6050_P_CPU(cpu34, 11204, cpufreq_pc_die1, l2_cache_pc_die1); + + /* + * The clusters are MPIDR Aff1 (die 0's M0, M1 and P, then die 1's), each with its + * own L2. They are listed flat, as on the other two-die parts. The boot loader + * prunes the entries of cores it did not start. + */ + cpu-map { + cluster0 { + core0 { + cpu = <&cpu0>; + }; + core1 { + cpu = <&cpu1>; + }; + core2 { + cpu = <&cpu2>; + }; + core3 { + cpu = <&cpu3>; + }; + core4 { + cpu = <&cpu4>; + }; + }; + + cluster1 { + core0 { + cpu = <&cpu6>; + }; + core1 { + cpu = <&cpu7>; + }; + core2 { + cpu = <&cpu8>; + }; + core3 { + cpu = <&cpu9>; + }; + core4 { + cpu = <&cpu10>; + }; + }; + + cluster2 { + core0 { + cpu = <&cpu12>; + }; + core1 { + cpu = <&cpu13>; + }; + core2 { + cpu = <&cpu14>; + }; + core3 { + cpu = <&cpu15>; + }; + core4 { + cpu = <&cpu16>; + }; + }; + + cluster3 { + core0 { + cpu = <&cpu18>; + }; + core1 { + cpu = <&cpu19>; + }; + core2 { + cpu = <&cpu20>; + }; + core3 { + cpu = <&cpu21>; + }; + core4 { + cpu = <&cpu22>; + }; + }; + + cluster4 { + core0 { + cpu = <&cpu24>; + }; + core1 { + cpu = <&cpu25>; + }; + core2 { + cpu = <&cpu26>; + }; + core3 { + cpu = <&cpu27>; + }; + core4 { + cpu = <&cpu28>; + }; + }; + + cluster5 { + core0 { + cpu = <&cpu30>; + }; + core1 { + cpu = <&cpu31>; + }; + core2 { + cpu = <&cpu32>; + }; + core3 { + cpu = <&cpu33>; + }; + core4 { + cpu = <&cpu34>; + }; + }; + }; }; /* One L2 per cluster (t6050-base.dtsi, "Caches"). */ From 107d80fbea8d4a61e14a4803b2002e3d321dd541 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Wed, 11 Nov 2026 21:44:49 -0800 Subject: [PATCH 0199/1514] dt-bindings: gpu: apple,agx: Accept the M5 Ultra's GPU (apple,agx-g17d), so the Mac Studio's GPU can be described The M5 Ultra has the T6050's GPU on two dies (G17D). The driver matches the family name "apple,agx-g17s" and tells the M5 parts apart by the GPU's ID registers, so the Ultra needs no entry of its own there, but its device tree should say which part it is. Allow "apple,agx-g17d" with "apple,agx-g17s" as its fallback, beside the M5 Max's "apple,agx-g17c" that ewb's commit 4c7fdf1d3b57 ("dt-bindings: gpu: apple: Describe the J716c GPU and panel handoff") added: his entry becomes a list of two names, the form the G13 and G14 parts already use (apple,agx-g13c and apple,agx-g13d, apple,agx-g14c and apple,agx-g14d). The M5 Ultra's GPU node has the M5 Pro's hand-off shape: one "sgx" range, the two firmware mailboxes and the six reserved regions, and no operating-point tables. Since sithglan's commit 8f418a490a97 ("dt-bindings: gpu: apple,agx: Tell the two G17S layouts apart") that entry applies to a node whose only compatible is "apple,agx-g17s", so apply it to a node with "apple,agx-g17d" as well. A node with only "apple,agx-g17s" and a "apple,agx-g17c" node take the entries they took before, and no existing device tree uses the new name. Signed-off-by: Jeff Queisser --- .../devicetree/bindings/gpu/apple,agx.yaml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Documentation/devicetree/bindings/gpu/apple,agx.yaml b/Documentation/devicetree/bindings/gpu/apple,agx.yaml index 7794c0e13b9395..1829e74c572871 100644 --- a/Documentation/devicetree/bindings/gpu/apple,agx.yaml +++ b/Documentation/devicetree/bindings/gpu/apple,agx.yaml @@ -25,7 +25,9 @@ properties: - apple,agx-t8140 - apple,agx-t8142 - items: - - const: apple,agx-g17c + - enum: + - apple,agx-g17c + - apple,agx-g17d - const: apple,agx-g17s - items: - const: apple,agx-t8103 @@ -267,12 +269,15 @@ allOf: - if: properties: compatible: - const: apple,agx-g17s + anyOf: + - const: apple,agx-g17s + - contains: + const: apple,agx-g17d then: description: - The M5 Pro GPU uses one MMIO range and two firmware mailbox roles. - Its firmware graph supplies the performance tables, so it has no - operating-point table in the board DT. + The M5 Pro and M5 Ultra GPUs use one MMIO range and two firmware + mailbox roles. Their firmware graph supplies the performance tables, + so they have no operating-point table in the board DT. properties: reg: maxItems: 1 From 0a83dd0372e11ee5e49d016384ad69d4d174937e Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 10 Nov 2026 23:07:02 -0800 Subject: [PATCH 0200/1514] arm64: dts: apple: t6050-j775d: Give the Mac Studio (M5 Ultra) a working GPU: describe it for the boot loader's handoff The GPU driver has the M5 Ultra's configuration, but the J775D device tree leaves the GPU and both GPU coprocessor nodes of the inventory disabled, with no mailboxes and no reservations, so the Mac Studio boots without a render node and its desktop session cannot start. Add t6050-j775d-gpu.dtsi in the shape of dj's t6050-j714s-gpu-panel.dtsi, commit 32a31cfb06e7 ("arm64: dts: apple: t6050-j714s: Describe the GPU and panel handoff"): the "gpu" alias, the six reservations the boot loader fills, the two firmware mailboxes in place of the inventory's coprocessor nodes, GPX and AFR held on, and the GPU node's handoff properties. The J775D ADT gives the same addresses and interrupts as J714s's: both firmware roles and their mailboxes are on die 0. Two things differ from the J714s file: - no panel or display part: the Studio's display chain is described already; - the part's name, "apple,agx-g17d", with the "apple,agx-g17s" fallback the driver and the boot loader match. The GPU part now reads much the same in four board files: the J714s, J716c and K114c GPU files and this one. It could be one shared file that they include; this leaves the others as they are. Everything stays disabled in the source: the boot loader enables the nodes after checking the ADT and the GPU firmware build. A loader that does not know the Ultra's build leaves the GPU off, as today. Only t6050-j775d.dts includes the new file. Testing, on J775D, integration/aurora's head of 2026-11-14 (the merge of #1901) with this series, in six boots: one through aura main with the loader's own pull request ("kboot: T6050: hand the M5 Ultra's GPU to Linux instead of refusing its firmware build"), the kernel uploaded over USB, and five through a boot loader that also hands over the display. In each the loader reports the GPU enabled, the driver probes 2300000000.gpu with both firmware roles' initdata acknowledged, and a render node appears, where integration's head has none; the compute and chained-submit checks pass, 46 concurrent clients pass, and a 628-case render CTS subset reads 571 pass and 57 not supported, with no GPU recovery, fault or timeout in the kernel log. The ten other T6050 board device trees (J714c, J714s, J716c, J716s, J775c, J873s, K114c, K114s, K116c, K116s) and T8142's J704, J813 and J815 are byte-identical with and without the series. Signed-off-by: Jeff Queisser --- .../arm64/boot/dts/apple/t6050-j775d-gpu.dtsi | 120 ++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-j775d.dts | 2 + 2 files changed, 122 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi new file mode 100644 index 00000000000000..8b64a03432d965 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-j775d-gpu.dtsi @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J775D GPU (G17D), for the boot loader's GPU handoff, as + * t6050-j714s-gpu-panel.dtsi describes the J714s's. Everything here stays + * disabled: the loader checks the ADT and the live GPU firmware state, fills + * the GPU reservations, and only then enables the nodes, the GPU last. A + * loader without the handoff, or one whose checks fail, leaves the GPU off. + * + * Values are from the J775DAP 27.0 ADT (sgx, gfx-asc, gfx1-asc, pmgr). Both + * firmware roles, their mailboxes and the GPU node are die 0's, with the + * addresses and interrupts of a one-die T6050; die 1 adds only its power + * states (t6050-ultra.dtsi). + */ + +/ { + aliases { + /* The loader finds the GPU through this alias */ + gpu = &sgx; + }; + + reserved-memory { + /* Filled and enabled by the loader from the ADT */ + gpu_fw_text: gpu-fw-text { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + gpu_fw_data: gpu-fw-data { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_ttbs: uat-ttbs { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_pagetables: uat-pagetables { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_l2_pagetables: uat-l2-pagetables { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + + uat_handoff: uat-handoff { + reg = <0 0 0 0>; + no-map; + status = "disabled"; + }; + }; +}; + +/* The inventory ASC nodes; the mailboxes below describe the same windows. */ +/delete-node/ &gfx_asc; +/delete-node/ &gfx1_asc; + +&{/soc} { + /* + * ADT gfx-asc and gfx1-asc at their physical windows: the wrapper, the + * 8-byte iop-vbar, and their second and third interrupts (send-empty, + * recv-not-empty), as T8140/T8142. + */ + gfx_mbox: mailbox@2302600000 { + compatible = "apple,t6050-j775d-ascwrap-v6"; + reg = <0x23 0x2600000 0x0 0x88000>, + <0x23 0x2050000 0x0 0x8>; + reg-names = "wrapper", "iop-vbar"; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + apple,firmware-role = "GFX"; + power-domains = <&ps_gfx>; + #mbox-cells = <0>; + status = "disabled"; + }; + + gfx1_mbox: mailbox@2302e00000 { + compatible = "apple,t6050-j775d-ascwrap-v6"; + reg = <0x23 0x2e00000 0x0 0x88000>, + <0x23 0x2850000 0x0 0x8>; + reg-names = "wrapper", "iop-vbar"; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + apple,firmware-role = "GFX1"; + power-domains = <&ps_gfx>; + #mbox-cells = <0>; + status = "disabled"; + }; +}; + +/* The ADT marks GPX and AFR, GFX's parents, critical. */ +&ps_gpx { + apple,always-on; +}; + +&ps_afr { + apple,always-on; +}; + +&sgx { + compatible = "apple,agx-g17d", "apple,agx-g17s"; + /* ADT sgx reg[0]; the driver maps the first 16 MiB as "sgx" */ + reg = <0x23 0x0 0x0 0x3fdc000>; + reg-names = "sgx"; + /delete-property/ interrupts; + mboxes = <&gfx_mbox>, <&gfx1_mbox>; + memory-region = <&uat_ttbs>, <&uat_pagetables>, <&uat_handoff>, + <&gpu_fw_data>, <&uat_l2_pagetables>, <&gpu_fw_text>; + memory-region-names = "ttbs", "pagetables", "handoff", "fw-data", + "l2-pagetables", "fw-text"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index 38923533c5f4c7..4d527a6417f830 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -637,3 +637,5 @@ #define T6050_J775D #include "t6050-peripherals.dtsi" + +#include "t6050-j775d-gpu.dtsi" From f52bf1b7895ace43d5e7be6af537eb7286777a20 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 18 Nov 2026 14:24:00 -0300 Subject: [PATCH 0201/1514] drm/asahi: g17: judge a page fault without a latched MMU fault like a timeout On 2026-11-18 at 16:39:57 UTC one deqp-vk hang (memory_model u64 atomics, a fragment shader spinning on a lock) cost T3 Code and Hyprland their devices, and the desktop with them. The first restart failed deqp-vk's interrupted render, as it should. Its next queued render spun again, and 83 ms later the firmware blamed T3 Code's queue 40, whose render was waiting behind it, then Hyprland's queue 36, whose oldest render had never started. Both took EIO, which marks the VM lost. The checks that catch a starved bystander did not run. Every one of those restarts read reason 3, page fault, and for a page fault host_fallback keeps the firmware's blame. fault_override needs a decoded MMU fault, and both fault banks read clear. The same spin on the same boot at 03:40 UTC read reason 0. host_fallback then moved the blame to deqp-vk's running render, and nothing else failed. The reason word is not this restart's. The firmware (here 25G83) writes it only for some restarts, and nothing clears it. Reason 0 shows only in a boot's first recoveries. A real page fault at 04:30 left it at 3 for every later spin. Every other reason-3 recovery on record has a decoded fault in at least one bank (04:30 and two on 11-17), because the faulting access stays latched until the restart. Whenever the reason comes from the firmware's reason word, read the fault banks while the firmware is halted. When the word says page fault but neither bank holds a valid fault, treat the restart as a non-fault restart: slot identity and the host's pass records may correct the firmware's blame, as they do for a timeout. A latched fault in either bank keeps the page-fault handling unchanged. The latch belongs to the MMU, not to a firmware build, so the check runs on every firmware that has the word, the A18 Pro's 26A428 included. M5 has no reason word: its page fault comes from its latched fault register and is not checked against the banks. Sources::settle_reason holds that rule in one place. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/recovery.rs | 2 +- .../gpu/drm/asahi/g17/recovery/attribution.rs | 99 ++++++++++++++++++- drivers/gpu/drm/asahi/g17/runtime/events.rs | 6 +- 3 files changed, 98 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 3c59030544d5ed..62d337a03e99a3 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -11,7 +11,7 @@ mod attribution; mod slot; mod safety; pub(crate) use safety::{note_retired, since_retired}; -pub(crate) use attribution::{fault_qids, Record, Sources, PAGE_FAULT}; +pub(crate) use attribution::{fault_qids, Record, Sources}; use attribution::Attribution; pub(super) fn slot_key(slot: usize, slot_keys: Option) -> Option { diff --git a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs index 8047cfa31620b9..403eb311f8979b 100644 --- a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs +++ b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs @@ -58,6 +58,8 @@ pub(crate) struct Sources { mask: u32, records: [Source; SLOTS], count: usize, + /// `reason` reads PAGE_FAULT, but no MMU fault bank holds a fault (`check_fault_banks`). + stale_fault: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -106,6 +108,7 @@ impl Sources { mask, records: [Source::default(); SLOTS], count: 0, + stale_fault: false, }; for slot in 0..SLOTS { if mask & (1 << slot) == 0 { @@ -132,6 +135,40 @@ impl Sources { self.reason.or(self.record.map(|record| record.reason)) } + /// Completes the reason of `InitData::fault_sources`. M5 attribution leaves the firmware + /// reason out: its latched MMU fault register (`mmu_fault`) gives reason 3. A reason read + /// from the firmware's reason word is checked against the MMU fault banks (`banks`, read + /// while the firmware is halted) on every firmware ([`Self::check_fault_banks`]). + pub(crate) fn settle_reason(&mut self, mmu_fault: bool, banks: impl FnOnce() -> Option<[(u64, u64); 2]>) { + if self.reason.is_some() { + if let Some(banks) = banks() { + self.check_fault_banks(&banks); + } + } else if mmu_fault { + self.reason = Some(PAGE_FAULT); + } + } + + /// The firmware writes its reason word only for some restarts, and nothing clears it: after + /// a page fault, every later restart it gives no reason for still reads PAGE_FAULT + /// (2026-11-18, 25G83: a deqp-vk spin read 0 before the boot's first page fault, 3 after + /// it). A page fault keeps its access latched in an MMU fault bank until the restart, so + /// when both banks read clear the reason is an earlier restart's and this one is no page + /// fault. + fn check_fault_banks(&mut self, banks: &[(u64, u64); 2]) { + if self.reason == Some(PAGE_FAULT) + && banks.iter().all(|&(status, address)| crate::regs::decode_fault(status, address, true).is_none()) + { + kernel::pr_warn!("G17: recovery reason {} without a latched MMU fault is left over from an earlier restart\n", + PAGE_FAULT); + self.stale_fault = true; + } + } + + fn page_fault(&self) -> bool { + self.reason == Some(PAGE_FAULT) && !self.stale_fault + } + pub(super) fn attribute( &mut self, blamed: Option, @@ -148,7 +185,7 @@ impl Sources { source.started = started(qid, source.stamp); } } - if self.reason == Some(PAGE_FAULT) || self.mask.count_ones() < 2 { + if self.page_fault() || self.mask.count_ones() < 2 { return Attribution::Firmware; } let Some(blamed) = blamed else { @@ -188,7 +225,7 @@ impl Sources { attribution: Attribution, culprit: impl FnOnce() -> Option, ) -> Attribution { - if attribution != Attribution::Firmware || self.reason.is_none_or(|reason| reason == PAGE_FAULT) { + if attribution != Attribution::Firmware || self.reason.is_none() || self.page_fault() { return attribution; } culprit().map_or(Attribution::Firmware, Attribution::Queues) @@ -206,7 +243,7 @@ impl Sources { slots: u64, culprit: impl FnOnce(u64) -> Option, ) -> Attribution { - if self.reason != Some(PAGE_FAULT) || attribution != Attribution::Firmware || slots == 0 { + if !self.page_fault() || attribution != Attribution::Firmware || slots == 0 { return attribution; } let Some(blamed) = blamed else { @@ -327,6 +364,62 @@ mod tests { Attribution::NoCulprit); } + #[test] + fn a_page_fault_reason_without_a_latched_fault_is_judged_like_a_timeout() { + // 2026-11-18 16:39:57 UTC: deqp-vk's spinning renders (queues 84/85, failed by the + // first restart) kept hanging the GPU; the reason word still read the page fault of + // 04:30, both banks were clear, and the firmware blamed T3 Code's queue 40, then + // Hyprland's 36. Both lost their device. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.check_fault_banks(&[(0, 0); 2]); + let attribution = sources.attribute(Some(40), |_, _| panic!("unknown key")); + assert_eq!(attribution, Attribution::Firmware); + assert_eq!(sources.host_fallback(attribution, || Some(3 << 84)), Attribution::Queues(3 << 84)); + assert_eq!(sources.fault_override(attribution, Some(40), 0, |_| panic!("no fault")), + Attribution::Firmware); + } + + #[test] + fn only_a_reason_from_the_firmware_word_is_checked_against_the_banks() { + // Any firmware's reason word: clear banks show a left-over page fault. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.settle_reason(false, || Some([(0, 0); 2])); + assert!(sources.stale_fault); + // Unreadable banks leave it a page fault. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.settle_reason(false, || None); + assert!(sources.page_fault()); + // M5 has no reason word: its latched fault register is the page fault, never judged + // by the banks. + let mut sources = Sources::sample(0b10, |_| None); + sources.settle_reason(true, || panic!("M5 fault checked against the banks")); + assert!(sources.page_fault()); + // No reason and no latched fault stays unknown. + let mut sources = Sources::sample(0b10, |_| None); + sources.settle_reason(false, || panic!("no reason to check")); + assert_eq!(sources.reason, None); + } + + #[test] + fn a_latched_fault_in_either_bank_keeps_the_page_fault() { + // 2026-11-17 18:27:07 UTC: reason 3, bank 0 clear, bank 1 an unmapped UL1C read. + for banks in [[(0, 0), (0x84e926e311, 0x40f00003d80 >> 6)], [(0x8f0779c411, 0), (0, 0)]] { + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(PAGE_FAULT); + sources.check_fault_banks(&banks); + assert_eq!(sources.host_fallback(Attribution::Firmware, || panic!("page fault")), + Attribution::Firmware); + } + // Clear banks change no other reason. + let mut sources = Sources::sample(0b10, |_| Some((0, 2))); + sources.reason = Some(2); + sources.check_fault_banks(&[(0, 0); 2]); + assert!(!sources.stale_fault); + } + /// The in-flight work of 2026-11-06 12:37:58: WoW's render pair (QIDs 65 and 66, four /// renders in context 19) and a compute test's queue 60 in context 17. fn incident(slots: u64) -> Option { diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 24bf7c382ecf46..4a5112b0fb0d73 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -168,11 +168,7 @@ impl recovery::Memory for Service<'_> { } } let mut sources = self.firmware.init.fault_sources()?; - // M5 attribution leaves the firmware reason out (see InitData::fault_sources); a - // latched MMU fault is reason 3. - if mmu_fault && sources.reason.is_none() { - sources.reason = Some(recovery::PAGE_FAULT); - } + sources.settle_reason(mmu_fault, || self.firmware.port.fault_banks().ok()); Ok(sources) } From d289ed035fb396c308ba0b808d99734aab1e2fa7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Thu, 19 Nov 2026 07:46:10 -0500 Subject: [PATCH 0202/1514] PCI: apple: wake on a root port's PME (Wake-on-LAN on the M4 Mac mini) On T8132 a PME message a root port receives sets its Root Status PME bit, but the root port never raises its own interrupt, the PCIe port services' MSI, for it. The PME service then never runs: a device armed to wake the system (the Mac mini's BCM57762 with Wake-on-LAN) signals its PME and the system stays in suspend-to-idle until something else wakes it, and the Root Status stays set, holding back the next PME. The port's own interrupt status (PORT_INTSTAT) has bit 8 set exactly then: on a J773g in suspend-to-idle, after a magic packet the Ethernet root port 00:02.0 reads RootSta "PME ReqID 0200, PMEStatus+" with bit 8 set, while a suspend without one leaves both clear; the port services' vector counted no interrupt either way. Take bit 8 as the port's PME interrupt on every Apple PCIe root port. Its threaded handler, which runs through suspend, raises the root port's port services vector by hand (generic_handle_irq_safe()), so the PME service handles the request as if the MSI had come: it resumes or wakes the requester and clears the Root Status, and while the system sleeps the wake that vector is armed for (enable_irq_wake() at the PME service's suspend) takes place. Tested on a J773g (Mac mini M4), Ethernet with "ethtool -s end0 wol g": - rtcwake -m freeze with a 90 s alarm, one magic packet from another machine at 20 s: back on the network 4-5 s after the packet, 5 of 5 (three with rtcwake, two with systemctl suspend); /sys/power/pm_wakeup_irq is the port services' vector, the Root Status clear afterwards; - without the packet, the 90 s alarm wakes it as before. Signed-off-by: Diljit Singh --- drivers/pci/controller/pcie-apple.c | 73 ++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 8e20a36cc575e3..50b7a18f58e987 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -155,6 +155,11 @@ MODULE_PARM_DESC(t6050_sd_port_wake, #define PORT_INT_LINK_DOWN 14 #define PORT_INT_LINK_UP 12 #define PORT_INT_LINK_BWMGMT 11 +/* + * The root port received a PME message (it sets its Root Status PME bit too). + * The root port does not raise its own MSI for a PME (measured on T8132). + */ +#define PORT_INT_PME 8 #define PORT_INT_AER_MASK (15 << 4) #define PORT_INT_PORT_ERR 4 #define PORT_INT_INTx(i) i @@ -635,6 +640,8 @@ struct apple_pcie_port { struct apple_tunable *tunable; unsigned int irq; unsigned int link_irqs[2]; + /* PORT_INT_PME's interrupt (0: none), see apple_pcie_port_pme_thread() */ + unsigned int pme_irq; u32 saved_intmask; int sid_map_sz; struct gpio_desc *perst_gpio; @@ -1093,6 +1100,59 @@ static irqreturn_t apple_pcie_port_irq(int irq, void *data) return IRQ_HANDLED; } +/* + * A PME message reached the root port. Because the root port does not raise + * its own PCIe port services MSI for a PME (measured on T8132), forward the + * port's PME interrupt to that vector by hand: the PME service reads Root + * Status, resumes or wakes the requester, and while the system sleeps the wake + * that interrupt is armed for (enable_irq_wake() at the PME service's suspend) + * takes place. This is how a Wake-on-LAN packet ends suspend-to-idle. + */ +static irqreturn_t apple_pcie_port_pme_thread(int irq, void *data) +{ + struct apple_pcie_port *port = data; + struct pci_host_bridge *bridge = dev_get_drvdata(port->pcie->dev); + struct pci_dev *rp; + int vector; + + if (!bridge || !bridge->bus) + return IRQ_NONE; + rp = pci_get_slot(bridge->bus, PCI_DEVFN(port->idx, 0)); + if (!rp) + return IRQ_NONE; + vector = rp->msi_enabled || rp->msix_enabled ? pci_irq_vector(rp, 0) : rp->irq; + if (vector > 0) + generic_handle_irq_safe(vector); + else + dev_warn_ratelimited(port->pcie->dev, "%pOF: PME, but %s has no interrupt\n", + port->np, pci_name(rp)); + pci_dev_put(rp); + return IRQ_HANDLED; +} + +static int apple_pcie_port_register_pme(struct apple_pcie_port *port) +{ + struct irq_fwspec fwspec = { + .fwnode = &port->np->fwnode, + .param_count = 1, + .param = { [0] = PORT_INT_PME, }, + }; + int irq, ret; + + irq = irq_domain_alloc_irqs(port->domain, 1, NUMA_NO_NODE, &fwspec); + if (irq <= 0) + return irq ?: -ENOMEM; + /* Runs through suspend: it is what ends a suspend-to-idle for a PME. */ + ret = request_threaded_irq(irq, NULL, apple_pcie_port_pme_thread, + IRQF_ONESHOT | IRQF_NO_SUSPEND, "PME", port); + if (ret) { + irq_domain_free_irqs(irq, 1); + return ret; + } + port->pme_irq = irq; + return 0; +} + static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) { static struct { @@ -1102,7 +1162,7 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) { PORT_INT_LINK_UP, "Link up", }, { PORT_INT_LINK_DOWN, "Link down", }, }; - int i; + int i, ret; for (i = 0; i < ARRAY_SIZE(port_irqs); i++) { struct irq_fwspec fwspec = { @@ -1112,7 +1172,7 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) [0] = port_irqs[i].hwirq, }, }; - int irq, ret; + int irq; irq = irq_domain_alloc_irqs(port->domain, 1, NUMA_NO_NODE, &fwspec); @@ -1129,6 +1189,10 @@ static int apple_pcie_port_register_irqs(struct apple_pcie_port *port) port->link_irqs[i] = irq; } + ret = apple_pcie_port_register_pme(port); + if (ret) + dev_warn(port->pcie->dev, "%pOF: no PME interrupt: %d\n", port->np, ret); + return 0; } @@ -1144,6 +1208,11 @@ static void apple_pcie_port_unregister_irqs(struct apple_pcie_port *port) irq_domain_free_irqs(port->link_irqs[i], 1); port->link_irqs[i] = 0; } + if (port->pme_irq) { + free_irq(port->pme_irq, port); + irq_domain_free_irqs(port->pme_irq, 1); + port->pme_irq = 0; + } } /* From b50908437311deace3d03eb2d6e65e116ab6b31e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 23:22:24 +1100 Subject: [PATCH 0203/1514] PCI/ASPM: Enable L1 PM Substates and Clock PM where devicetree routes CLKREQ# On devicetree platforms the default ASPM policy enables L0s and L1 but leaves the L1 PM Substates and Clock PM off, because both need CLKREQ# between the two ports and the kernel cannot see whether it is routed. The devicetree can say so: "supports-clkreq" (pci-bus-common) states that CLKREQ# is routed from the root port to the downstream device. On links whose port node carries it, add the supported L1 PM Substates to the default ASPM states and enable Clock PM by default if both ends support it. Nothing changes for links without the property, "aspm-no-l1ss" and "aspm-no-l1" still win, and the policy knobs work as before. On an M3 MacBook Air (J615) the Wi-Fi/Bluetooth link then enters L1.1/L1.2 with Clock PM under the default policy, and s2idle draws 2.91 W instead of 3.09 W. Signed-off-by: Ryan Murray --- drivers/pci/pcie/aspm.c | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/drivers/pci/pcie/aspm.c b/drivers/pci/pcie/aspm.c index 3b02e794dbd740..13fcb0c919d8f3 100644 --- a/drivers/pci/pcie/aspm.c +++ b/drivers/pci/pcie/aspm.c @@ -923,14 +923,40 @@ static void pcie_aspm_override_default_link_state(struct pcie_link_state *link) link->aspm_default |= PCIE_LINK_STATE_L0S; if (link->aspm_support & PCIE_LINK_STATE_L1) link->aspm_default |= PCIE_LINK_STATE_L1; + /* + * L1 PM Substates need CLKREQ# between the two ports. Enable + * them by default only on links whose devicetree node says the + * signal is routed. + */ + if (pcie_link_has_aspm_override(link, "supports-clkreq")) + link->aspm_default |= link->aspm_support & PCIE_LINK_STATE_L1SS; override = link->aspm_default & ~link->aspm_enabled; if (override) - pci_info(pdev, "ASPM: default states%s%s\n", + pci_info(pdev, "ASPM: default states%s%s%s%s%s%s\n", FLAG(override, L0S, " L0s"), - FLAG(override, L1, " L1")); + FLAG(override, L1, " L1"), + FLAG(override, L1_1, " ASPM-L1.1"), + FLAG(override, L1_2, " ASPM-L1.2"), + FLAG(override, L1_1_PCIPM, " PCI-PM-L1.1"), + FLAG(override, L1_2_PCIPM, " PCI-PM-L1.2")); } } +/* + * Clock PM, like the L1 PM Substates, needs CLKREQ#. On devicetree platforms, + * enable it by default on links whose node says the signal is routed. + */ +static void pcie_clkpm_override_default_link_state(struct pcie_link_state *link) +{ + if (!of_have_populated_dt() || !link->clkpm_capable || link->clkpm_default) + return; + if (!pcie_link_has_aspm_override(link, "supports-clkreq")) + return; + + link->clkpm_default = 1; + pci_info(link->downstream, "ASPM: default Clock PM (supports-clkreq)\n"); +} + static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist) { struct pci_dev *child = link->downstream, *parent = link->pdev; @@ -1256,6 +1282,7 @@ void pcie_aspm_init_link_state(struct pci_dev *pdev) /* Setup initial Clock PM state */ pcie_clkpm_cap_init(link, blacklist); + pcie_clkpm_override_default_link_state(link); /* * At this stage drivers haven't had an opportunity to change the From 7bc29a898525203ffe2636f256f5a1ac9fe6be18 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 23:22:25 +1100 Subject: [PATCH 0204/1514] arm64: dts: apple: t8122-j613-j615: mark the Wi-Fi port as CLKREQ# routed The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC on the M3 MacBook Airs: the ADT gives the Wi-Fi PCIe bridge a CLKREQ function, the pin is muxed to it, and both ends advertise L1 PM Substates and Clock PM. Add "supports-clkreq" to the port so the link uses L1.1/L1.2 and Clock PM by default. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index dbb9da8d4e36b3..c362debb4c0369 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -110,6 +110,15 @@ #include "isp-imx558-cfg0.dtsi" +/* + * The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC (the ADT gives the + * Wi-Fi bridge a CLKREQ function), so the link may use Clock PM and the L1 PM + * Substates. + */ +&port00 { + supports-clkreq; +}; + &isp { apple,platform-id = <18>; apple,temporal-filter = <1>; From 7127d7310c1b1c4b2e61d9885400b0ca423233f3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 08:37:03 +1100 Subject: [PATCH 0205/1514] spi: apple-qspi: runtime suspend any controller in a power domain Runtime PM was enabled only for the T8140 controller. Every other one holds its power domain on for as long as the driver is bound. On the J615, whose tree now describes the NVRAM NOR on the QSPIMC, that keeps the qspi and spi_p domains on: blank idle went from 2.8 W to 3.45 W. The runtime suspend and resume paths already restore what a gated block loses (the reset helper re-applies timing, FIFO thresholds and interrupt state; mode, divider and descriptors are set per operation). Use them for every controller whose node puts it in a power domain, instead of a per-SoC flag. Signed-off-by: Ryan Murray --- drivers/spi/spi-apple-qspi.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/spi/spi-apple-qspi.c b/drivers/spi/spi-apple-qspi.c index d3af8452c9aad3..270e53ebd13477 100644 --- a/drivers/spi/spi-apple-qspi.c +++ b/drivers/spi/spi-apple-qspi.c @@ -94,7 +94,6 @@ struct apple_qspi_soc { /* T8140: data reads of any shape pass straight to the controller. */ bool multi_io_reads; - bool runtime_pm; }; /* @@ -1077,8 +1076,12 @@ static int apple_qspi_probe(struct platform_device *pdev) ctlr->mem_ops = &apple_qspi_mem_ops; platform_set_drvdata(pdev, ctlr); - /* Keep probe and SPI NOR discovery powered until registration finishes. */ - if (soc->runtime_pm && IS_ENABLED(CONFIG_PM)) { + /* + * A controller in a power domain lets it gate between accesses, which + * it otherwise holds on for as long as the driver is bound. Keep probe + * and SPI NOR discovery powered until registration finishes. + */ + if (dev->pm_domain && IS_ENABLED(CONFIG_PM)) { pm_runtime_get_noresume(dev); ret = devm_pm_runtime_set_active_enabled(dev); if (ret) { @@ -1263,7 +1266,6 @@ static const struct apple_qspi_soc apple_qspi_single_io = { }; static const struct apple_qspi_soc apple_qspi_t8140 = { .multi_io_reads = true, - .runtime_pm = true, }; static const struct of_device_id apple_qspi_of_match[] = { From 86801ace65258b048fec859d546d2a8b0fb9ec49 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Thu, 19 Nov 2026 18:22:02 +0000 Subject: [PATCH 0206/1514] dt-bindings: power: apple,pmc: the CLPC's GPU busy-share memory states The CLPC driver's per-SoC table says which DCS and fabric state reported GPU work gets. On SoCs whose memory latency and power at each state have been measured, scaling that floor by the GPU's busy share lets light GPU work use lower memory states while busy GPU work keeps the top states. Describe the optional apple,gpu-busy-memory-states and apple,gpu-busy-permille properties on the performance-controller node. Both properties are required together; without them, reported GPU work gets the compatible's default floor. Signed-off-by: AxxzyWasTaken --- .../devicetree/bindings/power/apple,pmc.yaml | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index bd8d9972e15337..6c4d228e46fadd 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -270,6 +270,40 @@ patternProperties: The SMC, whose package power reading the low-power platform profile holds the CPU clusters to. + apple,gpu-busy-memory-states: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: + The DCS state (first row) and fabric state (second row) for GPU work + the GPU driver reports, by the busy share it reports, below each of + the three apple,gpu-busy-permille shares and at or above the last. + A non-zero top DCS state enables the busy-share ladder; without + these properties, reported GPU work gets the compatible's default + floor. + minItems: 2 + maxItems: 2 + items: + minItems: 4 + maxItems: 4 + items: + maximum: 15 + + apple,gpu-busy-permille: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + The GPU busy shares, in permille of the time the GPU spends + executing, from which reported GPU work gets the second, third and + top column of apple,gpu-busy-memory-states. + minItems: 3 + maxItems: 3 + items: + maximum: 1000 + + dependentRequired: + apple,gpu-busy-memory-states: + - apple,gpu-busy-permille + apple,gpu-busy-permille: + - apple,gpu-busy-memory-states + required: - compatible - reg From 449130bf67c8ec49505f0703c398908ef65c8cd4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 08:49:11 +1100 Subject: [PATCH 0207/1514] drm/asahi: g17p: publish the firmware DATA base only from fw-data The previous change published the G17P GFX DATA base from the GPU's fw-data reserved-memory region, and fell back to a fixed physical address when the bound GPU was a T8140 and the region was absent. That fallback was a chip-id compare carrying a loader-specific address. The device tree already describes this memory. t8140.dtsi declares /reserved-memory/gpu-fw-data and the GPU node names it fw-data; the loader fills it from the ADT sgx gfx-data and gfx1-data segments, GFX first, which is the layout g17p_fw_data_start() checks. A boot whose loader leaves the region disabled has nothing to publish. Drop the fixed address and the chip-id compare and publish only from the region. Without a usable region g17p_gfx_link_to_physical() returns None, so no diagnostic reads memory: g17p_diag_knobs reports each firmware word as "none (no G17P fw-data region)" and g17p_fw_peek prints "error: no G17P fw-data region". Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 7 +------ drivers/gpu/drm/asahi/g18/compat/g17p.rs | 13 +++++-------- drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs | 4 ++-- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 0546a854ad02fd..c950804a778926 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -604,12 +604,7 @@ impl AsahiPlatformDriver { // The G17P firmware DATA diagnostics read only the bound GPU's own data segment. #[cfg(CONFIG_DRM_ASAHI_G18)] if cfg.identity.gpu_variant == hw::GpuVariant::P { - let fixed = if cfg.chip_id == hw::t8140::CHIP_ID { - crate::g18::compat::g17p::G17P_J700_GFX_DATA_FIXED - } else { - 0 - }; - crate::g18::compat::g17p::g17p_publish_gfx_data(pdev.as_ref(), fixed); + crate::g18::compat::g17p::g17p_publish_gfx_data(pdev.as_ref()); } Ok(AsahiPlatformDriverData { binding, diff --git a/drivers/gpu/drm/asahi/g18/compat/g17p.rs b/drivers/gpu/drm/asahi/g18/compat/g17p.rs index fb37f009665079..c6af8b95af9527 100644 --- a/drivers/gpu/drm/asahi/g18/compat/g17p.rs +++ b/drivers/gpu/drm/asahi/g18/compat/g17p.rs @@ -29,10 +29,6 @@ const G17P_GFX_LINK_DATA_END: u64 = 0xffff_fc00_0018_0000; /// bound. The module parameters that read firmware DATA exist on every Mac. static G17P_GFX_PHYSICAL_DATA_BASE: AtomicU64 = AtomicU64::new(0); -/// Where the J700's boot loader places the GFX DATA segment (T8140), for a -/// boot whose device tree has no `fw-data` region. -pub(crate) const G17P_J700_GFX_DATA_FIXED: u64 = 0x0000_0100_01d7_c000; - /// The `fw-data` region's start, if it holds the whole GFX DATA segment. The /// region holds the data segments of both firmware roles, GFX (ADT sgx /// gfx-data) first. @@ -51,10 +47,11 @@ fn g17p_fw_data_start(dev: &device::Device) -> Option { Some(start) } -/// Publish the GFX DATA base of a probed G17P GPU: its `fw-data` region, or -/// else `fixed`, the address its boot loader is known to use (0 = none). -pub(crate) fn g17p_publish_gfx_data(dev: &device::Device, fixed: u64) { - let base = g17p_fw_data_start(dev).unwrap_or(fixed); +/// Publish the GFX DATA base of a probed G17P GPU from its `fw-data` region. +/// Without a usable region nothing is published and the diagnostics that read +/// firmware DATA report none. +pub(crate) fn g17p_publish_gfx_data(dev: &device::Device) { + let base = g17p_fw_data_start(dev).unwrap_or(0); G17P_GFX_PHYSICAL_DATA_BASE.store(base, Ordering::Release); } diff --git a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs index f378116ca5ecfc..12fc7bf28c97d9 100644 --- a/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs +++ b/drivers/gpu/drm/asahi/g18/compat/timing_buffer.rs @@ -396,7 +396,7 @@ unsafe extern "C" fn diag_get(buf: *mut core::ffi::c_char, for (name, link) in [("powerups", 0xffff_fc00_0012_4ba0u64), ("state", 0xffff_fc00_0017_71f8), ("idleoff", 0xffff_fc00_0017_7838), ("keepon", 0xffff_fc00_0012_8a68)] { let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(link) else { - let _ = writeln!(out, "{} none (no G17P bound)", name); + let _ = writeln!(out, "{} none (no G17P fw-data region)", name); continue; }; let value = crate::g18::compat::g17p::LiveFirmwareU64Probe::new(physical) @@ -441,7 +441,7 @@ unsafe extern "C" fn peek_get(buf: *mut core::ffi::c_char, if address < PEEK_DATA_START { return 0; } let page = crate::pgtable::UAT_PGSZ as u64; let Some(physical) = crate::g18::compat::g17p::g17p_gfx_link_to_physical(address) else { - let _ = writeln!(out, "error: no G17P bound"); + let _ = writeln!(out, "error: no G17P fw-data region"); return out.used as core::ffi::c_int; }; let room = ((page - (physical & (page - 1))) / 8).min(64) as usize; From 5c415384582bc0888c2d1dc443771c9bc7baf831 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sat, 21 Nov 2026 13:49:52 -0800 Subject: [PATCH 0208/1514] soc: apple: rtkit: allocate endpoint 7 buffers only for clients that ask for them The endpoint map starts endpoint 7 only for clients that set APPLE_RTKIT_NEEDS_COREANALYTICS and for registry-v2 PMP firmware, but apple_rtkit_rx_dispatch() hands every other endpoint-7 message to apple_rtkit_coreanalytics_rx(). Any co-processor's buffer request is therefore allocated, zeroed and kept until the session is torn down, at whatever size the request names (up to 255 MiB), although nothing on the host reads that buffer for it. Decide this once: apple_rtkit_ep7_served() is the one predicate the endpoint map and the dispatcher both use, so the endpoint is served exactly for the clients it is started for. A message there from any other co-processor is reported as one to an unknown endpoint, as the debug endpoint already is without sync_syslog_ack. Clients that ask for CoreAnalytics, today the PMP, and the registry-v2 auxiliary buffer are handled as before. This applies to every RTKit client on every SoC. The new host test, tools/asahi/rtkit-coreanalytics-tests.py, compiles the dispatcher and the CoreAnalytics handlers from this file and checks both sides; the code before this change allocates for a client that did not ask. The two host tests that compile the dispatcher with stand-ins get one for apple_rtkit_ep7_served(). Fixes: 2aff1b95c550 ("soc: apple: rtkit: describe and adopt retained system buffers") Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/soc/apple/rtkit.c | 17 +- tools/asahi/display-sleep-merge-tests.py | 1 + tools/asahi/rtkit-coreanalytics-tests.py | 221 ++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + .../selftests/drivers/gpu/apple-dcp/run.py | 2 + 5 files changed, 242 insertions(+), 2 deletions(-) create mode 100755 tools/asahi/rtkit-coreanalytics-tests.py diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..e364719675cd64 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -179,6 +179,15 @@ static bool apple_rtkit_needs_coreanalytics(struct apple_rtkit *rtk) return rtk->ops->flags & APPLE_RTKIT_NEEDS_COREANALYTICS; } +/* + * Endpoint 7 carries CoreAnalytics, or the auxiliary buffer of registry-v2 PMP + * firmware. The endpoint map starts it, and the dispatcher serves it, only then. + */ +static bool apple_rtkit_ep7_served(struct apple_rtkit *rtk) +{ + return rtk->pmp_registry_v2 || apple_rtkit_needs_coreanalytics(rtk); +} + static bool apple_rtkit_firmware_owns_crashlog(struct apple_rtkit *rtk) { return rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG; @@ -426,7 +435,7 @@ static void apple_rtkit_management_rx_epmap(struct apple_rtkit *rtk, u64 msg) break; case APPLE_RTKIT_EP_COREANALYTICS: - if (!rtk->pmp_registry_v2 && !apple_rtkit_needs_coreanalytics(rtk)) + if (!apple_rtkit_ep7_served(rtk)) break; fallthrough; @@ -1503,7 +1512,11 @@ static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, ep, msg); break; case APPLE_RTKIT_EP_COREANALYTICS: - if (rtk->pmp_registry_v2) + if (!apple_rtkit_ep7_served(rtk)) + dev_warn(rtk->dev, + "RTKit: message to unknown endpoint %02x: %llx\n", + ep, msg); + else if (rtk->pmp_registry_v2) apple_rtkit_pmp_aux_rx(rtk, msg); else apple_rtkit_coreanalytics_rx(rtk, msg); diff --git a/tools/asahi/display-sleep-merge-tests.py b/tools/asahi/display-sleep-merge-tests.py index a0e9dc8e6f72ff..c9d1debf086973 100644 --- a/tools/asahi/display-sleep-merge-tests.py +++ b/tools/asahi/display-sleep-merge-tests.py @@ -135,6 +135,7 @@ def run(name, code, negative=False, extra=()): STUB(apple_rtkit_management_rx) STUB(apple_rtkit_crashlog_rx) STUB(apple_rtkit_syslog_rx) STUB(apple_rtkit_ioreport_rx) STUB(apple_rtkit_kdebug_rx) STUB(apple_rtkit_pmp_aux_rx) STUB(apple_rtkit_coreanalytics_rx) STUB(apple_rtkit_oslog_rx) +static bool apple_rtkit_ep7_served(struct apple_rtkit *r) { return false; } static void timed_cb(void *c,u8 e,u64 m,u64 ns) { assert(e==0x2a && m==0x1234); timed++; observed=ns; } static void legacy_cb(void *c,u8 e,u64 m) { assert(e==0x2a && m==0x1234); legacy++; } ''' diff --git a/tools/asahi/rtkit-coreanalytics-tests.py b/tools/asahi/rtkit-coreanalytics-tests.py new file mode 100755 index 00000000000000..546303ea32191c --- /dev/null +++ b/tools/asahi/rtkit-coreanalytics-tests.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check which co-processors' endpoint 7 messages RTKit serves. + +apple_rtkit_rx_dispatch() and the CoreAnalytics handlers are taken from +drivers/soc/apple/rtkit.c unchanged and built with ASan and UBSan. The +endpoint map starts endpoint 7 only for a client that asks for CoreAnalytics +(APPLE_RTKIT_NEEDS_COREANALYTICS) and for registry-v2 PMP firmware, so only +those get a buffer or an acknowledgment there: a buffer request from any +other co-processor, of any size, allocates nothing and is not answered. + +--old-ref REV runs the same checks on the driver at REV and requires them to +fail there. +""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +HEADER = 'include/linux/soc/apple/rtkit.h' +INTERNAL = 'drivers/soc/apple/rtkit-internal.h' + + +def function(source, name, optional=False): + match = re.search(r'^(?:static )?(?:void|int|bool|size_t) ' + name + r'\(', source, re.M) + if not match and optional: + return '' + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def constants(source, header, internal): + out = [line for line in source.splitlines() if re.match(r'#define APPLE_RTKIT_CA_\w+ ', line)] + out += [f'#define APPLE_RTKIT_{name} {value}' + for name, value in re.findall(r'^\tAPPLE_RTKIT_(EP_\w+) = (\w+),', source, re.M)] + out += [line for line in header.splitlines() + if re.match(r'#define APPLE_RTKIT_NEEDS_COREANALYTICS\b', line)] + out += [line for line in internal.splitlines() + if re.match(r'#define APPLE_RTKIT_APP_ENDPOINT_START\b', line)] + for name in ('NEEDS_COREANALYTICS', 'EP_COREANALYTICS', 'APP_ENDPOINT_START', 'CA_TYPE'): + assert any(name in line for line in out), name + return '\n'.join(out) + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef uint64_t dma_addr_t; +#define __iomem +#define BIT(n) (1UL << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define GENMASK_ULL(h,l) ((~0ULL << (l)) & (~0ULL >> (63-(h)))) +#define FIELD_GET(m,v) (((v) & (m)) >> __builtin_ctzll(m)) +#define FIELD_PREP(m,v) (((u64)(v) << __builtin_ctzll(m)) & (m)) +#define FIELD_FIT(m,v) (!((((u64)(v)) << __builtin_ctzll(m)) & ~(m))) +#define READ_ONCE(x) (x) +#define dev_warn(...) ((void)0) +#define dev_err(...) ((void)0) +#define dev_dbg(...) ((void)0) + +struct apple_rtkit_shmem { + void *buffer; void *iomem; size_t size; dma_addr_t iova; + bool is_mapped, needs_dma_sync; void *private; +}; +struct apple_rtkit_ops { + unsigned int flags; + void (*recv_message)(void *, u8, u64); + void (*recv_message_timed)(void *, u8, u64, u64); + int (*shmem_setup)(void *, struct apple_rtkit_shmem *); + int (*shmem_setup_ep)(void *, u8, struct apple_rtkit_shmem *); +}; +struct apple_rtkit { + void *dev, *cookie; + const struct apple_rtkit_ops *ops; + bool shutting_down, sync_syslog_ack, pmp_registry_v2; + struct { int error; } m5_saved; + struct apple_rtkit_shmem coreanalytics_buffer; + int coreanalytics_completion; +}; + +static unsigned allocations, frees, sent, aux; +static size_t allocated; +static char memory[64]; +static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, struct apple_rtkit_shmem *b) +{ + (void)rtk; assert(ep == APPLE_RTKIT_EP_COREANALYTICS); + allocations++; allocated = b->size; + /* Only the bookkeeping matters here: the memset below gets a stand-in. */ + b->buffer = memory; b->iova = 0x10000; + return 0; +} +#define memset(p, c, n) ((void)(p), (void)(c), (void)(n)) +#define memset_io(p, c, n) ((void)(p), (void)(c), (void)(n)) +static void apple_rtkit_free_buffer(struct apple_rtkit *rtk, struct apple_rtkit_shmem *b) +{ + (void)rtk; (void)b; frees++; +} +static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool a) +{ + (void)rtk; (void)msg; (void)c; (void)a; assert(ep == APPLE_RTKIT_EP_COREANALYTICS); sent++; return 0; +} +static void complete_all(int *c) { (*c)++; } +#define STUB(n) static void n(struct apple_rtkit *r, u64 m) { (void)r; (void)m; } +STUB(apple_rtkit_management_rx) STUB(apple_rtkit_crashlog_rx) STUB(apple_rtkit_syslog_rx) +STUB(apple_rtkit_ioreport_rx) STUB(apple_rtkit_kdebug_rx) STUB(apple_rtkit_oslog_rx) +static void apple_rtkit_pmp_aux_rx(struct apple_rtkit *r, u64 m) { (void)r; (void)m; aux++; } +''' + +MAIN = r''' +static u64 buffer_request(unsigned count, u64 unit) +{ + return FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, count) | unit; +} + +static void deliver(const struct apple_rtkit_ops *ops, bool registry_v2, u64 msg) +{ + struct apple_rtkit rtk = { .ops = ops, .pmp_registry_v2 = registry_v2 }; + + allocations = frees = sent = aux = 0; + allocated = 0; + apple_rtkit_rx_dispatch(&rtk, APPLE_RTKIT_EP_COREANALYTICS, msg, false, 0); +} + +int main(void) +{ + const struct apple_rtkit_ops plain = { 0 }; + const struct apple_rtkit_ops asks = { .flags = APPLE_RTKIT_NEEDS_COREANALYTICS }; + u64 largest = buffer_request(255, APPLE_RTKIT_CA_UNIT_1M); + u64 small = buffer_request(4, APPLE_RTKIT_CA_UNIT_4K); + u64 event = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 9); + + /* A client that asked for CoreAnalytics gets its buffer and its acks. */ + deliver(&asks, false, small); + assert(allocations == 1 && allocated == 0x4000 && sent == 1 && frees == 0); + deliver(&asks, false, event); + assert(allocations == 0 && sent == 1); + + /* Registry-v2 PMP firmware's endpoint 7 is its auxiliary buffer. */ + deliver(&plain, true, small); + assert(aux == 1 && allocations == 0 && sent == 0); + + /* Any other co-processor: nothing allocated, nothing answered. */ + deliver(&plain, false, small); + assert(allocations == 0 && sent == 0 && aux == 0); + deliver(&plain, false, largest); + assert(allocations == 0 && sent == 0 && aux == 0); + deliver(&plain, false, event); + assert(allocations == 0 && sent == 0 && aux == 0); + + puts("PASS endpoint 7 is served only for the clients the endpoint map starts it for"); + return 0; +} +''' + + +def read(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='require the driver at this revision to fail') + args = parser.parse_args() + source = read(args.old_ref, DRIVER) + code = constants(source, read(args.old_ref, HEADER), read(args.old_ref, INTERNAL)) + PREFIX + for name in ('apple_rtkit_needs_coreanalytics', 'apple_rtkit_coreanalytics_size', + 'apple_rtkit_coreanalytics_reply', 'apple_rtkit_coreanalytics_get_buffer', + 'apple_rtkit_coreanalytics_rx', 'apple_rtkit_rx_dispatch'): + code += function(source, name) + if name == 'apple_rtkit_needs_coreanalytics': + # The one predicate the endpoint map and the dispatcher share; absent before it. + code += function(source, 'apple_rtkit_ep7_served', optional=True) + code += MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'coreanalytics.c', out / 'coreanalytics' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + result = subprocess.run([str(exe)], capture_output=True, text=True) + if args.old_ref: + if result.returncode == 0: + raise SystemExit(f'{args.old_ref} passed; the test does not catch the original code') + print(result.stderr, end='') + print('old revision fails as required') + return 0 + print(result.stdout + result.stderr, end='') + return result.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='rtkit-coreanalytics-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 350e45f0d663e1..6774eb4f427c17 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -283,6 +283,9 @@ def mutations(flag, names, base, expect=KILL): 'radio-sleep-fence-tests.py': [([], PASS)], 'radio-sleep-power-tests.py': [([], PASS)], 'radio-sleep-snapshot-tests.py': [([], PASS)], + # cacf35543b4d serves endpoint 7 for every co-processor. + 'rtkit-coreanalytics-tests.py': [(out(), PASS), + (out() + ['--old-ref', 'cacf35543b4d534fccef3033bd2ddbb415a325b2'], PASS)], 'rtkit-crashlog-tests.py': [(out(), PASS)] + mutations('--mutation', ('buffer-header', 'section-header', 'section-size', 'footer-room', 'mailbox-minimum', 'version-string', 'message-string'), out()), diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index e97977c2e7860e..9bedfb0e0eded8 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -175,6 +175,8 @@ def main(): # The T6050 PMP registry-v2 buffer shares endpoint 7. prefix += ('#define apple_rtkit_pmp_aux_rx(...) ' 'assert(!"The PMP auxiliary buffer is outside this ordered-display fixture")\n') + # A display co-processor doesn't take CoreAnalytics buffers. + prefix += '#define apple_rtkit_ep7_served(...) false\n' unit = prefix + unit if unit is not None: result['translation_unit_sha256'] = run_unit(name, unit, output, cases, includes if name == 'service-rebind' else (), flags) From ef2eb6b7aa59b37075637ddc152b4633326543a6 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sat, 21 Nov 2026 13:40:35 -0800 Subject: [PATCH 0209/1514] PCI: apple: T6050: adopt a boot-trained link above 8 GT/s, so the J775D's 10 Gb Ethernet keeps 16 GT/s apple_pcie_adopt_link() refuses a boot-trained link faster than 8 GT/s (-ENOLINK). The boot loader sets each GP port's Target Link Speed from the port's ADT bridge: "maximum-link-speed" 3 (8 GT/s) on the N1 and the USB-A controller, and nothing on the J775D's port 2, whose RTL8127A supports 16 GT/s. Once the boot loader trains that port at 16 GT/s, the fixed ceiling would refuse the J775D's only wired network. Use the root port's own Target Link Speed (LNKCTL2) as the ceiling, so a link is adopted at up to the speed the boot loader asked for. A link does not train above its root port's target, so every link adopted today (8 GT/s or less) still is. Reach: the T6050 hosts with adopt_link. Only the check changes, and nothing new is written. A link above 8 GT/s that was refused before is now adopted wherever the boot loader left the target higher; today that is only a boot loader with "pcie_t6050: train each GP port at the speed its ADT bridge allows". Tested on the J775D (Mac Studio, M5 Ultra), with the boot loader setting the target from the ADT (aura: "pcie_t6050: train each GP port at the speed its ADT bridge allows"), on two boots: port 2 was adopted at 16 GT/s x1, and ports 0 and 3 at 8 GT/s x1 as before. Signed-off-by: Jeff Queisser --- drivers/pci/controller/pcie-apple.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 8cb1df80d0d8ee..05429c43e7b866 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -1963,6 +1963,7 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) void __iomem *rp, *ep; char name[16]; u32 value, bus; + u16 tls; u8 cap; bool msi = false; int ret, i; @@ -2029,7 +2030,7 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) port->perst = NULL; } - /* The currently qualified handoff is Gen3 x1, with no retrain in progress. */ + /* The qualified handoff is x1, with no retrain in progress. */ cap = readb(rp + PCI_CAPABILITY_LIST); for (i = 0; cap && i < 48; i++) { if (cap < 0x40 || (cap & 3)) @@ -2041,13 +2042,17 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) if (!cap || i == 48) return -EINVAL; /* - * x1 at up to the Gen3 target the bootloader set. The endpoint picks the speed: the N1's - * ROM personality links at Gen1 and comes back at Gen3 after its root-port reset. + * x1 at up to the target link speed the bootloader set in the root port, which + * it takes from the port's ADT bridge: 8 GT/s where that sets 3 (the N1, the + * USB-A controller), the root port's fastest where it sets none (the J775D's + * 10 Gb Ethernet). The endpoint picks the speed within it: the N1's ROM + * personality links at Gen1 and comes back at Gen3 after its root-port reset. */ value = readw(rp + cap + PCI_EXP_LNKSTA); + tls = readw(rp + cap + PCI_EXP_LNKCTL2) & PCI_EXP_LNKCTL2_TLS; if ((value & (PCI_EXP_LNKSTA_NLW | PCI_EXP_LNKSTA_LT)) != (1 << PCI_EXP_LNKSTA_NLW_SHIFT) || (value & PCI_EXP_LNKSTA_CLS) < PCI_EXP_LNKSTA_CLS_2_5GB || - (value & PCI_EXP_LNKSTA_CLS) > PCI_EXP_LNKSTA_CLS_8_0GB) + (value & PCI_EXP_LNKSTA_CLS) > tls) return -ENOLINK; /* Refuse an active endpoint or malformed capability chain. */ From 7bd6b5ad954862b9cd121cb0efd3578e4c3d79b5 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 3 Nov 2026 18:00:46 +0000 Subject: [PATCH 0210/1514] sched/uclamp: cap SCHED_IDLE tasks at smallest CPU capacity on asymmetric systems SCHED_IDLE only lowers a task's scheduling weight; it says nothing about clock selection or core placement. On an asymmetric CPU capacity system, a runnable SCHED_IDLE task on an otherwise idle system can still run on a high-capacity core at its top frequency. Automatically cap the effective uclamp.min and uclamp.max of non-RT/DL SCHED_IDLE tasks at the capacity of the smallest active CPU in an asymmetric scheduling domain whenever sched_asym_cpucapacity is active. The cap is derived from arch_scale_cpu_capacity() whenever scheduling domains are initialized or rebuilt, so it tracks each machine's topology and CPU hotplug changes without per-machine userspace tuning. Energy-aware placement fits such tasks on the efficiency cores, and schedutil keeps higher-capacity clusters' clocks down when they spill over. System default limits (uclamp_default) still apply first, rt_or_dl_task() keeps RT/DL (including PI-boosted) tasks excluded, and the cap wins over task and group clamp requests while preserving tighter caps. Leave nice-based background selection to userspace via sched_setattr() or cgroup cpu.uclamp.max so the kernel policy keys only on the unambiguous SCHED_IDLE signal. Symmetric systems (!sched_asym_cpucap_active()) are completely untouched and do not enable sched_uclamp_used. On asymmetric systems the cap is enabled by default (activating sched_uclamp_used automatically) and can be disabled via kernel.sched_util_clamp_background=0. Changes to the sysctl take effect for each task at its next enqueue; a CPU-bound SCHED_IDLE task that never sleeps retains its previous effective clamp until then. Signed-off-by: AxxzyWasTaken --- Documentation/admin-guide/sysctl/kernel.rst | 20 ++++++ kernel/sched/core.c | 79 ++++++++++++++++++++- kernel/sched/sched.h | 10 +++ kernel/sched/topology.c | 23 +++++- 4 files changed, 130 insertions(+), 2 deletions(-) diff --git a/Documentation/admin-guide/sysctl/kernel.rst b/Documentation/admin-guide/sysctl/kernel.rst index ffea61d448ebb1..0b3d35de5fcf30 100644 --- a/Documentation/admin-guide/sysctl/kernel.rst +++ b/Documentation/admin-guide/sysctl/kernel.rst @@ -1328,6 +1328,26 @@ restrict all boosts temporarily by modifying sched_util_clamp_min. As soon as this restriction is lifted, the requested sched_util_clamp_min_rt_default will take effect. +sched_util_clamp_background +=========================== + +Enables/disables automatic utilization capping of SCHED_IDLE tasks on +asymmetric CPU capacity systems (default 1). + +When enabled on a system with asymmetric CPU capacities +(sched_asym_cpucapacity active), the effective uclamp.min and uclamp.max of +non-RT/DL SCHED_IDLE tasks are capped at the capacity of the smallest active +CPU in an asymmetric scheduling domain (derived from arch_scale_cpu_capacity() +whenever scheduling domains are rebuilt). This biases background SCHED_IDLE +work toward efficiency cores and limits frequency scaling when it spills onto +higher-capacity cores, taking precedence over task and cgroup clamp requests +while preserving tighter system defaults. + +Setting this knob to 0 disables the cap. Symmetric systems are unaffected +regardless of the setting. Changes take effect for each task at its next +enqueue; a CPU-bound SCHED_IDLE task that never sleeps retains its previous +effective clamp until it is next enqueued. + seccomp ======= diff --git a/kernel/sched/core.c b/kernel/sched/core.c index c481404713aaa5..32d71981e60865 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -1590,6 +1590,17 @@ static unsigned int __maybe_unused sysctl_sched_uclamp_util_max = SCHED_CAPACITY */ unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE; +/* + * On asymmetric CPU capacity systems, cap SCHED_IDLE tasks (both uclamp.min + * and uclamp.max) at the smallest active asymmetric CPU's capacity so EAS + * keeps them on efficiency cores and schedutil keeps bigger clusters' clocks + * down when they spill over. The cap wins over task and group requests. + * Enabled by default (1); set to 0 to opt out. Symmetric systems are + * unaffected. + */ +static int sysctl_sched_uclamp_util_background = 1; +static unsigned int uclamp_background_cap = SCHED_CAPACITY_SCALE; + /* All clamps are required to be less or equal than these values */ static struct uclamp_se uclamp_default[UCLAMP_CNT]; @@ -1744,7 +1755,17 @@ uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id) /* System default restrictions always apply */ if (unlikely(uc_req.value > uc_max.value)) - return uc_max; + uc_req = uc_max; + + if (sched_asym_cpucap_active() && + unlikely(p->policy == SCHED_IDLE) && + !rt_or_dl_task(p) && + READ_ONCE(sysctl_sched_uclamp_util_background)) { + unsigned int bg = READ_ONCE(uclamp_background_cap); + + if (uc_req.value > bg) + uclamp_se_set(&uc_req, bg, false); + } return uc_req; } @@ -2041,6 +2062,16 @@ uclamp_update_active_tasks(struct cgroup_subsys_state *css) static void cpu_util_update_eff(struct cgroup_subsys_state *css); #endif +void uclamp_update_background_cap(unsigned int cap) +{ + lockdep_assert_held(&sched_domains_mutex); + + WRITE_ONCE(uclamp_background_cap, cap); + if (cap < SCHED_CAPACITY_SCALE && + READ_ONCE(sysctl_sched_uclamp_util_background)) + sched_uclamp_enable_cpuslocked(); +} + #ifdef CONFIG_SYSCTL #ifdef CONFIG_UCLAMP_TASK_GROUP static void uclamp_update_root_tg(void) @@ -2146,6 +2177,43 @@ static int sysctl_sched_uclamp_handler(const struct ctl_table *table, int write, sysctl_sched_uclamp_util_min_rt_default = old_min_rt; return result; } + +static int sysctl_sched_uclamp_background_handler(const struct ctl_table *table, + int write, void *buffer, + size_t *lenp, loff_t *ppos) +{ + int val = READ_ONCE(sysctl_sched_uclamp_util_background); + const struct ctl_table t = { + .procname = table->procname, + .data = &val, + .maxlen = sizeof(val), + .extra1 = table->extra1, + .extra2 = table->extra2, + }; + int result; + + if (write && !capable(CAP_SYS_ADMIN)) + return -EPERM; + + result = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); + if (result || !write) + return result; + + /* + * Tasks pick up the new setting at their next enqueue; a CPU-bound + * task that never sleeps keeps its previous effective clamp until then. + */ + cpus_read_lock(); + sched_domains_mutex_lock(); + WRITE_ONCE(sysctl_sched_uclamp_util_background, val); + if (val && sched_asym_cpucap_active() && + uclamp_background_cap < SCHED_CAPACITY_SCALE) + sched_uclamp_enable_cpuslocked(); + sched_domains_mutex_unlock(); + cpus_read_unlock(); + + return 0; +} #endif /* CONFIG_SYSCTL */ static void uclamp_fork(struct task_struct *p) @@ -4874,6 +4942,15 @@ static const struct ctl_table sched_core_sysctls[] = { .mode = 0644, .proc_handler = sysctl_sched_uclamp_handler, }, + { + .procname = "sched_util_clamp_background", + .data = NULL, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = sysctl_sched_uclamp_background_handler, + .extra1 = SYSCTL_ZERO, + .extra2 = SYSCTL_ONE, + }, #endif /* CONFIG_UCLAMP_TASK */ #ifdef CONFIG_NUMA_BALANCING { diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 9dd8c6e6f73b5c..78640a29b0fbc2 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -3691,6 +3691,14 @@ static inline void sched_uclamp_enable(void) static_branch_enable(&sched_uclamp_used); } +static inline void sched_uclamp_enable_cpuslocked(void) +{ + if (!uclamp_is_used()) + static_branch_enable_cpuslocked(&sched_uclamp_used); +} + +void uclamp_update_background_cap(unsigned int cap); + static inline unsigned long uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) { @@ -3771,6 +3779,8 @@ static inline bool uclamp_is_used(void) } static inline void sched_uclamp_enable(void) {} +static inline void sched_uclamp_enable_cpuslocked(void) {} +static inline void uclamp_update_background_cap(unsigned int cap) {} static inline unsigned long uclamp_rq_get(struct rq *rq, enum uclamp_id clamp_id) diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 3dab0253976fb4..f3f702d7b23760 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -3279,6 +3279,24 @@ void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) kfree(doms); } +static void sched_uclamp_background_update(void) +{ + unsigned long cap = SCHED_CAPACITY_SCALE; + int cpu; + + if (!IS_ENABLED(CONFIG_UCLAMP_TASK)) + return; + + if (sched_asym_cpucap_active()) { + for_each_cpu(cpu, cpu_active_mask) { + if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu))) + cap = min(cap, arch_scale_cpu_capacity(cpu)); + } + } + + uclamp_update_background_cap(cap); +} + /* * Set up scheduler domains and groups. For now this just excludes isolated * CPUs, but could be used to exclude other special cases in the future. @@ -3301,8 +3319,10 @@ int __init sched_init_domains(const struct cpumask *cpu_map) doms_cur = &fallback_doms; cpumask_and(doms_cur[0], cpu_map, housekeeping_cpumask(HK_TYPE_DOMAIN)); err = build_sched_domains(doms_cur[0], NULL, &multi_llcs); - if (!err) + if (!err) { sched_cache_set(multi_llcs); + sched_uclamp_background_update(); + } return err; } @@ -3460,6 +3480,7 @@ static void partition_sched_domains_locked(int ndoms_new, cpumask_var_t doms_new ; } sched_cache_set(has_multi_llcs); + sched_uclamp_background_update(); #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_CPU_FREQ_GOV_SCHEDUTIL) /* Build perf domains: */ From 225afc294fcb5d40dcf73bf1eb7cfab45ee9dd1d Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Thu, 19 Nov 2026 18:22:02 +0000 Subject: [PATCH 0211/1514] soc: apple: clpc: scale the GPU memory floor with its busy share from the DT On SoCs where the GPU driver reports work in flight to the CLPC, any reported GPU work holds the top memory and fabric floor. At 120 Hz a scrolling browser keeps the GPU reported active most of the time for a few percent of real execution, so light desktop use pays for the top DCS and fabric states. Let the GPU driver report its busy share per window through apple_clpc_gpu_set_busy() and, when a performance-controller node provides apple,gpu-busy-memory-states and apple,gpu-busy-permille (apple,pmc.yaml), pick the GPU floor from that four-column ladder. A non-zero top DCS state enables the ladder; otherwise, and on every node without these DT properties, reported GPU work keeps the compatible's default top floor unchanged. Each DT state is bounded by its rail's maximum in the compatible table (max(map[rail][top], gpu[rail]), matching apple_clpc_ane_states_set()) as well as the 4-bit PMC state field. Because the optional ladder only lowers a floor, malformed DT properties (bad cell count, missing partner, out-of-range rail state or unordered thresholds) log a warning and fall back to the compatible's static table unchanged instead of failing CLPC probe. A higher busy level applies at once. A lower one applies at the first CLPC sample at least 400 ms after the last sample that asked for the current level or a higher one. Clearing GPU activity forgets the last reported share so a new burst after idle starts at the top column, as does a GPU driver that reports no share. The debugfs status reports the last busy share and, when a ladder is active, the current level without advancing it. Extend tools/asahi/clpc-gpu-demand-tests.py to cover the DT parser bounds, safe fallback on malformed properties, the busy-share ladder, the no-share and no-DT fallbacks, the 400 ms down-step hold and negative controls. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/clpc.c | 232 +++++++++++++++++++++++++-- include/linux/soc/apple/clpc.h | 2 + tools/asahi/clpc-gpu-demand-tests.py | 191 +++++++++++++++++++++- 3 files changed, 407 insertions(+), 18 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index c06f00e508bdeb..8ec5471fc735a6 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -77,6 +77,9 @@ enum apple_clpc_rail { #define APPLE_CLPC_REASON_HOLD BIT(4) #define APPLE_CLPC_REASON_ANE BIT(5) +/* A lower GPU busy level must last this long; a higher one applies at once. */ +#define APPLE_CLPC_GPU_DOWN_MS 400 + /** * struct apple_clpc_hw - per-SoC CLPC parameters * @rail: PMC rail of the DCS and of the fabric @@ -101,7 +104,19 @@ enum apple_clpc_rail { * measured on; SoCs sharing this CLPC without it get no cluster floor * @gpu_input: the GPU driver reports its work in flight through * apple_clpc_gpu_get(); while there is some, both rails go to the top - * of @map + * of @map (or @gpu where higher), or to @gpu_busy if enabled from the DT + * @gpu_busy: state of each rail for reported GPU work below @gpu_busy_mid, + * @gpu_busy_high and @gpu_busy_top and at or above it, from the node's + * apple,gpu-busy-memory-states and apple,gpu-busy-permille properties; + * a non-zero top DCS state enables the busy-share ladder, otherwise + * reported GPU work falls back to the top of @map (or @gpu where higher) + * @gpu_busy_mid: GPU busy share in permille (apple_clpc_gpu_set_busy()) + * from which reported GPU work gets the second column of @gpu_busy + * @gpu_busy_high: busy share from which it gets the third column + * @gpu_busy_top: busy share from which it gets the top column, as does a + * GPU that reports no share. The share is the busiest engine's time spent + * executing at whatever clock the GPU runs, not bandwidth: a scrolling + * browser reads a few percent, CS2 at 120 fps ~480-620 permille. * @idle_on_time: sample every period even with no vote held, instead of * from a deferrable timer * @low_power_khz: CPU frequency ceiling of the low-power platform profile, @@ -123,6 +138,10 @@ struct apple_clpc_hw { unsigned int pmp_agent; unsigned int gpu_dense; bool gpu_input; + u8 gpu_busy[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int gpu_busy_mid; + unsigned int gpu_busy_high; + unsigned int gpu_busy_top; u8 ane[APPLE_CLPC_RAILS]; unsigned int ane_cluster; unsigned int ane_cluster_khz; @@ -157,6 +176,11 @@ struct apple_clpc_gpu { bool active; u64 updated_ns; u64 sequence; + /* Busy share of the last window in permille, if the GPU reports one */ + unsigned int busy; + bool busy_valid; + unsigned int level; + unsigned long level_since; struct delayed_work *wake; }; @@ -266,12 +290,35 @@ void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) if (active && !gpu->active && gpu->wake) mod_delayed_work(system_freezable_power_efficient_wq, gpu->wake, 0); gpu->active = active; + /* A new burst after idle starts from the top, not from an old share. */ + if (!active) + gpu->busy_valid = false; gpu->updated_ns = ktime_get_mono_fast_ns(); gpu->sequence++; spin_unlock_irqrestore(&gpu->lock, flags); } EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_active); +/** + * apple_clpc_gpu_set_busy() - Report the GPU busy share of the last window + * @gpu: the GPU input, from apple_clpc_gpu_get() + * @permille: share of the window the GPU spent executing work, 0..1000 + * + * Scales the floor that reported GPU work gets, see &struct apple_clpc_hw.gpu_busy. + */ +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + unsigned long flags; + + if (!gpu) + return; + spin_lock_irqsave(&gpu->lock, flags); + gpu->busy = min(permille, 1000U); + gpu->busy_valid = true; + spin_unlock_irqrestore(&gpu->lock, flags); +} +EXPORT_SYMBOL_GPL(apple_clpc_gpu_set_busy); + void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) { if (gpu) { @@ -340,6 +387,36 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out) } EXPORT_SYMBOL_GPL(apple_clpc_gpu_get); +/* + * The column of @hw->gpu_busy for reported GPU work, from its busy share. + * Called once per CLPC sample: a higher column applies at once, a lower one + * at the first sample at least APPLE_CLPC_GPU_DOWN_MS after the last one + * that asked for the current column or a higher one. + */ +static unsigned int apple_clpc_gpu_level(const struct apple_clpc_hw *hw, + struct apple_clpc_gpu *gpu) +{ + unsigned long flags; + unsigned int level; + + spin_lock_irqsave(&gpu->lock, flags); + if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top) + level = APPLE_CLPC_LEVELS - 1; + else if (gpu->busy >= hw->gpu_busy_high) + level = 2; + else + level = gpu->busy >= hw->gpu_busy_mid ? 1 : 0; + if (level >= gpu->level || + time_after_eq(jiffies, gpu->level_since + + msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS))) { + gpu->level = level; + gpu->level_since = jiffies; + } + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + return level; +} + static bool apple_clpc_gpu_active(struct apple_clpc_gpu *gpu, u64 *updated, u64 *sequence) { unsigned long flags; @@ -724,22 +801,30 @@ static void apple_clpc_gpu_floor_count(struct apple_clpc *clpc, bool released) /* * The GPU driver's input, where it drives demand instead of the GFX power - * state: every rail at the top of @map, or at @gpu where that is higher, - * while the driver reports work. + * state: while the driver reports work, every rail at @gpu_busy for the + * reported busy share when @gpu_busy has a non-zero top DCS state, or at the + * top of @map (or @gpu where that is higher) otherwise. */ static bool apple_clpc_gpu_input_demand(const struct apple_clpc_hw *hw, struct apple_clpc_gpu *gpu, unsigned int *demand) { + bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]; u64 updated, sequence; - unsigned int rail; + unsigned int level = 0, rail; if (!gpu || hw->gpu_demand || !apple_clpc_gpu_active(gpu, &updated, &sequence)) return false; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], - max(hw->map[rail][APPLE_CLPC_LEVELS - 1], hw->gpu[rail])); + if (has_busy) + level = apple_clpc_gpu_level(hw, gpu); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + unsigned int state = has_busy ? hw->gpu_busy[rail][level] : + max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + demand[rail] = max(demand[rail], state); + } return true; } @@ -1033,9 +1118,25 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), READ_ONCE(clpc->last_vote_ns)); if (clpc->gpu) { + struct apple_clpc_gpu *gpu = clpc->gpu; + unsigned int busy, level; + unsigned long flags; u64 updated, sequence; - bool active = apple_clpc_gpu_active(clpc->gpu, &updated, &sequence); - + bool active = apple_clpc_gpu_active(gpu, &updated, &sequence); + bool busy_valid; + + /* Show the level the last sample chose; reading must not move it. */ + spin_lock_irqsave(&gpu->lock, flags); + busy = gpu->busy; + busy_valid = gpu->busy_valid; + level = gpu->level; + spin_unlock_irqrestore(&gpu->lock, flags); + if (clpc->hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1]) + seq_printf(s, "host_gpu busy: %u permille (%s) level %u\n", + busy, busy_valid ? "reported" : "none", level); + else + seq_printf(s, "host_gpu busy: %u permille (%s)\n", + busy, busy_valid ? "reported" : "none"); seq_printf(s, "host_gpu: active %u request_ns %llu sequence %llu\n", active, updated, sequence); } @@ -1354,6 +1455,115 @@ static const struct platform_profile_ops apple_clpc_profile_ops = { .profile_set = apple_clpc_profile_set, }; +/* + * Fills @hw->gpu_busy from a DT matrix: APPLE_CLPC_RAILS rows of + * APPLE_CLPC_LEVELS states, each bounded by the compatible table's rail + * maximum (and the 4-bit PMC state field). + */ +static int apple_clpc_dt_map(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + u8 states[APPLE_CLPC_RAILS][APPLE_CLPC_LEVELS]; + unsigned int rail, level; + + if (n != APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS) + return -EINVAL; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + u32 top = max(hw->map[rail][APPLE_CLPC_LEVELS - 1], + hw->gpu[rail]); + + for (level = 0; level < APPLE_CLPC_LEVELS; level++) { + u32 state = cells[rail * APPLE_CLPC_LEVELS + level]; + + if (state > top || state > 15) + return -EINVAL; + states[rail][level] = state; + } + } + memcpy(hw->gpu_busy, states, sizeof(states)); + return 0; +} + +/* The busy shares from which reported GPU work gets the 2nd, 3rd and top column. */ +static int apple_clpc_dt_busy(struct apple_clpc_hw *hw, const u32 *cells, int n) +{ + if (n != 3 || cells[0] > cells[1] || cells[1] > cells[2] || cells[2] > 1000) + return -EINVAL; + hw->gpu_busy_mid = cells[0]; + hw->gpu_busy_high = cells[1]; + hw->gpu_busy_top = cells[2]; + return 0; +} + +/* + * Applies parsed DT GPU busy-share cells onto a copy of @soc. Any error in + * either property warns and leaves @soc unchanged so a malformed optional + * ladder never aborts CLPC probe. + */ +static bool apple_clpc_dt_apply(struct device *dev, + const struct apple_clpc_hw *soc, + struct apple_clpc_hw *out, + const u32 *states, int n_states, + const u32 *busy, int n_busy) +{ + int err; + + *out = *soc; + err = n_states < 0 ? n_states : apple_clpc_dt_map(out, states, n_states); + if (!err) + err = n_busy < 0 ? n_busy : apple_clpc_dt_busy(out, busy, n_busy); + if (err) { + dev_warn(dev, + "ignoring invalid GPU busy-share states in the device tree (%d)\n", + err); + *out = *soc; + return false; + } + return true; +} + +/* Reads up to @max cells of @name; returns how many, or an error. */ +static int apple_clpc_dt_cells(struct device_node *np, const char *name, + u32 *cells, int max) +{ + int n = of_property_count_u32_elems(np, name); + + if (n < 0) + return n; + if (n > max) + return -EOVERFLOW; + return of_property_read_u32_array(np, name, cells, n) ?: n; +} + +/* + * The compatible's table, with the GPU busy-share memory states the node + * gives (apple,pmc.yaml). Without those properties, or if they are malformed, + * the compatible's own table applies unchanged. + */ +static const struct apple_clpc_hw *apple_clpc_dt_hw(struct device *dev, + const struct apple_clpc_hw *soc) +{ + u32 states[APPLE_CLPC_RAILS * APPLE_CLPC_LEVELS]; + u32 busy[3]; + struct device_node *np = dev->of_node; + struct apple_clpc_hw copy, *hw; + int n_states, n_busy; + + if (!of_property_present(np, "apple,gpu-busy-memory-states") && + !of_property_present(np, "apple,gpu-busy-permille")) + return soc; + n_states = apple_clpc_dt_cells(np, "apple,gpu-busy-memory-states", + states, ARRAY_SIZE(states)); + n_busy = apple_clpc_dt_cells(np, "apple,gpu-busy-permille", + busy, ARRAY_SIZE(busy)); + if (!apple_clpc_dt_apply(dev, soc, ©, states, n_states, + busy, n_busy)) + return soc; + hw = devm_kmemdup(dev, ©, sizeof(copy), GFP_KERNEL); + if (!hw) + return ERR_PTR(-ENOMEM); + return hw; +} + static int apple_clpc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -1368,7 +1578,9 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->dev = dev; clpc->pmc = dev->parent; - clpc->hw = of_device_get_match_data(dev); + clpc->hw = apple_clpc_dt_hw(dev, of_device_get_match_data(dev)); + if (IS_ERR(clpc->hw)) + return PTR_ERR(clpc->hw); /* T6040 firmware keeps GFX powered for its whole lifetime. A separate * host publication/idle input, not that supplier state, drives demand; * the T8132 and M5 (T8142) GPU drivers report through the same input. diff --git a/include/linux/soc/apple/clpc.h b/include/linux/soc/apple/clpc.h index 0a4c4f439ac565..5f83b2aedc609c 100644 --- a/include/linux/soc/apple/clpc.h +++ b/include/linux/soc/apple/clpc.h @@ -12,6 +12,7 @@ struct apple_clpc_ane; #if IS_REACHABLE(CONFIG_APPLE_CLPC) int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu); /* Optional, single-publisher input: success with NULL means no provider. */ int apple_clpc_ane_get(struct device *dev, struct apple_clpc_ane **out); @@ -24,6 +25,7 @@ static inline int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu * return device_property_present(dev, "apple,clpc") ? -ENODEV : 0; } static inline void apple_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) {} +static inline void apple_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) {} static inline void apple_clpc_gpu_put(struct apple_clpc_gpu *gpu) {} /* ANE remains usable when the optional floor provider is not reachable. */ diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index a4db3f838738e1..1d3d72281bcea6 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -26,11 +26,32 @@ def main(): rail_shift = re.search(r'^#define APPLE_PMC_RAIL_SHIFT\(rail\).*$', header, re.M).group(0) dense_samples = re.search(r'^#define APPLE_CLPC_GPU_DENSE_SAMPLES\s.*$', source, re.M).group(0) reasons = '\n'.join(re.findall(r'^#define APPLE_CLPC_REASON_\w+\s.*$', source, re.M)) + gpu_down = re.search(r'^#define APPLE_CLPC_GPU_DOWN_MS\s.*$', source, re.M).group(0) types = '\n'.join(item(source, s) + ';' for s in [ 'struct apple_clpc_hw {', 'struct apple_clpc_vote {']) tables = '\n'.join(item(source, 'static const struct apple_clpc_hw ' + n + ' =') + ';' for n in ['apple_clpc_hw_t8132', 'apple_clpc_hw_t8140', - 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041']) + 'apple_clpc_hw_t6040', 'apple_clpc_hw_t6041', + 'apple_clpc_hw_t6050']) + # When t6041.dtsi supplies the GPU busy-share properties, parse and test them directly; + # otherwise exercise the DT parsers and ladder against the reference values. + dts = (ROOT / 'arch/arm64/boot/dts/apple/t6041.dtsi').read_text() + clpc_node = item(dts, '&clpc {') + + def cells(name): + match = re.search(r'\s' + re.escape(name) + r'\s*=\s*([^;]*);', clpc_node) + if not match: + return None + return [int(x, 0) for x in re.findall(r'0x[0-9a-fA-F]+|\d+', match.group(1))] + + dt_states = cells('apple,gpu-busy-memory-states') + dt_busy = cells('apple,gpu-busy-permille') + assert (dt_states is None) == (dt_busy is None) + gpu_states = dt_states or [1, 2, 4, 5, 0, 0, 0, 3] + gpu_busy = dt_busy or [160, 500, 800] + t6041_dt = ( + 'static const u32 t6041_gpu_states[] = {' + ', '.join(str(x) for x in gpu_states) + '};\n' + 'static const u32 t6041_gpu_busy[] = {' + ', '.join(str(x) for x in gpu_busy) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', 'static bool apple_clpc_gpu_streaming(', @@ -38,6 +59,10 @@ def main(): 'static bool apple_clpc_gpu_dense(', 'static bool apple_clpc_gpu_limited(', 'static void apple_clpc_gpu_floor_count(', + 'static unsigned int apple_clpc_gpu_level(', + 'static int apple_clpc_dt_map(', + 'static int apple_clpc_dt_busy(', + 'static bool apple_clpc_dt_apply(', 'static bool apple_clpc_gpu_input_demand(', 'static bool apple_clpc_ane_input_demand(', 'static void apple_clpc_ane_cluster(', @@ -47,16 +72,19 @@ def main(): #include #include #include +#include #include typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +struct device; #define APPLE_CLPC_LEVELS 4 #define APPLE_CLPC_HOLD_MS 32 #define APPLE_CLPC_SAMPLE_MS 4 #define APPLE_CLPC_GPU_BACKOFF_MS 100 #define HZ 1000 #define max(a,b) ((a) > (b) ? (a) : (b)) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define GENMASK(h,l) (((1u << ((h)-(l)+1))-1) << (l)) #define BIT(n) (1u << (n)) #define APPLE_PMC_RAIL_SHIFT(r) ((r)*8) @@ -64,11 +92,15 @@ def main(): #define time_after(a,b) ((long)((a)-(b)) > 0) #define time_before(a,b) ((long)((a)-(b)) < 0) #define msecs_to_jiffies(ms) (ms) -static int warned; +static int warned, dt_warned; #define dev_warn_once(d, ...) ((void)(d), warned++) +#define dev_warn(d, ...) ((void)(d), dt_warned++) enum apple_clpc_rail { APPLE_CLPC_DCS, APPLE_CLPC_SOC, APPLE_CLPC_RAILS }; ''' + types + r''' -struct apple_clpc_gpu { bool active; u64 sequence; }; +struct apple_clpc_gpu { + int lock; bool active; u64 sequence; + unsigned int busy; bool busy_valid; unsigned int level; unsigned long level_since; +}; struct apple_clpc_ane { int lock; bool active, pending; }; #define spin_lock_irqsave(l, f) ((void)(l), (f) = 0) #define spin_unlock_irqrestore(l, f) ((void)(l), (void)(f)) @@ -135,7 +167,83 @@ def main(): static void apple_clpc_queue(struct apple_clpc *c, bool idle) { (void)c; queued_idle=idle; } #define READ_ONCE(x) (x) static void apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } -''' + dense_samples + '\n' + reasons + '\n' + tables + '\n' + methods + r''' +''' + dense_samples + '\n' + reasons + '\n' + gpu_down + '\n' + tables + '\n' + methods + '\n' + t6041_dt + r''' +// Apply DT GPU busy-share properties through the driver's parsers: the CPU map +// stays untouched, valid GPU states/thresholds populate the ladder, states +// above the compatible table's rail maximum are rejected, and any malformed +// optional ladder warns and falls back to the compatible's static table. +static struct apple_clpc_hw t6041_dt_hw; +static void t6041_from_dt(void) { + static const u8 cpu[2][4] = {{5, 5, 5, 5}, {3, 3, 3, 3}}, gpu[2][4] = {{1, 2, 4, 5}, {0, 0, 0, 3}}; + struct apple_clpc_hw out, bad = apple_clpc_hw_t6040; + u32 over_4bit[8] = {1, 2, 4, 5, 0, 0, 0, 16}; + u32 t6041_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 3}; + u32 t6041_over_dcs6[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 t6041_over_soc[8] = {1, 2, 4, 5, 0, 0, 0, 4}; + u32 t6050_ok[8] = {1, 2, 4, 6, 0, 0, 0, 2}; + u32 t6050_over_dcs[8] = {1, 2, 4, 7, 0, 0, 0, 2}; + u32 t6050_over_soc[8] = {1, 2, 4, 6, 0, 0, 0, 3}; + u32 busy[3] = {500, 160, 800}; + + dt_warned = 0; + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &t6041_dt_hw, + t6041_gpu_states, ARRAY_SIZE(t6041_gpu_states), + t6041_gpu_busy, ARRAY_SIZE(t6041_gpu_busy))); + assert(dt_warned == 0); + for (int r = 0; r < 2; r++) + for (int l = 0; l < 4; l++) + assert(t6041_dt_hw.map[r][l] == cpu[r][l] && t6041_dt_hw.gpu_busy[r][l] == gpu[r][l]); + + // Direct parser bounds: 4-bit max, rail-specific compatible max, counts, thresholds. + assert(apple_clpc_dt_map(&bad, over_4bit, 8) == -EINVAL); + assert(apple_clpc_dt_map(&bad, over_4bit, 7) == -EINVAL); + assert(apple_clpc_dt_map(&bad, t6041_gpu_states, 8) == -EINVAL); // fabric 3 > T6040 max 2 + bad = apple_clpc_hw_t6041; + assert(apple_clpc_dt_map(&bad, t6041_over_dcs, 8) == -EINVAL); // DCS 7 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_dcs6, 8) == -EINVAL); // DCS 6 > T6041 max 5 + assert(apple_clpc_dt_map(&bad, t6041_over_soc, 8) == -EINVAL); // fabric 4 > T6041 max 3 + // T6050 rail max uses max(map[rail][top], gpu[rail]): DCS 6 from gpu[DCS], fabric 2. + assert(apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_ok, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 0 && out.gpu_busy[APPLE_CLPC_DCS][3] == 6); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 1 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6050, &out, + t6050_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 2 && !memcmp(&out, &apple_clpc_hw_t6050, sizeof(out))); + + // Malformed optional DT properties warn and fall back to the static soc table unchanged. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_dcs, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 3 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_over_soc, 8, t6041_gpu_busy, 3)); + assert(dt_warned == 4 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Valid states paired with bad permille or missing partner must not leave partial ladder. + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, busy, 3)); + assert(dt_warned == 5 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + t6041_gpu_states, 8, NULL, -EINVAL)); + assert(dt_warned == 6 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + assert(!apple_clpc_dt_apply(NULL, &apple_clpc_hw_t6041, &out, + NULL, -EINVAL, t6041_gpu_busy, 3)); + assert(dt_warned == 7 && !memcmp(&out, &apple_clpc_hw_t6041, sizeof(out))); + // Falling back keeps the compatible's full GPU floor even when a low busy share arrives. + { + struct apple_clpc_gpu g = {.active = true, .busy_valid = true, .busy = 100}; + struct apple_clpc c = {.hw = &out, .agent = 1, .mask = 3, .gpu = &g}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; jiffies = 2900; published = ~0u; + apple_clpc_sample(&c); + assert(published == 0x35 && c.last_reason == 2); + } + + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + busy[0] = 160; busy[1] = 500; busy[2] = 1001; + assert(apple_clpc_dt_busy(&bad, busy, 3) == -EINVAL); + assert(apple_clpc_dt_busy(&bad, busy, 2) == -EINVAL); +} // T8140 ANE work holds its DRAM and fabric states while it runs, a request // shorter than one sample is still seen once, and the hold then expires. static void check_t8140_ane(void) { @@ -172,6 +280,55 @@ def main(): ane.active=true; jiffies=2040; apple_clpc_sample(&c); assert(qos_adds==1 && qos_min==3756000); } +// DT GPU busy-share ladder: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at +// 160, 500 and 800 permille. A higher level applies at once, a lower one at the +// first sample at least 400 ms after the last one that asked for the current +// level or more. A table without a non-zero top DCS state falls back to @map. +static void check_t6041_busy(void) { + struct apple_clpc_gpu gpu={0}; + struct apple_clpc c={.hw=&t6041_dt_hw,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc_hw no_top = t6041_dt_hw; + assert(c.hw->gpu_busy_mid==160 && c.hw->gpu_busy_high==500 && c.hw->gpu_busy_top==800); + read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; published=~0u; + // No share reported: the top of the ladder, as before the busy share. + gpu.active=true; jiffies=3000; apple_clpc_sample(&c); + assert(published==0x35 && c.last_reason==2 && gpu.level==3); + gpu.active=false; jiffies=3100; apple_clpc_sample(&c); assert(published==0); + // Below gpu_busy_mid: the lowest GPU state (after a long idle, at once). + gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=3500; + apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2 && gpu.level==0); + // Between the thresholds, going up: each level applies at the next sample. + gpu.busy=160; jiffies=3504; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=499; jiffies=3508; apple_clpc_sample(&c); assert(published==0x02 && gpu.level==1); + gpu.busy=500; jiffies=3512; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=799; jiffies=3516; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=800; jiffies=3520; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // Going down waits 400 ms from the last sample at the top. + gpu.busy=100; + for (jiffies=3524; jiffies<3920; jiffies+=4) { + apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + } + jiffies=3919; apple_clpc_sample(&c); assert(published==0x35 && gpu.level==3); + // At 400 ms the DCS drops at once; the fabric state keeps HOLD_MS. + jiffies=3920; apple_clpc_sample(&c); assert(published==0x31 && gpu.level==0); + jiffies=3952; apple_clpc_sample(&c); assert(published==0x01 && c.last_reason==2); + // A sample that asks for the current level again restarts the 400 ms. + gpu.busy=600; jiffies=4000; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + gpu.busy=100; jiffies=4200; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=550; jiffies=4300; apple_clpc_sample(&c); assert(gpu.level==2); + gpu.busy=100; jiffies=4699; apple_clpc_sample(&c); assert(published==0x04 && gpu.level==2); + jiffies=4700; apple_clpc_sample(&c); assert(published==0x01 && gpu.level==0); + gpu.active=false; jiffies=4800; apple_clpc_sample(&c); assert(published==0 && queued_idle); + // Without a non-zero top DCS state, even a low reported share keeps the map top. + no_top.gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1] = 0; + c.hw = &no_top; gpu.active=true; gpu.busy_valid=true; gpu.busy=100; jiffies=4900; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + // Same for a static table with no DT properties at all. + c.hw = &apple_clpc_hw_t6041; jiffies=4904; + apple_clpc_sample(&c); assert(published==0x35 && c.last_reason==2); + gpu.active=false; jiffies=5000; apple_clpc_sample(&c); assert(published==0 && queued_idle); +} + // T8132's G16 firmware keeps graphics powered while the GPU idles: the // M5/F3 floor follows the work the GPU driver reports, as on T6040. static void check_t8132(void) { @@ -190,10 +347,10 @@ def main(): // T6041 (M4 Max) votes DCS 5 / fabric 3 for CPU and host GPU demand without a // streak, samples on time while idle, preserves T6041's DCS 5 / fabric 2 ANE // floor, and carries the 2808 MHz Low Power ceiling. -static void check_t6041(void) { +static void check_t6041(const struct apple_clpc_hw *hw) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6041,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; + struct apple_clpc c={.hw=hw,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; assert(!c.hw->gpu_demand && c.hw->gpu_input && c.hw->sustain==0 && c.hw->idle_on_time); @@ -299,14 +456,17 @@ def main(): assert(published==0x12 && c.last_reason==1); c.clusters[0].request[0]=c.clusters[0].request[1]=0; jiffies=264; apple_clpc_sample(&c); assert(published==0); + t6041_from_dt(); + check_t6041_busy(); check_t8132(); - check_t6041(); + check_t6041(&apple_clpc_hw_t6041); + check_t6041(&t6041_dt_hw); check_read_error(); check_t8140(); check_t8140_dense(); check_t8140_ane(); check_t6040_ane(); - puts("PASS: T6040, T6041 and T8132 host demand; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); + puts("PASS: T6040, T6041 and T8132 host demand; DT GPU busy share and down-step hold; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); } ''' code = code.replace('#define APPLE_PMC_RAIL_SHIFT(r) ((r)*8)', rail_shift) @@ -331,7 +491,22 @@ def main(): ('omit-pmp-backoff', code.replace('bool released = apple_clpc_gpu_limited(clpc, now);', 'bool released = (apple_clpc_gpu_limited(clpc, now), false);')), ('release-too-early', code.replace('msecs_to_jiffies(APPLE_CLPC_HOLD_MS)', '0')), + ('gpu-down-at-once', code.replace('msecs_to_jiffies(APPLE_CLPC_GPU_DOWN_MS)', '0')), + ('gpu-busy-ignored', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (true || gpu->busy >= hw->gpu_busy_top)')), + ('gpu-no-share-uses-table', code.replace('if (!gpu->busy_valid || gpu->busy >= hw->gpu_busy_top)', + 'if (gpu->busy >= hw->gpu_busy_top)')), + ('gpu-busy-without-dt', code.replace('bool has_busy = hw->gpu_busy[APPLE_CLPC_DCS][APPLE_CLPC_LEVELS - 1];', + 'bool has_busy = true;')), ('retain-at-idle', code.replace('vote->state = 0;', '')), + ('dt-state-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, false)')), + ('dt-rail-bound-unchecked', code.replace('if (state > top || state > 15)', 'if ((void)top, state > 15)')), + ('dt-gpu-rail-max-ignored', code.replace('max(hw->map[rail][APPLE_CLPC_LEVELS - 1],\n\t\t\t hw->gpu[rail])', + 'hw->map[rail][APPLE_CLPC_LEVELS - 1]')), + ('dt-fallback-keeps-partial', code.replace('\t\t*out = *soc;\n\t\treturn false;', '\t\treturn false;')), + ('dt-fallback-silent', code.replace('dev_warn(dev,\n\t\t\t "ignoring invalid GPU busy-share states in the device tree (%d)\\n",\n\t\t\t err);', + '(void)dev; (void)err;')), + ('dt-busy-unordered', code.replace('cells[0] > cells[1] || ', '')), ]: # A mutation that no longer matches the driver tests nothing. assert name == 'fixed' or text != code, 'stale mutation: ' + name From 5819ed4b3308f990f4589c47929d6289c439840f Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Fri, 20 Nov 2026 16:34:45 +0000 Subject: [PATCH 0212/1514] drm/asahi: g17: report the busiest engine's share to CLPC Track the engine time charged across all clients per engine (vertex, fragment and compute) in usage.rs, track each active QID's oldest unretired command timestamp in g17/qos.rs, and report the busiest engine's share of each 200 ms window to CLPC through apple_clpc_gpu_set_busy(). The three engines run in parallel, so summing their times is not a share of the window: in CS2 on the J616c the fragment and compute engines run 73 % and 83 % busy concurrently, which saturated a summed share at 1000 permille and pinned the memory ladder at its top column. Taking the busiest engine's share avoids that double-counting; overlapping work across multiple clients on the same engine still clamps to 1000 permille, safely erring toward the higher floor. Counting only retired stages misses a long compute or render command in flight alongside a light submitter such as a compositor, which would otherwise keep reporting the compositor's low share until the long command retired. Difference (retired_ns + in_flight_age) per engine across window boundaries so in-flight commands count while they run without being double-counted when they retire, and lift immediately to 1000 permille (including mid-window and via idle_check rechecks when no other client submits) once any unretired command reaches 50 ms. Reading ENGINE_NS with Acquire ordering before locking qos pairs with Client::add()'s Release store after qos_complete() so a concurrent retirement cannot be counted twice. Also notify port GPU activity on ComputeHost::note_submission() to match the render and direct paths. Add KUnit tests in g17/power.rs and extend tools/asahi/clpc-gpu-demand-tests.py to drive the production CLPC ladder with the production g17 BusyShare logic for a long compute command running beside a light compositor, along with negative controls. Measured on the J616c (busiest-engine retired share): - CS2, fixed de_dust2 scene, FIFO 120: busy share reads 480-620 permille instead of 1000, ladder steps to levels 1-2, 120.0 fps unchanged. - CS2 uncapped: 176.6-177.1 fps against 176.1-176.5 fps. - gltxf (3456x2234) and gldepthbench: identical 3.84 ms frame times and power (single busy engine reads the same). Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/clpc.c | 6 + drivers/gpu/drm/asahi/g17/clpc.h | 1 + drivers/gpu/drm/asahi/g17/mod.rs | 14 +- drivers/gpu/drm/asahi/g17/port.rs | 117 +++++++++-- drivers/gpu/drm/asahi/g17/power.rs | 282 +++++++++++++++++++++++++++ drivers/gpu/drm/asahi/g17/qos.rs | 76 +++++++- drivers/gpu/drm/asahi/g17/runtime.rs | 1 + drivers/gpu/drm/asahi/usage.rs | 23 ++- tools/asahi/clpc-gpu-demand-tests.py | 273 +++++++++++++++++++++++++- 9 files changed, 763 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/clpc.c b/drivers/gpu/drm/asahi/g17/clpc.c index 58adaba19910f2..bfe26e5d91c14d 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.c +++ b/drivers/gpu/drm/asahi/g17/clpc.c @@ -10,6 +10,12 @@ void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active) { apple_clpc_gpu_set_active(gpu, active); } + +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille) +{ + apple_clpc_gpu_set_busy(gpu, permille); +} + void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu) { apple_clpc_gpu_put(gpu); diff --git a/drivers/gpu/drm/asahi/g17/clpc.h b/drivers/gpu/drm/asahi/g17/clpc.h index 372820ade7efff..6b16d5e8d58012 100644 --- a/drivers/gpu/drm/asahi/g17/clpc.h +++ b/drivers/gpu/drm/asahi/g17/clpc.h @@ -5,5 +5,6 @@ struct device; struct apple_clpc_gpu; int asahi_clpc_gpu_get(void *dev, struct apple_clpc_gpu **out); void asahi_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); +void asahi_clpc_gpu_set_busy(struct apple_clpc_gpu *gpu, unsigned int permille); void asahi_clpc_gpu_put(struct apple_clpc_gpu *gpu); #endif diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d43b2b3aa69b95..fe960caa74f3d4 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1076,12 +1076,14 @@ impl Firmware { } power::IdleAction::Recheck(delay) => Some(delay), }; - Ok( - match (effort, self.idle_hold(now_ns, in_flight || submitted)) { - (Some(a), Some(b)) => Some(a.min(b)), - (a, b) => a.or(b), - }, - ) + let busy_recheck = if in_flight { + self.port.report_busy(now_ns); + self.port.busy_recheck_delay(now_ns) + } else { + None + }; + let hold = self.idle_hold(now_ns, in_flight || submitted); + Ok([effort, hold, busy_recheck].into_iter().flatten().min()) } /// Drives the idle hold (see power::Hold); returns the delay in ns for its next check. A diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index f9bd31f13bc7d5..2a535f81429c8b 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -116,6 +116,13 @@ pub(super) struct Port { /// Full firmware effort is applied; cleared before an idle clear rechecks `submissions`. effort_full: AtomicBool, demand: super::power::Demand, + /// Serializes busy-share window accounting and CLPC busy updates. + #[pin] + busy: SpinLock, + /// Mirrored from `busy` and `qos` for a lock-free fast path in `note_gpu_activity()`. + busy_window_start: AtomicU64, + busy_below_top: AtomicBool, + oldest_in_flight_any: AtomicU64, statistics_epoch: AtomicU64, last_submission_ns: AtomicU64, submissions: AtomicU64, @@ -174,6 +181,10 @@ impl Port { publications: AtomicU64::new(0), effort_full: AtomicBool::new(false), demand, + busy <- new_spinlock!(super::power::BusyShare::new(), "g17::Port::busy"), + busy_window_start: AtomicU64::new(0), + busy_below_top: AtomicBool::new(false), + oldest_in_flight_any: AtomicU64::new(0), statistics_epoch: AtomicU64::new(0), last_submission_ns: AtomicU64::new(0), submissions: AtomicU64::new(0), @@ -427,10 +438,14 @@ impl Port { policy: Policy, ) -> Result { let view = self.qos_view()?; - let publication = self - .qos - .lock() - .publish(&view, owner, scheduler, policy, qos::clock)?; + let publication = { + let mut qos = self.qos.lock(); + let publication = + qos.publish(&view, owner, scheduler, policy, qos::clock, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publication + }; self.rx_update(); Ok(publication) } @@ -443,17 +458,31 @@ impl Port { policy: Policy, ) -> Result<[qos::Publication; 2]> { let view = self.qos_view()?; - let publications = - self.qos - .lock() - .publish_owners(&view, owners, scheduler, policy, qos::clock)?; + let publications = { + let mut qos = self.qos.lock(); + let publications = qos.publish_owners( + &view, + owners, + scheduler, + policy, + qos::clock, + super::now_ns(), + )?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + publications + }; self.rx_update(); Ok(publications) } pub(super) fn qos_cancel(&self, publication: qos::Publication) -> Result { let view = self.qos_view()?; - self.qos.lock().cancel(&view, publication) + let mut qos = self.qos.lock(); + qos.cancel(&view, publication)?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + Ok(()) } /// Clears the QoS table rows of released QoS IDs (`QosIds::forget_released`); returns @@ -468,7 +497,12 @@ impl Port { pub(super) fn qos_complete(&self, owners: &[qos::Owner]) -> Result { let view = self.qos_view()?; - self.qos.lock().complete(&view, owners)?; + { + let mut qos = self.qos.lock(); + qos.complete(&view, owners, super::now_ns())?; + self.oldest_in_flight_any + .store(qos.oldest_in_flight_any(), Ordering::Relaxed); + } self.rx_update(); Ok(()) } @@ -538,7 +572,15 @@ impl Port { pub(super) fn set_effort_full(&self, full: bool) { self.effort_full.store(full, Ordering::SeqCst); - self.demand.set_active(full); + if full { + self.demand.set_active(true); + } else { + let mut busy = self.busy.lock(); + self.demand.set_active(false); + busy.clear_active(); + self.busy_window_start.store(0, Ordering::Relaxed); + self.busy_below_top.store(false, Ordering::Relaxed); + } } /// The next statistics drain and reader discard what the decoder holds. @@ -550,6 +592,54 @@ impl Port { self.statistics_epoch.load(Ordering::Acquire) } + /// Reports the busiest GPU engine's share of the last window (including unretired + /// in-flight commands) to CLPC once a window elapses or an in-flight command + /// saturates its engine. Lock-free on the common in-window path. + pub(super) fn report_busy(&self, now_ns: u64) { + if !self.demand.has_provider() { + return; + } + let start = self.busy_window_start.load(Ordering::Relaxed); + let window_due = + start == 0 || now_ns.saturating_sub(start) >= super::power::BUSY_WINDOW_NS; + let long_due = !window_due + && self.busy_below_top.load(Ordering::Relaxed) + && { + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + oldest != 0 + && now_ns.saturating_sub(oldest) >= super::power::BUSY_LONG_COMMAND_NS + }; + if !window_due && !long_due { + return; + } + // Read retired time (Acquire) before qos (lock Acquire): retirement calls + // qos_complete() before usage::Client::add() Release-adds ENGINE_NS, so we + // never observe both the retired time and the old in-flight timestamp. + let retired = crate::usage::ENGINE_NS + .each_ref() + .map(|ns| ns.load(Ordering::Acquire)); + let oldest = self.qos.lock().oldest_in_flight(); + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if let Some(permille) = busy.sample(now_ns, retired, oldest) { + self.demand.set_busy(permille); + } + self.busy_window_start + .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); + self.busy_below_top + .store(busy.below_top(), Ordering::Relaxed); + } + + /// Wake delay (ns) for `idle_check` while a solo long command is running below + /// the top CLPC busy column, or `None` when already at top or idle. + pub(super) fn busy_recheck_delay(&self, now_ns: u64) -> Option { + if !self.demand.has_provider() || !self.busy_below_top.load(Ordering::Relaxed) { + return None; + } + let oldest = self.oldest_in_flight_any.load(Ordering::Relaxed); + super::power::BusyShare::recheck_delay_for(now_ns, oldest) + } + pub(super) fn note_gpu_activity(&self) { // Observe gating before activity can wake the cores. A lockless // publisher cannot clear the decoder under the device mutex; this @@ -561,9 +651,10 @@ impl Port { { self.statistics_epoch.fetch_add(1, Ordering::Release); } - self.last_submission_ns - .store(super::now_ns(), Ordering::Relaxed); + let now_ns = super::now_ns(); + self.last_submission_ns.store(now_ns, Ordering::Relaxed); self.demand.set_active(true); + self.report_busy(now_ns); } pub(super) fn write_power(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index 8ae6e5d1808ebe..cf1fe38cbea5e7 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -420,6 +420,141 @@ pub(super) fn release(control: &mut C) -> kernel::error::Result { result } +/// Busy-share window: long enough to span frames, short enough to follow a burst. +pub(super) const BUSY_WINDOW_NS: u64 = 200_000_000; +/// A longer gap between reports with no long command in flight was idle: start over +/// rather than average it in. +pub(super) const BUSY_WINDOW_MAX_NS: u64 = 2_000_000_000; +/// An unretired command that has been running continuously for this long saturates +/// its engine and immediately lifts the busy share to 1000 permille, without waiting +/// for it to retire or for the current window to end. +pub(super) const BUSY_LONG_COMMAND_NS: u64 = 50_000_000; + +/// Per-window busiest GPU engine share (0..=1000 permille), combining retired stage +/// execution time with unretired in-flight command time. +/// +/// The vertex, fragment and compute engines run in parallel, so their summed time is +/// not a share of the window: taking the busiest engine's share avoids double-counting +/// across engines. For each engine, `retired_ns + in_flight_age` is differenced across +/// window boundaries so a command spanning a boundary counts in the window it runs in +/// and is never double-counted when it later retires. Any engine with an unretired +/// command older than [`BUSY_LONG_COMMAND_NS`] lifts immediately to 1000 permille so +/// long compute or render work running beside a light compositor never sits at a low +/// memory floor waiting for retirement. In-flight age counts from publication, so time +/// a command waits in its queue or on dependencies, and a render's vertex and fragment +/// stages retiring together, err toward a higher share, which is the safe direction. +pub(super) struct BusyShare { + start_ns: Option, + retired_ns: [u64; crate::usage::NUM_ENGINES], + in_flight_ns: [u64; crate::usage::NUM_ENGINES], + below_top: bool, +} + +impl BusyShare { + pub(super) const fn new() -> Self { + Self { + start_ns: None, + retired_ns: [0; crate::usage::NUM_ENGINES], + in_flight_ns: [0; crate::usage::NUM_ENGINES], + below_top: false, + } + } + + /// CLPC cleared GPU activity (forgetting its last share so a new burst starts + /// at the top column). Only called once the GPU is idle: restart the window so + /// the first report of the next burst re-baselines instead of closing a window + /// diluted by the idle gap, which would drop the burst off the top column. + pub(super) fn clear_active(&mut self) { + self.start_ns = None; + self.in_flight_ns = [0; crate::usage::NUM_ENGINES]; + self.below_top = false; + } + + pub(super) fn below_top(&self) -> bool { + self.below_top + } + + pub(super) fn window_start(&self) -> Option { + self.start_ns + } + + pub(super) fn is_long_in_flight( + now_ns: u64, + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> bool { + oldest_in_flight + .iter() + .any(|&since| since != 0 && now_ns.saturating_sub(since) >= BUSY_LONG_COMMAND_NS) + } + + /// Delay (ns) until an in-flight command reaches [`BUSY_LONG_COMMAND_NS`], at + /// least 1 ms. Retirement runs its own event pass, so this never delays idle + /// teardown. + pub(super) fn recheck_delay_for(now_ns: u64, oldest: u64) -> Option { + if oldest == 0 { + return None; + } + let age = now_ns.saturating_sub(oldest); + Some(BUSY_LONG_COMMAND_NS.saturating_sub(age).max(1_000_000)) + } + + pub(super) fn sample( + &mut self, + now_ns: u64, + retired_ns: [u64; crate::usage::NUM_ENGINES], + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> Option { + let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight); + let Some(start) = self.start_ns else { + self.start_ns = Some(now_ns); + self.retired_ns = retired_ns; + for (slot, &since) in self.in_flight_ns.iter_mut().zip(oldest_in_flight.iter()) { + *slot = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + } + return None; + }; + let elapsed = now_ns.saturating_sub(start); + if elapsed < BUSY_WINDOW_NS { + if self.below_top && long_in_flight { + self.below_top = false; + return Some(1000); + } + return None; + } + let mut busiest = 0u64; + for i in 0..crate::usage::NUM_ENGINES { + let now = retired_ns[i]; + let delta = now.saturating_sub(self.retired_ns[i]); + self.retired_ns[i] = now; + let since = oldest_in_flight[i]; + let age = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + let prev_age = self.in_flight_ns[i]; + self.in_flight_ns[i] = age; + let busy = delta.saturating_add(age).saturating_sub(prev_age); + busiest = busiest.max(busy); + } + self.start_ns = Some(now_ns); + if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight { + return None; + } + let permille = if long_in_flight { + 1000 + } else { + (busiest.saturating_mul(1000) / elapsed).min(1000) as u32 + }; + self.below_top = permille < 1000; + Some(permille) + } +} + #[cfg_attr(not(test), kernel::macros::kunit_tests(asahi_g17_idle_hold))] mod tests { use super::*; @@ -576,12 +711,150 @@ mod tests { hold.asserted(); assert_eq!(hold.step(1, false, 2, FIRMWARE_IDLE_OFF_MS), HoldAction::Release); } + + #[test] + fn long_in_flight_command_lifts_beside_light_submitter() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Establish light compositor baseline: ~50 permille (10 ms in 200 ms). + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!( + share.sample(1200 * NS_MS, [2 * NS_MS, 10 * NS_MS, 0], [0, 0, 0]), + Some(50) + ); + assert!(share.below_top()); + // A 500 ms compute job starts at t=1250 ms; compositor submits at t=1410 ms. + assert_eq!( + share.sample( + 1410 * NS_MS, + [4 * NS_MS, 20 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + assert!(!share.below_top()); + // Still running across the next window at t=1610 ms: stays at 1000. + assert_eq!( + share.sample( + 1610 * NS_MS, + [6 * NS_MS, 30 * NS_MS, 0], + [0, 0, 1250 * NS_MS], + ), + Some(1000) + ); + // Retires at t=1750 ms (+500 ms retired); only the 140 ms in [1610, 1750] counts. + assert_eq!( + share.sample(1810 * NS_MS, [8 * NS_MS, 40 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(700) + ); + // Next window returns cleanly to the light compositor share. + assert_eq!( + share.sample(2010 * NS_MS, [10 * NS_MS, 50 * NS_MS, 500 * NS_MS], [0, 0, 0]), + Some(50) + ); + } + + #[test] + fn late_long_command_lifts_mid_window_without_double_counting() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1200 * NS_MS, [0, 10 * NS_MS, 0], [0, 0, 0]), Some(50)); + // Long compute starts at t=1390 ms; window closes at t=1410 ms (only 20 ms old). + assert_eq!( + share.sample(1410 * NS_MS, [0, 20 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(95) + ); + assert!(share.below_top()); + // At t=1440 ms (50 ms old, mid-window), early lift reports 1000 immediately. + assert_eq!( + share.sample(1440 * NS_MS, [0, 22 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + Some(1000) + ); + assert!(!share.below_top()); + // Second mid-window submit does not spam CLPC. + assert_eq!( + share.sample(1460 * NS_MS, [0, 23 * NS_MS, 0], [0, 0, 1390 * NS_MS]), + None + ); + // Retires at t=1490 ms (+100 ms retired); window [1410, 1610] credits exact 80 ms. + assert_eq!( + share.sample(1610 * NS_MS, [0, 30 * NS_MS, 100 * NS_MS], [0, 0, 0]), + Some(400) + ); + } + + #[test] + fn straddling_short_command_and_long_gaps_behave_cleanly() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + // 40 ms command [1170, 1210] straddles boundary 1200: 30 ms in first, 10 ms in second. + assert_eq!( + share.sample(1200 * NS_MS, [0, 0, 0], [0, 0, 1170 * NS_MS]), + Some(150) + ); + assert_eq!( + share.sample(1400 * NS_MS, [0, 0, 40 * NS_MS], [0, 0, 0]), + Some(50) + ); + // Multi-engine takes busiest engine rather than summing parallel engines. + assert_eq!( + share.sample(1600 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 0]), + Some(600) + ); + // >2 s idle gap with a freshly-started command (age 0) restarts without reporting. + assert_eq!( + share.sample(5000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + None + ); + // >2 s active command still reports 1000. + assert_eq!( + share.sample(8000 * NS_MS, [0, 120 * NS_MS, 150 * NS_MS], [0, 0, 5000 * NS_MS]), + Some(1000) + ); + // Recheck delay wakes once at the long-command age (at least 1 ms), None when idle. + assert_eq!(BusyShare::recheck_delay_for(1010 * NS_MS, 0), None); + assert_eq!( + BusyShare::recheck_delay_for(1010 * NS_MS, 1000 * NS_MS), + Some(40 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1045 * NS_MS, 1000 * NS_MS), + Some(5 * NS_MS) + ); + assert_eq!( + BusyShare::recheck_delay_for(1100 * NS_MS, 1000 * NS_MS), + Some(NS_MS) + ); + } + + #[test] + fn new_burst_after_idle_restarts_the_window() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Steady 600 permille fragment work. + assert_eq!(share.sample(900 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1100 * NS_MS, [0, 120 * NS_MS, 0], [0, 0, 0]), Some(600)); + assert_eq!(share.sample(1300 * NS_MS, [0, 240 * NS_MS, 0], [0, 0, 0]), Some(600)); + // Work continues to 1400 ms, then the GPU idles and CLPC clears its share. + share.clear_active(); + assert!(!share.below_top()); + // First submission after a 600 ms idle gap: closing [1300, 2000] would report + // a diluted 85 permille (60 ms in 700 ms); it re-baselines instead. + assert_eq!(share.sample(2000 * NS_MS, [0, 300 * NS_MS, 0], [0, 0, 0]), None); + assert!(!share.below_top()); + // No report until a fresh 200 ms window of the new burst completes. + assert_eq!(share.sample(2190 * NS_MS, [0, 414 * NS_MS, 0], [0, 0, 0]), None); + assert_eq!(share.sample(2200 * NS_MS, [0, 420 * NS_MS, 0], [0, 0, 0]), Some(600)); + } } unsafe extern "C" { fn asahi_clpc_gpu_get(dev: *mut core::ffi::c_void, out: *mut *mut core::ffi::c_void) -> core::ffi::c_int; fn asahi_clpc_gpu_set_active(gpu: *mut core::ffi::c_void, active: bool); fn asahi_clpc_gpu_put(gpu: *mut core::ffi::c_void); + fn asahi_clpc_gpu_set_busy(gpu: *mut core::ffi::c_void, permille: core::ffi::c_uint); } /// DT-selected memory-demand provider. Its independent allocation outlives a @@ -605,10 +878,19 @@ impl Demand { } } + pub(super) fn has_provider(&self) -> bool { + !self.0.is_null() + } + pub(super) fn set_active(&self, active: bool) { // SAFETY: the retained reference is live; NULL denotes no DT provider. unsafe { asahi_clpc_gpu_set_active(self.0, active) }; } + + pub(super) fn set_busy(&self, permille: u32) { + // SAFETY: the retained reference is live; NULL denotes no DT provider. + unsafe { asahi_clpc_gpu_set_busy(self.0, permille.min(1000) as core::ffi::c_uint) }; + } } impl Drop for Demand { diff --git a/drivers/gpu/drm/asahi/g17/qos.rs b/drivers/gpu/drm/asahi/g17/qos.rs index 5adccb14b5cad7..36a20a5e02d8fa 100644 --- a/drivers/gpu/drm/asahi/g17/qos.rs +++ b/drivers/gpu/drm/asahi/g17/qos.rs @@ -6,7 +6,10 @@ //! precedes submitted counters; retiring a final owner clears only its two row //! bytes. Cancellation balances host references without rewinding shared counts. -use super::fw::{qos as fw, queue::Policy}; +use super::fw::{ + qos as fw, + queue::{DataMaster, Policy}, +}; use crate::hw::t8140::qos as cfg; use core::{ mem::offset_of, @@ -14,6 +17,13 @@ use core::{ }; use kernel::prelude::*; +const _: () = { + assert!(fw::QUEUES <= 128); + assert!(DataMaster::Tiling as usize == crate::usage::Engine::Vertex as usize); + assert!(DataMaster::Fragment as usize == crate::usage::Engine::Fragment as usize); + assert!(DataMaster::Compute as usize == crate::usage::Engine::Compute as usize); +}; + /// Atomic views retain the allocation borrow and never borrow firmware words /// as ordinary mutable memory. The arrays are disjoint apart from the explicit /// data-master time/count indexing in `times_and_counts`. @@ -87,6 +97,11 @@ pub(crate) struct Accounting { in_flight: [u32; fw::QUEUES], dm_in_flight: [u64; fw::DATA_MASTERS], dm_by_qid: [u8; fw::QUEUES], + /// Bitmask of QIDs with `in_flight[qid] > 0`. + active_qids: u128, + /// Monotonic start timestamp (ns) of each active QID's oldest unretired command, + /// advanced when a command completes with more work still in flight on that QID. + qid_since_ns: [u64; fw::QUEUES], /// The table's rows and counts as last stored, indexed as in [`View`]. Only the host /// writes them, so a publication counts on from these instead of reading them back. rows: [[u8; 8]; fw::QUEUES], @@ -101,6 +116,8 @@ impl Accounting { in_flight: [0; fw::QUEUES], dm_in_flight: [0; fw::DATA_MASTERS], dm_by_qid: [0; fw::QUEUES], + active_qids: 0, + qid_since_ns: [0; fw::QUEUES], rows: [[0; 8]; fw::QUEUES], queue_submitted: [0; fw::QUEUES], owner_submitted: [0; fw::QUEUES], @@ -119,8 +136,9 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result { - let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock)?; + let [publication] = self.publish_owners(view, [owner], scheduler, policy, clock, now_ns)?; Ok(publication) } @@ -136,6 +154,7 @@ impl Accounting { scheduler: u64, policy: Policy, clock: impl FnOnce() -> (u64, u64), + now_ns: u64, ) -> Result<[Publication; N]> { if scheduler == 0 { return Err(EINVAL); @@ -219,6 +238,10 @@ impl Accounting { let mut record = rows[index]; record[0] = owner.qos; record[1] = class; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = now_ns.max(1); + self.active_qids |= 1u128 << qid; + } self.in_flight[qid] += 1; self.dm_in_flight[dm] += 1; self.dm_by_qid[qid] = owner.data_master; @@ -243,7 +266,7 @@ impl Accounting { { return Err(EIO); } - self.complete(view, &[ticket.owner]) + self.complete_inner(view, &[ticket.owner], 0, true) } /// Clears the scheduler and share rows of the QoS IDs in `ids`, which no context holds: a @@ -271,7 +294,17 @@ impl Accounting { /// Preflights the entire set before clearing any final row. QID membership, /// scheduler mappings and monotonically increasing counts remain intact. - pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner]) -> Result { + pub(crate) fn complete(&mut self, view: &View<'_>, owners: &[Owner], now_ns: u64) -> Result { + self.complete_inner(view, owners, now_ns, false) + } + + fn complete_inner( + &mut self, + view: &View<'_>, + owners: &[Owner], + now_ns: u64, + cancelled: bool, + ) -> Result { let mut completed = [0u64; fw::DATA_MASTERS]; for (index, owner) in owners.iter().copied().enumerate() { let (qid, _, dm) = owner.indices()?; @@ -300,7 +333,14 @@ impl Accounting { } } for owner in owners { - self.in_flight[usize::from(owner.qid)] -= 1; + let qid = usize::from(owner.qid); + self.in_flight[qid] -= 1; + if self.in_flight[qid] == 0 { + self.qid_since_ns[qid] = 0; + self.active_qids &= !(1u128 << qid); + } else if !cancelled { + self.qid_since_ns[qid] = now_ns.max(1); + } } for (dm, count) in completed.iter().enumerate() { self.dm_in_flight[dm] -= count; @@ -308,6 +348,32 @@ impl Accounting { fence(Ordering::SeqCst); Ok(()) } + + /// Oldest unretired command timestamp (monotonic ns) per engine + /// (vertex, fragment, compute), or 0 when that engine has none in flight. + pub(crate) fn oldest_in_flight(&self) -> [u64; crate::usage::NUM_ENGINES] { + let mut oldest = [0u64; crate::usage::NUM_ENGINES]; + let mut mask = self.active_qids; + while mask != 0 { + let qid = mask.trailing_zeros() as usize; + mask &= mask - 1; + let dm = usize::from(self.dm_by_qid[qid]); + let since = self.qid_since_ns[qid]; + if dm < oldest.len() && since != 0 && (oldest[dm] == 0 || since < oldest[dm]) { + oldest[dm] = since; + } + } + oldest + } + + /// Oldest unretired command timestamp across all engines, or 0 if idle. + pub(crate) fn oldest_in_flight_any(&self) -> u64 { + self.oldest_in_flight() + .into_iter() + .filter(|&since| since != 0) + .min() + .unwrap_or(0) + } } /// Firmware accounting uses a 24 MHz domain independent of host timer speed. diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 810ba873678756..8a4cc264703339 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1598,6 +1598,7 @@ impl compute::Host for ComputeHost<'_> { } fn note_submission(&mut self) -> Result { self.shared.note_submitter(); + self.port.note_gpu_activity(); self.shared.note_gpu_activity(); self.effort.submit(); self.effort.note_waiters(super::now_ns(), super::fence::waiters()); diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index aa817d2d417687..f25b367ea81011 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -11,6 +11,16 @@ use core::sync::atomic::{AtomicU64, Ordering}; +/// Number of GPU engines tracked in [`Engine`]: vertex, fragment and compute. +pub(crate) const NUM_ENGINES: usize = 3; + +/// Engine time charged across all clients per [`Engine`], in ns, for the GPU busy share. +/// +/// Overlapping work from multiple clients on the same engine adds up here; consumers clamp +/// the resulting busy share to 1000 permille, which safely errs toward the higher floor. +pub(crate) static ENGINE_NS: [AtomicU64; NUM_ENGINES] = + [const { AtomicU64::new(0) }; NUM_ENGINES]; + #[derive(Clone, Copy)] pub(crate) enum Engine { Vertex, @@ -20,13 +30,13 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { - ns: [AtomicU64; 3], + ns: [AtomicU64; NUM_ENGINES], } impl Client { pub(crate) const fn new() -> Self { Self { - ns: [const { AtomicU64::new(0) }; 3], + ns: [const { AtomicU64::new(0) }; NUM_ENGINES], } } @@ -38,6 +48,9 @@ impl Client { return; } let ns = ticks_to_ns(end - start, frequency_hz); + // Release orders retirement's earlier qos_complete() before any reader + // that Acquire-loads ENGINE_NS and then reads qos.oldest_in_flight(). + ENGINE_NS[engine as usize].fetch_add(ns, Ordering::Release); let counter = &self.ns[engine as usize]; let mut old = counter.load(Ordering::Relaxed); loop { @@ -54,7 +67,7 @@ impl Client { } /// Vertex, fragment and compute, in ns. No cross-engine atomic snapshot is promised. - pub(crate) fn snapshot(&self) -> [u64; 3] { + pub(crate) fn snapshot(&self) -> [u64; NUM_ENGINES] { self.ns.each_ref().map(|ns| ns.load(Ordering::Relaxed)) } } @@ -75,14 +88,14 @@ const DISCONTINUITY_S: u64 = 60; /// still add up, one union each. pub(crate) struct Lane

{ client: P, - covered: [AtomicU64; 3], + covered: [AtomicU64; NUM_ENGINES], } impl> Lane

{ pub(crate) fn new(client: P) -> Self { Self { client, - covered: [const { AtomicU64::new(0) }; 3], + covered: [const { AtomicU64::new(0) }; NUM_ENGINES], } } diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index 1d3d72281bcea6..278794f1fc3b9d 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -20,7 +20,182 @@ def item(text, signature): return text[start:end] +def test_g17_busy_share(): + """Compile and run production g17 BusyShare (power.rs) with negative controls. + + Returns the (t_ms, permille) reports emitted for the long-command-beside- + light-compositor scenario, and the (t_ms, permille or -1 for no report) + samples of a new burst after idle, so the C CLPC harness drives + apple_clpc_sample() with them end-to-end. + """ + power = (ROOT / 'drivers/gpu/drm/asahi/g17/power.rs').read_text() + consts = '\n'.join( + re.search(r'^pub\(super\) const ' + name + r': u64 = [^\n]+$', power, re.M).group(0) + for name in ('BUSY_WINDOW_NS', 'BUSY_WINDOW_MAX_NS', 'BUSY_LONG_COMMAND_NS')) + struct_def = item(power, 'pub(super) struct BusyShare {') + impl_def = item(power, 'impl BusyShare {') + prod = f'{consts}\n{struct_def}\n{impl_def}\n' + + harness = r''' +#![allow(dead_code)] +mod usage { + pub const NUM_ENGINES: usize = 3; +} +mod power { +''' + prod + r''' +} +use power::{BusyShare, BUSY_LONG_COMMAND_NS}; + +fn main() { + const MS: u64 = 1_000_000; + // Scenario 1: long 500 ms compute job running next to a light compositor. + // Light compositor runs 10 ms per 200 ms window (50 permille -> level 0). + let mut s = BusyShare::new(); + assert_eq!(s.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + let r0 = s.sample(1200 * MS, [2 * MS, 10 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r0, 50); + assert!(s.below_top()); + // Compute job (500 ms) starts at t=1650 ms (after CLPC has dropped to level 0 + // following its 400 ms down-step hold); compositor submits at t=1810 ms (210 ms + // after a 1600 ms window start). Must immediately report 1000 while still running. + let r1 = s.sample(1400 * MS, [4 * MS, 20 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r1, 50); + let r2 = s.sample(1600 * MS, [6 * MS, 30 * MS, 0], [0, 0, 0]).unwrap(); + assert_eq!(r2, 50); + let r3 = s.sample(1810 * MS, [8 * MS, 40 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r3, 1000, "long in-flight compute next to light compositor must lift to 1000"); + assert!(!s.below_top()); + // Still running across the next 200 ms window at t=2010 ms: holds 1000. + let r4 = s.sample(2010 * MS, [10 * MS, 50 * MS, 0], [0, 0, 1650 * MS]).unwrap(); + assert_eq!(r4, 1000); + // Job retires at t=2150 ms (+500 ms retired). At t=2210 ms only the 140 ms in + // [2010, 2150] counts (700 permille), proving zero double-counting. + let r5 = s.sample(2210 * MS, [12 * MS, 60 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r5, 700, "post-retirement window must not double-count prior in-flight time"); + // Next window returns cleanly to compositor's 50 permille. + let r6 = s.sample(2410 * MS, [14 * MS, 70 * MS, 500 * MS], [0, 0, 0]).unwrap(); + assert_eq!(r6, 50); + + // Scenario 2: long command starting late in a window lifts mid-window at 50 ms. + let mut late = BusyShare::new(); + assert_eq!(late.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(late.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + assert_eq!(late.sample(1410 * MS, [0, 20 * MS, 0], [0, 0, 1390 * MS]), Some(95)); + assert!(late.below_top()); + assert_eq!(late.sample(1440 * MS, [0, 22 * MS, 0], [0, 0, 1390 * MS]), Some(1000)); + assert!(!late.below_top()); + assert_eq!(late.sample(1460 * MS, [0, 23 * MS, 0], [0, 0, 1390 * MS]), None); + assert_eq!(late.sample(1610 * MS, [0, 30 * MS, 100 * MS], [0, 0, 0]), Some(400)); + + // Scenario 3: solo long command driven by recheck_delay_for reaches 1000 and stops. + let mut solo = BusyShare::new(); + assert_eq!(solo.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(solo.sample(1200 * MS, [0, 10 * MS, 0], [0, 0, 0]), Some(50)); + let mut t = 1222 * MS; + let start = 1210 * MS; + let mut lifted = false; + let mut rechecks = 0; + for _ in 0..8 { + if let Some(p) = solo.sample(t, [0, 10 * MS, 0], [0, 0, start]) { + assert_eq!(p, 1000); + lifted = true; + break; + } + let delay = BusyShare::recheck_delay_for(t, start).unwrap(); + assert!(delay <= BUSY_LONG_COMMAND_NS); + t += delay; + rechecks += 1; + } + // One wake-up at the long-command age, not a train of short ones. + assert!(lifted && !solo.below_top() && t == start + BUSY_LONG_COMMAND_NS && rechecks == 1); + + // Scenario 4: short straddling command (no double count), multi-engine max, >2 s gaps. + let mut misc = BusyShare::new(); + assert_eq!(misc.sample(1000 * MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(misc.sample(1200 * MS, [0, 0, 0], [0, 0, 1170 * MS]), Some(150)); + assert_eq!(misc.sample(1400 * MS, [0, 0, 40 * MS], [0, 0, 0]), Some(50)); + assert_eq!(misc.sample(1600 * MS, [0, 120 * MS, 150 * MS], [0, 0, 0]), Some(600)); + assert_eq!(misc.sample(5000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), None); + assert_eq!(misc.sample(8000 * MS, [0, 120 * MS, 150 * MS], [0, 0, 5000 * MS]), Some(1000)); + + // Scenario 5: steady 600 permille work until 1400 ms, idle (CLPC cleared), then a + // new burst at 2000 ms. Closing [1300, 2000] would report a diluted 85 permille + // (60 ms in 700 ms); the first submission re-baselines instead and nothing is + // reported until a fresh 200 ms window of the new burst completes. + let mut burst = BusyShare::new(); + assert_eq!(burst.sample(900 * MS, [0, 0, 0], [0, 0, 0]), None); + let mut idle_events = Vec::new(); + for (t, frag) in [(1100, 120), (1300, 240)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, Some(600)); + idle_events.push((t, p)); + } + burst.clear_active(); + assert!(!burst.below_top()); + for (t, frag) in [(2000, 300), (2048, 328), (2100, 360), (2148, 388), (2196, 417), (2200, 420)] { + let p = burst.sample(t * MS, [0, frag * MS, 0], [0, 0, 0]); + assert_eq!(p, if t < 2200 { None } else { Some(600) }, + "new burst after idle must not report a window diluted by the idle gap"); + idle_events.push((t, p)); + } + assert!(burst.below_top()); + + println!("EVENTS:1200={r0},1400={r1},1600={r2},1810={r3},2010={r4},2210={r5},2410={r6}"); + let idle: Vec = + idle_events.iter().map(|(t, p)| format!("{t}={}", p.map_or(-1, i64::from))).collect(); + println!("IDLE:{}", idle.join(",")); +} +''' + rustc = os.environ.get('RUSTC', 'rustc') + events = idle_events = None + with tempfile.TemporaryDirectory(prefix='asahi-g17-busy-') as tmp: + root = Path(tmp) + for name, text in [ + ('fixed', harness), + ('g17-ignore-in-flight', + harness.replace('let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);', + 'let _ = oldest_in_flight; let oldest_in_flight = [0; crate::usage::NUM_ENGINES];\n' + ' let long_in_flight = Self::is_long_in_flight(now_ns, oldest_in_flight);')), + ('g17-double-count-in-flight', + harness.replace('let busy = delta.saturating_add(age).saturating_sub(prev_age);', + 'let _ = prev_age; let busy = delta.saturating_add(age);')), + ('g17-no-early-lift', + harness.replace('if self.below_top && long_in_flight {', + 'if false && self.below_top && long_in_flight {')), + ('g17-long-idle-reports', + harness.replace('if elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {', + 'if false && elapsed > BUSY_WINDOW_MAX_NS && !long_in_flight {')), + ('g17-idle-keeps-window', + harness.replace('self.start_ns = None;\n self.in_flight_ns = [0; crate::usage::NUM_ENGINES];\n' + ' self.below_top = false;', + 'self.below_top = false;')), + ]: + assert name == 'fixed' or text != harness, 'stale mutation: ' + name + src = root / (name + '.rs') + src.write_text(text) + binary = src.with_suffix('') + subprocess.run([rustc, '--edition=2021', '-Dwarnings', str(src), '-o', str(binary)], + check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if name == 'fixed': + assert run.returncode == 0, run.stderr + lines = run.stdout.strip().splitlines() + assert len(lines) == 2 and lines[0].startswith('EVENTS:') \ + and lines[1].startswith('IDLE:'), lines + events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[0].removeprefix('EVENTS:').split(',')] + idle_events = [tuple(int(x) for x in pair.split('=')) + for pair in lines[1].removeprefix('IDLE:').split(',')] + print('PASS: g17 BusyShare (in-flight long command, early lift, solo recheck, ' + 'non-double-counting, new burst after idle)') + else: + assert run.returncode != 0, name + print('PASS negative control:', name) + return events, idle_events + + def main(): + g17_events, g17_idle_events = test_g17_busy_share() source = (ROOT / 'drivers/soc/apple/clpc.c').read_text() header = (ROOT / 'include/linux/soc/apple/pmc.h').read_text() rail_shift = re.search(r'^#define APPLE_PMC_RAIL_SHIFT\(rail\).*$', header, re.M).group(0) @@ -51,7 +226,11 @@ def cells(name): gpu_busy = dt_busy or [160, 500, 800] t6041_dt = ( 'static const u32 t6041_gpu_states[] = {' + ', '.join(str(x) for x in gpu_states) + '};\n' - 'static const u32 t6041_gpu_busy[] = {' + ', '.join(str(x) for x in gpu_busy) + '};\n') + 'static const u32 t6041_gpu_busy[] = {' + ', '.join(str(x) for x in gpu_busy) + '};\n' + 'static const struct { unsigned long ms; unsigned int permille; } g17_long_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_events) + '};\n' + 'static const struct { unsigned long ms; int permille; } g17_idle_events[] = {' + + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', 'static bool apple_clpc_gpu_streaming(', @@ -329,6 +508,96 @@ def cells(name): gpu.active=false; jiffies=5000; apple_clpc_sample(&c); assert(published==0 && queued_idle); } +// End-to-end: feed g17 BusyShare's actual reports for a 500 ms compute job +// running beside a light compositor into CLPC's T6041 ladder. CLPC drops to +// DCS 1 / fabric 0 during light compositing, lifts IMMEDIATELY to DCS 5 / +// fabric 3 (0x35) at t=1810 ms while the compute job is still in flight, holds +// 0x35 while it runs, and drops back to 0x01 after it finishes + 400 ms hold. +static void check_t6041_long_in_flight(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + gpu.active = true; + // Initial burst starts at top (no share yet). + jiffies = 1000; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Light compositor windows (1200, 1400, 1600 ms -> 50 permille) drop to DCS 1 / fabric 0. + assert(ARRAY_SIZE(g17_long_events) == 7); + for (size_t i = 0; i < 3; i++) { + gpu.busy = g17_long_events[i].permille; gpu.busy_valid = true; + jiffies = g17_long_events[i].ms; apple_clpc_sample(&c); + } + // After 400 ms down-step hold + 32 ms fabric hold, CLPC is at DCS 1 / fabric 0. + jiffies = 1640; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); + // At t=1810 ms (160 ms into the 500 ms compute job, still in flight!), BusyShare + // reports 1000 permille and CLPC lifts IMMEDIATELY to DCS 5 / fabric 3. + gpu.busy = g17_long_events[3].permille; gpu.busy_valid = true; + jiffies = g17_long_events[3].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Still running at t=2010 ms: stays at DCS 5 / fabric 3. + gpu.busy = g17_long_events[4].permille; gpu.busy_valid = true; + jiffies = g17_long_events[4].ms; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + // Retires at t=2150 ms; window at t=2210 ms reports exact 700 (still in 400 ms hold). + gpu.busy = g17_long_events[5].permille; gpu.busy_valid = true; + for (jiffies = g17_long_events[5].ms; jiffies < g17_long_events[6].ms; jiffies += 4) { + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + // Next light window at t=2410 ms (400 ms after last top request at 2010 ms): + // DCS drops immediately to 1, fabric keeps HOLD_MS (32 ms) from the 2406 ms sample. + gpu.busy = g17_long_events[6].permille; gpu.busy_valid = true; + jiffies = g17_long_events[6].ms; apple_clpc_sample(&c); + assert(published == 0x31 && gpu.level == 0); + jiffies = g17_long_events[6].ms + APPLE_CLPC_HOLD_MS; apple_clpc_sample(&c); + assert(published == 0x01 && gpu.level == 0); +} + +// End-to-end: g17 BusyShare's samples (-1: no report) for steady 600 permille +// work, an idle gap in which the GPU clears its activity (apple_clpc_gpu_set_active +// false also clears busy_valid), and a new burst 600 ms later. The new burst starts +// at the top (0x35) and stays there until a fresh 200 ms window reports; the +// diluted 85 permille a stale window would report drops it to 0x01 at once. +static void check_t6041_idle_burst(void) { + struct apple_clpc_gpu gpu = {0}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + size_t i = 0, n = ARRAY_SIZE(g17_idle_events); + read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; + assert(n == 8 && g17_idle_events[0].ms == 1100 && g17_idle_events[2].ms == 2000); + gpu.active = true; jiffies = 900; apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + for (; i < 2; i++) { + assert(g17_idle_events[i].permille == 600); + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + jiffies = g17_idle_events[i].ms; apple_clpc_sample(&c); + } + assert(gpu.level == 2); + // Idle: the GPU clears its activity and CLPC forgets the share. + gpu.active = false; gpu.busy_valid = false; + for (jiffies = 1416; jiffies < 2000; jiffies += 4) + apple_clpc_sample(&c); + assert(published == 0); + gpu.active = true; + for (jiffies = 2000; jiffies <= 2200; jiffies += 4) { + if (i < n && g17_idle_events[i].ms == jiffies) { + if (g17_idle_events[i].permille >= 0) { + gpu.busy = g17_idle_events[i].permille; gpu.busy_valid = true; + } + i++; + } + assert(gpu.busy_valid == (jiffies >= 2200)); + apple_clpc_sample(&c); + assert(published == 0x35 && gpu.level == 3); + } + assert(i == n); + // The stale window's diluted share would have dropped the new burst at once. + gpu.active = false; gpu.busy_valid = false; jiffies = 2400; apple_clpc_sample(&c); + gpu.active = true; gpu.busy = 85; gpu.busy_valid = true; jiffies = 3000; + apple_clpc_sample(&c); assert(published == 0x01 && gpu.level == 0); + gpu.active = false; jiffies = 3100; apple_clpc_sample(&c); assert(published == 0); +} + // T8132's G16 firmware keeps graphics powered while the GPU idles: the // M5/F3 floor follows the work the GPU driver reports, as on T6040. static void check_t8132(void) { @@ -458,6 +727,8 @@ def cells(name): jiffies=264; apple_clpc_sample(&c); assert(published==0); t6041_from_dt(); check_t6041_busy(); + check_t6041_long_in_flight(); + check_t6041_idle_burst(); check_t8132(); check_t6041(&apple_clpc_hw_t6041); check_t6041(&t6041_dt_hw); From e0b93b21f2142629c1908747ece397bf0523c167 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Thu, 19 Nov 2026 18:22:02 +0000 Subject: [PATCH 0213/1514] arm64: dts: apple: t6041: the GPU busy-share memory states measured on the J616c Give the M4 Max's CLPC node the GPU busy-share memory states measured on the 32-core J616c: DCS 1, 2, 4, 5 and fabric 0, 0, 0, 3, split at 160, 500 and 800 permille of the busy share reported by the GPU driver. The top column matches apple_clpc_hw_t6041's DCS 5 / fabric 3 floor, so busy GPU work keeps full memory bandwidth while light work such as scrolling a browser drops to the lower memory states. These values were measured on the 32-core J616c only; placing them in t6041.dtsi also applies them to the J614c and J575c (which have not been measured yet). With a 3 GB/s copy on the J616c: DCS 0 / fabric 0 draws 5.46 W at 309 ns DRAM latency, DCS 3 draws 6.22 W at 166 ns, DCS 4 draws 6.92 W at 114 ns, and DCS 5 draws 7.04 W at 113 ns. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041.dtsi | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 23720e5e53b6b7..dd165c4b151767 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -341,8 +341,20 @@ apple,static-voters = <1 3>; }; +/* + * The GPU's memory states by the busy share the GPU driver reports, measured + * on a J616c: DCS 1, 2, 4 or 5 and fabric 0, 0, 0 or 3, split at 160, 500 + * and 800 permille, and the top column with no share reported. The top + * column matches apple_clpc_hw_t6041's DCS 5 / fabric 3 floor (full memory + * bandwidth), so busy GPU work keeps it; light work such as scrolling a + * browser gets the lower columns. With a 3 GB/s copy: DCS 0 / fabric 0 + * 5.46 W at 309 ns DRAM latency, DCS 3 6.22 W at 166 ns, DCS 4 6.92 W at + * 114 ns, DCS 5 7.04 W at 113 ns. + */ &clpc { compatible = "apple,t6041-max-clpc", "apple,t6041-clpc"; + apple,gpu-busy-memory-states = <1 2 4 5>, <0 0 0 3>; + apple,gpu-busy-permille = <160 500 800>; }; / { From 5b302458524f1ea86d992722cae8e40a810a87b2 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 20 Nov 2026 02:10:16 -0500 Subject: [PATCH 0214/1514] soc: apple: mcc: wait for display controllers to retire boot scanout A display controller can keep scanning out the framebuffer the bootloader left on screen after it binds, and also while its node stays disabled because the bootloader kept the boot framebuffer as the display. For a boot DMA supplier that an enabled simple-framebuffer names as its display, enable cache allocation only once the display driver reports that a displayed swap of its own has retired that scanout. Other suppliers still only need to be bound. A supplier phandle that does not resolve, or a detached consumer or supplier node, leaves allocation off. The display driver reserves the record before it can retire the scanout, so the one-shot retirement cannot be lost to an allocation failure. Retirement survives either driver's unbind and reprobe; records and waiters are dropped when a node they name is detached, and none is added or retried for a detached node. OF flags a node detached before it calls the reconfig notifiers, so probe cannot hold a detach off, but the notifier always runs after the flag is set. Probe therefore checks its nodes and enables allocation under the lock the detach notifier takes, and registers the enabled controller there. Either probe sees the flag and fails, or the notifier finds the controller and turns allocation off, unless the detached node is a supplier whose boot scanout already retired, and cancels the enable a wake from deep sleep would do. Suspend, resume and shutdown take the same lock. A failed enable's write-back (up to 100 ms per plane) is done under that lock and delays a detach by as much. A deferred controller is retried outside the display driver's receive path. Signed-off-by: Erik Bourget --- .../bindings/soc/apple/apple,t8140-mcc.yaml | 5 +- drivers/soc/apple/Kconfig | 4 + drivers/soc/apple/Makefile | 2 + drivers/soc/apple/mcc-boot-dma.c | 304 ++++++++++++ drivers/soc/apple/mcc.c | 180 ++++++- include/linux/soc/apple/mcc.h | 37 ++ tools/asahi/mcc-boot-dma-tests.py | 446 ++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 8 files changed, 967 insertions(+), 15 deletions(-) create mode 100644 drivers/soc/apple/mcc-boot-dma.c create mode 100644 include/linux/soc/apple/mcc.h create mode 100644 tools/asahi/mcc-boot-dma-tests.py diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml index 08f2f7431b6c4c..c976dcca6d9610 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-mcc.yaml @@ -111,7 +111,10 @@ allOf: maxItems: 1 description: Devices that take over DMA the bootloader left running. Cache allocation - is enabled only once each of them is bound to its driver. + is enabled only once each of them is bound to its driver. A supplier + that an enabled simple-framebuffer names as its display is scanning out + that boot framebuffer, enabled or not, and is waited for until a + displayed swap of its own has replaced it. required: - compatible diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 33644e1d08bf97..35d9573e99f03a 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -46,8 +46,12 @@ config APPLE_MAILBOX Say Y here if you have an Apple SoC. +config APPLE_MCC_BOOT_DMA + bool + config APPLE_MCC tristate "Apple T8140, T6040 and T6050 system level cache" + select APPLE_MCC_BOOT_DMA depends on ARCH_APPLE || COMPILE_TEST depends on OF default ARCH_APPLE diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 233df860395b8c..bda77a82ca6442 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only +obj-$(CONFIG_APPLE_MCC_BOOT_DMA) += mcc-boot-dma.o + obj-$(CONFIG_APPLE_J613_DISPLAY_SYNC) += j613-display.o obj-$(CONFIG_APPLE_DBGVIEW) += apple-dbgview.o diff --git a/drivers/soc/apple/mcc-boot-dma.c b/drivers/soc/apple/mcc-boot-dma.c new file mode 100644 index 00000000000000..0dc303327468d5 --- /dev/null +++ b/drivers/soc/apple/mcc-boot-dma.c @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * A display controller can keep scanning out the boot loader's framebuffer + * after it binds, or with its node disabled. Its driver reserves a record + * while it tracks that boot scanout and marks it once a displayed swap of + * its own has retired it. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct apple_mcc_scanout { + struct list_head link; + struct device_node *supplier; + bool retired; +}; + +struct apple_mcc_scanout_waiter { + struct list_head link; + struct device_node *consumer; + struct device_node *supplier; +}; + +/* + * Retirement survives either driver's unbind and reprobe; records and + * waiters go when a node they name is detached. + */ +static DEFINE_MUTEX(boot_scanout_lock); +static LIST_HEAD(boot_scanouts); +static LIST_HEAD(waiting_consumers); +static LIST_HEAD(retry_consumers); +static LIST_HEAD(enabled_consumers); + +/* A node detached already: the notifier has dropped, or will drop, its entries. */ +static bool node_detached(struct device_node *np) +{ + return of_node_check_flag(np, OF_DETACHED); +} + +static struct apple_mcc_scanout *find_scanout_locked(struct device_node *supplier) +{ + struct apple_mcc_scanout *scanout; + + list_for_each_entry(scanout, &boot_scanouts, link) { + if (scanout->supplier == supplier) + return scanout; + } + return NULL; +} + +int apple_mcc_boot_scanout_reserve(struct device_node *supplier) +{ + struct apple_mcc_scanout *scanout; + int ret = 0; + + mutex_lock(&boot_scanout_lock); + if (node_detached(supplier)) { + ret = -ENODEV; + goto out_unlock; + } + /* A scanout retired before the supplier was rebound stays retired. */ + if (find_scanout_locked(supplier)) + goto out_unlock; + scanout = kzalloc_obj(*scanout); + if (!scanout) { + ret = -ENOMEM; + goto out_unlock; + } + scanout->supplier = of_node_get(supplier); + list_add_tail(&scanout->link, &boot_scanouts); + +out_unlock: + mutex_unlock(&boot_scanout_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_reserve); + +/* + * Held across a cache controller's final check of its nodes and its + * allocation enable, and by the detach notifier. OF flags a node detached + * before it calls the notifier, so probe cannot hold a detach off; but the + * notifier always runs after the flag is set. Either probe sees the flag, + * or it enabled allocation and registered first, and the notifier then + * turns allocation off (apple_mcc_boot_dma_lost()). + */ +void apple_mcc_boot_dma_lock(void) +{ + mutex_lock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_lock); + +void apple_mcc_boot_dma_unlock(void) +{ + mutex_unlock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_unlock); + +/* Under apple_mcc_boot_dma_lock(), once allocation is enabled. */ +void apple_mcc_boot_dma_register_locked(struct apple_mcc_boot_dma_consumer *consumer) +{ + list_add_tail(&consumer->link, &enabled_consumers); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_register_locked); + +/* Before the consumer turns allocation off and goes. */ +void apple_mcc_boot_dma_unregister(struct apple_mcc_boot_dma_consumer *consumer) +{ + mutex_lock(&boot_scanout_lock); + list_del_init(&consumer->link); + mutex_unlock(&boot_scanout_lock); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_dma_unregister); + +/* + * Whether detaching @np leaves @consumer's boot DMA unconfirmed: its own + * node, or a boot DMA supplier whose boot scanout has not retired. The + * detached node no longer resolves, so match its phandle. + */ +static bool consumer_loses_boot_dma_locked(struct apple_mcc_boot_dma_consumer *consumer, + struct device_node *np) +{ + struct device_node *node = consumer->dev->of_node; + struct apple_mcc_scanout *scanout; + u32 phandle; + int i, n; + + if (node == np) + return true; + if (!np->phandle) + return false; + n = of_property_count_u32_elems(node, "apple,boot-dma-devices"); + for (i = 0; i < n; i++) { + if (of_property_read_u32_index(node, "apple,boot-dma-devices", i, &phandle) || + phandle != np->phandle) + continue; + scanout = find_scanout_locked(np); + return !scanout || !scanout->retired; + } + return false; +} + +static void waiter_free(struct apple_mcc_scanout_waiter *waiter) +{ + of_node_put(waiter->consumer); + of_node_put(waiter->supplier); + kfree(waiter); +} + +int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier) +{ + struct apple_mcc_scanout_waiter *waiter; + struct apple_mcc_scanout *scanout; + struct device_node *consumer = dev->of_node; + int ret = -EPROBE_DEFER; + + mutex_lock(&boot_scanout_lock); + if (node_detached(consumer) || node_detached(supplier)) { + ret = -ENODEV; + goto out_unlock; + } + scanout = find_scanout_locked(supplier); + if (scanout && scanout->retired) { + ret = 0; + goto out_unlock; + } + + list_for_each_entry(waiter, &waiting_consumers, link) { + if (waiter->consumer == consumer && waiter->supplier == supplier) + goto out_unlock; + } + waiter = kzalloc_obj(*waiter); + if (!waiter) { + ret = -ENOMEM; + goto out_unlock; + } + waiter->consumer = of_node_get(consumer); + waiter->supplier = of_node_get(supplier); + list_add_tail(&waiter->link, &waiting_consumers); + +out_unlock: + mutex_unlock(&boot_scanout_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_ready); + +static void apple_mcc_retry(struct work_struct *work) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + LIST_HEAD(pending); + + mutex_lock(&boot_scanout_lock); + list_splice_tail_init(&retry_consumers, &pending); + mutex_unlock(&boot_scanout_lock); + + list_for_each_entry_safe(waiter, tmp, &pending, link) { + struct platform_device *pdev = NULL; + + list_del(&waiter->link); + mutex_lock(&boot_scanout_lock); + if (!node_detached(waiter->consumer) && !node_detached(waiter->supplier)) + pdev = of_find_device_by_node(waiter->consumer); + mutex_unlock(&boot_scanout_lock); + if (pdev) { + device_initial_probe(&pdev->dev); + put_device(&pdev->dev); + } + waiter_free(waiter); + } +} + +static DECLARE_WORK(retry_work, apple_mcc_retry); + +void apple_mcc_boot_scanout_retired(struct device_node *supplier) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + struct apple_mcc_scanout *scanout; + bool schedule = false; + + mutex_lock(&boot_scanout_lock); + /* Reserved by apple_mcc_boot_scanout_reserve(): marking it cannot fail. */ + scanout = find_scanout_locked(supplier); + if (scanout) + scanout->retired = true; + else + WARN_ON_ONCE(!node_detached(supplier)); + + list_for_each_entry_safe(waiter, tmp, &waiting_consumers, link) { + if (waiter->supplier == supplier) { + list_move_tail(&waiter->link, &retry_consumers); + schedule = true; + } + } + mutex_unlock(&boot_scanout_lock); + + if (schedule) + schedule_work(&retry_work); +} +EXPORT_SYMBOL_GPL(apple_mcc_boot_scanout_retired); + +static void drop_waiters_locked(struct list_head *list, struct device_node *np) +{ + struct apple_mcc_scanout_waiter *waiter, *tmp; + + list_for_each_entry_safe(waiter, tmp, list, link) { + if (waiter->consumer == np || waiter->supplier == np) { + list_del(&waiter->link); + waiter_free(waiter); + } + } +} + +static int apple_mcc_of_notify(struct notifier_block *nb, unsigned long action, void *arg) +{ + struct apple_mcc_boot_dma_consumer *consumer, *next; + struct of_reconfig_data *rd = arg; + struct apple_mcc_scanout *scanout, *tmp; + + if (action != OF_RECONFIG_DETACH_NODE) + return NOTIFY_DONE; + + mutex_lock(&boot_scanout_lock); + /* Before the records go: a retired supplier may detach. */ + list_for_each_entry_safe(consumer, next, &enabled_consumers, link) { + if (consumer_loses_boot_dma_locked(consumer, rd->dn)) { + list_del_init(&consumer->link); + consumer->lost(consumer); + } + } + list_for_each_entry_safe(scanout, tmp, &boot_scanouts, link) { + if (scanout->supplier == rd->dn) { + list_del(&scanout->link); + of_node_put(scanout->supplier); + kfree(scanout); + } + } + drop_waiters_locked(&waiting_consumers, rd->dn); + drop_waiters_locked(&retry_consumers, rd->dn); + mutex_unlock(&boot_scanout_lock); + return NOTIFY_OK; +} + +static struct notifier_block apple_mcc_of_nb = { + .notifier_call = apple_mcc_of_notify, +}; + +static int __init apple_mcc_boot_dma_init(void) +{ + /* Without CONFIG_OF_DYNAMIC no node is ever detached. */ + if (IS_ENABLED(CONFIG_OF_DYNAMIC)) + return of_reconfig_notifier_register(&apple_mcc_of_nb); + return 0; +} +core_initcall(apple_mcc_boot_dma_init); diff --git a/drivers/soc/apple/mcc.c b/drivers/soc/apple/mcc.c index dcc36d303f652a..8bcdfc740eeaac 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #if IS_ENABLED(CONFIG_APPLE_MCC_KUNIT_TEST) @@ -51,6 +52,7 @@ struct apple_mcc { u32 ways; /* Turned off for a deep sleep, to be turned back on after it. */ bool sleep_disabled; + struct apple_mcc_boot_dma_consumer boot_dma; }; static void apple_mcc_writel(struct apple_mcc *mcc, unsigned int plane, @@ -136,14 +138,72 @@ static int apple_mcc_enable_t8132(struct apple_mcc *mcc) return 0; } +/* An enabled boot framebuffer that names @supplier as its display hardware. */ +static bool apple_mcc_scans_boot_framebuffer(struct device_node *supplier) +{ + struct device_node *fb, *display; + + for_each_compatible_node(fb, NULL, "simple-framebuffer") { + if (!of_device_is_available(fb)) + continue; + display = of_parse_phandle(fb, "display", 0); + of_node_put(display); + if (display && display == supplier) { + of_node_put(fb); + return true; + } + } + return false; +} + static int apple_mcc_wait_boot_dma(struct device *dev) { struct of_phandle_iterator it; int ret; + /* A detached node's suppliers can no longer be confirmed. */ + if (of_node_check_flag(dev->of_node, OF_DETACHED)) + return -ENODEV; + of_for_each_phandle(&it, ret, dev->of_node, "apple,boot-dma-devices", NULL, 0) { - struct platform_device *pdev = of_find_device_by_node(it.node); - bool bound = pdev && device_is_bound(&pdev->dev); + struct platform_device *pdev; + bool bound; + + /* + * An empty entry names no device. A phandle that resolves to + * no node is a device tree error that a retry cannot fix, and + * leaves its boot DMA unconfirmed: keep allocation off. + */ + if (!it.node) { + if (!it.phandle) + continue; + return dev_err_probe(dev, -EINVAL, + "boot DMA supplier phandle %#x does not resolve\n", + it.phandle); + } + if (of_node_check_flag(it.node, OF_DETACHED)) { + of_node_put(it.node); + return -ENODEV; + } + + /* + * A display controller scanning out the boot framebuffer keeps + * that DMA running whether or not its node is enabled or bound, + * until its driver reports a displayed swap of its own. + */ + if (apple_mcc_scans_boot_framebuffer(it.node)) { + ret = apple_mcc_boot_scanout_ready(dev, it.node); + if (ret) { + ret = dev_err_probe(dev, ret, + "waiting for %pOF to retire boot scanout\n", + it.node); + of_node_put(it.node); + return ret; + } + } + + pdev = of_find_device_by_node(it.node); + bound = pdev && device_is_bound(&pdev->dev); if (pdev) put_device(&pdev->dev); @@ -159,6 +219,29 @@ static int apple_mcc_wait_boot_dma(struct device *dev) return ret == -ENOENT ? 0 : ret; } +/* Under apple_mcc_boot_dma_lock(): the last check before allocation is enabled. */ +static bool apple_mcc_boot_dma_detached(struct device *dev) +{ + struct of_phandle_iterator it; + int ret; + + if (of_node_check_flag(dev->of_node, OF_DETACHED)) + return true; + of_for_each_phandle(&it, ret, dev->of_node, "apple,boot-dma-devices", NULL, 0) { + /* The first walk resolved it: a node that went is detached. */ + if (!it.node) { + if (it.phandle) + return true; + continue; + } + if (of_node_check_flag(it.node, OF_DETACHED)) { + of_node_put(it.node); + return true; + } + } + return false; +} + static bool apple_mcc_plane_ready(struct apple_mcc *mcc, unsigned int plane) { void __iomem *regs = mcc->planes[plane]; @@ -254,6 +337,32 @@ static void apple_mcc_quiesce(struct apple_mcc *mcc) mcc->enabled = false; } +/* Turn allocation off for good: removal, or a boot DMA node detached. */ +static void apple_mcc_turn_off(struct apple_mcc *mcc) +{ + /* Without this driver nothing writes T8132's cache back before a deep sleep. */ + if (mcc->retained) { + apple_mcc_disable_t8132(mcc); + mcc->enabled = false; + return; + } + apple_mcc_quiesce(mcc); +} + +/* + * The detach notifier, under the boot DMA lock. Only the disable and its + * write-back: marked not enabled, nothing later writes this cache back. + */ +static void apple_mcc_boot_dma_lost(struct apple_mcc_boot_dma_consumer *consumer) +{ + struct apple_mcc *mcc = container_of(consumer, struct apple_mcc, boot_dma); + + dev_warn(mcc->dev, "boot DMA node detached: system level cache allocation off\n"); + apple_mcc_turn_off(mcc); + /* Nor does a wake turn it back on. */ + mcc->sleep_disabled = false; +} + static int apple_mcc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -265,6 +374,9 @@ static int apple_mcc_probe(struct platform_device *pdev) return -ENOMEM; mcc->dev = dev; + INIT_LIST_HEAD(&mcc->boot_dma.link); + mcc->boot_dma.dev = dev; + mcc->boot_dma.lost = apple_mcc_boot_dma_lost; mcc->retained = of_device_is_compatible(dev->of_node, "apple,t8132-mcc"); mcc->ways_off = of_device_is_compatible(dev->of_node, "apple,t8142-mcc"); while (platform_get_resource(pdev, IORESOURCE_MEM, mcc->nr_planes)) { @@ -288,14 +400,30 @@ static int apple_mcc_probe(struct platform_device *pdev) platform_set_drvdata(pdev, mcc); + /* + * A node detached after this check is flagged before, and notified + * after, the enable below: the notifier finds this controller + * registered and turns allocation off again. The lock is held across + * the enable, including a failed enable's write-back of the planes it + * reached (up to MCC_FLUSH_TIMEOUT_US each), which delays a detach. + */ + apple_mcc_boot_dma_lock(); + if (apple_mcc_boot_dma_detached(dev)) { + apple_mcc_boot_dma_unlock(); + return -ENODEV; + } /* Allocation is only a performance setting: leave a cache that is not ready alone. */ ret = mcc->retained ? apple_mcc_enable_t8132(mcc) : apple_mcc_enable(mcc); + if (!ret) { + mcc->enabled = true; + apple_mcc_boot_dma_register_locked(&mcc->boot_dma); + } + apple_mcc_boot_dma_unlock(); if (ret == -EBUSY) return 0; if (ret) return ret; - mcc->enabled = true; if (mcc->ways_off) mcc->ways = FIELD_GET(MCC_CACHE_WAYS_ENABLED, readl(mcc->planes[0] + MCC_CACHE_WAYS)); @@ -307,28 +435,27 @@ static void apple_mcc_remove(struct platform_device *pdev) { struct apple_mcc *mcc = platform_get_drvdata(pdev); - /* Without this driver nothing writes T8132's cache back before a deep sleep. */ - if (mcc->retained) { - apple_mcc_disable_t8132(mcc); - mcc->enabled = false; - return; - } - apple_mcc_quiesce(mcc); + /* After this, the detach notifier no longer reaches this controller. */ + apple_mcc_boot_dma_unregister(&mcc->boot_dma); + apple_mcc_turn_off(mcc); } static void apple_mcc_shutdown(struct platform_device *pdev) { struct apple_mcc *mcc = platform_get_drvdata(pdev); - if (mcc) - apple_mcc_quiesce(mcc); + if (!mcc) + return; + apple_mcc_boot_dma_lock(); + apple_mcc_quiesce(mcc); + apple_mcc_boot_dma_unlock(); } /* * A deep sleep takes the cache's power with the rest of the SoC: stop allocating and write it * back first, as at shutdown, and allocate again after. Suspend-to-idle keeps it. */ -static int apple_mcc_suspend_noirq(struct device *dev) +static int apple_mcc_suspend_locked(struct device *dev) { struct apple_mcc *mcc = dev_get_drvdata(dev); int ret; @@ -360,7 +487,7 @@ static int apple_mcc_suspend_noirq(struct device *dev) return 0; } -static int apple_mcc_resume_noirq(struct device *dev) +static int apple_mcc_resume_locked(struct device *dev) { struct apple_mcc *mcc = dev_get_drvdata(dev); int ret; @@ -381,6 +508,31 @@ static int apple_mcc_resume_noirq(struct device *dev) return 0; } +/* + * Serialized with the OF detach notifier, which may turn allocation off + * and cancel the enable after the wake. Noirq callbacks may sleep, and + * nothing taken under the lock takes it again. + */ +static int apple_mcc_suspend_noirq(struct device *dev) +{ + int ret; + + apple_mcc_boot_dma_lock(); + ret = apple_mcc_suspend_locked(dev); + apple_mcc_boot_dma_unlock(); + return ret; +} + +static int apple_mcc_resume_noirq(struct device *dev) +{ + int ret; + + apple_mcc_boot_dma_lock(); + ret = apple_mcc_resume_locked(dev); + apple_mcc_boot_dma_unlock(); + return ret; +} + static const struct dev_pm_ops apple_mcc_pm_ops = { NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_mcc_suspend_noirq, apple_mcc_resume_noirq) }; diff --git a/include/linux/soc/apple/mcc.h b/include/linux/soc/apple/mcc.h new file mode 100644 index 00000000000000..76e92ea270a3ba --- /dev/null +++ b/include/linux/soc/apple/mcc.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _LINUX_SOC_APPLE_MCC_H_ +#define _LINUX_SOC_APPLE_MCC_H_ + +#include +#include +#include + +struct device; +struct device_node; + +/* A cache controller with allocation enabled, for the OF detach notifier. */ +struct apple_mcc_boot_dma_consumer { + struct list_head link; + struct device *dev; + /* Under the boot DMA lock: turn allocation off. */ + void (*lost)(struct apple_mcc_boot_dma_consumer *consumer); +}; + +#if IS_ENABLED(CONFIG_APPLE_MCC_BOOT_DMA) +int apple_mcc_boot_scanout_reserve(struct device_node *supplier); +void apple_mcc_boot_scanout_retired(struct device_node *supplier); +int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier); +void apple_mcc_boot_dma_lock(void); +void apple_mcc_boot_dma_unlock(void); +void apple_mcc_boot_dma_register_locked(struct apple_mcc_boot_dma_consumer *consumer); +void apple_mcc_boot_dma_unregister(struct apple_mcc_boot_dma_consumer *consumer); +#else +static inline int apple_mcc_boot_scanout_reserve(struct device_node *supplier) +{ + return 0; +} + +static inline void apple_mcc_boot_scanout_retired(struct device_node *supplier) { } +#endif + +#endif diff --git a/tools/asahi/mcc-boot-dma-tests.py b/tools/asahi/mcc-boot-dma-tests.py new file mode 100644 index 00000000000000..d0400c29465b2d --- /dev/null +++ b/tools/asahi/mcc-boot-dma-tests.py @@ -0,0 +1,446 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run apple-mcc's boot DMA supplier walk against mock device tree nodes.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +SRC = (ROOT / 'drivers/soc/apple/mcc.c').read_text() + + +def function(name): + a = SRC.rfind('\n', 0, SRC.index(name + '(struct')) + 1 + b = SRC.index('\n}\n', a) + 3 + return SRC[a:b] + + +CODE = (function('apple_mcc_scans_boot_framebuffer') + function('apple_mcc_wait_boot_dma') + + function('apple_mcc_boot_dma_detached')) +UNRESOLVED = 'if (!it.node) {' +DETACHED = 'if (of_node_check_flag(it.node, OF_DETACHED)) {' +assert CODE.count(UNRESOLVED) == 2 and CODE.count(DETACHED) == 2 +if '--accept-unresolved' in sys.argv: + CODE = CODE.replace(UNRESOLVED, 'if (0) {', 1) +if '--final-skips-unresolved' in sys.argv: + a = CODE.index('apple_mcc_boot_dma_detached(') + CODE = CODE[:a] + CODE[a:].replace('return true;\n\t\t\tcontinue;', 'continue;\n\t\t\tcontinue;', 1) +if '--ignore-detached-supplier' in sys.argv: + CODE = CODE.replace(DETACHED, 'if (0) {', 1) + +PRE = r''' +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define EPROBE_DEFER 517 +#define OF_DETACHED 3 +struct device_node { + const char *name; u32 phandle; bool detached, detach_on_lookup, available, fb, bound, retired; + struct device_node *display; u32 boot[4]; int nboot, refs; +}; +struct device { struct device_node *of_node; }; +struct platform_device { struct device dev; struct device_node *np; }; +static struct device_node *nodes[8]; +static int nnodes, readies; +static struct device_node *get(struct device_node *n) { if (n) n->refs++; return n; } +static void of_node_put(struct device_node *n) { if (n) { assert(n->refs > 0); n->refs--; } } +static bool of_node_check_flag(struct device_node *n, int f) { assert(n && f == OF_DETACHED); return n->detached; } +static bool of_device_is_available(struct device_node *n) { return n->available; } +static struct device_node *of_parse_phandle(struct device_node *n, const char *p, int i) +{ return get(n->display); } +static struct device_node *next_fb(struct device_node *from) +{ + int i = 0; + + if (from) { + while (nodes[i] != from) + i++; + of_node_put(from); + i++; + } + for (; i < nnodes; i++) + if (nodes[i]->fb) + return get(nodes[i]); + return NULL; +} +#define for_each_compatible_node(dn, type, compat) \ + for (dn = next_fb(NULL); dn; dn = next_fb(dn)) +struct of_phandle_iterator { struct device_node *node, *parent; u32 phandle; int i; }; +static struct device_node *by_phandle(u32 ph) +{ + /* A detached node has left the tree and its phandle cache. */ + for (int i = 0; i < nnodes; i++) + if (nodes[i]->phandle == ph && !nodes[i]->detached) { + /* Detached between lookup and use. */ + if (nodes[i]->detach_on_lookup) + nodes[i]->detached = true; + return get(nodes[i]); + } + return NULL; +} +static bool it_next(struct of_phandle_iterator *it, int *err) +{ + of_node_put(it->node); + it->node = NULL; + if (it->i >= it->parent->nboot) { + *err = -ENOENT; + return false; + } + it->phandle = it->parent->boot[it->i++]; + it->node = it->phandle ? by_phandle(it->phandle) : NULL; + return true; +} +#define of_for_each_phandle(it, err, np, name, cells, count) \ + for ((it)->node = NULL, (it)->parent = (np), (it)->i = 0; it_next((it), &(err));) +static struct platform_device pdevs[8]; +static struct platform_device *of_find_device_by_node(struct device_node *n) +{ + for (int i = 0; i < nnodes; i++) + if (nodes[i] == n) { + pdevs[i].np = get(n); + return &pdevs[i]; + } + return NULL; +} +static bool device_is_bound(struct device *d) { return container_of_pdev(d)->np->bound; } +'''.replace('container_of_pdev(d)', '((struct platform_device *)((char *)(d) - offsetof(struct platform_device, dev)))') + r''' +static void put_device(struct device *d) +{ of_node_put(((struct platform_device *)((char *)d - offsetof(struct platform_device, dev)))->np); } +#define dev_err_probe(dev, err, ...) (err) +static int apple_mcc_boot_scanout_ready(struct device *dev, struct device_node *supplier) +{ + assert(supplier && !supplier->detached); + readies++; + return supplier->retired ? 0 : -EPROBE_DEFER; +} +''' + +MAIN = r''' +static struct device_node mcc, dcp, disp, fb; +static struct device dev = { .of_node = &mcc }; + +static void reset(void) +{ + mcc = (struct device_node){ .name = "mcc", .phandle = 1, .available = true }; + dcp = (struct device_node){ .name = "dcp", .phandle = 2 }; + disp = (struct device_node){ .name = "disp", .phandle = 3, .available = true, .bound = true }; + fb = (struct device_node){ .name = "fb", .phandle = 4, .available = true, .fb = true }; + nodes[0] = &mcc; nodes[1] = &dcp; nodes[2] = &disp; nodes[3] = &fb; nnodes = 4; + readies = 0; +} + +static int walk(void) +{ + int ret = apple_mcc_wait_boot_dma(&dev); + + for (int i = 0; i < nnodes; i++) + assert(nodes[i]->refs == 0); + return ret; +} + +int main(void) +{ + /* Legacy supplier, bound: allocation allowed, no scanout wait. */ + reset(); mcc.boot[0] = 3; mcc.nboot = 1; + assert(walk() == 0 && !readies); + disp.bound = false; + assert(walk() == -EPROBE_DEFER); + + /* Empty entry: no device. */ + reset(); mcc.nboot = 1; + assert(walk() == 0); + + /* Unresolved phandle, and an enabled framebuffer naming no display. */ + reset(); mcc.boot[0] = 99; mcc.nboot = 1; + assert(walk() == -EINVAL && !readies); + /* Unresolved, then a legacy supplier: still refused. */ + reset(); mcc.boot[0] = 99; mcc.boot[1] = 3; mcc.nboot = 2; + assert(walk() == -EINVAL); + + /* A disabled DCP scanning the boot framebuffer keeps allocation off. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; + assert(walk() == -EPROBE_DEFER && readies == 1); + /* A bound DCP scanning the boot framebuffer waits until scanout retires. */ + dcp.available = true; dcp.bound = true; + assert(walk() == -EPROBE_DEFER && readies == 2); + dcp.retired = true; + assert(walk() == 0 && readies == 3); + /* An unbound DCP still defers to bind even after scanout retired. */ + dcp.bound = false; + assert(walk() == -EPROBE_DEFER && readies == 4); + /* Disabled framebuffer: no scanout wait, and a disabled supplier still defers to bind. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; fb.available = false; + assert(walk() == -EPROBE_DEFER && !readies); + dcp.available = true; dcp.bound = true; + assert(walk() == 0 && !readies); + + /* Detached consumer or supplier: cannot confirm. */ + reset(); mcc.boot[0] = 2; mcc.nboot = 1; fb.display = &dcp; dcp.retired = true; + mcc.detached = true; + assert(walk() == -ENODEV); + /* A detached supplier no longer resolves; one detached after its lookup. */ + mcc.detached = false; dcp.detached = true; + assert(walk() == -EINVAL && !readies); + dcp.detached = false; dcp.detach_on_lookup = true; + assert(walk() == -ENODEV && !readies); + + /* The final check under the lock, before allocation is enabled. */ + reset(); mcc.boot[0] = 3; mcc.boot[1] = 2; mcc.nboot = 2; + assert(!apple_mcc_boot_dma_detached(&dev)); + dcp.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + dcp.detached = false; mcc.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + /* A supplier that disappears between the two walks. */ + reset(); mcc.boot[0] = 3; mcc.boot[1] = 2; mcc.boot[2] = 0; mcc.nboot = 3; + fb.display = &dcp; dcp.retired = true; dcp.available = true; dcp.bound = true; + assert(walk() == 0); + dcp.detached = true; + assert(apple_mcc_boot_dma_detached(&dev)); + dcp.detached = false; + assert(!apple_mcc_boot_dma_detached(&dev)); + for (int i = 0; i < nnodes; i++) + assert(nodes[i]->refs == 0); + return 0; +} +''' + +# The detach notifier in mcc-boot-dma.c, against an enabled controller. +BOOT = (ROOT / 'drivers/soc/apple/mcc-boot-dma.c').read_text() +HDR = (ROOT / 'include/linux/soc/apple/mcc.h').read_text() +LOSES = 'return !scanout || !scanout->retired;' +assert BOOT.count(LOSES) == 1 +if '--detach-retired-only' in sys.argv: + BOOT = BOOT.replace(LOSES, 'return !scanout;') +strip = lambda text: '\n'.join(l for l in text.splitlines() if not l.startswith('#include')) +HDR = strip(HDR).replace('#if IS_ENABLED(CONFIG_APPLE_MCC_BOOT_DMA)', '#if 1') + +NPRE = r""" +#include +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define EPROBE_DEFER 517 +#define OF_DETACHED 3 +#define __init +#define core_initcall(f) +#define EXPORT_SYMBOL_GPL(f) +#define IS_ENABLED(x) 1 +#define WARN_ON_ONCE(c) assert(!(c)) +#define container_of(p, t, m) ((t *)((char *)(p) - offsetof(t, m))) +struct list_head { struct list_head *next, *prev; }; +#define LIST_HEAD(n) struct list_head n = { &(n), &(n) } +static void INIT_LIST_HEAD(struct list_head *h) { h->next = h->prev = h; } +static bool list_empty(struct list_head *h) { return h->next == h; } +static void list_add_tail(struct list_head *n, struct list_head *h) +{ n->next = h; n->prev = h->prev; h->prev->next = n; h->prev = n; } +static void list_del(struct list_head *n) { n->prev->next = n->next; n->next->prev = n->prev; } +static void list_del_init(struct list_head *n) { list_del(n); INIT_LIST_HEAD(n); } +static void list_move_tail(struct list_head *n, struct list_head *h) { list_del(n); list_add_tail(n, h); } +static void list_splice_tail_init(struct list_head *n, struct list_head *h) +{ while (!list_empty(n)) list_move_tail(n->next, h); } +#define list_entry(p, t, m) container_of(p, t, m) +#define list_for_each_entry(p, h, m) \ + for (p = list_entry((h)->next, typeof(*p), m); &p->m != (h); p = list_entry(p->m.next, typeof(*p), m)) +#define list_for_each_entry_safe(p, n, h, m) \ + for (p = list_entry((h)->next, typeof(*p), m), n = list_entry(p->m.next, typeof(*p), m); \ + &p->m != (h); p = n, n = list_entry(n->m.next, typeof(*n), m)) +static int locked; +struct mutex { int unused; }; +#define DEFINE_MUTEX(n) struct mutex n +static void mutex_lock(struct mutex *m) { assert(!locked); locked = 1; } +static void mutex_unlock(struct mutex *m) { assert(locked); locked = 0; } +#define kzalloc_obj(x) calloc(1, sizeof(x)) +#define kfree free +struct device_node { u32 phandle; bool detached; u32 boot[4]; int nboot; int refs; }; +struct device { struct device_node *of_node; }; +struct platform_device { struct device dev; }; +static struct device_node *of_node_get(struct device_node *n) { if (n) n->refs++; return n; } +static void of_node_put(struct device_node *n) { if (n) { assert(n->refs > 0); n->refs--; } } +static bool of_node_check_flag(struct device_node *n, int f) { return n->detached; } +static int of_property_count_u32_elems(struct device_node *n, const char *p) { return n->nboot; } +static int of_property_read_u32_index(struct device_node *n, const char *p, int i, u32 *v) +{ *v = n->boot[i]; return 0; } +static struct platform_device *of_find_device_by_node(struct device_node *n) { return NULL; } +static void device_initial_probe(struct device *d) { } +static void put_device(struct device *d) { } +struct work_struct { int unused; }; +#define DECLARE_WORK(n, f) struct work_struct n +static void schedule_work(struct work_struct *w) { } +struct notifier_block { int (*notifier_call)(struct notifier_block *, unsigned long, void *); }; +#define NOTIFY_DONE 0 +#define NOTIFY_OK 1 +#define OF_RECONFIG_DETACH_NODE 2 +struct of_reconfig_data { struct device_node *dn; }; +static int of_reconfig_notifier_register(struct notifier_block *nb) { return 0; } +""" + +NMAIN = r""" +static int lost_calls; +static void lost(struct apple_mcc_boot_dma_consumer *c) +{ + assert(locked); + lost_calls++; +} + +static struct device_node mcc = { .phandle = 1, .boot = { 3, 2 }, .nboot = 2 }; +static struct device_node dcp = { .phandle = 2 }, disp = { .phandle = 3 }, other = { .phandle = 9 }; +static struct device dev = { .of_node = &mcc }; +static struct apple_mcc_boot_dma_consumer c = { .dev = &dev, .lost = lost }; + +static void enable(void) +{ + apple_mcc_boot_dma_lock(); + apple_mcc_boot_dma_register_locked(&c); + apple_mcc_boot_dma_unlock(); +} + +static int detach(struct device_node *n) +{ + struct of_reconfig_data rd = { .dn = n }; + int before = lost_calls; + + n->detached = true; + apple_mcc_of_notify(NULL, OF_RECONFIG_DETACH_NODE, &rd); + n->detached = false; + return lost_calls - before; +} + +int main(void) +{ + INIT_LIST_HEAD(&c.link); + enable(); + /* An unrelated node. */ + assert(detach(&other) == 0 && !list_empty(&c.link)); + /* Enabled, then a supplier still scanning out detaches: allocation off. */ + assert(apple_mcc_boot_scanout_reserve(&dcp) == 0); + assert(detach(&dcp) == 1 && list_empty(&c.link)); + /* Not registered any more: a second detach reaches nothing. */ + assert(detach(&mcc) == 0); + /* A supplier whose boot scanout retired may detach. */ + enable(); + assert(apple_mcc_boot_scanout_reserve(&dcp) == 0); + apple_mcc_boot_scanout_retired(&dcp); + assert(detach(&dcp) == 0 && !list_empty(&c.link)); + /* A supplier with no scanout record (bound only), and the controller's own node. */ + assert(detach(&disp) == 1); + enable(); + assert(detach(&mcc) == 1); + /* Removal unregisters first. */ + enable(); + apple_mcc_boot_dma_unregister(&c); + assert(detach(&dcp) == 0 && detach(&mcc) == 0); + assert(dcp.refs == 0 && mcc.refs == 0); + return 0; +} +""" + +# A deep sleep with a detach in between, through mcc.c's PM callbacks and the real notifier. +a = SRC.index('struct apple_mcc {') +MSTRUCT = SRC[a:SRC.index('\n};\n', a) + 4] +PMCODE = ''.join(function(n) for n in ('apple_mcc_turn_off', 'apple_mcc_boot_dma_lost', + 'apple_mcc_suspend_locked', 'apple_mcc_resume_locked', + 'apple_mcc_suspend_noirq', 'apple_mcc_resume_noirq')) +CLEAR = '\tmcc->sleep_disabled = false;\n}' +assert PMCODE.count(CLEAR) == 1 +if '--resume-after-detach' in sys.argv: + PMCODE = PMCODE.replace(CLEAR, '}') +MPRE = r""" +#define __iomem +#define MCC_MAX_PLANES 64 +#define MCC_CACHE_WAYS 0x2800 +#define FIELD_GET(m, v) (v) +#define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) +static u32 readl(void *p) { return 0; } +static bool alloc_on; +static bool pm_suspend_via_firmware(void) { return true; } +""" + MSTRUCT + r""" +static void *drvdata; +static void *dev_get_drvdata(struct device *d) { return drvdata; } +static void apple_mcc_quiesce(struct apple_mcc *mcc) +{ + assert(locked); + if (!mcc->enabled || mcc->retained) + return; + alloc_on = false; + mcc->enabled = false; +} +static int apple_mcc_disable_t8132(struct apple_mcc *mcc) { alloc_on = false; return 0; } +static int apple_mcc_enable(struct apple_mcc *mcc) { assert(locked); alloc_on = true; return 0; } +static int apple_mcc_enable_t8132(struct apple_mcc *mcc) { alloc_on = true; return 0; } +static int apple_mcc_set_ways(struct apple_mcc *mcc, u32 ways) { return 0; } +""" +PMAIN = r""" +static struct device_node pmcc = { .phandle = 1, .boot = { 2 }, .nboot = 1 }; +static struct device_node pdcp = { .phandle = 2 }; +static struct device pdev = { .of_node = &pmcc }; +static struct apple_mcc m; + +static void probe(void) +{ + m = (struct apple_mcc){ .dev = &pdev, .enabled = true }; + INIT_LIST_HEAD(&m.boot_dma.link); + m.boot_dma.dev = &pdev; + m.boot_dma.lost = apple_mcc_boot_dma_lost; + drvdata = &m; + alloc_on = true; + apple_mcc_boot_dma_lock(); + apple_mcc_boot_dma_register_locked(&m.boot_dma); + apple_mcc_boot_dma_unlock(); +} + +static void detach(struct device_node *n) +{ + struct of_reconfig_data rd = { .dn = n }; + + n->detached = true; + apple_mcc_of_notify(NULL, OF_RECONFIG_DETACH_NODE, &rd); + n->detached = false; +} + +int main(void) +{ + /* Suspend, a supplier still scanning out detaches, resume: allocation stays off. */ + assert(apple_mcc_boot_scanout_reserve(&pdcp) == 0); + probe(); + assert(apple_mcc_suspend_noirq(&pdev) == 0 && !alloc_on && m.sleep_disabled); + detach(&pdcp); + assert(!m.sleep_disabled && list_empty(&m.boot_dma.link)); + assert(apple_mcc_resume_noirq(&pdev) == 0 && !alloc_on && !m.enabled); + assert(!locked); + + /* The same with a retired supplier (the detach dropped its record): the wake turns allocation back on. */ + assert(apple_mcc_boot_scanout_reserve(&pdcp) == 0); + apple_mcc_boot_scanout_retired(&pdcp); + probe(); + assert(apple_mcc_suspend_noirq(&pdev) == 0 && !alloc_on); + detach(&pdcp); + assert(m.sleep_disabled && !list_empty(&m.boot_dma.link)); + assert(apple_mcc_resume_noirq(&pdev) == 0 && alloc_on && m.enabled); + assert(!locked); + return 0; +} +""" + +with tempfile.TemporaryDirectory() as t: + for name, text in (('mcc', PRE + CODE + MAIN), ('notify', NPRE + HDR + strip(BOOT) + NMAIN), + ('pm', NPRE + HDR + strip(BOOT) + MPRE + PMCODE + PMAIN)): + src = Path(t) / (name + '.c') + src.write_text(text) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-Wno-unused-variable', '-fsanitize=address,undefined', str(src), + '-o', str(src.with_suffix(''))], check=True) + if subprocess.run([str(src.with_suffix(''))]).returncode: + sys.exit(1) +print('PASS boot DMA walk: legacy bound/unbound, empty entry, unresolved phandle, ' + 'disabled scanning DCP, disabled framebuffer, detached consumer/supplier, final detach check, supplier gone between walks; ' + 'enabled then supplier/own node detached, retired supplier, removal; ' + 'suspend-detach-resume stays off, retired supplier resumes') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1af0e3c242fc4f..c3cecff8b36dde 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -62,6 +62,10 @@ def mutations(flag, names, base, expect=KILL): 'display-sleep-merge-tests.py': [(out(), PASS)], 'dcpext26-slot-unregister-tests.py': [(out(), PASS)], 'dcpext26-budget-tests.py': [([], PASS)], + 'mcc-boot-dma-tests.py': [([], PASS), (['--accept-unresolved'], KILL), (['--ignore-detached-supplier'], KILL), + (['--final-skips-unresolved'], KILL), + (['--detach-retired-only'], KILL), + (['--resume-after-detach'], KILL)], 'dcpext26-queue-tests.py': [([], PASS), (['--drop-v27-close'], KILL)], 'dcpext26-retrain-tests.py': [([], PASS), (['--negative-control'], KILL)], 'dcpext26-lifecycle-tests.py': [([], PASS)], From 408f43b0240c4f5ea5f5dfa83c9271fb7a2162ef Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sat, 21 Nov 2026 15:11:58 -0800 Subject: [PATCH 0215/1514] PCI: apple: T6050: train a port at its DT max-link-speed, so a Linux-trained link targets the speed the ADT gives it apple_pcie_t6050_port_configure() writes Target Link Speed 8 GT/s whenever Linux trains a T6050 port itself: the N1's root-port reset, a port the boot loader left down (the J714c's N1, the J714s and K116s SD reader), and the laptops' resume. The boot loader trains its ports at the speed the port's ADT bridge gives, so the two could differ: the SD reader's bridge gives 5 GT/s ("maximum-link-speed" 1, its child's "expected-link-speed" 2), and Linux targeted 8 GT/s. Take the target from the root port node's "max-link-speed", which the boot loader fills in from the ADT (aura: "pcie_t6050: publish each GP port's link speed as max-link-speed"), as the T8140 path already does with of_pci_get_max_link_speed(). Without the property the target stays 8 GT/s, so nothing changes until the tree carries it. A speed above the root port's fastest is lowered to it, as the boot loader lowers its own target, so a hand-written property cannot stop a retrain. What each port gets with both changes: the N1 3 (8 GT/s, as before), the J775D's 10 Gb Ethernet 4, the USB-A controller 3, the SD reader 2 (5 GT/s, where it was 8). The reader's link speed is not expected to change: the GL9755 supports at most 5 GT/s, and on the J775D, with aura#163 bringing the port up, it linked at 5 GT/s x1 under an 8 GT/s target. Tested on the J775D (Mac Studio, M5 Ultra): the N1's root-port reset trains it again at the published 8 GT/s x1. Signed-off-by: Jeff Queisser --- drivers/pci/controller/pcie-apple.c | 37 +++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 05429c43e7b866..1c9e91d76e9395 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -2093,10 +2093,10 @@ static int apple_pcie_adopt_link(struct apple_pcie_port *port) /* * T6050 port bring-up, for an adopted port whose endpoint must come back on a * retrained link: port disable, the port reset table, port enable, root complex - * configuration for Gen3 x1, then the lane PHY, PERST# and the LTSSM. The port's - * registers are its port, phy and intr2axi blocks; the root complex's - * are the root port's config space. The boot loader copies the port's tunables - * onto its node. + * configuration (an x1 link at the port's max-link-speed), then the lane PHY, + * PERST# and the LTSSM. The port's registers are its port, phy and + * intr2axi blocks; the root complex's are the root port's config space. The + * boot loader copies the port's tunables onto its node. */ static const struct apple_pcie_reset_reg apple_pcie_t6050_reset_regs[] = { { 0x088, 0x00000110 }, @@ -2308,7 +2308,12 @@ static int apple_pcie_t6050_port_enable(struct apple_pcie_port *port) 250000); } -/* Root complex tunables and a Gen3 x1 link, with the read-only registers opened for it */ +/* + * Root complex tunables and an x1 link at the port's DT "max-link-speed" (which the + * boot loader fills in from the ADT), 8 GT/s without one, with the read-only + * registers opened for it. A speed above the root port's fastest is lowered to it, + * as the boot loader does. + */ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) { static const char * const shadow[] = { @@ -2319,11 +2324,16 @@ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) static const u32 shadow_sel[] = { 0, BIT(24), 0 }; void __iomem *dbi = apple_pcie_t6050_dbi(port); int cap = apple_pcie_t6050_exp_cap(dbi); + int speed = of_pci_get_max_link_speed(port->np); + int top; + u32 sls; u16 ctl2; int ret, i; if (!cap) return -EIO; + if (speed <= 0) + speed = PCI_EXP_LNKCTL2_TLS_8_0GT; apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_MISC_CONTROL_1, 0, RC_T6050_DBI_RO_WR_EN); ret = apple_pcie_t6050_tune(port, dbi, "apple,pcie-rc-tunables"); for (i = 0; !ret && i < ARRAY_SIZE(shadow); i++) { @@ -2333,13 +2343,19 @@ static int apple_pcie_t6050_port_configure(struct apple_pcie_port *port) } if (!ret) { apple_pcie_t6050_dbi_rmw(dbi, 0x194, 0, BIT(0)); - if (!(readl(dbi + cap + PCI_EXP_LNKCAP2) & PCI_EXP_LNKCAP2_SLS_8_0GB)) + sls = readl(dbi + cap + PCI_EXP_LNKCAP2) & PCI_EXP_LNKCAP2_SLS; + top = sls ? __fls(sls) : 0; + if (top && speed > top) { + dev_info(port->pcie->dev, "port %d: max-link-speed %d above the root port's %d\n", + port->idx, speed, top); + speed = top; + } + if (!top || !(sls & BIT(speed))) ret = -EIO; } if (!ret) { ctl2 = readw(dbi + cap + PCI_EXP_LNKCTL2); - writew((ctl2 & ~PCI_EXP_LNKCTL2_TLS) | PCI_EXP_LNKCTL2_TLS_8_0GT, - dbi + cap + PCI_EXP_LNKCTL2); + writew((ctl2 & ~PCI_EXP_LNKCTL2_TLS) | speed, dbi + cap + PCI_EXP_LNKCTL2); apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_PORT_LINK_CTRL, RC_T6050_LINK_MODE, FIELD_PREP(RC_T6050_LINK_MODE, 1)); apple_pcie_t6050_dbi_rmw(dbi, RC_T6050_LINK_WIDTH_SPEED_CTRL, RC_T6050_LINK_WIDTH, @@ -2765,8 +2781,9 @@ static int apple_pcie_t6050_port_routes(struct apple_pcie_port *port, const u32 * Root-port reset of an adopted T6050 port, for an endpoint that must come back on a * retrained link (the N1 after its ROM boot): PME_Turn_Off to L2, PERST# asserted, the * port disabled, reset, enabled and configured, its routes and MSI map rewritten, then the - * lane PHY, PERST# release and LTSSM to a Gen3 x1 link. The caller has quiesced the - * endpoint and saved the root port's state; the PCI core restores it. + * lane PHY, PERST# release and LTSSM to an x1 link at the port's max-link-speed. The + * caller has quiesced the endpoint and saved the root port's state; the PCI core + * restores it. */ static int apple_pcie_t6050_reset_root_port(struct pci_host_bridge *bridge, struct pci_dev *rp) From 086a909dc8c6439ff59e7efc86c6b4691b12e1b9 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 20 Nov 2026 02:41:41 -0500 Subject: [PATCH 0216/1514] drm/asahi: overlap cross-engine commands with timestamped producers on G17 Allow a G17 queue's render or compute command that writes no timestamps to overlap a cross-engine producer carrying host-written timestamps via firmware dependencies instead of stalling on the producer's host completion fence, while preserving ordered timestamp publication and deferred producer error propagation: - Use ordered host publication (`Publication`) for G17 compute commands as well as renders whenever the command writes timestamps or inherits host predecessors (dropping the `!compute &&` guard in `Completion::new`). Previously compute commands always used `HostOutput::Immediate`; using `Publication` lets overlapping cross-engine consumers chain completion and error propagation behind a timestamped compute producer and lets compute consumers chain behind earlier publications. A compute command with outputs and no predecessors clears its sentinel at activation and still publishes synchronously on finish with no extra delay. - Require host waits whenever a cross-engine consumer writes timestamps or accesses pending queries, and on the same engine for query-accessing compute and timestamp-writing renders behind an active publication chain (so a render's fragment-end window write cannot race with a transitive producer's host write or bypass an inherited error; timestamp-writing NO_QUERY_ACCESS compute chains publication on the same engine). - Chain host publication (`Publication`) across cross-engine and same-engine successors, keeping failed covered publications that survive frontier pruning (`status <= 0`) so a predecessor error arriving between pruning and link collection still propagates. - Extract `EnqueueOrdering::build()` and `HostOutput::new()` so the production ordering and publication selection logic are covered by KUnit tests for shared timestamp slots in both directions, transitive render window writes, post-prune predecessor failure propagation, standalone timestamped compute publishing immediately on finish, and timestamp-free compute chaining ordered publication behind a render. - Document DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS by what the command touches: no timestamp or availability word whose host publication is still pending. A command may copy or reset queries whose words are already published. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/file.rs | 9 +- drivers/gpu/drm/asahi/g17/command.rs | 5 +- drivers/gpu/drm/asahi/g17/completion.rs | 96 ++- .../drm/asahi/g17/completion/publication.rs | 74 +- drivers/gpu/drm/asahi/g17/fence.rs | 9 + drivers/gpu/drm/asahi/g17/job.rs | 17 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 704 +++++++++++++++--- include/uapi/drm/asahi_drm.h | 10 +- 8 files changed, 789 insertions(+), 135 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index cd70a367363b08..43aaf6587b6d81 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -134,10 +134,11 @@ pub(crate) const DRM_ASAHI_RENDER_PROGRAM_TASK: u32 = uapi::DRM_ASAHI_RENDER_PRO #[allow(dead_code)] pub(crate) const DRM_ASAHI_COMPUTE_USES_MATRIX: u32 = uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_USES_MATRIX as u32; -/// The compute command neither copies nor resets queries, so it cannot observe -/// timestamps the host publishes after earlier commands complete -/// (DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). Accepted, and reported with -/// DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS by the G17 command sets. +/// The compute command reads and writes no timestamp or availability word whose +/// host publication is still pending for an earlier command, so it need not wait +/// for that publication (DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). It may copy or reset +/// queries whose words are already published. Accepted, and reported with +/// DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS, by the G17 command sets. pub(crate) const DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: u32 = uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS as u32; diff --git a/drivers/gpu/drm/asahi/g17/command.rs b/drivers/gpu/drm/asahi/g17/command.rs index da60d6b456d7eb..4403306c98d488 100644 --- a/drivers/gpu/drm/asahi/g17/command.rs +++ b/drivers/gpu/drm/asahi/g17/command.rs @@ -473,8 +473,9 @@ pub(crate) enum Validated { long_job: bool, intersection: IntersectionTables, matrix_ops: bool, - /// The command may copy or reset queries, so it must follow the host's - /// timestamp publication for earlier commands. + /// The command may read or write a timestamp or availability word whose + /// host publication for an earlier command is still pending, so it must + /// follow that publication (no DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS). query_access: bool, /// The command's writes are visible when it completes (M5). visible_completion: bool, diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index c255632a55b19c..ab076cbac03eda 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -175,6 +175,15 @@ impl Destinations { self.stamps.iter().any(Option::is_some) } + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn empty() -> Self { + Self { + stamps: core::array::from_fn(|_| None), + render: false, + handed: AtomicBool::new(false), + } + } + fn iter(&self) -> core::slice::Iter<'_, Option> { self.stamps.iter() } @@ -211,25 +220,76 @@ impl Output { } } -enum HostOutput { +enum HostOutputKind { Immediate(Output), Ordered(Arc), } +pub(super) struct HostOutput(HostOutputKind); + impl HostOutput { + /// Both render and compute commands use an ordered [`Publication`] when + /// they write host timestamps or inherit ordered host predecessors: + /// timestamp-writing compute must expose a [`Publication`] so overlapping + /// cross-engine consumers can chain behind it, and compute consumers with + /// host predecessors must chain behind theirs. When `host_predecessors` is + /// false, activation clears the sentinel immediately so `finish()` + /// publishes synchronously with no extra delay. + fn new( + output: Output, + status: Arc, + host_predecessors: bool, + has_outputs: bool, + ) -> Result { + if host_predecessors || has_outputs { + Ok(Self(HostOutputKind::Ordered(Publication::new( + output, status, + )?))) + } else { + Ok(Self(HostOutputKind::Immediate(output))) + } + } + fn output(&self) -> &Output { - match self { - Self::Immediate(output) => output, - Self::Ordered(publication) => publication.output(), + match &self.0 { + HostOutputKind::Immediate(output) => output, + HostOutputKind::Ordered(publication) => publication.output(), } } - fn finish(&self, result: Result<[u64; 4]>) { - match self { - Self::Immediate(output) => output.publish(result), - Self::Ordered(publication) => publication.finish(result), + pub(super) fn publication(&self) -> Option> { + match &self.0 { + HostOutputKind::Ordered(publication) => Some(publication.clone()), + HostOutputKind::Immediate(_) => None, + } + } + + pub(super) fn finish(&self, result: Result<[u64; 4]>) { + match &self.0 { + HostOutputKind::Immediate(output) => output.publish(result), + HostOutputKind::Ordered(publication) => publication.finish(result), } } + + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn test_pair( + contexts: &FenceContexts, + status: &Arc, + host_predecessors: bool, + has_outputs: bool, + ) -> Result<(Self, Fence)> { + let fence = fence::independent(contexts)?; + let handle = Fence::from_fence(&fence); + let output = Output { + fence, + member: fence::Aggregate::test_member(contexts)?, + destinations: Destinations::empty(), + }; + Ok(( + Self::new(output, status.clone(), host_predecessors, has_outputs)?, + handle, + )) + } } /// Firmware writes two aligned words in a write-combined page of its own per @@ -370,7 +430,7 @@ impl M5ComputeTimestamps { pub(crate) struct Completion { status: Arc, output: HostOutput, - // Present only when this command's public result may wait for a render + // Present only when this command's public result may wait for a // predecessor's host writes. DRM credits must follow the terminal result. terminal: Option>, compute: Option, @@ -424,7 +484,7 @@ impl Completion { usage: Arc>>, ) -> Result> { let fence = fence::independent(contexts)?; - let ordered = !compute && (host_predecessors || destinations.iter().any(Option::is_some)); + let has_outputs = destinations.has_outputs(); let terminal = if host_predecessors { Some(fence::independent(contexts)?) } else { @@ -435,11 +495,12 @@ impl Completion { member, destinations, }; - let output = if ordered { - HostOutput::Ordered(Publication::new(output, context.status().clone())?) - } else { - HostOutput::Immediate(output) - }; + let output = HostOutput::new( + output, + context.status().clone(), + host_predecessors, + has_outputs, + )?; // M5 compute binds its timestamp pair in its physical queue's page at publication. let is_compute = compute; let compute = if compute && !context.is_m5() { @@ -485,10 +546,7 @@ impl Completion { .map_or_else(|| self.fence(), |fence| Fence::from_fence(fence)) } pub(crate) fn publication(&self) -> Option> { - match &self.output { - HostOutput::Ordered(publication) => Some(publication.clone()), - HostOutput::Immediate(_) => None, - } + self.output.publication() } fn signal_terminal(&self, result: Result<[u64; 4]>) { if let Some(fence) = &self.terminal { diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 8e16a14f054886..161a051dc9540a 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -2,7 +2,7 @@ //! Host-only ordering of timestamp writes, independent of scheduler credits. //! -//! Links point from earlier logical render ordinals to later ones. They retain +//! Links point from earlier logical ordinals to later ones. They retain //! only public output state, never a packet, physical render lease or VM job pin. //! All link storage is allocated before acceptance. Completion neither allocates //! nor waits for another command; the last prerequisite publishes a ready result. @@ -78,7 +78,7 @@ impl Publication { } /// One terminal result, offered separately from its physical-retirement proof. - pub(super) fn finish(&self, result: Result<[u64; 4]>) { + pub(crate) fn finish(&self, result: Result<[u64; 4]>) { let ready = { let mut state = self.state.lock(); if state.claimed || state.result.is_some() { @@ -207,3 +207,73 @@ impl Prepared { Publication::drain(self.target.predecessor_done(Ok(()))); } } + +#[cfg(CONFIG_KUNIT = "y")] +impl Publication { + pub(crate) fn test_pair( + contexts: &kernel::dma_fence::FenceContexts, + status: &Arc, + ) -> Result<(Arc, kernel::dma_fence::Fence)> { + let fence = crate::g17::fence::independent(contexts)?; + let handle = kernel::dma_fence::Fence::from_fence(&fence); + let output = Output { + fence, + member: crate::g17::fence::Aggregate::test_member(contexts)?, + destinations: super::Destinations::empty(), + }; + Ok((Self::new(output, status.clone())?, handle)) + } +} + +#[kunit_tests(asahi_g17_publication_order)] +mod tests { + use super::*; + use crate::g17::{ + completion::Destinations, + fence::{independent, Aggregate}, + job::fence_status, + }; + use kernel::{c_str, dma_fence::{Fence, FenceContexts}, sync::LockClassKey}; + + static KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); + + fn make_pub( + contexts: &FenceContexts, + status: &Arc, + ) -> (Arc, Fence) { + let fence = independent(contexts).unwrap(); + let handle = Fence::from_fence(&fence); + let output = Output { + fence, + member: Aggregate::test_member(contexts).unwrap(), + destinations: Destinations::empty(), + }; + (Publication::new(output, status.clone()).unwrap(), handle) + } + + #[test] + fn consumer_retiring_before_delayed_producer_failure_inherits_error() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, prod_fence) = make_pub(&contexts, &status); + let (consumer, cons_fence) = make_pub(&contexts, &status); + let (downstream, down_fence) = make_pub(&contexts, &status); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(downstream.clone(), core::iter::once(&consumer)).unwrap().activate(); + + // Consumer and its transitive successor retire before the producer's + // deferred failure runs: neither may signal success early. + consumer.finish(Ok([1, 2, 0, 0])); + downstream.finish(Ok([3, 4, 0, 0])); + assert_eq!(fence_status(&prod_fence), 0); + assert_eq!(fence_status(&cons_fence), 0); + assert_eq!(fence_status(&down_fence), 0); + + producer.finish(Err(EIO)); + assert_eq!(fence_status(&prod_fence), EIO.to_errno()); + assert_eq!(fence_status(&cons_fence), PRODUCER_FAILED.to_errno()); + assert_eq!(fence_status(&down_fence), PRODUCER_FAILED.to_errno()); + } +} diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index df98a3410a50de..5184dc44047aac 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -314,6 +314,15 @@ impl Aggregate { self.source().member_done(&self.0, result); self.source().owner_done(); } + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn test_member(contexts: &FenceContexts) -> Result { + let mut fence = export_fallback(contexts)?; + fence.source = Some(Submission::with_work(None, false)?); + let aggregate = Self(fence.into()); + let member = aggregate.member(); + aggregate.finish_enqueue(Ok(())); + Ok(member) + } } pub(crate) struct Member { diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index f5ddc1419361a8..09892c8d17f04f 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -519,6 +519,7 @@ pub(crate) struct Scheduler { #[derive(Clone)] pub(crate) struct Fences { pub(crate) ready: Fence, + pub(crate) scheduled: Fence, pub(crate) completed: Fence, pub(crate) publication: Option>, pub(crate) owner: Arc, @@ -589,14 +590,9 @@ impl Scheduler { super::trace::schedule(&packet, 0, dependency_count as i32); let completed = packet.completion.fence(); let host_timestamps = packet.completion.has_timestamps(); - // Only commands which actually write timestamps become host-prefix - // producers. Ordinary consumers retain the scheduled ready fence and - // their existing firmware dependency path for cross-engine overlap. - let host_publication = if host_timestamps { - packet.completion.publication() - } else { - None - }; + // Expose any ordered publication so later commands that overlap execution + // with this command still order their completion and error propagation. + let host_publication = packet.completion.publication(); if self.allowance_ms > super::timeout::DEFAULT_ALLOWANCE_MS { packet.allowance_end.store(u64::MAX, Ordering::Relaxed); } @@ -620,10 +616,11 @@ impl Scheduler { if let Some(publication) = publication { publication.activate(); } + let scheduled = job.fences().scheduled(); let ready = if host_timestamps { completed.clone() } else { - job.fences().scheduled() + scheduled.clone() }; // All fallible scheduler setup precedes early hardware publication. The // scheduler still owns watchdog, credits and cancellation after push. @@ -644,6 +641,6 @@ impl Scheduler { self.backend.count_backlog(&packet); } job.push(); - Ok(Fences { ready, completed, publication: host_publication, owner: packet.completion.clone() }) + Ok(Fences { ready, scheduled, completed, publication: host_publication, owner: packet.completion.clone() }) } } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e3..008dc7839f8d7c 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -8,7 +8,7 @@ pub(crate) mod render; use super::{ command::{Parser, UscWindow, Validated}, - completion::{Completion, Destinations, PreparedPublication}, + completion::{Completion, Destinations, PreparedPublication, Publication}, context::Context, dependency::FailureRecord, fence::Outputs, @@ -199,6 +199,16 @@ impl Queue { }); } + fn has_pending_publication(&self, order: &Order) -> bool { + self.frontiers.iter().enumerate().any(|(index, frontier)| { + frontier.iter().any(|(sequence, fences)| { + Order::contains(order.wait_through[index], *sequence) + && fences.publication.is_some() + && fences.status() <= 0 + }) + }) + } + #[expect( clippy::too_many_arguments, reason = "Enqueue keeps validated command, ordering, and destination owners explicit." @@ -218,6 +228,7 @@ impl Queue { Validated::Compute { .. } => Engine::Compute, }; let index = engine.index(); + let other = 1 - index; if let Validated::Render { ray_query, .. } = &command { let blocks = self .backend @@ -227,6 +238,7 @@ impl Queue { } } self.prune_frontier(index); + self.prune_frontier(other); self.frontiers[index].reserve(1, GFP_KERNEL)?; if engine == Engine::Compute { self.ensure_compute(&command)?; @@ -239,16 +251,21 @@ impl Queue { // Ring order completes a converted input only if a kick waits for its // ring predecessor; without that, keep the input's completion wait. let host_waits = self.backend.host_producer_waits(); + let has_outputs = destinations.has_outputs(); + let query_access = match &command { + Validated::Compute { query_access, .. } => *query_access, + Validated::Render { .. } => true, + }; let sources = if !host_waits && engine == Engine::Compute && !inputs.is_empty() - && !destinations.has_outputs() + && !has_outputs && self.frontiers[0].iter().all(|(sequence, fences)| { !Order::contains(order.wait_through[0], *sequence) || fences.status() > 0 }) && self.frontiers[1].iter().all(|(sequence, fences)| { !Order::contains(order.wait_through[1], *sequence) - || fences.ready.raw() != fences.completed.raw() + || (fences.ready.raw() != fences.completed.raw() && fences.publication.is_none()) || fences.status() > 0 }) && self.failures.iter_mut().enumerate().all(|(index, failure)| { @@ -270,65 +287,40 @@ impl Queue { ); } - // Only earlier render ordinals covered by the explicit logical prefix - // can delay host publication. These links never become GPU dependencies. - let host_predecessors = self.frontiers[index] - .iter() - .take_while(|(sequence, _)| { - engine == Engine::Render && Order::contains(order.wait_through[index], *sequence) - }) - .filter_map(|(_, fences)| fences.publication.as_ref()); - let completion = Completion::new( - &self.dev, - &self.fences, - &self.context, - aggregate.member(), - guard, - destinations, - engine == Engine::Compute, - host_predecessors.clone().next().is_some(), - self.backend.feed(), - sources.clone(), - self.usage.clone(), - )?; - let publication = completion - .publication() - .map(|target| PreparedPublication::new(target, host_predecessors)) - .transpose()?; - if engine == Engine::Compute { - self.prune_frontier(Engine::Render.index()); - } - let other = 1 - index; - let prefix = order.wait_through[other]; - let frontier = if prefix.is_some() { - let frontier = self.frontiers[other].as_slice(); - // Accepted sequences increase from one, and retain preserves their - // order, so all members of a logical prefix form one slice. - let end = frontier.partition_point(|(sequence, _)| Order::contains(prefix, *sequence)); - &frontier[..end] - } else { - &[] - }; - let count = frontier.len(); - // Only a command that copies or resets queries can observe timestamps the - // host has not yet published for its predecessors. - let query_access = match &command { - Validated::Compute { query_access, .. } => *query_access, - Validated::Render { .. } => true, - }; - let timestamp_prefix = order.wait_through[index]; - let timestamps = if engine == Engine::Compute && query_access && timestamp_prefix.is_some() { - let frontier = self.frontiers[index].as_slice(); - let end = frontier - .partition_point(|(sequence, _)| Order::contains(timestamp_prefix, *sequence)); - &frontier[..end] - } else { - &[] + let (completion, publication, ordering_host_waits, ordering_firmware_waits) = { + let ordering = EnqueueOrdering::build( + &self.frontiers[index], + &self.frontiers[other], + order, + engine, + host_waits, + has_outputs, + query_access, + )?; + let completion = Completion::new( + &self.dev, + &self.fences, + &self.context, + aggregate.member(), + guard, + destinations, + engine == Engine::Compute, + !ordering.predecessors.is_empty(), + self.backend.feed(), + sources.clone(), + self.usage.clone(), + )?; + let publication = completion + .publication() + .map(|target| PreparedPublication::new(target, ordering.predecessors.iter().copied())) + .transpose()?; + ( + completion, + publication, + ordering.host_waits, + ordering.firmware_waits, + ) }; - let timestamp_count = timestamps - .iter() - .filter(|(_, fences)| fences.ready.raw() == fences.completed.raw()) - .count(); let mut failures: [Option; 2] = [None, None]; for (index, failure) in self.failures.iter_mut().enumerate() { failures[index] = failure.earliest().and_then(|(sequence, fences)| { @@ -337,49 +329,29 @@ impl Queue { } let failure_count = failures.iter().flatten().count(); let mut dependencies = KVec::with_capacity( - inputs.len() + count + timestamp_count + failure_count, + inputs.len() + + ordering_host_waits.len() + + ordering_firmware_waits.len() + + failure_count, GFP_KERNEL, )?; // Host-waited producers are checked on the host instead of in firmware. - let (host_count, firmware_count) = if host_waits { - (count, 0) - } else { - (0, count) - }; let mut checked_inputs = KVec::with_capacity( - inputs.len() + host_count + timestamp_count + failure_count, + inputs.len() + ordering_host_waits.len() + failure_count, GFP_KERNEL, )?; - let mut firmware = KVec::with_capacity(firmware_count, GFP_KERNEL)?; + let mut firmware = KVec::with_capacity(ordering_firmware_waits.len(), GFP_KERNEL)?; for fence in failures.into_iter().flatten() { checked_inputs.push(fence.clone(), GFP_KERNEL)?; dependencies.push(fence.clone(), GFP_KERNEL)?; } - // Same-engine parents order GPU execution, not the host's timestamp - // writes. Only timestamp publishers need these completion waits and - // status checks; ordinary compute keeps its existing queue ordering. - for (_, fences) in timestamps { - if fences.ready.raw() == fences.completed.raw() { - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; - } + for fence in ordering_host_waits { + dependencies.push(fence.clone(), GFP_KERNEL)?; + checked_inputs.push(fence, GFP_KERNEL)?; } - for (_, fences) in frontier { - // Successful completion includes host timestamp publication. Its - // ready fence adds no ordering and would prevent shallow inline - // publication. Failed and pending producers still need checking. - if fences.status() > 0 { - continue; - } - if host_waits { - // Keep other-engine producers on the host until completion, and - // propagate their errors before publishing the consumer. - dependencies.push(fences.completed.clone(), GFP_KERNEL)?; - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; - } else { - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; - firmware.push(fences.completed.clone(), GFP_KERNEL)?; - } + for (scheduled, completed) in ordering_firmware_waits { + dependencies.push(scheduled, GFP_KERNEL)?; + firmware.push(completed, GFP_KERNEL)?; } // Each command owns every input fence; independent engines may publish in // either order and must each consume an input's error status before running. @@ -603,7 +575,8 @@ impl crate::queue::Queue for Queue { let firmware_source = pending.len() == 1 && matches!(&pending[0].0, Validated::Compute { visible_completion, .. } if *visible_completion || !visible_required) - && !pending[0].2.has_outputs(); + && !pending[0].2.has_outputs() + && !self.has_pending_publication(&pending[0].1); let aggregate = outputs.publish(self.context.clone(), firmware_source)?; let output_fence = aggregate.fence(); super::trace::submit( @@ -658,3 +631,546 @@ impl Drop for Queue { self.backend.release_owner(); } } + +/// Whether a cross-engine consumer must wait on the host for a covered +/// producer's completion fence before scheduling. +const fn cross_engine_wait_completed( + host_waits: bool, + has_outputs: bool, + engine: Engine, + query_access: bool, + has_publication: bool, +) -> bool { + if host_waits { + return true; + } + if !has_publication { + return false; + } + has_outputs || (matches!(engine, Engine::Compute) && query_access) +} + +/// Whether a cross-engine consumer overlaps execution with a producer that has +/// ordered host publication and therefore chains its completion behind it. +const fn cross_engine_chain_publication( + host_waits: bool, + has_outputs: bool, + engine: Engine, + query_access: bool, +) -> bool { + !host_waits && !has_outputs && !(matches!(engine, Engine::Compute) && query_access) +} + +/// Whether a same-engine consumer must wait on the host for covered same-engine +/// predecessors that have ordered host publication: query-accessing compute may +/// read or write, on the GPU, query words whose host publication is still +/// pending, and timestamp-writing renders can write their fragment-end +/// timestamp window on the GPU before a transitive cross-engine producer +/// finishes its deferred host write or error publication. +const fn same_engine_wait_completed( + engine: Engine, + has_outputs: bool, + query_access: bool, +) -> bool { + (matches!(engine, Engine::Compute) && query_access) + || (matches!(engine, Engine::Render) && has_outputs) +} + +trait FrontierEntry { + fn status(&self) -> i32; + fn ready_is_completed(&self) -> bool; + fn publication(&self) -> Option<&Arc>; + fn completed(&self) -> &Fence; + fn scheduled(&self) -> &Fence; +} + +impl FrontierEntry for Fences { + fn status(&self) -> i32 { + self.status() + } + + fn ready_is_completed(&self) -> bool { + self.ready.raw() == self.completed.raw() + } + + fn publication(&self) -> Option<&Arc> { + self.publication.as_ref() + } + + fn completed(&self) -> &Fence { + &self.completed + } + + fn scheduled(&self) -> &Fence { + &self.scheduled + } +} + +struct EnqueueOrdering<'a> { + predecessors: KVec<&'a Arc>, + host_waits: KVec, + firmware_waits: KVec<(Fence, Fence)>, +} + +impl<'a> EnqueueOrdering<'a> { + fn build( + same_frontier: &'a [(u64, E)], + other_frontier: &'a [(u64, E)], + order: Order, + engine: Engine, + host_waits: bool, + has_outputs: bool, + query_access: bool, + ) -> Result { + let index = engine.index(); + let other = 1 - index; + + let same_prefix = order.wait_through[index]; + let same_covered = if same_prefix.is_some() { + let end = + same_frontier.partition_point(|(sequence, _)| Order::contains(same_prefix, *sequence)); + &same_frontier[..end] + } else { + &[] + }; + + let other_prefix = order.wait_through[other]; + let other_covered = if other_prefix.is_some() { + let end = other_frontier + .partition_point(|(sequence, _)| Order::contains(other_prefix, *sequence)); + &other_frontier[..end] + } else { + &[] + }; + + let same_wait = same_engine_wait_completed(engine, has_outputs, query_access); + let same_chain = !same_wait; + let cross_chain = + cross_engine_chain_publication(host_waits, has_outputs, engine, query_access); + + // Retain covered failed publications (`status() <= 0`, not only `== 0`) + // that survived `prune_frontier()`: if a predecessor's deferred error + // published between pruning and link selection, `add_successor()` still + // delivers that failure immediately instead of letting the successor + // signal success. + let mut predecessors = KVec::new(); + if same_chain { + for (_, entry) in same_covered { + if entry.status() <= 0 { + if let Some(publication) = entry.publication() { + predecessors.push(publication, GFP_KERNEL)?; + } + } + } + } + if cross_chain { + for (_, entry) in other_covered { + if entry.status() <= 0 { + if let Some(publication) = entry.publication() { + predecessors.push(publication, GFP_KERNEL)?; + } + } + } + } + + let mut host = KVec::new(); + let mut firmware = KVec::new(); + if same_wait { + for (_, entry) in same_covered { + if entry.status() <= 0 + && (entry.ready_is_completed() || entry.publication().is_some()) + { + host.push(entry.completed().clone(), GFP_KERNEL)?; + } + } + } + + for (_, entry) in other_covered { + // Successful completion includes host timestamp publication. Its + // ready fence adds no ordering and would prevent shallow inline + // publication. Failed and pending producers still need checking. + if entry.status() > 0 { + continue; + } + if cross_engine_wait_completed( + host_waits, + has_outputs, + engine, + query_access, + entry.publication().is_some(), + ) { + host.push(entry.completed().clone(), GFP_KERNEL)?; + } else { + firmware.push( + (entry.scheduled().clone(), entry.completed().clone()), + GFP_KERNEL, + )?; + } + } + + Ok(Self { + predecessors, + host_waits: host, + firmware_waits: firmware, + }) + } +} + +#[kunit_tests(asahi_g17_cross_engine_timestamps)] +mod tests { + use super::*; + use crate::g17::{fence::independent, job::fence_status, status::VmStatus}; + + static TEST_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); + + struct TestEntry { + ready: Fence, + scheduled: Fence, + completed: Fence, + publication: Option>, + } + + impl FrontierEntry for TestEntry { + fn status(&self) -> i32 { + fence_status(&self.completed) + } + + fn ready_is_completed(&self) -> bool { + self.ready.raw() == self.completed.raw() + } + + fn publication(&self) -> Option<&Arc> { + self.publication.as_ref() + } + + fn completed(&self) -> &Fence { + &self.completed + } + + fn scheduled(&self) -> &Fence { + &self.scheduled + } + } + + fn test_entry( + contexts: &FenceContexts, + status: &Arc, + with_pub: bool, + ) -> (TestEntry, Option>) { + let ready = Fence::from_fence(&independent(contexts).unwrap()); + let scheduled = Fence::from_fence(&independent(contexts).unwrap()); + if with_pub { + let (publication, completed) = Publication::test_pair(contexts, status).unwrap(); + ( + TestEntry { + ready, + scheduled, + completed, + publication: Some(publication.clone()), + }, + Some(publication), + ) + } else { + let completed = Fence::from_fence(&independent(contexts).unwrap()); + ( + TestEntry { + ready, + scheduled, + completed, + publication: None, + }, + None, + ) + } + } + + #[test] + fn transitive_render_window_waits_for_intermediate_completion() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_ts_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + // Compute A writes a timestamp (has ordered host publication). + let (comp_a, pub_a) = test_entry(&contexts, &status, true); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let compute_frontier = [(1u64, comp_a)]; + + // Render B has no timestamps and covers Compute A: overlaps A via + // firmware wait and chains its publication behind A. + let order_b = Order { + sequence: 1, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }; + let plan_b = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &compute_frontier, + order_b, + Engine::Render, + false, + false, + true, + ) + .unwrap(); + assert!(plan_b.host_waits.is_empty()); + assert_eq!(plan_b.firmware_waits.len(), 1); + assert_eq!(plan_b.predecessors.len(), 1); + + let (rend_b, pub_b) = test_entry(&contexts, &status, true); + let pub_b = pub_b.unwrap(); + let rend_b_completed = rend_b.completed.raw(); + PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter().copied()) + .unwrap() + .activate(); + let render_frontier = [(1u64, rend_b)]; + + // Render C writes a timestamp (may use fragment-end window) and covers + // only Render B: must host-wait on B's completion fence so C cannot + // write the slot or bypass A's error before A publishes through B. + let order_c = Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }; + let plan_c = EnqueueOrdering::build( + &render_frontier, + &compute_frontier, + order_c, + Engine::Render, + false, + true, + true, + ) + .unwrap(); + assert_eq!(plan_c.host_waits.len(), 1); + assert_eq!(plan_c.host_waits[0].raw(), rend_b_completed); + assert!(plan_c.firmware_waits.is_empty()); + assert!(plan_c.predecessors.is_empty()); + + pub_a.finish(Ok([1, 2, 0, 0])); + pub_b.finish(Ok([3, 4, 0, 0])); + } + + #[test] + fn predecessor_failing_after_prune_propagates_to_same_engine_successor() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_fail_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (comp_a, pub_a) = test_entry(&contexts, &status, true); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (rend_b, pub_b) = test_entry(&contexts, &status, true); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // Render B retires cleanly in hardware while waiting on Compute A, so + // prune_frontier() sees B pending (`status() == 0`). + pub_b.finish(Ok([1, 2, 0, 0])); + assert_eq!(rend_b.status(), 0); + + // Compute A's deferred error publishes B's PRODUCER_FAILED after + // prune_frontier() and before Render C selects its predecessors. + pub_a.finish(Err(EIO)); + assert!(rend_b.status() < 0); + + let render_frontier = [(1u64, rend_b)]; + let compute_frontier = [(1u64, comp_a)]; + let order_c = Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }; + let plan_c = EnqueueOrdering::build( + &render_frontier, + &compute_frontier, + order_c, + Engine::Render, + false, + false, + true, + ) + .unwrap(); + assert_eq!(plan_c.predecessors.len(), 1); + + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status).unwrap(); + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + .unwrap() + .activate(); + pub_c.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&fence_c) < 0); + } + + #[test] + fn shared_timestamp_slot_keeps_host_wait_in_both_directions() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_dir_test"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_ra) = test_entry(&contexts, &status, true); + let pub_ra = pub_ra.unwrap(); + PreparedPublication::new(pub_ra.clone(), core::iter::empty()) + .unwrap() + .activate(); + let rend_a_completed = rend_a.completed.raw(); + let render_frontier = [(1u64, rend_a)]; + + // Render(ts) -> NO_QUERY_ACCESS Compute writing timestamps. + let plan_rc = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + false, + ) + .unwrap(); + assert_eq!(plan_rc.host_waits.len(), 1); + assert_eq!(plan_rc.host_waits[0].raw(), rend_a_completed); + assert!(plan_rc.firmware_waits.is_empty()); + + let (comp_a, pub_ca) = test_entry(&contexts, &status, true); + let pub_ca = pub_ca.unwrap(); + PreparedPublication::new(pub_ca.clone(), core::iter::empty()) + .unwrap() + .activate(); + let comp_a_completed = comp_a.completed.raw(); + let compute_frontier = [(1u64, comp_a)]; + + // Compute(ts) -> Render writing timestamps (including fragment-end window). + let plan_cr = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &compute_frontier, + Order { + sequence: 1, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + true, + ) + .unwrap(); + assert_eq!(plan_cr.host_waits.len(), 1); + assert_eq!(plan_cr.host_waits[0].raw(), comp_a_completed); + assert!(plan_cr.firmware_waits.is_empty()); + + pub_ra.finish(Ok([1, 2, 0, 0])); + pub_ca.finish(Ok([3, 4, 0, 0])); + } + + #[test] + fn compute_with_outputs_and_no_predecessors_publishes_on_finish() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_pub"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let plan = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &[], + Order { + sequence: 1, + wait_through: [None, None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + false, + ) + .unwrap(); + assert!(plan.predecessors.is_empty()); + assert!(plan.host_waits.is_empty()); + assert!(plan.firmware_waits.is_empty()); + + let (host_output, completed) = crate::g17::completion::HostOutput::test_pair( + &contexts, + &status, + !plan.predecessors.is_empty(), + true, + ) + .unwrap(); + let publication = host_output + .publication() + .expect("compute with outputs uses ordered publication"); + PreparedPublication::new(publication, plan.predecessors.iter().copied()) + .unwrap() + .activate(); + + // Activation clears the sentinel with no predecessors, but does not + // signal until the command finishes. + assert_eq!(fence_status(&completed), 0); + + // Finishing publishes synchronously with no extra delay. + host_output.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&completed) > 0); + } + + #[test] + fn no_query_access_compute_behind_render_chains_ordered_publication() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_chain"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, true); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let rend_a_scheduled = rend_a.scheduled.raw(); + let rend_a_completed = rend_a.completed.raw(); + let render_frontier = [(1u64, rend_a)]; + + // NO_QUERY_ACCESS compute with no timestamp outputs behind Render A: + // waits in firmware on A's scheduled fence and chains ordered publication. + let plan_b = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + false, + false, + ) + .unwrap(); + assert!(plan_b.host_waits.is_empty()); + assert_eq!(plan_b.firmware_waits.len(), 1); + assert_eq!(plan_b.firmware_waits[0].0.raw(), rend_a_scheduled); + assert_eq!(plan_b.firmware_waits[0].1.raw(), rend_a_completed); + assert_eq!(plan_b.predecessors.len(), 1); + + let (host_output_b, comp_b_completed) = crate::g17::completion::HostOutput::test_pair( + &contexts, + &status, + !plan_b.predecessors.is_empty(), + false, + ) + .unwrap(); + let pub_b = host_output_b + .publication() + .expect("compute consumer behind publication uses ordered publication"); + PreparedPublication::new(pub_b, plan_b.predecessors.iter().copied()) + .unwrap() + .activate(); + + // Compute B finishes first, but its completion stays pending until Render A publishes. + host_output_b.finish(Ok([3, 4, 0, 0])); + assert_eq!(fence_status(&comp_b_completed), 0); + + pub_a.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&comp_b_completed) > 0); + } +} diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 75301a90c564c0..a1fc22a7959992 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -2255,10 +2255,12 @@ enum drm_asahi_compute_flags { DRM_ASAHI_COMPUTE_USES_MATRIX = (1L << 16), /** - * @DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: The command neither copies nor - * resets queries, so it cannot observe timestamps the kernel publishes - * for earlier commands and need not wait for that publication. Requires - * DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS. + * @DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: The command reads and writes no + * timestamp or availability word whose host publication by the kernel + * is still pending for an earlier command, so it need not wait for that + * publication. The command may copy or reset queries whose words are + * all already published, or were never bound for host timestamps. + * Requires DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS. */ DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS = (1L << 17), From 2244998f3fc6a6cc3e14cf22aea78778084ba63f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 09:15:23 +1100 Subject: [PATCH 0217/1514] 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 3b74ce8736f4a7..864a1e9bc3f654 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 fa6239d6f8a7ac..b82324d7647fef 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 82ad98630f629d4a98edec8fae99c16869309ee3 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 11:23:57 +0700 Subject: [PATCH 0218/1514] dt-bindings: media: apple,scaler-v23: Allow the T8142 scaler to be enabled The binding keeps every firmware-fronted scaler disabled until its firmware handoff, clocks, power and reset ownership are qualified. On the M5 (T8142) they are: the driver starts the firmware core from the image iBoot pre-loads, with the two power domains, and runs jobs on the MacBook Air 15" M5. Keep the T6050 and T8152 instances disabled. Signed-off-by: Nick --- .../bindings/media/apple,scaler-v23.yaml | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml b/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml index ac3fa521557d51..fdb507eddfba34 100644 --- a/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml +++ b/Documentation/devicetree/bindings/media/apple,scaler-v23.yaml @@ -20,7 +20,9 @@ description: | resources. Each instance has its own DART; an advertised MSRn-DART gate belongs to that DART, rather than the scaler functional domains. Keep the device disabled until its firmware handoff, clocks, - power and reset ownership have been qualified. + power and reset ownership have been qualified. They have been on + T8142, whose firmware core the OS starts from the image the boot + loader pre-loads. properties: compatible: @@ -59,15 +61,11 @@ properties: resets: maxItems: 1 - status: - const: disabled - required: - compatible - reg - interrupts - iommus - - status allOf: - if: @@ -108,4 +106,18 @@ allOf: - power-domains - resets + - if: + properties: + compatible: + contains: + enum: + - apple,t6050-scaler + - apple,t8152-scaler + then: + properties: + status: + const: disabled + required: + - status + additionalProperties: false From ab6115c5c0461fb544b4187ba5c448b6b90dbcab Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 15:23:07 +1100 Subject: [PATCH 0219/1514] iommu/apple-dart: take the firmware table handoff only on a v2.2 DART apple_dart_fw_handoff_enabled() admitted any locked DART with the APPLE_DART2 PTE layout. That includes the T6000 DARTs (M1 Pro/Max display and DCP DARTs), which never set dart->version. The paths that keep a handed-off table away from firmware-owned slots (retire, the per-slot invalidate and the locked map/unmap) all require version 0x0202 or later, so on such a DART a loader that set apple,firmware-root-handoff = <1> would get a whole-SID TLB flush under the running DCP on the first unmap. Require dart->version >= 0x0202 as well. Only the T8110 family reports a version, so this keeps T6000 and pre-2.2 DARTs on the existing no-handoff path. The host fixture gains two refusing cases: a DART with no version, and one at 2.1. Both fail on the previous predicate and pass with this one; all 88 cases pass. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 7 +++++-- tools/asahi/apple-dart-fw-tests.py | 2 +- tools/asahi/apple-dart-fw/fixture.c | 4 ++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 71412d018389e5..63d0592c5b789b 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -1037,8 +1037,10 @@ static phys_addr_t apple_dart_pte_to_paddr(const struct apple_dart *dart, /* * Firmware table pages must remain outside Linux's page allocator. The boot * loader says it reserved them with apple,firmware-root-handoff; the walker - * decodes them in the APPLE_DART2 PTE layout, so that is the only other - * condition. + * decodes them in the APPLE_DART2 PTE layout, and the handoff paths (retire, + * per-slot invalidate, locked map/unmap) need a DART whose probed version is + * at least 2.2. Only the T8110 family reports a version, so a T6000 DART, + * which shares the APPLE_DART2 layout, never takes the handoff. */ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) { @@ -1046,6 +1048,7 @@ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) u32 handoff; return dart->locked && dart->hw->fmt == APPLE_DART2 && + dart->version >= 0x0202 && of_property_count_u32_elems(np, "apple,firmware-root-handoff") == 1 && !of_property_read_u32(np, "apple,firmware-root-handoff", &handoff) && handoff == 1; diff --git a/tools/asahi/apple-dart-fw-tests.py b/tools/asahi/apple-dart-fw-tests.py index 281b11f9b47926..aaa5247fee7673 100644 --- a/tools/asahi/apple-dart-fw-tests.py +++ b/tools/asahi/apple-dart-fw-tests.py @@ -5,7 +5,7 @@ import argparse, hashlib, json, re, subprocess ROOT=Path(__file__).resolve().parents[2] NAMES=('apple_dart_fw_handoff_enabled','apple_dart_pte_to_paddr','apple_dart_fw_table_page','apple_dart_fw_table_ram','apple_dart_fw_table_pte','apple_dart_fw_table_decode','apple_dart_fw_tree_table','apple_dart_fw_slot_owned','apple_dart_fw_leaf_decode','apple_dart_fw_mapping_matches','apple_dart_fw_page_matches','apple_dart_fw_slot_mirrors','apple_dart_publish_root','apple_dart_retire_root','apple_dart_free_fw_root','apple_dart_snapshot_fw_root','apple_dart_free_fw_tree','apple_dart_fw_tree_phys','apple_dart_fw_slot_foreign','apple_dart_domain_uses_fw','apple_dart_check_fw_map','apple_dart_inherited_phys_prot','apple_dart_inherited_phys','apple_dart_fw_slot_range','apple_dart_get_fw_resv_regions','apple_dart_fw_invalidate','apple_dart_hw_unmap_locked_ttbr','apple_dart_retire_error','apple_dart_t8110_hw_invalidate_tlb','apple_dart_release_device','apple_dart_domain_free') -CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') +CASES=("legacy-map-match","legacy-map-mismatch","legacy-lookup","legacy-snapshot",'mirror','changed-leaf','wrong-permission','wrong-physical','malformed-leaf','vacant','changed-owner','retire','reserved-ram','unreserved','mmio','misalignment','address-width','root-encoding','leaf-as-table','snapshot','snapshot-malformed','snapshot-unreserved','snapshot-root-change','snapshot-map-failure','snapshot-allocation-failure','range-three','range-offset','range-width','range-overflow','range-underflow','range-four','range-four-last','map-firmware','map-hole','map-host','map-owned','map-unmatched','map-attached','map-wrong-physical','map-wrong-permission','map-changed-root','map-four','lookup-inherited','lookup-changed-leaf','lookup-changed-root','lookup-unmatched','reserve-firmware','reserve-teardown','reserve-unmatched','reserve-owned','invalidate-three','invalidate-four','invalidate-changed-root','invalidate-error','core-inherited','core-hole','core-changed-leaf','core-second-dart','snapshot-unmatched','snapshot-four','range-four-width','range-three-last','handoff-matched','handoff-missing','handoff-duplicate','handoff-zero','handoff-unlocked','handoff-dart1-format','handoff-unversioned','handoff-version-0201','retire-free','retire-free-timeout','retire-release','retire-release-timeout','retire-rollback-timeout','retire-repeat-timeout','tree-lookup','tree-changed-root','tree-changed-mid','tree-unrecorded','tree-reserve','tree-mirror-only','subtree-free-partial','subtree-table-reserved','subtree-table-unclaimed','subtree-table-claimed','subtree-table-ram','subtree-table-misalignment') def function(s,name): match=re.search(r'^static[^;{}]*\b'+re.escape(name)+r'\([^;{}]*\)\s*\{',s,re.M) if not match:return None diff --git a/tools/asahi/apple-dart-fw/fixture.c b/tools/asahi/apple-dart-fw/fixture.c index d566daa80bc16e..ccab85f7fab1d0 100644 --- a/tools/asahi/apple-dart-fw/fixture.c +++ b/tools/asahi/apple-dart-fw/fixture.c @@ -203,11 +203,15 @@ int main(int argc,char**argv){ }else abort(); } else if(!strncmp(c,"handoff-",8)){ + d.version=0x0202; if(!strcmp(c,"handoff-missing"))node.count=-EINVAL; if(!strcmp(c,"handoff-duplicate"))node.count=2; if(!strcmp(c,"handoff-zero"))node.value=0; if(!strcmp(c,"handoff-unlocked"))d.locked=0; if(!strcmp(c,"handoff-dart1-format"))hw.fmt=APPLE_DART; + /* A T6000 DART has the APPLE_DART2 layout but reports no version. */ + if(!strcmp(c,"handoff-unversioned"))d.version=0; + if(!strcmp(c,"handoff-version-0201"))d.version=0x0201; assert(apple_dart_fw_handoff_enabled(&d)==!strcmp(c,"handoff-matched")); } else if(!strncmp(c,"core-",5)){ From fbfeb1193f4a4068aa078d85e26326911025cc3b Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sat, 21 Nov 2026 19:23:47 -0800 Subject: [PATCH 0220/1514] soc: apple: aop: one child device per service, however often it is announced Each service announcement whose name is one of the seven services this driver knows queues a work item that registers a platform device with PLATFORM_DEVID_AUTO and adds it to the list of children. Nothing checks whether the service already has a device, so an announcement that arrives again adds another child with its driver bound, and the number of children is not bounded. The DCP driver's AFK transport (drivers/gpu/drm/apple/afk.c) ignores a repeated announcement on a channel whose service is still live, and the listener tables here already refuse a second listener for one service; only the child registration had no such check. Keep the record where the decision is made: the registration gate, which already orders queueing against removal, now holds the services that have a device, registered or queued, and the name table moves next to it into aop_services.rs. An unchanged repeat of an announcement is ignored. A known name announced on another channel, or a channel announced again under another name, gets no device; the endpoint counts it as a dropped message and logs it, with the announced name and channel, under the same throttle as its other dropped messages. The record holds at most one entry per entry of the table, reserved at probe, so announcements allocate nothing beyond the seven devices. A registration that fails gives up its claim, so the next announcement of that service tries again. This applies to every SoC this driver supports. The new KUnit suite apple_aop_services checks the record; tools/asahi/aop-service-tests.py builds register_service() against host stand-ins and checks the devices queued and the refusal's log line, and the code before this change fails it. Fixes: 3ed935e50d23 ("soc: apple: Add support for the AOP co-processor") Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/soc/apple/aop.rs | 66 ++++++--- drivers/soc/apple/aop_services.rs | 145 +++++++++++++++++++ tools/asahi/aop-service-tests.py | 222 ++++++++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 4 files changed, 414 insertions(+), 22 deletions(-) create mode 100644 drivers/soc/apple/aop_services.rs create mode 100644 tools/asahi/aop-service-tests.py diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 685ff60c89b579..788d7d1b2ba2dd 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -57,7 +57,10 @@ use kernel::{ self, ASC_CPU_CONTROL, // }, - str::CString, + str::{ + BStr, + CString, // + }, sync::{ aref::ARef, atomic::{ @@ -216,6 +219,7 @@ const ALS_SENSOR_BLOB_LEN: usize = 193; const ALS_SENSOR_MESSAGE_LEN: usize = 216; mod aop_ring; +mod aop_services; /// Index into the AFK endpoint tables for RTKit endpoint `ep`, if it is one /// of the endpoints this driver drives. @@ -1307,10 +1311,11 @@ struct AopData { epic_v4: bool, /// Runs the service registrations one at a time; drained on removal. registration_queue: OwnedQueue, - /// Serializes queueing a registration with the start of removal, so that - /// nothing is queued once the queue drains. Never held across a drain. + /// The services that have a device, registered or queued. Taken to queue + /// a registration and by the start of removal, so that nothing is queued + /// once the queue drains. Never held across a drain. #[pin] - registration_gate: Mutex<()>, + registration_gate: Mutex, /// Set once by the first teardown; later teardowns return at once. removing: Atomic, /// Set when the transport starts closing; no call is started after it. @@ -1432,11 +1437,13 @@ impl WorkItem for AopServiceRegisterWork { // transport, but nothing on that path takes this lock. let mut subdevices = this.data.subdevices.lock(); if subdevices.reserve(1, GFP_KERNEL).is_err() { + drop(subdevices); dev_err!( this.data.dev, "Failed to allocate the device slot for service {:?}", this.name ); + this.data.registration_gate.lock().release(this.service); return; } // SAFETY: `info` is a valid, fully initialized `platform_device_info` @@ -1445,12 +1452,14 @@ impl WorkItem for AopServiceRegisterWork { drop(fwnode); match pdev.and_then(|pdev| NonNull::new(pdev).ok_or(EINVAL)) { Err(e) => { + drop(subdevices); dev_err!( this.data.dev, "Failed to create device for service {:?}: {:?}", this.name, e ); + this.data.registration_gate.lock().release(this.service); } Ok(pdev) => { if let Err(child) = subdevices.push_within_capacity(ChildDevice(pdev)) { @@ -1517,13 +1526,14 @@ impl AopData { } else { None }; + let claims = aop_services::Claims::new()?; Arc::pin_init( pin_init!( AopData { dev: dev.as_ref().into(), epic_v4: cfg.epic_v4, registration_queue, - registration_gate <- new_mutex!(()), + registration_gate <- new_mutex!(claims), removing: Atomic::new(false), transport_closing: Atomic::new(false), cpu_started: Atomic::new(false), @@ -1640,29 +1650,41 @@ impl AopData { channel, endpoint: ep.index, }; - let dev_name = match name { - b"aop-audio" => c_str!("audio"), - b"las" => c_str!("las"), - b"als" => c_str!("als"), - b"accel" => c_str!("accel"), - b"gyro" => c_str!("gyro"), - b"devmotion6" => c_str!("devmotion6"), - b"als-temp" => c_str!("als-temp"), - _ => { - return Ok(()); - } - }; // The child's probe calls back into the transport, so it runs from a // work item with the endpoint lock dropped. The gate orders queueing // it against removal, which drains the queue after setting the flag. - let gate = self.registration_gate.lock(); + let mut claims = self.registration_gate.lock(); if self.removing.load(Acquire) { return Ok(()); } - let work = AopServiceRegisterWork::new(dev_name, self.clone(), svc)?; - self.registration_queue.enqueue(work); - drop(gate); - Ok(()) + let dev_name = match claims.claim(svc, name) { + Ok(Some(dev_name)) => dev_name, + Ok(None) => return Ok(()), + Err(e) => { + // Counted and logged as the endpoint's other dropped + // messages are, with what the firmware announced. + ep.drop_message( + &self.dev, + fmt!( + "service \"{}\" on channel {}: {:?} (its name or channel has a device)", + BStr::from_bytes(name), + channel, + e + ), + ); + return Ok(()); + } + }; + match AopServiceRegisterWork::new(dev_name, self.clone(), svc) { + Ok(work) => { + self.registration_queue.enqueue(work); + Ok(()) + } + Err(e) => { + claims.release(svc); + Err(e) + } + } } /// Hands a report to its listener; `Ok(false)` when there is none. diff --git a/drivers/soc/apple/aop_services.rs b/drivers/soc/apple/aop_services.rs new file mode 100644 index 00000000000000..46157a1d6a443d --- /dev/null +++ b/drivers/soc/apple/aop_services.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The services that get a child device, and the record of those that have one. +//! +//! The firmware announces each service it offers by name, with the channel +//! the service answers on. A service this driver knows gets one platform +//! device, named for it and described by the AOP's device-tree child of that +//! name. The record allows one device per known name and per service, so its +//! size is bounded by the table below, whatever the firmware announces. + +use kernel::{prelude::*, soc::apple::aop::EPICService}; + +/// The announced names of the services that get a device, and the device's +/// name. Each device name appears once. +const DEVICES: [(&[u8], &CStr); 7] = [ + (b"aop-audio", c"audio"), + (b"las", c"las"), + (b"als", c"als"), + (b"accel", c"accel"), + (b"gyro", c"gyro"), + (b"devmotion6", c"devmotion6"), + (b"als-temp", c"als-temp"), +]; + +/// The services that have a device, registered or queued for registration, +/// each with its entry in [`DEVICES`]. +pub(super) struct Claims(KVec<(EPICService, usize)>); + +impl Claims { + pub(super) fn new() -> Result { + Ok(Self(KVec::with_capacity(DEVICES.len(), GFP_KERNEL)?)) + } + + /// Claims the device for a service announced as `name`. Returns the name + /// of the device to register, or `None` when there is nothing to do: the + /// service has no device, or it was announced before as it is now. A + /// service whose name already has a device on another channel, or whose + /// channel already has one under another name, gets none (`EEXIST`). + pub(super) fn claim( + &mut self, + service: EPICService, + name: &[u8], + ) -> Result> { + let Some(index) = DEVICES.iter().position(|&(known, _)| known == name) else { + return Ok(None); + }; + for &(claimed, claimed_index) in self.0.iter() { + match (claimed == service, claimed_index == index) { + (true, true) => return Ok(None), + (false, false) => {} + _ => return Err(EEXIST), + } + } + // Each entry of the table is claimed at most once, so this stays + // within the capacity reserved for the whole table. + self.0.push_within_capacity((service, index)).map_err(|_| ENOSPC)?; + Ok(Some(DEVICES[index].1)) + } + + /// Gives up the claim of a service whose device could not be registered, + /// so that the next announcement of the service tries again. + pub(super) fn release(&mut self, service: EPICService) { + self.0.retain(|&mut (claimed, _)| claimed != service); + } +} + +#[kunit_tests(apple_aop_services)] +mod tests { + use super::*; + + fn svc(endpoint: u8, channel: u32) -> EPICService { + EPICService { channel, endpoint } + } + + #[test] + fn known_services_get_their_device() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + assert_eq!(claims.claim(svc(0x23, 2), b"als-temp")?, Some(c"als-temp")); + Ok(()) + } + + #[test] + fn unknown_services_get_nothing() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x20, 1), b"misc")?, None); + assert_eq!(claims.claim(svc(0x20, 2), b"")?, None); + assert_eq!(claims.claim(svc(0x20, 3), b"als\0")?, None); + // The unknown announcements took no claim on the channel. + assert_eq!(claims.claim(svc(0x20, 1), b"als")?, Some(c"als")); + Ok(()) + } + + #[test] + fn an_unchanged_announcement_adds_no_device() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + for _ in 0..100 { + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, None); + } + Ok(()) + } + + #[test] + fn a_name_or_channel_with_a_device_is_refused() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + // The same name on another channel or endpoint. + assert_eq!(claims.claim(svc(0x23, 2), b"als"), Err(EEXIST)); + assert_eq!(claims.claim(svc(0x24, 1), b"als"), Err(EEXIST)); + // The same channel under another name. + assert_eq!(claims.claim(svc(0x23, 1), b"las"), Err(EEXIST)); + // Other services are unaffected. + assert_eq!(claims.claim(svc(0x23, 2), b"las")?, Some(c"las")); + Ok(()) + } + + #[test] + fn devices_are_bounded_by_the_table() -> Result { + let mut claims = Claims::new()?; + let mut devices = 0; + for channel in 0..64 { + for &(name, _) in DEVICES.iter() { + if let Ok(Some(_)) = claims.claim(svc(0x20 + (channel % 8) as u8, channel), name) { + devices += 1; + } + } + } + assert_eq!(devices, DEVICES.len()); + assert_eq!(claims.0.len(), DEVICES.len()); + Ok(()) + } + + #[test] + fn a_released_service_can_be_claimed_again() -> Result { + let mut claims = Claims::new()?; + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, Some(c"als")); + claims.release(svc(0x21, 1)); + assert_eq!(claims.claim(svc(0x21, 1), b"aop-audio")?, Some(c"audio")); + assert_eq!(claims.claim(svc(0x23, 1), b"als")?, None); + Ok(()) + } +} diff --git a/tools/asahi/aop-service-tests.py b/tools/asahi/aop-service-tests.py new file mode 100644 index 00000000000000..2b7faa55a50866 --- /dev/null +++ b/tools/asahi/aop-service-tests.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production AOP service registration against host mocks. + +Each check announces services to AopData::register_service and counts the +child-device registrations it queues. A service gets one device however +often, and under whatever other channel or name, it is announced again. +""" +import argparse +from pathlib import Path +import os +import shlex +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +AOP = 'drivers/soc/apple/aop.rs' +SERVICES = 'drivers/soc/apple/aop_services.rs' + + +def read(ref, path): + if ref is None: + file = ROOT / path + return file.read_text() if file.is_file() else None + probe = subprocess.run(['git', 'cat-file', '-e', f'{ref}:{path}'], cwd=ROOT, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if probe.returncode: + return None + return subprocess.check_output(['git', 'show', f'{ref}:{path}'], cwd=ROOT, text=True) + + +def block(source, marker): + start = source.index(marker) + brace = source.index('{', source.index(')', start)) + depth = 1 + end = brace + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def program(ref): + aop = read(ref, AOP) + services = read(ref, SERVICES) + parts = [STUBS] + if services is None: + parts.append('type Gate = ();\nfn gate() -> Gate {}\n') + else: + body = services[:services.index('#[kunit_tests')] + body = '\n'.join(line for line in body.splitlines() + if not line.startswith(('use kernel', '//!'))) + parts.append('mod aop_services {\nuse super::*;\n' + body + '\n}\n') + parts.append('type Gate = aop_services::Claims;\n' + 'fn gate() -> Gate { aop_services::Claims::new().unwrap() }\n') + parts.append('impl AopData {\n' + block(aop, ' fn register_service(') + '\n}\n') + parts.append(CHECKS) + return '\n'.join(parts) + + +STUBS = r''' +#![allow(dead_code, unused_imports, unused_macros)] +use std::ffi::CStr; +use std::pin::Pin; +use std::sync::atomic::Ordering::Acquire; +use std::sync::Arc; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(i32); +const ENOMEM: Error = Error(-12); +const EEXIST: Error = Error(-17); +const ENOSPC: Error = Error(-28); +type Result = std::result::Result; +const GFP_KERNEL: u32 = 0; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EPICService { pub channel: u32, pub endpoint: u8 } +pub struct KVec { items: Vec, cap: usize } +impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { Ok(Self { items: Vec::new(), cap }) } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + if self.items.len() < self.cap { self.items.push(v); Ok(()) } else { Err(v) } + } + fn iter(&self) -> std::slice::Iter<'_, T> { self.items.iter() } + fn retain(&mut self, f: impl FnMut(&mut T) -> bool) { self.items.retain_mut(f) } + fn len(&self) -> usize { self.items.len() } +} +macro_rules! c_str { + ($s:literal) => { + match CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()) { Ok(c) => c, Err(_) => panic!() } + }; +} +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Atomic(std::sync::Mutex); +impl Atomic { fn load(&self, _: std::sync::atomic::Ordering) -> T { *self.0.lock().unwrap() } } +struct Queue(std::sync::Mutex>); +impl Queue { + fn enqueue(&self, work: Pin>) { + self.0.lock().unwrap().push((work.name.to_str().unwrap().into(), work.service)); + } +} +struct AopServiceRegisterWork { name: &'static CStr, service: EPICService } +impl AopServiceRegisterWork { + fn new(name: &'static CStr, _data: Arc, service: EPICService) -> Result>> { + Ok(Box::pin(Self { name, service })) + } +} +macro_rules! fmt { ($($t:tt)*) => { format_args!($($t)*) }; } +struct BStr<'a>(&'a [u8]); +impl<'a> BStr<'a> { fn from_bytes(b: &'a [u8]) -> Self { BStr(b) } } +impl std::fmt::Display for BStr<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&String::from_utf8_lossy(self.0)) } +} +struct Device; +struct AFKEndpoint { index: u8, dropped: Vec } +impl AFKEndpoint { + fn drop_message(&mut self, _dev: &Device, why: std::fmt::Arguments<'_>) { self.dropped.push(why.to_string()); } +} +struct AopData { + dev: Device, registration_gate: Mutex, removing: Atomic, registration_queue: Queue, +} +''' + +CHECKS = r''' +const NAMES: [&[u8]; 7] = [b"aop-audio", b"las", b"als", b"accel", b"gyro", b"devmotion6", b"als-temp"]; +fn data(removing: bool) -> Arc { + Arc::new(AopData { + dev: Device, + registration_gate: Mutex(std::sync::Mutex::new(gate())), + removing: Atomic(std::sync::Mutex::new(removing)), + registration_queue: Queue(std::sync::Mutex::new(Vec::new())), + }) +} +fn announce_logged(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> Vec { + let mut ep = AFKEndpoint { index: endpoint, dropped: Vec::new() }; + // An error return is logged by the caller; the queue and the endpoint's dropped messages are what matter here. + let _ = d.clone().register_service(&mut ep, channel, name); + ep.dropped +} +fn announce(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) { announce_logged(d, endpoint, channel, name); } +fn queued(d: &Arc) -> usize { d.registration_queue.0.lock().unwrap().len() } +fn main() { + let mut fixed = Vec::new(); + let mut control = Vec::new(); + let d = data(false); + for _ in 0..5 { announce(&d, 0x23, 1, b"als"); } + fixed.push(("an unchanged announcement repeated 5 times", queued(&d), 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 2, b"als"); + announce(&d, 0x24, 1, b"als"); + fixed.push(("a name announced again on another channel and endpoint", queued(&d), 1)); + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + announce(&d, 0x21, 1, b"als"); + fixed.push(("a channel announced again under another name", queued(&d), 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + let log = announce_logged(&d, 0x23, 2, b"als"); + let named = log.len() == 1 && log[0].contains("\"als\"") && log[0].contains("channel 2"); + fixed.push(("a refused announcement logged once as a dropped message, with its name and channel", named as usize, 1)); + let d = data(false); + announce(&d, 0x23, 1, b"als"); + let quiet = announce_logged(&d, 0x23, 1, b"als").len(); + control.push(("an unchanged repeat logs nothing", quiet, 0)); + let d = data(false); + for channel in 0..64u32 { + for name in NAMES { announce(&d, 0x20 + (channel % 8) as u8, channel, name); } + } + fixed.push(("every known name on 64 channels", queued(&d), NAMES.len())); + let d = data(false); + for (i, name) in NAMES.iter().enumerate() { announce(&d, 0x20 + i as u8, i as u32, name); } + control.push(("each known service once", queued(&d), NAMES.len())); + let d = data(false); + announce(&d, 0x20, 1, b"misc"); + announce(&d, 0x20, 2, b"aop-audio\0x"); + control.push(("unknown services", queued(&d), 0)); + let d = data(true); + announce(&d, 0x23, 1, b"als"); + control.push(("an announcement during removal", queued(&d), 0)); + let mut out = String::new(); + let mut fixed_failed = 0; + let mut control_failed = 0; + for (kind, list) in [("check", &fixed), ("control", &control)] { + for (what, got, want) in list.iter() { + let ok = got == want; + if !ok { if kind == "check" { fixed_failed += 1 } else { control_failed += 1 } } + out += &format!("{} {}: {}: got {}, expected {}\n", if ok { "ok" } else { "FAIL" }, kind, what, got, want); + } + } + print!("{}", out); + println!("checks failed {} of {}, controls failed {} of {}", fixed_failed, fixed.len(), control_failed, control.len()); + std::process::exit(if control_failed > 0 { 3 } else if fixed_failed > 0 { 1 } else { 0 }); +} +''' + + +def run(ref, tmp): + source = Path(tmp) / (('old-' if ref else '') + 'aop-service.rs') + binary = source.with_suffix('') + source.write_text(program(ref)) + subprocess.run(shlex.split(os.environ.get('RUSTC', 'rustc')) + + ['--edition=2021', '-Dwarnings', str(source), '-o', str(binary)], check=True) + return subprocess.run([str(binary)]).returncode + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('--old-ref', help='require this older revision to fail the checks and pass the controls') + args = ap.parse_args() + with tempfile.TemporaryDirectory(prefix='aop-service-') as tmp: + rc = run(args.old_ref, tmp) + if args.old_ref: + if rc == 1: + print(f'{args.old_ref} fails the checks, as expected') + return 0 + raise SystemExit(f'{args.old_ref}: rc {rc}; the test does not catch the original code') + return rc + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 8ad9b94ac5b3cb..438bad1b2ba074 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -103,6 +103,9 @@ def mutations(flag, names, base, expect=KILL): 'aop-als-channel-tests.py': [([], PASS)], 'aop-als-calibration-tests.py': [([], PASS)], 'aop-bootargs-tests.py': [([], PASS)], + # 24dc422773c9 registers another child device for each repeated service announcement. + 'aop-service-tests.py': [([], PASS), + (['--old-ref', '24dc422773c9beb9e99ee9e1ab713e9d6abb1e7b'], PASS)], 'mtp-pm-tests.py': [(out(), PASS), (out() + ['--old-transport', '4db3a5a22c43'], PASS), (out() + ['--old-mouse', '62d2045d8928'], PASS)], From 404788a51301370721bcd8e4dd62d10d39377b4c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:24:05 -0500 Subject: [PATCH 0221/1514] soc: apple: display: recognise the T8132 macOS 27.2 DCP image The Mac mini (J773g) on macOS 27.2 (26B123) runs one DCP image, UUID B3BA603C-3CA7-3E21-B393-44EB20BD2AEF, on dcp, dcpext0 and dcpext1 (its 27.2 ADT; the three share __TEXT). Its external processors are to be driven through the firmware-27 backend as the T6041's 27.2 ones are, so the display gate and the DCP driver need the same pinned admission the T6041 helpers give: the image UUID, firmware version and compatibility 27.2.0. Split the T6041 check into apple_dcp_image_v27_2(), which takes the image UUID, and add apple_t8132_dcpext_v27_2() for a J773g dcpext. It is limited to the J773g until another T8132 board's 27.2 trace shows the same interface. apple_t8132_dcpext_v27_2() is in linux/soc/apple/t8132.h, with the other T8132 board helpers: its machine check stays out of display.h, whose T6041 helpers key on the processor and its image alone (the apple-dcp boot selftest builds them with no of_machine_is_compatible()). Signed-off-by: Diljit Singh --- include/linux/soc/apple/display.h | 6 ++++++ include/linux/soc/apple/t8132.h | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index aa7266693ace87..f6264be746ca90 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -18,6 +18,12 @@ int apple_drm_t8132_link_device(struct device *consumer); /* T6041 DCP image shipped with macOS 27.2 (26B123). */ #define APPLE_T6041_DCP_26B123_UUID "964EDE5B-8F78-38C2-A727-519CC9F0AF27" +/* + * T8132 DCP image shipped with macOS 27.2 (26B123), as the J773g's 27.2 ADT + * names it for dcp, dcpext0 and dcpext1 alike (they share its __TEXT). + */ +#define APPLE_T8132_DCP_26B123_UUID "B3BA603C-3CA7-3E21-B393-44EB20BD2AEF" + /* * @np is a @compat_name display processor that the boot loader handed over * with the 27.2 (26B123) image @image_uuid: firmware version and diff --git a/include/linux/soc/apple/t8132.h b/include/linux/soc/apple/t8132.h index ec91e8faaa9b5d..9a0607a7eb962e 100644 --- a/include/linux/soc/apple/t8132.h +++ b/include/linux/soc/apple/t8132.h @@ -3,6 +3,7 @@ #define _LINUX_SOC_APPLE_T8132_H #include +#include #include #include @@ -54,6 +55,20 @@ static inline bool apple_t8132_firmware_path(void) return apple_t8132_air() || apple_t8132_qualified_firmware(); } +/* + * A T8132 external display processor on the Mac mini (J773g) handed over + * with the 27.2 image: it runs the firmware-27 backend (iomfb_v27.c), not + * the M4 26.6.2 one (iomfb_m4.c). Other T8132 boards and images are not + * admitted until a trace of theirs says the same interface applies. Kept + * here, not in display.h, whose T6041 helpers key on the processor alone. + */ +static inline bool apple_t8132_dcpext_v27_2(const struct device_node *np) +{ + return of_machine_is_compatible("apple,j773g") && + apple_dcp_image_v27_2(np, "apple,t8132-dcpext", + APPLE_T8132_DCP_26B123_UUID); +} + /* * The radio port the Airs have: reg-on on the SMC's gP13 with the same * template, and the radio's two ordinary streams managed on port 0 of the From cb9fdb871c77d691a3331f228ea584eaea45cd25 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:25:04 -0500 Subject: [PATCH 0222/1514] drm/apple: keep the M4 backend off firmware-27 T8132 display processors The M4 backend (iomfb_m4.c, t8132_ext_drm.c) adopts T8132 display processors on the 26.6.2 firmware path. The Mac mini's device tree is also booted on macOS 27.2 firmware, where the boot loader leaves the main DCP running idle and hands it to nobody, and where dcpext0 is to run the firmware-27 backend instead. Make the M4 paths say so: - dcp_check_firmware_version() refuses an M4 hw-data DCP off apple_t8132_firmware_path(), before the probe claims its IOMMU domain. iomfb_m4_init() refused such firmware already, but only later. - apple_dcp_usable() leaves the main T8132 DCP out of the DRM device's components off that path, so a device tree that enables it (as the 26.6.2 HDMI work does) does not hold the DRM device up waiting for it. - dcp_is_t8132_ext() and the probe, remove and shutdown dispatch match only an M4-adopted dcpext (dcp_t8132_ext_m4_node()): a J773g dcpext with the 27.2 image (apple_t8132_dcpext_v27_2()) is neither routed through dcp_platform_probe_t8132_ext() nor caught by the T8132 Type-C, crossbar and tunnel special cases of the fabric and the DPTX service. Nothing changes on the Airs (any firmware) or on any T8132 Mac on 26.6.2. The host replays that extract dcp_is_t8132_ext() (tiled-split, dcpext26-crossbar-union) take the new helper with it; the crossbar one also checks that a J773g 27.2 dcpext takes the T6041 firmware-27 link. The apple-dcp boot selftest checks the gate both ways: a T8132 processor of the M4 backend is the M4 backend's on its firmware path, and nobody's off it. Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/apple_drv.c | 9 ++++++- drivers/gpu/drm/apple/dcp-fabric.c | 20 ++++++++++----- drivers/gpu/drm/apple/dcp-fabric.h | 7 +++++- drivers/gpu/drm/apple/dcp.c | 20 ++++++++++++--- tools/asahi/dcpext26-crossbar-union-tests.py | 19 +++++++++++--- tools/asahi/t6030-clock/fixture.c | 4 +-- tools/asahi/tiled-split-tests.py | 3 ++- tools/asahi/tiled-split/fixture.c | 7 ++++++ tools/asahi/tunnel-route/fixture.c | 2 +- .../selftests/drivers/gpu/apple-dcp/boot.py | 25 +++++++++++++++++++ 10 files changed, 98 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index b6ec46a7902590..0a19d5ae26e152 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -25,6 +25,7 @@ #include #include #include +#include #include #include @@ -1497,7 +1498,13 @@ static bool apple_dcp_usable(struct device_node *np) dcp_h17p_external_supported(np)) && /* t6041_dcpext=0 keeps the T6041 external processors out. */ (!of_device_is_compatible(np, "apple,t6041-dcpext") || - dcp_t6041_ext_enabled()); + dcp_t6041_ext_enabled()) && + /* + * The T8132 main DCP is the M4 backend's, on its 26.6.2 + * firmware path only (see dcp_check_firmware_version()). + */ + (!of_device_is_compatible(np, "apple,t8132-dcp") || + apple_t8132_firmware_path()); } static void apple_drm_quiesce_connectors(struct drm_device *drm) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 08f5057cf1a9d7..7ff72bfe6dddaf 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -12,7 +12,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -226,6 +228,17 @@ bool dcp_hdmi_port_attached(struct apple_dcp *dcp) gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0; } +bool dcp_t8132_ext_m4_node(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t8132-dcpext") && + !apple_t8132_dcpext_v27_2(np); +} + +bool dcp_is_t8132_ext(const struct apple_dcp *dcp) +{ + return dcp_t8132_ext_m4_node(dcp->dev->of_node); +} + /* * A route of an adopted T8132 dcpext whose PHY has no DP alt mode: the * crossbar's DP PHY output has nothing behind it. The board marks the PHYs @@ -234,17 +247,12 @@ bool dcp_hdmi_port_attached(struct apple_dcp *dcp) */ static bool dcp_typec_route_no_dp_alt(const struct apple_dcp_typec_route *route) { - if (!of_device_is_compatible(route->dcp->dev->of_node, "apple,t8132-dcpext")) + if (!dcp_is_t8132_ext(route->dcp)) return false; return IS_ERR_OR_NULL(route->phy) || !of_property_read_bool(route->phy->dev.of_node, "apple,dp-alt-mode"); } -bool dcp_is_t8132_ext(const struct apple_dcp *dcp) -{ - return of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"); -} - /* * DP IN outputs (bits 0/1) whose tunnel pixel clock source @route cannot be: * T6030 even sources only, T8132 its dcpexts (2 and 4), others any. diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index 7876718cbfdfaa..9457e0016c1f24 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -120,7 +120,12 @@ int dcp_tunnel_set_rate(struct apple_dcp *dcp, struct phy *phy, u32 unit, u32 link_rate); int dcp_tunnel_dpin_activate(struct apple_dcp *dcp, u32 unit, bool active); -/* An adopted T8132 dcpext. */ +/* + * A T8132 dcpext adopted through the M4 26.6.2 backend (iomfb_m4.c, + * t8132_ext_drm.c). A J773g dcpext on firmware 27.2 is an ordinary + * firmware-27 pipe instead and is neither of these. + */ +bool dcp_t8132_ext_m4_node(const struct device_node *np); bool dcp_is_t8132_ext(const struct apple_dcp *dcp); /* DCP probe, resume and endpoint teardown hooks. */ diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..2f120135cc4287 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -6008,6 +6009,19 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); } + /* + * The M4 backend (iomfb_m4.c) is written for the 26.6.2 firmware path + * only (apple_t8132_firmware_path()). Off it, as on a Mac mini booted + * from macOS 27.2, the boot loader leaves the main DCP running idle and + * hands it to nobody: never adopt or touch it. iomfb_m4_init() would + * refuse such firmware too, but only after the probe has claimed the + * DCP's IOMMU domain. + */ + if (hw->firmware_compat == DCP_FIRMWARE_M4 && !apple_t8132_firmware_path()) { + dev_info(dev, "T8132 display processor left alone off the M4 26.6.2 firmware path\n"); + return DCP_FIRMWARE_UNKNOWN; + } + /* * SoCs introduced with H17-generation firmware pin its interface; the * loader may not recognise their boot firmware version. @@ -7898,7 +7912,7 @@ static int dcp_platform_probe(struct platform_device *pdev) return -ENODEV; } - if (of_device_is_compatible(dev->of_node, "apple,t8132-dcpext")) + if (dcp_t8132_ext_m4_node(dev->of_node)) return dcp_platform_probe_t8132_ext(pdev); if (!dcp_ext_is_failsafe(dev->of_node)) return dcp_platform_probe_pipe(pdev); @@ -7974,7 +7988,7 @@ static void dcp_platform_remove(struct platform_device *pdev) if (dcp) av_audiosrv_quiesce(dcp); /* An adopted external DCP never joined the DRM device. */ - if (of_device_is_compatible(pdev->dev.of_node, "apple,t8132-dcpext")) { + if (dcp_t8132_ext_m4_node(pdev->dev.of_node)) { /* Enabled with its Type-C routes, see dcp_t8132_ext_routes(). */ if (dcp) disable_delayed_work_sync(&dcp->typec_reconnect_wq); @@ -8040,7 +8054,7 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) } /* An adopted external DCP never joined the DRM device. */ - if (of_device_is_compatible(pdev->dev.of_node, "apple,t8132-dcpext")) + if (dcp_t8132_ext_m4_node(pdev->dev.of_node)) return; component_del(&pdev->dev, &dcp_comp_ops); } diff --git a/tools/asahi/dcpext26-crossbar-union-tests.py b/tools/asahi/dcpext26-crossbar-union-tests.py index 9607ad8ee202e2..b6291bcf915531 100644 --- a/tools/asahi/dcpext26-crossbar-union-tests.py +++ b/tools/asahi/dcpext26-crossbar-union-tests.py @@ -44,7 +44,7 @@ def function(text, name): #include #include enum { DCP_FIRMWARE_V_27_0 = 27, DCP_IOMFB_METHODS_J613_EXT26 = 26 }; -struct device_node { const char *compatible; }; +struct device_node { const char *compatible; bool v27_2; }; struct device { struct device_node *of_node; }; struct mux_control { int id; }; struct apple_dcp_typec_route { @@ -68,6 +68,10 @@ def function(text, name): static bool of_device_is_compatible(const struct device_node *n, const char *name) { return !strcmp(n->compatible, name); } +/* The J773g's 27.2 (26B123) dcpext admission, include/linux/soc/apple/display.h. */ +static bool apple_t8132_dcpext_v27_2(const struct device_node *n) { + return of_device_is_compatible(n, "apple,t8132-dcpext") && n->v27_2; +} static void mock_guard(int *lock) { (void)lock; locks++; } #define guard(kind) mock_guard #define dev_warn(...) ((void)0) @@ -81,7 +85,7 @@ def function(text, name): cases = r''' static void reset(void) { links = v27 = locks = 0; last = NULL; last_up = false; fault = 0; } int main(void) { - struct device_node node = { "apple,other-dcp" }; + struct device_node node = { .compatible = "apple,other-dcp" }; struct device dev = { &node }; struct mux_control a = {1}, b = {2}; struct apple_dcp_typec_route route = { .xbar = &a, .selected = true }; @@ -128,16 +132,25 @@ def function(text, name): reset(); assert(dcp_direct_crossbar_link(&d, true) == 0); assert(v27 == 0 && links == 1 && locks == 1); } + /* A J773g dcpext on firmware 27.2 is no M4 dcpext: it links as a T6041 firmware-27 one. */ + machine = "apple,other"; node.compatible = "apple,t8132-dcpext"; node.v27_2 = true; + struct apple_dcp j773g = { .dev = &dev, .active_typec_route = &route, + .fw_compat = DCP_FIRMWARE_V_27_0, .desktop_external = true }; + assert(!dcp_is_t8132_ext(&j773g)); + reset(); assert(dcp_direct_crossbar_link(&j773g, true) == 0); + assert(v27 == 0 && links == 1 && locks == 1 && j773g.direct_xbar_up == &a); + node.v27_2 = false; machine = "apple,other"; node.compatible = "apple,other-dcp"; struct apple_dcp unrelated = { .dev = &dev, .active_typec_route = &route }; reset(); assert(dcp_direct_crossbar_link(&unrelated, true) == 0); assert(links == 0 && locks == 0); - puts("PASS production crossbar union, route/cache/error behavior, V27 precedence and unrelated exclusion"); + puts("PASS production crossbar union, route/cache/error behavior, V27 precedence, J773g 27.2 and unrelated exclusion"); return 0; } ''' unit = pre + function(header, 'dcp_is_ext26') + '\n' unit += function(source, 'dcp_t6041_ext_v27') + '\n' +unit += function(source, 'dcp_t8132_ext_m4_node') + '\n' unit += function(source, 'dcp_is_t8132_ext') + '\n' + link + '\n' + cases with tempfile.TemporaryDirectory() as tmp: c = Path(tmp) / 'crossbar.c' diff --git a/tools/asahi/t6030-clock/fixture.c b/tools/asahi/t6030-clock/fixture.c index 3efdc838fe8d18..580fc335c2f680 100644 --- a/tools/asahi/t6030-clock/fixture.c +++ b/tools/asahi/t6030-clock/fixture.c @@ -139,8 +139,8 @@ static int apple_t6050_dp_tunnel_clock(struct phy *p, unsigned clock, u8 rate) return t6050_error; } /* - * Production: of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"). - * These are T6030 DCPs: the T8132 dcpext paths must never be taken. + * Production: an apple,t8132-dcpext the M4 backend adopts (dcp_t8132_ext_m4_node(): + * not a J773g one on firmware 27.2). These are T6030 DCPs: the T8132 dcpext paths must never be taken. */ static bool dcp_is_t8132_ext(const struct apple_dcp *dcp) { diff --git a/tools/asahi/tiled-split-tests.py b/tools/asahi/tiled-split-tests.py index 7ee72aa18bf5cd..8ee3749aa80baf 100644 --- a/tools/asahi/tiled-split-tests.py +++ b/tools/asahi/tiled-split-tests.py @@ -21,7 +21,8 @@ 'drivers/gpu/drm/apple/dcp-fabric-session.h': ['dcp_fabric_binding_request'], 'drivers/gpu/drm/apple/dcp-fabric-core.c': ['dcp_fabric_tunnel_slot'], 'drivers/gpu/drm/apple/dcp-fabric.c': [ - 'dcp_typec_route_no_dp_alt', 'dcp_is_t8132_ext', 'dcp_typec_port_untileable', + 'dcp_t8132_ext_m4_node', 'dcp_is_t8132_ext', 'dcp_typec_route_no_dp_alt', + 'dcp_typec_port_untileable', 'dcp_tb_slot', 'dcp_tb_split_locked', 'dcp_tb_dispatch_request'], } CASES = ['t6030-dpin1-alone', 't6030-dpin1-alone-before-services', diff --git a/tools/asahi/tiled-split/fixture.c b/tools/asahi/tiled-split/fixture.c index 30f4ca0a797265..a0a6974408071e 100644 --- a/tools/asahi/tiled-split/fixture.c +++ b/tools/asahi/tiled-split/fixture.c @@ -61,6 +61,13 @@ static bool of_property_read_bool(const struct device_node *np, const char *name return np && !strcmp(name, "apple,dp-alt-mode") && np->dp_alt_mode; } +/* No J773g firmware-27.2 dcpext here: every T8132 dcpext is the M4 backend's. */ +static bool apple_t8132_dcpext_v27_2(const struct device_node *np) +{ + (void)np; + return false; +} + #define IS_ERR_OR_NULL(ptr) (!(ptr)) struct phy { struct device dev; }; struct mux_chip; diff --git a/tools/asahi/tunnel-route/fixture.c b/tools/asahi/tunnel-route/fixture.c index 2bcb8e713e5bef..e95d06be8446c0 100644 --- a/tools/asahi/tunnel-route/fixture.c +++ b/tools/asahi/tunnel-route/fixture.c @@ -67,7 +67,7 @@ static bool of_machine_is_compatible(const char *compatible) assert(!strcmp(compatible, "apple,t6030")); return t6030; } -/* Production: of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"). */ +/* Production: an M4-adopted apple,t8132-dcpext (dcp_t8132_ext_m4_node()). */ static bool dcp_is_t8132_ext(const struct apple_dcp *dcp) { return t8132_ext; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index b7ebb2fc9fc5ff..ad07edf47e594e 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -228,6 +228,7 @@ def t6041_v27_admission(root): DCP_FIRMWARE_UNKNOWN, DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0, + DCP_FIRMWARE_M4, }; struct dcp_v14_board; struct apple_dcp_hw_data { enum dcp_firmware_version firmware_compat; }; @@ -294,6 +295,13 @@ def t6041_v27_admission(root): #define DCP_FW_VERSION_STR_LEN 32 #define GFP_KERNEL 0 #define dev_err(...) ((void)0) +#define dev_info(...) ((void)0) +/* linux/soc/apple/t8132.h: the M4 backend's 26.6.2 firmware path (or an Air) */ +static bool t8132_firmware_path; +static bool apple_t8132_firmware_path(void) +{ + return t8132_firmware_path; +} static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) { (void)dev; (void)src; (void)len; (void)gfp; @@ -422,9 +430,26 @@ def t6041_v27_admission(root): node.fw[2] = 0; node.compat[2] = 0; assert(apple_t8122_dcp_v27_2(&node)); + /* + * A T8132 processor of the M4 backend keeps it on the M4 firmware path + * only; off it (a Mac mini booted from 27.2) nobody adopts or touches it. + */ + static struct apple_dcp_hw_data hw_m4 = { .firmware_compat = DCP_FIRMWARE_M4 }; + dev.hw = &hw_m4; + for (unsigned ext = 0; ext < 2; ext++) { + reset_t6041_26b123(ext); + node.compatible = ext ? "apple,t8132-dcpext" : "apple,t8132-dcp"; + node.uuid = "other"; + t8132_firmware_path = true; + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + t8132_firmware_path = false; + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + } + dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); + puts("PASS T8132 M4 backend only on its firmware path"); return 0; } ''' From 3f777b58516e510f506a6b41957840eb49d51c34 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:27:15 -0500 Subject: [PATCH 0223/1514] drm/apple: dcp: run the J773g dcpext on firmware 27.2 with the 27.2 table On macOS 27.2 (26B123) the Mac mini's (J773g) external display processors run the same image as its main DCP (UUID B3BA603C), and aura hands them over the way it hands over the M4 Max Mac Studio's (J575c): firmware memory in text/data/heap regions, apple,firmware-version and -compat 27.2.0, the image UUID, and the dispextN provider clocks. Admit such a dcpext the way the T6041 27.2 dcpext is admitted: - dcp_check_firmware_version() returns firmware 27 for it, with the 27.2 method table, before the M4 hw data is looked at. That the T8132 26B123 image numbers its IOMFB methods as the T6041 and T8142 26B123 images do is assumed, not traced; the comment says so. The method table check is now one helper, dcp_v27_method_table(), shared with the existing firmware-27 and T6041 cases. - It gets apple_dcp_hw_t8132_dcpext_v27, whichever hw data its compatible matched: firmware_dma_bits 41 (the firmware DART window, 1 TiB + 64 GiB, ADT dart-dcpext0 vm-base and vm-size-23), num_dptx_ports 2, adopt_live_session (iBoot leaves it running, pre-loaded = running = 1) and sink_metadata_edid, as T6041's dcpext gets on 27.2. No sleep support. - It is a failsafe external processor and a component of the DRM device (apple_dcp_id_tbl, apple_dcp_usable()), unlike an M4-adopted dcpext. The apple-dcp boot selftest (t6041-v27-admission) now also builds dcp_v27_method_table() and the real apple_t8132_dcpext_v27_2(), with its machine check as a flag. It checks: - the J773g dcpext with the T8132 27.2 image runs the 27.2 table, on and off the M4 path; - another M4 Mac's dcpext does not; - the main DCP, the T6041 image, a missing or second UUID, and other releases are refused. Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/apple_drv.c | 10 ++- drivers/gpu/drm/apple/dcp.c | 61 +++++++++++++++++-- .../selftests/drivers/gpu/apple-dcp/boot.py | 55 +++++++++++++++-- 3 files changed, 117 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 0a19d5ae26e152..d791d22ec6d13d 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1480,6 +1480,8 @@ static const struct of_device_id apple_dcp_id_tbl[] = { #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) { .compatible = "apple,t8132-dcp" }, #endif + /* apple_dcp_usable(): only a J773g one on firmware 27.2. */ + { .compatible = "apple,t8132-dcpext" }, {}, }; @@ -1504,7 +1506,13 @@ static bool apple_dcp_usable(struct device_node *np) * firmware path only (see dcp_check_firmware_version()). */ (!of_device_is_compatible(np, "apple,t8132-dcp") || - apple_t8132_firmware_path()); + apple_t8132_firmware_path()) && + /* + * A T8132 dcpext the M4 backend adopts is no component: its + * outputs are t8132_ext_drm.c's. The J773g's on 27.2 is a pipe. + */ + (!of_device_is_compatible(np, "apple,t8132-dcpext") || + apple_t8132_dcpext_v27_2(np)); } static void apple_drm_quiesce_connectors(struct drm_device *drm) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 2f120135cc4287..4378f6ad93ca72 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6000,6 +6000,25 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); } + /* + * T8132 external processors: the Mac mini's (J773g) on macOS 27.2 + * (26B123), handed over as the T6041's 27.2 ones are, run the + * firmware-27 backend with the 27.2 method table, as on T6041; any + * other is the M4 backend's (below). Both need + * CONFIG_DRM_APPLE_DCP_T8132, which matches the T8132 nodes. + * + * ASSUMED, NOT TRACED: the T8132 26B123 image (B3BA603C) numbers its + * IOMFB methods as the T6041 (964EDE5B) and T8142 26B123 images do + * (dcp_methods_27_2), and calls the same D-callbacks. A trace of macOS + * 27.2 driving the mini's dcpext0 has to confirm the A4xx/A5xx IDs + * before this is relied on. + */ + if (apple_t8132_dcpext_v27_2(dev->of_node)) { + /* Checked by apple_t8132_dcpext_v27_2(). */ + dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); + return dcp_v27_method_table(dev, compat_str); + } + if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { @@ -6782,8 +6801,9 @@ static void dcp_ext_give_up(struct apple_dcp *dcp, int err, const char *when); /* * The external processors whose failure must not take the DRM device down: - * T8122's, T6041's, T6050's and T8142's dcpext. One that fails to probe or bind joins - * as an unusable pipe (ext_dead), and the other displays go on without it. + * T8122's, T6041's, T6050's and T8142's dcpext, and the J773g's on 27.2. One + * that fails to probe or bind joins as an unusable pipe (ext_dead), and the + * other displays go on without it. * With every processor failed the DRM device has no pipe and does not bind. */ static bool dcp_ext_is_failsafe(struct device_node *np) @@ -6791,7 +6811,8 @@ static bool dcp_ext_is_failsafe(struct device_node *np) return of_device_is_compatible(np, "apple,t8122-dcpext") || of_device_is_compatible(np, "apple,t6041-dcpext") || of_device_is_compatible(np, "apple,t6050-dcpext") || - of_device_is_compatible(np, "apple,t8142-dcpext"); + of_device_is_compatible(np, "apple,t8142-dcpext") || + apple_t8132_dcpext_v27_2(np); } /* @@ -7164,6 +7185,32 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) static int dcp_s2r_pm_register(struct apple_dcp *dcp); +/* + * T8132 (Mac mini, J773g) external processor on firmware 27.2, admitted by + * dcp_check_firmware_version(): what the T6041 dcpext gets on that firmware + * (see dcp_platform_probe_pipe()), whatever hw data the compatible matched. + * - firmware_dma_bits 41: its firmware DART's window (ADT dart-dcpext0 + * vm-base 1 TiB, vm-size-23 64 GiB; apple,dma-range <0x100 0 0x10 0>) + * ends at 1 TiB + 64 GiB, which takes 41 bits, as on T6041. + * - num_dptx_ports 2: the dcpdptx-port-epic units 0 and 1 every external + * processor of this generation has (T6041's, and T8132's own on the M4 + * path); the fixed HDMI port is unit 0. + * - adopt_live_session: iBoot leaves it running with the 27.2 image + * loaded (ADT pre-loaded = running = 1), as the boot loader hands it + * over; Linux never starts its CPU. + * - sink_metadata_edid: the display it finds at boot is its first sink, + * as on the T6041 dcpext. + * No sleep support: neither a firmware-27 sleep nor a link release has run + * on this processor. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { + .firmware_dma_bits = 41, + .num_dptx_ports = 2, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_V_27_0, + .sink_metadata_edid = true, +}; + static int dcp_platform_probe_pipe(struct platform_device *pdev) { const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); @@ -7364,6 +7411,9 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) /* Its ports where they have been opened so far, see dcp_v27_dptx_layout(). */ dcp->hw.dptx_endpoint = DPTX_ENDPOINT_V2; } + if (fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dev->of_node, "apple,t8132-dcpext")) + dcp->hw = apple_dcp_hw_t8132_dcpext_v27; /* * A SoC with derived power words is offered the stop only when asked for, and only on * firmware 27.0, whose calls are the ones that ran with them. @@ -10141,7 +10191,10 @@ static const struct of_device_id of_match[] = { { .compatible = "apple,t8142-dcp", .data = &apple_dcp_hw_t8142, }, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) { .compatible = "apple,t8132-dcp", .data = &apple_dcp_hw_t8132, }, - /* Same firmware as the internal DCP; adopted from the boot loader. */ + /* + * Same firmware as the internal DCP; adopted from the boot loader. The + * J773g's on 27.2 is a firmware-27 pipe (apple_dcp_hw_t8132_dcpext_v27). + */ { .compatible = "apple,t8132-dcpext", .data = &apple_dcp_hw_t8132_dcpext, }, #endif { .compatible = "apple,t6030-dcp", .data = &apple_dcp_hw_t6030, }, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index ad07edf47e594e..f4ff686713efc4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -199,8 +199,9 @@ def t6041_v27_admission(root): display_h = (root / 'include/linux/soc/apple/display.h').read_text() uuid_defines = [line for line in display_h.splitlines() if line.startswith(('#define APPLE_T6041_DCP_26B123_UUID ', - '#define APPLE_T8122_DCP_26B123_UUID '))] - assert len(uuid_defines) == 2 + '#define APPLE_T8122_DCP_26B123_UUID ', + '#define APPLE_T8132_DCP_26B123_UUID '))] + assert len(uuid_defines) == 3 helper = '\n'.join((*uuid_defines, *( block(display_h, 'static inline bool ' + name + '(') for name in ( 'apple_dcp_image_v27_2', @@ -217,6 +218,13 @@ def t6041_v27_admission(root): selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' + # The J773g's admission, with its machine check as a flag: no of_machine_is_compatible() + # exists in this translation unit, so the T6041 helpers cannot depend on the machine. + t8132_h = (root / 'include/linux/soc/apple/t8132.h').read_text() + t8132_admission = block(t8132_h, 'static inline bool apple_t8132_dcpext_v27_2(') + assert t8132_admission.count('of_machine_is_compatible("apple,j773g")') == 1 + t8132_admission = ('static bool machine_j773g;\n' + + t8132_admission.replace('of_machine_is_compatible("apple,j773g")', 'machine_j773g')) return r''' #include #include @@ -320,7 +328,7 @@ def t6041_v27_admission(root): snprintf(out, DCP_FW_VERSION_STR_LEN, "%u.%u.%u", v[0], v[1], v[2]); return 3; } -''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + method_table + '\n' + selector + r''' +''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + t8132_admission + '\n' + method_table + '\n' + selector + r''' static struct device_node node; static struct apple_dcp_hw_data hw_t6041; static struct device dev = { .of_node = &node, .hw = &hw_t6041 }; @@ -446,10 +454,49 @@ def t6041_v27_admission(root): assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); } + /* + * The Mac mini's (J773g) dcpext handed over with the T8132 27.2 image runs + * the 27.2 table; nothing else of T8132 does, whatever the firmware path. + */ + reset_t6041_26b123(true); + node.compatible = "apple,t8132-dcpext"; + node.uuid = APPLE_T8132_DCP_26B123_UUID; + assert(!apple_t6041_dcpext_v27_2(&node)); + for (unsigned path = 0; path < 2; path++) { + t8132_firmware_path = path; + machine_j773g = true; + assert(apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + /* Another M4 Mac (J713, J604): the M4 backend's, as before. */ + machine_j773g = false; + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == (path ? DCP_FIRMWARE_M4 : DCP_FIRMWARE_UNKNOWN)); + } + t8132_firmware_path = false; + machine_j773g = true; + /* The internal DCP is never admitted: macOS parks it; aura hands it to nobody. */ + node.compatible = "apple,t8132-dcp"; + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + /* The T6041 image, a missing or second UUID, and other releases are refused. */ + node.compatible = "apple,t8132-dcpext"; + node.uuid = APPLE_T6041_DCP_26B123_UUID; + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.uuid_count = 0; assert(!apple_t8132_dcpext_v27_2(&node)); + node.uuid_count = 2; assert(!apple_t8132_dcpext_v27_2(&node)); + node.uuid_count = 1; + node.compat[1] = 0; assert(!apple_t8132_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + node.compat[1] = 2; node.fw[2] = 1; assert(!apple_t8132_dcpext_v27_2(&node)); + node.fw[2] = 0; assert(apple_t8132_dcpext_v27_2(&node)); + machine_j773g = false; + dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); - puts("PASS T8132 M4 backend only on its firmware path"); + puts("PASS T8132 M4 backend only on its firmware path; the J773g dcpext on 27.2 alone runs the 27.2 table"); return 0; } ''' From 135817ee37e118151d10b4a16114c0edef2a8e4d Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:28:37 -0500 Subject: [PATCH 0224/1514] drm/apple: dcp: drive the J773g HDMI port from dcpext0 as the J575c does macOS 27.2 drives the Mac mini's HDMI port from DCPEXT0 alone (4K60 without DSC, 4K120 with DSC, FRL on the PS190 converter): the LPDPTX PHY with source select = dcpext0's dcp-index 1, the converter's rails on SMC GPIOs 15 (hdmi_pwr_en) and 26 (dp2hdmi_pwr_en), and no Type-C crossbar route. That is the M4 Max Mac Studio's (J575c) HDMI port: the same converter, rails and LPDPTX PHY ("dptx-phy,t8132" in both ADTs), which its T6041 dcpext0 drives on 27.2 as a desktop external processor. Make the J773g's firmware-27 dcpext a desktop external processor too (dcp->desktop_external, now the one test dcp_desktop_external() reads), so it takes the J575c's fixed-port path rather than porting the M4 backend's (dcp_t8132_fixed_hdmi on 26.6.2): - its fixed dp-phy is initialised and powered at probe (dcp_desktop_probe_routes()), and the converter rails get their 100 ms before the DCP asks for the link; - a direct crossbar link request takes the T6041 path, not the T6050 crossbar one (dcp_direct_crossbar_link()); with no crossbar or route described it has nothing to do. The HPD line, the rails, the PHY and the connector type come from the device tree, as on J575c. Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/dcp-fabric.c | 1 + drivers/gpu/drm/apple/dcp-internal.h | 6 +++++- drivers/gpu/drm/apple/dcp.c | 23 +++++++++++++++++++---- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 7ff72bfe6dddaf..791c24262f10fb 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -553,6 +553,7 @@ static int dcp_dpxbar_tunnel_select_source(struct mux_control *mux, int state) return ret; } +/* A desktop external processor on firmware 27: T6041's, or the J773g's T8132 one. */ static bool dcp_t6041_ext_v27(const struct apple_dcp *dcp) { return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->desktop_external; diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..2042e257f55251 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -568,7 +568,11 @@ struct apple_dcp { bool external; /* Any external processor (apple,dcpext), whatever its SoC; set at probe. */ bool dcpext; - /* A desktop 26.x external processor (apple,t6041-dcpext) */ + /* + * A desktop external processor: apple,t6041-dcpext (26.x or 27.2), or + * the J773g's apple,t8132-dcpext on 27.2 (apple_t8132_dcpext_v27_2()), + * which drives the HDMI port the same way. + */ bool desktop_external; /* * A failsafe dcpext (dcp_ext_is_failsafe(): T8122's, T6041's, T6050's): diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4378f6ad93ca72..f44e79ad326600 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -507,7 +507,21 @@ bool dcp_t6041_ext_enabled(void) static bool dcp_desktop_external(struct apple_dcp *dcp) { - return of_device_is_compatible(dcp->dev->of_node, "apple,t6041-dcpext"); + return dcp->desktop_external; +} + +/* + * The T6041 external processors, and the Mac mini's (J773g) T8132 ones on + * macOS 27.2: macOS drives the mini's HDMI port from dcpext0 alone, through + * the LPDPTX PHY (source select = dcp-index 1) and a PS190 DP-to-HDMI + * converter on the same SMC rails (gP0f, gP1a) as the M4 Max Mac Studio's + * (J575c), whose dcpext0 drives its HDMI port the same way. Its fixed PHY is + * powered at probe and its converter rails settle before the link, as there. + */ +static bool dcp_desktop_external_node(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t6041-dcpext") || + apple_t8132_dcpext_v27_2(np); } /* @@ -7117,8 +7131,9 @@ static void dcp_desktop_phy_off(void *data) } /* - * The fixed HDMI output of a desktop 26.x external processor (T6041 dcpext0): - * its DP PHY is powered here, as the boot loader's working sequence does. A + * The fixed HDMI output of a desktop external processor (T6041 dcpext0, and + * the J773g's T8132 dcpext0 on 27.2): its DP PHY is powered here, as the + * boot loader's working sequence does. A * Type-C output (dcpext1) has no fixed PHY; the display fabric powers the * PHY of the route a port claims (see dcp_typec_phy_on()). */ @@ -7332,7 +7347,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->ext_failsafe = dcp_ext_is_failsafe(dev->of_node); dcp->dcpext = of_device_is_compatible(dev->of_node, "apple,dcpext"); dcp->external = of_device_is_compatible(dev->of_node, "apple,t6030-dcpext"); - dcp->desktop_external = of_device_is_compatible(dev->of_node, "apple,t6041-dcpext"); + dcp->desktop_external = dcp_desktop_external_node(dev->of_node); dcp->external_native = dcp->external && dcp_t6030_ext_native(dev->of_node); /* * J714s: the internal panel's processor suspends and resumes asynchronously, not in From 79c27af9800edbb757c208e4244c870dd6a9d2c4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:28:53 -0500 Subject: [PATCH 0225/1514] dt-bindings: phy: apple,dptx-phy: add the T8132 LPDPTX PHY The Mac mini (J773g) drives its HDMI port through the T8132's own LPDPTX PHY (ADT /arm-io/dptx-phy, "dptx-phy,t8132", crossbar dfp-endpoint 4). The M4 Max Mac Studio's HDMI PHY is the same block ("dptx-phy,t8132" in its ADT too) and is described as the T6050 layout with the ADT's PLL calibration. Allow apple,t8132-dptx-phy with the same fallback, and the calibration's sixth value, RODCOROLEAKCOMP, which the driver reads (apple,pll-rodcoroleakcomp) and the mini's ADT sets (0), where the Studio's leaves it unset. Signed-off-by: Diljit Singh --- Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml b/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml index 5e48405d80a127..01dc9abadc887a 100644 --- a/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,dptx-phy.yaml @@ -24,6 +24,7 @@ select: - apple,t6041-dptx-phy - apple,t6050-dptx-phy - apple,t8122-dptx-phy + - apple,t8132-dptx-phy required: - compatible @@ -36,7 +37,9 @@ properties: - const: apple,dptx-phy - const: apple,t6050-dptx-phy - items: - - const: apple,t6041-dptx-phy + - enum: + - apple,t6041-dptx-phy + - apple,t8132-dptx-phy - const: apple,t6050-dptx-phy reg: @@ -63,7 +66,7 @@ properties: The display crossbar's upstream-facing endpoint that feeds this PHY. patternProperties: - '^apple,(pll-(dcocfg|dtcvreg|dtccal|dcdadj|dlfcfg)|pclkdrv-select)$': + '^apple,(pll-(dcocfg|dtcvreg|dtccal|dcdadj|dlfcfg|rodcoroleakcomp)|pclkdrv-select)$': $ref: /schemas/types.yaml#/definitions/uint32 description: PLL and pixel clock driver settings the PHY is programmed with, as the From e4d7957f27b485b2c216f2c94b8d6f95284a25fa Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:30:04 -0500 Subject: [PATCH 0226/1514] soc: apple: display-gate: enable the J773g HDMI chain on macOS 27.2 On macOS 27.2 the Mac mini (J773g) is off the M4 26.6.2 firmware path, so the display gate did nothing for it. aura hands it over as it hands over the M4 Max Mac Studio (J575c): dcpext0's (and dcpext1's) firmware memory and firmware clocks, the main DCP left running idle, and the display subsystem and its DART enabled on iBoot's boot framebuffer, with every dcpext node left disabled for this gate. Add a J773g gate that does what gate_t6041_max_run() does for the J575c's HDMI chain: once dcpext0 has its firmware memory, the display subsystem is enabled and the image is the pinned 27.2 one (apple_t8132_dcpext_v27_2()), enable the LPDPTX PHY, dcpext0's firmware and display DARTs, its mailbox, its PIODMA child and dcpext0 in one changeset. A chain that is not all there and disabled is left alone, as there. It runs only off the M4 firmware path; on 26.6.2 the J713 dcpext route handling runs instead, unchanged. One difference from the J575c: the display subsystem's iommus become dispext0's DART rather than having it appended. The main pipe's display DART (disp0) belongs to the running main DCP, which nothing hands over on this firmware and which apple-dart never probes there; left in the iommus it would hold the display subsystem's probe forever. The main DCP's own nodes are left as the device tree has them. Signed-off-by: Diljit Singh --- drivers/soc/apple/display-gate.c | 145 +++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 2830a17ae6cafc..e2dce8a89f54da 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -84,6 +84,13 @@ * display processor's firmware memory. The gate enables a chain once its * processor has that memory and the display subsystem is enabled, before any * device exists (see gate_t6041_max_run()). + * + * The M4 Mac mini (J773g, apple,t8132) on macOS 27.2 is handed over as the + * J575c is: aura fills dcpext0's and dcpext1's firmware memory, adds their + * firmware clocks, leaves the main DCP running idle and enables the display + * subsystem on iBoot's boot framebuffer. The gate enables the HDMI chain + * behind dcpext0 the same way (see gate_t8132_j773g_run()). On the M4 26.6.2 + * firmware path the J713 dcpext routes below apply instead. */ #define pr_fmt(fmt) fmt @@ -362,12 +369,28 @@ static const struct gate_soc gate_t6041_max __initconst = { .run = gate_t6041_max_run, }; +static void __init gate_t8132_j773g_run(void); + +/* + * T8132 Mac mini (J773g) off the M4 26.6.2 firmware path: no internal display + * handoff, only its HDMI chain, as on the J575c. + */ +static const struct gate_soc gate_t8132_j773g __initconst = { + .machine = "apple,j773g", + .prefix = "apple-t8132-display: ", + .name = "T8132", + .dcp_compat = "apple,t8132-dcp", + .display_compat = "apple,t8132-display-subsystem", + .run = gate_t8132_j773g_run, +}; + static const struct gate_soc *const gate_socs[] __initconst = { &gate_t6030, &gate_t8122, &gate_t6031, &gate_t6041, &gate_t6041_max, + &gate_t8132_j773g, }; /* The SoC this boot runs on, if the gate serves it. */ @@ -3398,6 +3421,128 @@ static void __init gate_j713_dcpext_routes(void) gate_cs_free(cs); } +/* + * The J773g's HDMI chain on macOS 27.2 (t8132-j773g.dts): the LPDPTX PHY, + * dcpext0's firmware and display DARTs, its mailbox, its PIODMA child, then + * dcpext0. As on the J575c no PMP runs and no DISPEXT0 power domain is + * described for them: iBoot leaves the pipe powered. No Type-C route: dcpext0 + * drives only the HDMI port here. + */ +static const char *const t8132_j773g_hdmi_nodes[] = { + "/soc/phy@39a700000", + "/soc/iommu@286340000", + "/soc/iommu@286300000", + "/soc/mailbox@286e08000", + "/soc/dcp@286e00000/piodma", + "/soc/dcp@286e00000", +}; + +static const struct gate_staged t8132_j773g_hdmi = { + "/soc/iommu@286300000", t8132_j773g_hdmi_nodes, ARRAY_SIZE(t8132_j773g_hdmi_nodes), +}; + +/* Applied, it stays: the live tree refers to it. */ +static struct of_changeset t8132_j773g_cs; + +/* The display subsystem's iommus become <@dart 0>, whatever they were. */ +static int __init gate_iommus_set(struct of_changeset *cs, struct device_node *display, + struct device_node *dart) +{ + struct property *prop; + __be32 *value; + + if (!dart->phandle) + return -EINVAL; + prop = kzalloc_obj(*prop); + value = kmalloc(2 * sizeof(*value), GFP_KERNEL); + if (!prop || !value) { + kfree(prop); + kfree(value); + return -ENOMEM; + } + value[0] = cpu_to_be32(dart->phandle); + value[1] = cpu_to_be32(0); + prop->name = "iommus"; + prop->length = 2 * sizeof(*value); + prop->value = value; + return of_changeset_update_property(cs, display, prop); +} + +/* + * The J773g on macOS 27.2: dcpext0 drives the HDMI port, as macOS does there, + * through the firmware-27 backend (apple_t8132_dcpext_v27_2()). Its chain is + * enabled in one changeset once aura has given dcpext0 its firmware memory and + * enabled the display subsystem, and only for the pinned 27.2 image. + * + * The display subsystem's iommus are set to dispext0's DART instead of having + * it appended, as on the J575c: the main pipe's display DART (disp0) belongs + * to the main DCP, which iBoot leaves running and nothing hands over on this + * firmware, and the DART driver never probes it there (apple-dart.c). Left in + * the iommus, it would hold the display subsystem's probe forever. The main + * DCP's own nodes are left as the device tree has them: its driver refuses it + * off the M4 firmware path (dcp_check_firmware_version()). + */ +static void __init gate_t8132_j773g_run(void) +{ + const struct gate_staged *st = &t8132_j773g_hdmi; + const char *dcp_path = st->nodes[st->nr - 1]; + struct device_node *display, *np; + bool approved; + unsigned int i; + int ret; + + if (IS_ENABLED(CONFIG_VIDEO) && video_firmware_drivers_only()) + return; + staged_prefix = gate_soc->prefix; + + np = of_find_node_by_path(dcp_path); + if (!np) + return; /* a tree without the external pipes */ + approved = apple_t8132_dcpext_v27_2(np); + if (!approved && of_property_present(np, "apple,firmware-compat")) + staged_info("%s: not the 27.2 (26B123) image, HDMI left off\n", dcp_path); + of_node_put(np); + if (!approved) + return; + + display = of_find_node_by_path("disp0"); + if (!display || !of_device_is_compatible(display, gate_soc->display_compat)) { + staged_err("no display subsystem, HDMI left off\n"); + of_node_put(display); + return; + } + if (!of_device_is_available(display)) { + staged_info("display subsystem not enabled, HDMI left off\n"); + of_node_put(display); + return; + } + if (!staged_ready(st)) { + of_node_put(display); + return; + } + + of_changeset_init(&t8132_j773g_cs); + np = of_find_node_by_path(st->dart); + ret = np ? gate_iommus_set(&t8132_j773g_cs, display, np) : -ENODEV; + of_node_put(np); + for (i = 0; !ret && i < st->nr; i++) { + np = of_find_node_by_path(st->nodes[i]); + ret = np ? of_changeset_update_prop_string(&t8132_j773g_cs, np, "status", "okay") : + -ENODEV; + of_node_put(np); + } + if (!ret) + ret = of_changeset_apply(&t8132_j773g_cs); + if (ret) { + of_changeset_destroy(&t8132_j773g_cs); + staged_err("%s: could not enable the HDMI chain: %d\n", dcp_path, ret); + } else { + staged_info("%s enabled for HDMI; display subsystem on %s only\n", dcp_path, + st->dart); + } + of_node_put(display); +} + /* Runs before of_platform_default_populate_init() at arch_initcall_sync. */ static int __init apple_display_gate(void) { From 9dd242c0e804ea743b4a2bf41df22fc39e6d33f4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 00:32:17 -0500 Subject: [PATCH 0227/1514] arm64: dts: apple: t8132-j773g: describe the HDMI port on dcpext0 for 27.2 On macOS 27.2 the Mac mini drives its HDMI port from DCPEXT0 alone, through the LPDPTX PHY (source select = dcpext0's dcp-index 1) and the PS190 DP-to-HDMI converter, whose rails are SMC GPIOs 15 and 26. It is the M4 Max Mac Studio's HDMI port, so describe it in the J575c's style (t6041-j575c-hdmi.dtsi), from the mini's 27.2 ADT: - dcpext0's firmware memory as three disabled apple,asc-mem placeholders named text, data and heap, for aura to fill; - the PHY (ADT /arm-io/dptx-phy, "dptx-phy,t8132", core and dptx banks at 0x39a700000/0x39a740000) in the T6050 layout with the ADT's PLL calibration, crossbar ufp-endpoint 0 (dispext0), disabled; - dcpext0 as an HDMI-A port: that PHY at crossbar output 4, hdmi_hpd on AOP GPIO 41, hdmi_pwr_en and dp2hdmi_pwr_en on SMC gP0f and gP1a; - no power domain on dcpext0, its mailbox and DARTs: no PMP runs off the M4 firmware path and iBoot leaves DISPEXT0 powered, as on the J575c (and as the 26.6.2 HDMI work found for this pipe). - DISPEXT0_FE always on: only the boot framebuffer holds it (and DISPEXT0_SYS through it), so once the display driver removes that, genpd would power the front end off under the running dcpext0. The T8132 PMGR driver leaves its auto-enable bits alone either way. Everything stays disabled: the display gate enables the chain on 27.2. The main DCP, its DARTs and the display subsystem are left as they were, so a 26.6.2 boot, whose main-DCP HDMI path enables them from the board tree, keeps them. On 26.6.2 the M4 PMGR policy still decides whether DISPEXT0_FE is Linux's at all; always-on only applies where it is and the policy does not give it to the firmware. Signed-off-by: Diljit Singh --- arch/arm64/boot/dts/apple/t8132-j773g.dts | 114 +++++++++++++++++++++- 1 file changed, 113 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j773g.dts b/arch/arm64/boot/dts/apple/t8132-j773g.dts index baf3e3ffcfecb9..3d0ffe608fb82e 100644 --- a/arch/arm64/boot/dts/apple/t8132-j773g.dts +++ b/arch/arm64/boot/dts/apple/t8132-j773g.dts @@ -4,7 +4,8 @@ * * target-type: J773g * - * Wired from the J773g ADT (macOS 26.6.2). + * Wired from the J773g ADT (macOS 26.6.2; the HDMI port on dcpext0 from the + * macOS 27.2 one). * * Copyright The Asahi Linux Contributors */ @@ -43,6 +44,117 @@ power-domains = <&ps_dispext0_fe>, <&ps_dptx_phy>; }; +/* + * The HDMI port as macOS 27.2 drives it: from dispext0 alone (4K60, and + * 4K120 with DSC; the main DCP started and then parked), through the LPDPTX + * PHY and the PS190 DP-to-HDMI converter. It is the M4 Max Mac Studio's HDMI + * port (t6041-j575c-hdmi.dtsi): the same PHY block, converter and rails, and + * it is handed over the same way, on the firmware-27 backend. + * + * Every node is disabled. On macOS 27.2 the boot loader (aura) fills + * dcpext0's firmware memory and firmware clocks, leaves the main DCP running + * idle, and enables the display subsystem on iBoot's framebuffer; the display + * gate (drivers/soc/apple/display-gate.c) then enables this chain and points + * the display subsystem at dispext0's DART. On the M4 26.6.2 firmware path + * none of it is enabled from here. + */ +/ { + reserved-memory { + /* Filled by the boot loader on macOS 27.2, as the J575c's. */ + dcpext0_text: dcpext0-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext0_data: dcpext0-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext0_heap: dcpext0-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; +}; + +&soc { + /* + * ADT /arm-io/dptx-phy (dptx-phy,t8132, as the J575c's lpdptx-phy0): + * the T6050 layout, a core bank and a dptx bank, and the ADT's PLL + * calibration (FD0FD1SWAP unset). The display crossbar's dfp-endpoint 4 + * (lpdptx); dispext0 is its ufp-endpoint 0, which the PHY's source + * select takes as 1, dcpext0's apple,dcp-index. + */ + lpdptx_phy: phy@39a700000 { + compatible = "apple,t8132-dptx-phy", "apple,t6050-dptx-phy"; + reg = <0x3 0x9a700000 0x0 0x4000>, + <0x3 0x9a740000 0x0 0x10000>; + reg-names = "core", "dptx"; + power-domains = <&ps_dptx_phy>; + #phy-cells = <0>; + #reset-cells = <0>; + apple,ufp-endpoint = <0>; + apple,pll-dcocfg = <0x4>; + apple,pll-dtcvreg = <0xf>; + apple,pll-dtccal = <0x2>; + apple,pll-dcdadj = <0x10>; + apple,pll-dlfcfg = <0x3>; + apple,pll-rodcoroleakcomp = <0x0>; + status = "disabled"; + }; +}; + +/* + * No PMP runs off the M4 firmware path, and iBoot leaves DISPEXT0 powered + * with its CPU domain under hardware control: as on the J575c, the pipe has + * no power domain here, and Linux never switches it. Its front end (and + * through it DISPEXT0_SYS) is held by the boot framebuffer only: keep it on + * once the display driver has taken over, or the domain would be powered off + * under the running processor. + */ +&ps_dispext0_fe { + apple,always-on; +}; + +&dcpext0_mbox { + /delete-property/ power-domains; +}; + +&dcpext0_dart { + /delete-property/ power-domains; +}; + +&dispext0_dart { + /delete-property/ power-domains; +}; + +/* + * ADT /arm-io/dp2hdmi-gpio0: hdmi_hpd on AOP GPIO 41, hdmi_pwr_en on SMC + * gP0f and dp2hdmi_pwr_en on SMC gP1a (the J575c's rails). No Type-C route: + * dcpext0 drives only this port. + */ +&dcpext0 { + /delete-property/ power-domains; + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "HDMI-A"; + hdmi-hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; + hdmi-pwren-gpios = <&smc_gpio 15 GPIO_ACTIVE_HIGH>; + dp2hdmi-pwren-gpios = <&smc_gpio 26 GPIO_ACTIVE_HIGH>; + phys = <&lpdptx_phy>; + phy-names = "dp-phy"; + /* the crossbar's output 4 (ADT dptx-phy dp-switch-dfp-endpoint) */ + apple,dptx-phy = <4>; + memory-region = <&dcpext0_text>, <&dcpext0_data>, <&dcpext0_heap>; + memory-region-names = "text", "data", "heap"; +}; + /* * Without this, the PMP firmware faults in the PMC block (0x382800000) * shortly after it starts on this board. J713 keeps ps_pmc out of Linux From 0b2f60befbfab87990e8fbaf48ce4b842eb0e122 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 19:28:26 -0500 Subject: [PATCH 0228/1514] soc: apple: t8132: admit a 27.2 dcpext by its processor and image, not its board apple_t8132_dcpext_v27_2() also required of_machine_is_compatible( "apple,j773g"). The firmware interface belongs to the coprocessor and the image it runs, and both are already checked: an apple,t8132-dcpext node with the T8132 27.2 (26B123) image UUID and firmware version and compatibility 27.2.0. What differs between T8132 boards (the J773g's fixed HDMI port, its LPDPTX PHY, converter rails and hot-plug line) is described in each board's device tree, and the driver takes it from there. RyanTheTide asked for this in the review of aurora-silicon/linux#2541. Drop the board check. The apple-dcp boot unit now asserts that the admission has no machine check and that a T8132 dcpext on the 27.2 image is admitted on either firmware path. Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/apple_drv.c | 4 ++-- include/linux/soc/apple/t8132.h | 14 +++++------ .../selftests/drivers/gpu/apple-dcp/boot.py | 23 +++++++------------ 3 files changed, 17 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index d791d22ec6d13d..de0dbb7a597651 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1480,7 +1480,7 @@ static const struct of_device_id apple_dcp_id_tbl[] = { #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) { .compatible = "apple,t8132-dcp" }, #endif - /* apple_dcp_usable(): only a J773g one on firmware 27.2. */ + /* apple_dcp_usable(): only one on firmware 27.2 (apple_t8132_dcpext_v27_2()). */ { .compatible = "apple,t8132-dcpext" }, {}, }; @@ -1509,7 +1509,7 @@ static bool apple_dcp_usable(struct device_node *np) apple_t8132_firmware_path()) && /* * A T8132 dcpext the M4 backend adopts is no component: its - * outputs are t8132_ext_drm.c's. The J773g's on 27.2 is a pipe. + * outputs are t8132_ext_drm.c's. One on the 27.2 image is a pipe. */ (!of_device_is_compatible(np, "apple,t8132-dcpext") || apple_t8132_dcpext_v27_2(np)); diff --git a/include/linux/soc/apple/t8132.h b/include/linux/soc/apple/t8132.h index 9a0607a7eb962e..72ece899b148a8 100644 --- a/include/linux/soc/apple/t8132.h +++ b/include/linux/soc/apple/t8132.h @@ -56,16 +56,16 @@ static inline bool apple_t8132_firmware_path(void) } /* - * A T8132 external display processor on the Mac mini (J773g) handed over - * with the 27.2 image: it runs the firmware-27 backend (iomfb_v27.c), not - * the M4 26.6.2 one (iomfb_m4.c). Other T8132 boards and images are not - * admitted until a trace of theirs says the same interface applies. Kept - * here, not in display.h, whose T6041 helpers key on the processor alone. + * A T8132 external display processor handed over with the 27.2 image + * (first on the Mac mini, J773g): it runs the firmware-27 backend + * (iomfb_v27.c), not the M4 26.6.2 one (iomfb_m4.c). The firmware + * interface belongs to the processor and the image it runs, so both are + * checked and the board is not; what differs between boards (the HDMI + * port, its PHY, rails and hot-plug line) comes from the device tree. */ static inline bool apple_t8132_dcpext_v27_2(const struct device_node *np) { - return of_machine_is_compatible("apple,j773g") && - apple_dcp_image_v27_2(np, "apple,t8132-dcpext", + return apple_dcp_image_v27_2(np, "apple,t8132-dcpext", APPLE_T8132_DCP_26B123_UUID); } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index f4ff686713efc4..543e5be169698d 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -218,13 +218,12 @@ def t6041_v27_admission(root): selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' - # The J773g's admission, with its machine check as a flag: no of_machine_is_compatible() - # exists in this translation unit, so the T6041 helpers cannot depend on the machine. + # The T8132 27.2 dcpext admission: by processor and image, never by board. No + # of_machine_is_compatible() exists in this translation unit, so neither it nor the T6041 + # helpers can depend on the machine. t8132_h = (root / 'include/linux/soc/apple/t8132.h').read_text() t8132_admission = block(t8132_h, 'static inline bool apple_t8132_dcpext_v27_2(') - assert t8132_admission.count('of_machine_is_compatible("apple,j773g")') == 1 - t8132_admission = ('static bool machine_j773g;\n' + - t8132_admission.replace('of_machine_is_compatible("apple,j773g")', 'machine_j773g')) + assert 'of_machine_is_compatible' not in t8132_admission return r''' #include #include @@ -455,8 +454,9 @@ def t6041_v27_admission(root): } /* - * The Mac mini's (J773g) dcpext handed over with the T8132 27.2 image runs - * the 27.2 table; nothing else of T8132 does, whatever the firmware path. + * A T8132 dcpext handed over with the T8132 27.2 image (first the Mac + * mini's, J773g) runs the 27.2 table, whatever the firmware path and on + * any board: the selection is by processor and image. */ reset_t6041_26b123(true); node.compatible = "apple,t8132-dcpext"; @@ -464,16 +464,10 @@ def t6041_v27_admission(root): assert(!apple_t6041_dcpext_v27_2(&node)); for (unsigned path = 0; path < 2; path++) { t8132_firmware_path = path; - machine_j773g = true; assert(apple_t8132_dcpext_v27_2(&node)); assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); - /* Another M4 Mac (J713, J604): the M4 backend's, as before. */ - machine_j773g = false; - assert(!apple_t8132_dcpext_v27_2(&node)); - assert(dcp_check_firmware_version(&dev) == (path ? DCP_FIRMWARE_M4 : DCP_FIRMWARE_UNKNOWN)); } t8132_firmware_path = false; - machine_j773g = true; /* The internal DCP is never admitted: macOS parks it; aura hands it to nobody. */ node.compatible = "apple,t8132-dcp"; assert(!apple_t8132_dcpext_v27_2(&node)); @@ -491,12 +485,11 @@ def t6041_v27_admission(root): assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.compat[1] = 2; node.fw[2] = 1; assert(!apple_t8132_dcpext_v27_2(&node)); node.fw[2] = 0; assert(apple_t8132_dcpext_v27_2(&node)); - machine_j773g = false; dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); - puts("PASS T8132 M4 backend only on its firmware path; the J773g dcpext on 27.2 alone runs the 27.2 table"); + puts("PASS T8132 M4 backend only on its firmware path; a T8132 dcpext on the 27.2 image runs the 27.2 table on any board"); return 0; } ''' From 7317d4c70cd1407721ca3fc8ece8cbd862e71666 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Fri, 20 Nov 2026 19:28:27 -0500 Subject: [PATCH 0229/1514] selftests: apple-dcp: readiness: stub the T8132 admission helpers apple_dcp_usable() calls apple_t8132_firmware_path() and apple_t8132_dcpext_v27_2() since this series, and the readiness unit extracts it without linux/soc/apple/t8132.h, so it no longer compiled. No scenario there has a T8132 node: stub both as unreachable, like the T6030 and T6041 helpers next to them. The patch is RyanTheTide's, from the review of aurora-silicon/linux#2541. Signed-off-by: Diljit Singh --- tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..02fdb3eff477f1 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1579,6 +1579,11 @@ def function(source, marker): /* Nor a T6041 dcpext. */ static bool __attribute__((unused)) dcp_t6041_ext_enabled(void) { assert(!"T6041 dcpext in a J700 scenario"); return false; } +/* Nor a T8132 processor of either backend. */ +static bool __attribute__((unused)) apple_t8132_firmware_path(void) +{ assert(!"T8132 DCP in a J700 scenario"); return false; } +static bool __attribute__((unused)) apple_t8132_dcpext_v27_2(const struct device_node *n) +{ (void)n; assert(!"T8132 dcpext in a J700 scenario"); return false; } static void __attribute__((unused)) iomfb_v14_7_external_refuse(struct apple_dcp *d, const char *why) { (void)d; (void)why; assert(!"T6030 external processor in a J700 scenario"); } struct drm_device { int unused; }; From bc0067c7a0a10a4603e0e72266686a6bf1df1527 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:40:40 -0500 Subject: [PATCH 0230/1514] soc: apple: display-gate: key T8132 fixed-DP chain on DT phandles Match gate_t8132 on the SoC ("apple,t8132") instead of "apple,j773g" and drop the hard-coded J773g node path table. The M4 Airs still route to gate_j713_dcpext_routes() before gate_socs[] is walked. In gate_t8132_run(), walk apple,t8132-dcpext nodes, select any that names a fixed "dp-phy" and passes apple_t8132_dcpext_v27_2(), and derive its chain from its DT phandles (phys, iommus, mboxes, piodma and piodma's iommus). When the main apple,t8132-dcp is handed over on 27.2 (26B123 image plus apple,clock-ids, e.g. a T8132 laptop with an internal panel), append the external display DART to disp0's iommus instead of replacing it; on a headless Mac mini where the main DCP is not handed over, replace iommus as before. Add tools/asahi/t8132-display-gate-tests.py (registered in tools/asahi/run-host-tests.py) covering phandle-derived chain resolution, replace-vs-append disp0 iommus behavior, and fail-closed controls. Signed-off-by: Diljit Singh --- drivers/soc/apple/display-gate.c | 335 ++++++++--- tools/asahi/run-host-tests.py | 1 + tools/asahi/t8132-display-gate-tests.py | 732 ++++++++++++++++++++++++ 3 files changed, 973 insertions(+), 95 deletions(-) create mode 100755 tools/asahi/t8132-display-gate-tests.py diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index e2dce8a89f54da..d6580c1c4b0eda 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -85,12 +85,14 @@ * processor has that memory and the display subsystem is enabled, before any * device exists (see gate_t6041_max_run()). * - * The M4 Mac mini (J773g, apple,t8132) on macOS 27.2 is handed over as the - * J575c is: aura fills dcpext0's and dcpext1's firmware memory, adds their - * firmware clocks, leaves the main DCP running idle and enables the display - * subsystem on iBoot's boot framebuffer. The gate enables the HDMI chain - * behind dcpext0 the same way (see gate_t8132_j773g_run()). On the M4 26.6.2 - * firmware path the J713 dcpext routes below apply instead. + * On T8132 (apple,t8132) off the M4 26.6.2 firmware path (first the Mac mini, + * J773g, on macOS 27.2), aura hands over external display processors as on the + * J575c: it fills their firmware memory, adds their firmware clocks, and + * enables the display subsystem on iBoot's boot framebuffer. For any + * apple,t8132-dcpext with a fixed dp-phy running the pinned 27.2 image, the + * gate derives the chain from its phandles and enables it in one changeset + * (see gate_t8132_run()). On the M4 26.6.2 firmware path (and on M4 Airs) the + * J713 dcpext routes below apply instead. */ #define pr_fmt(fmt) fmt @@ -369,19 +371,21 @@ static const struct gate_soc gate_t6041_max __initconst = { .run = gate_t6041_max_run, }; -static void __init gate_t8132_j773g_run(void); +static void __init gate_t8132_run(void); /* - * T8132 Mac mini (J773g) off the M4 26.6.2 firmware path: no internal display - * handoff, only its HDMI chain, as on the J575c. + * T8132 off the M4 26.6.2 firmware path (the Airs take + * gate_j713_dcpext_routes() before gate_socs[] is walked): enable any + * fixed-DP external display chain (phy-names = "dp-phy") running the pinned + * 27.2 image, as on the J575c. */ -static const struct gate_soc gate_t8132_j773g __initconst = { - .machine = "apple,j773g", +static const struct gate_soc gate_t8132 __initconst = { + .machine = "apple,t8132", .prefix = "apple-t8132-display: ", .name = "T8132", .dcp_compat = "apple,t8132-dcp", .display_compat = "apple,t8132-display-subsystem", - .run = gate_t8132_j773g_run, + .run = gate_t8132_run, }; static const struct gate_soc *const gate_socs[] __initconst = { @@ -390,7 +394,7 @@ static const struct gate_soc *const gate_socs[] __initconst = { &gate_t6031, &gate_t6041, &gate_t6041_max, - &gate_t8132_j773g, + &gate_t8132, }; /* The SoC this boot runs on, if the gate serves it. */ @@ -3421,29 +3425,6 @@ static void __init gate_j713_dcpext_routes(void) gate_cs_free(cs); } -/* - * The J773g's HDMI chain on macOS 27.2 (t8132-j773g.dts): the LPDPTX PHY, - * dcpext0's firmware and display DARTs, its mailbox, its PIODMA child, then - * dcpext0. As on the J575c no PMP runs and no DISPEXT0 power domain is - * described for them: iBoot leaves the pipe powered. No Type-C route: dcpext0 - * drives only the HDMI port here. - */ -static const char *const t8132_j773g_hdmi_nodes[] = { - "/soc/phy@39a700000", - "/soc/iommu@286340000", - "/soc/iommu@286300000", - "/soc/mailbox@286e08000", - "/soc/dcp@286e00000/piodma", - "/soc/dcp@286e00000", -}; - -static const struct gate_staged t8132_j773g_hdmi = { - "/soc/iommu@286300000", t8132_j773g_hdmi_nodes, ARRAY_SIZE(t8132_j773g_hdmi_nodes), -}; - -/* Applied, it stays: the live tree refers to it. */ -static struct of_changeset t8132_j773g_cs; - /* The display subsystem's iommus become <@dart 0>, whatever they were. */ static int __init gate_iommus_set(struct of_changeset *cs, struct device_node *display, struct device_node *dart) @@ -3468,77 +3449,241 @@ static int __init gate_iommus_set(struct of_changeset *cs, struct device_node *d return of_changeset_update_property(cs, display, prop); } +enum { + T8132_HDMI_PHY, + T8132_HDMI_FW_DART, + T8132_HDMI_DISP_DART, + T8132_HDMI_MBOX, + T8132_HDMI_PIODMA, + T8132_HDMI_DCP, + T8132_HDMI_NR, +}; + +/* + * Check that every memory-region of @np is an available apple,asc-mem node, + * as staged_firmware_memory() does for path-addressed stages. + */ +static bool __init staged_node_firmware_memory(struct device_node *np) +{ + struct device_node *chosen, *region; + int i, n; + u32 record[2]; + + n = of_count_phandle_with_args(np, "memory-region", NULL); + for (i = 0; i < n; i++) { + region = of_parse_phandle(np, "memory-region", i); + if (region && of_device_is_available(region) && + of_device_is_compatible(region, "apple,asc-mem")) { + of_node_put(region); + continue; + } + of_node_put(region); + n = -ENODEV; + break; + } + if (n > 0) + return true; + chosen = of_find_node_by_path("/chosen"); + if (chosen && !of_property_read_u32_array(chosen, "m4,dcpext", record, 2)) + staged_err("%pOF: no firmware memory (loader record <%u %u>), nothing enabled\n", + np, record[0], record[1]); + else + staged_err("%pOF: no firmware memory, nothing enabled\n", np); + of_node_put(chosen); + return false; +} + +/* + * A T8132 internal display processor handed over with the 27.2 (26B123) image + * and firmware-27 clock metadata (apple,clock-ids): present on a laptop with + * an internal panel (e.g. a 14-inch MacBook Pro), absent on a headless Mac + * mini whose main DCP is left running idle. + */ +static bool __init gate_t8132_dcp_v27_2(const struct device_node *np) +{ + return apple_dcp_image_v27_2(np, "apple,t8132-dcp", + APPLE_T8132_DCP_26B123_UUID) && + of_property_present(np, "apple,clock-ids"); +} + +static void __init gate_t8132_put_nodes(struct device_node *nodes[T8132_HDMI_NR]) +{ + unsigned int i; + + for (i = 0; i < T8132_HDMI_NR; i++) { + of_node_put(nodes[i]); + nodes[i] = NULL; + } +} + +/* + * Derive a fixed-DP T8132 dcpext's chain from its own DT phandles: the dp-phy + * PHY, firmware DART (iommus), display DART (piodma's iommus), mailbox + * (mboxes), piodma child, then the dcpext node itself. + */ +static int __init gate_t8132_resolve_fixed_dp(struct device_node *dcp, + int phy_idx, + struct device_node *nodes[T8132_HDMI_NR]) +{ + struct of_phandle_args args; + + memset(nodes, 0, T8132_HDMI_NR * sizeof(*nodes)); + + if (of_parse_phandle_with_args(dcp, "phys", "#phy-cells", phy_idx, &args)) + goto fail; + nodes[T8132_HDMI_PHY] = args.np; + + if (of_parse_phandle_with_args(dcp, "iommus", "#iommu-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_FW_DART] = args.np; + + if (of_parse_phandle_with_args(dcp, "mboxes", "#mbox-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_MBOX] = args.np; + + nodes[T8132_HDMI_PIODMA] = of_get_child_by_name(dcp, "piodma"); + if (!nodes[T8132_HDMI_PIODMA]) + goto fail; + + if (of_parse_phandle_with_args(nodes[T8132_HDMI_PIODMA], "iommus", + "#iommu-cells", 0, &args)) + goto fail; + nodes[T8132_HDMI_DISP_DART] = args.np; + + nodes[T8132_HDMI_DCP] = of_node_get(dcp); + return 0; + +fail: + gate_t8132_put_nodes(nodes); + return -EINVAL; +} + +/* Every node of @nodes is distinct and still disabled, and its processor has firmware memory. */ +static bool __init gate_t8132_fixed_dp_ready(struct device_node *nodes[T8132_HDMI_NR]) +{ + unsigned int i, j; + + if (!staged_node_firmware_memory(nodes[T8132_HDMI_DCP])) + return false; + for (i = 0; i < T8132_HDMI_NR; i++) { + if (!nodes[i]) + return false; + for (j = 0; j < i; j++) { + if (nodes[j] == nodes[i]) { + staged_err("%pOF: duplicate node in chain, nothing enabled\n", + nodes[i]); + return false; + } + } + if (of_device_is_available(nodes[i])) { + staged_err("%pOF: already enabled, nothing changed\n", nodes[i]); + return false; + } + } + return true; +} + /* - * The J773g on macOS 27.2: dcpext0 drives the HDMI port, as macOS does there, - * through the firmware-27 backend (apple_t8132_dcpext_v27_2()). Its chain is - * enabled in one changeset once aura has given dcpext0 its firmware memory and - * enabled the display subsystem, and only for the pinned 27.2 image. + * T8132 on macOS 27.2 (off the M4 26.6.2 firmware path): any apple,t8132-dcpext + * wired to a fixed DP PHY (phy-names = "dp-phy", e.g. the J773g HDMI port) + * runs through the firmware-27 backend (apple_t8132_dcpext_v27_2()). Its chain + * is derived from its DT phandles and enabled in one changeset once aura has + * given it firmware memory and enabled the display subsystem, and only for the + * pinned 27.2 image. * - * The display subsystem's iommus are set to dispext0's DART instead of having - * it appended, as on the J575c: the main pipe's display DART (disp0) belongs - * to the main DCP, which iBoot leaves running and nothing hands over on this - * firmware, and the DART driver never probes it there (apple-dart.c). Left in - * the iommus, it would hold the display subsystem's probe forever. The main - * DCP's own nodes are left as the device tree has them: its driver refuses it - * off the M4 firmware path (dcp_check_firmware_version()). + * When the main DCP is also handed over on 27.2 (a T8132 laptop with an + * internal panel), dispext's display DART is appended to the display + * subsystem's iommus so the internal panel keeps its DART. When the main DCP + * is not handed over (a headless Mac mini), disp0's DART is left unprobed by + * apple-dart and would hold the display subsystem's probe forever, so iommus + * is replaced with dispext's DART instead. */ -static void __init gate_t8132_j773g_run(void) +static void __init gate_t8132_run(void) { - const struct gate_staged *st = &t8132_j773g_hdmi; - const char *dcp_path = st->nodes[st->nr - 1]; - struct device_node *display, *np; - bool approved; + struct device_node *display = NULL, *internal, *dcp; + struct device_node *nodes[T8132_HDMI_NR]; + bool append_dart = false; + bool display_checked = false; unsigned int i; - int ret; + int phy_idx, ret; if (IS_ENABLED(CONFIG_VIDEO) && video_firmware_drivers_only()) return; staged_prefix = gate_soc->prefix; - np = of_find_node_by_path(dcp_path); - if (!np) - return; /* a tree without the external pipes */ - approved = apple_t8132_dcpext_v27_2(np); - if (!approved && of_property_present(np, "apple,firmware-compat")) - staged_info("%s: not the 27.2 (26B123) image, HDMI left off\n", dcp_path); - of_node_put(np); - if (!approved) - return; + for_each_compatible_node(dcp, NULL, "apple,t8132-dcpext") { + struct of_changeset *cs; - display = of_find_node_by_path("disp0"); - if (!display || !of_device_is_compatible(display, gate_soc->display_compat)) { - staged_err("no display subsystem, HDMI left off\n"); - of_node_put(display); - return; - } - if (!of_device_is_available(display)) { - staged_info("display subsystem not enabled, HDMI left off\n"); - of_node_put(display); - return; - } - if (!staged_ready(st)) { - of_node_put(display); - return; - } + phy_idx = of_property_match_string(dcp, "phy-names", "dp-phy"); + if (phy_idx < 0) + continue; - of_changeset_init(&t8132_j773g_cs); - np = of_find_node_by_path(st->dart); - ret = np ? gate_iommus_set(&t8132_j773g_cs, display, np) : -ENODEV; - of_node_put(np); - for (i = 0; !ret && i < st->nr; i++) { - np = of_find_node_by_path(st->nodes[i]); - ret = np ? of_changeset_update_prop_string(&t8132_j773g_cs, np, "status", "okay") : - -ENODEV; - of_node_put(np); - } - if (!ret) - ret = of_changeset_apply(&t8132_j773g_cs); - if (ret) { - of_changeset_destroy(&t8132_j773g_cs); - staged_err("%s: could not enable the HDMI chain: %d\n", dcp_path, ret); - } else { - staged_info("%s enabled for HDMI; display subsystem on %s only\n", dcp_path, - st->dart); + if (!apple_t8132_dcpext_v27_2(dcp)) { + if (of_property_present(dcp, "apple,firmware-compat")) + staged_info("%pOF: not the 27.2 (26B123) image, HDMI left off\n", + dcp); + continue; + } + + if (!display_checked) { + display_checked = true; + display = of_find_node_by_path("disp0"); + if (!display) + display = of_find_compatible_node(NULL, NULL, + gate_soc->display_compat); + if (!display || !of_device_is_compatible(display, + gate_soc->display_compat)) { + staged_err("no display subsystem, HDMI left off\n"); + of_node_put(display); + of_node_put(dcp); + return; + } + if (!of_device_is_available(display)) { + staged_info("display subsystem not enabled, HDMI left off\n"); + of_node_put(display); + of_node_put(dcp); + return; + } + internal = of_find_node_by_path("dcp"); + if (!internal) + internal = of_find_compatible_node(NULL, NULL, + gate_soc->dcp_compat); + append_dart = gate_t8132_dcp_v27_2(internal); + of_node_put(internal); + } + + if (gate_t8132_resolve_fixed_dp(dcp, phy_idx, nodes)) { + staged_err("%pOF: incomplete fixed-DP chain, HDMI left off\n", dcp); + continue; + } + if (!gate_t8132_fixed_dp_ready(nodes)) { + gate_t8132_put_nodes(nodes); + continue; + } + + cs = gate_cs_alloc(); + if (!cs) { + staged_err("%pOF: could not allocate changeset\n", dcp); + gate_t8132_put_nodes(nodes); + continue; + } + ret = append_dart ? + gate_iommus_append(cs, display, nodes[T8132_HDMI_DISP_DART]) : + gate_iommus_set(cs, display, nodes[T8132_HDMI_DISP_DART]); + for (i = 0; !ret && i < T8132_HDMI_NR; i++) + ret = of_changeset_update_prop_string(cs, nodes[i], "status", "okay"); + if (!ret) + ret = of_changeset_apply(cs); + if (ret) { + gate_cs_free(cs); + staged_err("%pOF: could not enable the HDMI chain: %d\n", dcp, ret); + } else { + staged_info("%pOF enabled for HDMI; display subsystem %s %pOF\n", dcp, + append_dart ? "appended" : "on", + nodes[T8132_HDMI_DISP_DART]); + append_dart = true; + } + gate_t8132_put_nodes(nodes); } of_node_put(display); } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 8ad9b94ac5b3cb..e07441a3af9062 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -303,6 +303,7 @@ def mutations(flag, names, base, expect=KILL): 't6040-calibration-tests.py': [([], PASS)], 't604x-cpu-order-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS)], 't6050-combo-join-tests.py': [([], PASS)], + 't8132-display-gate-tests.py': [([], PASS)], 't8132-usb4-policy-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS)], 'tb-cio-sleep-tests.py': [(out('--output'), PASS)], 'tb-dock-pm-tests.py': [(out('--output'), PASS)], diff --git a/tools/asahi/t8132-display-gate-tests.py b/tools/asahi/t8132-display-gate-tests.py new file mode 100755 index 00000000000000..9361b8a6008f50 --- /dev/null +++ b/tools/asahi/t8132-display-gate-tests.py @@ -0,0 +1,732 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host tests for the T8132 fixed-DP display gate (drivers/soc/apple/display-gate.c).""" +import os +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def extract_block(source, marker): + match = None + for cand in re.finditer(marker, source, re.M): + semi = source.find(';', cand.start()) + brace = source.find('{', cand.start()) + if brace >= 0 and (semi < 0 or brace < semi): + match = cand + break + assert match, f'missing marker: {marker}' + start = match.start() + brace = source.index('{', start) + depth = 1 + pos = brace + 1 + while depth: + depth += (source[pos] == '{') - (source[pos] == '}') + pos += 1 + if pos < len(source) and source[pos] == ';': + pos += 1 + return source[start:pos] + '\n' + + +def main(): + gate_src = (ROOT / 'drivers/soc/apple/display-gate.c').read_text() + disp_hdr = (ROOT / 'include/linux/soc/apple/display.h').read_text() + t8132_hdr = (ROOT / 'include/linux/soc/apple/t8132.h').read_text() + + # Enforce at source level that T8132 fixed-DP gate matches the SoC, not a board name, + # and carries no hard-coded board node paths. + soc_block = extract_block(gate_src, r'^static const struct gate_soc gate_t8132\b') + assert '.machine = "apple,t8132"' in soc_block, soc_block + assert 'j773g' not in soc_block, soc_block + assert 't8132_j773g_hdmi_nodes' not in gate_src + + uuid_lines = '\n'.join( + line for line in disp_hdr.splitlines() + if line.startswith('#define APPLE_T8132_DCP_26B123_UUID') + ) + helpers = '\n'.join([ + uuid_lines, + extract_block(disp_hdr, r'^static inline bool apple_dcp_image_v27_2\('), + extract_block(t8132_hdr, r'^static inline bool apple_t8132_dcpext_v27_2\('), + extract_block(gate_src, r'^static int gate_iommus_append\('), + extract_block(gate_src, r'^static struct of_changeset \*__init gate_cs_alloc\('), + extract_block(gate_src, r'^static void __init gate_cs_free\('), + extract_block(gate_src, r'^static int __init gate_iommus_set\('), + extract_block(gate_src, r'^enum \{\n\tT8132_HDMI_PHY,'), + extract_block(gate_src, r'^static bool __init staged_node_firmware_memory\('), + extract_block(gate_src, r'^static bool __init gate_t8132_dcp_v27_2\('), + extract_block(gate_src, r'^static void __init gate_t8132_put_nodes\('), + extract_block(gate_src, r'^static int __init gate_t8132_resolve_fixed_dp\('), + extract_block(gate_src, r'^static bool __init gate_t8132_fixed_dp_ready\('), + extract_block(gate_src, r'^static void __init gate_t8132_run\('), + ]) + + program = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint32_t u32; +typedef uint32_t __be32; +#define __init +#define __initconst +#define GFP_KERNEL 0 +#define CONFIG_VIDEO 1 +#define IS_ENABLED(x) (x) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define kzalloc_obj(x) calloc(1, sizeof(x)) +#define kmalloc(n, g) malloc(n) +#define kfree(p) free(p) + +static __be32 cpu_to_be32(u32 v) { return __builtin_bswap32(v); } +static u32 be32_to_cpu(__be32 v) { return __builtin_bswap32(v); } + +struct gate_soc { + const char *machine; + const char *prefix; + const char *name; + const char *dcp_compat; + const char *display_compat; +}; + +static const struct gate_soc test_soc = { + .machine = "apple,t8132", + .prefix = "apple-t8132-display: ", + .name = "T8132", + .dcp_compat = "apple,t8132-dcp", + .display_compat = "apple,t8132-display-subsystem", +}; +static const struct gate_soc *gate_soc = &test_soc; +static const char *staged_prefix; +static bool nomodeset; +static unsigned int err_count, info_count; + +#define staged_info(...) do { (void)staged_prefix; info_count++; } while (0) +#define staged_err(...) do { (void)staged_prefix; err_count++; } while (0) + +static bool video_firmware_drivers_only(void) { return nomodeset; } + +struct property { + const char *name; + void *value; + size_t length; +}; + +struct device_node { + const char *path; + const char *alias; + const char *name; + const char *compatible; + u32 phandle; + bool available; + int refcount; + + /* Firmware identity */ + const char *fw_uuid; + int fw_uuid_count; + u32 fw_ver[3]; + int fw_ver_cells; + u32 fw_compat[3]; + int fw_compat_cells; + bool has_clock_ids; + + /* Phandle references */ + const char *phy_names[4]; + int phy_name_count; + struct device_node *phys[4]; + + struct device_node *iommus[4]; + u32 iommu_args[4]; + int iommu_count; + struct property iommus_prop; + __be32 iommus_buf[8]; + + struct device_node *mboxes[2]; + int mbox_count; + + struct device_node *mem_regions[4]; + int mem_region_count; + + struct device_node *piodma_child; +}; + +struct of_phandle_args { + struct device_node *np; + int args_count; + u32 args[4]; +}; + +struct cs_op { + struct device_node *np; + bool is_status; + const char *status; + struct property *prop; +}; + +struct of_changeset { + struct cs_op ops[16]; + unsigned int nops; + bool applied; +}; + +#define MAX_NODES 32 +static struct device_node *all_nodes[MAX_NODES]; +static unsigned int nr_nodes; +static struct of_changeset *applied_cs[8]; +static unsigned int nr_applied_cs; + +static void sync_iommus_prop(struct device_node *np) +{ + int i; + + if (np->iommu_count <= 0) { + np->iommus_prop.name = NULL; + np->iommus_prop.value = NULL; + np->iommus_prop.length = 0; + return; + } + for (i = 0; i < np->iommu_count; i++) { + np->iommus_buf[2 * i] = cpu_to_be32(np->iommus[i]->phandle); + np->iommus_buf[2 * i + 1] = cpu_to_be32(np->iommu_args[i]); + } + np->iommus_prop.name = "iommus"; + np->iommus_prop.value = np->iommus_buf; + np->iommus_prop.length = (size_t)np->iommu_count * 2 * sizeof(__be32); +} + +static struct device_node *of_node_get(struct device_node *np) +{ + if (np) + np->refcount++; + return np; +} + +static void of_node_put(struct device_node *np) +{ + if (np) { + assert(np->refcount > 0); + np->refcount--; + } +} + +static bool of_device_is_compatible(const struct device_node *np, const char *compat) +{ + return np && np->compatible && !strcmp(np->compatible, compat); +} + +static bool of_device_is_available(const struct device_node *np) +{ + return np && np->available; +} + +static bool of_property_present(const struct device_node *np, const char *name) +{ + if (!np) + return false; + if (!strcmp(name, "apple,firmware-compat")) + return np->fw_compat_cells > 0; + if (!strcmp(name, "apple,clock-ids")) + return np->has_clock_ids; + return false; +} + +static int of_property_count_strings(const struct device_node *np, const char *name) +{ + assert(!strcmp(name, "apple,firmware-uuid")); + return np ? np->fw_uuid_count : -EINVAL; +} + +static int of_property_read_string(const struct device_node *np, const char *name, const char **out) +{ + assert(!strcmp(name, "apple,firmware-uuid")); + if (!np || np->fw_uuid_count < 1 || !np->fw_uuid) + return -EINVAL; + *out = np->fw_uuid; + return 0; +} + +static int of_property_count_u32_elems(const struct device_node *np, const char *name) +{ + if (!np) + return -EINVAL; + if (!strcmp(name, "apple,firmware-version")) + return np->fw_ver_cells; + if (!strcmp(name, "apple,firmware-compat")) + return np->fw_compat_cells; + return -EINVAL; +} + +static int of_property_read_u32_array(const struct device_node *np, const char *name, + u32 *out, size_t n) +{ + if (!np) + return -EINVAL; + if (!strcmp(name, "apple,firmware-version") && n == 3 && np->fw_ver_cells == 3) { + memcpy(out, np->fw_ver, 3 * sizeof(u32)); + return 0; + } + if (!strcmp(name, "apple,firmware-compat") && n == 3 && np->fw_compat_cells == 3) { + memcpy(out, np->fw_compat, 3 * sizeof(u32)); + return 0; + } + return -ENOENT; +} + +static int of_property_match_string(const struct device_node *np, const char *prop, const char *val) +{ + int i; + + assert(!strcmp(prop, "phy-names")); + if (!np) + return -EINVAL; + for (i = 0; i < np->phy_name_count; i++) { + if (np->phy_names[i] && !strcmp(np->phy_names[i], val)) + return i; + } + return -ENODATA; +} + +static struct property *of_find_property(struct device_node *np, const char *name, int *lenp) +{ + assert(!strcmp(name, "iommus")); + if (!np || !np->iommus_prop.name) + return NULL; + if (lenp) + *lenp = (int)np->iommus_prop.length; + return &np->iommus_prop; +} + +static int of_count_phandle_with_args(const struct device_node *np, const char *list, + const char *cells) +{ + (void)cells; + if (!np) + return -EINVAL; + if (!strcmp(list, "memory-region")) + return np->mem_region_count; + if (!strcmp(list, "iommus")) + return np->iommu_count; + return -EINVAL; +} + +static struct device_node *of_parse_phandle(const struct device_node *np, const char *name, int idx) +{ + assert(!strcmp(name, "memory-region")); + if (!np || idx < 0 || idx >= np->mem_region_count || !np->mem_regions[idx]) + return NULL; + return of_node_get(np->mem_regions[idx]); +} + +static int of_parse_phandle_with_args(const struct device_node *np, const char *list, + const char *cells, int idx, struct of_phandle_args *out) +{ + (void)cells; + if (!np || idx < 0) + return -EINVAL; + if (!strcmp(list, "phys")) { + if (idx >= np->phy_name_count || !np->phys[idx]) + return -ENOENT; + out->np = of_node_get(np->phys[idx]); + out->args_count = 0; + return 0; + } + if (!strcmp(list, "iommus")) { + if (idx >= np->iommu_count || !np->iommus[idx]) + return -ENOENT; + out->np = of_node_get(np->iommus[idx]); + out->args_count = 1; + out->args[0] = np->iommu_args[idx]; + return 0; + } + if (!strcmp(list, "mboxes")) { + if (idx >= np->mbox_count || !np->mboxes[idx]) + return -ENOENT; + out->np = of_node_get(np->mboxes[idx]); + out->args_count = 0; + return 0; + } + return -EINVAL; +} + +static struct device_node *of_get_child_by_name(const struct device_node *np, const char *name) +{ + assert(!strcmp(name, "piodma")); + return (np && np->piodma_child) ? of_node_get(np->piodma_child) : NULL; +} + +static struct device_node *of_find_node_by_path(const char *path) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) { + if ((all_nodes[i]->path && !strcmp(all_nodes[i]->path, path)) || + (all_nodes[i]->alias && !strcmp(all_nodes[i]->alias, path))) + return of_node_get(all_nodes[i]); + } + return NULL; +} + +static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, const char *compat) +{ + unsigned int i = 0; + + (void)type; + if (from) { + while (i < nr_nodes && all_nodes[i] != from) + i++; + if (i < nr_nodes) + i++; + of_node_put(from); + } + for (; i < nr_nodes; i++) { + if (of_device_is_compatible(all_nodes[i], compat)) + return of_node_get(all_nodes[i]); + } + return NULL; +} + +#define for_each_compatible_node(dn, type, compatible) \ + for (dn = of_find_compatible_node(NULL, type, compatible); dn; \ + dn = of_find_compatible_node(dn, type, compatible)) + +static struct device_node *find_by_phandle(u32 phandle) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) { + if (all_nodes[i]->phandle == phandle) + return all_nodes[i]; + } + return NULL; +} + +static void of_changeset_init(struct of_changeset *cs) +{ + memset(cs, 0, sizeof(*cs)); +} + +static void of_changeset_destroy(struct of_changeset *cs) +{ + unsigned int i; + + for (i = 0; i < cs->nops; i++) { + if (!cs->ops[i].is_status && cs->ops[i].prop) { + free(cs->ops[i].prop->value); + free(cs->ops[i].prop); + } + } + cs->nops = 0; +} + +static int of_changeset_update_property(struct of_changeset *cs, struct device_node *np, + struct property *prop) +{ + assert(cs->nops < ARRAY_SIZE(cs->ops)); + cs->ops[cs->nops++] = (struct cs_op){ .np = np, .is_status = false, .prop = prop }; + return 0; +} + +static int of_changeset_update_prop_string(struct of_changeset *cs, struct device_node *np, + const char *name, const char *val) +{ + assert(!strcmp(name, "status")); + assert(cs->nops < ARRAY_SIZE(cs->ops)); + cs->ops[cs->nops++] = (struct cs_op){ .np = np, .is_status = true, .status = val }; + return 0; +} + +static int of_changeset_apply(struct of_changeset *cs) +{ + unsigned int i; + + for (i = 0; i < cs->nops; i++) { + struct cs_op *op = &cs->ops[i]; + + if (op->is_status) { + op->np->available = !strcmp(op->status, "okay"); + } else { + const __be32 *vals = op->prop->value; + int n = (int)(op->prop->length / (2 * sizeof(__be32))); + int j; + + assert(!strcmp(op->prop->name, "iommus")); + assert(n >= 1 && n <= 4); + op->np->iommu_count = n; + for (j = 0; j < n; j++) { + op->np->iommus[j] = find_by_phandle(be32_to_cpu(vals[2 * j])); + assert(op->np->iommus[j]); + op->np->iommu_args[j] = be32_to_cpu(vals[2 * j + 1]); + } + sync_iommus_prop(op->np); + } + } + cs->applied = true; + assert(nr_applied_cs < ARRAY_SIZE(applied_cs)); + applied_cs[nr_applied_cs++] = cs; + return 0; +} +''' + helpers + r''' +struct fixture { + struct device_node display, disp0_dart, main_dcp; + struct device_node phy, fw_dart, disp_dart, mbox, piodma, dcpext0; + struct device_node mem_text, mem_data, mem_heap; + struct device_node dcpext1; +}; + +static void register_node(struct device_node *np) +{ + assert(nr_nodes < MAX_NODES); + all_nodes[nr_nodes++] = np; +} + +static void cleanup_applied(void) +{ + unsigned int i; + + for (i = 0; i < nr_applied_cs; i++) { + of_changeset_destroy(applied_cs[i]); + free(applied_cs[i]); + } + nr_applied_cs = 0; +} + +static void check_refs_zero(void) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + assert(all_nodes[i]->refcount == 0); +} + +static void set_v27_2(struct device_node *np) +{ + np->fw_uuid = APPLE_T8132_DCP_26B123_UUID; + np->fw_uuid_count = 1; + np->fw_ver[0] = 27; np->fw_ver[1] = 2; np->fw_ver[2] = 0; + np->fw_ver_cells = 3; + np->fw_compat[0] = 27; np->fw_compat[1] = 2; np->fw_compat[2] = 0; + np->fw_compat_cells = 3; +} + +static void init_fixture(struct fixture *f) +{ + cleanup_applied(); + memset(f, 0, sizeof(*f)); + nr_nodes = 0; + nomodeset = false; + err_count = info_count = 0; + + /* Deliberately use non-J773g paths to prove resolution is phandle-driven. */ + f->disp0_dart = (struct device_node){ + .path = "/soc/iommu@111100000", .phandle = 10, .available = false, + }; + f->display = (struct device_node){ + .path = "/soc/display-subsystem", .alias = "disp0", + .compatible = "apple,t8132-display-subsystem", + .phandle = 11, .available = true, + .iommus = { &f->disp0_dart }, .iommu_args = { 0 }, .iommu_count = 1, + }; + sync_iommus_prop(&f->display); + + f->main_dcp = (struct device_node){ + .path = "/soc/dcp@111e00000", .alias = "dcp", + .compatible = "apple,t8132-dcp", .phandle = 12, .available = false, + }; + + f->phy = (struct device_node){ + .path = "/soc/phy@999700000", .phandle = 20, .available = false, + }; + f->fw_dart = (struct device_node){ + .path = "/soc/iommu@999340000", .phandle = 21, .available = false, + }; + f->disp_dart = (struct device_node){ + .path = "/soc/iommu@999300000", .phandle = 22, .available = false, + }; + f->mbox = (struct device_node){ + .path = "/soc/mailbox@999e08000", .phandle = 23, .available = false, + }; + f->piodma = (struct device_node){ + .path = "/soc/dcp@999e00000/piodma", .name = "piodma", + .phandle = 24, .available = false, + .iommus = { &f->disp_dart }, .iommu_args = { 16 }, .iommu_count = 1, + }; + sync_iommus_prop(&f->piodma); + + f->mem_text = (struct device_node){ + .path = "/reserved-memory/text", .compatible = "apple,asc-mem", .available = true, + }; + f->mem_data = (struct device_node){ + .path = "/reserved-memory/data", .compatible = "apple,asc-mem", .available = true, + }; + f->mem_heap = (struct device_node){ + .path = "/reserved-memory/heap", .compatible = "apple,asc-mem", .available = true, + }; + + f->dcpext0 = (struct device_node){ + .path = "/soc/dcp@999e00000", .compatible = "apple,t8132-dcpext", + .phandle = 25, .available = false, + .phy_names = { "dp-phy" }, .phy_name_count = 1, .phys = { &f->phy }, + .iommus = { &f->fw_dart }, .iommu_args = { 23 }, .iommu_count = 1, + .mboxes = { &f->mbox }, .mbox_count = 1, + .mem_regions = { &f->mem_text, &f->mem_data, &f->mem_heap }, + .mem_region_count = 3, + .piodma_child = &f->piodma, + }; + sync_iommus_prop(&f->dcpext0); + set_v27_2(&f->dcpext0); + + /* Second dcpext without dp-phy (Type-C only): must stay untouched. */ + f->dcpext1 = (struct device_node){ + .path = "/soc/dcp@888e00000", .compatible = "apple,t8132-dcpext", + .phandle = 30, .available = false, + .phy_names = { "typec0" }, .phy_name_count = 1, .phys = { &f->phy }, + }; + set_v27_2(&f->dcpext1); + + register_node(&f->disp0_dart); + register_node(&f->display); + register_node(&f->main_dcp); + register_node(&f->phy); + register_node(&f->fw_dart); + register_node(&f->disp_dart); + register_node(&f->mbox); + register_node(&f->piodma); + register_node(&f->mem_text); + register_node(&f->mem_data); + register_node(&f->mem_heap); + register_node(&f->dcpext0); + register_node(&f->dcpext1); +} + +static void expect_chain(struct fixture *f, bool enabled) +{ + assert(f->phy.available == enabled); + assert(f->fw_dart.available == enabled); + assert(f->disp_dart.available == enabled); + assert(f->mbox.available == enabled); + assert(f->piodma.available == enabled); + assert(f->dcpext0.available == enabled); + assert(!f->dcpext1.available); +} + +int main(void) +{ + struct fixture f; + + /* 1. Headless T8132 (J773g-like): phandle-derived chain enabled; disp0 iommus replaced. */ + init_fixture(&f); + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 1); + assert(f.display.iommus[0] == &f.disp_dart && f.display.iommu_args[0] == 0); + check_refs_zero(); + + /* 2. Laptop T8132 (14" MBP-like): main DCP handed over on 27.2 -> disp0 iommus appended. */ + init_fixture(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = true; + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 2); + assert(f.display.iommus[0] == &f.disp0_dart && f.display.iommu_args[0] == 0); + assert(f.display.iommus[1] == &f.disp_dart && f.display.iommu_args[1] == 0); + check_refs_zero(); + + /* 3. Main DCP with 27.2 image but no apple,clock-ids (idle) -> replaced, not appended. */ + init_fixture(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = false; + gate_t8132_run(); + expect_chain(&f, true); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp_dart); + check_refs_zero(); + + /* 4. Unapproved firmware UUID on dcpext0 -> chain stays disabled, disp0 unchanged. */ + init_fixture(&f); + f.dcpext0.fw_uuid = "00000000-0000-0000-0000-000000000000"; + gate_t8132_run(); + expect_chain(&f, false); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* 5. Placeholder (disabled) memory-region -> refused whole. */ + init_fixture(&f); + f.mem_heap.available = false; + gate_t8132_run(); + expect_chain(&f, false); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* 6. Missing phandle (e.g. no piodma child) -> refused whole. */ + init_fixture(&f); + f.dcpext0.piodma_child = NULL; + gate_t8132_run(); + expect_chain(&f, false); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* 7. Any chain node already enabled -> refused whole, DART not modified. */ + init_fixture(&f); + f.phy.available = true; + gate_t8132_run(); + assert(f.phy.available); + assert(!f.fw_dart.available && !f.disp_dart.available && !f.mbox.available && + !f.piodma.available && !f.dcpext0.available); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* 8. Disabled display subsystem -> chain stays disabled. */ + init_fixture(&f); + f.display.available = false; + gate_t8132_run(); + expect_chain(&f, false); + assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + check_refs_zero(); + + /* 9. Tree with no fixed dp-phy on any dcpext -> quiet no-op. */ + init_fixture(&f); + f.dcpext0.phy_names[0] = "typec1"; + gate_t8132_run(); + expect_chain(&f, false); + assert(err_count == 0 && info_count == 0); + check_refs_zero(); + + /* 10. nomodeset -> no-op. */ + init_fixture(&f); + nomodeset = true; + gate_t8132_run(); + expect_chain(&f, false); + check_refs_zero(); + + cleanup_applied(); + puts("PASS T8132 fixed-DP display gate: phandle chain, replace vs append disp0 iommus, fail-closed controls"); + return 0; +} +''' + + with tempfile.TemporaryDirectory(prefix='t8132-display-gate-') as tmp: + src = Path(tmp) / 'test.c' + exe = Path(tmp) / 'test' + src.write_text(program) + subprocess.run( + [os.environ.get('CC', 'clang'), '-std=gnu11', '-Wall', '-Wextra', '-Werror', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], + check=True, + ) + subprocess.run( + [str(exe)], + check=True, + env={**os.environ, 'ASAN_OPTIONS': 'detect_leaks=0'}, + ) + + +if __name__ == '__main__': + main() From 025e7ea2df1b068fc18ae0bf48f87eb3b2867ad5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 23:57:15 -0500 Subject: [PATCH 0231/1514] phy: apple: atc: serve a T8132 device role on USB2 On a T8132 port whose SuperSpeed banks are calibrated, a USB device role previously failed in atcphy_usb3_set_mode() with -EOPNOTSUPP, causing dwc3-apple to fail setup and the Type-C port controller to give up after cable revalidation retries. SuperSpeed device mode is not supported by this driver on T8132, so serve a T8132 device role on USB2 instead: - Map APPLE_ATCPHY_MODE_USB3 and pin-D APPLE_ATCPHY_MODE_USB3_DP to APPLE_ATCPHY_MODE_USB2 while the device role is active, keeping four-lane APPLE_ATCPHY_MODE_DP (pin C/E, where USB2 uses its own wires) unchanged. - Set t8132_device only after atcphy_mux_switch() and atcphy_usb3_route() succeed, and clear it on controller role exit (atcphy_usb3_power_off() or PHY_MODE_USB_HOST) rather than on mux SAFE/OFF transitions. - Preserve the partner's un-downgraded mode in typec_mode so a direct device-to-host data role swap restores SuperSpeed lanes before host_active blocks T8132 lane reconfiguration, and subsequent atcphy_usb2_init() calls respect t8132_device. - Update the KUnit test and host selftest fixtures in the same commit so host test builds remain bisectable. Signed-off-by: Diljit Singh --- drivers/phy/apple/atc-test.c | 44 +++++++ drivers/phy/apple/atc.c | 91 +++++++++++-- tools/asahi/atc-usb3-tests.py | 124 ++++++++++++++++-- .../selftests/drivers/gpu/apple-dcp/common.py | 23 +++- .../drivers/gpu/apple-dcp/dwc3/mocks.c | 4 +- .../drivers/gpu/apple-dcp/dwc3/prefix.c | 1 + .../drivers/gpu/apple-dcp/lifecycle.py | 10 +- .../selftests/drivers/gpu/apple-dcp/phy.py | 31 ++++- .../drivers/gpu/apple-dcp/quiesce.py | 2 +- 9 files changed, 297 insertions(+), 33 deletions(-) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 09eec7f9d6185f..31c75d6a596027 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -104,6 +104,49 @@ static void atcphy_test_target_mode_t8132(struct kunit *test) KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_OFF); } +/* + * SuperSpeed device mode is not supported by this driver on T8132: a device + * role keeps the lanes on USB2 while preserving the partner's requested mode. + */ +static void atcphy_test_t8132_device_role_usb2(struct kunit *test) +{ + struct typec_altmode dp = { .svid = USB_TYPEC_DP_SID }; + struct typec_mux_state state = { .mode = TYPEC_STATE_USB }; + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + + atcphy->hw = &atcphy_hw_t8132; + atcphy->t8132_ss = true; + atcphy->ss_tunables = true; + atcphy->t8132_dp_alt = true; + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_DP), + APPLE_ATCPHY_MODE_DP); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB2), + APPLE_ATCPHY_MODE_USB2); + KUNIT_EXPECT_EQ(test, atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_OFF), + APPLE_ATCPHY_MODE_OFF); + + /* Target mode preserves the partner's request so a host swap can restore SuperSpeed. */ + atcphy->t8132_device = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB3); + atcphy->mode = APPLE_ATCPHY_MODE_USB2; + KUNIT_EXPECT_TRUE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3)); + KUNIT_EXPECT_TRUE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3_DP)); + KUNIT_EXPECT_FALSE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_OFF)); + atcphy->t8132_device = false; + KUNIT_EXPECT_FALSE(test, atcphy_mux_in_mode(atcphy, APPLE_ATCPHY_MODE_USB3)); + + state.alt = &dp; + state.mode = TYPEC_DP_STATE_C; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_DP); + state.alt = NULL; + state.mode = TYPEC_STATE_SAFE; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_OFF); +} + static void atcphy_test_noop_same_mode(struct kunit *test) { struct apple_atcphy *atcphy = atcphy_test_alloc(test, true); @@ -1391,6 +1434,7 @@ static struct kunit_case atcphy_mux_test_cases[] = { KUNIT_CASE(atcphy_test_target_mode), KUNIT_CASE(atcphy_test_target_mode_fixed_hub), KUNIT_CASE(atcphy_test_target_mode_t8132), + KUNIT_CASE(atcphy_test_t8132_device_role_usb2), KUNIT_CASE(atcphy_test_noop_same_mode), KUNIT_CASE(atcphy_test_noop_needs_work), KUNIT_CASE(atcphy_test_usb3_port_ready), diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..b5dd9c167ee28c 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -881,6 +881,13 @@ struct apple_atcphy { const struct atcphy_hw *hw; /* T8132 keeps USB2 support when its optional SuperSpeed banks are absent. */ bool t8132_ss; + /* + * SuperSpeed device mode is not supported by this driver on T8132: + * while the controller holds the device role, the lanes run USB2 + * instead of a partner's SuperSpeed mode. Cleared when the USB3 PHY + * powers off or the controller switches to host mode. + */ + bool t8132_device; /* Only this driver's admitted common-power epoch may be stopped. */ bool t8132_common_owned; /* A touched failure has no qualified partial rollback or retry. */ @@ -3620,6 +3627,19 @@ static bool atcphy_t8132_dp_on(const struct apple_atcphy *atcphy) return atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy->t8132_dp_alt; } +/* + * The mode a T8132 port runs in while its controller is a USB device: + * SuperSpeed device mode is not supported by this driver, so USB3 and pin-D + * USB3+DP fall back to USB2. Four-lane DisplayPort (pin C/E) keeps USB2 on its + * own wires and is unchanged. + */ +static enum atcphy_mode atcphy_t8132_device_mode(enum atcphy_mode mode) +{ + if (mode == APPLE_ATCPHY_MODE_USB3 || mode == APPLE_ATCPHY_MODE_USB3_DP) + return APPLE_ATCPHY_MODE_USB2; + return mode; +} + /* * The T8132 lane start differs from the T8122 one: both blocks start at swing * 0 / pre-emphasis 0, the RX block's VREF filter is held until both DTVREG @@ -4552,8 +4572,13 @@ static int atcphy_usb2_init(struct phy *phy) /* A delayed shutdown may have completed after the last Type-C event. */ if (!atcphy->fixed_usb2) { - if (atcphy->mode == APPLE_ATCPHY_MODE_OFF || atcphy->mode_dirty) - return atcphy_configure(atcphy, atcphy->typec_mode); + if (atcphy->mode == APPLE_ATCPHY_MODE_OFF || atcphy->mode_dirty) { + enum atcphy_mode mode = atcphy->t8132_device ? + atcphy_t8132_device_mode(atcphy->typec_mode) : + atcphy->typec_mode; + + return atcphy_configure(atcphy, mode); + } /* * Reset assertion stops USB2 even when a DisplayPort mode keeps * the common block running. An aborted suspend need not produce @@ -4627,10 +4652,11 @@ static int atcphy_usb3_power_off(struct phy *phy) atcphy_restore_after_pd_off(atcphy); /* - * dwc3 has left host mode: nothing drives the PIPE any more, and the + * dwc3 has left its role: nothing drives the PIPE any more, and the * next host powers its SuperSpeed port on as it starts. */ atcphy->host_active = false; + atcphy->t8132_device = false; atcphy->usb3_port_off = false; ret = atcphy_park_pipehandler(atcphy, true); @@ -4714,6 +4740,8 @@ static int atcphy_usb3_route(struct apple_atcphy *atcphy, bool host) return atcphy_configure_pipehandler(atcphy, host); } +static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode); + static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode) { struct apple_atcphy *atcphy = phy_get_drvdata(phy); @@ -4725,18 +4753,51 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode if (atcphy->usb_off_pending) return -EBUSY; - if (atcphy->t8132_ss && - (atcphy->mode == APPLE_ATCPHY_MODE_USB3 || atcphy->mode == APPLE_ATCPHY_MODE_USB3_DP) && - mode == PHY_MODE_USB_DEVICE) - return -EOPNOTSUPP; - switch (mode) { case PHY_MODE_USB_HOST: + if (atcphy->t8132_device) { + enum atcphy_mode target = atcphy->typec_mode; + + /* + * Leaving the device role lifts the USB2 fallback: + * restore the partner's SuperSpeed mode before + * host_active blocks T8132 lane reconfiguration. + */ + atcphy->t8132_device = false; + if (atcphy->mode == APPLE_ATCPHY_MODE_USB2 && + atcphy_t8132_device_mode(target) != target) { + ret = atcphy_mux_switch(atcphy, target); + if (ret) { + atcphy->t8132_device = true; + return ret; + } + } + } atcphy->host_active = true; /* A host that starts up powers the ports of its root hubs itself. */ atcphy->usb3_port_off = false; break; case PHY_MODE_USB_DEVICE: + if (atcphy->t8132_ss) { + enum atcphy_mode usb2 = atcphy_t8132_device_mode(atcphy->mode); + + /* + * SuperSpeed device mode is not supported by this + * driver on T8132: serve the device role on USB2 + * instead of failing it. Keep typec_mode intact so a + * later host role can restore SuperSpeed. + */ + if (usb2 != atcphy->mode) { + enum atcphy_mode saved_typec_mode = atcphy->typec_mode; + + dev_info(atcphy->dev, + "USB device role: SuperSpeed device mode not supported by driver, using USB2\n"); + ret = atcphy_mux_switch(atcphy, usb2); + atcphy->typec_mode = saved_typec_mode; + if (ret) + return ret; + } + } atcphy->host_active = false; break; default: @@ -4744,6 +4805,8 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode } ret = atcphy_usb3_route(atcphy, mode == PHY_MODE_USB_HOST); + if (!ret && atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE) + atcphy->t8132_device = true; if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) dev_dbg(atcphy->dev, "USB %s route: mode=%u ss=%u calibration=%u common=%u dirty=%u pipe=%u pending=%u ret=%d mux=%#x override=%#x config=%#x\n", @@ -5823,6 +5886,8 @@ static enum atcphy_mode atcphy_typec_target_mode(struct apple_atcphy *atcphy, */ static bool atcphy_mux_in_mode(const struct apple_atcphy *atcphy, enum atcphy_mode target_mode) { + if (atcphy->t8132_device) + target_mode = atcphy_t8132_device_mode(target_mode); if (atcphy->mode != target_mode || atcphy->mode_dirty || atcphy->t8103_dummy_pending || atcphy->t8103_usb3_retry) return false; @@ -5907,9 +5972,12 @@ static int atcphy_mux_check(const struct apple_atcphy *atcphy, enum atcphy_mode static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode) { + enum atcphy_mode requested_mode = target_mode; int ret; lockdep_assert_held(&atcphy->lock); + if (atcphy->t8132_device) + target_mode = atcphy_t8132_device_mode(target_mode); if (atcphy->t8103_dummy_pending) { ret = atcphy_park_live_t8103_pipehandler(atcphy); if (ret) @@ -5917,7 +5985,7 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe } if (atcphy->mode == target_mode && !atcphy->mode_dirty) { - atcphy->typec_mode = target_mode; + atcphy->typec_mode = requested_mode; /* A canceled lane change owes the old USB3 backend its reconnect. */ if (atcphy->t8103_usb3_retry) { if (atcphy_pipe_state_for(atcphy, target_mode) == @@ -5947,7 +6015,7 @@ static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode targe ret = atcphy_mux_check(atcphy, target_mode); if (ret) return ret; - atcphy->typec_mode = target_mode; + atcphy->typec_mode = requested_mode; if (atcphy->fixed_usb2) { enum atcphy_pipehandler_state pipe_state; @@ -6069,7 +6137,8 @@ static int atcphy_mux_update_to(struct apple_atcphy *atcphy, enum atcphy_mode ta return 0; } /* Turn down a mode the PHY cannot run before USB3 goes down for it. */ - ret = atcphy_mux_check(atcphy, target_mode); + ret = atcphy_mux_check(atcphy, atcphy->t8132_device ? + atcphy_t8132_device_mode(target_mode) : target_mode); if (ret) return ret; in_mode = atcphy_mux_in_mode(atcphy, target_mode); diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..3932b682c124c8 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -63,6 +63,7 @@ def block(source, marker): #define dev_warn(...) ((void)reports++) #define dev_err(...) ((void)reports++) #define dev_dbg(...) ((void)0) +#define dev_info(...) ((void)0) #define lockdep_assert_held(...) ((void)0) #define guard(which) (void) #define IS_ENABLED(x) 0 @@ -101,6 +102,8 @@ def block(source, marker): bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, t8140_dp_tunables, dp_tunables; /* T8132 ownership is tested without entering its lane-setup backend. */ bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + /* T8132: SuperSpeed device mode is not supported by this driver; keep USB2. */ + bool t8132_device; struct { void *usb3_dp; } tunables; }; struct phy { struct apple_atcphy *data; }; @@ -113,14 +116,14 @@ def block(source, marker): static struct atcphy_hw hw; static struct apple_atcphy p; static struct phy phy; -static unsigned polls, sleeps, sets, clears, muxes, bist_old, bist_new; +static unsigned polls, sleeps, sets, clears, muxes, bist_old, bist_new, bist_t8132; static unsigned configure_calls, restore_calls, unlocks, warnings; static unsigned dummy_muxes, pending_seen_at_unlock; static unsigned usb2_power_off_calls; static unsigned ack_on; static int check_ret, bist_ret, unlock_ret, configure_ret; static bool concurrent_override_change; -static bool model_t8132_off; +static bool model_t8132_off, model_t8132_usb2, model_t8132_usb3, model_t8132_pipe; static u32 readl(const void *ptr) { u32 v; memcpy(&v, ptr, sizeof(v)); return v; } static void writel(u32 val, void *ptr) { memcpy(ptr, &val, sizeof(val)); } static void set32(void *ptr, u32 mask) { @@ -144,7 +147,7 @@ def block(source, marker): return ack_on && polls >= ack_on ? PIPEHANDLER_LOCK_EN : 0; } #define readl_poll_timeout(addr,val,cond,delay,timeout) \ - ({ assert((delay) == 10 && (timeout) == 1000); \ + ({ assert((delay) == 10 && (timeout) == (hw.gen == ATCPHY_GENERATION_T8132 ? 6000 : 1000)); \ (val) = poll_value(addr); (cond) ? 0 : -ETIMEDOUT; }) static void usleep_range(unsigned lo, unsigned hi) { assert(lo == 5000 && hi == 10000); sleeps++; @@ -177,13 +180,23 @@ def block(source, marker): static int atcphy_usb2_power_off(struct apple_atcphy *a) { (void)a; usb2_power_off_calls++; return 0; } -/* Only an explicitly expected T8132 OFF boundary is modeled, not lane setup. */ +/* Only explicitly expected T8132 mode boundaries are modeled, not lane setup. */ static int atcphy_configure_t8132(struct apple_atcphy *a, enum atcphy_mode mode) { - assert(model_t8132_off && mode == APPLE_ATCPHY_MODE_OFF); - configure_calls++;a->mode=mode;a->mode_dirty=false;return 0; + assert((model_t8132_off && mode == APPLE_ATCPHY_MODE_OFF) || + (model_t8132_usb2 && mode == APPLE_ATCPHY_MODE_USB2) || + (model_t8132_usb3 && mode == APPLE_ATCPHY_MODE_USB3)); + if (a->pipe_pending || a->pipe_state != ATCPHY_PIPEHANDLER_STATE_DUMMY) + return -EBUSY; + if (a->t8132_common_owned && a->host_active) + return -EBUSY; + configure_calls++; + if (configure_ret) { a->mode_dirty = true; return configure_ret; } + a->mode = mode; a->mode_dirty = false; return 0; } static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *a) { - (void)a; assert(!"T8132 PIPE setup reached"); return -EINVAL; + (void)a; + assert(model_t8132_pipe); + bist_t8132++; return bist_ret; } static void atcphy_usb2_power_on(struct apple_atcphy *a) { (void)a; assert(!"USB2-only power restore reached"); @@ -207,7 +220,7 @@ def block(source, marker): const struct device_node root = {compatibles, 1}; p.t8103_usb3_workaround = atcphy_has_t8103_usb3_workaround(&hw, &root); phy.data = &p; - polls = sleeps = sets = clears = muxes = bist_old = bist_new = 0; + polls = sleeps = sets = clears = muxes = bist_old = bist_new = bist_t8132 = 0; configure_calls = restore_calls = unlocks = warnings = reports = 0; dummy_muxes = pending_seen_at_unlock = 0; usb2_power_off_calls = 0; @@ -215,6 +228,9 @@ def block(source, marker): check_ret = bist_ret = unlock_ret = configure_ret = 0; concurrent_override_change = false; model_t8132_off = false; + model_t8132_usb2 = false; + model_t8132_usb3 = false; + model_t8132_pipe = false; } static void reset_machine(enum atcphy_generation generation, const char *machine) { reset(generation, false); @@ -425,6 +441,70 @@ def block(source, marker): setup_legacy_usb3();p.t8103_dummy_pending=p.t8103_usb3_retry=true;p.pipe_pending=true; atcphy_setup_pipehandler(&p);assert(!p.t8103_dummy_pending&&!p.t8103_usb3_retry&&!p.pipe_pending&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY); } +/* + * SuperSpeed device mode is not supported by this driver on T8132: a device + * role takes the lanes to USB2 while preserving typec_mode, survives SAFE + * bounces, clears on power_off or host swap, and restores USB3 on host swap. + */ +static void t8132_device_role_runs_usb2(void) { + struct typec_mux_state state={.mode=TYPEC_STATE_USB}; + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB3;p.typec_mode=APPLE_ATCPHY_MODE_USB3; + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3); + model_t8132_usb2=true; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + assert(configure_calls==1&&!p.host_active&&p.pipe_state==ATCPHY_PIPEHANDLER_STATE_DUMMY); + /* A later USB3 request from the port controller stays on USB2 and keeps typec_mode. */ + assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3); + assert(atcphy_mux_in_mode(&p,APPLE_ATCPHY_MODE_USB3)); + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3&&configure_calls==1); + /* The device role again on USB2: nothing to change. */ + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0));assert(configure_calls==1); + /* Pin-D USB3+DP drops to USB2 unconditionally; 4-lane DP keeps USB2 on its own wires. */ + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP)==APPLE_ATCPHY_MODE_USB2); + p.t8132_dp_alt=true; + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_USB3_DP)==APPLE_ATCPHY_MODE_USB2); + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_DP)==APPLE_ATCPHY_MODE_DP); + assert(atcphy_t8132_device_mode(APPLE_ATCPHY_MODE_OFF)==APPLE_ATCPHY_MODE_OFF); + p.t8132_dp_alt=false; + /* A SAFE/OFF mux bounce does not clear the active device role. */ + model_t8132_off=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_OFF)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_OFF&&p.typec_mode==APPLE_ATCPHY_MODE_OFF); + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_USB2&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* Leaving the role via power_off clears t8132_device so the next partner gets USB3. */ + assert(!atcphy_usb3_power_off(&phy));assert(!p.t8132_device&&p.mode==APPLE_ATCPHY_MODE_OFF); + model_t8132_usb3=true; + assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_USB3)); + assert(p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* A failed device-role switch (e.g. host still owns common/PIPE) must not stick t8132_device. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB3; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.t8132_common_owned=true;p.host_active=true; + model_t8132_usb2=true; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)==-EBUSY); + assert(!p.t8132_device&&p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + /* A failed route after USB2 also must not stick t8132_device. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB2; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.mode_dirty=true; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0)==-EBUSY); + assert(!p.t8132_device); + /* Direct device -> host DR swap restores USB3 lanes before host_active and routes PIPE. */ + reset(ATCPHY_GENERATION_T8132,false);p.t8132_ss=true;p.mode=APPLE_ATCPHY_MODE_USB2; + p.typec_mode=APPLE_ATCPHY_MODE_USB3;p.t8132_device=true;p.t8132_common_owned=true; + model_t8132_usb3=true;model_t8132_pipe=true; + configure_ret=-EIO; + assert(atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)==-EIO); + assert(p.t8132_device&&!p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB2); + configure_ret=0;p.mode_dirty=false; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_HOST,0)); + assert(!p.t8132_device&&p.host_active&&p.mode==APPLE_ATCPHY_MODE_USB3&&p.typec_mode==APPLE_ATCPHY_MODE_USB3); + assert(p.pipe_state==ATCPHY_PIPEHANDLER_STATE_USB3&&bist_t8132==1); + /* Without the SuperSpeed banks the port was USB2 already: no lane change. */ + reset(ATCPHY_GENERATION_T8132,false);p.mode=APPLE_ATCPHY_MODE_USB2; + assert(!atcphy_usb3_set_mode(&phy,PHY_MODE_USB_DEVICE,0));assert(!p.t8132_device&&!configure_calls); +} static void target_mode_table_and_dirty(void) { reset(ATCPHY_GENERATION_T8103,false);struct typec_mux_state state={.mode=TYPEC_DP_STATE_D};struct typec_altmode alt={.svid=USB_TYPEC_DP_SID};state.alt=&alt; assert(atcphy_typec_target_mode(&p,&state)==APPLE_ATCPHY_MODE_USB3_DP);state.mode=TYPEC_DP_STATE_C; @@ -602,6 +682,7 @@ def block(source, marker): } int main(void) { TEST(both_role_and_typec_orders_complete_usb3); + TEST(t8132_device_role_runs_usb2); TEST(nonusb3_commit_discharges_deferred_role); TEST(deferred_role_survives_configuration_failures); TEST(admission_requires_machine_and_generation); @@ -717,7 +798,10 @@ def harness(source): # The PIPE backend of a mode, which T8132 CIO keeps on the dummy one. helpers = [block(source, "static bool atcphy_mode_is_cio("), block(source, "static bool atcphy_t8132_dp_on("), - block(source, "static enum atcphy_pipehandler_state\natcphy_pipe_state_for(")] + block(source, "static enum atcphy_mode atcphy_t8132_device_mode("), + block(source, "static enum atcphy_pipehandler_state\natcphy_pipe_state_for("), + # atcphy_usb3_set_mode() moves a T8132 device role to USB2 through it. + "static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode);"] functions = "\n".join(helpers + [block(source, "static " + kind + " " + name + "(") for kind, name in function_specs]) configure = block(source, "static int atcphy_configure(") @@ -731,7 +815,27 @@ def harness(source): return PRELUDE + defines + "\n" + "\n".join(usb_defines) + "\n" + types + "\n" + table + stubs + functions + scope_c + TESTS -MUTATIONS = {'t8132-usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', +MUTATIONS = {'t8132-device-role-refused': ('atcphy_usb3_set_mode', + 'if (atcphy->t8132_ss) {', + 'if (atcphy->t8132_ss) {\n\t\t\treturn -EOPNOTSUPP;'), + 't8132-device-role-not-remembered': ('atcphy_mux_switch', + 'if (atcphy->t8132_device)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);', + 'if (false)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);'), + 't8132-device-role-in-mode-ignores-flag': ('bool atcphy_mux_in_mode', + 'if (atcphy->t8132_device)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);', + 'if (false)\n\t\ttarget_mode = atcphy_t8132_device_mode(target_mode);'), + 't8132-device-role-sticks-after-poweroff': ('atcphy_usb3_power_off', + 'atcphy->t8132_device = false;', '(void)0;'), + 't8132-device-role-set-on-route-error': ('atcphy_usb3_set_mode', + 'if (!ret && atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE)\n\t\tatcphy->t8132_device = true;', + 'if (atcphy->t8132_ss && mode == PHY_MODE_USB_DEVICE)\n\t\tatcphy->t8132_device = true;'), + 't8132-device-to-host-stays-usb2': ('atcphy_usb3_set_mode', + 'if (atcphy->mode == APPLE_ATCPHY_MODE_USB2 &&\n\t\t\t atcphy_t8132_device_mode(target) != target) {', + 'if (false) {'), + 't8132-pin-d-keeps-dp': ('enum atcphy_mode atcphy_t8132_device_mode', + 'mode == APPLE_ATCPHY_MODE_USB3 || mode == APPLE_ATCPHY_MODE_USB3_DP', + 'mode == APPLE_ATCPHY_MODE_USB3'), + 't8132-usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', '&&\n\t !atcphy->mode_dirty)', ')'), 't8132-usb-stop-drops-cio': ('atcphy_usb3_power_off', 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode)', 'false'), diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py index 980a7a8773b97f..ce4b775b2f734f 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py @@ -176,20 +176,25 @@ def atc_function(source, name): def atc_cio_helpers(source): - """The PIPE backend of a mode, which T8132 CIO keeps on the dummy one, and - whether a T8132 port is wired for DP alt mode. + """The PIPE backend of a mode, which T8132 CIO keeps on the dummy one, + whether a T8132 port is wired for DP alt mode, and the T8132 device-role + mode mapping. The mux and PIPE functions call these; older sources have none: ''. """ result = '' for name in ('atcphy_mode_is_cio', 'atcphy_pipe_state_for', - 'atcphy_usb2_sig_host', 'atcphy_t8132_dp_on'): + 'atcphy_usb2_sig_host', 'atcphy_t8132_dp_on', + 'atcphy_t8132_device_mode'): marker = re.search(r'^static [^;{}()]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M) if marker: helper = block(source, marker.start()) if name == 'atcphy_usb2_sig_host': helper = helper.replace('static u32', 'static __attribute__((unused)) u32', 1) + elif name == 'atcphy_t8132_device_mode': + helper = helper.replace('static enum atcphy_mode', + 'static __attribute__((unused)) enum atcphy_mode', 1) result += helper + '\n' return result @@ -223,6 +228,18 @@ def atc_mux_noop(source): return ''.join(atc_function(source, name) for name in ('atcphy_mux_in_mode', 'atcphy_mux_is_noop')) +def atc_set_mode_prototypes(source): + """Prototype atcphy_usb3_set_mode() needs ahead of the mux. + + It moves a T8132 device role to USB2 and restores SuperSpeed on a host swap + through atcphy_mux_switch(), which atc_mux_without_pm() emits with the mux, + after the role functions in some fixtures. + """ + if 'atcphy_mux_switch(' not in block(source, 'static int atcphy_usb3_set_mode('): + return '' + return 'static int atcphy_mux_switch(struct apple_atcphy *atcphy, enum atcphy_mode target_mode);\n' + + def atc_mux_without_pm(source): """Lane/teardown fixtures omit USB PM, keeping mode mapping and lane work real. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index cc3197c1b738a1..c76fa8299e526b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -2,8 +2,8 @@ /* This fixture selects the original controller layout, not T8132. */ #define of_device_is_compatible(...) false struct apple_atcphy { - /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c index 8c0bfb426e8a05..36b5272fc4f3fd 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c @@ -30,6 +30,7 @@ static void warning(const char *message) #define dev_warn(d, message, ...) warning(message) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) +#define dev_info(...) ((void)0) #define lockdep_assert_held(p) assert(*(p)) #define WARN_ON_ONCE(v) assert(!(v)) static void mutex_lock(int *m) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..dc9b11fa89a54a 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -3,7 +3,7 @@ """Actual disconnect authority, DWC3 teardown and firmware resource admission.""" from pathlib import Path import re -from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers +from common import block, apple_function, atc_set_mode_prototypes, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers def disconnect(root): # Copyright 2026 Ryan Murray @@ -824,6 +824,9 @@ def poweroff_replug(root): #define fake_guard(x) ((void)(x)) #define scoped_guard(x, y) for (int once = ((void)(y), 1); once; once = 0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) #define dev_err(...) ((void)0) struct delayed_work { bool pending; }; @@ -1127,6 +1130,8 @@ def fn(n, name): m = re.search(r'^(?:static [^\n]*\b|(?:int|void) )' + name + r'\([^;{}]*\)\s*\{', s, re.M) assert m, (n, name) result = block(s, m.start()) + if n == 'atc' and name == 'atcphy_usb3_set_mode': + result = atc_set_mode_prototypes(s) + result return result decls = [] @@ -1838,6 +1843,9 @@ def vrr(root): #define DCP_IOMFB_METHODS_H17P_EXTERNAL 2 #define READ_ONCE(x) (x) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif struct apple_connector { bool connected; }; /* The native T6030 14.7 backend is never selected in these scenarios. */ enum dcp_firmware_version { DCP_FIRMWARE_UNKNOWN, DCP_FIRMWARE_V_12_3, DCP_FIRMWARE_V_13_5, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 26c0f62dabb254..16b8b2df07491d 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -3,7 +3,7 @@ """Actual PHY parking, failure/retry, masked context and OFF controls.""" from pathlib import Path import re -from common import (block, source_defines, atc_mux_without_pm, ATC_POST_TUNABLE, +from common import (block, source_defines, atc_mux_without_pm, atc_set_mode_prototypes, ATC_POST_TUNABLE, atc_function, ATC_SPLIT, ATC_T8103_LIVE, atc_restore_helpers, atc_common_state_helpers, atc_cio_helpers) @@ -16,6 +16,9 @@ def parking(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(source, re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -34,7 +37,7 @@ def function(source, name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -224,6 +227,9 @@ def function(source, name): #define hweight32(v) __builtin_popcount(v) #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report @@ -1901,6 +1907,9 @@ def usb_context(root): } #undef dev_dbg #define dev_dbg(dev, format, ...) record_debug(format, ##__VA_ARGS__) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif ''' return ns["prefix"] + logger + "#define PROPOSAL\n" + production + ns["suffix"].replace("int main(", "int original_fixture_main(", 1) + controls @@ -1923,6 +1932,9 @@ def block(marker): def function(name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -1936,7 +1948,7 @@ def function(name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -2047,6 +2059,9 @@ def function(name): #define FIELD_GET(m, v) (((v) & (m)) >> __builtin_ctz(m)) #define field_prep FIELD_PREP #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) #define dev_err(...) ((void)0) #define lockdep_assert_held(...) ((void)0) @@ -2320,6 +2335,9 @@ def unwind(root): def function(source, name): if name == 'atcphy_mux_set' and 'static int atcphy_mux_set_locked(' in source: return atc_mux_without_pm(source) + if name == 'atcphy_usb3_set_mode': + return atc_set_mode_prototypes(source) + block(source, re.search( + r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) if name in ATC_SPLIT + ATC_T8103_LIVE: return atc_function(source, name) return block(source, re.search(r'^static [^\n;]+\b' + name + r'\([^;{}]*\)\s*\{', source, re.M).group()) @@ -2336,7 +2354,7 @@ def function(source, name): parts.append(r''' struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; @@ -2467,6 +2485,9 @@ def function(source, name): #define hweight32(v) __builtin_popcount(v) #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) +#ifndef dev_info +#define dev_info(...) ((void)0) +#endif #define dev_warn(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report @@ -2661,7 +2682,7 @@ def aux(root): #define BIT(n) (1U << (n)) struct apple_atcphy { /* T8132-only paths are covered by drivers/apple/atc-t8132-usb3.py. */ - bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; + bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt, t8132_device; /* A CIO sleep is T8132's too, covered by tools/asahi/atc-cio-sleep-tests.py. */ struct { bool prepared; } cio_sleep; struct { void *usb3_dp, *dp_lioa, *dp_common_config; } tunables; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py index 9257b85dec643c..d78a19800b05bf 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/quiesce.py @@ -158,7 +158,7 @@ def make_unit(source, parent=False, reference=None): void *dev; int lock; const struct atcphy_hw *hw; struct { void *usb2phy; } regs; - bool fixed_usb2,host_active,mode_dirty,pipe_pending,usb_off_pending,ss_tunables,dp_tunables,cio_tunables,t8132_dp_alt; + bool fixed_usb2,host_active,mode_dirty,pipe_pending,usb_off_pending,ss_tunables,dp_tunables,cio_tunables,t8132_dp_alt,t8132_device; bool usb3_port_off,park_owed,dp_only,pd_was_off; bool t8103_dummy_pending,t8103_usb3_retry,t8103_usb3_workaround; enum atcphy_mode mode,typec_mode; From 02829ba72a82dce098013bed011db0bed21a1fdb Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sat, 21 Nov 2026 23:46:09 +0000 Subject: [PATCH 0232/1514] arm64: dts: apple: t6041: add PMC SoC rail floor domain Define the pmc_soc_max (floor-soc-max) power domain under &pmc on T6041 using rail 1 (SOC, verified from J616c ADT /arm-io/pmgr voter-rail-data) and AP static voter agent 3 (already listed in apple,static-voters). Unlike M4 Pro (T6040, SOC states 0..2), M4 Max (T6041) exposes four SOC states (0..3 in J616c ADT /arm-io/pmp/iop-pmp-nub dvfs-domain and pmgr voltage-states0/28/29). State 2 (VMAX, 815 mV) already reaches the maximum SOC_AFC clock (2004 MHz) and matches ADT AVD-SOC-VMAX (0x19c) and VENC0-SOC-VMAX (0x198), while state 3 (VOVD, 820 mV) only raises SOC_AFI (975 -> 1300 MHz) and is driven by CLPC for CPU/GPU demand. Use level 2 here with label "soc-vmax" to match the ADT VMAX floor without implying the top VOVD state in apple-pmc debugfs. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041.dtsi | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 23720e5e53b6b7..a539ea3f8688c9 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -339,6 +339,21 @@ &pmc { #cooling-cells = <2>; apple,static-voters = <1 3>; + + /* + * SoC fabric rail floor (rail 1, AP voter agent 3). T6041 has four + * SOC states (0-3; ADT pmp dvfs-domain and pmgr voltage-states0/28/29): + * state 2 (VMAX, 815 mV) already reaches the maximum SOC_AFC clock + * (2004 MHz) and matches ADT AVD-SOC-VMAX and VENC0-SOC-VMAX; state 3 + * (VOVD, 820 mV) only raises SOC_AFI (975 -> 1300 MHz) and is voted by + * CLPC for CPU/GPU demand. + */ + pmc_soc_max: floor-soc-max { + label = "soc-vmax"; + #power-domain-cells = <0>; + apple,rail = <1>; + apple,level = <2>; + }; }; &clpc { From fa1e8e3e772e29920d41eed93ae83d10e2832338 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 06:07:47 +0000 Subject: [PATCH 0233/1514] arm64: dts: apple: t6041: wire pmc_soc_max perf floor to AVD and AVE Attach the PMC SoC rail floor domain (&pmc_soc_max) as the "perf" power domain on &avd and &ave in t6041.dtsi, matching T6040 (t6040.dtsi) and the existing AVD and AVE bindings and drivers. &ane is intentionally left without the PMC floor: on T6041, apple_clpc_hw_t6041 already votes SoC state 2 for every ANE EXECUTE (clpc.c: apple_clpc_hw_t6041.ane[APPLE_CLPC_SOC] = 2) and active CPU demand votes SoC state 3 (VOVD). All T6041 boards (J616c, J614c, J575c) enable &pmc. On J616c and J614c &ave remains disabled until brought up; on J575c &ave is already enabled and now receives the VMAX SoC floor alongside &avd. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041.dtsi | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index a539ea3f8688c9..5fead37c82762f 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -9,7 +9,15 @@ &avd { compatible = "apple,t6041-max-avd", "apple,t6041-avd", "apple,t8132-avd"; - power-domains = <&ps_avd_sys>; + power-domains = <&ps_avd_sys>, <&pmc_soc_max>; + power-domain-names = "core", "perf"; +}; + +&ave { + power-domains = <&ps_venc0_dma>, <&ps_venc0_pipe4>, + <&ps_venc0_pipe5>, <&ps_venc0_me0>, <&ps_venc0_me1>, + <&pmc_soc_max>; + power-domain-names = "dma", "pipe4", "pipe5", "me0", "me1", "perf"; }; /* From e08ff749d9136e3a796b2399a66540055dc3f8bf Mon Sep 17 00:00:00 2001 From: Naeem Malik <104218167+malik-na@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:11:46 +0530 Subject: [PATCH 0234/1514] media: apple: avd: decode VP9 frames smaller than 64x64 on the legacy transport validate_dec_params() refuses every VP9 frame narrower or shorter than 64 pixels, and requires the frame size, aligned to 64x16, to equal the CAPTURE format. The CAPTURE format is never smaller than the 64x64 minimum of the VP9 frame size range, so a frame below 64 in either dimension could not pass either check. Such a stream fails its first frame ("unexpected bitstream resolution") and stops. The 64-pixel floor came from rkvdec; H.264, HEVC and AV1 frames as small as 16x16 already decode on this decoder. Raise the aligned frame size to the 64x64 minimum before comparing it with the CAPTURE format, as the CAPTURE format is. A frame larger than the CAPTURE format is still refused. Drop the floor on the legacy transport only, where it was measured. The firmware transports (queued firmware, Apple firmware) keep it until sub-64 frames are measured there: an input their firmware does not expect can reset the engine instead of failing the frame. Add avd_backend_is_open() for that check. Tested on a J516c (M3 Max, T6031, legacy transport). Of the 64 libvpx vp90-2-02-size-WxH conformance vectors (8 to 66 pixels), 4 decoded before (those 64 or larger in both dimensions) and all 64 now match FFmpeg's software decode, which matches the libvpx MD5s. H.264, HEVC, VP9 and AV1 at other sizes and throughput are unchanged. The VP9 host test now checks that a 32x16 frame into a 64x64 CAPTURE format is refused on the firmware transport, decodes on the legacy transport, and that a larger frame is still refused there. Signed-off-by: Naeem Malik <104218167+malik-na@users.noreply.github.com> --- .../platform/apple/avd/avd-backend-open.c | 5 +++++ drivers/media/platform/apple/avd/avd-vp9.c | 21 +++++++++++++++---- drivers/media/platform/apple/avd/avd.h | 1 + .../platform/apple/avd/tests/vp9-test.py | 15 +++++++++++++ 4 files changed, 38 insertions(+), 4 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-backend-open.c b/drivers/media/platform/apple/avd/avd-backend-open.c index d2054d06f948b8..525c7848b4edcc 100644 --- a/drivers/media/platform/apple/avd/avd-backend-open.c +++ b/drivers/media/platform/apple/avd/avd-backend-open.c @@ -177,6 +177,11 @@ static irqreturn_t avd_open_irq(struct avd_dev *avd) return IRQ_HANDLED; } +bool avd_backend_is_open(const struct avd_dev *avd) +{ + return avd->backend == &avd_open_backend; +} + const struct avd_backend_ops avd_open_backend = { .name = "open-compat", .boot = avd_boot, diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index bf2d8b80854e60..a596b420ac2c70 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -670,12 +670,25 @@ static int validate_dec_params(struct avd_ctx *ctx, { unsigned int aligned_width, aligned_height; - if (dec_params->frame_height_minus_1 + 1 < 64 || - dec_params->frame_width_minus_1 + 1 < 64) + /* + * The CAPTURE format is at least 64x64, the minimum of the VP9 frame + * size range, so a smaller frame is decoded into a 64x64 buffer, as + * H.264, HEVC and AV1 frames are. That is measured on the legacy + * transport only. The firmware transports keep the 64-pixel floor + * until it is measured there: an input their firmware does not + * expect can reset the engine instead of failing the frame. + */ + if (!avd_backend_is_open(ctx->dev) && + (dec_params->frame_width_minus_1 + 1 < 64 || + dec_params->frame_height_minus_1 + 1 < 64)) return -EINVAL; - aligned_width = round_up(dec_params->frame_width_minus_1 + 1, 64); - aligned_height = round_up(dec_params->frame_height_minus_1 + 1, 16); + aligned_width = max_t(unsigned int, + round_up(dec_params->frame_width_minus_1 + 1, 64), + 64); + aligned_height = max_t(unsigned int, + round_up(dec_params->frame_height_minus_1 + 1, 16), + 64); /* * Userspace should update the capture/decoded format when the diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 568cbfc6d06f8d..85f75303cf3b9c 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -418,6 +418,7 @@ void avd_qfw_select(struct avd_dev *avd); void avd_qfw_prepare_boot(struct avd_dev *avd); void avd_qfw_debug(struct avd_dev *avd, struct avd_frame *f, const char *where); bool avd_backend_is_qfw(const struct avd_dev *avd); +bool avd_backend_is_open(const struct avd_dev *avd); bool avd_qfw_has_vp_done(const struct avd_dev *avd); unsigned int avd_qfw_picture_banks(const struct avd_dev *avd, unsigned int codec); int avd_backend_select(struct avd_dev *avd); diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 7c60bbb1688439..083c06e095a1f5 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -62,6 +62,7 @@ #define kfree free static bool vp_feature = true; static bool avd_qfw_has_vp_done(const struct avd_dev *d) { return d->queued && vp_feature; } +static bool avd_backend_is_open(const struct avd_dev *d) { return !d->queued; } static void *vb2_plane_vaddr(struct vb2_buffer *b,int p) { (void)p;return b->cpu; } static size_t vb2_get_plane_payload(struct vb2_buffer *b,int p) { (void)p;return b->payload; } static struct vb2_v4l2_buffer *current_src,*current_dst; @@ -208,12 +209,26 @@ def without_includes(s): assert(p->bank[0].busy&&p->bank[1].busy); avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); } + /* The firmware transport keeps the 64-pixel floor. */ + ctx.decoded_fmt.fmt.pix_mp.width=64;ctx.decoded_fmt.fmt.pix_mp.height=64; + ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=64; + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_KEY_FRAME|V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=31,.frame_height_minus_1=15,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); avd_vp9_stop(&ctx);assert(!avd_vp9_ready(&ctx)); /* Old firmware and the legacy transport allocate only one bank. */ for(unsigned int mode=0;mode<2;mode++) { dev.queued=mode;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; assert(p->nbanks==1&&ctx.max_frames==1);avd_vp9_stop(&ctx); } + /* On the legacy transport a frame below 64x64 decodes into a 64x64 CAPTURE buffer. */ + dev.queued=false;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + /* A frame larger than the CAPTURE format is still refused. */ + params.frame_width_minus_1=1919;params.frame_height_minus_1=1087; + assert(avd_vp9_run(&ctx)==-EINVAL); + avd_vp9_stop(&ctx); dev.queued=true;vp_feature=true;fail_alloc_after=13;allocating_ctx=&ctx; assert(avd_vp9_start(&ctx)==-ENOMEM);allocating_ctx=NULL; assert(!ctx.priv&&!avd_vp9_ready(&ctx)&&ctx.max_frames==1); From 92d43be3161f558286c3c8bd66d1e061c6597edc Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 17 Nov 2026 11:21:30 -0500 Subject: [PATCH 0235/1514] arm64: dts: apple: t6050-j716c: Add the Touch ID sensor The J716c ADT wires the Mesa sensor as on the J714s: sensor-id 0x3356 on spi2 at 0x505108000, 8 MHz, chip select 0, power on NUB GPIO 21 (function-mesa_pwr) and data ready on AP GPIO 138. The device tree did not describe it, so apple_sep fell back to the T6020 controller address, found nothing there and never registered the sensor. Enable nub-gpio0, spi2 and their power states and add the fingerprint node with the J714s timing and SPI mode, naming the J716c calibration and root-key files. Expose AP GPIO 138: while it was reserved, gpiolib would have refused the data-ready interrupt's mapping. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t6050-j716c.dts | 42 +++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index 8fdea5242027b6..68895b2cc7f20a 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -176,11 +176,12 @@ /* * Pin 112's register (0x29c0001c0) takes an SError when read, so only the pins a node - * here names are exposed: 80 (PCIe port 0's PERST#, ADT pci-bridge0 function-perst). + * here names are exposed: 80 (PCIe port 0's PERST#, ADT pci-bridge0 function-perst) and + * 138 (the Touch ID sensor's data-ready line). * A reserved line cannot be requested, so a node that names a new pin opens it here too. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 140>; + gpio-reserved-ranges = <0 80>, <81 57>, <139 82>; }; /* This board's SMC fan and power keys are not yet checked */ @@ -246,6 +247,43 @@ 63 2e 00 06 02 69 4f 53 00 00 00 00]; }; +/* + * Touch ID (ADT spi2/mesa), wired as on the J714s: the Mesa sensor (sensor-id + * 0x3356) at 8 MHz on chip select 0, powered by NUB GPIO 21 (function-mesa_pwr), + * data ready on AP GPIO 138. The controller's clock (ADT clock-ids 451) is the + * 24 MHz reference. + */ +&ps_nub_gpio { + status = "okay"; +}; + +&nub_gpio0 { + status = "okay"; +}; + +&ps_spi2 { + status = "okay"; +}; + +&spi2 { + clocks = <&clkref>; + status = "okay"; + + mesa: fingerprint@0 { + compatible = "apple,mesa-fingerprint"; + reg = <0>; + spi-max-frequency = <8000000>; + spi-cpol; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <138 IRQ_TYPE_EDGE_RISING>; + /* Per-device factory data from this Mac's own iBoot system container */ + firmware-name = "apple/mesacal-j716c.bin", "apple/msrk-j716c.bin"; + }; +}; + #include "t6050-j716c-isp.dtsi" #include "t6050-j716c-gpu-panel.dtsi" From 7803302be7eeff297f40902a918ee111a8099e86 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 20 Nov 2026 02:29:04 -0500 Subject: [PATCH 0236/1514] drm/apple: publish completion of native display takeover A display controller the bootloader left scanning out a framebuffer can still show that surface after DRM registration. Reserve its retirement record with the cache controller when binding, and mark it retired once an accepted, shown KMS swap replaces or clears slot zero. A paired firmware-27 scanout passes the firmware's shown state to the owner, set when both engines displayed the retired swap. If the record cannot be allocated the display still takes over, without a retirement report, so allocation stays off. Until that displayed completion arrives, pull the primary plane into atomic commits for that CRTC so cursor- or overlay-only commits replay the intended slot-zero surface with its own framebuffer reference, force an explicit slot-zero clear when the primary plane is disabled, and drop any inherited slot-zero reference from the pending scanout to match that clear. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/apple_drv.c | 73 ++++++++++++++- drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp-peer-frames-v27.h | 17 +++- .../gpu/drm/apple/dcp-peer-runtime-v27.inc | 10 +- drivers/gpu/drm/apple/dcp.c | 14 +++ drivers/gpu/drm/apple/dcp.h | 5 +- drivers/gpu/drm/apple/iomfb.c | 21 +++++ drivers/gpu/drm/apple/iomfb_template.c | 48 ++++++++-- tools/asahi/dcp-peer-shown-tests.py | 91 +++++++++++++++++++ tools/asahi/dcpext26-queue-tests.py | 5 +- tools/asahi/run-host-tests.py | 1 + 11 files changed, 266 insertions(+), 21 deletions(-) create mode 100644 tools/asahi/dcp-peer-shown-tests.py diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index dddbacc0cf41a9..d3256d772bbb31 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -777,11 +777,82 @@ static int apple_atomic_commit(struct drm_device *dev, return ret; } +static int apple_atomic_check(struct drm_device *dev, + struct drm_atomic_commit *state) +{ + struct drm_plane *plane; + struct drm_plane_state *old_plane_state, *new_plane_state; + struct drm_crtc *crtc; + struct drm_crtc_state *crtc_state; + int i, ret; + + ret = drm_atomic_helper_check_modeset(dev, state); + if (ret) + return ret; + + /* + * Until a displayed KMS swap retires the boot scanout, pull the CRTC + * and its primary plane into every commit touching that CRTC so a + * cursor- or overlay-only commit replays the intended slot-zero state + * and framebuffer reference inside the atomic transaction. + */ + for_each_oldnew_plane_in_state(state, plane, old_plane_state, + new_plane_state, i) { + struct drm_crtc *targets[2] = { + old_plane_state->crtc, + new_plane_state->crtc, + }; + + for (int t = 0; t < ARRAY_SIZE(targets); t++) { + struct drm_crtc *target = targets[t]; + + if (!target || t8132_ext_crtc(target)) + continue; + if (!dcp_boot_surface_pending(to_apple_crtc(target)->dcp)) + continue; + crtc_state = drm_atomic_get_crtc_state(state, target); + if (IS_ERR(crtc_state)) + return PTR_ERR(crtc_state); + } + } + + for_each_new_crtc_in_state(state, crtc, crtc_state, i) { + struct drm_plane_state *plane_state; + + if (t8132_ext_crtc(crtc) || !crtc->primary) + continue; + if (!crtc_state->enable || !crtc_state->active) + continue; + if (!dcp_boot_surface_pending(to_apple_crtc(crtc)->dcp)) + continue; + + plane_state = drm_atomic_get_plane_state(state, crtc->primary); + if (IS_ERR(plane_state)) + return PTR_ERR(plane_state); + crtc_state->planes_changed = true; + } + + if (dev->mode_config.normalize_zpos) { + ret = drm_atomic_normalize_zpos(dev, state); + if (ret) + return ret; + } + + ret = drm_atomic_helper_check_planes(dev, state); + if (ret) + return ret; + + if (state->legacy_cursor_update) + state->async_update = !drm_atomic_helper_async_check(dev, state); + + return 0; +} + static const struct drm_mode_config_funcs apple_mode_config_funcs = { .atomic_state_alloc = apple_atomic_state_alloc, .atomic_state_clear = apple_atomic_state_clear, .atomic_state_free = apple_atomic_state_free, - .atomic_check = drm_atomic_helper_check, + .atomic_check = apple_atomic_check, .atomic_commit = apple_atomic_commit, .fb_create = drm_gem_fb_create, }; diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index ea38c3fd64de71..924955a057250d 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -863,6 +863,8 @@ struct apple_dcp { /* clear all surfaces on init */ bool surfaces_cleared; + bool boot_surface_pending; + bool boot_scanout_reserved; /* enable CRC calculation */ bool crc_enabled; diff --git a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h index abb7798a1764fe..749aea54992448 100644 --- a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h +++ b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h @@ -8,8 +8,8 @@ * outstanding swaps, as in the existing single-pipe retirement path. */ struct dcp_peer_frames_v27 { - u32 first, submitted, engine[2], retired; - bool active, armed, failed, have[2], have_retired; + u32 first, submitted, engine[2], retired, shown[2]; + bool active, armed, failed, have[2], have_retired, have_shown[2]; }; static inline void dcp_peer_frame_submit_v27(struct dcp_peer_frames_v27 *s, u32 id) @@ -21,9 +21,14 @@ static inline void dcp_peer_frame_submit_v27(struct dcp_peer_frames_v27 *s, u32 s->submitted = id; } +/* + * *shown: both engines' firmware reported the retired swap itself as + * displayed, from completions of that swap ID. + */ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, unsigned int engine, u32 id, - u32 *watermark) + bool shown_now, u32 *watermark, + bool *shown) { u32 done; @@ -33,6 +38,10 @@ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, return false; s->engine[engine] = id; s->have[engine] = true; + if (shown_now) { + s->shown[engine] = id; + s->have_shown[engine] = true; + } if (!s->have[0] || !s->have[1]) return false; done = (s32)(s->engine[0] - s->engine[1]) < 0 ? s->engine[0] : s->engine[1]; @@ -40,6 +49,8 @@ static inline bool dcp_peer_frame_complete_v27(struct dcp_peer_frames_v27 *s, return false; s->retired = *watermark = done; s->have_retired = true; + *shown = s->have_shown[0] && s->shown[0] == done && + s->have_shown[1] && s->shown[1] == done; return true; } #endif diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index cd8340105b37bf..7094402d5c94f0 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -325,11 +325,12 @@ void dcp_peer_swap_failed_v27(struct apple_dcp *dcp) dcp_mode_invalidate(&dcp->mode_state); } -bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, - void (*report)(struct apple_dcp *, u32, ktime_t)) +bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown, + void (*report)(struct apple_dcp *, u32, ktime_t, bool)) { struct apple_dcp *owner; u32 watermark; + bool both_shown; /* Independent CRTCs must not serialize through the pair's mutex. */ if (!peer_scanout || (!READ_ONCE(dcp->peer_frames.active) && @@ -339,9 +340,10 @@ bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, owner = dcp->peer_owner ?: dcp; if (!peer_scanout || !owner->peer_frames.active) return false; - if (dcp_peer_frame_complete_v27(&owner->peer_frames, dcp != owner, id, &watermark)) + if (dcp_peer_frame_complete_v27(&owner->peer_frames, dcp != owner, id, shown, + &watermark, &both_shown)) /* Queue the combined watermark to the primary IOMFB owner. */ - report(owner, watermark, now); + report(owner, watermark, now, both_shown); return true; } diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 8a338952358526..485284e2053fae 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -6104,6 +6105,19 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) dcp->dfb_region_size = resource_size(&resource); if (!dcp->dfb_region_size) return -EINVAL; + /* + * The boot surface is on screen until a displayed swap of ours + * replaces it. Reserve its retirement record before any present. + * Without the record the display still takes over, and a cache + * controller waiting on it keeps allocation off. + */ + ret = apple_mcc_boot_scanout_reserve(dev->of_node); + if (ret == -ENOMEM) + dev_warn(dev, "no boot scanout record: system cache allocation stays off\n"); + else if (ret) + return ret; + dcp->boot_scanout_reserved = !ret; + WRITE_ONCE(dcp->boot_surface_pending, true); clocks: /* diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f1d0f49026d601..66b3102fffd612 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -82,8 +82,8 @@ int dcp_peer_stop_v27(struct apple_dcp *dcp); struct apple_dcp *dcp_peer_scanout_v27(struct apple_dcp *dcp); void dcp_peer_swap_armed_v27(struct apple_dcp *dcp, u32 id); void dcp_peer_swap_failed_v27(struct apple_dcp *dcp); -bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, - void (*report)(struct apple_dcp *, u32, ktime_t)); +bool dcp_peer_swap_complete_v27(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown, + void (*report)(struct apple_dcp *, u32, ktime_t, bool)); int dcp_set_crc(struct drm_crtc *crtc, bool enabled); int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commit); int dcp_get_connector_type(struct platform_device *pdev); @@ -105,6 +105,7 @@ void dcp_ext26_open_services(struct apple_dcp *dcp); int dcp_ext26_layout_stop(struct apple_dcp *dcp); int dcp_wait_ready(struct platform_device *pdev, u64 timeout); void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit); +bool dcp_boot_surface_pending(struct platform_device *pdev); bool dcp_hdr_metadata_live(struct platform_device *pdev); bool dcp_edr_live(struct platform_device *pdev); void dcp_retain_framebuffer(struct platform_device *pdev, diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1f3e97e6c5e9f0..fc822729f3cfd0 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3796,6 +3796,20 @@ iomfb_scanout_prepare_h17p(struct apple_dcp *dcp, struct drm_crtc *crtc, drm_framebuffer_get(new_state->fb); } } + if (dcp->boot_surface_pending && scanout->fb[0]) { + struct drm_plane_state *primary = crtc->primary ? + drm_atomic_get_new_plane_state(state, crtc->primary) : NULL; + + /* + * Match the explicit slot-zero clear in iomfb_flush() when the + * primary plane is disabled; dcp->iomfb.scanout keeps its own + * reference pinned until completion replaces it. + */ + if (!primary || primary->crtc != crtc || !primary->visible || !primary->fb) { + drm_framebuffer_put(scanout->fb[0]); + scanout->fb[0] = NULL; + } + } if (dcp_is_ext26(dcp)) { struct iomfb_scanout_h17p *dropped; u64 bytes = ext26_scanout_bytes(scanout); @@ -4401,6 +4415,13 @@ static void iomfb_start(struct apple_dcp *dcp) } } +bool dcp_boot_surface_pending(struct platform_device *pdev) +{ + struct apple_dcp *dcp = pdev ? platform_get_drvdata(pdev) : NULL; + + return dcp && READ_ONCE(dcp->boot_surface_pending); +} + bool dcp_is_initialized(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 066c7a5f1cfdda..225c89529a38ea 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -737,7 +738,7 @@ static u32 dcpep_cb_zero(struct apple_dcp *dcp) return 0; } -static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) +static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now, bool shown) { bool retire = true; if (dcp_is_ext26(dcp)) { @@ -790,8 +791,18 @@ static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) dcp->crashed = true; return; } - if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) + if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) { + /* Only a displayed KMS swap that touched boot slot zero retires it. */ + if (dcp->boot_surface_pending && shown && dcp->iomfb.next_scanout && + !iomfb_present_brightness_only_h17p(dcp) && + (DCP_FW_SWAP(dcp).swap.swap_enabled & BIT(0))) { + WRITE_ONCE(dcp->boot_surface_pending, false); + dev_info(dcp->dev, "boot scanout retired by displayed swap %u\n", id); + if (dcp->boot_scanout_reserved) + apple_mcc_boot_scanout_retired(dcp->dev->of_node); + } retire = iomfb_present_complete_h17p(dcp); + } #endif #if DCP_FW_DESKTOP_26(DCP_FW_VER) /* Late or duplicate completions cannot retire the replacement's flip. */ @@ -825,15 +836,17 @@ static void dcp_report_swap_complete(struct apple_dcp *dcp, u32 id, ktime_t now) } #if (DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER >= DCP_FW_VERSION(27, 0, 0)) -struct dcp_peer_completion { u32 id; ktime_t time; }; +struct dcp_peer_completion { u32 id; ktime_t time; bool shown; }; + static void dcp_peer_report_on_owner(struct apple_dcp *owner, void *data, void *cookie) { struct dcp_peer_completion *completion = data; - dcp_report_swap_complete(owner, completion->id, completion->time); + dcp_report_swap_complete(owner, completion->id, completion->time, completion->shown); } -static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t time) + +static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t time, bool shown) { - struct dcp_peer_completion completion = { id, time }; + struct dcp_peer_completion completion = { id, time, shown }; if (iomfb_queue_callback(owner, dcp_peer_report_on_owner, &completion, sizeof(completion), NULL)) { WRITE_ONCE(owner->crashed, true); @@ -848,10 +861,15 @@ static void dcpep_cb_swap_complete(struct apple_dcp *dcp, ktime_t now = dcp_is_ext26(dcp) ? ns_to_ktime(dcp->ext26_rx_ns) : ktime_get(); trace_iomfb_swap_complete(dcp, resp->swap_id); #if (DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER >= DCP_FW_VERSION(27, 0, 0)) - if (dcp_peer_swap_complete_v27(dcp, resp->swap_id, now, dcp_peer_queue_completion)) + if (dcp_peer_swap_complete_v27(dcp, resp->swap_id, now, resp->unkbool, + dcp_peer_queue_completion)) return; #endif - dcp_report_swap_complete(dcp, resp->swap_id, now); +#if DCP_FW_H17(DCP_FW_VER) + dcp_report_swap_complete(dcp, resp->swap_id, now, resp->unkbool); +#else + dcp_report_swap_complete(dcp, resp->swap_id, now, false); +#endif } /* special */ @@ -4540,9 +4558,21 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru #endif } +#if DCP_FW_H17(DCP_FW_VER) + /* + * Keep sending an explicit slot-zero update until a displayed KMS + * completion confirms the boot scanout has retired. An enabled primary + * plane is pulled into the atomic commit by apple_atomic_check(); if + * slot zero is still absent here, the primary plane is disabled and + * slot zero should be cleared. + */ + if (dcp->boot_surface_pending && !(req->swap.swap_enabled & BIT(0))) + req->swap.swap_enabled |= BIT(0); +#endif + if (!has_surface && !crtc_state->color_mgmt_changed) { if (crtc_state->enable && crtc_state->active && - !crtc_state->planes_changed) { + !crtc_state->planes_changed && !dcp->boot_surface_pending) { schedule_work(&dcp->vblank_wq); return; } diff --git a/tools/asahi/dcp-peer-shown-tests.py b/tools/asahi/dcp-peer-shown-tests.py new file mode 100644 index 00000000000000..1b26c2d3ab4080 --- /dev/null +++ b/tools/asahi/dcp-peer-shown-tests.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Paired firmware-27 completions carry the retired swap's displayed state to the owner.""" +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +HEADER = (ROOT / 'drivers/gpu/drm/apple/dcp-peer-frames-v27.h').read_text() +SHOWN = ''' *shown = s->have_shown[0] && s->shown[0] == done && + s->have_shown[1] && s->shown[1] == done; +''' +assert HEADER.count(SHOWN) == 1 +if '--always-shown' in sys.argv: + HEADER = HEADER.replace(SHOWN, '\t*shown = true;\n') +if '--owner-only' in sys.argv: + HEADER = HEADER.replace(SHOWN, '\t*shown = s->have_shown[0] && s->shown[0] == done;\n') + +TEST = r''' +#include +#include +#include +typedef uint32_t u32; typedef int32_t s32; +''' + HEADER.replace('#include ', '') + r''' +static struct dcp_peer_frames_v27 paired(u32 first, u32 last) +{ + struct dcp_peer_frames_v27 s = { .active = true }; + + for (u32 id = first; id <= last; id++) + dcp_peer_frame_submit_v27(&s, id); + return s; +} + +int main(void) +{ + struct dcp_peer_frames_v27 s; + u32 w = 0; + bool shown = true; + + /* First modeset of a pair: both engines display swap 5. */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 5, true, &w, &shown)); + assert(w == 5 && shown); + + /* The peer's half of swap 5 was not displayed. */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 5, false, &w, &shown)); + assert(w == 5 && !shown); + + /* Neither half displayed (the owner's completion came second). */ + s = paired(5, 5); + assert(!dcp_peer_frame_complete_v27(&s, 1, 5, false, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 0, 5, false, &w, &shown)); + assert(w == 5 && !shown); + + /* + * Engines drift: the peer has shown 6 when the owner shows 5. The + * retired swap is 5, which the peer's shown 6 does not vouch for; + * swap 6 then retires shown. + */ + s = paired(5, 6); + assert(!dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(w == 5 && !shown); + assert(dcp_peer_frame_complete_v27(&s, 0, 6, true, &w, &shown)); + assert(w == 6 && shown); + + /* A displayed earlier swap does not mark a later, undisplayed one. */ + s = paired(5, 6); + assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); + assert(!dcp_peer_frame_complete_v27(&s, 0, 6, false, &w, &shown)); + assert(dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + assert(w == 6 && !shown); + + /* A stale or duplicate completion is not a retirement. */ + assert(!dcp_peer_frame_complete_v27(&s, 1, 6, true, &w, &shown)); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as t: + src = Path(t) / 'peer.c' + src.write_text(TEST) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', '-fsanitize=address,undefined', + str(src), '-o', str(src.with_suffix(''))], check=True) + if subprocess.run([str(src.with_suffix(''))]).returncode: + sys.exit(1) +print('PASS paired completion shown state: first modeset, undisplayed half, drift, stale shown, duplicate') diff --git a/tools/asahi/dcpext26-queue-tests.py b/tools/asahi/dcpext26-queue-tests.py index 76a4cafd6899bc..983a57a65ee25a 100644 --- a/tools/asahi/dcpext26-queue-tests.py +++ b/tools/asahi/dcpext26-queue-tests.py @@ -55,11 +55,12 @@ def function(name): struct drm_framebuffer {struct obj *obj[1];int refs;}; static void drm_framebuffer_get(struct drm_framebuffer *f){assert(f->refs>0);f->refs++;} static void drm_framebuffer_put(struct drm_framebuffer *f){assert(f->refs>1);f->refs--;} -struct drm_crtc {int unused;}; struct drm_plane {unsigned iomfb_surf;}; +struct drm_crtc {struct drm_plane *primary;}; #define to_apple_plane(p) (p) struct drm_plane_state {struct drm_crtc *crtc;bool visible;struct drm_framebuffer *fb;}; struct drm_atomic_commit {int refs,count;struct drm_plane plane[4];struct drm_plane_state old[4],new[4];}; +static struct drm_plane_state *drm_atomic_get_new_plane_state(struct drm_atomic_commit *s,struct drm_plane *p){for(int i=0;icount;i++)if(&s->plane[i]==p)return &s->new[i];return NULL;} #define for_each_oldnew_plane_in_state(s,p,o,n,i) for(i=0;i<(s)->count&&((p)=&(s)->plane[i],(o)=&(s)->old[i],(n)=&(s)->new[i],1);i++) static struct drm_atomic_commit *drm_atomic_commit_get(struct drm_atomic_commit *s){s->refs++;return s;} static void drm_atomic_commit_put(struct drm_atomic_commit *s){assert(s->refs>1);s->refs--;} @@ -79,7 +80,7 @@ def function(name): struct {bool pending;} present_state_h17p;struct {bool valid;} mode_state;struct {bool connected;} *connector; struct {void *data;} chunks;bool native,crashed,ext26_control_pending,ext26_blanked,ext26_normal,ext26_early_complete; unsigned ext26_epochs;u64 ext26_retained_bytes;struct list_head ext26_retained; - int fw_compat;struct work_struct vblank_wq,bl_update_wq; + int fw_compat;bool boot_surface_pending;struct work_struct vblank_wq,bl_update_wq; }; static void iomfb_v27_sleep_start(struct apple_dcp *d, struct iomfb_transaction *t) { } #define DCP_FIRMWARE_V_27_0 27 diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index c3cecff8b36dde..b650bca3977b97 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -66,6 +66,7 @@ def mutations(flag, names, base, expect=KILL): (['--final-skips-unresolved'], KILL), (['--detach-retired-only'], KILL), (['--resume-after-detach'], KILL)], + 'dcp-peer-shown-tests.py': [([], PASS), (['--always-shown'], KILL), (['--owner-only'], KILL)], 'dcpext26-queue-tests.py': [([], PASS), (['--drop-v27-close'], KILL)], 'dcpext26-retrain-tests.py': [([], PASS), (['--negative-control'], KILL)], 'dcpext26-lifecycle-tests.py': [([], PASS)], From 5c61e0295fc3f57afb419c13b2eea0cb1195e205 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:11:19 -0500 Subject: [PATCH 0237/1514] dt-bindings: spmi: apple,spmi: add apple,response-vector Document the optional apple,response-vector property for gen-1 Apple SPMI controllers so a devicetree node can state its RX FIFO command-response vector (and peripheral interrupt count) directly instead of deriving it from compatible-string position. Disallow it on generation 4 ("apple,t8142-spmi") controllers, which do not use the gen-1 interrupt layout. Signed-off-by: Erik Bourget --- .../devicetree/bindings/spmi/apple,spmi.yaml | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml index 48706095da208b..e9226980635f29 100644 --- a/Documentation/devicetree/bindings/spmi/apple,spmi.yaml +++ b/Documentation/devicetree/bindings/spmi/apple,spmi.yaml @@ -13,6 +13,14 @@ description: A SPMI controller present on most Apple SoCs allOf: - $ref: spmi.yaml# + - if: + properties: + compatible: + contains: + const: apple,t8142-spmi + then: + properties: + apple,response-vector: false properties: compatible: @@ -63,6 +71,19 @@ properties: "#interrupt-cells": const: 2 + apple,response-vector: + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 64 + maximum: 256 + multipleOf: 64 + description: + Controller vector index for the RX FIFO command-response notification on + gen-1 controllers. Peripheral interrupts occupy vectors 0 through N-1, so + this also gives the peripheral interrupt count. When omitted, the driver + uses the compatible's default (192 for T6000, 256 for other gen-1 + controllers). Not applicable to generation 4 controllers + ("apple,t8142-spmi"). + power-domains: maxItems: 1 From d05dde0ba28211f7d738fa2b36af2331e630f761 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:42:43 -0500 Subject: [PATCH 0238/1514] arm64: dts: apple: t8103: describe nub-spmi response vector T8103's nub-spmi reports command replies on vector 192 (the first interrupt listed in the ADT's nub-spmi node). Publish apple,response-vector = <192> on nub_spmi before wiring its interrupt or teaching spmi-apple-controller to read the property; kernels without support continue polling as before. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 38978c3675d3dc..0c216e45ae54f6 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1209,6 +1209,7 @@ reg = <0x2 0x3d0d9300 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; + apple,response-vector = <192>; pmic1: pmic@f { compatible = "apple,sera-pmic", "apple,spmi-nvmem"; From ec141ba114c722be8fdb8d995c7da6fd2f69e0da Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:11:20 -0500 Subject: [PATCH 0239/1514] spmi: apple: read command response vector from DT T8103's SPMI controllers report command replies on vector 192 (matching the first interrupt entry in the ADT's nub-spmi node), while later SoCs that list "apple,t8103-spmi" as a fallback compatible use 256 vectors. Store the active vector count per controller instance, defaulting to the match-table value (256 for gen-1, 192 for T6000) and allowing gen-1 nodes to override it via the apple,response-vector DT property (validated as a non-zero multiple of 64 up to SPMI_MAX_PERIPHERAL_IRQS). Warn if apple,response-vector is present on a generation 4 controller where the legacy interrupt layout is unused. Existing DTBs without the property keep their current behavior. Signed-off-by: Erik Bourget --- drivers/spmi/spmi-apple-controller.c | 51 +++++++++++++++++++++------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index c5f8829cfeb455..30d2916378626e 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -110,6 +110,7 @@ struct apple_spmi { void __iomem *faults; unsigned int nfaults; const struct apple_spmi_hw *hw; + u32 num_irqs; struct mutex fifo_lock; struct completion fifo_rx; struct irq_domain *irqd; @@ -282,7 +283,7 @@ static int __spmi_raw_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid, u16 para return ret; } else { writel(SPMI_ACT_FIFO_FLUSH, spmi->regs + SPMI_ACT_REG); - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); } spmi->prev_fail = false; } @@ -451,7 +452,7 @@ static int apple_spmi_irq_domain_translate(struct irq_domain *irqd, if (fwspec->param_count != 2) return -EINVAL; - if (args[0] >= spmi->hw->num_irqs) + if (args[0] >= spmi->num_irqs) return -EINVAL; *hwirq = args[0]; *type = args[1] & IRQ_TYPE_SENSE_MASK; @@ -471,7 +472,7 @@ static int apple_spmi_irq_domain_alloc(struct irq_domain *irqd, unsigned int vir if (ret) return ret; - if (hwirq + nr_irqs > spmi->hw->num_irqs) + if (hwirq + nr_irqs > spmi->num_irqs) return -EINVAL; for (i = 0; i < nr_irqs; i++) { @@ -508,7 +509,7 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) { struct apple_spmi *spmi = irq_desc_get_handler_data(desc); struct irq_chip *chip = irq_desc_get_chip(desc); - u32 notify = spmi->hw->num_irqs; + u32 notify = spmi->num_irqs; bool handled = false, held = false, raw_pending = false; unsigned long val, offset, bit; @@ -579,7 +580,7 @@ static void apple_spmi_teardown_irq(void *data) { struct apple_spmi *spmi = data; - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) + for (size_t offset = 0; offset < (spmi->num_irqs + 32) / 8; offset += 4) writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); synchronize_irq(spmi->irq); @@ -599,7 +600,7 @@ static int apple_spmi_init_irq(struct platform_device *pdev, raw_spin_lock_init(&spmi->irq_mask_lock); - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) { + for (size_t offset = 0; offset < (spmi->num_irqs + 32) / 8; offset += 4) { writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); writel(U32_MAX, spmi->regs + SPMI_IRQ_ACK_BASE + offset); } @@ -613,7 +614,7 @@ static int apple_spmi_init_irq(struct platform_device *pdev, return ret; irq_set_chained_handler_and_data(spmi->irq, apple_spmi_irq_handler, spmi); - apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_unmask_raw(spmi, spmi->num_irqs); spmi->notify_irq = true; return 0; @@ -639,8 +640,8 @@ static int apple_spmi_suspend_noirq(struct device *dev) spmi->notify_irq = false; spmi->notify_parked = true; raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); - apple_spmi_irq_mask_raw(spmi, spmi->hw->num_irqs); - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_mask_raw(spmi, spmi->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); return 0; @@ -660,12 +661,12 @@ static int apple_spmi_resume_noirq(struct device *dev) raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); /* Whether the enables survive a real sleep has not been measured. */ if (pm_resume_via_firmware()) { - bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->hw->num_irqs); - for (i = 0; i < spmi->hw->num_irqs / 32; i++) + bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->num_irqs); + for (i = 0; i < spmi->num_irqs / 32; i++) writel(words[i], spmi->regs + SPMI_IRQ_MASK_BASE + i * 4); } - apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); - apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); + apple_spmi_irq_ack_raw(spmi, spmi->num_irqs); + apple_spmi_irq_unmask_raw(spmi, spmi->num_irqs); raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); spmi->notify_parked = false; spmi->notify_irq = true; @@ -690,6 +691,30 @@ static int apple_spmi_probe(struct platform_device *pdev) spmi->hw = device_get_match_data(&pdev->dev); if (!spmi->hw) return -EINVAL; + spmi->num_irqs = spmi->hw->num_irqs; + if (spmi->hw->legacy_irqs) { + u32 response_vector; + + ret = of_property_read_u32(pdev->dev.of_node, + "apple,response-vector", + &response_vector); + if (!ret) { + if (!response_vector || + response_vector > SPMI_MAX_PERIPHERAL_IRQS || + response_vector % 64) + return dev_err_probe(&pdev->dev, -EINVAL, + "invalid apple,response-vector %u\n", + response_vector); + spmi->num_irqs = response_vector; + } else if (ret != -EINVAL) { + return dev_err_probe(&pdev->dev, ret, + "failed to read apple,response-vector\n"); + } + } else if (of_property_present(pdev->dev.of_node, + "apple,response-vector")) { + dev_warn(&pdev->dev, + "ignoring apple,response-vector on generation 4 controller\n"); + } mutex_init(&spmi->fifo_lock); init_completion(&spmi->fifo_rx); platform_set_drvdata(pdev, spmi); From faae4f12ac1db551128cceb59368d7b51b51c1f0 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:37:35 -0500 Subject: [PATCH 0240/1514] nvmem: apple-spmi: populate Sera's child nodes M1's PMU (Sera) carries an RTC child node like the other Apple PMUs; populate its child platform devices in probe. Signed-off-by: Erik Bourget --- drivers/nvmem/apple-spmi-nvmem.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/nvmem/apple-spmi-nvmem.c b/drivers/nvmem/apple-spmi-nvmem.c index b31b8212d3fcc0..6a270ccb9aca81 100644 --- a/drivers/nvmem/apple-spmi-nvmem.c +++ b/drivers/nvmem/apple-spmi-nvmem.c @@ -65,7 +65,8 @@ static int apple_spmi_nvmem_probe(struct spmi_device *sdev) !of_device_is_compatible(sdev->dev.of_node, "apple,abbey-pmic") && !of_device_is_compatible(sdev->dev.of_node, "apple,chapel-pmic") && !of_device_is_compatible(sdev->dev.of_node, "apple,maverick-pmic") && - !of_device_is_compatible(sdev->dev.of_node, "apple,stowe-pmic")) + !of_device_is_compatible(sdev->dev.of_node, "apple,stowe-pmic") && + !of_device_is_compatible(sdev->dev.of_node, "apple,sera-pmic")) return 0; return devm_of_platform_populate(&sdev->dev); From 76f6062b812e236db0dc6920bf2b30ac9d7d75cc Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 20 Nov 2026 03:00:45 -0500 Subject: [PATCH 0241/1514] drm/asahi: enable two render pairs per queue on G17C Enable two physical render pairs per logical render queue on 4+ cluster M5 parts (40-core G17C and 80-core G17D, 8-16 GiB render-pool inventory), where a single physical render ring underutilizes the wider shader array across back-to-back deep renders. Narrower M5 parts (1-cluster J813 and 2-cluster J714, 2-4 GiB inventory) keep one pair per queue to avoid the extra per-pair ring/graph/PB footprint and doubled ray-query render-pool extras until measured. Preserve both full logical queue capacity and guaranteed first-pair capacity when two pairs per owner are enabled: - Track explicit pair publication (`State::published`) so unpublished siblings yield before published ones, and gate `note_published()` on a live, unclosed slot so a slot released while a lease was out cannot have `published` re-set. - Allow idle, drained published siblings (no active lease/refs, no in-flight footprint, `Pair::detachable()` true, owner retains another usable pair) to detach on demand via `Pair::release_owner()` while keeping their installed QIDs (`released |= bit`, `owners[slot]` kept to identify the previous owner until reuse, `published` cleared) so new queues reuse the installed QIDs via `bind_owner()`. When a later owner rebinds a detached slot whose prior owner is still open, `rebind_pair()` passes `entry.closed` to `teardown.displace()`, deferring context teardown until the prior owner closes instead of draining its live scheduler. - Count only non-reclaimable live siblings and teardown-held released pairs in `Pool::pair_demand()` / `Pool::render_demand()`, while `Pool::try_reserve_queue_reclaiming()` and `Backend::new()` reclaim idle siblings (unbuilt, parked, reusable/warmed unpublished, or idle drained published) before refusing a new logical queue. - Gate every lease that would promote an idle reclaimable sibling into protected demand (`acquire_for`, `join_for`, `can_pick_for`, and `warmable_sibling`) against `render_capacity` under the admission lock so compute growth cannot leave an open queue without a first pair. - Account for cancelable unpublished render spares in compute readiness (`compute_qid_fits`) and reservation (`reserve_compute_reclaiming`), cancelling one idle unpublished spare before reserving a fresh compute QID on a full table and dropping reclaimed backing off-lock. - In `QueueIds::compute_room()`, cap future queue headroom at `FULL_RENDER_RESERVE - floor` while always protecting current pair demand (`2 * pairs + 2`), and size `QueueIds::reserve()` for `queue_limit(floor)` open queues so a floored table does not lock out compute. - Add KUnit coverage for sibling reclamation up to full queue capacity including published siblings, busy published protection vs idle published detachment and `note_published` on released slots, compute-shrink sibling gating, full-table compute admission with cancelable siblings, teardown-held released pairs, and compute reserve above `MAX_EXECUTION_CONTEXTS`; update the host tests accordingly. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/kick.rs | 83 +- drivers/gpu/drm/asahi/g17/pairs.rs | 29 +- drivers/gpu/drm/asahi/g17/queue/admission.rs | 878 ++++++++++++++++-- drivers/gpu/drm/asahi/g17/queue/render.rs | 11 +- drivers/gpu/drm/asahi/g17/runtime.rs | 194 +++- drivers/gpu/drm/asahi/g17/runtime/render.rs | 260 +++++- .../drm/asahi/g17/runtime/render/direct.rs | 7 +- .../drm/asahi/g17/runtime/render/prepare.rs | 5 +- .../drm/asahi/g17/runtime/render/submit.rs | 9 + drivers/gpu/drm/asahi/hw/t8140.rs | 2 +- tools/asahi/g17-admission-deadline-tests.py | 11 +- tools/asahi/g17-admission-order-tests.py | 32 +- tools/asahi/g17-pool-release-tests.py | 8 +- tools/asahi/g17-quarantine-drain-tests.py | 7 +- tools/asahi/g17-resource-tests.py | 8 +- 15 files changed, 1401 insertions(+), 143 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 5f49bf1b5093d8..5b03f1766c728c 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -56,8 +56,9 @@ const _: () = { assert!(queue_limit(0) == crate::mmu::MAX_EXECUTION_CONTEXTS); // Compute keeps this many channels even with every execution context open. assert!(QID_COUNT - FULL_RENDER_RESERVE >= 4); - // The reserve counts one pair per owner. A second pair of an owner comes - // only from surplus (g17::pairs), never from this reserve. + // Future queue headroom caps at one pair per execution context; compute + // reservation still protects current pair demand (including live siblings + // and teardown-held released pairs) above that cap. assert!(FULL_RENDER_RESERVE == 2 * crate::mmu::MAX_EXECUTION_CONTEXTS as usize + 2); }; @@ -130,7 +131,7 @@ impl QueueIds { engine: DataMaster, preferred: Option, ) -> Result { - self.reserve_for(owner, engine, preferred, crate::mmu::MAX_EXECUTION_CONTEXTS as usize) + self.reserve_for(owner, engine, preferred, queue_limit(self.floor) as usize) } fn render_ids(&self) -> usize { @@ -141,10 +142,18 @@ impl QueueIds { .count() } + /// Total dedicated render pairs the QID table can hold beside the + /// bootstrap reservations and installed compute channels. + pub(crate) fn render_pair_capacity(&self) -> usize { + (self.render_ids() + (QID_COUNT - self.floor - self.leased)) + .saturating_sub(2) + / 2 + } + /// Whether `queues` open logical queues can each still install a dedicated /// render pair, beside the bootstrap reservations and installed compute. pub(crate) fn render_fits(&self, queues: usize) -> bool { - self.render_ids() + (QID_COUNT - self.floor - self.leased) >= 2 * queues + 2 + self.render_pair_capacity() >= queues } /// Whether a render pair not yet built can still reserve both of its identities. @@ -155,22 +164,38 @@ impl QueueIds { /// Whether a fresh compute identity fits beside the render reserve of /// `queues` open logical queues, without reserving it. pub(crate) fn compute_fits(&self, queues: usize) -> bool { + self.compute_fits_with_reclaim(queues, 0) + } + + /// Whether a fresh compute identity fits once `reclaim_render_ids` + /// unpublished render identities are cancelled first. + pub(crate) fn compute_fits_with_reclaim( + &self, + queues: usize, + reclaim_render_ids: usize, + ) -> bool { let initial = self.leased == QID_COUNT - self.floor && self.initial_render.iter().flatten().any(|id| self.can_cancel_unpublished(*id)); - self.compute_room(queues, usize::from(initial)) + self.compute_room(queues, usize::from(initial).max(reclaim_render_ids)) } - fn compute_room(&self, queues: usize, replacement: usize) -> bool { + fn compute_room(&self, pairs: usize, replacement: usize) -> bool { // Existing render identities already satisfy this reservation. Counting // them twice can refuse compute even while physical QIDs remain free. // Replacing an initial reservation consumes one render identity. // Include that transition when protecting render's minimum, and // count the replacement as available compute capacity. + // + // Cap future queue headroom at `FULL_RENDER_RESERVE - self.floor`, but + // always protect every pair in current demand (`2 * pairs + 2`) so + // compute cannot strand an open queue when live siblings or + // teardown-held pairs push demand above `queue_limit(self.floor)`. let render = self.render_ids(); + let current = 2 * pairs + 2; + let with_headroom = render_reserve(pairs).min(FULL_RENDER_RESERVE - self.floor); + let reserve = current.max(with_headroom); QID_COUNT - self.floor - self.leased + replacement - > render_reserve(queues) - .min(FULL_RENDER_RESERVE - self.floor) - .saturating_sub(render - replacement) + > reserve.saturating_sub(render.saturating_sub(replacement)) } /// As [`Self::reserve`], with the compute reserve sized for `queues` open @@ -388,6 +413,46 @@ mod accounting_tests { assert_eq!(ids.leased, QID_COUNT); assert_eq!(ids.reserve(1002, DataMaster::Fragment, None), Err(EINVAL)); } + + #[test] + fn compute_reserve_protects_sibling_demand_above_context_limit() { + let mut ids = table(); + ids.reserve_initial_render().unwrap(); + let max = crate::mmu::MAX_EXECUTION_CONTEXTS as usize; + // 58 open queues + 1 live sibling = 59 pairs demand (above MAX_EXECUTION_CONTEXTS). + let demand = max + 1; + // Install 57 first pairs + 1 sibling = 58 pairs (116 render IDs) plus 2 bootstrap IDs. + let mut owner = 100u64; + for _ in 0..max { + let t = ids.reserve_for(owner, DataMaster::Tiling, None, demand).unwrap(); + ids.publish(t).unwrap(); + owner += 1; + let f = ids.reserve_for(owner, DataMaster::Fragment, None, demand).unwrap(); + ids.publish(f).unwrap(); + owner += 1; + } + // Compute takes all remaining QIDs except the 2 needed for the 58th queue's first pair. + let compute_budget = QID_COUNT - (2 * demand + 2); + for _ in 0..compute_budget { + let c = ids.reserve_for(owner, DataMaster::Compute, None, demand).unwrap(); + ids.publish(c).unwrap(); + owner += 1; + } + assert_eq!(ids.render_pair_capacity(), demand); + assert!(!ids.compute_fits(demand)); + assert_eq!( + ids.reserve_for(owner, DataMaster::Compute, None, demand), + Err(ENOSPC) + ); + // The last open queue can still install its first pair. + assert!(ids.render_pair_fits()); + let t = ids.reserve_for(owner, DataMaster::Tiling, None, demand).unwrap(); + let f = ids + .reserve_for(owner + 1, DataMaster::Fragment, None, demand) + .unwrap(); + ids.publish(t).unwrap(); + ids.publish(f).unwrap(); + } } // Aliases drop before their backing. A compute queue is allocated low first; diff --git a/drivers/gpu/drm/asahi/g17/pairs.rs b/drivers/gpu/drm/asahi/g17/pairs.rs index c7515c1c764171..405718f78bf4a0 100644 --- a/drivers/gpu/drm/asahi/g17/pairs.rs +++ b/drivers/gpu/drm/asahi/g17/pairs.rs @@ -1,12 +1,22 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Render pairs one logical render queue may hold: two on the G17D (M5 Ultra), one elsewhere. +//! Render pairs one logical render queue may hold: two on G17C and G17D (4+ clusters), +//! one elsewhere. //! //! A second pair lets one queue's depth run on two physical render rings. It comes only from -//! surplus: the QID budget ([`super::kick::render_reserve`]) keeps counting one pair per open -//! queue, admission claims a sibling only while a pair can still be built, and an unused -//! sibling is reassigned to an owner that needs a first pair. An owner's overlapping renders on -//! its two pairs are ordered in firmware ([`super::hazard::plan`]). +//! surplus: the QID budget ([`super::kick::render_reserve`]) reserves one pair for every live +//! render demand (open queues, non-reclaimable siblings, and teardown-held released pairs) plus +//! headroom for future queues, admission claims a released pair only while surplus first-pair +//! capacity remains and builds a fresh sibling only while a pair can also be built, and an unused +//! sibling is reclaimed before refusing a new logical queue or reassigned to an owner that needs a +//! first pair. An owner's overlapping renders on its two pairs are ordered in firmware +//! ([`super::hazard::plan`]). +//! +//! Two pairs are enabled at 4+ GPU clusters (40-core G17C and 80-core G17D, 8-16 GiB render-pool +//! inventory), where a single physical render ring underutilizes the wider shader array across +//! back-to-back deep renders. Narrower M5 parts (1-cluster J813, 2-cluster J714, 2-4 GiB +//! inventory) keep one pair per queue to avoid the extra per-pair ring/graph/PB footprint and +//! doubled ray-query render-pool extras (`fw::render_rt::required_blocks`) until measured. //! //! A queue samples the count once, when it is created ([`per_owner`]): its scheduler credits, //! render pool and pair limit all follow that one value. @@ -15,14 +25,17 @@ use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; use crate::hw::t8140::queues::RENDER_PAIRS_MAX; -/// G17D's count. -const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8; +/// Multi-pair count for large multi-cluster M5 parts (G17C/G17D). +const MULTI_PAIRS: u8 = RENDER_PAIRS_MAX as u8; static PAIRS: AtomicU8 = AtomicU8::new(1); /// The count for the probed board, set once at probe (one GPU per system). pub(crate) fn select_board(board: &crate::g17::fw::m5::initdata::Board) { - PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed); + PAIRS.store( + if board.clusters >= 4 { MULTI_PAIRS } else { 1 }, + Relaxed, + ); } /// Render pairs a logical render queue created now may hold. diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index cc93cb6167981b..e0daa71b28c421 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -90,6 +90,14 @@ struct State { /// The physical queue table still has room for a pair built in an unowned slot. The /// runtime updates this whenever the table changes. build_room: bool, + /// Total dedicated render pairs the QID table can hold (installed plus buildable). + /// Updated alongside `build_room` so sibling admission preserves first-pair capacity. + render_capacity: usize, + /// Live slots on which the current owner has published (or started) a + /// firmware-visible render graph; unpublished siblings yield before + /// published ones, and reclaiming a published sibling keeps its installed + /// QIDs in the `released` state for `bind_owner()` reuse. + published: u64, released: u64, epoch: u64, footprints: KVec, @@ -112,12 +120,50 @@ impl State { killed_at: [0; cfg::RENDER_SLOTS], held: 0, build_room: true, + render_capacity: cfg::RENDER_SLOTS - 1, + published: 0, released: 0, epoch: 0, footprints: KVec::new(), next_ticket: 1, } } + fn owns_live(&self, owner: u64, slot: usize) -> bool { + self.owners.get(slot) == Some(&owner) && self.released & (1u64 << slot) == 0 + } + fn has_live_owner(&self, owner: u64) -> bool { + (1..cfg::RENDER_SLOTS).any(|slot| self.owns_live(owner, slot)) + } + fn live_owners(&self) -> usize { + let mut count = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if !(1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + count += 1; + } + } + count + } + fn live_siblings(&self) -> usize { + let mut siblings = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if (1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + siblings += 1; + } + } + siblings + } fn exhausted(&self) -> bool { self.quarantined & Self::MASK == Self::MASK } @@ -127,7 +173,7 @@ impl State { /// sibling never bypasses it. fn owner_quarantine(&self, owner: u64) -> Option { let owned = (0..cfg::RENDER_SLOTS) - .filter(|slot| self.owners[*slot] == owner) + .filter(|slot| self.owns_live(owner, *slot)) .fold(0u64, |mask, slot| mask | 1u64 << slot); let quarantined = self.quarantined & owned; (quarantined != 0).then_some(quarantined & !self.spared == 0) @@ -139,34 +185,36 @@ impl State { if self.owner_quarantine(owner).is_some() { return Err(EIO); } - match self.owners.iter().position(|id| *id == owner) { - None if !self.owners[1..].contains(&0) - && self.released - & !self.active - & !self.quarantined - & !self.kill_hold + if !self.has_live_owner(owner) + && !self.owners[1..].contains(&0) + && self.released + & !self.active + & !self.quarantined + & !self.kill_hold & !self.held - & Self::MASK - == 0 => - { - Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RenderSlots)) - } - _ => Ok(()), + & Self::MASK + == 0 + { + return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RenderSlots)); } + Ok(()) } fn advance(&mut self, slot: usize) { self.epoch = self.epoch.wrapping_add(1); self.epochs[slot] = self.epoch; } fn take_idle(&mut self, slot: usize, owner: u64) -> u8 { - if self.owners[slot] != owner { - crate::g17::trace::teardown( - 6, - slot as u64, - self.owners[slot], - owner | u64::from(self.killed & (1u64 << slot) != 0) << 63, - ); + if self.owners[slot] != owner || self.released & (1u64 << slot) != 0 { + if self.owners[slot] != owner { + crate::g17::trace::teardown( + 6, + slot as u64, + self.owners[slot], + owner | u64::from(self.killed & (1u64 << slot) != 0) << 63, + ); + } self.killed &= !(1u64 << slot); + self.published &= !(1u64 << slot); } self.refs[slot] += 1; self.active |= 1u64 << slot; @@ -175,7 +223,11 @@ impl State { self.advance(slot); slot as u8 } + #[cfg(CONFIG_KUNIT = "y")] fn acquire(&mut self, owner: u64, pairs: usize) -> Option { + self.acquire_for(owner, pairs, 0) + } + fn acquire_for(&mut self, owner: u64, pairs: usize, open_queues: usize) -> Option { if owner == 0 { return None; } @@ -201,25 +253,26 @@ impl State { // only while this owner has no live kick, before constructing it. let idle = (0..cfg::RENDER_SLOTS) .filter(|slot| { - self.owners[*slot] == owner + self.owns_live(owner, *slot) && self.refs[*slot] == 0 && self.quarantined & (1u64 << slot) == 0 + && self.can_lease_slot(owner, *slot, open_queues) }) .max_by_key(|slot| (self.epochs[*slot], usize::MAX - *slot)); if let Some(slot) = idle { if !(0..cfg::RENDER_SLOTS) - .any(|other| self.owners[other] == owner && self.refs[other] != 0) + .any(|other| self.owns_live(owner, other) && self.refs[other] != 0) { - self.claim_sibling(owner, pairs); + self.claim_sibling(owner, pairs, open_queues); } return Some(self.take_idle(slot, owner)); } - if self.owners.contains(&owner) { + if self.has_live_owner(owner) { // Consecutive kicks are ordered by firmware dependencies. Stack // onto the least-loaded retained pair without a retirement wait. let slot = (0..cfg::RENDER_SLOTS) .filter(|slot| { - self.owners[*slot] == owner + self.owns_live(owner, *slot) && self.quarantined & (1u64 << slot) == 0 && self.active & (1u64 << slot) != 0 && self.refs[*slot] < cfg::RENDER_DEPTH @@ -249,12 +302,133 @@ impl State { }) .or_else(unowned)?; let first = self.take_idle(slot, owner); - self.claim_sibling(owner, pairs); + self.claim_sibling(owner, pairs, open_queues); Some(first) } - /// Claims another pair for an owner that may hold `pairs`. - fn claim_sibling(&mut self, owner: u64, pairs: usize) { - if self.owners.iter().filter(|id| **id == owner).count() >= pairs { + fn unavailable_released(&self) -> usize { + (self.released + & (self.active | self.quarantined | self.kill_hold | self.held) + & Self::MASK) + .count_ones() as usize + } + + /// Idle live siblings in `eligible` (unpublished or drained published) + /// that can be given back without taking any live owner's last usable pair. + fn reclaimable_siblings_in(&self, eligible: u64) -> usize { + let unavailable = self.quarantined | self.kill_hold | self.held; + let mut reclaimable = 0usize; + for slot in 1..cfg::RENDER_SLOTS { + let owner = self.owners[slot]; + if owner == 0 || self.released & (1u64 << slot) != 0 { + continue; + } + if (1..slot).any(|prev| { + self.owners[prev] == owner && self.released & (1u64 << prev) == 0 + }) { + continue; + } + let mut usable = 0usize; + let mut candidates = 0usize; + for s in slot..cfg::RENDER_SLOTS { + let bit = 1u64 << s; + if self.owners[s] != owner || self.released & bit != 0 { + continue; + } + if unavailable & bit == 0 { + usable += 1; + if eligible & bit != 0 + && self.refs[s] == 0 + && (self.active | self.killed) & bit == 0 + { + candidates += 1; + } + } + } + reclaimable += candidates.min(usable.saturating_sub(1)); + } + reclaimable + } + + fn reclaimable_siblings(&self) -> usize { + self.reclaimable_siblings_in(Self::MASK) + } + + /// Whether leasing `slot` for live `owner` would turn a reclaimable + /// sibling into protected (non-reclaimable) demand. + fn promotes_reclaimable_sibling(&self, owner: u64, slot: usize) -> bool { + if slot == 0 || slot >= cfg::RENDER_SLOTS || owner == 0 { + return false; + } + let bit = 1u64 << slot; + let unavailable = self.quarantined | self.kill_hold | self.held; + if self.owners[slot] != owner + || self.released & bit != 0 + || self.refs[slot] != 0 + || (unavailable | self.active | self.killed) & bit != 0 + { + return false; + } + let mut usable = 0usize; + let mut candidates = 0usize; + for s in 1..cfg::RENDER_SLOTS { + let sbit = 1u64 << s; + if self.owners[s] != owner || self.released & sbit != 0 { + continue; + } + if unavailable & sbit == 0 { + usable += 1; + if self.refs[s] == 0 && (self.active | self.killed) & sbit == 0 { + candidates += 1; + } + } + } + usable > 1 && candidates < usable + } + + /// Whether `owner` may take a lease on `slot` without pushing protected + /// demand above `render_capacity`. + fn can_lease_slot(&self, owner: u64, slot: usize, open_queues: usize) -> bool { + if !self.promotes_reclaimable_sibling(owner, slot) { + return true; + } + let cap = self.render_capacity.min(cfg::RENDER_SLOTS - 1); + self.pair_demand(open_queues).saturating_add(1) <= cap + } + + /// All render pairs currently spoken for, including reclaimable siblings + /// claimed from surplus. + fn total_pair_demand(&self, open_queues: usize) -> usize { + open_queues + .max(self.live_owners()) + .saturating_add(self.live_siblings()) + .saturating_add(self.unavailable_released()) + } + + /// Render pairs that cannot be given back: one first pair per open logical + /// queue, non-reclaimable live siblings (busy, quarantined, or held), and + /// teardown-held released pairs. + fn pair_demand(&self, open_queues: usize) -> usize { + open_queues + .max(self.live_owners()) + .saturating_add( + self.live_siblings() + .saturating_sub(self.reclaimable_siblings()), + ) + .saturating_add(self.unavailable_released()) + } + + /// Claims another pair for an owner that may hold `pairs`, while keeping + /// first-pair capacity for every open logical queue. + fn claim_sibling(&mut self, owner: u64, pairs: usize, open_queues: usize) { + if (1..cfg::RENDER_SLOTS) + .filter(|slot| self.owns_live(owner, *slot)) + .count() + >= pairs + { + return; + } + let needed = self.total_pair_demand(open_queues).saturating_add(1); + if needed > self.render_capacity.min(cfg::RENDER_SLOTS - 1) { return; } // A speculative sibling never takes a killed context's pair. @@ -277,19 +451,16 @@ impl State { }); if let Some(slot) = sibling { self.released &= !(1u64 << slot); + self.published &= !(1u64 << slot); self.owners[slot] = owner; // A speculative sibling has no GPU-use recency yet. self.epochs[slot] = 0; } } - /// The device lock separately proves the physical graph was never published. - /// An open owner keeps another usable pair. Exclude every live borrower, - /// including off-lock sibling construction; a closed owner needs no spare. - /// A spare goes only to an owner without a pair: a second pair comes only - /// from surplus, through claim_sibling. - fn reassign_unused_spare( - &mut self, + /// Whether [`Self::reassign_unused_spare`] would accept `slot` right now. + fn can_reassign_unused_spare( + &self, slot: u8, expected: Option, owner: Option, @@ -297,16 +468,13 @@ impl State { let slot = usize::from(slot); if slot == 0 || slot >= cfg::RENDER_SLOTS - || owner.is_some_and(|owner| { - owner == 0 - || self.owners.contains(&owner) - }) + || owner.is_some_and(|owner| owner == 0 || self.has_live_owner(owner)) { return false; } let bit = 1u64 << slot; let old = self.owners[slot]; - if old == 0 + !(old == 0 || self.killed & bit != 0 || owner == Some(old) || expected.is_some_and(|expected| expected != old) @@ -316,16 +484,81 @@ impl State { && !self.owners.iter().enumerate().any(|(other, value)| { other != slot && *value == old + && self.released & (1u64 << other) == 0 && (self.quarantined | self.kill_hold | self.held) & (1u64 << other) == 0 - })) - { + }))) + } + /// The device lock separately proves the physical graph was never published. + /// An open owner keeps another usable pair. Exclude every live borrower, + /// including off-lock sibling construction; a closed owner needs no spare. + /// A spare goes only to an owner without a pair: a second pair comes only + /// from surplus, through claim_sibling. + fn reassign_unused_spare( + &mut self, + slot: u8, + expected: Option, + owner: Option, + ) -> bool { + if !self.can_reassign_unused_spare(slot, expected, owner) { return false; } + let slot = usize::from(slot); + let bit = 1u64 << slot; self.owners[slot] = owner.unwrap_or(0); self.released &= !bit; + self.published &= !bit; self.epochs[slot] = 0; true } + /// Reclaims an idle live sibling. When `keep_installed` is true, its + /// physical slot retains installed render QIDs for reuse, so `owners[slot]` + /// stays set with `released` marked (the same invariant as `release_owner`); + /// otherwise the slot returns to the unowned state. + fn release_unused_sibling( + &mut self, + slot: u8, + expected: Option, + keep_installed: bool, + ) -> bool { + let index = usize::from(slot); + if index == 0 || index >= cfg::RENDER_SLOTS { + return false; + } + let bit = 1u64 << index; + if self.released & bit != 0 { + return false; + } + if !self.can_reassign_unused_spare(slot, expected, None) { + return false; + } + if keep_installed { + self.released |= bit; + } else { + self.owners[index] = 0; + self.released &= !bit; + } + self.published &= !bit; + self.epochs[index] = 0; + true + } + /// Takes back one idle live sibling in `eligible`, preferring unpublished + /// siblings before published ones. Slots in `installed` or `published` keep + /// `released` set so their installed QIDs are reused first. + fn reclaim_sibling(&mut self, eligible: u64, installed: u64) -> Option { + for allow_published in [false, true] { + for slot in 1..cfg::RENDER_SLOTS { + let bit = 1u64 << slot; + if eligible & bit == 0 || (!allow_published && self.published & bit != 0) { + continue; + } + let keep_installed = (installed | self.published) & bit != 0; + if self.release_unused_sibling(slot as u8, None, keep_installed) { + return Some(slot as u8); + } + } + } + None + } fn warmable_sibling(&self, owner: u64, publishing: u8) -> Option { if self.refs.get(usize::from(publishing)) != Some(&1) { return None; @@ -355,6 +588,7 @@ impl State { { self.owners[slot] = 0; self.released &= !bit; + self.published &= !bit; self.epochs[slot] = 0; true } else { @@ -384,14 +618,21 @@ impl State { } /// Whether `pick` would return a slot, without taking it. + #[cfg(CONFIG_KUNIT = "y")] fn can_pick(&self, owner: u64, plan: Plan) -> bool { - let usable = |slot: usize| self.usable(owner, slot); + self.can_pick_for(owner, 0, plan) + } + + /// Whether `pick_for` would return a slot, without taking it. + fn can_pick_for(&self, owner: u64, open_queues: usize, plan: Plan) -> bool { + let usable = + |slot: usize| self.usable(owner, slot) && self.can_lease_slot(owner, slot, open_queues); match plan { Plan::Wait => false, Plan::Pair(slot) => usable(usize::from(slot)), Plan::Join(_) => (0..cfg::RENDER_SLOTS).any(usable), Plan::Any if owner == 0 => false, - Plan::Any if self.owners.contains(&owner) => (0..cfg::RENDER_SLOTS).any(usable), + Plan::Any if self.has_live_owner(owner) => (0..cfg::RENDER_SLOTS).any(usable), Plan::Any => { let free = !self.active & Self::MASK & !self.quarantined & !self.kill_hold & !self.held; (0..cfg::RENDER_SLOTS).any(|slot| { @@ -402,28 +643,49 @@ impl State { } } + #[cfg(CONFIG_KUNIT = "y")] fn pick(&mut self, owner: u64, pairs: usize, plan: Plan) -> Option { + self.pick_for(owner, pairs, 0, plan) + } + + fn pick_for( + &mut self, + owner: u64, + pairs: usize, + open_queues: usize, + plan: Plan, + ) -> Option { match plan { - Plan::Any => self.acquire(owner, pairs), + Plan::Any => self.acquire_for(owner, pairs, open_queues), Plan::Wait => None, - Plan::Pair(slot) => self.join(owner, usize::from(slot)), + Plan::Pair(slot) => self.join_for(owner, usize::from(slot), open_queues), // The preferred pair, else the owner's least-loaded other pair: // the publication barrier orders the overlap from there. - Plan::Join(slot) => self.join(owner, usize::from(slot)).or_else(|| { - let other = (0..cfg::RENDER_SLOTS) - .filter(|other| *other != usize::from(slot) && self.usable(owner, *other)) - .min_by_key(|other| (self.refs[*other], u64::MAX - self.epochs[*other]))?; - self.join(owner, other) - }), + Plan::Join(slot) => self + .join_for(owner, usize::from(slot), open_queues) + .or_else(|| { + let other = (0..cfg::RENDER_SLOTS) + .filter(|other| { + *other != usize::from(slot) + && self.usable(owner, *other) + && self.can_lease_slot(owner, *other, open_queues) + }) + .min_by_key(|other| (self.refs[*other], u64::MAX - self.epochs[*other]))?; + self.join_for(owner, other, open_queues) + }), } } fn usable(&self, owner: u64, slot: usize) -> bool { - self.owners.get(slot) == Some(&owner) + self.owns_live(owner, slot) && (self.quarantined | self.kill_hold) & (1u64 << slot) == 0 && self.refs[slot] < cfg::RENDER_DEPTH } + #[cfg(CONFIG_KUNIT = "y")] fn join(&mut self, owner: u64, index: usize) -> Option { - if !self.usable(owner, index) { + self.join_for(owner, index, 0) + } + fn join_for(&mut self, owner: u64, index: usize, open_queues: usize) -> Option { + if !self.usable(owner, index) || !self.can_lease_slot(owner, index, open_queues) { return None; } if self.refs[index] == 0 { @@ -608,11 +870,79 @@ impl Pool { pub(crate) fn has_room(&self) -> bool { self.queues() < self.max_queues } + /// Render pairs needed so every open logical queue (plus `extra_queues`) + /// keeps a first pair alongside non-reclaimable sibling and teardown-held + /// pairs. + pub(crate) fn render_demand(&self, extra_queues: usize) -> usize { + let state = self.state.lock(); + let open = self.queues.load(Ordering::Acquire) as usize; + state.pair_demand(open).saturating_add(extra_queues) + } + /// Whether admitting one more logical queue requires reclaiming a warmed + /// (built, unpublished) sibling outside `reclaimable` before + /// [`Self::try_reserve_queue_reclaiming`] can succeed. + pub(crate) fn needs_warmed_sibling_reclaim( + &self, + render_capacity: usize, + reclaimable: u64, + ) -> bool { + let state = self.state.lock(); + let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); + let open = self.queues.load(Ordering::Acquire) as usize; + let total = state.total_pair_demand(open).saturating_add(1); + total > cap && total.saturating_sub(state.reclaimable_siblings_in(reclaimable)) > cap + } + #[cfg(CONFIG_KUNIT = "y")] pub(crate) fn reserve_queue(self: &Arc) -> Result { + self.try_reserve_queue(cfg::RENDER_SLOTS - 1) + } + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn try_reserve_queue( + self: &Arc, + render_capacity: usize, + ) -> Result { + self.try_reserve_queue_reclaiming(render_capacity, State::MASK, 0) + } + /// Reserves a logical queue slot if every open queue (including this one), + /// every non-reclaimable sibling, and every teardown-held released pair + /// fits within `render_capacity`, reclaiming idle unpublished siblings in + /// `reclaimable` first so eager sibling claims never reduce queue capacity. + pub(crate) fn try_reserve_queue_reclaiming( + self: &Arc, + render_capacity: usize, + reclaimable: u64, + installed: u64, + ) -> Result { + let mut state = self.state.lock(); + state.render_capacity = render_capacity; + let cap = render_capacity.min(cfg::RENDER_SLOTS - 1); let mut count = self.queues.load(Ordering::Acquire); + let mut reclaimed = false; loop { if count >= self.max_queues { - return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::LogicalQueues)); + drop(state); + if reclaimed { + self.returned(); + } + return Err(crate::g17::capacity::refused( + crate::g17::capacity::Site::LogicalQueues, + )); + } + while state.total_pair_demand(count as usize).saturating_add(1) > cap { + if state.reclaim_sibling(reclaimable, installed).is_none() { + break; + } + reclaimed = true; + } + let needed = state.total_pair_demand(count as usize).saturating_add(1); + if needed > cap { + drop(state); + if reclaimed { + self.returned(); + } + return Err(crate::g17::capacity::refused( + crate::g17::capacity::Site::LogicalQueues, + )); } match self.queues.compare_exchange( count, @@ -620,11 +950,46 @@ impl Pool { Ordering::AcqRel, Ordering::Acquire, ) { - Ok(_) => return Ok(QueueSlot { pool: self.clone() }), + Ok(_) => { + drop(state); + if reclaimed { + self.returned(); + } + return Ok(QueueSlot { pool: self.clone() }); + } Err(current) => count = current, } } } + /// Reserves a compute QID while holding admission's state lock so sibling + /// admission cannot race ahead of the updated render-pair capacity. + pub(crate) fn reserve_compute_with_budget( + &self, + reclaimable: u64, + installed: u64, + reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, + ) -> Result { + let mut state = self.state.lock(); + let open = self.queues.load(Ordering::Acquire) as usize; + let demand = state.pair_demand(open); + let (value, room, capacity) = reserve(demand)?; + let grew = (room && !state.build_room) || capacity > state.render_capacity; + state.build_room = room; + state.render_capacity = capacity; + let cap = capacity.min(cfg::RENDER_SLOTS - 1); + let mut reclaimed = false; + while state.total_pair_demand(open) > cap { + if state.reclaim_sibling(reclaimable, installed).is_none() { + break; + } + reclaimed = true; + } + drop(state); + if grew || reclaimed { + self.returned(); + } + Ok(value) + } /// The owner's pair is quarantined behind another VM's recovery (spared) and drains. pub(crate) fn spared_quarantined(&self, owner: u64) -> bool { self.state.lock().owner_quarantine(owner) == Some(true) @@ -683,7 +1048,8 @@ impl Pool { } else { state.plan(owner, request, ticket) }; - if let Some(slot) = state.pick(owner, pairs, plan) { + let open_queues = self.queues.load(Ordering::Acquire) as usize; + if let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) { state.forget_waiter(ticket.take()); let record = request.and_then(|request| state.record(owner, Some(slot), 0, request)); @@ -733,11 +1099,12 @@ impl Pool { return Ok(None); } let mut state = self.state.lock(); - if state.refusal(owner).is_err() || !state.owners.contains(&owner) { + if state.refusal(owner).is_err() || !state.has_live_owner(owner) { return Ok(None); } let plan = state.plan(owner, request, None); - let Some(slot) = state.pick(owner, pairs, plan) else { + let open_queues = self.queues.load(Ordering::Acquire) as usize; + let Some(slot) = state.pick_for(owner, pairs, open_queues, plan) else { return Ok(None); }; let record = request.and_then(|request| state.record(owner, Some(slot), 0, request)); @@ -758,7 +1125,8 @@ impl Pool { return false; } let plan = state.plan(owner, request, None); - state.can_pick(owner, plan) + let open_queues = self.queues.load(Ordering::Acquire) as usize; + state.can_pick_for(owner, open_queues, plan) } pub(crate) fn warmable_sibling( self: &Arc, @@ -766,6 +1134,11 @@ impl Pool { publishing: u8, ) -> Option { let mut state = self.state.lock(); + let open_queues = self.queues.load(Ordering::Acquire) as usize; + let candidate = state.warmable_sibling(owner, publishing)?; + if !state.can_lease_slot(owner, usize::from(candidate), open_queues) { + return None; + } let slot = state.borrow_warm_sibling(owner, publishing)?; // This is a host construction borrower, not a GPU-use epoch. In // particular it must not clear a logical close or age an unused spare. @@ -775,6 +1148,16 @@ impl Pool { record: None, }) } + pub(crate) fn can_reassign_unused_spare( + &self, + slot: u8, + expected: Option, + owner: Option, + ) -> bool { + self.state + .lock() + .can_reassign_unused_spare(slot, expected, owner) + } pub(crate) fn reassign_unused_spare( &self, slot: u8, @@ -785,14 +1168,41 @@ impl Pool { .lock() .reassign_unused_spare(slot, expected, owner) } + pub(crate) fn release_unused_sibling( + &self, + slot: u8, + expected: Option, + keep_installed: bool, + ) -> bool { + let released = self + .state + .lock() + .release_unused_sibling(slot, expected, keep_installed); + if released { + self.returned(); + } + released + } pub(crate) fn owns_slot(&self, owner: u64, slot: usize) -> bool { - self.state.lock().owners.get(slot) == Some(&owner) + self.state.lock().owns_live(owner, slot) + } + pub(crate) fn note_published(&self, slot: u8) { + let index = usize::from(slot); + if index > 0 && index < cfg::RENDER_SLOTS { + let bit = 1u64 << index; + let mut state = self.state.lock(); + if state.owners[index] != 0 && state.released & bit == 0 { + state.published |= bit; + } + } } pub(crate) fn release_owner(&self, owner: u64) { let mut state = self.state.lock(); for slot in 0..cfg::RENDER_SLOTS { if state.owners[slot] == owner { - state.released |= 1u64 << slot; + let bit = 1u64 << slot; + state.released |= bit; + state.published &= !bit; } } drop(state); @@ -810,6 +1220,7 @@ impl Pool { } } state.released &= !released; + state.published &= !released; state.quarantined &= !released; state.spared &= !released; state.kill_hold = 0; @@ -862,11 +1273,14 @@ impl Pool { } } - /// Whether the physical queue table can hold another pair (see `State::build_room`). - pub(crate) fn note_build_room(&self, room: bool) { + /// Whether the physical queue table can hold another pair and how many + /// dedicated render pairs fit in total (see `State::build_room` and + /// `State::render_capacity`). + pub(crate) fn note_build_room(&self, room: bool, capacity: usize) { let mut state = self.state.lock(); - if state.build_room != room { + if state.build_room != room || state.render_capacity != capacity { state.build_room = room; + state.render_capacity = capacity; drop(state); self.returned(); } @@ -1090,10 +1504,11 @@ impl RenderLease { /// Called under the device mutex once the render's kicks are committed, /// including a replay, which supersedes the earlier kick. pub(crate) fn note_publication(&self, fragment: KickDependency) { + let mut state = self.pool.state.lock(); + state.published |= (1u64 << self.slot) & State::MASK; let Some(record) = self.record else { return; }; - let mut state = self.pool.state.lock(); if let Some(index) = state.position(self.slot, record) { state.footprints[index].fragment = Some(fragment); } @@ -1398,7 +1813,7 @@ mod fault_capacity_tests { let built = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); assert!(usize::from(built.slot()) >= 8); // Without room it takes the killed pair released longest ago. - pool.note_build_room(false); + pool.note_build_room(false, cfg::RENDER_SLOTS - 1); let reused = pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap(); assert_eq!(reused.slot(), 7); assert_eq!(pool.state.lock().killed & (1u64 << 7), 0); @@ -1583,6 +1998,333 @@ mod two_pair_tests { assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); assert_eq!(state.acquire(1, 1), Some(first)); } + + #[test] + fn sibling_claim_preserves_first_pair_capacity_for_open_queues() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let _q1 = pool.try_reserve_queue(2).unwrap(); + let _q2 = pool.try_reserve_queue(2).unwrap(); + // Two open queues and capacity for two pairs: neither an unowned slot + // nor a released pair may be claimed as a sibling. + { + let mut state = pool.state.lock(); + state.owners[5] = 99; + state.released |= 1u64 << 5; + } + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 1 + ); + // The second open queue still gets its guaranteed first pair. + let l2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 2).count(), + 1 + ); + drop(l1); + drop(l2); + // Once capacity exceeds open queues, a sibling is claimed from surplus. + pool.note_build_room(true, 3); + let l1_again = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 2 + ); + // The idle unpublished sibling can still yield to a new queue. + assert_eq!(pool.render_demand(0), 2); + assert_eq!(pool.state.lock().total_pair_demand(2), 3); + drop(l1_again); + } + + #[test] + fn idle_siblings_yield_to_open_queues_up_to_full_capacity() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let cap = 8usize; + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, cap); + let mut queues = KVec::with_capacity(cap, GFP_KERNEL).unwrap(); + // First cap / 2 owners each publish on BOTH their primary and sibling + // pairs, filling all `cap` slots with published graphs, then go idle. + for owner in 1..=(cap / 2) as u64 { + queues.push(pool.try_reserve_queue(cap).unwrap(), GFP_KERNEL).unwrap(); + let first = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + first.note_publication(kick); + let sibling = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + assert_ne!(first.slot(), sibling.slot()); + sibling.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!( + (1..cfg::RENDER_SLOTS) + .filter(|slot| state.owns_live(owner, *slot)) + .count(), + 2 + ); + assert_ne!(state.published & (1u64 << sibling.slot()), 0); + } + drop(sibling); + drop(first); + } + assert_eq!(pool.state.lock().total_pair_demand(cap / 2), cap); + assert_eq!(pool.render_demand(0), cap / 2); + // Opening queues beyond cap / 2 detaches idle published siblings (marking + // them released while keeping their previous owner recorded) until full + // capacity is reached and each new owner reuses a detached slot. + for owner in (cap / 2 + 1) as u64..=cap as u64 { + assert!(pool.render_demand(1) <= cap); + queues.push(pool.try_reserve_queue(cap).unwrap(), GFP_KERNEL).unwrap(); + { + let state = pool.state.lock(); + assert_ne!(state.released & State::MASK, 0); + // Released slots retain their prior owner until rebound. + for slot in 1..cfg::RENDER_SLOTS { + if state.released & (1u64 << slot) != 0 { + assert_ne!(state.owners[slot], 0); + assert_eq!(state.published & (1u64 << slot), 0); + } + } + } + let lease = pool + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + lease.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!( + (1..cfg::RENDER_SLOTS) + .filter(|slot| state.owns_live(owner, *slot)) + .count(), + 1 + ); + } + drop(lease); + } + assert_eq!(pool.queues() as usize, cap); + assert!(matches!(pool.try_reserve_queue(cap), Err(ENOSPC))); + for owner in 1..=cap as u64 { + pool.release_owner(owner); + } + drop(queues); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn queue_and_compute_admission_account_for_non_reclaimable_siblings() { + crate::g17::pairs::set_sibling_backlog(0); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 2 + ); + // An idle, unpublished sibling is reclaimable and does not inflate pair_demand. + assert_eq!(pool.render_demand(0), 1); + assert_eq!(pool.render_demand(1), 2); + // Once owner 1 actually acquires its sibling, it is busy/used and cannot be reclaimed. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + assert_eq!(pool.render_demand(0), 2); + assert_eq!(pool.render_demand(1), 3); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + // Compute reservation observes demand including the non-reclaimable sibling. + let observed = pool + .reserve_compute_with_budget(State::MASK, 0, |demand| Ok((demand, false, 2))) + .unwrap(); + assert_eq!(observed, 2); + assert!(!pool.state.lock().build_room); + // Closing the sibling owner releases both pairs so a new queue fits. + drop(l2); + drop(l1); + pool.release_owner(1); + drop(q1); + assert_eq!(pool.render_demand(0), 0); + let _q2 = pool.try_reserve_queue(2).unwrap(); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn queue_admission_accounts_for_teardown_held_released_pairs() { + crate::g17::pairs::set_sibling_backlog(0); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 3); + let q1 = pool.try_reserve_queue(3).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + // Owner 1 now holds a primary pair and an idle sibling; acquire the sibling so it is busy. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(l1.slot(), l2.slot()); + // Simulate a third pair that was released but is still held for teardown. + let held_slot = (1..cfg::RENDER_SLOTS) + .find(|slot| pool.state.lock().owners[*slot] == 0) + .unwrap(); + { + let mut state = pool.state.lock(); + state.owners[held_slot] = 99; + state.released |= 1u64 << held_slot; + state.held |= 1u64 << held_slot; + } + assert_eq!(pool.render_demand(0), 3); + assert_eq!(pool.render_demand(1), 4); + // All 3 pairs are non-reclaimable (2 busy + 1 teardown-held): queue 2 is refused. + assert!(matches!(pool.try_reserve_queue(3), Err(ENOSPC))); + // Compute reservation observes demand including the teardown-held pair. + let observed = pool + .reserve_compute_with_budget(State::MASK, 0, |demand| Ok((demand, false, 3))) + .unwrap(); + assert_eq!(observed, 3); + // Once teardown finishes and clears `held`, the released pair becomes reusable. + pool.state.lock().held &= !(1u64 << held_slot); + assert_eq!(pool.render_demand(0), 2); + let _q2 = pool.try_reserve_queue(3).unwrap(); + drop(l2); + drop(l1); + drop(q1); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn unpublished_sibling_lease_drop_stays_reclaimable() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + l1.note_publication(kick); + // Taking a sibling lease advances its epoch and protects it while busy. + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let sib = l2.slot(); + assert_ne!(l1.slot(), sib); + assert_eq!(pool.render_demand(0), 2); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + // Dropping the lease before publication leaves the sibling reclaimable. + drop(l2); + assert_ne!(pool.state.lock().epochs[usize::from(sib)], 0); + assert_eq!(pool.state.lock().published & (1u64 << sib), 0); + assert_eq!(pool.render_demand(0), 1); + let q2 = pool.try_reserve_queue(2).unwrap(); + assert_eq!( + pool.state.lock().owners.iter().filter(|id| **id == 1).count(), + 1 + ); + drop(q2); + drop(l1); + // A published sibling stays protected while busy, then yields once idle + // by detaching its owner into `released` so a new queue reuses its QIDs. + let l1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let l2 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let pub_sib = l2.slot(); + assert_ne!(l1.slot(), pub_sib); + l2.note_publication(kick); + assert_eq!(pool.render_demand(0), 2); + assert!(matches!(pool.try_reserve_queue(2), Err(ENOSPC))); + drop(l2); + assert_eq!(pool.render_demand(0), 1); + let q3 = pool.try_reserve_queue(2).unwrap(); + { + let state = pool.state.lock(); + assert_eq!(state.owners[usize::from(pub_sib)], 1); + assert_ne!(state.released & (1u64 << pub_sib), 0); + assert_eq!(state.published & (1u64 << pub_sib), 0); + } + // note_published() must not re-set `published` on a released slot. + pool.note_published(pub_sib); + assert_eq!(pool.state.lock().published & (1u64 << pub_sib), 0); + let l3 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(l3.slot(), pub_sib); + drop(l3); + drop(l1); + pool.release_owner(1); + pool.release_owner(2); + drop(q3); + drop(q1); + assert_eq!(pool.render_demand(0), 0); + crate::g17::pairs::set_sibling_backlog(1); + } + + #[test] + fn compute_shrink_gates_warmed_sibling_promotion() { + use crate::g17::fw::kick::KickTimestamp; + + crate::g17::pairs::set_sibling_backlog(0); + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 5); + let q1 = pool.try_reserve_queue(5).unwrap(); + let q2 = pool.try_reserve_queue(5).unwrap(); + let q3 = pool.try_reserve_queue(5).unwrap(); + // Owners 1 and 2 publish primaries and claim siblings; owner 3 has not rendered yet. + let p1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + p1.note_publication(kick); + drop(p1); + let p2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + p2.note_publication(kick); + drop(p2); + assert_eq!(pool.state.lock().total_pair_demand(3), 5); + assert_eq!(pool.render_demand(0), 3); + // Compute shrinks render_capacity from 5 to 4 while both siblings stay warmed + // (outside the lock-only reclaimable mask). + pool.reserve_compute_with_budget(0, 0, |demand| { + assert_eq!(demand, 3); + Ok(((), false, 4)) + }) + .unwrap(); + // One sibling can still be promoted up to the shrunk capacity of 4. + let p1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let s1 = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(p1.slot(), s1.slot()); + s1.note_publication(kick); + assert_eq!(pool.render_demand(0), 4); + // While owner 1's sibling is busy, owner 2's warmed sibling cannot promote + // past capacity 4 and stays reclaimable for owner 3's guaranteed first pair. + let p2 = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + let s2 = (1..cfg::RENDER_SLOTS) + .find(|slot| { + *slot != usize::from(p2.slot()) && pool.state.lock().owns_live(2, *slot) + }) + .unwrap() as u8; + assert!(pool.warmable_sibling(2, p2.slot()).is_none()); + let p2_stacked = pool.acquire_render(2, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(p2_stacked.slot(), p2.slot()); + { + let mut state = pool.state.lock(); + assert!(!state.can_pick_for(2, 3, Plan::Pair(s2))); + assert_eq!(state.pick_for(2, 2, 3, Plan::Pair(s2)), None); + assert_eq!(state.pick_for(2, 2, 3, Plan::Join(s2)), Some(p2.slot())); + state.release(p2.slot()); + } + drop(p2_stacked); + drop(p2); + assert_eq!(pool.render_demand(0), 4); + assert!(pool.release_unused_sibling(s2, Some(2), true)); + assert_eq!(pool.state.lock().owners[usize::from(s2)], 2); + assert_ne!(pool.state.lock().released & (1u64 << s2), 0); + let p3 = pool.acquire_render(3, 2, None, u64::MAX, || Ok(())).unwrap(); + assert_eq!(p3.slot(), s2); + drop(p3); + drop(s1); + drop(p1); + for owner in 1..=3 { + pool.release_owner(owner); + } + drop(q3); + drop(q2); + drop(q1); + crate::g17::pairs::set_sibling_backlog(1); + } } #[kunit_tests(asahi_g17_admission_deadline)] diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 4273f178bf602f..7377a89079fc09 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -2955,6 +2955,9 @@ impl Pair { } } } + pub(crate) fn graph_started(&self) -> bool { + self.graph_started + } pub(crate) fn forget_registration(&mut self) { self.registered = None; } @@ -3068,17 +3071,21 @@ impl Pair { .into_iter() .all(|c| c.done == c.read && c.read == c.write)) } - pub(crate) fn reusable(&self) -> Result { + /// Idle, drained, and free of pending retirement or channel errors so a + /// live owner's sibling can be detached or a closed owner's pair reused. + pub(crate) fn detachable(&self) -> Result { let previous_ready = self .previous .as_ref() .is_none_or(|p| p.memory.is_none() && self.context_update && !p.ready); Ok(!self.channel_error - && self.owner.is_none() && self.displaced.is_none() && previous_ready && self.idle_for_context(self.context())?) } + pub(crate) fn reusable(&self) -> Result { + Ok(self.owner.is_none() && self.detachable()?) + } /// An M5 pool may be replaced without changing the pair's live logical /// owner. Commands already using the pair must drain, and an earlier /// replacement must have retired, unless nothing was published since it: diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93b..0eccf2aa4b7092 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -288,7 +288,7 @@ impl Registry { if let Some(rebind) = self.bind_reusable(owner, context, required, admission)? { return Ok(rebind); } - if self.qids.compute_fits(self.admission.queues() as usize) { + if self.compute_qid_fits() { return Ok(Rebind::Fresh); } if self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) @@ -353,6 +353,15 @@ impl Registry { Ok(self.bind_reusable(owner, context, required, admission)?.unwrap_or(Rebind::Fresh)) } + /// Whether a fresh compute QID fits beside current render demand, either + /// directly or after cancelling one idle unpublished render spare. + fn compute_qid_fits(&self) -> bool { + let demand = self.admission.render_demand(0); + self.qids.compute_fits(demand) + || (self.has_cancelable_render_spare().unwrap_or(false) + && self.qids.compute_fits_with_reclaim(demand, 2)) + } + /// Whether `owner` can bind a channel now, without changing any binding. Owner 0 asks /// only whether some channel is free for a new owner. fn compute_readiness(&self, owner: u64, query: Option<(&Arc, super::freelist::ComputeCapacity)>) -> Readiness { @@ -378,7 +387,7 @@ impl Registry { (queue.reusable() || queue.shareable() || queue.can_rearm()) && !queue.context().is_some_and(|bound| teardown.releasing(bound)) }); - if available || self.qids.compute_fits(self.admission.queues() as usize) { + if available || self.compute_qid_fits() { Readiness::Ready } else { Readiness::Channel @@ -600,12 +609,20 @@ impl Registry { .ok_or_else(|| self.compute_admission_error( crate::g17::capacity::refused(crate::g17::capacity::Site::ComputeSlots)))?; let identity = self.identities.reserve(1)?.start; - let queues = self.admission.queues() as usize; + let (reclaimable, installed) = self.reclaimable_render_slots()?; + let qids = &mut self.qids; let id = self - .qids - .reserve_for(identity, DataMaster::Compute, Some(FIRST_COMPUTE_QID), queues) + .admission + .reserve_compute_with_budget(reclaimable, installed, |demand| { + let id = qids.reserve_for( + identity, + DataMaster::Compute, + Some(FIRST_COMPUTE_QID), + demand, + )?; + Ok((id, qids.render_pair_fits(), qids.render_pair_capacity())) + }) .map_err(|error| self.compute_admission_error(error))?; - self.note_build_room(); let reservation = ComputeReservation { slot, id, owner }; self.compute[slot] = Some(ComputeEntry { reservation, @@ -614,6 +631,20 @@ impl Registry { Ok(reservation) } + /// Reserves a fresh compute channel, storing any cancelled unpublished + /// render spare in `reclaimed` so the caller drops its backing off-lock. + fn reserve_compute_reclaiming( + &mut self, + owner: u64, + reclaimed: &mut Option, + ) -> Result { + let demand = self.admission.render_demand(0); + if !self.qids.compute_fits(demand) && self.qids.compute_fits_with_reclaim(demand, 2) { + *reclaimed = self.reclaim_unused_render_spare(None, true)?; + } + self.reserve_compute(owner) + } + fn reserved(&mut self, reservation: ComputeReservation) -> Result<&mut ComputeEntry> { let entry = self .compute @@ -776,6 +807,7 @@ impl Backend { let (lease, uat, pool, qos, execution, slot, share, render_id) = loop { let observed = shared.queues.observe(); let lease = shared.preparations.enter(true)?; + let mut reclaimed = None; let mut state = shared.state.lock(); let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; if shared.crashed.load(core::sync::atomic::Ordering::Acquire) { @@ -786,14 +818,44 @@ impl Backend { // notifies the queue domain observed above, so the creator's own // wait would end at once and admission would spin on the device // mutex for the whole wait, starving the queues it waits for. - let admission = &firmware.queues.admission; - // Installed compute channels narrow render's QIDs: every open - // logical queue keeps a dedicated render pair within reach. - if !admission.has_room() - || !firmware.queues.qids.render_fits(admission.queues() as usize + 1) + // + // Installed compute channels and non-reclaimable sibling render + // pairs narrow render's QIDs: every open logical queue keeps a + // dedicated first render pair within reach, while idle unpublished + // siblings give way before refusing a new queue. + if !firmware.queues.admission.has_room() + || !firmware + .queues + .qids + .render_fits(firmware.queues.admission.render_demand(1)) { return Err(super::capacity::refused(super::capacity::Site::LogicalQueues)); } + let (mut reclaimable, mut installed) = firmware.queues.reclaimable_render_slots()?; + let mut render_capacity = firmware.queues.qids.render_pair_capacity(); + if firmware + .queues + .admission + .needs_warmed_sibling_reclaim(render_capacity, reclaimable) + { + reclaimed = firmware.queues.reclaim_unused_render_sibling()?; + if reclaimed.is_none() { + return Err(super::capacity::refused(super::capacity::Site::LogicalQueues)); + } + render_capacity = firmware.queues.qids.render_pair_capacity(); + (reclaimable, installed) = firmware.queues.reclaimable_render_slots()?; + if firmware + .queues + .admission + .needs_warmed_sibling_reclaim(render_capacity, reclaimable) + { + drop(state); + drop(reclaimed); + drop(lease); + continue; + } + } + let admission = &firmware.queues.admission; // A context that takes its render pool identity now is refused here, holding // nothing, when render graphs kept until the firmware stops hold the rest. let render_id = if shared.variant.render_id_at_create { @@ -806,18 +868,31 @@ impl Backend { // G17P queues of one VM join its live execution context (super::exec_share). let joined = if firmware.uat.is_m5() { None } else { super::exec_share::join(vm) }; let attempt = if let Some((execution, share)) = joined { - Ok((execution, admission.reserve_queue()?, Some(share))) + Ok(( + execution, + admission.try_reserve_queue_reclaiming( + render_capacity, + reclaimable, + installed, + )?, + Some(share), + )) } else if firmware.uat.execution_contexts_used() < crate::mmu::MAX_EXECUTION_CONTEXTS { - // Creators hold the device mutex, so neither check above can - // have changed; the slot only fails on a broken invariant. - let slot = admission.reserve_queue()?; + // Creators hold the device mutex, and try_reserve_queue_reclaiming + // reclaims unbuilt/parked/reusable siblings and re-checks demand + // atomically against render_capacity before taking a slot. + let slot = admission.try_reserve_queue_reclaiming( + render_capacity, + reclaimable, + installed, + )?; firmware.uat.new_execution_context(vm, super::channel::control_witnessed()).map(|execution| (execution, slot, None)) } else { Err(ENOSPC) }; match attempt { Ok((execution, slot, share)) => { - break ( + let result = ( lease, firmware.uat.clone(), firmware.pool.clone(), @@ -826,7 +901,10 @@ impl Backend { slot, share, render_id, - ) + ); + drop(state); + drop(reclaimed); + break result; } Err(error) if error == ENOSPC => { // Every open queue holds one context; this one holds no @@ -838,6 +916,7 @@ impl Backend { } drop(render_id); drop(state); + drop(reclaimed); drop(lease); // Nothing is visible yet: a signalled creator restarts. if kernel::current!().signal_pending() { @@ -1204,6 +1283,7 @@ impl Backend { let observed = self.shared.channels.observe(); let lease = self.shared.preparations.enter_until(admission)?; let dev = self.shared.drm()?; + let mut reclaimed = None; let (uat, objects, reservation) = { let mut state = self.shared.state.lock(); admission.check()?; @@ -1230,24 +1310,33 @@ impl Backend { Rebind::Grow => { drop(state); drop(lease); return self.grow_compute(required, admission); } Rebind::Rearm(qid) => (firmware.uat.clone(), firmware.pool.clone(), Err(qid)), Rebind::Fresh => { - let reservation = match firmware.queues.reserve_compute(self.owner) { + let reservation = match firmware + .queues + .reserve_compute_reclaiming(self.owner, &mut reclaimed) + { Ok(reservation) => reservation, Err(error) if error == EAGAIN => { // All physical channels are occupied. Retain their // USC backing for exact-retirement handoff; releasing // it cannot create a QID and forces fresh allocation. drop(state); + drop(reclaimed); drop(lease); self.wait_channels(observed, admission, false)?; continue; } Err(error) if error == ENOSPC => { - let reclaimed = firmware.queues.reclaim_unused_render_spare(None, true)?; + let extra = if reclaimed.is_some() { + None + } else { + firmware.queues.reclaim_unused_render_spare(None, true)? + }; drop(state); - if reclaimed.is_none() { + drop(reclaimed); + if extra.is_none() { return Err(error); } - drop(reclaimed); + drop(extra); continue; } Err(error) => return Err(error), @@ -1256,6 +1345,7 @@ impl Backend { } } }; + drop(reclaimed); let alloc = super::object::Allocator { dev: &dev, uat: &uat, @@ -2825,7 +2915,7 @@ impl Registry { self.compute.iter().flatten().filter(|entry| entry.queue.is_none()).count())?; writeln!(f, "compute_channels used={} fresh_fits={}", self.compute.iter().flatten().count(), - u8::from(self.qids.compute_fits(self.admission.queues() as usize)))?; + u8::from(self.compute_qid_fits()))?; writeln!(f, "scheduler_teardown pending={}", self.teardown.len())?; for queue in self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) { queue.write_capacity(f)?; @@ -3037,6 +3127,66 @@ mod shared_capacity_tests { assert!(registry.qids.render_fits(slots.len() + 24)); assert!(!registry.qids.render_fits(crate::mmu::MAX_EXECUTION_CONTEXTS as usize)); } + + #[test] + fn cancelable_siblings_do_not_block_compute_on_full_qid_table() { + let mut registry = KBox::init( + Registry::new(1, Deflake::ONE_CLUSTER, [0; 2], &V26A428), + GFP_KERNEL, + ) + .unwrap(); + let mut slots = KVec::with_capacity(32, GFP_KERNEL).unwrap(); + for owner in 1..=32u64 { + slots.push(registry.admission.reserve_queue().unwrap(), GFP_KERNEL).unwrap(); + let lease = registry + .admission + .acquire_render(owner, 2, None, u64::MAX, || Ok(())) + .unwrap(); + registry.ensure_render_ids(lease.slot(), owner).unwrap(); + registry.publish_render_ids(lease.slot()).unwrap(); + if owner <= 31 { + let sibling = registry + .admission + .warmable_sibling(owner, lease.slot()) + .unwrap(); + registry.ensure_render_ids(sibling.slot(), owner).unwrap(); + drop(sibling); + } + drop(lease); + } + // All 128 QIDs are now occupied: 32 published primaries (64), 31 idle + // unpublished siblings (62), and the two bootstrap render reservations. + assert!(!registry.qids.render_pair_fits()); + // Consume both bootstrap replacements with installed compute channels. + registry.reserve_compute(1000).unwrap(); + registry.reserve_compute(1001).unwrap(); + // Raw compute_fits() is false because no free or bootstrap QID remains, + // yet idle unpublished siblings can yield QIDs for fresh compute work. + assert!(!registry.qids.compute_fits(registry.admission.render_demand(0))); + assert!(registry.has_cancelable_render_spare().unwrap()); + assert!(registry.compute_qid_fits()); + assert!(matches!(registry.compute_readiness(1002, None), Readiness::Ready)); + let mut reclaimed = None; + registry.reserve_compute_reclaiming(1002, &mut reclaimed).unwrap(); + assert!(reclaimed.is_some()); + drop(reclaimed); + // Compute grows to the full budget left above render_reserve(32) = 114. + let mut count = 3usize; + let mut owner = 1003u64; + while registry.compute_qid_fits() { + let mut spare = None; + registry.reserve_compute_reclaiming(owner, &mut spare).unwrap(); + drop(spare); + count += 1; + owner += 1; + } + assert_eq!(count, super::super::kick::QID_COUNT - super::super::kick::render_reserve(32)); + assert!(matches!(registry.compute_readiness(owner, None), Readiness::Channel)); + let mut spare = None; + assert!(matches!(registry.reserve_compute_reclaiming(owner, &mut spare), Err(EAGAIN))); + assert!(spare.is_none()); + assert!(registry.qids.render_fits(slots.len() + 24)); + } } impl Backend { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index ab33c149ba96d3..a24fb888354bce 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -232,18 +232,83 @@ impl RenderState { } impl Registry { - /// Yield unused warming only when admission has run out of physical slots. - /// Previously published graphs keep their existing ownership and retirement - /// rules. The caller destroys returned backing after dropping the device lock. + /// Whether at least one unused render entry holds unpublished QIDs that + /// [`Self::reclaim_unused_render_spare`] can cancel for compute. + pub(super) fn has_cancelable_render_spare(&self) -> Result { + for slot in 1..RENDER_SLOTS { + let Some(entry) = self.render.entries[slot].as_ref() else { + continue; + }; + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + if !entry + .reservation + .ids + .iter() + .all(|id| self.qids.can_cancel_unpublished(*id)) + { + continue; + } + let expected = if let Some(pair) = entry.pair.as_ref() { + if pair.can_yield_unused()? { + Some(entry.reservation.owner) + } else { + continue; + } + } else if entry.context.is_none() { + None + } else { + continue; + }; + if self + .admission + .can_reassign_unused_spare(slot as u8, expected, None) + { + return Ok(true); + } + } + Ok(false) + } + + /// Yield unused warming or idle drained published siblings when admission + /// has run out of physical slots. Compute only cancels unpublished + /// identities; render can also detach an idle drained published sibling so + /// a new owner reuses its installed QIDs via `bind_owner()`. The caller + /// destroys returned backing after dropping the device lock. pub(super) fn reclaim_unused_render_spare( &mut self, owner: Option, require_ids: bool, ) -> Result> { - // Prefer an empty reservation or an already parked channel. - for with_backing in [false, true] { + // Prefer an empty reservation or an already parked channel, then a + // reusable or warmed unpublished pair, then an idle drained published + // sibling (render only). + for pass in 0..3u8 { + if pass == 2 && owner.is_none() { + break; + } + let with_backing = pass != 0; for slot in 1..RENDER_SLOTS { + if with_backing + && self.render.entries[slot].as_ref().is_some_and(|entry| { + entry.pair.is_some() + && !entry.constructing + && entry.preparing.is_none() + && !entry.growing + && entry.pending_error.is_none() + && !entry.pending_timeout + }) + { + self.render.collect_retired(slot)?; + } let mut warm = false; + let mut detach = false; let expected = if let Some(entry) = self.render.entries[slot].as_ref() { if entry.constructing || entry.preparing.is_some() @@ -269,10 +334,17 @@ impl Registry { if !with_backing { continue; } - if owner.is_some() && pair.reusable()? { - None - } else if pair.can_yield_unused()? { - warm = true; + if pass == 1 { + if owner.is_some() && pair.reusable()? { + None + } else if pair.can_yield_unused()? { + warm = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else if pair.detachable()? && !self.teardown.releasing(pair.context()) { + detach = true; Some(entry.reservation.owner) } else { continue; @@ -322,6 +394,161 @@ impl Registry { entry.context = None; entry.pool = None; binding = Some(retired); + } else if detach { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + entry.pair.as_mut().ok_or(EIO)?.release_owner(); + self.hold_render_slot(slot); + } + return Ok(Some(UnusedRenderSpare { + _entry: None, + _binding: binding, + })); + } + } + Ok(None) + } + + /// Slots whose live-sibling claim can be dropped under admission's lock + /// without modifying `render.entries` or dropping backing off-lock: + /// `(reclaimable_mask, installed_mask)`. + pub(super) fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { + let mut reclaimable = 0u64; + let mut installed = 0u64; + for slot in 1..RENDER_SLOTS { + let bit = 1u64 << slot; + let Some(entry) = self.render.entries[slot].as_ref() else { + reclaimable |= bit; + continue; + }; + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + if let Some(pair) = entry.pair.as_ref() { + if pair.reusable()? { + reclaimable |= bit; + installed |= bit; + } + } else if entry.parked.is_some() && entry.context.is_none() { + reclaimable |= bit; + installed |= bit; + } + } + Ok((reclaimable, installed)) + } + + /// Reclaim one idle live sibling (unbuilt, parked, reusable, warmed + /// unpublished, or idle drained published) so a new logical queue can take + /// its first pair. Published siblings keep their installed QIDs and detach + /// only that slot's owner so the next queue reuses them via `bind_owner()`. + /// The caller destroys any returned backing after dropping the device lock. + pub(super) fn reclaim_unused_render_sibling(&mut self) -> Result> { + for pass in 0..3u8 { + let with_backing = pass != 0; + for slot in 1..RENDER_SLOTS { + if with_backing + && self.render.entries[slot].as_ref().is_some_and(|entry| { + entry.pair.is_some() + && !entry.constructing + && entry.preparing.is_none() + && !entry.growing + && entry.pending_error.is_none() + && !entry.pending_timeout + }) + { + self.render.collect_retired(slot)?; + } + let mut warm = false; + let mut detach = false; + let mut keep_installed = false; + let expected = if let Some(entry) = self.render.entries[slot].as_ref() { + if entry.constructing + || entry.preparing.is_some() + || entry.growing + || entry.pending_error.is_some() + || entry.pending_timeout + { + continue; + } + let cancelable = entry + .reservation + .ids + .iter() + .all(|id| self.qids.can_cancel_unpublished(*id)); + keep_installed = !cancelable; + if let Some(pair) = entry.pair.as_ref() { + if !with_backing { + continue; + } + if pass == 1 { + if pair.reusable()? { + None + } else if pair.can_yield_unused()? { + warm = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else if pair.detachable()? && !self.teardown.releasing(pair.context()) { + detach = true; + keep_installed = true; + Some(entry.reservation.owner) + } else { + continue; + } + } else { + if with_backing || entry.context.is_some() { + continue; + } + None + } + } else { + if with_backing { + continue; + } + None + }; + if !self + .admission + .release_unused_sibling(slot as u8, expected, keep_installed) + { + continue; + } + if !keep_installed { + let entry = self.render.entries[slot].take(); + if let Some(entry) = entry.as_ref() { + for id in entry.reservation.ids { + self.qids.cancel_unpublished(id)?; + } + if let Some(pair) = entry.pair.as_ref() { + self.buffers.unreserve_owner(pair.buffer_id())?; + } + self.note_build_room(); + } + return Ok(Some(UnusedRenderSpare { + _entry: entry, + _binding: None, + })); + } + let mut binding = None; + if warm { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + let mut pair = entry.pair.take().ok_or(EIO)?; + self.buffers.unreserve_owner(pair.buffer_id())?; + pair.release_owner(); + let (parked, retired) = KBox::into_inner(pair).park(); + entry.parked = Some(parked); + entry.context = None; + entry.pool = None; + binding = Some(retired); + } else if detach { + let entry = self.render.entries[slot].as_mut().ok_or(EIO)?; + entry.pair.as_mut().ok_or(EIO)?.release_owner(); + self.hold_render_slot(slot); } return Ok(Some(UnusedRenderSpare { _entry: None, @@ -364,7 +591,20 @@ impl Registry { /// Tell admission whether another render pair can still be built. pub(super) fn note_build_room(&self) { - self.admission.note_build_room(self.qids.render_pair_fits()); + self.admission.note_build_room( + self.qids.render_pair_fits(), + self.qids.render_pair_capacity(), + ); + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn publish_render_ids(&mut self, slot: u8) -> Result { + let ids = self.render.entry(slot)?.reservation.ids; + for id in ids { + self.qids.publish(id)?; + } + self.admission.note_published(slot); + Ok(()) } pub(super) fn ensure_render_ids(&mut self, slot: u8, owner: u64) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 117edccb28e350..97004baa72df1f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -243,16 +243,21 @@ impl crate::g17::Firmware { if entry.pending_error.is_some() || entry.pending_timeout { self.primary.state.shared.queue_events(); } + let closed = entry.closed; let pair = entry.pair.as_mut().ok_or(EIO)?; - if entry.closed { + if closed { pair.release_owner(); } if !packet.is_published() { pair.discard_prepared(packet)?; } + let published = packet.is_published() || pair.graph_started(); // A failed publication may have quarantined the lent pair, and its owner may have // closed while it was lent. self.queues.hold_render_slot(usize::from(slot)); + if published && !closed { + self.queues.admission.note_published(slot); + } if let Some((id, generation)) = activation { if self.queues.render.pools.activate(id, generation).is_err() { self.primary.state.shared.lose_device_quietly(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 71f6e4b5943a25..7ff095befe47ae 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -717,11 +717,12 @@ impl super::super::Backend { return Err(crate::g17::capacity::refused(crate::g17::capacity::Site::RetiredRenderBindings)); } // A rebind of the same context (a render that needs a bigger pool) keeps its - // live scheduler state; only another context's is displaced. + // live scheduler state; only another context's is displaced. A detached sibling + // of a still-open owner stays in Deferred until that owner closes. if !pair.matches(self.owner, &self.context)? { firmware.queues.teardown.displace( pair.context(), - true, + entry.closed, super::super::now_ns(), )?; } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 70efc3cbb0f2b5..dda6ebf5b9eb71 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -828,6 +828,15 @@ impl crate::g17::Firmware { &mut |event| deferred.push(event), ) }); + let entry = self.queues.render.entry(slot)?; + let started = packet.is_published() + || entry + .pair + .as_ref() + .is_some_and(|pair| pair.graph_started()); + if started && !entry.closed { + self.queues.admission.note_published(slot); + } if packet.is_published() { self.queues.render.entry_mut(slot)?.published = true; } else if result.is_err() { diff --git a/drivers/gpu/drm/asahi/hw/t8140.rs b/drivers/gpu/drm/asahi/hw/t8140.rs index 01651405655678..bfa192d58d8ca2 100644 --- a/drivers/gpu/drm/asahi/hw/t8140.rs +++ b/drivers/gpu/drm/asahi/hw/t8140.rs @@ -453,7 +453,7 @@ pub(crate) mod queues { pub(crate) const RENDER_SLOTS: usize = 64; // The QID budget reserves one physical pair per logical owner, which // leaves room for every execution context in the shared 128-QID - // namespace. A second pair comes only from surplus, on G17D + // namespace. A second pair comes only from surplus, on G17C and G17D // (g17::pairs). Commands queue at RENDER_DEPTH per pair, as many as a pair // has command records (the render memory's RECORDS). pub(crate) const RENDER_PAIRS_MAX: usize = 2; diff --git a/tools/asahi/g17-admission-deadline-tests.py b/tools/asahi/g17-admission-deadline-tests.py index 501c903b59f8ff..9d8cc6b46b68b8 100644 --- a/tools/asahi/g17-admission-deadline-tests.py +++ b/tools/asahi/g17-admission-deadline-tests.py @@ -27,7 +27,7 @@ def fixture(): source = (ROOT / 'queue/admission.rs').read_text() return r''' #![allow(dead_code)] -use std::sync::{Arc, Mutex, atomic::{AtomicU64, AtomicUsize, Ordering}}; +use std::sync::{Arc, Mutex, atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}}; type Result = std::result::Result; const EBUSY:i32=-16;const EIO:i32=-5;const EINVAL:i32=-22; const ERESTARTSYS:i32=-512;const ECANCELED:i32=-125; @@ -41,13 +41,14 @@ def fixture(): const QUARANTINE_WAIT_MS:u32=1000; #[derive(Clone,Copy,PartialEq)] enum Plan {Any,Conflict} #[derive(Clone,Copy)] struct Request<'a>(&'a ()); -struct State {owners:[u64;cfg::RENDER_SLOTS],quarantined:u64,spared:u64,next_ticket:u64,waiters:usize,conflict:bool,ready:bool} +struct State {owners:[u64;cfg::RENDER_SLOTS],released:u64,quarantined:u64,spared:u64,next_ticket:u64,waiters:usize,conflict:bool,ready:bool} impl State { fn exhausted(&self)->bool {false} -''' + item(source, 'fn owner_quarantine(') + r''' +''' + item(source, 'fn owns_live(') + '\n' + item(source, 'fn owner_quarantine(') + r''' fn refusal(&self,_:u64)->Result {Ok(())} fn plan(&self,_:u64,_:Option>,_:Option)->Plan {if self.conflict {Plan::Conflict}else{Plan::Any}} fn pick(&mut self,_:u64,_:usize,_:Plan)->Option {if self.ready{Some(1)}else{None}} + fn pick_for(&mut self,owner:u64,pairs:usize,_:usize,plan:Plan)->Option {self.pick(owner,pairs,plan)} fn record(&mut self,_:u64,slot:Option,_:u64,_:Request<'_>)->Option {if slot.is_none(){self.waiters+=1;}Some(0)} fn forget_waiter(&mut self,t:Option){if t.is_some(){self.waiters-=1;}} } @@ -66,12 +67,12 @@ def fixture(): } } } -struct Pool {state:Lock,released:CondVar} +struct Pool {state:Lock,released:CondVar,queues:AtomicU32} struct RenderLease {pool:Arc,slot:u8,record:Option} ''' + item(source, 'fn wait_slice_ms(') + '\nimpl Pool {\n' + item(source, 'pub(crate) fn acquire_render(') + r''' } fn new_pool(conflict:bool,quarantined:u64)->Arc { - Arc::new(Pool{state:Lock(Mutex::new(State{owners:[0,1],quarantined,spared:0,next_ticket:1,waiters:0,conflict,ready:false})),released:CondVar}) + Arc::new(Pool{state:Lock(Mutex::new(State{owners:[0,1],released:0,quarantined,spared:0,next_ticket:1,waiters:0,conflict,ready:false})),released:CondVar,queues:AtomicU32::new(1)}) } fn reset(mode:usize){NOW.store(0,Ordering::SeqCst);WAITS.store(0,Ordering::SeqCst);MODE.store(mode,Ordering::SeqCst);} fn main(){ diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 89c9dc15c809d0..8397c06ac7c9ca 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -160,10 +160,14 @@ def held_fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', - 'fn cancel_empty_slot(', 'fn can_pick(', 'fn pick(', 'fn usable(', 'fn join(', 'fn release(', - 'fn set_held(', 'fn retained(', 'fn used(']) + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', + 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn can_reassign_unused_spare(', 'fn reassign_unused_spare(', + 'fn cancel_empty_slot(', 'fn can_pick(', + 'fn can_pick_for(', 'fn pick(', 'fn pick_for(', 'fn usable(', 'fn join(', 'fn join_for(', + 'fn release(', 'fn set_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn set_held(', 'pub(crate) fn release_retained_owners_after_processor_stop(', 'pub(crate) fn killed_pair_free(']) @@ -229,8 +233,18 @@ def held_fixture(): assert_eq!(state.refusal(2), Err(ENOSPC), "a new owner facing only held slots is refused for capacity"); assert!(!state.can_pick(2, Plan::Any), "scheduler admission counts no held slot"); assert_eq!(state.pick(2, 1, Plan::Any), None, "a held slot goes to no new owner"); - state.claim_sibling(1, cfg::RENDER_PAIRS_MAX); + state.claim_sibling(1, cfg::RENDER_PAIRS_MAX, 0); assert_eq!(state.owners[5], 1005, "a sibling never comes from a held slot"); + // With pair capacity to spare a sibling is claimed, but from the next + // released slot: slot 5 is the oldest release and stays held. + let mut spare = crowded(&[5, 9, 2]); + assert!(!spare.set_held(5, true)); + spare.owners[9] = 1; + spare.released &= !bit(9); + spare.render_capacity = SLOTS; + spare.claim_sibling(1, cfg::RENDER_PAIRS_MAX, 0); + assert_eq!(spare.owners[5], 1005, "a sibling never comes from a held slot"); + assert_eq!(spare.owners[2], 1, "a sibling comes from a released, unheld slot"); assert!(!state.reassign_unused_spare(5, Some(1005), Some(3)), "a held slot is no spare for another owner"); assert!(!state.reassign_unused_spare(5, Some(1005), None), "a held slot is not freed for compute"); assert_eq!(state.owners[5], 1005); @@ -354,9 +368,11 @@ def release_fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn set_held(', - 'fn sync_held(', 'fn retained(', 'fn used(']) + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', + 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn usable(', 'fn set_held(', 'fn sync_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn set_held(', 'pub(crate) fn sync_held(', 'pub(crate) fn release_owner(']) pending = '\n'.join(item(teardown, name) for name in [ diff --git a/tools/asahi/g17-pool-release-tests.py b/tools/asahi/g17-pool-release-tests.py index 70004fe94ecf91..beb6af4f3faffd 100644 --- a/tools/asahi/g17-pool-release-tests.py +++ b/tools/asahi/g17-pool-release-tests.py @@ -74,7 +74,10 @@ def fixture(): struct ComputeReservation { slot: usize, id: Id, owner: u64 } type ComputeSlot = Option>; struct ComputeEntry { reservation: ComputeReservation, queue: ComputeSlot } -struct Admission; impl Admission {fn queues(&self)->u32{4}} +struct Admission; impl Admission {fn queues(&self)->u32{4} + fn reserve_compute_with_budget(&self, _: u64, _: u64, reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>) -> Result { + reserve(self.queues() as usize).map(|(value, _, _)| value) + }} struct QueueIds { free: bool, fail: Option } impl QueueIds { fn reserve_for(&mut self, _: u64, _: DataMaster, preferred: Option, _: usize) -> Result { @@ -83,6 +86,8 @@ def fixture(): self.free = false; Ok(Id { qid: preferred.unwrap() }) } + fn render_pair_fits(&self) -> bool { true } + fn render_pair_capacity(&self) -> usize { 0 } } struct Identities { next: u64 } impl Identities { @@ -100,6 +105,7 @@ def fixture(): impl Registry { // Physical-QID capacity notification does not change this pool-release fixture. fn note_build_room(&self) {} + fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { Ok((0, 0)) } METHODS fn poll(&self) -> bool { self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref())PREDICATE diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 70a60bab46adbf..6764cd183083f1 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -84,8 +84,11 @@ def fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(admission, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', + 'const fn new(', 'fn owns_live(', 'fn has_live_owner(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', + 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', + 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', + 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', + 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', 'fn rehabilitate(', 'fn pair_drained(&mut self', 'fn retained(', 'fn used(']) pool = '\n'.join(item(admission, name) for name in [ 'pub(crate) fn release_owner(', 'pub(crate) fn release_retained_owners_after_processor_stop(', diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index ad83a154d7b7b3..c1607ff54700cb 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -21,8 +21,8 @@ def item(start): return s[at:end] constants='\n'.join(re.search(r'pub\(crate\) const '+name+r': [^;]+;',cfg).group(0) for name in ['RENDER_SLOTS','RENDER_PAIRS_MAX','RENDER_DEPTH']) pairs=(source/'g17/pairs.rs').read_text() - assert 'const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8;' in pairs - assert 'PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed);' in pairs + assert 'const MULTI_PAIRS: u8 = RENDER_PAIRS_MAX as u8;' in pairs + assert 'if board.clusters >= 4 {' in pairs at=pairs.index('const SIBLING_BACKLOG');backlog=pairs[at:pairs.index('\n}\n',pairs.index('fn sibling_backlog',at))+3] mmu=(source/'mmu.rs').read_text() limits='\n'.join(re.search(r'const '+name+r': [^;]+;',mmu).group(0) for name in ['EXECUTION_CONTEXT_MASK','MAX_EXECUTION_CONTEXTS']) @@ -39,7 +39,7 @@ def item(start): macro_rules! resource_exhausted { ($s:literal)=>{ENOSPC}; } type KVec = Vec; struct InFlight; mod cfg {\n'''+constants+'}\n'+limits+'\n' - methods=['const fn new','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn take_idle','fn acquire','fn usable','fn claim_sibling','fn reassign_unused_spare','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release'] + methods=['const fn new','fn owns_live','fn has_live_owner','fn live_owners','fn live_siblings','fn reclaimable_siblings_in','fn reclaimable_siblings(','fn promotes_reclaimable_sibling','fn can_lease_slot','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn take_idle','fn acquire(','fn acquire_for','fn unavailable_released','fn total_pair_demand','fn pair_demand','fn usable','fn claim_sibling','fn can_reassign_unused_spare','fn reassign_unused_spare','fn release_unused_sibling','fn reclaim_sibling','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release('] code=header+item('struct State')+'\nimpl State {\n'+re.search(r' const MASK: u64 = .*;',s).group(0)+'\n'+'\n'.join(item(n) for n in methods)+'\n}\n'+''' // A queue holds g17::pairs::per_owner() pairs (Backend::pairs): one, or // RENDER_PAIRS_MAX on G17D. Both admissions run. @@ -177,7 +177,7 @@ def item(s,start): #[derive(Clone,Copy,PartialEq,Eq,Debug)] enum DataMaster {Compute,Tiling,Fragment} #[derive(Clone,Copy,PartialEq,Eq,Debug)] struct Id {qid:u8,owner:u64,engine:DataMaster} #[derive(Clone,Copy)] struct Identity {id:Id,published:bool} - '''+constants+'\n'+item(s,'const fn render_reserve(')+'\n'+item(s,'pub(crate) struct QueueIds')+'\nimpl QueueIds {\n'+''.join(item(s,'pub(crate) fn '+name+'(')+'\n' for name in ['reserve_initial_render','reserve','reserve_for','publish','can_cancel_unpublished','cancel_unpublished'])+''.join(item(s, sig)+'\n' for sig in ['fn render_ids(', 'fn compute_room('])+'}\n' + '''+constants+'\n'+item(s,'const fn render_reserve(')+'\n'+item(s,'const fn queue_limit(')+'\n'+item(s,'pub(crate) struct QueueIds')+'\nimpl QueueIds {\n'+''.join(item(s,'pub(crate) fn '+name+'(')+'\n' for name in ['reserve_initial_render','reserve','reserve_for','publish','can_cancel_unpublished','cancel_unpublished'])+''.join(item(s, sig)+'\n' for sig in ['fn render_ids(', 'fn compute_room('])+'}\n' test=''' fn fresh()->QueueIds {QueueIds {entries:[None;QID_COUNT],initial_render:[None;2],leased:0,floor:0}} fn main(){ From a5eb4dea7c5efc5e8c46ff90808ef370bb1bdc7f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:46:49 -0500 Subject: [PATCH 0242/1514] rtc: apple-pmu: read the RTC register block base from DT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Store per-layout register offsets relative to the RTC block base in struct apple_pmu_rtc_hw, keeping each existing layout's historical base as the fallback when the devicetree node omits apple,rtc-base. When apple,rtc-base is present on the RTC node, validate that the block fits within the 16-bit SPMI register space and add rtc->base to the shared offsets. This lets PMUs that share an existing register layout at a different block base — such as M1's Sera at 0xd000 (from the T8103 ADT spmi-pmu info-rtc* properties, matching Stowe's offsets and signed 1/32768 s offset format) — reuse the existing layout table from DT without adding a duplicate per-chip register table. Update tools/asahi/pmu-rtc-tests.py and run-host-tests.py to exercise Stowe's layout rebased to Sera's 0xd000 block and add a reg-base mutation check ensuring rtc->base is honored. Signed-off-by: Erik Bourget --- drivers/rtc/rtc-apple-pmu.c | 135 +++++++++++++++++++++++----------- tools/asahi/pmu-rtc-tests.py | 21 ++++-- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 108 insertions(+), 50 deletions(-) diff --git a/drivers/rtc/rtc-apple-pmu.c b/drivers/rtc/rtc-apple-pmu.c index dc5db42c5c0e2e..2388c2eafd7220 100644 --- a/drivers/rtc/rtc-apple-pmu.c +++ b/drivers/rtc/rtc-apple-pmu.c @@ -22,10 +22,13 @@ #define APPLE_PMU_RTC_MAX_DELAY 3600 /* - * Register addresses in the PMIC's SPMI space. The counter is six bytes - * at 65536 Hz; the comparator is four bytes of whole counter seconds. + * Register offsets within the PMIC's SPMI RTC block, plus the historical + * default block base for devicetrees that omit apple,rtc-base. The counter + * is six bytes at 65536 Hz; the comparator is four bytes of whole counter + * seconds. */ struct apple_pmu_rtc_hw { + u16 base; u16 control; u16 counter; u16 compare; @@ -40,11 +43,12 @@ struct apple_pmu_rtc_hw { }; static const struct apple_pmu_rtc_hw apple_pmu_rtc_baku = { - .control = 0xf800, - .counter = 0xf802, - .compare = 0xf808, - .mask = 0xf80e, - .event = 0xf80c, + .base = 0xf800, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x0c, .event_bit = BIT(0), .offset_in_seconds = true, /* As far as the comparator reaches: macOS's own deep-sleep wakes use it. */ @@ -52,23 +56,29 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_baku = { }; static const struct apple_pmu_rtc_hw apple_pmu_rtc_abbey = { - .control = 0x2000, - .counter = 0x2002, - .compare = 0x2008, - .mask = 0x200e, - .event = 0x2000, + .base = 0x2000, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x00, .event_bit = BIT(1), .monitor_bit = BIT(0), .max_delay = APPLE_PMU_RTC_MAX_DELAY, }; -/* M2 (t8112): Baku's register block with the offset in 1/32768 s. */ +/* + * M2 (t8112, Stowe at 0xf800) and compatible blocks at a DT-specified base + * such as M1 (t8103, Sera at 0xd000): Baku's layout with the offset in + * 1/32768 s. + */ static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = { - .control = 0xf800, - .counter = 0xf802, - .compare = 0xf808, - .mask = 0xf80e, - .event = 0xf80c, + .base = 0xf800, + .control = 0x00, + .counter = 0x02, + .compare = 0x08, + .mask = 0x0e, + .event = 0x0c, .event_bit = BIT(0), .monitor_bit = BIT(0), .max_delay = APPLE_PMU_RTC_MAX_DELAY, @@ -76,11 +86,12 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = { /* M1 Pro, Max and Ultra (t600x), offset in 1/32768 s */ static const struct apple_pmu_rtc_hw apple_pmu_rtc_maverick = { - .control = 0x1401, - .counter = 0x1406, - .compare = 0x140c, - .mask = 0x14c2, - .event = 0x14c0, + .base = 0x1400, + .control = 0x01, + .counter = 0x06, + .compare = 0x0c, + .mask = 0xc2, + .event = 0xc0, .event_bit = BIT(0), .control_event_bit = BIT(1), .monitor_bit = BIT(0), @@ -89,6 +100,7 @@ static const struct apple_pmu_rtc_hw apple_pmu_rtc_maverick = { struct apple_pmu_rtc { const struct apple_pmu_rtc_hw *hw; + u16 base; struct regmap *map; struct nvmem_cell *offset; struct rtc_device *clock; @@ -98,12 +110,17 @@ struct apple_pmu_rtc { bool io_failed; }; +static u16 apple_pmu_rtc_reg(const struct apple_pmu_rtc *rtc, u16 offset) +{ + return rtc->base + offset; +} + static int apple_pmu_rtc_counter(struct apple_pmu_rtc *rtc, u64 *ticks) { u8 count[8] = {}; int error; - error = regmap_bulk_read(rtc->map, rtc->hw->counter, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->counter), count, 6); if (error) return error; @@ -195,11 +212,11 @@ static int apple_pmu_rtc_ack_alarm(struct apple_pmu_rtc *rtc) * when acknowledging, rather than writing only the event bit. */ if (rtc->hw->event == rtc->hw->control) { - error = regmap_read(rtc->map, rtc->hw->event, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &control); if (error) return error; } - return regmap_write(rtc->map, rtc->hw->event, control | rtc->hw->event_bit); + return regmap_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), control | rtc->hw->event_bit); } static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) @@ -207,7 +224,7 @@ static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) unsigned int control; int error; - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (error) return error; /* Do not acknowledge a shared W1C event as a side effect of RMW. */ @@ -219,14 +236,14 @@ static int apple_pmu_rtc_arm(struct apple_pmu_rtc *rtc, bool enable) if (enable) control |= APPLE_PMU_RTC_ARM; control |= rtc->hw->monitor_bit; - return regmap_write(rtc->map, rtc->hw->control, control); + return regmap_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), control); } static int apple_pmu_rtc_stop_alarm(struct apple_pmu_rtc *rtc) { int error; - error = regmap_update_bits(rtc->map, rtc->hw->mask, + error = regmap_update_bits(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), APPLE_PMU_RTC_ALARM, APPLE_PMU_RTC_ALARM); if (error) return error; @@ -242,7 +259,7 @@ static int apple_pmu_rtc_start_alarm(struct apple_pmu_rtc *rtc) error = apple_pmu_rtc_ack_alarm(rtc); if (!error) - error = regmap_update_bits(rtc->map, rtc->hw->mask, + error = regmap_update_bits(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), APPLE_PMU_RTC_ALARM, 0); if (!error) error = apple_pmu_rtc_arm(rtc, true); @@ -279,14 +296,14 @@ static int apple_pmu_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm error = apple_pmu_rtc_offset(rtc, &epoch); if (error) return error; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (!error) - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (!error) - error = regmap_read(rtc->map, rtc->hw->event, &event); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &event); if (!error) - error = regmap_read(rtc->map, rtc->hw->mask, &mask); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), &mask); if (error) return error; rtc_time64_to_tm((epoch >> APPLE_PMU_RTC_HZ_SHIFT) + @@ -320,11 +337,11 @@ static int apple_pmu_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm) if (error) return error; comparator = cpu_to_le32(deadline); - error = regmap_bulk_write(rtc->map, rtc->hw->compare, + error = regmap_bulk_write(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &readback, sizeof(readback)); if (error) return error; @@ -346,7 +363,7 @@ static int apple_pmu_rtc_alarm_enable(struct device *dev, unsigned int enable) return apple_pmu_rtc_stop_alarm(rtc); if (rtc->io_failed) return -EIO; - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; @@ -362,7 +379,7 @@ static irqreturn_t apple_pmu_rtc_interrupt(int irq, void *context) int error; mutex_lock(&rtc->transaction); - error = regmap_read(rtc->map, rtc->hw->event, &event); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->event), &event); if (!error && (event & rtc->hw->event_bit)) error = apple_pmu_rtc_stop_alarm(rtc); if (error) { @@ -395,11 +412,11 @@ static int apple_pmu_rtc_init_alarm(struct apple_pmu_rtc *rtc) __le32 comparator; int error; - error = regmap_read(rtc->map, rtc->hw->control, &control); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->control), &control); if (!error) - error = regmap_read(rtc->map, rtc->hw->mask, &mask); + error = regmap_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->mask), &mask); if (!error) - error = regmap_bulk_read(rtc->map, rtc->hw->compare, + error = regmap_bulk_read(rtc->map, apple_pmu_rtc_reg(rtc, rtc->hw->compare), &comparator, sizeof(comparator)); if (error) return error; @@ -461,6 +478,39 @@ static void apple_pmu_rtc_release(void *context) device_init_wakeup(dev, false); } +static u16 apple_pmu_rtc_span(const struct apple_pmu_rtc_hw *hw) +{ + u16 end = hw->control + 1; + + end = max_t(u16, end, hw->counter + 6); + end = max_t(u16, end, hw->compare + 4); + end = max_t(u16, end, hw->mask + 1); + end = max_t(u16, end, hw->event + 1); + return end; +} + +static int apple_pmu_rtc_parse_base(struct device *dev, struct apple_pmu_rtc *rtc) +{ + u32 base; + u16 span = apple_pmu_rtc_span(rtc->hw); + int error; + + error = of_property_read_u32(dev->of_node, "apple,rtc-base", &base); + if (!error) { + if (base > 0xffff || (u64)base + span > 0x10000) + return dev_err_probe(dev, -EINVAL, + "invalid apple,rtc-base %#x (span %#x)\n", + base, span); + rtc->base = base; + return 0; + } + if (error == -EINVAL) { + rtc->base = rtc->hw->base; + return 0; + } + return dev_err_probe(dev, error, "failed to read apple,rtc-base\n"); +} + static int apple_pmu_rtc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -473,6 +523,9 @@ static int apple_pmu_rtc_probe(struct platform_device *pdev) rtc->hw = of_device_get_match_data(dev); if (!rtc->hw) return -EINVAL; + error = apple_pmu_rtc_parse_base(dev, rtc); + if (error) + return error; rtc->map = dev_get_regmap(dev->parent, NULL); if (!rtc->map) return dev_err_probe(dev, -EPROBE_DEFER, "PMIC regmap unavailable\n"); diff --git a/tools/asahi/pmu-rtc-tests.py b/tools/asahi/pmu-rtc-tests.py index 062597ca80b56f..b378c1c61b350f 100644 --- a/tools/asahi/pmu-rtc-tests.py +++ b/tools/asahi/pmu-rtc-tests.py @@ -3,7 +3,7 @@ """Execute the PMU RTC callbacks against a byte-addressed W1C regmap model. C bodies and match data are extracted from the driver. The hardware model has -independent Baku, Abbey, Stowe and Maverick addresses. This checks arithmetic, alarm transactions, +independent Baku, Abbey, Stowe, Sera (DT-rebased Stowe) and Maverick addresses. This checks arithmetic, alarm transactions, shared control preservation, stale events and I/O failures, not physical wake. """ import argparse @@ -19,12 +19,13 @@ 'offset-seconds': ('sign_extend64(offset, 47) * 2', '(s64)offset'), 'offset-sign': ('sign_extend64(offset, 47) * 2', '(s64)offset * 2'), 'event-bit': ('.event_bit = BIT(1)', '.event_bit = BIT(0)'), - 'wrong-control': ('.control = 0x2000', '.control = 0xf800'), - 'maverick-event': ('.event = 0x14c0', '.event = 0x140c'), + 'wrong-control': ('.base = 0x2000', '.base = 0xf800'), + 'maverick-event': ('.event = 0xc0', '.event = 0x0c'), 'control-event-clear': ('control &= ~rtc->hw->control_event_bit;', 'control |= rtc->hw->control_event_bit;'), 'stowe-offset': ('static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = {', 'static const struct apple_pmu_rtc_hw apple_pmu_rtc_stowe = {\n\t.offset_in_seconds = true,'), + 'reg-base': ('return rtc->base + offset;', 'return rtc->hw->base + offset;'), 'baku-limit': ('.max_delay = U32_MAX,', '.max_delay = APPLE_PMU_RTC_MAX_DELAY,'), 'set-no-round': ('(counter + BIT(APPLE_PMU_RTC_HZ_SHIFT - 1))', '(counter)'), 'set-negative': ('if (offset < 0 || offset', 'if (offset'), @@ -153,7 +154,7 @@ static struct rtc_device clock_model; static struct apple_pmu_rtc rtc; static struct device dev; -enum { BAKU, ABBEY, STOWE, MAVERICK }; +enum { BAKU, ABBEY, STOWE, SERA, MAVERICK }; static bool abbey; /* offset in 1/32768 s and monitor bit */ static void set_counter(u64 ticks) { memcpy(map.bytes + map.counter, &ticks, 6); } static void set_offset(s64 ticks) { @@ -168,17 +169,20 @@ .event = 0x2000, .bit = 2}, [STOWE] = {.ctrl = 0xf800, .counter = 0xf802, .compare = 0xf808, .mask = 0xf80e, .event = 0xf80c, .bit = 1}, + [SERA] = {.ctrl = 0xd000, .counter = 0xd002, .compare = 0xd008, .mask = 0xd00e, + .event = 0xd00c, .bit = 1}, [MAVERICK] = {.ctrl = 0x1401, .counter = 0x1406, .compare = 0x140c, .mask = 0x14c2, .event = 0x14c0, .bit = 1, .control_event = 2}, }; static const struct apple_pmu_rtc_hw *hw[] = { [BAKU] = &apple_pmu_rtc_baku, [ABBEY] = &apple_pmu_rtc_abbey, - [STOWE] = &apple_pmu_rtc_stowe, [MAVERICK] = &apple_pmu_rtc_maverick, + [STOWE] = &apple_pmu_rtc_stowe, [SERA] = &apple_pmu_rtc_stowe, + [MAVERICK] = &apple_pmu_rtc_maverick, }; bool a = v != BAKU; variant = v; abbey = a; map = layout[v]; offset = (struct nvmem_cell){0}; clock_model = (struct rtc_device){0}; - rtc = (struct apple_pmu_rtc){.hw = hw[v], + rtc = (struct apple_pmu_rtc){.hw = hw[v], .base = v == SERA ? 0xd000 : hw[v]->base, .map = &map, .offset = &offset, .clock = &clock_model}; dev = (struct device){.data = &rtc, .wake = true}; disabled = 0; /* Keep an unrelated writable bit, and each variant's monitor bit. */ @@ -336,8 +340,9 @@ pm_suspend_target_state = PM_SUSPEND_TO_IDLE; } int main(void) { - run_variant(BAKU); run_variant(ABBEY); run_variant(STOWE); run_variant(MAVERICK); - puts("PMU RTC: Baku, Abbey, Stowe and Maverick arithmetic, W1C transactions, Baku clock setting and fault injection passed"); + run_variant(BAKU); run_variant(ABBEY); run_variant(STOWE); run_variant(SERA); + run_variant(MAVERICK); + puts("PMU RTC: Baku, Abbey, Stowe, Sera and Maverick arithmetic, W1C transactions, Baku clock setting and fault injection passed"); return 0; } ''' diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 350e45f0d663e1..6adda888266173 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -275,7 +275,7 @@ def mutations(flag, names, base, expect=KILL): 'pmu-rtc-tests.py': [(out(), PASS)] + mutations('--mutation', ('ack-clobber', 'arm-ack', 'offset-seconds', 'offset-sign', 'event-bit', 'wrong-control', - 'maverick-event', 'stowe-offset', 'baku-limit', + 'maverick-event', 'stowe-offset', 'reg-base', 'baku-limit', 'set-no-round', 'set-negative'), out()), 'perf-mmap-alias-lifecycle-tests.py': [([], PASS)], 'qspi-nvram-tests.py': [(out('--output'), PASS)], From 9daec27d56089a9ff9d54f1ed02c7a00cd484e72 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:46:49 -0500 Subject: [PATCH 0243/1514] dt-bindings: rtc: apple,j700-pmu-rtc: add apple,rtc-base and apple,t8103-pmu-rtc Document the optional apple,rtc-base property carrying the RTC register block's base offset in the parent PMIC's 16-bit SPMI register space, and add apple,t8103-pmu-rtc (with apple,t8112-pmu-rtc fallback and required apple,rtc-base). Using a dedicated property avoids adding #address-cells / #size-cells and reg on a child of an apple,spmi-nvmem node under a #size-cells = <0> SPMI bus, which would trigger OF address-translation cell-count errors during platform-device population. Signed-off-by: Erik Bourget --- .../bindings/rtc/apple,j700-pmu-rtc.yaml | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml b/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml index e23b6c47b1b5ed..38d4713caa7bb8 100644 --- a/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml +++ b/Documentation/devicetree/bindings/rtc/apple,j700-pmu-rtc.yaml @@ -27,6 +27,14 @@ allOf: then: required: - interrupts + - if: + properties: + compatible: + contains: + const: apple,t8103-pmu-rtc + then: + required: + - apple,rtc-base properties: compatible: @@ -42,9 +50,20 @@ properties: - apple,t8132-pmu-rtc - const: apple,t6041-pmu-rtc - items: - - const: apple,t8122-pmu-rtc + - enum: + - apple,t8103-pmu-rtc + - apple,t8122-pmu-rtc - const: apple,t8112-pmu-rtc + apple,rtc-base: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 0xffff + description: + Base address of the RTC register block in the parent PMIC's 16-bit + SPMI register space. Required when a PMU places a shared layout at a + different base (such as Sera on T8103); when omitted, the driver falls + back to the compatible's historical base. + interrupts: maxItems: 1 description: From c94b3c3bfa7684c7d7a249a91f09c82e82744c05 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:42:45 -0500 Subject: [PATCH 0244/1514] arm64: dts: apple: t8103: fix Sera PMU fault-shadow NVMEM offset The T8103 ADT spmi-pmu node places the 16-byte fault shadow cell at 0xa47b (info-fault_shadow = <42107 16>), confirmed by reading spmi_nvmem0 on a J313 (M1 MacBook Air), rather than 0xa67b. No in-tree driver currently references &fault_shadow; the cell is exposed via NVMEM sysfs. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 0c216e45ae54f6..10828045cc7e0a 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1243,8 +1243,8 @@ bits = <3 1>; }; - fault_shadow: fault-shadow@a67b { - reg = <0xa67b 0x10>; + fault_shadow: fault-shadow@a47b { + reg = <0xa47b 0x10>; }; socd: socd@ab00 { From 29e245e97e7cc660daf5b00cd1d36bd4bbbf2057 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:46:50 -0500 Subject: [PATCH 0245/1514] arm64: dts: apple: t8103: wire the PMU RTC and nub-spmi's interrupt nub-spmi raises its peripheral and command-reply interrupts on AIC 343 with its response notification on vector 192. Describe nub_spmi as an interrupt controller, add the Sera PMU RTC child node with apple,rtc-base = <0xd000> (matching the T8103 ADT spmi-pmu info-rtc* properties; compatible with apple,t8112-pmu-rtc; SPMI interrupt 2, wakeup-source, shared rtc_offset cell), and alias rtc0 = &smc_rtc and rtc1 = &pmu_rtc so rtc0 remains the writable SMC RTC. Depends on "spmi: apple: read command response vector from DT" and "rtc: apple-pmu: read the RTC register block base from DT" in this series; do not cherry-pick this DTS change onto a kernel or Stage 2 DTB without those driver commits, or nub-spmi commands will time out waiting on vector 256 and the RTC will address 0xf800 instead of 0xd000. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 10828045cc7e0a..077fc3949002cd 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -22,6 +22,8 @@ aliases { gpu = &gpu; + rtc0 = &smc_rtc; + rtc1 = &pmu_rtc; /* m1n1 copies this machine's Thunderbolt calibration onto the * node these names point at. Current m1n1 looks up usb4-N-acio * and usb4-N-nhi; the packaged 1.6.1 bootloader looks up @@ -1209,12 +1211,26 @@ reg = <0x2 0x3d0d9300 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; + #interrupt-cells = <2>; + interrupt-controller; + interrupt-parent = <&aic>; + interrupts = ; apple,response-vector = <192>; pmic1: pmic@f { compatible = "apple,sera-pmic", "apple,spmi-nvmem"; reg = <0xf SPMI_USID>; + pmu_rtc: rtc { + compatible = "apple,t8103-pmu-rtc", "apple,t8112-pmu-rtc"; + apple,rtc-base = <0xd000>; + interrupt-parent = <&nub_spmi>; + interrupts = <2 IRQ_TYPE_EDGE_RISING>; + nvmem-cells = <&rtc_offset>; + nvmem-cell-names = "rtc_offset"; + wakeup-source; + }; + nvmem-layout { compatible = "fixed-layout"; #address-cells = <1>; @@ -1324,7 +1340,7 @@ compatible = "apple,smc-hwmon"; }; - rtc { + smc_rtc: rtc { compatible = "apple,smc-rtc"; nvmem-cells = <&rtc_offset>; nvmem-cell-names = "rtc_offset"; From cf450974db280fab053360d3701f03389f8aaba0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:01:39 -0500 Subject: [PATCH 0246/1514] thermal: apple-pmp: no shared rail power budget on fan-cooled Macs The T8132 thermal driver restricts the CPU clusters and the G16 GPU through a shared budget on the measured CPU and GPU rails: 8 W sustained, a 600 J burst, and a slow climb toward a die temperature target. That is the fanless MacBook Airs' policy, and fan-cooled T8132 machines (Mac mini J773g, MacBook Pro J604, iMac J623/J624) currently inherit it too. On the M4 Mac mini (J773g), under gpubench render.heavy fill at 1080p, macOS 27.2 (26B123) holds its GPU at the top state (1578 MHz) at 100% active with 8.1-9.6 W of GPU power for the whole run. On Linux the fanless budget switched the same load between S10 and S9 every one to two seconds at a 58-61 C die, and earlier runs sat at S8. Decide whether to apply the shared rail power budget from the device tree rather than a board check: disable it when an available apple,smc-hwmon node describes one or more available fan-* children, and keep it on fanless machines. On fan-cooled Macs the rails are still read and reported through hwmon (with their own report timestamp and live rail sum, so long dark sensor spans do not make hwmon go stale), but restrict nothing; die protection (cooling from 106 C), the thermal governor and critical shutdown are unchanged. A missing or slow SMC rail reading no longer restricts anything on fan-cooled boards either: the GPU's level is published before the read. Signed-off-by: Diljit Singh --- drivers/thermal/apple-pmp-thermal.c | 91 ++++++++++++++++++++++++----- 1 file changed, 77 insertions(+), 14 deletions(-) diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index 1801153f2bb1e7..a42b25f17e14d5 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -62,8 +62,11 @@ static struct { struct device *power_hwmon; unsigned int rail_mw[3]; int power_error; + u64 power_report_ns; u64 gpu_epoch; bool power_polling; + /* The shared measured-rail power budget restricts the CPUs and the GPU. */ + bool power_budget; unsigned int guard_level; bool enabled; long cached_mc; @@ -92,6 +95,27 @@ module_param_named(sample_count, pmp_thermal.sample_count, ullong, 0444); module_param_named(governor_count, pmp_thermal.governor_count, ullong, 0444); module_param_named(ready, pmp_thermal.ready, bool, 0444); +/* + * The shared measured-rail power budget below is the fanless Airs' policy: + * 8 W sustained for the CPU and GPU rails together, a 600 J burst, and a + * slow climb toward a die temperature target. Machines whose device tree + * describes one or more SMC fans (fan-* children under apple,smc-hwmon) + * report the rails without restricting CPU/GPU states; the die protection, + * thermal governor and critical shutdown still apply. + */ +static bool apple_pmp_machine_has_fan(void) +{ + for_each_compatible_node_scoped(hwmon, NULL, "apple,smc-hwmon") { + if (!of_device_is_available(hwmon)) + continue; + for_each_available_child_of_node_scoped(hwmon, child) { + if (of_node_name_prefix(child, "fan-")) + return true; + } + } + return false; +} + static int apple_pmp_power_status(char *buffer, const struct kernel_param *kp) { struct apple_pmp_power_policy *p = &pmp_thermal.power; @@ -181,9 +205,15 @@ static void apple_pmp_power_work(struct work_struct *work) * for a read started in its own epoch, even if detach/attach was brief. */ u64 epoch = apple_pmp_gpu_epoch(pmp_thermal.sensors); + bool budget = pmp_thermal.power_budget; bool dark = false; u64 now; - int ret = apple_pmp_power_read_rails(mw); + int ret; + + /* Without a budget a slow SMC read must not let the GPU's level go stale. */ + if (!budget && epoch) + apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 0, ktime_get_ns()); + ret = apple_pmp_power_read_rails(mw); /* The running reader cannot read zero on both CPU rails. A firmware * reset/all-zero image must not refill the energy bucket; an idle * system may still draw well under 0.1 W on all three rails. @@ -213,8 +243,10 @@ static void apple_pmp_power_work(struct work_struct *work) now - pmp_thermal.cooling.last_ns > 500000000ULL)) ret = -EAGAIN; pmp_thermal.power_error = ret; - if (!ret) + if (!ret) { memcpy(pmp_thermal.rail_mw, mw, sizeof(mw)); + pmp_thermal.power_report_ns = now; + } if (pmp_thermal.gpu_epoch != epoch) { pmp_thermal.gpu_epoch = epoch; p->level[2] = 8; @@ -228,18 +260,28 @@ static void apple_pmp_power_work(struct work_struct *work) * dark: a zero publication selects full protection, and the next * real budget sample republishes its level at once. */ - apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 8, 0); + if (budget) + apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 8, 0); + else + apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 0, + active & BIT(2) ? now : 0); } else { apple_pmp_power_sample(p, now, mw, pmp_thermal.cached_mc, ret); + if (!budget) { + /* Reported only: the samples still fill the hwmon channels. */ + p->level[0] = 0; + p->level[1] = 0; + p->level[2] = 0; + } apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, p->level[2], - active & BIT(2) ? p->last_ns : 0); + active & BIT(2) ? (budget ? p->last_ns : now) : 0); } pr_debug("apple-pmp-thermal: power ns=%llu mc=%ld p_mw=%u e_mw=%u gpu_mw=%u total_mw=%d sustainable_mw=%d allowed_mw=%d credit_mj=%lld p_level=%u e_level=%u gpu_level=%u error=%d\n", now, pmp_thermal.cached_mc, mw[0], mw[1], mw[2], p->total_mw, p->sustainable_mw, p->allowed_mw, p->credit_mj, p->level[0], p->level[1], p->level[2], ret); mutex_unlock(&pmp_thermal.lock); - if (ret) + if (ret && budget) pr_warn_ratelimited("apple-pmp-thermal: power telemetry error %d, retaining minimum CPU/GPU ceilings\n", ret); schedule_delayed_work(&pmp_thermal.power_work, msecs_to_jiffies(500)); @@ -257,10 +299,20 @@ static int apple_pmp_power_read(struct device *dev, enum hwmon_sensor_types type guard(mutex)(&pmp_thermal.lock); if (type != hwmon_power || attr != hwmon_power_input || channel < 0 || channel > 3) return -EINVAL; - if (pmp_thermal.power.fault || pmp_thermal.power_error || - ktime_get_ns() - pmp_thermal.power.last_ns > APPLE_PMP_POWER_STALE_NS) - return -EAGAIN; - *value = 1000L * (channel == 3 ? pmp_thermal.power.total_mw : pmp_thermal.rail_mw[channel]); + if (pmp_thermal.power_budget) { + if (pmp_thermal.power.fault || pmp_thermal.power_error || + ktime_get_ns() - pmp_thermal.power.last_ns > APPLE_PMP_POWER_STALE_NS) + return -EAGAIN; + *value = 1000L * (channel == 3 ? pmp_thermal.power.total_mw : + pmp_thermal.rail_mw[channel]); + } else { + if (pmp_thermal.power_error || !pmp_thermal.power_report_ns || + ktime_get_ns() - pmp_thermal.power_report_ns > APPLE_PMP_POWER_STALE_NS) + return -EAGAIN; + *value = 1000L * (channel == 3 ? + pmp_thermal.rail_mw[0] + pmp_thermal.rail_mw[1] + + pmp_thermal.rail_mw[2] : pmp_thermal.rail_mw[channel]); + } return 0; } @@ -362,8 +414,10 @@ static int apple_pmp_guard(unsigned int level) unsigned int power_level = pmp_thermal.power.level[i]; unsigned int effective; - if (!pmp_thermal.power.last_ns || ktime_get_ns() - - pmp_thermal.power.last_ns > APPLE_PMP_POWER_STALE_NS) + if (!pmp_thermal.power_budget) + power_level = 0; + else if (!pmp_thermal.power.last_ns || ktime_get_ns() - + pmp_thermal.power.last_ns > APPLE_PMP_POWER_STALE_NS) power_level = 8; effective = max(level, power_level); @@ -719,6 +773,7 @@ static int apple_pmp_thermal_setup(void) e_members = GENMASK(2, 1) | GENMASK(9, 6); } apple_pmp_power_init(&pmp_thermal.power); + pmp_thermal.power_budget = !apple_pmp_machine_has_fan(); apple_pmp_cooling_init(&pmp_thermal.cooling); pmp_thermal.guard_level = 8; ret = apple_pmp_add_cluster(0, 0, p_members); @@ -767,7 +822,9 @@ static int apple_pmp_thermal_setup(void) if (ret) goto fail; } - pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, shared measured-rail power budget\n"); + pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, %s\n", + pmp_thermal.power_budget ? "shared measured-rail power budget" : + "rail power reported, no power budget"); pmp_thermal.ready = true; return 0; fail: @@ -801,6 +858,7 @@ static int apple_pmp_thermal_probe(struct platform_device *pdev) pmp_thermal.sensors = sensors; pmp_thermal.cached_error = -EAGAIN; pmp_thermal.power_error = -EAGAIN; + pmp_thermal.power_report_ns = 0; pmp_thermal.valid_ns = 0; pmp_thermal.critical = (struct apple_pmp_confirmation) {}; pmp_thermal.shutdown_requested = false; @@ -842,12 +900,17 @@ static void apple_pmp_thermal_complete(struct device *dev) return; pmp_thermal.sleep_paused = false; scoped_guard(mutex, &pmp_thermal.lock) { + u64 now = ktime_get_ns(); + /* The sleep is no telemetry gap, nor cool time to refill the bucket. */ if (p->last_ns) - p->last_ns = ktime_get_ns(); + p->last_ns = now; + if (pmp_thermal.power_report_ns) + pmp_thermal.power_report_ns = now; if (p->active & BIT(2)) apple_pmp_gpu_publish(pmp_thermal.sensors, pmp_thermal.gpu_epoch, - p->level[2], p->last_ns); + pmp_thermal.power_budget ? p->level[2] : 0, + pmp_thermal.power_budget ? p->last_ns : now); } if (pmp_thermal.power_polling) schedule_delayed_work(&pmp_thermal.power_work, msecs_to_jiffies(500)); From 1487a5806298daf3553eeb27de9fe8dd08d3f6bb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:01:40 -0500 Subject: [PATCH 0247/1514] soc: apple: pmp: find the T8132 temperature records by name The T8132 PMP telemetry reads six die temperature records at fixed SRAM offsets (0x68624..0x68958, stride 0xa4) observed on the 26.6.2 (25G83) firmware. On 27.2 (26B123), runtime SRAM scans find the same six named records 0x1140 bytes later (0x69764..0x69a98, same 0xa4 stride), while the RTKit header word at 0x234 (matching ADT segment-ranges) moves from 0x3c000 to 0x3d000. Each record starts with its NUL-terminated name. After registering, run a freezable delayed worker that checks apple_pmp_telemetry_online() (including the ASC run bit) before touching SRAM: try the 25G83 offsets first, and otherwise scan from the offset read at header word 0x234 for each record name. A candidate must have a validity word of 0 or 1; a name found more than once is taken only in step with a unique first record at the 0xa4 stride, or refused. Until the records are found, and if they never are, reads behave as before. The firmware populates the records after it starts, so the worker retries every second for a minute and logs the offsets it settles on. The host selftest covers moved records, implausible and duplicate copies, ambiguity and range bounds. Signed-off-by: Diljit Singh --- drivers/soc/apple/pmp-telemetry.c | 78 ++++++++++- include/linux/soc/apple/pmp-temps.h | 132 +++++++++++++++++- .../gpu/asahi-m4/check-thermal-sensor.c | 49 ++++++- .../drivers/gpu/asahi-m4/thermal_host.py | 7 +- 4 files changed, 254 insertions(+), 12 deletions(-) diff --git a/drivers/soc/apple/pmp-telemetry.c b/drivers/soc/apple/pmp-telemetry.c index 529f9826e1635e..4e8febffab1aef 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 @@ -35,14 +36,82 @@ struct apple_pmp_telemetry { spinlock_t gpu_lock; struct apple_pmp_gpu_lease gpu; u64 generation; + size_t size; + /* Where the running firmware keeps each temperature record. */ + struct apple_pmp_temp_map temps; + struct delayed_work locate; + unsigned int locate_tries; }; +/* + * The RTKit header word at 0x234 gives the start of the firmware's data + * range in SRAM (0x3c000 on 26.6.2/25G83, 0x3d000 on 27.2/26B123, matching + * ADT segment-ranges). + */ +#define PMP_TEMP_DATA_START_HDR 0x234 +#define PMP_TEMP_LOCATE_MS 1000 +#define PMP_TEMP_LOCATE_TRIES 60 + static bool apple_pmp_telemetry_online(const struct apple_pmp_telemetry *sensors) { return READ_ONCE(sensors->online) && (readl(sensors->asc + 0x44) & BIT(4)); } +static bool apple_pmp_temps_at(struct apple_pmp_telemetry *sensors, + const struct apple_pmp_temp_map *map) +{ + u8 record[PMP_TEMP_RECORD_SIZE]; + unsigned int i; + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + memcpy_fromio(record, sensors->sram + map->offset[i], sizeof(record)); + if (!apple_pmp_temp_record_plausible(record, apple_pmp_temp_records[i].name)) + return false; + } + return true; +} + +/* The firmware fills its records some time after it starts: look until they are there. */ +static void apple_pmp_temps_locate(struct work_struct *work) +{ + struct apple_pmp_telemetry *sensors = + container_of(to_delayed_work(work), struct apple_pmp_telemetry, locate); + struct apple_pmp_temp_map map; + size_t start = 0; + u32 data; + unsigned int i; + int ret; + + if (!apple_pmp_telemetry_online(sensors)) + return; + apple_pmp_temp_map_default(&map); + if (apple_pmp_temps_at(sensors, &map)) + return; + data = readl_relaxed(sensors->sram + PMP_TEMP_DATA_START_HDR); + if (!(data & 3) && data < sensors->size) + start = data; + ret = apple_pmp_temp_locate(sensors->sram, start, sensors->size, &map); + if (!apple_pmp_telemetry_online(sensors)) + return; + if (!ret) { + for (i = 0; i < PMP_TEMP_CHANNELS; i++) + WRITE_ONCE(sensors->temps.offset[i], map.offset[i]); + dev_info(sensors->dev, + "temperature records at %#x %#x %#x %#x %#x %#x (data from %#zx)\n", + map.offset[0], map.offset[1], map.offset[2], map.offset[3], + map.offset[4], map.offset[5], start); + return; + } + if (++sensors->locate_tries < PMP_TEMP_LOCATE_TRIES) { + queue_delayed_work(system_freezable_wq, &sensors->locate, + msecs_to_jiffies(PMP_TEMP_LOCATE_MS)); + return; + } + dev_warn(sensors->dev, "temperature records not found (%d, data from %#zx)\n", + ret, start); +} + int apple_pmp_telemetry_get_hotspot(const struct device_node *np, long *value) { struct apple_pmp_telemetry *sensors; @@ -58,7 +127,7 @@ int apple_pmp_telemetry_get_hotspot(const struct device_node *np, long *value) ret = -ENODEV; break; } - ret = apple_pmp_temp_hotspot(sensors->sram, value); + ret = apple_pmp_temp_hotspot_map(sensors->sram, &sensors->temps, value); /* A crash concurrent with the snapshot invalidates the result. */ if (!apple_pmp_telemetry_online(sensors)) ret = -ENODEV; @@ -189,7 +258,7 @@ static int apple_pmp_sensor_read(void *cookie, unsigned int channel, return -EINVAL; if (!apple_pmp_telemetry_online(sensors)) return -ENODEV; - ret = apple_pmp_temp_sample(sensors->sram, channel, value); + ret = apple_pmp_temp_sample_map(sensors->sram, &sensors->temps, channel, value); return apple_pmp_telemetry_online(sensors) ? ret : -ENODEV; } @@ -265,6 +334,7 @@ static void apple_pmp_telemetry_release(void *data) { struct apple_pmp_telemetry *sensors = data; + cancel_delayed_work_sync(&sensors->locate); mutex_lock(&apple_pmp_telemetry_lock); if (!list_empty(&sensors->list)) list_del_rcu(&sensors->list); @@ -290,6 +360,9 @@ int apple_pmp_telemetry_register(struct device *dev, void __iomem *sram, if (!sensors) return -ENOMEM; sensors->dev = dev; + sensors->size = size; + apple_pmp_temp_map_default(&sensors->temps); + INIT_DELAYED_WORK(&sensors->locate, apple_pmp_temps_locate); INIT_LIST_HEAD(&sensors->list); ret = devm_add_action_or_reset(dev, apple_pmp_telemetry_release, sensors); @@ -303,6 +376,7 @@ int apple_pmp_telemetry_register(struct device *dev, void __iomem *sram, mutex_lock(&apple_pmp_telemetry_lock); list_add_tail_rcu(&sensors->list, &apple_pmp_telemetry_list); mutex_unlock(&apple_pmp_telemetry_lock); + queue_delayed_work(system_freezable_wq, &sensors->locate, 0); if (IS_REACHABLE(CONFIG_HWMON)) { hwmon = devm_hwmon_device_register_with_info( dev, "apple_pmp", sensors, &apple_pmp_hwmon_chip, NULL); diff --git a/include/linux/soc/apple/pmp-temps.h b/include/linux/soc/apple/pmp-temps.h index fe9bf8faf03bbc..a81e666a35f81a 100644 --- a/include/linux/soc/apple/pmp-temps.h +++ b/include/linux/soc/apple/pmp-temps.h @@ -48,16 +48,106 @@ static inline int apple_pmp_temp_decode(const u8 *record, const char *name, long return 0; } -static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, - long *value) +/* + * The temperature record offsets in SRAM vary across firmware builds: the + * defaults above are those observed on the 26.6.2 (25G83) firmware. A map + * holds each record's offset for the running firmware. + */ +struct apple_pmp_temp_map { + u32 offset[PMP_TEMP_CHANNELS]; +}; + +static inline void apple_pmp_temp_map_default(struct apple_pmp_temp_map *map) +{ + unsigned int i; + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) + map->offset[i] = apple_pmp_temp_records[i].offset; +} + +/* Distance between consecutive records in the 25G83 firmware's array. */ +#define PMP_TEMP_RECORD_STRIDE 0xa4 + +/* A record with this name and a validity word of 0 or 1. */ +static inline bool apple_pmp_temp_record_plausible(const u8 *record, const char *name) +{ + return !memcmp(record, name, strlen(name) + 1) && + get_unaligned_le32(record + PMP_TEMP_VALID_OFFSET) <= 1; +} + +/** + * apple_pmp_temp_locate() - find the temperature records of the running firmware + * @sram: the PMP SRAM + * @start: first byte to search, 4-byte aligned + * @end: end of the search, at most the size of the SRAM mapping + * @map: filled with the offsets found + * + * Every record starts with its NUL-terminated name. Each name must appear at + * exactly one plausible record; where it appears at several, the one in step + * with a unique first record (PMP_TEMP_RECORD_STRIDE apart) is taken. + * + * Context: process context; reads up to @end - @start bytes of SRAM. + * Return: 0 with @map filled, -ENOENT if a record is missing, -EEXIST if one + * is ambiguous, -EINVAL for a bad range. @map is written only on success. + */ +static inline int apple_pmp_temp_locate(void __iomem *sram, size_t start, size_t end, + struct apple_pmp_temp_map *map) +{ + u32 found[PMP_TEMP_CHANNELS][4]; + unsigned int count[PMP_TEMP_CHANNELS] = {}; + struct apple_pmp_temp_map result; + u8 record[PMP_TEMP_RECORD_SIZE]; + unsigned int i, j; + size_t off; + + if ((start & 3) || end < PMP_TEMP_RECORD_SIZE || start > end - PMP_TEMP_RECORD_SIZE) + return -EINVAL; + for (off = start; off <= end - PMP_TEMP_RECORD_SIZE; off += 4) { + u32 word = readl_relaxed(sram + off); + + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + const char *name = apple_pmp_temp_records[i].name; + + if (word != get_unaligned_le32(name)) + continue; + memcpy_fromio(record, sram + off, sizeof(record)); + if (apple_pmp_temp_record_plausible(record, name) && + count[i] < ARRAY_SIZE(found[i])) + found[i][count[i]++] = off; + } + } + for (i = 0; i < PMP_TEMP_CHANNELS; i++) { + if (!count[i]) + return -ENOENT; + if (count[i] == 1) { + result.offset[i] = found[i][0]; + continue; + } + if (!i || count[0] != 1) + return -EEXIST; + for (j = 0; j < count[i]; j++) + if (found[i][j] == result.offset[0] + i * PMP_TEMP_RECORD_STRIDE) + break; + if (j == count[i]) + return -EEXIST; + result.offset[i] = found[i][j]; + } + *map = result; + return 0; +} + +static inline int apple_pmp_temp_sample_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + unsigned int index, long *value) { const struct apple_pmp_temp_record *record = &apple_pmp_temp_records[index]; + u32 offset = READ_ONCE(map->offset[index]); u8 first[PMP_TEMP_RECORD_SIZE], second[PMP_TEMP_RECORD_SIZE]; unsigned int attempt; for (attempt = 0; attempt < PMP_TEMP_READ_ATTEMPTS; attempt++) { - memcpy_fromio(first, sram + record->offset, sizeof(first)); - memcpy_fromio(second, sram + record->offset, sizeof(second)); + memcpy_fromio(first, sram + offset, sizeof(first)); + memcpy_fromio(second, sram + offset, sizeof(second)); if (!memcmp(first, second, sizeof(first))) return apple_pmp_temp_decode(first, record->name, value); } @@ -65,8 +155,18 @@ static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, return -EAGAIN; } -static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value, - int *channel) +static inline int apple_pmp_temp_sample(void __iomem *sram, unsigned int index, + long *value) +{ + struct apple_pmp_temp_map map; + + apple_pmp_temp_map_default(&map); + return apple_pmp_temp_sample_map(sram, &map, index, value); +} + +static inline int apple_pmp_temp_hotspot_channel_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + long *value, int *channel) { bool found = false; long hottest = 0, sample; @@ -75,7 +175,7 @@ static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value *channel = -1; for (i = 0; i < ARRAY_SIZE(apple_pmp_temp_records); i++) { - ret = apple_pmp_temp_sample(sram, i, &sample); + ret = apple_pmp_temp_sample_map(sram, map, i, &sample); if (ret == -ENODATA) continue; if (ret) @@ -93,6 +193,24 @@ static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value return 0; } +static inline int apple_pmp_temp_hotspot_channel(void __iomem *sram, long *value, + int *channel) +{ + struct apple_pmp_temp_map map; + + apple_pmp_temp_map_default(&map); + return apple_pmp_temp_hotspot_channel_map(sram, &map, value, channel); +} + +static inline int apple_pmp_temp_hotspot_map(void __iomem *sram, + const struct apple_pmp_temp_map *map, + long *value) +{ + int channel; + + return apple_pmp_temp_hotspot_channel_map(sram, map, value, &channel); +} + static inline int apple_pmp_temp_hotspot(void __iomem *sram, long *value) { int channel; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c index cc961c2aea325d..d2c2a33de278a1 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-sensor.c @@ -36,6 +36,52 @@ static void selftest(void) free(sram); } +/* Records moved in a later firmware are found by name. */ +static void locate_selftest(void) +{ + u8 *sram = calloc(1, PMP_TEMP_SRAM_SIZE); + struct apple_pmp_temp_map map, old; + const u32 shift = 0x1140; + long mc = 0; + int channel = -1; + + assert(sram); + apple_pmp_temp_map_default(&map); + assert(apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map) == -ENOENT); + for (unsigned int i = 0; i < PMP_TEMP_CHANNELS; i++) { + u8 *record = sram + apple_pmp_temp_records[i].offset + shift; + + memcpy(record, apple_pmp_temp_records[i].name, 7); + store32(record + PMP_TEMP_SAMPLE_OFFSET, (80 + i) * 64); + store32(record + PMP_TEMP_VALID_OFFSET, 1); + } + /* The 25G83 offsets no longer hold the records. */ + assert(apple_pmp_temp_hotspot(sram, &mc) == -EIO); + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + for (unsigned int i = 0; i < PMP_TEMP_CHANNELS; i++) + assert(map.offset[i] == apple_pmp_temp_records[i].offset + shift); + assert(!apple_pmp_temp_hotspot_channel_map(sram, &map, &mc, &channel)); + assert(mc == 85000 && channel == 5); + /* A name outside a plausible record (validity word > 1) is no candidate. */ + memcpy(sram + 0x40000, "te001m", 7); + store32(sram + 0x40000 + PMP_TEMP_VALID_OFFSET, 7); + old = map; + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + assert(!memcmp(&map, &old, sizeof(map))); + /* A second plausible copy: the one in step with the first record wins. */ + store32(sram + 0x40000 + PMP_TEMP_VALID_OFFSET, 0); + assert(!apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map)); + assert(map.offset[2] == apple_pmp_temp_records[2].offset + shift); + /* Two copies of the first record: ambiguous, and the map is kept. */ + memcpy(sram + 0x41000, "ta000m", 7); + assert(apple_pmp_temp_locate(sram, 0x3d000, PMP_TEMP_SRAM_SIZE, &map) == -EEXIST); + assert(map.offset[2] == apple_pmp_temp_records[2].offset + shift); + /* The search stays inside the range it is given. */ + assert(apple_pmp_temp_locate(sram, 0x69800, PMP_TEMP_SRAM_SIZE, &map) == -ENOENT); + assert(apple_pmp_temp_locate(sram, 0x3d001, PMP_TEMP_SRAM_SIZE, &map) == -EINVAL); + free(sram); +} + int main(int argc, char **argv) { int raw; @@ -45,7 +91,8 @@ int main(int argc, char **argv) (void)argv; if (argc > 1) { selftest(); - puts("Production PMP hotspot and missing-record checks passed"); + locate_selftest(); + puts("Production PMP hotspot, missing-record and record-location checks passed"); return 0; } while (scanf("%d %u %u %u", &raw, &valid, &actual, &expected) == 4) { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py b/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py index 711c6ac37bc3c2..75d0c1c8e8daa7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/thermal_host.py @@ -13,10 +13,13 @@ def build(root, out, source): 'types.h': '#pragma once\n#include \n#include \n' 'typedef uint8_t u8; typedef uint32_t u32;\n' 'typedef int32_t s32; typedef int64_t s64;\n', - 'io.h': '#pragma once\n#include \n#define __iomem\n' - '#define memcpy_fromio memcpy\n', + 'io.h': '#pragma once\n#include \n#include \n#define __iomem\n' + '#define memcpy_fromio memcpy\n' + 'static inline uint32_t readl_relaxed(const void *p) {\n' + ' uint32_t v; memcpy(&v, p, 4); return v; }\n', 'kernel.h': '#pragma once\n#include \n#include \n' '#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))\n' + '#define READ_ONCE(x) (*(const volatile __typeof__(x) *)&(x))\n' '#define DIV_ROUND_CLOSEST(x, d) ' '(((x) < 0 ? (x) - (d) / 2 : (x) + (d) / 2) / (d))\n', 'string.h': '#pragma once\n#include \n', From 31dcf5e8ab384a420961d0f8364629527685c715 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:24:33 -0500 Subject: [PATCH 0248/1514] soc: apple: pmp: keep the T8132 firmware's own data segment over a sleep Over a system sleep Linux keeps and restores the T8132 PMP's second ADT segment in SRAM: 0x3c000..0xa4000 (0x68000 bytes) on 26.6.2 (25G83). On 27.2 (26B123), ADT segment-ranges and the RTKit header word at 0x234 place that segment at 0x3d000..0xa5000 (still 0x68000 bytes). Keeping the fixed 0x3c000 range would overwrite the preceding 4 KiB page on wake and drop the final 4 KiB page of the segment. Prefer the DT apple,sram-keep property (offset and size supplied by the boot loader from ADT segment-ranges) whenever it is present. When apple,sram-keep is absent on T8132, take the offset from header word 0x234 with the 0x68000 fallback size, refusing any offset that is not 4 KiB-aligned or falls outside SRAM. Signed-off-by: Diljit Singh --- drivers/soc/apple/pmp.rs | 67 ++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 23 deletions(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index afc8a973f77130..4f7360774168e3 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -72,6 +72,8 @@ const BOOTARGS_UUID_VERSION: u32 = 5; const BOOTARGS_OFFSET: usize = 0x22c; const BOOTARGS_SIZE: usize = 0x230; const ASC_CPU_CONTROL_OFFSET: usize = 0x44; +/// The RTKit header word holding the SRAM offset of the firmware's data segment. +const SRAM_DATA_START: usize = 0x234; const PMP_ENDPOINT: u8 = 0x20; const PM_COMMAND_MARKER: u64 = pmp_power::MARKER; const PM_COMMAND_SHIFT: u32 = pmp_power::SHIFT; @@ -181,6 +183,8 @@ struct PmpData { display_error: AtomicI32, /// See [`PmpHwConfig::sram_backup`]. sram_backup: Option<(usize, usize)>, + /// See [`PmpHwConfig::sram_backup_data`]. + sram_backup_data: bool, } impl PmpData { @@ -189,22 +193,18 @@ impl PmpData { let pmp_mmio = pmp_req.iomap_sized::()?.into_devres()?; let asc_req = dev.io_request_by_name(c"asc").ok_or(EINVAL)?; let asc_mmio = asc_req.iomap_sized::()?.into_devres()?; - // The SRAM range kept over a sleep, if the SoC's config has none: from the DT, where - // the boot loader puts it. - let sram_backup = match cfg.sram_backup { - Some(range) => Some(range), - None => { - let node = dev.as_ref().fwnode().ok_or(EIO)?; - let prop_name = c"apple,sram-keep"; - if node.property_present(prop_name) { - let v = node - .property_read_array_vec::(prop_name, 2)? - .required_by(dev.as_ref())?; - Some((v[0] as usize, v[1] as usize)) - } else { - None - } - } + // The SRAM range kept over a sleep: prefer the DT property (`apple,sram-keep`, where + // the boot loader supplies the exact offset and size from ADT segment-ranges) when + // present, otherwise fall back to the SoC's config. + let node = dev.as_ref().fwnode().ok_or(EIO)?; + let prop_name = c"apple,sram-keep"; + let (sram_backup, sram_backup_data) = if node.property_present(prop_name) { + let v = node + .property_read_array_vec::(prop_name, 2)? + .required_by(dev.as_ref())?; + (Some((v[0] as usize, v[1] as usize)), false) + } else { + (cfg.sram_backup, cfg.sram_backup_data) }; Arc::pin_init( try_pin_init!( @@ -219,6 +219,7 @@ impl PmpData { display: AtomicPtr::new(core::ptr::null_mut()), display_error: AtomicI32::new(0), sram_backup, + sram_backup_data, } ), GFP_KERNEL, @@ -485,10 +486,20 @@ impl PmpData { .cast()) } /// Room for what SRAM needs kept, taken first so that running out refuses a sleep cleanly. - fn sram_alloc(&self, sram_size: usize) -> Result> { - let Some((offset, size)) = self.sram_backup else { + fn sram_alloc(&self, io: &Mmio<'_, Region>) -> Result> { + let sram_size = io.size(); + let Some((mut offset, size)) = self.sram_backup else { return Ok(None); }; + if self.sram_backup_data { + let data = io.as_view().relaxed().read32(SRAM_DATA_START) as usize; + // The segment starts on one of the image's 4 KiB pages. + if data % 0x1000 != 0 { + dev_err!(self.dev, "firmware data segment at {:#x}\n", data); + return Err(EINVAL); + } + offset = data; + } if !pmp_bootargs::word_range_valid(offset, size, sram_size) { return Err(EINVAL); } @@ -502,7 +513,7 @@ impl PmpData { let bound_dev = unsafe { self.dev.as_bound() }; let pmp_mmio = self.pmp_mmio.access(bound_dev)?.as_view(); let io = pmp_mmio.as_view().relaxed(); - let mut copy = self.sram_alloc(io.size())?; + let mut copy = self.sram_alloc(&pmp_mmio)?; let rtk = self.rtkit_handle()?; let control = self.asc_cpu_control()?; // SAFETY: the handle stays valid until unbind, which can't run during a system sleep, @@ -529,8 +540,7 @@ impl PmpData { // SAFETY: the PM core only calls a bound device. let bound_dev = unsafe { self.dev.as_bound() }; let pmp_mmio = self.pmp_mmio.access(bound_dev)?.as_view(); - let size = pmp_mmio.as_view().relaxed().size(); - let mut copy = self.sram_alloc(size)?; + let mut copy = self.sram_alloc(&pmp_mmio)?; stop.rtk = self.rtkit_handle()?; stop.control = self.asc_cpu_control()?; stop.sram = core::ptr::null_mut(); @@ -850,6 +860,9 @@ struct PmpHwConfig { /// The range of the firmware's SRAM, as (offset, size) in bytes, that a system sleep keeps /// and writes back. `None` where no sleep has been traced. sram_backup: Option<(usize, usize)>, + /// The range kept is the firmware's data segment: its offset comes from the firmware's + /// header ([`SRAM_DATA_START`]), and `sram_backup` gives its size. + sram_backup_data: bool, } /// Whether a PMP firmware needs endpoint 7 to finish its RTKit boot. @@ -868,6 +881,7 @@ const HW_CFG_DEFAULT: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: None, + sram_backup_data: false, }; /// T8140: the DART translates 42 bits and its DMA window starts at 1 TiB. @@ -876,6 +890,7 @@ const HW_CFG_T8140: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: Some((0x3c000, 0x5c000)), + sram_backup_data: false, }; /// T6041: the DART window starts at 1 TiB; the boot argument header is @@ -886,6 +901,7 @@ const HW_CFG_T6041: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: true, coreanalytics: Ep7::Always, sram_backup: None, + sram_backup_data: false, }; /// T8142: the DART window starts at 1 TiB as on T8140. Its registry-v2 @@ -896,6 +912,7 @@ const HW_CFG_T8142: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::Always, sram_backup: None, + sram_backup_data: false, }; /// T6050: the DART window starts at 1 TiB (ADT dart-pmp0 vm-base) and spans @@ -906,15 +923,19 @@ const HW_CFG_T6050: PmpHwConfig = PmpHwConfig { check_bootargs_uuid: false, coreanalytics: Ep7::No, sram_backup: None, + sram_backup_data: false, }; -/// T8132: the sleep engine reloads `__TEXT` from DRAM at the wake, and only `__DATA` -/// (the ADT's second segment) has to be kept. +/// T8132: over a sleep only the ADT's second segment (0x68000 bytes, starting at 0x3c000 on +/// 26.6.2/25G83 and 0x3d000 on 27.2/26B123 per ADT `segment-ranges` and SRAM header word 0x234) +/// needs to be kept. When the boot loader supplies `apple,sram-keep`, both offset and size come +/// from the DT instead of this fallback. const HW_CFG_T8132: PmpHwConfig = PmpHwConfig { dma_mask: None, check_bootargs_uuid: false, coreanalytics: Ep7::RetainedBoard, sram_backup: Some((0x3c000, 0x68000)), + sram_backup_data: true, }; impl Drop for PmpDriver { From a730d6b3fa4ca74ef1142c185691737bb9b9bfe4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:24:35 -0500 Subject: [PATCH 0249/1514] soc: apple: rtkit: start a firmware that powers itself on without asking it Some firmware reports in by itself once its CPU runs and then acknowledges IOP power on by itself. The T8132 PMP image of macOS 27.2 does: on the M4 Mac mini (J773g), about 0.13 ms after it reports in. After that it answers no IOP power request, so a wake, which clears the acknowledgment and asks again, waits for nothing: apple_pmp 380500000.pmp: RTKit: IOP power acknowledgment failed: -62 macOS 27.2 sends that firmware no IOP power request at all: once it has started the endpoints, the firmware acknowledges IOP power on, and macOS sets the AP on. Other firmware waits to be asked. Add apple_rtkit_boot_or_wake(). It gives the firmware a bounded time to report in (its endpoint map, and CoreAnalytics where the ops need it) and again to acknowledge IOP power on. If both happen, it finishes the boot without a request, as apple_rtkit_boot() does. Otherwise it asks as apple_rtkit_wake() does. A firmware that does not report in by itself therefore gets the request no later than the given time after its CPU starts. Add its Rust wrapper, RtKit::boot_or_wake(). Signed-off-by: Diljit Singh --- drivers/soc/apple/rtkit.c | 78 ++++++++++++++++++++++++++++++--- include/linux/soc/apple/rtkit.h | 8 ++++ rust/kernel/soc/apple/rtkit.rs | 8 ++++ 3 files changed, 89 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..ab8b770e50a5c3 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -481,7 +481,7 @@ static void apple_rtkit_management_rx_iop_pwr_ack(struct apple_rtkit *rtk, dev_dbg(rtk->dev, "RTKit: IOP power state transition: 0x%x -> 0x%x\n", rtk->iop_power_state, new_state); - rtk->iop_power_state = new_state; + WRITE_ONCE(rtk->iop_power_state, new_state); /* * A retained wake: a co-processor may report QUIESCED when it starts @@ -2974,7 +2974,8 @@ int apple_rtkit_quiesce(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_quiesce); -static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) +static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power, + bool reinit_iop_ack) { u64 msg; int ret; @@ -2982,7 +2983,8 @@ static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) if (apple_rtkit_is_running(rtk)) return -EINVAL; - reinit_completion(&rtk->iop_pwr_ack_completion); + if (reinit_iop_ack) + reinit_completion(&rtk->iop_pwr_ack_completion); /* * Use open-coded apple_rtkit_set_iop_power_state since apple_rtkit_boot @@ -2999,13 +3001,79 @@ static int apple_rtkit_wake_common(struct apple_rtkit *rtk, bool early_ap_power) int apple_rtkit_wake(struct apple_rtkit *rtk) { - return apple_rtkit_wake_common(rtk, false); + return apple_rtkit_wake_common(rtk, false, true); } EXPORT_SYMBOL_GPL(apple_rtkit_wake); +/* Wait up to @ms for @c, polling the mailbox where waits poll it: true once it is done. */ +static int apple_rtkit_done_within(struct apple_rtkit *rtk, struct completion *c, + unsigned int ms) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(ms); + long t; + + do { + if ((rtk->sync_syslog_ack || rtk->poll_waits) && apple_rtkit_poll(rtk) < 0) + break; + t = apple_rtkit_wait_timeout(rtk, c, msecs_to_jiffies(1)); + if (t < 0) + return t; + if (t > 0) + return 1; + } while (time_before(jiffies, deadline)); + + return try_wait_for_completion(c); +} + +/* + * Some firmware reports in by itself once its CPU runs and then acknowledges + * IOP power on by itself, answering no request for it after that; other + * firmware waits to be asked. Give the firmware up to @self_ack_ms to report in + * (its endpoint map, and CoreAnalytics where the ops need it) and again to + * acknowledge IOP power on; ask for IOP power as apple_rtkit_wake() does if it + * does neither. + */ +int apple_rtkit_boot_or_wake(struct apple_rtkit *rtk, unsigned int self_ack_ms) +{ + int ret; + + if (apple_rtkit_is_running(rtk)) + return -EINVAL; + if (rtk->crashed) + return -EINVAL; + + ret = apple_rtkit_done_within(rtk, &rtk->epmap_completion, self_ack_ms); + if (ret < 0) + return ret; + if (!ret || rtk->boot_result) + return apple_rtkit_wake(rtk); + if (apple_rtkit_needs_coreanalytics(rtk) && + test_bit(APPLE_RTKIT_EP_COREANALYTICS, rtk->endpoints)) { + ret = apple_rtkit_wait_for_completion(rtk, &rtk->coreanalytics_completion); + if (ret) { + dev_err(rtk->dev, "RTKit: CoreAnalytics readiness failed: %d\n", ret); + return ret; + } + } + + ret = apple_rtkit_done_within(rtk, &rtk->iop_pwr_ack_completion, self_ack_ms); + if (ret < 0) + return ret; + if (READ_ONCE(rtk->iop_power_state) == APPLE_RTKIT_PWR_STATE_ON) { + dev_dbg(rtk->dev, "RTKit: the IOP acknowledged power on by itself\n"); + return apple_rtkit_boot(rtk); + } + /* + * When !ret, iop_pwr_ack_completion was not signaled; keep it intact so + * a late self-ACK arriving before SET_IOP_PWR_STATE is not lost. + */ + return apple_rtkit_wake_common(rtk, false, ret != 0); +} +EXPORT_SYMBOL_GPL(apple_rtkit_boot_or_wake); + int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk) { - return apple_rtkit_wake_common(rtk, true); + return apple_rtkit_wake_common(rtk, true, true); } EXPORT_SYMBOL_GPL(apple_rtkit_wake_early_ap); diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 4db916bb89f09d..a8e6bd482a1027 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -248,6 +248,14 @@ int apple_rtkit_quiesce(struct apple_rtkit *rtk); */ int apple_rtkit_wake(struct apple_rtkit *rtk); +/* + * Start a co-processor whose firmware may acknowledge IOP power on by itself + * once it has reported in: take that acknowledgment if it comes within + * @self_ack_ms, else ask for IOP power as apple_rtkit_wake() does. Call it + * after the co-processor's CPU has been started. + */ +int apple_rtkit_boot_or_wake(struct apple_rtkit *rtk, unsigned int self_ack_ms); + /* Wake helpers which require AP readiness before their IOP power acknowledgment. */ int apple_rtkit_wake_early_ap(struct apple_rtkit *rtk); diff --git a/rust/kernel/soc/apple/rtkit.rs b/rust/kernel/soc/apple/rtkit.rs index f6ae2c60da979c..6a366887f50517 100644 --- a/rust/kernel/soc/apple/rtkit.rs +++ b/rust/kernel/soc/apple/rtkit.rs @@ -368,6 +368,14 @@ impl RtKit { to_result(unsafe { bindings::apple_rtkit_wake(self.rtk) }) } + /// Starts a coprocessor whose firmware may acknowledge IOP power on by itself once it has + /// reported in: takes that acknowledgment if it comes within `self_ack_ms`, and asks for IOP + /// power as [`Self::wake`] does otherwise. + pub fn boot_or_wake(self: Pin<&mut Self>, self_ack_ms: u32) -> Result { + // SAFETY: `rtk` is valid per the type invariant. + to_result(unsafe { bindings::apple_rtkit_boot_or_wake(self.rtk, self_ack_ms) }) + } + /// Waits for the RTKit coprocessor to finish booting. pub fn boot(self: Pin<&mut Self>) -> Result { // SAFETY: `rtk` is valid per the type invariant. From 3af4242ec1d8e898bc8d606940d2eb19f5bc17ff Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:24:36 -0500 Subject: [PATCH 0250/1514] soc: apple: pmp: take the firmware's own IOP power acknowledgment at start The PMP's start wakes the firmware: it asks for IOP power and waits for the acknowledgment. The T8132 PMP image of macOS 27.2 acknowledges IOP power on by itself once it has reported in, and answers no request after that, so on the M4 Mac mini (J773g) on 27.2 the start fails: apple_pmp 380500000.pmp: RTKit: IOP power acknowledgment failed: -62 macOS sends that image no IOP power request. Gate this on PmpHwConfig::self_ack_start (enabled only on T8132) and start such SoCs with apple_rtkit_boot_or_wake(): take the firmware's own acknowledgment if it comes, and ask as before if it doesn't. Other SoCs keep calling rtk.wake() directly with no behavior change or extra wait. On 27.2 the J773g's whole RTKit start takes 1.3 ms from its CPU starting, so the firmware gets 20 ms for each step. Signed-off-by: Diljit Singh --- drivers/soc/apple/pmp.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 4f7360774168e3..6695f19abd8c02 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -74,6 +74,10 @@ const BOOTARGS_SIZE: usize = 0x230; const ASC_CPU_CONTROL_OFFSET: usize = 0x44; /// The RTKit header word holding the SRAM offset of the firmware's data segment. const SRAM_DATA_START: usize = 0x234; +/// How long the PMP's start waits for the firmware to acknowledge IOP power on by itself before +/// asking for it. On the M4 Mac mini (J773g) the 27.2 image's whole RTKit start, from its CPU +/// starting to its acknowledgment and the AP going on, takes 1.3 ms; this is 15 times that. +const PMP_SELF_ACK_MS: u32 = 20; const PMP_ENDPOINT: u8 = 0x20; const PM_COMMAND_MARKER: u64 = pmp_power::MARKER; const PM_COMMAND_SHIFT: u32 = pmp_power::SHIFT; @@ -185,6 +189,8 @@ struct PmpData { sram_backup: Option<(usize, usize)>, /// See [`PmpHwConfig::sram_backup_data`]. sram_backup_data: bool, + /// See [`PmpHwConfig::self_ack_start`]. + self_ack_start: bool, } impl PmpData { @@ -220,6 +226,7 @@ impl PmpData { display_error: AtomicI32::new(0), sram_backup, sram_backup_data, + self_ack_start: cfg.self_ack_start, } ), GFP_KERNEL, @@ -228,7 +235,14 @@ impl PmpData { fn start(&self) -> Result<()> { let mut guard = self.rtkit.lock(); let mut rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.as_mut().wake()?; + // Some T8132 PMP images acknowledge IOP power on by themselves once they have reported in, + // and answer no request for it after that (macOS 27.2; macOS sends it none). Others wait + // to be asked. Only SoCs with `self_ack_start` wait for a self-acknowledgment first. + if self.self_ack_start { + rtk.as_mut().boot_or_wake(PMP_SELF_ACK_MS)?; + } else { + rtk.as_mut().wake()?; + } rtk.start_endpoint(PMP_ENDPOINT) } fn patch_bootargs( @@ -863,6 +877,9 @@ struct PmpHwConfig { /// The range kept is the firmware's data segment: its offset comes from the firmware's /// header ([`SRAM_DATA_START`]), and `sram_backup` gives its size. sram_backup_data: bool, + /// Wait briefly for the firmware to acknowledge IOP power on by itself before sending + /// SET_IOP_PWR_STATE. + self_ack_start: bool, } /// Whether a PMP firmware needs endpoint 7 to finish its RTKit boot. @@ -882,6 +899,7 @@ const HW_CFG_DEFAULT: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::No, sram_backup: None, sram_backup_data: false, + self_ack_start: false, }; /// T8140: the DART translates 42 bits and its DMA window starts at 1 TiB. @@ -891,6 +909,7 @@ const HW_CFG_T8140: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::No, sram_backup: Some((0x3c000, 0x5c000)), sram_backup_data: false, + self_ack_start: false, }; /// T6041: the DART window starts at 1 TiB; the boot argument header is @@ -902,6 +921,7 @@ const HW_CFG_T6041: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::Always, sram_backup: None, sram_backup_data: false, + self_ack_start: false, }; /// T8142: the DART window starts at 1 TiB as on T8140. Its registry-v2 @@ -913,6 +933,7 @@ const HW_CFG_T8142: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::Always, sram_backup: None, sram_backup_data: false, + self_ack_start: false, }; /// T6050: the DART window starts at 1 TiB (ADT dart-pmp0 vm-base) and spans @@ -924,6 +945,7 @@ const HW_CFG_T6050: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::No, sram_backup: None, sram_backup_data: false, + self_ack_start: false, }; /// T8132: over a sleep only the ADT's second segment (0x68000 bytes, starting at 0x3c000 on @@ -936,6 +958,7 @@ const HW_CFG_T8132: PmpHwConfig = PmpHwConfig { coreanalytics: Ep7::RetainedBoard, sram_backup: Some((0x3c000, 0x68000)), sram_backup_data: true, + self_ack_start: true, }; impl Drop for PmpDriver { From d81925b0f02fd11c102a6ca72d2480461a17e84a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:24:37 -0500 Subject: [PATCH 0251/1514] soc: apple: pmp: confirm a registry update with the entry's registered length The PMP firmware sends UPDATE_IOREG (endpoint 0x20, type 0x36) for some of the registry entries it registered, naming each by its own index, and waits for CONFIRM_IOREG (0x37) before it publishes their reports. The driver confirms with a zero value. On the M4 Mac mini (J773g) on macOS 27.2, the PMP image updates four entries at its start (indices 0x17c, 0x17f, 0x182 and 0x18a). macOS answers each with CONFIRM_IOREG 8 (A2I 0x0037000000000008, hv22/hv23 traces). 8 is the length the firmware registered for those entries; the index is word 0x48 of each entry's REGISTER_IOREG buffer. Keep the firmware's index with each registered entry, and gate answering UPDATE_IOREG with that entry's registered length on PmpHwConfig::confirm_ioreg_len (enabled only on T8132). Other SoCs keep the existing zero payload with no behavior change, and on T8132 an index that names no registered entry keeps the old zero with a warning. Signed-off-by: Diljit Singh --- drivers/soc/apple/pmp.rs | 59 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 6695f19abd8c02..86f664474c1d64 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -138,6 +138,9 @@ struct PmpState { allocs: KVec, value_buf: Option, ioreg_entries: KVec, + /// The firmware's own index of each entry in `ioreg_entries` (word 0x48 of its + /// REGISTER_IOREG buffer), by which UPDATE_IOREG names the entry. + ioreg_ids: KVec, /// Held from a system sleep's start until its end. sram: Option, } @@ -149,6 +152,7 @@ impl PmpState { allocs: KVec::with_capacity(10, GFP_KERNEL)?, value_buf: None, ioreg_entries: KVec::with_capacity(340, GFP_KERNEL)?, + ioreg_ids: KVec::with_capacity(340, GFP_KERNEL)?, sram: None, }) } @@ -191,6 +195,8 @@ struct PmpData { sram_backup_data: bool, /// See [`PmpHwConfig::self_ack_start`]. self_ack_start: bool, + /// See [`PmpHwConfig::confirm_ioreg_len`]. + confirm_ioreg_len: bool, } impl PmpData { @@ -227,6 +233,7 @@ impl PmpData { sram_backup, sram_backup_data, self_ack_start: cfg.self_ack_start, + confirm_ioreg_len: cfg.confirm_ioreg_len, } ), GFP_KERNEL, @@ -399,6 +406,14 @@ impl PmpData { let mut size = u32::from_le_bytes(unsafe { <&[u8] as TryInto<[u8; 4]>>::try_into(&msg_buf.as_ref()[0x40..0x44]).unwrap() }); + let id = if msg_buf.size() >= 0x4c { + // SAFETY: TODO + u32::from_le_bytes(unsafe { + <&[u8] as TryInto<[u8; 4]>>::try_into(&msg_buf.as_ref()[0x48..0x4c]).unwrap() + }) + } else { + u32::MAX + }; if size == 0 { let mut name_vec = KVec::with_capacity(0x31, GFP_KERNEL)?; name_vec @@ -446,6 +461,7 @@ impl PmpData { } } state.ioreg_entries.push(size, GFP_KERNEL)?; + state.ioreg_ids.push(id, GFP_KERNEL)?; let index = state.ioreg_entries.len() as u64; let msg = (OPC_REGISTER_IOREG | OPC_ACK_MASK) << OPC_SHIFT | (index << 32) | size as u64; Ok(msg) @@ -598,6 +614,30 @@ impl PmpData { // and `control` is inside the ASC mapping held by `self`. to_result(unsafe { bindings::apple_rtkit_sleep_return(rtk, control) }) } + /// CONFIRM_IOREG's value for an UPDATE_IOREG: the length of the entry the firmware names by + /// its own index, as registered. macOS 27.2 answers so on the M4 Mac mini (J773g), 8 for each + /// of the four entries that image updates. An index that names no registered entry, which + /// macOS doesn't see, gets 0, the answer this driver gave before. + fn confirm_ioreg_value(&self, id: u64) -> u64 { + let state = self.state.lock(); + let found = state + .ioreg_ids + .iter() + .position(|&e| u64::from(e) == id) + .and_then(|i| state.ioreg_entries.get(i).copied()); + drop(state); + match found { + Some(len) => u64::from(len), + None => { + dev_warn!( + self.dev, + "UPDATE_IOREG {:#x} names no registered entry\n", + id + ); + 0 + } + } + } fn recv_message(&self, msg: u64) -> Result<()> { let pm_command = (msg >> PM_COMMAND_SHIFT) & 0xff; if msg & PM_COMMAND_MARKER != 0 && (pm_command == 0x0f || pm_command == 0x10) { @@ -625,8 +665,15 @@ impl PmpData { OPC_REGISTER_IOREG => self.register_ioreg(msg & MSG_IOVA_MASK)?, OPC_SET_IOREG => self.set_ioreg(msg & SET_IOREG_INDEX_MASK)?, // Firmware waits for this confirmation before publishing reports. - // Do not echo the registry index/payload or add a generic ACK bit. - OPC_UPDATE_IOREG => OPC_CONFIRM_IOREG << OPC_SHIFT, + // Do not echo the registry index or add a generic ACK bit. + OPC_UPDATE_IOREG => { + let value = if self.confirm_ioreg_len { + self.confirm_ioreg_value(msg & SET_IOREG_INDEX_MASK) + } else { + 0 + }; + OPC_CONFIRM_IOREG << OPC_SHIFT | value + } _ => { dev_err!(self.dev, "Got unknown message {}", msg); return Err(EIO); @@ -880,6 +927,8 @@ struct PmpHwConfig { /// Wait briefly for the firmware to acknowledge IOP power on by itself before sending /// SET_IOP_PWR_STATE. self_ack_start: bool, + /// Answer UPDATE_IOREG with the registered entry's length instead of 0. + confirm_ioreg_len: bool, } /// Whether a PMP firmware needs endpoint 7 to finish its RTKit boot. @@ -900,6 +949,7 @@ const HW_CFG_DEFAULT: PmpHwConfig = PmpHwConfig { sram_backup: None, sram_backup_data: false, self_ack_start: false, + confirm_ioreg_len: false, }; /// T8140: the DART translates 42 bits and its DMA window starts at 1 TiB. @@ -910,6 +960,7 @@ const HW_CFG_T8140: PmpHwConfig = PmpHwConfig { sram_backup: Some((0x3c000, 0x5c000)), sram_backup_data: false, self_ack_start: false, + confirm_ioreg_len: false, }; /// T6041: the DART window starts at 1 TiB; the boot argument header is @@ -922,6 +973,7 @@ const HW_CFG_T6041: PmpHwConfig = PmpHwConfig { sram_backup: None, sram_backup_data: false, self_ack_start: false, + confirm_ioreg_len: false, }; /// T8142: the DART window starts at 1 TiB as on T8140. Its registry-v2 @@ -934,6 +986,7 @@ const HW_CFG_T8142: PmpHwConfig = PmpHwConfig { sram_backup: None, sram_backup_data: false, self_ack_start: false, + confirm_ioreg_len: false, }; /// T6050: the DART window starts at 1 TiB (ADT dart-pmp0 vm-base) and spans @@ -946,6 +999,7 @@ const HW_CFG_T6050: PmpHwConfig = PmpHwConfig { sram_backup: None, sram_backup_data: false, self_ack_start: false, + confirm_ioreg_len: false, }; /// T8132: over a sleep only the ADT's second segment (0x68000 bytes, starting at 0x3c000 on @@ -959,6 +1013,7 @@ const HW_CFG_T8132: PmpHwConfig = PmpHwConfig { sram_backup: Some((0x3c000, 0x68000)), sram_backup_data: true, self_ack_start: true, + confirm_ioreg_len: true, }; impl Drop for PmpDriver { From 74bdb93282849278fc805d915dffcdb33bf0b590 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 02:24:37 -0500 Subject: [PATCH 0252/1514] soc: apple: pmp: refuse a T8132 image whose header names no data segment A system sleep keeps the T8132 PMP firmware's data segment, at the offset the image's own RTKit header gives (word 0x234). The check that the header names a page-aligned segment inside the SRAM ran only when a sleep began, so a firmware image that doesn't describe itself that way ran until its first sleep, which then failed. Check it at probe, and refuse such an image there with a message. The driver then runs only a T8132 image that describes its own layout, and the M4 PMP pieces can rely on that instead of on the OS firmware's version. An offset of 0 is refused too. Signed-off-by: Diljit Singh --- drivers/soc/apple/pmp.rs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index 86f664474c1d64..a6ee4d4686e403 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -515,24 +515,40 @@ impl PmpData { .wrapping_add(ASC_CPU_CONTROL_OFFSET) .cast()) } - /// Room for what SRAM needs kept, taken first so that running out refuses a sleep cleanly. - fn sram_alloc(&self, io: &Mmio<'_, Region>) -> Result> { - let sram_size = io.size(); + /// The SRAM range a system sleep keeps: with [`PmpHwConfig::sram_backup_data`], the + /// firmware's data segment, at the offset its header gives ([`SRAM_DATA_START`]) and on one + /// of its 4 KiB pages. An image whose header names no such segment is refused. + fn sram_range( + &self, + io: &Mmio<'_, Region>, + ) -> Result> { let Some((mut offset, size)) = self.sram_backup else { return Ok(None); }; if self.sram_backup_data { let data = io.as_view().relaxed().read32(SRAM_DATA_START) as usize; - // The segment starts on one of the image's 4 KiB pages. - if data % 0x1000 != 0 { + if data == 0 || data % 0x1000 != 0 { dev_err!(self.dev, "firmware data segment at {:#x}\n", data); return Err(EINVAL); } offset = data; } - if !pmp_bootargs::word_range_valid(offset, size, sram_size) { + if !pmp_bootargs::word_range_valid(offset, size, io.size()) { + dev_err!( + self.dev, + "SRAM range {:#x}+{:#x} outside the SRAM\n", + offset, + size + ); return Err(EINVAL); } + Ok(Some((offset, size))) + } + /// Room for what SRAM needs kept, taken first so that running out refuses a sleep cleanly. + fn sram_alloc(&self, io: &Mmio<'_, Region>) -> Result> { + let Some((offset, size)) = self.sram_range(io)? else { + return Ok(None); + }; let mut words = KVVec::new(); words.resize(size / 4, 0u32, GFP_KERNEL)?; Ok(Some(SramCopy { offset, words })) @@ -1068,6 +1084,8 @@ impl platform::Driver for PmpDriver { let data = PmpData::new(pdev, cfg)?; let pmp_mmio = data.pmp_mmio.access(pdev.as_ref())?.as_view(); let asc_mmio = data.asc_mmio.access(pdev.as_ref())?.as_view(); + // The firmware's own header describes what a sleep keeps; refuse an image it doesn't. + data.sram_range(&pmp_mmio)?; let node = dev.fwnode().ok_or(EIO)?; let dvid = node .property_read(c"apple,dram-vendor-id") From 6a44e13336c3166ae0f8d1f2c0e83a3d5df0388c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 12:29:35 -0500 Subject: [PATCH 0253/1514] soc: apple: t8132: key the PMP session's pieces on the PMP node compatible MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The M4 PMP session's pieces — its power-vote bridge, its telemetry and thermal policy, and the PMP report's readiness — previously ran only on the Airs and on macOS 26.6.2 firmware because apple_t8132_firmware_path() compares the boot loader's os-fw-version with "26.6.2". On the M4 Mac mini (J773g) on macOS 27.2 there is then no thermal zone, no telemetry, and no vote bridge, so the G16 driver's apple_pmp_j713_gpu_prepare() refuses the PMP session and the GPU cannot come up. None of these pieces depends on the OS firmware's version or the root SoC compatible any more. Each takes what it needs from the PMP firmware itself: - the data segment from the image's header, which the PMP driver now checks at probe; - the temperature records by name; - the IOP power handshake the firmware starts; - each registry entry's length as the firmware registered it. The vote bridge still checks its soc-device record in the firmware's tunables. Key each piece on the PMP node's own compatible ("apple,t8132-pmp-v2") rather than the OS firmware version gate or a root SoC compatible check: - pmp-report.c checks supplier->of_node directly (dropping the unused apple_t8132_firmware_path stubs from the t6030-pmp host test harnesses); - apple-pmp-thermal.c checks sensors->dev->of_node; - pmp-display.h and pmp-telemetry.c check for an available apple,t8132-pmp-v2 node. apple_t8132_firmware_path() stays for the display, DART, and other paths that this series does not touch. Signed-off-by: Diljit Singh --- drivers/pmdomain/apple/pmp-report.c | 4 +--- drivers/soc/apple/pmp-telemetry.c | 8 ++++++-- drivers/thermal/apple-pmp-thermal.c | 7 +++---- include/linux/soc/apple/pmp-display.h | 14 +++++++++++--- tools/asahi/t6030-pmp-graph-tests.c | 11 ----------- tools/asahi/t6030-pmp-supplier-tests.c | 11 ----------- 6 files changed, 21 insertions(+), 34 deletions(-) diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index 67e81f95d5217f..b6c98074a1a5f6 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -35,7 +35,6 @@ #include #include #include -#include #include #include #include @@ -702,8 +701,7 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t struct platform_device *pdev; struct apple_pmp_report *rep; u64 status; - bool t8132 = apple_t8132_firmware_path() && - of_device_is_compatible(supplier->of_node, "apple,t8132-pmp-v2"); + bool t8132 = of_device_is_compatible(supplier->of_node, "apple,t8132-pmp-v2"); int ret; /* A declared report always takes the existing native25 path below. */ diff --git a/drivers/soc/apple/pmp-telemetry.c b/drivers/soc/apple/pmp-telemetry.c index 4e8febffab1aef..33051eaf8b3d8a 100644 --- a/drivers/soc/apple/pmp-telemetry.c +++ b/drivers/soc/apple/pmp-telemetry.c @@ -16,11 +16,15 @@ #include #include #include -#include bool apple_pmp_telemetry_retained_board(void) { - return apple_t8132_firmware_path(); + struct device_node *np = of_find_compatible_node(NULL, NULL, + "apple,t8132-pmp-v2"); + bool match = np && of_device_is_available(np); + + of_node_put(np); + return match; } static LIST_HEAD(apple_pmp_telemetry_list); diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index a42b25f17e14d5..ab11231cb86827 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -850,11 +849,11 @@ static int apple_pmp_thermal_probe(struct platform_device *pdev) { const struct apple_pmp_sensor_data *sensors = dev_get_platdata(&pdev->dev); - /* The M4 PMP sensor records and the Airs' fanless policy are qualified. */ - if (!apple_t8132_firmware_path()) - return -ENODEV; if (!sensors || !sensors->read || !sensors->dev) return -EINVAL; + /* The M4 PMP's sensor records, found by name in its own image. */ + if (!of_device_is_compatible(sensors->dev->of_node, "apple,t8132-pmp-v2")) + return -ENODEV; pmp_thermal.sensors = sensors; pmp_thermal.cached_error = -EAGAIN; pmp_thermal.power_error = -EAGAIN; diff --git a/include/linux/soc/apple/pmp-display.h b/include/linux/soc/apple/pmp-display.h index e65effb337aa82..93cefb5120382c 100644 --- a/include/linux/soc/apple/pmp-display.h +++ b/include/linux/soc/apple/pmp-display.h @@ -3,13 +3,21 @@ #define _LINUX_SOC_APPLE_PMP_DISPLAY_H #include -#include #include -/* The retained M4 bridge and raw thermal records: the M4 firmware path. */ +/* + * The retained PMP bridge and raw thermal records: keyed on an available + * `apple,t8132-pmp-v2` node rather than the root SoC compatible or OS + * firmware version. + */ static inline bool apple_pmp_j713_board(void) { - return apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132"); + struct device_node *np = of_find_compatible_node(NULL, NULL, + "apple,t8132-pmp-v2"); + bool match = np && of_device_is_available(np); + + of_node_put(np); + return match; } struct device; diff --git a/tools/asahi/t6030-pmp-graph-tests.c b/tools/asahi/t6030-pmp-graph-tests.c index 079e497499eef8..6a6607b85ade03 100644 --- a/tools/asahi/t6030-pmp-graph-tests.c +++ b/tools/asahi/t6030-pmp-graph-tests.c @@ -471,17 +471,6 @@ static bool of_machine_is_compatible(const char *s) { return !strcmp(s, "apple,t6030"); } -/* As in . */ -static inline bool apple_t8132_air(void) -{ - return of_machine_is_compatible("apple,j713") || - of_machine_is_compatible("apple,j715"); -} -/* The qualified-firmware term: these harnesses model no /chosen. */ -static inline bool apple_t8132_firmware_path(void) -{ - return apple_t8132_air(); -} static bool of_property_read_bool(const struct device_node *n, const char *p) { if (!strcmp(p, "apple,always-on")) diff --git a/tools/asahi/t6030-pmp-supplier-tests.c b/tools/asahi/t6030-pmp-supplier-tests.c index 7c3a7020b52158..48d61037038fbb 100644 --- a/tools/asahi/t6030-pmp-supplier-tests.c +++ b/tools/asahi/t6030-pmp-supplier-tests.c @@ -170,17 +170,6 @@ static bool of_machine_is_compatible(const char *name) { return !strcmp(machine, name); } -/* As in . */ -static inline bool apple_t8132_air(void) -{ - return of_machine_is_compatible("apple,j713") || - of_machine_is_compatible("apple,j715"); -} -/* The qualified-firmware term: these harnesses model no /chosen. */ -static inline bool apple_t8132_firmware_path(void) -{ - return apple_t8132_air(); -} static struct device_node *of_find_compatible_node(struct device_node *from, const char *type, const char *compat) From 0b5979cdc37d0ca5797575caa50b25594d775099 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 12:29:36 -0500 Subject: [PATCH 0254/1514] soc: apple: t8132-platform-handoff: key platform handoff on the PMP node compatible t8132_platform_handoff() previously returned early unless the boot loader reported macOS 26.6.2 firmware or the Mac was an Air. On other firmware, macOS 27.2 among them, it applied neither of its two parts: - The PMGR ownership policy. Without it Linux owns every power domain in the board tree, with auto-PM written to each one at probe, including domains that stay firmware-owned (AIC, GPIO, display) or out of Linux's reach. On the M4 Mac mini (J773g) on 27.2 that ends in an SError when the PCIe controller probes. - The memory nodes (MCC, PMC and CLPC) for a loader tree that lacks them. They depend on the PMP path, which now self-describes from the firmware image header. Key the handoff on the presence of an "apple,t8132-pmp-v2" node rather than the root SoC compatible or OS firmware version string, and reuse that node reference when populating the missing platform nodes. Signed-off-by: Diljit Singh --- drivers/soc/apple/t8132-platform-handoff.c | 24 +++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/drivers/soc/apple/t8132-platform-handoff.c b/drivers/soc/apple/t8132-platform-handoff.c index c25a95d198d446..0061a7892b8dab 100644 --- a/drivers/soc/apple/t8132-platform-handoff.c +++ b/drivers/soc/apple/t8132-platform-handoff.c @@ -314,18 +314,29 @@ static struct device_node *__init t8132_find_gfx(void) static int __init t8132_platform_handoff(void) { const void *data = __dtb_t8132_platform_data_begin; - struct device_node *soc, *pmp = NULL, *gpu = NULL, *gfx = NULL; + struct device_node *soc = NULL, *pmp = NULL, *gpu = NULL, *gfx = NULL; struct of_changeset *cs; unsigned int added = 0, changed = 0; int root, node, ret; - if (!apple_t8132_firmware_path()) + /* + * Key the handoff on the PMP node's own compatible rather than the root + * SoC compatible or OS firmware version. The copy only adds nodes the + * loader's tree lacks, and the PMP path they depend on runs on every + * firmware whose image header names its data segment. + */ + pmp = of_find_compatible_node(NULL, NULL, "apple,t8132-pmp-v2"); + if (!pmp) return 0; - if (fdt_check_header(data)) - return -EINVAL; + if (fdt_check_header(data)) { + ret = -EINVAL; + goto out; + } soc = of_find_node_by_path("/soc"); - if (!soc) - return -ENODEV; + if (!soc) { + ret = -ENODEV; + goto out; + } cs = kzalloc_obj(*cs); if (!cs) { ret = -ENOMEM; @@ -336,7 +347,6 @@ static int __init t8132_platform_handoff(void) if (ret) goto destroy; - pmp = of_find_compatible_node(NULL, NULL, "apple,t8132-pmp-v2"); gpu = of_find_compatible_node(NULL, NULL, "apple,agx-t8132"); gfx = gpu ? of_parse_phandle(gpu, "power-domains", 0) : NULL; if (!gfx) From ae550867e8d811c15778bf24d8434a7f3fde6260 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 01:43:12 -0500 Subject: [PATCH 0255/1514] mfd: macsmc: write WKTP full-wake state on probe and full resume On Apple Silicon machines whose SMC exposes the 1-byte writable WKTP (Wake Type / Silent Running) key (such as T8132 J773g), waking from firmware deep sleep on a non-HID source leaves the SMC in Silent Running (Power Nap) mode until the OS writes WKTP = 0 to signal a full wake. While stuck in Silent Running, the SMC holds the fan at 0 RPM, clamps thermal/power budgets under load, and emits thermal-pressure sleep requests until the next cold reboot. Probe SMC_KEY(WKTP) dynamically via apple_smc_get_key_info() during apple_smc_probe() (requiring a 1-byte key with APPLE_SMC_WRITABLE) with no board allowlists, device-tree properties, or module knobs: - Record smc->has_wktp and write WKTP = 0 once at probe so warm-boot or kexec paths start out of Silent Running. - In apple_smc_complete(), after the quarantine check and any sleep_warned rollback, write WKTP = 0 when smc->has_wktp and !pm_dark_wake(), logging a warning on failure. - Add KUnit coverage in drivers/mfd/macsmc-test.c for WKTP probing, full-wake completion, dark-wake skipping, and quarantined skipping. Signed-off-by: Diljit Singh --- drivers/mfd/macsmc-test.c | 124 +++++++++++++++++++++++++++++++++++++ drivers/mfd/macsmc.c | 32 ++++++++++ include/linux/mfd/macsmc.h | 2 + 3 files changed, 158 insertions(+) diff --git a/drivers/mfd/macsmc-test.c b/drivers/mfd/macsmc-test.c index 2dec0920f982dc..fedc84197d884f 100644 --- a/drivers/mfd/macsmc-test.c +++ b/drivers/mfd/macsmc-test.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Included by macsmc.c; the command and SRAM transports are stubbed. */ +#include #include struct macsmc_test_context { @@ -14,6 +15,9 @@ struct macsmc_test_context { unsigned int seen_count; int ap_power_result; u64 record; + smc_key last_write_key; + size_t last_write_size; + u8 last_write_byte; }; #define MACSMC_TEST_AP_IDLE 0 @@ -26,6 +30,11 @@ static int macsmc_test_command(struct apple_smc *smc, u64 cmd, u64 arg, KUNIT_EXPECT_TRUE(kunit_get_current_test(), mutex_is_locked(&smc->mutex)); ctx->calls++; + if (cmd == SMC_MSG_WRITE_KEY) { + ctx->last_write_key = arg; + ctx->last_write_size = size; + ctx->last_write_byte = ctx->shmem[0]; + } if (ctx->seen_count < ARRAY_SIZE(ctx->seen)) ctx->seen[ctx->seen_count++] = cmd == SMC_MSG_WRITE_KEY ? get_unaligned((u32 *)ctx->shmem) : arg; @@ -395,6 +404,117 @@ static void macsmc_port_reasons_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_smc_port_reasons_only(&ctx->smc, BIT_ULL(43))); } +static struct device *macsmc_test_attach_dev(struct kunit *test, + struct macsmc_test_context *ctx) +{ + struct device *dev = kunit_device_register(test, "macsmc-test"); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dev_set_drvdata(dev, &ctx->smc); + ctx->smc.dev = dev; + return dev; +} + +static void macsmc_wktp_probe_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + const u8 ro_wire[] = { 1, 'u', 'i', '8', ' ', APPLE_SMC_READABLE }; + const u8 wide_wire[] = { 2, 'u', 'i', '1', '6', + APPLE_SMC_READABLE | APPLE_SMC_WRITABLE }; + const u8 valid_wire[] = { 1, 'u', 'i', '8', ' ', + APPLE_SMC_READABLE | APPLE_SMC_WRITABLE | + APPLE_SMC_FUNCTION }; + + macsmc_test_attach_dev(test, ctx); + + /* Absent WKTP leaves has_wktp clear and issues no write. */ + ctx->result = -EIO; + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + /* Read-only or wrong-sized WKTP is ignored. */ + ctx->result = 0; + ctx->calls = 0; + memcpy(ctx->shmem, ro_wire, sizeof(ro_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + ctx->calls = 0; + memcpy(ctx->shmem, wide_wire, sizeof(wide_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_FALSE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + + /* Valid 1-byte writable WKTP enables tracking and writes full wake (0). */ + ctx->calls = 0; + memcpy(ctx->shmem, valid_wire, sizeof(valid_wire)); + apple_smc_probe_wktp(&ctx->smc); + KUNIT_EXPECT_TRUE(test, ctx->smc.has_wktp); + KUNIT_EXPECT_EQ(test, ctx->calls, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_write_key, SMC_KEY(WKTP)); + KUNIT_EXPECT_EQ(test, ctx->last_write_size, sizeof(u8)); + KUNIT_EXPECT_EQ(test, ctx->last_write_byte, (u8)SMC_WAKE_TYPE_FULL); +} + +static void macsmc_wktp_full_wake_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + pm_suspend_clear_flags(); + + /* Without WKTP capability, complete() issues no write. */ + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); + + /* Full wake writes WKTP = 0 to exit Silent Running / Power Nap. */ + ctx->smc.has_wktp = true; + ctx->shmem[0] = 0xa5; + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_write_key, SMC_KEY(WKTP)); + KUNIT_EXPECT_EQ(test, ctx->last_write_size, sizeof(u8)); + KUNIT_EXPECT_EQ(test, ctx->last_write_byte, (u8)SMC_WAKE_TYPE_FULL); +} + +static void macsmc_wktp_dark_wake_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + if (!IS_ENABLED(CONFIG_PM_SLEEP)) + kunit_skip(test, "CONFIG_PM_SLEEP disabled"); + + ctx->smc.has_wktp = true; + pm_suspend_clear_flags(); + pm_set_dark_wake(); + apple_smc_complete(dev); + pm_suspend_clear_flags(); + + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); +} + +static void macsmc_wktp_quarantined_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct device *dev = macsmc_test_attach_dev(test, ctx); + + pm_suspend_clear_flags(); + ctx->smc.has_wktp = true; + ctx->smc.saved_enabled = true; + ctx->smc.saved_recovery = true; + + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); + + ctx->smc.saved_recovery = false; + ctx->smc.saved_fault = -EIO; + apple_smc_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->calls, 0U); +} + static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_key_info_lock_test), KUNIT_CASE(macsmc_key_index_test), @@ -412,6 +532,10 @@ static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_lid_wake_test), KUNIT_CASE(macsmc_wake_reason_test), KUNIT_CASE(macsmc_port_reasons_test), + KUNIT_CASE(macsmc_wktp_probe_test), + KUNIT_CASE(macsmc_wktp_full_wake_test), + KUNIT_CASE(macsmc_wktp_dark_wake_test), + KUNIT_CASE(macsmc_wktp_quarantined_test), {} }; diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index ad4d84f9c3dd2b..746bb81d312fac 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -55,6 +55,9 @@ /* Restart and power-off go through atomic writes; give the SMC time. */ #define SMC_ATOMIC_TIMEOUT_MS 5000 +/* WKTP wake type: 0 exits Silent Running / Power Nap for a full wake. */ +#define SMC_WAKE_TYPE_FULL 0U + static const struct mfd_cell apple_smc_devs[] = { MFD_CELL_NAME("macsmc-input"), MFD_CELL_NAME("macsmc-power"), @@ -629,6 +632,30 @@ static const struct apple_smc_wake_reason apple_smc_j714s_wake_reasons[] = { { 43, "USB2_plug" }, { 44, "USB2_wake" }, { 45, "aupo" }, { 48, "rtc" }, { } }; +static void apple_smc_write_full_wake(struct apple_smc *smc) +{ + int ret; + + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WAKE_TYPE_FULL); + if (ret < 0) + dev_warn(smc->dev, "Failed to write WKTP = %u: %d\n", + SMC_WAKE_TYPE_FULL, ret); +} + +static void apple_smc_probe_wktp(struct apple_smc *smc) +{ + struct apple_smc_key_info info; + int ret; + + ret = apple_smc_get_key_info(smc, SMC_KEY(WKTP), &info); + if (ret < 0 || info.size != sizeof(u8) || + !(info.flags & APPLE_SMC_WRITABLE)) + return; + + smc->has_wktp = true; + apple_smc_write_full_wake(smc); +} + static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -726,6 +753,8 @@ static int apple_smc_probe(struct platform_device *pdev) if (ret) return ret; + apple_smc_probe_wktp(smc); + t6050 = of_device_is_compatible(dev->of_node, "apple,t6050-smc"); if (t6050) ret = devm_mfd_add_devices(smc->dev, PLATFORM_DEVID_NONE, @@ -1717,6 +1746,9 @@ static void apple_smc_complete(struct device *dev) smc->sleep_warned = false; } smc->sleep_policy = NULL; + + if (smc->has_wktp && !pm_dark_wake()) + apple_smc_write_full_wake(smc); } /* diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 0bfd2079d0b969..1924162d54df35 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -123,6 +123,8 @@ struct apple_smc { const struct apple_sleep_smc_policy *sleep_policy; u64 sleep_warn_ack; bool sleep_pmvc_info; + /* WKTP (1-byte writable) supported: notify SMC on full wake. */ + bool has_wktp; /* The saved scope's pmVC after ANS, and when it was answered. */ bool saved_pmvc_sent; u64 saved_pmvc_at; From 266cdb85feb435dfd47899616c16834ea620accd Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 23:25:40 -0500 Subject: [PATCH 0256/1514] drm/apple: dcp: reconnect fixed HDMI DPTX link after deep sleep dcp_s2r_ext_suspend() disconnects external displays via dcp_external_disconnect(), dropping dptxport[0].connected and deactivating the LPDPTX PHY, and stops DCPEXT firmware. On resume, dcp_s2r_restart_done() re-enables Type-C reconnect work, which only reattaches Type-C routes and leaves fixed HDMI outputs (such as J773g dcpext0 with hdmi-hpd-gpios and no Type-C route) permanently disconnected because the HPD IRQ is edge-triggered. Factor fixed-HDMI HPD sampling and DPTX port 0 reconnection into dcp_fixed_hdmi_reconnect() (shared with dcp_enable_dp2hdmi_hpd(), logging any dcp_dptx_connect() error). Across dcp_s2r_ext_suspend(), disable hdmi_hpd_irq while firmware is stopping (re-enabling it on pre-stop refusals and leaving it disabled while firmware is crashed or stopped so HPD edges cannot race a stopped coprocessor). In dcp_s2r_restart_done(), re-initialize fixed HDMI rails/fabric (dcp_fabric_hdmi_reinit() on native outputs, or hdmi_pwren/dp2hdmi_pwren GPIOs otherwise), reconnect via dcp_fixed_hdmi_reconnect(), and re-enable hdmi_hpd_irq via dcp_fabric_run_resume(). Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/dcp-internal.h | 1 + drivers/gpu/drm/apple/dcp.c | 86 ++++++++++++++++++++++++---- 2 files changed, 77 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..58a24e5e171ba0 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -843,6 +843,7 @@ struct apple_dcp { bool sleep_v27_unhandled; bool s2r_active; bool s2r_stopped; + bool s2r_hdmi_irq_disabled; /* DPMS off stopped the firmware and lowered the domains; DPMS on brings them back. */ bool dpms_powered_off; /* Refused its idle with the display off: the firmware still runs, the display is dark. */ diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..424cb1ea732ac6 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -4932,20 +4932,43 @@ static const struct dcp_fabric_resume_ops dcp_resume_ops = { .sample = dcp_resume_sample, }; +/* + * Sample fixed-HDMI HPD and reconnect DPTX port 0 (or power off / report + * unplug when no sink is present). Shared by initial bring-up and deep sleep + * recovery. + */ +static void dcp_fixed_hdmi_reconnect(struct apple_dcp *dcp, bool poweroff_unplugged) +{ + bool connected; + int ret; + + if (dcp_is_typec_output(dcp) || !dcp->hdmi_hpd || + READ_ONCE(dcp->active_typec_route)) + return; + + /* Check HPD before enabling the edge-triggered IRQ. */ + connected = gpiod_get_value_cansleep(dcp->hdmi_hpd); + dev_info(dcp->dev, "%s: DP2HDMI HPD connected:%d\n", __func__, connected); + + if (connected && !READ_ONCE(dcp->hdmi_yielded)) { + ret = dcp_dptx_connect(dcp, 0); + if (ret) + dev_warn(dcp->dev, "HDMI DPTX connect failed: %d\n", ret); + } else if (!connected) { + if (poweroff_unplugged) + _dcp_poweroff(dcp); + else if (dcp->connector) + disconnected_hpd_event(dcp->connector); + } +} + static int dcp_enable_dp2hdmi_hpd(struct apple_dcp *dcp) { if (dcp_is_typec_output(dcp)) { if (READ_ONCE(dcp->typec_cable_connected)) dcp_dptx_connect(dcp, 0); - } else if (dcp->hdmi_hpd) { - /* Check HPD before enabling the edge-triggered IRQ. */ - bool connected = gpiod_get_value_cansleep(dcp->hdmi_hpd); - dev_info(dcp->dev, "%s: DP2HDMI HPD connected:%d\n", __func__, connected); - - if (connected && !READ_ONCE(dcp->hdmi_yielded)) - dcp_dptx_connect(dcp, 0); - else if (!connected) - _dcp_poweroff(dcp); + } else { + dcp_fixed_hdmi_reconnect(dcp, true); } if (dcp->hdmi_hpd_irq) @@ -8686,11 +8709,28 @@ static int dcp_s2r_stop_crashed(struct apple_dcp *dcp) return 0; } +static void dcp_s2r_hdmi_irq_disable(struct apple_dcp *dcp) +{ + if (dcp->hdmi_hpd_irq && !dcp->s2r_hdmi_irq_disabled) { + disable_irq(dcp->hdmi_hpd_irq); + dcp->s2r_hdmi_irq_disabled = true; + } +} + +static void dcp_s2r_hdmi_irq_enable(struct apple_dcp *dcp) +{ + if (dcp->hdmi_hpd_irq && dcp->s2r_hdmi_irq_disabled) { + dcp->s2r_hdmi_irq_disabled = false; + dcp_fabric_run_resume(&dcp_resume_ops, dcp); + } +} + static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) { int ret; if (READ_ONCE(dcp->s2r_fw_down)) { + dcp_s2r_hdmi_irq_disable(dcp); dcp_s2r_stop_failed_start(dcp); dcp_s2r_find_darts(dcp); dcp->s2r_stopped = true; @@ -8705,9 +8745,15 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) return 0; } - /* No A500 and no disconnect: the link and its crossbar output just go down. */ + /* + * No A500 and no disconnect: the link and its crossbar output just go down. + * If dcp_s2r_stop_crashed() fails, it calls dcp_s2r_restart_failed_stop(), + * which re-enables hdmi_hpd_irq on a clean restart or leaves it disabled + * while the firmware stays crashed. + */ if (dcp_s2r_stops_crashed(dcp)) { dcp_disable_typec_work(dcp, false); + dcp_s2r_hdmi_irq_disable(dcp); dcp_typec_route_park(dcp); return dcp_s2r_stop_crashed(dcp); } @@ -8718,9 +8764,11 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) dev_dbg(dcp->dev, "a display is attached: released for the sleep, connected again after it\n"); dcp_disable_typec_work(dcp, false); + dcp_s2r_hdmi_irq_disable(dcp); ret = dcp_external_disconnect(dcp, false); if (ret) { dcp_enable_typec_work(dcp); + dcp_s2r_hdmi_irq_enable(dcp); return ret; } @@ -8730,6 +8778,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) if (iomfb_queue_settle(dcp, msecs_to_jiffies(500))) { iomfb_pause_presentation(dcp, false); dcp_enable_typec_work(dcp); + dcp_s2r_hdmi_irq_enable(dcp); dev_err(dcp->dev, "display updates still pending, refusing sleep\n"); return -EBUSY; } @@ -8742,6 +8791,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) dev_err(dcp->dev, "no reply to A500: %d\n", ret); WRITE_ONCE(dcp->crashed, true); dcp_typec_route_unpark(dcp); + /* Keep typec work and hdmi_hpd_irq disabled while firmware is crashed. */ return ret == -ETIMEDOUT ? -EBUSY : ret; } usleep_range(4000, 5000); @@ -8753,6 +8803,7 @@ static int dcp_s2r_ext_suspend(struct apple_dcp *dcp) readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS)); WRITE_ONCE(dcp->crashed, true); dcp_typec_route_unpark(dcp); + /* Keep typec work and hdmi_hpd_irq disabled while firmware is crashed. */ return ret == -ETIMEDOUT ? -EBUSY : ret; } @@ -9272,6 +9323,7 @@ static void dcp_s2r_restart_done(struct apple_dcp *dcp, int ret) dcp_typec_route_unpark(dcp); if (ret) { WRITE_ONCE(dcp->crashed, true); + /* Firmware stays stopped/crashed, so hdmi_hpd_irq intentionally stays disabled. */ dev_warn(dcp->dev, "firmware stopped for sleep, display stays off until reboot\n"); return; } @@ -9281,6 +9333,20 @@ static void dcp_s2r_restart_done(struct apple_dcp *dcp, int ret) iomfb_pause_presentation(dcp, false); if (ext && !READ_ONCE(dcp->typec_work_enabled)) dcp_enable_typec_work(dcp); + if (ext && !dcp_is_typec_output(dcp) && dcp->hdmi_hpd && + !READ_ONCE(dcp->active_typec_route)) { + if (dcp->external_native) { + dcp_fabric_hdmi_reinit(dcp, "after deep sleep"); + } else { + if (dcp->hdmi_pwren) + gpiod_set_value_cansleep(dcp->hdmi_pwren, 1); + if (dcp->dp2hdmi_pwren) + gpiod_set_value_cansleep(dcp->dp2hdmi_pwren, 1); + } + dcp_fixed_hdmi_reconnect(dcp, false); + } + if (ext) + dcp_s2r_hdmi_irq_enable(dcp); } /* From 06633f4f6b3996ee849eb1aa7200f325600f6cfc Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:18:11 +1100 Subject: [PATCH 0257/1514] arm64: apple: handle M4+ WFI/WFIT state loss by MIDR alone Apple M4 and later cores (MIDR part 0x052 and up) can come back from WFI and WFIT with their general-purpose and FP/SIMD registers cleared. The kernel already handles this on every such part through midr_is_apple_m4_or_later(): cpu_do_idle() saves the registers around WFI (d58647b808f6, 34649b455f4a) and cpuinfo records WFxT as absent (5186d2e3ebbe), so ARM64_HAS_WFXT and HWCAP2_WFXT stay off. Several per-chip leftovers from before that predicate remained: - has_wfxt() (848cb14c09cd, Thomas Glanzmann) kept a T8142/T6050/T8152 MIDR list. The sanitised ID_AA64ISAR2_EL1 already reads WFxT as 0 on those parts and on every other M4+ part, so the list never changes the result. Go back to has_cpuid_feature() and HWCAP_CAP() for WFxT. Its comment also pointed at apple_m5_needs_wait_save(), which no longer exists. - __delay() busy-waited on T8142 and T6050 only (dbb5e443c126), to stay off WFIT. WFIT cannot be reached there any more, and the WFE event-stream loop that remains is the same path arm64.nowfxt selected on T8152 (0 bad SHA-256 runs in 288 under schedutil on J873) and the path T8140 and T6040 run today. WFE is also what smp_cond_load_*() and the spinlocks run on these cores all the time. Drop the list. - An idle=nop from the boot loader was ignored on T8142 and T6050 only (5c9cbb25dba8, 72f8eecf708b). Ignore it on every part that takes the register-saving WFI. Older aura and m1n1 append it on every M4+ chip, after the user's arguments; spinning idle costs 85-92 C against 43 C on T8140, about 90 C on T8142 and about 10 W on T6050. apple_keep_idle_nop still keeps it for comparisons. - t8140-j700.dts set bootargs = "arm64.nowfxt" in /chosen, marked temporary until the kernel stopped using WFxT on T8140. The kernel already did (part 0x060/0x061 is matched). Remove it. Document the per-part evidence at midr_is_apple_m4_or_later(), and why parts nobody measured are matched (the same core generations, and later parts by default). On EFI boots (U-Boot -> GRUB -> EFI stub) the stub replaces /chosen/bootargs with the loader's command line, so neither the DT bootargs nor the arguments aura appends reached the kernel there. For those users the only change is __delay() on T8142/T6050 using WFE instead of spinning. Direct (non-EFI) boots stop depending on loader arguments. Signed-off-by: Ryan Murray --- .../admin-guide/kernel-parameters.txt | 11 +++--- arch/arm64/boot/dts/apple/t8140-j700.dts | 5 --- arch/arm64/include/asm/cputype.h | 26 ++++++++++++- arch/arm64/kernel/cpufeature.c | 39 +------------------ arch/arm64/kernel/cpuinfo.c | 7 ++-- arch/arm64/kernel/idle.c | 29 +++++++------- arch/arm64/lib/delay.c | 15 ------- 7 files changed, 51 insertions(+), 81 deletions(-) diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 388b32354bede2..cbbe028f254c4c 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -553,11 +553,12 @@ Kernel parameters See header of arch/x86/kernel/apm_32.c. apple_keep_idle_nop - [ARM64,EARLY] On T6050 and T8142, keep idle=nop. - These cores idle in WFI by default, and an idle=nop - that the boot loader appends is ignored, because the - kernel preserves the registers WFI loses there. With - this flag idle=nop spins the idle loop as elsewhere. + [ARM64,EARLY] On Apple M4 and later cores, keep + idle=nop. These cores idle in WFI by default, and an + idle=nop that an older boot loader appends is + ignored, because the kernel preserves the registers + WFI loses there. With this flag idle=nop spins the + idle loop as elsewhere. apparmor= [APPARMOR] Disable or enable AppArmor at boot time Format: { "0" | "1" } diff --git a/arch/arm64/boot/dts/apple/t8140-j700.dts b/arch/arm64/boot/dts/apple/t8140-j700.dts index b20146bb491516..940431d7aac3bb 100644 --- a/arch/arm64/boot/dts/apple/t8140-j700.dts +++ b/arch/arm64/boot/dts/apple/t8140-j700.dts @@ -47,11 +47,6 @@ #size-cells = <2>; ranges; stdout-path = "serial0"; - /* - * Temporary: the secondary cores lose state in WFIT and the - * kernel does not yet stop using WFxT on T8140 by itself. - */ - bootargs = "arm64.nowfxt"; framebuffer0: framebuffer@0 { compatible = "apple,simple-framebuffer", "simple-framebuffer"; diff --git a/arch/arm64/include/asm/cputype.h b/arch/arm64/include/asm/cputype.h index 8215a3b1dac4ee..9fe3c491c96074 100644 --- a/arch/arm64/include/asm/cputype.h +++ b/arch/arm64/include/asm/cputype.h @@ -296,7 +296,31 @@ static inline u32 __attribute_const__ read_cpuid_id(void) return read_cpuid(MIDR_EL1); } -/* Apple part numbers from Donan onward identify the M4 and later generations. */ +/* + * Apple part numbers from Donan onward identify the M4 and later generations. + * + * These cores can come back from WFI and WFIT with their general-purpose and + * FP/SIMD registers cleared; SP and memory survive. On M1 to M3 the boot + * loader sets the cores up to keep that state in WFI (CYC_OVRD); from M4 on + * that register is locked before the kernel runs. The kernel keeps the state + * itself on every part matched here: cpu_do_idle() saves it around WFI, and + * WFxT is recorded as absent so that nothing executes WFIT. Neither idle=nop + * nor arm64.nowfxt is needed. + * + * Seen on: + * 0x054/0x055 T6040 (M4 Pro, J616s): the boot P core in WFI. + * 0x060/0x061 T8140 (A18 Pro, J700): the secondaries in WFI and WFIT. + * 0x062/0x063 T8142 (M5, J813): WFI in the idle loop, WFIT in a cpufreq + * __delay(). + * 0x064/0x065 T6050 (M5 Pro/Max, J714s/J716s): WFI. + * 0x072/0x073 T8152 (M6, J873): WFI at the first idle; WFIT under + * schedutil gave wrong SHA-256 results. + * Not measured separately, matched as the same core generations: 0x052/0x053 + * T8132 (M4), 0x058/0x059 T6041 (M4 Max), 0x068/0x069 and 0x06c/0x06d (M5 + * Pro/Max/Ultra variants). Later parts are matched as well: where the state + * would have survived, the save costs a few stores per idle entry; where it + * does not, a missing save corrupts the idle loop. + */ static inline bool midr_is_apple_m4_or_later(u32 midr) { return MIDR_IMPLEMENTOR(midr) == ARM_CPU_IMP_APPLE && diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index 4e5ae7bf52b06a..3d245b3213acdd 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2627,40 +2627,6 @@ test_has_gicv5_legacy(const struct arm64_cpu_capabilities *entry, int scope) return !!(read_sysreg_s(SYS_ICC_IDR0_EL1) & ICC_IDR0_EL1_GCIE_LEGACY); } -/* - * Apple T8152 (M6) cores clear architectural state across WFIT, the FP/SIMD - * registers included. __delay() would execute it from any context, including - * the cpufreq transition polling that load-driven governors run on a CPU - * whose current task still has live FP/SIMD state: on J873 (M6) 25-56% of - * SHA-256 runs gave wrong results under schedutil. Treat WFxT as absent - * there, as arm64.nowfxt does, so __delay() uses WFE. T8142 (M5) was not - * measured; it is included because apple_m5_needs_wait_save() groups its - * cores with T8152 for this state loss. - * - * T6050 (M5 Pro and Max, parts 0x064 and 0x065) was not measured for the WFIT - * state loss either. On the K116s, at EL1 under the boot loader's monitor, - * ID_AA64ISAR2_EL1.WFxT reads 0, so the capability is not set there today - * with or without these entries, and __delay() already avoids WFIT on these - * cores by MIDR. The entries are a precaution for a kernel started at EL2, - * where the field may read as implemented. - */ -static bool has_wfxt(const struct arm64_cpu_capabilities *entry, int scope) -{ - static const struct midr_range apple_wfxt_loses_state[] = { - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8142_E)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8142_P)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T6050_064)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T6050_065)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8152_E)), - MIDR_ALL_VERSIONS(MIDR_CPU_MODEL(ARM_CPU_IMP_APPLE, APPLE_CPU_PART_T8152_P)), - {} - }; - - if (is_midr_in_range_list(apple_wfxt_loses_state)) - return false; - return has_cpuid_feature(entry, scope); -} - static const struct arm64_cpu_capabilities arm64_features[] = { #ifdef CONFIG_ARM64_USER4K_EXPERIMENTAL { @@ -3165,7 +3131,7 @@ static const struct arm64_cpu_capabilities arm64_features[] = { .desc = "WFx with timeout", .capability = ARM64_HAS_WFXT, .type = ARM64_CPUCAP_SYSTEM_FEATURE, - .matches = has_wfxt, + .matches = has_cpuid_feature, ARM64_CPUID_FIELDS(ID_AA64ISAR2_EL1, WFxT, IMP) }, { @@ -3529,8 +3495,7 @@ static const struct arm64_cpu_capabilities arm64_elf_hwcaps[] = { HWCAP_CAP(ID_AA64ISAR2_EL1, CSSC, CMPBR, CAP_HWCAP, KERNEL_HWCAP_CMPBR), HWCAP_CAP(ID_AA64ISAR2_EL1, RPRFM, IMP, CAP_HWCAP, KERNEL_HWCAP_RPRFM), HWCAP_CAP(ID_AA64ISAR2_EL1, RPRES, IMP, CAP_HWCAP, KERNEL_HWCAP_RPRES), - /* WFxT loses state on apple_wfxt_loses_state parts; hide the hwcap there too. */ - HWCAP_CAP_MATCH_ID(has_wfxt, ID_AA64ISAR2_EL1, WFxT, IMP, CAP_HWCAP, KERNEL_HWCAP_WFXT), + HWCAP_CAP(ID_AA64ISAR2_EL1, WFxT, IMP, CAP_HWCAP, KERNEL_HWCAP_WFXT), HWCAP_CAP(ID_AA64ISAR2_EL1, MOPS, IMP, CAP_HWCAP, KERNEL_HWCAP_MOPS), HWCAP_CAP(ID_AA64ISAR2_EL1, BC, IMP, CAP_HWCAP, KERNEL_HWCAP_HBC), #ifdef CONFIG_ARM64_SME diff --git a/arch/arm64/kernel/cpuinfo.c b/arch/arm64/kernel/cpuinfo.c index 006cec695867df..f93f4e8782dc5c 100644 --- a/arch/arm64/kernel/cpuinfo.c +++ b/arch/arm64/kernel/cpuinfo.c @@ -551,9 +551,10 @@ static void __cpuinfo_store_cpu(struct cpuinfo_arm64 *info) info->reg_id_aa64isar2 = read_cpuid(ID_AA64ISAR2_EL1); /* * Timed waits bypass the register-saving idle path on Apple M4 and - * later cores. Record WFxT as absent on every CPU, so the sanitised - * register hides it from the kernel, KVM guests and userspace - * (HWCAP2_WFXT) and a boot argument cannot bring it back. + * later cores, and lose the same state there (see + * midr_is_apple_m4_or_later()). Record WFxT as absent on every CPU, + * so the sanitised register hides it from the kernel, KVM guests and + * userspace (HWCAP2_WFXT) and a boot argument cannot bring it back. */ if (IS_ENABLED(CONFIG_ARCH_APPLE) && midr_is_apple_m4_or_later(info->reg_midr)) diff --git a/arch/arm64/kernel/idle.c b/arch/arm64/kernel/idle.c index 0d76030f78205b..d197776f5db8b8 100644 --- a/arch/arm64/kernel/idle.c +++ b/arch/arm64/kernel/idle.c @@ -53,8 +53,9 @@ static bool apple_wfi_loses_regs __ro_after_init; static bool apple_keep_idle_nop __initdata; /* - * The boot loader appends idle=nop after the user's arguments, so it cannot - * be overridden on the command line. This flag keeps it anyway. + * Older boot loaders append idle=nop after the user's arguments on these + * cores, so it cannot be overridden on the command line, and it is ignored + * below. This flag keeps it anyway, for comparisons. */ static int __init setup_apple_keep_idle_nop(char *arg) { @@ -65,22 +66,20 @@ early_param("apple_keep_idle_nop", setup_apple_keep_idle_nop); void __init apple_wfi_quirk_init(void) { - u32 model = read_cpuid_id() & MIDR_CPU_MODEL_MASK; + if (!midr_is_apple_m4_or_later(read_cpuid_id())) + return; + + apple_wfi_loses_regs = true; + pr_info("Apple: preserving registers across WFI\n"); - if (midr_is_apple_m4_or_later(read_cpuid_id())) { - apple_wfi_loses_regs = true; - pr_info("Apple: preserving registers across WFI\n"); - } /* - * aura (J813) and m1n1 (T6050) pass idle=nop on M4 and later for - * kernels without this quirk. Spinning idle keeps every core busy - * (cpuidle's WFI states spin too): on T8142 the SoC sits near 90 C - * and throttles, on T6050 the system draws about 10 W more at idle. - * WFI is safe here. + * aura and m1n1 used to pass idle=nop on M4 and later for kernels + * without this path. Spinning idle keeps every core busy (cpuidle's + * WFI states spin too): on T8142 the SoC sits near 90 C and + * throttles, on T6050 the system draws about 10 W more at idle, on + * T8140 the die idles at 85-92 C instead of 43 C. WFI is safe here. */ - if (idle == ARM64_IDLE_NOP && !apple_keep_idle_nop && - (model == MIDR_APPLE_T8142_E || model == MIDR_APPLE_T8142_P || - model == MIDR_APPLE_T6050_064 || model == MIDR_APPLE_T6050_065)) { + if (idle == ARM64_IDLE_NOP && !apple_keep_idle_nop) { idle = ARM64_IDLE_WFI; pr_info("Apple: idling in WFI, ignoring idle=nop\n"); } diff --git a/arch/arm64/lib/delay.c b/arch/arm64/lib/delay.c index 591c2552147724..e278e060e78a9e 100644 --- a/arch/arm64/lib/delay.c +++ b/arch/arm64/lib/delay.c @@ -14,7 +14,6 @@ #include #include -#include #define USECS_TO_CYCLES(time_usecs) \ xloops_to_cycles((time_usecs) * 0x10C7UL) @@ -43,19 +42,6 @@ void __delay(unsigned long cycles) { cycles_t start = __delay_cycles(); - /* - * T8142 and T6050 can clear registers on WFIT just as it does on WFI. A delay - * may run with live kernel SIMD state, so the idle task's save/flush - * path is not applicable here. Keep the core awake for short delays. - */ - if (IS_ENABLED(CONFIG_ARCH_APPLE)) { - u32 midr = read_cpuid_id() & MIDR_CPU_MODEL_MASK; - - if (midr == MIDR_APPLE_T8142_E || midr == MIDR_APPLE_T8142_P || - midr == MIDR_APPLE_T6050_064 || midr == MIDR_APPLE_T6050_065) - goto counter_delay; - } - if (alternative_has_cap_unlikely(ARM64_HAS_WFXT)) { u64 end = start + cycles; @@ -74,7 +60,6 @@ void __delay(unsigned long cycles) wfe(); } -counter_delay: while ((__delay_cycles() - start) < cycles) cpu_relax(); } From 128023ecf2f75f9e62c5bb6603ddfe0aa041b41d Mon Sep 17 00:00:00 2001 From: chrisohearn <137103567+chrisohearn@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:09:31 -0700 Subject: [PATCH 0258/1514] drm/apple: describe an internal panel without a known gamut as Display P3 The EDID built for an internal panel takes its primaries from the firmware or, without a complete set, from the colour target the ADT's /product artwork-display-gamut names. A gamut string the driver does not know leaves no target, and the EDID then carries zero red, green and blue primaries with only the D65 white. The K114s (MacBook Pro 14-inch OLED, M5 Pro, firmware 27.2) is such a panel: its ADT says "Rec2020", with a valid version-1 primary-calibration-matrix. Compositors take the zero primaries at face value. Hyprland's colour management builds its conversion matrix from them, the matrix is singular, and every frame comes out black while the firmware completes each swap. Every untagged RGB surface on an internal panel is already tagged P3-D65 (iomfb_template.c: "the panel's own primaries (P3-D65, as its EDID reports)"). Describe a panel whose ADT names no known space in that same space, so the EDID and the surface tag agree, and log it. The Rec2020 string is not mapped to BT.2020 primaries: the firmware is handed P3-tagged surfaces, so BT.2020 primaries in the EDID would make compositors encode for a wider space than the one the pixels are shown in. dcp_panel_edid() keeps its contract (no target, white only) for its other callers and tests. KUnit: parser_panel_adt_color_target covers a "Rec2020" ADT (no target of its own, Display P3 primaries, D65 and gamma 2.2 in the EDID) and a known gamut keeping its own space. Not booted: built, and the Apple display KUnit suites pass in QEMU. Closes: https://github.com/aurora-silicon/linux/issues/2060 Signed-off-by: chrisohearn <137103567+chrisohearn@users.noreply.github.com> [ryan: taken alone from #2087, onto the current integration/aurora; booted on a K114s by the author, see #2087] Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-display-metadata.c | 13 +++++++++++ drivers/gpu/drm/apple/dcp-display-metadata.h | 1 + drivers/gpu/drm/apple/dcp.c | 5 +++- drivers/gpu/drm/apple/parser-test.c | 24 +++++++++++++++++++- 4 files changed, 41 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-display-metadata.c b/drivers/gpu/drm/apple/dcp-display-metadata.c index bcc3f70d8db7ac..1e393c2ea9d2b0 100644 --- a/drivers/gpu/drm/apple/dcp-display-metadata.c +++ b/drivers/gpu/drm/apple/dcp-display-metadata.c @@ -198,6 +198,19 @@ const struct dcp_color_space *dcp_panel_gamut_color_space(enum dcp_panel_gamut g } } +/* + * An internal panel's colour target: the standard space its ADT names, or + * else Display P3. Every untagged RGB surface on an internal panel is tagged + * P3-D65 (see iomfb_template.c), so a panel whose ADT names no space known + * here (the K114s says "Rec2020") is described in the space it is driven in. + * Zero primaries are no description: compositors build a singular + * conversion matrix from them. + */ +const struct dcp_color_space *dcp_panel_color_target(enum dcp_panel_gamut gamut) +{ + return dcp_panel_gamut_color_space(gamut) ?: dcp_color_space_lookup("display-p3"); +} + /* * Firmware chromaticities win. Without a complete, valid set, use the panel's * named target. Without either the block keeps its nominal white only. diff --git a/drivers/gpu/drm/apple/dcp-display-metadata.h b/drivers/gpu/drm/apple/dcp-display-metadata.h index 20ba07d691fe70..9a12bebaacbf21 100644 --- a/drivers/gpu/drm/apple/dcp-display-metadata.h +++ b/drivers/gpu/drm/apple/dcp-display-metadata.h @@ -50,6 +50,7 @@ struct dcp_color_space { const struct dcp_color_space *dcp_color_space_lookup(const char *name); const struct dcp_color_space *dcp_panel_gamut_color_space(enum dcp_panel_gamut gamut); +const struct dcp_color_space *dcp_panel_color_target(enum dcp_panel_gamut gamut); struct drm_edid; struct drm_display_mode; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..994116dcec6a14 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1292,7 +1292,10 @@ static void dcp_panel_read_adt(struct apple_dcp *dcp) dcp->panel.height_mm = panel.height_mm; if (dcp->panel_identity) dcp->panel_identity->adt = panel.identity; - dcp->panel.color_target = ret ? NULL : dcp_panel_gamut_color_space(panel.gamut); + if (ret || !dcp_panel_gamut_color_space(panel.gamut)) + dev_info(dcp->dev, "panel ADT: no known colour gamut, EDID primaries default to Display P3\n"); + dcp->panel.color_target = + dcp_panel_color_target(ret ? DCP_PANEL_GAMUT_UNSPECIFIED : panel.gamut); if (desktop || dcp->fw_compat == DCP_FIRMWARE_V_27_0) dcp->panel.edr_ceiling = dcp_edr_ceiling(panel.edr_potential_headroom); /* diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index e79da0fb0ad08e..547337c5d4753c 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -1654,6 +1654,28 @@ static void parser_panel_adt_color_target(struct kunit *test) for (unsigned int i = 0; i < ARRAY_SIZE(srgb); i++) KUNIT_EXPECT_EQ(test, panel_color_coord(raw, i), srgb[i]); + /* + * A gamut not known here (the K114s ADT says "Rec2020") gives no + * target of its own: the panel is described as Display P3, the space + * its surfaces are tagged with, never with zero primaries. + */ + parser_adt_synthetic_matrix(matrix, 1 << 20); + size = parser_adt_color_fixture(adt, sizeof(adt), "Rec2020", sizeof("Rec2020"), + matrix, sizeof(matrix)); + panel = (struct dcp_panel_adt) {}; + KUNIT_ASSERT_EQ(test, dcp_panel_adt_parse(adt, size, &panel), 0); + KUNIT_EXPECT_EQ(test, panel.gamut, DCP_PANEL_GAMUT_UNSPECIFIED); + KUNIT_EXPECT_NULL(test, dcp_panel_gamut_color_space(panel.gamut)); + target = dcp_panel_color_target(panel.gamut); + KUNIT_EXPECT_PTR_EQ(test, target, dcp_color_space_lookup("display-p3")); + raw = panel_color_edid(test, &metadata, target); + for (unsigned int i = 0; i < ARRAY_SIZE(p3); i++) + KUNIT_EXPECT_EQ(test, panel_color_coord(raw, i), p3[i]); + KUNIT_EXPECT_EQ(test, raw->gamma, 120); + /* A known gamut keeps its own space. */ + KUNIT_EXPECT_PTR_EQ(test, dcp_panel_color_target(DCP_PANEL_GAMUT_SRGB), + dcp_color_space_lookup("srgb")); + /* Unknown, malformed, short, wrong-version, unbounded, non-neutral or singular. */ for (unsigned int fault = 0; fault < 7; fault++) { const char *name = fault == 0 ? "AdobeRGB" : "P3"; @@ -1843,7 +1865,7 @@ static void parser_panel_publication(struct kunit *test, dcp->fw_compat = fw_compat; dcp->panel.width_mm = panel.width_mm; dcp->panel.height_mm = panel.height_mm; - dcp->panel.color_target = dcp_panel_gamut_color_space(panel.gamut); + dcp->panel.color_target = dcp_panel_color_target(panel.gamut); id->adt = panel.identity; dcp->connector = connector; dcp->modes = &mode; From a004bcbadd2c5b3473e36fdeb744b43b87c64c82 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 05:20:24 -0500 Subject: [PATCH 0259/1514] drm/apple: register the system-sleep notifier at module init apple_drm_init() registers its PM notifier at the end of the component bind, so register_pm_notifier() takes the PM notifier chain's rwsem under component_mutex. With the Apple CIO driver that closes a cycle, which lockdep reports on the first suspend of a J775c (Mac Studio, M5 Max) with a Thunderbolt link: component_mutex -> pm_chain_head.rwsem apple_drm_bind() -> register_pm_notifier() acio->lock -> tb->lock -> component_mutex apple_cio_tbt_switch_set() holds acio->lock around of_platform_populate(), which probes the NHI: tb_domain_add() and usb4_port_device_add() -> component_add() pm_chain_head.rwsem -> acio->lock pm_suspend() -> apple_cio_dp_pm_notify() With a suspend, a cable event and the display bind at the same time, each waits on the next. Register one notifier at module init instead. A bound display subsystem joins a list under a new leaf mutex at the end of init and leaves it at the start of uninit, and the notifier walks that list. register_pm_notifier() then never runs under component_mutex, and the new mutex is taken only below component_mutex and the notifier chain. The notifier still acts only on PM_POST_SUSPEND for a bound device whose outputs a dark wake held, as before. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/apple_drv.c | 46 +++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index ff047f59fd73f8..b2a134cc66f247 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -73,11 +73,27 @@ struct apple_drm_private { bool s2r_skipped; /* A dark wake left the outputs as the suspend did, for the next resume. */ bool dark_held; - struct notifier_block pm_nb; + /* On apple_drm_pm_list while bound, for the system-sleep notifier. */ + struct list_head pm_node; }; static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data); +/* + * One system-sleep notifier for every bound display subsystem, registered at + * module init. Registering it from the component bind would take the PM + * notifier chain's rwsem under component_mutex, while a PM notifier that + * takes a lock held around a component_add() (as the Apple CIO driver's does + * with its device lock, which it holds while populating the NHI) closes a + * cycle: component_mutex -> pm_chain_head.rwsem -> acio->lock -> + * component_mutex. apple_drm_pm_lock is a leaf below both. + */ +static DEFINE_MUTEX(apple_drm_pm_lock); +static LIST_HEAD(apple_drm_pm_list); +static struct notifier_block apple_drm_pm_nb = { + .notifier_call = apple_drm_pm_notify, +}; + /* Component readiness is later than platform probe/bind. */ static DEFINE_MUTEX(apple_g15_display_lock); static struct device *apple_t6030_display; @@ -1713,6 +1729,7 @@ static int apple_drm_init(struct device *dev) if (IS_ERR(apple)) return PTR_ERR(apple); + INIT_LIST_HEAD(&apple->pm_node); dev_set_drvdata(dev, apple); ret = drmm_mode_config_init(&apple->drm); @@ -1855,8 +1872,9 @@ static int apple_drm_init(struct device *dev) goto err_unbind; } - apple->pm_nb.notifier_call = apple_drm_pm_notify; - register_pm_notifier(&apple->pm_nb); + mutex_lock(&apple_drm_pm_lock); + list_add_tail(&apple->pm_node, &apple_drm_pm_list); + mutex_unlock(&apple_drm_pm_lock); return 0; @@ -1881,7 +1899,9 @@ static void apple_drm_uninit(struct device *dev) if (apple->aborted) return; - unregister_pm_notifier(&apple->pm_nb); + mutex_lock(&apple_drm_pm_lock); + list_del_init(&apple->pm_node); + mutex_unlock(&apple_drm_pm_lock); /* Before anything of the DRM device is torn down. */ t8132_ext_drm_fini(&apple->drm); @@ -2105,12 +2125,19 @@ static void apple_platform_complete(struct device *dev) /* It failed before ->prepare() reached this device, so ->complete() didn't run either. */ static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data) { - struct apple_drm_private *apple = container_of(nb, struct apple_drm_private, pm_nb); + struct apple_drm_private *apple; - if (action == PM_POST_SUSPEND && apple->dark_held) { - dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); - apple_drm_resume_outputs(apple); + if (action != PM_POST_SUSPEND) + return NOTIFY_DONE; + + mutex_lock(&apple_drm_pm_lock); + list_for_each_entry(apple, &apple_drm_pm_list, pm_node) { + if (apple->dark_held) { + dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); + apple_drm_resume_outputs(apple); + } } + mutex_unlock(&apple_drm_pm_lock); return NOTIFY_DONE; } @@ -2163,9 +2190,11 @@ static int __init appledrm_register(void) ret = dcp_register(); if (ret) goto unregister_audio; + register_pm_notifier(&apple_drm_pm_nb); ret = platform_driver_register(&apple_platform_driver); if (!ret) return 0; + unregister_pm_notifier(&apple_drm_pm_nb); dcp_unregister(); unregister_audio: apple_j613_display_fail(); @@ -2183,6 +2212,7 @@ static void __exit appledrm_unregister(void) #endif dcp_unregister(); platform_driver_unregister(&apple_platform_driver); + unregister_pm_notifier(&apple_drm_pm_nb); } module_init(appledrm_register); From 857fa8373d67051336d677c4b0abc09de9120cd5 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:00:00 -0500 Subject: [PATCH 0260/1514] drm/asahi: share the 26.x wire helpers and clean bound TTBAT slots Factor three 26.x wire encoders out of the M3 code so another firmware interface can use them without copying: the 0x18-byte submission entry (m3_channel_format::submission_entry), the runtime directory's channel pointers and the cache-flush ring pair (m3_init_26::write_channels, write_flush_ring), and the 0x28-byte register record (m3_mmio_26::write_record). The M3 paths call them and encode the same bytes; host tests cover the submission entry and the flush-ring pair. Bind also writes back the TTBAT slot it fills when the UAT's walker does not snoop the CPU caches (an adopted UAT without the clean_tables quirk). Until now only the tables were written back there. The asahi-m4 retention harness models UatInner::clean_poc, which bind now reads. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/m3/m3_channel_format.rs | 33 +++++++++ drivers/gpu/drm/asahi/m3/m3_config.rs | 9 +-- drivers/gpu/drm/asahi/m3/m3_init_26.rs | 71 ++++++++++++++----- drivers/gpu/drm/asahi/m3/m3_mmio_26.rs | 6 ++ drivers/gpu/drm/asahi/m3/m3_runtime.rs | 2 +- drivers/gpu/drm/asahi/mmu.rs | 7 ++ .../gpu/asahi-m4/test-mmu-retention.py | 4 +- 7 files changed, 104 insertions(+), 28 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs index 45eebda112b738..d3cc240e898cbe 100644 --- a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs +++ b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs @@ -7,6 +7,27 @@ use super::m3_init_layout::Error; pub(crate) const CONTROL_BYTES: usize = 64; pub(crate) const RECEIVE_BYTES: usize = 72; pub(crate) const SLOTS: u32 = 256; +pub(crate) const SUBMISSION_BYTES: usize = 0x18; +/// Two firmware engine classes for each of the three data masters. +pub(crate) const ENGINE_CLASSES: u32 = 6; + +/// Wire entry shared by G15G 26.6.2 and G14G 26B123. The caller owns the queue +/// and publishes its contents before advancing the channel's shared write index. +pub(crate) fn submission_entry( + selector: u32, queue: u64, position: u16, stamp: u8, first: bool, +) -> Result<[u8; SUBMISSION_BYTES], Error> { + if selector > 2 { + return Err(Error::Bounds); + } + let mut entry = [0; SUBMISSION_BYTES]; + entry[8..16].copy_from_slice(&queue.to_le_bytes()); + entry[16..20].copy_from_slice(&selector.to_le_bytes()); + entry[20..22].copy_from_slice(&position.to_le_bytes()); + entry[22] = stamp; + entry[23] = u8::from(first); + Ok(entry) +} + #[derive(Clone, Copy, Debug)] pub(crate) enum Action { @@ -163,6 +184,18 @@ mod tests { assert!(payload_offset(9, 0).is_err()); } + #[test] + fn first_and_reused_compute_entries_match_the_26b123_wire_format() { + let expected = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0x12, 0x34, 0xa0, 0xff, 0xff, + 0xff, 2, 0, 0, 0, 0x23, 1, 7, 1]; + let queue = 0xffff_ffa0_3412_4000; + assert_eq!(submission_entry(2, queue, 0x123, 7, true).unwrap(), expected); + let reused = submission_entry(2, queue, 0x123, 7, false).unwrap(); + assert_eq!(&reused[..23], &expected[..23]); + assert_eq!(reused[23], 0); + assert!(submission_entry(3, queue, 0, 0, true).is_err()); + } + #[test] fn release_uses_the_packed_owned_pointer() { let action = Action::Release { diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index 88ca6f9c765afc..b6646e223c4f19 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -299,12 +299,9 @@ impl Config { let state=kind*2;let ring=state+1; let w=self.objects[state].read_u32(0x20)?; if w>=256 || self.objects[state].read_u32(0)?!=w { return Err(EBUSY); } - let mut message=[0u8;0x18]; - message[8..16].copy_from_slice(&queue.to_le_bytes()); - message[16..20].copy_from_slice(&(kind as u32).to_le_bytes()); - message[20..22].copy_from_slice(&head.to_le_bytes()); - message[22]=event;message[23]=u8::from(new); // New queue; caller selected the event slot. - self.objects[ring].write(w as usize*0x18,&message)?; + let message = super::m3_channel_format::submission_entry(kind as u32, queue, head, event, new) + .map_err(|_| EINVAL)?; + self.objects[ring].write(w as usize * message.len(), &message)?; agx_memory::publish(); self.objects[state].u32(0x20,(w+1)%256)?; agx_memory::publish(); diff --git a/drivers/gpu/drm/asahi/m3/m3_init_26.rs b/drivers/gpu/drm/asahi/m3/m3_init_26.rs index a86432b2bbe2b5..750f6065103bc4 100644 --- a/drivers/gpu/drm/asahi/m3/m3_init_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_init_26.rs @@ -19,11 +19,24 @@ pub(crate) const LOG_THREADS: usize = 9; pub(crate) const RX_BYTES: usize = 0x48; pub(crate) const LOG_PAYLOAD_BYTES: usize = 0xd8; +/// The shared cache-flush ring has separate index and entry addresses on the wire. +pub(crate) fn write_flush_ring( + bytes: &mut [u8], offset: usize, state: u64, entries: u64, +) -> Result<(), Error> { + if state == 0 || entries == 0 || (state | entries) & 0x3f != 0 { + return Err(Error::Address); + } + let pair = bytes.get_mut(offset..).and_then(|s| s.get_mut(..16)).ok_or(Error::Size)?; + pair[..8].copy_from_slice(&state.to_le_bytes()); + pair[8..].copy_from_slice(&entries.to_le_bytes()); + Ok(()) +} + /// Extend the existing M3 owner indices instead of introducing another owner graph. pub(crate) fn allocation(index: usize) -> Result { let size = match index { 0..=23 if index % 2 == 0 => 0x30, - 0..=23 => 0x1800, + 0..=23 => super::m3_channel_format::SLOTS as usize * super::m3_channel_format::SUBMISSION_BYTES, 24 | 26 | 30 | 32 => 0x30, 25 => 0x4000, 27 | 33 => 0x4800, @@ -65,6 +78,30 @@ pub(crate) fn cached(index: usize) -> bool { matches!(index, 39 | PERFORMANCE_CONTROL) } +/// Thirteen TX descriptors and four RX state/ring pairs. Both the extended +/// M3 profile and the adjacent G14G profile use these directory offsets. +/// The caller owns all 34 buffers through firmware stop. +pub(crate) fn write_channels(bytes: &mut [u8], addresses: &[u64; 34]) -> Result<(), Error> { + if bytes.len() < 0x200 || addresses.contains(&0) { + return Err(Error::Bounds); + } + let pointer = |bytes: &mut [u8], offset, value: u64| { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + }; + for channel in 0..13 { + let offset = 0x20 + channel * 0x20; + let state = addresses[channel * 2]; + pointer(bytes, offset, state); + pointer(bytes, offset + 8, state + 0x10); + pointer(bytes, offset + 16, state + 0x20); + pointer(bytes, offset + 24, addresses[channel * 2 + 1]); + } + for (index, &address) in addresses[26..].iter().enumerate() { + pointer(bytes, 0x1c0 + index * 8, address); + } + Ok(()) +} + pub(crate) struct PointerGraph<'a> { pub(crate) owners: &'a [Region; COUNT], pub(crate) scratch: Region, @@ -155,14 +192,6 @@ impl PointerGraph<'_> { for (offset, owner) in [ (0, storage::HARDWARE_DATA), (0x10, storage::UNKNOWN_PAIR), - (0x1c0, 26), - (0x1c8, 27), - (0x1d0, 28), - (0x1d8, 29), - (0x1e0, 30), - (0x1e8, 31), - (0x1f0, 32), - (0x1f8, 33), (0x200, storage::FWLOG_PAYLOAD), (0x254, storage::UNKNOWN_C0), (0x25c, storage::UNKNOWN_C1), @@ -174,14 +203,7 @@ impl PointerGraph<'_> { ] { pointer(bytes, offset, addresses[owner]); } - for channel in 0..13 { - let offset = 0x20 + channel * 0x20; - let state = addresses[channel * 2]; - pointer(bytes, offset, state); - pointer(bytes, offset + 8, state + 0x10); - pointer(bytes, offset + 16, state + 0x20); - pointer(bytes, offset + 24, addresses[channel * 2 + 1]); - } + write_channels(bytes, addresses[..34].try_into().map_err(|_| Error::Bounds)?)?; Ok(()) } @@ -191,8 +213,8 @@ impl PointerGraph<'_> { .get_mut(..allocation(storage::CONTROL_REGION)?.size) .ok_or(Error::Size)?; bytes.fill(0); - bytes[0x4f88..0x4f90].copy_from_slice(&addresses[storage::FW_CONTROL_STATE].to_le_bytes()); - bytes[0x4f90..0x4f98].copy_from_slice(&addresses[storage::FW_CONTROL_RING].to_le_bytes()); + write_flush_ring(bytes, 0x4f88, addresses[storage::FW_CONTROL_STATE], + addresses[storage::FW_CONTROL_RING])?; bytes[0x4fd4..0x4fd8].copy_from_slice(&1u32.to_le_bytes()); Ok(()) } @@ -202,6 +224,17 @@ impl PointerGraph<'_> { mod tests { use super::*; + #[test] + fn empty_flush_ring_publishes_both_views() { + let mut control = [0u8; 0x4bf8]; + let base = 0xffff_ffa8_0010_0000; + write_flush_ring(&mut control, 0x4be0, base, base + 0x40).unwrap(); + assert_eq!(&control[0x4be0..0x4be8], &base.to_le_bytes()); + assert_eq!(&control[0x4be8..0x4bf0], &(base + 0x40).to_le_bytes()); + assert_eq!(&control[0x4bf0..], &[0; 8]); + assert!(write_flush_ring(&mut control[..0x4be8], 0x4be0, base, base + 0x40).is_err()); + } + fn owners(delta: u64) -> [Region; COUNT] { core::array::from_fn(|index| { let item = allocation(index).unwrap(); diff --git a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs index a17bc0ee399c34..31e463f6cd1ec0 100644 --- a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs @@ -142,6 +142,12 @@ pub(crate) fn encode( } _ => return Err(Error::Address), }; + write_record(output, physical, va, bytes, requested, register, mode) +} + +/// Common 0x28-byte record used by the single-role G14G and G15G interfaces. +pub(crate) fn write_record(output: &mut [u8], physical: u64, va: u64, bytes: u32, + requested: u32, register: u64, mode: u64) -> Result<(), Error> { let bytes_out = output.get_mut(..RECORD_BYTES).ok_or(Error::Size)?; bytes_out.fill(0); bytes_out[0..8].copy_from_slice(&physical.to_le_bytes()); diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 8bd242a483432b..8596347bdc13dd 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -1300,7 +1300,7 @@ impl Runtime { self.retire_extended_control(first)?; self.inner.boot_step = BootStep::DeviceControl; // Each data master registers its two firmware engine classes. - for ordinal in 0..6 { + for ordinal in 0..super::m3_channel_format::ENGINE_CLASSES { let action = Action::Register { pipe: ordinal / 2, engine: ordinal % 2 + 1 }; self.send_extended_control(action)?; } diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index a3b98ca76fc1a6..484a471f1190cc 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -3867,6 +3867,13 @@ impl Uat { uat_inner.owned_user_roots[idx] = ttb; binding.generation = binding_wire_generation(incarnation); uat_inner.publish_slot(idx); + if self.inner.clean_poc && !uat_inner.quirks.clean_tables { + // A table walker that does not snoop the CPU caches must also see the new + // TTBAT words, not only the new tables. + let slot = core::ptr::from_ref(&uat_inner.ttbs()[idx]).cast::(); + pgtable::clean_poc(slot, size_of::()); + pgtable::poc_barrier(); + } drop(transaction); // Make sure all TLB entries from the previous owner of this ASID are gone diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 485241a5644636..08a06e25ac76fc 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -42,7 +42,7 @@ def body(source,marker): struct Quirks{handoff_lock:bool,clean_tables:bool} struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],quirks:Quirks} impl UatShared{fn handoff(&self)->&Handoff{&self.handoff}fn ttbs(&self)->&[SlotTTBS;64]{&self.ttbs}} -struct UatInner{firmware:UatFirmware,m4_adopted:bool,failed:AtomicBool,shared:Mutex} +struct UatInner{firmware:UatFirmware,m4_adopted:bool,clean_poc:bool,failed:AtomicBool,shared:Mutex} ''' mid=mid.replace('impl UatShared{','impl UatShared{'+''.join(body(mm,m) for m in ['fn handoff_lock(', 'fn handoff_unlock(', 'fn publish_slot('])) raii='#[path="'+str(ROOT/'drivers/gpu/drm/asahi/mmu/ppl.rs')+'"]mod ppl;\n'+'\n'.join(body(mm,m) for m in [ @@ -51,7 +51,7 @@ def body(source,marker): ]) inner='impl UatInner{\n'+'\n'.join(body(mm,m) for m in ['fn lock(&self) -> Guard', 'fn check_m4(', 'fn lock_handoff(', 'fn lock_m4_upper('])+'\n}\n' models=r''' -fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} +fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc:false,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}} From 119cce51da9feab841232df225e7efb80eae0c6e Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 06:36:05 -0500 Subject: [PATCH 0261/1514] drm/asahi: test the bound TTBAT slot clean; name submission_entry's users The asahi-m4 retention harness modelled every UAT with clean_poc false, so the TTBAT write-back that bind_inner does for an adopted UAT without the clean_tables quirk compiled but never ran. Add a bind case for each walker configuration that counts writebacks of the bound slot: once by bind for clean_poc alone, once by publish_slot with the quirk, none for a coherent walker. With the new branch disabled the case fails. submission_entry's comment named only G15G 26.6.2 and G14G 26B123. The M3 runtime writes it for both of its profiles (14.8.3 and 26.6.2) through m3_config::submit_queue, which has no per-profile layout; say so. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/m3/m3_channel_format.rs | 7 +++++-- .../drivers/gpu/asahi-m4/test-mmu-retention.py | 15 ++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs index d3cc240e898cbe..4d2217697cf62c 100644 --- a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs +++ b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs @@ -11,8 +11,11 @@ pub(crate) const SUBMISSION_BYTES: usize = 0x18; /// Two firmware engine classes for each of the three data masters. pub(crate) const ENGINE_CLASSES: u32 = 6; -/// Wire entry shared by G15G 26.6.2 and G14G 26B123. The caller owns the queue -/// and publishes its contents before advancing the channel's shared write index. +/// Submission-channel wire entry. The M3 runtime writes it for both of its +/// profiles (14.8.3 Legacy and 26.6.2 Extended) through `m3_config::submit_queue`, +/// which has no per-profile layout; the G14G firmware-27.2 path (26B123) writes the +/// same entry. The caller owns the queue and publishes its contents before +/// advancing the channel's shared write index. pub(crate) fn submission_entry( selector: u32, queue: u64, position: u16, stamp: u8, first: bool, ) -> Result<[u8; SUBMISSION_BYTES], Error> { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 08a06e25ac76fc..a40521662daaa0 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -24,12 +24,12 @@ def body(source,marker): static TRIP_LOAD:AtomicUsize=AtomicUsize::new(0); struct AtomicBool(StdAtomicBool);impl AtomicBool{fn new(v:bool)->Self{Self(StdAtomicBool::new(v))}fn store(&self,v:bool,o:Ordering){self.0.store(v,o);}fn load(&self,o:Ordering)->bool{let n=TRIP_LOAD.load(Ordering::Relaxed);if n!=0&&TRIP_LOAD.fetch_sub(1,Ordering::Relaxed)==1{self.0.store(true,Ordering::Release);}self.0.load(o)}} const UAT_NUM_CTX:usize=64;const UAT_USER_CTX_START:usize=1;const TTBR_VALID:u64=1;const TTBR_ASID_SHIFT:usize=48;const UAT_PGSZ:usize=0x4000; -static NODE_DROPS:AtomicUsize=AtomicUsize::new(0);static MUTATIONS:AtomicUsize=AtomicUsize::new(0);static ROOT_FREES:AtomicUsize=AtomicUsize::new(0);static TREE_FREES:AtomicUsize=AtomicUsize::new(0);static FWCTL:AtomicUsize=AtomicUsize::new(0);static LEAF_CLEARS:AtomicUsize=AtomicUsize::new(0);static BARRIERS:AtomicUsize=AtomicUsize::new(0); +static NODE_DROPS:AtomicUsize=AtomicUsize::new(0);static MUTATIONS:AtomicUsize=AtomicUsize::new(0);static ROOT_FREES:AtomicUsize=AtomicUsize::new(0);static TREE_FREES:AtomicUsize=AtomicUsize::new(0);static FWCTL:AtomicUsize=AtomicUsize::new(0);static LEAF_CLEARS:AtomicUsize=AtomicUsize::new(0);static BARRIERS:AtomicUsize=AtomicUsize::new(0);static CLEANS:StdMutex>=StdMutex::new(Vec::new()); macro_rules! pr_err{($($t:tt)*)=>{()};}macro_rules! mod_pr_debug{($($t:tt)*)=>{()};}macro_rules! mod_dev_dbg{($($t:tt)*)=>{()};}macro_rules! dev_err{($($t:tt)*)=>{()};} struct MutexBackend;struct Mutex(StdMutex);implMutex{fn new(v:T)->Self{Self(StdMutex::new(v))}fn lock(&self)->Guard<'_,T,MutexBackend>{Guard(self.0.lock().unwrap(),std::marker::PhantomData)}} struct Guard<'a,T,M>(std::sync::MutexGuard<'a,T>,std::marker::PhantomData);implDeref for Guard<'_,T,M>{type Target=T;fn deref(&self)->&T{&self.0}}implDerefMut for Guard<'_,T,M>{fn deref_mut(&mut self)->&mut T{&mut self.0}} struct Monotonic;struct Delta;impl Delta{fn from_millis(n:u64)->u64{n}}struct Instant{n:std::cell::Cell,p:std::marker::PhantomData}implInstant{fn now()->Self{Self{n:std::cell::Cell::new(0),p:std::marker::PhantomData}}fn elapsed(&self)->u64{let n=self.n.get();self.n.set(n+1);n}} -mod pgtable{pub fn clean_poc(_p:*const u8,_n:usize){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn poc_barrier(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}} +mod pgtable{pub fn clean_poc(p:*const u8,n:usize){super::CLEANS.lock().unwrap().push((p as usize,n));super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn poc_barrier(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}} mod mem{pub fn sync(){super::BARRIERS.fetch_add(1,super::Ordering::Relaxed);}pub fn tlbi_asid(_:u8){}} #[derive(Clone,Copy,PartialEq,Eq)]enum UatFirmware{Handoff,PublishedRoots} struct Handoff{lock_ap:AtomicU8,lock_fw:AtomicU8,turn:AtomicU32,cur_slot:AtomicU32}impl Handoff{fn new()->Self{Self{lock_ap:AtomicU8::new(0),lock_fw:AtomicU8::new(0),turn:AtomicU32::new(0),cur_slot:AtomicU32::new(0xffff)}} @@ -51,7 +51,8 @@ def body(source,marker): ]) inner='impl UatInner{\n'+'\n'.join(body(mm,m) for m in ['fn lock(&self) -> Guard', 'fn check_m4(', 'fn lock_handoff(', 'fn lock_m4_upper('])+'\n}\n' models=r''' -fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc:false,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} +fn uat(m4:bool,firmware:UatFirmware)->Rc{uat_with(m4,firmware,false,false)} +fn uat_with(m4:bool,firmware:UatFirmware,clean_poc:bool,clean_tables:bool)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}} @@ -87,7 +88,7 @@ def body(source,marker): impl VmInner{fn ttb(&self)->u64{self.page_table.ttb}} '''+body(mm,'impl Drop for VmInner {') main=r''' -fn reset(){TRIP_LOAD.store(0,Ordering::Relaxed);for c in [&NODE_DROPS,&MUTATIONS,&ROOT_FREES,&TREE_FREES,&FWCTL,&LEAF_CLEARS,&BARRIERS]{c.store(0,Ordering::Relaxed);}} +fn reset(){TRIP_LOAD.store(0,Ordering::Relaxed);CLEANS.lock().unwrap().clear();for c in [&NODE_DROPS,&MUTATIONS,&ROOT_FREES,&TREE_FREES,&FWCTL,&LEAF_CLEARS,&BARRIERS]{c.store(0,Ordering::Relaxed);}} fn mapping(u:Rc,cached:bool,fail_unmap:bool)->(KernelMapping,Rc){let bo=Rc::new(PinBo);let n=Node{va:0xfffffc2000000000,inner:KernelMappingInner{owner:Rc::new(Owner(RefCell::new(OwnerState{dev:(),is_kernel:true,page_table:MapTable{fail:fail_unmap}}))),uat_inner:u,prot:Prot{cached},mapped_size:0x4000,_bo:bo.clone(),private:None}};(KernelMapping(ManuallyDrop::new(n)),bo)} fn mapping_tests(){ for (m4,firmware,cached,node_free,fwctl) in [(false,UatFirmware::Handoff,false,1,0),(false,UatFirmware::Handoff,true,1,1),(false,UatFirmware::PublishedRoots,true,1,0),(true,UatFirmware::Handoff,false,1,0),(true,UatFirmware::Handoff,true,0,0)]{reset();let u=uat(m4,firmware);let (m,bo)=mapping(u.clone(),cached,false);drop(m);assert_eq!(NODE_DROPS.load(Ordering::Relaxed),node_free);assert_eq!(FWCTL.load(Ordering::Relaxed),fwctl);assert_eq!(Rc::strong_count(&bo),if node_free==0{2}else{1});assert_eq!(u.failed.load(Ordering::Acquire),m4&&cached);assert_eq!(u.shared.lock().handoff.lock_ap.load(Ordering::Relaxed),0);} @@ -107,6 +108,10 @@ def body(source,marker): // A previously faulted M4 is refused before any new lock or TTBAT generation mutation. let u=uat(true,UatFirmware::Handoff);u.failed.store(true,Ordering::Release);let backend=Uat{inner:u.clone(),slots:Allocator};assert!(backend.bind(&Vm{id:9,binding:new_binding()}).is_err());assert_eq!(u.shared.lock().binding_generations[4],0); } +// A non-snooping walker sees the TTBAT slot bind fills written back exactly once: by bind for an +// adopted UAT without the clean_tables quirk (clean_poc only), by publish_slot with the quirk. +// A coherent walker (neither) gets no clean. +fn ttbat_clean_tests(){for (clean_poc,clean_tables,cleaned) in [(false,false,false),(true,false,true),(true,true,true)]{reset();let u=uat_with(false,UatFirmware::Handoff,clean_poc,clean_tables);let backend=Uat{inner:u.clone(),slots:Allocator};let bound=backend.bind(&Vm{id:9,binding:new_binding()}).unwrap();assert_eq!(bound.1,4);let s=u.shared.lock();let slot=(core::ptr::from_ref(&s.ttbs[4]) as usize,size_of::());let cleans=CLEANS.lock().unwrap();assert_eq!(cleans.iter().filter(|c|**c==slot).count(),usize::from(cleaned));assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0x804000001|(4<<48));}} fn generation_churn_test(){ let u=uat(true,UatFirmware::Handoff);let backend=Uat{inner:u.clone(),slots:Allocator}; let published=backend.bind(&Vm{id:1,binding:new_binding()}).unwrap();assert_eq!(published.0.binding.lock().generation,1); @@ -116,7 +121,7 @@ def body(source,marker): let next=backend.bind(&Vm{id:999,binding:new_binding()}).unwrap();assert_eq!(next.0.binding.lock().generation,3); } fn vm_drop_tests(){for (m4,blocked,pre_failed) in [(false,false,false),(true,false,false),(true,true,false),(true,false,true)]{reset();let u=uat(m4,UatFirmware::Handoff);let binding=new_binding();binding.lock().bind_token=Some(Token(3));let low=0x804000001|(4<<48);{let mut s=u.shared.lock();s.ttbs[4].ttb0.store(low,Ordering::Release);s.owned_user_roots[4]=low;s.handoff.lock_fw.store(u8::from(blocked),Ordering::Release);}u.failed.store(pre_failed,Ordering::Release);drop(VmInner{id:9,binding,uat_inner:u.clone(),page_table:UatPageTable::new()});let uncertain=blocked||pre_failed;assert_eq!(ROOT_FREES.load(Ordering::Relaxed),usize::from(!uncertain));assert_eq!(TREE_FREES.load(Ordering::Relaxed),usize::from(!uncertain));let s=u.shared.lock();assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),if uncertain{low}else{0});assert_eq!(s.owned_user_roots[4],if uncertain{low}else{0});assert_eq!(s.handoff.lock_ap.load(Ordering::Relaxed),0);assert_eq!(u.failed.load(Ordering::Acquire),uncertain);}} -fn main(){generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition (mock hardware)");} +fn main(){ttbat_clean_tests();generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition; a non-snooping adopted UAT writes back the bound TTBAT slot once (mock hardware)");} ''' source=pre+handoff+mid+raii+inner+models+map_drop+pages+bindings+helpers+bind+vm+main (OUT/'check-mmu-retention.rs').write_text(source) From 9955fbfc318005f4aedced59fc0e0e85c2f911a8 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 05:29:14 -0500 Subject: [PATCH 0262/1514] soc: apple: aop: check the firmware segments wherever the loader lists them The macOS 27.2 AOP firmware on T8112 runs its external code and data from DRAM, as the T6040 firmware does, so it needs the same checks of the segments the boot loader reserves: every page mapped where the device tree says, the external code at its fixed address, and the translated __EDATA passed as ED0p. The 13.5 firmware on the same SoC needs none of this. Select the checks by the device tree instead of by SoC: also run them when the AOP node has a memory-region. Only a loader that handed the segments over lists them, and no SoC whose configuration leaves the checks off gets one today, so nothing changes elsewhere. Signed-off-by: Satya Benson --- drivers/soc/apple/aop.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 38cddac3a30e99..5f83063af9f044 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -3028,7 +3028,9 @@ struct AopHwConfig { required_endpoints: &'static [u8], /// The firmware runs segments from DRAM, which the bootloader reserves /// and lists in `memory-region`; check their IOMMU mappings before - /// starting it (T6040). + /// starting it (T6040). Other SoCs check them when the bootloader lists + /// them (`AopData::has_fw_regions`), as it does for the macOS 27.2 + /// firmware on T8112. fw_regions: bool, bootargs_word_access: bool, /// Halt the co-processor again when its start fails (T6040). @@ -3343,7 +3345,7 @@ impl platform::Driver for AopDriver { let asc_mmio = asc_req.iomap_sized::()?; let asc_mmio = asc_mmio.as_view().relaxed(); let aop_mmio = aop_mmio.as_view(); - let ed0p = if cfg.fw_regions { + let ed0p = if cfg.fw_regions || AopData::has_fw_regions(pdev.as_ref()) { // Before anything is written to the AOP: no mapping, no start. let allow_ed0p = cfg.patch_bootargs && AopData::bootargs_has_ed0p(&aop_mmio, cfg.bootargs_word_access)?; From f188ef1a2f7dd88b9edbd7e56630f47a93769f21 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 06:29:12 -0500 Subject: [PATCH 0263/1514] PCI: apple: keep a boot-trained adopted link in D0 through suspend The host's s2idle check refuses an adopted link unless every function on it is accessible in D0. On J775c the PCI core's system-suspend path puts the boot-trained root port 00:01.0 in D3hot first (PMCSR 0x000b at the host's noirq check, with runtime PM forbidden on every PCI device), so s2idle is refused on every attempt. Mark a root port the boot loader trained on an adopted link, and every function below it, PCI_DEV_FLAGS_NO_D3 when it is enabled. The selection is the port's adopted-link state: an adopted port that Linux trains itself (pwren-gpios) is not marked. Those functions also lose runtime D3. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index dcff27ac6b2689..13e48efc9f6140 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -3690,6 +3690,24 @@ static int apple_pcie_adopted_no_clkpm_walk(struct pci_dev *pdev, void *data) return 0; } +/* + * Whether @pdev is a root port the boot loader trained on an adopted link, or a + * function below one: a port adopted without its endpoint power line, which + * Linux trains itself (pwren-gpios), is not. + */ +static bool apple_pcie_on_boot_trained_link(struct apple_pcie *pcie, struct pci_dev *pdev) +{ + struct pci_dev *rp = pcie_find_root_port(pdev); + struct apple_pcie_port *port; + + if (!pcie->hw->adopt_link || !rp) + return false; + list_for_each_entry(port, &pcie->ports, entry) + if (port->idx == PCI_SLOT(rp->devfn)) + return !port->pwren; + return false; +} + static int apple_pcie_enable_device(struct pci_host_bridge *bridge, struct pci_dev *pdev) { struct apple_pcie *pcie = pci_host_bridge_priv(bridge); @@ -3710,6 +3728,14 @@ static int apple_pcie_enable_device(struct pci_host_bridge *bridge, struct pci_d if (pcie->hw->tunneled) pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; + /* + * Firmware owns the power of a boot-trained adopted link, and s2idle + * requires the port and everything below it to stay accessible in D0. + * Keep the PCI core's suspend paths from putting them in D3hot. + */ + if (apple_pcie_on_boot_trained_link(pcie, pdev)) + pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; + /* * Endpoint BARs share PCIe-C's tunneled, non-posted MMIO fabric. Mark * them before the function driver maps its BAR so pci_iomap() selects From 513067f6cbc3987054e3eb1c729ccc3a26019ba5 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 06:30:01 -0500 Subject: [PATCH 0264/1514] PCI: apple: share adopted-link training detection Use one root-port walk and training test when setting NO_D3 and checking D0 for s2idle. Still check D0 when the root port is unknown. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 33 +++++++++-------------------- 1 file changed, 10 insertions(+), 23 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 13e48efc9f6140..967d6d3bedef69 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -3691,11 +3691,12 @@ static int apple_pcie_adopted_no_clkpm_walk(struct pci_dev *pdev, void *data) } /* - * Whether @pdev is a root port the boot loader trained on an adopted link, or a - * function below one: a port adopted without its endpoint power line, which - * Linux trains itself (pwren-gpios), is not. + * An adopted port with an endpoint power GPIO (pwren-gpios) is trained by + * Linux. Match the root port itself as well as functions below it. + * If no port matches, neither kind of training can be established. */ -static bool apple_pcie_on_boot_trained_link(struct apple_pcie *pcie, struct pci_dev *pdev) +static bool apple_pcie_adopted_link_trained_by(struct apple_pcie *pcie, + struct pci_dev *pdev, bool bootloader) { struct pci_dev *rp = pcie_find_root_port(pdev); struct apple_pcie_port *port; @@ -3704,7 +3705,7 @@ static bool apple_pcie_on_boot_trained_link(struct apple_pcie *pcie, struct pci_ return false; list_for_each_entry(port, &pcie->ports, entry) if (port->idx == PCI_SLOT(rp->devfn)) - return !port->pwren; + return bootloader == !port->pwren; return false; } @@ -3733,7 +3734,7 @@ static int apple_pcie_enable_device(struct pci_host_bridge *bridge, struct pci_d * requires the port and everything below it to stay accessible in D0. * Keep the PCI core's suspend paths from putting them in D3hot. */ - if (apple_pcie_on_boot_trained_link(pcie, pdev)) + if (apple_pcie_adopted_link_trained_by(pcie, pdev, true)) pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3; /* @@ -6803,22 +6804,6 @@ static void apple_pcie_stop_for_sleep(struct device *dev) static void apple_pcie_neo_save_functions(struct apple_pcie *pcie); -/* Whether Linux trained the port above pdev itself (cold train), rather than adopting it */ -static bool apple_pcie_below_kernel_trained_port(struct pci_dev *pdev) -{ - struct pci_config_window *cfg = pdev->sysdata; - struct apple_pcie *pcie = apple_pcie_lookup(cfg->parent); - struct pci_dev *rp = pcie_find_root_port(pdev); - struct apple_pcie_port *port; - - if (!rp) - return false; - list_for_each_entry(port, &pcie->ports, entry) - if (port->idx == PCI_SLOT(rp->devfn)) - return !!port->pwren; - return false; -} - /* * The J716c radio drivers save PCI state without entering D3. The PCI core * keeps the root port in D0 as well. Its host and DART have no switchable @@ -6830,6 +6815,8 @@ static bool apple_pcie_below_kernel_trained_port(struct pci_dev *pdev) */ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) { + struct pci_config_window *cfg = pdev->sysdata; + struct apple_pcie *pcie = apple_pcie_lookup(cfg->parent); int *error = data; u16 value; @@ -6840,7 +6827,7 @@ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) * asked to stay awake need to remain in D0. */ if (!device_awake_path(&pdev->dev) && - apple_pcie_below_kernel_trained_port(pdev)) + apple_pcie_adopted_link_trained_by(pcie, pdev, false)) return 0; if (pci_read_config_word(pdev, PCI_VENDOR_ID, &value) || From 96c882e979f6ed78131750067c2c5ad616b5fce6 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:18:03 -0500 Subject: [PATCH 0265/1514] drm/asahi: G14 compute on GPU firmware 27.2 GPU firmware 27.2 on G14 (the M2's G14G) takes a new root: four opaque records (status, control, power, an extra block) after the UAT level descriptors, and a runtime directory of 26.x-style channels in place of the 13.5 RuntimePointers. Add that root as G14 V27_2 and a compute-only runtime on it. - fw/initdata.rs: the raw InitData and HwDataB layouts gain V27_2 (a new AGX_V27_2 version group instantiates only these two), with layout checks against 13.5. - gpu/v27_2.rs: builds the root on the records of a 13.5 G14 manager (GpuManager::build_graph with GraphProfile::G14V27_2, which maps no registers and keeps the private range below the 27.2 timestamp aperture): hardware data from the 13.5 values, the chip's 27.2 register table (hw/t8112.rs), the power and thermal controller, the idle-policy records, and one queue with a kernel-owned boot compute job. - g14_v27_2.rs: start sequence and runtime. The driver's kernel window is mirrored into the loader's shared second-level table and named in TTBAT context 0 (mmu::FirmwareWindow); the ASC is started, the GPU held powered and the boot job retired; clients then submit through the 26.x front end (m3_submit), each compute command re-encoded in the 27.2 layout from a 48-slot pool and published in order. Completion follows the queue's retired position. The firmware's event, statistics, log and trace rings are consumed as they fill. Render commands get EINVAL. - driver.rs: a G14G whose DT apple,firmware-version is 27.2.0 takes this path, before anything starts the coprocessor. There are no module parameters. Inputs come from the DT (operating points, power and thermal properties, apple,coredump-copy-buffer, the SRAM voltages the loader publishes, the UAT regions), the GPU's ID registers and the T8112 chip configuration. Unbind stops the firmware (allow-off, RTKit power-off if it does not stop, ASC halt) and keeps its memory for the rest of the boot. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/Makefile | 2 +- drivers/gpu/drm/asahi/asahi_core.rs | 2 + drivers/gpu/drm/asahi/driver.rs | 72 ++ drivers/gpu/drm/asahi/event.rs | 11 + drivers/gpu/drm/asahi/fw/initdata.rs | 56 +- drivers/gpu/drm/asahi/g14_v27_2.rs | 656 ++++++++++++ drivers/gpu/drm/asahi/g15/uat.rs | 2 +- drivers/gpu/drm/asahi/g17/fw/initdata.rs | 1 + drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 19 +- drivers/gpu/drm/asahi/gpu.rs | 80 +- drivers/gpu/drm/asahi/gpu/v27_2.rs | 1009 +++++++++++++++++++ drivers/gpu/drm/asahi/hw/mod.rs | 24 + drivers/gpu/drm/asahi/hw/t8112.rs | 44 + drivers/gpu/drm/asahi/m3/m3_submit.rs | 73 +- drivers/gpu/drm/asahi/m3/mod.rs | 14 +- drivers/gpu/drm/asahi/mmu.rs | 139 +++ drivers/gpu/drm/asahi/object.rs | 17 + drivers/gpu/drm/asahi/regs.rs | 7 + drivers/gpu/drm/asahi/rtkit_dump.c | 19 + rust/macros/versions.rs | 12 +- 21 files changed, 2207 insertions(+), 54 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g14_v27_2.rs create mode 100644 drivers/gpu/drm/asahi/gpu/v27_2.rs create mode 100644 drivers/gpu/drm/asahi/rtkit_dump.c diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 24341a6f3abce9..a356bb326d2458 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -8,4 +8,4 @@ aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o +aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o rtkit_dump.o diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b9706916510321..5f180203f8369c 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,6 +27,8 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +mod g14_v27_2; mod hw; mod initdata; mod m3; diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2b..1526566cf68a56 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -53,6 +53,9 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, + /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. raw_dev: *mut bindings::device, @@ -337,6 +340,10 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = this.g14_v27_2.as_ref() { + backend.stop(); + } this.close_binding(); } @@ -368,6 +375,18 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => return Err(ENODEV), }; + // G14 with firmware 27.2 has its own root and start sequence (g14_v27_2.rs). + if (cfg.gpu_gen, cfg.gpu_variant) == (hw::GpuGen::G14, hw::GpuVariant::G) { + let version: Option> = pdev.as_ref().fwnode().ok_or(EIO)? + .property_read_array_vec(c"apple,firmware-version", 3)?.optional(); + if version.as_deref() == Some(&[27, 2, 0]) { + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg); + #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] + return Err(ENODEV); + } + } + // SAFETY: The selected SoC's UAT output width bounds all device DMA. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; @@ -449,6 +468,8 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -461,6 +482,41 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { + /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + fn probe_g14_v27_2<'bound>( + pdev: &'bound platform::Device>, + cfg: &'static hw::HwConfig, + ) -> Result> { + let crate::g14_v27_2::Started { backend, drm, binding, resources } = + crate::g14_v27_2::start(pdev, cfg)?; + let gpu = backend.clone() as Arc; + let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); + // SAFETY: The registration is stored in the platform data and unregistered when it is + // dropped, after the backend has stopped the firmware. + let reg = match unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0) } { + Ok(reg) => reg, + Err(error) => { + backend.stop(); + return Err(error); + } + }; + dev_info!(pdev.as_ref(), "G14 firmware 27.2 running; compute-only DRM device registered\n"); + Ok(AsahiPlatformDriverData { + binding, + _device: reg.device().into(), + _reg: reg, + g17: None, + #[cfg(CONFIG_DRM_ASAHI_G16)] + g16: None, + m3: None, + g14_v27_2: Some(backend), + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn probe_g15<'bound>( pdev: &'bound platform::Device>, @@ -487,6 +543,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -529,6 +587,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), stats: None, @@ -605,6 +665,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -652,6 +714,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -691,6 +755,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, g16: Some(gpu), raw_dev, raw_stats, @@ -747,6 +813,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -780,5 +848,9 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = self.g14_v27_2.as_ref() { + backend.stop(); + } } } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index edd7d701e665cd..a993bca69f5072 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,6 +54,11 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn raw(self) -> u32 { + self.0 + } + /// Returns the `EventValue` that succeeds this one. pub(crate) fn next(&self) -> EventValue { EventValue(self.0.wrapping_add(0x100)) @@ -199,6 +204,12 @@ impl EventManager { Ok(ev) } + /// Reserve the normal stamp pair for a kernel queue that polls its own completion. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn try_get_polled(&self) -> Result { + self.alloc.try_get(None) + } + /// Signals an event by slot, indicating completion (of one or more commands). pub(crate) fn signal(&self, slot: u32) { match self diff --git a/drivers/gpu/drm/asahi/fw/initdata.rs b/drivers/gpu/drm/asahi/fw/initdata.rs index 7c7488e950acef..7c7e3cfe45eb08 100644 --- a/drivers/gpu/drm/asahi/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/fw/initdata.rs @@ -637,7 +637,7 @@ pub(crate) mod raw { pub(crate) afr_unkpad: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct HwDataB { @@ -663,10 +663,15 @@ pub(crate) mod raw { pub(crate) yuv_matrices: Array<0x3f, Array<3, Array<4, i16>>>, pub(crate) pad_1c8: Pad<0x8>, + #[ver(V < V27_2)] pub(crate) io_mappings: Array, + #[ver(V >= V27_2)] + pub(crate) io_mappings: Array<60, crate::g17::fw::initdata::RegisterMapEntry>, #[ver(V >= V13_0B4)] pub(crate) sgx_sram_ptr: U64, + #[ver(V >= V27_2)] + pub(crate) coredump_copy_buffer_size: U64, pub(crate) chip_id: u32, pub(crate) unk_454: u32, @@ -835,7 +840,7 @@ pub(crate) mod raw { #[ver(V >= V13_0B4)] pub(crate) unk_c3c: u32, } - #[versions(AGX)] + #[versions(AGX_V27_2)] default_zeroed!(HwDataB::ver); #[derive(Debug)] @@ -1243,7 +1248,7 @@ pub(crate) mod raw { pub(crate) index_mask: U64, } - #[versions(AGX)] + #[versions(AGX_V27_2)] #[derive(Debug)] #[repr(C)] pub(crate) struct InitData<'a> { @@ -1253,20 +1258,65 @@ pub(crate) mod raw { pub(crate) unk_buf: GpuPointer<'a, &'a [u8]>, pub(crate) unk_8: u32, pub(crate) unk_c: u32, + #[ver(V < V27_2)] pub(crate) runtime_pointers: GpuPointer<'a, super::RuntimePointers::ver>, + #[ver(V < V27_2)] pub(crate) globals: GpuPointer<'a, super::Globals::ver>, + #[ver(V < V27_2)] pub(crate) fw_status: GpuPointer<'a, super::FwStatus>, + // From 27.2 the root names opaque records; their layouts live with the 27.2 builder. + #[ver(V >= V27_2)] + pub(crate) runtime_pointers: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) globals: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) role: u32, + #[ver(V >= V27_2)] + pub(crate) host_mapped_fw_allocations: u32, pub(crate) uat_page_size: u16, pub(crate) uat_page_bits: u8, pub(crate) uat_num_levels: u8, pub(crate) uat_level_info: Array<0x3, UatLevelInfo>, pub(crate) __pad0: Pad<0x14>, + #[ver(V < V27_2)] pub(crate) host_mapped_fw_allocations: u32, + #[ver(V < V27_2)] pub(crate) unk_ac: u32, + #[ver(V < V27_2)] pub(crate) unk_b0: u32, + #[ver(V < V27_2)] pub(crate) unk_b4: u32, + #[ver(V < V27_2)] pub(crate) unk_b8: u32, + #[ver(V >= V27_2)] + pub(crate) status_record: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) control: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) power: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) extra: GpuPointer<'a, &'a [u8]>, } + + // Layout checks for the firmware 27.2 root and hardware data against the 13.5 layout. + const _: () = { + // T8112's older layout locates its optional SRAM pointer after 25 IO records. + assert!(core::mem::offset_of!(HwDataBG14V13_5, io_mappings) == 0x640); + assert!(core::mem::size_of::() == 0x20); + assert!(core::mem::offset_of!(HwDataBG14V13_5, sgx_sram_ptr) == 0x960); + assert!(core::mem::offset_of!(HwDataBG14V27_2, io_mappings) == 0x640); + assert!(core::mem::offset_of!(HwDataBG14V27_2, sgx_sram_ptr) == 0xfa0); + assert!(core::mem::offset_of!(HwDataBG14V27_2, coredump_copy_buffer_size) == 0xfa8); + assert!(core::mem::offset_of!(HwDataBG14V27_2, chip_id) == 0xfb0); + type Root = InitDataG14V27_2<'static>; + assert!(core::mem::offset_of!(Root, ver_info) == 0); + assert!(core::mem::offset_of!(Root, role) == 0x28); + assert!(core::mem::offset_of!(Root, host_mapped_fw_allocations) == 0x2c); + assert!(core::mem::offset_of!(Root, uat_level_info) == 0x34); + assert!(core::mem::offset_of!(Root, status_record) == 0xa8); + assert!(core::mem::offset_of!(Root, extra) == 0xc0); + assert!(core::mem::size_of::() == 0xc8); + }; } #[derive(Debug)] diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs new file mode 100644 index 00000000000000..ea585628b1e4f0 --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -0,0 +1,656 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 GPUs on GPU firmware 27.2: start the firmware and run compute work on it. +//! +//! [`start`] builds the 27.2 root (`gpu/v27_2.rs`) on the records of a 13.5 G14 manager, +//! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the +//! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients +//! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the +//! 27.2 layout and published, in order, on the root's queue. Render commands are refused. +//! +//! Completion follows the queue's retired position, which the firmware advances in order. +//! The firmware's event, statistics, log and trace rings are consumed as they fill, since +//! the firmware waits for space in them. + +use core::ops::Range; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +use kernel::{ + device, + drm::sched, + new_delayed_work, new_mutex, + platform, + prelude::*, + soc::apple::rtkit, + sync::{aref::ARef, Arc, Mutex}, + time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, + uapi, + workqueue::{self, impl_has_delayed_work, DelayedWork, WorkItem}, +}; + +use crate::{ + alloc, event, gem, + gpu::{self, CommandPool, ComputeJob, GpuManagerG14V13_5, QueueInfo, RootV27_2, POOL_SLOTS}, + hw, mmu, queue, + m3::m3_submit::{Command, Packet}, +}; + +/// RTKit endpoints of the GPU firmware. +const EP_FIRMWARE: u8 = 0x20; +const EP_DOORBELL: u8 = 0x21; + +/// ASC CPU control register and its run bit. +const ASC_CPU_CONTROL: usize = 0x44; +const ASC_RUN: u32 = 0x10; + +/// Commands slower than this are a hang; the firmware state is then not trusted. +const COMMAND_TIMEOUT_MS: i64 = 5000; +/// Idle polling keeps the firmware's rings drained and bounds completion latency. +const IDLE_POLL_MS: u64 = 20; + +/// The ASC control page, kept mapped until the firmware is stopped. +pub(crate) struct AscControl(*mut u8); +// SAFETY: a device register page; accesses are single 32-bit MMIO operations. +unsafe impl Send for AscControl {} +// SAFETY: as above. +unsafe impl Sync for AscControl {} + +impl AscControl { + fn new(phys: u64) -> Result { + // SAFETY: `phys` is the ASC register window of this platform device. + let ptr = unsafe { kernel::bindings::ioremap(phys, 0x4000) }; + if ptr.is_null() { return Err(ENOMEM); } + Ok(Self(ptr.cast())) + } + fn read(&self, at: usize) -> u32 { + // SAFETY: `at` is a register offset inside the mapped page. + unsafe { kernel::bindings::readl(self.0.add(at).cast()) } + } + fn write(&self, at: usize, value: u32) { + // SAFETY: as above. + unsafe { kernel::bindings::writel(value, self.0.add(at).cast()) } + } + /// Clears the ASC run bit. + fn halt(&self) { + self.write(ASC_CPU_CONTROL, self.read(ASC_CPU_CONTROL) & !ASC_RUN); + } +} + +impl Drop for AscControl { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { kernel::bindings::iounmap(self.0.cast()) } + } +} + +/// RTKit operations of the GPU firmware: its crash log lives in the loader's data segment. +pub(crate) struct Firmware; + +#[vtable] +impl rtkit::Operations for Firmware { + type Data = Arc>; + type Buffer = crate::g17::CrashLog; + + const COPROC_PLACES_BUFFERS: bool = true; + + fn shmem_map(dev: kernel::sync::ArcBorrow<'_, ARef>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(&dev, iova, size) + } + + fn crashed(dev: kernel::sync::ArcBorrow<'_, ARef>, log: Option<&[u8]>) { + unsafe extern "C" { + fn asahi_save_rtkit_dump(dev: *mut core::ffi::c_void, data: *const u8, size: usize); + } + dev_err!(&**dev, "GPU firmware crashed\n"); + if let Some(log) = log { + // SAFETY: RTKit and the device remain live throughout this synchronous copy. + unsafe { asahi_save_rtkit_dump(dev.as_raw().cast(), log.as_ptr(), log.len()) }; + } + } + + fn recv_message(_dev: kernel::sync::ArcBorrow<'_, ARef>, _ep: u8, _message: u64) {} +} + +type Peer = Pin>>; + +/// Polls `done` every millisecond, draining the firmware's rings, for at most `ms`. +fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Result { + let start = Instant::::now(); + loop { + if done()? { return Ok(()); } + if start.elapsed() >= Delta::from_millis(ms) { return Err(ETIMEDOUT); } + let _ = root.drain(); + fsleep(Delta::from_millis(1)); + } +} + +/// Publishes an idle-policy record and waits until the firmware has consumed and +/// acknowledged it. +fn set_idle_policy(root: &RootV27_2, peer: &mut Peer, allow_off: bool) -> Result { + let (target, generation) = root.publish_idle_policy(allow_off)?; + peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; + wait(root, 500, || Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation)) +} + +/// Stops firmware that no runtime owns: allow power-off, then RTKit power-off, then the ASC +/// run bit. Everything it could reach is kept for the rest of the boot. +fn halt_unowned(dev: &device::Device, mut peer: Peer, root: crate::fw::types::GpuObject, + asc: AscControl, booted: bool) { + if booted { + let allowed = set_idle_policy(&root, &mut peer, true); + // SAFETY: the RTKit instance is live and owned here. + let off = kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(peer.as_raw()) }); + dev_err!(dev, "GPU firmware halted: allow-off={:?} power-off={:?}\n", allowed, off); + } + asc.halt(); + core::mem::forget(peer); + core::mem::forget(root); + core::mem::forget(asc); +} + +/// A started 27.2 GPU, ready for DRM registration. +pub(crate) struct Started<'a> { + pub(crate) backend: Arc, + pub(crate) drm: kernel::drm::UnregisteredDevice, + pub(crate) binding: crate::binding::Owner, + pub(crate) resources: crate::regs::Resources<'a>, +} + +/// Starts the firmware and retires the boot job. +pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'static hw::HwConfig) + -> Result> { + use kernel::dma::{Device as _, DmaMask}; + let dev: &device::Device = pdev.as_ref(); + let (registers, writable) = match cfg.chip_id { + 0x8112 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), + _ => return Err(ENODEV), + }; + let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; + let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; + let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; + let control = asc.read(ASC_CPU_CONTROL); + if control & ASC_RUN != 0 { return Err(EBUSY); } + let mut peer = KBox::pin( + rtkit::RtKit::::new(dev, None, 0, Arc::new(ARef::from(dev), GFP_KERNEL)?)?, + GFP_KERNEL)?; + let resources = crate::regs::Resources::new(pdev)?; + let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let copy_bytes: u32 = dev.fwnode().ok_or(ENODEV)? + .property_read(c"apple,coredump-copy-buffer").required_by(dev)?; + let board = gpu::BoardV27_2 { + sgx: sgx.start(), sgx_size: sgx.size() as u64, copy_bytes, registers, writable, + }; + + // SAFETY: the mask is the UAT's physical width. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(geometry.oas)?)? }; + let drm = kernel::drm::UnregisteredDevice::::new(pdev, Ok(()))?; + // SAFETY: the unregistered DRM instance is private to this bound probe. + let binding = unsafe { crate::binding::Owner::new(pdev.as_ref(), &drm)? }; + let uat = mmu::Uat::new_adopted(&drm, geometry, &window.regions())?; + let graph = GpuManagerG14V13_5::build_graph(&drm, &resources, cfg, KBox::new(uat, GFP_KERNEL)?, + gpu::GraphProfile::G14V27_2)?; + let root = RootV27_2::build(&graph, &board)?; + let pool = CommandPool::new(&mut gpu::GpuManager::alloc(&*graph), cfg)?; + window.mirror(graph.kernel_uat())?; + window.install()?; + window.announce(); + asc.write(ASC_CPU_CONTROL, control | ASC_RUN); + + // From here the firmware may read everything the window names: nothing is freed. + let mut booted = false; + let result = (|| -> Result { + let start = Instant::::now(); + while !window.answered() { + if start.elapsed() >= Delta::from_millis(1000) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + peer.as_mut().boot()?; + booted = true; + peer.as_mut().start_endpoint(EP_FIRMWARE)?; + peer.as_mut().start_endpoint(EP_DOORBELL)?; + if !window.intact() { return Err(EIO); } + peer.as_mut().send_message(EP_FIRMWARE, gpu::init_message(root.gpu_va().get()))?; + // Let initialization settle before the first control record. + let _ = wait(&root, 1000, || Ok(false)); + set_idle_policy(&root, &mut peer, false)?; + // Command-handler installation completes during powered initialization. + let _ = wait(&root, 500, || Ok(root.command_service()? == (2, 0))); + root.publish_boot_job(resources.operating_point())?; + peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + wait(&root, 3000, || root.boot_job_complete()) + })(); + if let Err(e) = result { + dev_err!(dev, "GPU firmware 27.2 did not start: {:?}\n", e); + halt_unowned(dev, peer, root, asc, booted); + core::mem::forget(window); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + // The firmware keeps using the window until it is stopped; it stays for the life of the boot. + core::mem::forget(window); + let backend = Backend::start(&drm, dev, peer, root, graph, pool, asc, cfg)?; + Ok(Started { backend, drm, binding, resources }) +} + +struct Inflight { + packet: Arc, + last: bool, + stamp: event::EventValue, + slot: usize, + /// Queue publications up to and including this command, counted from take-over. + ordinal: u64, + started: Instant, + _bind: mmu::VmBind, +} + +struct State { + peer: Peer, + root: crate::fw::types::GpuObject, + pool: CommandPool, + asc: AscControl, + queue: QueueInfo, + last: event::EventValue, + sequence: u64, + next_slot: usize, + waiting_unlink: bool, + /// Publications and retirements counted on the queue's position block. + published: u64, + retired_total: u64, + retired_raw: u32, + capacity: u32, + inflight: KVec, + pending: KVec<(Arc, usize)>, + submitted: u64, + retired: u64, +} + +#[pin_data(PinnedDrop)] +pub(crate) struct Runtime { + dev: ARef, + graph: Arc, + healthy: AtomicBool, + /// Poll work queued or running; `stop` waits for zero so no work outlives the module. + queued: AtomicU32, + #[pin] + state: Mutex>, + #[pin] + poll: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Runtime { self.poll } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + let busy = this.service(); + if this.healthy.load(Ordering::Acquire) { + this.schedule(if busy { 1 } else { IDLE_POLL_MS }); + } + this.queued.fetch_sub(1, Ordering::AcqRel); + } +} + +#[pinned_drop] +impl PinnedDrop for Runtime { + fn drop(self: Pin<&mut Self>) { + // The poll work holds a reference while scheduled, so this runs only once the + // runtime is idle; stop the firmware first if no one has. + if self.state.lock().is_some() { self.stop(); } + } +} + +impl Runtime { + fn schedule(self: &Arc, ms: u64) { + if !self.healthy() { return; } + self.queued.fetch_add(1, Ordering::AcqRel); + if workqueue::system_highpri() + .enqueue_delayed::, 0>(self.clone(), msecs_to_jiffies(ms as u32)).is_err() { + // Already queued: that run accounts for itself. + self.queued.fetch_sub(1, Ordering::AcqRel); + } + } + + pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } + + /// Queues a packet; the poll work publishes and retires it. + pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { + if !self.healthy() { return Err(EIO); } + if packet.commands.is_empty() { + return Err(ENOTSUPP); + } + { + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); + } + self.schedule(1); + Ok(()) + } + + /// Withdraws a packet's unpublished commands; published ones retire normally. + pub(crate) fn withdraw(&self, packet: &Arc) { + let mut guard = self.state.lock(); + if let Some(state) = Option::as_mut(&mut *guard) { + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + if !state.inflight.iter().any(|f| Arc::ptr_eq(&f.packet, packet)) { + packet.release_guard(); + } + } + } + + fn fail_all(&self, state: &mut State, error: Error) { + self.healthy.store(false, Ordering::Release); + for (packet, _) in state.pending.drain(..) { + packet.release_guard(); + packet.finish(Err(error)); + } + // Published work stays owned: the firmware may still read it. + for f in state.inflight.iter() { + if let Some(status) = f.packet.vm.status() { status.record(error); } + f.packet.finish(Err(error)); + } + } + + /// Publishes pending commands while pool slots are free. + fn pump(&self, state: &mut State) { + while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { + // A slot is reused only once the firmware has unlinked it from its tracking list. + match state.pool.registered(state.next_slot) { + Ok(false) => {} + Ok(true) => { + if !state.waiting_unlink { + // Wake the firmware's service once so its retirement scan runs. + state.waiting_unlink = true; + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); + } + return; + } + Err(e) => { self.fail_all(state, e); return; } + } + state.waiting_unlink = false; + let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); + let Command::Compute(control) = packet.commands[index] else { + // Queues of this backend accept only compute commands (Queue::submit). + let _ = state.pending.remove(0); + if !(packet.may_be_published() && index != 0) { packet.release_guard(); } + packet.finish(Err(EINVAL)); + continue; + }; + let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { + let bind = self.graph.kernel_uat().bind(&packet.vm)?; + let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); + let stamp = state.last.next(); + let job = ComputeJob { + context: bind.slot(), + sequence: state.sequence, + cdm_base: control.base, + cdm_end: control.end, + usc_base: control.usc_base, + preempt, + }; + let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; + packet.mark_published(); + state.root.publish(command)?; + state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + Ok((bind, stamp)) + })(); + match result { + Ok((bind, stamp)) => { + state.last = stamp; + state.sequence += 1; + let slot = state.next_slot; + state.published += 1; + let ordinal = state.published; + state.next_slot = (state.next_slot + 1) % POOL_SLOTS; + state.submitted += 1; + let last = index + 1 == packet.commands.len(); + if state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + started: Instant::now(), _bind: bind }, GFP_KERNEL).is_err() { + self.fail_all(state, ENOMEM); + return; + } + if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } + } + Err(e) => { + dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); + let _ = state.pending.remove(0); + // Earlier commands of a published packet fail it when they retire. + if !(packet.may_be_published() && index != 0) { + packet.release_guard(); + } + packet.finish(Err(e)); + } + } + } + } + + /// Retires completed commands, publishes more and keeps the firmware's rings drained. + /// Returns whether work remains. + fn service(&self) -> bool { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return false; }; + let _ = state.root.drain(); + if state.peer.is_crashed() { + dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", + state.pending.len(), state.inflight.len()); + self.fail_all(state, EIO); + return false; + } + let raw = match state.root.progress() { + Ok((_, raw)) => raw, + Err(e) => { self.fail_all(state, e); return false; } + }; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + while !state.inflight.is_empty() { + let front = &state.inflight[0]; + if state.retired_total >= front.ordinal { + if let Ok(done) = state.inflight.remove(0) { + if let Err(e) = state.pool.retire(done.slot) { + dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + } + state.retired += 1; + if done.last { + done.packet.retired(); + } + } + continue; + } + if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", + state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); + self.fail_all(state, ETIMEDOUT); + return false; + } + break; + } + if self.healthy() { self.pump(state); } + !state.inflight.is_empty() || !state.pending.is_empty() + } + + /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC + /// with every mapping still in place (RTKit power-off if the firmware does not stop). + pub(crate) fn stop(&self) { + let start = Instant::::now(); + while start.elapsed() < Delta::from_millis(2000) { + if !self.service() { break; } + fsleep(Delta::from_millis(1)); + } + self.healthy.store(false, Ordering::Release); + // No poll work may remain queued or running once this returns. + let start = Instant::::now(); + while self.queued.load(Ordering::Acquire) != 0 && start.elapsed() < Delta::from_millis(2000) { + fsleep(Delta::from_millis(5)); + } + // Let a run that just accounted for itself return out of this module. + fsleep(Delta::from_millis(20)); + let mut guard = self.state.lock(); + let Some(mut state) = guard.take() else { return; }; + self.fail_all(&mut state, ENODEV); + let allowed = set_idle_policy(&state.root, &mut state.peer, true); + let root = &state.root; + let _ = wait(root, 500, || Ok(root.firmware_running()? == 0)); + let running = root.firmware_running(); + let forced = (running != Ok(0)).then(|| { + // SAFETY: the RTKit instance is live and owned here. + kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) + }); + state.asc.halt(); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={}\n", + allowed, running, forced, state.submitted, state.retired); + if running != Ok(0) && forced != Some(Ok(())) { + dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); + } + // Keep everything the firmware could reach for the rest of the boot, halted or not: + // its page tables still name these pages. + core::mem::forget(state); + core::mem::forget(self.graph.clone()); + } +} + +impl State { + fn queue_stamp(&self) -> u32 { + self.root.queue().1.raw() + } +} + +pub(crate) struct Backend { + graph: Arc, + runtime: Arc, + scheduler: Arc>, + ids: gpu::SequenceIDs, + preempt_bytes: usize, +} + +impl Backend { + /// Takes over the running firmware after the boot job. + #[allow(clippy::too_many_arguments)] + fn start( + drm: &crate::driver::AsahiDrmDevice, + dev: &device::Device, + peer: Peer, + root: crate::fw::types::GpuObject, + graph: Arc, + pool: CommandPool, + asc: AscControl, + cfg: &'static hw::HwConfig, + ) -> Result> { + // The runtime is created empty first, so no allocation failure can drop firmware-visible + // state. Every failure after the state is moved in goes through Runtime::stop, which + // halts the firmware and keeps all of its memory. + let runtime_graph = graph.clone(); + let runtime = match Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + queued: AtomicU32::new(0), + state <- new_mutex!(None, "g14_v27_2::Runtime::state"), + poll <- new_delayed_work!("g14_v27_2::Runtime::poll"), + }), GFP_KERNEL) { + Ok(runtime) => runtime, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + let (queue, last) = root.queue(); + let checked = (|| -> Result<(u32, u32)> { + let (head, retired) = root.progress()?; + if head != retired { return Err(EBUSY); } + Ok((head, root.capacity()?)) + })(); + let (head, capacity) = match checked { + Ok(v) => v, + Err(e) => { + halt_unowned(dev, peer, root, asc, true); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + *runtime.state.lock() = Some(State { + peer, root, pool, asc, queue, last, + sequence: u64::from(head), + next_slot: 0, + waiting_unlink: false, + published: 0, + retired_total: 0, + retired_raw: head, + capacity, + inflight: KVec::new(), + pending: KVec::new(), + submitted: 0, + retired: 0, + }); + runtime.schedule(IDLE_POLL_MS); + // One run queue per DRM scheduler priority (the front end maps queue priorities 0-3). + let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, POOL_SLOTS as u32 - 1, 0, 10000, + c"asahi_g14_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { + Ok(scheduler) => scheduler, + Err(e) => { + runtime.stop(); + return Err(e); + } + }; + let preempt_bytes = cfg.compute_preempt1_size + 0x20; + match Arc::new(Self { graph, runtime: runtime.clone(), scheduler, ids: gpu::SequenceIDs::default(), preempt_bytes }, + GFP_KERNEL) { + Ok(backend) => Ok(backend), + Err(e) => { runtime.stop(); Err(e.into()) } + } + } + + pub(crate) fn stop(&self) { self.runtime.stop(); } +} + +impl Drop for Backend { + fn drop(&mut self) { self.runtime.stop(); } +} + +impl gpu::Gpu for Backend { + fn stats_snapshot(&self) -> Option> { None } + fn as_any(&self) -> &dyn core::any::Any { self } + fn arc_as_any(self: Arc) -> Arc { self as Arc } + fn manager(&self) -> Option<&dyn gpu::GpuManager> { None } + fn init(&self) -> Result { if self.runtime.healthy() { Ok(()) } else { Err(ENODEV) } } + fn ids(&self) -> &gpu::SequenceIDs { &self.ids } + fn is_crashed(&self) -> bool { !self.runtime.healthy() } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + ::get_params(&self.graph, params)?; + params.max_commands_per_submission = crate::m3::agx_uapi::UAPI_MAX_HARDWARE_COMMANDS; + params.max_attachments = crate::m3::agx_uapi::UAPI_MAX_ATTACHMENTS as u32; + Ok(()) + } + fn supports_vm_status(&self) -> bool { true } + fn feature_flags(&self) -> u64 { + uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 + | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 + } + fn tracked_submission(&self) -> bool { true } + fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } + fn uat_geometry(&self) -> mmu::UatGeometry { ::uat_geometry(&self.graph) } + fn new_vm(&self, range: Range) -> Result { + self.graph.kernel_uat().new_vm(self.ids.vm.next(), range)?.with_tracked_status() + } + fn new_queue(&self, vm: mmu::Vm, _ualloc: Arc>, + ualloc_priv: Arc>, priority: u32, + usc_exec_base: u64, _usage: Arc) -> Result> { + Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), + vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes)?, GFP_KERNEL)?) + } + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { + // Timestamp buffers would need new tables in the firmware window after boot. + Err(ENOTSUPP) + } +} diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs index 0f91f7c9f06100..8168f32abe01b5 100644 --- a/drivers/gpu/drm/asahi/g15/uat.rs +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -118,7 +118,7 @@ fn clean_entries(pa: u64, first: usize, count: usize) -> Result { } /// Cleans a whole RAM table page to the point of coherency. -fn clean_page(pa: u64) -> Result { +pub(crate) fn clean_page(pa: u64) -> Result { clean_entries(pa, 0, ENTRIES) } diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index a70b5763eac4d2..9c827c6d8c1885 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -652,6 +652,7 @@ impl RegisterWindow { const RESERVED_SLOT_UNK_20: u32 = 2; /// One register-map slot of the hardware data. +#[derive(Debug)] #[repr(C)] pub(crate) struct RegisterMapEntry { /// Physical address of the window. diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index ded8c30ac41fda..848f2171278aed 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -1857,7 +1857,7 @@ const COMMON26_POLICY_BOOT_TIMESTAMP: usize = 0x6c14; /// initPowerAndPerformanceData stores (the G18 backend's G18G_26A428_POLICY_BANDS). 26A428 /// inserts 0x680 bytes between the AON PTD pointer and the boot timestamp; the 25G76 words /// there have no place. -const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ +pub(crate) const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ band(0x0000, 0x009c, 0, Evidence::ProducerChecked), band(0x00a0, 0x0200, 0x10, Evidence::ProducerChecked), band(0x09b8, 0x295c, 0x10, Evidence::ProducerChecked), diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d923272a9a18d5..546cab58bc3c5b 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -375,6 +375,16 @@ enum CrashLogMap { FirmwareData(data_segment::DataSegmentLog), } +impl CrashLog { + /// Map only the range firmware requested within its loader-reserved data. + pub(crate) fn from_firmware(dev: &device::Device, iova: usize, size: usize) -> Result { + Ok(Self { + iova, + map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map(dev, iova, size)?), + }) + } +} + impl rtkit::Buffer for CrashLog { fn iova(&self) -> Result { Ok(self.iova) @@ -483,14 +493,7 @@ impl rtkit::Operations for RoleOps { }); } // The firmware places its buffers in its data segment, at their physical address. - Ok(CrashLog { - iova, - map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map( - &data.shared.dev, - iova, - size, - )?), - }) + CrashLog::from_firmware(&data.shared.dev, iova, size) } } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index d462ecbd1a7ae7..2166a7e3dce1ec 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -106,6 +106,17 @@ const EP_DOORBELL: u8 = 0x21; const MSG_INIT: u64 = 0x81 << 48; const INIT_DATA_MASK: u64 = (1 << 44) - 1; +/// The firmware-endpoint message that hands the firmware its root at `address`. +pub(crate) const fn init_message(address: u64) -> u64 { + MSG_INIT | (address & INIT_DATA_MASK) +} + +/// The G14 firmware-27.2 root and the records only it uses. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +mod v27_2; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use v27_2::*; + const RX_WORK_PENDING: u32 = 1 << 0; const RX_WORK_RUNNING: u32 = 1 << 1; @@ -127,6 +138,10 @@ const DOORBELL_DEVCTRL: u64 = 0x11; // Upper kernel half VA address ranges. /// Private (cached) firmware structure VA range base. const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; +/// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator +/// stays below it in that profile. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; /// Shared (uncached) firmware structure VA range base. @@ -178,6 +193,17 @@ pub(crate) struct KernelAllocators { pub(crate) gpu_ro: alloc::DefaultAllocator, } +/// What [`GpuManager::build_graph`] builds the records for. +#[derive(Copy, Clone)] +pub(crate) enum GraphProfile { + /// The manager's own firmware: map the registers, use the whole private range. + Native, + /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register + /// mappings, and the private range ends below that firmware's timestamp aperture. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + G14V27_2, +} + /// Receive (GPU->driver) ring buffer channels. #[versions(AGX)] #[pin_data] @@ -659,13 +685,42 @@ impl GpuManager::ver { cfg: &'static hw::HwConfig, ) -> Result> { let uat = Self::make_uat(dev, cfg)?; + let mgr = Self::build_graph(dev, res, cfg, uat, GraphProfile::Native)?; + let rtkit = + rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; + + *mgr.rtkit.lock() = Some(rtkit); + + { + let mut rxc = mgr.rx_channels.lock(); + rxc.event.set_manager(mgr.clone()); + rxc.stats.set_manager(mgr.clone()); + } + + Ok(mgr) + } + + /// Build the manager and its firmware records without attaching RTKit. + #[inline(never)] + pub(crate) fn build_graph( + dev: &AsahiDrmDevice, + res: ®s::Resources<'_>, + cfg: &'static hw::HwConfig, + uat: KBox, + profile: GraphProfile, + ) -> Result> { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; + let private_end = match profile { + GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, + }; let mut alloc = KernelAllocators { private: alloc::DefaultAllocator::new( dev, uat.kernel_vm(), - IOVA_KERN_PRIV_RANGE, + IOVA_KERN_PRIV_RANGE.start..private_end, 0x80, mmu::PROT_FW_PRIV_RW, 1024 * 1024, @@ -808,14 +863,16 @@ impl GpuManager::ver { } }); + // The 27.2 root publishes its own register table (gpu/v27_2.rs). + let map_registers = matches!(profile, GraphProfile::Native); for (i, map) in cfg.io_mappings.iter().enumerate() { - if let Some(map) = map.as_ref() { + if let Some(map) = map.as_ref().filter(|_| map_registers) { Self::iomap(&mut mgr, cfg, i, map)?; } } #[ver(V >= V13_0B4)] - if let Some(base) = cfg.sram_base { + if let Some(base) = cfg.sram_base.filter(|_| map_registers) { let size = cfg.sram_size.unwrap(); let iova = mgr.as_mut().alloc_mmio_iova(size); @@ -838,20 +895,7 @@ impl GpuManager::ver { mgr.as_mut().io_mappings_mut().push(mapping, GFP_KERNEL)?; } - let mgr = Arc::from(mgr); - - let rtkit = - rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; - - *mgr.rtkit.lock() = Some(rtkit); - - { - let mut rxc = mgr.rx_channels.lock(); - rxc.event.set_manager(mgr.clone()); - rxc.stats.set_manager(mgr.clone()); - } - - Ok(mgr) + Ok(Arc::from(mgr)) } /// Return a mutable reference to the initdata member @@ -1596,7 +1640,7 @@ impl Gpu for GpuManager::ver { rtk.as_mut().start_endpoint(EP_FIRMWARE)?; rtk.as_mut().start_endpoint(EP_DOORBELL)?; rtk.as_mut() - .send_message(EP_FIRMWARE, MSG_INIT | (initdata & INIT_DATA_MASK))?; + .send_message(EP_FIRMWARE, init_message(initdata))?; rtk.as_mut() .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; core::mem::drop(guard); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs new file mode 100644 index 00000000000000..0ee4c1ec07ed4f --- /dev/null +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -0,0 +1,1009 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The G14 root for GPU firmware 27.2, the boot compute job that starts the firmware's command +//! service, and the command pool the 27.2 compute runtime (`crate::g14_v27_2`) publishes from. +//! +//! The root is built on the records of a 13.5 G14 manager, made with +//! [`GraphProfile::G14V27_2`]: its hardware data supplies the calibrated values, and its +//! kernel UAT, allocators and buffer-manager control pages are shared. The firmware never sees +//! that manager's own root. + +use super::*; +use crate::g17::fw::m5::initdata as abi; +use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; +use crate::m3::m3_init_26 as directory26; + +/// The firmware build word this root carries in its version field. +const FIRMWARE_WORD: u64 = 0x0c8a_8342_8392_04c8; + +/// Kick message for the compute submission ring the root uses (group 2, compute). +pub(crate) const COMPUTE_KICK: u64 = MSG_TX_DOORBELL | (4 * PRIORITY_GROUP + COMPUTE) as u64; +/// Kick message for the device-control ring. +pub(crate) const DEVICE_CONTROL_KICK: u64 = MSG_FWCTL | DOORBELL_DEVCTRL; + +/// Data master of the root's queue, and its priority group: the legacy G14 priority row 2. +const COMPUTE: usize = 2; +const PRIORITY_GROUP: usize = 2; +const PRIORITY_ROW: usize = 2; +/// The submission descriptor the queue publishes on (three per group). +const SUBMISSION_RING: usize = 3 * PRIORITY_GROUP + COMPUTE; +/// Firmware event, log, trace and statistics rings in the 34-entry channel list. +const EVENT_RING: usize = 13; +const LOG_RINGS: usize = 14; +const TRACE_RING: usize = 15; +const STATISTICS_RING: usize = 16; +/// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. +const TRACE_RECORDS: u32 = 512; +const RING_RECORDS: u32 = 256; +/// Queue capacity at position block +0x50 (16 x the 0x50 channels). +const QUEUE_CAPACITY: u32 = 0x500; +/// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. +/// Only this cap has run on hardware. +const STATE_CAP: u32 = 100; + +/// Board facts the root needs, read from the device tree at probe. +pub(crate) struct BoardV27_2 { + /// The SGX register window (`reg` "sgx"). + pub(crate) sgx: u64, + pub(crate) sgx_size: u64, + /// Bytes of the firmware's crash copy buffer (`apple,coredump-copy-buffer`). + pub(crate) copy_bytes: u32, + /// The chip's 27.2 register table. + pub(crate) registers: &'static [RegisterV27_2], + /// Slots whose stock mode is read-write (bit per slot). + pub(crate) writable: u64, +} + +/// Firmware-visible facts of the root's queue that every compute command names. +#[derive(Copy, Clone)] +pub(crate) struct QueueInfo { + pub(crate) queue: u64, + pub(crate) slot: u32, + pub(crate) stamp: u64, + pub(crate) fw_stamp: u64, + pub(crate) compute_state: u64, +} + +/// One compute command, as the 26.x submission front end hands it over. +pub(crate) struct ComputeJob { + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) cdm_base: u64, + pub(crate) cdm_end: u64, + pub(crate) usc_base: u64, + /// VA of the preemption buffer in the same context (13.5 layout: buffer 1 at +0, + /// buffers 2 to 5 at +compute_preempt1_size + 8n). + pub(crate) preempt: u64, +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} + +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Encodes a type-3 compute command (0x358 bytes, the 13.5 G14 job parameters inside the +/// 27.2 wrapper) and its start/finish stream. Both buffers must be zeroed. +#[allow(clippy::too_many_arguments)] +fn encode_compute( + cmd: &mut [u8], cmd_va: u64, stream: &mut [u8], stream_va: u64, tracking: u64, + timestamps: u64, preempt1: u64, q: &QueueInfo, stamp_value: u32, job: &ComputeJob, +) { + put32(cmd, 0, 3); + put64(cmd, 4, job.sequence); + put32(cmd, 0xc, job.context); + put64(cmd, 0x10, tracking); + // 13.5 JobParameters1 at +0x68. + let p2 = job.preempt + preempt1; + for (at, v) in [(0x00, job.preempt), (0x08, job.cdm_base), (0x10, p2), (0x18, p2 + 8), + (0x20, p2 + 16), (0x28, p2 + 24), (0x30, job.usc_base), (0x38, 0x8c60), (0x58, 1)] { + put64(cmd, 0x68 + at, v); + } + put64(cmd, 0x1e8, stream_va); + put32(cmd, 0x1f0, 0x2c0); + // 13.5 JobParameters2: preemption buffer and CDM end; EncoderParams mask. + put64(cmd, 0x220, job.preempt); + put64(cmd, 0x228, job.cdm_end); + put32(cmd, 0x270, u32::MAX); + put64(cmd, 0x298, q.stamp); + put64(cmd, 0x2a0, q.fw_stamp); + put32(cmd, 0x2a8, stamp_value); + put32(cmd, 0x2b0, q.slot); + put64(cmd, 0x2cc, timestamps); + put64(cmd, 0x2d4, timestamps + 8); + // Command-local dependency latch, enabled with seed 0; the firmware clears 0x10 bytes + // through the pointer at +0x334. + put32(cmd, 0x33c, 1); + put64(cmd, 0x334, timestamps + 0x20); + + put32(stream, 0, 11); + put64(stream, 0x160, job.sequence); + put64(stream, 0x04, cmd_va + 0x18); + put64(stream, 0x0c, cmd_va + 0x68); + put64(stream, 0x14, q.compute_state); + put64(stream, 0x1c, q.queue); + put32(stream, 0x24, job.context); + put32(stream, 0x34, q.slot); + put64(stream, 0x3c, cmd_va + 0x1f4); + put64(stream, 0x158, cmd_va + 0x340); + for (at, op, selected) in [(0x16c, 0x8000_0003u32, 0x2ccu64), (0x1bc, 3, 0x2d4)] { + put32(stream, at, op); + put64(stream, at + 0x04, cmd_va + 0x2c4); + put64(stream, at + 0x0c, cmd_va + 0x2cc); + put64(stream, at + 0x14, cmd_va + selected); + put64(stream, at + 0x1c, q.queue); + put64(stream, at + 0x2c, cmd_va + 0x314); + put64(stream, at + 0x34, cmd_va + 0x264); + } + put32(stream, 0x1b8, 0x0080_0000); + let finish = 0x208; + put32(stream, finish, 12); + put64(stream, finish + 4, q.compute_state); + put64(stream, finish + 0x0c, q.queue); + put32(stream, finish + 0x14, job.context); + put64(stream, finish + 0x18, cmd_va + 0x1f4); + put64(stream, finish + 0x2c, q.fw_stamp); + put32(stream, finish + 0x34, stamp_value); + put32(stream, finish + 0x5c, (-(finish as i32)) as u32); + put64(stream, finish + 0x71, cmd_va + 0x340); + put64(stream, finish + 0x79, cmd_va + 0x304); + put32(stream, finish + 0x84, 0x4000_0002); +} + +/// The root's queue and the kernel-owned boot job published on it: one compute dispatch of an +/// empty control stream in context 0, which the firmware must retire before clients run. +struct BootJob { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + pointers: fw::types::GpuArray, + command: fw::types::GpuArray, + stream: fw::types::GpuArray, + tracking: fw::types::GpuArray, + timestamps: fw::types::GpuArray, + event: event::Event, + expected_stamp: u32, + _owners: KVec>, + /// The job's buffers in context 0: mapping before backing. + _client: (mmu::KernelMapping, gem::ObjectRef), + client_va: u64, + preempt1: u64, +} + +impl BootJob { + fn new(alloc: &mut KernelAllocators, event: event::Event, uat: &mmu::Uat, dev: &AsahiDevice, + cfg: &'static hw::HwConfig) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut queue_stamps = alloc.shared.array_empty::(0x18)?; + let command = alloc.private.array_empty::(0x400)?; + let stream = alloc.private.array_empty::(0x400)?; + // A command-buffer tracking slot (0x100 stride, 0xc8 bytes kept by the firmware) + // whose first word names its own cleared retirement cursor. + let mut tracking = alloc.private.array_empty::(0x100)?; + let cursor = alloc.shared.array_empty::(0x90)?; + put64(tracking.as_mut_slice(), 0, cursor.gpu_va().get()); + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), 0x100); + + let queue_stamps_va = queue_stamps.gpu_va().get(); + put64(queue_stamps.as_mut_slice(), 8, queue_stamps_va); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, queue_stamps_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + put64(q, offset, value); + } + // The kernel-owned queue has no owning process. + for offset in [0x2c, 0x4c, 0x50] { + put32(q, offset, u32::MAX); + } + let row = crate::fw::workqueue::raw::PRIORITY[PRIORITY_ROW]; + put32(q, 0x30, row.0); + put32(q, 0x34, row.1); + put64(q, 0x38, row.2.0); + put32(q, 0x40, row.3); + put32(q, 0x44, row.4); + // The current lane stays at the all-ones sentinel; the firmware assigns it. + put32(q, 0x48, u32::MAX); + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + put32(positions.as_mut_slice(), 0x50, QUEUE_CAPACITY); + + // The job's preemption buffer and control stream live in context 0 at a client VA. + let preempt1 = cfg.compute_preempt1_size; + let client_va = IOVA_KERN_GPU_BUFMGR_LOW + 0x10_0000; + let mut object = gem::new_kernel_object(dev, preempt1 + 0x4000)?; + let size = object.size(); + { + use kernel::io::Io; + let map = object.vmap()?; + for off in (0..size).step_by(8) { map.try_write64(0, off)?; } + // CDM control stream: one Stream Terminate block (block type 2 in bits 31:29). + map.try_write32(0x4000_0000, preempt1 + 0x2000)?; + } + let mapping = object.map_at(uat.kernel_lower_vm(), client_va, mmu::PROT_GPU_SHARED_RW, false)?; + let timestamps = alloc.shared.array_empty::(0x80)?; + + let mut owners = KVec::new(); + for owner in [&queue_stamps, &pointers, &scheduler] { + crate::pgtable::clean_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + for owner in [queue_stamps, scheduler, cursor] { + owners.push(owner, GFP_KERNEL)?; + } + let expected_stamp = event.current().next().raw(); + Ok(Self { queue, positions, pointers, command, stream, tracking, timestamps, event, + expected_stamp, _owners: owners, _client: (mapping, object), + client_va, preempt1: preempt1 as u64 }) + } + + fn info(&self, compute_state: u64) -> QueueInfo { + QueueInfo { + queue: self.queue.gpu_va().get(), + slot: self.event.slot(), + stamp: u64::from(self.event.stamp_pointer()), + fw_stamp: u64::from(self.event.fw_stamp_pointer()), + compute_state, + } + } + + /// Encodes the boot command and names it at queue position 0. + fn encode(&mut self, q: &QueueInfo) { + let cdm = self.client_va + self.preempt1 + 0x2000; + let job = ComputeJob { + context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, + usc_base: 0x11_0000_0000, preempt: self.client_va, + }; + let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); + encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, + self.tracking.gpu_va().get(), self.timestamps.gpu_va().get(), self.preempt1, + q, self.expected_stamp, &job); + crate::pgtable::clean_poc(self.stream.as_slice().as_ptr(), self.stream.as_slice().len()); + crate::pgtable::clean_poc(self.command.as_slice().as_ptr(), self.command.as_slice().len()); + put64(self.pointers.as_mut_slice(), 0, cmd_va); + crate::pgtable::clean_poc(self.pointers.as_slice().as_ptr(), 8); + crate::pgtable::poc_barrier(); + } +} + +/// Command slots for client compute work. They are allocated with the root, before the +/// firmware window's tables are mirrored, so every slot lies in a table the firmware already +/// translates. Slots are reused in order. +pub(crate) const POOL_SLOTS: usize = 48; + +pub(crate) struct CommandPool { + commands: fw::types::GpuArray, + streams: fw::types::GpuArray, + tracking: fw::types::GpuArray, + cursors: fw::types::GpuArray, + stamps: fw::types::GpuArray, + preempt1: u64, +} + +impl CommandPool { + pub(crate) fn new(alloc: &mut KernelAllocators, cfg: &'static hw::HwConfig) -> Result { + let commands = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; + let streams = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; + let mut tracking = alloc.private.array_empty::(POOL_SLOTS * 0x100)?; + // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. + let cursors = alloc.shared.array_empty::(POOL_SLOTS * 0x40)?; + let stamps = alloc.shared.array_empty::(POOL_SLOTS * 0x80)?; + let base = cursors.gpu_va().get(); + for (i, chunk) in tracking.as_mut_slice().chunks_mut(0x100).enumerate() { + put64(chunk, 0, base + 0x40 * i as u64); + } + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); + Ok(Self { commands, streams, tracking, cursors, stamps, preempt1: cfg.compute_preempt1_size as u64 }) + } + + /// Builds slot `i` for `job` and returns the command's firmware VA. + pub(crate) fn encode(&mut self, i: usize, q: &QueueInfo, stamp_value: u32, job: &ComputeJob) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + let cmd_va = self.commands.gpu_va().get() + (i * 0x400) as u64; + let stream_va = self.streams.gpu_va().get() + (i * 0x400) as u64; + let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; + let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; + // The firmware keeps 0xc8 bytes of the tracking slot; start each use cleared. + let tracking = &mut self.tracking.as_mut_slice()[i * 0x100..(i + 1) * 0x100]; + tracking[8..].fill(0); + crate::pgtable::clean_poc(tracking.as_ptr(), tracking.len()); + let stamps = &mut self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80]; + stamps.fill(0); + crate::pgtable::clean_poc(stamps.as_ptr(), 0x80); + let cmd = &mut self.commands.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + cmd.fill(0); + let stream = &mut self.streams.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + stream.fill(0); + encode_compute(cmd, cmd_va, stream, stream_va, tracking_va, timestamps_va, self.preempt1, + q, stamp_value, job); + crate::pgtable::clean_poc(stream.as_ptr(), stream.len()); + crate::pgtable::clean_poc(cmd.as_ptr(), cmd.len()); + crate::pgtable::poc_barrier(); + Ok(cmd_va) + } + + /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at + /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. + pub(crate) fn retire(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); + crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). + pub(crate) fn registered(&self, i: usize) -> Result { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + Ok(self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire) != 0) + } +} + +/// The firmware 27.2 root and every record it names. +pub(crate) struct RootV27_2 { + graph: Arc, + boot: BootJob, + compute_state: u64, + channels: KVec>, + _owners: KVec>, + _register_mappings: KVec, + _controller: fw::types::GpuArray, + _directory: fw::types::GpuArray, + boot_page: fw::types::GpuArray, + globals: fw::types::GpuArray, + status: fw::types::GpuArray, + control: fw::types::GpuArray, + power: fw::types::GpuArray, + extra: fw::types::GpuArray, +} + +impl fw::types::GpuStruct for RootV27_2 { + type Raw<'a> = fw::initdata::raw::InitDataG14V27_2<'a>; +} + +impl GpuManagerG14V13_5 { + /// The kernel UAT these records live in. + pub(crate) fn kernel_uat(&self) -> &mmu::Uat { + &self.uat + } +} + +impl RootV27_2 { + fn word(a: &fw::types::GpuArray, at: usize) -> Result { + Ok(a.shared_index(at)?.load(Ordering::Acquire)) + } + + /// The queue's identity for client commands, and the stamp value it last reached. + pub(crate) fn queue(&self) -> (QueueInfo, event::EventValue) { + (self.boot.info(self.compute_state), self.boot.event.current()) + } + + /// The queue's capacity (position block +0x50). + pub(crate) fn capacity(&self) -> Result { + Self::word(&self.boot.positions, 0x50) + } + + /// The queue head and the firmware's retired position, which it advances in order. + pub(crate) fn progress(&self) -> Result<(u32, u32)> { + let positions = self.boot.positions.as_slice(); + crate::pgtable::clean_invalidate_poc(positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok((Self::word(&self.boot.positions, 0x40)?, Self::word(&self.boot.positions, 0)?)) + } + + /// Publishes `command` as the queue's next command: pointer, queue head, then the compute + /// submission entry and its producer. + pub(crate) fn publish(&self, command: u64) -> Result { + let job = &self.boot; + let head = job.positions.shared_index(0x40)?; + let old = head.load(Ordering::Acquire); + let capacity = Self::word(&job.positions, 0x50)?; + if capacity == 0 || (old % capacity) as usize * 8 + 8 > job.pointers.as_slice().len() { + return Err(EINVAL); + } + let at = (old % capacity) as usize * 8; + job.pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); + job.pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); + crate::pgtable::clean_poc(job.pointers.as_slice()[at..].as_ptr(), 8); + crate::pgtable::poc_barrier(); + let new = (old + 1) % capacity; + head.store(new, Ordering::Release); + crate::pgtable::clean_poc(job.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + let state = &self.channels[2 * SUBMISSION_RING]; + let ring = &self.channels[2 * SUBMISSION_RING + 1]; + let w = Self::word(state, 0x20)?; + if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), + u16::try_from(new).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + let base = w as usize * entry.len(); + for (k, word) in entry.chunks(4).enumerate() { + ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); + crate::pgtable::poc_barrier(); + state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); + crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Publishes the boot job, whose command and ring entry the root already holds. The GPU + /// must be held powered (`operating_point`: the Fender state, nonzero index, no request + /// pending) and the command service installed. + pub(crate) fn publish_boot_job(&self, operating_point: u32) -> Result { + let job = &self.boot; + let index = operating_point & 0xf; + if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate + || self.idle_progress()? != [1; 3] + || self.idle_acknowledgement()? != Self::word(&self.globals, 0xe40)? + || self.command_service()?.1 != 0 { + return Err(EAGAIN); + } + let producer = self.channels[2 * SUBMISSION_RING].shared_index(0x20)?; + let head = job.positions.shared_index(0x40)?; + if Self::word(&self.status, 0x14)? != 1 || producer.load(Ordering::Acquire) != 0 + || head.load(Ordering::Acquire) != 0 { + return Err(EAGAIN); + } + crate::pgtable::poc_barrier(); + head.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Whether the boot job has retired: ring consumed, queue read and retired, stamp reached. + pub(crate) fn boot_job_complete(&self) -> Result { + self.drain()?; + let job = &self.boot; + Ok(Self::word(&self.channels[2 * SUBMISSION_RING], 0)? == 1 + && Self::word(&job.positions, 0x30)? == 1 + && Self::word(&job.positions, 0)? == 1 + && job.event.current().raw() == job.expected_stamp) + } + + /// Consumes everything the firmware published on its statistics, event, log and trace + /// rings. The firmware waits for space when one is full, and host consumer advancement is + /// the acknowledgement; completion is followed through the queue's position block, so the + /// records are not kept. + pub(crate) fn drain(&self) -> Result { + let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { + let write = Self::word(state, base + 0x20)?; + let read = state.shared_index(base)?; + if write < records && read.load(Ordering::Acquire) != write { + read.store(write, Ordering::Release); + crate::pgtable::poc_barrier(); + } + Ok(()) + }; + consume(&self.channels[2 * STATISTICS_RING], 0, RING_RECORDS)?; + consume(&self.channels[2 * EVENT_RING], 0, RING_RECORDS)?; + // One log ring per log thread, state blocks 0x30 apart. + for thread in 0..directory26::LOG_THREADS { + consume(&self.channels[2 * LOG_RINGS], thread * 0x30, RING_RECORDS)?; + } + consume(&self.channels[2 * TRACE_RING], 0, TRACE_RECORDS) + } + + /// Shared status +0x10: nonzero while the firmware reports itself running. + pub(crate) fn firmware_running(&self) -> Result { + Self::word(&self.status, 0x10) + } + + /// Command-service state: (powered stage, pending installation request). + /// Engine entries may be published only at (2, 0). + pub(crate) fn command_service(&self) -> Result<(u32, u32)> { + Ok((Self::word(&self.control, 0x4c00)?, Self::word(&self.control, 0x4c24)?)) + } + + pub(crate) fn idle_acknowledgement(&self) -> Result { + Self::word(&self.control, 0xe838) + } + + /// Device-control ring consumer, target and producer. + pub(crate) fn idle_progress(&self) -> Result<[u32; 3]> { + self.drain()?; + let ring = &self.channels[2 * crate::m3::DEVICE_CONTROL]; + Ok([Self::word(ring, 0)?, Self::word(ring, 0x10)?, Self::word(ring, 0x20)?]) + } + + /// Publishes one of the two pre-encoded idle-policy records on the device-control ring: + /// keep powered first, then allow off. Returns the ring cursor and the counted generation + /// the firmware acknowledges, which follows the larger of the host's last publication and + /// the firmware's consumed count. + pub(crate) fn publish_idle_policy(&self, allow_off: bool) -> Result<(u32, u32)> { + let cursor = u32::from(allow_off); + let host = self.globals.shared_index(0xe40)?; + let firmware = self.idle_acknowledgement()?; + let producer = self.channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; + if Self::word(&self.status, 0x14)? != 1 || + crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)? != cursor { + return Err(EAGAIN); + } + let action = crate::m3::Action::Idle { enabled: allow_off }; + let generation = action.generation(host.load(Ordering::Acquire), firmware).map_err(|_| EOVERFLOW)?; + host.store(generation, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(cursor + 1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok((cursor + 1, generation)) + } + + /// Builds the root, the boot job and every record they name. + pub(crate) fn build(graph: &Arc, board: &BoardV27_2) -> Result> { + let cfg = graph.cfg; + let pwr = &graph.dyncfg.pwr; + let states = &pwr.perf_states; + let id = &graph.dyncfg.id; + // Inputs the controller below is built from, all from the DT and the ID registers. + let [core_mask] = id.core_masks.as_slice() else { return Err(EINVAL); }; + if !pwr.power_zones.is_empty() || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 + || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) + || pwr.power_sample_period == 0 + || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period + || pwr.avg_power_filter_tc_ms < pwr.power_sample_period + || pwr.avg_power_target_filter_tc == 0 + || !(2..=abi::COMMON26_HW_PERF_ROWS).contains(&states.len()) + || states.windows(2).any(|s| s[1].pwr_mw <= s[0].pwr_mw || s[1].freq_hz <= s[0].freq_hz) + || pwr.perf_base_pstate == 0 || pwr.perf_base_pstate as usize >= states.len() + || core_mask.count_ones() != id.total_active_cores || id.total_active_cores == 0 + || cfg.shared3_tab.len() != 16 + || board.copy_bytes == 0 || board.sgx_size < 0xe14000 { + return Err(EINVAL); + } + // Alarm sensors: the chip's fast-die selection, also its sensor inventory. + let sensors = cfg.fast_sensor_mask[0]; + if sensors == 0 || sensors >> 32 != 0 || cfg.fast_sensor_mask_alt[0] != sensors { + return Err(EINVAL); + } + // The SRAM voltage of each operating point, published by the loader from the ADT. + let sram_table = Self::sram_table(states.len())?; + + let mut alloc = graph.alloc(); + let mut boot = BootJob::new(&mut alloc, graph.event_manager.try_get_polled()?, + graph.kernel_uat(), &graph.dev, cfg)?; + // The 0x60-byte root child and the eight-byte temperature generation occupy + // consecutive, 64-byte-aligned shared suballocations. + let extra = alloc.shared.array_empty::(0x80 + 8)?; + + // The thirteen TX descriptors and four RX rings. + let mut channels = KVec::new(); + let mut addresses = [0; 34]; + for (index, address) in addresses.iter_mut().enumerate() { + let size = directory26::allocation(index).map_err(|_| EINVAL)?.size; + let owner = if index < 26 && index % 2 == 1 { + alloc.private.array_empty::(size)? + } else { + alloc.shared.array_empty::(size)? + }; + *address = owner.gpu_va().get(); + channels.push(owner, GFP_KERNEL)?; + } + { + // The boot job's entry is pending at index 0 of its empty ring. + let slot = u8::try_from(boot.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, boot.queue.gpu_va().get(), 1, slot, true) + .map_err(|_| EINVAL)?; + let ring = channels[2 * SUBMISSION_RING + 1].as_mut_slice(); + ring[..entry.len()].copy_from_slice(&entry); + crate::pgtable::clean_poc(ring.as_ptr(), ring.len()); + } + { + // The two idle-policy records: keep powered, then allow off. + let records = &mut channels[2 * crate::m3::DEVICE_CONTROL + 1].as_mut_slice() + [..2 * crate::m3::CONTROL_BYTES]; + for (index, record) in records.chunks_exact_mut(crate::m3::CONTROL_BYTES).enumerate() { + crate::m3::Action::Idle { enabled: index == 1 }.encode(record).map_err(|_| EINVAL)?; + } + crate::pgtable::clean_poc(records.as_ptr(), records.len()); + } + + let mut directory = alloc.private.array_empty::(0x4c8)?; + let bytes = directory.as_mut_slice(); + directory26::write_channels(bytes, &addresses).map_err(|_| EINVAL)?; + let base = &graph.initdata.runtime_pointers; + + // Hardware data: the 27.2 inline block. + use fw::initdata::raw::HwDataBG14V27_2 as Hw; + use crate::m3::m3_mmio_26::{write_record, RECORD_BYTES, TABLE_OFFSET}; + let mut hardware = alloc.private.array_empty::(0x2788)?; + let hw = hardware.as_mut_slice(); + let mode = |slot: usize| if board.writable & (1 << slot) != 0 { 2 } else { 0 }; + for slot in 0..60 { + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * slot..], 0, 0, 0, 0, 0, mode(slot)) + .map_err(|_| EINVAL)?; + } + let mut register_mappings = KVec::new(); + let mut io_va = IOVA_KERN_MMIO_RANGE.start; + for reg in board.registers { + let physical = match reg.base { + RegisterBaseV27_2::Physical(pa) => pa, + RegisterBaseV27_2::Sgx(offset) => board.sgx + offset, + }; + let Some(va_offset) = reg.install else { continue; }; + let subpage = physical as usize & mmu::UAT_PGMSK; + let span = (subpage + reg.size as usize + mmu::UAT_PGMSK) & !mmu::UAT_PGMSK; + let writable = mode(reg.slot) == 2; + let page_start = physical - subpage as u64; + let va = match va_offset { + 0 => io_va, + offset => IOVA_KERN_MMIO_RANGE.start + offset, + }; + let page = graph.uat.kernel_vm().map_io( + graph.dev.as_ref().as_ref(), va, page_start as usize, span, + if writable { mmu::PROT_FW_MMIO_RW } else { mmu::PROT_FW_MMIO_RO }, + )?; + if page.translate_offset(subpage)? != physical + || page.translate_offset(subpage + reg.size as usize - 1)? != physical + u64::from(reg.size) - 1 { + return Err(EINVAL); + } + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * reg.slot..], physical, + page.iova() + subpage as u64, reg.size, reg.size, reg.relative, mode(reg.slot)) + .map_err(|_| EINVAL)?; + if va_offset == 0 { + io_va = io_va.checked_add(span as u64).ok_or(EOVERFLOW)?; + } + register_mappings.push(page, GFP_KERNEL)?; + } + let dump = core::mem::offset_of!(Hw, coredump_copy_buffer_size); + put64(hw, dump, u64::from(board.copy_bytes)); + base.hwdata_b.with(|old, _| { + for (offset, value) in [ + (0x00, old.unk_8.0), (0x08, old.unk_18.0), + (0x10, 0x11_00000000), (0x18, 0x11_00000000), + (0x20, 0x6f_ffff8000), (0x28, IOVA_G14_V27_2_TIMESTAMP_RANGE.start), + (0x10cc, old.uat_ttb_base.0), + ] { + put64(hw, offset, value); + } + for (offset, value) in [(0x10d4, old.gpu_core_id), (0x10d8, old.gpu_rev_id), + (0x10dc, id.total_active_cores), (0x10e0, old.max_pstate)] { + put32(hw, offset, value); + } + let chip = core::mem::offset_of!(Hw, chip_id); + for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c].into_iter().enumerate() { + put32(hw, chip + 4 * i, word); + } + }); + // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. + for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), + (0xffc, 1), (0x2724, 1), (0x2754, 1), + (0xfc4, 1), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), + (0x109c, 0), (0x1064, 0), (0x2728, 0)] { + put32(hw, offset as usize, value); + } + // Compute resource mask, one low bit per configured core; the firmware seeds the + // compute engine's population from it. + let cores = id.total_active_cores; + put32(hw, 0x2670, if cores < 32 { (1u32 << cores) - 1 } else { u32::MAX }); + // Firmware-managed operating points, CRE and event-assisted operating-point completion. + for offset in [0xfc0, 0x26b8, 0x1054] { + put32(hw, offset, 1); + } + put64(hw, 0x267c, u64::from(*core_mask)); + put32(hw, 0x2684, id.total_active_cores); + // Operating points: power above the lowest state, and frequency above the base state, + // as percentages; MHz and the per-lane core and SRAM voltages. + let top = states.len() - 1; + if old_max_pstate(base)? as usize != top { return Err(EINVAL); } + let baseline = states[0].pwr_mw; + let span = crate::float::F32::from(states[top].pwr_mw - baseline); + for (i, state) in states.iter().enumerate() { + let percentage = crate::float::F32::from(state.pwr_mw - baseline) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_A + i * 4, percentage.to_bits()); + } + let base_idx = pwr.perf_base_pstate as usize; + let base_hz = states[base_idx].freq_hz; + let span = crate::float::F32::from(states[top].freq_hz - base_hz); + for (i, state) in states.iter().enumerate().skip(base_idx + 1) { + let relative = crate::float::F32::from(state.freq_hz - base_hz) * crate::f32!(100.0) / span; + put32(hw, abi::COMMON26_HW_PERF_RELATIVE_B + 4 * i, relative.to_bits()); + } + for (i, state) in states.iter().enumerate() { + let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; + let sram_mv = match &sram_table { + Some(table) => { + let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz { + return Err(EINVAL); + } + let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if value < *mv || value > 1100 { return Err(EINVAL); } + value + } + None => (*mv).max(850), + }; + let mhz = state.freq_hz / 1_000_000; + for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { + put32(hw, series + i * 4, mhz); + } + for lane in 0..abi::COMMON26_HW_PERF_LANES { + let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE + lane * 4; + put32(hw, abi::COMMON26_HW_PERF_CORE_VOLTAGE + row, *mv); + put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); + } + } + crate::pgtable::clean_poc(hw.as_ptr(), hw.len()); + put64(bytes, 0, hardware.gpu_va().get()); + channels.push(hardware, GFP_KERNEL)?; + + // The directory's other records; +0x485 is the power controller. + let mut owners = KVec::new(); + let mut controller = None; + let mut compute_state = 0; + for (offset, size) in [(0x10, 0x88), (0x254, 0x678), (0x25c, 0x760), + (0x264, 0x6d0), (0x26c, 0x60), (0x485, 0x6c48)] { + let mut owner = alloc.private.array_empty::(size)?; + if offset == 0x485 { + Self::controller(owner.as_mut_slice(), graph, &extra, sensors)?; + } + let address = owner.gpu_va().get(); + put64(bytes, offset, address); + if offset == 0x10 { + put64(bytes, 8, address); + } + if offset == 0x264 { + // The compute engine state the start and finish records name. + compute_state = address; + } + if offset == 0x485 { + controller = Some(owner); + } else { + owners.push(owner, GFP_KERNEL)?; + } + } + let controller = controller.ok_or(EINVAL)?; + let ids = alloc.private.array_empty::(0x134c)?; + for (slot, offset) in [(0x2c8, 0), (0x2d0, 0x1000), (0x2d8, 0x1300)] { + put64(bytes, slot, ids.gpu_va().get() + offset); + } + owners.push(ids, GFP_KERNEL)?; + let low = base.buffer_mgr_ctl_low_mapping.as_ref().ok_or(EINVAL)?; + let high = base.buffer_mgr_ctl_high_mapping.as_ref().ok_or(EINVAL)?; + if low.translate_offset(0)? != high.translate_offset(0)? { return Err(EINVAL); } + put64(bytes, 0x2e0, low.iova()); + put64(bytes, 0x2e8, high.iova()); + bytes[0x3e4] = 0xff; + let payload = alloc.shared.array_empty::( + directory26::LOG_THREADS * RING_RECORDS as usize * directory26::LOG_PAYLOAD_BYTES)?; + put64(bytes, 0x200, payload.gpu_va().get()); + owners.push(payload, GFP_KERNEL)?; + crate::pgtable::clean_poc(bytes.as_ptr(), bytes.len()); + + let status = alloc.shared.array_empty::(0x20)?; + let boot_page = { + let page = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + fw::types::GpuArray::empty(page, mmu::UAT_PGSZ)? + }; + let mut globals = alloc.shared_ro.array_empty::(0xe48)?; + { + let data = globals.as_mut_slice(); + for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { + data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); + } + let ceiling = pwr.perf_max_pstate * 100; + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, STATE_CAP)] { + put32(data, at, value); + } + put32(data, 0x6e, 1); + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + let mut control = alloc.shared.array_empty::(0xe850)?; + { + // One shared backing: 0x20 bytes of indices, followed at +0x40 by 256 cache-flush + // requests. An empty ring still needs both VAs. + let flush = alloc.shared.array_empty::(0x40 + 256 * 0x18)?; + let state = flush.gpu_va().get(); + directory26::write_flush_ring(control.as_mut_slice(), 0x4be0, state, state + 0x40) + .map_err(|_| EINVAL)?; + // Request command-handler installation during powered initialization. + put32(control.as_mut_slice(), 0x4c24, 1); + owners.push(flush, GFP_KERNEL)?; + } + let mut power = alloc.shared.array_empty::(0x6a0)?; + { + // Cold mirrors of the controller's power and temperature-loop values. + let gains = base.hwdata_a.with(|a, _| (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); + let data = power.as_mut_slice(); + for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { + put32(data, at, value); + } + let initial = controller.as_slice(); + for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), + (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { + data[dst..dst + 4].copy_from_slice(&initial[src..src + 4]); + } + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + + boot.encode(&boot.info(compute_state)); + let (page_size, page_bits, levels, descriptors) = graph.initdata.with(|r, _| + (r.uat_page_size, r.uat_page_bits, r.uat_num_levels, r.uat_level_info)); + let root = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + core::mem::drop(alloc); + let root = fw::types::GpuObject::::new_init_prealloc(root, + |_| try_init!(Self { + graph: graph.clone(), boot, compute_state, channels, _owners: owners, + _register_mappings: register_mappings, _controller: controller, _directory: directory, + boot_page, globals, status, control, power, extra, + }), + |owners, _| { + try_init!(fw::initdata::raw::InitDataG14V27_2 { + ver_info: fw::types::Array::new(core::array::from_fn(|i| (FIRMWARE_WORD >> (16 * i)) as u16)), + unk_buf: owners.boot_page.gpu_pointer(), + unk_8: 0, + unk_c: 0, + runtime_pointers: owners._directory.gpu_pointer(), + globals: owners.globals.gpu_pointer(), + role: 0, + host_mapped_fw_allocations: 1, + uat_page_size: page_size, + uat_page_bits: page_bits, + uat_num_levels: levels, + uat_level_info: descriptors, + __pad0: Default::default(), + status_record: owners.status.gpu_pointer(), + control: owners.control.gpu_pointer(), + power: owners.power.gpu_pointer(), + extra: owners.extra.gpu_pointer(), + }) + }, + )?; + root.with(|r, _| crate::pgtable::clean_poc(core::ptr::from_ref(r).cast(), core::mem::size_of_val(r))); + Ok(root) + } + + /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` + /// (frequency and SRAM millivolts per state), if it published one. The node itself must exist. + fn sram_table(states: usize) -> Result>> { + let chosen = kernel::of::chosen().ok_or(ENODEV)?; + let is = |name: Option>, want: &[u8]| { + name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) + }; + for parent in chosen.children() { + if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } + for child in parent.children() { + if is(child.get_opt_property::>(c"name")?, b"sgx") { + let table = child.get_opt_property::>(c"adt-perf-states-sram")?; + if table.as_ref().is_some_and(|t| t.len() != states * 8) { return Err(EINVAL); } + return Ok(table); + } + } + } + Err(EINVAL) + } + + /// The power and thermal controller (directory +0x485): the 13.5 calibrated values of the + /// hardware data A, moved to the 27.2 layout. + fn controller(policy: &mut [u8], graph: &GpuManagerG14V13_5, extra: &fw::types::GpuArray, + sensors: u64) -> Result { + let pwr = &graph.dyncfg.pwr; + let cfg = graph.cfg; + let base = &graph.initdata.runtime_pointers; + let max_state = (pwr.perf_states.len() as u32 - 1) * 100; + for offset in [0x222c, 0x2880] { + put32(policy, offset, max_state); + } + let generation = extra.gpu_va().get() + 0x80; + if generation & 0x3f != 0 || extra.as_slice()[0x80..] != [0; 8] { + return Err(EINVAL); + } + put64(policy, 0x3b98, generation); + // Secure metrology sensor set, and the fast-die release temperature, mask and gains. + put64(policy, 0x3ba0, sensors); + let (release, mask, integral, proportional) = base.hwdata_a.with(|old, _| + (old.fast_die0_release_temp_cc, old.fast_die0_sensor_mask.0, + old.fast_die0_ki_dt.to_bits(), old.fast_die0_kp.to_bits())); + for (source, value, width) in [(0x2270, u64::from(release), 4), (0x2268, mask, 8), + (0x2294, u64::from(integral), 4), (0x22a4, u64::from(proportional), 4)] { + let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(at..at + width).ok_or(EINVAL)?.copy_from_slice(&value.to_le_bytes()[..width]); + } + // Thermal thresholds and corrections, then the SoC-hot alarm selection. + for (at, value) in [(0x22d4, 11000), (0x2284, 900), (0x2288, 4), + (0x229c, crate::f32!(1.0).to_bits()), (0x2f30, 125), (0x2f34, 1)] { + put32(policy, at, value); + } + for at in [0x2320, 0x2420, 0x2f38, 0x3038] { + for sid in (0..64).filter(|sid| sensors & (1u64 << sid) != 0) { + put32(policy, at + 4 * sid, crate::f32!(5.3).to_bits()); + } + } + put64(policy, 0x2f28, sensors); + put32(policy, 0x3ba8, 1); + for (word, value) in policy[0x62b8..0x62f8].chunks_exact_mut(4).zip(cfg.shared3_tab) { + word.copy_from_slice(&value.to_le_bytes()); + } + // Cold-wake operand: the board's base operating point. + put32(policy, 0xa4, pwr.perf_base_pstate); + for (source, bits) in [ + (4, pwr.pwr_sample_period_aic_clks), + (8, pwr.pwr_sample_period_aic_clks), + // Two initial state sources; the current state at +0x38 belongs to the firmware. + (0x2c, pwr.perf_base_pstate), + (0x30, pwr.perf_base_pstate), + (0x9f0, pwr.pwr_min_duty_cycle), + (0xb5c, pwr.perf_integral_gain.to_bits()), + (0xb60, pwr.perf_integral_gain2.to_bits()), + (0xb6c, pwr.perf_proportional_gain.to_bits()), + (0xb70, pwr.perf_proportional_gain2.to_bits()), + ] { + let target = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(target..target + 4).ok_or(EINVAL)?.copy_from_slice(&bits.to_le_bytes()); + } + // The calibrated values of the 13.5 producer; only the layout and the peak length unit + // differ. No power zones. + let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; + let fields = base.hwdata_a.with(|a, _| [ + (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), + (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), + (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), + (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), + (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), + (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), + (0xa48, max_state), + (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), + (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), + (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), + (0xb64, a.perf_filter_a.to_bits()), (0xb68, a.perf_filter_a2.to_bits()), + (0xb74, a.perf_integral_min_clamp.to_bits()), (0xb78, a.unk_79c.to_bits()), + (0xb84, a.boost_state_unk_k.to_bits()), (0xb88, a.base_pstate_scaled_2), + (0xb8c, a.max_pstate_scaled_5), (0xb90, a.base_pstate_scaled_3), + (0xb9c, a.perf_tgt_utilization_2), (0xbd0, a.base_pstate_scaled_4), + (0x2204, a.pwr_min_duty_cycle_2.to_bits()), (0x2208, a.max_pstate_scaled_6.to_bits()), + (0x220c, pwr.max_freq_mhz), + (0x22b0, a.unk_8a8.to_bits()), (0x22c0, a.pwr_min_duty_cycle_4), + (0x22c4, a.max_pstate_scaled_8), (0x22c8, a.max_pstate_scaled_9), + (0x2308, a.max_pstate_scaled_10), + (0x28e8, 0), (0x28f0, a.max_power_4), + (0x28f4, a.max_power_5), (0x28f8, a.max_power_6), + (0x2904, a.avg_power_target_filter_a_neg.to_bits()), + (0x2908, a.avg_power_target_filter_a.to_bits()), + (0x29f0, a.avg_power_filter_a_neg.to_bits()), + (0x29f8, a.avg_power_filter_a.to_bits()), + (0x2a00, a.avg_power_ki_dt.to_bits()), (0x2a10, a.avg_power_kp.to_bits()), + (0x2a0c, a.unk_d20.to_bits()), (0x2a1c, a.avg_power_min_duty_cycle), + (0x2a20, a.max_pstate_scaled_12), (0x2a2c, a.max_power_7.to_bits()), + (0x2a30, a.max_power_8), + (0x2b80, a.unk_e10_0.gpu_se_filter_a_neg.to_bits()), + (0x2b84, a.unk_e10_0.gpu_se_filter_1_a_neg.to_bits()), + (0x2b88, a.unk_e10_0.gpu_se_filter_a.to_bits()), + (0x2b8c, a.unk_e10_0.gpu_se_filter_1_a.to_bits()), + (0x2b90, a.unk_e10_0.gpu_se_ki_dt.to_bits()), + (0x2b94, a.unk_e10_0.gpu_se_ki_1_dt.to_bits()), + (0x2b9c, a.unk_e10_0.unk_7c.to_bits()), + (0x2ba0, a.unk_e10_0.gpu_se_kp.to_bits()), + (0x2ba4, a.unk_e10_0.gpu_se_kp_1.to_bits()), + (0x2bac, a.unk_e10_0.unk_8c), (0x2bb0, a.unk_e10_0.max_pstate_scaled_1), + (0x2c10, a.unk_e10_0.unk_3c), (0x2c14, a.unk_e10_0.unk_38), + (0x2c28, a.unk_e10_0.gpu_se_reset_criteria), + (0x6ac8, 1), + ]); + for (at, value) in fields { + put32(policy, at, value); + } + put64(policy, 0xae0, u64::from(samples) * u64::from(pwr.pwr_sample_period_aic_clks)); + crate::pgtable::clean_poc(policy.as_ptr(), policy.len()); + Ok(()) + } +} + +/// The 13.5 hardware data's highest operating-point index. +fn old_max_pstate(base: &fw::initdata::RuntimePointersG14V13_5) -> Result { + Ok(base.hwdata_b.with(|old, _| old.max_pstate)) +} diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index a58fac5e12c372..2fd17c298d68d4 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -122,6 +122,30 @@ pub(crate) struct PowerZone { pub(crate) filter_tc: u32, } +/// Base of a window in the firmware 27.2 register table. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[derive(Debug, Copy, Clone)] +pub(crate) enum RegisterBaseV27_2 { + /// A fixed physical address. + Physical(u64), + /// An offset into the GPU's SGX window (its `sgx` resource). + Sgx(u64), +} + +/// One record of the firmware 27.2 register table: 60 slots, each naming one window. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[derive(Debug, Copy, Clone)] +pub(crate) struct RegisterV27_2 { + pub(crate) slot: usize, + pub(crate) base: RegisterBaseV27_2, + pub(crate) size: u32, + /// Offset of the window within the GPU's register space, as the record carries it. + pub(crate) relative: u64, + /// Where the window is mapped for the firmware: `None` leaves the record without a + /// mapping, `Some(0)` takes the next free MMIO VA, `Some(offset)` a fixed MMIO VA offset. + pub(crate) install: Option, +} + /// An MMIO mapping used by the firmware. #[derive(Debug, Copy, Clone)] pub(crate) struct IOMapping { diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index bac2757175f2c2..1879be7f8ceade 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -104,3 +104,47 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_base: None, sram_size: None, }; + +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { + RegisterV27_2 { slot, base, size, relative, install } +} + +/// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except +/// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped +/// apart from the others. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { + use RegisterBaseV27_2::{Physical, Sgx}; + &[ + reg(0, Physical(0x23b0c4000), 0x4000, 0, None), // AIC software interrupt + reg(1, Physical(0x23b2c0000), 0x1000, 0, Some(0)), // Analog temperature controller + reg(3, Physical(0x200f04000), 0x18000, 0, None), // Memory cache + reg(8, Physical(0x27d050000), 0x4000, 0, None), // Streaming codec + reg(9, Physical(0x23b3d0000), 0x1000, 0, Some(0x10_0000)), // Push telemetry + reg(10, Physical(0x23b3c0000), 0x1000, 0, Some(0)), // Push telemetry readback + reg(12, Physical(0x26b45c000), 0x4000, 0, None), // ANE doorbell + reg(17, Sgx(0), 0x20000, 0, Some(0)), // GPU core + reg(31, Sgx(0xd04000), 0xc000, 0xd04000, Some(0)), // Fender configuration + reg(32, Sgx(0xd61000), 0x1000, 0xd61000, Some(0)), // GIFAF + reg(33, Sgx(0xe0c000), 0x4000, 0xe0c000, Some(0)), // CRE + reg(34, Sgx(0xd10000), 0x4000, 0xd10000, Some(0)), // CPMS + reg(37, Sgx(0xe10000), 0x1000, 0xe10000, Some(0)), // Fender scratch RAM + reg(40, Sgx(0xd00000), 0x4000, 0xd00000, Some(0)), // Fender multi-GPU configuration + reg(44, Sgx(0xd80000), 0x8000, 0, Some(0)), // Metrology sensors + ] +}; + +/// Slots of the 27.2 register table whose stock mode is read-write. +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) const WRITABLE_V27_2: u64 = { + let mut mask = 0u64; + let mut slot = 0; + while slot < 60 { + if matches!(slot, 0 | 2 | 3 | 5..=9 | 12 | 17 | 25..=27 | 31..=40 | 42..=48 | 52..=55 | 58) { + mask |= 1 << slot; + } + slot += 1; + } + mask +}; diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9f..70116b7116622d 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -2,6 +2,7 @@ //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] pub(crate) struct Completion; @@ -53,7 +54,12 @@ pub(crate) struct Packet { /// Who submitted the packet, for the failure log only. pub(crate) owner:Owner, vm_job:Pin>>>, + /// G14 firmware 27.2: the compute preemption buffer in the packet's VM, kept until retirement. + pub(crate) preempt:Option>, } +/// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. +#[derive(Clone)] +pub(crate) enum Sink { M3(Shared), G14V27_2(Arc) } /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -118,9 +124,9 @@ impl Packet { } } } -pub(crate) struct Job {shared:Shared,packet:Arc} +pub(crate) struct Job {shared:Sink,packet:Arc} /// Timeout state of a [`Job`], owned by the scheduler's timeout worker. -pub(crate) struct JobTimeout {shared:Shared,packet:Arc} +pub(crate) struct JobTimeout {shared:Sink,packet:Arc} impl sched::JobImpl for Job { type TimeoutData = JobTimeout; fn timeout_data(&self)->JobTimeout { @@ -129,7 +135,11 @@ impl sched::JobImpl for Job { fn run(job:&mut Self)->Result> { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. - if let Err(e)=crate::m3::m3_runtime::Runtime::submit(&job.shared,job.packet.clone()) { + let submitted=match &job.shared { + Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), + }; + if let Err(e)=submitted { pr_err!("M3 scheduler: submission failed {:?}\n",e); // submit() failed before this packet could be published. job.packet.release_guard();job.packet.finish(Err(e)); @@ -137,13 +147,23 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { + let shared=match &job.shared { + Sink::M3(shared)=>shared.clone(), + Sink::G14V27_2(runtime)=>{ + // The runtime's own command timeout fails a hung GPU; a healthy one is late. + if runtime.healthy() {return sched::Status::NoHang;} + runtime.withdraw(&job.packet); + job.packet.finish(Err(EIO)); + return sched::Status::NoDevice; + } + }; // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { - if let Some(r)=Option::as_mut(&mut *job.shared.lock()) {r.health().mark_failed();} - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(ETIMEDOUT));return sched::Status::NoDevice; } - let guard=job.shared.lock(); + let guard=shared.lock(); let Some(runtime)=guard.as_ref() else { job.packet.finish(Err(ENODEV)); return sched::Status::NoDevice; @@ -154,12 +174,15 @@ impl sched::JobImpl for Job { // device loss or corrupting an already signaled fence. if runtime.health().healthy() { return sched::Status::NoHang; } drop(guard); - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(EIO)); sched::Status::NoDevice } fn cancel(job:&mut Self) { - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + match &job.shared { + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } job.packet.finish(Err(ECANCELED)); } } @@ -175,7 +198,10 @@ impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { } pub(crate) struct Queue { entity:sched::Entity,_scheduler:Arc>, - shared:Shared,vm:mmu::Vm,usc:u64,fences:FenceContexts, + shared:Sink,vm:mmu::Vm,usc:u64,fences:FenceContexts, + /// G14 firmware 27.2: the VM's private allocator and the size of the per-packet + /// preemption buffer it provides. + preempt_alloc:Option<(Arc>,usize)>, /// Whether the SoC advertises early tiling (`m3_soc::Features::fragment_dependency`). early_tiling:bool, wide_visibility:bool, @@ -190,8 +216,19 @@ impl Queue { let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, - shared,vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency}) + shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, + early_tiling,wide_visibility,urgency,preempt_alloc:None}) + } + /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, + ualloc_priv:Arc>,preempt_bytes:usize)->Result { + agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; + let urgency=3u8.saturating_sub(priority.min(3) as u8); + let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, + 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; + Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, + shared:Sink::G14V27_2(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_g14_queue"),kernel::static_lock_class!())?, + early_tiling:false,wide_visibility:false,urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes))}) } } impl queue::Queue for Queue { @@ -201,6 +238,8 @@ impl queue::Queue for Queue { let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { + // The G14 firmware-27.2 runtime is compute-only. + if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); @@ -237,13 +276,21 @@ impl queue::Queue for Queue { pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper); EINVAL })?; - crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + if self.preempt_alloc.is_none() { + crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc}),GFP_KERNEL)?; } parser.finish().map_err(|_|EINVAL)?; - let packet=Arc::new(Packet{vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, + let preempt=match &self.preempt_alloc { + Some((alloc,bytes)) if commands.iter().any(|c| matches!(c, Command::Compute(_))) => + Some(alloc.lock().array_empty::(*bytes)?), + _ => None, + }; + let packet=Arc::new(Packet{preempt,vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eafd5732bceac8..cb64aa8f1ecbcc 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -81,7 +81,7 @@ mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_uapi; +pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -125,7 +125,7 @@ mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod m3_submit; +pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -201,11 +201,15 @@ pub(crate) mod m3_soc; mod t8122_hwdata; -mod m3_init_26; +pub(crate) mod m3_init_26; mod m3_profile; -mod m3_mmio_26; +pub(crate) mod m3_mmio_26; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_power_26; -mod m3_channel_format; +pub(crate) mod m3_channel_format; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 484a471f1190cc..a4fd3c7a7a594c 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4521,3 +4521,142 @@ mod execution_context_tests { assert!(pick_returned(core::iter::empty(), &returns, &fences, 0).is_none()); } } + +/// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. +#[cfg(CONFIG_DRM_ASAHI_G15)] +const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; + +/// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its +/// kernel window into the firmware's shared second-level table and names its own trees in +/// TTBAT context 0 before the ASC starts. +#[cfg(CONFIG_DRM_ASAHI_G15)] +pub(crate) struct FirmwareWindow { + handoff: UatRegion, + ttbs: UatRegion, + tables: UatRegion, + shared_l2: UatRegion, + entries: KVec, + lower_root: u64, + pa_mask: u64, +} + +#[cfg(CONFIG_DRM_ASAHI_G15)] +impl FirmwareWindow { + /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared + /// table and context 0 are empty. + pub(crate) fn reserve(dev: &device::Device, geometry: UatGeometry) -> Result { + let handoff = Uat::map_region(dev, c"handoff", HANDOFF_SIZE, true)?; + let ttbs = Uat::map_region(dev, c"ttbs", UAT_PGSZ, true)?; + let tables = Uat::map_region(dev, c"pagetables", UAT_PGSZ, true)?; + let shared_l2 = Uat::map_region(dev, c"shared-l2", UAT_PGSZ, true)?; + let this = Self { + handoff, ttbs, tables, shared_l2, + entries: KVec::from_elem(0u64, UAT_PGSZ / 8, GFP_KERNEL)?, + lower_root: 0, + pa_mask: ((1u64 << geometry.oas) - 1) & !(UAT_PGMSK as u64), + }; + let h = this.handoff(); + if h.magic_ap.load(Ordering::Acquire) != 0 || h.magic_fw.load(Ordering::Acquire) != 0 + || h.lock_ap.load(Ordering::Acquire) != 0 || h.lock_fw.load(Ordering::Acquire) != 0 + || !this.empty() { + return Err(EBUSY); + } + Ok(this) + } + + fn handoff(&self) -> &Handoff { + // SAFETY: map_region checked the size of the handoff reservation; only its aligned + // atomic fields are used. + unsafe { &*self.handoff.map.ptr().cast::() } + } + + fn shared(&self) -> &[AtomicU64; UAT_PGSZ / 8] { + // SAFETY: the shared-l2 reservation is one mapped 16 KiB table. + unsafe { &*self.shared_l2.map.ptr().cast::<[AtomicU64; UAT_PGSZ / 8]>() } + } + + fn context(&self) -> &SlotTTBS { + // SAFETY: the TTBAT reservation holds at least one aligned slot. + unsafe { &*self.ttbs.map.ptr().cast::() } + } + + fn empty(&self) -> bool { + let context = self.context(); + self.shared().iter().all(|w| w.load(Ordering::Acquire) == 0) + && context.ttb0.load(Ordering::Acquire) == 0 && context.ttb1.load(Ordering::Acquire) == 0 + } + + /// The regions to adopt the UAT from. + pub(crate) fn regions(&self) -> AdoptedRegions { + AdoptedRegions { + handoff: self.handoff.base..self.handoff.base + UAT_PGSZ as PhysicalAddr, + ttbs: self.ttbs.base..self.ttbs.base + UAT_PGSZ as PhysicalAddr, + kernel_root: self.tables.base, + } + } + + /// Copies the kernel window's second-level entries from `uat` and writes all of its tables + /// back. Call after the last allocation the firmware is to reach. + pub(crate) fn mirror(&mut self, uat: &Uat) -> Result { + let mask = self.pa_mask; + let root = uat.kernel_window_root(); + let entries = &mut self.entries; + // SAFETY: the adopted UAT's driver-owned window root and its second level are live + // RAM tables. + unsafe { + let upper = pgtable::with_root_entries(None, root, 3, |w| w[2].load(Ordering::Acquire))?; + if upper & 3 != 3 { return Err(EINVAL); } + pgtable::with_root_entries(None, upper & mask, entries.len(), |w| { + for (entry, word) in entries.iter_mut().zip(w) { + *entry = word.load(Ordering::Acquire); + } + })?; + } + // The window's last 4 GiB is the MMIO range: its register mappings use one table. + let first_io = (0xf_0000_0000u64 >> 25) as usize; + if entries[first_io..].iter().filter(|w| **w != 0).count() != 1 { return Err(EINVAL); } + for &w in entries.iter().filter(|w| **w != 0) { + if w & 3 != 3 { return Err(EINVAL); } + crate::g15::uat::clean_page(w & mask)?; + } + crate::g15::uat::clean_lower(uat)?; + self.lower_root = uat.kernel_lower_root(); + Ok(()) + } + + /// Installs the mirrored window and names the driver's trees in context 0. + pub(crate) fn install(&self) -> Result { + if !self.empty() || self.lower_root == 0 { return Err(EBUSY); } + for (word, value) in self.shared().iter().zip(self.entries.iter()) { + if *value != 0 { word.store(*value, Ordering::Release); } + } + let context = self.context(); + context.ttb0.store(self.lower_root | TTBR_VALID, Ordering::Release); + context.ttb1.store(self.tables.base | TTBR_VALID, Ordering::Release); + pgtable::clean_poc(self.ttbs.map.ptr(), size_of::()); + pgtable::clean_poc(self.shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + Ok(()) + } + + /// Announces the host to the firmware; call just before starting the ASC. + pub(crate) fn announce(&self) { + self.handoff().magic_ap.store(MAGIC_G14_V27_2, Ordering::Release); + fence(Ordering::SeqCst); + } + + /// Whether the firmware has answered the announcement. + pub(crate) fn answered(&self) -> bool { + self.handoff().magic_fw.load(Ordering::Acquire) == MAGIC_G14_V27_2 + } + + /// Whether the firmware still names the shared table and context 0 as installed. + pub(crate) fn intact(&self) -> bool { + // SAFETY: the firmware's kernel root is one mapped 16 KiB table. + let root = unsafe { &*self.tables.map.ptr().cast::<[AtomicU64; 4]>() }; + let context = self.context(); + root[2].load(Ordering::Acquire) & self.pa_mask == self.shared_l2.base + && context.ttb0.load(Ordering::Acquire) == self.lower_root | TTBR_VALID + && context.ttb1.load(Ordering::Acquire) == self.tables.base | TTBR_VALID + } +} diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index 0c9e6f62b5bbe2..e3ce17cb7cb7ee 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -697,6 +697,23 @@ impl> GpuArray { } } +#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +impl> GpuArray { + /// Aligned index in a shared firmware ring, accessed without borrowing its payload. + pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { + if offset.checked_add(4).is_none_or(|end| end > self.len) { + return Err(EINVAL); + } + let ptr = self.raw.wrapping_add(offset).cast::(); + if !ptr.is_aligned() { + return Err(EINVAL); + } + // SAFETY: bounds and alignment checked; the shared ring ABI accesses + // this word only in aligned 32-bit transactions while the ring is live. + Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) + } +} + impl> Deref for GpuArray { type Target = GpuOnlyArray; diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 1fde883e6c6df4..658c98de1e77ac 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -349,6 +349,13 @@ impl Resources<'_> { .expect("64-bit read failed!") } + /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in + /// bit 4. Sampled while the firmware holds the GPU powered. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + pub(crate) fn operating_point(&self) -> u32 { + self.sgx_read32::<0xd01000>() + } + /// Initialize the MMIO registers for the GPU. pub(crate) fn init_mmio(&self) -> Result { // Nothing to do for now... diff --git a/drivers/gpu/drm/asahi/rtkit_dump.c b/drivers/gpu/drm/asahi/rtkit_dump.c new file mode 100644 index 00000000000000..c7b147c35a286a --- /dev/null +++ b/drivers/gpu/drm/asahi/rtkit_dump.c @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size); + +/* RTKit owns its immutable shadow only during the crash callback. */ +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size) +{ + void *copy; + + if (!size) + return; + copy = vmalloc(size); + if (copy) { + memcpy(copy, data, size); + dev_coredumpv(dev, copy, size, GFP_KERNEL); + } +} diff --git a/rust/macros/versions.rs b/rust/macros/versions.rs index b13a5d55c0e17b..21a6d5985332cc 100644 --- a/rust/macros/versions.rs +++ b/rust/macros/versions.rs @@ -93,7 +93,7 @@ static AGX_VERSIONS: VersionConfig = VersionConfig { fields: &["G", "V"], enums: &[ &["G13", "G14", "G14X"], - &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5"], + &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5", "V27_2"], ], versions: &[ &["G13", "V12_3"], @@ -276,8 +276,11 @@ fn filter_versions( } pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { - let config = match attr.to_string().as_str() { - "AGX" => &AGX_VERSIONS, + // AGX_V27_2 is AGX plus G14/V27_2: only the firmware 27.2 root and hardware-data layouts + // are instantiated for that version. + let group = attr.to_string(); + let config = match group.as_str() { + "AGX" | "AGX_V27_2" => &AGX_VERSIONS, _ => panic!("Unknown version group {}", attr), }; @@ -321,7 +324,8 @@ pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { body.extend(it); - for ver in config.versions { + let candidate = (group == "AGX_V27_2").then_some(&["G14", "V27_2"][..]); + for ver in config.versions.iter().copied().chain(candidate) { let tag = ver.join(""); let mut ver_num = Vec::::new(); for (i, comp) in ver.iter().enumerate() { From a47acf0bf9faf421fb4a6cb83eb86eee9597b777 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 06:40:39 -0500 Subject: [PATCH 0266/1514] drm/asahi: run the G14 firmware-27.2 runtime from firmware notifications Review asked for no sleep or poll loops where the firmware gives a signal. The runtime polled from delayed work every 1 ms while busy and every 20 ms when idle, and dropped every endpoint message. The firmware sends endpoint 0x20 a message after it publishes event, statistics or log records. Each message now queues one run of the service, which consumes the rings and retires completed commands; there is no idle poll and no timer. The DRM scheduler's job timeout runs the service once more, so a command the firmware never completes still hits the command timeout. A firmware crash also runs it. The service runs on its own ordered workqueue. Stop waits for published work on a condition variable the service signals, detaches the message route so nothing queues more work, and drains the workqueue, replacing the fsleep loops and the fixed 20 ms sleep. Start waits for the firmware's ready status (+0x14) instead of a fixed 1 s, and fails if the command handlers are not installed in time instead of ignoring the timeout. Installation is acknowledged by the firmware clearing the request word (+0x4c24); the old wait also required the powered-stage word (+0x4c00) to read 2, which it never did after the handlers were installed, so it always ran out its 500 ms. A failed start names the step. These and the idle-policy and running-flag waits stay bounded checks of a shared word: the firmware writes it and sends no message, as with the existing G14 device-control channel. The completion stamp is written before the firmware's post-processing advances the queue's retired position, which sends no message. When the stamp is there and the position is not, the service waits for the position for at most 2 ms. Faster retirement showed that the firmware keeps a retired command's tracking slot (+0x94) linked for a while, and can link one again after releasing it; with a fixed round-robin the pool stopped at the first reuse. Pump now takes the next slot that is neither in flight nor held. If all are held it kicks the firmware's retirement scan once and the next notification, submission or scheduler timeout retries; there is no message for a slot's release. The stop line reports the notifications received, how often the position wait ran and how many held slots were passed over. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 316 +++++++++++++++++--------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 16 +- drivers/gpu/drm/asahi/m3/m3_submit.rs | 2 + 3 files changed, 226 insertions(+), 108 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index ea585628b1e4f0..91e327b361c81c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -8,24 +8,26 @@ //! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the //! 27.2 layout and published, in order, on the root's queue. Render commands are refused. //! -//! Completion follows the queue's retired position, which the firmware advances in order. -//! The firmware's event, statistics, log and trace rings are consumed as they fill, since -//! the firmware waits for space in them. +//! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after +//! publishing records on its event, statistics and log rings: each one runs the service, which +//! consumes those rings (the firmware waits for space in them) and retires completed commands. +//! Completion follows the queue's retired position, which the firmware advances in order. There +//! is no timer: the DRM scheduler's job timeout runs the service as the backstop for a hang. use core::ops::Range; -use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ device, drm::sched, - new_delayed_work, new_mutex, + new_condvar, new_mutex, new_spinlock, new_work, platform, prelude::*, soc::apple::rtkit, - sync::{aref::ARef, Arc, Mutex}, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, - workqueue::{self, impl_has_delayed_work, DelayedWork, WorkItem}, + workqueue::{impl_has_work, OwnedQueue, Work, WorkItem}, }; use crate::{ @@ -45,8 +47,10 @@ const ASC_RUN: u32 = 0x10; /// Commands slower than this are a hang; the firmware state is then not trusted. const COMMAND_TIMEOUT_MS: i64 = 5000; -/// Idle polling keeps the firmware's rings drained and bounds completion latency. -const IDLE_POLL_MS: u64 = 20; +/// How long `stop` lets published work retire before it fails what is left. +const STOP_DRAIN_MS: u32 = 2000; +/// Bound on the wait between a command's completion stamp and its retired position. +const RETIRE_WAIT_US: i64 = 2000; /// The ASC control page, kept mapped until the firmware is stopped. pub(crate) struct AscControl(*mut u8); @@ -83,37 +87,87 @@ impl Drop for AscControl { } } +/// Where the firmware's messages go: the runtime once it exists, nowhere before or after. +#[pin_data] +pub(crate) struct Notify { + dev: ARef, + #[pin] + runtime: SpinLock>>, + /// Endpoint-0x20 messages received, reported when the firmware stops. + messages: AtomicU64, +} + +impl Notify { + fn new(dev: &device::Device) -> Result> { + Arc::pin_init(pin_init!(Self { + dev: dev.into(), + runtime <- new_spinlock!(None, "g14_v27_2::Notify::runtime"), + messages: AtomicU64::new(0), + }), GFP_KERNEL) + } + + /// Queues one service run if a runtime is attached. A run already queued covers this one. + fn wake(&self) { + if let Some(runtime) = self.runtime.lock().as_ref() { + let _ = runtime.queue.enqueue::, 0>(runtime.clone()); + } + } + + fn attach(&self, runtime: Arc) { + *self.runtime.lock() = Some(runtime); + } + + /// After this returns, nothing queues service work. + fn detach(&self) -> Option> { + self.runtime.lock().take() + } +} + /// RTKit operations of the GPU firmware: its crash log lives in the loader's data segment. pub(crate) struct Firmware; #[vtable] impl rtkit::Operations for Firmware { - type Data = Arc>; + type Data = Arc; type Buffer = crate::g17::CrashLog; const COPROC_PLACES_BUFFERS: bool = true; - fn shmem_map(dev: kernel::sync::ArcBorrow<'_, ARef>, iova: usize, size: usize) -> Result { - crate::g17::CrashLog::from_firmware(&dev, iova, size) + fn shmem_map(notify: ArcBorrow<'_, Notify>, iova: usize, size: usize) -> Result { + crate::g17::CrashLog::from_firmware(¬ify.dev, iova, size) } - fn crashed(dev: kernel::sync::ArcBorrow<'_, ARef>, log: Option<&[u8]>) { + fn crashed(notify: ArcBorrow<'_, Notify>, log: Option<&[u8]>) { unsafe extern "C" { fn asahi_save_rtkit_dump(dev: *mut core::ffi::c_void, data: *const u8, size: usize); } - dev_err!(&**dev, "GPU firmware crashed\n"); + dev_err!(&*notify.dev, "GPU firmware crashed\n"); if let Some(log) = log { // SAFETY: RTKit and the device remain live throughout this synchronous copy. - unsafe { asahi_save_rtkit_dump(dev.as_raw().cast(), log.as_ptr(), log.len()) }; + unsafe { asahi_save_rtkit_dump(notify.dev.as_raw().cast(), log.as_ptr(), log.len()) }; } + // The service sees the crash and fails outstanding work. + notify.wake(); } - fn recv_message(_dev: kernel::sync::ArcBorrow<'_, ARef>, _ep: u8, _message: u64) {} + /// The firmware sends endpoint 0x20 a message after it publishes event, statistics or log + /// records. Whatever the message, the service reads every ring and the queue's position, + /// so each one is a wakeup. + fn recv_message(notify: ArcBorrow<'_, Notify>, ep: u8, _message: u64) { + if ep == EP_FIRMWARE { + notify.messages.fetch_add(1, Ordering::Relaxed); + notify.wake(); + } + } } type Peer = Pin>>; -/// Polls `done` every millisecond, draining the firmware's rings, for at most `ms`. +/// Waits for a shared-word acknowledgement, checking `done` every millisecond and draining the +/// firmware's rings, for at most `ms`. Only for the start/stop handshakes whose acknowledgement +/// is a word the firmware writes with no message: the ready status, the command-service +/// installation, device-control (idle-policy) consumption and the running flag. The existing G14 +/// path waits for its device-control channel the same way (`channel::TxChannel::wait_for`). fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Result { let start = Instant::::now(); loop { @@ -170,8 +224,9 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; let control = asc.read(ASC_CPU_CONTROL); if control & ASC_RUN != 0 { return Err(EBUSY); } + let notify = Notify::new(dev)?; let mut peer = KBox::pin( - rtkit::RtKit::::new(dev, None, 0, Arc::new(ARef::from(dev), GFP_KERNEL)?)?, + rtkit::RtKit::::new(dev, None, 0, notify.clone())?, GFP_KERNEL)?; let resources = crate::regs::Resources::new(pdev)?; let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; @@ -198,29 +253,37 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta // From here the firmware may read everything the window names: nothing is freed. let mut booted = false; + let mut step = "loader handoff"; let result = (|| -> Result { let start = Instant::::now(); while !window.answered() { if start.elapsed() >= Delta::from_millis(1000) { return Err(ETIMEDOUT); } fsleep(Delta::from_millis(1)); } + step = "RTKit boot"; peer.as_mut().boot()?; booted = true; peer.as_mut().start_endpoint(EP_FIRMWARE)?; peer.as_mut().start_endpoint(EP_DOORBELL)?; if !window.intact() { return Err(EIO); } + step = "initialization"; peer.as_mut().send_message(EP_FIRMWARE, gpu::init_message(root.gpu_va().get()))?; - // Let initialization settle before the first control record. - let _ = wait(&root, 1000, || Ok(false)); + // The firmware sets status +0x14 when it has initialized; the first control record + // waits for it. + wait(&root, 2000, || root.initialized())?; + step = "keep-powered policy"; set_idle_policy(&root, &mut peer, false)?; - // Command-handler installation completes during powered initialization. - let _ = wait(&root, 500, || Ok(root.command_service()? == (2, 0))); + // Powered initialization installs the command handlers and then clears the + // installation request the root set (+0x4c24). + step = "command-handler installation"; + wait(&root, 500, || root.commands_installed())?; + step = "boot job"; root.publish_boot_job(resources.operating_point())?; peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; wait(&root, 3000, || root.boot_job_complete()) })(); if let Err(e) = result { - dev_err!(dev, "GPU firmware 27.2 did not start: {:?}\n", e); + dev_err!(dev, "GPU firmware 27.2 did not start: {}: {:?}\n", step, e); halt_unowned(dev, peer, root, asc, booted); core::mem::forget(window); core::mem::forget(pool); @@ -229,7 +292,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta } // The firmware keeps using the window until it is stopped; it stays for the life of the boot. core::mem::forget(window); - let backend = Backend::start(&drm, dev, peer, root, graph, pool, asc, cfg)?; + let backend = Backend::start(&drm, dev, notify, peer, root, graph, pool, asc, cfg)?; Ok(Started { backend, drm, binding, resources }) } @@ -256,6 +319,12 @@ struct State { waiting_unlink: bool, /// Publications and retirements counted on the queue's position block. published: u64, + /// Completion stamps seen before the retired position they precede. + late: u64, + /// Pool slots holding a published command, one bit each. + busy: u64, + /// Free slots passed over because the firmware still held them. + skipped: u64, retired_total: u64, retired_raw: u32, capacity: u32, @@ -270,64 +339,56 @@ pub(crate) struct Runtime { dev: ARef, graph: Arc, healthy: AtomicBool, - /// Poll work queued or running; `stop` waits for zero so no work outlives the module. - queued: AtomicU32, + notify: Arc, + /// Runs the service; only `Notify::wake` queues on it, and `stop` drains it. + queue: OwnedQueue, #[pin] state: Mutex>, + /// Signalled when no work is pending or published, or the runtime fails. #[pin] - poll: DelayedWork, + idle: CondVar, + #[pin] + work: Work, } -impl_has_delayed_work! { - impl HasDelayedWork for Runtime { self.poll } +impl_has_work! { + impl HasWork for Runtime { self.work } } impl WorkItem for Runtime { type Pointer = Arc; fn run(this: Arc) { - let busy = this.service(); - if this.healthy.load(Ordering::Acquire) { - this.schedule(if busy { 1 } else { IDLE_POLL_MS }); - } - this.queued.fetch_sub(1, Ordering::AcqRel); + this.service(); } } #[pinned_drop] impl PinnedDrop for Runtime { fn drop(self: Pin<&mut Self>) { - // The poll work holds a reference while scheduled, so this runs only once the - // runtime is idle; stop the firmware first if no one has. + // `Notify` holds a reference until `stop`, so this runs only after it, or for a + // runtime that never took over the firmware. if self.state.lock().is_some() { self.stop(); } } } impl Runtime { - fn schedule(self: &Arc, ms: u64) { - if !self.healthy() { return; } - self.queued.fetch_add(1, Ordering::AcqRel); - if workqueue::system_highpri() - .enqueue_delayed::, 0>(self.clone(), msecs_to_jiffies(ms as u32)).is_err() { - // Already queued: that run accounts for itself. - self.queued.fetch_sub(1, Ordering::AcqRel); - } - } - pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } - /// Queues a packet; the poll work publishes and retires it. + /// Runs the service once more: the DRM scheduler's job timeout calls this, so a command the + /// firmware never completes still reaches the command timeout. + pub(crate) fn wake(&self) { self.notify.wake(); } + + /// Queues a packet and publishes what the pool has room for; the firmware's completion + /// notifications run the service, which retires it and publishes the rest. pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { if !self.healthy() { return Err(EIO); } if packet.commands.is_empty() { return Err(ENOTSUPP); } - { - let mut guard = self.state.lock(); - let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; - state.pending.push((packet, 0), GFP_KERNEL)?; - self.pump(state); - } - self.schedule(1); + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); Ok(()) } @@ -346,6 +407,7 @@ impl Runtime { fn fail_all(&self, state: &mut State, error: Error) { self.healthy.store(false, Ordering::Release); + self.idle.notify_all(); for (packet, _) in state.pending.drain(..) { packet.release_guard(); packet.finish(Err(error)); @@ -360,19 +422,30 @@ impl Runtime { /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { - // A slot is reused only once the firmware has unlinked it from its tracking list. - match state.pool.registered(state.next_slot) { - Ok(false) => {} - Ok(true) => { - if !state.waiting_unlink { - // Wake the firmware's service once so its retirement scan runs. - state.waiting_unlink = true; - let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); - } - return; + // A slot is reused only once the firmware has unlinked it from its tracking list + // (+0x94). It normally has by the time the pool comes round to it, but the firmware + // can link a retired slot again and keep it; take the next free slot instead. + let mut chosen = None; + for k in 0..POOL_SLOTS { + let slot = (state.next_slot + k) % POOL_SLOTS; + if state.busy & (1 << slot) != 0 { continue; } + match state.pool.registered(slot) { + Ok(false) => { chosen = Some(slot); break; } + Ok(true) => state.skipped += 1, + Err(e) => { self.fail_all(state, e); return; } } - Err(e) => { self.fail_all(state, e); return; } } + let Some(slot) = chosen else { + if !state.waiting_unlink { + // Every free slot is held: wake the firmware's service once so its + // retirement scan runs. The scan sends nothing; the next notification, + // submission or scheduler timeout retries. + state.waiting_unlink = true; + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); + } + return; + }; + state.next_slot = slot; state.waiting_unlink = false; let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); let Command::Compute(control) = packet.commands[index] else { @@ -405,6 +478,7 @@ impl Runtime { state.last = stamp; state.sequence += 1; let slot = state.next_slot; + state.busy |= 1 << slot; state.published += 1; let ordinal = state.published; state.next_slot = (state.next_slot + 1) % POOL_SLOTS; @@ -430,26 +504,47 @@ impl Runtime { } } - /// Retires completed commands, publishes more and keeps the firmware's rings drained. - /// Returns whether work remains. - fn service(&self) -> bool { + /// Reads the queue's retired position into `retired_total`. + fn advance(&self, state: &mut State) -> Result { + let (_, raw) = state.root.progress()?; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + Ok(()) + } + + /// Retires completed commands, publishes more and consumes the firmware's rings. + fn service(&self) { let mut guard = self.state.lock(); - let Some(state) = Option::as_mut(&mut *guard) else { return false; }; + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + self.service_locked(state); + if state.inflight.is_empty() && state.pending.is_empty() { self.idle.notify_all(); } + } + + fn service_locked(&self, state: &mut State) { let _ = state.root.drain(); if state.peer.is_crashed() { dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", state.pending.len(), state.inflight.len()); self.fail_all(state, EIO); - return false; + return; } - let raw = match state.root.progress() { - Ok((_, raw)) => raw, - Err(e) => { self.fail_all(state, e); return false; } - }; - if state.capacity != 0 && raw < state.capacity { - let delta = (raw + state.capacity - state.retired_raw) % state.capacity; - state.retired_total += u64::from(delta); - state.retired_raw = raw; + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + // The completion stamp is written before the firmware's post-processing advances the + // retired position, and that advance sends no message. If the front command's stamp + // is there but its position is not, the advance is imminent: wait for it, bounded, + // rather than for a notification that does not come. + if let Some((ordinal, stamp)) = state.inflight.first().map(|f| (f.ordinal, f.stamp)) { + if state.retired_total < ordinal && state.root.queue().1 >= stamp { + state.late += 1; + let start = Instant::::now(); + while state.retired_total < ordinal && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { + fsleep(Delta::from_micros(20)); + if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } + } + } } while !state.inflight.is_empty() { let front = &state.inflight[0]; @@ -458,6 +553,7 @@ impl Runtime { if let Err(e) = state.pool.retire(done.slot) { dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); } + state.busy &= !(1 << done.slot); state.retired += 1; if done.last { done.packet.retired(); @@ -469,30 +565,32 @@ impl Runtime { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); self.fail_all(state, ETIMEDOUT); - return false; + return; } break; } - if self.healthy() { self.pump(state); } - !state.inflight.is_empty() || !state.pending.is_empty() + if !self.healthy() { return; } + self.pump(state); } /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC /// with every mapping still in place (RTKit power-off if the firmware does not stop). pub(crate) fn stop(&self) { - let start = Instant::::now(); - while start.elapsed() < Delta::from_millis(2000) { - if !self.service() { break; } - fsleep(Delta::from_millis(1)); + // Let published work retire; the service signals `idle` when nothing is left. + { + let mut guard = self.state.lock(); + let start = Instant::::now(); + while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { + let Some(state) = guard.as_ref() else { break; }; + if state.inflight.is_empty() && state.pending.is_empty() { break; } + let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); + } } self.healthy.store(false, Ordering::Release); - // No poll work may remain queued or running once this returns. - let start = Instant::::now(); - while self.queued.load(Ordering::Acquire) != 0 && start.elapsed() < Delta::from_millis(2000) { - fsleep(Delta::from_millis(5)); - } - // Let a run that just accounted for itself return out of this module. - fsleep(Delta::from_millis(20)); + // Nothing queues service work after the detach, and none is queued or running once the + // drain returns, so no work outlives the module. + drop(self.notify.detach()); + self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; self.fail_all(&mut state, ENODEV); @@ -505,8 +603,9 @@ impl Runtime { kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) }); state.asc.halt(); - dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={}\n", - allowed, running, forced, state.submitted, state.retired); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={}\n", + allowed, running, forced, state.submitted, state.retired, + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped); if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } @@ -537,6 +636,7 @@ impl Backend { fn start( drm: &crate::driver::AsahiDrmDevice, dev: &device::Device, + notify: Arc, peer: Peer, root: crate::fw::types::GpuObject, graph: Arc, @@ -548,14 +648,18 @@ impl Backend { // state. Every failure after the state is moved in goes through Runtime::stop, which // halts the firmware and keeps all of its memory. let runtime_graph = graph.clone(); - let runtime = match Arc::pin_init(try_pin_init!(Runtime { - dev: dev.into(), - graph: runtime_graph, - healthy: AtomicBool::new(true), - queued: AtomicU32::new(0), - state <- new_mutex!(None, "g14_v27_2::Runtime::state"), - poll <- new_delayed_work!("g14_v27_2::Runtime::poll"), - }), GFP_KERNEL) { + let runtime_notify = notify.clone(); + let runtime = match OwnedQueue::new_ordered(c"asahi-g14-v27-2").and_then(|queue| + Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + notify: runtime_notify, + queue, + state <- new_mutex!(None, "g14_v27_2::Runtime::state"), + idle <- new_condvar!("g14_v27_2::Runtime::idle"), + work <- new_work!("g14_v27_2::Runtime::work"), + }), GFP_KERNEL)) { Ok(runtime) => runtime, Err(e) => { halt_unowned(dev, peer, root, asc, true); @@ -585,6 +689,9 @@ impl Backend { next_slot: 0, waiting_unlink: false, published: 0, + late: 0, + busy: 0, + skipped: 0, retired_total: 0, retired_raw: head, capacity, @@ -593,7 +700,10 @@ impl Backend { submitted: 0, retired: 0, }); - runtime.schedule(IDLE_POLL_MS); + // From here the firmware's messages run the service; one run consumes anything it + // published before. + notify.attach(runtime.clone()); + notify.wake(); // One run queue per DRM scheduler priority (the front end maps queue priorities 0-3). let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, POOL_SLOTS as u32 - 1, 0, 10000, c"asahi_g14_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 0ee4c1ec07ed4f..1690ff60342bea 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -450,7 +450,7 @@ impl RootV27_2 { if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate || self.idle_progress()? != [1; 3] || self.idle_acknowledgement()? != Self::word(&self.globals, 0xe40)? - || self.command_service()?.1 != 0 { + || !self.commands_installed()? { return Err(EAGAIN); } let producer = self.channels[2 * SUBMISSION_RING].shared_index(0x20)?; @@ -500,15 +500,21 @@ impl RootV27_2 { consume(&self.channels[2 * TRACE_RING], 0, TRACE_RECORDS) } + /// Shared status +0x14: the firmware sets it to 1 once it has initialized. + pub(crate) fn initialized(&self) -> Result { + Ok(Self::word(&self.status, 0x14)? == 1) + } + /// Shared status +0x10: nonzero while the firmware reports itself running. pub(crate) fn firmware_running(&self) -> Result { Self::word(&self.status, 0x10) } - /// Command-service state: (powered stage, pending installation request). - /// Engine entries may be published only at (2, 0). - pub(crate) fn command_service(&self) -> Result<(u32, u32)> { - Ok((Self::word(&self.control, 0x4c00)?, Self::word(&self.control, 0x4c24)?)) + /// Whether the firmware has installed its command handlers: it clears the installation + /// request (+0x4c24), which the root sets, once powered initialization has copied them. + /// Engine entries may be published only after that. + pub(crate) fn commands_installed(&self) -> Result { + Ok(Self::word(&self.control, 0x4c24)? == 0) } pub(crate) fn idle_acknowledgement(&self) -> Result { diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 70116b7116622d..b8a377264be8fa 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -151,6 +151,8 @@ impl sched::JobImpl for Job { Sink::M3(shared)=>shared.clone(), Sink::G14V27_2(runtime)=>{ // The runtime's own command timeout fails a hung GPU; a healthy one is late. + // Run its service once, so a hang is found without a notification. + runtime.wake(); if runtime.healthy() {return sched::Status::NoHang;} runtime.withdraw(&job.packet); job.packet.finish(Err(EIO)); From 660936a3b0509ca334fe6dded99a48cb0c33e39c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 12:54:38 -0500 Subject: [PATCH 0267/1514] drm/asahi: advance a G14 27.2 pool slot's cursor only after the firmware records it On phellos (J413, firmware 27.2) the 300-dispatch compute check stalled at the first pool wrap on most boots: every slot was still linked in the queue's tracking list (+0x94), so no slot could be reused and the 49th command timed out (submitted=48 completed=48 skipped-slots=480). Dumps of the tracking slots at the wrap show why. The firmware records the value a slot's retirement cursor must reach (+0xc, 1 for every use) in its post-processing, which can run after the queue's retired position advances. The service retires a command as soon as the position moves, so it usually read +0xc as 0 and wrote 0 to the cursor. The firmware then never unlinked the slot. In the boots that passed, the read happened to land after the record for one slot; only that slot was ever unlinked, and the pool reused it for the rest of the run (skipped-slots near 47 per command). The polled runtime before the notification rework retired 1 to 20 ms later and usually missed the window, which is why it mostly passed. Retirement now advances the cursor only once +0xc is recorded. A slot retired before that is kept in a pending set, and its cursor is advanced when the service next runs: on the firmware's next notification, submission or scheduler timeout. That is no fixed wait. The stop line counts the deferred cursors. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 47 ++++++++++++++++++++++++++---- drivers/gpu/drm/asahi/gpu/v27_2.rs | 11 +++++-- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 91e327b361c81c..533ddf48dd86c5 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -325,6 +325,11 @@ struct State { busy: u64, /// Free slots passed over because the firmware still held them. skipped: u64, + /// Retired slots whose cursor is not advanced yet: the firmware had not recorded the + /// value to advance it to (`CommandPool::retire`). One bit each. + unacked: u64, + /// Retirements whose cursor had to wait for the firmware's record. + deferred: u64, retired_total: u64, retired_raw: u32, capacity: u32, @@ -419,12 +424,31 @@ impl Runtime { } } + /// Advances the cursors of retired slots that were waiting for the firmware's record. + fn acknowledge(&self, state: &mut State) { + let mut pending = state.unacked; + while pending != 0 { + let slot = pending.trailing_zeros() as usize; + pending &= pending - 1; + match state.pool.retire(slot) { + Ok(false) => {} + Ok(true) => state.unacked &= !(1 << slot), + Err(e) => { + dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + state.unacked &= !(1 << slot); + } + } + } + } + /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { + self.acknowledge(state); while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { // A slot is reused only once the firmware has unlinked it from its tracking list - // (+0x94). It normally has by the time the pool comes round to it, but the firmware - // can link a retired slot again and keep it; take the next free slot instead. + // (+0x94), which its retirement scan does after the slot's cursor is advanced. + // Slots retire in order but are unlinked whenever the scan runs; take the next + // free slot that is unlinked. let mut chosen = None; for k in 0..POOL_SLOTS { let slot = (state.next_slot + k) % POOL_SLOTS; @@ -447,6 +471,8 @@ impl Runtime { }; state.next_slot = slot; state.waiting_unlink = false; + // Unlinked already: its cursor needs no further advance. + state.unacked &= !(1 << slot); let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); let Command::Compute(control) = packet.commands[index] else { // Queues of this backend accept only compute commands (Queue::submit). @@ -550,8 +576,15 @@ impl Runtime { let front = &state.inflight[0]; if state.retired_total >= front.ordinal { if let Ok(done) = state.inflight.remove(0) { - if let Err(e) = state.pool.retire(done.slot) { - dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e); + match state.pool.retire(done.slot) { + Ok(true) => {} + // The firmware has not recorded the cursor value yet; `acknowledge` + // retries on its next notification. + Ok(false) => { + state.unacked |= 1 << done.slot; + state.deferred += 1; + } + Err(e) => dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e), } state.busy &= !(1 << done.slot); state.retired += 1; @@ -603,9 +636,9 @@ impl Runtime { kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) }); state.asc.halt(); - dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={}\n", + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", allowed, running, forced, state.submitted, state.retired, - self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped); + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped, state.deferred); if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } @@ -692,6 +725,8 @@ impl Backend { late: 0, busy: 0, skipped: 0, + unacked: 0, + deferred: 0, retired_total: 0, retired_raw: head, capacity, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1690ff60342bea..8db6c0ded49fde 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -331,15 +331,22 @@ impl CommandPool { /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. - pub(crate) fn retire(&self, i: usize) -> Result { + /// + /// The firmware records +0xc in its post-processing, which can run after the queue's + /// retired position has advanced. Until then +0xc reads 0 (the slot is cleared for each + /// use) and nothing is written: the cursor would stay behind and the firmware would keep + /// the slot linked for good. Returns whether the cursor was advanced; the caller retries a + /// slot that returned `false` on the firmware's next notification. + pub(crate) fn retire(&self, i: usize) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); crate::pgtable::poc_barrier(); let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + if expected == 0 { return Ok(false); } self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); crate::pgtable::poc_barrier(); - Ok(()) + Ok(true) } /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). From 4c4f313592fa57186dba793752de61c1b41edda0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 16:40:47 -0500 Subject: [PATCH 0268/1514] drm/asahi: let the G14 firmware-27.2 GPU through suspend-to-idle With the G14 firmware-27.2 runtime bound, a suspend-to-idle on phellos (J413) left the GPU unusable. At the wake the GFX power domain did not come back ("PS gfx: Failed to reach power state 0xf"), and the next GPU access, a compute dispatch or an unbind, hung a CPU. The driver had no callback for that sleep. Linux gated the domain under the running firmware, as on J713 before apple,sleep-retained. The domain is now kept through the sleep by the device tree (apple,sleep-retained on the J413 firmware-27 GFX domain). Before suspend-to-idle, the runtime holds new publications and lets published commands retire, so the sleep starts with nothing in flight; after the wake it publishes what was held. The firmware keeps running with its keep-powered policy. The ASC, the root and every mapping stay as they are. Its own power-off handshake (idle policy allow-off before the sleep, keep-powered after it) was tried and not kept: the firmware crashed in the wake that followed it. The sleep is refused (EBUSY) if published work does not retire within the stop drain time. A sleep that powers the SoC down is still refused: the firmware would be lost, and this runtime has no cold restart. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/driver.rs | 22 +++++++++++-- drivers/gpu/drm/asahi/g14_v27_2.rs | 52 ++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 1526566cf68a56..ae25ebbd5255b3 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -270,12 +270,23 @@ unsafe fn sleep_data<'a>(dev: *mut bindings::device) -> &'a AsahiPlatformDriverD /// Runs before any device suspends, so the GPU goes first and work still in flight can finish. unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_int { + // SAFETY: Called by the PM core. + let data = unsafe { sleep_data(dev) }; + // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in + // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that + // is refused. + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = data.g14_v27_2.as_ref() { + // SAFETY: Reads a global flag word. + if unsafe { bindings::pm_suspend_via_firmware() } { + return EBUSY.to_errno(); + } + return kernel::error::from_result(|| backend.sleep_prepare().map(|_| 0)); + } // SAFETY: Reads a global flag word. if !unsafe { bindings::pm_suspend_via_firmware() } { return 0; } - // SAFETY: Called by the PM core. - let data = unsafe { sleep_data(dev) }; match data.g17.as_ref() { Some(gpu) => kernel::error::from_result(|| gpu.sleep_prepare().map(|_| 0)), None => EBUSY.to_errno(), @@ -285,7 +296,12 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i /// Runs after every device resumed. Does nothing unless [`sleep_prepare`] stopped the firmware. unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. - if let Some(gpu) = unsafe { sleep_data(dev) }.g17.as_ref() { + let data = unsafe { sleep_data(dev) }; + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + if let Some(backend) = data.g14_v27_2.as_ref() { + backend.sleep_complete(); + } + if let Some(gpu) = data.g17.as_ref() { gpu.sleep_complete(); } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 533ddf48dd86c5..773693a0cdfcbc 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -344,6 +344,9 @@ pub(crate) struct Runtime { dev: ARef, graph: Arc, healthy: AtomicBool, + /// Set between [`Runtime::sleep_prepare`] and [`Runtime::sleep_complete`]: nothing is + /// published across a system sleep. + asleep: AtomicBool, notify: Arc, /// Runs the service; only `Notify::wake` queues on it, and `stop` drains it. queue: OwnedQueue, @@ -444,6 +447,7 @@ impl Runtime { /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { self.acknowledge(state); + if self.asleep.load(Ordering::Acquire) { return; } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { // A slot is reused only once the firmware has unlinked it from its tracking list // (+0x94), which its retirement scan does after the slot's cursor is advanced. @@ -606,6 +610,51 @@ impl Runtime { self.pump(state); } + /// Before a suspend-to-idle: holds new publications and lets published work retire, so the + /// sleep starts with nothing in flight. The firmware keeps running with its keep-powered + /// policy: its GPU power domain is kept through the sleep (`apple,sleep-retained`), and the + /// ASC, its memory and the root stay as they are. Refuses the sleep (EBUSY) if published work + /// does not retire within the stop drain time. + /// + /// The firmware's own power-off handshake (idle policy allow-off, then keep-powered again + /// after the wake) is not used: on phellos the firmware crashed in the wake that followed it. + pub(crate) fn sleep_prepare(&self) -> Result { + let mut guard = self.state.lock(); + if !self.healthy() || guard.is_none() { return Ok(()); } + // Hold publications first, then let what is published retire. User space is frozen by + // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. + self.asleep.store(true, Ordering::Release); + let start = Instant::::now(); + loop { + let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; + if !self.healthy() { return Ok(()); } + if state.inflight.is_empty() { + dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + return Ok(()); + } + if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) { + dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len()); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(EBUSY); + } + // The service retires on notifications; `idle` is signalled only when nothing at all + // is left, so look again every 50 ms. + let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(50)); + } + } + + /// After the sleep: publishes the work held during it. + pub(crate) fn sleep_complete(&self) { + let mut guard = self.state.lock(); + if !self.asleep.swap(false, Ordering::AcqRel) { return; } + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + dev_info!(self.dev, "GPU released after sleep: running={:?} pending={}\n", + state.root.firmware_running(), state.pending.len()); + if self.healthy() { self.pump(state); } + } + /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC /// with every mapping still in place (RTKit power-off if the firmware does not stop). pub(crate) fn stop(&self) { @@ -687,6 +736,7 @@ impl Backend { dev: dev.into(), graph: runtime_graph, healthy: AtomicBool::new(true), + asleep: AtomicBool::new(false), notify: runtime_notify, queue, state <- new_mutex!(None, "g14_v27_2::Runtime::state"), @@ -757,6 +807,8 @@ impl Backend { } pub(crate) fn stop(&self) { self.runtime.stop(); } + pub(crate) fn sleep_prepare(&self) -> Result { self.runtime.sleep_prepare() } + pub(crate) fn sleep_complete(&self) { self.runtime.sleep_complete() } } impl Drop for Backend { From 3d8b62c366887ef731b43962f1133672a85e2697 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:28:05 -0500 Subject: [PATCH 0269/1514] drm/asahi: build the G14 firmware-27.2 path without the M3 runtime The G14 firmware-27.2 runtime reuses the 26.x submission front end (m3_submit, agx_uapi and their helpers), so it was built only with CONFIG_DRM_ASAHI_M3_T8122. Give it its own option, DRM_ASAHI_G14_V27_2 (default y), and build the shared front end when either user is enabled: - m3/mod.rs: agx_uapi, agx_compute, agx_attachments, agx_memory and m3_submit build with DRM_ASAHI_M3_T8122 or DRM_ASAHI_G14_V27_2. - m3_submit.rs: the M3 sink, queue constructor, render validation, CDM launch check, timeout handling and fence-timing profile build only with the M3 runtime; without it a render command gets EINVAL. task_comm() moves here from m3_client.rs, which now calls it here. - The G14 path's own code is gated on the new option. Like the M3 runtime, the option depends on DRM_ASAHI_G15: the firmware's UAT is adopted through that backend's handoff helpers (Uat::new_adopted, the G15 UAT table cleaning). Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/Kconfig | 12 +++++ drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/driver.rs | 30 +++++------ drivers/gpu/drm/asahi/event.rs | 4 +- drivers/gpu/drm/asahi/gpu.rs | 10 ++-- drivers/gpu/drm/asahi/hw/mod.rs | 4 +- drivers/gpu/drm/asahi/hw/t8112.rs | 6 +-- drivers/gpu/drm/asahi/m3/m3_client.rs | 15 +----- drivers/gpu/drm/asahi/m3/m3_submit.rs | 72 +++++++++++++++++++++------ drivers/gpu/drm/asahi/m3/mod.rs | 15 +++--- drivers/gpu/drm/asahi/mmu.rs | 6 +-- drivers/gpu/drm/asahi/object.rs | 2 +- drivers/gpu/drm/asahi/regs.rs | 2 +- 13 files changed, 110 insertions(+), 70 deletions(-) diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825f..c4402190207791 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -95,6 +95,18 @@ config DRM_ASAHI_M3_T8122 boards and firmware do not gain automatic admission. Other GPUs are not affected. +config DRM_ASAHI_G14_V27_2 + bool "Apple M2 (G14G) on GPU firmware 27.2, compute only" + depends on DRM_ASAHI + # The firmware's UAT is adopted through the G15 backend's handoff helpers. + depends on DRM_ASAHI_G15 + default y + help + Start an M2 GPU (G14G) whose boot loader reports GPU firmware + 27.2, and register a compute-only DRM device on it. Clients use + the 26.x submission interface; render commands are refused. + Other GPUs and firmware versions are not affected. + config DRM_ASAHI_G15 bool "Apple M3 Pro/Max (G15) support" depends on DRM_ASAHI diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 5f180203f8369c..e0de39368342d6 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,7 +27,7 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod g14_v27_2; mod hw; mod initdata; diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index ae25ebbd5255b3..03ffba4433a865 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -54,7 +54,7 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { pub(crate) g16: Option>, m3: Option, /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. @@ -275,7 +275,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that // is refused. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { // SAFETY: Reads a global flag word. if unsafe { bindings::pm_suspend_via_firmware() } { @@ -297,7 +297,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. let data = unsafe { sleep_data(dev) }; - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { backend.sleep_complete(); } @@ -356,7 +356,7 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = this.g14_v27_2.as_ref() { backend.stop(); } @@ -396,9 +396,9 @@ impl platform::Driver for AsahiPlatformDriver { let version: Option> = pdev.as_ref().fwnode().ok_or(EIO)? .property_read_array_vec(c"apple,firmware-version", 3)?.optional(); if version.as_deref() == Some(&[27, 2, 0]) { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg); - #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] + #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] return Err(ENODEV); } } @@ -484,7 +484,7 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -499,7 +499,7 @@ impl platform::Driver for AsahiPlatformDriver { impl AsahiPlatformDriver { /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, @@ -559,7 +559,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -603,7 +603,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), @@ -681,7 +681,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -730,7 +730,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -771,7 +771,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, g16: Some(gpu), raw_dev, @@ -829,7 +829,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -864,7 +864,7 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = self.g14_v27_2.as_ref() { backend.stop(); } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index a993bca69f5072..dbea26792b6c0c 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,7 +54,7 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn raw(self) -> u32 { self.0 } @@ -205,7 +205,7 @@ impl EventManager { } /// Reserve the normal stamp pair for a kernel queue that polls its own completion. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn try_get_polled(&self) -> Result { self.alloc.try_get(None) } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 2166a7e3dce1ec..e9b715aeca9801 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -112,9 +112,9 @@ pub(crate) const fn init_message(address: u64) -> u64 { } /// The G14 firmware-27.2 root and the records only it uses. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod v27_2; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use v27_2::*; const RX_WORK_PENDING: u32 = 1 << 0; @@ -140,7 +140,7 @@ const DOORBELL_DEVCTRL: u64 = 0x11; const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; /// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator /// stays below it in that profile. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; @@ -200,7 +200,7 @@ pub(crate) enum GraphProfile { Native, /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register /// mappings, and the private range ends below that firmware's timestamp aperture. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] G14V27_2, } @@ -712,7 +712,7 @@ impl GpuManager::ver { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; let private_end = match profile { GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, }; diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index 2fd17c298d68d4..934c52380c43db 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -123,7 +123,7 @@ pub(crate) struct PowerZone { } /// Base of a window in the firmware 27.2 register table. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) enum RegisterBaseV27_2 { /// A fixed physical address. @@ -133,7 +133,7 @@ pub(crate) enum RegisterBaseV27_2 { } /// One record of the firmware 27.2 register table: 60 slots, each naming one window. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) struct RegisterV27_2 { pub(crate) slot: usize, diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index 1879be7f8ceade..d22238d90247b1 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -105,7 +105,7 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_size: None, }; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { RegisterV27_2 { slot, base, size, relative, install } } @@ -113,7 +113,7 @@ const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, ins /// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except /// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped /// apart from the others. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { use RegisterBaseV27_2::{Physical, Sgx}; &[ @@ -136,7 +136,7 @@ pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { }; /// Slots of the 27.2 register table whose stock mode is read-write. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const WRITABLE_V27_2: u64 = { let mut mask = 0u64; let mut slot = 0; diff --git a/drivers/gpu/drm/asahi/m3/m3_client.rs b/drivers/gpu/drm/asahi/m3/m3_client.rs index c1a07d61120d13..7d9169fe1ecc0f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_client.rs +++ b/drivers/gpu/drm/asahi/m3/m3_client.rs @@ -63,7 +63,7 @@ pub(crate) fn admit_vm_for( let refusals = REFUSALS.fetch_add(1, Ordering::Relaxed).saturating_add(1); if refusals <= REFUSALS_LOGGED { let task = kernel::current!(); - let comm = task_comm(task); + let comm = super::m3_submit::task_comm(task); let len = comm.iter().position(|&b| b == 0).unwrap_or(comm.len()); let name = core::str::from_utf8(&comm[..len]).unwrap_or("?"); let last = if refusals == REFUSALS_LOGGED { @@ -87,19 +87,6 @@ pub(crate) fn admit_vm_for( } } -/// The name of `task`, for log lines only. -pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { - let mut name = [0u8; 16]; - // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with - // volatile loads because a concurrent rename may change it; a torn name is only printed. - unsafe { - let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); - for (i, byte) in name.iter_mut().enumerate() { - *byte = comm.add(i).read_volatile(); - } - } - name -} /// Bytes at the start of a compute control stream whose launch records are checked. const LAUNCH_WINDOW: usize = 4096; diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index b8a377264be8fa..df0a26e4babc9d 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; -use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::{file,m3::agx_uapi,mmu,queue}; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +use crate::m3::m3_drm::Shared; use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] @@ -59,7 +61,12 @@ pub(crate) struct Packet { } /// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. #[derive(Clone)] -pub(crate) enum Sink { M3(Shared), G14V27_2(Arc) } +pub(crate) enum Sink { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + M3(Shared), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + G14V27_2(Arc), +} /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -68,8 +75,7 @@ impl Owner { fn current()->Self { let task=kernel::current!(); let leader=task.group_leader(); - Self {pid:leader.pid(),process:crate::m3::m3_client::task_comm(leader), - thread:crate::m3::m3_client::task_comm(task)} + Self {pid:leader.pid(),process:task_comm(leader),thread:task_comm(task)} } fn name(comm:&[u8;16])->&str { let len=comm.iter().position(|&b|b==0).unwrap_or(comm.len()); @@ -78,6 +84,19 @@ impl Owner { pub(crate) fn process(&self)->&str {Self::name(&self.process)} pub(crate) fn thread(&self)->&str {Self::name(&self.thread)} } +/// The name of `task`, for log lines only. +pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { + let mut name = [0u8; 16]; + // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with + // volatile loads because a concurrent rename may change it; a torn name is only printed. + unsafe { + let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); + for (i, byte) in name.iter_mut().enumerate() { + *byte = comm.add(i).read_volatile(); + } + } + name +} impl Packet { pub(crate) fn profile_id(&self)->usize {self as *const Self as usize} pub(crate) fn timestamp_addresses(&self,index:usize)->[u64;2] { @@ -113,9 +132,12 @@ impl Packet { // nonzero: GEM closes otherwise accumulate across completed frames. // Signalling an error is not retirement. crate::m3::agx_memory::publish(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let profile=crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let before=if profile {crate::m3::m3_runtime::physical_counter()} else {0}; self.completion.signal(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if profile { let after=crate::m3::m3_runtime::physical_counter(); let status=match result {Ok(())=>0,Err(e)=>e.to_errno()}; @@ -136,7 +158,9 @@ impl sched::JobImpl for Job { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. let submitted=match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), }; if let Err(e)=submitted { @@ -147,8 +171,10 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { - let shared=match &job.shared { - Sink::M3(shared)=>shared.clone(), + match job.shared.clone() { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>Self::timed_out_m3(shared,job), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>{ // The runtime's own command timeout fails a hung GPU; a healthy one is late. // Run its service once, so a hang is found without a notification. @@ -156,9 +182,23 @@ impl sched::JobImpl for Job { if runtime.healthy() {return sched::Status::NoHang;} runtime.withdraw(&job.packet); job.packet.finish(Err(EIO)); - return sched::Status::NoDevice; + sched::Status::NoDevice } - }; + } + } + fn cancel(job:&mut Self) { + match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } + job.packet.finish(Err(ECANCELED)); + } +} +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +impl Job { + fn timed_out_m3(shared:Shared,job:&mut JobTimeout)->sched::Status { // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} @@ -180,13 +220,6 @@ impl sched::JobImpl for Job { job.packet.finish(Err(EIO)); sched::Status::NoDevice } - fn cancel(job:&mut Self) { - match &job.shared { - Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} - Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), - } - job.packet.finish(Err(ECANCELED)); - } } struct AddressSpace<'a>(&'a mmu::Vm); impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { @@ -210,6 +243,7 @@ pub(crate) struct Queue { urgency:u8, } impl Queue { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] pub(crate) fn new(shared:Shared,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, early_tiling:bool, wide_visibility:bool)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -222,6 +256,7 @@ impl Queue { early_tiling,wide_visibility,urgency,preempt_alloc:None}) } /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, ualloc_priv:Arc>,preempt_bytes:usize)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -239,8 +274,11 @@ impl queue::Queue for Queue { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { + // Only the M3 runtime renders; the G14 firmware-27.2 runtime is compute-only. + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + if let agx_uapi::ParsedHardwareCommand::Render{..}=command {return Err(EINVAL);} + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - // The G14 firmware-27.2 runtime is compute-only. if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); @@ -279,6 +317,7 @@ impl queue::Queue for Queue { EINVAL })?; // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if self.preempt_alloc.is_none() { crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; } @@ -325,6 +364,7 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) Ok(out) } +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, early_tiling: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index cb64aa8f1ecbcc..eec633d1301991 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -70,17 +70,18 @@ pub(crate) fn t8122_admitted(pdev: &platform::Device>) -> Result<&'stat } // The T8122 runtime, ported from the 7.1.12 release-20 kernel (c46d7dcdb871). -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +// The 26.x submission front end, shared with the G14 firmware-27.2 runtime. +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_attachments; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_compute; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; @@ -124,7 +125,7 @@ mod m3_resources; mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; @@ -209,7 +210,7 @@ pub(crate) mod m3_mmio_26; mod m3_power_26; pub(crate) mod m3_channel_format; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index a4fd3c7a7a594c..0ff2a803f88a4e 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4523,13 +4523,13 @@ mod execution_context_tests { } /// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; /// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its /// kernel window into the firmware's shared second-level table and names its own trees in /// TTBAT context 0 before the ASC starts. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) struct FirmwareWindow { handoff: UatRegion, ttbs: UatRegion, @@ -4540,7 +4540,7 @@ pub(crate) struct FirmwareWindow { pa_mask: u64, } -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl FirmwareWindow { /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared /// table and context 0 are empty. diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index e3ce17cb7cb7ee..ef7027ff1a6363 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -697,7 +697,7 @@ impl> GpuArray { } } -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl> GpuArray { /// Aligned index in a shared firmware ring, accessed without borrowing its payload. pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 658c98de1e77ac..7e40d4b137ba9f 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -351,7 +351,7 @@ impl Resources<'_> { /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in /// bit 4. Sampled while the firmware holds the GPU powered. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn operating_point(&self) -> u32 { self.sgx_read32::<0xd01000>() } From 3515e7d7d0300f1973924911047e8b1a24b5d618 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 15:32:27 -0500 Subject: [PATCH 0270/1514] drm/asahi: report the G14 firmware-27.2 device as compute-only The G14 firmware-27.2 runtime refuses render commands, but nothing in GET_PARAMS says so. Graphics userspace therefore takes the device for GL: on phellos (J413) with the GPU published, kmsro picked the aurora render node for the internal panel, and the greeter's Hyprland and sddm-greeter-qt aborted after their first renders failed with EINVAL. Add DRM_ASAHI_FEATURE_COMPUTE_ONLY (bit 41; bits 39 and 40 are claimed by open PRs #2059 and #2523) and set it on that runtime. It is a property of the device, not of a board or chip list: Mesa can decline to create a graphics screen or a graphics queue on a device that reports it, and fall back to software rendering, while compute keeps working. Kernels without the bit keep their current behaviour. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 6 +++++- include/uapi/drm/asahi_drm.h | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 773693a0cdfcbc..1f6b8a0359b35c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -6,7 +6,8 @@ //! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the //! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients //! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the -//! 27.2 layout and published, in order, on the root's queue. Render commands are refused. +//! 27.2 layout and published, in order, on the root's queue. Render commands are refused, and the device +//! reports `DRM_ASAHI_FEATURE_COMPUTE_ONLY`. //! //! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after //! publishing records on its event, statistics and log rings: each one runs the service, which @@ -830,9 +831,12 @@ impl gpu::Gpu for Backend { Ok(()) } fn supports_vm_status(&self) -> bool { true } + /// Render commands are refused (`m3_submit`), so the device also reports itself + /// compute-only: graphics userspace then leaves it alone instead of failing its first render. fn feature_flags(&self) -> u64 { uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 + | uapi::DRM_ASAHI_FEATURE_COMPUTE_ONLY as u64 } fn tracked_submission(&self) -> bool { true } fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 75301a90c564c0..7193c1ef7e4546 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -535,6 +535,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_RENDER_MESH_OUTPUT ((1ULL) << 38) +/* + * DRM_ASAHI_FEATURE_COMPUTE_ONLY: the device runs compute commands only. + * DRM_ASAHI_CMD_RENDER is refused, so the device cannot serve graphics APIs; + * userspace should not offer it for them. Compute commands, the VM and GEM + * interfaces are unaffected. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 From 1210dd585630f1f15d420ab819ae01172ee3e8d0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 05:33:29 -0500 Subject: [PATCH 0271/1514] arm64: dts: apple: t8132: describe the SIO for loader handoff Describe the T8132 SIO resources in the shared t8132-sio.dtsi included by all T8132 boards (as on T6041 and T8140): the sio alias the boot loader looks for, the SIO DART window above the preloaded segments, its mailbox, the 128-channel count (dp-audio2 is channel 0x68), and the SPI/UART/DPA parents of SIO_CPU that the SIO firmware's shims need. Re-enable ps_sio_cpu and ps_dpa_p in t8132-j713-j715.dtsi and drivers/soc/apple/t8132-platform-data.dts after t8132-j713-pmgr.dtsi (just like ps_gfx) so J713/J715 keep sio_mbox's and dart_sio0's power domains available across t8132-platform-handoff without changing the legacy-loader adapter's t8132-j713-pmgr.dtsi, and drop the /delete-property/ power-domains override on dart_sio0 so it keeps its ps_sio_cpu power domain now that both are enabled. The sio node itself stays disabled in the static DT; the boot loader enables it once it has published the boot tables. Signed-off-by: Diljit Singh --- .../arm64/boot/dts/apple/t8132-j713-j715.dtsi | 21 ++++++----- arch/arm64/boot/dts/apple/t8132-sio.dtsi | 36 +++++++++++++++++-- drivers/soc/apple/t8132-platform-data.dts | 8 +++++ 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi index 28e1d62a4a64da..bae6c27244f3c5 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j713-j715.dtsi @@ -131,6 +131,15 @@ status = "okay"; }; +/* The SIO itself is described for every M4 Mac in t8132-sio.dtsi. */ +&ps_sio_cpu { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + /* The J713's full 2560x1664 panel including the notch rows, 224 ppi. */ &dcp { apple,panel-width-mm = <290>; @@ -357,10 +366,10 @@ }; /* - * t8132-j713-pmgr.dtsi disables SCODEC and SIO_CPU, and their engines with - * them. Their DARTs, which name those states in t8132-peripherals.dtsi, would - * wait for them forever if anything enabled them, so drop the reference here. - * VENC is enabled there: the video encoder and its DARTs below. + * t8132-j713-pmgr.dtsi disables SCODEC, and its engines with it. Their DARTs, + * which name those states in t8132-peripherals.dtsi, would wait for them + * forever if anything enabled them, so drop the reference here. VENC is + * enabled there: the video encoder and its DARTs below. */ &dart_ave2 { /delete-property/ power-domains; @@ -370,10 +379,6 @@ /delete-property/ power-domains; }; -&dart_sio0 { - /delete-property/ power-domains; -}; - /* The video encoder; t8132-j713-pmgr.dtsi enables its VENC states. */ &dart_ave0 { status = "okay"; diff --git a/arch/arm64/boot/dts/apple/t8132-sio.dtsi b/arch/arm64/boot/dts/apple/t8132-sio.dtsi index 09861ddb281830..fb36969fd69025 100644 --- a/arch/arm64/boot/dts/apple/t8132-sio.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-sio.dtsi @@ -1,5 +1,16 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* T8132 SIO resources; channel layout and firmware regions require loader support. */ +/* + * T8132 SIO resources. iBoot preloads the SIO firmware; the boot loader + * reserves it, publishes the boot tables (T6041 layout) and enables the SIO + * node, which it finds by the alias. Without such a loader the SIO stays + * disabled and nothing else changes. + */ + +/ { + aliases { + sio = &sio; + }; +}; &soc { sio_mbox: mailbox@3ade08000 { @@ -14,7 +25,7 @@ "recv-empty", "recv-not-empty"; #mbox-cells = <0>; power-domains = <&ps_sio_cpu>; - status = "disabled"; + status = "okay"; }; sio: dma-controller@3ade00000 { @@ -22,6 +33,8 @@ reg = <0x3 0xade00000 0x0 0x8000>, <0x3 0xad850000 0x0 0x4000>; #dma-cells = <1>; + /* Channel numbers run up to dp-audio2's 0x68, as on T8140. */ + dma-channels = <128>; mboxes = <&sio_mbox>; iommus = <&dart_sio0 0>; power-domains = <&ps_sio_cpu>; @@ -29,3 +42,22 @@ status = "disabled"; }; }; + +/* The boot tables sit in the window above the preloaded segments (ADT vm-base, vm-size). */ +&dart_sio0 { + apple,dma-range = <0x100 0x1c000 0x2ff 0xfffe4000>; + status = "okay"; +}; + +/* + * The SIO firmware drives the SPI, UART and DP audio shims, so keep their + * parents on while it runs, as on T6041 and T8140. + */ +&ps_sio_cpu { + power-domains = <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>; + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; diff --git a/drivers/soc/apple/t8132-platform-data.dts b/drivers/soc/apple/t8132-platform-data.dts index 2f5e783a179cbd..06be8ecd1bb873 100644 --- a/drivers/soc/apple/t8132-platform-data.dts +++ b/drivers/soc/apple/t8132-platform-data.dts @@ -95,3 +95,11 @@ &ps_gfx { status = "okay"; }; + +&ps_sio_cpu { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; From 4036f6067a61f2c48389ee8350b736275b9752f8 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:01:57 -0500 Subject: [PATCH 0272/1514] dmaengine: apple-sio: the M4 (T8132) SIO takes the T8140 data The J773g ADT describes the SIO boot tables as on T8140 (T6041's layout) and its DisplayPort audio channels alike: [2, 0, 0x800, 0x800, 0x800, 0]. Give apple,t8132-sio the T8140 data instead of the generic one. Signed-off-by: Diljit Singh --- drivers/dma/apple-sio.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index cb75beb54ae994..1efd0d1a44975e 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -709,6 +709,11 @@ static const struct of_device_id sio_of_match[] = { { .compatible = "apple,t6050-sio", .data = &sio_hw_t6050 }, { .compatible = "apple,t6041-sio", .data = &sio_hw_t6041 }, { .compatible = "apple,t8140-sio", .data = &sio_hw_t8140 }, + /* + * T8132 (M4): the J773g ADT describes the SIO tables as T8140's and + * its DisplayPort audio channels alike ([2, 0, 0x800, 0x800, 0x800, 0]). + */ + { .compatible = "apple,t8132-sio", .data = &sio_hw_t8140 }, { .compatible = "apple,t6030-sio", .data = &sio_hw_t6030 }, { .compatible = "apple,sio", .data = &sio_hw_generic }, { } From d2490aac6b89d99eff0db11c09af7385faa8e4e4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 21:01:43 -0500 Subject: [PATCH 0273/1514] arm64: dts: apple: t8132-sio: add asc and auxiliary reg-names Add reg-names = "asc", "auxiliary" to sio: dma-controller@3ade00000 so drivers/soc/apple/sleep.c can map the SIO ASC window via of_property_match_string("reg-names", "asc") when the boot loader enables SIO through the sio alias (matching t8140 and t6050). Without this, enabling the sio alias in t8132-sio.dtsi causes apple-sleep to reject deep sleep on T8132 boards such as J713. Signed-off-by: Diljit Singh --- arch/arm64/boot/dts/apple/t8132-sio.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8132-sio.dtsi b/arch/arm64/boot/dts/apple/t8132-sio.dtsi index fb36969fd69025..ba5d3815d452bb 100644 --- a/arch/arm64/boot/dts/apple/t8132-sio.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-sio.dtsi @@ -32,6 +32,7 @@ compatible = "apple,t8132-sio", "apple,sio"; reg = <0x3 0xade00000 0x0 0x8000>, <0x3 0xad850000 0x0 0x4000>; + reg-names = "asc", "auxiliary"; #dma-cells = <1>; /* Channel numbers run up to dp-audio2's 0x68, as on T8140. */ dma-channels = <128>; From 3724352eec6e95ba53cc477fe2a5f6cec74af88c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 21:24:34 -0500 Subject: [PATCH 0274/1514] dt-bindings: dma: apple,sio: require asc and auxiliary reg-names on T8132 Constrain reg-names to [asc, auxiliary] and require it in the apple,t8132-sio branch of apple,sio.yaml so dtbs_check catches any T8132 tree that drops the ASC register window name needed by apple-sleep. Signed-off-by: Diljit Singh --- Documentation/devicetree/bindings/dma/apple,sio.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Documentation/devicetree/bindings/dma/apple,sio.yaml b/Documentation/devicetree/bindings/dma/apple,sio.yaml index 62c517ccff0220..97e361cc393971 100644 --- a/Documentation/devicetree/bindings/dma/apple,sio.yaml +++ b/Documentation/devicetree/bindings/dma/apple,sio.yaml @@ -75,12 +75,17 @@ allOf: reg: minItems: 2 maxItems: 2 + reg-names: + items: + - const: asc + - const: auxiliary clocks: minItems: 3 maxItems: 3 status: const: disabled required: + - reg-names - clocks - status - if: From 08acd2e1e6d5877503fd76e4a2f194940a94ea47 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Wed, 18 Nov 2026 18:47:43 +0100 Subject: [PATCH 0275/1514] ASoC: cs42l84: write the registers back without leaving events latched After a firmware sleep, the codec comes out of reset and the resume writes its cached registers back with regcache_sync(), in address order, with the interrupt still off. Turning tip and ring sensing on latches plug events at once, as do some later writes (MSM_BLOCK_EN3 among them), and the remote button sources come up latched (0x60 in REMOTE_BUTTON_STATUS1). Nothing reads them, and the codec stops answering the bus a write or two later: the write times out (-ETIME), the resume fails, and the jack stays dead until the driver is bound again. On the MacBook Air (M4, J713) this happened on every deep sleep. Write plug detection back first, in the order the probe sets it up, then every other register the cache holds, once each, in address order, and read the plug interrupt status after each write to clear what it latched, as the interrupt thread does. The remote button status is read once, after plug detection. A KUnit suite checks that order, that the plug detection list matches what the probe writes, and that a codec that stops answering ends the write-back with the error. Fixes: b91208392f51 ("ASoC: cs42l84: Bring the codec back after a firmware sleep") Signed-off-by: Bartosz Nitka --- sound/soc/codecs/Kconfig | 3 +- sound/soc/codecs/cs42l84-test.c | 264 +++++++++++++++++++++++++++++++- sound/soc/codecs/cs42l84.c | 75 ++++++++- 3 files changed, 336 insertions(+), 6 deletions(-) diff --git a/sound/soc/codecs/Kconfig b/sound/soc/codecs/Kconfig index cd02d72f1e4eb0..e0be5ba78fb43e 100644 --- a/sound/soc/codecs/Kconfig +++ b/sound/soc/codecs/Kconfig @@ -1067,7 +1067,8 @@ config SND_SOC_CS42L84_TEST help This builds KUnit tests for the clock switching that the Cirrus Logic cs42l84 codec driver does when a stream is - muted or unmuted. The tests are built into the cs42l84 + muted or unmuted, and for how it writes its registers back + after a firmware sleep. The tests are built into the cs42l84 driver and run when it is loaded. For more information on KUnit and unit tests in general, diff --git a/sound/soc/codecs/cs42l84-test.c b/sound/soc/codecs/cs42l84-test.c index 4d4952a33c8485..a8c6e0b1654bf3 100644 --- a/sound/soc/codecs/cs42l84-test.c +++ b/sound/soc/codecs/cs42l84-test.c @@ -1,10 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only // -// KUnit tests for the clock switching in cs42l84_mute_stream(). +// KUnit tests for the clock switching in cs42l84_mute_stream(), and for +// writing the registers back after a firmware sleep. // // This file is included at the end of cs42l84.c when // CONFIG_SND_SOC_CS42L84_TEST is enabled, so the tests can reach the -// driver's static DAI ops and PLL configuration. +// driver's static DAI ops, PLL configuration and register write-back. // // The codec runs from its internal oscillator (RCO) while no stream is // active. Unmuting the first stream moves it onto BCLK, through the PLL @@ -517,4 +518,261 @@ static struct kunit_suite cs42l84_test_suite = { .test_cases = cs42l84_test_cases, }; -kunit_test_suite(cs42l84_test_suite); +/* + * Writing the registers back after a firmware sleep, in + * cs42l84_restore_regs(), runs on the driver's own regmap configuration: + * its cache and its volatile registers. Every bus access is logged, reads + * too, so the order of writes and status reads can be checked. + */ + +#define CS42L84_TEST_MAX_ACCESSES 128 + +struct cs42l84_test_access { + bool write; + unsigned int reg; +}; + +struct cs42l84_sleep_test_priv { + struct kunit *test; + + struct cs42l84_private cs42l84; + + /* Register contents seen by the driver */ + u8 *regs; + + /* Every bus access made by the driver, in order */ + struct cs42l84_test_access accesses[CS42L84_TEST_MAX_ACCESSES]; + unsigned int num_accesses; + + /* The codec stops answering at the first write to fail_reg */ + unsigned int fail_reg; + bool dead; + unsigned int num_dead_accesses; +}; + +static int cs42l84_sleep_test_access(struct cs42l84_sleep_test_priv *priv, + bool write, unsigned int reg) +{ + if (reg >= CS42L84_TEST_NUM_REGS) + return -EINVAL; + + if (priv->dead) { + priv->num_dead_accesses++; + return -ETIME; + } + if (write && reg == priv->fail_reg) { + priv->dead = true; + return -ETIME; + } + + if (priv->num_accesses < ARRAY_SIZE(priv->accesses)) { + priv->accesses[priv->num_accesses].write = write; + priv->accesses[priv->num_accesses].reg = reg; + priv->num_accesses++; + } else { + KUNIT_FAIL(priv->test, "access log full at reg %#x", reg); + } + + return 0; +} + +static int cs42l84_sleep_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct cs42l84_sleep_test_priv *priv = context; + int ret; + + ret = cs42l84_sleep_test_access(priv, false, reg); + if (ret) + return ret; + + *val = priv->regs[reg]; + + return 0; +} + +static int cs42l84_sleep_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct cs42l84_sleep_test_priv *priv = context; + int ret; + + ret = cs42l84_sleep_test_access(priv, true, reg); + if (ret) + return ret; + + priv->regs[reg] = val; + + return 0; +} + +/* Set the codec up as the probe does, and some registers around plug detection */ +static void cs42l84_sleep_test_probe(struct cs42l84_sleep_test_priv *priv) +{ + struct cs42l84_private *cs42l84 = &priv->cs42l84; + + cs42l84_setup_plug_detect(cs42l84); + cs42l84_set_interrupt_masks(cs42l84, CS42L84_RS_PLUG | CS42L84_RS_UNPLUG); + + /* HSBIAS on, as a headset with a mic leaves it */ + regmap_write(cs42l84->regmap, CS42L84_MISC_DET_CTL, + FIELD_PREP(CS42L84_MISC_DET_CTL_HSBIAS_CTL, 3) | + FIELD_PREP(CS42L84_MISC_DET_CTL_DETECT_MODE, 3) | + CS42L84_MISC_DET_CTL_PDN_MIC_LVL_DET); + regmap_write(cs42l84->regmap, CS42L84_DAC_CTL1, CS42L84_DAC_CTL1_UNMUTE); +} + +/* The suspend before a firmware sleep, then the reset the codec wakes up from */ +static void cs42l84_sleep_test_sleep(struct cs42l84_sleep_test_priv *priv) +{ + struct regmap *regmap = priv->cs42l84.regmap; + + regcache_cache_only(regmap, true); + regcache_mark_dirty(regmap); + + memset(priv->regs, 0, CS42L84_TEST_NUM_REGS); + + regcache_cache_only(regmap, false); + priv->num_accesses = 0; +} + +static void cs42l84_sleep_test_expect_status_read(struct kunit *test, unsigned int i) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + + KUNIT_ASSERT_LT(test, i, priv->num_accesses); + KUNIT_EXPECT_FALSE(test, priv->accesses[i].write); + KUNIT_EXPECT_EQ(test, priv->accesses[i].reg, CS42L84_TSRS_PLUG_INT_STATUS); +} + +/* + * Plug detection goes back first, in the order cs42l84_setup_plug_detect() + * turns it on, then the remote button status is read once, then every other + * register the cache holds is written once, in address order. Each write is + * followed by a read of the plug interrupt status, and the codec ends up with + * the registers it had before the sleep. + */ +static void cs42l84_test_restore_order(struct kunit *test) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + const unsigned int n = ARRAY_SIZE(cs42l84_plug_detect_regs); + unsigned int i, reg, num_setup = 0, mismatches = 0; + u8 *before; + + cs42l84_sleep_test_probe(priv); + + /* The list is what the probe writes before it reads the tip sense */ + for (i = 0; i < priv->num_accesses; i++) { + if (!priv->accesses[i].write && + priv->accesses[i].reg == CS42L84_TSRS_PLUG_STATUS) + break; + if (!priv->accesses[i].write) + continue; + KUNIT_ASSERT_LT(test, num_setup, n); + KUNIT_EXPECT_EQ(test, priv->accesses[i].reg, + cs42l84_plug_detect_regs[num_setup]); + num_setup++; + } + KUNIT_EXPECT_EQ(test, num_setup, n); + + before = kunit_kmalloc(test, CS42L84_TEST_NUM_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, before); + memcpy(before, priv->regs, CS42L84_TEST_NUM_REGS); + + cs42l84_sleep_test_sleep(priv); + KUNIT_ASSERT_EQ(test, cs42l84_restore_regs(&priv->cs42l84), 0); + + for (i = 0; i < n; i++) { + KUNIT_ASSERT_LT(test, 2 * i, priv->num_accesses); + KUNIT_EXPECT_TRUE(test, priv->accesses[2 * i].write); + KUNIT_EXPECT_EQ(test, priv->accesses[2 * i].reg, cs42l84_plug_detect_regs[i]); + cs42l84_sleep_test_expect_status_read(test, 2 * i + 1); + } + + KUNIT_ASSERT_LT(test, 2 * n, priv->num_accesses); + KUNIT_EXPECT_FALSE(test, priv->accesses[2 * n].write); + KUNIT_EXPECT_EQ(test, priv->accesses[2 * n].reg, CS42L84_REMOTE_BUTTON_STATUS1); + + /* Registers below the plug detection ones too */ + KUNIT_ASSERT_LT(test, 2 * n + 1, priv->num_accesses); + KUNIT_EXPECT_LT(test, priv->accesses[2 * n + 1].reg, CS42L84_RING_SENSE_CTL); + + for (i = 2 * n + 1; i < priv->num_accesses; i += 2) { + reg = priv->accesses[i].reg; + KUNIT_EXPECT_TRUE(test, priv->accesses[i].write); + KUNIT_EXPECT_FALSE(test, cs42l84_is_plug_detect_reg(reg)); + KUNIT_EXPECT_FALSE(test, cs42l84_volatile_register(NULL, reg)); + if (i > 2 * n + 1) + KUNIT_EXPECT_GT(test, reg, priv->accesses[i - 2].reg); + cs42l84_sleep_test_expect_status_read(test, i + 1); + } + + for (reg = 0; reg < CS42L84_TEST_NUM_REGS; reg++) { + if (!cs42l84_volatile_register(NULL, reg) && priv->regs[reg] != before[reg]) + mismatches++; + } + KUNIT_EXPECT_EQ(test, mismatches, 0); +} + +/* A codec that stops answering ends the write-back with the bus error */ +static void cs42l84_test_restore_stops_at_error(struct kunit *test) +{ + struct cs42l84_sleep_test_priv *priv = test->priv; + + cs42l84_sleep_test_probe(priv); + cs42l84_sleep_test_sleep(priv); + + priv->fail_reg = CS42L84_HS_SWITCH_CTL; + KUNIT_EXPECT_EQ(test, cs42l84_restore_regs(&priv->cs42l84), -ETIME); + KUNIT_EXPECT_TRUE(test, priv->dead); + KUNIT_EXPECT_EQ(test, priv->num_dead_accesses, 0); +} + +static int cs42l84_sleep_test_case_init(struct kunit *test) +{ + /* The driver's cache and volatile registers, on the logging bus */ + const struct regmap_config config = { + .reg_bits = cs42l84_regmap.reg_bits, + .val_bits = cs42l84_regmap.val_bits, + .volatile_reg = cs42l84_regmap.volatile_reg, + .max_register = cs42l84_regmap.max_register, + .cache_type = cs42l84_regmap.cache_type, + .reg_read = cs42l84_sleep_test_reg_read, + .reg_write = cs42l84_sleep_test_reg_write, + }; + struct cs42l84_sleep_test_priv *priv; + struct regmap *regmap; + struct device *dev; + + priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv); + priv->test = test; + priv->fail_reg = UINT_MAX; + test->priv = priv; + + priv->regs = kunit_kzalloc(test, CS42L84_TEST_NUM_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, priv->regs); + + dev = kunit_device_register(test, "cs42l84_sleep_test_drv"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + regmap = devm_regmap_init(dev, NULL, priv, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + priv->cs42l84.dev = dev; + priv->cs42l84.regmap = regmap; + + return 0; +} + +static struct kunit_case cs42l84_sleep_test_cases[] = { + KUNIT_CASE(cs42l84_test_restore_order), + KUNIT_CASE(cs42l84_test_restore_stops_at_error), + { } /* terminator */ +}; + +static struct kunit_suite cs42l84_sleep_test_suite = { + .name = "snd-soc-cs42l84-sleep-test", + .init = cs42l84_sleep_test_case_init, + .test_cases = cs42l84_sleep_test_cases, +}; + +kunit_test_suites(&cs42l84_test_suite, &cs42l84_sleep_test_suite); diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index 37a8c1bf92a797..fb2d9f1baa9762 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -1128,7 +1128,7 @@ static void cs42l84_setup_plug_detect(struct cs42l84_private *cs42l84) { unsigned int reg; - /* Set up plug detection */ + /* Set up plug detection, as cs42l84_plug_detect_regs[] lists it */ regmap_update_bits(cs42l84->regmap, CS42L84_MIC_DET_CTL4, CS42L84_MIC_DET_CTL4_LATCH_TO_VP, CS42L84_MIC_DET_CTL4_LATCH_TO_VP); @@ -1394,6 +1394,77 @@ static void cs42l84_i2c_remove(struct i2c_client *i2c_client) gpiod_set_value_cansleep(cs42l84->reset_gpio, 0); } +/* + * The registers cs42l84_setup_plug_detect() turns plug detection on with, in + * its order. After a firmware sleep they are written back first, in this + * order, so the two must stay in step. + */ +static const unsigned int cs42l84_plug_detect_regs[] = { + CS42L84_MIC_DET_CTL4, + CS42L84_TIP_SENSE_CTL2, + CS42L84_RING_SENSE_CTL, + CS42L84_TIP_SENSE_CTL, + CS42L84_MSM_BLOCK_EN3, +}; + +static bool cs42l84_is_plug_detect_reg(unsigned int reg) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cs42l84_plug_detect_regs); i++) { + if (cs42l84_plug_detect_regs[i] == reg) + return true; + } + return false; +} + +/* Write one cached register back, then clear what the write latched. */ +static int cs42l84_restore_reg(struct cs42l84_private *cs42l84, unsigned int reg) +{ + unsigned int status; + int ret; + + ret = regcache_sync_region(cs42l84->regmap, reg, reg); + if (ret) + return ret; + return regmap_read(cs42l84->regmap, CS42L84_TSRS_PLUG_INT_STATUS, &status); +} + +/* + * Write the cache back after the codec's reset. Turning tip and ring sensing + * on latches plug events at once, and so do some of the other writes; the + * remote button sources also come up latched. With the interrupt off, nothing + * reads them, and a codec left with a latched event stops answering the bus a + * write or two later. So plug detection goes first, in the probe's order, then + * every other register the cache holds, one at a time, with the status read + * after each write to clear what it latched, as the interrupt thread does. + */ +static int cs42l84_restore_regs(struct cs42l84_private *cs42l84) +{ + unsigned int i, reg, val, max = regmap_get_max_register(cs42l84->regmap); + int ret; + + for (i = 0; i < ARRAY_SIZE(cs42l84_plug_detect_regs); i++) { + ret = cs42l84_restore_reg(cs42l84, cs42l84_plug_detect_regs[i]); + if (ret) + return ret; + } + ret = regmap_read(cs42l84->regmap, CS42L84_REMOTE_BUTTON_STATUS1, &val); + if (ret) + return ret; + + for (reg = 0; reg <= max; reg++) { + /* Plug detection is back already */ + if (cs42l84_is_plug_detect_reg(reg) || + !regcache_reg_cached(cs42l84->regmap, reg)) + continue; + ret = cs42l84_restore_reg(cs42l84, reg); + if (ret) + return ret; + } + return 0; +} + /* * A firmware-driven system sleep holds the codec in reset, so it comes back * with none of its registers and answers nothing until the reset is released. @@ -1478,7 +1549,7 @@ static int cs42l84_resume(struct device *dev) goto err; } - ret = regcache_sync(cs42l84->regmap); + ret = cs42l84_restore_regs(cs42l84); if (ret) goto err; From 60fbca7a90d63d72f3fcda1c0ebcab8f62969275 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Wed, 18 Nov 2026 20:04:35 +0100 Subject: [PATCH 0276/1514] ASoC: cs42l84: power the headset bias down after an unplug in a sleep A headset unplugged during a firmware sleep leaves its bias on. The resume writes the cache back, the 2.7 V mic bias included, finds the jack empty and reports it, but unlike the interrupt thread's unplug path it does not call cs42l84_revert_hs(). The bias stays powered, disconnected from the jack, until the next plug. Revert the headset setup when the jack is empty after the wake, on both the tip-sense and ring-sense paths, as the unplug paths do. Fixes: b91208392f51 ("ASoC: cs42l84: Bring the codec back after a firmware sleep") Fixes: 2f122e3977e4 ("ASoC: cs42l84: add ring-sense plug detection, selected from DT") Signed-off-by: Bartosz Nitka --- sound/soc/codecs/cs42l84.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sound/soc/codecs/cs42l84.c b/sound/soc/codecs/cs42l84.c index fb2d9f1baa9762..12fed85fd3e4f9 100644 --- a/sound/soc/codecs/cs42l84.c +++ b/sound/soc/codecs/cs42l84.c @@ -1571,6 +1571,8 @@ static int cs42l84_resume(struct device *dev) cs42l84_detect_hs(cs42l84); } else { cs42l84->tip_state = CS42L84_UNPLUG; + /* As on an unplug: the cache may hold a headset's bias */ + cs42l84_revert_hs(cs42l84); cs42l84->hs_type = 0; snd_soc_jack_report(cs42l84->jack, 0, SND_JACK_HEADSET); } @@ -1580,6 +1582,8 @@ static int cs42l84_resume(struct device *dev) cs42l84_set_interrupt_masks(cs42l84, 0); } else { cs42l84->ring_state = CS42L84_UNPLUG; + /* As on an unplug: the cache may hold a headset's bias */ + cs42l84_revert_hs(cs42l84); cs42l84->hs_type = 0; snd_soc_jack_report(cs42l84->jack, 0, SND_JACK_HEADSET); cs42l84_set_interrupt_masks(cs42l84, From a8969bf41782998b88fe02e382661336905746a2 Mon Sep 17 00:00:00 2001 From: Fredrik Silfver <1684291+freber@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:49:14 +0100 Subject: [PATCH 0277/1514] drm/asahi: m3: default to render batches of two The M3 runtime publishes one render pass at a time unless asahi.m3_render_batch_size or the writable m3_render_batch_override asks for more. On a J615 (15-inch M3 MacBook Air) that costs frames while Chromium scrolls an image-heavy page. Make the boot default 2. Measured on a J615 with the stock 7.2.11 aurora16 module, whose next_batch() and render_batch_size() match this tree's, booted with asahi.t8122_pstate_cap=5 and setting m3_render_batch_override at runtime. Chromium images scene, median of three runs: batch dropped frames p99 frame interval 1 2.2 % 33.3 ms 2 0 % 16.7 ms 4 0.1 % 16.7 ms Two same-session control runs at batch 1 dropped 2.6 % and 2.4 %. With 2, a burst of eight glprobe draws retired 1.6 render commands per retirement instead of 1.0, its median fell from 4.53 ms to 4.00 ms and GPU mailbox interrupts per run fell from 320 to 200. gpubench throughput and idle power stayed within noise. The kernel log had no GPU errors. Only T8122 is affected. This parameter exists only with CONFIG_DRM_ASAHI_M3_T8122, its only reader is the runtime's next_batch(), the runtime's only SoC table is T8122 and it starts only on the J613 and J615. T6030 and T6031 keep the G15 backend or the probe refusal. The first render draw is still published alone for InitBM, and the T8122 pipeline depth of 2 and the 4000 us batch budget still bound every batch. m3_render_batch_override=1 restores the old behaviour at runtime, asahi.m3_render_batch_size=1 at boot. A 7.3 kernel built from this head with #1985, #2199 and #2203 merged then booted on a J615 with the default command line. In the same Chromium scene under the balanced profile at panel scale 1.6, median of three runs, 11.8 % of frames dropped at the default of 2 against 15.6 % on the same kernel booted with asahi.m3_render_batch_size=1. The eight-draw glprobe burst retired 1.52 render commands per retirement against 1.00. The kernel log had no GPU errors. #2203 raises that build's ceiling to state 8. The J613 runs the same runtime and gets the same default but was not tested. Neither was a 7.3 build at the T8122 ceiling of 2 that applies without #2203. Signed-off-by: Fredrik Silfver <1684291+freber@users.noreply.github.com> --- drivers/gpu/drm/asahi/m3/m3_params.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 85033c88e4192d..109c03ba2ef160 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -205,8 +205,8 @@ pub(crate) fn render_internal_timestamps()->bool { // The runtime's boot-time module parameters. On 7.1.12 they were `module!` parameters; they // keep their names, and exist only with the T8122 runtime built in. -/// `asahi.m3_render_batch_size`: bounded ordered render batch size (1..16). -static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); +/// `asahi.m3_render_batch_size`: bounded ordered render batch size (1..16, default 2). +static M3_RENDER_BATCH_SIZE: AtomicU64 = AtomicU64::new(2); m3_param!("m3_render_batch_size", M3_RENDER_BATCH_SIZE, parse_u64); /// `asahi.m3_compute_batch_size`: bounded ordered compute batch size (1..16). static M3_COMPUTE_BATCH_SIZE: AtomicU64 = AtomicU64::new(1); From 4d65aa07997c2e1f8bbcd8421b8d01c157f492ed Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 23:01:59 +1100 Subject: [PATCH 0278/1514] btrfs: bound blocking COW direct-write lookahead Skip the extent-map walk for NOWAIT requests because the COW path returns EAGAIN without allocating. Bound blocking lookahead by the filesystem maximum extent size, and reschedule during cached extent-map walks. Signed-off-by: Ryan Murray --- fs/btrfs/direct-io.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c index 561d4bc3b51b52..d8be2e59444873 100644 --- a/fs/btrfs/direct-io.c +++ b/fs/btrfs/direct-io.c @@ -388,15 +388,15 @@ static bool btrfs_dio_write_is_cow(const struct btrfs_inode *inode, * A COW write replaces everything mapped in its range with one newly allocated * extent, so the boundaries of the extents it overwrites do not matter. Extend * the mapping [@start, @start + @len) over the following extent maps that a - * direct write would COW as well, up to @length. Without this, a sequential - * rewrite of a fragmented range allocates one new extent (and ordered extent, - * file extent item and bio) per old extent, so the file stays as fragmented as - * it was and the rewrite runs at small-write speed. + * direct write would COW as well, within @length and the maximum extent size. + * Without this, a sequential rewrite of a fragmented range allocates one new + * extent (and ordered extent, file extent item and bio) per old extent. The + * file stays fragmented and the rewrite runs at small-write speed. */ static u64 btrfs_dio_cow_write_len(struct btrfs_inode *inode, u64 start, u64 len, u64 length) { - const u64 limit = start + length; + const u64 limit = start + min(length, inode->root->fs_info->max_extent_size); u64 end = start + len; while (end < limit) { @@ -413,6 +413,7 @@ static u64 btrfs_dio_cow_write_len(struct btrfs_inode *inode, u64 start, if (!cow) break; end = min(em_end, limit); + cond_resched(); } return end - start; @@ -560,7 +561,8 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, } len = min(len, em->len - (start - em->start)); - if (write && btrfs_dio_write_is_cow(BTRFS_I(inode), em)) + if (write && !(flags & IOMAP_NOWAIT) && + btrfs_dio_write_is_cow(BTRFS_I(inode), em)) len = btrfs_dio_cow_write_len(BTRFS_I(inode), start, len, length); /* From 101261596b9faa267be32cc57711757a192cd049 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 08:28:33 +0100 Subject: [PATCH 0279/1514] drm/asahi: g18: compare the command read-back instead of hashing it Between two application jobs the GPU waits about 154 us on the J873g for the next kick. About 100 us of it is spent hashing: the encoder computes FNV-1a digests of both commands and their register blocks (14 KiB, 56 us), and the audit reads both commands back from the write-combined graph and hashes them again (45 us for the hash, 7 us for the read). FNV-1a runs one dependent multiply per byte. Keep the encoder's cached copy of the commands with the encoded job and have the per-frame audit compare the read-back with it byte for byte. That is an exact check where the digests were a hash comparison, and it reads the graph in wide loads. The digests are computed from the cached copy only where they are logged: the first three frames of a client and the H1 audit, which now compares its read-back the same way and still logs the digests of what it read. EncodedJob moves to the kernel side, since the shared assembly code stays free of kernel allocations, and fnv64_uncached() loses its last user. Signed-off-by: Thomas Glanzmann --- .../gpu/drm/asahi/g18/fw/graphics_payload.rs | 11 ------ .../gpu/drm/asahi/g18/fw/render_assembly.rs | 17 +++++---- .../gpu/drm/asahi/g18/runtime/graphics_job.rs | 37 ++++++++++++++----- .../g18/runtime/graphics_job_application.rs | 15 +++++--- 4 files changed, 47 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs b/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs index ef70ea09af81a9..56f90cc6f860d3 100644 --- a/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs +++ b/drivers/gpu/drm/asahi/g18/fw/graphics_payload.rs @@ -116,17 +116,6 @@ fn fnv64_from(basis: u64, bytes: &[u8]) -> u64 { bytes.iter().fold(basis, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3)) } -/// [`fnv64`] of bytes in uncached (write-combined) memory. They are read in -/// wide copies: a byte load from such memory is a bus transaction each. -pub(crate) fn fnv64_uncached(bytes: &[u8]) -> u64 { - let mut chunk = [0u8; 256]; - bytes.chunks(chunk.len()).fold(0xcbf2_9ce4_8422_2325, |h, part| { - let copy = &mut chunk[..part.len()]; - copy.copy_from_slice(part); - fnv64_from(h, copy) - }) -} - impl<'a> GraphicsPayload<'a> { pub(crate) fn parse(bytes: &'a [u8]) -> Result { if bytes.len() < HEADER_BYTES { return Err(PayloadError::Length); } diff --git a/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs b/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs index 86ad9028ad3692..4385203fb81961 100644 --- a/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs +++ b/drivers/gpu/drm/asahi/g18/fw/render_assembly.rs @@ -106,7 +106,13 @@ pub(crate) enum AssemblyError { Registers(regs::G18RenderError), Command(cmd::G1 impl From for AssemblyError { fn from(e: regs::G18RenderError) -> Self { Self::Registers(e) } } impl From for AssemblyError { fn from(e: cmd::G18RenderCommandError) -> Self { Self::Command(e) } } -pub(crate) struct EncodedJob { pub rce: [[M5SksmRce; 4]; 2], pub digests: [u64; 7] } +/// FNV digests of a TA and a 3D command and of their register blocks, in +/// [`DIGEST_NAMES`] order. +pub(crate) fn digests(ta: &[u8], fragment: &[u8]) -> [u64; 7] { + [fnv64(ta), fnv64(fragment), fnv64(&ta[0x60..0x60 + 91 * 12]), + fnv64(&fragment[0xa0..0xa0 + 92 * 12]), fnv64(&fragment[0x7c0..0x7c0 + 17 * 12]), + fnv64(&fragment[0xee0..0xee0 + 24 * 12]), fnv64(&fragment[0x1600..0x1600 + 12 * 12])] +} // Only integer fields: zero is a valid initial representation. Kept on the // heap by the kernel caller, including across the register-builder calls. @@ -122,7 +128,7 @@ pub(crate) fn encode( ta: &mut [u8; cmd::G18_TA_COMMAND_BYTES], fragment: &mut [u8; cmd::G18_3D_COMMAND_BYTES], p: &G17pRenderParameters, controls: ®s::G18RenderControls, inputs: &cmd::G18RenderCommandInputs, -) -> Result { +) -> Result<[[M5SksmRce; 4]; 2], AssemblyError> { let mut workspace = Workspace { ta: regs::G18Program::empty(), fragment: regs::G18FragmentPrograms { main: regs::G18Program::empty(), store: regs::G18Program::empty(), resume: regs::G18Program::empty(), load: regs::G18Program::empty() } }; @@ -134,7 +140,7 @@ pub(crate) fn encode_into( ta: &mut [u8; cmd::G18_TA_COMMAND_BYTES], fragment: &mut [u8; cmd::G18_3D_COMMAND_BYTES], p: &G17pRenderParameters, controls: ®s::G18RenderControls, inputs: &cmd::G18RenderCommandInputs, workspace: &mut Workspace, -) -> Result { +) -> Result<[[M5SksmRce; 4]; 2], AssemblyError> { ta.fill(0); fragment.fill(0); regs::build_g18_ta_program_into(&mut workspace.ta, p, controls)?; regs::build_g18_fragment_programs_into(&mut workspace.fragment, p, controls)?; @@ -147,10 +153,7 @@ pub(crate) fn encode_into( va::GRAPHICS_JOB_LOW + FRAGMENT_OFFSET as u64, inputs, &programs)?; // The linked 3D tuple in inputs is finalized before encoding TA. let ta_rce = cmd::encode_g18_ta_command(ta, va::GRAPHICS_JOB_LOW, inputs, &view(&t))?; - let digests = [fnv64(ta), fnv64(fragment), fnv64(&ta[0x60..0x60 + 91 * 12]), - fnv64(&fragment[0xa0..0xa0 + 92 * 12]), fnv64(&fragment[0x7c0..0x7c0 + 17 * 12]), - fnv64(&fragment[0xee0..0xee0 + 24 * 12]), fnv64(&fragment[0x1600..0x1600 + 12 * 12])]; - Ok(EncodedJob { rce: [ta_rce, fr_rce], digests }) + Ok([ta_rce, fr_rce]) } /// Runtime variants are deliberately a closed set. H2 repeats three frames; diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs index dd3eb2837c9c83..3497a4a6aedc71 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs @@ -8,10 +8,28 @@ use crate::{g18::buffer::object::MappedObject, g18::runtime::graphics_memory::G1 G18ParameterBuffer, G18PbAddresses, G18PbPolicy, G18QueuedPass, G18PbReadback}}; use crate::{driver::AsahiDrmDevice, g18::fw::render_params::G17pRenderParameters, g18::address_map as va, g18::fw::render as regs, g18::fw::render_command as cmd, - g18::fw::render_assembly::{self as assembly, EncodedJob, RenderVariant}, mmu}; + g18::fw::render_assembly::{self as assembly, RenderVariant}, g18::fw::sksm::M5SksmRce, mmu}; use core::sync::atomic::{fence, Ordering}; use kernel::prelude::*; +/// An encoded render: its RCE records and the cached copy of its TA and 3D +/// commands, as copied to the graph. The copy (`G18_TA_COMMAND_BYTES` + +/// `G18_3D_COMMAND_BYTES`, about 11 KiB) lives as long as the job, so the +/// audits can compare the graph's read-back with it. +pub(crate) struct EncodedJob { pub rce: [[M5SksmRce; 4]; 2], commands: KVec } + +impl EncodedJob { + /// The TA and the 3D command. + pub(crate) fn commands(&self) -> (&[u8], &[u8]) { + self.commands.split_at(cmd::G18_TA_COMMAND_BYTES) + } + /// The [`assembly::digests`] of the commands, for the logs. + pub(crate) fn digests(&self) -> [u64; 7] { + let (ta, fragment) = self.commands(); + assembly::digests(ta, fragment) + } +} + pub(crate) struct G18GraphicsJob { // Payload's context lease retracts before the additional job mappings drop. program: G18GraphicsMemory, @@ -225,15 +243,13 @@ impl G18GraphicsJob { let digest=self.program.terminated_digest(self.parameters.encoder)?; dev_info!(dev.as_ref(), "G18_RENDER_DIGEST name=terminated-vdm-page fnv={:#018x}\n",digest); } - let expected=self.encoded.as_ref().ok_or(EINVAL)?.digests; + let (ta_expected,fr_expected)=self.encoded.as_ref().ok_or(EINVAL)?.commands(); self.graph.with_bytes_mut(|bytes| { let ta=&bytes[..cmd::G18_TA_COMMAND_BYTES]; let fr=&bytes[assembly::FRAGMENT_OFFSET..assembly::FRAGMENT_OFFSET+cmd::G18_3D_COMMAND_BYTES]; - let f=crate::g18::fw::graphics_payload::fnv64; - let actual=[f(ta),f(fr),f(&ta[0x60..0x60+91*12]),f(&fr[0xa0..0xa0+92*12]), - f(&fr[0x7c0..0x7c0+17*12]),f(&fr[0xee0..0xee0+24*12]),f(&fr[0x1600..0x1600+12*12])]; - if actual!=expected {return Err(EIO);} - for (name,digest) in assembly::DIGEST_NAMES.iter().zip(actual) { + if ta!=ta_expected || fr!=fr_expected {return Err(EIO);} + // Equal to the read-back: hash the cached copy, not the write-combined graph. + for (name,digest) in assembly::DIGEST_NAMES.iter().zip(assembly::digests(ta_expected,fr_expected)) { dev_info!(dev.as_ref(), "G18_RENDER_DIGEST name={} fnv={:#018x}\n",name,digest); } Ok(()) @@ -304,11 +320,12 @@ impl G18GraphicsJob { unsafe { core::ptr::write_bytes(workspace.as_mut_ptr(), 0, 1); } let mut workspace = unsafe { workspace.assume_init() }; // Encode in cached memory and copy the commands to the write-combined - // graph at once: the encoder and its digests read what they write. + // graph at once: the encoder reads what it writes. The cached copy is + // kept for the audit's comparison. let mut commands = KVec::from_elem(0u8, cmd::G18_TA_COMMAND_BYTES + cmd::G18_3D_COMMAND_BYTES, GFP_KERNEL)?; let (ta, fragment) = commands.split_at_mut(cmd::G18_TA_COMMAND_BYTES); - let encoded = assembly::encode_into(ta.try_into().map_err(|_| EINVAL)?, + let rce = assembly::encode_into(ta.try_into().map_err(|_| EINVAL)?, fragment.try_into().map_err(|_| EINVAL)?, &self.parameters, &self.controls, inputs, &mut workspace).map_err(|_| EINVAL)?; self.graph.with_bytes_mut(|bytes| { @@ -317,7 +334,7 @@ impl G18GraphicsJob { rest[..cmd::G18_3D_COMMAND_BYTES].copy_from_slice(fragment); Ok(()) })?; - self.encoded = Some(encoded); + self.encoded = Some(EncodedJob { rce, commands }); fence(Ordering::SeqCst); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index fb5a3e7c46bcc4..8165a9a1a68dde 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -204,13 +204,18 @@ impl ApplicationJob { pages+=uat.kernel_vm().translate_pages(address,bytes)?.len(); } } - let expected=self.job.encoded.as_ref().ok_or(EINVAL)?.digests; - self.job.graph.with_bytes_mut(|out| { - if crate::g18::fw::graphics_payload::fnv64_uncached(&out[..cmd::G18_TA_COMMAND_BYTES])!=expected[0] - || crate::g18::fw::graphics_payload::fnv64_uncached(&out[0x4000..0x4000+cmd::G18_3D_COMMAND_BYTES])!=expected[1] {return Err(EIO);}Ok(()) + // Compared byte for byte with the encoder's cached copy, which reads + // the write-combined graph in wide loads; hashing both every frame + // cost about 100 us between two jobs. + let job=&mut *self.job; + let encoded=job.encoded.as_ref().ok_or(EINVAL)?; + let (ta,fragment)=encoded.commands(); + job.graph.with_bytes_mut(|out| { + if out[..cmd::G18_TA_COMMAND_BYTES]!=*ta + || out[assembly::FRAGMENT_OFFSET..assembly::FRAGMENT_OFFSET+cmd::G18_3D_COMMAND_BYTES]!=*fragment {return Err(EIO);}Ok(()) })?; if frame.generation<=3 { - for (name,digest) in assembly::DIGEST_NAMES.iter().zip(expected) { + for (name,digest) in assembly::DIGEST_NAMES.iter().zip(encoded.digests()) { dev_info!(dev.as_ref(),"G18_APP_DIGEST frame={} name={} fnv={:#018x}\n",frame.generation,name,digest); } dev_info!(dev.as_ref(),"G18_APP_AUDIT frame={} pb=resident uma=match translations={} previous_stamp={:#x}\n",frame.generation,pages,frame.previous_stamp()); From 65e3300cb31f2f246538ff993f5e858935f3ab02 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 22:59:24 +1100 Subject: [PATCH 0280/1514] arm64: dts: apple: t8132: give the internal DCP its realtime bandwidth slot The firmware-27 DCP backend asks for apple,bw-scratch before it binds ("Incompatible devicetree!" without it). The T8132 internal DCP's slot is in the PMC window it already has as disp-4: bandwidth agent 0, the one the ADT's /arm-io/disp0 bw_req interrupt (BIRQ 0x35) names in the PMGR bwr-agent table, 0x20000 into the window; agents are 0x4000 apart, which puts the dcpexts' agents 3 and 4 at the pmgr_dcpext slots this tree already has. Describe it the way the dcpexts' slots are described, inside display window 4. The M4 26.6.2 backend reads the same property and has run the internal panel without a mailbox; keep it that way by taking the mailbox for an external processor only, so nothing changes on 26.6.2. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-dcp.dtsi | 13 +++++++++++++ drivers/gpu/drm/apple/iomfb_m4.c | 7 ++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-dcp.dtsi b/arch/arm64/boot/dts/apple/t8132-dcp.dtsi index b4383741a15fb9..b50f371e31fb9c 100644 --- a/arch/arm64/boot/dts/apple/t8132-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-dcp.dtsi @@ -70,6 +70,7 @@ iommus = <&dcp_dart 23>; power-domains = <&ps_disp_cpu>; dma-noncoherent; + apple,bw-scratch = <&pmgr_dcp 0 4 0>; status = "disabled"; disp0_piodma: piodma { @@ -79,6 +80,18 @@ }; }; + /* + * The internal pipe's realtime bandwidth request slot in the PMC, 0x20000 + * into the window the DCP has as disp-4: bandwidth agent 0, the one the + * ADT's disp0 bw_req interrupt names (agents are 0x4000 apart from + * 0x20000; the dcpexts' agents 3 and 4 are pmgr_dcpext's slots). + */ + pmgr_dcp: power-management@382820000 { + reg = <0x3 0x82820000 0x0 0x8>; + reg-names = "dcp-bw-scratch"; + #apple,bw-scratch-cells = <3>; + }; + /* The scanout frontend; it has no registers of its own. */ display: display-subsystem { compatible = "apple,t8132-display-subsystem", "apple,t8132-display-diagnostics"; diff --git a/drivers/gpu/drm/apple/iomfb_m4.c b/drivers/gpu/drm/apple/iomfb_m4.c index 1d61f083ff60f8..eb2523c95c8d5c 100644 --- a/drivers/gpu/drm/apple/iomfb_m4.c +++ b/drivers/gpu/drm/apple/iomfb_m4.c @@ -2695,7 +2695,12 @@ int iomfb_m4_init(struct apple_dcp *owner) return -ENOMEM; dcp->owner = owner; dcp->dev = dev; - dcp->bw_mailbox = dcp_m4_bw_mailbox(dev); + /* + * The 26.6.2 panel path runs without the realtime bandwidth mailbox; + * the slot the DT gives the internal DCP is the firmware-27 backend's. + */ + if (external) + dcp->bw_mailbox = dcp_m4_bw_mailbox(dev); mutex_init(&dcp->lock); mutex_init(&dcp->ext_modes_lock); spin_lock_init(&dcp->state_lock); From 58477fdd2f1af3c94d6a724e7d05f58084480e5c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 22:59:25 +1100 Subject: [PATCH 0281/1514] drm/apple: dcp: run the T8132 internal DCP on firmware 27.2 with the 27.2 table On the macOS 27.2 stub the M4 MacBook Air's (J713) internal display processor runs the 26B123 image the J773g's processors run (UUID B3BA603C), and the M4 backend refuses it ("unqualified firmware 26.6.2 handoff"), so the panel stays on simpledrm. Admit an internal T8132 DCP that the boot loader handed over with that image (firmware version and compatibility 27.2.0) and with the firmware-27 clock metadata (apple,clock-ids, from /arm-io/disp0) to the firmware-27 backend with the 27.2 method table, before the M4 hw data is looked at. Requiring the clocks keeps out a main DCP that a boot loader leaves running idle without a handoff, as on the Mac mini. It gets apple_dcp_hw_t8132_v27: 41-bit firmware DMA (apple,dma-range <0x100 0 0x10 0> ends at 1 TiB + 64 GiB), no DPTX port service, and adoption of the live session iBoot leaves running. No sleep support. That the T8132 26B123 image numbers its IOMFB methods as the T6041 and T8142 26B123 images do is the assumption the J773g dcpext admission makes too. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 34 +++++++++++++++++++++++++++++++ include/linux/soc/apple/display.h | 14 +++++++++++++ 2 files changed, 48 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index f44e79ad326600..b5d03469575e81 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6027,6 +6027,20 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) * 27.2 driving the mini's dcpext0 has to confirm the A4xx/A5xx IDs * before this is relied on. */ + /* + * The T8132 internal panel's processor on the macOS 27.2 stub, handed + * over by the boot loader with the 26B123 image (see + * apple_t8132_dcp_v27_2()): the firmware-27 backend with the 27.2 + * method table. That this image numbers its IOMFB methods as the + * T6041 and T8142 26B123 images do is the same assumption the J773g + * dcpext case below makes. + */ + if (apple_t8132_dcp_v27_2(dev->of_node)) { + /* Checked by apple_t8132_dcp_v27_2(). */ + dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); + return dcp_v27_method_table(dev, compat_str); + } + if (apple_t8132_dcpext_v27_2(dev->of_node)) { /* Checked by apple_t8132_dcpext_v27_2(). */ dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); @@ -7218,6 +7232,23 @@ static int dcp_s2r_pm_register(struct apple_dcp *dcp); * No sleep support: neither a firmware-27 sleep nor a link release has run * on this processor. */ +/* + * T8132 internal display processor on firmware 27.2, admitted by + * dcp_check_firmware_version(), whatever hw data its compatible matched: + * - firmware_dma_bits 41: its firmware DART's window (apple,dma-range + * <0x100 0 0x10 0>, 1 TiB + 64 GiB) takes 41 bits, as the dcpext's does. + * - num_dptx_ports 0: it drives the panel only. + * - adopt_live_session: iBoot leaves it running with the 27.2 image and the + * panel lit; Linux never starts its CPU. + * No sleep support: no firmware-27 sleep has run on this processor. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8132_v27 = { + .firmware_dma_bits = 41, + .num_dptx_ports = 0, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_V_27_0, +}; + static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { .firmware_dma_bits = 41, .num_dptx_ports = 2, @@ -7429,6 +7460,9 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t8132-dcpext")) dcp->hw = apple_dcp_hw_t8132_dcpext_v27; + if (fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dev->of_node, "apple,t8132-dcp")) + dcp->hw = apple_dcp_hw_t8132_v27; /* * A SoC with derived power words is offered the stop only when asked for, and only on * firmware 27.0, whose calls are the ones that ran with them. diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index f6264be746ca90..7ff30067ddc30d 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -50,6 +50,20 @@ static inline bool apple_dcp_image_v27_2(const struct device_node *np, compat[0] == 27 && compat[1] == 2 && compat[2] == 0; } +/* + * A T8132 internal display processor that the boot loader handed over with + * the 27.2 (26B123) image and the firmware-27 clock metadata (apple,clock-ids + * from the ADT's /arm-io/disp0): the firmware-27 backend's, not the M4 + * 26.6.2 one's. Keyed on the processor, the image and the handoff, so a main + * DCP a boot loader leaves running idle (a Mac mini's) is never adopted. + */ +static inline bool apple_t8132_dcp_v27_2(const struct device_node *np) +{ + return apple_dcp_image_v27_2(np, "apple,t8132-dcp", + APPLE_T8132_DCP_26B123_UUID) && + of_property_present(np, "apple,clock-ids"); +} + static inline bool apple_t6041_dcp_any_v27_2(const struct device_node *np, const char *compat_name) { From ffdaff64ca617cb0039596ca02795b7e66f53fa1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 07:44:44 -0500 Subject: [PATCH 0282/1514] drm/apple: keep the sleep notifier's lock a leaf, fold in the T8132 one Two gaps in the previous commit: - apple_drm_pm_lock was described as a leaf, but apple_drm_pm_notify() held it across apple_drm_resume_outputs(), which takes the hotplug, modeset, fbdev and DCP locks and clientlist_mutex. The notifier now only queues each held device's restore (pm_resume_work) on an ordered workqueue under the lock, and the restore runs from the work. The next PM_SUSPEND_PREPARE flushes the queue, outside the lock, so a restore never overlaps the next suspend; apple_drm_uninit() cancels its device's after taking it off the list. PM_POST_SUSPEND already runs after user space is thawed (suspend_finish()), so moving the restore to a work item does not change that order. - The T8132 external outputs registered and unregistered their own PM notifier from t8132_ext_drm_init()/_fini(), which run inside the same component bind and unbind, so the cycle stayed open on T8132. Their sleep handling is now t8132_ext_drm_pm_event(), called from appledrm's one notifier. It still holds t8132_ext_reg_lock throughout, so fini, which empties the registry under that lock, still waits for a call under way, as the unregister did. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/apple_drv.c | 74 +++++++++++++++++++++------ drivers/gpu/drm/apple/t8132_ext_drm.c | 54 ++++++------------- drivers/gpu/drm/apple/t8132_ext_drm.h | 6 ++- 3 files changed, 81 insertions(+), 53 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index b2a134cc66f247..12c9c34f6f66f6 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -75,21 +75,37 @@ struct apple_drm_private { bool dark_held; /* On apple_drm_pm_list while bound, for the system-sleep notifier. */ struct list_head pm_node; + /* The notifier's output restore, run outside apple_drm_pm_lock. */ + struct work_struct pm_resume_work; }; static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data); +#ifdef CONFIG_PM_SLEEP +static void apple_drm_pm_resume_work(struct work_struct *work); +#endif /* - * One system-sleep notifier for every bound display subsystem, registered at - * module init. Registering it from the component bind would take the PM - * notifier chain's rwsem under component_mutex, while a PM notifier that - * takes a lock held around a component_add() (as the Apple CIO driver's does - * with its device lock, which it holds while populating the NHI) closes a - * cycle: component_mutex -> pm_chain_head.rwsem -> acio->lock -> - * component_mutex. apple_drm_pm_lock is a leaf below both. + * One system-sleep notifier for every bound display subsystem (and for the + * T8132 external outputs), registered at module init. Registering it from the + * component bind would take the PM notifier chain's rwsem under + * component_mutex, while a PM notifier that takes a lock held around a + * component_add() (as the Apple CIO driver's does with its device lock, which + * it holds while populating the NHI) closes a cycle: component_mutex -> + * pm_chain_head.rwsem -> acio->lock -> component_mutex. + * + * apple_drm_pm_lock is a leaf: it guards apple_drm_pm_list only, and nothing + * else is taken under it. At PM_POST_SUSPEND the notifier queues each + * device's restore (pm_resume_work) on apple_drm_pm_wq under it; the restore + * itself, which takes the hotplug, modeset and DCP locks, runs from the work. + * PM_POST_SUSPEND comes after user space is thawed, as before. The next + * PM_SUSPEND_PREPARE flushes the queue, outside the lock, so a restore never + * overlaps the next suspend, and apple_drm_uninit() cancels its device's + * after taking it off the list. */ static DEFINE_MUTEX(apple_drm_pm_lock); static LIST_HEAD(apple_drm_pm_list); +/* Ordered, so the next suspend's PM_SUSPEND_PREPARE can wait for every restore. */ +static struct workqueue_struct *apple_drm_pm_wq; static struct notifier_block apple_drm_pm_nb = { .notifier_call = apple_drm_pm_notify, }; @@ -1730,6 +1746,9 @@ static int apple_drm_init(struct device *dev) return PTR_ERR(apple); INIT_LIST_HEAD(&apple->pm_node); +#ifdef CONFIG_PM_SLEEP + INIT_WORK(&apple->pm_resume_work, apple_drm_pm_resume_work); +#endif dev_set_drvdata(dev, apple); ret = drmm_mode_config_init(&apple->drm); @@ -1902,6 +1921,9 @@ static void apple_drm_uninit(struct device *dev) mutex_lock(&apple_drm_pm_lock); list_del_init(&apple->pm_node); mutex_unlock(&apple_drm_pm_lock); +#ifdef CONFIG_PM_SLEEP + cancel_work_sync(&apple->pm_resume_work); +#endif /* Before anything of the DRM device is torn down. */ t8132_ext_drm_fini(&apple->drm); @@ -2123,23 +2145,37 @@ static void apple_platform_complete(struct device *dev) } /* It failed before ->prepare() reached this device, so ->complete() didn't run either. */ +static void apple_drm_pm_resume_work(struct work_struct *work) +{ + struct apple_drm_private *apple = + container_of(work, struct apple_drm_private, pm_resume_work); + + if (apple->dark_held) { + dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); + apple_drm_resume_outputs(apple); + } +} + static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, void *data) { struct apple_drm_private *apple; + int ret; + if (action == PM_SUSPEND_PREPARE) + flush_workqueue(apple_drm_pm_wq); + + /* The T8132 external outputs' sleep handling (a no-op without them). */ + ret = t8132_ext_drm_pm_event(action); if (action != PM_POST_SUSPEND) - return NOTIFY_DONE; + return ret; mutex_lock(&apple_drm_pm_lock); - list_for_each_entry(apple, &apple_drm_pm_list, pm_node) { - if (apple->dark_held) { - dev_warn(apple->drm.dev, "dark wake over without a resume: outputs back now\n"); - apple_drm_resume_outputs(apple); - } - } + list_for_each_entry(apple, &apple_drm_pm_list, pm_node) + if (apple->dark_held) + queue_work(apple_drm_pm_wq, &apple->pm_resume_work); mutex_unlock(&apple_drm_pm_lock); - return NOTIFY_DONE; + return ret; } static const struct dev_pm_ops apple_platform_pm_ops = { @@ -2190,11 +2226,18 @@ static int __init appledrm_register(void) ret = dcp_register(); if (ret) goto unregister_audio; + apple_drm_pm_wq = alloc_ordered_workqueue("appledrm-pm", 0); + if (!apple_drm_pm_wq) { + ret = -ENOMEM; + goto unregister_dcp; + } register_pm_notifier(&apple_drm_pm_nb); ret = platform_driver_register(&apple_platform_driver); if (!ret) return 0; unregister_pm_notifier(&apple_drm_pm_nb); + destroy_workqueue(apple_drm_pm_wq); +unregister_dcp: dcp_unregister(); unregister_audio: apple_j613_display_fail(); @@ -2213,6 +2256,7 @@ static void __exit appledrm_unregister(void) dcp_unregister(); platform_driver_unregister(&apple_platform_driver); unregister_pm_notifier(&apple_drm_pm_nb); + destroy_workqueue(apple_drm_pm_wq); } module_init(appledrm_register); diff --git a/drivers/gpu/drm/apple/t8132_ext_drm.c b/drivers/gpu/drm/apple/t8132_ext_drm.c index c1fef32983069c..f37290b351669e 100644 --- a/drivers/gpu/drm/apple/t8132_ext_drm.c +++ b/drivers/gpu/drm/apple/t8132_ext_drm.c @@ -110,19 +110,19 @@ static DEFINE_SPINLOCK(t8132_ext_lock); /* Registered outputs, for t8132_ext_drm_hotplug() (t8132_ext_lock) */ static struct t8132_ext_out *t8132_ext_live[T8132_EXT_MAX]; /* - * Every output initialised, for the layer's one PM notifier, all of one DRM - * device (t8132_ext_pm_drm, the first to init; a second one's outputs get no - * sleep handling): set up by its t8132_ext_drm_init(), the notifier registered - * after them; its t8132_ext_drm_fini() unregisters it before anything is torn - * down. All under t8132_ext_reg_lock, which the notifier holds throughout: - * outermost, before any modeset lock, and never held to (un)register the - * notifier. + * Every output initialised, for the sleep handling (t8132_ext_drm_pm_event(), + * called from appledrm's one PM notifier, registered at module init), all of + * one DRM device (t8132_ext_pm_drm, the first to init; a second one's outputs + * get no sleep handling): set up by its t8132_ext_drm_init(), emptied by its + * t8132_ext_drm_fini() before anything is torn down. All under + * t8132_ext_reg_lock, which the sleep handling holds throughout, so a call + * under way finishes before fini empties the registry: outermost, before any + * modeset lock. */ static DEFINE_MUTEX(t8132_ext_reg_lock); static struct drm_device *t8132_ext_pm_drm; static struct t8132_ext_out *t8132_ext_outs[T8132_EXT_MAX]; static unsigned int t8132_ext_nouts; -static bool t8132_ext_pm_registered; static const u32 t8132_ext_formats[] = { DRM_FORMAT_XRGB8888, @@ -997,7 +997,7 @@ static void t8132_ext_sleep_end(struct t8132_ext_out *out) * no PM_POST_SUSPEND here (the chain rolls back only the notifiers before * this one): the outputs already prepared come back at once. */ -static int t8132_ext_pm_notify(struct notifier_block *nb, unsigned long event, void *unused) +int t8132_ext_drm_pm_event(unsigned long event) { unsigned long deadline; unsigned int i; @@ -1027,14 +1027,10 @@ static int t8132_ext_pm_notify(struct notifier_block *nb, unsigned long event, v return NOTIFY_DONE; } -static struct notifier_block t8132_ext_pm_nb = { - .notifier_call = t8132_ext_pm_notify, -}; - /* * First in the DRM device's unbind (and its probe's failure paths), - * before drm_dev_unregister() and any DRM object is torn down: the PM - * notifier unregistered (a call of it under way finishes first), then every + * before drm_dev_unregister() and any DRM object is torn down: the registry + * emptied for the sleep handling (a call of it under way finishes first), then every * output dying, its work cancelled, and one left in a sleep (no * PM_POST_SUSPEND will come) out of it, its connector's hold ended. Only for * the DRM device whose outputs these are; called again, nothing. @@ -1044,19 +1040,15 @@ void t8132_ext_drm_fini(struct drm_device *drm) struct t8132_ext_out *outs[T8132_EXT_MAX]; unsigned int n = 0; unsigned long flags; - bool mine, reg; + bool mine; + /* A sleep-handling call under way holds the registry lock: it finishes first. */ mutex_lock(&t8132_ext_reg_lock); mine = drm && t8132_ext_pm_drm == drm; - reg = mine && t8132_ext_pm_registered; - mutex_unlock(&t8132_ext_reg_lock); - if (!mine) + if (!mine) { + mutex_unlock(&t8132_ext_reg_lock); return; - /* Not under the registry lock: a call under way holds it. */ - if (reg) - unregister_pm_notifier(&t8132_ext_pm_nb); - mutex_lock(&t8132_ext_reg_lock); - t8132_ext_pm_registered = false; + } for (n = 0; n < t8132_ext_nouts; n++) { outs[n] = t8132_ext_outs[n]; t8132_ext_outs[n] = NULL; @@ -1176,7 +1168,7 @@ int t8132_ext_drm_init(struct drm_device *drm) struct device_node *np; unsigned int count = 0; int err; - bool mine, reg; + bool mine; int ret = 0; if (!apple_t8132_firmware_path()) @@ -1210,18 +1202,6 @@ int t8132_ext_drm_init(struct drm_device *drm) put_device(&pdev->dev); ret = ret ?: err; } - /* - * After the outputs, not under the registry lock (see there); - * unregistered first by t8132_ext_drm_fini(). - */ - mutex_lock(&t8132_ext_reg_lock); - reg = mine && t8132_ext_nouts && !t8132_ext_pm_registered; - mutex_unlock(&t8132_ext_reg_lock); - if (reg && !register_pm_notifier(&t8132_ext_pm_nb)) { - mutex_lock(&t8132_ext_reg_lock); - t8132_ext_pm_registered = true; - mutex_unlock(&t8132_ext_reg_lock); - } if (count || ret) drm_info(drm, "%u T8132 external output(s): %d\n", count, ret); return ret; diff --git a/drivers/gpu/drm/apple/t8132_ext_drm.h b/drivers/gpu/drm/apple/t8132_ext_drm.h index df79579a5e8a55..8792ced388bda7 100644 --- a/drivers/gpu/drm/apple/t8132_ext_drm.h +++ b/drivers/gpu/drm/apple/t8132_ext_drm.h @@ -4,6 +4,7 @@ #define __APPLE_T8132_EXT_DRM_H__ #include +#include #include struct device; @@ -15,7 +16,7 @@ struct drm_atomic_commit; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) int t8132_ext_drm_init(struct drm_device *drm); -/* First in the DRM device's teardown: the PM notifier and the work stopped. */ +/* First in the DRM device's teardown: the sleep handling and the work stopped. */ void t8132_ext_drm_fini(struct drm_device *drm); /* The objects of these outputs are not apple_crtc/apple_connector/apple_plane. */ bool t8132_ext_crtc(const struct drm_crtc *crtc); @@ -28,6 +29,8 @@ void t8132_ext_drm_flip_done(struct device *dcpext); /* Whether @state has one of these CRTCs, and wait for their flips. */ bool t8132_ext_drm_in_commit(struct drm_atomic_commit *state); void t8132_ext_drm_wait_flips(struct drm_atomic_commit *state); +/* System-sleep event from appledrm's PM notifier: a notifier return value. */ +int t8132_ext_drm_pm_event(unsigned long event); #else static inline int t8132_ext_drm_init(struct drm_device *drm) { return 0; } static inline void t8132_ext_drm_fini(struct drm_device *drm) { } @@ -38,6 +41,7 @@ static inline void t8132_ext_drm_hotplug(struct device *dcpext) { } static inline void t8132_ext_drm_flip_done(struct device *dcpext) { } static inline bool t8132_ext_drm_in_commit(struct drm_atomic_commit *state) { return false; } static inline void t8132_ext_drm_wait_flips(struct drm_atomic_commit *state) { } +static inline int t8132_ext_drm_pm_event(unsigned long event) { return NOTIFY_DONE; } #endif #endif From 5df68cfa2f7ecd9c9abc7407a4acc356d294ceb4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 23:10:22 +1100 Subject: [PATCH 0283/1514] selftests: apple-dcp: boot: the T8132 internal DCP's 27.2 admission Build the real apple_t8132_dcp_v27_2() into the t6041-v27-admission unit (of_property_present() mocked for apple,clock-ids) and check that the internal processor handed over with the T8132 26B123 image and its firmware-27 clocks runs the 27.2 table on either firmware path, and that without the clocks, with the T6041 image, a missing UUID or another release it is the M4 backend's on its path and nobody's off it. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/apple-dcp/boot.py | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 543e5be169698d..f05a1c835a3b75 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -204,7 +204,7 @@ def t6041_v27_admission(root): assert len(uuid_defines) == 3 helper = '\n'.join((*uuid_defines, *( block(display_h, 'static inline bool ' + name + '(') for name in ( - 'apple_dcp_image_v27_2', + 'apple_dcp_image_v27_2', 'apple_t8132_dcp_v27_2', 'apple_t6041_dcp_any_v27_2', 'apple_t6041_dcp_v27_2', 'apple_t6041_dcpext_v27_2', 'apple_t8122_dcp_v27_2')))) iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() @@ -247,6 +247,7 @@ def t6041_v27_admission(root): int fw_cells; u32 compat[3]; int compat_cells; + bool clock_ids; }; struct device { struct device_node *of_node; @@ -256,6 +257,11 @@ def t6041_v27_admission(root): { return np && np->compatible && !strcmp(np->compatible, s); } +static bool of_property_present(const struct device_node *np, const char *name) +{ + assert(!strcmp(name, "apple,clock-ids")); + return np && np->clock_ids; +} static int of_property_count_strings(const struct device_node *np, const char *name) { assert(!strcmp(name, "apple,firmware-uuid")); @@ -486,10 +492,46 @@ def t6041_v27_admission(root): node.compat[1] = 2; node.fw[2] = 1; assert(!apple_t8132_dcpext_v27_2(&node)); node.fw[2] = 0; assert(apple_t8132_dcpext_v27_2(&node)); + /* + * The internal DCP handed over with the T8132 27.2 image and its + * firmware-27 clocks (the M4 Air's on the 27.2 stub) runs the 27.2 + * table on any board and either firmware path; without the clocks it is + * the M4 backend's on its path and nobody's off it, as above. + */ + reset_t6041_26b123(false); + node.compatible = "apple,t8132-dcp"; + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.clock_ids = true; + for (unsigned path = 0; path < 2; path++) { + t8132_firmware_path = path; + assert(apple_t8132_dcp_v27_2(&node)); + assert(!apple_t8132_dcpext_v27_2(&node)); + assert(!apple_t6041_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + node.clock_ids = false; + assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == (path ? DCP_FIRMWARE_M4 : DCP_FIRMWARE_UNKNOWN)); + node.clock_ids = true; + } + t8132_firmware_path = true; + /* Not on a dcpext, nor with the T6041 image, a missing UUID or another release. */ + node.compatible = "apple,t8132-dcpext"; assert(!apple_t8132_dcp_v27_2(&node)); + node.compatible = "apple,t8132-dcp"; + node.uuid = APPLE_T6041_DCP_26B123_UUID; assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + node.uuid = APPLE_T8132_DCP_26B123_UUID; + node.uuid_count = 0; assert(!apple_t8132_dcp_v27_2(&node)); + node.uuid_count = 1; + node.compat[1] = 0; assert(!apple_t8132_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); + node.compat[1] = 2; assert(apple_t8132_dcp_v27_2(&node)); + t8132_firmware_path = false; + dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); puts("PASS T8132 M4 backend only on its firmware path; a T8132 dcpext on the 27.2 image runs the 27.2 table on any board"); + puts("PASS T8132 internal DCP with the 27.2 image and its firmware-27 clocks runs the 27.2 table; without them nothing changes"); return 0; } ''' From 8ef008a54e20e5346f48a153851cd52e7646f13c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 01:59:06 +1100 Subject: [PATCH 0284/1514] iommu: apple-dart: keep a 27.2 J713 internal display DART's locked roots like T6041's On the macOS 27.2 stub the M4 MacBook Air's internal display processor runs the 26B123 image and the firmware-27 backend. That backend DMAs through ordinary IOMMU domains: RTKit and IOMFB shared memory on SID23, PIODMA maps on SID16, scan-out on SID0. The borrowed J713 display path cannot serve it. It admits only the 26.6.2 layout, so the DCP is left without any IOMMU domain, and it reserves the whole SID23 window from generic DMA for the M4 backend's own allocators. When the internal DCP was handed over with the 27.2 image and its firmware-27 clocks (apple_t8132_dcp_v27_2()), do not borrow its two display DARTs. Give them the locked-root handling T6041's display DARTs get on firmware 27 (fw_mirror): the firmware's live slots are kept and Linux's mappings go into the rest. Refuse the DART if it is not locked as expected. Nothing changes for a DCP on its 26.6.2 handoff, or for a 27.2 one without the firmware-27 clocks (the default Stage 2 hands it over without them). Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 24 ++++++++++++++++++++++-- include/linux/soc/apple/t8132.h | 17 +++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 33a29ce9beb045..e4efde6868029d 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -5361,7 +5361,7 @@ static int apple_dart_probe(struct platform_device *pdev) bool tunneled = dev->of_node->parent && of_node_name_prefix(dev->of_node->parent, "usb4-pcie-tunnel-"); - bool j713_display, j713_dcpext, j713_dispext, j713_radio; + bool j713_display, j713_dcpext, j713_dispext, j713_radio, j713_display_v27 = false; /* * The M4 internal display DARTs are live: DCP firmware (SID23) @@ -5372,6 +5372,18 @@ static int apple_dart_probe(struct platform_device *pdev) j713_display = res && !tunneled && apple_t8132_firmware_path() && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL); + /* + * The internal DCP handed over with the 27.2 image runs the firmware-27 + * backend, which DMAs through ordinary domains (RTKit and IOMFB shared + * memory, PIODMA maps) as on T6041. Its two display DARTs are then not + * borrowed: they keep their firmware's locked roots the way T6041's do + * (fw_mirror below). The borrowed path admits only the 26.6.2 layout + * and reserves its whole SID23 window from generic DMA. + */ + if (j713_display && apple_t8132_internal_dcp_v27_2()) { + j713_display = false; + j713_display_v27 = true; + } /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ j713_dcpext = res && !tunneled && apple_t8132_firmware_path() && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && @@ -5889,7 +5901,15 @@ static int apple_dart_probe(struct platform_device *pdev) (of_device_is_compatible(dev->of_node, "apple,t6041-dart") || of_device_is_compatible(dev->of_node, "apple,t6050-dart") || of_device_is_compatible(dev->of_node, "apple,t8140-dart") || - of_device_is_compatible(dev->of_node, "apple,t8142-dart")); + of_device_is_compatible(dev->of_node, "apple,t8142-dart") || + j713_display_v27); + if (j713_display_v27) + dev_info(dev, "J713 internal display DART on the 27.2 image: locked roots kept (%s)\n", + dart->fw_mirror ? "mirror" : "NOT locked: refusing"); + if (j713_display_v27 && !dart->fw_mirror) { + ret = -EINVAL; + goto err_clk_disable; + } /* * J614s may arrive with the MTP live after the boot keyboard used it. * Do not reset its DART unless there is no advertised handoff. diff --git a/include/linux/soc/apple/t8132.h b/include/linux/soc/apple/t8132.h index 72ece899b148a8..d47cfe0a13e13a 100644 --- a/include/linux/soc/apple/t8132.h +++ b/include/linux/soc/apple/t8132.h @@ -55,6 +55,23 @@ static inline bool apple_t8132_firmware_path(void) return apple_t8132_air() || apple_t8132_qualified_firmware(); } +/* + * The available internal display processor was handed over with the 27.2 + * image and its firmware-27 clocks (apple_t8132_dcp_v27_2()): it runs the + * firmware-27 backend, whose DMA needs ordinary IOMMU domains. + */ +static inline bool apple_t8132_internal_dcp_v27_2(void) +{ + struct device_node *np; + bool v27 = false; + + for_each_compatible_node(np, NULL, "apple,t8132-dcp") { + if (of_device_is_available(np) && apple_t8132_dcp_v27_2(np)) + v27 = true; + } + return v27; +} + /* * A T8132 external display processor handed over with the 27.2 image * (first on the Mac mini, J773g): it runs the firmware-27 backend From 8644419127e6d3272698de4ebeebbe7e2caab53c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 02:23:14 +1100 Subject: [PATCH 0285/1514] iommu: apple-dart: map a 27.2 J713 display DART's firmware segments as its leaves do On the J713's 27.2 handoff the internal display DARTs keep their firmware's locked roots (fw_mirror). A Linux table in a slot the firmware holds must then mirror the firmware's leaves exactly, protection included (apple_dart_fw_slot_mirrors()). The boot loader re-exports the firmware's own segments as iommu-addresses, and the core maps those read-write, and uncached for this non-coherent DCP. The live leaves differ: the firmware's text is read-only, and all of its segments are cacheable (SID23 dump on the 27.2 stub: __TEXT flags 0x5, __DATA and the four other segments 0x1). As it stood, the DCP's attach would refuse every segment and leave the processor without a domain. For such a DART, give each translated region the protection the live leaves give every one of its pages. A region whose pages are not mapped there, map elsewhere or disagree keeps its protection, and the attach then refuses it as before. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 94 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index e4efde6868029d..2745ab0b96a5a5 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -426,6 +426,8 @@ struct apple_dart { u32 sleep_gated : 1; /* Locked roots may hold firmware slots that mirror Linux mappings. */ u32 fw_mirror : 1; + /* A J713 internal display DART on the 27.2 image (fw_mirror, not borrowed). */ + u32 j713_v27 : 1; /* * fw_mirror's four-level locked roots hold firmware's own subtrees, which * are recorded and reserved (apple_dart_snapshot_fw_tree()). Set only for @@ -4562,6 +4564,96 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, } } +/* + * A J713 internal display DART on the 27.2 image (fw_mirror): the boot loader + * re-exports the firmware's own segments as iommu-addresses, which the core + * maps read-write, and uncached for this non-coherent DCP. The firmware's + * leaves say what those pages are: its text read-only, all of it cacheable. + * A Linux table in a slot the firmware holds must mirror its leaves exactly + * (apple_dart_fw_slot_mirrors()), so give each such region the protection the + * live leaves give every one of its pages. A region whose pages are not mapped + * there, map elsewhere or disagree keeps its protection, and the attach then + * refuses it as before. + */ +static void apple_dart_j713_v27_fw_prot(struct device *dev, struct list_head *head) +{ + struct apple_dart_master_cfg *cfg = dev_iommu_priv_get(dev); + const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; + struct iommu_resv_region *region; + struct apple_dart *dart; + size_t entries; + u64 *root; + u32 ttbr; + int sid; + + if (!cfg || !cfg->stream_maps[0].dart || cfg->stream_maps[1].dart) + return; + dart = cfg->stream_maps[0].dart; + if (!dart->j713_v27 || !dart->locked || dart->hw->fmt != APPLE_DART2) + return; + entries = dart->pgsize / sizeof(u64); + sid = find_first_bit(cfg->stream_maps[0].sidmap, dart->num_streams); + if (sid >= dart->num_streams || + bitmap_weight(cfg->stream_maps[0].sidmap, dart->num_streams) != 1) + return; + if (pm_runtime_resume_and_get(dart->dev) < 0) + return; + ttbr = apple_dart_readl(dart, DART_TTBR(dart, sid, 0)); + pm_runtime_put(dart->dev); + if (!(ttbr & dart->hw->ttbr_valid) || + (dart->hw->tcr_4level && + (apple_dart_readl(dart, DART_TCR(dart, sid)) & dart->hw->tcr_4level))) + return; + ttbr &= ~dart->hw->ttbr_valid; + if (dart->hw->ttbr_addr_field_shift) + ttbr >>= dart->hw->ttbr_addr_field_shift; + root = memremap(((phys_addr_t)ttbr) << dart->hw->ttbr_shift, dart->pgsize, MEMREMAP_WB); + if (!root) + return; + + list_for_each_entry(region, head, list) { + u64 *leaf = NULL; + size_t mapped_slot = entries; + int prot = -1; + + if (region->type != IOMMU_RESV_TRANSLATED || !region->length || + !IS_ALIGNED(region->dva | region->start | region->length, dart->pgsize)) + continue; + for (u64 off = 0; off < region->length; off += dart->pgsize) { + u64 dva = region->dva + off; /* bits 14..35: the 1 TiB base drops out */ + size_t slot = (dva >> (ilog2(dart->pgsize) + ilog2(entries))) & (entries - 1); + size_t idx = (dva >> ilog2(dart->pgsize)) & (entries - 1); + u64 entry = READ_ONCE(root[slot]); + phys_addr_t phys; + int page_prot; + + if (slot != mapped_slot) { + if (leaf) + memunmap(leaf); + leaf = (entry & APPLE_DART_PTE_VALID) ? + memremap(apple_dart_pte_to_paddr(dart, entry), dart->pgsize, + MEMREMAP_WB) : NULL; + mapped_slot = slot; + } + if (!leaf || + !apple_dart_fw_leaf_decode(READ_ONCE(leaf[idx]), 0, &phys, &page_prot) || + phys != region->start + off || (prot >= 0 && page_prot != prot)) { + prot = -1; + break; + } + prot = page_prot; + } + if (leaf) + memunmap(leaf); + if (prot >= 0 && (region->prot & mask) != (prot & mask)) { + dev_info(dev, "firmware segment %pad+%#zx: protection %#x as its live leaves (asked %#x)\n", + ®ion->dva, region->length, prot & mask, region->prot & mask); + region->prot = (region->prot & ~mask) | (prot & mask); + } + } + memunmap(root); +} + static void apple_dart_get_resv_regions(struct device *dev, struct list_head *head) { @@ -4591,6 +4683,7 @@ static void apple_dart_get_resv_regions(struct device *dev, /* Keep the translated-domain requirement and inherited translations. */ iommu_dma_get_resv_regions(dev, head); + apple_dart_j713_v27_fw_prot(dev, head); apple_dart_get_fw_resv_regions(dev, head); } @@ -5906,6 +5999,7 @@ static int apple_dart_probe(struct platform_device *pdev) if (j713_display_v27) dev_info(dev, "J713 internal display DART on the 27.2 image: locked roots kept (%s)\n", dart->fw_mirror ? "mirror" : "NOT locked: refusing"); + dart->j713_v27 = j713_display_v27; if (j713_display_v27 && !dart->fw_mirror) { ret = -EINVAL; goto err_clk_disable; From e7ae9f620403069df052bd25c1c4cfbc243af117 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 03:51:17 +1100 Subject: [PATCH 0286/1514] arm64: dts: apple: t8132-j713: describe the internal panel The firmware-27 DCP backend takes the internal connector type (eDP) and the backlight range from the DCP's apple,panel child. The M4 26.6.2 backend never needed one, so the J713 has none, and on the 27.2 stub its panel comes up as an 'Unknown' connector without a backlight device. Describe the panel as on the other Airs: 2560x1664 at 224 ppi, 64 notch rows above the desktop, and the published 500 nits maximum. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j713.dts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-j713.dts b/arch/arm64/boot/dts/apple/t8132-j713.dts index 440ecff14d4a1e..e445896854733f 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713.dts +++ b/arch/arm64/boot/dts/apple/t8132-j713.dts @@ -195,6 +195,15 @@ &dcp { apple,pmc-interface = <&pmc_disp0>; + + panel: panel { + compatible = "apple,panel-j713", "apple,panel"; + /* 2560x1664 at 224 ppi; 64 notch rows above the desktop. */ + width-mm = <290>; + height-mm = <189>; + adj-height-mm = <181>; + apple,max-brightness = <500>; + }; }; /* From 0a33a0855d1386724d9dbd93e395105968fbc2f0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 04:31:10 +1100 Subject: [PATCH 0287/1514] iommu: apple-dart: test the 27.2 J713 firmware segment protection Split the region walk from its device lookup and test it on a fake locked root: read-only text pages and read-write data pages take the protection of the leaves that map them (cacheable), a region whose leaf maps another page keeps what it asked for, and nothing changes on a DART that is not a 27.2 J713 display DART. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 73 +++++++++++++++++++++++++++++++++ drivers/iommu/apple-dart.c | 9 +++- 2 files changed, 80 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 0c474454ee82a3..2c4096903db0f5 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1326,6 +1326,78 @@ static void apple_dart_test_host_power_tables(struct kunit *test) } #endif +/* + * A 27.2 J713 display DART: re-exported firmware segments take the protection + * of the live leaves that map them (read-only text, cacheable data); a region + * whose leaf maps another page keeps what it asked for. + */ +static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) +{ + const u64 fields = GENMASK_ULL(51, 40) | BIT_ULL(0); + const phys_addr_t text_pa = 0x80000000ULL, data_pa = 0x80100000ULL; + const u64 dva = 0x10000000000ULL + (3ULL << 25); + struct iommu_resv_region text = {}, data = {}, moved = {}; + struct apple_dart_master_cfg master = {}; + struct apple_dart *dart; + LIST_HEAD(head); + u64 *root, *leaf; + void *regs; + + if (PAGE_SIZE < SZ_16K) + kunit_skip(test, "needs kernel pages of at least 16 KiB"); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->dev = kunit_device_register(test, "apple-dart-j713-v27-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); + regs = vzalloc(APPLE_DART_TEST_REGS_SIZE); + KUNIT_ASSERT_NOT_NULL(test, regs); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_dart_test_vfree, regs), 0); + dart->regs = (__force void __iomem *)regs; + dart->hw = &apple_dart_hw_t8110; + dart->pgsize = SZ_16K; + dart->num_streams = 32; + dart->locked = true; + dart->fw_mirror = true; + dart->j713_v27 = true; + root = kunit_kzalloc(test, SZ_16K, GFP_KERNEL); + leaf = kunit_kzalloc(test, SZ_16K, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, root); + KUNIT_ASSERT_NOT_NULL(test, leaf); + KUNIT_ASSERT_TRUE(test, IS_ALIGNED(virt_to_phys(root) | virt_to_phys(leaf), SZ_16K)); + writel(((virt_to_phys(root) >> dart->hw->ttbr_shift) << dart->hw->ttbr_addr_field_shift) | + dart->hw->ttbr_valid, dart->regs + DART_TTBR(dart, 23, 0)); + root[3] = (virt_to_phys(leaf) >> 4) | BIT_ULL(0); + /* Text: two read-only pages; data: one read-write page; all cacheable. */ + leaf[0] = fields | (text_pa >> 4) | BIT_ULL(2); + leaf[1] = fields | ((text_pa + SZ_16K) >> 4) | BIT_ULL(2); + leaf[2] = fields | (data_pa >> 4); + text = (struct iommu_resv_region){ .start = text_pa, .dva = dva, .length = SZ_32K, + .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + data = (struct iommu_resv_region){ .start = data_pa, .dva = dva + SZ_32K, .length = SZ_16K, + .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + moved = (struct iommu_resv_region){ .start = data_pa + SZ_16K, .dva = dva + SZ_32K, + .length = SZ_16K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + list_add_tail(&text.list, &head); + list_add_tail(&data.list, &head); + list_add_tail(&moved.list, &head); + master.stream_maps[0].dart = dart; + __set_bit(23, master.stream_maps[0].sidmap); + pm_runtime_set_active(dart->dev); + pm_runtime_enable(dart->dev); + + __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); + KUNIT_EXPECT_EQ(test, data.prot, IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); + KUNIT_EXPECT_EQ(test, moved.prot, IOMMU_READ | IOMMU_WRITE); + + /* Not a 27.2 J713 display DART: nothing changes. */ + text.prot = IOMMU_READ | IOMMU_WRITE; + dart->j713_v27 = false; + __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + pm_runtime_disable(dart->dev); +} + static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_strict_engines), KUNIT_CASE(apple_dart_test_topology), @@ -1335,6 +1407,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_locked_handoff), KUNIT_CASE(apple_dart_test_sync_unknown_roots), KUNIT_CASE(apple_dart_test_firmware_roots), + KUNIT_CASE(apple_dart_test_j713_v27_fw_prot), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 2745ab0b96a5a5..fef15eeb7da579 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -4575,9 +4575,9 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, * there, map elsewhere or disagree keeps its protection, and the attach then * refuses it as before. */ -static void apple_dart_j713_v27_fw_prot(struct device *dev, struct list_head *head) +static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, struct device *dev, + struct list_head *head) { - struct apple_dart_master_cfg *cfg = dev_iommu_priv_get(dev); const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; struct iommu_resv_region *region; struct apple_dart *dart; @@ -4654,6 +4654,11 @@ static void apple_dart_j713_v27_fw_prot(struct device *dev, struct list_head *he memunmap(root); } +static void apple_dart_j713_v27_fw_prot(struct device *dev, struct list_head *head) +{ + __apple_dart_j713_v27_fw_prot(dev_iommu_priv_get(dev), dev, head); +} + static void apple_dart_get_resv_regions(struct device *dev, struct list_head *head) { From a50a201754a2b67cf0a16be65d231c47d12c2c42 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:43:46 +1100 Subject: [PATCH 0288/1514] iommu: apple-dart: read a 27.2 J713 DART's firmware leaves only from its tables, in its window The live-leaf protection for a 27.2 J713 internal display DART's firmware segments memremaps the stream's root straight from TTBR, and each leaf table straight from its root entry, write-back. The rest of the driver maps a firmware table only after apple_dart_fw_table_decode() has checked it: a table entry with no stray bits, naming reserved RAM. An entry that named a device's registers would get a Normal write-back mapping here. The leaf slot also comes from DVA bits 14..35 alone, so a region outside the stream's 64 GiB window aliases into it. The physical address match made that harmless, but the region should not be looked up at all. Map the root only when it is a firmware table in reserved RAM, decode each leaf table entry with apple_dart_fw_table_decode(), and skip a region that does not lie inside the stream's window (locked_window, the DART's apple,dma-range until a domain attaches: 64 GiB at 1 TiB on the display DARTs). A skipped region keeps the protection it asked for, and the attach refuses it as before. KUnit: the tables are now reserved pages; new cases for a region whose two pages have different protections, a region 64 GiB above the window, and a leaf table outside reserved RAM. All three stay unchanged. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 50 +++++++++++++++++++++++++++++---- drivers/iommu/apple-dart.c | 21 ++++++++++---- 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 2c4096903db0f5..6ebc214842b2c1 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1326,6 +1326,26 @@ static void apple_dart_test_host_power_tables(struct kunit *test) } #endif +/* A zeroed 16 KiB page marked reserved, as the firmware's tables are. */ +static void apple_dart_test_free_reserved(void *data) +{ + struct page *page = data; + + ClearPageReserved(page); + __free_pages(page, get_order(SZ_16K)); +} + +static u64 *apple_dart_test_reserved_table(struct kunit *test) +{ + struct page *page = alloc_pages(GFP_KERNEL | __GFP_ZERO, get_order(SZ_16K)); + + KUNIT_ASSERT_NOT_NULL(test, page); + SetPageReserved(page); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_dart_test_free_reserved, page), + 0); + return page_address(page); +} + /* * A 27.2 J713 display DART: re-exported firmware segments take the protection * of the live leaves that map them (read-only text, cacheable data); a region @@ -1336,7 +1356,7 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) const u64 fields = GENMASK_ULL(51, 40) | BIT_ULL(0); const phys_addr_t text_pa = 0x80000000ULL, data_pa = 0x80100000ULL; const u64 dva = 0x10000000000ULL + (3ULL << 25); - struct iommu_resv_region text = {}, data = {}, moved = {}; + struct iommu_resv_region text = {}, data = {}, moved = {}, mixed = {}, outside = {}; struct apple_dart_master_cfg master = {}; struct apple_dart *dart; LIST_HEAD(head); @@ -1356,13 +1376,14 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) dart->hw = &apple_dart_hw_t8110; dart->pgsize = SZ_16K; dart->num_streams = 32; + dart->oas = 42; dart->locked = true; dart->fw_mirror = true; dart->j713_v27 = true; - root = kunit_kzalloc(test, SZ_16K, GFP_KERNEL); - leaf = kunit_kzalloc(test, SZ_16K, GFP_KERNEL); - KUNIT_ASSERT_NOT_NULL(test, root); - KUNIT_ASSERT_NOT_NULL(test, leaf); + /* The display DARTs' window: 64 GiB at 1 TiB. */ + dart->locked_window[23] = 0x10000000000ULL; + root = apple_dart_test_reserved_table(test); + leaf = apple_dart_test_reserved_table(test); KUNIT_ASSERT_TRUE(test, IS_ALIGNED(virt_to_phys(root) | virt_to_phys(leaf), SZ_16K)); writel(((virt_to_phys(root) >> dart->hw->ttbr_shift) << dart->hw->ttbr_addr_field_shift) | dart->hw->ttbr_valid, dart->regs + DART_TTBR(dart, 23, 0)); @@ -1371,15 +1392,25 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) leaf[0] = fields | (text_pa >> 4) | BIT_ULL(2); leaf[1] = fields | ((text_pa + SZ_16K) >> 4) | BIT_ULL(2); leaf[2] = fields | (data_pa >> 4); + /* Two pages that disagree: one read-only, one read-write. */ + leaf[4] = fields | ((data_pa + SZ_32K) >> 4) | BIT_ULL(2); + leaf[5] = fields | ((data_pa + SZ_32K + SZ_16K) >> 4); text = (struct iommu_resv_region){ .start = text_pa, .dva = dva, .length = SZ_32K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; data = (struct iommu_resv_region){ .start = data_pa, .dva = dva + SZ_32K, .length = SZ_16K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; moved = (struct iommu_resv_region){ .start = data_pa + SZ_16K, .dva = dva + SZ_32K, .length = SZ_16K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + mixed = (struct iommu_resv_region){ .start = data_pa + SZ_32K, .dva = dva + SZ_64K, + .length = SZ_32K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; + /* 64 GiB higher: the same slot bits, outside the window. */ + outside = (struct iommu_resv_region){ .start = text_pa, .dva = dva + SZ_64G, + .length = SZ_32K, .prot = IOMMU_READ | IOMMU_WRITE, .type = IOMMU_RESV_TRANSLATED }; list_add_tail(&text.list, &head); list_add_tail(&data.list, &head); list_add_tail(&moved.list, &head); + list_add_tail(&mixed.list, &head); + list_add_tail(&outside.list, &head); master.stream_maps[0].dart = dart; __set_bit(23, master.stream_maps[0].sidmap); pm_runtime_set_active(dart->dev); @@ -1389,6 +1420,15 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, data.prot, IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, moved.prot, IOMMU_READ | IOMMU_WRITE); + KUNIT_EXPECT_EQ(test, mixed.prot, IOMMU_READ | IOMMU_WRITE); + KUNIT_EXPECT_EQ(test, outside.prot, IOMMU_READ | IOMMU_WRITE); + + /* A leaf table outside reserved RAM is never mapped: nothing changes. */ + text.prot = IOMMU_READ | IOMMU_WRITE; + ClearPageReserved(virt_to_page(leaf)); + __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + SetPageReserved(virt_to_page(leaf)); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); /* Not a 27.2 J713 display DART: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index fef15eeb7da579..bf2c7a2d3c68e8 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -4581,8 +4581,9 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; struct iommu_resv_region *region; struct apple_dart *dart; + phys_addr_t table; + u64 *root, span, base; size_t entries; - u64 *root; u32 ttbr; int sid; @@ -4607,9 +4608,16 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str ttbr &= ~dart->hw->ttbr_valid; if (dart->hw->ttbr_addr_field_shift) ttbr >>= dart->hw->ttbr_addr_field_shift; - root = memremap(((phys_addr_t)ttbr) << dart->hw->ttbr_shift, dart->pgsize, MEMREMAP_WB); + table = ((phys_addr_t)ttbr) << dart->hw->ttbr_shift; + /* Only a firmware table in reserved RAM is mapped write-back, as elsewhere. */ + if (!apple_dart_fw_table_ram(dart, table)) + return; + root = memremap(table, dart->pgsize, MEMREMAP_WB); if (!root) return; + /* A three-level root walks one span of the stream's window (DVA bits 14..35). */ + span = BIT_ULL(ilog2(dart->pgsize) + 2 * ilog2(entries)); + base = READ_ONCE(dart->locked_window[sid]) & ~(span - 1); list_for_each_entry(region, head, list) { u64 *leaf = NULL; @@ -4619,6 +4627,10 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str if (region->type != IOMMU_RESV_TRANSLATED || !region->length || !IS_ALIGNED(region->dva | region->start | region->length, dart->pgsize)) continue; + /* Outside the window the slot bits would alias another region's leaves. */ + if (region->dva < base || region->length > span || + region->dva - base > span - region->length) + continue; for (u64 off = 0; off < region->length; off += dart->pgsize) { u64 dva = region->dva + off; /* bits 14..35: the 1 TiB base drops out */ size_t slot = (dva >> (ilog2(dart->pgsize) + ilog2(entries))) & (entries - 1); @@ -4630,9 +4642,8 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str if (slot != mapped_slot) { if (leaf) memunmap(leaf); - leaf = (entry & APPLE_DART_PTE_VALID) ? - memremap(apple_dart_pte_to_paddr(dart, entry), dart->pgsize, - MEMREMAP_WB) : NULL; + leaf = apple_dart_fw_table_decode(dart, entry, &table) ? + memremap(table, dart->pgsize, MEMREMAP_WB) : NULL; mapped_slot = slot; } if (!leaf || From fb8640635285e3d9bbd9ec90a767760bddf59d0c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:43:47 +1100 Subject: [PATCH 0289/1514] iommu: apple-dart: log a refused 27.2 J713 display DART as an error A 27.2 J713 internal display DART that the boot loader did not leave locked is refused (-EINVAL), but the line saying so was logged with dev_info() as one of two cases of the same message. Log the refusal with dev_err() on its own. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bf2c7a2d3c68e8..4b8623e2388160 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -6012,9 +6012,10 @@ static int apple_dart_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8140-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-dart") || j713_display_v27); - if (j713_display_v27) - dev_info(dev, "J713 internal display DART on the 27.2 image: locked roots kept (%s)\n", - dart->fw_mirror ? "mirror" : "NOT locked: refusing"); + if (j713_display_v27 && dart->fw_mirror) + dev_info(dev, "J713 internal display DART on the 27.2 image: locked roots kept (mirror)\n"); + else if (j713_display_v27) + dev_err(dev, "J713 internal display DART on the 27.2 image: NOT locked: refusing\n"); dart->j713_v27 = j713_display_v27; if (j713_display_v27 && !dart->fw_mirror) { ret = -EINVAL; From 8469fa3e58d28b3b83aff7dd579f9231a7a8f722 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:43:47 +1100 Subject: [PATCH 0290/1514] drm/apple: dcp: keep the J773g dcpext comment next to its code The T8132 internal DCP's 27.2 case in dcp_check_firmware_version() sat between the J773g dcpext comment ("ASSUMED, NOT TRACED") and the code that comment describes. Move it below that code; the two predicates match different compatibles, so the order changes nothing. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b5d03469575e81..e2c96564e6763c 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6027,13 +6027,19 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) * 27.2 driving the mini's dcpext0 has to confirm the A4xx/A5xx IDs * before this is relied on. */ + if (apple_t8132_dcpext_v27_2(dev->of_node)) { + /* Checked by apple_t8132_dcpext_v27_2(). */ + dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); + return dcp_v27_method_table(dev, compat_str); + } + /* * The T8132 internal panel's processor on the macOS 27.2 stub, handed * over by the boot loader with the 26B123 image (see * apple_t8132_dcp_v27_2()): the firmware-27 backend with the 27.2 * method table. That this image numbers its IOMFB methods as the * T6041 and T8142 26B123 images do is the same assumption the J773g - * dcpext case below makes. + * dcpext case above makes. */ if (apple_t8132_dcp_v27_2(dev->of_node)) { /* Checked by apple_t8132_dcp_v27_2(). */ @@ -6041,12 +6047,6 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); } - if (apple_t8132_dcpext_v27_2(dev->of_node)) { - /* Checked by apple_t8132_dcpext_v27_2(). */ - dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - return dcp_v27_method_table(dev, compat_str); - } - if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { From cd2c258d81592ca17d0a91d1f05f56ced56a0f71 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 23:58:01 +1100 Subject: [PATCH 0291/1514] iommu: apple-dart: key a 27.2 internal display DART on its processor's handoff A T8132 DART took the firmware-27 path for the internal display when it sat at one of the two J713 internal display DART addresses on the M4 firmware path and any available internal DCP anywhere was handed over with the 27.2 image (apple_t8132_internal_dcp_v27_2(), a global scan). The address list and the scan say nothing about whether this DART belongs to that processor. Ask the DART's own user instead: a T8132 DART is a 27.2 internal display DART when an available apple,t8132-dcp that the boot loader handed over with the 27.2 image (apple_t8132_dcp_v27_2(): image, firmware version and its firmware-27 clocks) names it, in its own iommus (the firmware DART) or in a child's (the PIODMA's display DART). Such a DART also skips the "leave it untouched off the qualified firmware" refusal, which is keyed on the same addresses: its processor was handed over. On the J713 the same two DARTs qualify as before. Another M4 whose internal DCP is handed over with the 27.2 image and its clocks now gets its DARTs on the same path instead of the backend running on DARTs left on the borrowed path. The 26.6.2 path and its address keys are unchanged. apple_t8132_internal_dcp_v27_2() has no users left. Link: https://github.com/aurora-silicon/linux/issues/2621 Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 52 +++++++++++++++++++++++++++++---- include/linux/soc/apple/t8132.h | 17 ----------- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 4b8623e2388160..34e169ec0c26f2 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -5458,6 +5458,46 @@ static bool apple_dart_is_available(struct device_node *np) return false; } +/* Whether @consumer names @dart_np in its iommus. */ +static bool apple_dart_np_is_iommu_of(const struct device_node *consumer, + const struct device_node *dart_np) +{ + struct of_phandle_args args; + + for (int i = 0; !of_parse_phandle_with_args(consumer, "iommus", "#iommu-cells", i, &args); + i++) { + bool match = args.np == dart_np; + + of_node_put(args.np); + if (match) + return true; + } + return false; +} + +/* + * Whether @dart_np serves an available T8132 internal display processor the + * boot loader handed over with the 27.2 image (apple_t8132_dcp_v27_2()): its + * firmware DART (the processor's iommus) or its display DART (its PIODMA's). + * The DART is keyed on the handoff of the processor that uses it, not on its + * address or on the board. + */ +static bool apple_dart_serves_t8132_dcp_v27(const struct device_node *dart_np) +{ + struct device_node *np, *child; + bool serves = false; + + for_each_compatible_node(np, NULL, "apple,t8132-dcp") { + if (serves || !of_device_is_available(np) || !apple_t8132_dcp_v27_2(np)) + continue; + serves = apple_dart_np_is_iommu_of(np, dart_np); + for_each_child_of_node(np, child) + if (!serves && apple_dart_np_is_iommu_of(child, dart_np)) + serves = true; + } + return serves; +} + static int apple_dart_probe(struct platform_device *pdev) { int ret, sid; @@ -5489,10 +5529,11 @@ static int apple_dart_probe(struct platform_device *pdev) * (fw_mirror below). The borrowed path admits only the 26.6.2 layout * and reserves its whole SID23 window from generic DMA. */ - if (j713_display && apple_t8132_internal_dcp_v27_2()) { + j713_display_v27 = res && !tunneled && + of_device_is_compatible(dev->of_node, "apple,t8132-dart") && + apple_dart_serves_t8132_dcp_v27(dev->of_node); + if (j713_display_v27) j713_display = false; - j713_display_v27 = true; - } /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ j713_dcpext = res && !tunneled && apple_t8132_firmware_path() && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && @@ -5508,9 +5549,10 @@ static int apple_dart_probe(struct platform_device *pdev) res->start == 0x490000000ULL; /* * Off the qualified firmware nothing hands the internal display DARTs - * over, but the running DCP still uses them: never reset them. + * over, but the running DCP still uses them: never reset them. A DART + * whose processor was handed over with the 27.2 image is handed over. */ - if (res && !tunneled && !apple_t8132_firmware_path() && + if (res && !tunneled && !j713_display_v27 && !apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { diff --git a/include/linux/soc/apple/t8132.h b/include/linux/soc/apple/t8132.h index d47cfe0a13e13a..72ece899b148a8 100644 --- a/include/linux/soc/apple/t8132.h +++ b/include/linux/soc/apple/t8132.h @@ -55,23 +55,6 @@ static inline bool apple_t8132_firmware_path(void) return apple_t8132_air() || apple_t8132_qualified_firmware(); } -/* - * The available internal display processor was handed over with the 27.2 - * image and its firmware-27 clocks (apple_t8132_dcp_v27_2()): it runs the - * firmware-27 backend, whose DMA needs ordinary IOMMU domains. - */ -static inline bool apple_t8132_internal_dcp_v27_2(void) -{ - struct device_node *np; - bool v27 = false; - - for_each_compatible_node(np, NULL, "apple,t8132-dcp") { - if (of_device_is_available(np) && apple_t8132_dcp_v27_2(np)) - v27 = true; - } - return v27; -} - /* * A T8132 external display processor handed over with the 27.2 image * (first on the Mac mini, J773g): it runs the firmware-27 backend From a912b89b3c469d92a3dd00c9a812533fd053fa42 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 04:53:07 +1100 Subject: [PATCH 0292/1514] drm/apple: let a 27.2 T8132 internal DCP join the DRM device on any board dcp_check_firmware_version() runs a T8132 internal DCP that the boot loader handed over with the 27.2 image and its firmware-27 clocks on the firmware-27 backend wherever it is (apple_t8132_dcp_v27_2(): processor, image and handoff). apple_dcp_usable() still kept every apple,t8132-dcp out of the component match unless apple_t8132_firmware_path() held, which off 26.6.2 is true only for the J713/J715 board names. An M4 MacBook Pro handed over the same way would have probed and never bound. Admit it on the same handoff predicate. Nothing changes on the Airs (already on the path), on 26.6.2, or for a DCP without the 27.2 image or its clocks (a Mac mini's parked main DCP stays out). The t6041-v27-admission host unit now runs apple_dcp_usable() for the T8132 internal DCP and dcpext on both paths and asserts it names no machine; the readiness unit stubs the new helper as unreachable. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 8 +++-- .../selftests/drivers/gpu/apple-dcp/boot.py | 34 ++++++++++++++++++- .../drivers/gpu/apple-dcp/lifecycle.py | 2 ++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index de0dbb7a597651..b7ed049c04c647 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1502,11 +1502,13 @@ static bool apple_dcp_usable(struct device_node *np) (!of_device_is_compatible(np, "apple,t6041-dcpext") || dcp_t6041_ext_enabled()) && /* - * The T8132 main DCP is the M4 backend's, on its 26.6.2 - * firmware path only (see dcp_check_firmware_version()). + * The T8132 main DCP is the M4 backend's on its 26.6.2 + * firmware path, and the firmware-27 backend's wherever the + * boot loader handed it over with the 27.2 image and its + * clocks, on any board (see dcp_check_firmware_version()). */ (!of_device_is_compatible(np, "apple,t8132-dcp") || - apple_t8132_firmware_path()) && + apple_t8132_firmware_path() || apple_t8132_dcp_v27_2(np)) && /* * A T8132 dcpext the M4 backend adopts is no component: its * outputs are t8132_ext_drm.c's. One on the 27.2 image is a pipe. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index f05a1c835a3b75..a4e244caf8f28e 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -224,6 +224,11 @@ def t6041_v27_admission(root): t8132_h = (root / 'include/linux/soc/apple/t8132.h').read_text() t8132_admission = block(t8132_h, 'static inline bool apple_t8132_dcpext_v27_2(') assert 'of_machine_is_compatible' not in t8132_admission + # Which processors join the DRM device: the T8132 internal DCP on the 27.2 image joins + # off the M4 backend's firmware path too, decided by the same handoff, not the board. + drv_c = (root / 'drivers/gpu/drm/apple/apple_drv.c').read_text() + usable = block(drv_c, 'static bool apple_dcp_usable(') + assert 'of_machine_is_compatible' not in usable return r''' #include #include @@ -257,6 +262,17 @@ def t6041_v27_admission(root): { return np && np->compatible && !strcmp(np->compatible, s); } +static bool of_device_is_available(const struct device_node *np) +{ + return np != NULL; +} +/* apple_dcp_usable()'s other processors: never reached by a T8132 node. */ +static bool dcp_t6030_ext_native(struct device_node *np) +{ (void)np; assert(!"T6030 dcpext in a T8132 scenario"); return false; } +static bool dcp_h17p_external_supported(struct device_node *np) +{ (void)np; assert(!"T8140 dcpext in a T8132 scenario"); return false; } +static bool dcp_t6041_ext_enabled(void) +{ assert(!"T6041 dcpext in a T8132 scenario"); return false; } static bool of_property_present(const struct device_node *np, const char *name) { assert(!strcmp(name, "apple,clock-ids")); @@ -333,7 +349,7 @@ def t6041_v27_admission(root): snprintf(out, DCP_FW_VERSION_STR_LEN, "%u.%u.%u", v[0], v[1], v[2]); return 3; } -''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + t8132_admission + '\n' + method_table + '\n' + selector + r''' +''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + t8132_admission + '\n' + method_table + '\n' + selector + '\n' + usable + r''' static struct device_node node; static struct apple_dcp_hw_data hw_t6041; static struct device dev = { .of_node = &node, .hw = &hw_t6041 }; @@ -508,9 +524,11 @@ def t6041_v27_admission(root): assert(!apple_t8132_dcpext_v27_2(&node)); assert(!apple_t6041_dcp_v27_2(&node)); assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + assert(apple_dcp_usable(&node)); node.clock_ids = false; assert(!apple_t8132_dcp_v27_2(&node)); assert(dcp_check_firmware_version(&dev) == (path ? DCP_FIRMWARE_M4 : DCP_FIRMWARE_UNKNOWN)); + assert(apple_dcp_usable(&node) == path); node.clock_ids = true; } t8132_firmware_path = true; @@ -526,12 +544,26 @@ def t6041_v27_admission(root): assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_M4); node.compat[1] = 2; assert(apple_t8132_dcp_v27_2(&node)); t8132_firmware_path = false; + /* Off the M4 path another release keeps the internal DCP out of the DRM device. */ + node.compat[1] = 0; assert(!apple_dcp_usable(&node)); + node.compat[1] = 2; assert(apple_dcp_usable(&node)); + /* A T8132 dcpext joins only on the 27.2 image, on either path. */ + node.compatible = "apple,t8132-dcpext"; + for (unsigned path = 0; path < 2; path++) { + t8132_firmware_path = path; + assert(apple_dcp_usable(&node)); + node.uuid = APPLE_T6041_DCP_26B123_UUID; + assert(!apple_dcp_usable(&node)); + node.uuid = APPLE_T8132_DCP_26B123_UUID; + } + t8132_firmware_path = false; dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); puts("PASS T8132 M4 backend only on its firmware path; a T8132 dcpext on the 27.2 image runs the 27.2 table on any board"); puts("PASS T8132 internal DCP with the 27.2 image and its firmware-27 clocks runs the 27.2 table; without them nothing changes"); + puts("PASS T8132 internal DCP on the 27.2 image joins the DRM device on any board; off the M4 path nothing else does"); return 0; } ''' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 02fdb3eff477f1..6d56ed6835e419 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1584,6 +1584,8 @@ def function(source, marker): { assert(!"T8132 DCP in a J700 scenario"); return false; } static bool __attribute__((unused)) apple_t8132_dcpext_v27_2(const struct device_node *n) { (void)n; assert(!"T8132 dcpext in a J700 scenario"); return false; } +static bool __attribute__((unused)) apple_t8132_dcp_v27_2(const struct device_node *n) +{ (void)n; assert(!"T8132 DCP in a J700 scenario"); return false; } static void __attribute__((unused)) iomfb_v14_7_external_refuse(struct apple_dcp *d, const char *why) { (void)d; (void)why; assert(!"T6030 external processor in a J700 scenario"); } struct drm_device { int unused; }; From 3bd2f90d721c5a43339cb6a7b73412e65a85ec0c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 11:46:10 +1100 Subject: [PATCH 0293/1514] iommu: apple-dart: report the streams a display DART has enabled A DCP whose device tree names its display power words but not its DART streams stops the streams its DARTs have enabled before its first power-down and enables them again at power-up. Let it read them: the first 32 streams of a T8110 DART, read while its domain is up. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 14 ++++++++++++++ include/linux/soc/apple/dart.h | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 34e169ec0c26f2..02133837431c90 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -7931,6 +7931,20 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl } EXPORT_SYMBOL_GPL(apple_dart_display_streams); +/* + * The streams 0 to 31 a T8110 display DART has enabled, read while its domain is up: what + * a DCP whose device tree names no streams stops and enables again around its power cycle. + */ +u32 apple_dart_enabled_streams(struct device *dev) +{ + struct apple_dart *dart = dev_get_drvdata(dev); + + if (!dart || dart->hw->type != DART_T8110) + return 0; + return readl(dart->regs + DART_T8110_ENABLE_STREAMS); +} +EXPORT_SYMBOL_GPL(apple_dart_enabled_streams); + /* * A DART whose domain goes off with its consumer's, at runtime, while other users still map * into it: dark, maps reach memory only and their invalidations wait; lit, those run. Its diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 0a7925025e6287..1c263ff4e561ee 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -187,6 +187,8 @@ int apple_dart_sleep_prepare(struct device *dev); void apple_dart_sleep_restore(struct device *dev); /* A display DART's streams around a display power cycle, see the DART driver. */ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush); +/* The streams 0 to 31 a display DART has enabled. */ +u32 apple_dart_enabled_streams(struct device *dev); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); /* A display DART whose domain goes off at runtime while others still map into it. */ @@ -221,6 +223,11 @@ static inline int apple_dart_display_streams(struct device *dev, u32 streams, bo return -ENODEV; } +static inline u32 apple_dart_enabled_streams(struct device *dev) +{ + return 0; +} + static inline int apple_dart_gapf_ready(struct device *dev) { return 0; From 77e0841e6e69f5c74cfbe7d523054a2a0e15c757 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 11:46:10 +1100 Subject: [PATCH 0294/1514] drm/apple: dcp: stop a DCP for a deep sleep with its panel lit on every hw.s2r SoC The system-sleep stop ran with an active panel only where the power words are measured, or on the J813, so another SoC's internal DCP stayed running into a deep sleep unless DPMS had turned its panel off first, and the sleep was refused. A derived layout only survives probe with appledrm.s2r_untested set, which already decides it: drop the board check. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index e2c96564e6763c..3addf5c97caf4d 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9854,12 +9854,11 @@ static int dcp_platform_suspend(struct device *dev) return dcp_v27_sleep_suspend(dcp); /* - * J813 uses the same qualified stop as DPMS off. Probe already gates - * its derived power layout on appledrm.s2r_untested; without this - * system-suspend path an active panel leaves the DCP running. + * The same stop as DPMS off; without this system-suspend path an active + * panel leaves the DCP running. Probe already gates a derived power + * layout (T8142) on appledrm.s2r_untested. */ - if (pm_suspend_via_firmware() && dcp_s2r_capable(dcp) && - (!dcp->hw.s2r_untested || of_machine_is_compatible("apple,j813"))) { + if (pm_suspend_via_firmware() && dcp_s2r_capable(dcp)) { int ret = dcp_s2r_suspend(dcp); /* Lit by the last resume with its CRTC off: the next resume finds it off by DPMS. */ From 5ff9c1c5891bd7fa7c5ddb7c79fe6fcfe09ec829 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 11:46:24 +1100 Subject: [PATCH 0295/1514] drm/apple: dcp: stop the T8132 internal DCP's 27.2 firmware, with its power words from the device tree The M4 MacBook Air's internal DCP runs the firmware-27 backend on macOS 27.2 but has no firmware stop, so a deep sleep is refused with the processor still running, and DPMS off only darkens the backlight. Give it the hw.s2r stop the T8142 runs on 27.2: set_power_state(0), D572, the AP link's release (A550 in the 27.2 table), RTKit idle and the CPU stop, then the DCP DART's streams. It has no secure mailbox. Its power words are not a per-SoC table: a hw.s2r DCP without a layout in its hw data takes them from its device tree, the ones its deep sleep lowers. DISP_CPU is the first state of its power-domains, DISP_FE that state's parent and DISP_SYS theirs; the retention words are DISP_CPU's apple,retention-workaround, of which only the masked bits are written, the off value at power-off and the value read at probe at power-on; pmc-dcp counts it where the display-power node has that word; and the DART streams are the ones its DARTs have enabled before the first stop. Without those properties the firmware keeps running, as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 10 ++ drivers/gpu/drm/apple/dcp.c | 131 +++++++++++++++++++++++++-- 2 files changed, 134 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 2042e257f55251..8fc4e23c37947f 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -250,6 +250,13 @@ struct dcp_s2r_layout { u32 disp_streams; /* "pmc-dcp" counts the powered DCPs: T8132 and T8140 only */ bool pmc_dcp; + /* + * From the device tree (dcp_s2r_layout_from_dt()): only the @*_mask bits of a + * retention word are written, @*_off while off and the value read at probe back on. + * Zero masks: the whole words, as above. + */ + u32 ret_ff_mask, ret_ff_off, ret_ff_on; + u32 ret_mem_mask, ret_mem_off, ret_mem_on; }; /* @@ -889,6 +896,9 @@ struct apple_dcp { struct completion s2r_dart_done; struct device *s2r_disp_dart; struct device *s2r_dcp_dart; + /* hw.s2r without a layout in its hw data: the device tree's, see dcp_s2r_layout_from_dt() */ + struct dcp_s2r_layout s2r_dt_layout; + bool s2r_dt_layout_ok; /* eDP display without DP-HDMI conversion */ bool main_display; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 3addf5c97caf4d..5c66f233648ec3 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -297,6 +297,92 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) * without a secure mailbox says so (hw.s2r_no_secure_port), and one behind * appledrm.s2r_untested stops its firmware for DPMS off and J813 system sleep. */ +/* + * hw.s2r without a layout in its hw data takes its words from the device tree, the ones its + * deep sleep lowers: DISP_CPU is the first state of the DCP's power-domains, DISP_FE that + * state's parent and DISP_SYS theirs, each at its reg in the power manager whose block the + * display-power node's "ps" starts. The retention words are DISP_CPU's two + * apple,retention-workaround entries (power manager offset, mask, value while off), in the + * node's "pwrgate" block, and the value each reads now, with the DCP running, is the one it + * gets back at power-on. It counts in pmc-dcp where the node has that word. The DART streams + * are the ones its DARTs have enabled at the first stop, see dcp_s2r_find_darts(). + */ +static int dcp_s2r_layout_from_dt(struct apple_dcp *dcp) +{ + struct dcp_s2r_layout *l = &dcp->s2r_dt_layout; + struct device_node *power, *pmgr = NULL, *ps[3] = {}; + struct resource ps_res, gate_res, pmgr_res; + u32 off[3], ret[6]; + void __iomem *gate; + int i, err = -EINVAL; + + power = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); + if (!power) + return -ENODEV; + if (of_address_to_resource(power, of_property_match_string(power, "reg-names", "ps"), + &ps_res) || + of_address_to_resource(power, of_property_match_string(power, "reg-names", "pwrgate"), + &gate_res)) + goto out; + ps[0] = of_parse_phandle(dcp->dev->of_node, "power-domains", 0); + for (i = 1; i < 3 && ps[i - 1]; i++) + ps[i] = of_parse_phandle(ps[i - 1], "power-domains", 0); + if (!ps[2]) + goto out; + pmgr = of_get_parent(ps[0]); + if (!pmgr || of_address_to_resource(pmgr, 0, &pmgr_res) || pmgr_res.start != ps_res.start) + goto out; + for (i = 0; i < 3; i++) { + struct device_node *parent = of_get_parent(ps[i]); + + of_node_put(parent); + if (parent != pmgr || of_property_read_u32(ps[i], "reg", &off[i]) || + off[i] > resource_size(&ps_res) - 4) + goto out; + } + if (of_property_read_u32_array(ps[0], "apple,retention-workaround", ret, 6) || + of_property_count_u32_elems(ps[0], "apple,retention-workaround") != 6) + goto out; + for (i = 0; i < 6; i += 3) { + u64 at = pmgr_res.start + ret[i]; + + if (at <= gate_res.start || at + 4 > gate_res.end + 1 || at % 4 || !ret[i + 1] || + ret[i + 2] & ~ret[i + 1]) + goto out; + } + gate = ioremap(gate_res.start, resource_size(&gate_res)); + if (!gate) { + err = -ENOMEM; + goto out; + } + *l = (struct dcp_s2r_layout){ + .disp_cpu = off[0], + .disp_fe = off[1], + .disp_sys = off[2], + .ret_ff = pmgr_res.start + ret[0] - gate_res.start, + .ret_ff_mask = ret[1], + .ret_ff_off = ret[2], + .ret_mem = pmgr_res.start + ret[3] - gate_res.start, + .ret_mem_mask = ret[4], + .ret_mem_off = ret[5], + .pmc_dcp = of_property_match_string(power, "reg-names", "pmc-dcp") >= 0, + }; + l->ret_ff_on = readl(gate + l->ret_ff); + l->ret_mem_on = readl(gate + l->ret_mem); + iounmap(gate); + dcp->s2r_dt_layout_ok = true; + dev_dbg(dcp->dev, "display power from the device tree: CPU %#x FE %#x SYS %#x, retention %#x/%#x on %#x/%#x\n", + l->disp_cpu, l->disp_fe, l->disp_sys, l->ret_ff, l->ret_mem, l->ret_ff_on, + l->ret_mem_on); + err = 0; +out: + for (i = 0; i < 3; i++) + of_node_put(ps[i]); + of_node_put(pmgr); + of_node_put(power); + return err; +} + static void dcp_s2r_check_dt(struct apple_dcp *dcp) { struct device_node *np = dcp->dev->of_node; @@ -309,6 +395,15 @@ static void dcp_s2r_check_dt(struct apple_dcp *dcp) !power ? "apple,display-power" : "secure mailbox"); dcp->hw.s2r = false; } + if (dcp->hw.s2r && !dcp->hw.s2r_layout) { + int ret = dcp_s2r_layout_from_dt(dcp); + + if (ret) { + dev_info(dcp->dev, "display power words not in the device tree (%d), the firmware keeps running\n", + ret); + dcp->hw.s2r = false; + } + } if (dcp->hw.s2r_ext && !power) { dev_info(dcp->dev, "no apple,display-power in the device tree, the firmware keeps running\n"); dcp->hw.s2r_ext = false; @@ -7240,13 +7335,17 @@ static int dcp_s2r_pm_register(struct apple_dcp *dcp); * - num_dptx_ports 0: it drives the panel only. * - adopt_live_session: iBoot leaves it running with the 27.2 image and the * panel lit; Linux never starts its CPU. - * No sleep support: no firmware-27 sleep has run on this processor. + * - s2r: the firmware-27 stop (iomfb_v27.c) for DPMS off and deep sleep, + * with the 27.2 table's calls and the power words its device tree names + * (dcp_s2r_layout_from_dt()). It has no secure mailbox. */ static const struct apple_dcp_hw_data apple_dcp_hw_t8132_v27 = { .firmware_dma_bits = 41, .num_dptx_ports = 0, .adopt_live_session = true, .firmware_compat = DCP_FIRMWARE_V_27_0, + .s2r = true, + .s2r_no_secure_port = true, }; static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { @@ -7467,7 +7566,8 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) * A SoC with derived power words is offered the stop only when asked for, and only on * firmware 27.0, whose calls are the ones that ran with them. */ - if (dcp->hw.s2r && (!dcp->hw.s2r_layout || + if (dcp->hw.s2r && ((!dcp->hw.s2r_layout && + !of_property_present(dev->of_node, "apple,display-power")) || (dcp->hw.s2r_untested && (!s2r_untested || fw_compat != DCP_FIRMWARE_V_27_0)))) dcp->hw.s2r = false; @@ -8444,7 +8544,9 @@ static const struct dcp_s2r_layout *dcp_s2r_layout(struct apple_dcp *dcp) { if (dcp_s2r_is_t8142_ext(dcp)) return &dcp_s2r_t8142_ext[dcp->index - 1]; - return dcp->hw.s2r_layout ?: &dcp_s2r_t8140; + if (dcp->hw.s2r_layout) + return dcp->hw.s2r_layout; + return dcp->s2r_dt_layout_ok ? &dcp->s2r_dt_layout : &dcp_s2r_t8140; } #define DCP_PS_MIN GENMASK(19, 16) @@ -8484,6 +8586,15 @@ static void dcp_s2r_find_darts(struct apple_dcp *dcp) dcp->s2r_disp_dart = dcp_s2r_find_dart(piodma); of_node_put(piodma); } + /* A device-tree layout's streams: what its DARTs have on before the first stop. */ + if (dcp->s2r_dt_layout_ok && !dcp->s2r_dt_layout.dcp_streams && dcp->s2r_dcp_dart) { + dcp->s2r_dt_layout.dcp_streams = apple_dart_enabled_streams(dcp->s2r_dcp_dart); + if (dcp->s2r_disp_dart) + dcp->s2r_dt_layout.disp_streams = + apple_dart_enabled_streams(dcp->s2r_disp_dart); + dev_dbg(dcp->dev, "DART streams for the stop: DCP %#x, display %#x\n", + dcp->s2r_dt_layout.dcp_streams, dcp->s2r_dt_layout.disp_streams); + } } void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) @@ -8953,6 +9064,12 @@ static void dcp_s2r_ps_lower(void __iomem *reg) writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), reg); } +/* A retention word: the whole of it from a hw-data layout, only its masked bits from the DT's. */ +static void dcp_s2r_ret_write(void __iomem *reg, u32 mask, u32 val, u32 word) +{ + writel(mask ? (readl(reg) & ~mask) | (val & mask) : word, reg); +} + /* Its display-power words, pmc-dcp only where the layout has one. */ static int dcp_s2r_map_power(struct apple_dcp *dcp, void __iomem **ps, void __iomem **pwrgate, void __iomem **pmc) @@ -8991,8 +9108,8 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) if (val & BIT(28)) writel(val & ~(BIT(28) | GENMASK(9, 8)), ps + l->disp_cpu); if (l->ret_ff) { - writel(3, pwrgate + l->ret_ff); - writel(0, pwrgate + l->ret_mem); + dcp_s2r_ret_write(pwrgate + l->ret_ff, l->ret_ff_mask, l->ret_ff_off, 3); + dcp_s2r_ret_write(pwrgate + l->ret_mem, l->ret_mem_mask, l->ret_mem_off, 0); } dcp_s2r_ps_lower(ps + l->disp_cpu); dcp_s2r_ps_lower(ps + l->disp_fe); @@ -9043,8 +9160,8 @@ static int dcp_s2r_domains_on(struct apple_dcp *dcp) } writel(val | 0xf, ps + l->disp_cpu); if (l->ret_ff) { - writel(0, pwrgate + l->ret_ff); - writel(1, pwrgate + l->ret_mem); + dcp_s2r_ret_write(pwrgate + l->ret_ff, l->ret_ff_mask, l->ret_ff_on, 0); + dcp_s2r_ret_write(pwrgate + l->ret_mem, l->ret_mem_mask, l->ret_mem_on, 1); } writel(val | 0xf | BIT(28), ps + l->disp_cpu); if (pmc) From 2d60e9ca527799c44779753fd9a2875f25e11640 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 11:58:52 +1100 Subject: [PATCH 0296/1514] dt-bindings: display: apple,t8140-display-power: add the T8132 The T8132's words are T8140's: pmc-dcp, the power manager's power states and its power gate block. Signed-off-by: Ryan Murray --- .../bindings/display/apple,t8140-display-power.yaml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml index 7d157451342678..89c84ca242d4ed 100644 --- a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml @@ -4,7 +4,7 @@ $id: http://devicetree.org/schemas/display/apple,t8140-display-power.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple T8140 and T8142 display power words +title: Apple T8132, T8140 and T8142 display power words maintainers: - Diljit Singh @@ -18,6 +18,7 @@ description: properties: compatible: enum: + - apple,t8132-display-power - apple,t8140-display-power - apple,t8142-display-power @@ -38,7 +39,9 @@ allOf: - if: properties: compatible: - const: apple,t8140-display-power + enum: + - apple,t8132-display-power + - apple,t8140-display-power then: properties: reg: From c9ec13a853c484c7cf4994a75c744ae617f2f8ec Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 11:58:52 +1100 Subject: [PATCH 0297/1514] arm64: dts: apple: t8132-j713: the internal DCP's display power words Name the power manager blocks the internal DCP's firmware-27 stop writes, the ones the deep sleep lowers (pmc-dcp, the power states and the power gate block), and the DCP DART's clock-protection slice (42 in the ADT's dart-dcp) as its gapf word: the stop clears it after the DART's power-down flush so that DISP_CPU's power state can be written. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j713.dts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-j713.dts b/arch/arm64/boot/dts/apple/t8132-j713.dts index e445896854733f..8037c760a8f088 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713.dts +++ b/arch/arm64/boot/dts/apple/t8132-j713.dts @@ -193,8 +193,31 @@ apple,clock-protection = <&ps_prot 8>; }; +/* + * The words the firmware-27 stop of the internal DCP writes (appledrm.s2r_untested), + * the same ones the deep sleep lowers: pmc-dcp, the PMGR power states and its power + * gate block. + */ +&soc { + dcp_power: display-power@3828a9c14 { + compatible = "apple,t8132-display-power"; + reg = <0x3 0x828a9c14 0x0 0x4>, + <0x3 0x80700000 0x0 0x14000>, + <0x3 0x80724000 0x0 0x2000>; + reg-names = "pmc-dcp", "ps", "pwrgate"; + }; +}; + +/* Clock-protection slice 42 (ADT dart-dcp): it guards DISP_CPU's power state. */ +&dcp_dart { + reg = <0x3 0x0a340000 0x0 0x20000>, + <0x3 0x8079cb80 0x0 0x4>; + reg-names = "dart", "gapf"; +}; + &dcp { apple,pmc-interface = <&pmc_disp0>; + apple,display-power = <&dcp_power>; panel: panel { compatible = "apple,panel-j713", "apple,panel"; From b42f40fd8980c9b6236ad44eeda084e9e17d3d3e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 08:58:02 +1100 Subject: [PATCH 0298/1514] drm/apple: dcp, iommu: apple-dart: take a DT layout's DART streams at probe, and only all of them Review points on the device-tree power layout: - Its DART streams were read at the first stop, with dcp_streams == 0 standing for "not read yet". A first read of 0 would have had later stops and power-ons read the DART again, maybe with DISP_CPU still lowered, and the restart would enable no streams. Now the streams are read once at probe, with the firmware running. A DCP DART that reads none refuses the layout, and the firmware keeps running as with no power words. - apple_dart_enabled_streams() read only the first enable word. If a stream above 31 is enabled, the 32-bit mask can't describe the DART, so it now reads every word up to num_streams, warns once, and reports 0 in that case. - Comments still described the stop as behind appledrm.s2r_untested or J813-only. The device tree's words stop the firmware by default; only a SoC whose static words are merely derived (T8142) needs the parameter. The same holds for the layout added in "drm/apple: dcp: stop a DCP for a deep sleep with its panel lit on every hw.s2r SoC", whose message says otherwise. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-j713.dts | 6 +-- drivers/gpu/drm/apple/dcp.c | 57 +++++++++++++++++------- drivers/iommu/apple-dart.c | 13 +++++- include/linux/soc/apple/dart.h | 2 +- 4 files changed, 57 insertions(+), 21 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j713.dts b/arch/arm64/boot/dts/apple/t8132-j713.dts index 8037c760a8f088..57c761674b0b44 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713.dts +++ b/arch/arm64/boot/dts/apple/t8132-j713.dts @@ -194,9 +194,9 @@ }; /* - * The words the firmware-27 stop of the internal DCP writes (appledrm.s2r_untested), - * the same ones the deep sleep lowers: pmc-dcp, the PMGR power states and its power - * gate block. + * The words the firmware-27 stop of the internal DCP writes (by default, see + * dcp_s2r_layout_from_dt()), the same ones the deep sleep lowers: pmc-dcp, the PMGR + * power states and its power gate block. */ &soc { dcp_power: display-power@3828a9c14 { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 5c66f233648ec3..e174f7803a47f6 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -294,8 +294,9 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) * display domains through apple,display-power, and the internal DCP only takes IOP idle * once its secure port has gone idle. A device tree without those keeps the firmware * running: DPMS is the backlight alone and the display stays up across a sleep. A SoC - * without a secure mailbox says so (hw.s2r_no_secure_port), and one behind - * appledrm.s2r_untested stops its firmware for DPMS off and J813 system sleep. + * without a secure mailbox says so (hw.s2r_no_secure_port). Power words from the device + * tree stop the firmware by default; a SoC whose static words are only derived (T8142) does + * so only with appledrm.s2r_untested. */ /* * hw.s2r without a layout in its hw data takes its words from the device tree, the ones its @@ -383,6 +384,38 @@ static int dcp_s2r_layout_from_dt(struct apple_dcp *dcp) return err; } +static struct device *dcp_s2r_find_dart(struct device_node *np); + +/* + * A device-tree layout's DART streams: the ones its DARTs have enabled at probe, with the + * firmware running. A DCP DART that reads none leaves nothing for the stop to restore. + */ +static int dcp_s2r_layout_streams(struct apple_dcp *dcp) +{ + struct device_node *piodma; + struct device *dart; + + dart = dcp_s2r_find_dart(dcp->dev->of_node); + if (!dart) + return -ENODEV; + dcp->s2r_dt_layout.dcp_streams = apple_dart_enabled_streams(dart); + put_device(dart); + if (!dcp->s2r_dt_layout.dcp_streams) + return -ENODATA; + piodma = of_get_child_by_name(dcp->dev->of_node, "piodma"); + if (piodma) { + dart = dcp_s2r_find_dart(piodma); + of_node_put(piodma); + if (dart) { + dcp->s2r_dt_layout.disp_streams = apple_dart_enabled_streams(dart); + put_device(dart); + } + } + dev_dbg(dcp->dev, "DART streams for the stop: DCP %#x, display %#x\n", + dcp->s2r_dt_layout.dcp_streams, dcp->s2r_dt_layout.disp_streams); + return 0; +} + static void dcp_s2r_check_dt(struct apple_dcp *dcp) { struct device_node *np = dcp->dev->of_node; @@ -396,11 +429,12 @@ static void dcp_s2r_check_dt(struct apple_dcp *dcp) dcp->hw.s2r = false; } if (dcp->hw.s2r && !dcp->hw.s2r_layout) { - int ret = dcp_s2r_layout_from_dt(dcp); + int ret = dcp_s2r_layout_from_dt(dcp) ?: dcp_s2r_layout_streams(dcp); if (ret) { - dev_info(dcp->dev, "display power words not in the device tree (%d), the firmware keeps running\n", + dev_info(dcp->dev, "no display power layout (%d), the firmware keeps running\n", ret); + dcp->s2r_dt_layout_ok = false; dcp->hw.s2r = false; } } @@ -580,7 +614,7 @@ static bool dcp_j714s_ext(struct device *dev) static bool s2r_untested; module_param(s2r_untested, bool, 0444); MODULE_PARM_DESC(s2r_untested, - "Stop the DCP firmware on DPMS off and J813 system sleep using derived T8142 power words (default 0)"); + "Stop the DCP firmware on DPMS off and system sleep using derived T8142 power words (default 0)"); bool dcp_t6041_ext_enabled(void) { @@ -7563,7 +7597,9 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8132-dcp")) dcp->hw = apple_dcp_hw_t8132_v27; /* - * A SoC with derived power words is offered the stop only when asked for, and only on + * A stop needs power words: a static layout, or the device tree's (see + * dcp_s2r_layout_from_dt(), offered by default). A SoC whose static words are only + * derived (hw.s2r_untested, T8142) is offered it only when asked for, and only on * firmware 27.0, whose calls are the ones that ran with them. */ if (dcp->hw.s2r && ((!dcp->hw.s2r_layout && @@ -8586,15 +8622,6 @@ static void dcp_s2r_find_darts(struct apple_dcp *dcp) dcp->s2r_disp_dart = dcp_s2r_find_dart(piodma); of_node_put(piodma); } - /* A device-tree layout's streams: what its DARTs have on before the first stop. */ - if (dcp->s2r_dt_layout_ok && !dcp->s2r_dt_layout.dcp_streams && dcp->s2r_dcp_dart) { - dcp->s2r_dt_layout.dcp_streams = apple_dart_enabled_streams(dcp->s2r_dcp_dart); - if (dcp->s2r_disp_dart) - dcp->s2r_dt_layout.disp_streams = - apple_dart_enabled_streams(dcp->s2r_disp_dart); - dev_dbg(dcp->dev, "DART streams for the stop: DCP %#x, display %#x\n", - dcp->s2r_dt_layout.dcp_streams, dcp->s2r_dt_layout.disp_streams); - } } void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 02133837431c90..628c3cc14d7a48 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -7932,15 +7932,24 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl EXPORT_SYMBOL_GPL(apple_dart_display_streams); /* - * The streams 0 to 31 a T8110 display DART has enabled, read while its domain is up: what - * a DCP whose device tree names no streams stops and enables again around its power cycle. + * The streams a T8110 display DART has enabled, read while its domain is up: what a DCP + * whose device tree names no streams stops and enables again around its power cycle. The + * mask holds streams 0 to 31; a DART with any stream above them enabled can't be described + * by it and reads 0, which its caller takes as no streams to stop. */ u32 apple_dart_enabled_streams(struct device *dev) { struct apple_dart *dart = dev_get_drvdata(dev); + unsigned int i; if (!dart || dart->hw->type != DART_T8110) return 0; + for (i = 1; i < DIV_ROUND_UP(dart->num_streams, 32); i++) { + if (readl(dart->regs + DART_T8110_ENABLE_STREAMS + 4 * i)) { + dev_warn_once(dart->dev, "streams above 31 enabled: not reported\n"); + return 0; + } + } return readl(dart->regs + DART_T8110_ENABLE_STREAMS); } EXPORT_SYMBOL_GPL(apple_dart_enabled_streams); diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 1c263ff4e561ee..03b09d49321706 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -187,7 +187,7 @@ int apple_dart_sleep_prepare(struct device *dev); void apple_dart_sleep_restore(struct device *dev); /* A display DART's streams around a display power cycle, see the DART driver. */ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush); -/* The streams 0 to 31 a display DART has enabled. */ +/* The streams 0 to 31 a display DART has enabled; 0 if any stream above 31 is on. */ u32 apple_dart_enabled_streams(struct device *dev); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); From 888805b87936b04d41f3fcea35beade5f84f6f26 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 19:32:05 +1100 Subject: [PATCH 0299/1514] drm/apple: dcp: refuse a DT layout without its display DART streams, and check power word alignment A DCP with a piodma child restores the display DART's streams at power-on from the layout. If that DART is not found, or reads no streams (none enabled, or streams above 31 that the 32-bit mask cannot describe), the layout kept disp_streams = 0 and power-on would have enabled none. Refuse the layout then, like a DCP DART that reads none: the firmware keeps running. The DISP_CPU/FE/SYS offsets are checked against the "ps" block without underflowing on a block shorter than a word, and must be word aligned like the retention offsets. The overview comment named the old first-stop stream read; point it at dcp_s2r_layout_streams(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index e174f7803a47f6..3dd71183621970 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -306,7 +306,7 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) * apple,retention-workaround entries (power manager offset, mask, value while off), in the * node's "pwrgate" block, and the value each reads now, with the DCP running, is the one it * gets back at power-on. It counts in pmc-dcp where the node has that word. The DART streams - * are the ones its DARTs have enabled at the first stop, see dcp_s2r_find_darts(). + * are the ones its DARTs have enabled at probe, see dcp_s2r_layout_streams(). */ static int dcp_s2r_layout_from_dt(struct apple_dcp *dcp) { @@ -338,7 +338,8 @@ static int dcp_s2r_layout_from_dt(struct apple_dcp *dcp) of_node_put(parent); if (parent != pmgr || of_property_read_u32(ps[i], "reg", &off[i]) || - off[i] > resource_size(&ps_res) - 4) + resource_size(&ps_res) < 4 || off[i] > resource_size(&ps_res) - 4 || + off[i] % 4) goto out; } if (of_property_read_u32_array(ps[0], "apple,retention-workaround", ret, 6) || @@ -388,7 +389,8 @@ static struct device *dcp_s2r_find_dart(struct device_node *np); /* * A device-tree layout's DART streams: the ones its DARTs have enabled at probe, with the - * firmware running. A DCP DART that reads none leaves nothing for the stop to restore. + * firmware running. A DCP DART, or a piodma DART where the DCP has a piodma node, that is + * missing or reads none leaves nothing for the stop to restore, so the layout is refused. */ static int dcp_s2r_layout_streams(struct apple_dcp *dcp) { @@ -406,10 +408,12 @@ static int dcp_s2r_layout_streams(struct apple_dcp *dcp) if (piodma) { dart = dcp_s2r_find_dart(piodma); of_node_put(piodma); - if (dart) { - dcp->s2r_dt_layout.disp_streams = apple_dart_enabled_streams(dart); - put_device(dart); - } + if (!dart) + return -ENODEV; + dcp->s2r_dt_layout.disp_streams = apple_dart_enabled_streams(dart); + put_device(dart); + if (!dcp->s2r_dt_layout.disp_streams) + return -ENODATA; } dev_dbg(dcp->dev, "DART streams for the stop: DCP %#x, display %#x\n", dcp->s2r_dt_layout.dcp_streams, dcp->s2r_dt_layout.disp_streams); From 7428f77bbe34574c45d33a0a0a274c81eb24e6de Mon Sep 17 00:00:00 2001 From: Fredrik Silfver <1684291+freber@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:50:44 +0100 Subject: [PATCH 0300/1514] arm64: dts: apple: t8122-j615: describe the CPU memory floor The 15-inch M3 MacBook Air (J615) has the J613's SoC, DRAM, PMP tables and PACC0 request layout. Its device tree is a legacy handoff tree. The report binds the generic "apple,t8122-pmp-v2-report" and names its PMP with apple,pmp. This driver starts that PMP, which runs the 14.x firmware (3B18C886-4C70-349B-B1C4-70F35DE2C5CD). Without a memory floor nothing raises the DRAM or fabric state for the CPUs. A 4-thread membw2 read then reaches 19.8 GB/s. Give its report apple,cpu-memory-floor = <0x21 2 0x25 4>. The levels come from the J615 runs of the earlier J615 floor patch, not from the J613 tree. That patch stored DCS 4 in bits 51:48 and fabric level 2 in bits 35:32 of the PACC0 request, word 0x2004000200000000. Those are the lanes of request classes 0x25 and 0x21, so these pairs build the same word. The 14.x PMP answered it with DVFS-STATE 0x24 within 5.1 ms. That is class 0x25 at 4 in the low nibble with class 0x21 at 2 in the high nibble. In one boot it confirmed 39 of 39 raises and 38 of 38 releases. With the floor the same membw2 read reached 68.2 GB/s. The levels equal the J613's because the SoC, DRAM and PMP tables are the same, but they were measured on this board. The driver needs no change. pmp_floor_probe() runs for any report with the property. pmp_floor_find_pmp() takes the report's apple,pmp without an availability check, so it does not matter that the PMP is still disabled when the report probes. The start work waits for the report to read READY. It does once the PMP runs, which apple_pmp_start_init() arranges when the display asks for it. Admission then reads the tables m1n1 fills in on the PMP node. Run on this board's live tables, the upstream check admits 2 CPU clients and puts the PACC0 update alias at +0x10888, where the earlier patch wrote it. pmp_floor_word_of() builds 0x2004000200000000 from the pairs. The binding already allows the property on apple,t8122-pmp-v2-report. The generic T8122 report does not set floor_confirm. Raises and releases are published without the DVFS-STATE check, as on every report but the J613 25G83 one. The experimental t8122-j615-25g83 tree includes this file. It binds the native J613 report, where the floor has not run on a J615. It deletes the property so that it stays uncovered, as it was before. Tested by building both J615 trees. Decompiled, the J615 report carries the property while the 25G83 report has none. pmp-report.o builds with clang 18. The floor ran on a J615 with the 14.x firmware on a 7.2.11 kernel carrying the earlier patch. A 7.3 kernel built from this tree with #2090, #2199 and #2203 merged then booted on a J615 with the 14.x firmware and the default command line. The report admitted the floor from the property with the PACC0 update alias at +0x10888. During three 4-thread membw2 reads the floor was up, DVFS-STATE read 0x24 each time and the read reached 69.3 GB/s. The boot logged no floor fault or refusal. On a later boot of the same kernel the read gave 21.6 GB/s with the floor's enable attribute at 0 and 69.3 GB/s with it at 1. Signed-off-by: Fredrik Silfver <1684291+freber@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t8122-j615-25g83.dts | 5 +++++ arch/arm64/boot/dts/apple/t8122-j615.dts | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts index 7aef84a8e34940..a56f93b0864b3d 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615-25g83.dts @@ -7,6 +7,11 @@ #include "t8122-j613-dcp-25g83.dtsi" #include "t8122-j613-qspi.dtsi" +/* The memory floor has not run with the native J613 report on a J615. */ +&pmp_report { + /delete-property/ apple,cpu-memory-floor; +}; + /* As on the J613 25G83. */ &mtp { compatible = "apple,t8122-mtp", "apple,t8122-rtk-helper-asc4", "apple,mtp"; diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index fdb511bd9a4e7c..7bf3577a31ef52 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -17,6 +17,14 @@ model = "Apple MacBook Air (15-inch, M3, 2024)"; }; +/* + * CPU memory floor, class 0x25 (DCS) at 4 and 0x21 (fabric) at 2. The 14.x + * PMP answers it with DVFS-STATE 0x24: 4-thread membw2 19.8 -> 68.2 GB/s. + */ +&pmp_report { + apple,cpu-memory-floor = <0x21 2 0x25 4>; +}; + &dcp { panel: panel { compatible = "apple,panel-j615", "apple,panel"; From d91a256494420f946d29d53943f11ca9c2f6c9a6 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 01:37:43 -0800 Subject: [PATCH 0301/1514] soc: apple: rtkit: rate-limit receive-path warnings so firmware cannot flood the log Since the previous commit, an endpoint-7 message from a co-processor that did not ask for CoreAnalytics is reported as one to an unknown endpoint instead of being acknowledged silently. How often such a message arrives is up to the firmware: one that sends CoreAnalytics events periodically would log a warning per event. The same holds for every warning the receive path prints about a firmware message. The dispatcher printed the unknown-endpoint warning in three places (the debug endpoint without sync_syslog_ack, endpoint 7 when not served, and any other endpoint); they now share apple_rtkit_unserved_ep_msg(). That helper, the receive path's "Message from undiscovered endpoint" warning (printed for the same kind of message on an adopted session) and the per-endpoint warnings for a message the handler doesn't know (management, CoreAnalytics, crash log, ioreport, syslog, oslog, and an application endpoint with no receiver) all use dev_warn_ratelimited(), as the kdebug and syslog-record warnings already did, and the registry-v2 PMP's "refused auxiliary buffer request" error uses dev_err_ratelimited(). Warnings about what the AP sends, and the endpoint map's one-time report of an unknown system endpoint, are unchanged. Only logging changes. rtkit-coreanalytics-tests.py now checks that an unserved endpoint-7 message, and a message to a system endpoint nobody serves, go through the shared warning. The host tests that compile these functions with stand-ins (display-sleep-merge, rtkit-oslog, apple-dcp ordered-rx and oslog-events) get dev_warn_ratelimited() or a stand-in for the helper. Suggested-by: Ryan Murray Suggested-by: DjDeveloperr Signed-off-by: Jeff Queisser --- drivers/soc/apple/rtkit.c | 58 +++++++++++-------- tools/asahi/display-sleep-merge-tests.py | 2 + tools/asahi/rtkit-coreanalytics-tests.py | 41 +++++++++---- tools/asahi/rtkit-oslog-tests.py | 1 + .../selftests/drivers/gpu/apple-dcp/boot.py | 1 + .../selftests/drivers/gpu/apple-dcp/run.py | 3 + 6 files changed, 69 insertions(+), 37 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e364719675cd64..d1d5f5a92f0b9b 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -560,7 +560,7 @@ static void apple_rtkit_management_rx(struct apple_rtkit *rtk, u64 msg) dev_dbg(rtk->dev, "RTKit: co-processor idle: 0x%llx\n", msg); break; default: - dev_warn( + dev_warn_ratelimited( rtk->dev, "RTKit: unknown management message: 0x%llx (type: 0x%02x)\n", msg, type); @@ -920,7 +920,7 @@ static void apple_rtkit_coreanalytics_rx(struct apple_rtkit *rtk, u64 msg) reply, NULL, false); break; default: - dev_warn(rtk->dev, "RTKit: Unknown CoreAnalytics message: %llx\n", msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown CoreAnalytics message: %llx\n", msg); return; } if (ret) @@ -1080,8 +1080,8 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) bool await_log = false; if (type != APPLE_RTKIT_CRASHLOG_CRASH) { - dev_warn(rtk->dev, "RTKit: Unknown crashlog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown crashlog message: %llx\n", + msg); return; } @@ -1232,8 +1232,8 @@ static void apple_rtkit_ioreport_rx(struct apple_rtkit *rtk, u64 msg) NULL, false); break; default: - dev_warn(rtk->dev, "RTKit: Unknown ioreport message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown ioreport message: %llx\n", + msg); } } @@ -1354,8 +1354,8 @@ static void apple_rtkit_syslog_rx(struct apple_rtkit *rtk, u64 msg) apple_rtkit_syslog_rx_log(rtk, msg); break; default: - dev_warn(rtk->dev, "RTKit: Unknown syslog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown syslog message: %llx\n", + msg); } } @@ -1406,7 +1406,8 @@ static void apple_rtkit_oslog_rx(struct apple_rtkit *rtk, u64 msg) if (apple_rtkit_oslog_unanswered(rtk)) dev_dbg(rtk->dev, "RTKit: oslog notification: %016llx\n", msg); else - dev_warn(rtk->dev, "RTKit: invalid oslog notification: %llx\n", msg); + dev_warn_ratelimited(rtk->dev, "RTKit: invalid oslog notification: %llx\n", + msg); return; } @@ -1438,8 +1439,8 @@ static void apple_rtkit_oslog_rx(struct apple_rtkit *rtk, u64 msg) dev_dbg(rtk->dev, "RTKit: oslog notification: %016llx\n", msg); break; default: - dev_warn(rtk->dev, "RTKit: Unknown oslog message: %llx\n", - msg); + dev_warn_ratelimited(rtk->dev, "RTKit: Unknown oslog message: %llx\n", + msg); } } @@ -1471,13 +1472,26 @@ static void apple_rtkit_pmp_aux_rx(struct apple_rtkit *rtk, u64 msg) msg != (FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_BUFFER_REQUEST) | FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_SIZE, 2))) { - dev_err(rtk->dev, "RTKit: refused auxiliary buffer request\n"); + dev_err_ratelimited(rtk->dev, "RTKit: refused auxiliary buffer request\n"); return; } apple_rtkit_common_rx_get_buffer(rtk, &rtk->pmp_aux_buffer, APPLE_RTKIT_EP_PMP_AUX, msg); } +/* + * A message to an endpoint this client doesn't serve. How often one arrives is + * up to the firmware, which may send its events periodically, so the warning + * is rate-limited, as every warning the receive path prints for a firmware + * message is. + */ +static void apple_rtkit_unserved_ep_msg(struct apple_rtkit *rtk, u8 ep, u64 msg) +{ + dev_warn_ratelimited(rtk->dev, + "RTKit: message to unknown endpoint %02x: %llx\n", + ep, msg); +} + static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, bool retained, u64 received_ns) { @@ -1507,15 +1521,11 @@ static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, if (rtk->sync_syslog_ack) apple_rtkit_kdebug_rx(rtk, msg); else - dev_warn(rtk->dev, - "RTKit: message to unknown endpoint %02x: %llx\n", - ep, msg); + apple_rtkit_unserved_ep_msg(rtk, ep, msg); break; case APPLE_RTKIT_EP_COREANALYTICS: if (!apple_rtkit_ep7_served(rtk)) - dev_warn(rtk->dev, - "RTKit: message to unknown endpoint %02x: %llx\n", - ep, msg); + apple_rtkit_unserved_ep_msg(rtk, ep, msg); else if (rtk->pmp_registry_v2) apple_rtkit_pmp_aux_rx(rtk, msg); else @@ -1533,15 +1543,13 @@ static void apple_rtkit_rx_dispatch(struct apple_rtkit *rtk, u8 ep, u64 msg, else if (rtk->ops->recv_message_timed) rtk->ops->recv_message_timed(rtk->cookie, ep, msg, 0); else - dev_warn( + dev_warn_ratelimited( rtk->dev, "Received unexpected message to EP%02d: %llx\n", ep, msg); break; default: - dev_warn(rtk->dev, - "RTKit: message to unknown endpoint %02x: %llx\n", - ep, msg); + apple_rtkit_unserved_ep_msg(rtk, ep, msg); } } @@ -1711,9 +1719,9 @@ static void apple_rtkit_rx(struct apple_mbox *mbox, struct apple_mbox_msg msg, * Warning about it here too reads as if the AP sent the message. */ if (!test_bit(ep, rtk->endpoints) && ep != APPLE_RTKIT_EP_CRASHLOG) - dev_warn(rtk->dev, - "RTKit: Message from undiscovered endpoint 0x%02x\n", - ep); + dev_warn_ratelimited(rtk->dev, + "RTKit: Message from undiscovered endpoint 0x%02x\n", + ep); if (ep >= APPLE_RTKIT_APP_ENDPOINT_START && rtk->ops->recv_message_early && diff --git a/tools/asahi/display-sleep-merge-tests.py b/tools/asahi/display-sleep-merge-tests.py index c9d1debf086973..126a8e6de471c8 100644 --- a/tools/asahi/display-sleep-merge-tests.py +++ b/tools/asahi/display-sleep-merge-tests.py @@ -113,6 +113,7 @@ def run(name, code, negative=False, extra=()): #define READ_ONCE(x) (x) #define IS_ENABLED(x) 1 #define dev_warn(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) #define dev_err(...) ((void)0) #define container_of(p,t,m) ((t *)((char *)(p)-offsetof(t,m))) #define APPLE_RTKIT_EP_MGMT 0 @@ -136,6 +137,7 @@ def run(name, code, negative=False, extra=()): STUB(apple_rtkit_ioreport_rx) STUB(apple_rtkit_kdebug_rx) STUB(apple_rtkit_pmp_aux_rx) STUB(apple_rtkit_coreanalytics_rx) STUB(apple_rtkit_oslog_rx) static bool apple_rtkit_ep7_served(struct apple_rtkit *r) { return false; } +static void apple_rtkit_unserved_ep_msg(struct apple_rtkit *r,u8 e,u64 m) {} static void timed_cb(void *c,u8 e,u64 m,u64 ns) { assert(e==0x2a && m==0x1234); timed++; observed=ns; } static void legacy_cb(void *c,u8 e,u64 m) { assert(e==0x2a && m==0x1234); legacy++; } ''' diff --git a/tools/asahi/rtkit-coreanalytics-tests.py b/tools/asahi/rtkit-coreanalytics-tests.py index 546303ea32191c..55b5a2f929adf3 100755 --- a/tools/asahi/rtkit-coreanalytics-tests.py +++ b/tools/asahi/rtkit-coreanalytics-tests.py @@ -7,7 +7,8 @@ endpoint map starts endpoint 7 only for a client that asks for CoreAnalytics (APPLE_RTKIT_NEEDS_COREANALYTICS) and for registry-v2 PMP firmware, so only those get a buffer or an acknowledgment there: a buffer request from any -other co-processor, of any size, allocates nothing and is not answered. +other co-processor, of any size, allocates nothing and is not answered, and +is reported through the rate-limited unknown-endpoint warning. --old-ref REV runs the same checks on the driver at REV and requires them to fail there. @@ -69,6 +70,7 @@ def constants(source, header, internal): #define FIELD_FIT(m,v) (!((((u64)(v)) << __builtin_ctzll(m)) & ~(m))) #define READ_ONCE(x) (x) #define dev_warn(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)warned++) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) @@ -92,7 +94,7 @@ def constants(source, header, internal): int coreanalytics_completion; }; -static unsigned allocations, frees, sent, aux; +static unsigned allocations, frees, sent, aux, warned; static size_t allocated; static char memory[64]; static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, struct apple_rtkit_shmem *b) @@ -127,13 +129,18 @@ def constants(source, header, internal): FIELD_PREP(APPLE_RTKIT_CA_COUNT, count) | unit; } -static void deliver(const struct apple_rtkit_ops *ops, bool registry_v2, u64 msg) +static void deliver_ep(const struct apple_rtkit_ops *ops, bool registry_v2, u8 ep, u64 msg) { struct apple_rtkit rtk = { .ops = ops, .pmp_registry_v2 = registry_v2 }; - allocations = frees = sent = aux = 0; + allocations = frees = sent = aux = warned = 0; allocated = 0; - apple_rtkit_rx_dispatch(&rtk, APPLE_RTKIT_EP_COREANALYTICS, msg, false, 0); + apple_rtkit_rx_dispatch(&rtk, ep, msg, false, 0); +} + +static void deliver(const struct apple_rtkit_ops *ops, bool registry_v2, u64 msg) +{ + deliver_ep(ops, registry_v2, APPLE_RTKIT_EP_COREANALYTICS, msg); } int main(void) @@ -147,21 +154,29 @@ def constants(source, header, internal): /* A client that asked for CoreAnalytics gets its buffer and its acks. */ deliver(&asks, false, small); - assert(allocations == 1 && allocated == 0x4000 && sent == 1 && frees == 0); + assert(allocations == 1 && allocated == 0x4000 && sent == 1 && frees == 0 && !warned); deliver(&asks, false, event); - assert(allocations == 0 && sent == 1); + assert(allocations == 0 && sent == 1 && !warned); /* Registry-v2 PMP firmware's endpoint 7 is its auxiliary buffer. */ deliver(&plain, true, small); - assert(aux == 1 && allocations == 0 && sent == 0); + assert(aux == 1 && allocations == 0 && sent == 0 && !warned); - /* Any other co-processor: nothing allocated, nothing answered. */ + /* + * Any other co-processor: nothing allocated, nothing answered, and the + * message reported through the rate-limited unknown-endpoint warning, + * since the firmware decides how often it arrives. + */ deliver(&plain, false, small); - assert(allocations == 0 && sent == 0 && aux == 0); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); deliver(&plain, false, largest); - assert(allocations == 0 && sent == 0 && aux == 0); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); deliver(&plain, false, event); - assert(allocations == 0 && sent == 0 && aux == 0); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); + + /* A system endpoint nobody serves takes the same warning. */ + deliver_ep(&asks, false, 0x10, small); + assert(allocations == 0 && sent == 0 && aux == 0 && warned == 1); puts("PASS endpoint 7 is served only for the clients the endpoint map starts it for"); return 0; @@ -191,6 +206,8 @@ def main(): if name == 'apple_rtkit_needs_coreanalytics': # The one predicate the endpoint map and the dispatcher share; absent before it. code += function(source, 'apple_rtkit_ep7_served', optional=True) + # The one rate-limited warning for unserved endpoints; absent before it. + code += function(source, 'apple_rtkit_unserved_ep_msg', optional=True) code += MAIN def run(out): diff --git a/tools/asahi/rtkit-oslog-tests.py b/tools/asahi/rtkit-oslog-tests.py index 0f1bbf7be90c4c..944e07c67b887d 100644 --- a/tools/asahi/rtkit-oslog-tests.py +++ b/tools/asahi/rtkit-oslog-tests.py @@ -74,6 +74,7 @@ def function(source, name): #define kfifo_reset(f) (*(f)=0) #define dev_dbg(...) ((void)0) #define dev_warn(...) (++warnings) +#define dev_warn_ratelimited(...) (++warnings) #define dev_err(...) (++errors) static void set_bit(unsigned n, unsigned long *b) { b[n/64] |= 1UL << (n%64); } static void bitmap_zero(unsigned long *b, unsigned n) { memset(b,0,n/8); } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index c40bbc8e3ffb0c..aeecc282cb26e6 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -36,6 +36,7 @@ def oslog(root): static bool neo, m5; #define of_machine_is_compatible(s) ((!strcmp(s,"apple,t8140") && neo) || (!strcmp(s,"apple,t8142") && m5)) #define dev_warn(dev,fmt,msg) do { (void)(dev); (void)(fmt); warnings++; observed=(msg); } while (0) +#define dev_warn_ratelimited(dev,fmt,msg) dev_warn(dev,fmt,msg) #define dev_dbg(dev,fmt,msg) do { (void)(dev); (void)(fmt); notifications++; observed=(msg); } while (0) #define dev_err(dev,fmt,msg) do { (void)(dev); (void)(fmt); (void)(msg); errors++; } while (0) static int __attribute__((unused)) apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *completion, bool atomic) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 9bedfb0e0eded8..8baa88f4e43952 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -177,6 +177,9 @@ def main(): 'assert(!"The PMP auxiliary buffer is outside this ordered-display fixture")\n') # A display co-processor doesn't take CoreAnalytics buffers. prefix += '#define apple_rtkit_ep7_served(...) false\n' + # Nor does it receive messages for endpoints it doesn't serve. + prefix += ('#define apple_rtkit_unserved_ep_msg(...) ' + 'assert(!"No unserved endpoint is in this ordered-display fixture")\n') unit = prefix + unit if unit is not None: result['translation_unit_sha256'] = run_unit(name, unit, output, cases, includes if name == 'service-rebind' else (), flags) From e562a5c23a96bbb97092a250b12b128ffebcb675 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 15:52:13 -0800 Subject: [PATCH 0302/1514] drm/asahi: g17: tie kick-ring views to a render pair's time in a VM A render pair's two kick rings are mapped read-only into the VM of the client that runs on the pair. That view was handed to the VM and kept until the VM was closed, so after the pair moved to a queue of another client the previous VM still mapped the rings. A pair rebound in place to a context of another VM was also not cleared first. The views of the kick rings now belong to the pair's time in a VM instead of to the VM. The pair holds them while it runs that VM's contexts and moves between them, and keeps them while it is parked for as long as the VM is open, so a later context of that VM reuses them. Once the client has closed the VM, a parked pair gives them up: when it parks, when it comes back from a failed rebuild, and, for pairs already parked, when the VM is closed. A parked pair therefore never keeps a closed VM's page tables alive. The views are dropped off the device lock. When the pair goes to a context of another VM, the rings are cleared and the new owner's first entry is written only after the previous VM's views are gone. From the parked state, the previous VM's views are removed and the rings cleared before the new VM's views exist. On an in-place rebind, the rings are cleared first, the new VM's views are then created while the previous VM's still exist, and the previous VM's views are removed when the new binding is installed; both are read-only and the cleared rings hold no entries, so neither VM can read the other's. Either way the pair is idle and the firmware consumed every entry; a rebind that fails keeps the previous VM's views. A pair drops its views before its rings, so a ring that is reused never finds an older view of its pages. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/kick.rs | 36 +++++----- drivers/gpu/drm/asahi/g17/mod.rs | 15 ++++ drivers/gpu/drm/asahi/g17/object.rs | 6 +- drivers/gpu/drm/asahi/g17/queue/render.rs | 51 ++++++++++++-- .../gpu/drm/asahi/g17/queue/render/parked.rs | 68 +++++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/render.rs | 12 ++++ .../drm/asahi/g17/runtime/render/prepare.rs | 8 ++- 7 files changed, 162 insertions(+), 34 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 5f49bf1b5093d8..89d9baea757f43 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -410,7 +410,7 @@ struct RenderStorage { // The lower alias drops before its backing. low: mmu::KernelMapping, high: KernelObject, - /// The client VM the storage was created for, whose alias of it lasts as long as that VM. + /// The client VM the storage was created for, or last handed to. vm: u64, /// That VM's status, which tells when its client closed it. status: Option>, @@ -425,13 +425,11 @@ impl RenderStorage { /// Render ring storage outlives its rings for the life of the device. /// -/// A client VM keeps each render ring alias it installs until the VM closes, -/// while an installed pair whose identities were never published can be -/// reclaimed and its rings dropped. Freeing that storage would hand its shared -/// lower address to another ring; a client still aliasing the old pages there -/// that later receives the new ring could not alias it (`prepare_client_alias` -/// fails with EFAULT). Retired storage is therefore kept and reused by later -/// rings: an address keeps naming the same pages, so every alias stays valid. +/// An installed pair whose identities were never published can be reclaimed +/// and its rings dropped. Retired storage is kept and reused by later rings, so +/// a ring's shared lower address keeps naming the same pages. A client's views +/// of a ring belong to the render pair holding it (`Pair::client_kicks`), +/// which drops them before the ring, so no VM has a view of retired storage. #[pin_data] pub(crate) struct RenderRings { #[pin] @@ -461,8 +459,7 @@ impl RenderRings { } /// Reusable storage created for `client`, else storage whose VM its client has closed, - /// which then belongs to `client`. Storage of another open VM is never handed out: that VM - /// keeps its read-write alias of the pages, so it could read and write the new ring. + /// which then belongs to `client`. Storage of another open VM is never handed out. fn take(&self, client: &mmu::Vm) -> Option { let vm = client.id(); let mut stock = self.stock.lock(); @@ -518,8 +515,8 @@ impl Drop for RenderRing { } } -/// An installed queue's permanent ring. Client aliases are held by the bound -/// context graph and must be dropped before this object. +/// An installed queue's permanent ring. A render ring's client views are held by its pair +/// for its time in their VM and must be dropped before this object. pub(crate) struct Queue { backing: Backing, id: Id, @@ -587,9 +584,9 @@ impl Queue { }) } - /// Retired storage of a never-written ring is reused first. Its address - /// names the same pages in every client that aliases it, so an existing - /// alias in `client` is kept (None) and a missing one is created. + /// Retired storage of a never-written ring is reused first. The returned view of the ring + /// in `client` is new: views belong to the pair that holds the ring, which drops them before + /// the ring, so retired storage has none. pub(crate) fn render( alloc: &Allocator<'_>, id: Id, @@ -613,8 +610,9 @@ impl Queue { ring.storage .high .prepare_alias(client, address, CLIENT_KICK_PROT, false); - // On failure the storage returns to the stock and a fresh ring is built. - if let Ok(alias) = alias { + // On failure, or if `client` still had a view of the pages, the storage returns to + // the stock and a fresh ring is built. + if let Ok(Some(alias)) = alias { return Ok(( Self { backing: Backing::Render(ring), @@ -622,7 +620,7 @@ impl Queue { timestamp: KickTimestamp::FIRST, previous: None, }, - alias, + Some(alias), )); } } @@ -736,7 +734,7 @@ impl Queue { Ok(()) } - /// Reuse a permanent client view only when every page names this ring. + /// Reuse the pair's client view only when every page names this ring. pub(crate) fn prepare_client_alias(&self, vm: &mmu::Vm) -> Result> { let object = match &self.backing { Backing::Compute { low, .. } => low, diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..7383d76d9c4a27 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2498,6 +2498,21 @@ impl gpu::Gpu for Gpu { self.shared.crashed.load(Ordering::Acquire) } + /// A parked render pair keeps its views of the kick rings in the VM that last ran on it + /// while that VM is open. Once the client has closed the VM (its status says so before + /// this runs), they go, one pair at a time and dropped off the device lock, so they do not + /// keep the VM's page tables alive. A pair that parks or returns after this sees the + /// closed status itself. + fn vm_closed(&self, _vm: &mmu::Vm) { + loop { + let views = (*self.shared.state.lock()) + .as_deref_mut() + .and_then(|firmware| firmware.queues.take_closed_parked_views()); + let Some(views) = views else { break }; + drop(views); + } + } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS) diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index 6922d130852244..de422808e8e668 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -137,9 +137,9 @@ impl KernelObject { } else { error }) } - /// Reuses only a complete alias of this exact retained backing. Permanent - /// queue aliases stay owned by the client VM after a physical pair moves; - /// returning to that VM must not replace or duplicate those mappings. + /// Reuses only a complete alias of this exact retained backing. A render pair keeps its + /// views of its kick rings while it moves between contexts of one VM; preparing the view + /// for that VM again must not replace or duplicate them. pub(crate) fn prepare_alias( &self, vm: &mmu::Vm, diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 4273f178bf602f..77f6897574ad58 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -196,6 +196,11 @@ pub(crate) struct Pair { /// acknowledgement: the pair keeps its owner and graph until then. channel_error: bool, kick_aliases: Option<[Option; 2]>, + /// The read-only views of the two kick rings in the VM of the pair's contexts, installed with + /// its first graph in that VM. They belong to the pair's time in that VM, not to the VM: they + /// go before the pair runs a context of another VM, so its previous owner cannot read the + /// new owner's kick entries. Dropped before `kicks`. + client_kicks: [Option; 2], memory: KBox, kicks: [kick::Queue; 2], free_list: Arc, @@ -353,6 +358,7 @@ impl Pair { storage.write_init(kernel::try_init!(Self { pool_pin, kick_aliases: Some([ta_alias, fragment_alias]), + client_kicks: [None, None], memory, kicks: [tiling, fragment], free_list, @@ -2820,10 +2826,13 @@ impl Pair { &mut self.memory, &mut self.pending_aliases, &mut self.kick_aliases, + &mut self.client_kicks, ) } } +/// Installs a graph's memory. The new kick ring views in `kick_aliases` go to `views`, the +/// pair's views in the graph's VM ([`Pair::client_kicks`]). fn install_memory( alloc: &Allocator<'_>, descriptors: &crate::g17::object::KernelObject, @@ -2831,6 +2840,7 @@ fn install_memory( memory: &mut memory::Memory, pending_aliases: &mut Option>, kick_aliases: &mut Option<[Option; 2]>, + views: &mut [Option; 2], ) -> Result { use core::sync::atomic::{fence, Ordering}; if pending_aliases.is_none() && kick_aliases.is_none() { @@ -2839,8 +2849,6 @@ fn install_memory( if !memory.context.is_current() || kick_aliases.is_none() { return Err(EIO); } - let mut driver = KVec::new(); - driver.reserve(2, GFP_KERNEL)?; let aliases = memory.take_persistent(pending_aliases.as_mut().ok_or(EIO)?)?; let context = memory.context.clone(); let vm = context.vm(); @@ -2869,10 +2877,11 @@ fn install_memory( } fence(Ordering::SeqCst); staged = Some(previous); - for mapping in kick_aliases.take().ok_or(EIO)?.into_iter().flatten() { - driver.push(mapping, GFP_KERNEL)?; + for (view, alias) in views.iter_mut().zip(kick_aliases.take().ok_or(EIO)?) { + if alias.is_some() { + *view = alias; + } } - vm.append_driver_mappings(driver)?; Ok(()) })(); if let Err(error) = result { @@ -2914,6 +2923,10 @@ pub(crate) struct PreparedBinding { /// The registry retains displaced backing until this exact context's release /// is acknowledged. A warm binding retains the old context without its graph. pub(crate) struct RetiredBinding { + /// Views of the kick rings in `context`'s VM that a pair parked after the VM's client + /// closed it gave up (`Pair::park`). Only held: declared first, they drop before the + /// memory and the context below. + _client_kicks: [Option; 2], memory: Option>, context: Arc, pool: Arc, @@ -3153,10 +3166,25 @@ impl Pair { let pm_generation = pm_generation.ok_or(EINVAL)?; let layout = m5_render_submission::layout(&first.command, self.clusters, self.variant.programs)?; + // A context of another VM gets the rings cleared before its VM is given its view, + // so it cannot read the entries earlier owners' commands left, as for a parked pair. + // The pair is bindable, hence idle: the firmware consumed every entry. + let other_vm = self.context().vm().id() != context.vm().id(); + if other_vm { + for kick in &mut self.kicks { + kick.clear_render_ring()?; + } + } let aliases = [ self.kicks[0].prepare_client_alias(context.vm())?, self.kicks[1].prepare_client_alias(context.vm())?, ]; + // A view the VM already has is the one this pair holds for it. + for (alias, view) in aliases.iter().zip(&self.client_kicks) { + if alias.is_none() && (other_vm || view.is_none()) { + return Err(EFAULT); + } + } let (memory, persistent) = memory::Memory::new( alloc, pool, @@ -3213,6 +3241,7 @@ impl Pair { } else { None }; + let mut views = [None, None]; let installed = install_memory( alloc, descriptors, @@ -3220,6 +3249,7 @@ impl Pair { memory, &mut binding.aliases, &mut binding.kicks, + &mut views, ); if let Err(error) = installed { if let Some((slot, mappings)) = moved { @@ -3228,6 +3258,16 @@ impl Pair { return Err(error); } drop(moved); + // The previous VM's views go before the new owner's first kick entry is written. + if self.context().vm().id() != binding.context.vm().id() { + drop(core::mem::replace(&mut self.client_kicks, views)); + } else { + for (view, alias) in self.client_kicks.iter_mut().zip(views) { + if alias.is_some() { + *view = alias; + } + } + } } else { // The same logical context keeps its M5 queue records: their host // words already name it, and a rewrite would store firmware-owned @@ -3246,6 +3286,7 @@ impl Pair { .take() .map(|memory| core::mem::replace(&mut self.memory, memory)); let retired = RetiredBinding { + _client_kicks: [None, None], memory: old_memory, context: old_context, pool: old_pool, diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index 6313bf2ef5128a..35e39e2130b855 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -18,6 +18,9 @@ use kernel::{prelude::*, sync::Arc}; /// without retaining that scheduler's execution context or client root. A prior /// context awaiting an executed replacement keeps its separate retirement owner. pub(crate) struct ParkedPair { + /// The pair's views of the kick rings in `vm` ([`Pair::client_kicks`]), dropped before + /// `kicks`. + client_kicks: [Option; 2], kicks: Option<[kick::Queue; 2]>, _scheduler: Arc, ids: [kick::Id; 2], @@ -40,6 +43,8 @@ pub(crate) struct ParkedPair { executed: u64, /// The VM of the context that last ran on these rings. vm: u64, + /// That VM's status, which tells when its client closed it ([`Self::take_closed_views`]). + status: Option>, } /// All new graph ownership stays separate from the installed kick storage until commit. @@ -49,6 +54,8 @@ pub(crate) struct Prepared { pool: Arc, aliases: Option>, kicks: Option<[Option; 2]>, + /// The new views of the kick rings, once installed. + views: [Option; 2], ids: [kick::Id; 2], slot: u8, ordinal: u64, @@ -87,10 +94,20 @@ impl Pair { pub(crate) fn park(self) -> (ParkedPair, RetiredBinding) { let context = self.memory.context.clone(); let vm = context.vm().id(); + let status = context.vm().status().cloned(); let scheduler = context.scheduler_owner(); let buffer_id = self.buffer_id(); + // A pair parked after its VM's client closed it keeps no views there: they go with the + // retired binding, whose context holds that VM anyway, and drop with it off the device + // lock. + let (client_kicks, retired_kicks) = if closed(status.as_ref()) { + ([None, None], self.client_kicks) + } else { + (self.client_kicks, [None, None]) + }; let parked = ParkedPair { ids: self.kicks.each_ref().map(|queue| queue.id()), + client_kicks, kicks: Some(self.kicks), _scheduler: scheduler, slot: self.slot, @@ -107,8 +124,10 @@ impl Pair { previous: self.previous, executed: self.executed, vm, + status, }; let retired = RetiredBinding { + _client_kicks: retired_kicks, memory: Some(self.memory), context, pool: self.free_list, @@ -121,21 +140,41 @@ impl Pair { } } +/// The client of the VM with this status closed it: nothing runs there again. +fn closed(status: Option<&Arc>) -> bool { + status.is_some_and(|status| status.client_closed()) +} + impl ParkedPair { - /// Clears both kick rings when the pair goes to a context of another VM than the one - /// that last ran on it, so the new owner cannot read the entries the previous owner's - /// commands left. The pair is parked, so the firmware consumed every entry. - pub(crate) fn clear_for_vm(&mut self, vm: u64) -> Result { - if self.vm == vm { + /// Removes the previous VM's views of both kick rings and clears the rings when the pair + /// goes to a context of another VM than the one that last ran on it, so neither owner can + /// read the entries the other's commands leave there. The pair is parked, so the firmware + /// consumed every entry and no longer reads the rings through those views. + pub(crate) fn clear_for_vm(&mut self, vm: &mmu::Vm) -> Result { + if self.vm == vm.id() { return Ok(()); } + self.client_kicks = [None, None]; for queue in self.kicks.as_mut().ok_or(EBUSY)?.iter_mut() { queue.clear_render_ring()?; } - self.vm = vm; + self.vm = vm.id(); + self.status = vm.status().cloned(); Ok(()) } + /// Takes the pair's views of the kick rings once the client of the VM they are in has + /// closed it, for the caller to drop off the device lock: each view holds that VM, whose + /// page tables would otherwise stay alive for as long as the pair stays parked. A later + /// context of the same VM gets new views, as one of another VM does. + pub(crate) fn take_closed_views(&mut self) -> [Option; 2] { + if closed(self.status.as_ref()) { + core::mem::take(&mut self.client_kicks) + } else { + [None, None] + } + } + /// The release of `scheduler` has been consumed: a later owner change no /// longer has to wait for it. pub(crate) fn release_consumed(&mut self, scheduler: u64) { @@ -186,6 +225,13 @@ impl ParkedPair { kicks[0].prepare_client_alias(context.vm())?, kicks[1].prepare_client_alias(context.vm())?, ]; + // A view the VM already has is the one this pair holds for it (`clear_for_vm` dropped + // those of any other VM). + for (alias, view) in aliases.iter().zip(&self.client_kicks) { + if alias.is_none() && view.is_none() { + return Err(EFAULT); + } + } let (memory, persistent) = memory::Memory::new( alloc, pool, @@ -206,6 +252,7 @@ impl ParkedPair { pool: free_list, aliases: Some(persistent), kicks: Some(aliases), + views: [None, None], ids: self.ids, slot: self.slot, ordinal: self.ordinal, @@ -248,10 +295,18 @@ impl ParkedPair { self.kicks = Some(kicks); return Err(EIO); }; + // The new views, else the ones this pair already held in the same VM. + let mut client_kicks = core::mem::take(&mut next.views); + for (view, held) in client_kicks.iter_mut().zip(self.client_kicks.iter_mut()) { + if view.is_none() { + *view = held.take(); + } + } storage.write_init(kernel::try_init!(Pair { pool_pin: next.pool_pin.take(), graph_started: false, kick_aliases: None, + client_kicks, memory, kicks, free_list: next.pool.clone(), @@ -319,6 +374,7 @@ impl Prepared { self.memory.as_mut().ok_or(EIO)?, &mut self.aliases, &mut self.kicks, + &mut self.views, )?; self.installed = true; Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index ab33c149ba96d3..450234d27cbb7d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1401,6 +1401,18 @@ impl RenderState { } impl Registry { + /// The kick-ring views of one parked pair whose VM's client has closed it + /// (`ParkedPair::take_closed_views`), for the caller to drop off the device lock; `None` + /// once no parked pair holds any. + pub(in crate::g17) fn take_closed_parked_views( + &mut self, + ) -> Option<[Option; 2]> { + self.render.entries.iter_mut().flatten().find_map(|entry| { + let views = entry.parked.as_mut()?.take_closed_views(); + views.iter().any(Option::is_some).then_some(views) + }) + } + /// Give idle private backing to another ready client under capacity pressure. /// Keep graph/QID/context ownership; the next use rearms the same pool after /// its consumed release, exactly as eviction-driven reclaim does. diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 71f6e4b5943a25..a90d5dea25c24d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -537,7 +537,7 @@ impl super::super::Backend { first, } = *ctx; let built = (|| -> Result<_> { - parked.clear_for_vm(self.context.vm().id())?; + parked.clear_for_vm(self.context.vm())?; let free_list = self.context.render_pool( alloc, &resources.ids, @@ -613,10 +613,15 @@ impl super::super::Backend { // returns, while the original installed kick owner stays live. drop(prepared); drop(storage); + // Views a returning pair gives up because its VM closed meanwhile; they drop after the + // device lock. Checked under the lock, so a VM closed before the pair is back is seen + // either here or by the close's own pass (`Registry::take_closed_parked_views`). + let mut closed_views = [None, None]; let grow_ready = { let mut state = self.shared.state.lock(); let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; if result.is_err() { + closed_views = parked.take_closed_views(); firmware.queues.render.entry_mut(slot)?.parked = Some(parked); firmware.queues.buffers.release(buffer.0)?; } else { @@ -634,6 +639,7 @@ impl super::super::Backend { } firmware.render_grow_ready() }; + drop(closed_views); self.shared.note_changed(); if grow_ready { self.shared.queue_grow(); From af97a52c0a587e084aed2e715dfe716d3e444d43 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Fri, 20 Nov 2026 05:42:26 -0700 Subject: [PATCH 0303/1514] mfd: macsmc: count a port's dark wake on every board with a sleep policy apple_smc_prepare_guard() waits for a command in flight only when dark_wakes is set, and apple_smc_dark_wake() returns for every board but the J714s before it counts a wake that apple_sleep_port_wake() already made dark. On the other boards with a sleep policy (the J716c) the guard at .suspend after a port's wake with the lid closed is then a single trylock: if a command of the wake is still running, .suspend returns -EBUSY and the dark wake ends in a full one. Count the wake first, then keep the J714s's own rule to the J714s. The comment on the wait no longer names the J714s. A board without a sleep policy (the J813) does not get here and is not changed. Fixes: 18b493373c7c ("mfd: macsmc: J714s: keep the port and radio dark wakes to the J714s") Signed-off-by: Jens Axboe --- drivers/mfd/macsmc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index a22d119c1694ad..0f43520741fdf9 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -1022,14 +1022,14 @@ static void apple_smc_dark_wake(struct apple_smc *smc) const char *why = is_radio ? "wifibt" : "USB-C_plug"; s64 asleep_ms; - /* The J714s's rule alone: other boards with a sleep policy keep these wakes full. */ - if (smc->wake_reasons != apple_smc_j714s_wake_reasons) - return; /* Already dark (a port's wake with the lid closed): counted, so the re-entry waits as after ours. */ if (pm_dark_wake()) { smc->dark_wakes++; return; } + /* The J714s's rule alone: other boards with a sleep policy keep these wakes full. */ + if (smc->wake_reasons != apple_smc_j714s_wake_reasons) + return; if (!is_radio && (port < 0 || smc->wake_record != BIT_ULL(port))) return; asleep_ms = ktime_ms_delta(ktime_get_boottime(), smc->sleep_entry_boot) - @@ -1489,7 +1489,7 @@ static int apple_smc_prepare_policy(struct apple_smc *smc) /* * The saved-context guard, under the command mutex, without waiting for it: a sleep a user asks - * for doesn't wait on a stuck command. The re-entry right after a J714s dark wake does, for at + * for doesn't wait on a stuck command. The re-entry right after a counted dark wake does, for at * most SMC_DARK_REENTRY_MS: the notification of the event that woke it is still being handled * then, its ordinary command in flight, and refusing ended every dark wake in a full one. */ From fc11f9496aa4c21bd819b6f5ce60bf37920c6a5e Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Sun, 22 Nov 2026 07:28:56 -0700 Subject: [PATCH 0304/1514] arm64: dts: apple: t6050-k116s: High Power mode macOS offers High Power mode on the 16-inch M5 Pro. Say so on the CLPC node, and keep the CLPC's SMC link the record is sent over, which was held back here until it had been tried. On a K116s the SMC on firmware 27.2 takes the record as the J714s's 27.0 does: in the performance profile the fans run up to their maximum under a sustained load, where they level off at 62 % of it otherwise. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-k116s.dts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index fe6468edc72c10..2c951afdc61bbc 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -872,18 +872,17 @@ #include "t6050-j716c-isp.dtsi" /* - * Two things the shared T6050 files now turn on for every board are held back here until - * they have been tried on the K116s: the CPU PMU (t6050-base.dtsi, measured on the J714s) - * and the CLPC's SMC link (t6050-die0.dtsi), through which the low-power platform profile - * polls the package power. Without the link that profile has only its frequency ceiling. - * To try them, remove this block. + * The CPU PMU the shared T6050 files turn on for every board (t6050-base.dtsi, measured on + * the J714s) is held back here until it has been tried on the K116s. To try it, remove + * this block. */ &cpu_pmu { status = "disabled"; }; +/* macOS offers High Power mode on this machine */ &clpc { - /delete-property/ apple,smc; + apple,high-power-mode; }; /* From e641792fadcd392a3fd8935608fcbc10e5cd4605 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 21:41:34 +0700 Subject: [PATCH 0305/1514] dt-bindings: power: apple,pmc: Add the CLPC's Low Power mode ceiling Let the boot loader pass the CPU frequency ceiling of macOS's Low Power mode, which the ADT has as pmgr/clpc cpu-low-power-frequency-max, on the performance controller node. The property keeps the ADT's unit (MHz), so the loader copies the value as it is. The name and text match the property proposed for the same ADT key on the M4 Pro and Max MacBook Pros. Signed-off-by: Nick --- Documentation/devicetree/bindings/power/apple,pmc.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index 434126bb21506f..32636c38f23dde 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -278,6 +278,13 @@ patternProperties: offers on some MacBook Pros. The performance platform profile then tells the SMC (apple,smc) that it is on. + apple,low-power-frequency-max-mhz: + description: + The machine's CPU frequency ceiling in macOS's Low Power mode, in + MHz, as the ADT's cpu-low-power-frequency-max has it. The low-power + platform profile holds the CPU clusters to it, up to the next + frequency of their tables. + required: - compatible - reg From 4e0335927443de39e3c14c101e10649afa80e50b Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 21:41:34 +0700 Subject: [PATCH 0306/1514] soc: apple: clpc: Take the Low Power mode ceiling from the DT The ADT has macOS's Low Power mode CPU ceiling as pmgr/clpc cpu-low-power-frequency-max: 2220 MHz on the J704, J813 and J815 (M5), 2088 MHz on the J713 (M4 Air), 3144 MHz on the J700. The boot loader now copies it into the CLPC node as apple,low-power-frequency-max-mhz. Register the low-power platform profile wherever the node has that property, with its value as the ceiling. A node without it keeps the SoC's built-in value where there is one, so the T6041 and T8140 profiles stay as they are under an older loader. With the same ceiling built into the driver for the J815, low-power took its P cluster from 4464 to 2220 MHz and back (M5, 27.2 stub). Signed-off-by: Nick [Ryan: rebased onto the DT High Power mode change (68986f0e, ef719df7): the four places that read hw->low_power_khz for the profile (the profile and SMC gates, the policy notifier, the profile name and the idle-sampling decision) now read clpc->low_power_khz, so a DT-only ceiling registers as apple-clpc and keeps its ceiling; the host test model carries the new field.] Signed-off-by: Ryan Murray --- drivers/soc/apple/clpc.c | 38 +++++++++++++++++++--------- tools/asahi/clpc-gpu-demand-tests.py | 6 +++-- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 4bd3d6c7c0a950..9c40a734cb8edf 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -105,7 +105,8 @@ enum apple_clpc_rail { * @idle_on_time: sample every period even with no vote held, instead of * from a deferrable timer * @low_power_khz: CPU frequency ceiling of the low-power platform profile, - * taken up to the next table frequency; 0 for no platform profile + * taken up to the next table frequency, for a node without + * apple,low-power-frequency-max-mhz; 0 for no platform profile * @low_power_mw: package power (the SMC's PHPC key) the low-power profile * holds the CPU clusters to; 0 for none * @high_power_machine: the machine compatible that had High Power mode from @@ -234,6 +235,8 @@ struct apple_clpc { /* The platform profile and, for its power target, the SMC */ enum platform_profile_option profile; bool low_power; + /* the DT ceiling, else hw->low_power_khz, else 0 */ + unsigned int low_power_khz; struct device_node *smc_np; struct apple_smc *smc; /* The performance profile is sent to the SMC as High Power mode */ @@ -845,7 +848,7 @@ static bool apple_clpc_steps_first(unsigned int a_khz, unsigned int a_max, /* * The platform profile's ceilings. In the low-power profile every cluster - * stays at or below the first frequency at or above hw->low_power_khz. Each + * stays at or below the first frequency at or above clpc->low_power_khz. Each * new package power reading above hw->low_power_mw takes one table step off * one cluster, and each one below 90% of it puts one back, in the order of * apple_clpc_steps_first(). Elsewhere there is no ceiling. @@ -857,7 +860,7 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) unsigned int i, khz, pick_khz = 0; int mw, step = 0, pick = -1; - if (!clpc->hw->low_power_khz || time_before(jiffies, clpc->power_next)) + if (!clpc->low_power_khz || time_before(jiffies, clpc->power_next)) return; clpc->power_next = jiffies + msecs_to_jiffies(APPLE_CLPC_POWER_MS); if (low && clpc->hw->low_power_mw) { @@ -883,10 +886,10 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) freq_qos_add_request(&policy[i]->constraints, &cl->max_qos, FREQ_QOS_MAX, FREQ_QOS_MAX_DEFAULT_VALUE) < 0) clpc->update_errors++; - /* The top: the first table frequency at or above hw->low_power_khz */ + /* The top: the first table frequency at or above clpc->low_power_khz */ cl->top_khz = apple_clpc_step_khz(policy[i], - clpc->hw->low_power_khz - 1, true); - if (cl->top_khz < clpc->hw->low_power_khz) + clpc->low_power_khz - 1, true); + if (cl->top_khz < clpc->low_power_khz) cl->top_khz = policy[i]->cpuinfo.max_freq; if (!low) cl->max_khz = 0; @@ -998,7 +1001,7 @@ static void apple_clpc_sample(struct apple_clpc *clpc) */ apple_clpc_queue(clpc, !apple_clpc_floor(clpc, state) && !clpc->gpu_on && !clpc->ane_qos_khz && - !(clpc->hw->low_power_khz && READ_ONCE(clpc->low_power))); + !(clpc->low_power_khz && READ_ONCE(clpc->low_power))); } static void apple_clpc_run(struct apple_clpc *clpc) @@ -1061,7 +1064,7 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) } seq_printf(s, "samples: %lu update errors: %lu\n", clpc->samples, clpc->update_errors); - if (clpc->hw->low_power_khz) { + if (clpc->low_power_khz) { seq_printf(s, "profile: %s power %d mW (%lu new of %lu readings) ceilings (kHz):", clpc->profile == PLATFORM_PROFILE_LOW_POWER ? "low-power" : clpc->profile == PLATFORM_PROFILE_PERFORMANCE ? "performance" : @@ -1367,6 +1370,7 @@ static int apple_clpc_probe(struct platform_device *pdev) struct apple_clpc *clpc; unsigned int rail, i; bool high_power; + u32 mhz; int ret; clpc = devm_kzalloc(dev, sizeof(*clpc), GFP_KERNEL); @@ -1504,6 +1508,15 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->profile = PLATFORM_PROFILE_BALANCED; clpc->power_next = jiffies; + /* + * The boot loader copies the ADT's Low Power mode CPU ceiling + * (pmgr/clpc cpu-low-power-frequency-max) into the node. Without it, + * a SoC's own value applies where it has one. + */ + if (!of_property_read_u32(dev->of_node, "apple,low-power-frequency-max-mhz", &mhz)) + clpc->low_power_khz = mhz * 1000; + else + clpc->low_power_khz = clpc->hw->low_power_khz; /* * The board DT says whether the machine has High Power mode: then the * performance profile tells the SMC that it is on (the zETM record). @@ -1518,16 +1531,17 @@ static int apple_clpc_probe(struct platform_device *pdev) */ if (!high_power && clpc->hw->high_power_machine) high_power = of_machine_is_compatible(clpc->hw->high_power_machine); - if ((clpc->hw->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + if ((clpc->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { /* The SMC is optional: without it the low-power profile has only its ceiling. */ clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); clpc->high_power = clpc->smc_np && high_power; } /* High Power mode alone needs the SMC; without it there is no profile. */ - if ((clpc->hw->low_power_khz || clpc->high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + if ((clpc->low_power_khz || clpc->high_power) && + IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { struct device *ppdev; - if (clpc->hw->low_power_khz && !clpc->policy_nb_added) { + if (clpc->low_power_khz && !clpc->policy_nb_added) { clpc->policy_nb.notifier_call = apple_clpc_policy_notify; clpc->policy_nb_added = !cpufreq_register_notifier(&clpc->policy_nb, CPUFREQ_POLICY_NOTIFIER); @@ -1536,7 +1550,7 @@ static int apple_clpc_probe(struct platform_device *pdev) * "apple-clpc" budgets the low-power profile itself; "apple-smc" * only carries High Power mode, and userspace keeps the CPU budget. */ - ppdev = devm_platform_profile_register(dev, clpc->hw->low_power_khz ? "apple-clpc" : + ppdev = devm_platform_profile_register(dev, clpc->low_power_khz ? "apple-clpc" : "apple-smc", clpc, &apple_clpc_profile_ops); if (IS_ERR(ppdev)) dev_warn(dev, "no platform profile: %pe\n", ppdev); diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index ff36eb19c162cc..93174c98800397 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -112,6 +112,7 @@ def main(): unsigned int ane_qos_khz; unsigned long ane_until; bool low_power; + unsigned int low_power_khz; }; static unsigned long jiffies; static u64 ktime_get_mono_fast_ns(void) { return jiffies * 1000000ull; } @@ -277,14 +278,15 @@ def main(): } // Low power samples on time only where it has a CPU ceiling to keep -// (low_power_khz); a High Power-only profile stays deferrable when idle. +// (clpc->low_power_khz: the DT ceiling, else the table one); a High Power-only +// profile stays deferrable when idle. static void check_low_power(void) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_hw lp=apple_clpc_hw_t6040; struct apple_clpc c={.hw=&lp,.agent=1,.mask=3,.gpu=&gpu,.low_power=true}; read_error=vote_error=0; pmgr_status=0xf0; published=~0u; jiffies=3000; apple_clpc_sample(&c); assert(published==0 && queued_idle); - lp.low_power_khz=2808000; + c.low_power_khz=2808000; jiffies=3004; apple_clpc_sample(&c); assert(published==0 && !queued_idle); c.low_power=false; jiffies=3008; apple_clpc_sample(&c); assert(published==0 && queued_idle); From a7907d9ee4b84f1ac8948213bbd3e40b8028507b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 15:21:39 +0100 Subject: [PATCH 0307/1514] arm64: dts: apple: t8152-j873g: power domains for the USB and Ethernet DARTs Every enabled DART must name the power state of the engine it serves (scripts/dtc/apple-dart-pd-check.py). The J873g USB and Ethernet DARTs named none. USB: the controllers' state is the ATC PMGR's ATC1_USB (usb-drd1, on atc-phy1) and ATC2_USB (usb-drd2, on atc-phy2), as for the dwc3 DARTs on T8132. The ADT also gives usb-drd1/2 service-gates 175/176, but those PSD service blocks take a bus error from the CPU. The loader leaves ATCn_USB and ATCn_USB_AON on (read back as 0x3ff on J873g), and they hold the controllers' reset and the USB2 PHY setup it did, which Linux cannot redo yet. So all four stay on, without automatic power management. ATCn_USB is a child of ATCn_USB_AON, as on T8132, so the order holds if that ever changes. The DWC3 nodes take the same state as their DARTs. Ethernet: dart-apcie2 takes APCIE_SYS_GP (child of APCIE_GP), as pcie2_dart does on T8142. iBoot leaves both on (0x2ff and 0x1f0003ff), and the loader's PHY and lane setup for port 2 cannot be redone by Linux, so both stay on. APCIE_GP has no automatic state set, and automatic power management would power gate it, so it stays off for both. Offsets are from the 26A434 ADT pmgr device list. Signed-off-by: Thomas Glanzmann --- .../boot/dts/apple/t8152-j873-ethernet.dtsi | 33 +++++++ arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 88 ++++++++++++++++--- 2 files changed, 109 insertions(+), 12 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi index 8b4f0f007df54a..b40923e9fec9e4 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-ethernet.dtsi @@ -18,6 +18,38 @@ }; }; +/* + * The internal PCIe power states (ADT pmgr devices APCIE_GP and APCIE_SYS_GP, + * the latter's parent the former). iBoot leaves both on, and Linux cannot redo + * the PHY and lane setup the loader does on them, so they stay on, without + * automatic power management: APCIE_GP has no automatic state set and would + * be power gated by it. dart-apcie2 takes APCIE_SYS_GP, as on T8142. + */ +&pmgr { + ps_apcie_gp: power-controller@8c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x8c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_gp"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_apcie_sys_gp: power-controller@ec0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xec0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_sys_gp"; + power-domains = <&ps_apcie_gp>; + apple,no-auto-pm; + apple,always-on; + }; +}; + /* * dart-apcie2, described in t8152-peripherals.dtsi. The ADT window is * 0x20000; keep the 0xc000 this port was brought up with, the size that @@ -25,6 +57,7 @@ */ &pcie2_dart { reg = <0x3 0x8a000000 0x0 0xc000>; + power-domains = <&ps_apcie_sys_gp>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index dc4b2fb720f894..924df52e3622bb 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -3,12 +3,13 @@ * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 * (front ports via the on-board hub). * The loader powers the controllers and sets up the USB2 side of their ATC - * PHYs for host mode before Linux starts (there is no T8152 USB power-domain, - * ATC PHY or Type-C support yet). + * PHYs for host mode before Linux starts (there is no T8152 ATC PHY or Type-C + * support yet). * The controllers are described by their DWC3 core region, as hosts behind - * their two DARTs (apple,t8152-dwc3); their PHY reset and power domain, and on - * the Type-C port the role switch, exist but are left to the loader. - * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2. + * their two DARTs (apple,t8152-dwc3); their PHY reset, and on the Type-C port + * the role switch, exist but are left to the loader. + * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2 (on atc-phy1 and + * atc-phy2) and the pmgr devices ATC1_USB_AON/USB and ATC2_USB_AON/USB. * * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists @@ -18,29 +19,90 @@ * own window only, and describe instance 1 as a node of its own. */ -/* - * The USB DARTs' power domain is PSD service 175 (usb-drd1) and 176 (usb-drd2). - * It waits on the T8152 PSD provider (aurora-silicon/linux#2459), and must stay - * on until Linux can restore the USB2 PHY setup the loader leaves behind. - */ &dwc3_1_dart { reg = <0x4 0x0b020000 0x0 0xc000>; + power-domains = <&ps_atc1_usb>; status = "okay"; }; &dwc3_2_dart { reg = <0x3 0x83020000 0x0 0xc000>; + power-domains = <&ps_atc2_usb>; status = "okay"; }; / { soc { - /* Power domain: PSD service 175, see dwc3_1_dart above. */ + /* + * The ATCs' PMGR power states (ADT pmgr devices ATCn_USB_AON and + * ATCn_USB from 0x308290100, 0x40 apart per ATC). The ADT gives + * usb-drd1/2 service-gates 175/176, but those PSD service blocks + * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. + * + * The loader leaves them on; they hold the controllers' reset and + * the USB2 PHY setup it did, which Linux cannot redo yet. So they + * stay on, without automatic power management. + */ + pmgr_atc: power-management@308290000 { + compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", + "syscon", "simple-mfd"; + #address-cells = <1>; + #size-cells = <1>; + reg = <0x3 0x08290000 0x0 0x1000>; + + ps_atc1_usb_aon: power-controller@140 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc1_usb: power-controller@160 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x160 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_usb"; + power-domains = <&ps_atc1_usb_aon>; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc2_usb_aon: power-controller@180 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x180 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + + ps_atc2_usb: power-controller@1a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_usb"; + power-domains = <&ps_atc2_usb_aon>; + apple,no-auto-pm; + apple,always-on; + }; + }; + dwc3_1_dart_1: iommu@40b040000 { compatible = "apple,t8152-dart", "apple,t8110-dart"; reg = <0x4 0x0b040000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_atc1_usb>; }; usb1: usb@40a430000 { @@ -50,16 +112,17 @@ dr_mode = "host"; maximum-speed = "high-speed"; iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; + power-domains = <&ps_atc1_usb>; snps,dis_u2_susphy_quirk; snps,dis_u3_susphy_quirk; }; - /* Power domain: PSD service 176, see dwc3_1_dart above. */ dwc3_2_dart_1: iommu@383040000 { compatible = "apple,t8152-dart", "apple,t8110-dart"; reg = <0x3 0x83040000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_atc2_usb>; }; /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ @@ -70,6 +133,7 @@ dr_mode = "host"; maximum-speed = "high-speed"; iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; + power-domains = <&ps_atc2_usb>; snps,dis_u2_susphy_quirk; snps,dis_u3_susphy_quirk; }; From 4cce5434d0fcbb08e08cd764f9d2fc3c64fde820 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:54:10 +0100 Subject: [PATCH 0308/1514] soc: apple: rtkit: let clients register adopted endpoints A co-processor adopted from the bootloader has already sent its endpoint map, to the bootloader, so the application endpoints a client starts on it by hand are not in rtk->endpoints. Every message on them is then logged as one to an undiscovered endpoint. The T8152 DCP driver would get one per SET_SURFACE, about 60 lines a second during video. Add apple_rtkit_adopt_ep() for a client to register an application endpoint of such a session. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/rtkit.c | 12 ++++++++++++ include/linux/soc/apple/rtkit.h | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..e516f9d6cb6a9f 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2125,6 +2125,18 @@ bool apple_rtkit_v27_rx_drained(struct apple_rtkit *rtk) } EXPORT_SYMBOL_GPL(apple_rtkit_v27_rx_drained); +/* + * A co-processor adopted from the bootloader has already sent its endpoint + * map. A client that starts one of its application endpoints by hand + * registers it here, so its messages are not reported as undiscovered. + */ +void apple_rtkit_adopt_ep(struct apple_rtkit *rtk, u8 ep) +{ + if (ep >= APPLE_RTKIT_APP_ENDPOINT_START) + set_bit(ep, rtk->endpoints); +} +EXPORT_SYMBOL_GPL(apple_rtkit_adopt_ep); + int apple_rtkit_start_ep(struct apple_rtkit *rtk, u8 endpoint) { u64 msg; diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 4db916bb89f09d..c76e50bd67d595 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -512,4 +512,14 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops); +/* + * Registers an application endpoint the client started itself on a + * co-processor whose endpoint map the bootloader consumed, so that its + * messages are not reported as undiscovered + * + * @rtk: RTKit reference + * @ep: endpoint to register + */ +void apple_rtkit_adopt_ep(struct apple_rtkit *rtk, u8 ep); + #endif /* _LINUX_APPLE_RTKIT_H_ */ From 36b6071305bb7a9c5a62d52afa0617dfd9d46b9b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:55:49 +0100 Subject: [PATCH 0309/1514] dt-bindings: iommu: apple,dart: add the T8152 Gen3 display DARTs The DARTs in front of the T8152 display coprocessors (DCP, DCPEXT) and their display pipes (ADT "dart,gen3", version 0x300) use the T8110 register layout, but they belong to the SPTM, and the bootloader hands them over locked. Their TLB command register at 0x80 answers translation queries instead of flushing. A stream is invalidated the way iBoot does it: a payload naming the DART and the stream is written to the SoC's TLB invalidation aperture, which these DARTs share, and a broadcast TLBI follows. Add apple,t8152-dart-gen3 for them, without the apple,t8110-dart fallback, since a T8110 driver would flush through the wrong register, and a "tlbi" register entry for the DART's window in the aperture. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/iommu/apple,dart.yaml | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index 034e70bdc65589..d7e8e332951ade 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -32,6 +32,7 @@ properties: - apple,t8103-usb4-dart - apple,t8110-dart - apple,t6000-dart + - apple,t8152-dart-gen3 - items: - const: apple,t8140-ane-dart - const: apple,t8140-dart @@ -87,13 +88,16 @@ properties: fabric filter (GAPF) that protects the power state of the coprocessor CPU behind this DART, cleared to power that CPU down, or the shared PS write-disable register that holds this DART's - bit for the same purpose (T8142) + bit for the same purpose (T8142), or on a T8152 Gen3 DART its + window in the SoC's TLB invalidation aperture (ADT + dart-tlbi-aperture plus tlbi-aperture-offset), which the Gen3 + DARTs share reg-names: minItems: 1 items: - const: dart - - enum: [dapf, gapf, ps-wr-dis, auxiliary] + - enum: [dapf, gapf, ps-wr-dis, auxiliary, tlbi] interrupts: maxItems: 1 @@ -361,6 +365,35 @@ allOf: then: required: - reg-names + - if: + properties: + compatible: + contains: + const: apple,t8152-dart-gen3 + then: + description: + The T8152 Gen3 DARTs in front of the display coprocessors and their + display pipes belong to the SPTM. The bootloader hands them over + locked, and the operating system only adds page table entries in + root slots that are empty at handoff. Their TLB command register + answers translation queries; a stream is invalidated through the + TLB invalidation aperture instead. + properties: + reg: + minItems: 2 + reg-names: + items: + - const: dart + - const: tlbi + required: + - reg-names + else: + properties: + reg-names: + minItems: 1 + items: + - const: dart + - enum: [dapf, gapf, ps-wr-dis, auxiliary] additionalProperties: false From 2ac0620b46399f918c15e8a1ed90adcb8587e12e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:57:36 +0100 Subject: [PATCH 0310/1514] iommu: apple-dart: support the locked Gen3 DARTs of T8152 The T8152 display DARTs (ADT "dart,gen3", version 0x300) use the T8110 register layout but belong to the SPTM: their TLB command register at 0x80 answers translation queries instead of flushing. A stream is invalidated the way iBoot does it, by writing a 128-bit payload (valid, route, SID) to the SoC's shared TLBI aperture and broadcasting a TLBI, which the DART snoops. The route is the DART's 0x4604 register. Admit a Gen3 DART only when the bootloader hands it over locked (its streams cannot be set up cold yet), map the aperture from a second "tlbi" reg entry without claiming it, since every Gen3 DART shares it, flush the whole stream where a range flush would go through 0x80, and do not claim the fault interrupt or drain stale exceptions, whose handling acknowledges through that register as well. The range flush test fixture gains the new hw flag. Signed-off-by: Thomas Glanzmann --- drivers/iommu/apple-dart.c | 113 +++++++++++++++++- tools/asahi/apple-dart-range-tests.py | 2 +- .../drivers/apple/bcm4377-radio-sids.py | 1 + 3 files changed, 112 insertions(+), 4 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 9e009107f5a9d0..a6c45cf6399647 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -277,6 +277,8 @@ struct apple_dart; struct apple_dart_hw { enum dart_type type; + /* T8110 register layout, SPTM-owned TLB invalidation (T8152) */ + bool gen3; irqreturn_t (*irq_handler)(int irq, void *dev); int (*invalidate_tlb)(struct apple_dart_stream_map *stream_map); void (*enable_remap)(struct apple_dart *dart, int sid, int remap_to); @@ -540,6 +542,10 @@ struct apple_dart { unsigned int sleep_writers; bool sleep_closed; + /* Gen3: shared TLBI aperture and this DART's route in it */ + void __iomem *tlbi; + u8 tlbi_route; + DECLARE_BITMAP(remapped, DART_MAX_STREAMS); u8 remap_target[DART_MAX_STREAMS]; @@ -1998,6 +2004,43 @@ static int apple_dart_fw_invalidate(struct apple_dart_stream_map *stream_map, return 0; } +#define DART_GEN3_TLBI_ROUTE 0x4604 +#define DART_GEN3_TLBI_VALID BIT_ULL(60) +#define DART_GEN3_TLBI_ROUTE_FIELD GENMASK_ULL(59, 56) +#define DART_GEN3_TLBI_SID GENMASK_ULL(55, 48) + +/* + * Gen3 DARTs (T8152) are owned by the SPTM, and their TLB command register at + * 0x80 answers translation queries instead of flushing. A stream is + * invalidated the way iBoot does it: write a 128-bit payload (valid, route, + * SID) to the shared TLBI aperture, then broadcast a TLBI, which the DART + * snoops and applies to that stream. + */ +static int +apple_dart_gen3_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) +{ + struct apple_dart *dart = stream_map->dart; + unsigned long flags; + int sid; + + spin_lock_irqsave(&dart->lock, flags); + for_each_set_bit(sid, stream_map->sidmap, dart->num_streams) { + u64 lo = DART_GEN3_TLBI_VALID | + FIELD_PREP(DART_GEN3_TLBI_ROUTE_FIELD, dart->tlbi_route) | + FIELD_PREP(DART_GEN3_TLBI_SID, sid); + + dma_wmb(); + asm volatile("stp %0, xzr, [%1]\n" + "dsb ish\n" + ".inst 0xd50881bf\n" /* tlbi vale1os, xzr */ + "dsb osh\n" + : : "r"(lo), "r"(dart->tlbi) : "memory"); + } + spin_unlock_irqrestore(&dart->lock, flags); + + return 0; +} + static int apple_dart_t8020_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) { @@ -2736,8 +2779,11 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, /* The range registers take the DVA the device issues. */ start = first + domain->dma_offset; end = last + domain->dma_offset; - if (range && (stream.dart->fw_mirror || stream.dart->fw_handoff) && - stream.dart->version >= 0x0202) + /* Gen3 has no range command; invalidate the complete stream. */ + if (stream.dart->hw->gen3) + ret = stream.dart->hw->invalidate_tlb(&stream); + else if (range && (stream.dart->fw_mirror || stream.dart->fw_handoff) && + stream.dart->version >= 0x0202) ret = apple_dart_fw_invalidate(&stream, start, end); else if (range && stream.dart->locked && stream.dart->version >= 0x0202) ret = apple_dart_t8110_hw_tlb_command_range(&stream, op, true, @@ -5632,6 +5678,13 @@ static int apple_dart_probe(struct platform_device *pdev) * not admitted: never enable that level IRQ for one block alone. */ dart->irq = -1; + } else if (dart->hw->gen3) { + /* + * The T8110 fault handler acknowledges through the TLB command + * register, which a Gen3 DART uses for translation queries. + * Leave its faults to the firmware for now. + */ + dart->irq = -1; } else if (dart->preserve_display || j713_radio) { dart->irq = platform_get_irq_optional(pdev, 0); if (dart->irq == -ENXIO) @@ -6021,8 +6074,34 @@ static int apple_dart_probe(struct platform_device *pdev) goto err_clk_disable; } + if (dart->hw->gen3) { + struct resource *tlbi; + + /* Only an iBoot-provisioned (locked) Gen3 stream is supported. */ + if (!dart->locked) { + dev_err(dev, "Gen3 DART is not locked; cold setup is not supported\n"); + ret = -ENODEV; + goto err_clk_disable; + } + /* The aperture is shared by every Gen3 DART: map, do not claim. */ + tlbi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "tlbi"); + if (!tlbi || resource_size(tlbi) < 16) { + dev_err(dev, "Gen3 DART needs its TLBI aperture\n"); + ret = -EINVAL; + goto err_clk_disable; + } + dart->tlbi = devm_ioremap(dev, tlbi->start, resource_size(tlbi)); + if (!dart->tlbi) { + ret = -ENOMEM; + goto err_clk_disable; + } + dart->tlbi_route = apple_dart_readl(dart, DART_GEN3_TLBI_ROUTE) & 0xf; + dev_info(dev, "Gen3 DART, version %#x, TLBI route %u\n", + dart->version, dart->tlbi_route); + } + /* Borrowed display state: never acknowledge someone else's fault. */ - if (dart->locked && !dart->preserve_display) + if (dart->locked && !dart->preserve_display && !dart->hw->gen3) apple_dart_drain_stale_exceptions(dart); /* Refuse an already pending inherited fault before joining the shared IRQ. */ @@ -6377,6 +6456,33 @@ static const struct apple_dart_hw apple_dart_hw_t6000 = { .ttbr_count = 4, }; +static const struct apple_dart_hw apple_dart_hw_gen3 = { + .type = DART_T8110, + .gen3 = true, + .irq_handler = apple_dart_t8110_irq, + .invalidate_tlb = apple_dart_gen3_hw_invalidate_tlb, + .fmt = APPLE_DART2, + .max_sid_count = 256, + + .enable_streams = DART_T8110_ENABLE_STREAMS, + .lock = DART_T8110_PROTECT, + .lock_bit = DART_T8110_PROTECT_TTBR_TCR, + + .error = DART_T8110_ERROR, + + .tcr = DART_T8110_TCR, + .tcr_enabled = DART_T8110_TCR_TRANSLATE_ENABLE, + .tcr_disabled = 0, + .tcr_bypass = DART_T8110_TCR_BYPASS_DAPF | DART_T8110_TCR_BYPASS_DART, + .tcr_4level = DART_T8110_TCR_FOUR_LEVEL, + + .ttbr = DART_T8110_TTBR, + .ttbr_valid = DART_T8110_TTBR_VALID, + .ttbr_addr_field_shift = DART_T8110_TTBR_ADDR_FIELD_SHIFT, + .ttbr_shift = DART_T8110_TTBR_SHIFT, + .ttbr_count = 1, +}; + static const struct apple_dart_hw apple_dart_hw_t8110 = { .type = DART_T8110, .irq_handler = apple_dart_t8110_irq, @@ -7254,6 +7360,7 @@ static const struct dev_pm_ops apple_dart_pm_ops = { }; static const struct of_device_id apple_dart_of_match[] = { + { .compatible = "apple,t8152-dart-gen3", .data = &apple_dart_hw_gen3 }, { .compatible = "apple,t8103-dart", .data = &apple_dart_hw_t8103 }, { .compatible = "apple,t8103-usb4-dart", .data = &apple_dart_hw_t8103_usb4 }, { .compatible = "apple,t8110-dart", .data = &apple_dart_hw_t8110 }, diff --git a/tools/asahi/apple-dart-range-tests.py b/tools/asahi/apple-dart-range-tests.py index edebda6eb6a9d9..8939de0a74e85b 100644 --- a/tools/asahi/apple-dart-range-tests.py +++ b/tools/asahi/apple-dart-range-tests.py @@ -44,7 +44,7 @@ def main(): #define io_pgtable_ops_to_pgtable(x) ((struct io_pgtable *)(x)) struct apple_dart; struct apple_dart_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; -struct apple_dart_hw { int (*invalidate_tlb)(struct apple_dart_stream_map *); }; +struct apple_dart_hw { int (*invalidate_tlb)(struct apple_dart_stream_map *); bool gen3; }; struct apple_dart { int num_streams, locked, version; bool fw_mirror, fw_handoff, managed_sids, display_dark, display_tlb_stale; void *dev; struct apple_dart_hw *hw; }; struct apple_dart_atomic_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; struct apple_dart_domain { diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index 3d1026008cbd9f..e13025a6157c5b 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -97,6 +97,7 @@ def main(): u32 tcr_enabled, tcr_4level, ttbr_shift, ttbr_addr_field_shift; void (*enable_remap)(struct apple_dart *, int, int); int (*invalidate_tlb)(struct apple_dart_stream_map *); + bool gen3; }; struct apple_dart { const struct apple_dart_hw *hw; From 762549f5a30a008f90a583f521253324dd1fe885 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:58:00 +0100 Subject: [PATCH 0311/1514] iommu: apple-dart: issue the Gen3 TLBI in the EL1&0 regime on VHE The Gen3 DART snoops the broadcast TLBI that follows the aperture write. iBoot and the aura bootloader issue TLBI VALE1OS at EL2 without VHE, which targets the EL1&0 regime. On a VHE kernel the same instruction targets EL2&0 while HCR_EL2.TGE is set, so clear TGE around it, as KVM does to reach the EL1&0 regime. The J873g display works with this in place; the effect of the change on its own has not been isolated on hardware. Signed-off-by: Thomas Glanzmann --- drivers/iommu/apple-dart.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index a6c45cf6399647..52a87ddcd878b0 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -57,6 +57,9 @@ #include #include +#include +#include + #include "dma-iommu.h" #if IS_ENABLED(CONFIG_APPLE_DART_KUNIT_TEST) @@ -2021,9 +2024,21 @@ apple_dart_gen3_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) { struct apple_dart *dart = stream_map->dart; unsigned long flags; + u64 hcr = 0; int sid; spin_lock_irqsave(&dart->lock, flags); + /* + * The DART snoops an EL1&0 TLBI, as iBoot and aura (EL2 without VHE) + * issue it. A VHE kernel's TLBI VALE1OS targets EL2&0 while + * HCR_EL2.TGE is set, so clear TGE around it, as KVM does to reach + * the EL1&0 regime. + */ + if (is_kernel_in_hyp_mode()) { + hcr = read_sysreg(hcr_el2); + write_sysreg(hcr & ~HCR_TGE, hcr_el2); + isb(); + } for_each_set_bit(sid, stream_map->sidmap, dart->num_streams) { u64 lo = DART_GEN3_TLBI_VALID | FIELD_PREP(DART_GEN3_TLBI_ROUTE_FIELD, dart->tlbi_route) | @@ -2036,6 +2051,10 @@ apple_dart_gen3_hw_invalidate_tlb(struct apple_dart_stream_map *stream_map) "dsb osh\n" : : "r"(lo), "r"(dart->tlbi) : "memory"); } + if (is_kernel_in_hyp_mode()) { + write_sysreg(hcr, hcr_el2); + isb(); + } spin_unlock_irqrestore(&dart->lock, flags); return 0; From 47451b59770f69e10fef4a47abf955d90b6f9224 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:58:41 +0100 Subject: [PATCH 0312/1514] dt-bindings: display: add the Apple T8152 DCP on the iBoot interface The display coprocessor (DCP) of the Apple T8152 runs RTKit firmware that offers a small display service, "disp0-service", next to the full IOMobileFramebuffer protocol; iBoot drives the displays through it. The DCP fetches through its own DART, and the display pipe scans out through another one that is locked with a root of its own, so the scanout stream is a child node. The DCP's DPTX port drives either the ATC PHY of a USB-C port, whose PD controller reports the DisplayPort alt mode and the plug orientation, or, on the Mac mini (J873g), the dedicated DisplayPort PHY that feeds the HDMI port through a DisplayPort-to-HDMI converter. The sink's EDID is read through the AP's DisplayPort AUX controller. Signed-off-by: Thomas Glanzmann --- .../display/apple,t8152-dcp-iboot.yaml | 235 ++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml new file mode 100644 index 00000000000000..37b14961bbe775 --- /dev/null +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/display/apple,t8152-dcp-iboot.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 DCP on the iBoot display interface + +maintainers: + - Thomas Glanzmann + +description: | + The Display Coprocessor (DCP) of the Apple T8152 SoC runs RTKit firmware + that offers a small iBoot display interface (disp0-service) next to the + full IOMobileFramebuffer protocol. This binding describes the DCP driven + through that interface, together with the DisplayPort PHY its DPTX port + is routed to. The DCP fetches through its own DART, the display pipe + scans out through another one, which sees each scanout buffer at the same + address. + +properties: + compatible: + const: apple,t8152-dcp-iboot + + reg: + minItems: 2 + maxItems: 7 + + reg-names: + oneOf: + - items: + - const: coproc + - const: atc + - const: dp-clock + - const: atc-ps + - const: atc-psd + - const: aux + - const: aux-ps + minItems: 5 + description: + DCP coprocessor, ATC DisplayPort PHY (USB-C), the PMGR clock + control of its DisplayPort link, the PMGR power states the PHY + depends on, and optionally the AP DisplayPort AUX controller that + reads the sink's EDID with its PMGR power state + - items: + - const: coproc + - const: phy-core + - const: phy-apb + - const: aux + - const: aux-ps + minItems: 3 + description: + DCP coprocessor, the HDMI dptx-phy blocks, and optionally the AP + DisplayPort AUX controller that reads the sink's EDID with its + PMGR power state + - items: + - const: coproc + - const: dp-clock + - const: aux + - const: aux-ps + minItems: 2 + description: + DCP coprocessor, the PMGR clock control of the ATC DisplayPort + link (shared by the ports), and optionally the AP DisplayPort AUX + controller with its PMGR power state; the USB-C ports follow as + usb-c child nodes + + apple,tunable-pre: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the ATC PHY block + - description: mask + - description: value + description: + ATC PHY tunables (ADT ACIOPHY_CMN and CIOPLL_CORE defaults), applied + before the lane crossbar setup when the PHY starts from cold. + + apple,tunable-post: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the ATC PHY block + - description: mask + - description: value + description: + ATC PHY tunables (ADT ATC_FABRIC, DPPLL and AUX defaults), applied + after the lane crossbar setup. + + apple,hdmi: + type: boolean + description: + The DCP drives the HDMI port through the dedicated dptx-phy and an + on-board DisplayPort-to-HDMI converter, instead of an ATC USB-C PHY. + + apple,usb-pd: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The USB-C port's PD controller (SPMI), polled for the DisplayPort alt + mode connection and the plug orientation. + + hpd-gpios: + maxItems: 1 + description: + Hot plug detect line of the connector, if the AP can read it (J873g + HDMI); without it the sink is assumed to stay connected. + + mboxes: + maxItems: 1 + + iommus: + maxItems: 1 + description: DCP DART stream + + scanout: + type: object + additionalProperties: false + description: + The display pipe's scanout stream. Its DART is locked with its own + root, so it is a separate device that sees each scanout buffer at the + DCP's address. + properties: + iommus: + maxItems: 1 + dma-coherent: true + required: + - iommus + + dma-coherent: true + + apple,die: + $ref: /schemas/types.yaml#/definitions/uint32 + description: Die of the DPTX connection target, 0 if absent. + + "#address-cells": + const: 2 + + "#size-cells": + const: 2 + + ranges: true + +patternProperties: + "^usb-c@[0-9a-f]+$": + type: object + additionalProperties: false + description: + A USB-C port whose ATC PHY the DCP can drive. The DCP drives one port + at a time, the one a DisplayPort sink is plugged into. + properties: + reg: + maxItems: 3 + reg-names: + items: + - const: atc + - const: atc-ps + - const: atc-psd + description: + ATC DisplayPort PHY, the PMGR power states it depends on (DP_0, + DP_1 and USB_AON) and its common power domain (PSD) + apple,dfp-endpoint: + $ref: /schemas/types.yaml#/definitions/uint32 + description: The ATC's display-crossbar0 DFP endpoint (ATC instance). + apple,usb-pd: + $ref: /schemas/types.yaml#/definitions/phandle + description: The port's PD controller (SPMI). + apple,tunable-pre: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: As the node's apple,tunable-pre, for this port's PHY. + apple,tunable-post: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + description: As the node's apple,tunable-post, for this port's PHY. + required: + - reg + - reg-names + - apple,dfp-endpoint + - apple,usb-pd + +required: + - compatible + - reg + - reg-names + - mboxes + - iommus + - scanout + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + display@286e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x86e00000 0x0 0x74000>, + <0x4 0x13000000 0x0 0x84000>, + <0x3 0x0002005c 0x0 0x4>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "coproc", "atc", "dp-clock", "atc-ps", "atc-psd"; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + + scanout { + iommus = <&disp0_dart 0>; + }; + }; + + display@296e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x96e00000 0x0 0x74000>, + <0x3 0x0002005c 0x0 0x4>; + reg-names = "coproc", "dp-clock"; + #address-cells = <2>; + #size-cells = <2>; + ranges; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + + scanout { + iommus = <&disp0_dart 0>; + }; + + usb-c@413000000 { + reg = <0x4 0x13000000 0x0 0x84000>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <3>; + apple,usb-pd = <&hpm3>; + }; + }; + }; From c443b6bdbd843132892bd3ba69c439af5244e10f Mon Sep 17 00:00:00 2001 From: Acelogic Date: Fri, 6 Nov 2026 05:00:57 -0500 Subject: [PATCH 0313/1514] dt-bindings: display: apple,t8152-dcp-iboot: add the HDMI power states A USB-C-only J873 boot leaves DPTX_PHY off, and reading the HDMI PHY then raises an SError. Describe the read-only PMGR power states of the HDMI PHY (DPTX_PHY) and of the DCPEXT CPU (DISPEXT0_CPU) with the HDMI PHY's register layout, so that the driver can check them before it touches the PHY. Signed-off-by: Acelogic [Thomas: split out of the driver change] Signed-off-by: Thomas Glanzmann --- .../bindings/display/apple,t8152-dcp-iboot.yaml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index 37b14961bbe775..20b5b31e6b0a4d 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -48,11 +48,14 @@ properties: - const: phy-apb - const: aux - const: aux-ps - minItems: 3 + - const: phy-ps + - const: coproc-ps description: - DCP coprocessor, the HDMI dptx-phy blocks, and optionally the AP + DCP coprocessor, the HDMI dptx-phy blocks, the AP DisplayPort AUX controller that reads the sink's EDID with its - PMGR power state + PMGR power state, and the read-only PMGR power states for the + HDMI PHY and DCPEXT CPU. The driver only adopts the bootloader's + powered link and must check these states before accessing the PHY. - items: - const: coproc - const: dp-clock From ce320b2a9239ef5d79ecbf7eb69a25844e3869f4 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Fri, 6 Nov 2026 05:08:51 -0500 Subject: [PATCH 0314/1514] dt-bindings: display: apple,t8152-dcp-iboot: add apple,afk-active-endpoints The bootloader may hand the DCP over with AFK endpoints still running, and an AFK INIT on a live endpoint asserts in the firmware. Add a property the bootloader fills in at boot with the endpoints it left running, so that the operating system can stop them before it starts a session of its own. Signed-off-by: Acelogic [Thomas: split out of the driver change, added the description] Signed-off-by: Thomas Glanzmann --- .../bindings/display/apple,t8152-dcp-iboot.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index 20b5b31e6b0a4d..f1396f44990db8 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -22,6 +22,17 @@ properties: compatible: const: apple,t8152-dcp-iboot + apple,afk-active-endpoints: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 65535 + description: + Runtime handoff from the bootloader. Bit N records that AFK endpoint + 0x20 + N is running and must acknowledge shutdown before a new session + starts. A zero bit means stopped. The bootloader inserts this only + for controllers whose complete endpoint state it owns, and reserves + the old session's buffers. The driver refuses takeover if absent. + This property must not be hard-coded in a board device tree. + reg: minItems: 2 maxItems: 7 From a5c2e9c45dca6cc7c1cc50e3d015036fcaaf8a94 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 22:53:55 +0100 Subject: [PATCH 0315/1514] dt-bindings: display: apple,t8152-dcp-iboot: describe DCPEXT1 and shared USB-C ports All three T8152 display controllers can drive the rear USB-C ports through the one display crossbar. Describe what a controller needs for that: - apple,dp-source: its crossbar UFP endpoint (0 DCP, 1 DCPEXT0, 2 DCPEXT1); - apple,usb-c-ports: the node holding the shared usb-c port children, the DP clock dividers and the AUX controller; - coproc-psd: the read-only PMGR2 PSD admission state of a DCPEXT, checked before its coprocessor is touched (a read while it is gated hangs the machine), and the coproc + coproc-psd layout of an extra controller without PHY resources of its own; - apple,rtkit-wake: set by the loader for an unused DCPEXT whose firmware iBoot loaded and powered and which waits for an RTKit wake. The dp-clock resource now spans the PMGR ATC DP clock dividers of all ATCs (one every eight bytes from ATC0) instead of ATC3's alone. Signed-off-by: Thomas Glanzmann --- .../display/apple,t8152-dcp-iboot.yaml | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index f1396f44990db8..d4f007202ae65a 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -33,9 +33,31 @@ properties: the old session's buffers. The driver refuses takeover if absent. This property must not be hard-coded in a board device tree. + apple,dp-source: + $ref: /schemas/types.yaml#/definitions/uint32 + maximum: 2 + description: + Display-crossbar UFP endpoint, 0 for DCP, 1 for DCPEXT0, 2 for DCPEXT1. + The driver uses DPTX port zero, whose ATC mux selector is twice this. + + apple,usb-c-ports: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Controller node containing the shared USB-C port children, dp-clock, + aux and aux-ps resources. Each connected port has one controller owner. + + apple,rtkit-wake: + type: boolean + description: + Runtime handoff for an unused DCPEXT whose firmware is loaded, powered, + and awaiting RTKit wake. The loader must reserve its firmware mappings + and buffers and supply apple,afk-active-endpoints. This property must + not be hard-coded in a board tree. An adopted HDMI session is already + running and takes precedence over this unused-controller indication. + reg: minItems: 2 - maxItems: 7 + maxItems: 8 reg-names: oneOf: @@ -61,12 +83,20 @@ properties: - const: aux-ps - const: phy-ps - const: coproc-ps + - const: coproc-psd + minItems: 7 description: DCP coprocessor, the HDMI dptx-phy blocks, the AP DisplayPort AUX controller that reads the sink's EDID with its PMGR power state, and the read-only PMGR power states for the HDMI PHY and DCPEXT CPU. The driver only adopts the bootloader's powered link and must check these states before accessing the PHY. + - items: + - const: coproc + - const: coproc-psd + description: + Additional display controller and its PMGR2 PSD admission state; + PHY resources are shared through apple,usb-c-ports. - items: - const: coproc - const: dp-clock @@ -75,9 +105,9 @@ properties: minItems: 2 description: DCP coprocessor, the PMGR clock control of the ATC DisplayPort - link (shared by the ports), and optionally the AP DisplayPort AUX - controller with its PMGR power state; the USB-C ports follow as - usb-c child nodes + links (one divider every eight bytes, starting with ATC0), and + optionally the AP DisplayPort AUX controller with its PMGR power + state; the USB-C ports follow as usb-c child nodes apple,tunable-pre: $ref: /schemas/types.yaml#/definitions/uint32-matrix @@ -105,7 +135,8 @@ properties: type: boolean description: The DCP drives the HDMI port through the dedicated dptx-phy and an - on-board DisplayPort-to-HDMI converter, instead of an ATC USB-C PHY. + on-board DisplayPort-to-HDMI converter. With apple,usb-c-ports it can + instead claim a USB-C port when the bootloader has not assigned HDMI. apple,usb-pd: $ref: /schemas/types.yaml#/definitions/phandle @@ -210,7 +241,7 @@ examples: compatible = "apple,t8152-dcp-iboot"; reg = <0x2 0x86e00000 0x0 0x74000>, <0x4 0x13000000 0x0 0x84000>, - <0x3 0x0002005c 0x0 0x4>, + <0x3 0x00020044 0x0 0x1c>, <0x3 0x082900c0 0x0 0x104>, <0x3 0x03a13a00 0x0 0xc0>; reg-names = "coproc", "atc", "dp-clock", "atc-ps", "atc-psd"; @@ -225,7 +256,7 @@ examples: display@296e00000 { compatible = "apple,t8152-dcp-iboot"; reg = <0x2 0x96e00000 0x0 0x74000>, - <0x3 0x0002005c 0x0 0x4>; + <0x3 0x00020044 0x0 0x1c>; reg-names = "coproc", "dp-clock"; #address-cells = <2>; #size-cells = <2>; From 4fc411f256c83859073a7b31b90b7b76f9ed29ad Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Wed, 18 Nov 2026 11:03:18 +0100 Subject: [PATCH 0316/1514] dt-bindings: display: apple,t8152-dcp-iboot: describe the HDMI cold start The J873g HDMI port works only if the bootloader brought it up. For the driver to start it itself, the HDMI node needs the PMGR2 PSD service of the dptx-phy (phy-psd), the phy tunables from the ADT (apple,tunable-phy), and the SMC writes that power the PS190 DisplayPort-to-HDMI converter (apple,smc, apple,pcon-power). The phy's PMGR power state is no longer only read. Signed-off-by: Thomas Glanzmann --- .../display/apple,t8152-dcp-iboot.yaml | 39 +++++++++++++++++-- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index d4f007202ae65a..7c4e2b1db5ab93 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -57,7 +57,7 @@ properties: reg: minItems: 2 - maxItems: 8 + maxItems: 9 reg-names: oneOf: @@ -84,13 +84,15 @@ properties: - const: phy-ps - const: coproc-ps - const: coproc-psd + - const: phy-psd minItems: 7 description: DCP coprocessor, the HDMI dptx-phy blocks, the AP DisplayPort AUX controller that reads the sink's EDID with its - PMGR power state, and the read-only PMGR power states for the - HDMI PHY and DCPEXT CPU. The driver only adopts the bootloader's - powered link and must check these states before accessing the PHY. + PMGR power state, the PMGR power state of the HDMI PHY, the read + only power state of the DCPEXT CPU, and the PMGR2 PSD service of + the HDMI PHY. The PHY is accessed only once its power states read + powered; with phy-psd it is powered up for a cold HDMI start. - items: - const: coproc - const: coproc-psd @@ -138,6 +140,35 @@ properties: on-board DisplayPort-to-HDMI converter. With apple,usb-c-ports it can instead claim a USB-C port when the bootloader has not assigned HDMI. + apple,tunable-phy: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: register offset in the HDMI dptx-phy core block + - description: mask + - description: value + description: + HDMI dptx-phy tunables (ADT dptx-phy asdc and lane-shm-regs groups), + applied when the PHY starts from cold. + + apple,smc: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The SMC that switches the power of the DisplayPort-to-HDMI converter. + + apple,pcon-power: + $ref: /schemas/types.yaml#/definitions/uint32-matrix + items: + items: + - description: SMC key + - description: value, bits 63:32 + - description: value, bits 31:0 + description: + SMC writes, in order, that power the DisplayPort-to-HDMI converter + (ADT dp2hdmi-gpio0 function-dp2hdmi_pwr_en and function-hdmi_pwr_en). + The converter drives the HDMI hot-plug detect line only while it is + powered. + apple,usb-pd: $ref: /schemas/types.yaml#/definitions/phandle description: From ddaa639dfe53771a3a18be480e3503de544b2def Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 17:49:53 +0100 Subject: [PATCH 0317/1514] dt-bindings: chosen: add apple,dcp-rtkit-running The loader reports whether the internal DCP's RTKit was running at the hand-off (1) or whether it quiesced the coprocessor after a failed display setup (0). apple,dcp-rtkit-quiesced carries the same values under a name that reads the other way round, so the T8152 loader and DCP driver use this name instead. Signed-off-by: Thomas Glanzmann --- .../chosen/apple,dcp-rtkit-running.yaml | 37 +++++++++++++++++++ MAINTAINERS | 1 + 2 files changed, 38 insertions(+) create mode 100644 Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml diff --git a/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml b/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml new file mode 100644 index 00000000000000..38a4dcb4044a5e --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/apple,dcp-rtkit-running.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple DCP RTKit state at the loader hand-off + +maintainers: + - Thomas Glanzmann + +description: + The loader records whether the internal display coprocessor's RTKit was + running when it handed over to the kernel, or whether the loader quiesced + it after a failed display setup. The loader omits this property when it + never started the coprocessor. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + apple,dcp-rtkit-running: + $ref: /schemas/types.yaml#/definitions/uint32 + enum: [0, 1] + description: + One if the internal DCP's RTKit was running at the hand-off, zero if + the loader quiesced it. + +additionalProperties: true +... diff --git a/MAINTAINERS b/MAINTAINERS index 5c8fc89e51d008..cb48635b6e3680 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2093,6 +2093,7 @@ F: drivers/soc/apple/pmp.rs F: include/linux/mt7932.h F: include/linux/soc/apple/pmp-report.h F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-quiesced.yaml +F: Documentation/devicetree/bindings/chosen/apple,dcp-rtkit-running.yaml F: Documentation/devicetree/bindings/chosen/aurora,ctxr-exec-window.yaml F: Documentation/devicetree/bindings/display/apple,dcp.yaml F: Documentation/devicetree/bindings/display/apple,display-subsystem.yaml From 01d47a3ae576931ee5c524efe0298085bcf247df Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 21:22:30 +0100 Subject: [PATCH 0318/1514] iommu: apple-dart: report T8152 Gen3 DART faults A T8152 Gen3 DART reports a fault as a v2 DART does: a bitmap of the streams with a pending exception at 0x4000, a record per stream at 0x8000 (status, address), acknowledged by writing the bitmap back. Request its interrupt and let apple_dart_t8110_v2_irq() report and acknowledge its faults instead of leaving them to the firmware. Only the unlock after a lock-on-error exception differs: a Gen3 DART's TLB command register serves translation queries, so it is not used to unlock. A Gen3 DART with lock-on-error set says that its stream stays stopped. The J873g's Gen3 DARTs have it clear. Tested on the J873g by clearing the AVD DART's SID 0 TTBR during an H.264 decode: one interrupt, "translation fault: SID:0 write TTBR invalid at 0x10fff000000 (status 0x00000100)", the bitmap acknowledged with no repeat, and the decoder retired by its recovery path. After the TTBR was restored and the decoder reloaded, the same file decoded bit-exact again. None of the other eight Gen3 DART fault lines fired, including those of the locked display DARTs with three displays running. Signed-off-by: Thomas Glanzmann --- drivers/iommu/apple-dart.c | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 52a87ddcd878b0..938e6f519efa66 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -2230,6 +2230,15 @@ static int apple_dart_t8110_v2_unlock(struct apple_dart *dart) return -EPERM; if (!(readl(dart->regs + DART_T8110_DIAG_LOCK) & DART_T8110_DIAG_LOCK_ON_ERR)) return 0; + /* + * A Gen3 DART's TLB command register serves translation queries and + * cannot unlock it. Its streams stay stopped until the DART is reset. + */ + if (dart->hw->gen3) { + dev_err_ratelimited(dart->dev, + "locked on error; a Gen3 DART is not unlocked\n"); + return -EOPNOTSUPP; + } /* Unlock after acknowledging a lock-on-error exception. */ __set_bit(0, stream_map.sidmap); @@ -5699,11 +5708,16 @@ static int apple_dart_probe(struct platform_device *pdev) dart->irq = -1; } else if (dart->hw->gen3) { /* - * The T8110 fault handler acknowledges through the TLB command - * register, which a Gen3 DART uses for translation queries. - * Leave its faults to the firmware for now. + * Gen3 reports a fault like a v2 DART: the per-SID exception + * bitmap and records, acknowledged by writing the bitmap back + * (apple_dart_t8110_v2_irq()). Only the unlock after a + * lock-on-error exception differs: see apple_dart_t8110_v2_unlock(). */ - dart->irq = -1; + dart->irq = platform_get_irq_optional(pdev, 0); + if (dart->irq == -ENXIO) + dart->irq = -1; + else if (dart->irq < 0) + return dart->irq; } else if (dart->preserve_display || j713_radio) { dart->irq = platform_get_irq_optional(pdev, 0); if (dart->irq == -ENXIO) From d2429a90a778fd93f8ad48a7bb951ec93c396434 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:21:46 +0100 Subject: [PATCH 0319/1514] drm/apple: let the match data select the AFKv2 wire afk_init() picks the AFKv2 wire for firmware 27 and for the T8122 external processor on 26.x, both recognised by their IOMFB interface. The T8152 DCP firmware speaks AFKv2 on every endpoint of its iBoot interface (the display service, the DPAV controller services and the DPTX port services), and drm/apple drives no IOMFB interface of it that a version could key on. Add hw.afk_v2, which selects AFKv2 for all endpoints of a processor. No match entry sets it yet. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 3 ++- drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 3c5eaf725d02a2..27fc612d460bb6 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -115,7 +115,8 @@ struct apple_dcp_afkep *afk_init(struct apple_dcp *dcp, u32 endpoint, afkep->ops = ops; afkep->dcp = dcp; - afkep->wire_v2 = dcp->fw_compat == DCP_FIRMWARE_V_27_0 || dcp_is_ext26(dcp); + afkep->wire_v2 = dcp->fw_compat == DCP_FIRMWARE_V_27_0 || dcp_is_ext26(dcp) || + dcp->hw.afk_v2; afkep->endpoint = endpoint; afkep->wq = alloc_ordered_workqueue("apple-dcp-afkep%02x", WQ_MEM_RECLAIM, endpoint); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..943019c89f8af7 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -345,6 +345,12 @@ struct apple_dcp_hw_data { * firmware 27.0 and 27.2.1), so there is no secure port to idle before the IOP. */ bool s2r_no_secure_port; + /* + * Every AFK endpoint speaks AFKv2 (see afk_init()), whatever the + * firmware interface: for a firmware that does so on all of them + * without an IOMFB interface version that implies it. + */ + bool afk_v2; }; enum dcp_test_point { From 0eedf7ceda42919935768a54740fb24c2b9d8b6e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:23:44 +0100 Subject: [PATCH 0320/1514] drm/apple: start AFK endpoints of an RTKit session taken without its map The T8152 DCP does not acknowledge AP QUIESCED, and an IOP INIT while its AP power is still on panics the firmware ("Invalid AP power: 32"). A session the bootloader leaves running can only be taken over as it runs, with apple_rtkit_init_adopted(), without the HELLO/EPMAP handshake: the endpoint map went to the bootloader, and apple_rtkit_start_ep() refuses an endpoint RTKit does not know. Add hw.afk_adopt_endpoints. With it afk_start() registers the endpoint with apple_rtkit_adopt_ep() before it sends anything to it, so its START_EP goes out and its replies are not taken for an unknown endpoint's. No match entry sets it yet. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 7 +++++++ drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ 2 files changed, 13 insertions(+) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 27fc612d460bb6..ff105620dfc097 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -249,6 +249,13 @@ int afk_start(struct apple_dcp_afkep *ep) } reinit_completion(&ep->started); + /* + * An adopted session's endpoint map went to the bootloader, and RTKit + * starts only endpoints it knows. Registered before anything is sent, + * the endpoint's replies are not reported as an unknown endpoint's. + */ + if (ep->dcp->hw.afk_adopt_endpoints) + apple_rtkit_adopt_ep(ep->dcp->rtk, ep->endpoint); ret = apple_rtkit_start_ep(ep->dcp->rtk, ep->endpoint); if (ret) return ret; diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 943019c89f8af7..ef548bb14ae56f 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -351,6 +351,12 @@ struct apple_dcp_hw_data { * without an IOMFB interface version that implies it. */ bool afk_v2; + /* + * The RTKit session is taken over without its endpoint map (see + * apple_rtkit_init_adopted()): afk_start() registers each endpoint + * with RTKit before starting it. + */ + bool afk_adopt_endpoints; }; enum dcp_test_point { From 2a1bfe4154a9ac33bccf4b61bb26f9191e44f33e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:25:35 +0100 Subject: [PATCH 0321/1514] drm/apple: stop the AFK endpoints a bootloader left running A bootloader that drives the display through the DCP firmware can leave AFK endpoints running with its scanout when it hands over, as the T8152 loader does with the iBoot interface's endpoints. An AFK INIT on a live endpoint asserts in the firmware. Add dcp->afk_live_endpoints, bit N for endpoint 0x20 + N, which a processor's probe fills from such a hand-off (the T8152 loader's apple,afk-active-endpoints). afk_start() sends an endpoint whose bit is set a SHUTDOWN and waits for its acknowledgment before START_EP and INIT, after registering it with an adopted RTKit session so that the acknowledgment is not taken for an unknown endpoint's. The old session's ring stays the bootloader's, which keeps it reserved. The mask is zero on every processor that sets nothing, so their start is unchanged. The stop of the live endpoints is based on a change by Acelogic for the T8152 hand-off. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 32 ++++++++++++++++++++++++++++ drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ 2 files changed, 38 insertions(+) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index ff105620dfc097..d0f6f84d5704a7 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -236,6 +236,35 @@ static int afk_start_polled(struct apple_dcp_afkep *ep) return -ETIMEDOUT; } +/* + * An endpoint the bootloader left running (afk_live_endpoints): an INIT + * on a live endpoint asserts in the firmware. Stop it and wait for the + * acknowledgment first. Its old ring stays with the bootloader, which + * keeps it reserved. + */ +static int afk_stop_live(struct apple_dcp_afkep *ep) +{ + u32 bit; + + if (ep->endpoint < 0x20 || ep->endpoint >= 0x40) + return 0; + bit = BIT(ep->endpoint - 0x20); + if (!(ep->dcp->afk_live_endpoints & bit)) + return 0; + reinit_completion(&ep->stopped); + afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_SHUTDOWN)); + if (!wait_for_completion_timeout(&ep->stopped, msecs_to_jiffies(1000))) { + dev_err(ep->dcp->dev, "AFK[ep:%02x]: inherited endpoint did not stop\n", + ep->endpoint); + return -ETIMEDOUT; + } + reinit_completion(&ep->stopped); + ep->dcp->afk_live_endpoints &= ~bit; + dev_info(ep->dcp->dev, "AFK[ep:%02x]: inherited endpoint stopped\n", + ep->endpoint); + return 0; +} + int afk_start(struct apple_dcp_afkep *ep) { int ret; @@ -256,6 +285,9 @@ int afk_start(struct apple_dcp_afkep *ep) */ if (ep->dcp->hw.afk_adopt_endpoints) apple_rtkit_adopt_ep(ep->dcp->rtk, ep->endpoint); + ret = afk_stop_live(ep); + if (ret) + return ret; ret = apple_rtkit_start_ep(ep->dcp->rtk, ep->endpoint); if (ret) return ret; diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index ef548bb14ae56f..bc5449a12f97d5 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -575,6 +575,12 @@ struct apple_dcp { enum dcp_firmware_version fw_compat; /* Bumped by every iomfb poweron; see afk_compact_slot(). */ u32 afk_power_gen; + /* + * AFK endpoints the bootloader left running, bit N for endpoint + * 0x20 + N, from its hand-off: afk_start() stops each before its + * INIT. Zero for a processor without such a hand-off. + */ + u32 afk_live_endpoints; /* Firmware 27.x: the method IDs of this build (iomfb_v27_methods()). */ const struct dcp_method_entry *v27_methods; bool external; From 4a1f227206dba93e2e75d6de8d947f9defa6569f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:27:27 +0100 Subject: [PATCH 0322/1514] drm/apple: send AFK commands without output without a reply buffer afk_send_command() allocates a reply buffer of the output length and names it in the command, even for a length of zero. The AFKv2 setters of the T8152 DCP firmware's iBoot interface (SET_POWER, SET_MODE, SET_SURFACE) answer with a transport status alone. Given a reply buffer, the firmware copies an empty reply into it and asserts. Give a command without output no reply buffer: its descriptor carries address and length zero, which the AFKv2 codec already accepts and checks the reply against. Every current caller passes an output length, so none of them changes. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index d0f6f84d5704a7..2a52c9fd63c185 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -3308,11 +3308,20 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, goto err_put_service; } - rxbuf = dma_alloc_coherent(ep->dcp->dev, output_len, &rxbuf_dma, - GFP_KERNEL); - if (!rxbuf) { - ret = -ENOMEM; - goto err_put_service; + /* + * A command without output carries no reply buffer: firmware that + * answers some commands with a status alone asserts when it is given + * one, since it then copies an empty reply. + */ + rxbuf = NULL; + rxbuf_dma = 0; + if (output_len) { + rxbuf = dma_alloc_coherent(ep->dcp->dev, output_len, &rxbuf_dma, + GFP_KERNEL); + if (!rxbuf) { + ret = -ENOMEM; + goto err_put_service; + } } txbuf = dma_alloc_coherent(ep->dcp->dev, payload_len, &txbuf_dma, GFP_KERNEL); @@ -3470,7 +3479,7 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, if (!dcp_is_ext26(ep->dcp)) dma_free_coherent(ep->dcp->dev, payload_len, txbuf, txbuf_dma); err_free_rxbuf: - if (!dcp_is_ext26(ep->dcp)) + if (rxbuf && !dcp_is_ext26(ep->dcp)) dma_free_coherent(ep->dcp->dev, output_len, rxbuf, rxbuf_dma); err_put_service: afk_service_put(service); From b1bc3a3b4c4569820f6e2f865fdae02c50ef6262 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:29:25 +0100 Subject: [PATCH 0323/1514] drm/apple: match AFK services by their announced name afk_recv_handle_init() parses the properties that follow a service's announced name whenever there are any, and matches the service by the EPIC provider class found there. Which keys it accepts depends on the firmware interface version. The T8152 DCP firmware's iBoot service (disp0-service, dispext-service) is announced by name alone, and the properties of its DPTX and DPAV services are not needed to drive it: a property set the parser rejects would leave such a service unopened. Add hw.afk_announced_names. With it the properties are not parsed, the service is matched by its announced name, and that name is what its handler gets as the EPIC name. No match entry sets it yet. The startup host test's and the apple-dcp service rebind test's processors gain the flag, and the latter kstrdup(). The provider admission test looks for the announcement's OPEN in the first 7000 bytes of afk_recv_handle_init() instead of 6500, which no longer reach it. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 15 ++++++++++++--- drivers/gpu/drm/apple/dcp-internal.h | 5 +++++ tools/asahi/dcpext26-startup-tests.py | 3 ++- .../selftests/drivers/gpu/apple-dcp/edid.py | 6 ++++-- 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 2a52c9fd63c185..630acfdc5af17b 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1779,7 +1779,7 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, * EPICProviderClass was used. If the init call has props parse them and * use EPICProviderClass to match the service. */ - if (props_size > 36) { + if (props_size > 36 && !ep->dcp->hw.afk_announced_names) { int ret = parse(props, props_size, &ctx); if (ret) { dev_err(ep->dcp->dev, @@ -1824,8 +1824,17 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, service_name = epic_class; } } else { - service_name = name; - } + service_name = name; + /* + * hw.afk_announced_names: the announced name is the service's + * identity, and its handler gets it as the EPIC name. + */ + if (ep->dcp->hw.afk_announced_names) { + epic_name = kstrdup(name, GFP_KERNEL); + if (!epic_name) + return; + } + } if (ep->match_epic_name) ops = afk_match_service(ep, epic_name); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index bc5449a12f97d5..1621c62f1a4a0f 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -357,6 +357,11 @@ struct apple_dcp_hw_data { * with RTKit before starting it. */ bool afk_adopt_endpoints; + /* + * AFK services are matched by the name in their announcement; the + * properties after it are not parsed (afk_recv_handle_init()). + */ + bool afk_announced_names; }; enum dcp_test_point { diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index 0811ada7ce526c..c71308f06d2587 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -59,6 +59,7 @@ def run(name,code,reject=False): #define kmalloc(n,f) malloc(n) #define kzalloc_obj(v) calloc(1,sizeof(v)) #define kfree(p) free((void *)(p)) +#define kstrdup(s,f) strdup(s) #define max(a,b) ((a)>(b)?(a):(b)) #define dev_info(...) ((void)0) #define dev_err(...) ((void)0) @@ -93,7 +94,7 @@ def run(name,code,reject=False): struct apple_epic_service_ops {const char *name;bool reusable,optional,open_later;int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);}; struct apple_epic_service {struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops;bool enabled,torndown,pending_open,defer_start;unsigned users;int lock;u32 channel;void *cookie;const char *pending_name,*pending_class;s64 pending_unit;int cmd_map[1];}; struct dptx_port {struct apple_epic_service *service;s64 unit;bool enabled,connected;int enable_completion;}; -struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; +struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;bool afk_announced_names;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops;struct apple_epic_service services[AFK_MAX_CHANNEL];}; static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index fe2e56e1f46ea9..bc5eb6f352967b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -100,7 +100,7 @@ def function(file,signature): struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; bool external_physically_absent,hpd_mutex,quiescing,typec_cable_connected;u64 typec_generation;unsigned int nr_modes; - struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints; unsigned int num_dptx_ports; } hw; bool ext_dead,external_native; + struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints,afk_announced_names; unsigned int num_dptx_ports; } hw; bool ext_dead,external_native; struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; u64 opened_epoch,close_gen,terminated_epoch,close_epoch;bool opening;struct work_struct close_wq; } dcpavserv; /* A J714s firmware 27 processor's: this one is not. */ @@ -146,6 +146,8 @@ def function(file,signature): struct dcp_parse_ctx { struct item *items;unsigned int count,index;bool key; }; struct iterator { struct dcp_parse_ctx *handle;unsigned int idx,len; }; #define kfree(p) free((void *)(p)) +#define GFP_KERNEL 0 +#define kstrdup(s,f) strdup(s) #define PTR_ERR(p) ((int)(intptr_t)(p)) static struct item announcement_items[3]; static int parse(u8 *p,size_t n,struct dcp_parse_ctx *ctx) @@ -574,7 +576,7 @@ def function(file, signature): av = (base / 'epic/dpavservep.c').read_text() af = (base / 'afk.c').read_text() - announce = af[af.index('static void afk_recv_handle_init('):af.index('static void afk_recv_handle_init(') + 6500] + announce = af[af.index('static void afk_recv_handle_init('):af.index('static void afk_recv_handle_init(') + 7000] assert announce.index('ops->prepare(service,') < announce.index('EPIC_CAT_REPORT, AFKV2_OPEN') assert '.prepare = dcpavserv_prepare,' in av and '.prepare = dcpdpserv_prepare,' in av prefix = r''' From ea4edea96760296fd793ef689fe98f87cc69c088 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:31:15 +0100 Subject: [PATCH 0324/1514] drm/apple: open AFK services that have no handler An announced service that no entry of its endpoint's ops table names is left unopened, apart from two firmware-specific exceptions that bind it to the endpoint's first entry. The T8152 DCP firmware's DPAV controller endpoint announces four services and expects all of them to be opened, among them dcpav-video-interface, whose opening starts the firmware's idle power off timer for the display. None of them takes commands from the host. Add ep->unmatched_ops, bound to every announced service that no entry of the endpoint's ops table matches, which is then opened and initialised like a matched one. It is NULL on every existing endpoint, whose unmatched services stay unopened as before. The startup host test's and the apple-dcp service rebind test's endpoints gain the field. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 2 ++ drivers/gpu/drm/apple/afk.h | 5 +++++ tools/asahi/dcpext26-startup-tests.py | 2 +- tools/testing/selftests/drivers/gpu/apple-dcp/edid.py | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 630acfdc5af17b..7b0e00d052b477 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1857,6 +1857,8 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, if (!ops && dcp_is_ext26(ep->dcp) && ep->ops && !strcmp(ep->ops->name, "native26-observer")) ops = ep->ops; + if (!ops) + ops = ep->unmatched_ops; if (!ops) { dev_err(ep->dcp->dev, "AFK[ep:%02x]: unable to match service %s on channel %d\n", diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index b2c7c5deddb29b..da51a5fa0daee0 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -580,6 +580,11 @@ struct apple_dcp_afkep { void *compact_rx_data; const struct apple_epic_service_ops *ops; + /* + * Bound to an announced service no entry of @ops names, which is then + * opened like a matched one. NULL leaves such a service unopened. + */ + const struct apple_epic_service_ops *unmatched_ops; struct apple_epic_service services[AFK_MAX_CHANNEL]; u32 num_channels; diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index c71308f06d2587..bc8a0aa89a9927 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -95,7 +95,7 @@ def run(name,code,reject=False): struct apple_epic_service {struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops;bool enabled,torndown,pending_open,defer_start;unsigned users;int lock;u32 channel;void *cookie;const char *pending_name,*pending_class;s64 pending_unit;int cmd_map[1];}; struct dptx_port {struct apple_epic_service *service;s64 unit;bool enabled,connected;int enable_completion;}; struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;bool afk_announced_names;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; -struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops;struct apple_epic_service services[AFK_MAX_CHANNEL];}; +struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops,*unmatched_ops;struct apple_epic_service services[AFK_MAX_CHANNEL];}; static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} static bool dcp_is_v14_7_external(struct apple_dcp *d){return false;} diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index bc5eb6f352967b..b4ea075b85f278 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -95,7 +95,7 @@ def function(file,signature): bool pending_open;const char *pending_name,*pending_class;s64 pending_unit; }; /* v27_closed_teardown: set only by a J714s firmware 27 sleep. */ -struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; +struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops,*unmatched_ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; struct apple_connector { void *dcp;bool connected,edid_invalidation_pending;struct { int registration_state; } base;unsigned int hotplug_wq; }; struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; From 10c6cd1cc6c24339f17255eef0b48c3ed1905224 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:33:32 +0100 Subject: [PATCH 0325/1514] drm/apple: let the match data set the AFK timeout AFK waits one second for an endpoint to start or stop and for a command or service call to be answered. The T8152 DCP firmware's iBoot display commands answer only once the DisplayPort work they start is done: SET_POWER and SET_MODE wait for the link training, during which the firmware calls into the AP for the PHY. The T8152 displays have been run on the hardware with three seconds for each of these. Add hw.afk_timeout_ms, the time afk_start(), afk_shutdown(), the inherited endpoint stop, afk_send_command(), afk_service_call() and afk_service_call_len() wait. Zero keeps one second, so every processor that sets nothing waits as before. Callers that pass their own timeout, and the legacy reply-length calls, are unchanged. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 27 +++++++++++++++++++++------ drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 7b0e00d052b477..6b65f13e052095 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -83,6 +83,18 @@ void afk_service_retry(struct apple_dcp_afkep *ep) } EXPORT_SYMBOL_IF_KUNIT(afk_service_retry); +/* How long the host waits for the firmware: the processor's own, or one second. */ +static unsigned int afk_timeout_ms(struct apple_dcp_afkep *ep) +{ + return ep->dcp->hw.afk_timeout_ms ?: MSEC_PER_SEC; +} + +/* The same for a service the caller may not have; the call fails without one. */ +static unsigned int afk_service_timeout_ms(struct apple_epic_service *service) +{ + return service ? afk_timeout_ms(service->ep) : MSEC_PER_SEC; +} + static void afk_send(struct apple_dcp_afkep *ep, u64 message) { dcp_send_message(ep->dcp, ep->endpoint, message); @@ -185,7 +197,8 @@ void afk_shutdown(struct apple_dcp_afkep *afkep) afk_send(afkep, FIELD_PREP(RBEP_TYPE, RBEP_SHUTDOWN)); int ret; - ret = wait_for_completion_timeout(&afkep->stopped, msecs_to_jiffies(1000)); + ret = wait_for_completion_timeout(&afkep->stopped, + msecs_to_jiffies(afk_timeout_ms(afkep))); if (ret <= 0) { dev_err(afkep->dcp->dev, "Timed out shutting down AFK endpoint %02x", afkep->endpoint); } @@ -253,7 +266,8 @@ static int afk_stop_live(struct apple_dcp_afkep *ep) return 0; reinit_completion(&ep->stopped); afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_SHUTDOWN)); - if (!wait_for_completion_timeout(&ep->stopped, msecs_to_jiffies(1000))) { + if (!wait_for_completion_timeout(&ep->stopped, + msecs_to_jiffies(afk_timeout_ms(ep)))) { dev_err(ep->dcp->dev, "AFK[ep:%02x]: inherited endpoint did not stop\n", ep->endpoint); return -ETIMEDOUT; @@ -296,7 +310,8 @@ int afk_start(struct apple_dcp_afkep *ep) return afk_start_polled(ep); afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_INIT)); - ret = wait_for_completion_timeout(&ep->started, msecs_to_jiffies(1000)); + ret = wait_for_completion_timeout(&ep->started, + msecs_to_jiffies(afk_timeout_ms(ep))); if (ret <= 0 && ep->dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) dev_warn(ep->dcp->dev, @@ -3187,7 +3202,7 @@ int afk_send_command(struct apple_epic_service *service, u8 type, { return afk_send_command_timeout(service, type, payload, payload_len, output, output_len, retcode, - MSEC_PER_SEC); + afk_service_timeout_ms(service)); } static u16 afk_command_tag(struct apple_epic_service *service, u8 slot) @@ -3503,7 +3518,7 @@ int afk_service_call(struct apple_epic_service *service, u16 group, u32 command, { return afk_service_call_timeout(service, group, command, data, data_len, data_pad, output, output_len, - output_pad, MSEC_PER_SEC); + output_pad, afk_service_timeout_ms(service)); } int afk_service_call_len(struct apple_epic_service *service, u16 group, @@ -3513,7 +3528,7 @@ int afk_service_call_len(struct apple_epic_service *service, u16 group, { return afk_service_call_timeout_len(service, group, command, data, data_len, data_pad, output, output_len, output_pad, - MSEC_PER_SEC, received); + afk_service_timeout_ms(service), received); } int afk_service_call_timeout(struct apple_epic_service *service, u16 group, diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 1621c62f1a4a0f..f3a8c15ec3d747 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -362,6 +362,12 @@ struct apple_dcp_hw_data { * properties after it are not parsed (afk_recv_handle_init()). */ bool afk_announced_names; + /* + * How long AFK waits for the firmware to start or stop an endpoint + * and to answer a command or service call (afk_timeout_ms()); zero + * for one second. + */ + unsigned int afk_timeout_ms; }; enum dcp_test_point { From 842c9c424757b9e78eb5d110cadf3f36d902e8fb Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:37:26 +0100 Subject: [PATCH 0326/1514] drm/apple: add iBoot SET_SURFACE and display commands for other users ibootep.c sends the iBoot interface's display commands only for the T6030 external role's first-pixel diagnostic: the queries and setters are reachable from its sysfs file and pattern path alone, gated on dcp->external, and the surface is set through the swap operations 15/16/18/19. The T8152 DCP firmware is driven through this interface alone and sets its surface with operation 1, SET_SURFACE. - Add DCP_FIRMWARE_IBOOT, a DCP driven through the iBoot interface alone, and dcp_is_iboot(). No match entry selects it yet. - Build SET_SURFACE (operation 1, one 164-byte layer) and the three queries in iboot_build_pattern_request(). - Export ibootep_set_power(), ibootep_get_hpd(), ibootep_get_timing_modes(), ibootep_get_color_modes(), ibootep_set_mode() and ibootep_set_surface(), with the mode records in ibootep.h. On AFKv2 the setters go out without a reply buffer, as the firmware asserts on one, and a reply is checked against the length the transport reports, through the new afk_send_command_len(). SET_SURFACE scans out one linear BGRA plane in colour space 2, as the bootloader sets it on T8152. - Open the service for a DCP_FIRMWARE_IBOOT processor under either of its names (disp0-service on the main DCP, dispext-service on the external ones), without the manual query file: its display driver sends every command. The T6030 external role keeps its gate, its service name, its sysfs file and its pattern and frame commands as they were. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 9 ++ drivers/gpu/drm/apple/afk.h | 7 + drivers/gpu/drm/apple/dcp-internal.h | 6 + drivers/gpu/drm/apple/ibootep.c | 205 +++++++++++++++++++++++++- drivers/gpu/drm/apple/ibootep.h | 38 +++++ drivers/gpu/drm/apple/version_utils.h | 6 + 6 files changed, 266 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 6b65f13e052095..ad684ae5e954bb 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -3247,6 +3247,15 @@ int afk_send_command_timeout(struct apple_epic_service *service, u8 type, output, output_len, retcode, timeout_ms, NULL); } +int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *payload, size_t payload_len, void *output, + size_t output_len, u32 *retcode, size_t *received) +{ + return afk_send_command_timeout_len(service, type, payload, payload_len, + output, output_len, retcode, + afk_service_timeout_ms(service), received); +} + /* * @reply_len (legacy EPIC only): return just the bytes the firmware reported * in its reply instead of the whole allocated output. diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index da51a5fa0daee0..c01022b6b0f875 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -646,6 +646,13 @@ int afk_send_command_timeout(struct apple_epic_service *service, u8 type, const void *payload, size_t payload_len, void *output, size_t output_len, u32 *retcode, unsigned int timeout_ms); +/* + * As afk_send_command(), and @received is set to the number of bytes of + * @output the reply filled: an AFKv2 reply may be shorter than @output_len. + */ +int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *payload, size_t payload_len, void *output, + size_t output_len, u32 *retcode, size_t *received); int afk_service_call(struct apple_epic_service *service, u16 group, u32 command, const void *data, size_t data_len, size_t data_pad, void *output, size_t output_len, size_t output_pad); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index f3a8c15ec3d747..9618011b29c56b 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1211,6 +1211,12 @@ struct apple_dcp { struct dcp_cec *cec; }; +/* A DCP driven through the firmware's iBoot interface alone. */ +static inline bool dcp_is_iboot(const struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_IBOOT; +} + /* T8132 firmware uses its own wire codec, with the common DRM/KMS owner. */ static inline bool iomfb_is_m4(const struct apple_dcp *dcp) { diff --git a/drivers/gpu/drm/apple/ibootep.c b/drivers/gpu/drm/apple/ibootep.c index 7f90f68bf26f64..1a12fb947d2ccf 100644 --- a/drivers/gpu/drm/apple/ibootep.c +++ b/drivers/gpu/drm/apple/ibootep.c @@ -22,9 +22,12 @@ #define IBOOT_PATTERN_STRIDE DCPEXT_STRIDE enum iboot_query_op { + IBOOT_SET_SURFACE = 1, + IBOOT_SET_POWER = 2, IBOOT_GET_HPD = 3, IBOOT_GET_TIMING_MODES = 4, IBOOT_GET_COLOR_MODES = 5, + IBOOT_SET_MODE = 6, }; /* Packed layouts from m1n1 src/dcp_iboot.h and swap_set_layer_cmd_v13_3. */ @@ -148,15 +151,25 @@ static int iboot_parse_swap_begin(const u8 *reply, size_t received, u32 *id) return 0; } -static int iboot_parse_modes(const u8 *payload, size_t size, u32 *count) +/* A mode list: a count, then as many 24-byte records. */ +static int iboot_parse_mode_count(const u8 *payload, size_t size, u32 *count) { - u32 i; - if (size < 4) return -EPROTO; *count = get_unaligned_le32(payload); if (*count > (size - 4) / IBOOT_MODE_SIZE) return -EPROTO; + return 0; +} + +static int iboot_parse_modes(const u8 *payload, size_t size, u32 *count) +{ + u32 i; + int ret; + + ret = iboot_parse_mode_count(payload, size, count); + if (ret) + return ret; for (i = 0; i < *count; i++) if (get_unaligned_le32(payload + 4 + i * IBOOT_MODE_SIZE) > 1) return -EPROTO; @@ -234,7 +247,13 @@ static int iboot_build_pattern_request(u32 op, const void *data, size_t data_siz size_t expected; switch (op) { + case 1: /* SetSurface */ + expected = sizeof(struct iboot_layer); + break; case 2: expected = 1; break; /* SetPower */ + case 3 ... 5: /* GetHPD, GetTimingModes, GetColorModes */ + expected = 0; + break; case 6: expected = 2 * IBOOT_MODE_SIZE; break; /* SetMode */ case 15: expected = 0; break; /* SwapBegin */ case 16: expected = sizeof(struct iboot_swap_layer_v13_3); break; @@ -401,7 +420,7 @@ static struct iboot_query *iboot_find_query(struct apple_dcp *dcp) struct apple_dcp_afkep *ep = READ_ONCE(dcp->ibootep); u32 i; - if (!dcp->external || !ep) + if ((!dcp->external && !dcp_is_iboot(dcp)) || !ep) return ERR_PTR(-ENODEV); for (i = 0; i < AFK_MAX_CHANNEL; i++) { struct iboot_query *query = smp_load_acquire(&ep->services[i].cookie); @@ -668,6 +687,157 @@ int ibootep_present_pattern(struct apple_dcp *dcp, u64 iova, size_t size, u32 st return ret; } +/* + * One display command of the iBoot interface, with its reply payload copied + * to @out (at least @min_size bytes of it; returns the bytes copied), or a + * setter if @out is NULL. On AFKv2 the setters answer with a transport + * status alone: given a reply buffer, the firmware copies an empty reply + * into it and asserts, so they go out without one. Only the reply's own + * length is checked, not that its first word repeats @op. + */ +static int iboot_command(struct apple_dcp *dcp, u32 op, const void *data, + size_t size, void *out, size_t out_size, size_t min_size) +{ + struct iboot_query *query = iboot_find_query(dcp); + u8 request[16 + sizeof(struct iboot_swap_layer_v13_3)]; + size_t len, received = 0; + u32 retcode = 0, reply_len; + u8 *reply = NULL; + int ret; + + if (IS_ERR(query)) + return PTR_ERR(query); + ret = iboot_build_pattern_request(op, data, size, request, + sizeof(request), &len); + if (ret) + return ret; + if (out || !query->service->ep->wire_v2) { + reply = kzalloc(IBOOT_QUERY_RX_SIZE, GFP_KERNEL); + if (!reply) + return -ENOMEM; + } + ret = afk_send_command_len(query->service, EPIC_SUBTYPE_STD_SERVICE, + request, len, reply, + reply ? IBOOT_QUERY_RX_SIZE : 0, &retcode, + &received); + if (!ret && retcode) { + dev_dbg(dcp->dev, "iBoot command %u returned %#x\n", op, retcode); + ret = -EIO; + } + if (ret || !out) + goto out; + reply_len = received >= 8 ? get_unaligned_le32(reply + 4) : 0; + if (reply_len < 8 || reply_len > received || reply_len - 8 < min_size) { + dev_err(dcp->dev, "iBoot: bad response length for command %u\n", op); + ret = -EPROTO; + goto out; + } + ret = min_t(size_t, reply_len - 8, out_size); + memcpy(out, reply + 8, ret); +out: + kfree(reply); + return ret; +} + +int ibootep_set_power(struct apple_dcp *dcp, bool on) +{ + u8 power = on; + + return iboot_command(dcp, IBOOT_SET_POWER, &power, sizeof(power), NULL, + 0, 0); +} + +int ibootep_get_hpd(struct apple_dcp *dcp, u32 *timings, u32 *colors) +{ + u8 payload[12]; + u32 timing_count, color_count; + bool hpd; + int ret; + + ret = iboot_command(dcp, IBOOT_GET_HPD, NULL, 0, payload, sizeof(payload), + sizeof(payload)); + if (ret >= 0) + ret = iboot_parse_hpd(payload, ret, &hpd, &timing_count, + &color_count); + if (ret) + return ret; + if (timings) + *timings = timing_count; + if (colors) + *colors = color_count; + return hpd; +} + +static int iboot_get_modes(struct apple_dcp *dcp, u32 op, void **modes, + unsigned int *count) +{ + u32 n; + u8 *buf; + int ret; + + buf = kzalloc(IBOOT_QUERY_RX_SIZE, GFP_KERNEL); + if (!buf) + return -ENOMEM; + ret = iboot_command(dcp, op, NULL, 0, buf, IBOOT_QUERY_RX_SIZE, 4); + if (ret >= 0) + ret = iboot_parse_mode_count(buf, ret, &n); + if (!ret) { + *modes = kmemdup(buf + 4, n * IBOOT_MODE_SIZE, GFP_KERNEL); + if (*modes) + *count = n; + else + ret = -ENOMEM; + } + kfree(buf); + return ret; +} + +int ibootep_get_timing_modes(struct apple_dcp *dcp, + struct iboot_timing_mode **modes, + unsigned int *count) +{ + return iboot_get_modes(dcp, IBOOT_GET_TIMING_MODES, (void **)modes, count); +} + +int ibootep_get_color_modes(struct apple_dcp *dcp, + struct iboot_color_mode **modes, unsigned int *count) +{ + return iboot_get_modes(dcp, IBOOT_GET_COLOR_MODES, (void **)modes, count); +} + +int ibootep_set_mode(struct apple_dcp *dcp, const struct iboot_timing_mode *timing, + const struct iboot_color_mode *color) +{ + struct { + struct iboot_timing_mode timing; + struct iboot_color_mode color; + } __packed mode = { *timing, *color }; + + return iboot_command(dcp, IBOOT_SET_MODE, &mode, sizeof(mode), NULL, 0, 0); +} + +int ibootep_set_surface(struct apple_dcp *dcp, u64 iova, u32 width, u32 height, + u32 stride) +{ + /* One linear BGRA plane, SDR, in colour space 2 as the bootloader sets. */ + struct iboot_layer layer = { + .planes = { { + .addr = cpu_to_le64(iova), + .stride = cpu_to_le32(stride), + .addr_format = cpu_to_le32(1), + } }, + .plane_count = cpu_to_le32(1), + .width = cpu_to_le32(width), + .height = cpu_to_le32(height), + .surface_format = cpu_to_le32(1), + .colorspace = cpu_to_le32(2), + .eotf = cpu_to_le32(1), + }; + + return iboot_command(dcp, IBOOT_SET_SURFACE, &layer, sizeof(layer), NULL, + 0, 0); +} + static ssize_t dcpext_modes_query_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) @@ -699,7 +869,7 @@ static void disp_service_init(struct apple_epic_service *service, const char *na struct iboot_query *query; int ret; - if (!dcp->external) + if (!dcp->external && !dcp_is_iboot(dcp)) return; query = devm_kzalloc(dcp->dev, sizeof(*query), GFP_KERNEL); if (!query) @@ -710,6 +880,16 @@ static void disp_service_init(struct apple_epic_service *service, const char *na ret = devm_add_action_or_reset(dcp->dev, iboot_query_cancel, query); if (ret) return; + /* + * A DCP driven through this interface alone has a display driver that + * sends every command (the exported ibootep_* calls); it takes no + * manual queries next to them. + */ + if (dcp_is_iboot(dcp)) { + /* Published for iboot_find_query()'s acquire. */ + smp_store_release(&service->cookie, query); + return; + } /* Remove the sysfs entry before cancelling work during device cleanup. */ ret = devm_device_add_group(dcp->dev, &iboot_query_group); if (ret) { @@ -741,6 +921,19 @@ static const struct apple_epic_service_ops external_ibootep_ops[] = { {} }; +/* DCP_FIRMWARE_IBOOT: the main DCP's service, or an external one's. */ +static const struct apple_epic_service_ops iboot_variant_ops[] = { + { + .name = "disp0-service", + .init = disp_service_init, + }, + { + .name = "dispext-service", + .init = disp_service_init, + }, + {} +}; + int ibootep_init(struct apple_dcp *dcp) { const struct apple_epic_service_ops *ops = ibootep_ops; @@ -751,6 +944,8 @@ int ibootep_init(struct apple_dcp *dcp) return -EBUSY; if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) ops = external_ibootep_ops; + if (dcp_is_iboot(dcp)) + ops = iboot_variant_ops; dcp->ibootep = afk_init(dcp, DISP0_ENDPOINT, ops); if (IS_ERR(dcp->ibootep)) { ret = PTR_ERR(dcp->ibootep); diff --git a/drivers/gpu/drm/apple/ibootep.h b/drivers/gpu/drm/apple/ibootep.h index aa44c2f8754e44..aa6ad17a61be17 100644 --- a/drivers/gpu/drm/apple/ibootep.h +++ b/drivers/gpu/drm/apple/ibootep.h @@ -27,4 +27,42 @@ int ibootep_rearm_pattern(struct apple_dcp *dcp); */ int ibootep_present_frame(struct apple_dcp *dcp, u64 iova, size_t size, u32 stride); +/* + * The iBoot interface's display commands, for a DCP driven through it + * (DCP_FIRMWARE_IBOOT) and for the T6030 external role. Sleepable callers + * outside the AFK receive queue; the caller serializes them. + */ +struct iboot_timing_mode { + __le32 valid; + __le32 width; + __le32 height; + __le32 fps; /* 16.16 */ + /* byte 0 bit 6: a standard mode the firmware adds on its own */ + u8 flags[8]; +} __packed; + +struct iboot_color_mode { + __le32 valid; + __le32 colorimetry; + __le32 eotf; + __le32 encoding; + __le32 bpp; + u8 pad[4]; +} __packed; + +int ibootep_set_power(struct apple_dcp *dcp, bool on); +/* 1 with a sink, 0 without; the counts of its timing and colour modes. */ +int ibootep_get_hpd(struct apple_dcp *dcp, u32 *timings, u32 *colors); +/* The sink's mode lists, newly allocated; the caller frees them. */ +int ibootep_get_timing_modes(struct apple_dcp *dcp, + struct iboot_timing_mode **modes, + unsigned int *count); +int ibootep_get_color_modes(struct apple_dcp *dcp, + struct iboot_color_mode **modes, unsigned int *count); +int ibootep_set_mode(struct apple_dcp *dcp, const struct iboot_timing_mode *timing, + const struct iboot_color_mode *color); +/* SET_SURFACE: scan out one linear BGRA plane at @iova. */ +int ibootep_set_surface(struct apple_dcp *dcp, u64 iova, u32 width, u32 height, + u32 stride); + #endif diff --git a/drivers/gpu/drm/apple/version_utils.h b/drivers/gpu/drm/apple/version_utils.h index 8cf36e39d3f247..fe19968ee5f1ef 100644 --- a/drivers/gpu/drm/apple/version_utils.h +++ b/drivers/gpu/drm/apple/version_utils.h @@ -62,6 +62,12 @@ enum dcp_firmware_version { */ DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0, + /* + * A DCP driven through its firmware's iBoot interface alone + * (disp0-service, dispext-service; see ibootep.c), not through + * IOMFB: the T8152 one. + */ + DCP_FIRMWARE_IBOOT, }; #endif /*__APPLE_VERSION_UTILS_H__*/ From 9ab600a3f46e2a6cb3c673816e47f9bd3b359114 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:48:46 +0100 Subject: [PATCH 0327/1514] drm/apple: add the interim T8152 DisplayPort hardware The T8152 (Mac mini J873g) DCPs drive their displays through hardware no subsystem driver covers yet: the rear USB-C ports' ATC PHYs have no DisplayPort mode in drivers/phy/apple/atc.c for T8152, the HDMI port's DisplayPort PHY has no T8152 type in drivers/phy/apple/dptx.c (its lanes are 0x2800 apart from 0x4500), the PS190 DisplayPort-to-HDMI converter behind it is powered through the SMC, the ports' ACE3 PD controllers do not report to the Type-C route layer, and the DCP firmware's iBoot interface does not hand out the sink's EDID. Add the T8152 code for them as separate files, each marked interim until atc.c's DisplayPort mode, tipd and the Type-C route layer take over. The bootloader trains the displays before Linux starts; the PHYs keep its setup and reprogram what a link training changes, as the DCP firmware calls into the AP for them. t8152_atc.c, the USB-C ports: - The three DCPs share the three rear ports through the one display crossbar. A DCP claims a free ATC under a mutex and gives it up on unplug; a monitor stays with its DCP while userspace blanks it. The crossbar's upstream reset, clock and enable fields are indexed by DCP endpoint * 2 + DPTX port, independently of the downstream DFP0 mux fields, which select that endpoint. - Each ATC has its own PMGR DP clock divider, at 0x300020044 + 8 * n. - The ATC's DP clock switch (PHY CFG block + 0x14 select, + 0x18 enable, + 0x1c status) chooses where each DP pixel clock comes from. PCLK1 is switched to PMGR DP clock 0 (select field 1, enable and status bit 1) after the divider for the link rate is written, and switched off the same way. With source 0 selected the stream clock never followed the divider: modes above about 165 MHz pixel clock, and 640x480, stayed black while the link trained and the firmware set the mode. - A monitor that also carries USB3 negotiates pin assignment D (data status bit 5): two DisplayPort lanes, and only the PMA that carries them is set up. GET_MAX_LANE_COUNT reports the route's lanes. - A cold start powers the ATC's dependencies (USB AON, the common PSD, both DP power states), the common block and AUX, and starts the lanes at HBR at once: from cold, AUX only works with the DP PLL and PMAs running. A power down undoes what it powered up. - The EDID is read through the AP AUX controller aux0, which the three DCPs share and take in turn; its output select for an ATC port is the ATC instance * 3 + its local DFP. t8152_hdmi.c, the HDMI port: - The bootloader wires the HDMI PHY (source select, APB 0x10) to the main DCP (0) when no USB-C display is attached at boot, and then never starts DCPEXT0; next to a USB-C display it wires DCPEXT0 (1). The source select is read only while the PHY's PMGR power state is requested and active: a USB-C-only boot leaves the PHY off, and a read of its registers then raises an SError. - When the bootloader left HDMI off (no monitor at boot leaves its PLL unlocked), the HDMI port becomes one of the shared ports. A DCP that drives no USB-C display takes it when the HPD line goes high, starts the PHY from cold (PMGR and PSD power, the PS190, source select, PLL, AUX and PHY power, the tunables, PLL and PHY activation, four lanes, impedance calibration), keeps the link up across display off, and gives the port back once the sink is gone. The source select takes every DCP's crossbar endpoint, DCPEXT1's 2 included, so DCPEXT1 takes the port while the other two drive USB-C monitors. The HPD line is requested once for all of them. - The PS190 is powered through the SMC when the port is set up, before anything reads HPD or an EDID: it drives the HPD line only while it is powered, and while it is off every AUX request on the USB-C ports ends with channel status 2 as well. Without the SMC bound yet, the setup is deferred. t8152_aux.c: the AUX controllers' request framing. Bits 21:8 of the retry register are a 14-bit reply timeout, set to 3200; read as a three-bit delay, the EDID through a USB-C to HDMI adapter timed out. A sink left in D3 is woken before DDC. t8152_pd.c: the ACE3 plug, orientation, DP alt mode and HPD state over SPMI, read through the logical register window under the SPMI device's lock, which the USB4 port monitor takes as well. A controller in power state 7 enters alt mode only after SSPS 0. A sink that stopped answering AUX after a monitor's deep sleep comes back after a reset (Gaid) and SSPS 0. t8152_dptx.c: the DPTX port service's calls into the AP apply link rate, lanes and drive settings to these PHYs and read the drive settings back as they were set; an unsupported GET_DRIVE_SETTINGS was followed by a firmware crash. The port's release is group 8 command 7, and its HPD call (group 8 command 8) carries a status in its reply's first word. dptxep.c serves the same calls for PHY framework PHYs, the crossbar mux and Thunderbolt tunnels; its connect and display request, its call numbers and its port records are used here. The HDMI PHY's power state check is based on a change by Acelogic. The files are built with the new DRM_APPLE_DCP_T8152, enabled in asahi.config, and nothing uses them yet. A MAINTAINERS entry for the T8152 display covers them and the binding. Signed-off-by: Thomas Glanzmann --- MAINTAINERS | 7 + arch/arm64/configs/asahi.config | 1 + drivers/gpu/drm/apple/Kconfig | 16 + drivers/gpu/drm/apple/Makefile | 2 + drivers/gpu/drm/apple/dcp-internal.h | 3 + drivers/gpu/drm/apple/t8152_atc.c | 924 ++++++++++++++++++++++++++ drivers/gpu/drm/apple/t8152_aux.c | 200 ++++++ drivers/gpu/drm/apple/t8152_display.h | 140 ++++ drivers/gpu/drm/apple/t8152_dptx.c | 315 +++++++++ drivers/gpu/drm/apple/t8152_hdmi.c | 669 +++++++++++++++++++ drivers/gpu/drm/apple/t8152_pd.c | 211 ++++++ 11 files changed, 2488 insertions(+) create mode 100644 drivers/gpu/drm/apple/t8152_atc.c create mode 100644 drivers/gpu/drm/apple/t8152_aux.c create mode 100644 drivers/gpu/drm/apple/t8152_display.h create mode 100644 drivers/gpu/drm/apple/t8152_dptx.c create mode 100644 drivers/gpu/drm/apple/t8152_hdmi.c create mode 100644 drivers/gpu/drm/apple/t8152_pd.c diff --git a/MAINTAINERS b/MAINTAINERS index cb48635b6e3680..1afb033e7ffcd0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2151,6 +2151,13 @@ F: tools/testing/kunit/configs/mt7932.config F: tools/testing/selftests/drivers/apple/aop-las.py F: tools/testing/selftests/drivers/gpu/apple-dcp/ +APPLE T8152 DCP DISPLAY DRIVER (IBOOT INTERFACE) +M: Thomas Glanzmann +L: dri-devel@lists.freedesktop.org +S: Maintained +F: Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +F: drivers/gpu/drm/apple/t8152_* + APPLETALK NETWORK LAYER L: netdev@vger.kernel.org S: Obsolete diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index 3173021d4f19d8..ff74ba4c8dad68 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -88,6 +88,7 @@ CONFIG_DRM_ASAHI_M3_T8122=y CONFIG_DRM_ADP=m CONFIG_DRM_APPLE=m CONFIG_DRM_APPLE_DCP_T8132=y +CONFIG_DRM_APPLE_DCP_T8152=y CONFIG_DRM_APPLE_CEC=y CONFIG_DRM_APPLE_AUDIO=y CONFIG_DRM_APPLE_DCP_T6030_AUDIO=y diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 99632ffe1535cb..d27d975da6f41c 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -75,6 +75,22 @@ config DRM_APPLE_DCP_T8132 Load appledrm explicitly before the GPU, with its alias autoload disabled, after guarded admission of the inherited display DARTs. +config DRM_APPLE_DCP_T8152 + bool "Mac mini M6 (J873g) displays" + depends on DRM_APPLE + depends on SPMI=y || SPMI=DRM_APPLE + depends on MFD_MACSMC=y || MFD_MACSMC=DRM_APPLE + help + Lets the common Apple display driver drive the three display + coprocessors of the T8152 Mac mini (J873g) through their firmware's + iBoot interface: the HDMI port, whose DisplayPort-to-HDMI converter + is powered through the SMC, and displays on the rear USB-C ports, + whose PD controllers are polled over SPMI. + + The boot loader hands each coprocessor over, running or quiesced, + with the AFK endpoints it left running. The adopted sessions cannot + be stopped; their DMA stays retained until reboot. + config DRM_APPLE_DEBUG bool "Enable additional driver debugging" depends on DRM_APPLE diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index a6687d7cccd657..3a0953cf6628aa 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -18,6 +18,8 @@ appledrm-y += iomfb_v14_7_tpl.o appledrm-y += iomfb_v26_6_desktop.o appledrm-y += iomfb_v14_7.o iomfb_v14_7_link.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8132) += iomfb_m4.o t8132_ext_drm.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_atc.o t8152_aux.o t8152_dptx.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_pd.o appledrm-y += iomfb_h17p.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_h17p_test.o parser_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_external_hdr_hints_test.o diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 9618011b29c56b..857ece58491568 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -462,6 +462,7 @@ struct dcp_desktop_state { /* TODO: move IOMFB members to its own struct */ struct dcpext_scanout; +struct t8152_display; struct dcp_hdmi; struct dcp_cec; @@ -584,6 +585,8 @@ struct apple_dcp { /* firmware version and compatible firmware version */ enum dcp_firmware_version fw_compat; + /* T8152: the DisplayPort hardware behind the DPTX port (t8152_display.h) */ + struct t8152_display *t8152; /* Bumped by every iomfb poweron; see afk_compact_slot(). */ u32 afk_power_gen; /* diff --git a/drivers/gpu/drm/apple/t8152_atc.c b/drivers/gpu/drm/apple/t8152_atc.c new file mode 100644 index 00000000000000..ce4b6a84602de1 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_atc.c @@ -0,0 +1,924 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * T8152 (J873g) ATC PHYs as DisplayPort outputs of the DCPs' DPTX ports. + * + * Interim, until drivers/phy/apple/atc.c has a DisplayPort mode for T8152 + * and the display crossbar driver and the Type-C route layer of + * dcp-fabric.c take over the route and the choice of port: this programs + * the PHY's DisplayPort lanes, its pixel clock and the crossbar route + * itself. + * + * The bootloader trains a USB-C display before Linux starts; this takes + * that link over and then follows the firmware: link rate changes (stop and + * set up the lanes again), drive settings, the DCP -> ATCn/DFP0 crossbar + * route, and with the display off or unplugged a full power down and a cold + * start. A DCP drives one USB-C port at a time: the one it claims from the + * shared ports while polling their PD controllers. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dptxep.h" +#include "t8152_display.h" + +#define ATC_AON 0x1e00 +#define ATC_CFG 0x60000 +#define ATC_XBAR 0x74000 +/* + * The DP clock switch at CFG + 0x14 (select), + 0x18 (enable) and + 0x1c + * (status). DP pixel clock n (1..4) runs from switch n: select field n is n + * for PMGR DP clock n - 1, 7 for none, and enable/status bit 1 + 7 * (n - 1) + * gates that PMGR clock. PCLK1 is used here, from PMGR DP0, whose divider + * atc_clock_write() sets for the link rate. + */ +#define ATC_CLKSW_SELECT (ATC_CFG + 0x14) +#define ATC_CLKSW_ENABLE (ATC_CFG + 0x18) +#define ATC_CLKSW_STATUS (ATC_CFG + 0x1c) +#define ATC_CLKSW_PCLK1_SEL GENMASK(2, 0) +#define ATC_CLKSW_PCLK1_MODE BIT(12) +#define ATC_CLKSW_PCLK1_OFF 7 +#define ATC_CLKSW_PCLK1_DP0 1 +#define ATC_CLKSW_PCLK1_EN BIT(1) +#define ATC_TIMEOUT_US 10000 + +struct t8152_atc_port { + void __iomem *base; + unsigned int index; /* ATC instance */ + /* display crossbar DFP endpoint of this ATC */ + u32 dfp; + struct spmi_device *pd; + /* AP DisplayPort AUX controller aux0 (shared), for the EDID */ + struct t8152_aux *aux; + /* PMGR power states of the four ATC dependencies */ + void __iomem *ps; + void __iomem *psd; + /* the dependencies this driver powered up, and may power down */ + u8 owned; + /* {offset, mask, value} tunables, before and after the lane setup */ + const __be32 *tunable[2]; + int tunable_len[2]; + /* This ATC's PMGR DP clock divider selects the link rate. */ + void __iomem *dp_clock; + bool swap; + bool active; + bool route_started; + u32 link_rate; + u32 lanes, next_lanes; +}; + +struct t8152_atc { + struct t8152_aux aux; + struct t8152_atc_port port[4]; + unsigned int nports; + /* the port the DCP drives, and the one a sink was found on */ + struct t8152_atc_port *cur, *next; +}; + +/* J873 has one display crossbar. Claims outlive firmware PHY power cycles. */ +static DEFINE_MUTEX(atc_owner_lock); +static struct device *atc_owner[4]; +/* All three DCPs borrow the same AP AUX controller for EDID reads. */ +static DEFINE_MUTEX(atc_aux_lock); + +static struct t8152_atc_port *atc_cur(struct t8152_display *disp) +{ + return ((struct t8152_atc *)disp->phy_priv)->cur; +} + +static const u32 atc_rates[] = { + LINK_RATE_RBR, LINK_RATE_HBR, LINK_RATE_HBR2, LINK_RATE_HBR3, +}; + +static bool atc_dp_pma(struct t8152_atc_port *atc, u32 pma) +{ + return atc->lanes == 4 || pma == !atc->swap; +} + +static bool atc_dp_register(struct t8152_atc_port *atc, u32 offset) +{ + if (offset >= 0x3000 && offset < 0xc000) + return atc_dp_pma(atc, 0); + if (offset >= 0xc000 && offset < 0x15000) + return atc_dp_pma(atc, 1); + return true; +} + +static void atc_update(struct t8152_atc_port *atc, u32 offset, u32 mask, u32 value) +{ + u32 reg = readl(atc->base + offset); + + writel((reg & ~mask) | value, atc->base + offset); +} + +static int atc_poll(struct t8152_atc_port *atc, u32 offset, u32 mask, u32 value) +{ + u32 reg; + + return readl_poll_timeout(atc->base + offset, reg, + (reg & mask) == value, 1, ATC_TIMEOUT_US); +} + +static int atc_route_stop(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + u32 ufp = disp->dp_source * 2; + u32 mask = BIT(ufp); + + if (!atc->route_started) + return 0; + atc_update(atc, ATC_XBAR + 0x3c, mask, 0); + atc_update(atc, ATC_XBAR, mask, 0); + atc_update(atc, ATC_XBAR + 0xc, mask, 0); + atc_update(atc, ATC_XBAR + 0x24, 0x100, 0); + udelay(1); + /* + * With the pipe powered off (the bootloader hands the display over + * that way) nothing acknowledges the stop; the route is idle then, so + * finish it anyway. + */ + if (atc_poll(atc, ATC_XBAR + 0x800, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x808, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x81c, 0x100, 0)) + dev_info(disp->dev, "ATC%u: no crossbar stop acknowledgment\n", atc->index); + atc_update(atc, ATC_XBAR + 8, mask, 0); + atc_update(atc, ATC_XBAR + 0x20, 7 << (3 * ufp), 0); + atc_update(atc, ATC_XBAR + 0x38, 0x700, 0); + atc_update(atc, ATC_XBAR + 4, mask, mask); + atc_update(atc, ATC_XBAR + 0x1c, mask, mask); + atc_update(atc, ATC_XBAR + 0x34, 0x100, 0x100); + atc->route_started = false; + dev_dbg(disp->dev, "ATC%u: display route disabled\n", atc->index); + return 0; +} + +/* + * A source -> ATCn/DFP0 route, PCLK1: both DFP0 mux fields (0x44 bits 23:20 + * and 11:8) select the source. The upstream reset, clock and enable fields + * are indexed by DCP endpoint * 2 + DPTX port, independently of the + * downstream DFP0 fields. AUX borrowing keeps that DCP's clock path. + */ +#define ATC_SEL_AUX0 9 /* UFP endpoint 5 (aux0) + 4 */ + +static int atc_route_start_sel(struct t8152_display *disp, + struct t8152_atc_port *atc, u32 sel) +{ + u32 ufp = disp->dp_source * 2; + u32 mask = BIT(ufp); + + if (atc->route_started) + return 0; + atc_update(atc, ATC_XBAR + 0x44, 0x00f00000, sel << 20); + atc_update(atc, ATC_XBAR + 0x44, 0x00000f00, sel << 8); + atc_update(atc, ATC_XBAR + 4, mask, 0); + atc_update(atc, ATC_XBAR + 0x1c, mask, 0); + atc_update(atc, ATC_XBAR + 0x34, 0x100, 0); + udelay(1); + if (atc_poll(atc, ATC_XBAR + 0x804, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x818, mask, 0) || + atc_poll(atc, ATC_XBAR + 0x82c, 0x100, 0)) { + dev_err(disp->dev, "ATC%u: crossbar reset acknowledgment timeout\n", + atc->index); + return -ETIMEDOUT; + } + atc_update(atc, ATC_XBAR + 8, mask, mask); + atc_update(atc, ATC_XBAR + 0x20, 7 << (3 * ufp), 1 << (3 * ufp)); + atc_update(atc, ATC_XBAR + 0x38, 0x700, 0x100); + atc_update(atc, ATC_XBAR + 0x48, 1, 0); + atc_update(atc, ATC_XBAR, mask, mask); + atc_update(atc, ATC_XBAR + 0xc, mask, mask); + atc_update(atc, ATC_XBAR + 0x24, 0x100, 0x100); + atc_update(atc, ATC_XBAR + 0x4c, 0x100, 0x100); + atc_update(atc, ATC_XBAR + 0x3c, mask, mask); + atc->route_started = true; + dev_dbg(disp->dev, "ATC%u: source %u to local DFP0 route configured\n", + atc->index, sel); + return 0; +} + +static int atc_route_start(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + return atc_route_start_sel(disp, atc, disp->dp_source * 2); +} + +/* Common four-lane setup; the rate-dependent fields follow in atc_dp_start. */ +static const struct { + u32 offset, mask, value; +} atc_dp_setup[] = { + { 0x2044, 0xffff, 0x4b0 }, + { 0x4c, 0x3c0000, 0x3c0000 }, + { 0x4c80, 0x40, 0x40 }, + { 0xdc80, 0x40, 0x40 }, + { 0x4fd4, 0x2000000, 0x2000000 }, + { 0x4fd4, 0x1800000, 0x800000 }, + { 0xdfd4, 0x2000000, 0x2000000 }, + { 0xdfd4, 0x1800000, 0x800000 }, + { 0x4d84, 0x1c0000, 0 }, + { 0x4fd4, 1, 0 }, + { 0x4fd4, 8, 0 }, + { 0x4fd4, 2, 2 }, + { 0x4fd4, 0x10, 0x10 }, + { 0x8904, 0x1c0000, 0 }, + { 0x8800, 0x10000000, 0 }, + { 0x8800, 0x80000000, 0 }, + { 0x8800, 0x20000000, 0x20000000 }, + { 0x8804, 1, 1 }, + { 0xdd84, 0x1c0000, 0 }, + { 0xdfd4, 1, 0 }, + { 0xdfd4, 8, 0 }, + { 0xdfd4, 2, 2 }, + { 0xdfd4, 0x10, 0x10 }, + { 0x11904, 0x1c0000, 0 }, + { 0x11800, 0x10000000, 0 }, + { 0x11800, 0x80000000, 0 }, + { 0x11800, 0x20000000, 0x20000000 }, + { 0x11804, 1, 1 }, + { 0x3c04, 2, 2 }, + { 0x3c04, 1, 1 }, + { 0xcc04, 2, 2 }, + { 0xcc04, 1, 1 }, +}; + +/* Program the PMGR DP clock divider and wait for the change to settle. */ +static int atc_clock_write(struct t8152_atc_port *atc, u32 divider) +{ + u32 reg = readl(atc->dp_clock); + + writel((reg & ~0x0f000000) | (divider << 24), atc->dp_clock); + return readl_poll_timeout(atc->dp_clock, reg, !(reg & BIT(30)), 1, + ATC_TIMEOUT_US); +} + +/* Stop the DP lanes: route, pixel clock, then both PMAs. */ +static int atc_dp_stop(struct t8152_display *disp, struct t8152_atc_port *atc) +{ + u32 reg; + + atc_route_stop(disp, atc); + atc_update(atc, ATC_CLKSW_SELECT, ATC_CLKSW_PCLK1_SEL | ATC_CLKSW_PCLK1_MODE, + ATC_CLKSW_PCLK1_OFF); + atc_update(atc, ATC_CLKSW_ENABLE, ATC_CLKSW_PCLK1_EN, 0); + if (readl_poll_timeout(atc->base + ATC_CLKSW_STATUS, reg, + !(reg & ATC_CLKSW_PCLK1_EN), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: DPTX clock stop failed\n", atc->index); + return -ETIMEDOUT; + } + atc_update(atc, 0x2040, BIT(16), 0); + udelay(5); + atc_update(atc, 0x2000, BIT(15), 0); + atc_update(atc, 0x2000, BIT(13), 0); + atc_update(atc, 0x2000, BIT(14), 0); + atc_update(atc, 0x2000, BIT(2), 0); + atc_update(atc, 0x2000, BIT(3), BIT(3)); + atc_update(atc, 0xe10, BIT(2), BIT(2)); + atc_update(atc, 0xe08, BIT(29), BIT(29)); + /* Remove both PMA clock requests, then clamp and power down both lanes. */ + for (u32 offset = 0x1e18; offset <= 0x1e1c; offset += 4) { + u32 pma = (offset - 0x1e18) / 4; + + if (!atc_dp_pma(atc, pma)) + continue; + atc_update(atc, ATC_AON + 0x24, + BIT(12 + 2 * pma) | BIT(16 + 2 * pma), 0); + udelay(1); + atc_update(atc, offset, BIT(5), 0); + udelay(1); + atc_update(atc, offset, BIT(0), BIT(0)); + udelay(1); + atc_update(atc, offset, BIT(2), 0); + udelay(1); + atc_update(atc, offset, BIT(1), 0); + udelay(1); + } + atc->link_rate = 0; + return 0; +} + +/* DP lane setup at rate index r. */ +static int atc_dp_start(struct t8152_display *disp, struct t8152_atc_port *atc, u32 r) +{ + static const u32 tx_ctrl[] = { 0x4eb0, 0x8b10, 0xdeb0, 0x11b10 }; + static const u32 wake_count[] = { 0xbb5, 0xbb7, 0xbb8, 0xbb9 }; + u32 reg; + int ret; + + if (readl(atc->dp_clock) & BIT(30)) + return -EBUSY; + if (!r) { + atc_update(atc, 0xe10, BIT(2), BIT(2)); + atc_update(atc, 0xe08, BIT(29), BIT(29)); + } + for (u32 i = 0; i < 2; i++) { + u32 offset = 0x1e18 + 4 * i; + + if (!atc_dp_pma(atc, i)) + continue; + atc_update(atc, ATC_AON + 0x24, BIT(12 + 2 * i), BIT(12 + 2 * i)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(16 + 2 * i), BIT(16 + 2 * i)); + udelay(1); + atc_update(atc, offset, BIT(1), BIT(1)); + udelay(1); + atc_update(atc, offset, BIT(2), BIT(2)); + udelay(1); + atc_update(atc, offset, BIT(0), 0); + udelay(1); + atc_update(atc, offset, BIT(5), BIT(5)); + udelay(2); + } + atc_update(atc, 0x2000, 0x380000, r << 19); + for (unsigned int i = 0; i < ARRAY_SIZE(atc_dp_setup); i++) + if (atc_dp_register(atc, atc_dp_setup[i].offset)) + atc_update(atc, atc_dp_setup[i].offset, atc_dp_setup[i].mask, + atc_dp_setup[i].value); + for (u32 i = 0; i < 2; i++) { + if (!atc_dp_pma(atc, i)) + continue; + atc_update(atc, 0x8684 + i * 0x9000, 3, r ? 0 : 1); + atc_update(atc, 0x4c80 + i * 0x9000, 0x30, r ? 0 : 0x10); + } + for (unsigned int i = 0; i < ARRAY_SIZE(tx_ctrl); i++) { + if (!atc_dp_register(atc, tx_ctrl[i])) + continue; + atc_update(atc, tx_ctrl[i], 0x7e07ff, 1); + atc_update(atc, tx_ctrl[i] - 0x14, 0x7f, r < 2 ? 0x65 : 0x40); + } + atc_update(atc, 0x2000, 0x70, 0x10); + atc_update(atc, 0x2000, BIT(13), BIT(13)); + atc_update(atc, 0x2044, 0xffff0000, wake_count[r] << 16); + atc_update(atc, atc->swap ? 0x89f0 : 0x119f0, BIT(14), BIT(14)); + atc_update(atc, 0x2000, BIT(2), BIT(2)); + atc_update(atc, 0x2000, BIT(3), BIT(3)); + atc_update(atc, 0x2040, BIT(16), BIT(16)); + + ret = atc_clock_write(atc, 10 - r); + if (ret) { + dev_err(disp->dev, "ATC%u: DP clock change timeout\n", atc->index); + return ret; + } + /* + * Clock the stream from PMGR DP0 at the link-rate divider just set. + * With source 0 selected instead, the pixel clock does not follow the + * divider, and every mode above about 165 MHz stays black. + */ + atc_update(atc, ATC_CLKSW_SELECT, ATC_CLKSW_PCLK1_SEL | ATC_CLKSW_PCLK1_MODE, + ATC_CLKSW_PCLK1_DP0); + atc_update(atc, ATC_CLKSW_ENABLE, ATC_CLKSW_PCLK1_EN, ATC_CLKSW_PCLK1_EN); + if (readl_poll_timeout(atc->base + ATC_CLKSW_STATUS, reg, + reg & ATC_CLKSW_PCLK1_EN, 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: DP pixel clock does not start\n", atc->index); + return -ETIMEDOUT; + } + ret = atc_route_start(disp, atc); + if (ret) + return ret; + atc->link_rate = atc_rates[r]; + dev_info(disp->dev, "ATC%u: %u-lane DPTX setup at rate %#x\n", atc->index, + atc->lanes, atc->link_rate); + return 0; +} + +/* + * The power dependencies, in order: the ATC's USB AON (PS +0x100), its common + * PSD, then its two DP PS registers (+0, +0x20), with the values they idle at + * (ATC3: PS 0x1c0, PSD 58, PS 0xc0, 0xe0). + */ +#define ATC_PSD_TARGET 0x90 +#define ATC_PSD_STATE 0x80 +static const u32 atc_ps_offset[] = { 0x100, 0, 0x0, 0x20 }; +static const u32 atc_ps_idle[] = { 0x300, 6, 0x244, 0x244 }; + +static int atc_psd_wait(struct t8152_atc_port *atc, u32 state) +{ + u32 reg; + + /* + * Only the state: the acknowledge bit stays clear when Linux switches + * the PSD, in either direction. + */ + return readl_poll_timeout(atc->psd + ATC_PSD_STATE, reg, + (reg & 7) == state, 1, ATC_TIMEOUT_US); +} + +static int atc_gate(struct t8152_atc_port *atc, unsigned int i, bool on) +{ + u32 value = on ? (atc_ps_idle[i] & 0xfffffcf0) | 15 : atc_ps_idle[i]; + u32 reg; + + /* Already up (the bootloader's or an earlier activation's). */ + if (on && (i == 1 ? !(readl(atc->psd + ATC_PSD_STATE) & 7) : + (readl(atc->ps + atc_ps_offset[i]) & 0xf0) == 0xf0)) + return 0; + if (on) + atc->owned |= BIT(i); + else + atc->owned &= ~BIT(i); + if (i == 1) { + writel(on ? 0 : atc_ps_idle[i], atc->psd + ATC_PSD_TARGET); + return atc_psd_wait(atc, on ? 0 : atc_ps_idle[i]); + } + writel(value, atc->ps + atc_ps_offset[i]); + return readl_poll_timeout(atc->ps + atc_ps_offset[i], reg, + (reg & 0xf0) == ((value & 15) << 4), 1, + ATC_TIMEOUT_US); +} + +static void atc_apply_tunables(struct t8152_atc_port *atc, unsigned int which) +{ + const __be32 *t = atc->tunable[which]; + + for (int i = 0; i + 3 <= atc->tunable_len[which]; i += 3) + atc_update(atc, be32_to_cpu(t[i]), be32_to_cpu(t[i + 1]), + be32_to_cpu(t[i + 2])); +} + +/* Cold start: the power dependencies, the common block and AUX, then the lanes at HBR. */ +static int atc_activate(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + void __iomem *cfg = atc->base + ATC_CFG; + unsigned int gates = 0; + u32 reg; + + if (READ_ONCE(atc_owner[atc->index]) != disp->dev) + return -EBUSY; + if (atc->active) + return 0; + if (!atc->tunable[0] || !atc->tunable[1]) + return -EOPNOTSUPP; + for (; gates < ARRAY_SIZE(atc_ps_idle); gates++) + if (atc_gate(atc, gates, true)) + goto fail; + if (readl(cfg) != 4 || (readl(cfg + 4) & 3) || readl(cfg + 0x30)) + goto fail; + writel(readl(cfg + 0x30) | BIT(0), cfg + 0x30); + udelay(1); + writel(readl(cfg) | BIT(0), cfg); + if (readl_poll_timeout(cfg + 4, reg, reg & BIT(0), 1, ATC_TIMEOUT_US)) + goto fail; + writel(readl(cfg) | BIT(1), cfg); + if (readl_poll_timeout(cfg + 4, reg, reg & BIT(1), 1, ATC_TIMEOUT_US)) + goto fail; + writel(readl(cfg) & ~BIT(2), cfg); + udelay(1); + writel(readl(cfg) | BIT(3), cfg); + + atc_apply_tunables(atc, 0); + /* Pin D/F keeps the other PMA out of the DP path. */ + atc_update(atc, 0x4c, 0x1f, + atc->lanes == 2 ? (atc->swap ? 0x11 : 0x10) : 0x14); + atc_update(atc, 0x4c, 0x3ffe0, + atc->lanes == 2 || atc->swap ? 0x100 : 0x22000); + atc_apply_tunables(atc, 1); + atc_update(atc, ATC_CFG + 8, BIT(1), atc->swap ? BIT(1) : 0); + writel(readl(cfg) | BIT(4), cfg); + if ((readl(cfg) & 0x1f) != 0x1b) + goto fail; + /* AUX: release small and big sleep, then the AUX clamp. */ + atc_update(atc, ATC_AON + 0x24, BIT(8), BIT(8)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(6), BIT(6)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(10), 0); + udelay(1); + atc->active = true; + dev_info(disp->dev, "ATC%u: common PHY and AUX up from cold\n", atc->index); + /* + * The lanes start at HBR right away. From cold, AUX only works with + * the DP PLL and PMAs running (without them the firmware reports + * DEVICE_NOT_RESPONDING); the firmware switches to its rate afterwards. + */ + return atc_dp_start(disp, atc, 1); +fail: + dev_err(disp->dev, "ATC%u: cold start failed (gates %u, cfg %#x/%#x)\n", + atc->index, gates, + gates == ARRAY_SIZE(atc_ps_idle) ? readl(cfg) : 0, + gates == ARRAY_SIZE(atc_ps_idle) ? readl(cfg + 4) : 0); + return -EIO; +} + +/* Power the PHY down, dependencies included. */ +static int atc_deactivate(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + void __iomem *cfg = atc->base + ATC_CFG; + int ret = 0; + u32 reg; + + if (!atc->active) + return 0; + if (atc->link_rate && atc_dp_stop(disp, atc)) { + dev_err(disp->dev, "ATC%u: DP stop failed\n", atc->index); + return -EIO; + } + atc_route_stop(disp, atc); + atc_update(atc, ATC_AON + 0x24, BIT(10), BIT(10)); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(6), 0); + udelay(1); + atc_update(atc, ATC_AON + 0x24, BIT(8), 0); + udelay(1); + writel(readl(cfg) & ~BIT(4), cfg); + udelay(1); + writel(readl(cfg) & ~BIT(3), cfg); + writel(readl(cfg) | BIT(2), cfg); + writel(readl(cfg) & ~BIT(1), cfg); + if (readl_poll_timeout(cfg + 4, reg, !(reg & BIT(1)), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: big-sleep entry timeout\n", atc->index); + ret = -ETIMEDOUT; + } + writel(readl(cfg) & ~BIT(0), cfg); + if (readl_poll_timeout(cfg + 4, reg, !(reg & BIT(0)), 1, ATC_TIMEOUT_US)) { + dev_err(disp->dev, "ATC%u: small-sleep entry timeout\n", atc->index); + ret = -ETIMEDOUT; + } + writel(readl(cfg + 0x30) & ~BIT(0), cfg + 0x30); + atc->active = false; + /* + * Then the power dependencies it powered up: the next activation starts + * it cold. The USB controller of a port keeps the ones it uses. + */ + for (int i = ARRAY_SIZE(atc_ps_idle) - 1; i >= 0; i--) + if ((atc->owned & BIT(i)) && atc_gate(atc, i, false)) + ret = -ETIMEDOUT; + dev_info(disp->dev, "ATC%u: powered down: %d\n", atc->index, ret); + return ret; +} + +static int atc_set_link_rate(struct t8152_display *disp, u32 rate) +{ + struct t8152_atc_port *atc = atc_cur(disp); + u32 r; + int ret; + + /* The firmware drops the link (rate 0) before it retrains. */ + if (!rate || rate == atc->link_rate) + return 0; + for (r = 0; r < ARRAY_SIZE(atc_rates); r++) + if (atc_rates[r] == rate) + break; + if (r == ARRAY_SIZE(atc_rates) || !atc->active) + return -EINVAL; + dev_info(disp->dev, "ATC%u: link rate %#x, was %#x\n", atc->index, rate, + atc->link_rate); + if (atc->link_rate) { + ret = atc_dp_stop(disp, atc); + if (ret) + return ret; + } + return atc_dp_start(disp, atc, r); +} + +static int atc_set_route(struct t8152_display *disp, bool enable) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + if (!enable) + return atc_route_stop(disp, atc); + if (!atc->active) + return -ENODEV; + if (atc_route_start(disp, atc)) + return -EIO; + mdelay(5); + return 0; +} + +/* + * Lane drive presets, indexed by voltage * 4 + pre-emphasis; they serve + * every link rate. + */ +static const u32 atc_drive_presets[16] = { + 0x025, 0x420, 0x717, 0x90f, 0x019, 0x397, 0x78f, 0x025, + 0x011, 0x38f, 0x025, 0x025, 0x000, 0x025, 0x025, 0x025, +}; + +static int atc_set_drive(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count) +{ + struct t8152_atc_port *atc = atc_cur(disp); + u32 presets[4]; + + if (!count) + return 0; + if (count > atc->lanes || !atc->active || !atc->link_rate) + return -EINVAL; + /* Validate the entire request before changing any lane. */ + for (u32 i = 0; i < count; i++) { + u32 v = le32_to_cpu(settings[i].voltage); + u32 e = le32_to_cpu(settings[i].pre_emphasis); + + if (settings[i].format || v > 3 || e > 3 || v + e > 3) + return -EINVAL; + presets[i] = atc_drive_presets[v * 4 + e]; + } + for (u32 i = 0; i < count; i++) { + u32 pma = (i / 2) ^ !atc->swap; + /* Even DP lanes use the PMA RX pair, odd lanes its TX pair. */ + u32 offset = ((i & 1) ? 0x4eb0 : 0x8b10) + pma * 0x9000; + u32 preset = presets[i]; + u32 control = 1 | (((preset >> 13) & 0x3f) << 17) | + (((preset >> 7) & 0x3f) << 5); + + atc_update(atc, offset, 0x7e07ff, control); + atc_update(atc, offset - 0x14, 0x7f, (preset & 0x3f) | 0x40); + } + return 0; +} + +static void atc_set_orientation(struct t8152_display *disp, bool flipped) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + /* Applied by the next cold start; a running PHY keeps its own. */ + if (atc->active && atc->swap != flipped) + dev_warn(disp->dev, "ATC%u: orientation changed while active\n", + atc->index); + atc->swap = flipped; + atc->lanes = atc->next_lanes; +} + +static u32 atc_max_lane_count(struct t8152_display *disp) +{ + return atc_cur(disp)->lanes; +} + +/* + * The sink's EDID through the AP AUX controller aux0, which reaches the ATC + * through crossbar UFP aux0 like the DCP: the DCP's route comes down for + * the read, so this runs while the firmware does no AUX itself (display + * off, HPD not asserted yet). + */ +static int atc_read_edid(struct t8152_display *disp, u8 *buf, size_t size) +{ + struct t8152_atc_port *atc = atc_cur(disp); + bool was_started = atc->route_started; + int ret; + + if (!atc->active || !atc->aux->regs) + return -ENODEV; + mutex_lock(&atc_aux_lock); + /* The AUX output select of an ATC port: ATC instance * 3 + local DFP. */ + atc->aux->sel = atc->index * 3; + ret = t8152_aux_init(disp, atc->aux); + if (ret) + goto out; + atc_route_stop(disp, atc); + ret = atc_route_start_sel(disp, atc, ATC_SEL_AUX0); + if (!ret) + ret = t8152_aux_read_edid(disp, atc->aux, buf, size); + atc_route_stop(disp, atc); + if (was_started) + atc_route_start(disp, atc); +out: + mutex_unlock(&atc_aux_lock); + return ret; +} + +/* + * 1 with a sink on one of the ports: the current one first, then the + * others; select() switches to a port found that way. + */ +static int atc_detect(struct t8152_display *disp, bool *flipped) +{ + struct t8152_atc *atc = disp->phy_priv; + int ret = 0; + + mutex_lock(&atc_owner_lock); + atc->next = atc->cur; + /* Keep a monitor on its controller, including while userspace blanks it. */ + if (atc_owner[atc->cur->index] == disp->dev) { + ret = t8152_pd_sink(atc->cur->pd, flipped, &atc->cur->next_lanes); + if (ret > 0 && (atc->cur->swap != *flipped || + atc->cur->lanes != atc->cur->next_lanes)) + disp->hpd = 0; + if (ret) + goto out; + /* Unplug powers down in KMS; release on the next poll. */ + if (!atc->cur->active) + atc_owner[atc->cur->index] = NULL; + } + for (unsigned int i = 0; i < atc->nports; i++) { + struct t8152_atc_port *port = &atc->port[i]; + + if (atc_owner[port->index] || + t8152_pd_sink(port->pd, flipped, &port->next_lanes) <= 0) + continue; + atc_owner[port->index] = disp->dev; + atc->next = port; + disp->hpd = 0; + ret = 1; + break; + } +out: + mutex_unlock(&atc_owner_lock); + return ret; +} + +/* + * Drive the port a sink was found on: power the old one down and connect + * the DPTX port to the new one's display crossbar endpoint. + */ +static void atc_select(struct t8152_display *disp) +{ + struct t8152_atc *atc = disp->phy_priv; + struct t8152_atc_port *port = atc->next; + + if (!port || port == atc->cur) + return; + if (atc->cur->active && atc_deactivate(disp)) + return; + mutex_lock(&atc_owner_lock); + if (atc_owner[atc->cur->index] == disp->dev) + atc_owner[atc->cur->index] = NULL; + mutex_unlock(&atc_owner_lock); + dev_info(disp->dev, "USB-C display on ATC%u now, was ATC%u\n", + port->index, atc->cur->index); + atc->cur = port; + disp->pd = port->pd; + disp->dcp_output = port->dfp; +} + +/* + * Before the DCP drives another PHY (the HDMI port): give up the claim on a + * port that is powered down. False while the current port is still up. + */ +bool t8152_atc_release(struct t8152_display *disp) +{ + struct t8152_atc_port *atc = atc_cur(disp); + + if (atc->active) + return false; + guard(mutex)(&atc_owner_lock); + if (atc_owner[atc->index] == disp->dev) + atc_owner[atc->index] = NULL; + return true; +} + +static const struct t8152_phy_ops atc_ops = { + .activate = atc_activate, + .deactivate = atc_deactivate, + .set_link_rate = atc_set_link_rate, + .max_lane_count = atc_max_lane_count, + .set_drive = atc_set_drive, + .set_route = atc_set_route, + .set_orientation = atc_set_orientation, + .read_edid = atc_read_edid, + .detect = atc_detect, + .select = atc_select, + .max_link_rate = LINK_RATE_HBR2, +}; + +/* PMGR registers, inside blocks their power domain driver has claimed. */ +static void __iomem *atc_map(struct t8152_display *disp, struct device_node *np, + const char *name) +{ + int i = of_property_match_string(np, "reg-names", name); + struct resource res; + + if (i < 0 || of_address_to_resource(np, i, &res)) + return NULL; + return devm_ioremap(disp->dev, res.start, resource_size(&res)); +} + +static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, + struct device_node *np, void __iomem *dp_clock) +{ + struct t8152_atc_port *port = &atc->port[atc->nports]; + u32 cfg, r; + + port->base = atc_map(disp, np, "atc"); + port->ps = atc_map(disp, np, "atc-ps"); + port->psd = atc_map(disp, np, "atc-psd"); + if (!port->base || !port->ps || !port->psd) + return -ENOMEM; + port->pd = t8152_pd_get(np); + if (IS_ERR_OR_NULL(port->pd)) + return port->pd ? PTR_ERR(port->pd) : -ENODEV; + /* The node without ports is ATC3's (J873g back-right). */ + port->dfp = 3; + of_property_read_u32(np, "apple,dfp-endpoint", &port->dfp); + port->index = port->dfp; + port->lanes = 4; + port->next_lanes = 4; + if (port->index >= 4) + return -EINVAL; + port->dp_clock = dp_clock + port->index * 8; + port->aux = &atc->aux; + port->tunable[0] = of_get_property(np, "apple,tunable-pre", + &port->tunable_len[0]); + port->tunable[1] = of_get_property(np, "apple,tunable-post", + &port->tunable_len[1]); + port->tunable_len[0] /= sizeof(__be32); + port->tunable_len[1] /= sizeof(__be32); + atc->nports++; + + /* + * The PHY block hangs the bus while it is power-gated: look at it only + * with its DP dependencies and the common PSD up. + */ + if ((readl(port->ps) & 0xf0) != 0xf0 || + (readl(port->psd + ATC_PSD_STATE) & 7)) { + dev_info(disp->dev, "ATC%u: powered down\n", port->index); + return 0; + } + /* A different DCP may already be driving this port. */ + if (atc_owner[port->index] || + ((readl(port->base + ATC_XBAR + 0x44) >> 20) & 0xf) != + disp->dp_source * 2) + return 0; + /* Common block out of reset and AUX up, as the bootloader leaves it. */ + cfg = readl(port->base + ATC_CFG); + port->active = (cfg & 0x1f) == 0x1b; + if ((readl(port->base + 0x4c) & 0x1f) == 0x10 || + (readl(port->base + 0x4c) & 0x1f) == 0x11) { + port->lanes = 2; + port->next_lanes = 2; + } + port->swap = !!(readl(port->base + ATC_CFG + 8) & BIT(1)); + port->route_started = + (readl(port->base + ATC_XBAR) & BIT(disp->dp_source * 2)) && + (readl(port->base + ATC_XBAR + 0x3c) & BIT(disp->dp_source * 2)); + r = (readl(port->base + 0x2000) >> 19) & 7; + if (port->active && (readl(port->base + 0x2040) & BIT(16)) && + r < ARRAY_SIZE(atc_rates)) + port->link_rate = atc_rates[r]; + /* The bootloader's display: its dependencies are the display's. */ + if (port->active) + port->owned = GENMASK(ARRAY_SIZE(atc_ps_idle) - 1, 0); + dev_info(disp->dev, + "ATC%u: inherited state: active %d, rate %#x, route %d, reversed %d (cfg %#x)\n", + port->index, port->active, port->link_rate, port->route_started, + port->swap, cfg); + return 0; +} + +int t8152_atc_init(struct t8152_display *disp) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(disp->dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: disp->dev->of_node; + struct resource clock_res; + void __iomem *dp_clock; + struct t8152_atc *atc; + int ret; + + atc = devm_kzalloc(disp->dev, sizeof(*atc), GFP_KERNEL); + if (!atc) + return -ENOMEM; + ret = of_property_match_string(np, "reg-names", "dp-clock"); + if (ret < 0 || of_address_to_resource(np, ret, &clock_res)) + return -EINVAL; + /* Older J873 DTs describe ATC3's divider alone; each ATC has its own. */ + if (resource_size(&clock_res) == 4 && clock_res.start == 0x30002005cULL) + clock_res.start -= 3 * 8; + if (resource_size(&clock_res) < 28) + return -EINVAL; + dp_clock = devm_ioremap(disp->dev, clock_res.start, resource_size(&clock_res)); + if (!dp_clock) + return -ENOMEM; + /* Shared AUX0 is serialized by atc_aux_lock. */ + atc->aux.regs = atc_map(disp, np, "aux"); + atc->aux.ps = atc_map(disp, np, "aux-ps"); + if (!atc->aux.ps) + atc->aux.regs = NULL; + + guard(mutex)(&atc_owner_lock); + /* One child per USB-C port, or the node itself for ATC3 alone. */ + for_each_child_of_node_scoped(np, child) { + if (!of_property_present(child, "apple,dfp-endpoint")) + continue; + if (atc->nports == ARRAY_SIZE(atc->port)) + break; + ret = atc_port_init(disp, atc, child, dp_clock); + if (ret) + return ret; + } + if (!atc->nports) { + ret = atc_port_init(disp, atc, np, dp_clock); + if (ret) + return ret; + } + + /* Only adopt a bootloader route belonging to this DCP. */ + atc->cur = &atc->port[0]; + for (unsigned int i = 0; i < atc->nports; i++) { + if (atc->port[i].active) { + atc->cur = &atc->port[i]; + atc_owner[atc->cur->index] = disp->dev; + break; + } + } + atc->next = atc->cur; + disp->phy = &atc_ops; + disp->phy_priv = atc; + disp->pd = atc->cur->pd; + disp->dcp_output = atc->cur->dfp; + dev_info(disp->dev, "USB-C display on ATC%u (%u ports)\n", atc->cur->index, + atc->nports); + return 0; +} diff --git a/drivers/gpu/drm/apple/t8152_aux.c b/drivers/gpu/drm/apple/t8152_aux.c new file mode 100644 index 00000000000000..8e2dbd2d2bd0c2 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_aux.c @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The T8152 AP's DisplayPort AUX controllers aux0 and aux1: Analogix-derived + * DPTX cores with their own request framing. They attach to the display + * crossbar as UFP endpoints 5 and 6; the PHY code routes one to its port + * for the time of a read. Used for the sink's EDID, which the DCP firmware + * does not hand out on its iBoot interface. + * + * Interim, until the DCP's DPAV service or a DRM DP AUX channel provides the + * EDID on T8152. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "t8152_display.h" + +#define AUX_TIMEOUT_US 10000 +#define AUX_SEL 0x000 /* output: 9 crossbar UFP aux0, 0x10 lpdptx PHY */ +#define AUX_FUNC_EN_2 0x01c +#define AUX_FUNC_EN_N BIT(2) +#define AUX_HW_RETRY 0x390 +#define AUX_INT_STA 0x3dc +#define AUX_REPLY BIT(1) +#define AUX_ERROR BIT(0) +#define AUX_CH_STA 0x780 +#define AUX_DEFER_CTL 0x788 +#define AUX_RX_COMM 0x78c +#define AUX_BUF_CTL 0x790 +#define AUX_BUF_CLR BIT(9) +#define AUX_BUF_COUNT GENMASK(8, 0) +#define AUX_LEN 0x794 +#define AUX_ADDR_7_0 0x798 +#define AUX_ADDR_15_8 0x79c +#define AUX_CMD_ADDR 0x7a0 /* request in [7:4], address [19:16] */ +#define AUX_CTL 0x7a4 +#define AUX_GO BIT(0) +#define AUX_ADDR_ONLY BIT(1) +#define AUX_DATA 0xc00 /* one byte per word */ +#define AUX_MAX 16 + +#define AUX_NATIVE_WRITE 0x80 +#define AUX_I2C_WRITE 0x00 +#define AUX_I2C_READ 0x10 +#define AUX_I2C_MOT 0x40 +#define DDC_ADDR 0x50 +#define DPCD_SET_POWER 0x600 +#define DP_SET_POWER_D0 1 + +static void aux_update(void __iomem *reg, u32 mask, u32 value) +{ + writel((readl(reg) & ~mask) | value, reg); +} + +int t8152_aux_init(struct t8152_display *disp, struct t8152_aux *aux) +{ + u32 reg; + + /* PMGR power state of the controller */ + aux_update(aux->ps, 0xf, 0xf); + if (readl_poll_timeout(aux->ps, reg, ((reg >> 4) & 0xf) == 0xf, 1, + AUX_TIMEOUT_US)) { + dev_err(disp->dev, "AUX: controller does not power up\n"); + return -ETIMEDOUT; + } + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + aux_update(aux->regs + AUX_FUNC_EN_2, AUX_FUNC_EN_N, AUX_FUNC_EN_N); + usleep_range(10, 20); + aux_update(aux->regs + AUX_FUNC_EN_2, AUX_FUNC_EN_N, 0); + /* + * Bits 21:8 of AUX_HW_RETRY are a 14-bit reply timeout, not Analogix's + * three-bit expected-delay field: the value 3 let native reads pass + * but timed out the EDID through a USB-C to HDMI adapter. 3200, with + * a retry interval of 3. + */ + writel((3200 << 8) | (3 << 3), aux->regs + AUX_HW_RETRY); + writel(BIT(7) | 1, aux->regs + AUX_DEFER_CTL); + aux_update(aux->regs + AUX_SEL, 0x3f, aux->sel); + return 0; +} + +/* One AUX request of up to 16 bytes; returns the bytes transferred. */ +static int aux_xfer(struct t8152_aux *aux, u32 cmd, u32 addr, u8 *buf, + u32 len, bool write) +{ + u32 sta, n; + int i; + + for (int tries = 0; tries < 7; tries++) { + writel(AUX_BUF_CLR, aux->regs + AUX_BUF_CTL); + writel(len ? len - 1 : 0, aux->regs + AUX_LEN); + writel(addr & 0xff, aux->regs + AUX_ADDR_7_0); + writel((addr >> 8) & 0xff, aux->regs + AUX_ADDR_15_8); + writel((cmd & 0xf0) | ((addr >> 16) & 0xf), aux->regs + AUX_CMD_ADDR); + aux_update(aux->regs + AUX_CTL, AUX_ADDR_ONLY, len ? 0 : AUX_ADDR_ONLY); + for (i = 0; write && i < len; i++) + writel(buf[i], aux->regs + AUX_DATA + 4 * i); + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + aux_update(aux->regs + AUX_CTL, AUX_GO, AUX_GO); + if (readl_poll_timeout(aux->regs + AUX_INT_STA, sta, + sta & (AUX_REPLY | AUX_ERROR), 10, 20000)) + return -ETIMEDOUT; + writel(AUX_REPLY | AUX_ERROR, aux->regs + AUX_INT_STA); + if ((sta & AUX_ERROR) || (readl(aux->regs + AUX_CH_STA) & 0xf)) + return -EIO; + /* [3:2] I2C and [1:0] AUX reply: 0 ACK, 1 NACK, 2 DEFER */ + sta = readl(aux->regs + AUX_RX_COMM); + if (sta & 0x5) + return -ENXIO; + if (sta & 0xa) { + usleep_range(500, 1000); + continue; + } + if (write) + return len; + n = min(readl(aux->regs + AUX_BUF_CTL) & AUX_BUF_COUNT, len); + for (i = 0; i < n; i++) + buf[i] = readl(aux->regs + AUX_DATA + 4 * i); + return n; + } + return -EBUSY; +} + +/* DDC over I2C-over-AUX: offset 0, then 16-byte reads up to @size. */ +static int aux_ddc_read(struct t8152_aux *aux, u8 *buf, size_t size) +{ + u8 offset = 0; + size_t done = 0; + int ret; + + ret = aux_xfer(aux, AUX_I2C_WRITE | AUX_I2C_MOT, DDC_ADDR, &offset, 1, true); + while (ret >= 0 && done < size) { + ret = aux_xfer(aux, AUX_I2C_READ | AUX_I2C_MOT, DDC_ADDR, + buf + done, min_t(size_t, size - done, AUX_MAX), + false); + if (ret > 0) + done += ret; + else if (!ret) + ret = -EIO; + } + /* End the I2C transaction with an address-only read without MOT. */ + aux_xfer(aux, AUX_I2C_READ, DDC_ADDR, NULL, 0, false); + return ret < 0 ? ret : done; +} + +/* + * The EDID over DDC, the base block and its extensions; the sink answers + * AUX only some time after the path is up, and a sink just plugged in a + * little later still. + */ +int t8152_aux_read_edid(struct t8152_display *disp, struct t8152_aux *aux, + u8 *buf, size_t size) +{ + u8 d0 = DP_SET_POWER_D0; + int ret = -EIO, ext; + + for (int i = 0; i < 30 && (ret == -EIO || ret == -ETIMEDOUT); i++) { + msleep(i ? 100 : 20); + /* + * A sink left in D3 (after an unplug) NACKs DDC: wake it + * first, as the DP spec asks before AUX use. + */ + ret = aux_xfer(aux, AUX_NATIVE_WRITE, DPCD_SET_POWER, &d0, 1, true); + if (ret < 0) + continue; + usleep_range(1000, 2000); + ret = aux_ddc_read(aux, buf, min_t(size_t, size, EDID_LENGTH)); + } + if (ret != EDID_LENGTH) + return ret < 0 ? ret : -EIO; + ext = min_t(size_t, buf[0x7e], size / EDID_LENGTH - 1); + return ext ? aux_ddc_read(aux, buf, (1 + ext) * EDID_LENGTH) : ret; +} + +/* + * The controller named by np's "aux" and "aux-ps" regs (np need not be the + * DCP's own node); the PMGR register is mapped without claiming it. + */ +void t8152_aux_probe(struct t8152_display *disp, struct t8152_aux *aux, + u32 sel, struct device_node *np) +{ + int ps = of_property_match_string(np, "reg-names", "aux-ps"); + int regs = of_property_match_string(np, "reg-names", "aux"); + struct resource res; + + aux->sel = sel; + if (ps < 0 || regs < 0 || of_address_to_resource(np, ps, &res)) + return; + aux->ps = devm_ioremap(disp->dev, res.start, resource_size(&res)); + aux->regs = devm_of_iomap(disp->dev, np, regs, NULL); + if (IS_ERR(aux->regs) || !aux->ps) + aux->regs = NULL; +} diff --git a/drivers/gpu/drm/apple/t8152_display.h b/drivers/gpu/drm/apple/t8152_display.h new file mode 100644 index 00000000000000..b26baf6b04924f --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_display.h @@ -0,0 +1,140 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * The T8152 (Mac mini J873g) DisplayPort hardware behind a DCP's DPTX port + * that no subsystem driver covers yet: the ATC PHYs' DisplayPort lanes and + * their display crossbar route (t8152_atc.c), the HDMI port's dedicated + * DisplayPort PHY and PS190 converter (t8152_hdmi.c), the AP's DisplayPort + * AUX controllers that read the sink's EDID (t8152_aux.c), the rear USB-C + * ports' ACE3 PD controllers (t8152_pd.c), and the DPTX port service the + * DCP firmware calls into for the PHY (t8152_dptx.c). + * + * Interim: the ATC DisplayPort mode moves to drivers/phy/apple/atc.c, the + * ACE3 controllers to tipd, and the choice of port with DP alt mode to the + * Type-C route layer of dcp-fabric.c, each in its own change. Until then + * these files program the registers themselves, for the iBoot interface + * DCPs of iomfb_iboot.c alone. + */ +#ifndef __APPLE_T8152_DISPLAY_H__ +#define __APPLE_T8152_DISPLAY_H__ + +#include + +struct apple_dcp; +struct apple_epic_service_ops; +struct device; +struct device_node; +struct gpio_desc; +struct spmi_device; +struct t8152_display; +struct t8152_hdmi; + +/* SET_DRIVE_SETTINGS and GET_DRIVE_SETTINGS records, one per lane */ +struct t8152_drive_settings { + __le32 format; + __le32 voltage; + __le32 pre_emphasis; +} __packed; + +/* The PHY behind the DCP's DPTX port; link rates in DPCD units. */ +struct t8152_phy_ops { + int (*activate)(struct t8152_display *disp); + int (*deactivate)(struct t8152_display *disp); + int (*set_link_rate)(struct t8152_display *disp, u32 rate); + /* optional */ + int (*set_lane_count)(struct t8152_display *disp, u32 lanes); + u32 (*max_lane_count)(struct t8152_display *disp); + int (*set_drive)(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count); + int (*set_route)(struct t8152_display *disp, bool enable); + /* optional: plug orientation for the next activation */ + void (*set_orientation)(struct t8152_display *disp, bool flipped); + /* optional: the sink's EDID, returns its length */ + int (*read_edid)(struct t8152_display *disp, u8 *buf, size_t size); + /* + * optional: 1 with a sink on one of the PHY's ports, 0 without; the + * port it found is taken by select() in the plug path + */ + int (*detect)(struct t8152_display *disp, bool *flipped); + void (*select)(struct t8152_display *disp); + u32 max_link_rate; +}; + +/* The DPTX port state the firmware's calls set and read back. */ +struct t8152_port { + u32 link_rate; + u32 lanes; + /* the drive settings the firmware set last, for GET_DRIVE_SETTINGS */ + struct t8152_drive_settings drive[4]; + u32 drive_count; +}; + +/* An AP DisplayPort AUX controller, and its output select */ +struct t8152_aux { + void __iomem *regs; + void __iomem *ps; + u32 sel; +}; + +/* The DisplayPort side of one DCP */ +struct t8152_display { + struct apple_dcp *dcp; + struct device *dev; + /* display crossbar UFP endpoint of the DCP; DPTX port 0 */ + u32 dp_source; + /* display crossbar DFP endpoint the DCP drives */ + u32 dcp_output; + u32 die; + + const struct t8152_phy_ops *phy; + void *phy_priv; + /* optional sink HPD line (HDMI), polled; the last level seen */ + struct gpio_desc *hpd_gpio; + int hpd; + /* USB-C: the PD controller of the port in use */ + struct spmi_device *pd; + /* HDMI PHY: DCPEXT0's, or the main DCP's on an HDMI-only boot */ + bool hdmi; + /* + * The HDMI port of the shared ports when the bootloader brought HDMI + * up on no DCP: taken while this DCP drives no USB-C display, with + * the USB-C PHY kept to switch back. + */ + struct t8152_hdmi *hdmi_port; + bool on_hdmi; + const struct t8152_phy_ops *usbc_phy; + void *usbc_phy_priv; + u32 usbc_output; + + struct t8152_port port[2]; +}; + +/* t8152_atc.c */ +int t8152_atc_init(struct t8152_display *disp); +bool t8152_atc_release(struct t8152_display *disp); + +/* t8152_hdmi.c */ +struct device_node *t8152_hdmi_node(void); +int t8152_hdmi_source(struct device_node *np); +int t8152_hdmi_init(struct t8152_display *disp, struct device_node *np); +int t8152_hdmi_port_init(struct t8152_display *disp, struct device_node *np); +void t8152_hdmi_port_poll(struct t8152_display *disp); + +/* t8152_aux.c */ +void t8152_aux_probe(struct t8152_display *disp, struct t8152_aux *aux, + u32 sel, struct device_node *np); +int t8152_aux_init(struct t8152_display *disp, struct t8152_aux *aux); +int t8152_aux_read_edid(struct t8152_display *disp, struct t8152_aux *aux, + u8 *buf, size_t size); + +/* t8152_pd.c */ +struct spmi_device *t8152_pd_get(struct device_node *np); +int t8152_pd_sink(struct spmi_device *pd, bool *flipped, u32 *lanes); +int t8152_pd_reconnect(struct t8152_display *disp); + +/* t8152_dptx.c */ +extern const struct apple_epic_service_ops t8152_dptx_port_ops; +int t8152_dptx_connect(struct t8152_display *disp, unsigned int port); +int t8152_dptx_disconnect(struct t8152_display *disp, unsigned int port); +int t8152_dptx_set_hpd(struct t8152_display *disp, unsigned int port, bool hpd); + +#endif diff --git a/drivers/gpu/drm/apple/t8152_dptx.c b/drivers/gpu/drm/apple/t8152_dptx.c new file mode 100644 index 00000000000000..14da33f3c7c3ee --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_dptx.c @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The DPTX port service of a T8152 iBoot interface DCP: the calls the + * firmware makes into the AP for the PHY behind its DPTX port, and the + * port's release and HPD calls. + * + * dptxep.c serves the same calls for the PHYs of the PHY framework, the + * display crossbar mux and Thunderbolt tunnels. The T8152 PHYs are + * programmed by t8152_atc.c and t8152_hdmi.c instead: their link rate, + * lanes and drive settings are applied here, and the drive settings are + * read back as they were set. The port's connect and display request are + * dptxep.c's. Interim, until the T8152 PHYs are PHY framework providers + * and dptxep.c can host this service. + */ + +#include +#include +#include + +#include "afk.h" +#include "dcp-internal.h" +#include "dptx-service.h" +#include "dptxep.h" +#include "t8152_display.h" + +/* IOReturn values the firmware takes as call status */ +#define KIO_RETURN_ERROR 0xe00002bcU +#define KIO_RETURN_BAD_ARG 0xe00002c2U +#define KIO_RETURN_UNSUPPORTED 0xe00002c7U +#define KIO_RETURN_NOT_READY 0xe00002d8U + +static bool dptx_needs_port(u32 command) +{ + switch (command) { + case DPTX_APCALL_ACTIVATE: + case DPTX_APCALL_DEACTIVATE: + case DPTX_APCALL_WILL_CHANGE_LINKG_CONFIG: + case DPTX_APCALL_DID_CHANGE_LINK_CONFIG: + case DPTX_APCALL_SET_LINK_RATE: + case DPTX_APCALL_SET_DOWN_SPREAD: + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_SET_DRIVE_SETTINGS: + case DPTX_APCALL_GET_LINK_RATE: + case DPTX_APCALL_GET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_GET_DRIVE_SETTINGS: + return true; + default: + return false; + } +} + +/* + * One call; the IOReturn status. Requests carry their argument, replies + * their value, at offset 16. @reply holds a copy of the request. + */ +static u32 dptx_apcall(struct t8152_display *disp, struct t8152_port *port, + u16 group, u32 command, const void *data, size_t data_size, + void *reply, size_t reply_size) +{ + const struct t8152_phy_ops *phy = disp->phy; + u64 value; + u32 arg; + + if (group && !(group == 1 && (command == DPTX_APCALL_SET_DRIVE_SETTINGS || + command == DPTX_APCALL_GET_DRIVE_SETTINGS))) + return KIO_RETURN_UNSUPPORTED; + + if ((!port || !phy) && dptx_needs_port(command)) + return KIO_RETURN_NOT_READY; + + switch (command) { + case DPTX_APCALL_ACTIVATE: + if (phy->activate(disp)) + return KIO_RETURN_ERROR; + port->link_rate = LINK_RATE_HBR; + return 0; + case DPTX_APCALL_DEACTIVATE: + if (phy->deactivate(disp)) + return KIO_RETURN_ERROR; + port->link_rate = 0; + return 0; + case DPTX_APCALL_WILL_CHANGE_LINKG_CONFIG: + case DPTX_APCALL_DID_CHANGE_LINK_CONFIG: + return phy->set_route(disp, command == + DPTX_APCALL_DID_CHANGE_LINK_CONFIG) ? + KIO_RETURN_ERROR : 0; + case DPTX_APCALL_GET_MAX_LINK_RATE: + value = phy ? phy->max_link_rate : LINK_RATE_HBR; + break; + case DPTX_APCALL_GET_LINK_RATE: + value = port->link_rate; + break; + case DPTX_APCALL_SET_LINK_RATE: + if (data_size < 17) + return KIO_RETURN_BAD_ARG; + arg = ((const u8 *)data)[16]; + if (arg > phy->max_link_rate) + return KIO_RETURN_UNSUPPORTED; + if (phy->set_link_rate(disp, arg)) + return KIO_RETURN_ERROR; + port->link_rate = arg; + return 0; + case DPTX_APCALL_GET_MAX_LANE_COUNT: + value = phy && phy->max_lane_count ? phy->max_lane_count(disp) : 4; + break; + case DPTX_APCALL_GET_ACTIVE_LANE_COUNT: + value = port->lanes; + break; + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + if (data_size < 20) + return KIO_RETURN_BAD_ARG; + arg = get_unaligned_le32(data + 16); + if (arg == 3 || arg > 4) + return KIO_RETURN_BAD_ARG; + dev_info(disp->dev, "DPTX: %u active lanes\n", arg); + if (phy->set_lane_count && phy->set_lane_count(disp, arg)) + return KIO_RETURN_ERROR; + port->lanes = arg; + return 0; + case DPTX_APCALL_GET_MAX_DRIVE_SETTINGS: { + const struct t8152_drive_settings maximum = { + 0, cpu_to_le32(3), cpu_to_le32(3) + }; + + if (reply_size < 16 + sizeof(maximum)) + return KIO_RETURN_BAD_ARG; + memcpy(reply + 16, &maximum, sizeof(maximum)); + return 0; + } + case DPTX_APCALL_SET_DRIVE_SETTINGS: { + struct t8152_drive_settings settings[4]; + + if (group != 1) + return KIO_RETURN_UNSUPPORTED; + if (data_size < 32) + return KIO_RETURN_BAD_ARG; + arg = get_unaligned_le32(data + 16); + if (arg > 4 || data_size < 32 + arg * sizeof(settings[0])) + return KIO_RETURN_BAD_ARG; + memcpy(settings, data + 32, arg * sizeof(settings[0])); + if (phy->set_drive(disp, settings, arg)) + return KIO_RETURN_ERROR; + memcpy(port->drive, settings, arg * sizeof(settings[0])); + port->drive_count = arg; + return 0; + } + case DPTX_APCALL_GET_DRIVE_SETTINGS: + /* + * The firmware reads back what it set during link training; an + * unsupported reply here was followed by a firmware crash. + * Same layout as SET: count at 16, settings from 32. + */ + if (group != 1) + return KIO_RETURN_UNSUPPORTED; + if (reply_size < 32 + port->drive_count * sizeof(port->drive[0])) + return KIO_RETURN_BAD_ARG; + put_unaligned_le32(port->drive_count, reply + 16); + memcpy(reply + 32, port->drive, + port->drive_count * sizeof(port->drive[0])); + return 0; + case DPTX_APCALL_SET_DOWN_SPREAD: + if (data_size < 17) + return KIO_RETURN_BAD_ARG; + /* The link is set up with downspread disabled. */ + return ((const u8 *)data)[16] ? KIO_RETURN_UNSUPPORTED : 0; + case DPTX_APCALL_GET_SUPPORTS_DOWN_SPREAD: + case DPTX_APCALL_GET_DOWN_SPREAD: + case DPTX_APCALL_GET_SUPPORTS_LANE_MAPPING: + case DPTX_APCALL_GET_VIRTUAL_DEVICE_MODE: + value = 0; + break; + case DPTX_APCALL_GET_SUPPORTS_HPD: + value = 1; + break; + case DPTX_APCALL_INACTIVE_SINK_DETECTED: + case DPTX_APCALL_DEVICE_NOT_RESPONDING: + case DPTX_APCALL_DEVICE_BUSY_TIMEOUT: + case DPTX_APCALL_DEVICE_NOT_STARTED: + /* Link fault reports: acknowledged with a zero status. */ + dev_info(disp->dev, "DPTX: firmware reports link fault %u\n", + command); + return 0; + case DPTX_APCALL_SET_TILED_DISPLAY_HINTS: + /* Acknowledged, the hints unused. */ + return 0; + default: + dev_info(disp->dev, "DPTX: unsupported call %u\n", command); + return KIO_RETURN_UNSUPPORTED; + } + + if (reply_size < 16 + sizeof(value)) + return KIO_RETURN_BAD_ARG; + put_unaligned_le64(value, reply + 16); + return 0; +} + +/* + * The reply starts as a copy of the request and carries the call's status + * in its first word; the transport status is always success. + */ +static int t8152_dptx_call(struct apple_epic_service *service, u16 group, + u32 command, const void *data, size_t size, + void *reply, size_t room) +{ + struct apple_dcp *dcp = service->ep->dcp; + struct dptx_port *dptx = service->cookie; + struct t8152_display *disp = READ_ONCE(dcp->t8152); + u32 status; + + dev_dbg(dcp->dev, "DPTX: port %d group %u command %u size %zu\n", + dptx ? (int)dptx->unit : -1, group, command, size); + memcpy(reply, data, min(room, size)); + if (disp) + status = dptx_apcall(disp, dptx ? &disp->port[dptx->unit] : NULL, + group, command, data, size, reply, room); + else + status = KIO_RETURN_NOT_READY; + if (status) + dev_dbg(dcp->dev, "DPTX: group %u command %u -> %#x\n", group, + command, status); + put_unaligned_le32(status, reply); + return 0; +} + +/* + * The ports in the order the firmware announces them. A further service is + * opened as well, without a port. + */ +static int t8152_dptx_prepare(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct apple_dcp *dcp = service->ep->dcp; + + for (unsigned int i = 0; i < ARRAY_SIZE(dcp->dptxport); i++) + if (!dcp->dptxport[i].service) + return dptx_service_bind(service, &dcp->dptxport[i], i); + return 0; +} + +static void t8152_dptx_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + if (service->cookie) + dptx_service_publish(service); +} + +/* Bound to every service of the DPTX endpoint (afk unmatched_ops). */ +const struct apple_epic_service_ops t8152_dptx_port_ops = { + .name = "dcpdptx-port", + .prepare = t8152_dptx_prepare, + .init = t8152_dptx_init, + .call_v2 = t8152_dptx_call, +}; + +static struct apple_epic_service *t8152_dptx_service(struct t8152_display *disp, + unsigned int port) +{ + struct dptx_port *dptx = &disp->dcp->dptxport[port]; + + return dptx_service_available(dptx) ? dptx->service : NULL; +} + +/* Connect the port to the PHY the DCP drives and request the display. */ +int t8152_dptx_connect(struct t8152_display *disp, unsigned int port) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + int ret; + + if (!service) + return -ENODEV; + ret = dptxport_connect(service, 0, disp->dcp_output, disp->die, true); + if (!ret) + ret = dptxport_request_display(service); + return ret; +} + +/* + * HPD as the port reports it to the firmware (group 8, command 8): the + * reply's first word is the call's status. + */ +int t8152_dptx_set_hpd(struct t8152_display *disp, unsigned int port, bool hpd) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + struct { + u8 pad[16]; + __le32 hpd; + } __packed cmd = { .hpd = cpu_to_le32(hpd) }, resp = {}; + size_t received; + int ret; + + if (!service) + return -ENODEV; + ret = afk_service_call_len(service, 8, 8, &cmd, sizeof(cmd), 12, &resp, + sizeof(resp), 12, &received); + if (ret) + return ret; + return get_unaligned_le32(resp.pad) ? -EIO : 0; +} + +/* Release the display (group 8, command 7), then HPD low. */ +int t8152_dptx_disconnect(struct t8152_display *disp, unsigned int port) +{ + struct apple_epic_service *service = t8152_dptx_service(disp, port); + __le32 status = 0; + size_t received; + int ret; + + if (!service) + return -ENODEV; + ret = afk_service_call_len(service, 8, 7, NULL, 0, 16, &status, + sizeof(status), 12, &received); + if (ret || status) + return ret ?: -EIO; + return t8152_dptx_set_hpd(disp, port, false); +} diff --git a/drivers/gpu/drm/apple/t8152_hdmi.c b/drivers/gpu/drm/apple/t8152_hdmi.c new file mode 100644 index 00000000000000..5b11879b1724b4 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_hdmi.c @@ -0,0 +1,669 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The J873g HDMI port: the T8152's dedicated DisplayPort PHY in display + * crossbar 0's lpdptx slot, converted by a PS190. + * + * Interim, until drivers/phy/apple/dptx.c has a T8152 type (its lanes are + * 0x2800 apart from 0x4500) and the PS190's power through the SMC is + * described as a supply: this programs the PHY and powers the converter + * itself. + * + * When the bootloader brought HDMI up, this keeps its setup and reprograms + * what a link training changes: the PLL for a new link rate and the active + * lanes. Drive settings are only recorded, and there is no per-link route. + * When it did not (no HDMI monitor at boot, or a USB-C display on the main + * DCP), the HDMI port joins the shared USB-C ports: a DCP without a USB-C + * display takes it on a plug and starts the PHY and the PS190 from cold. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dptxep.h" +#include "t8152_display.h" + +#define HDMI_LANES 4 +#define HDMI_LANE0 0x4500 +#define HDMI_LANE_STRIDE 0x2800 + +struct t8152_hdmi { + void __iomem *core; + void __iomem *apb; + /* AP DisplayPort AUX controller aux1, for the EDID */ + struct t8152_aux aux; + /* The cold start of the HDMI port taken from the shared ports: */ + void __iomem *ps; /* PMGR power state of the PHY */ + void __iomem *psd; /* PMGR PSD service of the PHY */ + struct gpio_desc *hpd; + struct device_node *smc_np; + const __be32 *pcon, *tunable; + int pcon_len, tunable_len; + bool active; +}; + +/* + * The DCP driving the HDMI port taken from the shared ports, if any, and its + * HPD line, requested once for all the DCPs that may take the port. + */ +static DEFINE_MUTEX(hdmi_port_lock); +static struct device *hdmi_port_owner; +static struct gpio_desc *hdmi_port_hpd; +static unsigned int hdmi_port_users; + +#define HDMI_PS_TARGET GENMASK(3, 0) +#define HDMI_PS_ACTUAL GENMASK(7, 4) +#define HDMI_PS_FLAGS GENMASK(9, 8) /* write-one-to-clear */ +#define HDMI_PSD_STATE 0x80 +#define HDMI_PSD_TARGET 0x90 +#define HDMI_POWER_TIMEOUT_US 100000 + +/* APB 0x10 bits 3:0: the crossbar UFP feeding the PHY */ +#define HDMI_SOURCE_SELECT 0x10 +#define HDMI_SOURCE_AUX1 6 /* UFP endpoint of the aux1 controller */ + +static void hdmi_set_bits(struct t8152_hdmi *hdmi, u32 offset, u32 shift, + u32 mask, u32 value) +{ + u32 reg = readl(hdmi->core + offset); + + writel((reg & ~mask) | (value << shift), hdmi->core + offset); +} + +static void hdmi_apb_update(struct t8152_hdmi *hdmi, u32 offset, u32 mask, + u32 value) +{ + u32 reg = readl(hdmi->apb + offset); + + writel((reg & ~mask) | value, hdmi->apb + offset); +} + +/* The PLL configuration words for each link rate (DPCD units). */ +static const struct { + u32 rate; + u32 w[22]; +} hdmi_pll_configs[] = { + { LINK_RATE_RBR, + { 1, 0x21c, 0, 0, 1, 0x13, 1, 0, 0, 0x1a, 1, 0x3c, 2, 1, 0, 0, 1, 0, + 0, 0, 1, 3 } }, + { LINK_RATE_HBR, + { 1, 0x1c2, 0x1fff, 0x3ffe, 1, 0x13, 1, 0, 0, 0x1a, 1, 0x32, 2, 1, 0, + 0, 1, 0, 0, 0, 1, 3 } }, + { LINK_RATE_HBR2, + { 0, 0x1c2, 0x1fff, 0x3ffe, 1, 9, 1, 0, 0, 0x1a, 1, 0x32, 1, 0, 0, 1, + 0, 0, 0, 1, 1, 3 } }, + { LINK_RATE_HBR3, + { 0, 0x2a3, 0x2ffd, 0x3ffc, 1, 9, 1, 0, 0, 0x1a, 1, 0x5a, 1, 0, 0, 1, + 0, 0, 0, 1, 1, 3 } }, +}; + +/* A PLL command: command in 0x408[2:0], request bit 3, acknowledge bit 19. */ +static int hdmi_pll_command(struct t8152_display *disp, struct t8152_hdmi *hdmi, + u32 command) +{ + int i; + + hdmi_set_bits(hdmi, 0x408, 6, 0x40, 1); + hdmi_set_bits(hdmi, 0x408, 0, 0x7, command); + hdmi_set_bits(hdmi, 0x408, 3, 0x8, 1); + for (i = 0; i < 10; i++) { + usleep_range(16, 32); + if (readl(hdmi->core + 0x408) & BIT(19)) + break; + } + hdmi_set_bits(hdmi, 0x408, 3, 0x8, 0); + hdmi_set_bits(hdmi, 0x408, 6, 0x40, 0); + if (i == 10) { + dev_err(disp->dev, "HDMI: no ACK to PLL command %u\n", command); + return -ETIMEDOUT; + } + return 0; +} + +/* The lane-disable bits of each lane; 0x2420 holds the mask of unused lanes. */ +static void hdmi_set_lanes(struct t8152_hdmi *hdmi, u32 lanes) +{ + static const u32 offsets[] = { 0x64, 0x24, 0x24, 0x48, 0x48, 0x5c, 0x5c, 0x48 }; + static const u32 shifts[] = { 4, 4, 1, 0, 1, 2, 3, 4 }; + static const u32 masks[] = { 0x10, 0x10, 0x2, 0x1, 0x2, 0x4, 0x8, 0x10 }; + u32 lane, i; + + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 0); + for (lane = 0; lane < HDMI_LANES; lane++) { + u32 base = HDMI_LANE0 + lane * HDMI_LANE_STRIDE; + + for (i = 0; i < ARRAY_SIZE(offsets); i++) + hdmi_set_bits(hdmi, base + offsets[i], shifts[i], + masks[i], lane >= lanes); + } + hdmi_set_bits(hdmi, 0x2420, 0, 0xf, 0xf & ~((1 << lanes) - 1)); + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 1); +} + +static int hdmi_activate(struct t8152_display *disp) +{ + return 0; +} + +static int hdmi_deactivate(struct t8152_display *disp) +{ + dev_info(disp->dev, "HDMI: keeping the link up on deactivate\n"); + return 0; +} + +/* + * A new link rate: lanes off, PLL down, the PLL frequency, half link rate, + * PLL up again. + */ +static int hdmi_set_link_rate(struct t8152_display *disp, u32 rate) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + const u32 *w = NULL; + bool half; + size_t i; + int ret; + + for (i = 0; i < ARRAY_SIZE(hdmi_pll_configs); i++) + if (hdmi_pll_configs[i].rate == rate) + w = hdmi_pll_configs[i].w; + if (!w) + return -EINVAL; + + dev_info(disp->dev, "HDMI: link rate %#x\n", rate); + hdmi_set_bits(hdmi, 0x2400, 0, 0x1, 0); + ret = hdmi_pll_command(disp, hdmi, 0); + if (ret) + return ret; + + /* The PLL frequency, downspread off */ + hdmi_set_bits(hdmi, 0x6c0, 0, 0x7ff, w[1]); + hdmi_set_bits(hdmi, 0x6c0, 11, 0x800, w[6]); + hdmi_set_bits(hdmi, 0x6c0, 13, 0x2000, w[10]); + hdmi_set_bits(hdmi, 0x6c0, 18, 0x3c0000, w[21]); + hdmi_set_bits(hdmi, 0x6c4, 14, 0xfffc000, w[2]); + hdmi_set_bits(hdmi, 0x6c4, 0, 0x3fff, + (!(w[7] & 1) && w[2] < 2) ? 0 : w[3]); + hdmi_set_bits(hdmi, 0x6c8, 14, 0xc000, w[0]); + hdmi_set_bits(hdmi, 0x6c8, 8, 0x100, 0); + hdmi_set_bits(hdmi, 0x6c8, 0, 0xff, w[8]); + hdmi_set_bits(hdmi, 0x6c8, 9, 0x3e00, w[5]); + hdmi_set_bits(hdmi, 0x6c8, 16, 0x10000, w[17]); + hdmi_set_bits(hdmi, 0x6c8, 26, 0xfc000000, w[9]); + hdmi_set_bits(hdmi, 0x6cc, 0, 0x7f, w[11]); + hdmi_set_bits(hdmi, 0x6cc, 9, 0x600, w[13]); + hdmi_set_bits(hdmi, 0x6cc, 11, 0x7800, w[14]); + hdmi_set_bits(hdmi, 0x6cc, 15, 0x38000, w[15]); + hdmi_set_bits(hdmi, 0x6cc, 20, 0x100000, w[16]); + hdmi_set_bits(hdmi, 0x6cc, 21, 0x200000, w[18]); + hdmi_set_bits(hdmi, 0x6cc, 22, 0xc00000, w[19]); + hdmi_set_bits(hdmi, 0x6cc, 24, 0x3000000, w[4]); + hdmi_set_bits(hdmi, 0x6cc, 26, 0xc000000, w[20]); + + /* Latch the link rate dependent shadow registers (APB 0xa0). */ + hdmi_apb_update(hdmi, 0xa0, BIT(3), BIT(3)); + hdmi_apb_update(hdmi, 0xa0, BIT(2), BIT(2)); + hdmi_apb_update(hdmi, 0xa0, BIT(18), BIT(18)); + hdmi_apb_update(hdmi, 0xa0, BIT(18), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(19), BIT(19)); + hdmi_apb_update(hdmi, 0xa0, BIT(19), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(2), 0); + hdmi_apb_update(hdmi, 0xa0, BIT(3), 0); + + /* No UHBR rates; half link rate from HBR up. */ + half = rate >= LINK_RATE_HBR; + hdmi_set_bits(hdmi, 0x2400, 2, 0x4, 0); + hdmi_set_bits(hdmi, 0x2400, 3, 0x8, !half); + hdmi_set_bits(hdmi, 0x0000, 17, 0x20000, !half); + + ret = hdmi_pll_command(disp, hdmi, 7); + if (ret) + return ret; + if (!(readl(hdmi->core + 0x438) & BIT(30))) { + dev_err(disp->dev, "HDMI: PLL failed to lock at rate %#x\n", rate); + return -EIO; + } + return 0; +} + +static int hdmi_set_lane_count(struct t8152_display *disp, u32 lanes) +{ + /* The PHY takes no zero lane count. */ + if (lanes) + hdmi_set_lanes(disp->phy_priv, lanes); + return 0; +} + +static int hdmi_set_drive(struct t8152_display *disp, + const struct t8152_drive_settings *settings, u32 count) +{ + return 0; +} + +static int hdmi_set_route(struct t8152_display *disp, bool enable) +{ + return 0; +} + +/* + * The sink's EDID through the AP AUX controller aux1: the PHY takes its + * source from aux1 for the read (its AUX reaches the PS190, which reads the + * monitor's DDC), then from the DCP again. The display is off meanwhile. + */ +static int hdmi_read_edid(struct t8152_display *disp, u8 *buf, size_t size) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + u32 src; + int ret; + + if (!hdmi->aux.regs) + return -ENODEV; + ret = t8152_aux_init(disp, &hdmi->aux); + if (ret) + return ret; + src = readl(hdmi->apb + HDMI_SOURCE_SELECT); + writel((src & ~0xf) | HDMI_SOURCE_AUX1, hdmi->apb + HDMI_SOURCE_SELECT); + ret = t8152_aux_read_edid(disp, &hdmi->aux, buf, size); + writel(src, hdmi->apb + HDMI_SOURCE_SELECT); + return ret; +} + +static const struct t8152_phy_ops hdmi_ops = { + .activate = hdmi_activate, + .deactivate = hdmi_deactivate, + .set_link_rate = hdmi_set_link_rate, + .set_lane_count = hdmi_set_lane_count, + .set_drive = hdmi_set_drive, + .set_route = hdmi_set_route, + .read_edid = hdmi_read_edid, + .max_link_rate = LINK_RATE_HBR3, +}; + +/* + * The PS190's power through the SMC: the {key, value} writes of + * apple,pcon-power. The PS190 drives the HDMI HPD line only while it is + * powered, and the AP AUX controller that reads the USB-C monitors' EDID + * gets no reply from any USB-C port while it is off. Nothing here waits + * for it to come up: a DCP takes the port only once it sees HPD + * (t8152_hdmi_port_poll()), and an EDID read retries until the AUX + * replies (t8152_aux_read_edid()). On a port taken over, these writes find + * the PS190 powered since probe. + */ +static int hdmi_pcon_power(struct t8152_display *disp, struct t8152_hdmi *hdmi) +{ + struct platform_device *smc_pdev = of_find_device_by_node(hdmi->smc_np); + struct apple_smc *smc = smc_pdev ? platform_get_drvdata(smc_pdev) : NULL; + int ret = 0; + + if (!smc) { + ret = -EPROBE_DEFER; + goto out; + } + for (int i = 0; i + 3 <= hdmi->pcon_len; i += 3) { + u64 value = (u64)be32_to_cpu(hdmi->pcon[i + 1]) << 32 | + be32_to_cpu(hdmi->pcon[i + 2]); + + ret = apple_smc_write(smc, be32_to_cpu(hdmi->pcon[i]), &value, + sizeof(value)); + if (ret) { + dev_err(disp->dev, "HDMI: PS190 power failed: %d\n", ret); + goto out; + } + } +out: + if (smc_pdev) + put_device(&smc_pdev->dev); + return ret; +} + +/* The PHY's PMGR and PSD power, then the PS190's. */ +static int hdmi_power_up(struct t8152_display *disp, struct t8152_hdmi *hdmi) +{ + int ret; + u32 val; + + if ((readl(hdmi->ps) & HDMI_PS_ACTUAL) != HDMI_PS_ACTUAL) { + val = readl(hdmi->ps) & ~(HDMI_PS_TARGET | HDMI_PS_FLAGS); + writel(val | HDMI_PS_TARGET, hdmi->ps); + ret = readl_poll_timeout(hdmi->ps, val, + (val & HDMI_PS_ACTUAL) == HDMI_PS_ACTUAL, + 10, HDMI_POWER_TIMEOUT_US); + if (ret) { + dev_err(disp->dev, "HDMI: PHY power state stays %#x\n", val); + return ret; + } + } + if (readl(hdmi->psd + HDMI_PSD_STATE) & 7) { + writel(0, hdmi->psd + HDMI_PSD_TARGET); + ret = readl_poll_timeout(hdmi->psd + HDMI_PSD_STATE, val, !(val & 7), + 10, HDMI_POWER_TIMEOUT_US); + if (ret) { + dev_err(disp->dev, "HDMI: PHY PSD state stays %#x\n", val); + return ret; + } + } + return hdmi_pcon_power(disp, hdmi); +} + +/* The impedance calibration: wait for 0x1c04 bit 0, take 0x1c24 bits 12:6. */ +static void hdmi_impedance_calibration(struct t8152_display *disp, + struct t8152_hdmi *hdmi) +{ + u32 val; + + if (readl_poll_timeout(hdmi->core + 0x1c04, val, val & 1, 10, 1000000)) + dev_warn(disp->dev, "HDMI: impedance calibration timed out\n"); + hdmi_set_bits(hdmi, 0x1c00, 4, 0x3f0, 0x3f); + val = readl(hdmi->core + 0x1c24); + hdmi_set_bits(hdmi, 0x1c18, 15, 0x3f8000, (val >> 6) & 0x7f); + hdmi_set_bits(hdmi, 0x1c18, 14, 0x4000, 1); +} + +/* + * The cold start, as the bootloader does it: power, source select, PLL, AUX + * and PHY power, the tunables, the PLL and PHY activation, four lanes and + * the impedance calibration. Once up, the link is kept on deactivate, as + * for the bootloader's HDMI. + */ +static int hdmi_port_activate(struct t8152_display *disp) +{ + struct t8152_hdmi *hdmi = disp->phy_priv; + int ret; + + if (hdmi->active) + return 0; + ret = hdmi_power_up(disp, hdmi); + if (ret) + return ret; + /* The source select: only the low nibble */ + hdmi_apb_update(hdmi, HDMI_SOURCE_SELECT, 0xf, disp->dp_source); + /* PLL, AUX and PHY power enables */ + hdmi_apb_update(hdmi, 0x48, 0x010, 0x010); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x020, 0x020); + hdmi_apb_update(hdmi, 0x48, 0x040, 0); + hdmi_apb_update(hdmi, 0x48, 0x100, 0x100); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x200, 0x200); + hdmi_apb_update(hdmi, 0x48, 0x400, 0); + hdmi_apb_update(hdmi, 0x48, 0x001, 0x001); + usleep_range(1000, 2000); + hdmi_apb_update(hdmi, 0x48, 0x002, 0x002); + hdmi_apb_update(hdmi, 0x48, 0x004, 0); + + for (int i = 0; i + 3 <= hdmi->tunable_len; i += 3) { + void __iomem *reg = hdmi->core + be32_to_cpu(hdmi->tunable[i]); + + writel((readl(reg) & ~be32_to_cpu(hdmi->tunable[i + 1])) | + be32_to_cpu(hdmi->tunable[i + 2]), reg); + } + + hdmi_set_bits(hdmi, 0x08d0, 4, 0x10, 1); /* single-ended PLL clock */ + hdmi_set_bits(hdmi, 0x0000, 1, 0x02, 1); /* PLL on */ + hdmi_set_bits(hdmi, 0x1400, 0, 0x01, 0); /* AUX common control */ + hdmi_set_bits(hdmi, 0x1c00, 4, 0x3f0, 0x3c); /* PHY on */ + hdmi_set_bits(hdmi, 0x0000, 0, 0x01, 1); + usleep_range(1000, 2000); + hdmi_set_lanes(hdmi, HDMI_LANES); + hdmi_impedance_calibration(disp, hdmi); + hdmi->active = true; + dev_info(disp->dev, "HDMI: PHY up from cold, source %u\n", disp->dp_source); + return 0; +} + +static const struct t8152_phy_ops hdmi_port_ops = { + .activate = hdmi_port_activate, + .deactivate = hdmi_deactivate, + .set_link_rate = hdmi_set_link_rate, + .set_lane_count = hdmi_set_lane_count, + .set_drive = hdmi_set_drive, + .set_route = hdmi_set_route, + .read_edid = hdmi_read_edid, + .max_link_rate = LINK_RATE_HBR3, +}; + +/* Registers shared with the other DCPs that may take the HDMI port. */ +static void __iomem *hdmi_ioremap(struct t8152_display *disp, + struct device_node *np, const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + struct resource res; + + if (index < 0 || of_address_to_resource(np, index, &res)) + return NULL; + return devm_ioremap(disp->dev, res.start, resource_size(&res)); +} + +static void hdmi_put_smc(void *data) +{ + of_node_put(data); +} + +static void hdmi_port_put(void *data) +{ + guard(mutex)(&hdmi_port_lock); + if (!--hdmi_port_users) { + gpiod_put(hdmi_port_hpd); + hdmi_port_hpd = NULL; + } +} + +static struct gpio_desc *hdmi_port_get(struct t8152_display *disp, + struct device_node *np) +{ + struct gpio_desc *hpd; + int ret; + + scoped_guard(mutex, &hdmi_port_lock) { + if (!hdmi_port_users) { + hpd = fwnode_gpiod_get_index(of_fwnode_handle(np), "hpd", 0, + GPIOD_ASIS, "hdmi-hpd"); + if (IS_ERR(hpd)) + return hpd; + hdmi_port_hpd = hpd; + } + hdmi_port_users++; + hpd = hdmi_port_hpd; + } + ret = devm_add_action_or_reset(disp->dev, hdmi_port_put, NULL); + return ret ? ERR_PTR(ret) : hpd; +} + +/* + * The HDMI port of the shared ports, for every DCP: the PHY's source select + * takes each one's crossbar endpoint. Without the cold start description in + * np, HDMI stays the bootloader's. + */ +int t8152_hdmi_port_init(struct t8152_display *disp, struct device_node *np) +{ + struct t8152_hdmi *hdmi; + int ret; + + if (!of_property_present(np, "apple,pcon-power")) + return 0; + hdmi = devm_kzalloc(disp->dev, sizeof(*hdmi), GFP_KERNEL); + if (!hdmi) + return -ENOMEM; + hdmi->core = hdmi_ioremap(disp, np, "phy-core"); + hdmi->apb = hdmi_ioremap(disp, np, "phy-apb"); + hdmi->ps = hdmi_ioremap(disp, np, "phy-ps"); + hdmi->psd = hdmi_ioremap(disp, np, "phy-psd"); + hdmi->aux.regs = hdmi_ioremap(disp, np, "aux"); + hdmi->aux.ps = hdmi_ioremap(disp, np, "aux-ps"); + /* AUX output select 0x10: the lpdptx PHY */ + hdmi->aux.sel = 0x10; + if (!hdmi->core || !hdmi->apb || !hdmi->ps || !hdmi->psd) + return -ENOMEM; + if (!hdmi->aux.ps) + hdmi->aux.regs = NULL; + hdmi->pcon = of_get_property(np, "apple,pcon-power", &hdmi->pcon_len); + hdmi->pcon_len /= sizeof(__be32); + hdmi->tunable = of_get_property(np, "apple,tunable-phy", + &hdmi->tunable_len); + hdmi->tunable_len /= sizeof(__be32); + hdmi->smc_np = of_parse_phandle(np, "apple,smc", 0); + if (!hdmi->smc_np) + return -EINVAL; + ret = devm_add_action_or_reset(disp->dev, hdmi_put_smc, hdmi->smc_np); + if (ret) + return ret; + /* Without the bootloader's HDMI nothing else powers the PS190. */ + ret = hdmi_pcon_power(disp, hdmi); + if (ret) + return ret; + /* Every DCP that may take the port watches the same line. */ + hdmi->hpd = hdmi_port_get(disp, np); + if (IS_ERR(hdmi->hpd)) + return PTR_ERR(hdmi->hpd); + disp->hdmi_port = hdmi; + dev_info(disp->dev, "HDMI: port shared, taken without a USB-C display\n"); + return 0; +} + +/* + * Take the HDMI port when a sink is plugged in and this DCP drives no USB-C + * display; give it back once the sink is gone and the plug path has + * released the link. Called from the connector's detect with the display + * lock held. + */ +void t8152_hdmi_port_poll(struct t8152_display *disp) +{ + struct t8152_hdmi *hdmi = disp->hdmi_port; + int hpd; + + if (!hdmi) + return; + hpd = gpiod_get_value_cansleep(hdmi->hpd); + if (hpd < 0) + return; + guard(mutex)(&hdmi_port_lock); + if (disp->on_hdmi) { + if (hpd || disp->hpd) + return; + disp->phy = disp->usbc_phy; + disp->phy_priv = disp->usbc_phy_priv; + disp->dcp_output = disp->usbc_output; + disp->hpd_gpio = NULL; + disp->on_hdmi = false; + hdmi_port_owner = NULL; + dev_info(disp->dev, "HDMI: port given back\n"); + return; + } + if (!hpd || disp->hpd || hdmi_port_owner || !t8152_atc_release(disp)) + return; + hdmi_port_owner = disp->dev; + disp->usbc_phy = disp->phy; + disp->usbc_phy_priv = disp->phy_priv; + disp->usbc_output = disp->dcp_output; + disp->phy = &hdmi_port_ops; + disp->phy_priv = hdmi; + /* display crossbar DFP endpoint lpdptx */ + disp->dcp_output = 4; + disp->hpd_gpio = hdmi->hpd; + disp->on_hdmi = true; + dev_info(disp->dev, "HDMI: sink plugged, taking the HDMI port\n"); +} + +/* The DCP node that describes the HDMI PHY (DCPEXT0's). */ +struct device_node *t8152_hdmi_node(void) +{ + struct device_node *np; + + for_each_compatible_node(np, NULL, "apple,t8152-dcp-iboot") + if (of_property_read_bool(np, "apple,hdmi")) + return np; + return NULL; +} + +static void __iomem *hdmi_map(struct device *dev, struct device_node *np, + const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + + if (index < 0) + return IOMEM_ERR_PTR(index); + return devm_of_iomap(dev, np, index, NULL); +} + +static bool hdmi_power_active(struct device_node *np, const char *name) +{ + int index = of_property_match_string(np, "reg-names", name); + void __iomem *regs; + u32 state; + + if (index < 0) + return false; + regs = of_iomap(np, index); + if (!regs) + return false; + state = readl(regs); + iounmap(regs); + /* Both the requested and actual PMGR states must be active. */ + return (state & GENMASK(7, 0)) == GENMASK(7, 0); +} + +/* + * The DCP the bootloader wired to the PHY (its source select: 0 for the main + * DCP on the HDMI-only route, 1 for DCPEXT0 next to a USB-C display), or + * -ENODEV if it left the PHY off or the PLL unlocked. + */ +int t8152_hdmi_source(struct device_node *np) +{ + int core = of_property_match_string(np, "reg-names", "phy-core"); + int apb = of_property_match_string(np, "reg-names", "phy-apb"); + void __iomem *core_regs, *apb_regs; + int ret = -ENODEV; + + /* The PHY aperture aborts while gated, including on a USB-C-only boot. */ + if (core < 0 || apb < 0 || !hdmi_power_active(np, "phy-ps")) + return -ENODEV; + core_regs = of_iomap(np, core); + apb_regs = of_iomap(np, apb); + if (core_regs && apb_regs && readl(core_regs + 0x438) & BIT(30)) + ret = readl(apb_regs + HDMI_SOURCE_SELECT) & 0xf; + if (apb_regs) + iounmap(apb_regs); + if (core_regs) + iounmap(core_regs); + if (ret == 1 && !hdmi_power_active(np, "coproc-ps")) + return -ENODEV; + if (ret != 0 && ret != 1) + return -ENODEV; + return ret; +} + +/* The PHY, its AUX controller and its HPD line come from np. */ +int t8152_hdmi_init(struct t8152_display *disp, struct device_node *np) +{ + struct t8152_hdmi *hdmi; + + hdmi = devm_kzalloc(disp->dev, sizeof(*hdmi), GFP_KERNEL); + if (!hdmi) + return -ENOMEM; + hdmi->core = hdmi_map(disp->dev, np, "phy-core"); + if (IS_ERR(hdmi->core)) + return PTR_ERR(hdmi->core); + hdmi->apb = hdmi_map(disp->dev, np, "phy-apb"); + if (IS_ERR(hdmi->apb)) + return PTR_ERR(hdmi->apb); + + /* AUX output select 0x10: the lpdptx PHY */ + t8152_aux_probe(disp, &hdmi->aux, 0x10, np); + + dev_info(disp->dev, "HDMI: inherited source select %u, PLL %slocked\n", + readl(hdmi->apb + HDMI_SOURCE_SELECT) & 0xf, + readl(hdmi->core + 0x438) & BIT(30) ? "" : "not "); + + disp->phy = &hdmi_ops; + disp->phy_priv = hdmi; + /* display crossbar DFP endpoint lpdptx */ + disp->dcp_output = 4; + return 0; +} diff --git a/drivers/gpu/drm/apple/t8152_pd.c b/drivers/gpu/drm/apple/t8152_pd.c new file mode 100644 index 00000000000000..8c514d17d69d2c --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_pd.c @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * USB-C plug state from the rear ports' ACE3 PD controllers over SPMI, for + * the USB-C displays' hotplug: the DP alt mode connection, its pin + * assignment and the plug orientation. Logical registers are read through a + * window: select with a register-zero write, wait for the busy bit to + * clear, read the size at 0x1f and the data from 0x20. + * + * Interim, until tipd owns these controllers and reports DP alt mode to the + * Type-C route layer of dcp-fabric.c: tipd and this share the SPMI devices, + * serialized by the device lock. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "t8152_display.h" + +#define ACE3_SELECT 0x00 +#define ACE3_SELECT_BUSY BIT(7) +#define ACE3_SIZE 0x1f +#define ACE3_DATA 0x20 +#define ACE3_BURST 16 + +#define ACE3_REG_CMD1 0x08 +#define ACE3_REG_DATA1 0x09 +#define ACE3_REG_STATUS 0x1a +#define ACE3_REG_POWER_STATE 0x20 +#define ACE3_REG_DATA_STATUS 0x5f + +#define STATUS_PLUG_PRESENT BIT(0) +#define STATUS_UPSIDE_DOWN BIT(4) +#define DATA_DP_CONNECTION BIT(8) +#define DATA_HPD_LEVEL BIT(15) /* CD321x, as tipd */ + +static int ace3_read(struct spmi_device *sdev, u8 reg, u8 *buf, size_t len) +{ + u8 sel, size; + int ret, err = 0; + + ret = spmi_register_zero_write(sdev, reg); + if (ret) + return ret; + ret = read_poll_timeout(spmi_ext_register_read, err, + err || !(sel & ACE3_SELECT_BUSY), 50, 20000, + false, sdev, ACE3_SELECT, &sel, 1); + if (ret || err) + return ret ?: err; + ret = spmi_ext_register_read(sdev, ACE3_SIZE, &size, 1); + if (ret) + return ret; + if (size < len) + return -EIO; + for (size_t done = 0; done < len; done += ACE3_BURST) { + ret = spmi_ext_register_read(sdev, ACE3_DATA + done, buf + done, + min_t(size_t, len - done, ACE3_BURST)); + if (ret) + return ret; + } + return 0; +} + +static int ace3_select(struct spmi_device *sdev, u8 reg) +{ + u8 sel; + int ret, err = 0; + + ret = spmi_register_zero_write(sdev, reg); + if (ret) + return ret; + ret = read_poll_timeout(spmi_ext_register_read, err, + err || !(sel & ACE3_SELECT_BUSY), 50, 20000, + false, sdev, ACE3_SELECT, &sel, 1); + return ret ?: err; +} + +static int ace3_write(struct spmi_device *sdev, u8 reg, const u8 *buf, + size_t len) +{ + int ret = ace3_select(sdev, reg); + + return ret ?: spmi_ext_register_write(sdev, ACE3_DATA, (u8 *)buf, len); +} + +/* A 4CC command with an optional data byte; 0 once the controller took it. */ +static int ace3_cmd(struct spmi_device *sdev, const char *cmd, int data) +{ + u8 val[4]; + int ret; + + ret = spmi_command_wakeup(sdev); + if (ret) + return ret; + if (data >= 0) { + u8 d = data; + + ret = ace3_write(sdev, ACE3_REG_DATA1, &d, 1); + if (ret) + return ret; + } + ret = ace3_write(sdev, ACE3_REG_CMD1, cmd, 4); + if (ret) + return ret; + for (int i = 0; i < 1000; i++) { + ret = ace3_read(sdev, ACE3_REG_CMD1, val, sizeof(val)); + if (ret) + return ret; + if (!memcmp(val, "!CMD", 4)) + return -EIO; + if (!memcmp(val, "\0\0\0\0", 4)) + return 0; + usleep_range(1000, 2000); + } + return -ETIMEDOUT; +} + +/* + * Leave and enter DP alt mode again, as unplugging and plugging the cable + * does: reset the controller (Gaid), then power the port up again once it + * takes commands (SSPS 0). A sink that stopped answering AUX after a + * monitor's deep sleep comes back this way. + */ +int t8152_pd_reconnect(struct t8152_display *disp) +{ + struct spmi_device *pd = disp->pd; + int ret; + + device_lock(&pd->dev); + /* Gaid resets the controller before it can report completion. */ + ret = spmi_command_wakeup(pd); + if (!ret) + ret = ace3_write(pd, ACE3_REG_CMD1, "Gaid", 4); + if (ret) + goto out; + /* + * The controller restarts: on the J873g ports its mode register read + * "BOOT" about 22 ms after Gaid, it acknowledged no SPMI command from + * about 215 ms on, and it read "APP " and took SSPS again after about + * 290 ms. Polling it through that gap only gets NACKs, which the SPMI + * controller logs as errors, and nothing signals the restart's end. + * So SSPS is first sent 500 ms after Gaid, and every 500 ms after that + * for a controller that takes longer. + */ + for (int i = 0; i < 60; i++) { + msleep(500); + ret = ace3_cmd(pd, "SSPS", 0); + if (!ret) + break; + } +out: + device_unlock(&pd->dev); + return ret; +} + +/* 1 with a DisplayPort sink in DP alt mode and HPD high, 0 without. */ +int t8152_pd_sink(struct spmi_device *pd, bool *flipped, u32 *lanes) +{ + u8 status[4], data[4], power; + int ret; + + /* Serialize the logical register window with the USB4 port monitor. */ + device_lock(&pd->dev); + /* Without a plug the controller sleeps and ignores selects. */ + ret = spmi_command_wakeup(pd); + if (ret) + goto out; + ret = ace3_read(pd, ACE3_REG_POWER_STATE, &power, sizeof(power)); + if (ret) + goto out; + /* Register access alone does not enable the alt-mode policy engine. */ + if (power) { + ret = ace3_cmd(pd, "SSPS", 0); + if (ret) + goto out; + } + ret = ace3_read(pd, ACE3_REG_STATUS, status, sizeof(status)); + if (!ret) + ret = ace3_read(pd, ACE3_REG_DATA_STATUS, data, sizeof(data)); + if (ret) + goto out; + *flipped = status[0] & STATUS_UPSIDE_DOWN; + /* Pin D/F shares the cable with USB3; C/E uses all four DP lanes. */ + *lanes = get_unaligned_le32(data) & BIT(5) ? 2 : 4; + /* The sink answers AUX once it raised HPD, not at alt mode entry. */ + ret = (status[0] & STATUS_PLUG_PRESENT) && + (get_unaligned_le32(data) & DATA_DP_CONNECTION) && + (get_unaligned_le32(data) & DATA_HPD_LEVEL); +out: + device_unlock(&pd->dev); + return ret; +} + +/* The PD controller @np's apple,usb-pd points at, NULL without one. */ +struct spmi_device *t8152_pd_get(struct device_node *np) +{ + struct device_node *pd_np = of_parse_phandle(np, "apple,usb-pd", 0); + struct spmi_device *pd; + + if (!pd_np) + return NULL; + /* Holds a reference for the lifetime of the (retained) device. */ + pd = spmi_find_device_by_of_node(pd_np); + of_node_put(pd_np); + return pd ?: ERR_PTR(-EPROBE_DEFER); +} From 8d197aae70a930ad882ff8657e8086076a793691 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 07:21:03 +0100 Subject: [PATCH 0328/1514] drm/apple: wake AFK waiters when a service opens A caller that needs an endpoint's services, or the state one of their init callbacks sets up, can only poll for them. Give each endpoint a wait queue that is woken once a service has opened and its init callback has run, on each path that opens one: compact, AFKv2 and a deferred AFKv2 open. The host-test fixtures that build those paths get the wait queue too. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/afk.c | 3 +++ drivers/gpu/drm/apple/afk.h | 3 +++ tools/asahi/dcpext26-parity-tests.py | 3 ++- tools/asahi/dcpext26-startup-tests.py | 3 ++- tools/testing/selftests/drivers/gpu/apple-dcp/edid.py | 3 ++- 5 files changed, 12 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index ad684ae5e954bb..75152de0a85dd0 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1024,6 +1024,7 @@ static void afk_recv_handle_compact_init(struct apple_dcp_afkep *ep, if (ops->init) ops->init(service, service_name, service_name, unit); + wake_up_all(&ep->service_wq); dev_info(ep->dcp->dev, "AFK[ep:%02x]: new compact service %s on interface %u%s\n", @@ -1713,6 +1714,7 @@ static void afk_retry_service_init(struct apple_dcp_afkep *ep) if (ops->init) ops->init(service, service->pending_name, service->pending_class, service->pending_unit); + wake_up_all(&ep->service_wq); if (service->enabled) afk_populate_service_debugfs(service); kfree(service->pending_name); @@ -1951,6 +1953,7 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, ops->init_props(service, epic_unit, props, props_size); if (ops->init) ops->init(service, epic_name, epic_class, epic_unit); + wake_up_all(&ep->service_wq); dev_info(ep->dcp->dev, "AFK[ep:%02x]: new service %s on channel %d\n", ep->endpoint, service_name, channel); diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index c01022b6b0f875..cf214e1eb1b689 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -587,6 +587,8 @@ struct apple_dcp_afkep { const struct apple_epic_service_ops *unmatched_ops; struct apple_epic_service services[AFK_MAX_CHANNEL]; u32 num_channels; + /* Woken once a service has opened and its init callback has run. */ + wait_queue_head_t service_wq; struct dentry *debugfs_entry; @@ -606,6 +608,7 @@ static inline void afk_ep_init_state(struct apple_dcp_afkep *ep) spin_lock_init(&ep->lock); INIT_LIST_HEAD(&ep->compact_cmds); init_waitqueue_head(&ep->compact_orphan_wq); + init_waitqueue_head(&ep->service_wq); mutex_init(&ep->compact_tx_lock); init_completion(&ep->started); init_completion(&ep->stopped); diff --git a/tools/asahi/dcpext26-parity-tests.py b/tools/asahi/dcpext26-parity-tests.py index 08e8fddb71e0ff..bbdff169ae2e9a 100644 --- a/tools/asahi/dcpext26-parity-tests.py +++ b/tools/asahi/dcpext26-parity-tests.py @@ -158,7 +158,8 @@ def run(name,code): struct apple_epic_service {bool pending_open,enabled;const struct apple_epic_service_ops *ops;const char *pending_name,*pending_class;int pending_unit;u32 channel;}; struct apple_dcp {bool ext26_services_open;struct apple_dcp_afkep *dptxep;}; static bool dptx_native_controllers_ready(struct apple_dcp *d){return true;} -struct apple_dcp_afkep {struct apple_dcp *dcp;unsigned num_channels;struct apple_epic_service services[2];}; +struct apple_dcp_afkep {struct apple_dcp *dcp;unsigned num_channels;struct apple_epic_service services[2];int service_wq;}; +#define wake_up_all(q) ((void)(q)) static bool dcp_is_ext26(struct apple_dcp *d){return true;} static unsigned sent,published,discarded,initialized;static int fault; static void afk_discard_pending_open(struct apple_epic_service *s){discarded++;s->pending_open=false;} diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index bc8a0aa89a9927..98b984e5975545 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -95,7 +95,8 @@ def run(name,code,reject=False): struct apple_epic_service {struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops;bool enabled,torndown,pending_open,defer_start;unsigned users;int lock;u32 channel;void *cookie;const char *pending_name,*pending_class;s64 pending_unit;int cmd_map[1];}; struct dptx_port {struct apple_epic_service *service;s64 unit;bool enabled,connected;int enable_completion;}; struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;bool afk_announced_names;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; -struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops,*unmatched_ops;struct apple_epic_service services[AFK_MAX_CHANNEL];}; +struct apple_dcp_afkep {struct apple_dcp *dcp;u32 endpoint,num_channels;bool wire_v2,stopping,match_epic_name,compact;int lock;void *wq,*service_work;const struct apple_epic_service_ops *ops,*unmatched_ops;struct apple_epic_service services[AFK_MAX_CHANNEL];int service_wq;}; +#define wake_up_all(q) ((void)(q)) static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} static bool dcp_is_v14_7_external(struct apple_dcp *d){return false;} diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index b4ea075b85f278..6898b7b368801f 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -95,7 +95,8 @@ def function(file,signature): bool pending_open;const char *pending_name,*pending_class;s64 pending_unit; }; /* v27_closed_teardown: set only by a J714s firmware 27 sleep. */ -struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops,*unmatched_ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; +struct apple_dcp_afkep { u8 *command_tags;bool lock,stopping;void *wq;struct work_struct service_work;struct apple_dcp *dcp;const struct apple_epic_service_ops *ops,*unmatched_ops;bool wire_v2,inline_v2,match_epic_name,v27_closed_teardown;u32 endpoint;unsigned int num_channels;int service_wq;struct apple_epic_service services[AFK_MAX_CHANNEL]; }; +#define wake_up_all(q) ((void)(q)) struct apple_connector { void *dcp;bool connected,edid_invalidation_pending;struct { int registration_state; } base;unsigned int hotplug_wq; }; struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; From 54f310756b0828ef422df6cc1ed1794f294b4a47 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:59:43 +0100 Subject: [PATCH 0329/1514] drm/apple: drive the T8152 DCPs through the iBoot interface The T8152 (Mac mini J873g) DCP firmware offers a small display service, disp0-service on the main DCP and dispext-service on the DCPEXTs, next to its IOMFB interface. The bootloader drives the J873g displays through it, with the DPTX port service that the firmware calls into the AP for the PHY and the DPAV controller services it expects to be opened, all over AFKv2. Add these DCPs to drm/apple as the DCP_FIRMWARE_IBOOT variant, matched by apple,t8152-dcp-iboot, with the shared AFK code and the iBoot commands of ibootep.c. The match data selects AFKv2 on every endpoint, endpoints registered with an RTKit session taken without its map, services matched by their announced name and a three-second AFK timeout. dcp_platform_probe() hands such a DCP to iomfb_iboot.c. Taking the session over: - A running session is adopted without the RTKit handshake (apple_rtkit_init_adopted(), apple_rtkit_adopt_running()): the DCP does not acknowledge AP QUIESCED, and an IOP INIT while its AP power is on panics it. A session the loader quiesced after a failed display setup (/chosen apple,dcp-rtkit-running = 0; the older J873 loader build v0.1.0-259-ga30a589a predates the property and is recognised by its 640x1136 placeholder framebuffer) is woken instead, and so is an unused DCPEXT the loader marks apple,rtkit-wake, once its PSD reads powered (a read of the coprocessor while it is gated hangs the machine) and its CPU runs. - The loader's AFK endpoint hand-off (apple,afk-active-endpoints) is required and fills dcp->afk_live_endpoints, so afk_start() stops each endpoint the loader left running: an AFK INIT on a live endpoint asserts in the firmware. Without the property there is no telling whether an endpoint is live, and the DCP is not taken over. - A woken DCPEXT's oslog endpoint offers a 0x5ff8-byte ring at 0x100033cc000, the log segment of its own firmware addressed with the coprocessor's DRAM tag in bit 40, which only the firmware's retained DART tables map. With that buffer request failed, RTKit rejected the firmware's write counters as invalid instead of acknowledging them, which the firmware waits for before AP power transitions. The ring is taken as the firmware's, without a CPU mapping; the other buffers go through drm/apple's RTKit shared memory hooks. The surface log lines go to the debug level. - Once the session is taken it is retained until reboot like the other live sessions (dcp_retain_live_session(), split out of dcp_pin_live_session()). A failed start stops the endpoint work, detaches RTKit with its buffers kept and leaves the device bound, so nothing retries over a partly started session. Starting the display: - A new iBoot session has no surface, and a pipe that still runs then fetches from a null base (IOMFB axi_rd_err, firmware NMI): the display is powered off at once and powered on only after a SET_SURFACE. - The DPAV controller endpoint's four services are opened without a handler. Opening dcpav-video-interface starts the firmware's idle power off timer: a powered display without a following SET_MODE counts as idle, and the firmware takes the link down 30 s later, as it did with HDMI 30 s after boot while the compositor still had the output on. SET_MODE is sent again a second after that interface opens, from a work outside the AFK receive queues. - The DPTX port services are bound in the order they are announced. On USB-C the inherited DPTX link is released before the first connection. - The DCP fetches through dart-dcp and the display pipe scans out through dart-disp0; both are locked, with live roots of their own. One domain over both would publish dart-dcp's root into dart-disp0 and drop the bootloader's scanout mappings, so the scanout stream is a child device with a domain of its own. Scanout buffers are mapped there at their DCP address, cacheable, since the pipe faults on entries with the DART's no-cache bit, and below any range the firmware already maps there (a buffer mapped over one flickered). They are written through a write-combined mapping: the pipe does not snoop the CPU caches. - The bootloader's simple-framebuffer is taken over. KMS (iboot_drm.c), one DRM device per DCP: - Changing the surface between Linux buffers made later SET_MODEs crash the firmware. Three scanout buffers of at least 3840x2160 are allocated at probe; a frame's damage is copied by the CPU into one that is not on screen, which SET_SURFACE then shows, at most once per refresh by an hrtimer: there is no vblank interrupt, and several swaps within one refresh let an older frame stay on screen. The pitch is 64-byte aligned, as the firmware refuses an unaligned one. - The firmware takes a mode as width, height and a 16.16 refresh rate and picks the timing itself. The modes are the sink's EDID modes the firmware also lists, or the firmware's list with CVT timings. A DRM mode is matched to the firmware mode nearest by the exact refresh rate, within 1 Hz: next to an EIZO EV2780's 2560x1440@59.951 (241.5 MHz) the firmware lists a 60.000 Hz standard mode of its own (byte 0 bit 6), which it drives at 312.25 MHz and the monitor does not take. - The EDID is read through the AP's DisplayPort AUX controllers while the firmware does no AUX itself, since the iBoot interface does not hand it out. - A mode must fit the lanes the route may train, as GET_MAX_LANE_COUNT reports them, not those of the last training: a monitor that drops and reasserts HPD while the display is off is trained without a stream on a single lane, and 2560x1440@60 then failed the atomic check when the outputs came back on. - Right after power on the firmware still trains the link and fails SET_MODE; it takes the mode once the link is up, so SET_MODE is retried. The colour mode is the deepest valid one up to 32 bpp, as SET_MODE refuses the deeper ones the HDMI converter offers. - USB-C hotplug is polled from the PD controllers every 250 ms, HDMI from the converter's HPD line. An unplug releases DPTX and powers the PHY down, a sink that no longer answers after a monitor's deep sleep gets a fresh DP alt mode entry at most once a minute, and a quick reconnect restores a CRTC that was enabled. - drm/apple's per-DCP DRM device of dcpext_drm.c and dcpext_scanout.c does not fit: it is the T6030 external role's diagnostic, with one fixed 3840x2160 mode and the swap operations instead of SET_SURFACE. The DRM driver is named "apple-dcpib" (DCP iBoot interface), apart from the display subsystem's "apple"; appledrm.iboot_buffered=0 copies frames into the buffer on screen instead. Removal, shutdown and system sleep leave the firmware session alone. An unbind unplugs the DRM device, releases its committed state without touching the firmware, and detaches RTKit; the session stays retained, and a new bind is refused until reboot. The live endpoint hand-off and the retained failed start are based on changes by Acelogic. Tested on the J873g with HDMI and two rear USB-C monitors: all three come up, HDMI-A-1 at 2560x1440@59.951, DP-1 at 2560x1440@59.951 and DP-2 at 1920x1200@59.950. DPMS off and on works on each output, and so does HDMI at 1920x1080 and back. mpv runs fullscreen at 60 fps with no dropped frame after the first five. Unbinding DCPEXT1 removes its DRM device without a warning, and a new bind is refused with -EBUSY. Earlier runs of the same display code on the J873g: booted without HDMI, a monitor plugged in later is taken by a free DCP (DCPEXT0, and in another run DCPEXT1 with source select 2), which starts the PHY from cold and runs 2560x1440@60 at HBR3, DCPEXT0 within 0.6 s; with the bootloader's DCP start failing on purpose, HDMI and both USB-C monitors come up at their EDID modes; woken DCPEXTs log no buffer error. Signed-off-by: Thomas Glanzmann --- MAINTAINERS | 2 + drivers/gpu/drm/apple/Kconfig | 1 + drivers/gpu/drm/apple/Makefile | 1 + drivers/gpu/drm/apple/dcp-internal.h | 10 + drivers/gpu/drm/apple/dcp.c | 103 ++- drivers/gpu/drm/apple/iboot_drm.c | 1081 ++++++++++++++++++++++++++ drivers/gpu/drm/apple/iomfb_iboot.c | 840 ++++++++++++++++++++ drivers/gpu/drm/apple/iomfb_iboot.h | 139 ++++ 8 files changed, 2169 insertions(+), 8 deletions(-) create mode 100644 drivers/gpu/drm/apple/iboot_drm.c create mode 100644 drivers/gpu/drm/apple/iomfb_iboot.c create mode 100644 drivers/gpu/drm/apple/iomfb_iboot.h diff --git a/MAINTAINERS b/MAINTAINERS index 1afb033e7ffcd0..8bd740eea9930b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2156,6 +2156,8 @@ M: Thomas Glanzmann L: dri-devel@lists.freedesktop.org S: Maintained F: Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +F: drivers/gpu/drm/apple/iboot_drm.c +F: drivers/gpu/drm/apple/iomfb_iboot.* F: drivers/gpu/drm/apple/t8152_* APPLETALK NETWORK LAYER diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index d27d975da6f41c..876ebbd58605e1 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -80,6 +80,7 @@ config DRM_APPLE_DCP_T8152 depends on DRM_APPLE depends on SPMI=y || SPMI=DRM_APPLE depends on MFD_MACSMC=y || MFD_MACSMC=DRM_APPLE + select APERTURE_HELPERS help Lets the common Apple display driver drive the three display coprocessors of the T8152 Mac mini (J873g) through their firmware's diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index 3a0953cf6628aa..e6752d0f285166 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -20,6 +20,7 @@ appledrm-y += iomfb_v14_7.o iomfb_v14_7_link.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8132) += iomfb_m4.o t8132_ext_drm.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_atc.o t8152_aux.o t8152_dptx.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_pd.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += iomfb_iboot.o iboot_drm.o appledrm-y += iomfb_h17p.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_h17p_test.o parser_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_external_hdr_hints_test.o diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 857ece58491568..f55c05d9f17931 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -463,6 +463,7 @@ struct dcp_desktop_state { /* TODO: move IOMFB members to its own struct */ struct dcpext_scanout; struct t8152_display; +struct dcp_iboot; struct dcp_hdmi; struct dcp_cec; @@ -587,6 +588,8 @@ struct apple_dcp { enum dcp_firmware_version fw_compat; /* T8152: the DisplayPort hardware behind the DPTX port (t8152_display.h) */ struct t8152_display *t8152; + /* DCP_FIRMWARE_IBOOT: the display driven through it (iomfb_iboot.h) */ + struct dcp_iboot *iboot; /* Bumped by every iomfb poweron; see afk_compact_slot(). */ u32 afk_power_gen; /* @@ -1220,6 +1223,13 @@ static inline bool dcp_is_iboot(const struct apple_dcp *dcp) return dcp->fw_compat == DCP_FIRMWARE_IBOOT; } +struct apple_rtkit_shmem; +/* The common RTKit shared memory hooks, for a processor with its own RTKit ops. */ +int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr); +void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr); +/* Keep a session that cannot be stopped, its DMA and this driver until reboot. */ +int dcp_retain_live_session(struct apple_dcp *dcp); + /* T8132 firmware uses its own wire codec, with the common DRM/KMS owner. */ static inline bool iomfb_is_m4(const struct apple_dcp *dcp) { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..396b62c988ecbb 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -77,6 +77,7 @@ #include "dptx-service.h" #include "iomfb.h" #include "iomfb_internal.h" +#include "iomfb_iboot.h" #include "iomfb_m4.h" #include "ibootep.h" #include "iomfb_internal.h" @@ -114,15 +115,15 @@ static bool dcp_session_retained(struct device *dev) return retained; } -static int dcp_pin_live_session(struct apple_dcp *dcp) +/* + * Keep a live session's DMA device, domain use and this driver until reboot, + * and refuse a new probe of its device after an unbind. + */ +int dcp_retain_live_session(struct apple_dcp *dcp) { struct dcp_session_ref *session; - if ((!dcp->hw.adopt_live_session && - dcp->hw.iomfb_method_profile != - DCP_IOMFB_METHODS_H17P_EXTERNAL) || - !dcp_fail_stop(dcp) || - dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || dcp->retain_dma) + if (dcp->retain_dma) return 0; session = kzalloc_obj(*session); if (!session) @@ -143,6 +144,17 @@ static int dcp_pin_live_session(struct apple_dcp *dcp) return 0; } +static int dcp_pin_live_session(struct apple_dcp *dcp) +{ + if ((!dcp->hw.adopt_live_session && + dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL) || + !dcp_fail_stop(dcp) || + dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || dcp->retain_dma) + return 0; + return dcp_retain_live_session(dcp); +} + static void dcp_release_dma_domain(void *data) { struct apple_dcp *dcp = data; @@ -1843,7 +1855,7 @@ static int dcp_check_iova_contiguous(struct iommu_domain *domain, return 0; } -static int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) +int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_dcp *dcp = cookie; int ret; @@ -1904,7 +1916,7 @@ static int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) return 0; } -static void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +void dcp_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_dcp *dcp = cookie; @@ -7884,13 +7896,51 @@ static int dcp_platform_probe_t8132_ext(struct platform_device *pdev) * bind's, may still appear (bounded by the deferred probe timeout); on any * other failure join as an unusable pipe. */ +/* + * A DCP driven through the iBoot interface alone (DCP_FIRMWARE_IBOOT, + * iomfb_iboot.c): no component of a display subsystem, with a DRM device of + * its own. Its adopted session cannot be stopped: once the firmware is + * touched, its DMA and this driver stay until reboot, and a failed start + * leaves the device bound without a display. + */ +static int dcp_platform_probe_iboot(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct apple_dcp *dcp; + int ret; + + if (dcp_session_retained(dev)) + return dev_err_probe(dev, -EBUSY, "Previous live DCP session requires a reboot\n"); + dcp = kzalloc_obj(*dcp); + if (!dcp) + return -ENOMEM; + ret = devm_add_action_or_reset(dev, dcp_release_context, dcp); + if (ret) + return ret; + dcp->dev = dev; + dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); + dcp->fw_compat = dcp->hw.firmware_compat; + ret = iommu_device_use_default_domain(dev); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, dcp_release_dma_domain, dcp); + if (ret) + return ret; + platform_set_drvdata(pdev, dcp); + return dcp_iboot_probe(dcp); +} + static int dcp_platform_probe(struct platform_device *pdev) { + const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); struct device *dev = &pdev->dev; struct apple_dcp *dcp; void *group; int ret; + if (hw->firmware_compat == DCP_FIRMWARE_IBOOT) + return dcp_platform_probe_iboot(pdev); + /* t6041_dcpext=0: stay off the external processors' hardware. */ if (of_device_is_compatible(dev->of_node, "apple,t6041-dcpext") && !t6041_dcpext) { @@ -7949,6 +7999,11 @@ static void dcp_platform_remove(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); + /* No component and none of the works below; see dcp_iboot_remove(). */ + if (dcp && dcp_is_iboot(dcp)) { + dcp_iboot_remove(dcp); + return; + } if (dcp) { cancel_work_sync(&dcp->s2r_prewarm_work); cancel_delayed_work_sync(&dcp->s2r_prewarm_off_wq); @@ -8008,6 +8063,9 @@ VISIBLE_IF_KUNIT void dcp_platform_shutdown(struct platform_device *pdev) if (dcp_takeover_was_aborted(dcp)) return; + /* The iBoot interface's display stays as it is: no component to remove. */ + if (dcp && dcp_is_iboot(dcp)) + return; if (dcp && iomfb_is_m4(dcp)) { dcp_comp_unbind(&pdev->dev, NULL, NULL); @@ -8239,6 +8297,9 @@ static void dcp_platform_complete(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + /* The iBoot interface's display stays powered across system sleep. */ + if (dcp_is_iboot(dcp)) + return; if (dcp_is_ext26(dcp)) { WRITE_ONCE(dcp->ext26_pm_preparing, false); if (dcp->ext26_pm_work_off && !READ_ONCE(dcp->ext26_blocked) && @@ -9724,6 +9785,9 @@ static int dcp_platform_suspend(struct device *dev) /* Its power sequences may crash the DCP and blank the panel. */ if (dcp_takeover_was_aborted(dcp)) return -EBUSY; + /* The iBoot interface's display stays powered across system sleep. */ + if (dcp_is_iboot(dcp)) + return 0; /* * An external DCP given up at probe may never have set up the works @@ -9877,6 +9941,8 @@ static int dcp_platform_resume(struct device *dev) if (dcp_takeover_was_aborted(dcp)) return 0; + if (dcp_is_iboot(dcp)) + return 0; if (dcp_v27_sleep_selected(dcp) && READ_ONCE(dcp->sleep_v27_closed)) return dcp_v27_sleep_resume(dcp); @@ -10113,8 +10179,29 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8142_dcpext = { .s2r_layout = &dcp_s2r_t8142_ext[0], }; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) +/* + * T8152 (J873g): the DCP and both DCPEXTs, driven through the firmware's + * iBoot interface (disp0-service, dispext-service) over AFKv2, with the + * DPAV controller and DPTX port endpoints opened as the firmware expects + * them. The bootloader leaves each session running or quiesced; a running + * one is taken without the RTKit handshake. + */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8152_iboot = { + .num_dptx_ports = 2, + .firmware_compat = DCP_FIRMWARE_IBOOT, + .afk_v2 = true, + .afk_adopt_endpoints = true, + .afk_announced_names = true, + .afk_timeout_ms = 3000, +}; +#endif + static const struct of_device_id of_match[] = { { .compatible = "apple,t8142-dcpext", .data = &apple_dcp_hw_t8142_dcpext }, +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) + { .compatible = "apple,t8152-dcp-iboot", .data = &apple_dcp_hw_t8152_iboot }, +#endif { .compatible = "apple,t6041-dcp", .data = &apple_dcp_hw_t6041, }, { .compatible = "apple,t6041-dcpext", .data = &apple_dcp_hw_t6041_dcpext, }, { .compatible = "apple,t6050-dcp", .data = &apple_dcp_hw_t6050 }, diff --git a/drivers/gpu/drm/apple/iboot_drm.c b/drivers/gpu/drm/apple/iboot_drm.c new file mode 100644 index 00000000000000..c0b3bd2311962d --- /dev/null +++ b/drivers/gpu/drm/apple/iboot_drm.c @@ -0,0 +1,1081 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KMS of a DCP driven through the iBoot interface (DCP_FIRMWARE_IBOOT): a DRM + * device of its own per DCP with one primary plane, CRTC, encoder and + * connector. The firmware only takes width, height and refresh rate for a + * mode and picks the timing itself; the modes come from the sink's EDID, or + * from the firmware's list built with CVT. + * + * Framebuffers are shadow buffers copied by the CPU into the scanout + * buffers, and a modeset only changes their geometry, as the bootloader + * does. Changing the surface address between Linux buffers made later + * modesets crash the firmware (IOMFB axi_rd_err), so the scanout buffers + * are the only surfaces the firmware gets. There is no vblank interrupt. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dcp-internal.h" +#include "ibootep.h" +#include "iomfb_iboot.h" +#include "t8152_display.h" + +/* + * Swap between the scanout buffers per frame. Off: frames are copied into + * the buffer on screen, which tears during motion. + */ +static bool buffered = true; +module_param_named(iboot_buffered, buffered, bool, 0444); +MODULE_PARM_DESC(iboot_buffered, "iBoot interface displays: copy each frame into a scanout buffer that is not on screen (default: on)"); + +DEFINE_DRM_GEM_DMA_FOPS(dcp_iboot_fops); + +/* + * Not the display subsystem's "apple": these DCPs take no direct scanout, + * every frame is copied, so userspace must not treat them as that one. + */ +static const struct drm_driver dcp_iboot_drm_driver = { + /* + * Frames are copied by the CPU, imported ones too: a compositor + * driving both displays imports one device's buffers into the other. + */ + DRM_GEM_DMA_DRIVER_OPS_VMAP, + DRM_FBDEV_DMA_DRIVER_OPS, + .name = "apple-dcpib", + .desc = "Apple DCP (iBoot interface)", + .major = 1, + .minor = 0, + .driver_features = DRIVER_GEM | DRIVER_MODESET | DRIVER_ATOMIC, + .fops = &dcp_iboot_fops, +}; + +struct dcp_iboot *dcp_iboot_alloc(struct device *dev) +{ + return devm_drm_dev_alloc(dev, &dcp_iboot_drm_driver, struct dcp_iboot, drm); +} + +const char *dcp_iboot_driver_name(void) +{ + return dcp_iboot_drm_driver.name; +} + +static const u32 dcp_iboot_formats[] = { + DRM_FORMAT_XRGB8888, + DRM_FORMAT_ARGB8888, +}; + +static int iboot_refresh(const struct iboot_timing_mode *t) +{ + return (le32_to_cpu(t->fps) + 0x8000) >> 16; +} + +/* + * Whether @t works: the link at the PHY's highest rate must carry it (24 bpp + * plus about 12% blanking against rate x lanes x 0.8 for 8b/10b); a mode + * beyond that only blanks the display. + */ +static bool iboot_mode_fits(struct dcp_iboot *ib, const struct iboot_timing_mode *t) +{ + const struct t8152_phy_ops *phy = ib->disp.phy; + /* + * The lanes the firmware may train, as GET_MAX_LANE_COUNT reports them: + * the USB-C route's. Not the last training's: a sink that replugs while + * the display is off is trained with a single lane. + */ + u32 lanes = (phy->max_lane_count ? phy->max_lane_count(&ib->disp) : 4) ?: 2; + u64 link = (u64)phy->max_link_rate * 270000000ULL * lanes * 8 / 10; + u64 pixels = (u64)le32_to_cpu(t->width) * le32_to_cpu(t->height) * + iboot_refresh(t); + + /* Hotplug may return modes larger than the buffers allocated at probe. */ + if ((u64)ALIGN(le32_to_cpu(t->width) * 4, 64) * le32_to_cpu(t->height) > + ib->scan[0].size) + return false; + return pixels * 24 * 112 / 100 <= link; +} + +/* @mode's refresh rate in 16.16, as drm_mode_vrefresh() computes it. */ +static u32 iboot_mode_fps(const struct drm_display_mode *mode) +{ + u64 num = mul_u32_u32(mode->clock, 1000) << 16; + u64 den = mul_u32_u32(mode->htotal, mode->vtotal); + + if (mode->flags & DRM_MODE_FLAG_INTERLACE) + num *= 2; + if (mode->flags & DRM_MODE_FLAG_DBLSCAN) + den *= 2; + if (mode->vscan > 1) + den *= mode->vscan; + return den ? DIV64_U64_ROUND_CLOSEST(num, den) : 0; +} + +/* + * The firmware mode for @mode: same size, refresh rate within 1 Hz (EDID's + * 59.94 against the firmware's 60.00), the nearest one by the exact rate. + * The firmware picks the timing from the rate, and next to the sink's + * 2560x1440@59.951 (241.5 MHz) it lists a 60.000 standard mode that it + * drives with CVT at 312.25 MHz, which the J873g's USB-C EV2780 rejects. + */ +static const struct iboot_timing_mode * +iboot_find_mode(struct dcp_iboot *ib, const struct drm_display_mode *mode) +{ + const struct iboot_timing_mode *best = NULL; + u32 fps = iboot_mode_fps(mode); + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + if (!t->valid || le32_to_cpu(t->width) != mode->hdisplay || + le32_to_cpu(t->height) != mode->vdisplay || + abs_diff(le32_to_cpu(t->fps), fps) > 0x10000 || + !iboot_mode_fits(ib, t)) + continue; + if (!best || abs_diff(le32_to_cpu(t->fps), fps) < + abs_diff(le32_to_cpu(best->fps), fps)) + best = t; + } + return best; +} + +/* + * Valid, at most 32 bpp, the highest depth, then the lowest colorimetry, + * encoding and EOTF, as the bootloader chooses. Deeper modes the HDMI + * converter offers are refused by SET_MODE. + */ +static bool iboot_color_better(const struct iboot_color_mode *a, + const struct iboot_color_mode *b) +{ + u32 abpp = le32_to_cpu(a->bpp), bbpp = le32_to_cpu(b->bpp); + bool afits = abpp <= 32, bfits = bbpp <= 32; + + if (!!a->valid != !!b->valid) + return a->valid; + if (afits != bfits) + return afits; + if (abpp != bbpp) + return abpp > bbpp; + if (a->colorimetry != b->colorimetry) + return le32_to_cpu(a->colorimetry) < le32_to_cpu(b->colorimetry); + if (a->encoding != b->encoding) + return le32_to_cpu(a->encoding) < le32_to_cpu(b->encoding); + return le32_to_cpu(a->eotf) < le32_to_cpu(b->eotf); +} + +static const struct iboot_color_mode *iboot_find_color(struct dcp_iboot *ib) +{ + const struct iboot_color_mode *best = NULL; + + for (unsigned int i = 0; i < ib->nr_cmodes; i++) + if (!best || iboot_color_better(&ib->cmodes[i], best)) + best = &ib->cmodes[i]; + return best && best->valid ? best : NULL; +} + +/* + * A conservative console mode from 50 to 60 Hz, up to 1920x1080 on + * USB-C. Userspace can select the larger modes, including 2560x1440@60, + * after the sink's EDID is available. + */ +static const struct iboot_timing_mode *iboot_preferred(struct dcp_iboot *ib) +{ + const struct iboot_timing_mode *best = NULL; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + /* + * Byte 0 bit 6 marks standard modes a converter adds on its own + * (the J873g PS190 lists 3840x2160 for a 2560x1440 monitor); + * the bootloader's largest mode skips them too. + */ + if (!t->valid || iboot_refresh(t) > 60 || iboot_refresh(t) < 50 || + (t->flags[0] & 0x40) || + (!ib->disp.hdmi && (le32_to_cpu(t->width) > 1920 || + le32_to_cpu(t->height) > 1080)) || + !iboot_mode_fits(ib, t)) + continue; + if (!best || (u64)le32_to_cpu(t->width) * le32_to_cpu(t->height) > + (u64)le32_to_cpu(best->width) * le32_to_cpu(best->height) || + (t->width == best->width && t->height == best->height && + le32_to_cpu(t->fps) > le32_to_cpu(best->fps))) + best = t; + } + return best; +} + +/* + * The sink's EDID modes the firmware also has (mode_valid drops the rest), + * the largest of them preferred: firmware modes the sink does not list, + * such as 1400x1050 on the J873g EV2780, stay black. + */ +static int iboot_edid_get_modes(struct drm_connector *connector) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + struct drm_display_mode *mode, *best = NULL; + int count = drm_edid_connector_add_modes(connector); + + mutex_lock(&ib->lock); + list_for_each_entry(mode, &connector->probed_modes, head) { + mode->type &= ~DRM_MODE_TYPE_PREFERRED; + if (!iboot_find_mode(ib, mode)) + continue; + if (!best || mode->hdisplay * mode->vdisplay > + best->hdisplay * best->vdisplay || + (mode->hdisplay * mode->vdisplay == + best->hdisplay * best->vdisplay && + drm_mode_vrefresh(mode) > drm_mode_vrefresh(best))) + best = mode; + } + if (best) + best->type |= DRM_MODE_TYPE_PREFERRED; + mutex_unlock(&ib->lock); + return count; +} + +static int iboot_connector_get_modes(struct drm_connector *connector) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + const struct iboot_timing_mode *preferred; + int count = 0; + + drm_edid_connector_update(connector, ib->edid); + if (ib->edid) + return iboot_edid_get_modes(connector); + + /* Without an EDID, the firmware's list. */ + mutex_lock(&ib->lock); + preferred = iboot_preferred(ib); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + struct drm_display_mode *mode; + + if (!t->valid || !iboot_mode_fits(ib, t)) + continue; + mode = drm_cvt_mode(connector->dev, le32_to_cpu(t->width), + le32_to_cpu(t->height), iboot_refresh(t), + false, false, false); + if (!mode) + continue; + if (t == preferred) + mode->type |= DRM_MODE_TYPE_PREFERRED; + drm_mode_probed_add(connector, mode); + count++; + } + mutex_unlock(&ib->lock); + return count; +} + +static enum drm_mode_status +iboot_connector_mode_valid(struct drm_connector *connector, + const struct drm_display_mode *mode) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + + return iboot_find_mode(ib, mode) ? MODE_OK : MODE_NOMODE; +} + +static const struct drm_connector_helper_funcs iboot_connector_helper = { + .get_modes = iboot_connector_get_modes, + .mode_valid = iboot_connector_mode_valid, +}; + +static int iboot_set_mode_locked(struct dcp_iboot *ib, + const struct iboot_timing_mode *t, + const struct iboot_color_mode *c); + +/* With ib->lock held; queued work will observe the cleared pending slot. */ +static void iboot_cancel_swap_locked(struct dcp_iboot *ib) +{ + hrtimer_cancel(&ib->swap_timer); + ib->pending = -1; +} + +/* Read the sink's EDID through the PHY, if it can, and keep it. */ +void dcp_iboot_update_edid(struct dcp_iboot *ib) +{ + const struct drm_edid *edid = NULL; + u8 *buf; + int len; + + if (!ib->disp.phy->read_edid) + return; + buf = kzalloc(4 * EDID_LENGTH, GFP_KERNEL); + if (!buf) + return; + len = ib->disp.phy->read_edid(&ib->disp, buf, 4 * EDID_LENGTH); + if (len >= EDID_LENGTH) { + edid = drm_edid_alloc(buf, len); + if (edid && !drm_edid_valid(edid)) { + drm_edid_free(edid); + edid = NULL; + } + } + if (!edid) + dev_warn(ib->dcp->dev, "no EDID: %d\n", len); + else + dev_info(ib->dcp->dev, "EDID: %d bytes\n", len); + drm_edid_free(ib->edid); + ib->edid = edid; + kfree(buf); +} + +static enum drm_connector_status +iboot_connector_detect(struct drm_connector *connector, bool force) +{ + struct dcp_iboot *ib = to_dcp_iboot(connector->dev); + struct t8152_display *disp = &ib->disp; + struct apple_dcp *dcp = ib->dcp; + enum drm_connector_status status; + bool flipped = false; + int hpd; + + mutex_lock(&ib->lock); + t8152_hdmi_port_poll(disp); + if (disp->hpd_gpio) { + hpd = gpiod_get_value_cansleep(disp->hpd_gpio); + } else if (disp->phy->detect) { + hpd = disp->phy->detect(disp, &flipped); + } else { + status = ib->nr_tmodes ? connector_status_connected : + connector_status_disconnected; + goto out; + } + if (hpd < 0) { + status = connector_status_unknown; + goto out; + } + if (hpd != disp->hpd) { + dev_info(dcp->dev, "sink %s\n", hpd ? "plugged" : "unplugged"); + disp->hpd = hpd; + /* + * USB-C: the DPTX port's HPD follows the PD controller, and a + * new plug may come the other way round. + */ + if (disp->pd) { + if (!hpd || ib->powered) { + iboot_cancel_swap_locked(ib); + if (t8152_dptx_disconnect(disp, 0)) + dev_err(dcp->dev, "DPTX release failed\n"); + if (!ibootep_set_power(dcp, false)) { + ib->powered = false; + ib->mode_set = false; + disp->phy->deactivate(disp); + } + } + /* + * A plug while the display stayed on (unplug and plug + * between two polls): start the PHY cold again, the + * new plug may come the other way round. + */ + if (hpd) + disp->phy->deactivate(disp); + /* The sink may be on another port now. */ + if (hpd && disp->phy->select) + disp->phy->select(disp); + if (hpd && disp->phy->set_orientation) + disp->phy->set_orientation(disp, flipped); + /* The firmware talks AUX as soon as it sees HPD. */ + if (hpd && disp->phy->activate(disp)) + dev_err(dcp->dev, "PHY activation failed\n"); + if (hpd && t8152_dptx_connect(disp, 0)) + dev_err(dcp->dev, "DPTX connect failed\n"); + if (hpd && t8152_dptx_set_hpd(disp, 0, true)) + dev_err(dcp->dev, "DPTX HPD update failed\n"); + } + /* A new sink: the firmware reads its EDID, take the new lists. */ + if (hpd && (dcp_iboot_wait_hpd(ib) || dcp_iboot_get_modes(ib))) { + dev_err(dcp->dev, "no modes from the new sink\n"); + ib->nr_tmodes = 0; + ib->nr_cmodes = 0; + /* A sleeping EIZO may need a fresh DP alt mode entry. */ + if (disp->pd && !disp->on_hdmi && + time_after(jiffies, ib->pd_reset_time + 60 * HZ)) { + ib->pd_reset_time = jiffies; + schedule_work(&ib->pd_reset_work); + } + } + /* + * The EDID once the firmware has read it, so the sink's DDC + * answers, and before SET_MODE: reading it borrows the AUX path + * while the firmware does no AUX. + */ + if (hpd && ib->nr_tmodes) + dcp_iboot_update_edid(ib); + /* + * A fast reconnect can finish before userspace disables the CRTC. + * Restore its requested state even though unplug powered it off. + */ + if (hpd && ib->enabled && ib->cur_mode.valid) { + const struct iboot_timing_mode *t = NULL; + const struct iboot_color_mode *c = iboot_find_color(ib); + int ret = 0; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *candidate = &ib->tmodes[i]; + + if (candidate->valid && candidate->width == ib->cur_mode.width && + candidate->height == ib->cur_mode.height && + candidate->fps == ib->cur_mode.fps) { + t = candidate; + break; + } + } + if (t && c && !ib->powered) { + ret = ibootep_set_surface(dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), + le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (!ret) + ret = ibootep_set_power(dcp, true); + ib->powered = !ret; + } + if (t && c && !ret) + iboot_set_mode_locked(ib, t, c); + } + } + status = hpd && ib->nr_tmodes ? connector_status_connected : + connector_status_disconnected; +out: + mutex_unlock(&ib->lock); + return status; +} + +static const struct drm_connector_funcs iboot_connector_funcs = { + .detect = iboot_connector_detect, + .fill_modes = drm_helper_probe_single_connector_modes, + .destroy = drm_connector_cleanup, + .reset = drm_atomic_helper_connector_reset, + .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, + .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, +}; + +static int iboot_plane_atomic_check(struct drm_plane *plane, + struct drm_atomic_commit *state) +{ + struct drm_plane_state *new = drm_atomic_get_new_plane_state(state, plane); + struct dcp_iboot *ib = to_dcp_iboot(plane->dev); + struct drm_crtc_state *crtc_state = NULL; + u32 width, height; + int ret; + + if (new->crtc) + crtc_state = drm_atomic_get_new_crtc_state(state, new->crtc); + /* The surface fills the whole mode; no scaling or positioning. */ + ret = drm_atomic_helper_check_plane_state(new, crtc_state, + DRM_PLANE_NO_SCALING, + DRM_PLANE_NO_SCALING, + false, false); + if (ret || !new->visible) + return ret; + /* The helper clips src/dst; raw src_w/src_h may exceed the CRTC. */ + if ((new->src.x1 | new->src.y1 | new->src.x2 | new->src.y2) & 0xffff) + return -EINVAL; + width = drm_rect_width(&new->src) >> 16; + height = drm_rect_height(&new->src) >> 16; + return (u64)ALIGN(width * 4, 64) * height <= ib->scan[0].size ? 0 : -EINVAL; +} + +static void iboot_rect_grow(struct drm_rect *r, const struct drm_rect *add) +{ + if (!drm_rect_visible(r)) { + *r = *add; + return; + } + r->x1 = min(r->x1, add->x1); + r->y1 = min(r->y1, add->y1); + r->x2 = max(r->x2, add->x2); + r->y2 = max(r->y2, add->y2); +} + +/* The current mode's refresh period, from its exact 16.16 rate. */ +static s64 iboot_period_ns(struct dcp_iboot *ib) +{ + u32 fps = le32_to_cpu(ib->cur_mode.fps); + + if (fps < (24 << 16)) + fps = 60 << 16; + return div64_u64((u64)NSEC_PER_SEC << 16, fps); +} + +/* Whether a frame may be shown: the display is on, set up and alive. */ +static bool iboot_scanning_locked(struct dcp_iboot *ib) +{ + struct apple_rtkit *rtk = READ_ONCE(ib->dcp->rtk); + + return ib->powered && ib->mode_set && ib->disp.hpd && rtk && + !apple_rtkit_is_crashed(rtk); +} + +/* Show scan[buf]. Called with ib->lock held. */ +static void iboot_swap_locked(struct dcp_iboot *ib, unsigned int buf, u32 w, + u32 h, u32 pitch) +{ + int ret; + + if (!iboot_scanning_locked(ib)) + return; + + /* The pipe must see the whole frame before it is swapped in. */ + wmb(); + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[buf], w, h, pitch); + if (ret) { + /* Still on the old buffer, which misses this frame. */ + dev_err_ratelimited(ib->dcp->dev, "swap failed: %d\n", ret); + ib->stale[ib->front] = DRM_RECT_INIT(0, 0, INT_MAX / 2, INT_MAX / 2); + return; + } + ib->last_swap = ktime_get(); + ib->retired[ib->front] = ib->last_swap; + ib->front = buf; +} + +static void iboot_swap_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(work, struct dcp_iboot, swap_work); + + mutex_lock(&ib->lock); + if (ib->pending >= 0) { + iboot_swap_locked(ib, ib->pending, ib->pending_w, + ib->pending_h, ib->pending_pitch); + ib->pending = -1; + } + mutex_unlock(&ib->lock); +} + +static enum hrtimer_restart iboot_swap_timer(struct hrtimer *t) +{ + struct dcp_iboot *ib = container_of(t, struct dcp_iboot, swap_timer); + + queue_work(system_highpri_wq, &ib->swap_work); + return HRTIMER_NORESTART; +} + +/* + * Copy the frame into a scanout buffer that is not on screen and show it. + * That buffer already holds an older frame: copy this frame's damage and + * what changed since that buffer was last written. + * + * SET_SURFACE returns before the pipe takes the buffer at its next frame + * start, and there is no vblank interrupt. Several swaps within one refresh + * let an older frame stay on screen (a cursor that jumps back), so swaps are + * spaced one refresh apart: a frame that comes sooner waits in a pending + * buffer, which a newer frame overwrites, and a timer swaps it in. The + * commit itself never waits, so a client's next frame is not held up. + */ +static void iboot_plane_atomic_update(struct drm_plane *plane, + struct drm_atomic_commit *state) +{ + struct drm_plane_state *old = drm_atomic_get_old_plane_state(state, plane); + struct drm_plane_state *new = drm_atomic_get_new_plane_state(state, plane); + struct drm_shadow_plane_state *shadow = to_drm_shadow_plane_state(new); + struct dcp_iboot *ib = to_dcp_iboot(plane->dev); + struct drm_framebuffer *fb = new->fb; + struct drm_atomic_helper_damage_iter iter; + struct drm_rect clip, source_clip, src, full, damage = { 0, 0, 0, 0 }; + unsigned int pitch, back; + struct iosys_map dst; + s64 period, since; + + if (!fb || !new->visible) + return; + src = DRM_RECT_INIT(new->src.x1 >> 16, new->src.y1 >> 16, + drm_rect_width(&new->src) >> 16, + drm_rect_height(&new->src) >> 16); + full = DRM_RECT_INIT(0, 0, drm_rect_width(&src), drm_rect_height(&src)); + pitch = ALIGN(drm_rect_width(&full) * 4, 64); + drm_atomic_helper_damage_iter_init(&iter, old, new); + drm_atomic_for_each_plane_damage(&iter, &clip) { + if (!drm_rect_intersect(&clip, &src)) + continue; + drm_rect_translate(&clip, -src.x1, -src.y1); + iboot_rect_grow(&damage, &clip); + } + if (!drm_rect_visible(&damage)) + return; + + mutex_lock(&ib->lock); + if (!iboot_scanning_locked(ib)) + goto out; + period = iboot_period_ns(ib); + if (!READ_ONCE(buffered)) { + /* Into the buffer on screen (tears during motion). */ + back = ib->front; + } else if (ib->pending >= 0) { + back = ib->pending; + } else { + /* The other buffer that left the screen first. */ + unsigned int a = (ib->front + 1) % DCP_IBOOT_SCANOUT_BUFS; + unsigned int b = (ib->front + 2) % DCP_IBOOT_SCANOUT_BUFS; + s64 wait; + + back = ktime_before(ib->retired[a], ib->retired[b]) ? a : b; + /* Off screen for a full refresh: only after a mode change. */ + wait = period - ktime_to_ns(ktime_sub(ktime_get(), ib->retired[back])); + if (ib->mode_set && wait > 0) + usleep_range(div_s64(wait, NSEC_PER_USEC), + div_s64(wait, NSEC_PER_USEC) + 100); + } + clip = ib->stale[back]; + iboot_rect_grow(&clip, &damage); + if (drm_rect_intersect(&clip, &full)) { + iosys_map_set_vaddr(&dst, ib->scan_wc[back]); + iosys_map_incr(&dst, drm_fb_clip_offset(pitch, fb->format, &clip)); + source_clip = clip; + drm_rect_translate(&source_clip, src.x1, src.y1); + drm_fb_memcpy(&dst, &pitch, shadow->data, fb, &source_clip); + } + ib->stale[back] = (struct drm_rect){ 0, 0, 0, 0 }; + for (unsigned int i = 0; i < DCP_IBOOT_SCANOUT_BUFS; i++) + if (i != back) + iboot_rect_grow(&ib->stale[i], &damage); + if (back == ib->front) + goto out; + + since = ktime_to_ns(ktime_sub(ktime_get(), ib->last_swap)); + if (ib->pending < 0 && (!ib->mode_set || since >= period)) { + iboot_swap_locked(ib, back, drm_rect_width(&full), + drm_rect_height(&full), pitch); + goto out; + } + ib->pending_w = drm_rect_width(&full); + ib->pending_h = drm_rect_height(&full); + ib->pending_pitch = pitch; + if (ib->pending < 0) { + ib->pending = back; + hrtimer_start(&ib->swap_timer, ktime_add_ns(ib->last_swap, period), + HRTIMER_MODE_ABS); + } +out: + mutex_unlock(&ib->lock); +} + +static const struct drm_plane_helper_funcs iboot_plane_helper = { + DRM_GEM_SHADOW_PLANE_HELPER_FUNCS, + .atomic_check = iboot_plane_atomic_check, + .atomic_update = iboot_plane_atomic_update, +}; + +static const struct drm_plane_funcs iboot_plane_funcs = { + .update_plane = drm_atomic_helper_update_plane, + .disable_plane = drm_atomic_helper_disable_plane, + .destroy = drm_plane_cleanup, + DRM_GEM_SHADOW_PLANE_FUNCS, +}; + +static int iboot_crtc_atomic_check(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + + /* No vblank interrupt: the helpers complete events after the flush. */ + new->no_vblank = true; + if (new->enable && !iboot_find_mode(ib, &new->mode)) + return -EINVAL; + return 0; +} + +/* SET_MODE, then the scanout buffer with the new mode's geometry. */ +static int iboot_set_mode_locked(struct dcp_iboot *ib, + const struct iboot_timing_mode *t, + const struct iboot_color_mode *c) +{ + int ret; + + /* + * Right after power on the firmware may still train the link, and it + * fails SET_MODE with an error status until the link is up. It sends + * no message once it is: the DPTX calls it makes while training (link + * configuration, rate, lane count) have no last one, and a sink can + * be trained twice in a row. So SET_MODE is retried. In the traced + * J873g modesets the link was up 76 to 229 ms after power on; one + * failed SET_MODE takes about 200 ms itself, so 200 ms between tries + * cover a second training, and five tries give up after about two + * seconds. On USB-C the DP alt mode reentry below takes over then. + */ + for (int i = 0; i < 5; i++) { + ret = ibootep_set_mode(ib->dcp, t, c); + if (ret != -EIO) + break; + msleep(200); + } + if (ret) { + dev_err(ib->dcp->dev, "set_mode failed: %d\n", ret); + /* + * USB-C: a sink that no longer answers AUX (seen after the + * monitor's deep sleep) comes back with a fresh DP alt mode + * entry; the plug that follows sets the mode again. At most + * once a minute, so a dead sink does not loop. + */ + if (ib->disp.pd && !ib->disp.on_hdmi && + time_after(jiffies, ib->pd_reset_time + 60 * HZ)) { + ib->cur_mode = *t; + ib->mode_failed = true; + ib->pd_reset_time = jiffies; + schedule_work(&ib->pd_reset_work); + } + return ret; + } + ib->cur_mode = *t; + ib->mode_set = true; + ib->mode_failed = false; + /* The buffers hold the old geometry: the next frame is copied whole. */ + for (unsigned int i = 0; i < DCP_IBOOT_SCANOUT_BUFS; i++) + ib->stale[i] = DRM_RECT_INIT(0, 0, INT_MAX / 2, INT_MAX / 2); + /* A pending frame has the old geometry. */ + iboot_cancel_swap_locked(ib); + /* As the bootloader swaps after a modeset. */ + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (ret) + dev_err(ib->dcp->dev, "set_surface failed: %d\n", ret); + return ret; +} + +/* + * The boot mode again: a display powered on without SET_MODE counts as idle + * to the firmware's AV stack, which powers the link off after 30 s. + */ +int dcp_iboot_set_boot_mode(struct dcp_iboot *ib) +{ + const struct iboot_timing_mode *best = NULL; + const struct iboot_color_mode *c; + int ret = -ENOENT; + + mutex_lock(&ib->lock); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + const struct iboot_timing_mode *t = &ib->tmodes[i]; + + if (!t->valid || le32_to_cpu(t->width) != ib->boot_w || + le32_to_cpu(t->height) != ib->boot_h || + iboot_refresh(t) > 60) + continue; + if (!best || le32_to_cpu(t->fps) > le32_to_cpu(best->fps)) + best = t; + } + c = iboot_find_color(ib); + if (best && c) + ret = iboot_set_mode_locked(ib, best, c); + mutex_unlock(&ib->lock); + return ret; +} + +/* + * The DCPAV service starts the firmware's idle power off timer when its video + * interface comes up: until a SET_MODE follows, it counts the powered-on + * display as idle and takes the link down 30 s later. The probe's SET_MODE + * comes before the interface starts, so one follows it here. + */ +void dcp_iboot_reset_mode(struct dcp_iboot *ib) +{ + const struct iboot_color_mode *c; + + mutex_lock(&ib->lock); + c = iboot_find_color(ib); + if (c && ib->powered && ib->mode_set) + iboot_set_mode_locked(ib, &ib->cur_mode, c); + mutex_unlock(&ib->lock); +} + +/* + * From the AFK receive work of the DPAV endpoint: let the firmware finish + * opening the interface before the SET_MODE, which waits for a reply that + * another endpoint's receive work completes. + */ +void dcp_iboot_av_started(struct dcp_iboot *ib) +{ + queue_delayed_work(system_percpu_wq, &ib->av_work, msecs_to_jiffies(1000)); +} + +static void iboot_crtc_atomic_enable(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + struct apple_dcp *dcp = ib->dcp; + const struct iboot_timing_mode *t; + const struct iboot_color_mode *c; + int ret; + + mutex_lock(&ib->lock); + t = iboot_find_mode(ib, &new->mode); + c = iboot_find_color(ib); + if (!t || !c) + goto out; + ib->enabled = true; + if (!ib->powered) { + /* The PHY starts cold first; the firmware then trains. */ + ret = ib->disp.phy->activate(&ib->disp); + if (ret) { + dev_err(dcp->dev, "PHY activation failed: %d\n", ret); + goto out; + } + /* A pipe powered on without a surface fetches from a null base. */ + ret = ibootep_set_surface(dcp, ib->scan_dva[ib->front], + le32_to_cpu(t->width), le32_to_cpu(t->height), + ALIGN(le32_to_cpu(t->width) * 4, 64)); + if (ret) { + dev_err(dcp->dev, "set_surface failed: %d\n", ret); + goto out; + } + ret = ibootep_set_power(dcp, true); + if (ret) { + dev_err(dcp->dev, "set_power failed: %d\n", ret); + goto out; + } + ib->powered = true; + } + if (ib->mode_set && !memcmp(t, &ib->cur_mode, sizeof(*t))) + goto out; + dev_info(dcp->dev, "modeset %ux%u@%d\n", le32_to_cpu(t->width), + le32_to_cpu(t->height), iboot_refresh(t)); + /* + * As the bootloader configures a display: query the sink and both mode + * lists again before SET_MODE, and look the mode up in the fresh list. + * The DPTX port stays connected; reconnecting it here drops the link + * and the HDMI firmware then fails SET_MODE. + */ + ret = ibootep_set_power(dcp, true); + if (!ret) + ret = ibootep_get_hpd(dcp, NULL, NULL) < 0; + if (!ret) + ret = dcp_iboot_get_modes(ib); + if (ret) + dev_err(dcp->dev, "refreshing the modes failed: %d\n", ret); + t = iboot_find_mode(ib, &new->mode); + c = iboot_find_color(ib); + if (!t || !c) + goto out; + iboot_set_mode_locked(ib, t, c); +out: + mutex_unlock(&ib->lock); +} + +static void iboot_crtc_atomic_disable(struct drm_crtc *crtc, + struct drm_atomic_commit *state) +{ + struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); + struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); + int ret, idx; + + /* A mode change: SET_MODE alone switches, as before. */ + if (new->active) + return; + /* + * After an unbind the firmware session is retained as it is, and the + * shutdown commit only releases the state. + */ + if (!drm_dev_enter(crtc->dev, &idx)) + return; + /* + * Display off (DPMS, blanking): the firmware stops the pipe and the + * monitor goes to sleep. The next enable sets the mode again. + */ + mutex_lock(&ib->lock); + ib->enabled = false; + iboot_cancel_swap_locked(ib); + if (ib->powered) { + ret = ibootep_set_power(ib->dcp, false); + if (ret) { + dev_err(ib->dcp->dev, "set_power off failed: %d\n", ret); + } else { + dev_info(ib->dcp->dev, "display off\n"); + /* Nothing scans out: power the PHY down as well. */ + if (!ib->disp.phy->deactivate(&ib->disp)) + ib->disp.port[0].link_rate = 0; + } + ib->powered = !!ret; + ib->mode_set = false; + } + mutex_unlock(&ib->lock); + drm_dev_exit(idx); +} + +static const struct drm_crtc_helper_funcs iboot_crtc_helper = { + .atomic_check = iboot_crtc_atomic_check, + .atomic_enable = iboot_crtc_atomic_enable, + .atomic_disable = iboot_crtc_atomic_disable, +}; + +static const struct drm_crtc_funcs iboot_crtc_funcs = { + .reset = drm_atomic_helper_crtc_reset, + .destroy = drm_crtc_cleanup, + .set_config = drm_atomic_helper_set_config, + .page_flip = drm_atomic_helper_page_flip, + .atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state, + .atomic_destroy_state = drm_atomic_helper_crtc_destroy_state, +}; + +static const struct drm_encoder_funcs iboot_encoder_funcs = { + .destroy = drm_encoder_cleanup, +}; + +/* Modeset before the plane update, which copies at the new geometry. */ +static const struct drm_mode_config_helper_funcs iboot_mode_config_helpers = { + .atomic_commit_tail = drm_atomic_helper_commit_tail_rpm, +}; + +static const struct drm_mode_config_funcs iboot_mode_config_funcs = { + /* fbdev writes reach the scanout buffer through the dirty damage */ + .fb_create = drm_gem_fb_create_with_dirty, + .atomic_check = drm_atomic_helper_check, + .atomic_commit = drm_atomic_helper_commit, +}; + +static void iboot_pd_reset_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(work, struct dcp_iboot, pd_reset_work); + struct t8152_display *disp = &ib->disp; + int ret; + + dev_info(ib->dcp->dev, "USB-C sink does not answer, entering DP alt mode again\n"); + /* The reset may finish between polls. Release the old link explicitly. */ + mutex_lock(&ib->lock); + iboot_cancel_swap_locked(ib); + ret = t8152_dptx_disconnect(disp, 0); + if (!ret) + ret = ibootep_set_power(ib->dcp, false); + if (!ret) { + ib->powered = false; + ib->mode_set = false; + ret = disp->phy->deactivate(disp); + } + if (ret) { + mutex_unlock(&ib->lock); + dev_err(ib->dcp->dev, "cannot release old DP link: %d\n", ret); + return; + } + disp->hpd = 0; + ret = t8152_pd_reconnect(disp); + mutex_unlock(&ib->lock); + if (ret) { + dev_err(ib->dcp->dev, "DP alt mode entry failed: %d\n", ret); + return; + } + drm_kms_helper_hotplug_event(&ib->drm); +} + +static void iboot_hpd_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(to_delayed_work(work), struct dcp_iboot, + hpd_work); + + if (!READ_ONCE(ib->ready)) + return; + drm_helper_hpd_irq_event(&ib->drm); + if (READ_ONCE(ib->ready)) + queue_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(250)); +} + +void dcp_iboot_kms_stop(struct dcp_iboot *ib) +{ + if (!ib->kms_work_ready) + return; + + cancel_delayed_work_sync(&ib->hpd_work); + hrtimer_cancel(&ib->swap_timer); + cancel_work_sync(&ib->swap_work); + cancel_work_sync(&ib->pd_reset_work); +} + +static void iboot_swap_stop(void *data) +{ + dcp_iboot_kms_stop(data); +} + +int dcp_iboot_kms_init(struct dcp_iboot *ib) +{ + struct drm_device *drm = &ib->drm; + u32 max_w = 3840, max_h = 2160; + int ret; + + ib->pending = -1; + INIT_WORK(&ib->swap_work, iboot_swap_work); + INIT_WORK(&ib->pd_reset_work, iboot_pd_reset_work); + INIT_DELAYED_WORK(&ib->hpd_work, iboot_hpd_work); + hrtimer_setup(&ib->swap_timer, iboot_swap_timer, CLOCK_MONOTONIC, + HRTIMER_MODE_ABS); + ib->kms_work_ready = true; + ret = devm_add_action_or_reset(ib->dcp->dev, iboot_swap_stop, ib); + if (ret) + return ret; + + for (unsigned int i = 0; i < ib->nr_tmodes; i++) { + max_w = max(max_w, le32_to_cpu(ib->tmodes[i].width)); + max_h = max(max_h, le32_to_cpu(ib->tmodes[i].height)); + } + + ret = drmm_mode_config_init(drm); + if (ret) + return ret; + ib->pd_reset_time = jiffies - 61 * HZ; + + drm->mode_config.min_width = 320; + drm->mode_config.min_height = 240; + drm->mode_config.max_width = max_w; + drm->mode_config.max_height = max_h; + drm->mode_config.preferred_depth = 24; + drm->mode_config.funcs = &iboot_mode_config_funcs; + drm->mode_config.helper_private = &iboot_mode_config_helpers; + + ret = drm_universal_plane_init(drm, &ib->plane, 0, &iboot_plane_funcs, + dcp_iboot_formats, ARRAY_SIZE(dcp_iboot_formats), + NULL, DRM_PLANE_TYPE_PRIMARY, NULL); + if (ret) + return ret; + drm_plane_helper_add(&ib->plane, &iboot_plane_helper); + drm_plane_enable_fb_damage_clips(&ib->plane); + + ret = drm_crtc_init_with_planes(drm, &ib->crtc, &ib->plane, NULL, + &iboot_crtc_funcs, NULL); + if (ret) + return ret; + drm_crtc_helper_add(&ib->crtc, &iboot_crtc_helper); + + ret = drm_encoder_init(drm, &ib->encoder, &iboot_encoder_funcs, + DRM_MODE_ENCODER_TMDS, NULL); + if (ret) + return ret; + ib->encoder.possible_crtcs = drm_crtc_mask(&ib->crtc); + + ret = drm_connector_init(drm, &ib->connector, &iboot_connector_funcs, + ib->disp.hdmi ? DRM_MODE_CONNECTOR_HDMIA : + DRM_MODE_CONNECTOR_DisplayPort); + if (ret) + return ret; + drm_connector_helper_add(&ib->connector, &iboot_connector_helper); + if (ib->disp.hpd_gpio || ib->disp.pd) + ib->connector.polled = DRM_CONNECTOR_POLL_CONNECT | + DRM_CONNECTOR_POLL_DISCONNECT; + if (ib->disp.pd) + ib->connector.polled = DRM_CONNECTOR_POLL_HPD; + ret = drm_connector_attach_encoder(&ib->connector, &ib->encoder); + if (ret) + return ret; + + drm_mode_config_reset(drm); + return 0; +} diff --git a/drivers/gpu/drm/apple/iomfb_iboot.c b/drivers/gpu/drm/apple/iomfb_iboot.c new file mode 100644 index 00000000000000..757b122dc8e42e --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_iboot.c @@ -0,0 +1,840 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * DCP_FIRMWARE_IBOOT: the T8152 DCPs, driven through their firmware's + * iBoot interface alone. + * + * The bootloader leaves a successful display's RTKit session running, or + * quiesces it after a failed setup, and leaves an unused DCPEXT's firmware + * loaded and waiting for an RTKit wake (apple,rtkit-wake). This adopts or + * wakes that session, stops the AFK endpoints the bootloader left running + * and starts the iBoot (disp0-service or dispext-service), DPAV and DPTX + * port endpoints, reconnects the DPTX port and asserts HPD, then registers + * a DRM device whose flips are iBoot SET_SURFACE calls (iboot_drm.c), in + * the order the bootloader brings the display up. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "afk.h" +#include "dcp.h" +#include "dcp-internal.h" +#include "ibootep.h" +#include "iomfb_iboot.h" +#include "t8152_display.h" + +#define DCP_IBOOT_HPD_TIMEOUT_MS 10000 +/* RTKit's oslog system endpoint */ +#define DCP_IBOOT_RTKIT_EP_OSLOG 8 +/* The coprocessor's CPU control (bit 4: run) and status registers */ +#define DCP_IBOOT_CPU_CONTROL 0x44 +#define DCP_IBOOT_CPU_CONTROL_RUN BIT(4) +#define DCP_IBOOT_CPU_STATUS 0x48 + +static void dcp_iboot_rtk_crashed(void *cookie, const void *crashlog, size_t size) +{ + struct apple_dcp *dcp = cookie; + + WRITE_ONCE(dcp->crashed, true); + dev_err(dcp->dev, "DCP firmware crashed\n"); +} + +static void dcp_iboot_rtk_recv(void *cookie, u8 endpoint, u64 message) +{ + struct apple_dcp *dcp = cookie; + struct apple_dcp_afkep *ep = NULL; + + if (READ_ONCE(dcp->quiescing)) + return; + switch (endpoint) { + case DISP0_ENDPOINT: + ep = READ_ONCE(dcp->ibootep); + break; + case DPTX_CONTROLLER_ENDPOINT: + ep = READ_ONCE(dcp->dptx_controller_ep); + break; + case DPTX_ENDPOINT: + ep = READ_ONCE(dcp->dptxep); + break; + } + if (IS_ERR_OR_NULL(ep)) { + dev_dbg(dcp->dev, "message %#llx for idle endpoint %#x\n", + message, endpoint); + return; + } + afk_receive_message(ep, message); +} + +/* + * Buffers the firmware placed in its own DART mappings, or new ones, as for + * every DCP; and a woken DCPEXT's oslog ring. + */ +static int dcp_iboot_rtk_shmem_setup(void *cookie, u8 endpoint, + struct apple_rtkit_shmem *bfr) +{ + struct apple_dcp *dcp = cookie; + + /* + * A woken DCPEXT offers the oslog ring in its own firmware segment, at + * an address only the firmware's retained DART tables map. Linux never + * reads that ring and only acknowledges its write counters: take it as + * the firmware's, without a CPU mapping. The request needs no reply; + * the bootloader sends none either. + */ + if (bfr->iova && endpoint == DCP_IBOOT_RTKIT_EP_OSLOG) { + struct iommu_domain *domain = iommu_get_domain_for_dev(dcp->dev); + + if (domain && !iommu_iova_to_phys(domain, bfr->iova)) { + bfr->is_mapped = true; + return 0; + } + } + return dcp_rtk_shmem_setup(cookie, bfr); +} + +static void dcp_iboot_rtk_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +{ + /* The firmware's oslog ring, taken without a mapping */ + if (bfr->is_mapped && !bfr->buffer) + return; + dcp_rtk_shmem_destroy(cookie, bfr); +} + +static bool dcp_iboot_rtk_syslog_debug(void *cookie, const char *context, + const char *message) +{ + /* Surface logging through fbcon would itself submit another surface. */ + return strstr(message, "setSurfaceRequest") || + strstr(message, "swap_submit_dcp") || + strstr(message, "validateRequest: inSize"); +} + +static const struct apple_rtkit_ops dcp_iboot_rtkit_ops = { + .crashed = dcp_iboot_rtk_crashed, + .recv_message = dcp_iboot_rtk_recv, + .shmem_setup_ep = dcp_iboot_rtk_shmem_setup, + .shmem_destroy = dcp_iboot_rtk_shmem_destroy, + .syslog_is_debug = dcp_iboot_rtk_syslog_debug, +}; + +static bool dcp_iboot_handoff_quiesced(struct dcp_iboot *ib) +{ + struct device_node *chosen __free(device_node) = of_find_node_by_path("/chosen"); + const char *version; + u32 running; + + if (ib->disp.hdmi || !chosen) + return false; + if (!of_property_read_u32(chosen, "apple,dcp-rtkit-running", &running)) + return running == 0; + /* + * This older J873 loader predates the state property. Its failed + * display setup quiesces DCP and keeps iBoot's placeholder framebuffer; + * a successful setup hands over ON. Restrict this fallback to the + * verified loader build, rather than guessing for other handoffs. + */ + if (of_property_read_string(chosen, "asahi,m1n1-stage2-version", &version) || + strcmp(version, "v0.1.0-259-ga30a589a")) + return false; + for_each_child_of_node_scoped(chosen, np) { + u32 width, height; + + if (of_device_is_compatible(np, "simple-framebuffer") && + !of_property_read_u32(np, "width", &width) && + !of_property_read_u32(np, "height", &height)) + return width == 640 && height == 1136; + } + return false; +} + +/* The unused DCPEXT firmware is loaded and powered by iBoot. */ +static int dcp_iboot_check_wake(struct apple_dcp *dcp) +{ + struct platform_device *pdev = to_platform_device(dcp->dev); + struct resource *res; + void __iomem *psd, *coproc; + + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "coproc-psd"); + if (!res) + return -EINVAL; + psd = devm_ioremap(dcp->dev, res->start, resource_size(res)); + if (!psd) + return -ENOMEM; + /* A read from the coprocessor while gated hangs the machine. */ + if (readl(psd + 0x80) & 7) + return -ENODEV; + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "coproc"); + if (!res) + return -EINVAL; + coproc = devm_ioremap(dcp->dev, res->start, resource_size(res)); + if (!coproc) + return -ENOMEM; + dev_info(dcp->dev, "firmware handoff: CPU control %#x status %#x\n", + readl(coproc + DCP_IBOOT_CPU_CONTROL), + readl(coproc + DCP_IBOOT_CPU_STATUS)); + return (readl(coproc + DCP_IBOOT_CPU_CONTROL) & + DCP_IBOOT_CPU_CONTROL_RUN) ? 0 : -ENODEV; +} + +/* + * Wake only a quiesced session: IOP INIT on a running DCP can panic it. A + * running one is taken as it runs, without the HELLO/EPMAP handshake; + * its AFK endpoints are then registered as they start (hw.afk_adopt_endpoints). + */ +static int dcp_iboot_boot(struct dcp_iboot *ib) +{ + struct apple_dcp *dcp = ib->dcp; + bool wake = of_property_read_bool(dcp->dev->of_node, "apple,rtkit-wake"); + struct apple_rtkit *rtk; + int ret; + + if ((!ib->disp.hdmi && wake) || dcp_iboot_handoff_quiesced(ib)) { + if (wake) { + ret = dcp_iboot_check_wake(dcp); + if (ret) + return ret; + } + rtk = apple_rtkit_init(dcp->dev, dcp, NULL, 0, &dcp_iboot_rtkit_ops); + if (IS_ERR(rtk)) + return PTR_ERR(rtk); + dcp->rtk = rtk; + ret = apple_rtkit_wake(rtk); + dev_info(dcp->dev, "quiesced DCP wake: %d\n", ret); + return ret; + } + rtk = apple_rtkit_init_adopted(dcp->dev, dcp, NULL, 0, &dcp_iboot_rtkit_ops); + if (IS_ERR(rtk)) + return PTR_ERR(rtk); + dcp->rtk = rtk; + return apple_rtkit_adopt_running(rtk); +} + +/* + * The display pipe scans out through dart-disp0, the DCP fetches through + * dart-dcp. Both are locked with their own live root, so each needs its own + * device and domain: one domain spanning both would publish dart-dcp's root + * into dart-disp0 and drop the scanout mappings the bootloader left there + * (the pipe then faults, IOMFB axi_rd_err). Scanout buffers are allocated on + * the DCP device and mapped into the scanout domain at the same address. + */ +static int dcp_iboot_scanout_init(struct dcp_iboot *ib) +{ + struct device *dev = ib->dcp->dev; + struct device_node *np __free(device_node) = + of_get_child_by_name(dev->of_node, "scanout"); + int ret; + + if (!np) + return -ENODEV; + ib->scanout = of_platform_device_create(np, NULL, dev); + if (!ib->scanout) + ib->scanout = of_find_device_by_node(np); + if (!ib->scanout) + return -ENODEV; + ret = dma_set_mask_and_coherent(&ib->scanout->dev, DMA_BIT_MASK(64)); + if (ret) + return ret; + ret = of_dma_configure(&ib->scanout->dev, np, true); + if (ret) + return ret; + ib->scanout_dom = iommu_get_domain_for_dev(&ib->scanout->dev); + return ib->scanout_dom ? 0 : -ENODEV; +} + +/* Firmware-visible memory: never freed, the firmware may still use it. */ +static int dcp_iboot_dma_alloc(struct dcp_iboot *ib, struct dcp_iboot_dma *dma, + size_t size) +{ + dma->size = PAGE_ALIGN(size); + dma->cpu = dma_alloc_coherent(ib->dcp->dev, dma->size, &dma->iova, + GFP_KERNEL); + return dma->cpu ? 0 : -ENOMEM; +} + +static void *dcp_iboot_vmap_wc(struct sg_table *sgt) +{ + unsigned int n = 0, count = 0; + struct sg_page_iter iter; + struct page **pages; + void *vaddr; + + for_each_sgtable_page(sgt, &iter, 0) + count++; + pages = kvmalloc_array(count, sizeof(*pages), GFP_KERNEL); + if (!pages) + return NULL; + for_each_sgtable_page(sgt, &iter, 0) + pages[n++] = sg_page_iter_page(&iter); + vaddr = vmap(pages, count, VM_MAP, pgprot_writecombine(PAGE_KERNEL)); + kvfree(pages); + return vaddr; +} + +/* + * The display pipe's DART is locked and comes with the firmware's own + * mappings. The address the coprocessor's allocator handed out for a scanout + * buffer can be one of them, and mapping over it corrupts what the pipe + * fetches every frame (the picture flickers). Start at @dva and go down until + * a range with no mapping is found. + */ +static dma_addr_t dcp_iboot_scan_free_dva(struct dcp_iboot *ib, dma_addr_t dva, + size_t size) +{ + const size_t step = SZ_16K; + + size = ALIGN(size, step); + for (int tries = 0; tries < 64 && dva >= size; tries++) { + size_t off; + + for (off = 0; off < size; off += step) + if (iommu_iova_to_phys(ib->scanout_dom, dva + off)) + break; + if (off == size) + return dva; + dev_info(ib->dcp->dev, "scanout DART: %pad+%#zx is in use, moving down\n", + &dva, off); + dva -= size; + } + return 0; +} + +/* One scanout buffer: allocated, cleared, mapped for the CPU and the pipe. */ +static int dcp_iboot_scan_alloc(struct dcp_iboot *ib, int i, size_t size) +{ + struct dcp_iboot_dma *fb = &ib->scan[i]; + struct sg_table sgt; + ssize_t mapped; + dma_addr_t dva; + int ret; + + ret = dcp_iboot_dma_alloc(ib, fb, size); + if (ret) + return ret; + ret = dma_get_sgtable(ib->dcp->dev, &sgt, fb->cpu, fb->iova, fb->size); + if (ret) + return ret; + /* + * The DCP is coherent, the display pipe is not: it reads memory past + * the CPU caches, and frames written through the cacheable mapping + * show only once evicted. Write through a write-combined mapping of + * the same pages, with the zeroing of the allocation cleaned out first. + */ + arch_wb_cache_pmem(fb->cpu, fb->size); + ib->scan_wc[i] = dcp_iboot_vmap_wc(&sgt); + if (!ib->scan_wc[i]) { + sg_free_table(&sgt); + return -ENOMEM; + } + memset(ib->scan_wc[i], 0, fb->size); + /* + * Cacheable, as the bootloader maps scanout buffers: the pipe faults on + * entries with the DART's no-cache bit (IOMFB axi_rd_err). + */ + dva = dcp_iboot_scan_free_dva(ib, fb->iova, fb->size); + if (!dva) { + sg_free_table(&sgt); + return -ENOSPC; + } + mapped = iommu_map_sgtable(ib->scanout_dom, dva, &sgt, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); + sg_free_table(&sgt); + if (mapped < (ssize_t)fb->size) + return mapped < 0 ? mapped : -ENOMEM; + ib->scan_dva[i] = dva; + dev_info(ib->dcp->dev, "scanout buffer %d: %zu bytes at %pad\n", i, + fb->size, &dva); + return 0; +} + +/* + * A fresh iBoot session has no surface. Whenever the pipe runs without one + * (the link retrains when the DPTX services restart, SET_MODE turns it on), + * it fetches from a null base and the firmware takes an NMI (IOMFB + * axi_rd_err). Hand it a black buffer of the boot mode at once, sized from + * the bootloader's simple-framebuffer. + */ +static int dcp_iboot_boot_surface(struct dcp_iboot *ib) +{ + /* + * The boot display's framebuffer is /chosen's; the bootloader adds the + * second display's (HDMI) at the root. + */ + struct device_node *chosen __free(device_node) = + of_find_node_by_path("/chosen"); + struct device_node *parent __free(device_node) = + ib->disp.dp_source ? + of_find_node_by_path("/") : of_node_get(chosen); + u32 width = 1280, height = 720, stride = 1280 * 4; + size_t size; + int ret; + + for_each_child_of_node_scoped(parent, np) { + struct resource res; + + if (!of_device_is_compatible(np, "simple-framebuffer")) + continue; + of_property_read_u32(np, "width", &width); + of_property_read_u32(np, "height", &height); + of_property_read_u32(np, "stride", &stride); + /* + * Take the display over from simpledrm on the bootloader's + * framebuffer, so it does not shadow this driver's output + * (fbcon on a framebuffer nothing scans out). + */ + if (!of_address_to_resource(np, 0, &res)) { + ret = aperture_remove_conflicting_devices(res.start, + resource_size(&res), + dcp_iboot_driver_name()); + if (ret) + dev_warn(ib->dcp->dev, "simpledrm stays: %d\n", ret); + } + break; + } + /* + * Large enough for the largest mode: while a SET_MODE switches, the + * pipe briefly scans the current surface with the new mode's size. + * A monitor may first appear after probe, with a larger mode list. + */ + size = max_t(size_t, (size_t)stride * height, 3840 * 2160 * 4); + for (unsigned int i = 0; i < ib->nr_tmodes; i++) + size = max_t(size_t, size, (size_t)le32_to_cpu(ib->tmodes[i].width) * + le32_to_cpu(ib->tmodes[i].height) * 4); + ib->boot_w = width; + ib->boot_h = height; + ib->boot_stride = stride; + for (int i = 0; i < ARRAY_SIZE(ib->scan); i++) { + ret = dcp_iboot_scan_alloc(ib, i, size); + if (ret) + return ret; + } + ib->front = 0; + ret = ibootep_set_surface(ib->dcp, ib->scan_dva[0], width, height, stride); + dev_info(ib->dcp->dev, "boot surface %ux%u at %pad: %d\n", width, height, + &ib->scan_dva[0], ret); + return ret; +} + +/* Both mode lists of the current sink; a list is kept when its query fails. */ +int dcp_iboot_get_modes(struct dcp_iboot *ib) +{ + struct iboot_timing_mode *tmodes; + struct iboot_color_mode *cmodes; + unsigned int count; + int ret; + + ret = ibootep_get_timing_modes(ib->dcp, &tmodes, &count); + if (ret) + return ret; + kfree(ib->tmodes); + ib->tmodes = tmodes; + ib->nr_tmodes = count; + ret = ibootep_get_color_modes(ib->dcp, &cmodes, &count); + if (ret) + return ret; + kfree(ib->cmodes); + ib->cmodes = cmodes; + ib->nr_cmodes = count; + return 0; +} + +/* + * Wait until the firmware reports a sink with modes, as the bootloader does. + * Nothing on the iBoot interface announces the sink, so GET_HPD is asked + * every 100 ms; the J873g ports took 268 to 328 ms after power on. + */ +int dcp_iboot_wait_hpd(struct dcp_iboot *ib) +{ + unsigned long timeout = jiffies + msecs_to_jiffies(DCP_IBOOT_HPD_TIMEOUT_MS); + u32 timings = 0, colors = 0; + int hpd; + + do { + hpd = ibootep_get_hpd(ib->dcp, &timings, &colors); + if (hpd > 0 && timings && colors) { + dev_info(ib->dcp->dev, "sink: %u timing, %u color modes\n", + timings, colors); + return 0; + } + msleep(100); + } while (time_before(jiffies, timeout)); + + dev_err(ib->dcp->dev, "no sink (hpd %d, %u timing, %u color modes)\n", hpd, + timings, colors); + return hpd < 0 ? hpd : -ENODEV; +} + +static void dcp_iboot_av_work(struct work_struct *work) +{ + struct dcp_iboot *ib = container_of(to_delayed_work(work), struct dcp_iboot, + av_work); + + if (READ_ONCE(ib->ready)) + dcp_iboot_reset_mode(ib); +} + +/* + * The DPAV controller endpoint's services take no host commands, but the + * firmware expects all of them opened: its video interface powers the + * display on and starts its idle power off timer, so SET_MODE follows once + * that one is up. + */ +static void dcp_iboot_dpav_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct dcp_iboot *ib = READ_ONCE(service->ep->dcp->iboot); + + if (ib && name && strstr(name, "dcpav-video-interface")) + dcp_iboot_av_started(ib); +} + +static const struct apple_epic_service_ops dcp_iboot_dpav_ops = { + .name = "dcpav", + .reusable = true, + .init = dcp_iboot_dpav_init, +}; + +static unsigned int dcp_iboot_ep_services(struct apple_dcp_afkep *ep) +{ + unsigned int count = 0; + + for (unsigned int i = 0; i < AFK_MAX_CHANNEL; i++) + count += READ_ONCE(ep->services[i].enabled); + return count; +} + +/* + * The endpoint's services as it announces them, up to @expected within the + * AFK timeout; none is an error, fewer a warning. + */ +static int dcp_iboot_wait_services(struct apple_dcp *dcp, + struct apple_dcp_afkep *ep, unsigned int expected) +{ + unsigned int count; + + wait_event_timeout(ep->service_wq, dcp_iboot_ep_services(ep) >= expected, + msecs_to_jiffies(dcp->hw.afk_timeout_ms)); + count = dcp_iboot_ep_services(ep); + if (!count) { + dev_err(dcp->dev, "endpoint %#x announced no service\n", ep->endpoint); + return -ETIMEDOUT; + } + if (count < expected) + dev_warn(dcp->dev, "endpoint %#x: %u of %u services\n", ep->endpoint, + count, expected); + return 0; +} + +static int dcp_iboot_start_ep(struct apple_dcp *dcp, u32 endpoint, + struct apple_dcp_afkep **slot, + const struct apple_epic_service_ops *ops, + unsigned int expected) +{ + struct apple_dcp_afkep *ep = afk_init(dcp, endpoint, NULL); + int ret; + + if (IS_ERR(ep)) + return PTR_ERR(ep); + ep->unmatched_ops = ops; + WRITE_ONCE(*slot, ep); + ret = afk_start(ep); + if (ret) { + dev_err(dcp->dev, "endpoint %#x did not start: %d\n", endpoint, ret); + return ret; + } + return dcp_iboot_wait_services(dcp, ep, expected); +} + +/* The iBoot service is ready once its init callback has run. */ +static int dcp_iboot_start_iboot(struct apple_dcp *dcp) +{ + int ret; + + ret = ibootep_init(dcp); + if (ret) + return ret; + wait_event_timeout(dcp->ibootep->service_wq, ibootep_is_ready(dcp), + msecs_to_jiffies(dcp->hw.afk_timeout_ms)); + return ibootep_is_ready(dcp) ? 0 : -ENODEV; +} + +/* + * Once adopted, the DCP may still DMA into our buffers. Stop the host side: + * no more endpoint work or messages, no KMS work, and RTKit detached with + * its buffers retained. Firmware-visible storage stays allocated until + * reboot. + */ +static void dcp_iboot_detach(struct dcp_iboot *ib) +{ + struct apple_dcp *dcp = ib->dcp; + + WRITE_ONCE(ib->ready, false); + WRITE_ONCE(dcp->quiescing, true); + cancel_delayed_work_sync(&ib->av_work); + dcp_iboot_kms_stop(ib); + afk_quiesce(dcp->ibootep); + afk_quiesce(dcp->dptx_controller_ep); + afk_quiesce(dcp->dptxep); + if (!IS_ERR_OR_NULL(dcp->rtk)) + apple_rtkit_free_retaining_buffers(dcp->rtk); + WRITE_ONCE(dcp->rtk, NULL); +} + +static int dcp_iboot_start(struct dcp_iboot *ib) +{ + struct t8152_display *disp = &ib->disp; + struct apple_dcp *dcp = ib->dcp; + struct device *dev = dcp->dev; + bool sink = true; + int ret; + + ret = dcp_iboot_start_iboot(dcp); + if (ret) + return dev_err_probe(dev, ret, "no disp0-service\n"); + /* + * The new iBoot session has dropped the surface while the pipe still + * runs: it fetches from a null base (IOMFB axi_rd_err, firmware NMI) + * unless it is powered off at once. It comes back on below, after a + * surface is set. + */ + ret = ibootep_set_power(dcp, false); + if (ret) + return dev_err_probe(dev, ret, "display power off failed\n"); + ret = dcp_iboot_start_ep(dcp, DPTX_CONTROLLER_ENDPOINT, + &dcp->dptx_controller_ep, &dcp_iboot_dpav_ops, 4); + if (ret) + return dev_err_probe(dev, ret, "no DPAV controllers\n"); + ret = dcp_iboot_start_ep(dcp, DPTX_ENDPOINT, &dcp->dptxep, + &t8152_dptx_port_ops, 2); + if (ret) + return dev_err_probe(dev, ret, "no DPTX port service\n"); + if (disp->pd) { + ret = t8152_dptx_disconnect(disp, 0); + if (ret) + return dev_err_probe(dev, ret, "cannot release inherited DP link\n"); + } + + /* + * USB-C negotiation can outlive probe or fail while a monitor sleeps. + * Register the connector first; the hotplug path owns all USB-C links. + */ + if (disp->pd) + sink = false; + if (sink) { + ret = t8152_dptx_connect(disp, 0); + if (ret) + return dev_err_probe(dev, ret, "DPTX connect failed\n"); + ret = t8152_dptx_set_hpd(disp, 0, true); + if (ret) + return dev_err_probe(dev, ret, "DPTX hotplug failed\n"); + ret = dcp_iboot_wait_hpd(ib); + if (ret) + return ret; + ret = dcp_iboot_get_modes(ib); + if (ret) + return dev_err_probe(dev, ret, "no modes\n"); + } + ret = dcp_iboot_boot_surface(ib); + if (ret) + return dev_err_probe(dev, ret, "no boot surface\n"); + /* Keep an idle connector registered while the PD controller negotiates. */ + if (!sink) { + dev_info(dev, "waiting for a USB-C display\n"); + goto register_kms; + } + disp->hpd = 1; + /* + * Without the bootloader's link (no display on the port at boot) the + * PHY starts cold, the right way round for the plug. + */ + if (disp->phy->detect && disp->phy->set_orientation) { + bool flipped; + + if (disp->phy->detect(disp, &flipped) > 0) { + if (disp->phy->select) + disp->phy->select(disp); + disp->phy->set_orientation(disp, flipped); + } + } + ret = disp->phy->activate(disp); + if (ret) + return dev_err_probe(dev, ret, "PHY activation failed\n"); + /* While the display is still off and the firmware does no AUX. */ + dcp_iboot_update_edid(ib); + ret = ibootep_set_power(dcp, true); + if (ret) + return dev_err_probe(dev, ret, "set_power failed\n"); + ib->powered = true; + dev_info(dev, "%u timing modes, %u color modes\n", ib->nr_tmodes, + ib->nr_cmodes); + +register_kms: + ret = dcp_iboot_kms_init(ib); + if (ret) + return ret; + if (sink) { + ret = dcp_iboot_set_boot_mode(ib); + if (ret) + dev_warn(dev, "boot mode not set again: %d\n", ret); + } + ret = drm_dev_register(&ib->drm, 0); + if (ret) + return ret; + WRITE_ONCE(ib->ready, true); + if (disp->hpd_gpio || disp->pd) + drmm_kms_helper_poll_init(&ib->drm); + if (disp->pd) + queue_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(250)); + drm_client_setup(&ib->drm, NULL); + return 0; +} + +/* + * Without a USB-C display the bootloader drives HDMI from the main DCP + * (source 0) and never starts DCPEXT0. hdmi_np: DCPEXT0's node, which + * describes the HDMI PHY. + */ +int dcp_iboot_probe(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + struct device_node *hdmi_np __free(device_node) = t8152_hdmi_node(); + int source = hdmi_np ? t8152_hdmi_source(hdmi_np) : -ENODEV; + struct t8152_display *disp; + struct dcp_iboot *ib; + u32 live; + int ret; + + if (dev->of_node == hdmi_np && source != 1 && + !of_property_present(dev->of_node, "apple,usb-c-ports")) { + dev_info(dev, "%s\n", source == 0 ? "HDMI is on the main DCP" : + "no bootloader HDMI link to adopt"); + return -ENODEV; + } + + /* + * The bootloader's AFK endpoint hand-off: without it there is no + * telling whether an endpoint is live, and an INIT on a live one + * asserts in the firmware. + */ + ret = of_property_read_u32(dev->of_node, "apple,afk-active-endpoints", &live); + if (ret || live & ~GENMASK(15, 0)) + return dev_err_probe(dev, -EINVAL, + "bootloader AFK endpoint handoff required\n"); + + ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)); + if (ret) + return ret; + + ib = dcp_iboot_alloc(dev); + if (IS_ERR(ib)) + return PTR_ERR(ib); + ib->dcp = dcp; + disp = &ib->disp; + disp->dcp = dcp; + disp->dev = dev; + disp->dp_source = dev->of_node == hdmi_np ? 1 : 0; + of_property_read_u32(dev->of_node, "apple,dp-source", &disp->dp_source); + if (disp->dp_source > 2) + return -EINVAL; + of_property_read_u32(dev->of_node, "apple,die", &disp->die); + dcp->afk_live_endpoints = live; + mutex_init(&ib->lock); + INIT_DELAYED_WORK(&ib->av_work, dcp_iboot_av_work); + + ret = dcp_iboot_scanout_init(ib); + if (ret) + return dev_err_probe(dev, ret, "no scanout DART stream\n"); + + disp->hdmi = source >= 0 && source == disp->dp_source; + if (disp->hdmi && dev->of_node != hdmi_np) + dev_info(dev, "HDMI from the main DCP (no USB-C display at boot)\n"); + /* Read only: the pin belongs to a controller the AOP runs. */ + disp->hpd_gpio = NULL; + if (disp->hdmi) + disp->hpd_gpio = devm_fwnode_gpiod_get(dev, of_fwnode_handle(hdmi_np), + "hpd", GPIOD_ASIS, "hpd"); + if (PTR_ERR(disp->hpd_gpio) == -ENOENT) + disp->hpd_gpio = NULL; + if (IS_ERR(disp->hpd_gpio)) + return dev_err_probe(dev, PTR_ERR(disp->hpd_gpio), "no HPD GPIO\n"); + disp->hpd = 0; + ret = disp->hdmi ? t8152_hdmi_init(disp, hdmi_np) : t8152_atc_init(disp); + if (ret) + return dev_err_probe(dev, ret, "no DisplayPort PHY\n"); + /* Nobody has HDMI from the bootloader: it is one of the shared ports. */ + if (!disp->hdmi && source < 0 && hdmi_np) { + ret = t8152_hdmi_port_init(disp, hdmi_np); + if (ret) + return dev_err_probe(dev, ret, "no shared HDMI port\n"); + } + + WRITE_ONCE(dcp->t8152, disp); + WRITE_ONCE(dcp->iboot, ib); + ret = dcp_iboot_boot(ib); + if (IS_ERR_OR_NULL(dcp->rtk)) { + dcp->rtk = NULL; + return dev_err_probe(dev, ret, "cannot adopt the DCP\n"); + } + /* + * From here on the DCP may DMA into what this driver gives it, and + * there is no safe way to stop it: retain the session until reboot. + */ + if (dcp_retain_live_session(dcp)) { + dev_warn(dev, "live session not recorded; its DMA stays allocated\n"); + WRITE_ONCE(dcp->retain_dma, true); + } + if (ret) + dev_err(dev, "cannot adopt the DCP: %d\n", ret); + else + ret = dcp_iboot_start(ib); + if (!ret) + return 0; + + /* + * Gate RX before draining endpoint work; keep RTKit available until + * every sender has stopped. Do not reclaim firmware-visible storage + * or let the driver core retry a partially started session. + */ + dcp_iboot_detach(ib); + dev_err(dev, "initialization failed (%d); live DMA resources retained until reboot\n", + ret); + return 0; +} + +/* An unbind: the DRM device goes, the firmware session and its DMA stay. */ +void dcp_iboot_remove(struct apple_dcp *dcp) +{ + struct dcp_iboot *ib = dcp->iboot; + bool registered; + + if (!ib) + return; + registered = READ_ONCE(ib->ready); + if (ib->drm.mode_config.poll_enabled) + drm_kms_helper_poll_disable(&ib->drm); + if (!READ_ONCE(dcp->quiescing)) + dcp_iboot_detach(ib); + if (registered) { + drm_dev_unplug(&ib->drm); + /* Drops the committed state's connector reference. */ + drm_atomic_helper_shutdown(&ib->drm); + } +} diff --git a/drivers/gpu/drm/apple/iomfb_iboot.h b/drivers/gpu/drm/apple/iomfb_iboot.h new file mode 100644 index 00000000000000..9c2268604b0175 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_iboot.h @@ -0,0 +1,139 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * DCP_FIRMWARE_IBOOT: a T8152 DCP driven through its firmware's iBoot + * interface alone, with a DRM device of its own (iomfb_iboot.c, iboot_drm.c). + */ +#ifndef __APPLE_IOMFB_IBOOT_H__ +#define __APPLE_IOMFB_IBOOT_H__ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "ibootep.h" +#include "t8152_display.h" + +struct apple_dcp; +struct device; +struct drm_edid; +struct iommu_domain; +struct platform_device; + +struct dcp_iboot_dma { + void *cpu; + dma_addr_t iova; + size_t size; +}; + +/* + * Scanout buffers, each for the largest mode: a frame is copied into one not + * on screen, which SET_SURFACE then shows. Copying into the buffer being + * scanned out tore every frame. Three, so the one written next left the + * screen a frame ago. + */ +#define DCP_IBOOT_SCANOUT_BUFS 3 + +struct dcp_iboot { + struct drm_device drm; + struct apple_dcp *dcp; + struct t8152_display disp; + + /* The DRM device is registered and the session up. */ + bool ready; + bool kms_work_ready; + + /* The scanout DART's own device and domain (dcp_iboot_scanout_init()). */ + struct platform_device *scanout; + struct iommu_domain *scanout_dom; + struct dcp_iboot_dma scan[DCP_IBOOT_SCANOUT_BUFS]; + /* their pages write-combined: the pipe does not snoop the CPU caches */ + void *scan_wc[DCP_IBOOT_SCANOUT_BUFS]; + /* their addresses in the display pipe's DART */ + dma_addr_t scan_dva[DCP_IBOOT_SCANOUT_BUFS]; + /* scan[front] is on screen (or set as the surface at the next power on) */ + unsigned int front; + /* the part of the current picture scan[i] does not hold yet */ + struct drm_rect stale[DCP_IBOOT_SCANOUT_BUFS]; + /* when scan[i] stopped being the requested surface */ + ktime_t retired[DCP_IBOOT_SCANOUT_BUFS]; + /* the last SET_SURFACE of a new buffer */ + ktime_t last_swap; + /* + * A frame written within one refresh of the last swap waits in + * scan[pending] (-1: none) for swap_timer, at most one swap per + * refresh; a newer frame overwrites it. + */ + int pending; + u32 pending_w, pending_h, pending_pitch; + struct hrtimer swap_timer; + struct work_struct swap_work; + u32 boot_w, boot_h, boot_stride; + + /* the sink's EDID, read through the PHY (NULL if unavailable) */ + const struct drm_edid *edid; + + /* iBoot state below, under lock */ + struct mutex lock; + bool enabled; + bool powered; + struct iboot_timing_mode *tmodes; + unsigned int nr_tmodes; + struct iboot_color_mode *cmodes; + unsigned int nr_cmodes; + struct iboot_timing_mode cur_mode; + bool mode_set; + /* SET_MODE of cur_mode failed; the next plug sets it again */ + bool mode_failed; + /* USB-C: re-enter DP alt mode when the sink stopped answering */ + struct work_struct pd_reset_work; + unsigned long pd_reset_time; + /* + * The DPAV video interface started: SET_MODE again, or the + * firmware's idle power off timer takes the link down 30 s later. + */ + struct delayed_work av_work; + struct delayed_work hpd_work; + + struct drm_plane plane; + struct drm_crtc crtc; + struct drm_encoder encoder; + struct drm_connector connector; +}; + +static inline struct dcp_iboot *to_dcp_iboot(struct drm_device *drm) +{ + return container_of(drm, struct dcp_iboot, drm); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) +/* iomfb_iboot.c */ +int dcp_iboot_probe(struct apple_dcp *dcp); +void dcp_iboot_remove(struct apple_dcp *dcp); +int dcp_iboot_wait_hpd(struct dcp_iboot *ib); +int dcp_iboot_get_modes(struct dcp_iboot *ib); + +/* iboot_drm.c */ +struct dcp_iboot *dcp_iboot_alloc(struct device *dev); +const char *dcp_iboot_driver_name(void); +int dcp_iboot_kms_init(struct dcp_iboot *ib); +void dcp_iboot_kms_stop(struct dcp_iboot *ib); +int dcp_iboot_set_boot_mode(struct dcp_iboot *ib); +void dcp_iboot_update_edid(struct dcp_iboot *ib); +void dcp_iboot_reset_mode(struct dcp_iboot *ib); +void dcp_iboot_av_started(struct dcp_iboot *ib); +#else +static inline int dcp_iboot_probe(struct apple_dcp *dcp) { return -ENODEV; } +static inline void dcp_iboot_remove(struct apple_dcp *dcp) { } +#endif + +#endif From 4c54a002da2150db07f783b4d88fc12365f75ddb Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 10:07:11 +0100 Subject: [PATCH 0330/1514] arm64: dts: apple: t8152: describe the display DARTs as Gen3 The DARTs of the main DCP and of DCPEXT0, and those of their display pipes (ADT dart-dcp, dart-disp0, dart-dcpext0 and dart-dispext0), belong to the SPTM, and the bootloader hands them over locked. Their TLB is invalidated through the SoC's TLB invalidation aperture (dart-tlbi-aperture), not through the T8110 TLB command register. Describe them as apple,t8152-dart-gen3 with their windows in the aperture (ADT tlbi-aperture-offset 0x400 and 0x480). The second register window of the display pipe DARTs, their SMMU instance, is not used and is dropped. The other display DARTs keep their description until something uses them. Signed-off-by: Thomas Glanzmann --- .../boot/dts/apple/t8152-peripherals.dtsi | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi index 578e7730ef5f15..cab3001ab9086d 100644 --- a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi @@ -123,17 +123,20 @@ }; dcp_dart: iommu@286340000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x2 0x86340000 0x0 0x20000>; + compatible = "apple,t8152-dart-gen3"; + reg = <0x2 0x86340000 0x0 0x20000>, + <0x2 0x00000400 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; }; disp0_dart: iommu@286300000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; + compatible = "apple,t8152-dart-gen3"; reg = <0x2 0x86300000 0x0 0xc000>, - <0x2 0x86314000 0x0 0x4000>; + <0x2 0x00000400 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; @@ -148,17 +151,20 @@ }; dcpext0_dart: iommu@32a340000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x3 0x2a340000 0x0 0x20000>; + compatible = "apple,t8152-dart-gen3"; + reg = <0x3 0x2a340000 0x0 0x20000>, + <0x2 0x00000480 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; }; dispext0_dart: iommu@32a300000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; + compatible = "apple,t8152-dart-gen3"; reg = <0x3 0x2a300000 0x0 0xc000>, - <0x3 0x2a314000 0x0 0x4000>; + <0x2 0x00000480 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; status = "disabled"; From 6dce5ece61dfefe5353d229377cf79cdee60ab1e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 10:08:50 +0100 Subject: [PATCH 0331/1514] arm64: dts: apple: j873: add the USB-C and HDMI displays The bootloader trains the J873g displays through the DCP firmware's iBoot interface and hands both DCPs over with their RTKit sessions running: the main DCP drives a USB-C display on one of the rear ports, or HDMI when no USB-C display is attached at boot, and DCPEXT0 drives the HDMI port next to a USB-C display. Add both DCPs with their post-office mailboxes and enable their Gen3 DARTs, with the DMA window in the upper half of the firmware's 64 GiB window, above the firmware's and the bootloader's mappings. The main DCP lists the three rear USB-C ports with their ATC PHY, PMGR power states, tunables and PD controllers on nub-spmi-a0. DCPEXT0 has the HDMI PHY, the read-only PMGR power states of the PHY and of its CPU, and the HPD line of the DP-to-HDMI converter on the AOP's GPIO controller, which is polled since its interrupts belong to the AOP. Each DCP has the AP DisplayPort AUX controller that reads the sink's EDID. Resources are from the 26A434 ADT. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 471 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 472 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi new file mode 100644 index 00000000000000..e41c4008c425f3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -0,0 +1,471 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g displays: the rear USB-C ports and the HDMI port, driven through + * the DCP firmware's iBoot interface (apple,t8152-dcp-iboot). The + * bootloader trains the displays and hands both DCPs over with their RTKit + * sessions running. + * + * Resources are from the 26A434 ADT: dcp (iop,ascwrap-v8, post-office + * mailbox 5 with alias: 0x316020000 + 2 * 5 * 0x80), dart-dcp (SID 23), + * dart-disp0 (scanout SID 0), and the atc-phyN PHY windows. The Gen3 + * display DARTs stay locked by iBoot, each with its own live root, so the + * scanout stream is a child device with its own domain. Linux tables are + * published into vacant root slots, so the DMA window is the upper half of + * the 64 GiB vm-base window, above the firmware's and the bootloader's + * mappings. + */ +#include +#include + +&dcp_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + +&disp0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + +&dcpext0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + +&dispext0_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + +/ { + soc { + /* + * ADT /arm-io/nub-spmi-a0 (gen 4): the USB-C PD controllers of + * the three rear ports, each of which can carry the USB-C display. + */ + nub_spmi_a0: spmi@308908000 { + compatible = "apple,t8152-spmi", "apple,t8142-spmi"; + reg = <0x3 0x08908000 0x0 0x4000>; + #address-cells = <2>; + #size-cells = <0>; + + /* back-middle */ + hpm0: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + }; + + /* back-left */ + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + }; + + /* back-right */ + hpm3: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + }; + }; + + /* + * ADT aop-gpio. Its interrupts are the AOP's, so it has no + * interrupt controller here; the HDMI HPD line is polled. + */ + pinctrl_aop: pinctrl@310824000 { + compatible = "apple,t8152-pinctrl", "apple,t8103-pinctrl"; + reg = <0x3 0x10824000 0x0 0x4000>; + gpio-controller; + #gpio-cells = <2>; + gpio-ranges = <&pinctrl_aop 0 0 77>; + apple,npins = <77>; + }; + + dcp_mbox: mailbox@316020500 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020500 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + dcp_iboot: display@286e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x2 0x86e00000 0x0 0x74000>, + <0x3 0x0002005c 0x0 0x4>, + <0x3 0x1a760000 0x0 0x4000>, + <0x3 0x00700460 0x0 0x4>; + /* aux: ADT dptx0-aux, aux-ps: PMGR GLOBAL_AUX_CTRL0 */ + reg-names = "coproc", "dp-clock", "aux", "aux-ps"; + #address-cells = <2>; + #size-cells = <2>; + ranges; + mboxes = <&dcp_mbox>; + iommus = <&dcp_dart 23>; + /* + * Cacheable DMA, as iBoot maps DCP buffers: the firmware + * faults on entries with the DART's no-cache bit. + */ + dma-coherent; + + /* + * The display pipe's own stream: a separate device, so + * its domain imports dart-disp0's root, not dart-dcp's. + */ + scanout { + iommus = <&disp0_dart 0>; + dma-coherent; + }; + + /* + * USB-C back-middle: ADT atc-phy0. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain. Tunables before and after the lane crossbar setup. + */ + usb-c@403000000 { + reg = <0x4 0x03000000 0x0 0x84000>, + <0x3 0x08290000 0x0 0x104>, + <0x3 0x03a13700 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <0>; + apple,usb-pd = <&hpm0>; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bca4>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + }; + + /* + * USB-C back-left: ADT atc-phy1. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain. Tunables before and after the lane crossbar setup. + */ + usb-c@40b000000 { + reg = <0x4 0x0b000000 0x0 0x84000>, + <0x3 0x08290040 0x0 0x104>, + <0x3 0x03a13800 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <1>; + apple,usb-pd = <&hpm1>; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bc26>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + }; + + /* + * USB-C back-right: ADT atc-phy3. PS: the ATC's DP_0, DP_1 and + * USB_AON power states (+0, +0x20, +0x100), PSD: its common + * domain. Tunables before and after the lane crossbar setup. + */ + usb-c@413000000 { + reg = <0x4 0x13000000 0x0 0x84000>, + <0x3 0x082900c0 0x0 0x104>, + <0x3 0x03a13a00 0x0 0xc0>; + reg-names = "atc", "atc-ps", "atc-psd"; + apple,dfp-endpoint = <3>; + apple,usb-pd = <&hpm3>; + apple,tunable-pre = + /* ACIOPHY_CMN_DFLT */ + <0x00800 0x00fc0000 0x00fc0000>, + <0x0084c 0x000ff800 0x000ff800>, + <0x0085c 0x000000ff 0x00000080>, + <0x00860 0x007fffff 0x0052bc26>, + <0x00864 0x02c00000 0x00800000>, + /* CIOPLL_CORE_DFLT */ + <0x01614 0x0003ffc0 0x0001e5c0>, + <0x01640 0x00000007 0x00000003>, + <0x01668 0x00000ffc 0x000005f0>; + apple,tunable-post = + /* ATC_FABRIC */ + <0x6c004 0x003f003f 0x00200020>, + <0x6c00c 0x000000f1 0x000000a1>, + <0x6c010 0x0000801f 0x00000004>, + <0x6c018 0x003f003f 0x00200020>, + <0x6c020 0x000000f1 0x000000a1>, + <0x6c024 0x0000801f 0x00000004>, + <0x6c02c 0x007f007f 0x00410041>, + <0x6c034 0x000000f1 0x00000071>, + <0x6c038 0x0000801f 0x00000004>, + <0x6c040 0x0000001f 0x00000010>, + <0x6c048 0x0000801f 0x00000004>, + <0x6c050 0x007f007f 0x00450045>, + <0x6c058 0x000000f1 0x00000051>, + <0x6c05c 0x0000801f 0x00000004>, + <0x6c064 0x0000003f 0x00000020>, + <0x6c06c 0x0000801f 0x00000004>, + <0x6c074 0x00000001 0x00000001>, + <0x6c078 0x0000801f 0x00000004>, + <0x6c080 0x001f001f 0x00100010>, + <0x6c084 0x000000f1 0x00000011>, + <0x6c088 0x00000001 0x00000001>, + <0x6c08c 0x00000001 0x00000001>, + <0x6c090 0x0000801f 0x00000004>, + <0x6c098 0x001f001f 0x00100010>, + <0x6c09c 0x000000f1 0x00000011>, + <0x6c0a0 0x0000801f 0x00000004>, + <0x6c0a8 0x000000ff 0x000000a0>, + <0x6c0ac 0x0000801f 0x00000004>, + <0x6c0b4 0x0000003f 0x00000020>, + <0x6c0bc 0x0000801f 0x00000004>, + <0x6c0c4 0x0000003f 0x00000020>, + <0x6c0cc 0x0000801f 0x00000004>, + <0x6c0d4 0x0000000f 0x00000008>, + <0x6c0d8 0x0000801f 0x00000004>, + <0x6c0e0 0x001f001f 0x00180018>, + <0x6c0e4 0x0000801f 0x00000004>, + <0x6c0ec 0x001f001f 0x00180018>, + <0x6c0f0 0x0000801f 0x00000004>, + <0x6c0f8 0x001f001f 0x00180018>, + <0x6c0fc 0x0000801f 0x00000004>, + <0x6c104 0x001f001f 0x00180018>, + <0x6c108 0x0000801f 0x00000004>, + <0x6c110 0x00000001 0x00000001>, + <0x6c114 0x0000801f 0x00000004>, + <0x6c11c 0x0000801f 0x00000004>, + <0x6c124 0x0000801f 0x00000004>, + <0x6c12c 0x0000801f 0x00000004>, + <0x6c134 0x0000801f 0x00000004>, + <0x6c13c 0xffffffff 0x01010101>, + <0x6c140 0x0000801f 0x00000004>, + <0x6c148 0x0000801f 0x00000004>, + <0x6c150 0xffffffff 0x01010101>, + <0x6c154 0x0000ffff 0x00000101>, + <0x6c158 0x0000801f 0x00000004>, + <0x6c160 0x0000801f 0x00000004>, + <0x6c168 0x0000801f 0x00000004>, + <0x6c170 0x0000801f 0x00000004>, + <0x6c178 0x0000801f 0x00000004>, + <0x6c180 0xffffffff 0x01010101>, + <0x6c184 0x0000801f 0x00000004>, + <0x6c18c 0x0000801f 0x00000004>, + <0x6c194 0x0000801f 0x00000004>, + /* DPPLL_CORE_DFLT */ + <0x01040 0x0000000c 0x00000008>, + <0x01060 0x0001c000 0x0000c000>, + <0x01098 0x00000f00 0x00000800>, + <0x0109c 0x000fe000 0x000fe000>, + <0x01108 0x07c00000 0x04000000>, + <0x0110c 0x0000007c 0x00000010>, + /* DPPLL_TOP_DFLT */ + <0x00e8c 0x0000007f 0x0000003c>, + <0x00e9c 0x0000007f 0x00000032>, + <0x00eac 0x0000007f 0x00000032>, + <0x00ebc 0x0000007f 0x0000005a>, + /* ASDC_AUX_SHM_DFLT */ + <0x02308 0x000000fc 0x00000084>; + }; + }; + + /* + * HDMI: DCPEXT0 (post-office mailbox 6) drives the dedicated + * dptx-phy through the PS190 converter. ADT dcpext0, + * dart-dcpext0 and dart-dispext0. + */ + dcpext_mbox: mailbox@316020600 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020600 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + dcpext_iboot: display@32ae00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x3 0x2ae00000 0x0 0x74000>, + <0x3 0x1a740000 0x0 0x10000>, + <0x3 0x1a700000 0x0 0x4000>, + <0x3 0x1a764000 0x0 0x4000>, + <0x3 0x00700480 0x0 0x4>, + <0x3 0x007016c0 0x0 0x4>, + <0x3 0x00700e00 0x0 0x4>; + /* aux: ADT dptx1-aux, aux-ps: PMGR GLOBAL_AUX_CTRL1 */ + /* Read-only PMGR DPTX_PHY and DISPEXT0_CPU admission checks. */ + reg-names = "coproc", "phy-core", "phy-apb", "aux", "aux-ps", + "phy-ps", "coproc-ps"; + mboxes = <&dcpext_mbox>; + iommus = <&dcpext0_dart 23>; + dma-coherent; + apple,hdmi; + /* ADT dp2hdmi-gpio0 function-hdmi_hpd */ + hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; + + scanout { + iommus = <&dispext0_dart 0>; + dma-coherent; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 0f98b07748b016..169298a6c9e6c4 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -502,3 +502,4 @@ #include "t8152-j873-usb.dtsi" #include "t8152-j873-ethernet.dtsi" #include "t8152-j873-audio.dtsi" +#include "t8152-j873-dcp.dtsi" From e862cf520423cdea62fde3dc70a46d54fdb3ecdd Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 22:53:55 +0100 Subject: [PATCH 0332/1514] arm64: dts: apple: j873: add DCPEXT1 and share the USB-C ports Describe DCPEXT1 (ADT dcpext1: ASC at 0x502e00000, post-office mailbox 7, IRQs 306/266, DARTs dart-dcpext1 SID 23 and dart-dispext1 SID 0) with its PMGR2 PSD admission register. Give each controller its crossbar source, let DCPEXT0 and DCPEXT1 use the main DCP's USB-C port children, and widen dp-clock to the PMGR ATC DP clock dividers of all ATCs. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 58 ++++++++++++++++--- 1 file changed, 51 insertions(+), 7 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi index e41c4008c425f3..8929f26c8bcc51 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -1,9 +1,10 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * J873g displays: the rear USB-C ports and the HDMI port, driven through + * J873g displays: three controllers for the rear USB-C and HDMI ports, + * driven through * the DCP firmware's iBoot interface (apple,t8152-dcp-iboot). The - * bootloader trains the displays and hands both DCPs over with their RTKit - * sessions running. + * bootloader hands over running or quiesced RTKit sessions. Unused + * controllers can claim another USB-C monitor through the shared crossbar. * * Resources are from the 26A434 ADT: dcp (iop,ascwrap-v8, post-office * mailbox 5 with alias: 0x316020000 + 2 * 5 * 0x80), dart-dcp (SID 23), @@ -37,6 +38,17 @@ status = "okay"; }; +&dcpext1_dart { + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + +&dispext1_dart { + reg-names = "dart", "dapf"; + apple,dma-range = <0x108 0x0 0x8 0x0>; + status = "okay"; +}; + / { soc { /* @@ -93,7 +105,7 @@ dcp_iboot: display@286e00000 { compatible = "apple,t8152-dcp-iboot"; reg = <0x2 0x86e00000 0x0 0x74000>, - <0x3 0x0002005c 0x0 0x4>, + <0x3 0x00020044 0x0 0x1c>, <0x3 0x1a760000 0x0 0x4000>, <0x3 0x00700460 0x0 0x4>; /* aux: ADT dptx0-aux, aux-ps: PMGR GLOBAL_AUX_CTRL0 */ @@ -108,6 +120,7 @@ * faults on entries with the DART's no-cache bit. */ dma-coherent; + apple,dp-source = <0>; /* * The display pipe's own stream: a separate device, so @@ -429,7 +442,7 @@ }; /* - * HDMI: DCPEXT0 (post-office mailbox 6) drives the dedicated + * DCPEXT0 (post-office mailbox 6) can drive USB-C, or the dedicated * dptx-phy through the PS190 converter. ADT dcpext0, * dart-dcpext0 and dart-dispext0. */ @@ -450,14 +463,17 @@ <0x3 0x1a764000 0x0 0x4000>, <0x3 0x00700480 0x0 0x4>, <0x3 0x007016c0 0x0 0x4>, - <0x3 0x00700e00 0x0 0x4>; + <0x3 0x00700e00 0x0 0x4>, + <0x3 0x03a12c00 0x0 0xc0>; /* aux: ADT dptx1-aux, aux-ps: PMGR GLOBAL_AUX_CTRL1 */ /* Read-only PMGR DPTX_PHY and DISPEXT0_CPU admission checks. */ reg-names = "coproc", "phy-core", "phy-apb", "aux", "aux-ps", - "phy-ps", "coproc-ps"; + "phy-ps", "coproc-ps", "coproc-psd"; mboxes = <&dcpext_mbox>; iommus = <&dcpext0_dart 23>; dma-coherent; + apple,dp-source = <1>; + apple,usb-c-ports = <&dcp_iboot>; apple,hdmi; /* ADT dp2hdmi-gpio0 function-hdmi_hpd */ hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; @@ -467,5 +483,33 @@ dma-coherent; }; }; + + dcpext1_mbox: mailbox@316020700 { + compatible = "apple,t8152-ascwrap-v8-mailbox"; + reg = <0x3 0x16020700 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* ADT dcpext1: crossbar UFP2, firmware SID23, scanout SID0. */ + dcpext1_iboot: display@502e00000 { + compatible = "apple,t8152-dcp-iboot"; + reg = <0x5 0x02e00000 0x0 0x74000>, + <0x3 0x03a12d00 0x0 0xc0>; + reg-names = "coproc", "coproc-psd"; + mboxes = <&dcpext1_mbox>; + iommus = <&dcpext1_dart 23>; + dma-coherent; + apple,dp-source = <2>; + apple,usb-c-ports = <&dcp_iboot>; + + scanout { + iommus = <&dispext1_dart 0>; + dma-coherent; + }; + }; + }; }; From a199849f23e883639c4cab81b00543cbf3660336 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Wed, 18 Nov 2026 11:03:18 +0100 Subject: [PATCH 0333/1514] arm64: dts: apple: j873: describe the HDMI cold start Give the HDMI node the dptx-phy's PSD service (5), the SMC writes that power the PS190 (ADT dp2hdmi-gpio0 function-dp2hdmi_pwr_en and function-hdmi_pwr_en, SMC key pcIO) and the dptx-phy tunables from the ADT, so that the DCP driver can start HDMI without the bootloader. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi index 8929f26c8bcc51..ebfae0dbbd1d0f 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -464,11 +464,12 @@ <0x3 0x00700480 0x0 0x4>, <0x3 0x007016c0 0x0 0x4>, <0x3 0x00700e00 0x0 0x4>, - <0x3 0x03a12c00 0x0 0xc0>; + <0x3 0x03a12c00 0x0 0xc0>, + <0x3 0x03a10500 0x0 0xc0>; /* aux: ADT dptx1-aux, aux-ps: PMGR GLOBAL_AUX_CTRL1 */ - /* Read-only PMGR DPTX_PHY and DISPEXT0_CPU admission checks. */ + /* PMGR DPTX_PHY, read-only DISPEXT0_CPU, PSD service 5 (dptx-phy) */ reg-names = "coproc", "phy-core", "phy-apb", "aux", "aux-ps", - "phy-ps", "coproc-ps", "coproc-psd"; + "phy-ps", "coproc-ps", "coproc-psd", "phy-psd"; mboxes = <&dcpext_mbox>; iommus = <&dcpext0_dart 23>; dma-coherent; @@ -477,6 +478,38 @@ apple,hdmi; /* ADT dp2hdmi-gpio0 function-hdmi_hpd */ hpd-gpios = <&pinctrl_aop 41 GPIO_ACTIVE_HIGH>; + /* function-dp2hdmi_pwr_en, function-hdmi_pwr_en (SMC pcIO) */ + apple,smc = <&smc>; + apple,pcon-power = <0x7063494f 0x00140000 0x00000001>, + <0x7063494f 0x000f0000 0x00800001>; + /* ADT dptx-phy tunables, in AppleT8152DPTXPort::handleSetTunables order */ + apple,tunable-phy = <0x5180 0x1fff000 0x723000>, + <0x5184 0xffffffff 0x2bc>, + <0x7980 0x1fff000 0x723000>, + <0x7984 0xffffffff 0x2bc>, + <0xa180 0x1fff000 0x723000>, + <0xa184 0xffffffff 0x2bc>, + <0xc980 0x1fff000 0x723000>, + <0xc984 0xffffffff 0x2bc>, + <0x4524 0x3800000 0x2800000>, + <0x6d24 0x3800000 0x2800000>, + <0x9524 0x3800000 0x2800000>, + <0xbd24 0x3800000 0x2800000>, + <0x840 0xc 0x8>, + <0x860 0x1c000 0xc000>, + <0x898 0xf00 0x800>, + <0x89c 0xfe000 0xfe000>, + <0x908 0x7c00000 0x4000000>, + <0x90c 0x7c 0x10>, + <0x68c 0x7f 0x3c>, + <0x69c 0x7f 0x32>, + <0x6ac 0x7f 0x32>, + <0x6bc 0x7f 0x5a>, + <0x1408 0xfc 0x84>, + <0x1c4c 0xff800 0xff800>, + <0x1c5c 0xff 0x80>, + <0x1c60 0x7fffff 0x52bba7>, + <0x1c64 0x2c00000 0x800000>; scanout { iommus = <&dispext0_dart 0>; From 50d8d75faa478e0714bf2c2d6494bf8b59036f8a Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:09:54 -0600 Subject: [PATCH 0334/1514] spmi: apple: take interrupts on generation 4 controllers Generation 4 (t8142, t6050) had its interrupt refused at probe. macOS's trace (reported by Dj on the Aurora M5 Pro thread) acks peripheral sources 0..255 per bit in words from +0x600, with the controller fault source 263 at +0x620 bit 7. On K114c the PMIC RTC alarm sets +0x600 bit 2 (read-only probe, alarm armed 20 s out). Take the mask and ack bank offsets from the hw table (gen1 unchanged, shared with a host check in spmi-apple-irq.h). Generation 4 has no mask bank we could find (no word in 0x20..0x7f or 0x500..0x6ff toggles), so sources are masked in the cache only. Commands stay polled: the RX notification is not wired for gen 4. Tested: host check of the register math; compile only, not booted. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/spmi/spmi-apple-controller.c | 63 +++++++++++++++---------- drivers/spmi/spmi-apple-irq-host-test.c | 42 +++++++++++++++++ drivers/spmi/spmi-apple-irq.h | 37 +++++++++++++++ 3 files changed, 116 insertions(+), 26 deletions(-) create mode 100644 drivers/spmi/spmi-apple-irq-host-test.c create mode 100644 drivers/spmi/spmi-apple-irq.h diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index c5f8829cfeb455..7ecbf636dc16e2 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -32,14 +32,14 @@ #include #include +#include "spmi-apple-irq.h" + /* SPMI Controller Registers */ #define SPMI_STATUS_REG 0 #define SPMI_CMD_REG 0x4 #define SPMI_RSP_REG 0x8 #define SPMI_ACT_REG 0xa4 -#define SPMI_IRQ_MASK_BASE 0x20 -#define SPMI_IRQ_ACK_BASE 0x60 /* * Peripheral interrupts come first. The RX FIFO notification sits right * after them, followed by the controller's own fault interrupts, so the @@ -61,8 +61,6 @@ * reply FIFO. macOS acks the controller's fault interrupt (source 263, after the 256 * peripheral sources; ack words from 0x600) and empties the queue when the controller starts. */ -#define SPMI_GEN4_IRQ_ACK_BASE 0x600 -#define SPMI_GEN4_FAULT_IRQ (SPMI_MAX_PERIPHERAL_IRQS + 7) #define SPMI_FAULT_QUEUE_MAX 64 /* More than the reply FIFO holds: the bound of a recovery's read-out. */ #define SPMI_GEN4_REPLY_DRAIN_MAX 64 @@ -77,6 +75,8 @@ struct apple_spmi_hw { u32 rx_empty; bool legacy_irqs; u32 num_irqs; + u32 irq_mask; + u32 irq_ack; }; static const struct apple_spmi_hw apple_spmi_gen1 = { @@ -86,6 +86,8 @@ static const struct apple_spmi_hw apple_spmi_gen1 = { .rx_empty = SPMI_RX_FIFO_EMPTY, .legacy_irqs = true, .num_irqs = 256, + .irq_mask = APPLE_SPMI_GEN1_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN1_IRQ_ACK, }; /* M1 Pro, Max and Ultra: 192 peripheral interrupts, notification at 192 */ @@ -96,6 +98,8 @@ static const struct apple_spmi_hw apple_spmi_t6000 = { .rx_empty = SPMI_RX_FIFO_EMPTY, .legacy_irqs = true, .num_irqs = 192, + .irq_mask = APPLE_SPMI_GEN1_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN1_IRQ_ACK, }; static const struct apple_spmi_hw apple_spmi_gen4 = { @@ -103,6 +107,9 @@ static const struct apple_spmi_hw apple_spmi_gen4 = { .command = 0x210, .reply = 0x220, .rx_empty = BIT(30), + .num_irqs = 256, + .irq_mask = APPLE_SPMI_GEN4_IRQ_MASK, + .irq_ack = APPLE_SPMI_GEN4_IRQ_ACK, }; struct apple_spmi { @@ -125,23 +132,26 @@ struct apple_spmi { static void apple_spmi_irq_ack_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_ACK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_ack + (irq / 32) * 4; writel(BIT(irq % 32), reg); } static void apple_spmi_irq_mask_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_MASK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; - writel(readl(reg) & ~BIT(irq % 32), reg); + /* Generation 4 has no mask bank found: sources are masked in irq_mask_cache only. */ + if (spmi->hw->irq_mask) + writel(readl(reg) & ~BIT(irq % 32), reg); } static void apple_spmi_irq_unmask_raw(struct apple_spmi *spmi, u32 irq) { - u32 __iomem *reg = spmi->regs + SPMI_IRQ_MASK_BASE + (irq / 32) * 4; + u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; - writel(readl(reg) | BIT(irq % 32), reg); + if (spmi->hw->irq_mask) + writel(readl(reg) | BIT(irq % 32), reg); } static void apple_spmi_irq_ack(struct irq_data *d) @@ -181,8 +191,8 @@ static inline u32 apple_spmi_pack_cmd(u8 opc, u8 sid, u16 param) /* Ack the fault interrupt, then pop and log every queued fault record */ static void apple_spmi_drain_faults(struct device *dev, struct apple_spmi *spmi) { - void __iomem *ack = spmi->regs + SPMI_GEN4_IRQ_ACK_BASE + (SPMI_GEN4_FAULT_IRQ / 32) * 4; - u32 bit = BIT(SPMI_GEN4_FAULT_IRQ % 32), fault; + void __iomem *ack = spmi->regs + APPLE_SPMI_GEN4_IRQ_ACK + (APPLE_SPMI_GEN4_FAULT_IRQ / 32) * 4; + u32 bit = BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32), fault; int i; if (!spmi->faults) @@ -513,7 +523,7 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) unsigned long val, offset, bit; chained_irq_enter(chip, desc); - val = readl(spmi->regs + SPMI_IRQ_ACK_BASE + (notify / 32) * 4); + val = readl(spmi->regs + spmi->hw->irq_ack + (notify / 32) * 4); raw_pending |= !!val; if (val & BIT(notify % 32)) { apple_spmi_irq_ack_raw(spmi, notify); @@ -522,14 +532,14 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) } /* Other queues' responses, such as the sleep's own commands at the debug link's cut. */ if (val & ~BIT(notify % 32)) { - writel(val & ~BIT(notify % 32), spmi->regs + SPMI_IRQ_ACK_BASE + (notify / 32) * 4); + writel(val & ~BIT(notify % 32), spmi->regs + spmi->hw->irq_ack + (notify / 32) * 4); handled = true; } for (offset = 0; offset < notify / 8; offset += sizeof(val)) { unsigned long stray; - val = readq(spmi->regs + SPMI_IRQ_ACK_BASE + offset); + val = readq(spmi->regs + spmi->hw->irq_ack + offset); raw_pending |= !!val; /* * After a real sleep, sources no driver uses come up pending (on the Neo the @@ -540,8 +550,8 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) */ stray = val & ~spmi->irq_used[offset / sizeof(val)]; if (stray) { - writel(lower_32_bits(stray), spmi->regs + SPMI_IRQ_ACK_BASE + offset); - writel(upper_32_bits(stray), spmi->regs + SPMI_IRQ_ACK_BASE + offset + 4); + writel(lower_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset); + writel(upper_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset + 4); handled = true; } if (val & spmi->irq_used[offset / sizeof(val)] & @@ -571,7 +581,7 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) * unmasked, or it fires again for what was just cleared. */ if (handled) - readl(spmi->regs + SPMI_IRQ_ACK_BASE); + readl(spmi->regs + spmi->hw->irq_ack); chained_irq_exit(chip, desc); } @@ -580,7 +590,8 @@ static void apple_spmi_teardown_irq(void *data) struct apple_spmi *spmi = data; for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) - writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); + if (spmi->hw->irq_mask) + writel(0, spmi->regs + spmi->hw->irq_mask + offset); synchronize_irq(spmi->irq); irq_set_chained_handler_and_data(spmi->irq, NULL, NULL); @@ -600,8 +611,9 @@ static int apple_spmi_init_irq(struct platform_device *pdev, raw_spin_lock_init(&spmi->irq_mask_lock); for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) { - writel(0, spmi->regs + SPMI_IRQ_MASK_BASE + offset); - writel(U32_MAX, spmi->regs + SPMI_IRQ_ACK_BASE + offset); + if (spmi->hw->irq_mask) + writel(0, spmi->regs + spmi->hw->irq_mask + offset); + writel(U32_MAX, spmi->regs + spmi->hw->irq_ack + offset); } spmi->irqd = devm_irq_domain_instantiate(&pdev->dev, &info); @@ -613,8 +625,10 @@ static int apple_spmi_init_irq(struct platform_device *pdev, return ret; irq_set_chained_handler_and_data(spmi->irq, apple_spmi_irq_handler, spmi); - apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); - spmi->notify_irq = true; + if (spmi->hw->legacy_irqs) { + apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); + spmi->notify_irq = true; + } return 0; } @@ -662,7 +676,7 @@ static int apple_spmi_resume_noirq(struct device *dev) if (pm_resume_via_firmware()) { bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->hw->num_irqs); for (i = 0; i < spmi->hw->num_irqs / 32; i++) - writel(words[i], spmi->regs + SPMI_IRQ_MASK_BASE + i * 4); + writel(words[i], spmi->regs + spmi->hw->irq_mask + i * 4); } apple_spmi_irq_ack_raw(spmi, spmi->hw->num_irqs); apple_spmi_irq_unmask_raw(spmi, spmi->hw->num_irqs); @@ -715,9 +729,6 @@ static int apple_spmi_probe(struct platform_device *pdev) if (spmi->irq < 0 && spmi->irq != -ENXIO) return spmi->irq; if (spmi->irq >= 0) { - if (!spmi->hw->legacy_irqs) - return dev_err_probe(&pdev->dev, -EOPNOTSUPP, - "Generation 4 interrupt layout is not supported\n"); ret = apple_spmi_init_irq(pdev, spmi, spmi->irq); if (ret) return ret; diff --git a/drivers/spmi/spmi-apple-irq-host-test.c b/drivers/spmi/spmi-apple-irq-host-test.c new file mode 100644 index 00000000000000..89dbbacfedfb2a --- /dev/null +++ b/drivers/spmi/spmi-apple-irq-host-test.c @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Host check for the Apple SPMI interrupt register layout (not built by kbuild): + * cc -Wall -Werror -o /tmp/spmi-irq-test drivers/spmi/spmi-apple-irq-host-test.c && /tmp/spmi-irq-test + * + * The expected values are the layouts measured on hardware or traced from macOS: + * generation 1 (T8103/T6000): mask words from 0x20, ack/pending words from 0x60; + * generation 4 (T8142/T6050): ack/pending words from 0x600, source n in bit n % 32 + * of word n / 32, the controller's fault source 263 acked at 0x620 bit 7. + */ +#include +#include +#include + +typedef uint32_t u32; +#define BIT(n) (1U << (n)) + +#include "spmi-apple-irq.h" + +int main(void) +{ + /* generation 1 */ + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_MASK, 3) == 0x20); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_ACK, 3) == 0x60); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_ACK, 40) == 0x64); + assert(apple_spmi_irq_bit(40) == BIT(8)); + + /* generation 4: the PMU alarm source seen on K114c, the hpm2 wake bit macOS acks, the fault source */ + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 2) == 0x600); + assert(apple_spmi_irq_bit(2) == BIT(2)); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 19) == 0x600); + assert(apple_spmi_irq_bit(19) == BIT(19)); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, APPLE_SPMI_GEN4_FAULT_IRQ) == 0x620); + assert(apple_spmi_irq_bit(APPLE_SPMI_GEN4_FAULT_IRQ) == BIT(7)); + /* no hardware mask bank for gen 4 */ + assert(APPLE_SPMI_GEN4_IRQ_MASK == 0); + /* the last peripheral source is in word 7 */ + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 255) == 0x61c); + + puts("spmi-apple-irq host check: ok"); + return 0; +} diff --git a/drivers/spmi/spmi-apple-irq.h b/drivers/spmi/spmi-apple-irq.h new file mode 100644 index 00000000000000..dce85d2d65ae24 --- /dev/null +++ b/drivers/spmi/spmi-apple-irq.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Apple SPMI controller interrupt register layout, shared with the host check + * (spmi-apple-irq-host-test.c). + * + * Peripheral sources 0..255 come first, then the RX FIFO notification (256) and + * the controller's own fault sources. Source n sits in bit n % 32 of word n / 32 + * of both the mask bank and the ack/pending bank. + */ +#ifndef _SPMI_APPLE_IRQ_H +#define _SPMI_APPLE_IRQ_H + +/* Generation 1 (T8103, T6000) */ +#define APPLE_SPMI_GEN1_IRQ_MASK 0x20 +#define APPLE_SPMI_GEN1_IRQ_ACK 0x60 + +/* + * Generation 4 (T8142, T6050): ack and pending words from 0x600, the fault source + * 263 acked at 0x620 bit 7 (traced from macOS under the hypervisor). The mask bank + * is not found; see APPLE_SPMI_GEN4_IRQ_MASK. + */ +#define APPLE_SPMI_GEN4_IRQ_ACK 0x600 +#define APPLE_SPMI_GEN4_FAULT_IRQ (256 + 7) +/* No mask bank found by toggling every word in 0x20..0x7f and 0x500..0x6ff (K114c): 0 = soft mask only */ +#define APPLE_SPMI_GEN4_IRQ_MASK 0 + +static inline u32 apple_spmi_irq_reg(u32 base, u32 irq) +{ + return base + (irq / 32) * 4; +} + +static inline u32 apple_spmi_irq_bit(u32 irq) +{ + return BIT(irq % 32); +} + +#endif /* _SPMI_APPLE_IRQ_H */ From 47a85b996907e5f57f2ed1b4e42cd00b2355ba61 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:23:27 +0000 Subject: [PATCH 0335/1514] spmi: apple: use the generation 4 mask bank at +0x400 Probe on K114c: +0x400..0x41c toggle and restore (8 words), +0x420 does not, matching the +0x600 ack bank 0x200 above (Dj, seq 713, from write offsets in a macOS trace). The alarm latches +0x600 bit 2 once the PMIC alarm mask byte 0x200e is 0 (as rtc-macsmc writes it) and a write of 4 to +0x600 clears it (measured). Whether the +0x400 bit gates the AIC line is not measured. Drop the cache-only masking for gen 4. On a firmware resume re-apply the runtime mask, since a firmware sleep entry writes the mask bank itself. Host check extended; compile only, not booted. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/spmi/spmi-apple-controller.c | 24 ++++++++++++++---------- drivers/spmi/spmi-apple-irq-host-test.c | 7 +++++-- drivers/spmi/spmi-apple-irq.h | 6 +++--- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index 7ecbf636dc16e2..a7f2e1b32d7ba2 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -141,17 +141,14 @@ static void apple_spmi_irq_mask_raw(struct apple_spmi *spmi, u32 irq) { u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; - /* Generation 4 has no mask bank found: sources are masked in irq_mask_cache only. */ - if (spmi->hw->irq_mask) - writel(readl(reg) & ~BIT(irq % 32), reg); + writel(readl(reg) & ~BIT(irq % 32), reg); } static void apple_spmi_irq_unmask_raw(struct apple_spmi *spmi, u32 irq) { u32 __iomem *reg = spmi->regs + spmi->hw->irq_mask + (irq / 32) * 4; - if (spmi->hw->irq_mask) - writel(readl(reg) | BIT(irq % 32), reg); + writel(readl(reg) | BIT(irq % 32), reg); } static void apple_spmi_irq_ack(struct irq_data *d) @@ -590,8 +587,7 @@ static void apple_spmi_teardown_irq(void *data) struct apple_spmi *spmi = data; for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) - if (spmi->hw->irq_mask) - writel(0, spmi->regs + spmi->hw->irq_mask + offset); + writel(0, spmi->regs + spmi->hw->irq_mask + offset); synchronize_irq(spmi->irq); irq_set_chained_handler_and_data(spmi->irq, NULL, NULL); @@ -611,8 +607,7 @@ static int apple_spmi_init_irq(struct platform_device *pdev, raw_spin_lock_init(&spmi->irq_mask_lock); for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) { - if (spmi->hw->irq_mask) - writel(0, spmi->regs + spmi->hw->irq_mask + offset); + writel(0, spmi->regs + spmi->hw->irq_mask + offset); writel(U32_MAX, spmi->regs + spmi->hw->irq_ack + offset); } @@ -667,8 +662,17 @@ static int apple_spmi_resume_noirq(struct device *dev) unsigned long flags; size_t i; - if (!spmi->notify_parked) + if (!spmi->notify_parked) { + /* Gen 4 never parks the notification, but a firmware sleep entry writes the mask bank itself. */ + if (spmi->hw->legacy_irqs || !spmi->irqd || !pm_resume_via_firmware()) + return 0; + raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); + bitmap_to_arr32(words, spmi->irq_mask_cache, spmi->hw->num_irqs); + for (i = 0; i < spmi->hw->num_irqs / 32; i++) + writel(words[i], spmi->regs + spmi->hw->irq_mask + i * 4); + raw_spin_unlock_irqrestore(&spmi->irq_mask_lock, flags); return 0; + } guard(mutex)(&spmi->fifo_lock); raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); diff --git a/drivers/spmi/spmi-apple-irq-host-test.c b/drivers/spmi/spmi-apple-irq-host-test.c index 89dbbacfedfb2a..5ab780d73bc05e 100644 --- a/drivers/spmi/spmi-apple-irq-host-test.c +++ b/drivers/spmi/spmi-apple-irq-host-test.c @@ -32,8 +32,11 @@ int main(void) assert(apple_spmi_irq_bit(19) == BIT(19)); assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, APPLE_SPMI_GEN4_FAULT_IRQ) == 0x620); assert(apple_spmi_irq_bit(APPLE_SPMI_GEN4_FAULT_IRQ) == BIT(7)); - /* no hardware mask bank for gen 4 */ - assert(APPLE_SPMI_GEN4_IRQ_MASK == 0); + /* gen 4 mask bank (measured on K114c, Dj's HV trace writes +0x420), mirrors the ack bank */ + assert(APPLE_SPMI_GEN4_IRQ_MASK == 0x400); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_MASK, 2) == 0x400); + assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_MASK, 263) == 0x420); + assert(APPLE_SPMI_GEN4_IRQ_ACK - APPLE_SPMI_GEN4_IRQ_MASK == 0x200); /* the last peripheral source is in word 7 */ assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 255) == 0x61c); diff --git a/drivers/spmi/spmi-apple-irq.h b/drivers/spmi/spmi-apple-irq.h index dce85d2d65ae24..d43dfa1c606cbe 100644 --- a/drivers/spmi/spmi-apple-irq.h +++ b/drivers/spmi/spmi-apple-irq.h @@ -17,12 +17,12 @@ /* * Generation 4 (T8142, T6050): ack and pending words from 0x600, the fault source * 263 acked at 0x620 bit 7 (traced from macOS under the hypervisor). The mask bank - * is not found; see APPLE_SPMI_GEN4_IRQ_MASK. + * is at 0x400 (see APPLE_SPMI_GEN4_IRQ_MASK). */ #define APPLE_SPMI_GEN4_IRQ_ACK 0x600 #define APPLE_SPMI_GEN4_FAULT_IRQ (256 + 7) -/* No mask bank found by toggling every word in 0x20..0x7f and 0x500..0x6ff (K114c): 0 = soft mask only */ -#define APPLE_SPMI_GEN4_IRQ_MASK 0 +/* Mask bank mirrors the ack bank 0x200 below; +0x400..0x41c toggle on K114c, +0x420 does not. */ +#define APPLE_SPMI_GEN4_IRQ_MASK 0x400 static inline u32 apple_spmi_irq_reg(u32 base, u32 irq) { From 217257994425530a5c1d18069b6cea64ee2ac158 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:07:56 -0600 Subject: [PATCH 0336/1514] spmi: apple: read the fault queue before the shared ack, limit gen4 mask writes Both open code points from review: The controller's fault source (263, word 0x620 bit 7 on gen4) shares its ack word with the notification word the handler reads first, and the stray-source path acked it directly: queued fault records were lost. Drain the queue before the bit is acked, in both the notification-word path and the readq stray path. gen4 has no notification source, and the word at +0x420 does not behave as a mask bank, so the init and teardown loops now write only the num_irqs / 32 mask words on gen4 (the legacy controllers keep the extra notification word). The host-test file is dropped: kbuild never built it and it checked constants against themselves. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/spmi/spmi-apple-controller.c | 27 +++++++++++++-- drivers/spmi/spmi-apple-irq-host-test.c | 45 ------------------------- drivers/spmi/spmi-apple-irq.h | 3 +- 3 files changed, 26 insertions(+), 49 deletions(-) delete mode 100644 drivers/spmi/spmi-apple-irq-host-test.c diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index a7f2e1b32d7ba2..1237ac856ac55e 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -116,6 +116,7 @@ struct apple_spmi { void __iomem *regs; void __iomem *faults; unsigned int nfaults; + struct device *dev; const struct apple_spmi_hw *hw; struct mutex fifo_lock; struct completion fifo_rx; @@ -521,6 +522,17 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) chained_irq_enter(chip, desc); val = readl(spmi->regs + spmi->hw->irq_ack + (notify / 32) * 4); + /* + * On gen4 the controller's own fault source shares this last ack word + * (0x620, bit 7). Its queued records must be read before the source is + * acked, or drain_faults() never sees them. + */ + if (!spmi->hw->legacy_irqs && spmi->faults && + (val & BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32))) { + apple_spmi_drain_faults(spmi->dev, spmi); + val &= ~BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32); + handled = true; + } raw_pending |= !!val; if (val & BIT(notify % 32)) { apple_spmi_irq_ack_raw(spmi, notify); @@ -546,6 +558,14 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) * pending for its unmask: it isn't a bad interrupt either. */ stray = val & ~spmi->irq_used[offset / sizeof(val)]; + if (stray && !spmi->hw->legacy_irqs && spmi->faults && + offset == (APPLE_SPMI_GEN4_FAULT_IRQ / 32) * sizeof(val) && + (stray & BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32))) { + /* Same rule as above: read the queued records first. */ + apple_spmi_drain_faults(spmi->dev, spmi); + stray &= ~BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32); + handled = true; + } if (stray) { writel(lower_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset); writel(upper_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset + 4); @@ -586,7 +606,8 @@ static void apple_spmi_teardown_irq(void *data) { struct apple_spmi *spmi = data; - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) + for (size_t offset = 0; offset < spmi->hw->num_irqs / 8 + (spmi->hw->legacy_irqs ? 4 : 0); + offset += 4) writel(0, spmi->regs + spmi->hw->irq_mask + offset); synchronize_irq(spmi->irq); @@ -606,7 +627,8 @@ static int apple_spmi_init_irq(struct platform_device *pdev, raw_spin_lock_init(&spmi->irq_mask_lock); - for (size_t offset = 0; offset < (spmi->hw->num_irqs + 32) / 8; offset += 4) { + for (size_t offset = 0; offset < spmi->hw->num_irqs / 8 + (spmi->hw->legacy_irqs ? 4 : 0); + offset += 4) { writel(0, spmi->regs + spmi->hw->irq_mask + offset); writel(U32_MAX, spmi->regs + spmi->hw->irq_ack + offset); } @@ -705,6 +727,7 @@ static int apple_spmi_probe(struct platform_device *pdev) return -ENOMEM; spmi = spmi_controller_get_drvdata(ctrl); + spmi->dev = &pdev->dev; spmi->hw = device_get_match_data(&pdev->dev); if (!spmi->hw) return -EINVAL; diff --git a/drivers/spmi/spmi-apple-irq-host-test.c b/drivers/spmi/spmi-apple-irq-host-test.c deleted file mode 100644 index 5ab780d73bc05e..00000000000000 --- a/drivers/spmi/spmi-apple-irq-host-test.c +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 -/* - * Host check for the Apple SPMI interrupt register layout (not built by kbuild): - * cc -Wall -Werror -o /tmp/spmi-irq-test drivers/spmi/spmi-apple-irq-host-test.c && /tmp/spmi-irq-test - * - * The expected values are the layouts measured on hardware or traced from macOS: - * generation 1 (T8103/T6000): mask words from 0x20, ack/pending words from 0x60; - * generation 4 (T8142/T6050): ack/pending words from 0x600, source n in bit n % 32 - * of word n / 32, the controller's fault source 263 acked at 0x620 bit 7. - */ -#include -#include -#include - -typedef uint32_t u32; -#define BIT(n) (1U << (n)) - -#include "spmi-apple-irq.h" - -int main(void) -{ - /* generation 1 */ - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_MASK, 3) == 0x20); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_ACK, 3) == 0x60); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN1_IRQ_ACK, 40) == 0x64); - assert(apple_spmi_irq_bit(40) == BIT(8)); - - /* generation 4: the PMU alarm source seen on K114c, the hpm2 wake bit macOS acks, the fault source */ - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 2) == 0x600); - assert(apple_spmi_irq_bit(2) == BIT(2)); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 19) == 0x600); - assert(apple_spmi_irq_bit(19) == BIT(19)); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, APPLE_SPMI_GEN4_FAULT_IRQ) == 0x620); - assert(apple_spmi_irq_bit(APPLE_SPMI_GEN4_FAULT_IRQ) == BIT(7)); - /* gen 4 mask bank (measured on K114c, Dj's HV trace writes +0x420), mirrors the ack bank */ - assert(APPLE_SPMI_GEN4_IRQ_MASK == 0x400); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_MASK, 2) == 0x400); - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_MASK, 263) == 0x420); - assert(APPLE_SPMI_GEN4_IRQ_ACK - APPLE_SPMI_GEN4_IRQ_MASK == 0x200); - /* the last peripheral source is in word 7 */ - assert(apple_spmi_irq_reg(APPLE_SPMI_GEN4_IRQ_ACK, 255) == 0x61c); - - puts("spmi-apple-irq host check: ok"); - return 0; -} diff --git a/drivers/spmi/spmi-apple-irq.h b/drivers/spmi/spmi-apple-irq.h index d43dfa1c606cbe..4134ef37ff369b 100644 --- a/drivers/spmi/spmi-apple-irq.h +++ b/drivers/spmi/spmi-apple-irq.h @@ -1,7 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0 */ /* - * Apple SPMI controller interrupt register layout, shared with the host check - * (spmi-apple-irq-host-test.c). + * Apple SPMI controller interrupt register layout. * * Peripheral sources 0..255 come first, then the RX FIFO notification (256) and * the controller's own fault sources. Source n sits in bit n % 32 of word n / 32 From 7297cb87900409735bd095d12085419db920ec3e Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:27:53 -0600 Subject: [PATCH 0337/1514] spmi: apple: drop the unreachable fault drain in the stray-queue loop The stray-queue loop visits ack words 0 to 3 (bytes 0 to 24), while the gen4 fault source lives in word 8 (0x620), which the chained handler already reads and drains before acking. The hunk also compared a word index against byte offsets. It could never fire; remove it. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/spmi/spmi-apple-controller.c | 8 -------- 1 file changed, 8 deletions(-) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index 1237ac856ac55e..bdabe697859b1c 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -558,14 +558,6 @@ static void apple_spmi_irq_handler(struct irq_desc *desc) * pending for its unmask: it isn't a bad interrupt either. */ stray = val & ~spmi->irq_used[offset / sizeof(val)]; - if (stray && !spmi->hw->legacy_irqs && spmi->faults && - offset == (APPLE_SPMI_GEN4_FAULT_IRQ / 32) * sizeof(val) && - (stray & BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32))) { - /* Same rule as above: read the queued records first. */ - apple_spmi_drain_faults(spmi->dev, spmi); - stray &= ~BIT(APPLE_SPMI_GEN4_FAULT_IRQ % 32); - handled = true; - } if (stray) { writel(lower_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset); writel(upper_32_bits(stray), spmi->regs + spmi->hw->irq_ack + offset + 4); From c2bc858e7a2b4500acd9f92a7d5a4abadbf1e948 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 15:28:08 +0100 Subject: [PATCH 0338/1514] dt-bindings: display: apple,t8152-dcp-iboot: allow a power domain The display coprocessor has a power state of its own, which its DARTs follow. Allow the node to name it. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/display/apple,t8152-dcp-iboot.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index 7c4e2b1db5ab93..6fbdaba2d17a40 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -188,6 +188,12 @@ properties: maxItems: 1 description: DCP DART stream + power-domains: + maxItems: 1 + description: + The coprocessor's power state, which its firmware runs; the DARTs + follow it. + scanout: type: object additionalProperties: false From c805637e0cf8ca95caa1a275a09e717ec636458a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 23:50:54 +0100 Subject: [PATCH 0339/1514] dt-bindings: usb: apple,sn201202x: add the T8152 controllers The USB-C PD controllers behind the J873g's (T8152) SPMI controller at 0x308908000 answer as the T8132 ones do: no register-selection interrupt, so a selection is polled, and the payload length of the selected register is read from register 0x1f. Their event, sleep and wake sources are interrupts 11/17/19, 37/43/45 and 63/69/71 of that controller. Add apple,t8152-sn201202x with apple,t8132-sn201202x as fallback, so that the T8132 interrupt layout (irq, sleep, wake) applies. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/usb/apple,sn201202x.yaml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml b/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml index cc82767a25a517..84ae1f7bf08801 100644 --- a/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml +++ b/Documentation/devicetree/bindings/usb/apple,sn201202x.yaml @@ -18,7 +18,9 @@ description: | The controller can be polled when interrupt resources are not supplied. T8132 omits the register-selection interrupt, so selection is polled while - event, standby and wakeup notifications use interrupts. + event, standby and wakeup notifications use interrupts. The T8152 + controllers work as the T8132 ones do: no register-selection interrupt, and + the payload length of a selected register in register 0x1f. properties: compatible: @@ -27,6 +29,10 @@ properties: - items: - const: apple,t8132-sn201202x - const: apple,sn201202x + - items: + - const: apple,t8152-sn201202x + - const: apple,t8132-sn201202x + - const: apple,sn201202x reg: maxItems: 1 From 680a085f482f5b45faa5bd6360134ecacfbc487a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 15:28:08 +0100 Subject: [PATCH 0340/1514] arm64: dts: apple: t8152-j873g: power domains for the display DARTs Every enabled DART must name the power state of the engine it serves (scripts/dtc/apple-dart-pd-check.py). The six J873g display DARTs named none. Their engines are the display coprocessors, whose PMGR states are DISP_CPU (dcp), DISPEXT0_CPU (dcpext0) and DISPEXT1_CPU (dcpext1) in the 26A434 ADT. The AP does not switch those: a coprocessor is started through its PSD service (coproc-psd), and its firmware runs the state; Linux only reads DISPEXT0_CPU (coproc-ps). So they are described as firmware-owned: the OS keeps them on and never reads or writes them, which leaves the display hand-off and the HDMI cold start as they are. The coprocessor nodes name the same state as their DARTs. DISP_CPU sits at PMGR offset 0x14000 (it reads 0x0f0000ff on J873g, as DISPEXT0/1_CPU do), past the 0x14000 the PMGR node described, so the node now spans the ADT's 0x1c000 PMGR window. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 49 +++++++++++++++++++ .../arm64/boot/dts/apple/t8152-j873-qspi.dtsi | 3 +- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi index ebfae0dbbd1d0f..8263f1c68634be 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -18,34 +18,80 @@ #include #include +/* + * The display coprocessors' PMGR power states (ADT pmgr devices DISP_CPU, + * DISPEXT0_CPU and DISPEXT1_CPU), which their DARTs follow. The PMGR does not + * switch them for the AP: the coprocessor is started through its PSD service + * (coproc-psd below) and its firmware runs the state, so Linux only reads + * DISPEXT0_CPU (coproc-ps). They are the firmware's: the OS keeps them on and + * never accesses them. + */ +&pmgr { + ps_dispext1_cpu: power-controller@aa0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xaa0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_cpu"; + apple,firmware-owned; + }; + + ps_dispext0_cpu: power-controller@e00 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xe00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_cpu"; + apple,firmware-owned; + }; + + ps_disp_cpu: power-controller@14000 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x14000 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cpu"; + apple,firmware-owned; + }; +}; + &dcp_dart { apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_disp_cpu>; status = "okay"; }; &disp0_dart { apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_disp_cpu>; status = "okay"; }; &dcpext0_dart { apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext0_cpu>; status = "okay"; }; &dispext0_dart { apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext0_cpu>; status = "okay"; }; &dcpext1_dart { apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext1_cpu>; status = "okay"; }; &dispext1_dart { reg-names = "dart", "dapf"; apple,dma-range = <0x108 0x0 0x8 0x0>; + power-domains = <&ps_dispext1_cpu>; status = "okay"; }; @@ -115,6 +161,7 @@ ranges; mboxes = <&dcp_mbox>; iommus = <&dcp_dart 23>; + power-domains = <&ps_disp_cpu>; /* * Cacheable DMA, as iBoot maps DCP buffers: the firmware * faults on entries with the DART's no-cache bit. @@ -472,6 +519,7 @@ "phy-ps", "coproc-ps", "coproc-psd", "phy-psd"; mboxes = <&dcpext_mbox>; iommus = <&dcpext0_dart 23>; + power-domains = <&ps_dispext0_cpu>; dma-coherent; apple,dp-source = <1>; apple,usb-c-ports = <&dcp_iboot>; @@ -534,6 +582,7 @@ reg-names = "coproc", "coproc-psd"; mboxes = <&dcpext1_mbox>; iommus = <&dcpext1_dart 23>; + power-domains = <&ps_dispext1_cpu>; dma-coherent; apple,dp-source = <2>; apple,usb-c-ports = <&dcp_iboot>; diff --git a/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi index c03fbf04b24e4c..538511e3ffc170 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-qspi.dtsi @@ -25,7 +25,8 @@ "syscon", "simple-mfd"; #address-cells = <1>; #size-cells = <1>; - reg = <0x3 0x700000 0x0 0x14000>; + /* ADT pmgr reg[32]: power states up to DISP_CPU at 0x14000 */ + reg = <0x3 0x700000 0x0 0x1c000>; }; qspi: spi@331118000 { From bdb6c539491f308c09e85aa2c1c9e368487cf6cb Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 23:52:00 +0100 Subject: [PATCH 0341/1514] dt-bindings: display: apple,t8152-dcp-iboot: describe the USB-C ports as Type-C mode switches A T8152 DCP drives the rear USB-C port whose PD controller reports a DisplayPort sink. So far the DCP read the controllers itself, through apple,usb-pd. The controllers belong to the USB Type-C port driver instead, which passes the DisplayPort alt mode state of a port to the Type-C mode switches its connector's graph leads to. Describe one display switch per port, shared by the DCPs: the port's usb-c node in the shared ports node (the one apple,usb-c-ports refers to) is the mode switch, with an endpoint at the display port (port@3) of the port's usb-c-connector. The DCPs already share these nodes for the port's PHY registers and tunables, and each port has one owner at a time. One switch per DCP instead would fill the three mode switches a connector's port driver looks at (fwnode_typec_mux_get() collects the matches into a three-entry array and stops at the third endpoint without an error), and leave out the port's ATC PHY, which needs one for USB4. Drop apple,usb-pd, which nothing reads any more. Signed-off-by: Thomas Glanzmann --- .../display/apple,t8152-dcp-iboot.yaml | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index 6fbdaba2d17a40..cc7ea1045a323e 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -169,12 +169,6 @@ properties: The converter drives the HDMI hot-plug detect line only while it is powered. - apple,usb-pd: - $ref: /schemas/types.yaml#/definitions/phandle - description: - The USB-C port's PD controller (SPMI), polled for the DisplayPort alt - mode connection and the plug orientation. - hpd-gpios: maxItems: 1 description: @@ -243,20 +237,30 @@ patternProperties: apple,dfp-endpoint: $ref: /schemas/types.yaml#/definitions/uint32 description: The ATC's display-crossbar0 DFP endpoint (ATC instance). - apple,usb-pd: - $ref: /schemas/types.yaml#/definitions/phandle - description: The port's PD controller (SPMI). apple,tunable-pre: $ref: /schemas/types.yaml#/definitions/uint32-matrix description: As the node's apple,tunable-pre, for this port's PHY. apple,tunable-post: $ref: /schemas/types.yaml#/definitions/uint32-matrix description: As the node's apple,tunable-post, for this port's PHY. + mode-switch: + type: boolean + description: + The port's display switch, one per port and shared by all DCPs + that can drive it. The port controller sets the port's + DisplayPort alt mode state, pin assignment and HPD on it; the plug + orientation is the Type-C port's. + port: + $ref: /schemas/graph.yaml#/properties/port + description: + Connects to the display port (port@3) of the port's + usb-c-connector. + dependencies: + mode-switch: [ port ] required: - reg - reg-names - apple,dfp-endpoint - - apple,usb-pd required: - compatible @@ -311,7 +315,13 @@ examples: <0x3 0x03a13a00 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <3>; - apple,usb-pd = <&hpm3>; + mode-switch; + + port { + endpoint { + remote-endpoint = <&typec3_display>; + }; + }; }; }; }; From 0bcbf38c02ce985856cb53e8de2b929e2c86d49e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 22:52:24 +0100 Subject: [PATCH 0342/1514] drm/apple: iboot: send page-flip events from a vblank timer The iBoot interface has no vblank interrupt, so the CRTC set no_vblank and the atomic helpers completed every page-flip event right after the commit. A compositor then gets its flips back as fast as it can commit and renders, and asks its clients to render, at whatever rate the commits complete instead of once per refresh. The plane update still shows at most one new frame per refresh (swaps are spaced one refresh apart), so the extra frames are drawn and copied for nothing and the animation advances unevenly. Use the DRM vblank timer (drm_vblank_helper): drm_vblank_init(), the timer-backed enable/disable/timestamp functions, and drm_crtc_vblank_atomic_flush() to arm each commit's event for the next tick at the mode's refresh rate. The CRTC switches the timer on at the end of atomic_enable and off at the start of atomic_disable. The timer is not locked to the firmware's swaps. The flip timestamps and the vblank sequence (and so the wp_presentation_feedback a compositor derives from them) are the timer's ticks at the mode's rate, not measured scanout times: they can be up to one refresh away from when the frame actually showed. That is enough for pacing; a reader of presentation feedback on this path should not take them as scanout times. A commit that leaves the CRTC off still sets no_vblank. The commit tail (commit_tail_rpm) does not flush an inactive CRTC, so nothing arms its event; with no_vblank, drm_atomic_helper_commit_hw_done() sends it. Without that, commit_hw_done warns that the event was not consumed. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/iboot_drm.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/iboot_drm.c b/drivers/gpu/drm/apple/iboot_drm.c index c0b3bd2311962d..74eddc0fa3ce97 100644 --- a/drivers/gpu/drm/apple/iboot_drm.c +++ b/drivers/gpu/drm/apple/iboot_drm.c @@ -35,6 +35,8 @@ #include #include #include +#include +#include #include "dcp-internal.h" #include "ibootep.h" @@ -689,8 +691,15 @@ static int iboot_crtc_atomic_check(struct drm_crtc *crtc, struct drm_crtc_state *new = drm_atomic_get_new_crtc_state(state, crtc); struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); - /* No vblank interrupt: the helpers complete events after the flush. */ - new->no_vblank = true; + /* + * No vblank interrupt: page-flip events come from a timer at the + * mode's refresh rate (drm_vblank_helper), so a compositor and its + * clients render once per refresh instead of as fast as commits + * complete. A commit that leaves the CRTC off gets no flush + * (commit_tail_rpm flushes active CRTCs only), so its event goes out + * at once, as before. + */ + new->no_vblank = !new->active; if (new->enable && !iboot_find_mode(ib, &new->mode)) return -EINVAL; return 0; @@ -871,6 +880,7 @@ static void iboot_crtc_atomic_enable(struct drm_crtc *crtc, iboot_set_mode_locked(ib, t, c); out: mutex_unlock(&ib->lock); + drm_crtc_vblank_on(crtc); } static void iboot_crtc_atomic_disable(struct drm_crtc *crtc, @@ -880,6 +890,7 @@ static void iboot_crtc_atomic_disable(struct drm_crtc *crtc, struct dcp_iboot *ib = to_dcp_iboot(crtc->dev); int ret, idx; + drm_crtc_vblank_off(crtc); /* A mode change: SET_MODE alone switches, as before. */ if (new->active) return; @@ -915,6 +926,7 @@ static void iboot_crtc_atomic_disable(struct drm_crtc *crtc, static const struct drm_crtc_helper_funcs iboot_crtc_helper = { .atomic_check = iboot_crtc_atomic_check, + .atomic_flush = drm_crtc_vblank_atomic_flush, .atomic_enable = iboot_crtc_atomic_enable, .atomic_disable = iboot_crtc_atomic_disable, }; @@ -926,6 +938,7 @@ static const struct drm_crtc_funcs iboot_crtc_funcs = { .page_flip = drm_atomic_helper_page_flip, .atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state, .atomic_destroy_state = drm_atomic_helper_crtc_destroy_state, + DRM_CRTC_VBLANK_TIMER_FUNCS, }; static const struct drm_encoder_funcs iboot_encoder_funcs = { @@ -1055,6 +1068,10 @@ int dcp_iboot_kms_init(struct dcp_iboot *ib) return ret; drm_crtc_helper_add(&ib->crtc, &iboot_crtc_helper); + ret = drm_vblank_init(drm, 1); + if (ret) + return ret; + ret = drm_encoder_init(drm, &ib->encoder, &iboot_encoder_funcs, DRM_MODE_ENCODER_TMDS, NULL); if (ret) From 150065747fdb6aa09b9bbc95b74967f5d127211d Mon Sep 17 00:00:00 2001 From: Muness Castle <931+muness@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:30:24 -0500 Subject: [PATCH 0343/1514] arm64: dts: apple: enable PMP for M2 Pro and Max Move APPLE_USE_PMP to the T6021 SoC include. T6020 inherits it from that include, so drop the J414s board define. Pair the DTBs with a bootloader that can copy the PMP tunables. T6022 needs a separate change for its second-die AVD power domain. Link: https://github.com/aurora-silicon/aura/pull/268 Signed-off-by: Muness Castle <931+muness@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6020-j414s.dts | 6 ------ arch/arm64/boot/dts/apple/t6021.dtsi | 1 + 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6020-j414s.dts b/arch/arm64/boot/dts/apple/t6020-j414s.dts index 533bba8f4864d5..d25ddc974bd5ad 100644 --- a/arch/arm64/boot/dts/apple/t6020-j414s.dts +++ b/arch/arm64/boot/dts/apple/t6020-j414s.dts @@ -9,12 +9,6 @@ /dts-v1/; -/* - * Let m1n1 boot the PMP, which takes over the fabric and DCS p-states - * (needs an m1n1 that makes room for the PMP's tunables). - */ -#define APPLE_USE_PMP - #include "t6020.dtsi" #include "t602x-j414-j416.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6021.dtsi b/arch/arm64/boot/dts/apple/t6021.dtsi index bb1436a1f2dd40..f69afed98c55f8 100644 --- a/arch/arm64/boot/dts/apple/t6021.dtsi +++ b/arch/arm64/boot/dts/apple/t6021.dtsi @@ -24,6 +24,7 @@ #endif #define APPLE_T602X_NON_ULTRA +#define APPLE_USE_PMP #include "t602x-common.dtsi" From 96e069ad52d1f0b7455c654c6bd2ab0cb7710aa6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:08:55 +1100 Subject: [PATCH 0344/1514] drm/apple: dpavservep: test which AV service announcements are admitted dcpavserv_identity() decides which announced DP/HDMI AV service the AV client takes: the classic AFK wire (unit 0), the AFKV2 wire on the V2 endpoint (unit equal to the channel), the AFKV2 wire on the classic DPAV endpoint (unit 0, dynamic channel) and the native26 external role (DCPDPService, unit 0). It had no test. Add a table-driven KUnit suite, apple-dcpavserv-identity, that runs the function on a fake service, endpoint and DCP for 30 announcements: each admitted shape and the class, unit, channel and endpoint mismatches next to it, including the channel bounds (0 and over U16_MAX). No functional change. With dcpavserv_identity() as it was before the classic-endpoint AFKV2 case was added, the three "v2 ep 0x28" admit rows fail and the other 27 pass. Signed-off-by: Ryan Murray --- .../drm/apple/epic/dpavservep-identity-test.c | 143 ++++++++++++++++++ drivers/gpu/drm/apple/epic/dpavservep.c | 1 + 2 files changed, 144 insertions(+) create mode 100644 drivers/gpu/drm/apple/epic/dpavservep-identity-test.c diff --git a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c new file mode 100644 index 00000000000000..4f36cc35758b4c --- /dev/null +++ b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dpavservep.c: which announced AV services the DP/HDMI AV + * client admits. dcpavserv_identity() runs on a fake service, endpoint and + * DCP; each row is one announcement (name, class, unit, channel) on one + * endpoint and wire protocol. + */ +#include + +enum dpavid_role { + DPAVID_LEGACY, /* classic AFK wire */ + DPAVID_V2, /* AFKV2 wire */ + DPAVID_EXT26, /* AFKV2 wire, native26 external role */ +}; + +struct dpavid_case { + const char *desc; + enum dpavid_role role; + u32 endpoint; + const char *name; + const char *class; + s64 unit; + u32 channel; + bool admitted; +}; + +#define DPAVID_NAME "dcpav-service-epic" + +static const struct dpavid_case dpavid_cases[] = { + /* The service name gates every role. */ + { "legacy: no name", DPAVID_LEGACY, DPAVSERV_ENDPOINT, NULL, NULL, 0, 1, false }, + { "legacy: other name", DPAVID_LEGACY, DPAVSERV_ENDPOINT, "dcpav-service", + NULL, 0, 1, false }, + { "v2: other name", DPAVID_V2, DPAVSERV_ENDPOINT_V2, "dcpdp-service-epic", + "DCPDP13Service", 3, 3, false }, + { "ext26: other name", DPAVID_EXT26, DPAVSERV_ENDPOINT, "dcpdp-service-epic", + "DCPDPService", 0, 1, false }, + + /* Classic wire: unit 0 only, class and channel not consulted. */ + { "legacy: unit 0", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, NULL, 0, 0, true }, + { "legacy: unit 0, any class", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 9, true }, + { "legacy: unit 1", DPAVID_LEGACY, DPAVSERV_ENDPOINT, DPAVID_NAME, NULL, 1, 1, false }, + + /* AFKV2 on the V2 endpoint: interface-id is the unit, equal to the channel. */ + { "v2 ep 0x2a: DP2HDMI unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "AppleDCPDP2HDMI", 3, 3, true }, + { "v2 ep 0x2a: DP13 unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0xffff, 0xffff, true }, + { "v2 ep 0x2a: unit != channel", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 2, 3, false }, + { "v2 ep 0x2a: unit 0", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0, 3, false }, + { "v2 ep 0x2a: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0, 0, false }, + { "v2 ep 0x2a: channel over u16", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDP13Service", 0x10000, 0x10000, false }, + { "v2 ep 0x2a: no class", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + NULL, 3, 3, false }, + { "v2 ep 0x2a: DCPDPService class", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDPService", 3, 3, false }, + + /* AFKV2 on the classic DPAV endpoint: EPICUnit 0, dynamic channel. */ + { "v2 ep 0x28: DP13 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 7, true }, + { "v2 ep 0x28: DP2HDMI unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPDP2HDMI", 0, 1, true }, + { "v2 ep 0x28: unit 0, channel at u16 max", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0xffff, true }, + { "v2 ep 0x28: unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 7, 7, false }, + { "v2 ep 0x28: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0, false }, + { "v2 ep 0x28: channel over u16", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 0x10000, false }, + { "v2 ep 0x28: no class", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + NULL, 0, 7, false }, + { "v2 ep 0x28: DCPDPService class", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 7, false }, + + /* AFKV2 on any other endpoint. */ + { "v2 other endpoint", DPAVID_V2, 0x29, DPAVID_NAME, "DCPDP13Service", 0, 7, false }, + + /* native26: DCPDPService, unit 0, nonzero channel, classic endpoint only. */ + { "ext26: DCPDPService unit 0", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 1, true }, + { "ext26: unit 1", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 1, 1, false }, + { "ext26: channel 0", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDPService", 0, 0, false }, + { "ext26: no class", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + NULL, 0, 1, false }, + { "ext26: DP13 class", DPAVID_EXT26, DPAVSERV_ENDPOINT, DPAVID_NAME, + "DCPDP13Service", 0, 1, false }, + { "ext26: V2 endpoint", DPAVID_EXT26, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, + "DCPDPService", 0, 1, false }, +}; + +static void dpavid_case_desc(const struct dpavid_case *c, char *desc) +{ + strscpy(desc, c->desc, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dpavid, dpavid_cases, dpavid_case_desc); + +static void dpavid_admission(struct kunit *test) +{ + const struct dpavid_case *c = test->param_value; + struct apple_epic_service *svc; + struct apple_dcp_afkep *ep; + struct apple_dcp *dcp; + + dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + ep = kunit_kzalloc(test, sizeof(*ep), GFP_KERNEL); + svc = kunit_kzalloc(test, sizeof(*svc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dcp); + KUNIT_ASSERT_NOT_NULL(test, ep); + KUNIT_ASSERT_NOT_NULL(test, svc); + + if (c->role == DPAVID_EXT26) + dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + ep->dcp = dcp; + ep->endpoint = c->endpoint; + ep->wire_v2 = c->role != DPAVID_LEGACY; + svc->ep = ep; + svc->channel = c->channel; + + KUNIT_EXPECT_EQ(test, dcp_is_ext26(dcp), c->role == DPAVID_EXT26); + KUNIT_EXPECT_EQ(test, dcpavserv_identity(svc, c->name, c->class, c->unit), + c->admitted); +} + +static struct kunit_case dpavid_test_cases[] = { + KUNIT_CASE_PARAM(dpavid_admission, dpavid_gen_params), + {} +}; + +static struct kunit_suite dpavid_suite = { + .name = "apple-dcpavserv-identity", + .test_cases = dpavid_test_cases, +}; + +kunit_test_suite(dpavid_suite); diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index f94cf659e9a193..efc3babff3cb78 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -827,4 +827,5 @@ int dpavservep_init(struct apple_dcp *dcp) #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "dpavservep-v14-test.c" +#include "dpavservep-identity-test.c" #endif From 309a55f9c7d147d26852732ffb43b5273c341d9c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:15:43 +1100 Subject: [PATCH 0345/1514] soc: apple: clpc: test the frequency step, ceiling order, vote hold and floor word The low-power ceiling and the rail floors are built from four small helpers that had no test: apple_clpc_step_khz() (the next cpufreq table entry up or down, and the low-power top round-up), apple_clpc_steps_first() (which cluster's ceiling moves next), apple_clpc_vote() (the demand hold) and apple_clpc_floor() (the PMC floor word). Add a KUnit suite, apple-clpc-policy, next to apple-clpc-gpu: - step_khz on an unordered table with an invalid entry: one step either way, off-table values, both ends, and the first entry at or above low_power_khz (exact and in between, and none above the table). - steps_first: down takes the higher ceiling (the faster cluster on a tie), up the lower (the slower), and identical clusters keep the pick. - vote: a demand replaces the state at once, down as well as up; with no demand it holds for APPLE_CLPC_HOLD_MS and then drops, across the jiffies wrap. - floor: each rail's state in the nibble its table rail number names, masked so a wide state cannot spill into another rail. No functional change. A mutant that flips the steps_first tie-break, uses time_after() for the hold, drops the nibble mask and lets a down step return @khz itself fails all four new tests. Signed-off-by: Ryan Murray --- drivers/soc/apple/clpc.c | 137 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 4bd3d6c7c0a950..27c3a15da4fa9d 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -2085,6 +2085,143 @@ static struct kunit_suite apple_clpc_suite = { .test_cases = apple_clpc_cases, }; kunit_test_suite(apple_clpc_suite); + +/* A cpufreq table out of order, with an invalid entry, as a driver may give it. */ +static struct cpufreq_policy *apple_clpc_test_policy(struct kunit *test) +{ + static const unsigned int khz[] = { + 600000, CPUFREQ_ENTRY_INVALID, 1200000, 2000000, 1500000, + }; + struct cpufreq_frequency_table *table; + struct cpufreq_policy *policy; + unsigned int i; + + policy = kunit_kzalloc(test, sizeof(*policy), GFP_KERNEL); + table = kunit_kcalloc(test, ARRAY_SIZE(khz) + 1, sizeof(*table), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, policy); + KUNIT_ASSERT_NOT_NULL(test, table); + for (i = 0; i < ARRAY_SIZE(khz); i++) + table[i].frequency = khz[i]; + table[i].frequency = CPUFREQ_TABLE_END; + policy->freq_table = table; + policy->cpuinfo.max_freq = 2000000; + return policy; +} + +static void apple_clpc_step_khz_test(struct kunit *test) +{ + struct cpufreq_policy *policy = apple_clpc_test_policy(test); + + /* One table step either way, whatever the table order. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, true), 2000000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, false), 1200000u); + /* The invalid entry is not a step. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, false), 600000u); + /* Off the table: the nearest entry in that direction. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, false), 1200000u); + /* No step past either end: @khz back. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2000000, true), 2000000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000, false), 600000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2100000, true), 2100000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 0, false), 0u); + + /* + * The low-power top, as apple_clpc_profile_limit() takes it: the first + * entry at or above low_power_khz, so a value between two entries + * rounds up and an exact entry is kept. + */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1400000 - 1, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000 - 1, true), 1500000u); + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000 - 1, true), 600000u); + /* Above the table nothing is found; the caller falls back to max_freq. */ + KUNIT_EXPECT_LT(test, apple_clpc_step_khz(policy, 2100000 - 1, true), 2100000u); +} + +static void apple_clpc_steps_first_test(struct kunit *test) +{ + /* Down: the higher ceiling first; on a tie, the faster cluster. */ + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(2000000, 2000000, 1500000, 3000000, false)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 3000000, 2000000, 2000000, false)); + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 3000000, 1500000, 2000000, false)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 3000000, false)); + + /* Up: the lower ceiling first; on a tie, the slower cluster. */ + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 3000000, 2000000, 2000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(2000000, 2000000, 1500000, 3000000, true)); + KUNIT_EXPECT_TRUE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 3000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 3000000, 1500000, 2000000, true)); + + /* Identical clusters: the one already picked keeps the step. */ + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 2000000, true)); + KUNIT_EXPECT_FALSE(test, apple_clpc_steps_first(1500000, 2000000, 1500000, 2000000, false)); +} + +static void apple_clpc_vote_test(struct kunit *test) +{ + unsigned long hold = msecs_to_jiffies(APPLE_CLPC_HOLD_MS); + /* Start close to the jiffies wrap, so the hold spans it. */ + unsigned long t0 = ULONG_MAX - hold / 2; + struct apple_clpc_vote vote = {}; + + KUNIT_ASSERT_GT(test, hold, 1ul); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0), 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 5, t0), 5u); + /* No demand: the state holds for APPLE_CLPC_HOLD_MS, then drops. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + hold - 1), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + hold), 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 2 * hold), 0u); + + /* A new demand replaces the state at once, down as well as up. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 7, t0 + 2 * hold), 7u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 2, t0 + 2 * hold + 1), 2u); + /* and restarts the hold. */ + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 3 * hold), 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0 + 3 * hold + 1), 0u); +} + +static void apple_clpc_floor_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + struct apple_clpc_hw *hw = kunit_kzalloc(test, sizeof(*hw), GFP_KERNEL); + unsigned int state[APPLE_CLPC_RAILS] = {}; + + KUNIT_ASSERT_NOT_NULL(test, clpc); + KUNIT_ASSERT_NOT_NULL(test, hw); + clpc->hw = hw; + + /* Each rail's state in its own nibble of the PMC floor word. */ + hw->rail[APPLE_CLPC_DCS] = 0; + hw->rail[APPLE_CLPC_SOC] = 1; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0u); + state[APPLE_CLPC_DCS] = 5; + state[APPLE_CLPC_SOC] = 3; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0x35u); + + /* The rail numbers come from the table, not the rail order. */ + hw->rail[APPLE_CLPC_DCS] = 2; + hw->rail[APPLE_CLPC_SOC] = 0; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0x503u); + + /* A state wider than a nibble cannot spill into another rail. */ + state[APPLE_CLPC_DCS] = 0x1f; + state[APPLE_CLPC_SOC] = 0x10; + KUNIT_EXPECT_EQ(test, apple_clpc_floor(clpc, state), 0xf00u); +} + +static struct kunit_case apple_clpc_policy_cases[] = { + KUNIT_CASE(apple_clpc_step_khz_test), + KUNIT_CASE(apple_clpc_steps_first_test), + KUNIT_CASE(apple_clpc_vote_test), + KUNIT_CASE(apple_clpc_floor_test), + {} +}; +static struct kunit_suite apple_clpc_policy_suite = { + .name = "apple-clpc-policy", + .test_cases = apple_clpc_policy_cases, +}; +kunit_test_suite(apple_clpc_policy_suite); #endif /* T8152: DCS states 0-7 and fabric states 0-4. */ From 1a6e3dbe385f093fde94448c59a505e3a6965082 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:16:21 +1100 Subject: [PATCH 0346/1514] Revert "spi: apple-qspi: runtime suspend any controller in a power domain" This reverts commit 7127d7310c1b1c4b2e61d9885400b0ca423233f3. That change turns on runtime suspend for every QSPIMC controller in a power domain, including the T8132 and T6041 boards that write NVRAM, and it has no NVRAM write row across an autosuspend gap on any of them. Its stated motivation also did not hold: the J615 blank idle stayed at 3.46 W with it applied. It moves to its own pull request, together with holding the controller powered across a whole NVRAM erase/program/verify sequence. This series stays the J615 read-only NVRAM fix it was tested as. Signed-off-by: Ryan Murray --- drivers/spi/spi-apple-qspi.c | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/drivers/spi/spi-apple-qspi.c b/drivers/spi/spi-apple-qspi.c index 270e53ebd13477..d3af8452c9aad3 100644 --- a/drivers/spi/spi-apple-qspi.c +++ b/drivers/spi/spi-apple-qspi.c @@ -94,6 +94,7 @@ struct apple_qspi_soc { /* T8140: data reads of any shape pass straight to the controller. */ bool multi_io_reads; + bool runtime_pm; }; /* @@ -1076,12 +1077,8 @@ static int apple_qspi_probe(struct platform_device *pdev) ctlr->mem_ops = &apple_qspi_mem_ops; platform_set_drvdata(pdev, ctlr); - /* - * A controller in a power domain lets it gate between accesses, which - * it otherwise holds on for as long as the driver is bound. Keep probe - * and SPI NOR discovery powered until registration finishes. - */ - if (dev->pm_domain && IS_ENABLED(CONFIG_PM)) { + /* Keep probe and SPI NOR discovery powered until registration finishes. */ + if (soc->runtime_pm && IS_ENABLED(CONFIG_PM)) { pm_runtime_get_noresume(dev); ret = devm_pm_runtime_set_active_enabled(dev); if (ret) { @@ -1266,6 +1263,7 @@ static const struct apple_qspi_soc apple_qspi_single_io = { }; static const struct apple_qspi_soc apple_qspi_t8140 = { .multi_io_reads = true, + .runtime_pm = true, }; static const struct of_device_id apple_qspi_of_match[] = { From c35175c18c72f347aa086781155b2bf630d4171f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:19:52 +1100 Subject: [PATCH 0347/1514] drm/apple: dcp: test the boot loader handoff checks Two checks read the state the boot loader hands the display over in, and neither had a test: - dcp_external_is_idle(), which an H17P external DCP must pass at probe and again just before startup: CPU_CONTROL RUN set and CPU_STATUS STOPPED and IDLE both set. - boot_show_notch(), which follows /chosen/asahi,show-notch so the mode covers the same rows as the boot framebuffer. Add a KUnit suite, apple-dcp-handoff. The idle check runs on a fake coprocessor register window: all eight combinations of the three bits, then with every other bit set in both registers. The notch check applies the property to /chosen through an OF changeset and reverts it: only the string "1" shows the notch; absent, "0", "", "10", "yes", a u32 cell and an empty property do not. No functional change. With the IDLE bit check dropped, or with any string accepted for the notch, the matching test fails. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 1 + drivers/gpu/drm/apple/dcp_handoff_test.c | 129 +++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 drivers/gpu/drm/apple/dcp_handoff_test.c diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..bf4dc01b60e000 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -10166,4 +10166,5 @@ void dcp_unregister(void) #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "dcp_external_audio_test.c" +#include "dcp_handoff_test.c" #endif diff --git a/drivers/gpu/drm/apple/dcp_handoff_test.c b/drivers/gpu/drm/apple/dcp_handoff_test.c new file mode 100644 index 00000000000000..8bd8481866133c --- /dev/null +++ b/drivers/gpu/drm/apple/dcp_handoff_test.c @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by dcp.c: the boot loader handoff state the driver reads before + * it starts a display coprocessor. dcp_external_is_idle() runs on a fake + * coprocessor register window; boot_show_notch() on /chosen, with the + * property applied and reverted through an OF changeset. + */ +#include +#include + +#define DCP_HANDOFF_COPROC_SIZE (APPLE_DCP_COPROC_CPU_STATUS + sizeof(u32)) + +static struct apple_dcp *dcp_handoff_coproc(struct kunit *test, u32 control, u32 status) +{ + struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + void *regs = kunit_kzalloc(test, DCP_HANDOFF_COPROC_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, dcp); + KUNIT_ASSERT_NOT_NULL(test, regs); + *(u32 *)(regs + APPLE_DCP_COPROC_CPU_CONTROL) = control; + *(u32 *)(regs + APPLE_DCP_COPROC_CPU_STATUS) = status; + dcp->coproc_reg = (void __iomem __force *)regs; + return dcp; +} + +static void dcp_handoff_external_idle(struct kunit *test) +{ + const u32 run = APPLE_DCP_COPROC_CPU_CONTROL_RUN; + const u32 stopped = APPLE_DCP_COPROC_CPU_STATUS_STOPPED; + const u32 idle = APPLE_DCP_COPROC_CPU_STATUS_IDLE; + unsigned int bits; + + /* Inherited idle: the CPU enabled, and stopped and idle in its status. */ + KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, run, + stopped | idle))); + + /* Every other combination of the three bits is not. */ + for (bits = 0; bits < 7; bits++) { + u32 control = bits & 1 ? run : 0; + u32 status = (bits & 2 ? stopped : 0) | (bits & 4 ? idle : 0); + + KUNIT_EXPECT_FALSE_MSG(test, + dcp_external_is_idle(dcp_handoff_coproc(test, control, + status)), + "control %#x status %#x", control, status); + } + + /* Other bits in either register do not change the answer. */ + KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, ~0u))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~run, ~0u))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, ~idle))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, + ~stopped))); +} + +/* boot_show_notch() with /chosen/asahi,show-notch set by @add, or absent. */ +static bool dcp_handoff_notch(struct kunit *test, + int (*add)(struct of_changeset *cs, struct device_node *np)) +{ + struct of_changeset cs; + bool ret; + + if (!add) + return boot_show_notch(); + of_changeset_init(&cs); + KUNIT_ASSERT_EQ(test, add(&cs, of_chosen), 0); + KUNIT_ASSERT_EQ(test, of_changeset_apply(&cs), 0); + ret = boot_show_notch(); + KUNIT_EXPECT_EQ(test, of_changeset_revert(&cs), 0); + of_changeset_destroy(&cs); + return ret; +} + +#define DCP_HANDOFF_NOTCH_STRING(tag, value) \ +static int dcp_handoff_notch_##tag(struct of_changeset *cs, struct device_node *np) \ +{ \ + return of_changeset_add_prop_string(cs, np, "asahi,show-notch", value); \ +} + +DCP_HANDOFF_NOTCH_STRING(one, "1") +DCP_HANDOFF_NOTCH_STRING(zero, "0") +DCP_HANDOFF_NOTCH_STRING(empty, "") +DCP_HANDOFF_NOTCH_STRING(ten, "10") +DCP_HANDOFF_NOTCH_STRING(yes, "yes") + +static int dcp_handoff_notch_u32(struct of_changeset *cs, struct device_node *np) +{ + return of_changeset_add_prop_u32(cs, np, "asahi,show-notch", 1); +} + +static int dcp_handoff_notch_bool(struct of_changeset *cs, struct device_node *np) +{ + return of_changeset_add_prop_bool(cs, np, "asahi,show-notch"); +} + +static void dcp_handoff_boot_notch(struct kunit *test) +{ + if (!of_chosen) + kunit_skip(test, "no /chosen node"); + if (of_property_present(of_chosen, "asahi,show-notch")) + kunit_skip(test, "/chosen already has asahi,show-notch"); + + /* Absent: the driver keeps the notch rows out of the mode. */ + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, NULL)); + /* Only the string "1" the boot loader writes shows the notch. */ + KUNIT_EXPECT_TRUE(test, dcp_handoff_notch(test, dcp_handoff_notch_one)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_zero)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_empty)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_ten)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_yes)); + /* A cell or an empty property is not the string "1". */ + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_u32)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_bool)); + /* Reverted: absent again. */ + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, NULL)); +} + +static struct kunit_case dcp_handoff_cases[] = { + KUNIT_CASE(dcp_handoff_external_idle), + KUNIT_CASE(dcp_handoff_boot_notch), + {} +}; + +static struct kunit_suite dcp_handoff_suite = { + .name = "apple-dcp-handoff", + .test_cases = dcp_handoff_cases, +}; + +kunit_test_suite(dcp_handoff_suite); From 574c9cfd35d6b9db0ea63061dac99bd37ad05f83 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:23:43 +1100 Subject: [PATCH 0348/1514] pmdomain: apple: pmgr-pwrstate: test the reset controller operations Each power state also registers a one-line reset controller, and its assert, deassert, reset, status and xlate operations had no test: the apple-pmgr-pwrstate suite drives only power transitions and consumers. Add four cases on the suite's emulated register: - assert sets DEV_DISABLE and RESET without touching the power state, deassert clears both, status reads RESET back, a reset pulse (also with the T8132 deassert delay) ends deasserted, and xlate maps every phandle to line 0; - no reset write carries a WAS_*GATED flag, which is write-one-to-clear (the emulated register now counts such writes); - a firmware-owned or boot-loader-inherited domain refuses all four operations with -EPERM and its register is not written; - with the idle wait before reset (set on T8132), an idle block is reset, while one that stays busy is quiesced but not reset, assert and reset return -ETIMEDOUT, and the lock is released for the following deassert. No functional change. Dropping the flags from the assert mask, the owner check from status, the timeout return from the idle wait, or the DEV_DISABLE clear from deassert each fails a new case. Signed-off-by: Ryan Murray --- drivers/pmdomain/apple/pmgr-pwrstate-test.c | 125 ++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index 66fb065523dee0..39a9ec8000af76 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -18,6 +18,7 @@ struct pmgr_ps_test_reg { bool latched; /* bit 11 latched: on stops at clock-gated, off still reaches 0 */ bool latch_sticky; /* not even a PS reset clears it */ unsigned int reset_writes; /* writes with the PS reset bit */ + unsigned int flag_writes; /* writes that would clear a WAS_*GATED flag */ }; static int pmgr_ps_test_read(void *ctx, unsigned int reg, unsigned int *val) @@ -69,6 +70,8 @@ static int pmgr_ps_test_write(void *ctx, unsigned int reg, unsigned int val) r->busy_writes++; if (val & APPLE_PMGR_AUTO_ENABLE) r->auto_writes++; + if (val & APPLE_PMGR_FLAGS) + r->flag_writes++; r->val = (val & ~(APPLE_PMGR_PS_ACTUAL | APPLE_PMGR_BUSY)) | parent | FIELD_PREP(APPLE_PMGR_PS_ACTUAL, actual); return 0; @@ -544,6 +547,124 @@ static void pmgr_ps_consumer_refused_test(struct kunit *test) APPLE_PMGR_PS_ACTIVE); } +/* + * A powered-on domain with its reset controller, as probe registers it; + * @second for a second domain in one test (apple,no-auto-pm, which the + * reset operations do not read, gives its device another name). + */ +static struct apple_pmgr_ps *pmgr_ps_test_reset_domain(struct kunit *test, bool second, + struct pmgr_ps_test_reg **reg) +{ + struct apple_pmgr_ps *ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_ACTIVE, second, reg); + + spin_lock_init(&ps->genpd.slock); + ps->genpd.status = GENPD_STATE_ON; + ps->offset = 0x100; + ps->rcdev.ops = &apple_pmgr_reset_ops; + ps->rcdev.nr_resets = 1; + ps->rcdev.of_xlate = apple_pmgr_reset_xlate; + return ps; +} + +/* Assert quiesces, then resets; deassert undoes both; status reads it back. */ +static void pmgr_ps_reset_assert_deassert_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 1); + /* The power state is left alone. */ + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_EQ(test, r->reset_writes, 0u); + + /* A pulse ends deasserted; the T8132 deassert delay changes nothing else. */ + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); + ps->reset_time_us = APPLE_PMGR_T8132_RESET_TIME; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); + + /* Every phandle argument names the domain's one reset line. */ + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, NULL), 0); +} + +/* The WAS_*GATED flags are write-one-to-clear: reset writes never set them. */ +static void pmgr_ps_reset_keeps_flags_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); + r->val |= APPLE_PMGR_FLAGS; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->flag_writes, 0u); +} + +/* A domain the boot loader or firmware owns refuses every reset operation. */ +static void pmgr_ps_reset_refused_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + unsigned int owner; + u32 val; + + for (owner = 0; owner < 2; owner++) { + ps = pmgr_ps_test_reset_domain(test, owner, &r); + if (owner) + ps->inherited_on = true; + else + ps->firmware_owned = true; + r->val |= APPLE_PMGR_RESET; + val = r->val; + + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), -EPERM); + KUNIT_EXPECT_EQ(test, r->val, val); + } +} + +/* With the idle wait before reset (T8132), a block that stays busy is never reset. */ +static void pmgr_ps_reset_idle_wait_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + + ps->needs_reset_idle_wait = true; + /* Idle: the wait passes and the reset goes in. */ + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + + /* Busy for good: quiesced, but not reset, and the lock is released. */ + r->parent_stuck = true; + r->val |= APPLE_PMGR_BUSY; + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); +} + static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_power_on_test), KUNIT_CASE(pmgr_ps_power_off_undo_test), @@ -563,6 +684,10 @@ static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_consumer_retention_mask_test), KUNIT_CASE(pmgr_ps_consumer_plain_test), KUNIT_CASE(pmgr_ps_consumer_refused_test), + KUNIT_CASE(pmgr_ps_reset_assert_deassert_test), + KUNIT_CASE(pmgr_ps_reset_keeps_flags_test), + KUNIT_CASE(pmgr_ps_reset_refused_test), + KUNIT_CASE(pmgr_ps_reset_idle_wait_test), {} }; From f9f5b6b2cd2bac083fbc027618a9060bd417fac7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:28:46 +1100 Subject: [PATCH 0349/1514] soc: apple: display-gate, drm/apple: tighten the T8122 dcpext 27.2 window copy gate_t8122_dcpext_alias() took the internal DCP DART's apple,dma-range whatever its length. The DART driver reads that property as one window, a start and a size (two u64), so copy only a property of that length; anything else leaves the dcpext disabled as a missing window does. Free the property it built if the changeset does not take it. In the DCP driver, the T8122 dcpext on firmware 27 runs in the window the gate copied, the panel's (0x100_0000_0000 + 64 GiB), not the device tree's: say so, and give it the internal processor's 41-bit firmware DMA addressing, as the T8122 and T6041 processors on firmware 27 have. The window is below 2^41, so its mappings do not change. The refusal of other firmware now names both images the driver runs. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 7 +++++-- drivers/soc/apple/display-gate.c | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 860ad5fc61669d..56c05695e51bca 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6018,7 +6018,7 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); if (!strcmp(compat_str, "14.7.0")) return DCP_FIRMWARE_V_14_7_TEMPLATE; - dev_err(dev, "T8122 external display not started: DCP firmware-compat %s is not 14.7.0\n", + dev_err(dev, "T8122 external display not started: DCP firmware-compat %s is neither 14.7.0 nor the 27.2 image\n", compat_str); return DCP_FIRMWARE_UNKNOWN; } @@ -7279,10 +7279,13 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) * The T8122 external processor on firmware 27: the boot loader leaves * it unpowered (its DISPEXT domains are off at handoff), so Linux * starts it as on 14.7, with the firmware-27 endpoints and both DPTX - * port services. Its DART window is the one the device tree describes. + * port services. Its DART window is the internal panel's, which the + * display gate copied onto its DARTs (gate_t8122_dcpext_alias()): + * 0x100_0000_0000 + 64 GiB, so 41-bit firmware DMA addressing as there. */ if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { + dcp->hw.firmware_dma_bits = 41; dcp->hw.num_dptx_ports = 2; dcp->hw.fw_14_7_endpoints = false; dcp->hw.adopt_live_session = false; diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 2fb625de5b2b61..b98ad412388643 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -1903,7 +1903,8 @@ static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, panel_dart = dcp ? of_parse_phandle(dcp, "iommus", 0) : NULL; of_node_put(dcp); window = panel_dart ? of_find_property(panel_dart, "apple,dma-range", NULL) : NULL; - if (!window || !window->length) { + /* One window: its start and its size, as the DART driver reads it. */ + if (!window || window->length != 2 * sizeof(u64)) { of_node_put(panel_dart); return -ENODEV; } @@ -1923,6 +1924,10 @@ static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, prop->length = window->length; prop->value = value; ret = of_changeset_update_property(cs, targets[i], prop); + if (ret) { + kfree(prop); + kfree(value); + } } of_node_put(panel_dart); return ret; From 6a1865f4ff6dba63ac7bb2de859bca3a9e68e705 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:28:46 +1100 Subject: [PATCH 0350/1514] soc: apple: display-gate: expect the 27.2 PMP image in its KUnit case gate_t8122_pmp_image_27_2 hands the gate the 27.2 PMP image, which the gate takes, then checks the enabled PMP against the fixture's 14.x image UUID, so it always failed. Check it against the image the case passed. Signed-off-by: Ryan Murray --- drivers/soc/apple/display-gate-test.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index dbd534537e87ca..3ab52c0014072a 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -158,6 +158,7 @@ struct gate_test { bool requested, t6031_requested; int t6031_switch; const char *t6031_board; + const char *pmp_uuid; /* the PMP image the values name: the fixture's unless set */ }; static struct device_node *__init gt_node(struct kunit *test, const char *path) @@ -333,7 +334,7 @@ static void __init gt_expect_enabled(struct kunit *test) KUNIT_EXPECT_TRUE(test, of_device_is_compatible(pmp, s->pmp_compat)); KUNIT_EXPECT_FALSE(test, of_device_is_available(pmp)); KUNIT_ASSERT_EQ(test, of_property_read_string(pmp, "apple,tunable-uuid", &uuid), 0); - KUNIT_EXPECT_STREQ(test, uuid, s->pmp_uuid); + KUNIT_EXPECT_STREQ(test, uuid, t->pmp_uuid); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,tunable-test")); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,board-id")); KUNIT_EXPECT_TRUE(test, of_property_present(pmp, "apple,dram-vendor-id")); @@ -404,6 +405,7 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) return -ENOMEM; test->priv = t; t->s = s; + t->pmp_uuid = s->pmp_uuid; /* As the boot left them: the test kernel's command line sets neither. */ t->requested = gate_requested; t->t6031_requested = gate_t6031_requested; @@ -833,8 +835,10 @@ static void __init gate_t8122_t6031_pmp_image(struct kunit *test) /* The 27.2 (26B123) T8122 PMP image is taken as well. */ static void __init gate_t8122_pmp_image_27_2(struct kunit *test) { - gt_set_string(test, gt_t8122.values, "apple,tunable-uuid", - "C6CCB960-AC83-34A2-9493-C3131BD5AE4B"); + struct gate_test *t = test->priv; + + t->pmp_uuid = "C6CCB960-AC83-34A2-9493-C3131BD5AE4B"; + gt_set_string(test, gt_t8122.values, "apple,tunable-uuid", t->pmp_uuid); gt_run(test); gt_expect_enabled(test); } From dc4e9e6d6bcbfc5c1b0d168c42c7ab15ee480f81 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:28:47 +1100 Subject: [PATCH 0351/1514] soc: apple: display-gate: test the T8122 dcpext on 14.7 and on 27.2 Add the T8122 external display processor (dcpext) of t8122-dcp.dtsi to the gate's T8122 test tree, with its DARTs' 14.7 windows and the panel DARTs' window, but without the boot loader's firmware-ready mark, and KUnit cases for its admission: - without the mark it stays disabled; - on 14.7.0 it is enabled with its DARTs, mailbox, power floor, PMP DISPEXT request and display DART, and keeps the device tree's windows; - on 27.2.0 beside an internal DCP handed over on the 27.2 image (apple_t8122_dcpext_v27_2()) both of its DARTs get the panel's window; - 27.2.0 beside an internal DCP on its 14.x image, another version than compatibility, no version, or 27.0.0 leave it disabled; - without a panel window the 27.2 one is not enabled and nothing changes; - gate_t8122_dcpext_alias() alone copies one window onto both DARTs and refuses a window that is not one start and one size. The gate keeps the changeset that enabled the dcpext so the test can revert it, as it does for the panel's. Signed-off-by: Ryan Murray --- drivers/soc/apple/display-gate-test.c | 241 ++++++++++++++++++++++++- drivers/soc/apple/display-gate.c | 3 + drivers/soc/apple/t8122-gate-test.dtso | 72 +++++++- 3 files changed, 313 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index 3ab52c0014072a..c662de976f7af8 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -14,7 +14,9 @@ * changed when a check fails. * - T8122 (t8122-gate-test.dtso): on by default, with the full handoff, * and nothing changed when a check of the handoff or of the reused PMP - * topology fails. + * topology fails. Its external processor (dcpext) starts on 14.7.0, and + * on the 27.2 image beside an internal DCP handed over on it, with the + * panel's DMA window on both of its DARTs; otherwise it stays disabled. * - T6041: no test tree; a PMP that binds after the deadline still * starts the external display power-up, and only a failed PMP or power-up * leaves the internal panel alone. @@ -419,6 +421,7 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) gate_requested = true; gate_t6031_requested = false; gate_t6031_switch = -1; + gate_t8122_dcpext_cs = NULL; if (gt_live_soc) kunit_skip(test, "the booted device tree has its own /soc"); return 0; @@ -443,6 +446,12 @@ static void __init gt_exit(struct kunit *test) { struct gate_test *t = test->priv; + /* The T8122 dcpext's changes build on the display's: reverted first. */ + if (gate_t8122_dcpext_cs) { + of_changeset_revert(gate_t8122_dcpext_cs); + gate_cs_free(gate_t8122_dcpext_cs); + gate_t8122_dcpext_cs = NULL; + } /* The gate leaves its changes applied only when it enabled the display. */ if (gate_pmp_ovcs) { of_changeset_revert(&gate_pmp_cs); @@ -909,6 +918,227 @@ static void __init gate_t8122_enabled_again(struct kunit *test) gt_expect_enabled(test); } +/* T8122 external display processor (dcpext) */ + +#define GT_T8122_DCPEXT "/t8122-soc/dcp@31ac00000" +#define GT_T8122_DCPEXT_DART "/t8122-soc/iommu@31930c000" +#define GT_T8122_DISPEXT_DART "/t8122-soc/iommu@319304000" +#define GT_T8122_DCPEXT_MBOX "/t8122-soc/mailbox@31ac08000" +#define GT_T8122_DCPEXT_PS "/t8122-soc/power-management@2d0700000/power-controller@488" +#define GT_T8122_DCPEXT_ENTRY "/t8122-soc/pmp_report@2d03c0000/report@8" + +/* The device tree's 14.7 windows of the dcpext DARTs, and the panel's. */ +static const u64 gt_t8122_dcpext_window[2] __initconst = { 0x800000000, 0x7ffff0000 }; +static const u64 gt_t8122_dispext_window[2] __initconst = { 0x0, 0xfffff0000 }; +static const u64 gt_t8122_panel_window[2] __initconst = { 0x10000000000, 0x1000000000 }; + +static const u32 gt_v14_7[3] __initconst = { 14, 7, 0 }; +static const u32 gt_v27_0[3] __initconst = { 27, 0, 0 }; +static const u32 gt_v27_2[3] __initconst = { 27, 2, 0 }; + +/* Sets, or adds, the u32 array @name of @path. */ +static void __init gt_set_u32_array(struct kunit *test, const char *path, const char *name, + const u32 *val, size_t n) +{ + struct gate_test *t = test->priv; + struct device_node *np = gt_node(test, path); + + if (of_property_present(np, name)) + gt_remove(test, path, name); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32_array(&t->cs, np, name, val, n), 0); +} + +/* The dcpext as the boot loader marks it, with these firmware versions. */ +static void __init gt_t8122_dcpext_firmware(struct kunit *test, const u32 version[3], + const u32 compat[3]) +{ + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 1); + if (version) + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-version", version, 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", compat, 3); +} + +/* The internal DCP handed over on the 27.2 (26B123) image. */ +static void __init gt_t8122_dcp_v27_2(struct kunit *test) +{ + gt_set_string(test, gt_t8122.dcp, "apple,firmware-uuid", APPLE_T8122_DCP_26B123_UUID); + gt_set_u32_array(test, gt_t8122.dcp, "apple,firmware-version", gt_v27_2, 3); + gt_set_u32_array(test, gt_t8122.dcp, "apple,firmware-compat", gt_v27_2, 3); +} + +static void __init gt_expect_window(struct kunit *test, const char *path, const u64 want[2]) +{ + u64 window[2] = {}; + + KUNIT_ASSERT_EQ_MSG(test, of_property_read_u64_array(gt_node(test, path), + "apple,dma-range", window, 2), 0, + "%s", path); + KUNIT_EXPECT_EQ_MSG(test, window[0], want[0], "%s start", path); + KUNIT_EXPECT_EQ_MSG(test, window[1], want[1], "%s size", path); +} + +/* + * The panel as gt_expect_enabled() checks it, and the dcpext enabled or not + * with all it needs. @window: the window both dcpext DARTs must have, NULL + * for the device tree's own. + */ +static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 *window) +{ + struct device_node *display = gt_node(test, gt_t8122.display); + struct device_node *entry = gt_node(test, GT_T8122_DCPEXT_ENTRY); + struct of_phandle_args args; + + gt_expect_enabled(test); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT_DART), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DISPEXT_DART), enabled); + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT_MBOX), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,always-on"), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,soc-device-record"), enabled); + KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,defer-startup-ack"), enabled); + KUNIT_EXPECT_EQ(test, gt_u32(test, GT_T8122_DCPEXT_PS, "apple,min-state"), + enabled ? PMGR_PS_ACTIVE : 4); + /* Its scanout DART joins the display subsystem's, after the panel's. */ + KUNIT_EXPECT_EQ(test, of_count_phandle_with_args(display, "iommus", "#iommu-cells"), + enabled ? 2 : 1); + if (enabled) { + KUNIT_ASSERT_EQ(test, of_parse_phandle_with_args(display, "iommus", + "#iommu-cells", 1, &args), 0); + KUNIT_EXPECT_PTR_EQ(test, args.np, gt_node(test, GT_T8122_DISPEXT_DART)); + of_node_put(args.np); + } + gt_expect_window(test, GT_T8122_DCPEXT_DART, window ?: gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, window ?: gt_t8122_dispext_window); + /* The panel's own window stays as it is. */ + gt_expect_window(test, "/t8122-soc/iommu@28d30c000", gt_t8122_panel_window); +} + +static void __init gt_require_display_driver(struct kunit *test) +{ + if (!IS_ENABLED(CONFIG_DRM_APPLE)) + kunit_skip(test, "the gate keeps the dcpext off without the display driver"); +} + +/* Without the boot loader's firmware-ready mark the dcpext stays disabled. */ +static void __init gate_t8122_dcpext_not_ready(struct kunit *test) +{ + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* On 14.7.0 it starts with the device tree's windows. */ +static void __init gate_t8122_dcpext_v14_7(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_run(test); + gt_expect_dcpext(test, true, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +/* + * On the 27.2 image, beside an internal DCP handed over on it, it starts + * with the panel's window on both of its DARTs. + */ +static void __init gate_t8122_dcpext_v27_2(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, true, gt_t8122_panel_window); + KUNIT_EXPECT_TRUE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); + /* The internal DCP itself is not the external processor. */ + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, gt_t8122.dcp))); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(NULL)); +} + +/* 27.2.0 next to an internal DCP on its 14.x image is not the 27.2 image. */ +static void __init gate_t8122_dcpext_v27_2_internal_v14(struct kunit *test) +{ + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +/* Both its version and its compatibility must be 27.2.0. */ +static void __init gate_t8122_dcpext_v27_2_other_version(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_0, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); + KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); +} + +static void __init gate_t8122_dcpext_v27_2_no_version(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, NULL, gt_v27_2); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +static void __init gate_t8122_dcpext_other_firmware(struct kunit *test) +{ + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_0, gt_v27_0); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* Without the panel's window there is none to give it: nothing changes. */ +static void __init gate_t8122_dcpext_v27_2_no_panel_window(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_remove(test, "/t8122-soc/iommu@28d30c000", "apple,dma-range"); + gt_run(test); + gt_expect_enabled(test); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DCPEXT)); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DCPEXT_DART)); + KUNIT_EXPECT_FALSE(test, gt_okay(test, GT_T8122_DISPEXT_DART)); + KUNIT_EXPECT_FALSE(test, of_property_read_bool(gt_node(test, GT_T8122_DCPEXT_ENTRY), + "apple,always-on")); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_dispext_window); +} + +/* + * gate_t8122_dcpext_alias() alone: it copies one window (start and size) + * onto both DARTs, and takes nothing else. + */ +static void __init gate_t8122_dcpext_alias_window(struct kunit *test) +{ + struct device_node *dart = gt_node(test, GT_T8122_DCPEXT_DART); + struct device_node *disp_dart = gt_node(test, GT_T8122_DISPEXT_DART); + static const u32 short_window[2] __initconst = { 0x100, 0x0 }; + struct gate_test *t = test->priv; + struct of_changeset cs; + + of_changeset_init(&cs); + KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_alias(&cs, dart, disp_dart), 0); + KUNIT_ASSERT_EQ(test, of_changeset_apply(&cs), 0); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_panel_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_panel_window); + KUNIT_EXPECT_EQ(test, of_changeset_revert(&cs), 0); + of_changeset_destroy(&cs); + gt_expect_window(test, GT_T8122_DCPEXT_DART, gt_t8122_dcpext_window); + gt_expect_window(test, GT_T8122_DISPEXT_DART, gt_t8122_dispext_window); + + /* A window that is not one start and one size is refused. */ + gt_set_u32_array(test, "/t8122-soc/iommu@28d30c000", "apple,dma-range", + short_window, ARRAY_SIZE(short_window)); + KUNIT_ASSERT_EQ(test, of_changeset_apply(&t->cs), 0); + of_changeset_init(&cs); + KUNIT_EXPECT_EQ(test, gate_t8122_dcpext_alias(&cs, dart, disp_dart), -ENODEV); + KUNIT_EXPECT_TRUE(test, list_empty(&cs.entries)); + of_changeset_destroy(&cs); +} + /* The case and suite structs outlive init: only the functions are init code. */ static struct kunit_case gate_t6031_cases[] __refdata = { KUNIT_CASE(gate_t6031_param), @@ -983,6 +1213,15 @@ static struct kunit_case gate_t8122_cases[] __refdata = { KUNIT_CASE(gate_t8122_disp_no_ack), KUNIT_CASE(gate_t8122_no_storage_request), KUNIT_CASE(gate_t8122_not_inherited_on), + KUNIT_CASE(gate_t8122_dcpext_not_ready), + KUNIT_CASE(gate_t8122_dcpext_v14_7), + KUNIT_CASE(gate_t8122_dcpext_v27_2), + KUNIT_CASE(gate_t8122_dcpext_v27_2_internal_v14), + KUNIT_CASE(gate_t8122_dcpext_v27_2_other_version), + KUNIT_CASE(gate_t8122_dcpext_v27_2_no_version), + KUNIT_CASE(gate_t8122_dcpext_other_firmware), + KUNIT_CASE(gate_t8122_dcpext_v27_2_no_panel_window), + KUNIT_CASE(gate_t8122_dcpext_alias_window), KUNIT_CASE(gate_t8122_enabled_again), {} }; diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index b98ad412388643..8950f960b1ff9c 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -1828,6 +1828,8 @@ static void __init gate_describe(void) * alone. apple_t8122_display.dcpext=0 keeps them disabled too. */ static bool gate_t8122_dcpext_requested __initdata = true; +/* The changeset that enabled the dcpext; only the KUnit test reverts it. */ +static struct of_changeset *gate_t8122_dcpext_cs __initdata; static int __init gate_t8122_dcpext_setup(char *arg) { @@ -2067,6 +2069,7 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) gate_ext_refuse(np, "the gate could not enable it"); goto put; } + gate_t8122_dcpext_cs = cs; gate_info("enabled %pOF with its Type-C routes, DARTs, mailbox, %d display crossbar(s) with ATC common power kept on, display DART %pOF in the display subsystem, CPU power floor and PMP DISPEXT request; started by the display driver\n", np, nxbar, disp_dart); put: diff --git a/drivers/soc/apple/t8122-gate-test.dtso b/drivers/soc/apple/t8122-gate-test.dtso index beee48ab0afd9d..835a38a4e935e5 100644 --- a/drivers/soc/apple/t8122-gate-test.dtso +++ b/drivers/soc/apple/t8122-gate-test.dtso @@ -4,7 +4,10 @@ * nodes of t8122-dcp.dtsi with the boot loader's handoff applied, the power * states they hang from, the PMP topology of t8122.dtsi that the gate * reuses, and PMP values. The values are made up: only their presence and - * the PMP image UUID matter to the gate. + * the PMP image UUID matter to the gate. The external display processor + * (dcpext) of t8122-dcp.dtsi is there too, with its DARTs' 14.7 windows, + * but without the boot loader's firmware-ready mark: the cases that start + * it add the mark and its firmware versions. * * The nodes live under their own disabled bus, not /soc, so that they do * not collide with the T6030 test tree (both SoCs put the DCP at @@ -88,6 +91,14 @@ apple,min-state = <4>; apple,inherited-on; }; + + t8122_ps_dispext_cpu: power-controller@488 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x488 4>; + #power-domain-cells = <0>; + label = "dispext_cpu"; + apple,min-state = <4>; + }; }; t8122_pmp_dart: iommu@2d0300000 { @@ -117,7 +128,7 @@ apple,always-on; }; - report@8 { + t8122_report_dispext: report@8 { compatible = "apple,t8122-pmp-v2-report-entry", "apple,t6000-pmp-v2-report-entry"; reg = <0x8>; @@ -176,6 +187,7 @@ interrupts = <0 750 4>; #iommu-cells = <1>; power-domains = <&t8122_ps_disp_cpu>; + apple,dma-range = <0x100 0x0 0x10 0x0>; status = "disabled"; }; @@ -186,6 +198,7 @@ interrupts = <0 750 4>; #iommu-cells = <1>; power-domains = <&t8122_ps_disp_cpu>; + apple,dma-range = <0x100 0x0 0x10 0x0>; status = "disabled"; }; @@ -209,6 +222,61 @@ }; }; + t8122_dispext0_dart: iommu@319304000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x19304000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 599 4>; + #iommu-cells = <1>; + apple,dma-range = <0x0 0x0 0xf 0xffff0000>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + t8122_dcpext_dart: iommu@31930c000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x1930c000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 599 4>; + #iommu-cells = <1>; + apple,dma-range = <0x8 0x0 0x7 0xffff0000>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + t8122_dcpext_mbox: mailbox@31ac08000 { + compatible = "apple,t8122-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x1ac08000 0x0 0x4000>; + interrupt-parent = <&t8122_aic>; + interrupts = <0 582 4>, <0 583 4>, <0 584 4>, <0 585 4>; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + power-domains = <&t8122_ps_dispext_cpu>; + status = "disabled"; + }; + + /* Stands in for the boot loader's firmware reservations. */ + t8122_dcpext_mem: dcpext-firmware { + }; + + dcp@31ac00000 { + compatible = "apple,t8122-dcpext", "apple,dcpext"; + mboxes = <&t8122_dcpext_mbox>; + mbox-names = "mbox"; + iommus = <&t8122_dcpext_dart 5>; + reg-names = "coproc"; + reg = <0x3 0x1ac00000 0x0 0x4000>; + power-domains = <&t8122_ps_dispext_cpu>; + apple,pmp-report = <&t8122_report_dispext>; + memory-region = <&t8122_dcpext_mem>; + status = "disabled"; + + piodma { + iommus = <&t8122_dispext0_dart 4>; + }; + }; + display-subsystem { compatible = "apple,t8122-display-subsystem"; iommus = <&t8122_disp0_dart 0>; From b1c12cf6cab963f165dddd936d18bcec4f64b695 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:28:47 +1100 Subject: [PATCH 0352/1514] selftests: apple-dcp: test the T8122 dcpext 27.2 firmware selection Build apple_t8122_dcpext_v27_2() and the apple,t8122-dcpext arm of dcp_check_firmware_version() from the tree on the host and check which backend each firmware gets: the 27.2 table only for a dcpext whose version and compatibility are both 27.2.0 beside an internal DCP handed over on the 27.2 (26B123) image; nothing for another internal image, a missing internal DCP, another SoC's processor, or other or malformed versions; the 14.7 template and the native 26.x H17P path as before. The t6041 admission harness's stubs become a shared prelude, with an of_find_compatible_node() over the test's two processors. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/apple-dcp/boot.py | 145 ++++++++++++++++-- .../selftests/drivers/gpu/apple-dcp/run.py | 1 + 2 files changed, 137 insertions(+), 9 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index b7ebb2fc9fc5ff..7a23fdb3ff45f4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -195,17 +195,17 @@ def syslog(root): ''' -def t6041_v27_admission(root): +def _v27_prelude(root, helpers): + """Host stand-ins for the OF and DCP calls, then the production display.h + helpers named in @helpers, the firmware-27 method tables and + dcp_v27_method_table().""" display_h = (root / 'include/linux/soc/apple/display.h').read_text() uuid_defines = [line for line in display_h.splitlines() if line.startswith(('#define APPLE_T6041_DCP_26B123_UUID ', '#define APPLE_T8122_DCP_26B123_UUID '))] assert len(uuid_defines) == 2 helper = '\n'.join((*uuid_defines, *( - block(display_h, 'static inline bool ' + name + '(') for name in ( - 'apple_dcp_image_v27_2', - 'apple_t6041_dcp_any_v27_2', 'apple_t6041_dcp_v27_2', - 'apple_t6041_dcpext_v27_2', 'apple_t8122_dcp_v27_2')))) + block(display_h, 'static inline bool ' + name + '(') for name in helpers))) iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): iomfb_h.index('#define IOMFB_MAX_CB')] @@ -214,9 +214,6 @@ def t6041_v27_admission(root): v27_c.index('/* The template\'s calls resolve through')] dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() method_table = block(dcp_c, 'static enum dcp_firmware_version dcp_v27_method_table(') - selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') - cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' - selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' return r''' #include #include @@ -248,6 +245,25 @@ def t6041_v27_admission(root): { return np && np->compatible && !strcmp(np->compatible, s); } +/* The tree's display processors, for of_find_compatible_node(); unused by some units. */ +static struct device_node *of_nodes[2]; +static int of_node_refs; +__attribute__((unused)) static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, const char *s) +{ + assert(!from && !type); + for (unsigned i = 0; i < 2; i++) + if (of_device_is_compatible(of_nodes[i], s)) { + of_node_refs++; + return of_nodes[i]; + } + return NULL; +} +__attribute__((unused)) static void of_node_put(struct device_node *np) +{ + if (np) + assert(of_node_refs-- > 0); +} static int of_property_count_strings(const struct device_node *np, const char *name) { assert(!strcmp(name, "apple,firmware-uuid")); @@ -312,7 +328,17 @@ def t6041_v27_admission(root): snprintf(out, DCP_FW_VERSION_STR_LEN, "%u.%u.%u", v[0], v[1], v[2]); return 3; } -''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + method_table + '\n' + selector + r''' +''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + method_table + '\n' + + +def t6041_v27_admission(root): + dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') + cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' + selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' + return _v27_prelude(root, ('apple_dcp_image_v27_2', + 'apple_t6041_dcp_any_v27_2', 'apple_t6041_dcp_v27_2', + 'apple_t6041_dcpext_v27_2', 'apple_t8122_dcp_v27_2')) + selector + r''' static struct device_node node; static struct apple_dcp_hw_data hw_t6041; static struct device dev = { .of_node = &node, .hw = &hw_t6041 }; @@ -428,3 +454,104 @@ def t6041_v27_admission(root): return 0; } ''' + + +def t8122_dcpext_v27_admission(root): + """apple_t8122_dcpext_v27_2() and the apple,t8122-dcpext arm of + dcp_check_firmware_version(), both as the tree has them.""" + dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + selector = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') + arm = block(selector, selector.index( + 'if (of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) {')) + unit = _v27_prelude(root, ('apple_dcp_image_v27_2', 'apple_t8122_dcp_v27_2', + 'apple_t8122_dcpext_v27_2')) + # The arm runs with the firmware-compat the selector read before it. + return r''' +#define DCP_FIRMWARE_H17P 0x17 +#define DCP_FIRMWARE_V_14_7_TEMPLATE 0x147 +''' + unit + r''' +static bool ext26; +static bool dcp_ext26_admitted(struct device_node *np) { (void)np; return ext26; } +static enum dcp_firmware_version t8122_dcpext_arm(struct device *dev) +{ + char compat_str[DCP_FW_VERSION_STR_LEN] = ""; + + dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); + ''' + arm + r''' + return DCP_FIRMWARE_UNKNOWN; +} + +static struct device_node dcp, dcpext; +static struct device dev = { .of_node = &dcpext }; + +static void set(u32 *v, u32 a, u32 b, u32 c) { v[0] = a; v[1] = b; v[2] = c; } + +/* 27.2 on the J615: the internal DCP on 26B123, the dcpext with no image UUID. */ +static void reset(void) +{ + dcp = (struct device_node){ + .compatible = "apple,t8122-dcp", .uuid = APPLE_T8122_DCP_26B123_UUID, + .uuid_count = 1, .fw = { 27, 2, 0 }, .fw_cells = 3, + .compat = { 27, 2, 0 }, .compat_cells = 3, + }; + dcpext = (struct device_node){ + .compatible = "apple,t8122-dcpext", .fw = { 27, 2, 0 }, .fw_cells = 3, + .compat = { 27, 2, 0 }, .compat_cells = 3, + }; + of_nodes[0] = &dcp; + of_nodes[1] = &dcpext; + ext26 = false; +} + +static void expect(bool v27_2, enum dcp_firmware_version want) +{ + assert(apple_t8122_dcpext_v27_2(&dcpext) == v27_2); + assert(t8122_dcpext_arm(&dev) == want); + assert(!of_node_refs); +} + +int main(void) +{ + assert(!apple_t8122_dcpext_v27_2(NULL)); + + reset(); + expect(true, DCP_FIRMWARE_V_27_0); + /* The internal DCP is not the external one. */ + assert(!apple_t8122_dcpext_v27_2(&dcp)); + assert(!of_node_refs); + /* An image UUID on the dcpext changes nothing. */ + dcpext.uuid = APPLE_T8122_DCP_26B123_UUID; dcpext.uuid_count = 1; + expect(true, DCP_FIRMWARE_V_27_0); + puts("PASS T8122 dcpext on 27.2 beside the 26B123 internal DCP runs the 27.2 table"); + + /* Only beside an internal DCP handed over on the 27.2 image. */ + reset(); dcp.uuid = APPLE_T6041_DCP_26B123_UUID; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcp.uuid_count = 0; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcp.fw, 14, 7, 0); set(dcp.compat, 14, 7, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); of_nodes[0] = NULL; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcp.compatible = "apple,t6041-dcp"; expect(false, DCP_FIRMWARE_UNKNOWN); + /* Another SoC's dcpext is not it. */ + reset(); dcpext.compatible = "apple,t6041-dcpext"; + assert(!apple_t8122_dcpext_v27_2(&dcpext)); + assert(!of_node_refs); + puts("PASS T8122 dcpext 27.2 needs the internal DCP's 26B123 handoff"); + + /* Its own version and compatibility: both 27.2.0, three cells each. */ + reset(); set(dcpext.fw, 27, 0, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcpext.compat, 27, 0, 0); expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); set(dcpext.fw, 27, 2, 1); set(dcpext.compat, 27, 2, 1); + expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcpext.fw_cells = 0; expect(false, DCP_FIRMWARE_UNKNOWN); + reset(); dcpext.compat_cells = 4; expect(false, DCP_FIRMWARE_UNKNOWN); + puts("PASS T8122 dcpext 27.2 refuses other or malformed versions"); + + /* The 14.7 template and the native 26.x path are as before. */ + reset(); set(dcpext.fw, 14, 7, 0); set(dcpext.compat, 14, 7, 0); + expect(false, DCP_FIRMWARE_V_14_7_TEMPLATE); + reset(); ext26 = true; expect(true, DCP_FIRMWARE_H17P); + reset(); set(dcpext.fw, 26, 6, 2); set(dcpext.compat, 26, 6, 2); + expect(false, DCP_FIRMWARE_UNKNOWN); + puts("PASS T8122 dcpext 14.7.0 keeps the template, native 26.x keeps H17P"); + return 0; +} +''' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 1b748ae06db358..ab846db2166417 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -90,6 +90,7 @@ def main(): ('boot', 'oslog-events', boot.oslog, ((),), ()), ('boot', 'syslog-policy', boot.syslog, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), + ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ('-Wno-unused-function',)), ('edid', 'dpavserv-start', edid.startup, ((),), ()), ('edid', 'service-rebind', edid.rebind, ((),), ()), ('edid', 'provider-admission', edid.admission, ((),), ()), From e143d679cf6ca6e15db186767444a2cdabdcf690 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 08:05:03 +0700 Subject: [PATCH 0353/1514] dt-bindings: input: apple,dockchannel-hid: Describe trackpad touch states and palm rules The J813 and J815 (MacBook Air M5) trackpads send the standard MTP report, with a touch state and a firmware path ID in each contact record, and they need their own palm rules. Describe both on the multi-touch node, so the driver selects them by the trackpad and not by the machine, and another board with the same controller only needs its device tree: - apple,touch-states: the record's first word holds the touch state and the path ID; only touching contacts are reported, each in its path ID's slot. - apple,palm-debounce: two consecutive palm classes mark a palm (J813). - apple,palm-tool-area: the J815 rule, with the pad's two tool-area thresholds as values: a hand class past the first on two consecutive reports, or any contact on the surface past the second, is a palm, and its force doesn't count towards the host-derived click. The J700 report layout (compatible apple,j700-multitouch) has none of these fields, so the properties are not allowed with it. Signed-off-by: Nick --- .../bindings/input/apple,dockchannel-hid.yaml | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml b/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml index bf82f4dc8b3ee4..4f8da13249512a 100644 --- a/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml +++ b/Documentation/devicetree/bindings/input/apple,dockchannel-hid.yaml @@ -168,7 +168,59 @@ properties: power method 2 notifications without controlling an AFE GPIO. Mutually exclusive with apple,afe-reset-gpios on the parent. + apple,touch-states: + type: boolean + description: + The first word of each contact record of the trackpad's standard + report (38-byte header) holds the contact's touch state in its + high byte (start in range, hover, make touch, touching, break + touch, linger, out of range) and in its low byte the path ID under + which the firmware tracks the contact until it leaves the pad. + Only contacts that make or keep touch are then reported, each in + the slot of its path ID. + + apple,palm-debounce: + type: boolean + description: + The controller's palm classes (6 and above) flicker onto fingers + for single reports, so a contact counts as a palm once two + consecutive reports class it as one, whatever its tool area. + + apple,palm-tool-area: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Palm rule of a trackpad whose hand classes are 6, 7, 8 and 12, in + units of the record's contact ellipse major axis (10 um). A + contact in a hand class whose axis passes the first value on two + consecutive reports is a palm, and so is a contact on the surface + whose axis passes the second value, whatever its class. The force + of a palm, or of a contact past either value in a hand class, does + not count towards the click the host derives from the contacts' + force. The first value is below the second, and neither is above + 32767, the largest axis the record's signed 16-bit field holds. + items: + - description: Axis that marks a hand-class contact on two + consecutive reports. + maximum: 32767 + - description: Axis wider than any finger, marking a contact on + the surface at once. + maximum: 32767 + allOf: + - if: + required: + - apple,palm-tool-area + then: + properties: + apple,palm-debounce: false + - if: + required: + - compatible + then: + properties: + apple,touch-states: false + apple,palm-debounce: false + apple,palm-tool-area: false - if: required: - apple,firmware-managed-reset From 3fa72f8a794501db069c540bbdc600279b2485d6 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 08:05:14 +0700 Subject: [PATCH 0354/1514] arm64: dts: apple: t8142-j813, t8142-j815: Describe the trackpads' palm rules Give the multi-touch nodes the properties the driver will select the trackpad behaviour by, instead of the machine compatible: - J813: apple,palm-debounce, the rule its palms are reported with now, and apple,touch-states: gig3m's J813 recordings (MTP firmware 6310.85.7, 1,659 contacts) show the same state lifecycles and path IDs as the J815, with no path ID twice in a frame. Between a contact going out of range and the next start under its path ID come records in state 0 with zero sizes, which the on-surface test already drops. - J815: apple,touch-states (decoded on this pad against macOS's own parse of the same frames) and apple,palm-tool-area = <1200 2200>, the thresholds checked against macOS's labels for 607 contacts. Signed-off-by: Nick --- arch/arm64/boot/dts/apple/t8142-j813.dts | 4 ++++ arch/arm64/boot/dts/apple/t8142-j815.dts | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index aaa635fa853fba..063e036db4f18f 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -236,6 +236,10 @@ &mtp_hid { multi-touch { firmware-name = "apple/tpmtfw-j813.bin"; + /* Palm classes flicker onto fingers for single reports. */ + apple,palm-debounce; + /* The same touch states and path IDs as the J815's pad. */ + apple,touch-states; }; }; diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index 05d2e666cdb7b7..3276d2082c0ef0 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -136,6 +136,13 @@ multi-touch { /* ADT hid-merge-personality C1FD3,3 (J813: C1FD1,4). */ firmware-name = "apple/tpmtfw-j815.bin"; + /* Touch states and path IDs decoded on this pad against macOS. */ + apple,touch-states; + /* + * Hand classes past 12 mm on two reports, any contact past 22 mm + * at once (no finger on macOS passed 21 mm). + */ + apple,palm-tool-area = <1200 2200>; }; }; From 8be9e731e3137c498a7b7dc5b0f09cce3fcf4a2c Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 18 Nov 2026 16:03:40 +0700 Subject: [PATCH 0355/1514] soc: apple: sleep: T8142: start the cores and write the cluster words as XNU A traced macOS 27.2 sleep on a J813 (boot, a 40 s sleep, the wake and three more entries) differs from ours in three places: - The wake: 16.5 ms after it, right after the memory side and the WD2 stop, the boot core starts all nine other cores in one 0.23 ms burst, three words each (+4 the core's bit, +8 the E core's bit or 0, +0xc the P core's bit or 0). We started each core later, from its own bring-up, with two words. - The commit: the clusters' words are read-modify-written. The first sleep after boot reads 0xf and writes 0; every commit after a wake reads 0x2f and writes 0x20, keeping bit 5. We wrote 0 every time. - The SoC/DCS perf-state page is never accessed. Do the same: - At the end of the wake, start the cores that were online when the sleep began, in one burst with those three words. They come up through the boot object into the kernel's holding pen and wait there; each bring-up only releases its core. The per-core start stays for runtime hotplug. T8142's data has no cpu_clusters, so the cluster comes from the MPIDR. - Clear only the clusters' on bits at the commit. - Drop the SoC/DCS perf-state step (t8142_perf_down()) and the apple_sleep.perf_down switch that chose it. The burst depends on the holding pen being closed behind each released CPU ("arm64: spin table: close the holding pen behind each released CPU"); without it the last CPU booted runs ahead of its bring-up. Tested on J815 (MacBook Air 15" M5): two real deep sleeps (256 s and 172 s), each with "9 cores started in one burst" and nine "Booted secondary processor", all CPUs back, display, NVMe, Wi-Fi and Bluetooth up; the read-modify-write and no perf-state step in a third sleep of 366 s before that. On two J813s (sithglan, gig3m) alarm and lid wakes with the same behaviour. Reverting this commit is how to go back. Signed-off-by: Nick --- drivers/soc/apple/sleep.c | 111 ++++++++++++++++++++------------------ 1 file changed, 58 insertions(+), 53 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9b493cd1575b36..4faf0d46309035 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -816,6 +816,7 @@ struct apple_sleep { void __iomem *ps; void __iomem *pwrgate; void __iomem *cpu_start; + unsigned int cpu_burst_n; /* cores the last wake's burst started */ void __iomem *cllt; void __iomem *cluster; void __iomem *commit; @@ -1060,9 +1061,6 @@ struct apple_sleep { void __iomem *acc_e; void __iomem *acc_p; int cluster_p_ret; - int perf_soc_ret; - int perf_dcs_ret; - unsigned int perf_dcs_from; /* With radio_retrain: the radio's PCIe host, and its port's blocks and tables */ struct device_node *radio_host_np; void __iomem *radio_port; @@ -2252,9 +2250,17 @@ MODULE_PARM_DESC(mem_restore, "T8142: put the memory side (AMCC, SoC NI, DCS) ba static bool sleep_clk_restore = true; module_param_named(clk_restore, sleep_clk_restore, bool, 0644); MODULE_PARM_DESC(clk_restore, "T8142: put the 126 PMGR clkgen slots and the memory clock word back at the wake as XNU does"); -static bool sleep_perf_down = true; -module_param_named(perf_down, sleep_perf_down, bool, 0644); -MODULE_PARM_DESC(perf_down, "T8142: SoC/DCS perf states down before the memory stop (macOS on J813 never writes them; A/B)"); +/* + * The cores' start after a T8142 wake. A traced macOS 27.2 run on J813 (boot, a 40 s sleep, the + * wake and three more entries) starts all nine other cores 16.5 ms after the wake, right after + * the memory side and the WD2 stop, in one 0.23 ms burst, three words each: +4 the core's bit, +8 + * the E core's bit or 0, +0xc the P core's bit or 0. The wake does the same for the cores that + * were online when the sleep began (t8142_cpu_burst()); they come up through the boot object + * into the kernel's holding pen and wait there, and each bring-up only releases its core. + */ +static struct cpumask sleep_cpus_burst; +/* The CPUs online at .begin: the ones the PM core brings back after the wake. */ +static struct cpumask sleep_cpus_awake; static u64 t8142_boot_mpidr = ~0ULL; extern char t8142_el1_wfi_stub[], t8142_el1_wfi_stub_end[]; @@ -2514,6 +2520,13 @@ static int sleep_cpu_on(u64 mpidr) bool trace; DEFINE_DYNAMIC_DEBUG_METADATA(cpu_on_trace, "apple-sleep: cpu start after a sleep\n"); + /* Started by the wake's burst: it waits in the pen; release it. */ + if (cpu >= 0 && cpumask_test_and_clear_cpu(cpu, &sleep_cpus_burst)) { + pr_debug("apple-sleep: cpu%d start %#llx: started in the wake burst (%u cores), released from the pen\n", + cpu, mpidr, s->cpu_burst_n); + return 0; + } + trace = DYNAMIC_DEBUG_BRANCH(cpu_on_trace) && s->soc->cpu_clusters >= 2; if (trace) { slot = sleep_cpu_slot_map(cpu); @@ -6372,6 +6385,8 @@ static int apple_sleep_begin(suspend_state_t state) /* The PM core also calls .begin for s2idle when no s2idle ops are installed. */ if (state != PM_SUSPEND_MEM) return 0; + /* Before the PM core takes the other CPUs down: the wake's burst starts only these. */ + cpumask_copy(&sleep_cpus_awake, cpu_online_mask); ret = apple_sleep_profile_check(apple_sleep); if (ret) @@ -6817,9 +6832,6 @@ static void apple_sleep_report(void) s->soc->quiesce.offset[i]); if (s->cpus_stop_ret) dev_err(s->dev, "other CPUs did not stop: %d\n", s->cpus_stop_ret); - if (s->perf_soc_ret || s->perf_dcs_ret) - dev_warn(s->dev, "sleep perf states: SoC %d, DCS %d (DCS was %u)\n", s->perf_soc_ret, - s->perf_dcs_ret, s->perf_dcs_from); if (s->cluster_p_ret) dev_err(s->dev, "P complex did not come back on: %d\n", s->cluster_p_ret); if (s->radio_trainable && s->radio_stop_ret) @@ -8292,15 +8304,6 @@ static const struct apple_sleep_soc t8132_sleep_soc = { */ #define T8142_PMC_VOTER_AP (3 * PMC_VOTER_STRIDE) #define T8142_CLUSTER_BUSY BIT(4) -/* - * AppleT8142PMGR::setPerfState's words in PMGRCLKGEN_SOC_TOP (/arm-io/pmgr reg[2]): the SoC's - * at 0x24000, DCS's at 0x25000, each like T8132's: [3:0] asks, [11:8] has reached, bit 31 busy. - */ -#define T8142_PERF_REQ GENMASK(3, 0) -#define T8142_DCS_SLEEP_STATE 3 -#define T8142_DCS_STEP_STATE 5 -#define T8142_DCS_STEP_FROM 6 -#define T8142_DCS_MAX_STATE 10 /* * Every Linux access to the complexes' ACC word 0xe440f8 has hung J815 so far: a read at @@ -8313,32 +8316,6 @@ module_param_named(acc_wake, sleep_acc_wake, bool, 0644); MODULE_PARM_DESC(acc_wake, "T8142: write ACC 0xe440f8 = 1 per complex at a wake, as restoreHW does (default 0)"); -static int t8142_perf_request(void __iomem *reg, unsigned int state) -{ - writel((readl(reg) & ~T8142_PERF_REQ) | FIELD_PREP(T8142_PERF_REQ, state), reg); - return sleep_perf_wait(reg, state); -} - -/* - * AppleT8142PMGR::quiescePerfState, the PMGR's first sleep step: the SoC to Vmin (3), then DCS - * to 3, through 5 from 6..10. macOS waits on BUSY with no limit and panics on a DCS state - * above 10; here each wait is bounded, and such a state is left alone. - */ -static void t8142_perf_down(struct apple_sleep *s) -{ - unsigned int state = FIELD_GET(DCS_STATE, readl(s->dcs)); - - s->perf_dcs_from = state; - s->perf_soc_ret = t8142_perf_request(s->clk_perf + CLK_PERF_SOC, SOC_SLEEP_STATE); - if (state > T8142_DCS_MAX_STATE) { - s->perf_dcs_ret = -ERANGE; - return; - } - if (state >= T8142_DCS_STEP_FROM) - t8142_perf_request(s->dcs, T8142_DCS_STEP_STATE); - s->perf_dcs_ret = t8142_perf_request(s->dcs, T8142_DCS_SLEEP_STATE); -} - /* AppleT8142PMGR vtable 0xfa0: each complex's CPM gate word, read-modify-write. */ static void t8142_cpm_on(struct apple_sleep *s) { @@ -8643,10 +8620,7 @@ static void t8142_commit_note(struct apple_sleep *s) return; if (s->cpus_stop_ret) flags |= 0x01; - if (s->perf_soc_ret) - flags |= 0x02; - if (s->perf_dcs_ret) - flags |= 0x04; + /* 0x02 and 0x04 were the SoC and DCS perf-state steps, which are gone. */ for (i = 0; i < s->soc->wake_words; i++) { u32 pend = readl(s->wake + s->soc->wake_status + i * 4) & s->wake_armed[i]; @@ -8989,9 +8963,7 @@ static void t8142_last_mile(struct apple_sleep *s) const struct apple_sleep_soc *soc = s->soc; int i; - /* Not in macOS's J813 entry (its perf-state page is untouched in the whole trace): A/B. */ - if (READ_ONCE(sleep_perf_down)) - t8142_perf_down(s); + /* The SoC and DCS perf states stay: macOS's J813 entry never writes them. */ sleep_note(s, 0x64); /* T6050's commit window: the floor's voter to 0, not read, right before the memory stop */ @@ -9010,8 +8982,11 @@ static void t8142_last_mile(struct apple_sleep *s) t8142_commit_note(s); - for (i = 0; i < soc->ncluster_cpu; i++) - writel(0, s->cluster + soc->cluster_cpu[i]); + for (i = 0; i < soc->ncluster_cpu; i++) { + void __iomem *reg = s->cluster + soc->cluster_cpu[i]; + + writel(readl(reg) & ~CLUSTER_ON, reg); + } s->quiesce_still_on = 0; for (i = 0; i < soc->quiesce.count; i++) @@ -9133,6 +9108,35 @@ static int t8142_cluster_on(struct apple_sleep *s, u32 word, void __iomem *acc) return ret; } +/* The other cores started at once, three words each (see sleep_cpus_burst). */ +static void t8142_cpu_burst(struct apple_sleep *s) +{ + unsigned int cpu, n = 0, self = smp_processor_id(); + + cpumask_clear(&sleep_cpus_burst); + s->cpu_burst_n = 0; + /* T8142's data states no cpu_clusters (0): E = MPIDR cluster 0, P = 1, from the MPIDR. */ + if (!s->cpu_start) + return; + for_each_cpu(cpu, &sleep_cpus_awake) { + u64 mpidr = cpu_logical_map(cpu); + unsigned int cluster = sleep_cpu_cluster(s, mpidr), core = sleep_cpu_core(mpidr); + + if (cpu == self || cluster > 1) + continue; + writel(sleep_cpu_start_bit(s, mpidr), s->cpu_start + CPU_START_SYS); + writel(cluster == 0 ? BIT(core) : 0, s->cpu_start + CPU_START_CLUSTER(0)); + writel(cluster == 1 ? BIT(core) : 0, s->cpu_start + CPU_START_CLUSTER(1)); + cpumask_set_cpu(cpu, &sleep_cpus_burst); + n++; + } + s->cpu_burst_n = n; + pr_info("apple-sleep: wake: %u cores started in one burst; stop/sys/e/p now %x/%x/%x/%x\n", + n, readl(s->cpu_start + CPU_START_STOP), readl(s->cpu_start + CPU_START_SYS), + readl(s->cpu_start + CPU_START_CLUSTER(0)), + readl(s->cpu_start + CPU_START_CLUSTER(1))); +} + /* * AppleT8142PMGR::restoreHW: each complex on, pwrgate +0x0 and +0x60 read-modify-written, the * words back, the CPM gates, the ACC words once more. Its two "early wake hacks" (SEP's ps @@ -9193,6 +9197,7 @@ static void t8142_wake(struct apple_sleep *s) s->aon_wdt_marked = false; } apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); + t8142_cpu_burst(s); if (s->pcie_ans_stopped) s->pcie_ans_on_ret = apple_sleep_raise_apcie(s); From d321d4b8fd47c93a5a8802fb87df4368d2969680 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:41:26 +1100 Subject: [PATCH 0356/1514] drm/apple: include dcp-internal.h before instantiating the IOMFB template iomfb_template.c includes dcp-internal.h, which pulls in iomfb_v14_7_tpl.h and iomfb_v26_6_desktop.h. When that happens for the first time inside a template instance, those headers rely on the push_macro/pop_macro pragmas to keep the instance's DCP_FW and DCP_FW_VER. sparse does not implement these pragmas, so for every instance it saw DCP_FW_VER undefined and DCP_FW unexpanded, and gave up on iomfb_template.c with ~190 bogus errors (incomplete struct dcp_swap_submit_req_DCP_FW, undefined preprocessor identifier DCP_FW_VER). The template was effectively never checked. Include dcp-internal.h with the other per-version headers, before each instance defines DCP_FW, as the existing comment already asks. The headers' include guards then make the template's own include a no-op. No functional change: the generated code of every iomfb_* object is identical before and after. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_h17p.c | 1 + drivers/gpu/drm/apple/iomfb_v12_3.c | 8 +++++++- drivers/gpu/drm/apple/iomfb_v13_3.c | 8 +++++++- drivers/gpu/drm/apple/iomfb_v14_7_tpl.c | 8 +++++++- drivers/gpu/drm/apple/iomfb_v26_6_desktop.c | 8 +++++++- 5 files changed, 29 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_h17p.c b/drivers/gpu/drm/apple/iomfb_h17p.c index 54a82ce65dbe1f..18e7b936970381 100644 --- a/drivers/gpu/drm/apple/iomfb_h17p.c +++ b/drivers/gpu/drm/apple/iomfb_h17p.c @@ -13,6 +13,7 @@ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" +#include "dcp-internal.h" #include "version_utils.h" struct dcp_callback_size { diff --git a/drivers/gpu/drm/apple/iomfb_v12_3.c b/drivers/gpu/drm/apple/iomfb_v12_3.c index b2d07426897337..fba8add2e1aad0 100644 --- a/drivers/gpu/drm/apple/iomfb_v12_3.c +++ b/drivers/gpu/drm/apple/iomfb_v12_3.c @@ -1,11 +1,17 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright The Asahi Linux Contributors */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { diff --git a/drivers/gpu/drm/apple/iomfb_v13_3.c b/drivers/gpu/drm/apple/iomfb_v13_3.c index 6d9caa6b27780f..83e687fd7c63af 100644 --- a/drivers/gpu/drm/apple/iomfb_v13_3.c +++ b/drivers/gpu/drm/apple/iomfb_v13_3.c @@ -1,11 +1,17 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright The Asahi Linux Contributors */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c index 6ad66e7c84690a..0679ee5a13a7c3 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c @@ -7,11 +7,17 @@ * iomfb_v14_7.c, the native DCPLink backend for T6030 panels. */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { diff --git a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c index c2d0bee01e05f9..8778ccf269bb2c 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c @@ -9,12 +9,18 @@ * the H17-generation 26.x firmware of iomfb_h17p.c. */ -/* Include all per-version headers before defining DCP_FW ourself. */ +/* + * Include all per-version headers before defining DCP_FW ourself. + * dcp-internal.h pulls in the remaining ones; included first from inside + * the template, they would rely on #pragma push_macro to keep our DCP_FW, + * which sparse does not implement. + */ #include "iomfb_v12_3.h" #include "iomfb_v13_3.h" #include "iomfb_v14_7_tpl.h" #include "iomfb_v26_6_desktop.h" #include "iomfb_h17p.h" +#include "dcp-internal.h" #include "version_utils.h" static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { From ba15aedee99e0178e911db0bc7a63c98da2e6bb7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:41:26 +1100 Subject: [PATCH 0357/1514] drm/apple: make file-local ops static and fix two annotations - apple_drm_ops and dcp_playback_ops are only used in their own file: make them static (and const for the PCM ops, which snd_pcm_set_ops() takes as const). - ext_plane_disable() fills the scanout buffer with cpu_to_le32() values: type the pointer __le32. - dcp_crtc_next_flip_seq() was inserted between the kernel-doc comment of dcp_crtc_send_page_flip_event() and its function. Move it above the comment so the documentation is attached to the right function again. No functional change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 2 +- drivers/gpu/drm/apple/audio.c | 2 +- drivers/gpu/drm/apple/dcp.c | 38 +++++++++++++++--------------- drivers/gpu/drm/apple/dcpext_drm.c | 2 +- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 41a3327f47b41a..eccda68cea9e19 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1929,7 +1929,7 @@ static void apple_drm_unbind(struct device *dev) apple_drm_uninit(dev); } -const struct component_master_ops apple_drm_ops = { +static const struct component_master_ops apple_drm_ops = { .bind = apple_drm_bind, .unbind = apple_drm_unbind, }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 51fcc346a575b4..16c72864662f81 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -739,7 +739,7 @@ static int dcp_pcm_sync_stop(struct snd_pcm_substream *substream) return 0; } -struct snd_pcm_ops dcp_playback_ops = { +static const struct snd_pcm_ops dcp_playback_ops = { .open = dcp_pcm_open, .close = dcp_pcm_close, .hw_params = dcp_pcm_hw_params, diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..d20a2d9840f348 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -749,25 +749,6 @@ static void send_vblank_event(struct drm_device *dev, drm_send_event_timestamp_locked(dev, &e->base, now); } -/** - * dcp_crtc_send_page_flip_event - helper to send vblank event after pageflip - * @crtc: CRTC whose flip completed - * @e: pending vblank event - * @now: swap completion timestamp - * @start: swap submission timestamp - * - * Compensate for unknown slack between page flip and arrival of the - * swap_complete callback. Minimal observed duration on DCP with HDMI output - * was around 2.3 ms. If the fb swap was submitted closer to the expected - * swap_complete it gets a penalty of one frame duration. This is on the border - * of unreasonable considering that Apple advertises support for 240 Hz (frame - * duration of 4.167 ms). - * It is unreasonable considering kwin's kms commit scheduling. Kwin commits - * 1.5 ms + the mode's vblank time before the expected next page flip - * completion. This results in presenting at half the display's rate for HDMI - * outputs. - * This might be a difference between dcp and dcpext. - */ /* * Advance the CRTC's flip sequence by the number of refresh periods since the * previous flip (at least one), so that userspace sees a non-zero, increasing @@ -792,6 +773,25 @@ static u64 dcp_crtc_next_flip_seq(struct apple_crtc *crtc, ktime_t flip) return crtc->flip_seq; } +/** + * dcp_crtc_send_page_flip_event - helper to send vblank event after pageflip + * @crtc: CRTC whose flip completed + * @e: pending vblank event + * @now: swap completion timestamp + * @start: swap submission timestamp + * + * Compensate for unknown slack between page flip and arrival of the + * swap_complete callback. Minimal observed duration on DCP with HDMI output + * was around 2.3 ms. If the fb swap was submitted closer to the expected + * swap_complete it gets a penalty of one frame duration. This is on the border + * of unreasonable considering that Apple advertises support for 240 Hz (frame + * duration of 4.167 ms). + * It is unreasonable considering kwin's kms commit scheduling. Kwin commits + * 1.5 ms + the mode's vblank time before the expected next page flip + * completion. This results in presenting at half the display's rate for HDMI + * outputs. + * This might be a difference between dcp and dcpext. + */ static void dcp_crtc_send_page_flip_event(struct apple_crtc *crtc, struct drm_pending_vblank_event *e, ktime_t now, ktime_t start) diff --git a/drivers/gpu/drm/apple/dcpext_drm.c b/drivers/gpu/drm/apple/dcpext_drm.c index 1d9981b5def3f9..53ff271e105e6e 100644 --- a/drivers/gpu/drm/apple/dcpext_drm.c +++ b/drivers/gpu/drm/apple/dcpext_drm.c @@ -290,7 +290,7 @@ static void ext_plane_update(struct drm_plane *plane, struct drm_atomic_commit * static void ext_plane_disable(struct drm_plane *plane, struct drm_atomic_commit *state) { struct dcpext_drm *ext = container_of(plane->dev, struct dcpext_drm, drm); - u32 *dst = ext->pixels; + __le32 *dst = ext->pixels; struct dcpext_frame frame; int idx, i, ret; From 1442df5626f5bc7af79d0cd01cdf6d3af392b3d4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:42:29 +1100 Subject: [PATCH 0358/1514] media: apple: isp: group the IPC message payload for memcpy() chan_write_msg_index() copies arg1..arg7 with one memcpy() starting at &msg->arg1. With W=1, FORTIFY_SOURCE flags this as a read beyond the arg1 field (__read_overflow2_field). Wrap arg1..arg7 in struct_group(payload, ...) and copy sizeof(msg->payload). The message layout, its size and the bytes written are unchanged. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/isp/isp-drv.h | 17 ++++++++++------- drivers/media/platform/apple/isp/isp-ipc.c | 2 +- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/drivers/media/platform/apple/isp/isp-drv.h b/drivers/media/platform/apple/isp/isp-drv.h index 411041d8e82fc1..b3dccaf9a75089 100644 --- a/drivers/media/platform/apple/isp/isp-drv.h +++ b/drivers/media/platform/apple/isp/isp-drv.h @@ -101,13 +101,16 @@ struct isp_surf { struct isp_message { u64 arg0; - u64 arg1; - u64 arg2; - u64 arg3; - u64 arg4; - u64 arg5; - u64 arg6; - u64 arg7; + /* Written before arg0, which marks the message valid. */ + struct_group(payload, + u64 arg1; + u64 arg2; + u64 arg3; + u64 arg4; + u64 arg5; + u64 arg6; + u64 arg7; + ); } __packed; static_assert(sizeof(struct isp_message) == ISP_IPC_MESSAGE_SIZE); diff --git a/drivers/media/platform/apple/isp/isp-ipc.c b/drivers/media/platform/apple/isp/isp-ipc.c index 77ef0016a34de8..922e990010487b 100644 --- a/drivers/media/platform/apple/isp/isp-ipc.c +++ b/drivers/media/platform/apple/isp/isp-ipc.c @@ -97,7 +97,7 @@ static inline void chan_write_msg_index(struct apple_isp *isp, struct isp_message *msg, u32 index) { u64 *p0 = chan_msg_virt(chan, index); - memcpy(p0 + 1, &msg->arg1, sizeof(*msg) - 8); + memcpy(p0 + 1, &msg->payload, sizeof(msg->payload)); /* Make sure we write arg0 last, since that indicates message validity. */ From 28bf9f1a800d4d39efbff25b20bbe6975d5b7226 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:42:29 +1100 Subject: [PATCH 0359/1514] media: apple: avd: drop __iomem before KUNIT_ASSERT_NOT_NULL() The PM test backs the code, mailbox and PIODMA apertures with kunit_kzalloc() memory cast to __iomem. Asserting those pointers against NULL makes sparse warn about comparing different address spaces. Cast them back with __force for the check, as for the allocation. Test-only change. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-pm-test.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-pm-test.c b/drivers/media/platform/apple/avd/avd-pm-test.c index 61b911e51c119d..36efb30e83c4b5 100644 --- a/drivers/media/platform/apple/avd/avd-pm-test.c +++ b/drivers/media/platform/apple/avd/avd-pm-test.c @@ -291,9 +291,9 @@ static void avd_pm_open_boot_replay_test(struct kunit *test) avd->code = (__force void __iomem *)kunit_kzalloc(test, 0x100, GFP_KERNEL); avd->mbox = (__force void __iomem *)kunit_kzalloc(test, 0x100, GFP_KERNEL); avd->pm.piodma = (__force void __iomem *)kunit_kzalloc(test, 0x28, GFP_KERNEL); - KUNIT_ASSERT_NOT_NULL(test, avd->code); - KUNIT_ASSERT_NOT_NULL(test, avd->mbox); - KUNIT_ASSERT_NOT_NULL(test, avd->pm.piodma); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->code); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->mbox); + KUNIT_ASSERT_NOT_NULL(test, (__force void *)avd->pm.piodma); avd->pm.sram_phys = 0x123456780ULL; for (i = 0; i < 2; i++) { /* Model loss of both ITCM and PIODMA configuration between boots. */ From a6615613763bdaec82ea1ebdc18d8f9254e68c42 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:43:23 +1100 Subject: [PATCH 0360/1514] iommu/apple-dart: split the T8110 port-count max() for sparse max(FIELD_GET(...READ_PORTS, params), FIELD_GET(...WRITE_PORTS, params)) expands past sparse's token limit, so sparse reports "too long token expansion" and stops checking the rest of the expression. Read the two port counts into locals first and take max() of those. No functional change. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-cio-power.h | 5 +++-- drivers/iommu/apple-dart-sleep.c | 5 +++-- drivers/iommu/apple-dart.c | 10 ++++++---- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/drivers/iommu/apple-dart-cio-power.h b/drivers/iommu/apple-dart-cio-power.h index 740b06671d54a9..faa6f489d8814a 100644 --- a/drivers/iommu/apple-dart-cio-power.h +++ b/drivers/iommu/apple-dart-cio-power.h @@ -27,8 +27,9 @@ static bool dart_cio_fault(void __iomem *regs, const struct dart_cio_power *s) static int dart_cio_idle(void __iomem *regs, const struct dart_cio_power *s) { - unsigned int ports = max(FIELD_GET(GENMASK(18, 16), s->params[1]), - FIELD_GET(GENMASK(22, 20), s->params[1])); + unsigned int rports = FIELD_GET(GENMASK(18, 16), s->params[1]); + unsigned int wports = FIELD_GET(GENMASK(22, 20), s->params[1]); + unsigned int ports = max(rports, wports); u32 value; int ret; diff --git a/drivers/iommu/apple-dart-sleep.c b/drivers/iommu/apple-dart-sleep.c index 630e7101d5876d..b93338c4796ac7 100644 --- a/drivers/iommu/apple-dart-sleep.c +++ b/drivers/iommu/apple-dart-sleep.c @@ -364,8 +364,9 @@ static int apple_dart_sleep_idle(struct apple_dart_sleep_state *s) { struct apple_dart *dart = s->dart; u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int ports = max(rports, wports); int ret; if (!ports || ports > 4 || dart_power_fault_pending(dart->regs, &s->power)) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 33a29ce9beb045..d66e87da3f560c 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -7288,8 +7288,9 @@ static int apple_dart_tlb_command(struct apple_dart *dart, u32 command) static int apple_dart_idle(struct apple_dart *dart) { u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int ports = max(rports, wports); if (!ports || ports > 4 || apple_dart_fault_pending(dart)) return -EIO; @@ -7868,8 +7869,9 @@ static bool apple_dart_m5_streams_unowned(struct apple_dart *dart, u32 allowed) static int apple_dart_m5_idle(struct apple_dart *dart) { u32 params = readl(dart->regs + DART_PARAMS2); - unsigned int port, ports = max(FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params), - FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params)); + unsigned int rports = FIELD_GET(DART_T8110_PARAMS2_READ_PORTS, params); + unsigned int wports = FIELD_GET(DART_T8110_PARAMS2_WRITE_PORTS, params); + unsigned int port, ports = max(rports, wports); if (!ports || ports > 4 || apple_dart_fault_pending(dart)) return -EIO; From 7ce3f99f6648317e28a25fe603a3246f176c3092 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:43:24 +1100 Subject: [PATCH 0361/1514] drm/asahi: g17: compare fence ops with rcu_access_pointer() dma_fence::ops is __rcu. asahi_g17_is_scope() compared it directly, which sparse reports as a comparison between different address spaces. Use rcu_access_pointer(), as dma_fence_is_array() and the g18 sync_input code do. No functional change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g17/sync_scope.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g17/sync_scope.c b/drivers/gpu/drm/asahi/g17/sync_scope.c index 73dc096d119c98..c702cac631991f 100644 --- a/drivers/gpu/drm/asahi/g17/sync_scope.c +++ b/drivers/gpu/drm/asahi/g17/sync_scope.c @@ -47,7 +47,7 @@ static DEFINE_PER_CPU(struct llist_head *, active_scopes); bool asahi_g17_is_scope(struct dma_fence *fence) { - return fence && fence->ops == &scope_ops; + return fence && rcu_access_pointer(fence->ops) == &scope_ops; } static struct asahi_g17_scope *to_scope(struct dma_fence *fence) From c0e1ac84782a45e74ab5ab5ff94264dd84cf635e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:43:24 +1100 Subject: [PATCH 0362/1514] soc: apple: clpc: document apple_clpc_hw.pmp_agent W=1 kernel-doc reports the struct member as undocumented. Describe it: the PMC floor voter agent of the PMP that apple_clpc_gpu_limited() reads when @pmp_backoff is set. Signed-off-by: Ryan Murray --- drivers/soc/apple/clpc.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 9c40a734cb8edf..c3ca54ba859db4 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -90,6 +90,7 @@ enum apple_clpc_rail { * counts as streaming, see apple_clpc_gpu_streaming(); 0 counts it at once * @pmp_backoff: release that GPU floor while the PMP, voter agent * @pmp_agent, limits the DCS, see apple_clpc_gpu_limited() + * @pmp_agent: PMC floor voter agent of the PMP, read for @pmp_backoff * @gpu_dense: submissions per sampling period that make light GPU work * dense, see apple_clpc_gpu_dense(); 0 for none * @ane: state of each rail while ANE work is in flight; all zero disables input From 5e127c841afcca5ebc83ccf7e44ae3453efbee20 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:46:24 +1100 Subject: [PATCH 0363/1514] dt-bindings: display: apple,dcp: match the Type-C DP IN routes in use dtbs_check reports about 100 errors on the in-tree Apple DTBs against apple,dcp.yaml: - apple,t6030-dcpext and apple,t6031-dcpext are used with the "apple,dcpext" fallback (t6030-dcp.dtsi, t6031 display files) but are missing from the dcpext compatible list. - The T6020 external DCPs on J414/J416 name their Thunderbolt DP IN crossbar controls typecN-dpin0/1, as apple,dcp-typec-routes.yaml describes. A conditional block listing a few SoCs rejected -dpin names and more than 8 mux controls on every other SoC. The block before it already caps all non-T6050 parts at 10 controls and dpin0/1, which is what the DTs use. Drop the SoC list instead of adding another entry, so the route names are checked the same way on every DCP. - The apple,dcp-typec-routes.yaml example has a t6020-dcpext node without the reg, mailbox, IOMMU and bandwidth scratch properties apple,dcp.yaml requires. Add them, with the values of the T6021 dcpext2 node, and a unit address. Documentation-only change. dt_binding_check for display/apple,dcp is clean. dtbs_check of all Apple DTBs against apple,dcp.yaml goes from about 100 errors to 8 (the t6030-dcpext nodes describe only their coproc region). Signed-off-by: Ryan Murray --- .../display/apple,dcp-typec-routes.yaml | 12 +++++++++++- .../bindings/display/apple,dcp.yaml | 19 ++----------------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml index 858a09501e4f68..d13cfa7c2b4b9c 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml @@ -181,8 +181,18 @@ examples: - | #include - dcp { + dcp@8dc00000 { compatible = "apple,t6020-dcpext", "apple,dcpext"; + reg = <0x8dc00000 0x4000>, + <0x8c000000 0x4000000>, + <0x8d320000 0x4000>, + <0x8d344000 0x4000>, + <0x8d800000 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext_dart 5>; + apple,bw-scratch = <&pmgr_dcp 0 4 0x1220>; phys = <&atcphy0 PHY_TYPE_DP>; phy-names = "typec0"; mux-controls = <&atcphy0_xbar 0>, <&atcphy0_xbar 1>, diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 9437c59a76d3a0..193ceda46427f2 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -34,6 +34,8 @@ properties: - apple,t8112-dcpext - apple,t6000-dcpext - apple,t6020-dcpext + - apple,t6030-dcpext + - apple,t6031-dcpext - apple,t6041-dcpext - apple,t8122-dcpext - apple,t6050-dcpext @@ -593,23 +595,6 @@ allOf: maxItems: 10 items: pattern: '^(dp-xbar|typec[0-9]+(-dpin[01])?)$' - - if: - not: - properties: - compatible: - contains: - enum: ['apple,t6030-dcpext', 'apple,t8132-dcpext', - 'apple,t6050-dcp', 'apple,t6050-dcpext'] - required: - - compatible - then: - properties: - mux-controls: - maxItems: 8 - mux-control-names: - maxItems: 8 - items: - pattern: '^(dp-xbar|typec[0-9]+)$' - if: allOf: - not: From 419a05c37b8071c7e1d01cb3df8af45a08e8edea Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:51:39 +1100 Subject: [PATCH 0364/1514] drm/apple: dcp: leave the bind's clocks to its devres group dcp_comp_unbind() put dcp->clk with devm_clk_put(). That walks every devm clock entry of the device, and the optional "clock-194" lookup leaves an entry whose clock is NULL when the node has no such clock. devm_clk_match() warns on that entry (clk-devres.c), so every unbind of a DCP without clock-194 printed a WARNING with a stack trace. On a J473 this shows whenever another DCP fails to bind and the component framework unbinds the DCP that already bound. Both clocks are got during bind inside the devres group the component framework opens for it, and component_unbind() releases that group right after the unbind callback. Drop the explicit put and only clear the pointers, as was already done for clk_194. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b16995083020dc..0ee735ded4aa1b 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6999,10 +6999,12 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v cancel_work_sync(&dcp->bl_register_wq); cancel_work_sync(&dcp->bl_update_wq); } - if (dcp->clk) - devm_clk_put(dev, dcp->clk); + /* + * Both clocks are released with the bind's devres group. An explicit + * devm_clk_put() would also match the NULL devres entry of an absent + * optional clock and warn. + */ dcp->clk = NULL; - /* optional and possibly NULL, released with the bind's devres group */ dcp->clk_194 = NULL; dcp->firmware_clocks = NULL; dcp->num_firmware_clocks = 0; From 17db3f1c46c43671d801f4d3d8a0da59afd85670 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:04:58 +1100 Subject: [PATCH 0365/1514] drm/apple: test apple_typec_port_rgb8_only() apple_typec_port_rgb8_only() decides whether a Type-C connector gets the BT.2020/PQ output properties: it must not when any pipeline that can drive the port runs the native26 (ext26) IOMFB method set, which scans out XRGB8888 only. It had no test. Make it visible to KUnit (VISIBLE_IF_KUNIT, no change for non-KUnit builds) and add topology_rgb8_only_test to the apple-dcp-topology suite. It registers four ports over a 10-bit pipeline, an ext26 one and one without drvdata, and checks: no pipelines; any pipeline with an ext26 candidate after a 10-bit one; a single pipeline counting only its own method set, including one that is not a candidate for the port; a port the ext26 pipeline cannot drive; a candidate without drvdata being skipped; a port without routes and an index past the last port. No functional change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 8 +- .../gpu/drm/apple/dcp-fabric-topology-test.c | 117 ++++++++++++++++++ drivers/gpu/drm/apple/dcp-fabric.h | 6 + 3 files changed, 128 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 41a3327f47b41a..32b6376511785a 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -8,6 +8,7 @@ */ #include +#include #include #include #include @@ -1268,9 +1269,10 @@ static int apple_probe_per_dcp(struct device *dev, * Type-C connector any of whose pipelines is native26 offers no BT.2020/PQ * output contract. Every other pipeline has a 10-bit primary. */ -static bool apple_typec_port_rgb8_only(struct platform_device **dcp, int num_dcp, - struct platform_device *pipeline, - unsigned int port_idx) +VISIBLE_IF_KUNIT bool apple_typec_port_rgb8_only(struct platform_device **dcp, + int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx) { int i; diff --git a/drivers/gpu/drm/apple/dcp-fabric-topology-test.c b/drivers/gpu/drm/apple/dcp-fabric-topology-test.c index 2240be4d8b2a38..f1c62a6f010ae6 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-topology-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-topology-test.c @@ -410,6 +410,122 @@ static void topology_route_skip_test(struct kunit *test) KUNIT_EXPECT_TRUE(test, of_device_is_available(route_np)); } +/* + * apple_typec_port_rgb8_only(): a Type-C port is 8-bit RGB only if one of + * the pipelines in scope (all of them, or only @pipeline) is a candidate for + * the port and runs the native26 (ext26) IOMFB method set. + */ +enum { RGB8_PLAIN, RGB8_EXT26, RGB8_NODATA, RGB8_PIPES }; +enum { RGB8_BOTH, RGB8_PLAIN_ONLY, RGB8_NODATA_EXT26, RGB8_NONE, RGB8_PORTS }; + +struct topology_rgb8 { + struct apple_dcp_typec_port port[RGB8_PORTS]; + struct apple_dcp_typec_route route[RGB8_PORTS][2]; + struct apple_dcp dcp[RGB8_PIPES]; + struct platform_device *pdev[RGB8_PIPES]; + unsigned int first; +}; + +static void topology_rgb8_unlist(void *data) +{ + struct topology_rgb8 *t = data; + unsigned int p; + + guard(mutex)(&dcp_typec_fabric_lock); + for (p = 0; p < RGB8_PORTS; p++) + list_del(&t->port[p].link); +} + +static void topology_rgb8_route(struct topology_rgb8 *t, unsigned int p, + unsigned int slot, unsigned int pipe) +{ + struct apple_dcp_typec_route *route = &t->route[p][slot]; + + route->dcp = &t->dcp[pipe]; + route->port = &t->port[p]; + list_add_tail(&route->port_link, &t->port[p].routes); +} + +static struct topology_rgb8 *topology_rgb8_init(struct kunit *test) +{ + struct topology_rgb8 *t; + unsigned int p, i; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + for (i = 0; i < RGB8_PIPES; i++) { + t->pdev[i] = kunit_platform_device_alloc(test, "dcp-rgb8", + PLATFORM_DEVID_AUTO); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->pdev[i]); + KUNIT_ASSERT_EQ(test, kunit_platform_device_add(test, t->pdev[i]), 0); + t->dcp[i].dev = &t->pdev[i]->dev; + if (i != RGB8_NODATA) + platform_set_drvdata(t->pdev[i], &t->dcp[i]); + } + t->dcp[RGB8_EXT26].hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + /* An ext26 method set that cannot be reached: no drvdata */ + t->dcp[RGB8_NODATA].hw.iomfb_method_profile = DCP_IOMFB_METHODS_J613_EXT26; + + t->first = dcp_typec_nr_ports(); + scoped_guard(mutex, &dcp_typec_fabric_lock) { + for (p = 0; p < RGB8_PORTS; p++) + INIT_LIST_HEAD(&t->port[p].routes); + topology_rgb8_route(t, RGB8_BOTH, 0, RGB8_PLAIN); + topology_rgb8_route(t, RGB8_BOTH, 1, RGB8_EXT26); + topology_rgb8_route(t, RGB8_PLAIN_ONLY, 0, RGB8_PLAIN); + topology_rgb8_route(t, RGB8_NODATA_EXT26, 0, RGB8_NODATA); + topology_rgb8_route(t, RGB8_NODATA_EXT26, 1, RGB8_EXT26); + for (p = 0; p < RGB8_PORTS; p++) + list_add_tail(&t->port[p].link, &dcp_typec_ports); + } + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, topology_rgb8_unlist, t), 0); + return t; +} + +static void topology_rgb8_only_test(struct kunit *test) +{ + struct topology_rgb8 *t = topology_rgb8_init(test); + struct platform_device *all[] = { + t->pdev[RGB8_PLAIN], t->pdev[RGB8_EXT26], t->pdev[RGB8_NODATA], + }; + struct platform_device *nodata_first[] = { + t->pdev[RGB8_NODATA], t->pdev[RGB8_PLAIN], t->pdev[RGB8_EXT26], + }; + struct platform_device *plain = t->pdev[RGB8_PLAIN]; + struct platform_device *ext26 = t->pdev[RGB8_EXT26]; + struct platform_device *nodata = t->pdev[RGB8_NODATA]; + unsigned int both = t->first + RGB8_BOTH; + unsigned int plain_only = t->first + RGB8_PLAIN_ONLY; + unsigned int nodata_ext26 = t->first + RGB8_NODATA_EXT26; + unsigned int none = t->first + RGB8_NONE; + + /* No pipelines at all */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 0, NULL, both)); + + /* Any pipeline: an ext26 candidate after a 10-bit one */ + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(all, 3, NULL, both)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(nodata_first, 3, NULL, both)); + + /* One pipeline: only its own method set counts */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, plain, both)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(all, 3, ext26, both)); + /* A pipeline that is not a candidate for the port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, ext26, plain_only)); + + /* The ext26 pipeline is not a candidate for this port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, plain_only)); + + /* A candidate without drvdata is skipped, not dereferenced */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, nodata, nodata_ext26)); + KUNIT_EXPECT_TRUE(test, apple_typec_port_rgb8_only(nodata_first, 3, NULL, + nodata_ext26)); + + /* A port without routes, and one past the last port */ + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, none)); + KUNIT_EXPECT_FALSE(test, apple_typec_port_rgb8_only(all, 3, NULL, + t->first + RGB8_PORTS)); +} + static struct kunit_case dcp_topology_cases[] = { KUNIT_CASE(topology_pipeline_identity_test), KUNIT_CASE(topology_adopt_release_test), @@ -417,6 +533,7 @@ static struct kunit_case dcp_topology_cases[] = { KUNIT_CASE(topology_connector_group_test), KUNIT_CASE(topology_route_supplier_test), KUNIT_CASE(topology_route_skip_test), + KUNIT_CASE(topology_rgb8_only_test), {} }; diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index 7876718cbfdfaa..65082081e2b1bd 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -78,6 +78,12 @@ bool dcp_has_typec_routes(struct platform_device *pdev); unsigned int dcp_typec_nr_ports(void); struct device_node *dcp_typec_port_of_node(unsigned int idx); bool dcp_typec_port_has_candidate(unsigned int idx, struct platform_device *pdev); +#if IS_ENABLED(CONFIG_KUNIT) +/* apple_drv.c: whether a native26 pipeline can drive Type-C port @port_idx */ +bool apple_typec_port_rgb8_only(struct platform_device **dcp, int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx); +#endif /* Connectors by apple,connector-group; T6050's tunnel-only pairs after the others in each */ #define DCP_TYPEC_CONNECTOR_GROUPS 4 unsigned int dcp_typec_nr_passes(void); From c9f24a4f51bc1c6bce4f6e85c610b706915d9371 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:25:18 +1100 Subject: [PATCH 0366/1514] iommu: apple-dart: read a 27.2 display DART's TCR before dropping its PM reference __apple_dart_j713_v27_fw_prot() took a runtime-PM reference, read the stream's TTBR, dropped the reference and only then read DART_TCR for the four-level check. apple_dart_probe() drops its own probe reference for these DARTs, so the TCR read could hit a suspended DART. Read TTBR and TCR while the reference is held, then put it. The KUnit case now also checks that a stream whose TCR says four-level is left as it asked. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 7 +++++++ drivers/iommu/apple-dart.c | 9 +++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 6ebc214842b2c1..71c1bfa7a3a2d5 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1430,6 +1430,13 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) SetPageReserved(virt_to_page(leaf)); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + /* A four-level root is not walked: nothing changes. */ + text.prot = IOMMU_READ | IOMMU_WRITE; + writel(dart->hw->tcr_4level, dart->regs + DART_TCR(dart, 23)); + __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + writel(0, dart->regs + DART_TCR(dart, 23)); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + /* Not a 27.2 J713 display DART: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; dart->j713_v27 = false; diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 34e169ec0c26f2..b435a989ad1f8d 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -4584,7 +4584,7 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str phys_addr_t table; u64 *root, span, base; size_t entries; - u32 ttbr; + u32 ttbr, tcr = 0; int sid; if (!cfg || !cfg->stream_maps[0].dart || cfg->stream_maps[1].dart) @@ -4599,11 +4599,12 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str return; if (pm_runtime_resume_and_get(dart->dev) < 0) return; + /* Read both registers while the DART is held powered. */ ttbr = apple_dart_readl(dart, DART_TTBR(dart, sid, 0)); + if (dart->hw->tcr_4level) + tcr = apple_dart_readl(dart, DART_TCR(dart, sid)); pm_runtime_put(dart->dev); - if (!(ttbr & dart->hw->ttbr_valid) || - (dart->hw->tcr_4level && - (apple_dart_readl(dart, DART_TCR(dart, sid)) & dart->hw->tcr_4level))) + if (!(ttbr & dart->hw->ttbr_valid) || (tcr & dart->hw->tcr_4level)) return; ttbr &= ~dart->hw->ttbr_valid; if (dart->hw->ttbr_addr_field_shift) From 76c6464014c36d02049ca0c3cbdc1385b7a16289 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:25:55 +1100 Subject: [PATCH 0367/1514] iommu: apple-dart: name the 27.2 internal display DART after its handoff Since "iommu: apple-dart: key a 27.2 internal display DART on its processor's handoff" no board decides which DARTs take this path: any T8132 internal display DART whose DCP the boot loader handed over on the 27.2 image does. The flag, its helpers and the probe log still said J713, so an M4 MacBook Pro would log as one. Rename j713_v27 to t8132_dcp_v27 (and the helpers and the KUnit case with it) and log "T8132 internal display DART". No functional change. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 26 ++++++++++----------- drivers/iommu/apple-dart.c | 40 ++++++++++++++++----------------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 71c1bfa7a3a2d5..920097ea03f708 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1347,11 +1347,11 @@ static u64 *apple_dart_test_reserved_table(struct kunit *test) } /* - * A 27.2 J713 display DART: re-exported firmware segments take the protection - * of the live leaves that map them (read-only text, cacheable data); a region - * whose leaf maps another page keeps what it asked for. + * A 27.2 T8132 internal display DART: re-exported firmware segments take the + * protection of the live leaves that map them (read-only text, cacheable + * data); a region whose leaf maps another page keeps what it asked for. */ -static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) +static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) { const u64 fields = GENMASK_ULL(51, 40) | BIT_ULL(0); const phys_addr_t text_pa = 0x80000000ULL, data_pa = 0x80100000ULL; @@ -1367,7 +1367,7 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) kunit_skip(test, "needs kernel pages of at least 16 KiB"); dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, dart); - dart->dev = kunit_device_register(test, "apple-dart-j713-v27-test"); + dart->dev = kunit_device_register(test, "apple-dart-t8132-dcp-v27-test"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); regs = vzalloc(APPLE_DART_TEST_REGS_SIZE); KUNIT_ASSERT_NOT_NULL(test, regs); @@ -1379,7 +1379,7 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) dart->oas = 42; dart->locked = true; dart->fw_mirror = true; - dart->j713_v27 = true; + dart->t8132_dcp_v27 = true; /* The display DARTs' window: 64 GiB at 1 TiB. */ dart->locked_window[23] = 0x10000000000ULL; root = apple_dart_test_reserved_table(test); @@ -1416,7 +1416,7 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) pm_runtime_set_active(dart->dev); pm_runtime_enable(dart->dev); - __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, data.prot, IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, moved.prot, IOMMU_READ | IOMMU_WRITE); @@ -1426,21 +1426,21 @@ static void apple_dart_test_j713_v27_fw_prot(struct kunit *test) /* A leaf table outside reserved RAM is never mapped: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; ClearPageReserved(virt_to_page(leaf)); - __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); SetPageReserved(virt_to_page(leaf)); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); /* A four-level root is not walked: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; writel(dart->hw->tcr_4level, dart->regs + DART_TCR(dart, 23)); - __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); writel(0, dart->regs + DART_TCR(dart, 23)); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); - /* Not a 27.2 J713 display DART: nothing changes. */ + /* Not a 27.2 T8132 internal display DART: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; - dart->j713_v27 = false; - __apple_dart_j713_v27_fw_prot(&master, dart->dev, &head); + dart->t8132_dcp_v27 = false; + __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); pm_runtime_disable(dart->dev); } @@ -1454,7 +1454,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_locked_handoff), KUNIT_CASE(apple_dart_test_sync_unknown_roots), KUNIT_CASE(apple_dart_test_firmware_roots), - KUNIT_CASE(apple_dart_test_j713_v27_fw_prot), + KUNIT_CASE(apple_dart_test_t8132_dcp_v27_fw_prot), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index b435a989ad1f8d..f5c6bcc6f2b33b 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -426,8 +426,8 @@ struct apple_dart { u32 sleep_gated : 1; /* Locked roots may hold firmware slots that mirror Linux mappings. */ u32 fw_mirror : 1; - /* A J713 internal display DART on the 27.2 image (fw_mirror, not borrowed). */ - u32 j713_v27 : 1; + /* A T8132 internal display DART on the 27.2 image (fw_mirror, not borrowed). */ + u32 t8132_dcp_v27 : 1; /* * fw_mirror's four-level locked roots hold firmware's own subtrees, which * are recorded and reserved (apple_dart_snapshot_fw_tree()). Set only for @@ -4565,7 +4565,7 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, } /* - * A J713 internal display DART on the 27.2 image (fw_mirror): the boot loader + * A T8132 internal display DART on the 27.2 image (fw_mirror): the boot loader * re-exports the firmware's own segments as iommu-addresses, which the core * maps read-write, and uncached for this non-coherent DCP. The firmware's * leaves say what those pages are: its text read-only, all of it cacheable. @@ -4575,8 +4575,8 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, * there, map elsewhere or disagree keeps its protection, and the attach then * refuses it as before. */ -static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, struct device *dev, - struct list_head *head) +static void __apple_dart_t8132_dcp_v27_fw_prot(struct apple_dart_master_cfg *cfg, + struct device *dev, struct list_head *head) { const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; struct iommu_resv_region *region; @@ -4590,7 +4590,7 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str if (!cfg || !cfg->stream_maps[0].dart || cfg->stream_maps[1].dart) return; dart = cfg->stream_maps[0].dart; - if (!dart->j713_v27 || !dart->locked || dart->hw->fmt != APPLE_DART2) + if (!dart->t8132_dcp_v27 || !dart->locked || dart->hw->fmt != APPLE_DART2) return; entries = dart->pgsize / sizeof(u64); sid = find_first_bit(cfg->stream_maps[0].sidmap, dart->num_streams); @@ -4666,9 +4666,9 @@ static void __apple_dart_j713_v27_fw_prot(struct apple_dart_master_cfg *cfg, str memunmap(root); } -static void apple_dart_j713_v27_fw_prot(struct device *dev, struct list_head *head) +static void apple_dart_t8132_dcp_v27_fw_prot(struct device *dev, struct list_head *head) { - __apple_dart_j713_v27_fw_prot(dev_iommu_priv_get(dev), dev, head); + __apple_dart_t8132_dcp_v27_fw_prot(dev_iommu_priv_get(dev), dev, head); } static void apple_dart_get_resv_regions(struct device *dev, @@ -4700,7 +4700,7 @@ static void apple_dart_get_resv_regions(struct device *dev, /* Keep the translated-domain requirement and inherited translations. */ iommu_dma_get_resv_regions(dev, head); - apple_dart_j713_v27_fw_prot(dev, head); + apple_dart_t8132_dcp_v27_fw_prot(dev, head); apple_dart_get_fw_resv_regions(dev, head); } @@ -5511,7 +5511,7 @@ static int apple_dart_probe(struct platform_device *pdev) bool tunneled = dev->of_node->parent && of_node_name_prefix(dev->of_node->parent, "usb4-pcie-tunnel-"); - bool j713_display, j713_dcpext, j713_dispext, j713_radio, j713_display_v27 = false; + bool j713_display, j713_dcpext, j713_dispext, j713_radio, t8132_display_v27 = false; /* * The M4 internal display DARTs are live: DCP firmware (SID23) @@ -5530,10 +5530,10 @@ static int apple_dart_probe(struct platform_device *pdev) * (fw_mirror below). The borrowed path admits only the 26.6.2 layout * and reserves its whole SID23 window from generic DMA. */ - j713_display_v27 = res && !tunneled && + t8132_display_v27 = res && !tunneled && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && apple_dart_serves_t8132_dcp_v27(dev->of_node); - if (j713_display_v27) + if (t8132_display_v27) j713_display = false; /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ j713_dcpext = res && !tunneled && apple_t8132_firmware_path() && @@ -5553,7 +5553,7 @@ static int apple_dart_probe(struct platform_device *pdev) * over, but the running DCP still uses them: never reset them. A DART * whose processor was handed over with the 27.2 image is handed over. */ - if (res && !tunneled && !j713_display_v27 && !apple_t8132_firmware_path() && + if (res && !tunneled && !t8132_display_v27 && !apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { @@ -6054,13 +6054,13 @@ static int apple_dart_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t6050-dart") || of_device_is_compatible(dev->of_node, "apple,t8140-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-dart") || - j713_display_v27); - if (j713_display_v27 && dart->fw_mirror) - dev_info(dev, "J713 internal display DART on the 27.2 image: locked roots kept (mirror)\n"); - else if (j713_display_v27) - dev_err(dev, "J713 internal display DART on the 27.2 image: NOT locked: refusing\n"); - dart->j713_v27 = j713_display_v27; - if (j713_display_v27 && !dart->fw_mirror) { + t8132_display_v27); + if (t8132_display_v27 && dart->fw_mirror) + dev_info(dev, "T8132 internal display DART on the 27.2 image: locked roots kept (mirror)\n"); + else if (t8132_display_v27) + dev_err(dev, "T8132 internal display DART on the 27.2 image: NOT locked: refusing\n"); + dart->t8132_dcp_v27 = t8132_display_v27; + if (t8132_display_v27 && !dart->fw_mirror) { ret = -EINVAL; goto err_clk_disable; } From 97085f262267b008040816395792d4b58fc36421 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:26:08 +1100 Subject: [PATCH 0368/1514] iommu: apple-dart: say why a 27.2 internal display DART is refused fw_mirror needs the DART locked and no reserved-table handoff. A 27.2 T8132 internal display DART without fw_mirror was always logged as "NOT locked", also when it was locked and its boot loader had handed over reserved tables as well. Keep refusing both (the firmware-27 backend runs on the locked roots only), but log the reserved-table case as what it is. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index f5c6bcc6f2b33b..bc582e3facb514 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -6055,10 +6055,17 @@ static int apple_dart_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8140-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-dart") || t8132_display_v27); + /* + * The firmware-27 backend runs on the locked roots alone: a DART that + * is not locked, or whose boot loader also handed over reserved tables, + * is not the handoff it was written for. Refuse either, saying which. + */ if (t8132_display_v27 && dart->fw_mirror) dev_info(dev, "T8132 internal display DART on the 27.2 image: locked roots kept (mirror)\n"); - else if (t8132_display_v27) + else if (t8132_display_v27 && !dart->locked) dev_err(dev, "T8132 internal display DART on the 27.2 image: NOT locked: refusing\n"); + else if (t8132_display_v27) + dev_err(dev, "T8132 internal display DART on the 27.2 image: locked with a reserved-table handoff: refusing\n"); dart->t8132_dcp_v27 = t8132_display_v27; if (t8132_display_v27 && !dart->fw_mirror) { ret = -EINVAL; From df2748e9d323bea27aa55ce938ae261ae3cd99e1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:26:28 +1100 Subject: [PATCH 0369/1514] drm/apple: dcp: give the J773g dcpext hw data its comment back The T8132 internal DCP's 27.2 hw data and its comment went in between the J773g dcpext comment and apple_dcp_hw_t8132_dcpext_v27, so the dcpext struct read as undocumented and the dcpext comment sat on the wrong struct. Put the internal one after the dcpext struct. No functional change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index e2c96564e6763c..1b88efc7e8aace 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7232,6 +7232,14 @@ static int dcp_s2r_pm_register(struct apple_dcp *dcp); * No sleep support: neither a firmware-27 sleep nor a link release has run * on this processor. */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { + .firmware_dma_bits = 41, + .num_dptx_ports = 2, + .adopt_live_session = true, + .firmware_compat = DCP_FIRMWARE_V_27_0, + .sink_metadata_edid = true, +}; + /* * T8132 internal display processor on firmware 27.2, admitted by * dcp_check_firmware_version(), whatever hw data its compatible matched: @@ -7249,14 +7257,6 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8132_v27 = { .firmware_compat = DCP_FIRMWARE_V_27_0, }; -static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext_v27 = { - .firmware_dma_bits = 41, - .num_dptx_ports = 2, - .adopt_live_session = true, - .firmware_compat = DCP_FIRMWARE_V_27_0, - .sink_metadata_edid = true, -}; - static int dcp_platform_probe_pipe(struct platform_device *pdev) { const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); From ad87173bf07970fae21bffb1b48c51f9d9d2d7e0 Mon Sep 17 00:00:00 2001 From: Kazuhide Takahashi Date: Sat, 21 Nov 2026 05:45:08 +0000 Subject: [PATCH 0370/1514] drm/asahi: g16: admit 25G83 on every T8132 Air with one normalized entry The T8132 table pins the same 25G83 image (build 2 of armfw_g16g.im4p) three times, one TEXT digest per J713 variant, and #2667 would add a fourth for the J715. The images differ only in what iBoot writes into TEXT at load time. Comparing the TEXT of the 26.6.2 firmware file with the TEXT loaded on a J715 shows that iBoot writes three ranges besides the two entropy records. The image describes each of them itself: - 0x23c, 8 bytes: a header field. - 0x5c8df, 0x231 bytes: the record block (GKTS ... ECAP ...). The header states this offset and length at 0x22c/0x230. - 0x5cb10, 0x6a0 bytes: the tunables block. The block's TUNS record points at it, and its TUNZ record gives the size. With these ranges in boot_filled, the file's TEXT and the J715's loaded TEXT hash to the same digest. Every byte that differs between the two lies inside the ranges. Add that single entry ahead of the per-board ones, as the G17 tables already do, and name it so the identity line says which entry admitted the image. Keep the J713 8-core and 10-core entries after it for now. Only a J715 has booted with just the normalized entry; if a J713's iBoot writes anywhere outside the three ranges, removing its entries would stop its GPU at "unsupported GPU firmware build". They can go once both J713 variants have booted on 26.6.2 with only the normalized entry. j713_accepts_all_loaded_images() now expects the J713 digests at builds[1..=3], and checks that the normalized entry at builds[0] is found by its own digest and that its boot_filled ranges lie inside TEXT. Tested on J715 (Mac16,13, 10 cores, OS firmware 26.6.2) with only the normalized entry in the table: "firmware identity accepted", READY, Hyprland session. Not tested on J713. Signed-off-by: Kazuhide Takahashi --- drivers/gpu/drm/asahi/fwid.rs | 16 +++++++++++++++- drivers/gpu/drm/asahi/g16/hw.rs | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index f9525c0c08f306..3321c42efe35d2 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -563,9 +563,23 @@ mod tests { 0x86, 0x8b, 0xc9, 0xcf, ], ]; + // builds[0] is the normalized entry; the per-board J713 entries follow it. + let normalized = &builds[0]; + assert!(normalized + .boot_filled + .iter() + .all(|&(offset, len)| u64::from(offset) + u64::from(len) <= normalized.text_size)); + let found = measured( + builds, + 0x13c000, + &[[0x5c8df, 0x5c9c2]], + normalized.text_sha256, + ) + .unwrap(); + assert!(core::ptr::eq(found, normalized)); for (i, digest) in digests.into_iter().enumerate() { let found = measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], digest).unwrap(); - assert!(core::ptr::eq(found, &builds[i])); + assert!(core::ptr::eq(found, &builds[i + 1])); assert!(measured(builds, 0x138000, &[[0x5c8df, 0x5c9c2]], digest).is_none()); } assert!(measured(builds, 0x13c000, &[[0x5c8df, 0x5c9c2]], [0; 32]).is_none()); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 353199dea75a1b..5c3e913efdeaba 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -38,6 +38,25 @@ pub(crate) mod t8132 { counts: 0x0011010a, }], firmware: &[ + FirmwareBuild { + // 25G83 (build 2 of armfw_g16g.im4p) as iBoot loads it on a T8132 Air. Besides + // the entropy, iBoot fills a header field, the record block the header points at + // (0x5c8df, 0x231) and the tunables block its TUNS/TUNZ records describe + // (0x5cb10, 0x6a0). With those zeroed, the loaded image hashes the same as the + // TEXT of the firmware file. + name: "Apple GFX 25G83 (normalized loaded image, boot-filled ranges)", + text_size: 0x60000, + data_size: 0x13c000, + entropy: &[[0x5c8df, 0x5c9c2]], + boot_filled: &[(0x23c, 8), (0x5c8df, 0x231), (0x5cb10, 0x6a0)], + text_sha256: [ + 0x3a, 0x41, 0xe4, 0x77, 0xb1, 0x2d, 0x48, 0x8d, 0x0c, 0x27, 0x7d, 0x1d, 0x30, + 0x6b, 0x60, 0x88, 0x5e, 0x67, 0x5e, 0xc7, 0x98, 0x54, 0xca, 0xaf, 0x90, 0x29, + 0x35, 0xc2, 0x7e, 0xf8, 0x76, 0x5e, + ], + }, + // The per-board entries below stay until an 8-core and a 10-core J713 on 26.6.2 + // have booted with only the normalized entry above. FirmwareBuild { name: "Apple GFX 25G83 (normalized loaded image)", text_size: 0x60000, From 0444d9aef4075edd8ef0a647bdcdc8d129c93c2e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:41 +1100 Subject: [PATCH 0371/1514] wifi: apple: centauri: give the ring tail and PCI PM state their sparse types sparse (C=1, allmodconfig) reports four "cast to restricted __le16" and three "restricted pci_power_t degrades to integer" warnings here: - The IPC send and hello paths poll a little-endian ring index with READ_ONCE() into a u16 and then pass that to le16_to_cpu(). Declare the local as __le16, which is what it holds. The conversion and the comparison are unchanged. - PCI_D0 and PCI_D3hot are pci_power_t (__bitwise). Writing them into PCI_PM_CTRL needs a __force u16 cast, as drivers/pci/pci.c does. No functional change: the generated code is identical. Signed-off-by: Ryan Murray --- drivers/net/wireless/apple/centauri/centauri_ipc.c | 4 ++-- drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c | 4 ++-- drivers/net/wireless/apple/centauri/t6050/centauri_pci.c | 7 ++++--- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/centauri_ipc.c b/drivers/net/wireless/apple/centauri/centauri_ipc.c index 6f96041c772902..8d117989cd7602 100644 --- a/drivers/net/wireless/apple/centauri/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/centauri_ipc.c @@ -233,7 +233,7 @@ static int message(struct cen_context *ctx, void __iomem *doorbell, { u16 head = ctx->message_head; u8 *descriptor; - u16 tail; + __le16 tail; int ret; if (head >= 15 || !length || length > 512) @@ -274,7 +274,7 @@ static int cchi_init(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; u8 config[4] = {9, 0, 0xff, 0xff}, *entry; - u16 tail; + __le16 tail; int i, ret; ipc->cchi_rx = buffer_alloc(c, 0, SZ_32K); diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c index 0210363889d024..a5f49860afdd2f 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c @@ -191,7 +191,7 @@ static int message(struct cen_context *ctx, void __iomem *doorbell, { u16 head = ctx->message_head; u8 *descriptor; - u16 tail; + __le16 tail; int ret; if (head >= 15 || !length || length > 512) @@ -232,7 +232,7 @@ static int cchi_init(struct centauri_t6050 *c) { struct centauri_t6050_ipc *ipc = c->ipc; u8 config[4] = {9, 0, 0xff, 0xff}, *entry; - u16 tail; + __le16 tail; int i, ret; ipc->cchi_rx = buffer_alloc(c, 0, SZ_32K); diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c index 5932cc65720c45..6cda4019d8f0dc 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c @@ -401,7 +401,8 @@ static int centauri_t6050_port_cycle(struct pci_dev *endpoint) if (ret) goto stopped; ret = pcibios_err_to_errno(pci_write_config_word(endpoint, pm + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | PCI_D3hot | PCI_PM_CTRL_PME_ENABLE)); + (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | (__force u16)PCI_D3hot | + PCI_PM_CTRL_PME_ENABLE)); if (ret) goto stopped; usleep_range(10000, 11000); @@ -1030,7 +1031,7 @@ static void centauri_t6050_set_d3hot(struct pci_dev *pdev) if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl)) { pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | - PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); + (__force u16)PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); mdelay(pdev->d3hot_delay); } } @@ -1042,7 +1043,7 @@ static void centauri_t6050_ensure_d0(struct pci_dev *pdev) if (!pdev || !pdev->pm_cap) return; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl) && - (pmctrl & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { + (pmctrl & PCI_PM_CTRL_STATE_MASK) != (__force u16)PCI_D0) { pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl & ~PCI_PM_CTRL_STATE_MASK); mdelay(pdev->d3hot_delay); From 747fbe21f412a2ec888147cae068c5872fec12b1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:41 +1100 Subject: [PATCH 0372/1514] iommu/apple-dart: mark the DCP host lock helpers __maybe_unused apple_dart_host_lock() and apple_dart_host_unlock() live in apple-dart-dcp.h, but their only callers in apple-dart.c sit under CONFIG_APPLE_DART_J713_DCP. Any build without that option (APPLE_DART=m, 4K pages, allmodconfig) gets two -Wunused-function warnings. Mark them __maybe_unused. static inline would also silence the warning, but it changes clang's inlining in apple-dart.o; __maybe_unused leaves the generated code identical with CONFIG_APPLE_DART_J713_DCP=y. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-dcp.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart-dcp.h b/drivers/iommu/apple-dart-dcp.h index 49ed48c2f3de6e..813dd46c07df6d 100644 --- a/drivers/iommu/apple-dart-dcp.h +++ b/drivers/iommu/apple-dart-dcp.h @@ -139,7 +139,7 @@ static inline void apple_dart_pm_invalidate(struct apple_dart *dart, bool suspen * register used; its power-up flushes every translation, with these locks * held, before it enables the streams again. */ -static void apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) +static void __maybe_unused apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) { struct apple_dart_dcp *streams[] = { dart->dcp, dart->frontend[0], dart->frontend[1] }; unsigned int held = 0; @@ -150,7 +150,7 @@ static void apple_dart_host_lock(struct apple_dart *dart, unsigned long *flags) spin_lock_nested(&streams[i]->lock, held++); } -static void apple_dart_host_unlock(struct apple_dart *dart, unsigned long flags) +static void __maybe_unused apple_dart_host_unlock(struct apple_dart *dart, unsigned long flags) { struct apple_dart_dcp *streams[] = { dart->frontend[1], dart->frontend[0], dart->dcp }; From b1d6fc5549ab0ca3af760d6facf7e554a0af6a7c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:42 +1100 Subject: [PATCH 0373/1514] phy: apple: atc: build the DP lane mask without !! sparse warns "dubious: !x | y" on the DP lane mask. dp_lane[] is bool, so the double negation does nothing; drop it. The generated code is identical. Signed-off-by: Ryan Murray --- drivers/phy/apple/atc-j700-dp.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/phy/apple/atc-j700-dp.h b/drivers/phy/apple/atc-j700-dp.h index a07f1125c2c43f..55cd6fdeb4b7e3 100644 --- a/drivers/phy/apple/atc-j700-dp.h +++ b/drivers/phy/apple/atc-j700-dp.h @@ -483,7 +483,7 @@ static int j700_dp_configure(struct apple_atcphy *p, const struct phy_configure_ if (p->mode != APPLE_ATCPHY_MODE_DP && p->mode != APPLE_ATCPHY_MODE_USB3_DP) return -EINVAL; mode = atcphy_get_mode_config(p, p->mode); - pmas = !!mode->dp_lane[0] | (!!mode->dp_lane[1] << 1); + pmas = mode->dp_lane[0] | (mode->dp_lane[1] << 1); capacity = 2 * hweight32(pmas); if (o->lanes > capacity || (o->set_lanes && o->lanes != 1 && o->lanes != 2 && o->lanes != 4)) From fb37343c17f8466efbd278dd256d25b6015b3fa6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:49:00 +1100 Subject: [PATCH 0374/1514] soc: apple: clpc: make the vote test catch a wrap-unsafe hold t0 = ULONG_MAX - hold / 2 puts every held sample past the wrap together with last_demand + hold, so a plain 'now >= last_demand + hold' passes the test. Start at ULONG_MAX - (hold - 1) instead: the last held sample is ULONG_MAX while the deadline has wrapped to 0. Also move the invalid-entry comment to the up steps that can pick it, say the max_freq fallback of apple_clpc_profile_limit() is not covered, and expect the exact value above the table instead of a bound. Signed-off-by: Ryan Murray --- drivers/soc/apple/clpc.c | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 27c3a15da4fa9d..4b3e960a81e18f 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -2116,27 +2116,30 @@ static void apple_clpc_step_khz_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, true), 1500000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, true), 2000000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000, false), 1200000u); - /* The invalid entry is not a step. */ KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1200000, false), 600000u); /* Off the table: the nearest entry in that direction. */ KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, true), 1500000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1300000, false), 1200000u); - /* No step past either end: @khz back. */ + /* + * No step past either end: @khz back. The invalid entry sits above + * every real one, so these up steps are the ones that would pick it. + */ KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2000000, true), 2000000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000, false), 600000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2100000, true), 2100000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 0, false), 0u); /* - * The low-power top, as apple_clpc_profile_limit() takes it: the first - * entry at or above low_power_khz, so a value between two entries - * rounds up and an exact entry is kept. + * The lookup apple_clpc_profile_limit() makes for the low-power top: the + * first entry at or above low_power_khz, so a value between two entries + * rounds up and an exact entry is kept. Its max_freq fallback is not + * covered here. */ KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1400000 - 1, true), 1500000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 1500000 - 1, true), 1500000u); KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 600000 - 1, true), 600000u); - /* Above the table nothing is found; the caller falls back to max_freq. */ - KUNIT_EXPECT_LT(test, apple_clpc_step_khz(policy, 2100000 - 1, true), 2100000u); + /* Above the table nothing is found and @khz comes back. */ + KUNIT_EXPECT_EQ(test, apple_clpc_step_khz(policy, 2100000 - 1, true), 2100000u - 1); } static void apple_clpc_steps_first_test(struct kunit *test) @@ -2161,11 +2164,16 @@ static void apple_clpc_steps_first_test(struct kunit *test) static void apple_clpc_vote_test(struct kunit *test) { unsigned long hold = msecs_to_jiffies(APPLE_CLPC_HOLD_MS); - /* Start close to the jiffies wrap, so the hold spans it. */ - unsigned long t0 = ULONG_MAX - hold / 2; + /* + * Start so that the hold deadline wraps to 0 while its last held + * sample is still ULONG_MAX: a compare that is not wrap-safe drops + * the vote early there. + */ + unsigned long t0 = ULONG_MAX - (hold - 1); struct apple_clpc_vote vote = {}; KUNIT_ASSERT_GT(test, hold, 1ul); + KUNIT_ASSERT_EQ(test, t0 + hold - 1, ULONG_MAX); KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 0, t0), 0u); KUNIT_EXPECT_EQ(test, apple_clpc_vote(&vote, 5, t0), 5u); /* No demand: the state holds for APPLE_CLPC_HOLD_MS, then drops. */ From e29c9a8d76bd30582943b39e45874a4a157ee2af Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:59:19 -0500 Subject: [PATCH 0375/1514] drm/asahi: hold GPU power domain across suspend-to-idle During suspend-to-idle (!pm_suspend_via_firmware()), the GPU driver leaves its firmware running, but genpd_suspend_noirq() still powered off attached GPU power domains that are neither always-on nor sleep-retained (such as ps_gfx on M1/M2/M3 and M5 J813). Cutting power under the live GFX ASC crashed the firmware immediately on resume (PC=0, FAR=0). Instead of changing PMGR domain flags globally, hold the GPU device's own attached genpd from the drm/asahi driver side during the noirq sleep window using a temporary GENPD_NOTIFY_PRE_OFF veto notifier, matching pcie-apple. Allocate per-device hold state via devres at probe time across AsahiPlatformDriver, g15::Driver, and g16::Driver (so suspend_noirq never allocates and needs no global list or lock), and wire suspend_noirq and resume_noirq into SLEEP_OPS, SLEEP_REFUSE_OPS (g15::Driver, whose prepare only refuses firmware-driven sleep and allows s2idle), and g16::sleep::SLEEP_OPS. If dev_pm_genpd_add_notifier() reports -EEXIST, if the probe-time devres hold is unexpectedly absent, or if a future multi-domain GPU DT node leaves dev->pm_domain unset with more than one power-domains entry, warn and refuse suspend with -EBUSY rather than letting GPU power domains power off under live firmware. Firmware-driven deep sleep (pm_suspend_via_firmware() == true) and all other power domains are unaffected. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/Makefile | 2 +- drivers/gpu/drm/asahi/driver.rs | 39 ++++++++- drivers/gpu/drm/asahi/g16/sleep.rs | 2 + drivers/gpu/drm/asahi/sleep_pd.c | 125 +++++++++++++++++++++++++++++ drivers/gpu/drm/asahi/sleep_pd.h | 12 +++ 5 files changed, 178 insertions(+), 2 deletions(-) create mode 100644 drivers/gpu/drm/asahi/sleep_pd.c create mode 100644 drivers/gpu/drm/asahi/sleep_pd.h diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index e8d4ccb27f2100..bb0fbb11822208 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -8,5 +8,5 @@ aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o +aurora-y += retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2b..7bbfa81b7039c5 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -279,6 +279,34 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i } } +extern "C" { + fn asahi_sleep_pd_init(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_sleep_pd_suspend_noirq(dev: *mut core::ffi::c_void) -> core::ffi::c_int; + fn asahi_sleep_pd_resume_noirq(dev: *mut core::ffi::c_void) -> core::ffi::c_int; +} + +/// Allocates per-device suspend-to-idle power-domain hold state tied to `dev`'s binding. +fn sleep_pd_init(dev: &kernel::device::Device>) -> Result { + // SAFETY: `dev` is being probed, so attaching devres state to its raw device is valid. + kernel::error::to_result(unsafe { asahi_sleep_pd_init(dev.as_raw().cast()) }) +} + +/// Holds the GPU's attached power domain across suspend-to-idle while its firmware stays live. +pub(crate) unsafe extern "C" fn sleep_suspend_noirq( + dev: *mut bindings::device, +) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { asahi_sleep_pd_suspend_noirq(dev.cast()) } +} + +/// Releases any suspend-to-idle power-domain hold taken by [`sleep_suspend_noirq`]. +pub(crate) unsafe extern "C" fn sleep_resume_noirq( + dev: *mut bindings::device, +) -> core::ffi::c_int { + // SAFETY: Called by the PM core with a bound GPU device. + unsafe { asahi_sleep_pd_resume_noirq(dev.cast()) } +} + /// Runs after every device resumed. Does nothing unless [`sleep_prepare`] stopped the firmware. unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. @@ -290,6 +318,8 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), + suspend_noirq: Some(sleep_suspend_noirq), + resume_noirq: Some(sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); @@ -306,6 +336,8 @@ unsafe extern "C" fn sleep_refuse(_dev: *mut bindings::device) -> core::ffi::c_i static SLEEP_REFUSE_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_refuse), + suspend_noirq: Some(sleep_suspend_noirq), + resume_noirq: Some(sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); @@ -353,7 +385,10 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); - let cfg = match info.ok_or(ENODEV)? { + let info = info.ok_or(ENODEV)?; + sleep_pd_init(pdev.as_ref())?; + + let cfg = match info { ProbeConfig::Legacy(cfg) => *cfg, ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) @@ -466,6 +501,7 @@ impl AsahiPlatformDriver { pdev: &'bound platform::Device>, cfg: &'static crate::g15::Config, ) -> Result> { + sleep_pd_init(pdev.as_ref())?; // SAFETY: Admission checks the SoC and the UAT output width before DMA starts. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; let resources = regs::Resources::new(pdev)?; @@ -667,6 +703,7 @@ impl AsahiPlatformDriver { pdev: &'bound platform::Device>, cfg: &'static crate::g16::Config, ) -> Result> { + sleep_pd_init(pdev.as_ref())?; // SAFETY: the qualified UAT output width constrains this device's DMA. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(cfg.uat_oas)?)? }; let resources = regs::Resources::new(pdev)?; diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index a383a09b8d9711..69f91c7109450c 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -329,6 +329,8 @@ unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { static SLEEP_OPS: SleepOps = SleepOps(bindings::dev_pm_ops { prepare: Some(sleep_prepare), complete: Some(sleep_complete), + suspend_noirq: Some(crate::driver::sleep_suspend_noirq), + resume_noirq: Some(crate::driver::sleep_resume_noirq), // SAFETY: All-zero is the absence of every other callback. ..unsafe { core::mem::zeroed() } }); diff --git a/drivers/gpu/drm/asahi/sleep_pd.c b/drivers/gpu/drm/asahi/sleep_pd.c new file mode 100644 index 00000000000000..59afe0edd4f81a --- /dev/null +++ b/drivers/gpu/drm/asahi/sleep_pd.c @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Hold the GPU's attached power domain across suspend-to-idle. + * + * When a system sleep does not hand control to platform firmware + * (!pm_suspend_via_firmware()), the GPU driver leaves its firmware running. + * genpd would otherwise power the GPU's domain (such as ps_gfx) off in + * genpd_suspend_noirq(), cutting power under the live coprocessor. + * + * Register a temporary GENPD_NOTIFY_PRE_OFF veto notifier on the GPU device's + * own genpd for the noirq sleep window, matching pcie-apple's consumer-side + * hold without changing any other power domain. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sleep_pd.h" + +struct asahi_sleep_pd { + struct notifier_block nb; + bool active; +}; + +/* IRQ-safe domains invoke power notifiers in atomic context. */ +static int asahi_sleep_pd_notify(struct notifier_block *nb, + unsigned long action, void *data) +{ + if (action != GENPD_NOTIFY_PRE_OFF) + return NOTIFY_OK; + return notifier_from_errno(-EBUSY); +} + +static void asahi_sleep_pd_release(struct device *dev, void *res) +{ + struct asahi_sleep_pd *hold = res; + + if (hold->active) { + dev_pm_genpd_remove_notifier(dev); + hold->active = false; + } +} + +int asahi_sleep_pd_init(struct device *dev) +{ + struct asahi_sleep_pd *hold; + + hold = devres_alloc(asahi_sleep_pd_release, sizeof(*hold), GFP_KERNEL); + if (!hold) + return -ENOMEM; + + hold->nb.notifier_call = asahi_sleep_pd_notify; + devres_add(dev, hold); + return 0; +} + +int asahi_sleep_pd_suspend_noirq(struct device *dev) +{ + struct asahi_sleep_pd *hold; + int ret; + + if (pm_suspend_via_firmware()) + return 0; + + /* + * Every current GPU node attaches a single power domain (M2 attaches + * pmp_report_gfx with APPLE_USE_PMP, which keeps ps_gfx up as its + * parent), so dev->pm_domain is a single genpd that + * dev_pm_genpd_is_on() and dev_pm_genpd_add_notifier() target + * directly. For a multi-domain GPU node, genpd_dev_pm_attach() leaves + * dev->pm_domain unset, so dev_pm_genpd_is_on() would return false and + * genpd would power those domains off under live GPU firmware; refuse + * s2idle with -EBUSY rather than failing open. + */ + if (!dev->pm_domain) { + if (of_count_phandle_with_args(dev->of_node, "power-domains", + "#power-domain-cells") > 1) { + dev_warn_once(dev, + "GPU has multiple power domains; s2idle hold only supports a single genpd, refusing s2idle\n"); + return -EBUSY; + } + return 0; + } + + if (!dev_pm_genpd_is_on(dev)) + return 0; + + hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); + if (WARN_ON_ONCE(!hold)) + return -EBUSY; + + if (hold->active) + return 0; + + ret = dev_pm_genpd_add_notifier(dev, &hold->nb); + if (ret == -EEXIST) { + dev_warn(dev, "genpd already has a power notifier; refusing s2idle\n"); + return -EBUSY; + } + if (ret) + return ret; + + hold->active = true; + return 0; +} + +int asahi_sleep_pd_resume_noirq(struct device *dev) +{ + struct asahi_sleep_pd *hold; + + hold = devres_find(dev, asahi_sleep_pd_release, NULL, NULL); + if (!hold || !hold->active) + return 0; + + dev_pm_genpd_remove_notifier(dev); + hold->active = false; + return 0; +} diff --git a/drivers/gpu/drm/asahi/sleep_pd.h b/drivers/gpu/drm/asahi/sleep_pd.h new file mode 100644 index 00000000000000..a7cf65715fbfc7 --- /dev/null +++ b/drivers/gpu/drm/asahi/sleep_pd.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ + +#ifndef _ASAHI_SLEEP_PD_H +#define _ASAHI_SLEEP_PD_H + +struct device; + +int asahi_sleep_pd_init(struct device *dev); +int asahi_sleep_pd_suspend_noirq(struct device *dev); +int asahi_sleep_pd_resume_noirq(struct device *dev); + +#endif From a59a31a085addd1e7ab5362023c177ced05af0be Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 23:17:09 -0500 Subject: [PATCH 0376/1514] drm/asahi: admit the USC cache invalidate in the G15/G16 VDM root barrier The G15 (M3 Pro/Max) and G16 (M4) VDM stream gates admit a render only when its VDM stream starts with exactly 0x21000960. Mesa's AGX3 render-start barrier sets bit 3, the USC cache invalidate (0x21000968), so that the USC sees memory written since the previous render; on those GPUs it has to leave the bit out, or the render is refused with EINVAL. Admit the root barrier with or without the invalidate in both gates. The other backends do not check the root word, so every GPU now admits it: report that on every GPU with DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE, so userspace can set the bit whenever the kernel reports it and keep the plain word on older kernels. Bit 40 is unused in both the canonical and the G15 feature numbering. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/file.rs | 2 ++ drivers/gpu/drm/asahi/g15/gate.rs | 11 ++++++++--- drivers/gpu/drm/asahi/g15/params.rs | 7 ++++--- drivers/gpu/drm/asahi/g16/gate.rs | 7 +++++-- drivers/gpu/drm/asahi/g16/params.rs | 8 ++++---- include/uapi/drm/asahi_drm.h | 9 +++++++++ .../drivers/gpu/asahi-m4/test-stream-gate.py | 4 +++- 7 files changed, 35 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index b69834163d5b92..08837155027662 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -585,6 +585,8 @@ impl File { gpu.get_params(&mut params)?; params.features |= gpu.feature_flags(); + // Every backend admits the USC cache invalidate in the VDM root barrier. + params.features |= uapi::DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE as u64; if Self::supports_user_memory(reg_data) { params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64; } diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs index 590f5e6f0a5c11..c4c482fb8f89c8 100644 --- a/drivers/gpu/drm/asahi/g15/gate.rs +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -2,7 +2,9 @@ //! Stream admission gates (safety nets for userspace encoders). //! -//! VDM: the root stream's first word is 0x21000960. CDM walk from `cdm_ctrl_stream_base` through +//! VDM: the root stream's first word is 0x21000960, or 0x21000968 with the USC cache invalidate. +//! +//! CDM walk from `cdm_ctrl_stream_base` through //! links until TERMINATE (0x40000000), at most 64 links and [`CDM_MAX_BYTES`] of records (a //! longer or cyclic stream is rejected): barriers 0x60000160, 0x60001560, 0x600215fe, 0x600201fe; //! link 0x2000XXXX; direct launch (40 B, the G15 layout), indirect launches 36 B @@ -20,6 +22,8 @@ use super::{command::cover, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -148,7 +152,8 @@ fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G15 barrier. +/// VDM admission: a normal root stream opens with the G15 barrier, with or +/// without the USC cache invalidate. pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { if !params::stream_gate() { return Ok(()); @@ -156,7 +161,7 @@ pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { let mut bytes = [0u8; 4]; vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { return Err(reject("VDM root", va, &[word])); } Ok(()) diff --git a/drivers/gpu/drm/asahi/g15/params.rs b/drivers/gpu/drm/asahi/g15/params.rs index c2c34864750611..17ac71c28aa225 100644 --- a/drivers/gpu/drm/asahi/g15/params.rs +++ b/drivers/gpu/drm/asahi/g15/params.rs @@ -3,9 +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`, -//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`), the feature -//! word is exactly 0x3e (0xbe with `g15_early_tiling`). Never advertise SOFT_FAULTS, -//! FEW_PRIMITIVES or RENDER_RAY_QUERY on G15S. +//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`, and +//! VDM_USC_INVALIDATE, bit 40 in both numberings), the feature word is exactly 0x3e (0xbe with +//! `g15_early_tiling`) plus bit 40. Never advertise SOFT_FAULTS, FEW_PRIMITIVES or +//! RENDER_RAY_QUERY on G15S. use kernel::prelude::*; diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 0de0aeb5bfdc0e..b739890e1a375b 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -21,6 +21,8 @@ use super::{command::cover, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -103,7 +105,8 @@ fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> R Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G16 barrier. +/// VDM admission: a normal root stream opens with the G16 barrier, with or +/// without the USC cache invalidate. pub(crate) fn vdm(vm: &mmu::Vm, va: u64) -> Result { if !params::stream_gate() { return Ok(()); @@ -111,7 +114,7 @@ pub(crate) fn vdm(vm: &mmu::Vm, va: u64) -> Result { let mut bytes = [0u8; 4]; vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { return Err(reject("VDM root", va, &[word])); } Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index d2ef01e26b3a3d..ba6a59735a90e7 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`, VDM_USC_INVALIDATE), the feature word is 0x1c02 plus +//! bit 40: 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. use kernel::{prelude::*, uapi}; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 95ff9a15ffdb29..87ece3dd79d8dd 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -543,6 +543,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_ASYNC_SUBMIT ((1ULL) << 39) +/* + * DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE: the render-start VDM barrier at the + * root of a render's VDM stream may set the USC cache invalidate (bit 3). + * Reported on every GPU: the kernel's stream checks admit the barrier word + * with or without it. A feature bit like those of enum drm_asahi_feature, + * defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE ((1ULL) << 40) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index c701dd84471fa3..1295a8c128f640 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -240,7 +240,9 @@ } #[test] fn vdm_m4_root_barrier() { - assert!(g16::gate::vdm(&vm_for(&[0x21000960]), BASE).is_ok()); + for word in [0x21000960, 0x21000968] { + assert!(g16::gate::vdm(&vm_for(&[word]), BASE).is_ok()); + } for word in [0, 0x21000964, 0x40000000] { assert!(g16::gate::vdm(&vm_for(&[word]), BASE).is_err()); } From 7af9fe282129b3befdc5b2621eeff50f280062ee Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:42 +1100 Subject: [PATCH 0377/1514] media: apple: avd: mask the LSR address word before the u32 cast On LSR variants push_address() pushes (addr >> 8) as a u32. When a KUnit test passes a constant DMA address above 40 bits, sparse reports "cast truncates bits from constant value". Only the low 32 bits of (addr >> 8) go into the instruction word, so the truncation is intended. Say so with an explicit mask, the same way the non-LSR branch below writes its low word. (lower_32_bits() would do too, but the AVD host program test compiles this header without the kernel helpers.) The generated code is identical. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-inst.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/avd/avd-inst.h b/drivers/media/platform/apple/avd/avd-inst.h index dcdb205d793156..adf670a79645c6 100644 --- a/drivers/media/platform/apple/avd/avd-inst.h +++ b/drivers/media/platform/apple/avd/avd-inst.h @@ -176,7 +176,7 @@ static inline void push(struct avd_ctx *ctx, u32 inst) static inline void push_address(struct avd_ctx *ctx, dma_addr_t addr) { if (ctx->dev->variant->quirks & AVD_QUIRK_LSR) { - push(ctx, (addr >> 8)); + push(ctx, (u32)((addr >> 8) & 0xffffffff)); } else { push(ctx, (u32)(addr & 0xffffffff)); push(ctx, (u32)(addr >> 32)); From 23e09e0968c37ddb5e68c6df704bb01e4f1f30c1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:43 +1100 Subject: [PATCH 0378/1514] drm/apple: indent with tabs and fix brace and paren spacing Fix the checkpatch --strict ERRORs in drivers/gpu/drm/apple that are whitespace only and that no open pull request touches: - CODE_INDENT: indent with tabs (afk.h, audio.c, connector.c, dptxep.c, iomfb_internal.h, plane.c). - ELSE_AFTER_BRACE: "} else {" in parser.c, with braces on both branches. - SPACING: remove the inner spaces in DCP_FW_VERSION(). The generated code is identical. Files with many open PRs against them (dcp.c, dcp-internal.h, iomfb.c, iomfb_template.c, apple_drv.c, dcp-fabric.c) are left for later to avoid conflicts. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk.h | 4 ++-- drivers/gpu/drm/apple/audio.c | 22 +++++++++++----------- drivers/gpu/drm/apple/connector.c | 18 +++++++++--------- drivers/gpu/drm/apple/dptxep.c | 4 ++-- drivers/gpu/drm/apple/iomfb_internal.h | 10 +++++----- drivers/gpu/drm/apple/parser.c | 4 ++-- drivers/gpu/drm/apple/plane.c | 14 +++++++------- drivers/gpu/drm/apple/version_utils.h | 2 +- 8 files changed, 39 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index b2c7c5deddb29b..28b31aee6c2e3f 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -83,8 +83,8 @@ struct apple_epic_service { bool started; struct { - struct dentry *entry; - u8 *scratch; + struct dentry *entry; + u8 *scratch; } debugfs; }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 51fcc346a575b4..305766a731e4c0 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -318,16 +318,16 @@ static int dcpaud_select_cookie(struct dcp_audio *dcpaud, } static int dcpaud_rule_channels(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_interval *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); struct dcp_sound_format_mask hits = {0, 0, 0}; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return dcpaud_interval_bitmask(c, hits.nchans); + return dcpaud_interval_bitmask(c, hits.nchans); } static int dcpaud_refine_fmt_mask(struct snd_mask *m, u64 mask) @@ -343,29 +343,29 @@ static int dcpaud_refine_fmt_mask(struct snd_mask *m, u64 mask) } static int dcpaud_rule_format(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT); struct dcp_sound_format_mask hits; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return dcpaud_refine_fmt_mask(f, hits.formats); + return dcpaud_refine_fmt_mask(f, hits.formats); } static int dcpaud_rule_rate(struct snd_pcm_hw_params *params, - struct snd_pcm_hw_rule *rule) + struct snd_pcm_hw_rule *rule) { struct dcp_audio *dcpaud = rule->private; struct snd_interval *r = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct dcp_sound_format_mask hits; - dcpaud_consult_elements(dcpaud, params, &hits); + dcpaud_consult_elements(dcpaud, params, &hits); - return snd_interval_rate_bits(r, hits.rates); + return snd_interval_rate_bits(r, hits.rates); } static int dcpaud_init_dma(struct dcp_audio *dcpaud) @@ -1543,7 +1543,7 @@ static const struct snd_pcm_ops dcp_native_playback_ops = { #include "hdmi-codec-chmap.h" static int dcpaud_chmap_ctl_get(struct snd_kcontrol *kcontrol, - struct snd_ctl_elem_value *ucontrol) + struct snd_ctl_elem_value *ucontrol) { struct snd_pcm_chmap *info = snd_kcontrol_chip(kcontrol); struct dcp_audio *dcpaud = info->private_data; @@ -2110,7 +2110,7 @@ int __init dcp_audio_register(void) void dcp_audio_unregister(void) { - platform_driver_unregister(&dcpaud_driver); + platform_driver_unregister(&dcpaud_driver); } #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) diff --git a/drivers/gpu/drm/apple/connector.c b/drivers/gpu/drm/apple/connector.c index f3953abda34212..fb08369e2877d7 100644 --- a/drivers/gpu/drm/apple/connector.c +++ b/drivers/gpu/drm/apple/connector.c @@ -84,7 +84,7 @@ static int chunk_show(struct seq_file *m, } if (chunk) - seq_write(m, chunk->data, chunk->length); + seq_write(m, chunk->data, chunk->length); mutex_unlock(&apple_con->chunk_lock); @@ -94,18 +94,18 @@ static int chunk_show(struct seq_file *m, #define CONNECTOR_DEBUGFS_ENTRY(name, type) \ static int chunk_ ## name ## _show(struct seq_file *m, void *data) \ { \ - return chunk_show(m, type); \ + return chunk_show(m, type); \ } \ static int chunk_ ## name ## _open(struct inode *inode, struct file *file) \ { \ - return single_open(file, chunk_ ## name ## _show, inode->i_private); \ + return single_open(file, chunk_ ## name ## _show, inode->i_private); \ } \ static const struct file_operations chunk_ ## name ## _fops = { \ - .owner = THIS_MODULE, \ - .open = chunk_ ## name ## _open, \ - .read = seq_read, \ - .llseek = seq_lseek, \ - .release = single_release, \ + .owner = THIS_MODULE, \ + .open = chunk_ ## name ## _open, \ + .read = seq_read, \ + .llseek = seq_lseek, \ + .release = single_release, \ } CONNECTOR_DEBUGFS_ENTRY(color, DCP_CHUNK_COLOR_ELEMENTS); @@ -155,7 +155,7 @@ void apple_connector_debugfs_init(struct drm_connector *connector, struct dentry debugfs_create_file("DisplayAttributes", 0444, root, apple_con, &chunk_display_attribs_fops); debugfs_create_file("Transport", 0444, root, apple_con, - &chunk_transport_fops); + &chunk_transport_fops); switch (connector->connector_type) { case DRM_MODE_CONNECTOR_DisplayPort: diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index 1714bdbb2a6bf2..812c8116175960 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -986,7 +986,7 @@ static int dptxport_call(struct apple_epic_service *service, u32 idx, lc->lane_count = cpu_to_le64(dptx->lane_count); return 0; } - case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: + case DPTX_APCALL_SET_ACTIVE_LANE_COUNT: return dptxport_call_link_config(service, true, data, data_size, reply, reply_size); case DPTX_APCALL_GET_SUPPORTS_HPD: @@ -1059,7 +1059,7 @@ static int dptxport_call(struct apple_epic_service *service, u32 idx, reply, reply_size); return dptxport_call_set_drive_settings(service, data, data_size, reply, reply_size); - case DPTX_APCALL_ACTIVATE: + case DPTX_APCALL_ACTIVATE: return dptxport_call_activate(service, data, data_size, reply, reply_size); case DPTX_APCALL_DEACTIVATE: diff --git a/drivers/gpu/drm/apple/iomfb_internal.h b/drivers/gpu/drm/apple/iomfb_internal.h index 1fcaa17574dbe2..1e905637c3786d 100644 --- a/drivers/gpu/drm/apple/iomfb_internal.h +++ b/drivers/gpu/drm/apple/iomfb_internal.h @@ -66,11 +66,11 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); #define TRAMPOLINE_IN(func, handler, T_in) \ typedef void (*callback_##handler)(struct apple_dcp *, T_in *); \ - \ + \ static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ callback_##handler cb = handler; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ cb(dcp, in); \ return true; \ @@ -78,12 +78,12 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); #define TRAMPOLINE_INOUT(func, handler, T_in, T_out) \ typedef T_out (*callback_##handler)(struct apple_dcp *, T_in *); \ - \ + \ static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ T_out *typed_out = out; \ callback_##handler cb = handler; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ *typed_out = cb(dcp, in); \ return true; \ @@ -93,7 +93,7 @@ typedef void (*dcp_callback_t)(struct apple_dcp *, void *, void *); static bool __maybe_unused func(struct apple_dcp *dcp, int tag, void *out, void *in) \ { \ T_out *typed_out = out; \ - \ + \ trace_iomfb_callback(dcp, tag, #handler); \ *typed_out = handler(dcp); \ return true; \ diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 8538b0cb5aa0e7..28c429e48ecc75 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -390,9 +390,9 @@ static int parse_dimension(struct dcp_parse_ctx *handle, struct dimension *dim, else ret = parse_int_bound(it.handle, &dim->pixel_repetition, 0, U32_MAX); - } - else + } else { ret = skip(it.handle); + } if (!IS_ERR_OR_NULL(key)) kfree(key); diff --git a/drivers/gpu/drm/apple/plane.c b/drivers/gpu/drm/apple/plane.c index 35b86474e8f71a..97f29ebdee0378 100644 --- a/drivers/gpu/drm/apple/plane.c +++ b/drivers/gpu/drm/apple/plane.c @@ -655,7 +655,7 @@ static const struct drm_plane_helper_funcs apple_plane_helper_funcs = { // Duplicate drm_atomic_helper_plane_reset but allocate struct apple_plane_state static void apple_plane_reset(struct drm_plane *plane) { - struct apple_plane_state *state = to_apple_plane_state(plane->state); + struct apple_plane_state *state = to_apple_plane_state(plane->state); if (state) { apple_plane_cleanup_fb(plane, &state->base); __drm_atomic_helper_plane_destroy_state(&state->base); @@ -671,17 +671,17 @@ static void apple_plane_reset(struct drm_plane *plane) static struct drm_plane_state * apple_plane_duplicate_state(struct drm_plane *plane) { - struct apple_plane_state *apple_plane_state, *old_apple_plane_state; + struct apple_plane_state *apple_plane_state, *old_apple_plane_state; if (!plane->state) return NULL; - old_apple_plane_state = to_apple_plane_state(plane->state); - apple_plane_state = kzalloc(sizeof(*apple_plane_state), GFP_KERNEL); - if (!apple_plane_state) - return NULL; + old_apple_plane_state = to_apple_plane_state(plane->state); + apple_plane_state = kzalloc(sizeof(*apple_plane_state), GFP_KERNEL); + if (!apple_plane_state) + return NULL; - __drm_atomic_helper_plane_duplicate_state(plane, &apple_plane_state->base); + __drm_atomic_helper_plane_duplicate_state(plane, &apple_plane_state->base); apple_plane_state->surf = old_apple_plane_state->surf; apple_plane_state->src_rect = old_apple_plane_state->src_rect; diff --git a/drivers/gpu/drm/apple/version_utils.h b/drivers/gpu/drm/apple/version_utils.h index 8cf36e39d3f247..927986aeb8f00b 100644 --- a/drivers/gpu/drm/apple/version_utils.h +++ b/drivers/gpu/drm/apple/version_utils.h @@ -10,7 +10,7 @@ #define DCP_FW_UNION(u) (u).DCP_FW #define DCP_FW_SUFFIX CONCATENATE(_, DCP_FW) #define DCP_FW_NAME(name) CONCATENATE(name, DCP_FW_SUFFIX) -#define DCP_FW_VERSION(x, y, z) ( ((x) << 16) | ((y) << 8) | (z) ) +#define DCP_FW_VERSION(x, y, z) (((x) << 16) | ((y) << 8) | (z)) /* * 26.x firmware exists in two unrelated wire lineages. The H17-generation From dae4d256ff4e95480f39cd7965df36932f5fb3c7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:32:43 +1100 Subject: [PATCH 0379/1514] media: apple: avd, soc: apple: indent with tabs and fix bracket spacing Fix the whitespace-only checkpatch --strict ERRORs and LEADING_SPACE warnings in: - avd-av1-entropymode.c: indent the CDF tables with tabs, drop the spaces inside the array bounds of the table declarations, and write one cast as "(type *)". - avd.h: "const char *fw_name". - soc/apple dockchannel.c, shim.h and mailbox-g17-test.h: indent with tabs. The generated code is identical. Signed-off-by: Ryan Murray --- .../platform/apple/avd/avd-av1-entropymode.c | 38 +++++++++---------- drivers/media/platform/apple/avd/avd.h | 2 +- drivers/soc/apple/dockchannel.c | 4 +- drivers/soc/apple/mailbox-g17-test.h | 2 +- drivers/soc/apple/shim.h | 2 +- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-av1-entropymode.c b/drivers/media/platform/apple/avd/avd-av1-entropymode.c index ca15e08259a909..de312d214a0245 100644 --- a/drivers/media/platform/apple/avd/avd-av1-entropymode.c +++ b/drivers/media/platform/apple/avd/avd-av1-entropymode.c @@ -75,7 +75,7 @@ static_assert(offsetof(struct avd_av1_cdfs, dc_sign_cdf) == 5214); static_assert(offsetof(struct avd_av1_cdfs, coeff_base_cdf) == 6646); static_assert(sizeof(struct avd_av1_cdfs) == 9166); -static const u16 default_palette_uv_mode_cdf[ PALETTE_UV_MODE_CONTEXTS ] = { +static const u16 default_palette_uv_mode_cdf[PALETTE_UV_MODE_CONTEXTS] = { AOM_CDF(32461, 21488) }; @@ -94,15 +94,15 @@ static const u16 default_angle_delta_cdf[DIRECTIONAL_MODES] static const u16 default_if_y_mode_cdf[BLOCK_SIZE_GROUPS][CDF_SIZE(AV1_INTRA_MODES)] = { { AOM_CDF(22801, 23489, 24293, 24756, 25601, 26123, - 26606, 27418, 27945, 29228, 29685, 30349) + 26606, 27418, 27945, 29228, 29685, 30349) }, { AOM_CDF(18673, 19845, 22631, 23318, 23950, 24649, - 25527, 27364, 28152, 29701, 29984, 30852) + 25527, 27364, 28152, 29701, 29984, 30852) }, { AOM_CDF(19770, 20979, 23396, 23939, 24241, 24654, - 25136, 27073, 27830, 29360, 29730, 30659) + 25136, 27073, 27830, 29360, 29730, 30659) }, { AOM_CDF(20155, 21301, 22838, 23178, 23261, 23533, @@ -717,7 +717,7 @@ static const u16 default_palette_y_mode_cdf[PALETTE_BLOCK_SIZES] { { AOM_CDF(32450) }, { AOM_CDF(7946) }, { AOM_CDF(129) } } }; -static const u16 default_palette_size_2_y_color_cdf[ PALETTE_COLOR_CONTEXTS ] = { +static const u16 default_palette_size_2_y_color_cdf[PALETTE_COLOR_CONTEXTS] = { AOM_CDF(28710), AOM_CDF(16384), AOM_CDF(10553), @@ -725,7 +725,7 @@ static const u16 default_palette_size_2_y_color_cdf[ PALETTE_COLOR_CONTEXTS ] = AOM_CDF(31603) }; -static const u16 default_palette_size_3_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 ] = { +static const u16 default_palette_size_3_y_color_cdf[PALETTE_COLOR_CONTEXTS][2] = { { AOM_CDF(27877, 30490) }, { AOM_CDF(11532, 25697) }, { AOM_CDF(6544, 30234) }, @@ -733,7 +733,7 @@ static const u16 default_palette_size_3_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 { AOM_CDF(31915, 32385) } }; -static const u16 default_palette_size_4_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 ] = { +static const u16 default_palette_size_4_y_color_cdf[PALETTE_COLOR_CONTEXTS][3] = { { AOM_CDF(25572, 28046, 30045) }, { AOM_CDF(9478, 21590, 27256) }, { AOM_CDF(7248, 26837, 29824) }, @@ -741,7 +741,7 @@ static const u16 default_palette_size_4_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 { AOM_CDF(31400, 31825, 32250) } }; -static const u16 default_palette_size_5_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 ] = { +static const u16 default_palette_size_5_y_color_cdf[PALETTE_COLOR_CONTEXTS][4] = { { AOM_CDF(24779, 26955, 28576, 30282) }, { AOM_CDF(8669, 20364, 24073, 28093) }, { AOM_CDF(4255, 27565, 29377, 31067) }, @@ -749,7 +749,7 @@ static const u16 default_palette_size_5_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 { AOM_CDF(31646, 31893, 32147, 32426) } }; -static const u16 default_palette_size_6_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 ] = { +static const u16 default_palette_size_6_y_color_cdf[PALETTE_COLOR_CONTEXTS][5] = { { AOM_CDF(23132, 25407, 26970, 28435, 30073) }, { AOM_CDF(7443, 17242, 20717, 24762, 27982) }, { AOM_CDF(6300, 24862, 26944, 28784, 30671) }, @@ -757,7 +757,7 @@ static const u16 default_palette_size_6_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 { AOM_CDF(31270, 31550, 31808, 32059, 32353) } }; -static const u16 default_palette_size_7_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 ] = { +static const u16 default_palette_size_7_y_color_cdf[PALETTE_COLOR_CONTEXTS][6] = { { AOM_CDF(23105, 25199, 26464, 27684, 28931, 30318) }, { AOM_CDF(6950, 15447, 18952, 22681, 25567, 28563) }, { AOM_CDF(7560, 23474, 25490, 27203, 28921, 30708) }, @@ -765,7 +765,7 @@ static const u16 default_palette_size_7_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 { AOM_CDF(31198, 31451, 31670, 31882, 32123, 32391) } }; -static const u16 default_palette_size_8_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 ] = { +static const u16 default_palette_size_8_y_color_cdf[PALETTE_COLOR_CONTEXTS][7] = { { AOM_CDF(21689, 23883, 25163, 26352, 27506, 28827, 30195) }, { AOM_CDF(6892, 15385, 17840, 21606, 24287, 26753, 29204) }, { AOM_CDF(5651, 23182, 25042, 26518, 27982, 29392, 30900) }, @@ -773,7 +773,7 @@ static const u16 default_palette_size_8_y_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 { AOM_CDF(31028, 31270, 31504, 31705, 31927, 32153, 32392) } }; -static const u16 default_palette_size_2_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 1 ] = { +static const u16 default_palette_size_2_uv_color_cdf[PALETTE_COLOR_CONTEXTS][1] = { { AOM_CDF(29089) }, { AOM_CDF(16384) }, { AOM_CDF(8713) }, @@ -781,7 +781,7 @@ static const u16 default_palette_size_2_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(31610) } }; -static const u16 default_palette_size_3_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 2 ] = { +static const u16 default_palette_size_3_uv_color_cdf[PALETTE_COLOR_CONTEXTS][2] = { { AOM_CDF(25257, 29145) }, { AOM_CDF(12287, 27293) }, { AOM_CDF(7033, 27960) }, @@ -789,7 +789,7 @@ static const u16 default_palette_size_3_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30608, 31639) } }; -static const u16 default_palette_size_4_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 3 ] = { +static const u16 default_palette_size_4_uv_color_cdf[PALETTE_COLOR_CONTEXTS][3] = { { AOM_CDF(24210, 27175, 29903) }, { AOM_CDF(9888, 22386, 27214) }, { AOM_CDF(5901, 26053, 29293) }, @@ -797,7 +797,7 @@ static const u16 default_palette_size_4_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30459, 31136, 31926) } }; -static const u16 default_palette_size_5_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 4 ] = { +static const u16 default_palette_size_5_uv_color_cdf[PALETTE_COLOR_CONTEXTS][4] = { { AOM_CDF(22980, 25479, 27781, 29986) }, { AOM_CDF(8413, 21408, 24859, 28874) }, { AOM_CDF(2257, 29449, 30594, 31598) }, @@ -805,7 +805,7 @@ static const u16 default_palette_size_5_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(31844, 32044, 32281, 32518) } }; -static const u16 default_palette_size_6_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 5 ] = { +static const u16 default_palette_size_6_uv_color_cdf[PALETTE_COLOR_CONTEXTS][5] = { { AOM_CDF(22217, 24567, 26637, 28683, 30548) }, { AOM_CDF(7307, 16406, 19636, 24632, 28424) }, { AOM_CDF(4441, 25064, 26879, 28942, 30919) }, @@ -813,7 +813,7 @@ static const u16 default_palette_size_6_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30674, 30953, 31396, 31735, 32207) } }; -static const u16 default_palette_size_7_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 6 ] = { +static const u16 default_palette_size_7_uv_color_cdf[PALETTE_COLOR_CONTEXTS][6] = { { AOM_CDF(21239, 23168, 25044, 26962, 28705, 30506) }, { AOM_CDF(6545, 15012, 18004, 21817, 25503, 28701) }, { AOM_CDF(3448, 26295, 27437, 28704, 30126, 31442) }, @@ -821,7 +821,7 @@ static const u16 default_palette_size_7_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ { AOM_CDF(30988, 31204, 31479, 31734, 31983, 32325) } }; -static const u16 default_palette_size_8_uv_color_cdf[ PALETTE_COLOR_CONTEXTS ][ 7 ] = { +static const u16 default_palette_size_8_uv_color_cdf[PALETTE_COLOR_CONTEXTS][7] = { { AOM_CDF(21442, 23288, 24758, 26246, 27649, 28980, 30563) }, { AOM_CDF(5863, 14933, 17552, 20668, 23683, 26411, 29273) }, { AOM_CDF(3415, 25810, 26877, 27990, 29223, 30394, 31618) }, @@ -4023,7 +4023,7 @@ void avd_av1_default_coeff_probs(u32 base_qindex, void *ptr) void avd_av1_set_default_cdfs(void *ptr) //, { - struct avd_av1_cdfs *cdfs = ((struct avd_av1_cdfs*)ptr); + struct avd_av1_cdfs *cdfs = ((struct avd_av1_cdfs *)ptr); memcpy(cdfs->partition_cdf_0, default_partition_cdf_0, sizeof(cdfs->partition_cdf_0)); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 85f75303cf3b9c..f9fbb645b19527 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -212,7 +212,7 @@ struct avd_variant { unsigned int fw_caps_required; void (*configure_stream)(struct avd_dev *avd, dma_addr_t addr, u8 fifo_idx, u32 vp_slot); - const char* fw_name; + const char *fw_name; /* Older image tried when fw_name is not installed (legacy transport). */ const char *fw_name_fallback; unsigned char revision; /* the same as the device tree */ diff --git a/drivers/soc/apple/dockchannel.c b/drivers/soc/apple/dockchannel.c index 77dc01f8b43596..6ee1f9185eb709 100644 --- a/drivers/soc/apple/dockchannel.c +++ b/drivers/soc/apple/dockchannel.c @@ -122,7 +122,7 @@ int dockchannel_send(struct dockchannel *dockchannel, const void *buf, size_t co enable_irq(dockchannel->tx_irq); if (!wait_for_completion_timeout(&dockchannel->tx_comp, - msecs_to_jiffies(DOCKCHANNEL_TX_TIMEOUT_MS))) { + msecs_to_jiffies(DOCKCHANNEL_TX_TIMEOUT_MS))) { disable_irq(dockchannel->tx_irq); return -ETIMEDOUT; } @@ -164,7 +164,7 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) enable_irq(dockchannel->rx_irq); if (!wait_for_completion_timeout(&dockchannel->rx_comp, - msecs_to_jiffies(DOCKCHANNEL_RX_TIMEOUT_MS))) { + msecs_to_jiffies(DOCKCHANNEL_RX_TIMEOUT_MS))) { disable_irq(dockchannel->rx_irq); return -ETIMEDOUT; } diff --git a/drivers/soc/apple/mailbox-g17-test.h b/drivers/soc/apple/mailbox-g17-test.h index 10690d1d27bf78..c53e58c5060831 100644 --- a/drivers/soc/apple/mailbox-g17-test.h +++ b/drivers/soc/apple/mailbox-g17-test.h @@ -5,7 +5,7 @@ #include static void apple_g17_test_rx(struct apple_mbox *mbox, - struct apple_mbox_msg msg, void *cookie) + struct apple_mbox_msg msg, void *cookie) { unsigned int *count = cookie; diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 0cd4c6b9bd5ce7..1ca60f1b338a89 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -308,7 +308,7 @@ void sep_tk_set_blob_len(struct trusted_key_payload *p, unsigned int n); bool sep_keystore_only(void); bool sep_keystore_user_bags(void); int sep_complete_attach_register(struct device *dev, void *ctx, - int (*complete)(void *ctx)); + int (*complete)(void *ctx)); void sep_complete_attach_unregister(struct device *dev); void sep_diag_keystore_ended(void); void sep_diag_set_xart(bool writable); From 0f35583d84147297a7c4950209fa85b866024b24 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 17 Nov 2026 23:03:25 -0500 Subject: [PATCH 0380/1514] iommu: apple-dart: adopt T8132 internal display DARTs by default on 26.6.2 firmware On T8132 (M4) Macs running 26.6.2 firmware, the internal display DARTs that iBoot leaves live (the DCP's SID23 at 0x30a340000 and the scanout/PIODMA frontend at 0x30a300000) were adopted only when the command line set apple_dart.j713_dcp=1 and apple_dart.j713_display=1. No distribution sets them by default, so an installed 26.6.2 system came up on simpledrm: appledrm never bound the DCP, and the GPU never started. Gate internal display DART adoption directly on the internal DCP devicetree node instead of the board/OS-version helper or opt-in module parameters: require that the "dcp" node is available, compatible with "apple,t8132-dcp", and carries apple,firmware-version 26.6.2 via apple_dart_dcp_firmware(). That check stays strictly as a hardware-safety guard matching apple_dart_dcp_validate() until a loader-published internal DCP handoff property lands in Aura first and the kernel keys on it (tracked in https://github.com/aurora-silicon/linux/issues/2621): the retained-DART path assumes the inherited table and DMA layout of the 26.6.2 DCP firmware, so any other firmware (including 27.2, which is out of scope here) or disabled DCP leaves both internal display DARTs untouched (-ENODEV) without pinning their tables, reserving the SID23 window, or resetting the live DARTs. Remove the runtime-writable apple_dart.j713_dcp and apple_dart.j713_display module parameters, and update the APPLE_DART_J713_DCP Kconfig help text to reflect that it is no longer an opt-in bring-up profile. Those parameters originally guarded early READY bring-up with a requirement that userspace arm a watchdog before probing SID23, when an unvalidated probe risked resetting or corrupting a live locked display DART and wedging the SoC. That precondition no longer applies to the adopted path: - probe performs no DART register or page-table writes: preserve_display skips apple_dart_hw_reset() and apple_dart_drain_stale_exceptions(), and apple_dart_dcp_import() validates the locked T8110 registers (TCR, ENABLE_STREAMS, TTBR) and inherited root/leaf PTEs read-only against ADT reserved-memory bounds and excluded Linux RAM, refusing any mismatch or instability without mutating hardware; - probe refuses adoption (-EIO) if any display DART fault is already pending or masked, attaches the shared fault IRQ only once both display DARTs pass validation, quarantines the faulting DART's borrowed streams on fault without issuing FLUSH_UNLOCK, and quarantines both display peers before releasing the shared IRQ; - a refused DART leaves DCP probe refused (via the IOMMU-group check in drm/apple) so simpledrm keeps the panel safely. Adopting the display DARTs holds the display kexec blocker for the rest of the boot, as it already did with the parameters set; on T8132 Macs the managed radio DART also holds its own kexec blocker. Link: https://github.com/aurora-silicon/aura/issues/462 Link: https://github.com/aurora-silicon/linux/issues/2621 Signed-off-by: Erik Bourget --- drivers/iommu/Kconfig | 16 ++++++------ drivers/iommu/apple-dart.c | 51 ++++++++++++++------------------------ 2 files changed, 28 insertions(+), 39 deletions(-) diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig index 4233b253b06e2c..1cdbd93be4fb16 100644 --- a/drivers/iommu/Kconfig +++ b/drivers/iommu/Kconfig @@ -317,17 +317,19 @@ config APPLE_DART Say Y here if you are using an Apple SoC. config APPLE_DART_J713_DCP - bool "Retained J713 display DART support" + bool "Retained T8132 display DART support" depends on APPLE_DART=y && ARM64_16K_PAGES select MFD_SYSCON help - Adopt the qualified running J713 internal display DARTs. Their - firmware-visible allocations, page tables and noncoherent CPU - mappings remain pinned until platform reset. This limited bringup - profile requires the built-in ARM64 DMA implementation; its private - mapping/cache interfaces are not a modular DMA API. + Adopt the inherited T8132 (M4) display DARTs when the boot loader + hands over a qualified DCP firmware session. Their firmware-visible + allocations, page tables and noncoherent CPU mappings remain pinned + until platform reset, which requires the built-in ARM64 DMA + implementation (not APPLE_DART=m). - Leave this disabled for ordinary DART use, including APPLE_DART=m. + Say Y here to support native display and its dependent GPU bring-up + on T8132 Macs with a qualified DCP handoff (requires built-in + APPLE_DART and 16 KiB pages). config APPLE_DART_KUNIT_TEST bool "KUnit tests for Apple DART domains and commands" if !KUNIT_ALL_TESTS diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index d66e87da3f560c..65d7cafd98fceb 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -887,16 +887,6 @@ static struct platform_driver apple_dart_driver; static const struct iommu_ops apple_dart_iommu_ops; static bool apple_dart_fault_pending(struct apple_dart *dart); -/* READY bring-up only: userspace must arm its watchdog before probing SID23. */ -static bool apple_dart_dcp_enabled; - -module_param_named(j713_dcp, apple_dart_dcp_enabled, bool, 0600); -MODULE_PARM_DESC(j713_dcp, "Enable explicit J713 DCP DART probe after arming watchdog"); - -static bool apple_dart_frontend_enabled; -module_param_named(j713_display, apple_dart_frontend_enabled, bool, 0600); -MODULE_PARM_DESC(j713_display, "Enable explicit J713 display DART admission after arming watchdog"); - /* The machine's first compatible string, for log lines that name the board. */ static const char *apple_dart_board(void) { @@ -5365,11 +5355,12 @@ static int apple_dart_probe(struct platform_device *pdev) /* * The M4 internal display DARTs are live: DCP firmware (SID23) - * and the scanout/PIODMA frontend (SID0/SID16) keep using them. Leave - * both untouched until userspace, with its watchdog armed, opts in. + * and the scanout/PIODMA frontend (SID0/SID16) keep using them. + * Adopt them only when the internal DCP node carries the qualified + * firmware handoff; leave them untouched otherwise. */ res = platform_get_resource(pdev, IORESOURCE_MEM, 0); - j713_display = res && !tunneled && apple_t8132_firmware_path() && + j713_display = res && !tunneled && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL); /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ @@ -5385,25 +5376,21 @@ static int apple_dart_probe(struct platform_device *pdev) of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && res->start == 0x490000000ULL; - /* - * Off the qualified firmware nothing hands the internal display DARTs - * over, but the running DCP still uses them: never reset them. - */ - if (res && !tunneled && !apple_t8132_firmware_path() && - of_machine_is_compatible("apple,t8132") && - of_device_is_compatible(dev->of_node, "apple,t8132-dart") && - (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { - dev_info(dev, "Leaving inherited display DART untouched off the qualified firmware\n"); - return -ENODEV; - } - if (j713_display && !IS_ENABLED(CONFIG_APPLE_DART_J713_DCP)) - return dev_err_probe(dev, -EOPNOTSUPP, - "retained J713 display requires CONFIG_APPLE_DART_J713_DCP=y\n"); - if (j713_display && - ((res->start == 0x30a300000ULL && !READ_ONCE(apple_dart_frontend_enabled)) || - (res->start == 0x30a340000ULL && !READ_ONCE(apple_dart_dcp_enabled)))) { - dev_info(dev, "Leaving inherited display DART untouched; explicit guarded probe required\n"); - return -ENODEV; + if (j713_display) { + struct device_node *owner = of_find_node_by_path("dcp"); + bool handed_over = owner && + of_device_is_available(owner) && + of_device_is_compatible(owner, "apple,t8132-dcp") && + apple_dart_dcp_firmware(owner); + + of_node_put(owner); + if (!handed_over) { + dev_info(dev, "Leaving inherited display DART untouched\n"); + return -ENODEV; + } + if (!IS_ENABLED(CONFIG_APPLE_DART_J713_DCP)) + return dev_err_probe(dev, -EOPNOTSUPP, + "retained T8132 display requires CONFIG_APPLE_DART_J713_DCP=y\n"); } if (j713_dcpext) { /* Its block is powered only if the loader handed the DCP over. */ From daf16d935f5b41a85e7508391800d1774add7d9b Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Sun, 22 Nov 2026 17:00:03 +0100 Subject: [PATCH 0381/1514] arm64: dts: apple: t8142-j813: add CPU die backstop thermal zones The J813 (13-inch M5 MacBook Air) is fanless and runs the PMP's fast die-temperature effort loop (apple,fast-die-effort) as its primary thermal control, but still has no device-tree thermal zones: the macsmc_soc_die zone is tripless, so Linux has neither a passive power_allocator backstop nor a critical shutdown path if the PMP fails to hold the die. Measured on J813 with apple,fast-die-effort active (ambient 21.3 C): - Idle: 24.8-33 C. - 60 s E-cluster-only burn (6 cores at 2.96 GHz): 46.4 C, PPbb 2.57 W, PMP lane0 0. - 330 s all-core SHA256 soak (10 cores): PMP lane1 engages at 102.2 C and holds the hottest SMC die sensor (Tp04) at 102.3-102.5 C while keeping the E cluster at 2.96 GHz (lane0 0, PPbb 3.04 W) and tapering the P cluster from 4.46 to 3.88-4.02 GHz (PP0b 13.8 -> 10.1 W, combined CPU rail power 13.2 W at 330 s). Add #thermal-sensor-cells = <1> to &smc_hwmon on J813 and 18 per-sensor backstop zones covering the 4 E-cluster (Te04..Te0R, channels 4..7) and 14 P-cluster (Tp00..Tp1E, channels 8..21) CPU die sensors; the GPU and chassis/battery channels stay in hwmon without CPU zones because they have no CPU thermal limit in the ADT. The control (110 C) and critical (125 C, after three samples) trips come directly from the J813 ADT's PMP temp-sensor table, which gives every CPU die sensor a 110 C target and a 125 C maximum (sochot). Each zone throttles both clusters on the shared fanless die, weighted 3:1 in favour of E (capped at cooling state 5, 1152 MHz, more efficient per MHz than 300 MHz and above idle wake latency), with 13 W measured sustainable power, 1000 ms polling and a 20 s integral time constant. A 95 C switch-on (15 C gap -> k_po 887, k_pu 1774, k_i 88) keeps the proportional budget above the full-speed energy-model request (24.1 W) up to 103.6 C so cooling devices stay at state 0 throughout cold-start ramp and steady state under normal PMP operation (Tp04 <= 102.5 C; a 90 C switch-on trimmed P briefly on cold-start ramp at 102.3 C), while regulating smoothly without the oscillation observed with a 4-7 C gap. Scoped to t8142-j813.dts (t8142-j704.dtb and t8142-j815.dtb remain byte-identical): sustainable-power is a chassis measurement of the 13-inch J813, t8142-j815.dts uses apple,discover-temperatures (dynamic indices) on a larger 15-inch chassis whose sustained power is unmeasured, and t8142-j704.dts is fan-cooled and lacks opp-microwatt energy-model values. Signed-off-by: Bartosz Nitka --- arch/arm64/boot/dts/apple/t8142-j813.dts | 990 +++++++++++++++++++++++ 1 file changed, 990 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index 4c6cf3358ce3e0..c0ca420c87e36a 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -9,6 +9,7 @@ /dts-v1/; #include "t8142.dtsi" +#include / { compatible = "apple,j813", "apple,t8142", "apple,arm-platform"; @@ -293,3 +294,992 @@ &hpm1 { apple,sleep-ssps-rules; }; + +&smc_hwmon { + #thermal-sensor-cells = <1>; +}; + +/ { + /* + * Fanless: the CPUs are the only cooling devices, and both clusters + * share one die and one passive heat spreader. The PMP's fast + * die-temperature loop (apple,fast-die-effort) is the primary control: + * on J813, an all-core load holds the hottest SMC die sensor (Tp04) + * at 102.3-102.5 C while leaving the E cluster at 2.96 GHz and tapering + * the P cluster from 4.46 to 3.88-4.02 GHz as the chassis warms + * (13.2 W combined CPU rail power after 330 s). + * + * These per-sensor zones sit behind the PMP as a slow outer backstop + * and critical shutdown guard. The control (110 C) and critical + * (125 C, after three samples) trips come from the J813 ADT's PMP + * temp-sensor table, which gives every CPU die sensor a 110 C target + * and a 125 C maximum (sochot). A 95 C switch-on (15 C gap, 13 W + * measured sustainable power, 20 s integral time constant) keeps the + * power budget above the full-speed energy-model request (24.1 W) up to + * 103.6 C so cooling devices stay at state 0 throughout cold-start ramp + * and steady state under normal PMP operation (Tp04 <= 102.5 C), while + * regulating smoothly if PMP does not hold the die (k_po 887, k_pu 1774, + * k_i 88; a 4-7 C gap oscillated). The E cluster is weighted 3:1 over P + * and capped at state 5 (1152 MHz, more efficient per MHz than 300 MHz and + * above idle wake latency). + * + * Sensor indices count temperature-* children across hwmon-common + * (0: TH0x), hwmon-laptop (1-3: TB0T, TCHP, TW0P) and t8142-hwmon + * (4-7: Te04..Te0R, 8-21: Tp00..Tp1E). + */ + thermal-zones { + cpu-e0-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 4>; /* Te04 */ + sustainable-power = <13000>; + + trips { + cpu_e0_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e0_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e0_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e0_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e1-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 5>; /* Te08 */ + sustainable-power = <13000>; + + trips { + cpu_e1_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e1_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e1_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e1_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e2-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 6>; /* Te0C */ + sustainable-power = <13000>; + + trips { + cpu_e2_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e2_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e2_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e2_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-e3-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 7>; /* Te0R */ + sustainable-power = <13000>; + + trips { + cpu_e3_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_e3_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_e3_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_e3_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p0-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 8>; /* Tp00 */ + sustainable-power = <13000>; + + trips { + cpu_p0_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p0_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p0_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p0_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p1-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 9>; /* Tp04 */ + sustainable-power = <13000>; + + trips { + cpu_p1_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p1_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p1_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p1_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p2-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 10>; /* Tp0C */ + sustainable-power = <13000>; + + trips { + cpu_p2_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p2_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p2_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p2_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p3-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 11>; /* Tp0G */ + sustainable-power = <13000>; + + trips { + cpu_p3_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p3_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p3_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p3_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p4-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 12>; /* Tp0O */ + sustainable-power = <13000>; + + trips { + cpu_p4_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p4_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p4_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p4_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p5-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 13>; /* Tp0R */ + sustainable-power = <13000>; + + trips { + cpu_p5_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p5_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p5_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p5_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p6-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 14>; /* Tp0X */ + sustainable-power = <13000>; + + trips { + cpu_p6_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p6_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p6_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p6_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p7-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 15>; /* Tp0a */ + sustainable-power = <13000>; + + trips { + cpu_p7_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p7_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p7_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p7_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p8-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 16>; /* Tp0p */ + sustainable-power = <13000>; + + trips { + cpu_p8_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p8_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p8_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p8_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p9-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 17>; /* Tp0u */ + sustainable-power = <13000>; + + trips { + cpu_p9_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p9_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p9_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p9_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p10-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 18>; /* Tp0y */ + sustainable-power = <13000>; + + trips { + cpu_p10_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p10_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p10_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p10_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p11-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 19>; /* Tp12 */ + sustainable-power = <13000>; + + trips { + cpu_p11_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p11_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p11_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p11_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p12-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 20>; /* Tp16 */ + sustainable-power = <13000>; + + trips { + cpu_p12_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p12_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p12_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p12_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + + cpu-p13-thermal { + polling-delay-passive = <1000>; + polling-delay = <1000>; + integral-time-constant-ms = <20000>; + critical-samples = <3>; + thermal-sensors = <&smc_hwmon 21>; /* Tp1E */ + sustainable-power = <13000>; + + trips { + cpu_p13_switch_on: trip-switch-on { + temperature = <95000>; + hysteresis = <2000>; + type = "passive"; + }; + + cpu_p13_passive: trip-passive { + temperature = <110000>; + hysteresis = <2000>; + type = "passive"; + }; + + trip-critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&cpu_p13_passive>; + cooling-device = + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu7 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu8 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu9 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + contribution = <1024>; + }; + + map1 { + trip = <&cpu_p13_passive>; + cooling-device = + <&cpu0 THERMAL_NO_LIMIT 5>, + <&cpu1 THERMAL_NO_LIMIT 5>, + <&cpu2 THERMAL_NO_LIMIT 5>, + <&cpu3 THERMAL_NO_LIMIT 5>, + <&cpu4 THERMAL_NO_LIMIT 5>, + <&cpu5 THERMAL_NO_LIMIT 5>; + contribution = <3072>; + }; + }; + }; + }; +}; From 005860b86fa7b7cc0a9fa13c11dd1ff41671109a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 04:37:42 +1100 Subject: [PATCH 0382/1514] wifi: brcmfmac: refuse WoWLAN for a deeper sleep than s2idle On a bus whose only wake signal is the in-band MSI, a sleep deeper than suspend-to-idle cannot be woken by the radio, so brcmf_cfg80211_suspend() dropped the WoWLAN request by setting wowl to NULL and suspending without it. It then returned 0, which tells wiphy_suspend() that WoWLAN was configured: cfg80211 skips cfg80211_leave_all(), the event and work flush and the second suspend(NULL) call. Only station and P2P-client links were torn down by the driver, so an AP, P2P-GO or mesh interface stayed up in cfg80211 while the firmware powered down. Refuse WoWLAN the way the other refusal branches do: clear the scan status and return 1. cfg80211 then leaves every interface and calls the driver again with no WoWLAN, which runs the existing non-WoWLAN suspend. Also clear wowl_s2idle_only where brcmf_pcie_request_irq() resets wowl_wake, so a stale value can never outlive the IRQ setup that derives it. Update the host harness: with WoWLAN supported, a deeper target on an s2idle-only bus must return 1 with nothing configured and the scan status cleared, and the following suspend(NULL) must succeed with WoWLAN off on the bus. The previous wowl = NULL code fails that case. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/cfg80211.c | 10 +++++--- .../broadcom/brcm80211/brcmfmac/pcie.c | 1 + tools/asahi/brcmf-suspend-tests.py | 25 ++++++++++++------- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c index ac8e58be31690b..f152c873777c87 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c @@ -5265,15 +5265,17 @@ static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy, if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) brcmf_abort_scanning(cfg); - /* An in-band MSI cannot wake the host once the link goes down, so a - * deeper sleep than suspend-to-idle leaves the network, as without - * WoWLAN, instead of failing the whole system suspend. + /* An in-band MSI cannot wake the host once the link goes down, so + * refuse WoWLAN for a deeper sleep than suspend-to-idle instead of + * failing the whole system suspend. cfg80211 then leaves every + * interface (AP and P2P-GO included) and suspends again without it. */ if (wowl && cfg->pub->bus_if->wowl_s2idle_only && pm_suspend_target_state != PM_SUSPEND_TO_IDLE) { bphy_info_once(cfg->pub, "WoWLAN wakes only from suspend-to-idle here, sleeping without it\n"); - wowl = NULL; + cfg->scan_status = 0; + return 1; } if (wowl == NULL) { diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index b53a413d73d393..bcacceab2db308 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1286,6 +1286,7 @@ static int brcmf_pcie_request_irq(struct brcmf_pciedev_info *devinfo) brcmf_pcie_intr_disable(devinfo); bus->wowl_wake = pci_pme_capable(pdev, PCI_D3hot); + bus->wowl_s2idle_only = false; brcmf_dbg(PCIE, "Enter\n"); diff --git a/tools/asahi/brcmf-suspend-tests.py b/tools/asahi/brcmf-suspend-tests.py index 5d5d934946c33d..c66733209235b6 100644 --- a/tools/asahi/brcmf-suspend-tests.py +++ b/tools/asahi/brcmf-suspend-tests.py @@ -210,7 +210,8 @@ def function(source, name): static struct net_device *cfg_to_ndev(struct brcmf_cfg80211_info *c) {return c->pub->iflist[0]->ndev;} static struct brcmf_if *netdev_priv(struct net_device *n) {return &ifp[n-ndev];} static bool check_vif_up(struct brcmf_cfg80211_vif *v) {(void)v;return vif_up;} -static bool brcmf_feat_is_enabled(struct brcmf_if *i,int f) {(void)i;(void)f;return false;} +static unsigned feats; +static bool brcmf_feat_is_enabled(struct brcmf_if *i,int f) {(void)i;return feats&BIT(f);} static void brcmf_report_wowl_wakeind(struct wiphy *w,struct brcmf_if *i) {(void)w;(void)i;can_command();} static void brcmf_fil_iovar_int_set(struct brcmf_if *i,const char *s,int n) {(void)i;(void)s;(void)n;can_command();} static void brcmf_config_wowl_pattern(struct brcmf_if *i,const char *s,void *p,int n,void *q,int t) {(void)i;(void)s;(void)p;(void)n;(void)q;(void)t;can_command();} @@ -225,7 +226,8 @@ def function(source, name): static void brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();} static void brcmf_delay(int t) {(void)t;} static void brcmf_set_mpc(struct brcmf_if *i,int v) {(void)i;(void)v;can_command();} -static int brcmf_configure_wowl(struct brcmf_cfg80211_info *c,struct brcmf_if *i,struct cfg80211_wowlan *w) {(void)c;(void)i;(void)w;can_command();return 0;} +static unsigned wowl_configs; +static int brcmf_configure_wowl(struct brcmf_cfg80211_info *c,struct brcmf_if *i,struct cfg80211_wowlan *w) {(void)c;(void)i;(void)w;can_command();wowl_configs++;return 0;} static void brcmf_keepalive_start(struct brcmf_if *i,int n) {(void)i;(void)n;can_command();} ''' @@ -242,7 +244,7 @@ def function(source, name): devinfo.state=BRCMFMAC_PCIE_STATE_UP;devinfo.intr=devinfo.ready=devinfo.timer=true; country_gets=sets=bands=txflows=creates=cancels=removes=probes=0; failure=translation=d0_error=probe_error=wake_error=save_error=0;ack=true;retain=1;d3_informs=d0_informs=0; - pm_suspend_target_state=PM_SUSPEND_TO_IDLE; + pm_suspend_target_state=PM_SUSPEND_TO_IDLE;feats=0; } static void hint(const char *a) { struct regulatory_request r={.alpha2={a[0],a[1]}};brcmf_cfg80211_reg_notifier(&wiphy,&r); @@ -353,16 +355,21 @@ def function(source, name): assert(msgbuf.flowring_work.queued && msgbuf.txflow_work.queued); assert(!d0_informs && !removes && !probes);cases++; } - /* WoWLAN over an in-band MSI only wakes from s2idle: a deeper target sleeps - * as without WoWLAN (network left, WoWLAN off on the bus) instead of - * failing the suspend; s2idle, and a bus with a real wake line, keep it. */ + /* WoWLAN over an in-band MSI only wakes from s2idle: a deeper target + * refuses WoWLAN like the other refusals (scan state cleared, return 1, + * nothing configured) so cfg80211 leaves every interface and suspends + * again without it; s2idle, and a bus with a real wake line, keep it. */ for(int only=0;only<2;only++)for(int deep=0;deep<2;deep++) { static struct cfg80211_wowlan magic={.magic_pkt=true}; - reset();vif_up=true;wowl_offs=0;bus.wowl_s2idle_only=only; + reset();vif_up=true;wowl_offs=wowl_configs=0;bus.wowl_s2idle_only=only;feats=BIT(BRCMF_FEAT_WOWL); + cfg.scan_status=BIT(BRCMF_SCAN_STATUS_BUSY); pm_suspend_target_state=deep?PM_SUSPEND_ON:PM_SUSPEND_TO_IDLE; int ret=brcmf_cfg80211_suspend(&wiphy,&magic); - if(only&&deep)assert(!ret && cfg.suspended && wowl_offs==1); - else assert(ret==1 && !cfg.suspended && !wowl_offs); + assert(!cfg.scan_status); + if(only&&deep) { + assert(ret==1 && !cfg.suspended && !wowl_offs && !wowl_configs); + assert(!brcmf_cfg80211_suspend(&wiphy,NULL) && cfg.suspended && wowl_offs==1 && !wowl_configs); + } else assert(!ret && cfg.suspended && !wowl_offs && wowl_configs==1); cases++; } /* Outside s2idle (hibernation) Apple firmware still gets the D3 handshake. */ From 9713998860477fa7a9a8078be4abf279d75508ff Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 23:17:45 -0500 Subject: [PATCH 0383/1514] dt-bindings: iommu: apple,dart: add apple,sid16-page The T8132 radio DART's SID16 keeps a static bypass for the whole uptime, but only needs to reach one page. Let the DT name that page so the OS can translate the stream through a table that maps only it. Signed-off-by: Erik Bourget --- .../devicetree/bindings/iommu/apple,dart.yaml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index 6e7fdf9af5fdd6..8ff29b76c713ba 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -70,13 +70,24 @@ properties: normal streams and their exact-RID entries may be adopted by the OS. Other streams and RID entries remain inherited. The documented static SID16 bypass role may be initialized only from a disabled stream with - no valid root; an existing bypass remains unchanged. PIODMA and other + no valid root; an existing bypass remains unless apple,sid16-page + narrows it to one page. PIODMA and other reserved roles are not modified. This does not authorize a controller reset or takeover of active page tables. Both the radio DART and PCI host describe the same two ordinary streams. Error reporting must already be unmasked at admission; the OS preserves the inherited global error-mask policy rather than changing it for these streams. + apple,sid16-page: + $ref: /schemas/types.yaml#/definitions/uint64 + description: > + Physical address of the one 16 KiB page the radio's static SID16 + stream needs to reach. When present, the OS translates SID16 through a + table that maps only this page, identity, instead of keeping its + bypass. It applies only with apple,managed-sids, when the DART is + admitted as the managed radio DART. It must be 16 KiB aligned and below + 2^36. + reg: minItems: 1 items: @@ -328,6 +339,7 @@ required: dependencies: apple,gapf-slice-values: [ 'apple,gapf-slice' ] + apple,sid16-page: [ 'apple,managed-sids' ] allOf: - if: From a4c4da52403e390161354524ef9a3a515f73c1d2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:40:58 +1100 Subject: [PATCH 0384/1514] soc: apple: clpc: link without the SMC driver APPLE_CLPC treats the SMC as optional ("depends on MFD_MACSMC || !MFD_MACSMC"), but the PHPC package-power read and the zETM High Power mode record call apple_smc_read()/apple_smc_write(), which have no stubs. A kernel with APPLE_CLPC=y and MFD_MACSMC unset fails to link: clpc.c: undefined reference to `apple_smc_write' clpc.c: undefined reference to `apple_smc_read' That includes the driver's own clpc.kunitconfig, which does not enable the SMC. Test IS_ENABLED(CONFIG_MFD_MACSMC) before looking the SMC up, so both paths return -ENODEV and the calls drop out at compile time. Probe does not take the apple,smc phandle either in such a kernel, so High Power mode stays off and the performance profile switches like any other (without that, a machine with apple,high-power-mode would fail every write of "performance" with -ENODEV). The low-power profile then has only its frequency ceiling, as it already does when the node has no apple,smc phandle. Kernels with the SMC driver are unchanged. Fixes: f04da7cf87ff ("soc: apple: clpc: J714s: tell the SMC about High Power mode") Fixes: bdd3bc3f17b4 ("soc: apple: clpc: T6050 platform profiles after macOS's power modes") Signed-off-by: Ryan Murray --- drivers/soc/apple/clpc.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index c3ca54ba859db4..f5d5df46e31c6f 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -796,7 +796,11 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, return best; } -/* The SMC of the apple,smc phandle, once its driver is bound; NULL before. */ +/* + * The SMC of the apple,smc phandle, once its driver is bound; NULL before. + * Callers test IS_ENABLED(CONFIG_MFD_MACSMC) first, so a kernel without the + * SMC driver links without the apple_smc_*() calls. + */ static struct apple_smc *apple_clpc_smc(struct apple_clpc *clpc) { struct platform_device *pdev; @@ -819,7 +823,7 @@ static int apple_clpc_read_power(struct apple_clpc *clpc) u64 mw; u32 f; - if (!apple_clpc_smc(clpc)) + if (!IS_ENABLED(CONFIG_MFD_MACSMC) || !apple_clpc_smc(clpc)) return -ENODEV; ret = apple_smc_read_u32(clpc->smc, SMC_KEY(PHPC), &f); if (ret) @@ -1304,7 +1308,7 @@ static int apple_clpc_send_high_power(struct apple_clpc *clpc, bool on) u8 rec[APPLE_CLPC_ZETM_SIZE] = { APPLE_CLPC_ZETM_TYPE, APPLE_CLPC_ZETM_VERSION }; int ret; - if (!apple_clpc_smc(clpc)) + if (!IS_ENABLED(CONFIG_MFD_MACSMC) || !apple_clpc_smc(clpc)) return -ENODEV; rec[2] = ++clpc->high_power_seq; put_unaligned_le32(on ? APPLE_CLPC_FLOAT_ONE : 0, rec + APPLE_CLPC_ZETM_HIGH_POWER); @@ -1533,8 +1537,13 @@ static int apple_clpc_probe(struct platform_device *pdev) if (!high_power && clpc->hw->high_power_machine) high_power = of_machine_is_compatible(clpc->hw->high_power_machine); if ((clpc->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { - /* The SMC is optional: without it the low-power profile has only its ceiling. */ - clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); + /* + * The SMC is optional: without it (no apple,smc phandle, or a + * kernel without the SMC driver) the low-power profile has only + * its ceiling and there is no High Power mode. + */ + if (IS_ENABLED(CONFIG_MFD_MACSMC)) + clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); clpc->high_power = clpc->smc_np && high_power; } /* High Power mode alone needs the SMC; without it there is no profile. */ From 69bc2c322912755ce6d54dbd3437fe702cbba139 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 22:55:18 +1100 Subject: [PATCH 0385/1514] tools/asahi: clpc-high-power test: model the SMC driver being built apple_clpc_send_high_power() now tests IS_ENABLED(CONFIG_MFD_MACSMC) before it talks to the SMC. The host test compiles the extracted function against its own prelude, which had neither macro, so it stopped building. Define both, with the SMC driver built in, so the test keeps exercising the SMC path it checks. Signed-off-by: Ryan Murray --- tools/asahi/clpc-high-power-cleanup-tests.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index 709aed09ecf4f8..c664991024b57d 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -41,6 +41,9 @@ def function(source, name): #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define SMC_KEY(x) 0x7a45544d +/* Model a kernel built with the SMC driver, so the SMC path runs. */ +#define CONFIG_MFD_MACSMC 1 +#define IS_ENABLED(option) (option) #define dev_warn(...) (warnings++) enum platform_profile_option { PLATFORM_PROFILE_BALANCED, PLATFORM_PROFILE_LOW_POWER, PLATFORM_PROFILE_PERFORMANCE }; From dfa0142eab1bfc61ec134878fefc1639a531a499 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 04:59:56 +1100 Subject: [PATCH 0386/1514] phy: apple: t6050: use NULL and kernel style in the step tables The T6050 USB and CIO step tables fill the `name` pointer of every unnamed row with a plain 0. sparse reports "Using plain integer as NULL pointer" for each of them (it stops at 99 on apple_t6050_usb_phy.h and hides the rest behind its cap), which buries any real warning in drivers/phy/apple. apple_t6050_usb_phy.h says it was produced by generate-phy.py. That generator is not in this tree and did not come with the T6050 source, so fix the checked-in tables directly: - 177 rows in apple_t6050_usb_phy.h and 101 in apple_t6050_cio_phy.h (35 table rows, 66 macro rows) go from `0 }` to `NULL }`. Mapping NULL back to 0 gives the old files byte for byte. - Both headers were indented with 4 spaces. Use tabs, align continuation lines to their open parenthesis and put the compact `case X: stmt; break;` lines of apple_t6050_usb_phy_run() on separate lines. `git diff -w` shows only the NULL change and the case split. t6050-combo-join-tests.py parses these tables, so it now accepts NULL as an empty name as well as 0. No code change: drivers/phy/apple objects are identical in .text disassembly and function sizes for both the fleet config and an arm64 allmodconfig build. sparse + W=1 warnings in drivers/phy/apple go from 118 to 1 (fleet) and 103 to 1 (allmodconfig); the one left is the arm64 vDSO's __kernel_getrandom, outside this directory. checkpatch --strict on both files: 0 errors apart from the known COMPLEX_MACRO false positive on initializer-list macros. Signed-off-by: Ryan Murray --- .../phy/apple/usb-t6050/apple_t6050_cio_phy.h | 266 ++++----- .../phy/apple/usb-t6050/apple_t6050_usb_phy.h | 515 +++++++++--------- tools/asahi/t6050-combo-join-tests.py | 5 +- 3 files changed, 398 insertions(+), 388 deletions(-) diff --git a/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h b/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h index 4af28f8c2ccff7..0b529afca00e30 100644 --- a/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h +++ b/drivers/phy/apple/usb-t6050/apple_t6050_cio_phy.h @@ -14,176 +14,176 @@ /* The power-up and reset release, identical to the USB recipes. */ #define APPLE_T6050_CIO_POWERUP \ - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, \ - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 } + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, \ + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL } /* The common tunables, then the CIO set and the CIO80 set. An absent CIO80 * tunable is skipped. */ #define APPLE_T6050_CIO_TUNABLES \ - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, \ - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, \ - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, \ - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, \ - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, \ - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, \ - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, \ - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, \ - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, \ - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, \ - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, \ - { T6050_TUNABLE, 3, 0x0, 0x0, 0x0, 0, "tunable_UC_REGS_CIO_DFLT" }, \ - { T6050_TUNABLE, 16, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_TOP_CIO_DFLT" }, \ - { T6050_TUNABLE, 25, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_TOP_CIO_DFLT" }, \ - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_CIO_DFLT" }, \ - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_CIO_DFLT" } + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, \ + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, \ + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, \ + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, \ + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, \ + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, \ + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, \ + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, \ + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, \ + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, \ + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, \ + { T6050_TUNABLE, 3, 0x0, 0x0, 0x0, 0, "tunable_UC_REGS_CIO_DFLT" }, \ + { T6050_TUNABLE, 16, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_TOP_CIO_DFLT" }, \ + { T6050_TUNABLE, 25, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_TOP_CIO_DFLT" }, \ + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_CIO_DFLT" }, \ + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_CIO_DFLT" } /* The crossbar: clear the lane selects, set the orientation bit (+0x78) * and select CIO. */ #define APPLE_T6050_CIO_XBAR(reverse) \ - { T6050_MASK, 2, 0x6c, 0xfc, 0x0, 0, 0 }, \ - { T6050_MASK, 2, 0x78, 0x1f, (reverse), 0, 0 }, \ - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 } + { T6050_MASK, 2, 0x6c, 0xfc, 0x0, 0, NULL }, \ + { T6050_MASK, 2, 0x78, 0x1f, (reverse), 0, NULL }, \ + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL } /* Power a lane's receiver up, then release its transmitter overrides. */ #define APPLE_T6050_CIO_LANE(l) \ - { T6050_MASK, 2, 0x10, 0x10 << (l), 0x10 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x40 << (l), 0x40 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x1 << (l), 0x1 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x4 << (l), 0x4 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x400 << (l), 0x400 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x1000 << (l), 0x1000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x40 << (l), 0x40 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x100 << (l), 0x100 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x10000 << (l), 0x10000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x40 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x4 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x400 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0x10, 0x10 << (l), 0x10 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x40 << (l), 0x40 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x1 << (l), 0x1 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x4 << (l), 0x4 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x400 << (l), 0x400 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x1000 << (l), 0x1000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x40 << (l), 0x40 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x100 << (l), 0x100 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x10000 << (l), 0x10000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x40 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x4 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x400 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* The sleep-control release: the common block's overrides, then both lanes. */ #define APPLE_T6050_CIO_SLPCTRL \ - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - APPLE_T6050_CIO_LANE(0), \ - APPLE_T6050_CIO_LANE(1) + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + APPLE_T6050_CIO_LANE(0), \ + APPLE_T6050_CIO_LANE(1) /* Start the PHY firmware, wait for UC_TNBL_DONE and * deassert the ACIOPHY reset. No PIPE BIST and no ATCPHY_CFG +0x8 write. */ #define APPLE_T6050_CIO_START \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, \ - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, \ - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 } + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, \ + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, \ + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL } static const struct apple_t6050_usb_step apple_t6050_cio_init_normal[] = { - APPLE_T6050_CIO_POWERUP, - APPLE_T6050_CIO_TUNABLES, - APPLE_T6050_CIO_XBAR(0x0), - APPLE_T6050_CIO_SLPCTRL, - APPLE_T6050_CIO_START, + APPLE_T6050_CIO_POWERUP, + APPLE_T6050_CIO_TUNABLES, + APPLE_T6050_CIO_XBAR(0x0), + APPLE_T6050_CIO_SLPCTRL, + APPLE_T6050_CIO_START, }; static const struct apple_t6050_usb_step apple_t6050_cio_init_reverse[] = { - APPLE_T6050_CIO_POWERUP, - APPLE_T6050_CIO_TUNABLES, - APPLE_T6050_CIO_XBAR(0x1), - APPLE_T6050_CIO_SLPCTRL, - APPLE_T6050_CIO_START, + APPLE_T6050_CIO_POWERUP, + APPLE_T6050_CIO_TUNABLES, + APPLE_T6050_CIO_XBAR(0x1), + APPLE_T6050_CIO_SLPCTRL, + APPLE_T6050_CIO_START, }; /* Power a lane's transmitter down. */ #define APPLE_T6050_CIO_TX_DOWN(l) \ - { T6050_MASK, 2, 0x120, 0x100 << (l), 0x100 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x1 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x120, 0x10 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0x120, 0x100 << (l), 0x100 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x1 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x120, 0x10 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* Power a lane's receiver down; CIO powers the receivers down, USB does not. */ #define APPLE_T6050_CIO_RX_DOWN(l) \ - { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x4000 << (l), 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x40 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0xc, 0x400 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x1 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, \ - { T6050_MASK, 2, 0x10, 0x10 << (l), 0x0, 0, 0 }, \ - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 } + { T6050_MASK, 2, 0xc, 0x4000 << (l), 0x4000 << (l), 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x40 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0xc, 0x400 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x1 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, \ + { T6050_MASK, 2, 0x10, 0x10 << (l), 0x0, 0, NULL }, \ + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL } /* The shutdown: both lanes down without the PIPE BIST, the firmware * power-down, then the USB recipes' sleep, clamp and reset sequence. */ static const struct apple_t6050_usb_step apple_t6050_cio_shutdown[] = { - APPLE_T6050_CIO_TX_DOWN(0), - APPLE_T6050_CIO_TX_DOWN(1), - { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - APPLE_T6050_CIO_RX_DOWN(0), - APPLE_T6050_CIO_RX_DOWN(1), - { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, + APPLE_T6050_CIO_TX_DOWN(0), + APPLE_T6050_CIO_TX_DOWN(1), + { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + APPLE_T6050_CIO_RX_DOWN(0), + APPLE_T6050_CIO_RX_DOWN(1), + { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, }; #endif diff --git a/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h b/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h index 5c96da7d82c2d2..e0e7102831191c 100644 --- a/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h +++ b/drivers/phy/apple/usb-t6050/apple_t6050_usb_phy.h @@ -4,263 +4,272 @@ #define APPLE_T6050_USB_PHY_H #include "apple_t6050_usb3_bist.h" struct apple_t6050_usb_platform { - const struct apple_t6050_usb_io *io; - void *context; - int (*wrapper_power)(void *, unsigned int); - int (*firmware)(void *, unsigned int); - int (*tunable)(void *, unsigned int, const char *); - void (*pause_ns)(void *, unsigned int); + const struct apple_t6050_usb_io *io; + void *context; + int (*wrapper_power)(void *, unsigned int); + int (*firmware)(void *, unsigned int); + int (*tunable)(void *, unsigned int, const char *); + void (*pause_ns)(void *, unsigned int); }; enum apple_t6050_usb_op { T6050_MASK, T6050_POLL, T6050_DELAY, - T6050_POWER, T6050_FIRMWARE, T6050_TUNABLE }; + T6050_POWER, T6050_FIRMWARE, T6050_TUNABLE }; struct apple_t6050_usb_step { - unsigned int op, bank, offset, mask, value, timeout; - const char *name; + unsigned int op, bank, offset, mask, value, timeout; + const char *name; }; static const struct apple_t6050_usb_step apple_t6050_usb2_host[] = { - { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_DFLT" }, - { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_HOST" }, - { T6050_DELAY, 0, 0x0, 0x0, 0x2710, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x1, 0x0, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x2, 0x0, 0, 0 }, - { T6050_MASK, 1, 0x0, 0x9, 0x9, 0, 0 }, - { T6050_MASK, 0, 0x4, 0x4, 0x4, 0, 0 }, - { T6050_MASK, 0, 0x1c, 0x20000000, 0x0, 0, 0 }, - { T6050_MASK, 0, 0x1c, 0x40000000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1e, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_MASK, 0, 0x0, 0x7, 0x2, 0, 0 }, + { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_DFLT" }, + { T6050_TUNABLE, 0, 0x0, 0x0, 0x0, 0, "tunable_USB2PHY_HOST" }, + { T6050_DELAY, 0, 0x0, 0x0, 0x2710, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x1, 0x0, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x2, 0x0, 0, NULL }, + { T6050_MASK, 1, 0x0, 0x9, 0x9, 0, NULL }, + { T6050_MASK, 0, 0x4, 0x4, 0x4, 0, NULL }, + { T6050_MASK, 0, 0x1c, 0x20000000, 0x0, 0, NULL }, + { T6050_MASK, 0, 0x1c, 0x40000000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1e, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_MASK, 0, 0x0, 0x7, 0x2, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_init_normal[] = { - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 }, - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, - { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, 0 }, - { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, 0 }, - { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, 0 }, - { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, 0 }, - { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, 0 }, - { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_MASK, 2, 0x6c, 0x28000fc, 0x44, 0, 0 }, - { T6050_MASK, 2, 0x78, 0x1ffff, 0x110, 0, 0 }, - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x40, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x100, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x40, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x400, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 }, + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL }, + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, + { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, NULL }, + { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, NULL }, + { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, NULL }, + { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, NULL }, + { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, NULL }, + { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_MASK, 2, 0x6c, 0x28000fc, 0x44, 0, NULL }, + { T6050_MASK, 2, 0x78, 0x1ffff, 0x110, 0, NULL }, + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x40, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x100, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x40, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x400, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_init_reverse[] = { - { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, 0 }, - { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, - { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, - { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, - { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, - { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, - { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, - { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, - { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, - { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, 0 }, - { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, 0 }, - { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, 0 }, - { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, 0 }, - { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, 0 }, - { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, 0 }, - { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, - { T6050_MASK, 2, 0x6c, 0x14000fc, 0x28, 0, 0 }, - { T6050_MASK, 2, 0x78, 0x1ffff, 0x111, 0, 0 }, - { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x10, 0x80, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x20000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x200, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x2000, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x80, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x800, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x2, 0x2, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, 0 }, - { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, 0 }, + { T6050_MASK, 39, 0x0, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x1, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x2, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x0, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x8, 0, NULL }, + { T6050_TUNABLE, 41, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF" }, + { T6050_TUNABLE, 40, 0x0, 0x0, 0x0, 0, "tunable_ATC_FABRIC" }, + { T6050_TUNABLE, 43, 0x0, 0x0, 0x0, 0, "tunable_ATC_COMMON_CFG" }, + { T6050_TUNABLE, 42, 0x0, 0x0, 0x0, 0, "tunable_ATC0AXI2AF_LIOA" }, + { T6050_TUNABLE, 20, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 29, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_CFG_TX_OF_RXCLK" }, + { T6050_TUNABLE, 18, 0x0, 0x0, 0x0, 0, "tunable_LN0_RX_EQ_DFLT" }, + { T6050_TUNABLE, 27, 0x0, 0x0, 0x0, 0, "tunable_LN1_RX_EQ_DFLT" }, + { T6050_TUNABLE, 5, 0x0, 0x0, 0x0, 0, "tunable_AUS40CMN_SHM" }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_TUNABLE, 10, 0x0, 0x0, 0x0, 0, "tunable_CIO4PLL_CORE" }, + { T6050_MASK, 4, 0x0, 0x3f0, 0x1c0, 0, NULL }, + { T6050_MASK, 4, 0x18, 0xf000, 0x3000, 0, NULL }, + { T6050_MASK, 9, 0x88, 0xff, 0x27, 0, NULL }, + { T6050_MASK, 33, 0x4, 0x38, 0x8, 0, NULL }, + { T6050_MASK, 10, 0xdc, 0x3ff0, 0x1760, 0, NULL }, + { T6050_MASK, 21, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 30, 0xcc, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 20, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_MASK, 29, 0x90, 0x1f80000, 0x380000, 0, NULL }, + { T6050_TUNABLE, 8, 0x0, 0x0, 0x0, 0, "tunable_AUSPLL_CORE" }, + { T6050_MASK, 2, 0x6c, 0x14000fc, 0x28, 0, NULL }, + { T6050_MASK, 2, 0x78, 0x1ffff, 0x111, 0, NULL }, + { T6050_MASK, 2, 0x6c, 0x3, 0x2, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2a, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x10, 0x80, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x20000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x200, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x2000, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x80, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x800, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x2, 0x2, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_MASK, 38, 0x40, 0x1, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xa, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1388, 0, NULL }, + { T6050_POLL, 2, 0x260, 0x400, 0x400, 1000000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x64, 0, NULL }, }; static const struct apple_t6050_usb_step apple_t6050_usb3_shutdown[] = { - { T6050_MASK, 35, 0x4, 0x1, 0x1, 0, 0 }, - { T6050_MASK, 35, 0x10c, 0x100000, 0x0, 0, 0 }, - { T6050_MASK, 35, 0x110, 0x60, 0x20, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, 0 }, - { T6050_MASK, 35, 0x10c, 0x1e000000, 0x4000000, 0, 0 }, - { T6050_MASK, 35, 0x110, 0x600, 0x200, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, 0 }, - { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, 0 }, - { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, 0 }, - { T6050_MASK, 35, 0x4, 0x1, 0x0, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x100, 0x100, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x200, 0x200, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0x120, 0x20, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, 0 }, - { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, 0 }, - { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, 0 }, - { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, - { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, 0 }, - { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, 0 }, + { T6050_MASK, 35, 0x4, 0x1, 0x1, 0, NULL }, + { T6050_MASK, 35, 0x10c, 0x100000, 0x0, 0, NULL }, + { T6050_MASK, 35, 0x110, 0x60, 0x20, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, NULL }, + { T6050_MASK, 35, 0x10c, 0x1e000000, 0x4000000, 0, NULL }, + { T6050_MASK, 35, 0x110, 0x600, 0x200, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x8, 0, NULL }, + { T6050_MASK, 35, 0x4, 0x8, 0x0, 0, NULL }, + { T6050_POLL, 35, 0x104, 0x100, 0x100, 1000000, NULL }, + { T6050_MASK, 35, 0x4, 0x1, 0x0, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x100, 0x100, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x200, 0x200, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0x120, 0x20, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 5, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x10, 0x10, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 2, 0xc, 0x4, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0xc8, 0, NULL }, + { T6050_FIRMWARE, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_POWER, 0, 0x0, 0x0, 0x0, 0, NULL }, + { T6050_MASK, 39, 0x2c, 0x1, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x100, 0x100, 1000, NULL }, + { T6050_MASK, 39, 0x0, 0x10, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x8, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x4, 0x4, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x2, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x2, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x0, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_POLL, 39, 0x4, 0x1, 0x0, 1000, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, + { T6050_MASK, 39, 0x8, 0x1, 0x0, 0, NULL }, + { T6050_DELAY, 0, 0x0, 0x0, 0x1, 0, NULL }, }; static inline int apple_t6050_usb_phy_run(const struct apple_t6050_usb_platform *p, - const struct apple_t6050_usb_step *steps, unsigned int count) + const struct apple_t6050_usb_step *steps, unsigned int count) { - if (!p || !p->io || !p->io->read || !p->io->write || - !p->io->poll || !p->io->delay || !p->wrapper_power || - !p->firmware || !p->tunable) - return -1; - for (unsigned int i = 0; i < count; i++) { - const struct apple_t6050_usb_step *s = &steps[i]; - int ret = 0; - switch (s->op) { - case T6050_MASK: - apple_t6050_usb_mask(p->io, s->bank, s->offset, s->mask, s->value); - break; - case T6050_POLL: - ret = p->io->poll(p->io->context, s->bank, s->offset, - s->mask, s->value, s->timeout); - break; - case T6050_DELAY: p->io->delay(p->io->context, s->value); break; - case T6050_POWER: ret = p->wrapper_power(p->context, s->value); break; - case T6050_FIRMWARE: ret = p->firmware(p->context, s->value); break; - case T6050_TUNABLE: ret = p->tunable(p->context, s->bank, s->name); break; - default: return -1; - } - if (ret) - return ret; - } - return 0; + if (!p || !p->io || !p->io->read || !p->io->write || + !p->io->poll || !p->io->delay || !p->wrapper_power || + !p->firmware || !p->tunable) + return -1; + for (unsigned int i = 0; i < count; i++) { + const struct apple_t6050_usb_step *s = &steps[i]; + int ret = 0; + switch (s->op) { + case T6050_MASK: + apple_t6050_usb_mask(p->io, s->bank, s->offset, s->mask, s->value); + break; + case T6050_POLL: + ret = p->io->poll(p->io->context, s->bank, s->offset, + s->mask, s->value, s->timeout); + break; + case T6050_DELAY: + p->io->delay(p->io->context, s->value); + break; + case T6050_POWER: + ret = p->wrapper_power(p->context, s->value); + break; + case T6050_FIRMWARE: + ret = p->firmware(p->context, s->value); + break; + case T6050_TUNABLE: + ret = p->tunable(p->context, s->bank, s->name); + break; + default: + return -1; + } + if (ret) + return ret; + } + return 0; } #define APPLE_T6050_USB_RUN(p, steps) \ - apple_t6050_usb_phy_run((p), (steps), sizeof(steps) / sizeof((steps)[0])) + apple_t6050_usb_phy_run((p), (steps), sizeof(steps) / sizeof((steps)[0])) /* Native shutdown first asserts PORT_RESET only if it was not already set. * The 5 ms wait belongs to that transition, not every redundant stop call. @@ -268,19 +277,19 @@ apple_t6050_usb_phy_run(const struct apple_t6050_usb_platform *p, */ static inline int apple_t6050_usb2_stop(const struct apple_t6050_usb_platform *p) { - if (!p || !p->io || !p->io->read || !p->io->write || - !p->io->delay || !p->pause_ns) - return -1; - if (!(p->io->read(p->io->context, 0, 4) & 2)) { - apple_t6050_usb_mask(p->io, 0, 4, 2, 2); - p->io->delay(p->io->context, 5000); - } - apple_t6050_usb_mask(p->io, 0, 0, 7, 4); - apple_t6050_usb_mask(p->io, 0, 4, 8, 8); - apple_t6050_usb_mask(p->io, 0, 4, 1, 1); - apple_t6050_usb_mask(p->io, 0, 0x1c, 0x20000000, 0x20000000); - apple_t6050_usb_mask(p->io, 0, 0x1c, 0x40000000, 0x40000000); - p->pause_ns(p->context, 500); - return 0; + if (!p || !p->io || !p->io->read || !p->io->write || + !p->io->delay || !p->pause_ns) + return -1; + if (!(p->io->read(p->io->context, 0, 4) & 2)) { + apple_t6050_usb_mask(p->io, 0, 4, 2, 2); + p->io->delay(p->io->context, 5000); + } + apple_t6050_usb_mask(p->io, 0, 0, 7, 4); + apple_t6050_usb_mask(p->io, 0, 4, 8, 8); + apple_t6050_usb_mask(p->io, 0, 4, 1, 1); + apple_t6050_usb_mask(p->io, 0, 0x1c, 0x20000000, 0x20000000); + apple_t6050_usb_mask(p->io, 0, 0x1c, 0x40000000, 0x40000000); + p->pause_ns(p->context, 500); + return 0; } #endif diff --git a/tools/asahi/t6050-combo-join-tests.py b/tools/asahi/t6050-combo-join-tests.py index c57fe3dfaaaa11..e10a951fd2449e 100755 --- a/tools/asahi/t6050-combo-join-tests.py +++ b/tools/asahi/t6050-combo-join-tests.py @@ -16,13 +16,14 @@ ('apple_t6050_usb3_init_reverse', 'mf_reverse_init'), ('apple_t6050_usb3_shutdown', 'mf_poweroff')) ROW = re.compile(r'\{\s*(T6050_\w+|ATC_\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)\s*,\s*(\w+)' - r'\s*,\s*(\w+)(?:\s*,\s*("[^"]*"|0))?\s*\}') + r'\s*,\s*(\w+)(?:\s*,\s*("[^"]*"|0|NULL))?\s*\}') def table(text, name): m = re.search(r'\b' + re.escape(name) + r'\[\]\s*=\s*\{(.*?)\n\};', text, re.S) assert m, name - return [(r[0].split('_', 1)[1], *(int(x, 0) for x in r[1:6]), (r[6] or '').strip('"')) + return [(r[0].split('_', 1)[1], *(int(x, 0) for x in r[1:6]), + '' if r[6] in ('0', 'NULL') else r[6].strip('"')) for r in ROW.findall(m.group(1))] From 5ec8652d5852b4032487037036997812445473bd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:07:30 +1100 Subject: [PATCH 0387/1514] media: apple: isp: give the sensor sysfs test a page-sized buffer isp_test_sensor_sysfs calls sensor_show() with a 32-byte stack buffer. sensor_show() ends in sysfs_emit(), which WARNs ("invalid sysfs_emit") and returns 0 unless the buffer is page-aligned, as the one sysfs hands to a show() callback always is. The test therefore fails on every run (apple-isp-hw 1/2) and leaves a WARNING splat in the KUnit log. Allocate a zeroed PAGE_SIZE buffer with kunit_kzalloc() instead. kmalloc returns naturally aligned memory for power-of-two sizes, so the buffer is page-aligned. The driver is unchanged. Tested with kunit.py (arm64, 16K pages) 'apple-isp*': 52/53 before, 53/53 after, no WARNING. Fixes: 73a7a8513056 ("media: apple: isp: expose detected camera sensor name in sysfs") Signed-off-by: Ryan Murray --- drivers/media/platform/apple/isp/isp-drv-test.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/isp/isp-drv-test.c b/drivers/media/platform/apple/isp/isp-drv-test.c index 7ec962b8100341..ff4398ea654d60 100644 --- a/drivers/media/platform/apple/isp/isp-drv-test.c +++ b/drivers/media/platform/apple/isp/isp-drv-test.c @@ -220,9 +220,11 @@ static void isp_test_sensor_sysfs(struct kunit *test) { struct device *dev = kunit_device_register(test, "apple-isp-sensor-test"); struct apple_isp *isp; - char buf[32]; + /* sysfs_emit() wants the page-aligned buffer sysfs hands to show(). */ + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, buf); KUNIT_EXPECT_EQ(test, sensor_show(dev, &dev_attr_sensor, buf), -ENODATA); isp = kunit_kzalloc(test, sizeof(*isp), GFP_KERNEL); From d9142ed1fcbea8ca576778d4556771e5f8292d34 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:12:49 +1100 Subject: [PATCH 0388/1514] dt-bindings: sound: apple,dpaudio: give the example its register window The apple,dpaudio example node has no reg. apple,t6000-dpaudio.yaml also selects apple,t8112-dpaudio and requires reg, so dt_binding_check fails: apple,dpaudio.example.dtb: audio-controller (apple,t8112-dpaudio): 'reg' is a required property Every t8112 dpaudio node in t8112.dtsi has a reg. Put the example in a 2-cell soc node and use the dpa1 window it already describes (SIO channel 0x66, ps_dpa1): reg = <0x2 0x38334000 0x0 0x4000>. dt_binding_check over both dpaudio schemas: 1 error before, 0 after. Signed-off-by: Ryan Murray --- .../bindings/sound/apple,dpaudio.yaml | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml b/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml index a531eb26061286..0cbbf78a0d6b8f 100644 --- a/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,dpaudio.yaml @@ -72,21 +72,27 @@ additionalProperties: false examples: - | - audio-controller { - compatible = "apple,t8112-dpaudio", "apple,dpaudio"; - dmas = <&sio 0x66>; - dma-names = "tx"; - power-domains = <&ps_dpa1>; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - - endpoint { - remote-endpoint = <&dcpext_audio>; + soc { + #address-cells = <2>; + #size-cells = <2>; + + audio-controller@238334000 { + compatible = "apple,t8112-dpaudio", "apple,dpaudio"; + reg = <0x2 0x38334000 0x0 0x4000>; + dmas = <&sio 0x66>; + dma-names = "tx"; + power-domains = <&ps_dpa1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + endpoint { + remote-endpoint = <&dcpext_audio>; + }; }; }; }; From e873def277a7bb7e3aa54cac15290d9cdfb1de95 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:17:20 +1100 Subject: [PATCH 0389/1514] PCI/ASPM: Respect a disabled Clock PM in the supports-clkreq default pcie_clkpm_cap_init() sets clkpm_disable on blacklisted (pre-1.1) links, and pcie_set_clkpm() then refuses Clock PM. The supports-clkreq default still set clkpm_default and logged that Clock PM was on. Skip such links, and log the default at debug level: the "ASPM: default states" line already reports the L1 PM Substates. Signed-off-by: Ryan Murray --- drivers/pci/pcie/aspm.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/pci/pcie/aspm.c b/drivers/pci/pcie/aspm.c index 13fcb0c919d8f3..417d5b45868399 100644 --- a/drivers/pci/pcie/aspm.c +++ b/drivers/pci/pcie/aspm.c @@ -948,13 +948,14 @@ static void pcie_aspm_override_default_link_state(struct pcie_link_state *link) */ static void pcie_clkpm_override_default_link_state(struct pcie_link_state *link) { - if (!of_have_populated_dt() || !link->clkpm_capable || link->clkpm_default) + if (!of_have_populated_dt() || !link->clkpm_capable || + link->clkpm_disable || link->clkpm_default) return; if (!pcie_link_has_aspm_override(link, "supports-clkreq")) return; link->clkpm_default = 1; - pci_info(link->downstream, "ASPM: default Clock PM (supports-clkreq)\n"); + pci_dbg(link->downstream, "ASPM: default Clock PM (supports-clkreq)\n"); } static void pcie_aspm_cap_init(struct pcie_link_state *link, int blacklist) From 44a1bae6dd09a6496924072626581d98d723f16a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 15:57:54 +0100 Subject: [PATCH 0390/1514] spi: apple-qspi: admit NVRAM writes by the DT partition and the part A controller became a write candidate only through a row of apple_qspi_boards[]: controller and machine compatible, controller base, the nvram window the device tree had to describe exactly, the JEDEC IDs and the block-protect bits the firmware leaves set. Each new Mac needed a row, and five of the ten rows were assumed rather than checked against an ADT and a probe. Take those facts from the machine instead, and check the device tree's partition against the flash before anything is written to it: - The window is the node's one "nvram" partition, if it is not marked read-only, is a whole number of 64 KiB NVRAM banks from a 4 KiB boundary and lies within three-byte addressing (apple_qspi_window_valid()). - The part is read back before every program or erase and must be in a short part table (W25Q64, Macronix 2B27, W25Q16, GD25UF16E), which gives its size and the block-protect bits its firmware leaves set. The window must end within the part: a three-byte address past it wraps around into the start of the flash. - Before the first program or erase, and latched for the controller: the part's SFDP density must be the size the table bounds the window with, and every bank of the window must start with a v3 NVRAM store header ("3VVN", version 1, a store size within the bank) or be blank throughout, with at least one store. A partition over firmware, a stale one, or one running into padding or an image partway through a bank, admits nothing. - Also at that point, the block-protect bits are decoded, and a bank they reach even in part is dropped from the writable banks. A program or erase there is refused before WREN, so a bank erase cannot stop halfway with the bank's header already gone. On the J700, BP0 covers the top 64 KiB, so the window's last bank [0x1e4000, 0x1f4000) is never written. The bits are decoded against each request as well: one in the protected range is refused before WREN instead of failing its readback and latching read-only. The read-only default and the root opt-in, the opcode, range, page and erase checks, the readback verify and the fault latch are unchanged. Refusals for the part, its size, SFDP, the window and protection are logged, rate limited, with the reason. The boards the table admitted keep their window and part. Any other board whose device tree describes a usable nvram partition is admitted by these checks alone. The rules live in spi-apple-qspi-policy.h, where KUnit covers the window rule, the bank header, the part table, the protected ranges, the banks they leave writable and SFDP parsing. tools/asahi/qspi-nvram-tests.py runs the driver's write path against a flash model with SFDP and NVRAM banks, with changed-guard controls for each new check. Closes: https://github.com/aurora-silicon/linux/issues/2815 Signed-off-by: Thomas Glanzmann --- drivers/spi/spi-apple-qspi-policy-test.c | 182 ++++++++++++++ drivers/spi/spi-apple-qspi-policy.h | 175 +++++++++++++- drivers/spi/spi-apple-qspi.c | 290 ++++++++++++++--------- tools/asahi/qspi-nvram-tests.py | 241 +++++++++++++------ 4 files changed, 699 insertions(+), 189 deletions(-) diff --git a/drivers/spi/spi-apple-qspi-policy-test.c b/drivers/spi/spi-apple-qspi-policy-test.c index 5418c3a4d63ab3..5cd22c258ff91a 100644 --- a/drivers/spi/spi-apple-qspi-policy-test.c +++ b/drivers/spi/spi-apple-qspi-policy-test.c @@ -5,6 +5,7 @@ */ #include +#include #include "spi-apple-qspi-policy.h" @@ -208,6 +209,181 @@ static void qspi_policy_part_status(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc2, 0x20, 0, 0, 0x1c)); } +static void qspi_policy_window(struct kunit *test) +{ + /* The J813 and J700 partitions. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0x24000, 0x1d0000)); + /* Two nvram labels, or none (a disabled one is not counted). */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(2, 2, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(0, 2, 0, 0x700000, 0x100000)); + /* Marked read-only. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 1, 0x700000, 0x100000)); + /* Three reg cells, or none. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 3, 0, 0x700000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 0, 0, 0x700000, 0x100000)); + /* A misaligned start, a part of a bank, an empty partition. */ + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700800, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0xff000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0x700000, 0)); + /* Past three-byte addressing. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_window_valid(1, 2, 0, 0xf00000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0xf10000, 0x100000)); + KUNIT_EXPECT_FALSE(test, apple_qspi_window_valid(1, 2, 0, 0xfffff000, 0x10000)); +} + +static void qspi_policy_bank_state(struct kunit *test) +{ + unsigned char h[24]; + + memset(h, 0xff, sizeof(h)); + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 0); + memset(h, 0, sizeof(h)); + memcpy(h, "3VVN", 4); + h[5] = 0x40; /* store size 0x4000 */ + h[14] = 1; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[14] = 2; /* another version */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[14] = 1; + h[5] = 0; + h[6] = 1; /* 0x10000: a full bank */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[4] = 1; /* past the bank */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[4] = 23; + h[6] = 0; /* smaller than the header */ + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + h[4] = 24; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), 1); + h[0] = '2'; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + /* Firmware, not NVRAM, and a half-erased bank. */ + memset(h, 0, sizeof(h)); + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); + memset(h, 0xff, sizeof(h)); + h[23] = 0xfe; + KUNIT_EXPECT_EQ(test, apple_qspi_nvram_bank_state(h), -1); +} + +static void qspi_policy_parts(struct kunit *test) +{ + static const unsigned char known[][3] = { + { 0xef, 0x65, 0x17 }, { 0xc2, 0x2b, 0x27 }, + { 0xef, 0x65, 0x15 }, { 0xc8, 0x83, 0x15 }, + }; + static const unsigned int sizes[] = { 0x800000, 0x800000, 0x200000, 0x200000 }; + static const unsigned char bp_ok[] = { 0, 0, 0x1c, 0x1c }; + static const unsigned char unknown[][3] = { + { 0xef, 0x65, 0x16 }, { 0xef, 0x40, 0x17 }, { 0xc2, 0x2b, 0x28 }, + { 0xc8, 0x60, 0x15 }, { 0, 0, 0 }, { 0xff, 0xff, 0xff }, + }; + const struct apple_qspi_part *part; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(known); i++) { + part = apple_qspi_find_part(known[i]); + KUNIT_ASSERT_NOT_NULL(test, part); + KUNIT_EXPECT_EQ(test, part->size, sizes[i]); + KUNIT_EXPECT_EQ(test, part->bp_ok, bp_ok[i]); + } + for (i = 0; i < ARRAY_SIZE(unknown); i++) + KUNIT_EXPECT_NULL(test, apple_qspi_find_part(unknown[i])); + /* The size bounds the window: the J700's fits 2 MiB, the J813's does not. */ + part = apple_qspi_find_part(known[2]); + KUNIT_EXPECT_LE(test, 0x1f4000ULL, (unsigned long long)part->size); + KUNIT_EXPECT_GT(test, 0x800000ULL, (unsigned long long)part->size); +} + +static void qspi_policy_protected(struct kunit *test) +{ + unsigned long long s, e; + + KUNIT_EXPECT_EQ(test, apple_qspi_protected_range(0xef, 0, 0x200000, &s, &e), 0); + /* BP0 on the J700's parts: the top 64 KiB, inside the window's last bank. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x04, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); + KUNIT_EXPECT_EQ(test, e, 0x200000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xc8, 0x04, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); + /* BP0+BP2: the top half; BP1+BP2: all of it. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x14, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x100000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x18, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0ULL); + KUNIT_EXPECT_EQ(test, e, 0x200000ULL); + /* Winbond TB: the bottom 64 KiB, below the J700's window. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x24, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0ULL); + KUNIT_EXPECT_EQ(test, e, 0x10000ULL); + /* Winbond SEC: 4 KiB to 32 KiB. */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x44, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1ff000ULL); + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xef, 0x54, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f8000ULL); + /* GigaDevice SR1 bit 5 is BP3, not TB (the status policy refuses it). */ + KUNIT_ASSERT_EQ(test, apple_qspi_protected_range(0xc8, 0x24, 0x200000, &s, &e), 1); + KUNIT_EXPECT_EQ(test, s, 0x1f0000ULL); +} + +static void qspi_policy_unprotected_banks(struct kunit *test) +{ + unsigned long long s, e; + int ret; + + /* Nothing protected inside the window: all of it. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x10000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x24000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1f4000ULL); + ret = apple_qspi_unprotected_banks(0x700000, 0x800000, 0, 0x700000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x700000ULL); + /* BP0 on the J700: its last bank [0x1e4000, 0x1f4000) is a quarter covered, and dropped. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x1f0000, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x24000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1e4000ULL); + /* TB with BP0+BP1: the bottom 256 KiB takes the first two banks. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x40000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x44000ULL); + KUNIT_EXPECT_EQ(test, e, 0x1f4000ULL); + /* A range ending on a bank boundary takes exactly those banks. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x44000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, s, 0x44000ULL); + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x1e4000, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 1); + KUNIT_EXPECT_EQ(test, e, 0x1e4000ULL); + /* The top half, or all of the part: nothing left. */ + ret = apple_qspi_unprotected_banks(0x700000, 0x800000, 0x400000, 0x800000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0, 0x200000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); + /* A range inside the window. */ + ret = apple_qspi_unprotected_banks(0x24000, 0x1f4000, 0x100000, 0x110000, &s, &e); + KUNIT_EXPECT_EQ(test, ret, 0); +} + +static void qspi_policy_sfdp(struct kunit *test) +{ + unsigned char h[16] = { 'S', 'F', 'D', 'P', 6, 1, 1, 0xff, + 0x00, 6, 1, 16, 0x30, 0, 0, 0xff }; + + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), 0x30L); + h[3] = 'Q'; + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), -1L); + h[3] = 'P'; + h[8] = 0x84; /* not the basic table */ + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_basic_table(h), -1L); + /* 64 Mbit and 16 Mbit as bit counts minus one, and as a power of two. */ + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x03ffffff), 0x800000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x00ffffff), 0x200000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x80000000 | 26), 0x800000ULL); + KUNIT_EXPECT_EQ(test, apple_qspi_sfdp_size(0x80000000 | 1), 0ULL); +} + static struct kunit_case apple_qspi_policy_cases[] = { KUNIT_CASE(qspi_policy_write_enable), KUNIT_CASE(qspi_policy_program), @@ -220,6 +396,12 @@ static struct kunit_case apple_qspi_policy_cases[] = { KUNIT_CASE(qspi_policy_mx_status), KUNIT_CASE(qspi_policy_gd_status), KUNIT_CASE(qspi_policy_part_status), + KUNIT_CASE(qspi_policy_window), + KUNIT_CASE(qspi_policy_bank_state), + KUNIT_CASE(qspi_policy_parts), + KUNIT_CASE(qspi_policy_protected), + KUNIT_CASE(qspi_policy_unprotected_banks), + KUNIT_CASE(qspi_policy_sfdp), {} }; diff --git a/drivers/spi/spi-apple-qspi-policy.h b/drivers/spi/spi-apple-qspi-policy.h index 361ecc689fca75..f0ac13bf978b31 100644 --- a/drivers/spi/spi-apple-qspi-policy.h +++ b/drivers/spi/spi-apple-qspi-policy.h @@ -6,8 +6,8 @@ #define APPLE_QSPI_ERASE_SIZE 4096U /* - * [start, end) is the board's nvram partition. Subtraction avoids overflow; - * addr is not truncated to wire width first. + * [start, end) is the write window, the device tree's nvram partition. + * Subtraction avoids overflow; addr is not truncated to wire width first. */ static inline int apple_qspi_range_allowed(unsigned long long addr, unsigned int len, unsigned long long start, @@ -113,4 +113,175 @@ static inline int apple_qspi_part_status_allows_write(unsigned int mfr, return apple_qspi_status_allows_write(sr1, sr2, sr3, bp_ok); } } + +/* The size of one NVRAM v3 bank ("3VVN" store). */ +#define APPLE_QSPI_NVRAM_BANK 0x10000U + +/* + * Whether an nvram partition can be the write window: the only one with that + * label, one address and one size cell, not marked read-only, a whole number + * of NVRAM banks from a 4 KiB boundary, and within three-byte addressing. + */ +static inline int apple_qspi_window_valid(unsigned int found, + unsigned int reg_cells, int read_only, + unsigned long long start, + unsigned long long size) +{ + return found == 1 && reg_cells == 2 && !read_only && size && + !(start % APPLE_QSPI_ERASE_SIZE) && + !(size % APPLE_QSPI_NVRAM_BANK) && start + size <= 1ULL << 24; +} + +/* + * The first 24 bytes of an NVRAM bank: 1 for a v3 store header ("3VVN", + * version 1, a store size from the header itself up to the bank), 0 for a + * bank that may be erased (the caller checks the rest of it), -1 for + * anything else. The v3 header has no checksum of its own; each variable in + * the store carries a CRC32. + */ +static inline int apple_qspi_nvram_bank_state(const unsigned char h[24]) +{ + unsigned int size = h[4] | h[5] << 8 | h[6] << 16 | (unsigned int)h[7] << 24; + int i; + + for (i = 0; i < 24 && h[i] == 0xff; i++) + ; + if (i == 24) + return 0; + if (h[0] == '3' && h[1] == 'V' && h[2] == 'V' && h[3] == 'N' && + h[14] == 1 && size >= 24 && size <= APPLE_QSPI_NVRAM_BANK) + return 1; + return -1; +} + +/* + * The boot NOR parts whose nvram partition may be written: the JEDEC ID, the + * size, which bounds the window (a three-byte address past it wraps around) + * and must match the part's SFDP density, and the SR1 block-protect bits the + * part's firmware leaves set. Those stay set; apple_qspi_protected_range() + * says what they protect. + */ +struct apple_qspi_part { + unsigned char jedec[3]; + unsigned int size; + unsigned char bp_ok; +}; + +#define APPLE_QSPI_JEDEC_W25Q64 { 0xef, 0x65, 0x17 } +#define APPLE_QSPI_JEDEC_W25Q16 { 0xef, 0x65, 0x15 } +#define APPLE_QSPI_JEDEC_MX_2B27 { 0xc2, 0x2b, 0x27 } +#define APPLE_QSPI_JEDEC_GD25UF16E { 0xc8, 0x83, 0x15 } + +static const struct apple_qspi_part apple_qspi_parts[] = { + /* J613, J713, J813; also on the bus of some J616s */ + { APPLE_QSPI_JEDEC_W25Q64, 0x800000, 0 }, + /* J616s, the ID macOS reports */ + { APPLE_QSPI_JEDEC_MX_2B27, 0x800000, 0 }, + /* J700: iBoot leaves BP0 set, over the top 64 KiB */ + { APPLE_QSPI_JEDEC_W25Q16, 0x200000, 0x1c }, + /* Some J700s; BP0 covers the same range */ + { APPLE_QSPI_JEDEC_GD25UF16E, 0x200000, 0x1c }, +}; + +static inline const struct apple_qspi_part * +apple_qspi_find_part(const unsigned char id[3]) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(apple_qspi_parts); i++) + if (id[0] == apple_qspi_parts[i].jedec[0] && + id[1] == apple_qspi_parts[i].jedec[1] && + id[2] == apple_qspi_parts[i].jedec[2]) + return &apple_qspi_parts[i]; + return NULL; +} + +/* + * What SR1 protects on a part that tolerates BP bits (the 2 MiB parts, whose + * status policy leaves BP0-BP2 and, on Winbond, TB and SEC as found; CMP, and + * BP3/BP4 on GigaDevice, are refused before this). BP0-BP2 of 1 to 5 protect + * 1/32 to 1/2 of the part, or with SEC 4 to 32 KiB; 6 and 7 protect all of it. + * TB puts the range at the bottom instead of the top. Sets [*start, *end) and + * returns 1, or returns 0 when nothing is protected. + */ +static inline int apple_qspi_protected_range(unsigned int mfr, unsigned int sr1, + unsigned long long size, + unsigned long long *start, + unsigned long long *end) +{ + unsigned int bp = (sr1 >> 2) & 7, shift; + int bottom = 0, sec = 0; + unsigned long long len; + + if (!bp) + return 0; + if (mfr != APPLE_QSPI_MFR_GIGADEVICE) { + bottom = !!(sr1 & 0x20); + sec = !!(sr1 & 0x40); + } + if (bp >= 6) { + len = size; + } else if (sec) { + shift = bp - 1 < 3 ? bp - 1 : 3; + len = 0x1000ULL << shift; + } else { + len = (size >> 5) << (bp - 1); + } + *start = bottom ? 0 : size - len; + *end = *start + len; + return 1; +} + +/* + * The banks of the window [start, end) that a protected range [ps, pe) does + * not reach, as [*wstart, *wend): a bank the range only partly covers is + * dropped whole, so an erase of it never stops halfway. The decoded range + * always reaches one end of the part, so it takes a run of banks from one + * end of the window. Returns 0 when no bank is left, or for a range inside + * the window with banks on both sides of it, which no decode produces. + */ +static inline int apple_qspi_unprotected_banks(unsigned long long start, + unsigned long long end, + unsigned long long ps, + unsigned long long pe, + unsigned long long *wstart, + unsigned long long *wend) +{ + unsigned long long bank = APPLE_QSPI_NVRAM_BANK; + + *wstart = start; + *wend = end; + if (pe <= start || ps >= end) + return 1; + if (ps <= start) + *wstart = start + (pe - start + bank - 1) / bank * bank; + else if (pe >= end) + *wend = start + (ps - start) / bank * bank; + else + return 0; + return *wstart < *wend; +} + +/* + * The JEDEC basic flash parameter table from the first 16 bytes of the SFDP + * space: "SFDP", then the first parameter header, which must be the basic + * table (ID 0x00, MSB 0xff). Returns the table's address, or -1. + */ +static inline long apple_qspi_sfdp_basic_table(const unsigned char h[16]) +{ + if (h[0] != 'S' || h[1] != 'F' || h[2] != 'D' || h[3] != 'P' || + h[8] != 0x00 || h[15] != 0xff || h[11] < 2) + return -1; + return h[12] | h[13] << 8 | h[14] << 16; +} + +/* The part size in bytes from the basic table's second DWORD, or 0. */ +static inline unsigned long long apple_qspi_sfdp_size(unsigned int dword2) +{ + unsigned int n = dword2 & 0x7fffffff; + + if (dword2 & 0x80000000) + return n >= 3 && n < 64 ? 1ULL << (n - 3) : 0; + return ((unsigned long long)dword2 + 1) / 8; +} #endif diff --git a/drivers/spi/spi-apple-qspi.c b/drivers/spi/spi-apple-qspi.c index 06e2d356dcbec3..10d618dccea9c7 100644 --- a/drivers/spi/spi-apple-qspi.c +++ b/drivers/spi/spi-apple-qspi.c @@ -7,10 +7,10 @@ * command FIFO. This driver intentionally implements the PIO spi-mem path * only; that is sufficient for SPI NOR discovery and access. * - * The boot NOR starts read-only. On the qualified boards (J613, J713, - * J616s and the J700) root may opt in at runtime to bounded, verified - * programs and 4 KiB erases inside the nvram partition; everything else - * stays read-only. On T8140 data reads reach the whole NOR. + * The boot NOR starts read-only. Where the device tree describes its nvram + * partition and the flash is a part listed here, root may opt in at runtime + * to bounded, verified programs and 4 KiB erases inside that partition; + * everything else stays read-only. On T8140 data reads reach the whole NOR. */ #include @@ -25,9 +25,11 @@ #include #include #include +#include #include #include #include +#include #include "spi-apple-qspi-policy.h" @@ -97,61 +99,6 @@ struct apple_qspi_soc { bool runtime_pm; }; -/* - * A board whose NVRAM may be written: the controller compatible, the - * machine, the controller aperture, the nvram partition the device tree - * must describe, the boot NOR JEDEC ID, the SR1 block-protect bits its - * firmware leaves set at boot and the JEDEC ID of a second part, if any. - */ -struct apple_qspi_board { - const char *controller; - const char *machine; - resource_size_t base; - u32 nvram_start; - u32 nvram_size; - u8 jedec[3]; - u8 bp_ok; - u8 jedec_alt[3]; -}; - -#define APPLE_QSPI_JEDEC_W25Q64 { 0xef, 0x65, 0x17 } -#define APPLE_QSPI_JEDEC_W25Q16 { 0xef, 0x65, 0x15 } -#define APPLE_QSPI_JEDEC_MX_2B27 { 0xc2, 0x2b, 0x27 } -#define APPLE_QSPI_JEDEC_GD25UF16E { 0xc8, 0x83, 0x15 } - -static const struct apple_qspi_board apple_qspi_boards[] = { - { "apple,t8122-qspi", "apple,j613", 0x2a1118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j713", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* The J715 ADT has the J713's nvram; its NOR part is assumed the same. */ - { "apple,t8132-qspi", "apple,j715", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* - * The J773g ADT has the same nvram; the J604's dump omits it and the - * iMacs have no ADT yet. All are assumed to carry the J713's part. - */ - { "apple,t8132-qspi", "apple,j604", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j623", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j624", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - { "apple,t8132-qspi", "apple,j773g", 0x3ad118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_W25Q64, 0 }, - /* Macronix is the ID macOS reports; a J616s also reads W25Q64 on the bus. */ - { "apple,t6041-qspi", "apple,j616s", 0x429118000ULL, - 0x700000, 0x100000, APPLE_QSPI_JEDEC_MX_2B27, 0, - APPLE_QSPI_JEDEC_W25Q64 }, - /* - * iBoot leaves BP0 set on the J700, over the top 64 KiB. Some J700s - * carry a GigaDevice GD25UF16E, where BP0 covers the same range. - */ - { "apple,t8140-qspi", "apple,j700", 0x385110000ULL, - 0x24000, 0x1d0000, APPLE_QSPI_JEDEC_W25Q16, 0x1c, - APPLE_QSPI_JEDEC_GD25UF16E }, -}; - static DEFINE_MUTEX(apple_qspi_policy_lock); static bool read_only = true; static bool runtime_ready; @@ -189,7 +136,7 @@ static const struct kernel_param_ops apple_qspi_read_only_ops = { .get = apple_qspi_get_read_only, }; module_param_cb(read_only, &apple_qspi_read_only_ops, &read_only, 0644); -MODULE_PARM_DESC(read_only, "Default true; root runtime opt-in for bounded NVRAM writes on qualified boards"); +MODULE_PARM_DESC(read_only, "Default true; root runtime opt-in for bounded NVRAM writes in the nvram partition of a known part"); static bool apple_qspi_opcode_is_read(u8 opcode) { @@ -220,11 +167,17 @@ struct apple_qspi { /* The nvram partition [window_start, window_end). */ u64 window_start; u64 window_end; - /* Expected JEDEC IDs and the SR1 block-protect bits left by firmware. */ - u8 jedec[3]; - u8 jedec_alt[3]; - u8 bp_ok; + /* The device tree describes a usable nvram partition. */ bool nvram_write_candidate; + /* + * The window checked against the flash before its first program or + * erase, then latched: 0 not yet, 1 passed, a negative errno refused. + */ + int qualified; + const char *qualify_denial; + /* Once qualified: the banks of the window no block protection reaches. */ + u64 write_start; + u64 write_end; bool write_fault; void __iomem *base; void __iomem *p; @@ -718,9 +671,125 @@ static int apple_qspi_status(struct spi_mem *mem, u8 mfr, u8 sr[3]) return 0; } -static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op *op) +static int apple_qspi_read_sfdp(struct spi_mem *mem, u32 addr, u8 *buf, u32 len) +{ + struct spi_mem_op op = SPI_MEM_OP(SPI_MEM_OP_CMD(0x5a, 1), + SPI_MEM_OP_ADDR(3, addr, 1), SPI_MEM_OP_DUMMY(1, 1), + SPI_MEM_OP_DATA_IN(len, buf, 1)); + + return apple_qspi_transfer_op(mem, &op); +} + +/* + * Before the first program or erase, check the window against the flash, + * and latch the result: the part's SFDP density must be the size the part + * table bounds the window with, and every bank of the window must start with + * a v3 NVRAM store header or be erased throughout, with at least one store. + * A device tree partition that is not the NVRAM, or a part of another size, + * admits nothing. Writes are then admitted only in the banks that the block + * protection found in SR1 does not reach, even in part. + */ +static int apple_qspi_qualify(struct spi_mem *mem, struct apple_qspi *qspi, + const struct apple_qspi_part *part, + const char **denial) +{ + unsigned long long ps, pe, ws, we; + u8 head[24], dword[8], sr[3]; + u8 *buf = NULL; + u64 bank, at; + long table; + int state, stores = 0, ret; + + if (qspi->qualified) { + *denial = qspi->qualify_denial; + return qspi->qualified < 0 ? qspi->qualified : 0; + } + ret = apple_qspi_read_sfdp(mem, 0, head, 16); + if (ret) + return ret; + table = apple_qspi_sfdp_basic_table(head); + if (table < 0) { + *denial = "sfdp"; + ret = -ENODEV; + goto latch; + } + ret = apple_qspi_read_sfdp(mem, table, dword, sizeof(dword)); + if (ret) + return ret; + if (apple_qspi_sfdp_size(get_unaligned_le32(&dword[4])) != part->size) { + *denial = "part-size"; + ret = -ENODEV; + goto latch; + } + for (bank = qspi->window_start; bank < qspi->window_end; + bank += APPLE_QSPI_NVRAM_BANK) { + ret = apple_qspi_read_array(mem, bank, head, sizeof(head)); + if (ret) + goto out; + state = apple_qspi_nvram_bank_state(head); + /* Blank where a header would be is not enough: all of it. */ + if (!state && !buf) { + buf = kmalloc(APPLE_QSPI_ERASE_SIZE, GFP_KERNEL); + if (!buf) { + ret = -ENOMEM; + goto out; + } + } + for (at = bank; !state && at < bank + APPLE_QSPI_NVRAM_BANK; + at += APPLE_QSPI_ERASE_SIZE) { + ret = apple_qspi_read_array(mem, at, buf, APPLE_QSPI_ERASE_SIZE); + if (ret) + goto out; + if (memchr_inv(buf, 0xff, APPLE_QSPI_ERASE_SIZE)) + state = -1; + } + if (state < 0) { + *denial = "window"; + ret = -EACCES; + goto latch; + } + stores += state; + } + if (!stores) { + *denial = "window"; + ret = -EACCES; + goto latch; + } + ret = apple_qspi_status(mem, part->jedec[0], sr); + if (ret) + goto out; + ws = qspi->window_start; + we = qspi->window_end; + if (part->bp_ok && + apple_qspi_protected_range(part->jedec[0], sr[0], part->size, &ps, &pe) && + !apple_qspi_unprotected_banks(qspi->window_start, qspi->window_end, + ps, pe, &ws, &we)) { + *denial = "protected"; + ret = -EACCES; + goto latch; + } + qspi->write_start = ws; + qspi->write_end = we; + qspi->qualified = 1; + dev_info(&mem->spi->dev, + "nvram window [%#llx, %#llx): %d stores, writes in [%#llx, %#llx), part %02x%02x%02x\n", + qspi->window_start, qspi->window_end, stores, ws, we, + part->jedec[0], part->jedec[1], part->jedec[2]); + goto out; +latch: + qspi->qualified = ret; + qspi->qualify_denial = *denial; +out: + kfree(buf); + return ret; +} + +static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op *op, + const char **denial) { struct apple_qspi *qspi = spi_controller_get_devdata(mem->spi->controller); + const struct apple_qspi_part *part; + unsigned long long ps, pe; unsigned long deadline; u8 id[3], before[3], after[3], sr1; u8 *verify; @@ -734,17 +803,37 @@ static int apple_qspi_nvram_modify(struct spi_mem *mem, const struct spi_mem_op ret = apple_qspi_read_register(mem, 0x9f, id, sizeof(id)); if (ret) goto out; - if (memcmp(id, qspi->jedec, sizeof(id)) && - (!qspi->jedec_alt[0] || memcmp(id, qspi->jedec_alt, sizeof(id)))) { + /* A known part, the partition within it, and checked against it. */ + part = apple_qspi_find_part(id); + if (!part || qspi->window_end > part->size) { + *denial = part ? "part-size" : "part"; ret = -ENODEV; goto out; } + ret = apple_qspi_qualify(mem, qspi, part, denial); + if (ret) + goto out; + /* Never into a bank the protection reaches, so none is left half erased. */ + if (op->addr.val < qspi->write_start || op->addr.val + len > qspi->write_end) { + *denial = "protected"; + ret = -EACCES; + goto out; + } ret = apple_qspi_status(mem, id[0], before); if (ret) goto out; /* No unlocking. Conservatively refuse BP/CMP/WPS, BUSY/WEL or suspend. */ if (!apple_qspi_part_status_allows_write(id[0], before[0], before[1], - before[2], qspi->bp_ok)) { + before[2], part->bp_ok)) { + *denial = "status"; + ret = -EACCES; + goto out; + } + /* The flash would ignore this one: refuse it rather than latch a fault. */ + if (part->bp_ok && + apple_qspi_protected_range(id[0], before[0], part->size, &ps, &pe) && + op->addr.val < pe && op->addr.val + len > ps) { + *denial = "protected"; ret = -EACCES; goto out; } @@ -884,9 +973,9 @@ static int apple_qspi_exec_op(struct spi_mem *mem, const struct spi_mem_op *op) ret = 0; goto out; } - ret = apple_qspi_nvram_modify(mem, op); + ret = apple_qspi_nvram_modify(mem, op, &denial); out: - if (ret == -EACCES) + if (ret == -EACCES || ret == -ENODEV) dev_warn_ratelimited(&mem->spi->dev, "NVRAM denied: reason=%s opcode=%02x addr=%#llx addr_bytes=%u len=%u width=%u addr_width=%u dummy=%u dir=%u ro=%u candidate=%u fault=%u\n", denial, op->cmd.opcode, (unsigned long long)op->addr.val, @@ -922,35 +1011,19 @@ static const struct spi_controller_mem_ops apple_qspi_mem_ops = { .exec_op = apple_qspi_mem_exec_op, }; -/* Keep write qualification tied to the board and its controller aperture. */ -static const struct apple_qspi_board * -apple_qspi_nvram_write_board(struct device_node *node, resource_size_t base) -{ - const struct apple_qspi_board *board; - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(apple_qspi_boards); i++) { - board = &apple_qspi_boards[i]; - if (of_device_is_compatible(node, board->controller) && - of_machine_is_compatible(board->machine) && - base == board->base) - return board; - } - return NULL; -} - /* - * The one "nvram" partition of the flash on CS0, 4 KiB aligned and within - * three-byte addressing, since the policy only admits three-byte programs - * and erases. Without it, no program or erase is admitted. + * The one "nvram" partition of the flash on CS0 that apple_qspi_window_valid() + * accepts: not read-only, whole NVRAM banks from a 4 KiB boundary, within + * three-byte addressing, since the policy only admits three-byte programs and + * erases. Without it, no program or erase is admitted. */ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) { struct device_node *flash, *parts, *part; const char *label; - u32 reg[2], cells[2], cs; + u32 reg[2] = { 0 }, cells[2], cs; u64 start = 0, end = 0; - int found = 0; + int found = 0, reg_cells = 0, ro = 0; flash = of_get_child_by_name(dev->of_node, "flash"); if (!flash) @@ -973,18 +1046,18 @@ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) strcmp(label, "nvram")) continue; found++; - if (of_property_count_u32_elems(part, "reg") == 2 && - !of_property_read_u32_array(part, "reg", reg, 2)) { - start = reg[0]; - end = start + reg[1]; - } + ro = of_property_read_bool(part, "read-only"); + reg_cells = of_property_count_u32_elems(part, "reg"); + if (reg_cells != 2 || + of_property_read_u32_array(part, "reg", reg, 2)) + memset(reg, 0, sizeof(reg)); } } of_node_put(parts); - if (found != 1 || start >= end || end > 1ULL << 24 || - !IS_ALIGNED(start, APPLE_QSPI_ERASE_SIZE) || - !IS_ALIGNED(end, APPLE_QSPI_ERASE_SIZE)) - start = end = 0; + if (apple_qspi_window_valid(found, reg_cells, ro, reg[0], reg[1])) { + start = reg[0]; + end = start + reg[1]; + } out: qspi->window_start = start; qspi->window_end = end; @@ -997,7 +1070,6 @@ static void apple_qspi_nvram_window(struct device *dev, struct apple_qspi *qspi) static int apple_qspi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; - const struct apple_qspi_board *board; const struct apple_qspi_soc *soc; struct spi_controller *ctlr; struct apple_qspi *qspi; @@ -1028,15 +1100,11 @@ static int apple_qspi_probe(struct platform_device *pdev) return dev_err_probe(dev, -EINVAL, "QSPIMC aperture is too small\n"); - /* The device tree must describe exactly the board's nvram partition. */ - board = apple_qspi_nvram_write_board(dev->of_node, res->start); - if (board && qspi->window_start == board->nvram_start && - qspi->window_end == (u64)board->nvram_start + board->nvram_size) { - memcpy(qspi->jedec, board->jedec, sizeof(qspi->jedec)); - memcpy(qspi->jedec_alt, board->jedec_alt, sizeof(qspi->jedec_alt)); - qspi->bp_ok = board->bp_ok; - qspi->nvram_write_candidate = true; - } + /* + * The device tree's nvram partition is the write window. Each program + * or erase then checks the part and that the window lies within it. + */ + qspi->nvram_write_candidate = qspi->window_start < qspi->window_end; qspi->base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(qspi->base)) return PTR_ERR(qspi->base); diff --git a/tools/asahi/qspi-nvram-tests.py b/tools/asahi/qspi-nvram-tests.py index 3e377466e9444b..a67a44af650256 100644 --- a/tools/asahi/qspi-nvram-tests.py +++ b/tools/asahi/qspi-nvram-tests.py @@ -32,11 +32,8 @@ def function(source, signature): #include #include typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; -typedef uint64_t resource_size_t; -struct device_node { const char *compatible; }; -static const char *machine; -static bool of_device_is_compatible(struct device_node *node,const char *compat){return !strcmp(node->compatible,compat);} -static bool of_machine_is_compatible(const char *compat){return !strcmp(machine,compat);} +#define SZ_2M 0x200000 +#define SZ_8M 0x800000 #define EOPNOTSUPP 95 #define GFP_KERNEL 0 #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) @@ -49,6 +46,10 @@ def function(source, signature): #define SPI_MEM_OP_ADDR(n,a,w) { .val=a,.nbytes=n,.buswidth=w } #define SPI_MEM_OP_NO_ADDR {0} #define SPI_MEM_OP_NO_DUMMY {0} +#define SPI_MEM_OP_DUMMY(n,w) { .nbytes=n,.buswidth=w } +#define get_unaligned_le32(p) ((u32)((const u8*)(p))[0]|(u32)((const u8*)(p))[1]<<8|(u32)((const u8*)(p))[2]<<16|(u32)((const u8*)(p))[3]<<24) +static int info_count; +#define dev_info(device,...) (info_count++) #define SPI_MEM_OP_DATA_IN(n,b,w) { .nbytes=n,.buf.in=b,.buswidth=w,.dir=SPI_MEM_DATA_IN } #define SPI_MEM_OP_NO_DATA {0} #define SPI_MEM_OP(c,a,d,v) { .cmd=c,.addr=a,.dummy=d,.data=v } @@ -68,10 +69,12 @@ def function(source, signature): static int param_get_bool(char*b,const struct kernel_param*p){b[0]=*(bool*)p->arg?'Y':'N';return 1;} struct apple_qspi { bool nvram_policy, nvram_write_candidate, write_fault, nvram_window; - u64 window_start, window_end; - u8 jedec[3]; u8 jedec_alt[3]; u8 bp_ok; + int qualified; const char *qualify_denial; + u64 window_start, window_end, write_start, write_end; int irq; }; +/* The flash model admits only the window, which the controls set. */ +static struct apple_qspi q; struct spi_controller; struct device { struct device *parent; struct spi_controller *controller; }; struct spi_controller { struct apple_qspi *q; bool auto_runtime_pm; struct device dev; }; @@ -92,7 +95,18 @@ def function(source, signature): static bool deny_alloc; static void *kmalloc(size_t n,int flags){return deny_alloc?NULL:malloc(n);} #define kfree free +static void *memchr_inv(const void*p,int c,size_t n){const u8*b=p;for(size_t i=0;i>8;sfdp[0x36]=dword2>>16;sfdp[0x37]=dword2>>24; +} +/* A v3 NVRAM store header at the start of a bank. */ +static void store_at(u64 at){memset(flash+at,0,24);memcpy(flash+at,"3VVN",4);flash[at+5]=0x40;flash[at+14]=1;} static unsigned int wire[4096],wire_count,fail_opcode; static bool corrupt_readback,stuck_busy,programmed; static unsigned int pm_refs,busy_calls,busy_wire; @@ -105,6 +119,8 @@ def function(source, signature): if(o->cmd.opcode==fail_opcode)return -EIO; switch(o->cmd.opcode){ case 0x9f:memcpy(o->data.buf.in,jedec,o->data.nbytes);break; + case 0x5a:assert(o->addr.nbytes==3&&o->dummy.nbytes==1&&o->addr.val+o->data.nbytes<=sizeof(sfdp)); + memcpy(o->data.buf.in,sfdp+o->addr.val,o->data.nbytes);sfdp_reads++;break; case 0x05:*(u8*)o->data.buf.in=sr[0]|(stuck_busy&&programmed?1:0);break; case 0x35:assert(jedec[0]!=0xc2);*(u8*)o->data.buf.in=sr[1];break; case 0x15:*(u8*)o->data.buf.in=sr[2];break; @@ -116,10 +132,10 @@ def function(source, signature): case 0x06:assert(!(sr[0]&3));sr[0]|=2;break; case 0x04:sr[0]&=~2;break; case 0x02: - assert(sr[0]&2);assert(o->addr.val>=0x700000&&o->addr.val+o->data.nbytes<=0x800000); + assert(sr[0]&2);assert(o->addr.val>=q.window_start&&o->addr.val+o->data.nbytes<=q.window_end); for(unsigned int i=0;idata.nbytes;i++)flash[o->addr.val+i]&=((const u8*)o->data.buf.out)[i]; sr[0]&=~2;programmed=true;break; - case 0x20:assert(sr[0]&2);assert(o->addr.val>=0x700000&&o->addr.val+4096<=0x800000); + case 0x20:assert(sr[0]&2);assert(o->addr.val>=q.window_start&&o->addr.val+4096<=q.window_end); memset(flash+o->addr.val,0xff,4096);sr[0]&=~2;programmed=true;break; default:assert(!"forbidden opcode reached the wire"); }return 0; @@ -134,13 +150,15 @@ def function(source, signature): static struct spi_mem mem={&spi}; static struct kernel_param parameter={&read_only}; static void reset(void){ - memset(flash,0xff,sizeof(flash));memset(sr,0,sizeof(sr));q=(struct apple_qspi){.nvram_policy=true,.nvram_write_candidate=true,.window_start=0x700000,.window_end=0x800000,.jedec={0xef,0x65,0x17}}; + memset(flash,0xff,sizeof(flash));memset(sr,0,sizeof(sr));q=(struct apple_qspi){.nvram_policy=true,.nvram_write_candidate=true,.window_start=0x700000,.window_end=0x800000,.write_start=0x700000,.write_end=0x800000,.qualified=1};sfdp_set(0x03ffffff);sfdp_reads=0;info_count=0; read_only=true;runtime_ready=false;write_fault_latched=false;wire_count=0;fail_opcode=0;spi.cs=0; corrupt_readback=false;stuck_busy=false;programmed=false;deny_alloc=false;jiffies=0; jedec[0]=0xef;jedec[1]=0x65;jedec[2]=0x17; ctl.auto_runtime_pm=false;ctl.dev.parent=&parent; pm_refs=busy_calls=busy_wire=0; } +/* A window already qualified with nothing protected, unless a test clears q.qualified. */ +static void window(u64 start,u64 end){q.window_start=q.write_start=start;q.window_end=q.write_end=end;} static struct spi_mem_op program(u64 addr,unsigned int n,const u8*b){ struct spi_mem_op o=SPI_MEM_OP(SPI_MEM_OP_CMD(0x02,1),SPI_MEM_OP_ADDR(3,addr,1),SPI_MEM_OP_NO_DUMMY,SPI_MEM_OP_NO_DATA); o.data.nbytes=n;o.data.dir=SPI_MEM_DATA_OUT;o.data.buswidth=1;o.data.buf.out=b;return o; @@ -149,49 +167,48 @@ def function(source, signature): static bool sent(unsigned int o){for(unsigned int i=0;isize==sizes[i]&&part->bp_ok==tolerated[i]); } - const struct apple_qspi_board *qb; - struct device_node t6041={"apple,t6041-qspi"},t8140={"apple,t8140-qspi"}; - machine="apple,j616s";qb=apple_qspi_nvram_write_board(&t6041,0x429118000ULL); - assert(qb&&qb->nvram_start==0x700000&&qb->nvram_size==0x100000&&qb->jedec[0]==0xc2&&qb->jedec[1]==0x2b&&qb->jedec[2]==0x27&&!qb->bp_ok); - assert(qb->jedec_alt[0]==0xef&&qb->jedec_alt[1]==0x65&&qb->jedec_alt[2]==0x17); - machine="apple,j700";qb=apple_qspi_nvram_write_board(&t8140,0x385110000ULL); - assert(qb&&qb->nvram_start==0x24000&&qb->nvram_size==0x1d0000&&qb->jedec[2]==0x15&&qb->bp_ok==0x1c); - assert(qb->jedec_alt[0]==0xc8&&qb->jedec_alt[1]==0x83&&qb->jedec_alt[2]==0x15); - puts("PASS J613/J713/J700/J616s board, controller and full-width aperture qualification (140 combinations)"); + const u8 unknown[][3]={{0xef,0x65,0x16},{0xef,0x65,0x18},{0xc2,0x2b,0x28},{0xc8,0x60,0x15},{0xef,0x40,0x17},{0,0,0},{0xff,0xff,0xff}}; + for(unsigned int i=0;icontroller) &&', ''), - ('board', 'of_machine_is_compatible(board->machine) &&', ''), - ('aperture', 'base == board->base', 'base != 0'), - ('j616s-aperture', '"apple,j616s", 0x429118000ULL', '"apple,j616s", 0x429118800ULL'), - ('j616s-partition', '"apple,j616s", 0x429118000ULL,\n\t 0x700000', '"apple,j616s", 0x429118000ULL,\n\t 0x680000'), + ('part-id', 'return &apple_qspi_parts[i];\n\treturn NULL;', 'return &apple_qspi_parts[i];\n\treturn &apple_qspi_parts[0];'), + ('part-size', '!part || qspi->window_end > part->size', '!part'), + ('part-bp', 'before[2], part->bp_ok)', 'before[2], 0x1c)'), + ('w25q16-size', '{ APPLE_QSPI_JEDEC_W25Q16, 0x200000, 0x1c }', '{ APPLE_QSPI_JEDEC_W25Q16, 0x800000, 0x1c }'), + ('protected', 'op->addr.val < pe && op->addr.val + len > ps', '0'), + ('bank-invalid', 'if (state < 0) {', 'if (0) {'), + ('bank-none', 'if (!stores) {', 'if (stores < 0) {'), + ('bank-latch', 'qspi->qualified = ret;', '(void)0;'), + ('bank-blank', 'if (memchr_inv(buf, 0xff, APPLE_QSPI_ERASE_SIZE))', 'if (0)'), + ('protected-bank', 'op->addr.val < qspi->write_start || op->addr.val + len > qspi->write_end', '0'), + ('protected-qualify', '!apple_qspi_unprotected_banks(', '0 && !apple_qspi_unprotected_banks('), + ('sfdp-size', '!= part->size) {', '!= part->size && 0) {'), + ('window-read-only', '!read_only && size &&', 'size &&'), + ('window-bank', '!(size % APPLE_QSPI_NVRAM_BANK) &&', ''), ('range', 'addr >= start &&', 'addr >= 1 &&'), ('bp-ok', '!(sr1 & 0x1c & ~bp_ok)', '1'), ('mx-bp3', '!(sr & 0x3c & ~bp_ok)', '!(sr & 0x1c & ~bp_ok)'), ('mx-eqio', 'opcode = macronix;', 'opcode = winbond;'), ('mx-eqio-read', '!ret && id[0] == APPLE_QSPI_MFR_MACRONIX', '0'), - ('jedec-alt', 'memcmp(id, qspi->jedec_alt, sizeof(id))', '1'), - ('jedec-alt-empty', '!qspi->jedec_alt[0] || ', ''), ('gd-dispatch', 'return apple_qspi_gd_status_allows_write(sr1, sr2, bp_ok);', 'return apple_qspi_status_allows_write(sr1, sr2, sr3, bp_ok);'), ('gd-bp34', '!(sr1 & 0x7c & ~bp_ok)', '!(sr1 & 0x1c & ~bp_ok)'), From 87650bc2e3106bc2739080df8ae3c9a9ea45f65c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 19:16:21 +0100 Subject: [PATCH 0391/1514] spi: apple-qspi: cover the J813's NOR status in KUnit The J813 (MacBook Air 13-inch, M5) reads a Winbond W25Q64 (ef6517) with QE set and the SR3 drive strength at its default, and no block protection: flash_status: jedec=ef6517 sr1=00 sr2=02 sr3=60 Since #2817 the J813 is a write candidate through its device tree's nvram partition (0x700000, 1 MiB, the ADT anvram) and its probed part, with no board entry. Check in KUnit that these status registers pass the write policy for a part that tolerates no block-protect bits. Signed-off-by: Thomas Glanzmann --- drivers/spi/spi-apple-qspi-policy-test.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/spi/spi-apple-qspi-policy-test.c b/drivers/spi/spi-apple-qspi-policy-test.c index 5cd22c258ff91a..68b7de086be2f0 100644 --- a/drivers/spi/spi-apple-qspi-policy-test.c +++ b/drivers/spi/spi-apple-qspi-policy-test.c @@ -152,6 +152,8 @@ static void qspi_policy_status(struct kunit *test) /* Block protect only where the board allows it. */ KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0x04, 0, 0, 0)); KUNIT_EXPECT_TRUE(test, apple_qspi_status_allows_write(0x04, 0x02, 0, 0x1c)); + /* The J813 W25Q64: QE and the SR3 drive strength, no block protection. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_status_allows_write(0x00, 0x02, 0x60, 0)); /* CMP, SUS and WPS are refused everywhere. */ KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0, 0x40, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_status_allows_write(0, 0x80, 0, 0x1c)); From cdd27c5b135e93074c10c8115c08d5f19e05b2ef Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 19:26:24 +0100 Subject: [PATCH 0392/1514] drm/asahi: g18: say which timeline points the input error check sees asahi_g18_fence_error() walks a dma_fence_chain with dma_fence_chain_walk(), which unlinks the earlier points that have signalled. A job's inputs have all signalled when it runs, so of a timeline only the head point's own fence is checked, and an error on an earlier point is not seen. The comment said every fence was checked. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/g18/sync_input.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g18/sync_input.c b/drivers/gpu/drm/asahi/g18/sync_input.c index f443ff776f11d5..53d50bae534db1 100644 --- a/drivers/gpu/drm/asahi/g18/sync_input.c +++ b/drivers/gpu/drm/asahi/g18/sync_input.c @@ -37,7 +37,11 @@ int asahi_g18_wait_foreign_fences(struct dma_fence *head, * too, or 0. A container does not carry its fences' errors: a * dma_fence_chain (a timeline point) never copies them, and a * dma_fence_array whose signalling was never enabled clears its pending - * error when it is found signalled. So each fence is checked itself. + * error when it is found signalled. So each fence the walk reaches is + * checked itself. Of a timeline, the walk reaches only the head point: + * dma_fence_chain_walk() unlinks the earlier points that have signalled, and + * a job's inputs have all signalled when it runs, so an error on an earlier + * point is not seen. */ int asahi_g18_fence_error(struct dma_fence *head) { From f604f5dfc966049e71182612430c82ac335112a7 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 13:59:46 -0500 Subject: [PATCH 0393/1514] drm/apple: run the sleep notifier after the DCPs' own Registering apple_drm_pm_nb at module init put it ahead of any DCP that probes after the module loads (a deferred probe, or an unbind and rebind), since the PM chain appends equal priorities. At PM_POST_SUSPEND the restore of a dark-held device could then start before a DCPEXT's dark-wake firmware restart (dcp_s2r_dark_finish()), and a DCP that refuses PM_SUSPEND_PREPARE would roll appledrm back with a PM_POST_SUSPEND it did not get at bind. Priority -1 keeps it below the DCPs' notifiers (priority 0) whatever the probe order, which is the order the bind-time registration gave. Also flush the restore queue at every *_PREPARE, not only the suspend one, check register_pm_notifier()'s result, and bring the comments that still describe a separate T8132 notifier up to date. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/apple_drv.c | 23 ++++++++++++++++++++--- drivers/gpu/drm/apple/t8132_ext_drm.c | 9 +++++---- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 12c9c34f6f66f6..0cfbe2f4bda338 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -106,8 +106,17 @@ static DEFINE_MUTEX(apple_drm_pm_lock); static LIST_HEAD(apple_drm_pm_list); /* Ordered, so the next suspend's PM_SUSPEND_PREPARE can wait for every restore. */ static struct workqueue_struct *apple_drm_pm_wq; +/* + * Below the DCPs' own notifiers (dcp_s2r_pm_register(), priority 0), whatever + * the probe order: the chain runs higher priorities first and appends equal + * ones, and a DCP that defers past module init would otherwise come after + * this one. At PM_POST_SUSPEND a DCPEXT's dark-wake firmware restart then + * still finishes before the restore here is queued, and a DCP that refuses + * PM_SUSPEND_PREPARE rolls back only the notifiers before it, as at bind. + */ static struct notifier_block apple_drm_pm_nb = { .notifier_call = apple_drm_pm_notify, + .priority = -1, }; /* Component readiness is later than platform probe/bind. */ @@ -2144,7 +2153,10 @@ static void apple_platform_complete(struct device *dev) apple_drm_resume_outputs(apple); } -/* It failed before ->prepare() reached this device, so ->complete() didn't run either. */ +/* + * Queued at PM_POST_SUSPEND: the sleep failed before ->prepare() reached this + * device, so ->complete() didn't run either. + */ static void apple_drm_pm_resume_work(struct work_struct *work) { struct apple_drm_private *apple = @@ -2161,7 +2173,9 @@ static int apple_drm_pm_notify(struct notifier_block *nb, unsigned long action, struct apple_drm_private *apple; int ret; - if (action == PM_SUSPEND_PREPARE) + /* No restore queued by the last PM_POST_SUSPEND overlaps the next transition. */ + if (action == PM_SUSPEND_PREPARE || action == PM_HIBERNATION_PREPARE || + action == PM_RESTORE_PREPARE) flush_workqueue(apple_drm_pm_wq); /* The T8132 external outputs' sleep handling (a no-op without them). */ @@ -2231,11 +2245,14 @@ static int __init appledrm_register(void) ret = -ENOMEM; goto unregister_dcp; } - register_pm_notifier(&apple_drm_pm_nb); + ret = register_pm_notifier(&apple_drm_pm_nb); + if (ret) + goto destroy_wq; ret = platform_driver_register(&apple_platform_driver); if (!ret) return 0; unregister_pm_notifier(&apple_drm_pm_nb); +destroy_wq: destroy_workqueue(apple_drm_pm_wq); unregister_dcp: dcp_unregister(); diff --git a/drivers/gpu/drm/apple/t8132_ext_drm.c b/drivers/gpu/drm/apple/t8132_ext_drm.c index f37290b351669e..8a03c13d642ab2 100644 --- a/drivers/gpu/drm/apple/t8132_ext_drm.c +++ b/drivers/gpu/drm/apple/t8132_ext_drm.c @@ -900,7 +900,7 @@ static void t8132_ext_relink_end(struct t8132_ext_out *out) * display DART and a frame shown, iomfb_m4_ext_restore_result()) sets the * connector's link status BAD and sends a hotplug event: the compositor has * to set the mode again. A display released for the sleep was waited for - * before (t8132_ext_pm_notify()); its connector's hold ends here, and the + * before (t8132_ext_drm_pm_event()); its connector's hold ends here, and the * hotplug held meanwhile goes out at the end. */ static void t8132_ext_sleep_restore(struct t8132_ext_out *out) @@ -993,9 +993,10 @@ static void t8132_ext_sleep_end(struct t8132_ext_out *out) } /* - * The layer's one PM notifier, for every output. A refused sleep gets - * no PM_POST_SUSPEND here (the chain rolls back only the notifiers before - * this one): the outputs already prepared come back at once. + * The layer's sleep handling, for every output, called from appledrm's PM + * notifier (apple_drm_pm_notify()). A sleep this refuses gets no + * PM_POST_SUSPEND here, since the chain rolls back only the notifiers before + * appledrm's: the outputs already prepared come back at once. */ int t8132_ext_drm_pm_event(unsigned long event) { From e871c03cec199dd4ed93f5d8d649b1c735020c5f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:57:14 +1100 Subject: [PATCH 0394/1514] soc: apple: rtkit: adopt a running session with its endpoint map A co-processor that a boot stage handed over running does not repeat HELLO or EPMAP, so its new owner cannot learn the endpoints from the firmware. apple_rtkit_init_adopted() and _with_buffers() assume every system endpoint and know no application endpoint, so apple_rtkit_start_ep() refuses all of the firmware's own services. Add apple_rtkit_init_adopted_with_session(). It takes what the previous owner negotiated: the protocol version, the endpoint map the firmware advertised and the retained system buffers. The map is copied before mailbox RX starts. Management must be in it, and a system endpoint this driver does not implement makes the session invalid instead of being ignored. Application endpoints are only advertised: the new owner starts each one as usual. The existing initialisers keep their behaviour. Signed-off-by: Ryan Murray --- drivers/soc/apple/rtkit.c | 72 ++++++++++++++++++++++++++++++--- include/linux/soc/apple/rtkit.h | 22 ++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..541f8428402648 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2289,12 +2289,54 @@ static int apple_rtkit_inherit_buffers( return 0; } +/* + * The endpoint map the previous owner received for this session. Management + * is always present; system endpoints are limited to those RTKit implements + * here, so that an unknown one is not silently ignored. + */ +static int apple_rtkit_inherit_endpoints( + struct apple_rtkit *rtk, const struct apple_rtkit_adopted_session *session) +{ + static const u8 system_endpoints[] = { + APPLE_RTKIT_EP_MGMT, APPLE_RTKIT_EP_CRASHLOG, + APPLE_RTKIT_EP_SYSLOG, APPLE_RTKIT_EP_DEBUG, + APPLE_RTKIT_EP_IOREPORT, APPLE_RTKIT_EP_COREANALYTICS, + APPLE_RTKIT_EP_OSLOG, APPLE_RTKIT_EP_TRACEKIT, + }; + DECLARE_BITMAP(known, APPLE_RTKIT_APP_ENDPOINT_START) = {}; + DECLARE_BITMAP(map, APPLE_RTKIT_MAX_ENDPOINTS); + unsigned int i; + + BUILD_BUG_ON(APPLE_RTKIT_ADOPTED_EPMAP_WORDS * 32 != + APPLE_RTKIT_MAX_ENDPOINTS); + + if (session->protocol_version < APPLE_RTKIT_MIN_SUPPORTED_VERSION || + session->protocol_version > APPLE_RTKIT_MAX_SUPPORTED_VERSION || + (rtk->ops->protocol_version && + session->protocol_version != rtk->ops->protocol_version)) + return -EINVAL; + + bitmap_from_arr32(map, session->epmap, APPLE_RTKIT_MAX_ENDPOINTS); + for (i = 0; i < ARRAY_SIZE(system_endpoints); i++) + set_bit(system_endpoints[i], known); + if (!test_bit(APPLE_RTKIT_EP_MGMT, map)) + return -EINVAL; + for (i = 0; i < APPLE_RTKIT_APP_ENDPOINT_START; i++) + if (test_bit(i, map) && !test_bit(i, known)) + return -EINVAL; + + bitmap_copy(rtk->endpoints, map, APPLE_RTKIT_MAX_ENDPOINTS); + rtk->version = session->protocol_version; + return 0; +} + static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops, bool adopted, const struct apple_rtkit_inherited_buffer *buffers, - unsigned int count, bool track_saved) + unsigned int count, bool track_saved, + const struct apple_rtkit_adopted_session *session) { struct apple_rtkit *rtk; int ret; @@ -2376,6 +2418,12 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, /* Inherited system traffic may arrive as soon as mailbox RX is armed. */ if (adopted) apple_rtkit_mark_running(rtk); + /* The firmware's own endpoint map replaces the assumed one. */ + if (session) { + ret = apple_rtkit_inherit_endpoints(rtk, session); + if (ret) + goto destroy_wq; + } ret = apple_rtkit_claim_rx(rtk); if (ret) @@ -2403,7 +2451,7 @@ struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie, const struct apple_rtkit_ops *ops) { return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, - NULL, 0, false); + NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init); @@ -2412,7 +2460,7 @@ struct apple_rtkit *apple_rtkit_init_adopted(struct device *dev, void *cookie, const struct apple_rtkit_ops *ops) { return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, - NULL, 0, false); + NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted); @@ -2471,10 +2519,24 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_buffers( const struct apple_rtkit_inherited_buffer *buffers, unsigned int count) { return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, - buffers, count, false); + buffers, count, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted_with_buffers); +struct apple_rtkit *apple_rtkit_init_adopted_with_session( + struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, + const struct apple_rtkit_ops *ops, + const struct apple_rtkit_adopted_session *session) +{ + if (!session) + return ERR_PTR(-EINVAL); + + return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, + session->buffers, session->num_buffers, false, + session); +} +EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted_with_session); + static int apple_rtkit_wait_for_completion(struct apple_rtkit *rtk, struct completion *c) { @@ -3528,7 +3590,7 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo int ret; rtk = __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, - NULL, 0, true); + NULL, 0, true, NULL); if (IS_ERR(rtk)) return rtk; ret = devm_add_action_or_reset(dev, apple_rtkit_free_wrapper, rtk); diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 4db916bb89f09d..0e604bf2b5932b 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -186,6 +186,28 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_buffers( const struct apple_rtkit_ops *ops, const struct apple_rtkit_inherited_buffer *buffers, unsigned int count); +#define APPLE_RTKIT_ADOPTED_EPMAP_WORDS 8 + +/* + * Negotiated state from the previous owner of a running session: the + * protocol version, the endpoint map the firmware advertised (word i holds + * endpoints 32i..32i+31) and the retained system buffers. The parent driver + * verifies that the co-processor runs and the backing of each buffer. + * Application endpoints in the map each need a start from the new owner. + * Everything is copied before mailbox RX starts. + */ +struct apple_rtkit_adopted_session { + const struct apple_rtkit_inherited_buffer *buffers; + unsigned int num_buffers; + u32 epmap[APPLE_RTKIT_ADOPTED_EPMAP_WORDS]; + u16 protocol_version; +}; + +struct apple_rtkit *apple_rtkit_init_adopted_with_session( + struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, + const struct apple_rtkit_ops *ops, + const struct apple_rtkit_adopted_session *session); + /* * Free an instance of apple_rtkit. */ From abea85f0c40b673e2c8f76e7f71c5eb6b3b09721 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:57:15 +1100 Subject: [PATCH 0395/1514] drm/apple: dcp: admit a firmware-27 DCP by its method table dcp_check_firmware_version() admits the 27.x firmware ABI per SoC (T8122, T6041, the firmware-27 match data). A DCP whose loader reports a 27.x firmware-compat with a complete method table on another SoC, such as the M2 Mac mini's on the 27.2 stub, is refused with "firmware-compat 27.2.0 is not supported" although the table exists. When no legacy implementation matched, accept the reported ABI if iomfb_v27_methods() has a table for it. Nothing changes for a version a legacy path already handles or for one without a table. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 39bccc811e160f..317752aa45c20a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6120,6 +6120,14 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) (strncmp(fw_str, "14.7.0", sizeof(compat_str)) == 0)) return DCP_FIRMWARE_V_14_7_TEMPLATE; + /* + * The loader reports the method ABI for each DCP. Legacy match data + * leaves the ABI to this property, so accept a complete table here + * when the reported ABI has no legacy implementation. + */ + if (iomfb_v27_methods(compat_str)) + return dcp_v27_method_table(dev, compat_str); + dev_err(dev, "DCP firmware-compat %s (FW: %s) is not supported\n", compat_str, fw_str); From 3563449568b92e5fa7265af96826737e3ef1e7b6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:57:30 +1100 Subject: [PATCH 0396/1514] drm/apple: dcp: adopt a DCP that a boot stage handed over running A boot stage that drives a display through a DCP can hand the DCP on running, its RTKit session negotiated and its system buffers mapped. Such firmware does not repeat HELLO or EPMAP, so apple_rtkit_wake() times out in endpoint discovery (-ETIME) and the DRM device does not bind. The boot stage describes the session on the DCP node: apple,rtkit-live (layout 1), apple,rtkit-version, apple,rtkit-epmap (eight cells, cell i = endpoints 32i..32i+31) and apple,rtkit-live-buffers ( for each system buffer). When the node has it, check that the co-processor runs, that each buffer lies inside one of the node's reserved-memory carveouts (the regions the IOMMU core keeps mapped when it takes over a locked display DART) and that the DART translates its IOVA to that memory. Then initialise RTKit with the adopted session and skip the wake. An unknown layout or a buffer that fails a check fails the bind instead of starting the firmware a second time. Behaviour follows the description, not the SoC or firmware version: hw.adopt_live_session is set from the property, and a DCP without it boots as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp.c | 179 ++++++++++++++++++++++++++- 2 files changed, 179 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..68ccf32aad9306 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -473,6 +473,8 @@ struct apple_dcp { struct iomfb_m4 *v26_6; /* An adopted session has no confirmed firmware DMA stop boundary. */ bool retain_dma; + /* RTKit session handed over running by a boot stage (apple,rtkit-live) */ + bool rtkit_adopted; /* * Allocates AFK rings where the DMA API cannot, on an adopted * J713 external DCP whose DART only takes the retained allocator. diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 317752aa45c20a..bd8eb7c6a368a0 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -1843,6 +1844,160 @@ static int dcp_check_iova_contiguous(struct iommu_domain *domain, return 0; } +#define DCP_RTKIT_LIVE_V1 1 +#define DCP_RTKIT_LIVE_BUFFER_CELLS 8 +#define DCP_RTKIT_LIVE_MAX_BUFFERS 4 +#define DCP_RTKIT_LIVE_LOADER_OWNED BIT(0) + +struct dcp_rtkit_live { + struct apple_rtkit_adopted_session session; + struct apple_rtkit_inherited_buffer buffers[DCP_RTKIT_LIVE_MAX_BUFFERS]; +}; + +/* + * Inside one of this DCP's reserved-memory carveouts. Those are also what the IOMMU + * core rebuilds the DCP's DART mappings from when it takes over a locked + * root, so a buffer outside them would lose its mapping at attach. + */ +static bool dcp_rtkit_live_carveout(struct device_node *np, phys_addr_t phys, + size_t size) +{ + int i, count = of_count_phandle_with_args(np, "memory-region", NULL); + bool found = false; + + for (i = 0; !found && i < count; i++) { + struct device_node *mem = of_parse_phandle(np, "memory-region", i); + struct reserved_mem *rmem; + + if (!mem) + break; + rmem = of_reserved_mem_lookup(mem); + /* A reusable (CMA) region could be handed out by the kernel. */ + found = rmem && !of_property_present(mem, "reusable") && + phys >= rmem->base && size <= rmem->size && + phys - rmem->base <= rmem->size - size; + of_node_put(mem); + } + return found; +} + +static void dcp_rtkit_live_unmap(struct dcp_rtkit_live *live) +{ + unsigned int i; + + for (i = 0; i < live->session.num_buffers; i++) + vunmap(live->buffers[i].shmem.private); + live->session.num_buffers = 0; +} + +/* + * A boot stage that negotiated RTKit with this DCP and handed it over running + * describes the session on the node: apple,rtkit-live (layout version), + * apple,rtkit-version, apple,rtkit-epmap (word i = endpoints 32i..32i+31) and + * apple,rtkit-live-buffers ( per system buffer, each inside one of the node's memory-region + * carveouts and mapped there through its iommu-addresses). Such a firmware + * does not repeat HELLO or EPMAP. Returns 1 with the session filled in, 0 without a description, or an + * error for one that cannot be adopted safely. + */ +static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *live) +{ + u32 cells[DCP_RTKIT_LIVE_MAX_BUFFERS * DCP_RTKIT_LIVE_BUFFER_CELLS]; + struct device_node *np = dcp->dev->of_node; + struct iommu_domain *domain; + u32 layout, version; + int count, i, ret; + + if (!of_property_present(np, "apple,rtkit-live")) + return 0; + ret = of_property_read_u32(np, "apple,rtkit-live", &layout); + if (ret) + return ret; + if (layout != DCP_RTKIT_LIVE_V1) { + dev_err(dcp->dev, "unknown live RTKit layout %u\n", layout); + return -EINVAL; + } + if (!(readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & + APPLE_DCP_COPROC_CPU_CONTROL_RUN)) { + dev_err(dcp->dev, "live RTKit session without a running CPU\n"); + return -ENODEV; + } + ret = of_property_read_u32(np, "apple,rtkit-version", &version); + if (ret || version > U16_MAX) + return ret ?: -EINVAL; + live->session.protocol_version = version; + ret = of_property_read_u32_array(np, "apple,rtkit-epmap", + live->session.epmap, + APPLE_RTKIT_ADOPTED_EPMAP_WORDS); + if (ret) + return ret; + + count = of_property_count_u32_elems(np, "apple,rtkit-live-buffers"); + if (count == -EINVAL) + count = 0; + if (count < 0 || count > ARRAY_SIZE(cells) || + count % DCP_RTKIT_LIVE_BUFFER_CELLS) + return -EINVAL; + if (count) { + ret = of_property_read_u32_array(np, "apple,rtkit-live-buffers", + cells, count); + if (ret) + return ret; + } + count /= DCP_RTKIT_LIVE_BUFFER_CELLS; + + domain = iommu_get_domain_for_dev(dcp->dev); + if (count && !domain) + return -ENODEV; + + live->session.buffers = live->buffers; + for (i = 0; i < count; i++) { + const u32 *t = &cells[i * DCP_RTKIT_LIVE_BUFFER_CELLS]; + struct apple_rtkit_inherited_buffer *b = &live->buffers[i]; + u64 iova = (u64)t[2] << 32 | t[3]; + u64 phys = (u64)t[4] << 32 | t[5]; + u64 size = (u64)t[6] << 32 | t[7]; + + if (t[0] > U8_MAX || (t[1] & ~DCP_RTKIT_LIVE_LOADER_OWNED) || + !size || size > SZ_16M || !PAGE_ALIGNED(phys) || + !PAGE_ALIGNED(size) || iova + size < iova || + phys + size < phys) { + ret = -EINVAL; + goto fail; + } + if (!dcp_rtkit_live_carveout(np, phys, size)) { + dev_err(dcp->dev, "live RTKit buffer %#llx+%#llx is not in a DCP carveout\n", + phys, size); + ret = -EACCES; + goto fail; + } + /* The DCP's own DART must already translate it to that memory. */ + ret = dcp_check_iova_contiguous(domain, iova, size, phys); + if (ret) { + dev_err(dcp->dev, + "live RTKit buffer ep%u iova %#llx is not mapped to %#llx (DART: %pa)\n", + t[0], iova, phys, + &(phys_addr_t){ iommu_iova_to_phys(domain, iova) }); + goto fail; + } + + /* Firmware writes without CPU cache maintenance. */ + ret = dcp_vmap_wc(phys, size, &b->shmem.iomem, &b->shmem.private); + if (ret) + goto fail; + b->endpoint = t[0]; + b->shmem.iova = iova; + b->shmem.size = size; + b->shmem.is_mapped = true; + live->session.num_buffers = i + 1; + } + return 1; + +fail: + dcp_rtkit_live_unmap(live); + return ret; +} + static int dcp_rtk_shmem_setup(void *cookie, struct apple_rtkit_shmem *bfr) { struct apple_dcp *dcp = cookie; @@ -6459,7 +6614,9 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat { struct device_node *panel_np; struct apple_dcp *dcp = dev_get_drvdata(dev); + struct dcp_rtkit_live live_rtkit = {}; u32 cpu_ctrl; + int live = 0; int ret; if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) { @@ -6719,8 +6876,18 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat ret = dcp_pin_live_session(dcp); if (ret) goto err_piodma; + live = dcp_rtkit_live_parse(dcp, &live_rtkit); + if (live < 0) { + ret = dev_err_probe(dev, live, "Invalid live RTKit handoff\n"); + goto err_piodma; + } /* External H17P supplies shared-buffer addresses during RTKit startup. */ - if (dcp->hw.iomfb_method_profile == + if (live) + dcp->rtk = apple_rtkit_init_adopted_with_session( + dev, dcp, "mbox", 0, + dcp->hw.link_report ? &link_report_rtkit_ops : &rtkit_ops, + &live_rtkit.session); + else if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) dcp->rtk = apple_rtkit_init(dev, dcp, "mbox", 0, &external_h17p_rtkit_ops); @@ -6729,6 +6896,8 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat else dcp->rtk = apple_rtkit_init(dev, dcp, "mbox", 0, &rtkit_ops); if (IS_ERR(dcp->rtk)) { + if (live) + dcp_rtkit_live_unmap(&live_rtkit); ret = dev_err_probe(dev, PTR_ERR(dcp->rtk), "Failed to initialize RTKit\n"); goto err_piodma; @@ -6736,6 +6905,7 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat ret = devm_add_action_or_reset(dev, dcp_release_rtkit, dcp); if (ret) goto err_piodma; + dcp->rtkit_adopted = live; dcp_s2r_check_dt(dcp); /* After a warm restart its log counters need echoing, or it refuses its next idle. */ if (dcp->hw.s2r || dcp->hw.s2r_ext) @@ -6748,7 +6918,9 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat dev_dbg(dev, "negotiating RTKit with the running DCP\n"); /* Announce host readiness before awaiting external IOP readiness. */ - if (dcp->hw.iomfb_method_profile == + if (live) + ret = 0; /* HELLO and EPMAP happened before the handoff */ + else if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL) ret = apple_rtkit_wake_early_ap(dcp->rtk); else if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) @@ -7319,6 +7491,9 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (ret) return ret; dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); + /* A boot stage handed this DCP over running: keep its session. */ + if (of_property_present(dev->of_node, "apple,rtkit-live")) + dcp->hw.adopt_live_session = true; /* The link report: on the board it has run on (dcp_j714s_ext()). */ if (!dcp_j714s_ext(dev)) dcp->hw.link_report = false; From 86f405f50a5b23ff84be530fea02e6d0ad9e732c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:57:30 +1100 Subject: [PATCH 0397/1514] drm/apple: dcp: retrain an adopted DP2HDMI port's link A boot stage that handed a DCP over running left its DPTX port's display up, on a link it trained. The firmware then has no sink: it lists its default modes (640x480, 800x600, 1024x768) and no EDID. It sends no link configuration for a link that is already trained, so dcp_dptx_connect() withdrew the display after its timeout. On an adopted session, drop the port's HPD and release its display when the endpoints start. The next connect then trains the link and the firmware reads the sink again. Raise HPD after the link wait on an adopted DP2HDMI port, so that the firmware sees the display plugged (HPD is otherwise left to the converter on that output). The link wait on a DP2HDMI output was non-fatal only on the 13.5 firmware line. The reason is the output, not the firmware: the converter holds HPD and the firmware is not asked to detect the sink. So key it on the output alone. This only affects a wait that used to time out and withdraw the display. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 38 ++++++++++++++----- .../drivers/gpu/apple-dcp/lifecycle.py | 2 +- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bd8eb7c6a368a0..a2ad08dbbef9c5 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2467,16 +2467,15 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable bool late_hpd = dcp_ext_dptx_607(dcp); bool t8132 = dcp_is_t8132_ext(dcp); /* - * A DP2HDMI output on the 13.5 firmware line asserts its own HPD, in - * dcp_enable_dp2hdmi_hpd(), and the connect asks the firmware for HPD - * only on a DisplayPort connector or a late-HPD path, so this firmware - * is never asked to detect the sink and never sends the link - * configuration the wait below looks for. Treat the timeout as - * non-fatal, as the compact and late-HPD cases do, instead of - * withdrawing the display. + * A DP2HDMI output asserts its own HPD, in dcp_enable_dp2hdmi_hpd(), + * and the connect asks the firmware for HPD only on a DisplayPort + * connector or a late-HPD path, so the firmware is never asked to + * detect the sink and need not send the link configuration the wait + * below looks for (nor does one whose link a boot stage already + * trained). Treat the timeout as non-fatal, as the compact and + * late-HPD cases do, instead of withdrawing the display. */ - bool dp2hdmi = dcp->hdmi_hpd && !dcp_is_typec_output(dcp) && - dcp->fw_compat == DCP_FIRMWARE_V_13_5; + bool dp2hdmi = dcp->hdmi_hpd && !dcp_is_typec_output(dcp); bool compact, withdrawn; unsigned long timeout; u64 generation; @@ -2674,7 +2673,8 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable usleep_range(5, 10); - if (dcp->connector_type == DRM_MODE_CONNECTOR_DisplayPort || late_hpd) { + if (dcp->connector_type == DRM_MODE_CONNECTOR_DisplayPort || late_hpd || + (dp2hdmi && dcp->rtkit_adopted)) { ret = dptxport_set_hpd(dcp->dptxport[port].service, true); if (ret && late_hpd) dev_err(dcp->dev, @@ -4915,6 +4915,24 @@ int dcp_start(struct platform_device *pdev) if (ret) { dev_warn(dcp->dev, "Failed to start DPTX endpoint: %d\n", ret); + } else if (dcp->rtkit_adopted && + dptx_service_available(&dcp->dptxport[0])) { + /* + * The boot stage that handed this DCP over left the + * port's display up on a link it trained. Release it, + * so that the next connect trains the link and reads + * the sink again: until then the firmware only has its + * default modes and no EDID. Its HPD goes low as well; + * dcp_dptx_connect() raises it again after the link wait, + * so that the firmware sees the display plugged. + */ + ret = dptxport_set_hpd(dcp->dptxport[0].service, false); + if (!ret) + ret = dptxport_release_display(dcp->dptxport[0].service); + if (ret) + dev_warn(dcp->dev, "adopted DPTX display not released: %d\n", + ret); + ret = 0; #ifdef DCP_DPTX_DISCONNECT_ON_INIT /* * This disconnect / connect cycle on init is only necessary diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..bd749368aa8209 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -595,7 +595,7 @@ def swap(old, new): ' struct { bool connected, closed, tile_hint; void *service, *atcphy; int linkcfg_completion; } dptxport[1];\n' ' void *phy, *dev, *active_typec_route;\n' ' int dptx_die, dptx_phy, dptx_dfp_port, connector_type;\n' - ' bool external, external_link_ready, crashed;\n' + ' bool external, external_link_ready, crashed, rtkit_adopted;\n' ' bool typec_work_enabled;' + ('' if '\n int fw_compat;' in unit else ' int fw_compat;') + ' struct { bool fw_14_7_endpoints; } hw;\n' ' struct { bool active; } split;\n' From 748c27a5be2deda24ea8f2f14217827ba7d158fc Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 14:05:28 -0500 Subject: [PATCH 0398/1514] thunderbolt: preserve direct XDomain discovery across s2idle on awake Apple routers On Apple NHIs the host router stays powered through suspend-to-idle: the Apple driver sets QUIRK_NO_SYSTEM_SLEEP whenever its routers are not put to sleep (router_sleep off, the default). tb_domain_suspend_noirq() still stops the control channel. As the host suspends, a direct XDomain peer sends a round of discovery requests: on J775c with a Mac as the peer, four UUID and four properties requests. With the channel stopped they go unanswered, and the peer drops the link. On resume the router reports a cold start, port 0:1 fails to reach TB_PORT_UP, and the XDomain is disconnected and not found again: thunderbolt0 is gone after every s2idle. Keep the control channel running through noirq for that case only: a suspend without platform support (pm_suspend_no_platform()) on a host with QUIRK_NO_SYSTEM_SLEEP, and a root switch whose links are direct XDomain links with no device router behind them (tb_domain_retain_noirq_control()). Only the Apple driver sets QUIRK_NO_SYSTEM_SLEEP, so other NHIs are unchanged. While the channel runs, only XDomain discovery requests are handled: UUID, properties and link-state status are answered. Everything else is dropped, and an error-state handshake is not restarted until resume. On J775c the requests arrive and are answered at noirq suspend, before the system idles, and none follow during the sleep (10 s or 120 s) or after it. A peer that leaves during the sleep is still found at resume: tb_switch_resume() waits for each XDomain port and marks the XDomain unplugged if its link does not come back. Every other suspend stops the channel as before. Signed-off-by: Satya Benson --- drivers/thunderbolt/domain.c | 47 ++++++++++++++++++++++++++++++++--- drivers/thunderbolt/xdomain.c | 18 +++++++++++++- include/linux/thunderbolt.h | 2 ++ 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/drivers/thunderbolt/domain.c b/drivers/thunderbolt/domain.c index a06539264971c5..e77c0eab18cc46 100644 --- a/drivers/thunderbolt/domain.c +++ b/drivers/thunderbolt/domain.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -338,6 +339,10 @@ static bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, { struct tb *tb = data; + /* During noirq only XDomain discovery requests can receive a reply. */ + if (READ_ONCE(tb->noirq_ctl_retained) && type != TB_CFG_PKG_XDOMAIN_REQ) + return true; + if (!tb->cm_ops->handle_event) { tb_warn(tb, "domain does not have event handler\n"); return true; @@ -528,11 +533,34 @@ void tb_domain_remove(struct tb *tb) } EXPORT_SYMBOL_FOR_MODULES(tb_domain_remove, "thunderbolt_apple"); +static bool tb_domain_retain_noirq_control(struct tb *tb) +{ + struct tb_port *port; + bool xdomain = false; + + lockdep_assert_held(&tb->lock); + + if (!pm_suspend_no_platform() || + !(tb->nhi->quirks & QUIRK_NO_SYSTEM_SLEEP) || + !tb->root_switch) + return false; + + tb_switch_for_each_port(tb->root_switch, port) { + if (tb_port_has_remote(port)) + return false; + if (port->xdomain) + xdomain = true; + } + + return xdomain; +} + /** * tb_domain_suspend_noirq() - Suspend a domain * @tb: Domain to suspend * - * Suspends all devices in the domain and stops the control channel. + * Suspends all devices in the domain. Stops the control channel unless + * an awake host router needs it for direct XDomain discovery. * * Return: %0 on success, negative errno otherwise. */ @@ -548,8 +576,14 @@ int tb_domain_suspend_noirq(struct tb *tb) mutex_lock(&tb->lock); if (tb->cm_ops->suspend_noirq) ret = tb->cm_ops->suspend_noirq(tb); - if (!ret) - tb_ctl_stop(tb->ctl); + if (!ret) { + if (tb_domain_retain_noirq_control(tb)) { + WRITE_ONCE(tb->noirq_ctl_retained, true); + tb_dbg(tb, "XDomain control channel retained for s2idle\n"); + } else { + tb_ctl_stop(tb->ctl); + } + } mutex_unlock(&tb->lock); return ret; @@ -570,9 +604,14 @@ int tb_domain_resume_noirq(struct tb *tb) int ret = 0; mutex_lock(&tb->lock); - tb_ctl_start(tb->ctl); + if (!tb->noirq_ctl_retained) + tb_ctl_start(tb->ctl); if (tb->cm_ops->resume_noirq) ret = tb->cm_ops->resume_noirq(tb); + if (tb->noirq_ctl_retained) { + WRITE_ONCE(tb->noirq_ctl_retained, false); + tb_dbg(tb, "XDomain control channel remained active\n"); + } mutex_unlock(&tb->lock); return ret; diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index 857219a9ac8da8..fd45c77a8bf343 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -831,7 +831,8 @@ static void tb_xdp_handle_request(struct work_struct *work) * timing out, we will restart the handshake now that we * received UUID request from the remote host. */ - if (!ret && xd && xd->state == XDOMAIN_STATE_ERROR) { + if (!READ_ONCE(tb->noirq_ctl_retained) && !ret && xd && + xd->state == XDOMAIN_STATE_ERROR) { mutex_lock(&xd->lock); if (!xd->removing) { dev_dbg(&xd->dev, "restarting handshake\n"); @@ -2666,6 +2667,21 @@ bool tb_xdomain_handle_request(struct tb *tb, enum tb_cfg_pkg_type type, if (length < sizeof(*hdr) / 4 - sizeof(hdr->xd_hdr) / 4) return true; + if (READ_ONCE(tb->noirq_ctl_retained)) { + if (type != TB_CFG_PKG_XDOMAIN_REQ || !uuid_equal(&hdr->uuid, &tb_xdp_uuid)) + return true; + switch (hdr->type) { + case UUID_REQUEST_OLD: + case UUID_REQUEST: + case PROPERTIES_REQUEST: + case LINK_STATE_STATUS_REQUEST: + tb_dbg(tb, "XDomain discovery request %#x during s2idle\n", hdr->type); + break; + default: + return true; + } + } + /* * Handle XDomain discovery protocol packets directly here. For * other protocols (based on their UUID) we call registered diff --git a/include/linux/thunderbolt.h b/include/linux/thunderbolt.h index acd1668ed93d74..bf1b07f993b8e8 100644 --- a/include/linux/thunderbolt.h +++ b/include/linux/thunderbolt.h @@ -74,6 +74,7 @@ enum tb_security_level { * @remote_activity: Successful stock remote discovery exchanges * @nhi: Pointer to the NHI structure * @ctl: Control channel for this domain + * @noirq_ctl_retained: Control rings stayed active during noirq suspend * @wq: Ordered workqueue for all domain specific work * @root_switch: Root switch of this domain * @cm_ops: Connection manager specific operations vector @@ -88,6 +89,7 @@ struct tb { atomic64_t remote_activity; struct tb_nhi *nhi; struct tb_ctl *ctl; + bool noirq_ctl_retained; struct workqueue_struct *wq; struct tb_switch *root_switch; const struct tb_cm_ops *cm_ops; From bd272902b68c0ac9944852174d3fffeef4d0586b Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 14:05:29 -0500 Subject: [PATCH 0399/1514] thunderbolt: xdomain: handle discovery requests under the domain lock With the control channel kept through s2idle, tb_xdomain_handle_request() only schedules the read-only discovery requests (UUID, properties, link state status). But the request work runs later on system_wq, and only the scheduling side checked noirq_ctl_retained: CPU0 (system_wq) CPU1 (suspend) tb_xdomain_handle_request() noirq_ctl_retained == false schedule_work(PROPERTIES_CHANGED) tb_domain_suspend_noirq() mutex_lock(&tb->lock) ->suspend_noirq() noirq_ctl_retained = true mutex_unlock(&tb->lock) tb_xdp_handle_request() PROPERTIES_CHANGED_REQUEST queue xd->state_work (noirq: the domain is suspended) A LINK_STATE_CHANGE_REQUEST queued the same way does the same, and an allowed LINK_STATE_STATUS_REQUEST reads the downstream port with tb_port_read() without tb->lock, so it can run while tb_domain_suspend_noirq() or tb_domain_resume_noirq() works on the same domain. Handle each request under tb->lock, which those two hold while they set and clear noirq_ctl_retained, and re-check the flag there: a request other than discovery that arrives at the handler while the channel is retained gets ERROR_NOT_READY, and the peer asks again after resume. The port read now always runs under tb->lock. Both sides use one helper for the allowed requests. Lock order: tb->lock is taken before xdomain_lock and xd->lock here, as in the existing callers that hold tb->lock and take xd->lock; nothing takes tb->lock under either. tb_xdp_handle_request() then looks the XDomain up with tb_xdomain_find_by_route(), which expects the caller to hold tb->lock, not tb_xdomain_find_by_route_locked(), which takes it again. Signed-off-by: Satya Benson --- drivers/thunderbolt/xdomain.c | 44 +++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index fd45c77a8bf343..d174e7129191ca 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -759,6 +759,23 @@ static void stop_handshake(struct tb_xdomain *xd) __stop_handshake(xd); } +/* + * The XDomain discovery requests answered while the control channel is kept + * through s2idle (tb->noirq_ctl_retained): they only read state. + */ +static bool tb_xdp_noirq_request(enum tb_xdp_type type) +{ + switch (type) { + case UUID_REQUEST_OLD: + case UUID_REQUEST: + case PROPERTIES_REQUEST: + case LINK_STATE_STATUS_REQUEST: + return true; + default: + return false; + } +} + static void tb_xdp_handle_request(struct work_struct *work) { struct xdomain_request_work *xw = container_of(work, typeof(*xw), work); @@ -777,19 +794,28 @@ static void tb_xdp_handle_request(struct work_struct *work) sequence = xhdr->length_sn & TB_XDOMAIN_SN_MASK; sequence >>= TB_XDOMAIN_SN_SHIFT; + /* + * Handle the request under tb->lock. tb_domain_suspend_noirq() and + * tb_domain_resume_noirq() set and clear noirq_ctl_retained under it, + * so a request queued before the control channel was retained cannot + * run a non-discovery request (or touch a port) during noirq, and the + * port read below cannot overlap the domain's suspend or resume. + */ mutex_lock(&tb->lock); if (tb->root_switch) uuid = kmemdup(tb->root_switch->uuid, sizeof(*uuid), GFP_KERNEL); else uuid = NULL; - mutex_unlock(&tb->lock); - if (!uuid) { + if (!uuid || (READ_ONCE(tb->noirq_ctl_retained) && + !tb_xdp_noirq_request(pkg->type))) { tb_xdp_error_response(ctl, route, sequence, ERROR_NOT_READY); + mutex_unlock(&tb->lock); goto out; } - xd = tb_xdomain_find_by_route_locked(tb, route); + /* tb->lock is held: the _locked helper would take it again. */ + xd = tb_xdomain_find_by_route(tb, route); if (xd) update_property_block(xd); @@ -926,6 +952,7 @@ static void tb_xdp_handle_request(struct work_struct *work) } tb_xdomain_put(xd); + mutex_unlock(&tb->lock); if (ret) { tb_warn(tb, "failed to send XDomain response for %#x\n", @@ -2670,16 +2697,9 @@ bool tb_xdomain_handle_request(struct tb *tb, enum tb_cfg_pkg_type type, if (READ_ONCE(tb->noirq_ctl_retained)) { if (type != TB_CFG_PKG_XDOMAIN_REQ || !uuid_equal(&hdr->uuid, &tb_xdp_uuid)) return true; - switch (hdr->type) { - case UUID_REQUEST_OLD: - case UUID_REQUEST: - case PROPERTIES_REQUEST: - case LINK_STATE_STATUS_REQUEST: - tb_dbg(tb, "XDomain discovery request %#x during s2idle\n", hdr->type); - break; - default: + if (!tb_xdp_noirq_request(hdr->type)) return true; - } + tb_dbg(tb, "XDomain discovery request %#x during s2idle\n", hdr->type); } /* From f8accf4e6b8a6946424a4c47afdf70fe245cea3f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 23:17:45 -0500 Subject: [PATCH 0400/1514] iommu: apple-dart: narrow the T8132 radio's SID16 bypass to one page The radio DART's SID16 keeps the static bypass role it gets at boot for the whole uptime. A bypassed stream reaches all of physical memory, and the RID-to-SID admission cannot see which requester could be routed to it. At runtime the stream only writes one page: blocking it outright makes that write fault and the radio fail. When the DT names that page in apple,sid16-page, translate SID16 through a 3-level table that maps only it, identity, after admission and before any radio DMA is set up. Admission and the cold-link idle check accept the narrowed stream; the sleep snapshot and restore already carry its TCR and TTBR. Without the property the bypass is kept as before. Signed-off-by: Erik Bourget --- drivers/iommu/apple-dart.c | 193 +++++++++- .../drivers/apple/bcm4377-radio-sids.py | 336 +++++++++++++++++- 2 files changed, 518 insertions(+), 11 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index d66e87da3f560c..dfe9be07a9a8ad 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -532,6 +532,17 @@ struct apple_dart { bool cold_ane; u16 managed_sids; bool managed_failed; + /* + * The one page the radio's SID16 may reach, or 0 to keep its bypass. + * Its table is kept for the lifetime of the binding unless probe + * fails and tears the narrowing down before releasing the device. + */ + u64 sid16_page; + struct io_pgtable_ops *sid16_ops; + u32 sid16_ttbr; + u32 sid16_init_tcr; + u32 sid16_init_ttbr; + bool sid16_init_enabled; /* Serialize owned TCR publication against IRQ quarantine. */ spinlock_t managed_lock; struct apple_dart_sleep *sleep_record; @@ -2354,6 +2365,160 @@ static bool apple_dart_managed_static_bypass(u32 tcr) return (tcr & ~DART_T8110_TCR_BYPASS_DAPF) == DART_T8110_TCR_BYPASS_DART; } +/* SID16 translates through the one-page table this driver published. */ +static bool apple_dart_managed_sid16_narrowed(struct apple_dart *dart) +{ + u32 tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + + return dart->sid16_ops && tcr == DART_T8110_TCR_TRANSLATE_ENABLE && + apple_dart_readl(dart, DART_TTBR(dart, 16, 0)) == dart->sid16_ttbr && + (apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)); +} + +/* + * SID16 needs no more than one page, but a bypassed stream reaches all of + * physical memory, and nothing routes a requester to it that admission can + * check. Translate it through a table that maps only that page. Called after + * admission and before any radio DMA is set up; the SID16 TLB is flushed after + * switching TCR to translate so no firmware entry survives. + */ +static int apple_dart_managed_narrow_sid16(struct apple_dart *dart) +{ + struct apple_dart_stream_map stream = { .dart = dart }; + struct io_pgtable_cfg cfg = { + .pgsize_bitmap = SZ_16K, + .ias = 36, + .oas = dart->oas, + .coherent_walk = 1, + .iommu_dev = dart->dev, + }; + struct io_pgtable_ops *ops; + size_t mapped = 0; + phys_addr_t root; + u32 tcr, ttbr, init_tcr, init_ttbr; + int ret; + + if (dart->hw->type != DART_T8110 || dart->num_streams <= 16 || + dart->hw->ttbr_count != 1 || dart->pgsize != SZ_16K || + dart->oas < 36 || dart->sid16_page >= BIT_ULL(dart->oas)) + return -EINVAL; + if (dart->sid16_ops) + return -EBUSY; + init_tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + init_ttbr = apple_dart_readl(dart, DART_TTBR(dart, 16, 0)); + if (init_tcr == dart->hw->tcr_disabled) { + if (init_ttbr & dart->hw->ttbr_valid) + return -EBUSY; + } else if (apple_dart_managed_static_bypass(init_tcr)) { + if (!dart->supports_bypass || !dart->hw->tcr_bypass) + return -EBUSY; + } else { + return -EBUSY; + } + ops = alloc_io_pgtable_ops(APPLE_DART2, &cfg, NULL); + if (!ops) + return -ENOMEM; + if (cfg.apple_dart_cfg.n_ttbrs != 1 || cfg.apple_dart_cfg.n_levels != 3) { + ret = -EINVAL; + goto err_free; + } + ret = ops->map_pages(ops, dart->sid16_page, dart->sid16_page, SZ_16K, 1, + IOMMU_READ | IOMMU_WRITE | IOMMU_MMIO, GFP_KERNEL, &mapped); + if (!ret && (mapped != SZ_16K || + ops->iova_to_phys(ops, dart->sid16_page) != dart->sid16_page)) + ret = -EIO; + if (ret) + goto err_free; + + dart->sid16_init_tcr = init_tcr; + dart->sid16_init_ttbr = init_ttbr; + dart->sid16_init_enabled = !!(apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)); + root = virt_to_phys(cfg.apple_dart_cfg.ttbr[0]); + dart->sid16_ttbr = dart->hw->ttbr_valid | + (root >> dart->hw->ttbr_shift) << dart->hw->ttbr_addr_field_shift; + /* From here on the table may be walked until torn down and flushed. */ + dart->sid16_ops = ops; + apple_dart_writel(dart, dart->sid16_ttbr, DART_TTBR(dart, 16, 0)); + ttbr = apple_dart_readl(dart, DART_TTBR(dart, 16, 0)); + if (ttbr != dart->sid16_ttbr) { + dev_err(dart->dev, "SID16 TTBR0 readback failed (TTBR0 %#x)\n", ttbr); + return -EIO; + } + /* Plain translation: sleep restore replays the TCR as it reads back. */ + apple_dart_writel(dart, DART_T8110_TCR_TRANSLATE_ENABLE, DART_TCR(dart, 16)); + tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + if (tcr != DART_T8110_TCR_TRANSLATE_ENABLE) { + dev_err(dart->dev, "SID16 narrowing readback failed (TCR %#x)\n", tcr); + return -EIO; + } + __set_bit(16, stream.sidmap); + ret = dart->hw->invalidate_tlb(&stream); + if (ret) { + dev_err(dart->dev, "SID16 TLB invalidation failed (%d)\n", ret); + return ret; + } + apple_dart_writel(dart, BIT(16), dart->hw->enable_streams); + if (!apple_dart_managed_sid16_narrowed(dart)) { + dev_err(dart->dev, "SID16 enable readback failed (ENABLE %#x)\n", + apple_dart_readl(dart, dart->hw->enable_streams)); + return -EIO; + } + dev_info(dart->dev, "SID16 bypass narrowed to page %#llx\n", dart->sid16_page); + return 0; + +err_free: + free_io_pgtable_ops(ops); + return ret; +} + +static void apple_dart_managed_unnarrow_sid16(struct apple_dart *dart) +{ + struct apple_dart_stream_map stream = { .dart = dart }; + u32 tcr, enabled, restore_tcr; + + if (!dart->sid16_ops) + return; + + __set_bit(16, stream.sidmap); + if (!dart->sid16_init_enabled) { + apple_dart_writel(dart, BIT(16), DART_T8110_DISABLE_STREAMS); + if (apple_dart_readl(dart, dart->hw->enable_streams) & BIT(16)) { + dev_warn(dart->dev, + "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + } + + /* + * Static bypass restores the documented bypass request (including DAPF) + * while checking exact readback against the saved entry TCR. + */ + restore_tcr = dart->sid16_init_tcr == dart->hw->tcr_disabled ? + dart->hw->tcr_disabled : dart->hw->tcr_bypass; + apple_dart_writel(dart, restore_tcr, DART_TCR(dart, 16)); + tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); + if (tcr != dart->sid16_init_tcr) { + dev_warn(dart->dev, "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + + apple_dart_writel(dart, dart->sid16_init_ttbr, DART_TTBR(dart, 16, 0)); + enabled = apple_dart_readl(dart, dart->hw->enable_streams); + if (apple_dart_readl(dart, DART_TTBR(dart, 16, 0)) != dart->sid16_init_ttbr || + !!(enabled & BIT(16)) != dart->sid16_init_enabled || + dart->hw->invalidate_tlb(&stream)) { + dev_warn(dart->dev, "failed to tear down SID16 narrowing; keeping page table\n"); + return; + } + + free_io_pgtable_ops(dart->sid16_ops); + dart->sid16_ops = NULL; + dart->sid16_ttbr = 0; + dart->sid16_init_tcr = 0; + dart->sid16_init_ttbr = 0; + dart->sid16_init_enabled = false; +} + static ssize_t j713_radio_fault_state_show(struct device *dev, struct device_attribute *attr, char *buf) { @@ -2463,9 +2628,15 @@ static int apple_dart_managed_admit(struct apple_dart *dart, bool *init_bypass) return -EBUSY; } } - /* ADT assigns SID16 a static bypass role, independently of radio data. */ + /* + * ADT assigns SID16 a static bypass role, independently of radio data. + * Once narrowed to its one page by this driver, it stays so. + */ reserved_tcr = apple_dart_readl(dart, DART_TCR(dart, 16)); - if (!apple_dart_managed_static_bypass(reserved_tcr)) { + if (dart->sid16_ops) { + if (!apple_dart_managed_sid16_narrowed(dart)) + return -EBUSY; + } else if (!apple_dart_managed_static_bypass(reserved_tcr)) { if (reserved_tcr != dart->hw->tcr_disabled || !dart->supports_bypass) return -EBUSY; for (idx = 0; idx < dart->hw->ttbr_count; idx++) @@ -5488,6 +5659,12 @@ static int apple_dart_probe(struct platform_device *pdev) ids[0] != 1 || ids[1] != 2) return -EINVAL; dart->managed_sids = BIT(1) | BIT(2); + /* An identity-mapped page needs a 36-bit, 3-level table. */ + if (of_property_present(dev->of_node, "apple,sid16-page") && + (of_property_read_u64(dev->of_node, "apple,sid16-page", &dart->sid16_page) || + !dart->sid16_page || !IS_ALIGNED(dart->sid16_page, SZ_16K) || + dart->sid16_page >= BIT_ULL(36))) + return dev_err_probe(dev, -EINVAL, "invalid apple,sid16-page\n"); } spin_lock_init(&dart->managed_lock); ret = apple_dart_cio_init(dart, resource_size(res), j713_display); @@ -5991,7 +6168,8 @@ static int apple_dart_probe(struct platform_device *pdev) ret = apple_dart_retain_radio(dart); if (ret) goto err_clk_disable; - if (init_bypass) { + /* With a named page, a disabled SID16 is narrowed, never bypassed. */ + if (init_bypass && !dart->sid16_page) { struct apple_dart_stream_map stream = { .dart = dart }; u32 bypass_tcr; @@ -6005,6 +6183,13 @@ static int apple_dart_probe(struct platform_device *pdev) } apple_dart_writel(dart, BIT(16), dart->hw->enable_streams); } + if (dart->sid16_page) { + ret = apple_dart_managed_narrow_sid16(dart); + if (ret) { + ret = dev_err_probe(dev, ret, "cannot narrow the SID16 bypass\n"); + goto err_clk_disable; + } + } /* ENABLE is write-one-to-set; no foreign stream changes state. */ apple_dart_writel(dart, dart->managed_sids, dart->hw->enable_streams); } else if (!dart->locked && !dart->retained_mtp && !dart->live_mtp && !dart->preserve_display) { @@ -6103,6 +6288,8 @@ static int apple_dart_probe(struct platform_device *pdev) err_clk_disable: if (dart->managed_sids && dart->retained && !READ_ONCE(dart->managed_failed)) apple_dart_managed_quarantine(dart); + if (dart->sid16_ops) + apple_dart_managed_unnarrow_sid16(dart); /* Do not schedule suspend on failed radio or display adoption. */ if (dart->retained || dart->preserve_display) pm_runtime_put_noidle(dev); diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index 3d1026008cbd9f..d7de456deabb9e 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -36,13 +36,22 @@ def main(): typedef uint16_t u16; typedef uint8_t u8; typedef uint32_t u32; -typedef uint64_t u64; +typedef unsigned long long u64; typedef u64 phys_addr_t; typedef unsigned long atomic_long_t; #define BIT(n) (1UL << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define SZ_16K 16384 +#define GFP_KERNEL 0 +#define IOMMU_READ 1 +#define IOMMU_WRITE 2 +#define IOMMU_MMIO 4 +#define APPLE_DART2 1 +#define DART_T8110_DISABLE_STREAMS 0xc20 #define WRITE_ONCE(x,v) ((x) = (v)) #define READ_ONCE(x) (x) -#define dev_err(...) ((void)0) +#define dev_err(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) +#define dev_warn(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) #define dev_err_probe(dev, error, ...) (error) #define dev_err_ratelimited(...) ((void)0) #define dev_dbg(dev,...) do { (void)(dev); if (false) fprintf(stderr,__VA_ARGS__); } while (0) @@ -110,26 +119,51 @@ def main(): void *dcp, *frontend[2]; struct { bool ready; } iommu; void *dev; - unsigned pgsize; + unsigned pgsize, oas; int num_streams; + u64 sid16_page; + struct io_pgtable_ops *sid16_ops; + u32 sid16_ttbr; + u32 sid16_init_tcr; + u32 sid16_init_ttbr; + bool sid16_init_enabled; u32 regs[0x5000/4]; }; struct apple_dart_stream_map { struct apple_dart *dart; unsigned long sidmap[4]; }; struct apple_dart_atomic_stream_map { struct apple_dart *dart; atomic_long_t sidmap[4]; }; static u32 apple_dart_readl(struct apple_dart *d, unsigned o) { return d->regs[o/4]; } -static unsigned enable_writes, all_writes, guard_calls, device_pins, noidle_puts; -static bool drop_bypass_write; +static unsigned enable_writes, disable_writes, all_writes, guard_calls, device_pins, noidle_puts; +static bool drop_bypass_write, drop_enable_write, drop_disable_write, drop_ttbr_write; +static bool tcr_clear_dapf, sid16_saw_translate; +static unsigned sid16_tcr_writes; +static u32 last_sid16_tcr_write; static int guard_result, apple_dart_radio_kexec; static int kexec_block(void *guard) { assert(guard==&apple_dart_radio_kexec); guard_calls++; return guard_result; } static void get_device(void *dev) { assert(dev); device_pins++; } -static u32 last_enable; +static u32 last_enable, last_disable; static void apple_dart_writel(struct apple_dart *d, u32 v, unsigned o) { all_writes++; + if (o == DART_TCR(d, 16)) { + sid16_tcr_writes++; + last_sid16_tcr_write = v; + if (v & DART_T8110_TCR_TRANSLATE_ENABLE) + sid16_saw_translate = true; + } if (drop_bypass_write && o==DART_TCR(d,16)) return; + if (drop_ttbr_write && o==DART_TTBR(d,16,0)) return; if (o >= d->hw->enable_streams && o < d->hw->enable_streams + 32) { - d->regs[o/4] |= v; enable_writes++; last_enable=v; + enable_writes++; last_enable=v; + if (!drop_enable_write) + d->regs[o/4] |= v; + } else if (o >= DART_T8110_DISABLE_STREAMS && o < DART_T8110_DISABLE_STREAMS + 32) { + unsigned en = d->hw->enable_streams + (o - DART_T8110_DISABLE_STREAMS); + disable_writes++; last_disable=v; + if (!drop_disable_write) + d->regs[en/4] &= ~v; + } else if (tcr_clear_dapf && o >= 0x1000 && o < 0x1000 + 4 * DART_MAX_STREAMS) { + d->regs[o/4] = v & ~DART_T8110_TCR_BYPASS_DAPF; } else d->regs[o/4]=v; } static void writel(u32 v, void *p) { (void)v; (void)p; abort(); } @@ -137,11 +171,71 @@ def main(): { int sid; for_each_set_bit(sid,p,max) return sid; return max; } static u64 virt_to_phys(void *p) { return (uintptr_t)p; } static int tlb_result; +static unsigned tlb_flushes; +static unsigned long last_tlb_sidmap; static int test_invalidate_tlb(struct apple_dart_stream_map *m) -{ assert(m->sidmap[0] && !(m->sidmap[0] & ~m->dart->managed_sids)); return tlb_result; } +{ + assert(m->sidmap[0] && !(m->sidmap[0] & ~(m->dart->managed_sids | BIT(16)))); + tlb_flushes++; + last_tlb_sidmap = m->sidmap[0]; + return tlb_result; +} struct io_pgtable_cfg { + unsigned pgsize_bitmap, ias, oas; + int coherent_walk; + void *iommu_dev; struct { int n_ttbrs, n_levels; void *ttbr[1]; } apple_dart_cfg; }; +struct io_pgtable_ops { + int (*map_pages)(struct io_pgtable_ops *ops, unsigned long iova, + phys_addr_t paddr, size_t pgsize, size_t pgcount, + int prot, int gfp, size_t *mapped); + phys_addr_t (*iova_to_phys)(struct io_pgtable_ops *ops, unsigned long iova); + u64 mapped_iova; + phys_addr_t mapped_phys; + size_t mapped_size; +}; +static u64 sid16_root_page[1]; +static unsigned sid16_allocs, sid16_frees; +static int test_sid16_map_pages(struct io_pgtable_ops *ops, unsigned long iova, + phys_addr_t paddr, size_t pgsize, size_t pgcount, + int prot, int gfp, size_t *mapped) +{ + (void)gfp; + assert(pgsize == SZ_16K && pgcount == 1); + assert(prot == (IOMMU_READ | IOMMU_WRITE | IOMMU_MMIO)); + ops->mapped_iova = iova; + ops->mapped_phys = paddr; + ops->mapped_size = pgsize * pgcount; + *mapped = ops->mapped_size; + return 0; +} +static phys_addr_t test_sid16_iova_to_phys(struct io_pgtable_ops *ops, unsigned long iova) +{ + return iova == ops->mapped_iova ? ops->mapped_phys : 0; +} +static struct io_pgtable_ops *alloc_io_pgtable_ops(int fmt, struct io_pgtable_cfg *cfg, void *cookie) +{ + (void)cookie; + assert(fmt == APPLE_DART2 && cfg->pgsize_bitmap == SZ_16K && cfg->ias == 36); + struct io_pgtable_ops *ops = calloc(1, sizeof(*ops)); + assert(ops); + ops->map_pages = test_sid16_map_pages; + ops->iova_to_phys = test_sid16_iova_to_phys; + cfg->apple_dart_cfg.n_ttbrs = 1; + cfg->apple_dart_cfg.n_levels = 3; + cfg->apple_dart_cfg.ttbr[0] = (void *)0x4000; + (void)sid16_root_page; + sid16_allocs++; + return ops; +} +static void free_io_pgtable_ops(struct io_pgtable_ops *ops) +{ + if (!ops) + return; + sid16_frees++; + free(ops); +} struct io_pgtable { struct io_pgtable_cfg cfg; }; #define io_pgtable_ops_to_pgtable(p) (p) struct iommu_domain { int unused; }; @@ -299,6 +393,9 @@ def main(): 'apple_dart_hw_enable_bypass(', 'static void apple_dart_hw_disable_dma(', 'static bool apple_dart_managed_static_bypass(', + 'static bool apple_dart_managed_sid16_narrowed(', + 'static int apple_dart_managed_narrow_sid16(', + 'static void apple_dart_managed_unnarrow_sid16(', 'static int apple_dart_managed_admit(', 'int apple_dart_radio_check_idle(', 'static void apple_dart_managed_quarantine_locked(', @@ -359,6 +456,219 @@ def main(): assert(noidle_puts==1 && !pm_refs); drop_bypass_write=false; guard_result=0; + + /* + * SID16 narrowing + error-path teardown preserves inherited TCR, TTBR, and + * ENABLE[16] state (with write-one-to-clear DISABLE_STREAMS and T8132 + * non-retained DAPF request modeling) and allows clean rebind without -EBUSY. + */ + const struct { + u32 init_tcr, init_ttbr; + bool init_enabled, clear_dapf; + } sid16_cases[] = { + { 0, 0, false, true }, + { 0, 0x123400, false, true }, + { 0, 0x123400, true, true }, + { 2, 0, false, true }, + { 2, 0x5678001, false, true }, + { 2, 0xabcd001, true, true }, + { 6, 0, false, false }, + { 6, 0xabcd001, false, false }, + { 6, 0xabcd001, true, false }, + }; + for (unsigned i=0; ienable_streams/4]=BIT(18)|(sid16_cases[i].init_enabled?BIT(16):0); + tlb_result=0; tlb_flushes=0; last_tlb_sidmap=0; + sid16_allocs=sid16_frees=disable_writes=0; pm_refs=1; guard_result=0; + assert(!test_probe_start(&narrow)); + assert(narrow.sid16_ops && narrow.regs[DART_TCR(&narrow,16)/4]==1); + assert(narrow.regs[DART_TTBR(&narrow,16,0)/4]==narrow.sid16_ttbr); + assert(narrow.regs[hw->enable_streams/4]==(BIT(1)|BIT(2)|BIT(16)|BIT(18))); + assert(tlb_flushes==1 && last_tlb_sidmap==BIT(16)); + assert(sid16_allocs==1 && !sid16_frees); + bool ib=false; + assert(!apple_dart_managed_admit(&narrow,&ib)); + narrow.regs[hw->enable_streams/4]&=~BIT(16); + assert(apple_dart_managed_admit(&narrow,&ib)==-EBUSY); + narrow.regs[hw->enable_streams/4]|=BIT(16); + + /* Simulated post-narrowing probe failure tears down and frees table. */ + tlb_flushes=0; last_tlb_sidmap=0; disable_writes=0; last_disable=0; + last_sid16_tcr_write=0; + apple_dart_managed_quarantine(&narrow); + apple_dart_managed_unnarrow_sid16(&narrow); + assert(!narrow.sid16_ops && !narrow.sid16_ttbr && sid16_frees==1); + assert(last_sid16_tcr_write== + (sid16_cases[i].init_tcr?hw->tcr_bypass:hw->tcr_disabled)); + assert(narrow.regs[DART_TCR(&narrow,16)/4]==sid16_cases[i].init_tcr); + assert(narrow.regs[DART_TTBR(&narrow,16,0)/4]==sid16_cases[i].init_ttbr); + assert(narrow.regs[hw->enable_streams/4]== + (BIT(1)|BIT(2)|BIT(18)|(sid16_cases[i].init_enabled?BIT(16):0))); + assert(disable_writes==(sid16_cases[i].init_enabled?0u:1u)); + if (!sid16_cases[i].init_enabled) + assert(last_disable==BIT(16)); + assert(tlb_flushes==1 && last_tlb_sidmap==BIT(16)); + + /* A fresh rebind sees the restored state and admits cleanly. */ + struct apple_dart rebind={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + memcpy(rebind.regs,narrow.regs,sizeof(rebind.regs)); + pm_refs=1; + assert(!test_probe_start(&rebind)); + assert(rebind.sid16_ops && rebind.regs[DART_TCR(&rebind,16)/4]==1); + free_io_pgtable_ops(rebind.sid16_ops); + pm_refs=0; + } + + /* Entry states that cannot be restored are rejected before narrowing. */ + tcr_clear_dapf=true; + struct apple_dart bad_entry={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=false,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + bad_entry.regs[DART_TCR(&bad_entry,16)/4]=2; + sid16_allocs=0; all_writes=0; + assert(apple_dart_managed_narrow_sid16(&bad_entry)==-EBUSY); + assert(!bad_entry.sid16_ops && !sid16_allocs && !all_writes); + bad_entry.supports_bypass=true; + bad_entry.regs[DART_TCR(&bad_entry,16)/4]=0; + bad_entry.regs[DART_TTBR(&bad_entry,16,0)/4]=hw->ttbr_valid|0x1000; + pm_refs=1; + assert(test_probe_start(&bad_entry)==-EBUSY && !pm_refs); + assert(apple_dart_managed_narrow_sid16(&bad_entry)==-EBUSY); + assert(!bad_entry.sid16_ops && !sid16_allocs && !all_writes); + bad_entry.regs[DART_TTBR(&bad_entry,16,0)/4]=0; + const u32 bad_tcrs[]={1,4,8,0x80}; + for (unsigned i=0; ienable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; noidle_puts=0; + sid16_saw_translate=false; sid16_tcr_writes=0; last_sid16_tcr_write=0; + drop_ttbr_write=true; + assert(test_probe_start(&drop_ttbr)==-EIO); + drop_ttbr_write=false; + assert(!sid16_saw_translate); + assert(drop_ttbr.retained && drop_ttbr.managed_failed && noidle_puts==1 && !pm_refs); + assert(!drop_ttbr.sid16_ops && !drop_ttbr.sid16_ttbr && sid16_allocs==1 && sid16_frees==1); + assert(drop_ttbr.regs[DART_TCR(&drop_ttbr,16)/4]==2); + assert(last_sid16_tcr_write==hw->tcr_bypass); + assert(drop_ttbr.regs[DART_TTBR(&drop_ttbr,16,0)/4]==0xabcd001); + assert((drop_ttbr.regs[hw->enable_streams/4]&(BIT(1)|BIT(2)|BIT(16)))==BIT(16)); + + /* Dropped ENABLE[16] write during narrowing fails probe and rolls back. */ + struct apple_dart drop_en={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + drop_en.regs[DART_TCR(&drop_en,16)/4]=2; + drop_en.regs[DART_TTBR(&drop_en,16,0)/4]=0xabcd001; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; noidle_puts=0; + last_sid16_tcr_write=0; + drop_enable_write=true; + assert(test_probe_start(&drop_en)==-EIO); + drop_enable_write=false; + assert(drop_en.retained && drop_en.managed_failed && noidle_puts==1 && !pm_refs); + assert(!drop_en.sid16_ops && !drop_en.sid16_ttbr && sid16_allocs==1 && sid16_frees==1); + assert(last_sid16_tcr_write==hw->tcr_bypass); + assert(drop_en.regs[DART_TCR(&drop_en,16)/4]==2); + assert(drop_en.regs[DART_TTBR(&drop_en,16,0)/4]==0xabcd001); + assert(!(drop_en.regs[hw->enable_streams/4]&(BIT(1)|BIT(2)|BIT(16)))); + + /* Mismatched TCR readback on restore keeps table unfreed. */ + struct apple_dart mismatch_tcr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + mismatch_tcr.regs[DART_TCR(&mismatch_tcr,16)/4]=6; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&mismatch_tcr)); + apple_dart_managed_unnarrow_sid16(&mismatch_tcr); + assert(mismatch_tcr.sid16_ops && sid16_frees==0); + assert(mismatch_tcr.regs[DART_TCR(&mismatch_tcr,16)/4]==2); + free_io_pgtable_ops(mismatch_tcr.sid16_ops); + pm_refs=0; + + /* Failed DISABLE_STREAMS clear refuses to restore bypass and keeps table unfreed. */ + struct apple_dart stuck_en={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_en.regs[DART_TCR(&stuck_en,16)/4]=2; + stuck_en.regs[DART_TTBR(&stuck_en,16,0)/4]=0xabcd001; + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_en)); + drop_disable_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_en); + assert(stuck_en.sid16_ops && sid16_frees==0); + assert(stuck_en.regs[DART_TCR(&stuck_en,16)/4]==1); + assert(stuck_en.regs[DART_TTBR(&stuck_en,16,0)/4]==stuck_en.sid16_ttbr); + drop_disable_write=false; + free_io_pgtable_ops(stuck_en.sid16_ops); + pm_refs=0; + + /* Failed TCR restore keeps TTBR intact and keeps table unfreed. */ + struct apple_dart stuck_tcr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_tcr.regs[DART_TCR(&stuck_tcr,16)/4]=2; + stuck_tcr.regs[DART_TTBR(&stuck_tcr,16,0)/4]=0xabcd001; + stuck_tcr.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_tcr)); + drop_bypass_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_tcr); + assert(stuck_tcr.sid16_ops && sid16_frees==0); + assert(stuck_tcr.regs[DART_TCR(&stuck_tcr,16)/4]==1); + assert(stuck_tcr.regs[DART_TTBR(&stuck_tcr,16,0)/4]==stuck_tcr.sid16_ttbr); + drop_bypass_write=false; + free_io_pgtable_ops(stuck_tcr.sid16_ops); + pm_refs=0; + + /* Failed TTBR restore keeps table unfreed. */ + struct apple_dart stuck_ttbr={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck_ttbr.regs[DART_TCR(&stuck_ttbr,16)/4]=2; + stuck_ttbr.regs[DART_TTBR(&stuck_ttbr,16,0)/4]=0xabcd001; + stuck_ttbr.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck_ttbr)); + drop_ttbr_write=true; + apple_dart_managed_unnarrow_sid16(&stuck_ttbr); + assert(stuck_ttbr.sid16_ops && sid16_frees==0); + assert(stuck_ttbr.regs[DART_TTBR(&stuck_ttbr,16,0)/4]==stuck_ttbr.sid16_ttbr); + drop_ttbr_write=false; + free_io_pgtable_ops(stuck_ttbr.sid16_ops); + pm_refs=0; + + /* Failed TLB flush during teardown keeps the page table unfreed. */ + struct apple_dart stuck={.hw=hw,.managed_sids=BIT(1)|BIT(2),.version=0x202, + .num_streams=19,.supports_bypass=true,.pgsize=SZ_16K, + .oas=36,.sid16_page=0x381204000ULL,.dev=(void *)1}; + stuck.regs[DART_TCR(&stuck,16)/4]=2; + stuck.regs[hw->enable_streams/4]=BIT(16); + tlb_result=0; sid16_allocs=sid16_frees=0; pm_refs=1; + assert(!test_probe_start(&stuck)); + tlb_result=-EIO; + apple_dart_managed_unnarrow_sid16(&stuck); + assert(stuck.sid16_ops && sid16_frees==0); + free_io_pgtable_ops(stuck.sid16_ops); + tlb_result=0; pm_refs=0; tcr_clear_dapf=false; } ''' code += r''' @@ -609,6 +919,16 @@ def main(): map_result[1]=-ENODEV; assert(apple_pcie_radio_check_cold(&port)==-ENODEV); map_result[1]=0; assert(!memcmp(before,d.regs,sizeof(before)) && !node_refs && !provider_refs); assert(!radio_provider.dev.locked && !d.managed_lock); + d.sid16_ops=(void *)1; d.sid16_ttbr=0x4001; + d.regs[DART_TCR(&d,16)/4]=1; d.regs[DART_TTBR(&d,16,0)/4]=0x4001; + assert(apple_pcie_radio_check_cold(&port)==0); + d.regs[hw.enable_streams/4]&=~BIT(16); + assert(apple_pcie_radio_check_cold(&port)==-EBUSY); + d.regs[hw.enable_streams/4]|=BIT(16); + assert(apple_pcie_radio_check_cold(&port)==0); + d.sid16_ops=NULL; d.sid16_ttbr=0; + d.regs[DART_TCR(&d,16)/4]=before[DART_TCR(&d,16)/4]; + d.regs[DART_TTBR(&d,16,0)/4]=before[DART_TTBR(&d,16,0)/4]; puts("radio normal SIDs: admission, scoped publication, foreign preservation, TLB failure rollback, quarantine, group merge and checked cold start PASS"); } ''' From 4744d692f905b621e509d1c2bee62f222662a046 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 23:17:45 -0500 Subject: [PATCH 0401/1514] arm64: dts: apple: t8132: narrow the radio's SID16 to its page On the J713 the radio DART's static SID16 stream only writes the SoC page at 0x381204000. Name it in the shared T8132 board include, next to apple,managed-sids, so the DART driver replaces the stream's bypass with a one-page table on every board that has the radio port. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8132-jxxx.dtsi | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index 3f378b1ffc1cc4..78d775954b0e13 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -443,6 +443,15 @@ &dart_apcie0 { apple,managed-sids = <1 2>; apple,dma-range = <0x100 0x00100000 0x0 0x3fe00000>; + /* + * Limit the static SID16 stream to this SoC MMIO page instead of + * keeping it in bypass. 0x381204000 sits 0x38000 bytes past aic's + * core window (0x381000000 + 0x1cc000) and below DRAM; no DT node + * claims it, so its owning SoC block is not identified in the DT yet. + * Blocking SID16 on J713 faulted on writes to this page within + * seconds, and J715 uses the same page with 0 faults. + */ + apple,sid16-page = /bits/ 64 <0x381204000>; status = "okay"; }; From a9454a5477b4c3be07c6b962e5f61fbfcb9731a7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 04:24:50 +1100 Subject: [PATCH 0402/1514] phy: apple: t6040: keep a running coprocessor's domains on through s2idle In suspend-to-idle the Type-C link stays up: the USB4/Thunderbolt router holds its own power domains out of the system transition while a cable is set up, and nothing stops a running PHY coprocessor. genpd still powered off this PHY's domain (common_dp, and phymxwrap above it) in its noirq phase, under the running coprocessor. The link died shortly after resume ("SBX disconnected"), and the detach that followed found a coprocessor that no longer answered: RTKit: AP idle not acknowledged: -62 USB3: PHY coprocessor idle failed: -62 ... RTKit: endpoint discovery failed: -62 sn201202x 1-0c: failed to configure Type-C connection: -62 From then on every start failed the same way until a reboot, hard recoveries included, although a hard recovery brings back a port that never slept. Hold the PHY device out of the whole suspend-to-idle transition, from before its prepare to after its complete, while its coprocessor runs, so genpd leaves its domains on. Sleeps the platform firmware takes part in are left as they were (pm_suspend_no_platform() is false there). Signed-off-by: Ryan Murray --- drivers/phy/apple/t6040-usb2.c | 57 ++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 50d82116aac2d1..c6d567a0b58345 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -285,6 +286,8 @@ struct t6040_usb2_phy { struct completion app_reply; struct t6040_recovery_state recovery; atomic_t drop_next_power_down_ack; + struct notifier_block pm_nb; + bool s2idle_held; /* held out of this suspend-to-idle, see t6040_pm_notify() */ struct dentry *debugfs; enum typec_orientation orientation; bool usb3_up; /* tuned by the coprocessor this power cycle */ @@ -2128,6 +2131,52 @@ static void t6040_rtkit_cleanup(void *data) t6040_rtkit_stop_transport(data); } +/* + * Suspend-to-idle leaves the Type-C link up: the USB4/Thunderbolt router keeps + * its own domains out of the system transition while a cable is set up, and a + * running PHY coprocessor is not stopped either. genpd would still power off + * common_dp (and with it phymxwrap) in its noirq phase once this device has + * suspended, under the running coprocessor: the link then dies after resume and + * the next detach finds a coprocessor that no longer answers (AP idle -62). + * Hold this device out of the whole transition, from before its prepare to + * after its complete, while its coprocessor runs, so its domains stay on. A + * sleep the platform takes part in (firmware suspend) is left as it was. + */ +static int t6040_pm_notify(struct notifier_block *nb, unsigned long action, void *data) +{ + struct t6040_usb2_phy *tphy = container_of(nb, struct t6040_usb2_phy, pm_nb); + + switch (action) { + case PM_SUSPEND_PREPARE: + if (!pm_suspend_no_platform()) + break; + scoped_guard(mutex, &tphy->lock) { + if (tphy->rtk && apple_rtkit_is_running(tphy->rtk)) { + dev_pm_syscore_device(tphy->dev, true); + tphy->s2idle_held = true; + dev_dbg(tphy->dev, "PHY coprocessor running: domains kept on for s2idle\n"); + } + } + break; + case PM_POST_SUSPEND: + scoped_guard(mutex, &tphy->lock) { + if (tphy->s2idle_held) { + dev_pm_syscore_device(tphy->dev, false); + tphy->s2idle_held = false; + } + } + break; + } + return NOTIFY_DONE; +} + +static void t6040_pm_notifier_unregister(void *data) +{ + struct t6040_usb2_phy *tphy = data; + + unregister_pm_notifier(&tphy->pm_nb); +} + static void t6040_mbox_dev_put(void *data) { put_device(data); @@ -2296,6 +2345,14 @@ static int t6040_usb3_probe(struct t6040_usb2_phy *tphy, struct platform_device if (ret) return ret; + tphy->pm_nb.notifier_call = t6040_pm_notify; + ret = register_pm_notifier(&tphy->pm_nb); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, t6040_pm_notifier_unregister, tphy); + if (ret) + return ret; + ret = t6040_debugfs_init(tphy); if (ret) return ret; From 45f238024b4c88b37c9a291187430915bf6ad61b Mon Sep 17 00:00:00 2001 From: termg Date: Fri, 20 Nov 2026 14:58:22 +0000 Subject: [PATCH 0403/1514] drm/asahi: g17: Log an unsupported firmware build only when none matches firmware_variant() tries the identified builds in turn, the one the boot loader's apple,firmware-version names first. Each try measured the loaded TEXT again and, when it was not that build, logged "unsupported GPU firmware build", the build it was not, and "GPU firmware image not admitted: EINVAL", even when a later build then matched. Without apple,firmware-version (the installed aura does not write it on T8142), an M5 on macOS 27.2 logs three such errors for the 26A428 build before it admits 26B123. Measure the TEXT once and try each build against that measurement (Measured::find, which leaves the copy as it found it). Only when no build matches, log the measured identity and every supported build, before the existing "Unsupported GPU firmware image" line. A matched build still logs "GPU firmware build: ...". The TEXT is now copied and hashed once per probe rather than once per candidate build. Signed-off-by: termg --- drivers/gpu/drm/asahi/g17/mod.rs | 37 +++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..befcadd8d30112 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1890,11 +1890,16 @@ impl Gpu { let others = builds .iter() .filter(|build| Some(build.os_version) != version); + // Measure the loaded TEXT once and try each build against it. A build that is not this + // image is not an error while another one may be: only when none is, say what was + // measured and what is supported. + let mut measured = Self::measure_text(dev)?; let mut identified = None; for build in Iterator::chain(preferred, others) { - if Self::identify_image(dev, build).is_err() { + let Some(image) = measured.find(build.images) else { continue; - } + }; + dev_info!(dev.as_ref(), "GPU firmware build: {}\n", image.name); let admits = build.config.is_none_or(|config| { config .core_layout @@ -1911,6 +1916,14 @@ impl Gpu { dev_info!(dev.as_ref(), "GPU firmware: {}\n", build.name); return Ok((build.variant, build.config)); } + dev_err!( + dev.as_ref(), + "unsupported GPU firmware build: {}\n", + measured.identity(builds.iter().flat_map(|build| build.images)) + ); + for image in builds.iter().flat_map(|build| build.images) { + dev_err!(dev.as_ref(), "supported: {}\n", image.name); + } dev_err!( dev.as_ref(), "Unsupported GPU firmware image (reported macOS version {:?})\n", @@ -1919,19 +1932,23 @@ impl Gpu { Err(ENODEV) } - /// Checks that the loaded TEXT (the `fw-text` region) is one of `build`'s images, with the DATA size - /// of the `fw-data` region. The version property is only a selection hint. - fn identify_image(dev: &AsahiDrmDevice, build: &'static fw::variant::Build) -> Result { + /// Measures the loaded TEXT (the `fw-text` region), with the DATA size of the `fw-data` + /// region, for [`Self::firmware_variant`] to identify among the builds. The version + /// property is only a selection hint. + fn measure_text(dev: &AsahiDrmDevice) -> Result { let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; let text = node.reserved_mem_region_to_resource_byname(c_str!("fw-text"))?; let data = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; let start = text.start(); let end = start.checked_add(text.size()).ok_or(EINVAL)?; - crate::fwid::identify(dev.as_ref().as_ref(), start..end, data.size(), build.images) - .inspect_err(|e| { - dev_err!(dev.as_ref(), "GPU firmware image not admitted: {:?}\n", e) - })?; - Ok(()) + crate::fwid::measure(start..end, data.size()).inspect_err(|e| { + if *e == EAGAIN { + dev_err!( + dev.as_ref(), + "GPU firmware TEXT changed while it was measured\n" + ); + } + }) } /// The macOS version the boot loader reports for the boot firmware that loaded the GPU From 313c264eb8020acd86b552120c513125964fd783 Mon Sep 17 00:00:00 2001 From: termg Date: Sat, 21 Nov 2026 03:12:37 +0000 Subject: [PATCH 0404/1514] drm/asahi: g17: Report a TEXT that cannot be measured, and test the shared measurement Follow-ups to "Log an unsupported firmware build only when none matches": - measure_text() logged only EAGAIN. A missing fw-text or fw-data region (a DT or boot loader mismatch) now returned from the probe silently, where before it printed "GPU firmware image not admitted". Log every other error too. - A measurement error (EAGAIN, ENOMEM, EINVAL) now ends the probe with that error, where before each candidate build measured again and the probe ended with ENODEV after "Unsupported GPU firmware image". So a transient EAGAIN (TEXT changed between the two copies) is no longer retried by the next candidate; it is logged instead. - "GPU firmware build: " is logged once, for the build that is taken, next to "GPU firmware: ". It was logged for every build whose image matched, so an image shared by a build whose configuration does not admit the probed cores logged it twice. - The "supported:" list walked every build's images, so an image shared by builds that differ only in their core layout (as T6041 25G83 is) was listed once per build. List each image once, comparing name and TEXT digest: the address of a const-promoted entry is not guaranteed to be shared. - g17-firmware-selection-tests.py compiles firmware_variant() against stub types, and its Build stub still had a single `image` with an identify_image() stub, so the host test stopped building (E0609 "no field images"). Model the new shape instead: Build::images, a stub measure_text() and a Measured whose find() records each image it is tried against, so the existing checks on the order of the candidates still hold. The stub dev_info!/dev_err! now build their messages, so the log lines are type-checked as well. Signed-off-by: termg --- drivers/gpu/drm/asahi/g17/mod.rs | 42 ++++++++++++----- tools/asahi/g17-firmware-selection-tests.py | 51 +++++++++++++++------ 2 files changed, 68 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index befcadd8d30112..3fbb6006507b06 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1899,7 +1899,6 @@ impl Gpu { let Some(image) = measured.find(build.images) else { continue; }; - dev_info!(dev.as_ref(), "GPU firmware build: {}\n", image.name); let admits = build.config.is_none_or(|config| { config .core_layout @@ -1907,12 +1906,13 @@ impl Gpu { .is_none_or(|measured| measured == cores) }); if admits { - identified = Some(build); + identified = Some((build, image)); break; } - identified.get_or_insert(build); + identified.get_or_insert((build, image)); } - if let Some(build) = identified { + if let Some((build, image)) = identified { + dev_info!(dev.as_ref(), "GPU firmware build: {}\n", image.name); dev_info!(dev.as_ref(), "GPU firmware: {}\n", build.name); return Ok((build.variant, build.config)); } @@ -1921,8 +1921,16 @@ impl Gpu { "unsupported GPU firmware build: {}\n", measured.identity(builds.iter().flat_map(|build| build.images)) ); - for image in builds.iter().flat_map(|build| build.images) { - dev_err!(dev.as_ref(), "supported: {}\n", image.name); + // Builds that differ only in their core layout share an image: list each image once. + // Compare by name and digest; the address of a `const`-promoted entry is not unique. + let images = || builds.iter().flat_map(|build| build.images); + for (i, image) in images().enumerate() { + if !images() + .take(i) + .any(|seen| (seen.name, seen.text_sha256) == (image.name, image.text_sha256)) + { + dev_err!(dev.as_ref(), "supported: {}\n", image.name); + } } dev_err!( dev.as_ref(), @@ -1936,17 +1944,27 @@ impl Gpu { /// region, for [`Self::firmware_variant`] to identify among the builds. The version /// property is only a selection hint. fn measure_text(dev: &AsahiDrmDevice) -> Result { - let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; - let text = node.reserved_mem_region_to_resource_byname(c_str!("fw-text"))?; - let data = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; - let start = text.start(); - let end = start.checked_add(text.size()).ok_or(EINVAL)?; - crate::fwid::measure(start..end, data.size()).inspect_err(|e| { + let measure = || { + let node = dev.as_ref().as_ref().of_node().ok_or(EINVAL)?; + let text = node.reserved_mem_region_to_resource_byname(c_str!("fw-text"))?; + let data = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; + let start = text.start(); + let end = start.checked_add(text.size()).ok_or(EINVAL)?; + crate::fwid::measure(start..end, data.size()) + }; + measure().inspect_err(|e| { if *e == EAGAIN { dev_err!( dev.as_ref(), "GPU firmware TEXT changed while it was measured\n" ); + } else { + // A missing or bad fw-text/fw-data region: a DT or boot loader mismatch. + dev_err!( + dev.as_ref(), + "GPU firmware image not measured (fw-text/fw-data): {:?}\n", + e + ); } }) } diff --git a/tools/asahi/g17-firmware-selection-tests.py b/tools/asahi/g17-firmware-selection-tests.py index 6b9cc52d70ea7a..43335e4e3098b1 100644 --- a/tools/asahi/g17-firmware-selection-tests.py +++ b/tools/asahi/g17-firmware-selection-tests.py @@ -27,12 +27,13 @@ def method(source, signature): #![allow(dead_code)] type Result = std::result::Result; const ENODEV: i32 = -19; -macro_rules! dev_info { ($($t:tt)*) => { () }; } -macro_rules! dev_err { ($($t:tt)*) => { () }; } +// The device argument is dropped; the message and its arguments are still built. +macro_rules! dev_info { ($dev:expr, $($t:tt)*) => { { let _ = format!($($t)*); } }; } +macro_rules! dev_err { ($dev:expr, $($t:tt)*) => { { let _ = format!($($t)*); } }; } struct AsahiDrmDevice { version: Option<[u32; 3]>, image: u32, - checked: std::cell::RefCell>, + checked: std::rc::Rc>>, } struct CoreLayout { cores: Option<(u32, u32)>, @@ -41,6 +42,29 @@ def method(source, signature): id: u32, core_layout: CoreLayout, } +mod fwid { + pub struct FirmwareBuild { + pub name: &'static str, + pub image: u32, + pub text_sha256: [u8; 32], + } + // The loaded TEXT, modelled by its image number; records every image it is tried against. + pub struct Measured { + pub image: u32, + pub checked: std::rc::Rc>>, + } + impl Measured { + pub fn find(&mut self, builds: &'static [FirmwareBuild]) -> Option<&'static FirmwareBuild> { + builds.iter().find(|build| { + self.checked.borrow_mut().push(build.image); + build.image == self.image + }) + } + pub fn identity(&mut self, _: impl IntoIterator) -> u32 { + self.image + } + } +} mod fw { pub struct Variant(pub u32); pub mod variant { @@ -48,7 +72,7 @@ def method(source, signature): pub struct Build { pub os_version: [u32; 3], pub name: &'static str, - pub image: u32, + pub images: &'static [crate::fwid::FirmwareBuild], pub variant: &'static Variant, pub config: Option<&'static crate::Config>, } @@ -58,35 +82,36 @@ def method(source, signature): struct Gpu; impl Gpu { fn os_firmware_version(dev: &AsahiDrmDevice) -> Option<[u32; 3]> { dev.version } - fn identify_image(dev: &AsahiDrmDevice, build: &'static fw::variant::Build) -> Result { - dev.checked.borrow_mut().push(build.image); - if dev.image == build.image { Ok(()) } else { Err(ENODEV) } + fn measure_text(dev: &AsahiDrmDevice) -> Result { + Ok(fwid::Measured { image: dev.image, checked: dev.checked.clone() }) } ''' TESTS = r''' } +static IMAGE_1: [fwid::FirmwareBuild; 1] = [fwid::FirmwareBuild { name: "image 1", image: 1, text_sha256: [1; 32] }]; +static IMAGE_2: [fwid::FirmwareBuild; 1] = [fwid::FirmwareBuild { name: "image 2", image: 2, text_sha256: [2; 32] }]; static FIRST: fw::Variant = fw::Variant(1); static SECOND: fw::Variant = fw::Variant(2); static OWN: Config = Config { id: 7, core_layout: CoreLayout { cores: None } }; static BUILDS: [fw::variant::Build; 2] = [ - fw::variant::Build { os_version: [26,6,2], name: "first", image: 1, variant: &FIRST, config: None }, - fw::variant::Build { os_version: [27,0,0], name: "second", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,6,2], name: "first", images: &IMAGE_1, variant: &FIRST, config: None }, + fw::variant::Build { os_version: [27,0,0], name: "second", images: &IMAGE_2, variant: &SECOND, config: Some(&OWN) }, ]; // One image admitted with the configurations of two core layouts, as T6041 25G83 is. static FORTY: Config = Config { id: 40, core_layout: CoreLayout { cores: Some((4, 40)) } }; static THIRTY_TWO: Config = Config { id: 32, core_layout: CoreLayout { cores: Some((4, 32)) } }; static SHARED: [fw::variant::Build; 3] = [ - fw::variant::Build { os_version: [26,5,2], name: "other", image: 1, variant: &FIRST, config: None }, - fw::variant::Build { os_version: [26,6,2], name: "40", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,5,2], name: "other", images: &IMAGE_1, variant: &FIRST, config: None }, + fw::variant::Build { os_version: [26,6,2], name: "40", images: &IMAGE_2, variant: &SECOND, config: Some(&FORTY) }, - fw::variant::Build { os_version: [26,6,2], name: "32", image: 2, variant: &SECOND, + fw::variant::Build { os_version: [26,6,2], name: "32", images: &IMAGE_2, variant: &SECOND, config: Some(&THIRTY_TWO) }, ]; const CORES: (u32, u32) = (4, 40); fn device(version: Option<[u32; 3]>, image: u32) -> AsahiDrmDevice { - AsahiDrmDevice { version, image, checked: std::cell::RefCell::new(Vec::new()) } + AsahiDrmDevice { version, image, checked: Default::default() } } fn main() { use fw::variant::Firmware; From a9553e19abcef458db8296611a69d2932c43146c Mon Sep 17 00:00:00 2001 From: termg Date: Fri, 20 Nov 2026 15:22:06 +0000 Subject: [PATCH 0405/1514] arm64: dts: apple: t8142-j704: Keep the PCIe host to the trained port 0 The bootloader trains apcie port 0 only (aura's j813_n1_prepare(), the same sequence as J813, accepting J704's BCM4388 since aurora-silicon/aura "j813_n1: T8142: accept J704's BCM4388 on apcie port 0"). Port 2 (GL9755 SD reader) stays untrained, but the tree gave the generic ECAM host buses 0-2, gave the MSI controller port 2's MSI block and enabled port 2's DART. Describe port 0 only, as J813 does: ECAM buses 0-1, port 0's MSI block and DART. The SD reader comes back once port 2 is trained. Tested on a J704 (Fedora 44, 7.3.0 aurora kernel with CONFIG_PCIE_APPLE_MSI=y) with the equivalent tree: 01:00.0 BCM4388 [14e4:4434] rev 06 with brcmfmac (4388C2 firmware 23.10.1042) scans 2.4 and 5 GHz and associates through NetworkManager; 01:00.1 [14e4:5f72] with hci_bcm4377 gives hci0, BLE scan finds devices; "pcie-apple-msi: 32 MSIs at 0xfffff000". Signed-off-by: termg --- .../arm64/boot/dts/apple/t8142-j704-pcie.dtsi | 55 +++++++------------ 1 file changed, 21 insertions(+), 34 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi index a0694d50645556..9b65f408c43de1 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j704-pcie.dtsi @@ -1,11 +1,16 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * Internal PCIe: BCM4388 Wi-Fi/Bluetooth on apcie port 0 and the GL9755 SD - * card reader on port 2. As on J813, the bootloader trains the links and - * Linux uses the root ports as a generic ECAM host that owns the DARTs and - * the endpoints. Nothing programs the ports' RID-to-SID tables, so every - * function uses stream zero of its port's DART. Ranges, MSI maps and DART - * IRQs are from the J704 ADT; port 0 matches J813. + * Internal PCIe: BCM4388 Wi-Fi/Bluetooth on apcie port 0. As on J813, the + * bootloader trains the link and Linux uses the root port as a generic ECAM + * host that owns the DART and the endpoints. Nothing programs the port's + * RID-to-SID table, so both functions use stream zero of the port's DART. + * Ranges, the MSI map and the DART IRQ are from the J704 ADT; port 0 + * matches J813. + * + * The GL9755 SD card reader sits on port 2 (ADT pci-bridge2, bus 2, MSI map + * at 0x48a028000, pcie2_dart). The bootloader trains port 0 only, so the + * ECAM window and the MSI controller stop at port 0 until port 2 is + * trained too. */ &{/} { @@ -14,15 +19,18 @@ device_type = "pci"; #address-cells = <3>; #size-cells = <2>; - bus-range = <0 2>; - reg = <0x1c 0xb0000000 0 0x300000>; + bus-range = <0 1>; + reg = <0x1c 0xb0000000 0 0x200000>; ranges = <0x43000000 0xb 0xc0000000 0xb 0xc0000000 0 0x20000000>, <0x02000000 0 0x80000000 0xb 0x80000000 0 0x40000000>; dma-coherent; msi-parent = <&pcie0_msi>; + /* + * Port 2's root port (00:02.0) still enumerates on bus 0 and has no + * entry here, so "no iommu-map translation for id 0x10" is expected. + */ iommu-map = <0x100 &pcie0_dart 0 1>, - <0x101 &pcie0_dart 0 1>, - <0x200 &pcie2_dart 0 1>; + <0x101 &pcie0_dart 0 1>; port00: pci@0,0 { device_type = "pci"; @@ -49,34 +57,17 @@ local-bd-address = [00 00 00 00 00 00]; }; }; - - port02: pci@2,0 { - device_type = "pci"; - reg = <0x1000 0x0 0x0 0x0 0x0>; - bus-range = <2 2>; - #address-cells = <3>; - #size-cells = <2>; - ranges; - - sdhci0: mmc@0,0 { - compatible = "pci17a0,9755"; - reg = <0x20000 0x0 0x0 0x0 0x0>; - cd-inverted; - wp-inverted; - }; - }; }; }; &{/soc} { /* - * The MSI maps of ports 0 and 2. They share the root complex's AIC - * range (ADT msi-vector-offset 1741); 32 vectors are enough for both. + * Port 0's MSI map (ADT msi-vector-offset 1741, port 0 owns the first + * 32 vectors). */ pcie0_msi: msi-controller@488028000 { compatible = "apple,t8142-pcie-msi"; - reg = <0x4 0x88028000 0x0 0x8000>, - <0x4 0x8a028000 0x0 0x8000>; + reg = <0x4 0x88028000 0x0 0x8000>; msi-controller; msi-ranges = <&aic AIC_IRQ 1741 IRQ_TYPE_EDGE_RISING 32>; }; @@ -85,7 +76,3 @@ &pcie0_dart { status = "okay"; }; - -&pcie2_dart { - status = "okay"; -}; From f7e582e048771e52fd153da74de66bd2f3be0c98 Mon Sep 17 00:00:00 2001 From: termg Date: Fri, 20 Nov 2026 16:34:10 +0000 Subject: [PATCH 0406/1514] dt-bindings: sound: apple,macaudio: Add J704 The MacBook Pro (14-inch, M5) J704 sound card, a J813-style AOP-fed macaudio card. Signed-off-by: termg --- Documentation/devicetree/bindings/sound/apple,macaudio.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml index c9880a39e9b29c..4a2c875931c240 100644 --- a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml @@ -46,6 +46,7 @@ properties: - apple,j623-macaudio-jack - apple,j624-macaudio-jack - apple,j700-macaudio + - apple,j704-macaudio - apple,j713-macaudio - apple,j713-macaudio-jack - apple,j714-macaudio From bd4ed4742c705a48e9a6e30fa2913df1b181a6ba Mon Sep 17 00:00:00 2001 From: termg Date: Fri, 20 Nov 2026 16:33:47 +0000 Subject: [PATCH 0407/1514] ASoC: apple: macaudio: J704 (MacBook Pro 14" M5), speakers off The J704 has J813's AOP-fed audio: the T8152-style AOP audio driver as the CPU component and a CS42L84 headphone jack on "cout". Its six SN012776 speakers (two woofers and a tweeter per side) sit in an order of their own, not J815's, and have no verified slots or protection profile yet. Add a J704 entry with J813's jack format and front-ends, and no safe level, so macaudio_speakers_allowed() never admits a J704 speaker link. The admission KUnit case checks that. Tested on a J704 (Fedora 44) with the J704 audio tree: the jack plays (volume, both channels), the headset mic captures, no speaker is bound. Signed-off-by: termg --- sound/soc/apple/macaudio-admission-test.h | 4 +++- sound/soc/apple/macaudio.c | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/sound/soc/apple/macaudio-admission-test.h b/sound/soc/apple/macaudio-admission-test.h index fa5e9f4df00c75..aec1939dbbea5f 100644 --- a/sound/soc/apple/macaudio-admission-test.h +++ b/sound/soc/apple/macaudio-admission-test.h @@ -11,12 +11,14 @@ static void macaudio_admission_needs_a_safe_level(struct kunit *test) KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j45x_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j413_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j700_cfg)); - /* The AOP-fed machines: J714 and J813 with their safe level, J873 without one */ + /* The AOP-fed machines: J714 and J813 with their safe level, J873 and J704 without one */ KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j714_cfg)); KUNIT_EXPECT_TRUE(test, macaudio_speakers_allowed(&macaudio_j813_cfg)); KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j873_cfg)); /* The Mac Studio M5: no sense and no protection owner yet, speaker off */ KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j775_cfg)); + /* J704: speakers off until their slots and protection are verified */ + KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j704_cfg)); cfg = macaudio_j413_cfg; cfg.safe_vol = 0; KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&cfg)); diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index b05d60bc0451a0..13cff9b01a6da1 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -4124,6 +4124,27 @@ struct macaudio_platform_cfg macaudio_j813_cfg = { .spk_secondary_only = true, }; +/* + * J704 (T8142, MacBook Pro 14" M5): J813's audio fabric (the AOP firmware, + * the T8152-style AOP audio driver, the CS42L84 jack on "cout"). The + * speakers are six SN012776 (two woofers and a tweeter per side) in an + * order of their own; they stay off until their slots and a protection + * profile are verified: no safe level, so macaudio_speakers_allowed() keeps + * any speaker link unbound. The jack is unaffected. + */ +struct macaudio_platform_cfg macaudio_j704_cfg = { + .enable_speakers = false, + .amp = AMP_SN012776, + .speakers = SPKR_2W1T, + .stereo = true, + .safe_vol = 0, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + /* * J714s (T6050, MacBook Pro 14" M5 Pro): as on J813, the AOP firmware owns * the audio fabric and the CPU component is the T8152-style AOP audio @@ -4475,6 +4496,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j775c-macaudio", .data = &macaudio_j775_cfg }, /* j775d - sn012776 - 1x 1W (AOP-fed, no sense: speaker off) */ { .compatible = "apple,j775d-macaudio", .data = &macaudio_j775_cfg }, + /* j704 - sn012776 15 2x 2W+1T (AOP-fed; speakers off until bring-up) */ + { .compatible = "apple,j704-macaudio", .data = &macaudio_j704_cfg }, /* j813 AID? sn012776 15 2x 1W+1T (AOP-fed, V/I sense) */ { .compatible = "apple,j813-macaudio", .data = &macaudio_j813_cfg }, /* j815 AID43 sn012776 15 2x 2W+1T (AOP-fed, V/I sense) */ From c7e211b0fc0c4c722bfb7898555dd981c4cd781a Mon Sep 17 00:00:00 2001 From: termg Date: Fri, 20 Nov 2026 16:34:31 +0000 Subject: [PATCH 0408/1514] arm64: dts: apple: t8142-j704: Add the headphone jack and microphones The J704 (MacBook Pro 14", M5) ADT shows J813's audio wiring: the AOP (ascwrap-v6, mailbox IRQs 490-493), dart-aop, admac-base-ns (IRQ 549) and admac-leap-s (IRQ 551) at the same addresses, the CS42L84 jack codec at i2c1 0x4b (IRQ on AP pin 100, reset on nub pin 18) and the three-microphone LEAP stream. Reuse t8142-j813-audio.dtsi as J815 does, with the J704 names. The six SN012776 speakers on i2c3 (0x38-0x3d) are in an order of their own (0x39 left woofer 2, 0x3a left tweeter, 0x3c right woofer 2, 0x3d right tweeter), so until their slots and a protection profile are verified neither the amps nor i2c3 are described: their driver never binds and they stay in shutdown. The card is "apple,j704-macaudio", whose macaudio entry admits no speaker link. Tested on a J704 (Fedora 44, aurora 7.3.0): the CS42L84 probes (revision 36), the jack plays with volume and both channels, jack and headset-mic detection work, and the HPAI card captures the three microphones (3 x float, 48 kHz). Signed-off-by: termg --- .../boot/dts/apple/t8142-j704-audio.dtsi | 41 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8142-j704.dts | 1 + 2 files changed, 42 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi diff --git a/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi new file mode 100644 index 00000000000000..474f8d25a108b8 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Apple MacBook Pro (14-inch, M5) J704: sound through the AOP firmware, the + * headphone jack and the microphone array only. + * + * The J704 ADT matches J813's audio wiring: the AOP (ascwrap-v6, mailbox + * IRQs 490-493), dart-aop, admac-base-ns (IRQ 549) and admac-leap-s + * (IRQ 551) at the same addresses, the CS42L84 jack codec at i2c1 0x4b + * (IRQ AP pin 100, reset nub pin 18) and the three-microphone "audio-hp-mic" + * LEAP stream. So this reuses J813's description, as J815 does. + * + * The speakers are six SN012776 on i2c3 (0x38-0x3d), but in a different + * order than J815's (ADT: 0x39 left woofer 2, 0x3a left tweeter, 0x3c right + * woofer 2, 0x3d right tweeter). Until their slots and a speaker protection + * profile are verified, neither the amplifiers nor their i2c3 bus are + * described: their driver never binds and they stay in shutdown. + */ + +#include "t8142-j813-audio.dtsi" + +&aop_audio { + /* The microphone card's name: AppleJ704HPAI. */ + apple,chassis-name = "J704"; + apple,machine-kind = "MacBook Pro"; +}; + +/delete-node/ &speaker_left_woofer; +/delete-node/ &speaker_left_tweeter; +/delete-node/ &speaker_right_woofer; +/delete-node/ &speaker_right_tweeter; +/* Nothing else is on the speakers' bus. */ +/delete-node/ &i2c3; + +/ { + sound { + compatible = "apple,j704-macaudio", "apple,macaudio"; + model = "MacBook Pro J704"; + + /delete-node/ dai-link@1; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8142-j704.dts b/arch/arm64/boot/dts/apple/t8142-j704.dts index aebc8830d136a0..c3bb183608c9a1 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704.dts +++ b/arch/arm64/boot/dts/apple/t8142-j704.dts @@ -322,3 +322,4 @@ #include "t8142-j704-pcie.dtsi" #include "t8142-j704-power.dtsi" #include "t8142-j704-hwmon.dtsi" +#include "t8142-j704-audio.dtsi" From 0de7a974ae75b395ddb017c195af5a61dba09375 Mon Sep 17 00:00:00 2001 From: termg Date: Sat, 21 Nov 2026 03:10:38 +0000 Subject: [PATCH 0409/1514] arm64: dts: apple: t8142-j704: Say the speaker amplifiers are never configured The comment said the J704's SN012776 amplifiers "stay in shutdown". With neither i2c3 nor their shutdown (SDZ) line described, Linux never touches them, so they stay in whatever state iBoot left them in after the chime. They still cannot play: there is no speaker link, so no bit clock. Say that instead. Signed-off-by: termg --- arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi index 474f8d25a108b8..72ef40e339647a 100644 --- a/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j704-audio.dtsi @@ -13,7 +13,9 @@ * order than J815's (ADT: 0x39 left woofer 2, 0x3a left tweeter, 0x3c right * woofer 2, 0x3d right tweeter). Until their slots and a speaker protection * profile are verified, neither the amplifiers nor their i2c3 bus are - * described: their driver never binds and they stay in shutdown. + * described: their driver never binds and Linux never configures them. Their + * shutdown (SDZ) line is not described either, so they keep the state iBoot + * left them in; with no speaker link there is no bit clock, so they cannot play. */ #include "t8142-j813-audio.dtsi" From 9377776ee95f8c7f823a9c086296d3b5c3da6763 Mon Sep 17 00:00:00 2001 From: termg Date: Sat, 21 Nov 2026 03:10:38 +0000 Subject: [PATCH 0410/1514] ASoC: apple: macaudio: No safe gain for J704 in the device table The J704 row listed a gain of 15, but macaudio_j704_cfg has no safe level: its speakers are off. Write "-", as the J775 rows do. Signed-off-by: termg --- sound/soc/apple/macaudio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index 13cff9b01a6da1..2043dc1415f222 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -4496,7 +4496,7 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j775c-macaudio", .data = &macaudio_j775_cfg }, /* j775d - sn012776 - 1x 1W (AOP-fed, no sense: speaker off) */ { .compatible = "apple,j775d-macaudio", .data = &macaudio_j775_cfg }, - /* j704 - sn012776 15 2x 2W+1T (AOP-fed; speakers off until bring-up) */ + /* j704 - sn012776 - 2x 2W+1T (AOP-fed; speakers off until bring-up) */ { .compatible = "apple,j704-macaudio", .data = &macaudio_j704_cfg }, /* j813 AID? sn012776 15 2x 1W+1T (AOP-fed, V/I sense) */ { .compatible = "apple,j813-macaudio", .data = &macaudio_j813_cfg }, From 8ee2b0b9cc273d765d99858dba17ad57fc12e766 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 05:47:05 +1100 Subject: [PATCH 0411/1514] dt-bindings: display: apple,dcp: describe a session handed over running A boot stage that lit a display may leave its display processor running with the RTKit session it negotiated. That firmware does not repeat HELLO or its endpoint map, so the operating system can only continue the session if the boot stage describes it. Document the properties the boot stage sets on the DCP node for that. apple,rtkit-handoff ("dcp-live-v1") and apple,rtkit-buffers follow the RTKit handoff of other co-processors handed over running; for a DCP the buffer's device address is the DART input address, and each buffer lies in a memory-region carveout that maps it through iommu-addresses. apple,rtkit-version and apple,rtkit-epmap carry the negotiated protocol version and endpoint map a DCP needs on top. Signed-off-by: Ryan Murray --- .../bindings/display/apple,dcp.yaml | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 193ceda46427f2..c0395f922f0975 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -279,6 +279,50 @@ properties: maxItems: 5 description: Loader-provided firmware ABI version used for IOMFB selection. + apple,rtkit-handoff: + $ref: /schemas/types.yaml#/definitions/string + enum: + - dcp-live-v1 + description: | + Added by a boot stage that negotiated RTKit with this processor and + handed it over running. Such a firmware does not repeat HELLO or its + endpoint map, so the operating system takes over the session as + described by apple,rtkit-version, apple,rtkit-epmap and + apple,rtkit-buffers instead of starting RTKit again. Absent when the + processor was not left running. + + apple,rtkit-version: + $ref: /schemas/types.yaml#/definitions/uint32 + description: RTKit protocol version of the handed-over session. + + apple,rtkit-epmap: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 8 + maxItems: 8 + description: | + Endpoints the firmware advertised for the handed-over session; word i + holds endpoints 32i to 32i + 31. Application endpoints are stopped at + the handover and are started again by the new owner. + + apple,rtkit-buffers: + oneOf: + - type: boolean + - $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 5 + maxItems: 20 + description: | + The shared buffers of the handed-over session, in groups of five + cells as for other co-processors handed over running: system endpoint + number (1 crashlog, 2 syslog, 4 IOReport, 8 OSLog, each at most once), + device address high cell, device address low cell, size in bytes, and + 1 if the firmware supplied the address (0 if the boot stage allocated + the buffer). The device address is the DART input address. Every + buffer lies inside one of the reserved-memory regions referenced by + memory-region, and that region maps it at the same address through + iommu-addresses, so the mapping survives the IOMMU taking over the + processor's page tables. An empty property records that the session + has no shared buffers. + apple,j613-25g83-dcpext-handoff: $ref: /schemas/types.yaml#/definitions/uint32 const: 1 From e59f0246ce81567316fc384781aecd5241923102 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 06:09:54 +1100 Subject: [PATCH 0412/1514] drm/apple: dpavservep: admit the MCDP29xx converters' AV service On the 27.2 firmware the M2 Mac mini's DCPs announce the AV service of their DP-to-HDMI converter on the classic DPAV endpoint, EPICUnit 0, with the converter's part as its class: AppleDCPMCDP29XX for the built-in HDMI port and AppleDCPMCDP2900 for a USB-C to HDMI adapter. Neither class is admitted, so the service is refused with -ENODEV, its EDID is never read and the HDMI connector reports a 0-byte EDID. Admit both classes under the same rules as AppleDCPDP2HDMI and DCPDP13Service. With it the M2 Mac mini's HDMI connector gets the monitor's 256-byte EDID (name, BT.2020 colorimetry, ST 2084). New identity cases cover both classes, a non-zero unit and another part. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep-identity-test.c | 8 ++++++++ drivers/gpu/drm/apple/epic/dpavservep.c | 9 ++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c index 4f36cc35758b4c..5f3732eecf7a9b 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c +++ b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c @@ -65,6 +65,14 @@ static const struct dpavid_case dpavid_cases[] = { "DCPDP13Service", 0, 7, true }, { "v2 ep 0x28: DP2HDMI unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "AppleDCPDP2HDMI", 0, 1, true }, + { "v2 ep 0x28: MCDP29XX unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP29XX", 0, 5, true }, + { "v2 ep 0x28: MCDP2900 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2900", 0, 1, true }, + { "v2 ep 0x28: MCDP2900 unit 1", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2900", 1, 1, false }, + { "v2 ep 0x28: other MCDP part", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, + "AppleDCPMCDP2800", 0, 1, false }, { "v2 ep 0x28: unit 0, channel at u16 max", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "DCPDP13Service", 0, 0xffff, true }, { "v2 ep 0x28: unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index efc3babff3cb78..5ca5e7af0370ea 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -44,8 +44,15 @@ static bool dcpavserv_identity(struct apple_epic_service *service, const char *n class && !strcmp(class, "DCPDPService") && service->channel; if (!service->ep->wire_v2) return unit == 0; + /* + * A DP-to-HDMI converter's AV service: the generic ones, and the + * MCDP29xx converters that firmware 27 names after their part (the + * M2 Mac mini's HDMI port, and USB-C to HDMI adapters). + */ if (!class || (strcmp(class, "AppleDCPDP2HDMI") && - strcmp(class, "DCPDP13Service")) || + strcmp(class, "DCPDP13Service") && + strcmp(class, "AppleDCPMCDP29XX") && + strcmp(class, "AppleDCPMCDP2900")) || !service->channel || service->channel > U16_MAX) return false; /* H17P's lower-case interface-id is dynamic, not a physical-port unit. */ From 0ee2165c6be9448c5574c8e86cc6d65fbe2fe8c1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 06:19:56 +1100 Subject: [PATCH 0413/1514] tools/asahi: check the RTKit import of an adopted session's endpoint map apple_rtkit_inherit_endpoints() decides which endpoints a session a boot stage handed over has; a wrong map either leaves application endpoints unstarted or lets RTKit accept traffic for endpoints it does not serve. Run the importer from the source on the host with the map the M2 Mac mini's HDMI display processor hands over on the 27.2 firmware, and check the version rules, the management endpoint, unknown system endpoints and the full endpoint range. The test also checks that the map replaces the assumed one before mailbox RX is claimed. One mutation per check makes sure each check is exercised. Signed-off-by: Ryan Murray --- tools/asahi/rtkit-adopted-session-tests.py | 180 +++++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 2 files changed, 183 insertions(+) create mode 100755 tools/asahi/rtkit-adopted-session-tests.py diff --git a/tools/asahi/rtkit-adopted-session-tests.py b/tools/asahi/rtkit-adopted-session-tests.py new file mode 100755 index 00000000000000..6f516abd9aac7d --- /dev/null +++ b/tools/asahi/rtkit-adopted-session-tests.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check how RTKit imports the endpoint map of a session a boot stage handed over.""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +INTERNAL = 'drivers/soc/apple/rtkit-internal.h' +HEADER = 'include/linux/soc/apple/rtkit.h' + +# Each mutation drops one check; an assertion must then fail. +MUTATIONS = { + 'no-management': ('if (!test_bit(APPLE_RTKIT_EP_MGMT, map))', 'if (0)'), + 'any-system': ('if (test_bit(i, map) && !test_bit(i, known))', 'if (0)'), + 'any-version': ('session->protocol_version < APPLE_RTKIT_MIN_SUPPORTED_VERSION ||', '0 ||'), + 'ignore-ops-version': ('session->protocol_version != rtk->ops->protocol_version', '0'), +} + + +def function(source, name): + match = re.search(r'^static int ' + name + r'\(', source, re.M) + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; +#define BUILD_BUG_ON(x) _Static_assert(!(x), #x) +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define DECLARE_BITMAP(n, bits) bool n[bits] +static void set_bit(unsigned int b, bool *m) { m[b] = true; } +static bool test_bit(unsigned int b, const bool *m) { return m[b]; } +static void bitmap_from_arr32(bool *m, const u32 *a, unsigned int bits) +{ for (unsigned int i = 0; i < bits; i++) m[i] = a[i / 32] >> (i % 32) & 1; } +static void bitmap_copy(bool *d, const bool *s, unsigned int bits) { memcpy(d, s, bits); } +struct apple_rtkit_inherited_buffer { int unused; }; +struct apple_rtkit_ops { u16 protocol_version; }; +''' + +TESTS = r''' +struct apple_rtkit { + const struct apple_rtkit_ops *ops; + bool endpoints[APPLE_RTKIT_MAX_ENDPOINTS]; + u16 version; +}; +''' + '%s' + r''' +static int run(u16 required, u16 version, const u32 *map, struct apple_rtkit *rtk) +{ + static struct apple_rtkit_ops ops; + struct apple_rtkit_adopted_session s = { .protocol_version = version }; + + ops.protocol_version = required; + memset(rtk, 0, sizeof(*rtk)); + rtk->ops = &ops; + memcpy(s.epmap, map, sizeof(s.epmap)); + return apple_rtkit_inherit_endpoints(rtk, &s); +} + +int main(void) +{ + /* + * An M2 Mac mini HDMI DCP on the 27.2 firmware, as its boot stage + * describes it: system endpoints 0-4 and 8, application endpoints + * 0x20-0x2c, 0x31 and 0x37. + */ + const u32 dcpext[8] = { 0x0000011f, 0x00821fff }; + struct apple_rtkit r; + u32 m[8]; + int i; + + assert(run(0, 12, dcpext, &r) == 0); + for (i = 0; i < APPLE_RTKIT_MAX_ENDPOINTS; i++) { + bool want = i <= 4 || i == 8 || (i >= 0x20 && i <= 0x2c) || + i == 0x31 || i == 0x37; + assert(r.endpoints[i] == want); + } + assert(r.version == 12); + + /* A driver that needs one protocol version takes only that one. */ + assert(run(12, 12, dcpext, &r) == 0); + assert(run(11, 12, dcpext, &r) == -EINVAL); + /* Versions RTKit does not speak are refused. */ + assert(run(0, APPLE_RTKIT_MIN_SUPPORTED_VERSION - 1, dcpext, &r) == -EINVAL); + assert(run(0, APPLE_RTKIT_MAX_SUPPORTED_VERSION + 1, dcpext, &r) == -EINVAL); + + /* Without management there is no session to adopt. */ + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~1u; + assert(run(0, 12, m, &r) == -EINVAL); + /* A system endpoint RTKit does not implement is not silently ignored. */ + memcpy(m, dcpext, sizeof(m)); + m[0] |= 1u << 5; + assert(run(0, 12, m, &r) == -EINVAL); + /* Tracekit (0xa) is one RTKit knows. */ + memcpy(m, dcpext, sizeof(m)); + m[0] |= 1u << 0xa; + assert(run(0, 12, m, &r) == 0 && r.endpoints[0xa]); + /* Every known system endpoint and every application endpoint. */ + for (i = 0; i < 8; i++) + m[i] = i ? ~0u : 0x59fu; + assert(run(0, 11, m, &r) == 0 && r.endpoints[0x20] && r.endpoints[0xff]); + /* Management alone. */ + memset(m, 0, sizeof(m)); + m[0] = 1; + assert(run(0, 12, m, &r) == 0 && r.endpoints[0] && !r.endpoints[0x37]); + + puts("PASS adopted session endpoint map, protocol version and system endpoints"); + return 0; +} +''' + + +def build_source(mutation): + driver = (ROOT / DRIVER).read_text() + internal = (ROOT / INTERNAL).read_text() + header = (ROOT / HEADER).read_text() + defines = re.findall(r'^#define APPLE_RTKIT_(?:MIN_SUPPORTED_VERSION|MAX_SUPPORTED_VERSION|' + r'APP_ENDPOINT_START|MAX_ENDPOINTS)\b.*$', driver + internal, re.M) + assert len(defines) == 4, defines + words = re.search(r'^#define APPLE_RTKIT_ADOPTED_EPMAP_WORDS.*$', header, re.M) + session = re.search(r'^struct apple_rtkit_adopted_session \{.*?^\};', header, re.M | re.S) + endpoints = re.search(r'enum \{\s*APPLE_RTKIT_EP_MGMT = 0,.*?\};', driver, re.S) + assert words and session and endpoints + imported = function(driver, 'apple_rtkit_inherit_endpoints') + if mutation: + old, new = MUTATIONS[mutation] + assert old in imported, mutation + imported = imported.replace(old, new) + # The firmware's map replaces the assumed one before RX can deliver + # traffic for its endpoints. + init = re.search(r'^static struct apple_rtkit \*__apple_rtkit_init\(.*?^\}', driver, re.M | re.S) + assert init + body = init.group(0) + assert (body.index('apple_rtkit_mark_running(rtk)') < + body.index('apple_rtkit_inherit_endpoints(') < + body.index('apple_rtkit_claim_rx(')) + return (PREFIX + '\n'.join(defines) + '\n' + words.group(0) + '\n' + endpoints.group(0) + + '\n' + session.group(0) + '\n' + TESTS % imported) + + +def run(out, cc, mutation): + source = out / 'rtkit-adopted-session.c' + binary = out / 'rtkit-adopted-session' + source.write_text(build_source(mutation)) + subprocess.run([cc, '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-fsanitize=address,undefined', + str(source), '-o', str(binary)], check=True) + return subprocess.run([str(binary)]).returncode + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--mutation', choices=sorted(MUTATIONS), + help='drop one check (the run must fail an assertion)') + args = parser.parse_args() + with tempfile.TemporaryDirectory() as tmp: + out = args.out or Path(tmp) + out.mkdir(parents=True, exist_ok=True) + status = run(out, args.cc, args.mutation) + raise SystemExit(status) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..03942d5188ad7b 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -292,6 +292,9 @@ def mutations(flag, names, base, expect=KILL): 'mailbox-minimum', 'version-string', 'message-string'), out()), 'rtkit-oslog-tests.py': [(out(), PASS)] + mutations('--mutate', ('admission', 'channel', 'counter', 'reset', 'buffer'), out()), + 'rtkit-adopted-session-tests.py': [(out(), PASS)] + + mutations('--mutation', ('no-management', 'any-system', 'any-version', + 'ignore-ops-version'), out()), 'rtkit-retained-tests.py': [(out(), PASS)], 't6030-clock-tests.py': [(out(), PASS)], 't6030-display-admission-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], From 638611e15e64549f27d46eb0aad3947bb4d8ee61 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 06:46:37 +1100 Subject: [PATCH 0414/1514] drm/apple: dcp: read a live DCP session from the RTKit handoff properties Describe the session a boot stage hands over with the RTKit handoff properties other co-processors use: apple,rtkit-handoff ("dcp-live-v1") and apple,rtkit-buffers in tuples, plus apple,rtkit-version and apple,rtkit-epmap, instead of a parallel set of properties with physical addresses in them. Each buffer's physical address now comes from the DCP's own DART: it must translate the whole buffer contiguously, and the result must lie in one of the node's carveouts, as before. A boot stage that publishes the old properties is not adopted and the DCP takes its normal start. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 2 +- drivers/gpu/drm/apple/dcp.c | 77 ++++++++++++++-------------- 2 files changed, 40 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 68ccf32aad9306..730ca75f04d30d 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -473,7 +473,7 @@ struct apple_dcp { struct iomfb_m4 *v26_6; /* An adopted session has no confirmed firmware DMA stop boundary. */ bool retain_dma; - /* RTKit session handed over running by a boot stage (apple,rtkit-live) */ + /* RTKit session handed over running by a boot stage (apple,rtkit-handoff) */ bool rtkit_adopted; /* * Allocates AFK rings where the DMA API cannot, on an adopted diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index a2ad08dbbef9c5..a68631cadf0b68 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1844,10 +1844,9 @@ static int dcp_check_iova_contiguous(struct iommu_domain *domain, return 0; } -#define DCP_RTKIT_LIVE_V1 1 -#define DCP_RTKIT_LIVE_BUFFER_CELLS 8 +#define DCP_RTKIT_HANDOFF "dcp-live-v1" +#define DCP_RTKIT_LIVE_BUFFER_CELLS 5 #define DCP_RTKIT_LIVE_MAX_BUFFERS 4 -#define DCP_RTKIT_LIVE_LOADER_OWNED BIT(0) struct dcp_rtkit_live { struct apple_rtkit_adopted_session session; @@ -1892,29 +1891,32 @@ static void dcp_rtkit_live_unmap(struct dcp_rtkit_live *live) /* * A boot stage that negotiated RTKit with this DCP and handed it over running - * describes the session on the node: apple,rtkit-live (layout version), - * apple,rtkit-version, apple,rtkit-epmap (word i = endpoints 32i..32i+31) and - * apple,rtkit-live-buffers ( per system buffer, each inside one of the node's memory-region - * carveouts and mapped there through its iommu-addresses). Such a firmware - * does not repeat HELLO or EPMAP. Returns 1 with the session filled in, 0 without a description, or an - * error for one that cannot be adopted safely. + * describes the session on the node, with the RTKit handoff properties of other + * co-processors handed over running: apple,rtkit-handoff ("dcp-live-v1") and + * apple,rtkit-buffers ( per system buffer, the + * device address being the DART input address), plus apple,rtkit-version and + * apple,rtkit-epmap (word i = endpoints 32i..32i+31). Each buffer lies in one of + * the node's memory-region carveouts, mapped there through its iommu-addresses. + * Such a firmware does not repeat HELLO or EPMAP. Returns 1 with the session + * filled in, 0 without a description, or an error for one that cannot be adopted + * safely. */ static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *live) { u32 cells[DCP_RTKIT_LIVE_MAX_BUFFERS * DCP_RTKIT_LIVE_BUFFER_CELLS]; struct device_node *np = dcp->dev->of_node; struct iommu_domain *domain; - u32 layout, version; + const char *handoff; int count, i, ret; + u32 version; - if (!of_property_present(np, "apple,rtkit-live")) + if (!of_property_present(np, "apple,rtkit-handoff")) return 0; - ret = of_property_read_u32(np, "apple,rtkit-live", &layout); + ret = of_property_read_string(np, "apple,rtkit-handoff", &handoff); if (ret) return ret; - if (layout != DCP_RTKIT_LIVE_V1) { - dev_err(dcp->dev, "unknown live RTKit layout %u\n", layout); + if (strcmp(handoff, DCP_RTKIT_HANDOFF)) { + dev_err(dcp->dev, "unknown RTKit handoff \"%s\"\n", handoff); return -EINVAL; } if (!(readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & @@ -1932,14 +1934,14 @@ static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *li if (ret) return ret; - count = of_property_count_u32_elems(np, "apple,rtkit-live-buffers"); - if (count == -EINVAL) + count = of_property_count_u32_elems(np, "apple,rtkit-buffers"); + if (count == -EINVAL || count == -ENODATA) count = 0; if (count < 0 || count > ARRAY_SIZE(cells) || count % DCP_RTKIT_LIVE_BUFFER_CELLS) return -EINVAL; if (count) { - ret = of_property_read_u32_array(np, "apple,rtkit-live-buffers", + ret = of_property_read_u32_array(np, "apple,rtkit-buffers", cells, count); if (ret) return ret; @@ -1954,30 +1956,29 @@ static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *li for (i = 0; i < count; i++) { const u32 *t = &cells[i * DCP_RTKIT_LIVE_BUFFER_CELLS]; struct apple_rtkit_inherited_buffer *b = &live->buffers[i]; - u64 iova = (u64)t[2] << 32 | t[3]; - u64 phys = (u64)t[4] << 32 | t[5]; - u64 size = (u64)t[6] << 32 | t[7]; - - if (t[0] > U8_MAX || (t[1] & ~DCP_RTKIT_LIVE_LOADER_OWNED) || - !size || size > SZ_16M || !PAGE_ALIGNED(phys) || - !PAGE_ALIGNED(size) || iova + size < iova || - phys + size < phys) { + u64 iova = (u64)t[1] << 32 | t[2]; + u64 size = t[3]; + phys_addr_t phys; + + /* The system endpoints with shared buffers, as for other handoffs. */ + if ((t[0] != 1 && t[0] != 2 && t[0] != 4 && t[0] != 8) || + t[4] > 1 || !size || size > SZ_16M || !PAGE_ALIGNED(iova) || + !PAGE_ALIGNED(size) || iova + size < iova) { ret = -EINVAL; goto fail; } - if (!dcp_rtkit_live_carveout(np, phys, size)) { - dev_err(dcp->dev, "live RTKit buffer %#llx+%#llx is not in a DCP carveout\n", - phys, size); - ret = -EACCES; + /* The DCP's own DART says where the buffer is; it must be contiguous. */ + phys = iommu_iova_to_phys(domain, iova); + ret = phys ? dcp_check_iova_contiguous(domain, iova, size, phys) : -ENXIO; + if (ret) { + dev_err(dcp->dev, "live RTKit buffer ep%u iova %#llx+%#llx is not mapped\n", + t[0], iova, size); goto fail; } - /* The DCP's own DART must already translate it to that memory. */ - ret = dcp_check_iova_contiguous(domain, iova, size, phys); - if (ret) { - dev_err(dcp->dev, - "live RTKit buffer ep%u iova %#llx is not mapped to %#llx (DART: %pa)\n", - t[0], iova, phys, - &(phys_addr_t){ iommu_iova_to_phys(domain, iova) }); + if (!dcp_rtkit_live_carveout(np, phys, size)) { + dev_err(dcp->dev, "live RTKit buffer %pa+%#llx is not in a DCP carveout\n", + &phys, size); + ret = -EACCES; goto fail; } @@ -7510,7 +7511,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) return ret; dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); /* A boot stage handed this DCP over running: keep its session. */ - if (of_property_present(dev->of_node, "apple,rtkit-live")) + if (of_property_present(dev->of_node, "apple,rtkit-handoff")) dcp->hw.adopt_live_session = true; /* The link report: on the board it has run on (dcp_j714s_ext()). */ if (!dcp_j714s_ext(dev)) From 676064c49b98365cac91ac0662c9524d8d3b63f8 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 19:26:24 +0100 Subject: [PATCH 0415/1514] drm/asahi: g18: bound, rate-limit and drain the async job queue Three follow-ups to the asynchronous submit path (#2679): - A failed job is reported at most once a second, with the number of failures not reported in between, unless VerboseFaults is set, as for GPU faults. A client that submits failing jobs in a loop could otherwise flood the log; the output fence and the queue's next submit still carry every error. - The device holds at most 256 jobs waiting to run, over all queues and files. Each queue was bounded at 32, but a file can open any number of queues. A submit takes one of the 256 slots after it has waited for other drivers' fences and before it publishes anything, so a signal restarts the ioctl as the existing waits do. The slot becomes the job, or is given back if the submit fails. The bound is device-wide on purpose: one worker runs the jobs in the order they were accepted, so a client blocked by a full device would only have waited on its fence instead. - Jobs run on the device's own unbound workqueue instead of system_unbound, with WQ_MEM_RECLAIM, since memory reclaim can wait for the fences its jobs signal. The worker is a work item that is part of the job queue, and the queue of waiting jobs is allocated for 256 up front, so nothing is allocated under the state lock, which the worker takes while fences are pending. When G18DrmGpu is dropped, the queue is taken out of the job state and destroyed, which waits for the worker to return, so no job work item outlives the device. A submit after that is refused with -ENODEV. On the J873 this happens only on the probe error path today: once the firmware session starts, the module is pinned until reboot and the platform driver has no bind attributes. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/g18/drm.rs | 168 +++++++++++++++++++++++++++---- 1 file changed, 148 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index e011c75f6ba2bd..14a726b24fc4cc 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -24,7 +24,9 @@ use core::ops::Range; use core::sync::atomic::{AtomicI32, Ordering}; use kernel::{bindings, macros::vtable, new_condvar, new_mutex, prelude::*, static_lock_class, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, - sync::{Arc, CondVar, Mutex, SpinLock}, uapi, workqueue, xarray}; + sync::{Arc, CondVar, Mutex, SpinLock}, time::{Delta, Instant, Monotonic}, uapi, workqueue, + xarray}; +use crate::debug::{debug_enabled, DebugFlags}; use crate::{alloc, driver::AsahiRegData, file, g18::uapi::command as g17_uapi, g18::hw, g18::uapi::application::{self as g18_application, G18ApplicationRefusal, G18RenderJobSink, G18RenderRetirement}, gem, gpu, g18::fw::vm_layout as m5_vm, mmu, queue, stats, stats_raw, timestamp}; @@ -154,6 +156,14 @@ impl G18DrmGpu { } } +impl Drop for G18DrmGpu { + /// Every file has let go of the device: finish the accepted jobs and + /// destroy the worker queue before the module can be unloaded. + fn drop(&mut self) { + self.jobs.shut_down(); + } +} + // Module 1134 reached G18 through its `DrmGpu` trait (drm_gpu.rs) and // computed GET_PARAMS in file.rs from `DrmGpu::params`; here the same facts // fill `drm_asahi_params_global` through `gpu::Gpu::get_params`. The shared @@ -340,6 +350,22 @@ impl Drop for JobFence { /// Accepted jobs a queue may have waiting or running; a further submit /// waits for the oldest. const QUEUE_DEPTH: usize = 32; +/// Jobs waiting to run on the device, over all its queues and files, counting +/// the submits that hold a [`Room`]; a further submit waits for room before +/// it publishes anything. A file may open any number of queues, and each may +/// hold [`QUEUE_DEPTH`]. A waiting job holds its translated commands, its +/// input fences and its VM job guard, which keeps the mappings it uses +/// pinned, so this bounds the kernel memory and the mappings that work not +/// yet run can hold. 256 is eight queues at [`QUEUE_DEPTH`]. +/// +/// The bound is device-wide, so a file that fills it makes another client's +/// submit wait in the ioctl. That is intended: one worker runs the jobs in +/// the order they were accepted, so that client's job would run after those +/// 256 anyway, and the cap only moves its wait from the output fence into +/// the ioctl. A per-file share would change who waits, not when work runs. +const DEVICE_DEPTH: usize = 256; +/// The shortest time between two reports of a failed asynchronous job. +const FAILURE_REPORT_INTERVAL: Delta = Delta::from_millis(1000); /// One accepted submission. Dropping it signals its output fence. struct G18Job { @@ -362,7 +388,7 @@ struct G18Job { } impl G18Job { - fn run(mut job: KBox) { + fn run(mut job: KBox, jobs: &JobQueue) { let result = job.execute(); // Release the mappings before the fence signals, as a synchronous // submit did. @@ -373,9 +399,14 @@ impl G18Job { // The ioctl returned long ago and cannot report this; the output // fence carries the error and the queue's next submit returns it. (None, Err(error)) => { - let len = job.comm.iter().position(|&c| c == 0).unwrap_or(job.comm.len()); - pr_warn!("G18 job failed: submission {} pid {} ({}): {:?}\n", job.submission, - job.pid, kernel::str::BStr::from_bytes(&job.comm[..len]), error); + if let Some(unreported) = jobs.failure_report() { + if unreported > 0 { + pr_warn!("G18: {} more failed jobs not reported\n", unreported); + } + let len = job.comm.iter().position(|&c| c == 0).unwrap_or(job.comm.len()); + pr_warn!("G18 job failed: submission {} pid {} ({}): {:?}\n", job.submission, + job.pid, kernel::str::BStr::from_bytes(&job.comm[..len]), error); + } let _ = job.queue_failed.compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire); } @@ -442,27 +473,59 @@ impl G18Job { struct JobQueue { #[pin] state: Mutex, - /// Notified whenever `completed` advances. + /// Notified whenever `completed` advances, or a [`Room`] is given back. #[pin] retired: CondVar, + /// The worker, queued on `workers` to drain `pending`. It is part of the + /// queue, so starting it allocates nothing under the state lock, which + /// the fence-signalling worker takes. + #[pin] + work: workqueue::Work, +} + +kernel::impl_has_work! { + impl HasWork for JobQueue { self.work } +} + +impl workqueue::WorkItem for JobQueue { + type Pointer = Arc; + + fn run(this: Arc) { + this.drain(); + } } struct JobQueueState { + /// Allocated for [`DEVICE_DEPTH`] jobs up front: nothing is allocated + /// under the state lock. pending: KVec>, /// A worker is draining `pending`. running: bool, /// Sequence numbers of the last accepted and the last finished job. submitted: u64, completed: u64, + /// Submits holding a [`Room`]: they may each add one job. + reserved: usize, + /// The device's own worker queue; taken, and so drained, when the device + /// goes away. Without it no job is accepted. Its jobs signal fences that + /// memory reclaim can wait for, so it has a rescuer (WQ_MEM_RECLAIM). + workers: Option, + /// When the last failed job was reported, and how many have not been since. + reported: Option>, + unreported: u32, } impl JobQueue { fn new() -> Result> { + let workers = workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g18_jobs", false)?; + let pending = KVec::with_capacity(DEVICE_DEPTH, GFP_KERNEL)?; Arc::pin_init(pin_init!(Self { state <- new_mutex!(JobQueueState { - pending: KVec::new(), running: false, submitted: 0, completed: 0, + pending, running: false, submitted: 0, completed: 0, + reserved: 0, workers: Some(workers), reported: None, unreported: 0, }, "G18 jobs"), retired <- new_condvar!("G18 job retired"), + work <- kernel::new_work!("G18 job worker"), }), GFP_KERNEL) } @@ -471,21 +534,24 @@ impl JobQueue { /// cannot be queued. The fence is installed under the lock, once the /// job has its place: a submission that finds it in a syncobj is /// accepted later and so runs after the job that signals it. - fn push(self: &Arc, publication: OutputPublication, + fn push(self: &Arc, room: Room, publication: OutputPublication, job: impl FnOnce(JobFence) -> KBox) - -> core::result::Result { + -> core::result::Result { + // On a refusal `room`, a parameter, is dropped after `state` and gives + // its slot back then; an accepted job takes it over under the lock. let mut state = self.state.lock(); - if state.pending.reserve(1, GFP_KERNEL).is_err() { return Err(publication); } + let Some(workers) = state.workers.as_ref() else { return Err((publication, ENODEV)) }; + // The room keeps pending.len() below DEVICE_DEPTH, the capacity. + if state.pending.len() >= state.pending.capacity() { return Err((publication, ENOMEM)); } if !state.running { - let this = self.clone(); - if workqueue::system_unbound().try_spawn(GFP_KERNEL, move || this.drain()).is_err() { - return Err(publication); - } + // Already queued means a drain is about to run anyway. + let _ = workers.enqueue(self.clone()); state.running = true; } let job = job(publication.accept()); - // Cannot fail: room was reserved above. + // Cannot fail: the capacity was checked above, under the same lock. let _ = state.pending.push_within_capacity(job); + room.consume(&mut state); state.submitted += 1; Ok(state.submitted) } @@ -499,12 +565,48 @@ impl JobQueue { Err(_) => { state.running = false; return; } } }; - G18Job::run(job); + G18Job::run(job, self); self.state.lock().completed += 1; self.retired.notify_all(); } } + /// Wait, interruptibly, until the jobs waiting to run and the [`Room`]s + /// taken are fewer than [`DEVICE_DEPTH`], then take one. Called before + /// anything is published, so a signal restarts the ioctl. + fn wait_room(self: &Arc) -> Result { + let mut state = self.state.lock(); + while state.pending.len() + state.reserved >= DEVICE_DEPTH { + if self.retired.wait_interruptible(&mut state) { return Err(ERESTARTSYS); } + } + state.reserved += 1; + Ok(Room(Some(self.clone()))) + } + + /// Whether to report a failed job now, with how many were not reported + /// since the last report: at most one report per [`FAILURE_REPORT_INTERVAL`]. + /// With `VerboseFaults` set every failure is reported, as GPU faults are. + fn failure_report(&self) -> Option { + let mut state = self.state.lock(); + let recent = state.reported.as_ref() + .is_some_and(|last| last.elapsed() < FAILURE_REPORT_INTERVAL); + if recent && !debug_enabled(DebugFlags::VerboseFaults) { + state.unreported = state.unreported.saturating_add(1); + return None; + } + state.reported = Some(Instant::now()); + Some(core::mem::take(&mut state.unreported)) + } + + /// Stop accepting jobs and wait for the worker to finish the accepted + /// ones, so that no work item of this module runs after it goes away. + fn shut_down(&self) { + let workers = self.state.lock().workers.take(); + // Dropping the queue destroys it, which drains it; the worker takes the + // state lock, so it must not be held here. + drop(workers); + } + /// Wait until job `seq` has finished and its fence has signalled. fn wait(&self, seq: u64, interruptible: bool) -> Result { let mut state = self.state.lock(); @@ -519,6 +621,28 @@ impl JobQueue { } } +/// A slot taken by [`JobQueue::wait_room`]: its submit may add one job. +/// [`JobQueue::push`] turns it into that job; dropping it gives the slot back. +struct Room(Option>); + +impl Room { + /// The job is in `pending` now and holds the slot itself: no waiter can + /// get in, so none is woken. + fn consume(mut self, state: &mut JobQueueState) { + state.reserved -= 1; + self.0 = None; + } +} + +impl Drop for Room { + fn drop(&mut self) { + if let Some(jobs) = self.0.take() { + jobs.state.lock().reserved -= 1; + jobs.retired.notify_all(); + } + } +} + struct UserAddressSpace<'a> { vm: &'a mmu::Vm } impl g17_uapi::GpuAddressSpace for UserAddressSpace<'_> { fn covers(&self, address: u64, size: u64, access: g17_uapi::GpuAccess) -> bool { @@ -593,6 +717,9 @@ impl queue::Queue for G18Queue { let fence: UserFence = self.fences.new_fence(0, G18SubmissionFence)?.into(); wait_foreign_inputs(&fence, &syncs[..in_sync_count])?; + // Taken after the foreign inputs, so that a submit waiting for + // another driver's fence holds no slot meanwhile. + let room = self.jobs.wait_room()?; let synchronous = !self.asynchronous || syncs.len() == in_sync_count; let mut publication = OutputPublication { fence: Some(fence), syncs, input_count: in_sync_count, result: Err(ECANCELED), @@ -611,6 +738,7 @@ impl queue::Queue for G18Queue { let (slot, result, inputs, vm_job, commands) = match accepted { Ok(accepted) => accepted, Err(error) => { + drop(room); // The runtime records and quarantines a failed published VM // before this output fence is installed/signalled by the // publication guard, after the queue's earlier fences. @@ -629,13 +757,13 @@ impl queue::Queue for G18Queue { fence, queue_failed: self.failed.clone(), submission: submission_id, pid: task.pid(), comm, }); - let seq = match self.jobs.push(publication, job) { + let seq = match self.jobs.push(room, publication, job) { Ok(seq) => seq, - Err(mut publication) => { + Err((mut publication, error)) => { // As above: the fence signals after the queue's earlier ones. - publication.result = Err(ENOMEM); + publication.result = Err(error); self.jobs.wait(self.last, false)?; - return Err(ENOMEM); + return Err(error); } }; self.recent[self.next] = seq; From 311ccad59cde3f323293cdfb55676bae3cd67df1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 06:59:37 +1100 Subject: [PATCH 0416/1514] Revert "drm/apple: dpavservep: admit the AFKV2 AV service on the classic DPAV endpoint" This reverts commit 78e59bdf47516725479015dacca0597d6e7fc154. With the external DCP's AV service admitted, the M4 MacBook Air (J713, macOS 27.2 stub) resets about 0.6 s after a DPMS off while it drives an external monitor. The last kernel lines before the reset are the external processor releasing the DP link (dcp_dptx_disconnect) and the hotplug mode probe that follows. Nothing else reaches the kernel log or a network console, and the Mac comes back on its default boot. The likely trigger is a request to the AV service while the firmware is closing it with the link, but that is not proven yet. On the J713 default kernel the first DPMS off resets the Mac. The same kernel with only this commit reverted, so the service is refused again, completes 3 of 3 DPMS off/on cycles with the monitor on. Both outputs are off while blanked and back after, with no DART faults, oopses or AVCs. Revert it until the AV service is used safely across a link release, proven with DPMS and sleep rows on both Airs. External monitors on the Airs keep their modes from the firmware's catalogue; they lose the monitor name and EDID colour data again. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep.c | 15 ++++----------- .../selftests/drivers/gpu/apple-dcp/edid.py | 14 -------------- 2 files changed, 4 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index efc3babff3cb78..37038852e5ca4f 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -44,18 +44,11 @@ static bool dcpavserv_identity(struct apple_epic_service *service, const char *n class && !strcmp(class, "DCPDPService") && service->channel; if (!service->ep->wire_v2) return unit == 0; - if (!class || (strcmp(class, "AppleDCPDP2HDMI") && - strcmp(class, "DCPDP13Service")) || - !service->channel || service->channel > U16_MAX) - return false; /* H17P's lower-case interface-id is dynamic, not a physical-port unit. */ - if (service->ep->endpoint == DPAVSERV_ENDPOINT_V2) - return unit == service->channel; - /* - * An AFKV2 AV service on the classic DPAV endpoint carries EPICUnit 0; - * its interface-id (the channel) is dynamic across reconnects. - */ - return service->ep->endpoint == DPAVSERV_ENDPOINT && unit == 0; + return service->ep->endpoint == DPAVSERV_ENDPOINT_V2 && class && + (!strcmp(class, "AppleDCPDP2HDMI") || + !strcmp(class, "DCPDP13Service")) && service->channel && + service->channel <= U16_MAX && unit == service->channel; } static bool dcpavserv_admission_current(struct apple_dcp *dcp, u64 generation) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 7b4df18396a6e5..fe2e56e1f46ea9 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -293,20 +293,6 @@ def function(file,signature): const char *forged[]={"DCPDP13ServiceExtra","dcpdp13service","AppleDCPDP2HDMIExtra","unrelated-provider"}; announce(13,name,forged[variant],13);assert(opens==before && !d.dcpavserv.service); } - /* AFKV2 on the classic DPAV endpoint: EPICUnit 0 with a dynamic interface-id. */ - ep.endpoint=0x28; - for(unsigned int variant=0;variant<2;variant++) { - const char *provider=variant?native_class:class; - assert(!prepare(1,1,name,provider));assert(!prepare(5,5,name,provider)); - assert(!prepare(0,0,name,provider));assert(!prepare(65536,0,name,provider)); - assert(!prepare(5,0,"dcpdp-service-epic",provider));assert(!prepare(5,0,name,"unrelated-provider")); - for(u32 channel=1;channel<=13;channel+=4) { - struct apple_epic_service *s=prepare(channel,0,name,provider); - assert(s && "EPICUnit-0 AV provider must be admitted");afk_service_discard(s); - } - } - ep.endpoint=0x2c;assert(!prepare(5,0,name,native_class));ep.endpoint=0x2a; - assert(!prepare(5,0,name,native_class)); /* H17P keeps unit == interface-id. */ assert(!prepare(13,13,name,NULL)); open_error=-EIO;announce(13,name,native_class,13);assert(opens==++before && !d.dcpavserv.service);open_error=0; for(unsigned int window=0;window<5;window++) { From 51fb66c22f2022c7607de88c1df7b3f0db940d01 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Sun, 22 Nov 2026 21:17:22 +0100 Subject: [PATCH 0417/1514] arm64: dts: apple: t8142-j813: add pmp alias and drop static PMP values t8142-j813-peripherals.dtsi (shared by J813 and J815) defines the PMP node without a /aliases pmp entry, unlike t8142-j704-peripherals.dtsi and t8140-j700.dts. Without the alias, Aura's dt_set_pmp() skips the node and Linux boots the PMP with values hardcoded from a single J813 unit: apple,board-id = <36> (overridden to <38> on J815), apple,dram-vendor-id = <1>, and 61 static apple,tunable-* properties in t8142-j813-pmp-tunables.dtsi. On machines with different DRAM vendors (for example, a J813 whose ADT /chosen reports dram-vendor-id 255 / Micron), the PMP never receives this machine's actual dram-vendor-id, per-unit boot arguments, or live /arm-io/pmp/iop-pmp-nub tunables, and J815 inherits J813's static tunable table as well. Add pmp = &pmp to /aliases in t8142-j813-peripherals.dtsi, drop the hardcoded apple,board-id, apple,dram-vendor-id, and t8142-j813-pmp-tunables.dtsi (along with the now-redundant board-id override in t8142-j815.dts), matching t8142-j704-peripherals.dtsi. Aura populates these properties from each machine's ADT at boot; on T8142, dart-pmp carries no DAPF aperture in its ADT instance table so Aura's dapf_init_fdt() leaves it to firmware. Signed-off-by: Bartosz Nitka --- .../dts/apple/t8142-j813-peripherals.dtsi | 11 +-- .../dts/apple/t8142-j813-pmp-tunables.dtsi | 70 ------------------- arch/arm64/boot/dts/apple/t8142-j815.dts | 6 -- 3 files changed, 6 insertions(+), 81 deletions(-) delete mode 100644 arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi diff --git a/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi index a387343ee2610d..c9038be7707c14 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-peripherals.dtsi @@ -4,6 +4,7 @@ / { aliases { nvram = &nvram; + pmp = &pmp; }; /* J813 ADT /arm-io/qspi clock-ids [396]; rate as the T8140 QSPI. */ @@ -102,10 +103,11 @@ mbox-names = "mbox"; iommus = <&pmp_dart 0>; power-domains = <&ps_pmp>; - /* ADT /chosen board-id, dram-vendor-id */ - apple,board-id = <36>; - apple,dram-vendor-id = <1>; - /* ADT /arm-io/pmgr pmc, pmc-pmgr (registry-v2 boot arguments) */ + /* + * ADT /arm-io/pmgr pmc, pmc-pmgr (registry-v2 boot arguments). + * The loader adds apple,board-id, apple,dram-vendor-id and the + * apple,tunable-* values from this machine's ADT. + */ apple,pmc = <1>; apple,pmc-pmgr = <31>; }; @@ -163,7 +165,6 @@ #pwm-cells = <2>; }; }; -#include "t8142-j813-pmp-tunables.dtsi" &pmp_dart { apple,dma-range = /bits/ 64 <0x10000000000 0xbff00000>; diff --git a/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi deleted file mode 100644 index fa34d4d80fe7d3..00000000000000 --- a/arch/arm64/boot/dts/apple/t8142-j813-pmp-tunables.dtsi +++ /dev/null @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* - * J813 PMP firmware properties: the ADT /arm-io/pmp/iop-pmp-nub values the - * firmware queries by name at boot (pmp.rs serves apple,tunable-). - * Generated from the J813 ADT by tools/adtnub.py; raw ADT bytes. - */ - -&pmp { - apple,tunable-agx-dcs-bw-constraint = [00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00]; - apple,tunable-mc_quota_req_ptd_count = [08 00 00 00]; - apple,tunable-mc_cmd_ptd_count = [02 00 00 00]; - apple,tunable-ane-dcs-bw-dvfs-filter = [ff ff 1f 00]; - apple,tunable-sochot-sensors = [01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00]; - apple,tunable-soc-ni3-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-agx-af-rd-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 00 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 00 00 00 00 00 00 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 39 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 12 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 11 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3c 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 7a 00 00 00 00 00 00 00 32 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 79 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2c 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 8a 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 89 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1e 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3e 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 6f 00 00 00 00 00 00 00 3d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 6e 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 34 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 33 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2c 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 40 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00]; - apple,tunable-ane-af-bw-dvfs-filter = [ff ff 1f 00]; - apple,tunable-ans-af-bw-threshold = [70 3d 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 70 3d 0b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 cc 0c 1c 00 00 00 00 00]; - apple,tunable-ptd-range = [01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 50 54 44 2d 4e 55 4c 4c 00 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 01 00 00 00 0b 00 00 00 50 4d 50 2d 53 54 41 54 55 53 00 00 00 00 00 00 03 00 00 00 02 00 00 00 04 00 00 00 00 00 00 00 44 56 46 53 2d 53 54 41 54 45 00 00 00 00 00 00 04 00 00 00 06 00 00 00 04 00 00 00 00 00 00 00 50 4d 50 54 4f 4f 4c 00 00 00 00 00 00 00 00 00 05 00 00 00 98 00 00 00 08 00 00 00 00 00 00 00 50 4d 53 2d 50 4d 47 52 2d 50 4b 54 00 00 00 00 06 00 00 00 a0 00 00 00 08 00 00 00 00 00 00 00 50 4d 53 2d 44 50 45 2d 50 4b 54 00 00 00 00 00 07 00 00 00 28 02 00 00 18 00 00 00 00 00 00 00 50 4d 53 2d 44 45 56 43 2d 50 4b 54 00 00 00 00 09 00 00 00 a8 00 00 00 80 01 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 4b 54 00 00 00 00 00 0a 00 00 00 27 00 00 00 08 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 53 2d 52 45 51 00 00 0b 00 00 00 2f 00 00 00 08 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 50 53 2d 41 43 4b 00 00 0c 00 00 00 37 00 00 00 10 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 44 56 46 53 00 00 00 00 0d 00 00 00 47 00 00 00 0a 00 00 00 00 00 00 00 53 4f 43 2d 44 45 56 2d 42 57 52 00 00 00 00 00 0e 00 00 00 13 00 00 00 0a 00 00 00 00 00 00 00 4d 43 2d 44 52 56 2d 54 4f 2d 43 54 52 4c 00 00 0f 00 00 00 51 00 00 00 01 00 00 00 00 00 00 00 44 56 46 53 2d 43 45 49 4c 00 00 00 00 00 00 00 14 00 00 00 0a 00 00 00 01 00 00 00 00 00 00 00 41 56 44 2d 4e 52 47 00 00 00 00 00 00 00 00 00 15 00 00 00 0b 00 00 00 01 00 00 00 00 00 00 00 53 4f 43 2d 41 4f 4e 2d 4e 52 47 00 00 00 00 00 16 00 00 00 0c 00 00 00 01 00 00 00 00 00 00 00 53 4f 43 2d 52 45 53 54 2d 4e 52 47 00 00 00 00 1e 00 00 00 1d 00 00 00 09 00 00 00 00 00 00 00 4d 43 2d 43 54 52 4c 2d 54 4f 2d 44 52 56 00 00 1f 00 00 00 0f 00 00 00 02 00 00 00 0c 00 00 00 46 41 53 54 2d 44 49 45 2d 43 45 00 00 00 00 00 20 00 00 00 52 00 00 00 07 00 00 00 0d 00 00 00 53 4d 43 2d 54 4f 2d 50 50 4d 00 00 00 00 00 00 21 00 00 00 0d 00 00 00 01 00 00 00 0a 00 00 00 4c 54 53 2d 56 4f 4c 54 2d 43 41 50 00 00 00 00 40 00 00 00 59 00 00 00 05 00 00 00 0e 00 00 00 50 50 4d 2d 54 4f 2d 53 4d 43 00 00 00 00 00 00 41 00 00 00 5e 00 00 00 05 00 00 00 0f 00 00 00 43 4c 50 43 2d 54 4f 2d 53 4d 43 00 00 00 00 00 43 00 00 00 11 00 00 00 02 00 00 00 00 00 00 00 46 41 53 54 2d 44 49 45 2d 54 4f 2d 53 4d 43 00 44 00 00 00 26 00 00 00 01 00 00 00 00 00 00 00 4d 45 4d 43 2d 54 4f 2d 53 4d 43 00 00 00 00 00 52 00 00 00 0e 00 00 00 01 00 00 00 00 00 00 00 4c 54 53 2d 54 4f 2d 47 46 58 00 00 00 00 00 00]; - apple,tunable-sram-index = [01 00 00 00]; - apple,tunable-no-shutdown = [01 00 00 00]; - apple,tunable-dvfs-domain = [01 00 00 00 08 00 00 00 00 00 00 00 44 43 53 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 05 00 00 00 00 00 00 00 53 4f 43 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 06 00 00 00 00 00 00 00 44 49 53 50 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-dvfs-disp-min-state = [01 00 00 00]; - apple,tunable-fast-die-ctrl-ce-map = [01 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 5f 41 4e 45 00 00 00 00 00 00 00 00]; - apple,tunable-ane-dcs-bw-constraint = [00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00]; - apple,tunable-soc-ni2-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-agx-af-wr-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-user-power-managed = [01 00 00 00]; - apple,tunable-ane-af-bw-threshold = [00 00 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 1c 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 09 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f4 01 00 00 00 00 00 00 06 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 16 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 15 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 40 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3f 00 00 00 00 00 00 00 12 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 3e 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3a 00 00 00 00 00 00 00 0c 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 39 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3a 00 00 00 00 00 00 00 0c 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 39 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 31 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 1e 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 0e 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 08 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 02 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 f4 01 00 00 00 00 00 00 02 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 f3 01 06 00 00 00]; - apple,tunable-lts-voltage = [01 00 00 00 03 00 00 00 03 00 00 00 01 00 00 00 45 41 43 43 00 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 02 00 00 00 50 41 43 43 00 00 00 00 03 00 00 00 01 00 00 00 06 00 00 00 00 00 00 00 41 4e 45 00 00 00 00 00 04 00 00 00 03 00 00 00 05 00 00 00 04 00 00 00 41 47 58 00 00 00 00 00]; - apple,tunable-ane-dcs-bw-threshold = [a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00 a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00 a3 f0 13 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 a3 f0 12 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 0e 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 09 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 00 00 00 00 00 00 09 00 06 00 00 00 1e 05 3a 00 00 00 00 00 66 e6 26 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 1e 05 3a 00 00 00 00 00 00 00 0e 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 06 00 00 00 1e 05 3a 00 00 00 00 00 00 00 0e 00 06 00 00 00 0a 57 4a 00 00 00 00 00 1e 05 39 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 04 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 15 00 00 00 00 00 00 00 00 00 06 00 00 00 0a 57 4a 00 00 00 00 00 00 00 14 00 06 00 00 00 3d 0a 57 00 00 00 00 00 0a 57 49 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 3d 0a 57 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2a 00 00 00 00 00 00 00 00 00 06 00 00 00 3d 0a 57 00 00 00 00 00 00 00 29 00 06 00 00 00 3d 8a 65 00 00 00 00 00 3d 0a 56 00 06 00 00 00 5c 0f 74 00 00 00 00 00 3d 8a 64 00 06 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 06 00 00 00]; - apple,tunable-bwr-catch-up-factor = [00 00 01 00]; - apple,tunable-controller = [01 00 00 00 1f 00 00 00 43 00 00 00 00 00 00 00 00 00 00 00 44 49 45 2d 54 45 4d 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 46 49 2d 54 4f 50 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 30 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 31 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 32 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 33 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 34 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 35 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 41 46 2d 52 44 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 41 46 2d 57 52 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 2d 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 2d 41 46 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 2d 44 43 53 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 53 2d 41 46 2d 42 57 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 0e 00 00 00 1e 00 00 00 00 00 00 00 00 00 00 00 4d 45 4d 2d 43 41 43 48 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 11 00 00 00 52 00 00 00 21 00 00 00 00 00 00 00 00 00 00 00 4c 49 46 45 54 49 4d 45 2d 53 45 52 56 4f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-soc-device-ps-group = [00 fc ff 1f 00 00 00 00]; - apple,tunable-agx-dcs-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 12 00 00 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 38 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 00 00 00 00 00 00 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 10 00 06 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 06 00 00 00 00 00 4a 00 00 00 00 00 00 00 38 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 49 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 27 00 00 00 00 00 00 00 0b 00 06 00 00 00 00 00 39 00 00 00 00 00 00 00 26 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 38 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 22 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 21 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 1f 00 00 00 00 00 00 00 14 00 06 00 00 00 00 00 47 00 00 00 00 00 00 00 1e 00 06 00 00 00 00 00 57 00 00 00 00 00 00 00 46 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 56 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 07 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 57 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 65 00 00 00 00 00 00 00 56 00 06 00 00 00 00 00 e8 03 00 00 00 00 00 00 64 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 e7 03 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 17 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 43 00 00 00 00 00 00 00 16 00 06 00 00 00 00 00 65 00 00 00 00 00 00 00 42 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 64 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 50 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 4f 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 10 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 0f 00 06 00 00 00 00 00 74 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 73 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 05 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 04 00 06 00 00 00 00 00 1e 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00]; - apple,tunable-soc-ni1-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-mc_quota_rsp_ptd_count = [08 00 00 00]; - apple,tunable-lts-ctrl-ts = [00 00 05 00]; - apple,tunable-temp-sensor = [01 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 80 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 30 69 00 00 00 00 00 00 00 00 00 00 02 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 33 b3 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 31 69 00 00 00 00 00 00 00 00 00 00 03 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 66 e6 03 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 32 69 00 00 00 00 00 00 00 00 00 00 04 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 00 80 05 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 35 69 00 00 00 00 00 00 00 00 00 00 05 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 66 e6 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 36 69 00 00 00 00 00 00 00 00 00 00 06 00 00 00 08 00 00 00 06 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00 cc 4c 05 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 61 30 30 37 69 00 00 00 00 00 00 00 00 00 00 07 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 30 69 00 00 00 00 00 00 00 00 00 00 08 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 31 69 00 00 00 00 00 00 00 00 00 00 09 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 33 69 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 08 00 00 00 04 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 34 69 00 00 00 00 00 00 00 00 00 00 0b 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 00 00 01 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6c 69 00 00 00 00 00 00 00 00 00 00 0c 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00 00 00 01 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6d 69 00 00 00 00 00 00 00 00 00 00 0d 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 33 33 03 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6e 69 00 00 00 00 00 00 00 00 00 00 0e 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 06 00 00 00 00 00 00 00 66 e6 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 6f 69 00 00 00 00 00 00 00 00 00 00 0f 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 07 00 00 00 00 00 00 00 99 99 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 70 69 00 00 00 00 00 00 00 00 00 00 10 00 00 00 08 00 00 00 04 00 00 00 01 00 00 00 09 00 00 00 00 00 00 00 33 33 02 00 00 80 06 00 6e 00 00 00 7d 00 00 00 54 70 30 30 72 69 00 00 00 00 00 00 00 00 00 00 11 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 39 69 00 00 00 00 00 00 00 00 00 00 12 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 61 69 00 00 00 00 00 00 00 00 00 00 13 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 02 00 00 00 00 00 00 00 00 00 07 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 36 69 00 00 00 00 00 00 00 00 00 00 14 00 00 00 08 00 00 00 04 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 40 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 70 30 30 37 69 00 00 00 00 00 00 00 00 00 00 15 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 66 66 08 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 37 69 00 00 00 00 00 00 00 00 00 00 16 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 80 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 31 69 00 00 00 00 00 00 00 00 00 00 17 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 99 99 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 32 69 00 00 00 00 00 00 00 00 00 00 18 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 33 b3 04 00 00 80 04 00 6e 00 00 00 7d 00 00 00 54 65 30 30 33 69 00 00 00 00 00 00 00 00 00 00 19 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 6d 00 00 00 6d 00 00 00 4d 54 52 5f 54 4f 50 5f 41 47 58 00 00 00 00 00]; - apple,tunable-agx-af-wr-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-dcs-bw-threshold = [a3 f0 13 00 01 00 00 00 00 00 00 00 00 00 00 00 66 e6 27 00 02 00 00 00 a3 f0 12 00 00 00 00 00 1e 05 3a 00 03 00 00 00 66 e6 26 00 00 00 00 00 0a 57 4a 00 04 00 00 00 1e 05 39 00 00 00 00 00 3d 0a 57 00 05 00 00 00 0a 57 49 00 00 00 00 00 3d 8a 65 00 06 00 00 00 3d 0a 56 00 00 00 00 00 5c 0f 74 00 07 00 00 00 3d 8a 64 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 0f 73 00 00 00 00 00]; - apple,tunable-mc_cmd_ack_ptd_count = [01 00 00 00]; - apple,tunable-soc-ni0-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-fast-die-ctrl-loop = [01 00 00 00 00 00 00 00 00 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 15 00 00 00 16 00 00 00 17 00 00 00 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 02 00 00 00 66 06 00 00 47 41 00 00 00 00 6e 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 01 00 16 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-agx-dcs-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-agx-af-rd-bw-dvfs-filter = [fe 7f 00 00]; - apple,tunable-firmware-name = [74 38 31 34 32 70 6d 70 00]; - apple,tunable-lts-clpc-voltage = [01 00 00 00 98 03 00 00 00 00 69 00 33 33 69 00 00 00 00 00 50 41 43 43 00 00 00 00]; - apple,tunable-soc-ni5-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-energy-counter = [01 00 00 00 01 00 00 00 05 00 00 00 01 00 00 00 41 47 58 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 01 00 00 00 05 00 00 00 02 00 00 00 41 47 58 2d 53 52 41 4d 00 00 00 00 00 00 00 00 03 00 00 00 01 00 00 00 06 00 00 00 01 00 00 00 41 4e 45 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 56 44 45 43 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 53 4f 43 5f 41 4f 4e 00 00 00 00 00 00 00 00 00]; - apple,tunable-lts-config = [01 00 00 00 3b 01 00 00 a6 72 0f 00 00 00 00 00 b5 d5 0f 00 6e 00 00 00 69 00 00 00 00 00 11 00 33 b3 00 00 b0 32 47 01 02 00 00 00 47 03 00 00 3b 61 00 00 00 00 00 00 f7 dd 0f 00 6e 00 00 00 69 00 00 00 00 00 11 00 33 b3 00 00 d7 43 ef 02]; - apple,tunable-agx-af-rd-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-ane-af-bw-constraint = [00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00]; - apple,tunable-mcache-stream = [0e 00 00 00 04 00 00 00 01 00 00 00 0d 00 00 00 0d 00 00 00 38 00 00 00 38 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 11 00 00 00 04 00 00 00 01 00 00 00 0e 00 00 00 0e 00 00 00 3c 00 00 00 3c 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1b 00 00 00 04 00 00 00 01 00 00 00 0e 00 00 00 0e 00 00 00 3d 00 00 00 3d 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 13 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 40 00 00 00 40 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 24 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 41 00 00 00 41 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1c 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00 42 00 00 00 42 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1e 00 00 00 03 00 00 00 01 00 00 00 02 00 00 00 02 00 00 00 0c 00 00 00 0c 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 2b 00 00 00 03 00 00 00 01 00 00 00 02 00 00 00 02 00 00 00 0e 00 00 00 0e 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 05 00 00 00 01 00 00 00 01 00 00 00 07 00 00 00 07 00 00 00 20 00 00 00 20 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 06 00 00 00 02 00 00 00 01 00 00 00 08 00 00 00 08 00 00 00 24 00 00 00 24 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 0b 00 00 00 05 00 00 00 01 00 00 00 0b 00 00 00 0b 00 00 00 30 00 00 00 30 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 04 00 00 00 00 00 00 00 01 00 00 00 11 00 00 00 11 00 00 00 48 00 00 00 48 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 01 00 00 00 13 00 00 00 13 00 00 00 50 00 00 00 50 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 15 00 00 00 15 00 00 00 58 00 00 00 5a 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 10 00 00 00 04 00 00 00 01 00 00 00 1f 00 00 00 1f 00 00 00 80 00 00 00 bf 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0f 00 00 00 04 00 00 00 02 00 00 00 10 00 00 00 10 00 00 00 44 00 00 00 44 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 20 00 00 00 03 00 00 00 02 00 00 00 03 00 00 00 06 00 00 00 10 00 00 00 1f 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 01 00 00 00 1f 00 00 00 03 00 00 00 02 00 00 00 1e 00 00 00 1e 00 00 00 7c 00 00 00 7c 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 12 00 00 00 05 00 00 00 02 00 00 00 09 00 00 00 09 00 00 00 28 00 00 00 28 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0a 00 00 00 05 00 00 00 02 00 00 00 0c 00 00 00 0c 00 00 00 34 00 00 00 34 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 15 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5d 00 00 00 5d 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 36 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5e 00 00 00 5e 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 37 00 00 00 07 00 00 00 02 00 00 00 16 00 00 00 16 00 00 00 5f 00 00 00 5f 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 19 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 04 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 1a 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 05 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 29 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 06 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 2a 00 00 00 08 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 07 00 00 00 07 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 0d 00 00 00 0b 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 08 00 00 00 08 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 0c 00 00 00 0b 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 09 00 00 00 09 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 14 00 00 00 04 00 00 00 03 00 00 00 01 00 00 00 01 00 00 00 0a 00 00 00 0a 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 27 00 00 00 04 00 00 00 03 00 00 00 1d 00 00 00 1d 00 00 00 78 00 00 00 78 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2c 00 00 00 03 00 00 00 03 00 00 00 18 00 00 00 18 00 00 00 64 00 00 00 64 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2f 00 00 00 02 00 00 00 03 00 00 00 1a 00 00 00 1a 00 00 00 6c 00 00 00 6c 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 26 00 00 00 05 00 00 00 03 00 00 00 1c 00 00 00 1c 00 00 00 74 00 00 00 74 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 23 00 00 00 00 00 00 00 03 00 00 00 14 00 00 00 14 00 00 00 54 00 00 00 54 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 01 00 00 00 28 00 00 00 00 00 00 00 03 00 00 00 1b 00 00 00 1b 00 00 00 70 00 00 00 70 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 31 00 00 00 0f 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 60 00 00 00 60 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 30 00 00 00 0e 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 61 00 00 00 61 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 33 00 00 00 11 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 62 00 00 00 62 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 34 00 00 00 12 00 00 00 03 00 00 00 17 00 00 00 17 00 00 00 63 00 00 00 63 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 35 00 00 00 09 00 00 00 03 00 00 00 19 00 00 00 19 00 00 00 68 00 00 00 68 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 1d 00 00 00 09 00 00 00 03 00 00 00 19 00 00 00 19 00 00 00 69 00 00 00 6b 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 2d 00 00 00 0c 00 00 00 03 00 00 00 18 00 00 00 18 00 00 00 65 00 00 00 65 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 16 00 00 00 0b 00 00 00 03 00 00 00 ff ff 00 00 ff ff 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00]; - apple,tunable-ptd-driver-version = [01 00 00 00]; - apple,tunable-afi-top-bw-threshold = [99 19 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 51 78 4d 00 01 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 51 78 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 33 33 73 00 00 00 00 00 00 00 00 00 00 00 00 00 b8 1e 7c 00 00 00 00 00]; - apple,tunable-region-size = [00 00 0d 00 00 00 00 00]; - apple,tunable-coredump-enable = [40 00 00 00]; - apple,tunable-soc-ni4-bw-threshold = [cc 0c 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 26 00 01 00 00 00 cc 0c 1c 00 00 00 00 00 00 00 00 00 00 00 00 00 e1 ba 25 00 00 00 00 00 00 00 00 00 00 00 00 00 99 19 39 00 00 00 00 00 00 00 00 00 00 00 00 00 5c 8f 3d 00 00 00 00 00]; - apple,tunable-pm-ptd-ranges = [01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00 00 06 00 00 00 07 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 00 00 00 00 0f 00 00 00]; - apple,tunable-fast-die-ctrl-ts-avg-temp = [00 00 64 00]; - apple,tunable-lts-ctrl-loop = [02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 07 00 00 00 08 00 00 00 09 00 00 00 0a 00 00 00 0b 00 00 00 0c 00 00 00 0d 00 00 00 0e 00 00 00 0f 00 00 00 10 00 00 00 11 00 00 00 12 00 00 00 13 00 00 00 14 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 47 50 55 00 00 00 00 00 00 00 00 00 00 00 00 00]; - apple,tunable-soc-device = [01 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 43 53 00 00 00 00 00 02 00 00 00 45 4e 4f 4e 01 00 00 00 16 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4d 43 43 00 00 00 00 17 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 30 00 18 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 31 00 19 00 00 00 45 4e 4f 4e 01 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 32 00 1a 00 00 00 45 4e 4f 4e 01 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 33 00 1b 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 34 00 1c 00 00 00 45 4e 4f 4e 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 4e 49 35 00 10 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 41 4f 4e 00 11 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 4f 43 2d 52 45 53 54 03 00 00 00 45 4e 4f 4e 03 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 41 43 43 30 00 00 00 04 00 00 00 45 4e 4f 4e 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 50 41 43 43 30 00 00 00 05 00 00 00 5f 58 46 47 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 47 58 00 00 00 00 00 06 00 00 00 45 4e 4f 4e 03 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 45 30 00 00 00 00 07 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 49 53 50 00 00 00 00 00 08 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 00 00 00 00 09 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 45 58 54 30 0a 00 00 00 45 4e 4f 4e 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 44 49 53 50 45 58 54 31 0b 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 56 45 00 00 00 00 00 0c 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 56 44 00 00 00 00 00 0d 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4d 53 52 00 00 00 00 00 0e 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4a 50 45 47 00 00 00 00 0f 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 43 4f 44 45 43 00 00 1d 00 00 00 5f 52 54 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 4c 54 52 00 00 00 00 00 1e 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 30 00 00 00 00 1f 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 31 00 00 00 00 20 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 32 00 00 00 00 21 00 00 00 45 4e 4f 4e 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 54 43 33 00 00 00 00 22 00 00 00 45 4e 4f 4e 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 41 4e 53 00 00 00 00 00 23 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 50 43 49 45 00 00 00 00 24 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 42 52 00 00 00 00 00 25 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 45 50 00 00 00 00 00 26 00 00 00 45 4e 4f 4e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 53 49 4f 00 00 00 00 00]; - apple,tunable-fast-die-ctrl-ts = [00 00 05 00]; - apple,tunable-region-base = [00 00 50 80 03 00 00 00]; - apple,tunable-agx-af-wr-bw-threshold = [00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 00 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 00 00 00 00 00 00 3a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 39 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 2d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 2c 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 12 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 00 00 00 00 00 00 00 11 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 3c 00 00 00 00 00 00 00 0d 00 06 00 00 00 00 00 89 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 88 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 7a 00 00 00 00 00 00 00 32 00 06 00 00 00 00 00 93 00 00 00 00 00 00 00 79 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 92 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2c 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 8a 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 89 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1e 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3e 00 00 00 00 00 00 00 1d 00 06 00 00 00 00 00 6f 00 00 00 00 00 00 00 3d 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 6e 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 34 00 00 00 00 00 00 00 09 00 06 00 00 00 00 00 5a 00 00 00 00 00 00 00 33 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 59 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 2c 00 00 00 00 00 00 00 03 00 06 00 00 00 00 00 41 00 00 00 00 00 00 00 2b 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 40 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 3c 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 3b 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 19 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 37 00 00 00 00 00 00 00 18 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 36 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 14 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 32 00 00 00 00 00 00 00 13 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 31 00 06 00 00 00]; - apple,tunable-uuid = [30 41 37 44 41 39 43 33 2d 45 37 46 36 2d 33 31 35 31 2d 41 43 44 45 2d 44 41 30 31 37 42 45 42 45 36 34 35 00]; - apple,tunable-segment-names = [5f 5f 54 45 58 54 3b 5f 5f 44 41 54 41 00]; - apple,tunable-segment-ranges = [00 00 50 80 03 00 00 00 00 00 00 01 00 00 00 00 00 00 50 80 03 00 00 00 00 c0 03 00 03 00 00 00 00 c0 53 80 03 00 00 00 00 c0 03 01 00 00 00 00 00 c0 53 80 03 00 00 00 00 e0 06 00 06 00 00 00]; - apple,tunable-pre-loaded = [01 00 00 00]; -}; diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index 82e73d6dafc2b9..8734889ece7010 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -6,7 +6,6 @@ * J813 board fragments and overrides what the J815 ADT shows to be * different: * - * - /chosen board-id 0x26 (J813: 0x24) * - 15.3" 2880x1864 panel (2880x1800 below the notch), 326 x 211 mm * - six SN012776 speaker amplifiers on i2c3 (0x38-0x3d: two tweeters and * four force-cancelling woofers); J813 has four @@ -139,11 +138,6 @@ }; }; -&pmp { - /* ADT /chosen board-id (J815) */ - apple,board-id = <38>; -}; - &panel { compatible = "apple,panel-j815", "apple,panel"; width-mm = <326>; From d9c2c299096c0aa2059b3c399d7637615bd58f77 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 15:30:39 +0000 Subject: [PATCH 0418/1514] drm/asahi: g17: enable render stage prefixes on T6041 (25G83) A render whose vertex work depends on a narrower prefix of earlier render and compute work than its fragment work currently waits as a whole for that compute work on T6041, because DRM_ASAHI_RENDER_STAGE_PREFIXES is rejected when variant.render_stage_prefixes is false. On non-M5 builds (!variant.m5_commands), stage-prefix splitting is handled entirely in the host device-mutex submission path: g17/runtime/render/direct.rs keeps staged renders off the direct path, g17/runtime/render/submit.rs resolves the narrower tiling prefixes and whole fragment prefixes, and g17/queue/render.rs emits standard KickDependency words into the kick barrier arrays with dependency_types set to None. A18 Pro (V26A428, also !m5_commands) already runs this exact path with render_stage_prefixes enabled. There are no new firmware descriptor fields or firmware ABI changes. Enable render_stage_prefixes on T6041's 25G83 firmware variant (both 32-core and 40-core configurations share BUILD_25G83), exposing DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2. T6040 (M4 Pro), T6041 26B123, and T6041 25F84 are left unchanged. Test scope: compile-tested here; runtime verification on J616C (32-core T6041, 25G83) with staged-render Vulkan/Mesa workloads is pending, and 40-core configurations (J614C/J575C) have not been hardware-tested. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/hw/t6041.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 30370e792e1695..68394ee6e6848f 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -205,6 +205,9 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { ], // Four clusters: the tiler segment values of 25F84 on this machine. variant: &fw::variant::Variant { + // Tiling and fragment kicks wait on their own prefixes (host path, !m5_commands); + // unmeasured on the M4 Pro, which keeps false. + render_stage_prefixes: true, ta_mode_1: true, ..fw::variant::V25G83 }, From d75593af3d3b3ad200b1c4389b4d2fe890471d83 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 22 Nov 2026 15:45:31 -0300 Subject: [PATCH 0419/1514] arm64: dts: apple: t6041-j575c: describe the boot NOR and its NVRAM The J575c leaves the QSPI controller disabled and describes no flash, so no MTD partition is labelled "nvram" and asahi-nvram and asahi-bless have nothing to open. Describe the boot NOR as the J614c/J616c do: the always-on supply, the jedec,spi-nor flash at 10 MHz single-lane, the nvram partition and its alias, and the QSPI power state. The J575c's ADT (macOS 27.0.1 and 27.2.1) has the same controller and layout: /arm-io/qspi is "qspi,qspimc" at 0x229118000 with IRQ 1573 (the t604x.dtsi qspi node), and /arm-io/qspi/spinor/anvram is 0x700000, 0x100000. Tested on a J575c with a device tree built from this commit: the flash probes (JEDEC ef6517, spi-nor-generic), the "nvram" partition appears as a 1 MiB MTD device, asahi-nvram reads it through the read-only node and asahi-bless reports the boot target. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 46 +++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index a9b42e9a63ab1d..fe50c0ea9a676f 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -36,12 +36,23 @@ dcp = &dcp; disp0 = &display; disp0-piodma = &disp0_piodma; + nvram = &nvram; }; chosen { stdout-path = "serial0:115200n8"; }; + /* + * The boot NOR runs from a PMU rail that is on whenever the SoC is + * and that no OS switches. The ADT gives the flash no supply. + */ + nor_flash_vcc: regulator-nor-flash-vcc { + compatible = "regulator-fixed"; + regulator-name = "nor-flash-vcc"; + regulator-always-on; + }; + reserved-memory { #address-cells = <2>; #size-cells = <2>; @@ -2015,3 +2026,38 @@ &gpu { power-domains = <&pmp_gfx>; }; + +/* + * Boot NOR, as on the J614c/J616c. ADT /arm-io/qspi ("qspi,qspimc", + * 0x229118000, IRQ 1573) is the t604x.dtsi qspi node, and the partition is + * /arm-io/qspi/spinor/anvram (0x700000, 0x100000), flash-relative; + * asahi-bless and asahi-nvram find it by its label. + */ +&qspi { + status = "okay"; + + flash@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + spi-max-frequency = <10000000>; + spi-rx-bus-width = <1>; + spi-tx-bus-width = <1>; + vcc-supply = <&nor_flash_vcc>; + + partitions { + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; + + nvram: partition@700000 { + label = "nvram"; + reg = <0x700000 0x100000>; + }; + }; + }; +}; + +/* The QSPI controller cannot probe while its power state is disabled. */ +&ps_qspi { + status = "okay"; +}; From 7bde038737cacbbb7f46a0f4b0e52cd60761aeda Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 00:37:21 +0100 Subject: [PATCH 0420/1514] soc: apple: clpc: take the T8152 GPU's work as input The T8152 CLPC raises the memory controller (DCS) and fabric floor only for busy CPU clusters. GPU work alone leaves both at their lowest states, so on the J873g (Mac mini M6) a GPU-bound render ran a third slower than it can, and faster the more CPU time the G18 driver's own job waits used while polling: polling made a CPU cluster busy, which raised the floor for the GPU as a side effect. Take GPU input on T8152 as on T8142: while the GPU driver reports work in flight (apple_clpc_gpu_get(), apple_clpc_gpu_set_active()), both rails go to the top of the map, DCS 7 and fabric 4. Accept the T8152 CLPC in apple_clpc_gpu_get(). A provider node the tree disables never gets a device that binds, so apple_clpc_gpu_get() returns 0 for it (no input) rather than -EPROBE_DEFER: a GPU that defers on the CLPC would otherwise wait forever. Signed-off-by: Thomas Glanzmann --- drivers/soc/apple/clpc.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index f5d5df46e31c6f..c0f5906838153d 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -314,10 +314,16 @@ int apple_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out) !of_device_is_compatible(np, "apple,t6050-clpc") && !of_device_is_compatible(np, "apple,t8132-clpc") && !of_device_is_compatible(np, "apple,t8140-clpc") && - !of_device_is_compatible(np, "apple,t8142-clpc")) { + !of_device_is_compatible(np, "apple,t8142-clpc") && + !of_device_is_compatible(np, "apple,t8152-clpc")) { of_node_put(np); return -EINVAL; } + /* A disabled provider never probes: run without its input, do not defer. */ + if (!of_device_is_available(np)) { + of_node_put(np); + return 0; + } provider = of_find_device_by_node(np); of_node_put(np); if (!provider) @@ -2111,13 +2117,20 @@ static struct kunit_suite apple_clpc_suite = { kunit_test_suite(apple_clpc_suite); #endif -/* T8152: DCS states 0-7 and fabric states 0-4. */ +/* + * T8152: DCS states 0-7 and fabric states 0-4. The G18 GPU driver reports its + * work in flight, as on T8142, and gets the top of the map while it has some. + * Without that input only busy CPU clusters raised the floor: on the J873g a + * GPU-bound render ran 34% faster with it (783 against 585 frames/s), and + * before, the GPU ran faster the more CPU time its own job waits used. + */ static const struct apple_clpc_hw apple_clpc_hw_t8152 = { .rail = { [APPLE_CLPC_DCS] = 0, [APPLE_CLPC_SOC] = 1 }, .map = { [APPLE_CLPC_DCS] = { 2, 4, 6, 7 }, [APPLE_CLPC_SOC] = { 1, 2, 3, 4 }, }, + .gpu_input = true, }; /* From cb9554f3936ee2e722f2ddec9fca72b680f1032b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 00:37:21 +0100 Subject: [PATCH 0421/1514] arm64: dts: apple: t8152-j873: link the GPU to its CLPC Name the T8152 CLPC as the GPU's host performance controller (apple,clpc), as the J813 does, so that the GPU driver can report its work in flight and get the memory controller and fabric floor while it has some. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi index 2166be04d41118..24ae92c61489cb 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-gpu.dtsi @@ -112,6 +112,7 @@ "gfx-data", "gfx1-data", "gfx-data-shared-ro", "gfx1-data-shared-ro"; mboxes = <&gfx_asc>, <&gfx1_asc>; + apple,clpc = <&clpc>; }; /* From 3692f9763dad91c5d9f8b0e3b4e0babe36b9f376 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 00:37:21 +0100 Subject: [PATCH 0422/1514] drm/asahi: g18: report GPU work to the CLPC The G18 backend never told the CLPC that the GPU was busy, so on the J873g the memory controller and fabric floor followed the CPU clusters alone. A GPU-bound render then ran faster the more CPU time the job wait used, and any change that made the wait cheaper made the GPU slower. Report work in flight through the CLPC's GPU input, as the G17 backend does. Each job wait holds the request from the job's start until it ends, on every path out of the wait. The request is dropped 16 ms after the last job ended (a delayed work item), so frame-paced clients keep the floor between frames and an idle GPU releases it. A mutex orders the request against that work, which drops it only while no job runs. The work is cancelled and the CLPC reference put when the last holder of the handle drops it: the session, or a job guard, which keeps its own reference. Without an apple,clpc provider nothing changes. The handle is taken at the start of the probe, before any GPU access. A CLPC that has not probed yet defers the probe there (-EPROBE_DEFER), instead of the GPU running without the floor for the whole boot; later in the probe a deferral can no longer be repeated safely. DRM_ASAHI_G18 depends on APPLE_CLPC being reachable from the driver, as DRM_ASAHI_G16 does. On the J873g (asyncbench, polling job waits, four interleaved rounds on one boot), with the floor against without it: - 20000 triangles per frame: 789 against 585 frames/s - 200 triangles per frame: 1847 against 1636 frames/s - 20000 triangles plus 2 ms of application CPU work: 490 against 488 (CPU-bound, as expected) With 48 ms jobs (1M triangles a frame) the request stays on for the whole run, sampled every 2 ms. When it was refreshed only at a job's start and end, it was off for 54-62% of those samples. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/Kconfig | 1 + drivers/gpu/drm/asahi/Makefile | 1 + drivers/gpu/drm/asahi/g18/boot/mod.rs | 4 + drivers/gpu/drm/asahi/g18/boot/recovery.rs | 3 + drivers/gpu/drm/asahi/g18/demand.c | 109 +++++++++++++++++++++ drivers/gpu/drm/asahi/g18/demand.rs | 76 ++++++++++++++ drivers/gpu/drm/asahi/g18/mod.rs | 1 + drivers/gpu/drm/asahi/g18/probe.rs | 7 ++ 8 files changed, 202 insertions(+) create mode 100644 drivers/gpu/drm/asahi/g18/demand.c create mode 100644 drivers/gpu/drm/asahi/g18/demand.rs diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825f..a08567e0a57176 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -50,6 +50,7 @@ config DRM_ASAHI_G16 config DRM_ASAHI_G18 bool "Apple M6 (G18G, T8152) support (experimental)" depends on DRM_ASAHI && ARM64 + depends on APPLE_CLPC=y || APPLE_CLPC=DRM_ASAHI || APPLE_CLPC=n select WANT_DEV_COREDUMP help Backend for the Mac mini M6 (J873) GPU and its 26A428 firmware. diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index e8d4ccb27f2100..f0fb22fa392e09 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -10,3 +10,4 @@ aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o +aurora-$(CONFIG_DRM_ASAHI_G18) += g18/demand.o diff --git a/drivers/gpu/drm/asahi/g18/boot/mod.rs b/drivers/gpu/drm/asahi/g18/boot/mod.rs index b05b6d95ef8526..85995224bb62c2 100644 --- a/drivers/gpu/drm/asahi/g18/boot/mod.rs +++ b/drivers/gpu/drm/asahi/g18/boot/mod.rs @@ -1053,6 +1053,8 @@ struct G18RoleSlot { struct G18Session { roles: [G18RoleSlot; 2], states: [Arc; 2], + /// The CLPC's GPU input: memory and fabric floor while jobs run. + demand: crate::g18::demand::G18Demand, memory: Option>, queue_probe: Option, render_job: Option>, @@ -2055,9 +2057,11 @@ fn prepare_firmware_session(pdev: &platform::Device>, probe: T8152Probe if roles[0].role != G18Role::Gfx || roles[1].role != G18Role::Gfx1 { return Err(EINVAL); } + let demand = probe.demand; let session = KBox::new(G18Session { roles, states, + demand, memory: None, queue_probe: None, render_job: None, diff --git a/drivers/gpu/drm/asahi/g18/boot/recovery.rs b/drivers/gpu/drm/asahi/g18/boot/recovery.rs index bd4718c804a168..fca20c69a30ca9 100644 --- a/drivers/gpu/drm/asahi/g18/boot/recovery.rs +++ b/drivers/gpu/drm/asahi/g18/boot/recovery.rs @@ -395,6 +395,9 @@ impl G18Session { let mut since = Instant::::now(); let mut reported = 0u32; self.growth_refused = false; + // The job is running: the CLPC holds the memory and fabric floor + // until it ends, on every path out of here, and 16 ms past the last. + let _job = self.demand.job(); loop { if let Some(serviced) = self.poll_faults(label)? { if recovery.is_none() { diff --git a/drivers/gpu/drm/asahi/g18/demand.c b/drivers/gpu/drm/asahi/g18/demand.c new file mode 100644 index 00000000000000..4af04d3c48e58d --- /dev/null +++ b/drivers/gpu/drm/asahi/g18/demand.c @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * G18: the CLPC's GPU input. While the GPU has work, the CLPC holds the + * memory controller (DCS) and fabric floor at the top of its map, as the G17 + * backend reports its work. The T8152 CLPC otherwise raises that floor only + * for busy CPU clusters. Each job the driver waits for holds the request from + * its start until it ends, however long it runs; the request is dropped 16 ms + * after the last job ended. + */ + +#include +#include +#include +#include +#include +#include + +#define G18_DEMAND_IDLE_MS 16 + +struct g18_demand { + struct apple_clpc_gpu *gpu; + struct delayed_work idle; + /* Orders the request against the idle work, which drops it only with no job. */ + struct mutex lock; + unsigned int jobs; +}; + +int g18_demand_get(struct device *dev, struct g18_demand **out); +void g18_demand_begin(struct g18_demand *demand); +void g18_demand_end(struct g18_demand *demand); +void g18_demand_put(struct g18_demand *demand); + +static void g18_demand_idle(struct work_struct *work) +{ + struct g18_demand *demand = + container_of(to_delayed_work(work), struct g18_demand, idle); + + mutex_lock(&demand->lock); + if (!demand->jobs) + apple_clpc_gpu_set_active(demand->gpu, false); + mutex_unlock(&demand->lock); +} + +/* + * *out is NULL without an apple,clpc provider, or when the provider refuses the + * GPU input: the GPU then runs without the floor. -EPROBE_DEFER while the + * provider has not probed yet, and -ENOMEM, are returned for the probe to act + * on, before it touches the GPU. + */ +int g18_demand_get(struct device *dev, struct g18_demand **out) +{ + struct apple_clpc_gpu *gpu = NULL; + struct g18_demand *demand; + int ret = apple_clpc_gpu_get(dev, &gpu); + + *out = NULL; + if (ret == -EPROBE_DEFER) + return ret; + if (ret || !gpu) { + if (ret) + dev_warn(dev, "G18: no CLPC GPU input: %d\n", ret); + return 0; + } + demand = kzalloc(sizeof(*demand), GFP_KERNEL); + if (!demand) { + apple_clpc_gpu_put(gpu); + return -ENOMEM; + } + demand->gpu = gpu; + INIT_DELAYED_WORK(&demand->idle, g18_demand_idle); + mutex_init(&demand->lock); + *out = demand; + return 0; +} + +/* A job started: hold the floor until it ends. */ +void g18_demand_begin(struct g18_demand *demand) +{ + if (!demand) + return; + mutex_lock(&demand->lock); + demand->jobs++; + apple_clpc_gpu_set_active(demand->gpu, true); + mutex_unlock(&demand->lock); +} + +/* A job ended: drop the floor 16 ms after the last one, unless another starts. */ +void g18_demand_end(struct g18_demand *demand) +{ + if (!demand) + return; + mutex_lock(&demand->lock); + if (!WARN_ON_ONCE(!demand->jobs)) + demand->jobs--; + mutex_unlock(&demand->lock); + mod_delayed_work(system_wq, &demand->idle, + msecs_to_jiffies(G18_DEMAND_IDLE_MS)); +} + +/* With no job left: stop the idle work, drop the request and the CLPC reference. */ +void g18_demand_put(struct g18_demand *demand) +{ + if (!demand) + return; + cancel_delayed_work_sync(&demand->idle); + apple_clpc_gpu_put(demand->gpu); + mutex_destroy(&demand->lock); + kfree(demand); +} diff --git a/drivers/gpu/drm/asahi/g18/demand.rs b/drivers/gpu/drm/asahi/g18/demand.rs new file mode 100644 index 00000000000000..a8e1ab0c75c52e --- /dev/null +++ b/drivers/gpu/drm/asahi/g18/demand.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The CLPC's GPU input (`demand.c`): the memory controller and fabric floor +//! while the GPU has work. + +use core::ffi::c_void; +use core::ptr::NonNull; +use kernel::{error::to_result, prelude::*, sync::Arc}; + +extern "C" { + // `struct device *`: the bindings type has no fields Rust can see. + fn g18_demand_get(dev: *mut c_void, out: *mut *mut c_void) -> i32; + fn g18_demand_begin(demand: *mut c_void); + fn g18_demand_end(demand: *mut c_void); + fn g18_demand_put(demand: *mut c_void); +} + +/// The allocation from `g18_demand_get`, released when the last reference +/// (the session's or a running job's) goes. +struct Handle(NonNull); + +// SAFETY: the C side serializes on its own lock and queues a work item. +unsafe impl Send for Handle {} +// SAFETY: as above. +unsafe impl Sync for Handle {} + +impl Drop for Handle { + fn drop(&mut self) { + // SAFETY: a live allocation from `g18_demand_get`, released once, + // after every guard holding it has ended its job. + unsafe { g18_demand_put(self.0.as_ptr()) } + } +} + +/// Absent without an `apple,clpc` provider. +pub(crate) struct G18Demand(Option>); + +impl G18Demand { + /// `dev` is the GPU platform device, whose node may name `apple,clpc`. + /// EPROBE_DEFER while the provider has not probed yet: call it before + /// the probe touches the GPU. + pub(crate) fn new( + dev: &kernel::device::Device, + ) -> Result { + let mut demand = core::ptr::null_mut(); + // SAFETY: a live device; `demand` is written before the call returns. + to_result(unsafe { g18_demand_get(dev.as_raw().cast(), &mut demand) })?; + Ok(Self(match NonNull::new(demand) { + Some(demand) => Some(Arc::new(Handle(demand), GFP_KERNEL)?), + None => None, + })) + } + + /// A job is running: the floor is held until the returned guard is + /// dropped, and released 16 ms after the last job ended. The guard + /// holds its own reference, so it may outlive this value. + pub(crate) fn job(&self) -> G18DemandJob { + if let Some(handle) = &self.0 { + // SAFETY: a live allocation, held by `self`. + unsafe { g18_demand_begin(handle.0.as_ptr()) } + } + G18DemandJob(self.0.clone()) + } +} + +/// One job's hold on the floor, from [`G18Demand::job`] until dropped. +pub(crate) struct G18DemandJob(Option>); + +impl Drop for G18DemandJob { + fn drop(&mut self) { + if let Some(handle) = &self.0 { + // SAFETY: a live allocation, held by this guard's reference. + unsafe { g18_demand_end(handle.0.as_ptr()) } + } + } +} diff --git a/drivers/gpu/drm/asahi/g18/mod.rs b/drivers/gpu/drm/asahi/g18/mod.rs index 23e6f2a76a62ce..15fc66d273e02f 100644 --- a/drivers/gpu/drm/asahi/g18/mod.rs +++ b/drivers/gpu/drm/asahi/g18/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod address_map; pub(crate) mod boot; pub(crate) mod buffer; pub(crate) mod compat; +pub(crate) mod demand; #[allow(dead_code)] pub(crate) mod drm; pub(crate) mod fixture; diff --git a/drivers/gpu/drm/asahi/g18/probe.rs b/drivers/gpu/drm/asahi/g18/probe.rs index 26534683e1ed52..b91f5237c18843 100644 --- a/drivers/gpu/drm/asahi/g18/probe.rs +++ b/drivers/gpu/drm/asahi/g18/probe.rs @@ -133,6 +133,8 @@ pub(crate) struct T8152Probe { /// The DRM device, not yet registered. The live-boot module allocates /// its kernel objects on it; the shared probe registers it at stage 10. pub(crate) drm: ARef, + /// The CLPC's GPU input, taken before the probe touched the GPU. + pub(crate) demand: crate::g18::demand::G18Demand, } /// Loader receipts the G18G firmware stages require. The loader writes one @@ -286,6 +288,10 @@ fn prepare_t8152_device( let identity = identity::decode_gpu_identity(soc.hw_family, soc.hw_variant, soc.num_dies as u8) .ok_or(EINVAL)?; + // Before any GPU access: a CLPC that has not probed yet defers this probe + // here, while it can still be repeated, instead of the GPU running + // without the floor for the whole boot. + let demand = crate::g18::demand::G18Demand::new(pdev.as_ref())?; if soc.chip_id != 0x8152 || identity.gpu_gen != hw::GpuGen::G18 || identity.gpu_variant != identity::GpuVariant::G @@ -385,6 +391,7 @@ fn prepare_t8152_device( registers, observed, drm, + demand, }) } From c5e25e0925351be6efedb961f44674d0af5562c5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:29:21 +1100 Subject: [PATCH 0423/1514] drm/apple: dpavservep: expect AFKV2 on the classic DPAV endpoint to be refused The revert of 78e59bdf ("drm/apple: dpavservep: admit the AFKV2 AV service on the classic DPAV endpoint") makes dcpavserv_identity() refuse the AV service on endpoint 0x28 over the AFKV2 wire again, but the apple-dcpavserv-identity suite still expected three of those rows to be admitted, so it failed 40/43. Expect them to be refused, and say why in the section comment. They can flip back together with the admission once the service is safe to use across a link release. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep-identity-test.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c index 4f36cc35758b4c..6cdee1ac5881f7 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c +++ b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c @@ -60,13 +60,16 @@ static const struct dpavid_case dpavid_cases[] = { { "v2 ep 0x2a: DCPDPService class", DPAVID_V2, DPAVSERV_ENDPOINT_V2, DPAVID_NAME, "DCPDPService", 3, 3, false }, - /* AFKV2 on the classic DPAV endpoint: EPICUnit 0, dynamic channel. */ + /* + * AFKV2 on the classic DPAV endpoint is refused: using the service there + * resets the M4 Air when the external processor releases its link. + */ { "v2 ep 0x28: DP13 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, - "DCPDP13Service", 0, 7, true }, + "DCPDP13Service", 0, 7, false }, { "v2 ep 0x28: DP2HDMI unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, - "AppleDCPDP2HDMI", 0, 1, true }, + "AppleDCPDP2HDMI", 0, 1, false }, { "v2 ep 0x28: unit 0, channel at u16 max", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, - "DCPDP13Service", 0, 0xffff, true }, + "DCPDP13Service", 0, 0xffff, false }, { "v2 ep 0x28: unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "DCPDP13Service", 7, 7, false }, { "v2 ep 0x28: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, From be7754062eb98a24672e0804d1bda098a4588ecc Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 14:35:16 -0500 Subject: [PATCH 0424/1514] thunderbolt: end the s2idle control hold before the connection manager resumes tb_domain_resume_noirq() cleared noirq_ctl_retained only after cm_ops->resume_noirq(). Until then tb_domain_event_cb() kept dropping every packet but XDomain requests, so a hotplug event or an XDomain response that arrived while the connection manager resumed was lost: a plug in that window was never acked, and a request the host had sent timed out. Clear the flag where a stopped channel would be started, before resume_noirq(). Events then reach the connection manager from the same point as on a suspend without the hold. The lock argument is unchanged: tb->lock is held from the clear until resume_noirq() returns, and the XDomain request work takes tb->lock before it re-checks the flag, so a request queued during noirq still cannot act before the domain has resumed. The packet filter in tb_xdomain_handle_request() reads the flag without tb->lock. If the clear lands between that read and the request work: - the filter saw the hold, so only a discovery request was scheduled; its work then waits for tb->lock, sees the hold ended and answers it as on any resume, the same answer it would have had during the hold; - the filter saw no hold, so the clear came first and the work sees the same. Packets the filter drops while it still sees the hold are lost as before, in a window that now ends earlier. Events and protocol packets that arrive after the clear reach the connection manager and the protocol handlers while resume_noirq() runs, exactly as when the channel was stopped and tb_ctl_start() ran before resume_noirq(). Also say in the comment on the requests answered during the hold that LINK_STATE_STATUS_REQUEST reads the downstream port's registers, under tb->lock, rather than only stored state. Signed-off-by: Satya Benson --- drivers/thunderbolt/domain.c | 14 ++++++++++---- drivers/thunderbolt/xdomain.c | 5 ++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/thunderbolt/domain.c b/drivers/thunderbolt/domain.c index e77c0eab18cc46..c870fc456598f1 100644 --- a/drivers/thunderbolt/domain.c +++ b/drivers/thunderbolt/domain.c @@ -604,14 +604,20 @@ int tb_domain_resume_noirq(struct tb *tb) int ret = 0; mutex_lock(&tb->lock); - if (!tb->noirq_ctl_retained) - tb_ctl_start(tb->ctl); - if (tb->cm_ops->resume_noirq) - ret = tb->cm_ops->resume_noirq(tb); + /* + * End the hold before resume_noirq(), where a stopped channel would be + * started: hotplug events and XDomain responses then reach the + * connection manager from the same point as without the hold. Requests + * still wait for tb->lock, which is held until the resume is done. + */ if (tb->noirq_ctl_retained) { WRITE_ONCE(tb->noirq_ctl_retained, false); tb_dbg(tb, "XDomain control channel remained active\n"); + } else { + tb_ctl_start(tb->ctl); } + if (tb->cm_ops->resume_noirq) + ret = tb->cm_ops->resume_noirq(tb); mutex_unlock(&tb->lock); return ret; diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index d174e7129191ca..4d297d54626d33 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -761,7 +761,10 @@ static void stop_handshake(struct tb_xdomain *xd) /* * The XDomain discovery requests answered while the control channel is kept - * through s2idle (tb->noirq_ctl_retained): they only read state. + * through s2idle (tb->noirq_ctl_retained). They change no state: UUID and + * properties are answered from memory, and LINK_STATE_STATUS_REQUEST reads + * the downstream port's registers, under tb->lock, from a host router that + * stays powered (QUIRK_NO_SYSTEM_SLEEP). */ static bool tb_xdp_noirq_request(enum tb_xdp_type type) { From 63649b08eb1e5bb9973f520b714fc46d93abb44c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:30:48 +1100 Subject: [PATCH 0425/1514] drm/apple: dcp: check a handed-over session before retaining it A DCP that a boot stage handed over running pinned its DMA resources until reboot before its description was checked, so an unknown handoff string, a bad endpoint map or a buffer outside the carveouts failed the bind with the device, module and IOMMU group already retained. Parse and check the description first and retain the session only once it passed. A description that fails leaves the DCP unbound with nothing retained. That is safe because every buffer of the session must now lie in a no-map carveout, which the kernel never hands out. A carveout in the linear map would also alias the buffer's write-combined mapping with a cacheable one, so such a carveout is refused as well. apple,rtkit-buffers must be present; a session without shared buffers has the property empty. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index a68631cadf0b68..9ec53df3dbb44c 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1854,9 +1854,11 @@ struct dcp_rtkit_live { }; /* - * Inside one of this DCP's reserved-memory carveouts. Those are also what the IOMMU - * core rebuilds the DCP's DART mappings from when it takes over a locked - * root, so a buffer outside them would lose its mapping at attach. + * Inside one of this DCP's no-map reserved-memory carveouts. Those are also what + * the IOMMU core rebuilds the DCP's DART mappings from when it takes over a + * locked root, so a buffer outside them would lose its mapping at attach. A + * region in the linear map would alias the write-combined mapping of the buffer + * with a cacheable one, and a reusable (CMA) region could be handed out. */ static bool dcp_rtkit_live_carveout(struct device_node *np, phys_addr_t phys, size_t size) @@ -1871,8 +1873,8 @@ static bool dcp_rtkit_live_carveout(struct device_node *np, phys_addr_t phys, if (!mem) break; rmem = of_reserved_mem_lookup(mem); - /* A reusable (CMA) region could be handed out by the kernel. */ - found = rmem && !of_property_present(mem, "reusable") && + found = rmem && of_property_present(mem, "no-map") && + !of_property_present(mem, "reusable") && phys >= rmem->base && size <= rmem->size && phys - rmem->base <= rmem->size - size; of_node_put(mem); @@ -1934,8 +1936,11 @@ static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *li if (ret) return ret; + /* A session without shared buffers has the property, empty. */ + if (!of_find_property(np, "apple,rtkit-buffers", NULL)) + return -EINVAL; count = of_property_count_u32_elems(np, "apple,rtkit-buffers"); - if (count == -EINVAL || count == -ENODATA) + if (count == -ENODATA) count = 0; if (count < 0 || count > ARRAY_SIZE(cells) || count % DCP_RTKIT_LIVE_BUFFER_CELLS) @@ -1989,6 +1994,10 @@ static int dcp_rtkit_live_parse(struct apple_dcp *dcp, struct dcp_rtkit_live *li b->endpoint = t[0]; b->shmem.iova = iova; b->shmem.size = size; + /* + * The is_mapped cell only says who placed the buffer; Linux has + * mapped every one here, and is_mapped makes RTKit unmap it. + */ b->shmem.is_mapped = true; live->session.num_buffers = i + 1; } @@ -6891,15 +6900,23 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); } - /* Registering the mailbox can already expose RTKit buffer requests. */ - ret = dcp_pin_live_session(dcp); - if (ret) - goto err_piodma; + /* + * Check a handed-over session before anything is retained for it: a + * description that fails leaves the DCP unbound and nothing pinned. + * Its buffers are in no-map carveouts, which the kernel never hands out. + */ live = dcp_rtkit_live_parse(dcp, &live_rtkit); if (live < 0) { ret = dev_err_probe(dev, live, "Invalid live RTKit handoff\n"); goto err_piodma; } + /* Registering the mailbox can already expose RTKit buffer requests. */ + ret = dcp_pin_live_session(dcp); + if (ret) { + if (live) + dcp_rtkit_live_unmap(&live_rtkit); + goto err_piodma; + } /* External H17P supplies shared-buffer addresses during RTKit startup. */ if (live) dcp->rtk = apple_rtkit_init_adopted_with_session( From c170bcf22d127afb4e9b918e146b96ff03b36d17 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:30:49 +1100 Subject: [PATCH 0426/1514] drm/apple: dcp: keep the DP2HDMI link wait fatal on a cold start "drm/apple: dcp: retrain an adopted DP2HDMI port's link" made a link configuration timeout non-fatal on every DP2HDMI output. On a cold start a real training failure then no longer withdrew the display. Keep the timeout non-fatal only where no link configuration is to be expected: on the 13.5 firmware line, which is never asked to detect the sink, and on a session a boot stage handed over, whose link it already trained. Fix the comment on the HPD that follows the wait. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 9ec53df3dbb44c..c30a7e5c4a38cb 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2477,15 +2477,15 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable bool late_hpd = dcp_ext_dptx_607(dcp); bool t8132 = dcp_is_t8132_ext(dcp); /* - * A DP2HDMI output asserts its own HPD, in dcp_enable_dp2hdmi_hpd(), - * and the connect asks the firmware for HPD only on a DisplayPort - * connector or a late-HPD path, so the firmware is never asked to - * detect the sink and need not send the link configuration the wait - * below looks for (nor does one whose link a boot stage already - * trained). Treat the timeout as non-fatal, as the compact and - * late-HPD cases do, instead of withdrawing the display. + * A DP2HDMI output asserts its own HPD, in dcp_enable_dp2hdmi_hpd(). + * The 13.5 firmware line is then never asked to detect the sink and + * never sends the link configuration the wait below looks for, and a + * session a boot stage handed over has a link it already trained. + * Treat the timeout as non-fatal there, as the compact and late-HPD + * cases do, instead of withdrawing the display. */ - bool dp2hdmi = dcp->hdmi_hpd && !dcp_is_typec_output(dcp); + bool dp2hdmi = dcp->hdmi_hpd && !dcp_is_typec_output(dcp) && + (dcp->fw_compat == DCP_FIRMWARE_V_13_5 || dcp->rtkit_adopted); bool compact, withdrawn; unsigned long timeout; u64 generation; @@ -2659,8 +2659,9 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable ret = 0; } else if (!ret && dp2hdmi) { /* - * The converter holds HPD itself, and dptxport_set_hpd() below runs - * only for a DisplayPort connector, so nothing is asserted here. + * The converter holds HPD itself; dptxport_set_hpd() below raises + * the firmware's HPD only on an adopted session, whose release at + * start dropped it. */ dev_dbg(dcp->dev, "dcp_dptx_connect: no link configuration on port %u, HPD is the converter's\n", From 3fa6ec52c752656207fa3ef5a7aebda937636a0e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:30:49 +1100 Subject: [PATCH 0427/1514] drm/apple: dcp: stop a retained DCP's HDMI HPD interrupt at unbind An unbind that retains a live DCP session returned before disabling the HDMI HPD interrupt and the swap watchdog. An HPD edge after the unbind then ran its handler against a session the driver had left, and the watchdog could still fire. Disable both on that path too, before the endpoints are quiesced. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index c30a7e5c4a38cb..eb0387edc1dbc8 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7096,6 +7096,9 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v drm_dev_get(dcp->crtc->base.dev); dcp->drm_retained = true; } + /* Its handler talks to the session this unbind leaves behind. */ + if (dcp->hdmi_hpd_irq) + disable_irq(dcp->hdmi_hpd_irq); iomfb_queue_stop(dcp); afk_quiesce(dcp->avep); afk_quiesce(dcp->dptxep); @@ -7122,6 +7125,7 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v dcp->announce.stopped = true; disable_delayed_work_sync(&dcp->announce_wq); dcp_test_point(dcp, DCP_TEST_UNBIND_ANNOUNCE_STOPPED); + disable_delayed_work_sync(&dcp->swap_watchdog_wq); cancel_work_sync(&dcp->vblank_wq); if (dcp->connector) cancel_work_sync(&dcp->connector->hotplug_wq); From b659e739160bb4b87c81767998bc5153749ca9fc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:30:50 +1100 Subject: [PATCH 0428/1514] soc: apple: rtkit: refuse a retained buffer without its endpoint An adopted session's retained buffers were not checked against the endpoint map the session came with: a crashlog, syslog, IOReport or OSLog buffer could be inherited for an endpoint the firmware does not have. Refuse such a session. The host test checks the M2 Mac mini's three buffers against its map, a map without the IOReport or OSLog endpoint, and drops the check in one new mutation. Signed-off-by: Ryan Murray --- drivers/soc/apple/rtkit.c | 6 ++++ tools/asahi/rtkit-adopted-session-tests.py | 32 +++++++++++++++++++++- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 541f8428402648..533fa40c10f576 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2324,6 +2324,12 @@ static int apple_rtkit_inherit_endpoints( for (i = 0; i < APPLE_RTKIT_APP_ENDPOINT_START; i++) if (test_bit(i, map) && !test_bit(i, known)) return -EINVAL; + /* A retained buffer belongs to an endpoint the session has. */ + if ((rtk->crashlog_buffer.size && !test_bit(APPLE_RTKIT_EP_CRASHLOG, map)) || + (rtk->syslog_buffer.size && !test_bit(APPLE_RTKIT_EP_SYSLOG, map)) || + (rtk->ioreport_buffer.size && !test_bit(APPLE_RTKIT_EP_IOREPORT, map)) || + (rtk->oslog_buffer.size && !test_bit(APPLE_RTKIT_EP_OSLOG, map))) + return -EINVAL; bitmap_copy(rtk->endpoints, map, APPLE_RTKIT_MAX_ENDPOINTS); rtk->version = session->protocol_version; diff --git a/tools/asahi/rtkit-adopted-session-tests.py b/tools/asahi/rtkit-adopted-session-tests.py index 6f516abd9aac7d..a43f60b841bbad 100755 --- a/tools/asahi/rtkit-adopted-session-tests.py +++ b/tools/asahi/rtkit-adopted-session-tests.py @@ -18,6 +18,7 @@ 'any-system': ('if (test_bit(i, map) && !test_bit(i, known))', 'if (0)'), 'any-version': ('session->protocol_version < APPLE_RTKIT_MIN_SUPPORTED_VERSION ||', '0 ||'), 'ignore-ops-version': ('session->protocol_version != rtk->ops->protocol_version', '0'), + 'any-buffer-endpoint': ('rtk->ioreport_buffer.size && !test_bit(APPLE_RTKIT_EP_IOREPORT, map)', '0'), } @@ -53,20 +54,29 @@ def function(source, name): ''' TESTS = r''' +struct apple_rtkit_shmem { unsigned long size; }; struct apple_rtkit { const struct apple_rtkit_ops *ops; bool endpoints[APPLE_RTKIT_MAX_ENDPOINTS]; u16 version; + struct apple_rtkit_shmem crashlog_buffer, syslog_buffer, ioreport_buffer, oslog_buffer; }; ''' + '%s' + r''' static int run(u16 required, u16 version, const u32 *map, struct apple_rtkit *rtk) { static struct apple_rtkit_ops ops; struct apple_rtkit_adopted_session s = { .protocol_version = version }; + struct apple_rtkit_shmem crashlog = rtk->crashlog_buffer, syslog = rtk->syslog_buffer; + struct apple_rtkit_shmem ioreport = rtk->ioreport_buffer, oslog = rtk->oslog_buffer; ops.protocol_version = required; memset(rtk, 0, sizeof(*rtk)); rtk->ops = &ops; + /* The buffers the session retained, set by the caller. */ + rtk->crashlog_buffer = crashlog; + rtk->syslog_buffer = syslog; + rtk->ioreport_buffer = ioreport; + rtk->oslog_buffer = oslog; memcpy(s.epmap, map, sizeof(s.epmap)); return apple_rtkit_inherit_endpoints(rtk, &s); } @@ -79,7 +89,7 @@ def function(source, name): * 0x20-0x2c, 0x31 and 0x37. */ const u32 dcpext[8] = { 0x0000011f, 0x00821fff }; - struct apple_rtkit r; + struct apple_rtkit r = {}; u32 m[8]; int i; @@ -119,6 +129,26 @@ def function(source, name): m[0] = 1; assert(run(0, 12, m, &r) == 0 && r.endpoints[0] && !r.endpoints[0x37]); + /* + * The J473 retains crashlog, syslog and ioreport buffers: all three + * endpoints are in its map. A buffer for an endpoint the map lacks + * is refused. + */ + memset(&r, 0, sizeof(r)); + r.crashlog_buffer.size = 0x10000; + r.syslog_buffer.size = 0x4000; + r.ioreport_buffer.size = 0x4000; + assert(run(0, 12, dcpext, &r) == 0); + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~(1u << 4); + assert(run(0, 12, m, &r) == -EINVAL); + memset(&r, 0, sizeof(r)); + r.oslog_buffer.size = 0x4000; + assert(run(0, 12, dcpext, &r) == 0); + memcpy(m, dcpext, sizeof(m)); + m[0] &= ~(1u << 8); + assert(run(0, 12, m, &r) == -EINVAL); + puts("PASS adopted session endpoint map, protocol version and system endpoints"); return 0; } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 03942d5188ad7b..e7a1e5b940bc86 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -294,7 +294,7 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutate', ('admission', 'channel', 'counter', 'reset', 'buffer'), out()), 'rtkit-adopted-session-tests.py': [(out(), PASS)] + mutations('--mutation', ('no-management', 'any-system', 'any-version', - 'ignore-ops-version'), out()), + 'ignore-ops-version', 'any-buffer-endpoint'), out()), 'rtkit-retained-tests.py': [(out(), PASS)], 't6030-clock-tests.py': [(out(), PASS)], 't6030-display-admission-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], From e2cc4ab5174d5ac8f6ea85b6ba5fb476db39d81a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:30:50 +1100 Subject: [PATCH 0429/1514] dt-bindings: display: apple,dcp: require the handed-over session's properties A handed-over session needs its protocol version, endpoint map and buffers; require them with apple,rtkit-handoff. State that the regions the buffers lie in are no-map. Signed-off-by: Ryan Murray --- Documentation/devicetree/bindings/display/apple,dcp.yaml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index c0395f922f0975..6867256ee228ec 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -320,8 +320,8 @@ properties: buffer lies inside one of the reserved-memory regions referenced by memory-region, and that region maps it at the same address through iommu-addresses, so the mapping survives the IOMMU taking over the - processor's page tables. An empty property records that the session - has no shared buffers. + processor's page tables. Those regions are no-map. An empty property + records that the session has no shared buffers. apple,j613-25g83-dcpext-handoff: $ref: /schemas/types.yaml#/definitions/uint32 @@ -622,6 +622,9 @@ required: - mboxes - iommus +dependentRequired: + apple,rtkit-handoff: [ 'apple,rtkit-version', 'apple,rtkit-epmap', 'apple,rtkit-buffers' ] + allOf: - if: not: From 02e964d107a844792d186c634a01ce0932aa221d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 15:46:09 -0500 Subject: [PATCH 0430/1514] phy: apple: atc-t6050: keep active combo PHY domains powered across s2idle On T6050, t6050_dp_suspend_late() quiesces the combo PHY only for firmware deep sleep. During suspend-to-idle an active combo PHY keeps running, but genpd_suspend_noirq() still powered off its virtual genpd devices (atc1_phymxwrap among them) under the running PHY CPU. On resume, the first CIO-to-SAFE transition timed out with "PHY firmware stop failed: -62" and marked the PHY faulted, wedging the port (-5) until reboot. In t6050_dp_suspend_late(), on a suspend without platform support (pm_suspend_no_platform()), take a snapshot of the active domains and DP tunnel gates under the PHY lock and hold each of them out of genpd's system suspend with dev_pm_syscore_device(..., true), recording them in bounded masks. t6050_dp_resume_early() releases exactly the recorded holds, which also covers a suspend that unwinds after late suspend. Between the two, mode, tunnel-clock and CIO changes are fenced (s2idle_frozen), including from work that can still run after the freezer. A zero-rate tunnel clock request during the fence records a stop, so DCP can release the route; the stop runs after the thaw, or before the clock is used again, and its pending state is cleared only once the clock is parked and its gate released. The firmware deep-sleep handling (combo_pm_notify(), on the boards combo_sleep_board() names) is unchanged. Signed-off-by: Satya Benson --- drivers/phy/apple/atc-t6050-combo.h | 65 ++++++++++++- drivers/phy/apple/atc-t6050-dp.c | 137 ++++++++++++++++++++++++---- 2 files changed, 184 insertions(+), 18 deletions(-) diff --git a/drivers/phy/apple/atc-t6050-combo.h b/drivers/phy/apple/atc-t6050-combo.h index 7dceb224d2556d..e21ab1c4e57b68 100644 --- a/drivers/phy/apple/atc-t6050-combo.h +++ b/drivers/phy/apple/atc-t6050-combo.h @@ -241,6 +241,8 @@ static int combo_orientation(struct t6050_dp *dp, enum typec_orientation orienta int ret; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; if (orientation != TYPEC_ORIENTATION_NONE && orientation != TYPEC_ORIENTATION_NORMAL && @@ -281,6 +283,8 @@ static int combo_mux(struct t6050_dp *dp, struct typec_mux_state *state) return -EOPNOTSUPP; } guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; /* SAFE with a domain still held: a sleep kept it, and nothing came back on the port. */ @@ -374,6 +378,61 @@ static void combo_resume(struct t6050_dp *dp) dev_info(dp->dev, "mode %d back: the sleep did not happen\n", dp->sleep_mode); } +/* + * Suspend-to-idle leaves an active combo PHY running: t6050_dp_suspend_late() + * only quiesces for firmware sleep. Hold the active virtual genpd devices out + * of genpd_suspend_noirq() so phymxwrap (and common/usb/dp gates) are not + * powered off under the running PHY CPU. Close PHY mode and clock changes + * under the same mutex as the late snapshot, including work that can still + * run after the freezer. Reopen after noirq on resume or suspend unwind. + */ +static void combo_s2idle_hold(struct t6050_dp *dp) +{ + guard(mutex)(&dp->lock); + dp->s2idle_frozen = true; + if (dp->faulted || dp->combo_mode == COMBO_SAFE) + return; + for (unsigned int i = 0; i < dp->ndomains; i++) { + if (dp->domain[i].active && + !(i == 0 && dp->aon_syscore) && + !(dp->s2idle_domain_syscore & BIT(i))) { + dev_pm_syscore_device(dp->domain[i].dev, true); + dp->s2idle_domain_syscore |= BIT(i); + } + } + if (dp->dp_gates) { + for (unsigned int i = 0; i < ATC_DP_TUNNELS; i++) { + if (dp->dp_gate[i].active && + !(dp->s2idle_gate_syscore & BIT(i))) { + dev_pm_syscore_device(dp->dp_gate[i].dev, true); + dp->s2idle_gate_syscore |= BIT(i); + } + } + } +} + +static void combo_s2idle_release(struct t6050_dp *dp) +{ + guard(mutex)(&dp->lock); + if (dp->s2idle_domain_syscore) { + for (unsigned int i = 0; i < dp->ndomains; i++) { + if (dp->s2idle_domain_syscore & BIT(i)) + dev_pm_syscore_device(dp->domain[i].dev, false); + } + dp->s2idle_domain_syscore = 0; + } + if (dp->s2idle_gate_syscore) { + for (unsigned int i = 0; i < ATC_DP_TUNNELS; i++) { + if (dp->s2idle_gate_syscore & BIT(i)) + dev_pm_syscore_device(dp->dp_gate[i].dev, false); + } + dp->s2idle_gate_syscore = 0; + } + dp->s2idle_frozen = false; + if (dp->s2idle_clock_stops) + queue_work(system_freezable_wq, &dp->s2idle_clock_work); +} + /* * A port in use keeps its always-on domain through a deep sleep: held out of the system * transition from before its prepare to after its complete, so the power domain is not @@ -712,7 +771,11 @@ static int combo_setup(struct platform_device *pdev, struct t6050_dp *dp) return PTR_ERR(dp->combo_phy[i]); phy_set_drvdata(dp->combo_phy[i], dp); } - /* A deep sleep's hold of the always-on domain: see combo_sleep_board(). */ + /* + * Deep-sleep hold of the always-on domain (board gate left for the + * deep-sleep pass); s2idle hold runs for all T6050 combo PHYs in + * t6050_dp_suspend_late() / t6050_dp_resume_early(). + */ if (!combo_sleep_board()) return 0; dp->pm_nb.notifier_call = combo_pm_notify; diff --git a/drivers/phy/apple/atc-t6050-dp.c b/drivers/phy/apple/atc-t6050-dp.c index d266091a78d0f0..607ac8ec98d7e1 100644 --- a/drivers/phy/apple/atc-t6050-dp.c +++ b/drivers/phy/apple/atc-t6050-dp.c @@ -28,6 +28,7 @@ #include #include #include +#include enum atc_operation { ATC_MASK, ATC_TUNABLE, ATC_DELAY, ATC_POLL, ATC_POWER, ATC_FIRMWARE }; struct atc_op { @@ -135,6 +136,11 @@ struct t6050_dp { enum combo_mode sleep_mode; /* the mode the sleep's stop took down */ bool sleep_stopped; /* stopped for a sleep that has not been accounted for yet */ bool aon_syscore; /* the always-on domain is held out of this system transition */ + struct work_struct s2idle_clock_work; + u8 s2idle_clock_stops; + bool s2idle_frozen; /* serialize mode and gate changes with system sleep */ + u8 s2idle_domain_syscore; /* active domains held out of s2idle genpd suspend */ + u8 s2idle_gate_syscore; /* active DP tunnel gates held out of s2idle genpd suspend */ bool aon_kept; /* the stop left the always-on domain's reference in place */ /* A USB4 router's sleep in place: its host stops and restarts the port, see the end. */ bool cio_sleep; /* asked for: the PHY's own stop for the sleep is skipped */ @@ -634,6 +640,8 @@ static int t6050_dp_set_mode(struct phy *phy, enum phy_mode mode, int submode) struct t6050_dp *dp = phy_get_drvdata(phy); guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (mode == PHY_MODE_DP) return dp->typec ? (dp->enabled ? 0 : -ENOLINK) : atc_start(dp); if (mode == PHY_MODE_INVALID) @@ -681,6 +689,8 @@ static int t6050_dp_configure(struct phy *phy, union phy_configure_opts *opts) if (cfg->set_voltages && cfg->set_rate && rate < 0 && cfg->lanes) return -EINVAL; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->faulted) return -EIO; if (!dp->enabled) @@ -741,26 +751,14 @@ EXPORT_SYMBOL_GPL(apple_dp_phy_link_config); * never given another rate in place. Every change applies all four clocks in * order (atc_dp_tunnels_apply()). */ -int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) +static int atc_dp_tunnel_clock_locked(struct t6050_dp *dp, unsigned int clock, + u8 rate, int src) { - struct t6050_dp *dp; unsigned int i = clock - 1; - int src = 0, ret; u32 v = 0; + int ret; - if (!phy || phy->ops != &t6050_dp_ops) - return -EOPNOTSUPP; - if (clock < 1 || clock > ATC_DP_TUNNELS) - return -EINVAL; - if (rate) { - src = atc_dp_source(rate); - if (src < 0) - return src; - } - dp = phy_get_drvdata(phy); - guard(mutex)(&dp->lock); - if (!dp->combo || !dp->dp_clk_src) - return -EOPNOTSUPP; + lockdep_assert_held(&dp->lock); if (dp->tunnel_rate[i] == rate) { /* A failed start or gate suspend can leave a held domain at rate zero. */ if (!rate && dp->dp_gates) @@ -804,6 +802,80 @@ int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) clock, rate, src, v); return 0; } + +static int atc_s2idle_clock_stop(struct t6050_dp *dp, unsigned int i) +{ + int ret; + + lockdep_assert_held(&dp->lock); + dp->tunnel_rate[i] = 0; + ret = atc_dp_tunnel_apply(dp, i + 1, NULL); + if (!ret) + dp->s2idle_clock_stops &= ~BIT(i); + return ret; +} + +static void atc_s2idle_clock_work(struct work_struct *work) +{ + struct t6050_dp *dp = container_of(work, struct t6050_dp, s2idle_clock_work); + unsigned int i; + int ret; + + guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return; + for (i = 0; i < ATC_DP_TUNNELS; i++) { + if (!(dp->s2idle_clock_stops & BIT(i))) + continue; + ret = atc_s2idle_clock_stop(dp, i); + if (ret) + dev_warn(dp->dev, "Deferred DP tunnel clock %u stop failed: %d\n", + i + 1, ret); + } +} + +static void atc_s2idle_clock_cancel(void *data) +{ + struct t6050_dp *dp = data; + + cancel_work_sync(&dp->s2idle_clock_work); +} + +int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) +{ + struct t6050_dp *dp; + unsigned int stop; + int src = 0, ret; + + if (!phy || phy->ops != &t6050_dp_ops) + return -EOPNOTSUPP; + if (clock < 1 || clock > ATC_DP_TUNNELS) + return -EINVAL; + if (rate) { + src = atc_dp_source(rate); + if (src < 0) + return src; + } + dp = phy_get_drvdata(phy); + guard(mutex)(&dp->lock); + if (!dp->combo || !dp->dp_clk_src) + return -EOPNOTSUPP; + + stop = BIT(clock - 1); + if (dp->s2idle_frozen) { + if (rate) + return -EBUSY; + /* DCP may discard the route once it asks us to stop this clock. */ + dp->s2idle_clock_stops |= stop; + return 0; + } + if (dp->s2idle_clock_stops & stop) { + ret = atc_s2idle_clock_stop(dp, clock - 1); + if (ret || !rate) + return ret; + } + return atc_dp_tunnel_clock_locked(dp, clock, rate, src); +} EXPORT_SYMBOL_GPL(apple_t6050_dp_tunnel_clock); /* The connector sets orientation before changing the alternate-mode mux. */ @@ -1066,6 +1138,9 @@ static int t6050_dp_probe(struct platform_device *pdev) } if (ndomains != 3 && !(dp->combo && ndomains == 4)) return -EINVAL; + BUILD_BUG_ON(ATC_DP_TUNNELS > BITS_PER_TYPE(dp->s2idle_gate_syscore)); + if (ndomains > BITS_PER_TYPE(dp->s2idle_domain_syscore)) + return -EINVAL; dp->ndomains = ndomains; for (unsigned int i = 0; i < dp->ndomains; i++) { dp->domain[i].dev = dev_pm_domain_attach_by_name(dev, domains[i]); @@ -1120,6 +1195,10 @@ static int t6050_dp_probe(struct platform_device *pdev) return PTR_ERR(phy); phy_set_drvdata(phy, dp); dp->combo_phy[2] = phy; + INIT_WORK(&dp->s2idle_clock_work, atc_s2idle_clock_work); + ret = devm_add_action_or_reset(dev, atc_s2idle_clock_cancel, dp); + if (ret) + return ret; provider = devm_of_phy_provider_register(dev, dp->combo ? combo_xlate : of_phy_simple_xlate); if (IS_ERR(provider)) return PTR_ERR(provider); @@ -1139,7 +1218,13 @@ static int t6050_dp_suspend_late(struct device *dev) { struct t6050_dp *dp = dev_get_drvdata(dev); - if (!dp->combo || !pm_suspend_via_firmware()) + if (!dp->combo) + return 0; + if (pm_suspend_no_platform()) { + combo_s2idle_hold(dp); + return 0; + } + if (!pm_suspend_via_firmware()) return 0; /* A router sleeping in place still uses the link: its host stops the PHY after it. */ scoped_guard(mutex, &dp->lock) { @@ -1152,6 +1237,15 @@ static int t6050_dp_suspend_late(struct device *dev) return combo_suspend_late(dp); } +static int t6050_dp_resume_early(struct device *dev) +{ + struct t6050_dp *dp = dev_get_drvdata(dev); + + if (dp->combo) + combo_s2idle_release(dp); + return 0; +} + static int t6050_dp_resume_noirq(struct device *dev) { struct t6050_dp *dp = dev_get_drvdata(dev); @@ -1193,6 +1287,8 @@ int apple_t6050_phy_cio_prepare(struct device *dev) if (!dp || !dp->combo) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (dp->cio_sleep || dp->faulted || dp->combo_mode != COMBO_CIO || !dp->cio_prepared) return -EBUSY; dp->cio_sleep = true; @@ -1210,6 +1306,8 @@ int apple_t6050_phy_cio_off(struct device *dev) if (!dp) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (!dp->cio_sleep || dp->cio_sleep_off || dp->faulted || dp->combo_mode != COMBO_CIO) return -EBUSY; atc_dp_tunnels_stop(dp); @@ -1245,6 +1343,8 @@ int apple_t6050_phy_cio_on(struct device *dev) if (!dp) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; if (!dp->cio_sleep) return -EINVAL; if (!dp->cio_sleep_off) @@ -1319,6 +1419,8 @@ int apple_t6050_phy_cio_usb(struct device *dev, enum apple_t6050_cio_usb step) if (!dp || !dp->combo) return -EOPNOTSUPP; guard(mutex)(&dp->lock); + if (dp->s2idle_frozen) + return -EBUSY; /* TEST (sv6t11): the PIPE handler, the controller's bank, read while it holds its domain. */ if (step == APPLE_T6050_CIO_USB_PARK && dp->cio_usb_kept && !dp->cio_usb_parked) { mux = readl(dp->banks[44] + 0xc); @@ -1380,6 +1482,7 @@ EXPORT_SYMBOL_GPL(apple_t6050_phy_cio_usb); static const struct dev_pm_ops t6050_dp_pm_ops = { .suspend_late = pm_sleep_ptr(t6050_dp_suspend_late), .resume_noirq = pm_sleep_ptr(t6050_dp_resume_noirq), + .resume_early = pm_sleep_ptr(t6050_dp_resume_early), .resume = pm_sleep_ptr(t6050_dp_resume), }; From 56bc4ebcfb5319f428c797d6c00f4cf0e6d4f3b0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 15:46:09 -0500 Subject: [PATCH 0431/1514] phy: apple: atc-t6050: drop deferred tunnel clock stops with USB4 mode A tunnel clock that DCP asks to stop while the PHY is frozen for s2idle is only marked in s2idle_clock_stops, and the stop runs from s2idle_clock_work after the thaw. atc_dp_tunnels_stop(), which stops every clock when the PHY leaves USB4 mode, did not clear those marks. If tipd's resume work took the PHY to SAFE first (a cable pulled during the sleep), the deferred stop then wrote the tunnel switch registers in banks[39] and polled their status with the PHY out of USB4 mode and its domains off, and so did the next call for that clock. Clear the marks in atc_dp_tunnels_stop(), where every clock is stopped anyway. A deferred stop that finds the PHY out of USB4 mode, or faulted, releases only the clock's gate and writes no switch. It stops through atc_dp_tunnels_apply(), as an immediate stop does, rather than the single-clock helper. Also log, at debug level, a clock start refused while the PHY is frozen. Signed-off-by: Satya Benson --- drivers/phy/apple/atc-t6050-dp.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/drivers/phy/apple/atc-t6050-dp.c b/drivers/phy/apple/atc-t6050-dp.c index 607ac8ec98d7e1..c13b08b66ad706 100644 --- a/drivers/phy/apple/atc-t6050-dp.c +++ b/drivers/phy/apple/atc-t6050-dp.c @@ -624,6 +624,8 @@ static void atc_dp_tunnels_stop(struct t6050_dp *dp) bool running = memchr_inv(dp->tunnel_rate, 0, sizeof(dp->tunnel_rate)); memset(dp->tunnel_rate, 0, sizeof(dp->tunnel_rate)); + /* Every clock is stopped here: no stop deferred across s2idle is left. */ + dp->s2idle_clock_stops = 0; if (running) { atc_dp_tunnels_apply(dp, 0, NULL); return; @@ -809,7 +811,16 @@ static int atc_s2idle_clock_stop(struct t6050_dp *dp, unsigned int i) lockdep_assert_held(&dp->lock); dp->tunnel_rate[i] = 0; - ret = atc_dp_tunnel_apply(dp, i + 1, NULL); + /* + * The switches are written only in USB4 mode. If the PHY left it (or + * faulted) since the stop was deferred, the clock no longer runs: only + * its gate can still be held. + */ + if (dp->faulted || dp->combo_mode != COMBO_CIO) { + ret = dp->dp_gates ? atc_domain_set(&dp->dp_gate[i], false) : 0; + } else { + ret = atc_dp_tunnels_apply(dp, i + 1, NULL); + } if (!ret) dp->s2idle_clock_stops &= ~BIT(i); return ret; @@ -863,8 +874,10 @@ int apple_t6050_dp_tunnel_clock(struct phy *phy, unsigned int clock, u8 rate) stop = BIT(clock - 1); if (dp->s2idle_frozen) { - if (rate) + if (rate) { + dev_dbg(dp->dev, "DP tunnel clock %u start refused across s2idle\n", clock); return -EBUSY; + } /* DCP may discard the route once it asks us to stop this clock. */ dp->s2idle_clock_stops |= stop; return 0; From 73dea0df7a51aedda30612268872879f1b8ba2af Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:55:52 +1100 Subject: [PATCH 0432/1514] dt-bindings: power: apple,pmgr-pwrstate: sleep-wakeup-path covers a running consumer apple,sleep-wakeup-path was written for a consumer that the sleep's final commit stops after the noirq phase. A consumer that keeps running through the whole sleep while it is on the wakeup path needs the same thing from the OS: keep the domain on through system sleep, also when it was off when the power controller probed. Say so in the description. No change in meaning for existing users. Signed-off-by: Ryan Murray --- .../bindings/power/apple,pmgr-pwrstate.yaml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml index d8c03b0a12702c..537ae7012bc764 100644 --- a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml @@ -151,11 +151,12 @@ properties: apple,sleep-wakeup-path: description: - A consumer of this domain is stopped by the system sleep's final commit, - after the noirq phase, and stays on the wakeup path until then. The OS - keeps the domain on through system sleep while a device under it is on - the wakeup path, also when the domain was off when the power controller - probed. Other domains are unaffected. + A consumer of this domain can keep running into system sleep, until the + sleep's final commit after the noirq phase or through the whole sleep, + and is then on the wakeup path. The OS keeps the domain on through + system sleep while a device under it is on the wakeup path, also when + the domain was off when the power controller probed. Other domains are + unaffected. type: boolean apple,firmware-owned: From c1c5e672585dd1578709b21fa901b5936bb2c444 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:55:53 +1100 Subject: [PATCH 0433/1514] arm64: dts: apple: t604x: mark the ATC common_dp domains sleep-wakeup-path The Type-C PHY coprocessor under atcN_common_dp keeps running through suspend-to-idle while a link is up. Mark the four common_dp domains apple,sleep-wakeup-path so that genpd keeps one on while the PHY puts itself on the awake path, also when the domain was off when the power controller probed (no cable at boot). phymxwrap above it stays on through its subdomain count. Nothing changes for a PHY that is not on the awake path. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t604x-pmgr.dtsi | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi index 977818bca2ec32..daa6811c841116 100644 --- a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi @@ -431,6 +431,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc0_phymxwrap>; }; @@ -467,6 +469,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc1_phymxwrap>; }; @@ -503,6 +507,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc2_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; power-domains = <&ps_atc2_phymxwrap>; }; }; @@ -578,6 +584,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc3_common_dp"; + /* The PHY coprocessor can keep running through s2idle. */ + apple,sleep-wakeup-path; status = "disabled"; }; From e1b79fc07d8e86e9db631754c573a3b894e49238 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 07:55:53 +1100 Subject: [PATCH 0434/1514] phy: apple: t6040: hold a running coprocessor's domains via the awake path The PM notifier sampled "coprocessor running" once, at PM_SUSPEND_PREPARE. A coprocessor started later was not held: an attach between PREPARE and the device's suspend, or an attach during a dark wake, where enter_state() runs suspend_devices_and_enter() again without the notifiers (a cable or charger plugged into a closed, sleeping machine). genpd then powered common_dp off under it in noirq, which is the original bug. dev_pm_syscore_device() also kept the device out of the PM core's prepare/late handling altogether. Decide in the device's own .suspend instead, on every suspend pass, and put the device on the awake path with device_set_awake_path() while its coprocessor runs; common_dp carries apple,sleep-wakeup-path, so genpd keeps it (and phymxwrap above it) on. Decide again in .suspend_noirq, which genpd runs before its own awake-path check, for a coprocessor started after .suspend. In noirq a caller holding the PHY lock may be waiting for a coprocessor reply that cannot arrive; the outcome is then unknown, so the domains stay on for that sleep rather than block. The notifier, the syscore flag and the held state go away. Sleeps the platform firmware takes part in are left as they were (pm_suspend_no_platform() is false there). Signed-off-by: Ryan Murray --- drivers/phy/apple/t6040-usb2.c | 86 ++++++++++++++++++---------------- 1 file changed, 45 insertions(+), 41 deletions(-) diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index c6d567a0b58345..4e995d029785cc 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -286,8 +286,6 @@ struct t6040_usb2_phy { struct completion app_reply; struct t6040_recovery_state recovery; atomic_t drop_next_power_down_ack; - struct notifier_block pm_nb; - bool s2idle_held; /* held out of this suspend-to-idle, see t6040_pm_notify() */ struct dentry *debugfs; enum typec_orientation orientation; bool usb3_up; /* tuned by the coprocessor this power cycle */ @@ -2135,48 +2133,61 @@ static void t6040_rtkit_cleanup(void *data) * Suspend-to-idle leaves the Type-C link up: the USB4/Thunderbolt router keeps * its own domains out of the system transition while a cable is set up, and a * running PHY coprocessor is not stopped either. genpd would still power off - * common_dp (and with it phymxwrap) in its noirq phase once this device has - * suspended, under the running coprocessor: the link then dies after resume and - * the next detach finds a coprocessor that no longer answers (AP idle -62). - * Hold this device out of the whole transition, from before its prepare to - * after its complete, while its coprocessor runs, so its domains stay on. A - * sleep the platform takes part in (firmware suspend) is left as it was. + * common_dp (and with it phymxwrap) in its noirq phase under the running + * coprocessor: the link then dies after resume and the next detach finds a + * coprocessor that no longer answers (AP idle -62). Put this device on the + * awake path while its coprocessor runs, so genpd keeps the domains on + * (common_dp carries apple,sleep-wakeup-path). The decision is taken again in + * every suspend pass, dark wakes included, and once more in noirq for a + * coprocessor started after .suspend. A sleep the platform takes part in + * (firmware suspend) is left as it was. */ -static int t6040_pm_notify(struct notifier_block *nb, unsigned long action, void *data) +static void t6040_keep_running_cpu_awake(struct t6040_usb2_phy *tphy, bool noirq) { - struct t6040_usb2_phy *tphy = container_of(nb, struct t6040_usb2_phy, pm_nb); + bool running; - switch (action) { - case PM_SUSPEND_PREPARE: - if (!pm_suspend_no_platform()) - break; - scoped_guard(mutex, &tphy->lock) { - if (tphy->rtk && apple_rtkit_is_running(tphy->rtk)) { - dev_pm_syscore_device(tphy->dev, true); - tphy->s2idle_held = true; - dev_dbg(tphy->dev, "PHY coprocessor running: domains kept on for s2idle\n"); - } - } - break; - case PM_POST_SUSPEND: - scoped_guard(mutex, &tphy->lock) { - if (tphy->s2idle_held) { - dev_pm_syscore_device(tphy->dev, false); - tphy->s2idle_held = false; - } + if (!pm_suspend_no_platform()) + return; + + if (noirq) { + /* + * An attach or detach holding the lock may wait for a coprocessor + * reply that cannot arrive now. Its outcome is unknown: keep the + * domains on for this sleep. + */ + if (!mutex_trylock(&tphy->lock)) { + device_set_awake_path(tphy->dev); + return; } - break; + } else { + mutex_lock(&tphy->lock); + } + running = tphy->rtk && apple_rtkit_is_running(tphy->rtk); + mutex_unlock(&tphy->lock); + + if (running) { + device_set_awake_path(tphy->dev); + dev_dbg(tphy->dev, "PHY coprocessor running: domains kept on for s2idle\n"); } - return NOTIFY_DONE; } -static void t6040_pm_notifier_unregister(void *data) +static int t6040_usb2_suspend(struct device *dev) { - struct t6040_usb2_phy *tphy = data; + t6040_keep_running_cpu_awake(dev_get_drvdata(dev), false); + return 0; +} - unregister_pm_notifier(&tphy->pm_nb); +static int t6040_usb2_suspend_noirq(struct device *dev) +{ + t6040_keep_running_cpu_awake(dev_get_drvdata(dev), true); + return 0; } +static const struct dev_pm_ops t6040_usb2_pm_ops = { + .suspend = t6040_usb2_suspend, + .suspend_noirq = t6040_usb2_suspend_noirq, +}; + static void t6040_mbox_dev_put(void *data) { put_device(data); @@ -2345,14 +2356,6 @@ static int t6040_usb3_probe(struct t6040_usb2_phy *tphy, struct platform_device if (ret) return ret; - tphy->pm_nb.notifier_call = t6040_pm_notify; - ret = register_pm_notifier(&tphy->pm_nb); - if (ret) - return ret; - ret = devm_add_action_or_reset(dev, t6040_pm_notifier_unregister, tphy); - if (ret) - return ret; - ret = t6040_debugfs_init(tphy); if (ret) return ret; @@ -2562,6 +2565,7 @@ static struct platform_driver t6040_usb2_driver = { .driver = { .name = "phy-apple-t6040-usb2", .of_match_table = t6040_usb2_of_match, + .pm = pm_sleep_ptr(&t6040_usb2_pm_ops), }, }; module_platform_driver(t6040_usb2_driver); From e5dc25e438cf027dbfb30709e8c7f90a98dfd1ae Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 15:29:50 +0000 Subject: [PATCH 0435/1514] arm64: dts: apple: t6041-j616c: enable High Power mode on CLPC The 16-inch MacBook Pro with the M4 Max (J616c) has High Power mode on macOS, matching the 16-inch M4 Pro (J616s). Set apple,high-power-mode on its CLPC node so the performance platform profile sends the High Power record to the SMC (t604x.dtsi already links apple,smc = <&smc>). The 14-inch J614c was not tested here and is left unchanged. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j616c.dts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index 80f0a2a103071a..aaebd20dc588aa 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -41,6 +41,11 @@ apple,output-templates = <0xe 0x00800000>; }; +/* The 16-inch M4 Max chassis has High Power mode, as on the J616s */ +&clpc { + apple,high-power-mode; +}; + /* * ADT aop-spmi0/stockholm-spmi: the Stockholm NFC controller at SPMI 9, its * interrupts in 224-230 and its enable on SMC gp0e, as on the J616s. From 42cc92083f684f0327528ea289153a1a92272561 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 22:35:36 +1100 Subject: [PATCH 0436/1514] arm64: dts: apple: t8112, t602x: alias the SEP on the M2 desktops The SEP node is disabled in t8112.dtsi and t602x-die0.dtsi on every board, laptops included. That is the warm-attach contract of apple_sep: on these SoCs the SEP is already running when Linux starts, and the driver enables the SEP node and sep_dart with a changeset at module load, after it has picked the SoC's profile and before the DART probes. The running M2 Air (J413) shows it: "SEP DART changeset applied", "SEP node enabled", then "ready ... 12 endpoints". Say so at the node, so the disabled status does not read as a missing enable. What a board must provide is the sep alias: m1n1 finds the SEP through it to add the sepfw region and the local-policy and iBoot manifests, and the warm registration refuses to attach without the manifests. The M2 laptops have it; the Mac mini (J473, J474s) and the Mac Studio M2 Max (J475c) have a SEP and a profile (T8112, T6020/T6021) but no alias, so the driver could never attach there (key store, Magic Keyboard Touch ID). Add it. These boards have no built-in sensor and leave the mesa node disabled. The M2 Ultra boards (J475d, J180d) get no alias: the driver has no T6022 profile, so it would only reserve memory for nothing. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6020-j474s.dts | 4 ++++ arch/arm64/boot/dts/apple/t6021-j475c.dts | 4 ++++ arch/arm64/boot/dts/apple/t602x-die0.dtsi | 9 +++++++++ arch/arm64/boot/dts/apple/t8112-j473.dts | 1 + arch/arm64/boot/dts/apple/t8112.dtsi | 9 +++++++++ 5 files changed, 27 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6020-j474s.dts b/arch/arm64/boot/dts/apple/t6020-j474s.dts index 3d2b4c3e0211b3..7b80e06270ab5e 100644 --- a/arch/arm64/boot/dts/apple/t6020-j474s.dts +++ b/arch/arm64/boot/dts/apple/t6020-j474s.dts @@ -21,6 +21,10 @@ / { compatible = "apple,j474s", "apple,t6020", "apple,arm-platform"; model = "Apple Mac mini (M2 Pro, 2023)"; + + aliases { + sep = &sep; + }; }; /* PCIe devices */ diff --git a/arch/arm64/boot/dts/apple/t6021-j475c.dts b/arch/arm64/boot/dts/apple/t6021-j475c.dts index c3fce206ab662a..fa6ee51e9cf4bb 100644 --- a/arch/arm64/boot/dts/apple/t6021-j475c.dts +++ b/arch/arm64/boot/dts/apple/t6021-j475c.dts @@ -15,6 +15,10 @@ / { compatible = "apple,j475c", "apple,t6021", "apple,arm-platform"; model = "Apple Mac Studio (M2 Max, 2023)"; + + aliases { + sep = &sep; + }; }; &wifi0 { diff --git a/arch/arm64/boot/dts/apple/t602x-die0.dtsi b/arch/arm64/boot/dts/apple/t602x-die0.dtsi index 828f6ac65c4a8b..488afa4e9e5744 100644 --- a/arch/arm64/boot/dts/apple/t602x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-die0.dtsi @@ -722,6 +722,15 @@ status = "disabled"; }; + /* + * Disabled here on every board by design. The SEP is already + * running when Linux starts (warm attach: one shared-memory + * registration, no cold boot), so apple_sep enables this node + * and sep_dart with a changeset at module load, once it has + * picked this SoC's profile and before the DART probes. A + * board with the enclave only needs the sep alias, which m1n1 + * uses to add the sepfw region and the boot manifests. + */ sep: sep@396400000 { compatible = "apple,sep"; reg = <0x3 0x96400000 0x0 0x6C000>; diff --git a/arch/arm64/boot/dts/apple/t8112-j473.dts b/arch/arm64/boot/dts/apple/t8112-j473.dts index 84ecd65613567d..eeda54799f63f3 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473.dts +++ b/arch/arm64/boot/dts/apple/t8112-j473.dts @@ -24,6 +24,7 @@ ethernet0 = ðernet0; rtc0 = &smc_rtc; rtc1 = &pmu_rtc; + sep = &sep; wifi0 = &wifi0; }; }; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index d6787eff621bb6..a645b90092883b 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1847,6 +1847,15 @@ status = "disabled"; }; + /* + * Disabled here on every board by design. The SEP is already + * running when Linux starts (warm attach: one shared-memory + * registration, no cold boot), so apple_sep enables this node + * and sep_dart with a changeset at module load, once it has + * picked this SoC's profile and before the DART probes. A + * board with the enclave only needs the sep alias, which m1n1 + * uses to add the sepfw region and the boot manifests. + */ sep: sep@25e400000 { compatible = "apple,sep"; reg = <0x2 0x5e400000 0x0 0x6C000>; From 9cbc00e0a01595a89fa18be9aa9e42de5fd94eb7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:08:27 +1100 Subject: [PATCH 0437/1514] phy: apple: atc: tell a drive level request apart from a bad one The DP PHYs without drive level control (the T8103 generation, which the M1 and M2 ATC PHYs are) refused a voltage swing and pre-emphasis request with -EINVAL, like an invalid configuration. A caller then cannot tell "this PHY keeps its levels" from a request that is wrong. Return -EOPNOTSUPP for it. The lanes keep the levels their tunables set up, as before. Signed-off-by: Ryan Murray --- drivers/phy/apple/atc.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..89ff2f9f1cc3f9 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -4949,8 +4949,13 @@ static int atcphy_dpphy_configure(struct phy *phy, union phy_configure_opts *opt if (atcphy->hw->dp_t8122) return atcphy_dpphy_configure_t8122(atcphy, opts); + /* + * These PHYs have no drive level control: the lanes keep the levels + * their tunables set up. Tell a drive level request apart from a bad + * one, so the caller can keep the levels it asked for. + */ if (opts->set_voltages) - return -EINVAL; + return -EOPNOTSUPP; if (opts->set_lanes) return -EINVAL; From 2b316ee558c4aa47b1f453bae930567d54842d8a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:08:28 +1100 Subject: [PATCH 0438/1514] drm/apple: dptx: keep the drive levels a PHY cannot set On firmware 27, SetDriveSettings passes DCP's requested voltage swing and pre-emphasis to the Type-C PHY. A PHY without drive level control refuses that, the call fails and DCP restarts link training: on the M2 Mac mini, a USB-C display behind a DP-to-HDMI adapter trained at HBR2 x4 five times and stayed disconnected. Before firmware 27 the levels were only recorded, which is how these PHYs have always trained. When the PHY says it has no drive level control, keep the levels DCP asked for and answer as before; any other PHY error still fails the call. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dptx-drive-v27.inc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dptx-drive-v27.inc b/drivers/gpu/drm/apple/dptx-drive-v27.inc index 4fabf1347a8cdb..35e62ceabd2f8b 100644 --- a/drivers/gpu/drm/apple/dptx-drive-v27.inc +++ b/drivers/gpu/drm/apple/dptx-drive-v27.inc @@ -103,7 +103,12 @@ static int dptxport_call_drive_v27(struct apple_epic_service *service, bool set, if (!dptx->atcphy) return -ENODEV; ret = phy_configure(dptx->atcphy, &opts); - if (ret) + /* + * A PHY without drive level control keeps the levels + * its tunables set; DCP's link training goes on with + * them, as with the firmware before 27. + */ + if (ret && ret != -EOPNOTSUPP) return ret; } for (u32 i = 0; i < count; i++) { From 1c33c3b8dc6058c3a6269ecd7cd16588abcf199c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:08:28 +1100 Subject: [PATCH 0439/1514] drm/apple: dcp: open the firmware-27 DPTX ports of a DCP with Type-C routes dcp_v27_dptx_layout() chooses the DPTX controller and port endpoints from what firmware 27 advertises, but only for a dcpext. A primary DCP that the device tree connects to Type-C display routes, as on the M2 Mac mini, keeps the default endpoints, so its DPTX endpoint start times out ("Failed to start DPTX endpoint: -110") and USB-C displays stay dark. Choose the advertised endpoints for a DCP with Type-C routes too. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 39bccc811e160f..5295f566c88f67 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -4657,6 +4657,9 @@ static int dcp_ext26_start_services(struct apple_dcp *dcp) * whose firmware advertises both of those gets the controller and its ports * there. * + * A primary DCP can also serve external ports when the device tree connects + * Type-C display routes to it. + * * Decided here, not at probe: RTKit is woken at bind, and its endpoint map is * known only from then on. Hardware data that names an endpoint keeps it: * T8142's dcpext (the same layout), and the T6050 and firmware-27 T6041 @@ -4664,8 +4667,8 @@ static int dcp_ext26_start_services(struct apple_dcp *dcp) */ static void dcp_v27_dptx_layout(struct apple_dcp *dcp) { - if (dcp->fw_compat != DCP_FIRMWARE_V_27_0 || !dcp->dcpext || - dcp->hw.dptx_endpoint) + if (dcp->fw_compat != DCP_FIRMWARE_V_27_0 || + (!dcp->dcpext && !dcp->nr_typec_routes) || dcp->hw.dptx_endpoint) return; if (!apple_rtkit_has_endpoint(dcp->rtk, DPTX_CONTROLLER_ENDPOINT) || !apple_rtkit_has_endpoint(dcp->rtk, DPTX_ENDPOINT)) From dbb40da095c76161de2d656f65c6a75bd0e20179 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:14:40 +1100 Subject: [PATCH 0440/1514] accel/ane: size a buffer object's address range in 64 bits ane_iommu_map_pages() reserves a buffer object's device address range with `bo->npages << ane->shift`, which is evaluated in 32 bits because npages is a u32, while ane_iommu_map_batch() maps `(size_t)bo->npages << shift` bytes, so for a large enough buffer object the reservation and the range that is mapped (and, after an -EEXIST, cleared as strays) differ. BO_INIT also accepts any size. Compute the size once, in 64 bits, and use it for both the reservation and the map, so the map and the stray clearing never leave the node that was just reserved. Use 64-bit page offsets in the per-page map, unmap and reclaim loops. Refuse a BO_INIT whose size does not fit the device address range the allocator manages with -E2BIG, before any page is allocated: such a buffer object could never be mapped, and the check also keeps the page count within the u32 the map paths use and the page array allocation well below its limit. KUnit: ane-bo checks the range size at the u32 page-count boundary and the BO_INIT size check at the range limit, past it, with a page count past u32 and with U64_MAX. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane.h | 4 +++ drivers/accel/ane/ane_drv.c | 50 ++++++++++++++++++++------ drivers/accel/ane/ane_drv_test.c | 61 ++++++++++++++++++++++++++++++-- 3 files changed, 103 insertions(+), 12 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 24a44ea99ed5db..119f73dfedf072 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -46,6 +46,8 @@ struct ane_device { void __iomem *ps; struct drm_mm mm; + /* Size of the device address range that mm manages. */ + u64 iova_span; struct iommu_domain *domain; unsigned long shift; struct ane_dart { @@ -223,6 +225,8 @@ static inline bool ane_tm_failure_recoverable(bool tm_retention, } #if IS_ENABLED(CONFIG_KUNIT) +u64 ane_bo_iova_size(u32 npages, unsigned int shift); +int ane_bo_check_size(u64 size, u64 iova_span); int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, size_t btsp_size); #endif diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 9db29596045700..c722af5c6170b3 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -115,6 +115,32 @@ static struct ane_bo *bo_lookup(struct drm_file *file, u32 handle) return to_bo(gem); } +/* + * The IOVA span of a buffer object. Computed in 64 bits: the reservation + * and the map must cover the same range for any page count. + */ +VISIBLE_IF_KUNIT u64 ane_bo_iova_size(u32 npages, unsigned int shift) +{ + return (u64)npages << shift; +} +EXPORT_SYMBOL_IF_KUNIT(ane_bo_iova_size); + +/* + * A buffer object must fit the device address range the allocator + * manages, or it can never be mapped. Refusing it before any page is + * allocated also keeps the page count within the u32 that the map + * paths use. + */ +VISIBLE_IF_KUNIT int ane_bo_check_size(u64 size, u64 iova_span) +{ + if (!size) + return -EINVAL; + if (size > iova_span || round_up(size, PAGE_SIZE) > iova_span) + return -E2BIG; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(ane_bo_check_size); + /* Unmap every valid PTE in [start, end) and return how many there were. */ static unsigned long ane_iommu_clear_range(struct ane_device *ane, u64 start, u64 end) @@ -145,7 +171,7 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, int err = 0; for (u32 i = 0; i < bo->npages; i++) { - dma_addr_t iova = bo->iova + (i << ane->shift); + dma_addr_t iova = bo->iova + ((u64)i << ane->shift); bool healed = false; retry: @@ -168,12 +194,12 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, unmapped = iommu_unmap(ane->domain, bo->iova + - (i << ane->shift), + ((u64)i << ane->shift), 1UL << ane->shift); if (unmapped != 1UL << ane->shift) dev_err(ane->dev, "rollback unmap short at %#llx: %zu\n", - bo->iova + (i << ane->shift), + bo->iova + ((u64)i << ane->shift), unmapped); } break; @@ -191,7 +217,7 @@ static int ane_iommu_map_each(struct ane_device *ane, struct ane_bo *bo, static int ane_iommu_map_batch(struct ane_device *ane, struct ane_bo *bo, int prot) { - size_t size = (size_t)bo->npages << ane->shift; + size_t size = ane_bo_iova_size(bo->npages, ane->shift); struct sg_table sgt; unsigned long strays; ssize_t mapped; @@ -261,7 +287,7 @@ static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) /* reserve area from ANE address space */ err = drm_mm_insert_node_generic(&ane->mm, bo->mm, - bo->npages << ane->shift, + ane_bo_iova_size(bo->npages, ane->shift), 1UL << ane->shift, 0, 0); if (err < 0) { dev_err(ane->dev, "out of ANE space: %d\n", err); @@ -300,7 +326,7 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) list_del_init(&bo->node); mutex_lock(&ane->iommu_lock); for (u32 i = 0; i < bo->npages; i++) { - dma_addr_t iova = bo->iova + (i << ane->shift); + dma_addr_t iova = bo->iova + ((u64)i << ane->shift); size_t unmapped = iommu_unmap(ane->domain, iova, 1UL << ane->shift); @@ -371,12 +397,12 @@ void ane_reclaim_preserved(struct ane_device *ane) size_t unmapped; unmapped = iommu_unmap(ane->domain, - iova + (i << ane->shift), + iova + ((u64)i << ane->shift), 1UL << ane->shift); if (unmapped != 1UL << ane->shift) dev_err(ane->dev, "preserved unmap short at %#llx: %zu\n", - iova + (i << ane->shift), unmapped); + iova + ((u64)i << ane->shift), unmapped); } drm_mm_remove_node(p->mm); mutex_unlock(&ane->iommu_lock); @@ -488,8 +514,11 @@ static int ane_bo_init(struct drm_device *drm, void *data, struct ane_bo *bo; int err; - if (args->pad || !args->size) + if (args->pad) return -EINVAL; + err = ane_bo_check_size(args->size, ane->iova_span); + if (err) + return err; bo = kzalloc_obj(*bo); if (!bo) @@ -1044,7 +1073,8 @@ static int ane_iommu_domain_init(struct ane_device *ane) return -EINVAL; ane->domain = domain; ane->shift = PAGE_SHIFT; - drm_mm_init(&ane->mm, min_iova, limit - min_iova); + ane->iova_span = limit - min_iova; + drm_mm_init(&ane->mm, min_iova, ane->iova_span); return 0; } diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index 90708b9613de3d..f0cb7cc3fad9eb 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* - * KUnit tests for the buffer size checks of DRM_IOCTL_ANE_SUBMIT. + * KUnit tests for the buffer size checks of DRM_IOCTL_ANE_SUBMIT and + * DRM_IOCTL_ANE_BO_INIT. */ #include @@ -145,7 +146,63 @@ static struct kunit_suite ane_recovery_test_suite = { .test_cases = ane_recovery_test_cases, }; -kunit_test_suites(&ane_submit_test_suite, &ane_recovery_test_suite); +/* BO_INIT: the reservation and the map must agree for any page count. */ +static void ane_bo_iova_size_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(1, 14), (u64)SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x3ffff, 14), + (u64)SZ_4G - SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x40000, 14), (u64)SZ_4G); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(0x40001, 14), + (u64)SZ_4G + SZ_16K); + KUNIT_EXPECT_EQ(test, ane_bo_iova_size(U32_MAX, 12), + (u64)U32_MAX << 12); +} + +struct ane_bo_size_case { + const char *desc; + u64 size; + u64 span; + int ret; +}; + +/* The H13 allocator range: one page above zero up to 4 GiB. */ +#define ANE_TEST_SPAN ((u64)SZ_4G - PAGE_SIZE) + +static const struct ane_bo_size_case ane_bo_size_cases[] = { + { "zero bytes", 0, ANE_TEST_SPAN, -EINVAL }, + { "one byte", 1, ANE_TEST_SPAN, 0 }, + { "the whole range", ANE_TEST_SPAN, ANE_TEST_SPAN, 0 }, + { "one byte past the range", ANE_TEST_SPAN + 1, ANE_TEST_SPAN, -E2BIG }, + { "4 GiB", SZ_4G, ANE_TEST_SPAN, -E2BIG }, + { "4 GiB and one page", (u64)SZ_4G + PAGE_SIZE, ANE_TEST_SPAN, -E2BIG }, + { "page count past u32", (u64)PAGE_SIZE << 32, ANE_TEST_SPAN, -E2BIG }, + { "largest u64", U64_MAX, ANE_TEST_SPAN, -E2BIG }, + { "rounds up past a smaller range", SZ_16K + 1, SZ_16K + 1, -E2BIG }, +}; + +KUNIT_ARRAY_PARAM_DESC(ane_bo_size, ane_bo_size_cases, desc); + +static void ane_bo_check_size_test(struct kunit *test) +{ + const struct ane_bo_size_case *c = test->param_value; + + KUNIT_EXPECT_EQ(test, ane_bo_check_size(c->size, c->span), c->ret); +} + +static struct kunit_case ane_bo_test_cases[] = { + KUNIT_CASE(ane_bo_iova_size_test), + KUNIT_CASE_PARAM(ane_bo_check_size_test, ane_bo_size_gen_params), + {} +}; + +static struct kunit_suite ane_bo_test_suite = { + .name = "ane-bo", + .test_cases = ane_bo_test_cases, +}; + +kunit_test_suites(&ane_submit_test_suite, &ane_recovery_test_suite, + &ane_bo_test_suite); MODULE_DESCRIPTION("KUnit tests for the Apple Neural Engine SUBMIT checks"); MODULE_LICENSE("Dual MIT/GPL"); From cde874ee627d75331949bedfdd1c853dfccda797 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 21 Nov 2026 14:15:03 -0300 Subject: [PATCH 0441/1514] drm/asahi: g17: keep a queue's frontier off contiguous pages A logical queue keeps one frontier entry per command whose completion has not signalled yet, and the pruned entries of the current ioctl in `finished`. Both are KVecs, so they grow by krealloc() into physically contiguous memory. The frontier is bounded only by how much work userspace keeps queued: vkd3d-proton's test_resolve_image_exhaustive_descriptors records 64 x 1024 resolves in one command list, and the frontier reaches thousands of entries. Growing it then needs an order-5 or order-6 block (512 KiB to 1 MiB with 16K pages). On a fragmented machine (4.3 GB free, nothing above order 4) the allocation fails. If it is `finished`, prune_frontier() falls back and only warn_alloc() dumps a trace. If it is the frontier's own reserve, the submit fails with ENOMEM after some of its commands may already have been queued, so Mesa marks the queue lost and reports VK_ERROR_DEVICE_LOST: vkd3d_queue: page allocation failure: order:6, mode:0x40cc0(GFP_KERNEL|__GFP_COMP) ... krealloc_node_align_noprof+0x154/0x238 rust_helper_krealloc_node_align+0x10/0x20 ..._asahi_core3g175queue...14prune_frontier... asahi 28a600000.gpu: [File 119992 Queue 1]: IOCTL: submit failed! (submission ID: 38521603 err: ENOMEM) The same test reproduces it alone on a loaded machine (nothing free above order 3): a perf probe on kmem:kmalloc shows the frontier's reserve asking for 196608 bytes (2048 -> 4096 entries) and getting NULL, and the submit fails with ENOMEM. Nothing needs these arrays contiguous: only the ioctl reads them. Make both KVVecs. kvrealloc() still tries kmalloc first, for a large size without direct reclaim or a warning, and falls back to vmalloc. Small frontiers keep their kmalloc memory, and a deep one no longer depends on high-order pages. Reserve the frontier room for a whole submission before its output fences are published, instead of one entry per command as it is queued, so that an allocation failure fails the submission cleanly instead of half-way. Userspace decides how long the frontier gets, and it can now grow past what contiguous pages ever allowed, so charge it and `finished` to the caller's memory cgroup (GFP_KERNEL_ACCOUNT). Fixes: 52ef95b9e763 ("drm/asahi: add the T8140 firmware interface") Fixes: 39bdd5b8e2d5 ("drm/asahi: release pruned G17 frontier entries after the ioctl publishes") Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 12 ++++++--- drivers/gpu/drm/asahi/g17/queue/mod.rs | 34 +++++++++++++++----------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index b6536c07b443f9..1707686b0531ab 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -37,6 +37,13 @@ pub(crate) enum Engine { } impl Engine { + pub(crate) fn of(command: &Validated) -> Self { + match command { + Validated::Render { .. } => Self::Render, + Validated::Compute { .. } => Self::Compute, + } + } + pub(crate) fn index(self) -> usize { match self { Self::Render => 0, @@ -176,10 +183,7 @@ impl Packet { } pub(crate) fn engine(&self) -> Engine { - match &self.command { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - } + Engine::of(&self.command) } /// Replay holds the device mutex. Its original inputs were satisfied before diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e3..292317bbca82e1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -100,10 +100,13 @@ pub(crate) struct Queue { variant: &'static crate::g17::fw::Variant, proof: Proof, sequence: [u64; 2], - frontiers: [KVec<(u64, Fences)>; 2], + /// One entry per unfinished command, so as long as userspace keeps work queued + /// (thousands under vkd3d-proton). Neither it nor `finished` needs + /// contiguous pages, and their growth must not fail a submit on fragmentation. + frontiers: [KVVec<(u64, Fences)>; 2], /// Finished frontier entries pruned during this ioctl. Their last references /// can tear a whole completion down; that waits until the ioctl has published. - finished: KVec, + finished: KVVec, failures: [FailureRecord; 2], // Closing the userspace queue releases admission even if firmware still // retains one of its execution contexts or installed physical graphs. @@ -152,8 +155,8 @@ impl Queue { variant, proof: Proof::new(), sequence: [0; 2], - frontiers: core::array::from_fn(|_| KVec::new()), - finished: KVec::new(), + frontiers: core::array::from_fn(|_| KVVec::new()), + finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], _slot: slot, }) @@ -179,7 +182,7 @@ impl Queue { // Without room the entries are released here, as they always could be. let mut finished = if self .finished - .reserve(self.frontiers[index].len(), GFP_KERNEL) + .reserve(self.frontiers[index].len(), GFP_KERNEL_ACCOUNT) .is_ok() { Some(&mut self.finished) @@ -213,10 +216,7 @@ impl Queue { inputs: &[file::SyncItem], destinations: Destinations, ) -> Result { - let engine = match &command { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - }; + let engine = Engine::of(&command); let index = engine.index(); if let Validated::Render { ray_query, .. } = &command { let blocks = self @@ -227,7 +227,6 @@ impl Queue { } } self.prune_frontier(index); - self.frontiers[index].reserve(1, GFP_KERNEL)?; if engine == Engine::Compute { self.ensure_compute(&command)?; } @@ -475,10 +474,7 @@ impl Queue { &command.payload, ) .map_err(|error| refused("the command's requirements", error))?; - let engine = match &payload { - Validated::Render { .. } => Engine::Render, - Validated::Compute { .. } => Engine::Compute, - }; + let engine = Engine::of(&payload); if !self.backend.supports_engine(engine) { return Err(ENOTSUPP); } self.backend .prepare_command(&mut payload) @@ -596,6 +592,16 @@ impl crate::queue::Queue for Queue { command.allow_long_job(); } } + // Room for every command's frontier entry, so that running out of memory fails + // the submission before any of it is queued. Userspace sets the frontier's + // length, so its memory is charged to the caller. + let mut room = [0; 2]; + for (command, _, _) in pending.iter() { + room[Engine::of(command).index()] += 1; + } + for (frontier, room) in self.frontiers.iter_mut().zip(room) { + frontier.reserve(room, GFP_KERNEL_ACCOUNT)?; + } let mut guards = guards.into_iter(); // Where a firmware wait reports completion before a weak stream tail's writes are // visible, only a command that declares a visible completion is waited for there. From 4522bf737f1a51ba549d2d11f7deed6b84d2d05b Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 21 Nov 2026 17:00:20 -0300 Subject: [PATCH 0442/1514] drm/asahi: g17: prune a queue's frontier from the front Every enqueue pruned its engine's frontier with a full retain(): it read the completion status of every unfinished command, and the kernel's Vec::retain() swaps each kept entry in place, three 48-byte memcpy() calls per entry. A frontier holds every unfinished command, thousands under vkd3d-proton, so submitting N queued commands cost O(N^2). In test_resolve_image_exhaustive_descriptors (64 x 1024 resolves) on an M4 Pro, prune_frontier() and its memcpy() took about 70% of the ASAHI_SUBMIT ioctl's kernel time, 0.6 s of CPU per run. Commands mostly finish in order, so take finished entries from the front and stop at the first unfinished one: a prune now costs what it removes. When the room runs out, the held entries are moved down into the gap left in front once it is at least half as large as they are, so a move costs at most two per entry that left, and a steady deep queue does not double its room. A success that finishes behind an older unfinished command stays until it reaches the front. The readers already skip finished entries by their status, except the two that relied on a just-pruned frontier, host_predecessors and the compute timestamp waits; they now check it too, so they see the same set. The input-source check walks only the prefixes it covers, and the room for other-engine dependencies is sized by the unfinished ones alone. A failure cannot wait for the front: later commands whose prefix covers it must be cancelled from the next prune on, and a same-engine command without inputs or timestamps has no other reader that would see it. So a public fence that fails is counted twice in its VM's status: before its error is set and after it has signalled. A prune scans the whole frontier, as before, while the first count is ahead of the second one at its last full scan, so it keeps doing so until a scan has run after the failure finished. A prune that comes while the error is being signalled therefore still finds it. Entries now leave by moving into `finished` instead of by a clone, and `finished` grows as entries arrive instead of reserving room for the whole frontier on every prune. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/completion.rs | 24 +- .../drm/asahi/g17/completion/publication.rs | 2 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 110 +++---- .../gpu/drm/asahi/g17/queue/outstanding.rs | 291 ++++++++++++++++++ drivers/gpu/drm/asahi/g17/status.rs | 34 +- tools/asahi/g17-quarantine-drain-tests.py | 2 +- 6 files changed, 390 insertions(+), 73 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g17/queue/outstanding.rs diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a4..aa0ad7c301e490 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -201,12 +201,18 @@ struct Output { } impl Output { - fn publish(&self, result: Result<[u64; 4]>) { + /// `status` is the command's VM status. + fn publish(&self, result: Result<[u64; 4]>, status: &VmStatus) { match result { - Ok(ticks) => self.destinations.write(ticks), - Err(error) => self.fence.set_error(error), + Ok(ticks) => { + self.destinations.write(ticks); + self.fence.signal(); + } + Err(error) => status.signal_failure(|| { + self.fence.set_error(error); + self.fence.signal(); + }), } - self.fence.signal(); self.member.complete(result.map(|_| ())); } } @@ -224,9 +230,9 @@ impl HostOutput { } } - fn finish(&self, result: Result<[u64; 4]>) { + fn finish(&self, result: Result<[u64; 4]>, status: &VmStatus) { match self { - Self::Immediate(output) => output.publish(result), + Self::Immediate(output) => output.publish(result, status), Self::Ordered(publication) => publication.finish(result), } } @@ -877,7 +883,7 @@ impl Completion { } self.release_healthy(); self.signal_terminal(result); - self.output.finish(result); + self.output.finish(result, &self.status); } /// A rejected, never-published command cannot poison the VM for contention. @@ -894,7 +900,7 @@ impl Completion { } self.release_healthy(); self.signal_terminal(Err(error)); - self.output.finish(Err(error)); + self.output.finish(Err(error), &self.status); } /// The physical queue must already be quarantined. Keep mappings pinned while @@ -915,7 +921,7 @@ impl Completion { self.report(error); } self.signal_terminal(Err(error)); - self.output.finish(Err(error)); + self.output.finish(Err(error), &self.status); } } diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 8e16a14f054886..427e1f4ea20a85 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -100,7 +100,7 @@ impl Publication { self.status.report_failure(error); } } - self.output.publish(result); + self.output.publish(result, &self.status); let result = result.map(|_| ()); let mut links = { let mut state = self.state.lock(); diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 292317bbca82e1..e10e7b17cf63b9 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -31,6 +31,15 @@ use kernel::{ static FENCE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); pub(crate) mod admission; +mod outstanding; + +use outstanding::Outstanding; + +impl outstanding::Status for Fences { + fn status(&self) -> i32 { + Fences::status(self) + } +} /// Host identities for retained physical channels, separate from firmware object generations. /// The device mutex protects allocation; cancelled preparations never reuse IDs. @@ -100,12 +109,13 @@ pub(crate) struct Queue { variant: &'static crate::g17::fw::Variant, proof: Proof, sequence: [u64; 2], - /// One entry per unfinished command, so as long as userspace keeps work queued - /// (thousands under vkd3d-proton). Neither it nor `finished` needs - /// contiguous pages, and their growth must not fail a submit on fragmentation. - frontiers: [KVVec<(u64, Fences)>; 2], + /// Each engine's unfinished commands, as many as userspace keeps queued (thousands + /// under vkd3d-proton). + frontiers: [Outstanding; 2], /// Finished frontier entries pruned during this ioctl. Their last references /// can tear a whole completion down; that waits until the ioctl has published. + /// Like the frontiers it needs no contiguous pages, and its growth must not fail + /// a submit on fragmentation. finished: KVVec, failures: [FailureRecord; 2], // Closing the userspace queue releases admission even if firmware still @@ -140,6 +150,7 @@ impl Queue { Engine::Render, super::timeout::DEFAULT_ALLOWANCE_MS, )?); + let failures = context.status().failures().finished; Ok(Self { dev: dev.into(), context, @@ -155,7 +166,7 @@ impl Queue { variant, proof: Proof::new(), sequence: [0; 2], - frontiers: core::array::from_fn(|_| KVVec::new()), + frontiers: [Outstanding::new(failures), Outstanding::new(failures)], finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], _slot: slot, @@ -178,27 +189,13 @@ impl Queue { } fn prune_frontier(&mut self, index: usize) { + let failures = self.context.status().failures(); let failure = &mut self.failures[index]; - // Without room the entries are released here, as they always could be. - let mut finished = if self - .finished - .reserve(self.frontiers[index].len(), GFP_KERNEL_ACCOUNT) - .is_ok() - { - Some(&mut self.finished) - } else { - None - }; - self.frontiers[index].retain(|(sequence, fences)| { - let status = fences.status(); - if status == 0 { - return true; - } - if let Some(finished) = finished.as_mut() { - let _ = finished.push_within_capacity(fences.clone()); - } - failure.note(*sequence, status, fences); - false + let finished = &mut self.finished; + self.frontiers[index].prune(failures, |sequence, status, fences| { + failure.note(sequence, status, &fences); + // Without room the entry is released here, as it always could be. + let _ = finished.push(fences, GFP_KERNEL_ACCOUNT); }); } @@ -242,13 +239,11 @@ impl Queue { && engine == Engine::Compute && !inputs.is_empty() && !destinations.has_outputs() - && self.frontiers[0].iter().all(|(sequence, fences)| { - !Order::contains(order.wait_through[0], *sequence) || fences.status() > 0 - }) - && self.frontiers[1].iter().all(|(sequence, fences)| { - !Order::contains(order.wait_through[1], *sequence) - || fences.ready.raw() != fences.completed.raw() - || fences.status() > 0 + && self.frontiers[0] + .prefix(order.wait_through[0]) + .all(|(_, fences)| fences.status() > 0) + && self.frontiers[1].prefix(order.wait_through[1]).all(|(_, fences)| { + fences.ready.raw() != fences.completed.raw() || fences.status() > 0 }) && self.failures.iter_mut().enumerate().all(|(index, failure)| { failure.earliest().is_none_or(|(sequence, _)| { @@ -271,12 +266,11 @@ impl Queue { // Only earlier render ordinals covered by the explicit logical prefix // can delay host publication. These links never become GPU dependencies. + // A finished one may still be held behind an unfinished one: it delays nothing. + let host_prefix = if engine == Engine::Render { order.wait_through[index] } else { None }; let host_predecessors = self.frontiers[index] - .iter() - .take_while(|(sequence, _)| { - engine == Engine::Render && Order::contains(order.wait_through[index], *sequence) - }) - .filter_map(|(_, fences)| fences.publication.as_ref()); + .prefix(host_prefix) + .filter_map(|(_, fences)| fences.publication.as_ref().filter(|_| fences.status() <= 0)); let completion = Completion::new( &self.dev, &self.fences, @@ -299,34 +293,30 @@ impl Queue { } let other = 1 - index; let prefix = order.wait_through[other]; - let frontier = if prefix.is_some() { - let frontier = self.frontiers[other].as_slice(); - // Accepted sequences increase from one, and retain preserves their - // order, so all members of a logical prefix form one slice. - let end = frontier.partition_point(|(sequence, _)| Order::contains(prefix, *sequence)); - &frontier[..end] - } else { - &[] - }; - let count = frontier.len(); + let frontier = self.frontiers[other].prefix(prefix); + // Finished producers are skipped below. Those still held behind an unfinished one are + // left out here too, so the room below is not sized by them. + let count = frontier.clone().filter(|(_, fences)| fences.status() <= 0).count(); // Only a command that copies or resets queries can observe timestamps the // host has not yet published for its predecessors. let query_access = match &command { Validated::Compute { query_access, .. } => *query_access, Validated::Render { .. } => true, }; - let timestamp_prefix = order.wait_through[index]; - let timestamps = if engine == Engine::Compute && query_access && timestamp_prefix.is_some() { - let frontier = self.frontiers[index].as_slice(); - let end = frontier - .partition_point(|(sequence, _)| Order::contains(timestamp_prefix, *sequence)); - &frontier[..end] + let timestamp_prefix = if engine == Engine::Compute && query_access { + order.wait_through[index] } else { - &[] + None }; + // A finished publisher may still be held behind an unfinished one: its timestamps + // are written, so there is nothing to wait for. + let pending_publisher = |fences: &Fences| { + fences.ready.raw() == fences.completed.raw() && fences.status() <= 0 + }; + let timestamps = self.frontiers[index].prefix(timestamp_prefix); let timestamp_count = timestamps - .iter() - .filter(|(_, fences)| fences.ready.raw() == fences.completed.raw()) + .clone() + .filter(|(_, fences)| pending_publisher(fences)) .count(); let mut failures: [Option; 2] = [None, None]; for (index, failure) in self.failures.iter_mut().enumerate() { @@ -358,7 +348,7 @@ impl Queue { // writes. Only timestamp publishers need these completion waits and // status checks; ordinary compute keeps its existing queue ordering. for (_, fences) in timestamps { - if fences.ready.raw() == fences.completed.raw() { + if pending_publisher(fences) { checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; dependencies.push(fences.ready.clone(), GFP_KERNEL)?; } @@ -430,9 +420,7 @@ impl Queue { .ok_or(ENODEV)? .enqueue(packet, dependencies, early, publication)?; self.sequence[index] = order.sequence; - self.frontiers[index] - .push_within_capacity((order.sequence, fences)) - .map_err(|_| ENOMEM)?; + self.frontiers[index].push_within_capacity(order.sequence, fences)?; Ok(()) } /// Finish parsing, validation and VM pinning before entering publication. @@ -600,7 +588,7 @@ impl crate::queue::Queue for Queue { room[Engine::of(command).index()] += 1; } for (frontier, room) in self.frontiers.iter_mut().zip(room) { - frontier.reserve(room, GFP_KERNEL_ACCOUNT)?; + frontier.reserve(room)?; } let mut guards = guards.into_iter(); // Where a firmware wait reports completion before a weak stream tail's writes are diff --git a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs new file mode 100644 index 00000000000000..cf2f29d95f49af --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs @@ -0,0 +1,291 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! One engine's accepted commands that have not finished, oldest first. +//! +//! Commands mostly finish in order, so a prune takes finished entries from the front and stops at +//! the first unfinished one: it costs what it removes, not the length of the list. An entry that +//! finishes behind an older unfinished one stays until it reaches the front; every reader skips it +//! by its status. A failure must not wait like that, because later commands whose prefix covers it +//! are cancelled: a prune is given its VM's failure counts and scans the whole list from when a +//! failure starts until it has finished and one scan has run after that. + +use crate::g17::{job::Order, status::Failures}; +use kernel::prelude::*; + +/// A command's completion status, as `dma_fence_get_status()`: 0 while unfinished, then 1 or +/// a negative error. +pub(crate) trait Status { + fn status(&self) -> i32; +} + +pub(crate) struct Outstanding { + /// Entries before `head` have left the front and hold nothing. Every entry from `head` + /// on holds its command. It needs no contiguous pages, and its growth must not fail a + /// submit on fragmentation. + entries: KVVec<(u64, Option)>, + head: usize, + /// [`Failures::finished`] at the last full scan. + failures: u64, +} + +impl Outstanding { + /// `failures`: the VM's [`Failures::finished`] now. + pub(crate) const fn new(failures: u64) -> Self { + Self { + entries: KVVec::new(), + head: 0, + failures, + } + } + + /// The entries still held. Some may have finished since the last prune. + pub(crate) fn len(&self) -> usize { + self.entries.len() - self.head + } + + /// The entries still held, oldest first. + pub(crate) fn iter(&self) -> impl Iterator + Clone { + Self::held(&self.entries[self.head..]) + } + + /// The entries still held whose sequence `prefix` covers ([`Order::contains`]). + pub(crate) fn prefix(&self, prefix: Option) -> impl Iterator + Clone { + let held = &self.entries[self.head..]; + // Accepted sequences increase from one, so the entries a prefix covers come first. + let end = held.partition_point(|(sequence, _)| Order::contains(prefix, *sequence)); + Self::held(&held[..end]) + } + + fn held(entries: &[(u64, Option)]) -> impl Iterator + Clone { + entries + .iter() + .filter_map(|(sequence, entry)| Some((*sequence, entry.as_ref()?))) + } + + /// Userspace sets how many commands are outstanding, so their room is charged to it. + pub(crate) fn reserve(&mut self, additional: usize) -> Result { + // Reuse the room in front instead of growing past it, once moving the held entries + // down costs at most two moves for each entry that left since the last move. + if self.entries.capacity() - self.entries.len() < additional && 2 * self.head >= self.len() + { + drop(self.entries.drain(..self.head)); + self.head = 0; + } + Ok(self.entries.reserve(additional, GFP_KERNEL_ACCOUNT)?) + } + + pub(crate) fn push_within_capacity(&mut self, sequence: u64, entry: T) -> Result { + self.entries + .push_within_capacity((sequence, Some(entry))) + .map_err(|_| ENOMEM) + } + + /// Removes finished entries and hands each to `finished` with its status, oldest first. + /// While no failure has started since the last full scan, only entries in front of the + /// oldest unfinished one leave. + pub(crate) fn prune(&mut self, failures: Failures, mut finished: impl FnMut(u64, i32, T)) { + if failures.started != self.failures { + // Only a finished failure is sure to be seen by this scan. One still being signalled + // keeps `started` ahead, so the scans stay full until it has finished. + self.failures = failures.finished; + self.entries.retain(|(sequence, entry)| { + let Some(status) = entry.as_ref().map(Status::status) else { + return false; + }; + if status == 0 { + return true; + } + if let Some(entry) = entry.take() { + finished(*sequence, status, entry); + } + false + }); + self.head = 0; + return; + } + while let Some((sequence, entry)) = self.entries.get_mut(self.head) { + let Some(status) = entry.as_ref().map(Status::status) else { + break; + }; + if status == 0 { + break; + } + if let Some(entry) = entry.take() { + finished(*sequence, status, entry); + } + self.head += 1; + } + } +} + +#[kunit_tests(asahi_g17_outstanding)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicI32, AtomicUsize, Ordering}; + use kernel::sync::Arc; + + /// Status reads of every test command. KUnit runs a suite's cases one after another. + static READS: AtomicUsize = AtomicUsize::new(0); + + /// A command whose status the test sets. + #[derive(Clone)] + struct Command(Arc); + + impl Command { + fn new() -> Self { + Self(Arc::new(AtomicI32::new(0), GFP_KERNEL).unwrap()) + } + fn finish(&self, status: i32) { + self.0.store(status, Ordering::Relaxed); + } + } + + impl Status for Command { + fn status(&self) -> i32 { + READS.fetch_add(1, Ordering::Relaxed); + self.0.load(Ordering::Relaxed) + } + } + + fn push(queue: &mut Outstanding, sequence: u64) -> Command { + let command = Command::new(); + queue.reserve(1).unwrap(); + queue + .push_within_capacity(sequence, command.clone()) + .unwrap(); + command + } + + fn queue(count: u64) -> (Outstanding, KVec) { + let mut queue = Outstanding::new(0); + let mut commands = KVec::new(); + for sequence in 1..=count { + let command = push(&mut queue, sequence); + commands.push(command, GFP_KERNEL).unwrap(); + } + (queue, commands) + } + + fn sequences<'a>(entries: impl Iterator) -> KVec { + let mut sequences = KVec::new(); + for (sequence, _) in entries { + sequences.push(sequence, GFP_KERNEL).unwrap(); + } + sequences + } + + /// A prune with `failures` failures started and finished. + fn prune(queue: &mut Outstanding, failures: u64) -> KVec<(u64, i32)> { + prune_counts(queue, failures, failures) + } + + fn prune_counts( + queue: &mut Outstanding, + started: u64, + finished: u64, + ) -> KVec<(u64, i32)> { + let mut left = KVec::new(); + queue.prune(Failures { started, finished }, |sequence, status, _| { + left.push((sequence, status), GFP_KERNEL).unwrap() + }); + left + } + + #[test] + fn finished_commands_leave_from_the_front_in_order() { + let (mut queue, commands) = queue(4); + commands[0].finish(1); + commands[1].finish(EIO.to_errno()); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32), (2, EIO.to_errno())]); + assert_eq!(sequences(queue.iter()), [3u64, 4]); + assert_eq!(queue.len(), 2); + assert!(prune(&mut queue, 0).is_empty()); + } + + #[test] + fn a_command_finished_behind_an_unfinished_one_waits_for_the_front() { + let (mut queue, commands) = queue(3); + commands[1].finish(1); + assert!(prune(&mut queue, 0).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 2, 3]); + commands[0].finish(1); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32), (2, 1)]); + assert_eq!(sequences(queue.iter()), [3u64]); + } + + #[test] + fn a_moved_failure_count_scans_the_whole_queue() { + let (mut queue, commands) = queue(5); + commands[0].finish(1); + assert_eq!(prune(&mut queue, 0), [(1u64, 1i32)]); + commands[2].finish(ECANCELED.to_errno()); + commands[4].finish(1); + assert_eq!(prune(&mut queue, 1), [(3u64, ECANCELED.to_errno()), (5, 1)]); + assert_eq!(sequences(queue.iter()), [2u64, 4]); + commands[1].finish(1); + commands[3].finish(1); + assert_eq!(prune(&mut queue, 1), [(2u64, 1i32), (4, 1)]); + assert_eq!(queue.len(), 0); + } + + #[test] + fn a_failure_behind_an_unfinished_command_leaves_once_counted() { + let (mut queue, commands) = queue(3); + commands[1].finish(EIO.to_errno()); + // Not counted yet: like a success, it waits for the front. + assert!(prune(&mut queue, 0).is_empty()); + assert_eq!(prune(&mut queue, 1), [(2u64, EIO.to_errno())]); + // Only the prune that saw the count move looks behind the front. + commands[2].finish(1); + assert!(prune(&mut queue, 1).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 3]); + } + + #[test] + fn a_failure_being_signalled_keeps_prunes_full_until_it_has_finished() { + let (mut queue, commands) = queue(4); + // Started, but its error is not visible yet. + assert!(prune_counts(&mut queue, 1, 0).is_empty()); + // Visible but not finished: the prune must still look behind the front for it. + commands[1].finish(EIO.to_errno()); + assert_eq!(prune_counts(&mut queue, 1, 0), [(2u64, EIO.to_errno())]); + // Its finish is scanned for once more, then prunes go back to the front. + commands[2].finish(1); + assert_eq!(prune_counts(&mut queue, 1, 1), [(3u64, 1i32)]); + commands[3].finish(1); + assert!(prune_counts(&mut queue, 1, 1).is_empty()); + assert_eq!(sequences(queue.iter()), [1u64, 4]); + } + + #[test] + fn a_prefix_covers_the_oldest_held_commands() { + let (mut queue, commands) = queue(4); + commands[0].finish(1); + prune(&mut queue, 0); + assert!(sequences(queue.prefix(None)).is_empty()); + assert!(sequences(queue.prefix(Some(1))).is_empty()); + assert_eq!(sequences(queue.prefix(Some(3))), [2u64, 3]); + assert_eq!(sequences(queue.prefix(Some(9))), [2u64, 3, 4]); + } + + #[test] + fn a_deep_steady_queue_reads_only_what_leaves_and_never_grows() { + // Commands queued deep, then one finishing for each new one, as under vkd3d-proton. + // A little over half of the room is held: moving down only once as many have left + // as are held would double it. + const DEPTH: u64 = 1100; + let (mut queue, mut commands) = queue(DEPTH); + let capacity = queue.entries.capacity(); + READS.store(0, Ordering::Relaxed); + for sequence in DEPTH + 1..=10 * DEPTH { + commands[(sequence - DEPTH - 1) as usize].finish(1); + assert_eq!(prune(&mut queue, 0), [(sequence - DEPTH, 1i32)]); + let command = push(&mut queue, sequence); + commands.push(command, GFP_KERNEL).unwrap(); + assert_eq!(queue.len(), DEPTH as usize); + assert_eq!(queue.entries.capacity(), capacity); + } + // Each prune read the one that left and the unfinished one behind it. + assert_eq!(READS.load(Ordering::Relaxed), 2 * 9 * DEPTH as usize); + } +} diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index de7b98bdbc553a..5c062f8a2c8e86 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -4,7 +4,7 @@ use crate::debug::*; use crate::gem; -use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use kernel::{new_mutex, prelude::*, str::BStr, sync::Mutex, task::Pid}; const DEBUG_CLASS: DebugFlags = DebugFlags::Errors; @@ -33,6 +33,10 @@ pub(crate) struct VmStatus { /// Further restarts that may find this VM guilty and still be charged to it /// ([`Self::charge_restart`]), or [`UNCHARGED`] before the first. restarts_left: AtomicU32, + /// Commands whose public fence is failing ([`Self::signal_failure`]): counted before + /// its error is set, and again once it has signalled. + failures_started: AtomicU64, + failures_finished: AtomicU64, /// The process that created the VM, named in the failure report. tgid: Pid, comm: [u8; 16], @@ -51,6 +55,14 @@ struct Mirror { // only accessed atomically through this pointer while the mutex is held. unsafe impl Send for Mirror {} +/// [`VmStatus::signal_failure`] counts: every failure in `finished` has signalled its error, +/// and those in `started` but not `finished` may be anywhere between. +#[derive(Clone, Copy)] +pub(crate) struct Failures { + pub(crate) started: u64, + pub(crate) finished: u64, +} + impl VmStatus { /// Called from the creating client's ioctl: the VM records who it belongs to. pub(crate) fn new() -> impl PinInit { @@ -69,6 +81,8 @@ impl VmStatus { warned: AtomicBool::new(false), recovery_guilty: AtomicBool::new(false), restarts_left: AtomicU32::new(UNCHARGED), + failures_started: AtomicU64::new(0), + failures_finished: AtomicU64::new(0), tgid, comm, mirror <- new_mutex!(None, "Asahi VM status mirror"), @@ -89,6 +103,24 @@ impl VmStatus { (BStr::from_bytes(&self.comm[..len]), self.tgid) } + /// Fails a command's public fence: `signal` sets its error and signals it. The failure + /// counts as started before anyone can see the error and as finished after the signal, so + /// a frontier prune that reads the counts in between can tell that one is in flight. + pub(crate) fn signal_failure(&self, signal: impl FnOnce()) { + // Relaxed: the fence's signal, a release, publishes it together with the error. + self.failures_started.fetch_add(1, Ordering::Relaxed); + signal(); + // Release: whoever sees this count also sees the signalled error. + self.failures_finished.fetch_add(1, Ordering::Release); + } + + /// This VM's failure counts, `finished` read first so that `started` covers it. + pub(crate) fn failures(&self) -> Failures { + let finished = self.failures_finished.load(Ordering::Acquire); + let started = self.failures_started.load(Ordering::Acquire); + Failures { started, finished } + } + pub(crate) fn note_recovery_guilty(&self) { self.recovery_guilty.store(true, Ordering::Release); } diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 53204a179edd66..786064c1209fe5 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -155,7 +155,7 @@ def fixture(): fn report_failure(&self, _: Error) {} } pub struct Output; -impl Output { fn finish(&self, _: Result<[u64; 4]>) {} } +impl Output { fn finish(&self, _: Result<[u64; 4]>, _: &Status) {} } pub struct Sources; impl Sources { fn release(&self) {} } From 3a74adfce80e91f449a44bf6add894781db23ee6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:11:45 +1100 Subject: [PATCH 0443/1514] media: apple: ave: require a whole picture behind the OUTPUT address ave_sess_input() adds the OUTPUT plane's data_offset to its DMA address and, when the payload does not describe a packed-stride frame, hands that address to the encoder after checking only its alignment. vb2 accepts any data_offset below bytesused, so the address can sit anywhere in the buffer, up to its last 64 bytes, while the encoder still reads a whole picture from it: p->ch luma lines, and chroma from p->height lines on. Refuse the frame unless a whole picture, the size S_FMT reports (stride * coded height * 3 / 2), fits in the plane after data_offset. Use the same size for the in-place repack check, which so far allowed only the visible lines although the encoder reads the coded height, and for the per-slot copy. A client that queues frames at offset 0, or with room for a picture after its offset, sees no change. tests/run-input.py runs the production ave_sess_input() against a DMA boundary whose addresses are the host memory behind them, sweeps every data_offset vb2 accepts for MMAP and imported buffers, and reads the picture at each accepted address as the encoder does, under ASan. Fixes: b2fd1d5d90d6 ("media: apple: ave: two streams, survive system sleep, copy odd strides") Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-sess.c | 15 +- drivers/media/platform/apple/ave/tests/README | 13 ++ .../platform/apple/ave/tests/input-boundary.h | 72 +++++++ .../platform/apple/ave/tests/input-session.h | 10 + .../platform/apple/ave/tests/input-test.c | 196 ++++++++++++++++++ .../platform/apple/ave/tests/run-input.py | 43 ++++ tools/asahi/run-host-tests.py | 1 + 7 files changed, 348 insertions(+), 2 deletions(-) create mode 100644 drivers/media/platform/apple/ave/tests/input-boundary.h create mode 100644 drivers/media/platform/apple/ave/tests/input-session.h create mode 100644 drivers/media/platform/apple/ave/tests/input-test.c create mode 100644 drivers/media/platform/apple/ave/tests/run-input.py diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index ddf95b2b129699..901fc784581b77 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -764,6 +764,10 @@ static void ave_note_copy(struct ave_ctx *ctx, u32 stride, const char *how) * buffer with their own, smaller line size instead, which shows in the * payload size; such frames are copied to a per-slot buffer in the * encoder's layout. + * + * The encoder reads a whole coded frame (p->ch lines, the size S_FMT + * reports) from the address it is given, so every address handed out here + * has that much memory behind it. */ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffer *src, dma_addr_t *input) @@ -775,6 +779,7 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe u32 used = vb2_get_plane_payload(vb, 0) - min(off, vb2_get_plane_payload(vb, 0)); u32 crows = DIV_ROUND_UP(p->height, 2), rows = p->height + crows; u32 width = ALIGN(p->width, 2) * p->sample_bytes, stride; + size_t frame = (size_t)p->stride * p->ch * 3 / 2; struct ave_buf *b = &sess->slot[slot].bounce; const u8 *from; u8 *to; @@ -782,6 +787,12 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe *input = vb2_dma_contig_plane_dma_addr(vb, 0) + off; if (!used || used >= p->stride * rows || used % rows || used / rows < width) { + if ((size_t)off + frame > vb2_plane_size(vb, 0)) { + dev_err(ctx->ave->dev, + "OUTPUT plane has no %zu byte frame after offset %u\n", + frame, off); + return -EINVAL; + } if (IS_ALIGNED(*input, 64)) return 0; dev_err(ctx->ave->dev, "OUTPUT plane at %pad is not 64-byte aligned\n", input); @@ -804,7 +815,7 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe * with other users and get a copy instead. */ if (vb->memory == VB2_MEMORY_MMAP && - vb2_plane_size(vb, 0) >= off + (size_t)p->stride * rows) { + vb2_plane_size(vb, 0) >= (size_t)off + frame) { to = (u8 *)from; for (u32 y = rows; y-- > 0;) memmove(to + y * p->stride, from + y * stride, width); @@ -812,7 +823,7 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe return 0; } - ret = ave_alloc(ctx->ave, b, p->stride * rows, 0); + ret = ave_alloc(ctx->ave, b, frame, 0); if (ret) { dev_err(ctx->ave->dev, "no room to copy %u byte stride input\n", stride); return ret; diff --git a/drivers/media/platform/apple/ave/tests/README b/drivers/media/platform/apple/ave/tests/README index c084c14ff414f2..b6f47dc154b88f 100644 --- a/drivers/media/platform/apple/ave/tests/README +++ b/drivers/media/platform/apple/ave/tests/README @@ -58,6 +58,19 @@ expiry boundaries, with staggered attempts and across jiffies wrap. Run with ../.kunitconfig using tools/testing/kunit/kunit.py. The existing tools/asahi/ave-pm-tests.py also checks the #651 sleep rollback contract. +OUTPUT input address +-------------------- + +Run python3 run-input.py for ASan/UBSan checks of the production +ave_sess_input(). The fake DMA boundary makes each DART address the host +address of the memory behind it, and the test reads the picture there as the +encoder does (p->ch luma lines, then p->ch / 2 chroma lines after p->height +luma lines). It sweeps every 64-byte data_offset vb2 accepts, for MMAP and +imported buffers, and checks that each accepted address has the whole read +inside the OUTPUT buffer or the slot's bounce copy, that a whole picture +after a non-zero data_offset is still used in place, and that tightly packed +lines are moved to the encoder's stride unchanged. + MCTF streaming tool ------------------- diff --git a/drivers/media/platform/apple/ave/tests/input-boundary.h b/drivers/media/platform/apple/ave/tests/input-boundary.h new file mode 100644 index 00000000000000..b4a62754b88469 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-boundary.h @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * vb2 and DMA boundary for the production ave_sess_input(). A DMA address + * is the host address of the memory behind it, so the simulated encoder + * read below touches exactly what the hardware would and AddressSanitizer + * reports a read past the buffer. + */ +#define PAGE_SIZE 4096UL +#define PAGE_ALIGN(x) ALIGN((size_t)(x), PAGE_SIZE) +#define min(x, y) ((x) < (y) ? (x) : (y)) +#define SZ_16K_ALIGNED 0x4000UL + +#define VB2_MAX_PLANES 8 + +enum vb2_memory { VB2_MEMORY_MMAP = 1, VB2_MEMORY_DMABUF = 4 }; + +struct vb2_plane { + void *mem; + unsigned int bytesused, length, data_offset; +}; + +struct vb2_buffer { + enum vb2_memory memory; + struct vb2_plane planes[VB2_MAX_PLANES]; +}; + +struct vb2_v4l2_buffer { struct vb2_buffer vb2_buf; }; +struct ave_vb2_mem; + +static unsigned long vb2_get_plane_payload(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].bytesused; +} + +static unsigned long vb2_plane_size(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].length; +} + +static void *vb2_plane_vaddr(struct vb2_buffer *vb, unsigned int p) +{ + return vb->planes[p].mem; +} + +static dma_addr_t vb2_dma_contig_plane_dma_addr(struct vb2_buffer *vb, unsigned int p) +{ + return (uintptr_t)vb->planes[p].mem; +} + +struct device { int unused; }; + +static unsigned int dma_allocs; + +static void *dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma, int gfp, + unsigned long attrs) +{ + void *p = NULL; + + assert(!posix_memalign(&p, SZ_16K_ALIGNED, size)); + memset(p, 0, size); + *dma = (uintptr_t)p; + dma_allocs++; + return p; +} + +static void dma_free_attrs(struct device *dev, size_t size, void *cpu, dma_addr_t dma, + unsigned long attrs) +{ + assert((uintptr_t)cpu == dma); + free(cpu); + dma_allocs--; +} diff --git a/drivers/media/platform/apple/ave/tests/input-session.h b/drivers/media/platform/apple/ave/tests/input-session.h new file mode 100644 index 00000000000000..f5f53b0a7b3291 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-session.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* Only the session state ave_sess_input() reads. */ +struct ave_session { + struct ave_params p; + struct ave_slot slot[1]; + bool copy_noted; +}; + +struct ave_dev { struct device *dev; }; +struct ave_ctx { struct ave_dev *ave; struct ave_session *sess; }; diff --git a/drivers/media/platform/apple/ave/tests/input-test.c b/drivers/media/platform/apple/ave/tests/input-test.c new file mode 100644 index 00000000000000..23f50758b9a1bd --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/input-test.c @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * ave_sess_input() hands the encoder one DART address per frame. The + * encoder reads p->ch luma lines from it and p->ch / 2 chroma lines from + * p->height lines further on (ave_build_process()). Every accepted address + * must have all of that inside the OUTPUT buffer or the slot's bounce copy, + * for any data_offset and payload vb2 lets through + * (data_offset < bytesused <= length). + */ +static struct device dev; +static struct ave_dev ave = { .dev = &dev }; +static struct ave_session sess; +static struct ave_ctx ctx = { .ave = &ave, .sess = &sess }; +/* Not static: the simulated encoder reads must not be optimised away. */ +u8 sink; + +static void geometry(u32 width, u32 height) +{ + memset(&sess, 0, sizeof(sess)); + sess.p.width = width; + sess.p.height = height; + sess.p.cw = ALIGN(width, 16); + sess.p.ch = ALIGN(height, 16); + sess.p.stride = ALIGN(width, 64); + sess.p.sample_bytes = 1; +} + +static size_t sizeimage(void) +{ + return (size_t)sess.p.stride * sess.p.ch * 3 / 2; +} + +static size_t encoder_extent(void) +{ + const struct ave_params *p = &sess.p; + + return max((size_t)p->stride * p->ch, + (size_t)p->stride * (p->height + p->ch / 2)); +} + +static bool inside(dma_addr_t a, size_t n, const void *base, size_t len) +{ + uintptr_t b = (uintptr_t)base; + + return base && a >= b && a - b <= len && n <= len - (a - b); +} + +/* What the encoder does with the address: read the whole picture. */ +static void encoder_read(dma_addr_t input) +{ + const struct ave_params *p = &sess.p; + const u8 *y = (const u8 *)(uintptr_t)input; + const u8 *uv = y + (size_t)p->stride * p->height; + u8 sum = 0; + + for (size_t i = 0; i < (size_t)p->stride * p->ch; i++) + sum += y[i]; + for (size_t i = 0; i < (size_t)p->stride * (p->ch / 2); i++) + sum += uv[i]; + sink = sum; +} + +static struct vb2_v4l2_buffer *buffer(enum vb2_memory memory, size_t length) +{ + struct vb2_v4l2_buffer *b = calloc(1, sizeof(*b)); + + assert(b); + b->vb2_buf.memory = memory; + b->vb2_buf.planes[0].length = length; + /* Exactly @length bytes, so AddressSanitizer sees a read past the end. */ + assert(!posix_memalign(&b->vb2_buf.planes[0].mem, SZ_16K_ALIGNED, length)); + memset(b->vb2_buf.planes[0].mem, 0x5a, length); + return b; +} + +static void put(struct vb2_v4l2_buffer *b) +{ + free(b->vb2_buf.planes[0].mem); + free(b); +} + +static void release_bounce(void) +{ + ave_free(&ave, &sess.slot[0].bounce); +} + +/* + * Feed one buffer through the production code; if it is accepted, check + * the address and read the picture there as the encoder would. + */ +static int submit(struct vb2_v4l2_buffer *b, unsigned int off, unsigned int used) +{ + struct vb2_plane *pl = &b->vb2_buf.planes[0]; + const struct ave_buf *bounce = &sess.slot[0].bounce; + dma_addr_t input = 0; + int ret; + + assert(off < used && used <= pl->length); + pl->data_offset = off; + pl->bytesused = used; + ret = ave_sess_input(&ctx, 0, b, &input); + if (ret) + return ret; + if (!inside(input, encoder_extent(), pl->mem, pl->length) && + !inside(input, encoder_extent(), bounce->cpu, bounce->size)) { + fprintf(stderr, + "FAIL: data_offset %u payload %u (%s, %u byte buffer): encoder input %#llx reads %zu bytes outside the buffer\n", + off, used, b->vb2_buf.memory == VB2_MEMORY_MMAP ? "MMAP" : "DMABUF", + pl->length, (unsigned long long)input, encoder_extent()); + exit(1); + } + encoder_read(input); + return 0; +} + +/* Every 64-byte data_offset vb2 accepts, for both payload extremes. */ +static void sweep(enum vb2_memory memory, size_t length) +{ + struct vb2_v4l2_buffer *b = buffer(memory, length); + unsigned int accepted = 0, refused = 0; + + for (unsigned int k = 0; k < 2; k++) { + unsigned int used = k ? length : sizeimage(); + + for (unsigned int off = 0; off < used; off += 64) { + if (submit(b, off, used)) + refused++; + else + accepted++; + release_bounce(); + } + } + /* Offset 0 with the S_FMT payload always works. */ + assert(accepted); + assert(refused); + put(b); +} + +/* A whole picture after a non-zero data_offset still goes straight in. */ +static void offset_with_room(enum vb2_memory memory) +{ + unsigned int off = 4 * SZ_16K_ALIGNED; + struct vb2_v4l2_buffer *b = buffer(memory, off + sizeimage()); + dma_addr_t input; + + b->vb2_buf.planes[0].data_offset = off; + b->vb2_buf.planes[0].bytesused = off + sizeimage(); + assert(!ave_sess_input(&ctx, 0, b, &input)); + assert(input == (uintptr_t)b->vb2_buf.planes[0].mem + off); + assert(!sess.slot[0].bounce.cpu); + put(b); +} + +/* Tightly packed lines are moved to the encoder's stride, unchanged. */ +static void packed(enum vb2_memory memory, unsigned int off, bool in_place) +{ + const struct ave_params *p = &sess.p; + u32 rows = p->height + DIV_ROUND_UP(p->height, 2), line = p->width; + struct vb2_v4l2_buffer *b = buffer(memory, sizeimage()); + u8 *from = (u8 *)b->vb2_buf.planes[0].mem + off; + const u8 *to; + + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + from[y * line + x] = (u8)(y * 7 + x); + assert(!submit(b, off, off + rows * line)); + to = in_place ? from : sess.slot[0].bounce.cpu; + assert(to && (bool)sess.slot[0].bounce.cpu == !in_place); + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + assert(to[(size_t)y * p->stride + x] == (u8)(y * 7 + x)); + release_bounce(); + put(b); +} + +int main(void) +{ + static const u32 sizes[][2] = { { 128, 64 }, { 100, 60 }, { 320, 180 } }; + + for (unsigned int i = 0; i < ARRAY_SIZE(sizes); i++) { + geometry(sizes[i][0], sizes[i][1]); + sweep(VB2_MEMORY_MMAP, sizeimage()); + sweep(VB2_MEMORY_DMABUF, sizeimage()); + sweep(VB2_MEMORY_MMAP, sizeimage() + 3 * 64); + offset_with_room(VB2_MEMORY_MMAP); + offset_with_room(VB2_MEMORY_DMABUF); + } + geometry(100, 60); + packed(VB2_MEMORY_MMAP, 0, true); + packed(VB2_MEMORY_MMAP, 64, false); + packed(VB2_MEMORY_DMABUF, 0, false); + packed(VB2_MEMORY_DMABUF, 128, false); + assert(!dma_allocs && jiffies); + puts("ok: OUTPUT data_offset sweep (MMAP, DMABUF), offset with room, packed-stride repack"); + return 0; +} diff --git a/drivers/media/platform/apple/ave/tests/run-input.py b/drivers/media/platform/apple/ave/tests/run-input.py new file mode 100644 index 00000000000000..61db7ff3425cf9 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/run-input.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Check the production OUTPUT picture address against the buffer behind it.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +# python3 -I leaves the script directory off sys.path; run.py sits next to this file. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from run import declaration, function, source + + +def main(): + here = Path(__file__).resolve().parent + src = here.parent + header = (src / 'ave.h').read_text() + code = (here / 'shim.h').read_text() + code += (here / 'input-boundary.h').read_text() + for name in ('ave_codec', 'ave_buf', 'ave_params', 'ave_slot'): + code += declaration(header, name) + code += (here / 'input-session.h').read_text() + code += function((src / 'ave-fw.c').read_text(), 'ave_free') + code += function((src / 'ave-fw.c').read_text(), 'ave_alloc_padded') + code += function((src / 'ave-fw.c').read_text(), 'ave_alloc') + sess = (src / 'ave-sess.c').read_text() + code += function(sess, 'ave_note_copy') + code += function(sess, 'ave_sess_input') + code += (here / 'input-test.c').read_text() + with tempfile.TemporaryDirectory(prefix='ave-input-') as tmp: + path = Path(tmp) + (path / 'test.c').write_text(code) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O1', '-g', + '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', + '-Wno-unused-function', '-fsanitize=address,undefined', + '-fno-omit-frame-pointer', str(path / 'test.c'), + '-o', str(path / 'test')], check=True) + subprocess.run([str(path / 'test')], check=True) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..a7a46f435bdefb 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -336,6 +336,7 @@ def mutations(flag, names, base, expect=KILL): # recovery code built against host boundaries. ('ave-host', AVE_TESTS, ['python3', '-I', '-B', 'run.py', '--build', '{out}']), ('ave-recovery', AVE_TESTS, ['python3', '-I', '-B', 'run-recovery.py']), + ('ave-input', AVE_TESTS, ['python3', '-I', '-B', 'run-input.py']), ] # tools/testing/selftests/drivers/apple: the host-runnable harnesses build the From ec2ded20afba4353cc30ad47e5db31b5c63da481 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:15:14 +1100 Subject: [PATCH 0444/1514] media: apple: ave: validate each firmware ring descriptor once ave_ipc_parse_channels() checks every channel descriptor in the shared channel area, then reads the direction, slot count and ring address of each descriptor again to hand the host-to-firmware slots to the host. The second pass trusts those fresh values without checking them and ignores the return value of ave_fw_offset(), so a descriptor that changes between the passes makes the hand-over use an unchecked slot count and an unset ring offset. The name is also read twice: memchr() checks it for a terminator, then strcmp() and strscpy() read it again. Copy each descriptor into a local buffer once and parse only that copy. Record the slot count and offset of every validated host-to-firmware ring and do the hand-over from the recorded values, so the descriptors are not read again and ave_fw_offset() is only called where its result is checked. The writes and their order are unchanged for firmware that leaves its descriptors alone. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-ipc.c | 60 ++++++++++++---------- drivers/media/platform/apple/ave/ave.h | 2 + 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 518604147cc17d..6e18f29799d361 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -100,22 +100,34 @@ static bool ave_rings_overlap(const struct ave_ring *a, int ave_ipc_parse_channels(struct ave_dev *ave) { + const struct ave_fw_transport *t = ave->layout->abi->transport; + /* Validated host-to-firmware rings by descriptor; zero slots: none. */ + struct { + u32 slots; + u32 offset; + } h2t[AVE_IPC_MAX_CHANNELS] = {}; bool found[AVE_RINGS] = {}; + if (t->descriptors > ARRAY_SIZE(h2t)) + return -EPROTO; memset(ave->ring, 0, sizeof(ave->ring)); - for (unsigned int i = 0; i < ave->layout->abi->transport->descriptors; - i++) { - u8 *desc = ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + - i * AVE_CHAN_DESC_STRIDE; - u32 dir = get_unaligned_le32(desc + AVE_CHAN_DESC_DIR); - u32 doorbell = get_unaligned_le32(desc + AVE_CHAN_DESC_IRQ); - u32 slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); - u64 addr = get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR); + for (unsigned int i = 0; i < t->descriptors; i++) { + /* + * The firmware may write the channel area at any time: take one + * copy of the descriptor and use only that copy from here on. + */ + u8 desc[AVE_CHAN_DESC_ADDR + sizeof(u64)]; + u32 dir, doorbell, slots, offset; struct ave_ring *r; + u64 addr; int id; - u32 offset; - const struct ave_fw_transport *t = ave->layout->abi->transport; + memcpy(desc, ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + + i * AVE_CHAN_DESC_STRIDE, sizeof(desc)); + dir = get_unaligned_le32(desc + AVE_CHAN_DESC_DIR); + doorbell = get_unaligned_le32(desc + AVE_CHAN_DESC_IRQ); + slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); + addr = get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR); if (!memchr(desc, 0, AVE_CHAN_DESC_NAME_LEN) || slots > ave->channel_bytes / AVE_RING_SLOT_BYTES || @@ -128,7 +140,11 @@ int ave_ipc_parse_channels(struct ave_dev *ave) offset + slots * AVE_RING_SLOT_BYTES > AVE_IPC_CHANNEL_OFF + ave->channel_bytes) return -EPROTO; - id = ave_ring_id(desc); + if (!dir) { + h2t[i].slots = slots; + h2t[i].offset = offset; + } + id = ave_ring_id((const char *)desc); /* Channels the host has no use for are left alone. */ if (id == AVE_RING_SMALLOC && !t->smalloc_bytes) id = -ENOENT; @@ -148,7 +164,7 @@ int ave_ipc_parse_channels(struct ave_dev *ave) found[id] = true; r = &ave->ring[id]; - strscpy(r->name, desc, sizeof(r->name)); + strscpy(r->name, (const char *)desc, sizeof(r->name)); /* * Host-to-firmware rings start empty, firmware-to-host rings * full. Bit 0 of a slot's first word says whose turn it is: @@ -172,22 +188,12 @@ int ave_ipc_parse_channels(struct ave_dev *ave) /* * Hand every slot of every host-to-firmware ring to the host, the ones * the host never uses too: ownership is bit 0, and a slot left at zero - * reads to the firmware as a message posted to it. + * reads to the firmware as a message posted to it. Only the values + * validated above are used; the descriptors are not read again. */ - for (unsigned int i = 0; i < ave->layout->abi->transport->descriptors; - i++) { - u8 *desc = ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + - i * AVE_CHAN_DESC_STRIDE; - u32 slots = get_unaligned_le32(desc + AVE_CHAN_DESC_SLOTS); - u32 offset; - - if (get_unaligned_le32(desc + AVE_CHAN_DESC_DIR)) - continue; - /* Checked above. */ - ave_fw_offset(ave, get_unaligned_le64(desc + AVE_CHAN_DESC_ADDR), - (size_t)slots * AVE_RING_SLOT_BYTES, &offset); - for (unsigned int n = 0; n < slots; n++) { - __le64 *slot = ave->ipc.cpu + offset + + for (unsigned int i = 0; i < t->descriptors; i++) { + for (unsigned int n = 0; n < h2t[i].slots; n++) { + __le64 *slot = ave->ipc.cpu + h2t[i].offset + n * AVE_RING_SLOT_BYTES; slot[0] = cpu_to_le64(1); diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index e86c3735086610..c8f6cf68adf7e7 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -54,6 +54,8 @@ struct ave_mctf_layout; #define AVE_IPC_BYTES (20 * SZ_1M) #define AVE_IPC_CHANNEL_OFF 0x4000 #define AVE_IPC_HANDSHAKE_OFF 0x24000 +/* Most channel descriptors any firmware publishes (the 6070 one: 7). */ +#define AVE_IPC_MAX_CHANNELS 8 #define AVE_IPC_SHARED_OFF 0x28000 #define AVE_IPC_SHARED_BYTES SZ_64K #define AVE_IPC_CMD_OFF 0x40000 From 397d2c81fa19ef6f13c8832575d1c69ca719e65d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:15:15 +1100 Subject: [PATCH 0445/1514] media: apple: ave: tests: check that channel descriptors are read once Add run-ipc.py, a host harness that builds the production ave_ipc_parse_channels() with the 6070 transport against a fake shared memory boundary. Every read of the channel area goes through a fake firmware that can rewrite the ring size, ring address or name of a descriptor right after the host has read it, or assert that no descriptor byte is fetched twice. Each case must yield the rings of the well-behaved firmware and change nothing in the IPC window but the hand-over of the validated host-to-firmware slots. Run it from tools/asahi/run-host-tests.py next to the other AVE harnesses and describe it in the README. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/tests/README | 12 ++ .../platform/apple/ave/tests/ipc-boundary.h | 134 ++++++++++++++++ .../media/platform/apple/ave/tests/ipc-test.c | 151 ++++++++++++++++++ .../media/platform/apple/ave/tests/run-ipc.py | 64 ++++++++ tools/asahi/run-host-tests.py | 1 + 5 files changed, 362 insertions(+) create mode 100644 drivers/media/platform/apple/ave/tests/ipc-boundary.h create mode 100644 drivers/media/platform/apple/ave/tests/ipc-test.c create mode 100644 drivers/media/platform/apple/ave/tests/run-ipc.py diff --git a/drivers/media/platform/apple/ave/tests/README b/drivers/media/platform/apple/ave/tests/README index b6f47dc154b88f..9d0ba50c2373c1 100644 --- a/drivers/media/platform/apple/ave/tests/README +++ b/drivers/media/platform/apple/ave/tests/README @@ -71,6 +71,18 @@ inside the OUTPUT buffer or the slot's bounce copy, that a whole picture after a non-zero data_offset is still used in place, and that tightly packed lines are moved to the encoder's stride unchanged. +Channel descriptor checks +------------------------- + +Run python3 run-ipc.py for ASan/UBSan checks of the production channel parser +(ave_ipc_parse_channels with the 6070 transport). ipc-boundary.h routes every +read of the channel area through a fake firmware that rewrites a descriptor +field (ring size, ring address or name) right after the host has read it, and +can assert that no descriptor byte is fetched twice. Each case must parse the +rings a well-behaved firmware publishes and hand over exactly the validated +host-to-firmware slots; the rest of the IPC window must stay untouched. +An argument (slots, addr, name or once) runs a single case. + MCTF streaming tool ------------------- diff --git a/drivers/media/platform/apple/ave/tests/ipc-boundary.h b/drivers/media/platform/apple/ave/tests/ipc-boundary.h new file mode 100644 index 00000000000000..c5b1b1c18eb948 --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/ipc-boundary.h @@ -0,0 +1,134 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * Fake device and shared-memory boundary for the production channel parser. + * Every read the parser makes is routed through fw_read(), which plays a + * firmware that rewrites a descriptor field as soon as the host has read it. + */ +typedef u64 __le64; +#define cpu_to_le64(x) ((u64)(x)) +#define dma_wmb() ((void)0) +#ifndef AVE_IPC_MAX_CHANNELS +#define AVE_IPC_MAX_CHANNELS 8 +#endif + +struct ave_dev { + const struct ave_fw_layout *layout; + struct ave_buf ipc; + u64 ipc_fw_base; + u32 channel_bytes; + struct ave_ring ring[AVE_RINGS]; +}; + +enum { + FW_SLOTS = BIT(0), /* grow the ring past the IPC window */ + FW_ADDR = BIT(1), /* move the ring to the start of the window */ + FW_NAME = BIT(2), /* rename the channel */ + FW_ONCE = BIT(3), /* assert no descriptor byte is fetched twice */ +}; + +static struct ave_dev *fw_ave; +static unsigned int fw_mode, fw_descriptors; +static unsigned char fw_fetched[AVE_IPC_MAX_CHANNELS * AVE_CHAN_DESC_STRIDE]; + +static bool fw_overlaps(long a, size_t len, long b, size_t blen) +{ + return a < b + (long)blen && b < a + (long)len; +} + +static void fw_read(const void *p, size_t len) +{ + const u8 *table = (const u8 *)fw_ave->ipc.cpu + AVE_IPC_CHANNEL_OFF; + size_t bytes = fw_descriptors * AVE_CHAN_DESC_STRIDE; + size_t start; + + if ((const u8 *)p < table || (const u8 *)p >= table + bytes) + return; + start = (const u8 *)p - table; + assert(start + len <= bytes); + for (size_t b = start; b < start + len; b++) { + if (fw_mode & FW_ONCE) + assert(!fw_fetched[b]); + fw_fetched[b]++; + } + for (unsigned int i = start / AVE_CHAN_DESC_STRIDE; + i * AVE_CHAN_DESC_STRIDE < start + len; i++) { + long at = (long)start - (long)(i * AVE_CHAN_DESC_STRIDE); + u8 *desc = (u8 *)table + i * AVE_CHAN_DESC_STRIDE; + + if (fw_mode & FW_SLOTS && + fw_overlaps(at, len, AVE_CHAN_DESC_SLOTS, 4)) + put_unaligned_le32(0x100000, desc + AVE_CHAN_DESC_SLOTS); + if (fw_mode & FW_ADDR && + fw_overlaps(at, len, AVE_CHAN_DESC_ADDR, 8)) + put_unaligned_le64(fw_ave->ipc_fw_base, + desc + AVE_CHAN_DESC_ADDR); + if (fw_mode & FW_NAME && + fw_overlaps(at, len, 0, AVE_CHAN_DESC_NAME_LEN)) + (memcpy)(desc, "X", 2); + } +} + +static inline u32 fw_le32(const void *p) +{ + u32 v = get_unaligned_le32(p); + + fw_read(p, 4); + return v; +} + +static inline u64 fw_le64(const void *p) +{ + u64 v = get_unaligned_le64(p); + + fw_read(p, 8); + return v; +} + +static void *fw_memcpy(void *d, const void *s, size_t n) +{ + (memcpy)(d, s, n); + fw_read(s, n); + return d; +} + +static void *fw_memchr(const void *s, int c, size_t n) +{ + void *r = (memchr)(s, c, n); + + fw_read(s, r ? (size_t)((const u8 *)r - (const u8 *)s) + 1 : n); + return r; +} + +static int fw_strcmp(const char *a, const char *b) +{ + size_t n = 0; + int r; + + while (a[n] && a[n] == b[n]) + n++; + r = (unsigned char)a[n] - (unsigned char)b[n]; + fw_read(a, n + 1); + fw_read(b, n + 1); + return r; +} + +static long fw_strscpy(char *d, const char *s, size_t n) +{ + size_t len = strnlen(s, n); + + fw_read(s, len < n ? len + 1 : n); + if (len == n) { + (memcpy)(d, s, n - 1); + d[n - 1] = 0; + return -E2BIG; + } + (memcpy)(d, s, len + 1); + return len; +} + +#define get_unaligned_le32(p) fw_le32(p) +#define get_unaligned_le64(p) fw_le64(p) +#define memcpy(d, s, n) fw_memcpy(d, s, n) +#define memchr(s, c, n) fw_memchr(s, c, n) +#define strcmp(a, b) fw_strcmp(a, b) +#define strscpy(d, s, n) fw_strscpy(d, s, n) diff --git a/drivers/media/platform/apple/ave/tests/ipc-test.c b/drivers/media/platform/apple/ave/tests/ipc-test.c new file mode 100644 index 00000000000000..38f16061ad155b --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/ipc-test.c @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-2.0-only +#undef get_unaligned_le32 +#undef get_unaligned_le64 +#undef memcpy +#undef memchr +#undef strcmp +#undef strscpy + +/* The channels the 6070 firmware publishes (as in the KUnit suite). */ +static const struct { + const char *name; + u32 dir, doorbell, slots, offset; +} channels[] = { + { "TERMINAL", 2, 0, 512, 0x700 }, { "IO", 0, 1, 32, 0x8700 }, + { "DEBUG", 0, 1, 8, 0x8f00 }, { "BUF_H2T", 0, 2, 1, 0x9100 }, + { "BUF_T2H", 1, 3, 1, 0x9140 }, { "SHAREDMALLOC", 1, 3, 8, 0x9180 }, + { "IO_T2H", 1, 3, 32, 0x9380 }, +}; + +static const struct ave_fw_abi abi = { .transport = &ave_transport_6070 }; +static const struct ave_fw_layout layout = { .abi = &abi }; +static struct ave_dev ave; +static u8 *expect; + +static void setup(unsigned int mode) +{ + fw_ave = &ave; + fw_mode = mode; + fw_descriptors = ARRAY_SIZE(channels); + memset(fw_fetched, 0, sizeof(fw_fetched)); + free(ave.ipc.cpu); + memset(&ave, 0, sizeof(ave)); + ave.layout = &layout; + ave.ipc.size = ave_transport_6070.ipc_bytes; + /* Exactly the window: ASan reports any write past its end. */ + ave.ipc.cpu = malloc(ave.ipc.size); + assert(ave.ipc.cpu); + memset(ave.ipc.cpu, 0x5a, ave.ipc.size); + ave.ipc_fw_base = 0x100000000ULL; + ave.channel_bytes = ave_transport_6070.hello[1]; + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) { + u8 *desc = (u8 *)ave.ipc.cpu + AVE_IPC_CHANNEL_OFF + + i * AVE_CHAN_DESC_STRIDE; + + memset(desc, 0, AVE_CHAN_DESC_STRIDE); + memcpy(desc, channels[i].name, strlen(channels[i].name) + 1); + put_unaligned_le32(channels[i].dir, desc + AVE_CHAN_DESC_DIR); + put_unaligned_le32(channels[i].doorbell, desc + AVE_CHAN_DESC_IRQ); + put_unaligned_le32(channels[i].slots, desc + AVE_CHAN_DESC_SLOTS); + put_unaligned_le64(ave.ipc_fw_base + AVE_IPC_CHANNEL_OFF + + channels[i].offset, desc + AVE_CHAN_DESC_ADDR); + } +} + +static void check_ring(unsigned int id, const char *name, u32 mode, + u32 doorbell, u32 slots, u32 offset) +{ + const struct ave_ring *r = &ave.ring[id]; + + assert(!strcmp(r->name, name)); + assert(r->mode == mode && r->doorbell == doorbell); + assert(r->slots == slots && r->offset == AVE_IPC_CHANNEL_OFF + offset); + assert(r->consumer == (mode ? -1 : 0) && r->producer == (mode ? 0 : -1)); +} + +static void check_result(void) +{ + size_t table = AVE_IPC_CHANNEL_OFF; + size_t table_end = table + ARRAY_SIZE(channels) * AVE_CHAN_DESC_STRIDE; + const u8 *ipc = ave.ipc.cpu; + + check_ring(AVE_RING_IO, "IO", 1, 1, 32, 0x8700); + check_ring(AVE_RING_T2H, "IO_T2H", 0, 3, 32, 0x9380); + check_ring(AVE_RING_SMALLOC, "SHAREDMALLOC", 0, 3, 8, 0x9180); + check_ring(AVE_RING_LOG, "TERMINAL", 0, 0, 512, 0x700); + /* + * Outside the descriptors (the firmware's to change) the window holds + * exactly the hand-over of the validated host-to-firmware rings. + */ + for (size_t b = 0; b < ave.ipc.size; b++) { + if (b >= table && b < table_end) + continue; + if (ipc[b] != expect[b]) { + fprintf(stderr, "FAIL: byte %#zx is %#x, want %#x\n", b, + ipc[b], expect[b]); + abort(); + } + } +} + +static void well_behaved(void) +{ + setup(0); + expect = malloc(ave.ipc.size); + assert(expect); + memcpy(expect, ave.ipc.cpu, ave.ipc.size); + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) { + if (channels[i].dir) + continue; + for (unsigned int n = 0; n < channels[i].slots; n++) { + u8 *slot = expect + AVE_IPC_CHANNEL_OFF + + channels[i].offset + n * AVE_RING_SLOT_BYTES; + + put_unaligned_le64(1, slot); + put_unaligned_le64(0, slot + 8); + put_unaligned_le64(0, slot + 16); + } + } + assert(ave_ipc_parse_channels(&ave) == 0); + check_result(); + /* Every descriptor field the parser depends on was read. */ + for (unsigned int i = 0; i < ARRAY_SIZE(channels); i++) + for (unsigned int b = AVE_CHAN_DESC_DIR; + b < AVE_CHAN_DESC_ADDR + 8; b++) + assert(fw_fetched[i * AVE_CHAN_DESC_STRIDE + b]); +} + +/* The firmware rewrites a field right after the host has read it. */ +static const struct { + const char *name, *what; + unsigned int mode; +} cases[] = { + { "slots", "ring size changed after its check", FW_SLOTS }, + { "addr", "ring address changed after its check", FW_ADDR }, + { "name", "channel name changed after its check", FW_NAME }, + { "once", "descriptor bytes fetched more than once", FW_ONCE }, +}; + +int main(int argc, char **argv) +{ + well_behaved(); + for (unsigned int c = 0; c < ARRAY_SIZE(cases); c++) { + int ret; + + if (argc > 1 && strcmp(argv[1], cases[c].name)) + continue; + setup(cases[c].mode); + ret = ave_ipc_parse_channels(&ave); + if (ret) { + fprintf(stderr, "FAIL: %s: parse returned %d\n", + cases[c].what, ret); + abort(); + } + check_result(); + printf("ok: %s\n", cases[c].what); + } + free(ave.ipc.cpu); + free(expect); + puts("ok: channel descriptors read once, hand-over only to validated rings"); + return 0; +} diff --git a/drivers/media/platform/apple/ave/tests/run-ipc.py b/drivers/media/platform/apple/ave/tests/run-ipc.py new file mode 100644 index 00000000000000..9600890c05f7fe --- /dev/null +++ b/drivers/media/platform/apple/ave/tests/run-ipc.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the production AVE channel parser against a firmware that rewrites +the channel descriptors while the host reads them. + +An optional argument (slots, addr, name or once) runs only that case after +the well-behaved one. +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +# python3 -I leaves the script directory off sys.path; run.py sits next to this file. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from run import declaration, function, source + + +def block(text, start): + begin = text.index(start) + return text[begin:text.index('\n};', begin) + 3] + '\n' + + +def main(): + here = Path(__file__).resolve().parent + src = here.parent + header = (src / 'ave.h').read_text() + code = (here / 'shim.h').read_text() + code += source((src / 'ave-regs.h').read_text()) + for name in ('AVE_IPC_CHANNEL_OFF', 'AVE_IPC_MAX_CHANNELS'): + match = re.search(r'^#define ' + name + r'\s+[^\n]+', header, re.M) + if match: + code += match[0] + '\n' + code += block(header, 'enum {\n\tAVE_RING_IO,') + for name in ('ave_codec', 'ave_buf', 'ave_ring', 'ave_image', 'ave_opcode'): + code += declaration(header, name) + code += source((src / 'ave-layout.h').read_text()) + code += (here / 'ipc-boundary.h').read_text() + code += block((src / 'ave-abi.c').read_text(), + 'static const struct ave_fw_transport ave_transport_6070 =') + text = (src / 'ave-ipc.c').read_text() + code += block(text, 'static const struct {\n\tconst char *name;\n\tu32 dir;') + for name in ('ave_fw_offset', 'ave_ring_id', 'ave_rings_overlap', + 'ave_ipc_parse_channels'): + code += function(text, name) + code += (here / 'ipc-test.c').read_text() + with tempfile.TemporaryDirectory(prefix='ave-ipc-') as tmp: + path = Path(tmp) + (path / 'test.c').write_text(code) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-O1', '-g', + '-Wall', '-Wextra', '-Werror', '-Wno-unused-parameter', + '-Wno-unused-function', '-Wno-unused-variable', + '-Wno-pointer-sign', + '-Wno-sign-compare', '-fsanitize=address,undefined', + '-fno-sanitize-recover=all', + '-fno-omit-frame-pointer', str(path / 'test.c'), + '-o', str(path / 'test')], check=True) + subprocess.run([str(path / 'test')] + sys.argv[1:], check=True) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a7a46f435bdefb..326dccb7b85730 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -337,6 +337,7 @@ def mutations(flag, names, base, expect=KILL): ('ave-host', AVE_TESTS, ['python3', '-I', '-B', 'run.py', '--build', '{out}']), ('ave-recovery', AVE_TESTS, ['python3', '-I', '-B', 'run-recovery.py']), ('ave-input', AVE_TESTS, ['python3', '-I', '-B', 'run-input.py']), + ('ave-ipc', AVE_TESTS, ['python3', '-I', '-B', 'run-ipc.py']), ] # tools/testing/selftests/drivers/apple: the host-runnable harnesses build the From a5343b255ee7d0fc55359f666b986eb45855be0e Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 18:27:05 -0300 Subject: [PATCH 0446/1514] selftests/arm64: check that a uffd-wp window's populated neighbours read zero marker_window() checks that one write into a window write-protected before its first touch maps the whole native page at once, and that the neighbours keep their uffd-wp bit. It never read the neighbours, so a populate path that left stale data in their slots would pass. Check that pages 2 and 3 read zero after the first write. The loop after it still expects their WP bit, so it also shows that a read does not clear it. Signed-off-by: Jonathan Goyvaerts --- tools/testing/selftests/arm64/user4k/uffd-wp-init.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/testing/selftests/arm64/user4k/uffd-wp-init.c b/tools/testing/selftests/arm64/user4k/uffd-wp-init.c index 78f43f1c0b9b7c..2246f8425cff92 100644 --- a/tools/testing/selftests/arm64/user4k/uffd-wp-init.c +++ b/tools/testing/selftests/arm64/user4k/uffd-wp-init.c @@ -466,6 +466,8 @@ static void marker_window(size_t ps, size_t native) CHECK(physical(a + i, ps) == start + i); CHECK(((pagemap(a + i, ps) >> 57) & 1) == (i != ps)); } + /* The neighbours the write populated read zero; a read keeps their WP bit. */ + CHECK(!a[2 * ps] && !a[3 * ps]); /* An async WP fault on a populated neighbour only clears its own bit. */ a[0] = 0xa5; for (size_t i = 0; i < native; i += ps) { From fcb27ed757813ea4d386e217a1d5c5895e2501a4 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 22 Nov 2026 16:31:17 -0500 Subject: [PATCH 0447/1514] phy: apple: atc-t6050: say why the CIO finish and lost calls are not fenced apple_t6050_phy_cio_finish() and apple_t6050_phy_cio_lost() do not check s2idle_frozen, unlike the other CIO calls. Say why in a comment: they write no PHY register and change no mode, clock or domain, and their one caller, the Thunderbolt host's CIO sleep, runs them only for a suspend-to-RAM it prepared (PM_SUSPEND_MEM), never across s2idle. No functional change. Signed-off-by: Satya Benson --- drivers/phy/apple/atc-t6050-dp.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/phy/apple/atc-t6050-dp.c b/drivers/phy/apple/atc-t6050-dp.c index c13b08b66ad706..12c5ca251ad475 100644 --- a/drivers/phy/apple/atc-t6050-dp.c +++ b/drivers/phy/apple/atc-t6050-dp.c @@ -1372,6 +1372,14 @@ int apple_t6050_phy_cio_on(struct device *dev) } EXPORT_SYMBOL_GPL(apple_t6050_phy_cio_on); +/* + * Not fenced by s2idle_frozen, unlike the CIO calls above: this and + * apple_t6050_phy_cio_lost() write no PHY register and change no mode, + * clock or domain. They only update the sleep-in-place bookkeeping, under + * dp->lock. Their only caller, the Thunderbolt host's CIO sleep in + * drivers/thunderbolt/apple-cio-sleep.c, runs them only for a + * suspend-to-RAM it prepared (PM_SUSPEND_MEM), never across s2idle. + */ int apple_t6050_phy_cio_finish(struct device *dev) { struct t6050_dp *dp = t6050_dp_from_dev(dev); From 3f67ead4c2c8f41a10b03dbe4c2a6c6d72db6071 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:33:45 +1100 Subject: [PATCH 0448/1514] soc: apple: sep: describe what SEP_BIO_REARM does with its secret The comment on SEP_BIO_REARM says the password is used to unwrap a re-arm record. It is not: the driver copies the secret in and wipes it unused, and ends the enclave's lockout with the stored secret of the configured user's key bag. The failed attempts, the lockout and the wait for the first password since boot are also kept once for the machine, not per account. Describe that, so that a caller does not rely on the kernel to check the password or to scope the re-arm to one account. No change to the ABI or to what the ioctl does. Signed-off-by: Ryan Murray --- include/uapi/linux/apple-sep.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/include/uapi/linux/apple-sep.h b/include/uapi/linux/apple-sep.h index 2b949a8c895974..609b897b6a792b 100644 --- a/include/uapi/linux/apple-sep.h +++ b/include/uapi/linux/apple-sep.h @@ -207,9 +207,14 @@ struct sep_bio_lockout { #define SEP_BIO_LOCKOUT_STATE _IOR(SEP_BIO_IOC_MAGIC, 0x0e, struct sep_bio_lockout) /* * Ends a lockout. Call it only once the user's password has been verified: - * the password is used once to unwrap the Linux-owned FV re-arm record and is - * wiped after the request. Needs CAP_SYS_ADMIN. Without a lockout it clears - * the failed attempts (see SEP_BIO_LOCKOUT_FLAG_EVERY_PASSWORD). + * the kernel does not check the password. 'secret' is copied in and wiped + * after the request without being used; the enclave's lockout is ended with + * the stored secret of the configured user's key bag. The failed attempts, + * the lockout and the wait for the first password since boot + * (SEP_BIO_REQUIRE_PASSWORD) are kept once for the whole machine, not per + * account, and one call clears them for every enrolled finger. Needs + * CAP_SYS_ADMIN. Without a lockout it clears the failed attempts (see + * SEP_BIO_LOCKOUT_FLAG_EVERY_PASSWORD). */ #define SEP_BIO_REARM_SECRET_MAX 1024 struct sep_bio_rearm { From 07effed23425a059f2874f15623a33662a507ead Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Sun, 22 Nov 2026 21:06:21 +0100 Subject: [PATCH 0449/1514] soc: apple: clpc: hold ANE memory/fabric floor on T8142 The H17 ANE driver on T8142 (M5) already requests an ANE CLPC handle via apple_clpc_ane_get() and publishes activity via apple_clpc_ane_set_active(), and the T8142 device trees already declare "apple,t8142-clpc", but drivers/soc/apple/clpc.c neither lists "apple,t8142-clpc" in apple_clpc_ane_providers[] nor configures a floor in apple_clpc_hw_t8142. When the CPUs are idle or lightly loaded, both the DRAM controller (DCS) and SoC fabric stay at low states while ANE inference runs, throttling memory- and fabric-bound workloads. Register "apple,t8142-clpc" as an ANE CLPC provider and set apple_clpc_hw_t8142.ane to DCS 7 (top DCS state) and fabric 3 (a measured policy choice below top fabric state 4). Measured on J813 (MacBook Air 13" M5; J815 and J704 share the compatible and were not tested) via /sys/kernel/debug/ane-h17/.../ execute, CLPC ane_states, and macsmc_hwmon Total System Power: - Cold-SLC denoise-640 firmware time (CPU fixed at 1 GHz, pre-exec floor 0): 20.02 ms at (0, 0) -> 16.02 ms at (7, 0) -> 15.79 ms at (7, 1) -> 11.71 ms at (7, 2) -> 10.37 ms at (7, 3); (7, 4) is 10.36 ms (no gain). - Cold-SLC mm-512x2048 firmware time: 782 us at (0, 0) -> 728 us at (7, 0) -> 560 us at (7, 2) -> 526 us at (7, 3); (7, 4) is 552 us. - Controlled A-B-A sweep (CPU pinned at min freq so ANE owns the floor) across three workload classes shows fabric 3 saturates firmware time while fabric 4 adds 71-121 mW with zero speedup: * denoise-640 (conv UNet): 16.48 ms (0, 0) -> 11.67 ms (7, 2) -> 10.33 ms / 4.284 W (7, 3) vs 10.35 ms / 4.405 W (7, 4) (+121 mW). * unet-320 (conv UNet): 3.94 ms (0, 0) -> 2.79 ms (7, 2) -> 2.46 ms / 3.944 W (7, 3) vs 2.46 ms / 4.035 W (7, 4) (+91 mW). * mm-512x2048 (GEMM): 627 us (0, 0) -> 493 us (7, 2) -> 420 us / 3.948 W (7, 3) vs 420 us / 4.019 W (7, 4) (+71 mW). - Default schedutil (warm SLC, 100 runs) denoise-640 firmware / p50 host latency: 11.60 / 15.43 ms at (0, 0) -> 10.35 / 13.90 ms at (7, 3); (7, 4) adds +95 mW (4.841 vs 4.746 W) with no fw speedup. - Sustained 10.5 min (631 s, 45,164 runs) continuous denoise-640 soak on fanless J813: 4.717 W mean total system power, SoC die plateaued at 31.7 C (21.8 C ambient), 0 CLPC update errors, bit-exact sha256. Closing /dev/accel/accel0 drops the floor to 0x0 within 1 s and returns idle system power to 2.48 W (vs 2.52 W median pre-soak). Under combined ANE + 10-core CPU load, PMP fast-die-effort (lane1) still engages cleanly at 96.7 C and holds die temp <= 99.6 C. - Pinning CPU P-cluster frequency from 1.0 to 4.46 GHz does not change ANE firmware time (10.25 vs 10.24 ms), so no CPU cluster floor is needed. Update the apple-clpc-gpu KUnit suite to assert T8142's DCS 7 / fabric 3 ANE demand instead of expecting no ANE floor on T8142. Signed-off-by: Bartosz Nitka --- drivers/soc/apple/clpc.c | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index c3ca54ba859db4..53230b745cb5f0 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -403,6 +403,7 @@ static const struct of_device_id apple_clpc_ane_providers[] = { { .compatible = "apple,t6041-max-clpc" }, { .compatible = "apple,t6041-clpc" }, { .compatible = "apple,t8140-clpc" }, + { .compatible = "apple,t8142-clpc" }, {} }; @@ -1749,6 +1750,20 @@ static const struct apple_clpc_hw apple_clpc_hw_t8142 = { [APPLE_CLPC_SOC] = { 1, 2, 3, 4 }, }, .gpu_input = true, + /* + * Measured ANE demand (J813, H17; J815/J704 share the compatible and + * are untested): DCS 7 is the top DCS state; fabric 3 is a measured + * policy choice below the top fabric state (4). With the CPU pinned at + * minimum frequency so ANE owns the floor, firmware time drops from + * (0, 0) -> (7, 2) -> (7, 3) across denoise-640 (16.5 -> 11.7 -> 10.3 + * ms; cold SLC 20.0 -> 11.7 -> 10.4 ms), unet-320 conv (3.94 -> 2.79 + * -> 2.46 ms), and mm-512x2048 GEMM (627 -> 493 -> 420 us; cold SLC + * 782 -> 560 -> 526 us). Fabric 4 gives no further speedup on any of + * them and adds 71-121 mW of system power (4.28 -> 4.41 W on + * denoise-640, 3.94 -> 4.04 W on unet-320, 3.95 -> 4.02 W on + * mm-512x2048). + */ + .ane = { [APPLE_CLPC_DCS] = 7, [APPLE_CLPC_SOC] = 3 }, }; #if IS_BUILTIN(CONFIG_KUNIT) && !defined(MODULE) @@ -1989,6 +2004,18 @@ static void apple_clpc_ane_demand_hold_test(struct kunit *test) /* T6040 holds its top qualified DCS and fabric states for the ANE. */ KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane[APPLE_CLPC_DCS], 5); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane[APPLE_CLPC_SOC], 2); + /* T8142 holds DCS 7 and fabric 3 while ANE work is in flight. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_DCS], 7); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_SOC], 3); + clpc->hw = &apple_clpc_hw_t8142; + clpc->ane_states[APPLE_CLPC_DCS] = clpc->hw->ane[APPLE_CLPC_DCS]; + clpc->ane_states[APPLE_CLPC_SOC] = clpc->hw->ane[APPLE_CLPC_SOC]; + memset(demand, 0, sizeof(demand)); + apple_clpc_ane_set_active(&ane, true); + KUNIT_EXPECT_TRUE(test, apple_clpc_ane_input_demand(clpc, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 7u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 3u); + apple_clpc_ane_set_active(&ane, false); } static void apple_clpc_ane_cluster_test(struct kunit *test) @@ -2052,7 +2079,6 @@ static void apple_clpc_ane_no_provider_test(struct kunit *test) KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 0u); KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 0u); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8132.ane[APPLE_CLPC_DCS], 0); - KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane[APPLE_CLPC_DCS], 0); } static void apple_clpc_ane_wake_removal_test(struct kunit *test) From 5029465c333af4cac084c6aa5c33835b7a810793 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:38:17 +1100 Subject: [PATCH 0450/1514] tools/asahi: check the firmware-27 DPTX layout of a DCP with Type-C routes "drm/apple: dcp: open the firmware-27 DPTX ports of a DCP with Type-C routes" lets a DCP that the device tree connects to Type-C routes take the advertised DPTX endpoints, not only a dcpext. The layout test still modelled the dcpext-only rule and failed. Run the matrix with and without Type-C routes, adapt the mutations to the new condition, and add one that leaves a DCP with Type-C routes on the default endpoints. Signed-off-by: Ryan Murray --- tools/asahi/dcp-v27-dptx-layout-tests.py | 28 ++++++++++++++---------- tools/asahi/run-host-tests.py | 3 ++- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/tools/asahi/dcp-v27-dptx-layout-tests.py b/tools/asahi/dcp-v27-dptx-layout-tests.py index 03c130d0650fcc..1119c30a4acc92 100755 --- a/tools/asahi/dcp-v27-dptx-layout-tests.py +++ b/tools/asahi/dcp-v27-dptx-layout-tests.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Where a firmware-27 dcpext opens its DPTX controller and ports. +"""Where a firmware-27 dcpext, or a DCP with Type-C routes, opens its DPTX controller and ports. Builds the production dcp_v27_dptx_layout() and dptxep_init()'s endpoint choice, and runs them over firmware, processor role, advertised endpoints and -hardware data. A firmware-27 dcpext whose firmware advertises both -DPTX_CONTROLLER_ENDPOINT (0x24) and DPTX_ENDPOINT (0x2a) gets the controller -and its ports there (J413 and J615 on 27.2); hardware data that names an +hardware data. A firmware-27 dcpext, or a firmware-27 DCP that the device tree +connects to Type-C display routes (the M2 Mac mini's primary), whose firmware +advertises both DPTX_CONTROLLER_ENDPOINT (0x24) and DPTX_ENDPOINT (0x2a) gets +the controller and its ports there (J413 and J615 on 27.2); hardware data that names an endpoint keeps it (T8142, T6050 and firmware-27 T6041 dcpexts); every other processor is unchanged. The selector must not test a compatible. @@ -24,9 +25,11 @@ 'ignore-advertisement': ('\tif (!apple_rtkit_has_endpoint(dcp->rtk, DPTX_CONTROLLER_ENDPOINT) ||\n' '\t !apple_rtkit_has_endpoint(dcp->rtk, DPTX_ENDPOINT))\n\t\treturn;\n', ''), # Override hardware data that already names an endpoint. - 'ignore-pinned': (' ||\n\t dcp->hw.dptx_endpoint)\n', ')\n'), - # Apply to internal processors too. - 'ignore-dcpext': (' || !dcp->dcpext', ''), + 'ignore-pinned': (' || dcp->hw.dptx_endpoint)\n', ')\n'), + # Apply to every processor, with or without Type-C routes. + 'ignore-dcpext': ('(!dcp->dcpext && !dcp->nr_typec_routes) || ', ''), + # Leave a DCP with Type-C routes on the default endpoints. + 'ignore-typec-routes': ('(!dcp->dcpext && !dcp->nr_typec_routes)', '!dcp->dcpext'), } parser = argparse.ArgumentParser(description=__doc__) @@ -93,7 +96,7 @@ def table(name): #define DPTX_CONTROLLER_ENDPOINT 0x24 #define DPTX_ENDPOINT 0x2a #define DPTX_ENDPOINT_V2 0x2c -struct apple_dcp { int fw_compat; bool dcpext, ext26; void *rtk, *dev; +struct apple_dcp { int fw_compat; bool dcpext, ext26; u32 nr_typec_routes; void *rtk, *dev; struct { u8 dptx_endpoint; bool dptx_controller; int iomfb_method_profile; } hw; }; static u32 advertised; static bool apple_rtkit_has_endpoint(void *rtk, int ep) { return advertised & (1u << (ep - 0x20)); } @@ -122,12 +125,13 @@ def table(name): for (unsigned ext = 0; ext < 2; ext++) for (unsigned m = 0; m < 6; m++) for (unsigned p = 0; p < 3; p++) - for (unsigned c = 0; c < 2; c++) { - struct apple_dcp d = { .fw_compat = fws[f], .dcpext = ext, + for (unsigned c = 0; c < 2; c++) + for (unsigned r = 0; r < 2; r++) { + struct apple_dcp d = { .fw_compat = fws[f], .dcpext = ext, .nr_typec_routes = 2 * r, .hw.dptx_endpoint = pins[p], .hw.dptx_controller = c }; struct apple_dcp before = d; bool both = (maps[m] & BIT(0x24)) && (maps[m] & BIT(0x2a)); - bool chosen = fws[f] == DCP_FIRMWARE_V_27_0 && ext && !pins[p] && both; + bool chosen = fws[f] == DCP_FIRMWARE_V_27_0 && (ext || r) && !pins[p] && both; advertised = maps[m]; info_lines = 0; @@ -175,4 +179,4 @@ def table(name): run = subprocess.run([str(exe)]) if run.returncode: sys.exit(f'FAIL: the layout matrix exited {run.returncode}') -print('PASS firmware-27 dcpext DPTX layout from its advertised endpoints; pinned and other processors unchanged') +print('PASS firmware-27 dcpext / Type-C-routed DCP DPTX layout from its advertised endpoints; pinned and other processors unchanged') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..7a21d3c4fb27ff 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -80,7 +80,8 @@ def mutations(flag, names, base, expect=KILL): 'dcpext26-startup-tests.py': [([], PASS)], 'iomfb-startup-tests.py': [([], PASS)], 'dcp-v27-dptx-layout-tests.py': [([], PASS)] + mutations( - '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext'], []), + '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext', + 'ignore-typec-routes'], []), 'dcpext26-wire-tests.py': [([], PASS)], 'pmp-native26-tests.py': [([], PASS)], From 505c88dd000a7026a316a6c9a1e5ea54d3623605 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:42:42 +1100 Subject: [PATCH 0451/1514] tools/aurora-sep: take the /tmp Limine lock only when root already owns it esp-history.py, m3-boot-profile.py and air-gpu-oneshot.sh (and the copies in install-aurora-sep.sh) took /run/lock/boot-partition.lock and then /tmp/limine-global.lock, creating the second one if it was missing. /tmp is world-writable, so that file can be made or held by any user. Keep /run/lock/boot-partition.lock as the lock that is always taken. Take /tmp/limine-global.lock, which older Omarchy Limine tools still use, only when it already exists as a regular file owned by root. The Python tools check this with fstat after an O_NOFOLLOW open, without O_CREAT. The shell script opens it read-only and checks the owner, the file type and the inode of the open descriptor against the path. Otherwise it is skipped. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 1 + tools/aurora-sep/air-gpu/air-gpu-oneshot.sh | 36 +++- tools/aurora-sep/esp-history.py | 35 +++- tools/aurora-sep/install-aurora-sep.sh | 84 +++++++-- tools/aurora-sep/m3-boot-profile.py | 43 ++++- tools/aurora-sep/tests/test_air_gpu.py | 1 + tools/aurora-sep/tests/test_boot_locks.py | 199 ++++++++++++++++++++ tools/aurora-sep/tests/test_m3max_kit.py | 1 + 8 files changed, 374 insertions(+), 26 deletions(-) create mode 100644 tools/aurora-sep/tests/test_boot_locks.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 3f824af0d4f61c..0047abfd7768a6 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -74,6 +74,7 @@ jobs: python3 -m unittest tools/aurora-sep/tests/test_key_context_cleanup.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_packaging.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_sep_writes_always_on.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v rust-build: runs-on: ubuntu-24.04 diff --git a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh index 2231a78b2a3465..b89fc8ac3398ae 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh @@ -91,8 +91,11 @@ BLI_GUID=4a67b082-0a4c-41cf-b6c7-440b29bb8c4f UBOOT_GUID=b2ac5fc9-92b7-4acd-aeac-11e818c3130c GLOBAL_GUID=8be4df61-93ca-11d2-aa0d-00e098032b8c # Omarchy's Limine tools take one of these before they touch the EFI partition (newer ones the -# first, older ones the second); maclab takes both in this order, and so does this script. -LOCKS="/run/lock/boot-partition.lock /tmp/limine-global.lock" +# first, older ones the second); maclab takes both in this order, and so does this script. The +# second is in world-writable /tmp, where any user could make or hold it first: it is taken only +# when it is already there as a regular file of root's (COMPAT_LOCKS, never created). +LOCKS="/run/lock/boot-partition.lock" +COMPAT_LOCKS="/tmp/limine-global.lock" STATE_DIR=/var/lib/air-gpu # limine-entry-tool's settings; ENABLE_ENROLL_LIMINE_CONFIG=yes there makes Limine check a hash # of limine.conf enrolled into its EFI binary, so an edited limine.conf would not boot. @@ -303,6 +306,35 @@ take_locks() { fi LOCK_FDS+=("$fd") done + for l in $COMPAT_LOCKS; do + open_compat_lock "$l" || continue + fd=$COMPAT_FD + if ! flock -w 5 "$fd"; then + release_locks + refuse "$l is held by another tool (limine-snapper-sync?); try again in a moment." + fi + LOCK_FDS+=("$fd") + done +} +# Open a compatibility lock read-only (never created) into COMPAT_FD, and keep it only when the +# opened file is a regular file owned by this user (root) and is the path itself, not something +# a symbolic link points to; that is checked on the open descriptor. The test before the open only +# avoids opening a FIFO (which would block): in sticky /tmp nobody else can replace root's file. +COMPAT_FD= +open_compat_lock() { + local l=$1 fd owner inode type + COMPAT_FD= + [[ -f $l && ! -L $l && -O $l ]] || return 1 + exec {fd}<"$l" 2>/dev/null || return 1 + # stat inherits the descriptor: /proc/self/fd/N is the file that was opened. + read -r owner inode type < <(stat -L -c '%u %d:%i %F' "/proc/self/fd/$fd" 2>/dev/null) || true + if [[ $owner == "$EUID" && $type == regular* && + $inode == "$(stat -c '%d:%i' "$l" 2>/dev/null)" ]]; then + COMPAT_FD=$fd + return 0 + fi + exec {fd}<&- + return 1 } LOCK_FDS=() release_locks() { diff --git a/tools/aurora-sep/esp-history.py b/tools/aurora-sep/esp-history.py index 07fe588a531368..a8c11bcff0fce0 100644 --- a/tools/aurora-sep/esp-history.py +++ b/tools/aurora-sep/esp-history.py @@ -87,8 +87,25 @@ def inventory(esp, state): return records +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take, or None. + + It sits in world-writable /tmp, where any user could create it first or + hold it. So it is never created or followed: it is used only when it is + already there as a regular file owned by this (root) user; otherwise the + /run/lock lock alone serializes the boot partition.""" + try: + fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + except OSError: + return None + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + return None + return fd + @contextlib.contextmanager -def lock(paths): +def lock(paths, compat=()): fds = [] try: for path in paths: @@ -98,19 +115,31 @@ def lock(paths): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + for path in compat: + fd = compat_lock(path) + if fd is None: + continue + fds.append(fd) + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield finally: for fd in reversed(fds): os.close(fd) -def archive(esp, state, destination, lock_paths=None): +BOOT_LOCK = Path('/run/lock/boot-partition.lock') +COMPAT_LOCK = Path('/tmp/limine-global.lock') + + +def archive(esp, state, destination, lock_paths=None, compat_locks=None): esp, state, destination = esp.absolute(), state.absolute(), destination.absolute() destination.mkdir(parents=True, exist_ok=True) checked_tree(destination) if destination.resolve().is_relative_to(esp.resolve()) or os.stat(destination).st_dev == os.stat(esp).st_dev: raise ValueError('archive must be on a different filesystem from the EFI partition') - with lock(lock_paths or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')]): + if lock_paths is None: + lock_paths, compat_locks = [BOOT_LOCK], [COMPAT_LOCK] if compat_locks is None else compat_locks + with lock(lock_paths, compat_locks or ()): planned = inventory(esp, state) moved = [] for item in planned: diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index b27cad73b1aea5..0d186e3419e39c 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -685,7 +685,7 @@ M3_PERSISTENT_TRANSACTION_ACTIVE=0 M3_PERSISTENT_MAIN_ARMED=0 M3_GPU_BIN=/usr/local/bin M3_GPU_SCRIPTS=( - "air-gpu-oneshot.sh d0259869b8519439a4dbcdae08ef1b0e17fdcaf84ac746fca61febf6a325f8aa" + "air-gpu-oneshot.sh 0cb379e91c4cdccbfa8591dfea362413bb420953918b4f6d29f0f610c9cd7923" "air-gpu-collect.sh face8fac811b59c31a8e98e6ca704a2cb33eceada8bc37986397cb393b050b30" "air-gpu-job.sh 9a0eb9aab52fd099488054e4ed4846c579b19fc9f78144245242b6975a40da1d" ) @@ -7178,8 +7178,25 @@ def inventory(esp, state): return records +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take, or None. + + It sits in world-writable /tmp, where any user could create it first or + hold it. So it is never created or followed: it is used only when it is + already there as a regular file owned by this (root) user; otherwise the + /run/lock lock alone serializes the boot partition.""" + try: + fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + except OSError: + return None + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + return None + return fd + @contextlib.contextmanager -def lock(paths): +def lock(paths, compat=()): fds = [] try: for path in paths: @@ -7189,19 +7206,31 @@ def lock(paths): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + for path in compat: + fd = compat_lock(path) + if fd is None: + continue + fds.append(fd) + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield finally: for fd in reversed(fds): os.close(fd) -def archive(esp, state, destination, lock_paths=None): +BOOT_LOCK = Path('/run/lock/boot-partition.lock') +COMPAT_LOCK = Path('/tmp/limine-global.lock') + + +def archive(esp, state, destination, lock_paths=None, compat_locks=None): esp, state, destination = esp.absolute(), state.absolute(), destination.absolute() destination.mkdir(parents=True, exist_ok=True) checked_tree(destination) if destination.resolve().is_relative_to(esp.resolve()) or os.stat(destination).st_dev == os.stat(esp).st_dev: raise ValueError('archive must be on a different filesystem from the EFI partition') - with lock(lock_paths or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')]): + if lock_paths is None: + lock_paths, compat_locks = [BOOT_LOCK], [COMPAT_LOCK] if compat_locks is None else compat_locks + with lock(lock_paths, compat_locks or ()): planned = inventory(esp, state) moved = [] for item in planned: @@ -7539,16 +7568,38 @@ def atomic(path, data): finally: if os.path.exists(name): os.unlink(name) +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take, or None. + + It sits in world-writable /tmp, where any user could create it first or + hold it. So it is never created or followed: it is used only when it is + already there as a regular file owned by this (root) user; otherwise the + /run/lock lock alone serializes the boot partition.""" + try: + fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + except OSError: + return None + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + return None + return fd + @contextlib.contextmanager -def locks(paths, timeout=30.0): +def locks(paths, timeout=30.0, compat=()): deadline = time.monotonic() + timeout fds = [] try: - for path in paths: - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) - fds.append(fd) - if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + for path, required in [(p, True) for p in paths] + [(p, False) for p in compat]: + if required: + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + fds.append(fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + else: + fd = compat_lock(path) + if fd is None: continue + fds.append(fd) while True: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -7616,7 +7667,7 @@ def same_esp_path(left, right): return False def limine(args): - with locks(args.lock, args.lock_timeout): + with locks(args.lock, args.lock_timeout, args.compat_lock): loader = regular(args.esp / 'EFI/BOOT/BOOTAA64.EFI').read_bytes() if b'limine.conf' not in loader: raise ValueError('EFI loader is not Limine') sig = b'++CONFIG_B2SUM_SIGNATURE++' @@ -7739,11 +7790,16 @@ def main(): p.add_argument('--release', default=os.uname().release) p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') + p.add_argument('--compat-lock', type=Path, action='append', + help='a lock taken only if it already exists as a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: p.error('lock timeout must be between 0 and 30 seconds') - args.lock = args.lock or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')] + if not args.lock: + args.lock = [Path('/run/lock/boot-partition.lock')] + args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')] + args.compat_lock = args.compat_lock or [] try: limine(args) except (OSError, ValueError, KeyError) as e: p.exit(1, f'M3 boot profile refused: {e}\n') @@ -8867,7 +8923,8 @@ M3MAX_KIT_DEBUGFS=/sys/kernel/debug # arming script itself (the runner's copy; the setup's download before that). M3MAX_KIT_EFIVARS=/sys/firmware/efi/efivars M3MAX_KIT_CMDLINE=/proc/cmdline -M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock /tmp/limine-global.lock" +M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock" +M3MAX_KIT_COMPAT_LOCKS="/tmp/limine-global.lock" M3MAX_KIT_LIMINE_DEFAULTS=/etc/default/limine M3MAX_KIT_ONESHOT=$M3MAX_KIT_LIBEXEC/air-gpu-oneshot.sh M3MAX_KIT_JOB=$M3MAX_KIT_LIBEXEC/air-gpu-job.sh @@ -9181,6 +9238,7 @@ m3max_kit_oneshot_setup() { EFIVARS=$M3MAX_KIT_EFIVARS CMDLINE=$M3MAX_KIT_CMDLINE LOCKS=$M3MAX_KIT_LOCKS + COMPAT_LOCKS=$M3MAX_KIT_COMPAT_LOCKS LIMINE_DEFAULTS=$M3MAX_KIT_LIMINE_DEFAULTS check_board() { is_m3_max || refuse "this Mac ($(this_board), $(this_soc)) is not a 16-core M3 Max (t6031: $M3_MAX_BOARDS)." diff --git a/tools/aurora-sep/m3-boot-profile.py b/tools/aurora-sep/m3-boot-profile.py index ea681588c9ae7c..02f1c58d86fdbe 100644 --- a/tools/aurora-sep/m3-boot-profile.py +++ b/tools/aurora-sep/m3-boot-profile.py @@ -38,16 +38,38 @@ def atomic(path, data): finally: if os.path.exists(name): os.unlink(name) +def compat_lock(path): + """fd of the compatibility lock older Omarchy Limine tools take, or None. + + It sits in world-writable /tmp, where any user could create it first or + hold it. So it is never created or followed: it is used only when it is + already there as a regular file owned by this (root) user; otherwise the + /run/lock lock alone serializes the boot partition.""" + try: + fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + except OSError: + return None + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): + os.close(fd) + return None + return fd + @contextlib.contextmanager -def locks(paths, timeout=30.0): +def locks(paths, timeout=30.0, compat=()): deadline = time.monotonic() + timeout fds = [] try: - for path in paths: - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) - fds.append(fd) - if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + for path, required in [(p, True) for p in paths] + [(p, False) for p in compat]: + if required: + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) + fds.append(fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') + else: + fd = compat_lock(path) + if fd is None: continue + fds.append(fd) while True: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) @@ -115,7 +137,7 @@ def same_esp_path(left, right): return False def limine(args): - with locks(args.lock, args.lock_timeout): + with locks(args.lock, args.lock_timeout, args.compat_lock): loader = regular(args.esp / 'EFI/BOOT/BOOTAA64.EFI').read_bytes() if b'limine.conf' not in loader: raise ValueError('EFI loader is not Limine') sig = b'++CONFIG_B2SUM_SIGNATURE++' @@ -238,11 +260,16 @@ def main(): p.add_argument('--release', default=os.uname().release) p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') + p.add_argument('--compat-lock', type=Path, action='append', + help='a lock taken only if it already exists as a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: p.error('lock timeout must be between 0 and 30 seconds') - args.lock = args.lock or [Path('/run/lock/boot-partition.lock'), Path('/tmp/limine-global.lock')] + if not args.lock: + args.lock = [Path('/run/lock/boot-partition.lock')] + args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')] + args.compat_lock = args.compat_lock or [] try: limine(args) except (OSError, ValueError, KeyError) as e: p.exit(1, f'M3 boot profile refused: {e}\n') diff --git a/tools/aurora-sep/tests/test_air_gpu.py b/tools/aurora-sep/tests/test_air_gpu.py index 26cec8567230fd..b6ee6b1c4b9857 100644 --- a/tools/aurora-sep/tests/test_air_gpu.py +++ b/tools/aurora-sep/tests/test_air_gpu.py @@ -174,6 +174,7 @@ def prelude(self, script, root=True): STATE_DIR='{self.state}' CMDLINE='{self.cmdline}' LOCKS='{self.tmp}/run/boot-partition.lock {self.tmp}/run/limine-global.lock' +COMPAT_LOCKS='' LIMINE_DEFAULTS='{self.tmp}/etc/limine' KREL='{KREL}' is_root() {{ {'true' if root else 'false'}; }} diff --git a/tools/aurora-sep/tests/test_boot_locks.py b/tools/aurora-sep/tests/test_boot_locks.py new file mode 100644 index 00000000000000..1efe90ac948f0b --- /dev/null +++ b/tools/aurora-sep/tests/test_boot_locks.py @@ -0,0 +1,199 @@ +"""The boot-partition tools' compatibility lock in /tmp: taken only when it is already there as a +regular file of the tool's own user (root), never created and never followed through a link. +The /run/lock lock is taken as before.""" +from pathlib import Path +import fcntl +import importlib.util +import os +import shutil +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +TOOLS = Path(__file__).resolve().parents[1] +ONESHOT = TOOLS / 'air-gpu/air-gpu-oneshot.sh' +INSTALLER = TOOLS / 'install-aurora-sep.sh' + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +ESP = load('esp_history_locks', TOOLS / 'esp-history.py') +M3 = load('m3_boot_profile_locks', TOOLS / 'm3-boot-profile.py') + + +def held_by_someone(path): + """True when another open file description holds an exclusive flock on path.""" + fd = os.open(path, os.O_RDONLY) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + finally: + os.close(fd) + return False + + +class PythonLocks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.boot = self.root / 'run/boot-partition.lock' + self.compat = self.root / 'tmp/limine-global.lock' + self.compat.parent.mkdir() + + def lockers(self): + return (('esp-history', lambda: ESP.lock([self.boot], [self.compat])), + ('m3-boot-profile', lambda: M3.locks([self.boot], 0.2, [self.compat]))) + + def test_defaults_name_the_compat_lock_separately(self): + self.assertEqual(ESP.BOOT_LOCK, Path('/run/lock/boot-partition.lock')) + self.assertEqual(ESP.COMPAT_LOCK, Path('/tmp/limine-global.lock')) + text = (TOOLS / 'm3-boot-profile.py').read_text() + self.assertIn("args.lock = [Path('/run/lock/boot-partition.lock')]", text) + self.assertIn("args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')]", text) + + def test_missing_compat_lock_is_not_created(self): + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + self.assertTrue(held_by_someone(self.boot)) + self.assertFalse(self.compat.exists()) + + def test_symlinked_compat_lock_is_not_followed(self): + target = self.root / 'victim' + self.compat.symlink_to(target) + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + pass + self.assertFalse(target.exists()) + target.write_text('x') + for name, locker in self.lockers(): + with self.subTest(name + ' existing target'): + with locker(): + self.assertFalse(held_by_someone(target)) + + def test_compat_lock_of_another_user_is_ignored_even_when_held(self): + self.compat.touch() + holder = os.open(self.compat, os.O_RDONLY) + self.addCleanup(os.close, holder) + fcntl.flock(holder, fcntl.LOCK_EX) + # The file belongs to someone else when the tool's own uid is another one. + for module in (ESP, M3): + with self.subTest(module.__name__), patch.object(module.os, 'geteuid', + return_value=os.geteuid() + 1): + ctx = ESP.lock([self.boot], [self.compat]) if module is ESP else \ + M3.locks([self.boot], 0.2, [self.compat]) + with ctx: + self.assertTrue(held_by_someone(self.boot)) + + def test_own_compat_lock_is_taken_and_a_holder_still_blocks(self): + self.compat.touch() + os.chmod(self.compat, 0o600) + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + self.assertTrue(held_by_someone(self.compat)) + self.assertFalse(held_by_someone(self.compat)) + holder = os.open(self.compat, os.O_RDONLY) + self.addCleanup(os.close, holder) + fcntl.flock(holder, fcntl.LOCK_EX) + with self.assertRaises(BlockingIOError): + with ESP.lock([self.boot], [self.compat]): + pass + with self.assertRaises(TimeoutError): + with M3.locks([self.boot], 0.2, [self.compat]): + pass + + def test_a_fifo_is_not_a_lock(self): + os.mkfifo(self.compat) + for name, locker in self.lockers(): + with self.subTest(name): + with locker(): + pass + + def test_installer_copies_match(self): + installer = INSTALLER.read_text() + for tag, path in (('ESP_HISTORY_PY', 'esp-history.py'), ('M3_BOOT_PROFILE_PY', 'm3-boot-profile.py')): + embedded = installer.split(f"<<'{tag}'\n", 1)[1].split(f'\n{tag}\n', 1)[0] + '\n' + self.assertEqual(embedded, (TOOLS / path).read_text(), path) + self.assertIn('M3MAX_KIT_LOCKS="/run/lock/boot-partition.lock"\n', installer) + self.assertIn('M3MAX_KIT_COMPAT_LOCKS="/tmp/limine-global.lock"\n', installer) + self.assertIn(' COMPAT_LOCKS=$M3MAX_KIT_COMPAT_LOCKS\n', installer) + + +@unittest.skipUnless(shutil.which('flock') and shutil.which('stat'), 'flock and stat are needed') +class ShellLocks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.boot = self.root / 'run/boot-partition.lock' + self.compat = self.root / 'tmp/limine-global.lock' + self.compat.parent.mkdir() + + def take(self, then='true'): + """Source the one-shot script, take its locks, then run `then` while they are held.""" + script = f""" +set -euo pipefail +AIR_GPU_SOURCE_ONLY=1 source '{ONESHOT}' +LOCKS='{self.boot}' +COMPAT_LOCKS='{self.compat}' +refuse() {{ echo "REFUSED: $*"; exit 7; }} +take_locks +echo "held ${{#LOCK_FDS[@]}}" +{then} +""" + return subprocess.run(['bash', '-c', script], capture_output=True, text=True) + + def probe(self, path): + return f"flock -n '{path}' true && echo free || echo busy" + + def test_defaults(self): + text = ONESHOT.read_text() + self.assertIn('\nLOCKS="/run/lock/boot-partition.lock"\n', text) + self.assertIn('\nCOMPAT_LOCKS="/tmp/limine-global.lock"\n', text) + + def test_missing_compat_lock_is_not_created(self): + r = self.take() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 1', r.stdout) + self.assertFalse(self.compat.exists()) + + def test_symlinked_compat_lock_is_not_used(self): + target = self.root / 'victim' + target.write_text('x') + self.compat.symlink_to(target) + r = self.take(self.probe(target)) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 1', r.stdout) + self.assertIn('free', r.stdout) + self.compat.unlink() + self.compat.symlink_to(self.root / 'missing') + r = self.take() + self.assertIn('held 1', r.stdout) + self.assertFalse((self.root / 'missing').exists()) + + def test_own_regular_compat_lock_is_held(self): + self.compat.write_text('') + r = self.take(self.probe(self.compat)) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 2', r.stdout) + self.assertIn('busy', r.stdout) + + def test_a_fifo_is_not_a_lock(self): + os.mkfifo(self.compat) + r = self.take() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('held 1', r.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/aurora-sep/tests/test_m3max_kit.py b/tools/aurora-sep/tests/test_m3max_kit.py index 019558e4c73bac..41a7f5ed760a8d 100644 --- a/tools/aurora-sep/tests/test_m3max_kit.py +++ b/tools/aurora-sep/tests/test_m3max_kit.py @@ -385,6 +385,7 @@ def kit_body(self): M3MAX_KIT_EFIVARS='{self.efivars}' M3MAX_KIT_CMDLINE='{t}/proc/cmdline' M3MAX_KIT_LOCKS='{t}/run/boot-partition.lock {t}/run/limine-global.lock' +M3MAX_KIT_COMPAT_LOCKS='' M3MAX_KIT_LIMINE_DEFAULTS='{t}/etc/limine' M3MAX_KIT_TTY='{self.tty}' M3MAX_KIT_SETTLE=0 From e6da4c50519a4a054755ed23be7867c7fb577e03 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:43:15 +1100 Subject: [PATCH 0452/1514] tools/aurora-sep: read only the SEP driver's own kernel messages aurora-sep-policy-change picked the refused xART record and the gigalocker base with unanchored searches over every kernel line that contained "apple_sep" or "xART". aurora-sep-ready did the same for the sensor refusals that start the Touch ID file rebuild. Any kernel line holding those words matched, for example a USB device's product string. No diag attribute reports either value, so they still come from the log. aurora-sep-policy-change now reads `journalctl -k -o json` and keeps only kernel-transport entries from the driver: its device messages (_KERNEL_SUBSYSTEM=platform, a "+platform:*.sep" _KERNEL_DEVICE and the "apple_sep : " prefix) and its pr_* messages ("apple_sep: " prefix). It strips the prefix and anchors both patterns at the start of the message. aurora-sep-ready asks journalctl for the SEP device's entries only (dmesg without journald) and anchors the match at "apple_sep : sensor: ". The Arch package's copies are symlinks to these files. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 1 + tools/aurora-sep/aurora-sep-policy-change | 46 ++++- tools/aurora-sep/aurora-sep-ready | 22 ++- .../tests/test_kernel_log_anchor.py | 159 ++++++++++++++++++ 4 files changed, 221 insertions(+), 7 deletions(-) create mode 100644 tools/aurora-sep/tests/test_kernel_log_anchor.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 0047abfd7768a6..37d9ded3ae0eca 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -75,6 +75,7 @@ jobs: python3 -m unittest discover -s tools/aurora-sep/tests -p test_packaging.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_sep_writes_always_on.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_kernel_log_anchor.py -v rust-build: runs-on: ubuntu-24.04 diff --git a/tools/aurora-sep/aurora-sep-policy-change b/tools/aurora-sep/aurora-sep-policy-change index fc9aab126e0d6b..70fd154b7bdb1f 100755 --- a/tools/aurora-sep/aurora-sep-policy-change +++ b/tools/aurora-sep/aurora-sep-policy-change @@ -36,6 +36,7 @@ root, and never adds the record to Linux's list. See XART-SAFETY.md. """ import hashlib +import json import os import re import shutil @@ -57,8 +58,11 @@ HOST_FILES = ( ) FPRINT = "/var/lib/fprint" -REFUSED = re.compile(r"xART guard: refused to rewrite kind-([34]) record ([0-9a-f]{32})") -BASE = re.compile(r"xART: APFS-resolved \.gl extent \(base (0x[0-9a-f]+)\)") +# Matched at the start of the driver's own messages only (kernel_log): a line +# anyone can get into the kernel log (a USB product string, say) is not one. +REFUSED = re.compile(r"^xART guard: refused to rewrite kind-([34]) record ([0-9a-f]{32}),", re.M) +BASE = re.compile(r"^xART: APFS-resolved \.gl extent \(base (0x[0-9a-f]+)\);", re.M) +DRIVER = "apple_sep" def die(msg): @@ -70,13 +74,45 @@ def say(msg): print(f"aurora-sep-policy-change: {msg}") +def driver_message(entry): + """The text of one journal entry if the apple_sep driver logged it, else None. + + Its device messages carry the SEP platform device in the journal's + kernel fields and start "apple_sep : "; its messages without a + device start "apple_sep: ". The prefix is removed.""" + if not isinstance(entry, dict) or entry.get("_TRANSPORT") != "kernel": + return None + msg = entry.get("MESSAGE") + if not isinstance(msg, str): + return None + device = entry.get("_KERNEL_DEVICE") + if device is None: + prefix = f"{DRIVER}: " + else: + name = device[len("+platform:"):] if isinstance(device, str) else "" + if (entry.get("_KERNEL_SUBSYSTEM") != "platform" or not device.startswith("+platform:") + or not name.endswith(".sep")): + return None + prefix = f"{DRIVER} {name}: " + return msg[len(prefix):] if msg.startswith(prefix) else None + + def kernel_log(): + """This boot's apple_sep messages, one per line, without the driver prefix.""" out = subprocess.run( - ["journalctl", "-k", "-b", "-o", "cat", "--no-pager", "-g", "apple_sep|xART"], + ["journalctl", "-k", "-b", "-o", "json", "--no-pager", "-g", "apple_sep|xART"], capture_output=True, text=True, ) - return out.stdout + lines = [] + for raw in out.stdout.splitlines(): + try: + msg = driver_message(json.loads(raw)) + except ValueError: + continue + if msg is not None: + lines.append(msg.rstrip("\n")) + return "\n".join(lines) + ("\n" if lines else "") def entry(kind, uuid): @@ -174,7 +210,7 @@ def status(log): say(f"refused this boot: kind-{kind} record {uuid}") for line in log.splitlines(): if "one-time rewrite" in line or "one-time allowance" in line: - say("this boot: " + line.split("apple_sep: ")[-1]) + say("this boot: " + line) def main(argv): diff --git a/tools/aurora-sep/aurora-sep-ready b/tools/aurora-sep/aurora-sep-ready index d1043c26e29903..e7e97535430504 100644 --- a/tools/aurora-sep/aurora-sep-ready +++ b/tools/aurora-sep/aurora-sep-ready @@ -112,11 +112,29 @@ failed() { run_dir=${AURORA_SEP_RUN:-/run/aurora-sep} repair_checked= repair_started= +# This boot's kernel messages of the SEP device named by the diag directory +# (journal entries whose kernel fields are that device; dmesg without +# journald). The driver writes them as "apple_sep : ...". +sep_device=${diag%/diag} +sep_device=${sep_device##*/} +sep_kernel_log() { + [ -n "$sep_device" ] || return 0 + if command -v journalctl >/dev/null 2>&1; then + journalctl -k -b -o cat --no-pager _KERNEL_SUBSYSTEM=platform \ + "_KERNEL_DEVICE=+platform:$sep_device" 2>/dev/null + else + dmesg 2>/dev/null | sed 's/^\[[^]]*\] //' + fi +} repair_once() { [ -z "$repair_checked" ] || return 0 repair_checked=1 - line=$({ journalctl -k -b -o cat --no-pager 2>/dev/null || dmesg 2>/dev/null; } | - grep -m1 -E 'sensor: ((LOAD_CALIBRATION|SENSOR_ROOT_KEY) refused|calibration refused|calibration blob [^ ]+ could not be loaded|signed root-key container [^ ]+ unavailable)') + [ -n "$sep_device" ] || return 0 + # Only a line that starts with the driver's own prefix for this device: + # text that merely contains the words (a USB product string) is not one. + device_re=$(printf '%s' "$sep_device" | sed 's/[][\.*^$/]/\\&/g') + line=$(sep_kernel_log | + grep -m1 -E "^apple_sep $device_re: sensor: ((LOAD_CALIBRATION|SENSOR_ROOT_KEY) refused|calibration refused|calibration blob [^ ]+ could not be loaded|signed root-key container [^ ]+ unavailable)") [ -n "$line" ] || return 0 if [ -e "$run_dir/touchid-auto-rebuild" ]; then log "the enclave refused a Touch ID file again ($line); the automatic rebuild already ran this boot, so not again. Run 'sudo aurora-touchid-setup --check' for details" diff --git a/tools/aurora-sep/tests/test_kernel_log_anchor.py b/tools/aurora-sep/tests/test_kernel_log_anchor.py new file mode 100644 index 00000000000000..9c86f8a41fa2e8 --- /dev/null +++ b/tools/aurora-sep/tests/test_kernel_log_anchor.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""aurora-sep-policy-change and aurora-sep-ready act only on the apple_sep driver's own kernel +messages: a line that merely contains the driver's words (a USB product string, another device) +is not one.""" +from pathlib import Path +import importlib.machinery +import importlib.util +import json +import os +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +TOOLS = Path(__file__).resolve().parents[1] +UUID = '0123456789abcdef0123456789abcdef' +OTHER = 'fedcba9876543210fedcba9876543210' +DEVICE = '406600000.sep' + + +def load_policy_change(): + loader = importlib.machinery.SourceFileLoader('policy_change_anchor', + str(TOOLS / 'aurora-sep-policy-change')) + module = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader)) + loader.exec_module(module) + return module + + +M = load_policy_change() + + +def kernel(msg, device=None, subsystem='platform', transport='kernel'): + e = {'MESSAGE': msg, '_TRANSPORT': transport} + if device is not None: + e['_KERNEL_DEVICE'] = device + e['_KERNEL_SUBSYSTEM'] = subsystem + return e + + +REAL_REFUSAL = kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {UUID}, ' + 'which this Linux install did not create') +REAL_BASE = kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x4d4000); 170 slots, ' + '10 live records, max revision 1765, 0 malformed, 0 duplicate, 0 repaired; writes ENABLED', + f'+platform:{DEVICE}') +FORGED = [ + # A USB device's product string. + kernel(f'usb 1-1: Product: xART guard: refused to rewrite kind-3 record {OTHER},', '+usb:1-1', 'usb'), + kernel('usb 1-1: Product: xART: APFS-resolved .gl extent (base 0x1000);', '+usb:1-1', 'usb'), + # Text that contains the driver's prefix somewhere else, without a device. + kernel(f'EXT4-fs: bad option apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},'), + # The device prefix on another subsystem's or device's entry. + kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x2000);', f'+usb:{DEVICE}', 'usb'), + kernel('apple_sep 1-1: xART: APFS-resolved .gl extent (base 0x3000);', '+platform:1-1'), + # Not from the kernel. + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', transport='syslog'), +] + + +class PolicyChangeLog(unittest.TestCase): + def log(self, entries): + out = '\n'.join(json.dumps(e) for e in entries) + '\n' + done = subprocess.CompletedProcess([], 0, stdout=out, stderr='') + with patch.object(M.subprocess, 'run', return_value=done) as run: + text = M.kernel_log() + self.assertIn('json', run.call_args[0][0]) + return text + + def test_forged_lines_are_not_the_drivers(self): + text = self.log(FORGED) + self.assertEqual(M.REFUSED.findall(text), []) + self.assertIsNone(M.BASE.search(text)) + + def test_the_drivers_lines_are_read(self): + text = self.log(FORGED[:2] + [REAL_REFUSAL, REAL_BASE] + FORGED[2:]) + self.assertEqual(M.REFUSED.findall(text), [('4', UUID)]) + self.assertEqual(M.BASE.search(text).group(1), '0x4d4000') + + def test_patterns_are_anchored(self): + self.assertIsNone(M.REFUSED.search(f'Product: xART guard: refused to rewrite kind-4 record {UUID},')) + self.assertIsNone(M.BASE.search('Product: xART: APFS-resolved .gl extent (base 0x1);')) + + def test_one_forged_refusal_does_not_block_or_steer_main(self): + # A forged line next to no real refusal: nothing to allow. + text = self.log(FORGED + [REAL_BASE]) + with patch.object(M, 'kernel_log', return_value=text), \ + patch.object(M.os, 'geteuid', return_value=0), \ + patch.object(M, 'backup') as backup, patch.object(M, 'arm') as arm: + with self.assertRaises(SystemExit): + M.main(['aurora-sep-policy-change']) + backup.assert_not_called() + arm.assert_not_called() + # Next to a real refusal: the real record, not "more than one". + text = self.log(FORGED + [REAL_REFUSAL, REAL_BASE]) + with patch.object(M, 'kernel_log', return_value=text), \ + patch.object(M.os, 'geteuid', return_value=0), \ + patch.object(M, 'backup', return_value='/x') as backup, \ + patch.object(M, 'arm') as arm: + M.main(['aurora-sep-policy-change']) + arm.assert_called_once_with(M.entry(4, bytes.fromhex(UUID))) + + def test_arch_copy_is_the_same(self): + for name in ('aurora-sep-policy-change', 'aurora-sep-ready'): + self.assertEqual((TOOLS / 'packaging/arch/aurora-sep' / name).read_bytes(), + (TOOLS / name).read_bytes(), name) + + +class ReadyLog(unittest.TestCase): + """aurora-sep-ready's rebuild trigger.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.bin, self.run = self.root / 'bin', self.root / 'run' + self.bin.mkdir() + self.diag = self.root / 'devices' / DEVICE / 'diag' + self.diag.mkdir(parents=True) + self.calls = self.root / 'calls' + for tool in ('journalctl', 'systemctl', 'authselect'): + (self.bin / tool).write_text(f'#!/bin/sh\necho "{tool} $*" >>"{self.calls}"\n' + + ('cat "$KMSG"\n' if tool == 'journalctl' else '')) + (self.bin / tool).chmod(0o755) + self.kmsg = self.root / 'kmsg' + + def ready(self, kmsg): + for name, value in {'touchid': 'ready', 'sensor_attach': 'not-ready', 'restore': 'restored', + 'matching': 'usable', 'sensor': 'online'}.items(): + (self.diag / name).write_text(value + '\n') + self.kmsg.write_text(kmsg) + done = subprocess.run(['sh', str(TOOLS / 'aurora-sep-ready')], capture_output=True, text=True, env={ + **os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}', 'KMSG': str(self.kmsg), + 'AURORA_SEP_DEV': '/dev/null', 'AURORA_SEP_SYSFS': str(self.root / 'devices'), + 'AURORA_SEP_READY_WAIT': '0', 'AURORA_SEP_RUN': str(self.run)}) + calls = self.calls.read_text() if self.calls.exists() else '' + self.calls.unlink(missing_ok=True) + return calls + + def test_reads_only_the_sep_devices_entries(self): + calls = self.ready('') + self.assertIn(f'_KERNEL_DEVICE=+platform:{DEVICE}', calls) + self.assertIn('_KERNEL_SUBSYSTEM=platform', calls) + + def test_a_refusal_in_another_line_starts_nothing(self): + for line in ('usb 1-1: Product: sensor: LOAD_CALIBRATION refused with status 0x1c', + f'usb 1-1: Product: apple_sep {DEVICE}: sensor: SENSOR_ROOT_KEY refused', + 'apple_sep 1-1: sensor: LOAD_CALIBRATION refused with status 0x1c', + 'apple_sep 406600000xsep: sensor: LOAD_CALIBRATION refused with status 0x1c'): + with self.subTest(line): + calls = self.ready(line + '\n') + self.assertNotIn('systemctl', calls) + self.assertFalse((self.run / 'calibration-refused').exists()) + + def test_the_drivers_refusal_starts_the_rebuild(self): + calls = self.ready(f'apple_sep {DEVICE}: sensor: LOAD_CALIBRATION refused with status 0x1c\n') + self.assertIn('systemctl start --no-block aurora-touchid-setup.service', calls) + + +if __name__ == '__main__': + unittest.main() From 812d91b62899989aed7420a1fccb44c8d145677b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:44:40 +1100 Subject: [PATCH 0453/1514] tools/aurora-sep: air-gpu-collect.sh: hand the tgz over privately The collector copied its tgz to a mktemp file in /tmp, made it 0644 and then copied it into the user's home. The copy in /tmp was world-readable until it was removed, and it stayed there when the home could not be written. With --include-dumps the tgz holds GPU memory, and it always holds the kernel log of the analysed boot. Stream the tgz through a pipe into a file that the user's own process creates with umask 077, so the file is the user's, mode 0600, and no other copy exists. If the home cannot be written, keep the tgz in a root-only $STATE_DIR/collect/ and say so. Update the script's sha256 in M3_GPU_SCRIPTS. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 1 + tools/aurora-sep/air-gpu/air-gpu-collect.sh | 32 ++++---- tools/aurora-sep/install-aurora-sep.sh | 2 +- .../aurora-sep/tests/test_collect_handover.py | 78 +++++++++++++++++++ 4 files changed, 96 insertions(+), 17 deletions(-) create mode 100644 tools/aurora-sep/tests/test_collect_handover.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 37d9ded3ae0eca..e0b284f759753b 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -76,6 +76,7 @@ jobs: python3 -m unittest discover -s tools/aurora-sep/tests -p test_sep_writes_always_on.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_kernel_log_anchor.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_collect_handover.py -v rust-build: runs-on: ubuntu-24.04 diff --git a/tools/aurora-sep/air-gpu/air-gpu-collect.sh b/tools/aurora-sep/air-gpu/air-gpu-collect.sh index 4a3e92bb346f63..840354fca853b2 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-collect.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-collect.sh @@ -759,25 +759,25 @@ main() { mv "$d" "$dir/$base" summary=$dir/$base/summary.txt tar -C "$dir" -czf "$dir/out.tgz" "$base" - # The user (runu) can't read the root-only mktemp dir, so hand the tgz over through its own - # world-readable temp file (the tgz is meant for a public issue); the collection dir stays 0700. - local pub - pub=$(mktemp --tmpdir "air-gpu-collect.XXXXXX.tgz") - cp -f "$dir/out.tgz" "$pub" - chmod 0644 "$pub" - # Durable before this returns (fsync the tgz and its directory): a hard reset right after must - # not lose it. - # shellcheck disable=SC2016 # $1..$3 are expanded by that sh - if runu sh -c 'cp -f -- "$1" "$2" && sync -- "$2" && sync -- "$3"' _ "$pub" "$out.tgz" "$home" 2>/dev/null; then + # The user (runu) can't read the root-only mktemp dir, so the tgz goes to them through a pipe: + # their own process creates the file, theirs and 0600 (with --include-dumps it holds GPU + # memory), and no copy is left anywhere else. Durable before this returns (fsync the tgz and + # its directory): a hard reset right after must not lose it. + # shellcheck disable=SC2016 # $1..$2 are expanded by that sh + if runu sh -c 'umask 077 && rm -f -- "$1" && cat >"$1" && sync -- "$1" && sync -- "$2"' \ + _ "$out.tgz" "$home" <"$dir/out.tgz" 2>/dev/null; then say "wrote $out.tgz" else - # The user's home was not writable (a symlink, say): keep the temp copy, under a name - # mktemp chose, where root can reach it. - sync "$pub" 2>/dev/null || true - say "wrote $pub (could not write $user's home)" - pub="" + # The user's home was not writable (a symlink, say): keep it where only root can read it. + local keep + keep=$STATE_DIR/collect/$base.tgz + if (umask 077 && mkdir -p -- "$STATE_DIR/collect" && cp -- "$dir/out.tgz" "$keep" && + sync -- "$keep"); then + say "wrote $keep, readable by root only (could not write $user's home)" + else + say "could not write $user's home or $STATE_DIR/collect; nothing was kept" + fi fi - [[ -z $pub ]] || rm -f "$pub" sed -n '2,6p' "$summary" head -1 "$summary" } diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index 0d186e3419e39c..ff54c35f0964b3 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -686,7 +686,7 @@ M3_PERSISTENT_MAIN_ARMED=0 M3_GPU_BIN=/usr/local/bin M3_GPU_SCRIPTS=( "air-gpu-oneshot.sh 0cb379e91c4cdccbfa8591dfea362413bb420953918b4f6d29f0f610c9cd7923" - "air-gpu-collect.sh face8fac811b59c31a8e98e6ca704a2cb33eceada8bc37986397cb393b050b30" + "air-gpu-collect.sh 6a457261dc9773401f2ec7e436839a5f0d3b2bccdd9a90f013f8e72878189879" "air-gpu-job.sh 9a0eb9aab52fd099488054e4ed4846c579b19fc9f78144245242b6975a40da1d" ) # The Mesa prefix air-gpu-job.sh runs with: mesa-m3's (12.4 on; it replaces the separate diff --git a/tools/aurora-sep/tests/test_collect_handover.py b/tools/aurora-sep/tests/test_collect_handover.py new file mode 100644 index 00000000000000..4b2d0c9d499081 --- /dev/null +++ b/tools/aurora-sep/tests/test_collect_handover.py @@ -0,0 +1,78 @@ +"""air-gpu-collect.sh hands its tgz to the user privately: the file is created by the user's own +process with mode 0600, and no copy is left in the temp directory (or anywhere world-readable) +when the user's home cannot be written.""" +import os +from pathlib import Path +import stat +import unittest + +import test_air_gpu as A +from test_air_gpu import ARMED, COLLECT, RUNNING, k1 + + +class CollectHandOverTest(unittest.TestCase): + def setUp(self): + # CollectRunTest's fake Mac, journal and home, without its tests. + rig = A.CollectRunTest("test_this_boot") + rig.setUp() + self.addCleanup(rig.doCleanups) + self.mac, self.home, self.statedir = rig.mac, rig.home, rig.statedir + self.rig = rig + self.tmpdir = self.mac.tmp / "tmpdir" + self.tmpdir.mkdir() + self.mac.cmdline.write_text(ARMED + "\n") + rig.journal(0, ARMED, RUNNING + k1("job-completed", ": the first compute job finished")) + + def collect(self): + t = self.mac.tmp + body = f""" +export FAKE='{self.rig.fake}' +export TMPDIR='{self.tmpdir}' +DEBUGFS='{t}/debug' +SYS='{t}/sys' +BOOT_ID='{self.rig.boot_id}' +STATE_DIR='{self.statedir}' +EXTRA_HOMES='' +user_home() {{ echo '{self.home}'; }} +main +""" + return self.mac.run(COLLECT, body, check=True) + + def leftovers(self): + return sorted(p.name for p in self.tmpdir.iterdir()) + + def test_the_tgz_is_private_and_nothing_is_left_behind(self): + old = os.umask(0o022) + try: + self.collect() + finally: + os.umask(old) + tgz = list(self.home.glob("air-gpu-collect-*.tgz")) + self.assertEqual(len(tgz), 1) + mode = stat.S_IMODE(tgz[0].stat().st_mode) + self.assertEqual(mode & 0o077, 0, oct(mode)) + self.assertEqual(tgz[0].stat().st_uid, os.getuid()) + self.assertEqual(self.leftovers(), []) + + def test_an_unwritable_home_keeps_a_root_only_copy(self): + os.chmod(self.home, 0o500) + self.addCleanup(os.chmod, self.home, 0o700) + if os.access(self.home, os.W_OK): + self.skipTest("running with DAC override (root)") + proc = self.collect() + self.assertEqual(list(self.home.glob("air-gpu-collect-*.tgz")), []) + self.assertEqual(self.leftovers(), []) + kept = list((self.statedir / "collect").glob("air-gpu-collect-*.tgz")) + self.assertEqual(len(kept), 1, proc.stdout) + self.assertEqual(stat.S_IMODE(kept[0].stat().st_mode) & 0o077, 0) + self.assertEqual(stat.S_IMODE((self.statedir / "collect").stat().st_mode) & 0o077, 0) + self.assertIn("readable by root only", proc.stdout) + + def test_no_world_readable_hand_over_in_the_script(self): + text = (Path(__file__).resolve().parents[1] / "air-gpu/air-gpu-collect.sh").read_text() + self.assertNotIn("chmod 0644", text) + self.assertNotIn("mktemp --tmpdir", text) + + +if __name__ == "__main__": + unittest.main() From 22fd5d9904238ff6480cd52e00fcb8a3cd44f000 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:44:53 +1100 Subject: [PATCH 0454/1514] tools/aurora-sep: aurora-touchid: let fprintd open /dev/sep-bio only The aurora-touchid fprintd drop-in allowed the whole misc device class (DeviceAllow=char-misc), which also covers uinput, fuse, kvm, the device-mapper control node and more. It did this because a path rule is resolved when fprintd's cgroup is set up, before ExecStartPre= runs, and /dev/sep-bio may not exist yet at that point. Move the wait for /dev/sep-bio into its own oneshot unit, aurora-touchid-device.service (after apple-sep.service, before fprintd). Order fprintd after it and after aurora-sep-ready.service, and allow only DeviceAllow=/dev/sep-bio rw, as the Fedora and Arch aurora-sep drop-in does. Bump pkgrel and the PKGBUILD checksums. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 1 + tools/aurora-sep/aurora-touchid/PKGBUILD | 7 +- .../aurora-touchid-device.service | 15 ++++ .../aurora-touchid/fprintd-aurora.conf | 19 ++--- .../aurora-sep/tests/test_touchid_package.py | 79 +++++++++++++++++++ 5 files changed, 110 insertions(+), 11 deletions(-) create mode 100644 tools/aurora-sep/aurora-touchid/aurora-touchid-device.service create mode 100644 tools/aurora-sep/tests/test_touchid_package.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index e0b284f759753b..d3531133042739 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -77,6 +77,7 @@ jobs: python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_kernel_log_anchor.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_collect_handover.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_touchid_package.py -v rust-build: runs-on: ubuntu-24.04 diff --git a/tools/aurora-sep/aurora-touchid/PKGBUILD b/tools/aurora-sep/aurora-touchid/PKGBUILD index ebad07307e9665..b96e1d891a3834 100644 --- a/tools/aurora-sep/aurora-touchid/PKGBUILD +++ b/tools/aurora-sep/aurora-touchid/PKGBUILD @@ -1,7 +1,7 @@ # Maintainer: Chris Kearney <303316+iconidentify@users.noreply.github.com> pkgname=aurora-touchid pkgver=20261003 -pkgrel=2 +pkgrel=3 pkgdesc="Touch ID for Omarchy on Apple Silicon (aurora kernel SEP driver)" arch=('any') url="https://github.com/iconidentify/aurora-linux" @@ -12,6 +12,7 @@ source=('aurora-touchid-setup' 'apple-sep.service' 'apple-sep.path' 'fprintd-aurora.conf' + 'aurora-touchid-device.service' 'aurora-touchid.sleep' 'wait-for-display' 'sddm-wait-display.conf') @@ -19,7 +20,8 @@ sha256sums=('406da23baf0127dd5ba116c2f83808fb10d979315a17227a78731c5d3081efe4' '15a878dcf382a22c5d807f0f2c754fe70d39baec88f65aea183b1fe56cf69441' '4f7b8a97e35e3511afa482ee8aedd019e960b1a67320675bd347f534feab49c3' '2f4b265a4c2180a9e0e4926c53ec77c3dbb074ddc3e083d7925d58db10a576b9' - 'e1b1152e576e9588cc134b09291b3a2306ac686d9a47be6f128670608da535fc' + '1ff4dc0bb2a731fc8ee7a65d270b86b51e0d11d7f68dcce0204a3e67570e58b1' + '6da30137e6e2408cab9b755af7a6c4b1e004057a79d857b0d528d5eaf08bfe5a' 'a87526383319cc7c1214082196d0d80ad9a6da09b5c30bf215f866e01443c611' '062f70bb84e4139baf75d4dbefff21478af28f67e5569ee095692734d764746b' '07edd06103f5d199e7d6dcca0b7fa8e10a912cb657973ffce764c6e2ef65fa40') @@ -30,6 +32,7 @@ package() { install -Dm644 apple-sep.service "$pkgdir/usr/lib/systemd/system/apple-sep.service" install -Dm644 apple-sep.path "$pkgdir/usr/lib/systemd/system/apple-sep.path" install -Dm644 fprintd-aurora.conf "$pkgdir/usr/lib/systemd/system/fprintd.service.d/aurora.conf" + install -Dm644 aurora-touchid-device.service "$pkgdir/usr/lib/systemd/system/aurora-touchid-device.service" install -Dm755 aurora-touchid.sleep "$pkgdir/usr/lib/systemd/system-sleep/aurora-touchid" install -Dm755 wait-for-display "$pkgdir/usr/lib/aurora-touchid/wait-for-display" install -Dm644 sddm-wait-display.conf "$pkgdir/usr/lib/systemd/system/sddm.service.d/50-aurora-wait-display.conf" diff --git a/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service b/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service new file mode 100644 index 00000000000000..cf112c29ec317c --- /dev/null +++ b/tools/aurora-sep/aurora-touchid/aurora-touchid-device.service @@ -0,0 +1,15 @@ +[Unit] +Description=Wait for the Touch ID device (/dev/sep-bio) +# apple-sep.service only runs modprobe; /dev/sep-bio appears a few seconds +# later, once the enclave is up. fprintd is ordered after this (its drop-in), +# so that it does not start, find no device and cache "No devices available" +# until it idles out, and so that its DeviceAllow=/dev/sep-bio finds the node. +After=apple-sep.service +Before=fprintd.service +ConditionPathExists=/dev/disk/by-partlabel/iBootSystemContainer + +[Service] +Type=oneshot +# At most 15 s; fprintd then starts without the node, and its next start +# (fprintd exits when idle) finds it. +ExecStart=/bin/sh -c 'i=0; while [ ! -e /dev/sep-bio ] && [ $i -lt 150 ]; do sleep 0.1; i=$((i+1)); done; exit 0' diff --git a/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf b/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf index bfa2385635b435..4a78939d5b7e44 100644 --- a/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf +++ b/tools/aurora-sep/aurora-touchid/fprintd-aurora.conf @@ -1,12 +1,13 @@ [Unit] -After=apple-sep.service +# aurora-touchid-device.service waits for /dev/sep-bio before fprintd starts: +# a DeviceAllow= path is resolved to a device number when fprintd's cgroup is +# set up, before any ExecStartPre= runs, and is dropped if the node does not +# exist yet. aurora-sep-ready.service does the same where the aurora-sep +# package is installed. +Wants=aurora-touchid-device.service +After=apple-sep.service aurora-touchid-device.service aurora-sep-ready.service [Service] -# apple-sep.service only runs modprobe; /dev/sep-bio appears a few seconds -# later, once the enclave is up. Wait for it (at most 15 s) so fprintd does not -# start, find no device and cache "No devices available" until it idles out. -ExecStartPre=/bin/sh -c 'i=0; while [ ! -e /dev/sep-bio ] && [ $i -lt 150 ]; do sleep 0.1; i=$((i+1)); done; exit 0' -# Allow the misc class rather than the node: a path rule is resolved to a -# device number when the cgroup is set up, before ExecStartPre runs, and is -# dropped if /dev/sep-bio does not exist yet. -DeviceAllow=char-misc rw +# Only the Touch ID node, not the whole misc class (uinput, fuse, kvm, +# device-mapper control, ...). +DeviceAllow=/dev/sep-bio rw diff --git a/tools/aurora-sep/tests/test_touchid_package.py b/tools/aurora-sep/tests/test_touchid_package.py new file mode 100644 index 00000000000000..c276cbd38e7035 --- /dev/null +++ b/tools/aurora-sep/tests/test_touchid_package.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""The aurora-touchid package (Omarchy): fprintd gets /dev/sep-bio only, not the whole misc +device class, and starts after the node exists; the PKGBUILD's checksums match its files.""" +import configparser +import hashlib +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +PKG = Path(__file__).resolve().parents[1] / 'aurora-touchid' + + +def unit(path): + cp = configparser.ConfigParser(strict=False, interpolation=None) + cp.optionxform = str + cp.read_string(path.read_text()) + return cp + + +def words(cp, section, key): + return [w for line in cp.get(section, key, fallback='').splitlines() for w in line.split()] + + +class TouchIdPackageTest(unittest.TestCase): + def test_fprintd_gets_only_the_touch_id_node(self): + text = (PKG / 'fprintd-aurora.conf').read_text() + rules = [l.split('=', 1)[1].strip() for l in text.splitlines() if l.startswith('DeviceAllow=')] + self.assertEqual(rules, ['/dev/sep-bio rw']) + self.assertNotIn('char-misc', ''.join(rules)) + # No wait inside fprintd's own start: the path rule is resolved before ExecStartPre= runs. + self.assertFalse(any(l.startswith('ExecStartPre') for l in text.splitlines())) + + def test_fprintd_starts_after_the_node_is_there(self): + dropin = unit(PKG / 'fprintd-aurora.conf') + self.assertIn('aurora-touchid-device.service', words(dropin, 'Unit', 'After')) + self.assertIn('aurora-touchid-device.service', words(dropin, 'Unit', 'Wants')) + self.assertIn('aurora-sep-ready.service', words(dropin, 'Unit', 'After')) + wait = unit(PKG / 'aurora-touchid-device.service') + self.assertIn('fprintd.service', words(wait, 'Unit', 'Before')) + self.assertIn('apple-sep.service', words(wait, 'Unit', 'After')) + self.assertEqual(wait.get('Service', 'Type'), 'oneshot') + self.assertIn('/dev/sep-bio', wait.get('Service', 'ExecStart')) + + def test_the_wait_ends(self): + cmd = unit(PKG / 'aurora-touchid-device.service').get('Service', 'ExecStart') + script = re.match(r"/bin/sh -c '(.*)'$", cmd).group(1).replace('/dev/sep-bio', '/nonexistent/sep-bio') + script = script.replace('-lt 150', '-lt 3') + self.assertEqual(subprocess.run(['sh', '-c', script], timeout=10).returncode, 0) + + def test_pkgbuild_installs_and_checks_every_source(self): + text = (PKG / 'PKGBUILD').read_text() + sources = re.findall(r"'([^']+)'", text.split('source=(', 1)[1].split(')', 1)[0]) + sums = re.findall(r"'([0-9a-f]{64})'", text.split('sha256sums=(', 1)[1].split(')', 1)[0]) + self.assertEqual(len(sources), len(sums)) + for name, digest in zip(sources, sums): + self.assertEqual(hashlib.sha256((PKG / name).read_bytes()).hexdigest(), digest, name) + self.assertIn('aurora-touchid-device.service', sources) + self.assertIn('"$pkgdir/usr/lib/systemd/system/aurora-touchid-device.service"', text) + + @unittest.skipUnless(shutil.which('systemd-analyze'), 'systemd-analyze is needed') + def test_units_verify(self): + with tempfile.TemporaryDirectory() as d: + d = Path(d) + (d / 'fprintd.service.d').mkdir() + (d / 'fprintd.service').write_text('[Unit]\nDescription=stub\n[Service]\nExecStart=/bin/true\n') + shutil.copy(PKG / 'fprintd-aurora.conf', d / 'fprintd.service.d/aurora.conf') + shutil.copy(PKG / 'aurora-touchid-device.service', d) + r = subprocess.run(['systemd-analyze', 'verify', '--man=no', + str(d / 'aurora-touchid-device.service'), str(d / 'fprintd.service')], + capture_output=True, text=True, env={'SYSTEMD_UNIT_PATH': f'{d}:', 'PATH': '/usr/bin:/bin'}) + self.assertNotIn('aurora-touchid-device', r.stderr) + self.assertNotIn('aurora.conf', r.stderr) + + +if __name__ == '__main__': + unittest.main() From 4e07891f0bc1fc9a7f54d72ebe3785dd0c0f21a3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 20:54:59 +0100 Subject: [PATCH 0455/1514] dt-bindings: power: add the Apple T8152 PSD service On T8152 the video decoder and the USB4 routers and their PHYs are powered through PMGR2 PSD services instead of PMGR power-state registers. Each service has a 0x100-byte block, given by its node's reg, with a target state, an acknowledge bit and the current state. The address comes from reg, not from the service number: the USB controllers' service numbers point at blocks that abort when read. Describe one service per node as a power domain, with an optional apple,always-on for a service whose consumers cannot restore what another agent set up in its blocks yet. Co-developed-by: Acelogic Signed-off-by: Acelogic Signed-off-by: Thomas Glanzmann --- .../bindings/power/apple,t8152-psd.yaml | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Documentation/devicetree/bindings/power/apple,t8152-psd.yaml diff --git a/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml b/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml new file mode 100644 index 00000000000000..fb5b6afd10a4ac --- /dev/null +++ b/Documentation/devicetree/bindings/power/apple,t8152-psd.yaml @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/power/apple,t8152-psd.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 PMGR2 PSD service + +maintainers: + - Thomas Glanzmann + +description: + On T8152, the video decoder, USB4 routers and their PHYs use PMGR2 PSD + services. The reg property identifies the 0x100-byte register block for + each service. The block contains a target-state request, an acknowledge + bit and the current state (0 powered, 6 cold). Reading the state consumes + the acknowledge. One node describes one service as a power domain. + +allOf: + - $ref: power-domain.yaml# + +properties: + compatible: + const: apple,t8152-psd + + reg: + maxItems: 1 + + '#power-domain-cells': + const: 0 + + label: + description: The service's name, for the power domain. + + apple,always-on: + type: boolean + description: + Keep the service powered. For a service whose consumers cannot yet + restore the state another agent set up in its blocks, such as a PHY + configured by the bootloader. + +required: + - compatible + - reg + - '#power-domain-cells' + +unevaluatedProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + power-controller@303a13200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13200 0x0 0x100>; + #power-domain-cells = <0>; + label = "avd"; + }; + }; From 5eaa2136d623c0d4c97f6285222e901da3675150 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 20:54:59 +0100 Subject: [PATCH 0456/1514] pmdomain: apple: add the T8152 PSD power domains Provide each T8152 PMGR2 PSD service as a power domain. Power-on requests state 0 and power-off the cold state 6. The driver waits for the acknowledge before it reads the state, because reading the state consumes the acknowledge. A service marked apple,always-on is powered at probe and kept on. Otherwise the domain starts in the state the hardware reports, so genpd powers off a service that nothing uses. The consumers include IRQ-safe devices, the DARTs, so the domains are IRQ-safe and a transition is polled atomically, as the PMGR power states are. On the J873g the AVD service (50) reaches state 0 in 390-500 us and the cold state in about 240 us; the timeout is 10 ms. The AVD and the USB4 routers' CIO services, which so far each had their own variant of this, use it. It has its own Kconfig symbol, APPLE_PMGR_PSD, on by default with ARCH_APPLE and built in by the shared asahi.config profile. Signed-off-by: Thomas Glanzmann --- arch/arm64/configs/asahi.config | 1 + drivers/pmdomain/apple/Kconfig | 12 +++ drivers/pmdomain/apple/Makefile | 1 + drivers/pmdomain/apple/pmgr-psd.c | 151 ++++++++++++++++++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 drivers/pmdomain/apple/pmgr-psd.c diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index 3173021d4f19d8..3702688ad75c6f 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -156,6 +156,7 @@ CONFIG_SECURITY_LOCKDOWN_LSM=y CONFIG_SECURITY_LOCKDOWN_LSM_EARLY=y CONFIG_LOCK_DOWN_KERNEL_FORCE_NONE=y CONFIG_APPLE_PMGR_PWRSTATE=y +CONFIG_APPLE_PMGR_PSD=y CONFIG_APPLE_T6041_CIO_RECONFIG=y CONFIG_APPLE_PMC=y CONFIG_APPLE_CLUSTER_PWRGATE=y diff --git a/drivers/pmdomain/apple/Kconfig b/drivers/pmdomain/apple/Kconfig index 118bcd17362426..252cceba3c561b 100644 --- a/drivers/pmdomain/apple/Kconfig +++ b/drivers/pmdomain/apple/Kconfig @@ -26,6 +26,18 @@ config APPLE_PMGR_PWRSTATE_KUNIT_TEST and need no Apple hardware. Also check the T6000 GFX missing-parent wait, its timeout, and the separate actual-state acknowledgment. +config APPLE_PMGR_PSD + bool "Apple T8152 PMGR service power domains" + depends on ARCH_APPLE || COMPILE_TEST + depends on PM && OF + select PM_GENERIC_DOMAINS + default ARCH_APPLE + help + The T8152 PMGR switches some blocks, the video decoder and the + USB4 routers and their PHYs, through service power states (PSD) + rather than PMGR power state registers. This driver offers each + service as a generic power domain. + config APPLE_T6041_CIO_RECONFIG bool "Apple T6041 CIO cluster reconfiguration" depends on OF diff --git a/drivers/pmdomain/apple/Makefile b/drivers/pmdomain/apple/Makefile index 351773930cb845..34b8898eff9111 100644 --- a/drivers/pmdomain/apple/Makefile +++ b/drivers/pmdomain/apple/Makefile @@ -8,3 +8,4 @@ obj-$(CONFIG_APPLE_PMP_DRAM_KUNIT_TEST) += pmp-dram-test.o obj-$(CONFIG_APPLE_PMC) += pmc.o obj-$(CONFIG_APPLE_PMP_ANE_KUNIT_TEST) += pmp-ane-test.o obj-$(CONFIG_APPLE_PMP_FLOOR_KUNIT_TEST) += pmp-floor-gov-test.o +obj-$(CONFIG_APPLE_PMGR_PSD) += pmgr-psd.o diff --git a/drivers/pmdomain/apple/pmgr-psd.c b/drivers/pmdomain/apple/pmgr-psd.c new file mode 100644 index 00000000000000..04bbf0d35e9486 --- /dev/null +++ b/drivers/pmdomain/apple/pmgr-psd.c @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T8152 PMGR2 PSD services as power domains. + * + * Each service has a 0x100 byte register block: the target state at +0x90, + * the acknowledge in bit 0 of +0xbc, and the current state in bits 2:0 of + * +0x80 (0 powered, 6 cold). Reading the state consumes the acknowledge, so + * the state is read only once the acknowledge is set. + * + * The consumers include IRQ-safe devices (DARTs), so the domains are IRQ-safe + * and a transition is polled atomically, as for the PMGR power states. + */ +#include +#include +#include +#include +#include +#include +#include + +#define APPLE_PSD_STATE 0x80 +#define APPLE_PSD_STATE_CUR GENMASK(2, 0) +#define APPLE_PSD_TARGET 0x90 +#define APPLE_PSD_ACK 0xbc +#define APPLE_PSD_ACK_DONE BIT(0) + +#define APPLE_PSD_ON 0 +#define APPLE_PSD_COLD 6 + +#define APPLE_PSD_TIMEOUT_US 10000 + +struct apple_psd { + struct generic_pm_domain genpd; + struct device *dev; + void __iomem *regs; +}; + +static u32 apple_psd_state(struct apple_psd *psd) +{ + return readl(psd->regs + APPLE_PSD_STATE) & APPLE_PSD_STATE_CUR; +} + +static bool apple_psd_reached(struct apple_psd *psd, u32 target, u32 *ack, + u32 *state) +{ + *ack = readl(psd->regs + APPLE_PSD_ACK); + if (!(*ack & APPLE_PSD_ACK_DONE)) + return false; + *state = apple_psd_state(psd); + return *state == target; +} + +static int apple_psd_set_state(struct generic_pm_domain *genpd, u32 target) +{ + struct apple_psd *psd = container_of(genpd, struct apple_psd, genpd); + u32 ack = 0, state; + bool done; + int ret; + + state = apple_psd_state(psd); + if (state == target) + return 0; + writel(target, psd->regs + APPLE_PSD_TARGET); + ret = read_poll_timeout_atomic(apple_psd_reached, done, done, 1, + APPLE_PSD_TIMEOUT_US, false, psd, target, + &ack, &state); + if (ret) { + dev_err(psd->dev, "%s: state %u not reached: ack %#x, state %u\n", + genpd->name, target, ack, state); + return ret; + } + return 0; +} + +static int apple_psd_power_on(struct generic_pm_domain *genpd) +{ + return apple_psd_set_state(genpd, APPLE_PSD_ON); +} + +static int apple_psd_power_off(struct generic_pm_domain *genpd) +{ + return apple_psd_set_state(genpd, APPLE_PSD_COLD); +} + +static void apple_psd_remove_provider(void *data) +{ + struct apple_psd *psd = data; + + of_genpd_del_provider(psd->dev->of_node); + pm_genpd_remove(&psd->genpd); +} + +static int apple_psd_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct apple_psd *psd; + bool is_off; + int ret; + + psd = devm_kzalloc(dev, sizeof(*psd), GFP_KERNEL); + if (!psd) + return -ENOMEM; + psd->dev = dev; + psd->regs = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(psd->regs)) + return PTR_ERR(psd->regs); + + if (of_property_read_string(np, "label", &psd->genpd.name)) + psd->genpd.name = dev_name(dev); + psd->genpd.power_on = apple_psd_power_on; + psd->genpd.power_off = apple_psd_power_off; + psd->genpd.flags = GENPD_FLAG_IRQ_SAFE; + + if (of_property_read_bool(np, "apple,always-on")) { + psd->genpd.flags |= GENPD_FLAG_ALWAYS_ON; + ret = apple_psd_power_on(&psd->genpd); + if (ret) + return ret; + } + is_off = apple_psd_state(psd) != APPLE_PSD_ON; + + ret = pm_genpd_init(&psd->genpd, NULL, is_off); + if (ret) + return ret; + ret = of_genpd_add_provider_simple(np, &psd->genpd); + if (ret) { + pm_genpd_remove(&psd->genpd); + return ret; + } + return devm_add_action_or_reset(dev, apple_psd_remove_provider, psd); +} + +static const struct of_device_id apple_psd_match[] = { + { .compatible = "apple,t8152-psd" }, + {} +}; +MODULE_DEVICE_TABLE(of, apple_psd_match); + +static struct platform_driver apple_psd_driver = { + .probe = apple_psd_probe, + .driver = { + .name = "apple-pmgr-psd", + .of_match_table = apple_psd_match, + .suppress_bind_attrs = true, + }, +}; +module_platform_driver(apple_psd_driver); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("Apple T8152 PMGR2 PSD power domains"); From 5907bb1b145ac52e6e3d434815fb477262989f12 Mon Sep 17 00:00:00 2001 From: Matt Date: Sun, 22 Nov 2026 17:12:24 -0500 Subject: [PATCH 0457/1514] soc: apple: sep: wipe capture buffers on rejected reads read_capture() wraps its receive buffer in Capture only after SPI transfer and CRC validation. A bus error after a partial or complete receive, or a checksum mismatch, frees the buffer without running Capture's wiping destructor. Construct the wiping owner before the transfer so every subsequent error return clears initialized receive bytes. Keep successful ownership and the existing allocation and input-validation behavior unchanged. Add a host regression using the production read function and destructor with synthetic SPI and allocation boundaries. All nine cases pass; the unpatched source fails the three receive-error cleanup cases. This is buffer-lifetime hardening; no information disclosure to an unprivileged caller has been demonstrated. Fixes: c1240e70b3c9 ("soc: apple: add Apple SEP driver (Touch ID and key sealing)") Signed-off-by: Matt --- drivers/soc/apple/sensor.rs | 7 +- .../tests/capture-error-wipe/README.md | 9 ++ .../tests/capture-error-wipe/cases.rs | 105 ++++++++++++++++++ .../tests/capture-error-wipe/prefix.rs | 89 +++++++++++++++ .../tests/capture-error-wipe/run.py | 72 ++++++++++++ 5 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 tools/aurora-sep/tests/capture-error-wipe/README.md create mode 100644 tools/aurora-sep/tests/capture-error-wipe/cases.rs create mode 100644 tools/aurora-sep/tests/capture-error-wipe/prefix.rs create mode 100644 tools/aurora-sep/tests/capture-error-wipe/run.py diff --git a/drivers/soc/apple/sensor.rs b/drivers/soc/apple/sensor.rs index 5e6a96afb43ecd..19c157f0f3f0b5 100644 --- a/drivers/soc/apple/sensor.rs +++ b/drivers/soc/apple/sensor.rs @@ -842,6 +842,11 @@ pub(crate) fn read_capture(length: u32) -> core::result::Result core::result::Result c, + Err(_) => panic!("unexpected error"), + }; + assert_eq!(&c.bytes()[..10], &[7; 10]); + FREED.with(|v| assert!(v.borrow().is_empty())); + drop(c); + wiped(); +} +#[test] +fn zero_length_no_io() { + init(); + assert!(matches!(read_capture(0), Err(CaptureError::Length(0)))); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn crc_only_no_io() { + init(); + assert!(matches!(read_capture(2), Err(CaptureError::Length(2)))); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn over_max_no_io() { + init(); + assert!(matches!( + read_capture(MAX_CAPTURE as u32 + 1), + Err(CaptureError::Length(_)) + )); + CALLS.with(|v| assert_eq!(v.get(), 0)); +} +#[test] +fn allocation_failure_no_io() { + init(); + ALLOC_FAIL.with(|v| v.set(true)); + assert!(matches!(read_capture(12), Err(CaptureError::NoMemory))); + CALLS.with(|v| assert_eq!(v.get(), 0)); + FREED.with(|v| assert!(v.borrow().is_empty())); +} +#[test] +fn resize_failure_no_image_written() { + init(); + RESIZE_FAIL.with(|v| v.set(true)); + assert!(matches!(read_capture(12), Err(CaptureError::NoMemory))); + CALLS.with(|v| assert_eq!(v.get(), 0)); + FREED.with(|v| assert_eq!(&*v.borrow(), &[Vec::::new()])); +} diff --git a/tools/aurora-sep/tests/capture-error-wipe/prefix.rs b/tools/aurora-sep/tests/capture-error-wipe/prefix.rs new file mode 100644 index 00000000000000..1a554a9e5d5713 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/prefix.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#![allow(dead_code)] +use std::cell::{Cell, RefCell}; +use std::ops::{Deref, DerefMut}; +const GFP_KERNEL: u32 = 0; +const CRC_LEN: usize = 2; +const MAX_CAPTURE: usize = 0x10000; +const CMD_LEN: usize = 7; +const READ_CMD_LEN: usize = 11; +const CMD_READ_PREFIX: [u8; CMD_LEN] = [0x80, 0x13, 0x00, 0x0b, 0x00, 0x00, 0x00]; +#[derive(Debug)] +struct Error(i32); +impl Error { + fn from_errno(e: i32) -> Self { + Self(e) + } +} +thread_local! { + static FREED:RefCell>>=const{RefCell::new(Vec::new())}; + static FRAME:RefCell>=const{RefCell::new(Vec::new())}; + static RC:Cell=const{Cell::new(0)}; + static PARTIAL:Cell=const{Cell::new(false)}; + static ALLOC_FAIL:Cell=const{Cell::new(false)}; + static RESIZE_FAIL:Cell=const{Cell::new(false)}; + static CALLS:Cell=const{Cell::new(0)}; +} +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _f: u32) -> Result { + if ALLOC_FAIL.with(|v| v.get()) { + Err(Error(-12)) + } else { + Ok(Self(Vec::with_capacity(n))) + } + } + fn resize(&mut self, n: usize, b: u8, _f: u32) -> Result<(), Error> { + if RESIZE_FAIL.with(|v| v.get()) { + Err(Error(-12)) + } else { + self.0.resize(n, b); + Ok(()) + } + } +} +impl Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { + &self.0 + } +} +impl DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { + &mut self.0 + } +} +// Only u8 is instantiated; the generic hook records the raw initialized bytes. +impl Drop for KVec { + fn drop(&mut self) { + assert_eq!(std::mem::size_of::(), 1); + let b = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::(), self.0.len()) }; + FREED.with(|v| v.borrow_mut().push(b.to_vec())); + } +} +unsafe fn sep_sensor_xfer2( + tx: *const std::ffi::c_void, + tn: usize, + rx: *mut std::ffi::c_void, + rn: usize, +) -> i32 { + CALLS.with(|v| v.set(v.get() + 1)); + assert_eq!(tn, READ_CMD_LEN); + let cmd = unsafe { std::slice::from_raw_parts(tx.cast::(), tn) }; + assert_eq!(&cmd[..CMD_LEN], &CMD_READ_PREFIX); + assert_eq!( + u32::from_le_bytes(cmd[CMD_LEN..].try_into().unwrap()), + rn as u32 + ); + FRAME.with(|f| { + let f = f.borrow(); + let n = if PARTIAL.with(|v| v.get()) { + rn / 2 + } else { + rn + }; + assert!(f.len() >= n); + unsafe { std::ptr::copy_nonoverlapping(f.as_ptr(), rx.cast::(), n) } + }); + RC.with(|v| v.get()) +} diff --git a/tools/aurora-sep/tests/capture-error-wipe/run.py b/tools/aurora-sep/tests/capture-error-wipe/run.py new file mode 100644 index 00000000000000..b40934ef456276 --- /dev/null +++ b/tools/aurora-sep/tests/capture-error-wipe/run.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production capture owner/parser with synthetic SPI and allocation.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def function(text, signature): + start = text.index(signature) + brace = text.index('{', start) + depth = 1 + end = brace + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def main(): + here = Path(__file__).resolve().parent + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, + default=here.parents[3] / 'drivers/soc/apple/sensor.rs') + parser.add_argument('--expect-failures', type=int, choices=(0, 3), default=0) + args = parser.parse_args() + text = args.source.read_text() + header = (here / 'prefix.rs').read_text() + for name in ('CMD_LEN', 'READ_CMD_LEN', 'CMD_READ_PREFIX', 'CRC_LEN', 'MAX_CAPTURE'): + pattern = r'(?:pub\(crate\) )?const ' + name + r'\s*:[^\n]+;' + real = re.search(pattern, text).group(0).replace('pub(crate) ', '') + fake = re.search(pattern, header).group(0) + if re.sub(r'\s+', '', real) != re.sub(r'\s+', '', fake): + raise SystemExit('Fixture constant differs from production: ' + name) + start = text.index('pub(crate) struct Capture(') + end = text.index('pub(crate) fn read_capture(', start) + production = (function(text, 'fn crc16_ansi(') + '\n' + text[start:end] + + function(text, 'pub(crate) fn read_capture(')) + harness = header + '\n' + production + '\n' + (here / 'cases.rs').read_text() + with tempfile.TemporaryDirectory(prefix='sep-capture-regression-') as name: + temp = Path(name) + source = temp / 'harness.rs' + binary = temp / 'tests' + source.write_text(harness) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '--test', + str(source), '-o', str(binary)], check=True, timeout=90) + result = subprocess.run([str(binary), '--test-threads=1'], text=True, + capture_output=True, timeout=90) + print(result.stdout, end='') + print(result.stderr, end='') + summary = re.search(r'test result: (\w+)\. (\d+) passed; (\d+) failed;', result.stdout) + if not summary: + raise SystemExit('Missing test summary') + passed, failed = int(summary[2]), int(summary[3]) + expected_code = 101 if args.expect_failures else 0 + if (passed, failed, result.returncode) != (9 - args.expect_failures, + args.expect_failures, expected_code): + raise SystemExit('Unexpected regression result') + print(json.dumps({'passed': passed, 'failed': failed, + 'expected_failures': args.expect_failures, + 'source_sha256': hashlib.sha256(text.encode()).hexdigest(), + 'production_excerpts_sha256': hashlib.sha256(production.encode()).hexdigest(), + 'hardware_access': False}, sort_keys=True)) + + +if __name__ == '__main__': + main() From 471593d0fab73739029b3c518d286ad88e4537f6 Mon Sep 17 00:00:00 2001 From: Matt Date: Sun, 22 Nov 2026 17:12:24 -0500 Subject: [PATCH 0458/1514] ci: sep: run the capture wipe suite Register tools/aurora-sep/tests/capture-error-wipe in the SEP source checks. It runs under the job's pinned Rust 1.85.0 toolchain. Signed-off-by: Matt --- .github/workflows/sep-source.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 3f824af0d4f61c..04fe12716ee83f 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -59,6 +59,9 @@ jobs: python3 -O -m unittest tools/aurora-sep/tests/test_store_open_errors.py -v python3 -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v python3 -O -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v + - name: Test capture wiping on rejected reads + run: | + python3 -I tools/aurora-sep/tests/capture-error-wipe/run.py - name: Test selected-policy diagnostics run: | python3 -m unittest tools/aurora-sep/tests/test_diag_policy.py tools/aurora-sep/tests/test_diag_sensor.py -v From 8fe9ce4e81c23f7deea53e58813621cf053e0bf9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:26:35 +1100 Subject: [PATCH 0459/1514] tools/aurora-sep: install from a root-owned copy of the checked downloads install_all downloaded the release files into a mktemp directory owned by the invoking user and checked their sha256 there as that user. Root then installed from the same directory: `pacman -U "$work"/*.pkg.tar.zst`, a glob over whatever the directory held. The frozen-dependency helper, and the pacman hook that runs it, were written there by the user and run by root. The M3 Max kit ran its root copy of this script from the user's directory and installed its runner from there, with no second check. - install_all: after the user-side check, work_to_root copies each listed file into a directory root owns. The user's shell opens the source, so root opens nothing the user named. It checks each sha256 again as root and uses only that copy from then on. pacman -U gets the checked archives by name, sorted as the glob was. The set-aside Mesa package, the frozen-dependency helper and its outputs, the Pro session migrator and the GPU check are written there through $sudo. - --m3max-kit under sudo: root copies the script without following a link, only as a regular file of the invoking user's, and checks its sha256. It runs that copy with its own directory as the kit's work directory, where it downloads and checks the kit's files itself. A root run refuses a work directory that is not root's own. Without sudo (running as root already) nothing changes. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 1 + tools/aurora-sep/install-aurora-sep.sh | 112 +++++++++- tools/aurora-sep/tests/test_m3_persistent.py | 2 + tools/aurora-sep/tests/test_m3_pro_mesa.py | 10 +- tools/aurora-sep/tests/test_root_staging.py | 217 +++++++++++++++++++ 5 files changed, 328 insertions(+), 14 deletions(-) create mode 100644 tools/aurora-sep/tests/test_root_staging.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index d3531133042739..d90f8c15c45616 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -78,6 +78,7 @@ jobs: python3 -m unittest discover -s tools/aurora-sep/tests -p test_kernel_log_anchor.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_collect_handover.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_touchid_package.py -v + python3 -m unittest discover -s tools/aurora-sep/tests -p test_root_staging.py -v rust-build: runs-on: ubuntu-24.04 diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index ff54c35f0964b3..685fe49a14d0d0 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -759,7 +759,7 @@ m3_pro_perf_activate() { $(cat /opt/mesa-m3/pro-vulkan/share/mesa-m3/profile) == t6030-pro-vulkan-legacy-hal ]] || die "paired Pro Mesa installation is incomplete" user=$(m3_pro_mesa_user) if [[ $user != root ]]; then - printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d > "$work/migrate-pro-session.py" + printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d | $sudo tee "$work/migrate-pro-session.py" >/dev/null $sudo runuser -u "$user" -- python3 - "$user" < "$work/migrate-pro-session.py" || die "could not update the managed native Pro session" fi $sudo systemctl enable mesa-m3-pro-performance.service @@ -2694,8 +2694,8 @@ m3_pro_mesa_set_aside() { local file file=$(m3_pro_mesa_file) [[ -n $M3_PRO_MESA_PACKAGE && -f $work/$file ]] || return 0 - mkdir -p "$work/m3-pro" - mv "$work/$file" "$work/m3-pro/" + $sudo mkdir -p "$work/m3-pro" + $sudo mv -- "$work/$file" "$work/m3-pro/" } # The M3_PRO_MESA_NEEDS entries this Mac does not satisfy, one "name version (needs min or @@ -3875,7 +3875,7 @@ frozen_dependency_prepare() { for archive in "$@"; do args+=(--candidate "$archive"); done args+=(--allow-remove linux-asahi --allow-remove linux-asahi-headers --allow-remove m1n1 --allow-remove mesa-m3-g15g) - cat >"$work/frozen-dependencies.py" <<'FROZEN_DEPENDENCIES_PY' + $sudo tee "$work/frozen-dependencies.py" >/dev/null <<'FROZEN_DEPENDENCIES_PY' #!/usr/bin/env python3 """Admit missing repository dependencies without changing installed packages.""" import argparse @@ -4222,7 +4222,7 @@ if __name__ == "__main__": sys.exit(1) FROZEN_DEPENDENCIES_PY say "Resolving only missing dependencies while preserving this image's package holds" - $sudo python3 "$work/frozen-dependencies.py" "${args[@]}" >"$work/dependency-result.json" || + $sudo python3 "$work/frozen-dependencies.py" "${args[@]}" | $sudo tee "$work/dependency-result.json" >/dev/null || die "could not admit a missing-only dependency transaction. Nothing was installed. The package holds were preserved." FROZEN_TRANSACTION_CONFIG=$(python3 - "$work/dependency-result.json" <<'FROZEN_CONFIG_PY' import json, sys @@ -4230,7 +4230,7 @@ print(json.load(open(sys.argv[1]))['transaction_config']) FROZEN_CONFIG_PY ) $sudo test -f "$FROZEN_TRANSACTION_CONFIG" || die "missing admitted package transaction configuration" - python3 - "$work/dependency-result.json" >"$work/dependency-files" <<'FROZEN_FILES_PY' + python3 - "$work/dependency-result.json" <<'FROZEN_FILES_PY' | $sudo tee "$work/dependency-files" >/dev/null import json, sys plan = json.load(open(sys.argv[1])) for filename in list(plan['candidate_sha256']) + [p['file'] for p in plan['dependencies']]: @@ -4270,6 +4270,35 @@ package_database_check() { Run 'omarchy update', reboot, then retry. Installing repository dependencies before a full update would be a partial upgrade. Nothing was installed." } +# The downloads were fetched and checked as the invoking user, in that user's own temporary +# directory, so another process of that user could still change them before root uses them. +# Under sudo, copy each listed file ("file sha256" lines on stdin) into a directory root owns +# (the user's shell opens the source, so root itself opens nothing the user named), check its +# sha256 again as root there, and use only that copy from then on: $work names it, and +# candidate_archives is rewritten to it. The directory is 0700 while files arrive and 0755 after +# (the user may read the packages, not change them). +WORK_ROOT_OWNED=0 +INSTALL_ARCHIVES=() +work_to_root() { + local old=$work new file sha + [[ -n $sudo ]] || return 0 + new=$($sudo mktemp -d) || die "could not make a work directory for root. Nothing was installed." + work=$new + WORK_ROOT_OWNED=1 + while read -r file sha; do + [[ -n $file ]] || continue + [[ $file != */* && $file != .* && $sha =~ ^[0-9a-f]{64}$ ]] || + die "unexpected release file entry '$file'. Nothing was installed." + $sudo sh -c 'umask 022 && cat >"$1"' _ "$new/$file" <"$old/$file" || + die "could not copy $file for root. Nothing was installed." + [[ $($sudo sha256sum -- "$new/$file" | cut -d' ' -f1) == "$sha" ]] || + die "$file changed after its checksum was checked. Nothing was installed." + done + $sudo chmod 0755 "$new" + candidate_archives=("${candidate_archives[@]/#"$old/"/"$new/"}") + rm -rf -- "$old" +} + install_all() { local entry file sha kernel chain rc local -a entries candidate_archives=() @@ -4343,6 +4372,9 @@ install_all() { [[ -n $file ]] || continue candidate_archives+=("$work/$file") done < <(desktop_fixes_files) + # Root installs and runs only its own checked copy of what was downloaded (work_to_root). + work_to_root < <(printf '%s\n' "${entries[@]}"; desktop_fixes_files) + INSTALL_ARCHIVES=("${candidate_archives[@]}") if ((M3_GPU_PERSISTENT)); then m3_persistent_package_check "$work/${M3_PRO_MESA_PACKAGE%% *}"; fi m3_pro_perf_verify m3_pro_mesa_set_aside @@ -7349,7 +7381,7 @@ m3_install_cleanup() { fi fi fi - if ((FROZEN_PACKAGES)); then $sudo rm -rf "${work:-}" + if ((FROZEN_PACKAGES || WORK_ROOT_OWNED)); then $sudo rm -rf "${work:-}" else rm -rf "${work:-}"; fi return "$status" } @@ -7421,7 +7453,16 @@ m3_install_packages() { M3_PRO_MESA_RESULT=installed fi else - $sudo pacman -U --noconfirm --ask 4 "$work"/*.pkg.tar.zst + # The checked archives (no glob over the directory), less a package set aside below it. + local archive + local -a archives=() + for archive in "${INSTALL_ARCHIVES[@]}"; do + [[ $archive == "$work"/*.pkg.tar.zst && -f $archive ]] && archives+=("$archive") + done + ((${#archives[@]})) || die "no checked package archives to install. Nothing was installed." + # In the order the directory listing gave them before. + mapfile -t archives < <(printf '%s\n' "${archives[@]}" | sort) + $sudo pacman -U --noconfirm --ask 4 "${archives[@]}" fi if ((M3_PRO_PERF_SELECTED)) && [[ -f $work/$(m3_pro_mesa_file) ]]; then M3_PRO_MESA_RESULT=installed; fi if ((M3_GPU_PERSISTENT)); then @@ -8000,7 +8041,7 @@ m3_gpu_check_plan() { m3_gpu_check_install() { local sha m3_gpu_check_plan - m3_gpu_check_builtin >"$work/aurora-m3-gpu-check" + m3_gpu_check_builtin | $sudo tee "$work/aurora-m3-gpu-check" >/dev/null sha=$(sha256sum "$work/aurora-m3-gpu-check" | cut -d' ' -f1) $sudo python3 - "$work/aurora-m3-gpu-check" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" "$sha" <<'M3_CHECK_INSTALL_PY' import hashlib, os, stat, sys, tempfile @@ -10638,16 +10679,20 @@ m3max_kit_identity() { # This script, on disk, into the work directory: the runner the kit installs. From a pipe # (curl ... | bash) it can't be read again, so this release's copy is downloaded, and it must # install exactly what this one does (m3max_kit_identity). +M3MAX_KIT_SELF_SHA="" m3max_kit_self() { local out=$M3MAX_KIT_WORK/install-aurora-sep.sh theirs rc=0 if [[ $SELF_SOURCE == file && -f $SELF_PATH ]]; then cp "$SELF_PATH" "$out" [[ $(sha256sum "$out" | cut -d' ' -f1) == "$SELF_SHA256" ]] || die "this script changed while it ran. Nothing was changed." + M3MAX_KIT_SELF_SHA=$SELF_SHA256 return 0 fi say "Downloading this release's install-aurora-sep.sh, for the kit's runner" fetch_release_file "$RELEASE_URL/install-aurora-sep.sh" "$out" || rc=$? ((rc == 0)) || die "could not download install-aurora-sep.sh from $TAG (curl exit $rc). Nothing was changed." + # The hash root's copy must have, taken before the identity check reads the file. + M3MAX_KIT_SELF_SHA=$(sha256sum "$out" | cut -d' ' -f1) # shellcheck disable=SC2016 # expanded by that bash theirs=$(bash -c 'AURORA_SEP_SOURCE_ONLY=1 source "$1" >/dev/null 2>&1 && m3max_kit_identity' _ "$out" 2>/dev/null) || theirs="" [[ -n $theirs && $theirs == "$(m3max_kit_identity)" ]] || @@ -10656,6 +10701,15 @@ m3max_kit_self() { chmod 0755 "$out" } +# As root, the kit's work directory must be root's own: its files are run and installed as root. +m3max_kit_work_is_root() { + local owner mode + [[ -d $M3MAX_KIT_WORK && ! -L $M3MAX_KIT_WORK ]] || die "the kit's work directory $M3MAX_KIT_WORK is missing. Nothing was changed." + read -r owner mode < <(stat -c '%u %a' "$M3MAX_KIT_WORK") + [[ $owner == "$EUID" ]] && (((8#$mode & 8#022) == 0)) || + die "the kit's work directory $M3MAX_KIT_WORK is not root's own (owner $owner, mode $mode). Nothing was changed." +} + # How many restarts the plan takes at most, and roughly how long, for the consent screen. m3max_kit_estimate() { local e max @@ -10784,15 +10838,49 @@ m3max_kit_setup() { # [--yes] [--kit-work DIR] if [[ -z $M3MAX_KIT_WORK ]]; then M3MAX_KIT_WORK=$(mktemp -d); fi M3MAX_KIT_USER_NAME=${SUDO_USER:-$(id -un)} # The kit runs as root from here (its state, its checks of the EFI variables, its runner), from - # this script's copy on disk. + # this script's copy on disk. Root does not run or install files from the invoking user's + # directory: it copies this + # script's checked copy into a directory of its own, opening it without following a link and + # only as a regular file of the invoking user's, checks the sha256 of its copy, and runs that + # copy with its own directory as the kit's work directory, where it downloads and checks the + # kit's other files itself. if [[ -n $sudo ]]; then m3max_kit_self say "The kit runs as root from here on (sudo may ask for your password)." a=() ((M3MAX_KIT_YES == 0)) || a=(--yes) - exec $sudo --preserve-env=AURORA_RELEASE_URL,AURORA_RELEASES_API bash "$M3MAX_KIT_WORK/install-aurora-sep.sh" \ - --m3max-kit --kit-work "$M3MAX_KIT_WORK" "${a[@]}" + local rc=0 + # shellcheck disable=SC2016 # expanded by that bash + $sudo --preserve-env=AURORA_RELEASE_URL,AURORA_RELEASES_API bash -c ' + set -eu + d=$(mktemp -d) + if ! python3 -I - "$1" "$d/install-aurora-sep.sh" "$2" "$(id -u "$3")" <<"KIT_SELF_COPY_PY" +import hashlib, os, stat, sys +src, dst, want, uid = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]) +fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) +st = os.fstat(fd) +if not stat.S_ISREG(st.st_mode) or st.st_uid != uid or st.st_size > 64 << 20: + sys.exit("not a regular file of the invoking user") +with os.fdopen(fd, "rb") as f: + data = f.read(64 << 20) +if hashlib.sha256(data).hexdigest() != want: + sys.exit("its sha256 differs from the checked one") +out = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o755) +with os.fdopen(out, "wb") as f: + f.write(data) +KIT_SELF_COPY_PY + then + rm -rf "$d" + echo "install-aurora-sep: error: root could not take the kit script ($1) as checked. Nothing was changed." >&2 + exit 1 + fi + shift 3 + exec bash "$d/install-aurora-sep.sh" --m3max-kit --kit-work "$d" "$@"' \ + _ "$M3MAX_KIT_WORK/install-aurora-sep.sh" "$M3MAX_KIT_SELF_SHA" "$(id -un)" "${a[@]}" || rc=$? + rm -rf -- "$M3MAX_KIT_WORK" + exit "$rc" fi + m3max_kit_work_is_root [[ -f $M3MAX_KIT_WORK/install-aurora-sep.sh ]] || m3max_kit_self m3max_kit_preflight m3max_kit_consent diff --git a/tools/aurora-sep/tests/test_m3_persistent.py b/tools/aurora-sep/tests/test_m3_persistent.py index ecab5effcf8640..4074a4de9e14eb 100644 --- a/tools/aurora-sep/tests/test_m3_persistent.py +++ b/tools/aurora-sep/tests/test_m3_persistent.py @@ -255,6 +255,8 @@ def transaction_paths(self): return self.selection()+f''' chain=limine work="{work}" +# What install_all checked (m3_install_packages installs these by name). +INSTALL_ARCHIVES=("$work/matched.pkg.tar.zst") M3_LIMINE_DEFAULTS="{defaults}" M3_GRUB_DEFAULTS="{self.etc}/default/grub" M3_PROFILE_HOOK="{self.etc}/hooks/profile.hook" diff --git a/tools/aurora-sep/tests/test_m3_pro_mesa.py b/tools/aurora-sep/tests/test_m3_pro_mesa.py index f2ef380f777ade..ccff9c13220bb6 100644 --- a/tools/aurora-sep/tests/test_m3_pro_mesa.py +++ b/tools/aurora-sep/tests/test_m3_pro_mesa.py @@ -102,6 +102,10 @@ def tree(tc): return out +WORK_TO_ROOT = re.compile(r'sudo (mktemp -d|sh -c umask 022 && cat >"\$1" _ /\S+|' + r'sha256sum -- /\S+|chmod 0755 |rm -rf )$') + + def package_check_log(tc, text): lines = text.splitlines() queries = [i for i, line in enumerate(lines) if line == 'pacman -Qu --color never'] @@ -115,6 +119,8 @@ def package_check_log(tc, text): out = [] for line in lines: if line in ('pacman -Qu --color never', 'pacman -Sy --noconfirm', 'sudo pacman -Sy --noconfirm'): continue + # work_to_root: root's own checked copy of the downloads (not in 12.2). + if WORK_TO_ROOT.match(line): continue line = line.replace('pacman -Sy --noconfirm --ask 4 ', 'pacman -S --noconfirm --ask 4 ') out.append(line) return out @@ -1683,8 +1689,8 @@ def test_nothing_is_written_for_it_outside_the_package(self): 'rm -rf "$dir"', 'if $sudo gpasswd -a "$user" "$g" >/dev/null && m3_pro_mesa_in_group "$user" "$g"; then', 'if $sudo gpasswd -d "$u" "$g" >/dev/null; then', - 'mkdir -p "$work/m3-pro"', - 'mv "$work/$file" "$work/m3-pro/"', + '$sudo mkdir -p "$work/m3-pro"', + '$sudo mv -- "$work/$file" "$work/m3-pro/"', } # Commands in command position (line start, after a pipe, a list operator, if, then or $( ), # and redirections into a variable's path. diff --git a/tools/aurora-sep/tests/test_root_staging.py b/tools/aurora-sep/tests/test_root_staging.py new file mode 100644 index 00000000000000..83dc61995620ff --- /dev/null +++ b/tools/aurora-sep/tests/test_root_staging.py @@ -0,0 +1,217 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""install-aurora-sep.sh: what root installs or runs comes from a directory root owns, checked +there as root, and pacman gets the checked archives by name (no glob over the directory). The +same for the M3 Max kit's root run of this script.""" +import hashlib +import os +from pathlib import Path +import re +import stat +import subprocess +import tempfile +import unittest + +INSTALLER = Path(__file__).resolve().parents[1] / 'install-aurora-sep.sh' + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +class Staging(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + self.log = self.root / 'log' + # Stands in for sudo: records the call and runs it (as this user). + (self.bin / 'fakesudo').write_text(f'#!/bin/sh\necho "sudo $*" >>"{self.log}"\nexec "$@"\n') + (self.bin / 'pacman').write_text(f'#!/bin/sh\necho "pacman $*" >>"{self.log}"\n') + for f in self.bin.iterdir(): + f.chmod(0o755) + self.tmpdir = self.root / 'tmp' + self.tmpdir.mkdir() + + def sh(self, body): + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.tmpdir}' +die() {{ echo "DIED: $*"; exit 9; }} +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def downloads(self, **files): + d = Path(tempfile.mkdtemp(dir=self.tmpdir)) + for name, data in files.items(): + (d / name).write_bytes(data) + return d + + def stage(self, d, entries, then=''): + lines = '\n'.join(entries) + return self.sh(f""" +sudo=fakesudo +work='{d}' +candidate_archives=('{d}/a.pkg.tar.zst') +work_to_root <<'EOF' +{lines} +EOF +echo "work=$work" +echo "cand=${{candidate_archives[*]}}" +{then} +""") + + def test_copies_and_checks_into_a_new_directory(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A', 'tool.sh': b'T'}) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}', f'tool.sh {sha(b"T")}']) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + work = Path(re.search(r'^work=(.*)$', r.stdout, re.M).group(1)) + self.assertNotEqual(work, d) + self.assertFalse(d.exists()) # the user's copy is gone + self.assertEqual((work / 'a.pkg.tar.zst').read_bytes(), b'A') + self.assertEqual((work / 'tool.sh').read_bytes(), b'T') + self.assertEqual(stat.S_IMODE(work.stat().st_mode), 0o755) + self.assertIn(f'cand={work}/a.pkg.tar.zst', r.stdout) + self.assertIn('sha256sum', self.log.read_text()) # checked by the root side + + def test_a_file_changed_after_the_check_is_refused(self): + d = self.downloads(**{'a.pkg.tar.zst': b'changed'}) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}']) + self.assertEqual(r.returncode, 9) + self.assertIn('changed after its checksum was checked', r.stdout) + + def test_a_link_planted_in_place_of_a_download_is_refused(self): + target = self.root / 'secret' + target.write_bytes(b'S') + d = self.downloads() + (d / 'a.pkg.tar.zst').symlink_to(target) + r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}']) + self.assertEqual(r.returncode, 9) + + def test_odd_names_are_refused(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + for name in ('../a.pkg.tar.zst', '.hidden', 'x/y'): + with self.subTest(name): + r = self.stage(d, [f'{name} {sha(b"A")}']) + self.assertEqual(r.returncode, 9, r.stdout) + + def test_without_sudo_nothing_moves(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + r = self.sh(f"sudo=''\nwork='{d}'\ncandidate_archives=()\nwork_to_root &|])>\s*"\$work/', line), f'{name}: {line}') + self.assertIsNone(re.search(r'^\s*(mkdir|mv|cp|cat)\b[^|]*"?\$work/', line), f'{name}: {line}') + install_all = body('install_all') + self.assertIn('work_to_root < <(', install_all) + self.assertLess(install_all.index('work_to_root'), install_all.index('frozen_dependency_prepare')) + self.assertLess(install_all.index('work_to_root'), install_all.index('m3_install_packages')) + + +class KitRootCopy(unittest.TestCase): + """--m3max-kit under sudo: root runs its own checked copy, from its own directory.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + (self.bin / 'fakesudo').write_text('#!/bin/sh\nwhile [ "${1#--}" != "$1" ]; do shift; done\nexec "$@"\n') + (self.bin / 'fakesudo').chmod(0o755) + self.tmpdir = self.root / 'tmp' + self.tmpdir.mkdir() + self.copy = b'#!/bin/bash\necho "ran $0 $*"\n' + + def setup(self, tamper=''): + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.tmpdir}' +die() {{ echo "DIED: $*"; exit 9; }} +sudo=fakesudo +release_source() {{ :; }} +require_supported_soc() {{ :; }} +is_m3_max() {{ true; }} +m3max_kit_self() {{ + printf '%b' {self.copy.decode()!r} >"$M3MAX_KIT_WORK/install-aurora-sep.sh" + M3MAX_KIT_SELF_SHA=$(sha256sum "$M3MAX_KIT_WORK/install-aurora-sep.sh" | cut -d' ' -f1) + echo "user-work=$M3MAX_KIT_WORK" + {tamper} +}} +m3max_kit_setup --yes +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def test_root_runs_its_own_copy(self): + r = self.setup() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + user = re.search(r'^user-work=(.*)$', r.stdout, re.M).group(1) + m = re.search(r'^ran (\S+)/install-aurora-sep\.sh --m3max-kit --kit-work (\S+) --yes$', r.stdout, re.M) + self.assertIsNotNone(m, r.stdout) + self.assertEqual(m.group(1), m.group(2)) + self.assertNotEqual(m.group(1), user) + self.assertFalse(Path(user).exists()) + + def test_a_changed_copy_is_not_run(self): + r = self.setup(tamper='echo "echo evil" >>"$M3MAX_KIT_WORK/install-aurora-sep.sh"') + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + self.assertIn('could not take the kit script', r.stderr) + + def test_a_link_is_not_followed(self): + r = self.setup(tamper=f'cp "$M3MAX_KIT_WORK/install-aurora-sep.sh" "{self.root}/real"; ' + f'ln -sf "{self.root}/real" "$M3MAX_KIT_WORK/install-aurora-sep.sh"') + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + + def test_root_refuses_a_work_directory_it_does_not_own(self): + d = Path(tempfile.mkdtemp(dir=self.tmpdir)) + os.chmod(d, 0o777) + script = f""" +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +die() {{ echo "DIED: $*"; exit 9; }} +M3MAX_KIT_WORK='{d}' +m3max_kit_work_is_root +echo ok +""" + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertIn("is not root's own", r.stdout) + os.chmod(d, 0o700) + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertIn('ok', r.stdout) + + +if __name__ == '__main__': + unittest.main() From 821328e5550d3ecc63f03d75bdaba611d18fde11 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:47:36 +1100 Subject: [PATCH 0460/1514] phy: apple: atc: accept a drive-only DP request on PHYs without drive control The T8103-generation ATC PHYs (T8103, T8112, T600x, T602x) have no drive level control: the lanes keep the levels their tunables set up. Answering a drive request with -EOPNOTSUPP and special-casing that errno in the firmware-27 SetDriveSettings handler overloads an errno that the phy core (no .configure) and the T8132 branch (DP alt mode not up) also return. Do what the T8132 branch already does: a drive-only request succeeds with a debug line and leaves the lanes alone, and drive levels together with a rate or lane change stay -EINVAL. The firmware-27 handler passes every PHY error back to DCP again, so a real failure still fails the call. tools/asahi/atc-dp-drive-tests.py builds the production atcphy_dpphy_configure() against stubs and checks the request matrix for the T8103 generation, T8132's DP-off and DP-on answers and the T8122 handler, and that the drive handler has no errno special case; three mutations (the -EOPNOTSUPP answer, accepting drive levels with a rate, refusing every drive request) must fail it. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dptx-drive-v27.inc | 7 +- drivers/phy/apple/atc.c | 14 +- tools/asahi/atc-dp-drive-tests.py | 155 +++++++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 4 files changed, 167 insertions(+), 11 deletions(-) create mode 100755 tools/asahi/atc-dp-drive-tests.py diff --git a/drivers/gpu/drm/apple/dptx-drive-v27.inc b/drivers/gpu/drm/apple/dptx-drive-v27.inc index 35e62ceabd2f8b..4fabf1347a8cdb 100644 --- a/drivers/gpu/drm/apple/dptx-drive-v27.inc +++ b/drivers/gpu/drm/apple/dptx-drive-v27.inc @@ -103,12 +103,7 @@ static int dptxport_call_drive_v27(struct apple_epic_service *service, bool set, if (!dptx->atcphy) return -ENODEV; ret = phy_configure(dptx->atcphy, &opts); - /* - * A PHY without drive level control keeps the levels - * its tunables set; DCP's link training goes on with - * them, as with the firmware before 27. - */ - if (ret && ret != -EOPNOTSUPP) + if (ret) return ret; } for (u32 i = 0; i < count; i++) { diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 89ff2f9f1cc3f9..7eb71a540b45c9 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -4951,12 +4951,16 @@ static int atcphy_dpphy_configure(struct phy *phy, union phy_configure_opts *opt /* * These PHYs have no drive level control: the lanes keep the levels - * their tunables set up. Tell a drive level request apart from a bad - * one, so the caller can keep the levels it asked for. + * their tunables set up, as the T8132 branch above does. A drive-only + * request succeeds, so DCP's link training goes on with those levels; + * drive levels together with a rate change are not a request DCP makes. */ - if (opts->set_voltages) - return -EOPNOTSUPP; - if (opts->set_lanes) + if (opts->set_voltages && !opts->set_rate && !opts->set_lanes) { + dev_dbg(atcphy->dev, "DP drive request ignored (lane 0 swing %u pre %u)\n", + opts->voltage[0], opts->pre[0]); + return 0; + } + if (opts->set_voltages || opts->set_lanes) return -EINVAL; if (opts->set_rate) { diff --git a/tools/asahi/atc-dp-drive-tests.py b/tools/asahi/atc-dp-drive-tests.py new file mode 100755 index 00000000000000..be0c0e23bf710e --- /dev/null +++ b/tools/asahi/atc-dp-drive-tests.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""How the ATC PHY answers a DP drive level request, and what the firmware-27 drive call does with it. + +Builds the production atcphy_dpphy_configure() against stubs and runs it over +PHY generation, DP state and the request's set_voltages/set_rate/set_lanes. A +PHY without drive level control (the T8103 generation: T8103, T8112, T600x, +T602x) accepts a drive-only request and keeps the levels its tunables set, as +the T8132 branch does; a drive request together with a rate or lane change is +refused. The firmware-27 SetDriveSettings handler passes every PHY error back +to DCP (no errno is special), so a real failure still fails the call. + +--mutation names a change to the production source that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +MUTATIONS = { + # The PR's first version: a drive-only request answered -EOPNOTSUPP. + 'eopnotsupp': ('\t\treturn 0;\n\t}\n\tif (opts->set_voltages || opts->set_lanes)', + '\t\treturn -EOPNOTSUPP;\n\t}\n\tif (opts->set_voltages || opts->set_lanes)'), + # Accept drive levels that come with a rate change. + 'accept-with-rate': ('opts->set_voltages && !opts->set_rate && !opts->set_lanes', + 'opts->set_voltages && !opts->set_lanes'), + # The pre-PR refusal of every drive request. + 'refuse-drive': ('opts->set_voltages && !opts->set_rate && !opts->set_lanes', '0'), +} + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--mutation', choices=sorted(MUTATIONS)) +args = parser.parse_args() + +root = Path(__file__).resolve().parents[2] +atc_c = (root / 'drivers/phy/apple/atc.c').read_text() +drive_inc = (root / 'drivers/gpu/drm/apple/dptx-drive-v27.inc').read_text() + + +def function(source, marker): + start = source.index(marker) + opening = source.index('{', start) + end, depth = opening + 1, 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +configure = function(atc_c, 'static int atcphy_dpphy_configure(struct phy *phy,') +# Selected by the PHY's generation and hardware flags, never by a compatible. +assert 'compatible' not in configure and 'of_machine' not in configure + +# The firmware-27 drive call returns every PHY error to DCP unchanged. +drive = function(drive_inc, 'static int dptxport_call_drive_v27(') +call = drive[drive.index('ret = phy_configure(dptx->atcphy, &opts);'):] +assert re.match(r'ret = phy_configure\(dptx->atcphy, &opts\);\s*if \(ret\)\s*return ret;', call), \ + 'dptxport_call_drive_v27() must pass every phy_configure() error back' +assert 'EOPNOTSUPP' not in drive + +if args.mutation: + old, new = MUTATIONS[args.mutation] + assert configure.count(old) == 1, args.mutation + configure = configure.replace(old, new) + +program = r''' +#include +#include +#include +#include +typedef unsigned int u32; +enum atcphy_dp_link_rate { ATCPHY_DP_LINK_RATE_RBR, ATCPHY_DP_LINK_RATE_HBR, ATCPHY_DP_LINK_RATE_HBR2, + ATCPHY_DP_LINK_RATE_HBR3 }; +enum { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8122, ATCPHY_GENERATION_T8132 }; +enum { APPLE_ATCPHY_MODE_OFF, APPLE_ATCPHY_MODE_DP, APPLE_ATCPHY_MODE_USB3_DP }; +struct phy_configure_opts_dp { u32 link_rate, lanes, voltage[4], pre[4]; bool set_rate, set_lanes, set_voltages; }; +union phy_configure_opts { struct phy_configure_opts_dp dp; }; +struct hw { int gen; bool has_t8140_dp, dp_t8122; }; +struct apple_atcphy { const struct hw *hw; void *dev; int mode; int lock; }; +struct phy { struct apple_atcphy *a; }; +static struct apple_atcphy *phy_get_drvdata(struct phy *p) { return p->a; } +static bool dp_on; +static int calls_rate, calls_other, last_rate = -1; +static bool atcphy_t8132_dp_on(struct apple_atcphy *a) { return dp_on; } +static int j700_dp_configure(struct apple_atcphy *a, struct phy_configure_opts_dp *o) { calls_other++; return 0; } +static int atcphy_dpphy_configure_t8122(struct apple_atcphy *a, struct phy_configure_opts_dp *o) { calls_other++; return 0; } +static void atcphy_restore_after_pd_off(struct apple_atcphy *a) { } +static int atcphy_dp_set_rate_t8122(struct apple_atcphy *a, u32 r) { calls_other++; return 0; } +static int atcphy_dp_configure(struct apple_atcphy *a, enum atcphy_dp_link_rate lr) { calls_rate++; last_rate = lr; return 0; } +#define guard(x) (void) +#define dev_dbg(...) do { } while (0) +#define dev_err(...) do { } while (0) +''' + configure + r''' +int main(void) +{ + static const struct hw t8103 = { ATCPHY_GENERATION_T8103 }; + struct apple_atcphy a = { .hw = &t8103, .mode = APPLE_ATCPHY_MODE_DP }; + struct phy p = { &a }; + unsigned cases = 0; + + for (unsigned v = 0; v < 2; v++) + for (unsigned r = 0; r < 2; r++) + for (unsigned l = 0; l < 2; l++) { + union phy_configure_opts o = { .dp = { .set_voltages = v, .set_rate = r, .set_lanes = l, + .link_rate = 5400, .voltage = { 2 }, .pre = { 1 } } }; + int ret; + + calls_rate = calls_other = 0; + ret = atcphy_dpphy_configure(&p, &o); + if (v && !r && !l) + /* A drive-only request: accepted, the PHY is not touched. */ + assert(ret == 0 && !calls_rate && !calls_other); + else if (v || l) + /* Drive levels with a rate or lanes, or lanes at all: refused, nothing done. */ + assert(ret == -EINVAL && !calls_rate && !calls_other); + else if (r) + assert(ret == 0 && calls_rate == 1 && last_rate == ATCPHY_DP_LINK_RATE_HBR2); + else + assert(ret == 0 && !calls_rate && !calls_other); + cases++; + } + /* An unknown rate is still refused. */ + union phy_configure_opts bad = { .dp = { .set_rate = true, .link_rate = 4321 } }; + assert(atcphy_dpphy_configure(&p, &bad) == -EINVAL); + + /* T8132 keeps its own answers: DP off is -EOPNOTSUPP, a drive-only request with DP on is 0. */ + static const struct hw t8132 = { ATCPHY_GENERATION_T8132 }; + a.hw = &t8132; + union phy_configure_opts drv = { .dp = { .set_voltages = true } }; + dp_on = false; + assert(atcphy_dpphy_configure(&p, &drv) == -EOPNOTSUPP); + dp_on = true; + assert(atcphy_dpphy_configure(&p, &drv) == 0); + /* T8122-class PHYs go to their own handler. */ + static const struct hw t8122 = { ATCPHY_GENERATION_T8122, .dp_t8122 = true }; + a.hw = &t8122; + calls_other = 0; + assert(atcphy_dpphy_configure(&p, &drv) == 0 && calls_other == 1); + printf("%u cases\n", cases); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test.c' + src.write_text(program) + exe = src.with_suffix('') + subprocess.run(['cc', '-Werror', '-Wall', '-Wno-unused-function', '-Wno-unused-value', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], check=True) + run = subprocess.run([str(exe)]) + if run.returncode: + sys.exit(f'FAIL: the drive matrix exited {run.returncode}') +print('PASS ATC PHY without drive control accepts a drive-only DP request; firmware-27 drive call passes PHY errors back') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7a21d3c4fb27ff..31dcbebc1673be 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -79,6 +79,8 @@ def mutations(flag, names, base, expect=KILL): 'dcpext26-startup-tests.py': [([], PASS)], 'iomfb-startup-tests.py': [([], PASS)], + 'atc-dp-drive-tests.py': [([], PASS)] + mutations( + '--mutation', ['eopnotsupp', 'accept-with-rate', 'refuse-drive'], []), 'dcp-v27-dptx-layout-tests.py': [([], PASS)] + mutations( '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext', 'ignore-typec-routes'], []), From 612c36f4405f41a047271d6c2aeecce90157a465 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:47:37 +1100 Subject: [PATCH 0461/1514] drm/apple: dptx: treat a Type-C-routed firmware-27 DCP like a dcpext in dptxep_init() dcp_v27_dptx_layout() moves the DPTX ports of a firmware-27 dcpext, and since the previous commits of a firmware-27 DCP with Type-C routes, to the endpoint its firmware advertises. dptxep_init() still waited for a port announce softly only on a dcpext, so a Type-C-routed DCP whose ports are not announced yet would fail its start with -ETIMEDOUT instead of leaving the endpoint up for a later announce. Use the same condition in both places and say so in the dptx_endpoint comment. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 3 ++- drivers/gpu/drm/apple/dptxep.c | 12 +++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..1f6dfaf61dfda2 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -315,7 +315,8 @@ struct apple_dcp_hw_data { * The endpoint the DPTX port services are announced on, where it is not * the firmware's default (DPTX_ENDPOINT_V2 on firmware 27): the T8142 * dcpext announces them on DPTX_ENDPOINT. 0: the default, or on a - * firmware-27 dcpext what its firmware advertises (dcp_v27_dptx_layout()). + * firmware-27 dcpext or DCP with Type-C routes what its firmware + * advertises (dcp_v27_dptx_layout()). */ u8 dptx_endpoint; /* diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index 812c8116175960..c6b773573ad499 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -1667,13 +1667,15 @@ int dptxep_init(struct apple_dcp *dcp) * up so a later announce can still bind. */ /* - * A firmware-27 external processor whose ports are not - * on this endpoint announces nothing here either (a 27.2 - * dcpext on DPTX_ENDPOINT_V2 where its firmware does not - * advertise DPTX_ENDPOINT, see dcp_v27_dptx_layout()). + * A firmware-27 external processor, or a firmware-27 + * DCP with Type-C routes, whose ports are not on this + * endpoint announces nothing here either (a 27.2 DCP on + * DPTX_ENDPOINT_V2 where its firmware does not advertise + * DPTX_ENDPOINT, see dcp_v27_dptx_layout()). */ if (dcp_fw_is_14_7(dcp) || dcp_is_ext26(dcp) || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->dcpext)) { + (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + (dcp->dcpext || dcp->nr_typec_routes))) { dev_info(dcp->dev, "DPTX port %u not announced yet\n", port); return 0; From 79c74a42daf61518272f0fa5ea643de502e51b11 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 14:48:17 -0800 Subject: [PATCH 0462/1514] media: apple: avd: leave bus_info to the cores, listing each decoder apart The driver set the media device's and VIDIOC_QUERYCAP's bus_info to a constant ("platform:avd" and "platform:" plus the driver name). On a multi-die SoC with one decoder per die (the M1, M2 and M5 Ultra: T6002, T6022, T6050) both instances then report the same bus, so v4l2-ctl --list-devices merges them into one entry and userspace cannot tell them apart. media_device_init() and v4l_querycap() already fill in "platform:" when the driver leaves the field alone, which is unique per instance. Drop the override, as the other Apple media drivers (ave, isp, jpeg, prores, scaler) already do. On a single-decoder SoC the value changes from "platform:avd" to "platform:" plus the device's name, the form the cores give every platform device. Tested on a J775D (Mac Studio, M5 Ultra). Signed-off-by: Jeff Queisser --- drivers/media/platform/apple/avd/avd-drv.c | 1 - drivers/media/platform/apple/avd/avd-v4l2.c | 2 -- 2 files changed, 3 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 58ea3fc604d875..fcaf378e8b816e 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -280,7 +280,6 @@ static int avd_v4l2_init(struct avd_dev *avd) avd->mdev.dev = avd->dev; strscpy(avd->mdev.model, "avd", sizeof(avd->mdev.model)); - strscpy(avd->mdev.bus_info, "platform:avd", sizeof(avd->mdev.bus_info)); media_device_init(&avd->mdev); avd->mdev.ops = &avd_media_ops; avd->v4l2_dev.mdev = &avd->mdev; diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 2a4903ee76aafb..7aba16fdec39e1 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -561,8 +561,6 @@ static int avd_querycap(struct file *file, void *priv, strscpy(cap->driver, avd->dev->driver->name, sizeof(cap->driver)); strscpy(cap->card, vdev->name, sizeof(cap->card)); - snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", - avd->dev->driver->name); return 0; } From f925befaa2679e41db2ca422d0aef91c6c8be011 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:11:30 +1100 Subject: [PATCH 0463/1514] thunderbolt: test: cover the control channel kept through s2idle A host router that stays awake through suspend-to-idle keeps its control channel when every connection is another host, so that the peer's XDomain discovery is still answered. Nothing tests which suspends retain the channel or what gets through it while the domain is suspended. Add four cases to the thunderbolt suite: - tb_xdp_noirq_request() admits the UUID, properties and link state status requests and no other packet type; - tb_domain_retain_noirq_control() retains only for a suspend-to-idle of a host router with QUIRK_NO_SYSTEM_SLEEP that has an XDomain and no router behind any port; - tb_domain_suspend_noirq() and tb_domain_resume_noirq() leave a retained control channel alone, retain nothing when the connection manager refuses the suspend, and tb_domain_event_cb() drops every event but an XDomain request until the domain has resumed; - tb_xdomain_handle_request() consumes service protocol packets, responses and state-changing discovery requests while retained, without calling a handler or queueing work. The domain in these cases has no control channel, so a path that stops or starts a retained one faults. tb_domain_event_cb(), tb_domain_retain_noirq_control() and tb_xdp_noirq_request() become VISIBLE_IF_KUNIT for this; they stay static without CONFIG_KUNIT. Signed-off-by: Ryan Murray --- drivers/thunderbolt/domain.c | 7 +- drivers/thunderbolt/tb.h | 4 + drivers/thunderbolt/test.c | 335 ++++++++++++++++++++++++++++++++++ drivers/thunderbolt/xdomain.c | 3 +- 4 files changed, 345 insertions(+), 4 deletions(-) diff --git a/drivers/thunderbolt/domain.c b/drivers/thunderbolt/domain.c index e77c0eab18cc46..b9e66861fbc75e 100644 --- a/drivers/thunderbolt/domain.c +++ b/drivers/thunderbolt/domain.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "tb.h" @@ -334,8 +335,8 @@ const struct device_type tb_domain_type = { .release = tb_domain_release, }; -static bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, - const void *buf, size_t size) +VISIBLE_IF_KUNIT bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, + const void *buf, size_t size) { struct tb *tb = data; @@ -533,7 +534,7 @@ void tb_domain_remove(struct tb *tb) } EXPORT_SYMBOL_FOR_MODULES(tb_domain_remove, "thunderbolt_apple"); -static bool tb_domain_retain_noirq_control(struct tb *tb) +VISIBLE_IF_KUNIT bool tb_domain_retain_noirq_control(struct tb *tb) { struct tb_port *port; bool xdomain = false; diff --git a/drivers/thunderbolt/tb.h b/drivers/thunderbolt/tb.h index 839468ed8def0b..70caebcf2b38be 100644 --- a/drivers/thunderbolt/tb.h +++ b/drivers/thunderbolt/tb.h @@ -773,6 +773,10 @@ int tb_consumed_dp_bandwidth(struct tb *tb, struct tb_port *src_port, int *consumed_up, int *consumed_down); u32 tb_dp_host_rate_limit(struct tb *tb); void tb_dp_host_tunnel_gone(struct tb *tb, unsigned int before); +bool tb_domain_event_cb(void *data, enum tb_cfg_pkg_type type, + const void *buf, size_t size); +bool tb_domain_retain_noirq_control(struct tb *tb); +bool tb_xdp_noirq_request(enum tb_xdp_type type); #endif #if IS_ENABLED(CONFIG_USB4_KUNIT_TEST) size_t tb_test_cm_size(void); diff --git a/drivers/thunderbolt/test.c b/drivers/thunderbolt/test.c index f8418132064afc..fbb318f17812dc 100644 --- a/drivers/thunderbolt/test.c +++ b/drivers/thunderbolt/test.c @@ -4316,6 +4316,337 @@ static void tb_test_dp_shared_rate_debounce_deferred(struct kunit *test) tb_test_dp_shared_rate_arrival(test, false, true); } +/* + * A domain as tb_domain_suspend_noirq() sees it on a host that keeps its + * router awake through suspend-to-idle (QUIRK_NO_SYSTEM_SLEEP): a host + * router and a connection manager that counts its calls. There is no + * control channel: the paths that keep it running must not touch it. + */ +struct tb_test_noirq { + struct tb_nhi nhi; + struct tb_cm_ops ops; + struct tb *tb; + struct tb_switch *host; + unsigned int saved_flags; + unsigned int suspends, resumes, events; + enum tb_cfg_pkg_type last_event; + int suspend_ret; + unsigned int handled; +}; + +static int tb_test_noirq_cm_suspend(struct tb *tb) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->suspends++; + return ctx->suspend_ret; +} + +static int tb_test_noirq_cm_resume(struct tb *tb) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->resumes++; + return 0; +} + +static void tb_test_noirq_cm_event(struct tb *tb, enum tb_cfg_pkg_type type, + const void *buf, size_t size) +{ + struct tb_test_noirq *ctx = kunit_get_current_test()->priv; + + ctx->events++; + ctx->last_event = type; +} + +/* The suspend in progress: to idle (the platform is not involved) or deeper. */ +#ifdef CONFIG_SUSPEND +static unsigned int tb_test_noirq_pm_flags(void) +{ + return pm_suspend_global_flags; +} + +static void tb_test_noirq_set_pm_flags(unsigned int flags) +{ + pm_suspend_global_flags = flags; +} + +static void tb_test_noirq_to_idle(bool to_idle) +{ + pm_suspend_clear_flags(); + if (to_idle) + pm_set_suspend_no_platform(); +} +#else +static unsigned int tb_test_noirq_pm_flags(void) +{ + return 0; +} + +static void tb_test_noirq_set_pm_flags(unsigned int flags) +{ +} + +static void tb_test_noirq_to_idle(bool to_idle) +{ +} +#endif + +static void tb_test_noirq_restore(void *data) +{ + struct tb_test_noirq *ctx = data; + + tb_test_noirq_set_pm_flags(ctx->saved_flags); + put_device(&ctx->tb->dev); +} + +/* The domain in a suspend-to-idle, with a host directly on port 1. */ +static struct tb_test_noirq *tb_test_noirq_alloc(struct kunit *test) +{ + struct tb_test_noirq *ctx; + struct tb_xdomain *xd; + struct tb *tb; + + if (!IS_ENABLED(CONFIG_SUSPEND)) + kunit_skip(test, "needs CONFIG_SUSPEND"); + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + tb = kunit_kzalloc(test, sizeof(*tb), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, tb); + xd = kunit_kzalloc(test, sizeof(*xd), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, xd); + ctx->host = alloc_host(test); + KUNIT_ASSERT_NOT_NULL(test, ctx->host); + + ctx->ops.suspend_noirq = tb_test_noirq_cm_suspend; + ctx->ops.resume_noirq = tb_test_noirq_cm_resume; + ctx->ops.handle_event = tb_test_noirq_cm_event; + ctx->nhi.quirks = QUIRK_NO_SYSTEM_SLEEP; + ctx->tb = tb; + tb->nhi = &ctx->nhi; + tb->cm_ops = &ctx->ops; + tb->root_switch = ctx->host; + ctx->host->tb = tb; + ctx->host->ports[1].xdomain = xd; + device_initialize(&tb->dev); + tb->dev.release = tb_test_dprx_release; + mutex_init(&tb->lock); + + ctx->saved_flags = tb_test_noirq_pm_flags(); + tb_test_noirq_to_idle(true); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, tb_test_noirq_restore, ctx), 0); + + test->priv = ctx; + return ctx; +} + +static bool tb_test_noirq_retain(struct tb_test_noirq *ctx) +{ + bool retain; + + mutex_lock(&ctx->tb->lock); + retain = tb_domain_retain_noirq_control(ctx->tb); + mutex_unlock(&ctx->tb->lock); + return retain; +} + +/* Only requests that read state are answered while the domain is suspended. */ +static void tb_test_noirq_xdp_request_types(struct kunit *test) +{ + unsigned int type; + + for (type = 0; type < 64; type++) { + bool discovery = type == UUID_REQUEST_OLD || type == UUID_REQUEST || + type == PROPERTIES_REQUEST || + type == LINK_STATE_STATUS_REQUEST; + + KUNIT_EXPECT_EQ_MSG(test, tb_xdp_noirq_request(type), discovery, + "XDomain packet type %u", type); + } +} + +/* + * The control channel stays up only for a suspend-to-idle of an awake host + * router whose every connection is another host. + */ +static void tb_test_noirq_retain_decision(struct kunit *test) +{ + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + struct tb_port *ports = ctx->host->ports; + struct tb_xdomain *xd = ports[1].xdomain; + struct tb_port *remote; + + remote = kunit_kzalloc(test, sizeof(*remote), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, remote); + + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + ports[3].xdomain = xd; + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + + /* A router behind any port needs the full suspend of its tunnels. */ + ports[3].xdomain = NULL; + ports[3].remote = remote; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ports[1].xdomain = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + + /* Nothing connected: nobody to answer. */ + ports[3].remote = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ports[1].xdomain = xd; + KUNIT_EXPECT_TRUE(test, tb_test_noirq_retain(ctx)); + + /* A host router that sleeps with the system loses its rings. */ + ctx->nhi.quirks = 0; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + ctx->nhi.quirks = QUIRK_NO_SYSTEM_SLEEP; + + /* The platform may power the router down in a deeper sleep. */ + tb_test_noirq_to_idle(false); + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); + tb_test_noirq_to_idle(true); + + ctx->tb->root_switch = NULL; + KUNIT_EXPECT_FALSE(test, tb_test_noirq_retain(ctx)); +} + +/* + * A retained control channel is neither stopped nor started (the domain has + * none here), and its events are dropped until the domain has resumed. + */ +static void tb_test_noirq_suspend_resume_retained(struct kunit *test) +{ + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + static const enum tb_cfg_pkg_type dropped[] = { + TB_CFG_PKG_ERROR, TB_CFG_PKG_NOTIFY_ACK, TB_CFG_PKG_EVENT, + TB_CFG_PKG_ICM_EVENT, + }; + struct tb *tb = ctx->tb; + u32 buf[4] = {}; + int i; + + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, TB_CFG_PKG_EVENT, buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 1U); + KUNIT_EXPECT_EQ(test, ctx->last_event, TB_CFG_PKG_EVENT); + + /* The connection manager refused: nothing is retained. */ + ctx->suspend_ret = -EBUSY; + KUNIT_EXPECT_EQ(test, tb_domain_suspend_noirq(tb), -EBUSY); + KUNIT_EXPECT_FALSE(test, tb->noirq_ctl_retained); + ctx->suspend_ret = 0; + + KUNIT_ASSERT_EQ(test, tb_domain_suspend_noirq(tb), 0); + KUNIT_EXPECT_EQ(test, ctx->suspends, 2U); + KUNIT_ASSERT_TRUE(test, tb->noirq_ctl_retained); + + for (i = 0; i < ARRAY_SIZE(dropped); i++) + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, dropped[i], buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 1U); + + KUNIT_ASSERT_EQ(test, tb_domain_resume_noirq(tb), 0); + KUNIT_EXPECT_EQ(test, ctx->resumes, 1U); + KUNIT_EXPECT_FALSE(test, tb->noirq_ctl_retained); + + KUNIT_EXPECT_TRUE(test, tb_domain_event_cb(tb, TB_CFG_PKG_ERROR, buf, sizeof(buf))); + KUNIT_EXPECT_EQ(test, ctx->events, 2U); + KUNIT_EXPECT_EQ(test, ctx->last_event, TB_CFG_PKG_ERROR); +} + +/* The XDomain discovery protocol and a service protocol of the test's own. */ +static const uuid_t tb_test_xdp_uuid = + UUID_INIT(0xb638d70e, 0x42ff, 0x40bb, + 0x97, 0xc2, 0x90, 0xe2, 0xc0, 0xb2, 0xff, 0x07); +static const uuid_t tb_test_service_uuid = + UUID_INIT(0x4b756e69, 0x7420, 0x7465, + 0x73, 0x74, 0x20, 0x6e, 0x6f, 0x69, 0x72, 0x71); + +static int tb_test_noirq_service(const void *buf, size_t size, void *data) +{ + struct tb_test_noirq *ctx = data; + + ctx->handled++; + return 1; +} + +static void tb_test_noirq_unregister(void *data) +{ + tb_unregister_protocol_handler(data); +} + +static bool tb_test_noirq_packet(struct tb_test_noirq *ctx, const uuid_t *uuid, + enum tb_cfg_pkg_type pkg, u32 type) +{ + struct tb_xdp_header hdr = { + .xd_hdr.length_sn = (sizeof(hdr) - sizeof(hdr.xd_hdr)) / 4, + .uuid = *uuid, + .type = type, + }; + + return tb_xdomain_handle_request(ctx->tb, pkg, &hdr, sizeof(hdr)); +} + +/* + * While the control channel is retained nothing but a discovery request + * gets past the XDomain dispatch: no service protocol, no response, no + * discovery request that changes state. + */ +static void tb_test_noirq_xdomain_filter(struct kunit *test) +{ + static const u32 refused[] = { + 0, UUID_RESPONSE, PROPERTIES_RESPONSE, PROPERTIES_CHANGED_REQUEST, + PROPERTIES_CHANGED_RESPONSE, ERROR_RESPONSE, + LINK_STATE_STATUS_RESPONSE, LINK_STATE_CHANGE_REQUEST, + LINK_STATE_CHANGE_RESPONSE, 31, + }; + struct tb_test_noirq *ctx = tb_test_noirq_alloc(test); + struct tb_protocol_handler *handler; + struct tb *tb = ctx->tb; + int i; + + handler = kunit_kzalloc(test, sizeof(*handler), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, handler); + handler->uuid = &tb_test_service_uuid; + handler->callback = tb_test_noirq_service; + handler->data = ctx; + KUNIT_ASSERT_EQ(test, tb_register_protocol_handler(handler), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, tb_test_noirq_unregister, + handler), 0); + + /* Awake: the service sees its packets, a discovery response is not consumed. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_REQ, UUID_REQUEST)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_EQ(test, ctx->handled, 2U); + KUNIT_EXPECT_FALSE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + + WRITE_ONCE(tb->noirq_ctl_retained, true); + + /* A service packet is dropped, whatever sits where discovery has its type. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_REQ, UUID_REQUEST)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_service_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_EQ(test, ctx->handled, 2U); + + /* A discovery response is consumed: no request of ours waits for one. */ + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_RESPONSE)); + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_RESP, UUID_REQUEST)); + + /* Queueing a request takes a reference to the domain: none is queued. */ + for (i = 0; i < ARRAY_SIZE(refused); i++) { + KUNIT_EXPECT_TRUE(test, tb_test_noirq_packet(ctx, &tb_test_xdp_uuid, + TB_CFG_PKG_XDOMAIN_REQ, + refused[i])); + KUNIT_EXPECT_EQ_MSG(test, kref_read(&tb->dev.kobj.kref), 1U, + "XDomain request %u was queued", refused[i]); + } +} + static struct kunit_case tb_test_cases[] = { KUNIT_CASE(tb_test_apple_right_dpin_wiring), KUNIT_CASE(tb_test_dp_reduce_bandwidth_shared), @@ -4339,6 +4670,10 @@ static struct kunit_case tb_test_cases[] = { KUNIT_CASE(tb_test_property_parse_u32_wrap), KUNIT_CASE(tb_test_property_parse_recursion), KUNIT_CASE(tb_test_property_parse_dir_len_underflow), + KUNIT_CASE(tb_test_noirq_xdp_request_types), + KUNIT_CASE(tb_test_noirq_retain_decision), + KUNIT_CASE(tb_test_noirq_suspend_resume_retained), + KUNIT_CASE(tb_test_noirq_xdomain_filter), KUNIT_CASE(tb_test_pci_host_teardown), KUNIT_CASE(tb_test_pci_host_daisy_chain), KUNIT_CASE(tb_test_tunnel_dp_host_credits), diff --git a/drivers/thunderbolt/xdomain.c b/drivers/thunderbolt/xdomain.c index d174e7129191ca..7858eaafb9967f 100644 --- a/drivers/thunderbolt/xdomain.c +++ b/drivers/thunderbolt/xdomain.c @@ -17,6 +17,7 @@ #include #include #include +#include #include "tb.h" @@ -763,7 +764,7 @@ static void stop_handshake(struct tb_xdomain *xd) * The XDomain discovery requests answered while the control channel is kept * through s2idle (tb->noirq_ctl_retained): they only read state. */ -static bool tb_xdp_noirq_request(enum tb_xdp_type type) +VISIBLE_IF_KUNIT bool tb_xdp_noirq_request(enum tb_xdp_type type) { switch (type) { case UUID_REQUEST_OLD: From 005b8bbfd59868ec13d3804f92187553c05535c0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:11:30 +1100 Subject: [PATCH 0464/1514] pmdomain: apple: pmp-report: test: cover the fast die-temperature effort apple_pmp_report_fast_die_effort() and the T8142 report layout have no test. A wrong lane shift, a missed "PMP is running" check or a 32-bit read of the T8142's 16-byte entry would hand a CPU cluster the wrong thermal effort, or none. Add the apple-pmp-fast-die suite, on a report in memory published the way probe publishes it: - each lane is one byte of the low word, read 32 or 64 bits wide, and a lane past the report's count is -EINVAL with nothing stored; - a stopped PMP gives -EAGAIN, and status bits other than "ready" count as running only where the SoC's table says so; - the report is found by its node (-EPROBE_DEFER when none is bound) and one without the entry gives -EOPNOTSUPP; - the T8142 table matches its PMP's entry numbers: status 1, fast die 15 (two lanes, wide), device requests 39, acknowledgments 47, DVFS 55..70. Signed-off-by: Ryan Murray --- drivers/pmdomain/apple/Kconfig | 4 +- .../pmdomain/apple/pmp-report-start-test.c | 197 +++++++++++++++++- 2 files changed, 199 insertions(+), 2 deletions(-) diff --git a/drivers/pmdomain/apple/Kconfig b/drivers/pmdomain/apple/Kconfig index 252cceba3c561b..0d67b542b97fae 100644 --- a/drivers/pmdomain/apple/Kconfig +++ b/drivers/pmdomain/apple/Kconfig @@ -129,7 +129,9 @@ config APPLE_PMP_REPORT_START_KUNIT_TEST failed checks, a PMP driver that does not bind, a PMP that does not report ready or acknowledge its startup requests, consumers that time out, and the teardown of the report and its entries while a - start or a consumer waits. The report region is simulated in + start or a consumer waits. Also reads the fast die-temperature + effort of a report: its lanes, reports that have none or do not + run, and the T8142 layout. The report region is simulated in memory. Only useful for kernel developers. endif diff --git a/drivers/pmdomain/apple/pmp-report-start-test.c b/drivers/pmdomain/apple/pmp-report-start-test.c index 36cf2c87eb128a..b6a8daa78ec745 100644 --- a/drivers/pmdomain/apple/pmp-report-start-test.c +++ b/drivers/pmdomain/apple/pmp-report-start-test.c @@ -6,6 +6,9 @@ * bind, no ready status, no acknowledgment), a consumer's own timeout and * the teardown of the provider can be driven without Apple hardware. * + * The fast die-temperature effort is read from a report in memory, too: its + * lanes, the reports that have none or do not run, and the T8142 layout. + * * Included by pmp-report.c. */ @@ -407,4 +410,196 @@ static struct kunit_suite pmp_start_suite = { .test_cases = pmp_start_cases, }; -kunit_test_suite(pmp_start_suite); +/* + * A report in memory with the PMP's status in its first word and the fast + * die-temperature efforts in an entry of its own: 16 bytes, of which the + * low 32 bits hold the lanes. + */ +#define PFD_STATUS 0x08 +#define PFD_EFFORT 0x10 +#define PFD_LANES 0xa4c30f5aU +#define PFD_OTHER 0x1122334400000000ULL + +struct pfd { + struct apple_pmp_report rep; + struct apple_pmp_report_offsets offsets; + struct device dev; + struct device_node node; + u64 regs[4]; +}; + +static void pfd_remove(void *data) +{ + struct pfd *t = data; + + mutex_lock(&apple_pmp_reports_lock); + list_del_rcu(&t->rep.list); + mutex_unlock(&apple_pmp_reports_lock); + synchronize_rcu(); +} + +/* A running report with @lanes fast-die lanes, published as probe does. */ +static struct pfd *pfd_new(struct kunit *test, u32 lanes) +{ + struct pfd *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, t); + t->offsets.status = PFD_STATUS; + t->offsets.fast_die = lanes ? PFD_EFFORT : 0; + t->offsets.fast_die_lanes = lanes; + t->dev.of_node = &t->node; + t->rep.dev = &t->dev; + t->rep.offsets = &t->offsets; + t->rep.base = (__force void __iomem *)t->regs; + spin_lock_init(&t->rep.lock); + + t->regs[PFD_STATUS / sizeof(u64)] = PMP_REPORT_READY; + t->regs[PFD_EFFORT / sizeof(u64)] = PFD_OTHER | PFD_LANES; + t->regs[PFD_EFFORT / sizeof(u64) + 1] = ~0ULL; + + mutex_lock(&apple_pmp_reports_lock); + list_add_tail_rcu(&t->rep.list, &apple_pmp_reports); + mutex_unlock(&apple_pmp_reports_lock); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, pfd_remove, t), 0); + return t; +} + +static int pfd_effort(struct pfd *t, unsigned int lane, u8 *effort) +{ + *effort = 0xee; + return apple_pmp_report_fast_die_effort(&t->node, lane, effort); +} + +/* Each lane is one byte of the low word, read 32 or 64 bits wide. */ +static void pmp_fast_die_lanes_test(struct kunit *test) +{ + struct pfd *t = pfd_new(test, 3); + u8 effort; + int wide; + + for (wide = 0; wide < 2; wide++) { + t->offsets.fast_die_wide = wide; + t->offsets.fast_die_lanes = 3; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x5a); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 2, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0xc3); + + /* Past the report's lanes: refused, nothing is stored. */ + KUNIT_EXPECT_EQ(test, pfd_effort(t, 3, &effort), -EINVAL); + KUNIT_EXPECT_EQ(test, effort, 0xee); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 4, &effort), -EINVAL); + KUNIT_EXPECT_EQ(test, pfd_effort(t, UINT_MAX, &effort), -EINVAL); + + t->offsets.fast_die_lanes = 4; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 3, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0xa4); + } +} + +/* A stopped PMP reads 0, which would ask for no limit: no effort then. */ +static void pmp_fast_die_running_test(struct kunit *test) +{ + struct pfd *t = pfd_new(test, 2); + u64 *status = &t->regs[PFD_STATUS / sizeof(u64)]; + u8 effort; + + WRITE_ONCE(*status, 0); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), -EAGAIN); + KUNIT_EXPECT_EQ(test, effort, 0xee); + t->offsets.running_any = true; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 0, &effort), -EAGAIN); + KUNIT_EXPECT_EQ(test, effort, 0xee); + + /* Status bits other than "ready" only count where the SoC says so. */ + WRITE_ONCE(*status, BIT_ULL(36)); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + t->offsets.running_any = false; + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), -EAGAIN); + + WRITE_ONCE(*status, BIT_ULL(36) | PMP_REPORT_READY); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x0f); + + /* A lane the report does not have is the caller's error, running or not. */ + WRITE_ONCE(*status, 0); + KUNIT_EXPECT_EQ(test, pfd_effort(t, 2, &effort), -EINVAL); +} + +/* The report is found by its node; one without the entry says so. */ +static void pmp_fast_die_lookup_test(struct kunit *test) +{ + struct pfd *none = pfd_new(test, 0); + struct pfd *a = pfd_new(test, 2); + struct pfd *b = pfd_new(test, 2); + struct device_node *unbound; + u8 effort = 0xee; + + unbound = kunit_kzalloc(test, sizeof(*unbound), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, unbound); + KUNIT_EXPECT_EQ(test, apple_pmp_report_fast_die_effort(unbound, 0, &effort), + -EPROBE_DEFER); + KUNIT_EXPECT_EQ(test, effort, 0xee); + + b->regs[PFD_EFFORT / sizeof(u64)] = 0x7781; + KUNIT_EXPECT_EQ(test, pfd_effort(a, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x5a); + KUNIT_EXPECT_EQ(test, pfd_effort(b, 0, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x81); + KUNIT_EXPECT_EQ(test, pfd_effort(b, 1, &effort), 0); + KUNIT_EXPECT_EQ(test, effort, 0x77); + + /* No entry: unsupported whatever the lane and the PMP's state. */ + KUNIT_EXPECT_EQ(test, pfd_effort(none, 0, &effort), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, effort, 0xee); + none->regs[PFD_STATUS / sizeof(u64)] = 0; + KUNIT_EXPECT_EQ(test, pfd_effort(none, 0, &effort), -EOPNOTSUPP); +} + +/* + * The T8142 report as its PMP's table of PTD entries gives it: PMP-STATUS 1, + * FAST-DIE-CE 15 (E, P), SOC-DEV-PS-REQ 39, SOC-DEV-PS-ACK 47 and + * SOC-DEV-DVFS 55 to 70. An entry is read in 16 bytes from the base and + * written in 8 bytes from the update aperture. + */ +static void pmp_fast_die_t8142_test(struct kunit *test) +{ + const struct apple_pmp_report_offsets *offs = NULL; + const struct of_device_id *id; + + for (id = apple_pmp_report_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, "apple,t8142-pmp-v2-report")) + offs = id->data; + KUNIT_ASSERT_NOT_NULL(test, offs); + + KUNIT_EXPECT_EQ(test, offs->status, 1 * 16); + KUNIT_EXPECT_EQ(test, offs->fast_die, 15 * 16); + KUNIT_EXPECT_EQ(test, offs->fast_die_lanes, 2); + KUNIT_EXPECT_TRUE(test, offs->fast_die_wide); + KUNIT_EXPECT_EQ(test, offs->tgt_read, 39 * 16); + KUNIT_EXPECT_EQ(test, offs->tgt_write, offs->update + 39 * 8); + KUNIT_EXPECT_EQ(test, offs->actual, 47 * 16); + KUNIT_EXPECT_EQ(test, offs->dvfs_first, 55); + KUNIT_EXPECT_EQ(test, offs->dvfs_first + offs->dvfs_count - 1, 70); + KUNIT_EXPECT_TRUE(test, offs->running_any); + KUNIT_EXPECT_TRUE(test, offs->defer_requests); + KUNIT_EXPECT_FALSE(test, offs->starts_pmp); +} + +static struct kunit_case pmp_fast_die_cases[] = { + KUNIT_CASE(pmp_fast_die_lanes_test), + KUNIT_CASE(pmp_fast_die_running_test), + KUNIT_CASE(pmp_fast_die_lookup_test), + KUNIT_CASE(pmp_fast_die_t8142_test), + {} +}; + +static struct kunit_suite pmp_fast_die_suite = { + .name = "apple-pmp-fast-die", + .test_cases = pmp_fast_die_cases, +}; + +kunit_test_suites(&pmp_start_suite, &pmp_fast_die_suite); From bc7933ef6bf1b73ab2fb6ab0bb6ab31877793736 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:13:15 +1100 Subject: [PATCH 0465/1514] arm64: dts: apple: t8112: share the SoC hwmon channels with the J473 The M2 Mac mini (J473) publishes 14 SMC hwmon channels and the M2 MacBook Air (J413) 102, on the same SoC. The J413 board files hold the channels that belong to the SoC and its PMU: the GPU and CPU die temperatures and the PMU rails. The J473 SMC has 71 of those keys and its device tree names none of them. Move them into two files that a T8112 board includes after its own hwmon files: t8112-hwmon.dtsi has the 29 die temperatures (Tg0e/Tg0m/Tg0q with their no-data threshold for a powered-off GPU, TCMb, Te04, Te06 and 23 Tp keys). All four T8112 boards include it. t8112-hwmon-rails.dtsi has the 42 rail channels both SMCs publish. The J413 and the J473 include it. The 11 rail keys the J473 SMC lacks (VP0R, VP2l, VP8l, VPkl, IP8l, IPBR, IPkl, PP8l, PPBR, PPkl, PR8b) stay in t8112-j413-hwmon-rails.dtsi. The consumer labels were measured on the J413 and hold on the J473. Its SMC values at idle, with the P cluster loaded and with the E cluster loaded, 20 s each: PP0b 430, 12717 and 49 mW; PPbb 13, 6 and 2116 mW; PP1b 0 with the GPU off. The Tp, Te and TCMb keys all read and follow the load. The J415 and J493 SMCs have not been read. macsmc-hwmon skips a voltage, current or power node whose key the SMC lacks. For a temperature node on this provider it logs one warning and hides the channel, keeping the index. Neither fails the probe, so those two boards get the die temperatures. They do not get the rails, whose labels are proven only on the J413 and J473. The temperature channels keep their order on every board: the ones in t8112.dtsi that the thermal zones index come first, then the board's, then these. In the J413 DTB the temperature nodes are unchanged; among the voltage, current and power nodes the 11 J413-only ones now come last, so their inN, currN and powerN numbers move. The labels do not change and nothing indexes those channels. Signed-off-by: Ryan Murray --- .../boot/dts/apple/t8112-hwmon-rails.dtsi | 234 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8112-hwmon.dtsi | 178 +++++++++++++ .../dts/apple/t8112-j413-hwmon-rails.dtsi | 225 +---------------- arch/arm64/boot/dts/apple/t8112-j413.dts | 168 +------------ arch/arm64/boot/dts/apple/t8112-j415.dts | 1 + arch/arm64/boot/dts/apple/t8112-j473.dts | 2 + arch/arm64/boot/dts/apple/t8112-j493.dts | 1 + 7 files changed, 421 insertions(+), 388 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi create mode 100644 arch/arm64/boot/dts/apple/t8112-hwmon.dtsi diff --git a/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi b/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi new file mode 100644 index 00000000000000..bd9901415f02b4 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-hwmon-rails.dtsi @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T8112 PMU rail channels published by the SMC on every board measured so + * far (J413, J473). + * + * The SMC samples the main PMU outputs (VPxy voltage, IPxy current, PPxy + * power) and a second regulator family (VRxy, IRxy, PRxy). With the other + * cluster held at its lowest step, one cluster under load moves only its + * own output. On the J413: + * P cluster (cpu4-7): VP0b 555-775 mV, IP0b up to 7.8 A, PP0b up to 6.1 W + * E cluster (cpu0-3): VPbb 537-905 mV, IPbb up to 2.2 A, PPbb up to 2.0 W + * GPU: VP1b 0 mV while power-gated, 900-930 mV under load, PP1b ~1.1 W + * The J473 moves the same outputs: PP0b 0.4 W idle, 12.7 W with the P + * cluster loaded; PPbb 0.01 W idle, 2.1 W with the E cluster loaded. + * The consumers of the other outputs are not mapped; they are labelled + * "PMU " and "Rail ". Outputs whose current and power read 0 in + * every state are left out. Linux only reads the SMC keys. + * + * The driver skips a voltage, current or power channel whose key the SMC + * does not have, so a board without one of these outputs loses only that + * channel. + */ + +&smc_hwmon { + voltage-VP0b { + apple,key-id = "VP0b"; + label = "P-cluster VP0b"; + }; + + voltage-VPbb { + apple,key-id = "VPbb"; + label = "E-cluster VPbb"; + }; + + voltage-VP1b { + apple,key-id = "VP1b"; + label = "GPU VP1b"; + }; + + voltage-VP2b { + apple,key-id = "VP2b"; + label = "PMU VP2b"; + }; + + voltage-VP3b { + apple,key-id = "VP3b"; + label = "PMU VP3b"; + }; + + voltage-VP4b { + apple,key-id = "VP4b"; + label = "PMU VP4b"; + }; + + voltage-VP7b { + apple,key-id = "VP7b"; + label = "PMU VP7b"; + }; + + voltage-VP7l { + apple,key-id = "VP7l"; + label = "PMU VP7l"; + }; + + voltage-VP9b { + apple,key-id = "VP9b"; + label = "PMU VP9b"; + }; + + voltage-VP9l { + apple,key-id = "VP9l"; + label = "PMU VP9l"; + }; + + voltage-VPdb { + apple,key-id = "VPdb"; + label = "PMU VPdb"; + }; + + voltage-VR4l { + apple,key-id = "VR4l"; + label = "Rail VR4l"; + }; + + voltage-VR5b { + apple,key-id = "VR5b"; + label = "Rail VR5b"; + }; + + voltage-VR6b { + apple,key-id = "VR6b"; + label = "Rail VR6b"; + }; + + voltage-VR8b { + apple,key-id = "VR8b"; + label = "Rail VR8b"; + }; + + voltage-VRab { + apple,key-id = "VRab"; + label = "Rail VRab"; + }; + + voltage-VRcb { + apple,key-id = "VRcb"; + label = "Rail VRcb"; + }; + + voltage-VRcl { + apple,key-id = "VRcl"; + label = "Rail VRcl"; + }; + + voltage-VReb { + apple,key-id = "VReb"; + label = "Rail VReb"; + }; + + current-IP0b { + apple,key-id = "IP0b"; + label = "P-cluster IP0b"; + }; + + current-IPbb { + apple,key-id = "IPbb"; + label = "E-cluster IPbb"; + }; + + current-IP1b { + apple,key-id = "IP1b"; + label = "GPU IP1b"; + }; + + current-IP2b { + apple,key-id = "IP2b"; + label = "PMU IP2b"; + }; + + current-IP4b { + apple,key-id = "IP4b"; + label = "PMU IP4b"; + }; + + current-IP7b { + apple,key-id = "IP7b"; + label = "PMU IP7b"; + }; + + current-IP7l { + apple,key-id = "IP7l"; + label = "PMU IP7l"; + }; + + current-IP9b { + apple,key-id = "IP9b"; + label = "PMU IP9b"; + }; + + current-IR4l { + apple,key-id = "IR4l"; + label = "Rail IR4l"; + }; + + current-IR5b { + apple,key-id = "IR5b"; + label = "Rail IR5b"; + }; + + current-IR8b { + apple,key-id = "IR8b"; + label = "Rail IR8b"; + }; + + current-IRcl { + apple,key-id = "IRcl"; + label = "Rail IRcl"; + }; + + power-PP0b { + apple,key-id = "PP0b"; + label = "P-cluster PP0b"; + }; + + power-PPbb { + apple,key-id = "PPbb"; + label = "E-cluster PPbb"; + }; + + power-PP1b { + apple,key-id = "PP1b"; + label = "GPU PP1b"; + }; + + power-PP2b { + apple,key-id = "PP2b"; + label = "PMU PP2b"; + }; + + power-PP4b { + apple,key-id = "PP4b"; + label = "PMU PP4b"; + }; + + power-PP7b { + apple,key-id = "PP7b"; + label = "PMU PP7b"; + }; + + power-PP7l { + apple,key-id = "PP7l"; + label = "PMU PP7l"; + }; + + power-PP9b { + apple,key-id = "PP9b"; + label = "PMU PP9b"; + }; + + power-PR4l { + apple,key-id = "PR4l"; + label = "Rail PR4l"; + }; + + power-PR5b { + apple,key-id = "PR5b"; + label = "Rail PR5b"; + }; + + power-PRcl { + apple,key-id = "PRcl"; + label = "Rail PRcl"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi b/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi new file mode 100644 index 00000000000000..ec67a007315257 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-hwmon.dtsi @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T8112 SoC temperature channels published by the SMC, beyond the ones in + * t8112.dtsi. They are sensors of the SoC die, read-only; the J413 and + * J473 SMCs both publish every key here. + * + * t8112.dtsi makes the hwmon node a thermal sensor provider, so the driver + * keeps the channel number of a temperature key the SMC does not have and + * hides that channel with one warning. + * + * Include this file after the board's other hwmon files. The thermal zones + * index the first channels of t8112.dtsi; nothing indexes these. + */ + +/* + * GPU temperatures. The SMC publishes them only while the GPU is powered: + * with the GPU off, Tg0e, Tg0m and Tg0q read 0 C and Tg0f, Tg0n and Tg0r + * 4.6 C (they track the first three plus a fixed 4.6 C). Those + * placeholders are no data. Tg0f, Tg0n and Tg0r are in t8112.dtsi. + */ +&smc_hwmon { + temperature-Tg0e { + apple,key-id = "Tg0e"; + label = "GPU Tg0e"; + apple,no-data-below-millicelsius = <10000>; + }; + + temperature-Tg0m { + apple,key-id = "Tg0m"; + label = "GPU Tg0m"; + apple,no-data-below-millicelsius = <10000>; + }; + + temperature-Tg0q { + apple,key-id = "Tg0q"; + label = "GPU Tg0q"; + apple,no-data-below-millicelsius = <10000>; + }; +}; + +/* + * The other CPU temperatures, after the GPU channels. Each sensor site has + * a reading, the same plus a fixed offset and a hotspot estimate; the CPU + * thermal zones use the offset keys of four P sites and Te05. Te04-Te06 + * follow the E cluster, every Tp key the P cluster, TCMz is the hottest + * hotspot key and TCMb the hottest offset key. + */ +&smc_hwmon { + temperature-TCMb { + apple,key-id = "TCMb"; + label = "SoC Die TCMb"; + }; + + temperature-Te04 { + apple,key-id = "Te04"; + label = "E-cluster Te04"; + }; + + temperature-Te06 { + apple,key-id = "Te06"; + label = "E-cluster Te06"; + }; + + temperature-Tp00 { + apple,key-id = "Tp00"; + label = "P-cluster Tp00"; + }; + + temperature-Tp02 { + apple,key-id = "Tp02"; + label = "P-cluster Tp02"; + }; + + temperature-Tp04 { + apple,key-id = "Tp04"; + label = "P-cluster Tp04"; + }; + + temperature-Tp06 { + apple,key-id = "Tp06"; + label = "P-cluster Tp06"; + }; + + temperature-Tp08 { + apple,key-id = "Tp08"; + label = "P-cluster Tp08"; + }; + + temperature-Tp0A { + apple,key-id = "Tp0A"; + label = "P-cluster Tp0A"; + }; + + temperature-Tp0C { + apple,key-id = "Tp0C"; + label = "P-cluster Tp0C"; + }; + + temperature-Tp0E { + apple,key-id = "Tp0E"; + label = "P-cluster Tp0E"; + }; + + temperature-Tp0a { + apple,key-id = "Tp0a"; + label = "P-cluster Tp0a"; + }; + + temperature-Tp0b { + apple,key-id = "Tp0b"; + label = "P-cluster Tp0b"; + }; + + temperature-Tp0c { + apple,key-id = "Tp0c"; + label = "P-cluster Tp0c"; + }; + + temperature-Tp0e { + apple,key-id = "Tp0e"; + label = "P-cluster Tp0e"; + }; + + temperature-Tp0f { + apple,key-id = "Tp0f"; + label = "P-cluster Tp0f"; + }; + + temperature-Tp0g { + apple,key-id = "Tp0g"; + label = "P-cluster Tp0g"; + }; + + temperature-Tp0i { + apple,key-id = "Tp0i"; + label = "P-cluster Tp0i"; + }; + + temperature-Tp0j { + apple,key-id = "Tp0j"; + label = "P-cluster Tp0j"; + }; + + temperature-Tp0k { + apple,key-id = "Tp0k"; + label = "P-cluster Tp0k"; + }; + + temperature-Tp0m { + apple,key-id = "Tp0m"; + label = "P-cluster Tp0m"; + }; + + temperature-Tp0n { + apple,key-id = "Tp0n"; + label = "P-cluster Tp0n"; + }; + + temperature-Tp0o { + apple,key-id = "Tp0o"; + label = "P-cluster Tp0o"; + }; + + temperature-Tp0q { + apple,key-id = "Tp0q"; + label = "P-cluster Tp0q"; + }; + + temperature-Tp0r { + apple,key-id = "Tp0r"; + label = "P-cluster Tp0r"; + }; + + temperature-Tp0s { + apple,key-id = "Tp0s"; + label = "P-cluster Tp0s"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi b/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi index dfe95d1bdc2e9b..0655d73a96d271 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j413-hwmon-rails.dtsi @@ -1,180 +1,36 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * T8112 J413 PMU rail channels published by the SMC. - * - * The SMC samples the main PMU outputs (VPxy voltage, IPxy current, PPxy - * power) and a second regulator family (VRxy, IRxy, PRxy). With the other - * cluster held at its lowest step, one cluster under load moves only its - * own output: - * P cluster (cpu4-7): VP0b 555-775 mV, IP0b up to 7.8 A, PP0b up to 6.1 W - * E cluster (cpu0-3): VPbb 537-905 mV, IPbb up to 2.2 A, PPbb up to 2.0 W - * GPU: VP1b 0 mV while power-gated, 900-930 mV under load, PP1b ~1.1 W - * The consumers of the other outputs are not mapped; they are labelled - * "PMU " and "Rail ". Outputs whose current and power read 0 in - * every state are left out. Linux only reads the SMC keys. + * T8112 J413 PMU rail channels the J473 SMC does not publish. The rails + * both boards have are in t8112-hwmon-rails.dtsi, where the key naming is + * explained. The consumers of these outputs are not mapped. */ &smc_hwmon { - voltage-VP0b { - apple,key-id = "VP0b"; - label = "P-cluster VP0b"; - }; - - voltage-VPbb { - apple,key-id = "VPbb"; - label = "E-cluster VPbb"; - }; - - voltage-VP1b { - apple,key-id = "VP1b"; - label = "GPU VP1b"; - }; - voltage-VP0R { apple,key-id = "VP0R"; label = "PMU VP0R"; }; - voltage-VP2b { - apple,key-id = "VP2b"; - label = "PMU VP2b"; - }; - voltage-VP2l { apple,key-id = "VP2l"; label = "PMU VP2l"; }; - voltage-VP3b { - apple,key-id = "VP3b"; - label = "PMU VP3b"; - }; - - voltage-VP4b { - apple,key-id = "VP4b"; - label = "PMU VP4b"; - }; - - voltage-VP7b { - apple,key-id = "VP7b"; - label = "PMU VP7b"; - }; - - voltage-VP7l { - apple,key-id = "VP7l"; - label = "PMU VP7l"; - }; - voltage-VP8l { apple,key-id = "VP8l"; label = "PMU VP8l"; }; - voltage-VP9b { - apple,key-id = "VP9b"; - label = "PMU VP9b"; - }; - - voltage-VP9l { - apple,key-id = "VP9l"; - label = "PMU VP9l"; - }; - - voltage-VPdb { - apple,key-id = "VPdb"; - label = "PMU VPdb"; - }; - voltage-VPkl { apple,key-id = "VPkl"; label = "PMU VPkl"; }; - voltage-VR4l { - apple,key-id = "VR4l"; - label = "Rail VR4l"; - }; - - voltage-VR5b { - apple,key-id = "VR5b"; - label = "Rail VR5b"; - }; - - voltage-VR6b { - apple,key-id = "VR6b"; - label = "Rail VR6b"; - }; - - voltage-VR8b { - apple,key-id = "VR8b"; - label = "Rail VR8b"; - }; - - voltage-VRab { - apple,key-id = "VRab"; - label = "Rail VRab"; - }; - - voltage-VRcb { - apple,key-id = "VRcb"; - label = "Rail VRcb"; - }; - - voltage-VRcl { - apple,key-id = "VRcl"; - label = "Rail VRcl"; - }; - - voltage-VReb { - apple,key-id = "VReb"; - label = "Rail VReb"; - }; - - current-IP0b { - apple,key-id = "IP0b"; - label = "P-cluster IP0b"; - }; - - current-IPbb { - apple,key-id = "IPbb"; - label = "E-cluster IPbb"; - }; - - current-IP1b { - apple,key-id = "IP1b"; - label = "GPU IP1b"; - }; - - current-IP2b { - apple,key-id = "IP2b"; - label = "PMU IP2b"; - }; - - current-IP4b { - apple,key-id = "IP4b"; - label = "PMU IP4b"; - }; - - current-IP7b { - apple,key-id = "IP7b"; - label = "PMU IP7b"; - }; - - current-IP7l { - apple,key-id = "IP7l"; - label = "PMU IP7l"; - }; - current-IP8l { apple,key-id = "IP8l"; label = "PMU IP8l"; }; - current-IP9b { - apple,key-id = "IP9b"; - label = "PMU IP9b"; - }; - current-IPBR { apple,key-id = "IPBR"; label = "PMU IPBR"; @@ -185,71 +41,11 @@ label = "PMU IPkl"; }; - current-IR4l { - apple,key-id = "IR4l"; - label = "Rail IR4l"; - }; - - current-IR5b { - apple,key-id = "IR5b"; - label = "Rail IR5b"; - }; - - current-IR8b { - apple,key-id = "IR8b"; - label = "Rail IR8b"; - }; - - current-IRcl { - apple,key-id = "IRcl"; - label = "Rail IRcl"; - }; - - power-PP0b { - apple,key-id = "PP0b"; - label = "P-cluster PP0b"; - }; - - power-PPbb { - apple,key-id = "PPbb"; - label = "E-cluster PPbb"; - }; - - power-PP1b { - apple,key-id = "PP1b"; - label = "GPU PP1b"; - }; - - power-PP2b { - apple,key-id = "PP2b"; - label = "PMU PP2b"; - }; - - power-PP4b { - apple,key-id = "PP4b"; - label = "PMU PP4b"; - }; - - power-PP7b { - apple,key-id = "PP7b"; - label = "PMU PP7b"; - }; - - power-PP7l { - apple,key-id = "PP7l"; - label = "PMU PP7l"; - }; - power-PP8l { apple,key-id = "PP8l"; label = "PMU PP8l"; }; - power-PP9b { - apple,key-id = "PP9b"; - label = "PMU PP9b"; - }; - power-PPBR { apple,key-id = "PPBR"; label = "PMU PPBR"; @@ -260,23 +56,8 @@ label = "PMU PPkl"; }; - power-PR4l { - apple,key-id = "PR4l"; - label = "Rail PR4l"; - }; - - power-PR5b { - apple,key-id = "PR5b"; - label = "Rail PR5b"; - }; - power-PR8b { apple,key-id = "PR8b"; label = "Rail PR8b"; }; - - power-PRcl { - apple,key-id = "PRcl"; - label = "Rail PRcl"; - }; }; diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index ff99c23afb7a96..4609399ea7e5c1 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -278,173 +278,9 @@ }; #include "hwmon-laptop.dtsi" +#include "t8112-hwmon-rails.dtsi" #include "t8112-j413-hwmon-rails.dtsi" - -/* - * GPU temperatures, after the channels the thermal zones index. The SMC - * publishes them only while the GPU is powered: with the GPU off, Tg0e, - * Tg0m and Tg0q read 0 C and Tg0f, Tg0n and Tg0r 4.6 C (they track the - * first three plus a fixed 4.6 C). Those placeholders are no data. - * Tg0f, Tg0n and Tg0r are in t8112.dtsi. - */ -&smc_hwmon { - temperature-Tg0e { - apple,key-id = "Tg0e"; - label = "GPU Tg0e"; - apple,no-data-below-millicelsius = <10000>; - }; - - temperature-Tg0m { - apple,key-id = "Tg0m"; - label = "GPU Tg0m"; - apple,no-data-below-millicelsius = <10000>; - }; - - temperature-Tg0q { - apple,key-id = "Tg0q"; - label = "GPU Tg0q"; - apple,no-data-below-millicelsius = <10000>; - }; -}; - -/* - * The other CPU temperatures, read-only, after the GPU channels. Each - * sensor site has a reading, the same plus a fixed offset and a hotspot - * estimate; the zones above use the offset keys of four P sites and Te05. - * Te04-Te06 follow the E cluster, every Tp key the P cluster, TCMz is the - * hottest hotspot key and TCMb the hottest offset key. - */ -&smc_hwmon { - temperature-TCMb { - apple,key-id = "TCMb"; - label = "SoC Die TCMb"; - }; - - temperature-Te04 { - apple,key-id = "Te04"; - label = "E-cluster Te04"; - }; - - temperature-Te06 { - apple,key-id = "Te06"; - label = "E-cluster Te06"; - }; - - temperature-Tp00 { - apple,key-id = "Tp00"; - label = "P-cluster Tp00"; - }; - - temperature-Tp02 { - apple,key-id = "Tp02"; - label = "P-cluster Tp02"; - }; - - temperature-Tp04 { - apple,key-id = "Tp04"; - label = "P-cluster Tp04"; - }; - - temperature-Tp06 { - apple,key-id = "Tp06"; - label = "P-cluster Tp06"; - }; - - temperature-Tp08 { - apple,key-id = "Tp08"; - label = "P-cluster Tp08"; - }; - - temperature-Tp0A { - apple,key-id = "Tp0A"; - label = "P-cluster Tp0A"; - }; - - temperature-Tp0C { - apple,key-id = "Tp0C"; - label = "P-cluster Tp0C"; - }; - - temperature-Tp0E { - apple,key-id = "Tp0E"; - label = "P-cluster Tp0E"; - }; - - temperature-Tp0a { - apple,key-id = "Tp0a"; - label = "P-cluster Tp0a"; - }; - - temperature-Tp0b { - apple,key-id = "Tp0b"; - label = "P-cluster Tp0b"; - }; - - temperature-Tp0c { - apple,key-id = "Tp0c"; - label = "P-cluster Tp0c"; - }; - - temperature-Tp0e { - apple,key-id = "Tp0e"; - label = "P-cluster Tp0e"; - }; - - temperature-Tp0f { - apple,key-id = "Tp0f"; - label = "P-cluster Tp0f"; - }; - - temperature-Tp0g { - apple,key-id = "Tp0g"; - label = "P-cluster Tp0g"; - }; - - temperature-Tp0i { - apple,key-id = "Tp0i"; - label = "P-cluster Tp0i"; - }; - - temperature-Tp0j { - apple,key-id = "Tp0j"; - label = "P-cluster Tp0j"; - }; - - temperature-Tp0k { - apple,key-id = "Tp0k"; - label = "P-cluster Tp0k"; - }; - - temperature-Tp0m { - apple,key-id = "Tp0m"; - label = "P-cluster Tp0m"; - }; - - temperature-Tp0n { - apple,key-id = "Tp0n"; - label = "P-cluster Tp0n"; - }; - - temperature-Tp0o { - apple,key-id = "Tp0o"; - label = "P-cluster Tp0o"; - }; - - temperature-Tp0q { - apple,key-id = "Tp0q"; - label = "P-cluster Tp0q"; - }; - - temperature-Tp0r { - apple,key-id = "Tp0r"; - label = "P-cluster Tp0r"; - }; - - temperature-Tp0s { - apple,key-id = "Tp0s"; - label = "P-cluster Tp0s"; - }; -}; +#include "t8112-hwmon.dtsi" /* * Mesa fingerprint sensor on spi2. The J413 platform device tree diff --git a/arch/arm64/boot/dts/apple/t8112-j415.dts b/arch/arm64/boot/dts/apple/t8112-j415.dts index 2eddcd7a5f3424..1ac373e638ea97 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415.dts +++ b/arch/arm64/boot/dts/apple/t8112-j415.dts @@ -288,6 +288,7 @@ }; #include "hwmon-laptop.dtsi" +#include "t8112-hwmon.dtsi" /* * Mesa fingerprint sensor on spi2 (J415 ADT /arm-io/spi2/mesa): power on AP * GPIO 178, active high, and data-ready on AP GPIO 177. The data-ready edge diff --git a/arch/arm64/boot/dts/apple/t8112-j473.dts b/arch/arm64/boot/dts/apple/t8112-j473.dts index 84ecd65613567d..3ac5bd50eedbf5 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473.dts +++ b/arch/arm64/boot/dts/apple/t8112-j473.dts @@ -277,6 +277,8 @@ }; #include "hwmon-mini.dtsi" +#include "t8112-hwmon-rails.dtsi" +#include "t8112-hwmon.dtsi" #include "t8112-j473-peripherals.dtsi" diff --git a/arch/arm64/boot/dts/apple/t8112-j493.dts b/arch/arm64/boot/dts/apple/t8112-j493.dts index 536010e4a3636a..08ae955c5a1bac 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493.dts +++ b/arch/arm64/boot/dts/apple/t8112-j493.dts @@ -316,6 +316,7 @@ #include "hwmon-laptop.dtsi" #include "hwmon-fan.dtsi" +#include "t8112-hwmon.dtsi" /* * SPI2 uses native chip select. The sensor power line is AP GPIO 178, * active high; the data-ready line is omitted so captures use polling. From d80bb1356d30022b8dfc50b1588367b473007458 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Fri, 20 Nov 2026 00:06:05 -0800 Subject: [PATCH 0466/1514] accel/ane: keep every H16/H17 DMA base inside the buffer its slot binds A task names each buffer the engine reads or writes as a relocated [lo, hi] record, whose 64-bit offset is taken relative to the DVA of the buffer bound to the record's BAR slot. The validator checked that each register lies in a known block and that the operation section binds each slot to the right resource, but not the offset, nor that the slot is bound, nor that a base is relocated at all. At LOAD, once the operation section is checked and before anything is mapped, walk every task: - A DMA base (the input DMA's sources 1 and 2, the output DMA, the coefficient DMA and the lookup table) is written only by a relocated record covering exactly its lo and hi words, on a slot the operation section binds. - The end of the last 64-byte line its transfer touches, ALIGN(offset + extent, 64), stays inside that buffer: a surface's declared size, the scratch's __bss size, or the kernel section to the end of its last 16 KiB page, which is what the kernel slot maps. The offset is unsigned, so a negative one fails; products and sums are overflow-checked. - An input or output extent is width x element bytes x interleave, plus (rows - 1) x row stride, (channel groups - 1) x plane stride, (depth - 1) x depth stride and (groups - 1) x group stride, the interleave packing that many channels per plane. The coefficient extent is its furthest lane (offset plus size, at least the aligned per-channel size) plus each further group and output channel group, a channel group being 16 << (common word 0x40 & 7) channels. The lookup table is its size word, at least 64. - A task that enables an input DMA source, the output DMA or the lookup table (a non-zero configuration word) writes that DMA's base in the same task, and a height and channel count that are not zero. A zero width, depth or group count is read as one: the compiler writes 0 there, and a zero width is in a 256 x 256 matmul that runs correctly on an M4 Pro. Lookup-table tasks configure the coefficient DMA without a base, so that DMA is bounded by the running image below instead. - Fields the extent rules decode stay within what the compiler writes: the output channel group (0x40 & 7) at most 5, and no format bits besides the interleave, the element size and the bits every program sets. - The only other relocated records are the cache-allocation words on the custom BAR slot 4. Dense header bits 21, 22 and 30, and a slot without the relocation bit, are refused. - The DMA registers the bound does not model stay zero: metadata and compression, texture, crop and wrap, the bias, post-scale and palette tables, the destination pixel offset, and the wrap and offset fields beside the cache hints and formats. They stay refused until a program needs them. Outside the DMA blocks, 0x44d0 stays zero and the cache DMA block takes only the six words the compiler writes. The L2, planar engine and neural engine blocks configure on-chip buffers and arithmetic, and cannot be relocated, so they hold no buffer address. Whether the engine starts each task from its defaults or keeps registers from the task before is not known, so both readings are checked: each task over the defaults, and a running image carried across the stream, against which every base written so far is checked after each task with the geometry in force then. Programs leave a word out wherever it holds the default, also when an earlier task set another value. Where that leaves an earlier base with a larger extent, the stream fits only the first reading and is refused. Refusals are ENOEXEC, as for the validator's other program checks. No register documentation is available. The extent rules are read from the encoder of aurora-silicon/mil-hwx-compiler and checked against programs whose bound lands exactly on their buffer. Of the 224 H16G and H17 programs that aurora-silicon/mil-hwx-compiler builds from its fixtures and examples, a mobilenet in every schedule it accepts and the two KUnit fixtures, 215 pass, most of them with the bound exactly equal to the buffer, and every H17 program among them. The running image refuses 8 H16G programs (space-to-depth, depth-to-space, an attention fixture and five L2-resident schedules of the linked mobilenet). One H16G matrix-multiply example is refused under both readings: it gives two 128-channel output groups a channel group stride of 0x40000 over a 0x20000 scratch. KUnit: ane_hx_dma_bound_test and ane_hx_dma_kernel_test cover a base exactly at the end of its buffer, one line past it, negative, wrapping 64 bits, on an unbound slot, unrelocated, scattered, relocated off its pair, and beside an unmodelled register. ane_hx_dma_carry_test covers geometry in one task with the bases in the next, and a base kept while a later task enlarges its geometry. ane_hx_dma_strict_test covers an enabled DMA without its base or with a zero size, the channel group, a format bit and the registers outside the DMA blocks. ane_hx_dma_align_test covers a lookup table at offset 1, which touches two lines. program_add128_dma_test runs the cases through the add-128 fixture's LOAD checks. The mobilenet and add-128 fixture cases still pass. On a J775D (die 0, 27.2 firmware) add-128 x1000 and a [1,128,16,16] add x200 stay bit exact, the linked mobilenet program classifies 16 of 16 images, and programs whose bases leave their buffers are refused at LOAD before anything is mapped. Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/accel/ane/ane_h16_program.c | 56 +++- drivers/accel/ane/ane_h16_program_test.c | 63 ++++ drivers/accel/ane/ane_h16_tasks.h | 390 +++++++++++++++++++++++ drivers/accel/ane/ane_h16_tasks_test.c | 328 ++++++++++++++++++- 4 files changed, 828 insertions(+), 9 deletions(-) diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index e7d9c67bc89a96..c80b4e78548edc 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -8,6 +8,7 @@ #include #include "ane_h16_program.h" +#include "ane_h16_tasks.h" /* * The one LOAD slot table. Slot 1 carries the HWX kernel section, or the @@ -355,6 +356,22 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, } EXPORT_SYMBOL_GPL(ane_h16_process_bindings); +/* The kernel slot runs to the end of the section's last 16 KiB page of its region. */ +static u64 h16_kernel_reach(const struct ane_h16_hwx *hwx) +{ + unsigned int i; + + for (i = 0; i < hwx->region_count; i++) { + const struct ane_h16_hwx_region *r = &hwx->regions[i]; + u64 offset = hwx->kernel.vm - r->vm; + + if (r->kind == ANE_H16_REGION_KERNEL && hwx->kernel.vm >= r->vm && + offset < r->size && hwx->kernel.size <= r->size - offset) + return ALIGN(offset + hwx->kernel.size, SZ_16K) - offset; + } + return hwx->kernel.size; +} + /* * The operation section binds BAR slots to resources: per record, a count at * +8 and (slot, tag) pairs from +0xc. A tag is a generic-section ID, or the @@ -363,6 +380,12 @@ EXPORT_SYMBOL_GPL(ane_h16_process_bindings); * name the resource whose HWX address is that base. Kernel programs must bind * the kernel: the legacy tag 2 instead makes the H17 firmware assert and stop * answering (H17 harness facts, kernel-table programs). + * + * Each DMA base offset in the task stream is taken relative to the DVA of + * the buffer bound to its slot, so every base must name a bound slot and + * stay inside that buffer with the extent of its transfer: a surface's + * declared size, the scratch's __bss size, or the kernel section to the end + * of its last 16 KiB page, which is what the kernel slot maps. */ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_hwx *hwx, const void *operation, @@ -374,6 +397,7 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const u8 *o = operation, *c; unsigned int r, records, i, j; bool kernel_bound = false; + u64 *bound; int ret; if (!hwx || !o || !bindings || count != hwx->surface_count || @@ -390,8 +414,13 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, return -ENOEXEC; records = get_unaligned_le32(o); if (!records || records > ANE_H16_OPERATION_RECORDS_MAX || - operation_size != 4 + (size_t)records * ANE_H16_OPERATION_RECORD) + operation_size != 4 + (size_t)records * ANE_H16_OPERATION_RECORD || + hwx->text.offset > snapshot->size || hwx->text.size > snapshot->size - hwx->text.offset) return -ENOEXEC; + bound = kcalloc(ANE_HX_DMA_SLOTS, sizeof(*bound), GFP_KERNEL); + if (!bound) + return -ENOMEM; + ret = -ENOEXEC; for (r = 0; r < records; r++) { const u8 *rec = o + 4 + r * ANE_H16_OPERATION_RECORD; u32 refs = get_unaligned_le32(rec + 8); @@ -399,31 +428,42 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, if (get_unaligned_le32(rec) || get_unaligned_le32(rec + 4) || refs > ANE_H16_OPERATION_REFS_MAX) - return -ENOEXEC; + goto out; for (i = 0; i < refs; i++) { u32 slot = get_unaligned_le32(rec + 0xc + i * 8); u32 tag = get_unaligned_le32(rec + 0x10 + i * 8); - u64 base, want = 0; + u64 base, want = 0, size = 0; - if (slot >= 64 || (seen & BIT_ULL(slot))) - return -ENOEXEC; + if (slot >= ANE_HX_DMA_SLOTS || (seen & BIT_ULL(slot))) + goto out; seen |= BIT_ULL(slot); base = get_unaligned_le64(c + 0x10 * (slot + 1)); if (tag == ANE_H16_RESOURCE_KERNEL && hwx->kernel.size) { want = hwx->kernel.vm; + size = h16_kernel_reach(hwx); kernel_bound = true; } else if (scratch && hwx->scratch.size && tag == scratch->index) { want = scratch->hwx_vm; + size = hwx->scratch.size; } else { for (j = 0; j < count; j++) - if (tag == bindings[j].index) + if (tag == bindings[j].index) { want = bindings[j].hwx_vm; + size = bindings[j].bytes; + } } if (!want || base != want) - return -ENOEXEC; + goto out; + bound[slot] = size; } } - return hwx->kernel.size && !kernel_bound ? -ENOEXEC : 0; + if (hwx->kernel.size && !kernel_bound) + goto out; + ret = ane_hx_task_stream_dma_validate((const u8 *)snapshot->bytes + hwx->text.offset, + hwx->text.size, bound); +out: + kfree(bound); + return ret; } EXPORT_SYMBOL_GPL(ane_h16_operation_validate); diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index a72ee6616f8d7a..536d2cbb19392f 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -1610,6 +1610,68 @@ static void program_pool_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->count, sent + 2); } +/* The add-128 source 1 base record: [0x4d10, 0x4d14], relocated on BAR slot 6. */ +#define ADD128_SRC1 (0x4d10 / 4 | 1 << 15 | BIT(29) | 6 << 23) + +/* + * Run the LOAD checks of the add-128 program with its source 1 base record + * header and offset replaced. The operation section binds x, y, z to slots + * 6, 7, 8; source 1 reads 128 rows of 0x100 bytes, all 32 KiB of x. + */ +static int add128_dma_load(struct kunit *test, u32 header, u64 offset) +{ + struct ane_h16_process_binding bindings[ANE_H16_SURFACES], scratch = {}; + struct ane_h16_hwx_snapshot *snapshot = kunit_kzalloc(test, sizeof(*snapshot), + GFP_KERNEL); + u8 *hwx = sparse_bytes(test, add128_hwx_runs, ARRAY_SIZE(add128_hwx_runs), + ADD128_HWX_SIZE); + u8 *generic = sparse_bytes(test, add128_generic_runs, ARRAY_SIZE(add128_generic_runs), + ADD128_GENERIC_SIZE); + u8 *operation = sparse_bytes(test, add128_operation_runs, + ARRAY_SIZE(add128_operation_runs), ADD128_OPERATION_SIZE); + unsigned int count; + size_t at; + int ret; + + if (!snapshot || !hwx || !generic || !operation) + return -ENOMEM; + for (at = 0; at + 12 <= ADD128_HWX_SIZE; at += 4) + if (get_unaligned_le32(hwx + at) == ADD128_SRC1) + break; + if (at + 12 > ADD128_HWX_SIZE) + return -ENOENT; + put_unaligned_le32(header, hwx + at); + put_unaligned_le64(offset, hwx + at + 4); + ret = ane_h16_hwx_snapshot_create(hwx, ADD128_HWX_SIZE, snapshot); + if (ret) + return ret; + ret = kunit_add_action_or_reset(test, snapshot_free, snapshot); + if (ret) + return ret; + ret = ane_h16_process_bindings(&snapshot->info, generic, ADD128_GENERIC_SIZE, bindings, + &count, &scratch); + if (!ret) + ret = ane_h16_operation_validate(snapshot, &snapshot->info, operation, + ADD128_OPERATION_SIZE, bindings, count, &scratch); + return ret; +} + +/* Each DMA base stays inside the buffer its slot binds, at LOAD and before any mapping. */ +static void program_add128_dma_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0), 0); + /* One 64-byte line past the end of x, into z's place, and before x. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0x40), -ENOEXEC); + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, 0x10000), -ENOEXEC); + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1, -0x8000), -ENOEXEC); + /* Slot 9, which the operation section does not bind. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, (ADD128_SRC1 & ~(0x3f << 23)) | 9 << 23, 0), + -ENOEXEC); + /* The base without its relocation: an absolute DVA. */ + KUNIT_EXPECT_EQ(test, add128_dma_load(test, ADD128_SRC1 & ~(BIT(29) | 0x3f << 23), 0), + -ENOEXEC); +} + static u8 *fw_sparse_large(struct kunit *test, const struct ane_h16_sparse_run *runs, unsigned int count, size_t size) { @@ -3395,6 +3457,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_add128_slots_test), KUNIT_CASE(program_kernel_slots_test), KUNIT_CASE(program_add128_hwx_test), + KUNIT_CASE(program_add128_dma_test), KUNIT_CASE(program_replies_test), KUNIT_CASE(program_deny_list_test), KUNIT_CASE(program_custom_bar_test), diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h index e96ff85d778abe..0ee1104a9e3901 100644 --- a/drivers/accel/ane/ane_h16_tasks.h +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -6,7 +6,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -130,6 +133,393 @@ ane_h16_task_stream_validate(const void *text, size_t size, u32 expected_tasks) return ane_hx_task_stream_validate(text, size, expected_tasks, 1); } +/* + * DMA bases. A task names each buffer the engine reads or writes as a + * relocated [lo, hi] record: its 64-bit offset is taken relative to the DVA + * of the buffer bound to the record's BAR slot, and nothing after this point + * bounds the sum. The bases are the input DMA's sources 1 and 2, the output + * DMA, the coefficient DMA and the lookup table. + */ +#define ANE_HX_DMA_SLOTS 64 +#define ANE_HX_DMA_WORDS (23 + 81 + 21 + 72) + +/* Image index of a common or DMA register byte address, or -1. */ +static inline int ane_hx_dma_index(u32 addr) +{ + if (addr < 0x5c) + return addr / 4; + if (addr >= 0x4d00 && addr < 0x4e44) + return 23 + (addr - 0x4d00) / 4; + if (addr >= 0x5100 && addr < 0x5154) + return 104 + (addr - 0x5100) / 4; + if (addr >= 0x5500 && addr < 0x5620) + return 125 + (addr - 0x5500) / 4; + return -1; +} + +static inline bool ane_hx_dma_base(u32 addr) +{ + switch (addr & ~4) { + case 0x4d10: case 0x4d28: case 0x5108: case 0x5510: case 0x5618: + return true; + } + return false; +} + +/* + * The DMA registers a task may set: the bases, their strides, formats and + * coefficient lanes, and the words that only configure or hint a transfer. + * The rest of each DMA block (metadata and compression, texture, crop and + * wrap, the bias, post-scale and palette tables) moves addresses this bound + * does not model, and no measured program sets it, so it stays zero. + */ +static inline bool ane_hx_dma_modelled(u32 addr) +{ + return (addr >= 0x4d00 && addr <= 0x4d3c) || addr == 0x4d68 || addr == 0x4d6c || + addr == 0x5100 || (addr >= 0x5108 && addr <= 0x511c) || addr == 0x5138 || + addr == 0x5500 || addr == 0x5504 || (addr >= 0x5510 && addr <= 0x55dc) || + (addr >= 0x5610 && addr <= 0x561c); +} + +/* Source 1, source 2 and destination DMA configuration and coefficient lanes. */ +static inline bool ane_hx_dma_config(u32 addr) +{ + return addr == 0x4d00 || addr == 0x4d04 || addr == 0x5100 || + (addr >= 0x5520 && addr <= 0x555c); +} + +/* Byte address of value @i of the record with header @h. */ +static inline u32 ane_hx_record_addr(u32 h, u32 i) +{ + u32 base = h & 0x7fff, mask = (h >> 15) & 0xffff, bit; + + if (!(h & BIT(31)) || !i) + return (base + i) * 4; + for (bit = 0; bit < 16; bit++) + if ((mask & BIT(bit)) && !--i) + break; + return (base + bit + 1) * 4; +} + +static inline u32 ane_hx_record_count(u32 h) +{ + return h & BIT(31) ? 1 + hweight32((h >> 15) & 0xffff) : ((h >> 15) & 0x3f) + 1; +} + +/* + * Bytes an input or output DMA stream touches from its base: the last + * element of the last row, plane, depth slice and group. Interleave k packs + * k channels into each element, so a plane holds k channels (the measured + * matmul staging writes 128 channels interleaved 8 as 16 planes of 2 KiB, its + * exact scratch). + */ +static inline int ane_hx_dma_tile(const u32 *img, u32 base, u64 *extent) +{ + static const u8 bytes[] = { 1, 1, 2, 4 }; + bool dst = base == 0x5108; + u32 stride = base + 8, format = dst ? 0x5138 : base == 0x4d10 ? 0x4d68 : 0x4d6c; + u32 dim = dst ? 0x14 : 0x4, f = img[ane_hx_dma_index(format)]; + u64 k = max(1U, (f >> 24) & 0xf), n[5], sum, term; + unsigned int i; + + for (i = 0; i < 4; i++) + n[i] = max(1U, img[ane_hx_dma_index(dim + 4 * i)]); + n[4] = max(1U, img[ane_hx_dma_index(0x24)]); + n[2] = DIV_ROUND_UP(n[2], k); + sum = n[0] * bytes[(f >> 12) & 3] * k; + for (i = 1; i < 5; i++) + if (check_mul_overflow(n[i] - 1, (u64)img[ane_hx_dma_index(stride + 4 * (i - 1))], + &term) || + check_add_overflow(sum, term, &sum)) + return -ENOEXEC; + *extent = sum; + return 0; +} + +/* + * Bytes the coefficient DMA reads from its base: the furthest of the 16 lanes + * (offset 0x5560 + 4i, size 0x55a0 + 4i, at least the per-channel aligned + * size 0x5504; an unset size is 64), then every group (stride 0x5518) and + * every output channel group (stride 0x551c) after the first. An output + * channel group is 16 << (common word 0x40 & 7) channels, 128 when that + * word is unset. + */ +static inline int ane_hx_dma_kernel(const u32 *img, u64 *extent) +{ + u64 lanes = 0, groups, ocgs, term; + unsigned int i; + + for (i = 0; i < 16; i++) + lanes = max(lanes, (u64)img[ane_hx_dma_index(0x5560 + 4 * i)] + + max(img[ane_hx_dma_index(0x55a0 + 4 * i)], + img[ane_hx_dma_index(0x5504)])); + groups = max(1U, img[ane_hx_dma_index(0x24)]) - 1; + ocgs = DIV_ROUND_UP((u64)max(1U, img[ane_hx_dma_index(0x1c)]), + 16U << (img[ane_hx_dma_index(0x40)] & 7)) - 1; + if (check_mul_overflow(groups, (u64)img[ane_hx_dma_index(0x5518)], &term) || + check_add_overflow(lanes, term, &lanes) || + check_mul_overflow(ocgs, (u64)img[ane_hx_dma_index(0x551c)], &term) || + check_add_overflow(lanes, term, extent)) + return -ENOEXEC; + return 0; +} + +/* The five DMA bases, in the order of ane_hx_dma_state's arrays. */ +static const u16 ane_hx_dma_base_addr[] = { 0x4d10, 0x4d28, 0x5108, 0x5510, 0x5618 }; +#define ANE_HX_DMA_BASES ARRAY_SIZE(ane_hx_dma_base_addr) + +/* A register image, and each base's slot and offset as last written into it. */ +struct ane_hx_dma_state { + u32 img[ANE_HX_DMA_WORDS]; + u64 offset[ANE_HX_DMA_BASES]; + u8 slot[ANE_HX_DMA_BASES]; + u8 written; /* bit b: base b was written */ +}; + +static inline void ane_hx_dma_defaults(struct ane_hx_dma_state *st) +{ + unsigned int i; + + memset(st, 0, sizeof(*st)); + st->img[ane_hx_dma_index(0x40)] = 3; + for (i = 0; i < 16; i++) + st->img[ane_hx_dma_index(0x55a0 + 4 * i)] = 64; +} + +/* + * Registers outside the common and DMA blocks that the bound does not model. + * The L2 (0x4100), planar engine (0x4500) and neural engine (0x4900) blocks + * configure on-chip buffers and arithmetic, and none of them can be + * relocated, so none carries a buffer address. 0x44d0 is never written; of + * the cache DMA block (0x5900), only the words the compiler writes, none of + * them an address, may be non-zero. + */ +static inline bool ane_hx_other_allowed(u32 addr) +{ + if (addr == 0x44d0) + return false; + if (addr >= 0x5900 && addr < 0x5934) + return addr == 0x5900 || addr == 0x5904 || addr == 0x5908 || + addr == 0x5918 || addr == 0x5928 || addr == 0x592c; + return true; +} + +/* + * Apply one task's records (bytes [rec, end) of @p) to @st, refusing the + * header forms the task stream never uses. A relocated record covering a + * base's [lo, hi] pair sets that base's slot and offset. + */ +static inline int ane_hx_dma_apply(const u8 *p, size_t rec, size_t end, + struct ane_hx_dma_state *st) +{ + unsigned int i, b; + int index; + + while (rec < end) { + u32 h = get_unaligned_le32(p + rec), count = ane_hx_record_count(h); + bool reloc = !(h & BIT(31)) && (h & BIT(29)); + u32 slot = (h >> 23) & 0x3f, first = (h & 0x7fff) * 4; + + rec += 4; + if (count > (end - rec) / 4) + return -ENOEXEC; + /* Dense header bits 21, 22 and 30 are unused, the slot only names a relocation. */ + if (!(h & BIT(31)) && ((h & (BIT(21) | BIT(22) | BIT(30))) || (!reloc && slot))) + return -ENOEXEC; + if (reloc && count == 2 && ane_hx_dma_base(first) && !(first & 4)) { + for (b = 0; ane_hx_dma_base_addr[b] != first; b++) + ; + st->offset[b] = get_unaligned_le32(p + rec) | + (u64)get_unaligned_le32(p + rec + 4) << 32; + st->slot[b] = slot; + st->written |= BIT(b); + } else if (reloc) { + if (slot != 4) + return -ENOEXEC; + for (i = 0; i < count; i++) + if (!ane_hx_dma_config(first + 4 * i)) + return -ENOEXEC; + } + for (i = 0; i < count; i++) { + u32 addr = ane_hx_record_addr(h, i); + + if (!reloc && ane_hx_dma_base(addr)) + return -ENOEXEC; + index = ane_hx_dma_index(addr); + if (index >= 0) + st->img[index] = get_unaligned_le32(p + rec + 4 * i); + else if (get_unaligned_le32(p + rec + 4 * i) && !ane_hx_other_allowed(addr)) + return -ENOEXEC; + } + rec += count * 4; + } + return 0; +} + +/* + * The DMA words of an image: only modelled registers, and no wrap, offset, + * crop or compression. Format bits other than the interleave, the element + * size and the bits every program sets are refused, as is an output channel + * group (common word 0x40 & 7) above 5, the largest the compiler writes. + */ +static inline int ane_hx_dma_image_check(const u32 *img) +{ + unsigned int i; + + for (i = 23; i < ANE_HX_DMA_WORDS; i++) { + u32 addr = i < 104 ? 0x4d00 + (i - 23) * 4 : i < 125 ? 0x5100 + (i - 104) * 4 : + 0x5500 + (i - 125) * 4; + + if (img[i] && !ane_hx_dma_modelled(addr)) + return -ENOEXEC; + } + if ((img[ane_hx_dma_index(0x4d08)] | img[ane_hx_dma_index(0x4d0c)]) & ~0xffU || + (img[ane_hx_dma_index(0x4d68)] | img[ane_hx_dma_index(0x4d6c)]) & ~0x0f003031U || + img[ane_hx_dma_index(0x5138)] & ~0x0f303031U || + (img[ane_hx_dma_index(0x40)] & 7) > 5) + return -ENOEXEC; + return 0; +} + +/* + * What one task enables it must also locate: an input DMA source, the output + * DMA or the lookup table with a non-zero configuration needs its relocated + * base in the same task, and a height and channel count that are not zero. + * A zero width, depth or group count is read as one: the compiler writes 0 + * for them, and a zero width is in the 256 x 256 matmul that runs correctly + * on an M4 Pro. The coefficient DMA is not held to this: lookup-table tasks + * configure it without a base (see ane_hx_task_stream_dma_validate()). + */ +static inline int ane_hx_dma_enabled_check(const struct ane_hx_dma_state *st) +{ + static const struct { u16 config, last, dim; u8 base; } dma[] = { + { 0x4d00, 0x4d00, 0x4, 0 }, { 0x4d04, 0x4d04, 0x4, 1 }, + { 0x5100, 0x5100, 0x14, 2 }, { 0x5600, 0x5614, 0, 4 }, + }; + unsigned int i; + u32 a, on; + + for (i = 0; i < ARRAY_SIZE(dma); i++) { + for (a = dma[i].config, on = 0; a <= dma[i].last; a += 4) + on |= st->img[ane_hx_dma_index(a)]; + if (!on) + continue; + if (!(st->written & BIT(dma[i].base)) || + (dma[i].dim && (!st->img[ane_hx_dma_index(dma[i].dim + 4)] || + !st->img[ane_hx_dma_index(dma[i].dim + 8)]))) + return -ENOEXEC; + } + return 0; +} + +/* + * Base @b of @st, with the extent its image gives, must lie inside the buffer + * bound to its slot: the end of the last 64-byte line it touches, + * ALIGN(offset + extent, 64), at most the buffer's size. The offset is + * unsigned: a negative one is larger than any buffer. + */ +static inline int ane_hx_dma_fits(const struct ane_hx_dma_state *st, unsigned int b, + const u64 bound[ANE_HX_DMA_SLOTS]) +{ + u32 base = ane_hx_dma_base_addr[b]; + u64 extent, last; + int ret = 0; + + if (base == 0x5510) + ret = ane_hx_dma_kernel(st->img, &extent); + else if (base == 0x5618) + extent = max(64U, st->img[ane_hx_dma_index(0x5614)]); + else + ret = ane_hx_dma_tile(st->img, base, &extent); + if (ret || !bound[st->slot[b]] || + check_add_overflow(st->offset[b], extent, &last) || + check_add_overflow(last, 63ULL, &last) || + (last & ~63ULL) > bound[st->slot[b]]) + return -ENOEXEC; + return 0; +} + +/* + * Bound every DMA base of an already validated stream. @bound[s] is the size + * of the buffer the operation section binds to BAR slot s, 0 when it binds + * none. A base must be a relocated [lo, hi] record on a bound slot, and its + * offset plus the extent of its transfer must stay inside that buffer. + * + * Whether the engine starts each task from its defaults or keeps registers + * from the task before is not known, so both readings are checked: + * - each task over the defaults: the bases it writes, with its own words, + * and every DMA it enables has its base in the task; + * - a running image over the whole stream, from the defaults: after each + * task, every base written so far, with the geometry in force then. This + * also bounds a coefficient DMA configured without a base of its own. + * Programs leave out words that hold the default even when an earlier task + * set another value; such a stream fits only the first reading and is + * refused. + */ +static inline int +ane_hx_task_stream_dma_validate(const void *text, size_t size, + const u64 bound[ANE_HX_DMA_SLOTS]) +{ + struct ane_hx_dma_state *task, *run; + const u8 *p = text; + size_t pos = 16; + unsigned int b; + int ret = 0; + + if (!p || !bound || size < 16 || size > ANE_H16_TASK_MAX || (size & 3)) + return -ENOEXEC; + task = kmalloc_array(2, sizeof(*task), GFP_KERNEL); + if (!task) + return -ENOMEM; + run = task + 1; + ane_hx_dma_defaults(run); + while (!ret && pos < size) { + u32 words, header_words = 9; + size_t end, rec; + + if (size - pos < 16) { + ret = -ENOEXEC; + break; + } + words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; + if (!words) { + pos += 16; + continue; + } + if (words < 9 || words > (size - pos) / 4) { + ret = -ENOEXEC; + break; + } + end = pos + words * 4; + if ((get_unaligned_le32(p + pos + 8 * 4) & 3) == 3) + header_words++; + if (words < header_words) { + ret = -ENOEXEC; + break; + } + rec = pos + header_words * 4; + ane_hx_dma_defaults(task); + ret = ane_hx_dma_apply(p, rec, end, task); + if (!ret) + ret = ane_hx_dma_image_check(task->img); + if (!ret) + ret = ane_hx_dma_enabled_check(task); + if (!ret) + ret = ane_hx_dma_apply(p, rec, end, run); + if (!ret) + ret = ane_hx_dma_image_check(run->img); + for (b = 0; !ret && b < ANE_HX_DMA_BASES; b++) { + if (task->written & BIT(b)) + ret = ane_hx_dma_fits(task, b, bound); + if (!ret && (run->written & BIT(b))) + ret = ane_hx_dma_fits(run, b, bound); + } + pos = end == size ? end : ALIGN(end, 16); + } + kfree(task); + return ret; +} + /* Section ordinal is supplied only by the validated complete section table. * This checks Mach-O relocation entries, not the distinct aperture records. */ diff --git a/drivers/accel/ane/ane_h16_tasks_test.c b/drivers/accel/ane/ane_h16_tasks_test.c index 2104e429185b72..a95932e4767704 100644 --- a/drivers/accel/ane/ane_h16_tasks_test.c +++ b/drivers/accel/ane/ane_h16_tasks_test.c @@ -137,6 +137,327 @@ static void ane_h17_prologue_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_h16_task_stream_validate(text, sizeof(text), 1), -ENOEXEC); } +/* + * One 16x16x128 fp16 add task as mil-hwx-compiler writes it: source 1 on BAR + * slot 6 and the destination on slot 7, each a relocated [lo, hi] record, + * rows of 0x40 and planes of 0x400 bytes, a source depth stride of 0. + * Returns the stream size. + */ +static size_t dma_task(u8 *text, u64 src, u64 dst) +{ + static const u32 dims[] = { 16, 16, 128, 0, 16, 16, 128 }; + size_t at = 16 + 9 * 4; + unsigned int i; + +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + memset(text, 0, 256); + put_unaligned_le32(1, text); + PUT(0x4 / 4 | 6 << 15); + for (i = 0; i < ARRAY_SIZE(dims); i++) + PUT(dims[i]); + PUT(0x4d18 / 4 | 2 << 15); + PUT(0x40); + PUT(0x400); + PUT(0); + PUT(0x4d68 / 4); + PUT(0x1002031); + PUT(0x5110 / 4 | 1 << 15); + PUT(0x40); + PUT(0x400); + PUT(0x5138 / 4); + PUT(0x1302031); + PUT(0x4d10 / 4 | 1 << 15 | BIT(29) | 6 << 23); + PUT(lower_32_bits(src)); + PUT(upper_32_bits(src)); + PUT(0x5108 / 4 | 1 << 15 | BIT(29) | 7 << 23); + PUT(lower_32_bits(dst)); + PUT(upper_32_bits(dst)); + /* The cache-allocation word takes the slot 4 custom BAR value. */ + PUT(0x4d00 / 4 | BIT(29) | 4 << 23); + PUT(0x21); +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* Record @n (0-based) of dma_task's one task. */ +static u8 *dma_record(u8 *text, unsigned int n) +{ + static const u8 words[] = { 8, 4, 2, 3, 2, 3, 3, 2 }; + size_t at = 16 + 9 * 4; + + while (n--) + at += words[n] * 4; + return text + at; +} + +static void ane_hx_dma_bound_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + + /* 15 rows of 0x40, 127 planes of 0x400 and one 32-byte row: exactly 128 KiB. */ + size = dma_task(text, 0, 0); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + size = dma_task(text, 0x40, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + size = dma_task(text, 0, 0x20000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + size = dma_task(text, 0, -0x70000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + size = dma_task(text, -1, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A larger buffer takes the same offset. */ + bound[7] = 0x40000; + size = dma_task(text, 0, 0x20000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + + /* A slot the operation section does not bind. */ + bound[7] = 0; + size = dma_task(text, 0, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + bound[7] = 0x20000; + + /* A base without relocation, or relocated on the custom BAR slot. */ + put_unaligned_le32(0x4d10 / 4 | 1 << 15, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(0x4d10 / 4 | 1 << 15 | BIT(29) | 4 << 23, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A relocated record that is not exactly the [lo, hi] pair. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d0c / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 5)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A scatter write of the hi word. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(BIT(31) | BIT(15) | 0x5108 / 4, dma_record(text, 6)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A relocation on a stride, and an unused header bit. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 1)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(30), dma_record(text, 1)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + + /* One byte more of plane stride crosses a line past the end. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x401, dma_record(text, 1) + 8); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* Rows, planes and depth slices whose sum wraps 64 bits to 32 bytes. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x80000001, dma_record(text, 0) + 8); + put_unaligned_le32(0x80000001, dma_record(text, 0) + 12); + put_unaligned_le32(3, dma_record(text, 0) + 16); + put_unaligned_le32(U32_MAX, dma_record(text, 1) + 4); + put_unaligned_le32(U32_MAX, dma_record(text, 1) + 8); + put_unaligned_le32(0x80000000, dma_record(text, 1) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A source 1 metadata address, which the bound does not model. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d40 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A wrap configuration beside the cache hint. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x4d08 / 4, dma_record(text, 2)); + put_unaligned_le32(0x1ce, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(0xce, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); +} + +/* + * Two tasks from dma_task's records: the geometry records (dimensions, strides + * and formats, records 0-4) and the base records (records 5-7), each task + * given @first then @second of them (bit 0 geometry, bit 1 bases), with the + * source plane stride of the second task's geometry set to @plane. + */ +static size_t dma_two(u8 *text, unsigned int first, unsigned int second, u32 plane) +{ + static const unsigned int parts[2][2] = { + { 0, 28 * 4 - 9 * 4 }, { 28 * 4 - 9 * 4, 8 * 4 }, + }; + u8 full[256]; + size_t at = 16, task, rec = 16 + 9 * 4; + unsigned int t, k; + + dma_task(full, 0, 0); + memset(text, 0, 512); + put_unaligned_le32(2, text); + for (t = 0; t < 2; t++) { + unsigned int want = t ? second : first; + + task = at; + memcpy(text + at, full + 16, 9 * 4); + at += 9 * 4; + for (k = 0; k < 2; k++) { + if (!(want & BIT(k))) + continue; + memcpy(text + at, full + rec + parts[k][0], parts[k][1]); + if (k == 0 && t == 1) + /* record 1 (source strides) starts 8 words in: row, plane, depth */ + put_unaligned_le32(plane, text + at + 8 * 4 + 8); + at += parts[k][1]; + } + put_unaligned_le32((at - task) / 4 << 16, text + task); + if (!t) + at = ALIGN(at, 16); + } + return at; +} + +/* + * Whether the engine keeps registers from one task to the next is not known, + * so a stream must fit both ways. Geometry in one task and bases in the next + * fits only per task when the geometry is too large; a base kept from an + * earlier task fits only per task when a later task enlarges its geometry. + */ +static void ane_hx_dma_carry_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[512]; + size_t size; + + /* Both tasks complete and in range. */ + size = dma_two(text, 3, 3, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + /* + * Task N: geometry (and large planes) with no base; task N+1: the bases + * alone, which enable the source with no size of its own. + */ + size = dma_two(text, 3, 2, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + size = dma_two(text, 1, 2, 0x400); + put_unaligned_le32(0x800, text + 16 + 9 * 4 + 8 * 4 + 8); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* The reverse: the bases kept from task N, larger planes in task N+1. */ + size = dma_two(text, 3, 1, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + size = dma_two(text, 3, 1, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); +} + +/* + * A task that enables a DMA must locate it and give it a real size; the + * channel group, the format bits and the registers outside the modelled + * blocks stay within what the compiler writes. + */ +static void ane_hx_dma_strict_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + + /* The destination enabled: the cache word (record 7) becomes its configuration 0x5100. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x5100 / 4, dma_record(text, 7)); + put_unaligned_le32(0x1000021, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + /* ... with a zero channel count, */ + put_unaligned_le32(0, dma_record(text, 0) + 28); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(128, dma_record(text, 0) + 28); + /* ... and without its base: record 6 rewrites the destination strides instead. */ + put_unaligned_le32(0x5110 / 4 | 1 << 15, dma_record(text, 6)); + put_unaligned_le32(0x40, dma_record(text, 6) + 4); + put_unaligned_le32(0x400, dma_record(text, 6) + 8); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A zero channel count on an enabled source. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* A zero width reads as one. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + /* An output channel group of 6, then 5: common word 0x40 in place of the source format. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x40 / 4, dma_record(text, 2)); + put_unaligned_le32(6, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(5, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + /* A source format bit the compiler never sets. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x1002033, dma_record(text, 2) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + /* 0x44d0, and a cache DMA word the compiler never writes, in place of the source format. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0x44d0 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(0x590c / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + put_unaligned_le32(0x5904 / 4, dma_record(text, 2)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); +} + +/* + * The end of a transfer is the end of the last 64-byte line it touches: a + * 64-byte lookup table at offset 1 reads [0, 128). + */ +static void ane_hx_dma_align_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 100 }; + u8 text[64] = {}; + size_t at = 16 + 9 * 4; + + put_unaligned_le32(1, text); + put_unaligned_le32(0x5618 / 4 | 1 << 15 | BIT(29) | 6 << 23, text + at); + put_unaligned_le32(1, text + at + 4); + put_unaligned_le32(0, text + at + 8); + at += 12; + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); + bound[6] = 128; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), 0); + /* Offset 0x41: the line at 0x40 through the one at 0x80. */ + put_unaligned_le32(0x41, text + 16 + 9 * 4 + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); +} + +/* + * Coefficient DMA: 16 lanes of 0x80 bytes at 0x80 apart from a base on slot + * 8, then a second output channel group 0x800 on (256 channels, 128 per + * group). + */ +static void ane_hx_dma_kernel_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [8] = 0x1000 }; + u8 text[512] = {}; + size_t at = 16 + 9 * 4; + unsigned int i; + +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + put_unaligned_le32(1, text); + PUT(0x1c / 4); + PUT(256); + PUT(0x551c / 4); + PUT(0x800); + PUT(0x5560 / 4 | 31 << 15); + for (i = 0; i < 16; i++) + PUT(i * 0x80); + for (i = 0; i < 16; i++) + PUT(0x80); + PUT(0x5510 / 4 | 1 << 15 | BIT(29) | 8 << 23); + PUT(0); + PUT(0); +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), 0); + bound[8] = 0xfc0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); + /* 3 at 0x40 is the default 128-channel group, 2 a 64-channel one: four groups. */ + bound[8] = 0x1000; + put_unaligned_le32(0x40 / 4, text + at); + put_unaligned_le32(2, text + at + 4); + put_unaligned_le32((at + 8 - 16) / 4 << 16, text + 16); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at + 8, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, bound), -ENOEXEC); + bound[8] = 0x2000; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, bound), 0); +} + static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_prologue_test), KUNIT_CASE(ane_h17_prologue_test), @@ -144,6 +465,11 @@ static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_scatter_task_test), KUNIT_CASE(ane_h16_extra_header_test), KUNIT_CASE(ane_h16_relocation_test), + KUNIT_CASE(ane_hx_dma_bound_test), + KUNIT_CASE(ane_hx_dma_kernel_test), + KUNIT_CASE(ane_hx_dma_carry_test), + KUNIT_CASE(ane_hx_dma_strict_test), + KUNIT_CASE(ane_hx_dma_align_test), {} }; @@ -153,5 +479,5 @@ static struct kunit_suite ane_h16_task_suite = { }; kunit_test_suite(ane_h16_task_suite); -MODULE_DESCRIPTION("KUnit tests for H16 task and relocation validation"); +MODULE_DESCRIPTION("KUnit tests for H16 task, relocation and DMA base validation"); MODULE_LICENSE("Dual MIT/GPL"); From 68bc9a8c583cda1be8ae492e7ba73b4831b6f36a Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Fri, 20 Nov 2026 15:17:33 -0800 Subject: [PATCH 0467/1514] accel/ane: send H16/H17 LOAD only the section bytes the validator checked H16_LOAD takes four host-built sections. The generic and operation sections were checked against the HWX field by field, but not their reserved bytes, and the procedure and text-properties sections only for their size. The text properties give the firmware the task stream's framing: segment offset, segment size and task count. The kernel validates the stream as it frames it, from its prologue with the HWX's task count, so properties that frame it differently describe a stream nobody checked. Both sections have one form, which the selftests' h16-sections.py writes and the kernel now derives from the validated program: one procedure, and one text segment covering the whole task stream with its task count. H16_LOAD refuses any other size or byte. The reserved bytes of the generic header and of each entry, and an operation record's bytes after its last reference, must be zero, and an entry's tail word must be ANE_H16_GENERIC_ENTRY_TAIL, as h16-sections.py writes them. Refusals are ENOEXEC, before anything is mapped or sent. The add-128 and mobilenet sections that h16-sections.py builds, which the KUnit fixtures carry, are exactly the kernel's form. KUnit: program_sections_exact_test refuses another task count, segment offset or size, a longer section, a changed procedure, and a nonzero reserved byte in each place above, and refuses such a LOAD before any mapping or firmware traffic. The session tests now pass the procedure and text properties h16-sections.py writes instead of zeroes. On a J775D (die 0, 27.2 firmware) add-128 x1000 and a [1,128,16,16] add x200 stay bit exact and the linked mobilenet program classifies 16 of 16 images; sections in any other form are refused at LOAD. Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/accel/ane/ane_h16_program.c | 66 +++++++++- drivers/accel/ane/ane_h16_program.h | 12 ++ drivers/accel/ane/ane_h16_program_test.c | 154 +++++++++++++++++++++++ 3 files changed, 227 insertions(+), 5 deletions(-) diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index c80b4e78548edc..dd0a5a59e1e641 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -303,10 +303,12 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, hwx->surface_count > ANE_H16_SURFACES || (hwx->scratch.size && !scratch)) return -EINVAL; entries = hwx->surface_count + !!hwx->scratch.size; + /* The firmware reads the whole section: every byte has its one value. */ if (generic_size != ANE_H16_GENERIC_HEADER + entries * ANE_H16_GENERIC_ENTRY || get_unaligned_le32(g) != ANE_H16_GENERIC_MAGIC || !get_unaligned_le32(g + 4) || get_unaligned_le32(g + 4) > ANE_H16_GENERIC_VERSION || + memchr_inv(g + 8, 0, ANE_H16_GENERIC_COUNT - 8) || get_unaligned_le32(g + ANE_H16_GENERIC_COUNT) != entries) return -ENOEXEC; for (i = 0; i < entries; i++) { @@ -321,7 +323,11 @@ int ane_h16_process_bindings(const struct ane_h16_hwx *hwx, const void *generic, if (get_unaligned_le32(e) != 1 || id == 2 || id == 3 || id > ANE_H16_GENERIC_ID_MAX || get_unaligned_le32(e + 8) != direction - 1 || - get_unaligned_le32(e + 0x10) != direction) + get_unaligned_le32(e + 0xc) || + get_unaligned_le32(e + 0x10) != direction || + memchr_inv(e + 0x14, 0, 0xc) || + get_unaligned_le32(e + 0x28) != ANE_H16_GENERIC_ENTRY_TAIL || + get_unaligned_le32(e + 0x2c)) return -ENOEXEC; /* The scratch entry may round __bss up to its 16 KiB mapping. */ if (is_scratch ? bytes < hwx->scratch.size || @@ -427,7 +433,8 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, u64 seen = 0; if (get_unaligned_le32(rec) || get_unaligned_le32(rec + 4) || - refs > ANE_H16_OPERATION_REFS_MAX) + refs > ANE_H16_OPERATION_REFS_MAX || + memchr_inv(rec + 0xc + refs * 8, 0, ANE_H16_OPERATION_RECORD - 0xc - refs * 8)) goto out; for (i = 0; i < refs; i++) { u32 slot = get_unaligned_le32(rec + 0xc + i * 8); @@ -467,6 +474,53 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, } EXPORT_SYMBOL_GPL(ane_h16_operation_validate); +/* + * The procedure and text-properties sections have one form each, which the + * kernel derives from the validated program: one procedure, and one text + * segment of the whole task stream with its task count. The firmware takes + * the stream's framing (segment offset, size, task count) from the text + * properties, so any other form would describe a stream other than the one + * the task validator checked. + */ +void ane_h16_fixed_sections(const struct ane_h16_hwx *hwx, + u8 procedure[ANE_H16_PROCEDURE_SIZE], + u8 properties[ANE_H16_PROPERTIES_SIZE]) +{ + static const u32 call[] = { 1, 3, 0, 0, 1, 0, U32_MAX, 4 }; + unsigned int i; + + memset(procedure, 0, ANE_H16_PROCEDURE_SIZE); + put_unaligned_le32(1, procedure); + put_unaligned_le64(0x18, procedure + 8); + put_unaligned_le64(sizeof(call), procedure + 0x10); + for (i = 0; i < ARRAY_SIZE(call); i++) + put_unaligned_le32(call[i], procedure + 0x18 + i * 4); + memset(properties, 0, ANE_H16_PROPERTIES_SIZE); + put_unaligned_le32(1, properties); + put_unaligned_le32(hwx->tasks, properties + 0xc); + put_unaligned_le64(hwx->text.size, properties + 0x20); +} +EXPORT_SYMBOL_GPL(ane_h16_fixed_sections); + +int ane_h16_fixed_sections_validate(const struct ane_h16_hwx *hwx, + const void *const aux[ANE_H16_AUX_COUNT], + const size_t aux_size[ANE_H16_AUX_COUNT]) +{ + u8 procedure[ANE_H16_PROCEDURE_SIZE], properties[ANE_H16_PROPERTIES_SIZE]; + + if (!hwx || !aux || !aux_size || !aux[ANE_H16_AUX_PROCEDURE] || + !aux[ANE_H16_AUX_TEXT_PROPERTIES]) + return -EINVAL; + ane_h16_fixed_sections(hwx, procedure, properties); + if (aux_size[ANE_H16_AUX_PROCEDURE] != sizeof(procedure) || + aux_size[ANE_H16_AUX_TEXT_PROPERTIES] != sizeof(properties) || + memcmp(aux[ANE_H16_AUX_PROCEDURE], procedure, sizeof(procedure)) || + memcmp(aux[ANE_H16_AUX_TEXT_PROPERTIES], properties, sizeof(properties))) + return -ENOEXEC; + return 0; +} +EXPORT_SYMBOL_GPL(ane_h16_fixed_sections_validate); + /* * The mcache custom-BAR records come from the program descriptor relocation * tuples pinned by the HWX validator. The linear 0x8a0 form has one prefetch @@ -987,9 +1041,11 @@ static int h16_program_bind(const struct ane_h16_program *p, { int ret; - ret = ane_h16_process_bindings(&p->hwx, aux[ANE_H16_AUX_GENERIC], - aux_size[ANE_H16_AUX_GENERIC], b->bindings, - &b->count, &b->scratch); + ret = ane_h16_fixed_sections_validate(&p->hwx, aux, aux_size); + if (!ret) + ret = ane_h16_process_bindings(&p->hwx, aux[ANE_H16_AUX_GENERIC], + aux_size[ANE_H16_AUX_GENERIC], b->bindings, + &b->count, &b->scratch); if (!ret) ret = ane_h16_operation_validate(&p->snapshot, &p->hwx, aux[ANE_H16_AUX_OPERATION], diff --git a/drivers/accel/ane/ane_h16_program.h b/drivers/accel/ane/ane_h16_program.h index bb30d3dce8c20d..be8aae41e34d5f 100644 --- a/drivers/accel/ane/ane_h16_program.h +++ b/drivers/accel/ane/ane_h16_program.h @@ -53,6 +53,8 @@ #define ANE_H16_GENERIC_HEADER 0x208 #define ANE_H16_GENERIC_ENTRY 0x30 #define ANE_H16_GENERIC_ID_MAX 0x3c +/* The u32 at +0x28 of every entry, as every host builder writes it. */ +#define ANE_H16_GENERIC_ENTRY_TAIL 0xffff /* Host-built operation section: a count, then fixed-size BAR records. */ #define ANE_H16_OPERATION_RECORD 0x40c @@ -71,6 +73,10 @@ enum ane_h16_aux { #define ANE_H16_AUX_MIN 0x28 #define ANE_H16_AUX_MAX SZ_64K +/* The one form of the procedure and text-properties sections. */ +#define ANE_H16_PROCEDURE_SIZE 0x38 +#define ANE_H16_PROPERTIES_SIZE 0x28 + /* Source of one LOAD slot. */ enum ane_h16_slot_source { ANE_H16_SLOT_EMPTY, @@ -155,6 +161,12 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_process_binding *bindings, unsigned int count, const struct ane_h16_process_binding *scratch); +void ane_h16_fixed_sections(const struct ane_h16_hwx *hwx, + u8 procedure[ANE_H16_PROCEDURE_SIZE], + u8 properties[ANE_H16_PROPERTIES_SIZE]); +int ane_h16_fixed_sections_validate(const struct ane_h16_hwx *hwx, + const void *const aux[ANE_H16_AUX_COUNT], + const size_t aux_size[ANE_H16_AUX_COUNT]); int ane_h16_custom_bars(const struct ane_h16_hwx_snapshot *snapshot, const struct ane_h16_hwx *hwx, u32 dsid, struct ane_h16_custom_bar *bars, unsigned int *count); diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index 536d2cbb19392f..38d36fb24fdca7 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -589,6 +589,15 @@ static size_t test_aux_size[ANE_H16_AUX_COUNT] = { 0x298, 0x410, 0x38, 0x28 }; #define TEST_GENERIC_BASE 8 +/* The procedure and text-properties sections a host builder writes for hwx. */ +static void fixed_fill(const struct ane_h16_hwx *hwx) +{ + ane_h16_fixed_sections(hwx, test_aux[ANE_H16_AUX_PROCEDURE], + test_aux[ANE_H16_AUX_TEXT_PROPERTIES]); + test_aux_size[ANE_H16_AUX_PROCEDURE] = ANE_H16_PROCEDURE_SIZE; + test_aux_size[ANE_H16_AUX_TEXT_PROPERTIES] = ANE_H16_PROPERTIES_SIZE; +} + static int fw_load_snapshot(struct prog_fw *f, struct ane_h16_hwx_snapshot *snapshot, struct ane_h16_program **p) { @@ -601,6 +610,7 @@ static int fw_load_snapshot(struct prog_fw *f, struct ane_h16_hwx_snapshot *snap test_aux_size[ANE_H16_AUX_OPERATION] = operation_fill(test_aux[ANE_H16_AUX_OPERATION], snapshot, &hwx, TEST_GENERIC_BASE); + fixed_fill(&hwx); return ane_h16_session_load(&f->s, snapshot, test_aux_ptr, test_aux_size, p); } @@ -1245,6 +1255,7 @@ static void program_scratch_test(struct kunit *test) put_unaligned_le32(TEST_GENERIC_BASE + 2, e + 4); test_aux_size[ANE_H16_AUX_GENERIC] = size; + fixed_fill(hwx); KUNIT_ASSERT_EQ(test, ane_h16_session_load(&f->s, snapshot, test_aux_ptr, test_aux_size, &p), 0); KUNIT_ASSERT_TRUE(test, p->has_scratch); @@ -1325,6 +1336,7 @@ static void program_bad_operation_test(struct kunit *test) test_aux_size[ANE_H16_AUX_OPERATION] = operation_fill(test_aux[ANE_H16_AUX_OPERATION], snapshot, &hwx, TEST_GENERIC_BASE); + fixed_fill(&hwx); /* One record more than the section carries. */ put_unaligned_le32(get_unaligned_le32(test_aux[ANE_H16_AUX_OPERATION]) + 1, test_aux[ANE_H16_AUX_OPERATION]); @@ -1719,6 +1731,147 @@ static void mobilenet_sections(struct kunit *test, const void *aux[ANE_H16_AUX_C ARRAY_SIZE(mobilenet_properties_runs), aux_size[3]); } +/* + * Every byte of the four host-built sections has its one value. The add128 + * and mobilenet fixtures' sections from h16-sections.py are the kernel's + * procedure and text properties, and any other procedure, text framing or + * nonzero reserved byte is refused at LOAD, before anything is mapped or sent. + */ +static void program_sections_exact_test(struct kunit *test) +{ + struct ane_h16_process_binding bindings[ANE_H16_SURFACES], scratch = {}; + struct ane_h16_hwx_snapshot *snapshot = kunit_kzalloc(test, sizeof(*snapshot), + GFP_KERNEL); + size_t aux_size[ANE_H16_AUX_COUNT] = { + ADD128_GENERIC_SIZE, ADD128_OPERATION_SIZE, + ADD128_PROCEDURE_SIZE, ADD128_PROPERTIES_SIZE, + }; + static const size_t generic_bytes[] = { 0x8, 0x100, 0x203 }; + static const size_t entry_bytes[] = { 0xc, 0x14, 0x1f, 0x28, 0x2c }; + const void *mobilenet[ANE_H16_AUX_COUNT]; + size_t mobilenet_size[ANE_H16_AUX_COUNT]; + struct ane_h16_hwx_snapshot *m = mobilenet_snapshot(test); + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + void *aux[ANE_H16_AUX_COUNT]; + u8 *hwx, *g, *o, *pr, *tp; + unsigned int i, count; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, snapshot); + KUNIT_ASSERT_NOT_NULL(test, m); + hwx = sparse_bytes(test, add128_hwx_runs, ARRAY_SIZE(add128_hwx_runs), ADD128_HWX_SIZE); + g = sparse_bytes(test, add128_generic_runs, ARRAY_SIZE(add128_generic_runs), + ADD128_GENERIC_SIZE); + o = sparse_bytes(test, add128_operation_runs, ARRAY_SIZE(add128_operation_runs), + ADD128_OPERATION_SIZE); + pr = sparse_bytes(test, add128_procedure_runs, ARRAY_SIZE(add128_procedure_runs), + ADD128_PROCEDURE_SIZE); + tp = sparse_bytes(test, add128_properties_runs, ARRAY_SIZE(add128_properties_runs), + ADD128_PROPERTIES_SIZE); + aux[0] = g; + aux[1] = o; + aux[2] = pr; + aux[3] = tp; + KUNIT_ASSERT_NOT_NULL(test, hwx); + for (i = 0; i < ANE_H16_AUX_COUNT; i++) + KUNIT_ASSERT_NOT_NULL(test, aux[i]); + KUNIT_ASSERT_EQ(test, ane_h16_hwx_snapshot_create(hwx, ADD128_HWX_SIZE, snapshot), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, snapshot_free, snapshot), 0); + + /* What the builder wrote is the kernel's form, for one task and for 28. */ + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), 0); + mobilenet_sections(test, mobilenet, mobilenet_size); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&m->info, mobilenet, + mobilenet_size), 0); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&m->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + + /* Another task count, segment offset or size, or a longer section. */ + put_unaligned_le32(2, tp + 0xc); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le32(1, tp + 0xc); + put_unaligned_le64(0x10, tp + 0x10); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le64(0, tp + 0x10); + put_unaligned_le64(0x120, tp + 0x20); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le64(0x130, tp + 0x20); + aux_size[3] = ADD128_PROPERTIES_SIZE + 4; + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + aux_size[3] = ADD128_PROPERTIES_SIZE; + /* A second procedure, or another word of the one there is. */ + put_unaligned_le32(2, pr); + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + put_unaligned_le32(1, pr); + pr[0x34] = 5; + KUNIT_EXPECT_EQ(test, ane_h16_fixed_sections_validate(&snapshot->info, + (const void *const *)aux, + aux_size), -ENOEXEC); + pr[0x34] = 4; + + /* Reserved generic bytes: in the header and in every field of an entry. */ + KUNIT_ASSERT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, ADD128_GENERIC_SIZE, + bindings, &count, &scratch), 0); + for (i = 0; i < ARRAY_SIZE(generic_bytes); i++) { + g[generic_bytes[i]] ^= 1; + KUNIT_EXPECT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, + ADD128_GENERIC_SIZE, bindings, + &count, &scratch), -ENOEXEC); + g[generic_bytes[i]] ^= 1; + } + for (i = 0; i < ARRAY_SIZE(entry_bytes); i++) { + u8 *e = g + ANE_H16_GENERIC_HEADER + 2 * ANE_H16_GENERIC_ENTRY + entry_bytes[i]; + + *e ^= 1; + KUNIT_EXPECT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, + ADD128_GENERIC_SIZE, bindings, + &count, &scratch), -ENOEXEC); + *e ^= 1; + } + KUNIT_ASSERT_EQ(test, ane_h16_process_bindings(&snapshot->info, g, ADD128_GENERIC_SIZE, + bindings, &count, &scratch), 0); + /* An operation record's bytes after its last reference. */ + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), 0); + o[4 + 0xc + 3 * 8] = 7; + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), -ENOEXEC); + o[4 + 0xc + 3 * 8] = 0; + o[ADD128_OPERATION_SIZE - 1] = 1; + KUNIT_EXPECT_EQ(test, ane_h16_operation_validate(snapshot, &snapshot->info, o, + ADD128_OPERATION_SIZE, bindings, count, + &scratch), -ENOEXEC); + o[ADD128_OPERATION_SIZE - 1] = 0; + + /* At LOAD: refused before any mapping or firmware traffic, then loads. */ + put_unaligned_le32(2, tp + 0xc); + KUNIT_EXPECT_EQ(test, ane_h16_session_load(&f->s, snapshot, (const void *const *)aux, + aux_size, &p), -ENOEXEC); + KUNIT_EXPECT_PTR_EQ(test, p, NULL); + KUNIT_EXPECT_EQ(test, f->count, 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + put_unaligned_le32(1, tp + 0xc); + KUNIT_ASSERT_EQ(test, ane_h16_session_load(&f->s, snapshot, (const void *const *)aux, + aux_size, &p), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); +} + /* * The H17 MobileNetV1 HWX is one linked program: 28 tasks, input x and * output y as surfaces, the 3.5 MiB __DATA scratch on BAR slot 3 and the @@ -3458,6 +3611,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_kernel_slots_test), KUNIT_CASE(program_add128_hwx_test), KUNIT_CASE(program_add128_dma_test), + KUNIT_CASE(program_sections_exact_test), KUNIT_CASE(program_replies_test), KUNIT_CASE(program_deny_list_test), KUNIT_CASE(program_custom_bar_test), From e2ec946581a7054c28ab530b8da24e81383ae495 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:25:27 +1100 Subject: [PATCH 0468/1514] HID: spi-hid-apple: bound message reassembly by the buffer size spihid_assemble_message() reassembles a message that spans several SPI packets into spihid->report.buf, which is SPIHID_MAX_INPUT_REPORT_SIZE bytes. The only bound on a fragmented message was that offset, length and remain fit 16 bits, so a message declared longer than the buffer had its later fragments copied past its end. Drop a fragment whose message does not fit the reassembly buffer. Continuation fragments have to match the first fragment's total, so every copy now stays inside the buffer. spihid_process_iface_hid_report_desc() also copied a report descriptor for the management interface into iface->hid_desc, which is allocated only for the keyboard, trackpad and actuator interfaces. Ignore a descriptor for an interface without a descriptor buffer. Add KUnit cases for a message longer than the buffer, a message that fills it exactly, and a descriptor for the management interface. Signed-off-by: Ryan Murray --- drivers/hid/spi-hid/spi-hid-apple-core.c | 9 ++- drivers/hid/spi-hid/spi-hid-apple-test.c | 83 ++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/drivers/hid/spi-hid/spi-hid-apple-core.c b/drivers/hid/spi-hid/spi-hid-apple-core.c index d2b62f57cd8c0b..5a1bbcbccde466 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-core.c +++ b/drivers/hid/spi-hid/spi-hid-apple-core.c @@ -776,7 +776,8 @@ static bool spihid_process_iface_hid_report_desc(struct spihid_apple *spihid, { struct spihid_interface *iface = spihid_get_iface(spihid, num); - if (!iface) + /* Only interfaces registered as HID devices have a descriptor buffer. */ + if (!iface || !iface->hid_desc) return false; if (iface->hid_desc_len == 0) { @@ -917,7 +918,11 @@ static void spihid_assemble_message(struct spihid_apple *spihid, remain = le16_to_cpu(pkt->remain); offset = le16_to_cpu(pkt->offset); - if (offset + length + remain > U16_MAX) { + /* The complete message has to fit the reassembly buffer. */ + if (offset + length + remain > SPIHID_MAX_INPUT_REPORT_SIZE) { + dev_warn_ratelimited(dev, + "dropping oversized report off:%zu len:%zu remain:%zu\n", + offset, length, remain); return; } diff --git a/drivers/hid/spi-hid/spi-hid-apple-test.c b/drivers/hid/spi-hid/spi-hid-apple-test.c index 2d9e394559aec5..d9545fe908f125 100644 --- a/drivers/hid/spi-hid/spi-hid-apple-test.c +++ b/drivers/hid/spi-hid/spi-hid-apple-test.c @@ -319,6 +319,86 @@ static void spihid_test_no_set_retry(struct kunit *test) KUNIT_EXPECT_EQ(test, ctx->writes, 1); } +static void spihid_test_fragment(struct spihid_apple *spihid, u16 offset, + u16 remain) +{ + struct spihid_transfer_packet *pkt = (void *)spihid->rx_buf; + + memset(pkt, 0, sizeof(*pkt)); + pkt->flags = SPIHID_READ_PACKET; + pkt->device = SPIHID_DEVICE_ID_TP; + pkt->offset = cpu_to_le16(offset); + pkt->remain = cpu_to_le16(remain); + pkt->length = cpu_to_le16(sizeof(pkt->data)); + memset(pkt->data, 0x5a, sizeof(pkt->data)); + pkt->crc16 = cpu_to_le16(crc16(0, (u8 *)pkt, + offsetof(struct spihid_transfer_packet, crc16))); + spihid_process_read(spihid); +} + +/* A fragmented message longer than the reassembly buffer is dropped. */ +static void spihid_test_oversized_message(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + struct spihid_apple *spihid = ctx->spihid; + const size_t frag = sizeof(((struct spihid_transfer_packet *)0)->data); + const size_t total = SPIHID_MAX_INPUT_REPORT_SIZE + 2 * frag; + const size_t guard = 2 * frag; + size_t offset, i; + u8 *buf; + + /* Room past the real buffer size, so an overrun is visible. */ + buf = kunit_kzalloc(test, SPIHID_MAX_INPUT_REPORT_SIZE + guard, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf + SPIHID_MAX_INPUT_REPORT_SIZE, 0xc3, guard); + spihid->report.buf = buf; + + /* Every fragment but the last, so the message never completes. */ + for (offset = 0; offset + frag < total; offset += frag) { + spihid_test_fragment(spihid, offset, total - offset - frag); + KUNIT_EXPECT_LE(test, spihid->report.length, + SPIHID_MAX_INPUT_REPORT_SIZE); + KUNIT_EXPECT_LE(test, spihid->report.offset, + SPIHID_MAX_INPUT_REPORT_SIZE); + } + + for (i = 0; i < guard; i++) + if (buf[SPIHID_MAX_INPUT_REPORT_SIZE + i] != 0xc3) + break; + KUNIT_EXPECT_EQ(test, i, guard); +} + +/* A message that fills the buffer exactly is still reassembled. */ +static void spihid_test_max_message(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + struct spihid_apple *spihid = ctx->spihid; + const size_t frag = sizeof(((struct spihid_transfer_packet *)0)->data); + const size_t total = SPIHID_MAX_INPUT_REPORT_SIZE; + size_t offset; + + for (offset = 0; offset + frag < total; offset += frag) { + spihid_test_fragment(spihid, offset, total - offset - frag); + KUNIT_EXPECT_EQ(test, spihid->report.offset, offset + frag); + KUNIT_EXPECT_EQ(test, spihid->report.length, total); + } +} + +/* The management interface has no descriptor buffer. */ +static void spihid_test_mngt_report_desc(struct kunit *test) +{ + struct spihid_test *ctx = test->priv; + u8 desc[16] = { 0x05, 0x01 }; + + KUNIT_EXPECT_NULL(test, ctx->spihid->mngt.hid_desc); + KUNIT_EXPECT_FALSE(test, + spihid_process_iface_hid_report_desc(ctx->spihid, + SPIHID_DEVICE_ID_MNGT, + desc, sizeof(desc))); + KUNIT_EXPECT_EQ(test, ctx->spihid->mngt.hid_desc_len, 0); +} + static struct kunit_case spihid_test_cases[] = { KUNIT_CASE(spihid_test_bad_status), KUNIT_CASE(spihid_test_later_get_bad_status), @@ -329,6 +409,9 @@ static struct kunit_case spihid_test_cases[] = { KUNIT_CASE(spihid_test_mixed_retry_limit), KUNIT_CASE(spihid_test_spi_error_no_retry), KUNIT_CASE(spihid_test_no_set_retry), + KUNIT_CASE(spihid_test_oversized_message), + KUNIT_CASE(spihid_test_max_message), + KUNIT_CASE(spihid_test_mngt_report_desc), {} }; From 451b707c93a2d5be73f3549c1386c6c10c8e5848 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:50:44 +1100 Subject: [PATCH 0469/1514] arm64: dts: apple: t602x: leave the SEP alias off J474s and J475c for now With the alias the boot loader reserves sepfw and publishes the boot manifests, and apple_sep then makes the SEP's one-shot warm registration. That has a hardware row on the Mac mini (J473) only; J474s and J475c have never booted with it, and a registration cannot be taken back within a boot. Drop their aliases until each has a row; they follow separately. Also name the boot loader in the SEP node comments rather than m1n1. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6020-j474s.dts | 4 ---- arch/arm64/boot/dts/apple/t6021-j475c.dts | 4 ---- arch/arm64/boot/dts/apple/t602x-die0.dtsi | 5 +++-- arch/arm64/boot/dts/apple/t8112.dtsi | 5 +++-- 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6020-j474s.dts b/arch/arm64/boot/dts/apple/t6020-j474s.dts index 7b80e06270ab5e..3d2b4c3e0211b3 100644 --- a/arch/arm64/boot/dts/apple/t6020-j474s.dts +++ b/arch/arm64/boot/dts/apple/t6020-j474s.dts @@ -21,10 +21,6 @@ / { compatible = "apple,j474s", "apple,t6020", "apple,arm-platform"; model = "Apple Mac mini (M2 Pro, 2023)"; - - aliases { - sep = &sep; - }; }; /* PCIe devices */ diff --git a/arch/arm64/boot/dts/apple/t6021-j475c.dts b/arch/arm64/boot/dts/apple/t6021-j475c.dts index fa6ee51e9cf4bb..c3fce206ab662a 100644 --- a/arch/arm64/boot/dts/apple/t6021-j475c.dts +++ b/arch/arm64/boot/dts/apple/t6021-j475c.dts @@ -15,10 +15,6 @@ / { compatible = "apple,j475c", "apple,t6021", "apple,arm-platform"; model = "Apple Mac Studio (M2 Max, 2023)"; - - aliases { - sep = &sep; - }; }; &wifi0 { diff --git a/arch/arm64/boot/dts/apple/t602x-die0.dtsi b/arch/arm64/boot/dts/apple/t602x-die0.dtsi index 488afa4e9e5744..7c1799131b46c5 100644 --- a/arch/arm64/boot/dts/apple/t602x-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t602x-die0.dtsi @@ -728,8 +728,9 @@ * registration, no cold boot), so apple_sep enables this node * and sep_dart with a changeset at module load, once it has * picked this SoC's profile and before the DART probes. A - * board with the enclave only needs the sep alias, which m1n1 - * uses to add the sepfw region and the boot manifests. + * board with the enclave only needs the sep alias, which the + * boot loader uses to add the sepfw region and the boot + * manifests. */ sep: sep@396400000 { compatible = "apple,sep"; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index a645b90092883b..1244444d470d57 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1853,8 +1853,9 @@ * registration, no cold boot), so apple_sep enables this node * and sep_dart with a changeset at module load, once it has * picked this SoC's profile and before the DART probes. A - * board with the enclave only needs the sep alias, which m1n1 - * uses to add the sepfw region and the boot manifests. + * board with the enclave only needs the sep alias, which the + * boot loader uses to add the sepfw region and the boot + * manifests. */ sep: sep@25e400000 { compatible = "apple,sep"; From c0b3e1c48210ab1d5779d210ddb876aa484e5a4a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:05:35 +1100 Subject: [PATCH 0470/1514] tools/aurora-sep: refuse, rather than skip, a /tmp Limine lock root cannot own Taking /tmp/limine-global.lock only when root already owned it meant that a missing file, or one another user had placed there, skipped the lock. An older Omarchy Limine tool that takes only that lock could then write the EFI partition at the same time as these tools. Create the lock when it is missing and take it as before. The Python tools open it with O_CREAT|O_RDWR|O_NOFOLLOW|O_NONBLOCK, without O_EXCL, and check it with fstat. The shell script creates a missing one with noclobber, which opens with O_EXCL, and checks the open descriptor. Anything else at that path makes the tool refuse with a message, before it changes anything: a file of another user, a link, a non-regular file, or an open that fs.protected_regular denies (EACCES, ELOOP). Update the installer's embedded copies and the air-gpu-oneshot.sh sha256. Signed-off-by: Ryan Murray --- tools/aurora-sep/air-gpu/air-gpu-oneshot.sh | 20 ++-- tools/aurora-sep/esp-history.py | 26 ++--- tools/aurora-sep/install-aurora-sep.sh | 55 ++++++----- tools/aurora-sep/m3-boot-profile.py | 27 +++--- tools/aurora-sep/tests/test_boot_locks.py | 100 +++++++++++--------- 5 files changed, 133 insertions(+), 95 deletions(-) diff --git a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh index b89fc8ac3398ae..0e997d434268a7 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh @@ -92,8 +92,8 @@ UBOOT_GUID=b2ac5fc9-92b7-4acd-aeac-11e818c3130c GLOBAL_GUID=8be4df61-93ca-11d2-aa0d-00e098032b8c # Omarchy's Limine tools take one of these before they touch the EFI partition (newer ones the # first, older ones the second); maclab takes both in this order, and so does this script. The -# second is in world-writable /tmp, where any user could make or hold it first: it is taken only -# when it is already there as a regular file of root's (COMPAT_LOCKS, never created). +# second is in world-writable /tmp, where any user could make or hold it first: it is created if +# missing, and anything there that is not root's own regular file makes the script refuse. LOCKS="/run/lock/boot-partition.lock" COMPAT_LOCKS="/tmp/limine-global.lock" STATE_DIR=/var/lib/air-gpu @@ -307,7 +307,10 @@ take_locks() { LOCK_FDS+=("$fd") done for l in $COMPAT_LOCKS; do - open_compat_lock "$l" || continue + if ! open_compat_lock "$l"; then + release_locks + refuse "$l is not root's own lock file (a link, another user's file or not a regular file); remove it and retry." + fi fd=$COMPAT_FD if ! flock -w 5 "$fd"; then release_locks @@ -316,14 +319,17 @@ take_locks() { LOCK_FDS+=("$fd") done } -# Open a compatibility lock read-only (never created) into COMPAT_FD, and keep it only when the -# opened file is a regular file owned by this user (root) and is the path itself, not something -# a symbolic link points to; that is checked on the open descriptor. The test before the open only -# avoids opening a FIFO (which would block): in sticky /tmp nobody else can replace root's file. +# Open the compatibility lock into COMPAT_FD; fails (and the caller refuses) unless it ends up +# a regular file owned by this user (root) at that very path. A missing one is created with +# noclobber, which opens with O_EXCL and so never follows a link. The test before the open +# keeps a FIFO or another user's file from being opened at all; in sticky /tmp nobody else can +# replace root's own file afterwards. The open descriptor is checked again (owner, type, and +# the path's own inode, so not a link's target). COMPAT_FD= open_compat_lock() { local l=$1 fd owner inode type COMPAT_FD= + [[ -e $l || -L $l ]] || (set -C; : >"$l") 2>/dev/null || true [[ -f $l && ! -L $l && -O $l ]] || return 1 exec {fd}<"$l" 2>/dev/null || return 1 # stat inherits the descriptor: /proc/self/fd/N is the file that was opened. diff --git a/tools/aurora-sep/esp-history.py b/tools/aurora-sep/esp-history.py index a8c11bcff0fce0..ed76460d8ea1b9 100644 --- a/tools/aurora-sep/esp-history.py +++ b/tools/aurora-sep/esp-history.py @@ -2,6 +2,7 @@ """Archive unreferenced EFI history while retaining boot and recovery entries.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -88,20 +89,25 @@ def inventory(esp, state): def compat_lock(path): - """fd of the compatibility lock older Omarchy Limine tools take, or None. + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). - It sits in world-writable /tmp, where any user could create it first or - hold it. So it is never created or followed: it is used only when it is - already there as a regular file owned by this (root) user; otherwise the - /run/lock lock alone serializes the boot partition.""" + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" try: - fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) - except OSError: - return None + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise st = os.fstat(fd) if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): os.close(fd) - return None + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') return fd @contextlib.contextmanager @@ -117,8 +123,6 @@ def lock(paths, compat=()): fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) for path in compat: fd = compat_lock(path) - if fd is None: - continue fds.append(fd) fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index 685fe49a14d0d0..3eb733bff25f55 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -685,7 +685,7 @@ M3_PERSISTENT_TRANSACTION_ACTIVE=0 M3_PERSISTENT_MAIN_ARMED=0 M3_GPU_BIN=/usr/local/bin M3_GPU_SCRIPTS=( - "air-gpu-oneshot.sh 0cb379e91c4cdccbfa8591dfea362413bb420953918b4f6d29f0f610c9cd7923" + "air-gpu-oneshot.sh 26b0417faf36ff6f4440ba2aa99aeb9de8272eafe04d45bddc8a50e4a4017158" "air-gpu-collect.sh 6a457261dc9773401f2ec7e436839a5f0d3b2bccdd9a90f013f8e72878189879" "air-gpu-job.sh 9a0eb9aab52fd099488054e4ed4846c579b19fc9f78144245242b6975a40da1d" ) @@ -7125,6 +7125,7 @@ esp_history_builtin() { """Archive unreferenced EFI history while retaining boot and recovery entries.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -7211,20 +7212,25 @@ def inventory(esp, state): def compat_lock(path): - """fd of the compatibility lock older Omarchy Limine tools take, or None. + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). - It sits in world-writable /tmp, where any user could create it first or - hold it. So it is never created or followed: it is used only when it is - already there as a regular file owned by this (root) user; otherwise the - /run/lock lock alone serializes the boot partition.""" + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" try: - fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) - except OSError: - return None + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise st = os.fstat(fd) if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): os.close(fd) - return None + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') return fd @contextlib.contextmanager @@ -7240,8 +7246,6 @@ def lock(paths, compat=()): fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) for path in compat: fd = compat_lock(path) - if fd is None: - continue fds.append(fd) fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) yield @@ -7573,6 +7577,7 @@ m3_boot_profile_install() { """Retain the running Limine UKI and publish bounded experimental activation.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -7610,20 +7615,25 @@ def atomic(path, data): if os.path.exists(name): os.unlink(name) def compat_lock(path): - """fd of the compatibility lock older Omarchy Limine tools take, or None. + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). - It sits in world-writable /tmp, where any user could create it first or - hold it. So it is never created or followed: it is used only when it is - already there as a regular file owned by this (root) user; otherwise the - /run/lock lock alone serializes the boot partition.""" + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" try: - fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) - except OSError: - return None + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise st = os.fstat(fd) if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): os.close(fd) - return None + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') return fd @contextlib.contextmanager @@ -7639,7 +7649,6 @@ def locks(paths, timeout=30.0, compat=()): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') else: fd = compat_lock(path) - if fd is None: continue fds.append(fd) while True: try: @@ -7832,7 +7841,7 @@ def main(): p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') p.add_argument('--compat-lock', type=Path, action='append', - help='a lock taken only if it already exists as a regular file of this user') + help='a lock in a shared directory: created if missing, refused unless a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: diff --git a/tools/aurora-sep/m3-boot-profile.py b/tools/aurora-sep/m3-boot-profile.py index 02f1c58d86fdbe..cefc808869f846 100644 --- a/tools/aurora-sep/m3-boot-profile.py +++ b/tools/aurora-sep/m3-boot-profile.py @@ -2,6 +2,7 @@ """Retain the running Limine UKI and publish bounded experimental activation.""" import argparse import contextlib +import errno import fcntl import hashlib import json @@ -39,20 +40,25 @@ def atomic(path, data): if os.path.exists(name): os.unlink(name) def compat_lock(path): - """fd of the compatibility lock older Omarchy Limine tools take, or None. + """fd of the compatibility lock older Omarchy Limine tools take (/tmp/limine-global.lock). - It sits in world-writable /tmp, where any user could create it first or - hold it. So it is never created or followed: it is used only when it is - already there as a regular file owned by this (root) user; otherwise the - /run/lock lock alone serializes the boot partition.""" + It is created when missing (root's, 0600) and never followed through a + link. /tmp is world-writable, so anything else at that path (a file of + another user, a link, a FIFO, or a file fs.protected_regular will not let + root open) is refused: going on without the lock could let an older + Limine tool write the EFI partition at the same time.""" try: - fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) - except OSError: - return None + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600) + except OSError as error: + if error.errno in (errno.EACCES, errno.EPERM, errno.ELOOP, errno.ENXIO): + raise ValueError(f'{path} is not root\'s own lock file ({os.strerror(error.errno)}); ' + 'remove it and retry. Nothing was changed') from None + raise st = os.fstat(fd) if not stat.S_ISREG(st.st_mode) or st.st_uid != os.geteuid(): os.close(fd) - return None + raise ValueError(f'{path} is not root\'s own lock file (a link, another user\'s file or ' + 'not a regular file); remove it and retry. Nothing was changed') return fd @contextlib.contextmanager @@ -68,7 +74,6 @@ def locks(paths, timeout=30.0, compat=()): if not stat.S_ISREG(os.fstat(fd).st_mode): raise ValueError('nonregular boot lock') else: fd = compat_lock(path) - if fd is None: continue fds.append(fd) while True: try: @@ -261,7 +266,7 @@ def main(): p.add_argument('--modules', type=Path, default=Path('/usr/lib/modules')) p.add_argument('--lock', type=Path, action='append') p.add_argument('--compat-lock', type=Path, action='append', - help='a lock taken only if it already exists as a regular file of this user') + help='a lock in a shared directory: created if missing, refused unless a regular file of this user') p.add_argument('--lock-timeout', type=float, default=30.0, help='total boot-lock wait, in seconds (0..30)') args = p.parse_args() if not 0 <= args.lock_timeout <= 30: diff --git a/tools/aurora-sep/tests/test_boot_locks.py b/tools/aurora-sep/tests/test_boot_locks.py index 1efe90ac948f0b..07f4df6f10da88 100644 --- a/tools/aurora-sep/tests/test_boot_locks.py +++ b/tools/aurora-sep/tests/test_boot_locks.py @@ -1,11 +1,13 @@ -"""The boot-partition tools' compatibility lock in /tmp: taken only when it is already there as a -regular file of the tool's own user (root), never created and never followed through a link. -The /run/lock lock is taken as before.""" +"""The boot-partition tools' compatibility lock in /tmp: created when missing and locked, never +followed through a link, and anything at that path that is not a regular file of the tool's own +user (root) makes the tool refuse before it changes anything. The /run/lock lock is taken as +before.""" from pathlib import Path import fcntl import importlib.util import os import shutil +import stat import subprocess import tempfile import unittest @@ -59,40 +61,55 @@ def test_defaults_name_the_compat_lock_separately(self): self.assertIn("args.lock = [Path('/run/lock/boot-partition.lock')]", text) self.assertIn("args.compat_lock = args.compat_lock or [Path('/tmp/limine-global.lock')]", text) - def test_missing_compat_lock_is_not_created(self): + def test_missing_compat_lock_is_created_and_locked(self): for name, locker in self.lockers(): with self.subTest(name): with locker(): self.assertTrue(held_by_someone(self.boot)) - self.assertFalse(self.compat.exists()) + self.assertTrue(held_by_someone(self.compat)) + st = self.compat.lstat() + self.assertTrue(stat.S_ISREG(st.st_mode)) + self.assertEqual(stat.S_IMODE(st.st_mode), 0o600) + self.compat.unlink() - def test_symlinked_compat_lock_is_not_followed(self): - target = self.root / 'victim' - self.compat.symlink_to(target) + def assert_refused(self): for name, locker in self.lockers(): with self.subTest(name): - with locker(): - pass - self.assertFalse(target.exists()) + with self.assertRaises(ValueError) as e: + with locker(): + self.fail('ran without the compatibility lock') + self.assertIn('Nothing was changed', str(e.exception)) + self.assertFalse(held_by_someone(self.boot)) + + def test_symlinked_compat_lock_refuses(self): + target = self.root / 'victim' + self.compat.symlink_to(target) + self.assert_refused() + self.assertFalse(target.exists()) target.write_text('x') - for name, locker in self.lockers(): - with self.subTest(name + ' existing target'): - with locker(): - self.assertFalse(held_by_someone(target)) + self.assert_refused() + self.assertFalse(held_by_someone(target)) - def test_compat_lock_of_another_user_is_ignored_even_when_held(self): + def test_compat_lock_of_another_user_refuses(self): self.compat.touch() - holder = os.open(self.compat, os.O_RDONLY) - self.addCleanup(os.close, holder) - fcntl.flock(holder, fcntl.LOCK_EX) # The file belongs to someone else when the tool's own uid is another one. + with patch.object(os, 'geteuid', return_value=os.geteuid() + 1): + self.assert_refused() + + def test_open_refused_by_the_kernel_refuses(self): + # fs.protected_regular: root's O_CREAT open of another user's file in sticky /tmp. + real = os.open + + def protected(path, flags, *a): + if Path(path) == self.compat: + raise PermissionError(13, 'Permission denied') + return real(path, flags, *a) for module in (ESP, M3): - with self.subTest(module.__name__), patch.object(module.os, 'geteuid', - return_value=os.geteuid() + 1): - ctx = ESP.lock([self.boot], [self.compat]) if module is ESP else \ - M3.locks([self.boot], 0.2, [self.compat]) - with ctx: - self.assertTrue(held_by_someone(self.boot)) + with self.subTest(module.__name__), patch.object(module.os, 'open', side_effect=protected): + with self.assertRaises(ValueError): + with (ESP.lock([self.boot], [self.compat]) if module is ESP + else M3.locks([self.boot], 0.2, [self.compat])): + self.fail('ran without the compatibility lock') def test_own_compat_lock_is_taken_and_a_holder_still_blocks(self): self.compat.touch() @@ -112,12 +129,9 @@ def test_own_compat_lock_is_taken_and_a_holder_still_blocks(self): with M3.locks([self.boot], 0.2, [self.compat]): pass - def test_a_fifo_is_not_a_lock(self): + def test_a_fifo_refuses(self): os.mkfifo(self.compat) - for name, locker in self.lockers(): - with self.subTest(name): - with locker(): - pass + self.assert_refused() def test_installer_copies_match(self): installer = INSTALLER.read_text() @@ -161,24 +175,24 @@ def test_defaults(self): self.assertIn('\nLOCKS="/run/lock/boot-partition.lock"\n', text) self.assertIn('\nCOMPAT_LOCKS="/tmp/limine-global.lock"\n', text) - def test_missing_compat_lock_is_not_created(self): - r = self.take() + def test_missing_compat_lock_is_created_and_held(self): + r = self.take(self.probe(self.compat)) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn('held 1', r.stdout) - self.assertFalse(self.compat.exists()) + self.assertIn('held 2', r.stdout) + self.assertIn('busy', r.stdout) + self.assertTrue(self.compat.is_file() and not self.compat.is_symlink()) - def test_symlinked_compat_lock_is_not_used(self): + def test_symlinked_compat_lock_refuses(self): target = self.root / 'victim' target.write_text('x') self.compat.symlink_to(target) r = self.take(self.probe(target)) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn('held 1', r.stdout) - self.assertIn('free', r.stdout) + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) + self.assertIn("not root's own lock file", r.stdout) self.compat.unlink() self.compat.symlink_to(self.root / 'missing') r = self.take() - self.assertIn('held 1', r.stdout) + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) self.assertFalse((self.root / 'missing').exists()) def test_own_regular_compat_lock_is_held(self): @@ -188,12 +202,12 @@ def test_own_regular_compat_lock_is_held(self): self.assertIn('held 2', r.stdout) self.assertIn('busy', r.stdout) - def test_a_fifo_is_not_a_lock(self): + def test_a_fifo_refuses(self): os.mkfifo(self.compat) r = self.take() - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn('held 1', r.stdout) - + self.assertEqual(r.returncode, 7, r.stdout + r.stderr) + # The /run/lock lock was let go again. + self.assertFalse(held_by_someone(self.boot)) if __name__ == '__main__': unittest.main() From 167c9bd48147c29af699dc8975ef2df3376a9813 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:05:36 +1100 Subject: [PATCH 0471/1514] tools/aurora-sep: aurora-sep-policy-change: check _KERNEL_DEVICE is a string first driver_message() called startswith() on _KERNEL_DEVICE before checking its type. A non-string value in the journal's JSON then raised AttributeError outside the ValueError handler. Check the type first and skip the entry. Signed-off-by: Ryan Murray --- tools/aurora-sep/aurora-sep-policy-change | 7 ++++--- tools/aurora-sep/tests/test_kernel_log_anchor.py | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/aurora-sep/aurora-sep-policy-change b/tools/aurora-sep/aurora-sep-policy-change index 70fd154b7bdb1f..6185c9f9870e6e 100755 --- a/tools/aurora-sep/aurora-sep-policy-change +++ b/tools/aurora-sep/aurora-sep-policy-change @@ -89,9 +89,10 @@ def driver_message(entry): if device is None: prefix = f"{DRIVER}: " else: - name = device[len("+platform:"):] if isinstance(device, str) else "" - if (entry.get("_KERNEL_SUBSYSTEM") != "platform" or not device.startswith("+platform:") - or not name.endswith(".sep")): + if not isinstance(device, str) or not device.startswith("+platform:"): + return None + name = device[len("+platform:"):] + if entry.get("_KERNEL_SUBSYSTEM") != "platform" or not name.endswith(".sep"): return None prefix = f"{DRIVER} {name}: " return msg[len(prefix):] if msg.startswith(prefix) else None diff --git a/tools/aurora-sep/tests/test_kernel_log_anchor.py b/tools/aurora-sep/tests/test_kernel_log_anchor.py index 9c86f8a41fa2e8..645aa108f58a89 100644 --- a/tools/aurora-sep/tests/test_kernel_log_anchor.py +++ b/tools/aurora-sep/tests/test_kernel_log_anchor.py @@ -51,6 +51,11 @@ def kernel(msg, device=None, subsystem='platform', transport='kernel'): # The device prefix on another subsystem's or device's entry. kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x2000);', f'+usb:{DEVICE}', 'usb'), kernel('apple_sep 1-1: xART: APFS-resolved .gl extent (base 0x3000);', '+platform:1-1'), + # A _KERNEL_DEVICE that is not a string. + dict(kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x5000);'), _KERNEL_DEVICE=[1, 2], + _KERNEL_SUBSYSTEM='platform'), + {'MESSAGE': f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x6000);', '_TRANSPORT': 'kernel', + '_KERNEL_DEVICE': 7, '_KERNEL_SUBSYSTEM': 'platform'}, # Not from the kernel. kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', transport='syslog'), ] From 2ab09ee53f9f8bfca497449ee042a0a5d3c8e692 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:20:29 +1100 Subject: [PATCH 0472/1514] tools/aurora-sep: air-gpu-oneshot.sh: keep stderr when opening the /tmp Limine lock open_compat_lock() opened the lock with "exec {fd}/dev/null". A redirection on exec without a command stays in effect, so from then on the script's stderr went to /dev/null: a later refusal, such as a lock held by another tool, exited 1 without printing anything. Put the exec in a brace group so that only its own error is discarded. Create a missing lock with umask 077, the mode the Python tools use. Update the script's sha256 in the installer. Signed-off-by: Ryan Murray --- tools/aurora-sep/air-gpu/air-gpu-oneshot.sh | 5 ++-- tools/aurora-sep/install-aurora-sep.sh | 2 +- tools/aurora-sep/tests/test_boot_locks.py | 33 +++++++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh index 0e997d434268a7..53069ff6a3cf98 100755 --- a/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh +++ b/tools/aurora-sep/air-gpu/air-gpu-oneshot.sh @@ -329,9 +329,10 @@ COMPAT_FD= open_compat_lock() { local l=$1 fd owner inode type COMPAT_FD= - [[ -e $l || -L $l ]] || (set -C; : >"$l") 2>/dev/null || true + [[ -e $l || -L $l ]] || (umask 077; set -C; : >"$l") 2>/dev/null || true [[ -f $l && ! -L $l && -O $l ]] || return 1 - exec {fd}<"$l" 2>/dev/null || return 1 + # In braces: a redirection on exec itself would stay on the script's stderr. + { exec {fd}<"$l"; } 2>/dev/null || return 1 # stat inherits the descriptor: /proc/self/fd/N is the file that was opened. read -r owner inode type < <(stat -L -c '%u %d:%i %F' "/proc/self/fd/$fd" 2>/dev/null) || true if [[ $owner == "$EUID" && $type == regular* && diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index 3eb733bff25f55..acab1be774cd74 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -685,7 +685,7 @@ M3_PERSISTENT_TRANSACTION_ACTIVE=0 M3_PERSISTENT_MAIN_ARMED=0 M3_GPU_BIN=/usr/local/bin M3_GPU_SCRIPTS=( - "air-gpu-oneshot.sh 26b0417faf36ff6f4440ba2aa99aeb9de8272eafe04d45bddc8a50e4a4017158" + "air-gpu-oneshot.sh 30e9d5e96100412d144acb8064ddc63f1000a7a77081ded49072a092b8738b8f" "air-gpu-collect.sh 6a457261dc9773401f2ec7e436839a5f0d3b2bccdd9a90f013f8e72878189879" "air-gpu-job.sh 9a0eb9aab52fd099488054e4ed4846c579b19fc9f78144245242b6975a40da1d" ) diff --git a/tools/aurora-sep/tests/test_boot_locks.py b/tools/aurora-sep/tests/test_boot_locks.py index 07f4df6f10da88..8df961536bf8eb 100644 --- a/tools/aurora-sep/tests/test_boot_locks.py +++ b/tools/aurora-sep/tests/test_boot_locks.py @@ -202,6 +202,39 @@ def test_own_regular_compat_lock_is_held(self): self.assertIn('held 2', r.stdout) self.assertIn('busy', r.stdout) + def test_created_compat_lock_is_private(self): + r = self.take() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertEqual(stat.S_IMODE(self.compat.stat().st_mode) & 0o077, 0) + + def test_stderr_survives_the_compat_lock(self): + # Opening the compatibility lock must leave the script's stderr alone: what it + # prints afterwards (a refusal, say) still has to reach the operator. + self.compat.write_text('') + r = self.take('echo "after the locks" >&2') + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('after the locks', r.stderr) + + def test_held_compat_lock_refusal_is_printed(self): + self.compat.write_text('') + script = f""" +set -euo pipefail +AIR_GPU_SOURCE_ONLY=1 source '{ONESHOT}' +LOCKS='{self.boot}' +COMPAT_LOCKS='{self.compat}' +log() {{ :; }} +flock() {{ if [[ $1 == -w ]]; then command flock -n "${{@:3}}"; else command flock "$@"; fi; }} +take_locks +echo "held ${{#LOCK_FDS[@]}}" +""" + with open(self.compat) as holder: + fcntl.flock(holder, fcntl.LOCK_EX) + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertNotIn('held', r.stdout) + self.assertIn('is held by another tool', r.stderr) + self.assertIn('Nothing was changed.', r.stderr) + def test_a_fifo_refuses(self): os.mkfifo(self.compat) r = self.take() From 4c9bfd3bab6956788e7ed732668ec3e6cdef4575 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:20:41 +1100 Subject: [PATCH 0473/1514] tools/aurora-sep: aurora-sep-policy-change: read only the kernel's own journal entries The journal's kernel transport is everything read from /dev/kmsg, which also carries lines that processes write there. Those have another syslog facility; the kernel's own messages have facility 0. The driver's messages without a device (the xART guard's refusal is one) were told apart only by their prefix. Require SYSLOG_FACILITY=0 for every entry driver_message() accepts, and add entries with another, a missing and a non-string facility to the test. Signed-off-by: Ryan Murray --- tools/aurora-sep/aurora-sep-policy-change | 7 ++++++- tools/aurora-sep/tests/test_kernel_log_anchor.py | 12 ++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/tools/aurora-sep/aurora-sep-policy-change b/tools/aurora-sep/aurora-sep-policy-change index 6185c9f9870e6e..d1948414af3a38 100755 --- a/tools/aurora-sep/aurora-sep-policy-change +++ b/tools/aurora-sep/aurora-sep-policy-change @@ -79,9 +79,14 @@ def driver_message(entry): Its device messages carry the SEP platform device in the journal's kernel fields and start "apple_sep : "; its messages without a - device start "apple_sep: ". The prefix is removed.""" + device start "apple_sep: ". The prefix is removed. + + The journal's kernel transport also carries what processes write to + /dev/kmsg; only the kernel's own messages have facility 0 there.""" if not isinstance(entry, dict) or entry.get("_TRANSPORT") != "kernel": return None + if entry.get("SYSLOG_FACILITY") != "0": + return None msg = entry.get("MESSAGE") if not isinstance(msg, str): return None diff --git a/tools/aurora-sep/tests/test_kernel_log_anchor.py b/tools/aurora-sep/tests/test_kernel_log_anchor.py index 645aa108f58a89..deb1b08fd4d68b 100644 --- a/tools/aurora-sep/tests/test_kernel_log_anchor.py +++ b/tools/aurora-sep/tests/test_kernel_log_anchor.py @@ -29,8 +29,10 @@ def load_policy_change(): M = load_policy_change() -def kernel(msg, device=None, subsystem='platform', transport='kernel'): +def kernel(msg, device=None, subsystem='platform', transport='kernel', facility='0'): e = {'MESSAGE': msg, '_TRANSPORT': transport} + if facility is not None: + e['SYSLOG_FACILITY'] = facility if device is not None: e['_KERNEL_DEVICE'] = device e['_KERNEL_SUBSYSTEM'] = subsystem @@ -55,7 +57,13 @@ def kernel(msg, device=None, subsystem='platform', transport='kernel'): dict(kernel(f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x5000);'), _KERNEL_DEVICE=[1, 2], _KERNEL_SUBSYSTEM='platform'), {'MESSAGE': f'apple_sep {DEVICE}: xART: APFS-resolved .gl extent (base 0x6000);', '_TRANSPORT': 'kernel', - '_KERNEL_DEVICE': 7, '_KERNEL_SUBSYSTEM': 'platform'}, + 'SYSLOG_FACILITY': '0', '_KERNEL_DEVICE': 7, '_KERNEL_SUBSYSTEM': 'platform'}, + # The kernel transport, but not the kernel's own facility (or none, or not a string). + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility='1'), + kernel(f'apple_sep: xART guard: refused to rewrite kind-3 record {OTHER},', facility='3'), + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility=None), + kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', facility=0), + kernel('apple_sep: xART: APFS-resolved .gl extent (base 0x7000);', facility='1'), # Not from the kernel. kernel(f'apple_sep: xART guard: refused to rewrite kind-4 record {OTHER},', transport='syslog'), ] From bc2883e58173c884d04b62ba5d768947f1ff3cf1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:16:15 +1100 Subject: [PATCH 0474/1514] media: apple: ave: do not round huge shared-memory requests to zero ave_smalloc_get() rounds the size the firmware asks for on the SHAREDMALLOC ring up to whole granules with DIV_ROUND_UP() in 32 bits. A request of 0xfffff001..0xffffffff bytes wraps to 0 units, passes the "units > total" check and is answered with the first free block and a length of about 4 GiB, while nothing is reserved: the bound on the pool is defeated and the same block is lent again to the next request. Round in 64 bits so such a request needs more units than the pool has and is refused. Fixes: 01d0284e3837 ("media: apple: ave: serve the 6070 firmware channels") Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-ipc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 518604147cc17d..60a5b006a7875e 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -389,7 +389,8 @@ static int ave_smalloc_get(struct ave_dev *ave, u32 bytes, u64 *addr) const struct ave_fw_transport *t = ave->layout->abi->transport; u32 total = min_t(u32, t->smalloc_bytes / AVE_SMALLOC_GRANULE, AVE_SMALLOC_UNITS); - u32 units = DIV_ROUND_UP(bytes, AVE_SMALLOC_GRANULE); + /* In 64 bits: a request near 4 GiB must not round up to 0 units */ + u32 units = DIV_ROUND_UP_ULL(bytes, AVE_SMALLOC_GRANULE); unsigned long first; unsigned int i; From 7a7a7d408b51970bfb0a42389e8450945c4ed0ce Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:16:15 +1100 Subject: [PATCH 0475/1514] drm: apple: parser: ignore channel counts the layout mask cannot hold parse_nchans_mask() sets "1 << nchans" for every channel count in an AudioChannelLayoutElements array. The count comes from the firmware's dictionary as a 64-bit integer and is truncated to int on the way, so a count of 32 or more, or a negative one, is an undefined shift, and a count above U32_MAX aliases a small one (2^32 + 2 becomes 2). Pass counts outside the u32 range on as U32_MAX, which matches no channel sieve, and only set a mask bit for a count the mask has a bit for. Every count from 0 to 31 is handled as before. Fixes: 2c7e3cad911d ("drm: apple: Add sound mode parsing") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/parser.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 28c429e48ecc75..0acc268c6813eb 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -2189,8 +2189,9 @@ static int parse_chan_layout_element(struct dcp_parse_ctx *handle, return ret; } + /* A count no u32 holds is no channel count: U32_MAX matches nothing */ if (nchans_out) - *nchans_out = nchans; + *nchans_out = nchans >= 0 && nchans <= U32_MAX ? nchans : U32_MAX; return 0; } @@ -2207,12 +2208,14 @@ static int parse_nchans_mask(struct dcp_parse_ctx *handle, unsigned int *mask) return ret; for (; it.idx < it.len; ++it.idx) { - int nchans; + unsigned int nchans; ret = parse_chan_layout_element(it.handle, &nchans, NULL); if (ret) return ret; - *mask |= 1 << nchans; + /* The firmware's count: one the mask has no bit for matches no sieve */ + if (nchans < BITS_PER_TYPE(*mask)) + *mask |= BIT(nchans); } return 0; @@ -2275,7 +2278,7 @@ static int parse_mode_in_avep_element(struct dcp_parse_ctx *handle, for (; it.idx < it.len; ++it.idx) { if (consume_string(it.handle, "AudioChannelLayoutElements")) { struct iterator inner_it; - int nchans; + unsigned int nchans; ret = iterator_begin(it.handle, &inner_it, false); if (ret) From 58f9020260fb62b4917c6c543337c383287418df Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:14:41 +1100 Subject: [PATCH 0476/1514] accel/ane: zero the page that a DART fault drain maps When a job faults on an unmapped address, ane_dart_drain_fault() maps a fresh page there, read-write, so the retried transaction can complete. The page came from alloc_page(GFP_KERNEL) and was not cleared, so the job could read stale kernel memory. Allocate the page with __GFP_ZERO. KUnit: ane-bo dirties and frees a set of pages, then checks that the scratch pages allocated next are zero (skipped when init_on_alloc zeroes every page anyway). Signed-off-by: Ryan Murray --- drivers/accel/ane/ane.h | 1 + drivers/accel/ane/ane_dart.c | 14 +++++++++- drivers/accel/ane/ane_drv_test.c | 44 +++++++++++++++++++++++++++++++- 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 119f73dfedf072..17976b2364f297 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -227,6 +227,7 @@ static inline bool ane_tm_failure_recoverable(bool tm_retention, #if IS_ENABLED(CONFIG_KUNIT) u64 ane_bo_iova_size(u32 npages, unsigned int shift); int ane_bo_check_size(u64 size, u64 iova_span); +struct page *ane_dart_alloc_scratch_page(void); int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, size_t btsp_size); #endif diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index f99d5c5b5c0c1b..77b8817fbbbd7b 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Copyright 2026 Joshua Warren */ +#include #include #include #include @@ -170,6 +171,17 @@ bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status) return false; } +/* + * The scratch page is mapped read-write for the job that faulted, and + * the job's output can carry what it reads from there: hand it out + * zeroed. + */ +VISIBLE_IF_KUNIT struct page *ane_dart_alloc_scratch_page(void) +{ + return alloc_page(GFP_KERNEL | __GFP_ZERO); +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); + /* * A fault is a missing PTE, nothing more: the page tables are provider * owned and unchanged, so the stream-restore apple-dart uses at reset @@ -201,7 +213,7 @@ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, u64 iova; int ret, i; - page = alloc_page(GFP_KERNEL); + page = ane_dart_alloc_scratch_page(); if (!page) return -ENOMEM; iova = fault_iova & ~((1ULL << ane->shift) - 1); diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index f0cb7cc3fad9eb..ae8f151c4dea77 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -1,10 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* * KUnit tests for the buffer size checks of DRM_IOCTL_ANE_SUBMIT and - * DRM_IOCTL_ANE_BO_INIT. + * DRM_IOCTL_ANE_BO_INIT, and the fault-drain scratch page. */ #include +#include +#include +#include #include #include "ane.h" @@ -190,9 +193,48 @@ static void ane_bo_check_size_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_bo_check_size(c->size, c->span), c->ret); } +/* + * The fault-drain scratch page is readable by the job that faulted. + * Dirty some pages and give them back to the allocator first, so an + * unzeroed allocation would very likely hand one of them out again + * (likely, not certain: the allocator may pick other pages). + */ +#define ANE_TEST_SCRATCH_PAGES 16 + +static void ane_dart_scratch_page_zeroed_test(struct kunit *test) +{ + struct page *pages[ANE_TEST_SCRATCH_PAGES]; + int i; + + /* The allocator zeroes every page itself: nothing to tell apart. */ + if (want_init_on_alloc(GFP_KERNEL)) + kunit_skip(test, "init_on_alloc zeroes every page"); + + for (i = 0; i < ARRAY_SIZE(pages); i++) { + pages[i] = alloc_page(GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + memset(page_address(pages[i]), 0xa5, PAGE_SIZE); + } + for (i = 0; i < ARRAY_SIZE(pages); i++) + __free_page(pages[i]); + + for (i = 0; i < ARRAY_SIZE(pages); i++) { + pages[i] = ane_dart_alloc_scratch_page(); + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + } + for (i = 0; i < ARRAY_SIZE(pages); i++) { + KUNIT_EXPECT_TRUE_MSG(test, + !memchr_inv(page_address(pages[i]), 0, + PAGE_SIZE), + "scratch page %d is not zeroed", i); + __free_page(pages[i]); + } +} + static struct kunit_case ane_bo_test_cases[] = { KUNIT_CASE(ane_bo_iova_size_test), KUNIT_CASE_PARAM(ane_bo_check_size_test, ane_bo_size_gen_params), + KUNIT_CASE(ane_dart_scratch_page_zeroed_test), {} }; From 1f01ea9fbd26f18bf0a81e5e368f51f058f413bb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:17:19 +1100 Subject: [PATCH 0477/1514] accel/ane: map only the running job's buffers in the DART Every file's buffer objects share the one DART domain of the H13 engine, and every BO was mapped from BO_INIT until it was freed. The task descriptors of a SUBMIT address memory as a tile base, which the kernel programs from the job's handles, plus offsets that the driver does not parse. So the DART mappings were the only bound on a job's memory accesses, and they held the buffers of all files. Jobs already run one at a time under engine_lock, synchronously, and hold a reference on each of their BOs until completion. Use that to make the DART the bound. BO_INIT now only reserves the BO's IOVA range and records its protection. Before the engine starts, SUBMIT takes every BO that the job does not name out of the DART and maps the job's handles and its bootstrap buffer. An access outside them then lands in an unmapped range and takes the existing fault path; one inside the reserved range of another BO cannot be drained with a scratch page, so that job fails and the engine recovers, as for any other access the drain refuses. A BO stays mapped after its job until a SUBMIT that does not name it, so repeated jobs on the same buffers do no DART work. Switching between jobs with different buffers costs one range unmap per BO leaving the DART and one map per BO entering it, each with one TLB invalidation per DART. Unmapping a whole BO in one call also replaces the per-page unmap loop, which invalidated the TLBs once per page. A BO freed while the engine is wedged keeps its mapping only if it is in the DART, that is, part of the job that wedged; any other BO cannot be reached by the engine and is freed at once. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane.h | 9 ++ drivers/accel/ane/ane_dart.c | 5 +- drivers/accel/ane/ane_drv.c | 167 ++++++++++++++++++++++++++++------- include/uapi/drm/ane_accel.h | 4 +- 4 files changed, 149 insertions(+), 36 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 17976b2364f297..8bf18a4f9ffb54 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -70,6 +70,15 @@ struct ane_device { struct mutex pm_lock; struct list_head bo_list; + /* + * BOs whose pages are in the DART now. Between jobs this is the last + * job's set; ane_submit() unmaps every other BO before the engine + * starts, so a job reaches only the buffers it names. job_seq tags + * the BOs of the job being set up. Both under engine_lock. + */ + struct list_head mapped_list; + u64 job_seq; + /* * Wedge-preserved BO ranges, tied to their still-inserted drm_mm * nodes (see ane_reclaim_preserved). Registered under engine_lock. diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index 77b8817fbbbd7b..9b141774b463c4 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -202,8 +202,9 @@ EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); * later BO_INIT, and a scratch whose release is skipped degrades into * a bounded, benign leak instead of a poisoned address space. Reserve * failure means a live BO node already owns the faulting page (a wild - * descriptor, not a hole): refuse and let the caller wedge, fail - * closed. + * descriptor, not a hole): a BO of another job, which ane_submit() took + * out of the DART for this one. Refuse and let the caller wedge and + * recover, fail closed. */ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, struct ane_dart_scratch *scratch, int *pages) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index c722af5c6170b3..489bc6e3b0f14c 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -81,27 +81,37 @@ MODULE_PARM_DESC(autosuspend_ms, "Power the ANE off this many ms after its last use (default 1500; 0 = keep it powered while the driver is bound)"); /* - * 1 (default): BO_INIT maps a buffer object with one iommu_map_sg(), so + * 1 (default): a buffer object goes into the DART (at the first SUBMIT + * that names it, see ane_dart_confine()) with one iommu_map_sg(), so * apple-dart invalidates the TLB of each DART once for each BO. 0: one * iommu_map() and one TLB invalidate on each DART for each page (a * 458 MB buffer: 27,955 pages x 3 DARTs = 83,865 invalidates). Read - * once for each BO_INIT; BOs mapped either way unmap the same way. + * at each map; BOs mapped either way unmap the same way. */ static bool map_batch = true; module_param(map_batch, bool, 0644); MODULE_PARM_DESC(map_batch, - "BO_INIT DART mapping: 1 = one TLB sync for each buffer object (default); 0 = one TLB sync for each page"); + "Buffer object DART mapping: 1 = one TLB sync for each buffer object (default); 0 = one TLB sync for each page"); #define CMD_BUF_BDX 0 #define KRN_BUF_BDX 1 +/* + * A BO owns its IOVA range (mm, iova) from BO_INIT to its free, but its + * pages are in the DART only while @mapped: from the first SUBMIT that + * names it until a SUBMIT that does not (see ane_dart_confine()). + */ struct ane_bo { struct drm_gem_object base; struct list_head node; + struct list_head mapped_node; struct drm_mm_node *mm; u32 npages; struct page **pages; dma_addr_t iova; + u64 job_seq; + int prot; + bool mapped; }; #define to_bo(gem) (container_of(gem, struct ane_bo, base)) @@ -266,54 +276,97 @@ static int ane_iommu_map_batch(struct ane_device *ane, struct ane_bo *bo, * setup, invalidation and fault IRQs are all provider-owned); * iommu_unmap() flushes through the provider before returning, so pages * may be reclaimed once it succeeds. + * + * BO_INIT only reserves the BO's IOVA range. The pages go into the DART + * when a SUBMIT names the BO (ane_dart_confine()), so the range stays the + * BO's for its whole life while its PTEs come and go. */ -static int ane_iommu_map_pages(struct ane_device *ane, struct ane_bo *bo) +static int ane_iommu_reserve(struct ane_device *ane, struct ane_bo *bo) { - int prot = IOMMU_READ | IOMMU_WRITE; int err; lockdep_assert_held(&ane->engine_lock); if (bo->mm) return -EBUSY; + bo->prot = IOMMU_READ | IOMMU_WRITE; if (map_mode & 1) - prot |= IOMMU_CACHE; + bo->prot |= IOMMU_CACHE; bo->mm = kzalloc_obj(*bo->mm); if (!bo->mm) return -ENOMEM; mutex_lock(&ane->iommu_lock); - /* reserve area from ANE address space */ err = drm_mm_insert_node_generic(&ane->mm, bo->mm, ane_bo_iova_size(bo->npages, ane->shift), 1UL << ane->shift, 0, 0); + mutex_unlock(&ane->iommu_lock); if (err < 0) { dev_err(ane->dev, "out of ANE space: %d\n", err); - goto unlock; + kfree(bo->mm); + bo->mm = NULL; + return err; } bo->iova = bo->mm->start; + return 0; +} + +/* Put the pages of a BO with a reserved range into the DART. */ +static int ane_bo_dart_map(struct ane_device *ane, struct ane_bo *bo) +{ + int err; + + lockdep_assert_held(&ane->engine_lock); + if (bo->mapped) + return 0; + if (!bo->mm) + return -EINVAL; + mutex_lock(&ane->iommu_lock); if (READ_ONCE(map_batch)) - err = ane_iommu_map_batch(ane, bo, prot); + err = ane_iommu_map_batch(ane, bo, bo->prot); else - err = ane_iommu_map_each(ane, bo, prot); - if (err < 0) { - drm_mm_remove_node(bo->mm); - bo->iova = 0; - } - -unlock: + err = ane_iommu_map_each(ane, bo, bo->prot); mutex_unlock(&ane->iommu_lock); - if (err < 0) { - kfree(bo->mm); - bo->mm = NULL; + if (err < 0) + return err; + + bo->mapped = true; + list_add_tail(&bo->mapped_node, &ane->mapped_list); + return 0; +} + +/* + * Take the pages of a BO out of the DART and keep its range. A mapped BO + * has a PTE on every page, so one range unmap (one TLB flush per DART) + * takes them all; a short unmap is cleared page by page. + */ +static void ane_bo_dart_unmap(struct ane_device *ane, struct ane_bo *bo) +{ + size_t size = ane_bo_iova_size(bo->npages, ane->shift); + size_t unmapped; + + lockdep_assert_held(&ane->engine_lock); + if (!bo->mapped) + return; + + mutex_lock(&ane->iommu_lock); + unmapped = iommu_unmap(ane->domain, bo->iova, size); + if (unmapped != size) { + dev_err(ane->dev, "unmap short at %#llx+%#zx: %zu\n", + bo->iova, size, unmapped); + ane_iommu_clear_range(ane, bo->iova, bo->iova + size); } - return err; + mutex_unlock(&ane->iommu_lock); + + list_del_init(&bo->mapped_node); + bo->mapped = false; } +/* Unmap a BO and give its range back to the allocator. */ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) { struct drm_mm_node *mm = bo->mm; @@ -324,16 +377,8 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) return; list_del_init(&bo->node); + ane_bo_dart_unmap(ane, bo); mutex_lock(&ane->iommu_lock); - for (u32 i = 0; i < bo->npages; i++) { - dma_addr_t iova = bo->iova + ((u64)i << ane->shift); - size_t unmapped = iommu_unmap(ane->domain, iova, - 1UL << ane->shift); - - if (unmapped != 1UL << ane->shift) - dev_err(ane->dev, "unmap short at %#llx: %zu\n", - iova, unmapped); - } drm_mm_remove_node(mm); bo->mm = NULL; bo->iova = 0; @@ -342,6 +387,42 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) kfree(mm); } +/* + * All files share one DART domain, and the task descriptors of a job + * address memory as a tile base plus an offset the kernel cannot check. + * So the DART is the bound: before the engine starts, every BO that is + * not part of this job leaves the DART and every BO of the job is put + * in. A descriptor that leaves the job's buffers then lands in a hole + * and faults (see ane_dart_drain_fault()) instead of reaching another + * file's buffer. Jobs run one at a time under engine_lock, and a job's + * lookup references keep its BOs alive until it completed, so the set + * cannot change under a running job. A BO that the next job names again + * stays mapped, so repeated jobs on the same buffers cost no remapping. + */ +static int ane_dart_confine(struct ane_device *ane, struct ane_bo **job, + int count) +{ + struct ane_bo *bo, *tmp; + u64 seq; + int err; + + lockdep_assert_held(&ane->engine_lock); + seq = ++ane->job_seq; + for (int i = 0; i < count; i++) + job[i]->job_seq = seq; + + list_for_each_entry_safe(bo, tmp, &ane->mapped_list, mapped_node) + if (bo->job_seq != seq) + ane_bo_dart_unmap(ane, bo); + + for (int i = 0; i < count; i++) { + err = ane_bo_dart_map(ane, job[i]); + if (err) + return err; + } + return 0; +} + /* * A BO freed while the engine is wedged keeps its mapping and its pages * (DMA may still be reading the IOVA), but the GEM object is gone. The @@ -458,17 +539,21 @@ static void ane_gem_free_object(struct drm_gem_object *gem) mutex_lock(&ane->engine_lock); if (bo->mm) { - if (atomic_read(&ane->wedged)) { + if (atomic_read(&ane->wedged) && bo->mapped) { /* Fail closed: keep the mapping and the pages so no * IOVA is torn down or page reused underneath active * DMA. The range's node stays reserved and tracked * until recovery quiesces the engine and reclaims * it, so no later BO_INIT can map over these PTEs * (a leaked-but-forgotten mapping turns into - * dart_init_pte -EEXIST WARNs). + * dart_init_pte -EEXIST WARNs). A BO that is not in + * the DART was not part of the job that wedged and + * the engine cannot reach it, so it is freed below. */ dev_err(ane->dev, "wedged: preserving bo mapping\n"); list_del_init(&bo->node); + list_del_init(&bo->mapped_node); + bo->mapped = false; ane_preserve_bo(ane, bo); } else { ane_iommu_unmap_pages(ane, bo); @@ -524,6 +609,7 @@ static int ane_bo_init(struct drm_device *drm, void *data, if (!bo) return -ENOMEM; INIT_LIST_HEAD(&bo->node); + INIT_LIST_HEAD(&bo->mapped_node); gem = &bo->base; gem->funcs = &ane_gem_object_funcs; @@ -558,7 +644,7 @@ static int ane_bo_init(struct drm_device *drm, void *data, goto unlock_put; } - err = ane_iommu_map_pages(ane, bo); + err = ane_iommu_reserve(ane, bo); if (err < 0) goto unlock_put; list_add_tail(&bo->node, &ane->bo_list); @@ -638,9 +724,11 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) struct drm_ane_submit *args = data; struct drm_gem_object *gem[DRM_ANE_TILE_COUNT] = { 0 }; struct drm_gem_object *btsp = NULL; + struct ane_bo *job[DRM_ANE_TILE_COUNT + 1]; struct ane_bo *bo; struct ane_request req; u64 stats_idx = 0; + int njob = 0; int err; memset(&req, 0, sizeof(req)); @@ -706,8 +794,14 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) /* * Lookup references are held across the synchronous execute and * dropped only after ane_tm_execute() confirmed completion, so a - * concurrent BO_FREE cannot unmap a buffer the engine reads. + * concurrent BO_FREE cannot unmap a buffer the engine reads. The + * same references are the job's DART set (ane_dart_confine()). */ + for (int bdx = 0; bdx < DRM_ANE_TILE_COUNT; bdx++) + if (gem[bdx]) + job[njob++] = to_bo(gem[bdx]); + job[njob++] = to_bo(btsp); + mutex_lock(&ane->engine_lock); if (ane->removed) { err = -ENODEV; @@ -719,6 +813,12 @@ static int ane_submit(struct drm_device *drm, void *data, struct drm_file *file) goto unlock; } + err = ane_dart_confine(ane, job, njob); + if (err) { + dev_err_ratelimited(ane->dev, "job buffers not mapped: %d\n", err); + goto unlock; + } + err = ane_perf_begin(ane); if (err) { dev_err_ratelimited(ane->dev, "performance request failed: %d\n", err); @@ -1286,6 +1386,7 @@ static int ane_platform_probe(struct platform_device *pdev) mutex_init(&ane->engine_lock); mutex_init(&ane->pm_lock); INIT_LIST_HEAD(&ane->bo_list); + INIT_LIST_HEAD(&ane->mapped_list); INIT_LIST_HEAD(&ane->preserved_list); err = ane_perf_init(ane, soc->high_level); if (err < 0) diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h index d0c226d131290c..584d138436a7bb 100644 --- a/include/uapi/drm/ane_accel.h +++ b/include/uapi/drm/ane_accel.h @@ -157,7 +157,9 @@ struct drm_ane_bo_free { * @pad: Must be zero. * * A successful SUBMIT returns after the engine completed the work, with the - * output buffers visible to the CPU. + * output buffers visible to the CPU. While it runs, the engine reaches only + * the buffers in @handles and @btsp_handle: an access outside them faults + * and fails the SUBMIT. */ struct drm_ane_submit { __u64 tsk_size; From d13aad47dbb522d55002c36ab19218a290fa9578 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:24:23 +1100 Subject: [PATCH 0478/1514] media: apple: ave: keep in-place repacked input 64-byte aligned The encoder takes its OUTPUT picture at a 64-byte aligned address, and the direct path refuses any other address. The path that spreads packed lines out to the encoder's stride inside a driver-allocated buffer did not check this, so a data_offset that is not a multiple of 64 handed the encoder the unaligned start of the picture. Repack in place only when the picture starts on the encoder's alignment; otherwise copy it to the slot's own buffer, as for imported buffers. The input host test now checks that every accepted address is aligned and repacks packed payloads at every byte offset of a buffer with room to spare (MMAP and DMABUF). Fixes: 6a99b550f905 ("media: apple: ave: fit the native panel size in the DMA window") Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-sess.c | 5 ++- .../platform/apple/ave/tests/input-test.c | 39 ++++++++++++++++++- drivers/media/platform/apple/ave/tests/shim.h | 1 + 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index 901fc784581b77..8da75fa5c4ac3e 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -812,9 +812,10 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe * Buffers the driver allocated (MMAP) are large enough for the * encoder's layout: spread the lines out in place, last line first, * so no extra DMA space is needed. Imported buffers may be shared - * with other users and get a copy instead. + * with other users and get a copy instead, and so does a buffer whose + * data_offset leaves the picture off the encoder's 64-byte alignment. */ - if (vb->memory == VB2_MEMORY_MMAP && + if (vb->memory == VB2_MEMORY_MMAP && IS_ALIGNED(*input, 64) && vb2_plane_size(vb, 0) >= (size_t)off + frame) { to = (u8 *)from; for (u32 y = rows; y-- > 0;) diff --git a/drivers/media/platform/apple/ave/tests/input-test.c b/drivers/media/platform/apple/ave/tests/input-test.c index 23f50758b9a1bd..43aca7c1428e51 100644 --- a/drivers/media/platform/apple/ave/tests/input-test.c +++ b/drivers/media/platform/apple/ave/tests/input-test.c @@ -109,6 +109,13 @@ static int submit(struct vb2_v4l2_buffer *b, unsigned int off, unsigned int used pl->length, (unsigned long long)input, encoder_extent()); exit(1); } + if (!IS_ALIGNED(input, 64)) { + fprintf(stderr, + "FAIL: data_offset %u payload %u (%s, %u byte buffer): encoder input %#llx is not 64-byte aligned\n", + off, used, b->vb2_buf.memory == VB2_MEMORY_MMAP ? "MMAP" : "DMABUF", + pl->length, (unsigned long long)input); + exit(1); + } encoder_read(input); return 0; } @@ -173,6 +180,34 @@ static void packed(enum vb2_memory memory, unsigned int off, bool in_place) put(b); } +/* + * Packed lines at every byte data_offset of a buffer with room to spare: + * each picture is accepted at an aligned address (submit() checks) and + * its lines arrive there unchanged, in place or in the copy. + */ +static void packed_any_offset(enum vb2_memory memory) +{ + const struct ave_params *p = &sess.p; + u32 rows = p->height + DIV_ROUND_UP(p->height, 2), line = p->width; + struct vb2_v4l2_buffer *b = buffer(memory, sizeimage() + 2 * 64); + + for (unsigned int off = 0; off < 2 * 64; off++) { + u8 *from = (u8 *)b->vb2_buf.planes[0].mem + off; + const u8 *to; + + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + from[y * line + x] = (u8)(y * 7 + x + off); + assert(!submit(b, off, off + rows * line)); + to = sess.slot[0].bounce.cpu ? sess.slot[0].bounce.cpu : from; + for (u32 y = 0; y < rows; y++) + for (u32 x = 0; x < line; x++) + assert(to[(size_t)y * p->stride + x] == (u8)(y * 7 + x + off)); + release_bounce(); + } + put(b); +} + int main(void) { static const u32 sizes[][2] = { { 128, 64 }, { 100, 60 }, { 320, 180 } }; @@ -190,7 +225,9 @@ int main(void) packed(VB2_MEMORY_MMAP, 64, false); packed(VB2_MEMORY_DMABUF, 0, false); packed(VB2_MEMORY_DMABUF, 128, false); + packed_any_offset(VB2_MEMORY_MMAP); + packed_any_offset(VB2_MEMORY_DMABUF); assert(!dma_allocs && jiffies); - puts("ok: OUTPUT data_offset sweep (MMAP, DMABUF), offset with room, packed-stride repack"); + puts("ok: OUTPUT data_offset sweep (MMAP, DMABUF), offset with room, packed repack at any offset"); return 0; } diff --git a/drivers/media/platform/apple/ave/tests/shim.h b/drivers/media/platform/apple/ave/tests/shim.h index f0a723c4894135..389ca5a4305087 100644 --- a/drivers/media/platform/apple/ave/tests/shim.h +++ b/drivers/media/platform/apple/ave/tests/shim.h @@ -74,6 +74,7 @@ static inline void sort(void *p, size_t n, size_t size, } #define dev_err(...) test_log(__VA_ARGS__) +#define dev_err_ratelimited(...) test_log(__VA_ARGS__) #define dev_info(...) test_log(__VA_ARGS__) #define dev_dbg(...) test_log(__VA_ARGS__) #define dev_warn(...) test_log(__VA_ARGS__) From d6132fa01bec14e35f4cdab72225414f914b94e0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:23:57 +1100 Subject: [PATCH 0479/1514] media: apple: ave: ratelimit the short OUTPUT plane error A client can queue a buffer that is too short for the picture after its data_offset on every frame; report it with dev_err_ratelimited() so the log is not flooded. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-sess.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index 8da75fa5c4ac3e..595284b0e6c471 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -788,9 +788,9 @@ int ave_sess_input(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buffe *input = vb2_dma_contig_plane_dma_addr(vb, 0) + off; if (!used || used >= p->stride * rows || used % rows || used / rows < width) { if ((size_t)off + frame > vb2_plane_size(vb, 0)) { - dev_err(ctx->ave->dev, - "OUTPUT plane has no %zu byte frame after offset %u\n", - frame, off); + dev_err_ratelimited(ctx->ave->dev, + "OUTPUT plane has no %zu byte frame after offset %u\n", + frame, off); return -EINVAL; } if (IS_ALIGNED(*input, 64)) From dda7b3de5407260325bcab049c96391ec7028725 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:20:42 +1100 Subject: [PATCH 0480/1514] tools/aurora-sep: install-aurora-sep.sh: finish the root-owned work directory Follow-ups to the root-owned copy of the checked downloads: - Under sudo, the M3 Max kit checked the identity of the downloaded script in the invoking user's directory, by path, after its sha256 was taken, so the bytes root copied were not necessarily the ones that check had read. Repeat the identity check on root's copy, after its sha256 check and before it is run. The check sources the script, so it runs with the invoking user's ids (runuser) and reads the copy from a descriptor root opened. Set the copy's mode explicitly. - sudo keeps the invoking user's umask. With umask 077, the files root wrote into its work directory with tee were 0600, and the user-side steps that read them back failed, after the packages were already installed. Write them through work_write(), which sets umask 022 in root's shell as work_to_root() does. - work_to_root() left the user's download directory behind when a copy or a checksum failed. The EXIT trap now removes it as well. - Run every root Python of the installer isolated (python3 -I), including the pacman hook's Exec line, so that the current directory and the user's environment are not on its module path. test_m3_pro_mesa's comparison with the 12.2 installer maps the new command lines to the old ones, and test_m3_flow's planner stub accepts the -I. Signed-off-by: Ryan Murray --- tools/aurora-sep/install-aurora-sep.sh | 73 ++++++++---- tools/aurora-sep/tests/test_m3_flow.py | 3 +- tools/aurora-sep/tests/test_m3_pro_mesa.py | 8 ++ tools/aurora-sep/tests/test_root_staging.py | 120 +++++++++++++++++++- 4 files changed, 177 insertions(+), 27 deletions(-) diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index acab1be774cd74..970e420a2e3675 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -759,7 +759,7 @@ m3_pro_perf_activate() { $(cat /opt/mesa-m3/pro-vulkan/share/mesa-m3/profile) == t6030-pro-vulkan-legacy-hal ]] || die "paired Pro Mesa installation is incomplete" user=$(m3_pro_mesa_user) if [[ $user != root ]]; then - printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d | $sudo tee "$work/migrate-pro-session.py" >/dev/null + printf '%s' "$M3_PRO_PERF_MIGRATOR" | base64 -d | work_write "$work/migrate-pro-session.py" $sudo runuser -u "$user" -- python3 - "$user" < "$work/migrate-pro-session.py" || die "could not update the managed native Pro session" fi $sudo systemctl enable mesa-m3-pro-performance.service @@ -3875,7 +3875,7 @@ frozen_dependency_prepare() { for archive in "$@"; do args+=(--candidate "$archive"); done args+=(--allow-remove linux-asahi --allow-remove linux-asahi-headers --allow-remove m1n1 --allow-remove mesa-m3-g15g) - $sudo tee "$work/frozen-dependencies.py" >/dev/null <<'FROZEN_DEPENDENCIES_PY' + work_write "$work/frozen-dependencies.py" <<'FROZEN_DEPENDENCIES_PY' #!/usr/bin/env python3 """Admit missing repository dependencies without changing installed packages.""" import argparse @@ -4209,7 +4209,7 @@ def main(): (work / "dependency-plan.json").write_text(json.dumps(receipt, indent=2) + "\n") hook.write_text("[Trigger]\nOperation = Install\nOperation = Upgrade\nOperation = Remove\n" "Type = Package\nTarget = *\n[Action]\nWhen = PreTransaction\n" - "Exec = /usr/bin/python3 " + str(helper) + " --verify-plan " + str(receipt_path) + + "Exec = /usr/bin/python3 -I " + str(helper) + " --verify-plan " + str(receipt_path) + " --plan-sha256 " + sha(receipt_path) + "\nAbortOnFail\n") print(json.dumps(receipt)) @@ -4222,7 +4222,7 @@ if __name__ == "__main__": sys.exit(1) FROZEN_DEPENDENCIES_PY say "Resolving only missing dependencies while preserving this image's package holds" - $sudo python3 "$work/frozen-dependencies.py" "${args[@]}" | $sudo tee "$work/dependency-result.json" >/dev/null || + $sudo python3 -I "$work/frozen-dependencies.py" "${args[@]}" | work_write "$work/dependency-result.json" || die "could not admit a missing-only dependency transaction. Nothing was installed. The package holds were preserved." FROZEN_TRANSACTION_CONFIG=$(python3 - "$work/dependency-result.json" <<'FROZEN_CONFIG_PY' import json, sys @@ -4230,7 +4230,7 @@ print(json.load(open(sys.argv[1]))['transaction_config']) FROZEN_CONFIG_PY ) $sudo test -f "$FROZEN_TRANSACTION_CONFIG" || die "missing admitted package transaction configuration" - python3 - "$work/dependency-result.json" <<'FROZEN_FILES_PY' | $sudo tee "$work/dependency-files" >/dev/null + python3 - "$work/dependency-result.json" <<'FROZEN_FILES_PY' | work_write "$work/dependency-files" import json, sys plan = json.load(open(sys.argv[1])) for filename in list(plan['candidate_sha256']) + [p['file'] for p in plan['dependencies']]: @@ -4277,11 +4277,21 @@ package_database_check() { # sha256 again as root there, and use only that copy from then on: $work names it, and # candidate_archives is rewritten to it. The directory is 0700 while files arrive and 0755 after # (the user may read the packages, not change them). +# Until it is done, WORK_DOWNLOADS names the user's directory, so that the EXIT trap removes +# both directories when a copy or a check fails. WORK_ROOT_OWNED=0 +WORK_DOWNLOADS="" INSTALL_ARCHIVES=() +# Write stdin to FILE in $work. Under sudo that directory is root's, and the invoking user's +# side still reads these files: sudo keeps the user's umask, so set the mode here (0644), as +# work_to_root does. +work_write() { # FILE + $sudo sh -c 'umask 022 && cat >"$1"' _ "$1" +} work_to_root() { local old=$work new file sha [[ -n $sudo ]] || return 0 + WORK_DOWNLOADS=$old new=$($sudo mktemp -d) || die "could not make a work directory for root. Nothing was installed." work=$new WORK_ROOT_OWNED=1 @@ -4297,6 +4307,7 @@ work_to_root() { $sudo chmod 0755 "$new" candidate_archives=("${candidate_archives[@]/#"$old/"/"$new/"}") rm -rf -- "$old" + WORK_DOWNLOADS="" } install_all() { @@ -5237,11 +5248,11 @@ m3_report_adt() { # DIR for ((i = 0; i < 10; i++)); do [[ -e $dev ]] && break; sleep 0.5; done if [[ ! -e $dev ]]; then why="no read-only device node $dev, so the ADT was not read" - elif ! $sudo python3 "$reader" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then + elif ! $sudo python3 -I "$reader" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then why="the ADT reader's check refused $dev, so the ADT was not read: $(tail -1 "$M3_WORK/adt.err" 2>/dev/null | cut -c1-200 || true)" else echo "read: $dev with ${reader##*/}" >>"$log" - $sudo python3 "$reader" "$dev" >"$out" 2>"$M3_WORK/adt.err" & + $sudo python3 -I "$reader" "$dev" >"$out" 2>"$M3_WORK/adt.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -5302,7 +5313,7 @@ m3_report_stage2_log() { # DIR READER LOG return 1 fi echo "log: $dev with ${reader##*/} --stage2-log" >>"$log" - $sudo python3 "$reader" --stage2-log "$dev" >"$out" 2>"$M3_WORK/log.err" & + $sudo python3 -I "$reader" --stage2-log "$dev" >"$out" 2>"$M3_WORK/log.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -5315,7 +5326,7 @@ m3_report_stage2_log() { # DIR READER LOG # And all 16 KiB of it, byte for byte but the same lines overwritten (a reader without --raw # leaves this file out). rc=0 - $sudo python3 "$reader" --stage2-log --raw "$dev" >"$1/m1n1-stage2-log.raw" 2>>"$M3_WORK/log.err" & + $sudo python3 -I "$reader" --stage2-log --raw "$dev" >"$1/m1n1-stage2-log.raw" 2>>"$M3_WORK/log.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -7347,7 +7358,7 @@ esp_history_run() { [[ $(boot_chain) == limine ]] || die "EFI history archiving is available only with Limine" target=$(esp_bootbin) || die "could not find the mounted FAT boot partition" code=$(esp_history_builtin) - $sudo python3 -c "$code" "$1" --esp "${target%/m1n1/boot.bin}" --state "$STATE" \ + $sudo python3 -I -c "$code" "$1" --esp "${target%/m1n1/boot.bin}" --state "$STATE" \ --archive "$STATE/esp-history" || die "EFI history was retained where archive checks failed; retry after checking the error" } @@ -7387,6 +7398,7 @@ m3_install_cleanup() { fi if ((FROZEN_PACKAGES || WORK_ROOT_OWNED)); then $sudo rm -rf "${work:-}" else rm -rf "${work:-}"; fi + [[ -z $WORK_DOWNLOADS ]] || rm -rf -- "$WORK_DOWNLOADS" return "$status" } @@ -7394,7 +7406,7 @@ m3_persistent_transaction_begin() { local defaults=$M3_LIMINE_DEFAULTS target [[ $1 != grub ]] || defaults=$M3_GRUB_DEFAULTS target=$(esp_bootbin) || die "persistent GPU requires the mounted boot.bin" - $sudo python3 - "$STATE/m3-persistent-transaction.json" "$defaults" "$M1N1_CONF" "$target" \ + $sudo python3 -I - "$STATE/m3-persistent-transaction.json" "$defaults" "$M1N1_CONF" "$target" \ "$M3_GPU_OPTIN" "$M3_GPU_PROFILE_FILE" "$STATE/m3-gpu-persistent" "$STATE/m3-mode" \ "$M3_PROFILE_HOOK" "$M3_PROFILE_UPDATE" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" <<'M3_TRANSACTION_BEGIN' import base64, json, os, stat, sys @@ -7416,7 +7428,7 @@ M3_TRANSACTION_BEGIN } m3_persistent_transaction_rollback() { - $sudo python3 - "$STATE/m3-persistent-transaction.json" <<'M3_TRANSACTION_ROLLBACK' + $sudo python3 -I - "$STATE/m3-persistent-transaction.json" <<'M3_TRANSACTION_ROLLBACK' import base64, json, os, stat, sys, tempfile from pathlib import Path snapshot=Path(sys.argv[1]) @@ -7493,7 +7505,7 @@ m3_persistent_cmdline() { if [[ $chain == grub ]]; then path=$M3_GRUB_DEFAULTS else path=$M3_LIMINE_DEFAULTS; fi [[ -f $STATE/m3-defaults.saved ]] || $sudo cp -p "$path" "$STATE/m3-defaults.saved" - $sudo python3 - "$path" "$chain" "$armed" "$M3_LIMINE_VENDOR_CONF" "$M3_PROCFS/cmdline" <<'M3_CMDLINE_PY' + $sudo python3 -I - "$path" "$chain" "$armed" "$M3_LIMINE_VENDOR_CONF" "$M3_PROCFS/cmdline" <<'M3_CMDLINE_PY' import os, re, sys, tempfile from pathlib import Path path, chain = Path(sys.argv[1]), sys.argv[2] @@ -7877,7 +7889,7 @@ m3_limine_remove_check() { local target target=$(esp_bootbin) || die "cannot check the retained Limine entry without its mounted FAT boot partition; recovery state was kept" m3_boot_profile_install - $sudo python3 "$M3_BOOT_PROFILE_HELPER" "${1:-check-remove}" --esp "${target%/m1n1/boot.bin}" --state "$STATE" || + $sudo python3 -I "$M3_BOOT_PROFILE_HELPER" "${1:-check-remove}" --esp "${target%/m1n1/boot.bin}" --state "$STATE" || die "could not safely remove the retained Limine entry; its recovery state and modules were kept" if [[ ${1:-} == remove ]]; then $sudo rm -f "$M3_BOOT_PROFILE_HELPER"; fi } @@ -7887,7 +7899,7 @@ m3_keep_limine_entry() { target=$(esp_bootbin) || die "persistent GPU requires the mounted FAT boot partition" esp=${target%/m1n1/boot.bin} m3_boot_profile_install - $sudo python3 "$M3_BOOT_PROFILE_HELPER" "$1" --esp "$esp" --state "$STATE" --kernel "${kernel:-linux-aurora}" || + $sudo python3 -I "$M3_BOOT_PROFILE_HELPER" "$1" --esp "$esp" --state "$STATE" --kernel "${kernel:-linux-aurora}" || die "could not retain/publish the checked GPU-off Limine entry" if [[ $1 == retain ]]; then release=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["release"])' "$STATE/m3-known-entry.json") @@ -7917,7 +7929,7 @@ EOF } m3_grub_fallback_off() { - $sudo python3 - "$1" <<'M3_GRUB_OFF' + $sudo python3 -I - "$1" <<'M3_GRUB_OFF' from pathlib import Path import re, sys path=Path(sys.argv[1]);text=path.read_text() @@ -7948,7 +7960,7 @@ m3_persistent_cmdline_remove() { if [[ -f $path ]] && grep -qF '# >>> aurora-sep: M3 GPU cmdline' "$path"; then owned=1; fi done ((owned)) || return 0 - $sudo python3 - "$M3_GRUB_DEFAULTS" "$M3_LIMINE_DEFAULTS" <<'M3_REMOVE_CMDLINE' + $sudo python3 -I - "$M3_GRUB_DEFAULTS" "$M3_LIMINE_DEFAULTS" <<'M3_REMOVE_CMDLINE' from pathlib import Path import re, sys begin, end = '# >>> aurora-sep: M3 GPU cmdline', '# <<< aurora-sep: M3 GPU cmdline' @@ -8050,9 +8062,9 @@ m3_gpu_check_plan() { m3_gpu_check_install() { local sha m3_gpu_check_plan - m3_gpu_check_builtin | $sudo tee "$work/aurora-m3-gpu-check" >/dev/null + m3_gpu_check_builtin | work_write "$work/aurora-m3-gpu-check" sha=$(sha256sum "$work/aurora-m3-gpu-check" | cut -d' ' -f1) - $sudo python3 - "$work/aurora-m3-gpu-check" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" "$sha" <<'M3_CHECK_INSTALL_PY' + $sudo python3 -I - "$work/aurora-m3-gpu-check" "$M3_GPU_CHECK" "$STATE/m3-gpu-check" "$sha" <<'M3_CHECK_INSTALL_PY' import hashlib, os, stat, sys, tempfile from pathlib import Path source, helper, record = map(Path, sys.argv[1:4]) @@ -8745,7 +8757,7 @@ neo_gpu_transaction_begin() { [[ $original_m1n1 == /* && -f $original_m1n1 && ! -L $original_m1n1 ]] || die "cannot preserve this Neo's original M1N1 binary: $original_m1n1" $sudo install -d "$STATE" - $sudo python3 - "$STATE/neo-transaction.json" "$UPDATE_M1N1_CONF" "$target" \ + $sudo python3 -I - "$STATE/neo-transaction.json" "$UPDATE_M1N1_CONF" "$target" \ "$NEO_GPU_CONFIG/profile" "$NEO_GPU_CONFIG/gpu-experiment" "$STATE/neo-gpu" "$original_m1n1" <<'NEO_SNAPSHOT' import base64,json,stat,sys from pathlib import Path @@ -8783,7 +8795,7 @@ NEO_BOOT_CONFIG neo_gpu_restore() { local snapshot=$1 [[ -f $snapshot ]] || return 0 - $sudo python3 - "$snapshot" <<'NEO_RESTORE' + $sudo python3 -I - "$snapshot" <<'NEO_RESTORE' import base64,json,os,tempfile,sys from pathlib import Path for row in json.loads(Path(sys.argv[1]).read_text()): @@ -10875,6 +10887,7 @@ with os.fdopen(fd, "rb") as f: if hashlib.sha256(data).hexdigest() != want: sys.exit("its sha256 differs from the checked one") out = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC, 0o755) +os.fchmod(out, 0o755) with os.fdopen(out, "wb") as f: f.write(data) KIT_SELF_COPY_PY @@ -10883,9 +10896,23 @@ KIT_SELF_COPY_PY echo "install-aurora-sep: error: root could not take the kit script ($1) as checked. Nothing was changed." >&2 exit 1 fi - shift 3 + # The identity check again, on root'"'"'s own copy, which can no longer change: what is run + # is what was checked. The check sources the script, so it runs as the invoking user, on + # the descriptor root opened (the directory stays root'"'"'s alone). + as_user=() + [[ $(id -u) == "$(id -u "$3")" ]] || as_user=(runuser -u "$3" --) + theirs=$(${as_user[@]+"${as_user[@]}"} env AURORA_SEP_SOURCE_ONLY=1 \ + bash -c '"'"'source /dev/stdin >/dev/null 2>&1 && m3max_kit_identity'"'"' \ + <"$d/install-aurora-sep.sh" 2>/dev/null) || theirs="" + if [[ -z $theirs || $theirs != "$4" ]]; then + rm -rf "$d" + echo "install-aurora-sep: error: root'"'"'s copy of the kit script is not the script that runs now. Nothing was changed." >&2 + exit 1 + fi + shift 4 exec bash "$d/install-aurora-sep.sh" --m3max-kit --kit-work "$d" "$@"' \ - _ "$M3MAX_KIT_WORK/install-aurora-sep.sh" "$M3MAX_KIT_SELF_SHA" "$(id -un)" "${a[@]}" || rc=$? + _ "$M3MAX_KIT_WORK/install-aurora-sep.sh" "$M3MAX_KIT_SELF_SHA" "$(id -un)" "$(m3max_kit_identity)" \ + "${a[@]}" || rc=$? rm -rf -- "$M3MAX_KIT_WORK" exit "$rc" fi diff --git a/tools/aurora-sep/tests/test_m3_flow.py b/tools/aurora-sep/tests/test_m3_flow.py index ed001d3562937a..1d203402771a8c 100644 --- a/tools/aurora-sep/tests/test_m3_flow.py +++ b/tools/aurora-sep/tests/test_m3_flow.py @@ -971,7 +971,8 @@ def test_frozen_preparation_binds_requirements_and_explicit_archive_list(self): mkdir -p "$work" touch "$work/$(m3_pro_mesa_file)" "$work/unrelated.pkg.tar.zst" "$work/transaction.conf" python3() { - if [[ $1 == "$work/frozen-dependencies.py" ]]; then + if [[ $1 == -I && $2 == "$work/frozen-dependencies.py" ]]; then + shift printf 'planner-arg:%s\\n' "$@" >>"$FAKE/log" printf '{"transaction_config":"%s/transaction.conf","candidate_sha256":{"%s/%s":"fixture"},"dependencies":[{"file":"%s/approved.pkg.tar.gz"}]}' "$work" "$work" "$(m3_pro_mesa_file)" "$work" else command python3 "$@"; fi diff --git a/tools/aurora-sep/tests/test_m3_pro_mesa.py b/tools/aurora-sep/tests/test_m3_pro_mesa.py index ccff9c13220bb6..c5450876998cd5 100644 --- a/tools/aurora-sep/tests/test_m3_pro_mesa.py +++ b/tools/aurora-sep/tests/test_m3_pro_mesa.py @@ -106,6 +106,11 @@ def tree(tc): r'sha256sum -- /\S+|chmod 0755 |rm -rf )$') +# work_write: what 12.2 wrote with "sudo tee" now gets its mode set in root's shell. +WORK_WRITE = re.compile(r'^sudo sh -c umask 022 && cat >"\$1" _ (/(?:migrate-pro-session\.py|' + r'frozen-dependencies\.py|dependency-result\.json|dependency-files|aurora-m3-gpu-check))$') + + def package_check_log(tc, text): lines = text.splitlines() queries = [i for i, line in enumerate(lines) if line == 'pacman -Qu --color never'] @@ -119,8 +124,11 @@ def package_check_log(tc, text): out = [] for line in lines: if line in ('pacman -Qu --color never', 'pacman -Sy --noconfirm', 'sudo pacman -Sy --noconfirm'): continue + line = WORK_WRITE.sub(r'sudo tee \1', line) # work_to_root: root's own checked copy of the downloads (not in 12.2). if WORK_TO_ROOT.match(line): continue + # Root's Python runs isolated (-I) since 12.2. + line = line.replace('sudo python3 -I ', 'sudo python3 ') line = line.replace('pacman -Sy --noconfirm --ask 4 ', 'pacman -S --noconfirm --ask 4 ') out.append(line) return out diff --git a/tools/aurora-sep/tests/test_root_staging.py b/tools/aurora-sep/tests/test_root_staging.py index 83dc61995620ff..619e0297018e8a 100644 --- a/tools/aurora-sep/tests/test_root_staging.py +++ b/tools/aurora-sep/tests/test_root_staging.py @@ -92,6 +92,56 @@ def test_a_link_planted_in_place_of_a_download_is_refused(self): r = self.stage(d, [f'a.pkg.tar.zst {sha(b"A")}']) self.assertEqual(r.returncode, 9) + def test_a_failed_copy_leaves_no_directory_behind(self): + d = self.downloads(**{'a.pkg.tar.zst': b'A', 'b.pkg.tar.zst': b'changed'}) + r = self.sh(f""" +sudo=fakesudo +work='{d}' +FROZEN_PACKAGES=0 NEO_GPU_PREPARED=0 M3_PERSISTENT_TRANSACTION_ACTIVE=0 +candidate_archives=() +trap 'm3_install_cleanup' EXIT +work_to_root <<'LIST' +a.pkg.tar.zst {sha(b"A")} +b.pkg.tar.zst {sha(b"B")} +LIST +""") + self.assertEqual(r.returncode, 9, r.stdout + r.stderr) + self.assertEqual(sorted(self.tmpdir.iterdir()), []) + + def test_root_files_stay_readable_under_a_private_umask(self): + # sudo keeps the invoking user's umask. What root writes into its work directory is + # read back by the user's side, so its mode must not depend on that umask. + d = self.downloads(**{'a.pkg.tar.zst': b'A'}) + state = self.root / 'state' + r = self.sh(f""" +umask 077 +sudo=fakesudo +work='{d}' +candidate_archives=() +work_to_root <<'LIST' +a.pkg.tar.zst {sha(b"A")} +LIST +echo text | work_write "$work/dependency-result.json" +m3_gpu_check_plan() {{ :; }} +STATE='{state}' M3_GPU_CHECK='{self.root}/sbin/aurora-m3-gpu-check' +m3_gpu_check_install +stat -c 'mode %a %n' "$work" "$work"/* +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + modes = {name: mode for mode, name in re.findall(r'^mode (\d+) \S*/([^/\n]+)$', r.stdout, re.M)} + self.assertEqual(modes.pop('a.pkg.tar.zst'), '644') + self.assertEqual(modes.pop('dependency-result.json'), '644') + self.assertEqual(modes.pop('aurora-m3-gpu-check'), '644') + self.assertEqual(list(modes.values()), ['755'], r.stdout) + self.assertEqual((self.root / 'sbin/aurora-m3-gpu-check').stat().st_mode & 0o777, 0o755) + + def test_root_writes_into_its_work_directory_set_the_mode(self): + text = INSTALLER.read_text() + self.assertEqual(re.findall(r'^[^#\n]*\btee "\$work/[^\n]*', text, re.M), []) + for name in ('migrate-pro-session.py', 'frozen-dependencies.py', 'dependency-result.json', + 'dependency-files', 'aurora-m3-gpu-check'): + self.assertRegex(text, rf'work_write "\$work/{re.escape(name)}"') + def test_odd_names_are_refused(self): d = self.downloads(**{'a.pkg.tar.zst': b'A'}) for name in ('../a.pkg.tar.zst', '.hidden', 'x/y'): @@ -138,6 +188,17 @@ def body(name): self.assertLess(install_all.index('work_to_root'), install_all.index('m3_install_packages')) +class PythonIsolation(unittest.TestCase): + def test_every_root_python_is_isolated(self): + text = INSTALLER.read_text() + calls = re.findall(r'\$sudo python3\b[^\n]*', text) + self.assertGreater(len(calls), 10) + for call in calls: + self.assertTrue(call.startswith('$sudo python3 -I '), call) + self.assertIn('"Exec = /usr/bin/python3 -I "', text) + self.assertIn('python3 -I - "$1" "$d/install-aurora-sep.sh"', text) + + class KitRootCopy(unittest.TestCase): """--m3max-kit under sudo: root runs its own checked copy, from its own directory.""" @@ -151,11 +212,24 @@ def setUp(self): (self.bin / 'fakesudo').chmod(0o755) self.tmpdir = self.root / 'tmp' self.tmpdir.mkdir() - self.copy = b'#!/bin/bash\necho "ran $0 $*"\n' + # The installer's own identity, and a stand-in copy that reports it when sourced + # (as the root side checks it) and says how it was run otherwise. + ident = subprocess.run(['bash', '-c', f"AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' && m3max_kit_identity"], + capture_output=True, text=True, check=True).stdout + (self.root / 'identity').write_text(ident) + (self.root / 'other-identity').write_text('another release|') + self.copy = self.root / 'copy.sh' + self.copy.write_text(self.stand_in('identity')) - def setup(self, tamper=''): + def stand_in(self, ident): + return (f"#!/bin/bash\nm3max_kit_identity() {{ cat '{self.root}/{ident}'; }}\n" + "if [[ ${AURORA_SEP_SOURCE_ONLY:-} == 1 ]]; then return 0; fi\n" + 'echo "ran $0 $*"\necho "mode $(stat -c %a "$0")"\n') + + def setup(self, tamper='', before=''): script = f""" set -euo pipefail +{before} AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' export TMPDIR='{self.tmpdir}' die() {{ echo "DIED: $*"; exit 9; }} @@ -164,7 +238,7 @@ def setup(self, tamper=''): require_supported_soc() {{ :; }} is_m3_max() {{ true; }} m3max_kit_self() {{ - printf '%b' {self.copy.decode()!r} >"$M3MAX_KIT_WORK/install-aurora-sep.sh" + cp '{self.copy}' "$M3MAX_KIT_WORK/install-aurora-sep.sh" M3MAX_KIT_SELF_SHA=$(sha256sum "$M3MAX_KIT_WORK/install-aurora-sep.sh" | cut -d' ' -f1) echo "user-work=$M3MAX_KIT_WORK" {tamper} @@ -190,6 +264,46 @@ def test_a_changed_copy_is_not_run(self): self.assertNotIn('ran ', r.stdout) self.assertIn('could not take the kit script', r.stderr) + def test_root_checks_the_identity_of_its_own_copy(self): + # The user-side checks saw a script that passed; the file root copies (its sha256 taken + # on that same content) is another script. Root's own identity check refuses it. + self.copy.write_text(self.stand_in('other-identity')) + r = self.setup() + self.assertNotEqual(r.returncode, 0) + self.assertNotIn('ran ', r.stdout) + self.assertIn('is not the script that runs now', r.stderr) + + def test_the_identity_check_of_roots_copy_runs_as_the_invoking_user(self): + # The check sources the script. With root's id differing from the invoking user's, it + # is run through runuser for that user, reading root's copy from its standard input. + log = self.root / 'runuser.log' + (self.bin / 'id').write_text('#!/bin/sh\nif [ "$*" = "-u" ]; then echo 0; else exec /usr/bin/id "$@"; fi\n') + (self.bin / 'runuser').write_text( + f'#!/bin/sh\necho "$*" >>"{log}"\nreadlink /proc/self/fd/0 >>"{log}"\nshift 3\nexec "$@"\n') + for name in ('id', 'runuser'): + (self.bin / name).chmod(0o755) + r = self.setup() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + m = re.search(r'^ran (\S+)/install-aurora-sep\.sh ', r.stdout, re.M) + self.assertIsNotNone(m, r.stdout) + call, stdin = log.read_text().splitlines() + user = subprocess.run(['/usr/bin/id', '-un'], capture_output=True, text=True).stdout.strip() + self.assertTrue(call.startswith(f'-u {user} -- env AURORA_SEP_SOURCE_ONLY=1 bash -c source /dev/stdin '), call) + self.assertEqual(stdin, f'{m.group(1)}/install-aurora-sep.sh') + + def test_the_installer_reports_its_identity_from_standard_input(self): + with open(INSTALLER) as f: + r = subprocess.run(['bash', '-c', 'AURORA_SEP_SOURCE_ONLY=1 source /dev/stdin >/dev/null 2>&1 && m3max_kit_identity'], + stdin=f, capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout, (self.root / 'identity').read_text()) + self.assertGreater(r.stdout.count('|'), 8) + + def test_roots_copy_is_readable_under_a_private_umask(self): + r = self.setup(before='umask 077') + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('\nmode 755\n', r.stdout) + def test_a_link_is_not_followed(self): r = self.setup(tamper=f'cp "$M3MAX_KIT_WORK/install-aurora-sep.sh" "{self.root}/real"; ' f'ln -sf "{self.root}/real" "$M3MAX_KIT_WORK/install-aurora-sep.sh"') From 4b5650c9f5115afcd748f12a419c560823747d97 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:18:03 +1100 Subject: [PATCH 0481/1514] soc: apple: rtkit: let ordinary firmware traffic through the committed v27 display stop The firmware-27 late display stop checks each display coprocessor once before the sleep's commit and again right before its stop, after the commit, where any failure ends in panic("Apple committed display stop failed"). Two steps failed on ordinary firmware traffic: - apple_rtkit_v27_check() consumed any pending mailbox message into the scope FIFO and returned -EAGAIN, also when called after the commit. The stop that follows reads the mailbox itself. - apple_rtkit_v27_idle_atomic() returned -EPROTO for any message that was neither one of the three power-state answers nor an owed OSLOG counter, e.g. a syslog line or an application endpoint's message. The check op now learns whether the sleep is committed (the sleep core passes entry_committed). Before the commit a pending message still refuses the sleep and is kept for the disarm; after it, the check leaves the message in the mailbox for the stop. The atomic idle keeps messages from other endpoints in the scope FIFO, which the disarm already replays after the restart, and goes on waiting for the power-state answers within the same 100 ms budget. A management message off the handshake, a crashlog message, a full FIFO and the timeout still fail the stop, as before. The panic itself stays: a coprocessor that did not stop still runs with its DARTs unstopped, and the DART stop requires the initiator to be stopped first. tools/asahi/rtkit-v27-late-tests.py compiles both functions from the source against a fake mailbox and firmware; its --consume-committed and --fail-foreign mutations restore the old behaviour and fail. Reported-by: erikwb <169195+erikwb@users.noreply.github.com> Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-v27-sleep.inc | 4 +- drivers/soc/apple/rtkit-v27-late.inc | 19 +- drivers/soc/apple/sleep-v27-late.inc | 2 +- include/linux/soc/apple/dcp-v27-sleep.h | 5 +- tools/asahi/rtkit-v27-late-tests.py | 266 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 6 files changed, 291 insertions(+), 7 deletions(-) create mode 100755 tools/asahi/rtkit-v27-late-tests.py diff --git a/drivers/gpu/drm/apple/dcp-v27-sleep.inc b/drivers/gpu/drm/apple/dcp-v27-sleep.inc index 027927a4ec055f..37a16ec8f4fecc 100644 --- a/drivers/gpu/drm/apple/dcp-v27-sleep.inc +++ b/drivers/gpu/drm/apple/dcp-v27-sleep.inc @@ -1305,7 +1305,7 @@ static int dcp_v27_late_arm(void *data) return 0; } -static int dcp_v27_late_check(void *data) +static int dcp_v27_late_check(void *data, bool committed) { struct dcp_v27_sleep *s = data; struct apple_dcp *dcp = s->dcp; @@ -1322,7 +1322,7 @@ static int dcp_v27_late_check(void *data) if (!ret) ret = apple_dart_v27_check(s->firmware); if (!ret) - ret = apple_rtkit_v27_check(s->rx); + ret = apple_rtkit_v27_check(s->rx, committed); return ret; } diff --git a/drivers/soc/apple/rtkit-v27-late.inc b/drivers/soc/apple/rtkit-v27-late.inc index 6f3bfd84ab0a5f..82d39de6f8cc00 100644 --- a/drivers/soc/apple/rtkit-v27-late.inc +++ b/drivers/soc/apple/rtkit-v27-late.inc @@ -96,7 +96,11 @@ undo: } EXPORT_SYMBOL_GPL(apple_rtkit_v27_arm); -int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) +/* + * Before the commit, a pending message refuses the sleep (it is kept for the disarm). After it, + * the stop that follows reads the mailbox itself: a message there is left to it. + */ +int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s, bool committed) { struct apple_mbox_msg msg; int ret; @@ -109,6 +113,8 @@ int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) return -EBUSY; if (kfifo_is_full(&s->deferred)) return -ENOBUFS; + if (committed) + return 0; ret = apple_mbox_recv_nowait(s->rtk->mbox, &msg); if (ret > 0) { kfifo_put(&s->deferred, msg); @@ -190,10 +196,19 @@ int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) } else if (apple_rtkit_oslog_owed_msg(rtk, msg.msg1, msg.msg0)) { echo = msg; echo_pending = true; - } else { + } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT || + msg.msg1 == APPLE_RTKIT_EP_CRASHLOG) { + /* Off the power-state handshake, or a crash: no stop. */ kfifo_put(&s->deferred, msg); ret = -EPROTO; goto poison; + } else { + /* + * Ordinary traffic (a log line, a report, an endpoint's + * message): kept for the disarm's replay, and the wait + * for the power-state answers goes on. + */ + kfifo_put(&s->deferred, msg); } } } diff --git a/drivers/soc/apple/sleep-v27-late.inc b/drivers/soc/apple/sleep-v27-late.inc index a130d3bd94d3a0..5adb3a10f261ba 100644 --- a/drivers/soc/apple/sleep-v27-late.inc +++ b/drivers/soc/apple/sleep-v27-late.inc @@ -141,7 +141,7 @@ static int sleep_v27_final_check(unsigned int i) if (!sleep_v27_held || i >= ARRAY_SIZE(sleep_v27) || !sleep_v27[i].armed || !READ_ONCE(sleep_v27[i].prepared)) return -EBUSY; - return sleep_v27[i].ops->check(sleep_v27[i].data); + return sleep_v27[i].ops->check(sleep_v27[i].data, apple_sleep->entry_committed); } static bool sleep_v27_gate_prepared(const struct device_node *np) diff --git a/include/linux/soc/apple/dcp-v27-sleep.h b/include/linux/soc/apple/dcp-v27-sleep.h index 5e56c401419036..9237932c951678 100644 --- a/include/linux/soc/apple/dcp-v27-sleep.h +++ b/include/linux/soc/apple/dcp-v27-sleep.h @@ -16,7 +16,8 @@ struct apple_dart_v27_lease; */ struct apple_sleep_v27_ops { int (*arm)(void *data); - int (*check)(void *data); + /* committed: called after the sleep's commit, right before stop. */ + int (*check)(void *data, bool committed); int (*stop)(void *data); int (*disarm)(void *data, bool stopped); }; @@ -37,7 +38,7 @@ static inline void apple_sleep_v27_prepared(struct device *dev, bool prepared) { int apple_rtkit_v27_arm(struct apple_rtkit *, struct apple_rtkit_v27_scope **); bool apple_rtkit_v27_live(struct apple_rtkit *); -int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *); +int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *, bool committed); int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *); int apple_rtkit_v27_disarm(struct apple_rtkit_v27_scope *, bool stopped); diff --git a/tools/asahi/rtkit-v27-late-tests.py b/tools/asahi/rtkit-v27-late-tests.py new file mode 100755 index 00000000000000..a40afaee4c3a86 --- /dev/null +++ b/tools/asahi/rtkit-v27-late-tests.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the firmware-27 late display stop's RTKit check and atomic idle against a fake mailbox. + +The bodies of apple_rtkit_v27_check() and apple_rtkit_v27_idle_atomic() are compiled from +drivers/soc/apple/rtkit-v27-late.inc, the RTKit constants and apple_rtkit_oslog_owed_msg() +from rtkit.c. The fake firmware answers the AP and IOP power-state requests and can put +ordinary traffic (a syslog line, an endpoint message) into the receive queue at any point. + +Cases: before the commit a pending message refuses (kept for the disarm); after the commit +the check leaves it in the mailbox and the stop completes; traffic during the stop's wait is +deferred into the scope FIFO in order and the stop completes; an unexpected management or a +crashlog message still fails the stop; no answer still times out; a full FIFO still fails. + +Mutations: --consume-committed (the committed check consumes and refuses as before), +--fail-foreign (the stop fails on any foreign message as before). +""" +from pathlib import Path +import argparse +import re +import subprocess +import sys +import tempfile + +ap = argparse.ArgumentParser() +ap.add_argument('--out') +ap.add_argument('--consume-committed', action='store_true') +ap.add_argument('--fail-foreign', action='store_true') +args = ap.parse_args() + +root = Path(__file__).resolve().parents[2] +inc = (root / 'drivers/soc/apple/rtkit-v27-late.inc').read_text() +rtkit = (root / 'drivers/soc/apple/rtkit.c').read_text() + + +def function(src, sig): + a = src.index(sig) + a = src.rfind('\n', 0, a) + 1 + b = src.index('\n}', src.index('{', a)) + 2 + return src[a:b] + + +def scope_struct(): + a = inc.index('struct apple_rtkit_v27_scope {') + return inc[a:inc.index('};', a) + 2] + + +consts = [] +for name in ['APPLE_RTKIT_PWR_STATE_IDLE', 'APPLE_RTKIT_PWR_STATE_ON', 'APPLE_RTKIT_EP_MGMT', + 'APPLE_RTKIT_EP_CRASHLOG', 'APPLE_RTKIT_EP_SYSLOG', 'APPLE_RTKIT_EP_OSLOG', + 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK', + 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK', + 'APPLE_RTKIT_MGMT_IDLE_NOTIFY']: + m = re.search(r'\b' + name + r' = (0x[0-9a-fA-F]+|[0-9]+),', rtkit) + consts.append(f'#define {name} {m.group(1)}') +for name in ['APPLE_RTKIT_MGMT_TYPE', 'APPLE_RTKIT_MGMT_PWR_STATE', 'APPLE_RTKIT_SYSLOG_TYPE', + 'APPLE_RTKIT_SYSLOG_LOG', 'APPLE_RTKIT_OSLOG_TYPE', 'APPLE_RTKIT_OSLOG_LOG']: + m = re.search(r'#define ' + name + r' (.+)', rtkit) + consts.append(f'#define {name} {m.group(1)}') + +check = function(inc, 'int apple_rtkit_v27_check(') +idle = function(inc, 'int apple_rtkit_v27_idle_atomic(') +if args.consume_committed: + old = '\tif (committed)\n\t\treturn 0;\n' + assert check.count(old) == 1 + check = check.replace(old, '') +if args.fail_foreign: + old = ('\t\t\t\t\t */\n\t\t\t\t\tkfifo_put(&s->deferred, msg);\n\t\t\t\t}') + assert idle.count(old) == 1 + idle = idle.replace(old, '\t\t\t\t\t */\n\t\t\t\t\tkfifo_put(&s->deferred, msg);\n' + '\t\t\t\t\tret = -EPROTO;\n\t\t\t\t\tgoto poison;\n\t\t\t\t}') + +pre = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +#define GENMASK_ULL(h, l) (((~0ULL) << (l)) & (~0ULL >> (63 - (h)))) +#define FIELD_PREP(m, v) ((((u64)(v)) << __builtin_ctzll(m)) & (m)) +#define FIELD_GET(m, v) ((((u64)(v)) & (m)) >> __builtin_ctzll(m)) +#define dma_wmb() ((void)0) +#define dma_rmb() ((void)0) +#define EXPORT_SYMBOL_GPL(x) +struct module; +struct apple_mbox_msg { u64 msg0; u32 msg1; }; +#define FIFO_N 64 +#define DECLARE_KFIFO(n, t, sz) struct { t buf[sz]; unsigned in, out; } n +#define INIT_KFIFO(f) ((f).in = (f).out = 0) +#define kfifo_is_full(f) ((f)->in - (f)->out == FIFO_N) +#define kfifo_len(f) ((f)->in - (f)->out) +#define kfifo_put(f, v) (kfifo_is_full(f) ? 0 : ((f)->buf[(f)->in++ % FIFO_N] = (v), 1)) +#define kfifo_get(f, p) ((f)->in == (f)->out ? 0 : (*(p) = (f)->buf[(f)->out++ % FIFO_N], 1)) +#define QN 256 +struct apple_mbox { + bool removing, active; + struct apple_mbox_msg rx[QN]; unsigned rx_in, rx_out; + struct apple_mbox_msg tx[QN]; unsigned tx_n; + bool recv_enabled; +}; +struct apple_rtkit { + struct apple_mbox *mbox; + bool crashed, shutting_down, strict_idle_poisoned, oslog_echo, silent; + unsigned ap_power_state, iop_power_state; + unsigned ticks, inject_at, injected; + struct apple_mbox_msg inject[8]; unsigned ninject; +}; +''' +consts_c = '\n'.join(consts) + '\n' +fake = r''' +static bool irqs_disabled(void) { return true; } +static struct apple_rtkit *cur; +static void push(struct apple_mbox *b, u32 ep, u64 msg0) +{ + b->rx[b->rx_in++ % QN] = (struct apple_mbox_msg){ .msg0 = msg0, .msg1 = ep }; +} +static void udelay(unsigned us) +{ + (void)us; + if (++cur->ticks == cur->inject_at) + for (unsigned i = 0; i < cur->ninject; i++, cur->injected++) + push(cur->mbox, cur->inject[i].msg1, cur->inject[i].msg0); +} +static bool apple_rtkit_v27_rx_drained(struct apple_rtkit *rtk) { return true; } +static void apple_mbox_set_recv_enabled(struct apple_mbox *b, bool on) { b->recv_enabled = on; } +static int apple_mbox_recv_nowait(struct apple_mbox *b, struct apple_mbox_msg *m) +{ + if (b->removing || !b->active) + return -ENODEV; + if (b->rx_in == b->rx_out) + return 0; + *m = b->rx[b->rx_out++ % QN]; + return 1; +} +/* The firmware: answers each power-state request, IOP idle followed by its notice. */ +static int apple_mbox_send_nowait(struct apple_mbox *b, struct apple_mbox_msg m) +{ + u8 type = FIELD_GET(APPLE_RTKIT_MGMT_TYPE, m.msg0); + u64 st = FIELD_GET(APPLE_RTKIT_MGMT_PWR_STATE, m.msg0); + + b->tx[b->tx_n++] = m; + if (cur->silent || m.msg1 != APPLE_RTKIT_EP_MGMT) + return 0; + if (type == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE) + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK) | st); + if (type == APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE) { + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK) | st); + push(b, 0, FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_IDLE_NOTIFY)); + } + return 0; +} +''' +owed = function(rtkit, 'static bool apple_rtkit_oslog_owed_msg(') + +main = r''' +static struct apple_mbox mb; +static struct apple_rtkit rk; +static struct apple_rtkit_v27_scope sc; +static void reset(void) +{ + memset(&mb, 0, sizeof(mb)); memset(&rk, 0, sizeof(rk)); memset(&sc, 0, sizeof(sc)); + mb.active = mb.recv_enabled = true; + rk.mbox = &mb; rk.ap_power_state = rk.iop_power_state = APPLE_RTKIT_PWR_STATE_ON; + sc.rtk = &rk; sc.held = true; INIT_KFIFO(sc.deferred); + cur = &rk; +} +#define SYSLOG_LINE (FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 0x12) +#define APP_MSG 0x123456789aULL +static void stopped_ok(void) +{ + assert(sc.stopped && !sc.failed && !rk.strict_idle_poisoned && !mb.recv_enabled); + assert(rk.ap_power_state == APPLE_RTKIT_PWR_STATE_IDLE); + assert(rk.iop_power_state == APPLE_RTKIT_PWR_STATE_IDLE); +} +int main(void) +{ + struct apple_mbox_msg m; + + /* Before the commit: a pending log line refuses the sleep and is kept for the disarm. */ + reset(); push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + assert(apple_rtkit_v27_check(&sc, false) == -EAGAIN); + assert(kfifo_len(&sc.deferred) == 1 && mb.rx_in == mb.rx_out); + reset(); + assert(apple_rtkit_v27_check(&sc, false) == 0 && apple_rtkit_v27_check(&sc, true) == 0); + + /* After the commit: the log line stays in the mailbox and the stop answers it. */ + reset(); push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + assert(apple_rtkit_v27_check(&sc, true) == 0); + assert(kfifo_len(&sc.deferred) == 0 && mb.rx_in != mb.rx_out); + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_SYSLOG && m.msg0 == SYSLOG_LINE); + assert(!kfifo_get(&sc.deferred, &m)); + + /* Ordinary traffic in the middle of the wait: deferred in order, the stop completes. */ + reset(); rk.inject_at = 1; rk.ninject = 2; + rk.inject[0] = (struct apple_mbox_msg){ .msg0 = SYSLOG_LINE, .msg1 = APPLE_RTKIT_EP_SYSLOG }; + rk.inject[1] = (struct apple_mbox_msg){ .msg0 = APP_MSG, .msg1 = 0x37 }; + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); assert(rk.injected == 2); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_SYSLOG); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == 0x37 && m.msg0 == APP_MSG); + assert(!kfifo_get(&sc.deferred, &m)); + + /* An owed OSLOG counter is still echoed, not deferred. */ + reset(); rk.oslog_echo = true; + push(&mb, APPLE_RTKIT_EP_OSLOG, FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_LOG) | 7); + assert(apple_rtkit_v27_idle_atomic(&sc) == 0); + stopped_ok(); assert(kfifo_len(&sc.deferred) == 0); + { + bool echoed = false; + for (unsigned i = 0; i < mb.tx_n; i++) + echoed |= mb.tx[i].msg1 == APPLE_RTKIT_EP_OSLOG; + assert(echoed); + } + + /* A management message off the handshake, or a crashlog: still no stop. */ + reset(); push(&mb, APPLE_RTKIT_EP_MGMT, + FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK) | + APPLE_RTKIT_PWR_STATE_ON); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned && kfifo_len(&sc.deferred) == 1); + reset(); push(&mb, APPLE_RTKIT_EP_CRASHLOG, 0x1ULL << 52); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned); + + /* No answer: the 100 ms budget still ends in a failure. */ + reset(); rk.silent = true; + assert(apple_rtkit_v27_idle_atomic(&sc) == -ETIMEDOUT); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned && mb.recv_enabled); + + /* A full FIFO: nothing more is consumed, the stop fails. */ + reset(); + for (unsigned i = 0; i < FIFO_N; i++) + push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + assert(apple_rtkit_v27_idle_atomic(&sc) == -ENOBUFS); + assert(sc.failed && !sc.stopped && kfifo_is_full(&sc.deferred)); + assert(apple_rtkit_v27_check(&sc, true) == -EBUSY); + return 0; +} +''' + +code = pre + consts_c + scope_struct() + '\n' + fake + owed + '\n' + check + '\n' + idle + '\n' + main + + +def build_and_run(out): + out.mkdir(parents=True, exist_ok=True) + c = out / 'rtkit-v27-late.c' + c.write_text(code) + exe = out / 'rtkit-v27-late' + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-fsanitize=address,undefined', str(c), '-o', str(exe)], check=True) + return subprocess.run([str(exe)]).returncode + + +if args.out: + rc = build_and_run(Path(args.out)) +else: + with tempfile.TemporaryDirectory() as t: + rc = build_and_run(Path(t)) +if rc: + sys.exit(1) +print('PASS rtkit v27 late stop: committed check leaves a message to the stop, ' + 'foreign traffic deferred in order, owed OSLOG echoed, MGMT/crashlog/timeout/full FIFO still fail') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..a0de632a8823e2 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -67,6 +67,8 @@ def mutations(flag, names, base, expect=KILL): 'dcpext26-slot-unregister-tests.py': [(out(), PASS)], 'dcpext26-budget-tests.py': [([], PASS)], 'dcpext26-queue-tests.py': [([], PASS), (['--drop-v27-close'], KILL)], + 'rtkit-v27-late-tests.py': [(out(), PASS), (out() + ['--consume-committed'], KILL), + (out() + ['--fail-foreign'], KILL)], 'dcpext26-retrain-tests.py': [([], PASS), (['--negative-control'], KILL)], 'dcpext26-lifecycle-tests.py': [([], PASS)], 'dcpext26-modeset-tests.py': [([], PASS)], From 5af8985d15ebcf3d53aad64a1855d7691972a6a8 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 16:44:57 +0000 Subject: [PATCH 0482/1514] drm/asahi: g17: T6041: report the performance state, its frequency and busy time T6041's 25G83 firmware emits the same performance state records (tags 0x19 and 0x1b, with words 1 and 3 naming states 1..10) and timestamped utilisation records (tag 0x13, 8 ms period = 192000 ticks at 24 MHz, as the existing 25G83 decoder assumes) as V26A428. Because stats::protocol() mapped all InitGraph::V25G83 builds to Protocol::NONE, agx_stats on T6041 reported pstate, achieved_frequency_hz and busy_ns as unsupported, and fdinfo omitted drm-curfreq-* and drm-maxfreq-*. Move the telemetry Protocol onto fw::variant::Variant so each firmware build declares its own telemetry capabilities directly instead of deriving them from InitGraph and m5_commands, and make Protocol describe only the firmware record format (Protocol::NONE, Protocol::PSTATE_8MS for 8 ms / 192000-tick utilisation with 0x19/0x1b state reports, and Protocol::PSTATE_16MS for 16 ms / 384000-tick utilisation with 0x19/0x1b state reports) rather than per-chip constants. Derive the valid pstate upper bound (max_pstate) at runtime from StateFrequencies::max_pstate() instead of hardcoding it on Protocol, storing it on Shared so initial boot and firmware recovery restarts share the same bound (13 on M5's 14-entry board table, 10 on A18 Pro's and T6041's 11-state PERF table, and 0 / fail-closed if no table is present). Enable Protocol::PSTATE_8MS on T6041's 25G83 build, while leaving T6041 26B123, T6041 25F84, and T6040 25G83 (M4 Pro) on Protocol::NONE because they have not been measured yet. State frequencies continue to come from perf.states_a mapped onto the device tree operating points; on T6041 both table A and table B map state 10 to OPP 15 (1578 MHz) and only differ on mid-states (states 5..9 on 32-core J616C, 6..9 on 40-core), so those mid-state frequencies are documented as nominal (taken from table A) until measured by a mid-state ALU benchmark. Add unit and integration test coverage for T6041's 0x13/0x19/0x1b handling, runtime-derived max_pstate bounds (10 vs 13 on PSTATE_8MS and fail-closed max_pstate == 0), defensive rejection of mismatched or out-of-range states, safe fallback if a build omits 0x1b, and 8 ms busy-time integration, and update the agx_stats and asahi-usage-stats documentation. Scope: targets J616C (32-core T6041) on 25G83; live boot-testing is pending. Left on Protocol::NONE: T6041 26B123, T6041 25F84, T6040 25G83. Enabled but unmeasured: 40-core T6041 (J614C/J575C) on 25G83. Signed-off-by: AxxzyWasTaken --- .../ABI/testing/sysfs-driver-asahi-agx-stats | 54 ++++--- Documentation/gpu/asahi-usage-stats.rst | 55 ++++--- drivers/gpu/drm/asahi/g17/channel.rs | 12 +- drivers/gpu/drm/asahi/g17/fw/variant.rs | 6 + drivers/gpu/drm/asahi/g17/mod.rs | 36 +++-- drivers/gpu/drm/asahi/g17/stats.rs | 43 +++--- drivers/gpu/drm/asahi/g17/telemetry.rs | 134 ++++++++++++++---- drivers/gpu/drm/asahi/hw/t6041.rs | 3 + drivers/gpu/drm/asahi/stats.rs | 3 +- drivers/gpu/drm/asahi/sysfs.c | 11 +- .../asahi/g17-telemetry-integration-tests.py | 132 +++++++++++++---- 11 files changed, 345 insertions(+), 144 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats index f5c8afcc98bbf1..3ecdd8a454fae8 100644 --- a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats +++ b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats @@ -108,11 +108,11 @@ Description: older than the age limit below or its epoch ended. unsupported is a fixed property of the firmware, taken from the driver's per-firmware match data, and - never changes at runtime: the V25G83 firmware accepts - tag 0x10 but never emits it, and no other record of - it carries the current pstate, so pstate_status - always reads unsupported on G16S. V26A428 reports - its state in other records (see below). + never changes at runtime: T6040 V25G83 (M4 Pro) is + left on Protocol::NONE because it has not been + measured yet, so pstate_status reads unsupported on + T6040. V26A428 and T6041 (25G83) report their state + in other records (see below). utilisation_status is never unsupported on these firmwares. Numeric metrics are printed only while their capability is valid; otherwise their value is @@ -132,7 +132,8 @@ Description: firmware whose match data says it emits tag 0x10 (none of the current G16S/G17P firmwares do). A firmware that reports its state in tags 0x19 and - 0x1b (V26A428) never has tag 0x10 decoded. Words 1 + 0x1b (V26A428 and T6041 25G83) never has tag 0x10 + decoded. Words 1 and 2 form a little-endian u64 firmware timestamp. The first timestamp establishes a baseline. Invalid selectors and backwards timestamps remove pstate @@ -141,21 +142,23 @@ Description: requested_frequency_hz, achieved_frequency_hz, busy_ns, power_mw, temperature_raw - Always unsupported on V25G83 (G16S). No record of it - carries a state, a qualified busy-time duration, a - power unit or a temperature. + Unsupported on T6040 V25G83 (M4 Pro), which is left + on Protocol::NONE because it has not been measured + yet; power_mw and temperature_raw are unsupported on + all G16S/G17P firmwares. - The V26A428 firmware, which the A18 Pro (T8140, G17P) and M5 - run, uses the same snapshot and keys, with these differences: + The V26A428 firmware (A18 Pro T8140 and M5) and T6041 (M4 Max, + 25G83) use the same snapshot and keys, with these + differences: pstate_status, pstate Supported. The firmware reports the performance state in effect in tag 0x1b, words 1 and 3, which must agree: an index into the performance state table, - 1..10 on the A18 Pro, 1..13 on M5. The end of the - interval record before it (tag 0x19, words 1 and 2) - is its firmware timestamp. A report that names state - 0 or a state beyond the table removes pstate + 1..10 on the A18 Pro and T6041, 1..13 on M5. The end + of the interval record before it (tag 0x19, words 1 + and 2) is its firmware timestamp. A report that names + state 0 or a state beyond the table removes pstate validity. While the GPU cores are gated, pstate reads valid 0: the GPU is off. Power-up starts a new epoch, stale until the next report. The driver asks for full @@ -167,16 +170,23 @@ Description: achieved_frequency_hz The frequency of pstate in Hz, while pstate_status is valid, and 0 for state 0. M5: the board's performance - state table. A18 Pro: the device tree operating point - that the state's entry of performance table A names. - Its records do not name the table; at its top state a - sustained FP32 FMA load completes faster than table - B's frequency there allows, so it runs table A. + state table. A18 Pro and T6041: the device tree + operating point that the state's entry of performance + table A names. Their records do not name the table: + on the A18 Pro, at the top state a sustained FP32 FMA + load completes faster than table B's frequency there + allows, so it runs table A; on T6041 both tables map + state 10 to OPP 15 (1578 MHz) and only differ on + mid-states (states 5..9 on 32-core J616C, 6..9 on + 40-core), so those mid-state frequencies are nominal + (taken from table A) until measured by a mid-state + ALU benchmark. busy_ns Cumulative u64 since the driver was bound. The tag - 0x13 records of this firmware carry a timestamp in + 0x13 records of these firmwares carry a timestamp in 24 MHz ticks (words 1 and 2), one every 8 ms on M5 - and every 16 ms on the A18 Pro. Each record credits + and T6041 (192000 ticks) and every 16 ms on the A18 + Pro (384000 ticks). Each record credits the window since the previous record of its epoch at its device utilisation. A record more than two periods after the previous one, or with an earlier diff --git a/Documentation/gpu/asahi-usage-stats.rst b/Documentation/gpu/asahi-usage-stats.rst index c2cda44ce1e459..e1b0632a9fd0f5 100644 --- a/Documentation/gpu/asahi-usage-stats.rst +++ b/Documentation/gpu/asahi-usage-stats.rst @@ -62,7 +62,8 @@ cycles, or multiplying time by a sampled/maximum GPU frequency, would give incorrect frequency-weighted utilization. Per-client execution-cycle counters would require a separate hardware measurement source. -On the M5 and the A18 Pro each engine also has the frequency keys:: +On the M5, the A18 Pro and T6041 (M4 Max, 25G83) each engine also has +the frequency keys:: drm-curfreq-compute: 1620000000 Hz drm-maxfreq-compute: 1620000000 Hz @@ -88,9 +89,10 @@ The native backends reuse existing timestamp reads. Classic completion callbacks read two internal cells per stage; commands without application timestamps also execute two existing timestamp microsequence operations per stage. Reading fdinfo loads three counters -and does not traverse queues, wait for fences or access hardware. On the M5 and -the A18 Pro a read also takes the device mutex once and drains the statistics -rings, as a read of ``agx_stats`` does, for the frequency keys. +and does not traverse queues, wait for fences or access hardware. On the M5, +the A18 Pro and T6041 (25G83) a read also takes the device mutex once +and drains the statistics rings, as a read of ``agx_stats`` does, for the +frequency keys. G16S and G17P device utilisation ------------------------------ @@ -133,33 +135,38 @@ ring on powered cores becomes stale rather than fabricating a zero-utilisation sample; only gated cores read as zero. Readers must not convert these percentages into engine nanoseconds or cycles. -Performance state and busy time on V26A428 (A18 Pro and M5) ------------------------------------------------------------ +Performance state and busy time on V26A428 (A18 Pro and M5) and T6041 +--------------------------------------------------------------------- -The V26A428 firmware, which the A18 Pro (T8140, G17P) and the M5 run on the same -backend and decoder, carries more in its statistics ring. ``agx_stats`` reports -there: +The V26A428 firmware (A18 Pro T8140 and M5) and T6041's 25G83 firmware +run on the same backend and decoder and carry more in their statistics ring. +``agx_stats`` reports there: * ``pstate``: the performance state in effect, from the firmware's state reports (tag ``0x1b``, words 1 and 3, which must agree). It is an index into - the performance state table: 1 to 10 on the A18 Pro, 1 to 13 on the M5. The - interval record before a report (tag ``0x19``) gives its firmware timestamp. + the performance state table: 1 to 10 on the A18 Pro and T6041, 1 to 13 on + the M5. The interval record before a report (tag ``0x19``) gives its + firmware timestamp. A report that names state 0 or a state beyond the table is not used. While the cores are gated the GPU is off and ``pstate`` reads a valid 0; power-up starts a new epoch, ``stale`` until the next report. * ``achieved_frequency_hz``: the frequency of that state while ``pstate_status`` is ``valid``, 0 for state 0. The M5 takes it from its - board's table. The A18 Pro takes the device tree operating point that the - state's entry of its performance table A names: its records do not name the - table, but at its top state a sustained FP32 FMA load completes faster than - table B's frequency there allows. + board's table. The A18 Pro and T6041 take the device tree operating point + that the state's entry of their performance table A names: their records do + not name the table; on the A18 Pro, at the top state a sustained FP32 FMA + load completes faster than table B's frequency there allows, while on T6041 + both tables map state 10 to OPP 15 (1578 MHz) and only differ on mid-states + (states 5..9 on 32-core J616C, 6..9 on 40-core), so those mid-state + frequencies are nominal (taken from table A) until measured by a mid-state + ALU benchmark. * ``busy_ns``: the utilisation records carry their own timestamps (words 1 and - 2, 24 MHz ticks), one every 8 ms on the M5 and every 16 ms on the A18 Pro, so - each record closes a window of known length, which is credited at the - record's device utilisation. A record that follows the previous one by more - than two periods, or whose timestamp went back, only starts a new window: - time the GPU spent gated is never credited, and a load sparser than one - period reads low. The total keeps counting across power epochs. + 2, 24 MHz ticks), one every 8 ms on the M5 and T6041 and every 16 ms on the + A18 Pro, so each record closes a window of known length, which is credited at + the record's device utilisation. A record that follows the previous one by + more than two periods, or whose timestamp went back, only starts a new + window: time the GPU spent gated is never credited, and a load sparser than + one period reads low. The total keeps counting across power epochs. The driver asks for full performance while work is in flight, which the firmware takes as a floor for its state. An A18 Pro at work therefore normally @@ -174,8 +181,10 @@ fdinfo's per-client ``drm-engine-*`` counters. Deferred shared power telemetry ------------------------------ -Current pstate and requested/achieved frequency remain unsupported on G16S -(V25G83); V26A428 reports its state in the statistics ring, see above. The +Current pstate and requested/achieved frequency remain unsupported on T6040 +(M4 Pro, V25G83), which is left on ``Protocol::NONE`` because it has not been +measured yet; V26A428 and T6041 (25G83) report their state in the statistics +ring, see above. The shared-power snapshot ABI is not sufficiently specified to implement a read-only reader, which G16S would need, and which would also name the A18 Pro's table directly. For **each** of G16S and G17P, it still needs: diff --git a/drivers/gpu/drm/asahi/g17/channel.rs b/drivers/gpu/drm/asahi/g17/channel.rs index 00aff91fa0a1c2..05c2f7ecf51c88 100644 --- a/drivers/gpu/drm/asahi/g17/channel.rs +++ b/drivers/gpu/drm/asahi/g17/channel.rs @@ -99,12 +99,18 @@ pub(crate) struct Rings { } impl Rings { - /// `m5`: the firmware runs the M5 protocol ([`super::stats::protocol`]). - pub(crate) fn new(graph: super::fw::variant::InitGraph, m5: bool) -> Result { + /// `protocol`: the records the firmware sends beyond utilisation + /// ([`super::telemetry::Protocol`]). + /// `max_pstate`: highest valid performance state index for `0x1b` reports. + pub(crate) fn new( + graph: super::fw::variant::InitGraph, + protocol: super::telemetry::Protocol, + max_pstate: u32, + ) -> Result { Ok(Self { quarantined: [[false; 2]; 2], reports: super::reports::Reports::new()?, - telemetry: super::telemetry::Telemetry::new(super::stats::protocol(graph, m5)), + telemetry: super::telemetry::Telemetry::new(protocol, max_pstate), max_age_ns: super::stats::max_age_ns(graph), suspended: false, discard_statistics: [false; 2], diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 59e9a5382cf8c0..3c40fba4aa8c00 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -109,6 +109,9 @@ pub(crate) struct Variant { /// an M4 Pro crash on a recycled work state; extending this needs a create/destroy-heavy /// queue test on that hardware. pub(crate) objects_after_release: bool, + /// What the firmware reports in its statistics ring beyond utilisation + /// ([`crate::g17::telemetry::Protocol`]). + pub(crate) telemetry_protocol: crate::g17::telemetry::Protocol, } /// A firmware build a SoC supports, identified by its loaded TEXT. @@ -164,6 +167,7 @@ pub(crate) const V26A428: Variant = Variant { registration_power_hold: true, render_id_at_create: true, objects_after_release: true, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_16MS, }; /// The M4 Pro firmware (25G83, `mBoot-18000.161.10`). @@ -205,6 +209,7 @@ pub(crate) const V25G83: Variant = Variant { registration_power_hold: true, render_id_at_create: false, objects_after_release: false, + telemetry_protocol: crate::g17::telemetry::Protocol::NONE, }; /// The 26A428 firmware of the M5 GPUs, which runs the M5 protocol (the M5 graph, queues and @@ -217,6 +222,7 @@ pub(crate) const V26A428_M5: Variant = Variant { registration_power_hold: false, render_id_at_create: false, objects_after_release: false, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, ..V26A428 }; diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 5eb67ede40227b..d73d9cc68b5c97 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1202,6 +1202,9 @@ struct Shared { clusters: u32, active_cores: u32, variant: &'static fw::Variant, + /// Highest valid performance state index for 0x1b telemetry reports, derived from the + /// state-frequency table. + max_pstate: u32, /// Layout of compute queues' operand-state buffers for this GPU's cores. operand_state: &'static fw::compute::OperandState, /// The M5 board ([`Config::m5`]) of an M5 profile. @@ -1764,6 +1767,10 @@ impl Gpu { }, GFP_KERNEL, )?; + let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; + let max_pstate = frequencies + .as_ref() + .map_or(0, stats::StateFrequencies::max_pstate); let shared = Arc::pin_init( pin_init!(Shared { drm <- new_mutex!(Some(dev.into()), "g17::Shared::drm"), @@ -1771,6 +1778,7 @@ impl Gpu { clusters: id.num_clusters, active_cores, variant, + max_pstate, operand_state: &cfg.core_layout.operand_state, m5_board: cfg.m5.filter(|_| m5), deflake: cfg.core_layout.deflake, @@ -1839,7 +1847,6 @@ impl Gpu { directory.read_only_file(c"hardware_data", reports::HardwareDataView(shared.clone())), GFP_KERNEL, )?; - let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; let stats = Arc::new( crate::stats::StatsSnapshot { g17_reader: Some(stats::Reader(shared.clone(), frequencies)), @@ -1954,18 +1961,21 @@ impl Gpu { } /// The frequency of each performance state the firmware reports - /// ([`stats::reports_pstate`]): M5's from its board, the A18 Pro's from the operating - /// points its performance table A names. The A18 Pro's records do not name the table, but - /// at its top state, where it runs while work is in flight, a sustained FP32 FMA load - /// completes faster than table B's frequency there allows. `None` where the firmware - /// reports no state. + /// ([`stats::reports_pstate`]): M5's from its board, the A18 Pro's and T6041's from the + /// operating points their performance table A names. Their records do not name the table; + /// on the A18 Pro, at the top state where the GPU runs while work is in flight, a sustained + /// FP32 FMA load completes faster than table B's frequency there allows. On T6041 both + /// tables map state 10 to OPP 15 (1578 MHz) and only differ on states 5..=9 on the + /// J616C (32-core; 40-core differs on 6..=9), so those mid-state frequencies are nominal + /// (taken from table A) until measured by a mid-state ALU benchmark. `None` where the + /// firmware reports no state. fn state_frequencies( dev: &AsahiDrmDevice, cfg: &'static Config, variant: &fw::variant::Variant, clusters: u32, ) -> Result> { - if !stats::reports_pstate(variant.graph, variant.m5_commands) { + if !stats::reports_pstate(variant.telemetry_protocol) { return Ok(None); } if let Some(board) = cfg.m5 { @@ -2090,7 +2100,11 @@ impl Gpu { shared.feed.clone(), )?, seen_submissions: 0, - rings: channel::Rings::new(shared.variant.graph, shared.variant.m5_commands)?, + rings: channel::Rings::new( + shared.variant.graph, + shared.variant.telemetry_protocol, + shared.max_pstate, + )?, recovery: recovery::State::new(), effort: power::Effort::new(), hold: power::Hold::new(), @@ -2294,7 +2308,11 @@ impl Gpu { shared.feed.clone(), )?, seen_submissions: 0, - rings: channel::Rings::new(shared.variant.graph, shared.variant.m5_commands)?, + rings: channel::Rings::new( + shared.variant.graph, + shared.variant.telemetry_protocol, + shared.max_pstate, + )?, recovery: recovery::State::new(), effort: power::Effort::new(), hold: power::Hold::new(), diff --git a/drivers/gpu/drm/asahi/g17/stats.rs b/drivers/gpu/drm/asahi/g17/stats.rs index 5484c68fa62f77..958d6815f236f4 100644 --- a/drivers/gpu/drm/asahi/g17/stats.rs +++ b/drivers/gpu/drm/asahi/g17/stats.rs @@ -30,6 +30,11 @@ impl StateFrequencies { Some(Self { mhz: table, states }) } + /// Highest valid performance state index in this table (`0` when empty or off-only). + pub(crate) fn max_pstate(&self) -> u32 { + self.states.saturating_sub(1) as u32 + } + /// The frequency of `pstate` in Hz; `None` beyond the table or where it is unknown (0). fn hz(&self, pstate: u32) -> Option { let mhz = *self.mhz[..self.states].get(pstate as usize)?; @@ -72,10 +77,10 @@ impl Reader { } fn read_firmware(&self) -> Readout { - let m5 = self.0.variant.m5_commands; + let protocol = self.0.variant.telemetry_protocol; let mut state = self.0.state.lock(); let Some(firmware) = state.as_deref_mut() else { - return qualify(self.0.variant.graph, m5, Readout::default()); + return qualify(protocol, Readout::default()); }; if self.0.crashed.load(Ordering::Acquire) || firmware.recovery.pending() { firmware.rings.invalidate_statistics(); @@ -94,11 +99,7 @@ impl Reader { // export samples across an observed boundary. firmware.observe_statistics_power(); } - qualify( - self.0.variant.graph, - m5, - firmware.rings.read_statistics(super::now_ns()), - ) + qualify(protocol, firmware.rings.read_statistics(super::now_ns())) } pub(crate) fn suspend(&self, suspended: bool) { @@ -118,33 +119,23 @@ pub(super) const fn max_age_ns(graph: InitGraph) -> u64 { } } -/// The records `graph`'s firmware sends beyond utilisation; `m5`: it runs the M5 protocol, -/// with M5's performance states. -pub(super) const fn protocol(graph: InitGraph, m5: bool) -> super::telemetry::Protocol { - match graph { - InitGraph::G17P if m5 => super::telemetry::Protocol::M5, - InitGraph::G17P => super::telemetry::Protocol::A18_PRO, - InitGraph::V25G83 => super::telemetry::Protocol::NONE, - } -} - /// Whether the firmware reports its performance state. V25G83 and V26A428 accept -/// the logical pstate record (tag 0x10) but never emit it. V26A428, on the A18 Pro -/// as on M5, reports the state in its own records instead (tags 0x19 and 0x1b, -/// [`protocol`]); V25G83 sends no record carrying it, so it is unsupported there. -/// A firmware that reports it reads valid or stale. -pub(super) const fn reports_pstate(graph: InitGraph, m5: bool) -> bool { - protocol(graph, m5).reports_pstate() +/// the logical pstate record (tag 0x10) but never emit it. V26A428 (A18 Pro and +/// M5) and T6041's 25G83 report the state in tags 0x19 and 0x1b instead +/// (`Variant::telemetry_protocol`); T6040's 25G83 is left on `Protocol::NONE` +/// because it has not been measured yet, so it is unsupported there. A firmware +/// that reports it reads valid or stale. +pub(super) const fn reports_pstate(protocol: super::telemetry::Protocol) -> bool { + protocol.reports_pstate() } /// Apply the firmware's static capabilities to a decoded readout. The decoder /// and the debugfs diagnostic still keep any tag 0x10 that does arrive. pub(super) fn qualify( - graph: InitGraph, - m5: bool, + protocol: super::telemetry::Protocol, mut view: super::telemetry::Readout, ) -> super::telemetry::Readout { - if !reports_pstate(graph, m5) { + if !reports_pstate(protocol) { view.pstate_status = super::telemetry::UNSUPPORTED; view.pstate = 0; view.pstate_host_ns = 0; diff --git a/drivers/gpu/drm/asahi/g17/telemetry.rs b/drivers/gpu/drm/asahi/g17/telemetry.rs index 23f66a7fcced0b..9e61dcd6b2e49e 100644 --- a/drivers/gpu/drm/asahi/g17/telemetry.rs +++ b/drivers/gpu/drm/asahi/g17/telemetry.rs @@ -3,9 +3,11 @@ //! Qualified V25G83/V26A428 statistics, decoded from complete copied records. //! No record of these firmwares measures power or temperature. //! -//! The 26A428 firmware (the A18 Pro's, and the M5's) reports the performance state the -//! GPU runs at (tags 0x19 and 0x1b), and its utilisation records carry their own -//! timestamps, from which busy time is integrated ([`Protocol`]). 25G83 sends neither. +//! The 26A428 firmware (the A18 Pro's, and the M5's) and T6041's 25G83 +//! firmware report the performance state the GPU runs at (tags 0x19 and 0x1b), +//! and their utilisation records carry their own timestamps, from which busy +//! time is integrated ([`Protocol`]). T6040's 25G83 is left on `Protocol::NONE` +//! because it has not been measured yet. //! All state is protected by the device mutex. pub(super) const UNAVAILABLE: u32 = 0; @@ -50,34 +52,34 @@ const TIMER_HZ: u64 = 24_000_000; /// What a firmware reports beyond utilisation. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Protocol { - /// Highest performance state its state records (tags 0x19 and 0x1b) name; zero where it - /// sends none. State 0 is off. - pub(crate) max_pstate: u32, + /// Emits performance state reports in tags 0x19 (interval) and 0x1b (state). + pub(crate) reports_pstate: bool, /// Interval of its utilisation record (tag 0x13), in timer ticks, whose timestamps busy /// time is integrated from; zero where it is not integrated. pub(crate) util_period_ticks: u64, } impl Protocol { - /// 25G83: utilisation only. + /// Utilisation only: no 0x19/0x1b performance state reports and no busy-time integration. pub(crate) const NONE: Self = Self { - max_pstate: 0, + reports_pstate: false, util_period_ticks: 0, }; - /// M5: the device tree's operating points 1 to 13, utilisation every 8 ms. - pub(crate) const M5: Self = Self { - max_pstate: 13, + /// Performance state reports (tags 0x19/0x1b) and 8 ms timestamped utilisation records + /// (192000 ticks at 24 MHz), as emitted by V26A428 M5 and T6041 25G83. + pub(crate) const PSTATE_8MS: Self = Self { + reports_pstate: true, util_period_ticks: 192_000, }; - /// A18 Pro: states 1 to 10 of its eleven-state performance tables, utilisation every - /// 16 ms. - pub(crate) const A18_PRO: Self = Self { - max_pstate: 10, + /// Performance state reports (tags 0x19/0x1b) and 16 ms timestamped utilisation records + /// (384000 ticks at 24 MHz), as emitted by V26A428 on A18 Pro. + pub(crate) const PSTATE_16MS: Self = Self { + reports_pstate: true, util_period_ticks: 384_000, }; pub(crate) const fn reports_pstate(self) -> bool { - self.max_pstate != 0 + self.reports_pstate } fn integrates_busy(self) -> bool { @@ -109,6 +111,9 @@ pub(super) struct Telemetry { gated: bool, /// The records decoded beyond utilisation. protocol: Protocol, + /// Highest valid performance state index for tags 0x19/0x1b, derived from the device's + /// state-frequency table; zero fails closed and rejects all 0x1b states. + max_pstate: u32, /// Timestamp of the latest utilisation record in this epoch: the start of the window the /// next one closes. busy_ts: Option, @@ -118,10 +123,12 @@ pub(super) struct Telemetry { } impl Telemetry { - /// Decoder for a firmware that also sends `protocol`'s records. - pub(super) fn new(protocol: Protocol) -> Self { + /// Decoder for a firmware that also sends `protocol`'s records, bounding 0x1b performance + /// state indices to `1..=max_pstate`. + pub(super) fn new(protocol: Protocol, max_pstate: u32) -> Self { Self { protocol, + max_pstate, ..Self::default() } } @@ -235,16 +242,16 @@ impl Telemetry { self.view.pstate_status = if words[6] <= 10 { VALID } else { UNAVAILABLE }; self.view.pstate = words[6]; } - // 26A428: the interval [words 3-4, words 1-2] that just ended. Its end - // timestamps the state report that follows it. + // The interval [words 3-4, words 1-2] that just ended. Its end timestamps the + // state report that follows it. 0x19 if self.protocol.reports_pstate() => { self.pstate_interval_end = Some(u64::from(words[1]) | (u64::from(words[2]) << 32)); } - // 26A428: the performance state now in effect, in words 1 and 3. A report whose - // two words differ is not used. + // The performance state now in effect, in words 1 and 3. A report whose two + // words differ is not used. 0x1b if self.protocol.reports_pstate() => { let pstate = words[1]; - if pstate != words[3] || pstate == 0 || pstate > self.protocol.max_pstate { + if pstate != words[3] || pstate == 0 || pstate > self.max_pstate { self.view.pstate_status = UNAVAILABLE; return; } @@ -533,7 +540,7 @@ mod tests { #[test] fn m5_state_reports_give_the_pstate() { - let mut stats = Telemetry::new(Protocol::M5); + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); stats.record(&M5_INTERVAL, 100, AGE); assert_eq!(stats.read(100, AGE).pstate_status, UNAVAILABLE); stats.record(&M5_STATE, 101, AGE); @@ -564,7 +571,7 @@ mod tests { #[test] fn m5_busy_time_integrates_utilisation_windows() { - let mut stats = Telemetry::new(Protocol::M5); + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); assert_eq!( (stats.read(0, AGE).busy_status, stats.read(0, AGE).busy_ns), (VALID, 0) @@ -604,7 +611,7 @@ mod tests { #[test] fn a18_pro_state_reports_give_the_pstate() { - let mut stats = Telemetry::new(Protocol::A18_PRO); + let mut stats = Telemetry::new(Protocol::PSTATE_16MS, 10); let mut interval = M5_INTERVAL; let mut state = M5_STATE; (state[1], state[3]) = (10, 10); @@ -633,7 +640,7 @@ mod tests { #[test] fn a18_pro_busy_time_integrates_16_ms_windows() { - let mut stats = Telemetry::new(Protocol::A18_PRO); + let mut stats = Telemetry::new(Protocol::PSTATE_16MS, 10); let mut words = M5_U[0]; stats.record(&words, 100, AGE); // One full 16 ms window at 100%, then one at 25%. @@ -653,6 +660,79 @@ mod tests { assert_eq!(stats.read(104, AGE).busy_ns, 28_000_000); } + #[test] + fn t6041_state_reports_give_the_pstate() { + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 10); + let mut interval = M5_INTERVAL; + let mut state = M5_STATE; + (state[1], state[3]) = (10, 10); + stats.record(&interval, 100, AGE); + stats.record(&state, 101, AGE); + let view = stats.read(101, AGE); + assert_eq!((view.pstate_status, view.pstate), (VALID, 10)); + assert_eq!(view.pstate_timestamp, 0x59_3c04_2f8f); + // Mismatched words, off, or beyond state 10 (even though M5 shares PSTATE_8MS with + // max_pstate 13): not a state. + for (a, b) in [(1, 10), (0, 0), (11, 11), (13, 13)] { + (state[1], state[3]) = (a, b); + stats.record(&state, 102, AGE); + assert_eq!(stats.read(102, AGE).pstate_status, UNAVAILABLE); + } + // Tag 0x10 is not this firmware's state report. + interval[1] += 1; + stats.record(&interval, 103, AGE); + stats.record(&P1, 103, AGE); + assert_eq!(stats.read(103, AGE).pstate_status, UNAVAILABLE); + (state[1], state[3]) = (1, 1); + stats.record(&state, 104, AGE); + assert_eq!(stats.read(104, AGE).pstate, 1); + // Gated cores are off. + stats.gate(); + let view = stats.read(105, AGE); + assert_eq!((view.pstate_status, view.pstate), (VALID, 0)); + stats.invalidate(); + assert_eq!(stats.read(106, AGE).pstate_status, STALE); + } + + #[test] + fn t6041_busy_time_integrates_8_ms_windows() { + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 10); + let mut words = M5_U[0]; + stats.record(&words, 100, AGE); + // One full 8 ms window at 100%, then one at 50%. + words[1] += 192_000; + stats.record(&words, 101, AGE); + assert_eq!(stats.read(101, AGE).busy_ns, 8_000_000); + words[1] += 192_000; + words[6] = 50; + stats.record(&words, 102, AGE); + assert_eq!(stats.read(102, AGE).busy_ns, 12_000_000); + // Up to two periods (16 ms) is one window; longer is a gap. + words[1] += 384_000; + stats.record(&words, 103, AGE); + assert_eq!(stats.read(103, AGE).busy_ns, 20_000_000); + words[1] += 384_001; + stats.record(&words, 104, AGE); + assert_eq!(stats.read(104, AGE).busy_ns, 20_000_000); + } + + #[test] + fn zero_max_pstate_fails_closed() { + for protocol in [Protocol::PSTATE_8MS, Protocol::PSTATE_16MS] { + let mut stats = Telemetry::new(protocol, 0); + stats.record(&M5_INTERVAL, 100, AGE); + for pstate in [0, 1, 10, 13] { + let mut words = M5_STATE; + (words[1], words[3]) = (pstate, pstate); + stats.record(&words, 101, AGE); + assert_eq!(stats.read(101, AGE).pstate_status, UNAVAILABLE); + } + // Tag 0x10 is still ignored when the protocol reports 0x19/0x1b. + stats.record(&P1, 102, AGE); + assert_eq!(stats.read(102, AGE).pstate_status, UNAVAILABLE); + } + } + #[test] fn other_firmwares_ignore_the_m5_records() { let mut stats = Telemetry::default(); diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 30370e792e1695..80586419db5ad6 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -204,8 +204,11 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { }, ], // Four clusters: the tiler segment values of 25F84 on this machine. + // T6041's 25G83 firmware emits pstate reports (tags 0x19/0x1b) and 8 ms + // timestamped utilisation records (tag 0x13). variant: &fw::variant::Variant { ta_mode_1: true, + telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, ..fw::variant::V25G83 }, config: None, diff --git a/drivers/gpu/drm/asahi/stats.rs b/drivers/gpu/drm/asahi/stats.rs index e0f68f14369803..1c2a16846586b9 100644 --- a/drivers/gpu/drm/asahi/stats.rs +++ b/drivers/gpu/drm/asahi/stats.rs @@ -85,7 +85,8 @@ impl StatsSnapshot { } /// The frequency the GPU runs at now, if the firmware reports it, and its highest, in - /// Hz, for fdinfo (`drm-curfreq-*`, `drm-maxfreq-*`): V26A428 (A18 Pro and M5) only. + /// Hz, for fdinfo (`drm-curfreq-*`, `drm-maxfreq-*`): V26A428 (A18 Pro and M5) and + /// T6041 (25G83). pub(crate) fn engine_frequency(&self) -> Option<(Option, u64)> { self.g17_reader.as_ref()?.frequency() } diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index fb0737c2693bd3..9cf5eba61c55e8 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -94,8 +94,10 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha "util_device_percent unsupported\n"); } /* - * unsupported comes from the firmware match data (g17::stats): V25G83 - * never emits a pstate record, so it is not a transient state. + * unsupported comes from the firmware match data (g17::stats): builds + * without a pstate telemetry protocol (such as T6040 25G83, left on + * Protocol::NONE pending measurement) have no qualified pstate support, + * so it is not a transient state. * unavailable keeps meaning "no qualified sample yet". */ n += sysfs_emit_at(buf, n, "pstate_status %s\n", @@ -107,8 +109,9 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha /* No host frequency request, measured power or temperature. */ n += sysfs_emit_at(buf, n, "requested_frequency_hz unsupported\n"); /* - * V26A428 reports the state the GPU runs at: its frequency is the - * achieved one. State 0 is off (gated cores) and runs at 0 Hz. + * Firmwares with a pstate protocol (V26A428, T6041 25G83) report + * the state the GPU runs at: its frequency is the achieved one. State 0 + * is off (gated cores) and runs at 0 Hz. */ if (snap.pstate_status == 1 && (snap.achieved_frequency_hz || !snap.pstate)) n += sysfs_emit_at(buf, n, "achieved_frequency_hz %llu\n", diff --git a/tools/asahi/g17-telemetry-integration-tests.py b/tools/asahi/g17-telemetry-integration-tests.py index 10bd7cb7d863e7..de4d614ed96006 100755 --- a/tools/asahi/g17-telemetry-integration-tests.py +++ b/tools/asahi/g17-telemetry-integration-tests.py @@ -146,18 +146,30 @@ def item(source, signature): impl State { fn lock(&self)->std::sync::MutexGuard<'_,Option>> { self.0.lock().unwrap() } } - struct Variant { graph:fw::variant::InitGraph, m5_commands:bool } + struct Variant { graph:fw::variant::InitGraph, telemetry_protocol:telemetry::Protocol } struct Shared { state:State, dev:crate::device::Device, variant:Variant, crashed:std::sync::atomic::AtomicBool } mod reports; ''' RUST_TESTS = r''' - fn reader(graph:fw::variant::InitGraph)->stats::Reader { + fn default_protocol(graph:fw::variant::InitGraph)->telemetry::Protocol { + match graph { + fw::variant::InitGraph::G17P=>telemetry::Protocol::PSTATE_16MS, + fw::variant::InitGraph::V25G83=>telemetry::Protocol::NONE, + } + } + + fn reader_with(graph:fw::variant::InitGraph,protocol:telemetry::Protocol,frequencies:Option)->stats::Reader { + let max_pstate=frequencies.as_ref().map_or(0,stats::StateFrequencies::max_pstate); stats::Reader(std::sync::Arc::new(Shared { state:State(std::sync::Mutex::new(Some(Box::new(Firmware { - rings:channel::Rings::new(graph,false).unwrap(), + rings:channel::Rings::new(graph,protocol,max_pstate).unwrap(), init:initdata::InitData::new(),powered:true,epoch:0,recovery:Recovery(false), - })))),dev:crate::device::Device,variant:Variant { graph, m5_commands:false },crashed:false.into(), - }),None) + })))),dev:crate::device::Device,variant:Variant { graph, telemetry_protocol:protocol },crashed:false.into(), + }),frequencies) + } + + fn reader(graph:fw::variant::InitGraph)->stats::Reader { + reader_with(graph,default_protocol(graph),None) } #[test] @@ -254,14 +266,14 @@ def item(source, signature): fn captured_histograms_are_preserved_without_inventing_pstate() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; - for graph in [InitGraph::V25G83,InitGraph::G17P] { + for (graph,protocol,max_pstate) in [(InitGraph::V25G83,telemetry::Protocol::NONE,0),(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,10),(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10)] { let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,protocol,max_pstate).unwrap(); for words in [HIST_IDLE,HIST_ACTIVE,HIST_OTHER,TRANSITION] { init.push(Secondary,words); rings.drain_statistics(&dev,&init,Secondary); - // 26A428 integrates busy time from its utilisation records; none arrived. - let busy=match graph { InitGraph::G17P=>telemetry::VALID, _=>telemetry::UNSUPPORTED }; + // Protocols with a utilisation period integrate busy time; none arrived. + let busy=if protocol.util_period_ticks != 0 { telemetry::VALID } else { telemetry::UNSUPPORTED }; assert_eq!(rings.read_statistics(1),telemetry::Readout { busy_status:busy,..Default::default() }); assert!(report(&rings).contains(&format!("words={:08x?}",words))); } @@ -274,7 +286,7 @@ def item(source, signature): let dev=crate::device::Device; for start in [0,5,7] { let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); for &role in &[Primary,Secondary] { for cursor in &init.cursors[role as usize] { cursor.store(start,Ordering::Relaxed); } for words in [HIST_OTHER,HIST_ACTIVE,TRANSITION] { init.push(role,words); } @@ -298,8 +310,8 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - // The decoder's tag 0x10 path: only a firmware without 26A428's state records decodes it. - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + // The decoder's tag 0x10 path: only a firmware without 0x19/0x1b state records decodes it. + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let util=[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]; let pstate=[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]; rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,1); @@ -329,34 +341,96 @@ def item(source, signature): fn v25g83_reports_pstate_unsupported_and_keeps_utilisation() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; - // 26A428 reports its state on the A18 Pro and on M5; 25G83 never does. - assert!(!stats::reports_pstate(InitGraph::V25G83,false)); - assert!(stats::reports_pstate(InitGraph::G17P,false)); - assert!(stats::reports_pstate(InitGraph::G17P,true)); + // Protocols with reports_pstate emit tags 0x19/0x1b; Protocol::NONE does not. + assert!(!stats::reports_pstate(telemetry::Protocol::NONE)); + assert!(stats::reports_pstate(telemetry::Protocol::PSTATE_8MS)); + assert!(stats::reports_pstate(telemetry::Protocol::PSTATE_16MS)); let graph=InitGraph::V25G83; - let empty=stats::qualify(graph,false,telemetry::Readout::default()); + let empty=stats::qualify(telemetry::Protocol::NONE,telemetry::Readout::default()); assert_eq!((empty.util_status,empty.pstate_status),(telemetry::UNAVAILABLE,telemetry::UNSUPPORTED)); let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,telemetry::Protocol::NONE,0).unwrap(); init.push(Primary,[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]); // Even a decodable tag 0x10 does not override the firmware's match data. init.push(Primary,[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); rings.drain_statistics(&dev,&init,Primary); assert_eq!(rings.read_statistics(1).pstate_status,telemetry::VALID); - let view=stats::qualify(graph,false,rings.read_statistics(1)); + let view=stats::qualify(telemetry::Protocol::NONE,rings.read_statistics(1)); assert_eq!((view.util_status,view.device,view.pstate_status,view.pstate,view.pstate_timestamp), (telemetry::VALID,97,telemetry::UNSUPPORTED,0,0)); rings.invalidate_statistics(); - let view=stats::qualify(graph,false,rings.read_statistics(1)); + let view=stats::qualify(telemetry::Protocol::NONE,rings.read_statistics(1)); assert_eq!((view.util_status,view.pstate_status),(telemetry::STALE,telemetry::UNSUPPORTED)); } + #[test] + fn t6041_reports_its_state_and_busy_time_through_the_reader() { + use {fw::variant::InitGraph,Role::*}; + // J616C OPP frequencies mapped by PERF.states_a (states 0..=10). + let mhz=[0,338,618,796,924,1056,1182,1312,1380,1470,1578]; + let freqs=stats::StateFrequencies::new(mhz.into_iter()).unwrap(); + assert_eq!(freqs.max_pstate(),10); + let reader=reader_with(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,Some(freqs)); + let push=|words|reader.0.state.lock().as_ref().unwrap().init.push(Primary,words); + // Safe fallback when no 0x1b arrives (e.g. a firmware that omits it): pstate unavailable, util still works. + push([0x13,100_000,0,20,40,0,50,0,0,0,0,0,0,0,0,0,0,0]); + let view=reader.read(); + assert_eq!((view.util_status,view.device,view.pstate_status,view.busy_status,view.busy_ns), + (telemetry::VALID,50,telemetry::UNAVAILABLE,telemetry::VALID,0)); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + // 8 ms (192_000 ticks) at 50% -> 4 ms busy; 16 ms (384_000 ticks) at 100% -> +16 ms; >384_000 ticks gap ignored. + push([0x13,100_000+192_000,0,20,40,0,50,0,0,0,0,0,0,0,0,0,0,0]); + push([0x13,100_000+192_000+384_000,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); + push([0x13,100_000+192_000+384_000+384_001,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().busy_ns,20_000_000); + // Tag 0x10 is ignored when Protocol::PSTATE_8MS is active. + push([0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().pstate_status,telemetry::UNAVAILABLE); + // Tag 0x19 + 0x1b report state 10 -> 1578 MHz. + push([0x19,0x2000,0x40,0x1000,0x40,0,0,0,0,0,0,0,0,0,0,0,0,0]); + push([0x1b,10,0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + let view=reader.read(); + assert_eq!((view.pstate_status,view.pstate,view.pstate_timestamp,view.achieved_frequency_hz), + (telemetry::VALID,10,0x40_0000_2000,1_578_000_000)); + assert_eq!(reader.frequency(),Some((Some(1_578_000_000),1_578_000_000))); + // Mismatched words[1] != words[3], state 0, or state beyond derived max_pstate (10) -> UNAVAILABLE. + for (a,b) in [(4,10),(0,0),(11,11),(13,13)] { + push([0x1b,a,0,b,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().pstate_status,telemetry::UNAVAILABLE); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + } + // Recover to valid state 1 -> 338 MHz. + push([0x1b,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(reader.read().achieved_frequency_hz,338_000_000); + // Gated cores -> state 0, 0 Hz. + reader.0.state.lock().as_mut().unwrap().powered=false; + let view=reader.read(); + assert_eq!((view.pstate_status,view.pstate,view.achieved_frequency_hz),(telemetry::VALID,0,0)); + assert_eq!(reader.frequency(),Some((Some(0),1_578_000_000))); + // Power-up -> STALE until next report. + reader.0.state.lock().as_mut().unwrap().powered=true; + assert_eq!(reader.read().pstate_status,telemetry::STALE); + assert_eq!(reader.frequency(),Some((None,1_578_000_000))); + // Same Protocol::PSTATE_8MS with a 14-state table (M5) derives max_pstate 13; without a table it fails closed. + let m5_mhz=[0,338,492,618,740,860,980,1100,1200,1300,1400,1470,1540,1620]; + let m5_freqs=stats::StateFrequencies::new(m5_mhz.into_iter()).unwrap(); + assert_eq!(m5_freqs.max_pstate(),13); + let m5_reader=reader_with(InitGraph::G17P,telemetry::Protocol::PSTATE_8MS,Some(m5_freqs)); + m5_reader.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,13,0,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(m5_reader.read().achieved_frequency_hz,1_620_000_000); + m5_reader.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,14,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(m5_reader.read().pstate_status,telemetry::UNAVAILABLE); + let closed=reader_with(InitGraph::V25G83,telemetry::Protocol::PSTATE_8MS,None); + closed.0.state.lock().as_ref().unwrap().init.push(Primary,[0x1b,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]); + assert_eq!(closed.read().pstate_status,telemetry::UNAVAILABLE); + } + #[test] fn a18_pro_reports_its_state_through_the_reader() { use {fw::variant::InitGraph,Role::*}; // States 0 to 10; an interval record, then the state in words 1 and 3. let mhz=[0,338,492,618,796,928,1056,1170,1278,1338,1470]; - let reader=stats::Reader(reader(InitGraph::G17P).0,stats::StateFrequencies::new(mhz.into_iter())); + let reader=reader_with(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,stats::StateFrequencies::new(mhz.into_iter())); let push=|words|reader.0.state.lock().as_ref().unwrap().init.push(Secondary,words); // Tag 0x10 is not this firmware's state report. push([0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); @@ -389,7 +463,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let util=[0x13,0,0,8,97,0,97,0,0,0,0,0,0,0,0,0,0,0]; // Three 8 ms records per producer update, one update every 24 ms. for n in 0..3u64 { @@ -409,7 +483,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],false,0); init.push(Secondary,HIST_IDLE); rings.drain_statistics(&dev,&init,Secondary); @@ -429,13 +503,13 @@ def item(source, signature): let graph=InitGraph::G17P; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(graph,false).unwrap(); + let mut rings=Rings::new(graph,telemetry::Protocol::PSTATE_16MS,10).unwrap(); init.push(Secondary,HIST_IDLE); rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,1); init.push(Secondary,HIST_ACTIVE); let shared=std::sync::Arc::new(Shared { state:State(std::sync::Mutex::new(Some(Box::new(Firmware { rings,init:initdata::InitData::new(),powered:true,epoch:0,recovery:Recovery(false), - })))),dev,variant:Variant { graph, m5_commands:false },crashed:false.into() }); + })))),dev,variant:Variant { graph, telemetry_protocol:telemetry::Protocol::PSTATE_16MS },crashed:false.into() }); let view=reports::View(shared.clone()); struct View<'a>(&'a reports::View); impl std::fmt::Display for View<'_> { @@ -453,7 +527,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::G17P,false).unwrap(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_16MS,10).unwrap(); let sample=|ta,render,device|[0x13,0,0,ta,render,0xdeadbeef,device,0,0,0,0,0,0,0,0,0,0,0]; init.push(Primary,sample(25,75,50)); init.push(Secondary,sample(35,85,65)); @@ -477,7 +551,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); let words=[0x13,0,0,25,75,0,50,0,0,0,0,0,0,0,0,0,0,0]; init.push(Primary,words); rings.drain_statistics(&dev,&init,Primary); @@ -506,7 +580,7 @@ def item(source, signature): use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; let init=initdata::InitData::new(); - let mut rings=Rings::new(InitGraph::V25G83,false).unwrap(); + let mut rings=Rings::new(InitGraph::V25G83,telemetry::Protocol::NONE,0).unwrap(); init.push(Primary,[0x10,0x1000,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0]); init.push(Secondary,[0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); rings.drain_statistics(&dev,&init,Primary); @@ -758,7 +832,7 @@ def main(): assert 'for &role in firmware.roles()' in stats_rs stats_rs = stats_rs.replace('for &role in firmware.roles()', 'for &role in &[]', 1) policy = '\n'.join(item(stats_rs, signature) for signature in - ['pub(super) const fn max_age_ns', 'pub(super) const fn protocol(', 'pub(super) const fn reports_pstate', + ['pub(super) const fn max_age_ns', 'pub(super) const fn reports_pstate', 'pub(super) fn qualify(']) # The rings take the family's statistics tags and control power rule from # InitData; build those production methods into the fixture's InitData. From 6fb60db5532ed20faee630cce67a782ccb597ab2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 19:14:39 -0500 Subject: [PATCH 0483/1514] wifi: apple: centauri: t6050: harden keep-alive sleep fallback and PME gating Harden the T6050 N1 keep-alive deep-sleep path on associated disconnects, partial keep-alive fallback unwinds, post-quiesce PCI saved state, and D3hot PME gating: - Drain in-flight data_tx_busy[] completions during wifi_disconnect(), and skip keep-alive in favor of the existing warm-reset teardown when cfg80211_leave_all() just disconnected inside wiphy_suspend() (centauri_t6050_wifi_pm_disconnected()). With WoWLAN off (the default), sleeps while associated now take the warm-reset path; keep-alive applies only to WoWLAN-armed or unassociated sleeps. - Unwind partial keep-alive ACIPC host-sleep cleanly before falling back to teardown: centauri_t6050_suspend() wakes Control and Alpha and logs any unwind failure, marking Wi-Fi failed with centauri_t6050_wifi_mark_failed() and scheduling recovery with apple_centauri_sleep_recovery_needed() (also covering aborted suspends where resume/rewake may not run) so centauri_t6050_quiesce() does not issue ACIPC commands against sleeping firmware; centauri_t6050_wifi_suspend() checks alpha_resume_locked() similarly; and cen_quiesce() wakes Beta ACIPC (clearing running if wake fails) before hci_unregister_dev(). - Refresh pci_save_state() for fn 1/2 in centauri_t6050_domain_fence() only when centauri_t6050_stop_dma() succeeded for that function, and clear state_saved otherwise (or if pci_save_state() fails, handing suspend_noirq state save and power-state selection back to the PCI core). Because cen_suspend() runs before centauri_t6050_suspend() and saves fn 2 PCI config while Bus Master is enabled in keep-alive mode, an aborted suspend after a Control fallback would otherwise restore Bus Master and the pre-quiesce header onto a quiesced function whose DMA arena was already freed, while calling pci_save_state() on a gone or unreadable function would snapshot 0xffff. - Gate PCI_PM_CTRL_PME_ENABLE in D3hot on actual wake arming (centauri_t6050_wifi_wowlan_armed() for fn 0/1, device_may_wakeup() && running for fn 2), update the stale D3hot PME_En overview comment, and add missing (__force u16) casts for PCI_D3hot and PCI_D0 in btcentauri_t6050.c. Because btcentauri_t6050 does not call device_init_wakeup() at probe, Bluetooth PME is intentionally off by default and follows sysfs wakeup policy. Extend tools/asahi/centauri-{wifi-pm,bt-arena,recovery}-tests.py and centauri-physical-recovery-tests.c to cover disconnect TX drain, PM disconnect/WoWLAN/mark-failed helpers, Beta fallback ACIPC unwind, and post-fence fn 1/2 state_saved refresh/unreadable-function clearing with negative controls. Signed-off-by: Diljit Singh --- drivers/bluetooth/btcentauri_t6050.c | 24 +++- .../apple/centauri/t6050/centauri_pci.c | 76 ++++++++++--- .../apple/centauri/t6050/centauri_t6050.h | 18 +++ .../apple/centauri/t6050/centauri_wifi.c | 103 ++++++++++++++---- tools/asahi/centauri-bt-arena-tests.py | 36 ++++-- .../asahi/centauri-physical-recovery-tests.c | 4 +- tools/asahi/centauri-recovery-tests.py | 55 +++++++++- tools/asahi/centauri-wifi-pm-tests.py | 53 +++++++-- 8 files changed, 301 insertions(+), 68 deletions(-) diff --git a/drivers/bluetooth/btcentauri_t6050.c b/drivers/bluetooth/btcentauri_t6050.c index b436effc29ba81..36fcc4b686c02b 100644 --- a/drivers/bluetooth/btcentauri_t6050.c +++ b/drivers/bluetooth/btcentauri_t6050.c @@ -815,6 +815,8 @@ static int cen_request_irqs(struct cen_bt *bt) return 0; } +static int cen_transport_state(struct cen_bt *bt, bool asleep); + /* * Called with the participant device locked, outside Control's boot_lock. Keep * the transport alive through HCI unregister: its close may send final commands. @@ -824,11 +826,23 @@ static int cen_request_irqs(struct cen_bt *bt) static int cen_quiesce(void *data) { struct cen_bt *bt = data; + int wake_ret = 0; if (bt->host_quiesced) return 0; + if (bt->transport_sleep_sent) { + bt->transport_sleep_sent = false; + wake_ret = cen_transport_state(bt, false); + if (wake_ret) + dev_warn(&bt->pdev->dev, + "Beta ACIPC host wake failed during teardown (%d)\n", + wake_ret); + } mutex_lock(&bt->lock); bt->quiescing = true; + if (wake_ret) + bt->running = false; + WRITE_ONCE(bt->transport_paused, false); mutex_unlock(&bt->lock); if (bt->hci_registered) { hci_unregister_dev(bt->hdev); @@ -1153,9 +1167,11 @@ static int cen_suspend_noirq(struct device *dev) if (!bt->transport_sleep_sent || !pm_suspend_via_firmware() || !pdev->pm_cap) return 0; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl)) { - pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | - PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); + pmctrl &= ~(PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_PME_ENABLE); + pmctrl |= (__force u16)PCI_D3hot; + if (device_may_wakeup(dev) && READ_ONCE(bt->running)) + pmctrl |= PCI_PM_CTRL_PME_ENABLE; + pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl); mdelay(pdev->d3hot_delay); } return 0; @@ -1181,7 +1197,7 @@ static int cen_resume_noirq(struct device *dev) } if (pdev->pm_cap && !pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl) && - (pmctrl & PCI_PM_CTRL_STATE_MASK) != PCI_D0) { + (pmctrl & PCI_PM_CTRL_STATE_MASK) != (__force u16)PCI_D0) { pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl & ~PCI_PM_CTRL_STATE_MASK); mdelay(pdev->d3hot_delay); diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c index 6cda4019d8f0dc..7856b358f9b742 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c @@ -599,10 +599,10 @@ static void centauri_t6050_remove(struct pci_dev *pdev) } /* - * On a healthy firmware sleep, Beta (fn 2), Alpha (fn 1), and Control (fn 0) enter ACIPC - * host-sleep, save PCI config state, enter D3hot with PME_En, and ask pcie-apple to skip - * the wake warm reset so the N1 firmware, Bluetooth, and (when armed) Wi-Fi association - * survive across PERST#. + * On a healthy firmware sleep (WoWLAN-armed or unassociated), Beta (fn 2), Alpha (fn 1), + * and Control (fn 0) enter ACIPC host-sleep, save PCI config state, enter D3hot (with + * PME_En only when wake is armed), and ask pcie-apple to skip the wake warm reset so the + * N1 firmware, Bluetooth, and (when armed) Wi-Fi association survive across PERST#. * * If any function fails host-sleep or wake, or firmware is unhealthy, the driver falls back * to teardown and warm-reset recovery: @@ -764,8 +764,22 @@ static bool centauri_t6050_domain_fence(struct centauri_t6050_rewake *rw) pci_clear_master(fn[i]); } for (i = 0; i < 3; i++) { - if (fn[i] && !centauri_t6050_stop_dma(fn[i])) + bool fn_stopped = !fn[i] || centauri_t6050_stop_dma(fn[i]); + + if (!fn_stopped) stopped = false; + /* + * Refresh any keep-alive PCI state saved before Control fell + * back to teardown so an aborted suspend cannot restore Bus + * Master or the old header onto a quiesced function whose DMA + * arena was freed. Never save an unreadable/gone function + * (which would snapshot 0xffff); clearing state_saved hands + * suspend_noirq state save and power-state selection back to + * the PCI core. + */ + if (fn[i] && i > 0 && fn[i]->state_saved && + (!fn_stopped || pci_save_state(fn[i]))) + fn[i]->state_saved = false; pci_dev_put(fn[i]); } return stopped; @@ -1022,16 +1036,18 @@ void apple_centauri_sleep_mark_fallback(struct pci_dev *fn) } EXPORT_SYMBOL_GPL(apple_centauri_sleep_mark_fallback); -static void centauri_t6050_set_d3hot(struct pci_dev *pdev) +static void centauri_t6050_set_d3hot(struct pci_dev *pdev, bool pme_enable) { u16 pmctrl; if (!pdev || !pdev->pm_cap) return; if (!pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &pmctrl)) { - pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, - (pmctrl & ~PCI_PM_CTRL_STATE_MASK) | - (__force u16)PCI_D3hot | PCI_PM_CTRL_PME_ENABLE); + pmctrl &= ~(PCI_PM_CTRL_STATE_MASK | PCI_PM_CTRL_PME_ENABLE); + pmctrl |= (__force u16)PCI_D3hot; + if (pme_enable) + pmctrl |= PCI_PM_CTRL_PME_ENABLE; + pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, pmctrl); mdelay(pdev->d3hot_delay); } } @@ -1128,19 +1144,26 @@ static int centauri_t6050_suspend(struct device *dev) c->firmware_kept = false; c->control_sleep_sent = false; + c->keep_alive_pme = false; if (!beta_fallback && c->boot_phase == CEN_BOOT_READY && c->ipc && c->wifi && !centauri_t6050_wifi_pm_error(c) && + !centauri_t6050_wifi_pm_disconnected(c) && readl(c->bar + 0x8000) == 2 && readl(c->bar + 0x8050) == 2) { + bool wifi_sleep_sent = false; + int unwind_err = 0, wake_ret; u32 id0 = 0, id1 = 0; fn1 = centauri_t6050_ipc_alpha_dev(c); if (!fn1 || pci_read_config_dword(pdev, PCI_VENDOR_ID, &id0) || pci_read_config_dword(fn1, PCI_VENDOR_ID, &id1) || (id0 & 0xffff) != pdev->vendor || (id1 & 0xffff) != fn1->vendor || - id0 == ~0U || id1 == ~0U) + id0 == ~0U || id1 == ~0U) { ret = -ENODEV; - else + } else { ret = centauri_t6050_wifi_suspend(c); + if (!ret) + wifi_sleep_sent = true; + } if (!ret) { ret = centauri_t6050_ipc_control_sleep(c, true); if (!ret) @@ -1156,13 +1179,38 @@ static int centauri_t6050_suspend(struct device *dev) centauri_t6050_save_memswap(pdev, c->saved_memswap[0]); centauri_t6050_save_memswap(fn1, c->saved_memswap[1]); apple_pcie_t6050_sleep_keep_alive(pdev->bus->self); + c->keep_alive_pme = centauri_t6050_wifi_wowlan_armed(c); c->firmware_kept = true; dev_dbg(dev, "N1 kept alive for firmware sleep\n"); return 0; } dev_warn(dev, "N1 keep-alive suspend failed (%d); falling back to warm-reset sleep\n", ret); - c->control_sleep_sent = false; + if (c->control_sleep_sent) { + wake_ret = centauri_t6050_ipc_control_sleep(c, false); + if (wake_ret) { + dev_warn(dev, + "Control ACIPC host wake failed during fallback (%d)\n", + wake_ret); + unwind_err = wake_ret; + } + c->control_sleep_sent = false; + } + if (wifi_sleep_sent) { + wake_ret = centauri_t6050_wifi_resume(c); + if (wake_ret) { + dev_warn(dev, + "Alpha host wake failed during fallback (%d)\n", + wake_ret); + if (!unwind_err) + unwind_err = wake_ret; + } + } + if (unwind_err) { + centauri_t6050_wifi_mark_failed(c); + /* Also covers an aborted suspend where resume/rewake may not run. */ + apple_centauri_sleep_recovery_needed(pdev, unwind_err); + } } ret = centauri_t6050_quiesce(c); @@ -1189,8 +1237,8 @@ static int centauri_t6050_suspend_noirq(struct device *dev) if (!c->firmware_kept || !pm_suspend_via_firmware()) return 0; fn1 = centauri_t6050_ipc_alpha_dev(c); - centauri_t6050_set_d3hot(fn1); - centauri_t6050_set_d3hot(pdev); + centauri_t6050_set_d3hot(fn1, c->keep_alive_pme); + centauri_t6050_set_d3hot(pdev, c->keep_alive_pme); return 0; } diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h index 17a92ca333985c..828b510ce028c4 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h @@ -62,6 +62,7 @@ struct centauri_t6050 { /* Kept alive across a firmware sleep via ACIPC host-sleep */ bool firmware_kept; bool control_sleep_sent; + bool keep_alive_pme; u32 saved_pci_id[2]; u32 saved_memswap[2][3]; struct centauri_t6050_ipc *ipc; @@ -88,6 +89,9 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c); void centauri_t6050_wifi_unregister(struct centauri_t6050 *c); void centauri_t6050_wifi_pm_prepare(struct centauri_t6050 *c); int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c); +bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c); +bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c); +void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c); void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c); int centauri_t6050_wifi_suspend(struct centauri_t6050 *c); int centauri_t6050_wifi_resume(struct centauri_t6050 *c); @@ -113,6 +117,20 @@ static inline int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c) return 0; } +static inline bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c) +{ + return false; +} + +static inline bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c) +{ + return false; +} + +static inline void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c) +{ +} + static inline void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) { } diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 61a421a58ec206..a2f7ad9ab90541 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -77,7 +77,7 @@ struct centauri_t6050_wifi { bool connecting, connected, connect_event, disconnect_event; bool disconnect_pending; /* PM callbacks and the normal disconnect producer serialize on lock. */ - bool pm_prepared; + bool pm_prepared, pm_wowlan_armed; struct centauri_wifi_disconnect_receipt pm_disconnect; u16 connect_status, scan_status, disconnect_status; struct ieee80211_channel *connect_channel; @@ -1942,6 +1942,32 @@ static int wait_disconnect(struct centauri_t6050_wifi *wifi) return 0; } +static bool data_tx_in_flight(struct centauri_t6050_wifi *wifi) +{ + unsigned int i; + + for (i = 0; i < DATA_TX_SLOTS; i++) + if (wifi->data_tx_busy[i]) + return true; + return false; +} + +static void drain_tx_in_flight(struct centauri_t6050_wifi *wifi) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(100); + + lockdep_assert_held(&wifi->lock); + while (data_tx_in_flight(wifi) && time_before(jiffies, deadline)) { + drain(wifi); + if (!data_tx_in_flight(wifi) || wifi->command_failed || + READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) + break; + usleep_range(500, 1000); + } + if (data_tx_in_flight(wifi)) + drain(wifi); +} + static int wifi_disconnect(struct wiphy *wiphy, struct net_device *netdev, u16 reason) { @@ -1988,6 +2014,8 @@ static int wifi_disconnect(struct wiphy *wiphy, struct net_device *netdev, wifi->connected = false; netif_stop_queue(netdev); skb_queue_purge(&wifi->data_tx_queue); + if (!READ_ONCE(wifi->stopping)) + drain_tx_in_flight(wifi); netif_carrier_off(netdev); if (connected) cfg80211_disconnected(netdev, reason, NULL, 0, true, @@ -2006,6 +2034,7 @@ void centauri_t6050_wifi_pm_prepare(struct centauri_t6050 *c) return; mutex_lock(&wifi->lock); wifi->pm_disconnect = (struct centauri_wifi_disconnect_receipt) {}; + wifi->pm_wowlan_armed = false; wifi->pm_prepared = true; mutex_unlock(&wifi->lock); } @@ -2024,6 +2053,46 @@ int centauri_t6050_wifi_pm_error(struct centauri_t6050 *c) return ret; } +bool centauri_t6050_wifi_pm_disconnected(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + bool disconnected = false; + + if (!wifi) + return false; + mutex_lock(&wifi->lock); + if (wifi->pm_prepared) + disconnected = wifi->pm_disconnect.seen; + mutex_unlock(&wifi->lock); + return disconnected; +} + +bool centauri_t6050_wifi_wowlan_armed(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + bool armed = false; + + if (!wifi) + return false; + mutex_lock(&wifi->lock); + if (wifi->pm_prepared) + armed = wifi->pm_wowlan_armed; + mutex_unlock(&wifi->lock); + return armed; +} + +void centauri_t6050_wifi_mark_failed(struct centauri_t6050 *c) +{ + struct centauri_t6050_wifi *wifi = c->wifi; + + if (!wifi) + return; + mutex_lock(&wifi->lock); + WRITE_ONCE(wifi->stopping, true); + wifi->command_failed = true; + mutex_unlock(&wifi->lock); +} + void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi = c->wifi; @@ -2032,6 +2101,7 @@ void centauri_t6050_wifi_pm_complete(struct centauri_t6050 *c) return; mutex_lock(&wifi->lock); /* Keep the receipt until the next prepare; it is not a sleep proof. */ + wifi->pm_wowlan_armed = false; wifi->pm_prepared = false; mutex_unlock(&wifi->lock); } @@ -2110,16 +2180,6 @@ static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) return ret; } -static bool data_tx_in_flight(struct centauri_t6050_wifi *wifi) -{ - unsigned int i; - - for (i = 0; i < DATA_TX_SLOTS; i++) - if (wifi->data_tx_busy[i]) - return true; - return false; -} - static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) { int ret; @@ -2152,7 +2212,6 @@ static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi = c->wifi; - unsigned long deadline; unsigned int i; int ret; @@ -2178,16 +2237,7 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) mutex_unlock(&wifi->lock); return -EIO; } - deadline = jiffies + msecs_to_jiffies(100); - while (data_tx_in_flight(wifi) && time_before(jiffies, deadline)) { - drain(wifi); - if (!data_tx_in_flight(wifi) || wifi->command_failed || - READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) - break; - usleep_range(500, 1000); - } - if (data_tx_in_flight(wifi)) - drain(wifi); + drain_tx_in_flight(wifi); if (data_tx_in_flight(wifi) || wifi->command_failed || READ_ONCE(wifi->stopping) || readl(wifi->a.bar + 8) != 2) { ret = data_tx_in_flight(wifi) ? -EBUSY : -EIO; @@ -2214,7 +2264,12 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) mutex_unlock(&wifi->lock); return 0; } - alpha_resume_locked(wifi); + if (alpha_resume_locked(wifi)) { + dev_warn(&c->pdev->dev, + "Alpha host wake failed during suspend unwind\n"); + WRITE_ONCE(wifi->stopping, true); + wifi->command_failed = true; + } mutex_unlock(&wifi->lock); return ret; @@ -2252,9 +2307,11 @@ static int wifi_suspend(struct wiphy *wiphy, struct cfg80211_wowlan *wowlan) ret = (wowlan->any && wifi->connected && !wifi->connecting && !wifi->disconnect_pending && !wifi->command_failed && !READ_ONCE(wifi->stopping)) ? 0 : 1; + wifi->pm_wowlan_armed = !ret; mutex_unlock(&wifi->lock); return ret; } + wifi->pm_wowlan_armed = false; /* cfg80211 already called normal leave; do not send another command. */ if (wifi->pm_prepared) ret = wifi->pm_disconnect.error; diff --git a/tools/asahi/centauri-bt-arena-tests.py b/tools/asahi/centauri-bt-arena-tests.py index c8272d0a9d239c..a8715ca8a8032a 100755 --- a/tools/asahi/centauri-bt-arena-tests.py +++ b/tools/asahi/centauri-bt-arena-tests.py @@ -49,7 +49,7 @@ def function(source, name): #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) struct device { int dummy; }; -struct pci_dev { struct device dev; void *data; }; +struct pci_dev { struct device dev; void *data; bool state_saved; }; struct hci_dev { int dummy; }; struct cen_bt { struct pci_dev *pdev; @@ -67,7 +67,7 @@ def function(source, name): static int config_error, pending, command, saves, save_error, requests, recovery_error; static int unregisters, closes, hci_frees, arena_frees, irq_frees; static int owner_unregisters, handoffs, fallbacks, transport_sleeps, transport_wakes; -static int transport_sleep_error; +static int transport_sleep_error, transport_wake_error; static unsigned int bar_exec, bar_ipc; static void *handed_arena; static uintptr_t handed_dma; @@ -93,7 +93,7 @@ def function(source, name): return transport_sleep_error; } transport_wakes++; - return 0; + return transport_wake_error; } static void apple_centauri_sleep_mark_fallback(struct pci_dev *p) { assert(p == active->pdev); @@ -102,6 +102,7 @@ def function(source, name): static void *hci_get_drvdata(struct hci_dev *p) { assert(p); return active; } static void hci_unregister_dev(struct hci_dev *p) { assert(p && active->arena && active->quiescing); + assert(!active->transport_sleep_sent && !active->transport_paused); /* The arena must remain available through HCI's close barrier. */ unregisters++; } @@ -159,7 +160,7 @@ def function(source, name): handoffs++; } } -static int pci_save_state(struct pci_dev *p) { (void)p; saves++; return save_error; } +static int pci_save_state(struct pci_dev *p) { saves++; if (!save_error) p->state_saved = true; return save_error; } #define dev_warn(...) ((void)0) ''' @@ -169,6 +170,7 @@ def function(source, name): static struct cen_bt bt; static void reset(void) { memset(&bt, 0, sizeof(bt)); + dev.state_saved = false; active = &bt; bt.pdev = &dev; dev.data = &bt; bt.hdev = &hdev; bt.hci_registered = true; @@ -180,7 +182,7 @@ def function(source, name): config_error = saves = save_error = requests = recovery_error = 0; unregisters = closes = hci_frees = arena_frees = irq_frees = 0; owner_unregisters = handoffs = fallbacks = transport_sleeps = transport_wakes = 0; - transport_sleep_error = 0; + transport_sleep_error = transport_wake_error = 0; bar_exec = bar_ipc = 2; handed_arena = NULL; handed_dma = 0; sleep_reboot = true; @@ -258,7 +260,19 @@ def function(source, name): assert(cen_suspend(&dev.dev) == 0); assert(bt.transport_sleep_sent && !bt.asleep && bt.hdev == &hdev); assert(bt.arena && arena_frees == 0 && transport_sleeps == 1 && fallbacks == 0); - assert(saves == 1 && requests == 0); + assert(saves == 1 && requests == 0 && dev.state_saved && (command & PCI_COMMAND_MASTER)); + /* Control fallback quiesce after Beta keep-alive wakes Beta ACIPC first. */ + assert(cen_quiesce(&bt) == 0); + assert(!bt.transport_sleep_sent && !bt.transport_paused && bt.asleep && !bt.hdev); + assert(transport_wakes == 1 && unregisters == 1 && hci_frees == 1); + /* Fallback quiesce with failed Beta ACIPC wake clears running before unregister. */ + reset(); bt.bar = (void *)0x3000; + assert(cen_suspend(&dev.dev) == 0); + assert(bt.transport_sleep_sent && bt.transport_paused && bt.running); + transport_wake_error = -EIO; + assert(cen_quiesce(&bt) == 0); + assert(!bt.transport_sleep_sent && !bt.transport_paused && !bt.running && bt.asleep); + assert(transport_wakes == 1 && unregisters == 1 && hci_frees == 1); /* Keep-alive save failure unwinds ACIPC sleep and falls back to teardown. */ reset(); bt.bar = (void *)0x3000; save_error = -ENOMEM; assert(cen_suspend(&dev.dev) == -ENOMEM); @@ -270,7 +284,7 @@ def function(source, name): assert(cen_suspend(&dev.dev) == 0); assert(!bt.transport_sleep_sent && bt.asleep && bt.arena && !bt.hdev); assert(transport_sleeps == 1 && transport_wakes == 0 && fallbacks == 1); - assert(saves == 1 && requests == 0); + assert(saves == 1 && requests == 0 && dev.state_saved && !(command & PCI_COMMAND_MASTER)); /* A published arena cannot be reclaimed by a local-only detach. */ reset(); assert(cen_stop(&bt) == -EBUSY && bt.arena && arena_frees == 0); @@ -400,9 +414,9 @@ def function(source, name): def probe_stubs(): stubs = STUBS.replace('struct device { int dummy; };', 'struct device { struct device *parent; void *of_node; };') - stubs = stubs.replace('struct pci_dev { struct device dev; void *data; };', + stubs = stubs.replace('struct pci_dev { struct device dev; void *data; bool state_saved; };', 'struct pci_bus { int number; };\n' - 'struct pci_dev { struct device dev; void *data; struct pci_bus *bus; int devfn; };') + 'struct pci_dev { struct device dev; void *data; bool state_saved; struct pci_bus *bus; int devfn; };') stubs = stubs.replace('struct hci_dev { int dummy; };', 'struct sk_buff;\nstruct hci_dev {\n int bus;\n int (*open)(struct hci_dev *), (*close)(struct hci_dev *);\n int (*flush)(struct hci_dev *), (*setup)(struct hci_dev *);\n int (*post_init)(struct hci_dev *), (*reset_dup_filter)(struct hci_dev *);\n int (*send)(struct hci_dev *, struct sk_buff *);\n};') stubs = stubs.replace('static struct cen_bt *active;', 'static struct cen_bt *active;\nstatic bool probe_hci_registered;') @@ -472,12 +486,16 @@ def run(name, body, stubs=STUBS, tests=TESTS, flags=()): "missing-final-work-drain": ( "cancel_work_sync(&bt->io_work);\n\tskb_queue_purge(&bt->txq);", "if (false) cancel_work_sync(&bt->io_work);\n\tskb_queue_purge(&bt->txq);"), + "missing-quiesce-acipc-wake": ( + "if (bt->transport_sleep_sent) {", + "if (false && bt->transport_sleep_sent) {"), } failures = { 'lost-retained-tuple': 'bt.asleep && bt.arena && arena_frees == 0 && requests == 0', 'missing-pending-fence': 'cen_release(&bt) == -EBUSY', 'missing-save-recovery': 'bt.asleep && bt.arena && requests == 1 && recovery_error == -ENOMEM', 'missing-final-work-drain': 'p && !active->running && !active->io_work && !active->irq_count', + 'missing-quiesce-acipc-wake': '!active->transport_sleep_sent && !active->transport_paused', } for name, (old, new) in controls.items(): assert helpers.count(old) == 1, name diff --git a/tools/asahi/centauri-physical-recovery-tests.c b/tools/asahi/centauri-physical-recovery-tests.c index 4c765125fe7374..475edceb42ca8d 100644 --- a/tools/asahi/centauri-physical-recovery-tests.c +++ b/tools/asahi/centauri-physical-recovery-tests.c @@ -35,7 +35,7 @@ struct pci_dev { struct pci_bus *bus, *subordinate; void *drvdata; int devfn, refs, command, reads, writes; - bool visible, pending; + bool visible, pending, state_saved; }; struct work_struct { int unused; }; struct kref { int count; }; @@ -110,6 +110,8 @@ static void *pci_get_drvdata(struct pci_dev *p) { return p->drvdata; } static bool can_config(struct pci_dev *p) { return link_active && p->visible; } static void pci_clear_master(struct pci_dev *p) { p->reads++; p->writes++; if (can_config(p)) p->command &= ~PCI_COMMAND_MASTER; } +static int pci_save_state(struct pci_dev *p) +{ p->reads++; if (!can_config(p)) return -EIO; p->state_saved = true; return 0; } static int pci_read_config_word(struct pci_dev *p, int where, u16 *v) { (void)where; p->reads++; *v = can_config(p) ? p->command : 0xffff; return 0; } static int pcibios_err_to_errno(int x) { return x ? -EIO : 0; } diff --git a/tools/asahi/centauri-recovery-tests.py b/tools/asahi/centauri-recovery-tests.py index 0950b1edab6482..e46538f68384a6 100644 --- a/tools/asahi/centauri-recovery-tests.py +++ b/tools/asahi/centauri-recovery-tests.py @@ -46,7 +46,7 @@ def block(name): #define list_for_each_entry(v,h,n) for ((v)=owner; (v); (v)=NULL) struct device { int lock; void *data; }; struct pci_bus; -struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; }; +struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; bool state_saved; }; struct pci_bus { struct pci_dev *self; struct pci_bus *subordinate; }; struct kref { int refs; }; struct work_struct { int queued; }; @@ -72,9 +72,9 @@ def block(name): static bool cen_exiting, supported_sleep=true; static struct centauri_t6050_rewake *owner; static struct pci_dev *slots[3]; -static int events[100], nevents, stop_error, beta_error, release_error; -static int wifi_error, requested_error, requests, queues; -enum { STOP_BOOT=1, QUIESCE, WIFI_STOP, IRQ_STOP, CLEAR, FENCE, RELEASE, FREE, +static int events[100], nevents, stop_error, beta_error, release_error, save_error; +static int wifi_error, requested_error, requests, queues, saved_fns[3]; +enum { STOP_BOOT=1, QUIESCE, WIFI_STOP, IRQ_STOP, CLEAR, FENCE, SAVE, RELEASE, FREE, PM_ERROR, PM_COMPLETE, REQUEST }; static void event(int n) { assert(nevents < 100); events[nevents++]=n; } static void mutex_lock(int *p) { assert(!*p); *p=1; } @@ -90,6 +90,16 @@ def block(name): { assert(p); event(CLEAR); } static bool centauri_t6050_stop_dma(struct pci_dev *p) { assert(p); event(FENCE); return !stop_error; } +static int pci_save_state(struct pci_dev *p) +{ + assert(p && (p->devfn & 7) < 3); + event(SAVE); + if (save_error) + return save_error; + p->state_saved = true; + saved_fns[p->devfn & 7]++; + return 0; +} static bool centauri_t6050_ipc_fenced(struct centauri_t6050_ipc *p) { return !p || p->fenced; } static void cancel_delayed_work_sync(int *p) { (void)p; event(STOP_BOOT); } @@ -130,7 +140,8 @@ def block(name): rw->ref.refs=1; rw->generation=1; c->pdev=&fn[0]; c->recovery=rw; c->ready=true; fn[0].dev.data=c; - nevents=stop_error=beta_error=release_error=wifi_error=requests=queues=0; + nevents=stop_error=beta_error=release_error=save_error=wifi_error=requests=queues=0; + memset(saved_fns,0,sizeof(saved_fns)); cen_exiting=false; } static int count(int value) @@ -175,6 +186,34 @@ def block(name): reset(&c,&rw,fn,&bridge,&bus); slots[2]=NULL; assert(!centauri_t6050_domain_fence(&rw)); /* old-owner identity cannot vanish */ + /* Keep-alive saved PCI state on fn1/fn2 must be refreshed after fence, before release. */ + reset(&c,&rw,fn,&bridge,&bus); + ipc.fenced=true; + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[0].state_saved=fn[1].state_saved=fn[2].state_saved=true; + assert(!centauri_t6050_quiesce(&c)); + assert(!saved_fns[0] && saved_fns[1]==1 && saved_fns[2]==1); + assert(fn[1].state_saved && fn[2].state_saved); + assert(first(SAVE)>first(FENCE) && first(RELEASE)>first(SAVE)); + + /* If re-save fails, clear stale state_saved so aborted resume cannot restore it. */ + reset(&c,&rw,fn,&bridge,&bus); + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[1].state_saved=fn[2].state_saved=true; + save_error=-ENOMEM; + assert(!centauri_t6050_quiesce(&c)); + assert(!saved_fns[1] && !saved_fns[2]); + assert(!fn[1].state_saved && !fn[2].state_saved); + + /* Unreadable/gone function (stop_dma fails) must clear state_saved without saving 0xffff. */ + reset(&c,&rw,fn,&bridge,&bus); + c.ipc=&ipc; c.firmware=&c; c.descriptor=&rw; + fn[1].state_saved=fn[2].state_saved=true; + stop_error=1; + assert(centauri_t6050_quiesce(&c)==-EBUSY); + assert(!saved_fns[1] && !saved_fns[2]); + assert(!fn[1].state_saved && !fn[2].state_saved); + reset(&c,&rw,fn,&bridge,&bus); rw.beta_fallback=true; assert(!centauri_t6050_prepare(&fn[0].dev) && c.pm_prepared && !rw.beta_fallback); @@ -226,7 +265,7 @@ def block(name): struct module { int refs; }; struct device { int lock, leases, refs; }; struct pci_bus; -struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; }; +struct pci_dev { struct device dev; struct pci_bus *bus, *subordinate; unsigned devfn; bool state_saved; }; struct pci_bus { struct pci_dev *self; }; struct kref { int refs; }; struct apple_centauri_sleep_ops { @@ -484,6 +523,8 @@ def run(): variants = [('baseline', bodies), ('negative-skip-fence', bodies.replace('!centauri_t6050_domain_fence(c->recovery)', 'false')), ('negative-skip-release', bodies.replace('ret = centauri_t6050_beta_call(c->recovery, true);', 'ret = 0;')), + ('negative-stale-state-saved', bodies.replace('fn[i]->state_saved &&', 'false && fn[i]->state_saved &&')), + ('negative-save-unreadable-fn', bodies.replace('(!fn_stopped || pci_save_state(fn[i]))', 'pci_save_state(fn[i])')), ('negative-lost-pm-error', bodies.replace('error = centauri_t6050_wifi_pm_error(c);', 'error = 0;')), ('negative-drop-new-generation', bodies.replace('rw->rerun = true;', 'rw->rerun = false;'))] ownership = '\n'.join(block(name) for name in [ @@ -502,6 +543,8 @@ def run(): 'negative-unlock-before-tuples': '!remove_done && original->dev.locked && rw->control==original', 'negative-skip-fence': 'first(WIFI_STOP)first(FENCE) && first(FREE)>first(RELEASE)', + 'negative-stale-state-saved': '!saved_fns[0] && saved_fns[1]==1 && saved_fns[2]==1', + 'negative-save-unreadable-fn': '!saved_fns[1] && !saved_fns[2]', 'negative-lost-pm-error': '!c.pm_prepared && rw.active && rw.error==-ETIMEDOUT && queues==1', 'negative-drop-new-generation': 'rw.rerun && queues==1 && rw.ref.refs==2', 'negative-lost-orphan': '!rw.ops && !rw.data && rw.arena==arena && rw.beta==&fn', diff --git a/tools/asahi/centauri-wifi-pm-tests.py b/tools/asahi/centauri-wifi-pm-tests.py index 56a259fd9c1ae7..78c3e98ebc1d15 100644 --- a/tools/asahi/centauri-wifi-pm-tests.py +++ b/tools/asahi/centauri-wifi-pm-tests.py @@ -17,7 +17,7 @@ def block(source, name): - match = re.search(r"^(?:static )?(?:int|void) " + re.escape(name) + r"\(", source, re.M) + match = re.search(r"^(?:static )?(?:int|void|bool) " + re.escape(name) + r"\(", source, re.M) if not match: raise RuntimeError(f"Production function {name} missing") brace = source.index("{", match.start()) @@ -39,22 +39,26 @@ def block(source, name): typedef uint16_t u16; typedef uint32_t u32; #define BIT(n) (1U << (n)) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define GFP_KERNEL 0 -#define BUFFER_SIZE 128 +#define BUFFER_SIZE 256 +#define DATA_TX_SLOTS 8 #define TX_BUFFER 2048 #define TR_BASE 0 #define dma_rmb() ((void)0) #define dma_wmb() ((void)0) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) +#define lockdep_assert_held(l) assert(*(l)) #define msecs_to_jiffies(x) (x) #define time_before(a, b) ((long)((a) - (b)) < 0) #define time_after_eq(a, b) (!time_before(a, b)) static unsigned long jiffies; struct centauri_t6050_wifi; -struct centauri_t6050 { struct centauri_t6050_wifi *wifi; bool removing; }; +struct pci_dev { int dev; }; +struct centauri_t6050 { struct pci_dev *pdev; struct centauri_t6050_wifi *wifi; bool removing; }; struct wiphy { struct centauri_t6050_wifi *wifi; }; struct net_device { int unused; }; struct cfg80211_wowlan { bool any; }; @@ -66,7 +70,8 @@ def block(source, name): struct { u8 *window, *bar; uint64_t window_dma; } a; int lock, connect_work, link_work, data_tx_queue; bool command_failed, stopping, connect_abort, disconnect_pending, connecting, connected; - bool reply_valid, pm_prepared; + bool reply_valid, pm_prepared, pm_wowlan_armed; + bool data_tx_busy[DATA_TX_SLOTS]; u16 command_head, sequence, reply_capture, reply_sequence, reply_status; u32 reply_command; u8 *reply_buffer; @@ -74,7 +79,7 @@ def block(source, name): struct centauri_wifi_disconnect_receipt pm_disconnect; }; static const u16 ring_size[5] = {0, 64}; -static unsigned int doorbells, drains, notifications, consumer; +static unsigned int doorbells, drains, notifications, consumer, tx_drain_rounds; static u16 firmware_status; static bool async_reply, async_event, wrong_reply; static bool *submission_probe; @@ -101,6 +106,11 @@ def block(source, name): { assert(wifi->lock); drains++; + if (tx_drain_rounds) { + tx_drain_rounds--; + if (!tx_drain_rounds) + memset(wifi->data_tx_busy, 0, sizeof(wifi->data_tx_busy)); + } if (transport_mode != REPLY) return; if (!wifi->reply_valid) { @@ -124,22 +134,23 @@ def block(source, name): ''' TESTS = r''' +static struct pci_dev pdev; static struct centauri_t6050 control; static struct centauri_t6050_wifi wifi; static struct wiphy wiphy; static struct net_device netdev; -static u8 window[16384], bar[8192]; +static u8 window[32768], bar[8192]; static void reset(void) { memset(&wifi, 0, sizeof(wifi)); memset(window, 0, sizeof(window)); - control = (struct centauri_t6050) { .wifi = &wifi }; + control = (struct centauri_t6050) { .pdev = &pdev, .wifi = &wifi }; wifi.control = &control; wifi.a.window = window; wifi.a.bar = bar; wifi.connected = true; wiphy.wifi = &wifi; - doorbells = drains = notifications = consumer = 0; + doorbells = drains = notifications = consumer = tx_drain_rounds = 0; firmware_status = 0; async_reply = async_event = wrong_reply = false; transport_mode = REPLY; @@ -188,12 +199,16 @@ def block(source, name): assert(!wifi.pm_disconnect.seen); expect_error(0); /* Missing transaction remains missing. */ struct cfg80211_wowlan wowlan = {}; + assert(!centauri_t6050_wifi_wowlan_armed(&control)); assert(call_registered_suspend(&wiphy, &wowlan) == 1); + assert(!centauri_t6050_wifi_wowlan_armed(&control)); wowlan.any = true; assert(call_registered_suspend(&wiphy, &wowlan) == 0); - assert(!doorbells && !wifi.pm_disconnect.seen); + assert(centauri_t6050_wifi_wowlan_armed(&control)); + assert(!doorbells && !wifi.pm_disconnect.seen && !centauri_t6050_wifi_pm_disconnected(&control)); wifi.connected = false; assert(call_registered_suspend(&wiphy, &wowlan) == 1); + assert(!centauri_t6050_wifi_wowlan_armed(&control)); wifi.connected = true; wifi.connecting = true; assert(call_registered_suspend(&wiphy, &wowlan) == 1); @@ -204,8 +219,12 @@ def block(source, name): assert(!doorbells && !wifi.pm_disconnect.seen); firmware_status = 326; + wifi.data_tx_busy[0] = true; + tx_drain_rounds = 2; assert(disconnect() == 0); + assert(!data_tx_in_flight(&wifi)); assert(wifi.pm_disconnect.seen && wifi.pm_disconnect.submitted); + assert(centauri_t6050_wifi_pm_disconnected(&control)); assert(wifi.pm_disconnect.replied && wifi.pm_disconnect.status == 326); assert(wifi.pm_disconnect.command_error == -EREMOTEIO); expect_error(0); /* Keep the existing helper normalization. */ @@ -303,6 +322,15 @@ def block(source, name): mutex_unlock(&wifi.lock); assert(published); submission_probe = NULL; + + /* Failed keep-alive unwind marks Wi-Fi failed so teardown skips ACIPC. */ + prepare(); + wifi.data_tx_busy[0] = true; + centauri_t6050_wifi_mark_failed(&control); + assert(wifi.stopping && wifi.command_failed); + assert(disconnect() == 0); + assert(wifi.pm_disconnect.stopping_skip && !doorbells && !drains); + puts("PASS: production disconnect/transport/PM callbacks and first-error retention"); return 0; } @@ -322,9 +350,12 @@ def main(): receipt = re.search(r"struct centauri_wifi_disconnect_receipt \{.*?\n\};", source, re.S) if not receipt: raise RuntimeError("Production receipt structure missing") - names = ["command_reply", "wait_disconnect", "wifi_disconnect", + names = ["command_reply", "wait_disconnect", "data_tx_in_flight", + "drain_tx_in_flight", "wifi_disconnect", "centauri_t6050_wifi_pm_prepare", "centauri_t6050_wifi_pm_error", - "centauri_t6050_wifi_pm_complete", "wifi_suspend"] + "centauri_t6050_wifi_pm_disconnected", "centauri_t6050_wifi_wowlan_armed", + "centauri_t6050_wifi_mark_failed", "centauri_t6050_wifi_pm_complete", + "wifi_suspend"] has_resume = bool(re.search(r"^static int wifi_resume\(", source, re.M)) if has_resume: names.append("wifi_resume") From 8ecf51d299877dbcb6b7d543a1f41a1290689442 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 19:41:31 -0500 Subject: [PATCH 0484/1514] wifi: apple: centauri: t6050: try full TLV 280 event mask on wake with legacy fallback Command 6 TLV 280 currently hardcodes the 85-event legacy mask on wake so older Alpha firmware (which rejects TLV 280 lengths >= 87 and event counts >= 86) accepts the command, leaving newer firmware that supports 91 events without its upper event slots restored after sleep. Keep the sleep command 6 TLV 280 at the existing 86-byte length (1 + 85, carrying the 9 filtered sleep events) on every firmware. On wake, try the 91-event full mask first and fall back to the 85-event legacy mask on -EREMOTEIO while the Alpha transport remains healthy (exec stage == 2). Log the refused firmware status once per Wi-Fi registration via dev_info() when fallback succeeds, without permanently latching the legacy count so a transient unrelated refusal does not pin a registration to 85 events. Extend tools/asahi/centauri-wifi-pm-tests.py to cover legacy fallback with one-shot dev_info logging, transient wake refusal recovery back to 91 events, full-mask wake acceptance, and sleep-length/fallback-log negative controls. Signed-off-by: Diljit Singh --- .../apple/centauri/t6050/centauri_wifi.c | 50 ++++++-- tools/asahi/centauri-wifi-pm-tests.py | 110 ++++++++++++++++-- 2 files changed, 144 insertions(+), 16 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index a2f7ad9ab90541..aa8904f969c0fa 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -72,6 +72,7 @@ struct centauri_t6050_wifi { size_t reply_capacity, reply_size; bool stopping, command_failed; bool tx_paused, transport_paused, host_sleep_sent, transport_sleep_sent; + bool host_events_fallback_logged; bool scan_abort, connect_abort; u8 scan_sequence; bool connecting, connected, connect_event, disconnect_event; @@ -2146,14 +2147,21 @@ static int alpha_transport_state(struct centauri_t6050_wifi *wifi, bool asleep) return ret; } -static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) +#define CEN_HOST_EVENTS_LEGACY 85 +#define CEN_HOST_EVENTS_FULL 91 + +static int alpha_host_power_send(struct centauri_t6050_wifi *wifi, bool asleep, + u8 event_count) { static const u8 sleep_events[] = { 24, 26, 27, 15, 51, 8, 9, 10, 84 }; - u8 payload[98] = {}, events[86] = {}, sleep_option = 1; + u8 payload[3 + 5 + 4 + 1 + CEN_HOST_EVENTS_FULL] = {}; + u8 events[1 + CEN_HOST_EVENTS_FULL] = {}; + u8 sleep_option = 1; u16 state = 0; u8 hint = 0; size_t size = 3; - int i, ret; + unsigned int i; + int ret; lockdep_assert_held(&wifi->lock); if (readl(wifi->a.bar + 8) != 2) @@ -2167,16 +2175,40 @@ static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) events[0] = ARRAY_SIZE(sleep_events); memcpy(events + 1, sleep_events, sizeof(sleep_events)); } else { - events[0] = sizeof(events) - 1; - for (i = 0; i < events[0]; i++) + events[0] = event_count; + for (i = 0; i < event_count; i++) events[i + 1] = i; } - append_tlv(payload, &size, 280, events, sizeof(events)); + append_tlv(payload, &size, 280, events, 1 + event_count); ret = command(wifi, 6, payload, size); dev_dbg(&wifi->control->pdev->dev, - "Alpha firmware host %s (connected=%d state=%u): ret=%d status=%u exec=%u\n", - asleep ? "sleep" : "awake", wifi->connected, state, ret, - wifi->reply_status, readl(wifi->a.bar + 8)); + "Alpha firmware host %s (connected=%d state=%u events=%u tlv280=%u): ret=%d status=%u exec=%u\n", + asleep ? "sleep" : "awake", wifi->connected, state, + events[0], 1 + event_count, ret, wifi->reply_status, + readl(wifi->a.bar + 8)); + return ret; +} + +static int alpha_host_power(struct centauri_t6050_wifi *wifi, bool asleep) +{ + u16 full_status; + int ret; + + if (asleep) + return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_LEGACY); + + ret = alpha_host_power_send(wifi, false, CEN_HOST_EVENTS_FULL); + if (ret == -EREMOTEIO && readl(wifi->a.bar + 8) == 2) { + full_status = wifi->reply_status; + ret = alpha_host_power_send(wifi, false, CEN_HOST_EVENTS_LEGACY); + if (!ret && !wifi->host_events_fallback_logged) { + wifi->host_events_fallback_logged = true; + dev_info(&wifi->control->pdev->dev, + "Alpha host wake fell back from %u to %u events (status=%u)\n", + CEN_HOST_EVENTS_FULL, CEN_HOST_EVENTS_LEGACY, + full_status); + } + } return ret; } diff --git a/tools/asahi/centauri-wifi-pm-tests.py b/tools/asahi/centauri-wifi-pm-tests.py index 78c3e98ebc1d15..1a4f9293e625eb 100644 --- a/tools/asahi/centauri-wifi-pm-tests.py +++ b/tools/asahi/centauri-wifi-pm-tests.py @@ -45,6 +45,8 @@ def block(source, name): #define GFP_KERNEL 0 #define BUFFER_SIZE 256 #define DATA_TX_SLOTS 8 +#define CEN_HOST_EVENTS_LEGACY 85 +#define CEN_HOST_EVENTS_FULL 91 #define TX_BUFFER 2048 #define TR_BASE 0 #define dma_rmb() ((void)0) @@ -72,6 +74,7 @@ def block(source, name): bool command_failed, stopping, connect_abort, disconnect_pending, connecting, connected; bool reply_valid, pm_prepared, pm_wowlan_armed; bool data_tx_busy[DATA_TX_SLOTS]; + bool host_events_fallback_logged; u16 command_head, sequence, reply_capture, reply_sequence, reply_status; u32 reply_command; u8 *reply_buffer; @@ -79,8 +82,12 @@ def block(source, name): struct centauri_wifi_disconnect_receipt pm_disconnect; }; static const u16 ring_size[5] = {0, 64}; -static unsigned int doorbells, drains, notifications, consumer, tx_drain_rounds; -static u16 firmware_status; +static unsigned int doorbells, drains, notifications, consumer, tx_drain_rounds, info_logs; +static void dev_info(const void *dev, const char *fmt, ...) +{ (void)dev; (void)fmt; info_logs++; } +static u16 firmware_status, last_cmd6_tlv280_len, mock_fw_transient_status; +static u32 mock_reply_command = 131073; +static u8 mock_fw_max_events, last_cmd6_tlv280_count; static bool async_reply, async_event, wrong_reply; static bool *submission_probe; static bool private_access_forbidden; @@ -101,6 +108,25 @@ def block(source, name): static void put_unaligned_le16(u16 value, void *p) { memcpy(p, &value, 2); } static void put_unaligned_le32(u32 value, void *p) { memcpy(p, &value, 4); } static void put_unaligned_le64(uint64_t value, void *p) { memcpy(p, &value, 8); } +static void append_tlv(u8 *buffer, size_t *size, u16 tag, const void *value, size_t len) +{ + put_unaligned_le16(tag, buffer + *size); + put_unaligned_le16(len, buffer + *size + 2); + memcpy(buffer + *size + 4, value, len); + *size += 4 + len; + if (tag == 280) { + last_cmd6_tlv280_len = len; + last_cmd6_tlv280_count = len ? ((const u8 *)value)[0] : 0; + } +} +static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, + const void *payload, size_t size, void *reply, + size_t *reply_size, bool *submitted); +static int command(struct centauri_t6050_wifi *wifi, u32 id, const void *payload, + size_t size) +{ + return command_reply(wifi, id, payload, size, NULL, NULL, NULL); +} static void command_fault(struct centauri_t6050_wifi *wifi) { wifi->command_failed = true; } static void drain(struct centauri_t6050_wifi *wifi) { @@ -116,8 +142,17 @@ def block(source, name): if (!wifi->reply_valid) { wifi->reply_valid = true; wifi->reply_sequence = wifi->reply_capture + wrong_reply; - wifi->reply_command = 131073 | (async_reply ? BIT(30) : 0); - wifi->reply_status = firmware_status; + wifi->reply_command = mock_reply_command | (async_reply ? BIT(30) : 0); + if (mock_reply_command == 6 && mock_fw_transient_status) { + wifi->reply_status = mock_fw_transient_status; + mock_fw_transient_status = 0; + } else if (mock_reply_command == 6 && mock_fw_max_events && + (last_cmd6_tlv280_len > 1 + mock_fw_max_events || + last_cmd6_tlv280_count > mock_fw_max_events)) { + wifi->reply_status = 1; + } else { + wifi->reply_status = firmware_status; + } } else if (async_event) { wifi->disconnect_pending = false; } @@ -150,8 +185,10 @@ def block(source, name): wifi.a.bar = bar; wifi.connected = true; wiphy.wifi = &wifi; - doorbells = drains = notifications = consumer = tx_drain_rounds = 0; - firmware_status = 0; + doorbells = drains = notifications = consumer = tx_drain_rounds = info_logs = 0; + firmware_status = last_cmd6_tlv280_len = mock_fw_transient_status = 0; + mock_reply_command = 131073; + mock_fw_max_events = last_cmd6_tlv280_count = 0; async_reply = async_event = wrong_reply = false; transport_mode = REPLY; jiffies = 0; @@ -331,6 +368,57 @@ def block(source, name): assert(disconnect() == 0); assert(wifi.pm_disconnect.stopping_skip && !doorbells && !drains); + /* + * Sleep sends legacy 86-byte TLV 280 without touching fallback state; + * legacy firmware refuses 91 events on wake (-EREMOTEIO), falls back to 85, + * and logs the fallback once via dev_info. + */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 85; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, true) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 9 && doorbells == 1); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && wifi.host_events_fallback_logged && + last_cmd6_tlv280_len == 86 && last_cmd6_tlv280_count == 85 && + doorbells == 3); + /* Subsequent wakes fall back without repeating the one-shot dev_info. */ + assert(alpha_host_power(&wifi, true) == 0); + assert(last_cmd6_tlv280_len == 86 && last_cmd6_tlv280_count == 9 && doorbells == 4); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 85 && doorbells == 6); + mutex_unlock(&wifi.lock); + + /* Transient unrelated -EREMOTEIO on wake does not permanently pin 85 events. */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 91; + mock_fw_transient_status = 777; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 85 && doorbells == 2); + assert(alpha_host_power(&wifi, false) == 0); + assert(info_logs == 1 && last_cmd6_tlv280_len == 92 && + last_cmd6_tlv280_count == 91 && doorbells == 3); + mutex_unlock(&wifi.lock); + + /* Full-mask firmware keeps 86-byte sleep TLV and accepts 91 events on wake. */ + prepare(); + mock_reply_command = 6; + mock_fw_max_events = 91; + mutex_lock(&wifi.lock); + assert(alpha_host_power(&wifi, true) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 86 && + last_cmd6_tlv280_count == 9 && doorbells == 1); + assert(alpha_host_power(&wifi, false) == 0); + assert(!info_logs && last_cmd6_tlv280_len == 92 && + last_cmd6_tlv280_count == 91 && doorbells == 2); + mutex_unlock(&wifi.lock); + puts("PASS: production disconnect/transport/PM callbacks and first-error retention"); return 0; } @@ -355,7 +443,7 @@ def main(): "centauri_t6050_wifi_pm_prepare", "centauri_t6050_wifi_pm_error", "centauri_t6050_wifi_pm_disconnected", "centauri_t6050_wifi_wowlan_armed", "centauri_t6050_wifi_mark_failed", "centauri_t6050_wifi_pm_complete", - "wifi_suspend"] + "alpha_host_power_send", "alpha_host_power", "wifi_suspend"] has_resume = bool(re.search(r"^static int wifi_resume\(", source, re.M)) if has_resume: names.append("wifi_resume") @@ -409,12 +497,20 @@ def main(): ("stale-reply", "receipt.replied = receipt.submitted && (!ret || ret == -EREMOTEIO);", "receipt.replied = true;"), ("wowlan-ignores-trigger", "wowlan->any && ", ""), + ("sleep-uses-full-len", + "return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_LEGACY);", + "return alpha_host_power_send(wifi, true, CEN_HOST_EVENTS_FULL);"), + ("silent-fallback-log", + "if (!ret && !wifi->host_events_fallback_logged)", + "if (false && !ret && !wifi->host_events_fallback_logged)"), ] failures = { 'lost-suspend-error': 'centauri_t6050_wifi_pm_error(&control) == expected', 'overwritten-first-error': 'wifi.pm_disconnect.status == 777', 'stale-reply': '!wifi.pm_disconnect.submitted && !wifi.pm_disconnect.replied', 'wowlan-ignores-trigger': 'call_registered_suspend(&wiphy, &wowlan) == 1', + 'sleep-uses-full-len': 'alpha_host_power(&wifi, true) == 0', + 'silent-fallback-log': 'info_logs == 1', } for name, before, after in negative_controls if args.negative_controls else []: if before not in production: From 47ef5125554a521aacfcd49e85ef44a79cec43e9 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 16:45:09 -0800 Subject: [PATCH 0485/1514] wifi: apple: centauri: t6050: unlink every avoided 6 GHz BSS, not only 16 commit c40b5ec3249d ("wifi: apple: centauri: t6050: do not report a network's 6 GHz BSSes after a failed 6 GHz join") keeps a network's 6 GHz BSSes out of the scan results for a while after a failed 6 GHz join, in two places. report_beacon() drops a 6 GHz beacon of the avoided network before cfg80211 sees it, and join_avoid_6ghz() unlinks the entries already listed. The second collects at most 16 entries per pass, in at most 8 passes, and looks each one up by BSSID alone, so an entry that shares its BSSID with another can be missed. Make it one helper, avoid_unlink(), called after a failed join and after each 6 GHz beacon cfg80211 is told about while the window is open. It looks each entry up by its BSSID, channel and the avoided SSID, and has no array. Each entry the first walk found gets one pass, and an entry that cfg80211 does not return (expired) or does not unlink (a hidden-SSID beacon that has probe responses) is passed over, with one more walk to find the entry after it. The BSS being joined or used stays, as before. While the window is open, each 6 GHz beacon costs one walk of the scan list, plus one per entry it unlinks or passes over. report_beacon() now tells cfg80211 about an avoided beacon and then unlinks its entry, instead of dropping the beacon first, so a scan dump that runs in between can list that entry for a moment. cfg80211 unlinks the BSSes one beacon describes as one set. The helper therefore keeps any entry whose set holds the BSS being joined or used, or a BSS of the network being joined or used when that is not the avoided one. A failed join to one network then leaves the 6 GHz entries of another network on the same APs in place once that one is joined. This driver does not yet make entries for the BSSes a beacon describes in a multiple-BSSID element, so each set is one entry, and the helper leaves out the same BSSes the two paths did. tools/asahi/centauri-wifi-avoid-tests.py runs the helper against a mock BSS list with cfg80211's set unlinking: entries passed over ahead of others, the joined BSS's set, the current network's sets, and the end of the window. Its negative control puts back a loop that re-read a passed-over entry and left a later avoided entry linked. Only the T6050 N1 Wi-Fi driver changes (the M5 Pro, Max and Ultra). Tested on a J775D (Mac Studio, M5 Ultra). Signed-off-by: Jeff Queisser --- .../apple/centauri/t6050/centauri_wifi.c | 211 ++++++++++----- tools/asahi/centauri-wifi-avoid-tests.py | 254 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 3 files changed, 402 insertions(+), 64 deletions(-) create mode 100755 tools/asahi/centauri-wifi-avoid-tests.py diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 61a421a58ec206..1bd78c621770f8 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -253,10 +253,131 @@ static bool avoided(struct centauri_t6050_wifi *wifi, !memcmp(ssid, wifi->avoid_ssid, ssid_len); } +/* + * The skip-th entry of the avoided network's 6 GHz BSSes that may go, and how + * many there are. An entry may not go when its set holds @keep, or a BSS of + * @cur_ssid: the network being joined or used, when that is not the avoided + * one. + */ +struct avoid_find { + struct centauri_t6050_wifi *wifi; + const u8 *keep, *cur_ssid; + size_t cur_ssid_len; + unsigned int skip, count; + u8 bssid[ETH_ALEN]; + struct ieee80211_channel *channel; +}; + +/* Whether @bss is one to keep. Under cfg80211's BSS lock. */ +static bool avoid_keep_bss(const struct avoid_find *find, + const struct cfg80211_bss *bss) +{ + const struct element *ssid; + bool same; + + if (find->keep && ether_addr_equal(bss->bssid, find->keep)) + return true; + if (!find->cur_ssid) + return false; + rcu_read_lock(); + ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); + same = ssid && ssid->datalen == find->cur_ssid_len && + !memcmp(ssid->data, find->cur_ssid, find->cur_ssid_len); + rcu_read_unlock(); + return same; +} + +/* + * Whether @bss's set holds a BSS to keep: the beacon's own BSS and those of + * its multiple-BSSID element, which cfg80211 unlinks together. + */ +static bool avoid_keep_set(const struct avoid_find *find, + const struct cfg80211_bss *bss) +{ + const struct cfg80211_bss *set = bss->transmitted_bss ?: bss, *member; + + if (avoid_keep_bss(find, set)) + return true; + list_for_each_entry(member, &set->nontrans_list, nontrans_list) + if (avoid_keep_bss(find, member)) + return true; + return false; +} + +/* Called for every BSS entry, under cfg80211's BSS lock. */ +static void avoid_find_one(struct wiphy *wiphy, struct cfg80211_bss *bss, + void *data) +{ + struct avoid_find *find = data; + const struct element *ssid; + bool same; + + rcu_read_lock(); + ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); + same = ssid && avoided(find->wifi, bss->channel, ssid->data, + ssid->datalen); + rcu_read_unlock(); + if (!same || avoid_keep_set(find, bss)) + return; + if (find->count++ == find->skip) { + ether_addr_copy(find->bssid, bss->bssid); + find->channel = bss->channel; + } +} + +/* + * Unlink the avoided network's 6 GHz BSSes but @keep. cfg80211 keeps the + * networks one beacon describes, its own and those of its multiple-BSSID + * element, as one set, and unlinking any of them unlinks the set. So an + * entry whose set holds @keep, or a BSS of the network being joined or used + * (unless that is the avoided one), stays, and the others go with their + * sets. The iterator may not unlink, so each pass looks up one entry and + * unlinks it; one that cfg80211 does not return or unlink is passed over, + * with one more walk to find the entry after it. Each entry the first walk + * found gets one pass. + * + * This runs after every 6 GHz beacon while the window is open: one walk of + * the whole BSS list under cfg80211's BSS lock, with bottom halves off, plus + * one more walk for each entry it unlinks or passes over. + */ +static void avoid_unlink(struct centauri_t6050_wifi *wifi, const u8 *keep) +{ + struct avoid_find find = { .wifi = wifi, .keep = keep }; + struct cfg80211_bss *bss; + unsigned int passes, count; + + if ((wifi->connecting || wifi->connected) && wifi->ssid_len && + !(wifi->ssid_len == wifi->avoid_ssid_len && + !memcmp(wifi->ssid, wifi->avoid_ssid, wifi->ssid_len))) { + find.cur_ssid = wifi->ssid; + find.cur_ssid_len = wifi->ssid_len; + } + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + for (passes = find.count; passes && find.skip < find.count; passes--) { + count = find.count; + bss = cfg80211_get_bss(wifi->wiphy, find.channel, find.bssid, + wifi->avoid_ssid, wifi->avoid_ssid_len, + IEEE80211_BSS_TYPE_ANY, + IEEE80211_PRIVACY_ANY); + if (bss) { + cfg80211_unlink_bss(wifi->wiphy, bss); + cfg80211_put_bss(wifi->wiphy, bss); + } + find.count = 0; + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + if (find.count < count) + continue; + /* Not unlinked: pass it over and look up the entry after it. */ + find.skip++; + find.count = 0; + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find); + } +} + static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, size_t size) { - const u8 *frame, *ie, *end, *ssid = NULL; + const u8 *frame, *ie, *end; struct ieee80211_channel *channel; struct cfg80211_bss *bss; u16 frame_size; @@ -274,8 +395,6 @@ static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, end = frame + frame_size; for (ie = frame + 36; ie + 2 <= end && ie + 2 + ie[1] <= end; ie += 2 + ie[1]) { - if (ie[0] == WLAN_EID_SSID && !ssid) - ssid = ie; if ((ie[0] == WLAN_EID_DS_PARAMS || ie[0] == WLAN_EID_HT_OPERATION) && ie[1]) { @@ -305,17 +424,15 @@ static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, signal = max_t(s8, payload[0x16], payload[0x17]); if (signal >= 0 || signal < -127) signal = -95; - if (ssid && avoided(wifi, channel, ssid + 2, ssid[1]) && - !((wifi->connecting || wifi->connected) && - ether_addr_equal(((struct ieee80211_mgmt *)frame)->bssid, - wifi->bssid))) - return; bss = cfg80211_inform_bss_frame(wifi->wiphy, channel, (struct ieee80211_mgmt *)frame, frame_size, signal * 100, GFP_KERNEL); if (bss) { wifi->beacons_seen++; cfg80211_put_bss(wifi->wiphy, bss); + if (channel->band == NL80211_BAND_6GHZ && wifi->avoid_valid) + avoid_unlink(wifi, wifi->connecting || wifi->connected ? + wifi->bssid : NULL); } } @@ -1709,78 +1826,44 @@ static int join_timeout(u16 status) */ #define AVOID_SECONDS 120 -struct avoid_entry { - u8 bssid[ETH_ALEN]; - struct ieee80211_channel *channel; -}; - -struct avoid_list { +struct avoid_band { struct centauri_t6050_wifi *wifi; bool other_band; - unsigned int count; - struct avoid_entry entry[16]; }; /* Called for every BSS entry, under cfg80211's BSS lock. */ -static void avoid_collect(struct wiphy *wiphy, struct cfg80211_bss *bss, - void *data) +static void avoid_other_band(struct wiphy *wiphy, struct cfg80211_bss *bss, + void *data) { - struct avoid_list *list = data; - struct centauri_t6050_wifi *wifi = list->wifi; + struct avoid_band *band = data; + struct centauri_t6050_wifi *wifi = band->wifi; const struct element *ssid; - bool same; + if (band->other_band || bss->channel->band == NL80211_BAND_6GHZ) + return; rcu_read_lock(); ssid = ieee80211_bss_get_elem(bss, WLAN_EID_SSID); - same = ssid && ssid->datalen == wifi->ssid_len && - !memcmp(ssid->data, wifi->ssid, wifi->ssid_len); + band->other_band = ssid && ssid->datalen == wifi->ssid_len && + !memcmp(ssid->data, wifi->ssid, wifi->ssid_len); rcu_read_unlock(); - if (!same) - return; - if (bss->channel->band != NL80211_BAND_6GHZ) { - list->other_band = true; - } else if (list->count < ARRAY_SIZE(list->entry)) { - ether_addr_copy(list->entry[list->count].bssid, bss->bssid); - list->entry[list->count++].channel = bss->channel; - } } /* The 6 GHz join to wifi->bssid failed. Called with wifi->lock held. */ static void join_avoid_6ghz(struct centauri_t6050_wifi *wifi) { - struct avoid_list list = { .wifi = wifi }; - struct cfg80211_bss *bss; - unsigned int i, pass; - - /* Entries can share a BSSID, and the iterator may not unlink. */ - for (pass = 0; pass < 8; pass++) { - list.count = 0; - cfg80211_bss_iter(wifi->wiphy, NULL, avoid_collect, &list); - if (!list.other_band) - return; - if (!pass) { - memcpy(wifi->avoid_ssid, wifi->ssid, wifi->ssid_len); - wifi->avoid_ssid_len = wifi->ssid_len; - wifi->avoid_until = jiffies + AVOID_SECONDS * HZ; - wifi->avoid_valid = true; - dev_info(&wifi->control->pdev->dev, - "6 GHz join to %pM failed: not reporting this network's 6 GHz BSSes for %u s\n", - wifi->bssid, AVOID_SECONDS); - } - for (i = 0; i < list.count; i++) { - bss = cfg80211_get_bss(wifi->wiphy, - list.entry[i].channel, - list.entry[i].bssid, NULL, 0, - IEEE80211_BSS_TYPE_ANY, - IEEE80211_PRIVACY_ANY); - if (!bss) - continue; - cfg80211_unlink_bss(wifi->wiphy, bss); - cfg80211_put_bss(wifi->wiphy, bss); - } - if (!list.count) - break; - } + struct avoid_band band = { .wifi = wifi }; + + cfg80211_bss_iter(wifi->wiphy, NULL, avoid_other_band, &band); + if (!band.other_band) + return; + memcpy(wifi->avoid_ssid, wifi->ssid, wifi->ssid_len); + wifi->avoid_ssid_len = wifi->ssid_len; + wifi->avoid_until = jiffies + AVOID_SECONDS * HZ; + wifi->avoid_valid = true; + dev_info(&wifi->control->pdev->dev, + "6 GHz join to %pM failed: not reporting this network's 6 GHz BSSes for %u s\n", + wifi->bssid, AVOID_SECONDS); + avoid_unlink(wifi, NULL); } static void connect_worker(struct work_struct *work) diff --git a/tools/asahi/centauri-wifi-avoid-tests.py b/tools/asahi/centauri-wifi-avoid-tests.py new file mode 100755 index 00000000000000..aa1f3b3ffb7938 --- /dev/null +++ b/tools/asahi/centauri-wifi-avoid-tests.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Execute the checkout's T6050 Wi-Fi 6 GHz avoid helper against a mock cfg80211 BSS list. + +The mock keeps cfg80211's set behaviour (unlinking any member of a beacon's +multiple-BSSID set unlinks the whole set), entries cfg80211 does not return +(expired) and entries it does not unlink. No kernel build or hardware is needed. +""" +import argparse +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +SRC = "drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c" + + +def block(source, kind, name): + """The production function (kind: bool, void) or struct `name`, braces balanced.""" + if kind == "struct": + match = re.search(r"^struct " + re.escape(name) + r" \{", source, re.M) + else: + match = re.search(r"^static " + kind + r" " + re.escape(name) + r"\(", source, re.M) + if not match: + raise RuntimeError(f"production {kind} {name} missing") + brace = source.index("{", match.start()) + depth, end = 1, brace + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + if kind == "struct": + end = source.index(";", end) + 1 + return source[match.start():end] + + +PRELUDE = r''' +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; +#define ETH_ALEN 6 +#define IEEE80211_MAX_SSID_LEN 32 +#define WLAN_EID_SSID 0 +#define NL80211_BAND_5GHZ 1 +#define NL80211_BAND_6GHZ 3 +#define IEEE80211_BSS_TYPE_ANY 0 +#define IEEE80211_PRIVACY_ANY 0 +#define time_after(a, b) ((long)((b) - (a)) < 0) +#define rcu_read_lock() ((void)0) +#define rcu_read_unlock() ((void)0) +#define container_of(p, t, m) ((t *)((char *)(p) - offsetof(t, m))) +struct list_head { struct list_head *next, *prev; }; +#define list_for_each_entry(pos, head, member) \ + for (pos = container_of((head)->next, __typeof__(*pos), member); \ + &pos->member != (head); \ + pos = container_of(pos->member.next, __typeof__(*pos), member)) +static unsigned long jiffies = 1000; +struct ieee80211_channel { int band; int center_freq; }; +struct element { u8 id, datalen; u8 data[IEEE80211_MAX_SSID_LEN]; }; +struct cfg80211_bss { + u8 bssid[ETH_ALEN]; + struct ieee80211_channel *channel; + struct cfg80211_bss *transmitted_bss; + struct list_head nontrans_list; + /* the mock's own */ + struct element ssid; + bool linked, expired, sticky; +}; +struct wiphy { int unused; }; +struct centauri_t6050_wifi { + struct wiphy *wiphy; + bool connecting, connected, avoid_valid; + u8 ssid[IEEE80211_MAX_SSID_LEN], bssid[ETH_ALEN]; + size_t ssid_len; + u8 avoid_ssid[IEEE80211_MAX_SSID_LEN]; + size_t avoid_ssid_len; + unsigned long avoid_until; +}; +static bool ether_addr_equal(const u8 *a, const u8 *b) { return !memcmp(a, b, ETH_ALEN); } +static void ether_addr_copy(u8 *d, const u8 *s) { memcpy(d, s, ETH_ALEN); } + +#define MAX_BSS 16 +static struct cfg80211_bss bsses[MAX_BSS]; +static int n_bss, walks; +static const struct element *ieee80211_bss_get_elem(const struct cfg80211_bss *b, int id) +{ + return id == WLAN_EID_SSID ? &b->ssid : NULL; +} +static void cfg80211_bss_iter(struct wiphy *w, void *chandef, + void (*iter)(struct wiphy *, struct cfg80211_bss *, void *), void *data) +{ + walks++; + for (int i = 0; i < n_bss; i++) + if (bsses[i].linked) + iter(w, &bsses[i], data); +} +static struct cfg80211_bss *cfg80211_get_bss(struct wiphy *w, struct ieee80211_channel *ch, + const u8 *bssid, const u8 *ssid, size_t ssid_len, + int type, int privacy) +{ + for (int i = 0; i < n_bss; i++) { + struct cfg80211_bss *b = &bsses[i]; + if (b->linked && !b->expired && b->channel == ch && ether_addr_equal(b->bssid, bssid) && + (!ssid || (b->ssid.datalen == ssid_len && !memcmp(b->ssid.data, ssid, ssid_len)))) + return b; + } + return NULL; +} +/* As cfg80211: a member takes its whole set down; a sticky entry stays. */ +static void unlink_one(struct cfg80211_bss *b) { if (!b->sticky) b->linked = false; } +static void cfg80211_unlink_bss(struct wiphy *w, struct cfg80211_bss *b) +{ + struct cfg80211_bss *set = b->transmitted_bss ? b->transmitted_bss : b; + for (int i = 0; i < n_bss; i++) + if (&bsses[i] == set || bsses[i].transmitted_bss == set) + unlink_one(&bsses[i]); +} +static void cfg80211_put_bss(struct wiphy *w, struct cfg80211_bss *b) { (void)w; (void)b; } +''' + +TESTS = r''' +static struct ieee80211_channel c6a = { NL80211_BAND_6GHZ, 6135 }, c6b = { NL80211_BAND_6GHZ, 6455 }, + c5 = { NL80211_BAND_5GHZ, 5180 }; +static struct wiphy wiphy; +static struct centauri_t6050_wifi wifi; + +static void reset(const char *avoid) +{ + memset(bsses, 0, sizeof(bsses)); n_bss = 0; walks = 0; + memset(&wifi, 0, sizeof(wifi)); wifi.wiphy = &wiphy; + wifi.avoid_valid = true; wifi.avoid_until = jiffies + 120; + wifi.avoid_ssid_len = strlen(avoid); memcpy(wifi.avoid_ssid, avoid, wifi.avoid_ssid_len); +} +/* One entry; tx: its set's transmitting entry, or NULL when it transmits. */ +static struct cfg80211_bss *add(u8 last, struct ieee80211_channel *ch, const char *ssid, struct cfg80211_bss *tx) +{ + struct cfg80211_bss *b = &bsses[n_bss++]; + u8 a[ETH_ALEN] = { 2, 0, 0, 0, 0, last }; + memcpy(b->bssid, a, ETH_ALEN); b->channel = ch; b->linked = true; + b->ssid.datalen = strlen(ssid); memcpy(b->ssid.data, ssid, b->ssid.datalen); + b->nontrans_list.next = b->nontrans_list.prev = &b->nontrans_list; + b->transmitted_bss = tx; + if (tx) { /* list_add_tail(&b->nontrans_list, &tx->nontrans_list) */ + struct list_head *h = &tx->nontrans_list; + b->nontrans_list.prev = h->prev; b->nontrans_list.next = h; + h->prev->next = &b->nontrans_list; h->prev = &b->nontrans_list; + } + return b; +} +static int linked(void) { int n = 0; for (int i = 0; i < n_bss; i++) n += bsses[i].linked; return n; } + +int main(void) +{ + /* An avoided entry cfg80211 does not return, ahead of two that it does: both go. */ + reset("guest"); + struct cfg80211_bss *x = add(1, &c6a, "guest", NULL), *y = add(2, &c6b, "guest", NULL), + *z = add(3, &c6b, "guest", NULL); + x->expired = true; + avoid_unlink(&wifi, NULL); + assert(x->linked && !y->linked && !z->linked); + /* The same with one that cfg80211 does not unlink. */ + reset("guest"); + x = add(1, &c6a, "guest", NULL); y = add(2, &c6b, "guest", NULL); z = add(3, &c6b, "guest", NULL); + x->sticky = true; + avoid_unlink(&wifi, NULL); + assert(x->linked && !y->linked && !z->linked); + puts("PASS passed-over entries: each later avoided entry is still unlinked"); + + /* Two avoided entries, the first in the joined BSS's set: it stays, the second goes. */ + reset("guest"); + struct cfg80211_bss *t1 = add(0x10, &c6a, "main", NULL), *g1 = add(0x11, &c6a, "guest", t1), + *t2 = add(0x20, &c6b, "other", NULL), *g2 = add(0x21, &c6b, "guest", t2), + *g5 = add(0x30, &c5, "guest", NULL); + wifi.connected = true; memcpy(wifi.bssid, t1->bssid, ETH_ALEN); + memcpy(wifi.ssid, "guest", 5); wifi.ssid_len = 5; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && g1->linked && !t2->linked && !g2->linked && g5->linked); + puts("PASS keep: the joined BSS's set stays, another AP's set goes with its avoided profile, 5 GHz untouched"); + + /* The current network's set stays though it holds the avoided profile; others go. */ + reset("guest"); + t1 = add(0x10, &c6a, "main", NULL); g1 = add(0x11, &c6a, "guest", t1); + t2 = add(0x20, &c6b, "main", NULL); g2 = add(0x21, &c6b, "guest", t2); + struct cfg80211_bss *t3 = add(0x40, &c6b, "lab", NULL), *g3 = add(0x41, &c6b, "guest", t3); + wifi.connected = true; memcpy(wifi.bssid, (u8[]){ 2, 0, 0, 0, 0, 0x99 }, ETH_ALEN); + memcpy(wifi.ssid, "main", 4); wifi.ssid_len = 4; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && g1->linked && t2->linked && g2->linked && !t3->linked && !g3->linked); + /* Not connecting or connected: no current network, all three sets go. */ + reset("guest"); + t1 = add(0x10, &c6a, "main", NULL); g1 = add(0x11, &c6a, "guest", t1); + t2 = add(0x20, &c6b, "main", NULL); g2 = add(0x21, &c6b, "guest", t2); + memcpy(wifi.ssid, "main", 4); wifi.ssid_len = 4; + avoid_unlink(&wifi, NULL); + assert(!t1->linked && !g1->linked && !t2->linked && !g2->linked); + /* The avoided network as the current one keeps nothing but the joined BSS's set. */ + reset("guest"); + t1 = add(0x10, &c6a, "guest", NULL); t2 = add(0x20, &c6b, "guest", NULL); + wifi.connecting = true; memcpy(wifi.bssid, t1->bssid, ETH_ALEN); + memcpy(wifi.ssid, "guest", 5); wifi.ssid_len = 5; + avoid_unlink(&wifi, wifi.bssid); + assert(t1->linked && !t2->linked); + puts("PASS current network: its sets stay while connecting or connected, unless it is the avoided one"); + + /* The window over: nothing is unlinked. */ + reset("guest"); + t1 = add(0x10, &c6a, "guest", NULL); + jiffies += 1000; + avoid_unlink(&wifi, NULL); + assert(t1->linked && !wifi.avoid_valid && linked() == 1); + puts("PASS window: after it ends nothing is unlinked"); + return 0; +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--root", default=str(Path(__file__).resolve().parents[2])) + ap.add_argument("--cc", default="cc") + ap.add_argument("--negative-control", action="store_true", + help="put back the loop that re-reads a passed-over entry: the first case must fail") + args = ap.parse_args() + source = (Path(args.root) / SRC).read_text() + parts = [block(source, "bool", "avoided"), block(source, "struct", "avoid_find"), + block(source, "bool", "avoid_keep_bss"), block(source, "bool", "avoid_keep_set"), + block(source, "void", "avoid_find_one"), block(source, "void", "avoid_unlink")] + if args.negative_control: + fixed = ("\t\tif (find.count < count)\n\t\t\tcontinue;\n" + "\t\t/* Not unlinked: pass it over and look up the entry after it. */\n" + "\t\tfind.skip++;\n\t\tfind.count = 0;\n" + "\t\tcfg80211_bss_iter(wifi->wiphy, NULL, avoid_find_one, &find);\n") + if fixed not in parts[-1]: + raise RuntimeError("negative control: the pass-over walk is not in avoid_unlink()") + parts[-1] = parts[-1].replace(fixed, "\t\tif (find.count >= count)\n\t\t\tfind.skip++;\n") + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "avoid.c" + c.write_text(PRELUDE + "\n\n".join(parts) + "\n" + TESTS) + exe = Path(tmp) / "avoid" + subprocess.run([args.cc, "-std=gnu11", "-O1", "-g", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", "-fsanitize=address,undefined", str(c), "-o", str(exe)], + check=True) + rc = subprocess.run([str(exe)], timeout=60).returncode + if rc: + print(f"FAIL: the helper broke a case above (exit {rc})") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..d8d873897829fd 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -170,6 +170,7 @@ def mutations(flag, names, base, expect=KILL): 'brcmfmac-sleep-lifetime-tests.py': [([], PASS)], 'cio-native-tests.py': [(out('--output'), PASS)], 'centauri-wifi-pm-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], + 'centauri-wifi-avoid-tests.py': [([], PASS), (['--negative-control'], KILL)], 'centauri-bt-arena-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-recovery-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-physical-recovery-tests.py': [(out(), PASS)] From 80941d6d7cec702ff1c0a2aabfbf64228131e1db Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 16:45:10 -0800 Subject: [PATCH 0486/1514] wifi: apple: centauri: t6050: report no beacons from disabled channels The scan's channel list leaves out the channels the regulatory domain disables, but report_beacon() passes on any beacon whose channel the wiphy knows, disabled or not. A beacon heard on a disabled channel, for example a 6 GHz one under a country without 6 GHz, then becomes a scan entry for a channel nothing may join on. Drop such beacons, as the scan channel list already skips those channels. Only the T6050 N1 Wi-Fi driver changes (the M5 Pro, Max and Ultra). Tested on a J775D (Mac Studio, M5 Ultra). Signed-off-by: Jeff Queisser --- drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 1bd78c621770f8..8117f0967e08ff 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -419,7 +419,7 @@ static void report_beacon(struct centauri_t6050_wifi *wifi, const u8 *payload, return; frequency = ieee80211_channel_to_frequency(number, band); channel = ieee80211_get_channel(wifi->wiphy, frequency); - if (!channel) + if (!channel || channel->flags & IEEE80211_CHAN_DISABLED) return; signal = max_t(s8, payload[0x16], payload[0x17]); if (signal >= 0 || signal < -127) From c8be29eb6530e00886bc7fde34cf48efa0721793 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 16:45:12 -0800 Subject: [PATCH 0487/1514] wifi: apple: centauri: t6050: list 6 GHz networks behind another's beacon An AP that serves several networks on one radio, common at 6 GHz, beacons one of them and describes the others in a multiple-BSSID element. cfg80211 makes scan entries for those nontransmitted networks only when the wiphy sets support_mbssid, and this driver does not. So a network that is a nontransmitted profile at 6 GHz has no 6 GHz scan entry, and clients join it on 2.4 or 5 GHz only, even though the split 6 GHz scan of commit dce09c0f6d6a ("wifi: apple: centauri: t6050: let cfg80211 scan 6 GHz after the other bands") finds its APs. Set support_mbssid, which cfg80211 applies to beacons on every band; it matters most at 6 GHz. After a failed 6 GHz join, avoid_unlink() runs after every 6 GHz beacon and now also finds the avoided network's entries that cfg80211 made from another network's multiple-BSSID element. cfg80211 unlinks a beacon's networks as one set, so for that window an AP's other networks on the same radio have no 6 GHz entry either, unless their set holds the BSS being joined or used, or a BSS of the network being joined or used. They come back when the window ends or a 6 GHz join to the network succeeds. Only the T6050 N1 Wi-Fi driver changes (the M5 Pro, Max and Ultra). Tested on a J775D (Mac Studio, M5 Ultra). Signed-off-by: Jeff Queisser --- drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 8117f0967e08ff..e0e8ae0e5c8902 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -2763,6 +2763,13 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) * on the preferred scanning channels and those the 2.4/5 GHz APs report. */ wifi->wiphy->flags |= WIPHY_FLAG_SPLIT_SCAN_6GHZ; + /* + * An AP serving several networks on one radio, the rule at 6 GHz, + * beacons one of them and describes the others in a multiple-BSSID + * element. cfg80211 makes scan entries for those nontransmitted BSSes + * only with this set; the firmware joins any of them by its BSSID. + */ + wifi->wiphy->support_mbssid = true; wifi->wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM; wifi->wiphy->reg_notifier = wifi_regulatory; wifi->wiphy->cipher_suites = cipher_suites; From 0ccf128c06ce984c4bca0123dfc4fbb11aa1d51b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:04 +1100 Subject: [PATCH 0488/1514] soc: apple: rtkit: add KUnit tests The RTKit IPC library and its crashlog parser have no tests. Add two suites, included from the drivers so they reach the static handlers: apple-rtkit (27 cases) feeds apple_rtkit_rx_dispatch() the messages a co-processor sends: HELLO version negotiation (accepted, capped, refused, client versions), the endpoint map (multipart, base offsets, EARLY_CRASHLOG and CoreAnalytics flags, retained state), IOP/AP power ACKs, idle notification, buffer requests, syslog, ioreport, kdebug, CoreAnalytics and crash reports, and checks the replies. A static stub on apple_rtkit_send_message() records them, after the crashed and running checks, so no mailbox is touched. apple-rtkit-crashlog (11 cases) checks that the parser follows the containers to the right log and never reads past a truncated or malformed crashlog: each log is placed flush against the end of a vzalloc'd area, so a read past it faults the case. Mutations caught: endpoint map base, crashlog size against the space left, the footer margin and the syslog index bound. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 15 + drivers/soc/apple/rtkit-crashlog-test.c | 454 ++++++++++ drivers/soc/apple/rtkit-crashlog.c | 4 + drivers/soc/apple/rtkit-test.c | 1035 +++++++++++++++++++++++ drivers/soc/apple/rtkit.c | 12 + drivers/soc/apple/rtkit.kunitconfig | 7 + 6 files changed, 1527 insertions(+) create mode 100644 drivers/soc/apple/rtkit-crashlog-test.c create mode 100644 drivers/soc/apple/rtkit-test.c create mode 100644 drivers/soc/apple/rtkit.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..45bd3f05d70682 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -140,6 +140,21 @@ config APPLE_RTKIT Say 'y' here if you have an Apple SoC. +config APPLE_RTKIT_KUNIT_TEST + bool "KUnit tests for the Apple RTKit IPC library" if !KUNIT_ALL_TESTS + depends on APPLE_RTKIT=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Feed the RTKit receive handlers the messages a co-processor sends + (HELLO version negotiation, the endpoint map, power state ACKs, + buffer requests, syslog, ioreport, kdebug, CoreAnalytics and crash + reports) and check the replies, with the mailbox send replaced by a + static stub. Check that the crashlog parser follows containers to + the right log and never reads past a truncated or malformed + crashlog. The tests touch no hardware. + + If unsure, say N. + config APPLE_RTKIT_HELPER tristate "Apple Generic RTKit helper co-processor" depends on APPLE_RTKIT diff --git a/drivers/soc/apple/rtkit-crashlog-test.c b/drivers/soc/apple/rtkit-crashlog-test.c new file mode 100644 index 00000000000000..930f9b07d8b935 --- /dev/null +++ b/drivers/soc/apple/rtkit-crashlog-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the RTKit crashlog parser. Included by rtkit-crashlog.c. + * + * apple_rtkit_crashlog_locate() is checked for the offsets it returns. The + * dump tests place each log flush against the end of a vmalloc() area, so a + * read past the log runs into the guard page and fails the case. + */ +#include +#include +#include + +#define CL_TEST_AREA PAGE_SIZE +#define CL_TEST_ID_OUTER FOURCC('A', 'O', 'P', ' ') +#define CL_TEST_ID_INNER FOURCC('t', 's', 'k', '1') +#define CL_TEST_SECTION 16 + +struct cl_test_ctx { + struct apple_rtkit *rtk; + u8 *area; +}; + +static int cl_test_init(struct kunit *test) +{ + struct cl_test_ctx *ctx; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->rtk = kunit_kzalloc(test, sizeof(*ctx->rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->rtk); + dev = kunit_device_register(test, "apple-rtkit-crashlog-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ctx->rtk->dev = dev; + ctx->area = vzalloc(CL_TEST_AREA); + KUNIT_ASSERT_NOT_NULL(test, ctx->area); + test->priv = ctx; + return 0; +} + +static void cl_test_exit(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + + vfree(ctx->area); +} + +/* A buffer of @size bytes that ends where the vmalloc guard page begins. */ +static u8 *cl_test_tail(struct kunit *test, size_t size) +{ + struct cl_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LE(test, size, CL_TEST_AREA); + memset(ctx->area, 0, CL_TEST_AREA); + return ctx->area + CL_TEST_AREA - size; +} + +static void cl_test_put32(u8 *p, u32 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_put64(u8 *p, u64 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_log(u8 *p, u32 size, u32 flags) +{ + struct apple_rtkit_crashlog_header h = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = size, + .flags = flags, + }; + + memcpy(p, &h, sizeof(h)); +} + +static void cl_test_container(u8 *p, u32 size, u32 current_id, u32 count) +{ + struct apple_rtkit_crashlog_container c = { + .fourcc = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC, + .version = APPLE_RTKIT_CRASHLOG_CONTAINER_VERSION << 8, + .size = size, + .current_id = current_id, + .count = count, + }; + + memcpy(p, &c, sizeof(c)); +} + +static void cl_test_record(u8 *container, u32 i, u64 id, u32 offset) +{ + struct apple_rtkit_crashlog_record r = { + .id = id, + .offset = offset, + }; + + memcpy(container + sizeof(struct apple_rtkit_crashlog_container) + i * sizeof(r), + &r, sizeof(r)); +} + +/* A section header: its fourcc and its size, which counts the header. */ +static u8 *cl_test_section(u8 *p, u32 fourcc, u32 size) +{ + cl_test_put32(p, fourcc); + cl_test_put32(p + 12, size); + return p + size; +} + +static int cl_test_locate(const u8 *bfr, size_t size, size_t *offset, u32 *id, + unsigned int *depth) +{ + *offset = ~0; + *id = ~0; + *depth = ~0; + return apple_rtkit_crashlog_locate(bfr, size, offset, id, depth); +} + +static void cl_test_locate_bare(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0); + KUNIT_EXPECT_EQ(test, id, 0); + KUNIT_EXPECT_EQ(test, depth, 0); + + /* A bare log is taken as it is, even marked as still being written. */ + cl_test_log(bfr, 0x40, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); +} + +static void cl_test_locate_bare_invalid(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_log(bfr, sizeof(struct apple_rtkit_crashlog_header) - 1, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_put32(bfr, FOURCC('C', 'L', 'H', 'F')); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + + /* Shorter than a header: nothing is read past the end. */ + bfr = cl_test_tail(test, sizeof(struct apple_rtkit_crashlog_header) - 1); + cl_test_put32(bfr, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x1f, &offset, &id, &depth), -EINVAL); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x200); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_container(bfr, 0x200, CL_TEST_ID_OUTER, 2); + cl_test_record(bfr, 0, FOURCC('o', 't', 'h', 'r'), 0x80); + cl_test_record(bfr, 1, CL_TEST_ID_OUTER, 0x100); + cl_test_log(bfr + 0x80, 0x40, 0); + cl_test_log(bfr + 0x100, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x100); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_OUTER); + KUNIT_EXPECT_EQ(test, depth, 1); + + /* The selected log may fill the rest of the buffer, but no more. */ + cl_test_log(bfr + 0x100, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EINVAL); + + /* A log still being written is retried later. */ + cl_test_log(bfr + 0x100, 0x100, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EAGAIN); +} + +static void cl_test_locate_nested(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x400); + unsigned int depth; + size_t offset; + u32 id; + + /* Per-coprocessor, then per-task: offsets are from each container. */ + cl_test_container(bfr, 0x400, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + cl_test_container(bfr + 0x100, 0x300, CL_TEST_ID_INNER, 2); + cl_test_record(bfr + 0x100, 0, FOURCC('t', 's', 'k', '0'), 0x80); + cl_test_record(bfr + 0x100, 1, CL_TEST_ID_INNER, 0x200); + cl_test_log(bfr + 0x300, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x300); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_INNER); + KUNIT_EXPECT_EQ(test, depth, 2); + + /* + * The inner log's size is checked against what follows it, not against + * the whole buffer: 0x180 fits the buffer but not the space left. + */ + cl_test_log(bfr + 0x300, 0x180, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); + + /* The same for an inner container claiming more than is left. */ + cl_test_log(bfr + 0x300, 0x100, 0); + cl_test_container(bfr + 0x100, 0x301, CL_TEST_ID_INNER, 2); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_bad_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + +#define CL_TEST_RESET() do { \ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 1); \ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); \ + cl_test_log(bfr + 0x80, 0x80, 0); \ + } while (0) + + CL_TEST_RESET(); + KUNIT_ASSERT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + + /* Another container version. */ + cl_test_put32(bfr + 4, 3 << 8); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + CL_TEST_RESET(); + /* Larger than the buffer. */ + cl_test_container(bfr, 0x101, CL_TEST_ID_OUTER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No records, or more than the buffer can hold. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, (0x100 - 0x14) / 0x18 + 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No record has the current ID. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_INNER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record pointing back into its container, at its end, or past it. */ + CL_TEST_RESET(); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x13); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xffffffff); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record leading to too little for a header. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xf0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); +#undef CL_TEST_RESET +} + +static void cl_test_locate_depth(struct kunit *test) +{ + unsigned int max = APPLE_RTKIT_CRASHLOG_CONTAINER_MAX_DEPTH, depth, i; + size_t len = 0x40 * (max + 2), offset; + u8 *bfr = cl_test_tail(test, len); + u32 id; + + /* @max containers, each leading 0x40 bytes on, then a log. */ + for (i = 0; i < max; i++) { + cl_test_container(bfr + 0x40 * i, len - 0x40 * i, i + 1, 1); + cl_test_record(bfr + 0x40 * i, 0, i + 1, 0x40); + } + cl_test_log(bfr + 0x40 * max, 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, depth, max); + KUNIT_EXPECT_EQ(test, offset, 0x40 * max); + KUNIT_EXPECT_EQ(test, id, max); + + /* One container more is too deep. */ + cl_test_container(bfr + 0x40 * max, len - 0x40 * max, max + 1, 1); + cl_test_record(bfr + 0x40 * max, 0, max + 1, 0x40); + cl_test_log(bfr + 0x40 * (max + 1), 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), -EINVAL); +} + +/* Every decoder, ending with a footer. The dump must reach it in bounds. */ +static void cl_test_dump_full(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x30 + 0x30 + 0x18 + (28 + 2 * 24) + (16 + 0x350) + + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + 0x30 + 0x10 + CL_TEST_SECTION; + u8 *bfr = cl_test_tail(test, len), *p; + + cl_test_log(bfr, len, 0); + p = bfr + 0x20; + memcpy(p + 20, "panic: test\nsecond line", 23); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_STR, 0x30); + memset(p + 16, 'v', 0x30 - 16); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_VERSION, 0x30); + cl_test_put64(p + 16, 1234); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_TIME, 0x18); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_MBOX, 28 + 2 * 24); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS, 16 + 0x350); + cl_test_put32(p + APPLE_RTKIT_CRASHLOG_CL4_SIZE, APPLE_RTKIT_CRASHLOG_CL4_NOMINAL_SIZE); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + p = cl_test_section(p, FOURCC('C', 'c', 's', 't'), 0x30); + /* An empty unknown section: a header only. */ + p = cl_test_section(p, FOURCC('C', 'x', 'y', 'z'), 0x10); + cl_test_section(p, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, CL_TEST_SECTION); + KUNIT_ASSERT_PTR_EQ(test, p + CL_TEST_SECTION, bfr + len); + + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +/* + * The last section of a log without a footer: its decoder could read 16 + * bytes past the log, so it is not decoded. + */ +static void cl_test_dump_no_footer(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_STR, APPLE_RTKIT_CRASHLOG_VERSION, + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_TIME, + FOURCC('C', 'c', 's', 't'), + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x40; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + /* No newline and no terminator: Cstr must stop at the section. */ + memset(bfr + 0x20 + 16, 'x', 0x40 - 16); + cl_test_section(bfr + 0x20, fourccs[i], 0x40); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_bad_sizes(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x80; + u8 *bfr = cl_test_tail(test, len); + + /* A log claiming more than the buffer. */ + cl_test_log(bfr, len + 0x1000, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 0x800); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section larger than what is left of the log. */ + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 1); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* Sizes that would never advance or underflow a decoder. */ + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 0); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 15); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section header cut off by the end of the log. */ + bfr = cl_test_tail(test, 0x28); + cl_test_log(bfr, 0x28, 0); + cl_test_put32(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, 0x28); + + /* Too small for a header. */ + apple_rtkit_crashlog_dump(ctx->rtk, cl_test_tail(test, 0x1f), 0x1f); + KUNIT_SUCCEED(test); +} + +/* Sections too small for their decoders are skipped, not decoded. */ +static void cl_test_dump_small_sections(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_REGS, + APPLE_RTKIT_CRASHLOG_REGS_CL4, APPLE_RTKIT_CRASHLOG_TIME, + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x10 + CL_TEST_SECTION; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, fourccs[i], 0x10); + cl_test_section(bfr + 0x30, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + CL_TEST_SECTION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + + /* A Crl4 frame of another size is not decoded either. */ + len = 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + CL_TEST_SECTION; + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_put32(bfr + 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SIZE, 0xd0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_container(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x100; + u8 *bfr = cl_test_tail(test, len); + + /* The selected log ends the buffer; its last section has no footer. */ + cl_test_container(bfr, len, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); + cl_test_log(bfr + 0x80, 0x80, 0); + memset(bfr + 0xa0 + 16, 'x', 0x60 - 16); + cl_test_section(bfr + 0xa0, APPLE_RTKIT_CRASHLOG_VERSION, 0x60); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A container whose record leads past the end is not followed. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x1000); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static struct kunit_case apple_rtkit_crashlog_test_cases[] = { + KUNIT_CASE(cl_test_locate_bare), + KUNIT_CASE(cl_test_locate_bare_invalid), + KUNIT_CASE(cl_test_locate_container), + KUNIT_CASE(cl_test_locate_nested), + KUNIT_CASE(cl_test_locate_bad_container), + KUNIT_CASE(cl_test_locate_depth), + KUNIT_CASE(cl_test_dump_full), + KUNIT_CASE(cl_test_dump_no_footer), + KUNIT_CASE(cl_test_dump_bad_sizes), + KUNIT_CASE(cl_test_dump_small_sections), + KUNIT_CASE(cl_test_dump_container), + {} +}; + +static struct kunit_suite apple_rtkit_crashlog_test_suite = { + .name = "apple-rtkit-crashlog", + .init = cl_test_init, + .exit = cl_test_exit, + .test_cases = apple_rtkit_crashlog_test_cases, +}; + +kunit_test_suite(apple_rtkit_crashlog_test_suite); diff --git a/drivers/soc/apple/rtkit-crashlog.c b/drivers/soc/apple/rtkit-crashlog.c index 81c5af4e29fc04..47335bf11c493a 100644 --- a/drivers/soc/apple/rtkit-crashlog.c +++ b/drivers/soc/apple/rtkit-crashlog.c @@ -492,3 +492,7 @@ void apple_rtkit_crashlog_dump(struct apple_rtkit *rtk, u8 *bfr, size_t size) dev_warn(rtk->dev, "RTKit: End of crashlog reached but no footer present"); } + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include "rtkit-crashlog-test.c" +#endif diff --git a/drivers/soc/apple/rtkit-test.c b/drivers/soc/apple/rtkit-test.c new file mode 100644 index 00000000000000..aba873abbe37c1 --- /dev/null +++ b/drivers/soc/apple/rtkit-test.c @@ -0,0 +1,1035 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple RTKit IPC library. Included by rtkit.c. + * + * The tests drive the receive handlers with messages a co-processor would + * send and check the replies. apple_rtkit_send_message() is redirected to a + * static stub just before the mailbox write, so its crashed and running + * checks still run; shared buffers come from a fake shmem_setup_ep. No + * mailbox, IOMMU or MMIO is touched. + */ +#include +#include +#include + +#define RTK_TEST_MAX_SENT 32 +#define RTK_TEST_IOVA_BASE 0x10000000 + +struct rtk_test_msg { + u8 ep; + u64 msg; +}; + +struct rtk_test_ctx { + struct kunit *test; + struct apple_rtkit *rtk; + struct apple_rtkit_ops ops; + + struct rtk_test_msg sent[RTK_TEST_MAX_SENT]; + unsigned int n_sent; + + unsigned int n_setup; + u8 setup_ep; + struct apple_rtkit_shmem setup_req; + int setup_ret; + dma_addr_t next_iova; + /* Written to each new buffer, as a log the firmware already wrote. */ + const void *prefill; + size_t prefill_len; + + unsigned int n_crashed; + size_t crashed_size; + u32 crashed_fourcc; + + unsigned int n_syslog; + char syslog_ctx[24]; + char syslog_msg[64]; + + unsigned int n_recv; + u8 recv_ep; + u64 recv_msg; +}; + +static int rtk_test_send(struct apple_rtkit *rtk, u8 ep, u64 message, + struct completion *completion, bool atomic) +{ + struct rtk_test_ctx *ctx = rtk->cookie; + + if (ctx->n_sent < RTK_TEST_MAX_SENT) { + ctx->sent[ctx->n_sent].ep = ep; + ctx->sent[ctx->n_sent].msg = message; + } + ctx->n_sent++; + return 0; +} + +static int rtk_test_shmem_setup(void *cookie, u8 ep, struct apple_rtkit_shmem *bfr) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_setup++; + ctx->setup_ep = ep; + ctx->setup_req = *bfr; + if (ctx->setup_ret) + return ctx->setup_ret; + + bfr->buffer = kunit_kzalloc(ctx->test, bfr->size, GFP_KERNEL); + if (!bfr->buffer) + return -ENOMEM; + if (ctx->prefill) + memcpy(bfr->buffer, ctx->prefill, min(ctx->prefill_len, bfr->size)); + if (bfr->iova) { + /* A buffer the co-processor placed at its own address. */ + bfr->is_mapped = true; + } else { + bfr->iova = ctx->next_iova; + ctx->next_iova += SZ_1M; + } + return 0; +} + +static void rtk_test_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +{ +} + +static void rtk_test_crashed(void *cookie, const void *crashlog, size_t size) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_crashed++; + ctx->crashed_size = size; + ctx->crashed_fourcc = 0; + if (crashlog && size >= sizeof(u32)) + memcpy(&ctx->crashed_fourcc, crashlog, sizeof(u32)); +} + +static bool rtk_test_syslog_is_debug(void *cookie, const char *context, + const char *message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_syslog++; + strscpy(ctx->syslog_ctx, context, sizeof(ctx->syslog_ctx)); + strscpy(ctx->syslog_msg, message, sizeof(ctx->syslog_msg)); + return true; +} + +static void rtk_test_recv(void *cookie, u8 endpoint, u64 message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_recv++; + ctx->recv_ep = endpoint; + ctx->recv_msg = message; +} + +static int rtk_test_init(struct kunit *test) +{ + struct rtk_test_ctx *ctx; + struct apple_rtkit *rtk; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + rtk = kunit_kzalloc(test, sizeof(*rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk); + dev = kunit_device_register(test, "apple-rtkit-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + ctx->test = test; + ctx->rtk = rtk; + ctx->next_iova = RTK_TEST_IOVA_BASE; + ctx->ops.crashed = rtk_test_crashed; + ctx->ops.recv_message = rtk_test_recv; + ctx->ops.shmem_setup_ep = rtk_test_shmem_setup; + ctx->ops.shmem_destroy = rtk_test_shmem_destroy; + ctx->ops.syslog_is_debug = rtk_test_syslog_is_debug; + + rtk->dev = dev; + rtk->cookie = ctx; + rtk->ops = &ctx->ops; + rtk->handshake_timeout_ms = APPLE_RTKIT_HANDSHAKE_TIMEOUT_MS; + init_completion(&rtk->epmap_completion); + init_completion(&rtk->coreanalytics_completion); + init_completion(&rtk->iop_pwr_ack_completion); + init_completion(&rtk->ap_pwr_ack_completion); + init_completion(&rtk->strict_idle_done); + INIT_KFIFO(rtk->sync_ack_fifo); + INIT_KFIFO(rtk->m5_saved.deferred); + INIT_DELAYED_WORK(&rtk->crashlog_late_work, apple_rtkit_crashlog_late); + rtk->wq = alloc_ordered_workqueue("apple-rtkit-test", 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->wq); + + kunit_activate_static_stub(test, apple_rtkit_send_message, rtk_test_send); + test->priv = ctx; + return 0; +} + +static void rtk_test_exit(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + cancel_delayed_work_sync(&rtk->crashlog_late_work); + destroy_workqueue(rtk->wq); + kfree(rtk->syslog_msg_buffer); +} + +static u64 rtk_test_mgmt(u8 type, u64 payload) +{ + return FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, type) | payload; +} + +static u64 rtk_test_hello(unsigned int min_ver, unsigned int max_ver) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, min_ver) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, max_ver)); +} + +static u64 rtk_test_epmap(u32 base, u32 bitmap, bool last) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, base) | + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BITMAP, bitmap) | + (last ? APPLE_RTKIT_MGMT_EPMAP_LAST : 0)); +} + +static u64 rtk_test_startep(u8 ep) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_STARTEP, + FIELD_PREP(APPLE_RTKIT_MGMT_STARTEP_EP, ep) | + APPLE_RTKIT_MGMT_STARTEP_FLAG); +} + +static u64 rtk_test_buffer_request(u8 type, size_t size, u64 iova) +{ + return FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, type) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_SIZE, size >> 12) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_IOVA, iova); +} + +static void rtk_test_expect_sent(struct kunit *test, unsigned int i, u8 ep, u64 msg) +{ + struct rtk_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LT(test, i, ctx->n_sent); + KUNIT_ASSERT_LT(test, i, RTK_TEST_MAX_SENT); + KUNIT_EXPECT_EQ(test, ctx->sent[i].ep, ep); + KUNIT_EXPECT_EQ(test, ctx->sent[i].msg, msg); +} + +static void rtk_test_hello_accepts_supported(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 reply12 = rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 12) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 12)); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 12); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, reply12); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + + /* A newer remote maximum settles on the highest version supported here. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 14), false, 0); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, reply12); + + /* Both ends of the supported range are accepted alone. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, reply12); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(1, 11), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_hello_rejects_unsupported(struct kunit *test) +{ + static const struct { unsigned int min, max; } bad[] = { + { 13, 14 }, /* minimum too new */ + { 9, 10 }, /* maximum too old */ + }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + int i; + + for (i = 0; i < ARRAY_SIZE(bad); i++) { + reinit_completion(&rtk->epmap_completion); + rtk->boot_result = 0; + rtk->version = 0; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_hello(bad[i].min, bad[i].max), false, 0); + KUNIT_EXPECT_EQ_MSG(test, rtk->boot_result, -EINVAL, "range %u..%u", + bad[i].min, bad[i].max); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, rtk->version, 0); + } + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_hello_client_version(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.protocol_version = 11; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + + /* The client's exact version outside the remote range aborts the boot. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EINVAL); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_epmap_starts_system_endpoints(struct kunit *test) +{ + static const u8 started[] = { 1, 2, 3, 4, 8, 0xa }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + /* mgmt, crashlog, syslog, debug, ioreport, 5 (unknown), 7, oslog, tracekit */ + u32 bitmap = BIT(0) | BIT(1) | BIT(2) | BIT(3) | BIT(4) | BIT(5) | + BIT(7) | BIT(8) | BIT(0xa); + int i; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_epmap(0, bitmap, true), + false, 0); + + for (i = 0; i < 32; i++) + KUNIT_EXPECT_EQ_MSG(test, apple_rtkit_has_endpoint(rtk, i), + !!(bitmap & BIT(i)), "endpoint %d", i); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1 + ARRAY_SIZE(started)); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + for (i = 0; i < ARRAY_SIZE(started); i++) { + rtk_test_expect_sent(test, 1 + i, APPLE_RTKIT_EP_MGMT, + rtk_test_startep(started[i])); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, started[i])); + } + /* Neither management, an unknown system endpoint nor CoreAnalytics. */ + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 5)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 7)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_multipart(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(2), false), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_REPLY_MORE)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 2)); + + /* The second part: endpoints 0x20 and 0x37 are application endpoints. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0) | BIT(0x17), true), false, 0); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x37)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 1)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 0x17)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, 1) | + APPLE_RTKIT_MGMT_EPMAP_LAST)); + /* Only system endpoints are started by RTKit itself. */ + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(2)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_flags(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS | APPLE_RTKIT_EARLY_CRASHLOG; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(7), true), false, 0); + + /* The crash log is started before the map is acknowledged, and only once. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, rtk_test_startep(1)); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(7)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 7)); +} + +static void rtk_test_epmap_retained(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->retained_wake = true; + set_bit(1, rtk->started); + set_bit(2, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(2) | BIT(4), true), + false, 0); + /* The started endpoints are echoed and nothing is started again. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + BIT(1) | BIT(2) | APPLE_RTKIT_MGMT_EPMAP_LAST)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + + /* A started endpoint missing from the map fails the wake. */ + reinit_completion(&rtk->epmap_completion); + set_bit(4 + 32, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0), true), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_power_acks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_ON), false, 0); + KUNIT_EXPECT_EQ(test, rtk->iop_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + + /* Bits above the 16-bit state field are not part of the state. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK, + BIT_ULL(40) | APPLE_RTKIT_PWR_STATE_ON), + false, 0); + KUNIT_EXPECT_EQ(test, rtk->ap_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_running(rtk)); + + rtk->crashed = true; + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_crashed(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_retained_quiesced(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 quiesced = rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_QUIESCED); + + rtk->retained_wake = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + /* One ON request, and still waiting for ON. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE, + APPLE_RTKIT_PWR_STATE_ON)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->iop_pwr_ack_completion)); + + /* A second QUIESCED is not asked again: it fails the wake. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_idle_notify(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->strict_idle_waiting = true; + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + /* A nonzero argument is not the idle notification. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 1), false, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->strict_idle_done)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 0), false, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->strict_idle_done)); + + /* Unknown management messages are dropped without a reply. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_mgmt(0x3f, 0), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_send_checks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + set_bit(0x20, rtk->endpoints); + /* Application endpoints need a running co-processor. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), -EINVAL); + /* An undiscovered endpoint cannot be started. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_ON; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_ON; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, 0x20, 0x1234); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, rtk_test_startep(0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + + /* Nothing is sent to a crashed co-processor, not even management. */ + rtk->crashed = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0, 0, NULL, false), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_app_endpoint_dispatch(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, 0x37, 0xdeadbeefcafeull, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->recv_ep, 0x37); + KUNIT_EXPECT_EQ(test, ctx->recv_msg, 0xdeadbeefcafeull); + + /* Nothing is delivered once teardown has started. */ + rtk->shutting_down = true; + apple_rtkit_rx_dispatch(rtk, 0x37, 1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_buffer_reply(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, 0); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_IOREPORT); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.iova, RTK_TEST_IOVA_BASE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, + RTK_TEST_IOVA_BASE)); + + /* An identical request is answered again without a new buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->sent[1].msg, ctx->sent[0].msg); + + /* A changed geometry is refused while the buffer is live. */ + req = rtk_test_buffer_request(1, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EBUSY); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + + /* ioreport's two unknown notifications are echoed, others dropped. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x9), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 4); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc)); +} + +static void rtk_test_buffer_request_invalid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req; + + /* A zero size is never set up. */ + req = rtk_test_buffer_request(1, 0, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + + /* A failed setup leaves no buffer behind and sends no reply. */ + ctx->setup_ret = -ENOMEM; + req = rtk_test_buffer_request(1, SZ_4K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->syslog_buffer, + APPLE_RTKIT_EP_SYSLOG, req), + -ENOMEM); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, 0); + ctx->setup_ret = 0; + + /* Without a setup callback, a placed buffer cannot be mapped. */ + ctx->ops.shmem_setup_ep = NULL; + req = rtk_test_buffer_request(1, SZ_4K, 0x8000); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_placed_buffers(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(1, SZ_16K, 0xabc000); + + /* A placed buffer is acknowledged with its request, unchanged. */ + ctx->ops.flags = APPLE_RTKIT_COPROC_PLACES_BUFFERS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0xabc000); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_TRUE(test, rtk->ioreport_buffer.is_mapped); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, req); + + /* A firmware-owned log buffer is taken as it is, unmapped and unanswered. */ + ctx->ops.flags = APPLE_RTKIT_FIRMWARE_OWNED_LOGS; + req = rtk_test_buffer_request(1, SZ_8K, 0xdef000); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_TRUE(test, rtk->syslog_buffer.is_mapped); + KUNIT_EXPECT_NULL(test, rtk->syslog_buffer.buffer); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.iova, 0xdef000); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, SZ_8K); + + /* Its records are still acknowledged, without being read. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG), + false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); +} + +static void rtk_test_oslog_buffer_request(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K); + + /* oslog carries its size unshifted and its IOVA in 4 KiB pages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_OSLOG); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_OSLOG, + FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, RTK_TEST_IOVA_BASE >> 12)); + + apple_rtkit_free_buffer(rtk, &rtk->oslog_buffer); + req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_8K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, 0x12345); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0x12345000); + KUNIT_EXPECT_EQ(test, rtk->oslog_buffer.iova, 0x12345000); +} + +/* Builds a syslog ring of four entries with a 0x40-byte message each. */ +static void rtk_test_syslog_setup(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + size_t entry_size = 0x20 + 0x40; + u8 *entry; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + rtk_test_buffer_request(1, SZ_8K, 0), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_buffer.buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_MSG_SIZE, 0x40), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_msg_buffer); + KUNIT_ASSERT_EQ(test, rtk->syslog_n_entries, 4); + KUNIT_ASSERT_EQ(test, rtk->syslog_msg_size, 0x40); + + entry = rtk->syslog_buffer.buffer + 1 * entry_size; + strscpy(entry + 8, "ctx", 24); + strscpy(entry + 8 + 24, "hello rtkit \r\n", 0x40); + /* Entry 4 is past the ring the firmware described, but inside the buffer. */ + entry = rtk->syslog_buffer.buffer + 4 * entry_size; + strscpy(entry + 8, "stale", 24); + strscpy(entry + 8 + 24, "not a record", 0x40); + ctx->n_sent = 0; +} + +static void rtk_test_syslog_log(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log1 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 1; + + rtk_test_syslog_setup(test); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 1); + KUNIT_EXPECT_STREQ(test, ctx->syslog_ctx, "ctx"); + /* Trailing whitespace is cropped. */ + KUNIT_EXPECT_STREQ(test, ctx->syslog_msg, "hello rtkit"); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log1); +} + +static void rtk_test_syslog_index_range(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log4 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 4; + u64 log_ff = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 0xff; + + rtk_test_syslog_setup(test); + /* Records past the ring are not read, but still acknowledged. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log4, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log_ff, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log4); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_SYSLOG, log_ff); +} + +static void rtk_test_syslog_no_geometry(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log0 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG); + + rtk_test_syslog_setup(test); + /* A zero-sized INIT drops the message buffer rather than kzalloc(0). */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4), false, 0); + KUNIT_EXPECT_NULL(test, rtk->syslog_msg_buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + + /* An inherited session cannot read the ring either. */ + rtk->syslog_inherited = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_kdebug(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 get = FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_GET_BUFFER); + + rtk->sync_syslog_ack = true; + /* No entries, and more than the cap, are refused before any setup. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, get, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, + APPLE_RTKIT_KDEBUG_BUF0_MAX / + APPLE_RTKIT_KDEBUG_ENTRY_SIZE + 1), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | APPLE_RTKIT_KDEBUG_DATA, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + /* 16 entries round up to one aligned buffer, plus the fixed second one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer0.size, APPLE_RTKIT_KDEBUG_BUF_ALIGN); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer1.size, APPLE_RTKIT_KDEBUG_BUF1_SIZE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER0) | + RTK_TEST_IOVA_BASE); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER1) | + (RTK_TEST_IOVA_BASE + SZ_1M)); + + /* A repeated request of the same size reuses both buffers. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 4); +} + +static void rtk_test_coreanalytics_encoding(struct kunit *test) +{ + u64 reply; + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_4K | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3)), + 0x3000); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_1M | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0x200000); + /* Without a unit there is no size. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0); + + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x3000, 0x40000, &reply), 0); + KUNIT_EXPECT_EQ(test, reply, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3) | APPLE_RTKIT_CA_UNIT_4K | 0x40000); + /* A partial unit rounds up; a megabyte or more counts in megabytes. */ + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x2001, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 3); + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x180000, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 2); + KUNIT_EXPECT_TRUE(test, reply & APPLE_RTKIT_CA_UNIT_1M); + KUNIT_EXPECT_FALSE(test, reply & APPLE_RTKIT_CA_UNIT_4K); + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0, 0, &reply), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0x1000, BIT_ULL(44), &reply), + -EINVAL); + /* 256 MiB needs a count of 256, which the 8-bit field cannot hold. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(SZ_256M, 0, &reply), -EINVAL); +} + +static void rtk_test_coreanalytics_rx(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REQUEST) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4); + u64 event = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234) | 0xff; + + /* A client that asks for CoreAnalytics, as the PMP does. */ + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_COREANALYTICS); + KUNIT_EXPECT_EQ(test, rtk->coreanalytics_buffer.size, 0x4000); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->coreanalytics_completion)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4) | + RTK_TEST_IOVA_BASE); + + /* A duplicate request never replaces the live buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + + /* An event is acknowledged with its ID only. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, event, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT_ACK) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234)); +} + +static void rtk_test_crashlog_handshake_then_crash(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_CRASHLOG_CRASH, SZ_4K, 0); + struct apple_rtkit_crashlog_header *hdr; + + set_bit(APPLE_RTKIT_EP_CRASHLOG, rtk->endpoints); + /* In a handshaked session the first message is the buffer request. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_FALSE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, SZ_4K); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_4K, + RTK_TEST_IOVA_BASE)); + + /* The firmware writes a log, then reports the crash. */ + hdr = rtk->crashlog_buffer.buffer; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = sizeof(*hdr); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + + /* Unknown crashlog messages are ignored; a crashed IOP gets no messages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 2), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, APPLE_RTKIT_EP_MGMT, 0, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_crashlog_report_only(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header log = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = sizeof(log), + }; + + /* + * An undiscovered crashlog endpoint only reports crashes; the client's + * setup maps the buffer, which already holds the log. + */ + ctx->prefill = &log; + ctx->prefill_len = sizeof(log); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); +} + +static void rtk_test_crashlog_unreadable(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* A buffer holding no log yet: the crash is reported without one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + /* ...and the log is looked for again later. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&rtk->crashlog_late_work)); + cancel_delayed_work_sync(&rtk->crashlog_late_work); +} + +static void rtk_test_crashlog_no_mapping(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* No setup callback and no IOMMU domain: the crash is still reported. */ + ctx->ops.shmem_setup_ep = NULL; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_crashlog_header_valid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header *hdr; + u32 *words; + + rtk->crashlog_buffer.size = 0x100; + rtk->crashlog_buffer.buffer = kunit_kzalloc(test, 0x100, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk->crashlog_buffer.buffer); + hdr = rtk->crashlog_buffer.buffer; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x100; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = 0x101; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* A container is valid when its current record leads to a log. */ + words = rtk->crashlog_buffer.buffer; + memset(words, 0, 0x100); + words[0] = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC; + words[1] = 0x200; /* version 2 */ + words[2] = 0x100; /* size */ + words[3] = 0x41; /* current id */ + words[4] = 1; /* one record */ + /* record 0 at 0x14: id (u64), unknown (u64), offset (u32) */ + words[5] = 0x41; + words[9] = 0x80; + hdr = rtk->crashlog_buffer.buffer + 0x80; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x80; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + words[3] = 0x42; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* Too small for a header at all. */ + rtk->crashlog_buffer.size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static struct kunit_case apple_rtkit_test_cases[] = { + KUNIT_CASE(rtk_test_hello_accepts_supported), + KUNIT_CASE(rtk_test_hello_rejects_unsupported), + KUNIT_CASE(rtk_test_hello_client_version), + KUNIT_CASE(rtk_test_epmap_starts_system_endpoints), + KUNIT_CASE(rtk_test_epmap_multipart), + KUNIT_CASE(rtk_test_epmap_flags), + KUNIT_CASE(rtk_test_epmap_retained), + KUNIT_CASE(rtk_test_power_acks), + KUNIT_CASE(rtk_test_retained_quiesced), + KUNIT_CASE(rtk_test_idle_notify), + KUNIT_CASE(rtk_test_send_checks), + KUNIT_CASE(rtk_test_app_endpoint_dispatch), + KUNIT_CASE(rtk_test_buffer_reply), + KUNIT_CASE(rtk_test_buffer_request_invalid), + KUNIT_CASE(rtk_test_placed_buffers), + KUNIT_CASE(rtk_test_oslog_buffer_request), + KUNIT_CASE(rtk_test_syslog_log), + KUNIT_CASE(rtk_test_syslog_index_range), + KUNIT_CASE(rtk_test_syslog_no_geometry), + KUNIT_CASE(rtk_test_kdebug), + KUNIT_CASE(rtk_test_coreanalytics_encoding), + KUNIT_CASE(rtk_test_coreanalytics_rx), + KUNIT_CASE(rtk_test_crashlog_handshake_then_crash), + KUNIT_CASE(rtk_test_crashlog_report_only), + KUNIT_CASE(rtk_test_crashlog_unreadable), + KUNIT_CASE(rtk_test_crashlog_no_mapping), + KUNIT_CASE(rtk_test_crashlog_header_valid), + {} +}; + +static struct kunit_suite apple_rtkit_test_suite = { + .name = "apple-rtkit", + .init = rtk_test_init, + .exit = rtk_test_exit, + .test_cases = apple_rtkit_test_cases, +}; + +kunit_test_suite(apple_rtkit_test_suite); diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..0d0a414db0515e 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -21,6 +21,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include +#endif + enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00, /* power off, cannot be restarted */ APPLE_RTKIT_PWR_STATE_SLEEP = 0x01, /* sleeping, can be restarted */ @@ -1752,6 +1756,10 @@ int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 message, */ dma_wmb(); +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_rtkit_send_message, rtk, ep, message, + completion, atomic); +#endif return apple_mbox_send(rtk->mbox, msg, atomic); } EXPORT_SYMBOL_GPL(apple_rtkit_send_message); @@ -3549,3 +3557,7 @@ MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple RTKit driver"); #include "rtkit-v27-late.inc" + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include "rtkit-test.c" +#endif diff --git a/drivers/soc/apple/rtkit.kunitconfig b/drivers/soc/apple/rtkit.kunitconfig new file mode 100644 index 00000000000000..40593c9ce46bb3 --- /dev/null +++ b/drivers/soc/apple/rtkit.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_RTKIT_KUNIT_TEST=y From 0790532fd6a54c30b6d83ae6fdd4b2f7013f2274 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:05 +1100 Subject: [PATCH 0489/1514] iommu: io-pgtable-dart: add KUnit tests The Apple DART page table code has no tests; apple-dart-test.c maps a single page. Add the io-pgtable-dart suite (15 cases, 31 with parameters), included from io-pgtable-dart.c: - the table layout chosen for DART1 4K/16K and DART2 16K granules and input sizes (levels, bits per level, 1 or 4 TTBRs), and the refused configurations; - exact leaf and table PTE encodings for both formats, against hand-computed values; - map/unmap/iova_to_phys across leaf table ends, at the top of an L1 table, through four levels and across the TTBR split, with -EEXIST, -EINVAL and -ERANGE refusals that write nothing; - that teardown frees every table page (NR_IOMMU_PAGES back to the baseline). Mutations caught: the DART2 output address shift, the index mask, the DART2 read/write bits swapped and a table page leaked at teardown. Signed-off-by: Ryan Murray --- drivers/iommu/Kconfig | 13 + drivers/iommu/io-pgtable-dart-test.c | 793 ++++++++++++++++++++++ drivers/iommu/io-pgtable-dart.c | 4 + drivers/iommu/io-pgtable-dart.kunitconfig | 4 + 4 files changed, 814 insertions(+) create mode 100644 drivers/iommu/io-pgtable-dart-test.c create mode 100644 drivers/iommu/io-pgtable-dart.kunitconfig diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig index 4233b253b06e2c..f2275eb0474dbc 100644 --- a/drivers/iommu/Kconfig +++ b/drivers/iommu/Kconfig @@ -81,6 +81,19 @@ config IOMMU_IO_PGTABLE_DART If unsure, say N here. +config IOMMU_IO_PGTABLE_DART_KUNIT_TEST + bool "KUnit tests for Apple DART page tables" if !KUNIT_ALL_TESTS + depends on IOMMU_IO_PGTABLE_DART && KUNIT=y + default KUNIT_ALL_TESTS + help + Enable KUnit tests for the Apple DART page table allocator. They + check the table layout chosen for each format, granule and input + size, the DART and DART2 PTE encodings, map/unmap/iova_to_phys + across table boundaries, rejection of invalid requests and that + teardown frees every table page. + + If unsure, say N here. + endmenu config IOMMU_DEBUGFS diff --git a/drivers/iommu/io-pgtable-dart-test.c b/drivers/iommu/io-pgtable-dart-test.c new file mode 100644 index 00000000000000..7a68c11003ebd9 --- /dev/null +++ b/drivers/iommu/io-pgtable-dart-test.c @@ -0,0 +1,793 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple DART page table formats. + * + * Included by io-pgtable-dart.c so that the table walkers can be checked + * against hand-computed table indexes and PTE encodings. + */ +#include +#include +#include +#include +#include +#include + +/* Leaf subpage protection: start 0, end 0xfff (whole page). */ +#define DART_TEST_SUBPAGE_ALL (0xfffULL << 40) + +struct dart_test { + struct device *dev; + struct io_pgtable_cfg cfg; + struct io_pgtable_ops *ops; + unsigned int tlb_add_page; + unsigned int tlb_other; + unsigned long tlb_last_iova; + size_t tlb_last_granule; +}; + +static void dart_test_tlb_flush_all(void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_flush_walk(unsigned long iova, size_t size, + size_t granule, void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_add_page(struct iommu_iotlb_gather *gather, + unsigned long iova, size_t granule, + void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_add_page++; + t->tlb_last_iova = iova; + t->tlb_last_granule = granule; +} + +static const struct iommu_flush_ops dart_test_flush_ops = { + .tlb_flush_all = dart_test_tlb_flush_all, + .tlb_flush_walk = dart_test_tlb_flush_walk, + .tlb_add_page = dart_test_tlb_add_page, +}; + +KUNIT_DEFINE_ACTION_WRAPPER(dart_test_free_ops, free_io_pgtable_ops, + struct io_pgtable_ops *); + +/* Exact count of pages held by iommu_alloc_pages_sz(), including per-CPU deltas. */ +static long dart_test_iommu_pages(void) +{ + struct pglist_data *pgdat; + long pages = 0; + int cpu; + + for_each_online_pgdat(pgdat) { + pages += atomic_long_read(&pgdat->vm_stat[NR_IOMMU_PAGES]); + for_each_possible_cpu(cpu) + pages += per_cpu_ptr(pgdat->per_cpu_nodestats, + cpu)->vm_node_stat_diff[NR_IOMMU_PAGES]; + } + + return pages; +} + +/* Pages iommu_alloc_pages_sz() accounts for one table of a granule (4 for 16K on a 4K kernel). */ +static long dart_test_tbl_pages(size_t granule) +{ + return 1L << get_order(granule); +} + +static int dart_test_init(struct kunit *test) +{ + struct dart_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "io-pgtable-dart-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + test->priv = t; + + return 0; +} + +static void dart_test_cfg(struct dart_test *t, size_t pgsize, u32 ias, u32 oas) +{ + t->cfg = (struct io_pgtable_cfg) { + .pgsize_bitmap = pgsize, + .ias = ias, + .oas = oas, + .coherent_walk = true, + .tlb = &dart_test_flush_ops, + .iommu_dev = t->dev, + }; +} + +static struct dart_io_pgtable *dart_test_alloc(struct kunit *test, + enum io_pgtable_fmt fmt, + size_t pgsize, u32 ias, u32 oas) +{ + struct dart_test *t = test->priv; + + dart_test_cfg(t, pgsize, ias, oas); + t->ops = alloc_io_pgtable_ops(fmt, &t->cfg, t); + KUNIT_ASSERT_NOT_NULL(test, t->ops); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dart_test_free_ops, + t->ops), 0); + + return io_pgtable_ops_to_data(t->ops); +} + +static int dart_test_map(struct dart_test *t, unsigned long iova, + phys_addr_t paddr, size_t pgcount, int prot, + size_t *mapped) +{ + return t->ops->map_pages(t->ops, iova, paddr, t->cfg.pgsize_bitmap, + pgcount, prot, GFP_KERNEL, mapped); +} + +static size_t dart_test_unmap(struct dart_test *t, unsigned long iova, + size_t pgcount, struct iommu_iotlb_gather *gather) +{ + return t->ops->unmap_pages(t->ops, iova, t->cfg.pgsize_bitmap, pgcount, + gather); +} + +static phys_addr_t dart_test_phys(struct dart_test *t, unsigned long iova) +{ + return t->ops->iova_to_phys(t->ops, iova); +} + +/* Leaf PTE slot found by the driver's own walker. */ +static dart_iopte *dart_test_leaf(struct dart_io_pgtable *data, + unsigned long iova) +{ + dart_iopte *ptep = dart_get_last(data, iova); + + return ptep ? ptep + dart_get_last_index(data, iova) : NULL; +} + +/* Expected table PTE for a next-level table, encoded by hand. */ +static dart_iopte dart_test_table_pte(enum io_pgtable_fmt fmt, void *table) +{ + u64 pa = __pa(table); + + if (fmt == APPLE_DART) + return (pa & GENMASK_ULL(35, 12)) | 1; + return ((pa >> 4) & GENMASK_ULL(37, 10)) | 1; +} + +/* Decode a table PTE by hand. */ +static dart_iopte *dart_test_next(enum io_pgtable_fmt fmt, dart_iopte pte) +{ + if (fmt == APPLE_DART) + return __va(pte & GENMASK_ULL(35, 12)); + return __va((pte & GENMASK_ULL(37, 10)) << 4); +} + +struct dart_test_layout { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + u32 n_ttbrs, n_levels; + int bits_per_level; +}; + +static const struct dart_test_layout dart_test_layouts[] = { + { "dart1-16k-ias32", APPLE_DART, SZ_16K, 32, 36, 1, 3, 11 }, + { "dart1-4k-ias32", APPLE_DART, SZ_4K, 32, 36, 4, 3, 9 }, + { "dart1-4k-ias30", APPLE_DART, SZ_4K, 30, 36, 1, 3, 9 }, + { "dart1-4k-ias36", APPLE_DART, SZ_4K, 36, 36, 1, 4, 9 }, + { "dart1-16k-ias36", APPLE_DART, SZ_16K, 36, 36, 1, 3, 11 }, + { "dart2-16k-ias36", APPLE_DART2, SZ_16K, 36, 42, 1, 3, 11 }, + { "dart2-16k-ias37", APPLE_DART2, SZ_16K, 37, 42, 1, 4, 11 }, + { "dart2-16k-ias42", APPLE_DART2, SZ_16K, 42, 42, 1, 4, 11 }, +}; + +static void dart_test_layout_desc(const struct dart_test_layout *l, char *desc) +{ + strscpy(desc, l->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_layout, dart_test_layouts, dart_test_layout_desc); + +/* Each supported format/granule/ias picks the expected TTBR count and depth. */ +static void dart_test_alloc_layout(struct kunit *test) +{ + const struct dart_test_layout *l = test->param_value; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + u32 i; + + data = dart_test_alloc(test, l->fmt, l->pgsize, l->ias, l->oas); + KUNIT_EXPECT_EQ(test, data->iop.fmt, l->fmt); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_ttbrs, l->n_ttbrs); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_levels, l->n_levels); + KUNIT_EXPECT_EQ(test, data->bits_per_level, l->bits_per_level); + KUNIT_EXPECT_EQ(test, DART_GRANULE(data), l->pgsize); + + for (i = 0; i < DART_MAX_TABLES; i++) { + if (i >= l->n_ttbrs) { + KUNIT_EXPECT_NULL(test, data->pgd[i]); + continue; + } + KUNIT_ASSERT_NOT_NULL(test, data->pgd[i]); + KUNIT_EXPECT_PTR_EQ(test, t->cfg.apple_dart_cfg.ttbr[i], data->pgd[i]); + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(__pa(data->pgd[i]), l->pgsize)); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], l->pgsize)); + } + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +struct dart_test_bad_cfg { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + bool noncoherent; +}; + +static const struct dart_test_bad_cfg dart_test_bad_cfgs[] = { + { "noncoherent", APPLE_DART2, SZ_16K, 36, 42, true }, + { "oas40", APPLE_DART2, SZ_16K, 36, 40 }, + { "oas48", APPLE_DART2, SZ_16K, 36, 48 }, + { "ias-gt-oas", APPLE_DART, SZ_16K, 37, 36 }, + { "pgsize-64k", APPLE_DART2, SZ_64K, 36, 42 }, + { "pgsize-8k", APPLE_DART, SZ_8K, 32, 36 }, + { "pgsize-bitmap", APPLE_DART, SZ_4K | SZ_16K, 32, 36 }, + { "4k-ias42-too-deep", APPLE_DART2, SZ_4K, 42, 42 }, +}; + +static void dart_test_bad_cfg_desc(const struct dart_test_bad_cfg *b, char *desc) +{ + strscpy(desc, b->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_bad_cfg, dart_test_bad_cfgs, dart_test_bad_cfg_desc); + +/* Unsupported walkers, widths and granules are refused without leaking pages. */ +static void dart_test_alloc_reject(struct kunit *test) +{ + const struct dart_test_bad_cfg *b = test->param_value; + struct dart_test *t = test->priv; + long before = dart_test_iommu_pages(); + struct io_pgtable_ops *ops; + + dart_test_cfg(t, b->pgsize, b->ias, b->oas); + t->cfg.coherent_walk = !b->noncoherent; + ops = alloc_io_pgtable_ops(b->fmt, &t->cfg, t); + KUNIT_EXPECT_NULL(test, ops); + if (ops) + free_io_pgtable_ops(ops); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +/* DART1 leaf PTEs: OA in bits 35:12, SP_DIS, NO_WRITE(7), NO_READ(8). */ +static void dart_test_pte_dart1(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x003 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x003 }, + { IOMMU_READ, 0x083 }, + { IOMMU_WRITE, 0x103 }, + }; + const phys_addr_t pa = 0x81234c000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, DART_TEST_SUBPAGE_ALL | pa | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x123), pa + 0x123); + } + + /* 4 KiB granule DART1: same encoding, 4 KiB aligned output address. */ + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x3000, 0x876543000ULL, 1, + IOMMU_READ | IOMMU_WRITE, NULL), 0); + ptep = dart_test_leaf(data, 0x3000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0876543003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), 0x876543fffULL); +} + +/* DART2 leaf PTEs: OA >> 4 in bits 37:10, NO_CACHE(1), NO_WRITE(2), NO_READ(3). */ +static void dart_test_pte_dart2(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x3 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x1 }, + { IOMMU_READ | IOMMU_CACHE, 0x5 }, + { IOMMU_WRITE | IOMMU_CACHE, 0x9 }, + { IOMMU_READ, 0x7 }, + }; + const phys_addr_t pa = 0x2abcdef4000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff2abcdef400ULL | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x3ff8), pa + 0x3ff8); + } + + /* The top of the 42-bit output space round-trips (bits 41:40 kept). */ + iova = SZ_2M; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x3ffffffc000ULL, 1, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff3ffffffc01ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 1), 0x3ffffffc001ULL); +} + +/* Table PTEs carry only the next table's address and the valid bit. */ +static void dart_test_table_ptes(struct kunit *test) +{ + static const enum io_pgtable_fmt fmts[] = { APPLE_DART, APPLE_DART2 }; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf, *l1; + int i; + + for (i = 0; i < ARRAY_SIZE(fmts); i++) { + data = dart_test_alloc(test, fmts[i], SZ_16K, 32, fmts[i] == APPLE_DART ? 36 : 42); + /* L1 index 3 (iova >> 25), leaf index 5 (iova >> 14). */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x6014000, SZ_1G, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + leaf = dart_test_next(fmts[i], l1[3]); + KUNIT_ASSERT_NE(test, l1[3], 0ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, 0x6014000), leaf + 5); + KUNIT_EXPECT_EQ(test, l1[3], dart_test_table_pte(fmts[i], leaf)); + KUNIT_EXPECT_EQ(test, l1[2], 0ULL); + KUNIT_EXPECT_EQ(test, l1[4], 0ULL); + KUNIT_EXPECT_NE(test, leaf[5], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[4], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[6], 0ULL); + } +} + +/* High L1 indexes on a 36-bit DART2 select their own tables (no aliasing). */ +static void dart_test_index_high_l1(struct kunit *test) +{ + const unsigned long hi = 0x802004000UL; /* L1 1025, leaf 1 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *leaf; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, hi, 0x10000000, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[1025], 0ULL); + KUNIT_EXPECT_EQ(test, l1[1], 0ULL); + leaf = dart_test_next(APPLE_DART2, l1[1025]); + KUNIT_EXPECT_EQ(test, leaf[1], 0x000fff0001000007ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0ULL); + + /* The low alias is a different IOVA and maps independently. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x2004000, 0x20000000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, hi, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); +} + +/* 4-level DART2 (ias 42): three table levels below the TTBR. */ +static void dart_test_four_level(struct kunit *test) +{ + const unsigned long top = 0x3ffffffc000UL; /* L1 63, L2 2047, L3 2047 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *l2, *l3; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 42, 42); + KUNIT_ASSERT_EQ(test, t->cfg.apple_dart_cfg.n_levels, 4U); + KUNIT_ASSERT_EQ(test, dart_test_map(t, top, 0x4000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0, 0x8000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + + /* L1 = iova >> 36, L2 = (iova >> 25) & 2047, L3 = (iova >> 14) & 2047. */ + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[63], 0ULL); + KUNIT_ASSERT_NE(test, l1[0], 0ULL); + l2 = dart_test_next(APPLE_DART2, l1[63]); + KUNIT_ASSERT_NE(test, l2[2047], 0ULL); + KUNIT_EXPECT_EQ(test, l1[63], dart_test_table_pte(APPLE_DART2, l2)); + l3 = dart_test_next(APPLE_DART2, l2[2047]); + KUNIT_EXPECT_EQ(test, l3[2047], 0x000fff0000000403ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, top), l3 + 2047); + + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top + 0x10), 0x4010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10), 0x8010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT(36)), 0ULL); + /* Beyond the single TTBR (iova >> 47 != 0). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT(47), 0x4000, 1, IOMMU_READ, NULL), -ENOMEM); +} + +/* 4 KiB DART1 with ias 32 splits the space over four TTBRs at 1 GiB. */ +static void dart_test_four_ttbrs(struct kunit *test) +{ + const unsigned long iova = 0xc0203000UL; /* TTBR 3, L1 1, leaf 3 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf; + size_t mapped = 0; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x87654000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_4K); + for (i = 0; i < 3; i++) + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], SZ_4K)); + KUNIT_ASSERT_NE(test, ((dart_iopte *)data->pgd[3])[1], 0ULL); + KUNIT_EXPECT_EQ(test, ((dart_iopte *)data->pgd[3])[0], 0ULL); + leaf = dart_test_next(APPLE_DART, ((dart_iopte *)data->pgd[3])[1]); + KUNIT_EXPECT_EQ(test, leaf[3], 0x000fff0087654003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0xabc), 0x87654abcULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova - SZ_1G), 0ULL); + + /* The last page of TTBR 0 and the first page of TTBR 1. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G - SZ_4K, 0x1000, 1, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G, 0x2000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[511], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[1])[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G - 1), 0x1fffULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G), 0x2000ULL); + + /* IOVA 4 GiB would need a fifth TTBR. */ + mapped = 0; + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(32), 0x1000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(32)), 0ULL); +} + +/* pgcount mappings fill consecutive PTEs and stop at the leaf table's end. */ +static void dart_test_map_multi(struct kunit *test) +{ + const unsigned long start = SZ_32M - 2 * SZ_16K; /* leaf 2046 of L1 0 */ + const phys_addr_t pa = 0x80000000; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + size_t mapped = SZ_1M, left = 5; + unsigned long iova = start; + int calls = 0, i; + dart_iopte *ptep; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + + /* *mapped accumulates; the first call stops after 2 pages. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, left, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_1M + 2 * SZ_16K); + + /* Continue as iommu_map() does until all pages are in. */ + mapped -= SZ_1M; + while (left) { + calls++; + left -= mapped / SZ_16K; + iova += mapped; + mapped = 0; + if (!left) + break; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa + (iova - start), left, + IOMMU_READ | IOMMU_WRITE, &mapped), 0); + KUNIT_ASSERT_GT(test, mapped, (size_t)0); + } + KUNIT_EXPECT_EQ(test, calls, 2); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[0], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[1], 0ULL); + + for (i = 0; i < 5; i++) { + ptep = dart_test_leaf(data, start + i * SZ_16K); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0008000003ULL + i * (SZ_16K >> 4)); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + i * SZ_16K + 8), + pa + i * SZ_16K + 8); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + 5 * SZ_16K), 0ULL); + + /* A large run in an empty leaf table fills all 2048 slots at once. */ + mapped = 0; + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0, 4096, IOMMU_READ, &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_32M); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M - 1), (phys_addr_t)SZ_32M - 1); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M), 0ULL); +} + +/* Mapping over a valid PTE fails without touching any slot of the range. */ +static void dart_test_map_exists(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte old, *ptep; + size_t mapped = 0; + int ret, i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x10008000, 0x40000000, 1, IOMMU_READ, NULL), 0); + ptep = dart_test_leaf(data, 0x10008000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + old = *ptep; + + kunit_warning_suppress(test) { + ret = dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + /* Slot 2 of [0, 4) is taken: nothing of the range is written. */ + ret = dart_test_map(t, 0x10000000, 0x60000000, 4, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 2); + } + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, *ptep, old); + for (i = 0; i < 4; i++) + if (i != 2) + KUNIT_EXPECT_EQ(test, *(ptep - 2 + i), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x40000000ULL); + + /* After an unmap the same IOVA maps again. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, 0x10008000, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_WRITE, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x50000000ULL); +} + +/* Bad sizes, protections and output addresses are rejected before any table is built. */ +static void dart_test_map_reject(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + long pages; + size_t mapped = 0; + int ret; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + pages = dart_test_iommu_pages(); + + /* Neither read nor write: refused without a warning. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, 0, &mapped), -EINVAL); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, IOMMU_CACHE, &mapped), -EINVAL); + + kunit_warning_suppress(test) { + /* Only the single configured page size is accepted. */ + ret = t->ops->map_pages(t->ops, 0, 0x4000, SZ_4K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = t->ops->map_pages(t->ops, 0, 0x8000, SZ_32K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + /* Output address at or past 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36), 1, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + /* A run that would cross 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 2, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 4); + } + + /* Beyond the single TTBR of a 16 KiB DART (iova >> 36). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(36), 0x4000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[0], SZ_16K)); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages); + + /* The last page below 2^oas is fine. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 1, IOMMU_READ, &mapped), + 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), BIT_ULL(36) - 1); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages + dart_test_tbl_pages(SZ_16K)); +} + +/* Unmap clears exactly the requested PTEs and queues one TLB page each. */ +static void dart_test_unmap_range(struct kunit *test) +{ + struct iommu_iotlb_gather gather; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *ptep; + size_t mapped = 0; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1M, SZ_1G, 4, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_ASSERT_EQ(test, mapped, (size_t)SZ_64K); + ptep = dart_test_leaf(data, SZ_1M); + KUNIT_ASSERT_NOT_NULL(test, ptep); + + iommu_iotlb_gather_init(&gather); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + SZ_16K, 2, &gather), (size_t)SZ_32K); + KUNIT_EXPECT_NE(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[1], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[2], 0ULL); + KUNIT_EXPECT_NE(test, ptep[3], 0ULL); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, t->tlb_last_iova, (unsigned long)SZ_1M + 2 * SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_last_granule, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M), (phys_addr_t)SZ_1G); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + 3 * SZ_16K), + (phys_addr_t)SZ_1G + 3 * SZ_16K); + + /* A queued gather defers invalidation to the caller. */ + gather.queued = true; + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M, 1, &gather), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + 3 * SZ_16K, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 3U); + KUNIT_EXPECT_TRUE(test, mem_is_zero(ptep, 4 * sizeof(*ptep))); + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +/* Unmap of holes, missing tables and runs past a leaf table end. */ +static void dart_test_unmap_partial(struct kunit *test) +{ + const unsigned long end = SZ_32M - SZ_16K; /* last leaf slot of L1 0 */ + struct dart_test *t = test->priv; + size_t size; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, end, 0x40000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M, 0x40004000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0x50000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M + 3 * SZ_16K, 0x50000000, 1, IOMMU_READ, + NULL), 0); + + /* A run crossing the leaf table end stops at it. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, end, 3, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + + kunit_warning_suppress(test) { + /* A hole at slot 2 ends the run after two pages. */ + size = dart_test_unmap(t, SZ_64M, 4, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)SZ_32K); + /* No leaf table at all. */ + size = dart_test_unmap(t, SZ_1G, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Nothing to do and wrong page size. */ + size = dart_test_unmap(t, SZ_32M, 0, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + size = t->ops->unmap_pages(t->ops, SZ_32M, SZ_4K, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Beyond the TTBR. */ + size = dart_test_unmap(t, BIT_ULL(36), 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 5); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + 3 * SZ_16K), 0x50000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_32M, 2, NULL), (size_t)SZ_32K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K), 0ULL); +} + +/* iova_to_phys() misses at each level of an otherwise populated table. */ +static void dart_test_iova_to_phys_miss(struct kunit *test) +{ + struct dart_test *t = test->priv; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 37, 42); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M + SZ_16K, 0x12340000, 1, IOMMU_READ, + NULL), 0); + /* Same leaf table, empty slot. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0ULL); + /* Same L2 table, no leaf table. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + /* No L2 table under L1 index 1. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(36) + SZ_32M + SZ_16K), 0ULL); + /* The offset within the page is kept. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K + 0x3fff), 0x12343fffULL); +} + +struct dart_test_teardown { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + unsigned long iova[4]; + long tables; /* tables held after alloc + the maps */ +}; + +static const struct dart_test_teardown dart_test_teardowns[] = { + /* 1 root + 2 leaf tables. */ + { "dart1-16k", APPLE_DART, SZ_16K, 32, 36, { 0, SZ_16K, SZ_32M, SZ_32M + SZ_16K }, 3 }, + /* 4 roots + 4 leaf tables, one per TTBR. */ + { "dart1-4k-4ttbr", APPLE_DART, SZ_4K, 32, 36, { 0, SZ_1G, 2UL * SZ_1G, 3UL * SZ_1G }, 8 }, + /* 1 root + 2 L2 + 3 leaf tables. */ + { "dart2-16k-4level", APPLE_DART2, SZ_16K, 42, 42, + { 0, SZ_32M, BIT(36), BIT(36) + SZ_16K }, 6 }, +}; + +static void dart_test_teardown_desc(const struct dart_test_teardown *td, char *desc) +{ + strscpy(desc, td->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_teardown, dart_test_teardowns, dart_test_teardown_desc); + +/* Every table page allocated by map_pages() is released by free_io_pgtable_ops(). */ +static void dart_test_teardown_free(struct kunit *test) +{ + const struct dart_test_teardown *td = test->param_value; + struct dart_test *t = test->priv; + long before; + int i; + + before = dart_test_iommu_pages(); + dart_test_alloc(test, td->fmt, td->pgsize, td->ias, td->oas); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + t->cfg.apple_dart_cfg.n_ttbrs * dart_test_tbl_pages(td->pgsize)); + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_ASSERT_EQ(test, dart_test_map(t, td->iova[i], SZ_1G, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + /* Unmap keeps the tables; the teardown frees them. */ + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, td->iova[i], 1, NULL), td->pgsize); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + kunit_release_action(test, dart_test_free_ops, t->ops); + t->ops = NULL; + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +static struct kunit_case io_pgtable_dart_test_cases[] = { + KUNIT_CASE_PARAM(dart_test_alloc_layout, dart_test_layout_gen_params), + KUNIT_CASE_PARAM(dart_test_alloc_reject, dart_test_bad_cfg_gen_params), + KUNIT_CASE(dart_test_pte_dart1), + KUNIT_CASE(dart_test_pte_dart2), + KUNIT_CASE(dart_test_table_ptes), + KUNIT_CASE(dart_test_index_high_l1), + KUNIT_CASE(dart_test_four_level), + KUNIT_CASE(dart_test_four_ttbrs), + KUNIT_CASE(dart_test_map_multi), + KUNIT_CASE(dart_test_map_exists), + KUNIT_CASE(dart_test_map_reject), + KUNIT_CASE(dart_test_unmap_range), + KUNIT_CASE(dart_test_unmap_partial), + KUNIT_CASE(dart_test_iova_to_phys_miss), + KUNIT_CASE_PARAM(dart_test_teardown_free, dart_test_teardown_gen_params), + {} +}; + +static struct kunit_suite io_pgtable_dart_test_suite = { + .name = "io-pgtable-dart", + .init = dart_test_init, + .test_cases = io_pgtable_dart_test_cases, +}; + +kunit_test_suite(io_pgtable_dart_test_suite); diff --git a/drivers/iommu/io-pgtable-dart.c b/drivers/iommu/io-pgtable-dart.c index ad817bf76c310a..93d268710a11e2 100644 --- a/drivers/iommu/io-pgtable-dart.c +++ b/drivers/iommu/io-pgtable-dart.c @@ -483,3 +483,7 @@ struct io_pgtable_init_fns io_pgtable_apple_dart_init_fns = { .alloc = apple_dart_alloc_pgtable, .free = apple_dart_free_pgtable, }; + +#if IS_ENABLED(CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST) +#include "io-pgtable-dart-test.c" +#endif diff --git a/drivers/iommu/io-pgtable-dart.kunitconfig b/drivers/iommu/io-pgtable-dart.kunitconfig new file mode 100644 index 00000000000000..3171f991a8f45f --- /dev/null +++ b/drivers/iommu/io-pgtable-dart.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_IOMMU_SUPPORT=y +CONFIG_IOMMU_IO_PGTABLE_DART=y +CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST=y From 0615a4964cbeeb942718178977d24cc3dec86c2d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:06 +1100 Subject: [PATCH 0490/1514] rtc: macsmc: add KUnit tests Add tests for the time and alarm arithmetic: the 48-bit tick offset with its sign extension and wrap, the 64-bit seconds offset and its rounding to the nearest second, and the PMU alarm's value, mask and control byte writes. A static stub replaces the SMC counter read and a RAM-backed NVMEM device holds the offset and alarm cells. The tick case expects set_time to return 0 on success, so it needs "rtc: macsmc: return 0 from a successful set_time" first; without it the case fails on the byte count (6). Signed-off-by: Ryan Murray --- drivers/rtc/Kconfig | 13 + drivers/rtc/rtc-macsmc-test.c | 574 +++++++++++++++++++++++++++++ drivers/rtc/rtc-macsmc.c | 4 + drivers/rtc/rtc-macsmc.kunitconfig | 13 + 4 files changed, 604 insertions(+) create mode 100644 drivers/rtc/rtc-macsmc-test.c create mode 100644 drivers/rtc/rtc-macsmc.kunitconfig diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig index a7e6eba6e7910d..243c4a563798a1 100644 --- a/drivers/rtc/Kconfig +++ b/drivers/rtc/Kconfig @@ -2121,6 +2121,19 @@ config RTC_DRV_MACSMC To compile this driver as a module, choose M here: the module will be called rtc-macsmc. +config RTC_DRV_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC RTC" if !KUNIT_ALL_TESTS + depends on RTC_DRV_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC RTC's time and alarm arithmetic: the + 48-bit tick offset with its sign extension and wrap, the 64-bit + seconds offset and its rounding, and the PMU alarm's value, mask + and control byte writes. A static stub replaces the SMC counter + read and a RAM-backed NVMEM device holds the offset and alarm + cells, so the tests need no Apple hardware. + config RTC_DRV_MSC313 tristate "MStar MSC313 RTC" depends on ARCH_MSTARV7 || COMPILE_TEST diff --git a/drivers/rtc/rtc-macsmc-test.c b/drivers/rtc/rtc-macsmc-test.c new file mode 100644 index 00000000000000..a71c72a95a77bc --- /dev/null +++ b/drivers/rtc/rtc-macsmc-test.c @@ -0,0 +1,574 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC RTC driver: the 48-bit tick and 64-bit + * seconds offset arithmetic and the PMU alarm programming. + * + * The CLKM counter comes from a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). The offset and alarm cells are real NVMEM cells of + * a RAM-backed NVMEM device, found through a cell lookup table, so the cell + * sizes and byte layouts are checked by the NVMEM core as on hardware. + * + * Included by rtc-macsmc.c. + */ + +#include +#include +#include +#include + +#define RTC_TEST_OFFSET 0 +#define RTC_TEST_CTRL 8 +#define RTC_TEST_MASK 9 +#define RTC_TEST_ALARM 12 +#define RTC_TEST_NVMEM_SIZE 16 + +#define RTC_TEST_TICKS BIT_ULL(RTC_SEC_SHIFT) +#define RTC_TEST_MASK48 GENMASK_ULL(RTC_BITS - 1, 0) + +/* 2023-11-14 22:13:20 UTC */ +#define RTC_TEST_T 1700000000LL + +struct macsmc_rtc_test_write { + unsigned int offset; + size_t bytes; + u8 val[8]; +}; + +struct macsmc_rtc_test { + struct apple_smc smc; + struct macsmc_rtc rtc; + struct device *dev; + u8 nvmem[RTC_TEST_NVMEM_SIZE]; + /* CLKM: the free-running 32768 Hz counter, and what its read returns */ + u64 clkm; + int clkm_ret; + /* NVMEM writes, in order; a write at fail_offset fails */ + struct macsmc_rtc_test_write writes[8]; + unsigned int nr_writes; + int fail_offset; + struct nvmem_cell_lookup lookups[4]; +}; + +static int macsmc_rtc_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_rtc_test *ctx = container_of(smc, struct macsmc_rtc_test, smc); + struct kunit *test = kunit_get_current_test(); + u8 le[8]; + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(CLKM)); + KUNIT_EXPECT_EQ(test, size, RTC_BYTES); + if (ctx->clkm_ret < 0) + return ctx->clkm_ret; + + put_unaligned_le64(ctx->clkm, le); + memcpy(buf, le, min(size, sizeof(le))); + return ctx->clkm_ret ?: size; +} + +static int macsmc_rtc_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_rtc_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + struct macsmc_rtc_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->offset = offset; + w->bytes = bytes; + memcpy(w->val, val, min(bytes, sizeof(w->val))); + } + ctx->nr_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_rtc_test_del_lookups(void *data) +{ + struct macsmc_rtc_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_rtc_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_rtc_test_cell(struct kunit *test, + struct macsmc_rtc_test *ctx, + const char *id) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, id); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_cell_put, + cell), 0); + return cell; +} + +/* + * An RTC whose offset cell holds @offset_bytes bytes: 6 for a tick offset, + * 8 for a seconds offset. + */ +static struct macsmc_rtc_test *macsmc_rtc_test_setup(struct kunit *test, + bool offset_in_seconds, + unsigned int offset_bytes) +{ + static const char * const names[] = { + "rtc_offset", "rtc_ctrl", "rtc_alarm_mask", "rtc_alarm", + }; + const unsigned int offsets[] = { + RTC_TEST_OFFSET, RTC_TEST_CTRL, RTC_TEST_MASK, RTC_TEST_ALARM, + }; + const unsigned int sizes[] = { offset_bytes, 1, 1, 4 }; + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_rtc_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, ARRAY_SIZE(names), sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + + for (i = 0; i < ARRAY_SIZE(names); i++) { + cells[i].name = names[i]; + cells[i].offset = offsets[i]; + cells[i].bytes = sizes[i]; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-rtc-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = ARRAY_SIZE(names); + config.ignore_wp = true; + config.reg_read = macsmc_rtc_test_reg_read; + config.reg_write = macsmc_rtc_test_reg_write; + config.size = RTC_TEST_NVMEM_SIZE; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "rtc"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < ARRAY_SIZE(names); i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = names[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = names[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_del_lookups, + ctx), 0); + + ctx->rtc.dev = ctx->dev; + ctx->rtc.smc = &ctx->smc; + ctx->rtc.offset_in_seconds = offset_in_seconds; + mutex_init(&ctx->rtc.alarm_lock); + ctx->rtc.rtc_offset = macsmc_rtc_test_cell(test, ctx, "rtc_offset"); + ctx->rtc.alarm_ctrl = macsmc_rtc_test_cell(test, ctx, "rtc_ctrl"); + ctx->rtc.alarm_mask = macsmc_rtc_test_cell(test, ctx, "rtc_alarm_mask"); + ctx->rtc.alarm_value = macsmc_rtc_test_cell(test, ctx, "rtc_alarm"); + dev_set_drvdata(ctx->dev, &ctx->rtc); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_rtc_test_read); + return ctx; +} + +static void macsmc_rtc_test_put_tick_offset(struct macsmc_rtc_test *ctx, u64 off) +{ + u8 le[8]; + + put_unaligned_le64(off & RTC_TEST_MASK48, le); + memcpy(ctx->nvmem + RTC_TEST_OFFSET, le, RTC_BYTES); +} + +static u64 macsmc_rtc_test_tick_offset(struct macsmc_rtc_test *ctx) +{ + u8 le[8] = {}; + + memcpy(le, ctx->nvmem + RTC_TEST_OFFSET, RTC_BYTES); + return get_unaligned_le64(le); +} + +static time64_t macsmc_rtc_test_now(struct kunit *test, struct macsmc_rtc_test *ctx) +{ + struct rtc_time tm = {}; + int ret; + + ret = macsmc_rtc_get_time(ctx->dev, &tm); + KUNIT_EXPECT_GE(test, ret, 0); + if (ret < 0) + return S64_MIN; + return rtc_tm_to_time64(&tm); +} + +static int macsmc_rtc_test_set(struct macsmc_rtc_test *ctx, time64_t t) +{ + struct rtc_time tm; + + rtc_time64_to_tm(t, &tm); + return macsmc_rtc_set_time(ctx->dev, &tm); +} + +static void macsmc_rtc_test_expect_write(struct kunit *test, + struct macsmc_rtc_test *ctx, + unsigned int idx, unsigned int offset, + size_t bytes, u64 val) +{ + struct macsmc_rtc_test_write *w = &ctx->writes[idx]; + u8 le[8]; + + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + put_unaligned_le64(val, le); + KUNIT_EXPECT_EQ_MSG(test, w->offset, offset, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, w->bytes, bytes, "write %u", idx); + KUNIT_EXPECT_MEMEQ_MSG(test, w->val, le, bytes, "write %u", idx); +} + +/* Tick offset: time = sign_extend48(CLKM + offset) / 2^15, rounded down. */ +static void macsmc_rtc_test_tick_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x123456789abULL; + + ctx->clkm = ctr; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + 12345 - ctr); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + + /* One tick before the next second, and the second itself. */ + ctx->clkm = ctr + RTC_TEST_TICKS - 12345 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm++; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 1); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The sum is taken modulo 2^48: a carry out of bit 47 is not time. */ +static void macsmc_rtc_test_tick_wrap(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + + ctx->clkm = RTC_TEST_MASK48 + 1 - RTC_TEST_TICKS; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* Set then read: the stored 6 bytes, and the set second starts at the set. */ +static void macsmc_rtc_test_tick_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x00ab12345678ULL; + + ctx->clkm = ctr; + /* .set_time returns 0, not the cell write's byte count. */ + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, RTC_BYTES, + ((RTC_TEST_T << RTC_SEC_SHIFT) - ctr) & RTC_TEST_MASK48); + + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + 3 * RTC_TEST_TICKS + 100; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 3); +} + +/* A time before 1970 is a negative 48-bit sum and must read back as such. */ +static void macsmc_rtc_test_tick_negative(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm = {}; + + ctx->clkm = 1000 * RTC_TEST_TICKS + 5; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, -1), 0); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_tick_offset(ctx), + ((u64)-(1LL << RTC_SEC_SHIFT) - ctx->clkm) & RTC_TEST_MASK48); + + KUNIT_EXPECT_GE(test, macsmc_rtc_get_time(ctx->dev, &tm), 0); + KUNIT_EXPECT_EQ(test, tm.tm_year, 69); + KUNIT_EXPECT_EQ(test, tm.tm_mon, 11); + KUNIT_EXPECT_EQ(test, tm.tm_mday, 31); + KUNIT_EXPECT_EQ(test, tm.tm_hour, 23); + KUNIT_EXPECT_EQ(test, tm.tm_min, 59); + KUNIT_EXPECT_EQ(test, tm.tm_sec, 59); +} + +/* Seconds offset: time = CLKM / 2^15 + offset, offset a LE64 at the cell. */ +static void macsmc_rtc_test_secs_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->clkm = 5 * RTC_TEST_TICKS + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 5); + + /* Bits above the counter's 48 are not read: CLKM is a 6-byte key. */ + ctx->clkm = BIT_ULL(RTC_BITS) | (7 * RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 7); +} + +/* An offset never written is not a time: reading it must fail. */ +static void macsmc_rtc_test_secs_unset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_time tm; + + ctx->clkm = 1234 * RTC_TEST_TICKS; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EINVAL); +} + +/* A seconds-mode offset cell shorter than 8 bytes is rejected, not half read. */ +static void macsmc_rtc_test_secs_short_cell(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + struct rtc_time tm; + + memset(ctx->nvmem, 0x11, RTC_BYTES); + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + rtc_time64_to_tm(RTC_TEST_T, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The seconds offset rounds the counter to the nearest second. */ +static void macsmc_rtc_test_secs_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, 8, RTC_TEST_T - 10); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_OFFSET, 8, RTC_TEST_T - 11); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 2); + + /* Read back half a second later: at most half a second off. */ + ctx->clkm += RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* CLKM failures and short replies fail the call and write nothing. */ +static void macsmc_rtc_test_clkm_errors(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm; + + ctx->clkm_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -ETIMEDOUT); + + ctx->clkm_ret = 4; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + + ctx->rtc.offset_in_seconds = true; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* + * Arming: a latched event is cleared by writing it back, then the value + * (counter seconds, LE32), the mask and the control byte with EN | MONITOR. + * The PMU's other control bits are kept. + */ +static void macsmc_rtc_test_alarm_arm(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const s64 off = 1000000; + + /* A tick offset with a fraction: whole seconds are used. */ + macsmc_rtc_test_put_tick_offset(ctx, (off << RTC_SEC_SHIFT) + 1234); + ctx->nvmem[RTC_TEST_CTRL] = 0x80 | RTC_CTRL_ALARM_EVENT; + ctx->nvmem[RTC_TEST_MASK] = 1; + + rtc_time64_to_tm(off + 4321, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 4321); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_ALARM, 4, 4321); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 3, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); +} + +/* A disabled alarm is remembered but disarms; enabling it arms the same second. */ +static void macsmc_rtc_test_alarm_disabled(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 0 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + /* Left armed by firmware, no event. */ + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + rtc_time64_to_tm(RTC_TEST_T + 60, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 60); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 60); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, + RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* The 32-bit compare holds counter seconds 1..U32_MAX; others are refused. */ +static void macsmc_rtc_test_alarm_range(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const time64_t off = 86400; + + put_unaligned_le64(off, ctx->nvmem + RTC_TEST_OFFSET); + + rtc_time64_to_tm(off, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off - 5, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off + (time64_t)U32_MAX + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + rtc_time64_to_tm(off + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 1); + rtc_time64_to_tm(off + U32_MAX, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), U32_MAX); +} + +/* A negative tick offset moves the alarm's counter second forward. */ +static void macsmc_rtc_test_alarm_negative_offset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + macsmc_rtc_test_put_tick_offset(ctx, (u64)-(5LL << RTC_SEC_SHIFT)); + rtc_time64_to_tm(100, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 105); + + memset(&alrm, 0, sizeof(alrm)); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), 100); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); +} + +/* Reading decodes the value against the offset and the EN/EVENT bits. */ +static void macsmc_rtc_test_alarm_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = {}; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + put_unaligned_le32(777, ctx->nvmem + RTC_TEST_ALARM); + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), RTC_TEST_T + 777); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_TRUE(test, alrm.pending); + + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_MONITOR; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_FALSE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The interrupt is one-shot: an event clears and disarms; no event is not ours. */ +static void macsmc_rtc_test_alarm_irq(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + const u8 armed = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + ctx->nvmem[RTC_TEST_CTRL] = armed; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_NONE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + ctx->nvmem[RTC_TEST_CTRL] = armed | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_HANDLED); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + armed | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* A failed mask write leaves the alarm unarmed and reports the error. */ +static void macsmc_rtc_test_alarm_write_error(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->fail_offset = RTC_TEST_MASK; + rtc_time64_to_tm(RTC_TEST_T + 10, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[RTC_TEST_CTRL], 0); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 10); +} + +static struct kunit_case macsmc_rtc_test_cases[] = { + KUNIT_CASE(macsmc_rtc_test_tick_read), + KUNIT_CASE(macsmc_rtc_test_tick_wrap), + KUNIT_CASE(macsmc_rtc_test_tick_set), + KUNIT_CASE(macsmc_rtc_test_tick_negative), + KUNIT_CASE(macsmc_rtc_test_secs_read), + KUNIT_CASE(macsmc_rtc_test_secs_unset), + KUNIT_CASE(macsmc_rtc_test_secs_short_cell), + KUNIT_CASE(macsmc_rtc_test_secs_set), + KUNIT_CASE(macsmc_rtc_test_clkm_errors), + KUNIT_CASE(macsmc_rtc_test_alarm_arm), + KUNIT_CASE(macsmc_rtc_test_alarm_disabled), + KUNIT_CASE(macsmc_rtc_test_alarm_range), + KUNIT_CASE(macsmc_rtc_test_alarm_negative_offset), + KUNIT_CASE(macsmc_rtc_test_alarm_read), + KUNIT_CASE(macsmc_rtc_test_alarm_irq), + KUNIT_CASE(macsmc_rtc_test_alarm_write_error), + {} +}; + +static struct kunit_suite macsmc_rtc_test_suite = { + .name = "macsmc-rtc", + .test_cases = macsmc_rtc_test_cases, +}; + +kunit_test_suite(macsmc_rtc_test_suite); diff --git a/drivers/rtc/rtc-macsmc.c b/drivers/rtc/rtc-macsmc.c index 690a4a84ff90e5..0b83e6e609d67c 100644 --- a/drivers/rtc/rtc-macsmc.c +++ b/drivers/rtc/rtc-macsmc.c @@ -482,3 +482,7 @@ module_platform_driver(macsmc_rtc_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC RTC driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_RTC_DRV_MACSMC_KUNIT_TEST) +#include "rtc-macsmc-test.c" +#endif diff --git a/drivers/rtc/rtc-macsmc.kunitconfig b/drivers/rtc/rtc-macsmc.kunitconfig new file mode 100644 index 00000000000000..08faff88f7bd88 --- /dev/null +++ b/drivers/rtc/rtc-macsmc.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/rtc/rtc-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_RTC_CLASS=y +CONFIG_RTC_DRV_MACSMC=y +CONFIG_RTC_DRV_MACSMC_KUNIT_TEST=y From c69655f6532b83bd9636da9366eb758969f589a8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:26:12 +1100 Subject: [PATCH 0491/1514] HID: dockchannel: keep one descriptor and retire commands under a lock An interface keeps a copy of every HID descriptor block it is sent before its HID device exists, and the copies are only released with the platform device. Free the previous copy when a descriptor is replaced, and leave the descriptor alone once the interface is queued for creation, as the HID core may then be parsing it. The receive path completes a pending command without the command's mutex. A reply that races with the command's timeout can pass the sequence and report checks and then copy into the response buffer after dchid_cmd() has cleared it and returned. Protect the pending command state with a spinlock taken by both dchid_cmd() and dchid_handle_ack(), so that a command is retired before its buffer is released and a later reply no longer matches it. Signed-off-by: Ryan Murray --- .../dockchannel-hid-parser-test.c | 37 ++++++++++++++++ drivers/hid/dockchannel-hid/dockchannel-hid.c | 44 ++++++++++++++++--- 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c b/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c index 64fde481641cd2..eeec7cbf027027 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-parser-test.c @@ -21,6 +21,7 @@ static int dchid_parser_test_init(struct kunit *test) iface->out_flags = 0x80; iface->tx_seq = 7; init_completion(&iface->out_complete); + spin_lock_init(&iface->resp_lock); dchid->ifaces[1] = iface; test->priv = iface; return 0; @@ -170,6 +171,41 @@ static void dchid_init_descriptor_test(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, iface->hid_desc, msg.descriptor, sizeof(msg.descriptor)); } +/* Repeated descriptors keep one copy, and none replaces a queued one. */ +static void dchid_init_descriptor_repeat_test(struct kunit *test) +{ + struct dchid_iface *iface = test->priv; + struct device *dev = iface->dchid->dev; + struct { + struct dchid_init_hdr hdr; + struct dchid_init_block_hdr block; + u8 descriptor[4]; + } __packed msg = { + .hdr = { .iface = 1, .more_packets = 1 }, + .block = { .type = INIT_HID_DESCRIPTOR, .length = 4 }, + .descriptor = { 0x05, 0x01, 0x09, 0x06 }, + }; + size_t resources = list_count_nodes(&dev->devres_head); + void *desc; + int i; + + for (i = 0; i < 3; i++) { + msg.descriptor[3] = i; + dchid_handle_init(iface->dchid, &msg, sizeof(msg)); + } + KUNIT_EXPECT_EQ(test, list_count_nodes(&dev->devres_head), resources + 1); + KUNIT_ASSERT_NOT_NULL(test, iface->hid_desc); + KUNIT_EXPECT_EQ(test, ((u8 *)iface->hid_desc)[3], 2); + + iface->creating = true; + desc = iface->hid_desc; + msg.descriptor[3] = 3; + dchid_handle_init(iface->dchid, &msg, sizeof(msg)); + KUNIT_EXPECT_PTR_EQ(test, iface->hid_desc, desc); + KUNIT_EXPECT_EQ(test, ((u8 *)iface->hid_desc)[3], 2); + KUNIT_EXPECT_EQ(test, list_count_nodes(&dev->devres_head), resources + 1); +} + static void dchid_packet_checksum_test(struct kunit *test) { struct dchid_hdr hdr = { .hdr_len = sizeof(hdr), .length = 8 }; @@ -265,6 +301,7 @@ static struct kunit_case dchid_parser_cases[] = { KUNIT_CASE(dchid_init_bounds_test), KUNIT_CASE(dchid_short_input_test), KUNIT_CASE(dchid_init_descriptor_test), + KUNIT_CASE(dchid_init_descriptor_repeat_test), KUNIT_CASE(dchid_packet_checksum_test), KUNIT_CASE(dchid_ring_wrap_test), KUNIT_CASE(dchid_ring_bad_header_test), diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index 9e0877ca2d496a..0b5e9ab609b0aa 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -185,6 +185,12 @@ struct dchid_iface { bool gpio_announced; struct mutex out_mutex; + /* + * Protects the pending command (out_flags, out_report, retcode, + * resp_buf, resp_size, tx_seq) against the receive path, which + * completes it without out_mutex. + */ + spinlock_t resp_lock; u32 out_flags; int out_report; u32 retcode; @@ -318,6 +324,7 @@ dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) init_completion(&iface->out_complete); init_completion(&iface->ready); mutex_init(&iface->out_mutex); + spin_lock_init(&iface->resp_lock); iface->wq = alloc_ordered_workqueue("dchid-%s", WQ_MEM_RECLAIM, iface->name); if (!iface->wq) goto err_put_node; @@ -432,12 +439,14 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, mutex_lock(&iface->out_mutex); + spin_lock(&iface->resp_lock); WARN_ON(iface->out_report != -1); iface->out_report = report_id; iface->out_flags = FIELD_PREP(FLAGS_GROUP, type) | FIELD_PREP(FLAGS_REQ, req); iface->resp_buf = resp_buf; iface->resp_size = resp_size; reinit_completion(&iface->out_complete); + spin_unlock(&iface->resp_lock); ret = dchid_send(iface, iface->out_flags, data, size); if (ret < 0) @@ -459,11 +468,17 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, } done: + /* + * Retire the command before the caller's buffer goes away: an + * acknowledgment that arrives from now on no longer matches it. + */ + spin_lock(&iface->resp_lock); iface->tx_seq++; iface->out_report = -1; iface->out_flags = 0; iface->resp_buf = NULL; iface->resp_size = 0; + spin_unlock(&iface->resp_lock); mutex_unlock(&iface->out_mutex); return ret; } @@ -1051,16 +1066,26 @@ static int dchid_create_interface(struct dchid_iface *iface) static void dchid_handle_descriptor(struct dchid_iface *iface, void *hid_desc, size_t desc_len) { - if (iface->hid) { + void *desc; + + /* + * Once the interface is queued for creation the HID core may be + * parsing its descriptor, which must then stay as it is. + */ + if (iface->hid || iface->creating) { dev_warn(iface->dchid->dev, "Tried to initialize already started interface %s!\n", iface->name); return; } - iface->hid_desc = devm_kmemdup(iface->dchid->dev, hid_desc, desc_len, GFP_KERNEL); - if (!iface->hid_desc) + desc = devm_kmemdup(iface->dchid->dev, hid_desc, desc_len, GFP_KERNEL); + if (!desc) return; + /* An interface has one descriptor: a repeated one replaces it. */ + if (iface->hid_desc) + devm_kfree(iface->dchid->dev, iface->hid_desc); + iface->hid_desc = desc; iface->hid_desc_len = desc_len; } @@ -1362,26 +1387,29 @@ static void dchid_handle_ack(struct dchid_iface *iface, struct dchid_hdr *hdr, v shdr->length, hdr->length - sizeof(*shdr)); return; } + + /* The command must not be retired between the checks and the copy. */ + spin_lock(&iface->resp_lock); if (shdr->flags != iface->out_flags) { dev_err(iface->dchid->dev, "Received unexpected flags 0x%x on ACK channel (expected 0x%x)\n", shdr->flags, iface->out_flags); - return; + goto out; } if (shdr->length < 1) { dev_err(iface->dchid->dev, "Received length 0 output report ack\n"); - return; + goto out; } if (iface->tx_seq != hdr->seq) { dev_err(iface->dchid->dev, "Received ACK with bad seq (expected %d, got %d)\n", iface->tx_seq, hdr->seq); - return; + goto out; } if (iface->out_report != payload[0]) { dev_err(iface->dchid->dev, "Received ACK with bad report (expected %d, got %d\n", iface->out_report, payload[0]); - return; + goto out; } /* @@ -1402,6 +1430,8 @@ static void dchid_handle_ack(struct dchid_iface *iface, struct dchid_hdr *hdr, v iface->out_report = -1; iface->retcode = shdr->retcode; complete(&iface->out_complete); +out: + spin_unlock(&iface->resp_lock); } /* From 23055f686b1d4c53918545d15d270bb57e96cc92 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:49:01 +1100 Subject: [PATCH 0492/1514] soc: apple: sep: only use an xART store on the internal NVMe disk The xART store is opened through the iBootSystemContainer partition-label link under /dev/disk/by-partlabel. That name is set by udev from the GPT label of any disk, so it can resolve to a partition on a USB, Thunderbolt, PCIe or loop device that carries the same label, and nothing after the open ties the device to the machine's own disk. The container always lives on the SoC's embedded NVMe disk. Add sep_store_open_internal_block(), which opens the partition as before and then requires the nearest platform-bus ancestor of its disk to be bound to the embedded NVMe (ANS) driver, and use it for the store owner. A device elsewhere is closed and refused with a warning, and the driver carries on as when the partition is absent. Add KUnit cases for the ancestry check: the embedded controller is accepted; USB, PCIe NVMe, an unbound controller, a disk without a platform ancestor and a disk below a nested platform device are refused. Signed-off-by: Ryan Murray --- drivers/soc/apple/shim.h | 1 + drivers/soc/apple/shim.rs | 14 ++++ drivers/soc/apple/store_shim.c | 47 ++++++++++++ drivers/soc/apple/store_shim_test.c | 106 ++++++++++++++++++++++++++++ drivers/soc/apple/xart_store.rs | 5 +- 5 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 drivers/soc/apple/store_shim_test.c diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 1ca60f1b338a89..675ae86fe7226b 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -55,6 +55,7 @@ void *sep_store_open_trunc(const char *path); void *sep_store_open_writable_existing(const char *path); void *sep_store_open_ro(const char *path); void *sep_store_open_block(const char *path, int writable); +void *sep_store_open_internal_block(const char *path, int writable); void sep_store_close(void *handle); long long sep_store_size(void *handle); long sep_store_read(void *handle, long long off, void *buf, size_t len); diff --git a/drivers/soc/apple/shim.rs b/drivers/soc/apple/shim.rs index e370a91b4c4e88..0bab5cb1e47ae1 100644 --- a/drivers/soc/apple/shim.rs +++ b/drivers/soc/apple/shim.rs @@ -12,6 +12,7 @@ extern "C" { fn sep_store_open_writable_existing(path: *const c_char) -> *mut c_void; fn sep_store_open_ro(path: *const c_char) -> *mut c_void; fn sep_store_open_block(path: *const c_char, writable: c_int) -> *mut c_void; + fn sep_store_open_internal_block(path: *const c_char, writable: c_int) -> *mut c_void; fn sep_store_close(handle: *mut c_void); fn sep_store_size(handle: *mut c_void) -> i64; fn sep_store_read(handle: *mut c_void, off: i64, buf: *mut c_void, len: usize) -> c_long; @@ -104,6 +105,19 @@ impl StoreFile { Ok(StoreFile { handle }) } + /// As [`Self::open_block`], and the device must be on the internal NVMe + /// disk: `path` names the partition but does not identify the disk. + pub(crate) fn open_internal_block(path: &CStr, writable: bool) -> Result { + // SAFETY: `path` is NUL-terminated; as `open_block`, and the shim + // also rejects a device that is not below the embedded NVMe controller. + let handle = + unsafe { sep_store_open_internal_block(path.as_char_ptr(), c_int::from(writable)) }; + if handle.is_null() { + return Err(ENODEV); + } + Ok(StoreFile { handle }) + } + pub(crate) fn size(&self) -> Result { // SAFETY: `handle` is live per the type invariant. let n = unsafe { sep_store_size(self.handle) }; diff --git a/drivers/soc/apple/store_shim.c b/drivers/soc/apple/store_shim.c index c1773fa2b64124..42d6ea2e6c5233 100644 --- a/drivers/soc/apple/store_shim.c +++ b/drivers/soc/apple/store_shim.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -112,6 +113,47 @@ void *sep_store_open_block(const char *path, int writable) return f; } +/* The platform driver of the SoC's embedded (ANS) NVMe controller. */ +#define SEP_STORE_ANS_DRIVER "nvme-apple" + +/* + * Whether @dev, a disk's device, sits below the embedded NVMe controller. The + * first platform-bus ancestor must be bound to the ANS driver: an NVMe + * namespace's parent is its controller, whose parent is the ANS platform + * device. A disk behind USB, PCIe/Thunderbolt or a loop device reaches a + * different platform device, or none, and is refused. + */ +static bool sep_store_dev_is_internal(const struct device *dev) +{ + for (dev = dev->parent; dev; dev = dev->parent) { + const struct device_driver *drv; + + if (!dev_is_platform(dev)) + continue; + drv = READ_ONCE(dev->driver); + return drv && !strcmp(drv->name, SEP_STORE_ANS_DRIVER); + } + return false; +} + +/* + * As sep_store_open_block(), for the enclave's own store: the path is only a + * name for the partition, so the device it resolves to must also be on the + * internal NVMe disk. + */ +void *sep_store_open_internal_block(const char *path, int writable) +{ + struct file *f = sep_store_open_block(path, writable); + + if (f && !sep_store_dev_is_internal(disk_to_dev(file_bdev(f)->bd_disk))) { + pr_warn_ratelimited("apple-sep: %s is not on the internal NVMe disk; not used\n", + path); + filp_close(f, NULL); + return NULL; + } + return f; +} + void sep_store_close(void *handle) { if (handle) @@ -180,3 +222,8 @@ int sep_store_sync_parent(void *handle) fput(dir); return ret; } + +/* Like the module's Rust tests, which need KUnit built in. */ +#if IS_ENABLED(CONFIG_APPLE_SEP_KUNIT_TEST) && IS_BUILTIN(CONFIG_KUNIT) +#include "store_shim_test.c" +#endif diff --git a/drivers/soc/apple/store_shim_test.c b/drivers/soc/apple/store_shim_test.c new file mode 100644 index 00000000000000..57b51c7c650c92 --- /dev/null +++ b/drivers/soc/apple/store_shim_test.c @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the check that the xART store's block device is on the + * internal NVMe disk. The device trees are built by hand and never registered. + */ + +#include + +static const struct device_driver sep_store_test_ans = { .name = "nvme-apple" }; +static const struct device_driver sep_store_test_usb = { .name = "xhci-hcd" }; +static const struct device_driver sep_store_test_pcie = { .name = "pcie-apple" }; + +/* + * disk -> controller -> @host, as for an NVMe namespace, plus two spare + * devices for the cases that insert a bridge or add a top level. Allocated, + * as struct device is too large for the stack. + */ +struct sep_store_test_chain { + struct device host, ctrl, disk, extra, top; +}; + +static struct sep_store_test_chain * +sep_store_test_chain(struct kunit *test, const struct device_driver *drv) +{ + struct sep_store_test_chain *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, c); + c->host.bus = &platform_bus_type; + c->host.driver = (struct device_driver *)drv; + c->ctrl.parent = &c->host; + c->disk.parent = &c->ctrl; + return c; +} + +static void sep_store_accepts_the_embedded_nvme(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_ans); + + KUNIT_EXPECT_TRUE(test, sep_store_dev_is_internal(&c->disk)); +} + +static void sep_store_refuses_a_usb_disk(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_usb); + + /* disk -> SCSI host -> USB controller */ + c->extra.parent = &c->ctrl; + c->disk.parent = &c->extra; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* PCIe or Thunderbolt NVMe: the PCI function is not a platform device. */ +static void sep_store_refuses_a_pcie_nvme_disk(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_pcie); + + c->extra.parent = &c->host; + c->ctrl.parent = &c->extra; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +static void sep_store_refuses_an_unbound_controller(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, NULL); + + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* A loop device, or any disk with no platform ancestor. */ +static void sep_store_refuses_a_disk_without_a_controller(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, NULL); + + c->ctrl.parent = NULL; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); + c->disk.parent = NULL; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +/* Only the nearest platform ancestor decides. */ +static void sep_store_checks_the_nearest_platform_device(struct kunit *test) +{ + struct sep_store_test_chain *c = sep_store_test_chain(test, &sep_store_test_usb); + + c->top.bus = &platform_bus_type; + c->top.driver = (struct device_driver *)&sep_store_test_ans; + c->host.parent = &c->top; + KUNIT_EXPECT_FALSE(test, sep_store_dev_is_internal(&c->disk)); +} + +static struct kunit_case sep_store_internal_cases[] = { + KUNIT_CASE(sep_store_accepts_the_embedded_nvme), + KUNIT_CASE(sep_store_refuses_a_usb_disk), + KUNIT_CASE(sep_store_refuses_a_pcie_nvme_disk), + KUNIT_CASE(sep_store_refuses_an_unbound_controller), + KUNIT_CASE(sep_store_refuses_a_disk_without_a_controller), + KUNIT_CASE(sep_store_checks_the_nearest_platform_device), + {} +}; + +static struct kunit_suite sep_store_internal_suite = { + .name = "apple_sep_store_internal", + .test_cases = sep_store_internal_cases, +}; + +kunit_test_suite(sep_store_internal_suite); diff --git a/drivers/soc/apple/xart_store.rs b/drivers/soc/apple/xart_store.rs index 1a52003a5dd796..75220de0f92942 100644 --- a/drivers/soc/apple/xart_store.rs +++ b/drivers/soc/apple/xart_store.rs @@ -12,7 +12,8 @@ use crate::shim; use kernel::prelude::*; /// The raw-extent owner opens this whole partition (the iBoot system container, -/// where the gigalocker lives) and serves the gigalocker window directly. +/// where the gigalocker lives) and serves the gigalocker window directly. The +/// name is only a hint: the opened device must be on the internal NVMe disk. pub(crate) const OWNER_PATH: &CStr = c"/dev/disk/by-partlabel/iBootSystemContainer"; const BLOCK_SIZE: usize = 0x1000; @@ -118,7 +119,7 @@ impl Store { /// an override of it. Writes additionally require a single-owner extent /// with no snapshots or pending revert, checked on the same block handle. pub(crate) fn open_owner(writes_enabled: bool, start_sector: u64) -> Result { - let file = shim::StoreFile::open_block(OWNER_PATH, writes_enabled)?; + let file = shim::StoreFile::open_internal_block(OWNER_PATH, writes_enabled)?; let base = crate::xart_apfs::locate(&file, writes_enabled)?; if start_sector != 0 { if start_sector.checked_mul(512).ok_or(EINVAL)? != base { From 2384bc598077e5986aab139170041cb2a5c5baef Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:56:40 +1100 Subject: [PATCH 0493/1514] arm64: dts: apple: t8122-j615: keep CLKREQ# to the J615 until the J613 is checked The supports-clkreq line for the Wi-Fi port sat in the shared J613/J615 dtsi, so it also told the J613's kernel that CLKREQ# is routed there. The CLKREQ# evidence (the ADT's CLKREQ function on the Wi-Fi bridge and the hardware rows) is from the J615 only, and the pin mux in t8122.dtsi says nothing about the board. Move the property to t8122-j615.dts. The J615 DTBs are unchanged; the J613 DTBs lose the property until a J613 row shows its link is fine with Clock PM and L1.2. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi | 9 --------- arch/arm64/boot/dts/apple/t8122-j615.dts | 9 +++++++++ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index c362debb4c0369..dbb9da8d4e36b3 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -110,15 +110,6 @@ #include "isp-imx558-cfg0.dtsi" -/* - * The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC (the ADT gives the - * Wi-Fi bridge a CLKREQ function), so the link may use Clock PM and the L1 PM - * Substates. - */ -&port00 { - supports-clkreq; -}; - &isp { apple,platform-id = <18>; apple,temporal-filter = <1>; diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index fdb511bd9a4e7c..6f2b10fea10dd3 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -161,3 +161,12 @@ /* Per-device factory data from this Mac's own iBoot system container. */ firmware-name = "apple/mesacal-j615.bin"; }; + +/* + * The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC (the J615 ADT gives + * the Wi-Fi bridge a CLKREQ function), so the link may use Clock PM and the L1 + * PM Substates. + */ +&port00 { + supports-clkreq; +}; From 936a6a7292c686bc17866f10e0822a36f75fa706 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:04:14 +1100 Subject: [PATCH 0494/1514] tools/aurora-sep: install-aurora-sep.sh: keep root off the user's temporary files Two more places where root, under sudo, used a file from a temporary directory of the invoking user: - The report's ADT reader was checked by sha256 as the user and then run as root from the report's work directory (or from a checkout). Root now runs a copy in a directory of its own, written from a descriptor the user's shell opened, and checks that copy's sha256 against M3_ADT_READER's there, as root. The directory is removed when the ADT step ends and by the report's traps. - update-m1n1's and m1n1's configuration (the freeze block, the switch block, the DTBS block, the Neo block and the saved default) was written to a mktemp file and installed from it by name. The text is now built in the shell and piped to root_put(), which writes a 0644 file next to the destination as root and renames it into place. No temporary file of the user's is involved, and a failed write leaves the old file. Without sudo the reader is run where it is, as before. test_m3_pro_mesa's comparison with the 12.2 installer maps the root_put command line to the old install line. Signed-off-by: Ryan Murray --- tools/aurora-sep/install-aurora-sep.sh | 153 +++++++++------- tools/aurora-sep/tests/test_m3_pro_mesa.py | 5 + tools/aurora-sep/tests/test_root_staging.py | 190 ++++++++++++++++++++ 3 files changed, 286 insertions(+), 62 deletions(-) diff --git a/tools/aurora-sep/install-aurora-sep.sh b/tools/aurora-sep/install-aurora-sep.sh index 970e420a2e3675..32eb27b930998f 100755 --- a/tools/aurora-sep/install-aurora-sep.sh +++ b/tools/aurora-sep/install-aurora-sep.sh @@ -875,17 +875,23 @@ update_m1n1_frozen() { "$UPDATE_M1N1_CONF" >/dev/null 2>&1 } +# Write stdin to DEST as root: a new 0644 file of root's, renamed over DEST. What root installs +# as configuration is passed to it this way, from the shell that made it, and never by way of +# a temporary file of the invoking user's. +root_put() { # DEST + # shellcheck disable=SC2016 # expanded by that sh + $sudo sh -c 'umask 022 && mkdir -p "$(dirname "$1")" && t=$(mktemp "$1.XXXXXX") && { cat >"$t" && chmod 0644 "$t" && mv -f "$t" "$1" || { rm -f "$t"; exit 1; }; }' _ "$1" +} + m3_freeze() { - local tmp + local text if update_m1n1_frozen; then M3_FROZEN_BY=already return 0 fi - tmp=$(mktemp) - if [[ -f $UPDATE_M1N1_CONF ]]; then cat "$UPDATE_M1N1_CONF" >"$tmp"; fi - printf '%s\nM1N1_UPDATE_DISABLED=1\n%s\n' "$M3_FREEZE_BEGIN" "$M3_FREEZE_END" >>"$tmp" - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" - rm -f "$tmp" + text=$({ if [[ -f $UPDATE_M1N1_CONF ]]; then cat "$UPDATE_M1N1_CONF"; fi; } && + printf '%s\nM1N1_UPDATE_DISABLED=1\n%s\nx' "$M3_FREEZE_BEGIN" "$M3_FREEZE_END") + printf '%s' "${text%x}" | root_put "$UPDATE_M1N1_CONF" update_m1n1_frozen || die "could not freeze update-m1n1 in $UPDATE_M1N1_CONF; nothing was installed" M3_FROZEN_BY=aurora-sep } @@ -900,16 +906,15 @@ m3_unfrozen() { # Lift only this script's freeze; a file that held nothing else goes. m3_unfreeze() { - local tmp + local text [[ -f $UPDATE_M1N1_CONF ]] && grep -qxF "$M3_FREEZE_BEGIN" "$UPDATE_M1N1_CONF" || return 0 - tmp=$(mktemp) - m3_unfrozen >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + text=$(m3_unfrozen && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" } # m1n1's boot.bin on the EFI partition, where macOS can reach it. Omarchy @@ -1309,21 +1314,20 @@ update_m1n1_customised() { # Lift the M3 bring-up's freeze: only its own three lines, and its marker. # The original is kept so --uninstall can put the freeze back. m3gpu_unfreeze() { - local tmp + local text [[ -f $UPDATE_M1N1_CONF ]] && grep -qxF "${M3GPU_FREEZE[0]}" "$UPDATE_M1N1_CONF" || return 0 [[ -f $STATE/update-m1n1.m3gpu.saved ]] || $sudo cp -p "$UPDATE_M1N1_CONF" "$STATE/update-m1n1.m3gpu.saved" - tmp=$(mktemp) - m3gpu_unfrozen >"$tmp" + text=$(m3gpu_unfrozen && printf x) + text=${text%x} if [[ -e $M3GPU_MARKER ]]; then [[ -f $STATE/m3gpu-marker.saved ]] || $sudo touch "$STATE/m3gpu-marker.saved" $sudo rm -f "$M3GPU_MARKER" fi - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" say "Lifted the M3 bring-up's freeze on update-m1n1 (from install-m3gpu.sh)" } @@ -1340,7 +1344,7 @@ m1n1_conf_without_switches() { } m3_switches_write() { - local tmp s begin=$M1N1_CONF_BEGIN end=$M1N1_CONF_END + local text s begin=$M1N1_CONF_BEGIN end=$M1N1_CONF_END if is_m3_air; then begin=$M1N1_CONF_AIR_BEGIN end=$M1N1_CONF_AIR_END @@ -1348,29 +1352,25 @@ m3_switches_write() { begin=$M1N1_CONF_MAX_BEGIN end=$M1N1_CONF_MAX_END fi - tmp=$(mktemp) - m1n1_conf_without_switches >"$tmp" - { + text=$(m1n1_conf_without_switches && { echo "$begin" for s in $(m3_switches); do echo "$s"; done echo "$end" - } >>"$tmp" - $sudo install -m 644 "$tmp" "$M1N1_CONF" - rm -f "$tmp" + } && printf x) + printf '%s' "${text%x}" | root_put "$M1N1_CONF" } m3_switches_remove() { - local tmp + local text [[ -f $M1N1_CONF ]] && grep -qxF -e "$M1N1_CONF_BEGIN" -e "$M1N1_CONF_AIR_BEGIN" -e "$M1N1_CONF_MAX_BEGIN" "$M1N1_CONF" || return 0 - tmp=$(mktemp) - m1n1_conf_without_switches >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$M1N1_CONF" + text=$(m1n1_conf_without_switches && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$M1N1_CONF" else $sudo rm -f "$M1N1_CONF" fi - rm -f "$tmp" } # The M3 path an earlier install took, or nothing. @@ -3514,7 +3514,7 @@ EOF # version number, kept for the fallback entry) without the Touch ID sensor node. # Point it at whatever directory linux-aurora owns, now and after its updates. m1n1_update() { - local target conf=$UPDATE_M1N1_CONF tmp + local target conf=$UPDATE_M1N1_CONF text local -a drop=(-e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d') [[ -f $conf && ! -f $STATE/update-m1n1.default.saved ]] && $sudo cp "$conf" "$STATE/update-m1n1.default.saved" @@ -3527,11 +3527,7 @@ m1n1_update() { if is_neo && [[ $NEO_AURORA_M1N1 == 1 ]]; then drop+=(-e '/^[[:space:]]*\(export[[:space:]]\{1,\}\)\{0,1\}M1N1=/d') fi - tmp=$(mktemp) - if [[ -f $conf ]]; then - $sudo sed "${drop[@]}" "$conf" >"$tmp" - fi - cat >>"$tmp" <<'EOF' + text=$({ if [[ -f $conf ]]; then $sudo sed "${drop[@]}" "$conf"; fi; } && cat <<'EOF' # aurora-sep: build m1n1's stage 2 from the device trees the installed # linux-aurora package owns, which carry the Touch ID sensor node. # @@ -3543,9 +3539,10 @@ m1n1_update() { # $(...), so the pipeline must succeed even when grep matches nothing.) DTBS=$(pacman -Qlq linux-aurora 2>/dev/null | grep '/dtbs/[^/]*\.dtb$' || true) EOF - if ((NEO_GPU)); then echo "M1N1=/usr/lib/m1n1-neo/m1n1.bin" >>"$tmp"; fi - $sudo install -m 644 "$tmp" "$conf" - rm -f "$tmp" + ) + text+=$'\n' + if ((NEO_GPU)); then text+=$'M1N1=/usr/lib/m1n1-neo/m1n1.bin\n'; fi + printf '%s' "$text" | root_put "$conf" if [[ ! -f $STATE/boot.bin.saved ]] && target=$(esp_bootbin); then $sudo cp "$target" "$STATE/boot.bin.saved" fi @@ -3814,13 +3811,11 @@ neo_radio_notice() { # update-m1n1's configuration (without this script's own M3 freeze from 11.36), # or that there was none; the bring-up's freeze; and boot.bin itself. snapshot_boot_state() { - local tmp target + local text target if [[ ! -e $STATE/update-m1n1.default.saved && ! -e $STATE/update-m1n1.absent ]]; then if [[ -f $UPDATE_M1N1_CONF ]]; then - tmp=$(mktemp) - m3_unfrozen >"$tmp" - $sudo install -m 644 "$tmp" "$STATE/update-m1n1.default.saved" - rm -f "$tmp" + text=$(m3_unfrozen && printf x) + printf '%s' "${text%x}" | root_put "$STATE/update-m1n1.default.saved" else $sudo touch "$STATE/update-m1n1.absent" fi @@ -5083,6 +5078,39 @@ m3_adt_reader() { echo "$M3_WORK/$file" } +# Under sudo, root does not run the reader from where the invoking user's processes can write +# (the report's work directory, or a checkout): it runs a copy in a directory of its own +# (M3_ADT_ROOT), and checks that copy's sha256 against M3_ADT_READER's there, as root. The +# user's shell opens the source, so root opens nothing the user named. Sets M3_ADT_RUN to the +# reader to run; or, returning 1, M3_ADT_WHY to why there is none. Without sudo the reader is +# run where it is. +M3_ADT_ROOT="" M3_ADT_RUN="" M3_ADT_WHY="" +m3_adt_reader_root() { # READER + M3_ADT_RUN=$1 M3_ADT_WHY="" + [[ -n $sudo ]] || return 0 + m3_adt_reader_root_done + if ! M3_ADT_ROOT=$($sudo mktemp -d); then + M3_ADT_ROOT="" + M3_ADT_WHY="could not make a directory for root's copy of the ADT reader, so the ADT was not read" + return 1 + fi + M3_ADT_RUN=$M3_ADT_ROOT/${1##*/} + # shellcheck disable=SC2016 # expanded by that sh + if ! $sudo sh -c 'umask 022 && cat >"$1"' _ "$M3_ADT_RUN" <"$1"; then + M3_ADT_WHY="could not copy the ADT reader for root, so the ADT was not read" + return 1 + fi + if [[ -n $M3_ADT_READER && + $($sudo sha256sum -- "$M3_ADT_RUN" | cut -d' ' -f1) != "${M3_ADT_READER##* }" ]]; then + M3_ADT_WHY="${1##*/} changed after its checksum was checked, so the ADT was not read" + return 1 + fi +} +m3_adt_reader_root_done() { + if [[ -n $M3_ADT_ROOT ]]; then $sudo rm -rf -- "$M3_ADT_ROOT" || true; fi + M3_ADT_ROOT="" +} + # The largest adt region the report reads (an ADT is well under 1 MiB). M3_ADT_MAX_BYTES=$((16 * 1024 * 1024)) # The on-demand ADT read's state, for the traps: whether this run loaded phram, and the reader. @@ -5178,6 +5206,7 @@ m3_adt_unload() { # directory removed. m3_report_cleanup() { m3_adt_unload || true + m3_adt_reader_root_done if [[ -n $M3_PARTIAL ]]; then rm -f "$M3_PARTIAL"; fi if [[ -n $M3_WORK ]]; then rm -rf "$M3_WORK"; fi M3_WORK="" @@ -5248,11 +5277,13 @@ m3_report_adt() { # DIR for ((i = 0; i < 10; i++)); do [[ -e $dev ]] && break; sleep 0.5; done if [[ ! -e $dev ]]; then why="no read-only device node $dev, so the ADT was not read" - elif ! $sudo python3 -I "$reader" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then + elif ! m3_adt_reader_root "$reader"; then + why=$M3_ADT_WHY + elif ! $sudo python3 -I "$M3_ADT_RUN" --check "$dev" >>"$log" 2>"$M3_WORK/adt.err"; then why="the ADT reader's check refused $dev, so the ADT was not read: $(tail -1 "$M3_WORK/adt.err" 2>/dev/null | cut -c1-200 || true)" else echo "read: $dev with ${reader##*/}" >>"$log" - $sudo python3 -I "$reader" "$dev" >"$out" 2>"$M3_WORK/adt.err" & + $sudo python3 -I "$M3_ADT_RUN" "$dev" >"$out" 2>"$M3_WORK/adt.err" & M3_ADT_PID=$! wait "$M3_ADT_PID" || rc=$? M3_ADT_PID="" @@ -5261,7 +5292,7 @@ m3_report_adt() { # DIR else # Only after the ADT was read: phram made exactly the two regions' devices, and the adt # device matched its region, so the log device is its region's too. - m3_report_stage2_log "$1" "$reader" "$log" || true + m3_report_stage2_log "$1" "$M3_ADT_RUN" "$log" || true fi fi fi @@ -5280,6 +5311,7 @@ m3_report_adt() { # DIR echo "unload FAILED: phram stays loaded (in use after udev settled, twice; not forced)" >>"$log" fi fi + m3_adt_reader_root_done after=$(m3_mtd_inventory) printf '== after\n%s\n' "$after" >>"$log" if [[ $after == "$before" ]]; then @@ -8777,19 +8809,17 @@ NEO_SNAPSHOT } neo_gpu_boot_config() { - local tmp - tmp=$(mktemp) - if [[ -f $UPDATE_M1N1_CONF ]]; then - $sudo sed '/^# >>> aurora-sep: Neo stage2$/,/^# <<< aurora-sep: Neo stage2$/d' "$UPDATE_M1N1_CONF" > "$tmp" - fi - cat >>"$tmp" <<'NEO_BOOT_CONFIG' + local text + text=$({ if [[ -f $UPDATE_M1N1_CONF ]]; then + $sudo sed '/^# >>> aurora-sep: Neo stage2$/,/^# <<< aurora-sep: Neo stage2$/d' "$UPDATE_M1N1_CONF" + fi; } && cat <<'NEO_BOOT_CONFIG' # >>> aurora-sep: Neo stage2 M1N1=/usr/lib/m1n1-neo/m1n1.bin DTBS=$(pacman -Qlq linux-aurora 2>/dev/null | grep '/dtbs/[^/]*\.dtb$' || true) # <<< aurora-sep: Neo stage2 NEO_BOOT_CONFIG - $sudo install -Dm644 "$tmp" "$UPDATE_M1N1_CONF" - rm -f "$tmp" + ) + printf '%s\n' "$text" | root_put "$UPDATE_M1N1_CONF" } neo_gpu_restore() { @@ -8856,20 +8886,19 @@ m3max_bootbin_record() { # one without the DTBS block m1n1_update wrote for the variant's rebuilds. Then frozen by this # script (m3_freeze), so no kernel or m1n1 update rebuilds the boot.bin that was put back. m3max_conf_kernel_only() { - local tmp + local text if [[ -f $STATE/update-m1n1.default.saved ]]; then $sudo install -m 644 "$STATE/update-m1n1.default.saved" "$UPDATE_M1N1_CONF" elif [[ -e $STATE/update-m1n1.absent ]]; then $sudo rm -f "$UPDATE_M1N1_CONF" elif [[ -f $UPDATE_M1N1_CONF ]]; then - tmp=$(mktemp) - $sudo sed -e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d' "$UPDATE_M1N1_CONF" >"$tmp" - if grep -q '[^[:space:]]' "$tmp"; then - $sudo install -m 644 "$tmp" "$UPDATE_M1N1_CONF" + text=$($sudo sed -e '/^# aurora-sep: build m1n1/,/^DTBS=/d' -e '/^DTBS=/d' "$UPDATE_M1N1_CONF" && printf x) + text=${text%x} + if [[ $text =~ [^[:space:]] ]]; then + printf '%s' "$text" | root_put "$UPDATE_M1N1_CONF" else $sudo rm -f "$UPDATE_M1N1_CONF" fi - rm -f "$tmp" fi m3_freeze } diff --git a/tools/aurora-sep/tests/test_m3_pro_mesa.py b/tools/aurora-sep/tests/test_m3_pro_mesa.py index c5450876998cd5..4d708c64069fbc 100644 --- a/tools/aurora-sep/tests/test_m3_pro_mesa.py +++ b/tools/aurora-sep/tests/test_m3_pro_mesa.py @@ -110,6 +110,10 @@ def tree(tc): WORK_WRITE = re.compile(r'^sudo sh -c umask 022 && cat >"\$1" _ (/(?:migrate-pro-session\.py|' r'frozen-dependencies\.py|dependency-result\.json|dependency-files|aurora-m3-gpu-check))$') +# root_put: what 12.2 installed from a temporary file is now passed to root's shell. +ROOT_PUT = re.compile(r'^sudo sh -c umask 022 && mkdir -p "\$\(dirname "\$1"\)" && t=\$\(mktemp "\$1\.XXXXXX"\) && ' + r'\{ cat >"\$t" && chmod 0644 "\$t" && mv -f "\$t" "\$1" \|\| \{ rm -f "\$t"; exit 1; \}; \} _ (\S+)$') + def package_check_log(tc, text): lines = text.splitlines() @@ -125,6 +129,7 @@ def package_check_log(tc, text): for line in lines: if line in ('pacman -Qu --color never', 'pacman -Sy --noconfirm', 'sudo pacman -Sy --noconfirm'): continue line = WORK_WRITE.sub(r'sudo tee \1', line) + line = ROOT_PUT.sub(r'sudo install -m 644 \1', line) # work_to_root: root's own checked copy of the downloads (not in 12.2). if WORK_TO_ROOT.match(line): continue # Root's Python runs isolated (-I) since 12.2. diff --git a/tools/aurora-sep/tests/test_root_staging.py b/tools/aurora-sep/tests/test_root_staging.py index 619e0297018e8a..1d660d4a377de9 100644 --- a/tools/aurora-sep/tests/test_root_staging.py +++ b/tools/aurora-sep/tests/test_root_staging.py @@ -327,5 +327,195 @@ def test_root_refuses_a_work_directory_it_does_not_own(self): self.assertIn('ok', r.stdout) +class RootConfiguration(unittest.TestCase): + """What root installs as update-m1n1's or m1n1's configuration is passed to it by the shell + that made it, and does not sit in a temporary file of the invoking user's on the way.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + self.log = self.root / 'log' + (self.bin / 'fakesudo').write_text(f'#!/bin/sh\necho "sudo $*" >>"{self.log}"\nexec "$@"\n') + # An install that finds its source changed since the shell wrote it: any file under the + # temporary directory that root is asked to install by name has other content by then. + (self.bin / 'install').write_text( + '#!/bin/bash\nfor a in "$@"; do\n' + f' if [[ -f $a && $a == "{self.root}/tmp/"* ]]; then echo CHANGED=1 >"$a"; fi\n' + 'done\nexec /usr/bin/install "$@"\n') + for f in self.bin.iterdir(): + f.chmod(0o755) + (self.root / 'tmp').mkdir() + self.etc = self.root / 'etc' + self.etc.mkdir() + self.state = self.root / 'state' + self.state.mkdir() + self.conf = self.etc / 'update-m1n1' + self.m1n1 = self.etc / 'm1n1.conf' + + def sh(self, body): + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.root}/tmp' +die() {{ echo "DIED: $*"; exit 9; }} +umask 077 +sudo=fakesudo +UPDATE_M1N1_CONF='{self.conf}' M1N1_CONF='{self.m1n1}' STATE='{self.state}' +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + # Nothing of the user's is left in the temporary directory, and none in /etc. + self.assertEqual(list((self.root / 'tmp').iterdir()), []) + self.assertEqual(sorted(p.name for p in self.etc.iterdir() if '.' in p.name and p.name != 'm1n1.conf'), []) + return r + + def mode(self, path): + return stat.S_IMODE(path.stat().st_mode) + + def test_no_user_temporary_file_is_installed_as_root(self): + text = INSTALLER.read_text() + self.assertEqual(re.findall(r'^[^#\n]*\$sudo install\b[^\n]*"\$tmp"[^\n]*', text, re.M), []) + for dest in ('"$UPDATE_M1N1_CONF"', '"$M1N1_CONF"', '"$conf"', '"$STATE/update-m1n1.default.saved"'): + self.assertIn(f'| root_put {dest}', text) + + def test_freeze_and_unfreeze(self): + self.conf.write_text('KEEP=1\n\n') + self.sh('m3_freeze; echo "by=$M3_FROZEN_BY"') + text = self.conf.read_text() + self.assertTrue(text.startswith('KEEP=1\n\n# >>> aurora-sep: keep this M3'), text) + self.assertTrue(text.endswith('\nM1N1_UPDATE_DISABLED=1\n# <<< aurora-sep: keep this M3\'s boot.bin as it is\n'), text) + self.assertNotIn('CHANGED', text) + self.assertEqual(self.mode(self.conf), 0o644) + self.sh('m3_unfreeze') + self.assertEqual(self.conf.read_text(), 'KEEP=1\n\n') + self.assertEqual(self.mode(self.conf), 0o644) + + def test_unfreeze_removes_a_file_that_held_only_the_freeze(self): + self.sh('m3_freeze') + self.assertIn('M1N1_UPDATE_DISABLED=1', self.conf.read_text()) + self.sh('m3_unfreeze') + self.assertFalse(self.conf.exists()) + + def test_switches_write_and_remove(self): + self.m1n1.write_text('other=1\n') + stubs = 'is_m3_air() { false; }; is_m3_max() { false; }; m3_switches() { echo chosen.a=1 chosen.b=0; }\n' + self.sh(stubs + 'm3_switches_write') + lines = self.m1n1.read_text().splitlines() + self.assertEqual(lines[0], 'other=1') + self.assertEqual(lines[2:4], ['chosen.a=1', 'chosen.b=0']) + self.assertEqual(len(lines), 5) + self.assertEqual(self.mode(self.m1n1), 0o644) + self.sh(stubs + 'm3_switches_remove') + self.assertEqual(self.m1n1.read_text(), 'other=1\n') + + def test_boot_state_snapshot_and_neo_block(self): + self.conf.write_text('M1N1=/x/m1n1.bin\n') + self.sh('m3_freeze; snapshot_boot_state || true') + self.assertEqual((self.state / 'update-m1n1.default.saved').read_text(), 'M1N1=/x/m1n1.bin\n') + self.assertEqual(self.mode(self.state / 'update-m1n1.default.saved'), 0o644) + self.sh('m3_unfreeze; neo_gpu_boot_config; neo_gpu_boot_config') + text = self.conf.read_text() + self.assertTrue(text.startswith('M1N1=/x/m1n1.bin\n# >>> aurora-sep: Neo stage2\n'), text) + self.assertEqual(text.count('# >>> aurora-sep: Neo stage2'), 1) + self.assertTrue(text.endswith('# <<< aurora-sep: Neo stage2\n'), text) + self.assertNotIn('CHANGED', text) + + def test_a_failed_write_keeps_the_old_file(self): + self.conf.write_text('KEEP=1\n') + (self.bin / 'mv').write_text('#!/bin/sh\nexit 1\n') + (self.bin / 'mv').chmod(0o755) + script = f""" +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +sudo='' +echo new | root_put '{self.conf}' && echo put-ok +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + r = subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + self.assertNotIn('put-ok', r.stdout) + self.assertEqual(self.conf.read_text(), 'KEEP=1\n') + self.assertEqual([p.name for p in self.etc.iterdir()], ['update-m1n1']) + + +class AdtReaderRootCopy(unittest.TestCase): + """The report's ADT reader: under sudo root runs its own copy, checked as root.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.bin = self.root / 'bin' + self.bin.mkdir() + (self.bin / 'fakesudo').write_text('#!/bin/sh\nexec "$@"\n') + (self.bin / 'fakesudo').chmod(0o755) + (self.root / 'tmp').mkdir() + self.work = self.root / 'work' + self.work.mkdir() + self.reader = self.work / 'aurora-adt-extract.py' + self.reader.write_bytes(b'print("reader")\n') + + def sh(self, body, sudo='fakesudo', pin=None): + pin = sha(b'print("reader")\n') if pin is None else pin + script = f""" +set -euo pipefail +AURORA_SEP_SOURCE_ONLY=1 source '{INSTALLER}' +export TMPDIR='{self.root}/tmp' +umask 077 +sudo={sudo!r} +M3_ADT_READER={('aurora-adt-extract.py ' + pin) if pin else ''!r} +M3_WORK='{self.work}' +{body} +""" + env = {**os.environ, 'PATH': f'{self.bin}:{os.environ["PATH"]}'} + return subprocess.run(['bash', '-c', script], capture_output=True, text=True, env=env) + + def test_root_runs_its_own_checked_copy(self): + r = self.sh(f""" +m3_adt_reader_root '{self.reader}' +echo "run=$M3_ADT_RUN" +echo CHANGED >'{self.reader}' +python3 -I "$M3_ADT_RUN" +stat -c 'mode %a' "$M3_ADT_RUN" +m3_adt_reader_root_done +echo "root=[$M3_ADT_ROOT]" +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + run = Path(re.search(r'^run=(.*)$', r.stdout, re.M).group(1)) + self.assertEqual(run.name, 'aurora-adt-extract.py') + self.assertNotEqual(run.parent, self.work) + self.assertIn('\nreader\nmode 644\nroot=[]\n', r.stdout) + self.assertFalse(run.parent.exists()) + + def test_a_copy_that_differs_from_the_pinned_reader_is_refused(self): + r = self.sh(f""" +echo 'print("other")' >'{self.reader}' +if m3_adt_reader_root '{self.reader}'; then echo accepted; else echo "why=$M3_ADT_WHY"; fi +m3_report_cleanup +""") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertNotIn('accepted', r.stdout) + self.assertIn('why=aurora-adt-extract.py changed after its checksum was checked, so the ADT was not read', r.stdout) + self.assertEqual(list((self.root / 'tmp').iterdir()), []) + + def test_without_sudo_the_reader_runs_where_it_is(self): + r = self.sh(f"m3_adt_reader_root '{self.reader}'; echo \"run=$M3_ADT_RUN root=[$M3_ADT_ROOT]\"", sudo='') + self.assertIn(f'run={self.reader} root=[]', r.stdout) + + def test_the_report_runs_only_roots_copy(self): + text = INSTALLER.read_text() + for name in ('m3_report_adt', 'm3_report_stage2_log'): + body = text.split(f'\n{name}() {{', 1)[1].split('\n}\n', 1)[0] + runs = re.findall(r'\$sudo python3 -I "\$(\w+)"', body) + self.assertGreaterEqual(len(runs), 2, name) + adt = text.split('\nm3_report_adt() {', 1)[1].split('\n}\n', 1)[0] + self.assertEqual(set(re.findall(r'\$sudo python3 -I "\$(\w+)"', adt)), {'M3_ADT_RUN'}) + self.assertIn('m3_report_stage2_log "$1" "$M3_ADT_RUN" "$log"', adt) + self.assertLess(adt.index('m3_adt_reader_root "$reader"'), adt.index('$sudo python3 -I')) + + if __name__ == '__main__': unittest.main() From cd74f48616aa6eab1f353cee98cfb265b44ff3dc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:06 +1100 Subject: [PATCH 0495/1514] gpio: macsmc: add KUnit tests Add tests for the gPxx key names of the pins, the output command words, the J700 pcIO and J713 radio lines with their remembered levels, the DT output and pcIO templates, the valid line mask and the pcIO output-command chip. A static stub replaces SMC writes. Not covered: lookups that go through apple_smc_get_key_by_index() and apple_smc_rw(), which have no stub reachable from outside the MFD. Signed-off-by: Ryan Murray --- drivers/gpio/Kconfig | 13 + drivers/gpio/gpio-macsmc-test.c | 467 +++++++++++++++++++++++++++ drivers/gpio/gpio-macsmc.c | 4 + drivers/gpio/gpio-macsmc.kunitconfig | 12 + 4 files changed, 496 insertions(+) create mode 100644 drivers/gpio/gpio-macsmc-test.c create mode 100644 drivers/gpio/gpio-macsmc.kunitconfig diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig index a48586bb8edbae..b35f8bbe369624 100644 --- a/drivers/gpio/Kconfig +++ b/drivers/gpio/Kconfig @@ -1557,6 +1557,19 @@ config GPIO_MACSMC This driver can also be built as a module. If so, the module will be called gpio-macsmc. +config GPIO_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC GPIO driver" if !KUNIT_ALL_TESTS + depends on GPIO_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC GPIO driver: the gPxx key names of + the pins, the output command words, the J700 pcIO and J713 radio + lines with their remembered levels, the DT output and pcIO + templates, the valid line mask and the pcIO output-command chip. + A static stub replaces SMC writes, so the tests need no Apple + hardware. + config GPIO_MADERA tristate "Cirrus Logic Madera class codecs" depends on PINCTRL_MADERA diff --git a/drivers/gpio/gpio-macsmc-test.c b/drivers/gpio/gpio-macsmc-test.c new file mode 100644 index 00000000000000..50482dd40e5638 --- /dev/null +++ b/drivers/gpio/gpio-macsmc-test.c @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC GPIO driver: the gPxx key names, the output + * command words, the board-specific lines (J700 pcIO outputs, the J713 radio + * line) with their cached levels, the DT command templates and the + * pcIO output-command variant. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST); the gpio_chip is registered with gpiolib so the + * driver's callbacks run on a real chip. The SMC has no keys here, so no + * line needs an SMC read. + * + * Included by gpio-macsmc.c. + */ + +#include +#include +#include +#include + +#define GPIO_TEST_GP ((smc_key)_SMC_KEY("gP\0\0")) +#define GPIO_TEST_GPL ((smc_key)_SMC_KEY("gp\0\0")) + +struct macsmc_gpio_test_write { + smc_key key; + size_t size; + u64 val; +}; + +struct macsmc_gpio_test { + struct apple_smc smc; + u8 shmem[256]; + /* + * The driver state, and the pcIO commands it points at, live in ctx: + * ctx is allocated before the device, so they outlive the gpio_chip + * that the device's devres removes at the end of the case. + */ + struct macsmc_gpio gpio; + u64 commands[2]; + struct macsmc_gpio *smcgp; + struct device *dev; + struct software_node swnode; + struct macsmc_gpio_test_write writes[8]; + unsigned int nr_writes; + int write_ret; +}; + +static int macsmc_gpio_test_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_gpio_test *ctx = container_of(smc, struct macsmc_gpio_test, smc); + struct macsmc_gpio_test_write *w; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->key = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_writes++; + return ctx->write_ret; +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_remove_swnode, device_remove_software_node, + struct device *); +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_unregister_swnode, software_node_unregister, + const struct software_node *); + +static struct macsmc_gpio_test *macsmc_gpio_test_alloc(struct kunit *test, + const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + /* + * The gpiochip's device shares the parent's fwnode and drops its + * reference after the parent's devres runs, so the node is registered + * before the device and unregistered after it is gone. A managed node + * would get its reference dropped once per device. + */ + if (props) { + ctx->swnode.properties = props; + KUNIT_ASSERT_EQ(test, software_node_register(&ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_unregister_swnode, + &ctx->swnode); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + if (props) { + KUNIT_ASSERT_EQ(test, device_add_software_node(ctx->dev, &ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_remove_swnode, ctx->dev); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->smcgp = &ctx->gpio; + ctx->smcgp->dev = ctx->dev; + ctx->smcgp->smc = &ctx->smc; + mutex_init(&ctx->smcgp->j713_reg_on_lock); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_gpio_test_write); + return ctx; +} + +/* The chip macsmc_gpio_probe() registers, on an SMC without GPIO keys. */ +static void macsmc_gpio_test_register(struct kunit *test, struct macsmc_gpio_test *ctx, + smc_key base_key, bool j700, bool j713) +{ + struct macsmc_gpio *smcgp = ctx->smcgp; + + smcgp->base_key = base_key; + smcgp->j700_pcio = j700; + smcgp->j713 = j713; + KUNIT_ASSERT_EQ(test, macsmc_gpio_parse_templates(smcgp), 0); + + smcgp->gc.label = "macsmc-gpio-test"; + smcgp->gc.owner = THIS_MODULE; + smcgp->gc.get = macsmc_gpio_get; + smcgp->gc.set = macsmc_gpio_set; + smcgp->gc.get_direction = macsmc_gpio_get_direction; + smcgp->gc.init_valid_mask = macsmc_gpio_init_valid_mask; + smcgp->gc.can_sleep = true; + smcgp->gc.ngpio = MAX_GPIO; + smcgp->gc.base = -1; + smcgp->gc.parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, &smcgp->gc, smcgp), 0); +} + +static void macsmc_gpio_test_expect_write(struct kunit *test, + struct macsmc_gpio_test *ctx, + unsigned int idx, smc_key key, + size_t size, u64 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].key, key, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].size, size, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].val, val, "write %u", idx); +} + +/* Pin numbers become two lowercase hex digits after the base key. */ +static void macsmc_gpio_test_key_name(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0), _SMC_KEY("gP00")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x0a), _SMC_KEY("gP0a")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x13), _SMC_KEY("gP13")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x3f), _SMC_KEY("gP3f")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0x05), _SMC_KEY("gp05")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0xc1), _SMC_KEY("gpc1")); +} + +/* Key names parse back to pin numbers; non-hex names are rejected. */ +static void macsmc_gpio_test_key_nr(struct kunit *test) +{ + unsigned int i; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP13")), 0x13); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0a")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0A")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gp3f")), 63); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPzz")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPg0")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0-")), -1); + + for (i = 0; i < MAX_GPIO; i++) + KUNIT_EXPECT_EQ_MSG(test, macsmc_gpio_nr(macsmc_gpio_key(GPIO_TEST_GP, i)), i, + "pin %u", i); +} + +/* A plain line is set with a CMD_OUTPUT word carrying the level in bit 0. */ +static void macsmc_gpio_test_set_plain(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x2c, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP2c"), 4, CMD_OUTPUT); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), -EIO); +} + +/* On the J713 family gP13 is the radio's reg_on: template | level, cached. */ +static void macsmc_gpio_test_j713_reg_on(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + const unsigned int pin = MACSMC_J713_RADIO_REG_ON_GPIO; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, true); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, pin), GPIO_LINE_DIRECTION_OUT); + /* No readback: nothing is known before the first write. */ + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), -EOPNOTSUPP); + + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 1); + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 0), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE); + + /* A failed write does not change the reported level. */ + ctx->write_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); +} + +/* The radio line is gP13 only: not gp13, not another gP pin. */ +static void macsmc_gpio_test_j713_other_lines(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GPL, false, true); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gp13"), 4, CMD_OUTPUT | 1); + + ctx->smcgp->base_key = GPIO_TEST_GP; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO - 1, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP12"), 4, CMD_OUTPUT | 1); + + /* Without the J713 flag gP13 is a plain line too. */ + ctx->smcgp->j713 = false; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 0), 0); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("gP13"), 4, CMD_OUTPUT); +} + +static const u32 macsmc_gpio_test_out_tmpl[] = { 5, 0x00a00000, 0x3e, 0x00300000 }; + +static const struct property_entry macsmc_gpio_test_out_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + {} +}; + +/* apple,output-templates: pairs; the write is template | level. */ +static void macsmc_gpio_test_output_template(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_out_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 6)); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 5), GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x3e, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, 0x00a00001); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP3e"), 4, 0x00300000); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 0), -EIO); +} + +static const u32 macsmc_gpio_test_pcio_tmpl[] = { 21, 0x40000, 0x150000 }; + +static const struct property_entry macsmc_gpio_test_pcio_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", macsmc_gpio_test_pcio_tmpl), + {} +}; + +/* + * J700: pins 19 and 8 and the pcio-templates pins are eight-byte pcIO + * writes, hi << 32 | lo | level, whose level is remembered for reads. + */ +static void macsmc_gpio_test_j700_pcio(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, MACSMC_J700_AFE_RESET_GPIO), + GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_RADIO_REG_ON_HI << 32) | + MACSMC_J700_RADIO_REG_ON_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, + (0x150000ULL << 32) | 0x40000 | 1); + macsmc_gpio_test_expect_write(test, ctx, 3, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO); + + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_AFE_RESET_GPIO), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + KUNIT_EXPECT_EQ(test, gc->get(gc, 21), 1); + + /* A failed write keeps the remembered level. */ + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 0), -EIO); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + + /* An output template still wins over pcIO for its own pin. */ + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 5, _SMC_KEY("gP05"), 4, 0x00a00001); +} + +/* The valid mask is the board's fixed lines plus the templated ones. */ +static void macsmc_gpio_test_valid_mask(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + unsigned int i, valid = 0; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + for (i = 0; i < MAX_GPIO; i++) + valid += gpiochip_line_is_valid(gc, i); + KUNIT_EXPECT_EQ(test, valid, 5); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_RADIO_REG_ON_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* Off the J700, pcio-templates do nothing: those pins are plain gPxx lines. */ +static void macsmc_gpio_test_pcio_template_not_j700(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP15"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, CMD_OUTPUT | 1); +} + +static int macsmc_gpio_test_parse(struct kunit *test, const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, name, props); + + return macsmc_gpio_parse_templates(ctx->smcgp); +} + +/* Malformed template lists are refused, the pin bound is 0..63. */ +static void macsmc_gpio_test_template_errors(struct kunit *test) +{ + static const u32 odd[] = { 5, 0x00a00000, 6 }; + static const u32 pin64[] = { 64, 0x00a00000 }; + static const u32 pin63[] = { 63, 0x00a00000 }; + static const u32 pcio_short[] = { 21, 0x40000, 0x150000, 22 }; + static const u32 pcio_pin64[] = { 64, 0x40000, 0x150000 }; + const struct property_entry p_odd[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", odd), {} + }; + const struct property_entry p_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin64), {} + }; + const struct property_entry p_pin63[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin63), {} + }; + const struct property_entry p_pcio_short[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_short), {} + }; + const struct property_entry p_pcio_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_pin64), {} + }; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse0", p_odd), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse1", p_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse2", p_pin63), 0); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse3", p_pcio_short), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse4", p_pcio_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse5", NULL), 0); +} + +/* apple,smc-pcio-gpio: line N writes output_commands[N] | level as LE64 to pcIO. */ +static void macsmc_gpio_test_pcio_outputs(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct macsmc_gpio *smcgp = ctx->smcgp; + struct gpio_chip *gc = &smcgp->gc; + static const u64 commands[] = { 0x0013000000010000ULL, 0x0008000000800000ULL }; + + BUILD_BUG_ON(sizeof(commands) != sizeof(ctx->commands)); + memcpy(ctx->commands, commands, sizeof(commands)); + smcgp->output_commands = ctx->commands; + + /* As macsmc_pcio_probe() sets it up. */ + gc->label = "macsmc-pcio-output-test"; + gc->owner = THIS_MODULE; + gc->get = macsmc_pcio_get; + gc->set = macsmc_pcio_set; + gc->direction_output = macsmc_pcio_set; + gc->get_direction = macsmc_pcio_get_direction; + gc->can_sleep = true; + gc->ngpio = ARRAY_SIZE(commands); + gc->base = -1; + gc->parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, gc, smcgp), 0); + + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 1), GPIO_LINE_DIRECTION_OUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, 0), -EOPNOTSUPP); + + /* A positive status from the write is success. */ + ctx->write_ret = 8; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 1), 0); + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->direction_output(gc, 1, 0), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 1, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, commands[0] | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, commands[1]); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, commands[1] | 1); + + ctx->write_ret = -EBUSY; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 0), -EBUSY); +} + +static struct kunit_case macsmc_gpio_test_cases[] = { + KUNIT_CASE(macsmc_gpio_test_key_name), + KUNIT_CASE(macsmc_gpio_test_key_nr), + KUNIT_CASE(macsmc_gpio_test_set_plain), + KUNIT_CASE(macsmc_gpio_test_j713_reg_on), + KUNIT_CASE(macsmc_gpio_test_j713_other_lines), + KUNIT_CASE(macsmc_gpio_test_output_template), + KUNIT_CASE(macsmc_gpio_test_j700_pcio), + KUNIT_CASE(macsmc_gpio_test_valid_mask), + KUNIT_CASE(macsmc_gpio_test_pcio_template_not_j700), + KUNIT_CASE(macsmc_gpio_test_template_errors), + KUNIT_CASE(macsmc_gpio_test_pcio_outputs), + {} +}; + +static struct kunit_suite macsmc_gpio_test_suite = { + .name = "macsmc-gpio", + .test_cases = macsmc_gpio_test_cases, +}; + +kunit_test_suite(macsmc_gpio_test_suite); diff --git a/drivers/gpio/gpio-macsmc.c b/drivers/gpio/gpio-macsmc.c index 434ed549d4c1ed..68b1802a1eacf0 100644 --- a/drivers/gpio/gpio-macsmc.c +++ b/drivers/gpio/gpio-macsmc.c @@ -599,3 +599,7 @@ module_platform_driver(macsmc_gpio_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC GPIO driver"); + +#if IS_ENABLED(CONFIG_GPIO_MACSMC_KUNIT_TEST) +#include "gpio-macsmc-test.c" +#endif diff --git a/drivers/gpio/gpio-macsmc.kunitconfig b/drivers/gpio/gpio-macsmc.kunitconfig new file mode 100644 index 00000000000000..1b9e736fdd0e7e --- /dev/null +++ b/drivers/gpio/gpio-macsmc.kunitconfig @@ -0,0 +1,12 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/gpio/gpio-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_GPIOLIB=y +CONFIG_GPIO_MACSMC=y +CONFIG_GPIO_MACSMC_KUNIT_TEST=y From 43dd5ccc8337c50f7a107add3298334de7b8ea63 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:07 +1100 Subject: [PATCH 0496/1514] power: reset: macsmc: add KUnit tests Add tests for the MBSE key and the boot_stage and shutdown_flag writes before a restart or power off, the clearing of the boot error and panic counters, the refusal of atomic writes from a non-atomic SMC, and the ac_power_mode attribute's read-modify-write of the power-on policy byte. A static stub replaces SMC writes and a RAM-backed NVMEM device holds the PMU cells. Signed-off-by: Ryan Murray --- drivers/power/reset/Kconfig | 13 + drivers/power/reset/macsmc-reboot-test.c | 454 ++++++++++++++++++ drivers/power/reset/macsmc-reboot.c | 4 + drivers/power/reset/macsmc-reboot.kunitconfig | 13 + 4 files changed, 484 insertions(+) create mode 100644 drivers/power/reset/macsmc-reboot-test.c create mode 100644 drivers/power/reset/macsmc-reboot.kunitconfig diff --git a/drivers/power/reset/Kconfig b/drivers/power/reset/Kconfig index bce996bbef28f5..3cc66edaf551a9 100644 --- a/drivers/power/reset/Kconfig +++ b/drivers/power/reset/Kconfig @@ -149,6 +149,19 @@ config POWER_RESET_MACSMC Say Y here if you have an Apple Silicon Mac. +config POWER_RESET_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC reboot driver" if !KUNIT_ALL_TESTS + depends on POWER_RESET_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC reboot driver: the MBSE key and the + boot_stage and shutdown_flag writes before a restart or power off, + the clearing of the boot error and panic counters, and the + ac_power_mode attribute's read-modify-write of the power-on policy + byte. A static stub replaces SMC writes and a RAM-backed NVMEM + device holds the PMU cells, so the tests need no Apple hardware. + config POWER_RESET_MSM bool "Qualcomm MSM power-off driver" depends on ARCH_QCOM diff --git a/drivers/power/reset/macsmc-reboot-test.c b/drivers/power/reset/macsmc-reboot-test.c new file mode 100644 index 00000000000000..e4db004ec6ec19 --- /dev/null +++ b/drivers/power/reset/macsmc-reboot-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC reboot driver: the MBSE key and NVMEM flag + * sequence before a restart or power off, the boot error and panic counters, + * and the ac_power_mode attribute over the PMU's power-on policy byte. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST). The PMU cells are real NVMEM cells of a RAM-backed + * NVMEM device, found through a cell lookup table. + * + * Included by macsmc-reboot.c. + */ + +#include +#include +#include +#include +#include + +enum { + REBOOT_TEST_SHUTDOWN_FLAG, + REBOOT_TEST_BOOT_STAGE, + REBOOT_TEST_BOOT_ERROR_COUNT, + REBOOT_TEST_PANIC_COUNT, + REBOOT_TEST_PM_SETTING, + REBOOT_TEST_NR_CELLS, +}; + +static const char * const macsmc_reboot_test_cells[] = { + [REBOOT_TEST_SHUTDOWN_FLAG] = "shutdown_flag", + [REBOOT_TEST_BOOT_STAGE] = "boot_stage", + [REBOOT_TEST_BOOT_ERROR_COUNT] = "boot_error_count", + [REBOOT_TEST_PANIC_COUNT] = "panic_count", + [REBOOT_TEST_PM_SETTING] = "pm_setting", +}; + +struct macsmc_reboot_test_write { + u32 where; /* SMC key, or NVMEM offset */ + size_t size; + u32 val; +}; + +struct macsmc_reboot_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_reboot reboot; + struct device *dev; + u8 nvmem[REBOOT_TEST_NR_CELLS]; + /* NVMEM writes and SMC writes, each in order */ + struct macsmc_reboot_test_write nv_writes[8]; + unsigned int nr_nv_writes; + struct macsmc_reboot_test_write smc_writes[4]; + unsigned int nr_smc_writes; + int smc_ret; + int fail_offset; + struct nvmem_cell_lookup lookups[REBOOT_TEST_NR_CELLS]; +}; + +static int macsmc_reboot_test_smc_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_reboot_test *ctx = container_of(smc, struct macsmc_reboot_test, smc); + struct macsmc_reboot_test_write *w; + + if (ctx->nr_smc_writes < ARRAY_SIZE(ctx->smc_writes)) { + w = &ctx->smc_writes[ctx->nr_smc_writes]; + w->where = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_smc_writes++; + return ctx->smc_ret; +} + +static int macsmc_reboot_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_reboot_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + struct macsmc_reboot_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + if (ctx->nr_nv_writes < ARRAY_SIZE(ctx->nv_writes)) { + w = &ctx->nv_writes[ctx->nr_nv_writes]; + w->where = offset; + w->size = bytes; + w->val = *(u8 *)val; + } + ctx->nr_nv_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_reboot_test_del_lookups(void *data) +{ + struct macsmc_reboot_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_reboot_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_reboot_test_cell(struct kunit *test, + struct macsmc_reboot_test *ctx, + unsigned int idx) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, macsmc_reboot_test_cells[idx]); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_cell_put, + cell), 0); + return cell; +} + +/* A reboot handler with every cell, as macsmc_reboot_probe() leaves it. */ +static struct macsmc_reboot_test *macsmc_reboot_test_setup(struct kunit *test) +{ + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_reboot_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, REBOOT_TEST_NR_CELLS, sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + cells[i].name = macsmc_reboot_test_cells[i]; + cells[i].offset = i; + cells[i].bytes = 1; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-reboot-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = REBOOT_TEST_NR_CELLS; + config.ignore_wp = true; + config.reg_read = macsmc_reboot_test_reg_read; + config.reg_write = macsmc_reboot_test_reg_write; + config.size = REBOOT_TEST_NR_CELLS; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "reboot"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = macsmc_reboot_test_cells[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = macsmc_reboot_test_cells[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_del_lookups, + ctx), 0); + + ctx->reboot.dev = ctx->dev; + ctx->reboot.smc = &ctx->smc; + mutex_init(&ctx->reboot.pm_setting_lock); + for (i = 0; i < ARRAY_SIZE(nvmem_names); i++) { + KUNIT_ASSERT_STREQ(test, nvmem_names[i], macsmc_reboot_test_cells[i]); + ctx->reboot.nvm_cells[i] = macsmc_reboot_test_cell(test, ctx, i); + } + ctx->reboot.pm_setting = macsmc_reboot_test_cell(test, ctx, REBOOT_TEST_PM_SETTING); + ctx->reboot.reboot_notify.notifier_call = macsmc_reboot_notify; + dev_set_drvdata(ctx->dev, &ctx->reboot); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_reboot_test_smc_write); + return ctx; +} + +static int macsmc_reboot_test_notify(struct macsmc_reboot_test *ctx, unsigned long action) +{ + return macsmc_reboot_notify(&ctx->reboot.reboot_notify, action, NULL); +} + +static void macsmc_reboot_test_expect_nv(struct kunit *test, struct macsmc_reboot_test *ctx, + unsigned int idx, unsigned int cell, u8 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_nv_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].where, cell, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].size, 1, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].val, val, "write %u", idx); +} + +static void macsmc_reboot_test_expect_mbse(struct kunit *test, struct macsmc_reboot_test *ctx, + smc_key val) +{ + KUNIT_ASSERT_EQ(test, ctx->nr_smc_writes, 1); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].where, SMC_KEY(MBSE)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].size, sizeof(u32)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].val, val); +} + +/* Restart: MBSE = rest, a clean boot_stage and shutdown_flag 0 (power back on). */ +static void macsmc_reboot_test_notify_restart(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG] = 1; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(rest)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 0); +} + +/* Power off: MBSE = offw, a clean boot_stage and shutdown_flag 1 (stay off). */ +static void macsmc_reboot_test_notify_power_off(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 1); +} + +/* A halt is not ours to prepare: nothing is written. */ +static void macsmc_reboot_test_notify_other(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_HALT), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_DOWN + 100), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, ctx->nr_smc_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Missing cells are skipped; MBSE is still written. */ +static void macsmc_reboot_test_notify_no_cells(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->reboot.nvm.shutdown_flag = NULL; + ctx->reboot.nvm.boot_stage = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* A failed MBSE write does not stop the PMU flags from being written. */ +static void macsmc_reboot_test_notify_mbse_error(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->smc_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 1); + + /* Nor does a failed boot_stage write stop shutdown_flag. */ + ctx->smc_ret = 0; + ctx->fail_offset = REBOOT_TEST_BOOT_STAGE; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 0); +} + +/* Logged boot errors and panics are cleared: panic_count first. */ +static void macsmc_reboot_test_error_counts(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 2; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PANIC_COUNT, 0); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_BOOT_ERROR_COUNT, 0); + + ctx->nr_nv_writes = 0; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0xff; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PANIC_COUNT], 0); + + /* Nothing logged: nothing written. */ + ctx->nr_nv_writes = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Without both counter cells the counters are left alone. */ +static void macsmc_reboot_test_error_counts_missing(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 3; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 4; + ctx->reboot.nvm.panic_count = NULL; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT], 3); +} + +/* Bit 5 clear powers on at connect; otherwise bit 0 picks off or restore. */ +static void macsmc_reboot_test_ac_mode_decode(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x21), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xff), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x20), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xfe), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x01), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x00), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xde), AC_POWER_ALWAYS); +} + +static void macsmc_reboot_test_expect_show(struct kunit *test, struct macsmc_reboot_test *ctx, + u8 setting, const char *expect) +{ + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + ctx->nvmem[REBOOT_TEST_PM_SETTING] = setting; + KUNIT_EXPECT_EQ(test, ac_power_mode_show(ctx->dev, &dev_attr_ac_power_mode, buf), + strlen(expect)); + KUNIT_EXPECT_STREQ(test, buf, expect); +} + +static void macsmc_reboot_test_ac_mode_show(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + macsmc_reboot_test_expect_show(test, ctx, 0x21, "[off] restore always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0xa0, "off [restore] always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0x80, "off restore [always]\n"); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +static ssize_t macsmc_reboot_test_store(struct macsmc_reboot_test *ctx, const char *buf) +{ + return ac_power_mode_store(ctx->dev, &dev_attr_ac_power_mode, buf, strlen(buf)); +} + +/* A store changes bits 0 and 5 only, and only when the mode changes. */ +static void macsmc_reboot_test_ac_mode_store(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x80 | PM_SETTING_AC_POWER_MASK; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "restore\n"), 8); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa0); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), 6); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x81); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off"), 3); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa1); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 3); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PM_SETTING, 0xa0); + + /* Unchanged: no write. */ + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off\n"), 4); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 3); +} + +static void macsmc_reboot_test_ac_mode_store_errors(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x21; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "on"), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, ""), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + + ctx->fail_offset = REBOOT_TEST_PM_SETTING; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x21); +} + +/* ac_power_mode exists only with a pm_setting cell. */ +static void macsmc_reboot_test_ac_mode_visible(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct attribute *attr = &dev_attr_ac_power_mode.attr; + + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0644); + ctx->reboot.pm_setting = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); + dev_set_drvdata(ctx->dev, NULL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); +} + +/* + * off1 and phra are atomic writes. On a booted SMC that has not entered + * atomic mode they are refused, and the handlers return at once instead of + * waiting for the power to go (mdelay(100), then a warning). + */ +static void macsmc_reboot_test_atomic_refused(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct sys_off_data data = { .cb_data = &ctx->reboot }; + ktime_t start; + + ctx->smc.boot_stage = APPLE_SMC_INITIALIZED; + ctx->smc.atomic_mode = false; + /* What refuses is the atomic mode check, not the boot stage. */ + KUNIT_ASSERT_EQ(test, apple_smc_write_u32_atomic(&ctx->smc, SMC_KEY(MBSE), + SMC_KEY(off1)), -EIO); + + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_power_off(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_restart(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); +} + +static struct kunit_case macsmc_reboot_test_cases[] = { + KUNIT_CASE(macsmc_reboot_test_notify_restart), + KUNIT_CASE(macsmc_reboot_test_notify_power_off), + KUNIT_CASE(macsmc_reboot_test_notify_other), + KUNIT_CASE(macsmc_reboot_test_notify_no_cells), + KUNIT_CASE(macsmc_reboot_test_notify_mbse_error), + KUNIT_CASE(macsmc_reboot_test_error_counts), + KUNIT_CASE(macsmc_reboot_test_error_counts_missing), + KUNIT_CASE(macsmc_reboot_test_ac_mode_decode), + KUNIT_CASE(macsmc_reboot_test_ac_mode_show), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store_errors), + KUNIT_CASE(macsmc_reboot_test_ac_mode_visible), + KUNIT_CASE(macsmc_reboot_test_atomic_refused), + {} +}; + +static struct kunit_suite macsmc_reboot_test_suite = { + .name = "macsmc-reboot", + .test_cases = macsmc_reboot_test_cases, +}; + +kunit_test_suite(macsmc_reboot_test_suite); diff --git a/drivers/power/reset/macsmc-reboot.c b/drivers/power/reset/macsmc-reboot.c index a2e1422e05bd82..c89c0d892b7f3a 100644 --- a/drivers/power/reset/macsmc-reboot.c +++ b/drivers/power/reset/macsmc-reboot.c @@ -413,3 +413,7 @@ module_platform_driver(macsmc_reboot_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC reboot/poweroff driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_POWER_RESET_MACSMC_KUNIT_TEST) +#include "macsmc-reboot-test.c" +#endif diff --git a/drivers/power/reset/macsmc-reboot.kunitconfig b/drivers/power/reset/macsmc-reboot.kunitconfig new file mode 100644 index 00000000000000..3af2e4d04a7eb2 --- /dev/null +++ b/drivers/power/reset/macsmc-reboot.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/power/reset/macsmc-reboot.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_POWER_RESET=y +CONFIG_POWER_RESET_MACSMC=y +CONFIG_POWER_RESET_MACSMC_KUNIT_TEST=y From 2be1d7ba37818e498335255635e9bc6cdc90d538 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:08 +1100 Subject: [PATCH 0497/1514] Input: macsmc-input - add KUnit tests Add tests for the decoding of the SMC's power button and lid notifications and their handling as wake events while the system goes to sleep, including the lid-open check against MSLD and the settle time. A static stub replaces SMC reads. The tests report KEY_POWER and SW_LID through a real input device and touch global suspend state (pm_wakeup_clear(), pm_system_wakeup()), so they skip once the system is running and only run at boot, before user space. Not covered: the MSLD resync after resume and the dark-wake refusal in .prepare, which need apple_smc_key_exists() to succeed. Signed-off-by: Ryan Murray --- drivers/input/misc/Kconfig | 15 + drivers/input/misc/macsmc-input-test.c | 414 ++++++++++++++++++++ drivers/input/misc/macsmc-input.c | 4 + drivers/input/misc/macsmc-input.kunitconfig | 15 + 4 files changed, 448 insertions(+) create mode 100644 drivers/input/misc/macsmc-input-test.c create mode 100644 drivers/input/misc/macsmc-input.kunitconfig diff --git a/drivers/input/misc/Kconfig b/drivers/input/misc/Kconfig index aad2bc5fb0eb63..d7844492bdec12 100644 --- a/drivers/input/misc/Kconfig +++ b/drivers/input/misc/Kconfig @@ -1034,4 +1034,19 @@ config INPUT_MACSMC_INPUT To compile this driver as a module, choose M here: the module will be called macsmc-input. +config INPUT_MACSMC_INPUT_KUNIT_TEST + bool "KUnit tests for the Apple SMC lid/buttons driver" if !KUNIT_ALL_TESTS + depends on INPUT_MACSMC_INPUT=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && SUSPEND + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC input driver: the decoding of the + SMC's power button and lid notifications, and their handling as + wake events while the system goes to sleep, including the lid-open + check against MSLD and the settle time. A static stub replaces SMC + reads, so the tests need no Apple hardware. + The tests report power button presses and lid changes through an + input device and change global suspend state, so they run only at + boot, before user space, and skip when run later. + endif diff --git a/drivers/input/misc/macsmc-input-test.c b/drivers/input/misc/macsmc-input-test.c new file mode 100644 index 00000000000000..5e1dedd0ab3be9 --- /dev/null +++ b/drivers/input/misc/macsmc-input-test.c @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC input driver: decoding of the SMC's button + * and lid notifications into KEY_POWER and SW_LID, and the sleep window in + * which they are wake events instead, with the lid-open confirmation + * against MSLD and the settle time. + * + * MSLD reads go to a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). Events go to a registered input device; wakeups + * are seen on the device's wakeup source and, for hard wakeups, through + * pm_wakeup_pending(). + * + * The cases touch global PM state (pm_abort_suspend, the dark wake flag) + * and report KEY_POWER and SW_LID through a real input device, which a + * running system's logind would act on by powering off or suspending. So + * the suite runs only at boot, before user space; run later (from the + * kunit debugfs interface or a module) it skips every case. + * + * Included by macsmc-input.c. + */ + +#include +#include +#include + +#define INPUT_TEST_EV(type, hi, lo) (((type) << 16) | ((hi) << 8) | (lo)) +#define INPUT_TEST_BTN(button, state) INPUT_TEST_EV(SMC_EV_BTN, button, state) +#define INPUT_TEST_LID(closed, lo) INPUT_TEST_EV(SMC_EV_LID, closed, lo) + +struct macsmc_input_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_input smcin; + /* MSLD: 1 while the lid is closed, and what its read returns */ + u8 msld; + int msld_ret; + unsigned int msld_reads; + unsigned int saved_flags; +}; + +static int macsmc_input_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_input_test *ctx = container_of(smc, struct macsmc_input_test, smc); + struct kunit *test = kunit_get_current_test(); + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(MSLD)); + KUNIT_EXPECT_EQ(test, size, 1); + ctx->msld_reads++; + if (ctx->msld_ret < 0) + return ctx->msld_ret; + *(u8 *)buf = ctx->msld; + return size; +} + +static void macsmc_input_test_exit(void *data) +{ + struct macsmc_input_test *ctx = data; + + pm_suspend_global_flags = ctx->saved_flags; + pm_wakeup_clear(0); +} + +static struct macsmc_input_test *macsmc_input_test_setup(struct kunit *test) +{ + struct macsmc_input_test *ctx; + struct macsmc_input *smcin; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* SMC commands other than the stubbed read fail: key_exists() is false. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + ctx->saved_flags = pm_suspend_global_flags; + pm_wakeup_clear(0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_input_test_exit, ctx), 0); + + dev = kunit_device_register(test, "input"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_EQ(test, devm_device_init_wakeup(dev), 0); + + smcin = &ctx->smcin; + smcin->dev = dev; + smcin->smc = &ctx->smc; + smcin->nb.notifier_call = macsmc_input_event; + smcin->pm_nb.notifier_call = macsmc_input_pm_notify; + mutex_init(&smcin->lid_lock); + dev_set_drvdata(dev, smcin); + + smcin->input = devm_input_allocate_device(dev); + KUNIT_ASSERT_NOT_NULL(test, smcin->input); + smcin->input->name = "macsmc-input-test"; + input_set_capability(smcin->input, EV_SW, SW_LID); + input_set_capability(smcin->input, EV_KEY, KEY_POWER); + KUNIT_ASSERT_EQ(test, input_register_device(smcin->input), 0); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_input_test_read); + return ctx; +} + +static int macsmc_input_test_event(struct macsmc_input_test *ctx, unsigned long event) +{ + return macsmc_input_event(&ctx->smcin.nb, event, NULL); +} + +static bool macsmc_input_test_key(struct macsmc_input_test *ctx) +{ + return test_bit(KEY_POWER, ctx->smcin.input->key); +} + +static bool macsmc_input_test_lid(struct macsmc_input_test *ctx) +{ + return test_bit(SW_LID, ctx->smcin.input->sw); +} + +static unsigned long macsmc_input_test_wake_events(struct macsmc_input_test *ctx) +{ + return ctx->smcin.dev->power.wakeup->event_count; +} + +/* Was a hard wakeup (one that aborts a suspend) asked for? Clears it. */ +static bool macsmc_input_test_hard_wake(void) +{ + bool pending = pm_wakeup_pending(); + + pm_wakeup_clear(0); + return pending; +} + +static void macsmc_input_test_sleep(struct macsmc_input_test *ctx, unsigned int settle_ms, + unsigned int slept_ms) +{ + ctx->smcin.lid_settle_ms = settle_ms; + ctx->smcin.wakeup_mode = true; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), slept_ms); +} + +/* Only the button and lid event types are this driver's. */ +static void macsmc_input_test_dispatch(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7202, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7101, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x0000, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)), + NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)), NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); +} + +/* Power and Touch ID buttons: bits 15:8 the button, any nonzero low byte is down. */ +static void macsmc_input_test_power_button(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0x80)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + /* Awake, presses are wakeup events but never hard wakeups. */ + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 4); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* "Held" notices and unknown buttons are not key presses. */ +static void macsmc_input_test_other_buttons(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_SHORT, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + /* The long hold's release, never its press: that powers off. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_LONG, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x07, 1)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x02, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); +} + +/* In the sleep window a press is a hard wakeup and no KEY_POWER. */ +static void macsmc_input_test_button_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + /* A release does not wake. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 2); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); +} + +/* Lid: bits 15:8 nonzero is closed; the low byte is not the state. */ +static void macsmc_input_test_lid_awake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0x80, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 0xff)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + + /* Awake, MSLD is not consulted and nothing is a hard wakeup. */ + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* Closing the lid in the sleep window is neither reported nor a wakeup. */ +static void macsmc_input_test_lid_close_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); +} + +/* An open report while MSLD still says closed is held, not a wakeup. */ +static void macsmc_input_test_lid_open_msld_closed(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, 0, 5000); + ctx->msld = 1; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 1); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 1); +} + +/* With a settle time, an open within it is held; after it, it wakes. */ +static void macsmc_input_test_lid_open_settle(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, LID_WAKE_SETTLE_MS_J716S, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + + ctx->smcin.lid_held = false; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), + LID_WAKE_SETTLE_MS_J716S + 500); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + /* Reported by .complete from MSLD, not here. */ + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* Without a settle time an open with MSLD open wakes at once. */ +static void macsmc_input_test_lid_open_wakes(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + + /* An unreadable MSLD does not hold the report back. */ + ctx->msld_ret = -ETIMEDOUT; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* The PM notifier opens the window at PM_SUSPEND_PREPARE and closes it after. */ +static void macsmc_input_test_pm_notify(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + ktime_t before = ktime_get_boottime(); + + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_SUSPEND_PREPARE, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_GE(test, ktime_to_ns(smcin->sleep_start), ktime_to_ns(before)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + smcin->dark = true; + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_POST_SUSPEND, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->dark); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + + /* Other actions change nothing. */ + macsmc_input_pm_notify(&smcin->pm_nb, PM_HIBERNATION_PREPARE, NULL); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* .prepare opens the window; a full .complete closes it and drops a held open. */ +static void macsmc_input_test_pm_prepare_complete(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + pm_suspend_global_flags &= ~PM_SUSPEND_FLAG_DARK_WAKE; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + + smcin->lid_held = true; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_FALSE(test, smcin->dark); +} + +/* + * A dark wake keeps the window and the held open, and marks the next + * .prepare to recheck the lid unless MSLD reads open. + */ +static void macsmc_input_test_pm_dark_wake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + smcin->lid_held = true; + pm_set_dark_wake(); + + ctx->msld = 1; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_TRUE(test, smcin->lid_held); + KUNIT_EXPECT_TRUE(test, smcin->dark); + + ctx->msld = 0; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->dark); + + ctx->msld_ret = -EIO; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->dark); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 3); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); +} + +static int macsmc_input_test_init(struct kunit *test) +{ + if (system_state == SYSTEM_RUNNING) + kunit_skip(test, "reports KEY_POWER/SW_LID and changes PM state: boot only"); + return 0; +} + +static struct kunit_case macsmc_input_test_cases[] = { + KUNIT_CASE(macsmc_input_test_dispatch), + KUNIT_CASE(macsmc_input_test_power_button), + KUNIT_CASE(macsmc_input_test_other_buttons), + KUNIT_CASE(macsmc_input_test_button_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_awake), + KUNIT_CASE(macsmc_input_test_lid_close_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_open_msld_closed), + KUNIT_CASE(macsmc_input_test_lid_open_settle), + KUNIT_CASE(macsmc_input_test_lid_open_wakes), + KUNIT_CASE(macsmc_input_test_pm_notify), + KUNIT_CASE(macsmc_input_test_pm_prepare_complete), + KUNIT_CASE(macsmc_input_test_pm_dark_wake), + {} +}; + +static struct kunit_suite macsmc_input_test_suite = { + .name = "macsmc-input", + .init = macsmc_input_test_init, + .test_cases = macsmc_input_test_cases, +}; + +kunit_test_suite(macsmc_input_test_suite); diff --git a/drivers/input/misc/macsmc-input.c b/drivers/input/misc/macsmc-input.c index 0971ac3085c29c..eaf7655832dbc0 100644 --- a/drivers/input/misc/macsmc-input.c +++ b/drivers/input/misc/macsmc-input.c @@ -401,3 +401,7 @@ MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC input driver"); MODULE_ALIAS("platform:macsmc-input"); + +#if IS_ENABLED(CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST) +#include "macsmc-input-test.c" +#endif diff --git a/drivers/input/misc/macsmc-input.kunitconfig b/drivers/input/misc/macsmc-input.kunitconfig new file mode 100644 index 00000000000000..7f809e65a57300 --- /dev/null +++ b/drivers/input/misc/macsmc-input.kunitconfig @@ -0,0 +1,15 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/input/misc/macsmc-input.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_INPUT=y +CONFIG_INPUT_MISC=y +CONFIG_INPUT_MACSMC_INPUT=y +CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST=y From ec4ba77ff81baa61b448a72f242a4de9e3fec5e5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:08 +1100 Subject: [PATCH 0498/1514] drm: apple: add DCP parser bounds tests parse_display_metadata(), parse_panel_product_metadata(), parse_array_count(), parse_dptx_caps(), the system log mnits parsers, the timing colour and id catalogs, parse_panel_edid_data(), dcp_mode_default_above() and the audio element parsers had no tests. Add the apple-dcp-parser-bounds suite (22 cases). Besides the decoded values, every case feeds each strict prefix of a valid blob and expects a clean error, so a parser that reads past the end of a truncated blob fails. It also covers the framing and depth limits of the skipper, and channel layouts whose counts the u32 mask has no bit for (fixed earlier in this series): 32, 33, 34, 63, 64, -1, -31 and 2^32 + 1 must neither set a bit nor alias a small count, and a layout claiming 2^32 + 8 channels must not be taken for the 8-channel one. Mutations caught: the depth limit off by one, an id list bound off by one, raw EDID bytes beyond the length kept and a one-byte over-read in parse_bytes(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/Kconfig | 3 + drivers/gpu/drm/apple/Makefile | 1 + drivers/gpu/drm/apple/parser-bounds-test.c | 1416 ++++++++++++++++++++ 3 files changed, 1420 insertions(+) create mode 100644 drivers/gpu/drm/apple/parser-bounds-test.c diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 99632ffe1535cb..6115091a8f7686 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -110,6 +110,9 @@ config DRM_APPLE_PARSER_KUNIT_TEST help Build tests for AFKv2 lengths, DMA ownership and reply correlation, legacy EPIC replies, and H17P IOMFB callback envelopes and sizes. + Also check that the DCP dictionary parsers (display metadata, + DPTX capabilities, log events, timing catalogs, EDID properties + and audio elements) reject truncated and malformed blobs. The tests use allocated buffers and fake devices and do not require an Apple display controller or any firmware. diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index a6687d7cccd657..c5674550875530 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -51,6 +51,7 @@ obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk-service-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_cec_test.o obj-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += afkv2-test.o +appledrm-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += parser-bounds-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += parser-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += hotplug-test.o diff --git a/drivers/gpu/drm/apple/parser-bounds-test.c b/drivers/gpu/drm/apple/parser-bounds-test.c new file mode 100644 index 00000000000000..2c4db5f99eaa87 --- /dev/null +++ b/drivers/gpu/drm/apple/parser-bounds-test.c @@ -0,0 +1,1416 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the DCP serialized dictionary parsers that the other parser + * suites do not call: display metadata, DPTX capabilities, system log events, + * timing catalogs, panel EDID properties and audio elements. Firmware hands + * these blobs to the driver, so beyond the accepted shapes every parser must + * fail on every truncation of a valid blob instead of reading past its end. + * + * All values are synthetic. + */ + +#include +#include +#include +#include +#include +#include + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +#include +#endif + +#include "dcp-peer-v27.h" +#include "parser.h" + +/* Tag: size in bits 0-23, type in 24-28, padding in 29-30, last in 31. */ +#define PB_DICT 1 +#define PB_ARRAY 2 +#define PB_INT64 4 +#define PB_STRING 9 +#define PB_BLOB 10 +#define PB_BOOL 11 +#define PB_CAP 8192 + +struct pb { + struct kunit *test; + u8 *data; + u32 len; +}; + +static struct pb *pb_new(struct kunit *test, bool header) +{ + struct pb *b = kunit_kzalloc(test, sizeof(*b), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, b); + b->data = kunit_kzalloc(test, PB_CAP, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, b->data); + b->test = test; + if (header) { + put_unaligned_le32(0xd3, b->data); + b->len = 4; + } + return b; +} + +static void pb_raw(struct pb *b, const void *bytes, u32 n) +{ + KUNIT_ASSERT_LE(b->test, b->len + n, PB_CAP); + memcpy(b->data + b->len, bytes, n); + b->len += n; +} + +static void pb_word(struct pb *b, u32 word) +{ + b->len = round_up(b->len, 4); + KUNIT_ASSERT_LE(b->test, b->len + 4, PB_CAP); + put_unaligned_le32(word, b->data + b->len); + b->len += 4; +} + +static void pb_tag(struct pb *b, u32 type, u32 size) +{ + pb_word(b, size | type << 24); +} + +static void pb_str(struct pb *b, const char *s) +{ + pb_tag(b, PB_STRING, strlen(s)); + pb_raw(b, s, strlen(s)); +} + +static void pb_int(struct pb *b, s64 value) +{ + u8 raw[8]; + + pb_tag(b, PB_INT64, 0); + put_unaligned_le64(value, raw); + pb_raw(b, raw, sizeof(raw)); +} + +static void pb_kint(struct pb *b, const char *key, s64 value) +{ + pb_str(b, key); + pb_int(b, value); +} + +static void pb_kbool(struct pb *b, const char *key, bool value) +{ + pb_str(b, key); + pb_tag(b, PB_BOOL, value); +} + +static void pb_kstr(struct pb *b, const char *key, const char *value) +{ + pb_str(b, key); + pb_str(b, value); +} + +typedef int (*pb_parse_fn)(const u8 *data, size_t len, void *priv); + +/* + * Every strict prefix of @b must fail. The bytes after the prefix stay in + * place and complete a valid blob, so a parser that reads past its length + * succeeds instead. Each prefix also runs from an exact-size allocation, + * which KASAN checks when enabled. + */ +static void pb_expect_prefixes_fail(struct pb *b, pb_parse_fn fn, void *priv) +{ + struct kunit *test = b->test; + u32 len; + + for (len = 0; len < b->len; len++) { + u8 *copy; + + KUNIT_EXPECT_LT_MSG(test, fn(b->data, len, priv), 0, + "prefix %u of %u", len, b->len); + if (!len) + continue; + copy = kmemdup(b->data, len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy); + KUNIT_EXPECT_LT_MSG(test, fn(copy, len, priv), 0, + "exact prefix %u of %u", len, b->len); + kfree(copy); + } +} + +/* A parser that reports an error leaves its output alone. */ +static void pb_expect_untouched(struct kunit *test, const void *out, size_t size) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(out, 0xa5, size)); +} + +/* Serialized framing */ + +static bool pb_complete(struct pb *b) +{ + return dcp_property_complete(b->data, b->len, b->len); +} + +static void parser_bounds_framing_test(struct kunit *test) +{ + struct pb *b; + + /* The last-element flag in bit 31 is accepted. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "Key"); + pb_word(b, PB_INT64 << 24 | BIT(31)); + pb_raw(b, "\0\0\0\0\0\0\0\0", 8); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + /* Padding bits 29 and 30 must be clear. */ + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(29)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(30)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* Types the serializer does not define. */ + b = pb_new(test, true); + pb_tag(b, 3, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, 0, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* An integer is eight bytes whatever its tag size says. */ + b = pb_new(test, true); + pb_tag(b, PB_INT64, 4); + pb_raw(b, "\1\0\0\0", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* A string or blob longer than the bytes left. */ + b = pb_new(test, true); + pb_tag(b, PB_STRING, 5); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 0xffffff); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* The largest dictionary count, doubled for its keys, still ends at the blob. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0xffffff); + pb_kint(b, "Key", 1); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void pb_nest(struct pb *b, unsigned int depth) +{ + unsigned int i; + + for (i = 0; i < depth; i++) + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_BOOL, 1); +} + +/* The skipper bounds its recursion at 32 levels: 31 containers fit. */ +static void parser_bounds_depth_test(struct kunit *test) +{ + struct pb *b; + + b = pb_new(test, true); + pb_nest(b, 31); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 32); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 1000); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void parser_bounds_array_count_test(struct kunit *test) +{ + struct dcp_parse_ctx ctx; + struct pb *b; + u32 count = 0xa5a5a5a5; + + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 3); + pb_int(b, 1); + pb_int(b, 2); + pb_int(b, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 3); + /* The cursor is not consumed. */ + KUNIT_EXPECT_EQ(test, ctx.pos, 4); + + /* Only the tag is read: a count beyond the blob is the caller's to bound. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0xffffff); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 0xffffff); + + count = 0xa5a5a5a5; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_ASSERT_EQ(test, parse(b->data, 6, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_EXPECT_EQ(test, count, 0xa5a5a5a5); +} + +/* DisplayAttributes */ + +static void pb_point(struct pb *b, const char *key, s64 x, s64 y, s64 gamma) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, gamma ? 3 : 2); + pb_kint(b, "X", x); + pb_kint(b, "Y", y); + if (gamma) + pb_kint(b, "Gamma", gamma); +} + +static void pb_product(struct pb *b, const char *manufacturer, s64 product, + const char *name) +{ + pb_tag(b, PB_DICT, 7); + pb_kstr(b, "ManufacturerID", manufacturer); + pb_kint(b, "ProductID", product); + pb_kstr(b, "ProductName", name); + pb_kint(b, "SerialNumber", 7); + pb_kint(b, "WeekOfManufacture", 10); + pb_kint(b, "YearOfManufacture", 2024); + pb_kstr(b, "AlphanumericSerialNumber", "SN0001"); +} + +static struct pb *pb_display_attributes(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 10); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + pb_point(b, "DefaultWhitePoint", 20500, 21500, 144179); + pb_kbool(b, "SupportsPQEOTF", true); + pb_kbool(b, "SupportsHDRStaticMetadataType1", true); + pb_kint(b, "SupportsBT2020RGB", 1); + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "Max", 600 << 16); + pb_kint(b, "MaxFrameAverage", 400 << 16); + pb_kint(b, "Min", 1 << 12); + pb_kstr(b, "Unknown", "ignored"); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 0x1234, "Synthetic"); + return b; +} + +static int pb_run_display_metadata(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_display_metadata(&ctx, priv); +} + +static void parser_bounds_metadata_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 60); + KUNIT_EXPECT_EQ(test, md.height_cm, 34); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 42000); + KUNIT_EXPECT_EQ(test, md.chromaticity[1][1], 45000); + KUNIT_EXPECT_EQ(test, md.chromaticity[2][1], 4000); + KUNIT_EXPECT_EQ(test, md.white[0], 20500); + KUNIT_EXPECT_EQ(test, md.white[1], 21500); + KUNIT_EXPECT_EQ(test, md.gamma, 144179); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0x1234); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic"); + KUNIT_EXPECT_STREQ(test, md.serial_text, "SN0001"); + KUNIT_EXPECT_EQ(test, md.serial, 7); + KUNIT_EXPECT_EQ(test, md.week, 10); + KUNIT_EXPECT_EQ(test, md.year, 2024); + KUNIT_EXPECT_TRUE(test, md.pq); + KUNIT_EXPECT_TRUE(test, md.static_metadata_type1); + KUNIT_EXPECT_TRUE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.max_luminance, 600 << 16); + KUNIT_EXPECT_EQ(test, md.max_fall, 400 << 16); + KUNIT_EXPECT_EQ(test, md.min_luminance, 1 << 12); + KUNIT_EXPECT_EQ(test, md.defaults, 0); +} + +static void parser_bounds_metadata_truncated_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + pb_expect_prefixes_fail(b, pb_run_display_metadata, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* Optional values out of range fall back to EDID defaults; identity is required. */ +static void parser_bounds_metadata_defaults_test(struct kunit *test) +{ + struct dcp_display_metadata md; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 6); + pb_kint(b, "MaxHorizontalImageSize", 256); + pb_kint(b, "MaxVerticalImageSize", 34); + /* Primaries without a white point are no colour description. */ + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + /* A minimum at the maximum is no luminance range. */ + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Max", 100); + pb_kint(b, "Min", 100); + pb_kstr(b, "SupportsBT2020RGB", "yes"); + pb_str(b, "ProductAttributes"); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 0); + KUNIT_EXPECT_EQ(test, md.height_cm, 0); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 0); + KUNIT_EXPECT_EQ(test, md.max_luminance, 0); + KUNIT_EXPECT_FALSE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.defaults, + DCP_METADATA_DEFAULT_SIZE | DCP_METADATA_DEFAULT_COLOR | + DCP_METADATA_DEFAULT_NAME | DCP_METADATA_DEFAULT_DATE); + + /* No ProductAttributes at all. */ + memset(&md, 0xa5, sizeof(md)); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + pb_expect_untouched(test, &md, sizeof(md)); +} + +static void parser_bounds_metadata_keys_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char key[80]; + struct pb *b; + + memset(&md, 0xa5, sizeof(md)); + + /* A repeated key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxHorizontalImageSize", 61); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key with a control character. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Odd\nKey", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An empty key and one longer than the key buffer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + memset(key, 'K', sizeof(key)); + key[64] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, key, 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key of the wrong type. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_int(b, 1); + pb_int(b, 1); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An array where the dictionary goes. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); +} + +static int pb_run_panel_product(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_panel_product_metadata(&ctx, priv); +} + +static void parser_bounds_product_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char label[257]; + struct pb *b; + + /* A panel label is cut to a descriptor; its date is not read. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0xffff); + pb_kstr(b, "ProductName", "Synthetic Panel Label"); + pb_kstr(b, "WeekOfManufacture", "not a number"); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0xffff); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic Pan"); + KUNIT_EXPECT_EQ(test, md.week, 0); + + /* A blank label reads as absent. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", " "); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.name[0], 0); + + /* The legacy ID alone gives the manufacturer: TST = 20 << 10 | 19 << 5 | 20. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "LegacyManufacturerID", 20 << 10 | 19 << 5 | 20); + pb_kint(b, "ProductID", 1); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + + memset(&md, 0xa5, sizeof(md)); + + /* A legacy ID that disagrees with the manufacturer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "LegacyManufacturerID", 1 << 10 | 1 << 5 | 1); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* Not three capitals; a product beyond 16 bits; no product. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "tst"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TSTX"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0x10000); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ManufacturerID", "TST"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* A label longer than 255 bytes or with a control character. */ + memset(label, 'L', sizeof(label)); + label[256] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", label); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", "Tab\there"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); + + b = pb_new(test, true); + pb_product(b, "TST", 1, "Synthetic"); + pb_expect_prefixes_fail(b, pb_run_panel_product, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* DPTX port capabilities */ + +static int pb_run_dptx_caps(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_dptx_caps(&ctx, priv); +} + +static void parser_bounds_dptx_caps_test(struct kunit *test) +{ + struct dcp_dptx_caps caps; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_str(b, "Nested"); + pb_tag(b, PB_ARRAY, 2); + pb_tag(b, PB_DICT, 0); + pb_int(b, 3); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", U32_MAX); + KUNIT_ASSERT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), 0); + KUNIT_EXPECT_EQ(test, caps.width, 5120); + KUNIT_EXPECT_EQ(test, caps.total_rate, 1000000); + KUNIT_EXPECT_EQ(test, caps.active_rate, U32_MAX); + + memset(&caps, 0xa5, sizeof(caps)); + pb_expect_prefixes_fail(b, pb_run_dptx_caps, &caps); + + /* A missing limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxTotalPixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -ENOENT); + + /* A repeated limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxPixelWidth", 4096); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + /* Zero, beyond 32 bits, negative, or not an integer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxPixelWidth", 0); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxTotalPixelRate", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxActivePixelRate", -1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "MaxPixelWidth", "5120"); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + pb_expect_untouched(test, &caps, sizeof(caps)); +} + +/* System log brightness events */ + +static struct pb *pb_mnits_event(struct kunit *test, const char *event, s64 mnits) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 5); + pb_kstr(b, "logEvent", event); + pb_kint(b, "timestamp", 1234); + pb_kint(b, "iDAC", 56); + pb_str(b, "extra"); + pb_tag(b, PB_DICT, 1); + pb_kbool(b, "x", false); + pb_kint(b, "mNits", mnits); + return b; +} + +static int pb_run_mnits(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_system_log_mnits(&ctx, priv); +} + +static void parser_bounds_mnits_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_mnits_event(test, "Display (Event Forward)", 500000); + KUNIT_ASSERT_EQ(test, pb_run_mnits(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 500000); + KUNIT_EXPECT_EQ(test, entry.idac, 56); + KUNIT_EXPECT_EQ(test, entry.timestamp, 1234); + + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits, &entry); + + b = pb_mnits_event(test, "Display (Event Forward) ", 500000); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", -1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -ERANGE); + + /* No timestamp. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "logEvent", "Display (Event Forward)"); + pb_kint(b, "iDAC", 56); + pb_kint(b, "mNits", 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +static int pb_run_mnits_pairs(const u8 *data, size_t len, void *priv) +{ + return parse_system_log_mnits_pairs(data, len, priv); +} + +/* Header-less key/value pairs, read up to the first one that does not parse. */ +static void parser_bounds_mnits_pairs_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_new(test, false); + pb_kint(b, "timestamp", 99); + pb_kint(b, "iDAC", -5); + pb_kstr(b, "other", "value"); + pb_kint(b, "mNits", 250); + KUNIT_ASSERT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 250); + KUNIT_EXPECT_EQ(test, entry.idac, 0); + KUNIT_EXPECT_EQ(test, entry.timestamp, 99); + + /* mNits comes last, so no prefix holds all of it. */ + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits_pairs, &entry); + pb_expect_untouched(test, &entry, sizeof(entry)); + + /* A key whose length runs past the end stops the walk before mNits. */ + b = pb_new(test, false); + pb_tag(b, PB_STRING, 0x1000); + pb_raw(b, "mNits", 5); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + /* A value of the wrong type stops it too. */ + b = pb_new(test, false); + pb_kstr(b, "iDAC", "56"); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + b = pb_new(test, false); + pb_kint(b, "mNits", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +/* TimingElements catalogs */ + +static void pb_dimension(struct pb *b, const char *key, s64 active, s64 total) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "Active", active); + pb_kint(b, "Total", total); + pb_kint(b, "FrontPorch", 8); + pb_kint(b, "SyncWidth", 4); +} + +static struct pb *pb_timing_ids(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 4); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "ID", 3); + pb_dimension(b, "HorizontalAttributes", 1920, 2200); + pb_dimension(b, "VerticalAttributes", 1080, 1125); + /* Malformed entries are skipped: an ID of the wrong type, one beyond 32 bits. */ + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ID", "4"); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ID", (s64)U32_MAX + 5); + /* No size: zero. */ + pb_tag(b, PB_DICT, 2); + pb_kbool(b, "IsPreferred", true); + pb_kint(b, "ID", 9); + return b; +} + +static int pb_run_timing_ids(const u8 *data, size_t len, void *priv) +{ + return dcp_parse_timing_ids(data, len, priv, 4); +} + +static void parser_bounds_timing_ids_test(struct kunit *test) +{ + struct dcp_timing_id ids[4]; + struct pb *b = pb_timing_ids(test); + + memset(ids, 0xa5, sizeof(ids)); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), 2); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + KUNIT_EXPECT_EQ(test, ids[0].width, 1920); + KUNIT_EXPECT_EQ(test, ids[0].height, 1080); + KUNIT_EXPECT_EQ(test, ids[1].id, 9); + KUNIT_EXPECT_EQ(test, ids[1].width, 0); + KUNIT_EXPECT_EQ(test, ids[1].height, 0); + pb_expect_untouched(test, &ids[2], 2 * sizeof(ids[0])); + + /* At most @max are written. */ + memset(ids, 0xa5, sizeof(ids)); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 1), 1); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + pb_expect_untouched(test, &ids[1], 3 * sizeof(ids[0])); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 0), 0); + + /* Every truncation ends in a skip that cannot finish. */ + pb_expect_prefixes_fail(b, pb_run_timing_ids, ids); + + /* A dictionary is no catalog. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), -EINVAL); +} + +#define PB_MAX_COLORS 8 + +struct pb_colors { + unsigned int count; + struct dcp_color_element e[PB_MAX_COLORS]; +}; + +static void pb_collect_color(void *data, const struct dcp_color_element *e) +{ + struct pb_colors *c = data; + + if (c->count < PB_MAX_COLORS) + c->e[c->count] = *e; + c->count++; +} + +static void pb_color(struct pb *b, s64 id, s64 eotf) +{ + pb_tag(b, PB_DICT, 5); + pb_kint(b, "ID", id); + pb_kint(b, "Depth", 10); + pb_kint(b, "EOTF", eotf); + pb_kbool(b, "IsVirtual", false); + pb_kint(b, "Score", 100 + id); +} + +static struct pb *pb_timing_colors(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 3); + /* A malformed entry that would match. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 5); + pb_kstr(b, "IsInterlaced", "no"); + /* Another timing. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 4); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 1); + pb_color(b, 99, 0); + /* The timing, its colours before its ID. */ + pb_tag(b, PB_DICT, 5); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 2); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 11); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_kbool(b, "IsInterlaced", true); + pb_kint(b, "ID", 5); + return b; +} + +static int pb_run_timing_colors(const u8 *data, size_t len, void *priv) +{ + struct pb_colors *c = priv; + + c->count = 0; + return dcp_parse_timing_colors(data, len, 5, pb_collect_color, c, NULL); +} + +static void parser_bounds_timing_colors_test(struct kunit *test) +{ + struct pb *b = pb_timing_colors(test); + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + bool interlaced = false; + + KUNIT_ASSERT_NOT_NULL(test, c); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 5, pb_collect_color, + c, &interlaced), 0); + KUNIT_EXPECT_TRUE(test, interlaced); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_EQ(test, c->e[0].id, 10); + KUNIT_EXPECT_EQ(test, c->e[0].depth, 10); + KUNIT_EXPECT_EQ(test, c->e[0].score, 110); + KUNIT_EXPECT_EQ(test, c->e[0].range, -1); + KUNIT_EXPECT_FALSE(test, c->e[0].is_virtual); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_EQ(test, c->e[1].id, 11); + KUNIT_EXPECT_EQ(test, c->e[1].eotf, 2); + KUNIT_EXPECT_TRUE(test, c->e[1].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 6, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); + + pb_expect_prefixes_fail(b, pb_run_timing_colors, c); +} + +/* + * The restricted ID lists hold 64 entries each: further IDs are dropped, not + * written over the neighbouring list. + */ +static void parser_bounds_timing_colors_lists_test(struct kunit *test) +{ + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + struct pb *b = pb_new(test, true); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, c); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "ID", 1); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 65); + for (i = 0; i < 64; i++) + pb_int(b, 1000 + i); + pb_int(b, 11); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 0); + + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), 0); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[1].unsafe); + + /* A list entry of the wrong type makes the entry malformed. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 1); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_str(b, "11"); + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); +} + +/* Panel EDID properties */ + +static void pb_edid(u8 *edid, unsigned int blocks) +{ + memset(edid, 0, blocks * 128); + memcpy(edid, "\x00\xff\xff\xff\xff\xff\xff\x00", 8); + edid[126] = blocks - 1; +} + +static void pb_kedid(struct pb *b, const char *key, const u8 *edid, u32 size) +{ + pb_str(b, key); + pb_tag(b, PB_BLOB, size); + pb_raw(b, edid, size); +} + +static void parser_bounds_edid_raw_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 4224, GFP_KERNEL); + const u8 *found = NULL; + size_t size = 0; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 256, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)edid); + KUNIT_EXPECT_EQ(test, size, 256); + /* Trailing bytes after the extensions are not EDID. */ + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 300, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + + /* Extension blocks the buffer does not hold. */ + found = NULL; + size = 0; + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 255, &found, &size), -EINVAL); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 128, &found, &size), -EINVAL); + /* 33 blocks exceed the 4 KiB bound even when present. */ + pb_edid(edid, 33); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4224, &found, &size), -EINVAL); + pb_edid(edid, 32); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4096, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 4096); + + /* Fewer than 128 bytes is no raw EDID, and no serialized blob either. */ + found = NULL; + size = 0; + pb_edid(edid, 1); + KUNIT_EXPECT_LT(test, parse_panel_edid_data(edid, 127, &found, &size), 0); + KUNIT_EXPECT_NULL(test, found); + KUNIT_EXPECT_EQ(test, size, 0); +} + +static int pb_run_edid(const u8 *data, size_t len, void *priv) +{ + const u8 *edid; + size_t size; + + return parse_panel_edid_data(data, len, &edid, &size); +} + +static void parser_bounds_edid_serialized_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 384, GFP_KERNEL); + const u8 *found; + unsigned int i; + size_t size; + struct pb *b; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + + /* A blob at the root. */ + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)b->data + 8); + KUNIT_EXPECT_EQ(test, size, 256); + + /* A named blob in a nested dictionary, after other values. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Other", 1); + pb_str(b, "Properties"); + pb_tag(b, PB_DICT, 2); + pb_kedid(b, "NotEDID", edid, 128); + pb_kedid(b, "IODisplayEDID", edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + KUNIT_EXPECT_EQ(test, memcmp(found, edid, 256), 0); + pb_expect_prefixes_fail(b, pb_run_edid, NULL); + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "edid", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + + /* No EDID key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDIDs", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -ENOENT); + + /* Sizes that are no whole EDID, or disagree with its extension count. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 130); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 384); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid + 1, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* A blob size beyond the bytes present. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "EDID"); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* Deeper than four dictionaries. */ + b = pb_new(test, true); + for (i = 0; i < 5; i++) { + pb_tag(b, PB_DICT, 1); + pb_str(b, "Nested"); + } + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); + + /* More entries than the walk budget. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 64); + for (i = 0; i < 64; i++) + pb_kint(b, "N", i); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); +} + +/* Mode ranking */ + +static void pb_mode(struct dcp_display_mode *m, int clock, u16 htotal, u16 vtotal, + bool preferred) +{ + memset(m, 0, sizeof(*m)); + m->mode.clock = clock; + m->mode.htotal = htotal; + m->mode.vtotal = vtotal; + m->firmware_preferred = preferred; +} + +static void parser_bounds_default_above_test(struct kunit *test) +{ + struct dcp_display_mode a, b; + + /* The higher refresh rate first, whatever the preference or score. */ + pb_mode(&a, 297000, 2200, 1125, false); + pb_mode(&b, 148500, 2200, 1125, true); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 100)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 100, &a, 0)); + + /* Same rate from different totals: IsPreferred, then the score. */ + pb_mode(&a, 297000, 4400, 1125, false); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 100, &b, 0)); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&b, 0, &a, 100)); + a.firmware_preferred = true; + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 1, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 0, &b, 0)); + + /* The cross products do not wrap at the largest timings. */ + pb_mode(&a, INT_MAX, U16_MAX, U16_MAX, false); + pb_mode(&b, INT_MAX - 1, U16_MAX, U16_MAX, false); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 0, &a, 0)); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +/* Audio elements */ + +static void pb_layout(struct pb *b, s64 nchans, const char * const *labels, + unsigned int nlabels) +{ + unsigned int i; + + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", nchans); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, nlabels); + for (i = 0; i < nlabels; i++) + pb_str(b, labels[i]); +} + +static const char * const pb_stereo[] = { "Front Left", "Front Right" }; +static const char * const pb_surround[] = { + "Front Left", "Front Right", "Front Center", "Low Frequency Effects", + "Rear Left", "Rear Right", "Side Left", "Rear Center", +}; + +static void pb_avep(struct pb *b, s64 rate, s64 sample_size, const char *cookie_key, + u32 cookie_size) +{ + u8 cookie[DCP_SOUND_COOKIE_MAX + 4]; + unsigned int i; + + for (i = 0; i < sizeof(cookie); i++) + cookie[i] = i + 1; + pb_tag(b, PB_DICT, 5); + pb_kint(b, "StreamSampleRate", rate); + pb_kint(b, "SampleSize", sample_size); + pb_kstr(b, "Other", "skipped"); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 2, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_str(b, cookie_key); + pb_tag(b, PB_BLOB, cookie_size); + pb_raw(b, cookie, cookie_size); +} + +static struct pb *pb_audio(struct kunit *test, u32 cookie_size, bool unmatched) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, unmatched ? 3 : 2); + pb_avep(b, 44100, 16, "ElementData", cookie_size); + pb_avep(b, 48000, 24, "ElementData", cookie_size); + /* A rate ALSA has no bit for and a sample size it has no format for. */ + if (unmatched) + pb_avep(b, 12345, 18, "ElementData", cookie_size); + return b; +} + +static const struct dcp_sound_format_mask pb_any = { + .formats = ~0ULL, .rates = ~0U, .nchans = ~0U, +}; + +/* + * Channel counts the firmware reports but the u32 channel mask has no bit + * for (32 and up, negative, wider than 32 bits) match nothing; they must not + * wrap onto the bit of a small count (1 << 33 is 1 << 1 on arm64). + */ +static void parser_bounds_sound_wide_layouts_test(struct kunit *test) +{ + static const s64 counts[] = { 2, 31, 32, 33, 34, 63, 64, -1, -31, 0x100000001LL }; + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(counts)); + for (i = 0; i < ARRAY_SIZE(counts); i++) { + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ActiveChannelCount", counts[i]); + } + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(31)); + + /* No layout has 0 or 1 channels: a sieve for those matches no element */ + sieve.nchans = BIT(0) | BIT(1); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, 0U); + KUNIT_EXPECT_EQ(test, hits.rates, 0U); +} + +/* + * A count wider than 32 bits is not the low 32 bits of itself: a layout + * claiming 0x100000008 channels must not be taken for the 8-channel one + * and replace its channel map. + */ +static void parser_bounds_sound_wide_layout_map_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S16, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + u8 data[DCP_SOUND_COOKIE_SIZE] = { 1 }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_layout(b, 0x100000008LL, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, sizeof(data)); + pb_raw(b, data, sizeof(data)); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); +} + +static void parser_bounds_sound_constraints_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S16 | SNDRV_PCM_FMTBIT_S24); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(8)); + + sieve.rates = SNDRV_PCM_RATE_48000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S24); + + /* The parser reports a truncation instead of the elements it did read. */ + sieve = pb_any; + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_constraints(&ctx, &sieve, &hits), 0, + "prefix %u of %u", len, b->len); + } +} + +static void parser_bounds_sound_mode_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S24, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_ASSERT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[0], SNDRV_CHMAP_FL); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); + /* A label the table does not name. */ + KUNIT_EXPECT_EQ(test, chmap.map[6], SNDRV_CHMAP_UNKNOWN); + KUNIT_EXPECT_EQ(test, chmap.map[7], SNDRV_CHMAP_RC); + KUNIT_EXPECT_EQ(test, cookie.data[0], 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE - 1], DCP_SOUND_COOKIE_SIZE); + + /* No element matches. */ + sieve.rates = SNDRV_PCM_RATE_96000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0); + sieve.rates = SNDRV_PCM_RATE_48000; + + /* Link data shorter than the service takes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE - 1, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role takes 32 bytes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE_V14_7, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE_V14_7 - 1], + DCP_SOUND_COOKIE_SIZE_V14_7); +#endif + + /* The matching element is the last: no prefix holds all of it. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, false); + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0, + "prefix %u of %u", len, b->len); + } +} + +/* A layout with more labels than a channel map holds is cut at the map. */ +static void parser_bounds_sound_chmap_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + sieve.nchans = BIT(2); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 24); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", 2); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(chmap.map) + 5); + for (i = 0; i < ARRAY_SIZE(chmap.map) + 5; i++) + pb_str(b, i & 1 ? "Front Right" : "Front Left"); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, DCP_SOUND_COOKIE_MAX); + pb_raw(b, "abcdefghijklmnopqrstuvwxyz0123456789", DCP_SOUND_COOKIE_MAX); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, NULL), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, ARRAY_SIZE(chmap.map)); + KUNIT_EXPECT_EQ(test, chmap.map[ARRAY_SIZE(chmap.map) - 1], SNDRV_CHMAP_FL); +} +#endif + +static struct kunit_case parser_bounds_cases[] = { + KUNIT_CASE(parser_bounds_framing_test), + KUNIT_CASE(parser_bounds_depth_test), + KUNIT_CASE(parser_bounds_array_count_test), + KUNIT_CASE(parser_bounds_metadata_test), + KUNIT_CASE(parser_bounds_metadata_truncated_test), + KUNIT_CASE(parser_bounds_metadata_defaults_test), + KUNIT_CASE(parser_bounds_metadata_keys_test), + KUNIT_CASE(parser_bounds_product_test), + KUNIT_CASE(parser_bounds_dptx_caps_test), + KUNIT_CASE(parser_bounds_mnits_test), + KUNIT_CASE(parser_bounds_mnits_pairs_test), + KUNIT_CASE(parser_bounds_timing_ids_test), + KUNIT_CASE(parser_bounds_timing_colors_test), + KUNIT_CASE(parser_bounds_timing_colors_lists_test), + KUNIT_CASE(parser_bounds_edid_raw_test), + KUNIT_CASE(parser_bounds_edid_serialized_test), + KUNIT_CASE(parser_bounds_default_above_test), +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) + KUNIT_CASE(parser_bounds_sound_constraints_test), + KUNIT_CASE(parser_bounds_sound_wide_layouts_test), + KUNIT_CASE(parser_bounds_sound_wide_layout_map_test), + KUNIT_CASE(parser_bounds_sound_mode_test), + KUNIT_CASE(parser_bounds_sound_chmap_test), +#endif + {} +}; + +static struct kunit_suite parser_bounds_suite = { + .name = "apple-dcp-parser-bounds", + .test_cases = parser_bounds_cases, +}; + +kunit_test_suite(parser_bounds_suite); From 92f0abe9dce376a4f41e0ea5654d9824da7141d0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:09 +1100 Subject: [PATCH 0499/1514] media: apple: ave: add IPC and writer KUnit tests Add two suites for the input the AVE driver takes from the firmware and from user space: apple-ave-ipc (20 cases), included from ave-ipc.c: hello words, channel tables with overlapping or out-of-range rings, ring index wrap, full and empty rings, command acks and messages outside the shared window, log lines and shared-memory requests, including the near-4 GiB requests fixed earlier in this series. apple-ave-writer (8 cases): the 6070 Start and Process builders refuse out-of-range session counts, unaligned buffers and short codec state before they write anything. The shared window and the mailbox are kernel memory; no firmware or encoder hardware is needed. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/Kconfig | 14 + drivers/media/platform/apple/ave/Makefile | 1 + .../media/platform/apple/ave/ave-ipc-test.c | 1129 +++++++++++++++++ drivers/media/platform/apple/ave/ave-ipc.c | 4 + .../platform/apple/ave/ave-writer-test.c | 438 +++++++ 5 files changed, 1586 insertions(+) create mode 100644 drivers/media/platform/apple/ave/ave-ipc-test.c create mode 100644 drivers/media/platform/apple/ave/ave-writer-test.c diff --git a/drivers/media/platform/apple/ave/Kconfig b/drivers/media/platform/apple/ave/Kconfig index 0924ce46210276..c4c4c5038d66a5 100644 --- a/drivers/media/platform/apple/ave/Kconfig +++ b/drivers/media/platform/apple/ave/Kconfig @@ -44,3 +44,17 @@ config VIDEO_APPLE_AVE_CMD_KUNIT_TEST entropy interleave, alignment refusal, seven-channel discovery and encoding refusal. These tests run without firmware or encoder hardware. + +config VIDEO_APPLE_AVE_IPC_KUNIT_TEST + bool "KUnit tests for Apple AVE firmware and userspace input checks" if !KUNIT_ALL_TESTS + depends on KUNIT=y && VIDEO_APPLE_AVE=y + default KUNIT_ALL_TESTS + help + Feed malformed firmware input to the AVE IPC layer: hello words, + channel tables with overlapping or out-of-range rings, ring index + wrap, full and empty rings, command acks and messages outside the + shared window, log lines and shared-memory requests. Also test that + the 6070 Start and Process builders refuse out-of-range session + counts, unaligned buffers and short codec state before writing. + The tests use kernel memory for the shared window and the mailbox + and run without firmware or encoder hardware. diff --git a/drivers/media/platform/apple/ave/Makefile b/drivers/media/platform/apple/ave/Makefile index 03d3b1bba4978b..237f51e0e0f300 100644 --- a/drivers/media/platform/apple/ave/Makefile +++ b/drivers/media/platform/apple/ave/Makefile @@ -5,3 +5,4 @@ obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave-dma.o apple-ave-y := ave-drv.o ave-fw.o ave-ipc.o ave-cmd.o ave-writer.o ave-abi.o ave-layout.o ave-image.o ave-sess.o ave-v4l2.o ave-vb2.o ave-mctf.o ave-mctf-v4l2.o ave-cmp420.o obj-$(CONFIG_VIDEO_APPLE_AVE_KUNIT_TEST) += ave-sizes-test.o ave-recovery-test.o obj-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o +obj-$(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) += ave-writer-test.o diff --git a/drivers/media/platform/apple/ave/ave-ipc-test.c b/drivers/media/platform/apple/ave/ave-ipc-test.c new file mode 100644 index 00000000000000..40f32562ff3b94 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-ipc-test.c @@ -0,0 +1,1129 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the AVE IPC parsers and bounds checks: everything the + * firmware writes into the shared window (hello words, channel tables, ring + * slots, acks, messages, shared-memory requests) must stay inside it. + * + * Included at the end of ave-ipc.c to reach its static helpers. The shared + * window and the mailbox are plain kernel memory; no hardware is touched. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include + +#define T_FW_BASE 0x100000000ULL +/* Large enough to hold the whole 6070 command area. */ +#define T_IPC_BYTES 0x160000 +/* Bytes past ipc.size kept as a canary: nothing may write there. */ +#define T_CANARY_BYTES SZ_16K +#define T_CANARY 0xa5 + +struct t_ipc { + struct ave_dev *ave; + struct ave_fw_transport *t; + struct ave_fw_abi *abi; + struct ave_fw_layout *layout; +}; + +/* A device with a private copy of @base's layout, ABI and transport. */ +static void t_ipc_init(struct kunit *test, struct t_ipc *ti, + const struct ave_fw_layout *base, size_t ipc_bytes) +{ + struct ave_dev *ave = kunit_kzalloc(test, sizeof(*ave), GFP_KERNEL); + static atomic_t seq = ATOMIC_INIT(0); + char name[32]; + + KUNIT_ASSERT_NOT_NULL(test, ave); + ti->ave = ave; + ti->t = kunit_kmalloc(test, sizeof(*ti->t), GFP_KERNEL); + ti->abi = kunit_kmalloc(test, sizeof(*ti->abi), GFP_KERNEL); + ti->layout = kunit_kmalloc(test, sizeof(*ti->layout), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, ti->t && ti->abi && ti->layout); + *ti->layout = *base; + *ti->abi = *base->abi; + *ti->t = *base->abi->transport; + ti->abi->transport = ti->t; + ti->layout->abi = ti->abi; + ave->layout = ti->layout; + ave->variant = &ave_t6000; + + /* Several devices per case; names must be unique. */ + snprintf(name, sizeof(name), "apple-ave-ipc-%d", atomic_inc_return(&seq)); + ave->dev = kunit_device_register(test, name); + KUNIT_ASSERT_FALSE(test, IS_ERR(ave->dev)); + ave->ipc.cpu = kunit_kzalloc(test, ipc_bytes + T_CANARY_BYTES, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ave->ipc.cpu); + memset(ave->ipc.cpu + ipc_bytes, T_CANARY, T_CANARY_BYTES); + ave->ipc.size = ipc_bytes; + ave->ipc_fw_base = T_FW_BASE; + ave->mbox = (void __iomem __force *)kunit_kzalloc(test, SZ_4K, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, (void __force *)ave->mbox); + spin_lock_init(&ave->irq_lock); + init_waitqueue_head(&ave->irq_wait); + ave->fw_state = AVE_FW_RUNNING; +} + +static void t_canary_intact(struct kunit *test, struct ave_dev *ave) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + ave->ipc.size, + T_CANARY, T_CANARY_BYTES)); +} + +static __le64 *t_slot(struct ave_dev *ave, const struct ave_ring *r, + unsigned int n) +{ + return ave->ipc.cpu + r->offset + n * AVE_RING_SLOT_BYTES; +} + +/* Lay out one ring as ave_ipc_parse_channels() leaves it. */ +static void t_ring(struct ave_dev *ave, unsigned int id, u32 offset, + u32 slots, u32 doorbell, bool to_host) +{ + struct ave_ring *r = &ave->ring[id]; + + *r = (struct ave_ring){ + .mode = to_host ? 0 : 1, + .doorbell = doorbell, + .slots = slots, + .offset = AVE_IPC_CHANNEL_OFF + offset, + .consumer = to_host ? 0 : -1, + .producer = to_host ? -1 : 0, + }; + /* + * Bit 0 set: a host-to-firmware slot is free for the host, a + * firmware-to-host slot still belongs to the firmware. + */ + for (unsigned int n = 0; n < slots; n++) + *t_slot(ave, r, n) = cpu_to_le64(1); +} + +/* IO and IO_T2H with four slots each, as on 6070. */ +static void t_rings(struct ave_dev *ave) +{ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_IO, 0x800, 4, 1, false); + t_ring(ave, AVE_RING_T2H, 0xa00, 4, 3, true); +} + +/* Play the firmware: post @addr/@len to the host in ring slot @n. */ +static void t_fw_post(struct ave_dev *ave, unsigned int id, unsigned int n, + u64 addr, u64 len) +{ + __le64 *slot = t_slot(ave, &ave->ring[id], n); + + slot[1] = cpu_to_le64(len); + slot[2] = 0; + /* Host-to-firmware slots are acked by setting bit 0, others by clearing it. */ + slot[0] = cpu_to_le64(addr | ave->ring[id].mode); +} + +static void t_ring_indices_valid(struct kunit *test, const struct ave_ring *r) +{ + KUNIT_EXPECT_GE(test, r->consumer, -1); + KUNIT_EXPECT_LT(test, r->consumer, (int)r->slots); + KUNIT_EXPECT_GE(test, r->producer, -1); + KUNIT_EXPECT_LT(test, r->producer, (int)r->slots); +} + +/* 9003 hello: the descriptor area and the heap are both bounded. */ +static void ave_ipc_test_hello_9003(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_abi_9003.transport; + u32 min = t->descriptors * AVE_CHAN_DESC_STRIDE; + u32 max = AVE_IPC_HANDSHAKE_OFF - AVE_IPC_CHANNEL_OFF; + u32 hello[4] = { t->hello[0], min, t->hello[2], SZ_1M }; + + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[1] = min - 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = max; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + /* A channel area running into the handshake block. */ + hello[1] = max + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = min; + /* 9003 always asks for a heap, never more than 4 MiB. */ + hello[3] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = 4 * SZ_1M; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = SZ_1M; + hello[0] = t->hello[0] + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[0] = t->hello[0]; + hello[2] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); +} + +/* A bad hello is refused before the mailbox or the window are touched. */ +static void ave_ipc_test_negotiate_bad_hello(struct kunit *test) +{ + struct t_ipc ti; + u32 hello[4]; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[1]++; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_EQ(test, readl(ti.ave->mbox + AVE_MBOX_DOORBELL), 0U); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, 0U); + /* A heap larger than 4 MiB is not allocated either. */ + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_NULL(test, ti.ave->heap.cpu); +} + +/* + * The fake mailbox answers with the words the host wrote, so the IPC window + * address the "firmware" reports is ipc.dma. It must be 16 KiB aligned and + * the whole window must fit below 2^64. + */ +static void ave_ipc_test_negotiate_window(struct kunit *test) +{ + static const u64 bad[] = { + 0, T_FW_BASE + SZ_4K, 0xffffffffffffc000ULL, + }; + struct t_ipc ti; + u8 *hs; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + hs = ti.ave->ipc.cpu + AVE_IPC_HANDSHAKE_OFF; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + ti.ave->ipc.dma = bad[i]; + memset(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF, T_CANARY, 0x100); + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), + -EPROTO); + /* Nothing was cleared or handed to the firmware. */ + KUNIT_EXPECT_EQ(test, + *(u8 *)(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF), + T_CANARY); + } + + /* + * A good window gets the handshake block, but the echoed handshake + * address is not the channel area: refused before any channel is parsed. + */ + ti.ave->ipc.dma = T_FW_BASE; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), -EPROTO); + KUNIT_EXPECT_EQ(test, ti.ave->ipc_fw_base, T_FW_BASE); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, ti.t->hello[1]); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(hs + AVE_HS_CHANNELS), + T_FW_BASE + AVE_IPC_CHANNEL_OFF); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(hs + AVE_HS_DEVICE_TYPE), + ave_t6000.device_type); + KUNIT_EXPECT_EQ(test, ti.ave->ring[AVE_RING_IO].slots, 0U); + t_canary_intact(test, ti.ave); +} + +/* A two-descriptor (9003-style) table: IO then IO_T2H. */ +#define T_CHAN_BYTES 0x1000 + +static u8 *t_desc(struct ave_dev *ave, unsigned int i) +{ + return ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + i * AVE_CHAN_DESC_STRIDE; +} + +static void t_write_desc(struct ave_dev *ave, unsigned int i, const char *name, + u32 dir, u32 doorbell, u32 slots, u64 addr) +{ + u8 *desc = t_desc(ave, i); + + memset(desc, 0, AVE_CHAN_DESC_STRIDE); + strscpy(desc, name, AVE_CHAN_DESC_NAME_LEN); + put_unaligned_le32(dir, desc + AVE_CHAN_DESC_DIR); + put_unaligned_le32(doorbell, desc + AVE_CHAN_DESC_IRQ); + put_unaligned_le32(slots, desc + AVE_CHAN_DESC_SLOTS); + put_unaligned_le64(addr, desc + AVE_CHAN_DESC_ADDR); +} + +static u64 t_chan_addr(u32 off) +{ + return T_FW_BASE + AVE_IPC_CHANNEL_OFF + off; +} + +static void t_table_9003(struct ave_dev *ave) +{ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); +} + +static void t_channels_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_9003_78_0, T_IPC_BYTES); + ti->ave->channel_bytes = T_CHAN_BYTES; + t_table_9003(ti->ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ti->ave), 0); +} + +static void ave_ipc_test_channels_9003(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + KUNIT_EXPECT_STREQ(test, ave->ring[AVE_RING_IO].name, "IO"); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].mode, 1U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].producer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].consumer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].mode, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].producer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].consumer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 0U); + for (unsigned int n = 0; n < 8; n++) + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], n)), + 1ULL); + /* The slot after the ring is not handed over. */ + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], 8)), + 0ULL); + + /* The last ring may end exactly at the end of the channel area. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(T_CHAN_BYTES - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* Doorbell 31 is the last mailbox bit. */ + t_write_desc(ave, 1, "IO_T2H", 1, 31, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].doorbell, 31U); + /* Order does not matter on a table with no fixed indices. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); +} + +/* Every malformed descriptor the firmware could write is refused. */ +static void ave_ipc_test_channels_malformed(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *desc; + + t_channels_init(test, &ti); + ave = ti.ave; + desc = t_desc(ave, 0); + + /* A name with no terminating NUL in its 64 bytes. */ + memset(desc, 'A', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* A two-channel table has no room for unknown channels. */ + t_write_desc(ave, 0, "DEBUG", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Wrong direction. */ + put_unaligned_le32(1, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(2, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Doorbells outside the 32-bit doorbell register, or none for IO. */ + put_unaligned_le32(32, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* No slots. */ + put_unaligned_le32(0, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* More slots than the channel area holds (slots * 64 wraps in u32). */ + put_unaligned_le32(T_CHAN_BYTES / AVE_RING_SLOT_BYTES + 1, + desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0x04000000, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Two IO channels and no IO_T2H. */ + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Two IO_T2H channels and no IO. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); +} + +/* Ring addresses must land inside the channel area, past the descriptors. */ +static void ave_ipc_test_channels_out_of_range(struct kunit *test) +{ + static const u64 bad[] = { + /* Below the window, and far below it (u64 wrap). */ + T_FW_BASE - AVE_RING_SLOT_BYTES, + 0, + /* Not slot aligned. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 0x208, + /* On top of the descriptor table. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF, + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 2 * AVE_CHAN_DESC_STRIDE - + AVE_RING_SLOT_BYTES, + /* One slot past the end of the channel area. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + T_CHAN_BYTES - + 7 * AVE_RING_SLOT_BYTES, + /* Inside the window but past the channel area. */ + T_FW_BASE + AVE_IPC_HANDSHAKE_OFF, + /* Past the window, and at the top of the address space. */ + T_FW_BASE + T_IPC_BYTES, + U64_MAX & ~(u64)(AVE_RING_SLOT_BYTES - 1), + }; + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + for (unsigned int d = 0; d < 2; d++) { + t_table_9003(ave); + put_unaligned_le64(bad[i], t_desc(ave, d) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_parse_channels(ave), -EPROTO, + "descriptor %u at %#llx", d, bad[i]); + } + } + t_canary_intact(test, ave); +} + +/* Rings may touch but not share a slot. */ +static void ave_ipc_test_channels_overlap(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Same place. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* A one-slot ring inside the other. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 1, + t_chan_addr(0x200 + 3 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Back to back, either way round. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO further up, so that IO_T2H can sit right below it. */ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x600)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO_T2H ending in IO's first slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); +} + +/* The 6070 table: unknown channels are skipped but still bounds checked. */ +static const struct { + const char *name; + u32 dir, doorbell, slots, offset; +} t_6070_desc[] = { + { "TERMINAL", 2, 0, 512, 0x700 }, { "IO", 0, 1, 32, 0x8700 }, + { "DEBUG", 0, 1, 8, 0x8f00 }, { "BUF_H2T", 0, 2, 1, 0x9100 }, + { "BUF_T2H", 1, 3, 1, 0x9140 }, { "SHAREDMALLOC", 1, 3, 8, 0x9180 }, + { "IO_T2H", 1, 3, 32, 0x9380 }, +}; + +static void t_table_6070(struct ave_dev *ave) +{ + for (unsigned int i = 0; i < ARRAY_SIZE(t_6070_desc); i++) + t_write_desc(ave, i, t_6070_desc[i].name, t_6070_desc[i].dir, + t_6070_desc[i].doorbell, t_6070_desc[i].slots, + t_chan_addr(t_6070_desc[i].offset)); +} + +static void ave_ipc_test_channels_6070_unknown(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *debug; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + ave->channel_bytes = ti.t->hello[1]; + t_table_6070(ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ave), 0); + + debug = t_desc(ave, 2); + /* An unused channel pointing past the channel area. */ + put_unaligned_le64(t_chan_addr(ave->channel_bytes), debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or outside the window altogether. */ + put_unaligned_le64(T_FW_BASE + T_IPC_BYTES, debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or with an unterminated name. */ + t_table_6070(ave); + memset(debug, 'D', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* IO must be exactly where this firmware puts it. */ + put_unaligned_le64(t_chan_addr(0x8700 + AVE_RING_SLOT_BYTES), + t_desc(ave, 1) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + put_unaligned_le32(2, t_desc(ave, 6) + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* With no shared-memory pool, SHAREDMALLOC is an unknown channel. */ + ti.t->smalloc_bytes = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 512U); + t_canary_intact(test, ave); +} + +/* Host-to-firmware ring: fill, refuse when full, wrap, drain to empty. */ +static void ave_ipc_test_ring_h2f(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_IO]; + + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + for (unsigned int n = 0; n < 4; n++) { + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, 0x1000 * (n + 1), 0x40 + n), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), + 0x1000ULL * (n + 1)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[1]), + 0x40ULL + n); + t_ring_indices_valid(test, r); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(1)); + /* Full: a fifth command must not overwrite one the firmware owns. */ + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x1000ULL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[1]), 0x40ULL); + + /* Not acked yet. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + /* The ack of slot 0 frees exactly that slot. */ + t_fw_post(ave, AVE_RING_IO, 0, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x1000ULL); + KUNIT_EXPECT_EQ(test, len, 0U); + KUNIT_EXPECT_EQ(test, r->producer, 0); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + /* Wrap into slot 0; the ring is full again. */ + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x5000, 0x44), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x5000ULL); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + + /* Acks come back in ring order 1, 2, 3, 0. */ + for (unsigned int k = 0; k < 4; k++) { + unsigned int n = (k + 1) % 4; + u64 want = n ? 0x1000ULL * (n + 1) : 0x5000ULL; + + t_fw_post(ave, AVE_RING_IO, n, want, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, want); + t_ring_indices_valid(test, r); + } + /* Empty. */ + KUNIT_EXPECT_EQ(test, r->consumer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x6000, 0x40), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[0]), 0x6000ULL); +} + +/* Firmware-to-host ring: the two low bits never reach the address. */ +static void ave_ipc_test_ring_f2h(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_T2H]; + + /* Every slot still belongs to the firmware. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x1000, 0x40), -ENOSPC); + for (unsigned int k = 0; k < 6; k++) { + unsigned int n = k % 4; + + t_fw_post(ave, AVE_RING_T2H, n, 0x2000 * (k + 1) | 2, 0x40); + KUNIT_ASSERT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x2000ULL * (k + 1)); + KUNIT_EXPECT_EQ(test, len, 0x40U); + /* Next to read is the following slot, next to give back this one. */ + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, (int)n); + /* Give it back: bit 0 set hands the slot to the firmware. */ + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, addr, len), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), addr | 1); + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, addr, len), -ENOSPC); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(3)); +} + +/* Every command buffer maps to its own offset and back; nothing else does. */ +static void ave_ipc_test_buf_of(struct kunit *test) +{ + const struct ave_fw_layout *layouts[] = { + &ave_layout_9003_78_0, &ave_layout_6070_11_1, + }; + + for (unsigned int l = 0; l < ARRAY_SIZE(layouts); l++) { + const struct ave_fw_transport *t; + struct ave_dev *ave; + struct t_ipc ti; + size_t max, prev_end = 0; + int off; + + t_ipc_init(test, &ti, layouts[l], SZ_4K); + ave = ti.ave; + t = ti.t; + for (unsigned int buf = 0; buf < AVE_BUF_COUNT; buf++) { + off = ave_ipc_buf_offset(ave, buf, &max); + KUNIT_EXPECT_GE(test, off, (int)t->command_offset); + KUNIT_EXPECT_GE(test, (size_t)off, prev_end); + KUNIT_EXPECT_LE(test, off + max, ave_ipc_command_end(ave)); + prev_end = off + max; + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE + off), + (int)buf); + /* Inside a buffer is not a buffer. */ + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + off + 4), + -EPROTO); + } + KUNIT_EXPECT_EQ(test, prev_end, (size_t)ave_ipc_command_end(ave)); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, 0), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE - 1), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE), -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + t->command_offset - 4), + -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + ave_ipc_command_end(ave)), + -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, U64_MAX), -EPROTO); + /* A buffer offset with no window base under it. */ + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, t->command_offset), -EPROTO); + } +} + +/* A command buffer is only handed out when it fits the window. */ +static void ave_ipc_test_cmd_bounds(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + size_t max; + int off; + u8 *cmd; + + /* A window that ends half way into the first Process buffer. */ + t_ipc_init(test, &ti, &ave_layout_6070_11_1, + ave_layout_6070_11_1.abi->transport->process_offset + SZ_32K); + ave = ti.ave; + + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT, 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, U32_MAX, 4)); + off = ave_ipc_buf_offset(ave, AVE_BUF_CMD, &max); + memset(ave->ipc.cpu + off, 0x5a, 0x100); + cmd = ave_ipc_cmd(ave, AVE_BUF_CMD, 0x80); + KUNIT_ASSERT_PTR_EQ(test, (void *)cmd, ave->ipc.cpu + off); + KUNIT_EXPECT_NULL(test, memchr_inv(cmd, 0, 0x80)); + KUNIT_EXPECT_EQ(test, cmd[0x80], 0x5a); + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max + 1)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(0), + AVE_IPC_SCALAR_BYTES + 1)); + KUNIT_EXPECT_NOT_NULL(test, + ave_ipc_cmd(ave, AVE_BUF_SCALAR(AVE_IPC_SCALAR_BUFS - 1), + AVE_IPC_SCALAR_BYTES)); + /* A buffer the firmware still owns is not handed out. */ + ave->unacked = BIT(AVE_BUF_SCALAR(3)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(3), 4)); + ave->unacked = 0; + /* Process buffer 0 fits up to the end of the window, not past it. */ + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K + 4)); + /* Process buffer 1 starts past the window. */ + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(1), 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT - 1, 4)); + t_canary_intact(test, ave); + + /* Submit applies the same bounds before it reads the command. */ + mutex_init(&ave->hw_lock); + mutex_lock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(0), SZ_32K + 4, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(1), 0x40, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_COUNT, 0x40, 0, false), + -EINVAL); + mutex_unlock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave->unacked, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].slots, 0U); +} + +/* Command acks: only the exact address of a buffer the firmware holds. */ +static void ave_ipc_test_poll_acks(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 good; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + good = T_FW_BASE + ti.t->scalar_offset + 2 * AVE_IPC_SCALAR_BYTES; + + /* Nothing pending. */ + t_rings(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* A good ack clears exactly its buffer. */ + ave->unacked = BIT(AVE_BUF_SCALAR(2)) | BIT(AVE_BUF_CMD); + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40), 0); + t_fw_post(ave, AVE_RING_IO, 0, good, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_CMD)); + + /* An ack with a payload. */ + t_rings(ave); + ave->unacked = BIT(AVE_BUF_SCALAR(2)); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); + /* An ack inside a buffer. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good + 0x40, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack outside the window. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good - T_FW_BASE - 0x1000000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack for a buffer the host never sent. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, + T_FW_BASE + ti.t->scalar_offset + 3 * AVE_IPC_SCALAR_BYTES, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); +} + +/* Play the firmware: a 6070 lifecycle reply at window offset @off. */ +static void t_reply(struct t_ipc *ti, u32 off, enum ave_opcode op, u32 client, + u32 subtype, u32 status) +{ + u8 *msg = ti->ave->ipc.cpu + off; + + memset(msg, 0, 0x40); + put_unaligned_le16(ti->abi->reply_id[op], msg); + put_unaligned_le32(client, msg + 0x10); + put_unaligned_le32(subtype, msg + 0x1c); + put_unaligned_le32(status, msg + 0x38); +} + +#define T_MSG_OFF AVE_IPC_SHARED_OFF +#define T_REPLY_OK 0x00ee0000 + +static void t_msg_init(struct kunit *test, struct t_ipc *ti) +{ + struct ave_dev *ave; + + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti->ave; + t_rings(ave); + ave->want[AVE_OP_OPEN] = 1; + ave->expected[AVE_OP_OPEN].client = 10; + ave->expected[AVE_OP_OPEN].subtype = ti->abi->semantic[AVE_OP_OPEN]; + t_reply(ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti->abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + memset(ave->msg, 0x5a, sizeof(ave->msg)); +} + +/* The message is copied only when it lies inside the window, outside the commands. */ +static void ave_ipc_test_poll_msg_bounds(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_layout_6070_11_1.abi->transport; + static const struct { + u64 off; + u64 len; + } bad[] = { + /* Larger than the host's message buffer. */ + { T_MSG_OFF, AVE_MSG_MAX + 1 }, + { T_MSG_OFF, U32_MAX }, + /* Running off the end of the window. */ + { T_IPC_BYTES - 0x20, 0x40 }, + { T_IPC_BYTES, 0x40 }, + /* In, or straddling into or out of, the command buffers. */ + { 0x40000, 0x40 }, + { 0x40000 - 0x20, 0x40 }, + { 0x78000 + AVE_IPC_PROC_BUFS * 0x10000 - 0x20, 0x40 }, + }; + struct t_ipc ti; + + /* The offsets above are the 6070 command area. */ + KUNIT_ASSERT_EQ(test, t->command_offset, 0x40000U); + KUNIT_ASSERT_EQ(test, t->process_offset + AVE_IPC_PROC_BUFS * t->process_bytes, + 0x78000U + AVE_IPC_PROC_BUFS * 0x10000); + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + bad[i].off, bad[i].len); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_poll_once(ti.ave), -EPROTO, + "message %#llx/%#llx", bad[i].off, bad[i].len); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 1); + } + /* Below the window, and an address that only wraps into it. */ + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_MSG_OFF - T_FW_BASE, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + + /* Right below the command area is fine. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x40000 - 0x40, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + 0x40000 - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 0); + /* So is right after it. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, + T_FW_BASE + 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + t_canary_intact(test, ti.ave); +} + +/* Replies are matched to what the host waits for, and the slot handed back. */ +static void ave_ipc_test_poll_dispatch(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, 0); + KUNIT_EXPECT_EQ(test, ave->msg_len, 0x40U); + KUNIT_EXPECT_MEMEQ(test, ave->msg, ave->ipc.cpu + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave->msg[0x40], 0x5a); + slot = t_slot(ave, &ave->ring[AVE_RING_T2H], 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_MSG_OFF) | 1); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* The same reply again: nobody waits for it. */ + t_fw_post(ave, AVE_RING_T2H, 1, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + + /* A reply for another client. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 11, ti.abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A reply of the wrong length or with an unknown id. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x3c); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + t_msg_init(test, &ti); + ave = ti.ave; + put_unaligned_le16(0xffff, ave->ipc.cpu + T_MSG_OFF); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A refusal is answered but recorded. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti.abi->semantic[AVE_OP_OPEN], 1); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, -EIO); + + /* A frame result on a firmware build that cannot encode. */ + t_msg_init(test, &ti); + ave = ti.ave; + ti.layout->encode_ready = false; + t_reply(&ti, T_MSG_OFF, AVE_OP_PROCESS, 10, 0, T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x48); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); +} + +/* Log lines: every slot is handed back, wherever the line claims to be. */ +static void ave_ipc_test_drain_log(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_LOG, 0x1000, 4, 0, true); + r = &ave->ring[AVE_RING_LOG]; + memcpy(ave->ipc.cpu + T_MSG_OFF, "line\n", 5); + memset(ave->ipc.cpu + T_IPC_BYTES - AVE_LOG_LINE_MAX, 'x', + AVE_LOG_LINE_MAX); + + /* Nothing written yet. */ + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 0); + + t_fw_post(ave, AVE_RING_LOG, 0, T_FW_BASE + T_MSG_OFF, 5); + /* Running off the end of the window. */ + t_fw_post(ave, AVE_RING_LOG, 1, T_FW_BASE + T_IPC_BYTES - 4, 0x100); + /* An oversized line at the very end: clamped, so it fits. */ + t_fw_post(ave, AVE_RING_LOG, 2, + T_FW_BASE + T_IPC_BYTES - AVE_LOG_LINE_MAX, U32_MAX); + ave_ipc_drain_log(ave); + for (unsigned int n = 0; n < 3; n++) + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, n)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), 1ULL); + KUNIT_EXPECT_EQ(test, r->consumer, 3); + + /* Below the window, then a NULL line; the index wraps. */ + t_fw_post(ave, AVE_RING_LOG, 3, T_FW_BASE - 0x100, 0x10); + t_fw_post(ave, AVE_RING_LOG, 0, 0, 0x10); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 0)), + (u64)AVE_LOG_SLOT_FREE); + + /* A full ring is read once round, not forever. */ + for (unsigned int n = 0; n < 4; n++) + t_fw_post(ave, AVE_RING_LOG, n, T_FW_BASE + T_MSG_OFF, 5); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + t_canary_intact(test, ave); + + /* No TERMINAL channel: nothing to read. */ + memset(ave->ring, 0, sizeof(ave->ring)); + ave_ipc_drain_log(ave); +} + +/* A shared-memory pool of 48 granules, sized down for the test. */ +#define T_POOL_OFF 0x20000 +#define T_POOL_BYTES 0x30000 + +static void t_pool_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_POOL_OFF + T_POOL_BYTES); + ti->t->smalloc_offset = T_POOL_OFF; + ti->t->smalloc_bytes = T_POOL_BYTES; +} + +/* Every block lies inside the pool, and only blocks lent can be returned. */ +static void ave_ipc_test_smalloc_bounds(struct kunit *test) +{ + const u64 start = T_FW_BASE + T_POOL_OFF; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, a, b; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ipc.cpu + T_POOL_OFF, 0x77, T_POOL_BYTES); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 0, &addr), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES + 1, &addr), -EINVAL); + /* The whole pool in one block, zeroed, and not a byte more. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + T_POOL_OFF, 0, T_POOL_BYTES)); + t_canary_intact(test, ave); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + + /* Returns that are not a lent block. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start - AVE_SMALLOC_GRANULE), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + T_POOL_BYTES), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, U64_MAX & ~(u64)(SZ_4K - 1)), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + 1), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + AVE_SMALLOC_GRANULE), -ENOENT); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), 0); + /* Twice. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), -ENOENT); + + /* Partial granules round up; the last block ends at the pool's end. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES - AVE_SMALLOC_GRANULE, &b), 0); + KUNIT_EXPECT_EQ(test, a, start); + KUNIT_EXPECT_EQ(test, b, start + AVE_SMALLOC_GRANULE); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, AVE_SMALLOC_GRANULE, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + t_canary_intact(test, ave); +} + +/* The host tracks at most AVE_SMALLOC_MAX blocks, even with room left. */ +static void ave_ipc_test_smalloc_slots(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, first = 0; + + t_pool_init(test, &ti); + ave = ti.ave; + KUNIT_ASSERT_GT(test, T_POOL_BYTES / AVE_SMALLOC_GRANULE, AVE_SMALLOC_MAX); + for (unsigned int i = 0; i < AVE_SMALLOC_MAX; i++) { + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, T_FW_BASE + T_POOL_OFF + i * AVE_SMALLOC_GRANULE); + if (!i) + first = addr; + } + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOSPC); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, first), 0); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, first); +} + +/* The SHAREDMALLOC ring: unknown returns are answered, bad sizes stop serving. */ +static void ave_ipc_test_serve_smalloc(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 0); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + r = &ave->ring[AVE_RING_SMALLOC]; + + /* A block the host never lent: answered with no size. */ + t_fw_post(ave, AVE_RING_SMALLOC, 0, T_FW_BASE + T_POOL_OFF + SZ_64K, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + slot = t_slot(ave, r, 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_POOL_OFF + SZ_64K) | 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[1]), 0ULL); + /* An address outside the window is answered the same way. */ + t_fw_post(ave, AVE_RING_SMALLOC, 1, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[1]), 0ULL); + /* A request with no size, then one larger than the pool. */ + t_fw_post(ave, AVE_RING_SMALLOC, 2, 0, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, T_POOL_BYTES + 1); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring_indices_valid(test, r); + t_canary_intact(test, ave); +} + +/* + * Request sizes near 4 GiB: rounding them up to granules must not wrap to + * zero granules, which would lend nothing while telling the firmware it + * has the whole size, at an address the next request gets again. + */ +static void ave_ipc_test_smalloc_huge(struct kunit *test) +{ + static const u32 huge[] = { + U32_MAX - AVE_SMALLOC_GRANULE + 1, + U32_MAX - AVE_SMALLOC_GRANULE + 2, + U32_MAX, + }; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + + t_pool_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(huge); i++) + KUNIT_EXPECT_EQ_MSG(test, ave_smalloc_get(ave, huge[i], &addr), -EINVAL, + "request of %#x bytes", huge[i]); + + /* Through the ring: the request must not be answered with a block. */ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, U32_MAX); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, &ave->ring[AVE_RING_SMALLOC], 0)[0]), + 0ULL); +} + +static struct kunit_case ave_ipc_test_cases[] = { + KUNIT_CASE(ave_ipc_test_hello_9003), + KUNIT_CASE(ave_ipc_test_negotiate_bad_hello), + KUNIT_CASE(ave_ipc_test_negotiate_window), + KUNIT_CASE(ave_ipc_test_channels_9003), + KUNIT_CASE(ave_ipc_test_channels_malformed), + KUNIT_CASE(ave_ipc_test_channels_out_of_range), + KUNIT_CASE(ave_ipc_test_channels_overlap), + KUNIT_CASE(ave_ipc_test_channels_6070_unknown), + KUNIT_CASE(ave_ipc_test_ring_h2f), + KUNIT_CASE(ave_ipc_test_ring_f2h), + KUNIT_CASE(ave_ipc_test_buf_of), + KUNIT_CASE(ave_ipc_test_cmd_bounds), + KUNIT_CASE(ave_ipc_test_poll_acks), + KUNIT_CASE(ave_ipc_test_poll_msg_bounds), + KUNIT_CASE(ave_ipc_test_poll_dispatch), + KUNIT_CASE(ave_ipc_test_drain_log), + KUNIT_CASE(ave_ipc_test_smalloc_bounds), + KUNIT_CASE(ave_ipc_test_smalloc_slots), + KUNIT_CASE(ave_ipc_test_serve_smalloc), + KUNIT_CASE(ave_ipc_test_smalloc_huge), + {} +}; + +static struct kunit_suite ave_ipc_test_suite = { + .name = "apple-ave-ipc", + .test_cases = ave_ipc_test_cases, +}; + +kunit_test_suite(ave_ipc_test_suite); diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 60a5b006a7875e..e6288a6a86b251 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -1001,3 +1001,7 @@ int ave_ipc_settle(struct ave_dev *ave, unsigned int wait_ms) ave->reply_err = 0; return ret; } + +#if IS_ENABLED(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) +#include "ave-ipc-test.c" +#endif diff --git a/drivers/media/platform/apple/ave/ave-writer-test.c b/drivers/media/platform/apple/ave/ave-writer-test.c new file mode 100644 index 00000000000000..1228eba62da1a3 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-writer-test.c @@ -0,0 +1,438 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the checks the 6070 Start and Process builders make on + * session parameters and buffers before they write a command: counts that + * index the session arrays, every surface the firmware is told about, and + * the codec state copied into Process. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include +#include +#include +#include + +#include "ave.h" +#include "ave-layout.h" + +#define T_FILL 0xa5 + +struct t_wr { + struct ave_dev *ave; + struct ave_ctx *ctx; + struct ave_session *sess; + struct ave_fw_layout *fw; + u8 *start, *process; + size_t start_len, process_len; +}; + +/* Synthetic, 16 KiB aligned DMA addresses, one window per buffer. */ +static void t_buf(struct ave_buf *b, unsigned int *index) +{ + b->dma = 0x820000000ULL + (u64)(*index) * 0x2000000; + b->size = SZ_16K * (1 + (*index)++); +} + +static void t_wr_init(struct kunit *test, struct t_wr *t, enum ave_codec codec) +{ + struct ave_session *sess; + struct ave_params *p; + unsigned int index = 0; + + t->ave = kunit_kzalloc(test, sizeof(*t->ave), GFP_KERNEL); + t->ctx = kunit_kzalloc(test, sizeof(*t->ctx), GFP_KERNEL); + t->sess = kunit_kzalloc(test, sizeof(*t->sess), GFP_KERNEL); + t->fw = kunit_kmalloc(test, sizeof(*t->fw), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->ave && t->ctx && t->sess && t->fw); + *t->fw = ave_layout_6070_11_1; + t->fw->encode_ready = true; + t->ave->layout = t->fw; + t->ctx->ave = t->ave; + t->ctx->sess = t->sess; + sess = t->sess; + p = &sess->p; + + *p = (struct ave_params){ + .codec = codec, + .width = 1920, + .height = 1080, + .cw = 1920, + .ch = ALIGN(1080, 16), + .stride = ALIGN(1920, 64), + .fps_num = 30, + .fps_den = 1, + .fps_int = 30, + .bframes = true, + .slots = 5, + .refs = 5, + .gop = 30, + .rc_mode = 3, + .bitrate = 4000000, + .initial_qp = 33, + .min_qp = 0, + .max_qp = 48, + .profile = codec == AVE_CODEC_H264 ? 4 : 1, + .level = codec == AVE_CODEC_H264 ? 13 : 7, + .bit_depth = 8, + }; + p->mbs = p->cw / 16 * (p->ch / 16); + p->coded_cap = ALIGN(3 * p->cw * p->ch, SZ_16K); + sess->token = 400; + sess->client = 10; + t_buf(&sess->hdr, &index); + t_buf(&sess->client_mem, &index); + sess->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + t_buf(&sess->param_sets, &index); + for (unsigned int i = 0; i < AVE_MAX_REFS; i++) { + t_buf(&sess->ref_a[i], &index); + t_buf(&sess->ref_b[i], &index); + t_buf(&sess->ref_c[i], &index); + t_buf(&sess->ref_d[i], &index); + } + t_buf(&sess->mb, &index); + for (unsigned int set = 0; set < AVE_NEIGHBOUR_SETS; set++) { + t_buf(&sess->row_a[set], &index); + t_buf(&sess->row_b[set], &index); + t_buf(&sess->fixed[set], &index); + t_buf(&sess->neighbour_fw[set], &index); + } + for (unsigned int set = 0; set < AVE_ENTROPY_SETS; set++) + for (unsigned int i = 0; i < AVE_TILE_BUFS; i++) { + t_buf(&sess->tile[set][i], &index); + t_buf(&sess->tile_aux[set][i], &index); + } + for (unsigned int i = 0; i < 2; i++) { + t_buf(&sess->hevc_extra[i], &index); + t_buf(&sess->hevc_transcoded[i], &index); + } + sess->hevc_transcoded[1].size = sess->hevc_transcoded[0].size; + for (unsigned int i = 0; i < AVE_MAX_SLOTS; i++) { + t_buf(&sess->slot[i].coded, &index); + t_buf(&sess->slot[i].meta, &index); + t_buf(&sess->slot[i].aux, &index); + } + sess->codec_state_bytes = t->fw->codec_state_bytes[codec - 1]; + sess->codec_state = kunit_kzalloc(test, sess->codec_state_bytes, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sess->codec_state); + KUNIT_ASSERT_EQ(test, ave_init_codec_state(sess), 0); + + t->start_len = t->fw->bytes[codec - 1][AVE_IMAGE_START]; + t->process_len = t->fw->bytes[codec - 1][AVE_IMAGE_PROCESS]; + t->start = kunit_kmalloc(test, t->start_len + 1, GFP_KERNEL); + t->process = kunit_kmalloc(test, t->process_len + 1, GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->start && t->process); +} + +/* Build Start into a filled buffer; a refusal must leave it untouched. */ +static int t_start(struct kunit *test, struct t_wr *t) +{ + int ret; + + memset(t->start, T_FILL, t->start_len + 1); + ret = ave_build_start(t->ctx, t->start, t->start_len); + if (ret) + KUNIT_EXPECT_NULL(test, memchr_inv(t->start, T_FILL, t->start_len)); + KUNIT_EXPECT_EQ(test, t->start[t->start_len], T_FILL); + return ret; +} + +static int t_process(struct kunit *test, struct t_wr *t, unsigned int slot, + dma_addr_t input) +{ + memset(t->process, T_FILL, t->process_len + 1); + return ave_build_process(t->ctx, t->process, t->process_len, slot, input, + t->sess->p.bitrate, false, false); +} + +#define T_INPUT 0x8f0000000ULL + +/* Counts that index the session's arrays are bounded before any is read. */ +static void ave_writer_test_start_counts(struct kunit *test) +{ + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + p = &t.sess->p; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + + p->refs = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS; + p->slots = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* A command buffer of any other size. */ + memset(t.start, T_FILL, t.start_len + 1); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len - 4), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len + 1), -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.start, T_FILL, t.start_len + 1)); + /* A layout that cannot encode builds nothing. */ + t.fw->encode_ready = false; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EOPNOTSUPP); +} + +/* + * Each buffer the firmware gets must be mapped and 16 KiB aligned. Flip + * the alignment of one at a time: the last one of each array counts too. + */ +static void ave_writer_test_start_buffers(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; +#define T_BAD(field) \ + do { \ + dma_addr_t keep = (field).dma; \ + (field).dma = keep + SZ_4K; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "misaligned " #field); \ + (field).dma = 0; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "unmapped " #field); \ + (field).dma = keep; \ + } while (0) + T_BAD(s->hdr); + T_BAD(s->client_mem); + T_BAD(s->param_sets); + T_BAD(s->ref_a[0]); + T_BAD(s->ref_a[AVE_MAX_REFS - 1]); + T_BAD(s->ref_b[AVE_MAX_REFS - 1]); + T_BAD(s->ref_c[AVE_MAX_REFS - 1]); + T_BAD(s->ref_d[AVE_6070_LOWRES_RESULTS - 1]); + T_BAD(s->slot[0].coded); + T_BAD(s->slot[4].coded); + T_BAD(s->slot[4].meta); + T_BAD(s->row_a[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->row_b[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->fixed[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->neighbour_fw[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->tile[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); + T_BAD(s->tile_aux[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); +#undef T_BAD + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* The client memory has the size the firmware expects, no other. */ + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES - SZ_16K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + s->param_sets.size = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->param_sets.size = SZ_16K; + + /* Buffers this session does not use are not looked at. */ + s->slot[5].coded.dma = 0; + s->tile[0][AVE_6070_AVC_ENTROPY_TILES].dma = 1; + s->hevc_extra[1].dma = 1; + s->hevc_transcoded[0].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* HEVC uses four entropy tiles and the transcode buffers too. */ +static void ave_writer_test_start_buffers_hevc(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + s = t.sess; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + s->tile[AVE_ENTROPY_SETS - 1][3].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile[AVE_ENTROPY_SETS - 1][3].dma -= SZ_4K; + s->tile_aux[0][3].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile_aux[0][3].dma = 0x8e0000000ULL; + s->hevc_extra[1].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_extra[1].dma -= SZ_4K; + s->hevc_transcoded[1].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_transcoded[1].dma = 0x8e0004000ULL; + /* The fifth tile is not used. */ + s->tile[0][4].dma = 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* general_level_idc is 30 times the level (H.265 A.4); other levels are 0. */ +static void ave_writer_test_hevc_level_idc(struct kunit *test) +{ + static const u32 idc[] = { 0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 0 }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + l = &t.fw->start[AVE_CODEC_HEVC - 1]; + KUNIT_ASSERT_NE(test, l->hevc_level_a, 0U); + KUNIT_ASSERT_NE(test, l->hevc_level_b, 0U); + KUNIT_ASSERT_LE(test, l->hevc_level_a + 4, (u32)t.start_len); + KUNIT_ASSERT_LE(test, l->hevc_level_b + 4, (u32)t.start_len); + for (unsigned int level = 0; level < ARRAY_SIZE(idc); level++) { + t.sess->p.level = level; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_a), + idc[level], "level %u", level); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_b), + idc[level], "level %u", level); + } + t.sess->p.level = U32_MAX; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(t.start + l->hevc_level_a), 0U); +} + +/* H.264 level_idc (Table A-1) for every level the controls can select. */ +static void ave_writer_test_h264_level_idc(struct kunit *test) +{ + static const u32 idc[] = { + 10, 9, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, + }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + l = &t.fw->start[AVE_CODEC_H264 - 1]; + KUNIT_ASSERT_NE(test, l->h264_level, 0U); + for (unsigned int i = 0; i < ARRAY_SIZE(idc); i++) { + t.sess->p.level = i + 1; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->h264_level), + idc[i], "level %u", i + 1); + } +} + +/* Process: the slot, the input and the slot's buffers are checked first. */ +static void ave_writer_test_process_refusal(struct kunit *test) +{ + struct ave_session *s; + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + p = &s->p; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + KUNIT_EXPECT_EQ(test, t.process[t.process_len], T_FILL); + KUNIT_ASSERT_EQ(test, t_process(test, &t, p->slots - 1, T_INPUT), 0); + +#define T_REFUSED(expr) \ + do { \ + KUNIT_EXPECT_EQ_MSG(test, (expr), -EINVAL, #expr); \ + KUNIT_EXPECT_NULL_MSG(test, \ + memchr_inv(t.process, T_FILL, t.process_len + 1), \ + #expr " wrote the command"); \ + } while (0) + T_REFUSED(t_process(test, &t, p->slots, T_INPUT)); + T_REFUSED(t_process(test, &t, AVE_MAX_SLOTS, T_INPUT)); + T_REFUSED(t_process(test, &t, U32_MAX, T_INPUT)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + SZ_4K)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + 1)); + p->slots = t.fw->max_slots + 1; + T_REFUSED(t_process(test, &t, 0, T_INPUT)); + p->slots = 5; + s->slot[2].coded.dma += SZ_4K; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].coded.dma -= SZ_4K; + s->slot[2].meta.dma = 0; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].meta.dma = 0x8e0000000ULL; + s->slot[2].aux.dma += 4; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].aux.dma -= 4; + /* No codec state to copy into the command. */ + s->codec_state = NULL; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); +#undef T_REFUSED + memset(t.process, T_FILL, t.process_len + 1); + KUNIT_EXPECT_EQ(test, + ave_build_process(t.ctx, t.process, t.process_len - 4, 0, + T_INPUT, p->bitrate, false, false), + -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.process, T_FILL, t.process_len + 1)); +} + +/* The codec state copied into Process may not be read past its end. */ +static void ave_writer_test_process_state_bounds(struct kunit *test) +{ + const enum ave_codec codecs[] = { AVE_CODEC_H264, AVE_CODEC_HEVC }; + + for (unsigned int c = 0; c < ARRAY_SIZE(codecs); c++) { + struct ave_session *s; + struct t_wr t; + size_t full; + + t_wr_init(test, &t, codecs[c]); + s = t.sess; + full = s->codec_state_bytes; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + /* The same state in a buffer one byte short. */ + s->codec_state_bytes = full - 1; + s->codec_state = kunit_kzalloc(test, full - 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, s->codec_state); + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 1; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 0; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + } +} + +/* The codec state is only set up at the size this firmware uses. */ +static void ave_writer_test_codec_state(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + u8 *state; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + state = s->codec_state; + s->codec_state = NULL; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->codec_state = state; + s->codec_state_bytes = t.fw->codec_state_bytes[0] - 4; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + /* An H.264 state where HEVC is set up, and the other way round. */ + s->codec_state_bytes = t.fw->codec_state_bytes[0]; + s->p.codec = AVE_CODEC_HEVC; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = 0; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = AVE_CODEC_H264; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(state), (u32)s->codec_state_bytes); +} + +static struct kunit_case ave_writer_test_cases[] = { + KUNIT_CASE(ave_writer_test_start_counts), + KUNIT_CASE(ave_writer_test_start_buffers), + KUNIT_CASE(ave_writer_test_start_buffers_hevc), + KUNIT_CASE(ave_writer_test_hevc_level_idc), + KUNIT_CASE(ave_writer_test_h264_level_idc), + KUNIT_CASE(ave_writer_test_process_refusal), + KUNIT_CASE(ave_writer_test_process_state_bounds), + KUNIT_CASE(ave_writer_test_codec_state), + {} +}; + +static struct kunit_suite ave_writer_test_suite = { + .name = "apple-ave-writer", + .test_cases = ave_writer_test_cases, +}; + +kunit_test_suite(ave_writer_test_suite); + +MODULE_DESCRIPTION("KUnit tests for Apple AVE command builder input checks"); +MODULE_LICENSE("GPL"); From 599c10df66c2d37928cf1e3fd15a0aa8ddb65111 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:09 +1100 Subject: [PATCH 0500/1514] ASoC: apple: macaudio: add speaker volume unlock tests The "Speaker Volume Unlock" lease (macaudio_vlimit_update(), the slk_* control and the timeout work) has no direct tests. Add the apple-speaker-volume-unlock suite (9 cases) on the card of the pm-volumes tests: the speaker volumes leave the safe ceiling only while one process holds the lock control and every speaker volume, and only while it pings within SPEAKER_LOCK_TIMEOUT while speaker playback runs; a missed ping or a volume with another owner relocks them, and the lease is kept while idle. Mutations caught: mixed volume owners no longer relock, and the timeout work keeping the lease. Signed-off-by: Ryan Murray --- sound/soc/apple/macaudio-vlimit-test.h | 251 +++++++++++++++++++++++++ sound/soc/apple/macaudio.c | 1 + 2 files changed, 252 insertions(+) create mode 100644 sound/soc/apple/macaudio-vlimit-test.h diff --git a/sound/soc/apple/macaudio-vlimit-test.h b/sound/soc/apple/macaudio-vlimit-test.h new file mode 100644 index 00000000000000..26b8764805a65e --- /dev/null +++ b/sound/soc/apple/macaudio-vlimit-test.h @@ -0,0 +1,251 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * The "Speaker Volume Unlock" lease: the speaker volumes leave the safe + * ceiling only while one process holds the lock control and every speaker + * volume, and pings within SPEAKER_LOCK_TIMEOUT ms while speaker playback + * runs. Built on the card of macaudio-pm-volumes-test.h. + */ +#include +#include + +static int macaudio_vlt_put(struct kunit *test, struct macaudio_pmt_pm *t, long val) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + uval->value.integer.value[0] = val; + return macaudio_slk_put(t->slk, uval); +} + +static long macaudio_vlt_get(struct kunit *test, struct macaudio_pmt_pm *t) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + KUNIT_EXPECT_EQ(test, macaudio_slk_get(t->slk, uval), 0); + return uval->value.integer.value[0]; +} + +/* Speaker playback runs (or stops): the ping deadline is armed (or held). */ +static void macaudio_vlt_playing(struct macaudio_pmt_pm *t, bool playing) +{ + if (playing) + macaudio_vlimit_enable_timeout(t->ma); + else + macaudio_vlimit_disable_timeout(t->ma); +} + +/* Saved mixer states hold 0 or 1: restoring one is a no-op, nothing else is. */ +static void macaudio_vlimit_restore_values_are_noops(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 0), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, SPEAKER_MAGIC_VALUE + 1), -EINVAL); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + + /* Even for the owner */ + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* A ping without the lock is refused and unlocks nothing. */ +static void macaudio_vlimit_ping_needs_the_lock(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); +} + +/* The lock alone is not enough: every speaker volume must be the owner's. */ +static void macaudio_vlimit_needs_every_volume(struct kunit *test) +{ + struct snd_ctl_file *other = kunit_kzalloc(test, sizeof(*other), GFP_KERNEL); + struct macaudio_pmt_pm t; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, other); + for (i = 0; i < MACAUDIO_PMT_NR_VOLS - 1; i++) { + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s held by another file", macaudio_pmt_vol_names[i]); + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = NULL; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s not locked", macaudio_pmt_vol_names[i]); + } + + /* A volume that is not a speaker volume does not count */ + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[MACAUDIO_PMT_NR_VOLS - 1]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* Closing the lock relocks at once and clips the speaker volumes only. */ +static void macaudio_vlimit_unlock_clips(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 1L); + macaudio_pmt_expect_vols(test, &t, false); + + macaudio_slk_unlock(t.slk); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + macaudio_pmt_expect_vols(test, &t, true); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* + * While playback runs the lease ends SPEAKER_LOCK_TIMEOUT ms after the last + * ping. The owner's next ping reports the loss with -ETIMEDOUT and unlocks + * nothing; only the ping after it starts a new lease. + */ +static void macaudio_vlimit_lease_expires_while_playing(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_pmt_expect_vols(test, &t, true); + + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* + * Each ping moves the deadline to SPEAKER_LOCK_TIMEOUT ms after itself and + * re-arms the expiry. Checked on the deadline, not by racing the clock. + */ +static void macaudio_vlimit_pings_keep_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + ktime_t before, deadline; + unsigned int i; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + deadline = t.ma->speaker_lock_timeout; + for (i = 0; i < 3; i++) { + usleep_range(1000, 2000); + before = ktime_get(); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_GT(test, t.ma->speaker_lock_timeout, deadline); + KUNIT_EXPECT_GE(test, t.ma->speaker_lock_timeout, + ktime_add_ms(before, SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + deadline = t.ma->speaker_lock_timeout; + } + macaudio_vlt_playing(&t, false); +} + +/* + * Without playback the deadline is held: an idle owner keeps its lease, and + * the time it had left runs on when playback starts again. + */ +static void macaudio_vlimit_idle_holds_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, t.ma->speaker_lock_remain, ms_to_ktime(SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + + /* The time left runs from the start of playback and then ends */ + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* A new owner never inherits the previous owner's lease. */ +static void macaudio_vlimit_new_owner_pings_first(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_LE(test, t.ma->speaker_lock_remain, 0); + /* The relock was the switch of owners, not a lost lease */ + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* A card without speaker safety never touches its volumes. */ +static void macaudio_vlimit_without_safety(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + t.ma->has_safety = false; + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_slk_unlock(t.slk); + macaudio_pmt_expect_vols(test, &t, false); +} + +static struct kunit_case macaudio_vlimit_cases[] = { + KUNIT_CASE(macaudio_vlimit_restore_values_are_noops), + KUNIT_CASE(macaudio_vlimit_ping_needs_the_lock), + KUNIT_CASE(macaudio_vlimit_needs_every_volume), + KUNIT_CASE(macaudio_vlimit_unlock_clips), + KUNIT_CASE_SLOW(macaudio_vlimit_lease_expires_while_playing), + KUNIT_CASE(macaudio_vlimit_pings_keep_the_lease), + KUNIT_CASE_SLOW(macaudio_vlimit_idle_holds_the_lease), + KUNIT_CASE(macaudio_vlimit_new_owner_pings_first), + KUNIT_CASE(macaudio_vlimit_without_safety), + {} +}; + +static struct kunit_suite macaudio_vlimit_suite = { + .name = "apple-speaker-volume-unlock", + .test_cases = macaudio_vlimit_cases, +}; + +kunit_test_suite(macaudio_vlimit_suite); diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index b05d60bc0451a0..790e512f9c75ff 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -4623,6 +4623,7 @@ MODULE_LICENSE("GPL"); #include "macaudio-protection-test.h" #include "macaudio-hpf-test.h" #include "macaudio-pm-volumes-test.h" +#include "macaudio-vlimit-test.h" #include "macaudio-iface-test.h" #if IS_ENABLED(CONFIG_OF_OVERLAY) #include "macaudio-amp-level-test.h" From 20783b6037135144085d525726ba868b624c8c1e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:09:36 +1100 Subject: [PATCH 0501/1514] drm: apple: cec test: allocate the fakes before the device dcp_cec_test_setup() allocates the fake apple_dcp and AFK endpoint with kunit_kzalloc() after kunit_device_register(). KUnit releases resources in reverse order, so both are freed before the device is unregistered, and the device's devres action dcp_cec_devm_release() then reads them: KASAN reports a use-after-free in dcp_cec_unregister() and UBSAN an invalid bool load in afk_service_retry() for the apple-dcp-cec-adap cases. Allocate the fakes before the device. Fixes: 75773377faae ("drm/apple: add native HDMI-CEC and 2 ms IRQ_HPD pulse tracking") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/cec_adap_test.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/cec_adap_test.c b/drivers/gpu/drm/apple/cec_adap_test.c index 61a30501b3ef7d..d4b560c96fc68a 100644 --- a/drivers/gpu/drm/apple/cec_adap_test.c +++ b/drivers/gpu/drm/apple/cec_adap_test.c @@ -159,12 +159,13 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); spin_lock_init(&ctx->lock); - ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); - + /* + * The fakes are allocated before the device: KUnit frees in reverse + * order, and the device's devres (dcp_cec_devm_release()) still uses + * them when the device is unregistered. + */ ctx->dcp = kunit_kzalloc(test, sizeof(*ctx->dcp), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dcp); - ctx->dcp->dev = ctx->dev; ctx->dcp->fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA; ctx->ep = kunit_kzalloc(test, sizeof(*ctx->ep), GFP_KERNEL); @@ -173,6 +174,10 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) ctx->ep->endpoint = AV_AUDIO_ENDPOINT_DESKTOP; ctx->ep->compact = true; + ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + ctx->dcp->dev = ctx->dev; + ctx->port_srv.ep = ctx->ep; ctx->dcp->dptxport[0].service = &ctx->port_srv; From 38b37776c85cbedf7774bd913dbb54101742bb8d Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 22 Nov 2026 21:19:37 -0300 Subject: [PATCH 0502/1514] arm64: dts: apple: t6041-j575c: give the PMC DCS limit a power model Commit 5f3bca941c97 ("arm64: dts: apple: t6041: select M4 Max CLPC and wire GPU/DCS cooling") made the PMC DCS limit a cooling device. On T6041 it has no apple,dcs-power-microwatt, so it is not a power actor: the default power_allocator governor skips it, and once a zone that binds it has been moved to another governor it cannot go back: power_allocator: pmc-dcs is not a power actor power_allocator: binding failed Give the J575c's limit the power model the binding describes: system power above DCS state 0 at each DCS state, under a load whose speed follows the DCS state. Measured on one J575c (Mac Studio, M4 Max with 16 CPU and 40 GPU cores, 48 GB) with all 32 DCS channels enabled (ADT mcc: 8 AMCCs with 4 DCS each, dcs-channel-enable-mask 0xffffffff), with 256 MiB Vulkan buffer copies running throughout, pmc-dcs stepped through every state in four rounds of alternating order, and "Total System Power" (SMC) sampled at 2 Hz for 10 s per state: DCS state 5 4 3 2 1 0 system power 42.4 40.0 36.9 31.2 30.8 31.4 W GPU copy 233 208 182 123 85 85 GB/s States 1 and 2 draw no more than state 0, so they get 0. As a result power_allocator never limits DCS below state 2 (cooling state 3). The model goes in the board file, not t6041.dtsi: it comes from one memory configuration of one desktop, and the J614c and J616c, which bind the limit too, have not been measured. Nor has the M4 Max with the narrower memory bus (fewer DCS channels); on such a J575c this model probably overstates the DCS power. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index a9b42e9a63ab1d..556868f64edbbe 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -993,6 +993,18 @@ status = "okay"; }; +&pmc { + /* + * System power above DCS state 0 at each DCS state, measured on a + * J575c with all 32 DCS channels enabled (ADT mcc: 8 AMCCs, 4 DCS + * each, dcs-channel-enable-mask 0xffffffff) under 256 MiB GPU copies: + * 233 GB/s at state 5, 85 GB/s at states 0 and 1. States 1 and 2 draw + * no more than state 0, so the power allocator never asks for a limit + * below DCS state 2 (cooling state 3). + */ + apple,dcs-power-microwatt = <0 0 0 5508000 8559000 10966000>; +}; + /* The J616c's CPU keys and two fans, all read back on a J575c */ &smc_hwmon { temperature-TCMz { From 16434035dcbd582b16f4f4a65e76bc61631a1335 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 22 Nov 2026 21:19:37 -0300 Subject: [PATCH 0503/1514] arm64: dts: apple: t6041-j575c: bind the PMC DCS limit to the die zone Commit 5f3bca941c97 ("arm64: dts: apple: t6041: select M4 Max CLPC and wire GPU/DCS cooling") bound the PMC DCS limit to the cpu-die-thermal passive trip on the J614c and J616c only. The J575c zones are copies of theirs (same T6041, same sensors and trips), so bind it on the J575c too. sustainable-power stays at 48 W. With the limit in the zone, power_allocator splits that budget among the three CPU domains and the DCS limit by their requested power, so at the control trip the CPUs get less of it than before. That is intended: memory power then counts against the same die budget, and there is no J575c measurement to size a larger budget from. On this desktop the zone does not reach its trips anyway: under CPU and GPU load the SMC fans hold TCMz below 100 C. Tested on a J575c (Mac Studio, M4 Max), kernel from integration/aurora e892113c7, this DTB against the base DTB: - pmc-dcs is bound to cpu-die-passive next to the three CPU domains, and the zone goes to step_wise and back to power_allocator. - Real temperature, with the zone trips moved at runtime to 90/94 C (same gap, same PID constants), 16 CPU threads plus GPU copies for 5 min: at the same mean TCMz (87.8 C base, 87.0/87.4 C here) the DCS limit takes 16-19% of the granted power and GPU copies drop from 229 to 189-196 GB/s; CPU clocks stay within the run-to-run spread. The limit moves with the CPU domains, mostly between states 0 and 3. The zone already switched about 45 times a minute without it, because TCMz jumps by up to 25 C between samples while throttled; the DCS limit adds no oscillation of its own. Every state is 0 once the load stops. - Boot: no failed units, the same kernel errors as with the base DTB. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 556868f64edbbe..5b766cbc58d5fa 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -178,6 +178,12 @@ <&cpu_p14 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, <&cpu_p15 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; }; + + map-dcs { + trip = <&cpu_die_passive>; + cooling-device = + <&pmc THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; }; }; From d91adf9ae97d1f311d397a947868d3ff6854b481 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:06:43 +1100 Subject: [PATCH 0504/1514] soc: apple: sep: let a sep-bio capture end a sep-key touch wait A touch-gated /dev/sep-key call holds the sensor lock while it waits for a finger, up to a minute. A verify or an enrolment that /dev/sep-bio starts in that time queues its work item behind the lock, so a login or sudo prompt gets no sensor until the key call ends. The capture of the key call was also kept alive by the queued /dev/sep-bio capture: capture_live() returned true for either owner, so SEP_KEY_CANCEL and a signal to the caller did not end the wait while a prompt was queued. Decide who the running capture belongs to in one place, touch_capture_wanted(). While a touch-gated call owns the capture it is wanted until the call is cancelled, signalled or the driver goes away, or until /dev/sep-bio has a capture of its own that has not ended. The key call holds the sensor lock, so such a capture can only be waiting for it. The call then returns EBUSY and drops the lock, and the queued work item runs. A call that finds a /dev/sep-bio capture already queued when it gets the lock returns EBUSY without starting a capture. The UAPI header lists EBUSY for this case. A match or a non-match that was already decided is reported as before. Calls with no /dev/sep-bio activity behave as before. Signed-off-by: Ryan Murray --- drivers/soc/apple/key.rs | 61 ++++++++++++++++++++++++++++++---- include/uapi/linux/apple-sep.h | 5 +-- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index d227fd887f5382..d6607adc8e7a06 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -139,6 +139,23 @@ pub(crate) fn create_policy(flags: u32) -> Result { /// none until this long has passed; one capture itself waits up to a minute. const TOUCH_WAIT_MS: u64 = 60_000; +/// Whether the capture a verify is waiting on is still wanted. +/// +/// While a touch-gated `/dev/sep-key` call owns the capture (`key_wait`), it +/// is wanted until that call ends (`key_ended`: `CANCEL`, a signal, the +/// driver going away) or `/dev/sep-bio` starts an enrolment or a verify of +/// its own (`bio_live`). The call holds the sensor lock, so that capture's +/// work item can only be queued behind it: the call gives the sensor up +/// rather than keep a login prompt waiting for the rest of its minute. +/// Otherwise the capture is `/dev/sep-bio`'s and lives as its session says. +pub(crate) fn touch_capture_wanted(key_wait: bool, key_ended: bool, bio_live: bool) -> bool { + if key_wait { + !key_ended && !bio_live + } else { + bio_live + } +} + const MAGIC: u32 = 0xB1; /// Handle header: `"SEPK"`, version, flags, reserved u16, blob length (LE u32). @@ -1329,6 +1346,22 @@ mod tests { assert!(check_password(&pw).is_err()); } + #[test] + fn a_bio_capture_takes_the_sensor_from_a_key_touch_wait() { + // A touch-gated call waits alone: its capture is wanted. + assert!(touch_capture_wanted(true, false, false)); + // /dev/sep-bio starts a verify or an enrolment behind it: the call + // gives the sensor up at once. + assert!(!touch_capture_wanted(true, false, true)); + // CANCEL, a signal or shutdown ends the wait, also while a + // /dev/sep-bio capture is queued behind it. + assert!(!touch_capture_wanted(true, true, false)); + assert!(!touch_capture_wanted(true, true, true)); + // No touch-gated call: the capture is /dev/sep-bio's own. + assert!(touch_capture_wanted(false, false, true)); + assert!(!touch_capture_wanted(false, false, false)); + } + #[test] fn version_4_ioctls_have_their_sizes() { assert_eq!(IOC_CREATE_USER & 0xff, 0x28); @@ -1376,12 +1409,22 @@ impl SepData { /// touch-gated signature that owns it, or /dev/sep-bio's live session. /// A touch-gated call runs its capture in the caller's own thread, so a /// signal to the caller (or its death) ends the capture at once. + /// A capture `/dev/sep-bio` starts meanwhile ends it too (see + /// [`touch_capture_wanted`]). pub(crate) fn capture_live(&self) -> bool { - (self.key_touch_active.load(Relaxed) - && !self.key_touch_cancel.load(Relaxed) - && !self.shutting_down.load(Relaxed) - && !kernel::current!().signal_pending()) - || crate::bio::capture_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) + let key_wait = self.key_touch_active.load(Relaxed); + let key_ended = key_wait + && (self.key_touch_cancel.load(Relaxed) + || self.shutting_down.load(Relaxed) + || kernel::current!().signal_pending()); + touch_capture_wanted(key_wait, key_ended, self.bio_capture_live()) + } + + /// Whether `/dev/sep-bio` has an enrolment or a verify that has not + /// ended. During a touch-gated call, which holds the sensor lock, that + /// is one whose work item waits for the lock. + fn bio_capture_live(&self) -> bool { + crate::bio::capture_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) } fn key_bio_acl(&self, any: bool) -> Result { @@ -1583,7 +1626,8 @@ impl SepData { /// A touch-gated operation (see `key_sign_with_touch`). `CANCEL` ends /// the wait with `ECANCELED`, a signal to the caller (including its - /// death) with `EINTR`. + /// death) with `EINTR`, and an enrolment or a verify that `/dev/sep-bio` + /// starts meanwhile with `EBUSY`: the sensor goes to that prompt. fn key_touch_run( &self, blob: &[u8], @@ -1620,6 +1664,9 @@ impl SepData { if kernel::current!().signal_pending() { break Err(EINTR); } + if self.bio_capture_live() { + break Err(EBUSY); + } if !self.capture_begin() { break Err(EAGAIN); } @@ -1646,6 +1693,8 @@ impl SepData { } } Some(TouchOutcome::Failed(s)) if s == crate::ENROL_STATUS_LOCKOUT => break Err(EACCES), + // A capture given up for /dev/sep-bio ends as a failed one. + Some(TouchOutcome::Failed(_)) | None if self.bio_capture_live() => break Err(EBUSY), Some(TouchOutcome::Failed(_)) | None => break Err(EIO), } }; diff --git a/include/uapi/linux/apple-sep.h b/include/uapi/linux/apple-sep.h index 609b897b6a792b..d882c204c5b8f5 100644 --- a/include/uapi/linux/apple-sep.h +++ b/include/uapi/linux/apple-sep.h @@ -306,8 +306,9 @@ struct sep_bio_rearm { * install, or an access-control list not satisfied), EACCES when the touch * did not match (or Touch ID is locked out), ETIMEDOUT when no finger came, * ENODEV while the key store or Touch ID is not up, EOPNOTSUPP for a - * reserved policy, ECANCELED after SEP_KEY_CANCEL, EIO for any other - * enclave failure. + * reserved policy, ECANCELED after SEP_KEY_CANCEL, EBUSY when a Touch ID + * verify or enrolment on /dev/sep-bio wants the sensor during the wait (try + * again later), EIO for any other enclave failure. */ #define SEP_KEY_IFACE_VERSION 4 #define SEP_KEY_FEATURE_CANCEL 0x1 From a789b5ca16130b8e46998cb4f73311c6cf6270d6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:45:42 +1100 Subject: [PATCH 0505/1514] wifi: apple: centauri: keep the station counter length with its record Every reply to the statistics command overwrites stats_length, while station_stats_valid is only set by a station counter record of a supported length. A later reply carrying another record leaves the counters marked valid with a length that no longer describes them, and the debugfs and connection readers then iterate past station_stats. Record the length of the accepted counter record in its own field, set together with station_stats_valid, and iterate over that. Move the statistics reply handling into a helper so that it can be tested, and add a KUnit case for it (CONFIG_APPLE_CENTAURI_KUNIT_TEST). Signed-off-by: Ryan Murray --- drivers/net/wireless/apple/Kconfig | 11 +++ .../wireless/apple/centauri/centauri_wifi.c | 80 +++++++++++-------- .../apple/centauri/centauri_wifi_test.c | 52 ++++++++++++ 3 files changed, 110 insertions(+), 33 deletions(-) create mode 100644 drivers/net/wireless/apple/centauri/centauri_wifi_test.c diff --git a/drivers/net/wireless/apple/Kconfig b/drivers/net/wireless/apple/Kconfig index d9b13a9785de26..67bf179e874850 100644 --- a/drivers/net/wireless/apple/Kconfig +++ b/drivers/net/wireless/apple/Kconfig @@ -23,6 +23,17 @@ config APPLE_CENTAURI To build as a module, choose M; the module is apple_centauri. +config APPLE_CENTAURI_KUNIT_TEST + bool "KUnit tests for the N1 Centauri Wi-Fi reply parsing" if !KUNIT_ALL_TESTS + depends on APPLE_CENTAURI && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests that pass statistics replies to the J813 Wi-Fi reply + handler and check the recorded counter lengths. They need no N1 + hardware. + + If unsure, say N. + config APPLE_CENTAURI_T6050 tristate "Apple N1 Centauri T6050 firmware and IPC transport" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index de0d4d872932a0..5d255a18743232 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -160,6 +160,7 @@ struct centauri_wifi { u8 country[3]; bool country_valid; u8 station_stats[0x378]; + u16 station_stats_len; bool station_stats_valid; u8 rx_crypto_stats[64]; bool rx_crypto_stats_valid; @@ -549,6 +550,43 @@ static void drain_data_tx(struct centauri_wifi *wifi) netif_wake_queue(wifi->netdev); } +/* Record a reply to the statistics command 0xb0001. */ +static void record_stats_reply(struct centauri_wifi *wifi, const u8 *packet, + u16 size, u16 status) +{ + wifi->stats_reply_size = size; + wifi->stats_tag = size >= 28 ? get_unaligned_le16(packet + 24) : 0; + wifi->stats_length = size >= 28 ? get_unaligned_le16(packet + 26) : 0; + if (!status && wifi->stats_tag == 0xf928 && + (wifi->stats_length == 752 || wifi->stats_length == 888) && + size >= 28 + wifi->stats_length) { + /* Native firmware returns the older 752-byte counter record. */ + memset(wifi->station_stats, 0, sizeof(wifi->station_stats)); + memcpy(wifi->station_stats, packet + 28, wifi->stats_length); + /* A later reply can change stats_length; keep this record's own. */ + wifi->station_stats_len = wifi->stats_length; + wifi->station_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf921 && + wifi->stats_length == sizeof(wifi->rx_crypto_stats) && + size >= 28 + sizeof(wifi->rx_crypto_stats)) { + memcpy(wifi->rx_crypto_stats, packet + 28, sizeof(wifi->rx_crypto_stats)); + wifi->rx_crypto_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf91b && + wifi->stats_length == sizeof(wifi->dot11_mib_stats) && + size >= 28 + sizeof(wifi->dot11_mib_stats)) { + memcpy(wifi->dot11_mib_stats, packet + 28, sizeof(wifi->dot11_mib_stats)); + wifi->dot11_mib_stats_valid = true; + } + if (!status && wifi->stats_tag == 0xf920 && + wifi->stats_length == sizeof(wifi->tx_power_report) && + size >= 28 + sizeof(wifi->tx_power_report)) { + memcpy(wifi->tx_power_report, packet + 28, sizeof(wifi->tx_power_report)); + wifi->tx_power_report_valid = true; + } +} + static void drain_control(struct centauri_wifi *wifi, bool pm_command) { unsigned int ring; @@ -673,37 +711,8 @@ static void drain_control(struct centauri_wifi *wifi, bool pm_command) pos += 4 + length; } } - if (command == 0xb0001) { - wifi->stats_reply_size = size; - wifi->stats_tag = size >= 28 ? get_unaligned_le16(packet + 24) : 0; - wifi->stats_length = size >= 28 ? get_unaligned_le16(packet + 26) : 0; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf928 && - (wifi->stats_length == 752 || wifi->stats_length == 888) && - size >= 28 + wifi->stats_length) { - /* Native firmware returns the older 752-byte counter record. */ - memset(wifi->station_stats, 0, sizeof(wifi->station_stats)); - memcpy(wifi->station_stats, packet + 28, wifi->stats_length); - wifi->station_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf921 && - wifi->stats_length == sizeof(wifi->rx_crypto_stats) && - size >= 28 + sizeof(wifi->rx_crypto_stats)) { - memcpy(wifi->rx_crypto_stats, packet + 28, sizeof(wifi->rx_crypto_stats)); - wifi->rx_crypto_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf91b && - wifi->stats_length == sizeof(wifi->dot11_mib_stats) && - size >= 28 + sizeof(wifi->dot11_mib_stats)) { - memcpy(wifi->dot11_mib_stats, packet + 28, sizeof(wifi->dot11_mib_stats)); - wifi->dot11_mib_stats_valid = true; - } - if (command == 0xb0001 && !status && wifi->stats_tag == 0xf920 && - wifi->stats_length == sizeof(wifi->tx_power_report) && - size >= 28 + sizeof(wifi->tx_power_report)) { - memcpy(wifi->tx_power_report, packet + 28, sizeof(wifi->tx_power_report)); - wifi->tx_power_report_valid = true; - } + if (command == 0xb0001) + record_stats_reply(wifi, packet, size, status); if (command == 0xf0025) { wifi->pmk_seen = !status && size >= 60; wifi->pmk_matches = wifi->pmk_seen && @@ -1282,7 +1291,7 @@ static void connect_worker(struct work_struct *work) "connection counters: complete=%d rc=%d valid=%d length=%u\n", wifi->connect_event, probe_ret, wifi->station_stats_valid, wifi->stats_length); if (!probe_ret && wifi->station_stats_valid) - for (i = 0; i < wifi->stats_length; i += 4) { + for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); if (value) @@ -2276,6 +2285,7 @@ static int query_station_stats(struct centauri_wifi *wifi) put_unaligned_le16(363, payload + 9); put_unaligned_le16(9, payload + 11); wifi->station_stats_valid = false; + wifi->station_stats_len = 0; wifi->stats_reply_size = wifi->stats_tag = wifi->stats_length = 0; ret = wifi->configured ? command(wifi, 0xb0001, payload, sizeof(payload)) : -ENETDOWN; if (!ret) { @@ -2296,7 +2306,7 @@ static int station_stats_show(struct seq_file *seq, void *unused) seq_printf(seq, "rc=%d valid=%d size=%u tag=%#x length=%u\n", ret, wifi->station_stats_valid, wifi->stats_reply_size, wifi->stats_tag, wifi->stats_length); if (!ret && wifi->station_stats_valid) - for (i = 0; i < wifi->stats_length; i += 4) { + for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); if (value) @@ -2814,3 +2824,7 @@ void centauri_wifi_unregister(struct centauri *c) kfree(wifi); c->wifi = NULL; } + +#if IS_ENABLED(CONFIG_APPLE_CENTAURI_KUNIT_TEST) +#include "centauri_wifi_test.c" +#endif diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi_test.c b/drivers/net/wireless/apple/centauri/centauri_wifi_test.c new file mode 100644 index 00000000000000..9602e219a61e3e --- /dev/null +++ b/drivers/net/wireless/apple/centauri/centauri_wifi_test.c @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by centauri_wifi.c to exercise the statistics reply handler. */ +#include + +/* A reply to command 0xb0001 carrying one TLV of @length bytes. */ +static void centauri_stats_reply(struct centauri_wifi *wifi, u8 *packet, + u16 size, u16 tag, u16 length) +{ + memset(packet, 0, size); + put_unaligned_le16(tag, packet + 24); + put_unaligned_le16(length, packet + 26); + record_stats_reply(wifi, packet, size, 0); +} + +static void centauri_station_stats_len_test(struct kunit *test) +{ + struct centauri_wifi *wifi = kunit_kzalloc(test, sizeof(*wifi), GFP_KERNEL); + u8 *packet = kunit_kzalloc(test, BUFFER_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, wifi); + KUNIT_ASSERT_NOT_NULL(test, packet); + + centauri_stats_reply(wifi, packet, 28 + 752, 0xf928, 752); + KUNIT_ASSERT_TRUE(test, wifi->station_stats_valid); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 752); + + /* A later reply with another record leaves the counters as they were. */ + centauri_stats_reply(wifi, packet, 28, 0xf921, U16_MAX); + KUNIT_EXPECT_EQ(test, wifi->stats_length, U16_MAX); + KUNIT_EXPECT_TRUE(test, wifi->station_stats_valid); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 752); + KUNIT_EXPECT_LE(test, wifi->station_stats_len, sizeof(wifi->station_stats)); + + centauri_stats_reply(wifi, packet, 28 + 888, 0xf928, 888); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 888); + + /* An unsupported counter record length is not recorded. */ + centauri_stats_reply(wifi, packet, 28 + 900, 0xf928, 900); + KUNIT_EXPECT_EQ(test, wifi->station_stats_len, 888); +} + +static struct kunit_case centauri_wifi_cases[] = { + KUNIT_CASE(centauri_station_stats_len_test), + {} +}; + +static struct kunit_suite centauri_wifi_suite = { + .name = "apple-centauri-wifi", + .test_cases = centauri_wifi_cases, +}; + +kunit_test_suite(centauri_wifi_suite); From 39759136e3085ee0ed989d2728228f8085230333 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:45:41 +1100 Subject: [PATCH 0506/1514] soc: apple: t6050-aop: keep one ring buffer per endpoint Each AFK_GETBUF from the AOP2 firmware allocated a new device-managed coherent buffer and stored it in the endpoint's ring, replacing the one before. Those buffers are only released at unbind, which this driver does not allow, so a repeated GETBUF kept adding buffers. The stores of the buffer and its size were also not ordered against t6050_aop2_view(), which reads the rings from the resume path in another thread, so a reader could pair a new buffer with an old size. An endpoint now gets one buffer for as long as the firmware runs. A repeated GETBUF that fits in it is answered with the same IOVA; one with no size or a larger size than the buffer is refused and logged (ratelimited), without an answer. The buffer is published with smp_store_release() after its size and IOVA, and t6050_aop2_view() reads it with smp_load_acquire(), so a reader that finds the buffer also finds its size. As the buffer and its size never change once set, the readers need no lock for them. The ring offsets and sizes are still plain stores; t6050_aop2_view() checks them against the buffer's fixed size on every read, so a reader never leaves the buffer. Add KUnit tests (CONFIG_APPLE_T6050_AOP_KUNIT_TEST, suite apple_t6050_aop) for the GETBUF decision and the ring view's bounds. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 11 +++ drivers/soc/apple/t6050-aop-test.c | 91 +++++++++++++++++++++++++ drivers/soc/apple/t6050-aop.c | 54 ++++++++++++--- drivers/soc/apple/t6050-aop.kunitconfig | 10 +++ 4 files changed, 157 insertions(+), 9 deletions(-) create mode 100644 drivers/soc/apple/t6050-aop-test.c create mode 100644 drivers/soc/apple/t6050-aop.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..ab4986a03f0d63 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -128,6 +128,17 @@ config APPLE_SOC_SLEEP_KUNIT_TEST If unsure, say N. +config APPLE_T6050_AOP_KUNIT_TEST + bool "KUnit tests for the T6050 AOP2 driver" if !KUNIT_ALL_TESTS + depends on APPLE_SOC_SLEEP && KUNIT=y + default KUNIT_ALL_TESTS + help + Checks that each AOP2 endpoint gets one ring buffer for as long as + its firmware runs, and that a ring is read only inside it. The tests + touch no hardware. + + If unsure, say N. + config APPLE_RTKIT tristate "Apple RTKit co-processor IPC protocol" depends on APPLE_MAILBOX diff --git a/drivers/soc/apple/t6050-aop-test.c b/drivers/soc/apple/t6050-aop-test.c new file mode 100644 index 00000000000000..00f1c0082c4946 --- /dev/null +++ b/drivers/soc/apple/t6050-aop-test.c @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by t6050-aop.c: an endpoint's buffer is the firmware's first GETBUF's, for as long as + * the firmware runs; a later GETBUF that fits in it gets it again. + */ +#include + +static void t6050_aop_test_first_getbuf_allocates(struct kunit *test) +{ + struct t6050_aop_ring r = {}; + + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 0x4000), 0); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); +} + +static void t6050_aop_test_empty_getbuf_refused(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = {}; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0), 0); + r.buf = mem; + r.size = sizeof(mem); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0), 0); +} + +static void t6050_aop_test_repeat_getbuf_reuses(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + int i; + + for (i = 0; i < 64; i++) + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, sizeof(mem)), 1); +} + +static void t6050_aop_test_smaller_getbuf_reuses(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, sizeof(mem) / 2), 1); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 1), 1); +} + +static void t6050_aop_test_larger_getbuf_refused(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, sizeof(mem) + 1), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, sizeof(mem) * 2), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); +} + +static void t6050_aop_test_view_inside_buffer(struct kunit *test) +{ + static __le32 mem[0x400 / 4]; + struct t6050_aop_ring r = {}; + struct t6050_aop_view v; + u32 bufsz = 2 * AFK_QE_SLOT; + u32 size = bufsz + 3 * 0x40; + + mem[0] = cpu_to_le32(bufsz); + /* No buffer yet. */ + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0, size, true, &v), -EINVAL); + r.buf = mem; + r.size = sizeof(mem); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0, size, true, &v), 0); + KUNIT_EXPECT_PTR_EQ(test, (void *)v.hdr, (void *)mem); + /* A ring that does not fit the buffer. */ + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0x400 - 0x40, size, true, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, 0x440, 0x40, true, &v), -EINVAL); +} + +static struct kunit_case t6050_aop_test_cases[] = { + KUNIT_CASE(t6050_aop_test_first_getbuf_allocates), + KUNIT_CASE(t6050_aop_test_empty_getbuf_refused), + KUNIT_CASE(t6050_aop_test_repeat_getbuf_reuses), + KUNIT_CASE(t6050_aop_test_smaller_getbuf_reuses), + KUNIT_CASE(t6050_aop_test_larger_getbuf_refused), + KUNIT_CASE(t6050_aop_test_view_inside_buffer), + {} +}; + +static struct kunit_suite t6050_aop_test_suite = { + .name = "apple_t6050_aop", + .test_cases = t6050_aop_test_cases, +}; + +kunit_test_suite(t6050_aop_test_suite); diff --git a/drivers/soc/apple/t6050-aop.c b/drivers/soc/apple/t6050-aop.c index d7115b8c2c2f90..92d583ae337025 100644 --- a/drivers/soc/apple/t6050-aop.c +++ b/drivers/soc/apple/t6050-aop.c @@ -77,8 +77,10 @@ #define AOP_EP_COUNT (AOP_EP_LAST - AOP_EP_FIRST + 1) struct t6050_aop_ring { + /* Set once, by the firmware's first GETBUF; published after its size and IOVA */ void *buf; size_t size; + dma_addr_t iova; u32 tx_off, tx_size; u32 rx_off, rx_size; bool tx_ready, rx_ready; @@ -139,21 +141,48 @@ static void t6050_aop_send(struct t6050_aop *aop, u8 ep, u64 msg) dev_err(aop->dev, "endpoint %#x: send %#llx: %d\n", ep, msg, ret); } +/* + * What a GETBUF gets: 0 a new buffer, 1 the endpoint's own again, as it fits in it, or -EINVAL for + * no size or more than the endpoint's buffer holds. An endpoint has one buffer for as long as the + * firmware runs: its rings are read from it at a sleep and a wake, by other threads. + */ +static int t6050_aop_getbuf_check(const struct t6050_aop_ring *r, size_t size) +{ + if (!size) + return -EINVAL; + if (!r->buf) + return 0; + + return size <= r->size ? 1 : -EINVAL; +} + static void t6050_aop_getbuf(struct t6050_aop *aop, u8 ep, u64 msg) { + struct t6050_aop_ring *r = &aop->ring[ep - AOP_EP_FIRST]; size_t size = (size_t)FIELD_GET(AFK_GETBUF_SIZE, msg) << AFK_BLOCK_SHIFT; - dma_addr_t iova; void *buf; + int ret; - buf = dmam_alloc_coherent(aop->dev, size, &iova, GFP_KERNEL); - if (!buf) { - dev_err(aop->dev, "endpoint %#x: no %#zx byte buffer\n", ep, size); + /* Only this endpoint's messages, in order, change its buffer. */ + ret = t6050_aop_getbuf_check(r, size); + if (ret < 0) { + dev_err_ratelimited(aop->dev, "endpoint %#x: no buffer for a %#zx byte GETBUF (has %#zx)\n", + ep, size, r->buf ? r->size : 0); return; } - aop->ring[ep - AOP_EP_FIRST].buf = buf; - aop->ring[ep - AOP_EP_FIRST].size = size; + if (!ret) { + buf = dmam_alloc_coherent(aop->dev, size, &r->iova, GFP_KERNEL); + if (!buf) { + dev_err_ratelimited(aop->dev, "endpoint %#x: no %#zx byte buffer\n", + ep, size); + return; + } + r->size = size; + /* A reader that finds the buffer finds its size. */ + smp_store_release(&r->buf, buf); + } t6050_aop_send(aop, ep, FIELD_PREP(AFK_TYPE, AFK_GETBUF_ACK) | - FIELD_PREP(AFK_GETBUF_IOVA, iova)); + FIELD_PREP(AFK_GETBUF_IOVA, r->iova)); } static int t6050_aop2_take(struct t6050_aop *aop, u8 ep, u32 old, u32 new); @@ -221,9 +250,12 @@ static const struct apple_rtkit_ops t6050_aop2_rtkit_ops = { static int t6050_aop2_view(struct t6050_aop_ring *r, u32 off, u32 size, bool ready, struct t6050_aop_view *v) { - if (!ready || !r->buf || size < sizeof(__le32) || off > r->size || size > r->size - off) + /* Pairs with t6050_aop_getbuf(): a buffer found here comes with its size. */ + u8 *buf = smp_load_acquire(&r->buf); + + if (!ready || !buf || size < sizeof(__le32) || off > r->size || size > r->size - off) return -EINVAL; - v->hdr = (u8 *)r->buf + off; + v->hdr = buf + off; v->bufsz = le32_to_cpu(READ_ONCE(*(__le32 *)v->hdr)); if (v->bufsz >= size || (size - v->bufsz) % 3 || v->bufsz < 2 * AFK_QE_SLOT || v->bufsz > AFK_RING_MAX) @@ -746,3 +778,7 @@ static struct platform_driver t6050_aop_driver = { .probe = t6050_aop_probe, }; builtin_platform_driver(t6050_aop_driver); + +#if IS_ENABLED(CONFIG_APPLE_T6050_AOP_KUNIT_TEST) +#include "t6050-aop-test.c" +#endif diff --git a/drivers/soc/apple/t6050-aop.kunitconfig b/drivers/soc/apple/t6050-aop.kunitconfig new file mode 100644 index 00000000000000..e4da56c59ad8ef --- /dev/null +++ b/drivers/soc/apple/t6050-aop.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_COMPILE_TEST=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_HOTPLUG_CPU=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_SOC_SLEEP=y +CONFIG_APPLE_T6050_AOP_KUNIT_TEST=y From 4a5ebf1e65c22dc4609c1a8c3bc9750fd8b9bdc3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:32:09 +1100 Subject: [PATCH 0507/1514] wifi: brcmfmac: pcie: keep console reads inside the TCM and the console buffer The firmware console's descriptor address, buffer address, buffer size and write index all come from dongle memory. None of them was checked against the TCM mapping, so console reads could go past the end of the BAR. A write index at or past the buffer size also kept brcmf_pcie_bus_console_read() in its loop for good: the read index wraps at the buffer size and never meets the write index. Record the length of the TCM mapping. When the console is set up, accept its descriptor and buffer only when both lie within the mapping, otherwise leave the console disabled, as when the firmware reports none, and start reading it at the beginning of the buffer. The reader stops when the firmware's write index is outside the buffer. Add a KUnit case for the range check. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/Kconfig | 5 +- .../broadcom/brcm80211/brcmfmac/Makefile | 2 +- .../broadcom/brcm80211/brcmfmac/pcie.c | 18 +++++++ .../broadcom/brcm80211/brcmfmac/pcie.h | 8 ++++ .../brcm80211/brcmfmac/pcie_tcm_test.c | 48 +++++++++++++++++++ 5 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig index d158f95bb1800b..0556460739c8ad 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Kconfig @@ -12,13 +12,14 @@ config BRCMFMAC_PROTO_BCDC bool config BRCMFMAC_KUNIT_TEST - tristate "KUnit tests for brcmfmac scan timeout" if !KUNIT_ALL_TESTS + tristate "KUnit tests for brcmfmac scan timeout and PCIe TCM bounds" if !KUNIT_ALL_TESTS depends on KUNIT && BRCMFMAC default KUNIT_ALL_TESTS help Test channel-based scan deadline calculation without Wi-Fi hardware. Covers passive and active scan budgets, all-band scans, minimum - deadlines and saturation for oversized channel counts. + deadlines and saturation for oversized channel counts. Also test + the bounds check for firmware-supplied offsets into the PCIe TCM. These tests run under KUnit and are not needed for normal operation. config BRCMFMAC_PROTO_MSGBUF diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile index 8e9556579508a9..a77be645839e7d 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/Makefile @@ -10,7 +10,7 @@ ccflags-y += \ -I $(src)/../include obj-$(CONFIG_BRCMFMAC) += brcmfmac.o -obj-$(CONFIG_BRCMFMAC_KUNIT_TEST) += scan_timeout_test.o +obj-$(CONFIG_BRCMFMAC_KUNIT_TEST) += scan_timeout_test.o pcie_tcm_test.o brcmfmac-objs += \ cfg80211.o \ chip.o \ diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 2bfee245f43312..d86b7df0d64d11 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -429,6 +429,7 @@ struct brcmf_pciedev_info { const struct brcmf_pcie_reginfo *reginfo; void __iomem *regs; void __iomem *tcm; + size_t tcm_size; u32 fw_size; bool skip_reset_vector; struct brcmf_chip *ci; @@ -1133,11 +1134,25 @@ static void brcmf_pcie_bus_console_init(struct brcmf_pciedev_info *devinfo) console = &shared->console; addr = shared->tcm_base_address + BRCMF_SHARED_CONSOLE_ADDR_OFFSET; console->base_addr = brcmf_pcie_read_tcm32(devinfo, addr); + console->bufsize = 0; + console->read_idx = 0; + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr, + BRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) { + console->base_addr = 0; + return; + } addr = console->base_addr + BRCMF_CONSOLE_BUFADDR_OFFSET; console->buf_addr = brcmf_pcie_read_tcm32(devinfo, addr); addr = console->base_addr + BRCMF_CONSOLE_BUFSIZE_OFFSET; console->bufsize = brcmf_pcie_read_tcm32(devinfo, addr); + if (!console->bufsize || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr, + console->bufsize)) { + console->base_addr = 0; + console->bufsize = 0; + return; + } addr = console->base_addr + BRCMF_CONSOLE_WRITEIDX_OFFSET; console->scan_idx = brcmf_pcie_read_tcm32(devinfo, addr); console->scan_len = 0; @@ -1170,6 +1185,8 @@ static void brcmf_pcie_bus_console_read(struct brcmf_pciedev_info *devinfo, return; addr = console->base_addr + BRCMF_CONSOLE_WRITEIDX_OFFSET; newidx = brcmf_pcie_read_tcm32(devinfo, addr); + if (newidx >= console->bufsize || console->read_idx >= console->bufsize) + return; while (newidx != console->read_idx) { addr = console->buf_addr + console->read_idx; ch = brcmf_pcie_read_tcm8(devinfo, addr); @@ -2392,6 +2409,7 @@ static int brcmf_pcie_get_resource(struct brcmf_pciedev_info *devinfo) devinfo->regs = ioremap(bar0_addr, BRCMF_PCIE_REG_MAP_SIZE); devinfo->tcm = ioremap(bar1_addr, bar1_size); + devinfo->tcm_size = bar1_size; if (!devinfo->regs || !devinfo->tcm) { brcmf_err(bus, "ioremap() failed (%p,%p)\n", devinfo->regs, diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h index 8e6c227e8315c8..172175d7129a01 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.h @@ -5,10 +5,18 @@ #ifndef BRCMFMAC_PCIE_H #define BRCMFMAC_PCIE_H +#include struct brcmf_pciedev { struct brcmf_bus *bus; struct brcmf_pciedev_info *devinfo; }; +/* Whether @len bytes at @offset lie within a TCM mapping of @tcm_size bytes. */ +static inline bool brcmf_pcie_tcm_range_valid(size_t tcm_size, u32 offset, + u32 len) +{ + return len <= tcm_size && offset <= tcm_size - len; +} + #endif /* BRCMFMAC_PCIE_H */ diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c new file mode 100644 index 00000000000000..877327f20809b2 --- /dev/null +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie_tcm_test.c @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: ISC +#include +#include + +#include "pcie.h" + +static void brcmf_pcie_tcm_range(struct kunit *test) +{ + static const struct { + size_t tcm_size; + u32 offset; + u32 len; + bool valid; + } cases[] = { + { SZ_4M, 0, 8, true }, + { SZ_4M, SZ_4M - 8, 8, true }, + { SZ_4M, SZ_4M - 7, 8, false }, + { SZ_4M, SZ_4M, 8, false }, + { SZ_4M, SZ_4M, 0, true }, + { SZ_4M, U32_MAX - 3, 8, false }, + { SZ_4M, U32_MAX, 8, false }, + { 4, 0, 8, false }, + { 0, 0, 1, false }, + }; + int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) + KUNIT_EXPECT_EQ_MSG(test, + brcmf_pcie_tcm_range_valid(cases[i].tcm_size, + cases[i].offset, + cases[i].len), + cases[i].valid, "case %d", i); +} + +static struct kunit_case brcmf_pcie_tcm_cases[] = { + KUNIT_CASE(brcmf_pcie_tcm_range), + {} +}; + +static struct kunit_suite brcmf_pcie_tcm_suite = { + .name = "brcmfmac-pcie-tcm", + .test_cases = brcmf_pcie_tcm_cases, +}; + +kunit_test_suite(brcmf_pcie_tcm_suite); + +MODULE_DESCRIPTION("KUnit tests for brcmfmac PCIe TCM bounds"); +MODULE_LICENSE("Dual BSD/GPL"); From 69e4314729a7e11689d59904ba0bddd428e64662 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:35:32 +1100 Subject: [PATCH 0508/1514] wifi: brcmfmac: pcie: check the shared RAM addresses against the TCM The shared RAM block and the addresses it holds (the two mailbox words, the ring information, the ring memory and, when the firmware keeps the ring indices in its own memory, the four index arrays) are offsets into the TCM mapping that come from dongle memory. The driver reads and writes through all of them, but only checked that the shared RAM block starts inside the dongle's RAM. Check each against the length of the TCM mapping when it is read, before it is used, and fail the probe with -EINVAL when one is outside. The index arrays are checked for one index per common ring and flowring. Add tools/asahi/brcmf-shared-tcm-tests.py, which runs the driver's shared RAM, ring and console setup against a fake TCM that asserts on every access outside it; one mutation per check drops it and fails a control. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/pcie.c | 43 +++ tools/asahi/brcmf-shared-tcm-tests.py | 294 ++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 3 files changed, 341 insertions(+) create mode 100755 tools/asahi/brcmf-shared-tcm-tests.py diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index d86b7df0d64d11..97fb98d33d2723 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -307,6 +307,8 @@ static const struct brcmf_firmware_mapping brcmf_pcie_fwnames[] = { #define BRCMF_SHARED_FLAGS3_OFFSET 108 #define BRCMF_SHARED_HOST_CAP2_OFFSET 112 #define BRCMF_SHARED_HOST_CAP3_OFFSET 116 +/* The end of the last shared RAM field the driver reads or writes */ +#define BRCMF_SHARED_SIZE (BRCMF_SHARED_HOST_CAP2_OFFSET + 4) #define BRCMF_RING_H2D_RING_COUNT_OFFSET 0 #define BRCMF_RING_D2H_RING_COUNT_OFFSET 1 @@ -1599,6 +1601,8 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) u32 h2d_w_idx_ptr; u32 h2d_r_idx_ptr; u32 ring_mem_ptr; + u32 h2d_idx_len; + u32 d2h_idx_len; u32 i; u64 address; u32 bufsz; @@ -1624,6 +1628,13 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) brcmf_err(bus, "invalid max_flowrings(%d)\n", max_flowrings); return -EIO; } + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + le32_to_cpu(ringinfo.ringmem), + BRCMF_NROF_COMMON_MSGRINGS * + BRCMF_RING_MEM_SZ)) { + brcmf_err(bus, "ring memory outside the TCM\n"); + return -EINVAL; + } if (devinfo->dma_idx_sz != 0) { bufsz = (max_submissionrings + max_completionrings) * @@ -1641,6 +1652,21 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) h2d_w_idx_ptr = le32_to_cpu(ringinfo.h2d_w_idx_ptr); h2d_r_idx_ptr = le32_to_cpu(ringinfo.h2d_r_idx_ptr); idx_offset = sizeof(u32); + /* One index per common ring and flowring, each way */ + h2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings) * + idx_offset; + d2h_idx_len = BRCMF_NROF_D2H_COMMON_MSGRINGS * idx_offset; + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + h2d_w_idx_ptr, h2d_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + h2d_r_idx_ptr, h2d_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + d2h_w_idx_ptr, d2h_idx_len) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + d2h_r_idx_ptr, d2h_idx_len)) { + brcmf_err(bus, "ring indices outside the TCM\n"); + return -EINVAL; + } devinfo->write_ptr = brcmf_pcie_write_tcm16; devinfo->read_ptr = brcmf_pcie_read_tcm16; brcmf_dbg(PCIE, "Using TCM indices\n"); @@ -2031,6 +2057,12 @@ brcmf_pcie_init_share_ram_info(struct brcmf_pciedev_info *devinfo, u32 addr; shared = &devinfo->shared; + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, sharedram_addr, + BRCMF_SHARED_SIZE)) { + brcmf_err(bus, "shared RAM at 0x%08x is outside the TCM\n", + sharedram_addr); + return -EINVAL; + } shared->tcm_base_address = sharedram_addr; shared->flags = brcmf_pcie_read_tcm32(devinfo, sharedram_addr + @@ -2070,6 +2102,17 @@ brcmf_pcie_init_share_ram_info(struct brcmf_pciedev_info *devinfo, addr = sharedram_addr + BRCMF_SHARED_RING_INFO_ADDR_OFFSET; shared->ring_info_addr = brcmf_pcie_read_tcm32(devinfo, addr); + if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->htod_mb_data_addr, 4) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->dtoh_mb_data_addr, 4) || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, + shared->ring_info_addr, + sizeof(struct brcmf_pcie_dhi_ringinfo))) { + brcmf_err(bus, "shared RAM addresses outside the TCM\n"); + return -EINVAL; + } + brcmf_dbg(PCIE, "max rx buf post %d, rx dataoffset %d\n", shared->max_rxbufpost, shared->rx_dataoffset); diff --git a/tools/asahi/brcmf-shared-tcm-tests.py b/tools/asahi/brcmf-shared-tcm-tests.py new file mode 100755 index 00000000000000..3277d64ac1c0b3 --- /dev/null +++ b/tools/asahi/brcmf-shared-tcm-tests.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the production brcmfmac PCIe shared RAM, ring and console setup against a fake TCM. + +Every TCM access of the fake asserts that it lies inside the mapping, so a firmware-supplied +address the driver does not check makes a control fail. Each --mutation drops one check. +""" +import argparse +import json +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = ROOT / 'drivers/net/wireless/broadcom/brcm80211/brcmfmac' + + +def function(source, name): + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32)\s+' + name + + r'\([^;]*?\)\s*\{', source, re.M) + if not match: + raise ValueError('Missing function ' + name) + end = source.index('{', match.start()) + 1 + depth = 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def struct(source, name): + match = re.search(r'^struct ' + name + r' \{.*?^\};\n', source, re.M | re.S) + if not match: + raise ValueError('Missing struct ' + name) + return match.group(0) + + +def define(source, name): + match = re.search(r'^#define\s+' + name + r'\s+(.*)$', source, re.M) + if not match: + raise ValueError('Missing define ' + name) + return '#define %s %s\n' % (name, match.group(1)) + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +typedef uint64_t u64; typedef uint32_t u32; typedef uint16_t u16; typedef uint8_t u8; +typedef uint32_t __le32; typedef uint16_t __le16; typedef uint64_t dma_addr_t; +#define le32_to_cpu(x) (x) +#define le16_to_cpu(x) (x) +#define cpu_to_le32(x) (x) +#define GFP_KERNEL 0 +#define brcmf_dbg(...) ((void)0) +#define pr_debug(...) ((void)0) +#define BRCMF_FWCON_ON() 1 +#define kzalloc_objs(obj, n) calloc((n), sizeof(obj)) +static unsigned errs; +static char last_err[256]; +static void brcmf_err(void *bus, const char *fmt, ...) +{ va_list ap; (void)bus; va_start(ap, fmt); vsnprintf(last_err, sizeof(last_err), fmt, ap); va_end(ap); errs++; } +static void __brcmf_err(void *bus, const char *func, const char *fmt, ...) { (void)bus; (void)func; (void)fmt; } +/* DEFINES */ +/* STRUCTS */ +struct device { int unused; }; +struct pci_dev { struct device dev; }; +struct brcmf_bus { int unused; }; +static struct brcmf_bus bus; +static struct brcmf_bus *dev_get_drvdata(struct device *dev) { (void)dev; return &bus; } +struct brcmf_commonring { int unused; }; +struct brcmf_pciedev_info; +struct brcmf_pcie_ringbuf { struct brcmf_commonring commonring; struct brcmf_pciedev_info *devinfo; + u32 w_idx_addr, r_idx_addr; u16 id; }; +struct brcmf_pcie_console { u32 base_addr, buf_addr, bufsize, read_idx, log_idx; + u8 log_str[256]; u32 scan_idx; u8 scan_len; }; +struct brcmf_pcie_shared_info { u32 tcm_base_address, flags; struct brcmf_pcie_ringbuf *commonrings[5]; + struct brcmf_pcie_ringbuf *flowrings; u16 max_rxbufpost, max_flowrings, max_submissionrings, + max_completionrings; u32 rx_dataoffset, htod_mb_data_addr, dtoh_mb_data_addr, ring_info_addr; + struct brcmf_pcie_console console; u8 version; bool mb_via_ctl; u32 flags2, flags3; }; +struct brcmf_pciedev_info { struct pci_dev *pdev; u8 *tcm; size_t tcm_size; struct brcmf_pcie_shared_info shared; + u8 dma_idx_sz; void *idxbuf; u32 idxbuf_sz; dma_addr_t idxbuf_dmahandle; + u16 (*read_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset); + void (*write_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset, u16 value); }; + +/* Fake TCM: every access must lie inside the mapping. */ +#define TCM_SIZE 0x8000 +static u8 tcm[TCM_SIZE]; +static unsigned long reads; +static void in_tcm(struct brcmf_pciedev_info *d, u32 a, u32 n) +{ assert(d->tcm_size == TCM_SIZE); assert((u64)a + n <= TCM_SIZE); assert(++reads < 1000000); } +static u32 brcmf_pcie_read_tcm32(struct brcmf_pciedev_info *d, u32 a) { u32 v; in_tcm(d, a, 4); memcpy(&v, tcm + a, 4); return v; } +static u16 brcmf_pcie_read_tcm16(struct brcmf_pciedev_info *d, u32 a) { u16 v; in_tcm(d, a, 2); memcpy(&v, tcm + a, 2); return v; } +static u8 brcmf_pcie_read_tcm8(struct brcmf_pciedev_info *d, u32 a) { in_tcm(d, a, 1); return tcm[a]; } +static void brcmf_pcie_write_tcm32(struct brcmf_pciedev_info *d, u32 a, u32 v) { in_tcm(d, a, 4); memcpy(tcm + a, &v, 4); } +static void brcmf_pcie_write_tcm16(struct brcmf_pciedev_info *d, u32 a, u16 v) { in_tcm(d, a, 2); memcpy(tcm + a, &v, 2); } +static u16 brcmf_pcie_read_idx(struct brcmf_pciedev_info *d, u32 a) { (void)d; (void)a; return 0; } +static void brcmf_pcie_write_idx(struct brcmf_pciedev_info *d, u32 a, u16 v) { (void)d; (void)a; (void)v; } +static struct brcmf_pciedev_info devinfo; +static void memcpy_fromio(void *dst, const u8 *src, size_t n) +{ assert(src >= tcm); in_tcm(&devinfo, (u32)(src - tcm), (u32)n); memcpy(dst, src, n); } +static void memcpy_toio(u8 *dst, const void *src, size_t n) +{ assert(dst >= tcm); in_tcm(&devinfo, (u32)(dst - tcm), (u32)n); memcpy(dst, src, n); } +static void *dma_alloc_coherent(struct device *dev, size_t n, dma_addr_t *h, int gfp) +{ (void)dev; (void)gfp; *h = 0x10000000; return calloc(1, n); } +/* The real one reads the ring's size and writes its host address in its BRCMF_RING_MEM_SZ slot. */ +static struct brcmf_pcie_ringbuf rings_pool[5]; +static struct brcmf_pcie_ringbuf *brcmf_pcie_alloc_dma_and_ring(struct brcmf_pciedev_info *d, u32 id, u32 mem) +{ brcmf_pcie_read_tcm16(d, mem + BRCMF_RING_MAX_ITEM_OFFSET); brcmf_pcie_write_tcm32(d, mem + BRCMF_RING_MEM_BASE_ADDR_OFFSET + 4, 0); + return &rings_pool[id]; } +static void brcmf_pcie_release_ringbuffers(struct brcmf_pciedev_info *d) { (void)d; } +static void brcmf_pcie_ring_mb_ring_bell(void) {} +static void brcmf_pcie_ring_mb_update_rptr(void) {} +static void brcmf_pcie_ring_mb_update_wptr(void) {} +static void brcmf_pcie_ring_mb_write_rptr(void) {} +static void brcmf_pcie_ring_mb_write_wptr(void) {} +static void brcmf_commonring_register_cb(struct brcmf_commonring *c, void (*a)(void), void (*b)(void), + void (*e)(void), void (*f)(void), void (*g)(void), void *r) { (void)c; (void)a; (void)b; (void)e; (void)f; (void)g; (void)r; } +''' + +MAIN = r''' +#define SHARED 0x100 +#define CONS 0x200 +#define BUF 0x400 +#define RINGINFO 0x600 +#define RINGMEM 0x700 +#define IDX 0x800 +static struct pci_dev pdev; +static void put32(u32 a, u32 v) { memcpy(tcm + a, &v, 4); } +static void put16(u32 a, u16 v) { memcpy(tcm + a, &v, 2); } +/* A version 6 firmware with TCM ring indices, a console and two flowrings. */ +static void reset(void) +{ + free(devinfo.shared.flowrings); free(devinfo.idxbuf); + memset(tcm, 0, sizeof(tcm)); memset(&devinfo, 0, sizeof(devinfo)); memset(rings_pool, 0, sizeof(rings_pool)); + devinfo.pdev = &pdev; devinfo.tcm = tcm; devinfo.tcm_size = TCM_SIZE; errs = 0; reads = 0; + put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6); + put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, CONS); + put32(SHARED + BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET, 0xa00); + put32(SHARED + BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET, 0xa04); + put32(SHARED + BRCMF_SHARED_RING_INFO_ADDR_OFFSET, RINGINFO); + put32(CONS + BRCMF_CONSOLE_BUFADDR_OFFSET, BUF); put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 64); + put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 3); memcpy(tcm + BUF, "ok\n", 3); + struct brcmf_pcie_dhi_ringinfo *ri = (void *)(tcm + RINGINFO); + ri->ringmem = RINGMEM; ri->h2d_w_idx_ptr = IDX; ri->h2d_r_idx_ptr = IDX + 0x40; + ri->d2h_w_idx_ptr = IDX + 0x80; ri->d2h_r_idx_ptr = IDX + 0xc0; + ri->max_flowrings = 2; ri->max_submissionrings = 4; ri->max_completionrings = 3; +} +static int init(void) { return brcmf_pcie_init_share_ram_info(&devinfo, SHARED); } +static struct brcmf_pcie_dhi_ringinfo *ringinfo(void) { return (void *)(tcm + RINGINFO); } +/* Set up the rings, then touch every ring index as the data path does. */ +static int rings(void) +{ + int ret = brcmf_pcie_init_ringbuffers(&devinfo); + if (ret) + return ret; + for (int i = 0; i < 5; i++) { + devinfo.read_ptr(&devinfo, devinfo.shared.commonrings[i]->w_idx_addr); + devinfo.read_ptr(&devinfo, devinfo.shared.commonrings[i]->r_idx_addr); + } + for (int i = 0; i < devinfo.shared.max_flowrings; i++) { + devinfo.read_ptr(&devinfo, devinfo.shared.flowrings[i].w_idx_addr); + devinfo.read_ptr(&devinfo, devinfo.shared.flowrings[i].r_idx_addr); + } + return 0; +} +int main(void) +{ + unsigned cases = 0; + /* A well-formed firmware sets up and its console is read. */ + reset(); assert(!init() && devinfo.shared.console.bufsize == 64 && devinfo.shared.console.read_idx == 3); + assert(!rings() && !errs); cases++; + /* Shared RAM whose fields run past the TCM fails setup. */ + reset(); put32(TCM_SIZE - 8 + BRCMF_SHARED_FLAGS_OFFSET, 6); + assert(brcmf_pcie_init_share_ram_info(&devinfo, TCM_SIZE - 8) == -EINVAL); cases++; + /* Mailbox and ring info addresses outside the TCM fail setup. */ + reset(); put32(SHARED + BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET, TCM_SIZE - 2); assert(init() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET, 0xfffffffe); assert(init() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_RING_INFO_ADDR_OFFSET, TCM_SIZE - 8); assert(init() == -EINVAL); cases++; + /* So does ring memory or a ring index array outside the TCM. */ + reset(); assert(!init()); ringinfo()->ringmem = TCM_SIZE - 0x20; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->h2d_w_idx_ptr = TCM_SIZE - 8; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->h2d_r_idx_ptr = 0xfffffffc; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->d2h_w_idx_ptr = TCM_SIZE - 4; assert(rings() == -EINVAL); cases++; + reset(); assert(!init()); ringinfo()->d2h_r_idx_ptr = TCM_SIZE; assert(rings() == -EINVAL); cases++; + /* The flowring indices count against the TCM too. */ + reset(); assert(!init()); ringinfo()->h2d_w_idx_ptr = TCM_SIZE - 4 * 4; ringinfo()->max_flowrings = 3; + assert(rings() == -EINVAL); cases++; + /* A console descriptor or buffer outside the TCM leaves the console off; setup goes on. */ + reset(); put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, TCM_SIZE - 4); + assert(!init() && !devinfo.shared.console.base_addr); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_BUFADDR_OFFSET, TCM_SIZE - 16); + assert(!init() && !devinfo.shared.console.base_addr && !devinfo.shared.console.bufsize); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 0xffffffff); + assert(!init() && !devinfo.shared.console.base_addr); cases++; + /* A write index at or past the buffer size is not followed. */ + reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 64); assert(!init() && devinfo.shared.console.read_idx == 0); cases++; + reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 0x10000); assert(!init()); cases++; + /* A new firmware with a smaller console starts reading it from the beginning. */ + reset(); assert(!init()); devinfo.shared.console.read_idx = 60; put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 16); + put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 3); assert(!init() && devinfo.shared.console.read_idx == 3); cases++; + reset(); + printf("%u shared RAM bounds controls passed\n", cases); + return 0; +} +''' + +MUTATIONS = { + 'shared': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, sharedram_addr,\n' + '\t\t\t\t\tBRCMF_SHARED_SIZE)) {', '\tif (false) {'), + 'htod-mb': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->htod_mb_data_addr, 4) ||', + '\tif (false ||'), + 'dtoh-mb': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->dtoh_mb_data_addr, 4) ||', + '\t false ||'), + 'ring-info': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tshared->ring_info_addr,\n' + '\t\t\t\t\tsizeof(struct brcmf_pcie_dhi_ringinfo))) {', '\t false) {'), + 'ring-mem': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tle32_to_cpu(ringinfo.ringmem),', + '\tif (0 && !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\tle32_to_cpu(ringinfo.ringmem),'), + 'ring-idx': ('\t\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\t\th2d_w_idx_ptr, h2d_idx_len) ||', + '\t\tif (0 && !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\t\th2d_w_idx_ptr, h2d_idx_len) ||'), + 'flowring-idx': ('\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings) *', + '\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS) *'), + 'console-desc': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' + '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\tif (false) {'), + 'console-buf': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr,\n' + '\t\t\t\t\tconsole->bufsize)) {', '\t false) {'), + 'console-widx': ('\tif (newidx >= console->bufsize || console->read_idx >= console->bufsize)\n\t\treturn;\n', ''), + 'console-reinit': ('\tconsole->bufsize = 0;\n\tconsole->read_idx = 0;\n', '\tconsole->bufsize = 0;\n'), +} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path) + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + pcie = (DRIVER / 'pcie.c').read_text() + defines = ''.join(define(pcie, n) for n in ( + 'BRCMF_PCIE_SHARED_VERSION_7', 'BRCMF_PCIE_MIN_SHARED_VERSION', 'BRCMF_PCIE_MAX_SHARED_VERSION', 'BRCMF_PCIE_SHARED_VERSION_MASK', + 'BRCMF_PCIE_SHARED_DMA_INDEX', 'BRCMF_PCIE_SHARED_DMA_2B_IDX', 'BRCMF_PCIE_SHARED_USE_MAILBOX', + 'BRCMF_PCIE_SHARED_HOSTRDY_DB1', 'BRCMF_PCIE_SHARED_DAR', 'BRCMF_HOSTCAP_H2D_ENABLE_HOSTRDY', + 'BRCMF_HOSTCAP_H2D_DAR', 'BRCMF_HOSTCAP_DS_NO_OOB_DW', 'BRCMF_DEF_MAX_RXBUFPOST', + 'BRCMF_SHARED_FLAGS_OFFSET', 'BRCMF_SHARED_MAX_RXBUFPOST_OFFSET', 'BRCMF_SHARED_RX_DATAOFFSET_OFFSET', + 'BRCMF_SHARED_CONSOLE_ADDR_OFFSET', 'BRCMF_SHARED_HTOD_MB_DATA_ADDR_OFFSET', + 'BRCMF_SHARED_DTOH_MB_DATA_ADDR_OFFSET', 'BRCMF_SHARED_RING_INFO_ADDR_OFFSET', + 'BRCMF_SHARED_FLAGS2_OFFSET', 'BRCMF_SHARED_HOST_CAP_OFFSET', 'BRCMF_SHARED_FLAGS3_OFFSET', + 'BRCMF_SHARED_HOST_CAP2_OFFSET', 'BRCMF_SHARED_SIZE', 'BRCMF_CONSOLE_BUFADDR_OFFSET', + 'BRCMF_CONSOLE_BUFSIZE_OFFSET', 'BRCMF_CONSOLE_WRITEIDX_OFFSET', 'BRCMF_RING_MEM_SZ', + 'BRCMF_RING_MAX_ITEM_OFFSET', 'BRCMF_RING_MEM_BASE_ADDR_OFFSET')) + bus_h = (DRIVER / 'bus.h').read_text() + defines += ''.join(define(bus_h, n) for n in ( + 'BRCMF_H2D_MSGRING_FLOWRING_IDSTART', 'BRCMF_NROF_H2D_COMMON_MSGRINGS', 'BRCMF_NROF_D2H_COMMON_MSGRINGS')) + defines += '#define BRCMF_NROF_COMMON_MSGRINGS (BRCMF_NROF_H2D_COMMON_MSGRINGS + BRCMF_NROF_D2H_COMMON_MSGRINGS)\n' + structs = struct((DRIVER / 'msgbuf.h').read_text(), 'msgbuf_buf_addr') + struct(pcie, 'brcmf_pcie_dhi_ringinfo') + body = function((DRIVER / 'pcie.h').read_text(), 'brcmf_pcie_tcm_range_valid') + ''.join( + function(pcie, n) for n in ('brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', + 'brcmf_pcie_init_ringbuffers', 'brcmf_pcie_init_share_ram_info')) + if args.mutation: + old, new = MUTATIONS[args.mutation] + if old not in body: + raise ValueError('mutation site missing: ' + args.mutation) + body = body.replace(old, new) + code = PREFIX.replace('/* DEFINES */', defines).replace('/* STRUCTS */', structs) + body + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + source = out / 'controls.c' + source.write_text(code) + exe = out / 'controls' + subprocess.run(['clang', '-std=gnu11', '-O1', '-g', '-fsanitize=address,undefined', + '-fno-sanitize-recover=all', '-Wno-incompatible-function-pointer-types', + str(source), '-o', str(exe)], check=True) + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60) + receipt = {'exit': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr, + 'limits': 'Fake TCM and dongle tables; no firmware, PCIe link or DMA proof.'} + (out / 'results.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps(receipt)) + return result.returncode + + if args.out: + raise SystemExit(run(args.out)) + with tempfile.TemporaryDirectory(prefix='brcmf-shared-tcm-') as temp: + raise SystemExit(run(Path(temp))) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..ac040f6c5ed5cf 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -159,6 +159,10 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('stall-limit', 'trap-flag', 'console', 'line-start', 'once', 'rate-limit', 'stall-reset', 'ring-full'), out()), 'brcmf-roam-tests.py': [(out(), PASS)], + 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', + 'flowring-idx', 'console-desc', 'console-buf', 'console-widx', + 'console-reinit'), out()), 'brcmf-sae-vendor-tests.py': [(out(), PASS)] + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], 'brcmf-suspend-tests.py': [(out(), PASS)] From a426ba76c1704815b11b7dc137741730ed8956b3 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 21 Nov 2026 17:18:05 -0300 Subject: [PATCH 0509/1514] drm/asahi: g17: bound how long a finished command waits in the frontier Since the frontier is pruned from the front, a command that finishes behind an older unfinished one stays in it until the front finishes. The readers skip it, but it still holds its Completion: for a compute command that includes the 16 KiB timestamp page (a GEM object and its GPU mapping), which used to go back to the cache at the next prune. A compute command completes when its ring's stamp covers its kick, so one ring finishes in order. The completion-record fallback, a change of ring and recovery replay are not shown to keep that order, and a render queue spreads over several pairs. So rather than rely on it, also scan the whole frontier once there have been as many prunes as the last full scan left entries. The target is fixed at each scan: every enqueue prunes once and adds an entry, so with a stuck front a count compared against the current length would never catch up. That costs at most two more status reads per prune, amortized, and nothing finished waits longer than one queue length of submissions. A KUnit case keeps the front unfinished and adds an unfinished command with every prune; the finished ones behind it must leave at the scan. Signed-off-by: Jonathan Goyvaerts --- .../gpu/drm/asahi/g17/queue/outstanding.rs | 71 ++++++++++++++++--- 1 file changed, 62 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs index cf2f29d95f49af..fea34fb5f2a9c1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs +++ b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs @@ -4,10 +4,17 @@ //! //! Commands mostly finish in order, so a prune takes finished entries from the front and stops at //! the first unfinished one: it costs what it removes, not the length of the list. An entry that -//! finishes behind an older unfinished one stays until it reaches the front; every reader skips it -//! by its status. A failure must not wait like that, because later commands whose prefix covers it -//! are cancelled: a prune is given its VM's failure counts and scans the whole list from when a -//! failure starts until it has finished and one scan has run after that. +//! finishes behind an older unfinished one stays until it reaches the front or a full scan, and +//! every reader skips it by its status. While it stays it keeps its command's resources, such as +//! a compute command's timestamp page, so a full scan also runs once there have been as many +//! prunes as entries were held after the last one. That target is fixed at each scan, as a stuck +//! front with one new entry per prune would otherwise keep the length ahead of the count. It +//! costs at most two more status reads per prune, amortized, and nothing finished waits longer +//! than one queue length of submissions. +//! +//! A failure must not wait at all, because later commands whose prefix covers it are cancelled: +//! a prune is given its VM's failure counts and scans the whole list from when a failure starts +//! until it has finished and one scan has run after that. use crate::g17::{job::Order, status::Failures}; use kernel::prelude::*; @@ -26,6 +33,8 @@ pub(crate) struct Outstanding { head: usize, /// [`Failures::finished`] at the last full scan. failures: u64, + /// Front-only prunes left before the next full scan: the length after the last one. + scan_in: usize, } impl Outstanding { @@ -35,6 +44,7 @@ impl Outstanding { entries: KVVec::new(), head: 0, failures, + scan_in: 0, } } @@ -82,9 +92,10 @@ impl Outstanding { /// Removes finished entries and hands each to `finished` with its status, oldest first. /// While no failure has started since the last full scan, only entries in front of the - /// oldest unfinished one leave. + /// oldest unfinished one leave, until there have been as many prunes as entries were held + /// after the last full scan. pub(crate) fn prune(&mut self, failures: Failures, mut finished: impl FnMut(u64, i32, T)) { - if failures.started != self.failures { + if failures.started != self.failures || self.scan_in == 0 { // Only a finished failure is sure to be seen by this scan. One still being signalled // keeps `started` ahead, so the scans stay full until it has finished. self.failures = failures.finished; @@ -101,8 +112,10 @@ impl Outstanding { false }); self.head = 0; + self.scan_in = self.len(); return; } + self.scan_in -= 1; while let Some((sequence, entry)) = self.entries.get_mut(self.head) { let Some(status) = entry.as_ref().map(Status::status) else { break; @@ -163,6 +176,8 @@ mod tests { let command = push(&mut queue, sequence); commands.push(command, GFP_KERNEL).unwrap(); } + // As a queue in use: every enqueue prunes before it pushes, so it has been scanned. + assert!(prune(&mut queue, 0).is_empty()); (queue, commands) } @@ -213,6 +228,43 @@ mod tests { assert_eq!(sequences(queue.iter()), [3u64]); } + #[test] + fn a_command_finished_behind_an_unfinished_one_leaves_within_a_queue_length() { + let (mut queue, commands) = queue(4); + commands[2].finish(1); + let mut prunes = 0; + while prune(&mut queue, 0).is_empty() { + prunes += 1; + assert!(prunes <= 4); + } + assert_eq!(sequences(queue.iter()), [1u64, 2, 4]); + } + + #[test] + fn a_stuck_front_does_not_hold_finished_commands_past_a_queue_length() { + let (mut queue, commands) = queue(4); + commands[1].finish(1); + commands[2].finish(1); + commands[3].finish(1); + // Command 1 never finishes, and each prune comes with a new unfinished command, as a + // long command at the front of a busy queue. + let mut left = KVec::new(); + let mut prunes = 0; + for sequence in 5..=16u64 { + prunes += 1; + for (sequence, _) in prune(&mut queue, 0) { + left.push(sequence, GFP_KERNEL).unwrap(); + } + push(&mut queue, sequence); + if !left.is_empty() { + break; + } + } + // The 4 held at the last scan, then the scan itself. + assert_eq!(left, [2u64, 3, 4]); + assert_eq!(prunes, 4 + 1); + } + #[test] fn a_moved_failure_count_scans_the_whole_queue() { let (mut queue, commands) = queue(5); @@ -269,7 +321,7 @@ mod tests { } #[test] - fn a_deep_steady_queue_reads_only_what_leaves_and_never_grows() { + fn a_deep_steady_queue_reads_a_few_entries_per_prune_and_never_grows() { // Commands queued deep, then one finishing for each new one, as under vkd3d-proton. // A little over half of the room is held: moving down only once as many have left // as are held would double it. @@ -285,7 +337,8 @@ mod tests { assert_eq!(queue.len(), DEPTH as usize); assert_eq!(queue.entries.capacity(), capacity); } - // Each prune read the one that left and the unfinished one behind it. - assert_eq!(READS.load(Ordering::Relaxed), 2 * 9 * DEPTH as usize); + // Each prune read the one that left and the unfinished one behind it, and once per + // queue length a full scan read them all. + assert!(READS.load(Ordering::Relaxed) <= 3 * 9 * DEPTH as usize); } } From afa278b972d13fa675ad82e863e61bddeb36a7a8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:37:03 +1100 Subject: [PATCH 0510/1514] wifi: brcmfmac: pcie: read a trap record only inside the TCM When a control request stalls, brcmf_pcie_ctl_stall() reads the trap type and exception PC from a record whose address comes from shared RAM, without checking it against the TCM mapping. Read the record only when it lies within the mapping; the firmware is declared dead either way. The console trap scan starts at the write index the firmware reports when the console is set up. Reset the scan with the rest of the console state, and start it at the beginning of the buffer when that index is outside the buffer, so a scan that could not start before now does. tools/asahi/brcmf-recovery-tests.py gives its fake device the TCM size and adds a control for a trap record past the end of the TCM; the new mutation trap-bound drops the check and the fake's bounds assertion fails. Signed-off-by: Ryan Murray --- .../wireless/broadcom/brcm80211/brcmfmac/pcie.c | 15 +++++++++++---- tools/asahi/brcmf-recovery-tests.py | 12 +++++++++--- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 97fb98d33d2723..b70c96508d0914 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1059,9 +1059,13 @@ static void brcmf_pcie_ctl_stall(struct device *dev, u32 stalls) addr = brcmf_pcie_read_tcm32(devinfo, shared->tcm_base_address + BRCMF_SHARED_TRAP_ADDR_OFFSET); /* trap type, then the exception pc */ - brcmf_err(bus, "firmware trap 0x%x at 0x%08x\n", - brcmf_pcie_read_tcm32(devinfo, addr), - brcmf_pcie_read_tcm32(devinfo, addr + 4)); + if (brcmf_pcie_tcm_range_valid(devinfo->tcm_size, addr, 8)) + brcmf_err(bus, "firmware trap 0x%x at 0x%08x\n", + brcmf_pcie_read_tcm32(devinfo, addr), + brcmf_pcie_read_tcm32(devinfo, addr + 4)); + else + brcmf_err(bus, "firmware trap record at 0x%08x is outside the TCM\n", + addr); reason = "trap in shared RAM"; } else if ((flags & BRCMF_PCIE_SHARED_ASSERT_BUILT) && (flags & BRCMF_PCIE_SHARED_ASSERT)) { @@ -1138,6 +1142,8 @@ static void brcmf_pcie_bus_console_init(struct brcmf_pciedev_info *devinfo) console->base_addr = brcmf_pcie_read_tcm32(devinfo, addr); console->bufsize = 0; console->read_idx = 0; + console->scan_idx = 0; + console->scan_len = 0; if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr, BRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) { console->base_addr = 0; @@ -1157,7 +1163,8 @@ static void brcmf_pcie_bus_console_init(struct brcmf_pciedev_info *devinfo) } addr = console->base_addr + BRCMF_CONSOLE_WRITEIDX_OFFSET; console->scan_idx = brcmf_pcie_read_tcm32(devinfo, addr); - console->scan_len = 0; + if (console->scan_idx >= console->bufsize) + console->scan_idx = 0; brcmf_dbg(FWCON, "Console: base %x, buf %x, size %d\n", console->base_addr, console->buf_addr, console->bufsize); diff --git a/tools/asahi/brcmf-recovery-tests.py b/tools/asahi/brcmf-recovery-tests.py index 9ca30ac20b28dc..ae13fca63052c9 100755 --- a/tools/asahi/brcmf-recovery-tests.py +++ b/tools/asahi/brcmf-recovery-tests.py @@ -13,7 +13,7 @@ def function(source, name): - match = re.search(r'^(?:static\s+)?(?:void|int|bool|s32)\s+' + name + + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32)\s+' + name + r'\([^;]*?\)\s*\{', source, re.M) if not match: raise ValueError('Missing function ' + name) @@ -66,7 +66,7 @@ def define(source, name): u32 scan_idx; u8 scan_line[8]; u8 scan_len; }; struct brcmf_pcie_shared_info { u32 tcm_base_address; struct brcmf_pcie_console console; }; struct brcmf_pciedev_info { enum brcmf_pcie_state state; struct pci_dev *pdev; - struct brcmf_pcie_shared_info shared; bool fw_dead, reset_wanted; u32 recoveries; unsigned long recovery_window; }; + size_t tcm_size; struct brcmf_pcie_shared_info shared; bool fw_dead, reset_wanted; u32 recoveries; unsigned long recovery_window; }; struct pcie_priv { struct brcmf_pciedev_info *devinfo; }; struct brcmf_bus { enum brcmf_bus_state state; struct device *dev; struct { struct pcie_priv *pcie; } bus_priv; }; struct brcmf_proto { void *pd; }; @@ -116,6 +116,7 @@ def define(source, name): { memset(tcm, 0, sizeof(tcm)); link_down = false; memset(&devinfo, 0, sizeof(devinfo)); devinfo.pdev = &pdev; devinfo.state = BRCMFMAC_PCIE_STATE_UP; + devinfo.tcm_size = sizeof(tcm); devinfo.shared.tcm_base_address = SHARED; put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 0x10007); devinfo.shared.console.base_addr = CONS; devinfo.shared.console.buf_addr = BUF; devinfo.shared.console.bufsize = BUFSZ; put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 0); @@ -145,6 +146,9 @@ def define(source, name): /* Trap flag in shared RAM: dead at the first stall. */ reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_TRAP); put32(SHARED + BRCMF_SHARED_TRAP_ADDR_OFFSET, 0x800); put32(0x800, 4); put32(0x804, 0x1234); stall(1); assert(died("trap in shared RAM")); cases++; + /* A trap record outside the TCM is not read; the firmware is still dead. */ + reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_TRAP); + put32(SHARED + BRCMF_SHARED_TRAP_ADDR_OFFSET, sizeof(tcm) - 4); stall(1); assert(died("trap in shared RAM")); cases++; /* Assert only counts when the firmware was built with asserts. */ reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_ASSERT); stall(1); assert(!crashes); cases++; reset(); put32(SHARED, 0x10007 | BRCMF_PCIE_SHARED_ASSERT | BRCMF_PCIE_SHARED_ASSERT_BUILT); @@ -209,6 +213,7 @@ def define(source, name): 'wanted-over-limit': ('pcie', '\tif (xchg(&devinfo->fw_dead, true))\n\t\treturn;\n', '\tif (xchg(&devinfo->fw_dead, true))\n\t\treturn;\n' '\tWRITE_ONCE(devinfo->reset_wanted, true);\n'), + 'trap-bound': ('pcie', '\t\tif (brcmf_pcie_tcm_range_valid(devinfo->tcm_size, addr, 8))', '\t\tif (true)'), 'stall-reset': ('msgbuf', '\tmsgbuf->ctl_stalls = 0;\n', ''), 'ring-full': ('msgbuf', '\t\tif (err == -ENOMEM)\n', '\t\tif (false)\n'), } @@ -220,12 +225,13 @@ def main(): parser.add_argument('--mutation', choices=sorted(MUTATIONS)) args = parser.parse_args() sources = {name: (DRIVER / (name + '.c')).read_text() for name in ('pcie', 'msgbuf')} + sources['pcie.h'] = (DRIVER / 'pcie.h').read_text() defines = ''.join(define(sources['pcie'], n) for n in ( 'BRCMF_PCIE_SHARED_ASSERT_BUILT', 'BRCMF_PCIE_SHARED_ASSERT', 'BRCMF_PCIE_SHARED_TRAP', 'BRCMF_SHARED_FLAGS_OFFSET', 'BRCMF_SHARED_TRAP_ADDR_OFFSET', 'BRCMF_CONSOLE_WRITEIDX_OFFSET', 'BRCMF_PCIE_CTL_STALL_MAX', 'BRCMF_PCIE_RECOVERY_MAX', 'BRCMF_PCIE_RECOVERY_WINDOW_S')) bodies = { - 'pcie': ''.join(function(sources['pcie'], n) for n in ( + 'pcie': function(sources['pcie.h'], 'brcmf_pcie_tcm_range_valid') + ''.join(function(sources['pcie'], n) for n in ( 'brcmf_pcie_fw_died', 'brcmf_pcie_console_trapped', 'brcmf_pcie_ctl_stall')), 'msgbuf': function(sources['msgbuf'], 'brcmf_msgbuf_query_dcmd_len'), } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ac040f6c5ed5cf..9d64da34935b23 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -157,7 +157,7 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('narrow-stream', 'ignore-aperture', 'revision-wide'), out('--output')), 'brcmf-recovery-tests.py': [(out(), PASS)] + mutations('--mutation', ('stall-limit', 'trap-flag', 'console', 'line-start', 'once', - 'rate-limit', 'stall-reset', 'ring-full'), out()), + 'rate-limit', 'stall-reset', 'ring-full', 'trap-bound'), out()), 'brcmf-roam-tests.py': [(out(), PASS)], 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', From adb0cabf684bb7f3055de0a825c9811065c549a9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:18:38 +1100 Subject: [PATCH 0511/1514] accel/ane: t6021: give the firmware a kernel copy of a program's sections PROG_LOAD hashed the section bytes and ran the TD flags check directly on the caller's BOs, then gave the firmware the BO's IOVA (bo->dma + offset) for the first LOAD and for every reload after an eviction or a firmware restart. The program kept a reference on each BO to keep that memory alive. The BO stays mapped in the caller's address space, so the bytes the firmware read at a LOAD were not necessarily the bytes that were hashed and checked, for this file or for another file that the program table gave the same program by that hash. Copy each section at PROG_LOAD into its own dma_alloc_coherent buffer for the ANE device (the device the BOs are allocated for, with the same 16 KiB alignment and firmware alias checks). Userspace has no mapping of it. Compute the cache key and run ane_t6021_td_flags_check() over the copies, and name the copies in every LOAD_PROGRAM record. The program owns its copies and frees them when the firmware has dropped it (the release op), so a HELD program keeps them until a verified restart as before. A load that finds a cached program, or fails before the program is reserved, frees its copies. The copies count against bo_total_max_mb. The key is now taken in section slot order. The program no longer holds the section BOs, so drop the BO program reference count and the program/io publish state that only served it; a BO the firmware got as a CALL buffer is pooled or held as before. The copy, key and LOAD record steps are in ane_t6021_lifetime.h (ane_t6021_secs_fill/_key/_give, ane_t6021_load_records), and prog_sections_copied_test checks that changing the caller's buffer after the copy changes neither the key, nor the TD check result, nor the memory a first LOAD or a reload names. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_t6021_lifetime.h | 111 ++++++- drivers/accel/ane/ane_t6021_lifetime_test.c | 114 ++++++++ drivers/accel/ane/ane_t6021_rtclient_main.c | 302 ++++++++++---------- 3 files changed, 369 insertions(+), 158 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_lifetime.h b/drivers/accel/ane/ane_t6021_lifetime.h index db0689f2609d8e..3a8307162c7d1c 100644 --- a/drivers/accel/ane/ane_t6021_lifetime.h +++ b/drivers/accel/ane/ane_t6021_lifetime.h @@ -25,8 +25,10 @@ * the next poll and the cursor does not move. * * A program is shared by every file that loaded byte-identical sections and - * outlives the firmware instance it was loaded into. Each file holds one - * reference per program it loaded, by an opaque kernel ID that never changes. + * outlives the firmware instance it was loaded into. It owns a kernel copy of + * its sections, made at PROG_LOAD, and the firmware only ever reads that + * copy. Each file holds one reference per program it loaded, by an opaque + * kernel ID that never changes. * Whether the program is in the firmware right now (resident) is separate: * * - When the last file holding a program closes, it is unloaded: @@ -50,6 +52,7 @@ #define __ANE_T6021_LIFETIME_H__ #include +#include #include #include #include @@ -210,14 +213,106 @@ struct ane_t6021_prog { enum ane_t6021_prog_state state; bool resident; /* LOADed into the current firmware instance */ u64 last_use; - /* The program's own reference on each section buffer, or NULL, and - * the IOVA and size its LOAD names for that section. + /* The program's own kernel copy of each section, or NULL, and the + * IOVA and size its LOAD names for that section. */ void *sec[ANE_T6021_PROG_SECS]; u64 sec_iova[ANE_T6021_PROG_SECS]; u64 sec_size[ANE_T6021_PROG_SECS]; }; +/* + * The sections of a program while PROG_LOAD builds it, by slot (id - 1). + * Each is a kernel copy no client can map: the cache key, the TD check and + * every LOAD of the program read the copy, never the caller's buffer, so + * what was keyed and checked is what the firmware reads. + */ +struct ane_t6021_secs { + void *mem[ANE_T6021_PROG_SECS]; /* driver allocation, NULL: no section */ + u8 *cpu[ANE_T6021_PROG_SECS]; + u64 iova[ANE_T6021_PROG_SECS]; + u64 size[ANE_T6021_PROG_SECS]; +}; + +/* Copy @size bytes of the caller's section at @src into @cpu, the kernel + * allocation @mem at @iova, and record it at @slot. @src is not read again. + */ +static inline void ane_t6021_secs_fill(struct ane_t6021_secs *s, + unsigned int slot, void *mem, u8 *cpu, + u64 iova, const u8 *src, u64 size) +{ + memcpy(cpu, src, size); + s->mem[slot] = mem; + s->cpu[slot] = cpu; + s->iova[slot] = iova; + s->size[slot] = size; +} + +/* + * The cache key of the copies: SHA-256 over each section's id, size and + * bytes in slot order, so identical bytes give the same program. Returns + * ane_t6021_td_flags_check() of the TD stream copy. + */ +static inline int ane_t6021_secs_key(const struct ane_t6021_secs *s, + u8 digest[SHA256_DIGEST_SIZE]) +{ + struct sha256_ctx sha; + unsigned int i; + int td_flags = 0; + + sha256_init(&sha); + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + u64 hdr[2] = { i + 1, s->size[i] }; + + if (!s->mem[i]) + continue; + sha256_update(&sha, (const u8 *)hdr, sizeof(hdr)); + sha256_update(&sha, s->cpu[i], s->size[i]); + if (i + 1 == ANE_T6021_SEC_TEXT) + td_flags = ane_t6021_td_flags_check(s->cpu[i], + s->size[i]); + } + sha256_final(&sha, digest); + return td_flags; +} + +/* The program takes the copies; @s keeps none. */ +static inline void ane_t6021_secs_give(struct ane_t6021_secs *s, + struct ane_t6021_prog *p) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + p->sec[i] = s->mem[i]; + p->sec_iova[i] = s->iova[i]; + p->sec_size[i] = s->size[i]; + } + memset(s, 0, sizeof(*s)); +} + +/* + * The section records of a LOAD_PROGRAM (0x200) into the zeroed command + * @cmd: one 0x30-byte record per section at its identity slot from +0x08, + * flags bit0 = 1, id at +0x04, iova at +0x18, size at +0x20. The same + * records serve the first load and every reload. + */ +static inline void ane_t6021_load_records(u8 *cmd, + const struct ane_t6021_prog *p) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + u8 *rec = cmd + 0x8 + i * 0x30; + + if (!p->sec[i]) + continue; + *(__le32 *)(rec + 0x00) = cpu_to_le32(1); + *(__le32 *)(rec + 0x04) = cpu_to_le32(i + 1); + *(__le64 *)(rec + 0x18) = cpu_to_le64(p->sec_iova[i]); + *(__le64 *)(rec + 0x20) = cpu_to_le64(p->sec_size[i]); + } +} + struct ane_t6021_progtab { struct ane_t6021_prog progs[ANE_T6021_MAX_PROGRAMS]; unsigned int hi; /* slots below this index may be in use */ @@ -235,7 +330,7 @@ struct ane_t6021_fdprogs { struct ane_t6021_progtab_ops { /* Unload from the firmware; zero only when every command was acked. */ int (*unload)(void *ctx, struct ane_t6021_prog *p); - /* The firmware no longer reads the sections: drop their references. */ + /* The firmware no longer reads the sections: free their copies. */ void (*release)(void *ctx, struct ane_t6021_prog *p); /* LOAD the program again; on success set fw_prog_id. */ int (*load)(void *ctx, struct ane_t6021_prog *p); @@ -297,8 +392,8 @@ static inline bool ane_t6021_prog_unloadable(const struct ane_t6021_prog *p) /* * Claim a slot for a program about to be loaded. It starts HELD so nothing - * can find it, and it owns the section references taken before the LOAD is - * sent: if the LOAD fails, the buffers stay held with it. Make room in the + * can find it, and it owns the section copies given to it before the LOAD is + * sent: if the LOAD fails, the copies stay held with it. Make room in the * firmware before this: a restart frees unreferenced slots, this one too. */ static inline struct ane_t6021_prog * @@ -582,7 +677,7 @@ static inline int ane_t6021_progtab_ensure(struct ane_t6021_progtab *t, /* * A verified firmware restart dropped every program and process. Programs * no file holds are freed; held ones become LIVE and non-resident, keep - * their kernel IDs and section references, and load again on next use. + * their kernel IDs and section copies, and load again on next use. */ static inline void ane_t6021_progtab_restarted(struct ane_t6021_progtab *t, const struct ane_t6021_progtab_ops *ops, diff --git a/drivers/accel/ane/ane_t6021_lifetime_test.c b/drivers/accel/ane/ane_t6021_lifetime_test.c index 4654a2d2fa9011..b2620a351ca814 100644 --- a/drivers/accel/ane/ane_t6021_lifetime_test.c +++ b/drivers/accel/ane/ane_t6021_lifetime_test.c @@ -111,6 +111,119 @@ static void td_flags_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_t6021_td_flags_check(td, 2), 0); } +/* Fill @s with a TD stream (slot 2) and a constant section (slot 6) of @buf. */ +static void fill_two(struct kunit *test, struct ane_t6021_secs *s, + const u8 *buf, u8 **copy) +{ + copy[0] = kunit_kzalloc(test, 0x90, GFP_KERNEL); + copy[1] = kunit_kzalloc(test, 0x40, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy[0]); + KUNIT_ASSERT_NOT_NULL(test, copy[1]); + ane_t6021_secs_fill(s, ANE_T6021_SEC_TEXT - 1, copy[0], copy[0], + 0x40000000, buf, 0x90); + ane_t6021_secs_fill(s, 6, copy[1], copy[1], 0x40004000, buf + 0x90, + 0x40); +} + +static void check_records(struct kunit *test, const u8 *cmd) +{ + unsigned int i; + + for (i = 0; i < ANE_T6021_PROG_SECS; i++) { + const u8 *rec = cmd + 0x8 + i * 0x30; + u32 want_id = 0; + u64 want_iova = 0, want_size = 0; + + if (i == ANE_T6021_SEC_TEXT - 1) { + want_id = ANE_T6021_SEC_TEXT; + want_iova = 0x40000000; + want_size = 0x90; + } else if (i == 6) { + want_id = 7; + want_iova = 0x40004000; + want_size = 0x40; + } + KUNIT_EXPECT_EQ(test, get_unaligned_le32(rec), want_id ? 1U : 0U); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(rec + 0x04), want_id); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(rec + 0x18), want_iova); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(rec + 0x20), want_size); + } +} + +/* + * PROG_LOAD keys, checks and names a kernel copy of the caller's sections. + * The caller's buffer stays writable to it after the load, so a change + * there must reach neither the key, nor the TD check, nor the memory any + * LOAD of the program (first or reload) names. + */ +static void prog_sections_copied_test(struct kunit *test) +{ + struct ane_t6021_secs *secs, *ref, *now; + u8 digest[SHA256_DIGEST_SIZE], want[SHA256_DIGEST_SIZE]; + u8 changed[SHA256_DIGEST_SIZE]; + u8 *buf, *orig, *cmd, *copy[2], *ref_copy[2], *now_copy[2]; + struct ane_t6021_prog *p; + unsigned int i; + + buf = kunit_kzalloc(test, 0xd0, GFP_KERNEL); + cmd = kunit_kzalloc(test, 0x1c0, GFP_KERNEL); + p = kunit_kzalloc(test, sizeof(*p), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + KUNIT_ASSERT_NOT_NULL(test, cmd); + KUNIT_ASSERT_NOT_NULL(test, p); + secs = kunit_kzalloc(test, sizeof(*secs), GFP_KERNEL); + ref = kunit_kzalloc(test, sizeof(*ref), GFP_KERNEL); + now = kunit_kzalloc(test, sizeof(*now), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, secs); + KUNIT_ASSERT_NOT_NULL(test, ref); + KUNIT_ASSERT_NOT_NULL(test, now); + /* A well-formed single-task TD stream, then constants. */ + put_task(buf, 0x10, 0x20, 0x2a); + memset(buf + 0x90, 0x5a, 0x40); + orig = kunit_kzalloc(test, 0xd0, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, orig); + memcpy(orig, buf, 0xd0); + + fill_two(test, secs, buf, copy); + /* The caller rewrites its buffer: a TD stream the check refuses and + * other constants. + */ + put32(buf + 0x18, 0x08); + memset(buf + 0x90, 0xa5, 0x40); + + /* Key and check see the bytes as they were at the copy. */ + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(secs, digest), 0); + fill_two(test, ref, orig, ref_copy); + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(ref, want), 0); + KUNIT_EXPECT_EQ(test, memcmp(digest, want, sizeof(want)), 0); + /* The rewritten bytes would have been refused and keyed apart. */ + fill_two(test, now, buf, now_copy); + KUNIT_EXPECT_EQ(test, ane_t6021_secs_key(now, changed), -EINVAL); + KUNIT_EXPECT_NE(test, memcmp(digest, changed, sizeof(changed)), 0); + + /* The program owns the copies; the LOAD names them, not the buffer. */ + ane_t6021_secs_give(secs, p); + for (i = 0; i < ANE_T6021_PROG_SECS; i++) + KUNIT_EXPECT_NULL(test, secs->mem[i]); + KUNIT_EXPECT_PTR_EQ(test, p->sec[ANE_T6021_SEC_TEXT - 1], (void *)copy[0]); + KUNIT_EXPECT_PTR_EQ(test, p->sec[6], (void *)copy[1]); + ane_t6021_load_records(cmd, p); + check_records(test, cmd); + KUNIT_EXPECT_EQ(test, memcmp(copy[0], orig, 0x90), 0); + KUNIT_EXPECT_EQ(test, memcmp(copy[1], orig + 0x90, 0x40), 0); + KUNIT_EXPECT_NE(test, memcmp(copy[0], buf, 0x90), 0); + + /* A reload after an eviction or restart names the same copies, whatever + * the caller's buffer holds by then. + */ + memset(buf, 0xff, 0xd0); + memset(cmd, 0, 0x1c0); + ane_t6021_load_records(cmd, p); + check_records(test, cmd); + KUNIT_EXPECT_EQ(test, memcmp(copy[0], orig, 0x90), 0); + KUNIT_EXPECT_EQ(test, memcmp(copy[1], orig + 0x90, 0x40), 0); +} + /* A fake firmware. Records every command class and fails on demand. */ struct fake_fw { struct kunit *test; @@ -856,6 +969,7 @@ static struct kunit_case lifetime_cases[] = { KUNIT_CASE(mring_classify_test), KUNIT_CASE(legtab_reuse_test), KUNIT_CASE(td_flags_test), + KUNIT_CASE(prog_sections_copied_test), KUNIT_CASE(progtab_shared_unload_test), KUNIT_CASE(multitask_unloaded_at_close_test), KUNIT_CASE(progtab_failed_unload_holds_test), diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index b565f31112ae79..75e5a1a145b78f 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -9,8 +9,9 @@ * CREATE_PROCESS 0x202, PROCEDURE_CALL 0x204) driven through the * ioctls in this file; * - DRM accel: BO_INIT/BO_FREE plus PROG_LOAD/PROC_CREATE/EXEC per - * include/uapi/drm/ane_accel.h (ABI 2). Sections ride BOs the - * user supplies; one global mutex serializes every firmware + * include/uapi/drm/ane_accel.h (ABI 2). Sections arrive in BOs + * the user supplies and PROG_LOAD copies them into kernel memory; + * one global mutex serializes every firmware * command; completion = the legacy exchange's reply PLUS the * firmware's finish event on the IO_T2H ring. EXEC also returns the * fw's target-to-host slots (drained after every exchange). @@ -347,9 +348,9 @@ struct ane_t6021_fd { /* Per-file handle counter and every per-fd list against same-fd concurrent * ioctls. A BO whose IOVA reached the firmware (fw_ref) never goes back to - * the kernel: a program section is held until a verified reset, an io BO is parked - * for reuse (see ane_t6021_bo_release). Every other BO frees at its last - * reference. + * the kernel: an io BO is parked for reuse (see ane_t6021_bo_release). Every + * other BO frees at its last reference. Program sections are not BOs: a + * program owns a kernel copy of them (struct ane_t6021_sec_copy). * * Per-BO cap: matvec weights emitted by the H14 compiler are bounded by * `reduction * columns * 2`, which reaches 20 MiB at (K,N)=(2048,5120). @@ -357,7 +358,8 @@ struct ane_t6021_fd { * and any H14 softmax/reduction with an 8 MiB table. Total BO bytes * across all fds are capped separately (bo_total_max_mb) by an atomic * counter, enforced at alloc and released when the memory is really - * freed. Program sections stay held until a verified reset, and one large model's + * freed. The section copies of the programs count against the same cap: + * they stay until the firmware dropped the program, and one large model's * programs alone can hold gigabytes. * A cap of 0 refuses every BO_INIT with -ENOSPC; there is no unlimited * value. Every BO also needs IOVA below 4 GiB (32-bit DMA mask), so @@ -365,7 +367,6 @@ struct ane_t6021_fd { * The 16 KiB alignment check is unchanged: every DMA site assumes it. */ #define ANE_T6021_BO_MAX SZ_1G -#define ANE_T6021_BO_HASH_CHUNK SZ_1M struct ane_t6021_bo { struct list_head node; @@ -376,10 +377,7 @@ struct ane_t6021_bo { dma_addr_t dma; size_t size; u64 fw_epoch; - u32 prog_refs; /* program sections using this BO */ bool fw_ref; /* the firmware received this IOVA */ - bool fw_program; /* a loaded program keeps this IOVA */ - bool fw_io; /* published as a CALL buffer */ struct device *dev; }; @@ -429,11 +427,10 @@ static u64 ane_t6021_bo_epoch = 1; static DEFINE_SPINLOCK(ane_t6021_bo_pool_lock); /* Final put: the last handle or mapping is gone. The firmware must never - * see a freed IOVA, so a current-generation fw_ref BO is retained: a program - * section stays held, because a cached firmware program keeps reading - * it; an io BO goes to the pool, unless a quarantined firmware may still - * write it. Every other BO frees here, so the BO cap bounds only the - * memory the firmware may touch. + * see a freed IOVA, so a current-generation fw_ref BO is retained: an io BO + * goes to the pool, unless a quarantined firmware may still write it. Every + * other BO frees here, so the BO cap bounds only the memory the firmware + * may touch. */ static void ane_t6021_bo_destroy(struct ane_t6021_bo *bo) { @@ -451,7 +448,7 @@ static void ane_t6021_bo_release(struct kref *ref) spin_lock(&ane_t6021_bo_pool_lock); release = !bo->fw_ref || bo->fw_epoch != ane_t6021_bo_epoch; if (!release) { - if (bo->fw_program || atomic_read(&ane_t6021_quarantined)) + if (atomic_read(&ane_t6021_quarantined)) list_add_tail(&bo->node, &ane_t6021_bo_held); else list_add_tail(&bo->node, &ane_t6021_bo_pool); @@ -481,18 +478,10 @@ static void ane_t6021_bo_new_epoch(void) } /* bo_lock and a live handle protect the BO while its IOVA is published. */ -static void ane_t6021_bo_publish(struct ane_t6021_bo *bo, bool program) +static void ane_t6021_bo_publish(struct ane_t6021_bo *bo) { - if (bo->fw_epoch != ane_t6021_bo_epoch) { - bo->fw_program = false; - bo->fw_io = false; - } bo->fw_epoch = ane_t6021_bo_epoch; bo->fw_ref = true; - if (program) - bo->fw_program = true; - else - bo->fw_io = true; } /* A parked io BO of SIZE's page-aligned size, or NULL. */ @@ -1471,13 +1460,14 @@ static int ane_rtclient_command(struct ane_rtclient *ane, /* ---- LOAD / CREATE / CALL wrappers ---- */ /* Two loads of byte-identical sections share one program and one process. - * The key is SHA-256 over every section's id, size and bytes, so a client - * can only reach a program whose bytes it also supplied, and every file - * holds a reference on each program it loaded. The last close unloads a - * program, at most ANE_T6021_FW_RESIDENT_MAX programs are resident, and a - * program a file still holds loads again on its next use after it was - * unloaded for room or a restart (ane_t6021_lifetime.h). Protected by - * ane_t6021_fw_lock. + * The key is SHA-256 over every section's id, size and bytes, taken over the + * program's own kernel copy of the sections that the firmware reads and no + * client can map or change, so a client can only reach a program whose bytes + * it also supplied. Every file holds a reference on each program it loaded. + * The last close unloads a program, at most ANE_T6021_FW_RESIDENT_MAX + * programs are resident, and a program a file still holds loads again on + * its next use after it was unloaded for room or a restart + * (ane_t6021_lifetime.h). Protected by ane_t6021_fw_lock. */ static struct ane_t6021_progtab ane_t6021_progtab; static struct ane_fw_ids ane_t6021_ids; @@ -1560,28 +1550,75 @@ static int ane_t6021_prog_unload_op(void *ctx, struct ane_t6021_prog *p) return ret; } -/* The firmware no longer reads the sections: drop the program's references. - * A BO no other program uses stops being a program BO, and is freed or - * pooled by the usual rule at its last put. +/* A program's kernel copy of one section: allocated for the same device as + * the BOs, so the firmware reaches it the same way, never mapped to + * userspace and not written after PROG_LOAD filled it. Counted against + * bo_total_max_mb like a BO. */ +struct ane_t6021_sec_copy { + struct device *dev; + void *cpu; + dma_addr_t dma; + size_t size; /* allocated bytes, page aligned */ +}; + +static struct ane_t6021_sec_copy * +ane_t6021_sec_copy_alloc(struct ane_rtclient *ane, u64 size) +{ + struct ane_t6021_sec_copy *c; + size_t alloc; + + /* No BO holds more, so a larger section is refused anyway. */ + if (size > ANE_T6021_BO_MAX) + return ERR_PTR(-EINVAL); + alloc = PAGE_ALIGN(max_t(size_t, size, 1)); + if (atomic64_add_return(alloc, &ane_t6021_bo_total_bytes) > + (s64)bo_total_max_mb << 20) { + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + return ERR_PTR(-ENOSPC); + } + c = kzalloc_obj(*c); + if (!c) { + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + return ERR_PTR(-ENOMEM); + } + c->cpu = dma_alloc_coherent(ane->dev, alloc, &c->dma, GFP_KERNEL); + if (!c->cpu) { + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + kfree(c); + return ERR_PTR(-ENOMEM); + } + /* The same IOVA rules as a BO (see ane_t6021_bo_init_locked()). */ + if (!IS_ALIGNED(c->dma, SZ_16K) || + (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, c->dma, alloc))) { + dma_free_coherent(ane->dev, alloc, c->cpu, c->dma); + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + kfree(c); + return ERR_PTR(-ERANGE); + } + c->dev = ane->dev; + c->size = alloc; + return c; +} + +static void ane_t6021_sec_copy_free(struct ane_t6021_sec_copy *c) +{ + dma_free_coherent(c->dev, c->size, c->cpu, c->dma); + atomic64_sub(c->size, &ane_t6021_bo_total_bytes); + kfree(c); +} + +/* The firmware no longer reads the sections: free the program's copies. */ static void ane_t6021_prog_release_op(void *ctx, struct ane_t6021_prog *p) { unsigned int i; - mutex_lock(&ane_t6021_bo_lock); for (i = 0; i < ANE_T6021_PROG_SECS; i++) { - struct ane_t6021_bo *bo = p->sec[i]; - - if (!bo) + if (!p->sec[i]) continue; + ane_t6021_sec_copy_free(p->sec[i]); p->sec[i] = NULL; - if (!WARN_ON(!bo->prog_refs) && !--bo->prog_refs) { - bo->fw_program = false; - bo->fw_ref = bo->fw_io; - } - kref_put(&bo->refcount, ane_t6021_bo_release); } - mutex_unlock(&ane_t6021_bo_lock); } /* @@ -1590,8 +1627,8 @@ static void ane_t6021_prog_release_op(void *ctx, struct ane_t6021_prog *p) * at slot 6 and slot 5 stays empty when id 6 is absent). flags bit0 = 1, id * at +0x04, iova at +0x18, size at +0x20. The firmware writes the program ID * back at +0x1b8. Used for the first load and for every reload after an - * eviction or a restart; the section IOVAs are republished to the current - * firmware generation before the doorbell. + * eviction or a restart; every record names the program's kernel copy of + * the section, which lives until the firmware dropped the program for good. */ static int ane_rtclient_send_load(struct ane_rtclient *ane, struct ane_t6021_prog *p) @@ -1599,29 +1636,13 @@ static int ane_rtclient_send_load(struct ane_rtclient *ane, struct ane_legacy_buffer *command = ane->cmd_buf; u8 *cmd; u32 fw_prog; - unsigned int i; int ret; if (!command || atomic_read(&ane_t6021_quarantined)) return -ENODEV; cmd = command->cpu; memset(cmd, 0, SZ_16K); - mutex_lock(&ane_t6021_bo_lock); - for (i = 0; i < ANE_T6021_PROG_SECS; i++) { - u64 slot_base = 0x8 + (u64)i * 0x30; - - if (!p->sec[i]) - continue; - /* The firmware may read the section any time after the - * doorbell, including during a timeout. - */ - ane_t6021_bo_publish(p->sec[i], true); - *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); - *(u32 *)(cmd + slot_base + 0x04) = cpu_to_le32(i + 1); - *(u64 *)(cmd + slot_base + 0x18) = cpu_to_le64(p->sec_iova[i]); - *(u64 *)(cmd + slot_base + 0x20) = cpu_to_le64(p->sec_size[i]); - } - mutex_unlock(&ane_t6021_bo_lock); + ane_t6021_load_records(cmd, p); *(u32 *)(cmd + 0x1b8) = cpu_to_le32(U32_MAX); /* The LOAD command is 0x1C0 bytes: the nine 0x30 records end at * 0x1b8, ProgramId at +0x1b8, 8 bytes of zero tail. @@ -1692,11 +1713,28 @@ static const struct ane_t6021_progtab_ops ane_t6021_progtab_ops = { .restart = ane_t6021_prog_restart_op, }; +/* The BO of this file that holds section @sec, or NULL. Under bo_lock. */ +static struct ane_t6021_bo * +ane_t6021_sec_bo_locked(struct ane_t6021_fd *fd, + const struct drm_ane_section *sec) +{ + struct ane_t6021_bo *b; + + lockdep_assert_held(&ane_t6021_bo_lock); + list_for_each_entry(b, &fd->bos, node) { + if (b->handle != sec->bo_handle) + continue; + if (sec->size > b->size || sec->offset > b->size - sec->size) + return NULL; + return b; + } + return NULL; +} + /* Build a LOAD_PROGRAM (0x200) message in a kernel-owned buffer. The - * section bytes live in the BOs the user supplied (section_ptr), the - * generic binds (bufferId, bo_handle, size) patch the generic section - * at iova +0x20 / +0x28 once the BO is copied. Returns 0 with - * *prog_id set on success. + * section bytes are copied out of the BOs the user supplied (section_ptr) + * into kernel memory the program owns; the generic binds are accepted + * and unused (see below). Returns 0 with *prog_id set on success. */ static int ane_rtclient_load_program(struct ane_rtclient *ane, struct drm_file *file, @@ -1707,6 +1745,7 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, struct drm_ane_generic_bind *binds; struct ane_t6021_fd *fd = file->driver_priv; struct ane_t6021_prog *cached, *prog = NULL; + struct ane_t6021_secs secs = {}; bool sent = false; int td_flags = 0; u32 key, gen; @@ -1770,64 +1809,50 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, } } - /* Identical sections share one firmware program (see the table). - * A constant section can reach 20 MiB (the H14 (K,N)=(2048,5120) - * matvec), so feed the hash in ANE_T6021_BO_HASH_CHUNK-sized slices - * under bo_lock: a single sha256_update of a 20 MiB buffer would - * rely on a 20 MiB stack argument list and has no upper bound on - * the chunk that the BO could supply. + /* Copy every section out of the caller's buffer into kernel memory no + * client can map, then key and check the copies: identical sections + * share one firmware program (see the table), and the bytes keyed and + * checked here are the bytes every LOAD of the program names. The + * buffer is read once, under bo_lock. */ - { - struct sha256_ctx sha; - void *scratch; + /* Every section must name a BO of this file that holds it. */ + for (i = 0; i < user->section_count; i++) { + bool ok; - sha256_init(&sha); - scratch = kvmalloc(ANE_T6021_BO_HASH_CHUNK, GFP_KERNEL); - if (!scratch) { - ret = -ENOMEM; + mutex_lock(&ane_t6021_bo_lock); + ok = ane_t6021_sec_bo_locked(fd, §ions[i]); + mutex_unlock(&ane_t6021_bo_lock); + if (!ok) { + ret = -EINVAL; goto out; } - for (i = 0; i < user->section_count; i++) { - struct ane_t6021_bo *bo = NULL, *b; - u64 hdr[2] = { sections[i].id, sections[i].size }; - size_t left; + } + for (i = 0; i < user->section_count; i++) { + struct ane_t6021_sec_copy *c; + struct ane_t6021_bo *bo; + unsigned int slot = sections[i].id - 1; - mutex_lock(&ane_t6021_bo_lock); - list_for_each_entry(b, &fd->bos, node) { - if (b->handle == sections[i].bo_handle) { - bo = b; - break; - } - } - if (!bo || sections[i].size > bo->size || - sections[i].offset > bo->size - sections[i].size) { - mutex_unlock(&ane_t6021_bo_lock); - kvfree(scratch); - ret = -EINVAL; - goto out; - } - sha256_update(&sha, (const u8 *)hdr, sizeof(hdr)); - /* Checked in the same snapshot as the key. */ - if (sections[i].id == ANE_T6021_SEC_TEXT) - td_flags = ane_t6021_td_flags_check((const u8 *)bo->cpu + - sections[i].offset, - sections[i].size); - left = sections[i].size; - while (left) { - size_t n = min_t(size_t, left, - ANE_T6021_BO_HASH_CHUNK); - - memcpy(scratch, (const u8 *)bo->cpu + - sections[i].offset + - (sections[i].size - left), n); - sha256_update(&sha, scratch, n); - left -= n; - } - mutex_unlock(&ane_t6021_bo_lock); + c = ane_t6021_sec_copy_alloc(ane, sections[i].size); + if (IS_ERR(c)) { + ret = PTR_ERR(c); + goto out; + } + /* Looked up again: the BO may have been freed meanwhile. */ + mutex_lock(&ane_t6021_bo_lock); + bo = ane_t6021_sec_bo_locked(fd, §ions[i]); + if (bo) + ane_t6021_secs_fill(&secs, slot, c, c->cpu, c->dma, + (const u8 *)bo->cpu + + sections[i].offset, + sections[i].size); + mutex_unlock(&ane_t6021_bo_lock); + if (!bo) { + ane_t6021_sec_copy_free(c); + ret = -EINVAL; + goto out; } - kvfree(scratch); - sha256_final(&sha, digest); } + td_flags = ane_t6021_secs_key(&secs, digest); /* A program that opens or closes on the wrong task wedges the firmware * for every client; refuse it before the firmware sees it. */ @@ -1873,37 +1898,10 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, goto out; } gen = ane_t6021_progtab.gen; - /* The record slot IS the section identity (slot = id - 1). The program - * takes its own reference on each section buffer, kept until the - * firmware dropped the program for good (or forever if uncertain). + /* The program owns the copies from here, until the firmware dropped it + * for good (or forever if uncertain). */ - for (i = 0; i < user->section_count; i++) { - struct ane_t6021_bo *bo = NULL, *b; - unsigned int slot = sections[i].id - 1; - - mutex_lock(&ane_t6021_bo_lock); - list_for_each_entry(b, &fd->bos, node) { - if (b->handle == sections[i].bo_handle) { - bo = b; - break; - } - } - if (bo && sections[i].size <= bo->size && - sections[i].offset <= bo->size - sections[i].size) { - kref_get(&bo->refcount); - bo->prog_refs++; - prog->sec[slot] = bo; - prog->sec_iova[slot] = bo->dma + sections[i].offset; - prog->sec_size[slot] = sections[i].size; - } else { - bo = NULL; - } - mutex_unlock(&ane_t6021_bo_lock); - if (!bo) { - ret = -EINVAL; - goto out; - } - } + ane_t6021_secs_give(&secs, prog); /* Generic binds are accepted for ABI compatibility and unused: the * LOAD record already carries iova + size, and the generic section * image is prepared by userspace (generic.bin). @@ -1929,6 +1927,10 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, /* The firmware never saw these IOVAs: give the reservation back. */ if (prog && !sent) ane_t6021_progtab_cancel(prog, &ane_t6021_progtab_ops, ane); + /* Copies no program took (a cached program, or a failed load). */ + for (i = 0; i < ANE_T6021_PROG_SECS; i++) + if (secs.mem[i]) + ane_t6021_sec_copy_free(secs.mem[i]); kfree(sections); kfree(binds); return ret; @@ -2203,7 +2205,7 @@ static int ane_rtclient_procedure_call(struct ane_rtclient *ane, /* Keep this IO element out of the reuse pool until completion. */ kref_get(&bo->refcount); exec_bos[pinned++] = bo; - ane_t6021_bo_publish(bo, false); + ane_t6021_bo_publish(bo); iova = bo->dma; mutex_unlock(&ane_t6021_bo_lock); *(u32 *)(cmd + slot_base + 0x00) = cpu_to_le32(1); From 265fb587a8105b21d667f27219f7047b6a4eca3c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:15:18 +1100 Subject: [PATCH 0512/1514] accel/ane: t6021: map the firmware's text read-only for the engine The T602x/T8112 loader stages the firmware image in a dma_alloc_coherent buffer, which the DMA API maps read-write for the engine at fw_iova, and then aliases every page of it at the latched RVBAR entry with IOMMU_READ | IOMMU_WRITE. The engine could therefore write the __TEXT segment it executes, at both IOVAs, until the next restart re-copied it. Decide the protection per page from the pinned segment table: a page that lies wholly inside the image's __TEXT segment is mapped without IOMMU_WRITE, every other page (DATA, the vmsize tail, the extra RAM) keeps its read-write mapping. Apply it to the entry alias in both alias modes, and remap the __TEXT pages of the coherent buffer at fw_iova read-only, at the same IOVA and physical address, so that no device-writable mapping of __TEXT remains and dma_free_coherent() still unmaps the range as before. The kernel keeps writing __TEXT through its CPU mapping only: the DATA base patch and the re-copy before a restart are unchanged, and the restart path does not touch the mappings. Add a KUnit suite for the protection helper over both pinned images. Signed-off-by: Ryan Murray --- drivers/accel/ane/Makefile | 2 +- drivers/accel/ane/ane_t6021_fwload.c | 73 ++++++++++++++++++-- drivers/accel/ane/ane_t6021_fwmap.h | 45 +++++++++++++ drivers/accel/ane/ane_t6021_fwmap_test.c | 85 ++++++++++++++++++++++++ 4 files changed, 199 insertions(+), 6 deletions(-) create mode 100644 drivers/accel/ane/ane_t6021_fwmap.h create mode 100644 drivers/accel/ane/ane_t6021_fwmap_test.c diff --git a/drivers/accel/ane/Makefile b/drivers/accel/ane/Makefile index 4557afbf5ddc55..6fdd739d5b056c 100644 --- a/drivers/accel/ane/Makefile +++ b/drivers/accel/ane/Makefile @@ -10,7 +10,7 @@ obj-$(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) += ane_fw_platform_test.o \ ane_fw_transport_test.o ane_h16_boot_test.o \ ane_h16_pending_test.o ane_h16_hwx_test.o ane_h16_preload_test.o \ ane_h16_program_test.o ane_fw_cold_test.o ane_h16_accel_test.o \ - ane_t6021_lifetime_test.o + ane_t6021_lifetime_test.o ane_t6021_fwmap_test.o ane-y := \ ane_drv.o \ diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 21e0f2ce7e9dfd..0cf57d0cf02922 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -13,7 +13,10 @@ * three bound instances). Segment-wise copy * (__TEXT fileoff 0x4000 -> vm 0, __DATA -> its vmaddr; vmsize * tail zero from the coherent alloc). Coherent memory needs no - * explicit cache clean. + * explicit cache clean. The engine maps __TEXT read-only, at + * fw_iova and at the entry alias (ane_t6021_fw_prot(), selected by + * the pinned segment table); DATA and the rest stay read-write. + * The kernel writes TEXT through its CPU mapping only. * 4. Which copy runs. By default the staged copy (own memory). The * option fw_alias_reserved=1 (T6021 only) maps the copy iBoot * preloaded at SEG0/SEGi; probe refuses it unless no-map @@ -74,6 +77,7 @@ #include "ane_t6021.h" #include "ane_t6021_boot.h" #include "ane_fw_validate.h" +#include "ane_t6021_fwmap.h" MODULE_FIRMWARE(ANE_FW_SELENE_NAME); MODULE_FIRMWARE(ANE_FW_BIA_NAME); @@ -236,8 +240,57 @@ static int ane_t6021_pmu_map(struct ane_t6021 *ane, struct iommu_domain *dom) return ret; } +/* The coherent allocation maps every page read-write for the engine at + * fw_iova. Map the __TEXT pages there again, at the same IOVA and PA, + * read-only. The IOVA range stays the DMA API's and the same number of + * bytes stays mapped, so dma_free_coherent() unmaps it as before. + */ +static int ane_t6021_fw_staged_protect(struct ane_t6021 *ane) +{ + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); + struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); + int rw = IOMMU_READ | IOMMU_WRITE; + u64 off; + int ret; + + if (!dom) + return -ENODEV; + if (dev_is_dma_coherent(ane->dev)) + rw |= IOMMU_CACHE; + for (off = 0; off < ane->fw_size; off += ANE_T6021_FW_ALIAS_PAGE) { + u64 iova = ane->fw_iova + off; + int prot = ane_t6021_fw_prot(soc->fw->segs, ANE_FW_NSEGS, off, + ANE_T6021_FW_ALIAS_PAGE, rw); + phys_addr_t pa; + + if (prot == rw) + continue; + pa = iommu_iova_to_phys(dom, iova); + if (!pa || pa & (ANE_T6021_FW_ALIAS_PAGE - 1)) + return -EFAULT; + if (iommu_unmap(dom, iova, ANE_T6021_FW_ALIAS_PAGE) != + ANE_T6021_FW_ALIAS_PAGE) + return -EIO; + ret = iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, prot, + GFP_KERNEL); + /* Never leave a hole for dma_free_coherent() to trip on. */ + if (ret && iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, rw, + GFP_KERNEL)) + dev_err(ane->dev, "fwload: +%#llx left unmapped\n", off); + if (!ret && iommu_iova_to_phys(dom, iova) != pa) + ret = -EIO; + if (ret) { + dev_err(ane->dev, "fwload: TEXT +%#llx read-only map: %d\n", + off, ret); + return ret; + } + } + return 0; +} + static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) { + const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); void __iomem *eng = ane->base[ANE_T6021_REG_ENGINE]; u64 rvbar = readq(eng + ANE_ASC_RVBAR); @@ -332,7 +385,12 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) } ret = iommu_map(dom, win[w].iova + o, pa, - ANE_T6021_FW_ALIAS_PAGE, prot, + ANE_T6021_FW_ALIAS_PAGE, + ane_t6021_fw_prot(soc->fw->segs, + ANE_FW_NSEGS, + win[w].iova + o - entry, + ANE_T6021_FW_ALIAS_PAGE, + prot), GFP_KERNEL); if (ret) { dev_err(ane->dev, @@ -393,8 +451,11 @@ static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) ret = -EEXIST; goto err_unmap; } - ret = iommu_map(dom, entry + off, pa, - ANE_T6021_FW_ALIAS_PAGE, prot, GFP_KERNEL); + ret = iommu_map(dom, entry + off, pa, ANE_T6021_FW_ALIAS_PAGE, + ane_t6021_fw_prot(soc->fw->segs, ANE_FW_NSEGS, + off, ANE_T6021_FW_ALIAS_PAGE, + prot), + GFP_KERNEL); if (ret) { dev_err(ane->dev, "fwalias: iommu_map +%#llx: %d\n", off, ret); @@ -624,7 +685,9 @@ int ane_t6021_fwload_probe(struct ane_t6021 *ane) "fwload: %s PRELOAD validated + DART-mapped: entry %#llx, iova %pad size %#x\n", img->name, entry, &iova, alloc_size); - ret = reserved ? 0 : ane_t6021_fw_patch(ane, buf); + ret = ane_t6021_fw_staged_protect(ane); + if (!ret && !reserved) + ret = ane_t6021_fw_patch(ane, buf); if (!ret) ret = ane_t6021_fw_alias_map(ane, reserved); if (ret) { diff --git a/drivers/accel/ane/ane_t6021_fwmap.h b/drivers/accel/ane/ane_t6021_fwmap.h new file mode 100644 index 00000000000000..60e0352ae8b0cc --- /dev/null +++ b/drivers/accel/ane/ane_t6021_fwmap.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Engine-side protection of the staged H14 firmware image. + * + * Kept free of device access so the KUnit suite (ane_t6021_fwmap_test.c) + * runs the same code as the loader (ane_t6021_fwload.c). + */ +#ifndef __ANE_T6021_FWMAP_H__ +#define __ANE_T6021_FWMAP_H__ + +#include +#include +#include +#include + +#include "ane_fw_validate.h" + +/* + * IOMMU protection for the engine's mapping of [off, off + len) of the + * staged image, off counted from the image's vm base. A range that lies + * wholly inside the image's __TEXT segment (found by name in the pinned + * segment table) loses IOMMU_WRITE; every other range (DATA, the vmsize + * tail, the extra RAM after the image) keeps prot. This is the device + * side only: the kernel still writes TEXT through its own mapping (the + * DATA base patch, the re-copy before a restart). + */ +static inline int ane_t6021_fw_prot(const struct ane_fw_seg *segs, + unsigned int nsegs, u64 off, u64 len, + int prot) +{ + unsigned int i; + + for (i = 0; i < nsegs; i++) { + const struct ane_fw_seg *s = &segs[i]; + + if (strcmp(s->name, "__TEXT")) + continue; + if (off >= s->vmaddr && len <= s->vmsize && + off - s->vmaddr <= s->vmsize - len) + return prot & ~IOMMU_WRITE; + } + return prot; +} + +#endif /* __ANE_T6021_FWMAP_H__ */ diff --git a/drivers/accel/ane/ane_t6021_fwmap_test.c b/drivers/accel/ane/ane_t6021_fwmap_test.c new file mode 100644 index 00000000000000..8f44fe2bd817de --- /dev/null +++ b/drivers/accel/ane/ane_t6021_fwmap_test.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include + +#include "ane_t6021_fwmap.h" + +#define RW (IOMMU_READ | IOMMU_WRITE) + +/* Every 16 KiB page of the pinned __TEXT is read-only for the engine, every + * page from the DATA vmaddr to the end of the allocation stays read-write. + */ +static void fw_prot_image(struct kunit *test, const struct ane_fw_image *img) +{ + const struct ane_fw_seg *text = &img->segs[0]; + u64 end = ANE_FW_BUF_SIZE + SZ_2M; + u64 off; + + KUNIT_ASSERT_STREQ(test, text->name, "__TEXT"); + KUNIT_ASSERT_EQ(test, img->segs[1].vmaddr, text->vmaddr + text->vmsize); + for (off = 0; off < end; off += SZ_16K) { + int want = off < text->vmsize ? IOMMU_READ : RW; + + KUNIT_EXPECT_EQ_MSG(test, ane_t6021_fw_prot(img->segs, ANE_FW_NSEGS, + off, SZ_16K, RW), + want, "%s +%#llx", img->name, off); + KUNIT_EXPECT_EQ_MSG(test, ane_t6021_fw_prot(img->segs, ANE_FW_NSEGS, + off, SZ_16K, + RW | IOMMU_CACHE), + want | IOMMU_CACHE, "%s +%#llx", img->name, off); + } +} + +static void fw_prot_selene_test(struct kunit *test) +{ + fw_prot_image(test, &ane_fw_selene); +} + +static void fw_prot_bia_test(struct kunit *test) +{ + fw_prot_image(test, &ane_fw_bia); +} + +/* TEXT is found by name, wherever the table puts it; a range that is not + * wholly inside it (here one that runs into DATA) stays writable. + */ +static void fw_prot_by_table_test(struct kunit *test) +{ + static const struct ane_fw_seg segs[ANE_FW_NSEGS] = { + { 0x000000, 0x100000, 0x004000, 0x100000, "__DATA" }, + { 0x100000, 0x008000, 0x104000, 0x008000, "__TEXT" }, + }; + + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0, SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x100000, + SZ_16K, RW), IOMMU_READ); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x104000, + SZ_16K, RW), IOMMU_READ); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x0fc000, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x104000, + SZ_32K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, 0x108000, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, ANE_FW_NSEGS, U64_MAX - 1, + SZ_16K, RW), RW); + KUNIT_EXPECT_EQ(test, ane_t6021_fw_prot(segs, 1, 0x100000, SZ_16K, RW), RW); +} + +static struct kunit_case fwmap_cases[] = { + KUNIT_CASE(fw_prot_selene_test), + KUNIT_CASE(fw_prot_bia_test), + KUNIT_CASE(fw_prot_by_table_test), + {} +}; + +static struct kunit_suite fwmap_suite = { + .name = "ane-t6021-fwmap", + .test_cases = fwmap_cases, +}; + +kunit_test_suite(fwmap_suite); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("ANE H14 staged firmware mapping protection tests"); From 98005c9aed57425aed4a86ae7b88db0e44877d15 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:39:38 +1100 Subject: [PATCH 0513/1514] accel/ane: h17: give back the arena of the warm-sleep commands On a chip that sleeps warm, ane_fw_suspend_firmware() publishes EXCLAVE_MODE_STOP (0x31, once per firmware boot) and SUSPEND (0x24) into the command arena and never releases them. The transport survives the warm boot after the wake, so each system sleep kept its commands' arena until the next cold firmware boot, and the arena shrinks with every sleep. Take an arena mark before the two commands and release it once SUSPEND is answered and its reply has been read. Neither command is read by the firmware after its reply. A failure before the reply still quarantines the session with the arena as it is; a failed release only warns. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_cold.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 1cf7da420b3c97..e1ff911e09a8cf 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -472,6 +472,7 @@ static int ane_fw_exclave_mode_stop(struct ane_fw_backend *b) static int ane_fw_suspend_firmware(struct ane_fw_backend *b) { u8 command[8] = {}; + size_t mark; u8 *slot; u32 status; int ret; @@ -485,6 +486,12 @@ static int ane_fw_suspend_firmware(struct ane_fw_backend *b) ret = ane_fw_transport_settle(&b->transport, 2 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC); if (ret < 0) return ret; + /* + * The transport survives a warm sleep, so the arena the 0x31 and + * SUSPEND commands take must be given back once SUSPEND is answered, + * or every sleep would keep it until the next firmware boot. + */ + mark = ane_fw_transport_mark(&b->transport); ret = ane_fw_exclave_mode_stop(b); if (ret) { ane_h16_session_dump_fwlog(&b->session); @@ -514,6 +521,9 @@ static int ane_fw_suspend_firmware(struct ane_fw_backend *b) dev_info(&b->pdev->dev, "H17 ANE: SUSPEND reply %*ph\n", (int)sizeof(command), command); if (get_unaligned_le16(command + 6)) return -EREMOTEIO; + /* Both commands are answered and their replies read. */ + if (ane_fw_transport_release(&b->transport, mark)) + dev_warn(&b->pdev->dev, "H17 ANE: SUSPEND arena not released\n"); dev_info(&b->pdev->dev, "H17 ANE: SUSPEND acknowledged, wrapper status %#x\n", ane_rd32(b, b->engine + b->soc->wrapper + 0x48)); /* From 4d459a41e9f9e5723f49cb61f2a2dceef83614e1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:53:56 +1100 Subject: [PATCH 0514/1514] media: apple: ave: run the M2 encoder's macOS 27.2 firmware build On an M2 Mac with the macOS 27.2 (26B123) stub, as on the Mac mini (J473), the bootloader preloads a newer encoder firmware build than the one the T8112 variant knows: TEXT 0x11c000 instead of 0xd0000, DATA 0x128000. The driver refused it at probe ("unexpected firmware segment sizes"), so the encoder never registered. Like the M4's 27.2 loaders, the Mac mini's sets the word at TEXT 0x4224 on every boot; with it zeroed the TEXT CRC is 077a3444. That build is the M2 encoder's build of the firmware version the M3 already runs on 27.2, and it starts the way the M3's does: the boot configuration handshake as device 12 with handshake type 12, the 26B123 command layout and its reference buffer sizing (lfs_ref_scale 2, as on the M3 and M4), the codec clocks ungated by clearing the mailbox idle word, the bootloader's code base (marked valid) left in place, and DATA restored from the boot snapshot before every start. None of the 13.5 build's start (device 18/type 15, the TEXT link cell, the extra0 window) applies to it. Describe it as its own variant and let a variant name the variant of a later build of the same encoder (next_build). At probe the firmware reservations the bootloader made select the build by their segment sizes; the TEXT CRC then has to be that build's. Like the command layouts, which the TEXT CRC already selects, this keys on the firmware build because it must: the start and the command protocol belong to the build the bootloader handed over, and only its segments identify it. The 13.5 build keeps its variant and start, other sizes are still refused, and no other variant changes. KUnit covers the selection (13.5 sizes, 27.2 sizes, near misses), the 27.2 variant's start fields, its per-boot TEXT word (any value gives the zeroed-word CRC) and its layout lookup. Signed-off-by: Ryan Murray --- .../media/platform/apple/ave/ave-abi-test.c | 57 +++++++++++++++++++ drivers/media/platform/apple/ave/ave-drv.c | 30 ++++++++++ drivers/media/platform/apple/ave/ave-fw.c | 35 +++++++++++- drivers/media/platform/apple/ave/ave-layout.c | 3 +- drivers/media/platform/apple/ave/ave.h | 14 +++++ 5 files changed, 136 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 4b5f60f4d11b81..f8488c825e5cb9 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1499,6 +1499,62 @@ static void ave_26b123_layout(struct kunit *test) KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(AVE_FW_TEXT_CRC_T8122_26B123), b); } +/* + * The M2 with the 27.2 stub: the reserved segment sizes select the 27.2 + * build's own start (device 12, handshake type 12) and the 26B123 layout; + * the 13.5 build keeps the M2's 6070 start, and other sizes stay refused. + */ +static void ave_t8112_26b123_build(struct kunit *test) +{ + const struct ave_variant *n = ave_t8112.next_build; + + KUNIT_ASSERT_NOT_NULL(test, n); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0xd0000, 0x128000), + &ave_t8112); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x11c000, 0x128000), n); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x11c000, 0x12c000), + &ave_t8112); + KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x134000, 0x128000), + &ave_t8112); + KUNIT_EXPECT_NULL(test, n->next_build); + KUNIT_EXPECT_TRUE(test, n->boot_qualified); + KUNIT_EXPECT_PTR_EQ(test, n->regs, ave_t8112.regs); + KUNIT_EXPECT_EQ(test, n->boot_device_id, 12U); + KUNIT_EXPECT_EQ(test, n->device_type, 12U); + KUNIT_EXPECT_EQ(test, n->boot_arg_value, 0x10000U); + KUNIT_EXPECT_EQ(test, n->timebase_multiplier, 1U); + KUNIT_EXPECT_EQ(test, n->mbox_idle, 0x38U); + KUNIT_EXPECT_TRUE(test, n->restore_data_first); + KUNIT_EXPECT_EQ(test, n->text_link_cell, 0U); + /* The Mac mini's loader sets the word at TEXT 0x4224 on every boot. */ + KUNIT_EXPECT_EQ(test, n->text_boot_word, 0x4224U); + /* The 27.2 builds' reference buffer sizing, as on the M3 and M4. */ + KUNIT_EXPECT_EQ(test, n->lfs_ref_scale, 2U); + KUNIT_EXPECT_EQ(test, ave_t8112.lfs_ref_scale, 1U); + KUNIT_EXPECT_EQ(test, n->extra0_size, 0U); + KUNIT_EXPECT_EQ(test, n->vcbar_flags, (u64)AVE_COPROC_VCBAR_VALID); + KUNIT_EXPECT_EQ(test, ave_fw_vcbar(n, 0x800000000ULL), 0x800000001ULL); + KUNIT_EXPECT_EQ(test, n->text_crc, AVE_FW_TEXT_CRC_T8112_26B123); + { + const u32 off = n->text_boot_word, size = off + 0x40; + u8 *text = kunit_kzalloc(test, size, GFP_KERNEL); + u32 zeroed, a, b; + + KUNIT_ASSERT_NOT_NULL(test, text); + zeroed = crc32_le(~0U, text, size) ^ ~0U; + put_unaligned_le32(0x003d0000, text + off); + KUNIT_EXPECT_EQ(test, ave_fw_text_boot_crc(text, size, off, &a), 0); + put_unaligned_le32(0x00a10000, text + off); + KUNIT_EXPECT_EQ(test, ave_fw_text_boot_crc(text, size, off, &b), 0); + /* Any per-boot value gives the zeroed-word CRC. */ + KUNIT_EXPECT_EQ(test, a, zeroed); + KUNIT_EXPECT_EQ(test, b, zeroed); + } + KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(n->text_crc), &ave_layout_26b123); + KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(ave_t8112.text_crc), + &ave_layout_6070_11_1); +} + static void ave_t6041_text_boot_word(struct kunit *test) { const u32 off = ave_t6041.text_boot_word, size = off + 0x100; @@ -1572,6 +1628,7 @@ static struct kunit_case ave_abi_cases[] = { KUNIT_CASE(ave_6070_smalloc), KUNIT_CASE(ave_m3_probe_only), KUNIT_CASE(ave_26b123_layout), + KUNIT_CASE(ave_t8112_26b123_build), {} }; diff --git a/drivers/media/platform/apple/ave/ave-drv.c b/drivers/media/platform/apple/ave/ave-drv.c index 8cc10edd82900c..a5897fe998f6c6 100644 --- a/drivers/media/platform/apple/ave/ave-drv.c +++ b/drivers/media/platform/apple/ave/ave-drv.c @@ -68,6 +68,35 @@ const struct ave_variant ave_t6000 = { .boot_qualified = true, }; +/* + * The M2 (T8112) with the macOS 27.2 (26B123) stub, as on the Mac mini + * (J473): the bootloader preloads TEXT 0x11c000 and DATA 0x128000. Like the + * M4's 27.2 loaders, it sets the word at TEXT 0x4224 on every boot; with that + * word zeroed the TEXT CRC is 077a3444. It is the M2 encoder's build of the + * firmware version the M3 runs on 27.2, and it starts the same way: the boot + * configuration handshake as device 12 with handshake type 12, the 26B123 + * command layout, codec clocks ungated by clearing the mailbox idle word, + * the bootloader's code base (marked valid) left as it is, and DATA restored + * from the boot snapshot before every start. + */ +static const struct ave_variant ave_t8112_26b123 = { + .regs = &ave_coproc_6070, + .fw_text_size = 0x11c000, + .fw_data_size = 0x128000, + .boot_device_id = 12, + .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, + .timebase_multiplier = 1, + .vcbar_mask = GENMASK_ULL(41, 11), + .vcbar_flags = AVE_COPROC_VCBAR_VALID, + .device_type = 12, + .lfs_ref_scale = 2, + .text_crc = AVE_FW_TEXT_CRC_T8112_26B123, + .text_boot_word = 0x4224, + .mbox_idle = 0x38, + .restore_data_first = true, + .boot_qualified = true, +}; + const struct ave_variant ave_t8112 = { .regs = &ave_coproc_6070, .fw_text_size = 0xd0000, @@ -84,6 +113,7 @@ const struct ave_variant ave_t8112 = { .extra0_size = 0x4000, .boot_qualified = true, + .next_build = &ave_t8112_26b123, }; /* diff --git a/drivers/media/platform/apple/ave/ave-fw.c b/drivers/media/platform/apple/ave/ave-fw.c index 0ff259ca96275b..fd2e056610a379 100644 --- a/drivers/media/platform/apple/ave/ave-fw.c +++ b/drivers/media/platform/apple/ave/ave-fw.c @@ -44,6 +44,7 @@ static const u32 ave_known_text_crc[] = { AVE_FW_TEXT_CRC_T6050_26C5035, /* encoder firmware macOS 27.3 26C5035r / T6050 */ AVE_FW_TEXT_CRC_T8142_26A428, /* encoder firmware 9013.45.1, macOS 27.0 26A428 / T8142 */ AVE_FW_TEXT_CRC_T8122_26B123, /* encoder firmware macOS 27.2 26B123 / T8122 */ + AVE_FW_TEXT_CRC_T8112_26B123, /* encoder firmware macOS 27.2 26B123 / T8112 */ AVE_FW_TEXT_CRC_T8132_26B123, /* encoder firmware macOS 27.2 26B123 / T8132 */ AVE_FW_TEXT_CRC_T8142_26B123, /* encoder firmware 9013.55.1, macOS 27.2 26B123 / T8142 */ 0x460c7a7c, /* encoder firmware 6070.11.1 / T6000 */ @@ -234,6 +235,32 @@ static const struct ave_fw_build *ave_fw_find_build(const struct ave_variant *v, return NULL; } +/* Whether these are the segment sizes of one of v's builds */ +static bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, + size_t data) +{ + if (v->build_count) + return ave_fw_find_build(v, text, data, 0); + return text == v->fw_text_size && + (data == v->fw_data_size || + (v->fw_data_size_alt && data == v->fw_data_size_alt)); +} + +/* + * The variant for the build the bootloader preloaded: the matched one, or + * the first of its later builds whose segment sizes these are. Sizes alone + * pick the variant; ave_fw_probe() then refuses a TEXT CRC that is not the + * picked build's, so later builds of one encoder need sizes of their own. + */ +const struct ave_variant *ave_fw_select_build(const struct ave_variant *v, + size_t text, size_t data) +{ + for (const struct ave_variant *n = v; n; n = n->next_build) + if (ave_fw_sizes_match(n, text, data)) + return n; + return v; +} + /* * Find the firmware, check that it is a build we speak to and that DATA is * still as the bootloader left it, and keep a copy of DATA for restarts. @@ -242,8 +269,8 @@ int ave_fw_probe(struct ave_dev *ave) { struct device *dev = ave->dev; const struct ave_fw_build *build = NULL; - u32 text_crc, data_crc, want, want_crc = ave->variant->text_crc; - bool known = !ave->variant->boot_qualified; + u32 text_crc, data_crc, want, want_crc; + bool known; int ret; if (of_count_phandle_with_args(dev->of_node, "memory-region", NULL) != @@ -256,6 +283,10 @@ int ave_fw_probe(struct ave_dev *ave) if (ret) return dev_err_probe(dev, ret, "bad firmware reservation\n"); + ave->variant = ave_fw_select_build(ave->variant, ave->text.size, + ave->data.size); + want_crc = ave->variant->text_crc; + known = !ave->variant->boot_qualified; if (ave->variant->build_count) { build = ave_fw_find_build(ave->variant, ave->text.size, ave->data.size, 0); diff --git a/drivers/media/platform/apple/ave/ave-layout.c b/drivers/media/platform/apple/ave/ave-layout.c index 190d91415a009e..377406027f9abc 100644 --- a/drivers/media/platform/apple/ave/ave-layout.c +++ b/drivers/media/platform/apple/ave/ave-layout.c @@ -995,7 +995,8 @@ const struct ave_fw_layout *ave_layout_for_crc(u32 crc) if (crc == AVE_FW_TEXT_CRC_T6050_26C5035) return &ave_layout_26a428; if (crc == AVE_FW_TEXT_CRC_T8132_26B123 || - crc == AVE_FW_TEXT_CRC_T8122_26B123) + crc == AVE_FW_TEXT_CRC_T8122_26B123 || + crc == AVE_FW_TEXT_CRC_T8112_26B123) return &ave_layout_26b123; /* * The M5's macOS 27.2 build (9013.55.1), between 26A428 and the 27.3 diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index e86c3735086610..c45f0835628c0b 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -182,6 +182,11 @@ enum ave_opcode { #define AVE_FW_TEXT_CRC_T8132_26B123 0x99fc929a /* The M3 (T8122) build preloaded by the macOS 27.2 (26B123) stub. */ #define AVE_FW_TEXT_CRC_T8122_26B123 0x918d70d3 +/* + * The M2 (T8112) build preloaded by the macOS 27.2 (26B123) stub, with the + * per-boot word at TEXT 0x4224 zeroed. + */ +#define AVE_FW_TEXT_CRC_T8112_26B123 0x077a3444 /* * The M5 build of macOS 27.2 (26B123; 27.2.1 26B131 ships it unchanged), * AppleAVE2FW 9013.55.1: TEXT 0x154000, DATA 0x12c000, as 26A428's. @@ -248,6 +253,13 @@ struct ave_variant { u32 mbox_idle; /* Restore DATA from the boot snapshot before every start, the first included. */ bool restore_data_first; + /* + * The same encoder running another firmware build that a newer + * bootloader preloads, with a start and command protocol of its own. + * The firmware segment sizes the bootloader reserved select it. + * NULL when there is none. + */ + const struct ave_variant *next_build; size_t extra0_size; /* Register sequence and boot/hello configuration have been qualified. */ @@ -566,6 +578,8 @@ extern const struct ave_variant ave_t6000, ave_t6041, ave_t8112, ave_t8132, /* ave-fw.c */ u64 ave_fw_vcbar(const struct ave_variant *variant, u64 text_iova); int ave_fw_probe(struct ave_dev *ave); +const struct ave_variant *ave_fw_select_build(const struct ave_variant *v, + size_t text, size_t data); int ave_fw_text_id_crc(const void *text, size_t size, u32 cell_off, u64 data_iova, u32 *crc); int ave_fw_text_boot_crc(const void *text, size_t size, u32 word_off, From aa132a243fcd05c7a738252dc8af0ff06f66a351 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:45:42 +1100 Subject: [PATCH 0515/1514] soc: apple: pmp: bound the memory held for the firmware The PMP firmware asks the driver for DMA buffers (OPC_MALLOC) and for register slots (OPC_REGISTER_IOREG). Every request was granted and kept until the firmware freed it, so the number of buffers held for it, their total size and the register list had no bound. Count the live allocations and their size, and refuse one that would go over 64 buffers or four of the largest buffer a single request can ask for (its size field is 24 bits, so just under 64 MiB). The driver takes the size out of a request with the same constant. These are sanity bounds well above normal use: the driver's lists are sized for ten buffers and 340 registers, which is what a normal boot uses. A freed buffer gives its room back. Refuse a register once the list has 0xffff entries. The reply carries the new entry's index in 16 bits below the opcode, so a larger index cannot be returned without corrupting the reply. A refused request gets no reply and is logged, as other requests the driver cannot handle are. On the board that keeps the display bridge, that also stops display power commands, as any request the driver cannot handle does there. The bounds are in pmp_alloc.rs with host tests, run by tools/asahi/run-host-tests.py as pmp-alloc-tests.rs. Signed-off-by: Ryan Murray --- drivers/soc/apple/pmp.rs | 42 ++++++++++-- drivers/soc/apple/pmp_alloc.rs | 114 +++++++++++++++++++++++++++++++++ tools/asahi/pmp-alloc-tests.rs | 5 ++ tools/asahi/run-host-tests.py | 1 + 4 files changed, 157 insertions(+), 5 deletions(-) create mode 100644 drivers/soc/apple/pmp_alloc.rs create mode 100644 tools/asahi/pmp-alloc-tests.rs diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index afc8a973f77130..aae7356fd0c4fc 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -11,8 +11,10 @@ use core::mem; use core::sync::atomic::{fence, AtomicI32, AtomicPtr, Ordering}; +mod pmp_alloc; mod pmp_bootargs; mod pmp_power; +use pmp_alloc::AllocBudget; use pmp_power::Command; use kernel::{ @@ -85,7 +87,7 @@ const OPC_UPDATE_IOREG: u64 = 0x36; const OPC_CONFIRM_IOREG: u64 = 0x37; const OPC_ACK_MASK: u64 = 0x1; const OPC_SHIFT: u32 = 48; -const MALLOC_SIZE_MASK: u64 = 0xFFFFFF; +const MALLOC_SIZE_MASK: u64 = pmp_alloc::MALLOC_SIZE_MAX; const MSG_IOVA_MASK: u64 = 0xFFFFFFFFFFFF; const SET_IOREG_INDEX_MASK: u64 = 0xFFFF; const PIO_VM_BASE: u64 = 0xc0000000; @@ -130,6 +132,8 @@ struct SramCopy { struct PmpState { iova_table: Option>, allocs: KVec, + /// The number and total size of `allocs`. + alloc_budget: AllocBudget, value_buf: Option, ioreg_entries: KVec, /// Held from a system sleep's start until its end. @@ -141,6 +145,7 @@ impl PmpState { Ok(PmpState { iova_table: None, allocs: KVec::with_capacity(10, GFP_KERNEL)?, + alloc_budget: AllocBudget::new(), value_buf: None, ioreg_entries: KVec::with_capacity(340, GFP_KERNEL)?, sram: None, @@ -319,23 +324,42 @@ impl PmpData { fn malloc(&self, size: u64) -> Result { // SAFETY: TODO: ensure self.dev is bound let bound_dev = unsafe { self.dev.as_bound() }; - let iomem = Coherent::::zeroed_slice(bound_dev, size as usize, GFP_KERNEL)?; let mut state = self.state.lock(); + if !state.alloc_budget.claim(size) { + dev_err!( + self.dev, + "Refusing a {} byte allocation: {} held\n", + size, + state.allocs.len() + ); + return Err(ENOMEM); + } + let iomem = match Coherent::::zeroed_slice(bound_dev, size as usize, GFP_KERNEL) { + Ok(iomem) => iomem, + Err(e) => { + state.alloc_budget.release(size); + return Err(e); + } + }; let addr = iomem.dma_address(); let msg = (OPC_MALLOC | OPC_ACK_MASK) << OPC_SHIFT | addr; - state.allocs.push( + if let Err(e) = state.allocs.push( PmpAllocation { addr: addr, alloc: iomem, }, GFP_KERNEL, - )?; + ) { + state.alloc_budget.release(size); + return Err(e.into()); + } Ok(msg) } fn free(&self, addr: u64) -> Result { let mut state = self.state.lock(); if let Some(idx) = state.find_alloc(addr) { - state.allocs.swap_remove(idx); + let freed = state.allocs.swap_remove(idx); + state.alloc_budget.release(freed.alloc.size() as u64); } else { dev_err!( self.dev, @@ -370,6 +394,14 @@ impl PmpData { } fn register_ioreg(&self, addr: u64) -> Result { let mut state = self.state.lock(); + if !pmp_alloc::ioreg_fits(state.ioreg_entries.len()) { + dev_err!( + self.dev, + "Refusing register {}: no index left\n", + state.ioreg_entries.len() + 1 + ); + return Err(ENOSPC); + } let msg_buf = if let Some(s) = state.get_buf(addr) { s } else { diff --git a/drivers/soc/apple/pmp_alloc.rs b/drivers/soc/apple/pmp_alloc.rs new file mode 100644 index 00000000000000..f20addb55baa93 --- /dev/null +++ b/drivers/soc/apple/pmp_alloc.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Bounds on the memory the PMP firmware asks the kernel to hold for it. + +/// The largest buffer one allocation request can ask for: its 24-bit size field, +/// which is also the mask the driver takes the size out of a request with. +pub(crate) const MALLOC_SIZE_MAX: u64 = 0xff_ffff; + +/// Live allocations held for the firmware at once. A normal boot makes about ten. +pub(crate) const MAX_ALLOCS: usize = 64; + +/// The total size of those allocations: four of the largest the firmware can ask for. +pub(crate) const MAX_ALLOC_BYTES: u64 = 4 * MALLOC_SIZE_MAX; + +/// The highest register index a reply can carry: 16 bits, below the opcode. +pub(crate) const IOREG_INDEX_MAX: usize = 0xffff; + +/// The firmware's live allocations: how many, and their total size. +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +pub(crate) struct AllocBudget { + count: usize, + bytes: u64, +} + +impl AllocBudget { + pub(crate) const fn new() -> Self { + Self { count: 0, bytes: 0 } + } + + /// Takes room for one more allocation of `size` bytes, or refuses it. + pub(crate) fn claim(&mut self, size: u64) -> bool { + if size > MALLOC_SIZE_MAX || self.count >= MAX_ALLOCS || size > MAX_ALLOC_BYTES - self.bytes + { + return false; + } + self.count += 1; + self.bytes += size; + true + } + + /// Gives back the room of an allocation that was freed or never made. + pub(crate) fn release(&mut self, size: u64) { + self.count = self.count.saturating_sub(1); + self.bytes = self.bytes.saturating_sub(size); + } +} + +/// Whether one more register, after `registered`, gets an index a reply can carry. +pub(crate) fn ioreg_fits(registered: usize) -> bool { + registered < IOREG_INDEX_MAX +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_normal_boot_fits() { + let mut budget = AllocBudget::new(); + for _ in 0..10 { + assert!(budget.claim(0x4000)); + } + assert!(budget.claim(MALLOC_SIZE_MAX)); + } + + #[test] + fn the_number_of_live_allocations_is_bounded() { + let mut budget = AllocBudget::new(); + let mut granted = 0; + for _ in 0..100_000 { + if budget.claim(0x40) { + granted += 1; + } + } + assert_eq!(granted, MAX_ALLOCS); + } + + #[test] + fn their_total_size_is_bounded() { + let mut budget = AllocBudget::new(); + let mut bytes = 0; + for _ in 0..MAX_ALLOCS { + if budget.claim(MALLOC_SIZE_MAX) { + bytes += MALLOC_SIZE_MAX; + } + } + assert_eq!(bytes, MAX_ALLOC_BYTES); + assert!(!budget.claim(1)); + assert!(!budget.claim(MALLOC_SIZE_MAX + 1)); + } + + #[test] + fn a_freed_allocation_makes_room_again() { + let mut budget = AllocBudget::new(); + for _ in 0..=MAX_ALLOCS { + budget.claim(MALLOC_SIZE_MAX); + } + assert!(!budget.claim(0x1000)); + budget.release(MALLOC_SIZE_MAX); + assert!(budget.claim(0x1000)); + assert!(!budget.claim(MALLOC_SIZE_MAX)); + } + + #[test] + fn a_register_index_fits_its_reply() { + assert!(ioreg_fits(0)); + assert!(ioreg_fits(340)); + assert!(ioreg_fits(IOREG_INDEX_MAX - 1)); + assert!(!ioreg_fits(IOREG_INDEX_MAX)); + assert!(!ioreg_fits(usize::MAX)); + // The index of the last one admitted stays below the opcode. + assert_eq!(((IOREG_INDEX_MAX as u64) << 32) >> 48, 0); + } +} diff --git a/tools/asahi/pmp-alloc-tests.rs b/tools/asahi/pmp-alloc-tests.rs new file mode 100644 index 00000000000000..af8dedbe30a4d2 --- /dev/null +++ b/tools/asahi/pmp-alloc-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Host tests for the bounds on the PMP firmware's allocations and registers. +#[path = "../../drivers/soc/apple/pmp_alloc.rs"] +mod pmp_alloc; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..01472f308968dc 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -322,6 +322,7 @@ def mutations(flag, names, base, expect=KILL): # Production G17 decoder vectors also build directly with rustc --test. ASAHI_RUST += ['g17-telemetry-tests.rs', 'legacy-frequency-tests.rs'] ASAHI_RUST.append('m3-firmware-tests.rs') +ASAHI_RUST.append('pmp-alloc-tests.rs') # Python that runs on the host but imports its neighbours, so it keeps the # script directory on sys.path (-E -s instead of -I). From 6d7699ebdf939eb89cb0761ead03b8a827178266 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:47:54 +1100 Subject: [PATCH 0516/1514] drm/apple: dcp: test the boot notch property on a test-local node The handoff suite set asahi,show-notch on the live /chosen through an OF changeset. With DRM_APPLE as a module the suite runs once the platform driver is registered, so a display probing at that moment could read the test's "1" and drop the notch rows on a real panel. An assertion failing between init and destroy also leaked the changeset entries. Split the property read out of boot_show_notch() into dcp_boot_show_notch(), which takes the node, and test that on nodes the test builds itself. They are never part of the device tree, so the suite no longer reads or writes it, needs no changeset and no longer skips when /chosen is missing or already carries the property. boot_show_notch() passes of_chosen as before: no functional change. Add the cases a missing node, another property and an unterminated "1". The suite covers the property read only: the caller also honours the show_notch module parameter, which is not exercised here. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 9 ++- drivers/gpu/drm/apple/dcp_handoff_test.c | 95 ++++++++++-------------- 2 files changed, 47 insertions(+), 57 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bf4dc01b60e000..3f8235f5943baf 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6344,14 +6344,19 @@ static bool dcp_external_is_idle(struct apple_dcp *dcp) * drive the full panel (aura: chosen.asahi,show-notch=1). Follow it, so the * mode covers the same rows as the boot framebuffer did. */ -static bool boot_show_notch(void) +static bool dcp_boot_show_notch(const struct device_node *chosen) { const char *val; - return !of_property_read_string(of_chosen, "asahi,show-notch", &val) && + return !of_property_read_string(chosen, "asahi,show-notch", &val) && !strcmp(val, "1"); } +static bool boot_show_notch(void) +{ + return dcp_boot_show_notch(of_chosen); +} + /* * T8122 dcpext (DCP_FIRMWARE_V_14_7_TEMPLATE): if the PMP runs, the display * gate added its DISPEXT request and pointed the dcpext at it diff --git a/drivers/gpu/drm/apple/dcp_handoff_test.c b/drivers/gpu/drm/apple/dcp_handoff_test.c index 8bd8481866133c..24758ab69cd53e 100644 --- a/drivers/gpu/drm/apple/dcp_handoff_test.c +++ b/drivers/gpu/drm/apple/dcp_handoff_test.c @@ -2,8 +2,9 @@ /* * Included by dcp.c: the boot loader handoff state the driver reads before * it starts a display coprocessor. dcp_external_is_idle() runs on a fake - * coprocessor register window; boot_show_notch() on /chosen, with the - * property applied and reverted through an OF changeset. + * coprocessor register window; dcp_boot_show_notch(), which boot_show_notch() + * applies to /chosen, on nodes of the test's own. Nothing here reads or + * writes the device tree, so the suite is safe next to a probing display. */ #include #include @@ -53,66 +54,50 @@ static void dcp_handoff_external_idle(struct kunit *test) ~stopped))); } -/* boot_show_notch() with /chosen/asahi,show-notch set by @add, or absent. */ -static bool dcp_handoff_notch(struct kunit *test, - int (*add)(struct of_changeset *cs, struct device_node *np)) -{ - struct of_changeset cs; - bool ret; - - if (!add) - return boot_show_notch(); - of_changeset_init(&cs); - KUNIT_ASSERT_EQ(test, add(&cs, of_chosen), 0); - KUNIT_ASSERT_EQ(test, of_changeset_apply(&cs), 0); - ret = boot_show_notch(); - KUNIT_EXPECT_EQ(test, of_changeset_revert(&cs), 0); - of_changeset_destroy(&cs); - return ret; -} - -#define DCP_HANDOFF_NOTCH_STRING(tag, value) \ -static int dcp_handoff_notch_##tag(struct of_changeset *cs, struct device_node *np) \ -{ \ - return of_changeset_add_prop_string(cs, np, "asahi,show-notch", value); \ -} - -DCP_HANDOFF_NOTCH_STRING(one, "1") -DCP_HANDOFF_NOTCH_STRING(zero, "0") -DCP_HANDOFF_NOTCH_STRING(empty, "") -DCP_HANDOFF_NOTCH_STRING(ten, "10") -DCP_HANDOFF_NOTCH_STRING(yes, "yes") - -static int dcp_handoff_notch_u32(struct of_changeset *cs, struct device_node *np) +/* + * dcp_boot_show_notch() on a node of the test's own, never part of the + * device tree, with asahi,show-notch holding @length bytes at @value. + */ +static bool dcp_handoff_notch(const void *value, int length) { - return of_changeset_add_prop_u32(cs, np, "asahi,show-notch", 1); + struct property prop = { + .name = "asahi,show-notch", + .length = length, + .value = (void *)value, + }; + struct device_node chosen = { .properties = &prop }; + + return dcp_boot_show_notch(&chosen); } -static int dcp_handoff_notch_bool(struct of_changeset *cs, struct device_node *np) -{ - return of_changeset_add_prop_bool(cs, np, "asahi,show-notch"); -} +#define dcp_handoff_notch_string(s) dcp_handoff_notch(s, sizeof(s)) static void dcp_handoff_boot_notch(struct kunit *test) { - if (!of_chosen) - kunit_skip(test, "no /chosen node"); - if (of_property_present(of_chosen, "asahi,show-notch")) - kunit_skip(test, "/chosen already has asahi,show-notch"); - - /* Absent: the driver keeps the notch rows out of the mode. */ - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, NULL)); + static const char unterminated[] = { '1' }; + static const __be32 cell = cpu_to_be32(1); + struct property other = { + .name = "bootargs", + .length = sizeof("1"), + .value = "1", + }; + struct device_node chosen = {}; + + /* Absent, or no /chosen at all: the notch rows stay out of the mode. */ + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(NULL)); + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(&chosen)); + chosen.properties = &other; + KUNIT_EXPECT_FALSE(test, dcp_boot_show_notch(&chosen)); /* Only the string "1" the boot loader writes shows the notch. */ - KUNIT_EXPECT_TRUE(test, dcp_handoff_notch(test, dcp_handoff_notch_one)); - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_zero)); - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_empty)); - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_ten)); - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_yes)); - /* A cell or an empty property is not the string "1". */ - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_u32)); - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, dcp_handoff_notch_bool)); - /* Reverted: absent again. */ - KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(test, NULL)); + KUNIT_EXPECT_TRUE(test, dcp_handoff_notch_string("1")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("0")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("10")); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch_string("yes")); + /* A cell, an empty property or an unterminated "1" is not that string. */ + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(&cell, sizeof(cell))); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(NULL, 0)); + KUNIT_EXPECT_FALSE(test, dcp_handoff_notch(unterminated, sizeof(unterminated))); } static struct kunit_case dcp_handoff_cases[] = { From f9333fc07d22a6431d4773d8d8aa99ad7f26da4f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:48:14 +1100 Subject: [PATCH 0517/1514] drm/apple: dcp: do not pin CPU_STATUS RUNNING as idle in the handoff test The "other bits" cases of the idle test set every bit of both registers, CPU_STATUS RUNNING included, and expected dcp_external_is_idle() to accept that. apple_dcp_coprocessor_is_active() reads RUNNING as an active processor, so the test locked in RUNNING|STOPPED|IDLE as an inherited idle state: a change that makes the check refuse RUNNING would have failed it. Keep RUNNING out of the other bits. The cases still show that no other bit of either register changes the answer, and that dropping RUN, IDLE or STOPPED from the full pattern does. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp_handoff_test.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp_handoff_test.c b/drivers/gpu/drm/apple/dcp_handoff_test.c index 24758ab69cd53e..22c88773b9114c 100644 --- a/drivers/gpu/drm/apple/dcp_handoff_test.c +++ b/drivers/gpu/drm/apple/dcp_handoff_test.c @@ -9,6 +9,8 @@ #include #include +#include "dcp-lifecycle.h" + #define DCP_HANDOFF_COPROC_SIZE (APPLE_DCP_COPROC_CPU_STATUS + sizeof(u32)) static struct apple_dcp *dcp_handoff_coproc(struct kunit *test, u32 control, u32 status) @@ -29,6 +31,7 @@ static void dcp_handoff_external_idle(struct kunit *test) const u32 run = APPLE_DCP_COPROC_CPU_CONTROL_RUN; const u32 stopped = APPLE_DCP_COPROC_CPU_STATUS_STOPPED; const u32 idle = APPLE_DCP_COPROC_CPU_STATUS_IDLE; + const u32 others = ~(u32)APPLE_DCP_COPROC_CPU_STATUS_RUNNING; unsigned int bits; /* Inherited idle: the CPU enabled, and stopped and idle in its status. */ @@ -46,12 +49,18 @@ static void dcp_handoff_external_idle(struct kunit *test) "control %#x status %#x", control, status); } - /* Other bits in either register do not change the answer. */ - KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, ~0u))); - KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~run, ~0u))); - KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, ~idle))); + /* + * Other bits in either register do not change the answer. RUNNING is + * left out of them: apple_dcp_coprocessor_is_active() reads it as an + * active processor, and whether the check should refuse it next to + * STOPPED and IDLE is not this test's to pin. + */ + KUNIT_EXPECT_TRUE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, others))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~run, others))); + KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, + others & ~idle))); KUNIT_EXPECT_FALSE(test, dcp_external_is_idle(dcp_handoff_coproc(test, ~0u, - ~stopped))); + others & ~stopped))); } /* From 8157833f4cc412831f60d58f464561014e203de5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:48:25 +1100 Subject: [PATCH 0518/1514] drm/apple: run the display KUnit suites in CI No workflow built or ran the suites behind CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST: host-tests.yml runs only the host tests, and tests/.kunitconfig enables just the fabric suite. A pull request could be green without dcp_handoff_test.c ever being compiled. Commit the configuration the suites need as tests/display.kunitconfig, and add a workflow that runs it with kunit.py on arm64 QEMU for every pull request that touches drivers/gpu/drm/apple, as mt7932-kunit.yml does for the Wi-Fi driver. Signed-off-by: Ryan Murray --- .github/workflows/apple-drm-kunit.yml | 46 +++++++++++++++++++ .../gpu/drm/apple/tests/display.kunitconfig | 12 +++++ 2 files changed, 58 insertions(+) create mode 100644 .github/workflows/apple-drm-kunit.yml create mode 100644 drivers/gpu/drm/apple/tests/display.kunitconfig diff --git a/.github/workflows/apple-drm-kunit.yml b/.github/workflows/apple-drm-kunit.yml new file mode 100644 index 00000000000000..e973618725edbd --- /dev/null +++ b/.github/workflows/apple-drm-kunit.yml @@ -0,0 +1,46 @@ +name: Apple DRM KUnit + +# The Apple display driver's KUnit suites behind +# CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST (mode probing, external audio, boot +# loader handoff, ...) on arm64 QEMU. They use fake coprocessors and nodes, +# so they run without a display controller. + +on: + pull_request: + branches: [integration/aurora, aurora-wip] + paths: + - 'drivers/gpu/drm/apple/**' + - '.github/workflows/apple-drm-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: apple-drm-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + kunit: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Run the Apple display KUnit suites on arm64 QEMU + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig=drivers/gpu/drm/apple/tests/display.kunitconfig \ + --jobs="$(nproc)" --timeout=900 diff --git a/drivers/gpu/drm/apple/tests/display.kunitconfig b/drivers/gpu/drm/apple/tests/display.kunitconfig new file mode 100644 index 00000000000000..03105b192c48ef --- /dev/null +++ b/drivers/gpu/drm/apple/tests/display.kunitconfig @@ -0,0 +1,12 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_DRM=y +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_DRM_APPLE=y +CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST=y +CONFIG_OF_OVERLAY=y From c36aaf6162bb18e475186c195ea60813fb47f95b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:50:58 +1100 Subject: [PATCH 0519/1514] pmdomain: apple: pmgr-pwrstate: pin the reset write order and the idle wait The reset controller cases compared only the register's end state, so they passed with the two writes of assert or deassert swapped or folded into one. Record every write in the emulated register and check the sequence: assert sets DEV_DISABLE in a write of its own before the one that sets RESET, and deassert releases RESET while the block is still quiesced, then DEV_DISABLE. The idle wait before reset was covered only where it is set and the block never goes idle. Add: - a block that is busy with the wait not set: the reset goes in all the same, so waiting on every SoC fails the suite; - a block that goes idle on the second read of the wait: assert succeeds, and the write that sets RESET follows the read that found the block idle, so a single BUSY check instead of a poll fails; - the write counts of the refused and timed-out operations: none for a firmware-owned or inherited domain, only the quiesce for a block that stays busy. The reset domains no longer borrow apple,no-auto-pm to get a second device name: the helper takes the name. reset_xlate() is called with real phandle arguments, with and without cells, and the comment says what it shows: the domain's single line 0. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/pmdomain/apple/pmgr-pwrstate-test.c | 124 +++++++++++++++++--- 1 file changed, 106 insertions(+), 18 deletions(-) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index 39a9ec8000af76..3eaa22999e87f0 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -19,6 +19,8 @@ struct pmgr_ps_test_reg { bool latch_sticky; /* not even a PS reset clears it */ unsigned int reset_writes; /* writes with the PS reset bit */ unsigned int flag_writes; /* writes that would clear a WAS_*GATED flag */ + unsigned int nwrites; /* every write; the first of them are in @writes */ + u32 writes[8]; }; static int pmgr_ps_test_read(void *ctx, unsigned int reg, unsigned int *val) @@ -47,6 +49,9 @@ static int pmgr_ps_test_write(void *ctx, unsigned int reg, unsigned int val) u32 parent = r->val & APPLE_PMGR_BUSY; u32 actual; + if (r->nwrites < ARRAY_SIZE(r->writes)) + r->writes[r->nwrites] = val; + r->nwrites++; if (val & APPLE_PMGR_PS_RESET) { r->reset_writes++; if (r->latched && !r->latch_sticky) { @@ -86,11 +91,11 @@ static const struct regmap_config pmgr_ps_test_regmap = { .fast_io = true, }; -/* A domain in power state @pstate, actual and target, on a device of its own */ -static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, - bool no_auto_pm, struct pmgr_ps_test_reg **reg) +/* A domain in power state @pstate, actual and target, on a device of its own, @name */ +static struct apple_pmgr_ps *pmgr_ps_test_named_domain(struct kunit *test, const char *name, + u32 pstate, bool no_auto_pm, + struct pmgr_ps_test_reg **reg) { - static const char *const names[] = { "apple-pmgr-ps-auto", "apple-pmgr-ps-no-auto" }; struct pmgr_ps_test_reg *r; struct apple_pmgr_ps *ps; struct device *dev; @@ -99,7 +104,7 @@ static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, KUNIT_ASSERT_NOT_NULL(test, r); r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, pstate) | FIELD_PREP(APPLE_PMGR_PS_ACTUAL, pstate); - dev = kunit_device_register(test, names[no_auto_pm]); + dev = kunit_device_register(test, name); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); ps = kunit_kzalloc(test, sizeof(*ps), GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, ps); @@ -112,6 +117,14 @@ static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, return ps; } +static struct apple_pmgr_ps *pmgr_ps_test_domain(struct kunit *test, u32 pstate, + bool no_auto_pm, struct pmgr_ps_test_reg **reg) +{ + static const char *const names[] = { "apple-pmgr-ps-auto", "apple-pmgr-ps-no-auto" }; + + return pmgr_ps_test_named_domain(test, names[no_auto_pm], pstate, no_auto_pm, reg); +} + /* Powering on enables automatic PM, unless the domain is apple,no-auto-pm. */ static void pmgr_ps_power_on_test(struct kunit *test) { @@ -548,14 +561,14 @@ static void pmgr_ps_consumer_refused_test(struct kunit *test) } /* - * A powered-on domain with its reset controller, as probe registers it; - * @second for a second domain in one test (apple,no-auto-pm, which the - * reset operations do not read, gives its device another name). + * A powered-on domain with its reset controller, as probe registers it, on + * a device called @name. */ -static struct apple_pmgr_ps *pmgr_ps_test_reset_domain(struct kunit *test, bool second, +static struct apple_pmgr_ps *pmgr_ps_test_reset_domain(struct kunit *test, const char *name, struct pmgr_ps_test_reg **reg) { - struct apple_pmgr_ps *ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_ACTIVE, second, reg); + struct apple_pmgr_ps *ps = pmgr_ps_test_named_domain(test, name, APPLE_PMGR_PS_ACTIVE, + false, reg); spin_lock_init(&ps->genpd.slock); ps->genpd.status = GENPD_STATE_ON; @@ -566,14 +579,38 @@ static struct apple_pmgr_ps *pmgr_ps_test_reset_domain(struct kunit *test, bool return ps; } -/* Assert quiesces, then resets; deassert undoes both; status reads it back. */ +/* + * The register writes since the log was last cleared were exactly two, with + * DEV_DISABLE and RESET as in @first and then as in @second. Clears the log. + */ +static void pmgr_ps_test_expect_writes(struct kunit *test, struct pmgr_ps_test_reg *r, + u32 first, u32 second) +{ + const u32 mask = APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET; + + KUNIT_EXPECT_EQ(test, r->nwrites, 2u); + KUNIT_EXPECT_EQ(test, r->writes[0] & mask, first); + KUNIT_EXPECT_EQ(test, r->writes[1] & mask, second); + r->nwrites = 0; + memset(r->writes, 0, sizeof(r->writes)); +} + +/* + * Assert quiesces, then resets; deassert releases the reset, then the + * quiesce; status reads the reset back. + */ static void pmgr_ps_reset_assert_deassert_test(struct kunit *test) { + const struct of_phandle_args no_args = {}; + const struct of_phandle_args args = { .args_count = 2, .args = { 7, 9 } }; struct pmgr_ps_test_reg *r; - struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + /* DEV_DISABLE in a write of its own, before the one that sets RESET. */ + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 1); @@ -581,6 +618,8 @@ static void pmgr_ps_reset_assert_deassert_test(struct kunit *test) KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_TARGET, r->val), APPLE_PMGR_PS_ACTIVE); KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + /* RESET released while the block is still quiesced, DEV_DISABLE after. */ + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, 0); KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); @@ -594,15 +633,20 @@ static void pmgr_ps_reset_assert_deassert_test(struct kunit *test) KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); - /* Every phandle argument names the domain's one reset line. */ - KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, NULL), 0); + /* + * A domain has one reset line, 0. Probe registers the controller with + * no reset cells, so the core passes no arguments; xlate would not + * read any either. + */ + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, &no_args), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_xlate(&ps->rcdev, &args), 0); } /* The WAS_*GATED flags are write-one-to-clear: reset writes never set them. */ static void pmgr_ps_reset_keeps_flags_test(struct kunit *test) { struct pmgr_ps_test_reg *r; - struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); r->val |= APPLE_PMGR_FLAGS; KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); @@ -618,13 +662,16 @@ static void pmgr_ps_reset_keeps_flags_test(struct kunit *test) /* A domain the boot loader or firmware owns refuses every reset operation. */ static void pmgr_ps_reset_refused_test(struct kunit *test) { + static const char *const names[] = { + "apple-pmgr-ps-reset-firmware", "apple-pmgr-ps-reset-inherited", + }; struct pmgr_ps_test_reg *r; struct apple_pmgr_ps *ps; unsigned int owner; u32 val; for (owner = 0; owner < 2; owner++) { - ps = pmgr_ps_test_reset_domain(test, owner, &r); + ps = pmgr_ps_test_reset_domain(test, names[owner], &r); if (owner) ps->inherited_on = true; else @@ -637,14 +684,18 @@ static void pmgr_ps_reset_refused_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), -EPERM); KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), -EPERM); KUNIT_EXPECT_EQ(test, r->val, val); + KUNIT_EXPECT_EQ(test, r->nwrites, 0u); } } -/* With the idle wait before reset (T8132), a block that stays busy is never reset. */ +/* + * With the idle wait before reset (T8132), the reset goes in only once the + * block is idle; a block that stays busy is never reset. + */ static void pmgr_ps_reset_idle_wait_test(struct kunit *test) { struct pmgr_ps_test_reg *r; - struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, false, &r); + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); ps->needs_reset_idle_wait = true; /* Idle: the wait passes and the reset goes in. */ @@ -652,10 +703,28 @@ static void pmgr_ps_reset_idle_wait_test(struct kunit *test) KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_RESET); KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + /* + * Busy until the third read, which is the second of the wait (the + * quiesce write reads the register first): the wait polls, and the + * write that sets RESET follows the read that found the block idle. + */ + r->nwrites = 0; + r->val |= APPLE_PMGR_BUSY; + r->parent_reads = 3; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + KUNIT_EXPECT_EQ(test, r->parent_reads, 0u); + KUNIT_EXPECT_TRUE(test, r->writes[0] & APPLE_PMGR_BUSY); + KUNIT_EXPECT_FALSE(test, r->writes[1] & APPLE_PMGR_BUSY); + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + /* Busy for good: quiesced, but not reset, and the lock is released. */ + r->nwrites = 0; r->parent_stuck = true; r->val |= APPLE_PMGR_BUSY; KUNIT_EXPECT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r->nwrites, 1u); KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_DEV_DISABLE); KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_RESET); KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 0); @@ -665,6 +734,24 @@ static void pmgr_ps_reset_idle_wait_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_DEV_DISABLE); } +/* Without the idle wait, a block that stays busy is reset all the same. */ +static void pmgr_ps_reset_busy_no_idle_wait_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps = pmgr_ps_test_reset_domain(test, "apple-pmgr-ps-reset", &r); + + r->parent_stuck = true; + r->val |= APPLE_PMGR_BUSY; + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_assert(&ps->rcdev, 0), 0); + pmgr_ps_test_expect_writes(test, r, APPLE_PMGR_DEV_DISABLE, + APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_BUSY); + KUNIT_EXPECT_EQ(test, apple_pmgr_reset_status(&ps->rcdev, 0), 1); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_deassert(&ps->rcdev, 0), 0); + KUNIT_ASSERT_EQ(test, apple_pmgr_reset_reset(&ps->rcdev, 0), 0); + KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); +} + static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_power_on_test), KUNIT_CASE(pmgr_ps_power_off_undo_test), @@ -688,6 +775,7 @@ static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_reset_keeps_flags_test), KUNIT_CASE(pmgr_ps_reset_refused_test), KUNIT_CASE(pmgr_ps_reset_idle_wait_test), + KUNIT_CASE(pmgr_ps_reset_busy_no_idle_wait_test), {} }; From 7dddb8cecb7ca1c42b52e5b598761848b3908e3d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:50:58 +1100 Subject: [PATCH 0520/1514] pmdomain: apple: pmgr-pwrstate: run the KUnit suite in CI .kunitconfig.pmgr-pwrstate is in the tree, but no workflow used it: host-tests.yml runs only the host tests, so a green pull request never compiled or ran pmgr-pwrstate-test.c. Add a workflow that runs the suite with kunit.py on arm64 QEMU for every pull request that touches drivers/pmdomain/apple or the Apple SoC headers, as mt7932-kunit.yml does for the Wi-Fi driver. Signed-off-by: Ryan Murray --- .github/workflows/pmgr-pwrstate-kunit.yml | 46 +++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 .github/workflows/pmgr-pwrstate-kunit.yml diff --git a/.github/workflows/pmgr-pwrstate-kunit.yml b/.github/workflows/pmgr-pwrstate-kunit.yml new file mode 100644 index 00000000000000..5abc669e06de35 --- /dev/null +++ b/.github/workflows/pmgr-pwrstate-kunit.yml @@ -0,0 +1,46 @@ +name: PMGR power state KUnit + +# The apple-pmgr-pwrstate KUnit suite (power transitions, apple,no-auto-pm, +# consumers, reset controller) on arm64 QEMU. It runs on an emulated +# register, so it needs no PMGR. + +on: + pull_request: + branches: [integration/aurora, aurora-wip] + paths: + - 'drivers/pmdomain/apple/**' + - 'include/linux/soc/apple/**' + - '.github/workflows/pmgr-pwrstate-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pmgr-pwrstate-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + kunit: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Run the PMGR power state KUnit suite on arm64 QEMU + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig=drivers/pmdomain/apple/.kunitconfig.pmgr-pwrstate \ + --jobs="$(nproc)" --timeout=900 From c56132f4dbc37a9fa603d8367cb63c91022a97c6 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 22:54:51 -0300 Subject: [PATCH 0521/1514] drm/asahi: g17: signal G17P completions before draining reports Every G17P event pass drained the trace and statistics rings before it read the event rings, so each completion's fence waited for the reports the firmware queued ahead of it. On the M4 Pro (T6040, 25G83) a compute completion pass carries a trace and a statistics drain with two core-power observations (an MMIO read of about 0.3 us each), about 0.6 us before the fence is signalled. M5 already reads the event rings first and drains the reports in the worker's next locked step (47f115535c57, "drm/asahi: g17: Reduce M5 job completion latency"): the reports are not scheduling inputs. Do the same on every G17, which also shares one power observation between the two drains, and drop the per-role Transport hooks that only the old order used. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/event.rs | 16 ++---------- drivers/gpu/drm/asahi/g17/runtime/events.rs | 28 +++------------------ 2 files changed, 6 insertions(+), 38 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/event.rs b/drivers/gpu/drm/asahi/g17/event.rs index 7cfcf2ad75283b..63655f8d56489d 100644 --- a/drivers/gpu/drm/asahi/g17/event.rs +++ b/drivers/gpu/drm/asahi/g17/event.rs @@ -2,8 +2,8 @@ //! Event service ordering under the device mutex. A restart ends its role's batch; a worker //! joins preparation leases and services it on a separate turn before continuing the rings. -//! On M5 only the event rings are consumed here: the firmware's trace and statistics reports -//! are drained after the completions this service retires have been signalled +//! Only the event rings are consumed here: the firmware's trace and statistics reports are +//! drained after the completions this service retires have been signalled //! (`Firmware::drain_reports`), so no report queued ahead of a completion delays its fence. use super::{ @@ -16,10 +16,6 @@ use kernel::prelude::*; pub(super) trait Transport { /// The firmware instances of this GPU: the primary, and the secondary where one exists. fn roles(&self) -> &'static [Role]; - fn trace(&mut self, role: Role); - fn statistics(&mut self, role: Role); - /// The reports are drained after the pass's completions are signalled (M5). - fn reports_after_signal(&self) -> bool; fn drain( &mut self, role: Role, @@ -111,14 +107,6 @@ pub(super) fn service(host: &mut H) -> Result { return Ok(Pending::default()); } host.observe_render_releases()?; - if !host.reports_after_signal() { - for &role in host.roles() { - host.trace(role); - } - for &role in host.roles() { - host.statistics(role); - } - } let mut masks = [0; 2]; if !host.recovery().pending() { let mut settled = false; diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index be13a089f7a0fb..cf235fd44dd779 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -30,23 +30,6 @@ impl event::Transport for Service<'_> { fn roles(&self) -> &'static [Role] { self.firmware.roles() } - fn reports_after_signal(&self) -> bool { - self.firmware.init.is_m5() - } - fn trace(&mut self, role: Role) { - let firmware = &mut *self.firmware; - firmware - .rings - .drain_trace(&firmware.primary.state.shared.dev, &firmware.init, role); - } - fn statistics(&mut self, role: Role) { - let firmware = &mut *self.firmware; - firmware.observe_statistics_power(); - firmware - .rings - .drain_statistics(&firmware.primary.state.shared.dev, &firmware.init, role); - firmware.observe_statistics_power(); - } fn drain( &mut self, role: Role, @@ -337,9 +320,8 @@ impl Firmware { Ok(()) } - /// Drains every role's trace ring, then their statistics rings. On M5 the event worker calls - /// this after it has signalled the completions of its pass: the reports are not scheduling - /// inputs. + /// Drains every role's trace ring, then their statistics rings. The event worker calls this + /// after it has signalled the completions of its pass: the reports are not scheduling inputs. fn drain_reports(&mut self) { let dev = &self.primary.state.shared.dev; for &role in self.roles() { @@ -558,10 +540,8 @@ impl crate::g17::Shared { if self.crashed.load(core::sync::atomic::Ordering::Acquire) { return Err(EIO); } - if firmware.init.is_m5() { - // The completions above are signalled; the reports that arrived with them come after. - firmware.drain_reports(); - } + // The completions above are signalled; the reports that arrived with them come after. + firmware.drain_reports(); if recover { firmware.service_runtime_recovery(deferred)?; if !firmware.recovery.pending() From 99b0b4cd5fea8f0bd204b7826070e5b3d527a6f9 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 22:54:39 -0300 Subject: [PATCH 0522/1514] drm/asahi: g17: read the core power register only after an idle-off gap Every G17 publication read the GPU's core power register to notice a gating before its work woke the cores. On the M4 Pro that MMIO read takes about 0.3 us of the ~6 us submit ioctl, ahead of the doorbell. The firmware gates the cores only after they have been idle for its idle-off delay (power::FIRMWARE_IDLE_OFF_MS), counted from the last job, which completes after its own publication. A publication less than that delay after the previous one therefore cannot follow a gating. Read the register only when the gap since the last publication reaches the delay. The publication time was already kept for the firmware_reports view; sleep and recovery still invalidate the statistics on their own. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/port.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 2a535f81429c8b..b295835f901593 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -641,20 +641,29 @@ impl Port { } pub(super) fn note_gpu_activity(&self) { - // Observe gating before activity can wake the cores. A lockless + let now = super::now_ns(); + // The firmware gates the cores only after they idled for its idle-off delay, which + // follows the last job, so a publication within that delay of the previous one cannot + // follow a gating: skip the power register read (a few hundred ns) on back-to-back work. + // A direct publisher notes itself before it may fall back to its scheduler; a fallback + // published past the delay can then miss a gating, costing one statistics sample. + let idle_off_ns = u64::from(super::power::FIRMWARE_IDLE_OFF_MS) * 1_000_000; + let previous = self.last_submission_ns.load(Ordering::Relaxed); + let recent = now.saturating_sub(previous) < idle_off_ns; + // Otherwise observe gating before activity can wake the cores. A lockless // publisher cannot clear the decoder under the device mutex; this // epoch makes both the next drain and the next reader discard it. - if self - .regs - .as_ref() - .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) + if !recent + && self + .regs + .as_ref() + .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) { self.statistics_epoch.fetch_add(1, Ordering::Release); } - let now_ns = super::now_ns(); - self.last_submission_ns.store(now_ns, Ordering::Relaxed); + self.last_submission_ns.store(now, Ordering::Relaxed); self.demand.set_active(true); - self.report_busy(now_ns); + self.report_busy(now); } pub(super) fn write_power(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { From 02370c0d89cde9e6e3d9bd63ded16c52c7e9a0e2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 21:08:05 -0500 Subject: [PATCH 0523/1514] 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 f1aa0f417c028f..70e250a3b8ef74 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 413c2be0ecef23..5a7aca6dd0ab2f 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 65ddaa0adcccd3d635eae59ec704279b39242392 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 21:50:30 +0000 Subject: [PATCH 0524/1514] iio: aop_motion: calibrate once per boot and idle-stop direct reads Commit 9538a1d2111f ("iio: aop_motion: run the reports only while someone reads them") stopped the AOP accelerometer and gyroscope reports when nobody reads them, saving ~100 AP wakeups/s on an idle desktop. However, its direct-read path calls Control::start() and Control::stop() around every individual sysfs axis read, and start() unconditionally resends all three calibration packets (properties 75, 76 and 77) before setting the report interval. On T6041 (M4 Max, J616C), Chromium polling the raw X/Y/Z sysfs channels at 25-60 Hz drives ~73 start/stop cycles/s (~365 EPIC RPCs/s). On every start, properties 75 and 76 return kIOReturnUnsupported (0xe00002c7) while property 77 is re-accepted, logging "2 of 3 calibration packets kept from an earlier start" over 1,200 times in 17 seconds until the AOP firmware crashes on endpoint 0x24, wedging ALS and audio for the rest of the boot. Keep the 0 Hz idle behaviour while eliminating both the calibration rewrite storm and per-axis start/stop thrashing: - Track calibration state in Stream so the three calibration packets are sent once at probe, and subsequent starts for buffers, direct reads and s2idle resume only write PROP_INTERVAL. On s2idle (!pm_suspend_via_firmware()), the AOP core does nothing so calibration stays valid. Across firmware suspend (pm_suspend_via_firmware()), hibernation and restore (PM_POST_HIBERNATION / PM_POST_RESTORE), clear calibrated and active conservatively so calibration is sent once on the next start (on firmwares that kept it, packets 75/76 return STATUS_UNSUPPORTED benignly once). Downgrade the kept-packets log message from dev_info! to dev_dbg!. - Hold direct-read reports active for a 2 s idle window via a DelayedWork item on system_dfl_wq. Back-to-back X/Y/Z reads and polling callers share the running 50 Hz stream and extend the deadline with no extra EPIC calls, while quiet periods return the AOP to interval 0. - Back off direct reads for DIRECT_IDLE_MS after a failed start so a polling client cannot hammer a failing service or spam refused() logs; buffer enable, sleep transitions and shutdown clear the backoff. - Only clear active after stop_reports() succeeds, and park on PM_RESTORE_PREPARE alongside suspend/hibernation prepare. Cancel and join the idle work synchronously with the stream mutex dropped on sleep prepare (cancel_delayed_work_sync) and permanently disable it on unbind or a failed iio.register() in probe (disable_delayed_work_sync), reclaiming any pending Arc reference cleanly. - Extend the host selftest in tools/testing/selftests/drivers/apple/aop-motion.py to cover the production Stream state machine (including failed-start backoff and failed-stop / reset_cal handling) and update Documentation/iio/aop-sensors.rst. Fixes: 9538a1d2111f ("iio: aop_motion: run the reports only while someone reads them") Suggested-by: Ryan Murray Signed-off-by: AxxzyWasTaken --- Documentation/iio/aop-sensors.rst | 10 +- drivers/iio/common/aop_sensors/aop_motion.rs | 325 +++++++++++++++--- .../selftests/drivers/apple/aop-motion.py | 226 +++++++++++- 3 files changed, 513 insertions(+), 48 deletions(-) diff --git a/Documentation/iio/aop-sensors.rst b/Documentation/iio/aop-sensors.rst index dd00cb84e2709f..3dcdce2da440fd 100644 --- a/Documentation/iio/aop-sensors.rst +++ b/Documentation/iio/aop-sensors.rst @@ -52,8 +52,14 @@ them; the mapping to the machine's axes is not established yet. A raw read before the first sample returns ``ENODATA``. Both devices have a buffer that takes X, Y and Z together, with an optional -timestamp taken when the report arrives. The reports stop when the system -goes to sleep and start again, with the calibration resent, when it wakes. +timestamp taken when the report arrives. Reports stay off while nobody reads +them: enabling the buffer starts them and disabling it stops them, while direct +sysfs reads start them on demand and stop them again once reads go quiet. A +failed direct-read start backs off for the same idle window so polling clients +cannot hammer a failing service. The calibration packets are sent once at probe +and conservatively again after firmware suspend, hibernation or restore, rather +than on every start or s2idle resume. Around system sleep any active stream is +stopped and restored on wake only if a buffer is still enabled. If both devices bind but every raw read returns ``ENODATA``, check the AOP core's ``nCal`` boot argument for the SoC. The T6040 firmware accepts the diff --git a/drivers/iio/common/aop_sensors/aop_motion.rs b/drivers/iio/common/aop_sensors/aop_motion.rs index fa72bce5dbecbd..2300bbb38680ab 100644 --- a/drivers/iio/common/aop_sensors/aop_motion.rs +++ b/drivers/iio/common/aop_sensors/aop_motion.rs @@ -8,10 +8,11 @@ //! three calibration packets and a report interval. //! //! The reports run only while someone reads them: while a buffer is enabled, -//! or for the length of one direct read. With nobody reading they stay off, -//! as macOS keeps them (its accel and gyro drivers sit at report interval 0 on -//! an idle desktop), so the AOP does not wake the application processor 50 -//! times a second per sensor. +//! or until direct reads go quiet for a short idle window. Calibration is sent +//! once per AOP boot (not on every start), and with nobody reading the reports +//! stay off, as macOS keeps them (its accel and gyro drivers sit at report +//! interval 0 on an idle desktop), so the AOP does not wake the application +//! processor 50 times a second per sensor. use core::{ ffi::{c_int, c_void}, @@ -22,7 +23,7 @@ use core::{ use kernel::{ bindings, c_str, device::{self, Core}, - module_platform_driver, new_mutex, new_spinlock, of, platform, + module_platform_driver, new_delayed_work, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ @@ -30,8 +31,9 @@ use kernel::{ atomic::{Atomic, Relaxed}, Arc, Mutex, SpinLock, }, - time::{delay::fsleep, Delta}, + time::{self, delay::fsleep, Delta, Instant, Monotonic}, types::{ForeignOwnable, Opaque}, + workqueue::{self, impl_has_delayed_work, DelayedWork, Work, WorkItem}, }; /// The EPIC notification that writes a property of a sensor service. @@ -43,6 +45,10 @@ const INTERVAL_US: u32 = 20_000; /// How long a direct read waits for the first report of a fresh start. const FIRST_SAMPLE_MS: i64 = 200; const FIRST_SAMPLE_POLL_MS: i64 = 5; +/// How long reports stay on after the last direct read without a buffer, so +/// multi-axis X/Y/Z reads and polling callers share one running stream instead +/// of starting and stopping the service on every sysfs read. +const DIRECT_IDLE_MS: i64 = 2_000; /// The calibration properties of a service and the device tree properties the /// bootloader fills them from. They are written in this order, before the /// report interval. @@ -142,17 +148,101 @@ fn location0_packet(prop: &[u8]) -> Option<&[u8]> { None } -/// Who wants the reports of a service. -#[derive(Default)] -struct Stream { +/// What a stream state change requires from the service. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SyncAction { + None, + /// Enable reports; send calibration packets first when `calibrate` is true. + Start { + calibrate: bool, + }, + Stop, +} + +/// Outcome of checking the direct-read idle deadline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum IdleStep { + /// No direct-read hold to expire. + Ignore, + /// More reads extended the deadline; re-arm the work for this many ms. + RearmMs(u32), + /// The deadline passed; stop the reports if nothing else wants them. + Expire, +} + +/// Who wants the reports of a service and whether calibration has already been +/// sent in this AOP boot. +struct Stream { + /// Calibration has been accepted or confirmed held in this AOP boot. + calibrated: bool, /// A buffer is enabled. buffer_on: bool, + /// Reports are held on for recent direct reads until this deadline. + direct_until: Option, + /// A start for a direct read failed with this error; direct reads return + /// it without another try until this deadline. + failed_until: Option<(T, Error)>, /// Set across system sleep and after unbind: no reports. parked: bool, - /// The reports were started for the buffer. + /// The reports are currently enabled (interval != 0). active: bool, } +impl Stream { + const fn new() -> Self { + Self { + calibrated: false, + buffer_on: false, + direct_until: None, + failed_until: None, + parked: false, + active: false, + } + } + + fn want(&self) -> bool { + !self.parked && (self.buffer_on || self.direct_until.is_some()) + } + + fn next_action(&self) -> SyncAction { + match (self.want(), self.active) { + (true, false) => SyncAction::Start { + calibrate: !self.calibrated, + }, + (false, true) => SyncAction::Stop, + _ => SyncAction::None, + } + } + + /// Evaluates the direct-read idle deadline given the milliseconds left + /// until it expires (`<= 0` once expired). + fn check_idle(&mut self, remaining_ms: i64) -> IdleStep { + if self.direct_until.is_none() { + return IdleStep::Ignore; + } + if self.parked || self.buffer_on { + self.direct_until = None; + return IdleStep::Ignore; + } + if remaining_ms > 0 { + IdleStep::RearmMs(remaining_ms.clamp(1, DIRECT_IDLE_MS) as u32) + } else { + self.direct_until = None; + IdleStep::Expire + } + } + + /// Returns the error of a failed start for as long as direct reads back + /// off from it, given the milliseconds left until they may try again + /// (`<= 0` once they may). + fn check_backoff(&mut self, remaining_ms: i64) -> Option { + if remaining_ms <= 0 { + self.failed_until = None; + } + self.failed_until.as_ref().map(|(_, e)| *e) + } +} + /// Starts and stops the reports of one service. #[pin_data] struct Control { @@ -162,7 +252,14 @@ struct Control { packets: [KVec; 3], /// Serializes starting and stopping the reports. #[pin] - stream: Mutex, + stream: Mutex>>, + /// Stops direct-read reports once reads go quiet. + #[pin] + idle_work: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Control { self.idle_work } } impl Control { @@ -190,7 +287,8 @@ impl Control { aop, service, packets, - stream <- new_mutex!(Stream::default()), + stream <- new_mutex!(Stream::new()), + idle_work <- new_delayed_work!("Control::idle_work"), }), GFP_KERNEL, ) @@ -206,6 +304,8 @@ impl Control { .epic_call(&self.service, SUBTYPE_SET_PROPERTY, &msg) } + /// Direct reads back off after a failed start, so they log this at most + /// once per `DIRECT_IDLE_MS`. fn refused(&self, prop: u32, status: u32) -> Error { dev_err!( self.dev, @@ -223,8 +323,10 @@ impl Control { } } - /// Sends the calibration, then the interval that starts the reports. - fn start(&self) -> Result { + /// Sends the three calibration packets. The firmware keeps calibration for + /// the whole AOP boot, so this runs once at probe and conservatively again + /// after firmware suspend, hibernation or restore. + fn calibrate(&self) -> Result { let mut held = 0; for ((prop, _), packet) in CALIBRATION.iter().zip(self.packets.iter()) { let status = self.write(*prop, packet)?; @@ -235,40 +337,88 @@ impl Control { } } if held > 0 { - dev_info!( + dev_dbg!( self.dev, "{} of {} calibration packets kept from an earlier start\n", held, CALIBRATION.len() ); } + Ok(()) + } + + fn start_reports(&self) -> Result { self.set(PROP_INTERVAL, &INTERVAL_US.to_le_bytes()) } - fn stop(&self) -> Result { + fn stop_reports(&self) -> Result { self.set(PROP_INTERVAL, &0u32.to_le_bytes()) } - /// Starts or stops the buffer's reports to match their users. The caller - /// holds the stream lock. - fn sync_locked(&self, s: &mut Stream) -> Result { - match (s.buffer_on && !s.parked, s.active) { - (true, false) => { - self.start()?; + /// Checks once at probe that the service accepts the calibration and the + /// report interval, then leaves the reports off until someone reads them. + fn probe_init(&self) -> Result { + let mut s = self.stream.lock(); + self.calibrate()?; + s.calibrated = true; + self.start_reports()?; + self.stop_reports() + } + + /// Starts or stops the reports to match their users. The caller holds the + /// stream lock. + fn sync_locked(&self, s: &mut Stream>) -> Result { + match s.next_action() { + SyncAction::Start { calibrate } => { + if calibrate { + self.calibrate()?; + s.calibrated = true; + } + self.start_reports()?; s.active = true; Ok(()) } - (false, true) => { + SyncAction::Stop => { + self.stop_reports()?; s.active = false; - self.stop() + Ok(()) } - _ => Ok(()), + SyncAction::None => Ok(()), + } + } + + fn schedule_idle(self: &Arc, delay_ms: u32) { + let _ = + workqueue::system_dfl().enqueue_delayed(self.clone(), time::msecs_to_jiffies(delay_ms)); + } + + fn stop_idle_sync(self: &Arc, disable: bool) { + // SAFETY: `idle_work` is initialized and pinned in this `Arc`. Both + // helpers cancel pending work and join a running callback; the disable + // variant also prevents any later requeue. + let cancelled = unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(ptr::addr_of!(self.idle_work))); + let delayed = kernel::container_of!(work, bindings::delayed_work, work); + if disable { + bindings::disable_delayed_work_sync(delayed) + } else { + bindings::cancel_delayed_work_sync(delayed) + } + }; + if cancelled { + // SAFETY: A cancelled pending callback owned exactly one `Arc` + // transferred by `enqueue_delayed`. + drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } } fn set_buffer(&self, on: bool) -> Result { let mut s = self.stream.lock(); s.buffer_on = on; + if on { + s.direct_until = None; + s.failed_until = None; + } let ret = self.sync_locked(&mut s); if on && ret.is_err() { // The IIO core does not call predisable after a failed enable. @@ -277,10 +427,56 @@ impl Control { ret } - fn set_parked(&self, parked: bool) -> Result { - let mut s = self.stream.lock(); - s.parked = parked; - self.sync_locked(&mut s) + fn set_parked(self: &Arc, parked: bool, reset_cal: bool) -> Result { + let ret = { + let mut s = self.stream.lock(); + s.parked = parked; + s.failed_until = None; + if parked { + s.direct_until = None; + } else if reset_cal { + s.calibrated = false; + s.active = false; + } + self.sync_locked(&mut s) + }; + if parked { + self.stop_idle_sync(false); + } + ret + } + + fn shutdown(self: &Arc) -> Result { + let ret = { + let mut s = self.stream.lock(); + s.parked = true; + s.direct_until = None; + s.failed_until = None; + self.sync_locked(&mut s) + }; + self.stop_idle_sync(true); + ret + } +} + +impl WorkItem for Control { + type Pointer = Arc; + + fn run(this: Arc) { + let mut s = this.stream.lock(); + let Some(deadline) = s.direct_until else { + return; + }; + let remaining_ms = (deadline - Instant::::now()).as_millis_ceil(); + match s.check_idle(remaining_ms) { + IdleStep::Ignore => {} + IdleStep::RearmMs(delay_ms) => this.schedule_idle(delay_ms), + IdleStep::Expire => { + if let Err(e) = this.sync_locked(&mut s) { + dev_warn!(this.dev, "reports not stopped after idle: {:?}\n", e); + } + } + } } } @@ -312,23 +508,49 @@ struct State { } impl State { - /// Returns the latest sample. Without a buffer the reports are started - /// only for this read and stopped again after it. + /// Returns the latest sample. Without a buffer the reports are started on + /// demand and kept running until direct reads go quiet for + /// `DIRECT_IDLE_MS`. A failed start is not tried again for as long; reads + /// in between return its error. fn read_now(&self) -> Result<[i32; 3]> { - let s = self.control.stream.lock(); - if !s.active { - if s.parked { - return Err(EBUSY); + let mut s = self.control.stream.lock(); + if s.parked { + return Err(EBUSY); + } + if let Some((until, _)) = s.failed_until { + let remaining_ms = (until - Instant::::now()).as_millis_ceil(); + if let Some(e) = s.check_backoff(remaining_ms) { + return Err(e); } + } + let started = !s.active; + if started { // A sample from an earlier start may be stale. self.sample.lock().valid = false; - self.control.start()?; + } + if !s.buffer_on { + s.direct_until = Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + } + if let Err(e) = self.control.sync_locked(&mut s) { + s.direct_until = None; + // Polling readers must not repeat a failing start at their rate. + let until = Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS); + s.failed_until = Some((until, e)); + return Err(e); + } + if started { let mut waited = 0; while waited < FIRST_SAMPLE_MS && !self.sample.lock().valid { fsleep(Delta::from_millis(FIRST_SAMPLE_POLL_MS)); waited += FIRST_SAMPLE_POLL_MS; } - self.control.stop()?; + if !s.buffer_on { + s.direct_until = + Some(Instant::::now() + Delta::from_millis(DIRECT_IDLE_MS)); + } + } + if !s.buffer_on { + self.control.schedule_idle(DIRECT_IDLE_MS as u32); } let sample = *self.sample.lock(); if sample.valid { @@ -690,10 +912,22 @@ unsafe extern "C" fn pm_event( // SAFETY: `nb` is the first field of a registered `PmHook`. let hook = unsafe { &*nb.cast::() }; let ret = match action as u32 { - bindings::PM_SUSPEND_PREPARE | bindings::PM_HIBERNATION_PREPARE => { - hook.control.set_parked(true) + bindings::PM_SUSPEND_PREPARE + | bindings::PM_HIBERNATION_PREPARE + | bindings::PM_RESTORE_PREPARE => hook.control.set_parked(true, false), + // On s2idle the AOP core does nothing so calibration stays valid. + // Across firmware suspend, the AOP may have reset, so clear + // calibration conservatively; firmware that kept it answers packets + // 75/76 with STATUS_UNSUPPORTED once on the next start. + bindings::PM_POST_SUSPEND => { + // SAFETY: Reads the PM core's sleep-transition flag, which stays + // set until the next suspend entry. + let fw_sleep = unsafe { bindings::pm_suspend_via_firmware() }; + hook.control.set_parked(false, fw_sleep) + } + bindings::PM_POST_HIBERNATION | bindings::PM_POST_RESTORE => { + hook.control.set_parked(false, true) } - bindings::PM_POST_SUSPEND | bindings::PM_POST_HIBERNATION => hook.control.set_parked(false), _ => return bindings::NOTIFY_DONE as c_int, }; if let Err(e) = ret { @@ -834,9 +1068,12 @@ impl platform::Driver for IIOAopMotionDriver { let pm = PmHook::new(control.clone())?; // Check once that the service takes the calibration and the interval, // then leave the reports off until someone reads them. - control.start()?; - control.stop()?; - iio.register()?; + control.probe_init()?; + if let Err(e) = iio.register() { + pm.unregister(); + let _ = control.shutdown(); + return Err(e); + } Ok(IIOAopMotionDriver { pm, listener, @@ -847,7 +1084,7 @@ impl platform::Driver for IIOAopMotionDriver { fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { this.pm.unregister(); - let _ = this.control.set_parked(true); + let _ = this.control.shutdown(); this.listener.unregister(); } } diff --git a/tools/testing/selftests/drivers/apple/aop-motion.py b/tools/testing/selftests/drivers/apple/aop-motion.py index a66d26b77810ab..bed5ae1f9d4db3 100755 --- a/tools/testing/selftests/drivers/apple/aop-motion.py +++ b/tools/testing/selftests/drivers/apple/aop-motion.py @@ -27,11 +27,17 @@ def const(source, name): def main(): root = Path(__file__).resolve().parents[5] motion = (root / "drivers/iio/common/aop_sensors/aop_motion.rs").read_text() - parts = [const(motion, "REPORT_LEN"), const(motion, "XYZ_OFFSET"), + parts = ["#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nstruct Error(i32);", + const(motion, "REPORT_LEN"), const(motion, "XYZ_OFFSET"), + const(motion, "DIRECT_IDLE_MS"), block(motion, "fn decode("), block(motion, "fn le_u32("), block(motion, "fn location0_packet("), const(motion, "STATUS_UNSUPPORTED"), - block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum CalStatus"), block(motion, "fn cal_status("), r''' + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum CalStatus"), block(motion, "fn cal_status("), + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum SyncAction"), + block(motion, "#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum IdleStep"), + block(motion, "struct Stream"), + block(motion, "impl Stream"), r''' fn report(prefix: u8, xyz: [i32; 3], suffix: u8) -> Vec { let mut r = vec![prefix; 6]; for v in xyz { @@ -110,6 +116,222 @@ def main(): many[2] = 255; assert_eq!(location0_packet(&many), Some(&a[..])); } +#[test] +fn calibrates_once_and_reuses_direct_stream() { + let mut s = Stream::::new(); + assert!(!s.want()); + assert_eq!(s.next_action(), SyncAction::None); + + // Probe leaves calibration recorded and reports idle. + s.calibrated = true; + + // First direct read (X) starts reports without re-sending calibration. + s.direct_until = Some(2_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // Subsequent Y/Z and polling reads reuse the running stream with no RPCs. + s.direct_until = Some(2_010); + assert_eq!(s.next_action(), SyncAction::None); + assert_eq!(s.check_idle(10), IdleStep::RearmMs(10)); + assert_eq!(s.check_idle(DIRECT_IDLE_MS + 500), IdleStep::RearmMs(DIRECT_IDLE_MS as u32)); + assert!(s.direct_until.is_some()); + + // Once reads go quiet, idle expiry stops the reports. + assert_eq!(s.check_idle(0), IdleStep::Expire); + assert!(s.direct_until.is_none()); + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + assert_eq!(s.next_action(), SyncAction::None); + assert_eq!(s.check_idle(-1), IdleStep::Ignore); +} +#[test] +fn buffer_handoff_and_pm_calibration_policy() { + let mut s = Stream::::new(); + // Uncalibrated buffer start calibrates first. + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Suspend parks without clearing calibration; resume restarts interval only. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + s.parked = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // Hibernation clears calibration so the next start sends it once. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + s.parked = false; + s.calibrated = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Disabling buffer stops immediately. + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); + s.active = false; + + // Direct hold handed off cleanly to buffer; stale idle callback is ignored. + s.direct_until = Some(5_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + s.buffer_on = true; + assert_eq!(s.check_idle(0), IdleStep::Ignore); + assert!(s.direct_until.is_none()); + assert_eq!(s.next_action(), SyncAction::None); + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); +} +/// Counts the starts a sequence of direct reads tries on a failing service. +struct Service { + fail: Option, + starts: u32, +} + +/// One direct read at `now` ms, as `State::read_now()` does it. +fn read(s: &mut Stream, svc: &mut Service, now: i64) -> Result<(), Error> { + if let Some((until, _)) = s.failed_until { + if let Some(e) = s.check_backoff(until - now) { + return Err(e); + } + } + if !s.buffer_on { + s.direct_until = Some(now + DIRECT_IDLE_MS); + } + if let SyncAction::Start { .. } = s.next_action() { + svc.starts += 1; + if let Some(e) = svc.fail { + s.direct_until = None; + s.failed_until = Some((now + DIRECT_IDLE_MS, e)); + return Err(e); + } + s.calibrated = true; + s.active = true; + } + Ok(()) +} +#[test] +fn failed_start_backs_off_direct_reads() { + const EIO: Error = Error(5); + const ETIMEDOUT: Error = Error(110); + let mut s = Stream::::new(); + let mut svc = Service { fail: Some(EIO), starts: 0 }; + + // A 25 Hz poller on a failing service tries one start per idle window + // and gets the error of that start in between. + let mut now = 0; + while now < 10_000 { + assert_eq!(read(&mut s, &mut svc, now), Err(EIO)); + assert!(!s.want()); + now += 40; + } + assert_eq!(svc.starts, (10_000 / DIRECT_IDLE_MS) as u32); + + // The cached error is the one of the latest try. + svc.fail = Some(ETIMEDOUT); + assert_eq!(read(&mut s, &mut svc, 10_000), Err(ETIMEDOUT)); + assert_eq!(read(&mut s, &mut svc, 10_000 + DIRECT_IDLE_MS - 1), Err(ETIMEDOUT)); + assert_eq!(svc.starts, 6); + + // The first read after the window tries again; success ends the backoff. + svc.fail = None; + assert_eq!(read(&mut s, &mut svc, 10_000 + DIRECT_IDLE_MS), Ok(())); + assert_eq!(svc.starts, 7); + assert!(s.failed_until.is_none()); + assert!(s.active); + assert_eq!(read(&mut s, &mut svc, 10_040 + DIRECT_IDLE_MS), Ok(())); + assert_eq!(svc.starts, 7); + + // The deadline itself is the first moment of the next try. + assert_eq!(s.check_backoff(-1), None); + s.failed_until = Some((500, EIO)); + assert_eq!(s.check_backoff(1), Some(EIO)); + assert!(s.failed_until.is_some()); + assert_eq!(s.check_backoff(0), None); + assert!(s.failed_until.is_none()); +} +#[test] +fn buffer_and_sleep_end_the_backoff() { + const EIO: Error = Error(5); + let mut s = Stream::::new(); + let mut svc = Service { fail: Some(EIO), starts: 0 }; + assert_eq!(read(&mut s, &mut svc, 0), Err(EIO)); + assert_eq!(read(&mut s, &mut svc, 40), Err(EIO)); + assert_eq!(svc.starts, 1); + + // Enabling a buffer is a new request: it tries a start of its own, and + // a read under the running buffer is served, as `set_buffer()` does it. + svc.fail = None; + s.buffer_on = true; + s.direct_until = None; + s.failed_until = None; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + assert_eq!(read(&mut s, &mut svc, 80), Ok(())); + assert_eq!(svc.starts, 1); + s.buffer_on = false; + s.active = false; + + // Sleep drops a backoff, as `set_parked()` does it, so the first read + // after resume tries at once. + svc.fail = Some(EIO); + assert_eq!(read(&mut s, &mut svc, 1_000), Err(EIO)); + assert_eq!(svc.starts, 2); + s.parked = true; + s.failed_until = None; + s.parked = false; + s.failed_until = None; + svc.fail = None; + assert_eq!(read(&mut s, &mut svc, 1_040), Ok(())); + assert_eq!(svc.starts, 3); +} +#[test] +fn failed_stop_keeps_active_until_reset_cal() { + let mut s = Stream::::new(); + s.calibrated = true; + s.buffer_on = true; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: false }); + s.active = true; + + // A failed pre-sleep stop leaves `active` true instead of pretending the + // reports stopped, so an s2idle wake with no user retries stopping them. + s.parked = true; + assert_eq!(s.next_action(), SyncAction::Stop); + // Simulate stop_reports() returning Err: `active` stays true. + assert!(s.active); + + // After firmware suspend / hibernation (`reset_cal == true`), both + // `calibrated` and `active` are cleared so a running buffer cleanly + // recalibrates and restarts even if the pre-sleep stop failed. + s.parked = false; + s.calibrated = false; + s.active = false; + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); + s.calibrated = true; + s.active = true; + + // Same for a direct read after a failed stop + `reset_cal`: next read + // recalibrates and starts cleanly. + s.buffer_on = false; + assert_eq!(s.next_action(), SyncAction::Stop); + // Simulate failed stop leaving `active` true. + assert!(s.active); + s.parked = true; + s.direct_until = None; + s.parked = false; + s.calibrated = false; + s.active = false; + assert_eq!(s.next_action(), SyncAction::None); + s.direct_until = Some(2_000); + assert_eq!(s.next_action(), SyncAction::Start { calibrate: true }); +} '''] with tempfile.TemporaryDirectory(prefix="aop-motion-") as tmp: source = Path(tmp) / "test.rs" From 6b6878e84275e4639d3483d4c1e2c5369cd1839d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:20:02 +1100 Subject: [PATCH 0525/1514] wifi: brcmfmac: pcie: check the ring counts before sizing the host index buffer When the firmware keeps the ring indices in host memory, the index buffer is sized from the submission and completion ring counts it reports, while the driver hands out one index per common ring and flowring. A firmware that reports fewer submission rings than common rings plus flowrings, or fewer completion rings than common completion rings, made the driver read and write indices past the end of the buffer. Check both counts before the buffer is allocated and fail the probe with -EINVAL when they are short. Shared RAM versions before 6 derive the counts from the flowring count and always pass. tools/asahi/brcmf-shared-tcm-tests.py now uses the driver's own host index accessors and has controls for host indices; the mutation dma-counts drops the check. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/pcie.c | 9 +++++++++ tools/asahi/brcmf-shared-tcm-tests.py | 20 ++++++++++++++----- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index b70c96508d0914..03ae771f940ffa 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1644,6 +1644,15 @@ static int brcmf_pcie_init_ringbuffers(struct brcmf_pciedev_info *devinfo) } if (devinfo->dma_idx_sz != 0) { + /* The host index arrays hold one index per ring the driver uses */ + if (max_submissionrings < + BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings || + max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) { + brcmf_err(bus, "invalid ring counts: %u submission, %u completion, %u flowrings\n", + max_submissionrings, max_completionrings, + max_flowrings); + return -EINVAL; + } bufsz = (max_submissionrings + max_completionrings) * devinfo->dma_idx_sz * 2; devinfo->idxbuf = dma_alloc_coherent(&devinfo->pdev->dev, bufsz, diff --git a/tools/asahi/brcmf-shared-tcm-tests.py b/tools/asahi/brcmf-shared-tcm-tests.py index 3277d64ac1c0b3..85df62f4c69b3c 100755 --- a/tools/asahi/brcmf-shared-tcm-tests.py +++ b/tools/asahi/brcmf-shared-tcm-tests.py @@ -7,6 +7,7 @@ """ import argparse import json +import os from pathlib import Path import re import subprocess @@ -17,7 +18,7 @@ def function(source, name): - match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32)\s+' + name + + match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:void|int|bool|s32|u16)\s+' + name + r'\([^;]*?\)\s*\{', source, re.M) if not match: raise ValueError('Missing function ' + name) @@ -101,8 +102,6 @@ def define(source, name): static u8 brcmf_pcie_read_tcm8(struct brcmf_pciedev_info *d, u32 a) { in_tcm(d, a, 1); return tcm[a]; } static void brcmf_pcie_write_tcm32(struct brcmf_pciedev_info *d, u32 a, u32 v) { in_tcm(d, a, 4); memcpy(tcm + a, &v, 4); } static void brcmf_pcie_write_tcm16(struct brcmf_pciedev_info *d, u32 a, u16 v) { in_tcm(d, a, 2); memcpy(tcm + a, &v, 2); } -static u16 brcmf_pcie_read_idx(struct brcmf_pciedev_info *d, u32 a) { (void)d; (void)a; return 0; } -static void brcmf_pcie_write_idx(struct brcmf_pciedev_info *d, u32 a, u16 v) { (void)d; (void)a; (void)v; } static struct brcmf_pciedev_info devinfo; static void memcpy_fromio(void *dst, const u8 *src, size_t n) { assert(src >= tcm); in_tcm(&devinfo, (u32)(src - tcm), (u32)n); memcpy(dst, src, n); } @@ -193,6 +192,14 @@ def define(source, name): /* The flowring indices count against the TCM too. */ reset(); assert(!init()); ringinfo()->h2d_w_idx_ptr = TCM_SIZE - 4 * 4; ringinfo()->max_flowrings = 3; assert(rings() == -EINVAL); cases++; + /* Host memory ring indices: one per ring the driver uses, in a buffer sized from the ring counts. */ + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX | BRCMF_PCIE_SHARED_DMA_2B_IDX); + assert(!init() && devinfo.dma_idx_sz == 2 && !rings() && !errs); cases++; + /* Fewer submission or completion rings than the driver uses fail setup. */ + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX); + assert(!init()); ringinfo()->max_submissionrings = 2; assert(rings() == -EINVAL); cases++; + reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX); + assert(!init()); ringinfo()->max_completionrings = 0; assert(rings() == -EINVAL); cases++; /* A console descriptor or buffer outside the TCM leaves the console off; setup goes on. */ reset(); put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, TCM_SIZE - 4); assert(!init() && !devinfo.shared.console.base_addr); cases++; @@ -227,6 +234,8 @@ def define(source, name): '\t\tif (0 && !brcmf_pcie_tcm_range_valid(devinfo->tcm_size,\n\t\t\t\t\t\th2d_w_idx_ptr, h2d_idx_len) ||'), 'flowring-idx': ('\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings) *', '\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS) *'), + 'dma-counts': ('\t\tif (max_submissionrings <\n\t\t BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings ||\n' + '\t\t max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) {', '\t\tif (false) {'), 'console-desc': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\tif (false) {'), 'console-buf': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr,\n' @@ -260,7 +269,7 @@ def main(): defines += '#define BRCMF_NROF_COMMON_MSGRINGS (BRCMF_NROF_H2D_COMMON_MSGRINGS + BRCMF_NROF_D2H_COMMON_MSGRINGS)\n' structs = struct((DRIVER / 'msgbuf.h').read_text(), 'msgbuf_buf_addr') + struct(pcie, 'brcmf_pcie_dhi_ringinfo') body = function((DRIVER / 'pcie.h').read_text(), 'brcmf_pcie_tcm_range_valid') + ''.join( - function(pcie, n) for n in ('brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', + function(pcie, n) for n in ('brcmf_pcie_read_idx', 'brcmf_pcie_write_idx', 'brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', 'brcmf_pcie_init_ringbuffers', 'brcmf_pcie_init_share_ram_info')) if args.mutation: old, new = MUTATIONS[args.mutation] @@ -277,7 +286,8 @@ def run(out): subprocess.run(['clang', '-std=gnu11', '-O1', '-g', '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-Wno-incompatible-function-pointer-types', str(source), '-o', str(exe)], check=True) - result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60) + env = dict(os.environ, ASAN_OPTIONS='abort_on_error=1') + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60, env=env) receipt = {'exit': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr, 'limits': 'Fake TCM and dongle tables; no firmware, PCIe link or DMA proof.'} (out / 'results.json').write_text(json.dumps(receipt, indent=2) + '\n') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 9d64da34935b23..33de9620bd67c6 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -161,7 +161,7 @@ def mutations(flag, names, base, expect=KILL): 'brcmf-roam-tests.py': [(out(), PASS)], 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', - 'flowring-idx', 'console-desc', 'console-buf', 'console-widx', + 'flowring-idx', 'dma-counts', 'console-desc', 'console-buf', 'console-widx', 'console-reinit'), out()), 'brcmf-sae-vendor-tests.py': [(out(), PASS)] + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], From 2c9da3201cd8dc9b4cc6d7d2c834686eef396788 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:20:34 +1100 Subject: [PATCH 0526/1514] wifi: brcmfmac: pcie: read no console when the firmware reports none A console address of 0 means the firmware has no console, but the console setup still read its descriptor at the start of the TCM before the readers ignored it. Skip the reads in that case, and drop a partial console line left from an earlier firmware when the console is set up again. tools/asahi/brcmf-shared-tcm-tests.py gets a control for a firmware without a console; the mutation console-none drops the check. Signed-off-by: Ryan Murray --- drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c | 4 +++- tools/asahi/brcmf-shared-tcm-tests.py | 9 +++++++-- tools/asahi/run-host-tests.py | 4 ++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index 03ae771f940ffa..ac52ec21ff4ed0 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1142,9 +1142,11 @@ static void brcmf_pcie_bus_console_init(struct brcmf_pciedev_info *devinfo) console->base_addr = brcmf_pcie_read_tcm32(devinfo, addr); console->bufsize = 0; console->read_idx = 0; + console->log_idx = 0; console->scan_idx = 0; console->scan_len = 0; - if (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr, + if (!console->base_addr || + !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr, BRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) { console->base_addr = 0; return; diff --git a/tools/asahi/brcmf-shared-tcm-tests.py b/tools/asahi/brcmf-shared-tcm-tests.py index 85df62f4c69b3c..ecf9b3267cb217 100755 --- a/tools/asahi/brcmf-shared-tcm-tests.py +++ b/tools/asahi/brcmf-shared-tcm-tests.py @@ -207,6 +207,10 @@ def define(source, name): assert(!init() && !devinfo.shared.console.base_addr && !devinfo.shared.console.bufsize); cases++; reset(); put32(CONS + BRCMF_CONSOLE_BUFSIZE_OFFSET, 0xffffffff); assert(!init() && !devinfo.shared.console.base_addr); cases++; + /* No console reported: nothing is read at address 0, and a partial line is dropped. */ + reset(); assert(!init()); devinfo.shared.console.log_idx = 5; put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, 0); + reads = 0; brcmf_pcie_bus_console_init(&devinfo); + assert(reads == 1 && !devinfo.shared.console.base_addr && !devinfo.shared.console.log_idx); cases++; /* A write index at or past the buffer size is not followed. */ reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 64); assert(!init() && devinfo.shared.console.read_idx == 0); cases++; reset(); put32(CONS + BRCMF_CONSOLE_WRITEIDX_OFFSET, 0x10000); assert(!init()); cases++; @@ -236,8 +240,9 @@ def define(source, name): '\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS) *'), 'dma-counts': ('\t\tif (max_submissionrings <\n\t\t BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings ||\n' '\t\t max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) {', '\t\tif (false) {'), - 'console-desc': ('\tif (!brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' - '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\tif (false) {'), + 'console-desc': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' + '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\t false) {'), + 'console-none': ('\tif (!console->base_addr ||\n', '\tif (false ||\n'), 'console-buf': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->buf_addr,\n' '\t\t\t\t\tconsole->bufsize)) {', '\t false) {'), 'console-widx': ('\tif (newidx >= console->bufsize || console->read_idx >= console->bufsize)\n\t\treturn;\n', ''), diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 33de9620bd67c6..e9cabac7e1b797 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -161,8 +161,8 @@ def mutations(flag, names, base, expect=KILL): 'brcmf-roam-tests.py': [(out(), PASS)], 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', - 'flowring-idx', 'dma-counts', 'console-desc', 'console-buf', 'console-widx', - 'console-reinit'), out()), + 'flowring-idx', 'dma-counts', 'console-desc', 'console-none', + 'console-buf', 'console-widx', 'console-reinit'), out()), 'brcmf-sae-vendor-tests.py': [(out(), PASS)] + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], 'brcmf-suspend-tests.py': [(out(), PASS)] From 7709c6ec1217f8169aaeb889880518ac54bf57b1 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 18:20:53 -0800 Subject: [PATCH 0527/1514] soc: apple: aop: run the KUnit suites in CI The AOP driver has two KUnit suites (apple_aop_ring and apple_aop_services), but no CI job builds or runs them: the SEP source workflow's kunit job uses sep.kunitconfig with an apple_sep* filter, and its rust-build job compiles only apple-sep.o. A regression in either AOP suite would not show up on a pull request. Add drivers/soc/apple/aop.kunitconfig with the minimal options needed to build APPLE_AOP=y on arm64, and add a step in the sep-source.yml kunit job that runs both suites on arm64 QEMU with the apple_aop* filter in a separate build directory (.kunit-aop). Signed-off-by: Jeff Queisser --- .github/workflows/sep-source.yml | 9 +++++++++ drivers/soc/apple/aop.kunitconfig | 10 ++++++++++ 2 files changed, 19 insertions(+) create mode 100644 drivers/soc/apple/aop.kunitconfig diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 3f824af0d4f61c..c3fb83200c0113 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -144,6 +144,15 @@ jobs: --make_options LLVM=1 \ --kunitconfig=drivers/soc/apple/sep.kunitconfig \ --jobs="$(nproc)" --timeout=900 'apple_sep*' + - name: Run the Apple AOP KUnit suites on arm64 QEMU + env: + LIBCLANG_PATH: /usr/lib/llvm-18/lib + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --build_dir=.kunit-aop \ + --make_options LLVM=1 \ + --kunitconfig=drivers/soc/apple/aop.kunitconfig \ + --jobs="$(nproc)" --timeout=900 'apple_aop*' dwc3-atc-compile: name: DWC3/ATC ${{ matrix.profile }} diff --git a/drivers/soc/apple/aop.kunitconfig b/drivers/soc/apple/aop.kunitconfig new file mode 100644 index 00000000000000..ce8c3c6151b97a --- /dev/null +++ b/drivers/soc/apple/aop.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_RUST=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_IOMMU_SUPPORT=y +CONFIG_PM=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_AOP=y From a0837b9f9b42021b9ce5c81848b666738ecbb12a Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 18:20:55 -0800 Subject: [PATCH 0528/1514] soc: apple: aop: cover all three claim-release paths in the host test AopData::register_service() and AopServiceRegisterWork::run() release a service's claim on three failure paths: work-item allocation failure, subdevice-slot reservation failure, and platform_device_register_full() returning an error pointer or NULL. Previously tools/asahi/aop-service-tests.py only built register_service() with an infallible work-item constructor, so deleting any of those three releases left both the host test and the KUnit suites green. Extend tools/asahi/aop-service-tests.py to also build and run the production AopServiceRegisterWork::run() against host stand-ins, with fault injection for work-item allocation, subdevice-slot reservation, and platform device registration (both error pointer and NULL), plus a lock-order assertion that subdevices is dropped before registration_gate is locked. Verify that each failed registration releases its claim so a subsequent announcement registers the device, while keeping repeats refused once registration succeeds. Add --mutation modes (no-work-release, no-slot-release, no-register-release) that drop each release line from the extracted production source and require its control to fail, and register them in tools/asahi/run-host-tests.py. Signed-off-by: Jeff Queisser --- tools/asahi/aop-service-tests.py | 342 ++++++++++++++++++++++++++++--- tools/asahi/run-host-tests.py | 3 +- 2 files changed, 315 insertions(+), 30 deletions(-) diff --git a/tools/asahi/aop-service-tests.py b/tools/asahi/aop-service-tests.py index 2b7faa55a50866..735c27dcb1c36c 100644 --- a/tools/asahi/aop-service-tests.py +++ b/tools/asahi/aop-service-tests.py @@ -2,9 +2,11 @@ # SPDX-License-Identifier: GPL-2.0-only OR MIT """Run the production AOP service registration against host mocks. -Each check announces services to AopData::register_service and counts the -child-device registrations it queues. A service gets one device however -often, and under whatever other channel or name, it is announced again. +Each check announces services to AopData::register_service and runs +AopServiceRegisterWork::run to count the child-device registrations it queues +and completes. A service gets one device however often, and under whatever +other channel or name, it is announced again, and any registration failure +releases the claim so the next announcement tries again. """ import argparse from pathlib import Path @@ -18,6 +20,30 @@ AOP = 'drivers/soc/apple/aop.rs' SERVICES = 'drivers/soc/apple/aop_services.rs' +MUTATIONS = { + 'no-work-release': ( + 'register', + 'claims.release(svc);', + 0, + ['work-item allocation failure releases the claim'], + ), + 'no-slot-release': ( + 'run', + 'this.data.registration_gate.lock().release(this.service);', + 0, + ['subdevice slot allocation failure releases the claim'], + ), + 'no-register-release': ( + 'run', + 'this.data.registration_gate.lock().release(this.service);', + 1, + [ + 'platform device registration error releases the claim', + 'null platform device return releases the claim', + ], + ), +} + def read(ref, path): if ref is None: @@ -41,7 +67,24 @@ def block(source, marker): return source[start:end] -def program(ref): +def drop_occurrence(source, needle, which, expected_count): + positions = [] + pos = 0 + while True: + idx = source.find(needle, pos) + if idx < 0: + break + positions.append(idx) + pos = idx + len(needle) + if len(positions) != expected_count: + raise SystemExit( + f'mutation target {needle!r}: found {len(positions)} occurrences, expected {expected_count}' + ) + idx = positions[which] + return source[:idx] + source[idx + len(needle):] + + +def program(ref, mutation=None): aop = read(ref, AOP) services = read(ref, SERVICES) parts = [STUBS] @@ -54,31 +97,82 @@ def program(ref): parts.append('mod aop_services {\nuse super::*;\n' + body + '\n}\n') parts.append('type Gate = aop_services::Claims;\n' 'fn gate() -> Gate { aop_services::Claims::new().unwrap() }\n') - parts.append('impl AopData {\n' + block(aop, ' fn register_service(') + '\n}\n') + reg_fn = block(aop, ' fn register_service(') + run_fn = block(aop, ' fn run(this: Pin>)') + if mutation is not None: + target, needle, which, _ = MUTATIONS[mutation] + if target == 'register': + reg_fn = drop_occurrence(reg_fn, needle, which, 1) + else: + run_fn = drop_occurrence(run_fn, needle, which, 2) + parts.append('impl AopServiceRegisterWork {\n' + run_fn + '\n}\n') + parts.append('impl AopData {\n' + reg_fn + '\n}\n') parts.append(CHECKS) return '\n'.join(parts) STUBS = r''' -#![allow(dead_code, unused_imports, unused_macros)] -use std::ffi::CStr; +#![allow(dead_code, non_camel_case_types, unused_imports, unused_macros)] +use std::collections::VecDeque; +use std::ffi::{c_char, c_void, CStr}; +use std::mem; +use std::ops::{Deref, DerefMut}; use std::pin::Pin; -use std::sync::atomic::Ordering::Acquire; +use std::ptr::{self, NonNull}; +use std::sync::atomic::{ + AtomicBool, AtomicUsize, + Ordering::{Acquire, SeqCst}, +}; use std::sync::Arc; +type KBox = Box; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Error(i32); const ENOMEM: Error = Error(-12); const EEXIST: Error = Error(-17); +const EINVAL: Error = Error(-22); const ENOSPC: Error = Error(-28); type Result = std::result::Result; const GFP_KERNEL: u32 = 0; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct EPICService { pub channel: u32, pub endpoint: u8 } +pub struct PushError(pub T); +static FAIL_WORK_NEW: AtomicUsize = AtomicUsize::new(0); +static FAIL_SUBDEV_RESERVE: AtomicUsize = AtomicUsize::new(0); +static REGISTER_CALLS: AtomicUsize = AtomicUsize::new(0); +static NEXT_PDEV: AtomicUsize = AtomicUsize::new(1); +static UNREGISTER_CALLS: AtomicUsize = AtomicUsize::new(0); +static SUBDEVICES_LOCKED: AtomicBool = AtomicBool::new(false); +#[derive(Clone, Copy)] +enum RegisterOutcome { Ok, ErrPtr(i32), Null } +static REGISTER_OUTCOMES: std::sync::Mutex> = + std::sync::Mutex::new(VecDeque::new()); +static DEV_ERRS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +fn take_fail(counter: &AtomicUsize) -> bool { + let mut cur = counter.load(SeqCst); + while cur > 0 { + match counter.compare_exchange(cur, cur - 1, SeqCst, SeqCst) { + Ok(_) => return true, + Err(next) => cur = next, + } + } + false +} +fn push_register_outcome(outcome: RegisterOutcome) { + REGISTER_OUTCOMES.lock().unwrap().push_back(outcome); +} pub struct KVec { items: Vec, cap: usize } impl KVec { + fn new() -> Self { Self { items: Vec::new(), cap: 0 } } fn with_capacity(cap: usize, _flags: u32) -> Result { Ok(Self { items: Vec::new(), cap }) } - fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { - if self.items.len() < self.cap { self.items.push(v); Ok(()) } else { Err(v) } + fn reserve(&mut self, additional: usize, _flags: u32) -> Result<()> { + if take_fail(&FAIL_SUBDEV_RESERVE) { + return Err(ENOMEM); + } + self.cap = self.cap.max(self.items.len() + additional); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), PushError> { + if self.items.len() < self.cap { self.items.push(v); Ok(()) } else { Err(PushError(v)) } } fn iter(&self) -> std::slice::Iter<'_, T> { self.items.iter() } fn retain(&mut self, f: impl FnMut(&mut T) -> bool) { self.items.retain_mut(f) } @@ -89,20 +183,114 @@ def program(ref): match CStr::from_bytes_with_nul(concat!($s, "\0").as_bytes()) { Ok(c) => c, Err(_) => panic!() } }; } -struct Mutex(std::sync::Mutex); -impl Mutex { fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } } +macro_rules! dev_err { + ($dev:expr, $($arg:tt)+) => {{ + let _ = &$dev; + DEV_ERRS.lock().unwrap().push(format!($($arg)+)); + }}; +} +trait CStrExt { fn as_char_ptr(&self) -> *const c_char; } +impl CStrExt for CStr { fn as_char_ptr(&self) -> *const c_char { self.as_ptr() } } +struct GateMutex(std::sync::Mutex); +impl GateMutex { + fn lock(&self) -> std::sync::MutexGuard<'_, T> { + assert!(!SUBDEVICES_LOCKED.load(SeqCst), "registration_gate locked while holding subdevices"); + self.0.lock().unwrap() + } +} +struct SubdevGuard<'a, T>(std::sync::MutexGuard<'a, T>); +impl Deref for SubdevGuard<'_, T> { + type Target = T; + fn deref(&self) -> &T { &self.0 } +} +impl DerefMut for SubdevGuard<'_, T> { + fn deref_mut(&mut self) -> &mut T { &mut self.0 } +} +impl Drop for SubdevGuard<'_, T> { + fn drop(&mut self) { SUBDEVICES_LOCKED.store(false, SeqCst); } +} +struct SubdevMutex(std::sync::Mutex); +impl SubdevMutex { + fn lock(&self) -> SubdevGuard<'_, T> { + let g = self.0.lock().unwrap(); + SUBDEVICES_LOCKED.store(true, SeqCst); + SubdevGuard(g) + } +} struct Atomic(std::sync::Mutex); impl Atomic { fn load(&self, _: std::sync::atomic::Ordering) -> T { *self.0.lock().unwrap() } } -struct Queue(std::sync::Mutex>); +mod bindings { + use super::*; + pub const PLATFORM_DEVID_AUTO: i32 = -2; + pub struct device; + pub struct platform_device; + pub struct platform_device_info { + pub parent: *mut device, + pub name: *const c_char, + pub id: i32, + pub res: *mut c_void, + pub num_res: u32, + pub data: *const c_void, + pub size_data: usize, + pub dma_mask: u64, + pub fwnode: *mut c_void, + pub swnode: *mut c_void, + pub properties: *mut c_void, + pub of_node_reused: bool, + } + pub unsafe fn platform_device_register_full( + _info: *const platform_device_info, + ) -> *mut platform_device { + REGISTER_CALLS.fetch_add(1, SeqCst); + match REGISTER_OUTCOMES.lock().unwrap().pop_front().unwrap_or(RegisterOutcome::Ok) { + RegisterOutcome::Ok => (NEXT_PDEV.fetch_add(1, SeqCst) * 16) as *mut platform_device, + RegisterOutcome::ErrPtr(errno) => (errno as isize) as *mut platform_device, + RegisterOutcome::Null => ptr::null_mut(), + } + } +} +fn from_err_ptr(p: *mut T) -> Result<*mut T> { + let addr = p as usize as isize; + if (-4095..=-1).contains(&addr) { + Err(Error(addr as i32)) + } else { + Ok(p) + } +} +struct ChildDevice(NonNull); +impl ChildDevice { + fn unregister(self) { UNREGISTER_CALLS.fetch_add(1, SeqCst); } +} +struct FwNode; +impl FwNode { + fn get_child_by_name(&self, _name: &CStr) -> Option { None } + fn as_raw(&self) -> *mut c_void { ptr::null_mut() } +} +struct Queue(std::sync::Mutex>>>); impl Queue { fn enqueue(&self, work: Pin>) { - self.0.lock().unwrap().push((work.name.to_str().unwrap().into(), work.service)); + self.0.lock().unwrap().push(work); + } + fn drain(&self) { + loop { + let items: Vec<_> = { + let mut q = self.0.lock().unwrap(); + if q.is_empty() { break; } + q.drain(..).collect() + }; + for work in items { + AopServiceRegisterWork::run(work); + } + } } } -struct AopServiceRegisterWork { name: &'static CStr, service: EPICService } +struct AopServiceRegisterWork { name: &'static CStr, data: Arc, service: EPICService } impl AopServiceRegisterWork { - fn new(name: &'static CStr, _data: Arc, service: EPICService) -> Result>> { - Ok(Box::pin(Self { name, service })) + fn new(name: &'static CStr, data: Arc, service: EPICService) -> Result>> { + if take_fail(&FAIL_WORK_NEW) { + return Err(ENOMEM); + } + Ok(Box::pin(Self { name, data, service })) } } macro_rules! fmt { ($($t:tt)*) => { format_args!($($t)*) }; } @@ -112,12 +300,20 @@ def program(ref): fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&String::from_utf8_lossy(self.0)) } } struct Device; +impl Device { + fn fwnode(&self) -> Option { None } + fn as_raw(&self) -> *mut bindings::device { ptr::null_mut() } +} struct AFKEndpoint { index: u8, dropped: Vec } impl AFKEndpoint { fn drop_message(&mut self, _dev: &Device, why: std::fmt::Arguments<'_>) { self.dropped.push(why.to_string()); } } struct AopData { - dev: Device, registration_gate: Mutex, removing: Atomic, registration_queue: Queue, + dev: Device, + registration_gate: GateMutex, + removing: Atomic, + registration_queue: Queue, + subdevices: SubdevMutex>, } ''' @@ -126,19 +322,24 @@ def program(ref): fn data(removing: bool) -> Arc { Arc::new(AopData { dev: Device, - registration_gate: Mutex(std::sync::Mutex::new(gate())), + registration_gate: GateMutex(std::sync::Mutex::new(gate())), removing: Atomic(std::sync::Mutex::new(removing)), registration_queue: Queue(std::sync::Mutex::new(Vec::new())), + subdevices: SubdevMutex(std::sync::Mutex::new(KVec::new())), }) } -fn announce_logged(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> Vec { +fn announce_result(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> (Result<()>, Vec) { let mut ep = AFKEndpoint { index: endpoint, dropped: Vec::new() }; - // An error return is logged by the caller; the queue and the endpoint's dropped messages are what matter here. - let _ = d.clone().register_service(&mut ep, channel, name); - ep.dropped + let res = d.clone().register_service(&mut ep, channel, name); + (res, ep.dropped) +} +fn announce_logged(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) -> Vec { + announce_result(d, endpoint, channel, name).1 } fn announce(d: &Arc, endpoint: u8, channel: u32, name: &[u8]) { announce_logged(d, endpoint, channel, name); } fn queued(d: &Arc) -> usize { d.registration_queue.0.lock().unwrap().len() } +fn drain(d: &Arc) { d.registration_queue.drain(); } +fn registered(d: &Arc) -> usize { d.subdevices.lock().len() } fn main() { let mut fixed = Vec::new(); let mut control = Vec::new(); @@ -178,6 +379,76 @@ def program(ref): let d = data(true); announce(&d, 0x23, 1, b"als"); control.push(("an announcement during removal", queued(&d), 0)); + + // Claim-release path 1 (register_service): work-item allocation fails once. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + FAIL_WORK_NEW.store(1, SeqCst); + let (first, _) = announce_result(&d, 0x23, 1, b"als"); + let (retry, _) = announce_result(&d, 0x23, 1, b"als"); + drain(&d); + let ok_work = first == Err(ENOMEM) && retry.is_ok() && registered(&d) == 2; + control.push(("work-item allocation failure releases the claim", ok_work as usize, 1)); + + // Claim-release path 2 (AopServiceRegisterWork::run): subdevice slot reserve fails once. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + let calls_before = REGISTER_CALLS.load(SeqCst); + announce(&d, 0x23, 1, b"als"); + FAIL_SUBDEV_RESERVE.store(1, SeqCst); + drain(&d); + let skipped_reg = REGISTER_CALLS.load(SeqCst) == calls_before && registered(&d) == 1; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_slot = skipped_reg && registered(&d) == 2; + control.push(("subdevice slot allocation failure releases the claim", ok_slot as usize, 1)); + + // Claim-release path 3a (AopServiceRegisterWork::run): platform_device_register_full returns ERR_PTR. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::ErrPtr(-12)); + drain(&d); + let after_err = registered(&d) == 1; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_err = after_err && registered(&d) == 2; + control.push(("platform device registration error releases the claim", ok_err as usize, 1)); + + // Claim-release path 3b (AopServiceRegisterWork::run): platform_device_register_full returns NULL. + let d = data(false); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::Null); + drain(&d); + let after_null = registered(&d) == 0; + announce(&d, 0x23, 1, b"als"); + drain(&d); + let ok_null = after_null && registered(&d) == 1; + control.push(("null platform device return releases the claim", ok_null as usize, 1)); + + // After failing through all three paths and succeeding on retry, repeats stay refused + // and previously registered services keep their claims. + let d = data(false); + announce(&d, 0x21, 1, b"aop-audio"); + drain(&d); + FAIL_WORK_NEW.store(1, SeqCst); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 1, b"als"); + FAIL_SUBDEV_RESERVE.store(1, SeqCst); + drain(&d); + announce(&d, 0x23, 1, b"als"); + push_register_outcome(RegisterOutcome::ErrPtr(-12)); + drain(&d); + announce(&d, 0x23, 1, b"als"); + drain(&d); + announce(&d, 0x21, 1, b"aop-audio"); + announce(&d, 0x23, 1, b"als"); + announce(&d, 0x23, 2, b"als"); + drain(&d); + fixed.push(("repeats stay refused after failed registrations retry and succeed", registered(&d), 2)); + let mut out = String::new(); let mut fixed_failed = 0; let mut control_failed = 0; @@ -195,26 +466,39 @@ def program(ref): ''' -def run(ref, tmp): - source = Path(tmp) / (('old-' if ref else '') + 'aop-service.rs') +def run(ref, tmp, mutation=None): + prefix = f'mut-{mutation}-' if mutation else ('old-' if ref else '') + source = Path(tmp) / (prefix + 'aop-service.rs') binary = source.with_suffix('') - source.write_text(program(ref)) + source.write_text(program(ref, mutation)) subprocess.run(shlex.split(os.environ.get('RUSTC', 'rustc')) + ['--edition=2021', '-Dwarnings', str(source), '-o', str(binary)], check=True) - return subprocess.run([str(binary)]).returncode + res = subprocess.run([str(binary)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + sys.stdout.write(res.stdout) + return res.returncode, res.stdout def main(): ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument('--old-ref', help='require this older revision to fail the checks and pass the controls') + group = ap.add_mutually_exclusive_group() + group.add_argument('--old-ref', help='require this older revision to fail the checks and pass the controls') + group.add_argument('--mutation', choices=sorted(MUTATIONS), + help='drop one claim-release call and require its control to fail') args = ap.parse_args() with tempfile.TemporaryDirectory(prefix='aop-service-') as tmp: - rc = run(args.old_ref, tmp) + rc, out = run(args.old_ref, tmp, args.mutation) if args.old_ref: if rc == 1: print(f'{args.old_ref} fails the checks, as expected') return 0 raise SystemExit(f'{args.old_ref}: rc {rc}; the test does not catch the original code') + if args.mutation: + expected = MUTATIONS[args.mutation][3] + missing = [name for name in expected if f'FAIL control: {name}:' not in out] + if rc == 3 and not missing: + print(f'mutation {args.mutation} fails its control, as expected') + return 0 + raise SystemExit(f'mutation {args.mutation}: rc {rc}, missing failures {missing}') return rc diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 438bad1b2ba074..2cf5e5f7f44e94 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -105,7 +105,8 @@ def mutations(flag, names, base, expect=KILL): 'aop-bootargs-tests.py': [([], PASS)], # 24dc422773c9 registers another child device for each repeated service announcement. 'aop-service-tests.py': [([], PASS), - (['--old-ref', '24dc422773c9beb9e99ee9e1ab713e9d6abb1e7b'], PASS)], + (['--old-ref', '24dc422773c9beb9e99ee9e1ab713e9d6abb1e7b'], PASS)] + + mutations('--mutation', ('no-work-release', 'no-slot-release', 'no-register-release'), [], PASS), 'mtp-pm-tests.py': [(out(), PASS), (out() + ['--old-transport', '4db3a5a22c43'], PASS), (out() + ['--old-mouse', '62d2045d8928'], PASS)], From 73d8f7cde2683357de5cd04e28638f68785626c1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:21:15 +1100 Subject: [PATCH 0529/1514] wifi: brcmfmac: pcie: take ring pointers from the dongle only inside the ring The read and write pointers of the message rings are read back from the dongle (from TCM or from the host index buffer) and used as ring positions: the common ring code computes item counts and buffer addresses from them. A pointer at or past the ring depth made it reach past the end of the ring buffer. Take a pointer only when it is below the ring depth; otherwise keep the last one, log it (rate-limited) and return -EIO, as the update does when the bus is down. tools/asahi/brcmf-shared-tcm-tests.py gets a control for both updates; the mutations rptr-depth and wptr-depth drop the checks. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/pcie.c | 22 ++++++++++++-- tools/asahi/brcmf-shared-tcm-tests.py | 30 ++++++++++++++----- tools/asahi/run-host-tests.py | 3 +- 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index ac52ec21ff4ed0..d30845284b4b70 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -1459,11 +1459,20 @@ static int brcmf_pcie_ring_mb_update_rptr(void *ctx) struct brcmf_pcie_ringbuf *ring = (struct brcmf_pcie_ringbuf *)ctx; struct brcmf_pciedev_info *devinfo = ring->devinfo; struct brcmf_commonring *commonring = &ring->commonring; + u16 ptr; if (devinfo->state != BRCMFMAC_PCIE_STATE_UP) return -EIO; - commonring->r_ptr = devinfo->read_ptr(devinfo, ring->r_idx_addr); + /* The dongle's index is only used inside the ring; keep the last good one */ + ptr = devinfo->read_ptr(devinfo, ring->r_idx_addr); + if (ptr >= commonring->depth) { + brcmf_err(dev_get_drvdata(&devinfo->pdev->dev), + "ring %d: r_ptr %u outside depth %u\n", ring->id, ptr, + commonring->depth); + return -EIO; + } + commonring->r_ptr = ptr; brcmf_dbg(PCIE, "R r_ptr %d (%d), ring %d\n", commonring->r_ptr, commonring->w_ptr, ring->id); @@ -1477,11 +1486,20 @@ static int brcmf_pcie_ring_mb_update_wptr(void *ctx) struct brcmf_pcie_ringbuf *ring = (struct brcmf_pcie_ringbuf *)ctx; struct brcmf_pciedev_info *devinfo = ring->devinfo; struct brcmf_commonring *commonring = &ring->commonring; + u16 ptr; if (devinfo->state != BRCMFMAC_PCIE_STATE_UP) return -EIO; - commonring->w_ptr = devinfo->read_ptr(devinfo, ring->w_idx_addr); + /* The dongle's index is only used inside the ring; keep the last good one */ + ptr = devinfo->read_ptr(devinfo, ring->w_idx_addr); + if (ptr >= commonring->depth) { + brcmf_err(dev_get_drvdata(&devinfo->pdev->dev), + "ring %d: w_ptr %u outside depth %u\n", ring->id, ptr, + commonring->depth); + return -EIO; + } + commonring->w_ptr = ptr; brcmf_dbg(PCIE, "R w_ptr %d (%d), ring %d\n", commonring->w_ptr, commonring->r_ptr, ring->id); diff --git a/tools/asahi/brcmf-shared-tcm-tests.py b/tools/asahi/brcmf-shared-tcm-tests.py index ecf9b3267cb217..bc9242bb14fd1b 100755 --- a/tools/asahi/brcmf-shared-tcm-tests.py +++ b/tools/asahi/brcmf-shared-tcm-tests.py @@ -76,7 +76,8 @@ def define(source, name): struct brcmf_bus { int unused; }; static struct brcmf_bus bus; static struct brcmf_bus *dev_get_drvdata(struct device *dev) { (void)dev; return &bus; } -struct brcmf_commonring { int unused; }; +struct brcmf_commonring { u16 r_ptr, w_ptr, depth; }; +enum brcmf_pcie_state { BRCMFMAC_PCIE_STATE_DOWN, BRCMFMAC_PCIE_STATE_UP }; struct brcmf_pciedev_info; struct brcmf_pcie_ringbuf { struct brcmf_commonring commonring; struct brcmf_pciedev_info *devinfo; u32 w_idx_addr, r_idx_addr; u16 id; }; @@ -86,7 +87,7 @@ def define(source, name): struct brcmf_pcie_ringbuf *flowrings; u16 max_rxbufpost, max_flowrings, max_submissionrings, max_completionrings; u32 rx_dataoffset, htod_mb_data_addr, dtoh_mb_data_addr, ring_info_addr; struct brcmf_pcie_console console; u8 version; bool mb_via_ctl; u32 flags2, flags3; }; -struct brcmf_pciedev_info { struct pci_dev *pdev; u8 *tcm; size_t tcm_size; struct brcmf_pcie_shared_info shared; +struct brcmf_pciedev_info { enum brcmf_pcie_state state; struct pci_dev *pdev; u8 *tcm; size_t tcm_size; struct brcmf_pcie_shared_info shared; u8 dma_idx_sz; void *idxbuf; u32 idxbuf_sz; dma_addr_t idxbuf_dmahandle; u16 (*read_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset); void (*write_ptr)(struct brcmf_pciedev_info *devinfo, u32 mem_offset, u16 value); }; @@ -116,12 +117,12 @@ def define(source, name): return &rings_pool[id]; } static void brcmf_pcie_release_ringbuffers(struct brcmf_pciedev_info *d) { (void)d; } static void brcmf_pcie_ring_mb_ring_bell(void) {} -static void brcmf_pcie_ring_mb_update_rptr(void) {} -static void brcmf_pcie_ring_mb_update_wptr(void) {} static void brcmf_pcie_ring_mb_write_rptr(void) {} static void brcmf_pcie_ring_mb_write_wptr(void) {} -static void brcmf_commonring_register_cb(struct brcmf_commonring *c, void (*a)(void), void (*b)(void), - void (*e)(void), void (*f)(void), void (*g)(void), void *r) { (void)c; (void)a; (void)b; (void)e; (void)f; (void)g; (void)r; } +static int brcmf_pcie_ring_mb_update_rptr(void *ctx); +static int brcmf_pcie_ring_mb_update_wptr(void *ctx); +static void brcmf_commonring_register_cb(struct brcmf_commonring *c, void (*a)(void), int (*b)(void *), + int (*e)(void *), void (*f)(void), void (*g)(void), void *r) { (void)c; (void)a; (void)b; (void)e; (void)f; (void)g; (void)r; } ''' MAIN = r''' @@ -200,6 +201,15 @@ def define(source, name): assert(!init()); ringinfo()->max_submissionrings = 2; assert(rings() == -EINVAL); cases++; reset(); put32(SHARED + BRCMF_SHARED_FLAGS_OFFSET, 6 | BRCMF_PCIE_SHARED_DMA_INDEX); assert(!init()); ringinfo()->max_completionrings = 0; assert(rings() == -EINVAL); cases++; + /* Ring pointers from the dongle are taken only inside the ring; the last good one stays. */ + reset(); devinfo.state = BRCMFMAC_PCIE_STATE_UP; assert(!init() && !rings()); + struct brcmf_pcie_ringbuf *rb = devinfo.shared.commonrings[2]; rb->devinfo = &devinfo; rb->commonring.depth = 64; + put16(rb->r_idx_addr, 63); put16(rb->w_idx_addr, 10); + assert(!brcmf_pcie_ring_mb_update_rptr(rb) && !brcmf_pcie_ring_mb_update_wptr(rb)); + assert(rb->commonring.r_ptr == 63 && rb->commonring.w_ptr == 10); + put16(rb->r_idx_addr, 64); put16(rb->w_idx_addr, 0xffff); + assert(brcmf_pcie_ring_mb_update_rptr(rb) == -EIO && brcmf_pcie_ring_mb_update_wptr(rb) == -EIO); + assert(rb->commonring.r_ptr == 63 && rb->commonring.w_ptr == 10); cases++; /* A console descriptor or buffer outside the TCM leaves the console off; setup goes on. */ reset(); put32(SHARED + BRCMF_SHARED_CONSOLE_ADDR_OFFSET, TCM_SIZE - 4); assert(!init() && !devinfo.shared.console.base_addr); cases++; @@ -240,6 +250,10 @@ def define(source, name): '\t\th2d_idx_len = (BRCMF_NROF_H2D_COMMON_MSGRINGS) *'), 'dma-counts': ('\t\tif (max_submissionrings <\n\t\t BRCMF_NROF_H2D_COMMON_MSGRINGS + max_flowrings ||\n' '\t\t max_completionrings < BRCMF_NROF_D2H_COMMON_MSGRINGS) {', '\t\tif (false) {'), + 'rptr-depth': ('\tptr = devinfo->read_ptr(devinfo, ring->r_idx_addr);\n\tif (ptr >= commonring->depth) {', + '\tptr = devinfo->read_ptr(devinfo, ring->r_idx_addr);\n\tif (false) {'), + 'wptr-depth': ('\tptr = devinfo->read_ptr(devinfo, ring->w_idx_addr);\n\tif (ptr >= commonring->depth) {', + '\tptr = devinfo->read_ptr(devinfo, ring->w_idx_addr);\n\tif (false) {'), 'console-desc': ('\t !brcmf_pcie_tcm_range_valid(devinfo->tcm_size, console->base_addr,\n' '\t\t\t\t\tBRCMF_CONSOLE_WRITEIDX_OFFSET + 4)) {', '\t false) {'), 'console-none': ('\tif (!console->base_addr ||\n', '\tif (false ||\n'), @@ -274,7 +288,9 @@ def main(): defines += '#define BRCMF_NROF_COMMON_MSGRINGS (BRCMF_NROF_H2D_COMMON_MSGRINGS + BRCMF_NROF_D2H_COMMON_MSGRINGS)\n' structs = struct((DRIVER / 'msgbuf.h').read_text(), 'msgbuf_buf_addr') + struct(pcie, 'brcmf_pcie_dhi_ringinfo') body = function((DRIVER / 'pcie.h').read_text(), 'brcmf_pcie_tcm_range_valid') + ''.join( - function(pcie, n) for n in ('brcmf_pcie_read_idx', 'brcmf_pcie_write_idx', 'brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', + function(pcie, n) for n in ('brcmf_pcie_read_idx', 'brcmf_pcie_write_idx', + 'brcmf_pcie_ring_mb_update_rptr', 'brcmf_pcie_ring_mb_update_wptr', + 'brcmf_pcie_bus_console_init', 'brcmf_pcie_bus_console_read', 'brcmf_pcie_init_ringbuffers', 'brcmf_pcie_init_share_ram_info')) if args.mutation: old, new = MUTATIONS[args.mutation] diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index e9cabac7e1b797..fb4478d30cac3a 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -161,7 +161,8 @@ def mutations(flag, names, base, expect=KILL): 'brcmf-roam-tests.py': [(out(), PASS)], 'brcmf-shared-tcm-tests.py': [(out(), PASS)] + mutations('--mutation', ('shared', 'htod-mb', 'dtoh-mb', 'ring-info', 'ring-mem', 'ring-idx', - 'flowring-idx', 'dma-counts', 'console-desc', 'console-none', + 'flowring-idx', 'dma-counts', 'rptr-depth', 'wptr-depth', + 'console-desc', 'console-none', 'console-buf', 'console-widx', 'console-reinit'), out()), 'brcmf-sae-vendor-tests.py': [(out(), PASS)] + [(out() + ['--ref', '9260e1f021e075713931f3c23c0a5fa1da936b0b'], KILL)], From 3d1734b4a7a168d5133403caf07e826a82d7f175 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:22:53 +1100 Subject: [PATCH 0530/1514] soc: apple: t6050-aop: start an endpoint's rings over at each GETBUF A GETBUF that reuses the endpoint's buffer left its ring state from the last setup in place: both rings stayed marked ready at their old offsets and the element count went on. A sleep stop arriving between the GETBUF and the firmware's new ring announcements would then write its element at the old offsets in a buffer the firmware treats as new. The firmware announces the rings after each GETBUF, so start them over when one is answered: neither ring is ready, the element count and the recorded pointers go back to zero, and the endpoint is not open until its rings start again. A refused GETBUF changes nothing. Rename t6050_aop_getbuf_check() to t6050_aop_getbuf_claim() as it now changes the ring, and add KUnit cases for a reused and a refused GETBUF. Signed-off-by: Ryan Murray --- drivers/soc/apple/t6050-aop-test.c | 60 +++++++++++++++++++++++++----- drivers/soc/apple/t6050-aop.c | 23 +++++++++--- 2 files changed, 68 insertions(+), 15 deletions(-) diff --git a/drivers/soc/apple/t6050-aop-test.c b/drivers/soc/apple/t6050-aop-test.c index 00f1c0082c4946..9e7d77dec28b58 100644 --- a/drivers/soc/apple/t6050-aop-test.c +++ b/drivers/soc/apple/t6050-aop-test.c @@ -9,8 +9,8 @@ static void t6050_aop_test_first_getbuf_allocates(struct kunit *test) { struct t6050_aop_ring r = {}; - KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 0x4000), 0); - KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 0x4000), 0); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); } static void t6050_aop_test_empty_getbuf_refused(struct kunit *test) @@ -18,10 +18,10 @@ static void t6050_aop_test_empty_getbuf_refused(struct kunit *test) static u8 mem[0x100]; struct t6050_aop_ring r = {}; - KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0), 0); r.buf = mem; r.size = sizeof(mem); - KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0), 0); } static void t6050_aop_test_repeat_getbuf_reuses(struct kunit *test) @@ -31,7 +31,7 @@ static void t6050_aop_test_repeat_getbuf_reuses(struct kunit *test) int i; for (i = 0; i < 64; i++) - KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, sizeof(mem)), 1); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem)), 1); } static void t6050_aop_test_smaller_getbuf_reuses(struct kunit *test) @@ -39,8 +39,46 @@ static void t6050_aop_test_smaller_getbuf_reuses(struct kunit *test) static u8 mem[0x100]; struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; - KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, sizeof(mem) / 2), 1); - KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_check(&r, 1), 1); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem) / 2), 1); + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, 1), 1); +} + +static void t6050_aop_test_reused_getbuf_restarts_rings(struct kunit *test) +{ + static __le32 mem[0x400 / 4]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; + struct t6050_aop_view v; + u32 bufsz = 2 * AFK_QE_SLOT; + + mem[0] = cpu_to_le32(bufsz); + r.tx_off = 0; + r.tx_size = bufsz + 3 * 0x40; + r.tx_ready = true; + r.rx_off = 0; + r.rx_size = r.tx_size; + r.rx_ready = true; + r.seq = 5; + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.tx_off, r.tx_size, r.tx_ready, &v), 0); + + /* The firmware asks again: no ring until it announces them again. */ + KUNIT_EXPECT_EQ(test, t6050_aop_getbuf_claim(&r, sizeof(mem)), 1); + KUNIT_EXPECT_FALSE(test, r.tx_ready); + KUNIT_EXPECT_FALSE(test, r.rx_ready); + KUNIT_EXPECT_EQ(test, r.seq, 0); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.tx_off, r.tx_size, r.tx_ready, &v), -EINVAL); + KUNIT_EXPECT_EQ(test, t6050_aop2_view(&r, r.rx_off, r.rx_size, r.rx_ready, &v), -EINVAL); +} + +static void t6050_aop_test_refused_getbuf_keeps_rings(struct kunit *test) +{ + static u8 mem[0x100]; + struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000, + .tx_ready = true, .rx_ready = true, .seq = 5 }; + + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) + 1), 0); + KUNIT_EXPECT_TRUE(test, r.tx_ready); + KUNIT_EXPECT_TRUE(test, r.rx_ready); + KUNIT_EXPECT_EQ(test, r.seq, 5); } static void t6050_aop_test_larger_getbuf_refused(struct kunit *test) @@ -48,9 +86,9 @@ static void t6050_aop_test_larger_getbuf_refused(struct kunit *test) static u8 mem[0x100]; struct t6050_aop_ring r = { .buf = mem, .size = sizeof(mem), .iova = 0x1000 }; - KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, sizeof(mem) + 1), 0); - KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, sizeof(mem) * 2), 0); - KUNIT_EXPECT_LT(test, t6050_aop_getbuf_check(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) + 1), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, sizeof(mem) * 2), 0); + KUNIT_EXPECT_LT(test, t6050_aop_getbuf_claim(&r, 0xffffUL << AFK_BLOCK_SHIFT), 0); } static void t6050_aop_test_view_inside_buffer(struct kunit *test) @@ -79,6 +117,8 @@ static struct kunit_case t6050_aop_test_cases[] = { KUNIT_CASE(t6050_aop_test_repeat_getbuf_reuses), KUNIT_CASE(t6050_aop_test_smaller_getbuf_reuses), KUNIT_CASE(t6050_aop_test_larger_getbuf_refused), + KUNIT_CASE(t6050_aop_test_reused_getbuf_restarts_rings), + KUNIT_CASE(t6050_aop_test_refused_getbuf_keeps_rings), KUNIT_CASE(t6050_aop_test_view_inside_buffer), {} }; diff --git a/drivers/soc/apple/t6050-aop.c b/drivers/soc/apple/t6050-aop.c index 92d583ae337025..14bf2b0729b556 100644 --- a/drivers/soc/apple/t6050-aop.c +++ b/drivers/soc/apple/t6050-aop.c @@ -145,15 +145,26 @@ static void t6050_aop_send(struct t6050_aop *aop, u8 ep, u64 msg) * What a GETBUF gets: 0 a new buffer, 1 the endpoint's own again, as it fits in it, or -EINVAL for * no size or more than the endpoint's buffer holds. An endpoint has one buffer for as long as the * firmware runs: its rings are read from it at a sleep and a wake, by other threads. + * + * A GETBUF that is answered starts the endpoint's rings over: they are announced again after it, + * so the endpoint has none, and sends nothing, until then. */ -static int t6050_aop_getbuf_check(const struct t6050_aop_ring *r, size_t size) +static int t6050_aop_getbuf_claim(struct t6050_aop_ring *r, size_t size) { + int ret; + if (!size) return -EINVAL; - if (!r->buf) - return 0; + ret = !r->buf ? 0 : size <= r->size ? 1 : -EINVAL; + if (ret < 0) + return ret; - return size <= r->size ? 1 : -EINVAL; + WRITE_ONCE(r->tx_ready, false); + WRITE_ONCE(r->rx_ready, false); + r->seq = 0; + r->tx_rptr = 0; + r->tx_wptr = 0; + return ret; } static void t6050_aop_getbuf(struct t6050_aop *aop, u8 ep, u64 msg) @@ -164,12 +175,14 @@ static void t6050_aop_getbuf(struct t6050_aop *aop, u8 ep, u64 msg) int ret; /* Only this endpoint's messages, in order, change its buffer. */ - ret = t6050_aop_getbuf_check(r, size); + ret = t6050_aop_getbuf_claim(r, size); if (ret < 0) { dev_err_ratelimited(aop->dev, "endpoint %#x: no buffer for a %#zx byte GETBUF (has %#zx)\n", ep, size, r->buf ? r->size : 0); return; } + /* Open again once its rings start (AFK_START_ACK). */ + clear_bit(ep - AOP_EP_FIRST, &aop->opened); if (!ret) { buf = dmam_alloc_coherent(aop->dev, size, &r->iova, GFP_KERNEL); if (!buf) { From 6c2b4388b5d82338ffa11105928cf3d4bfa418bb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:23:17 +1100 Subject: [PATCH 0531/1514] wifi: apple: centauri: report the kept station counter length The connection log line printed the last statistics reply's length next to the station counters, which no longer has to be the counters' own length. Print the kept counter length there, and add it to the debugfs station_stats header as counters=, after the reply's own fields. Word the KUnit option's help for the driver, not one board. Signed-off-by: Ryan Murray --- drivers/net/wireless/apple/Kconfig | 6 +++--- drivers/net/wireless/apple/centauri/centauri_wifi.c | 8 +++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/drivers/net/wireless/apple/Kconfig b/drivers/net/wireless/apple/Kconfig index 67bf179e874850..1564b663d9d4fd 100644 --- a/drivers/net/wireless/apple/Kconfig +++ b/drivers/net/wireless/apple/Kconfig @@ -28,9 +28,9 @@ config APPLE_CENTAURI_KUNIT_TEST depends on APPLE_CENTAURI && KUNIT=y default KUNIT_ALL_TESTS help - Build tests that pass statistics replies to the J813 Wi-Fi reply - handler and check the recorded counter lengths. They need no N1 - hardware. + Build tests that pass statistics replies to the Centauri Wi-Fi + reply handler and check the recorded counter lengths. They need no + N1 hardware. If unsure, say N. diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index 5d255a18743232..2c16b4b92099c5 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -1289,7 +1289,8 @@ static void connect_worker(struct work_struct *work) probe_ret = query_station_stats(wifi); dev_info(&wifi->control->pdev->dev, "connection counters: complete=%d rc=%d valid=%d length=%u\n", - wifi->connect_event, probe_ret, wifi->station_stats_valid, wifi->stats_length); + wifi->connect_event, probe_ret, wifi->station_stats_valid, + wifi->station_stats_len); if (!probe_ret && wifi->station_stats_valid) for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); @@ -2303,8 +2304,9 @@ static int station_stats_show(struct seq_file *seq, void *unused) mutex_lock(&wifi->lock); ret = query_station_stats(wifi); - seq_printf(seq, "rc=%d valid=%d size=%u tag=%#x length=%u\n", ret, - wifi->station_stats_valid, wifi->stats_reply_size, wifi->stats_tag, wifi->stats_length); + seq_printf(seq, "rc=%d valid=%d size=%u tag=%#x length=%u counters=%u\n", ret, + wifi->station_stats_valid, wifi->stats_reply_size, wifi->stats_tag, + wifi->stats_length, wifi->station_stats_len); if (!ret && wifi->station_stats_valid) for (i = 0; i < wifi->station_stats_len; i += 4) { u32 value = get_unaligned_le32(wifi->station_stats + i); From 6f78a97f1117e867997947c7390390631c213d0f Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Mon, 2 Nov 2026 16:25:16 +0100 Subject: [PATCH 0532/1514] software node: only let the owner release a managed node device_create_managed_software_node() creates a node whose lifetime is tied to the device it was created for. software_node_notify_remove() is called for every device that has the node as its fwnode (primary OR secondary) and, if the node is managed, unconditionally detaches it from that device and drops the creation reference. This breaks when the node is shared with another device. Example: the i2c-designware copies the parent's fwnode to the adapter's struct device. When the adapter is deleted, it releases the reference that belongs to the owner and the latter ends up with a dangling pointer. Record the device's "manager" and only perform the actual release when notify is called for that "owner" device. Note that it was never the intention that managed software nodes would be shared, but descendants reusing ancestor firmware nodes is not uncommon and such use is hard to predict when allocating software nodes. Reported-by: Balasubramani Vivekanandan Closes: https://lore.kernel.org/all/20261009164241.923756-2-balasubramani.vivekanandan@intel.com/ Fixes: 151f6ff78cdf ("software node: Provide replacement for device_add_properties()") Signed-off-by: Bartosz Golaszewski Fixes: 0f485f88656a ("drm/xe/i2c: use device_create_managed_software_node()") Reviewed-by: Balasubramani Vivekanandan Tested-by: Balasubramani Vivekanandan Reviewed-by: Heikki Krogerus Cc: stable@vger.kernel.org Link: https://patch.msgid.link/20261102-swnode-only-owner-release-v1-1-ee4c9022a629@oss.qualcomm.com [ johan: drop temporary variable; skip clearing owner field; mention reuse not intended in commit message ] Signed-off-by: Johan Hovold (cherry picked from commit f8623ce596492d2e96ca57eeec992938d3d79f00) Signed-off-by: Ryan Murray --- drivers/base/swnode.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/base/swnode.c b/drivers/base/swnode.c index 84a77ffa3dc4bb..cf495e67f0763a 100644 --- a/drivers/base/swnode.c +++ b/drivers/base/swnode.c @@ -29,6 +29,8 @@ struct swnode { struct fwnode_handle fwnode; const struct software_node *node; int id; + /* Device the managed node's lifetime is tied to. */ + struct device *owner; /* hierarchy */ struct ida child_ids; @@ -37,7 +39,6 @@ struct swnode { struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; }; static DEFINE_IDA(swnode_root_ids); @@ -1145,7 +1146,7 @@ int device_create_managed_software_node(struct device *dev, if (IS_ERR(fwnode)) return PTR_ERR(fwnode); - to_swnode(fwnode)->managed = true; + to_swnode(fwnode)->owner = dev; set_secondary_fwnode(dev, fwnode); if (device_is_registered(dev)) @@ -1208,7 +1209,7 @@ void software_node_notify_remove(struct device *dev) swnode_put(swnode); - if (swnode->managed) { + if (swnode->owner == dev) { set_secondary_fwnode(dev, NULL); swnode_put(swnode); } From 1ebd859a25a6d1b292754c60f61a1948c171f9d2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:36:48 +1100 Subject: [PATCH 0533/1514] software node: check the owner before dropping the device's reference software_node_notify_remove() drops the reference the device took in software_node_notify() and only then reads swnode->owner to decide whether to release the managed node as well. The node does not always survive that put. Other devices may carry the owner's node; commit f8623ce59649 ("software node: only let the owner release a managed node") made the sharer's removal leave the owner's reference alone, but when the owner is unregistered first, the sharer's reference is the last one. Its put frees the node and the owner check then reads freed memory: BUG: KASAN: slab-use-after-free in software_node_notify_remove+0x1c4/0x1ec Read of size 8 at addr fff000000230e690 by task kunit_try_catch/42 Call trace: software_node_notify_remove+0x1c4/0x1ec device_del+0x324/0xa1c device_unregister+0x14/0x2c swnode_managed_owner_removed_first+0x10c/0x18c ... Freed by task 42: kfree+0x17c/0x3cc software_node_release+0x128/0x25c kobject_put+0x140/0x25c software_node_notify_remove+0x138/0x1ec device_del+0x324/0xa1c Check for the owner, and drop the managed reference if it is one, before dropping the device's own reference. The owner still holds both of its references at that point, and no other device touches the node after its put. Fixes: 151f6ff78cdf ("software node: Provide replacement for device_add_properties()") Cc: stable@vger.kernel.org Signed-off-by: Ryan Murray --- drivers/base/swnode.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/base/swnode.c b/drivers/base/swnode.c index cf495e67f0763a..07c586973c47fe 100644 --- a/drivers/base/swnode.c +++ b/drivers/base/swnode.c @@ -1207,12 +1207,16 @@ void software_node_notify_remove(struct device *dev) if (!device_match_fwnode(dev, &swnode->fwnode) && swnode->fwnode.dev == dev) swnode->fwnode.dev = NULL; - swnode_put(swnode); - + /* + * Check ownership before dropping this device's reference: when the + * owner is already gone, the put below may free the node. + */ if (swnode->owner == dev) { set_secondary_fwnode(dev, NULL); swnode_put(swnode); } + + swnode_put(swnode); } void __init software_node_init(void) From 47e2324f1b2dd5cee91c7b66153d1ceaf0f48ca2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:36:49 +1100 Subject: [PATCH 0534/1514] software node: add KUnit tests for the lifetime of managed nodes A managed software node belongs to the device it was created for, but other devices may carry the same fwnode, a child reusing its parent's node for instance. Removing those devices must drop only their own references, in either order, and free the node exactly once. Add a suite that gives a device a managed node, adds a second device sharing it and unregisters the two in both orders, checking that the remaining device can still read the node's properties. With KASAN enabled, the sharer-first case catches the double put fixed by commit f8623ce59649 ("software node: only let the owner release a managed node") and the owner-first case the read after the final put fixed by the previous patch. The tests are built with the existing DRIVER_SWNODE_KUNIT_TEST option, whose prompt now covers software nodes in general. Signed-off-by: Ryan Murray --- MAINTAINERS | 1 + drivers/base/test/Kconfig | 2 +- drivers/base/test/Makefile | 1 + drivers/base/test/swnode-managed-test.c | 139 ++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 drivers/base/test/swnode-managed-test.c diff --git a/MAINTAINERS b/MAINTAINERS index 5c8fc89e51d008..993373e41f9634 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -25635,6 +25635,7 @@ S: Maintained F: drivers/base/property.c F: drivers/base/swnode.c F: drivers/base/test/swnode-devlink-test.c +F: drivers/base/test/swnode-managed-test.c F: include/linux/fwnode.h F: include/linux/property.h diff --git a/drivers/base/test/Kconfig b/drivers/base/test/Kconfig index 1ecf0791241a1b..d48d7016f8ca1f 100644 --- a/drivers/base/test/Kconfig +++ b/drivers/base/test/Kconfig @@ -20,6 +20,6 @@ config DRIVER_PE_KUNIT_TEST default KUNIT_ALL_TESTS config DRIVER_SWNODE_KUNIT_TEST - tristate "KUnit Tests for software node fw_devlink links" if !KUNIT_ALL_TESTS + tristate "KUnit Tests for software nodes" if !KUNIT_ALL_TESTS depends on KUNIT default KUNIT_ALL_TESTS diff --git a/drivers/base/test/Makefile b/drivers/base/test/Makefile index 9ced7bbd569fc4..b37ec934e8ae24 100644 --- a/drivers/base/test/Makefile +++ b/drivers/base/test/Makefile @@ -8,3 +8,4 @@ obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN) obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-devlink-test.o +obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-managed-test.o diff --git a/drivers/base/test/swnode-managed-test.c b/drivers/base/test/swnode-managed-test.c new file mode 100644 index 00000000000000..9ea46c95535740 --- /dev/null +++ b/drivers/base/test/swnode-managed-test.c @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the lifetime of managed software nodes. + * + * A node created with device_create_managed_software_node() belongs to one + * device, but other devices may carry the same fwnode (a child that reuses + * its parent's node, a gpiochip's gdev->dev, an i2c adapter). Removing any + * of them must drop only that device's reference, in either order, and the + * node must be freed exactly once after the last one is gone. + * + * The use-after-free and double put these tests guard against are silent + * without CONFIG_KASAN; with it, KASAN fails the running test. + */ + +#include +#include +#include + +#include + +static const struct property_entry swnode_managed_props[] = { + PROPERTY_ENTRY_U32("test-value", 42), + { } +}; + +static void swnode_managed_dev_release(struct device *dev) +{ + kfree(dev); +} + +static struct device *swnode_managed_dev_add(struct kunit *test, + const char *name, + struct fwnode_handle *fwnode) +{ + struct device *dev; + int ret; + + dev = kzalloc_obj(*dev); + KUNIT_ASSERT_NOT_NULL(test, dev); + + device_initialize(dev); + dev->release = swnode_managed_dev_release; + device_set_node(dev, fwnode); + + ret = dev_set_name(dev, "%s", name); + if (!ret) + ret = device_add(dev); + if (ret) { + put_device(dev); + KUNIT_FAIL_AND_ABORT(test, "adding %s failed: %d\n", name, ret); + } + + return dev; +} + +/* Add the owner, give it a managed node, add a second device sharing it. */ +static void swnode_managed_setup(struct kunit *test, struct device **owner, + struct device **sharer) +{ + struct fwnode_handle *fwnode; + int ret; + + *owner = swnode_managed_dev_add(test, "swnode-managed-owner", NULL); + + ret = device_create_managed_software_node(*owner, swnode_managed_props, + NULL); + if (ret) { + device_unregister(*owner); + KUNIT_FAIL_AND_ABORT(test, "creating the node failed: %d\n", ret); + } + + fwnode = dev_fwnode(*owner); + KUNIT_ASSERT_TRUE(test, is_software_node(fwnode)); + + *sharer = swnode_managed_dev_add(test, "swnode-managed-sharer", fwnode); +} + +static void swnode_managed_expect_value(struct kunit *test, struct device *dev) +{ + u32 val = 0; + + KUNIT_EXPECT_EQ(test, device_property_read_u32(dev, "test-value", &val), + 0); + KUNIT_EXPECT_EQ(test, val, 42); +} + +/* + * The usual order: the sharer goes first. It must not take the owner's + * reference with it, or the owner's removal frees the node and then puts + * it again. + */ +static void swnode_managed_sharer_removed_first(struct kunit *test) +{ + struct device *owner, *sharer; + + swnode_managed_setup(test, &owner, &sharer); + + device_unregister(sharer); + + KUNIT_EXPECT_TRUE(test, is_software_node(dev_fwnode(owner))); + swnode_managed_expect_value(test, owner); + + device_unregister(owner); +} + +/* + * The owner goes first. The sharer keeps the node alive through its own + * reference, and its removal drops the last one: nothing may read the node + * after that. + */ +static void swnode_managed_owner_removed_first(struct kunit *test) +{ + struct device *owner, *sharer; + + swnode_managed_setup(test, &owner, &sharer); + + device_unregister(owner); + + KUNIT_EXPECT_TRUE(test, is_software_node(dev_fwnode(sharer))); + swnode_managed_expect_value(test, sharer); + + device_unregister(sharer); +} + +static struct kunit_case swnode_managed_test_cases[] = { + KUNIT_CASE(swnode_managed_sharer_removed_first), + KUNIT_CASE(swnode_managed_owner_removed_first), + { } +}; + +static struct kunit_suite swnode_managed_test_suite = { + .name = "software-node-managed", + .test_cases = swnode_managed_test_cases, +}; + +kunit_test_suite(swnode_managed_test_suite); + +MODULE_DESCRIPTION("Test module for managed software node lifetime"); +MODULE_LICENSE("GPL"); From 4aa52c40e14145c6030c42f83201141642ebc524 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:38:38 +1100 Subject: [PATCH 0535/1514] soc: apple: sart: add KUnit tests The SART driver decides which physical ranges the NVMe co-processor may DMA to, and none of it had a test. Add a suite that runs the real ops on a register block in kernel memory for each SART generation: - the address, size and flags encoding of an added region, a full table, regions that are not whole pages and the largest size a generation can encode, and physical addresses above 4 GiB; - remove of a region that was never added, and of the entries the bootloader left (they are kept and never handed out); - shutdown, and the firmware-driven sleep path: what suspend saves, what resume restores or keeps, the replay of saved entries and the refusal of a sleep whose table changed under it. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 15 + drivers/soc/apple/sart-test.c | 952 +++++++++++++++++++++++++++++ drivers/soc/apple/sart.c | 4 + drivers/soc/apple/sart.kunitconfig | 7 + 4 files changed, 978 insertions(+) create mode 100644 drivers/soc/apple/sart-test.c create mode 100644 drivers/soc/apple/sart.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..b2b9689efd9559 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -163,6 +163,21 @@ config APPLE_SART Say 'y' here if you have an Apple SoC. +config APPLE_SART_KUNIT_TEST + bool "KUnit tests for the Apple SART DMA address filter" if !KUNIT_ALL_TESTS + depends on APPLE_SART=y && KUNIT=y + depends on ARM64 && OF + default KUNIT_ALL_TESTS + help + Add and remove allowed regions on a SART whose registers are a + buffer of kernel memory, and check the register encoding of each + SART generation, the handling of a full table, of regions that are + not whole pages and of the bootloader's entries, and what a + firmware-driven sleep saves, restores and refuses. The tests touch + no hardware. + + If unsure, say N. + config APPLE_TUNABLE tristate depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/soc/apple/sart-test.c b/drivers/soc/apple/sart-test.c new file mode 100644 index 00000000000000..2095aaf7c2d973 --- /dev/null +++ b/drivers/soc/apple/sart-test.c @@ -0,0 +1,952 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SART driver. Included by sart.c. + * + * The SART under test is a struct apple_sart whose register block is a + * zeroed buffer of kernel memory, as large as the widest layout (SARTv4). + * The tests call the driver's own entry points and compare the whole block + * with a model that encodes each entry independently of the driver's + * macros, so a write to a wrong register shows up as well as a wrong value. + * No device is probed and no MMIO is touched. + */ +#include +#include +#include + +#define SART_TEST_REGS_SIZE 0x100 +#define SART_TEST_NREGS (SART_TEST_REGS_SIZE / 4) +#define SART_TEST_PG(n) ((phys_addr_t)(n) << 12) + +/* What the test expects of each register layout, in numbers of its own */ +struct sart_test_ver { + const char *name; + struct apple_sart_ops *ops; + unsigned int paddr_reg; + /* 0: the size shares the config register with the flags */ + unsigned int size_reg; + u8 allow; + /* in 4K pages */ + u32 size_max; +}; + +static const struct sart_test_ver sart_test_vers[] = { + { "v0", &sart_ops_v0, 0x40, 0, 0x0f, 0x7ffff }, + { "v2", &sart_ops_v2, 0x40, 0, 0xff, 0xffffff }, + { "v3", &sart_ops_v3, 0x40, 0x80, 0xff, 0x3fffffff }, + { "v4", &sart_ops_v4, 0x60, 0xc0, 0xff, 0x3fffffff }, +}; + +static void sart_test_ver_desc(const struct sart_test_ver *v, char *desc) +{ + strscpy(desc, v->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(sart_test_ver, sart_test_vers, sart_test_ver_desc); + +struct sart_test { + struct apple_sart sart; + const struct sart_test_ver *ver; + __le32 *regs; + u32 expect[SART_TEST_NREGS]; + suspend_state_t pm_state; + unsigned int pm_flags; +}; + +static struct sart_test *sart_test_new(struct kunit *test, + const struct sart_test_ver *ver) +{ + /* A case may set up several SARTs: test->priv counts them */ + unsigned long nr = (unsigned long)test->priv; + struct sart_test *t; + struct device *dev; + char name[16]; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->regs = kunit_kzalloc(test, SART_TEST_REGS_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->regs); + snprintf(name, sizeof(name), "sart-test%lu", nr); + test->priv = (void *)(nr + 1); + dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + t->ver = ver; + t->sart.dev = dev; + t->sart.ops = ver->ops; + t->sart.regs = (void __iomem __force *)t->regs; + dev_set_drvdata(dev, &t->sart); + + return t; +} + +static u32 sart_test_rd(struct sart_test *t, unsigned int reg) +{ + return le32_to_cpu(t->regs[reg / 4]); +} + +static void __maybe_unused sart_test_wr(struct sart_test *t, unsigned int reg, u32 val) +{ + t->regs[reg / 4] = cpu_to_le32(val); +} + +/* The model: entry idx holds these flags, address and size (in pages) */ +static void sart_test_model(struct sart_test *t, int idx, u8 flags, + u32 paddr_pg, u32 size_pg) +{ + const struct sart_test_ver *v = t->ver; + + if (v->size_reg) { + t->expect[idx] = flags; + t->expect[v->size_reg / 4 + idx] = size_pg; + } else { + t->expect[idx] = (u32)flags << 24 | size_pg; + } + t->expect[v->paddr_reg / 4 + idx] = paddr_pg; +} + +/* An entry that is in the registers before the driver sees them */ +static void sart_test_preload(struct sart_test *t, int idx, u8 flags, + u32 paddr_pg, u32 size_pg) +{ + int i; + + sart_test_model(t, idx, flags, paddr_pg, size_pg); + for (i = 0; i < SART_TEST_NREGS; i++) + t->regs[i] = cpu_to_le32(t->expect[i]); +} + +static void sart_test_check(struct kunit *test, struct sart_test *t) +{ + int i; + + for (i = 0; i < SART_TEST_NREGS; i++) + KUNIT_EXPECT_EQ_MSG(test, le32_to_cpu(t->regs[i]), t->expect[i], + "register %#x", 4 * i); +} + +static unsigned int sart_test_nonzero(struct sart_test *t) +{ + unsigned int n = 0; + int i; + + for (i = 0; i < SART_TEST_NREGS; i++) + n += !!t->regs[i]; + return n; +} + +static struct sart_test *sart_test_two_regions(struct kunit *test, int ver) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[ver]); + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, 0x812345000ULL, 0x40000)); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, 0x9abcd000, 0x1000)); + return t; +} + +/* The register values of two added regions, written out for each layout */ +static void sart_test_add_encoding(struct kunit *test) +{ + struct sart_test *t; + + /* SARTv0: 5 bits of flags over a 19-bit size, addresses at 0x40 */ + t = sart_test_two_regions(test, 0); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0x0f000040); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0x0f000001); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 4); + + /* SARTv2: 8 bits of flags over a 24-bit size, addresses at 0x40 */ + t = sart_test_two_regions(test, 1); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff000040); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff000001); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 4); + + /* SARTv3: flags, addresses at 0x40, sizes at 0x80 */ + t = sart_test_two_regions(test, 2); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x40), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x80), 0x40); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x44), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x84), 0x1); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 6); + + /* SARTv4: flags, addresses at 0x60, sizes at 0xc0 */ + t = sart_test_two_regions(test, 3); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x00), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x60), 0x00812345); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0xc0), 0x40); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x04), 0xff); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0x64), 0x0009abcd); + KUNIT_EXPECT_EQ(test, sart_test_rd(t, 0xc4), 0x1); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 6); +} + +/* Sixteen regions take the sixteen entries in order; the next is refused */ +static void sart_test_add_fills_table(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + int i; + + for (i = 0; i < 16; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, + SART_TEST_PG(0x100000 + 0x100 * i), + SART_TEST_PG(i + 1))); + sart_test_model(t, i, t->ver->allow, 0x100000 + 0x100 * i, i + 1); + sart_test_check(test, t); + } + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff); + + KUNIT_EXPECT_EQ(test, -EBUSY, + apple_sart_add_allowed_region(&t->sart, SART_TEST_PG(0x200000), + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff); +} + +/* The bootloader's entries are neither reused nor rewritten */ +static void sart_test_add_skips_protected(struct kunit *test) +{ + static const int slots[] = { 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + struct sart_test *t = sart_test_new(test, test->param_value); + int i; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 1, 0x01, 0x900000, 0x10); + sart_test_preload(t, 5, t->ver->allow, 0xa00000, 0x1); + t->sart.protected_entries = BIT(0) | BIT(1) | BIT(5); + + for (i = 0; i < ARRAY_SIZE(slots); i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(&t->sart, + SART_TEST_PG(0x100000 + i), + SART_TEST_PG(1))); + sart_test_model(t, slots[i], t->ver->allow, 0x100000 + i, 1); + sart_test_check(test, t); + } + KUNIT_EXPECT_EQ(test, t->sart.used_entries, 0xffff & ~0x23); + + KUNIT_EXPECT_EQ(test, -EBUSY, + apple_sart_add_allowed_region(&t->sart, SART_TEST_PG(0x200000), + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, t->sart.protected_entries, 0x23); +} + +/* A region that is not whole pages is refused and costs no entry */ +static void sart_test_add_rejects_unaligned(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 0x800, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 1, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000) + 0xfff, + SART_TEST_PG(1))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), 0x1800)); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), 0xfff)); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), + SART_TEST_PG(1) + 1)); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0); + sart_test_check(test, t); + + /* The first entry is still the next one handed out */ + KUNIT_EXPECT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), + SART_TEST_PG(1))); + sart_test_model(t, 0, t->ver->allow, 0x1000, 1); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); +} + +/* The largest size the layout's field holds is taken, one page more is not */ +static void sart_test_add_size_max(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + size_t max = (size_t)t->ver->size_max << 12; + phys_addr_t paddr; + size_t size; + u8 flags; + + KUNIT_EXPECT_EQ(test, 0, apple_sart_add_allowed_region(sart, SART_TEST_PG(0x1000), max)); + sart_test_model(t, 0, t->ver->allow, 0x1000, t->ver->size_max); + sart_test_check(test, t); + + /* A full size field must not spill into the flags */ + sart->ops->get_entry(sart, 0, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, t->ver->allow); + KUNIT_EXPECT_EQ(test, size, max); + KUNIT_EXPECT_EQ(test, paddr, SART_TEST_PG(0x1000)); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x2000), + max + SART_TEST_PG(1))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); +} + +/* The highest address the 32-bit page register holds, there and back */ +static void sart_test_high_paddr(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + phys_addr_t paddr; + size_t size; + u8 flags; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0xffffffff), + SART_TEST_PG(1))); + sart_test_model(t, 0, t->ver->allow, 0xffffffff, 1); + sart_test_check(test, t); + + sart->ops->get_entry(sart, 0, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, paddr, 0xffffffff000ULL); + KUNIT_EXPECT_EQ(test, size, 0x1000); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, 0xffffffff000ULL, 0x1000)); + sart_test_model(t, 0, 0, 0, 0); + sart_test_check(test, t); +} + +/* get_entry reads what a bootloader left in any entry, the last included */ +static void sart_test_get_entry(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + phys_addr_t paddr; + size_t size; + u8 flags; + + sart_test_preload(t, 7, 0x05, 0x1, 0x1); + sart_test_preload(t, 15, t->ver->allow, 0xfedcba98, t->ver->size_max); + + sart->ops->get_entry(sart, 7, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, 0x05); + KUNIT_EXPECT_EQ(test, paddr, 0x1000); + KUNIT_EXPECT_EQ(test, size, 0x1000); + + sart->ops->get_entry(sart, 15, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, t->ver->allow); + KUNIT_EXPECT_EQ(test, paddr, 0xfedcba98000ULL); + KUNIT_EXPECT_EQ(test, size, (size_t)t->ver->size_max << 12); + + sart->ops->get_entry(sart, 8, &flags, &paddr, &size); + KUNIT_EXPECT_EQ(test, flags, 0); + KUNIT_EXPECT_EQ(test, paddr, 0); + KUNIT_EXPECT_EQ(test, size, 0); + + /* Reading changes nothing */ + sart_test_check(test, t); +} + +/* A removed region's entry reads empty and is the next one handed out */ +static void sart_test_remove_frees_slot(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + int i; + + for (i = 0; i < 3; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(2 + i))); + sart_test_model(t, i, t->ver->allow, 0x4000 + i, 2 + i); + } + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4001), + SART_TEST_PG(3))); + sart_test_model(t, 1, 0, 0, 0); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0) | BIT(2)); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x7000), + SART_TEST_PG(8))); + sart_test_model(t, 1, t->ver->allow, 0x7000, 8); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0x7); +} + +/* Only the exact address and size that were added can be removed, once */ +static void sart_test_remove_nonexistent(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, t->ver->allow, 0x4000, 4); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x9000), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(5))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(3))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4001), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000) + 1, + SART_TEST_PG(4))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(0)); + + KUNIT_EXPECT_EQ(test, 0, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, 0, 0, 0); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->used_entries, 0); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_check(test, t); +} + +/* A bootloader's entry can't be removed, whatever address and size are asked */ +static void sart_test_remove_protected(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 3, t->ver->allow, 0x800000, 0x400); + sart->protected_entries = BIT(3); + + KUNIT_EXPECT_EQ(test, -EINVAL, + apple_sart_remove_allowed_region(sart, SART_TEST_PG(0x800000), + SART_TEST_PG(0x400))); + sart_test_check(test, t); + KUNIT_EXPECT_EQ(test, sart->protected_entries, BIT(3)); +} + +static void sart_test_inherited_region(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + const phys_addr_t base = SART_TEST_PG(0x80000); + const size_t len = SART_TEST_PG(0x10); + + sart_test_preload(t, 2, t->ver->allow, 0x80000, 0x10); + /* Allowed, but not the bootloader's */ + sart_test_preload(t, 4, t->ver->allow, 0x90000, 0x10); + /* The bootloader's, but with other flags */ + sart_test_preload(t, 6, 0x01, 0xa0000, 0x10); + sart->protected_entries = BIT(2) | BIT(6); + + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base, len)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base, 0x1000)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + len - 0x1000, + 0x1000)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + 1, 1)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + len - 1, 1)); + KUNIT_EXPECT_TRUE(test, apple_sart_is_inherited_region(sart, base + 1, len - 1)); + + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, len + 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + 1, len)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + len, 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base - 1, 1)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base - 0x1000, + len + 0x1000)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base + len - 0x1000, + 0x2000)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, 0)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, PHYS_ADDR_MAX, 2)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, base, SIZE_MAX)); + + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, SART_TEST_PG(0x90000), + len)); + KUNIT_EXPECT_FALSE(test, apple_sart_is_inherited_region(sart, SART_TEST_PG(0xa0000), + len)); + sart_test_check(test, t); +} + +/* Shutdown empties every entry but the bootloader's */ +static void sart_test_shutdown(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + struct platform_device *pdev; + int i; + + pdev = kunit_kzalloc(test, sizeof(*pdev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pdev); + platform_set_drvdata(pdev, sart); + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 15, t->ver->allow, 0x900000, 0x10); + /* Not the bootloader's and not handed out either */ + sart_test_preload(t, 12, t->ver->allow, 0xa00000, 0x10); + sart->protected_entries = BIT(0) | BIT(15); + for (i = 0; i < 3; i++) + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(1))); + KUNIT_ASSERT_EQ(test, sart->used_entries, BIT(1) | BIT(2) | BIT(3)); + KUNIT_ASSERT_NE(test, sart_test_rd(t, 0x04), 0); + + apple_sart_shutdown(pdev); + + sart_test_model(t, 12, 0, 0, 0); + sart_test_check(test, t); +} + +/* Each compatible selects the register layout of its SART generation */ +static void sart_test_of_match(struct kunit *test) +{ + static const struct { + const char *compat; + int len; + const struct apple_sart_ops *ops; + } cases[] = { + { "apple,t8015-sart", 17, &sart_ops_v0 }, + { "apple,t8103-sart", 17, &sart_ops_v2 }, + { "apple,t6000-sart", 17, &sart_ops_v3 }, + { "apple,t6050-sart", 17, &sart_ops_v4 }, + { "apple,t8152-sart", 17, &sart_ops_v4 }, + /* A newer SoC falls back to the generation it is compatible with */ + { "apple,t8112-sart\0apple,t6000-sart", 34, &sart_ops_v3 }, + { "apple,t6020-sart\0apple,t6000-sart", 34, &sart_ops_v3 }, + }; + const struct of_device_id *match; + struct device_node *np; + struct property *prop; + int i; + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + prop = kunit_kzalloc(test, sizeof(*prop), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, prop); + prop->name = (char *)"compatible"; + np->properties = prop; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + prop->value = (void *)cases[i].compat; + prop->length = cases[i].len; + match = of_match_node(apple_sart_of_match, np); + KUNIT_ASSERT_NOT_NULL_MSG(test, match, "%s", cases[i].compat); + KUNIT_EXPECT_PTR_EQ_MSG(test, match->data, cases[i].ops, "%s", + cases[i].compat); + } + + prop->value = (void *)"apple,t8103-dart"; + prop->length = 17; + KUNIT_EXPECT_NULL(test, of_match_node(apple_sart_of_match, np)); +} + +/* A consumer without an apple,sart phandle has no SART */ +static void sart_test_get_no_phandle(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[1]); + struct device *dev = t->sart.dev; + struct device_node *np; + struct apple_sart *sart; + + sart = devm_apple_sart_get(dev); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(sart), -ENODEV); + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + dev->of_node = np; + sart = devm_apple_sart_get(dev); + dev->of_node = NULL; + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(sart), -ENODEV); +} + +#ifdef CONFIG_SUSPEND +static void sart_test_pm_restore(void *data) +{ + struct sart_test *t = data; + + pm_suspend_target_state = t->pm_state; + pm_suspend_global_flags = t->pm_flags; +} + +/* Pretend the system is in a suspend to RAM that the firmware carries out */ +static void sart_test_pm_firmware_sleep(struct kunit *test, struct sart_test *t) +{ + t->pm_state = pm_suspend_target_state; + t->pm_flags = pm_suspend_global_flags; + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, sart_test_pm_restore, t)); + + pm_suspend_target_state = PM_SUSPEND_MEM; + pm_suspend_clear_flags(); + pm_set_suspend_via_firmware(); +} + +static void sart_test_snapshot(struct kunit *test, struct sart_test *t) +{ + sart_test_pm_firmware_sleep(test, t); + KUNIT_ASSERT_EQ(test, 0, apple_sart_suspend_late(t->sart.dev)); + KUNIT_ASSERT_TRUE(test, t->sart.saved_valid); +} + +/* The SART's power domain went off: every register reads zero */ +static void sart_test_power_loss(struct sart_test *t) +{ + memset(t->regs, 0, SART_TEST_REGS_SIZE); +} + +/* Only a suspend to RAM carried out by the firmware is snapshotted */ +static void sart_test_suspend_not_firmware(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_pm_firmware_sleep(test, t); + + pm_suspend_clear_flags(); + sart->saved_valid = true; + sart->replay_valid = true; + KUNIT_EXPECT_EQ(test, 0, apple_sart_suspend_late(sart->dev)); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + KUNIT_EXPECT_FALSE(test, sart->replay_valid); + + pm_set_suspend_via_firmware(); + pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + KUNIT_EXPECT_EQ(test, 0, apple_sart_suspend_late(sart->dev)); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + + /* Without a snapshot the wake writes nothing */ + sart_test_power_loss(t); + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + KUNIT_EXPECT_FALSE(test, sart->replay_valid); +} + +/* After a firmware sleep every entry is back, the bootloader's included */ +static void sart_test_suspend_resume(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart_test_preload(t, 15, t->ver->allow, 0xfedcba98, t->ver->size_max); + sart->protected_entries = BIT(0) | BIT(15); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 1, t->ver->allow, 0x4000, 4); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x812345), + SART_TEST_PG(0x40))); + sart_test_model(t, 2, t->ver->allow, 0x812345, 0x40); + + sart_test_snapshot(test, t); + sart_test_check(test, t); + sart_test_power_loss(t); + + /* A wake that the firmware did not carry out leaves the SART alone */ + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + KUNIT_EXPECT_TRUE(test, sart->saved_valid); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); + KUNIT_EXPECT_FALSE(test, sart->saved_valid); + KUNIT_EXPECT_TRUE(test, sart->replay_valid); + KUNIT_EXPECT_EQ(test, sart->used_entries, BIT(1) | BIT(2)); + + /* The snapshot is used once */ + sart_test_power_loss(t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); +} + +/* + * What the wake does with entries nobody uses that don't read empty after the + * sleep. Before SARTv4 they are left alone. SARTv4 empties them again, except + * the last one, which is only written when in use or whole in the snapshot. + */ +static void sart_test_resume_idle_entries(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v4 = t->ver->ops == &sart_ops_v4; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 0, t->ver->allow, 0x4000, 4); + sart_test_snapshot(test, t); + + sart_test_power_loss(t); + /* Left behind by the power-up in entries 5 and 15 */ + sart_test_wr(t, 0x14, t->ver->size_reg ? 0xff : 0xff000000); + sart_test_wr(t, t->ver->paddr_reg + 0x14, 0x1234); + sart_test_wr(t, 0x3c, t->ver->size_reg ? 0xff : 0xff000000); + if (!v4) { + t->expect[0x14 / 4] = sart_test_rd(t, 0x14); + t->expect[(t->ver->paddr_reg + 0x14) / 4] = 0x1234; + } + t->expect[0x3c / 4] = sart_test_rd(t, 0x3c); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); +} + +/* The last entry is written back like any other when a driver uses it */ +static void sart_test_resume_last_in_use(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + int i; + + for (i = 0; i < 16; i++) { + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000 + i), + SART_TEST_PG(1 + i))); + sart_test_model(t, i, t->ver->allow, 0x4000 + i, 1 + i); + } + sart_test_snapshot(test, t); + sart_test_power_loss(t); + sart_test_wr(t, 0x3c, t->ver->size_reg ? 0xff : 0xff000000); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); +} + +/* The replay before a coprocessor's run bit: SARTv3 and SARTv4, after a wake */ +static void sart_test_replay(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v3 = t->ver->size_reg; + + sart_test_preload(t, 0, t->ver->allow, 0x800000, 0x400); + sart->protected_entries = BIT(0); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x812345), + SART_TEST_PG(0x40))); + sart_test_model(t, 1, t->ver->allow, 0x812345, 0x40); + + /* No sleep yet: nothing to replay */ + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + sart_test_power_loss(t); + pm_set_resume_via_firmware(); + KUNIT_ASSERT_EQ(test, 0, apple_sart_resume_noirq(sart->dev)); + sart_test_check(test, t); + + /* The coprocessor's domain cycled once more after the wake */ + sart_test_power_loss(t); + if (!v3) { + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_replay(sart)); + KUNIT_EXPECT_EQ(test, sart_test_nonzero(t), 0); + return; + } + KUNIT_EXPECT_EQ(test, 0, apple_sart_replay(sart)); + sart_test_check(test, t); + + /* An entry that does not hold what was written is counted */ + sart->saved[1].paddr |= BIT_ULL(50); + KUNIT_EXPECT_EQ(test, 1, apple_sart_replay(sart)); + sart_test_check(test, t); +} + +/* The check before a sleep exists on SARTv4 only, and needs the snapshot */ +static void sart_test_sleep_validate_unsupported(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, test->param_value); + struct apple_sart *sart = &t->sart; + bool v4 = t->ver->ops == &sart_ops_v4; + + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + KUNIT_EXPECT_EQ(test, -EOPNOTSUPP, apple_sart_sleep_validate(sart)); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, v4 ? 0 : -EOPNOTSUPP, apple_sart_sleep_validate(sart)); +} + +static struct sart_test *sart_test_validate_new(struct kunit *test) +{ + struct sart_test *t = sart_test_new(test, &sart_test_vers[3]); + struct apple_sart *sart = &t->sart; + + sart_test_preload(t, 0, 0xff, 0x800000, 0x400); + sart->protected_entries = BIT(0); + KUNIT_ASSERT_EQ(test, 0, + apple_sart_add_allowed_region(sart, SART_TEST_PG(0x4000), + SART_TEST_PG(4))); + sart_test_model(t, 1, 0xff, 0x4000, 4); + return t; +} + +/* Entries that moved after the snapshot refuse the sleep */ +static void sart_test_sleep_validate_changed(struct kunit *test) +{ + struct sart_test *t = sart_test_validate_new(test); + struct apple_sart *sart = &t->sart; + + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + /* Entry 1: address, size, flags; then an idle entry that appeared */ + sart_test_wr(t, 0x64, 0x4001); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x64, 0x4000); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + sart_test_wr(t, 0xc4, 5); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0xc4, 4); + + sart_test_wr(t, 0x04, 0x7f); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x04, 0xff); + + sart_test_wr(t, 0x3c, 0xff); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart_test_wr(t, 0x3c, 0); + + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + /* The check is read-only */ + sart_test_check(test, t); + KUNIT_EXPECT_TRUE(test, sart->saved_valid); +} + +/* Flags without a range: fine in an entry nobody uses, not in anyone's */ +static void sart_test_sleep_validate_flags_only(struct kunit *test) +{ + struct sart_test *t = sart_test_validate_new(test); + struct apple_sart *sart = &t->sart; + + sart_test_wr(t, 0x3c, 0xff); + sart_test_wr(t, 0x14, 0x01); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); + + /* The same in the bootloader's entry */ + sart->protected_entries |= BIT(15); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart->protected_entries &= ~BIT(15); + + /* The same in a driver's entry */ + sart->used_entries |= BIT(5); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + sart->used_entries &= ~BIT(5); + KUNIT_EXPECT_EQ(test, 0, apple_sart_sleep_validate(sart)); +} + +/* Half an entry refuses the sleep, whoever's it is */ +static void sart_test_sleep_validate_half_set(struct kunit *test) +{ + struct sart_test *t; + struct apple_sart *sart; + + /* Idle: flags and an address, no size */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x14, 0xff); + sart_test_wr(t, 0x74, 0x1234); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + /* Idle: a range, no flags */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x74, 0x1234); + sart_test_wr(t, 0xd4, 0x10); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + /* A driver's: flags, no size */ + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0xc4, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); +} + +/* An entry that is someone's and reads empty refuses the sleep */ +static void sart_test_sleep_validate_in_use_empty(struct kunit *test) +{ + struct sart_test *t; + struct apple_sart *sart; + + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x04, 0); + sart_test_wr(t, 0x64, 0); + sart_test_wr(t, 0xc4, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); + + t = sart_test_validate_new(test); + sart = &t->sart; + sart_test_wr(t, 0x00, 0); + sart_test_wr(t, 0x60, 0); + sart_test_wr(t, 0xc0, 0); + sart_test_snapshot(test, t); + KUNIT_EXPECT_EQ(test, -ESTALE, apple_sart_sleep_validate(sart)); +} +#endif /* CONFIG_SUSPEND */ + +static struct kunit_case sart_test_cases[] = { + KUNIT_CASE(sart_test_add_encoding), + KUNIT_CASE_PARAM(sart_test_add_fills_table, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_skips_protected, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_rejects_unaligned, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_add_size_max, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_high_paddr, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_get_entry, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_frees_slot, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_nonexistent, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_remove_protected, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_inherited_region, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_shutdown, sart_test_ver_gen_params), + KUNIT_CASE(sart_test_of_match), + KUNIT_CASE(sart_test_get_no_phandle), +#ifdef CONFIG_SUSPEND + KUNIT_CASE_PARAM(sart_test_suspend_not_firmware, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_suspend_resume, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_resume_idle_entries, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_resume_last_in_use, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_replay, sart_test_ver_gen_params), + KUNIT_CASE_PARAM(sart_test_sleep_validate_unsupported, sart_test_ver_gen_params), + KUNIT_CASE(sart_test_sleep_validate_changed), + KUNIT_CASE(sart_test_sleep_validate_flags_only), + KUNIT_CASE(sart_test_sleep_validate_half_set), + KUNIT_CASE(sart_test_sleep_validate_in_use_empty), +#endif + {} +}; + +static struct kunit_suite sart_test_suite = { + .name = "apple-sart", + .test_cases = sart_test_cases, +}; +kunit_test_suite(sart_test_suite); diff --git a/drivers/soc/apple/sart.c b/drivers/soc/apple/sart.c index c6436bd645eaa8..44bf2fe4cb915a 100644 --- a/drivers/soc/apple/sart.c +++ b/drivers/soc/apple/sart.c @@ -609,3 +609,7 @@ module_platform_driver(apple_sart_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SART driver"); + +#if IS_ENABLED(CONFIG_APPLE_SART_KUNIT_TEST) +#include "sart-test.c" +#endif diff --git a/drivers/soc/apple/sart.kunitconfig b/drivers/soc/apple/sart.kunitconfig new file mode 100644 index 00000000000000..88ab5d0cf2be34 --- /dev/null +++ b/drivers/soc/apple/sart.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_APPLE_SART=y +CONFIG_APPLE_SART_KUNIT_TEST=y From ba4b931a5b2971732525a3009256f1a51ed737aa Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:38:40 +1100 Subject: [PATCH 0536/1514] soc: apple: tunable: add KUnit tests Hardware tunables come from devicetree properties of (offset, mask, value) triplets and are written into a device's MMIO range. Add a suite that parses properties of a device node built by the test and applies the result to a buffer of kernel memory: the triplet decoding, the refusal of a missing, empty or badly sized property, of offsets that are unaligned or past the end of the resource, and the mask and value arithmetic and order of the writes. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 14 + drivers/soc/apple/Makefile | 1 + drivers/soc/apple/tunable-test.c | 372 ++++++++++++++++++++++++++ drivers/soc/apple/tunable.kunitconfig | 4 + 4 files changed, 391 insertions(+) create mode 100644 drivers/soc/apple/tunable-test.c create mode 100644 drivers/soc/apple/tunable.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..c1a912f4677872 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -167,6 +167,20 @@ config APPLE_TUNABLE tristate depends on ARCH_APPLE || COMPILE_TEST +config APPLE_TUNABLE_KUNIT_TEST + tristate "KUnit tests for Apple Silicon hardware tunables" if !KUNIT_ALL_TESTS + depends on KUNIT && ARM64 && OF + depends on ARCH_APPLE || COMPILE_TEST + select APPLE_TUNABLE + default KUNIT_ALL_TESTS + help + Parse tunable properties from a device node built by the test and + apply them to a buffer of kernel memory: the triplet decoding, the + length, alignment and bounds checks, and the mask and value + arithmetic. The tests touch no hardware. + + If unsure, say N. + config RUST_APPLE_MAILBOX bool depends on PM diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 233df860395b8c..6ce2050c293e61 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -47,6 +47,7 @@ DTC_FLAGS_t6041-gate-test := -Wno-unit_address_vs_reg -Wno-avoid_unnecessary_add obj-$(CONFIG_APPLE_TUNABLE) += apple-tunable.o apple-tunable-y = tunable.o +obj-$(CONFIG_APPLE_TUNABLE_KUNIT_TEST) += tunable-test.o obj-$(CONFIG_APPLE_AOP) += aop.o diff --git a/drivers/soc/apple/tunable-test.c b/drivers/soc/apple/tunable-test.c new file mode 100644 index 00000000000000..7fa59a771e39e4 --- /dev/null +++ b/drivers/soc/apple/tunable-test.c @@ -0,0 +1,372 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple Silicon hardware tunable library. + * + * The property a boot stage would pass comes from a device node built by + * the test, and the registers the tunable is applied to are a buffer of + * kernel memory. No device tree of the machine and no MMIO is touched. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#define TUNABLE_TEST_PROP "apple,tunable-test" +#define TUNABLE_TEST_NREGS 8 + +struct tunable_test { + struct device *dev; + struct device_node np; + struct property prop; + __le32 regs[TUNABLE_TEST_NREGS]; +}; + +static int tunable_test_init(struct kunit *test) +{ + struct tunable_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "tunable-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + test->priv = t; + + return 0; +} + +/* Parse a property of len bytes holding the cells, for res_size bytes at start */ +static struct apple_tunable *tunable_test_parse_at(struct kunit *test, const u32 *cells, + size_t len, resource_size_t start, + resource_size_t res_size) +{ + struct tunable_test *t = test->priv; + struct resource res = DEFINE_RES_MEM(start, res_size); + __be32 *value; + size_t i; + + value = kunit_kzalloc(test, round_up(len, 4) + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + for (i = 0; i < DIV_ROUND_UP(len, 4); i++) + value[i] = cpu_to_be32(cells[i]); + + t->prop.name = (char *)TUNABLE_TEST_PROP; + t->prop.value = value; + t->prop.length = len; + t->np.properties = &t->prop; + + return devm_apple_tunable_parse(t->dev, &t->np, TUNABLE_TEST_PROP, &res); +} + +static struct apple_tunable *tunable_test_parse(struct kunit *test, const u32 *cells, + size_t len, resource_size_t res_size) +{ + return tunable_test_parse_at(test, cells, len, 0x2a0000000ULL, res_size); +} + +static u32 tunable_test_rd(struct tunable_test *t, unsigned int reg) +{ + return le32_to_cpu(t->regs[reg / 4]); +} + +static void tunable_test_apply(struct tunable_test *t, struct apple_tunable *tunable) +{ + apple_tunable_apply((void __iomem __force *)t->regs, tunable); +} + +/* Each [offset, mask, value] triplet of big-endian cells becomes one entry */ +static void tunable_test_parse_triplets(struct kunit *test) +{ + static const u32 cells[] = { + 0x00, 0x000000ff, 0x00000012, + 0x1c, 0xffff0000, 0xabcd0000, + 0x04, 0x80000001, 0x80000000, + }; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_ASSERT_EQ(test, tunable->sz, 3); + KUNIT_EXPECT_EQ(test, tunable->values[0].offset, 0x00); + KUNIT_EXPECT_EQ(test, tunable->values[0].mask, 0x000000ff); + KUNIT_EXPECT_EQ(test, tunable->values[0].value, 0x00000012); + KUNIT_EXPECT_EQ(test, tunable->values[1].offset, 0x1c); + KUNIT_EXPECT_EQ(test, tunable->values[1].mask, 0xffff0000); + KUNIT_EXPECT_EQ(test, tunable->values[1].value, 0xabcd0000); + KUNIT_EXPECT_EQ(test, tunable->values[2].offset, 0x04); + KUNIT_EXPECT_EQ(test, tunable->values[2].mask, 0x80000001); + KUNIT_EXPECT_EQ(test, tunable->values[2].value, 0x80000000); +} + +static void tunable_test_parse_missing(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12 }; + struct tunable_test *t = test->priv; + struct resource res = DEFINE_RES_MEM(0x2a0000000ULL, 0x20); + struct apple_tunable *tunable; + + /* A node without properties */ + tunable = devm_apple_tunable_parse(t->dev, &t->np, TUNABLE_TEST_PROP, &res); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -ENOENT); + + /* A node with another one */ + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + tunable = devm_apple_tunable_parse(t->dev, &t->np, "apple,tunable-other", &res); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -ENOENT); +} + +/* A property that is not whole triplets is refused */ +static void tunable_test_parse_bad_length(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12, 0x04, 0xff, 0x34 }; + static const size_t bad[] = { 1, 4, 8, 11, 13, 16, 20, 23 }; + struct apple_tunable *tunable; + int i; + + for (i = 0; i < ARRAY_SIZE(bad); i++) { + tunable = tunable_test_parse(test, cells, bad[i], 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "length %zu", bad[i]); + } + + tunable = tunable_test_parse(test, cells, 12, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 1); + tunable = tunable_test_parse(test, cells, 24, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 2); +} + +/* An empty property is a tunable with nothing to apply */ +static void tunable_test_parse_empty(struct kunit *test) +{ + static const u32 cells[] = { 0 }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, 0, 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + KUNIT_EXPECT_EQ(test, tunable->sz, 0); + + t->regs[0] = cpu_to_le32(0x12345678); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0), 0x12345678); +} + +/* A resource without room for one register takes no tunable */ +static void tunable_test_parse_small_resource(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0xff, 0x12 }; + struct apple_tunable *tunable; + resource_size_t size; + + for (size = 0; size < 4; size++) { + tunable = tunable_test_parse(test, cells, sizeof(cells), size); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "resource of %llu bytes", (u64)size); + /* Not even an empty one */ + tunable = tunable_test_parse(test, cells, 0, size); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "resource of %llu bytes", (u64)size); + } + + tunable = tunable_test_parse(test, cells, sizeof(cells), 4); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); +} + +/* Registers are 32 bits wide: an offset between two of them is refused */ +static void tunable_test_parse_unaligned_offset(struct kunit *test) +{ + u32 cells[] = { + 0x00, 0xff, 0x12, + 0x00, 0xff, 0x34, + }; + struct apple_tunable *tunable; + u32 off; + + for (off = 1; off < 8; off++) { + if (off == 4) + continue; + /* In the first triplet, then in the last */ + cells[0] = off; + cells[3] = 0; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "offset %u", off); + cells[0] = 0; + cells[3] = off; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ_MSG(test, PTR_ERR_OR_ZERO(tunable), -EINVAL, + "offset %u", off); + } +} + +/* The last register of the resource is the last offset taken */ +static void tunable_test_parse_offset_bounds(struct kunit *test) +{ + u32 cells[] = { + 0x00, 0xff, 0x12, + 0x00, 0xff, 0x34, + }; + struct apple_tunable *tunable; + + cells[3] = 0x1c; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + + cells[3] = 0x20; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + cells[3] = 0x24; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + cells[3] = 0xfffffffc; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + + /* In the first triplet too */ + cells[0] = 0x20; + cells[3] = 0; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + cells[0] = 0; + + /* A register that only starts inside the resource is outside */ + cells[3] = 0x1c; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x1f); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); + cells[3] = 0x18; + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x1f); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + + /* One register */ + cells[3] = 0x04; + tunable = tunable_test_parse(test, cells, sizeof(cells), 4); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); +} + +/* Offsets count from the start of the resource, wherever that is */ +static void tunable_test_parse_resource_start(struct kunit *test) +{ + static const u32 cells[] = { 0x1c, 0xff, 0x12 }; + struct apple_tunable *tunable; + + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0, 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0x10, 0x20); + KUNIT_EXPECT_FALSE(test, IS_ERR(tunable)); + tunable = tunable_test_parse_at(test, cells, sizeof(cells), 0x10, 0x1c); + KUNIT_EXPECT_EQ(test, PTR_ERR_OR_ZERO(tunable), -EINVAL); +} + +/* Applying clears the mask's bits and sets the value's, elsewhere nothing */ +static void tunable_test_apply_mask_value(struct kunit *test) +{ + static const u32 cells[] = { + 0x04, 0x00ff00ff, 0x00120034, + 0x1c, 0xffffffff, 0xdeadbeef, + 0x0c, 0x00000000, 0x00000000, + 0x10, 0xf0000000, 0x00000000, + }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + int i; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + for (i = 0; i < TUNABLE_TEST_NREGS; i++) + t->regs[i] = cpu_to_le32(0xa5a5a500 + i); + tunable_test_apply(t, tunable); + + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0xa5a5a500); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x04), 0xa512a534); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x08), 0xa5a5a502); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x0c), 0xa5a5a503); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x10), 0x05a5a504); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x14), 0xa5a5a505); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x18), 0xa5a5a506); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x1c), 0xdeadbeef); + + /* Applying it again changes nothing */ + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x04), 0xa512a534); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x10), 0x05a5a504); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x1c), 0xdeadbeef); +} + +/* Entries are applied in the property's order, each on the last one's result */ +static void tunable_test_apply_order(struct kunit *test) +{ + static const u32 cells[] = { + 0x08, 0x0000ffff, 0x00001111, + 0x08, 0x00000ff0, 0x00000220, + 0x08, 0xff000000, 0x33000000, + }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + t->regs[2] = cpu_to_le32(0xffffffff); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x08), 0x33ff1221); +} + +/* The value's bits are set as given, the mask only says what to clear first */ +static void tunable_test_apply_value_outside_mask(struct kunit *test) +{ + static const u32 cells[] = { 0x00, 0x0000000f, 0x00000105 }; + struct tunable_test *t = test->priv; + struct apple_tunable *tunable; + + tunable = tunable_test_parse(test, cells, sizeof(cells), 0x20); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, tunable); + + t->regs[0] = cpu_to_le32(0x0000f00a); + tunable_test_apply(t, tunable); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0x0000f105); +} + +/* A driver may apply a tunable that its device tree doesn't have */ +static void tunable_test_apply_null(struct kunit *test) +{ + struct tunable_test *t = test->priv; + + t->regs[0] = cpu_to_le32(0x12345678); + tunable_test_apply(t, NULL); + KUNIT_EXPECT_EQ(test, tunable_test_rd(t, 0x00), 0x12345678); +} + +static struct kunit_case tunable_test_cases[] = { + KUNIT_CASE(tunable_test_parse_triplets), + KUNIT_CASE(tunable_test_parse_missing), + KUNIT_CASE(tunable_test_parse_bad_length), + KUNIT_CASE(tunable_test_parse_empty), + KUNIT_CASE(tunable_test_parse_small_resource), + KUNIT_CASE(tunable_test_parse_unaligned_offset), + KUNIT_CASE(tunable_test_parse_offset_bounds), + KUNIT_CASE(tunable_test_parse_resource_start), + KUNIT_CASE(tunable_test_apply_mask_value), + KUNIT_CASE(tunable_test_apply_order), + KUNIT_CASE(tunable_test_apply_value_outside_mask), + KUNIT_CASE(tunable_test_apply_null), + {} +}; + +static struct kunit_suite tunable_test_suite = { + .name = "apple-tunable", + .init = tunable_test_init, + .test_cases = tunable_test_cases, +}; +kunit_test_suite(tunable_test_suite); + +MODULE_LICENSE("Dual MIT/GPL"); +MODULE_DESCRIPTION("KUnit tests for Apple Silicon hardware tunable support"); diff --git a/drivers/soc/apple/tunable.kunitconfig b/drivers/soc/apple/tunable.kunitconfig new file mode 100644 index 00000000000000..fb06c16954cb22 --- /dev/null +++ b/drivers/soc/apple/tunable.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_APPLE_TUNABLE_KUNIT_TEST=y From 8b5a4e4c836e8820587d16906fdb764b78f0de4a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:39:07 +1100 Subject: [PATCH 0537/1514] cpufreq: apple-soc: add KUnit tests The Apple SoC cpufreq driver had no test. Add a suite that runs the driver's own request and readback paths on a cluster register block in kernel memory: - the command and status field layout of every SoC the driver matches, and the writes a P-state request makes (with and without the wait for the previous one, and the lazily verified path that checks the result later); - requests outside the P-state range, a busy or unexpected status, the fast switch path, and the P-state to frequency mapping; - the fast die-temperature limit: its devicetree parsing (absent, required, described and invalid), the fit and the cap it applies; - get() readback of every status value, suspend/resume of the lazy path, and the cap applied while another driver owns board thermals. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/cpufreq/Kconfig.arm | 16 + drivers/cpufreq/apple-soc-cpufreq-test.c | 1529 +++++++++++++++++ drivers/cpufreq/apple-soc-cpufreq.c | 4 + drivers/cpufreq/apple-soc-cpufreq.kunitconfig | 9 + 4 files changed, 1558 insertions(+) create mode 100644 drivers/cpufreq/apple-soc-cpufreq-test.c create mode 100644 drivers/cpufreq/apple-soc-cpufreq.kunitconfig diff --git a/drivers/cpufreq/Kconfig.arm b/drivers/cpufreq/Kconfig.arm index a441668f9e0cc6..885564633bce7c 100644 --- a/drivers/cpufreq/Kconfig.arm +++ b/drivers/cpufreq/Kconfig.arm @@ -32,6 +32,22 @@ config ARM_APPLE_SOC_CPUFREQ This adds the CPUFreq driver for Apple Silicon machines (e.g. Apple M1). +config ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST + bool "KUnit tests for Apple Silicon SoC CPUFreq" if !KUNIT_ALL_TESTS + depends on ARM_APPLE_SOC_CPUFREQ=y && KUNIT=y + depends on ARM64 + default KUNIT_ALL_TESTS + help + Build tests for the Apple Silicon CPU cluster performance state + driver: the command and status register layout of each SoC, the + waited-for and the lazily verified request paths, the fast + die-temperature limit and its devicetree parsing, and the board + thermal ownership cap. The cluster registers are ordinary memory, + which the MMIO accessors of arm64 can read and write; no hardware + is accessed. + + If unsure, say N. + config ARM_ARMADA_37XX_CPUFREQ tristate "Armada 37xx CPUFreq support" depends on ARCH_MVEBU || COMPILE_TEST diff --git a/drivers/cpufreq/apple-soc-cpufreq-test.c b/drivers/cpufreq/apple-soc-cpufreq-test.c new file mode 100644 index 00000000000000..9e356e385e083e --- /dev/null +++ b/drivers/cpufreq/apple-soc-cpufreq-test.c @@ -0,0 +1,1529 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC CPU cluster performance state driver: the + * per-SoC command and status register layouts, the waited-for and the lazily + * verified request paths, the fast die-temperature limit arithmetic and its + * devicetree parsing, and the board thermal ownership cap. + * + * The cluster registers are a block of ordinary memory: the driver only uses + * plain MMIO accessors on its base pointer, and no test maps a device. A + * written request reads back as accepted, as on an idle cluster; a test sets + * the busy bit or another state itself to play the hardware. + * + * Most tests run on a cpufreq policy that is not known to the cpufreq core. + * The ->get() and thermal ownership tests need a policy of the core, so their + * suite registers a cpufreq driver of its own, whose requests do nothing, and + * is skipped where a cpufreq driver is already registered. + * + * Included by apple-soc-cpufreq.c. + */ + +#include +#include +#include + +#define CFT_REGS_SIZE 0x100 +#define CFT_NR_STATES 5 + +/* Frequencies in kHz and the P-state (OPP level) of each; made-up values. */ +static const struct cpufreq_frequency_table cft_table[CFT_NR_STATES + 1] = { + { .driver_data = 1, .frequency = 600000 }, + { .driver_data = 4, .frequency = 1200000 }, + { .driver_data = 7, .frequency = 1800000 }, + { .driver_data = 10, .frequency = 2400000 }, + { .driver_data = 15, .frequency = 3000000 }, + { .frequency = CPUFREQ_TABLE_END }, +}; + +struct cft_ctx { + struct cpufreq_policy *policy; + struct apple_cpu_priv *priv; + struct cpufreq_frequency_table *table; + u8 *regs; +}; + +static u64 cft_cmd(u8 *regs) +{ + return le64_to_cpup((__le64 *)(regs + APPLE_DVFS_CMD)); +} + +static void cft_set_cmd(u8 *regs, u64 val) +{ + *(__le64 *)(regs + APPLE_DVFS_CMD) = cpu_to_le64(val); +} + +static void cft_set_status(u8 *regs, u32 val) +{ + *(__le32 *)(regs + APPLE_DVFS_STATUS) = cpu_to_le32(val); +} + +static void cft_priv_init(struct apple_cpu_priv *priv, u8 *regs, + const struct apple_soc_cpufreq_info *info, + unsigned int pstate) +{ + /* As apple_soc_cpufreq_init() leaves it. */ + priv->reg_base = (void __iomem __force *)regs; + priv->info = info; + raw_spin_lock_init(&priv->lock); + hrtimer_setup(&priv->verify_timer, apple_soc_cpufreq_verify, + CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); + priv->pending_pstate = -1; + priv->cap_pstate = info->max_pstate; + priv->waited = true; + priv->expected_pstate = pstate; + cft_set_cmd(regs, pstate); +} + +/* A cluster of @info that idles in @pstate, with the cft_table states. */ +static struct cft_ctx *cft_setup(struct kunit *test, + const struct apple_soc_cpufreq_info *info, + unsigned int pstate) +{ + struct cft_ctx *prev = test->priv; + struct cft_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->regs = kunit_kzalloc(test, CFT_REGS_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->table = kunit_kzalloc(test, sizeof(cft_table), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->table); + memcpy(ctx->table, cft_table, sizeof(cft_table)); + ctx->policy = kunit_kzalloc(test, sizeof(*ctx->policy), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->policy); + ctx->priv = kunit_kzalloc(test, sizeof(*ctx->priv), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->priv); + + /* A test may set up one cluster after another, on the same device. */ + if (prev) { + hrtimer_cancel(&prev->priv->verify_timer); + ctx->priv->cpu_dev = prev->priv->cpu_dev; + } else { + ctx->priv->cpu_dev = kunit_device_register(test, "apple-cpufreq-test"); + } + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->priv->cpu_dev); + cft_priv_init(ctx->priv, ctx->regs, info, pstate); + + ctx->policy->freq_table = ctx->table; + ctx->policy->freq_table_sorted = CPUFREQ_TABLE_SORTED_ASCENDING; + ctx->policy->min = ctx->table[0].frequency; + ctx->policy->max = ctx->table[CFT_NR_STATES - 1].frequency; + ctx->policy->cur = ctx->table[0].frequency; + ctx->policy->driver_data = ctx->priv; + + test->priv = ctx; + return ctx; +} + +static void cft_exit(struct kunit *test) +{ + struct cft_ctx *ctx = test->priv; + + if (ctx && ctx->priv) + hrtimer_cancel(&ctx->priv->verify_timer); +} + +/* + * The lazily verified paths arm the verify timer, a hard interrupt timer due + * within a millisecond or less. A test calls them with interrupts off, so + * that the timer cannot run, and ends the section here: this returns whether + * the timer was armed, and cancels it. The test then runs the timer callback + * itself, in the state it has prepared. + */ +static bool cft_thaw(struct cft_ctx *ctx, unsigned long flags) +{ + bool queued = hrtimer_is_queued(&ctx->priv->verify_timer); + + hrtimer_cancel(&ctx->priv->verify_timer); + local_irq_restore(flags); + return queued; +} + +/* Runs the verify timer callback once, as cft_thaw() describes. */ +static bool cft_verify(struct cft_ctx *ctx) +{ + unsigned long flags; + + local_irq_save(flags); + apple_soc_cpufreq_verify(&ctx->priv->verify_timer); + return cft_thaw(ctx, flags); +} + +static bool cft_lazy_request(struct cft_ctx *ctx, unsigned int index, + unsigned int *freq) +{ + unsigned long flags; + + local_irq_save(flags); + *freq = apple_soc_cpufreq_lazy_request(ctx->policy, index); + return cft_thaw(ctx, flags); +} + +static bool cft_lazy_cap(struct cft_ctx *ctx, unsigned int cap, + unsigned int freq, int *moved) +{ + unsigned long flags; + + local_irq_save(flags); + *moved = apple_soc_cpufreq_lazy_cap(ctx->priv, cap, freq); + return cft_thaw(ctx, flags); +} + +/* + * Register layouts + */ + +struct cft_layout { + const char *compatible; + u64 ps1_mask; + u64 cur_pstate_mask; + u64 min_pstate; + u64 max_pstate; + bool has_ps2; +}; + +static const struct cft_layout cft_layouts[] = { + { "apple,s5l8960x-cluster-cpufreq", GENMASK(24, 22), GENMASK(5, 3), 0, 7, false }, + { "apple,t8103-cluster-cpufreq", GENMASK(4, 0), GENMASK(7, 4), 0, 15, true }, + { "apple,t8112-cluster-cpufreq", GENMASK(4, 0), GENMASK(9, 5), 0, 31, false }, + { "apple,t8132-cluster-cpufreq", GENMASK(4, 0), 0, 0, 31, false }, + { "apple,cluster-cpufreq", GENMASK(4, 0), 0, 0, 15, false }, + { "apple,t8140-cluster-cpufreq", GENMASK(4, 0), 0, 1, 31, false }, + { "apple,t6050-cluster-cpufreq", GENMASK(4, 0), 0, 0, 31, false }, + { "apple,t8142-cluster-cpufreq", GENMASK(4, 0), 0, 1, 31, false }, + { "apple,t8152-cluster-cpufreq", GENMASK(4, 0), 0, 2, 31, false }, +}; + +static void cft_layout_desc(const struct cft_layout *l, char *desc) +{ + strscpy(desc, l->compatible, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_layout, cft_layouts, cft_layout_desc); + +static const struct apple_soc_cpufreq_info *cft_match(const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_soc_cpufreq_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) + return id->data; + return NULL; +} + +/* Each compatible selects the layout of its SoC. */ +static void cft_test_layout(struct kunit *test) +{ + const struct cft_layout *l = test->param_value; + const struct apple_soc_cpufreq_info *info = cft_match(l->compatible); + + KUNIT_ASSERT_NOT_NULL(test, info); + KUNIT_EXPECT_EQ(test, info->ps1_mask, l->ps1_mask); + KUNIT_EXPECT_EQ(test, info->ps1_shift, __ffs64(l->ps1_mask)); + KUNIT_EXPECT_EQ(test, info->cur_pstate_mask, l->cur_pstate_mask); + if (l->cur_pstate_mask) + KUNIT_EXPECT_EQ(test, info->cur_pstate_shift, + __ffs64(l->cur_pstate_mask)); + KUNIT_EXPECT_EQ(test, info->min_pstate, l->min_pstate); + KUNIT_EXPECT_EQ(test, info->max_pstate, l->max_pstate); + KUNIT_EXPECT_EQ(test, info->has_ps2, l->has_ps2); +} + +/* What every layout must satisfy for the request and readback code to work. */ +static void cft_test_layout_invariants(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_soc_cpufreq_of_match; id->compatible[0]; id++) { + const struct apple_soc_cpufreq_info *info = id->data; + + KUNIT_ASSERT_NOT_NULL_MSG(test, info, "%s", id->compatible); + KUNIT_ASSERT_NE_MSG(test, info->ps1_mask, 0, "%s", id->compatible); + /* The request field holds every P-state. */ + KUNIT_EXPECT_EQ_MSG(test, info->ps1_shift, __ffs64(info->ps1_mask), + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->min_pstate, info->max_pstate, + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + info->ps1_mask >> info->ps1_shift, + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_unmanaged_pstate, info->max_pstate, + "%s", id->compatible); + if (info->has_ps2) + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + FIELD_MAX(APPLE_DVFS_CMD_PS2), + "%s", id->compatible); + /* So does the status field, where the SoC has one. */ + if (info->cur_pstate_mask) { + KUNIT_EXPECT_EQ_MSG(test, info->cur_pstate_shift, + __ffs64(info->cur_pstate_mask), + "%s", id->compatible); + KUNIT_EXPECT_LE_MSG(test, info->max_pstate, + info->cur_pstate_mask >> info->cur_pstate_shift, + "%s", id->compatible); + } + /* Verification reads the request back as APPLE_DVFS_CMD_PS1. */ + if (info->verify_transition) + KUNIT_EXPECT_EQ_MSG(test, info->ps1_mask, APPLE_DVFS_CMD_PS1, + "%s", id->compatible); + } +} + +struct cft_write { + const char *name; + const struct apple_soc_cpufreq_info *info; + u64 before; + unsigned int pstate; + u64 after; +}; + +static const struct cft_write cft_writes[] = { + { "t8103 sets PS1 and PS2", &soc_t8103_info, 0, 9, + BIT(25) | (9 << 12) | 9 }, + { "t8103 replaces PS1 and PS2 only", &soc_t8103_info, ~0ULL, 9, + (~0ULL & ~(GENMASK_ULL(15, 12) | GENMASK_ULL(4, 0))) | (9 << 12) | 9 }, + { "t8112 sets PS1", &soc_t8112_info, 0, 21, BIT(25) | 21 }, + { "t8112 leaves the PS2 bits", &soc_t8112_info, ~0ULL, 21, + (~0ULL & ~GENMASK_ULL(4, 0)) | 21 }, + { "s5l8960x sets bits 24:22", &soc_s5l8960x_info, 0, 5, + BIT(25) | (5 << 22) }, + { "s5l8960x replaces bits 24:22 only", &soc_s5l8960x_info, ~0ULL, 5, + (~0ULL & ~GENMASK_ULL(24, 22)) | (5 << 22) }, + { "t8140 highest state", &soc_t8140_info, 0, 31, BIT(25) | 31 }, + { "t8132 lowest state", &soc_t8132_info, GENMASK_ULL(4, 0), 0, BIT(25) }, + { "generic", &soc_default_info, 3, 12, BIT(25) | 12 }, +}; + +static void cft_write_desc(const struct cft_write *w, char *desc) +{ + strscpy(desc, w->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_write, cft_writes, cft_write_desc); + +/* A request replaces the state fields of its SoC and sets the SET bit. */ +static void cft_test_write(struct kunit *test) +{ + const struct cft_write *w = test->param_value; + struct cft_ctx *ctx = cft_setup(test, w->info, 0); + + apple_soc_cpufreq_write(ctx->priv, w->before, w->pstate); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), w->after); +} + +static void cft_test_timeout(struct kunit *test) +{ + static const struct apple_soc_cpufreq_info own = { + .transition_timeout_us = 1234, + }; + static const struct apple_soc_cpufreq_info none = {}; + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_timeout(&own), 1234); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_timeout(&none), + APPLE_DVFS_TRANSITION_TIMEOUT); +} + +/* + * Waited-for requests + */ + +/* The frequency-table index selects the P-state, not the other way round. */ +static void cft_test_request(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 3), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (10 << 12) | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (1 << 12) | 1); +} + +/* A P-state outside the range of the SoC is refused before any write. */ +static void cft_test_request_range(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + ctx->table[4].driver_data = 16; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 4), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + ctx->table[4].driver_data = 15; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 4), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + + /* The states of T8152 start at 2, those of T8140 at 1. */ + ctx = cft_setup(test, &soc_t8152_info, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); + ctx->table[0].driver_data = 2; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 2); + + ctx = cft_setup(test, &soc_t8140_info, 4); + ctx->table[0].driver_data = 0; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + ctx->table[0].driver_data = 1; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_request(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 1); +} + +/* A SoC that does not verify drops a request to a busy cluster, no more. */ +static void cft_test_set_pstate_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); + + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); +} + +static void cft_test_set_pstate_verified(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 10); + + /* The accepted state is not requested again. */ + cft_set_cmd(ctx->regs, 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 10); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); +} + +/* A state nobody asked for stops all requests: someone else owns the cluster. */ +static void cft_test_set_pstate_unexpected(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + cft_set_cmd(ctx->regs, 7); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_TRUE(test, ctx->priv->transition_failed); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 7); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); + + /* Not even one that would now match. */ + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); +} + +static void cft_test_set_pstate_verified_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_pstate(ctx->priv, 10), -EIO); + KUNIT_EXPECT_TRUE(test, ctx->priv->transition_failed); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); +} + +/* ->fast_switch() of a SoC that does not verify: lowest state at or above. */ +static void cft_test_fast_switch(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8103_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 1300000), + 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (7 << 12) | 7); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 600000), + 600000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (1 << 12) | 1); + /* The policy limits clamp the target. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, UINT_MAX), + 3000000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | (15 << 12) | 15); + ctx->policy->max = 2400000; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 3000000), + 2400000); + + /* 0 tells the scheduler that nothing was requested. */ + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_fast_switch(ctx->policy, 600000), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 10); +} + +static void cft_test_pstate_freq(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 1), 600000); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 15), 3000000); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 0), 0); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 5), 0); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 31), 0); + /* An entry the core has marked invalid has no frequency. */ + ctx->table[2].frequency = CPUFREQ_ENTRY_INVALID; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_pstate_freq(ctx->policy, 7), 0); +} + +/* + * Lazily verified requests + */ + +/* An idle cluster takes the request at once; the timer verifies it. */ +static void cft_test_lazy_idle(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, priv->waited); + KUNIT_EXPECT_EQ(test, ktime_us_delta(priv->verify_deadline, priv->write_time), + APPLE_DVFS_TRANSITION_TIMEOUT); + + /* The cluster accepted it: the timer has nothing to say or do. */ + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + /* The accepted state is not written again. */ + cft_set_cmd(ctx->regs, 10); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 10); +} + +/* A busy cluster keeps the newest request pending; the timer writes it. */ +static void cft_test_lazy_busy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + queued = cft_lazy_request(ctx, 3, &freq); + /* Committed all the same: schedutil does not ask twice. */ + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + KUNIT_EXPECT_NE(test, ktime_to_ns(priv->verify_deadline), 0); + + queued = cft_lazy_request(ctx, 2, &freq); + KUNIT_EXPECT_EQ(test, freq, 1800000); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 7); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); + + /* Still busy, within the timeout: the timer looks again. */ + priv->verify_deadline = ktime_add_ms(ktime_get(), 60 * MSEC_PER_SEC); + KUNIT_EXPECT_TRUE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 7); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + + /* The transition finished as expected: the pending request goes out. */ + cft_set_cmd(ctx->regs, 4); + KUNIT_EXPECT_TRUE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); +} + +/* A pending request for the state the cluster settled in is not written. */ +static void cft_test_lazy_pending_same(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + + ctx->priv->pending_pstate = 4; + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_EQ(test, ctx->priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, ctx->priv->transition_failed); +} + +/* An unexpected state fails the request; the timer reports it, once. */ +static void cft_test_lazy_unexpected(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + + cft_set_cmd(ctx->regs, 9); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_TRUE(test, priv->failure_unreported); + KUNIT_EXPECT_EQ(test, priv->failure_command, 9); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 9); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + /* No request after a failure, even one that would now match. */ + cft_set_cmd(ctx->regs, 4); + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + priv->pending_pstate = 10; + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); +} + +/* The timer finds what a request did not: the last request of a burst. */ +static void cft_test_lazy_verify_fails(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + /* The state changed under us. */ + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + KUNIT_EXPECT_EQ(test, priv->failure_command, 9); + + /* Busy for longer than the timeout; the pending request is dropped. */ + ctx = cft_setup(test, &soc_t8140_info, 4); + priv = ctx->priv; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 4); + priv->pending_pstate = 7; + priv->verify_deadline = ktime_sub_us(ktime_get(), 1); + KUNIT_EXPECT_FALSE(test, cft_verify(ctx)); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_EQ(test, priv->failure_command, APPLE_DVFS_CMD_BUSY | 4); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), APPLE_DVFS_CMD_BUSY | 4); +} + +static void cft_test_lazy_range(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + unsigned int freq; + bool queued; + + ctx->table[3].driver_data = 0; + queued = cft_lazy_request(ctx, 3, &freq); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + /* Not a fast-switch request at all: waited-for requests keep the cluster. */ + KUNIT_EXPECT_TRUE(test, ctx->priv->waited); +} + +/* ->fast_switch() of a lazily verified SoC, with and without a limit. */ +static void cft_test_lazy_fast_switch(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned long flags; + unsigned int freq; + bool queued; + + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 1300000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + + /* Above the limit: the limit is requested, and returned. */ + priv->cap_pstate = 4; + priv->cap_freq = 1200000; + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 3000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, freq, 1200000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 4); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 15); + + /* At the limit: as asked. */ + local_irq_save(flags); + freq = apple_soc_cpufreq_fast_switch(ctx->policy, 1200000); + cft_thaw(ctx, flags); + KUNIT_EXPECT_EQ(test, freq, 1200000); + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 4); +} + +/* A new limit moves the cluster at once, down and back up. */ +static void cft_test_lazy_cap(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + int moved; + + cft_lazy_request(ctx, 4, &freq); + KUNIT_ASSERT_EQ(test, freq, 3000000); + KUNIT_ASSERT_EQ(test, priv->expected_pstate, 15); + + queued = cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, moved, 7); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 1800000); + /* What the scheduler asked for is remembered. */ + KUNIT_EXPECT_EQ(test, priv->asked_pstate, 15); + + /* Nothing to move when the limit is already applied. */ + cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + + /* A lower state than the limit stays where the scheduler put it. */ + cft_lazy_request(ctx, 1, &freq); + KUNIT_EXPECT_EQ(test, freq, 1200000); + cft_lazy_cap(ctx, 10, 2400000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 4); + + /* The limit rises before schedutil saw it fall: the request is restored. */ + cft_lazy_request(ctx, 4, &freq); + KUNIT_EXPECT_EQ(test, freq, 2400000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 10); + cft_lazy_cap(ctx, 31, 3000000, &moved); + KUNIT_EXPECT_EQ(test, moved, 15); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + + /* A busy cluster gets the limit as its pending request. */ + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 15); + queued = cft_lazy_cap(ctx, 4, 1200000, &moved); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, moved, 4); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, 4); + /* And is not asked again while that is pending. */ + cft_lazy_cap(ctx, 4, 1200000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); +} + +/* Waited-for requests own the cluster: the limit is recorded, no more. */ +static void cft_test_lazy_cap_waited(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int freq; + bool queued; + int moved; + + queued = cft_lazy_cap(ctx, 1, 600000, &moved); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 1); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 600000); + + /* Nor is a cluster moved whose requests have stopped. */ + cft_lazy_request(ctx, 0, &freq); + KUNIT_ASSERT_EQ(test, freq, 600000); + priv->asked_pstate = 15; + priv->transition_failed = true; + cft_lazy_cap(ctx, 7, 1800000, &moved); + KUNIT_EXPECT_EQ(test, moved, -1); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 1); +} + +static void cft_test_drain(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + priv->waited = false; + priv->pending_pstate = 7; + priv->failure_unreported = true; + priv->failure_command = APPLE_DVFS_CMD_BUSY | 4; + hrtimer_start(&priv->verify_timer, ms_to_ktime(60 * MSEC_PER_SEC), + HRTIMER_MODE_REL_HARD); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_drain(priv), 7); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&priv->verify_timer)); + KUNIT_EXPECT_TRUE(test, priv->waited); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_FALSE(test, priv->failure_unreported); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_drain(priv), -1); +} + +/* ->target_index() replaces a pending request and waits for its own. */ +static void cft_test_set_target_lazy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + priv->waited = false; + priv->pending_pstate = 10; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_target(ctx->policy, 2), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 7); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_TRUE(test, priv->waited); +} + +/* Suspend settles the cluster and records where as policy->cur. */ +static void cft_test_suspend_lazy(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + + /* No suspend frequency: only the driver's own part runs. */ + ctx->policy->suspend_freq = 0; + + priv->waited = false; + priv->pending_pstate = 10; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), BIT(25) | 10); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 10); + KUNIT_EXPECT_EQ(test, priv->pending_pstate, -1); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 2400000); + + /* Nothing pending: policy->cur follows the accepted state. */ + ctx->policy->cur = 600000; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 2400000); + + /* A cluster that does not settle fails the suspend. */ + ctx->policy->cur = 600000; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 10); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_suspend(ctx->policy), -EIO); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 600000); +} + +/* After a firmware-driven sleep the state the cluster woke in is adopted. */ +static void cft_test_resume(struct kunit *test) +{ +#ifdef CONFIG_SUSPEND + struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); + struct apple_cpu_priv *priv = ctx->priv; + unsigned int flags = pm_suspend_global_flags; + + pm_suspend_clear_flags(); + + priv->transition_failed = true; + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 4); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + + pm_set_resume_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 9); + KUNIT_EXPECT_FALSE(test, priv->transition_failed); + + /* A busy cluster has no state to adopt yet. */ + priv->transition_failed = true; + cft_set_cmd(ctx->regs, APPLE_DVFS_CMD_BUSY | 12); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, priv->expected_pstate, 9); + KUNIT_EXPECT_TRUE(test, priv->transition_failed); + + /* A SoC that does not verify expects nothing. */ + ctx = cft_setup(test, &soc_t8112_info, 4); + cft_set_cmd(ctx->regs, 9); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); + KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); + + pm_suspend_global_flags = flags; +#else + kunit_skip(test, "needs CONFIG_SUSPEND"); +#endif +} + +/* + * Board thermal ownership cap + */ + +static void cft_test_unmanaged_max(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8132_info, 4); + unsigned int i; + + /* Highest state allowed without a thermal policy: 4. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 1200000); + + mutex_lock(&apple_soc_thermal_owner_lock); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_owner_cap(ctx->policy), 1200000); + ctx->priv->thermal_owned = true; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_owner_cap(ctx->policy), + FREQ_QOS_MAX_DEFAULT_VALUE); + mutex_unlock(&apple_soc_thermal_owner_lock); + + ctx->table[1].frequency = CPUFREQ_ENTRY_INVALID; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); + + /* No state is allowed: the slowest one has to do. */ + for (i = 0; i < CFT_NR_STATES; i++) + ctx->table[i].driver_data = 5 + i; + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); + + ctx = cft_setup(test, &soc_t8152_info, 4); + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_unmanaged_max(ctx->policy), 600000); +} + +/* + * Fast die-temperature limit + */ + +static const unsigned long cft_power[CFT_NR_STATES] = { 100, 300, 500, 800, 1000 }; + +/* A limit that only knows its policy and the power of each state. */ +static struct apple_fast_die *cft_fast_die(struct kunit *test, struct cft_ctx *ctx) +{ + struct apple_fast_die *fd; + unsigned int i; + + fd = kunit_kzalloc(test, struct_size(fd, power, CFT_NR_STATES), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fd); + fd->nr_states = CFT_NR_STATES; + for (i = 0; i < CFT_NR_STATES; i++) + fd->power[i] = cft_power[i]; + fd->policy = ctx->policy; + fd->max = ctx->table[CFT_NR_STATES - 1].frequency; + spin_lock_init(&fd->lock); + return fd; +} + +static bool cft_is_state(unsigned int freq) +{ + unsigned int i; + + for (i = 0; i < CFT_NR_STATES; i++) + if (cft_table[i].frequency == freq) + return true; + return false; +} + +static void cft_test_fast_die_fit(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + /* The slowest state when nothing fits. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 0), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 99), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 100), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 299), 600000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 300), 1200000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 999), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, 1000), 3000000); + KUNIT_EXPECT_EQ(test, apple_fast_die_fit(fd, U64_MAX), 3000000); +} + +static void cft_test_fast_die_limit(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + unsigned int effort, limit, last = UINT_MAX; + + /* No effort is no limit, whatever 1000 / 255 rounds to. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 0), 3000000); + /* 204 / 255 of 1000 is 800, 203 / 255 is 796. */ + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 1), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 51), 2400000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 52), 1800000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 128), 1200000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 255), 600000); + + for (effort = 0; effort <= APPLE_FAST_DIE_EFFORT_MAX; effort++) { + limit = apple_fast_die_limit(fd, effort); + KUNIT_EXPECT_LE_MSG(test, limit, last, "effort %u", effort); + KUNIT_EXPECT_TRUE_MSG(test, cft_is_state(limit), "effort %u: %u", + effort, limit); + last = limit; + } + + /* Tens of watts, in microwatts: the budget needs more than 32 bits. */ + fd->power[CFT_NR_STATES - 1] = 50000000; + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 0), 3000000); + KUNIT_EXPECT_EQ(test, apple_fast_die_limit(fd, 255), 600000); +} + +static void cft_test_fast_die_interval(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 5); + /* Warned, but the PMP runs: back to the fast interval. */ + fd->warned = true; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 5); + fd->waiting = true; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 1000); + fd->warned = false; + KUNIT_EXPECT_EQ(test, ktime_to_ms(apple_fast_die_interval(fd)), 100); +} + +/* The hrtimer samples only when the per-CPU timers do not. */ +static void cft_test_fast_die_arm(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + hrtimer_setup(&fd->poll, apple_fast_die_poll, CLOCK_MONOTONIC, + HRTIMER_MODE_REL_SOFT); + /* The slowest interval: the timer is cancelled long before it runs. */ + fd->waiting = true; + fd->warned = true; + + spin_lock_bh(&fd->lock); + fd->per_cpu = true; + fd->limit = fd->max; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, fd->polling); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + spin_lock_bh(&fd->lock); + fd->limit = fd->max - 1; + fd->stopping = true; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, fd->polling); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + spin_lock_bh(&fd->lock); + fd->stopping = false; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_TRUE(test, fd->polling); + KUNIT_EXPECT_TRUE(test, hrtimer_is_queued(&fd->poll)); + hrtimer_cancel(&fd->poll); + + /* Already polling: not armed twice. */ + spin_lock_bh(&fd->lock); + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_FALSE(test, hrtimer_is_queued(&fd->poll)); + + /* Without per-CPU timers the hrtimer samples at the maximum too. */ + spin_lock_bh(&fd->lock); + fd->polling = false; + fd->per_cpu = false; + fd->limit = fd->max; + apple_fast_die_arm(fd); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_TRUE(test, fd->polling); + KUNIT_EXPECT_TRUE(test, hrtimer_is_queued(&fd->poll)); + hrtimer_cancel(&fd->poll); +} + +/* A limit moves a lazily verified cluster and scaling_cur_freq with it. */ +static void cft_test_fast_die_cap(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8140_info, 4); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + struct apple_cpu_priv *priv = ctx->priv; + unsigned long flags; + unsigned int freq; + bool queued; + + cft_lazy_request(ctx, 4, &freq); + KUNIT_ASSERT_EQ(test, freq, 3000000); + ctx->policy->cur = freq; + + /* The fastest state at or below the limit. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 2000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, priv->cap_freq, 1800000); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 1800000); + + /* A limit below every state changes nothing. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 599999); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_FALSE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 7); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 7); + + /* A limit that is a state is that state. */ + local_irq_save(flags); + apple_fast_die_cap(fd, 3000000); + queued = cft_thaw(ctx, flags); + KUNIT_EXPECT_TRUE(test, queued); + KUNIT_EXPECT_EQ(test, priv->cap_pstate, 15); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_DVFS_CMD_PS1, cft_cmd(ctx->regs)), 15); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 3000000); +} + +/* A SoC whose requests the core limits is left to the core. */ +static void cft_test_fast_die_cap_unverified(struct kunit *test) +{ + struct cft_ctx *ctx = cft_setup(test, &soc_t8112_info, 15); + struct apple_fast_die *fd = cft_fast_die(test, ctx); + + ctx->policy->cur = 3000000; + apple_fast_die_cap(fd, 1800000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 15); + KUNIT_EXPECT_EQ(test, ctx->priv->cap_pstate, soc_t8112_info.max_pstate); + KUNIT_EXPECT_EQ(test, ctx->policy->cur, 3000000); +} + +static void cft_fast_die_exit(void *data) +{ + apple_fast_die_exit(data); +} + +static void cft_free_cpus(void *data) +{ + struct cpufreq_policy *policy = data; + + free_cpumask_var(policy->cpus); +} + +static void cft_remove_opps(void *data) +{ + dev_pm_opp_remove_all_dynamic(data); +} + +/* + * A cluster ready for apple_fast_die_init(): its CPU device has an OPP for + * every state, without power, and its policy has QoS constraints and no CPU, + * so that no per-CPU timer of the machine is touched. + */ +static struct cft_ctx *cft_fast_die_setup(struct kunit *test, + const struct apple_soc_cpufreq_info *info) +{ + struct cft_ctx *ctx = cft_setup(test, info, 4); + unsigned int i; + + KUNIT_ASSERT_TRUE(test, zalloc_cpumask_var(&ctx->policy->cpus, GFP_KERNEL)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_free_cpus, + ctx->policy), 0); + freq_constraints_init(&ctx->policy->constraints); + + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_remove_opps, + ctx->priv->cpu_dev), 0); + for (i = 0; i < CFT_NR_STATES; i++) { + struct dev_pm_opp_data opp = { + .level = ctx->table[i].driver_data, + .freq = ctx->table[i].frequency * 1000UL, + .u_volt = 800000, + }; + + KUNIT_ASSERT_EQ(test, dev_pm_opp_add_dynamic(ctx->priv->cpu_dev, &opp), 0); + } + + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_fast_die_exit, + ctx->priv), 0); + return ctx; +} + +/* A cluster node with @value as its apple,fast-die-effort, or without one. */ +static struct device_node *cft_cluster_node(struct kunit *test, __be32 *value, + unsigned int cells) +{ + struct device_node *np; + struct property *prop; + + np = kunit_kzalloc(test, sizeof(*np), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, np); + np->name = "cpufreq"; + np->full_name = "cpufreq-test"; + if (!value) + return np; + + prop = kunit_kzalloc(test, sizeof(*prop), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, prop); + prop->name = "apple,fast-die-effort"; + prop->value = value; + prop->length = cells * sizeof(*value); + np->properties = prop; + return np; +} + +static s32 cft_qos_max(struct cft_ctx *ctx) +{ + return freq_qos_read_value(&ctx->policy->constraints, FREQ_QOS_MAX); +} + +/* No limit described, none needed: nothing is set up. */ +static void cft_test_fast_die_init_none(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8112_info); + struct device_node *np = cft_cluster_node(test, NULL, 0); + + KUNIT_EXPECT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +/* A SoC that needs the limit is held at the fallback by an older devicetree. */ +static void cft_test_fast_die_init_required(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8140_info); + struct device_node *np = cft_cluster_node(test, NULL, 0); + struct apple_fast_die *fd; + unsigned int i; + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_NULL(test, fd->report); + KUNIT_EXPECT_TRUE(test, fd->warned); + KUNIT_EXPECT_EQ(test, fd->nr_states, CFT_NR_STATES); + /* The OPPs describe no power: the frequency stands in. */ + for (i = 0; i < CFT_NR_STATES; i++) + KUNIT_EXPECT_EQ(test, fd->power[i], ctx->table[i].frequency); + KUNIT_EXPECT_EQ(test, fd->max, 3000000); + /* The fastest state with at most a third of the fastest state's power. */ + KUNIT_EXPECT_EQ(test, fd->fallback, 600000); + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + /* Fast-switch requests are clamped from the start. */ + KUNIT_EXPECT_EQ(test, ctx->priv->cap_pstate, 1); + KUNIT_EXPECT_EQ(test, ctx->priv->cap_freq, 600000); + KUNIT_EXPECT_EQ(test, cft_cmd(ctx->regs), 4); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +/* The property names the PMP report node and the lane of the cluster. */ +static void cft_test_fast_die_init_described(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8140_info); + struct device_node *np, *report = NULL; + struct apple_fast_die *fd; + __be32 *value; + + /* Any node with a phandle can stand in for the report node. */ + for_each_of_allnodes(np) { + if (np->phandle) { + report = np; + break; + } + } + if (!report) + kunit_skip(test, "no devicetree node with a phandle"); + + value = kunit_kzalloc(test, 2 * sizeof(*value), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + value[0] = cpu_to_be32(report->phandle); + value[1] = cpu_to_be32(3); + np = cft_cluster_node(test, value, 2); + of_node_put(report); + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_PTR_EQ(test, fd->report, report); + KUNIT_EXPECT_EQ(test, fd->lane, 3); + KUNIT_EXPECT_FALSE(test, fd->warned); + /* Held at the fallback until the PMP is found running. */ + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_NULL(test, ctx->priv->fast_die); +} + +/* A misdescribed limit fails closed, also where none is required. */ +static void cft_test_fast_die_init_invalid(struct kunit *test) +{ + struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8112_info); + struct apple_fast_die *fd; + struct device_node *np; + __be32 *value; + + /* A phandle without the lane cell. */ + value = kunit_kzalloc(test, sizeof(*value), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, value); + value[0] = cpu_to_be32(1); + np = cft_cluster_node(test, value, 1); + + KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); + fd = ctx->priv->fast_die; + KUNIT_ASSERT_NOT_NULL(test, fd); + + spin_lock_bh(&fd->lock); + KUNIT_EXPECT_NULL(test, fd->report); + KUNIT_EXPECT_TRUE(test, fd->warned); + KUNIT_EXPECT_EQ(test, fd->limit, 600000); + spin_unlock_bh(&fd->lock); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), 600000); + + apple_fast_die_exit(ctx->priv); + KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); +} + +static struct kunit_case apple_soc_cpufreq_test_cases[] = { + KUNIT_CASE_PARAM(cft_test_layout, cft_layout_gen_params), + KUNIT_CASE(cft_test_layout_invariants), + KUNIT_CASE_PARAM(cft_test_write, cft_write_gen_params), + KUNIT_CASE(cft_test_timeout), + KUNIT_CASE(cft_test_request), + KUNIT_CASE(cft_test_request_range), + KUNIT_CASE(cft_test_set_pstate_busy), + KUNIT_CASE(cft_test_set_pstate_verified), + KUNIT_CASE(cft_test_set_pstate_unexpected), + KUNIT_CASE(cft_test_set_pstate_verified_busy), + KUNIT_CASE(cft_test_fast_switch), + KUNIT_CASE(cft_test_pstate_freq), + KUNIT_CASE(cft_test_lazy_idle), + KUNIT_CASE(cft_test_lazy_busy), + KUNIT_CASE(cft_test_lazy_pending_same), + KUNIT_CASE(cft_test_lazy_unexpected), + KUNIT_CASE(cft_test_lazy_verify_fails), + KUNIT_CASE(cft_test_lazy_range), + KUNIT_CASE(cft_test_lazy_fast_switch), + KUNIT_CASE(cft_test_lazy_cap), + KUNIT_CASE(cft_test_lazy_cap_waited), + KUNIT_CASE(cft_test_drain), + KUNIT_CASE(cft_test_set_target_lazy), + KUNIT_CASE(cft_test_suspend_lazy), + KUNIT_CASE(cft_test_resume), + KUNIT_CASE(cft_test_unmanaged_max), + KUNIT_CASE(cft_test_fast_die_fit), + KUNIT_CASE(cft_test_fast_die_limit), + KUNIT_CASE(cft_test_fast_die_interval), + KUNIT_CASE(cft_test_fast_die_arm), + KUNIT_CASE(cft_test_fast_die_cap), + KUNIT_CASE(cft_test_fast_die_cap_unverified), + KUNIT_CASE(cft_test_fast_die_init_none), + KUNIT_CASE(cft_test_fast_die_init_required), + KUNIT_CASE(cft_test_fast_die_init_described), + KUNIT_CASE(cft_test_fast_die_init_invalid), + {} +}; + +static struct kunit_suite apple_soc_cpufreq_test_suite = { + .name = "apple_soc_cpufreq", + .exit = cft_exit, + .test_cases = apple_soc_cpufreq_test_cases, +}; + +/* + * Tests on a policy of the cpufreq core + * + * ->get() finds its policy through the core, and the thermal ownership call + * takes the policy lock and checks which driver is registered. The suite + * registers a driver under this driver's name whose policies carry a cluster + * as above; its ->target_index() does nothing, so that the governor of the + * policy never touches the cluster the tests work on. + */ + +static u8 *cft_live_regs; +static struct apple_cpu_priv *cft_live_priv; +static struct cpufreq_frequency_table cft_live_table[CFT_NR_STATES + 1]; +static int cft_live_ret = -ENODEV; + +static int cft_live_init(struct cpufreq_policy *policy) +{ + policy->driver_data = cft_live_priv; + policy->freq_table = cft_live_table; + policy->cur = cft_live_table[0].frequency; + return 0; +} + +static void cft_live_exit(struct cpufreq_policy *policy) +{ + policy->driver_data = NULL; +} + +static int cft_live_target(struct cpufreq_policy *policy, unsigned int index) +{ + return 0; +} + +static struct cpufreq_driver cft_live_driver = { + .name = "apple-cpufreq", + .flags = CPUFREQ_HAVE_GOVERNOR_PER_POLICY, + .verify = cpufreq_generic_frequency_table_verify, + .init = cft_live_init, + .exit = cft_live_exit, + .target_index = cft_live_target, +}; + +static int cft_live_suite_init(struct kunit_suite *suite) +{ + cft_live_regs = kzalloc(CFT_REGS_SIZE, GFP_KERNEL); + cft_live_priv = kzalloc_obj(*cft_live_priv); + if (!cft_live_regs || !cft_live_priv) { + cft_live_ret = -ENOMEM; + return 0; + } + + memcpy(cft_live_table, cft_table, sizeof(cft_table)); + cft_live_priv->cpu_dev = get_cpu_device(cpumask_first(cpu_online_mask)); + cft_priv_init(cft_live_priv, cft_live_regs, &soc_default_info, 4); + + cft_live_ret = cpufreq_register_driver(&cft_live_driver); + return 0; +} + +static void cft_live_suite_exit(struct kunit_suite *suite) +{ + if (!cft_live_ret) + cpufreq_unregister_driver(&cft_live_driver); + cft_live_ret = -ENODEV; + kfree(cft_live_priv); + kfree(cft_live_regs); + cft_live_priv = NULL; + cft_live_regs = NULL; +} + +static int cft_live_test_init(struct kunit *test) +{ + if (cft_live_ret == -EEXIST) + kunit_skip(test, "a cpufreq driver is already registered"); + KUNIT_ASSERT_EQ(test, cft_live_ret, 0); + KUNIT_ASSERT_STREQ(test, cft_live_driver.name, apple_soc_cpufreq_driver.name); + return 0; +} + +static void cft_live_test_exit(struct kunit *test) +{ + if (cft_live_ret) + return; + cft_live_priv->info = &soc_default_info; + cft_set_cmd(cft_live_regs, 4); + cft_set_status(cft_live_regs, 0); +} + +struct cft_get { + const char *name; + const struct apple_soc_cpufreq_info *info; + u32 status; + u64 cmd; + unsigned int freq; +}; + +/* + * The current state sits in the status register at a place that moved from + * SoC to SoC; every other bit of the register is set, the target state next + * to it included. Without a known status layout the last request stands in. + */ +static const struct cft_get cft_gets[] = { + { "s5l8960x status bits 5:3", &soc_s5l8960x_info, + ~(u32)GENMASK(5, 3) | (4 << 3), ~0ULL, 1200000 }, + { "t8103 status bits 7:4", &soc_t8103_info, + ~(u32)GENMASK(7, 4) | (10 << 4), ~0ULL, 2400000 }, + { "t8112 status bits 9:5", &soc_t8112_info, + ~(u32)GENMASK(9, 5) | (15 << 5), ~0ULL, 3000000 }, + { "t8112 lowest state", &soc_t8112_info, + ~(u32)GENMASK(9, 5) | (1 << 5), ~0ULL, 600000 }, + { "generic command state", &soc_default_info, + ~0U, ~GENMASK_ULL(4, 0) | 7, 1800000 }, + { "t8132 command state", &soc_t8132_info, + 0, ~GENMASK_ULL(4, 0) | 10, 2400000 }, + { "t8140 command state", &soc_t8140_info, + ~0U, 15, 3000000 }, + /* States without a frequency-table entry have no frequency. */ + { "t8103 unknown state", &soc_t8103_info, + ~(u32)GENMASK(7, 4) | (5 << 4), 4, 0 }, + { "t8112 state beyond the table", &soc_t8112_info, ~0U, 4, 0 }, + { "t8112 state 0", &soc_t8112_info, 0, 4, 0 }, + { "generic state beyond the table", &soc_default_info, 4 << 4, ~0ULL, 0 }, +}; + +static void cft_get_desc(const struct cft_get *g, char *desc) +{ + strscpy(desc, g->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(cft_get, cft_gets, cft_get_desc); + +static void cft_test_get(struct kunit *test) +{ + const struct cft_get *g = test->param_value; + + cft_live_priv->info = g->info; + cft_set_status(cft_live_regs, g->status); + cft_set_cmd(cft_live_regs, g->cmd); + KUNIT_EXPECT_EQ(test, + apple_soc_cpufreq_get_rate(cpumask_first(cpu_online_mask)), + g->freq); +} + +/* The thermal driver takes the higher states and gives them back. */ +static void cft_test_thermal_owner(struct kunit *test) +{ + struct apple_cpu_priv *priv = cft_live_priv; + struct cpufreq_policy *policy; + int ret; + + policy = cpufreq_cpu_get(cpumask_first(cpu_online_mask)); + KUNIT_ASSERT_NOT_NULL(test, policy); + priv->info = &soc_t8132_info; + + /* A cluster that is not held back has nothing to hand over. */ + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), + -ENODEV); + KUNIT_EXPECT_FALSE(test, priv->thermal_owned); + + /* As apple_soc_cpufreq_init() holds it back. */ + mutex_lock(&apple_soc_thermal_owner_lock); + ret = freq_qos_add_request(&policy->constraints, &priv->unmanaged_cap, + FREQ_QOS_MAX, apple_soc_cpufreq_owner_cap(policy)); + mutex_unlock(&apple_soc_thermal_owner_lock); + KUNIT_EXPECT_GE(test, ret, 0); + if (ret < 0) + goto out; + KUNIT_EXPECT_EQ(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 1200000); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), 0); + KUNIT_EXPECT_TRUE(test, priv->thermal_owned); + KUNIT_EXPECT_GE(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 3000000); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, true), 0); + KUNIT_EXPECT_TRUE(test, priv->thermal_owned); + + KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_set_thermal_owner(policy, false), 0); + KUNIT_EXPECT_FALSE(test, priv->thermal_owned); + KUNIT_EXPECT_EQ(test, freq_qos_read_value(&policy->constraints, FREQ_QOS_MAX), + 1200000); + + freq_qos_remove_request(&priv->unmanaged_cap); +out: + priv->thermal_owned = false; + cpufreq_cpu_put(policy); +} + +static struct kunit_case apple_soc_cpufreq_policy_test_cases[] = { + KUNIT_CASE_PARAM(cft_test_get, cft_get_gen_params), + KUNIT_CASE(cft_test_thermal_owner), + {} +}; + +static struct kunit_suite apple_soc_cpufreq_policy_test_suite = { + .name = "apple_soc_cpufreq_policy", + .suite_init = cft_live_suite_init, + .suite_exit = cft_live_suite_exit, + .init = cft_live_test_init, + .exit = cft_live_test_exit, + .test_cases = apple_soc_cpufreq_policy_test_cases, +}; + +kunit_test_suites(&apple_soc_cpufreq_test_suite, + &apple_soc_cpufreq_policy_test_suite); diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 09233d4b4208d7..7f52a1a3ad97d9 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -1680,6 +1680,10 @@ static void __exit apple_soc_cpufreq_module_exit(void) } module_exit(apple_soc_cpufreq_module_exit); +#if IS_ENABLED(CONFIG_ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST) +#include "apple-soc-cpufreq-test.c" +#endif + MODULE_DEVICE_TABLE(of, apple_soc_cpufreq_of_match); MODULE_AUTHOR("Hector Martin "); MODULE_DESCRIPTION("Apple SoC CPU cluster DVFS driver"); diff --git a/drivers/cpufreq/apple-soc-cpufreq.kunitconfig b/drivers/cpufreq/apple-soc-cpufreq.kunitconfig new file mode 100644 index 00000000000000..68ca699bc91a4e --- /dev/null +++ b/drivers/cpufreq/apple-soc-cpufreq.kunitconfig @@ -0,0 +1,9 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/cpufreq/apple-soc-cpufreq.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_CPU_FREQ=y +CONFIG_ARM_APPLE_SOC_CPUFREQ=y +CONFIG_ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST=y From 2dff0d77853208273c11f831a0fe1bc74f3f1451 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:39:09 +1100 Subject: [PATCH 0538/1514] pwm: apple: add KUnit tests Add a suite for the Apple SoC PWM driver. The chip is registered on a KUnit device with a fixed clock rate and its registers in kernel memory, and the tests go through the PWM core: - period and duty cycle to ON/OFF cycle counts, with the rounding and the 32-bit saturation, for a range of clock rates and periods; - get_state() of what apply() wrote, its rounding up and its maximum; - disable, refusal of inverted polarity, of a duty cycle above the period and of a zero period; - the runtime PM reference a running output holds, and that runtime PM keeps the registers. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/pwm/Kconfig | 13 + drivers/pwm/pwm-apple-test.c | 526 ++++++++++++++++++++++++++++++ drivers/pwm/pwm-apple.c | 4 + drivers/pwm/pwm-apple.kunitconfig | 7 + 4 files changed, 550 insertions(+) create mode 100644 drivers/pwm/pwm-apple-test.c create mode 100644 drivers/pwm/pwm-apple.kunitconfig diff --git a/drivers/pwm/Kconfig b/drivers/pwm/Kconfig index 72977608687903..70fd31fbb06754 100644 --- a/drivers/pwm/Kconfig +++ b/drivers/pwm/Kconfig @@ -85,6 +85,19 @@ config PWM_APPLE To compile this driver as a module, choose M here: the module will be called pwm-apple. +config PWM_APPLE_KUNIT_TEST + bool "KUnit tests for the Apple SoC PWM" if !KUNIT_ALL_TESTS + depends on PWM_APPLE=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple SoC PWM driver: the conversion of a + period and duty cycle to ON and OFF cycle counts at the clock + rate with its rounding and 32-bit saturation, the state read back + from the registers, the refusal of inverted polarity and the + runtime PM reference held for a running output. The chip is + registered on a KUnit device with its registers in kernel + memory, so the tests need no Apple hardware. + config PWM_ARGON_FAN_HAT tristate "Argon40 Fan HAT support" depends on I2C && OF diff --git a/drivers/pwm/pwm-apple-test.c b/drivers/pwm/pwm-apple-test.c new file mode 100644 index 00000000000000..8c4af33ac51e2c --- /dev/null +++ b/drivers/pwm/pwm-apple-test.c @@ -0,0 +1,526 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * KUnit tests for the Apple SoC PWM driver: the period and duty cycle to + * ON/OFF cycle register conversion, its readback and the power reference + * held for a running output. + * + * The chip is a real pwm_chip registered on a KUnit device and driven + * through the PWM core by a consumer found through a lookup table. Its + * registers are plain kernel memory and the clock rate is set directly, so + * the tests need no Apple hardware. + * + * Included by pwm-apple.c. + */ + +#include +#include +#include + +#define APPLE_PWM_TEST_REGS 0x20 +#define APPLE_PWM_TEST_RATE 24000000ULL +#define APPLE_PWM_TEST_CTRL_ON (APPLE_PWM_CTRL_ENABLE | \ + APPLE_PWM_CTRL_OUTPUT_ENABLE | \ + APPLE_PWM_CTRL_UPDATE) + +struct apple_pwm_test { + struct device *dev; + struct pwm_chip *chip; + struct apple_pwm *fpwm; + struct pwm_device *pwm; + struct pwm_lookup lookup; +}; + +static void apple_pwm_test_put(void *data) +{ + pwm_put(data); +} + +static void apple_pwm_test_remove_table(void *data) +{ + pwm_remove_table(data, 1); +} + +static void apple_pwm_test_remove_chip(void *data) +{ + pwmchip_remove(data); +} + +static void apple_pwm_test_pm_disable(void *data) +{ + pm_runtime_disable(data); +} + +static int apple_pwm_test_init(struct kunit *test) +{ + struct apple_pwm_test *ctx; + struct device *consumer; + void *regs; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->dev = kunit_device_register(test, "apple-pwm-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + consumer = kunit_device_register(test, "apple-pwm-test-consumer"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, consumer); + + ctx->chip = devm_pwmchip_alloc(ctx->dev, 1, sizeof(*ctx->fpwm)); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->chip); + ctx->fpwm = to_apple_pwm(ctx->chip); + + regs = kunit_kzalloc(test, APPLE_PWM_TEST_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, regs); + ctx->fpwm->base = (void __iomem __force *)regs; + ctx->fpwm->clkrate = APPLE_PWM_TEST_RATE; + ctx->chip->ops = &apple_pwm_ops; + dev_set_drvdata(ctx->dev, ctx->chip); + + KUNIT_ASSERT_EQ(test, pm_runtime_set_active(ctx->dev), 0); + pm_runtime_enable(ctx->dev); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_pm_disable, + ctx->dev), 0); + + KUNIT_ASSERT_EQ(test, pwmchip_add(ctx->chip), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_remove_chip, + ctx->chip), 0); + + ctx->lookup.provider = dev_name(ctx->dev); + ctx->lookup.dev_id = dev_name(consumer); + ctx->lookup.con_id = "test"; + ctx->lookup.polarity = PWM_POLARITY_NORMAL; + pwm_add_table(&ctx->lookup, 1); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_remove_table, + &ctx->lookup), 0); + + ctx->pwm = pwm_get(consumer, "test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->pwm); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, apple_pwm_test_put, + ctx->pwm), 0); + + return 0; +} + +static u32 apple_pwm_test_reg(struct apple_pwm_test *ctx, unsigned int reg) +{ + return readl(ctx->fpwm->base + reg); +} + +static void apple_pwm_test_set_regs(struct apple_pwm_test *ctx, u32 ctrl, + u32 on_cycles, u32 off_cycles) +{ + writel(ctrl, ctx->fpwm->base + APPLE_PWM_CTRL); + writel(on_cycles, ctx->fpwm->base + APPLE_PWM_ON_CYCLES); + writel(off_cycles, ctx->fpwm->base + APPLE_PWM_OFF_CYCLES); +} + +static int apple_pwm_test_apply(struct apple_pwm_test *ctx, u64 period, + u64 duty_cycle, bool enabled) +{ + struct pwm_state state = { + .period = period, + .duty_cycle = duty_cycle, + .polarity = PWM_POLARITY_NORMAL, + .enabled = enabled, + }; + + return pwm_apply_might_sleep(ctx->pwm, &state); +} + +static int apple_pwm_test_usage(struct apple_pwm_test *ctx) +{ + return atomic_read(&ctx->dev->power.usage_count); +} + +struct apple_pwm_test_conv { + const char *name; + u64 clkrate; + u64 period; + u64 duty_cycle; + u32 on_cycles; + u32 off_cycles; +}; + +static const struct apple_pwm_test_conv apple_pwm_test_convs[] = { + { + .name = "24 MHz, 1 ms period, 25 % duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 250000, + .on_cycles = 6000, .off_cycles = 18000, + }, { + /* 2.4 cycles of duty round down to 2, the period is exact */ + .name = "24 MHz, duty rounds down", + .clkrate = 24000000, .period = 1000, .duty_cycle = 100, + .on_cycles = 2, .off_cycles = 22, + }, { + /* 1999 ns are 47.976 cycles */ + .name = "24 MHz, period rounds down", + .clkrate = 24000000, .period = 1999, .duty_cycle = 1000, + .on_cycles = 24, .off_cycles = 23, + }, { + /* 41 ns are less than one cycle of 41.67 ns */ + .name = "24 MHz, period below one cycle", + .clkrate = 24000000, .period = 41, .duty_cycle = 41, + .on_cycles = 0, .off_cycles = 0, + }, { + .name = "24 MHz, no duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 0, + .on_cycles = 0, .off_cycles = 24000, + }, { + .name = "24 MHz, full duty", + .clkrate = 24000000, .period = 1000000, .duty_cycle = 1000000, + .on_cycles = 24000, .off_cycles = 0, + }, { + /* 100 s and 150 s fit 32 bits each, their sum does not */ + .name = "24 MHz, period above 32 bits of cycles", + .clkrate = 24000000, .period = 250ULL * NSEC_PER_SEC, + .duty_cycle = 100ULL * NSEC_PER_SEC, + .on_cycles = 2400000000U, .off_cycles = 3600000000U, + }, { + /* 200 s of duty are 4.8e9 cycles: ON saturates, OFF keeps the rest */ + .name = "24 MHz, duty saturates, period kept", + .clkrate = 24000000, .period = 300ULL * NSEC_PER_SEC, + .duty_cycle = 200ULL * NSEC_PER_SEC, + .on_cycles = U32_MAX, .off_cycles = 2905032705U, + }, { + .name = "24 MHz, duty and period saturate", + .clkrate = 24000000, .period = 500ULL * NSEC_PER_SEC, + .duty_cycle = 400ULL * NSEC_PER_SEC, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* the period times the rate does not fit 64 bits */ + .name = "24 MHz, longest period", + .clkrate = 24000000, .period = U64_MAX, .duty_cycle = 1000000, + .on_cycles = 24000, .off_cycles = U32_MAX, + }, { + .name = "24 MHz, longest period and duty", + .clkrate = 24000000, .period = U64_MAX, .duty_cycle = U64_MAX, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* the fastest clock the probe accepts: one cycle per ns */ + .name = "1 GHz, one cycle per ns", + .clkrate = NSEC_PER_SEC, .period = 4000000000ULL, + .duty_cycle = 123456789, + .on_cycles = 123456789, .off_cycles = 3876543211U, + }, { + .name = "1 GHz, longest period and duty", + .clkrate = NSEC_PER_SEC, .period = U64_MAX, .duty_cycle = U64_MAX, + .on_cycles = U32_MAX, .off_cycles = U32_MAX, + }, { + /* 1 s is 32768 cycles, 100 us are 3.28 */ + .name = "32768 Hz", + .clkrate = 32768, .period = NSEC_PER_SEC, .duty_cycle = 100000, + .on_cycles = 3, .off_cycles = 32765, + }, +}; + +static void apple_pwm_test_conv_desc(const struct apple_pwm_test_conv *c, char *desc) +{ + strscpy(desc, c->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(apple_pwm_test_conv, apple_pwm_test_convs, apple_pwm_test_conv_desc); + +/* An enabled state is converted to ON and OFF cycles and latched. */ +static void apple_pwm_test_apply_cycles(struct kunit *test) +{ + const struct apple_pwm_test_conv *c = test->param_value; + struct apple_pwm_test *ctx = test->priv; + + ctx->fpwm->clkrate = c->clkrate; + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, c->period, c->duty_cycle, true), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), c->on_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), c->off_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); +} + +/* + * What the hardware reads back is never longer than what was asked for, is + * less than one clock cycle shorter unless a register saturated, and + * programs the same registers when it is applied again. + */ +static void apple_pwm_test_readback(struct kunit *test) +{ + const struct apple_pwm_test_conv *c = test->param_value; + struct apple_pwm_test *ctx = test->priv; + u64 cycle_ns = DIV64_U64_ROUND_UP(NSEC_PER_SEC, c->clkrate); + struct pwm_state hw; + + ctx->fpwm->clkrate = c->clkrate; + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, c->period, c->duty_cycle, true), 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + + KUNIT_EXPECT_TRUE(test, hw.enabled); + KUNIT_EXPECT_EQ(test, hw.polarity, PWM_POLARITY_NORMAL); + KUNIT_EXPECT_LE(test, hw.duty_cycle, hw.period); + KUNIT_EXPECT_LE(test, hw.duty_cycle, c->duty_cycle); + KUNIT_EXPECT_LE(test, hw.period, c->period); + if (c->on_cycles != U32_MAX) + KUNIT_EXPECT_LT(test, c->duty_cycle - hw.duty_cycle, cycle_ns); + if (c->on_cycles != U32_MAX && c->off_cycles != U32_MAX) + KUNIT_EXPECT_LT(test, c->period - hw.period, cycle_ns); + + /* Scribble over the registers so that the second apply shows. */ + apple_pwm_test_set_regs(ctx, 0, ~c->on_cycles, ~c->off_cycles); + KUNIT_ASSERT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), c->on_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), c->off_cycles); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); +} + +/* Readback rounds up to the next nanosecond, duty and period separately. */ +static void apple_pwm_test_get_state_rounds_up(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + /* 1 cycle is 41.67 ns, 2 are 83.33 ns, 3 are exactly 125 ns */ + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 1, 1); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 42); + KUNIT_EXPECT_EQ(test, hw.period, 84); + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 3, 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 125); + KUNIT_EXPECT_EQ(test, hw.period, 125); +} + +/* Both registers at their maximum: the 33-bit sum must not be truncated. */ +static void apple_pwm_test_get_state_max(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, U32_MAX, U32_MAX); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_TRUE(test, hw.enabled); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 178956970625ULL); + KUNIT_EXPECT_EQ(test, hw.period, 357913941250ULL); + + /* The slowest clock: 2^33 - 2 cycles of one second each. */ + ctx->fpwm->clkrate = 1; + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, (u64)U32_MAX * NSEC_PER_SEC); + KUNIT_EXPECT_EQ(test, hw.period, 2ULL * U32_MAX * NSEC_PER_SEC); +} + +/* The output only runs with both the enable and the output enable bit. */ +static void apple_pwm_test_get_state_enabled(struct kunit *test) +{ + static const struct { + u32 ctrl; + bool enabled; + } cases[] = { + { 0, false }, + { APPLE_PWM_CTRL_ENABLE, false }, + { APPLE_PWM_CTRL_OUTPUT_ENABLE, false }, + { APPLE_PWM_CTRL_UPDATE, false }, + { APPLE_PWM_CTRL_ENABLE | APPLE_PWM_CTRL_OUTPUT_ENABLE, true }, + { APPLE_PWM_TEST_CTRL_ON, true }, + { ~(u32)APPLE_PWM_CTRL_ENABLE, false }, + { ~(u32)APPLE_PWM_CTRL_OUTPUT_ENABLE, false }, + }; + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + apple_pwm_test_set_regs(ctx, cases[i].ctrl, 6000, 18000); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ_MSG(test, hw.enabled, cases[i].enabled, + "ctrl %#x", cases[i].ctrl); + KUNIT_EXPECT_EQ(test, hw.polarity, PWM_POLARITY_NORMAL); + KUNIT_EXPECT_EQ(test, hw.duty_cycle, 250000); + KUNIT_EXPECT_EQ(test, hw.period, 1000000); + } +} + +/* Disabling clears the control register and leaves the cycle registers. */ +static void apple_pwm_test_disable(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state hw; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 1000000, false), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 6000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 18000); + + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_FALSE(test, hw.enabled); +} + +/* A disabled state never has its period or duty cycle looked at. */ +static void apple_pwm_test_disable_ignores_timing(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_TEST_CTRL_ON, 11, 22); + /* duty above period, which is only valid while disabled */ + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 5, U64_MAX, false), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 11); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 22); +} + +static void apple_pwm_test_expect_untouched(struct kunit *test, int usage) +{ + struct apple_pwm_test *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_TEST_CTRL_ON); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 6000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 18000); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + KUNIT_EXPECT_TRUE(test, ctx->fpwm->enabled); +} + +/* The hardware cannot invert: refused before anything is written. */ +static void apple_pwm_test_inversed_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state state = { + .period = 2000000, + .duty_cycle = 500000, + .polarity = PWM_POLARITY_INVERSED, + .enabled = true, + }; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, pwm_apply_might_sleep(ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); + + /* Also when it is asked for together with a disable. */ + state.enabled = false; + KUNIT_EXPECT_EQ(test, pwm_apply_might_sleep(ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); + + /* And when the driver is called without the core in front. */ + KUNIT_EXPECT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &state), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* A duty cycle above the period never reaches the registers. */ +static void apple_pwm_test_duty_above_period_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 1000001, true), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* Nor does an enabled state without a period. */ +static void apple_pwm_test_zero_period_refused(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage; + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + usage = apple_pwm_test_usage(ctx); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_apply(ctx, 0, 0, true), -EINVAL); + apple_pwm_test_expect_untouched(test, usage); +} + +/* + * A running output holds exactly one runtime PM reference, however often it + * is reprogrammed, and gives it back when it is disabled. + */ +static void apple_pwm_test_enable_holds_power(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + struct pwm_state off = { .polarity = PWM_POLARITY_NORMAL }; + int usage = apple_pwm_test_usage(ctx); + + if (!IS_ENABLED(CONFIG_PM)) + kunit_skip(test, "needs CONFIG_PM"); + + KUNIT_EXPECT_FALSE(test, ctx->fpwm->enabled); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + KUNIT_EXPECT_TRUE(test, ctx->fpwm->enabled); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 500000, true), 0); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 500000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 2000000, 500000, false), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + KUNIT_EXPECT_FALSE(test, ctx->fpwm->enabled); + + /* A second disable, which the core would filter, gives nothing back. */ + KUNIT_ASSERT_EQ(test, apple_pwm_apply(ctx->chip, ctx->pwm, &off), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); + + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, true), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage + 1); + KUNIT_ASSERT_EQ(test, apple_pwm_test_apply(ctx, 1000000, 250000, false), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); +} + +/* Reading the state back takes no lasting power reference. */ +static void apple_pwm_test_get_state_power_balanced(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + int usage = apple_pwm_test_usage(ctx); + struct pwm_state hw; + + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_ASSERT_EQ(test, pwm_get_state_hw(ctx->pwm, &hw), 0); + KUNIT_EXPECT_EQ(test, apple_pwm_test_usage(ctx), usage); +} + +/* + * The power domain may drop the registers of a stopped PWM: runtime suspend + * saves all three and runtime resume writes them back. + */ +static void apple_pwm_test_runtime_pm_keeps_registers(struct kunit *test) +{ + struct apple_pwm_test *ctx = test->priv; + + apple_pwm_test_set_regs(ctx, APPLE_PWM_CTRL_MODE, 0x12345678, 0x9abcdef0); + KUNIT_ASSERT_EQ(test, apple_pwm_runtime_suspend(ctx->dev), 0); + + apple_pwm_test_set_regs(ctx, 0, 0, 0); + KUNIT_ASSERT_EQ(test, apple_pwm_runtime_resume(ctx->dev), 0); + + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_CTRL), APPLE_PWM_CTRL_MODE); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_ON_CYCLES), 0x12345678); + KUNIT_EXPECT_EQ(test, apple_pwm_test_reg(ctx, APPLE_PWM_OFF_CYCLES), 0x9abcdef0); +} + +static struct kunit_case apple_pwm_test_cases[] = { + KUNIT_CASE_PARAM(apple_pwm_test_apply_cycles, apple_pwm_test_conv_gen_params), + KUNIT_CASE_PARAM(apple_pwm_test_readback, apple_pwm_test_conv_gen_params), + KUNIT_CASE(apple_pwm_test_get_state_rounds_up), + KUNIT_CASE(apple_pwm_test_get_state_max), + KUNIT_CASE(apple_pwm_test_get_state_enabled), + KUNIT_CASE(apple_pwm_test_disable), + KUNIT_CASE(apple_pwm_test_disable_ignores_timing), + KUNIT_CASE(apple_pwm_test_inversed_refused), + KUNIT_CASE(apple_pwm_test_duty_above_period_refused), + KUNIT_CASE(apple_pwm_test_zero_period_refused), + KUNIT_CASE(apple_pwm_test_enable_holds_power), + KUNIT_CASE(apple_pwm_test_get_state_power_balanced), + KUNIT_CASE(apple_pwm_test_runtime_pm_keeps_registers), + {} +}; + +static struct kunit_suite apple_pwm_test_suite = { + .name = "pwm-apple", + .init = apple_pwm_test_init, + .test_cases = apple_pwm_test_cases, +}; + +kunit_test_suite(apple_pwm_test_suite); diff --git a/drivers/pwm/pwm-apple.c b/drivers/pwm/pwm-apple.c index 2659f777fafbe8..b42e24e498ce1d 100644 --- a/drivers/pwm/pwm-apple.c +++ b/drivers/pwm/pwm-apple.c @@ -252,3 +252,7 @@ module_platform_driver(apple_pwm_driver); MODULE_DESCRIPTION("Apple SoC PWM driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_PWM_APPLE_KUNIT_TEST) +#include "pwm-apple-test.c" +#endif diff --git a/drivers/pwm/pwm-apple.kunitconfig b/drivers/pwm/pwm-apple.kunitconfig new file mode 100644 index 00000000000000..bdeebf43bf5333 --- /dev/null +++ b/drivers/pwm/pwm-apple.kunitconfig @@ -0,0 +1,7 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/pwm/pwm-apple.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_PM=y +CONFIG_PWM=y +CONFIG_PWM_APPLE=y +CONFIG_PWM_APPLE_KUNIT_TEST=y From 205689fbf411263189852d582b6070ff9a160f93 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:40:20 +1100 Subject: [PATCH 0539/1514] Input: apple_z2 - keep device reports inside the receive buffer The touch controller decides how much the driver reads and parses: - apple_z2_read_packet() takes the packet length from the device's header (up to 64 KiB) and reads that many bytes into the 4000-byte receive buffer; - apple_z2_parse_touches() takes the finger count from the report and walks that many finger records, whether the report holds them or not; - apple_z2_upload_firmware() reads the magic and version of a firmware file before it knows the file is that long. Drop a packet longer than the receive buffer, walk only the finger records the report has room for, and refuse a firmware file shorter than its header. Fixes: 471a92f8a21a ("Input: apple_z2 - add a driver for Apple Z2 touchscreens") Signed-off-by: Ryan Murray --- drivers/input/touchscreen/apple_z2.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/drivers/input/touchscreen/apple_z2.c b/drivers/input/touchscreen/apple_z2.c index 271ababf0ad559..b0487b24b9a9f0 100644 --- a/drivers/input/touchscreen/apple_z2.c +++ b/drivers/input/touchscreen/apple_z2.c @@ -28,6 +28,7 @@ #define LOAD_COMMAND_SEND_BLOB 1 #define LOAD_COMMAND_SEND_CALIBRATION 2 #define CAL_PROP_NAME "apple,z2-cal-blob" +#define APPLE_Z2_RX_BUF_SIZE 4000 struct apple_z2 { struct spi_device *spidev; @@ -86,11 +87,16 @@ static void apple_z2_parse_touches(struct apple_z2 *z2, int nfingers; int slot; int slot_valid; + size_t max_fingers = 0; struct apple_z2_finger *fingers; if (msg_len <= APPLE_Z2_NUM_FINGERS_OFFSET) return; - nfingers = msg[APPLE_Z2_NUM_FINGERS_OFFSET]; + /* Only trust the finger records that the report has room for */ + if (msg_len > APPLE_Z2_FINGERS_OFFSET) + max_fingers = (msg_len - APPLE_Z2_FINGERS_OFFSET) / + sizeof(*fingers); + nfingers = min_t(size_t, msg[APPLE_Z2_NUM_FINGERS_OFFSET], max_fingers); fingers = (struct apple_z2_finger *)(msg + APPLE_Z2_FINGERS_OFFSET); for (i = 0; i < nfingers; i++) { slot = input_mt_get_slot_by_key(z2->input_dev, fingers[i].finger); @@ -147,6 +153,12 @@ static int apple_z2_read_packet(struct apple_z2 *z2) return 0; pkt_len = (get_unaligned_le16(z2->rx_buf + 1) + 8) & 0xfffffffc; + if (pkt_len > APPLE_Z2_RX_BUF_SIZE) { + dev_warn_ratelimited(&z2->spidev->dev, + "dropping oversized packet (%zu bytes)\n", + pkt_len); + return -EMSGSIZE; + } error = spi_read(z2->spidev, z2->rx_buf, pkt_len); if (error) @@ -271,7 +283,8 @@ static int apple_z2_upload_firmware(struct apple_z2 *z2) } fw_hdr = (const struct apple_z2_fw_hdr *)fw->data; - if (le32_to_cpu(fw_hdr->magic) != APPLE_Z2_FW_MAGIC || le32_to_cpu(fw_hdr->version) != 1) { + if (fw->size < sizeof(*fw_hdr) || + le32_to_cpu(fw_hdr->magic) != APPLE_Z2_FW_MAGIC || le32_to_cpu(fw_hdr->version) != 1) { dev_err(&z2->spidev->dev, "invalid firmware header\n"); return -EINVAL; } @@ -363,7 +376,7 @@ static int apple_z2_probe(struct spi_device *spi) if (!z2->tx_buf) return -ENOMEM; /* 4096 will end up being rounded up to 8192 due to devres header */ - z2->rx_buf = devm_kzalloc(dev, 4000, GFP_KERNEL); + z2->rx_buf = devm_kzalloc(dev, APPLE_Z2_RX_BUF_SIZE, GFP_KERNEL); if (!z2->rx_buf) return -ENOMEM; From 15ee00acfcae2bba8fcd7003efb3dcc4df893f32 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:40:30 +1100 Subject: [PATCH 0540/1514] Input: apple_z2 - parse the firmware apart from requesting it Move the parsing and upload of a firmware image out of apple_z2_upload_firmware() into apple_z2_load_firmware(), which takes the struct firmware. The upload itself is unchanged; this lets a test hand the parser synthetic images without a file system. No functional change. Signed-off-by: Ryan Murray --- drivers/input/touchscreen/apple_z2.c | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/drivers/input/touchscreen/apple_z2.c b/drivers/input/touchscreen/apple_z2.c index b0487b24b9a9f0..235e4fd69f6f9c 100644 --- a/drivers/input/touchscreen/apple_z2.c +++ b/drivers/input/touchscreen/apple_z2.c @@ -265,7 +265,8 @@ static int apple_z2_send_firmware_blob(struct apple_z2 *z2, const u8 *data, return 0; } -static int apple_z2_upload_firmware(struct apple_z2 *z2) +static int apple_z2_load_firmware(struct apple_z2 *z2, + const struct firmware *fw) { const struct apple_z2_fw_hdr *fw_hdr; size_t fw_idx = sizeof(struct apple_z2_fw_hdr); @@ -275,13 +276,6 @@ static int apple_z2_upload_firmware(struct apple_z2 *z2) bool init; size_t size; - const struct firmware *fw __free(firmware) = NULL; - error = request_firmware(&fw, z2->fw_name, &z2->spidev->dev); - if (error) { - dev_err(&z2->spidev->dev, "unable to load firmware\n"); - return error; - } - fw_hdr = (const struct apple_z2_fw_hdr *)fw->data; if (fw->size < sizeof(*fw_hdr) || le32_to_cpu(fw_hdr->magic) != APPLE_Z2_FW_MAGIC || le32_to_cpu(fw_hdr->version) != 1) { @@ -342,6 +336,20 @@ static int apple_z2_upload_firmware(struct apple_z2 *z2) return 0; } +static int apple_z2_upload_firmware(struct apple_z2 *z2) +{ + int error; + + const struct firmware *fw __free(firmware) = NULL; + error = request_firmware(&fw, z2->fw_name, &z2->spidev->dev); + if (error) { + dev_err(&z2->spidev->dev, "unable to load firmware\n"); + return error; + } + + return apple_z2_load_firmware(z2, fw); +} + static int apple_z2_boot(struct apple_z2 *z2) { int error; From 95a49b95c4496e8d5553e9d8efc7fce66dc1efe8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:40:31 +1100 Subject: [PATCH 0541/1514] Input: apple_z2 - add KUnit tests Add a suite for the Z2 touchscreen driver. A fake SPI controller on a KUnit device plays the touch controller (interrupt data command, packet reads, firmware blob acknowledges) and the touch reports end up in a real input device whose events a test input handler captures: - the report layout, start/move/release, several fingers, the other finger states, axis inversion and swapping; - reports shorter than their header, with no fingers, with a finger count beyond the records present (up to 255), or a partial record; - the read command framing, the length rounding, SPI errors, the largest packet the buffer holds and one that is longer; - the boot interrupt and the first data interrupt; - firmware upload of a good image (blob, init payload and calibration blob built from the devicetree), clean ends, and the rejection of bad magic or version, truncated commands, blobs or calibration addresses, unknown commands, huge blob sizes and an image shorter than its header, a missing file and an SPI error mid-upload. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/input/touchscreen/Kconfig | 14 + drivers/input/touchscreen/apple_z2-test.c | 1272 +++++++++++++++++ drivers/input/touchscreen/apple_z2.c | 4 + .../input/touchscreen/apple_z2.kunitconfig | 9 + 4 files changed, 1299 insertions(+) create mode 100644 drivers/input/touchscreen/apple_z2-test.c create mode 100644 drivers/input/touchscreen/apple_z2.kunitconfig diff --git a/drivers/input/touchscreen/Kconfig b/drivers/input/touchscreen/Kconfig index 9b9ae8ac3f7fd3..b11e8c16c9aa99 100644 --- a/drivers/input/touchscreen/Kconfig +++ b/drivers/input/touchscreen/Kconfig @@ -115,6 +115,20 @@ config TOUCHSCREEN_APPLE_Z2 To compile this driver as a module, choose M here: the module will be called apple_z2. +config TOUCHSCREEN_APPLE_Z2_KUNIT_TEST + bool "KUnit tests for the Apple Z2 touchscreen driver" if !KUNIT_ALL_TESTS + depends on TOUCHSCREEN_APPLE_Z2=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple Z2 touchscreen driver: the parsing of + touch reports into multitouch input events, including reports that + are shorter than their finger count claims, the framing of interrupt + data packets, and the firmware and calibration upload. A fake SPI + controller stands in for the touch controller and the firmware + images are synthetic, so the tests need no Apple hardware. + + If unsure, say N. + config TOUCHSCREEN_AR1021_I2C tristate "Microchip AR1020/1021 i2c touchscreen" depends on I2C && OF diff --git a/drivers/input/touchscreen/apple_z2-test.c b/drivers/input/touchscreen/apple_z2-test.c new file mode 100644 index 00000000000000..2d2d3ca0609a8a --- /dev/null +++ b/drivers/input/touchscreen/apple_z2-test.c @@ -0,0 +1,1272 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the Apple Z2 touchscreen driver + * + * This file is included at the end of apple_z2.c so that it can call the + * driver's static functions. The device is replaced by a fake SPI controller + * registered on a KUnit device: its transfer_one() plays the touch controller + * (interrupt data command, packet read, firmware blobs). Touch reports end up + * in a real registered input device and an input handler captures the events. + * Firmware images are synthetic and handed to the upload as struct firmware, + * so no file system is needed. + */ + +#include +#include +#include +#include + +/* Size of the receive buffer that apple_z2_probe() allocates */ +#define Z2_TEST_RX_SIZE 4000 +/* + * The test's receive buffer is much larger than the driver's, so that a read + * with a hostile length stays inside the allocation and can be checked. + */ +#define Z2_TEST_RX_ALLOC (SZ_64K + SZ_4K) +#define Z2_TEST_MSG_ALLOC SZ_8K +/* Bytes in front of the touch report in an interrupt data packet */ +#define Z2_TEST_PKT_HDR 5 +#define Z2_TEST_FINGER_LEN 30 +#define Z2_TEST_MAX_EVENTS 4096 +#define Z2_TEST_MAX_XFERS 32 +#define Z2_TEST_TX_LOG 64 +#define Z2_TEST_STATE_LIFTED 7 + +struct z2_test_event { + u16 type; + u16 code; + s32 value; +}; + +struct z2_test_xfer { + unsigned int len; + u8 bpw; + bool has_tx; + bool has_rx; + u8 tx[Z2_TEST_TX_LOG]; +}; + +struct z2_test_cfg { + u32 size_x; + u32 size_y; + bool invert_x; + bool invert_y; + bool swap_x_y; + const u8 *cal; + size_t cal_len; +}; + +struct z2_test_finger { + u8 key; + u8 state; + u16 x; + u16 y; + u16 tool_major; + u16 tool_minor; + u16 orientation; + u16 touch_major; + u16 touch_minor; +}; + +struct z2_test_ctx { + struct apple_z2 z2; + struct input_handler handler; + struct input_handle handle; + struct software_node swnode; + struct property_entry props[8]; + + /* Touch report under construction */ + u8 *msg; + + /* Captured input events */ + struct z2_test_event *events; + unsigned int nevents; + + /* Fake device: log of the transfers it has seen */ + struct z2_test_xfer xfers[Z2_TEST_MAX_XFERS]; + unsigned int nxfers; + size_t max_rx_len; + /* Fail the transfer with this index, -1 for none */ + int fail_xfer; + /* Fake device: pending interrupt data packet */ + bool pkt_ready; + u16 pkt_wire_len; + u8 *pkt; + size_t pkt_len; +}; + +static const struct z2_test_cfg z2_test_cfg_plain = { + .size_x = 2000, + .size_y = 600, +}; + +/* The fake touch controller */ +static int z2_test_transfer_one(struct spi_controller *ctlr, + struct spi_device *spi, + struct spi_transfer *xfer) +{ + struct z2_test_ctx *ctx = spi_controller_get_devdata(ctlr); + unsigned int idx = ctx->nxfers++; + const u8 *tx = xfer->tx_buf; + u8 *rx = xfer->rx_buf; + + if (idx < Z2_TEST_MAX_XFERS) { + struct z2_test_xfer *rec = &ctx->xfers[idx]; + + rec->len = xfer->len; + rec->bpw = xfer->bits_per_word; + rec->has_tx = tx; + rec->has_rx = rx; + if (tx) + memcpy(rec->tx, tx, min(xfer->len, Z2_TEST_TX_LOG)); + } + + if (ctx->fail_xfer >= 0 && idx == ctx->fail_xfer) + return -EIO; + + if (tx && rx) { + /* Interrupt data command: answer with the pending length */ + memset(rx, 0, xfer->len); + if (tx[0] == APPLE_Z2_CMD_READ_INTERRUPT_DATA && + ctx->pkt_ready && xfer->len >= 3) { + rx[0] = APPLE_Z2_REPLY_INTERRUPT_DATA; + put_unaligned_le16(ctx->pkt_wire_len, rx + 1); + } + } else if (rx) { + /* Packet read: only the packet's own bytes are written */ + ctx->max_rx_len = max(ctx->max_rx_len, xfer->len); + memcpy(rx, ctx->pkt, + min3((size_t)xfer->len, ctx->pkt_len, + (size_t)Z2_TEST_RX_ALLOC)); + ctx->pkt_ready = false; + } else if (tx && xfer->len == 2) { + /* Firmware blob acknowledge: the device raises its interrupt */ + complete(&ctx->z2.boot_irq); + } + + return 0; +} + +static void z2_test_event(struct input_handle *handle, unsigned int type, + unsigned int code, int value) +{ + struct z2_test_ctx *ctx = handle->handler->private; + + if (ctx->nevents < Z2_TEST_MAX_EVENTS) { + ctx->events[ctx->nevents].type = type; + ctx->events[ctx->nevents].code = code; + ctx->events[ctx->nevents].value = value; + } + ctx->nevents++; +} + +static int z2_test_connect(struct input_handler *handler, + struct input_dev *dev, + const struct input_device_id *id) +{ + struct z2_test_ctx *ctx = handler->private; + int error; + + if (dev != ctx->z2.input_dev) + return -ENODEV; + + ctx->handle.dev = dev; + ctx->handle.handler = handler; + ctx->handle.name = "apple-z2-kunit"; + + error = input_register_handle(&ctx->handle); + if (error) + return error; + + error = input_open_device(&ctx->handle); + if (error) + input_unregister_handle(&ctx->handle); + + return error; +} + +static void z2_test_disconnect(struct input_handle *handle) +{ + input_close_device(handle); + input_unregister_handle(handle); +} + +static const struct input_device_id z2_test_ids[] = { + { + /* connect() picks the test's own device */ + .flags = INPUT_DEVICE_ID_MATCH_BUS, + .bustype = BUS_SPI, + }, + { } +}; + +KUNIT_DEFINE_ACTION_WRAPPER(z2_test_unregister_input, input_unregister_device, + struct input_dev *); +KUNIT_DEFINE_ACTION_WRAPPER(z2_test_unregister_handler, + input_unregister_handler, struct input_handler *); + +/* + * Build what apple_z2_probe() builds, minus the hardware: an SPI device on a + * fake controller, the driver state and the registered input device. + */ +static struct z2_test_ctx *z2_test_setup(struct kunit *test, + const struct z2_test_cfg *cfg) +{ + struct spi_board_info info = { .modalias = "apple-z2-kunit" }; + struct z2_test_ctx *ctx; + struct spi_controller *ctlr; + struct spi_device *spi; + struct input_dev *input; + struct device *parent; + unsigned int nprops = 0; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->fail_xfer = -1; + ctx->events = kunit_kcalloc(test, Z2_TEST_MAX_EVENTS, + sizeof(*ctx->events), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->events); + ctx->msg = kunit_kzalloc(test, Z2_TEST_MSG_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->msg); + ctx->pkt = kunit_kzalloc(test, Z2_TEST_RX_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->pkt); + ctx->z2.tx_buf = kunit_kzalloc(test, + sizeof(struct apple_z2_read_interrupt_cmd), + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->z2.tx_buf); + ctx->z2.rx_buf = kunit_kzalloc(test, Z2_TEST_RX_ALLOC, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->z2.rx_buf); + init_completion(&ctx->z2.boot_irq); + + ctx->props[nprops++] = PROPERTY_ENTRY_U32("touchscreen-size-x", + cfg->size_x); + ctx->props[nprops++] = PROPERTY_ENTRY_U32("touchscreen-size-y", + cfg->size_y); + if (cfg->invert_x) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-inverted-x"); + if (cfg->invert_y) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-inverted-y"); + if (cfg->swap_x_y) + ctx->props[nprops++] = + PROPERTY_ENTRY_BOOL("touchscreen-swapped-x-y"); + if (cfg->cal) + ctx->props[nprops++] = + PROPERTY_ENTRY_U8_ARRAY_LEN(CAL_PROP_NAME, cfg->cal, + cfg->cal_len); + ctx->swnode.properties = ctx->props; + + parent = kunit_device_register(test, "apple-z2-kunit"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, parent); + + ctlr = devm_spi_alloc_host(parent, 0); + KUNIT_ASSERT_NOT_NULL(test, ctlr); + spi_controller_set_devdata(ctlr, ctx); + ctlr->num_chipselect = 1; + ctlr->transfer_one = z2_test_transfer_one; + KUNIT_ASSERT_EQ(test, devm_spi_register_controller(parent, ctlr), 0); + + info.max_speed_hz = 1000000; + info.swnode = &ctx->swnode; + spi = spi_new_device(ctlr, &info); + KUNIT_ASSERT_NOT_NULL(test, spi); + ctx->z2.spidev = spi; + + input = input_allocate_device(); + KUNIT_ASSERT_NOT_NULL(test, input); + ctx->z2.input_dev = input; + input->name = "Apple Z2 KUnit"; + input->phys = "apple_z2"; + input->id.bustype = BUS_SPI; + input->dev.parent = &spi->dev; + + input_set_abs_params(input, ABS_MT_POSITION_X, 0, 0, 0, 0); + input_set_abs_params(input, ABS_MT_POSITION_Y, 0, 0, 0, 0); + touchscreen_parse_properties(input, true, &ctx->z2.props); + input_set_abs_params(input, ABS_MT_WIDTH_MAJOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_WIDTH_MINOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 65535, 0, 0); + input_set_abs_params(input, ABS_MT_ORIENTATION, -32768, 32767, 0, 0); + if (input_mt_init_slots(input, 256, INPUT_MT_DIRECT) || + input_register_device(input)) { + input_free_device(input); + KUNIT_FAIL_AND_ABORT(test, "unable to set up the input device"); + } + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, + z2_test_unregister_input, + input), 0); + + ctx->handler.private = ctx; + ctx->handler.event = z2_test_event; + ctx->handler.connect = z2_test_connect; + ctx->handler.disconnect = z2_test_disconnect; + ctx->handler.name = "apple-z2-kunit"; + ctx->handler.id_table = z2_test_ids; + KUNIT_ASSERT_EQ(test, input_register_handler(&ctx->handler), 0); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, + z2_test_unregister_handler, + &ctx->handler), 0); + KUNIT_ASSERT_PTR_EQ(test, ctx->handle.dev, input); + + return ctx; +} + +static void z2_test_clear_log(struct z2_test_ctx *ctx) +{ + ctx->nevents = 0; + ctx->nxfers = 0; + ctx->max_rx_len = 0; +} + +static unsigned int z2_test_count_events(struct z2_test_ctx *ctx, u16 type, + u16 code) +{ + unsigned int i, n = 0; + + for (i = 0; i < min(ctx->nevents, Z2_TEST_MAX_EVENTS); i++) + if (ctx->events[i].type == type && ctx->events[i].code == code) + n++; + + return n; +} + +static bool z2_test_has_event(struct z2_test_ctx *ctx, u16 type, u16 code, + s32 value) +{ + unsigned int i; + + for (i = 0; i < min(ctx->nevents, Z2_TEST_MAX_EVENTS); i++) + if (ctx->events[i].type == type && + ctx->events[i].code == code && + ctx->events[i].value == value) + return true; + + return false; +} + +/* The slot that tracks the finger with this key, or -1 if it is not down */ +static int z2_test_slot_of(struct z2_test_ctx *ctx, int key) +{ + struct input_mt *mt = ctx->z2.input_dev->mt; + int i; + + for (i = 0; i < mt->num_slots; i++) + if (input_mt_is_active(&mt->slots[i]) && + mt->slots[i].key == key) + return i; + + return -1; +} + +static unsigned int z2_test_active_slots(struct z2_test_ctx *ctx) +{ + struct input_mt *mt = ctx->z2.input_dev->mt; + unsigned int i, n = 0; + + for (i = 0; i < mt->num_slots; i++) + if (input_mt_is_active(&mt->slots[i])) + n++; + + return n; +} + +static int z2_test_slot_abs(struct z2_test_ctx *ctx, int slot, + unsigned int code) +{ + return input_mt_get_value(&ctx->z2.input_dev->mt->slots[slot], code); +} + +/* Length of a touch report that holds exactly @nfingers finger records */ +static size_t z2_test_msg_len(unsigned int nfingers) +{ + return APPLE_Z2_FINGERS_OFFSET + nfingers * Z2_TEST_FINGER_LEN; +} + +static void z2_test_put_finger(struct z2_test_ctx *ctx, unsigned int idx, + const struct z2_test_finger *f) +{ + u8 *rec = ctx->msg + z2_test_msg_len(idx); + + memset(rec, 0, Z2_TEST_FINGER_LEN); + rec[0] = f->key; + rec[1] = f->state; + put_unaligned_le16(f->x, rec + 4); + put_unaligned_le16(f->y, rec + 6); + put_unaligned_le16(f->tool_major, rec + 12); + put_unaligned_le16(f->tool_minor, rec + 14); + put_unaligned_le16(f->orientation, rec + 16); + put_unaligned_le16(f->touch_major, rec + 18); + put_unaligned_le16(f->touch_minor, rec + 20); +} + +static void z2_test_put_touch(struct z2_test_ctx *ctx, unsigned int idx, + u8 key, u8 state, u16 x, u16 y) +{ + struct z2_test_finger f = { + .key = key, .state = state, .x = x, .y = y, + }; + + z2_test_put_finger(ctx, idx, &f); +} + +static void z2_test_parse(struct z2_test_ctx *ctx, unsigned int nfingers, + size_t msg_len) +{ + ctx->msg[APPLE_Z2_NUM_FINGERS_OFFSET] = nfingers; + apple_z2_parse_touches(&ctx->z2, ctx->msg, msg_len); +} + +/* + * Make ctx->msg the fake device's next interrupt data packet. @wire_len is + * the length field of the device's reply; the device then sends that length + * plus eight, rounded down to a multiple of four. + */ +static void z2_test_queue_packet(struct z2_test_ctx *ctx, + unsigned int nfingers, u16 wire_len) +{ + ctx->msg[APPLE_Z2_NUM_FINGERS_OFFSET] = nfingers; + memset(ctx->pkt, 0, Z2_TEST_RX_ALLOC); + memcpy(ctx->pkt + Z2_TEST_PKT_HDR, ctx->msg, Z2_TEST_MSG_ALLOC); + ctx->pkt_wire_len = wire_len; + ctx->pkt_len = (wire_len + 8) & ~3; + ctx->pkt_ready = true; +} + +/* The smallest length field for a packet that holds @nfingers records */ +static u16 z2_test_wire_len(unsigned int nfingers) +{ + return round_up(Z2_TEST_PKT_HDR + z2_test_msg_len(nfingers), 4) - 8; +} + +/* + * Touch report parser + */ + +/* A finger record written byte by byte, to pin the record layout */ +static void z2_parse_raw_layout(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u8 rec[Z2_TEST_FINGER_LEN] = { + [0] = 9, /* finger key */ + [1] = APPLE_Z2_TOUCH_STARTED, + [4] = 0x34, [5] = 0x02, /* x = 0x234 */ + [6] = 0x21, [7] = 0x01, /* y = 0x121 */ + [12] = 0x01, [13] = 0x10, /* tool major = 0x1001 */ + [14] = 0x02, [15] = 0x20, /* tool minor = 0x2002 */ + [16] = 0x03, [17] = 0x30, /* orientation = 0x3003 */ + [18] = 0x04, [19] = 0x40, /* touch major = 0x4004 */ + [20] = 0x05, [21] = 0x50, /* touch minor = 0x5005 */ + }; + int slot; + + KUNIT_ASSERT_EQ(test, sizeof(struct apple_z2_finger), + Z2_TEST_FINGER_LEN); + ctx->msg[16] = 1; + memcpy(ctx->msg + 24, rec, sizeof(rec)); + apple_z2_parse_touches(&ctx->z2, ctx->msg, 24 + sizeof(rec)); + + slot = z2_test_slot_of(ctx, 9); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 1); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 0x234); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 0x121); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 0x234)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 0x121)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_WIDTH_MAJOR, 0x1001)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_WIDTH_MINOR, 0x2002)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_ORIENTATION, 0x3003)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TOUCH_MAJOR, 0x4004)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TOUCH_MINOR, 0x5005)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 1); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_KEY, BTN_TOUCH, 1)); + + /* The frame is closed */ + KUNIT_ASSERT_GT(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, ctx->events[ctx->nevents - 1].type, EV_SYN); + KUNIT_EXPECT_EQ(test, ctx->events[ctx->nevents - 1].code, SYN_REPORT); +} + +static void z2_parse_touch_move_release(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot, id; + + z2_test_put_touch(ctx, 0, 4, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + slot = z2_test_slot_of(ctx, 4); + KUNIT_ASSERT_GE(test, slot, 0); + id = z2_test_slot_abs(ctx, slot, ABS_MT_TRACKING_ID); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TRACKING_ID, id)); + + /* A moving finger keeps its slot and its tracking id */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 4, APPLE_Z2_TOUCH_MOVED, 130, 60); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 4), slot); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_TRACKING_ID), + id); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 130)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 60)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); + + /* Any other state lifts the finger; its position is not reported */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 4, Z2_TEST_STATE_LIFTED, 999, 99); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 4), -1); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_TRACKING_ID, -1)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_POSITION_X), 0); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_KEY, BTN_TOUCH, 0)); +} + +static void z2_parse_two_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot_a, slot_b; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 200, APPLE_Z2_TOUCH_STARTED, 1500, 400); + z2_test_parse(ctx, 2, z2_test_msg_len(2)); + + slot_a = z2_test_slot_of(ctx, 1); + slot_b = z2_test_slot_of(ctx, 200); + KUNIT_ASSERT_GE(test, slot_a, 0); + KUNIT_ASSERT_GE(test, slot_b, 0); + KUNIT_EXPECT_NE(test, slot_a, slot_b); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 2); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_a, ABS_MT_POSITION_X), + 10); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_a, ABS_MT_POSITION_Y), + 20); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_b, ABS_MT_POSITION_X), + 1500); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot_b, ABS_MT_POSITION_Y), + 400); + KUNIT_EXPECT_NE(test, + z2_test_slot_abs(ctx, slot_a, ABS_MT_TRACKING_ID), + z2_test_slot_abs(ctx, slot_b, ABS_MT_TRACKING_ID)); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 2); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); + + /* One finger lifts, the other stays where it is */ + z2_test_put_touch(ctx, 0, 1, Z2_TEST_STATE_LIFTED, 10, 20); + z2_test_put_touch(ctx, 1, 200, APPLE_Z2_TOUCH_MOVED, 1500, 400); + z2_test_parse(ctx, 2, z2_test_msg_len(2)); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 1), -1); + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 200), slot_b); +} + +/* Only "started" and "moved" put a finger down */ +static void z2_parse_other_states(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int state; + + for (state = 0; state < 256; state++) { + bool down = state == APPLE_Z2_TOUCH_STARTED || + state == APPLE_Z2_TOUCH_MOVED; + + z2_test_put_touch(ctx, 0, 7, state, 300, 200); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + KUNIT_EXPECT_EQ_MSG(test, z2_test_slot_of(ctx, 7) >= 0, down, + "state %u", state); + } +} + +/* A report too short to hold the finger count is ignored altogether */ +static void z2_parse_short_msg(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t len; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + for (len = 0; len <= APPLE_Z2_NUM_FINGERS_OFFSET; len++) + z2_test_parse(ctx, 1, len); + + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); +} + +static void z2_parse_no_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* A record is present, but the count says there is none */ + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_parse(ctx, 0, z2_test_msg_len(1)); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +static void z2_parse_inverted(struct kunit *test) +{ + static const struct z2_test_cfg cfg = { + .size_x = 2000, .size_y = 600, + .invert_x = true, .invert_y = true, + }; + struct z2_test_ctx *ctx = z2_test_setup(test, &cfg); + int slot; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + + slot = z2_test_slot_of(ctx, 1); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 1999 - 100); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 599 - 50); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_X, 1899)); + KUNIT_EXPECT_TRUE(test, z2_test_has_event(ctx, EV_ABS, + ABS_MT_POSITION_Y, 549)); +} + +static void z2_parse_swapped(struct kunit *test) +{ + static const struct z2_test_cfg cfg = { + .size_x = 2000, .size_y = 600, + .invert_y = true, .swap_x_y = true, + }; + struct z2_test_ctx *ctx = z2_test_setup(test, &cfg); + int slot; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_parse(ctx, 1, z2_test_msg_len(1)); + + /* The y axis is inverted first, then the axes trade places */ + slot = z2_test_slot_of(ctx, 1); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 599 - 50); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 100); +} + +/* The largest count a report can carry, with all its records present */ +static void z2_parse_255_fingers(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int i; + + for (i = 0; i < 255; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_parse(ctx, 255, z2_test_msg_len(255)); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 255); + for (i = 0; i < 255; i += 127) { + int slot = z2_test_slot_of(ctx, i); + + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, + z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + i + 1); + KUNIT_EXPECT_EQ(test, + z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + i + 2); + } +} + +/* + * The report says it has 255 fingers but is only long enough for three. + * What lies behind the report (here: plausible finger records) is not part + * of it and must not turn into touches. + */ +static void z2_parse_count_beyond_report(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int i, beyond = 0; + + for (i = 0; i < 255; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_parse(ctx, 255, z2_test_msg_len(3)); + + for (i = 3; i < 255; i++) + if (z2_test_slot_of(ctx, i) >= 0) + beyond++; + KUNIT_EXPECT_EQ(test, beyond, 0); + KUNIT_EXPECT_LE(test, z2_test_active_slots(ctx), 3); +} + +/* The report ends before the first finger record */ +static void z2_parse_count_without_records(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t len; + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 30, 40); + for (len = APPLE_Z2_NUM_FINGERS_OFFSET + 1; + len <= APPLE_Z2_FINGERS_OFFSET; len++) + z2_test_parse(ctx, 2, len); + + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +/* The report ends in the middle of the second finger record */ +static void z2_parse_partial_record(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 10, 20); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 30, 40); + z2_test_parse(ctx, 2, z2_test_msg_len(2) - 1); + + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 2), -1); + KUNIT_EXPECT_LE(test, z2_test_active_slots(ctx), 1); +} + +/* + * Interrupt data packets + */ + +static void z2_read_command_framing(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u8 counters[] = { 1, 2, 1, 2 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(counters); i++) { + const struct z2_test_xfer *xfer = &ctx->xfers[0]; + + z2_test_clear_log(ctx); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + /* No data pending: the command is the only transfer */ + KUNIT_ASSERT_EQ(test, ctx->nxfers, 1); + KUNIT_EXPECT_EQ(test, xfer->len, 16); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_TRUE(test, xfer->has_rx); + KUNIT_EXPECT_EQ(test, xfer->tx[0], 0xeb); + KUNIT_EXPECT_EQ(test, xfer->tx[1], counters[i]); + KUNIT_EXPECT_TRUE(test, !memchr_inv(xfer->tx + 2, 0, 12)); + /* The checksum is the sum of the bytes in front of it */ + KUNIT_EXPECT_EQ(test, get_unaligned_le16(xfer->tx + 14), + 0xeb + counters[i]); + } + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); +} + +/* The packet read asks for the reply's length plus 8, rounded down to 4 */ +static void z2_read_length_rounding(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const struct { + u16 wire_len; + unsigned int read_len; + } cases[] = { + { 0, 8 }, { 1, 8 }, { 3, 8 }, { 4, 12 }, { 52, 60 }, + { 55, 60 }, { 56, 64 }, { 3991, 3996 }, { 3992, 4000 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + z2_test_clear_log(ctx); + z2_test_queue_packet(ctx, 0, cases[i].wire_len); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_ASSERT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_FALSE(test, ctx->xfers[1].has_tx); + KUNIT_EXPECT_TRUE(test, ctx->xfers[1].has_rx); + KUNIT_EXPECT_EQ_MSG(test, ctx->xfers[1].len, cases[i].read_len, + "length field %u", cases[i].wire_len); + } +} + +/* The touch report starts five bytes into the packet */ +static void z2_read_reports_touch(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + int slot; + + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + z2_test_put_touch(ctx, 1, 5, APPLE_Z2_TOUCH_STARTED, 800, 310); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(2)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 2); + slot = z2_test_slot_of(ctx, 3); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 700); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 300); + slot = z2_test_slot_of(ctx, 5); + KUNIT_ASSERT_GE(test, slot, 0); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_X), + 800); + KUNIT_EXPECT_EQ(test, z2_test_slot_abs(ctx, slot, ABS_MT_POSITION_Y), + 310); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_SYN, SYN_REPORT), + 1); +} + +static void z2_read_spi_errors(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + + /* The command fails: no packet read follows */ + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + ctx->fail_xfer = 0; + KUNIT_EXPECT_EQ(test, apple_z2_read_packet(&ctx->z2), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 1); + + /* The packet read fails: whatever is in the buffer is not parsed */ + z2_test_clear_log(ctx); + memcpy(ctx->z2.rx_buf, ctx->pkt, 64); + ctx->fail_xfer = 1; + KUNIT_EXPECT_EQ(test, apple_z2_read_packet(&ctx->z2), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 0); +} + +/* The largest packet that fits the driver's receive buffer */ +static void z2_read_largest_packet(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + unsigned int nfingers = (Z2_TEST_RX_SIZE - Z2_TEST_PKT_HDR - + APPLE_Z2_FINGERS_OFFSET) / Z2_TEST_FINGER_LEN; + unsigned int i; + + for (i = 0; i < nfingers; i++) + z2_test_put_touch(ctx, i, i, APPLE_Z2_TOUCH_STARTED, + i + 1, i + 2); + z2_test_queue_packet(ctx, nfingers, Z2_TEST_RX_SIZE - 8); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, ctx->max_rx_len, Z2_TEST_RX_SIZE); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), nfingers); +} + +/* + * The device's reply carries a 16-bit length. The driver must not read more + * than its receive buffer holds, whatever the device says. + */ +static void z2_read_oversize_length(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + static const u16 wire_lens[] = { + Z2_TEST_RX_SIZE - 7, Z2_TEST_RX_SIZE - 4, Z2_TEST_RX_SIZE, + 8192, 0xfff7, 0xffff, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(wire_lens); i++) { + z2_test_clear_log(ctx); + z2_test_queue_packet(ctx, 0, wire_lens[i]); + apple_z2_read_packet(&ctx->z2); + KUNIT_EXPECT_LE_MSG(test, ctx->max_rx_len, + (size_t)Z2_TEST_RX_SIZE, + "length field %u", wire_lens[i]); + } +} + +/* + * A packet that is too short for its finger count must not report what an + * earlier, longer packet left in the receive buffer. + */ +static void z2_read_stale_finger(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* Two fingers down */ + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_STARTED, 100, 50); + z2_test_put_touch(ctx, 1, 2, APPLE_Z2_TOUCH_STARTED, 900, 300); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(2)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + KUNIT_ASSERT_EQ(test, z2_test_active_slots(ctx), 2); + + /* Finger 2 lifts, in a packet with one record */ + z2_test_put_touch(ctx, 0, 2, Z2_TEST_STATE_LIFTED, 900, 300); + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + KUNIT_ASSERT_EQ(test, z2_test_slot_of(ctx, 2), -1); + + /* Finger 1 moves; the packet claims two records but holds one */ + z2_test_clear_log(ctx); + z2_test_put_touch(ctx, 0, 1, APPLE_Z2_TOUCH_MOVED, 110, 55); + z2_test_queue_packet(ctx, 2, z2_test_wire_len(1)); + KUNIT_ASSERT_EQ(test, apple_z2_read_packet(&ctx->z2), 0); + + KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 2), -1); + KUNIT_EXPECT_EQ(test, z2_test_count_events(ctx, EV_ABS, + ABS_MT_TRACKING_ID), 0); +} + +static void z2_irq_boot_and_data(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + /* Before the firmware runs, an interrupt only signals the boot */ + z2_test_put_touch(ctx, 0, 3, APPLE_Z2_TOUCH_STARTED, 700, 300); + z2_test_queue_packet(ctx, 1, z2_test_wire_len(1)); + KUNIT_EXPECT_EQ(test, apple_z2_irq(0, &ctx->z2), IRQ_HANDLED); + KUNIT_EXPECT_TRUE(test, try_wait_for_completion(&ctx->z2.boot_irq)); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); + KUNIT_EXPECT_EQ(test, ctx->nevents, 0); + + /* Afterwards it fetches a packet */ + ctx->z2.booted = true; + KUNIT_EXPECT_EQ(test, apple_z2_irq(0, &ctx->z2), IRQ_HANDLED); + KUNIT_EXPECT_FALSE(test, try_wait_for_completion(&ctx->z2.boot_irq)); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 2); + KUNIT_EXPECT_GE(test, z2_test_slot_of(ctx, 3), 0); +} + +/* + * Firmware upload + * + * The images below are synthetic and go straight to + * apple_z2_load_firmware(). Several entries share one image and differ in + * the size they declare. + */ + +static const __le32 z2_test_fw_good[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + /* Six bytes for 8-bit transfer, then two bytes of padding */ + cpu_to_le32(LOAD_COMMAND_INIT_PAYLOAD), cpu_to_le32(6), + cpu_to_le32(0x04030201), cpu_to_le32(0xeeee0605), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(8), + cpu_to_le32(0x14131211), cpu_to_le32(0x18171615), + cpu_to_le32(LOAD_COMMAND_SEND_CALIBRATION), cpu_to_le32(0x00123456), + /* Not part of the image except in the "trailing" entry */ + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), +}; + +static const __le32 z2_test_fw_bad_magic[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC + 1), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), +}; + +static const __le32 z2_test_fw_bad_version[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(2), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), +}; + +static const __le32 z2_test_fw_bad_command[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(4), + cpu_to_le32(0x04030201), + cpu_to_le32(3), cpu_to_le32(4), + cpu_to_le32(0x14131211), +}; + +static const __le32 z2_test_fw_huge_blob[] = { + cpu_to_le32(APPLE_Z2_FW_MAGIC), cpu_to_le32(1), + cpu_to_le32(LOAD_COMMAND_SEND_BLOB), cpu_to_le32(0xfffffffc), + cpu_to_le32(0x04030201), cpu_to_le32(0x08070605), +}; + +struct z2_test_image { + const char *name; + const void *data; + size_t size; +}; + +#define Z2_TEST_FW(_name, _image, _size) \ + { "apple-z2-kunit/" _name ".bin", (_image), (_size) } + +static const struct z2_test_image z2_test_fw_table[] = { + Z2_TEST_FW("good", z2_test_fw_good, 48), + Z2_TEST_FW("header-only", z2_test_fw_good, 8), + Z2_TEST_FW("short-header", z2_test_fw_good, 4), + Z2_TEST_FW("unpadded-end", z2_test_fw_good, 22), + Z2_TEST_FW("cut-command", z2_test_fw_good, 28), + Z2_TEST_FW("cut-blob", z2_test_fw_good, 20), + Z2_TEST_FW("cut-calibration", z2_test_fw_good, 44), + Z2_TEST_FW("trailing", z2_test_fw_good, 52), + Z2_TEST_FW("bad-magic", z2_test_fw_bad_magic, + sizeof(z2_test_fw_bad_magic)), + Z2_TEST_FW("bad-version", z2_test_fw_bad_version, + sizeof(z2_test_fw_bad_version)), + Z2_TEST_FW("bad-command", z2_test_fw_bad_command, + sizeof(z2_test_fw_bad_command)), + Z2_TEST_FW("huge-blob", z2_test_fw_huge_blob, + sizeof(z2_test_fw_huge_blob)), +}; + +static const u8 z2_test_cal[] = { + 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0xff, +}; + +/* The blob the driver builds from z2_test_cal for address 0x00123456 */ +static const u8 z2_test_cal_blob[] = { + 0x01, 0x30, /* blob command */ + 0x02, 0x00, /* length in 32-bit words */ + 0x56, 0x34, 0x12, 0x00, /* address */ + 0x9e, 0x00, /* sum of the six bytes before */ + 0x00, 0x00, /* padding */ + 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0xff, + 0xbf, 0x02, 0x00, 0x00, /* sum of the calibration bytes */ +}; + +static const struct z2_test_cfg z2_test_cfg_cal = { + .size_x = 2000, + .size_y = 600, + .cal = z2_test_cal, + .cal_len = sizeof(z2_test_cal), +}; + +/* Upload one of the images above, as apple_z2_upload_firmware() would */ +static int z2_test_upload(struct z2_test_ctx *ctx, const char *name) +{ + struct firmware fw = {}; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(z2_test_fw_table); i++) { + if (strcmp(z2_test_fw_table[i].name, name)) + continue; + fw.data = z2_test_fw_table[i].data; + fw.size = z2_test_fw_table[i].size; + return apple_z2_load_firmware(&ctx->z2, &fw); + } + + /* Not one of ours: let the firmware loader fail to find it */ + ctx->z2.fw_name = name; + return apple_z2_upload_firmware(&ctx->z2); +} + +/* A firmware blob transfer and the acknowledge that follows it */ +static void z2_test_expect_blob(struct kunit *test, struct z2_test_ctx *ctx, + unsigned int idx, const void *data, + unsigned int len, unsigned int bpw) +{ + static const u8 ack[] = { 0x1a, 0xa1 }; + const struct z2_test_xfer *xfer = &ctx->xfers[idx]; + + KUNIT_ASSERT_LT(test, idx + 1, min(ctx->nxfers, Z2_TEST_MAX_XFERS)); + KUNIT_ASSERT_LE(test, len, Z2_TEST_TX_LOG); + KUNIT_EXPECT_EQ(test, xfer->len, len); + KUNIT_EXPECT_EQ(test, xfer->bpw, bpw); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_FALSE(test, xfer->has_rx); + KUNIT_EXPECT_MEMEQ(test, xfer->tx, data, len); + + xfer++; + KUNIT_EXPECT_EQ(test, xfer->len, sizeof(ack)); + KUNIT_EXPECT_EQ(test, xfer->bpw, 8); + KUNIT_EXPECT_TRUE(test, xfer->has_tx); + KUNIT_EXPECT_FALSE(test, xfer->has_rx); + KUNIT_EXPECT_MEMEQ(test, xfer->tx, ack, sizeof(ack)); +} + +static void z2_fw_upload(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + + KUNIT_ASSERT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + + /* Three blobs with their acknowledges, then a first packet poll */ + KUNIT_ASSERT_EQ(test, ctx->nxfers, 7); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); + z2_test_expect_blob(test, ctx, 2, &z2_test_fw_good[8], 8, 16); + z2_test_expect_blob(test, ctx, 4, z2_test_cal_blob, + sizeof(z2_test_cal_blob), 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[6].len, 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[6].tx[0], 0xeb); +} + +/* Without a calibration property the calibration command is skipped */ +static void z2_fw_no_calibration(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + size_t size = 0; + + KUNIT_EXPECT_NULL(test, apple_z2_build_cal_blob(&ctx->z2, 0x123456, + &size)); + + KUNIT_ASSERT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_ASSERT_EQ(test, ctx->nxfers, 5); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); + z2_test_expect_blob(test, ctx, 2, &z2_test_fw_good[8], 8, 16); + KUNIT_EXPECT_EQ(test, ctx->xfers[4].tx[0], 0xeb); +} + +static void z2_fw_cal_blob(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + size_t size = 0; + const u8 *blob; + + blob = apple_z2_build_cal_blob(&ctx->z2, 0x00123456, &size); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, blob); + KUNIT_EXPECT_EQ(test, size, sizeof(z2_test_cal_blob)); + if (size == sizeof(z2_test_cal_blob)) + KUNIT_EXPECT_MEMEQ(test, blob, z2_test_cal_blob, size); + kfree(blob); +} + +/* Images that end cleanly, with and without commands */ +static void z2_fw_clean_end(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/header-only.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 1); + + /* The last blob need not be padded */ + ctx->z2.booted = false; + z2_test_clear_log(ctx); + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/unpadded-end.bin"), + 0); + KUNIT_EXPECT_TRUE(test, ctx->z2.booted); + KUNIT_ASSERT_EQ(test, ctx->nxfers, 3); + z2_test_expect_blob(test, ctx, 0, &z2_test_fw_good[4], 6, 8); +} + +struct z2_test_fw_case { + const char *name; + /* Transfers that happen before the image is found malformed */ + unsigned int nxfers; +}; + +static void z2_test_fw_case_desc(const struct z2_test_fw_case *c, char *desc) +{ + strscpy(desc, c->name + strlen("apple-z2-kunit/"), + KUNIT_PARAM_DESC_SIZE); +} + +static const struct z2_test_fw_case z2_test_fw_rejected[] = { + { "apple-z2-kunit/bad-magic.bin", 0 }, + { "apple-z2-kunit/bad-version.bin", 0 }, + /* The image ends inside a command header */ + { "apple-z2-kunit/cut-command.bin", 2 }, + /* The image ends inside a blob */ + { "apple-z2-kunit/cut-blob.bin", 0 }, + /* The image ends in front of the calibration address */ + { "apple-z2-kunit/cut-calibration.bin", 4 }, + /* Four stray bytes after the last command */ + { "apple-z2-kunit/trailing.bin", 4 }, + { "apple-z2-kunit/bad-command.bin", 2 }, + { "apple-z2-kunit/huge-blob.bin", 0 }, +}; + +KUNIT_ARRAY_PARAM(z2_fw_rejected, z2_test_fw_rejected, z2_test_fw_case_desc); + +static void z2_fw_rejected(struct kunit *test) +{ + const struct z2_test_fw_case *c = test->param_value; + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, z2_test_upload(ctx, c->name), -EINVAL); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, c->nxfers); +} + +/* An image shorter than its own header has no magic and version to accept */ +static void z2_fw_short_header(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_EQ(test, + z2_test_upload(ctx, "apple-z2-kunit/short-header.bin"), + -EINVAL); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); +} + +static void z2_fw_missing(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_plain); + + KUNIT_EXPECT_LT(test, + z2_test_upload(ctx, "apple-z2-kunit/missing.bin"), 0); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 0); +} + +static void z2_fw_spi_error(struct kunit *test) +{ + struct z2_test_ctx *ctx = z2_test_setup(test, &z2_test_cfg_cal); + + /* The second blob fails: the upload stops there */ + ctx->fail_xfer = 2; + KUNIT_EXPECT_EQ(test, z2_test_upload(ctx, "apple-z2-kunit/good.bin"), + -EIO); + KUNIT_EXPECT_FALSE(test, ctx->z2.booted); + KUNIT_EXPECT_EQ(test, ctx->nxfers, 3); +} + +static struct kunit_case apple_z2_test_cases[] = { + KUNIT_CASE(z2_parse_raw_layout), + KUNIT_CASE(z2_parse_touch_move_release), + KUNIT_CASE(z2_parse_two_fingers), + KUNIT_CASE(z2_parse_other_states), + KUNIT_CASE(z2_parse_short_msg), + KUNIT_CASE(z2_parse_no_fingers), + KUNIT_CASE(z2_parse_inverted), + KUNIT_CASE(z2_parse_swapped), + KUNIT_CASE(z2_parse_255_fingers), + KUNIT_CASE(z2_parse_count_beyond_report), + KUNIT_CASE(z2_parse_count_without_records), + KUNIT_CASE(z2_parse_partial_record), + KUNIT_CASE(z2_read_command_framing), + KUNIT_CASE(z2_read_length_rounding), + KUNIT_CASE(z2_read_reports_touch), + KUNIT_CASE(z2_read_spi_errors), + KUNIT_CASE(z2_read_largest_packet), + KUNIT_CASE(z2_read_oversize_length), + KUNIT_CASE(z2_read_stale_finger), + KUNIT_CASE(z2_irq_boot_and_data), + KUNIT_CASE(z2_fw_upload), + KUNIT_CASE(z2_fw_no_calibration), + KUNIT_CASE(z2_fw_cal_blob), + KUNIT_CASE(z2_fw_clean_end), + KUNIT_CASE_PARAM(z2_fw_rejected, z2_fw_rejected_gen_params), + KUNIT_CASE(z2_fw_short_header), + KUNIT_CASE(z2_fw_missing), + KUNIT_CASE(z2_fw_spi_error), + {} +}; + +static struct kunit_suite apple_z2_test_suite = { + .name = "apple-z2", + .test_cases = apple_z2_test_cases, +}; + +kunit_test_suite(apple_z2_test_suite); diff --git a/drivers/input/touchscreen/apple_z2.c b/drivers/input/touchscreen/apple_z2.c index 235e4fd69f6f9c..aad5a9e465e4dc 100644 --- a/drivers/input/touchscreen/apple_z2.c +++ b/drivers/input/touchscreen/apple_z2.c @@ -500,3 +500,7 @@ module_spi_driver(apple_z2_driver); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("apple/dfrmtfw-*.bin"); MODULE_DESCRIPTION("Apple Z2 touchscreens driver"); + +#if IS_ENABLED(CONFIG_TOUCHSCREEN_APPLE_Z2_KUNIT_TEST) +#include "apple_z2-test.c" +#endif diff --git a/drivers/input/touchscreen/apple_z2.kunitconfig b/drivers/input/touchscreen/apple_z2.kunitconfig new file mode 100644 index 00000000000000..526ee9bead6680 --- /dev/null +++ b/drivers/input/touchscreen/apple_z2.kunitconfig @@ -0,0 +1,9 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/input/touchscreen/apple_z2.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_SPI=y +CONFIG_INPUT=y +CONFIG_INPUT_TOUCHSCREEN=y +CONFIG_FW_LOADER=y +CONFIG_TOUCHSCREEN_APPLE_Z2=y +CONFIG_TOUCHSCREEN_APPLE_Z2_KUNIT_TEST=y From b729c69a9356ab5b7e03671f8d488f10decbc5d9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:43:24 +1100 Subject: [PATCH 0542/1514] soc: apple: sep: decide every capture's liveness through capture_live() Two places in sbio.rs still decided on their own whether the capture was wanted, with the expression capture_live() had before: - The verify capture's CaptureWait::Abandon arm logged "the sensor status became unreadable during the capture" whenever a touch-gated call was active, so a capture given up for /dev/sep-bio, cancelled or ended by a signal was reported as a sensor fault. - verify_wanted(), which bounds the bring-up retries of a verify on sensors with a nonce session, neither gave way to /dev/sep-bio nor ended on a signal to the caller, and kept retrying after SEP_KEY_CANCEL while a /dev/sep-bio verify was queued. Use capture_live() in both. The UAPI text now also says that a caller retrying after EBUSY should back off, as a /dev/sep-bio verify can stay open for a long time. Signed-off-by: Ryan Murray --- drivers/soc/apple/sbio.rs | 15 +++++++-------- include/uapi/linux/apple-sep.h | 3 ++- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 358dd8864c7f2b..1ce3134a42653b 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -2552,11 +2552,11 @@ impl SepData { } /// Whether the verify this work item runs is still wanted: not cancelled, - /// not ended by a suspend and not closed. + /// not ended by a suspend and not closed, and, for a touch-gated + /// `/dev/sep-key` call, not given up for `/dev/sep-bio` (see + /// [`Self::capture_live`]). fn verify_wanted(&self) -> bool { - !self.shutting_down.load(Relaxed) - && ((self.key_touch_active.load(Relaxed) && !self.key_touch_cancel.load(Relaxed)) - || bio::verify_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed))) + !self.shutting_down.load(Relaxed) && self.capture_live() } // Every verify registers the sensor again. On a profile with a nonce @@ -3071,10 +3071,9 @@ impl SepData { return bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR); } CaptureWait::Abandon => { - // A cancelled verify also abandons; only a live one is a fault. - if self.key_touch_active.load(Relaxed) - || bio::verify_is_live(&self.bio_session.lock(), self.capture_epoch.load(Relaxed)) - { + // A cancelled or given-up capture also abandons; only one + // still wanted is a fault. + if self.capture_live() { dev_err_ratelimited!( self.dev, "verify: the sensor status became unreadable during the capture\n" diff --git a/include/uapi/linux/apple-sep.h b/include/uapi/linux/apple-sep.h index d882c204c5b8f5..2c7ef1f6941a2b 100644 --- a/include/uapi/linux/apple-sep.h +++ b/include/uapi/linux/apple-sep.h @@ -308,7 +308,8 @@ struct sep_bio_rearm { * ENODEV while the key store or Touch ID is not up, EOPNOTSUPP for a * reserved policy, ECANCELED after SEP_KEY_CANCEL, EBUSY when a Touch ID * verify or enrolment on /dev/sep-bio wants the sensor during the wait (try - * again later), EIO for any other enclave failure. + * again later, backing off: a verify such as a lock screen's can stay open + * for a long time), EIO for any other enclave failure. */ #define SEP_KEY_IFACE_VERSION 4 #define SEP_KEY_FEATURE_CANCEL 0x1 From 8235c80cd7ea8d8a6608f07bdde6e652002d571c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:55:54 +1100 Subject: [PATCH 0543/1514] iommu: apple-dart: pass the DCP ADT tables to the import by reference apple_dart_dcp_import() takes struct dcp_adt_tables by value, and its callers copy the 552-byte table description into a local 'bounds' only to change start and end. With the import inlined, the external and internal frontend prepare paths each carry several copies: 2144 bytes of stack under KASAN, which fails a CONFIG_WERROR build at the default 2048-byte frame limit. Pass the firmware description by const pointer with the table range as two arguments, and store the adjusted copy only in the imported DCP. apple_dart_dispext_prepare() drops to 944 bytes and apple_dart_frontend_prepare() to 976 (arm64, KASAN inline). No change in behaviour. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-dcp.h | 51 +++++++++++++++++----------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/drivers/iommu/apple-dart-dcp.h b/drivers/iommu/apple-dart-dcp.h index 813dd46c07df6d..b9239cd7405a62 100644 --- a/drivers/iommu/apple-dart-dcp.h +++ b/drivers/iommu/apple-dart-dcp.h @@ -517,8 +517,13 @@ static bool apple_dart_dcp_leaf_safe(const struct apple_dart_dcp *dcp, u64 leaf) IORES_DESC_NONE) == REGION_DISJOINT; } +/* + * Import SID @sid, whose tables live in [@start, @end); @firmware supplies the + * rest of the ADT description. Passed by reference: the tables are ~0.5 KiB. + */ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, - struct dcp_adt_tables bounds, struct apple_dart_dcp **result) + const struct dcp_adt_tables *firmware, u64 start, u64 end, + struct apple_dart_dcp **result) { struct apple_dart_dcp *dcp; u64 root_pa; @@ -537,7 +542,7 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, "DCP admission: lock=%d type=%u streams=%u page=%u IAS/OAS=%u/%u range=%pad..%pad TCR%u=%08x enabled=%08x\n", dart->locked, dart->hw->type, dart->num_streams, dart->pgsize, dart->ias, dart->oas, &dart->dma_min, &dart->dma_max, sid, tcr, enabled); - ret = apple_dart_dcp_excluded(dart, bounds.start, bounds.end); + ret = apple_dart_dcp_excluded(dart, start, end); if (ret) return dev_err_probe(dart->dev, ret, "DCP table storage is not excluded memory\n"); dcp = apple_dart_retained_alloc(dart, sizeof(*dcp)); @@ -545,7 +550,9 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, return -ENOMEM; dcp->dart = dart; dcp->sid = sid; - dcp->firmware = bounds; + dcp->firmware = *firmware; + dcp->firmware.start = start; + dcp->firmware.end = end; ret = apple_dart_dcp_excluded_regions(dcp); if (ret) return dev_err_probe(dart->dev, ret, "invalid reserved-memory leaf exclusions\n"); @@ -559,17 +566,17 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, INIT_LIST_HEAD(&dcp->shared); dcp->ttbr = readl(dart->regs + DART_TTBR(dart, sid, 0)); root_pa = ((u64)dcp->ttbr >> 2) << 14; - if ((dcp->ttbr & 3) != 1 || (sid != 23 && root_pa != bounds.start) || - !dcp_dart_contains(bounds.start, bounds.end, root_pa, DCP_DART_PAGE)) + if ((dcp->ttbr & 3) != 1 || (sid != 23 && root_pa != start) || + !dcp_dart_contains(start, end, root_pa, DCP_DART_PAGE)) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: TTBR%u=%08x root=%llx outside ADT [%llx,%llx) or invalid flags\n", - sid, dcp->ttbr, root_pa, bounds.start, bounds.end); - storage = apple_dart_retained_memremap(dart, bounds.start, bounds.end - bounds.start); + sid, dcp->ttbr, root_pa, start, end); + storage = apple_dart_retained_memremap(dart, start, end - start); if (IS_ERR(storage)) return PTR_ERR(storage); if (!storage) return -ENOMEM; - dcp->root = (u64 *)(storage + root_pa - bounds.start); + dcp->root = (u64 *)(storage + root_pa - start); for (unsigned int i = 0; i < DCP_DART_ENTRIES; i++) { u64 pte = READ_ONCE(dcp->root[i]); u64 pa = dcp_dart_pte_phys(pte); @@ -581,16 +588,16 @@ static int apple_dart_dcp_import(struct apple_dart *dart, unsigned int sid, dcp->entry[i] = pte; if (!pte) continue; - if (pa == root_pa || !dcp_dart_contains(bounds.start, bounds.end, pa, DCP_DART_PAGE)) + if (pa == root_pa || !dcp_dart_contains(start, end, pa, DCP_DART_PAGE)) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: root[%u]=%016llx child=%llx outside ADT [%llx,%llx) or aliases root\n", - i, pte, pa, bounds.start, bounds.end); + i, pte, pa, start, end); for (unsigned int j = 0; j < i; j++) if (dcp->entry[j] && dcp_dart_pte_phys(dcp->entry[j]) == pa) return dev_err_probe(dart->dev, -EINVAL, "DCP admission: roots %u and %u alias child=%llx\n", j, i, pa); - dcp->table[i] = (u64 *)(storage + pa - bounds.start); + dcp->table[i] = (u64 *)(storage + pa - start); set_bit(i, dcp->foreign); if (sid != 23) { dcp->expected[i] = apple_dart_retained_alloc(dart, DCP_DART_PAGE); @@ -641,7 +648,7 @@ static int apple_dart_dcp_prepare(struct apple_dart *dart) if (ret) return dev_err_probe(dart->dev, ret, "cannot validate existing ADT table handoff\n"); - return apple_dart_dcp_import(dart, 23, tables, &dart->dcp); + return apple_dart_dcp_import(dart, 23, &tables, tables.start, tables.end, &dart->dcp); } static bool apple_dart_dcp_iova(u64 iova) @@ -863,7 +870,7 @@ static int apple_dart_frontend_validate(struct apple_dart_dcp *dcp, */ static int apple_dart_dispext_prepare(struct apple_dart *dart) { - struct dcp_adt_tables firmware, bounds; + struct dcp_adt_tables firmware; struct dcp_adt_frontend frontend; struct apple_dart_dcp *borrowed; int ret; @@ -878,10 +885,8 @@ static int apple_dart_dispext_prepare(struct apple_dart *dart) return dev_err_probe(dart->dev, ret, "tables not described\n"); if (!(frontend.seen & 4) || frontend.end[1] <= frontend.start[1]) return dev_err_probe(dart->dev, -ENODEV, "no SID16 table region\n"); - bounds = firmware; - bounds.start = frontend.start[1]; - bounds.end = frontend.end[1]; - ret = apple_dart_dcp_import(dart, 16, bounds, &borrowed); + ret = apple_dart_dcp_import(dart, 16, &firmware, frontend.start[1], frontend.end[1], + &borrowed); if (ret) return ret; if (!apple_dart_dcp_registers(borrowed)) @@ -902,10 +907,8 @@ static int apple_dart_dispext_prepare(struct apple_dart *dart) dev_info(dart->dev, "no SID0 table region: SID0 left alone\n"); return 0; } - bounds = firmware; - bounds.start = frontend.start[0]; - bounds.end = frontend.end[0]; - ret = apple_dart_dcp_import(dart, 0, bounds, &borrowed); + ret = apple_dart_dcp_import(dart, 0, &firmware, frontend.start[0], frontend.end[0], + &borrowed); if (ret || !apple_dart_dcp_registers(borrowed)) { dev_warn(dart->dev, "SID0 not adopted (%d); SID16 is\n", ret); return 0; @@ -981,12 +984,10 @@ static int apple_dart_frontend_prepare(struct apple_dart *dart) if (ret) return ret; for (unsigned int i = 0; i < 2; i++) { - struct dcp_adt_tables bounds = firmware; struct device_node *node; - bounds.start = frontend.start[i]; - bounds.end = frontend.end[i]; - ret = apple_dart_dcp_import(dart, i ? 16 : 0, bounds, &borrowed[i]); + ret = apple_dart_dcp_import(dart, i ? 16 : 0, &firmware, frontend.start[i], + frontend.end[i], &borrowed[i]); if (ret) return ret; node = of_find_node_by_path(i ? "disp0_piodma" : "disp0"); From 6c89cd20c55feac0fae8264fa2ecb33e6c21b1ab Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:55:55 +1100 Subject: [PATCH 0544/1514] drm/apple: complete an early swap without a swap_complete record on the stack dcp_swapped() completes a swap whose completion arrived early on external desktop 26.x firmware by building a zeroed dc_swap_complete_resp on the stack and passing it to dcpep_cb_swap_complete(), which only reads its swap_id. The record is 0x730 bytes on those firmware versions, enough to put dcp_swapped() at 2080 bytes under KASAN and fail a CONFIG_WERROR build. Split the swap-id handling out of dcpep_cb_swap_complete() into dcp_swap_complete_id() and call that directly. dcp_swapped() drops to 96 bytes. The receive path is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_template.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 0e9064dcb289b9..9b19b47c65651e 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -842,16 +842,22 @@ static void dcp_peer_queue_completion(struct apple_dcp *owner, u32 id, ktime_t t } #endif -static void dcpep_cb_swap_complete(struct apple_dcp *dcp, - struct DCP_FW_NAME(dc_swap_complete_resp) *resp) +/* Only the swap id of a swap_complete record is used. */ +static void dcp_swap_complete_id(struct apple_dcp *dcp, u32 swap_id) { ktime_t now = dcp_is_ext26(dcp) ? ns_to_ktime(dcp->ext26_rx_ns) : ktime_get(); - trace_iomfb_swap_complete(dcp, resp->swap_id); + trace_iomfb_swap_complete(dcp, swap_id); #if (DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER >= DCP_FW_VERSION(27, 0, 0)) - if (dcp_peer_swap_complete_v27(dcp, resp->swap_id, now, dcp_peer_queue_completion)) + if (dcp_peer_swap_complete_v27(dcp, swap_id, now, dcp_peer_queue_completion)) return; #endif - dcp_report_swap_complete(dcp, resp->swap_id, now); + dcp_report_swap_complete(dcp, swap_id, now); +} + +static void dcpep_cb_swap_complete(struct apple_dcp *dcp, + struct DCP_FW_NAME(dc_swap_complete_resp) *resp) +{ + dcp_swap_complete_id(dcp, resp->swap_id); } /* special */ @@ -3471,13 +3477,11 @@ static void dcp_swapped(struct apple_dcp *dcp, void *data, void *cookie) return; } if (dcp_is_ext26(dcp) && dcp->ext26_early_complete && dcp->ext26_early_id == swap_id) { - struct DCP_FW_NAME(dc_swap_complete_resp) completed = { .swap_id = swap_id }; - u64 received = dcp->ext26_rx_ns; dcp->ext26_early_complete = false; dcp->ext26_rx_ns = dcp->ext26_early_ns; - dcpep_cb_swap_complete(dcp, &completed); + dcp_swap_complete_id(dcp, swap_id); dcp->ext26_rx_ns = received; return; } From 6b64beeb861991394b0cdbfc3bfcc55b0f636bf9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:55:55 +1100 Subject: [PATCH 0545/1514] drm/apple: av: allocate the lifetime test's EPIC service av_lifetime_report_after_stop() keeps a struct apple_epic_service, pending-command table included, on the stack. Under KASAN that is a 2240-byte frame and a CONFIG_WERROR build fails. Allocate it with kunit_kzalloc() like the rest of the fixture (416 bytes). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/av-lifetime-test.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/av-lifetime-test.c b/drivers/gpu/drm/apple/av-lifetime-test.c index 1a466dfbbaca93..aead7bef1bd340 100644 --- a/drivers/gpu/drm/apple/av-lifetime-test.c +++ b/drivers/gpu/drm/apple/av-lifetime-test.c @@ -360,26 +360,29 @@ static void av_lifetime_quiesce_once_restart_once(struct kunit *test) static void av_lifetime_report_after_stop(struct kunit *test) { struct av_life_test *t = av_life_setup(test, av_life_owner_fn); - struct apple_epic_service svc = { }; + /* Off the stack: the service and its pending-command table are large. */ + struct apple_epic_service *svc = kunit_kzalloc(test, sizeof(*svc), GFP_KERNEL); struct epic_service_call call = { .group = cpu_to_le16(2), .command = cpu_to_le32(1), .magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC), }; + + KUNIT_ASSERT_NOT_NULL(test, svc); t->dcp->fw_compat = DCP_FIRMWARE_V_14_7; t->dcp->external_native = true; t->ep->dcp = t->dcp; - svc.ep = t->ep; - t->asrv->srv = &svc; + svc->ep = t->ep; + t->asrv->srv = svc; av_audiosrv_quiesce(t->dcp); av_audiosrv_quiesce(t->dcp); - av_audiosrv_report(&svc, 0, &call, sizeof(call)); + av_audiosrv_report(svc, 0, &call, sizeof(call)); KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 0); KUNIT_EXPECT_FALSE(test, work_busy(&t->asrv->terminate_wq)); av_audiosrv_reports_restart(t->dcp); - av_audiosrv_report(&svc, 0, &call, sizeof(call)); + av_audiosrv_report(svc, 0, &call, sizeof(call)); flush_work(&t->asrv->terminate_wq); KUNIT_EXPECT_EQ(test, atomic_read(&t->owner_runs), 1); av_audiosrv_quiesce(t->dcp); From 7663a8b04ed2bd380fe887c8357d9ad208b8fc19 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:55:56 +1100 Subject: [PATCH 0546/1514] drm/apple: drop the unused panel ADT test fixture Commit c7e3f37e7cb9 ("drm/apple: read the panel colour target from raw ADT") removed the only user of panel_test_adt, so a CONFIG_WERROR build of the parser tests fails on -Wunused-const-variable. Remove the array and keep panel_test_mode, which the tests still use. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-panel-test.h | 45 -------------------------- 1 file changed, 45 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-panel-test.h b/drivers/gpu/drm/apple/dcp-panel-test.h index 05d575d975fd50..0165d3999f93bb 100644 --- a/drivers/gpu/drm/apple/dcp-panel-test.h +++ b/drivers/gpu/drm/apple/dcp-panel-test.h @@ -1,49 +1,4 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -/* Synthetic J616s-shaped input: no /panel or /product/panel. */ -static const u8 panel_test_adt[] = { - 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x6e, 0x61, 0x6d, 0x65, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x64, 0x65, 0x76, 0x69, - 0x63, 0x65, 0x2d, 0x74, 0x72, 0x65, 0x65, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x00, 0x00, 0x00, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x00, - 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x2d, 0x69, 0x64, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, - 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x70, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x6c, 0x79, 0x2d, 0x6f, 0x63, 0x63, 0x6c, 0x75, 0x64, - 0x65, 0x64, 0x2d, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6e, 0x61, 0x6d, 0x65, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x61, 0x72, 0x6d, 0x2d, - 0x69, 0x6f, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, - 0x64, 0x69, 0x73, 0x70, 0x30, 0x00, 0x00, 0x00, 0x64, 0x69, 0x73, 0x70, - 0x6c, 0x61, 0x79, 0x2d, 0x74, 0x69, 0x6d, 0x69, 0x6e, 0x67, 0x2d, 0x69, - 0x6e, 0x66, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x6e, 0x61, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, - 0x63, 0x68, 0x6f, 0x73, 0x65, 0x6e, 0x00, 0x00, 0x73, 0x65, 0x72, 0x69, - 0x61, 0x6c, 0x2d, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x53, 0x59, 0x4e, 0x54, - 0x48, 0x45, 0x54, 0x49, 0x43, 0x2d, 0x4d, 0x41, 0x43, 0x48, 0x49, 0x4e, - 0x45, 0x00, 0x00, 0x00, -}; - /* Notch-hidden mode geometry observed through the public DRM interface. */ static const struct dcp_display_mode panel_test_mode = { .mode = { From 1630f31f1464c71bb3e9c9b50e45ba524cf46c80 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:18:30 +1100 Subject: [PATCH 0547/1514] nvmem: apple-efuses: add KUnit tests Add a suite for the Apple eFuse driver. Its nvmem read callback runs on a fuse range in kernel memory, directly and through a real nvmem device registered with the driver's callback and configuration: - word reads at every offset, runs of words, the whole range and its last word, a read with a partial tail, short reads, and that the read never writes the fuses; - reads through the nvmem device, which is read-only; - word cells, bit-field cells as the PHY calibration users read them, a cell in the last word and an unaligned cell. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/nvmem/Kconfig | 10 + drivers/nvmem/apple-efuses-test.c | 331 +++++++++++++++++++++++++ drivers/nvmem/apple-efuses.c | 4 + drivers/nvmem/apple-efuses.kunitconfig | 6 + 4 files changed, 351 insertions(+) create mode 100644 drivers/nvmem/apple-efuses-test.c create mode 100644 drivers/nvmem/apple-efuses.kunitconfig diff --git a/drivers/nvmem/Kconfig b/drivers/nvmem/Kconfig index c36c2a4c2a0b72..99ce966756a800 100644 --- a/drivers/nvmem/Kconfig +++ b/drivers/nvmem/Kconfig @@ -151,6 +151,16 @@ config NVMEM_APPLE_EFUSES This driver can also be built as a module. If so, the module will be called nvmem-apple-efuses. +config NVMEM_APPLE_EFUSES_KUNIT_TEST + bool "KUnit tests for the Apple eFuse driver" if !KUNIT_ALL_TESTS + depends on NVMEM_APPLE_EFUSES=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple eFuse driver: the nvmem read callback's + word reads, offsets and sizes against the fuse range, and word and + bit-field cell reads through a registered nvmem device. The fuses + are kernel memory, so the tests need no Apple hardware. + config NVMEM_APPLE_SPMI tristate "Apple SPMI NVMEM" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/nvmem/apple-efuses-test.c b/drivers/nvmem/apple-efuses-test.c new file mode 100644 index 00000000000000..c5474b13287f6f --- /dev/null +++ b/drivers/nvmem/apple-efuses-test.c @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC eFuse driver: the nvmem read callback's + * word reads, offsets and sizes against the fuse range, and reads through + * a real nvmem device registered with the driver's callback, including + * bit-field cells as the PHY calibration users read them. + * + * The fuse range is kernel memory, so the tests need no Apple hardware. + * + * Included by apple-efuses.c. + */ + +#include +#include +#include +#include + +/* Fuse range of the fake block, in words. */ +#define APPLE_EFUSES_TEST_WORDS 16 +#define APPLE_EFUSES_TEST_SIZE (APPLE_EFUSES_TEST_WORDS * sizeof(u32)) +/* The fake block is followed by guard words a read must never reach. */ +#define APPLE_EFUSES_TEST_GUARD 4 +/* Destination bytes a read has not written. */ +#define APPLE_EFUSES_TEST_POISON 0x5a + +struct apple_efuses_test { + struct apple_efuses_priv priv; + u32 *fuses; + struct device *dev; +}; + +static u32 apple_efuses_test_word(unsigned int i) +{ + return 0x10203040 + i * 0x01010101; +} + +static int apple_efuses_test_init(struct kunit *test) +{ + struct apple_efuses_test *ctx; + unsigned int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->fuses = kunit_kcalloc(test, APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD, + sizeof(u32), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->fuses); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + ctx->fuses[i] = cpu_to_le32(apple_efuses_test_word(i)); + for (; i < APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD; i++) + ctx->fuses[i] = cpu_to_le32(0xbad0bad0); + ctx->priv.fuses = (void __iomem __force *)ctx->fuses; + + return 0; +} + +/* One word at offset 0. */ +static void apple_efuses_test_read_word(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(0)); +} + +/* Each word at its own offset. */ +static void apple_efuses_test_read_each_offset(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + unsigned int i; + u32 val; + + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) { + val = 0; + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, i * sizeof(u32), + &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ_MSG(test, val, apple_efuses_test_word(i), "word %u", i); + } +} + +/* A multi-word read from an offset walks consecutive words. */ +static void apple_efuses_test_read_run(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[5]; + unsigned int i; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 3 * sizeof(u32), val, + sizeof(val)), 0); + for (i = 0; i < ARRAY_SIZE(val); i++) + KUNIT_EXPECT_EQ_MSG(test, val[i], apple_efuses_test_word(3 + i), "word %u", i); +} + +/* The whole range in one read, ending exactly at its last word. */ +static void apple_efuses_test_read_all(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[APPLE_EFUSES_TEST_WORDS + 1]; + unsigned int i; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, + APPLE_EFUSES_TEST_SIZE), 0); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + KUNIT_EXPECT_EQ_MSG(test, val[i], apple_efuses_test_word(i), "word %u", i); + /* Nothing written past the requested size. */ + KUNIT_EXPECT_EQ(test, val[APPLE_EFUSES_TEST_WORDS], 0x5a5a5a5aU); +} + +/* The last word of the range alone. */ +static void apple_efuses_test_read_last(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, APPLE_EFUSES_TEST_SIZE - 4, + &val, sizeof(val)), 0); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* + * The callback copies whole words only: a tail shorter than a word is not + * read or written, so the destination never overflows. The nvmem core + * rounds cell and sysfs reads to the 4-byte word size before it calls in. + */ +static void apple_efuses_test_partial_tail(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u8 val[12]; + u32 word; + + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 8, val, 6), 0); + memcpy(&word, val, sizeof(word)); + KUNIT_EXPECT_EQ(test, word, apple_efuses_test_word(2)); + KUNIT_EXPECT_EQ(test, val[4], APPLE_EFUSES_TEST_POISON); + KUNIT_EXPECT_EQ(test, val[5], APPLE_EFUSES_TEST_POISON); + KUNIT_EXPECT_EQ(test, val[6], APPLE_EFUSES_TEST_POISON); +} + +/* Reads of zero or fewer than four bytes write nothing and succeed. */ +static void apple_efuses_test_short_reads(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + size_t bytes; + u8 val[4]; + + for (bytes = 0; bytes < sizeof(u32); bytes++) { + memset(val, APPLE_EFUSES_TEST_POISON, sizeof(val)); + KUNIT_EXPECT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, bytes), 0); + KUNIT_EXPECT_MEMEQ(test, val, "\x5a\x5a\x5a\x5a", sizeof(val)); + } +} + +/* The fuses are read, never written. */ +static void apple_efuses_test_source_untouched(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + u32 val[APPLE_EFUSES_TEST_WORDS]; + unsigned int i; + + KUNIT_ASSERT_EQ(test, apple_efuses_read(&ctx->priv, 0, val, sizeof(val)), 0); + for (i = 0; i < APPLE_EFUSES_TEST_WORDS; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[i]), apple_efuses_test_word(i)); + for (; i < APPLE_EFUSES_TEST_WORDS + APPLE_EFUSES_TEST_GUARD; i++) + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[i]), 0xbad0bad0U); +} + +static struct nvmem_device *apple_efuses_test_register(struct kunit *test, + struct apple_efuses_test *ctx) +{ + /* as apple_efuses_probe(), with the fake range as the resource */ + struct nvmem_config config = { + .add_legacy_fixed_of_cells = true, + .read_only = true, + .reg_read = apple_efuses_read, + .stride = sizeof(u32), + .word_size = sizeof(u32), + .name = "apple_efuses_nvmem_test", + .id = NVMEM_DEVID_AUTO, + .root_only = true, + }; + struct nvmem_device *nvmem; + + ctx->dev = kunit_device_register(test, "apple-efuses-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + + config.dev = ctx->dev; + config.priv = &ctx->priv; + config.size = APPLE_EFUSES_TEST_SIZE; + + nvmem = devm_nvmem_register(ctx->dev, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + return nvmem; +} + +/* A registered device reports the fuse range and reads it through the driver. */ +static void apple_efuses_test_nvmem_read(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + u32 val[3]; + + KUNIT_EXPECT_EQ(test, nvmem_dev_size(nvmem), APPLE_EFUSES_TEST_SIZE); + + KUNIT_ASSERT_EQ(test, nvmem_device_read(nvmem, 0x14, sizeof(val), val), + (int)sizeof(val)); + KUNIT_EXPECT_EQ(test, val[0], apple_efuses_test_word(5)); + KUNIT_EXPECT_EQ(test, val[1], apple_efuses_test_word(6)); + KUNIT_EXPECT_EQ(test, val[2], apple_efuses_test_word(7)); + + KUNIT_ASSERT_EQ(test, nvmem_device_read(nvmem, APPLE_EFUSES_TEST_SIZE - 4, 4, val), 4); + KUNIT_EXPECT_EQ(test, val[0], apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* The device is read-only: a write is refused and leaves the fuses alone. */ +static void apple_efuses_test_nvmem_read_only(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + u32 val = 0x12345678; + + KUNIT_EXPECT_LT(test, nvmem_device_write(nvmem, 0, sizeof(val), &val), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(ctx->fuses[0]), apple_efuses_test_word(0)); +} + +/* + * An 8-bit field at bit 16 of a fuse word: the core reads the whole word + * through the driver, then shifts the field down to byte 0. + */ +static void apple_efuses_test_cell_byte(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "byte", + .offset = 0x8, + .bit_offset = 16, + .nbits = 8, + }; + u8 buf[4]; + + memset(buf, APPLE_EFUSES_TEST_POISON, sizeof(buf)); + /* bytes = DIV_ROUND_UP(16 + 8, 8), read as one 4-byte word */ + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, buf), 3); + KUNIT_EXPECT_EQ(test, buf[0], (u8)(apple_efuses_test_word(2) >> 16)); + KUNIT_EXPECT_EQ(test, buf[1], 0); + KUNIT_EXPECT_EQ(test, buf[2], 0); +} + +/* A bit field spanning two fuse words, as the PHY calibration cells use. */ +static void apple_efuses_test_cell_bits(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "bits", + .offset = 0x20, + .bit_offset = 26, + .nbits = 12, + }; + u64 both; + u8 buf[8]; + + memset(buf, APPLE_EFUSES_TEST_POISON, sizeof(buf)); + /* bytes = DIV_ROUND_UP(26 + 12, 8), read as two 4-byte words */ + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, buf), 5); + both = apple_efuses_test_word(8) | (u64)apple_efuses_test_word(9) << 32; + KUNIT_EXPECT_EQ(test, get_unaligned_le16(buf), (u16)((both >> 26) & GENMASK(11, 0))); +} + +/* A cell in the last fuse word reads it without touching what follows. */ +static void apple_efuses_test_cell_last_word(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "last", + .offset = APPLE_EFUSES_TEST_SIZE - 4, + .bytes = 4, + }; + u32 val = 0; + + KUNIT_ASSERT_EQ(test, nvmem_device_cell_read(nvmem, &info, &val), 4); + KUNIT_EXPECT_EQ(test, val, apple_efuses_test_word(APPLE_EFUSES_TEST_WORDS - 1)); +} + +/* The core refuses a cell that is not on the driver's 4-byte stride. */ +static void apple_efuses_test_cell_unaligned(struct kunit *test) +{ + struct apple_efuses_test *ctx = test->priv; + struct nvmem_device *nvmem = apple_efuses_test_register(test, ctx); + struct nvmem_cell_info info = { + .name = "unaligned", + .offset = 0x6, + .bytes = 2, + }; + u16 val = 0; + + KUNIT_EXPECT_EQ(test, nvmem_device_cell_read(nvmem, &info, &val), -EINVAL); +} + +static struct kunit_case apple_efuses_test_cases[] = { + KUNIT_CASE(apple_efuses_test_read_word), + KUNIT_CASE(apple_efuses_test_read_each_offset), + KUNIT_CASE(apple_efuses_test_read_run), + KUNIT_CASE(apple_efuses_test_read_all), + KUNIT_CASE(apple_efuses_test_read_last), + KUNIT_CASE(apple_efuses_test_partial_tail), + KUNIT_CASE(apple_efuses_test_short_reads), + KUNIT_CASE(apple_efuses_test_source_untouched), + KUNIT_CASE(apple_efuses_test_nvmem_read), + KUNIT_CASE(apple_efuses_test_nvmem_read_only), + KUNIT_CASE(apple_efuses_test_cell_byte), + KUNIT_CASE(apple_efuses_test_cell_bits), + KUNIT_CASE(apple_efuses_test_cell_last_word), + KUNIT_CASE(apple_efuses_test_cell_unaligned), + {} +}; + +static struct kunit_suite apple_efuses_test_suite = { + .name = "apple-efuses", + .init = apple_efuses_test_init, + .test_cases = apple_efuses_test_cases, +}; + +kunit_test_suite(apple_efuses_test_suite); diff --git a/drivers/nvmem/apple-efuses.c b/drivers/nvmem/apple-efuses.c index 9913e77b8ff067..7caf4e0f5c2434 100644 --- a/drivers/nvmem/apple-efuses.c +++ b/drivers/nvmem/apple-efuses.c @@ -79,3 +79,7 @@ module_platform_driver(apple_efuses_driver); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SoC eFuse driver"); MODULE_LICENSE("GPL"); + +#if IS_ENABLED(CONFIG_NVMEM_APPLE_EFUSES_KUNIT_TEST) +#include "apple-efuses-test.c" +#endif diff --git a/drivers/nvmem/apple-efuses.kunitconfig b/drivers/nvmem/apple-efuses.kunitconfig new file mode 100644 index 00000000000000..b2ced815094df8 --- /dev/null +++ b/drivers/nvmem/apple-efuses.kunitconfig @@ -0,0 +1,6 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/nvmem/apple-efuses.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_NVMEM=y +CONFIG_NVMEM_APPLE_EFUSES=y +CONFIG_NVMEM_APPLE_EFUSES_KUNIT_TEST=y From ebf58079178b9dda779ea9134fcb3a890071b7ea Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:18:31 +1100 Subject: [PATCH 0548/1514] backlight: apple_dwi: add KUnit tests Add a suite for the Apple DWI backlight driver. Its backlight ops run on a register block in kernel memory through a registered backlight device: - the brightness command word and send bits, levels at zero, at and above the maximum, and a level wider than the command field; - get_brightness() of what update_status() wrote, with the field masked and the type bits ignored, and that no other register is written; - blanking through bl_power and across suspend/resume, and turning the panel back on. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/video/backlight/Kconfig | 10 + drivers/video/backlight/apple_dwi_bl-test.c | 267 ++++++++++++++++++ drivers/video/backlight/apple_dwi_bl.c | 4 + .../video/backlight/apple_dwi_bl.kunitconfig | 8 + 4 files changed, 289 insertions(+) create mode 100644 drivers/video/backlight/apple_dwi_bl-test.c create mode 100644 drivers/video/backlight/apple_dwi_bl.kunitconfig diff --git a/drivers/video/backlight/Kconfig b/drivers/video/backlight/Kconfig index dbf4ca23a9b6d8..1868c84cc56fb2 100644 --- a/drivers/video/backlight/Kconfig +++ b/drivers/video/backlight/Kconfig @@ -336,6 +336,16 @@ config BACKLIGHT_APPLE_DWI To compile this driver as a module, choose M here: the module will be called apple_dwi_bl. +config BACKLIGHT_APPLE_DWI_KUNIT_TEST + bool "KUnit tests for the Apple DWI backlight driver" if !KUNIT_ALL_TESTS + depends on BACKLIGHT_APPLE_DWI=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple DWI backlight driver: the brightness + command word and send bits, reading the level back, the maximum, + and blanking through bl_power and suspend/resume. The registers + are kernel memory, so the tests need no Apple hardware. + config BACKLIGHT_QCOM_WLED tristate "Qualcomm PMIC WLED Driver" select REGMAP diff --git a/drivers/video/backlight/apple_dwi_bl-test.c b/drivers/video/backlight/apple_dwi_bl-test.c new file mode 100644 index 00000000000000..778a883f506b75 --- /dev/null +++ b/drivers/video/backlight/apple_dwi_bl-test.c @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: GPL-2.0 OR MIT +/* + * KUnit tests for the Apple DWI backlight driver: the brightness command + * encoding, the send bits, reading the brightness back from the command + * register, and blanking through bl_power and the backlight core's + * suspend/resume. + * + * A real backlight device is registered on a KUnit device with the driver's + * ops; its register block is kernel memory, so the tests need no Apple + * hardware. + * + * Included by apple_dwi_bl.c. + */ + +#include +#include + +#define DWI_BL_TEST_REGS 0x10 +/* What every register holds before the operation under test. */ +#define DWI_BL_TEST_FILL 0xdeadbeef +/* SEND1 | SEND2 | SEND3 | LE_DATA | SEND4 */ +#define DWI_BL_TEST_CTL_SEND 0x1071 + +struct dwi_bl_test { + struct apple_dwi_bl dwi_bl; + struct backlight_device *bl; + void *regs; +}; + +static u32 dwi_bl_test_reg(struct dwi_bl_test *ctx, unsigned int reg) +{ + return readl(ctx->dwi_bl.base + reg); +} + +static int dwi_bl_test_init(struct kunit *test) +{ + struct backlight_properties props = { + /* as dwi_bl_probe() */ + .type = BACKLIGHT_PLATFORM, + .max_brightness = DWI_BL_MAX_BRIGHTNESS, + .scale = BACKLIGHT_SCALE_LINEAR, + }; + struct dwi_bl_test *ctx; + struct device *dev; + unsigned int reg; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + ctx->regs = kunit_kzalloc(test, DWI_BL_TEST_REGS, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->dwi_bl.base = (void __iomem __force *)ctx->regs; + for (reg = 0; reg < DWI_BL_TEST_REGS; reg += sizeof(u32)) + writel(DWI_BL_TEST_FILL, ctx->dwi_bl.base + reg); + + dev = kunit_device_register(test, "apple-dwi-bl-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + ctx->bl = devm_backlight_device_register(dev, "apple-dwi-bl-test", dev, + &ctx->dwi_bl, &dwi_bl_ops, + &props); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->bl); + + return 0; +} + +static u32 dwi_bl_test_cmd(u32 brightness) +{ + return 0xa0000000 | brightness; +} + +/* The command word for a brightness: type 0xa in [31:28], level in [10:0]. */ +static void dwi_bl_test_encode(struct kunit *test) +{ + static const u32 levels[] = { 1, 2, 0x155, 0x2aa, 1023, 1024, 2046 }; + struct dwi_bl_test *ctx = test->priv; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(levels); i++) { + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, levels[i]), 0); + KUNIT_EXPECT_EQ_MSG(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), + dwi_bl_test_cmd(levels[i]), "level %u", levels[i]); + } +} + +/* Every update sets all five send bits, SEND4 (bit 12) included. */ +static void dwi_bl_test_send_bits(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 100), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* An update writes CTL and CMD and nothing beyond them. */ +static void dwi_bl_test_other_regs_untouched(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 7), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, 0x8), DWI_BL_TEST_FILL); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, 0xc), DWI_BL_TEST_FILL); +} + +/* The maximum is the full 11-bit level field. */ +static void dwi_bl_test_max(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, DWI_BL_MAX_BRIGHTNESS, (int)FIELD_MAX(DWI_BL_CMD_DATA)); + KUNIT_EXPECT_EQ(test, ctx->bl->props.max_brightness, 2047); + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 2047), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(2047)); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 2047); +} + +/* The core refuses a level above the maximum and the hardware keeps the last one. */ +static void dwi_bl_test_over_max(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 500), 0); + KUNIT_EXPECT_EQ(test, backlight_device_set_brightness(ctx->bl, 2048), -EINVAL); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(500)); + KUNIT_EXPECT_EQ(test, ctx->bl->props.brightness, 500); +} + +/* Brightness 0 is a real command, not a skipped write. */ +static void dwi_bl_test_zero(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 0), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* Every level written by update_status reads back through get_brightness. */ +static void dwi_bl_test_round_trip(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + u32 level; + + for (level = 0; level <= DWI_BL_MAX_BRIGHTNESS; level++) { + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, level), 0); + KUNIT_ASSERT_EQ_MSG(test, ctx->bl->ops->get_brightness(ctx->bl), level, + "level %u", level); + } +} + +/* get_brightness takes only the level field of the command register. */ +static void dwi_bl_test_get_masks_type(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + /* What the bootloader left: another type and junk above the field. */ + writel(0x5ffff800 | 0x3c4, ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 0x3c4); + + writel(0xfffff800, ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 0); + + writel(dwi_bl_test_cmd(2047), ctx->dwi_bl.base + DWI_BL_CMD); + KUNIT_EXPECT_EQ(test, dwi_bl_get_brightness(ctx->bl), 2047); +} + +/* A level above the field is truncated to it, never into the type nibble. */ +static void dwi_bl_test_field_overflow(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + /* Bypass the core's max check, as a caller writing props directly does. */ + ctx->bl->props.brightness = 0x800 | 0x12; + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD) & DWI_BL_CMD_TYPE, + 0xa0000000); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD) & ~DWI_BL_CMD_TYPE, + 0x12); +} + +/* bl_power off sends level 0 and keeps the set level; on sends it again. */ +static void dwi_bl_test_power_off_on(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 1200), 0); + + KUNIT_ASSERT_EQ(test, backlight_disable(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); + KUNIT_EXPECT_EQ(test, ctx->bl->props.brightness, 1200); + + writel(0, ctx->dwi_bl.base + DWI_BL_CTL); + KUNIT_ASSERT_EQ(test, backlight_enable(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(1200)); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CTL), DWI_BL_TEST_CTL_SEND); +} + +/* bl_power off alone (no fb blank state) also blanks. */ +static void dwi_bl_test_power_only(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 300), 0); + + mutex_lock(&ctx->bl->update_lock); + ctx->bl->props.power = BACKLIGHT_POWER_OFF; + mutex_unlock(&ctx->bl->update_lock); + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + /* A level set while off is kept but not sent. */ + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 400), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + mutex_lock(&ctx->bl->update_lock); + ctx->bl->props.power = BACKLIGHT_POWER_ON; + mutex_unlock(&ctx->bl->update_lock); + KUNIT_ASSERT_EQ(test, backlight_update_status(ctx->bl), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(400)); +} + +/* The driver asks the core to blank on suspend and restore on resume. */ +static void dwi_bl_test_suspend_resume(struct kunit *test) +{ + struct dwi_bl_test *ctx = test->priv; + const struct dev_pm_ops *pm = ctx->bl->dev.class->pm; + + KUNIT_EXPECT_TRUE(test, dwi_bl_ops.options & BL_CORE_SUSPENDRESUME); + + if (!IS_ENABLED(CONFIG_PM_SLEEP) || !pm || !pm->suspend || !pm->resume) + kunit_skip(test, "backlight class has no sleep ops (CONFIG_PM_SLEEP=n)"); + + KUNIT_ASSERT_EQ(test, backlight_device_set_brightness(ctx->bl, 900), 0); + + KUNIT_ASSERT_EQ(test, pm->suspend(&ctx->bl->dev), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(0)); + + KUNIT_ASSERT_EQ(test, pm->resume(&ctx->bl->dev), 0); + KUNIT_EXPECT_EQ(test, dwi_bl_test_reg(ctx, DWI_BL_CMD), dwi_bl_test_cmd(900)); +} + +static struct kunit_case dwi_bl_test_cases[] = { + KUNIT_CASE(dwi_bl_test_encode), + KUNIT_CASE(dwi_bl_test_send_bits), + KUNIT_CASE(dwi_bl_test_other_regs_untouched), + KUNIT_CASE(dwi_bl_test_max), + KUNIT_CASE(dwi_bl_test_over_max), + KUNIT_CASE(dwi_bl_test_zero), + KUNIT_CASE(dwi_bl_test_round_trip), + KUNIT_CASE(dwi_bl_test_get_masks_type), + KUNIT_CASE(dwi_bl_test_field_overflow), + KUNIT_CASE(dwi_bl_test_power_off_on), + KUNIT_CASE(dwi_bl_test_power_only), + KUNIT_CASE(dwi_bl_test_suspend_resume), + {} +}; + +static struct kunit_suite dwi_bl_test_suite = { + .name = "apple-dwi-bl", + .init = dwi_bl_test_init, + .test_cases = dwi_bl_test_cases, +}; + +kunit_test_suite(dwi_bl_test_suite); diff --git a/drivers/video/backlight/apple_dwi_bl.c b/drivers/video/backlight/apple_dwi_bl.c index 93bd744972d60a..8a280ab3a70fbe 100644 --- a/drivers/video/backlight/apple_dwi_bl.c +++ b/drivers/video/backlight/apple_dwi_bl.c @@ -121,3 +121,7 @@ module_platform_driver(dwi_bl_driver); MODULE_DESCRIPTION("Apple DWI Backlight Driver"); MODULE_AUTHOR("Nick Chan "); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_BACKLIGHT_APPLE_DWI_KUNIT_TEST) +#include "apple_dwi_bl-test.c" +#endif diff --git a/drivers/video/backlight/apple_dwi_bl.kunitconfig b/drivers/video/backlight/apple_dwi_bl.kunitconfig new file mode 100644 index 00000000000000..06e86f8a5d051c --- /dev/null +++ b/drivers/video/backlight/apple_dwi_bl.kunitconfig @@ -0,0 +1,8 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/video/backlight/apple_dwi_bl.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_BACKLIGHT_APPLE_DWI=y +CONFIG_BACKLIGHT_APPLE_DWI_KUNIT_TEST=y From fa152b667f914f962f1d864c51d962df8123a123 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:46:11 +1100 Subject: [PATCH 0549/1514] dmaengine: apple-admac: Do not keep the client's peripheral config pointer admac_device_config() saves the whole dma_slave_config so that a channel can be set up again after a system sleep took its registers. The copy includes peripheral_config, a pointer to memory the client only guarantees for the duration of the call: the AOP audio driver passes the address of a local variable. admac_restore_chan() then calls admac_device_config() on the saved copy and reads the realign frame size through that pointer again, long after the client returned. Split the register programming out into admac_program_config(), which the restore calls on the saved copy. admac_device_config() takes the frame size from the client's config once (it was assigned twice) and stores the copy with peripheral_config cleared, so a restore keeps the frame size the client configured and never touches the client's memory. Add a KUnit case that configures a capture channel, overwrites the client's frame size, marks the channel lost and restores it. Fixes: d9b438c4ca41 ("arm64: apple: support coordinated suspend-to-RAM on T8140") Signed-off-by: Ryan Murray --- drivers/dma/apple-admac-test.h | 54 ++++++++++++++++++++++++++++++++++ drivers/dma/apple-admac.c | 44 +++++++++++++++++---------- 2 files changed, 82 insertions(+), 16 deletions(-) diff --git a/drivers/dma/apple-admac-test.h b/drivers/dma/apple-admac-test.h index 24d390b9d6d5b1..26bb3472ea03e6 100644 --- a/drivers/dma/apple-admac-test.h +++ b/drivers/dma/apple-admac-test.h @@ -185,9 +185,63 @@ static void admac_realign_only_a_configured_capture(struct kunit *test) KUNIT_EXPECT_FALSE(test, admac_resume_realigns(&adchan)); } +/* + * The client's peripheral config is only valid while it configures the + * channel: a restore after a system sleep keeps the frame size taken then and + * does not read the client's memory again. + */ +static void admac_restore_keeps_the_frame_size(struct kunit *test) +{ + struct dma_slave_config config = {}; + struct admac_chan *adchan; + struct admac_data *ad; + void *regs; + u32 *frame; + + /* A capture channel (1) of a two-channel controller, its registers plain memory */ + ad = kunit_kzalloc(test, struct_size(ad, channels, 2), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ad); + ad->nchannels = 2; + regs = kunit_kzalloc(test, REG_CHAN_BASE(ad, 2), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, regs); + ad->base = (void __iomem *)regs; + adchan = &ad->channels[1]; + adchan->no = 1; + adchan->host = ad; + + frame = kunit_kzalloc(test, sizeof(*frame), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, frame); + *frame = 16; + + config.direction = DMA_DEV_TO_MEM; + config.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES; + config.src_port_window_size = 4; + config.peripheral_config = frame; + config.peripheral_size = sizeof(*frame); + KUNIT_ASSERT_EQ(test, admac_device_config(&adchan->chan, &config), 0); + KUNIT_EXPECT_EQ(test, adchan->realign_bytes, 16); + KUNIT_EXPECT_TRUE(test, adchan->cfg_valid); + KUNIT_EXPECT_NULL(test, adchan->cfg.peripheral_config); + KUNIT_EXPECT_EQ(test, adchan->cfg.peripheral_size, 0); + + /* The client's memory is reused, the channel's registers are lost */ + memset(frame, 0xa5, sizeof(*frame)); + writel_relaxed(0, ad->base + REG_BUS_WIDTH(ad, adchan->no)); + adchan->lost = true; + admac_restore_chan(adchan); + + KUNIT_EXPECT_FALSE(test, adchan->lost); + KUNIT_EXPECT_EQ(test, adchan->realign_bytes, 16); + KUNIT_EXPECT_NULL(test, adchan->cfg.peripheral_config); + /* The rest of the configuration is programmed again */ + KUNIT_EXPECT_EQ(test, readl_relaxed(ad->base + REG_BUS_WIDTH(ad, adchan->no)), + BUS_WIDTH_32BIT | BUS_WIDTH_FRAME_4_WORDS); +} + static struct kunit_case admac_realign_cases[] = { KUNIT_CASE(admac_realign_needs_a_frame_size), KUNIT_CASE(admac_realign_only_a_configured_capture), + KUNIT_CASE(admac_restore_keeps_the_frame_size), {} }; diff --git a/drivers/dma/apple-admac.c b/drivers/dma/apple-admac.c index cc57d9c76847e9..a42ba9559db11c 100644 --- a/drivers/dma/apple-admac.c +++ b/drivers/dma/apple-admac.c @@ -822,7 +822,8 @@ static void admac_reset_rings(struct admac_chan *adchan) writel_relaxed(0, ad->base + REG_CHAN_CTL(ad, adchan->no)); } -static int admac_device_config(struct dma_chan *chan, struct dma_slave_config *config); +static int admac_program_config(struct admac_chan *adchan, + const struct dma_slave_config *config); /* Registers can't be reached before a client powers the fabric, so this waits for it. */ static void admac_restore_chan(struct admac_chan *adchan) @@ -836,8 +837,9 @@ static void admac_restore_chan(struct admac_chan *adchan) if (ad->split_channels || ad->display) writel_relaxed(T8132_CTL_VAL, ad->base + REG_CTL); writel_relaxed(adchan->carveout, ad->base + REG_CHAN_SRAM_CARVEOUT(ad, adchan->no)); + /* The registers only: realign_bytes was taken when the client configured. */ if (adchan->cfg_valid) - admac_device_config(&adchan->chan, &adchan->cfg); + admac_program_config(adchan, &adchan->cfg); } /* @@ -1465,10 +1467,10 @@ static int admac_display_probe_control(struct admac_data *ad) return 0; } -static int admac_device_config(struct dma_chan *chan, - struct dma_slave_config *config) +/* Program a channel's registers from @config, a client's or the saved copy. */ +static int admac_program_config(struct admac_chan *adchan, + const struct dma_slave_config *config) { - struct admac_chan *adchan = to_admac_chan(chan); struct admac_data *ad = adchan->host; bool is_tx = admac_chan_direction(adchan->no) == DMA_MEM_TO_DEV; int wordsize = 0; @@ -1520,17 +1522,6 @@ static int admac_device_config(struct dma_chan *chan, writel_relaxed(bus_width, ad->base + REG_BUS_WIDTH(ad, adchan->no)); - adchan->realign_bytes = admac_config_realign_bytes(config); - - /* - * Optional: a u32 frame size in bytes, which a paused capture is - * restarted aligned to on resume (see admac_cyclic_realign()). - */ - if (config->peripheral_config && config->peripheral_size == sizeof(u32)) - adchan->realign_bytes = *(u32 *)config->peripheral_config; - else - adchan->realign_bytes = 0; - /* * By FIFOCTL_LIMIT we seem to set the maximal number of bytes allowed to be * held in controller's per-channel FIFO. Transfers seem to be triggered @@ -1549,7 +1540,28 @@ static int admac_device_config(struct dma_chan *chan, ad->base + REG_CHAN_FIFOCTL(ad, adchan->no)); } + return 0; +} + +static int admac_device_config(struct dma_chan *chan, + struct dma_slave_config *config) +{ + struct admac_chan *adchan = to_admac_chan(chan); + int ret; + + ret = admac_program_config(adchan, config); + if (ret) + return ret; + + /* + * The peripheral config is the client's memory and only valid during + * this call: take the frame size from it now and keep no pointer to it + * in the copy a restore programs the channel from. + */ + adchan->realign_bytes = admac_config_realign_bytes(config); adchan->cfg = *config; + adchan->cfg.peripheral_config = NULL; + adchan->cfg.peripheral_size = 0; adchan->cfg_valid = true; return 0; From c7e6527a587ff12701034ea85ce639d37d49fad7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:46:12 +1100 Subject: [PATCH 0550/1514] mfd: macsmc: Initialise the completions before the RTKit apple_smc_probe() initialised init_done and cmd_done only after the RTKit was initialised, woken and the SMC endpoint started. The receive callback is live from the RTKit's initialisation on, and it completes init_done for the first message on the SMC endpoint, so a message that arrives before the probe got that far completes a completion that is still all zeroes. Initialise both completions together with the mutex, the spinlock and the boot stage the receive callback checks, before the RTKit is initialised, in a helper, apple_smc_init_state(). Add a KUnit case that takes the first message with only that state set up. Fixes: e038d985c982 ("mfd: Add Apple Silicon System Management Controller") Signed-off-by: Ryan Murray --- drivers/mfd/macsmc-test.c | 26 ++++++++++++++++++++++++++ drivers/mfd/macsmc.c | 20 ++++++++++++++------ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/drivers/mfd/macsmc-test.c b/drivers/mfd/macsmc-test.c index 2dec0920f982dc..ce35b1a7f318f6 100644 --- a/drivers/mfd/macsmc-test.c +++ b/drivers/mfd/macsmc-test.c @@ -395,6 +395,31 @@ static void macsmc_port_reasons_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_smc_port_reasons_only(&ctx->smc, BIT_ULL(43))); } +/* + * The SMC's first message may come as soon as its endpoint is started: the + * state the probe sets up before the RTKit is enough to take it. + */ +static void macsmc_early_message_test(struct kunit *test) +{ + struct macsmc_test_context *ctx = test->priv; + struct resource sram = DEFINE_RES_MEM(0x10000, SMC_SHMEM_SIZE); + struct apple_smc *smc; + + smc = kunit_kzalloc(test, sizeof(*smc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, smc); + apple_smc_init_state(smc); + smc->sram = &sram; + smc->sram_base = (void __iomem *)ctx->shmem; + + KUNIT_EXPECT_EQ(test, smc->boot_stage, APPLE_SMC_BOOTING); + KUNIT_EXPECT_FALSE(test, completion_done(&smc->init_done)); + + KUNIT_EXPECT_TRUE(test, apple_smc_rtkit_recv_early(smc, SMC_ENDPOINT, sram.start)); + KUNIT_EXPECT_EQ(test, smc->boot_stage, APPLE_SMC_INITIALIZED); + KUNIT_EXPECT_TRUE(test, completion_done(&smc->init_done)); + KUNIT_EXPECT_PTR_EQ(test, smc->shmem.iomem, smc->sram_base); +} + static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_key_info_lock_test), KUNIT_CASE(macsmc_key_index_test), @@ -412,6 +437,7 @@ static struct kunit_case macsmc_parser_cases[] = { KUNIT_CASE(macsmc_lid_wake_test), KUNIT_CASE(macsmc_wake_reason_test), KUNIT_CASE(macsmc_port_reasons_test), + KUNIT_CASE(macsmc_early_message_test), {} }; diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index cb32577a3bf66a..f8deb3f4acfeca 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -635,6 +635,19 @@ static const struct apple_smc_wake_reason apple_smc_j714s_wake_reasons[] = { { 43, "USB2_plug" }, { 44, "USB2_wake" }, { 45, "aupo" }, { 48, "rtc" }, { } }; +/* + * The state the RTKit callbacks use. A message can arrive as soon as the + * RTKit is initialised, so this is set up before that. + */ +static void apple_smc_init_state(struct apple_smc *smc) +{ + mutex_init(&smc->mutex); + spin_lock_init(&smc->lock); + init_completion(&smc->init_done); + init_completion(&smc->cmd_done); + smc->boot_stage = APPLE_SMC_BOOTING; +} + static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -649,8 +662,7 @@ static int apple_smc_probe(struct platform_device *pdev) smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; - mutex_init(&smc->mutex); - spin_lock_init(&smc->lock); + apple_smc_init_state(smc); smc->dev = &pdev->dev; smc->saved_enabled = of_machine_is_compatible("apple,t6050") && (of_machine_is_compatible("apple,j714s") || @@ -672,7 +684,6 @@ static int apple_smc_probe(struct platform_device *pdev) if (IS_ERR(smc->rtk)) return dev_err_probe(dev, PTR_ERR(smc->rtk), "Failed to initialize RTKit"); - smc->boot_stage = APPLE_SMC_BOOTING; ret = apple_rtkit_wake(smc->rtk); if (ret) return dev_err_probe(dev, ret, "Failed to wake up SMC"); @@ -685,9 +696,6 @@ static int apple_smc_probe(struct platform_device *pdev) if (ret) return dev_err_probe(dev, ret, "Failed to start SMC endpoint"); - init_completion(&smc->init_done); - init_completion(&smc->cmd_done); - ret = apple_rtkit_send_message(smc->rtk, SMC_ENDPOINT, FIELD_PREP(SMC_MSG, SMC_MSG_INITIALIZE), NULL, false); if (ret) From 4bc3a3cc7f39b3f86f73ab3b92f5fc2783f0e740 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:55:42 +1100 Subject: [PATCH 0551/1514] iio: aop_motion: free the IIO device with the device's resources The triggered buffer and the trigger of each sensor are resources of the platform device, and the release of the triggered buffer reads the poll function and the buffer out of the IIO device. The IIO device, though, was freed when the driver's data was dropped, which the driver core does before it releases the resources of the device, both on unbind and when a probe fails after the buffer is set up. The buffer release then read an IIO device that was already freed. Hand the IIO device, its private data and the channel table it points to to the resources of the platform device, right after the allocation and before the trigger and the buffer are set up. Resources are released in reverse order, so the buffer and the trigger now go first and the IIO device last. Dropping the driver's data only unregisters the device. MotionIio::new() takes the bound device instead of the platform device, so that a KUnit test can run it on a faux device: the test checks that the private data of the IIO device is still there when the release of the device's resources begins and gone when it has ended. Signed-off-by: Ryan Murray --- drivers/iio/common/aop_sensors/aop_motion.rs | 234 +++++++++++++++++-- 1 file changed, 212 insertions(+), 22 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_motion.rs b/drivers/iio/common/aop_sensors/aop_motion.rs index fa72bce5dbecbd..1861aa2d8ead51 100644 --- a/drivers/iio/common/aop_sensors/aop_motion.rs +++ b/drivers/iio/common/aop_sensors/aop_motion.rs @@ -21,8 +21,8 @@ use core::{ use kernel::{ bindings, c_str, - device::{self, Core}, - module_platform_driver, new_mutex, new_spinlock, of, platform, + device::{self, Bound, Core}, + devres, module_platform_driver, new_mutex, new_spinlock, of, platform, prelude::*, soc::apple::aop::{EPICService, FakehidListener, FakehidRegistration, AOP}, sync::{ @@ -512,10 +512,40 @@ struct Spec { _p: PhantomPinned, } +/// Owns the IIO device and what it points to. +/// +/// It is handed to the platform device's resources right after the +/// allocation. Those are released in reverse order, so the IIO device is +/// freed after the trigger and the triggered buffer, whose release still +/// uses it, and after the driver's own data is gone. +struct IioAlloc { + dev: *mut bindings::iio_dev, + _spec: Pin>, +} + +impl Drop for IioAlloc { + fn drop(&mut self) { + // SAFETY: `self.dev` was allocated in `MotionIio::new()` with an + // `Arc` as its private data. `MotionIio` has unregistered it + // and the resources registered after this one are released, so + // nothing uses either after this. + unsafe { + drop(Arc::::from_foreign((*self.dev).priv_.cast())); + bindings::iio_device_free(self.dev); + } + } +} + +// SAFETY: The IIO device may be freed from any thread, and the channel +// table is only read. +unsafe impl Send for IioAlloc {} + /// The IIO device of a service, with its buffer. +/// +/// The device itself belongs to the platform device's resources, which are +/// released after the driver's data; this only takes it out of view again. struct MotionIio { dev: *mut bindings::iio_dev, - _spec: Pin>, registered: bool, } @@ -523,11 +553,10 @@ impl MotionIio { /// Allocates the device and its buffer; [`MotionIio::register`] makes it /// visible. fn new( - pdev: &platform::Device>, + dev: &device::Device, kind: &'static Kind, control: Arc, ) -> Result<(Self, Arc)> { - let dev = pdev.as_ref(); let spec = KBox::pin( Spec { channels: [ @@ -579,9 +608,20 @@ impl MotionIio { (*indio_dev).modes = bindings::INDIO_DIRECT_MODE as i32; (*indio_dev).available_scan_masks = SCAN_MASKS.as_ptr(); } + // From here the device, its private data and `spec` are freed with + // the resources of `dev`, also if this fails. It has to come before + // the trigger and the buffer: resources are released in reverse + // order, and the release of those two uses the IIO device. + devres::register( + dev, + IioAlloc { + dev: indio_dev, + _spec: spec, + }, + GFP_KERNEL, + )?; let this = Self { dev: indio_dev, - _spec: spec, registered: false, }; // The buffer fills as the AOP reports, so the trigger never fires. @@ -603,9 +643,9 @@ impl MotionIio { if trig.is_null() { return Err(ENOMEM); } - // SAFETY: `trig` was allocated above; it is unregistered and freed - // with the platform device's resources, after the IIO device that - // holds a reference to it. + // SAFETY: `trig` was allocated above; it is unregistered with the + // platform device's resources, before the IIO device is freed. The + // IIO device holds its own reference to it until then. let ret = unsafe { bindings::devm_iio_trigger_register(dev.as_raw(), trig) }; if ret < 0 { return Err(Error::from_errno(ret)); @@ -614,10 +654,11 @@ impl MotionIio { // here is dropped when the IIO device is released. unsafe { (*indio_dev).trig = bindings::iio_trigger_get(trig) }; // SAFETY: Both devices are valid. The buffer is released with the - // platform device's resources; the IIO device holds its own - // reference to it until it is freed. The poll function only stamps - // the time and completes the trigger; the report listener pushes the - // scans. The setup ops start the reports for the buffer. + // platform device's resources, before the IIO device, which that + // release reads the buffer and the poll function from. The poll + // function only stamps the time and completes the trigger; the + // report listener pushes the scans. The setup ops start the reports + // for the buffer. let ret = unsafe { bindings::devm_iio_triggered_buffer_setup_ext( dev.as_raw(), @@ -649,14 +690,11 @@ impl MotionIio { impl Drop for MotionIio { fn drop(&mut self) { - // SAFETY: `self.dev` was allocated in `new()` with an `Arc` - // as its private data, and nothing uses it after this. - unsafe { - if self.registered { - bindings::iio_device_unregister(self.dev); - } - drop(Arc::::from_foreign((*self.dev).priv_.cast())); - bindings::iio_device_free(self.dev); + if self.registered { + // SAFETY: `self.dev` was registered by `register()`. It is + // freed with the platform device's resources, which outlive + // this. + unsafe { bindings::iio_device_unregister(self.dev) }; } } } @@ -829,7 +867,7 @@ impl platform::Driver for IIOAopMotionDriver { let service = unsafe { *service }; let control = Control::new(dev, aop.clone(), service)?; - let (mut iio, state) = MotionIio::new(pdev, kind, control.clone())?; + let (mut iio, state) = MotionIio::new(dev, kind, control.clone())?; let listener = FakehidRegistration::new(aop, service, state)?; let pm = PmHook::new(control.clone())?; // Check once that the service takes the calibration and the interval, @@ -859,3 +897,155 @@ module_platform_driver! { license: "Dual MIT/GPL", alias: ["platform:iio_aop_motion"], } + +#[kunit_tests(iio_aop_motion)] +mod tests { + use super::*; + use kernel::{ + faux, + soc::apple::aop::{ReportListener, SourceRing}, + }; + + /// Stands in for the AOP core. The private data of the IIO device holds + /// the last reference to it once the test has dropped its own, so it + /// goes when that private data is freed, and notes that in `gone`. + struct FakeAop { + gone: Arc>, + } + + impl Drop for FakeAop { + fn drop(&mut self) { + self.gone.store(true, Relaxed); + } + } + + impl AOP for FakeAop { + fn epic_call(&self, _svc: &EPICService, _subtype: u16, _msg: &[u8]) -> Result { + Ok(0) + } + fn epic_call_ret( + &self, + _svc: &EPICService, + _subtype: u16, + _msg: &[u8], + _ret_len: usize, + ) -> Result<(u32, KVec)> { + Err(ENODEV) + } + fn add_fakehid_listener( + &self, + _svc: EPICService, + _listener: Arc, + ) -> Result<()> { + Err(ENODEV) + } + fn remove_fakehid_listener(&self, _svc: &EPICService) -> bool { + false + } + fn add_report_listener( + &self, + _svc: EPICService, + _subtype: u16, + _listener: Arc, + ) -> Result<()> { + Err(ENODEV) + } + fn remove_report_listener(&self, _svc: &EPICService, _subtype: u16) -> bool { + false + } + fn source_ring( + &self, + _dev: &device::Device, + _size: usize, + ) -> Result> { + Err(ENODEV) + } + fn bound_ring( + &self, + _dev: &device::Device, + _size: usize, + _bind: &mut dyn FnMut(u64, u64) -> Result<()>, + ) -> Result> { + Err(ENODEV) + } + fn remove(&self) {} + } + + /// A device resource registered after the IIO device is set up, so that + /// it is released first: it notes whether the IIO device's private data + /// was already freed when the release of the resources began. + struct ReleaseStart { + gone: Arc>, + ran: Arc>, + gone_before: Arc>, + } + + impl Drop for ReleaseStart { + fn drop(&mut self) { + self.gone_before.store(self.gone.load(Relaxed), Relaxed); + self.ran.store(true, Relaxed); + } + } + + /// The IIO device and its private data stay until the resources of the + /// parent device, among them the triggered buffer and the trigger, are + /// released; dropping `MotionIio`, as a failed probe and an unbind do + /// before that release, does not free them. + #[test] + fn iio_device_is_freed_with_the_device_resources() -> Result { + let gone = Arc::new(Atomic::new(false), GFP_KERNEL)?; + let ran = Arc::new(Atomic::new(false), GFP_KERNEL)?; + let gone_before = Arc::new(Atomic::new(false), GFP_KERNEL)?; + + let reg = faux::Registration::new(c"iio-aop-motion-kunit", None)?; + let fdev: &faux::Device = reg.as_ref(); + let dev: &device::Device = fdev.as_ref(); + let plain: &device::Device = dev; + let aop: Arc = Arc::new(FakeAop { gone: gone.clone() }, GFP_KERNEL)?; + let control = Arc::pin_init( + pin_init!(Control { + dev: plain.into(), + aop, + service: EPICService { + channel: 0, + endpoint: 0, + }, + packets: [KVec::new(), KVec::new(), KVec::new()], + stream <- new_mutex!(Stream::default()), + }), + GFP_KERNEL, + )?; + let (iio, state) = MotionIio::new(dev, &ACCEL, control.clone())?; + // The test's own reference keeps the memory of the IIO device valid + // whoever drops the allocation's reference, and whenever. + let indio_dev = iio.dev; + // SAFETY: `indio_dev` was just allocated and is live. + unsafe { bindings::get_device(&raw mut (*indio_dev).dev) }; + let started = devres::register( + dev, + ReleaseStart { + gone: gone.clone(), + ran: ran.clone(), + gone_before: gone_before.clone(), + }, + GFP_KERNEL, + ); + + drop(state); + drop(control); + drop(iio); + let gone_after_drop = gone.load(Relaxed); + // Unbinds the device, which releases its resources. + drop(reg); + let gone_after_release = gone.load(Relaxed); + // SAFETY: Drops the reference taken above. + unsafe { bindings::put_device(&raw mut (*indio_dev).dev) }; + + started?; + assert!(!gone_after_drop); + assert!(ran.load(Relaxed)); + assert!(!gone_before.load(Relaxed)); + assert!(gone_after_release); + Ok(()) + } +} From 6d16ae09a46537f0588dd12c5208a8a0cdb63c1b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:55:43 +1100 Subject: [PATCH 0552/1514] iio: aop_devmotion: write the whole buffer scan A scan is a quaternion and a timestamp: 24 bytes, which the 16-byte alignment of the quaternion rounds up to 32. The IIO core computes the same 32 bytes and copies them all into the buffer, but the last eight were padding of the scan structure, which nothing wrote. Make the tail a field and build the scan in one place that zeroes it, as the accelerometer, gyroscope and temperature drivers already do for their scans. Add a KUnit test that derives the scan size from the channels as the IIO core does, compares it with the structure, and checks that every byte after the timestamp of a freshly built scan is zero. Signed-off-by: Ryan Murray --- .../iio/common/aop_sensors/aop_devmotion.rs | 61 ++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_devmotion.rs b/drivers/iio/common/aop_sensors/aop_devmotion.rs index e392c1435bbd4d..8130bc4f73c2d0 100644 --- a/drivers/iio/common/aop_sensors/aop_devmotion.rs +++ b/drivers/iio/common/aop_sensors/aop_devmotion.rs @@ -69,11 +69,24 @@ struct Sample { valid: bool, } -/// One buffer scan. A quaternion is aligned like `IIO_DECLARE_QUATERNION()`. +/// One buffer scan. A quaternion is aligned like `IIO_DECLARE_QUATERNION()`, +/// which rounds the scan up to a multiple of its 16 bytes. The IIO core +/// copies all of that, so the tail is a field that is written, not padding. #[repr(C, align(16))] struct Scan { quat: [i32; 4], timestamp: i64, + pad: u64, +} + +impl Scan { + fn new(quat: [i32; 4], timestamp: i64) -> Self { + Self { + quat, + timestamp, + pad: 0, + } + } } fn le_u32(data: &[u8], at: usize) -> Option { @@ -258,7 +271,7 @@ impl State { *self.sample.lock() = Sample { quat, valid: true }; // SAFETY: The polling work is disabled before the IIO device is freed. let timestamp = unsafe { bindings::iio_get_time_ns(self.iio.0) }; - let scan = Scan { quat, timestamp }; + let scan = Scan::new(quat, timestamp); // SAFETY: `scan` contains the complete only data channel followed by // the timestamp, and the IIO core copies it synchronously. unsafe { bindings::iio_push_to_buffers(self.iio.0, ptr::from_ref(&scan).cast()) }; @@ -996,3 +1009,47 @@ module_platform_driver! { license: "Dual MIT/GPL", alias: ["platform:iio_aop_devmotion"], } + +#[kunit_tests(iio_aop_devmotion)] +mod tests { + use super::*; + use core::mem::MaybeUninit; + + /// The bytes the IIO core takes for a scan of `channels`, all enabled: + /// each element at a multiple of its size, a repeated one counted to the + /// next power of two, and the total a multiple of the largest, as + /// `iio_compute_scan_bytes()` lays them out. + fn scan_bytes(channels: &[bindings::iio_chan_spec]) -> usize { + let mut bytes = 0usize; + let mut largest = 1; + for chan in channels { + // SAFETY: The channels of this driver use the plain scan type. + let scan_type = unsafe { chan.__bindgen_anon_1.scan_type }; + let repeat = usize::from(scan_type.repeat.max(1)).next_power_of_two(); + let len = usize::from(scan_type.storagebits) / 8 * repeat; + bytes = bytes.next_multiple_of(len) + len; + largest = largest.max(len); + } + bytes.next_multiple_of(largest) + } + + #[test] + fn scan_is_written_in_full() { + let size = scan_bytes(&[quaternion_channel(), timestamp_channel()]); + assert_eq!(mem::size_of::(), size); + + let written = mem::size_of::<[i32; 4]>() + mem::size_of::(); + let mut slot = MaybeUninit::::uninit(); + // SAFETY: `slot` is valid for a write of one `Scan`, first of a byte + // pattern and then of a scan built as `State::publish()` builds it. + unsafe { + ptr::write_bytes(slot.as_mut_ptr(), 0xa5, 1); + slot.as_mut_ptr().write(Scan::new([1, 2, 3, 4], 5)); + } + for at in written..size { + // SAFETY: `at` is within `slot`, all of which was written above. + let byte = unsafe { slot.as_ptr().cast::().add(at).read_volatile() }; + assert_eq!(byte, 0); + } + } +} From 33f05ac891c96fe7bb61bde2c6fed3bc9050afb6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:47:40 +1100 Subject: [PATCH 0553/1514] drm/apple: afk: limit the compact replies waiting to be sent Every compact service call from the firmware gets a reply buffer of the call's size, which is queued on the endpoint's ordered transmit queue. A reply can wait there for transmit ring space for up to five seconds while the receive worker keeps taking calls, and nothing limits how many replies, or how many bytes of them, are queued in the meantime. A firmware that keeps calling while it does not drain its ring makes the queue grow without bound. Count the payload bytes of the replies that are queued and not yet sent, under the endpoint lock, and take a call only while its reply fits. The room is AFK_COMPACT_MESSAGE_MAX, the largest single message, which is also what the receive side holds in assembly: one call of any valid size is always taken when nothing is queued, and the short calls the display services receive stay far below it. A call beyond that is dropped with a rate-limited warning before its buffer is allocated and before the service handler runs, so it is not counted as a pending job either. The reply worker returns the room once the send has finished or failed, which covers the queue flush at teardown as well. A dropped call, like one whose reply buffer cannot be allocated, is never answered, which the firmware sees the same way as a reply that failed to send. With the coordinated sleep transport, mark the endpoint so that sleep does not proceed, as the reply worker already does for a failed send. Add a KUnit case that stalls the transmit queue, feeds calls until the room is used up and checks that later calls are dropped until the queue has drained, and that a dropped call holds off the coordinated sleep. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk-parser-test.c | 99 +++++++++++++++++++++++++ drivers/gpu/drm/apple/afk.c | 56 ++++++++++++-- drivers/gpu/drm/apple/afk.h | 2 + 3 files changed, 152 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/afk-parser-test.c b/drivers/gpu/drm/apple/afk-parser-test.c index c1a956a6616f14..99873d53329d1e 100644 --- a/drivers/gpu/drm/apple/afk-parser-test.c +++ b/drivers/gpu/drm/apple/afk-parser-test.c @@ -182,6 +182,104 @@ static void afk_compact_service_call_report_test(struct kunit *test) KUNIT_EXPECT_EQ(test, cap.pa, 0x3400); } +/* + * Replies to firmware calls wait on the endpoint's transmit queue. While it + * makes no progress, further calls are taken only as long as their replies + * fit the room of one message. + */ +struct compact_reply_gate { + struct work_struct work; + struct completion open; +}; + +static void compact_reply_gate_fn(struct work_struct *work) +{ + struct compact_reply_gate *gate = + container_of(work, struct compact_reply_gate, work); + + wait_for_completion(&gate->open); +} + +static int compact_call_count_cb(struct apple_epic_service *service, u16 group, + u32 command, const void *data, size_t size, + void *reply, size_t room) +{ + unsigned int *count = service->cookie; + + (*count)++; + return 0; +} + +static const struct apple_epic_service_ops compact_call_count_ops = { + .name = "compact-call-test", + .call_v2 = compact_call_count_cb, +}; + +static void afk_compact_call_reply_budget_test(struct kunit *test) +{ + /* Four calls of this size take all the room; the timestamp and sub-header precede. */ + const size_t payload_size = AFK_COMPACT_MESSAGE_MAX / 4; + const size_t wire_size = 16 + payload_size; + struct apple_dcp_afkep *ep = test->priv; + struct compact_reply_gate gate; + struct epic_compact_sub_hdr *sub; + struct epic_service_call *call; + unsigned int handled = 0, i; + u8 *wire; + + wire = kunit_kzalloc(test, wire_size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, wire); + sub = (void *)(wire + 8); + sub->category = 1; + sub->type = EPIC_SUBTYPE_STD_SERVICE; + call = (void *)((u8 *)(sub + 1) + sizeof(struct epic_compact_desc)); + call->command = cpu_to_le32(4); + call->data_len = cpu_to_le32(payload_size - sizeof(struct epic_compact_desc) - + sizeof(*call)); + call->magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC); + + ep->services[0].ops = &compact_call_count_ops; + ep->services[0].cookie = &handled; + ep->tx_wq = alloc_ordered_workqueue("afk-parser-test-tx", 0); + KUNIT_ASSERT_NOT_NULL(test, ep->tx_wq); + + /* The queue is ordered: nothing behind the gate runs until it opens. */ + INIT_WORK_ONSTACK(&gate.work, compact_reply_gate_fn); + init_completion(&gate.open); + queue_work(ep->tx_wq, &gate.work); + + /* A call left without a reply must hold off a coordinated sleep. */ + ep->dcp->v27_sleep_transport = true; + for (i = 0; i < 4; i++) + afk_recv_compact_message(ep, 1, wire, wire_size); + KUNIT_EXPECT_FALSE(test, ep->sleep_poisoned); + afk_recv_compact_message(ep, 1, wire, wire_size); + KUNIT_EXPECT_EQ(test, handled, 4U); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 4); + KUNIT_EXPECT_TRUE(test, ep->sleep_poisoned); + + /* A small call no longer fits either. */ + call->data_len = cpu_to_le32(0); + afk_recv_compact_message(ep, 1, wire, + 16 + sizeof(struct epic_compact_desc) + sizeof(*call)); + KUNIT_EXPECT_EQ(test, handled, 4U); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 4); + + /* The replies fail without a transmit ring, which frees their room. */ + complete(&gate.open); + flush_workqueue(ep->tx_wq); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 0); + + afk_recv_compact_message(ep, 1, wire, + 16 + sizeof(struct epic_compact_desc) + sizeof(*call)); + KUNIT_EXPECT_EQ(test, handled, 5U); + + destroy_workqueue(ep->tx_wq); + ep->tx_wq = NULL; + destroy_work_on_stack(&gate.work); + KUNIT_EXPECT_EQ(test, atomic_read(&ep->sleep_jobs), 0); +} + /* * Slot reuse for re-announced compact services. The firmware re-announces a * service under a fresh interface on every DP relink without closing the old @@ -341,6 +439,7 @@ static void afk_compact_cut_before_wildcard_test(struct kunit *test) static struct kunit_case afk_parser_cases[] = { KUNIT_CASE(afk_serialized_report_test), KUNIT_CASE(afk_compact_service_call_report_test), + KUNIT_CASE(afk_compact_call_reply_budget_test), KUNIT_CASE(afk_compact_header_test), KUNIT_CASE(afk_short_epic_test), KUNIT_CASE(afk_short_reply_test), diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 724a78c4bb93c6..c354ae19a01db8 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1116,6 +1116,43 @@ struct afk_compact_reply { u8 data[]; }; +/* + * Replies wait on the transmit queue for ring space that only the firmware + * frees, while the receive worker keeps taking calls, so what is queued + * needs a limit of its own. One message is at most AFK_COMPACT_MESSAGE_MAX + * bytes and the receive side assembles one at a time; the queued replies + * together get the same room. A reply is never larger than its call, so + * any single call fits when nothing else is queued, and the calls the + * firmware makes are a small fraction of that even in a burst. + */ +static bool afk_compact_reply_reserve(struct apple_dcp_afkep *ep, size_t size) +{ + guard(spinlock_irqsave)(&ep->lock); + if (size > AFK_COMPACT_MESSAGE_MAX || + ep->compact_reply_bytes > AFK_COMPACT_MESSAGE_MAX - size) + return false; + ep->compact_reply_bytes += size; + return true; +} + +static void afk_compact_reply_release(struct apple_dcp_afkep *ep, size_t size) +{ + guard(spinlock_irqsave)(&ep->lock); + ep->compact_reply_bytes -= size; +} + +/* + * A call that gets no reply leaves the firmware waiting on it, so a + * coordinated sleep must not run against it afterwards. + */ +static void afk_compact_call_unanswered(struct apple_dcp_afkep *ep) +{ + if (!ep->dcp->v27_sleep_transport) + return; + guard(spinlock_irqsave)(&ep->lock); + ep->sleep_poisoned = true; +} + static void afk_compact_reply_worker(struct work_struct *work) { struct afk_compact_reply *r = container_of(work, struct afk_compact_reply, work); @@ -1127,10 +1164,9 @@ static void afk_compact_reply_worker(struct work_struct *work) dev_err(r->ep->dcp->dev, "AFK[ep:%02x]: failed to reply to compact service call: %d\n", r->ep->endpoint, ret); - if (ret && r->ep->dcp->v27_sleep_transport) { - guard(spinlock_irqsave)(&r->ep->lock); - r->ep->sleep_poisoned = true; - } + if (ret) + afk_compact_call_unanswered(r->ep); + afk_compact_reply_release(r->ep, r->size); atomic_dec_return_release(&r->ep->sleep_jobs); kvfree(r); } @@ -1167,9 +1203,19 @@ static void afk_recv_handle_compact_call(struct apple_dcp_afkep *ep, group = le16_to_cpu(call->group); command = le32_to_cpu(call->command); + if (!afk_compact_reply_reserve(ep, payload_size)) { + dev_warn_ratelimited(ep->dcp->dev, + "AFK[ep:%02x]: too many replies queued, dropping compact service %u call %u:%u\n", + ep->endpoint, channel, group, command); + afk_compact_call_unanswered(ep); + return; + } r = kvzalloc(struct_size(r, data, payload_size), GFP_KERNEL); - if (!r) + if (!r) { + afk_compact_reply_release(ep, payload_size); + afk_compact_call_unanswered(ep); return; + } INIT_WORK(&r->work, afk_compact_reply_worker); r->ep = ep; r->channel = channel; diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index 28b31aee6c2e3f..e3fd2347493595 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -573,6 +573,8 @@ struct apple_dcp_afkep { bool compact_tx_desync; /* Replies to firmware calls, see afk_compact_reply_worker(). */ struct workqueue_struct *tx_wq; + /* Payload bytes of the replies queued there and not yet sent (lock). */ + size_t compact_reply_bytes; /* Accepted RX and queued replies, until each worker has returned. */ atomic_t sleep_jobs; struct mutex compact_tx_lock; From 7e8f0dce76e894b453e0c94f186a60393b349e71 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:23:30 +1100 Subject: [PATCH 0554/1514] drm/apple: audio: keep the DP audio domain while its DCP firmware runs A DCP that keeps its coprocessor running through a system sleep sets its wakeup path in its suspend, so genpd keeps its power domains on. The DP audio block that DCP firmware drives sits in a domain of its own, which the dp-audio device holds only while runtime-active: its late sleep callback suspends it, and genpd powers the domain off at noirq under the still running DCP firmware. On the Mac mini M2 (J473, macOS 27.2 firmware), once Linux has started the primary DCP, s2idle then hard-resets the machine almost every time (19 of 20 attempts, no log). The J473 is the M2 machine that enables the primary DCP's DP audio block; the external DCP's block, enabled on every M2, sits in a domain marked always-on. With the dp-audio device unbound, which leaves the domain held, the same kernel passes 5 of 5 sleeps in one boot; with appledrm not loaded, 4 of 4; and the production kernel, which never starts that DCP, 5 of 5. Hold the domain from the late callback when the linked DCP has set its wakeup path for this sleep, or has no driver bound (its firmware may still run, left by a boot stage or an earlier bind). Every device's .suspend has run by then, so the DCP's choice is known. The decision comes from the DCP's own sleep state and the OF graph link, not from the SoC or firmware version. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 565016dcd7a893..4066f6e4781e32 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -2071,6 +2071,37 @@ static __maybe_unused int dcpaud_system_suspend(struct device *dev) return 0; } +/* + * The DCP's firmware drives this block. A DCP that keeps its coprocessor + * running through a sleep keeps its own power domains for it (its suspend + * sets its wakeup path), and this block's domain must stay with them: + * cutting it at noirq under running DCP firmware resets the machine. A DCP + * device without a driver may still run firmware that a boot stage or an + * earlier bind left running, so its block is kept too. Every device's + * .suspend has run before this late phase, so the DCP's choice is known. + */ +static __maybe_unused int dcpaud_suspend_late(struct device *dev) +{ + struct device_node *endpoint, *dcp_node = NULL; + struct platform_device *dcp_pdev = NULL; + + endpoint = of_graph_get_endpoint_by_regs(dev->of_node, 0, 0); + if (endpoint) { + dcp_node = of_graph_get_remote_port_parent(endpoint); + of_node_put(endpoint); + } + if (dcp_node && of_device_is_available(dcp_node)) + dcp_pdev = of_find_device_by_node(dcp_node); + of_node_put(dcp_node); + if (dcp_pdev) { + if (!device_is_bound(&dcp_pdev->dev) || device_wakeup_path(&dcp_pdev->dev)) + device_set_wakeup_path(dev); + put_device(&dcp_pdev->dev); + } + + return pm_runtime_force_suspend(dev); +} + /* * Runtime PM stops in the late phase and comes back in the early one, so it * works through every device's .suspend and .resume. The display resumes @@ -2083,7 +2114,7 @@ static __maybe_unused int dcpaud_system_suspend(struct device *dev) static const struct dev_pm_ops dcpaud_pm_ops = { .prepare = pm_sleep_ptr(dcpaud_pm_prepare), SYSTEM_SLEEP_PM_OPS(dcpaud_system_suspend, NULL) - LATE_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) + LATE_SYSTEM_SLEEP_PM_OPS(dcpaud_suspend_late, pm_runtime_force_resume) RUNTIME_PM_OPS(dcpaud_suspend, dcpaud_resume, NULL) }; From 15ef01343c1dbb70b76af4f22e9edf0f01958b74 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:27:58 +1100 Subject: [PATCH 0555/1514] soc: apple: pmgr-misc: test the fabric controls apple-pmgr-misc has a suite for its DCS bandwidth voting only. Add one for the rest of the driver, on simulated registers and a test devicetree fragment: - the fabric and DCS p-states saved and restored across suspend, with and without the PMP, including keeping a choice the PMP made since; - the confirmed fabric raise, its timeout and retry, and fabric holds; - the idle fabric governor: lowering, each thing that blocks it, off, across sleep, and its parameter; prepare/complete; - the minimum p-states in the match table, and the devicetree lookup of the governor's bandwidth voters (by label; missing, disabled, without reg or label, duplicated) and of a PMP node that is not bound. The CPU frequency walk in apple_pmgr_cpus_at_min() is replaced by a KUnit static stub for these cases. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 12 + drivers/soc/apple/apple-pmgr-fabric-test.c | 709 ++++++++++++++++++ drivers/soc/apple/apple-pmgr-misc.c | 9 +- drivers/soc/apple/apple-pmgr-misc.kunitconfig | 9 + 4 files changed, 738 insertions(+), 1 deletion(-) create mode 100644 drivers/soc/apple/apple-pmgr-fabric-test.c create mode 100644 drivers/soc/apple/apple-pmgr-misc.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..d56ccc8619985c 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -90,6 +90,18 @@ config APPLE_PMGR_DCS_KUNIT_TEST Also verify that boot constraints and concurrent endpoints retain their votes, and that suspend restores the last confirmed request. +config APPLE_PMGR_FABRIC_KUNIT_TEST + bool "KUnit tests for the Apple PMGR fabric controls" if !KUNIT_ALL_TESTS + depends on KUNIT=y && APPLE_PMGR_MISC=y && OF_DYNAMIC && MFD_SYSCON + default KUNIT_ALL_TESTS + help + Test the fabric and DCS suspend and resume p-states with and + without PMP, the confirmed fabric raise and its timeout, fabric + holds, the idle fabric governor and its parameter, and the device + tree lookup of the governor's bandwidth voters, on simulated + registers and a test device tree fragment. No hardware is accessed; + only useful for kernel developers. + config APPLE_CLUSTER_PWRGATE bool "Apple SoC CPU cluster power gates" depends on OF diff --git a/drivers/soc/apple/apple-pmgr-fabric-test.c b/drivers/soc/apple/apple-pmgr-fabric-test.c new file mode 100644 index 00000000000000..4ba6524c648887 --- /dev/null +++ b/drivers/soc/apple/apple-pmgr-fabric-test.c @@ -0,0 +1,709 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the PMGR misc fabric controls: suspend/resume p-states + * with and without PMP, the confirmed fabric raise, holds, the idle fabric + * governor and its parameter, and the device tree lookup of its bandwidth + * voters. The fabric and DCS controls are words in kernel memory and the + * voters a regmap on a buffer; nothing touches MMIO. + */ + +#include +#include +#include + +#define PF_DEFAULT 0xa5000077 /* desired 7, actual 7, unknown upper bits */ +#define PF_VOTE_IDLE 0x0f /* target on, hardware gated: idle */ +#define PF_VOTE_BUSY 0xff + +struct pf_test { + struct apple_pmgr_misc misc; /* first: test->priv is both */ + u32 *fabric, *dcs; + u32 *votes; + bool cpus_min; + bool published; +}; + +static const struct regmap_config pf_vote_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = 0x1c, +}; + +static bool pf_fake_cpus_at_min(void) +{ + struct pf_test *f = kunit_get_current_test()->priv; + + return f->cpus_min; +} + +static int pf_test_init(struct kunit *test) +{ + struct apple_pmgr_misc *misc; + struct regmap *map; + struct pf_test *f; + unsigned int i; + + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + if (!f) + return -ENOMEM; + misc = &f->misc; + f->fabric = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); + f->dcs = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); + f->votes = kunit_kzalloc(test, 8 * sizeof(u32), GFP_KERNEL); + if (!f->fabric || !f->dcs || !f->votes) + return -ENOMEM; + misc->dev = kunit_device_register(test, "pmgr-fabric-test"); + if (IS_ERR(misc->dev)) + return PTR_ERR(misc->dev); + map = devm_regmap_init_mmio(misc->dev, (void __iomem *)f->votes, + &pf_vote_regmap_config); + if (IS_ERR(map)) + return PTR_ERR(map); + + /* t602x layout: plain read-modify-write of both desired fields. */ + writel(PF_DEFAULT, f->fabric); + writel(0xa5000099, f->dcs); + misc->devices[DEV_FABRIC].base = (void __iomem *)f->fabric; + misc->devices[DEV_FABRIC].active_state = 7; + misc->devices[DEV_FABRIC].suspend_state = SYS_DEV_PSTATE_SUSPEND; + misc->devices[DEV_DCS].base = (void __iomem *)f->dcs; + misc->devices[DEV_DCS].active_state = 9; + misc->devices[DEV_DCS].suspend_state = SYS_DEV_PSTATE_SUSPEND; + mutex_init(&misc->lock); + misc->fabric_now = 7; + INIT_DEFERRABLE_WORK(&misc->idle_work, apple_pmgr_idle_work); + INIT_DELAYED_WORK(&misc->idle_work_prompt, apple_pmgr_idle_work_prompt); + for (i = 0; i < ARRAY_SIZE(misc->votes); i++) { + f->votes[i] = PF_VOTE_IDLE; + misc->votes[i].regmap = map; + misc->votes[i].reg = i * sizeof(u32); + } + misc->voters_ok = true; + dev_set_drvdata(misc->dev, misc); + f->cpus_min = true; + test->priv = f; + kunit_activate_static_stub(test, apple_pmgr_cpus_at_min, pf_fake_cpus_at_min); + return 0; +} + +static void pf_test_exit(struct kunit *test) +{ + struct pf_test *f = test->priv; + + if (!f) + return; + cancel_delayed_work_sync(&f->misc.idle_work); + cancel_delayed_work_sync(&f->misc.idle_work_prompt); + WRITE_ONCE(idle_fabric_pstate, 0); + if (f->published) { + /* Pairs with the acquire in the driver's readers. */ + smp_store_release(&apple_pmgr_misc_inst, NULL); + } +} + +static void pf_publish(struct pf_test *f) +{ + f->published = true; + /* Pairs with the acquire in the driver's readers, as probe's release. */ + smp_store_release(&apple_pmgr_misc_inst, &f->misc); +} + +/* Fabric reported low by both fields, as after the governor lowered it. */ +static void pf_set_low(struct pf_test *f, u32 reg) +{ + writel(reg, f->fabric); + f->misc.fabric_now = 1; +} + +static void pf_suspend_resume_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + /* Only the desired field changes; readback and unknown bits stay. */ + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000091U); + misc->fabric_now = 1; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_suspend_absent_control_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* A control the device tree does not describe is skipped. */ + misc->devices[DEV_DCS].base = NULL; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); +} + +static void pf_pmp_suspend_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + misc->pmp_owned = true; + misc->pmp_sleep = true; + writel(0xa5000035, f->fabric); /* PMP chose fabric p-state 5 */ + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, misc->pmp_fabric, 5U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000031U); + /* DCS is PMP's: not lowered. */ + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000035U); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_pmp_resume_new_choice_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + misc->pmp_owned = true; + misc->pmp_sleep = true; + misc->pmp_fabric = 5; + /* PMP moved the fabric since suspend: its choice is kept. */ + writel(0xa5000033, f->fabric); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000033U); + + /* Without a fabric control only the bookkeeping happens. */ + misc->devices[DEV_FABRIC].base = NULL; + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); +} + +static void pf_raise_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Hardware already reports 7: the confirming poll succeeds at once. */ + pf_set_low(f, 0xa5000071); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_raise_timeout_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Actual never follows: report it and leave the state unconfirmed. */ + pf_set_low(f, 0xa5000011); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000017U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, U32_MAX); + + /* The next caller tries again rather than trusting fabric_now. */ + writel(0xa5000077, f->fabric); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 7U); +} + +static void pf_raise_skip_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Already at the boot p-state: no write, no poll. */ + writel(0xa5000013, f->fabric); + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000013U); + + /* PMP owns the fabric: delegate, never write. */ + pf_set_low(f, 0xa5000011); + misc->pmp_owned = true; + scoped_guard(mutex, &misc->lock) + KUNIT_EXPECT_EQ(test, apple_pmgr_raise_fabric(misc), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000011U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 1U); +} + +static void pf_hold_release_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* No instance yet: holds succeed and change nothing. */ + pf_set_low(f, 0xa5000071); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + + pf_publish(f); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + KUNIT_EXPECT_EQ(test, misc->holds, 1U); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), 0); + KUNIT_EXPECT_EQ(test, misc->holds, 2U); + apple_pmgr_fabric_release(); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); + + /* An unconfirmed raise is reported, but the hold stands. */ + pf_set_low(f, 0xa5000011); + KUNIT_EXPECT_EQ(test, apple_pmgr_fabric_hold(), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, misc->holds, 1U); + apple_pmgr_fabric_release(); + KUNIT_EXPECT_EQ(test, misc->holds, 0U); +} + +static void pf_voters_active_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + unsigned int i; + + /* Target on but gated by hardware is idle: only actual counts. */ + KUNIT_EXPECT_FALSE(test, apple_pmgr_voters_active(misc)); + for (i = 0; i < ARRAY_SIZE(misc->votes); i++) { + f->votes[i] = PF_VOTE_BUSY; + KUNIT_EXPECT_TRUE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = 0xf0; + KUNIT_EXPECT_TRUE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = 0xe0 | PF_VOTE_IDLE; + KUNIT_EXPECT_FALSE_MSG(test, apple_pmgr_voters_active(misc), "voter %u", i); + f->votes[i] = PF_VOTE_IDLE; + } + /* An unreadable voter counts as busy. */ + misc->votes[2].reg = 0x100; + KUNIT_EXPECT_TRUE(test, apple_pmgr_voters_active(misc)); +} + +static void pf_idle_lowers_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + WRITE_ONCE(idle_fabric_pstate, 1); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_EQ(test, misc->fabric_now, 1U); + /* While low, the prompt timer watches for new load. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&misc->idle_work_prompt)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* Already low: no second write. */ + writel(0xa5000011, f->fabric); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000011U); +} + +enum pf_blocker { + PF_HOLD, PF_DCS_BW, PF_VOTER, PF_CPU, PF_PMP, PF_NO_VOTERS, PF_IDLE_HIGH, + PF_BLOCKERS +}; + +static void pf_idle_blockers_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + unsigned int b; + + for (b = 0; b < PF_BLOCKERS; b++) { + WRITE_ONCE(idle_fabric_pstate, 1); + misc->holds = b == PF_HOLD; + misc->dcs_bw_active = b == PF_DCS_BW; + f->votes[1] = b == PF_VOTER ? PF_VOTE_BUSY : PF_VOTE_IDLE; + f->cpus_min = b != PF_CPU; + misc->pmp_owned = b == PF_PMP; + misc->voters_ok = b != PF_NO_VOTERS; + if (b == PF_IDLE_HIGH) + WRITE_ONCE(idle_fabric_pstate, 7); + pf_set_low(f, 0xa5000071); + + apple_pmgr_idle_eval(misc); + if (b == PF_PMP) { + /* PMP decides: neither lowered nor raised by us. */ + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + } else { + KUNIT_EXPECT_EQ_MSG(test, readl(f->fabric), PF_DEFAULT, "blocker %u", b); + KUNIT_EXPECT_EQ_MSG(test, misc->fabric_now, 7U, "blocker %u", b); + } + KUNIT_EXPECT_TRUE_MSG(test, delayed_work_pending(&misc->idle_work), + "blocker %u", b); + KUNIT_EXPECT_FALSE_MSG(test, delayed_work_pending(&misc->idle_work_prompt), + "blocker %u", b); + cancel_delayed_work_sync(&misc->idle_work); + } +} + +static void pf_idle_off_sleeping_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Governor off: raise to the boot state, no timer. */ + pf_set_low(f, 0xa5000071); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); + + /* Sleeping: the evaluation stops without touching the fabric. */ + WRITE_ONCE(idle_fabric_pstate, 1); + misc->sleeping = true; + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + pf_set_low(f, 0xa5000071); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), 0xa5000071U); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); +} + +static void pf_param_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("16", NULL), -EINVAL); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("one", NULL), -EINVAL); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 0U); + /* Before probe the value is only stored. */ + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("15", NULL), 0); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 15U); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); + + pf_publish(f); + /* + * Setting it runs the governor at once. The worker runs outside the + * test, without the CPU stub, so only that it ran is checked. + */ + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("1", NULL), 0); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 1U); + KUNIT_EXPECT_TRUE(test, flush_delayed_work(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* Clearing it stops the governor and raises the fabric. */ + pf_set_low(f, 0xa5000071); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work_prompt)); + + /* With PMP owning the fabric the governor cannot be enabled. */ + misc->pmp_owned = true; + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("1", NULL), -EBUSY); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate, 0U); + KUNIT_EXPECT_EQ(test, idle_fabric_pstate_set("0", NULL), 0); +} + +static void pf_prepare_complete_test(struct kunit *test) +{ + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + WRITE_ONCE(idle_fabric_pstate, 1); + pf_set_low(f, 0xa5000071); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + /* Raised before any device suspends, governor parked. */ + KUNIT_EXPECT_TRUE(test, misc->sleeping); + KUNIT_EXPECT_FALSE(test, misc->pmp_sleep); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); + + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_FALSE(test, misc->sleeping); + /* The governor restarts at once. */ + KUNIT_EXPECT_TRUE(test, flush_delayed_work(&misc->idle_work)); + cancel_delayed_work_sync(&misc->idle_work); + cancel_delayed_work_sync(&misc->idle_work_prompt); + + /* No fabric control: nothing to gate. */ + misc->devices[DEV_FABRIC].base = NULL; + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + KUNIT_EXPECT_FALSE(test, misc->sleeping); + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&misc->idle_work)); +} + +static void pf_match_data_test(struct kunit *test) +{ + const struct apple_pmgr_misc_hw *t600x = NULL, *t602x = NULL; + const struct of_device_id *id; + + for (id = apple_pmgr_misc_of_match; id->compatible[0]; id++) { + if (!strcmp(id->compatible, "apple,t6000-pmgr-misc")) + t600x = id->data; + else if (!strcmp(id->compatible, "apple,t6020-pmgr-misc")) + t602x = id->data; + } + KUNIT_ASSERT_NOT_NULL(test, t600x); + KUNIT_ASSERT_NOT_NULL(test, t602x); + KUNIT_EXPECT_EQ(test, t600x->dev_min_ps[DEV_FABRIC], 1U); + KUNIT_EXPECT_EQ(test, t600x->dev_min_ps[DEV_DCS], 7U); + KUNIT_EXPECT_EQ(test, t600x->dcs_valid_states, (u32)DCS_VALID_STATES_T600X); + KUNIT_EXPECT_EQ(test, t602x->dev_min_ps[DEV_FABRIC], 1U); + KUNIT_EXPECT_EQ(test, t602x->dev_min_ps[DEV_DCS], 1U); + /* No DCS state list: suspend uses the plain read-modify-write. */ + KUNIT_EXPECT_EQ(test, t602x->dcs_valid_states, 0U); +} + +/* + * Device tree voters. The pmgr node is created once and keeps a syscon + * entry for the whole boot (syscon entries cannot be removed), so it is + * never freed; each case adds and removes its own power-state children. + */ +static struct device_node *pf_dt_pmgr; +static u32 pf_dt_regs[0x50]; + +static const struct regmap_config pf_dt_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = sizeof(pf_dt_regs) - sizeof(u32), +}; + +struct pf_dt_child { + const char *name; + const char *label; /* NULL: no label property */ + u32 reg; /* 0: no reg property */ + bool disabled; + const char *compatible; /* NULL: apple,pmgr-pwrstate */ +}; + +static void pf_dt_apply(struct kunit *test, struct of_changeset *cs, + const struct pf_dt_child *c, unsigned int n) +{ + unsigned int i; + + of_changeset_init(cs); + for (i = 0; i < n; i++) { + const char *compatible = c[i].compatible ?: "apple,pmgr-pwrstate"; + struct device_node *np = of_changeset_create_node(cs, pf_dt_pmgr, c[i].name); + + KUNIT_ASSERT_NOT_NULL(test, np); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "compatible", + compatible), 0); + if (c[i].label) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "label", + c[i].label), 0); + if (c[i].reg) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32(cs, np, "reg", + c[i].reg), 0); + if (c[i].disabled) + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(cs, np, "status", + "disabled"), 0); + } + KUNIT_ASSERT_EQ(test, of_changeset_apply(cs), 0); +} + +static void pf_dt_revert(struct of_changeset *cs) +{ + of_changeset_revert(cs); + of_changeset_destroy(cs); +} + +static bool pf_dt_find(struct kunit *test, struct apple_pmgr_misc *misc, + const struct pf_dt_child *c, unsigned int n) +{ + struct of_changeset cs; + + memset(misc->votes, 0, sizeof(misc->votes)); + misc->voters_ok = false; + pf_dt_apply(test, &cs, c, n); + apple_pmgr_find_voters(misc); + pf_dt_revert(&cs); + return misc->voters_ok; +} + +static void pf_dt_voters_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@108", "disp0_sys", 0x108 }, + { "power-controller@110", "avd_sys", 0x110 }, + { "power-controller@118", "isp_sys", 0x118 }, + { "clock@120", "isp_sys", 0x120, false, "apple,t6000-clkgen" }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + struct regmap *map = syscon_node_to_regmap(pf_dt_pmgr); + + KUNIT_ASSERT_FALSE(test, IS_ERR(map)); + KUNIT_EXPECT_TRUE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); + /* Matched by label, in the order of apple_pmgr_fabric_voters. */ + KUNIT_EXPECT_EQ(test, misc->votes[0].reg, 0x100U); + KUNIT_EXPECT_EQ(test, misc->votes[1].reg, 0x110U); + KUNIT_EXPECT_EQ(test, misc->votes[2].reg, 0x118U); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[0].regmap, map); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[1].regmap, map); + KUNIT_EXPECT_PTR_EQ(test, misc->votes[2].regmap, map); + + /* The voters read through the parent's register map. */ + pf_dt_regs[0x110 / 4] = PF_VOTE_IDLE; + pf_dt_regs[0x118 / 4] = PF_VOTE_IDLE; + pf_dt_regs[0x100 / 4] = PF_VOTE_BUSY; + KUNIT_EXPECT_TRUE(test, apple_pmgr_voters_active(misc)); + pf_dt_regs[0x100 / 4] = PF_VOTE_IDLE; + KUNIT_EXPECT_FALSE(test, apple_pmgr_voters_active(misc)); +} + +static void pf_dt_voters_missing_test(struct kunit *test) +{ + struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@110", "avd_sys", 0x110 }, + { "power-controller@118", "isp_sys", 0x118 }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* Desktop without ISP: the governor must never lower. */ + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 2)); + KUNIT_EXPECT_NULL(test, misc->votes[2].regmap); + + c[2].disabled = true; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].disabled = false; + + c[2].reg = 0; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].reg = 0x118; + + c[2].label = NULL; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].label = "isp"; + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 3)); + c[2].label = "isp_sys"; + + KUNIT_EXPECT_TRUE(test, pf_dt_find(test, misc, c, 3)); + + /* With the voters missing the governor stays high. */ + misc->voters_ok = false; + WRITE_ONCE(idle_fabric_pstate, 1); + apple_pmgr_idle_eval(misc); + KUNIT_EXPECT_EQ(test, readl(f->fabric), PF_DEFAULT); +} + +static void pf_dt_voters_duplicate_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "power-controller@100", "gfx", 0x100 }, + { "power-controller@108", "gfx", 0x108 }, + { "power-controller@110", "avd_sys", 0x110 }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + + /* A second gfx node must not stand in for the missing isp_sys. */ + KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); + KUNIT_EXPECT_NOT_NULL(test, misc->votes[0].regmap); + KUNIT_EXPECT_NULL(test, misc->votes[2].regmap); +} + +static void pf_dt_pmp_unbound_test(struct kunit *test) +{ + static const struct pf_dt_child c[] = { + { "pmp", NULL, 0, false, "apple,t6000-pmp-v2" }, + }; + struct pf_test *f = test->priv; + struct apple_pmgr_misc *misc = &f->misc; + struct of_changeset cs; + + /* PMP described but no driver bound: sleep takes the path without it. */ + misc->pmp_owned = true; + pf_dt_apply(test, &cs, c, ARRAY_SIZE(c)); + KUNIT_EXPECT_EQ(test, apple_pmgr_misc_prepare(misc->dev), 0); + pf_dt_revert(&cs); + KUNIT_EXPECT_FALSE(test, misc->pmp_sleep); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_suspend_noirq(misc->dev), 0); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000091U); + KUNIT_ASSERT_EQ(test, apple_pmgr_misc_resume_noirq(misc->dev), 0); + apple_pmgr_misc_complete(misc->dev); + KUNIT_EXPECT_EQ(test, readl(f->dcs), 0xa5000099U); +} + +static int pf_suite_init(struct kunit_suite *suite) +{ + struct of_changeset cs; + struct device_node *box; + struct regmap *map; + int ret; + + if (!of_root) + return -ENODEV; + map = regmap_init_mmio(NULL, (void __iomem *)pf_dt_regs, &pf_dt_regmap_config); + if (IS_ERR(map)) + return PTR_ERR(map); + + /* + * Disabled container: nothing below it is populated as a device. The + * changeset is never reverted, see above. + */ + of_changeset_init(&cs); + box = of_changeset_create_node(&cs, of_root, "kunit-apple-pmgr-fabric"); + if (!box || of_changeset_add_prop_string(&cs, box, "status", "disabled")) + goto nomem; + pf_dt_pmgr = of_changeset_create_node(&cs, box, "power-management"); + if (!pf_dt_pmgr) + goto nomem; + ret = of_changeset_apply(&cs); + if (ret) + goto destroy; + return of_syscon_register_regmap(pf_dt_pmgr, map); + +nomem: + ret = -ENOMEM; +destroy: + of_changeset_destroy(&cs); + regmap_exit(map); + pf_dt_pmgr = NULL; + return ret; +} + +static struct kunit_case apple_pmgr_fabric_test_cases[] = { + KUNIT_CASE(pf_suspend_resume_test), + KUNIT_CASE(pf_suspend_absent_control_test), + KUNIT_CASE(pf_pmp_suspend_test), + KUNIT_CASE(pf_pmp_resume_new_choice_test), + KUNIT_CASE(pf_raise_test), + KUNIT_CASE(pf_raise_timeout_test), + KUNIT_CASE(pf_raise_skip_test), + KUNIT_CASE(pf_hold_release_test), + KUNIT_CASE(pf_voters_active_test), + KUNIT_CASE(pf_idle_lowers_test), + KUNIT_CASE(pf_idle_blockers_test), + KUNIT_CASE(pf_idle_off_sleeping_test), + KUNIT_CASE(pf_param_test), + KUNIT_CASE(pf_prepare_complete_test), + KUNIT_CASE(pf_match_data_test), + KUNIT_CASE(pf_dt_voters_test), + KUNIT_CASE(pf_dt_voters_missing_test), + KUNIT_CASE(pf_dt_voters_duplicate_test), + KUNIT_CASE(pf_dt_pmp_unbound_test), + {} +}; + +static struct kunit_suite apple_pmgr_fabric_test_suite = { + .name = "apple-pmgr-fabric", + .suite_init = pf_suite_init, + .init = pf_test_init, + .exit = pf_test_exit, + .test_cases = apple_pmgr_fabric_test_cases, +}; + +kunit_test_suite(apple_pmgr_fabric_test_suite); diff --git a/drivers/soc/apple/apple-pmgr-misc.c b/drivers/soc/apple/apple-pmgr-misc.c index 3912f45bb60d33..7c126e2845ebb6 100644 --- a/drivers/soc/apple/apple-pmgr-misc.c +++ b/drivers/soc/apple/apple-pmgr-misc.c @@ -22,7 +22,7 @@ #include #include #include -#if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) +#if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) || IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) #include #endif @@ -499,6 +499,9 @@ static bool apple_pmgr_cpus_at_min(void) unsigned int cpu; bool at_min = true; +#if IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_pmgr_cpus_at_min); +#endif for_each_online_cpu(cpu) { policy = cpufreq_cpu_get(cpu); if (!policy) @@ -849,3 +852,7 @@ module_platform_driver(apple_pmgr_misc_driver); #if IS_ENABLED(CONFIG_APPLE_PMGR_DCS_KUNIT_TEST) #include "apple-pmgr-dcs-test.c" #endif + +#if IS_ENABLED(CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST) +#include "apple-pmgr-fabric-test.c" +#endif diff --git a/drivers/soc/apple/apple-pmgr-misc.kunitconfig b/drivers/soc/apple/apple-pmgr-misc.kunitconfig new file mode 100644 index 00000000000000..e97c8ec17a7e8d --- /dev/null +++ b/drivers/soc/apple/apple-pmgr-misc.kunitconfig @@ -0,0 +1,9 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_OF_OVERLAY=y +CONFIG_PM=y +CONFIG_MFD_SYSCON=y +CONFIG_APPLE_PMGR_MISC=y +CONFIG_APPLE_PMGR_DCS_KUNIT_TEST=y +CONFIG_APPLE_PMGR_FABRIC_KUNIT_TEST=y From f4c58bb4b100449e89ef268ec26669a9d93f1670 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:28:00 +1100 Subject: [PATCH 0556/1514] reset: apple-cio: add KUnit tests Add a suite for the Apple CIO reset driver. The register is a regmap whose callbacks model each layout's request/busy/done handshake: - the deassert sequence of the t8103, t6000, t8142 and t6050 layouts: the bits written, waiting while busy, refusing while another port is busy, timeouts and write errors; - the match table, and the reset core's translation of ids, with ids past the number of ports refused and assert not supported; - a probe of a t6000 pmgr-child controller from a test devicetree fragment, and its failure without reg. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/reset/Kconfig | 12 + drivers/reset/reset-apple-cio-test.c | 655 ++++++++++++++++++++++ drivers/reset/reset-apple-cio.c | 4 + drivers/reset/reset-apple-cio.kunitconfig | 7 + 4 files changed, 678 insertions(+) create mode 100644 drivers/reset/reset-apple-cio-test.c create mode 100644 drivers/reset/reset-apple-cio.kunitconfig diff --git a/drivers/reset/Kconfig b/drivers/reset/Kconfig index 9579dd0528c48a..c25fdcd70c6dc0 100644 --- a/drivers/reset/Kconfig +++ b/drivers/reset/Kconfig @@ -33,6 +33,18 @@ config RESET_APPLE_CIO before the USB4/Thunderbolt host routers inside them can be brought up by the thunderbolt driver. +config RESET_APPLE_CIO_KUNIT_TEST + bool "KUnit tests for the Apple CIO reset driver" if !KUNIT_ALL_TESTS + depends on RESET_APPLE_CIO=y && KUNIT=y && OF_DYNAMIC + default KUNIT_ALL_TESTS + help + Run the deassert sequence of every CIO register layout against a + modelled request/busy register, including busy waits, timeouts and + write errors. Also probe a pmgr-child controller from a test device + tree fragment and check that the reset core refuses reset ids past + the number of ports. No hardware is accessed; only useful for kernel + developers. + config RESET_ASPEED tristate "ASPEED Reset Driver" depends on ARCH_ASPEED || COMPILE_TEST diff --git a/drivers/reset/reset-apple-cio-test.c b/drivers/reset/reset-apple-cio-test.c new file mode 100644 index 00000000000000..fde5b48c40ee29 --- /dev/null +++ b/drivers/reset/reset-apple-cio-test.c @@ -0,0 +1,655 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple CIO reset controller + * + * The CIO request register is a regmap whose read and write callbacks model + * the request/busy handshake described at the top of reset-apple-cio.c, so + * the real deassert sequences run without touching MMIO. A small device tree + * fragment under a disabled container exercises the pmgr-child probe path, + * the reset core's translation of reset ids and its refusal of ids past + * nr_resets. + */ + +#include +#include +#include +#include + +/* Phandles well above the ones QEMU and the DT compilers hand out. */ +#define CIO_TEST_PH_PROBE 0x00c10001 +#define CIO_TEST_PH_CORE 0x00c10002 +#define CIO_TEST_PH_NOREG 0x00c10003 +#define CIO_TEST_T6000_REG 0x1a034 + +/* + * One register with up to two timed transitions: after @left reads the value + * becomes @next, then after @left2 more reads it becomes @next2. A write runs + * the model's response to the request that was stored. + */ +struct cio_model { + u32 reg; + u32 val; + unsigned int left, left2; + u32 next, next2; + bool stuck; /* the current value never changes */ + void (*respond)(struct cio_model *m, u32 req); + int write_err; + unsigned int busy_reads; /* settle delay the response uses */ + unsigned int reads, writes, stray; + u32 last_write; + u32 val_at_write; /* register value seen by the write */ +}; + +static int cio_model_read(void *ctx, unsigned int reg, unsigned int *val) +{ + struct cio_model *m = ctx; + + if (reg != m->reg) { + m->stray++; + *val = 0; + return 0; + } + m->reads++; + *val = m->val; + if (m->stuck || !m->left) + return 0; + if (--m->left == 0) { + m->val = m->next; + m->left = m->left2; + m->next = m->next2; + m->left2 = 0; + } + return 0; +} + +static int cio_model_write(void *ctx, unsigned int reg, unsigned int val) +{ + struct cio_model *m = ctx; + + if (reg != m->reg) { + m->stray++; + return 0; + } + if (m->write_err) + return m->write_err; + m->writes++; + m->last_write = val; + m->val_at_write = m->val; + m->stuck = false; + m->left2 = 0; + if (m->respond) + m->respond(m, val); + return 0; +} + +/* t8103: request clears itself, busy while it runs, then only done is set. */ +static void cio_t8103_respond(struct cio_model *m, u32 req) +{ + m->val = req | T8103_CIO_CTRL_INIT_BUSY; + m->left = m->busy_reads; + m->next = T8103_CIO_CTRL_INIT_DONE; +} + +/* t6000/t8142: request bit N raises its busy bit, both clear when done. */ +static void cio_t6000_respond(struct cio_model *m, u32 req) +{ + u32 busy = req << 16; + + m->val |= req | busy; + m->left = m->busy_reads; + m->next = m->val & ~(req | busy); +} + +static void cio_t8142_respond(struct cio_model *m, u32 req) +{ + u32 busy = req << 1; + + m->val |= req | busy; + m->left = m->busy_reads; + m->next = m->val & ~(req | busy); +} + +/* t6050: request alone, then request and done, then both clear. */ +static void cio_t6050_respond(struct cio_model *m, u32 req) +{ + m->val |= req; + m->left = m->busy_reads; + m->next = m->val | (req << 1); + m->left2 = m->busy_reads; + m->next2 = m->val & ~(req | (req << 1)); +} + +static const struct regmap_config cio_test_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .reg_read = cio_model_read, + .reg_write = cio_model_write, +}; + +/* Model behind the syscon regmap of the DT fixture; reset by every case. */ +static struct cio_model cio_test_dt_model; +static struct regmap *cio_test_dt_regmap; +static struct of_changeset cio_test_cs; +static struct device_node *cio_test_pmgr, *cio_test_probe_np, *cio_test_core_np, + *cio_test_noreg_np, *cio_test_consumer; + +struct cio_test { + struct cio_model m; + struct device *dev; + struct apple_cio_reset priv; + struct platform_device *pdev; +}; + +static int cio_test_init(struct kunit *test) +{ + struct cio_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + if (!t) + return -ENOMEM; + t->dev = kunit_device_register(test, "apple-cio-reset-test"); + if (IS_ERR(t->dev)) + return PTR_ERR(t->dev); + t->priv.dev = t->dev; + t->priv.regmap = devm_regmap_init(t->dev, NULL, &t->m, &cio_test_regmap_config); + if (IS_ERR(t->priv.regmap)) + return PTR_ERR(t->priv.regmap); + mutex_init(&t->priv.lock); + t->priv.rcdev.ops = &apple_cio_reset_ops; + t->m.busy_reads = 3; + memset(&cio_test_dt_model, 0, sizeof(cio_test_dt_model)); + cio_test_dt_model.busy_reads = 3; + test->priv = t; + return 0; +} + +static void cio_test_exit(struct kunit *test) +{ + struct cio_test *t = test->priv; + + if (t && t->pdev) + of_platform_device_destroy(&t->pdev->dev, NULL); +} + +static void cio_test_setup(struct cio_test *t, const struct apple_cio_reset_variant *v, + u32 offset, u32 reg, + void (*respond)(struct cio_model *m, u32 req)) +{ + t->priv.variant = v; + t->priv.offset = offset; + t->priv.rcdev.nr_resets = v->nr_resets; + t->m.reg = reg; + t->m.respond = respond; +} + +static int cio_test_deassert(struct cio_test *t, unsigned long id) +{ + return t->priv.rcdev.ops->deassert(&t->priv.rcdev, id); +} + +static void cio_t8103_port_page_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + for (id = 0; id < apple_t8103_cio_reset.nr_resets; id++) { + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, + 0x84000 + id * T8103_CIO_CTRL_STRIDE, cio_t8103_respond); + t->m.val = 0; + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + /* A plain store of the request, not a read-modify-write. */ + KUNIT_EXPECT_EQ(test, t->m.last_write, T8103_CIO_CTRL_INIT_REQ); + KUNIT_EXPECT_EQ(test, t->m.val, T8103_CIO_CTRL_INIT_DONE); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t8103_plain_store_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + /* Unknown bits read back are not replayed into the request. */ + t->m.val = BIT(8) | BIT(31); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, T8103_CIO_CTRL_INIT_REQ); +} + +static void cio_t8103_waits_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.val = T8103_CIO_CTRL_INIT_BUSY; + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val_at_write & T8103_CIO_CTRL_INIT_BUSY, 0U); + KUNIT_EXPECT_EQ(test, t->m.val, T8103_CIO_CTRL_INIT_DONE); +} + +static void cio_t8103_busy_advisory_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* A reconfiguration that never finishes only warns before the request. */ + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.val = T8103_CIO_CTRL_INIT_BUSY; + t->m.stuck = true; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, T8103_CIO_CTRL_INIT_BUSY); +} + +static void cio_t8103_timeout_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8103_cio_reset, 0x84000, 0x84000, cio_t8103_respond); + t->m.busy_reads = 0; /* the response never settles */ + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + + /* Done must be the only bit set; anything else is not complete. */ + t->m.respond = NULL; + t->m.val = T8103_CIO_CTRL_INIT_DONE | BIT(5); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); +} + +static void cio_t6000_ports_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + for (id = 0; id < apple_t6000_cio_reset.nr_resets; id++) { + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(id)); + /* Returns only once request and busy cleared again. */ + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t6000_own_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.val = BIT(16 + 2); + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); +} + +static void cio_t6000_other_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* Another port's reconfiguration: store our request, keep its bits. */ + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.val = BIT(16 + 3); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(0)); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, (u32)BIT(16 + 3)); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)BIT(16 + 3)); +} + +static void cio_t6000_timeout_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.busy_reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); +} + +static void cio_t6000_write_error_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6000_cio_reset, CIO_TEST_T6000_REG, CIO_TEST_T6000_REG, + cio_t6000_respond); + t->m.write_err = -EIO; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), -EIO); + KUNIT_EXPECT_EQ(test, t->m.writes, 0U); + /* No polling for a request that was never stored. */ + KUNIT_EXPECT_EQ(test, t->m.reads, 1U); + KUNIT_EXPECT_FALSE(test, mutex_is_locked(&t->priv.lock)); +} + +static void cio_t8142_ports_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + /* The variant's own register: the generic offset is not used. */ + cio_test_setup(t, &apple_t8142_cio_reset, 0x1000, T8142_CIO_CTRL, cio_t8142_respond); + for (id = 0; id < apple_t8142_cio_reset.nr_resets; id++) { + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * id)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + } + KUNIT_EXPECT_EQ(test, t->m.writes, 4U); + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t8142_serializes_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* Any port busy holds back a request for every port. */ + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->m.val = BIT(2 * 3) | BIT(2 * 3 + 1); + t->m.left = 4; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(0)); +} + +static void cio_t8142_refuses_busy_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->m.val = BIT(2 * 1 + 1); + t->m.stuck = true; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 0U); + /* Request bits alone are not busy. */ + t->m.val = BIT(2 * 1); + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 2), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * 2)); +} + +static void cio_t6050_sequence_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + unsigned long id; + + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + for (id = 0; id < apple_t6050_cio_reset.nr_resets; id++) { + t->m.reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, id), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * id)); + /* Both transitions were waited for: request alone, then done. */ + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + KUNIT_EXPECT_EQ(test, t->m.left, 0U); + KUNIT_EXPECT_GE(test, t->m.reads, 1U + 2 * t->m.busy_reads); + } + KUNIT_EXPECT_EQ(test, t->m.stray, 0U); +} + +static void cio_t6050_port_mask_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + /* Own request still pending from before: wait for it to clear. */ + t->m.val = BIT(2 * 1) | BIT(2 * 1 + 1); + t->m.left = 3; + t->m.next = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 1), 0); + KUNIT_EXPECT_EQ(test, t->m.val_at_write, 0U); + + /* Another port's bits do not hold the request back. */ + t->m.val = BIT(2 * 3) | BIT(2 * 3 + 1); + t->m.writes = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), 0); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)(BIT(2 * 3) | BIT(2 * 3 + 1))); +} + +static void cio_t6050_no_done_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + + /* The request is never taken: done never shows up. */ + cio_test_setup(t, &apple_t6050_cio_reset, 0, 0x60, cio_t6050_respond); + t->m.busy_reads = 0; + KUNIT_EXPECT_EQ(test, cio_test_deassert(t, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + KUNIT_EXPECT_EQ(test, t->m.val, (u32)BIT(0)); +} + +static void cio_match_table_test(struct kunit *test) +{ + static const struct { + const char *compatible; + const struct apple_cio_reset_variant *v; + } rows[] = { + { "apple,t6050-cio-reset", &apple_t6050_cio_reset }, + { "apple,t8142-cio-reset", &apple_t8142_cio_reset }, + { "apple,t8103-cio-reset", &apple_t8103_cio_reset }, + { "apple,t6000-cio-reset", &apple_t6000_cio_reset }, + { "apple,t6030-cio-reset", &apple_t6000_cio_reset }, + }; + const struct of_device_id *id; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(rows); i++) { + for (id = apple_cio_reset_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, rows[i].compatible)) + break; + KUNIT_EXPECT_PTR_EQ_MSG(test, id->data, rows[i].v, "%s", rows[i].compatible); + } + KUNIT_EXPECT_EQ(test, apple_t8103_cio_reset.nr_resets, 2U); + KUNIT_EXPECT_TRUE(test, apple_t6000_cio_reset.pmgr_child); + KUNIT_EXPECT_FALSE(test, apple_t8142_cio_reset.pmgr_child); + KUNIT_EXPECT_FALSE(test, apple_t6050_cio_reset.pmgr_child); + KUNIT_EXPECT_EQ(test, apple_t6050_cio_reset.ctrl, 0x60U); + /* Only deassert: asserting needs the power domain cut. */ + KUNIT_EXPECT_NULL(test, apple_cio_reset_ops.assert); + KUNIT_EXPECT_NULL(test, apple_cio_reset_ops.reset); +} + +/* resets = <&probe 0>, <&probe 1>, <&probe 4>, <&core 3>, <&core 4>, <&noreg 0> */ +static void cio_core_xlate_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + struct reset_control *rc; + + cio_test_setup(t, &apple_t8142_cio_reset, 0, T8142_CIO_CTRL, cio_t8142_respond); + t->priv.rcdev.of_node = cio_test_core_np; + t->priv.rcdev.dev = t->dev; + KUNIT_ASSERT_EQ(test, devm_reset_controller_register(t->dev, &t->priv.rcdev), 0); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 3); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(rc), "get: %ld", PTR_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + KUNIT_EXPECT_EQ(test, t->m.last_write, (u32)BIT(2 * 3)); + KUNIT_EXPECT_EQ(test, t->m.val, 0U); + /* No .assert op: an exclusive assert cannot be honoured. */ + KUNIT_EXPECT_EQ(test, reset_control_assert(rc), -ENOTSUPP); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); + reset_control_put(rc); + + /* Id 4 is past the four ports. */ + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 4); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EINVAL)); + KUNIT_EXPECT_EQ(test, t->m.writes, 1U); +} + +static void cio_probe_pmgr_child_test(struct kunit *test) +{ + struct cio_model *m = &cio_test_dt_model; + struct cio_test *t = test->priv; + struct reset_control *rc; + + m->reg = CIO_TEST_T6000_REG; + m->respond = cio_t6000_respond; + t->pdev = of_platform_device_create(cio_test_probe_np, NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, t->pdev); + KUNIT_ASSERT_TRUE(test, device_is_bound(&t->pdev->dev)); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 1); + KUNIT_ASSERT_FALSE_MSG(test, IS_ERR(rc), "get: %ld", PTR_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + /* The offset came from "reg", the register map from the parent. */ + KUNIT_EXPECT_EQ(test, m->writes, 1U); + KUNIT_EXPECT_EQ(test, m->last_write, (u32)BIT(1)); + KUNIT_EXPECT_EQ(test, m->val, 0U); + KUNIT_EXPECT_EQ(test, m->stray, 0U); + reset_control_put(rc); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 0); + KUNIT_ASSERT_FALSE(test, IS_ERR(rc)); + KUNIT_EXPECT_EQ(test, reset_control_deassert(rc), 0); + KUNIT_EXPECT_EQ(test, m->last_write, (u32)BIT(0)); + reset_control_put(rc); + + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 2); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EINVAL)); + KUNIT_EXPECT_EQ(test, m->writes, 2U); +} + +static void cio_probe_no_reg_test(struct kunit *test) +{ + struct cio_test *t = test->priv; + struct reset_control *rc; + + t->pdev = of_platform_device_create(cio_test_noreg_np, NULL, NULL); + KUNIT_ASSERT_NOT_NULL(test, t->pdev); + KUNIT_EXPECT_FALSE(test, device_is_bound(&t->pdev->dev)); + /* No controller was registered for it. */ + rc = of_reset_control_get_exclusive_by_index(cio_test_consumer, 5); + KUNIT_EXPECT_PTR_EQ(test, rc, ERR_PTR(-EPROBE_DEFER)); + KUNIT_EXPECT_EQ(test, cio_test_dt_model.writes, 0U); +} + +static struct device_node *cio_test_node(struct device_node *parent, const char *name, + const char *compatible, u32 phandle) +{ + struct device_node *np = of_changeset_create_node(&cio_test_cs, parent, name); + + if (!np) + return NULL; + if (compatible && of_changeset_add_prop_string(&cio_test_cs, np, "compatible", + compatible)) + return NULL; + if (phandle && (of_changeset_add_prop_u32(&cio_test_cs, np, "phandle", phandle) || + of_changeset_add_prop_u32(&cio_test_cs, np, "#reset-cells", 1))) + return NULL; + return np; +} + +static int cio_test_suite_init(struct kunit_suite *suite) +{ + static const u32 resets[] = { + CIO_TEST_PH_PROBE, 0, CIO_TEST_PH_PROBE, 1, CIO_TEST_PH_PROBE, 4, + CIO_TEST_PH_CORE, 3, CIO_TEST_PH_CORE, 4, CIO_TEST_PH_NOREG, 0, + }; + struct device_node *box; + int ret; + + if (!of_root) + return -ENODEV; + cio_test_dt_regmap = regmap_init(NULL, NULL, &cio_test_dt_model, + &cio_test_regmap_config); + if (IS_ERR(cio_test_dt_regmap)) + return PTR_ERR(cio_test_dt_regmap); + + of_changeset_init(&cio_test_cs); + /* Disabled container: nothing below it is populated on its own. */ + box = cio_test_node(of_root, "kunit-apple-cio-reset", NULL, 0); + if (!box || of_changeset_add_prop_string(&cio_test_cs, box, "status", "disabled")) + goto nomem; + cio_test_pmgr = cio_test_node(box, "power-management", NULL, 0); + cio_test_probe_np = cio_test_node(cio_test_pmgr, "cio-reset@1a034", + "apple,t6000-cio-reset", CIO_TEST_PH_PROBE); + cio_test_noreg_np = cio_test_node(cio_test_pmgr, "cio-reset", + "apple,t6000-cio-reset", CIO_TEST_PH_NOREG); + cio_test_core_np = cio_test_node(box, "core-reset", NULL, CIO_TEST_PH_CORE); + cio_test_consumer = cio_test_node(box, "consumer", NULL, 0); + if (!cio_test_pmgr || !cio_test_probe_np || !cio_test_noreg_np || + !cio_test_core_np || !cio_test_consumer || + of_changeset_add_prop_u32(&cio_test_cs, cio_test_probe_np, "reg", + CIO_TEST_T6000_REG) || + of_changeset_add_prop_u32_array(&cio_test_cs, cio_test_consumer, "resets", + resets, ARRAY_SIZE(resets))) + goto nomem; + ret = of_changeset_apply(&cio_test_cs); + if (ret) + goto destroy; + /* + * A changeset attaches a node before adding its properties, so the + * "phandle" property is not picked up by the attach: set it here. + */ + cio_test_probe_np->phandle = CIO_TEST_PH_PROBE; + cio_test_noreg_np->phandle = CIO_TEST_PH_NOREG; + cio_test_core_np->phandle = CIO_TEST_PH_CORE; + /* + * A syscon entry cannot be removed, so the node it is keyed by keeps + * an extra reference and the register map stays: neither is freed. + */ + of_node_get(cio_test_pmgr); + ret = of_syscon_register_regmap(cio_test_pmgr, cio_test_dt_regmap); + if (ret) + of_changeset_revert(&cio_test_cs); + return ret; + +nomem: + ret = -ENOMEM; +destroy: + of_changeset_destroy(&cio_test_cs); + regmap_exit(cio_test_dt_regmap); + return ret; +} + +static void cio_test_suite_exit(struct kunit_suite *suite) +{ + of_changeset_revert(&cio_test_cs); +} + +static struct kunit_case apple_cio_reset_test_cases[] = { + KUNIT_CASE(cio_t8103_port_page_test), + KUNIT_CASE(cio_t8103_plain_store_test), + KUNIT_CASE(cio_t8103_waits_busy_test), + KUNIT_CASE(cio_t8103_busy_advisory_test), + KUNIT_CASE(cio_t8103_timeout_test), + KUNIT_CASE(cio_t6000_ports_test), + KUNIT_CASE(cio_t6000_own_busy_test), + KUNIT_CASE(cio_t6000_other_busy_test), + KUNIT_CASE(cio_t6000_timeout_test), + KUNIT_CASE(cio_t6000_write_error_test), + KUNIT_CASE(cio_t8142_ports_test), + KUNIT_CASE(cio_t8142_serializes_test), + KUNIT_CASE(cio_t8142_refuses_busy_test), + KUNIT_CASE(cio_t6050_sequence_test), + KUNIT_CASE(cio_t6050_port_mask_test), + KUNIT_CASE(cio_t6050_no_done_test), + KUNIT_CASE(cio_match_table_test), + KUNIT_CASE(cio_core_xlate_test), + KUNIT_CASE(cio_probe_pmgr_child_test), + KUNIT_CASE(cio_probe_no_reg_test), + {} +}; + +static struct kunit_suite apple_cio_reset_test_suite = { + .name = "apple-cio-reset", + .suite_init = cio_test_suite_init, + .suite_exit = cio_test_suite_exit, + .init = cio_test_init, + .exit = cio_test_exit, + .test_cases = apple_cio_reset_test_cases, +}; + +kunit_test_suite(apple_cio_reset_test_suite); diff --git a/drivers/reset/reset-apple-cio.c b/drivers/reset/reset-apple-cio.c index e5755ebb39affb..177b11b0bbffea 100644 --- a/drivers/reset/reset-apple-cio.c +++ b/drivers/reset/reset-apple-cio.c @@ -366,3 +366,7 @@ module_platform_driver(apple_cio_reset_driver); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple SoC CIO block reset driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_RESET_APPLE_CIO_KUNIT_TEST) +#include "reset-apple-cio-test.c" +#endif diff --git a/drivers/reset/reset-apple-cio.kunitconfig b/drivers/reset/reset-apple-cio.kunitconfig new file mode 100644 index 00000000000000..308c61595e8b1c --- /dev/null +++ b/drivers/reset/reset-apple-cio.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_OF_OVERLAY=y +CONFIG_RESET_CONTROLLER=y +CONFIG_RESET_APPLE_CIO=y +CONFIG_RESET_APPLE_CIO_KUNIT_TEST=y From 541e127d4fc2c18b510609ab52107c47e93fb683 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:28:10 +1100 Subject: [PATCH 0557/1514] cpufreq: apple-soc: KUnit: hold the node the fast-die case borrows cft_test_fast_die_init_described() takes a node from for_each_of_allnodes(), which holds no reference, and then drops one with of_node_put(): with OF_DYNAMIC that puts a live node one reference short. Take a reference for the time the case uses the node. cft_test_resume() also restores the global suspend flags only when it runs to the end; restore them from a KUnit action instead, so a failed assertion does not leave them changed for the cases after it. Signed-off-by: Ryan Murray --- drivers/cpufreq/apple-soc-cpufreq-test.c | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/drivers/cpufreq/apple-soc-cpufreq-test.c b/drivers/cpufreq/apple-soc-cpufreq-test.c index 9e356e385e083e..818caf75f302ed 100644 --- a/drivers/cpufreq/apple-soc-cpufreq-test.c +++ b/drivers/cpufreq/apple-soc-cpufreq-test.c @@ -806,13 +806,26 @@ static void cft_test_suspend_lazy(struct kunit *test) KUNIT_EXPECT_EQ(test, ctx->policy->cur, 600000); } +#ifdef CONFIG_SUSPEND +static void cft_restore_pm_flags(void *flags) +{ + pm_suspend_global_flags = *(unsigned int *)flags; +} +#endif + /* After a firmware-driven sleep the state the cluster woke in is adopted. */ static void cft_test_resume(struct kunit *test) { #ifdef CONFIG_SUSPEND struct cft_ctx *ctx = cft_setup(test, &soc_t6050_info, 4); struct apple_cpu_priv *priv = ctx->priv; - unsigned int flags = pm_suspend_global_flags; + unsigned int *flags; + + /* Put the global flags back even if an assertion ends the case. */ + flags = kunit_kmalloc(test, sizeof(*flags), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, flags); + *flags = pm_suspend_global_flags; + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, cft_restore_pm_flags, flags), 0); pm_suspend_clear_flags(); @@ -839,8 +852,6 @@ static void cft_test_resume(struct kunit *test) cft_set_cmd(ctx->regs, 9); KUNIT_EXPECT_EQ(test, apple_soc_cpufreq_resume(ctx->policy), 0); KUNIT_EXPECT_EQ(test, ctx->priv->expected_pstate, 4); - - pm_suspend_global_flags = flags; #else kunit_skip(test, "needs CONFIG_SUSPEND"); #endif @@ -1212,7 +1223,10 @@ static void cft_test_fast_die_init_described(struct kunit *test) struct apple_fast_die *fd; __be32 *value; - /* Any node with a phandle can stand in for the report node. */ + /* + * Any node with a phandle can stand in for the report node. The walk + * takes no reference: take one for the time the test uses the node. + */ for_each_of_allnodes(np) { if (np->phandle) { report = np; From c52ed9a394169f1e803fc9bcd791bb514c9dd2eb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:28:11 +1100 Subject: [PATCH 0558/1514] Input: apple_z2 - KUnit: check the bounded reports exactly The cases for a report whose finger count is beyond its records only checked that no more than the records present were reported. Check that exactly those are, so a bound that is too tight fails too. The oversized packet case now also checks the -EMSGSIZE return and that a dropped packet produces no events, and the test takes the receive buffer size from the driver. Say in the driver why an oversized packet is dropped unread. Signed-off-by: Ryan Murray --- drivers/input/touchscreen/apple_z2-test.c | 20 ++++++++++++++++---- drivers/input/touchscreen/apple_z2.c | 5 +++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/drivers/input/touchscreen/apple_z2-test.c b/drivers/input/touchscreen/apple_z2-test.c index 2d2d3ca0609a8a..61ee4f201e8f0c 100644 --- a/drivers/input/touchscreen/apple_z2-test.c +++ b/drivers/input/touchscreen/apple_z2-test.c @@ -17,7 +17,7 @@ #include /* Size of the receive buffer that apple_z2_probe() allocates */ -#define Z2_TEST_RX_SIZE 4000 +#define Z2_TEST_RX_SIZE APPLE_Z2_RX_BUF_SIZE /* * The test's receive buffer is much larger than the driver's, so that a read * with a hostile length stays inside the allocation and can be checked. @@ -714,7 +714,8 @@ static void z2_parse_count_beyond_report(struct kunit *test) if (z2_test_slot_of(ctx, i) >= 0) beyond++; KUNIT_EXPECT_EQ(test, beyond, 0); - KUNIT_EXPECT_LE(test, z2_test_active_slots(ctx), 3); + /* ...while the three records the report holds are all reported */ + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 3); } /* The report ends before the first finger record */ @@ -744,7 +745,8 @@ static void z2_parse_partial_record(struct kunit *test) z2_test_parse(ctx, 2, z2_test_msg_len(2) - 1); KUNIT_EXPECT_EQ(test, z2_test_slot_of(ctx, 2), -1); - KUNIT_EXPECT_LE(test, z2_test_active_slots(ctx), 1); + KUNIT_EXPECT_GE(test, z2_test_slot_of(ctx, 1), 0); + KUNIT_EXPECT_EQ(test, z2_test_active_slots(ctx), 1); } /* @@ -887,12 +889,22 @@ static void z2_read_oversize_length(struct kunit *test) unsigned int i; for (i = 0; i < ARRAY_SIZE(wire_lens); i++) { + /* The length the driver reads, as apple_z2_read_packet() rounds it */ + size_t pkt_len = (wire_lens[i] + 8) & ~3; + bool fits = pkt_len <= Z2_TEST_RX_SIZE; + z2_test_clear_log(ctx); z2_test_queue_packet(ctx, 0, wire_lens[i]); - apple_z2_read_packet(&ctx->z2); + KUNIT_EXPECT_EQ_MSG(test, apple_z2_read_packet(&ctx->z2), + fits ? 0 : -EMSGSIZE, + "length field %u", wire_lens[i]); KUNIT_EXPECT_LE_MSG(test, ctx->max_rx_len, (size_t)Z2_TEST_RX_SIZE, "length field %u", wire_lens[i]); + /* A dropped packet is not parsed */ + if (!fits) + KUNIT_EXPECT_EQ_MSG(test, ctx->nevents, 0, + "length field %u", wire_lens[i]); } } diff --git a/drivers/input/touchscreen/apple_z2.c b/drivers/input/touchscreen/apple_z2.c index aad5a9e465e4dc..32fde866a60d46 100644 --- a/drivers/input/touchscreen/apple_z2.c +++ b/drivers/input/touchscreen/apple_z2.c @@ -153,6 +153,11 @@ static int apple_z2_read_packet(struct apple_z2 *z2) return 0; pkt_len = (get_unaligned_le16(z2->rx_buf + 1) + 8) & 0xfffffffc; + /* + * No valid packet is this long. Drop it unread rather than read it in + * pieces: a controller that sends one is misbehaving, and touch input + * stopping is the safe outcome. + */ if (pkt_len > APPLE_Z2_RX_BUF_SIZE) { dev_warn_ratelimited(&z2->spidev->dev, "dropping oversized packet (%zu bytes)\n", From 182b72da006386645ca6c6d3b47cca71d099a46e Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 22 Nov 2026 22:32:02 -0500 Subject: [PATCH 0559/1514] drm/asahi: g18: propagate CLPC provider allocation failures apple_clpc_gpu_get() returns -ENOMEM when it cannot create the device link. Return that error to probe so that G18 does not bind with clock demand permanently disabled after an allocation failure. Assisted-by: OpenAI Codex Signed-off-by: Acelogic --- drivers/gpu/drm/asahi/g18/demand.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g18/demand.c b/drivers/gpu/drm/asahi/g18/demand.c index 4af04d3c48e58d..ed8bdfe4d8cd9c 100644 --- a/drivers/gpu/drm/asahi/g18/demand.c +++ b/drivers/gpu/drm/asahi/g18/demand.c @@ -54,7 +54,7 @@ int g18_demand_get(struct device *dev, struct g18_demand **out) int ret = apple_clpc_gpu_get(dev, &gpu); *out = NULL; - if (ret == -EPROBE_DEFER) + if (ret == -EPROBE_DEFER || ret == -ENOMEM) return ret; if (ret || !gpu) { if (ret) From 85730ab049e3fa178ab7618c1095aa09688c43f8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 13:06:35 +1100 Subject: [PATCH 0560/1514] ASoC: apple: aop_lpai: check the period range and the ring size of a format The low-power microphone takes its stream format and, on T6041, its ring geometry from properties of the AOP's audio service. The PCM limits are computed from the rate: the shortest period is PERIOD_MS_MIN of frames, and the most periods is the buffer limit divided by it. A rate that gives no whole frame in that time made the shortest period zero and the division one by zero, and a rate large enough overflowed the product; both stop the kernel when the PCM is opened. Compute the shortest period with checked arithmetic when the format is read, and refuse a format whose shortest period is empty or longer than the longest period the PCM offers. Such a format leaves the PCM out, as the other unusable formats do. The host ring was sized as frames times frame bytes with only a 4 GiB limit, and was allocated before the binding. Bound it by the ring's own format: at most RING_SECONDS_MAX (16) seconds of that format, four times the four seconds the firmware describes at any rate and channel count, and at most a fixed 64 MiB ceiling, which is above four seconds of the fastest format the PCM offers. Refuse a larger ring before anything is allocated, together with the report-interval checks that were already there, in one helper. Add KUnit cases for formats with and without a valid period range and for ring geometries on both sides of the time and byte limits, and for four seconds of every rate and channel count the ring takes. Signed-off-by: Ryan Murray --- sound/soc/apple/aop_lpai.rs | 135 +++++++++++++++++++++++++++++++++--- 1 file changed, 126 insertions(+), 9 deletions(-) diff --git a/sound/soc/apple/aop_lpai.rs b/sound/soc/apple/aop_lpai.rs index d218570a8b9992..d72627ecfac521 100644 --- a/sound/soc/apple/aop_lpai.rs +++ b/sound/soc/apple/aop_lpai.rs @@ -118,6 +118,14 @@ const PERIOD_MS_MIN: u32 = 10; const PERIOD_BYTES_MAX: usize = 0x10000; const BUFFER_BYTES_MAX: usize = 512 * 1024; const PERIODS_MIN: u32 = 2; +/// T6041: the longest host ring the driver allocates, in seconds of the +/// ring's own format. The firmware describes four seconds; the limit leaves +/// four times that, at any rate and channel count. +const RING_SECONDS_MAX: u64 = 16; +/// T6041: a ceiling on the ring whatever the format, above four seconds of +/// the fastest format the PCM offers ([`PERIOD_BYTES_MAX`] per +/// [`PERIOD_MS_MIN`]). +const RING_BYTES_MAX: usize = 64 << 20; /// Warning classes, one message per class and driver instance. const WARN_MALFORMED: usize = 0; @@ -319,6 +327,8 @@ impl StreamFormat { return None; } fmt.alsa_format()?; + // The PCM's period range must exist for the format. + fmt.period_bytes_min()?; Some(fmt) } @@ -326,6 +336,18 @@ impl StreamFormat { (self.channels * self.bytes_per_channel) as usize } + /// The bytes of the shortest period, [`PERIOD_MS_MIN`] of whole frames; + /// `None` when that is no frame at all or more than the longest period + /// ([`PERIOD_BYTES_MAX`]), so that the PCM would have no valid period. + fn period_bytes_min(&self) -> Option { + let frames = u64::from(self.rate).checked_mul(u64::from(PERIOD_MS_MIN))? / 1000; + let frame = self.channels.checked_mul(self.bytes_per_channel)?; + let bytes = frames.checked_mul(u64::from(frame))?; + usize::try_from(bytes) + .ok() + .filter(|b| (1..=PERIOD_BYTES_MAX).contains(b)) + } + /// Signed little-endian PCM of the container width. fn alsa_format(&self) -> Option { match self.bytes_per_channel { @@ -406,6 +428,26 @@ pub(crate) enum RingStep { Copy(usize), } +/// The bytes of a host ring of `frames` frames of `format` that reports its +/// producer every `quantum` frames; `None` for a geometry the driver does not +/// take: an empty ring, one longer than [`RING_SECONDS_MAX`] of the format or +/// larger than [`RING_BYTES_MAX`], or a report interval that is zero or more +/// than half the ring. +pub(crate) fn ring_geometry(format: &StreamFormat, frames: u64, quantum: u64) -> Option { + let frames_max = u64::from(format.rate).checked_mul(RING_SECONDS_MAX)?; + let frame_bytes = u64::try_from(format.frame_bytes()).ok()?; + let bytes = usize::try_from(frames.checked_mul(frame_bytes)?).ok()?; + if bytes == 0 + || frames > frames_max + || bytes > RING_BYTES_MAX + || quantum == 0 + || quantum > frames / 2 + { + return None; + } + Some(bytes) +} + pub(crate) fn ring_step(copied: Option, absolute: u64, ring_bytes: usize) -> RingStep { match copied { Some(c) if absolute >= c && ((absolute - c) as usize) < ring_bytes => { @@ -587,7 +629,8 @@ impl LpaiCapture { /// a node without one yields `Ok(None)`. /// /// The geometry is read before the binding so the ring has exactly the - /// size the firmware describes (frames times frame bytes). + /// size the firmware describes (frames times frame bytes); a ring beyond + /// [`ring_geometry`]'s limits is refused before anything is allocated. pub(crate) fn new_ring( bus: &device::Device, dev: &ARef, @@ -624,14 +667,10 @@ impl LpaiCapture { }; let frames = le_u64(&geo, GEOMETRY_RING_FRAMES).ok_or(EIO)?; let quantum = le_u64(&geo, GEOMETRY_REPORT_FRAMES).ok_or(EIO)?; - let ring_bytes = frames - .checked_mul(format.frame_bytes() as u64) - .filter(|b| *b > 0 && *b <= u64::from(u32::MAX)) - .ok_or(EIO)? as usize; - if quantum == 0 || quantum > frames / 2 { + let Some(ring_bytes) = ring_geometry(&format, frames, quantum) else { dev_err!(dev, "invalid lpai ring geometry: {} frames, {} per report\n", frames, quantum); return Err(EIO); - } + }; let ring = adata.bound_ring(bus, ring_bytes, &mut |iova, len| { let req = AudioSetDeviceProp::new( AUDIO_DEV_IO_BUFFER, @@ -784,8 +823,9 @@ impl LpaiCapture { } fn hw(&self) -> bindings::snd_pcm_hardware { - let frame = self.format.frame_bytes(); - let period_min = (self.format.rate * PERIOD_MS_MIN / 1000) as usize * frame; + // `StreamFormat::new` only yields formats with a minimum period in + // 1..=PERIOD_BYTES_MAX. + let period_min = self.format.period_bytes_min().unwrap_or(PERIOD_BYTES_MAX); bindings::snd_pcm_hardware { info: bindings::SNDRV_PCM_INFO_MMAP | bindings::SNDRV_PCM_INFO_MMAP_VALID @@ -1149,6 +1189,83 @@ mod tests { assert!(StreamFormat::parse(&p).is_none()); } + fn format(rate: u32, channels: u32, bytes: u32) -> [u8; 16] { + let mut p = [0u8; 16]; + p[0..4].copy_from_slice(&1u32.to_le_bytes()); + p[4..8].copy_from_slice(&rate.to_le_bytes()); + p[8..12].copy_from_slice(&channels.to_le_bytes()); + p[12..16].copy_from_slice(&bytes.to_le_bytes()); + p + } + + #[test] + fn a_format_without_a_valid_period_range_is_refused() { + let f = StreamFormat::parse(&format(16000, 3, 2)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(160 * 6)); + let f = StreamFormat::parse_ring(&format(16000, 3, 3)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(160 * 12)); + let f = StreamFormat::parse(&format(48000, 8, 4)).unwrap(); + assert_eq!(f.period_bytes_min(), Some(480 * 32)); + // The shortest period holds no frame. + assert!(StreamFormat::parse(&format(50, 3, 2)).is_none()); + assert!(StreamFormat::parse_ring(&format(50, 3, 3)).is_none()); + assert!(StreamFormat::parse(&format(99, 1, 2)).is_none()); + assert!(StreamFormat::parse(&format(100, 1, 2)).is_some()); + // The shortest period is longer than the longest. + assert!(StreamFormat::parse(&format(u32::MAX, 3, 2)).is_none()); + assert!(StreamFormat::parse_ring(&format(u32::MAX, 8, 3)).is_none()); + assert!(StreamFormat::parse(&format(0x2000_0000, 3, 2)).is_none()); + // Every period range the PCM offers is non-empty and in the buffer. + for rate in [100, 8000, 16000, 44100, 48000, 96000, 192000] { + for channels in 1..=8 { + for bytes in [2, 4] { + if let Some(f) = StreamFormat::parse(&format(rate, channels, bytes)) { + let min = f.period_bytes_min().unwrap(); + assert!(min >= f.frame_bytes() && min <= PERIOD_BYTES_MAX); + assert!(BUFFER_BYTES_MAX / min >= PERIODS_MIN as usize); + } + } + } + } + } + + #[test] + fn the_ring_geometry_is_bounded_by_its_format() { + // T6041: four seconds of 16 kHz, three 4-byte channels, 0.2 s reports. + let f = StreamFormat::parse_ring(&format(16000, 3, 4)).unwrap(); + assert_eq!(ring_geometry(&f, 64000, 3200), Some(768000)); + assert_eq!(ring_geometry(&f, 64000, 32000), Some(768000)); + assert_eq!(ring_geometry(&f, 64000, 32001), None); + assert_eq!(ring_geometry(&f, 64000, 0), None); + assert_eq!(ring_geometry(&f, 0, 0), None); + // Longer rings of the same format, up to the time limit. + assert_eq!(ring_geometry(&f, 16000 * 16, 3200), Some(16000 * 16 * 12)); + assert_eq!(ring_geometry(&f, 16000 * 16 + 1, 3200), None); + assert_eq!(ring_geometry(&f, 1 << 28, 3200), None); + assert_eq!(ring_geometry(&f, u64::from(u32::MAX) / 12, 3200), None); + assert_eq!(ring_geometry(&f, u64::MAX, 3200), None); + // Four seconds of other channel counts and rates are taken. + for rate in [8000, 16000, 24000, 32000, 44100, 48000, 96000, 192000] { + for channels in 1..=8 { + for bytes in [2, 3, 4] { + if let Some(f) = StreamFormat::parse_ring(&format(rate, channels, bytes)) { + let frames = u64::from(rate) * 4; + assert_eq!( + ring_geometry(&f, frames, frames / 20), + Some(frames as usize * f.frame_bytes()) + ); + } + } + } + } + // The byte ceiling holds near the fastest format the PCM offers. + let f = StreamFormat::parse_ring(&format(204800, 8, 4)).unwrap(); + assert!(ring_geometry(&f, 204800 * 10, 3200).is_some()); + assert_eq!(ring_geometry(&f, 204800 * 12, 3200), None); + // 10 ms of 204900 Hz is 2049 frames, a period above PERIOD_BYTES_MAX. + assert!(StreamFormat::parse_ring(&format(204900, 8, 4)).is_none()); + } + fn change(last_frame: u64, cursor: u64, property: u32) -> [u8; CHANGE_REPORT_MIN] { let mut r = [0u8; CHANGE_REPORT_MIN]; r[CHANGE_MAGIC..CHANGE_MAGIC + 4].copy_from_slice(&PROPERTY_CHANGE_MAGIC.to_le_bytes()); From 16930559199091aa1f83267934a31d5ac4e1455c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:33:37 +1100 Subject: [PATCH 0561/1514] tools/asahi: test the DP audio domain hold for a sleep Build the real dcpaud_suspend_late() and dcpaud_pm_ops from drivers/gpu/drm/apple/audio.c against stubs and run every combination of OF graph link, DCP device, bound driver, DCP wakeup path and runtime force-suspend result. The domain is held exactly when the linked DCP is on its own wakeup path or has no driver; every reference is dropped; pm_runtime_force_suspend() runs once and its result is returned; the late sleep slots carry the new callback. Four mutations (bound-only, leak-device, leak-node, invert-wakeup) and the code before the change must fail. Signed-off-by: Ryan Murray --- tools/asahi/dcpaud-sleep-hold-tests.c | 233 +++++++++++++++++++++++++ tools/asahi/dcpaud-sleep-hold-tests.py | 129 ++++++++++++++ tools/asahi/run-host-tests.py | 5 + 3 files changed, 367 insertions(+) create mode 100644 tools/asahi/dcpaud-sleep-hold-tests.c create mode 100755 tools/asahi/dcpaud-sleep-hold-tests.py diff --git a/tools/asahi/dcpaud-sleep-hold-tests.c b/tools/asahi/dcpaud-sleep-hold-tests.c new file mode 100644 index 00000000000000..1c50ae05d68975 --- /dev/null +++ b/tools/asahi/dcpaud-sleep-hold-tests.c @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * The actual dcp-dp-audio late sleep callback and dev_pm_ops against an OF + * graph and driver-core model that counts every node and device reference. + */ +#include +#include +#include +#include +#include + +/* The harness builds with -Wno-unused-function. */ +#define __maybe_unused +#define pm_sleep_ptr(fn) (fn) + +/* ACTUAL_PM_MACROS */ + +struct device_node { + int refs; + bool available; +}; + +struct device { + struct device_node *of_node; + int refs; + bool bound, wakeup_path, set_wakeup_path; +}; + +struct platform_device { + struct device dev; +}; + +struct dev_pm_ops { + int (*prepare)(struct device *dev); + int (*suspend)(struct device *dev); + int (*resume)(struct device *dev); + int (*freeze)(struct device *dev); + int (*thaw)(struct device *dev); + int (*poweroff)(struct device *dev); + int (*restore)(struct device *dev); + int (*suspend_late)(struct device *dev); + int (*resume_early)(struct device *dev); + int (*freeze_late)(struct device *dev); + int (*thaw_early)(struct device *dev); + int (*poweroff_late)(struct device *dev); + int (*restore_early)(struct device *dev); + int (*runtime_suspend)(struct device *dev); + int (*runtime_resume)(struct device *dev); + int (*runtime_idle)(struct device *dev); +}; + +/* The model: the dpaudio node, its endpoint, the DCP node and device. */ +static struct device_node audio_node, endpoint_node, dcp_node; +static struct platform_device dcp_pdev; +static struct device audio_dev = { .of_node = &audio_node }; +static bool have_endpoint, have_remote, have_pdev; +static int force_suspend_ret, force_suspend_calls, find_calls; + +static void get_node(struct device_node *np) +{ + assert(np->refs >= 0); + np->refs++; +} + +static void of_node_put(struct device_node *np) +{ + if (!np) + return; + assert(np == &endpoint_node || np == &dcp_node); + assert(np->refs > 0); + np->refs--; +} + +static struct device_node *of_graph_get_endpoint_by_regs(const struct device_node *parent, + int port, int reg) +{ + assert(parent == &audio_node && port == 0 && reg == 0); + if (!have_endpoint) + return NULL; + get_node(&endpoint_node); + return &endpoint_node; +} + +static struct device_node *of_graph_get_remote_port_parent(const struct device_node *np) +{ + assert(np == &endpoint_node && endpoint_node.refs > 0); + if (!have_remote) + return NULL; + get_node(&dcp_node); + return &dcp_node; +} + +static bool of_device_is_available(const struct device_node *np) +{ + assert(np == &dcp_node && dcp_node.refs > 0); + return np->available; +} + +static struct platform_device *of_find_device_by_node(struct device_node *np) +{ + assert(np == &dcp_node && dcp_node.refs > 0); + find_calls++; + if (!have_pdev) + return NULL; + dcp_pdev.dev.refs++; + return &dcp_pdev; +} + +static void put_device(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->refs > 0); + dev->refs--; +} + +static bool device_is_bound(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->refs > 0); + return dev->bound; +} + +static bool device_wakeup_path(struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->refs > 0); + return dev->wakeup_path; +} + +static void device_set_wakeup_path(struct device *dev) +{ + assert(dev == &audio_dev); + dev->set_wakeup_path = true; +} + +static int pm_runtime_force_suspend(struct device *dev) +{ + assert(dev == &audio_dev); + force_suspend_calls++; + return force_suspend_ret; +} + +static int pm_runtime_force_resume(struct device *dev) +{ + (void)dev; + return 0; +} + +/* The rest of the driver's callbacks only have to be distinct symbols. */ +static int dcpaud_pm_prepare(struct device *dev) +{ + (void)dev; + return 1; +} + +static int dcpaud_system_suspend(struct device *dev) +{ + (void)dev; + return 2; +} + +static int dcpaud_suspend(struct device *dev) +{ + (void)dev; + return 3; +} + +static int dcpaud_resume(struct device *dev) +{ + (void)dev; + return 4; +} + +/* ACTUAL_FUNCTION */ + +/* ACTUAL_PM_OPS */ + +int main(void) +{ + unsigned int cases = 0, held = 0; + + for (unsigned int bits = 0; bits < 128; bits++) { + bool expect; + int ret; + + have_endpoint = bits & 1; + have_remote = bits & 2; + dcp_node.available = bits & 4; + have_pdev = bits & 8; + dcp_pdev.dev.bound = bits & 16; + dcp_pdev.dev.wakeup_path = bits & 32; + force_suspend_ret = bits & 64 ? -EBUSY : 0; + endpoint_node.refs = dcp_node.refs = dcp_pdev.dev.refs = 0; + audio_dev.set_wakeup_path = false; + force_suspend_calls = find_calls = 0; + + /* The PM core calls the late slot for every system sleep. */ + ret = dcpaud_pm_ops.suspend_late(&audio_dev); + + expect = have_endpoint && have_remote && dcp_node.available && have_pdev && + (!dcp_pdev.dev.bound || dcp_pdev.dev.wakeup_path); + if (audio_dev.set_wakeup_path != expect) + fprintf(stderr, "case %#x: wakeup path %d, expected %d\n", bits, + audio_dev.set_wakeup_path, expect); + assert(audio_dev.set_wakeup_path == expect); + /* Every reference taken is dropped, whatever the topology. */ + assert(!endpoint_node.refs && !dcp_node.refs && !dcp_pdev.dev.refs); + /* An unavailable or missing DCP node is never looked up. */ + if (!(have_endpoint && have_remote && dcp_node.available)) + assert(!find_calls); + /* The runtime PM force-suspend always runs and its result is returned. */ + assert(force_suspend_calls == 1); + assert(ret == force_suspend_ret); + held += expect; + cases++; + } + + /* The wiring: late suspend and its siblings, then the rest unchanged. */ +#ifdef HAVE_SUSPEND_LATE + assert(dcpaud_pm_ops.suspend_late == dcpaud_suspend_late); + assert(dcpaud_pm_ops.freeze_late == dcpaud_suspend_late); + assert(dcpaud_pm_ops.poweroff_late == dcpaud_suspend_late); +#endif + assert(dcpaud_pm_ops.resume_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.thaw_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.restore_early == pm_runtime_force_resume); + assert(dcpaud_pm_ops.prepare == dcpaud_pm_prepare); + assert(dcpaud_pm_ops.suspend == dcpaud_system_suspend); + assert(!dcpaud_pm_ops.resume); + assert(dcpaud_pm_ops.runtime_suspend == dcpaud_suspend); + assert(dcpaud_pm_ops.runtime_resume == dcpaud_resume); + + printf("%u late-suspend cases passed, %u hold the dp-audio domain; pm ops wired\n", + cases, held); + return 0; +} diff --git a/tools/asahi/dcpaud-sleep-hold-tests.py b/tools/asahi/dcpaud-sleep-hold-tests.py new file mode 100755 index 00000000000000..66a5475bf61177 --- /dev/null +++ b/tools/asahi/dcpaud-sleep-hold-tests.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual dcp-dp-audio late sleep callback over every DCP topology. + +genpd powers the dp-audio domain off at noirq unless the device is on the +wakeup path, and cutting it under running DCP firmware resets the J473 on +s2idle. dcpaud_suspend_late() puts dp-audio on the wakeup path when the DCP +linked by its OF graph exists and is unbound or on its own wakeup path. The +fixture builds the real function and the real dcpaud_pm_ops (with the +kernel's PM_OPS macros) from drivers/gpu/drm/apple/audio.c against an OF +graph and driver-core model that counts every node and device reference. + +--mutation names a change to the production function that the matrix must +kill. --ref reads audio.c from an older revision: before the fix the late +slot was pm_runtime_force_suspend, which never holds the domain, so the +matrix fails (the old-code negative control). +""" +import argparse +import json +import os +import re +import resource +import subprocess +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +AUDIO = "drivers/gpu/drm/apple/audio.c" +PM = "include/linux/pm.h" + +MUTATIONS = { + # Hold only for a DCP on its wakeup path; an unbound DCP loses the domain. + "bound-only": ("!device_is_bound(&dcp_pdev->dev) || device_wakeup_path(", + "device_wakeup_path("), + # Leak the DCP device reference from of_find_device_by_node(). + "leak-device": ("\t\tput_device(&dcp_pdev->dev);\n", ""), + # Leak the DCP node reference from of_graph_get_remote_port_parent(). + "leak-node": ("\tof_node_put(dcp_node);\n", ""), + # Hold for a bound DCP that is NOT on its wakeup path. + "invert-wakeup": ("|| device_wakeup_path(", "|| !device_wakeup_path("), +} + + +def block(text, start): + begin = text.index("{", start) + depth, end = 1, begin + 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return end + + +def function(text, name): + match = re.search(r"^static [^\n;]*\bint " + name + r"\(struct device \*dev\)\n\{", + text, re.M) + if not match: + return None + return text[match.start():block(text, match.start())] + + +def pm_ops(text): + start = text.index("static const struct dev_pm_ops dcpaud_pm_ops = {") + return text[start:block(text, start)] + ";\n" + + +def macro(text, name): + match = re.search(r"^#define " + name + r"\(.*?[^\\]\n", text, re.M | re.S) + assert match, name + return match.group() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) + parser.add_argument("--ref", help="read audio.c from this revision") + parser.add_argument("--mutation", choices=sorted(MUTATIONS)) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + + if args.ref: + audio = subprocess.check_output(["git", "show", f"{args.ref}:{AUDIO}"], + cwd=ROOT, text=True) + else: + audio = (ROOT / AUDIO).read_text() + pm = (ROOT / PM).read_text() + late = function(audio, "dcpaud_suspend_late") + if args.mutation: + old, new = MUTATIONS[args.mutation] + if not late or late.count(old) != 1: + raise RuntimeError(f"mutation {args.mutation} did not apply exactly once") + late = late.replace(old, new) + + macros = "".join(macro(pm, name) for name in + ("SYSTEM_SLEEP_PM_OPS", "LATE_SYSTEM_SLEEP_PM_OPS", "RUNTIME_PM_OPS")) + code = (Path(__file__).with_suffix(".c").read_text() + .replace("/* ACTUAL_PM_MACROS */", macros) + .replace("/* ACTUAL_FUNCTION */", late or "") + .replace("/* ACTUAL_PM_OPS */", pm_ops(audio))) + + def run(out): + out.mkdir(parents=True, exist_ok=True) + source, binary = out / "dcpaud-sleep-hold.c", out / "dcpaud-sleep-hold" + source.write_text(code) + subprocess.run([os.environ.get("CC", "cc"), "-std=gnu11", "-O1", "-g", "-Wall", + "-Wextra", "-Werror", "-Wno-unused-function", + "-fsanitize=address,undefined", + "-fno-sanitize-recover=all"] + + (["-DHAVE_SUSPEND_LATE"] if late else []) + + [str(source), "-o", str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + (out / "results.json").write_text(json.dumps({ + "exit": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + "ref": args.ref, + "mutation": args.mutation, + "limits": "OF graph, driver core and runtime PM are host models; no genpd, no DCP.", + }, indent=2) + "\n") + print(result.stdout + result.stderr, end="") + return result.returncode != 0 + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + if args.out: + return run(args.out.resolve()) + with tempfile.TemporaryDirectory(prefix="dcpaud-sleep-hold-") as out: + return run(Path(out)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..c9e95d9d424517 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -177,6 +177,11 @@ def mutations(flag, names, base, expect=KILL): 'missing-control-firmware', 'missing-control-descriptor', 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), + # a7638d51880c, the parent of the fix, ran pm_runtime_force_suspend in the late + # slot, so the dp-audio domain dropped under a running DCP. + 'dcpaud-sleep-hold-tests.py': [(out(), PASS)] + + mutations('--mutation', ('bound-only', 'leak-device', 'leak-node', 'invert-wakeup'), out()) + + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), From f2a91885d491dead0b4c9c4340a477b9f606f624 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:39:09 +1100 Subject: [PATCH 0562/1514] soc: apple: dockchannel: add KUnit tests Add a suite for the DockChannel FIFO core. The FIFO data and count registers go through three small accessors that a KUnit static stub can redirect (they are the same relaxed MMIO accesses otherwise), so the test can model a FIFO that fills and drains, and a simulated interrupt drives the driver's own TX/RX handlers and RX thread: - send: whole words and tail bytes, exactly full, no room, one byte of room at a time, wake-ups without room, the TX threshold, timeouts; - recv: partial words and the tail byte in bits 15:8, a count larger than the caller's buffer and an all-ones count (never written past the buffer), unaligned buffers; - await with and without a callback, interrupt enable/disable balance across re-arms, and the interrupt controller's mask/unmask/ack. No functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 16 + drivers/soc/apple/dockchannel-test.c | 894 ++++++++++++++++++++++ drivers/soc/apple/dockchannel.c | 58 +- drivers/soc/apple/dockchannel.kunitconfig | 6 + 4 files changed, 964 insertions(+), 10 deletions(-) create mode 100644 drivers/soc/apple/dockchannel-test.c create mode 100644 drivers/soc/apple/dockchannel.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..cd636ec647b6a0 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -34,6 +34,22 @@ config APPLE_DOCKCHANNEL Say 'y' here if you have an Apple SoC. +config APPLE_DOCKCHANNEL_KUNIT_TEST + bool "KUnit tests for the Apple DockChannel FIFO" if !KUNIT_ALL_TESTS + depends on APPLE_DOCKCHANNEL=y && KUNIT=y + select IRQ_SIM + default KUNIT_ALL_TESTS + help + Send and receive through a DockChannel FIFO that the test models + behind static stubs: whole words and tail bytes, a FIFO with + partial, exact or no room, the TX and RX thresholds and waits, + timeouts, a count register that reports more than the caller's + buffer, and the receive callback. The FIFO interrupts are + simulated interrupts and the interrupt controller registers are + kernel memory. The tests touch no hardware. + + If unsure, say N. + config APPLE_MAILBOX tristate "Apple SoC mailboxes" depends on PM diff --git a/drivers/soc/apple/dockchannel-test.c b/drivers/soc/apple/dockchannel-test.c new file mode 100644 index 00000000000000..14cc35ae5d5003 --- /dev/null +++ b/drivers/soc/apple/dockchannel-test.c @@ -0,0 +1,894 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple DockChannel FIFO. + * + * Included at the end of dockchannel.c. The FIFO data and threshold + * registers are modelled behind static stubs on the register accessors: + * TX_FREE and RX_COUNT live in a buffer of kernel memory (so that the + * receive interrupt thread, which the stubs do not redirect, reads the same + * counts), the bytes written to the TX FIFO are logged and the RX FIFO is a + * queue of bytes. Writing a threshold register can add room or data and + * raise the FIFO's interrupt, which is a simulated interrupt handled by the + * driver's own handlers. The interrupt controller functions run on a buffer + * of kernel memory. Nothing touches hardware. + */ + +#include +#include +#include +#include +#include +#include + +#define DCT_FIFO_SIZE 16 +#define DCT_LOG 256 +#define DCT_STEPS 8 +#define DCT_GUARD 256 +#define DCT_POISON 0xee +/* Past this many model violations, abort the case: a runaway loop. */ +#define DCT_RUNAWAY 32 +/* No case reads a count register more often than this. */ +#define DCT_MAX_POLLS 64 + +struct dct_ctx { + struct dockchannel dc; + u8 *cfg; + u8 *data; + u8 *irqregs; + + struct fwnode_handle *fwnode; + struct irq_domain *domain; + struct task_struct *worker; + atomic_t fire_tx; + atomic_t fire_rx; + + /* TX FIFO: what was written, and how ('W' word, 'B' byte). */ + u8 tx_log[DCT_LOG]; + unsigned int tx_len; + char tx_ops[DCT_LOG + 1]; + unsigned int tx_nops; + unsigned int tx_free_reads; + /* Room added by each TX threshold write; each also raises the IRQ. */ + unsigned int tx_refill[DCT_STEPS]; + unsigned int tx_nrefill; + unsigned int tx_refill_pos; + u32 tx_thresh[DCT_STEPS]; + unsigned int tx_nthresh; + + /* RX FIFO: rx_q[rx_pos..rx_len) is queued, RX_COUNT of it visible. */ + u8 rx_q[DCT_LOG]; + unsigned int rx_len; + unsigned int rx_pos; + char rx_ops[DCT_LOG + 1]; + unsigned int rx_nops; + unsigned int rx_count_reads; + unsigned int rx_refill[DCT_STEPS]; + unsigned int rx_nrefill; + unsigned int rx_refill_pos; + u32 rx_thresh[DCT_STEPS]; + unsigned int rx_nthresh; + + /* Accesses the FIFO would not allow (write without room, etc.). */ + unsigned int violations; + + /* Receive callback (runs in the RX interrupt thread). */ + struct completion cb_done; + atomic_t cb_calls; + size_t cb_avail; + void *cb_cookie; + bool cb_recv; + u8 cb_buf[4]; + int cb_ret; +}; + +static u32 dct_reg(struct dct_ctx *ctx, unsigned int off) +{ + return READ_ONCE(*(u32 *)(ctx->data + off)); +} + +static void dct_set_reg(struct dct_ctx *ctx, unsigned int off, u32 val) +{ + WRITE_ONCE(*(u32 *)(ctx->data + off), val); +} + +/* Too many bad accesses: the driver is in a runaway loop, stop the case. */ +static void dct_violation(struct dct_ctx *ctx) +{ + if (++ctx->violations > DCT_RUNAWAY) + KUNIT_FAIL_AND_ABORT(kunit_get_current_test(), + "runaway FIFO access loop"); +} + +static u32 dct_rx_pop(struct dct_ctx *ctx, unsigned int n, char op) +{ + u32 avail = dct_reg(ctx, DATA_RX_COUNT); + u32 val = 0; + unsigned int i; + + if (avail < n || ctx->rx_pos + n > ctx->rx_len) { + dct_violation(ctx); + return 0xdeadbeef; + } + for (i = 0; i < n; i++) + val |= (u32)ctx->rx_q[ctx->rx_pos++] << (8 * i); + dct_set_reg(ctx, DATA_RX_COUNT, avail - n); + if (ctx->rx_nops < DCT_LOG) + ctx->rx_ops[ctx->rx_nops++] = op; + + return val; +} + +static u32 dct_readl(void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + long off = (u8 __force *)addr - ctx->data; + + switch (off) { + case DATA_TX_FREE: + if (++ctx->tx_free_reads > DCT_MAX_POLLS) + dct_violation(ctx); + return dct_reg(ctx, DATA_TX_FREE); + case DATA_RX_COUNT: + if (++ctx->rx_count_reads > DCT_MAX_POLLS) + dct_violation(ctx); + return dct_reg(ctx, DATA_RX_COUNT); + case DATA_RX32: + return dct_rx_pop(ctx, 4, 'W'); + case DATA_RX8: + /* The byte comes in bits [15:8]; fill the other bits with junk. */ + return 0x5a0000a5 | (dct_rx_pop(ctx, 1, 'B') & 0xff) << 8; + default: + ctx->violations++; + return 0; + } +} + +static void dct_tx_push(struct dct_ctx *ctx, u32 val, unsigned int n, char op) +{ + u32 room = dct_reg(ctx, DATA_TX_FREE); + unsigned int i; + + if (room < n || ctx->tx_len + n > DCT_LOG) { + dct_violation(ctx); + return; + } + for (i = 0; i < n; i++) + ctx->tx_log[ctx->tx_len++] = val >> (8 * i); + dct_set_reg(ctx, DATA_TX_FREE, room - n); + if (ctx->tx_nops < DCT_LOG) + ctx->tx_ops[ctx->tx_nops++] = op; +} + +static void dct_writel(u32 val, void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + u8 *p = (u8 __force *)addr; + + if (p == ctx->cfg + CONFIG_TX_THRESH) { + if (ctx->tx_nthresh < DCT_STEPS) + ctx->tx_thresh[ctx->tx_nthresh++] = val; + if (ctx->tx_refill_pos < ctx->tx_nrefill) { + dct_set_reg(ctx, DATA_TX_FREE, dct_reg(ctx, DATA_TX_FREE) + + ctx->tx_refill[ctx->tx_refill_pos++]); + atomic_set(&ctx->fire_tx, 1); + } + } else if (p == ctx->cfg + CONFIG_RX_THRESH) { + if (ctx->rx_nthresh < DCT_STEPS) + ctx->rx_thresh[ctx->rx_nthresh++] = val; + if (ctx->rx_refill_pos < ctx->rx_nrefill) { + dct_set_reg(ctx, DATA_RX_COUNT, dct_reg(ctx, DATA_RX_COUNT) + + ctx->rx_refill[ctx->rx_refill_pos++]); + atomic_set(&ctx->fire_rx, 1); + } + } else if (p == ctx->data + DATA_TX32) { + dct_tx_push(ctx, val, 4, 'W'); + } else { + ctx->violations++; + } +} + +static void dct_writeb(u8 val, void __iomem *addr) +{ + struct dct_ctx *ctx = kunit_get_current_test()->priv; + + if ((u8 __force *)addr == ctx->data + DATA_TX8) + dct_tx_push(ctx, val, 1, 'B'); + else + ctx->violations++; +} + +/* Raise a FIFO interrupt once the driver has enabled it. */ +static void dct_try_fire(atomic_t *fire, unsigned int virq) +{ + struct irq_data *d = irq_get_irq_data(virq); + + if (!atomic_read(fire) || irqd_irq_disabled(d) || irqd_irq_masked(d)) + return; + atomic_set(fire, 0); + irq_set_irqchip_state(virq, IRQCHIP_STATE_PENDING, true); +} + +static int dct_worker(void *arg) +{ + struct dct_ctx *ctx = arg; + + while (!kthread_should_stop()) { + dct_try_fire(&ctx->fire_tx, ctx->dc.tx_irq); + dct_try_fire(&ctx->fire_rx, ctx->dc.rx_irq); + usleep_range(200, 400); + } + + return 0; +} + +static void dct_fire_now(struct kunit *test, unsigned int virq) +{ + struct irq_data *d = irq_get_irq_data(virq); + + KUNIT_ASSERT_FALSE(test, irqd_irq_disabled(d)); + KUNIT_ASSERT_EQ(test, irq_set_irqchip_state(virq, IRQCHIP_STATE_PENDING, true), 0); +} + +static bool dct_irq_enabled(unsigned int virq) +{ + return !irqd_irq_disabled(irq_get_irq_data(virq)); +} + +static int dct_init(struct kunit *test) +{ + struct dct_ctx *ctx; + int irq, ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->cfg = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->data = kunit_kzalloc(test, 0x40, GFP_KERNEL); + ctx->irqregs = kunit_kzalloc(test, 0x10, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->cfg); + KUNIT_ASSERT_NOT_NULL(test, ctx->data); + KUNIT_ASSERT_NOT_NULL(test, ctx->irqregs); + + ctx->dc.config_base = (void __force __iomem *)ctx->cfg; + ctx->dc.data_base = (void __force __iomem *)ctx->data; + ctx->dc.fifo_size = DCT_FIFO_SIZE; + init_completion(&ctx->dc.tx_comp); + init_completion(&ctx->dc.rx_comp); + init_completion(&ctx->cb_done); + test->priv = ctx; + + ctx->fwnode = irq_domain_alloc_named_fwnode("dockchannel-kunit"); + KUNIT_ASSERT_NOT_NULL(test, ctx->fwnode); + ctx->domain = irq_domain_create_sim(ctx->fwnode, 2); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->domain)); + + irq = irq_create_mapping(ctx->domain, 0); + KUNIT_ASSERT_GT(test, irq, 0); + ctx->dc.tx_irq = irq; + irq = irq_create_mapping(ctx->domain, 1); + KUNIT_ASSERT_GT(test, irq, 0); + ctx->dc.rx_irq = irq; + + /* As dockchannel_init() requests them. */ + ret = request_irq(ctx->dc.tx_irq, dockchannel_tx_irq, IRQF_NO_AUTOEN, + "dockchannel-kunit-tx", &ctx->dc); + KUNIT_ASSERT_EQ(test, ret, 0); + ret = request_threaded_irq(ctx->dc.rx_irq, dockchannel_rx_irq, + dockchannel_rx_irq_thread, + IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, + "dockchannel-kunit-rx", &ctx->dc); + if (ret) + free_irq(ctx->dc.tx_irq, &ctx->dc); + KUNIT_ASSERT_EQ(test, ret, 0); + + ctx->worker = kthread_run(dct_worker, ctx, "dockchannel-kunit"); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->worker)); + + kunit_activate_static_stub(test, dockchannel_readl, dct_readl); + kunit_activate_static_stub(test, dockchannel_writel, dct_writel); + kunit_activate_static_stub(test, dockchannel_writeb, dct_writeb); + + return 0; +} + +static void dct_exit(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + if (!ctx || !ctx->domain || IS_ERR(ctx->domain)) + goto fwnode; + + if (ctx->worker && !IS_ERR(ctx->worker)) { + kthread_stop(ctx->worker); + free_irq(ctx->dc.rx_irq, &ctx->dc); + free_irq(ctx->dc.tx_irq, &ctx->dc); + } + if (ctx->dc.rx_irq > 0) + irq_dispose_mapping(ctx->dc.rx_irq); + if (ctx->dc.tx_irq > 0) + irq_dispose_mapping(ctx->dc.tx_irq); + irq_domain_remove_sim(ctx->domain); +fwnode: + if (ctx && ctx->fwnode) + irq_domain_free_fwnode(ctx->fwnode); +} + +static void dct_fill(u8 *buf, unsigned int len, u8 seed) +{ + unsigned int i; + + for (i = 0; i < len; i++) + buf[i] = seed + 7 * i; +} + +static void dct_queue_rx(struct dct_ctx *ctx, unsigned int len, unsigned int visible) +{ + dct_fill(ctx->rx_q, len, 0x31); + ctx->rx_len = len; + dct_set_reg(ctx, DATA_RX_COUNT, visible); +} + +static void dct_expect_guard(struct kunit *test, const u8 *guard, unsigned int len) +{ + unsigned int i, bad = 0; + + for (i = 0; i < len; i++) + bad += guard[i] != DCT_POISON; + KUNIT_EXPECT_EQ_MSG(test, bad, 0, "bytes written past the caller's buffer"); +} + +/* TX */ + +static void dct_send_whole_words(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[8]; + + dct_fill(buf, sizeof(buf), 1); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 8); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WW"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 8); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 56); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_tail_bytes(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[7]; + + dct_fill(buf, sizeof(buf), 0x80); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 7); + /* One little-endian word, then the three tail bytes in order. */ + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WBBB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 7); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 7); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_short(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[3] = { 0x10, 0x20, 0x30 }; + + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 3); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "BBB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 3); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 3); +} + +static void dct_send_unaligned_source(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[16]; + + dct_fill(buf, sizeof(buf), 0x42); + dct_set_reg(ctx, DATA_TX_FREE, 64); + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf + 1, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WWB"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 9); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf + 1, 9); +} + +static void dct_send_exact_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[10]; + + dct_fill(buf, sizeof(buf), 3); + dct_set_reg(ctx, DATA_TX_FREE, sizeof(buf)); + + /* Exactly full: no wait, no threshold write. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 10); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WWBB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 10); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 1); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_partial_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[10]; + + dct_fill(buf, sizeof(buf), 9); + dct_set_reg(ctx, DATA_TX_FREE, 6); + ctx->tx_refill[0] = 8; + ctx->tx_nrefill = 1; + + /* + * 6 bytes fit (a word and two bytes, never a word into 2 bytes of + * room), then the FIFO is full: wait for the 4 that are left. + */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 10); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WBBW"); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 10); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 10); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 4); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_TX_FREE), 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.tx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[40]; + + dct_fill(buf, sizeof(buf), 0x11); + ctx->tx_refill[0] = 16; + ctx->tx_refill[1] = 20; + ctx->tx_refill[2] = 4; + ctx->tx_nrefill = 3; + + /* Half the FIFO while more is left, then exactly what is left. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 40); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[2], 4); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 40); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 40); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_byte_room(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4] = { 0xa1, 0xb2, 0xc3, 0xd4 }; + + /* Room for one byte at a time: never a word write. */ + dct_set_reg(ctx, DATA_TX_FREE, 1); + ctx->tx_refill[0] = 1; + ctx->tx_refill[1] = 1; + ctx->tx_refill[2] = 1; + ctx->tx_nrefill = 3; + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 4); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "BBBB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 4); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 3); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[2], 1); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_spurious_wakeup(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[5]; + + dct_fill(buf, sizeof(buf), 0x55); + /* The first interrupt comes with no room: wait again. */ + ctx->tx_refill[0] = 0; + ctx->tx_refill[1] = 8; + ctx->tx_nrefill = 2; + + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), 5); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 2); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 5); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[1], 5); + KUNIT_EXPECT_STREQ(test, ctx->tx_ops, "WB"); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, buf, 5); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_timeout(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4] = { 1, 2, 3, 4 }; + + /* Nothing ever drains the FIFO. */ + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, sizeof(buf)), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_ASSERT_EQ(test, ctx->tx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_thresh[0], 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.tx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_send_zero(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[1] = { 0 }; + + dct_set_reg(ctx, DATA_TX_FREE, 64); + KUNIT_EXPECT_EQ(test, dockchannel_send(&ctx->dc, buf, 0), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_nthresh, 0); +} + +/* RX */ + +static void dct_recv_words_and_tail(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 7 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 7 + DCT_GUARD); + dct_queue_rx(ctx, 7, 7); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 7), 7); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WBBB"); + /* Word unpacked little-endian, tail bytes taken from bits [15:8]. */ + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 7); + dct_expect_guard(test, buf + 7, DCT_GUARD); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_RX_COUNT), 0); + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_count_exceeds_buffer(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 5 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 5 + DCT_GUARD); + dct_queue_rx(ctx, 64, 64); + + /* 64 bytes waiting, room for 5: take exactly 5, leave 59. */ + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 5), 5); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WB"); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 5); + dct_expect_guard(test, buf + 5, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 5); + KUNIT_EXPECT_EQ(test, dct_reg(ctx, DATA_RX_COUNT), 59); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_all_ones_count(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 6 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 6 + DCT_GUARD); + /* A count register that reads all ones must not size the copy. */ + dct_queue_rx(ctx, 8, 0xffffffff); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 6), 6); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 6); + dct_expect_guard(test, buf + 6, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 6); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_unaligned_dest(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 3 + 9 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 3 + 9 + DCT_GUARD); + dct_queue_rx(ctx, 9, 9); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf + 3, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "WWB"); + dct_expect_guard(test, buf, 3); + KUNIT_EXPECT_MEMEQ(test, buf + 3, ctx->rx_q, 9); + dct_expect_guard(test, buf + 12, DCT_GUARD); +} + +static void dct_recv_partial_waits(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 9 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 9 + DCT_GUARD); + /* 3 of 9 bytes there; the rest comes with the threshold interrupt. */ + dct_queue_rx(ctx, 9, 3); + ctx->rx_refill[0] = 6; + ctx->rx_nrefill = 1; + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 9), 9); + KUNIT_EXPECT_STREQ(test, ctx->rx_ops, "BBBWBB"); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 9); + dct_expect_guard(test, buf + 9, DCT_GUARD); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 6); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 30 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 30 + DCT_GUARD); + dct_queue_rx(ctx, 30, 0); + ctx->rx_refill[0] = 12; + ctx->rx_refill[1] = 18; + ctx->rx_nrefill = 2; + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 30), 30); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 2); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[1], DCT_FIFO_SIZE / 2); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 30); + dct_expect_guard(test, buf + 30, DCT_GUARD); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_timeout(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 *buf = kunit_kmalloc(test, 4 + DCT_GUARD, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + memset(buf, DCT_POISON, 4 + DCT_GUARD); + + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 4), -ETIMEDOUT); + dct_expect_guard(test, buf, 4 + DCT_GUARD); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 4); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dct_recv_zero(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[1] = { DCT_POISON }; + + dct_queue_rx(ctx, 8, 8); + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 0), 0); + KUNIT_EXPECT_EQ(test, ctx->rx_count_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->rx_pos, 0); + KUNIT_EXPECT_EQ(test, buf[0], DCT_POISON); +} + +/* Await */ + +static void dct_callback(void *cookie, size_t avail) +{ + struct dct_ctx *ctx = cookie; + + ctx->cb_cookie = cookie; + ctx->cb_avail = avail; + if (ctx->cb_recv) + ctx->cb_ret = dockchannel_recv(&ctx->dc, ctx->cb_buf, sizeof(ctx->cb_buf)); + atomic_inc(&ctx->cb_calls); + complete(&ctx->cb_done); +} + +static void dct_await_threshold(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], 4); + KUNIT_EXPECT_TRUE(test, ctx->dc.awaiting); + KUNIT_EXPECT_TRUE(test, dct_irq_enabled(ctx->dc.rx_irq)); + + /* A zero count disarms. */ + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); + KUNIT_EXPECT_FALSE(test, ctx->dc.awaiting); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 0); +} + +static void dct_await_clamped(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + /* A threshold above the FIFO size would never be reached. */ + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 100), + DCT_FIFO_SIZE); + KUNIT_ASSERT_EQ(test, ctx->rx_nthresh, 1); + KUNIT_EXPECT_EQ(test, ctx->rx_thresh[0], DCT_FIFO_SIZE); + KUNIT_EXPECT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); +} + +static void dct_await_callback(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + dct_set_reg(ctx, DATA_RX_COUNT, 9); + dct_fire_now(test, ctx->dc.rx_irq); + + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 1); + KUNIT_EXPECT_PTR_EQ(test, ctx->cb_cookie, (void *)ctx); + /* The callback is told what RX_COUNT says, and is not re-armed. */ + KUNIT_EXPECT_EQ(test, ctx->cb_avail, 9); + KUNIT_EXPECT_FALSE(test, ctx->dc.awaiting); + KUNIT_EXPECT_FALSE(test, dct_irq_enabled(ctx->dc.rx_irq)); +} + +static void dct_await_recv_in_callback(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + static const u8 want[4] = { 0x78, 0x56, 0x34, 0x12 }; + + /* + * The interrupt thread is not the test thread, so the stubs do not + * apply there: it reads the register buffer as it is. + */ + dct_set_reg(ctx, DATA_RX32, 0x12345678); + ctx->cb_recv = true; + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + dct_set_reg(ctx, DATA_RX_COUNT, 4); + dct_fire_now(test, ctx->dc.rx_irq); + + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, ctx->cb_ret, 4); + KUNIT_EXPECT_MEMEQ(test, ctx->cb_buf, want, 4); +} + +static void dct_await_rearm(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + int i; + + /* As the HID client does: every callback arms the next one. */ + for (i = 1; i <= 3; i++) { + reinit_completion(&ctx->cb_done); + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 8), 8); + KUNIT_ASSERT_TRUE(test, dct_irq_enabled(ctx->dc.rx_irq)); + dct_set_reg(ctx, DATA_RX_COUNT, 8 + i); + dct_fire_now(test, ctx->dc.rx_irq); + KUNIT_ASSERT_TRUE(test, + wait_for_completion_timeout(&ctx->cb_done, + msecs_to_jiffies(2000))); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), i); + KUNIT_EXPECT_EQ(test, ctx->cb_avail, 8 + i); + } + KUNIT_EXPECT_EQ(test, ctx->rx_nthresh, 3); +} + +static void dct_recv_after_await(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + u8 buf[4]; + + /* + * Once disarmed, the receive interrupt wakes a waiting + * dockchannel_recv() and no longer calls the callback. + */ + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, dct_callback, ctx, 4), 4); + KUNIT_ASSERT_EQ(test, dockchannel_await(&ctx->dc, NULL, NULL, 0), 0); + + dct_queue_rx(ctx, 4, 0); + ctx->rx_refill[0] = 4; + ctx->rx_nrefill = 1; + KUNIT_EXPECT_EQ(test, dockchannel_recv(&ctx->dc, buf, 4), 4); + KUNIT_EXPECT_MEMEQ(test, buf, ctx->rx_q, 4); + KUNIT_EXPECT_EQ(test, atomic_read(&ctx->cb_calls), 0); +} + +/* Interrupt controller */ + +static void dct_irqchip_mask_unmask(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + struct dockchannel_common dcc = { + .irq_base = (void __force __iomem *)ctx->irqregs, + }; + struct irq_data d = { .chip_data = &dcc }; + u32 *mask = (u32 *)(ctx->irqregs + IRQ_MASK); + u32 *flag = (u32 *)(ctx->irqregs + IRQ_FLAG); + + WRITE_ONCE(*mask, 0xa5a5a5a5); + WRITE_ONCE(*flag, 0x12345678); + + d.hwirq = 0; + dockchannel_irq_mask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a4); + d.hwirq = 1; + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + d.hwirq = 31; + dockchannel_irq_mask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0x25a5a5a6); + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + /* Unmasking an unmasked line changes nothing. */ + dockchannel_irq_unmask(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xa5a5a5a6); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), 0x12345678); +} + +static void dct_irqchip_ack(struct kunit *test) +{ + struct dct_ctx *ctx = test->priv; + struct dockchannel_common dcc = { + .irq_base = (void __force __iomem *)ctx->irqregs, + }; + struct irq_data d = { .chip_data = &dcc, .hwirq = 5 }; + u32 *mask = (u32 *)(ctx->irqregs + IRQ_MASK); + u32 *flag = (u32 *)(ctx->irqregs + IRQ_FLAG); + + WRITE_ONCE(*mask, 0xffffffff); + WRITE_ONCE(*flag, 0); + + /* IRQ_FLAG is write-one-to-clear: write only this line's bit. */ + dockchannel_irq_ack(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), BIT(5)); + d.hwirq = 31; + dockchannel_irq_ack(&d); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), BIT(31)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), 0xffffffff); +} + +static struct kunit_case dockchannel_test_cases[] = { + KUNIT_CASE(dct_send_whole_words), + KUNIT_CASE(dct_send_tail_bytes), + KUNIT_CASE(dct_send_short), + KUNIT_CASE(dct_send_unaligned_source), + KUNIT_CASE(dct_send_exact_room), + KUNIT_CASE(dct_send_partial_room), + KUNIT_CASE(dct_send_threshold), + KUNIT_CASE(dct_send_byte_room), + KUNIT_CASE(dct_send_spurious_wakeup), + KUNIT_CASE(dct_send_timeout), + KUNIT_CASE(dct_send_zero), + KUNIT_CASE(dct_recv_words_and_tail), + KUNIT_CASE(dct_recv_count_exceeds_buffer), + KUNIT_CASE(dct_recv_all_ones_count), + KUNIT_CASE(dct_recv_unaligned_dest), + KUNIT_CASE(dct_recv_partial_waits), + KUNIT_CASE(dct_recv_threshold), + KUNIT_CASE(dct_recv_timeout), + KUNIT_CASE(dct_recv_zero), + KUNIT_CASE(dct_await_threshold), + KUNIT_CASE(dct_await_clamped), + KUNIT_CASE(dct_await_callback), + KUNIT_CASE(dct_await_recv_in_callback), + KUNIT_CASE(dct_await_rearm), + KUNIT_CASE(dct_recv_after_await), + KUNIT_CASE(dct_irqchip_mask_unmask), + KUNIT_CASE(dct_irqchip_ack), + {} +}; + +static struct kunit_suite dockchannel_test_suite = { + .name = "apple-dockchannel", + .init = dct_init, + .exit = dct_exit, + .test_cases = dockchannel_test_cases, +}; + +kunit_test_suite(dockchannel_test_suite); diff --git a/drivers/soc/apple/dockchannel.c b/drivers/soc/apple/dockchannel.c index 6ee1f9185eb709..291d81d2df2fa8 100644 --- a/drivers/soc/apple/dockchannel.c +++ b/drivers/soc/apple/dockchannel.c @@ -18,6 +18,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include +#endif + #define DOCKCHANNEL_MAX_IRQ 32 #define DOCKCHANNEL_TX_TIMEOUT_MS 1000 @@ -68,6 +72,34 @@ struct dockchannel_common { void __iomem *irq_base; }; +/* + * FIFO register accesses. They are functions so that the KUnit test can model + * the FIFO behind them. + */ +static u32 dockchannel_readl(void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_readl, addr); +#endif + return readl_relaxed(addr); +} + +static void dockchannel_writel(u32 val, void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_writel, val, addr); +#endif + writel_relaxed(val, addr); +} + +static void dockchannel_writeb(u8 val, void __iomem *addr) +{ +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dockchannel_writeb, val, addr); +#endif + writeb_relaxed(val, addr); +} + /* Dockchannel FIFO functions */ static irqreturn_t dockchannel_tx_irq(int irq, void *data) @@ -97,7 +129,7 @@ static irqreturn_t dockchannel_rx_irq(int irq, void *data) static irqreturn_t dockchannel_rx_irq_thread(int irq, void *data) { struct dockchannel *dockchannel = data; - size_t avail = readl_relaxed(dockchannel->data_base + DATA_RX_COUNT); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT); dockchannel->awaiting = false; dockchannel->data_available(dockchannel->cookie, avail); @@ -111,13 +143,13 @@ int dockchannel_send(struct dockchannel *dockchannel, const void *buf, size_t co const u8 *p = buf; while (left > 0) { - size_t avail = readl_relaxed(dockchannel->data_base + DATA_TX_FREE); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_TX_FREE); size_t block = min(left, avail); if (avail == 0) { size_t threshold = min((size_t)(dockchannel->fifo_size / 2), left); - writel_relaxed(threshold, dockchannel->config_base + CONFIG_TX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_TX_THRESH); reinit_completion(&dockchannel->tx_comp); enable_irq(dockchannel->tx_irq); @@ -131,13 +163,14 @@ int dockchannel_send(struct dockchannel *dockchannel, const void *buf, size_t co } while (block >= 4) { - writel_relaxed(get_unaligned_le32(p), dockchannel->data_base + DATA_TX32); + dockchannel_writel(get_unaligned_le32(p), + dockchannel->data_base + DATA_TX32); p += 4; left -= 4; block -= 4; } while (block > 0) { - writeb_relaxed(*p++, dockchannel->data_base + DATA_TX8); + dockchannel_writeb(*p++, dockchannel->data_base + DATA_TX8); left--; block--; } @@ -153,13 +186,13 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) u8 *p = buf; while (left > 0) { - size_t avail = readl_relaxed(dockchannel->data_base + DATA_RX_COUNT); + size_t avail = dockchannel_readl(dockchannel->data_base + DATA_RX_COUNT); size_t block = min(left, avail); if (avail == 0) { size_t threshold = min((size_t)(dockchannel->fifo_size / 2), left); - writel_relaxed(threshold, dockchannel->config_base + CONFIG_RX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); reinit_completion(&dockchannel->rx_comp); enable_irq(dockchannel->rx_irq); @@ -173,13 +206,14 @@ int dockchannel_recv(struct dockchannel *dockchannel, void *buf, size_t count) } while (block >= 4) { - put_unaligned_le32(readl_relaxed(dockchannel->data_base + DATA_RX32), p); + put_unaligned_le32(dockchannel_readl(dockchannel->data_base + DATA_RX32), + p); p += 4; left -= 4; block -= 4; } while (block > 0) { - *p++ = readl_relaxed(dockchannel->data_base + DATA_RX8) >> 8; + *p++ = dockchannel_readl(dockchannel->data_base + DATA_RX8) >> 8; left--; block--; } @@ -204,7 +238,7 @@ int dockchannel_await(struct dockchannel *dockchannel, dockchannel->data_available = callback; dockchannel->cookie = cookie; dockchannel->awaiting = true; - writel_relaxed(threshold, dockchannel->config_base + CONFIG_RX_THRESH); + dockchannel_writel(threshold, dockchannel->config_base + CONFIG_RX_THRESH); enable_irq(dockchannel->rx_irq); return threshold; @@ -434,3 +468,7 @@ module_platform_driver(dockchannel_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple DockChannel driver"); + +#if IS_ENABLED(CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include "dockchannel-test.c" +#endif diff --git a/drivers/soc/apple/dockchannel.kunitconfig b/drivers/soc/apple/dockchannel.kunitconfig new file mode 100644 index 00000000000000..ad45d22b946006 --- /dev/null +++ b/drivers/soc/apple/dockchannel.kunitconfig @@ -0,0 +1,6 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_APPLE_DOCKCHANNEL=y +CONFIG_APPLE_DOCKCHANNEL_KUNIT_TEST=y From c36cb339c0d1f53e60cf1f2b26eda91d6786cb8a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:39:10 +1100 Subject: [PATCH 0563/1514] tty: serial: apple_dockchannel_uart: add KUnit tests Add a suite for the DockChannel UART. Its FIFO accesses go through accessors that a KUnit static stub can redirect (the same MMIO accesses otherwise), and the test models the FIFO behind them; the port is built but not registered, and received bytes are read back from the TTY flip buffers: - the RX drain and its per-pass FIFO_SIZE clamp, the interrupt path clearing only this channel's flag; - TX limited by the free room, x_char, dropping queued output after two ticks without room, and the drain timer; - startup/shutdown in interrupt, software-drain and never-wait modes, termios (forced to 8N1 at 115200), and the console helpers. No functional change. Signed-off-by: Ryan Murray --- drivers/tty/serial/Kconfig | 16 + .../tty/serial/apple_dockchannel_uart-test.c | 845 ++++++++++++++++++ drivers/tty/serial/apple_dockchannel_uart.c | 46 +- .../serial/apple_dockchannel_uart.kunitconfig | 7 + 4 files changed, 909 insertions(+), 5 deletions(-) create mode 100644 drivers/tty/serial/apple_dockchannel_uart-test.c create mode 100644 drivers/tty/serial/apple_dockchannel_uart.kunitconfig diff --git a/drivers/tty/serial/Kconfig b/drivers/tty/serial/Kconfig index 53819706c237dd..ab38a0d6e89f4e 100644 --- a/drivers/tty/serial/Kconfig +++ b/drivers/tty/serial/Kconfig @@ -121,6 +121,22 @@ config SERIAL_APPLE_DOCKCHANNEL whose firmware has configured this transport, including T8140. It can take over from the DockChannel early console during boot. +config SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST + bool "KUnit tests for the Apple DockChannel UART" if !KUNIT_ALL_TESTS + depends on SERIAL_APPLE_DOCKCHANNEL && KUNIT=y + select IRQ_SIM + default KUNIT_ALL_TESTS + help + Drive the DockChannel UART port through a FIFO that the test models + behind static stubs: RX draining with the per-pass FIFO size clamp, + TX limited by the room in the FIFO and dropped when no reader comes, + the interrupt mask bits of other channels, startup and shutdown, + termios, and the console output helpers. The UART interrupt is a + simulated interrupt and the other registers are kernel memory. The + tests touch no hardware and register no port. + + If unsure, say N. + config SERIAL_SB1250_DUART tristate "BCM1xxx on-chip DUART serial support" depends on SIBYTE_SB1xxx_SOC=y diff --git a/drivers/tty/serial/apple_dockchannel_uart-test.c b/drivers/tty/serial/apple_dockchannel_uart-test.c new file mode 100644 index 00000000000000..2a2c3ebcb71d18 --- /dev/null +++ b/drivers/tty/serial/apple_dockchannel_uart-test.c @@ -0,0 +1,845 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple DockChannel UART. + * + * Included at the end of apple_dockchannel_uart.c. The port is built by the + * test and never registered. The data FIFO accesses of the RX drain and TX + * paths go to a model behind static stubs; the interrupt and config + * registers, and the data registers as the console helpers in + * apple_dockchannel.h see them, are buffers of kernel memory. Received bytes + * are read back from the port's flip buffers. Nothing touches hardware. + */ + +#include +#include +#include + +#define DCUT_CHANNEL 3 +#define DCUT_OTHERS (BIT(0) | BIT(1) | BIT(9) | BIT(31)) +#define DCUT_LOG 4096 +#define DCUT_STEPS 8 +#define DCUT_POISON 0xee +#define DCUT_RUNAWAY 32 +#define DCUT_CON (MAX_PORTS - 1) + +struct dcut_ctx { + struct dcuart_port dcuart; + struct uart_state *state; + u8 *data; + u8 *cfg; + u8 *irqregs; + + struct fwnode_handle *fwnode; + struct irq_domain *domain; + int virq; + bool irq_requested; + bool con_slot; + + /* RX FIFO: rx_q[rx_pos..rx_len), rx_visible of it in RX_COUNT. */ + u8 rx_q[DCUT_LOG]; + unsigned int rx_len; + unsigned int rx_pos; + unsigned int rx_visible; + /* Bytes that arrive each time RX_COUNT is read while it is 0. */ + unsigned int rx_chunk[DCUT_STEPS]; + unsigned int rx_nchunk; + unsigned int rx_chunk_pos; + u32 rx_counts[DCUT_STEPS]; + unsigned int rx_ncounts; + + /* TX FIFO */ + unsigned int tx_room; + u8 tx_log[DCUT_LOG]; + unsigned int tx_len; + unsigned int tx_free_reads; + + unsigned int violations; +}; + +static u32 *dcut_reg(u8 *base, unsigned int off) +{ + return (u32 *)(base + off); +} + +static u32 dcut_rx_readl(struct dcuart_port *dcuart, u32 reg) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + u8 c; + + if (dcuart != &ctx->dcuart) { + ctx->violations++; + return 0; + } + + switch (reg) { + case DATA_RX_COUNT: + if (!ctx->rx_visible && ctx->rx_chunk_pos < ctx->rx_nchunk) + ctx->rx_visible = ctx->rx_chunk[ctx->rx_chunk_pos++]; + if (ctx->violations > DCUT_RUNAWAY) + ctx->rx_visible = 0; + if (ctx->rx_ncounts < DCUT_STEPS) + ctx->rx_counts[ctx->rx_ncounts++] = ctx->rx_visible; + return ctx->rx_visible; + case DATA_RX8: + if (!ctx->rx_visible || ctx->rx_pos >= ctx->rx_len) { + ctx->violations++; + return 0xdeadbeef; + } + ctx->rx_visible--; + c = ctx->rx_q[ctx->rx_pos++]; + /* The byte comes in bits [15:8]; fill the other bits with junk. */ + return 0x5a0000a5 | (u32)c << 8; + default: + ctx->violations++; + return 0; + } +} + +static u32 dcut_tx_free(struct dcuart_port *dcuart) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + + ctx->tx_free_reads++; + return ctx->tx_room; +} + +static void dcut_tx_put(struct dcuart_port *dcuart, u8 ch) +{ + struct dcut_ctx *ctx = kunit_get_current_test()->priv; + + if (!ctx->tx_room || ctx->tx_len >= DCUT_LOG) { + ctx->violations++; + return; + } + ctx->tx_room--; + ctx->tx_log[ctx->tx_len++] = ch; +} + +static int dcut_init(struct kunit *test) +{ + struct dcut_ctx *ctx; + struct uart_port *port; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->data = kunit_kzalloc(test, 0x40, GFP_KERNEL); + ctx->cfg = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->irqregs = kunit_kzalloc(test, 0x10, GFP_KERNEL); + ctx->state = kunit_kzalloc(test, sizeof(*ctx->state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->data); + KUNIT_ASSERT_NOT_NULL(test, ctx->cfg); + KUNIT_ASSERT_NOT_NULL(test, ctx->irqregs); + KUNIT_ASSERT_NOT_NULL(test, ctx->state); + test->priv = ctx; + + tty_port_init(&ctx->state->port); + KUNIT_ASSERT_EQ(test, kfifo_alloc(&ctx->state->port.xmit_fifo, PAGE_SIZE, + GFP_KERNEL), 0); + + /* As dcuart_probe() sets the port up. */ + port = &ctx->dcuart.port; + port->ops = &dcuart_ops; + port->fifosize = FIFO_SIZE; + port->iotype = UPIO_MEM32; + port->type = PORT_GENERIC; + port->membase = (void __force __iomem *)ctx->data; + port->state = ctx->state; + ctx->state->uart_port = port; + spin_lock_init(&port->lock); + spin_lock_init(&ctx->dcuart.lock); + ctx->dcuart.irq_base = (void __force __iomem *)ctx->irqregs; + ctx->dcuart.config_base = (void __force __iomem *)ctx->cfg; + ctx->dcuart.irq_tx = IRQ_TX(DCUT_CHANNEL); + ctx->dcuart.irq_rx = IRQ_RX(DCUT_CHANNEL); + timer_setup(&ctx->dcuart.drain_timer, dcuart_drain_timer, 0); + + kunit_activate_static_stub(test, dcuart_rx_readl, dcut_rx_readl); + kunit_activate_static_stub(test, dcuart_tx_free, dcut_tx_free); + kunit_activate_static_stub(test, dcuart_tx_put, dcut_tx_put); + + return 0; +} + +static void dcut_exit(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + if (!ctx || !ctx->state) + return; + + timer_delete_sync(&ctx->dcuart.drain_timer); + if (ctx->con_slot) + dcuart_ports[DCUT_CON] = NULL; + if (ctx->irq_requested) + free_irq(ctx->virq, ctx); + if (ctx->virq > 0) + irq_dispose_mapping(ctx->virq); + if (ctx->domain && !IS_ERR(ctx->domain)) + irq_domain_remove_sim(ctx->domain); + if (ctx->fwnode) + irq_domain_free_fwnode(ctx->fwnode); + tty_port_destroy(&ctx->state->port); + kfifo_free(&ctx->state->port.xmit_fifo); +} + +/* Give the port a (simulated) interrupt line, as a non-sw-drain probe does. */ +static irqreturn_t dcut_irq_handler(int irq, void *data) +{ + return IRQ_HANDLED; +} + +static void dcut_setup_irq(struct kunit *test, struct dcut_ctx *ctx) +{ + ctx->fwnode = irq_domain_alloc_named_fwnode("dockchannel-uart-kunit"); + KUNIT_ASSERT_NOT_NULL(test, ctx->fwnode); + ctx->domain = irq_domain_create_sim(ctx->fwnode, 1); + KUNIT_ASSERT_FALSE(test, IS_ERR(ctx->domain)); + ctx->virq = irq_create_mapping(ctx->domain, 0); + KUNIT_ASSERT_GT(test, ctx->virq, 0); + KUNIT_ASSERT_EQ(test, request_irq(ctx->virq, dcut_irq_handler, IRQF_NO_AUTOEN, + "dockchannel-uart-kunit", ctx), 0); + ctx->irq_requested = true; + ctx->dcuart.port.irq = ctx->virq; +} + +static bool dcut_irq_enabled(struct dcut_ctx *ctx) +{ + return !irqd_irq_disabled(irq_get_irq_data(ctx->virq)); +} + +static void dcut_queue_rx(struct dcut_ctx *ctx, unsigned int len, unsigned int visible) +{ + unsigned int i; + + for (i = 0; i < len; i++) + ctx->rx_q[i] = 0x20 + (i * 13) % 0x5f; + ctx->rx_len = len; + ctx->rx_visible = visible; +} + +static unsigned int dcut_queue_tx(struct dcut_ctx *ctx, const char *s) +{ + return kfifo_in(&ctx->state->port.xmit_fifo, s, strlen(s)); +} + +/* What the port handed to the TTY layer (flip buffers not yet pushed). */ +static unsigned int dcut_flip_read(struct dcut_ctx *ctx, u8 *out, unsigned int max) +{ + struct tty_buffer *b; + unsigned int n = 0, i; + + for (b = ctx->state->port.buf.head; b; b = b->next) + for (i = b->read; i < b->used && n < max; i++) + out[n++] = *char_buf_ptr(b, i); + + return n; +} + +static unsigned int dcut_drain(struct dcut_ctx *ctx, bool *got) +{ + unsigned long flags; + + spin_lock_irqsave(&ctx->dcuart.lock, flags); + *got = dcuart_drain_rx(&ctx->dcuart); + spin_unlock_irqrestore(&ctx->dcuart.lock, flags); + + return ctx->dcuart.port.icount.rx; +} + +static unsigned int dcut_tx_chars(struct dcut_ctx *ctx, bool tick) +{ + unsigned long flags; + unsigned int pending; + + uart_port_lock_irqsave(&ctx->dcuart.port, &flags); + pending = dcuart_tx_chars(&ctx->dcuart, tick); + uart_port_unlock_irqrestore(&ctx->dcuart.port, flags); + + return pending; +} + +/* RX */ + +static void dcut_drain_rx_bytes(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[16]; + bool got; + + dcut_queue_rx(ctx, 5, 5); + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 5); + KUNIT_EXPECT_TRUE(test, got); + /* Each byte taken from bits [15:8] of the byte FIFO register. */ + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 5); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 5); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 2); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 5); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.buf_overrun, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_empty(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[4]; + bool got; + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 0); + KUNIT_EXPECT_FALSE(test, got); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 1); + KUNIT_EXPECT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_clamps_pass(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + static u8 out[DCUT_LOG]; + bool got; + + /* More than a FIFO's worth: one FIFO_SIZE pass, then the rest. */ + dcut_queue_rx(ctx, 3000, 3000); + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 3000); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 3000); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 3000 - FIFO_SIZE); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[2], 0); + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 3000); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 3000); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_rx_arrivals(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u8 out[16]; + bool got; + + /* Data that arrives while draining is drained too. */ + dcut_queue_rx(ctx, 10, 3); + ctx->rx_chunk[0] = 4; + ctx->rx_chunk[1] = 3; + ctx->rx_nchunk = 2; + + KUNIT_EXPECT_EQ(test, dcut_drain(ctx, &got), 10); + KUNIT_ASSERT_EQ(test, ctx->rx_ncounts, 4); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[0], 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[1], 4); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[2], 3); + KUNIT_EXPECT_EQ(test, ctx->rx_counts[3], 0); + KUNIT_ASSERT_EQ(test, dcut_flip_read(ctx, out, sizeof(out)), 10); + KUNIT_EXPECT_MEMEQ(test, out, ctx->rx_q, 10); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_interrupt_rx(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_queue_rx(ctx, 4, 4); + WRITE_ONCE(*flag, ctx->dcuart.irq_rx | ctx->dcuart.irq_tx | DCUT_OTHERS); + + KUNIT_EXPECT_EQ(test, dcuart_interrupt(0, &ctx->dcuart), IRQ_HANDLED); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.rx, 4); + KUNIT_EXPECT_EQ(test, ctx->rx_visible, 0); + /* Only this channel's RX flag is cleared (write-one-to-clear). */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), ctx->dcuart.irq_rx); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_interrupt_other_channel(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_queue_rx(ctx, 4, 4); + WRITE_ONCE(*flag, DCUT_OTHERS | IRQ_RX(DCUT_CHANNEL + 1) | IRQ_TX(DCUT_CHANNEL - 1)); + + KUNIT_EXPECT_EQ(test, dcuart_interrupt(0, &ctx->dcuart), IRQ_NONE); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), DCUT_OTHERS | IRQ_RX(DCUT_CHANNEL + 1) | + IRQ_TX(DCUT_CHANNEL - 1)); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.rx, 0); +} + +/* Interrupt mask, startup and shutdown */ + +static void dcut_irq_bits_per_channel(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, IRQ_TX(0), BIT(0)); + KUNIT_EXPECT_EQ(test, IRQ_RX(0), BIT(1)); + KUNIT_EXPECT_EQ(test, IRQ_TX(3), BIT(6)); + KUNIT_EXPECT_EQ(test, IRQ_RX(3), BIT(7)); + KUNIT_EXPECT_EQ(test, IRQ_RX(MAX_CHANNELS - 1), BIT(31)); +} + +static void dcut_irq_mask_other_channels(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + WRITE_ONCE(*mask, DCUT_OTHERS); + WRITE_ONCE(*flag, 0); + + dcuart_irq_enable(dc, dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx); + /* Stale latched flag cleared before the unmask. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), dc->irq_rx); + + dcuart_irq_update(dc, dc->irq_tx, true); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx | dc->irq_tx); + + dcuart_irq_disable(dc, dc->irq_tx | dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); + dcuart_irq_disable(dc, dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_irq_mode(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + u32 *flag = dcut_reg(ctx->irqregs, IRQ_FLAG); + + dcut_setup_irq(test, ctx); + WRITE_ONCE(*mask, DCUT_OTHERS | dc->irq_tx); + WRITE_ONCE(*flag, 0); + + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->cfg, CONFIG_RX_THRESH)), 1); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->cfg, CONFIG_TX_THRESH)), FIFO_SIZE); + /* RX unmasked, TX masked, the other channels untouched. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS | dc->irq_rx); + KUNIT_EXPECT_EQ(test, READ_ONCE(*flag), dc->irq_rx); + KUNIT_EXPECT_TRUE(test, dcut_irq_enabled(ctx)); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_NE(test, ctx->state->port.closing_wait, ASYNC_CLOSING_WAIT_NONE); + + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, dcut_irq_enabled(ctx)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_sw_drain(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + u32 *mask = dcut_reg(ctx->irqregs, IRQ_MASK); + + dc->sw_drain = true; + WRITE_ONCE(*mask, DCUT_OTHERS | dc->irq_rx | dc->irq_tx); + + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + /* No RX interrupt: the drain timer polls the channel. */ + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, READ_ONCE(*mask), DCUT_OTHERS); +} + +static void dcut_startup_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->sw_drain = true; + dc->never_wait = true; + + /* A close must not wait for a reader that may never come. */ + KUNIT_EXPECT_EQ(test, dcuart_startup(&dc->port), 0); + KUNIT_EXPECT_EQ(test, ctx->state->port.closing_wait, ASYNC_CLOSING_WAIT_NONE); + dcuart_shutdown(&dc->port); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); +} + +/* TX */ + +static void dcut_tx_chars_room_limits(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "abcdefgh"); + ctx->tx_room = 5; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 3); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 5); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "abcde", 5); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.icount.tx, 5); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); + + /* The rest when room appears. */ + ctx->tx_room = 64; + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "abcdefgh", 8); +} + +static void dcut_tx_chars_exact_room(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "12345678"); + ctx->tx_room = 8; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 8); + KUNIT_EXPECT_EQ(test, ctx->tx_room, 0); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_chars_nothing_queued(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->tx_room = 8; + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + /* Not even a room read. */ + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); +} + +static void dcut_tx_chars_no_reader_drops(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "wxyz"); + ctx->tx_room = 0; + + /* Without a tick (start_tx), a full FIFO is not counted. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 4); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + + /* TX_STUCK_TICKS ticks without room: the queue goes. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 4); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 1); + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 0); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_chars_progress_resets(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + dcut_queue_tx(ctx, "abcd"); + ctx->dcuart.tx_stuck_ticks = 1; + ctx->tx_room = 2; + + /* Some room: progress, so the stuck count starts over. */ + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 2); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 0); + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, true), 2); + KUNIT_EXPECT_EQ(test, ctx->dcuart.tx_stuck_ticks, 1); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 2); + KUNIT_EXPECT_MEMEQ(test, ctx->tx_log, "ab", 2); +} + +static void dcut_tx_chars_x_char(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + + ctx->dcuart.never_wait = true; + ctx->dcuart.port.x_char = 0x13; + ctx->tx_room = 1; + + KUNIT_EXPECT_EQ(test, dcut_tx_chars(ctx, false), 0); + KUNIT_ASSERT_EQ(test, ctx->tx_len, 1); + KUNIT_EXPECT_EQ(test, ctx->tx_log[0], 0x13); + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.x_char, 0); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_tx_empty(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct uart_port *port = &ctx->dcuart.port; + + ctx->tx_room = 0; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), 0); + ctx->tx_room = 1; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), TIOCSER_TEMT); + + /* Never waiting: always empty, whatever the FIFO says. */ + ctx->dcuart.never_wait = true; + ctx->tx_room = 0; + ctx->tx_free_reads = 0; + KUNIT_EXPECT_EQ(test, dcuart_tx_empty(port), TIOCSER_TEMT); + KUNIT_EXPECT_EQ(test, ctx->tx_free_reads, 0); +} + +static void dcut_start_tx_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dcut_queue_tx(ctx, "hello"); + ctx->tx_room = 2; + + /* What does not fit goes from the timer. */ + dcuart_start_tx(&dc->port); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 2); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); +} + +static void dcut_start_tx_waiting(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + /* + * Without never_wait every byte goes through dockchannel_wait_putc(), + * which reads the register buffer directly. + */ + WRITE_ONCE(*dcut_reg(ctx->data, DATA_TX_FREE), 1); + dcut_queue_tx(ctx, "xyz"); + + dcuart_start_tx(&dc->port); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_EQ(test, dc->port.icount.tx, 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*dcut_reg(ctx->data, DATA_TX8)), 'z'); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 0); +} + +static void dcut_drain_timer_sw_drain(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dc->sw_drain = true; + dcut_queue_rx(ctx, 3, 3); + dcut_queue_tx(ctx, "ok"); + ctx->tx_room = 16; + + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, dc->port.icount.rx, 3); + KUNIT_EXPECT_EQ(test, ctx->tx_len, 2); + /* A software-drained channel keeps polling. */ + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, ctx->violations, 0); +} + +static void dcut_drain_timer_no_reader(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct dcuart_port *dc = &ctx->dcuart; + + dc->never_wait = true; + dcut_queue_tx(ctx, "abc"); + ctx->tx_room = 0; + + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_TRUE(test, timer_pending(&dc->drain_timer)); + timer_delete_sync(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 3); + + /* The second tick without room drops the queue and stops the timer. */ + dcuart_drain_timer(&dc->drain_timer); + KUNIT_EXPECT_EQ(test, kfifo_len(&ctx->state->port.xmit_fifo), 0); + KUNIT_EXPECT_FALSE(test, timer_pending(&dc->drain_timer)); + KUNIT_EXPECT_EQ(test, ctx->rx_ncounts, 0); +} + +/* termios and port ops */ + +static void dcut_set_termios(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct ktermios t = { + .c_cflag = B9600 | CS7 | PARENB | PARODD | CRTSCTS, + }; + + dcuart_set_termios(&ctx->dcuart.port, &t, NULL); + /* 8N1 at 115200, CLOCAL, whatever was asked. */ + KUNIT_EXPECT_EQ(test, t.c_cflag & CSIZE, CS8); + KUNIT_EXPECT_FALSE(test, t.c_cflag & PARENB); + KUNIT_EXPECT_TRUE(test, t.c_cflag & CLOCAL); + KUNIT_EXPECT_EQ(test, tty_termios_baud_rate(&t), 115200); + KUNIT_EXPECT_EQ(test, t.c_ispeed, 115200); + KUNIT_EXPECT_EQ(test, t.c_ospeed, 115200); + /* 10 bits a character at 115200 baud, rounded up. */ + KUNIT_EXPECT_EQ(test, ctx->dcuart.port.frame_time, 86806); +} + +static void dcut_port_ops(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct uart_port *port = &ctx->dcuart.port; + + KUNIT_EXPECT_EQ(test, dcuart_get_mctrl(port), TIOCM_CAR | TIOCM_DSR | TIOCM_CTS); + KUNIT_EXPECT_STREQ(test, dcuart_type(port), "Apple DockChannel UART"); + port->type = PORT_UNKNOWN; + KUNIT_EXPECT_NULL(test, dcuart_type(port)); + dcuart_config_port(port, 0); + KUNIT_EXPECT_EQ(test, port->type, PORT_UNKNOWN); + dcuart_config_port(port, UART_CONFIG_TYPE); + KUNIT_EXPECT_EQ(test, port->type, PORT_GENERIC); +} + +/* Console helpers (apple_dockchannel.h, shared with the earlycon) */ + +static void dcut_console_putc_room(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + void __iomem *data = ctx->dcuart.port.membase; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + struct dockchannel_tx tx; + + dockchannel_tx_begin(&tx); + WRITE_ONCE(*tx_free, 2); + dockchannel_console_putc(data, &tx, 'a'); + dockchannel_console_putc(data, &tx, 'b'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + KUNIT_EXPECT_EQ(test, tx.room, 0); + + /* Room used up: read again; it reads 0, so the rest is dropped. */ + WRITE_ONCE(*tx_free, 0); + dockchannel_console_putc(data, &tx, 'c'); + KUNIT_EXPECT_TRUE(test, tx.full); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + /* ... without reading again in the same write. */ + WRITE_ONCE(*tx_free, 5); + dockchannel_console_putc(data, &tx, 'd'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'b'); + + /* The next write starts over. */ + dockchannel_tx_begin(&tx); + dockchannel_console_putc(data, &tx, 'e'); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 'e'); + KUNIT_EXPECT_EQ(test, tx.room, 4); + KUNIT_EXPECT_FALSE(test, tx.full); +} + +static void dcut_wait_putc_no_reader(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + void __iomem *data = ctx->dcuart.port.membase; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + bool no_reader = false; + + WRITE_ONCE(*tx8, DCUT_POISON); + WRITE_ONCE(*tx_free, 0); + dockchannel_wait_putc(data, &no_reader, 'q'); + KUNIT_EXPECT_TRUE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + dockchannel_wait_putc(data, &no_reader, 'r'); + KUNIT_EXPECT_TRUE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + + /* Room again: write, and wait normally from now on. */ + WRITE_ONCE(*tx_free, 1); + dockchannel_wait_putc(data, &no_reader, 's'); + KUNIT_EXPECT_FALSE(test, no_reader); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), 's'); +} + +static void dcut_console_setup(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct console co = dcuart_console; + + co.index = -1; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + co.index = MAX_PORTS; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + + if (dcuart_ports[DCUT_CON]) + kunit_skip(test, "port %d is in use", DCUT_CON); + co.index = DCUT_CON; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), -ENODEV); + dcuart_ports[DCUT_CON] = &ctx->dcuart; + ctx->con_slot = true; + KUNIT_EXPECT_EQ(test, dcuart_console_setup(&co, NULL), 0); +} + +static void dcut_console_write_never_wait(struct kunit *test) +{ + struct dcut_ctx *ctx = test->priv; + struct console co = dcuart_console; + u32 *tx_free = dcut_reg(ctx->data, DATA_TX_FREE); + u32 *tx8 = dcut_reg(ctx->data, DATA_TX8); + + if (dcuart_ports[DCUT_CON]) + kunit_skip(test, "port %d is in use", DCUT_CON); + dcuart_ports[DCUT_CON] = &ctx->dcuart; + ctx->con_slot = true; + ctx->dcuart.never_wait = true; + co.index = DCUT_CON; + + /* No room: nothing written, and the write returns. */ + WRITE_ONCE(*tx8, DCUT_POISON); + WRITE_ONCE(*tx_free, 0); + dcuart_write(&co, "hi\n", 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), DCUT_POISON); + + WRITE_ONCE(*tx_free, 64); + dcuart_write(&co, "hi\n", 3); + KUNIT_EXPECT_EQ(test, READ_ONCE(*tx8), '\n'); + KUNIT_EXPECT_EQ(test, ctx->dcuart.console_tx.room, 64 - 4); +} + +static struct kunit_case dcuart_test_cases[] = { + KUNIT_CASE(dcut_drain_rx_bytes), + KUNIT_CASE(dcut_drain_rx_empty), + KUNIT_CASE(dcut_drain_rx_clamps_pass), + KUNIT_CASE(dcut_drain_rx_arrivals), + KUNIT_CASE(dcut_interrupt_rx), + KUNIT_CASE(dcut_interrupt_other_channel), + KUNIT_CASE(dcut_irq_bits_per_channel), + KUNIT_CASE(dcut_irq_mask_other_channels), + KUNIT_CASE(dcut_startup_irq_mode), + KUNIT_CASE(dcut_startup_sw_drain), + KUNIT_CASE(dcut_startup_never_wait), + KUNIT_CASE(dcut_tx_chars_room_limits), + KUNIT_CASE(dcut_tx_chars_exact_room), + KUNIT_CASE(dcut_tx_chars_nothing_queued), + KUNIT_CASE(dcut_tx_chars_no_reader_drops), + KUNIT_CASE(dcut_tx_chars_progress_resets), + KUNIT_CASE(dcut_tx_chars_x_char), + KUNIT_CASE(dcut_tx_empty), + KUNIT_CASE(dcut_start_tx_never_wait), + KUNIT_CASE(dcut_start_tx_waiting), + KUNIT_CASE(dcut_drain_timer_sw_drain), + KUNIT_CASE(dcut_drain_timer_no_reader), + KUNIT_CASE(dcut_set_termios), + KUNIT_CASE(dcut_port_ops), + KUNIT_CASE(dcut_console_putc_room), + KUNIT_CASE(dcut_wait_putc_no_reader), + KUNIT_CASE(dcut_console_setup), + KUNIT_CASE(dcut_console_write_never_wait), + {} +}; + +static struct kunit_suite dcuart_test_suite = { + .name = "apple-dockchannel-uart", + .init = dcut_init, + .exit = dcut_exit, + .test_cases = dcuart_test_cases, +}; + +kunit_test_suite(dcuart_test_suite); diff --git a/drivers/tty/serial/apple_dockchannel_uart.c b/drivers/tty/serial/apple_dockchannel_uart.c index 7150cf1cca350e..1411e84708c0d0 100644 --- a/drivers/tty/serial/apple_dockchannel_uart.c +++ b/drivers/tty/serial/apple_dockchannel_uart.c @@ -18,6 +18,10 @@ #include "apple_dockchannel.h" +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include +#endif + #define FIFO_SIZE 0x800 #define IRQ_MASK 0x0 @@ -81,6 +85,34 @@ static inline struct dcuart_port *port_to_dc(struct uart_port *port) return container_of(port, struct dcuart_port, port); } +/* + * Data FIFO accesses of the RX drain and the TX paths. They are functions so + * that the KUnit test can model the FIFO behind them. + */ +static u32 dcuart_rx_readl(struct dcuart_port *dcuart, u32 reg) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_rx_readl, dcuart, reg); +#endif + return readl_relaxed(dcuart->port.membase + reg); +} + +static u32 dcuart_tx_free(struct dcuart_port *dcuart) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_tx_free, dcuart); +#endif + return readl(dcuart->port.membase + DATA_TX_FREE); +} + +static void dcuart_tx_put(struct dcuart_port *dcuart, u8 ch) +{ +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(dcuart_tx_put, dcuart, ch); +#endif + writel(ch, dcuart->port.membase + DATA_TX8); +} + static void dcuart_irq_update(struct dcuart_port *dcuart, u32 bits, bool enable) { @@ -186,7 +218,7 @@ static bool dcuart_drain_rx(struct dcuart_port *dcuart) bool got = false; int left; - while ((left = readl_relaxed(dcuart->port.membase + DATA_RX_COUNT))) { + while ((left = dcuart_rx_readl(dcuart, DATA_RX_COUNT))) { left = min_t(size_t, left, FIFO_SIZE); while (left) { /* @@ -195,7 +227,7 @@ static bool dcuart_drain_rx(struct dcuart_port *dcuart) */ char c; - c = readl_relaxed(dcuart->port.membase + DATA_RX8) >> 8; + c = dcuart_rx_readl(dcuart, DATA_RX8) >> 8; uart_insert_char(&dcuart->port, 0, 0, c, TTY_NORMAL); dcuart->port.icount.rx++; left--; @@ -246,8 +278,8 @@ static unsigned int dcuart_tx_chars(struct dcuart_port *dcuart, bool tick) if (!queued && !port->x_char) return 0; - pending = uart_port_tx_limited(port, ch, readl(port->membase + DATA_TX_FREE), - true, writel(ch, port->membase + DATA_TX8), ({})); + pending = uart_port_tx_limited(port, ch, dcuart_tx_free(dcuart), + true, dcuart_tx_put(dcuart, ch), ({})); if (!pending || pending < queued) { dcuart->tx_stuck_ticks = 0; return pending; @@ -309,7 +341,7 @@ static void dcuart_drain_timer(struct timer_list *t) static unsigned int dcuart_tx_empty(struct uart_port *port) { if (!port_to_dc(port)->never_wait) - return (readl(port->membase + DATA_TX_FREE) != 0) ? TIOCSER_TEMT : 0; + return (dcuart_tx_free(port_to_dc(port)) != 0) ? TIOCSER_TEMT : 0; return TIOCSER_TEMT; } @@ -567,3 +599,7 @@ device_initcall(dcuart_init); MODULE_AUTHOR("Yureka Lilian "); MODULE_DESCRIPTION("Apple DockChannel UART driver"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST) +#include "apple_dockchannel_uart-test.c" +#endif diff --git a/drivers/tty/serial/apple_dockchannel_uart.kunitconfig b/drivers/tty/serial/apple_dockchannel_uart.kunitconfig new file mode 100644 index 00000000000000..81879d1b311880 --- /dev/null +++ b/drivers/tty/serial/apple_dockchannel_uart.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_TTY=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL_KUNIT_TEST=y From 170595177a0e8589a5d8062a5482a3c626a10eb8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:03:25 +1100 Subject: [PATCH 0564/1514] soc: apple: pmgr-misc: KUnit: leave a bound driver and the system tree alone The fabric cases publish their own instance as the driver's single instance and reset idle_fabric_pstate on exit. Where the driver is bound to real hardware (KUNIT_ALL_TESTS on a Mac) that took over the live instance and wiped a boot-time value of the parameter. Skip the cases when an instance is already published, and save and restore the parameter around each case. The devicetree cases look the voters and the PMP up in the whole tree, so on a Mac they would find the system's own nodes. Run them only when the fixture's nodes are the only ones. Signed-off-by: Ryan Murray --- drivers/soc/apple/apple-pmgr-fabric-test.c | 53 +++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/apple-pmgr-fabric-test.c b/drivers/soc/apple/apple-pmgr-fabric-test.c index 4ba6524c648887..85131e5923a34e 100644 --- a/drivers/soc/apple/apple-pmgr-fabric-test.c +++ b/drivers/soc/apple/apple-pmgr-fabric-test.c @@ -21,6 +21,7 @@ struct pf_test { u32 *votes; bool cpus_min; bool published; + unsigned int saved_idle_pstate; }; static const struct regmap_config pf_vote_regmap_config = { @@ -44,10 +45,19 @@ static int pf_test_init(struct kunit *test) struct pf_test *f; unsigned int i; + /* + * The cases drive the driver's single instance and its parameter. + * Where the driver runs on real hardware they would take both over. + */ + if (smp_load_acquire(&apple_pmgr_misc_inst)) + kunit_skip(test, "apple-pmgr-misc is bound on this system"); + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); if (!f) return -ENOMEM; misc = &f->misc; + f->saved_idle_pstate = READ_ONCE(idle_fabric_pstate); + WRITE_ONCE(idle_fabric_pstate, 0); f->fabric = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); f->dcs = kunit_kzalloc(test, sizeof(u32), GFP_KERNEL); f->votes = kunit_kzalloc(test, 8 * sizeof(u32), GFP_KERNEL); @@ -95,7 +105,7 @@ static void pf_test_exit(struct kunit *test) return; cancel_delayed_work_sync(&f->misc.idle_work); cancel_delayed_work_sync(&f->misc.idle_work_prompt); - WRITE_ONCE(idle_fabric_pstate, 0); + WRITE_ONCE(idle_fabric_pstate, f->saved_idle_pstate); if (f->published) { /* Pairs with the acquire in the driver's readers. */ smp_store_release(&apple_pmgr_misc_inst, NULL); @@ -468,6 +478,39 @@ static void pf_match_data_test(struct kunit *test) * never freed; each case adds and removes its own power-state children. */ static struct device_node *pf_dt_pmgr; + +/* + * The driver looks its voters and the PMP up in the whole tree. Nodes of + * the system's own devicetree would join the fixture's, so the devicetree + * cases only run where the fixture's are the only ones. + */ +static bool pf_dt_foreign(const char *compatible) +{ + struct device_node *np, *box = pf_dt_pmgr ? pf_dt_pmgr->parent : NULL; + + for_each_compatible_node(np, NULL, compatible) { + struct device_node *p; + bool ours = false; + + for (p = np->parent; p && box; p = p->parent) + if (p == box) { + ours = true; + break; + } + if (!ours) { + of_node_put(np); + return true; + } + } + return false; +} + +static void pf_dt_require_fixture_only(struct kunit *test) +{ + if (pf_dt_foreign("apple,pmgr-pwrstate") || + pf_dt_foreign("apple,t6000-pmp-v2")) + kunit_skip(test, "the system devicetree describes PMGR or PMP nodes"); +} static u32 pf_dt_regs[0x50]; static const struct regmap_config pf_dt_regmap_config = { @@ -543,6 +586,8 @@ static void pf_dt_voters_test(struct kunit *test) struct apple_pmgr_misc *misc = &f->misc; struct regmap *map = syscon_node_to_regmap(pf_dt_pmgr); + pf_dt_require_fixture_only(test); + KUNIT_ASSERT_FALSE(test, IS_ERR(map)); KUNIT_EXPECT_TRUE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); /* Matched by label, in the order of apple_pmgr_fabric_voters. */ @@ -572,6 +617,8 @@ static void pf_dt_voters_missing_test(struct kunit *test) struct pf_test *f = test->priv; struct apple_pmgr_misc *misc = &f->misc; + pf_dt_require_fixture_only(test); + /* Desktop without ISP: the governor must never lower. */ KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, 2)); KUNIT_EXPECT_NULL(test, misc->votes[2].regmap); @@ -609,6 +656,8 @@ static void pf_dt_voters_duplicate_test(struct kunit *test) struct pf_test *f = test->priv; struct apple_pmgr_misc *misc = &f->misc; + pf_dt_require_fixture_only(test); + /* A second gfx node must not stand in for the missing isp_sys. */ KUNIT_EXPECT_FALSE(test, pf_dt_find(test, misc, c, ARRAY_SIZE(c))); KUNIT_EXPECT_NOT_NULL(test, misc->votes[0].regmap); @@ -624,6 +673,8 @@ static void pf_dt_pmp_unbound_test(struct kunit *test) struct apple_pmgr_misc *misc = &f->misc; struct of_changeset cs; + pf_dt_require_fixture_only(test); + /* PMP described but no driver bound: sleep takes the path without it. */ misc->pmp_owned = true; pf_dt_apply(test, &cs, c, ARRAY_SIZE(c)); From 4a92d18ffddf7b0686ce95325a04abf9984d363e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:03:26 +1100 Subject: [PATCH 0565/1514] tty: serial: apple_dockchannel_uart: KUnit: pass other ports through The FIFO stubs are active for the test task, so an interrupt that runs a real DockChannel port on top of it reaches them too. The TX stubs took that port's bytes into the model and the RX stub returned nothing. Give any port other than the test's its own registers, as the driver would. Signed-off-by: Ryan Murray --- .../tty/serial/apple_dockchannel_uart-test.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/drivers/tty/serial/apple_dockchannel_uart-test.c b/drivers/tty/serial/apple_dockchannel_uart-test.c index 2a2c3ebcb71d18..0556266de9628e 100644 --- a/drivers/tty/serial/apple_dockchannel_uart-test.c +++ b/drivers/tty/serial/apple_dockchannel_uart-test.c @@ -61,15 +61,18 @@ static u32 *dcut_reg(u8 *base, unsigned int off) return (u32 *)(base + off); } +/* + * The stubs are active for the test task, so an interrupt that runs a real + * DockChannel port on top of it lands here too: give that port its own + * registers, as the driver would. + */ static u32 dcut_rx_readl(struct dcuart_port *dcuart, u32 reg) { struct dcut_ctx *ctx = kunit_get_current_test()->priv; u8 c; - if (dcuart != &ctx->dcuart) { - ctx->violations++; - return 0; - } + if (dcuart != &ctx->dcuart) + return readl_relaxed(dcuart->port.membase + reg); switch (reg) { case DATA_RX_COUNT: @@ -99,6 +102,9 @@ static u32 dcut_tx_free(struct dcuart_port *dcuart) { struct dcut_ctx *ctx = kunit_get_current_test()->priv; + if (dcuart != &ctx->dcuart) + return readl(dcuart->port.membase + DATA_TX_FREE); + ctx->tx_free_reads++; return ctx->tx_room; } @@ -107,6 +113,11 @@ static void dcut_tx_put(struct dcuart_port *dcuart, u8 ch) { struct dcut_ctx *ctx = kunit_get_current_test()->priv; + if (dcuart != &ctx->dcuart) { + writel(ch, dcuart->port.membase + DATA_TX8); + return; + } + if (!ctx->tx_room || ctx->tx_len >= DCUT_LOG) { ctx->violations++; return; From 7b00d12ea67e7a2481a3dc22d75375725c9d5518 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:07:37 +1100 Subject: [PATCH 0566/1514] Bluetooth: hci_bcm4377: keep the transfer ring producer index on the host bcm4377_enqueue() read the producer index of a transfer ring back from ring_state, the coherent buffer it shares with the device, and used it to place the next entry: offset = head * (entry + footer). The device also writes that buffer (the completion ring heads and the transfer ring tails), and only (head + 1) % n_entries was compared with the tail, so a head of n_entries or more placed the entry and its payload outside the ring. The completion path read the same value back to advance it. Keep the index in struct bcm4377_transfer_ring and only write it out to ring_state, through one helper that every place setting a head now uses: the enqueue, the event path, ring creation (0, and 0xf for device-to-host rings) and the PCI reset (for the control ring, which is not recreated). The device sees the same values as before. Add the driver's first KUnit cases (CONFIG_BT_HCIBCM4377_KUNIT_TEST), built into the driver like the MT7932 tests. The case puts a head past the last slot, and later 0xffff, into the shared state and checks that the entries land in the host's next slots and that the bytes after the ring stay untouched. Fixes: 8a06127602de ("Bluetooth: hci_bcm4377: Add new driver for BCM4377 PCIe boards") Signed-off-by: Ryan Murray --- MAINTAINERS | 1 + drivers/bluetooth/Kconfig | 11 ++++ drivers/bluetooth/hci_bcm4377.c | 34 +++++++--- drivers/bluetooth/hci_bcm4377_test.c | 96 ++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 drivers/bluetooth/hci_bcm4377_test.c diff --git a/MAINTAINERS b/MAINTAINERS index 5c8fc89e51d008..a7532aef375f97 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2774,6 +2774,7 @@ F: Documentation/hwmon/macsmc-hwmon.rst F: Documentation/power/apple-s2idle.rst F: arch/arm64/boot/dts/apple/ F: drivers/bluetooth/hci_bcm4377.c +F: drivers/bluetooth/hci_bcm4377_test.c F: tools/asahi/bcm4377-sleep-config-tests.* F: drivers/clk/clk-apple-nco.c F: drivers/cpufreq/apple-soc-cpufreq.c diff --git a/drivers/bluetooth/Kconfig b/drivers/bluetooth/Kconfig index 002a8985ca04fd..a77809e8f521c8 100644 --- a/drivers/bluetooth/Kconfig +++ b/drivers/bluetooth/Kconfig @@ -345,6 +345,17 @@ config BT_HCIBCM4377 Say Y here to compile support for HCI BCM4377 family devices into the kernel or say M to compile it as module (hci_bcm4377). +config BT_HCIBCM4377_KUNIT_TEST + bool "KUnit tests for the HCI BCM4377 PCIe driver" if !KUNIT_ALL_TESTS + depends on KUNIT=y && BT_HCIBCM4377 + default KUNIT_ALL_TESTS + help + Build KUnit tests into the BCM4377 family PCIe driver. They check, + without radio hardware, that a transfer ring is filled at the + host's own producer index whatever the shared ring state holds. + + If unsure, say N. + config BT_HCIBPA10X tristate "HCI BPA10x USB driver" depends on BT_HCIUART diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 02cc8fccbc27c2..3643e2f236347f 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -440,6 +440,7 @@ struct bcm4377_transfer_ring { size_t mapped_payload_size; u8 completion_ring; u16 n_entries; + u16 head; u8 generation; bool sync; @@ -671,6 +672,19 @@ static void bcm4377_ring_doorbell(struct bcm4377_data *bcm4377, u8 doorbell, iowrite32(db, bcm4377->bar0 + BCM4377_BAR0_DOORBELL); } +/* + * The producer index of a transfer ring is kept by the host. The copy in + * ring_state is shared with the device and only ever written here, never + * read back, so what the device writes there cannot move the slot the host + * fills next. + */ +static void bcm4377_set_xfer_head(struct bcm4377_data *bcm4377, + struct bcm4377_transfer_ring *ring, u16 head) +{ + ring->head = head; + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(head); +} + static int bcm4377_extract_msgid(struct bcm4377_data *bcm4377, struct bcm4377_transfer_ring *ring, u16 raw_msgid, u8 *msgid) @@ -739,9 +753,8 @@ static void bcm4377_handle_event(struct bcm4377_data *bcm4377, hci_recv_frame(bcm4377->hdev, skb); out: - head = le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]); - head = (head + 1) % ring->n_entries; - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(head); + head = (ring->head + 1) % ring->n_entries; + bcm4377_set_xfer_head(bcm4377, ring, head); bcm4377_ring_doorbell(bcm4377, ring->doorbell, head); @@ -984,7 +997,7 @@ static int bcm4377_enqueue(struct bcm4377_data *bcm4377, spin_lock_irqsave(&ring->lock, flags); - head = le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]); + head = ring->head; tail = le16_to_cpu(bcm4377->ring_state->xfer_ring_tail[ring->ring_id]); new_head = (head + 1) % ring->n_entries; @@ -1041,8 +1054,7 @@ static int bcm4377_enqueue(struct bcm4377_data *bcm4377, dev_dbg(&bcm4377->pdev->dev, "updating head for transfer queue #%d to %d\n", ring->ring_id, new_head); - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = - cpu_to_le16(new_head); + bcm4377_set_xfer_head(bcm4377, ring, new_head); if (!ring->sync) bcm4377_ring_doorbell(bcm4377, ring->doorbell, new_head); @@ -1147,7 +1159,7 @@ static int bcm4377_create_transfer_ring(struct bcm4377_data *bcm4377, msg.flags = cpu_to_le16(flags); msg.footer_size = ring->payload_size / 4; - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = 0; + bcm4377_set_xfer_head(bcm4377, ring, 0); bcm4377->ring_state->xfer_ring_tail[ring->ring_id] = 0; ring->generation++; spin_unlock_irqrestore(&ring->lock, spinlock_flags); @@ -1180,8 +1192,7 @@ static int bcm4377_create_transfer_ring(struct bcm4377_data *bcm4377, * to reply by acknowledging them in the completion ring */ if (ring->virtual || ring->d2h_buffers_only) { - bcm4377->ring_state->xfer_ring_head[ring->ring_id] = - cpu_to_le16(0xf); + bcm4377_set_xfer_head(bcm4377, ring, 0xf); bcm4377_ring_doorbell(bcm4377, ring->doorbell, 0xf); } @@ -1450,6 +1461,7 @@ static int bcm4377_pci_reset(struct bcm4377_data *bcm4377) WRITE_ONCE(bcm4377->rti_status, 0); memset(bcm4377->ring_state, 0, sizeof(*bcm4377->ring_state)); + bcm4377->control_h2d_ring.head = 0; bcm4377->control_h2d_ring.generation = 0; bcm4377->control_ack_ring.enabled = false; bitmap_zero(bcm4377->control_h2d_ring.msgids, @@ -3397,3 +3409,7 @@ MODULE_FIRMWARE("brcm/brcmbt4387*.bin"); MODULE_FIRMWARE("brcm/brcmbt4387*.ptb"); MODULE_FIRMWARE("brcm/brcmbt4388*.bin"); MODULE_FIRMWARE("brcm/brcmbt4388*.ptb"); + +#if IS_ENABLED(CONFIG_BT_HCIBCM4377_KUNIT_TEST) +#include "hci_bcm4377_test.c" +#endif diff --git a/drivers/bluetooth/hci_bcm4377_test.c b/drivers/bluetooth/hci_bcm4377_test.c new file mode 100644 index 00000000000000..a4f0c0ab06cb84 --- /dev/null +++ b/drivers/bluetooth/hci_bcm4377_test.c @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the hci_bcm4377 ring bookkeeping. Built as part of + * hci_bcm4377.c, so the tests reach its static helpers. They run without + * the radio: BAR0 and the shared ring state are plain kernel memory. + */ +#include + +#define BCM4377_TEST_BAR0_SIZE 0x200 + +struct bcm4377_test_ctx { + struct bcm4377_data *bcm4377; + struct pci_dev *pdev; +}; + +static int bcm4377_test_init(struct kunit *test) +{ + struct bcm4377_test_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->pdev = kunit_kzalloc(test, sizeof(*ctx->pdev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->pdev); + ctx->pdev->dev.init_name = "bcm4377-kunit"; + ctx->bcm4377 = kunit_kzalloc(test, sizeof(*ctx->bcm4377), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->bcm4377); + ctx->bcm4377->pdev = ctx->pdev; + ctx->bcm4377->ring_state = + kunit_kzalloc(test, sizeof(*ctx->bcm4377->ring_state), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->bcm4377->ring_state); + ctx->bcm4377->bar0 = (void __iomem *)kunit_kzalloc(test, BCM4377_TEST_BAR0_SIZE, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, (void __force *)ctx->bcm4377->bar0); + test->priv = ctx; + return 0; +} + +/* + * The slot the host fills comes from its own producer index: whatever the + * device leaves in the shared head, the entry lands inside the ring. + */ +static void bcm4377_enqueue_uses_host_head_test(struct kunit *test) +{ + struct bcm4377_test_ctx *ctx = test->priv; + struct bcm4377_data *bcm4377 = ctx->bcm4377; + struct bcm4377_transfer_ring *ring = &bcm4377->hci_h2d_ring; + const size_t slot = sizeof(struct bcm4377_xfer_ring_entry) + 16; + const size_t guard = slot; + struct bcm4377_xfer_ring_entry *entry; + u8 data[8], *buf; + size_t i; + + ring->ring_id = BCM4377_XFER_RING_HCI_H2D; + ring->n_entries = 4; + ring->payload_size = 16; + ring->sync = true; + spin_lock_init(&ring->lock); + buf = kunit_kzalloc(test, ring->n_entries * slot + guard, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + ring->ring = buf; + memset(data, 0x5a, sizeof(data)); + + /* A head one past the last slot, as the device could write it. */ + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(4); + KUNIT_ASSERT_EQ(test, bcm4377_enqueue(bcm4377, ring, data, sizeof(data), false), 0); + + for (i = 0; i < guard; i++) + KUNIT_EXPECT_EQ(test, buf[ring->n_entries * slot + i], 0); + entry = (void *)buf; + KUNIT_EXPECT_EQ(test, le16_to_cpu(entry->len), sizeof(data)); + KUNIT_EXPECT_EQ(test, entry->flags, BCM4377_XFER_RING_FLAG_PAYLOAD_IN_FOOTER); + KUNIT_EXPECT_EQ(test, ring->head, 1); + KUNIT_EXPECT_EQ(test, le16_to_cpu(bcm4377->ring_state->xfer_ring_head[ring->ring_id]), 1); + + /* A far-off value written later does not move the next slot either. */ + bcm4377->ring_state->xfer_ring_head[ring->ring_id] = cpu_to_le16(0xffff); + KUNIT_ASSERT_EQ(test, bcm4377_enqueue(bcm4377, ring, data, sizeof(data), false), 0); + entry = (void *)(buf + slot); + KUNIT_EXPECT_EQ(test, le16_to_cpu(entry->len), sizeof(data)); + KUNIT_EXPECT_EQ(test, ring->head, 2); + for (i = 0; i < guard; i++) + KUNIT_EXPECT_EQ(test, buf[ring->n_entries * slot + i], 0); +} + +static struct kunit_case bcm4377_test_cases[] = { + KUNIT_CASE(bcm4377_enqueue_uses_host_head_test), + {} +}; + +static struct kunit_suite bcm4377_test_suite = { + .name = "hci_bcm4377", + .init = bcm4377_test_init, + .test_cases = bcm4377_test_cases, +}; + +kunit_test_suite(bcm4377_test_suite); From fa6c3498d39df73d16aec29a859cf6c1f56388f8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:07:38 +1100 Subject: [PATCH 0567/1514] Bluetooth: hci_bcm4377: bound an event's footer payload by the footer An event on a device-to-host ring carries its payload either in a mapped buffer, whose length is checked against mapped_payload_size, or in the footer of the completion entry. The footer length was not checked: the entry's 32-bit len went to bt_skb_alloc(), which adds its reserve to an unsigned int, and to the memcpy() from the footer. A length past the footer read past the completion ring, and one near U32_MAX wrapped the allocation. Pass the completion ring's payload_size to bcm4377_handle_event() and drop an in-footer event longer than that with a warning. The ring head still advances, as for the other dropped events. Add a KUnit case that feeds lengths of footer + 1 and near U32_MAX, which are dropped, and the footer's own size, which is taken. Without the check the case oopses in the memcpy(). Fixes: 8a06127602de ("Bluetooth: hci_bcm4377: Add new driver for BCM4377 PCIe boards") Signed-off-by: Ryan Murray --- drivers/bluetooth/Kconfig | 4 ++- drivers/bluetooth/hci_bcm4377.c | 14 +++++++--- drivers/bluetooth/hci_bcm4377_test.c | 41 ++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/drivers/bluetooth/Kconfig b/drivers/bluetooth/Kconfig index a77809e8f521c8..08c6af1c39d38a 100644 --- a/drivers/bluetooth/Kconfig +++ b/drivers/bluetooth/Kconfig @@ -352,7 +352,9 @@ config BT_HCIBCM4377_KUNIT_TEST help Build KUnit tests into the BCM4377 family PCIe driver. They check, without radio hardware, that a transfer ring is filled at the - host's own producer index whatever the shared ring state holds. + host's own producer index whatever the shared ring state holds, + and that an event longer than its completion entry's footer is + dropped. If unsure, say N. diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 3643e2f236347f..236ed48a2c1015 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -713,7 +713,7 @@ static int bcm4377_extract_msgid(struct bcm4377_data *bcm4377, static void bcm4377_handle_event(struct bcm4377_data *bcm4377, struct bcm4377_transfer_ring *ring, u16 raw_msgid, u8 entry_flags, u8 type, - void *payload, size_t len) + void *payload, size_t len, size_t footer_size) { struct sk_buff *skb; u16 head; @@ -742,6 +742,12 @@ static void bcm4377_handle_event(struct bcm4377_data *bcm4377, } payload = ring->payloads + msgid * ring->mapped_payload_size; + } else if (len > footer_size) { + /* The payload is in the completion entry's footer. */ + dev_warn(&bcm4377->pdev->dev, + "invalid footer payload len in event for ring %d: %zu > %zu\n", + ring->ring_id, len, footer_size); + goto out; } skb = bt_skb_alloc(len, GFP_ATOMIC); @@ -844,17 +850,17 @@ static void bcm4377_handle_completion(struct bcm4377_data *bcm4377, case BCM4377_XFER_RING_HCI_D2H: bcm4377_handle_event(bcm4377, &bcm4377->hci_d2h_ring, msg_id, entry->flags, HCI_EVENT_PKT, data, - data_len); + data_len, ring->payload_size); break; case BCM4377_XFER_RING_SCO_D2H: bcm4377_handle_event(bcm4377, &bcm4377->sco_d2h_ring, msg_id, entry->flags, HCI_SCODATA_PKT, data, - data_len); + data_len, ring->payload_size); break; case BCM4377_XFER_RING_ACL_D2H: bcm4377_handle_event(bcm4377, &bcm4377->acl_d2h_ring, msg_id, entry->flags, HCI_ACLDATA_PKT, data, - data_len); + data_len, ring->payload_size); break; default: diff --git a/drivers/bluetooth/hci_bcm4377_test.c b/drivers/bluetooth/hci_bcm4377_test.c index a4f0c0ab06cb84..7beb3ddd267163 100644 --- a/drivers/bluetooth/hci_bcm4377_test.c +++ b/drivers/bluetooth/hci_bcm4377_test.c @@ -82,8 +82,49 @@ static void bcm4377_enqueue_uses_host_head_test(struct kunit *test) KUNIT_EXPECT_EQ(test, buf[ring->n_entries * slot + i], 0); } +/* + * An event whose payload sits in the completion entry's footer can be no + * longer than that footer; a longer one is dropped and the ring moves on. + */ +static void bcm4377_footer_event_len_test(struct kunit *test) +{ + static const u32 lens[] = { 9, 0xfffffff8, 0xffffffff, 8 }; + struct bcm4377_test_ctx *ctx = test->priv; + struct bcm4377_data *bcm4377 = ctx->bcm4377; + struct bcm4377_transfer_ring *ring = &bcm4377->hci_d2h_ring; + struct bcm4377_completion_ring_entry *entry; + struct bcm4377_completion_ring cring = { + .ring_id = BCM4377_EVENT_RING_HCI_ACL, + .payload_size = 8, + .n_entries = 2, + .transfer_rings = BIT(BCM4377_XFER_RING_HCI_D2H), + }; + size_t i; + + ring->ring_id = BCM4377_XFER_RING_HCI_D2H; + ring->n_entries = 8; + ring->virtual = true; + ring->enabled = true; + spin_lock_init(&ring->lock); + /* Room past the footer, so a missing check reads this, not a neighbour. */ + cring.ring = kunit_kzalloc(test, 2 * (sizeof(*entry) + cring.payload_size) + 64, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cring.ring); + entry = cring.ring; + entry->ring_id = cpu_to_le16(BCM4377_XFER_RING_HCI_D2H); + entry->flags = BCM4377_XFER_RING_FLAG_PAYLOAD_IN_FOOTER; + + /* No HCI device: an accepted frame is freed by hci_recv_frame(). */ + for (i = 0; i < ARRAY_SIZE(lens); i++) { + entry->len = cpu_to_le32(lens[i]); + bcm4377_handle_completion(bcm4377, &cring, 0); + KUNIT_EXPECT_EQ(test, ring->head, i + 1); + } +} + static struct kunit_case bcm4377_test_cases[] = { KUNIT_CASE(bcm4377_enqueue_uses_host_head_test), + KUNIT_CASE(bcm4377_footer_event_len_test), {} }; From 31de110bd4f146f0cf578a83c9138c6e705e8faf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:13:30 +1100 Subject: [PATCH 0568/1514] dmaengine: apple-sio: check the tag and channel of a firmware message sio_recv_msg() took the 6-bit tag of an ACK, NACK or STARTED message from the co-processor and only refused tags past the table, with a WARN_ON. Tag 0 is never allocated and its completion is never initialised, so an acknowledgment naming tag 0 went to complete() on an all-zero completion and faulted in the wait-queue walk. A tag that was not outstanding (never handed out, or freed after a timed-out call) was completed or, for an atomic tag, had its callback run and was freed a second time. The channel of an ACK callback or of a report was refused with a WARN_ON too, one per message. Complete or call back only for a tag the host has outstanding, and drop other acknowledgments and messages for a channel the device does not have with a rate-limited warning instead of a WARN_ON. Initialise all the completions in the probe, tag 0 included. Add a KUnit case that feeds tag 0, tags 17 and 63, a tag never handed out and channel 0xff, which are dropped without a WARN, and checks that an outstanding tag is still completed. Without the check it oopses in complete(). Fixes: 5fdca02134fa ("dmaengine: apple-sio: Add Apple SIO driver") Signed-off-by: Ryan Murray --- MAINTAINERS | 1 + drivers/dma/Kconfig | 3 ++ drivers/dma/apple-sio-msg-test.c | 69 ++++++++++++++++++++++++++++++++ drivers/dma/apple-sio.c | 31 ++++++++++++-- 4 files changed, 100 insertions(+), 4 deletions(-) create mode 100644 drivers/dma/apple-sio-msg-test.c diff --git a/MAINTAINERS b/MAINTAINERS index 5c8fc89e51d008..698e2909f71a0e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2699,6 +2699,7 @@ F: Documentation/devicetree/bindings/dma/apple,sio.yaml F: Documentation/devicetree/bindings/sound/apple,* F: Documentation/devicetree/bindings/sound/cirrus,cs42l84.yaml F: Documentation/devicetree/bindings/sound/trivial-codec.yaml +F: drivers/dma/apple-sio-msg-test.c F: drivers/dma/apple-sio-probe-test.c F: drivers/dma/apple-sio-probe-test.dtso F: drivers/dma/apple-sio-t6030-test.dtso diff --git a/drivers/dma/Kconfig b/drivers/dma/Kconfig index 924164e62f1a3f..aa35dfcab74481 100644 --- a/drivers/dma/Kconfig +++ b/drivers/dma/Kconfig @@ -127,6 +127,9 @@ config APPLE_SIO_KUNIT_TEST generic SIO of the M1 and M2, and a T6030 SIO only with validated protocol-10 boot tables. The compatible selects the firmware layout. Also check protocol-9 table order, DMA array counts and ACK failures. + And check that a firmware ACK, NACK or report naming a tag that + is not outstanding, or a channel the device does not have, is + dropped. config APPLE_SIO_T6030_KUNIT_TEST bool "KUnit tests for the T6030 SIO boot-table check" if !KUNIT_ALL_TESTS diff --git a/drivers/dma/apple-sio-msg-test.c b/drivers/dma/apple-sio-msg-test.c new file mode 100644 index 00000000000000..321b4f1bf9061b --- /dev/null +++ b/drivers/dma/apple-sio-msg-test.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-sio.c: the checks sio_recv_msg() applies to the tag and + * the channel a firmware message names. + */ +#include +#include + +static u64 sio_test_msg(u8 type, u8 tag, u8 sioep) +{ + return FIELD_PREP(SIOMSG_TYPE, type) | FIELD_PREP(SIOMSG_TAG, tag) | + FIELD_PREP(SIOMSG_EP, sioep); +} + +/* + * The firmware's ACKs, NACKs and reports name a tag and a channel. Only a + * tag the host has outstanding is completed; tag 0, tags past the table and + * channels past the device's are dropped without a WARN. + */ +static void sio_recv_msg_checks_tag_and_channel_test(struct kunit *test) +{ + bool tainted = test_taint(TAINT_WARN); + struct sio_data *sio; + struct device *dev; + + dev = kunit_device_register(test, "apple-sio-msg-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + sio = kunit_kzalloc(test, struct_size(sio, channels, 1), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sio); + sio->dev = dev; + sio->nchannels = 1; + /* As allocated, before the probe sets anything up. */ + init_completion(&sio->tags.completions[3]); + init_completion(&sio->tags.completions[4]); + + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 0, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[0].done, 0); + KUNIT_EXPECT_FALSE(test, sio->tags.acked[0]); + + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 17, 0)); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_NACK, 63, 0)); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_REPORT, 1, 0xff)); + + /* Tag 4 was never handed out. */ + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 4, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[4].done, 0); + KUNIT_EXPECT_FALSE(test, sio->tags.acked[4]); + + /* An outstanding tag is still completed. */ + set_bit(3, sio->tags.allocated); + sio_recv_msg(sio, EP_SIO, sio_test_msg(MSG_ACK, 3, 0)); + KUNIT_EXPECT_EQ(test, sio->tags.completions[3].done, 1); + KUNIT_EXPECT_TRUE(test, sio->tags.acked[3]); + + if (!tainted) + KUNIT_EXPECT_FALSE(test, test_taint(TAINT_WARN)); +} + +static struct kunit_case sio_msg_test_cases[] = { + KUNIT_CASE(sio_recv_msg_checks_tag_and_channel_test), + {} +}; + +static struct kunit_suite sio_msg_test_suite = { + .name = "apple-sio-msg", + .test_cases = sio_msg_test_cases, +}; + +kunit_test_suite(sio_msg_test_suite); diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index cb75beb54ae994..51c61c3037846c 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -1534,6 +1534,16 @@ static void sio_process_report(struct sio_chan *siochan) spin_unlock_irqrestore(&siochan->vc.lock, flags); } +/* + * A tag the firmware names in an ACK or NACK must be one the host handed out + * and has not freed: tag 0 is never allocated, and the field is wider than + * the table. + */ +static bool sio_tag_outstanding(struct sio_data *sio, u8 tag) +{ + return tag && tag < SIO_NTAGS && test_bit(tag, sio->tags.allocated); +} + static void sio_recv_msg(void *cookie, u8 ep, u64 msg) { struct sio_data *sio = cookie; @@ -1558,13 +1568,21 @@ static void sio_recv_msg(void *cookie, u8 ep, u64 msg) fallthrough; case MSG_ACK: case MSG_NACK: - if (WARN_ON(tag >= SIO_NTAGS)) + if (!sio_tag_outstanding(sio, tag)) { + dev_warn_ratelimited(sio->dev, + "ack for tag %u, which is not outstanding\n", + tag); break; + } if (tags->atomic[tag]) { sio_ack_callback callback = tags->ack_callback[tag]; - if (callback && !WARN_ON(sioep >= sio->nchannels)) + if (callback && sioep >= sio->nchannels) + dev_warn_ratelimited(sio->dev, + "ack for channel %u of %d\n", + sioep, sio->nchannels); + else if (callback) callback(&sio->channels[sioep], tags->cookie[tag], type == MSG_ACK); if (type == MSG_NACK) @@ -1577,8 +1595,12 @@ static void sio_recv_msg(void *cookie, u8 ep, u64 msg) break; case MSG_REPORT: - if (WARN_ON(sioep >= sio->nchannels)) + if (sioep >= sio->nchannels) { + dev_warn_ratelimited(sio->dev, + "report for channel %u of %d\n", + sioep, sio->nchannels); break; + } sio_process_report(&sio->channels[sioep]); break; @@ -2051,7 +2073,7 @@ static int sio_probe(struct platform_device *pdev) dev_err(&pdev->dev, "couldn't initialize rtkit\n"); goto rpm_put; } - for (i = 1; i < SIO_NTAGS; i++) + for (i = 0; i < SIO_NTAGS; i++) init_completion(&sio->tags.completions[i]); dma = &sio->dma; @@ -2354,4 +2376,5 @@ MODULE_LICENSE("Dual MIT/GPL"); #if IS_ENABLED(CONFIG_APPLE_SIO_KUNIT_TEST) #include "apple-sio-probe-test.c" #include "apple-sio-boot-test.c" +#include "apple-sio-msg-test.c" #endif From a5dbac8de4515535e24273c1a7f5cdf8af5016f1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:13:51 +1100 Subject: [PATCH 0569/1514] soc: apple: rtkit-helper: add KUnit tests Add a suite for the RTKit helper's own callbacks, run directly on a test context with the AP power request behind a KUnit static stub (a small wrapper, apple_rtkit_helper_send_ap_power(), that is the same call otherwise): - shared-memory setup: DMA allocation for a request without an address, SRAM placement inside, at the edges, one byte outside, straddling, zero and huge sizes, an iova+size that wraps, and no SRAM at all; adopted strict and legacy sessions; repeated setup and destroy; - the inherited buffer list from a test devicetree node: count limits, bad endpoints, zero size, a bad mapped flag, wrap, the 44-bit edge, and one bad entry rejecting the list; - the sleep state machine: prepare, suspend_late, suspend, resume and complete, the PM notifier, idle notices unanswered, answered late or still pending at the next sleep, a crashed co-processor, adopted s2idle with and without the CPU running, freeze, and input preservation. Tests only, no functional change. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 16 + drivers/soc/apple/rtkit-helper-test.c | 919 +++++++++++++++++++++ drivers/soc/apple/rtkit-helper.c | 21 +- drivers/soc/apple/rtkit-helper.kunitconfig | 10 + 4 files changed, 964 insertions(+), 2 deletions(-) create mode 100644 drivers/soc/apple/rtkit-helper-test.c create mode 100644 drivers/soc/apple/rtkit-helper.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e1..0ee767a734c445 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -153,6 +153,22 @@ config APPLE_RTKIT_HELPER Say 'y' here if you have an Apple SoC. +config APPLE_RTKIT_HELPER_KUNIT_TEST + bool "KUnit tests for the Apple RTKit helper co-processor" if !KUNIT_ALL_TESTS + depends on APPLE_RTKIT_HELPER=y && KUNIT=y && SUSPEND + default KUNIT_ALL_TESTS + help + Hand the helper's shared memory callbacks the buffer requests a + co-processor sends (no address, addresses in and around the SRAM + region, zero, unaligned and wrapping sizes, repeats), parse the + buffer inventory of a handed over session from a device node built + by the test, and walk the AP power notices of a sleep: prepare, + suspend, resume and complete, unanswered and late answered idle + notices. The RTKit AP power call is a static stub and the ASC and + SRAM registers are kernel memory. The tests touch no hardware. + + If unsure, say N. + config APPLE_SART tristate "Apple SART DMA address filter" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/soc/apple/rtkit-helper-test.c b/drivers/soc/apple/rtkit-helper-test.c new file mode 100644 index 00000000000000..4e3aa1b0e07aa3 --- /dev/null +++ b/drivers/soc/apple/rtkit-helper-test.c @@ -0,0 +1,919 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple RTKit helper co-processor driver. + * + * Included at the end of rtkit-helper.c. The tests call the helper's own + * shared memory callbacks, its buffer inventory parser and its sleep + * callbacks directly. The RTKit AP power notice is a static stub, the RTKit + * state the helper reads is a zeroed struct apple_rtkit, and the ASC and SRAM + * registers are kernel memory. No hardware is touched. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "rtkit-internal.h" + +/* The RTKit power states the helper's checks look at (rtkit.c). */ +#define RTKH_TEST_PWR_IDLE 0x201 +#define RTKH_TEST_PWR_ON 0x20 + +/* An SRAM region well inside the 44 bit DMA mask. */ +#define RTKH_TEST_SRAM_START 0x210000000ULL +#define RTKH_TEST_SRAM_SIZE 0x10000 +#define RTKH_TEST_MAX_CALLS 8 + +struct rtkh_test { + struct apple_rtkit_helper helper; + struct apple_rtkit rtk; + struct device *dev; + struct resource sram; + void *sram_mem; + u32 *asc; + + struct device_node np; + struct property compat; + struct property inventory; + __be32 cells[2 * APPLE_RTKIT_HELPER_MAX_BUFFERS * APPLE_RTKIT_HELPER_BUFFER_CELLS]; + + /* The AP power notices the helper sent, and what each one returns. */ + unsigned int ncalls; + bool sent_on[RTKH_TEST_MAX_CALLS]; + int ret[RTKH_TEST_MAX_CALLS]; + + unsigned int saved_flags; + suspend_state_t saved_target; +}; + +static int rtkh_stub_send_ap_power(struct apple_rtkit_helper *helper, bool on) +{ + struct kunit *test = kunit_get_current_test(); + struct rtkh_test *ctx = test->priv; + unsigned int i = ctx->ncalls++; + int ret; + + KUNIT_ASSERT_PTR_EQ(test, helper, &ctx->helper); + KUNIT_ASSERT_LT(test, i, RTKH_TEST_MAX_CALLS); + ctx->sent_on[i] = on; + ret = ctx->ret[i]; + /* An answered notice moves RTKit's AP state, as its ACK handler does. */ + if (!ret) + ctx->rtk.ap_power_state = on ? RTKH_TEST_PWR_ON : RTKH_TEST_PWR_IDLE; + return ret; +} + +static void rtkh_set_run(struct rtkh_test *ctx, bool run) +{ + ctx->asc[APPLE_ASC_CPU_CONTROL / 4] = run ? APPLE_ASC_CPU_CONTROL_RUN : 0; +} + +static int rtkh_test_init(struct kunit *test) +{ + struct rtkh_test *ctx; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + test->priv = ctx; + + dev = kunit_device_register(test, "rtkit-helper-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ctx->dev = dev; + dev->coherent_dma_mask = DMA_BIT_MASK(44); + dev->dma_mask = &dev->coherent_dma_mask; + /* Coherent: dma-direct hands out pages of the linear map. */ + dev_set_dma_coherent(dev); + + ctx->asc = kunit_kzalloc(test, APPLE_ASC_CPU_CONTROL + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->asc); + ctx->sram_mem = kunit_kzalloc(test, RTKH_TEST_SRAM_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->sram_mem); + ctx->sram = DEFINE_RES_MEM_NAMED(RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE, "sram"); + + ctx->rtk.dev = dev; + ctx->rtk.iop_power_state = RTKH_TEST_PWR_ON; + ctx->rtk.ap_power_state = RTKH_TEST_PWR_ON; + + ctx->helper.dev = dev; + ctx->helper.rtk = &ctx->rtk; + ctx->helper.asc_base = (__force void __iomem *)ctx->asc; + ctx->helper.sram = &ctx->sram; + ctx->helper.sram_base = (__force void __iomem *)ctx->sram_mem; + dev_set_drvdata(dev, &ctx->helper); + + ctx->saved_flags = pm_suspend_global_flags; + ctx->saved_target = pm_suspend_target_state; + pm_suspend_clear_flags(); + + kunit_activate_static_stub(test, apple_rtkit_helper_send_ap_power, + rtkh_stub_send_ap_power); + return 0; +} + +static void rtkh_test_exit(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + /* The node is the test's: the device must not put it. */ + if (ctx->dev) + ctx->dev->of_node = NULL; + pm_suspend_global_flags = ctx->saved_flags; + pm_suspend_target_state = ctx->saved_target; +} + +/* shmem_setup / shmem_destroy */ + +static int rtkh_setup(struct rtkh_test *ctx, struct apple_rtkit_shmem *bfr, + u64 iova, size_t size) +{ + memset(bfr, 0, sizeof(*bfr)); + bfr->iova = iova; + bfr->size = size; + return apple_rtkit_helper_shmem_setup(&ctx->helper, bfr); +} + +static void rtkh_expect_refused(struct kunit *test, struct apple_rtkit_shmem *bfr, + int ret, int err) +{ + KUNIT_EXPECT_EQ(test, ret, err); + KUNIT_EXPECT_NULL(test, bfr->buffer); + KUNIT_EXPECT_NULL(test, bfr->iomem); + KUNIT_EXPECT_FALSE(test, bfr->is_mapped); +} + +static void rtkh_shmem_dma_alloc(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, 0, 0x4000), 0); + KUNIT_ASSERT_NOT_NULL(test, bfr.buffer); + KUNIT_EXPECT_NE(test, bfr.iova, 0); + KUNIT_EXPECT_EQ(test, bfr.iova & (PAGE_SIZE - 1), 0); + KUNIT_EXPECT_LE(test, bfr.iova + bfr.size - 1, DMA_BIT_MASK(44)); + KUNIT_EXPECT_NULL(test, bfr.iomem); + KUNIT_EXPECT_FALSE(test, bfr.is_mapped); + KUNIT_EXPECT_EQ(test, bfr.size, 0x4000); + memset(bfr.buffer, 0xa5, bfr.size); + + dma_free_coherent(ctx->dev, bfr.size, bfr.buffer, bfr.iova); +} + +static void rtkh_shmem_sram_inside(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, + 0x2000), 0); + KUNIT_EXPECT_TRUE(test, bfr.is_mapped); + KUNIT_EXPECT_NULL(test, bfr.buffer); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x1000); + KUNIT_EXPECT_EQ(test, bfr.iova, RTKH_TEST_SRAM_START + 0x1000); + KUNIT_EXPECT_EQ(test, bfr.size, 0x2000); +} + +static void rtkh_shmem_sram_whole(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE), 0); + KUNIT_EXPECT_TRUE(test, bfr.is_mapped); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem); +} + +/* Byte granular and unaligned: the SRAM offset is the IOVA's, not rounded. */ +static void rtkh_shmem_sram_unaligned_edges(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x123, + 0x10), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x123); + + /* The very last byte of the region. */ + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, ctx->sram.end, 1), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 1); + + /* Ends exactly at the end of the region. */ + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x801, + 0x801), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 0x801); +} + +static void rtkh_shmem_sram_outside(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + /* One byte past the end. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x800, 0x801), + -EFAULT); + /* Straddles the end. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end + 1 - 0x1000, 0x2000), + -EFAULT); + /* Starts one byte before the region. */ + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START - 1, 0x10), + -EFAULT); + /* Right after it. */ + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, ctx->sram.end + 1, 1), + -EFAULT); + /* Somewhere else entirely, page aligned. */ + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, 0x10000000, 0x4000), + -EFAULT); +} + +static void rtkh_shmem_sram_zero_size(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, 0), + -EFAULT); +} + +static void rtkh_shmem_sram_huge(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, SZ_1G), + -EFAULT); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + RTKH_TEST_SRAM_SIZE + 1), + -EFAULT); +} + +/* iova + size wraps: the wrapped end lands back inside the region. */ +static void rtkh_shmem_sram_wrap(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x1000, + SIZE_MAX - 0x7ff), + -EFAULT); + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, + SIZE_MAX), + -EFAULT); + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, U64_MAX - 0xfff, 0x2000), + -EFAULT); +} + +static void rtkh_shmem_no_sram(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.sram = NULL; + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), + -EFAULT); +} + +/* A strict adopted session refuses every new buffer, allocated or placed. */ +static void rtkh_shmem_adopted_strict(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.adopted = true; + ctx->helper.strict_buffers = true; + rtkh_expect_refused(test, &bfr, rtkh_setup(ctx, &bfr, 0, 0x4000), -ENODATA); + KUNIT_EXPECT_EQ(test, bfr.iova, 0); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), + -ENODATA); + + /* strict_buffers alone, without an adopted session, does not refuse. */ + ctx->helper.adopted = false; + KUNIT_EXPECT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START, 0x1000), 0); +} + +/* A producer without an inventory (T8140) keeps mapping SRAM IOVAs. */ +static void rtkh_shmem_adopted_legacy(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem bfr; + + ctx->helper.adopted = true; + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &bfr, RTKH_TEST_SRAM_START + 0x4000, + 0x4000), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)bfr.iomem, ctx->sram_mem + 0x4000); + rtkh_expect_refused(test, &bfr, + rtkh_setup(ctx, &bfr, ctx->sram.end, 2), -EFAULT); +} + +/* Setting up the same request twice, and destroying twice, is harmless. */ +static void rtkh_shmem_double_setup_destroy(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_shmem a, b; + + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &a, RTKH_TEST_SRAM_START + 0x2000, + 0x1000), 0); + KUNIT_ASSERT_EQ(test, rtkh_setup(ctx, &b, RTKH_TEST_SRAM_START + 0x2000, + 0x1000), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)a.iomem, (__force void *)b.iomem); + + /* Re-running setup on a mapped buffer re-maps it to the same place. */ + KUNIT_ASSERT_EQ(test, apple_rtkit_helper_shmem_setup(&ctx->helper, &a), 0); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)a.iomem, (__force void *)b.iomem); + + apple_rtkit_helper_shmem_destroy(&ctx->helper, &a); + apple_rtkit_helper_shmem_destroy(&ctx->helper, &a); + memset(&b, 0, sizeof(b)); + apple_rtkit_helper_shmem_destroy(&ctx->helper, &b); +} + +static void rtkh_ops(struct kunit *test) +{ + KUNIT_EXPECT_PTR_EQ(test, apple_rtkit_helper_ops.shmem_setup, + &apple_rtkit_helper_shmem_setup); + KUNIT_EXPECT_PTR_EQ(test, apple_rtkit_helper_ops.shmem_destroy, + &apple_rtkit_helper_shmem_destroy); + /* RTKit refuses ops with both setup flavours; the helper has one. */ + KUNIT_EXPECT_NULL(test, apple_rtkit_helper_ops.shmem_setup_ep); +} + +/* The buffer inventory of a handed over session (apple,rtkit-buffers) */ + +static void rtkh_node(struct rtkh_test *ctx, const char *compatible) +{ + ctx->np.full_name = "mtp"; + if (compatible) { + ctx->compat.name = "compatible"; + ctx->compat.value = (void *)compatible; + ctx->compat.length = strlen(compatible) + 1; + ctx->np.properties = &ctx->compat; + } + ctx->dev->of_node = &ctx->np; +} + +static void rtkh_inventory(struct rtkh_test *ctx, const u32 *cells, unsigned int n) +{ + unsigned int i; + + for (i = 0; i < n && i < ARRAY_SIZE(ctx->cells); i++) + ctx->cells[i] = cpu_to_be32(cells[i]); + ctx->inventory.name = "apple,rtkit-buffers"; + ctx->inventory.value = n ? ctx->cells : NULL; + ctx->inventory.length = n * sizeof(__be32); + ctx->inventory.next = ctx->np.properties; + ctx->np.properties = &ctx->inventory; +} + +#define RTKH_HI(a) ((u32)((u64)(a) >> 32)) +#define RTKH_LO(a) ((u32)(a)) + +static int rtkh_inherit(struct rtkh_test *ctx, struct apple_rtkit_inherited_buffer *b) +{ + memset(b, 0, sizeof(*b) * APPLE_RTKIT_HELPER_MAX_BUFFERS); + return apple_rtkit_helper_inherit_buffers(&ctx->helper, b); +} + +static void rtkh_inherit_no_inventory(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + + /* Older producers (T8140) hand over without an inventory. */ + rtkh_node(ctx, "apple,t8140-mtp"); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), 0); + + /* T8132 sessions must describe their buffers. */ + rtkh_node(ctx, "apple,t8132-mtp"); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +static void rtkh_inherit_empty(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, NULL, 0); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), 0); +} + +static void rtkh_inherit_one_sram(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 iova = RTKH_TEST_SRAM_START + 0x1000; + const u32 cells[] = { 2, RTKH_HI(iova), RTKH_LO(iova), 0x2000, 0 }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 1); + KUNIT_EXPECT_EQ(test, b[0].endpoint, 2); + KUNIT_EXPECT_EQ(test, b[0].shmem.iova, iova); + KUNIT_EXPECT_EQ(test, b[0].shmem.size, 0x2000); + KUNIT_EXPECT_FALSE(test, b[0].shmem.is_mapped); + KUNIT_EXPECT_NULL(test, b[0].shmem.buffer); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[0].shmem.iomem, + ctx->sram_mem + 0x1000); +} + +static void rtkh_inherit_max(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 s = RTKH_TEST_SRAM_START; + const u32 cells[] = { + 1, RTKH_HI(s), RTKH_LO(s), 0x1000, 0, + 2, RTKH_HI(s + 0x1000), RTKH_LO(s + 0x1000), 0x1000, 1, + 4, RTKH_HI(s + 0x2000), RTKH_LO(s + 0x2000), 0x123, 0, + 8, RTKH_HI(s + 0xf000), RTKH_LO(s + 0xf000), 0x1000, 1, + }; + static const u8 eps[] = { 1, 2, 4, 8 }; + unsigned int i; + + rtkh_node(ctx, "apple,t8142-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 4); + for (i = 0; i < 4; i++) { + KUNIT_EXPECT_EQ(test, b[i].endpoint, eps[i]); + KUNIT_EXPECT_EQ(test, b[i].shmem.iova, ((u64)cells[i * 5 + 1] << 32) | + cells[i * 5 + 2]); + KUNIT_EXPECT_EQ(test, b[i].shmem.size, cells[i * 5 + 3]); + KUNIT_EXPECT_EQ(test, b[i].shmem.is_mapped, !!cells[i * 5 + 4]); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[i].shmem.iomem, + ctx->sram_mem + (b[i].shmem.iova - s)); + } +} + +static void rtkh_inherit_bad_count(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + u32 cells[ARRAY_SIZE(ctx->cells)]; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cells); i += 5) { + cells[i] = 1; + cells[i + 1] = RTKH_HI(RTKH_TEST_SRAM_START); + cells[i + 2] = RTKH_LO(RTKH_TEST_SRAM_START); + cells[i + 3] = 0x1000; + cells[i + 4] = 0; + } + + /* Five buffers: one more than the session may hold. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 5 * (APPLE_RTKIT_HELPER_MAX_BUFFERS + 1)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); + + /* A partial tuple. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 7); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); + + /* Not even a whole cell. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, 1); + ctx->inventory.length = 3; + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +static void rtkh_inherit_one_bad(struct kunit *test, u32 ep, u64 iova, u32 size, + u32 mapped) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u32 cells[] = { ep, RTKH_HI(iova), RTKH_LO(iova), size, mapped }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_EXPECT_EQ_MSG(test, rtkh_inherit(ctx, b), -EINVAL, + "ep %u iova %#llx size %#x mapped %u", ep, iova, size, + mapped); +} + +static void rtkh_inherit_bad_tuple(struct kunit *test) +{ + const u64 s = RTKH_TEST_SRAM_START; + + /* Not a system endpoint with a shared buffer. */ + rtkh_inherit_one_bad(test, 0, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 3, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 7, s, 0x1000, 0); + rtkh_inherit_one_bad(test, 0x20, s, 0x1000, 0); + /* No size. */ + rtkh_inherit_one_bad(test, 2, s, 0, 0); + /* is_mapped is a flag. */ + rtkh_inherit_one_bad(test, 2, s, 0x1000, 2); + /* Wraps past the top of the address space. */ + rtkh_inherit_one_bad(test, 2, U64_MAX - 0xfff, 0x2000, 0); + /* Above the 44 bit DMA mask. */ + rtkh_inherit_one_bad(test, 2, BIT_ULL(44), 0x1000, 0); + /* Outside SRAM, and no reserved memory region describes it. */ + rtkh_inherit_one_bad(test, 2, 0x10000000, 0x4000, 0); + rtkh_inherit_one_bad(test, 2, s + RTKH_TEST_SRAM_SIZE - 0x1000, 0x2000, 0); +} + +/* One bad tuple refuses the whole inventory. */ +static void rtkh_inherit_bad_second(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 s = RTKH_TEST_SRAM_START; + const u32 cells[] = { + 2, RTKH_HI(s), RTKH_LO(s), 0x1000, 0, + 4, RTKH_HI(s + 0x1000), RTKH_LO(s + 0x1000), 0x1000, 3, + }; + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, cells, ARRAY_SIZE(cells)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +/* The 44 bit limit is inclusive: a buffer may end on its last byte. */ +static void rtkh_inherit_dma_mask_edge(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct apple_rtkit_inherited_buffer b[APPLE_RTKIT_HELPER_MAX_BUFFERS]; + const u64 top = DMA_BIT_MASK(44) + 1; + const u32 ok[] = { 8, RTKH_HI(top - 0x1000), RTKH_LO(top - 0x1000), 0x1000, 0 }; + const u32 over[] = { 8, RTKH_HI(top - 0x1000), RTKH_LO(top - 0x1000), 0x1001, 0 }; + + ctx->sram = DEFINE_RES_MEM_NAMED(top - RTKH_TEST_SRAM_SIZE, + RTKH_TEST_SRAM_SIZE + 0x1000, "sram"); + + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, ok, ARRAY_SIZE(ok)); + KUNIT_ASSERT_EQ(test, rtkh_inherit(ctx, b), 1); + KUNIT_EXPECT_PTR_EQ(test, (__force void *)b[0].shmem.iomem, + ctx->sram_mem + RTKH_TEST_SRAM_SIZE - 0x1000); + + /* Inside this SRAM, but one byte past the DMA mask. */ + rtkh_node(ctx, "apple,t8132-mtp"); + rtkh_inventory(ctx, over, ARRAY_SIZE(over)); + KUNIT_EXPECT_EQ(test, rtkh_inherit(ctx, b), -EINVAL); +} + +/* Sleep: the AP power notices */ + +static void rtkh_expect_calls(struct kunit *test, const bool *on, unsigned int n) +{ + struct rtkh_test *ctx = test->priv; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ctx->ncalls, n); + for (i = 0; i < n; i++) + KUNIT_EXPECT_EQ_MSG(test, ctx->sent_on[i], on[i], "notice %u", i); +} + +/* A firmware sleep sends one idle notice and one AP on, whichever callback. */ +static void rtkh_pm_fw_sleep_cycle(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + pm_set_suspend_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + apple_rtkit_helper_complete(dev); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); +} + +/* The M5 Pro's idle notice waits for .suspend_late. */ +static void rtkh_pm_idle_late(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + ctx->helper.idle_late = true; + pm_set_suspend_via_firmware(); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* A sleep the firmware does not finish tells the co-processor nothing. */ +static void rtkh_pm_no_fw_no_notice(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + pm_suspend_target_state = PM_SUSPEND_MEM; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), 0); +} + +/* + * An unanswered idle notice fails .prepare; the PM notifier ends that sleep. + * Still no answer: nothing is sent, and the next sleep is refused without a + * second idle notice. + */ +static void rtkh_pm_unanswered_still_running(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EBUSY); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* The answer came before the sleep ended: AP on goes out at its end. */ +static void rtkh_pm_unanswered_late_answer(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, ctx->rtk.ap_power_state, RTKH_TEST_PWR_ON); + + /* The next sleep starts clean. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* A crashed co-processor is not running either: its idle is not pending. */ +static void rtkh_pm_unanswered_crashed(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + ctx->ret[1] = -ENODEV; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + ctx->rtk.crashed = true; + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 2); + KUNIT_EXPECT_TRUE(test, ctx->sent_on[1]); + /* A failed AP on is not an unanswered idle notice. */ + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); +} + +/* The answer came after the sleep ended: the next sleep sends AP on first. */ +static void rtkh_pm_pending_answered_later(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false, true }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_ASSERT_TRUE(test, ctx->helper.idle_pending); + + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_TRUE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +static void rtkh_pm_pending_ap_on_fails(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + ctx->ret[1] = -EIO; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -ETIMEDOUT); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), -EBUSY); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_pending); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* .complete and the PM notifier both end a sleep: only once. */ +static void rtkh_pm_complete_then_notify(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true }; + + ctx->helper.idle_late = true; + pm_set_suspend_via_firmware(); + ctx->ret[0] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend_late(dev), -ETIMEDOUT); + ctx->rtk.ap_power_state = RTKH_TEST_PWR_IDLE; + apple_rtkit_helper_complete(dev); + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + apple_rtkit_helper_complete(dev); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +static void rtkh_pm_notify_other_events(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + ctx->helper.idle_unanswered = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, + PM_SUSPEND_PREPARE, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, + PM_POST_HIBERNATION, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_TRUE(test, ctx->helper.idle_unanswered); + + ctx->helper.idle_unanswered = false; + apple_rtkit_helper_pm_notify(&ctx->helper.pm_nb, PM_POST_SUSPEND, NULL); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_pending); +} + +/* A failed AP on leaves nothing behind; the next sleep idles normally. */ +static void rtkh_pm_ap_on_fails(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + static const bool want[] = { false, true, false }; + + pm_set_suspend_via_firmware(); + ctx->ret[1] = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + KUNIT_EXPECT_FALSE(test, ctx->helper.ap_idle); + KUNIT_EXPECT_FALSE(test, ctx->helper.idle_unanswered); + apple_rtkit_helper_complete(dev); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_prepare(dev), 0); + rtkh_expect_calls(test, want, ARRAY_SIZE(want)); +} + +/* An adopted session survives s2idle only with its CPU still running. */ +static void rtkh_pm_adopted_s2idle(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + ctx->helper.adopted = true; + pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + + rtkh_set_run(ctx, true); + dev->power.wakeup_path = false; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_TRUE(test, device_awake_path(dev)); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); + + rtkh_set_run(ctx, false); + dev->power.wakeup_path = false; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EHOSTDOWN); + KUNIT_EXPECT_FALSE(test, device_awake_path(dev)); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), -EHOSTDOWN); + KUNIT_EXPECT_EQ(test, ctx->ncalls, 0); +} + +static void rtkh_pm_adopted_refuses(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + struct device *dev = ctx->dev; + + rtkh_set_run(ctx, true); + pm_suspend_target_state = PM_SUSPEND_MEM; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), 0); + + ctx->helper.adopted = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_suspend(dev), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_freeze(dev), -EBUSY); + + /* Not adopted: a stopped CPU does not matter on resume. */ + ctx->helper.adopted = false; + rtkh_set_run(ctx, false); + KUNIT_EXPECT_EQ(test, apple_rtkit_helper_resume(dev), 0); +} + +static void rtkh_preserves_input(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + ctx->helper.preserved = true; + KUNIT_EXPECT_TRUE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + dev_set_drvdata(ctx->dev, NULL); + KUNIT_EXPECT_FALSE(test, apple_rtkit_helper_preserves_input(ctx->dev)); + dev_set_drvdata(ctx->dev, &ctx->helper); +} + +static void rtkh_pm_register(struct kunit *test) +{ + struct rtkh_test *ctx = test->priv; + + KUNIT_ASSERT_EQ(test, apple_rtkit_helper_pm_register(&ctx->helper), 0); + KUNIT_EXPECT_PTR_EQ(test, ctx->helper.pm_nb.notifier_call, + &apple_rtkit_helper_pm_notify); + /* The device's devres unregisters it when the test ends. */ +} + +static struct kunit_case apple_rtkit_helper_test_cases[] = { + KUNIT_CASE(rtkh_ops), + KUNIT_CASE(rtkh_shmem_dma_alloc), + KUNIT_CASE(rtkh_shmem_sram_inside), + KUNIT_CASE(rtkh_shmem_sram_whole), + KUNIT_CASE(rtkh_shmem_sram_unaligned_edges), + KUNIT_CASE(rtkh_shmem_sram_outside), + KUNIT_CASE(rtkh_shmem_sram_zero_size), + KUNIT_CASE(rtkh_shmem_sram_huge), + KUNIT_CASE(rtkh_shmem_sram_wrap), + KUNIT_CASE(rtkh_shmem_no_sram), + KUNIT_CASE(rtkh_shmem_adopted_strict), + KUNIT_CASE(rtkh_shmem_adopted_legacy), + KUNIT_CASE(rtkh_shmem_double_setup_destroy), + KUNIT_CASE(rtkh_inherit_no_inventory), + KUNIT_CASE(rtkh_inherit_empty), + KUNIT_CASE(rtkh_inherit_one_sram), + KUNIT_CASE(rtkh_inherit_max), + KUNIT_CASE(rtkh_inherit_bad_count), + KUNIT_CASE(rtkh_inherit_bad_tuple), + KUNIT_CASE(rtkh_inherit_bad_second), + KUNIT_CASE(rtkh_inherit_dma_mask_edge), + KUNIT_CASE(rtkh_pm_fw_sleep_cycle), + KUNIT_CASE(rtkh_pm_idle_late), + KUNIT_CASE(rtkh_pm_no_fw_no_notice), + KUNIT_CASE(rtkh_pm_unanswered_still_running), + KUNIT_CASE(rtkh_pm_unanswered_late_answer), + KUNIT_CASE(rtkh_pm_unanswered_crashed), + KUNIT_CASE(rtkh_pm_pending_answered_later), + KUNIT_CASE(rtkh_pm_pending_ap_on_fails), + KUNIT_CASE(rtkh_pm_complete_then_notify), + KUNIT_CASE(rtkh_pm_notify_other_events), + KUNIT_CASE(rtkh_pm_ap_on_fails), + KUNIT_CASE(rtkh_pm_adopted_s2idle), + KUNIT_CASE(rtkh_pm_adopted_refuses), + KUNIT_CASE(rtkh_preserves_input), + KUNIT_CASE(rtkh_pm_register), + {} +}; + +static struct kunit_suite apple_rtkit_helper_test_suite = { + .name = "apple-rtkit-helper", + .init = rtkh_test_init, + .exit = rtkh_test_exit, + .test_cases = apple_rtkit_helper_test_cases, +}; + +kunit_test_suite(apple_rtkit_helper_test_suite); diff --git a/drivers/soc/apple/rtkit-helper.c b/drivers/soc/apple/rtkit-helper.c index 4db46fe2970db3..2468a9b2d55488 100644 --- a/drivers/soc/apple/rtkit-helper.c +++ b/drivers/soc/apple/rtkit-helper.c @@ -20,6 +20,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) +#include +#endif + #define APPLE_ASC_CPU_CONTROL 0x44 #define APPLE_ASC_CPU_CONTROL_RUN BIT(4) @@ -398,9 +402,18 @@ static void apple_rtkit_helper_remove(struct platform_device *pdev) writel_relaxed(0, helper->asc_base + APPLE_ASC_CPU_CONTROL); } +/* The AP power notice itself: the KUnit test replaces it with a static stub. */ +static int apple_rtkit_helper_send_ap_power(struct apple_rtkit_helper *helper, bool on) +{ +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_rtkit_helper_send_ap_power, helper, on); +#endif + return apple_rtkit_ap_power(helper->rtk, on); +} + static int apple_rtkit_helper_ap_power(struct apple_rtkit_helper *helper, bool on) { - int ret = apple_rtkit_ap_power(helper->rtk, on); + int ret = apple_rtkit_helper_send_ap_power(helper, on); if (ret) dev_err(helper->dev, "AP power notice (%s) not answered: %d\n", @@ -433,7 +446,7 @@ static int apple_rtkit_helper_ap_idle(struct apple_rtkit_helper *helper) } helper->idle_pending = false; dev_info(helper->dev, "the last AP idle notice was answered late, sending AP on first\n"); - if (apple_rtkit_ap_power(helper->rtk, true)) { + if (apple_rtkit_helper_send_ap_power(helper, true)) { dev_err(helper->dev, "AP on after the late answer not answered: no sleep\n"); helper->idle_pending = true; return -EBUSY; @@ -615,3 +628,7 @@ module_platform_driver(apple_rtkit_helper_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple RTKit helper driver"); + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST) +#include "rtkit-helper-test.c" +#endif diff --git a/drivers/soc/apple/rtkit-helper.kunitconfig b/drivers/soc/apple/rtkit-helper.kunitconfig new file mode 100644 index 00000000000000..2e7ff2826502a6 --- /dev/null +++ b/drivers/soc/apple/rtkit-helper.kunitconfig @@ -0,0 +1,10 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_RTKIT_HELPER=y +CONFIG_APPLE_RTKIT_HELPER_KUNIT_TEST=y From d80ccd4e601d0653ee4b9dbcd58ff216947b4177 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:14:00 +1100 Subject: [PATCH 0570/1514] EDAC/apple: add KUnit tests Add a suite for the Apple SoC EDAC driver. The T6041 and NI status registers are now read and written through two small accessors that a KUnit static stub can redirect (plain readl/writel otherwise), so the test can model write-one-to-clear status that clears on acknowledge: - the tables mapping interrupt lines to error sources, for each SoC; - T6041 and NI status decode and acknowledge, against a fake register block that rejects any access outside it, including bit 3 of the T6041 status, which is not an error; - uncorrectable error counts in the real EDAC core; - the mask-and-backoff of a stuck line: doubling to the 60 s cap, stopping after eight rearms, and the reset after 60 s quiet. No functional change. Signed-off-by: Ryan Murray --- drivers/edac/Kconfig | 13 + drivers/edac/apple_soc_edac-test.c | 760 ++++++++++++++++++++++++ drivers/edac/apple_soc_edac.c | 30 +- drivers/edac/apple_soc_edac.kunitconfig | 6 + 4 files changed, 803 insertions(+), 6 deletions(-) create mode 100644 drivers/edac/apple_soc_edac-test.c create mode 100644 drivers/edac/apple_soc_edac.kunitconfig diff --git a/drivers/edac/Kconfig b/drivers/edac/Kconfig index e0dfd136599bb9..81739f3f61f3ce 100644 --- a/drivers/edac/Kconfig +++ b/drivers/edac/Kconfig @@ -582,6 +582,19 @@ config EDAC_APPLE_SOC acknowledged and counted in the EDAC core; a source that stays asserted without status is masked. +config EDAC_APPLE_SOC_KUNIT_TEST + bool "KUnit tests for Apple SoC error reporting" if !KUNIT_ALL_TESTS + depends on EDAC_APPLE_SOC=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Build KUnit tests for the Apple SoC error reporting driver: the + interrupt index to error source tables, the T6041 and T8140 NI + status decode and acknowledge against a fake register block, the + uncorrectable error counts and the mask and backoff of lines that + stay asserted. + + If unsure, say N. + config EDAC_VERSALNET tristate "AMD VersalNET DDR Controller" depends on CDX_CONTROLLER && ARCH_ZYNQMP diff --git a/drivers/edac/apple_soc_edac-test.c b/drivers/edac/apple_soc_edac-test.c new file mode 100644 index 00000000000000..5d54283d1ce912 --- /dev/null +++ b/drivers/edac/apple_soc_edac-test.c @@ -0,0 +1,760 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple SoC platform error reporting driver + * + * Copyright The Aurora Silicon Contributors + * + * Included at the end of apple_soc_edac.c. The status registers are a fake + * write-one-to-clear register block behind the driver's static-stubbed + * accessors, so no MMIO is touched and every access is bounds checked. + */ + +#include +#include +#include +#include +#include + +#define EDAC_TEST_WORDS 64 +/* Not a valid interrupt: the IRQ core ignores masks and unmasks of it. */ +#define EDAC_TEST_IRQ INT_MAX + +struct edac_test_fake { + u32 regs[EDAC_TEST_WORDS]; + /* Bits that stay set after an acknowledge. */ + u32 sticky[EDAC_TEST_WORDS]; + unsigned int acks[EDAC_TEST_WORDS]; + unsigned int reads; + unsigned int writes; + unsigned int stray; +}; + +struct edac_test_ctx { + struct device *dev; + struct edac_test_fake fake; + struct apple_soc_edac edac; + struct apple_soc_edac_irq irq; + void __iomem *status_regs[T6041_NI_REGS]; +}; + +static int edac_test_word(struct edac_test_fake *fake, void __iomem *reg) +{ + uintptr_t off = (uintptr_t)(void __force *)reg - (uintptr_t)fake->regs; + + if (off % 4 || off >= sizeof(fake->regs)) { + fake->stray++; + return -1; + } + + return off / 4; +} + +static u32 edac_test_read(void __iomem *reg) +{ + struct kunit *test = kunit_get_current_test(); + struct edac_test_ctx *ctx = test->priv; + int word = edac_test_word(&ctx->fake, reg); + + if (word < 0) + return 0; + ctx->fake.reads++; + return ctx->fake.regs[word]; +} + +static void edac_test_write(void __iomem *reg, u32 val) +{ + struct kunit *test = kunit_get_current_test(); + struct edac_test_ctx *ctx = test->priv; + int word = edac_test_word(&ctx->fake, reg); + + if (word < 0) + return; + ctx->fake.writes++; + ctx->fake.acks[word]++; + ctx->fake.regs[word] = (ctx->fake.regs[word] & ~val) | + ctx->fake.sticky[word]; +} + +static void edac_test_free_dci(void *data) +{ + edac_device_free_ctl_info(data); +} + +static void edac_test_cancel(void *data) +{ + struct apple_soc_edac_irq *irq_data = data; + + cancel_delayed_work_sync(&irq_data->rearm); +} + +/* + * Set up one error line of @hw the way probe does, with the T6041 status + * words and the NI status block of the line in the fake register block. + */ +static struct edac_test_ctx *edac_test_line(struct kunit *test, + const struct apple_soc_edac_hw *hw, + unsigned int index) +{ + struct edac_test_ctx *ctx = test->priv; + struct apple_soc_edac_irq *irq_data = &ctx->irq; + struct device *dev = ctx->dev; + unsigned int i; + + /* A previous line of the same case: its EDAC device name is reused. */ + if (ctx->edac.dci) { + kunit_release_action(test, edac_test_cancel, irq_data); + kunit_release_action(test, edac_test_free_dci, ctx->edac.dci); + } + memset(&ctx->fake, 0, sizeof(ctx->fake)); + memset(&ctx->edac, 0, sizeof(ctx->edac)); + memset(irq_data, 0, sizeof(*irq_data)); + ctx->edac.dev = dev; + ctx->edac.hw = hw; + ctx->edac.irqs = irq_data; + ctx->edac.dci = edac_device_alloc_ctl_info(0, "apple_soc_edac_kunit", + 1, "platform", 1, 0, 0); + KUNIT_ASSERT_NOT_NULL(test, ctx->edac.dci); + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, + edac_test_free_dci, + ctx->edac.dci)); + ctx->edac.dci->dev = dev; + ctx->edac.dci->ctl_name = APPLE_SOC_EDAC_NAME; + ctx->edac.dci->dev_name = dev_name(dev); + ctx->edac.dci->log_ue = 0; + ctx->edac.dci->panic_on_ue = 0; + + /* T6041 line 45 + n reads its status word at fake word n. */ + for (i = 0; i < T6041_NI_REGS; i++) + ctx->status_regs[i] = (void __iomem __force *) + ((u8 *)&ctx->fake.regs[i] - T6041_NI_STATUS); + if (hw->num_status_regs) + ctx->edac.status_regs = ctx->status_regs; + + irq_data->edac = &ctx->edac; + irq_data->source = apple_soc_edac_source(hw, index); + KUNIT_ASSERT_NOT_NULL(test, irq_data->source); + irq_data->index = index; + irq_data->irq = EDAC_TEST_IRQ; + irq_data->backoff_ms = APPLE_SOC_EDAC_BACKOFF_MS; + irq_data->armed_jiffies = jiffies; + INIT_DELAYED_WORK(&irq_data->rearm, apple_soc_edac_rearm); + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, + edac_test_cancel, + irq_data)); + + /* An NI's status word n is fake word n. */ + for (i = 0; i < hw->nni; i++) { + if (hw->ni[i].index != index) + continue; + irq_data->ni = &hw->ni[i]; + irq_data->ni_base = (void __iomem __force *) + ((u8 *)ctx->fake.regs - hw->ni[i].status); + } + + return ctx; +} + +static u32 edac_test_ue(struct edac_test_ctx *ctx) +{ + return ctx->edac.dci->counters.ue_count; +} + +/* Run the IRQ thread; returns the rearm delay in jiffies, 0 if none. */ +static unsigned long edac_test_fire(struct kunit *test, + struct edac_test_ctx *ctx, + unsigned int expect_backoff_ms) +{ + struct apple_soc_edac_irq *irq_data = &ctx->irq; + unsigned long before, after, expires, delay; + + before = jiffies; + KUNIT_EXPECT_EQ(test, IRQ_HANDLED, + apple_soc_edac_irq_thread(irq_data->irq, irq_data)); + after = jiffies; + + if (!delayed_work_pending(&irq_data->rearm)) { + KUNIT_EXPECT_EQ(test, 0U, expect_backoff_ms); + return 0; + } + + expires = irq_data->rearm.timer.expires; + cancel_delayed_work_sync(&irq_data->rearm); + delay = msecs_to_jiffies(expect_backoff_ms); + KUNIT_EXPECT_NE(test, 0U, expect_backoff_ms); + KUNIT_EXPECT_GE(test, expires - before, delay); + KUNIT_EXPECT_LE(test, expires - after, delay); + + return expires - before; +} + +static int edac_test_init(struct kunit *test) +{ + struct edac_test_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + test->priv = ctx; + ctx->dev = kunit_device_register(test, "apple-soc-edac-kunit"); + if (IS_ERR(ctx->dev)) + return PTR_ERR(ctx->dev); + kunit_activate_static_stub(test, apple_soc_edac_read, edac_test_read); + kunit_activate_static_stub(test, apple_soc_edac_write, edac_test_write); + + return 0; +} + +static const struct apple_soc_edac_hw *const edac_test_error_hws[] = { + &t6000_error_hw, &t6041_error_hw, &t8112_error_hw, &t8140_error_hw, +}; + +static const struct apple_soc_edac_hw *const edac_test_event_hws[] = { + &t6000_event_hw, &t6041_event_hw, &t8112_event_hw, &t8140_event_hw, +}; + +static void edac_test_expect_source(struct kunit *test, + const struct apple_soc_edac_hw *hw, + unsigned int index, const char *expect) +{ + const char *name = apple_soc_edac_source(hw, index); + + if (!expect) { + KUNIT_EXPECT_NULL_MSG(test, name, "index %u", index); + return; + } + KUNIT_EXPECT_NOT_NULL_MSG(test, name, "index %u", index); + if (name) + KUNIT_EXPECT_STREQ_MSG(test, name, expect, "index %u", index); +} + +/* Every T6041 line maps to its range name, gaps and the tail to none. */ +static void edac_test_source_t6041(struct kunit *test) +{ + static const struct { + unsigned int index; + const char *name; + } cases[] = { + { 0, "sep" }, { 8, "sep" }, { 9, "pmgr" }, { 10, NULL }, + { 25, NULL }, { 26, "sram" }, { 28, "sram" }, { 29, NULL }, + { 44, NULL }, { 45, "ni0" }, { 47, "ni0" }, { 48, "ni1" }, + { 51, "ni1" }, { 52, "ni2" }, { 56, "ni3" }, { 63, "ni3" }, + { 64, "ni4" }, { 66, "ni5" }, { 68, "ni6" }, { 69, "ni6" }, + { 70, NULL }, { 88, NULL }, { 89, NULL }, { 255, NULL }, + { UINT_MAX, NULL }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) + edac_test_expect_source(test, &t6041_error_hw, cases[i].index, + cases[i].name); +} + +/* Range edges of every SoC: first and last line in, neighbours per table. */ +static void edac_test_source_edges(struct kunit *test) +{ + unsigned int h, r, i, claimed; + + for (h = 0; h < ARRAY_SIZE(edac_test_error_hws); h++) { + const struct apple_soc_edac_hw *hw = edac_test_error_hws[h]; + + claimed = 0; + for (i = 0; i < hw->num_irqs; i++) + claimed += !!apple_soc_edac_source(hw, i); + + for (r = 0; r < hw->nranges; r++) { + const struct apple_soc_edac_range *range = &hw->ranges[r]; + unsigned int last = range->first + range->count - 1; + + edac_test_expect_source(test, hw, range->first, + range->name); + edac_test_expect_source(test, hw, last, range->name); + claimed -= range->count; + } + /* Lines outside every range are left unclaimed. */ + KUNIT_EXPECT_EQ_MSG(test, claimed, 0U, "hw %u", h); + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, hw->num_irqs)); + } +} + +/* The ranges fit the interrupt count, ascend and do not overlap. */ +static void edac_test_tables(struct kunit *test) +{ + unsigned int h, r, end; + + for (h = 0; h < ARRAY_SIZE(edac_test_error_hws); h++) { + const struct apple_soc_edac_hw *hw = edac_test_error_hws[h]; + + KUNIT_EXPECT_FALSE(test, hw->event_log); + KUNIT_EXPECT_GT(test, hw->nranges, (size_t)0); + end = 0; + for (r = 0; r < hw->nranges; r++) { + const struct apple_soc_edac_range *range = &hw->ranges[r]; + + KUNIT_EXPECT_NOT_NULL(test, range->name); + KUNIT_EXPECT_GT(test, range->count, 0); + KUNIT_EXPECT_GE_MSG(test, (unsigned int)range->first, end, + "hw %u range %u", h, r); + end = range->first + range->count; + KUNIT_EXPECT_LE_MSG(test, end, hw->num_irqs, + "hw %u range %u", h, r); + } + } + + for (h = 0; h < ARRAY_SIZE(edac_test_event_hws); h++) { + KUNIT_EXPECT_TRUE(test, edac_test_event_hws[h]->event_log); + KUNIT_EXPECT_EQ(test, edac_test_event_hws[h]->nranges, (size_t)0); + KUNIT_EXPECT_EQ(test, edac_test_event_hws[h]->nni, (size_t)0); + } +} + +/* T6041: exactly the NI lines 45-69 own one status aperture each. */ +static void edac_test_t6041_status_lines(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = &t6041_error_hw; + unsigned int i; + + KUNIT_EXPECT_EQ(test, hw->num_status_regs, T6041_NI_REGS); + for (i = 45; i < 45 + T6041_NI_REGS; i++) { + const char *name = apple_soc_edac_source(hw, i); + + KUNIT_ASSERT_NOT_NULL(test, name); + KUNIT_EXPECT_EQ_MSG(test, strncmp(name, "ni", 2), 0, "index %u", i); + } + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, 44)); + KUNIT_EXPECT_NULL(test, apple_soc_edac_source(hw, 45 + T6041_NI_REGS)); +} + +/* T8140 NI blocks sit on claimed NI lines with a valid aperture and words. */ +static void edac_test_t8140_ni_table(struct kunit *test) +{ + const struct apple_soc_edac_hw *hw = &t8140_error_hw; + unsigned int i, j; + + KUNIT_EXPECT_EQ(test, hw->nni, (size_t)6); + for (i = 0; i < hw->nni; i++) { + const struct apple_soc_edac_ni *ni = &hw->ni[i]; + const char *name = apple_soc_edac_source(hw, ni->index); + + KUNIT_ASSERT_NOT_NULL(test, name); + KUNIT_EXPECT_EQ(test, strncmp(name, "ni", 2), 0); + KUNIT_EXPECT_NE(test, ni->words, 0U); + KUNIT_EXPECT_EQ(test, ni->status % 4, 0); + /* Interrupt n is described by the n-th interrupt-less reg. */ + KUNIT_EXPECT_GE(test, ni->reg, 9); + for (j = 0; j < i; j++) { + KUNIT_EXPECT_NE(test, ni->index, hw->ni[j].index); + KUNIT_EXPECT_NE(test, ni->reg, hw->ni[j].reg); + } + } + /* The NSI and PIO lines have no status block. */ + for (i = 24; i < 26; i++) + for (j = 0; j < hw->nni; j++) + KUNIT_EXPECT_NE(test, (unsigned int)hw->ni[j].index, i); +} + +static void edac_test_event_log_source(struct kunit *test) +{ + unsigned int h; + + for (h = 0; h < ARRAY_SIZE(edac_test_event_hws); h++) { + const struct apple_soc_edac_hw *hw = edac_test_event_hws[h]; + + edac_test_expect_source(test, hw, 0, "event-log"); + edac_test_expect_source(test, hw, hw->num_irqs - 1, "event-log"); + edac_test_expect_source(test, hw, hw->num_irqs, "event-log"); + } +} + +static void edac_test_of_match(struct kunit *test) +{ + const struct of_device_id *id; + unsigned int n = 0; + + for (id = apple_soc_edac_of_match; id->compatible[0]; id++) { + const struct apple_soc_edac_hw *hw = id->data; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_EXPECT_GT(test, hw->num_irqs, 0U); + KUNIT_EXPECT_EQ_MSG(test, hw->event_log, + !!strstr(id->compatible, "-event-log"), + "%s", id->compatible); + n++; + } + KUNIT_EXPECT_EQ(test, n, 8U); +} + +static bool edac_test_t6041(struct edac_test_ctx *ctx, bool *error, + bool *cleared) +{ + return apple_soc_edac_t6041_status(&ctx->irq, error, cleared); +} + +/* A T6041 NI word that reads zero is left alone. */ +static void edac_test_t6041_status_zero(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 50); + bool error = true, cleared = false; + + KUNIT_EXPECT_FALSE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_FALSE(test, error); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* Each bit is acknowledged; only bits 0-2 and 4-7 are platform errors. */ +static void edac_test_t6041_status_mask(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 45); + unsigned int bit; + bool error, cleared; + + for (bit = 0; bit < 32; bit++) { + ctx->fake.regs[0] = BIT(bit); + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_EQ_MSG(test, error, bit < 8 && bit != 3, "bit %u", bit); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[0], 0U); + } + KUNIT_EXPECT_EQ(test, ctx->fake.acks[0], 32U); + + /* Bit 3 among higher bits is still no error. */ + ctx->fake.regs[0] = 0xffffff08; + apple_soc_edac_t6041_status(&ctx->irq, &error, &cleared); + KUNIT_EXPECT_FALSE(test, error); + ctx->fake.regs[0] = 0xffffffff; + apple_soc_edac_t6041_status(&ctx->irq, &error, &cleared); + KUNIT_EXPECT_TRUE(test, error); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* A word that reads back set after the acknowledge is reported. */ +static void edac_test_t6041_status_sticky(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 60); + bool error, cleared; + + ctx->fake.regs[15] = 0x11; + ctx->fake.sticky[15] = 0x10; + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_TRUE(test, error); + KUNIT_EXPECT_FALSE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[15], 0x10U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[15], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 2U); +} + +/* Line 45 + n uses aperture n, and lines outside 45-69 touch none. */ +static void edac_test_t6041_status_index(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 45); + static const unsigned int outside[] = { 0, 9, 26, 44, 70, 88 }; + bool error, cleared; + unsigned int i; + + for (i = 0; i < T6041_NI_REGS; i++) + ctx->fake.regs[i] = 0x1; + + for (i = 0; i < T6041_NI_REGS; i++) { + ctx->irq.index = 45 + i; + KUNIT_EXPECT_TRUE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.acks[i], 1U, "line %u", 45 + i); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[i], 0U); + } + + for (i = 0; i < T6041_NI_REGS; i++) + ctx->fake.regs[i] = 0x1; + ctx->fake.reads = 0; + for (i = 0; i < ARRAY_SIZE(outside); i++) { + ctx->irq.index = outside[i]; + KUNIT_EXPECT_FALSE(test, edac_test_t6041(ctx, &error, &cleared)); + KUNIT_EXPECT_FALSE(test, error); + KUNIT_EXPECT_TRUE(test, cleared); + } + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* Only the words in the NI's mask are read, and set ones are acknowledged. */ +static void edac_test_ni_status_words(struct kunit *test) +{ + /* SoC NI 0: 0x1ffd7ff */ + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 18); + unsigned int bit; + bool cleared = false; + + KUNIT_ASSERT_NOT_NULL(test, ctx->irq.ni); + for (bit = 0; bit < 32; bit++) + ctx->fake.regs[bit] = 0xa5a5a5a5; + + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + for (bit = 0; bit < 32; bit++) { + bool in = ctx->irq.ni->words & BIT(bit); + + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.acks[bit], in ? 1U : 0U, + "word %u", bit); + KUNIT_EXPECT_EQ_MSG(test, ctx->fake.regs[bit], + in ? 0U : 0xa5a5a5a5U, "word %u", bit); + } + KUNIT_EXPECT_EQ(test, ctx->fake.reads, + 2 * hweight32(ctx->irq.ni->words)); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* No word set: nothing found and nothing written. */ +static void edac_test_ni_status_none(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 22); + bool cleared = false; + + KUNIT_ASSERT_NOT_NULL(test, ctx->irq.ni); + KUNIT_EXPECT_FALSE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, + hweight32(ctx->irq.ni->words)); +} + +/* One word of several staying set makes the NI not cleared. */ +static void edac_test_ni_status_sticky(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 23); + bool cleared = true; + + /* GFX NI: 0x3ff7ff, so words 0 and 21 are both in the mask. */ + ctx->fake.regs[0] = 0x2; + ctx->fake.regs[21] = 0x80000001; + ctx->fake.sticky[21] = 0x80000000; + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_FALSE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[0], 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[21], 0x80000000U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[0], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[21], 1U); +} + +/* Word 31 sits at status + 0x7c; word 11 of an NI without it is never read. */ +static void edac_test_ni_status_top_word(struct kunit *test) +{ + static const struct apple_soc_edac_ni ni = { 18, 9, 0x100, BIT(31) }; + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 18); + bool cleared; + + ctx->irq.ni = ∋ + ctx->irq.ni_base = (void __iomem __force *) + ((u8 *)ctx->fake.regs - ni.status); + ctx->fake.regs[31] = 0xffffffff; + ctx->fake.regs[30] = 0x1; + KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_TRUE(test, cleared); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[31], 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[30], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 2U); + + /* Word 11 is outside SoC NI 0's mask. */ + ctx->irq.ni = &t8140_ni[0]; + ctx->irq.ni_base = (void __iomem __force *) + ((u8 *)ctx->fake.regs - t8140_ni[0].status); + ctx->fake.regs[30] = 0; + ctx->fake.regs[11] = 0x1; + KUNIT_EXPECT_FALSE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[11], 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); +} + +/* T6041 NI error acknowledged: one UE, the line stays unmasked. */ +static void edac_test_irq_t6041_error(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 47); + + ctx->fake.regs[2] = 0x4; + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.regs[2], 0U); +} + +/* Bit 3 alone is acknowledged without an error count. */ +static void edac_test_irq_t6041_bit3(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 69); + + ctx->fake.regs[24] = BIT(3); + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[24], 1U); +} + +/* An NI line with no status set is masked and backed off, not counted. */ +static void edac_test_irq_t6041_empty(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 56); + + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); +} + +/* An acknowledge that does not take counts once and backs off. */ +static void edac_test_irq_t6041_sticky(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 64); + + ctx->fake.regs[19] = 0x1; + ctx->fake.sticky[19] = 0x1; + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); +} + +/* Lines without a status contract count a UE and back off. */ +static void edac_test_irq_no_status(struct kunit *test) +{ + static const struct { + const struct apple_soc_edac_hw *hw; + unsigned int index; + } lines[] = { + { &t6041_error_hw, 3 }, /* sep */ + { &t6041_error_hw, 27 }, /* sram */ + { &t6000_error_hw, 33 }, /* ni0, no status on T6000 */ + { &t8112_error_hw, 2 }, /* sep */ + { &t8140_error_hw, 24 }, /* nsi */ + { &t6000_event_hw, 0 }, + { &t8140_event_hw, 8 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(lines); i++) { + struct edac_test_ctx *ctx; + + ctx = edac_test_line(test, lines[i].hw, lines[i].index); + KUNIT_EXPECT_NULL(test, ctx->irq.ni); + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ_MSG(test, edac_test_ue(ctx), 1U, "line %u", i); + KUNIT_EXPECT_EQ(test, ctx->fake.reads, 0U); + KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); + cancel_delayed_work_sync(&ctx->irq.rearm); + } +} + +/* T8140 NI: acknowledged status is one UE without a mask. */ +static void edac_test_irq_ni_error(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 21); + + ctx->fake.regs[24] = 0x100; + KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->fake.acks[24], 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 0U); +} + +/* T8140 NI asserted with no status: masked, no UE. Sticky: UE once + mask. */ +static void edac_test_irq_ni_empty_sticky(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 19); + + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + + ctx->fake.regs[3] = 0x8; + ctx->fake.sticky[3] = 0x8; + edac_test_fire(test, ctx, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 2U); +} + +/* The backoff doubles to its cap; after the retry limit the line stays off. */ +static void edac_test_irq_backoff_limit(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6000_error_hw, 0); + unsigned int i, expect = APPLE_SOC_EDAC_BACKOFF_MS; + + for (i = 0; i < APPLE_SOC_EDAC_MAX_RETRIES; i++) { + /* Fires straight after its unmask: still asserted. */ + ctx->irq.armed_jiffies = jiffies; + edac_test_fire(test, ctx, expect); + expect = min(expect * 2, APPLE_SOC_EDAC_BACKOFF_MAX_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, expect); + } + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, APPLE_SOC_EDAC_BACKOFF_MAX_MS); + + ctx->irq.armed_jiffies = jiffies; + edac_test_fire(test, ctx, 0); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, APPLE_SOC_EDAC_MAX_RETRIES + 1); + KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), APPLE_SOC_EDAC_MAX_RETRIES + 1); +} + +/* A line that stayed quiet for a minute after its unmask starts over. */ +static void edac_test_irq_backoff_reset(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t8112_error_hw, 1); + + ctx->irq.retries = APPLE_SOC_EDAC_MAX_RETRIES + 1; + ctx->irq.backoff_ms = APPLE_SOC_EDAC_BACKOFF_MAX_MS; + ctx->irq.armed_jiffies = jiffies - + msecs_to_jiffies(APPLE_SOC_EDAC_BACKOFF_MAX_MS) - 1; + edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 1U); + KUNIT_EXPECT_EQ(test, ctx->irq.backoff_ms, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + + /* Unmasked under a minute ago: still counting. */ + ctx->irq.armed_jiffies = jiffies - + msecs_to_jiffies(APPLE_SOC_EDAC_BACKOFF_MAX_MS) + HZ; + edac_test_fire(test, ctx, 2 * APPLE_SOC_EDAC_BACKOFF_MS); + KUNIT_EXPECT_EQ(test, ctx->irq.retries, 2U); +} + +/* The rearm work unmasks and restarts the quiet-period clock. */ +static void edac_test_rearm(struct kunit *test) +{ + struct edac_test_ctx *ctx = edac_test_line(test, &t6000_error_hw, 12); + unsigned long before; + + ctx->irq.armed_jiffies = jiffies - 10 * HZ; + before = jiffies; + apple_soc_edac_rearm(&ctx->irq.rearm.work); + KUNIT_EXPECT_GE(test, ctx->irq.armed_jiffies, before); + KUNIT_EXPECT_LE(test, ctx->irq.armed_jiffies, jiffies); +} + +static struct kunit_case apple_soc_edac_test_cases[] = { + KUNIT_CASE(edac_test_source_t6041), + KUNIT_CASE(edac_test_source_edges), + KUNIT_CASE(edac_test_tables), + KUNIT_CASE(edac_test_t6041_status_lines), + KUNIT_CASE(edac_test_t8140_ni_table), + KUNIT_CASE(edac_test_event_log_source), + KUNIT_CASE(edac_test_of_match), + KUNIT_CASE(edac_test_t6041_status_zero), + KUNIT_CASE(edac_test_t6041_status_mask), + KUNIT_CASE(edac_test_t6041_status_sticky), + KUNIT_CASE(edac_test_t6041_status_index), + KUNIT_CASE(edac_test_ni_status_words), + KUNIT_CASE(edac_test_ni_status_none), + KUNIT_CASE(edac_test_ni_status_sticky), + KUNIT_CASE(edac_test_ni_status_top_word), + KUNIT_CASE(edac_test_irq_t6041_error), + KUNIT_CASE(edac_test_irq_t6041_bit3), + KUNIT_CASE(edac_test_irq_t6041_empty), + KUNIT_CASE(edac_test_irq_t6041_sticky), + KUNIT_CASE(edac_test_irq_no_status), + KUNIT_CASE(edac_test_irq_ni_error), + KUNIT_CASE(edac_test_irq_ni_empty_sticky), + KUNIT_CASE(edac_test_irq_backoff_limit), + KUNIT_CASE(edac_test_irq_backoff_reset), + KUNIT_CASE(edac_test_rearm), + {} +}; + +static struct kunit_suite apple_soc_edac_test_suite = { + .name = "apple-soc-edac", + .init = edac_test_init, + .test_cases = apple_soc_edac_test_cases, +}; + +kunit_test_suite(apple_soc_edac_test_suite); diff --git a/drivers/edac/apple_soc_edac.c b/drivers/edac/apple_soc_edac.c index ffdc17fe92e627..7bbc3230b1a396 100644 --- a/drivers/edac/apple_soc_edac.c +++ b/drivers/edac/apple_soc_edac.c @@ -5,6 +5,7 @@ * Copyright The Aurora Silicon Contributors */ +#include #include #include #include @@ -218,6 +219,19 @@ static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, return NULL; } +/* Status register accessors; KUnit redirects them to a fake register block. */ +static u32 apple_soc_edac_read(void __iomem *reg) +{ + KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_read, reg); + return readl(reg); +} + +static void apple_soc_edac_write(void __iomem *reg, u32 val) +{ + KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_write, reg, val); + writel(val, reg); +} + /* * Read and acknowledge a T6041 NI status word. Returns whether it was set; * @error says whether a bit in the platform error policy was set and @@ -236,14 +250,14 @@ static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, void __iomem *reg = edac->status_regs[irq_data->index - 45] + T6041_NI_STATUS; - status = readl(reg); + status = apple_soc_edac_read(reg); if (!status) return false; /* Bit 3 is not part of the platform error policy. */ *error = status & 0xf7; - writel(status, reg); - left = readl(reg); + apple_soc_edac_write(reg, status); + left = apple_soc_edac_read(reg); if (left) { *cleared = false; dev_info_ratelimited(edac->dev, @@ -273,11 +287,11 @@ static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, *cleared = true; for_each_set_bit(bit, &words, 32) { offset = ni->status + 4 * bit; - status = readl(irq_data->ni_base + offset); + status = apple_soc_edac_read(irq_data->ni_base + offset); if (!status) continue; - writel(status, irq_data->ni_base + offset); - left = readl(irq_data->ni_base + offset); + apple_soc_edac_write(irq_data->ni_base + offset, status); + left = apple_soc_edac_read(irq_data->ni_base + offset); dev_err_ratelimited(irq_data->edac->dev, "%s: status %#x at %#x, %#x after the acknowledge\n", irq_data->source, status, offset, left); @@ -541,3 +555,7 @@ module_platform_driver(apple_soc_edac_driver); MODULE_AUTHOR("The Aurora Silicon Contributors"); MODULE_DESCRIPTION("Apple SoC platform error reporting driver"); MODULE_LICENSE("GPL"); + +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +#include "apple_soc_edac-test.c" +#endif diff --git a/drivers/edac/apple_soc_edac.kunitconfig b/drivers/edac/apple_soc_edac.kunitconfig new file mode 100644 index 00000000000000..987bd6c1c064c2 --- /dev/null +++ b/drivers/edac/apple_soc_edac.kunitconfig @@ -0,0 +1,6 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_RAS=y +CONFIG_EDAC=y +CONFIG_EDAC_APPLE_SOC=y +CONFIG_EDAC_APPLE_SOC_KUNIT_TEST=y From aa6db0c74eddce3ba6c5cdf838c4a0785d85e5ef Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 12:16:30 +0100 Subject: [PATCH 0571/1514] dt-bindings: iommu: apple,dart: describe the T8152 AVD instance The AVD Gen3 DART uses the shared TLBI aperture like the display DARTs, but Linux initializes it from an unlocked state with inactive streams. Require its PSD power domain, DMA aperture and initialization tunables. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/iommu/apple,dart.yaml | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index d7e8e332951ade..ba49a093ecceeb 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -33,6 +33,7 @@ properties: - apple,t8110-dart - apple,t6000-dart - apple,t8152-dart-gen3 + - apple,t8152-avd-dart - items: - const: apple,t8140-ane-dart - const: apple,t8140-dart @@ -369,7 +370,9 @@ allOf: properties: compatible: contains: - const: apple,t8152-dart-gen3 + enum: + - apple,t8152-dart-gen3 + - apple,t8152-avd-dart then: description: The T8152 Gen3 DARTs in front of the display coprocessors and their @@ -377,7 +380,9 @@ allOf: locked, and the operating system only adds page table entries in root slots that are empty at handoff. Their TLB command register answers translation queries; a stream is invalidated through the - TLB invalidation aperture instead. + TLB invalidation aperture instead. The T8152 AVD instance uses the + same invalidation aperture, but starts unlocked with inactive streams + and is initialized by the operating system after its PSD domain is on. properties: reg: minItems: 2 @@ -395,6 +400,17 @@ allOf: - const: dart - enum: [dapf, gapf, ps-wr-dis, auxiliary] + - if: + properties: + compatible: + contains: + const: apple,t8152-avd-dart + then: + required: + - power-domains + - apple,dma-range + - apple,tunable + additionalProperties: false examples: From 90d575a1a46ec7ff504de4bcacb5413e55d04fc4 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 12:16:30 +0100 Subject: [PATCH 0572/1514] iommu: apple-dart: initialize the inactive T8152 AVD Gen3 DART Admit cold Gen3 setup only for the instance its apple,t8152-avd-dart compatible selects, with version 0x300, 16 streams, its PSD domain, ADT tunables and inactive streams 0..2. Clear those streams, apply their tunables and use the Gen3 TLBI aperture before enabling translation. Map the TLBI aperture before reset and select a two-level 16K page table inside a single 64 GiB high DMA window. Keep the existing locked display DART admission and all other unlocked Gen3 instances unchanged. On J873g this maps all three decoder streams for bit-exact H.264, HEVC, HEVC Main10, VP9 and AV1 decoding. Gen3 fault IRQ handling and suspend recovery remain outside this initial bring-up. Signed-off-by: Thomas Glanzmann --- drivers/iommu/apple-dart.c | 83 +++++++++++++------ .../drivers/apple/bcm4377-radio-sids.py | 1 + 2 files changed, 58 insertions(+), 26 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index b37d1ce94e618d..56428e019b4cee 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -361,6 +361,7 @@ struct apple_dart_fw_tree { #define APPLE_DART_GAPF_PROTECT BIT(4) struct apple_dart { + bool cold_gen3; struct device *dev; const struct apple_dart_hw *hw; @@ -2661,6 +2662,17 @@ static int apple_dart_hw_reset(struct apple_dart *dart) struct apple_dart_stream_map stream_map; int i; + if (dart->cold_gen3) { + stream_map.dart = dart; + bitmap_zero(stream_map.sidmap, DART_MAX_STREAMS); + bitmap_set(stream_map.sidmap, 0, 3); + apple_dart_hw_disable_dma(&stream_map); + apple_dart_hw_clear_all_ttbrs(&stream_map); + apple_dart_apply_own_tunables(dart); + apple_dart_writel(dart, 7, dart->hw->enable_streams); + return dart->hw->invalidate_tlb(&stream_map); + } + if (dart->isp_host) return apple_dart_isp_host_reset(dart); if (dart->managed_sids || dart->cold_ane) @@ -3393,6 +3405,17 @@ static int __apple_dart_finalize_domain(struct apple_dart_domain *dart_domain, .iommu_dev = dart->dev, }; + if (dart->cold_gen3) { + if ((dma_min ^ dma_max) & ~DMA_BIT_MASK(36)) { + ret = -ERANGE; + goto done; + } + /* Gen3 selects the high DMA window separately from its two-level + * 16K page-table indices, as with iBoot's display streams. + */ + pgtbl_cfg.ias = 36; + } + if (dart->locked) { unsigned long *sidmap; int sid; @@ -5548,6 +5571,7 @@ static int apple_dart_probe(struct platform_device *pdev) dart->dev = dev; dart->hw = of_device_get_match_data(dev); dart->tunneled = tunneled; + dart->cold_gen3 = of_device_is_compatible(dev->of_node, "apple,t8152-avd-dart"); dart->cold_ane = of_device_is_compatible(dev->of_node, "apple,t8140-ane-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-ane-dart"); if (dart->cold_ane && !IS_BUILTIN(CONFIG_APPLE_DART)) @@ -5967,6 +5991,38 @@ static int apple_dart_probe(struct platform_device *pdev) ret = -EBUSY; goto err_clk_disable; } + if (dart->hw->gen3) { + struct resource *tlbi; + + /* Cold initialization is qualified only for the AVD instance. */ + if (!dart->locked && !dart->cold_gen3) { + dev_err(dev, "Gen3 DART is not locked; cold setup is not supported\n"); + ret = -ENODEV; + goto err_clk_disable; + } + if (dart->cold_gen3 && (dart->locked || dart->version != 0x300 || + dart->num_streams != 16 || !dev->pm_domain || !dart->tunables || + (apple_dart_readl(dart, dart->hw->enable_streams) & 7))) { + ret = -EINVAL; + goto err_clk_disable; + } + /* The aperture is shared by every Gen3 DART: map, do not claim. */ + tlbi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "tlbi"); + if (!tlbi || resource_size(tlbi) < 16) { + dev_err(dev, "Gen3 DART needs its TLBI aperture\n"); + ret = -EINVAL; + goto err_clk_disable; + } + dart->tlbi = devm_ioremap(dev, tlbi->start, resource_size(tlbi)); + if (!dart->tlbi) { + ret = -ENOMEM; + goto err_clk_disable; + } + dart->tlbi_route = apple_dart_readl(dart, DART_GEN3_TLBI_ROUTE) & 0xf; + dev_info(dev, "Gen3 DART, version %#x, TLBI route %u\n", + dart->version, dart->tlbi_route); + } + apple_dart_parse_sleep_list(dart, res, "apple,sleep-prepare", &dart->sleep_prepare); apple_dart_parse_sleep_list(dart, res, "apple,sleep-restore", &dart->sleep_restore); apple_dart_parse_sleep_list(dart, res, "apple,sleep-restore-late", @@ -6107,32 +6163,6 @@ static int apple_dart_probe(struct platform_device *pdev) goto err_clk_disable; } - if (dart->hw->gen3) { - struct resource *tlbi; - - /* Only an iBoot-provisioned (locked) Gen3 stream is supported. */ - if (!dart->locked) { - dev_err(dev, "Gen3 DART is not locked; cold setup is not supported\n"); - ret = -ENODEV; - goto err_clk_disable; - } - /* The aperture is shared by every Gen3 DART: map, do not claim. */ - tlbi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "tlbi"); - if (!tlbi || resource_size(tlbi) < 16) { - dev_err(dev, "Gen3 DART needs its TLBI aperture\n"); - ret = -EINVAL; - goto err_clk_disable; - } - dart->tlbi = devm_ioremap(dev, tlbi->start, resource_size(tlbi)); - if (!dart->tlbi) { - ret = -ENOMEM; - goto err_clk_disable; - } - dart->tlbi_route = apple_dart_readl(dart, DART_GEN3_TLBI_ROUTE) & 0xf; - dev_info(dev, "Gen3 DART, version %#x, TLBI route %u\n", - dart->version, dart->tlbi_route); - } - /* Borrowed display state: never acknowledge someone else's fault. */ if (dart->locked && !dart->preserve_display && !dart->hw->gen3) apple_dart_drain_stale_exceptions(dart); @@ -7394,6 +7424,7 @@ static const struct dev_pm_ops apple_dart_pm_ops = { static const struct of_device_id apple_dart_of_match[] = { { .compatible = "apple,t8152-dart-gen3", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-avd-dart", .data = &apple_dart_hw_gen3 }, { .compatible = "apple,t8103-dart", .data = &apple_dart_hw_t8103 }, { .compatible = "apple,t8103-usb4-dart", .data = &apple_dart_hw_t8103_usb4 }, { .compatible = "apple,t8110-dart", .data = &apple_dart_hw_t8110 }, diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index e13025a6157c5b..4a148b13d707d1 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -106,6 +106,7 @@ def main(): bool four_level, per_stream, tunneled, fw_mirror, fw_handoff; bool pending, preserve_display; bool isp_host, cold_ane, live_mtp, display_dark, display_tlb_stale; + bool cold_gen3; void *tunables; unsigned long static_bypass[4]; void *dcp, *frontend[2]; From d652d40bfc0297c88f130ba6f490e71be28ec6bf Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 12:16:30 +0100 Subject: [PATCH 0573/1514] media: dt-bindings: describe the T8152 Kopsia decoder Describe the Kopsia MCU, decoder, wrapper and PIODMA register apertures, its three DART streams and its shared PSD power domain. The initial transport submits from the host with the MCU halted and polls completion; it does not use the PostOffice mailbox or the legacy decoder reset line. Signed-off-by: Thomas Glanzmann --- .../bindings/media/apple,t8152-avd.yaml | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Documentation/devicetree/bindings/media/apple,t8152-avd.yaml diff --git a/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml b/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml new file mode 100644 index 00000000000000..585a0a897fed72 --- /dev/null +++ b/Documentation/devicetree/bindings/media/apple,t8152-avd.yaml @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/media/apple,t8152-avd.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8152 Kopsia video decoder + +maintainers: + - Thomas Glanzmann + +description: + Kopsia is the T8152 stateless video decoder. Its decoder, PIODMA and + auxiliary data streams share a Gen3 DART and a PSD power domain. The host + submits codec programs with the MCU halted and polls decoder status; + the PostOffice mailbox transport is not used by this implementation. + +properties: + compatible: + const: apple,t8152-avd + + reg: + items: + - description: MCU code memory + - description: MCU control registers + - description: Decoder control registers + - description: Decoder wrapper registers + - description: PIODMA registers + + reg-names: + items: + - const: code + - const: mbox + - const: ctrl + - const: wrap + - const: dma + + iommus: + items: + - description: Decoder stream + - description: PIODMA stream + - description: Auxiliary data stream + + power-domains: + maxItems: 1 + +required: + - compatible + - reg + - reg-names + - iommus + - power-domains + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + video-codec@485400000 { + compatible = "apple,t8152-avd"; + reg = <0x4 0x85400000 0x0 0x12000>, + <0x4 0x85500000 0x0 0x4000>, + <0x4 0x85100000 0x0 0x10000>, + <0x4 0x850c0000 0x0 0x4000>, + <0x4 0x85070000 0x0 0x4000>; + reg-names = "code", "mbox", "ctrl", "wrap", "dma"; + iommus = <&avd_dart 0>, <&avd_dart 1>, <&avd_dart 2>; + power-domains = <&ps_avd>; + }; + }; From ec2d4767bbb29715c0bdd66b4302955898e7424e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 12:16:30 +0100 Subject: [PATCH 0574/1514] media: apple: avd: add a polled host backend for T8152 Kopsia T8152 Kopsia retains the T8142 codec program format but uses different initialization and completion registers. Add a host backend that halts the MCU, initializes the wrapper and PIODMA, and reuses the existing codec submission and completion logic with one frame in flight. Poll VP/PP status only while a frame is active. Enable H.264, HEVC, VP9 and AV1 on this variant without an external firmware image. Retain the 128-byte H.264 MV and HEVC v5 header quirks. Disable recovery reset: the existing watchdog parks DMA and retires the decoder instead of issuing an unqualified reset. The 346 register tunables are unchanged from the MIT-licensed avd-fw v5/tier2 table. The J873g ADT's avd node carries no tunables of its own (unlike its DART's), so there is nothing T8152-specific to describe in the device tree. The table was checked on the J873g by its output: with it, H.264, HEVC, HEVC Main10, VP9 and AV1 decode bit-exact against software (60 frames each), 4K60 H.264 runs at about 150 fps, and the results stay exact across hundreds of power-domain cycles, each of which applies the table again. On J873g, forced DRM PRIME decode and download compares exactly with software for 60 frames of each codec, including HEVC Main10; mpv also renders through DRM PRIME and seeks in both directions. The decoder is runtime power-gated through its PSD domain: the backend is set up again on every resume. A DART fault (injected on the J873g) retires the decoder through the existing recovery path until the module is reloaded. PostOffice completion and suspend/resume remain outstanding. Link: https://github.com/aurora-silicon/avd-fw/blob/ea3a65cc9c0c41907e6ad2714b813e4be6858485/src/hw/tunables/tunables_v5t2.h Signed-off-by: Thomas Glanzmann --- drivers/media/platform/apple/avd/Kconfig | 4 +- drivers/media/platform/apple/avd/Makefile | 2 +- .../platform/apple/avd/avd-backend-kopsia.c | 176 +++++++++ .../platform/apple/avd/avd-backend-open.c | 24 +- drivers/media/platform/apple/avd/avd-drv.c | 53 ++- .../platform/apple/avd/avd-kopsia-tunables.h | 350 ++++++++++++++++++ drivers/media/platform/apple/avd/avd.h | 5 + 7 files changed, 595 insertions(+), 19 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-backend-kopsia.c create mode 100644 drivers/media/platform/apple/avd/avd-kopsia-tunables.h diff --git a/drivers/media/platform/apple/avd/Kconfig b/drivers/media/platform/apple/avd/Kconfig index d3bb9763b6230e..4aa061da424e69 100644 --- a/drivers/media/platform/apple/avd/Kconfig +++ b/drivers/media/platform/apple/avd/Kconfig @@ -14,7 +14,9 @@ config VIDEO_APPLE_AVD help Support the Apple Silicon stateless video decoder. - Build the decoder firmware from https://github.com/aurora-silicon/avd-fw + T8152 uses host submission and does not need a firmware image. + + For earlier SoCs, build the decoder firmware from https://github.com/aurora-silicon/avd-fw and install it under /lib/firmware/apple/. J700/T8140 uses the avd-fw-v5-t0.bin image. Firmware is supplied separately from this driver. diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 60560dbab592a1..66b8e3c61356a6 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -2,7 +2,7 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ - avd-backend-apple.o avd-backend-queue.o + avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o avd-queue-test.o \ avd-pm-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-backend-kopsia.c b/drivers/media/platform/apple/avd/avd-backend-kopsia.c new file mode 100644 index 00000000000000..f242e90d4be8aa --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-backend-kopsia.c @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * T8152 Kopsia bring-up: host submission and polled VP/PP completion. + * + * Completion is polled because no decoder interrupt is described: the ADT's + * avd node lists only its PostOffice mailbox pair (AIC 308 and 268, mailbox + * 9's send-empty and recv-not-empty), and with the MCU halted nothing is known + * to raise them. The poll runs only while a frame is active. + */ +#include +#include +#include "avd.h" + +#define KOPSIA_STATUS(n) (0x194 + 4 * (n)) +#define KOPSIA_ERROR BIT(1) +#define KOPSIA_DONE BIT(2) +#define KOPSIA_PP 13 + +struct avd_kopsia_tunable { u32 off, mask, val; }; +#include "avd-kopsia-tunables.h" + +struct avd_kopsia { + struct avd_dev *avd; + void __iomem *wrap; + void __iomem *dma; + struct work_struct poll_work; + bool running; +}; + +static void kopsia_update(void __iomem *reg, u32 mask, u32 value) +{ + writel((readl(reg) & ~mask) | value, reg); +} + +static int avd_kopsia_boot(struct avd_dev *avd) +{ + struct avd_kopsia *k = avd->backend_priv; + unsigned int i; + + if (readl(avd->ctrl) != 0x40030) + return -ENODEV; + + /* Keep the MCU halted: this transport owns the hardware status bits. */ + writel(0xe, avd->mbox + 0x28); + kopsia_update(avd->mbox + 0x40, BIT(24), BIT(24)); + writel(0, avd->mbox + 0x104); + writel(1, k->wrap + 0x18); + writel(0, k->dma); + writel(0x20, avd->ctrl + 0x1cc); + writel(U32_MAX, avd->ctrl + 0xe6d0); + writel(U32_MAX, avd->ctrl + 0xe6d4); + writel(U32_MAX, avd->ctrl + 0xe710); + writel(U32_MAX, avd->ctrl + 0xe714); + for (i = 0; i < ARRAY_SIZE(kopsia_tunables); i++) { + const struct avd_kopsia_tunable *t = &kopsia_tunables[i]; + + kopsia_update(avd->ctrl + t->off, t->mask, t->val); + } + kopsia_update(k->wrap + 0x14, 1, 1); + kopsia_update(k->wrap + 0x18, 1, 1); + kopsia_update(k->wrap + 0x4c, 1, 1); + kopsia_update(k->dma, 2, 0); + kopsia_update(k->dma + 0x10, 0x1ff8000f, 2); + kopsia_update(k->dma + 0x14, 0x1ff8000f, 2); + kopsia_update(k->dma + 0x18, 0x1ff8000f, 3); + kopsia_update(k->dma + 0x1c, 0xf, 0); + kopsia_update(k->dma + 0x20, 0xf, 0); + for (i = 0; i <= KOPSIA_PP; i++) + writel(KOPSIA_DONE | KOPSIA_ERROR, avd->ctrl + KOPSIA_STATUS(i)); + k->running = true; + dev_info_once(avd->dev, "Kopsia host backend, decoder %#x (polled completion)\n", + readl(avd->ctrl)); + return 0; +} + +static void avd_kopsia_shutdown(struct avd_dev *avd) +{ + struct avd_kopsia *k = avd->backend_priv; + + /* Serialized against polling by queue_mutex or the idle PM reference. */ + WRITE_ONCE(k->running, false); +} + +static void avd_kopsia_poll(struct work_struct *work) +{ + struct avd_kopsia *k = container_of(work, struct avd_kopsia, poll_work); + struct avd_dev *avd = k->avd; + + for (;;) { + struct avd_frame *f; + u32 vp, status; + bool active; + + mutex_lock(&avd->queue_mutex); + f = avd->compat_active; + if (!READ_ONCE(k->running) || !f || avd->stopping || avd->faulted) { + mutex_unlock(&avd->queue_mutex); + break; + } + vp = avd->variant->vp_slot_base[f->cmd[0]]; + status = readl(avd->ctrl + KOPSIA_STATUS(vp)); + if (status & KOPSIA_ERROR) { + writel(KOPSIA_ERROR, avd->ctrl + KOPSIA_STATUS(vp)); + avd_status(avd, vp); + avd_open_complete(avd, vp); + mutex_unlock(&avd->queue_mutex); + break; + } + if (status & KOPSIA_DONE) { + writel(KOPSIA_DONE, avd->ctrl + KOPSIA_STATUS(vp)); + avd_open_complete(avd, 0x100 | vp); + } + status = readl(avd->ctrl + KOPSIA_STATUS(KOPSIA_PP)); + if (status & KOPSIA_DONE) { + writel(KOPSIA_DONE, avd->ctrl + KOPSIA_STATUS(KOPSIA_PP)); + avd_open_complete(avd, 0x1000); + } + active = avd->compat_active != NULL; + mutex_unlock(&avd->queue_mutex); + if (!active) + break; + usleep_range(100, 200); + } +} + +static int avd_kopsia_submit(struct avd_dev *avd, struct avd_frame *f) +{ + struct avd_kopsia *k = avd->backend_priv; + int ret = avd_open_submit(avd, f); + + if (!ret) + queue_work(system_dfl_wq, &k->poll_work); + return ret; +} + +static unsigned int avd_kopsia_max_inflight(struct avd_dev *avd) +{ + return 1; +} + +static void avd_kopsia_cleanup(void *data) +{ + struct avd_kopsia *k = data; + + WRITE_ONCE(k->running, false); + cancel_work_sync(&k->poll_work); +} + +static int avd_kopsia_probe(struct avd_dev *avd) +{ + struct avd_kopsia *k = devm_kzalloc(avd->dev, sizeof(*k), GFP_KERNEL); + + if (!k) + return -ENOMEM; + k->avd = avd; + k->wrap = devm_platform_ioremap_resource_byname(avd->pdev, "wrap"); + if (IS_ERR(k->wrap)) + return PTR_ERR(k->wrap); + k->dma = devm_platform_ioremap_resource_byname(avd->pdev, "dma"); + if (IS_ERR(k->dma)) + return PTR_ERR(k->dma); + INIT_WORK(&k->poll_work, avd_kopsia_poll); + avd->backend_priv = k; + return devm_add_action_or_reset(avd->dev, avd_kopsia_cleanup, k); +} + +const struct avd_backend_ops avd_kopsia_backend = { + .name = "kopsia-host", + .probe = avd_kopsia_probe, + .boot = avd_kopsia_boot, + .shutdown = avd_kopsia_shutdown, + .max_inflight = avd_kopsia_max_inflight, + .submit = avd_kopsia_submit, + .suspend = avd_pm_backend_suspend, + .resume = avd_pm_backend_resume, +}; diff --git a/drivers/media/platform/apple/avd/avd-backend-open.c b/drivers/media/platform/apple/avd/avd-backend-open.c index 525c7848b4edcc..13508cc5d5272d 100644 --- a/drivers/media/platform/apple/avd/avd-backend-open.c +++ b/drivers/media/platform/apple/avd/avd-backend-open.c @@ -74,7 +74,7 @@ static unsigned int avd_open_max_inflight(struct avd_dev *avd) return 1; } -static int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) +int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) { struct avd_ctx *ctx = f->ctx; u32 codec = f->cmd[0], vp = 0; @@ -131,13 +131,9 @@ static int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) return 0; } -static irqreturn_t avd_open_irq(struct avd_dev *avd) +irqreturn_t avd_open_complete(struct avd_dev *avd, u32 status) { struct avd_frame *f = avd->compat_active; - u32 status; - - if (!avd_mbox_pop(avd, &status)) - return IRQ_HANDLED; if (!f) { /* * The old driver kicked PP for every VP DONE. A VP DONE with no @@ -177,6 +173,15 @@ static irqreturn_t avd_open_irq(struct avd_dev *avd) return IRQ_HANDLED; } +static irqreturn_t avd_open_irq(struct avd_dev *avd) +{ + u32 status; + + if (!avd_mbox_pop(avd, &status)) + return IRQ_HANDLED; + return avd_open_complete(avd, status); +} + bool avd_backend_is_open(const struct avd_dev *avd) { return avd->backend == &avd_open_backend; @@ -241,6 +246,13 @@ int avd_backend_select(struct avd_dev *avd) { int ret; + if (avd->variant->quirks & AVD_QUIRK_KOPSIA) { + avd->backend = &avd_kopsia_backend; + avd->capabilities = avd->variant->capabilities; + avd->fw_capabilities = avd->capabilities; + return avd->backend->probe(avd); + } + /* Apple probe returns -ENOENT only when no usable image is present. */ if (avd->variant->apple) { ret = avd_apple_backend.probe(avd); diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 58ea3fc604d875..2b8ee0f381274c 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -590,8 +590,35 @@ static const struct avd_variant avd_t8142_variant = { .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_H264_MV_128, }; +static const struct avd_variant avd_t8152_variant = { + .vp_slots = { + [AVD_CODEC_HEVC] = 2, + [AVD_CODEC_H264] = 1, + [AVD_CODEC_VP9] = 1, + [AVD_CODEC_AV1] = 1, + }, + .vp_slot_base = { + [AVD_CODEC_HEVC] = 0, + [AVD_CODEC_H264] = 4, + [AVD_CODEC_VP9] = 8, + [AVD_CODEC_AV1] = 9, + }, + .fifo_slots = 7, + .configure_stream = t8122_configure_stream, + .capabilities = AVD_CAPABILITY_H264 | AVD_CAPABILITY_HEVC | + AVD_CAPABILITY_VP9 | AVD_CAPABILITY_AV1, + .revision = 4, + .vp_slot_offset = 0xc, + .submit_offset = 0x40, + .submit_queue_max_offset = 0x44, + .submit_queue_status_offset = 0x7c, + .quirks = AVD_QUIRK_HEVC_V5_HEADER | AVD_QUIRK_H264_MV_128 | + AVD_QUIRK_NO_RECOVERY_RESET | AVD_QUIRK_KOPSIA, +}; + /* can also be derived from a version register */ static const struct of_device_id avd_of_match[] = { + { .compatible = "apple,t8152-avd", .data = &avd_t8152_variant }, { .compatible = "apple,t8103-avd", .data = &avd_t8103_variant @@ -667,7 +694,8 @@ static int avd_probe(struct platform_device *pdev) match = of_match_node(avd_of_match, pdev->dev.of_node); avd->variant = match->data; - avd->rstc = devm_reset_control_get_exclusive(avd->dev, NULL); + avd->rstc = avd->variant->quirks & AVD_QUIRK_KOPSIA ? NULL : + devm_reset_control_get_exclusive(avd->dev, NULL); if (IS_ERR(avd->rstc)) return PTR_ERR(avd->rstc); @@ -729,16 +757,19 @@ static int avd_probe(struct platform_device *pdev) return ret; } - irq = platform_get_irq(pdev, 1); - if (irq < 0) - return irq; - avd->pm.irq = irq; - ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, - avd_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, - dev_name(&pdev->dev), avd); - if (ret) { - dev_err(avd->dev, "Could not request IRQ 1"); - return ret; + /* Kopsia has no described completion interrupt; its backend polls. */ + if (!(avd->variant->quirks & AVD_QUIRK_KOPSIA)) { + irq = platform_get_irq(pdev, 1); + if (irq < 0) + return irq; + avd->pm.irq = irq; + ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, + avd_irq_handler, IRQF_ONESHOT | IRQF_NO_AUTOEN, + dev_name(&pdev->dev), avd); + if (ret) { + dev_err(avd->dev, "Could not request IRQ 1"); + return ret; + } } /* diff --git a/drivers/media/platform/apple/avd/avd-kopsia-tunables.h b/drivers/media/platform/apple/avd/avd-kopsia-tunables.h new file mode 100644 index 00000000000000..95fb2d6d4792a9 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-kopsia-tunables.h @@ -0,0 +1,350 @@ +/* SPDX-License-Identifier: MIT */ +/* avd-fw v5/tier2 table, Copyright The Asahi Linux Contributors. */ +static const struct avd_kopsia_tunable kopsia_tunables[] = { + {0x0008, 0x80000000, 0x80000000}, /* MCTL_MODE */ + {0x1000, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1100, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1200, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1300, 0x80000000, 0x80000000}, /* HEVC_MODE */ + {0x1400, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1500, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1600, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1700, 0x80000000, 0x80000000}, /* H264_MODE */ + {0x1800, 0x80000000, 0x80000000}, /* VP9_MODE */ + {0x1900, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x1a00, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x1b00, 0x80000000, 0x80000000}, /* AV1_MODE */ + {0x4000, 0x80000000, 0x80000000}, /* QT_MODE */ + {0x4100, 0x80000000, 0x80000000}, /* IPMC_MODE */ + {0x4200, 0x80000000, 0x80000000}, /* LF_MODE */ + {0x4300, 0x80000000, 0x80000000}, /* MV_MODE */ + {0x4400, 0x80000000, 0x80000000}, /* TP_MODE */ + {0x4500, 0x80000000, 0x80000000}, /* PC_MODE */ + {0x4600, 0x80000000, 0x80000000}, /* SW_MODE */ + {0x4700, 0x80000000, 0x80000000}, /* LR_MODE */ + {0xc000, 0x00000001, 0x00000001}, /* VP_TOP_CLOCK_GATING */ + {0xc080, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc084, 0x1fff1fff, 0x00000028}, /* BUF */ + {0xc090, 0x000000ff, 0x00000001}, /* EXT */ + {0xc0c0, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc0c4, 0x1fff1fff, 0x00280028}, /* BUF */ + {0xc0d0, 0x000000ff, 0x00000002}, /* EXT */ + {0xc100, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc104, 0x1fff1fff, 0x00500028}, /* BUF */ + {0xc110, 0x000000ff, 0x00000003}, /* EXT */ + {0xc140, 0x800f0000, 0x80020000}, /* R_HEVC_BITS */ + {0xc144, 0x1fff1fff, 0x00780028}, /* BUF */ + {0xc150, 0x000000ff, 0x00000004}, /* EXT */ + {0xc180, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc184, 0x0fff0fff, 0x00be0028}, /* BUF */ + {0xc190, 0x000000ff, 0x00000056}, /* EXT */ + {0xc1c0, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc1c4, 0x0fff0fff, 0x00e60028}, /* BUF */ + {0xc1d0, 0x000000ff, 0x00000057}, /* EXT */ + {0xc200, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc204, 0x0fff0fff, 0x010e0028}, /* BUF */ + {0xc210, 0x000000ff, 0x00000058}, /* EXT */ + {0xc240, 0x800f0000, 0x80010000}, /* W_HEVC_INSN */ + {0xc244, 0x0fff0fff, 0x01360028}, /* BUF */ + {0xc250, 0x000000ff, 0x00000059}, /* EXT */ + {0xc280, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc284, 0x1fff1fff, 0x00a00020}, /* BUF */ + {0xc290, 0x000000ff, 0x0000000d}, /* EXT */ + {0xc2c0, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc2c4, 0x1fff1fff, 0x00c00020}, /* BUF */ + {0xc2d0, 0x000000ff, 0x0000000e}, /* EXT */ + {0xc300, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc304, 0x1fff1fff, 0x00e00020}, /* BUF */ + {0xc310, 0x000000ff, 0x0000000f}, /* EXT */ + {0xc340, 0x800f0000, 0x80020000}, /* R_H264_BITS */ + {0xc344, 0x1fff1fff, 0x01000020}, /* BUF */ + {0xc350, 0x000000ff, 0x00000010}, /* EXT */ + {0xc380, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc384, 0x0fff0fff, 0x00000004}, /* BUF */ + {0xc390, 0x000000ff, 0x00000011}, /* EXT */ + {0xc3c0, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc3c4, 0x0fff0fff, 0x00040004}, /* BUF */ + {0xc3d0, 0x000000ff, 0x00000012}, /* EXT */ + {0xc400, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc404, 0x0fff0fff, 0x00080004}, /* BUF */ + {0xc410, 0x000000ff, 0x00000013}, /* EXT */ + {0xc440, 0x800f0000, 0x80020000}, /* W_H264_ABOVE_INFO */ + {0xc444, 0x0fff0fff, 0x000c0004}, /* BUF */ + {0xc450, 0x000000ff, 0x00000014}, /* EXT */ + {0xc480, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc484, 0x1fff1fff, 0x01200006}, /* BUF */ + {0xc490, 0x000000ff, 0x00000015}, /* EXT */ + {0xc4c0, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc4c4, 0x1fff1fff, 0x01260006}, /* BUF */ + {0xc4d0, 0x000000ff, 0x00000016}, /* EXT */ + {0xc500, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc504, 0x1fff1fff, 0x012c0006}, /* BUF */ + {0xc510, 0x000000ff, 0x00000017}, /* EXT */ + {0xc540, 0x800f0000, 0x80020000}, /* R_H264_ABOVE_INFO */ + {0xc544, 0x1fff1fff, 0x01320006}, /* BUF */ + {0xc550, 0x000000ff, 0x00000018}, /* EXT */ + {0xc580, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc584, 0x0fff0fff, 0x015e0020}, /* BUF */ + {0xc590, 0x000000ff, 0x0000005a}, /* EXT */ + {0xc5c0, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc5c4, 0x0fff0fff, 0x017e0020}, /* BUF */ + {0xc5d0, 0x000000ff, 0x0000005b}, /* EXT */ + {0xc600, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc604, 0x0fff0fff, 0x019e0020}, /* BUF */ + {0xc610, 0x000000ff, 0x0000005c}, /* EXT */ + {0xc640, 0x800f0000, 0x80010000}, /* W_H264_INSN */ + {0xc644, 0x0fff0fff, 0x01be0020}, /* BUF */ + {0xc650, 0x000000ff, 0x0000005d}, /* EXT */ + {0xc680, 0x800f0000, 0x80020000}, /* R_VP9_BITS */ + {0xc684, 0x1fff1fff, 0x01380018}, /* BUF */ + {0xc690, 0x000000ff, 0x00000021}, /* EXT */ + {0xc6c0, 0x800f0000, 0x80020000}, /* W_VP9_ABOVE_INFO */ + {0xc6c4, 0x0fff0fff, 0x0010000a}, /* BUF */ + {0xc6d0, 0x000000ff, 0x00000022}, /* EXT */ + {0xc700, 0x800f0000, 0x80020000}, /* R_VP9_ABOVE_INFO */ + {0xc704, 0x1fff1fff, 0x0150000e}, /* BUF */ + {0xc710, 0x000000ff, 0x00000023}, /* EXT */ + {0xc740, 0x800f0000, 0x80020000}, /* W_VP9_SEG */ + {0xc744, 0x0fff0fff, 0x001a000a}, /* BUF */ + {0xc750, 0x000000ff, 0x00000024}, /* EXT */ + {0xc780, 0x800f0000, 0x80020000}, /* R_VP9_SEG */ + {0xc784, 0x1fff1fff, 0x015e000a}, /* BUF */ + {0xc790, 0x000000ff, 0x00000025}, /* EXT */ + {0xc7c0, 0x800f0000, 0x80020000}, /* W_VP9_COLOR */ + {0xc7c4, 0x0fff0fff, 0x0024000c}, /* BUF */ + {0xc7d0, 0x000000ff, 0x00000026}, /* EXT */ + {0xc800, 0x800f0000, 0x80020000}, /* R_VP9_COLOR */ + {0xc804, 0x1fff1fff, 0x01680012}, /* BUF */ + {0xc810, 0x000000ff, 0x00000027}, /* EXT */ + {0xc840, 0x800f0000, 0x80020000}, /* W_VP9_STATE */ + {0xc844, 0x0fff0fff, 0x0030000a}, /* BUF */ + {0xc850, 0x000000ff, 0x00000028}, /* EXT */ + {0xc880, 0x800f0000, 0x80020000}, /* R_VP9_STATE */ + {0xc884, 0x1fff1fff, 0x017a000a}, /* BUF */ + {0xc890, 0x000000ff, 0x00000029}, /* EXT */ + {0xc8c0, 0x800f0000, 0x80010000}, /* W_VP9_INSN */ + {0xc8c4, 0x0fff0fff, 0x01de0018}, /* BUF */ + {0xc8d0, 0x000000ff, 0x0000005e}, /* EXT */ + {0xc900, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc904, 0x1fff1fff, 0x01840016}, /* BUF */ + {0xc910, 0x000000ff, 0x0000002a}, /* EXT */ + {0xc940, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc944, 0x1fff1fff, 0x019a0016}, /* BUF */ + {0xc950, 0x000000ff, 0x0000002b}, /* EXT */ + {0xc980, 0x800f0000, 0x80020000}, /* R_AV1_BITS */ + {0xc984, 0x1fff1fff, 0x01b00016}, /* BUF */ + {0xc990, 0x000000ff, 0x0000002c}, /* EXT */ + {0xca00, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca04, 0x0fff0fff, 0x003a000a}, /* BUF */ + {0xca10, 0x000000ff, 0x0000002e}, /* EXT */ + {0xca40, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca44, 0x0fff0fff, 0x0044000a}, /* BUF */ + {0xca50, 0x000000ff, 0x0000002f}, /* EXT */ + {0xca80, 0x800f0000, 0x80020000}, /* W_AV1_ABOVE_INFO */ + {0xca84, 0x0fff0fff, 0x004e000a}, /* BUF */ + {0xca90, 0x000000ff, 0x00000030}, /* EXT */ + {0xcb00, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb04, 0x1fff1fff, 0x01c60014}, /* BUF */ + {0xcb10, 0x000000ff, 0x00000032}, /* EXT */ + {0xcb40, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb44, 0x1fff1fff, 0x01da0014}, /* BUF */ + {0xcb50, 0x000000ff, 0x00000033}, /* EXT */ + {0xcb80, 0x800f0000, 0x80020000}, /* R_AV1_ABOVE_INFO */ + {0xcb84, 0x1fff1fff, 0x01ee0014}, /* BUF */ + {0xcb90, 0x000000ff, 0x00000034}, /* EXT */ + {0xcc00, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc04, 0x0fff0fff, 0x00580004}, /* BUF */ + {0xcc10, 0x000000ff, 0x00000036}, /* EXT */ + {0xcc40, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc44, 0x0fff0fff, 0x005c0004}, /* BUF */ + {0xcc50, 0x000000ff, 0x00000037}, /* EXT */ + {0xcc80, 0x800f0000, 0x80020000}, /* W_AV1_SEG */ + {0xcc84, 0x0fff0fff, 0x00600004}, /* BUF */ + {0xcc90, 0x000000ff, 0x00000038}, /* EXT */ + {0xcd00, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd04, 0x1fff1fff, 0x02020008}, /* BUF */ + {0xcd10, 0x000000ff, 0x0000003a}, /* EXT */ + {0xcd40, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd44, 0x1fff1fff, 0x020a0008}, /* BUF */ + {0xcd50, 0x000000ff, 0x0000003b}, /* EXT */ + {0xcd80, 0x800f0000, 0x80020000}, /* R_AV1_SEG */ + {0xcd84, 0x1fff1fff, 0x02120008}, /* BUF */ + {0xcd90, 0x000000ff, 0x0000003c}, /* EXT */ + {0xce00, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce04, 0x0fff0fff, 0x00640008}, /* BUF */ + {0xce10, 0x000000ff, 0x0000003e}, /* EXT */ + {0xce40, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce44, 0x0fff0fff, 0x006c0008}, /* BUF */ + {0xce50, 0x000000ff, 0x0000003f}, /* EXT */ + {0xce80, 0x800f0000, 0x80020000}, /* W_AV1_COLOR */ + {0xce84, 0x0fff0fff, 0x00740008}, /* BUF */ + {0xce90, 0x000000ff, 0x00000040}, /* EXT */ + {0xcf00, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf04, 0x1fff1fff, 0x021a0010}, /* BUF */ + {0xcf10, 0x000000ff, 0x00000042}, /* EXT */ + {0xcf40, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf44, 0x1fff1fff, 0x022a0010}, /* BUF */ + {0xcf50, 0x000000ff, 0x00000043}, /* EXT */ + {0xcf80, 0x800f0000, 0x80020000}, /* R_AV1_COLOR0 */ + {0xcf84, 0x1fff1fff, 0x023a0010}, /* BUF */ + {0xcf90, 0x000000ff, 0x00000044}, /* EXT */ + {0xd000, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd004, 0x1fff1fff, 0x024a0010}, /* BUF */ + {0xd010, 0x000000ff, 0x00000046}, /* EXT */ + {0xd040, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd044, 0x1fff1fff, 0x025a0010}, /* BUF */ + {0xd050, 0x000000ff, 0x00000047}, /* EXT */ + {0xd080, 0x800f0000, 0x80020000}, /* R_AV1_COLOR1 */ + {0xd084, 0x1fff1fff, 0x026a0010}, /* BUF */ + {0xd090, 0x000000ff, 0x00000048}, /* EXT */ + {0xd100, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd104, 0x1fff1fff, 0x027a0010}, /* BUF */ + {0xd110, 0x000000ff, 0x0000004a}, /* EXT */ + {0xd140, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd144, 0x1fff1fff, 0x028a0010}, /* BUF */ + {0xd150, 0x000000ff, 0x0000004b}, /* EXT */ + {0xd180, 0x800f0000, 0x80020000}, /* R_AV1_COLOR2 */ + {0xd184, 0x1fff1fff, 0x029a0010}, /* BUF */ + {0xd190, 0x000000ff, 0x0000004c}, /* EXT */ + {0xd200, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd204, 0x0fff0fff, 0x007c0016}, /* BUF */ + {0xd210, 0x000000ff, 0x0000004e}, /* EXT */ + {0xd240, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd244, 0x0fff0fff, 0x00920016}, /* BUF */ + {0xd250, 0x000000ff, 0x0000004f}, /* EXT */ + {0xd280, 0x800f0000, 0x80020000}, /* W_AV1_PROBS */ + {0xd284, 0x0fff0fff, 0x00a80016}, /* BUF */ + {0xd290, 0x000000ff, 0x00000050}, /* EXT */ + {0xd300, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd304, 0x1fff1fff, 0x02aa0074}, /* BUF */ + {0xd310, 0x000000ff, 0x00000052}, /* EXT */ + {0xd340, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd344, 0x1fff1fff, 0x031e0074}, /* BUF */ + {0xd350, 0x000000ff, 0x00000053}, /* EXT */ + {0xd380, 0x800f0000, 0x80020000}, /* R_AV1_PROBS */ + {0xd384, 0x1fff1fff, 0x03920074}, /* BUF */ + {0xd390, 0x000000ff, 0x00000054}, /* EXT */ + {0xd400, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd404, 0x0fff0fff, 0x01f60016}, /* BUF */ + {0xd410, 0x000000ff, 0x0000005f}, /* EXT */ + {0xd440, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd444, 0x0fff0fff, 0x020c0016}, /* BUF */ + {0xd450, 0x000000ff, 0x00000060}, /* EXT */ + {0xd480, 0x800f0000, 0x80010000}, /* W_AV1_INSN */ + {0xd484, 0x0fff0fff, 0x02220016}, /* BUF */ + {0xd490, 0x000000ff, 0x00000061}, /* EXT */ + {0xd500, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd504, 0x1fff1fff, 0x040600f2}, /* BUF */ + {0xd510, 0x000000ff, 0x00000063}, /* EXT */ + {0xd540, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd544, 0x1fff1fff, 0x04f800f2}, /* BUF */ + {0xd550, 0x000000ff, 0x00000064}, /* EXT */ + {0xd580, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd584, 0x1fff1fff, 0x05ea00f2}, /* BUF */ + {0xd590, 0x000000ff, 0x00000065}, /* EXT */ + {0xd5c0, 0x800f3c00, 0x80011000}, /* R_PIPE_INSN */ + {0xd5c4, 0x1fff1fff, 0x06dc00f2}, /* BUF */ + {0xd5d0, 0x000000ff, 0x00000066}, /* EXT */ + {0xe000, 0x00000001, 0x00000001}, /* INTRA_TOP_CLOCK_GATING */ + {0xe080, 0x800f0000, 0x80020000}, /* W_IP_ABOVE_PIX */ + {0xe084, 0x0fff0fff, 0x0000001c}, /* BUF */ + {0xe090, 0x000000ff, 0x00000069}, /* EXT */ + {0xe0c0, 0x800f0000, 0x80020000}, /* R_IP_ABOVE_PIX */ + {0xe0c4, 0x1fff1fff, 0x0000002e}, /* BUF */ + {0xe0d0, 0x000000ff, 0x0000006a}, /* EXT */ + {0xe100, 0x800f0000, 0x80020000}, /* W_LF_ABOVE_PIX */ + {0xe104, 0x0fff0fff, 0x001c0054}, /* BUF */ + {0xe110, 0x000000ff, 0x00000071}, /* EXT */ + {0xe140, 0x800f0000, 0x80020000}, /* R_LF_ABOVE_PIX */ + {0xe144, 0x1fff1fff, 0x002e009e}, /* BUF */ + {0xe150, 0x000000ff, 0x00000072}, /* EXT */ + {0xe180, 0x800f0000, 0x80020000}, /* W_LF_ABOVE_INFO */ + {0xe184, 0x0fff0fff, 0x00700016}, /* BUF */ + {0xe190, 0x000000ff, 0x0000006f}, /* EXT */ + {0xe1c0, 0x800f0000, 0x80020000}, /* R_LF_ABOVE_INFO */ + {0xe1c4, 0x1fff1fff, 0x00cc0022}, /* BUF */ + {0xe1d0, 0x000000ff, 0x00000070}, /* EXT */ + {0xe200, 0x800f0000, 0x80020000}, /* W_LF_LEFT_PIX */ + {0xe204, 0x0fff0fff, 0x00860032}, /* BUF */ + {0xe210, 0x000000ff, 0x00000075}, /* EXT */ + {0xe240, 0x800f0000, 0x80020000}, /* R_LF_LEFT_PIX */ + {0xe244, 0x1fff1fff, 0x00ee0032}, /* BUF */ + {0xe250, 0x000000ff, 0x00000076}, /* EXT */ + {0xe280, 0x800f0000, 0x80020000}, /* W_LF_LEFT_INFO */ + {0xe284, 0x0fff0fff, 0x00b8000c}, /* BUF */ + {0xe290, 0x000000ff, 0x00000073}, /* EXT */ + {0xe2c0, 0x800f0000, 0x80020000}, /* R_LF_LEFT_INFO */ + {0xe2c4, 0x1fff1fff, 0x0120000c}, /* BUF */ + {0xe2d0, 0x000000ff, 0x00000074}, /* EXT */ + {0xe300, 0x800f0000, 0x80020000}, /* W_SR_LEFT_PIX */ + {0xe304, 0x0fff0fff, 0x00c40046}, /* BUF */ + {0xe310, 0x000000ff, 0x00000077}, /* EXT */ + {0xe340, 0x800f0000, 0x80020000}, /* R_SR_LEFT_PIX */ + {0xe344, 0x1fff1fff, 0x012c0046}, /* BUF */ + {0xe350, 0x000000ff, 0x00000078}, /* EXT */ + {0xe380, 0x800f0000, 0x80020000}, /* W_RF_ABOVE_INFO */ + {0xe384, 0x0fff0fff, 0x010a001a}, /* BUF */ + {0xe390, 0x000000ff, 0x00000079}, /* EXT */ + {0xe3c0, 0x800f0000, 0x80020000}, /* R_RF_ABOVE_INFO */ + {0xe3c4, 0x1fff1fff, 0x01720032}, /* BUF */ + {0xe3d0, 0x000000ff, 0x0000007a}, /* EXT */ + {0xe400, 0x800f0000, 0x80020000}, /* W_RF_LEFT_PIX */ + {0xe404, 0x0fff0fff, 0x0124002a}, /* BUF */ + {0xe410, 0x000000ff, 0x0000007d}, /* EXT */ + {0xe440, 0x800f0000, 0x80020000}, /* R_RF_LEFT_PIX */ + {0xe444, 0x1fff1fff, 0x01a4002a}, /* BUF */ + {0xe450, 0x000000ff, 0x0000007e}, /* EXT */ + {0xe480, 0x800f0000, 0x80020000}, /* W_RF_LEFT_INFO */ + {0xe484, 0x0fff0fff, 0x014e000a}, /* BUF */ + {0xe490, 0x000000ff, 0x0000007b}, /* EXT */ + {0xe4c0, 0x800f0000, 0x80020000}, /* R_RF_LEFT_INFO */ + {0xe4c4, 0x1fff1fff, 0x01ce000a}, /* BUF */ + {0xe4d0, 0x000000ff, 0x0000007c}, /* EXT */ + {0xe500, 0x800f7c00, 0x80027c00}, /* W_SW_PIX */ + {0xe504, 0x0fff0fff, 0x016800d0}, /* BUF */ + {0xe510, 0x000000ff, 0x00000085}, /* EXT */ + {0xe540, 0x800f0000, 0x80020000}, /* W_SW_LEFT */ + {0xe544, 0x0fff0fff, 0x015c000c}, /* BUF */ + {0xe550, 0x000000ff, 0x00000083}, /* EXT */ + {0xe580, 0x800f0000, 0x80020000}, /* R_SW_LEFT */ + {0xe584, 0x1fff1fff, 0x01d8000c}, /* BUF */ + {0xe590, 0x000000ff, 0x00000084}, /* EXT */ + {0xe5c0, 0x800f0000, 0x80020000}, /* W_AZ_ABOVE_PIX */ + {0xe5c4, 0x0fff0fff, 0x02380012}, /* BUF */ + {0xe5d0, 0x000000ff, 0x0000007f}, /* EXT */ + {0xe600, 0x800f0000, 0x80020000}, /* R_AZ_ABOVE_PIX */ + {0xe604, 0x1fff1fff, 0x01e40020}, /* BUF */ + {0xe610, 0x000000ff, 0x00000080}, /* EXT */ + {0xe640, 0x800f0000, 0x80020000}, /* W_AZ_LEFT_PIX */ + {0xe644, 0x0fff0fff, 0x024a006c}, /* BUF */ + {0xe650, 0x000000ff, 0x00000081}, /* EXT */ + {0xe680, 0x800f0000, 0x80020000}, /* R_AZ_LEFT_PIX */ + {0xe684, 0x1fff1fff, 0x02040060}, /* BUF */ + {0xe690, 0x000000ff, 0x00000082}, /* EXT */ + {0xe6c0, 0x800ff000, 0x80034000}, /* W_ZIP */ + {0xe6c8, 0x0fff0fff, 0x02ce009e}, /* BUF (CMP) */ + {0xe6cc, 0x0fff0fff, 0x02b6000c}, /* BUF (HDR) */ + {0xe6ec, 0x0000ffff, 0x00008789}, /* EXT */ + {0xe700, 0x800ff000, 0x80034000}, /* W_ZIP */ + {0xe708, 0x0fff0fff, 0x036c009e}, /* BUF (CMP) */ + {0xe70c, 0x0fff0fff, 0x02c2000c}, /* BUF (HDR) */ + {0xe72c, 0x0000ffff, 0x0000888a}, /* EXT */ + {0xe740, 0x800f0000, 0x80020000}, /* W_PIPE_STATS */ + {0xe744, 0x0fff0fff, 0x01580004}, /* BUF */ + {0xe750, 0x000000ff, 0x00000067}, /* EXT */ + {0xe800, 0x00000001, 0x00000001}, /* INTER_TOP_CLOCK_GATING */ + {0xe880, 0x800f0000, 0x80020000}, /* W_MV_ABOVE_INFO */ + {0xe884, 0x0fff0fff, 0x00000016}, /* BUF */ + {0xe890, 0x000000ff, 0x0000006b}, /* EXT */ + {0xe8c0, 0x800f0000, 0x80020000}, /* R_MV_ABOVE_INFO */ + {0xe8c4, 0x1fff1fff, 0x00000022}, /* BUF */ + {0xe8d0, 0x000000ff, 0x0000006c}, /* EXT */ + {0xe900, 0x800f0000, 0x80020000}, /* W_MV_COLOR */ + {0xe904, 0x0fff0fff, 0x00160022}, /* BUF */ + {0xe910, 0x000000ff, 0x0000006d}, /* EXT */ + {0xe940, 0x800f0000, 0x80020000}, /* R_MV_COLOR */ + {0xe944, 0x1fff1fff, 0x0022003e}, /* BUF */ + {0xe950, 0x000000ff, 0x0000006e}, /* EXT */ + {0xe980, 0x80ff0004, 0x80550004}, /* R_ZIP */ + {0xe9a8, 0xffffffff, 0x8d8f8c8e}, /* EXT */ +}; diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index f9fbb645b19527..7ec7d5a9fcd30a 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -46,6 +46,8 @@ /* A reset after a timeout hangs the machine: stay parked and retire the decoder */ #define AVD_QUIRK_NO_RECOVERY_RESET BIT(5) +#define AVD_QUIRK_KOPSIA BIT(6) + #define VP_SLOT_NONE 255 #define INST_FIFO_SLOT_NONE 255 @@ -410,6 +412,9 @@ void avd_queue_add_ctx(struct avd_ctx *ctx); void avd_queue_del_ctx(struct avd_ctx *ctx); int avd_open_build_program(struct avd_ctx *ctx); extern const struct avd_backend_ops avd_open_backend; +extern const struct avd_backend_ops avd_kopsia_backend; +int avd_open_submit(struct avd_dev *avd, struct avd_frame *f); +irqreturn_t avd_open_complete(struct avd_dev *avd, u32 status); extern const struct avd_backend_ops avd_apple_backend; extern const struct avd_backend_ops avd_qfw_backend; struct avd_qfw; From bb61904f348574926ab2cdba43425ea53413d7a3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:29:22 +0100 Subject: [PATCH 0575/1514] arm64: dts: apple: t8152: describe the Kopsia video decoder Describe the T8152 Kopsia decoder in the SoC peripherals, disabled, so every T8152 board can enable it: its five register banks, PSD service 50 (apple,t8152-psd) as the power domain shared by the decoder and its DART, powered off by genpd while both are idle, and the DART as the apple,t8152-avd-dart instance with its Gen3 TLBI aperture, its initialization tunables and a 64 GiB window at 1 TiB inside the native 1..4 TiB DMA aperture. The tunables are those of the J873g's ADT. Signed-off-by: Thomas Glanzmann --- .../boot/dts/apple/t8152-peripherals.dtsi | 55 ++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi index cab3001ab9086d..d1dcb53240fc11 100644 --- a/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-peripherals.dtsi @@ -229,11 +229,62 @@ status = "disabled"; }; + /* Kopsia decoder: PSD service 50, Gen3 DART streams 0..2. */ + ps_avd: power-controller@303a13200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13200 0x0 0x100>; + #power-domain-cells = <0>; + label = "avd"; + status = "disabled"; + }; + avd_dart: iommu@485020000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x4 0x85020000 0x0 0x20000>; + compatible = "apple,t8152-avd-dart"; + reg = <0x4 0x85020000 0x0 0x20000>, <0x2 0x300 0x0 0x10>; + reg-names = "dart", "tlbi"; interrupts = ; #iommu-cells = <1>; + power-domains = <&ps_avd>; + /* A 64-GiB window within the ADT's 1..4-TiB DMA aperture. */ + apple,dma-range = <0x100 0x0 0x10 0x0>; + apple,tunable = < + 0x20c 0x80000121 0x80000121 + 0x220 0xf0f 0xf0f + 0x224 0xffff 0x909 + 0x300 0x1f31 0x1 + 0x308 0x3ffffffc 0x10000000 + 0x310 0x3ffffffc 0x3ffffffc + 0x800 0xf007f 0x10000 + 0x804 0xf007f 0x20002 + 0x808 0xf007f 0x50006 + 0x80c 0xf007f 0x20026 + 0x810 0xf007f 0x3002a + 0x814 0xf007f 0x40032 + 0x818 0xf007f 0x0 + 0x81c 0xf007f 0x0 + 0x820 0xf007f 0x0 + 0x824 0xf007f 0x0 + 0x828 0xf007f 0x0 + 0x82c 0xf007f 0x0 + 0x830 0xf007f 0x0 + 0x834 0xf007f 0x0 + 0x838 0xf007f 0x0 + 0x83c 0xf007f 0x0 + 0x4600 0x2 0x2 + >; + status = "disabled"; + }; + + avd: video-codec@485400000 { + compatible = "apple,t8152-avd"; + reg = <0x4 0x85400000 0x0 0x12000>, + <0x4 0x85500000 0x0 0x4000>, + <0x4 0x85100000 0x0 0x10000>, + <0x4 0x850c0000 0x0 0x4000>, + <0x4 0x85070000 0x0 0x4000>; + reg-names = "code", "mbox", "ctrl", "wrap", "dma"; + power-domains = <&ps_avd>; + iommus = <&avd_dart 0>, <&avd_dart 1>, <&avd_dart 2>; status = "disabled"; }; From 42cd7faf9034c8035594dc01c1e2186744532499 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:29:27 +0100 Subject: [PATCH 0576/1514] arm64: dts: apple: j873: enable the Kopsia video decoder Enable the T8152 decoder, its PSD domain and its DART on the J873g. This enables the request decoder node used by FFmpeg and mpv on the M6 Mac mini. The PSD provider supplies both AVD and DART so translation is initialized only after their shared domain is powered. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi | 14 ++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 15 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi new file mode 100644 index 00000000000000..d36cd5ef242b27 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-avd.dtsi @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* J873g: the Kopsia video decoder (described in t8152-peripherals.dtsi). */ + +&ps_avd { + status = "okay"; +}; + +&avd_dart { + status = "okay"; +}; + +&avd { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 169298a6c9e6c4..5c229e74d5b0a7 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -503,3 +503,4 @@ #include "t8152-j873-ethernet.dtsi" #include "t8152-j873-audio.dtsi" #include "t8152-j873-dcp.dtsi" +#include "t8152-j873-avd.dtsi" From ef8ae783ef2b48363000b8da43edcdbf9d289f88 Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 22 Nov 2026 23:03:55 -0500 Subject: [PATCH 0577/1514] media: apple: avd: reject a failed first boot on Kopsia The Kopsia backend checks the hardware ID at the first runtime resume. Propagate a failed resume before registering the media device. Preserve the existing firmware transport probe behavior. --- drivers/media/platform/apple/avd/avd-drv.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 2b8ee0f381274c..0233dc55a59d95 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -790,10 +790,15 @@ static int avd_probe(struct platform_device *pdev) * size their contexts before the first decode would power it up. */ ret = pm_runtime_resume_and_get(avd->dev); - if (ret < 0) + if (ret < 0) { + if (avd->variant->quirks & AVD_QUIRK_KOPSIA) { + dev_err_probe(avd->dev, ret, "Kopsia probe boot failed\n"); + goto err_disable_runtime_pm; + } dev_warn(avd->dev, "firmware probe boot failed: %d\n", ret); - else + } else { pm_runtime_put_autosuspend(avd->dev); + } ret = avd_v4l2_init(avd); if (ret) From e75d18571f9d248027d9772025419a13cb52423d Mon Sep 17 00:00:00 2001 From: Acelogic Date: Sun, 22 Nov 2026 23:03:55 -0500 Subject: [PATCH 0578/1514] media: apple: avd: release probe resources on setup errors Allocate the empty IOMMU domain after the fallible backend, DMA and power-domain setup. Cancel the queue work scheduled on runtime resume and release the empty domain when probe fails after enabling runtime PM. --- drivers/media/platform/apple/avd/avd-drv.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 0233dc55a59d95..3de3f241430f5a 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -733,13 +733,6 @@ static int avd_probe(struct platform_device *pdev) return ret; avd->domain = iommu_get_domain_for_dev(avd->dev); - if (avd->domain) { - avd->empty_domain = iommu_paging_domain_alloc(avd->dev); - if (IS_ERR(avd->empty_domain)) { - avd->empty_domain = NULL; - dev_warn(avd->dev, "cannot alloc new empty domain"); - } - } ret = avd_backend_select(avd); if (ret) @@ -782,6 +775,13 @@ static int avd_probe(struct platform_device *pdev) if (ret) return ret; } + if (avd->domain) { + avd->empty_domain = iommu_paging_domain_alloc(avd->dev); + if (IS_ERR(avd->empty_domain)) { + avd->empty_domain = NULL; + dev_warn(avd->dev, "cannot alloc new empty domain"); + } + } avd_pm_enable(avd); /* @@ -809,6 +809,9 @@ static int avd_probe(struct platform_device *pdev) err_disable_runtime_pm: pm_runtime_dont_use_autosuspend(&pdev->dev); pm_runtime_disable(&pdev->dev); + cancel_delayed_work_sync(&avd->queue_work); + if (avd->empty_domain) + iommu_domain_free(avd->empty_domain); return ret; } From f3ad1a8f362c0e8ce3fec0faae52748c24f16d74 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 15:26:31 +1100 Subject: [PATCH 0579/1514] soc: apple: t6050-aop: mark an endpoint open again when its rings restart An endpoint whose wake element went unanswered stays closed. If the firmware then starts the endpoint over (GETBUF, ring announcements, AFK_START_ACK), it is open again while still marked closed, so the next sleep stop skips it and the next restart sends it a wake element it never had a sleep element for. A restarted endpoint has no sleep element pending, so clear closed when its rings start. Also mark the rings' ready flags with WRITE_ONCE() when they are announced and read them with READ_ONCE() on the sleep and wake path, matching the WRITE_ONCE() that clears them at a GETBUF. Signed-off-by: Ryan Murray --- drivers/soc/apple/t6050-aop.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/t6050-aop.c b/drivers/soc/apple/t6050-aop.c index 14bf2b0729b556..df00818ac506e5 100644 --- a/drivers/soc/apple/t6050-aop.c +++ b/drivers/soc/apple/t6050-aop.c @@ -220,15 +220,17 @@ static void t6050_aop_recv(void *cookie, u8 ep, u64 msg) case AFK_INIT_TX: r->tx_off = FIELD_GET(AFK_RING_OFFSET, msg) << AFK_BLOCK_SHIFT; r->tx_size = FIELD_GET(AFK_RING_SIZE, msg) << AFK_BLOCK_SHIFT; - r->tx_ready = true; + WRITE_ONCE(r->tx_ready, true); break; case AFK_INIT_RX: r->rx_off = FIELD_GET(AFK_RING_OFFSET, msg) << AFK_BLOCK_SHIFT; r->rx_size = FIELD_GET(AFK_RING_SIZE, msg) << AFK_BLOCK_SHIFT; - r->rx_ready = true; + WRITE_ONCE(r->rx_ready, true); t6050_aop_send(aop, ep, FIELD_PREP(AFK_TYPE, AFK_START)); break; case AFK_START_ACK: + /* Started again from a GETBUF: no sleep element of the last setup is pending. */ + r->closed = false; set_bit(ep - AOP_EP_FIRST, &aop->opened); break; case AFK_RING: @@ -304,7 +306,7 @@ static int t6050_aop2_put(struct t6050_aop *aop, u8 ep, const u32 *msg, unsigned __le32 *qe; int ret; - ret = t6050_aop2_view(r, r->tx_off, r->tx_size, r->tx_ready, &v); + ret = t6050_aop2_view(r, r->tx_off, r->tx_size, READ_ONCE(r->tx_ready), &v); if (ret) return ret; dma_rmb(); @@ -361,7 +363,7 @@ static int t6050_aop2_rx_wptr(struct t6050_aop *aop, u8 ep) struct t6050_aop_view v; u32 wptr; - if (t6050_aop2_view(r, r->rx_off, r->rx_size, r->rx_ready, &v)) + if (t6050_aop2_view(r, r->rx_off, r->rx_size, READ_ONCE(r->rx_ready), &v)) return -EINVAL; dma_rmb(); wptr = t6050_aop2_ptr(&v, AFK_PTR_WRITE); @@ -396,8 +398,8 @@ static int t6050_aop2_take(struct t6050_aop *aop, u8 ep, u32 old, u32 new) struct t6050_aop_view v; int code; - if (t6050_aop2_view(r, r->rx_off, r->rx_size, r->rx_ready, &v) || old >= v.bufsz || - new >= v.bufsz) + if (t6050_aop2_view(r, r->rx_off, r->rx_size, READ_ONCE(r->rx_ready), &v) || + old >= v.bufsz || new >= v.bufsz) return -EINVAL; if (old == new) return -ENOMSG; From 2144b43774e1e279f93fab88dec607711f7b94f5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:14:17 +1100 Subject: [PATCH 0580/1514] media: apple: avd: keep instructions inside the job table push() wrote the next instruction into job->segments[job->num] without checking that the segment exists or has room. The codecs size the table from the request before building it, so an error in that sizing became a write past the table, and a segment that filled up wrote into the next one. avd_open_build_program() only noticed a full segment after the writes. Record the number of allocated segments in the job, and have push() drop an instruction that has no segment or no room and mark the job. A marked job, or one whose segment index is past the table, is refused with -EOVERFLOW instead of being turned into a program. The H.264 path, which grows the table when a picture needs more slices, updates the count. Add KUnit cases for a full segment and a full table. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 2 +- .../platform/apple/avd/avd-backend-open.c | 3 + drivers/media/platform/apple/avd/avd-drv.c | 2 + drivers/media/platform/apple/avd/avd-h264.c | 1 + drivers/media/platform/apple/avd/avd-inst.h | 12 ++- .../media/platform/apple/avd/avd-job-test.c | 85 +++++++++++++++++++ drivers/media/platform/apple/avd/avd.h | 5 ++ 7 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-job-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 66b8e3c61356a6..278cf2da788865 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -4,5 +4,5 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o avd-queue-test.o \ - avd-pm-test.o + avd-pm-test.o avd-job-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-backend-open.c b/drivers/media/platform/apple/avd/avd-backend-open.c index 13508cc5d5272d..2681eeb63b7776 100644 --- a/drivers/media/platform/apple/avd/avd-backend-open.c +++ b/drivers/media/platform/apple/avd/avd-backend-open.c @@ -29,6 +29,9 @@ int avd_open_build_program(struct avd_ctx *ctx) if (!f || !job->segments) return -EINVAL; + /* The builder ran past the table or a segment; nothing fits. */ + if (job->overflow || job->num >= job->max) + return -EOVERFLOW; for (i = 0; i <= job->num; i++) { if (job->segments[i].num > AVD_MAX_INST || check_add_overflow(count, job->segments[i].num + !!i, &count)) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 3de3f241430f5a..c79379d2a50f25 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -100,9 +100,11 @@ int avd_init_job(struct avd_ctx *ctx, enum avd_codec codec, size_t segments) job->codec = codec; job->num = 0; + job->overflow = false; /* A table that was built but never submitted still belongs to us. */ kvfree(job->segments); job->segments = kvcalloc(segments, sizeof(*job->segments), GFP_KERNEL); + job->max = job->segments ? segments : 0; if (!job->segments) ret = -ENOMEM; return ret; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index db4830e7aca222..6d2b4ff0643c30 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -854,6 +854,7 @@ static int avd_h264_realloc_slices(struct avd_ctx *ctx, size_t max_slices) memcpy(ctx->job.segments, tmp, sizeof(*ctx->job.segments) * (ctx->job.num + 1)); + ctx->job.max = alloc_slice_num + 1; kvfree(tmp); return 0; diff --git a/drivers/media/platform/apple/avd/avd-inst.h b/drivers/media/platform/apple/avd/avd-inst.h index adf670a79645c6..d35efe68ebd510 100644 --- a/drivers/media/platform/apple/avd/avd-inst.h +++ b/drivers/media/platform/apple/avd/avd-inst.h @@ -169,7 +169,17 @@ static inline bool boolify(u32 v) static inline void push(struct avd_ctx *ctx, u32 inst) { struct avd_job *job = &ctx->job; - struct avd_segment *seg = &job->segments[job->num]; + struct avd_segment *seg; + + if (job->num >= job->max) { + job->overflow = true; + return; + } + seg = &job->segments[job->num]; + if (seg->num >= AVD_MAX_INST) { + job->overflow = true; + return; + } seg->instructions[seg->num++] = inst; } diff --git a/drivers/media/platform/apple/avd/avd-job-test.c b/drivers/media/platform/apple/avd/avd-job-test.c new file mode 100644 index 00000000000000..8263cddfd88ec8 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-job-test.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the instruction job table of the Apple video decoder. + */ + +#include + +#include "avd.h" +#include "avd-inst.h" + +static void avd_job_free(void *data) +{ + struct avd_ctx *ctx = data; + + kvfree(ctx->job.segments); +} + +static struct avd_ctx *avd_job_test_ctx(struct kunit *test, size_t segments) +{ + struct avd_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_EQ(test, avd_init_job(ctx, AVD_CODEC_H264, segments), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, avd_job_free, ctx), + 0); + KUNIT_EXPECT_EQ(test, ctx->job.max, segments); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + return ctx; +} + +/* A full segment takes no more instructions. */ +static void avd_job_segment_full_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_job_test_ctx(test, 2); + int i; + + for (i = 0; i < AVD_MAX_INST; i++) + push(i, "fill"); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, AVD_MAX_INST); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + + push(0xdeadbeef, "one too many"); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, AVD_MAX_INST); + KUNIT_EXPECT_TRUE(test, ctx->job.overflow); + /* The next segment was not written either. */ + KUNIT_EXPECT_EQ(test, ctx->job.segments[1].num, 0); +} + +/* Segments past the allocated table are never written. */ +static void avd_job_table_full_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_job_test_ctx(test, 2); + int i; + + push(1, "header"); + ctx->job.num++; + push(2, "first segment"); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + + for (i = 0; i < 8; i++) { + ctx->job.num++; + push(3, "past the table"); + } + KUNIT_EXPECT_TRUE(test, ctx->job.overflow); + KUNIT_EXPECT_EQ(test, ctx->job.segments[0].num, 1); + KUNIT_EXPECT_EQ(test, ctx->job.segments[1].num, 1); + + /* A new job starts clean. */ + KUNIT_ASSERT_EQ(test, avd_init_job(ctx, AVD_CODEC_H264, 1), 0); + KUNIT_EXPECT_FALSE(test, ctx->job.overflow); + KUNIT_EXPECT_EQ(test, ctx->job.max, 1); +} + +static struct kunit_case avd_job_test_cases[] = { + KUNIT_CASE(avd_job_segment_full_test), + KUNIT_CASE(avd_job_table_full_test), + {} +}; + +static struct kunit_suite avd_job_test_suite = { + .name = "apple-avd-job", + .test_cases = avd_job_test_cases, +}; + +kunit_test_suite(avd_job_test_suite); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 7ec7d5a9fcd30a..c77f18f7ad288c 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -302,7 +302,12 @@ struct avd_segment { struct avd_job { enum avd_codec codec; + /* index of the segment being written */ size_t num; + /* segments allocated */ + size_t max; + /* an instruction did not fit; the job must not be submitted */ + bool overflow; struct avd_segment *segments; }; From 259b966a937758c7f7d619c87ea34363297a61af Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:12:13 +1100 Subject: [PATCH 0581/1514] media: apple: avd: hevc: check the tile layout against the picture The tile tables are sized from the SPS picture size in CTBs, but explicitly sized tile columns and rows were taken from the PPS without comparing them with that size. The last column or row then took a wrapped, very large width, and building the CTB raster-to-tile-scan and tile id tables wrote outside both tables. Before building the tables, require what H.265 7.4.3.3.1 requires: no more tile columns or rows than the picture has CTBs, and explicit widths and heights that leave a non-empty last column and row. Also refuse an SPS with a zero picture width or height, or a CTB size other than 16, 32 or 64 (7.4.3.2.1), which the tables and the slice address arithmetic divide by. As a second line, the tile id table builder skips any index outside the tables. Add KUnit cases for the SPS geometry and tile layout checks that also build the tables, for accepted and refused layouts. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 4 +- .../media/platform/apple/avd/avd-hevc-test.c | 153 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-hevc.c | 125 ++++++++++++-- drivers/media/platform/apple/avd/avd.h | 6 + 4 files changed, 277 insertions(+), 11 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-hevc-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 278cf2da788865..9c32e537a4f833 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -3,6 +3,6 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o -apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o avd-queue-test.o \ - avd-pm-test.o avd-job-test.o +apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ + avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c new file mode 100644 index 00000000000000..50db548b19e287 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the HEVC picture, tile and slice checks of the Apple video + * decoder. + */ + +#include + +#include "avd.h" + +/* 64x64 luma samples in 16x16 CTBs: 4x4 CTBs. */ +static void avd_hevc_test_sps(struct v4l2_ctrl_hevc_sps *sps) +{ + *sps = (struct v4l2_ctrl_hevc_sps) { + .pic_width_in_luma_samples = 64, + .pic_height_in_luma_samples = 64, + .log2_min_luma_coding_block_size_minus3 = 0, + .log2_diff_max_min_luma_coding_block_size = 1, + }; +} + +struct avd_hevc_geometry_case { + const char *desc; + u16 width; + u16 height; + u8 min_cb_minus3; + u8 diff; + int ret; +}; + +static const struct avd_hevc_geometry_case avd_hevc_geometry_cases[] = { + { "16x16 CTBs", 64, 64, 0, 1, 0 }, + { "32x32 CTBs", 1920, 1080, 0, 2, 0 }, + { "64x64 CTBs", 4096, 2160, 0, 3, 0 }, + { "64x64 CTBs from 16x16 coding blocks", 4096, 2160, 1, 2, 0 }, + { "8x8 CTBs", 64, 64, 0, 0, -EINVAL }, + { "128x128 CTBs", 64, 64, 0, 4, -EINVAL }, + { "coding block size beyond any CTB", 64, 64, 255, 255, -EINVAL }, + { "zero width", 0, 64, 0, 1, -EINVAL }, + { "zero height", 64, 0, 0, 1, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_geometry, avd_hevc_geometry_cases, desc); + +static void avd_hevc_geometry_test(struct kunit *test) +{ + const struct avd_hevc_geometry_case *c = test->param_value; + struct v4l2_ctrl_hevc_sps sps = { + .pic_width_in_luma_samples = c->width, + .pic_height_in_luma_samples = c->height, + .log2_min_luma_coding_block_size_minus3 = c->min_cb_minus3, + .log2_diff_max_min_luma_coding_block_size = c->diff, + }; + + KUNIT_EXPECT_EQ(test, avd_hevc_check_sps_geometry(&sps), c->ret); +} + +struct avd_hevc_tiles_case { + const char *desc; + bool uniform; + u8 cols_minus1; + u8 rows_minus1; + u8 col_width_minus1[2]; + u8 row_height_minus1[2]; + int ret; + /* tile id of every CTB in tile scan order, if accepted */ + u32 ids[16]; +}; + +static const struct avd_hevc_tiles_case avd_hevc_tiles_cases[] = { + { "explicit 2x2 tiles", false, 1, 1, { 0 }, { 1 }, 0, + { 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3 } }, + { "explicit 3x1 tiles", false, 2, 0, { 1, 0 }, { 0 }, 0, + { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2 } }, + { "uniform 3x1 tiles", true, 2, 0, { 0 }, { 0 }, 0, + { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2 } }, + { "uniform 4x4 tiles", true, 3, 3, { 0 }, { 0 }, 0, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + { "explicit columns leave the last one empty", false, 1, 0, { 3 }, + { 0 }, -EINVAL }, + { "explicit columns wider than the picture", false, 1, 0, { 4 }, + { 0 }, -EINVAL }, + { "explicit columns far wider than the picture", false, 2, 0, + { 200, 200 }, { 0 }, -EINVAL }, + { "explicit rows taller than the picture", false, 0, 1, { 0 }, + { 4 }, -EINVAL }, + { "explicit rows leave the last one empty", false, 0, 2, { 0 }, + { 1, 1 }, -EINVAL }, + { "uniform, more columns than CTBs", true, 4, 0, { 0 }, { 0 }, + -EINVAL }, + { "uniform, more rows than CTBs", true, 0, 4, { 0 }, { 0 }, + -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_tiles, avd_hevc_tiles_cases, desc); + +static void avd_hevc_tiles_test(struct kunit *test) +{ + const struct avd_hevc_tiles_case *c = test->param_value; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + (c->uniform ? V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING : 0), + .num_tile_columns_minus1 = c->cols_minus1, + .num_tile_rows_minus1 = c->rows_minus1, + }; + u32 ids[16]; + + avd_hevc_test_sps(&sps); + memcpy(pps.column_width_minus1, c->col_width_minus1, + sizeof(c->col_width_minus1)); + memcpy(pps.row_height_minus1, c->row_height_minus1, + sizeof(c->row_height_minus1)); + + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), c->ret); + + /* The table builder must refuse the same layouts, before any write. */ + memset(ids, 0xff, sizeof(ids)); + KUNIT_ASSERT_EQ(test, + avd_hevc_kunit_compute_tiles(&sps, &pps, ids, + ARRAY_SIZE(ids)), + c->ret); + if (!c->ret) + KUNIT_EXPECT_MEMEQ(test, ids, c->ids, sizeof(ids)); +} + +static void avd_hevc_no_tiles_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ids[16]; + + avd_hevc_test_sps(&sps); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), 0); + KUNIT_EXPECT_EQ(test, + avd_hevc_kunit_compute_tiles(&sps, &pps, ids, + ARRAY_SIZE(ids)), + 0); +} + +static struct kunit_case avd_hevc_test_cases[] = { + KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), + KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), + KUNIT_CASE(avd_hevc_no_tiles_test), + {} +}; + +static struct kunit_suite avd_hevc_test_suite = { + .name = "apple-avd-hevc", + .test_cases = avd_hevc_test_cases, +}; + +kunit_test_suite(avd_hevc_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 04d43b759f0d73..58e90ebc7c4035 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -13,6 +13,7 @@ * Tomasz Figa */ +#include #include #include "avd.h" @@ -832,20 +833,25 @@ static void compute_rs_to_ts(struct avd_hevc_run *run, u32 pic_in_ctbs_size, } } -static void compute_tile_ids(struct avd_hevc_run *run, u32 pic_in_ctbs_width, - u32 *col_bd, u32 *row_bd, u32 *ctb_addr_rs_to_ts, - u32 *tile_ids) +static void compute_tile_ids(struct avd_hevc_run *run, u32 pic_in_ctbs_size, + u32 pic_in_ctbs_width, u32 *col_bd, u32 *row_bd, + u32 *ctb_addr_rs_to_ts, u32 *tile_ids) { const struct v4l2_ctrl_hevc_pps *pps = run->pps; int j, i, y, x; - u32 tile_idx; + u32 tile_idx, rs, ts; + for (j = 0, tile_idx = 0; j <= pps->num_tile_rows_minus1; j++) for (i = 0; i <= pps->num_tile_columns_minus1; i++, tile_idx++) for (y = row_bd[j]; y < row_bd[j + 1]; y++) - for (x = col_bd[i]; x < col_bd[i + 1]; x++) - tile_ids[ctb_addr_rs_to_ts - [y * pic_in_ctbs_width + - x]] = tile_idx; + for (x = col_bd[i]; x < col_bd[i + 1]; x++) { + rs = y * pic_in_ctbs_width + x; + if (rs >= pic_in_ctbs_size) + continue; + ts = ctb_addr_rs_to_ts[rs]; + if (ts < pic_in_ctbs_size) + tile_ids[ts] = tile_idx; + } } struct sl_ctx { @@ -1046,9 +1052,76 @@ static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, return AVD_IMG_FMT_ANY; } +/* + * The picture must have at least one sample in each direction and the CTB + * size must be one of those H.265 allows (CtbLog2SizeY 4 to 6, 7.4.3.2.1): + * the picture size in CTBs sizes the tile tables and divides slice addresses. + */ +VISIBLE_IF_KUNIT int +avd_hevc_check_sps_geometry(const struct v4l2_ctrl_hevc_sps *sps) +{ + unsigned int ctb_log2 = sps->log2_min_luma_coding_block_size_minus3 + 3 + + sps->log2_diff_max_min_luma_coding_block_size; + + if (!sps->pic_width_in_luma_samples || !sps->pic_height_in_luma_samples) + return -EINVAL; + if (ctb_log2 < 4 || ctb_log2 > 6) + return -EINVAL; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_sps_geometry); + +static void avd_hevc_pic_in_ctbs(const struct v4l2_ctrl_hevc_sps *sps, + u32 *width, u32 *height) +{ + u32 ctb = 1 << (sps->log2_min_luma_coding_block_size_minus3 + 3 + + sps->log2_diff_max_min_luma_coding_block_size); + + *width = DIV_ROUND_UP(sps->pic_width_in_luma_samples, ctb); + *height = DIV_ROUND_UP(sps->pic_height_in_luma_samples, ctb); +} + +/* + * The tile columns and rows must cover the picture, each at least one CTB + * wide or high (H.265 7.4.3.3.1). Explicitly sized tiles give all but the + * last width and height; the last one takes the rest and must not be empty. + * avd_hevc_check_sps_geometry() must have accepted the SPS. + */ +VISIBLE_IF_KUNIT int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps) +{ + u32 width, height, sum; + int i; + + if (!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED)) + return 0; + + avd_hevc_pic_in_ctbs(sps, &width, &height); + if (pps->num_tile_columns_minus1 >= width || + pps->num_tile_rows_minus1 >= height) + return -EINVAL; + if (pps->flags & V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING) + return 0; + + for (i = 0, sum = 0; i < pps->num_tile_columns_minus1; i++) + sum += pps->column_width_minus1[i] + 1; + if (sum >= width) + return -EINVAL; + + for (i = 0, sum = 0; i < pps->num_tile_rows_minus1; i++) + sum += pps->row_height_minus1[i] + 1; + if (sum >= height) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_tiles); + static int avd_hevc_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_hevc_sps *sps) { + if (avd_hevc_check_sps_geometry(sps)) + return -EINVAL; if (sps->pic_width_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.width || sps->pic_height_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.height) return -EINVAL; @@ -1292,6 +1365,9 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) tiles_enabled = !!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED); + if (avd_hevc_check_tiles(sps, pps)) + return -EINVAL; + tile_info->ctb_addr_rs_to_ts = kzalloc( sizeof(*tile_info->ctb_addr_rs_to_ts) * pic_in_ctbs_size, GFP_KERNEL); @@ -1332,7 +1408,8 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) tile_info->col_bd, tile_info->row_bd, tile_info->col_width, tile_info->row_height, tile_info->ctb_addr_rs_to_ts); - compute_tile_ids(run, pic_in_ctbs_width, tile_info->col_bd, + compute_tile_ids(run, pic_in_ctbs_size, pic_in_ctbs_width, + tile_info->col_bd, tile_info->row_bd, tile_info->ctb_addr_rs_to_ts, tile_info->tile_ids); @@ -1346,6 +1423,36 @@ static int avd_hevc_compute_tiles(struct avd_ctx *ctx, struct avd_hevc_run *run) return 0; } +#if IS_ENABLED(CONFIG_KUNIT) +/* Build the tile tables of a picture and copy out tile_ids in tile scan order. */ +int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + u32 *tile_ids, size_t n) +{ + struct avd_hevc_run *run; + u32 width, height; + int ret; + + run = kzalloc(sizeof(*run), GFP_KERNEL); + if (!run) + return -ENOMEM; + run->sps = sps; + run->pps = pps; + ret = avd_hevc_compute_tiles(NULL, run); + if (!ret) { + avd_hevc_pic_in_ctbs(sps, &width, &height); + memcpy(tile_ids, run->tile_info.tile_ids, + min_t(size_t, n, (size_t)width * height) * + sizeof(*tile_ids)); + } + kfree(run->tile_info.ctb_addr_rs_to_ts); + kfree(run->tile_info.tile_ids); + kfree(run); + return ret; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_kunit_compute_tiles); +#endif + /* * The slice builder below expects the GStreamer layout: the slices tile the * OUTPUT buffer as whole NALs, bit_size covers the whole NAL and diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index c77f18f7ad288c..7d10b2733a2ab3 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -377,6 +377,12 @@ bool avd_h264_slice_fits(const struct v4l2_ctrl_h264_sps *sps, size_t held, size_t held_bytes, u32 len, size_t decoded_size); bool avd_h264_scaling_is_flat(const struct v4l2_ctrl_h264_pps *pps, const struct v4l2_ctrl_h264_scaling_matrix *scaling); +int avd_hevc_check_sps_geometry(const struct v4l2_ctrl_hevc_sps *sps); +int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps); +int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + u32 *tile_ids, size_t n); #endif extern const struct avd_coded_fmt_ops avd_h264_fmt_ops; From 966778e4384097d84a6a57e142e4bf20fef6b9c9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:12:17 +1100 Subject: [PATCH 0582/1514] media: apple: avd: vp9: bound the tile counts The VP9 job is sized with one segment per tile, computed in int from tile_rows_log2 and tile_cols_log2, and set_tiles() then walks the tile grid with u32 counts. The V4L2 core bounds tile_cols_log2 to 6 but not tile_rows_log2, and the driver checked neither, so the int product can wrap and the job be allocated smaller than the grid that is filled in. Check the tiling in avd_vp9_validate_frame(), which runs when the frame control is set and again when the frame runs: tile_rows_log2 is at most 2 and tile_cols_log2 lies between calc_min_log2_tile_cols() and calc_max_log2_tile_cols() for the frame width (VP9 6.2.13 tile_info() and 6.2.14). With the 4096-pixel coded width limit that also keeps the column count within the VP9_MAX_TILE_COLS the scratch is sized for. Compute the segment count as a size_t shift of the summed log2 values. Add a KUnit test for the tiling check. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 3 +- .../media/platform/apple/avd/avd-vp9-test.c | 61 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-vp9.c | 46 ++++++++++++-- drivers/media/platform/apple/avd/avd.h | 1 + 4 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-vp9-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 9c32e537a4f833..be42b7f645da8a 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -4,5 +4,6 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ - avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o + avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o \ + avd-vp9-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-vp9-test.c b/drivers/media/platform/apple/avd/avd-vp9-test.c new file mode 100644 index 00000000000000..469de409886183 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-vp9-test.c @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the VP9 frame checks of the Apple video decoder. + */ + +#include + +#include "avd.h" + +struct avd_vp9_tiling_case { + const char *desc; + u16 width; + u8 tile_rows_log2; + u8 tile_cols_log2; + int ret; +}; + +static const struct avd_vp9_tiling_case avd_vp9_tiling_cases[] = { + { "one tile", 1920, 0, 0, 0 }, + { "two tile rows", 1920, 1, 0, 0 }, + { "four tile rows", 1920, 2, 0, 0 }, + { "eight tile rows", 1920, 3, 0, -EINVAL }, + { "2^26 tile rows", 4096, 26, 6, -EINVAL }, + { "2^31 tile rows", 4096, 31, 1, -EINVAL }, + { "255 tile rows log2", 1920, 255, 0, -EINVAL }, + { "four tile columns at 1920", 1920, 0, 2, 0 }, + { "eight tile columns at 1920", 1920, 0, 3, -EINVAL }, + { "sixteen tile columns at 4096", 4096, 2, 4, 0 }, + { "32 tile columns at 4096", 4096, 0, 5, -EINVAL }, + { "64 tile columns at 4096", 4096, 0, 6, -EINVAL }, + { "two tile columns at 64", 64, 0, 1, -EINVAL }, + { "one tile column at 8192", 8192, 0, 0, -EINVAL }, + { "two tile columns at 8192", 8192, 0, 1, 0 }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_vp9_tiling, avd_vp9_tiling_cases, desc); + +static void avd_vp9_tiling_test(struct kunit *test) +{ + const struct avd_vp9_tiling_case *c = test->param_value; + struct v4l2_ctrl_vp9_frame frame = { + .frame_width_minus_1 = c->width - 1, + .frame_height_minus_1 = 1079, + .tile_rows_log2 = c->tile_rows_log2, + .tile_cols_log2 = c->tile_cols_log2, + }; + + KUNIT_EXPECT_EQ(test, avd_vp9_check_tiling(&frame), c->ret); +} + +static struct kunit_case avd_vp9_test_cases[] = { + KUNIT_CASE_PARAM(avd_vp9_tiling_test, avd_vp9_tiling_gen_params), + {} +}; + +static struct kunit_suite avd_vp9_test_suite = { + .name = "apple-avd-vp9", + .test_cases = avd_vp9_test_cases, +}; + +kunit_test_suite(avd_vp9_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index a596b420ac2c70..769383460342b1 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -14,6 +14,7 @@ * Alpha Lin */ +#include #include #include @@ -780,6 +781,40 @@ static int avd_vp9_alloc_bufs(struct avd_ctx *ctx, struct avd_vp9_bank *bank) return 0; } +/* + * VP9 6.2.13 tile_info(): tile_rows_log2 is 0, 1 or 2, and tile_cols_log2 + * lies between calc_min_log2_tile_cols() and calc_max_log2_tile_cols() of + * 6.2.14, which follow from the frame width. The job has one segment per + * tile and the per-column scratch is sized for the column count this allows. + */ +#define VP9_MIN_TILE_WIDTH_B64 4 +#define VP9_MAX_TILE_WIDTH_B64 64 +#define VP9_MAX_TILE_ROWS_LOG2 2 + +VISIBLE_IF_KUNIT int +avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame) +{ + /* 6.2.6 Compute image size syntax */ + u32 sb_64_cols = (((frame->frame_width_minus_1 + 8) >> 3) + 7) >> 3; + u32 min_log2 = 0, max_log2 = 1; + + if (frame->tile_rows_log2 > VP9_MAX_TILE_ROWS_LOG2) + return -EINVAL; + + while ((VP9_MAX_TILE_WIDTH_B64 << min_log2) < sb_64_cols) + min_log2++; + while ((sb_64_cols >> max_log2) >= VP9_MIN_TILE_WIDTH_B64) + max_log2++; + max_log2--; + + if (frame->tile_cols_log2 < min_log2 || + frame->tile_cols_log2 > max_log2) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_check_tiling); + /* * Only VP9 profiles 0 and 2 (4:2:0, 8 and 10 bits) decode. A profile 1 * frame (4:2:2 or 4:4:4) is never completed: it times out and the whole @@ -796,7 +831,7 @@ static int avd_vp9_validate_frame(struct avd_ctx *ctx, if (frame->bit_depth != (frame->profile == 2 ? 10 : 8)) return -EINVAL; - return 0; + return avd_vp9_check_tiling(frame); } static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) @@ -880,11 +915,10 @@ static int avd_vp9_run(struct avd_ctx *ctx) return ret; } - ret = avd_init_job( - ctx, AVD_CODEC_VP9, - (1 << run.decode_params->tile_rows_log2) * - (1 << run.decode_params->tile_cols_log2) + - 1); + /* One segment per tile, bounded by avd_vp9_check_tiling(), and the header. */ + ret = avd_init_job(ctx, AVD_CODEC_VP9, + ((size_t)1 << (run.decode_params->tile_rows_log2 + + run.decode_params->tile_cols_log2)) + 1); if (ret) { avd_run_postamble(ctx, &run.base); return ret; diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 7d10b2733a2ab3..6fee27521eed2d 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -383,6 +383,7 @@ int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, const struct v4l2_ctrl_hevc_pps *pps, u32 *tile_ids, size_t n); +int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); #endif extern const struct avd_coded_fmt_ops avd_h264_fmt_ops; From 35ffdcf01277e5d32a9b836792a5ab1187a71a62 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:12:24 +1100 Subject: [PATCH 0583/1514] media: v4l2-ctrls: validate VP9 tile_rows_log2 validate_vp9_frame() checks tile_cols_log2 against its maximum but accepts any tile_rows_log2. The VP9 tile_info() syntax (section 6.2.13) codes it as at most two one-bit increments, so it is 0, 1 or 2. Reject larger values so drivers do not each have to. Signed-off-by: Ryan Murray --- drivers/media/v4l2-core/v4l2-ctrls-core.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/media/v4l2-core/v4l2-ctrls-core.c b/drivers/media/v4l2-core/v4l2-ctrls-core.c index 648b88c868bc6d..18718345a7ddd6 100644 --- a/drivers/media/v4l2-core/v4l2-ctrls-core.c +++ b/drivers/media/v4l2-core/v4l2-ctrls-core.c @@ -634,6 +634,10 @@ validate_vp9_frame(struct v4l2_ctrl_vp9_frame *frame) if (frame->tile_cols_log2 > 6) return -EINVAL; + /* tile_rows_log2 is coded as up to two one-bit increments. */ + if (frame->tile_rows_log2 > 2) + return -EINVAL; + if (frame->reference_mode > V4L2_VP9_REFERENCE_MODE_SELECT) return -EINVAL; From 276447127c767f01aa8055fd5c1322c26288a2cc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:50:45 +1100 Subject: [PATCH 0584/1514] media: apple: avd: build HEVC and VP9 jobs from copies of their controls The HEVC and VP9 run paths kept pointers into the current values of the picture controls (HEVC SPS, PPS, decode parameters and scaling matrix, VP9 frame and compressed header) while they checked those values and then built the job from them. A VIDIOC_S_EXT_CTRLS that sets current values, not a request, is not serialized with the decode work, so the values could change between the checks and their use, and the tile tables and job table could be built from values that were never checked. Copy the controls under the control lock when the job starts, as the HEVC path already does for its slice and entry point arrays, and check and build from the copies. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-hevc.c | 64 +++++++++++++++------ drivers/media/platform/apple/avd/avd-vp9.c | 41 ++++++++----- 2 files changed, 71 insertions(+), 34 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 58e90ebc7c4035..9c52f50586f884 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -1498,9 +1498,34 @@ static void avd_hevc_normalize_slices(struct avd_hevc_run *run, u32 payload) } } +/* + * A copy of a control's current value. The caller holds the control lock, + * so the control must have been looked up before (v4l2_ctrl_find() takes + * that lock too). + */ +static void *avd_hevc_ctrl_dup(struct v4l2_ctrl *ctrl) +{ + if (!ctrl) + return NULL; + return kmemdup(ctrl->p_cur.p, ctrl->elems * ctrl->elem_size, + GFP_KERNEL); +} + +static void avd_hevc_free_run(struct avd_hevc_run *run) +{ + kfree(run->tile_info.ctb_addr_rs_to_ts); + kfree(run->tile_info.tile_ids); + kfree(run->sl); + kfree(run->entry_point_offsets); + kfree(run->decode); + kfree(run->sps); + kfree(run->pps); + kfree(run->scaling_matrix); +} + static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) { - struct v4l2_ctrl *ctrl, *sl, *ep; + struct v4l2_ctrl *sl, *ep, *decode, *sps, *pps, *scaling; u32 dst_len, mv_color_len; if (!v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SLICE_PARAMS) || @@ -1518,20 +1543,15 @@ static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_HEVC_DECODE_PARAMS); - run->decode = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SPS); - run->sps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_PPS); - run->pps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_HEVC_SCALING_MATRIX); - run->scaling_matrix = ctrl ? ctrl->p_cur.p : NULL; - sl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SLICE_PARAMS); ep = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS); + decode = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_HEVC_DECODE_PARAMS); + sps = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_SPS); + pps = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_HEVC_PPS); + scaling = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_HEVC_SCALING_MATRIX); /* * Setting a larger dynamic array on a queued request reallocates the @@ -1539,15 +1559,24 @@ static int avd_hevc_run_preamble(struct avd_ctx *ctx, struct avd_hevc_run *run) * the run needs while holding the control lock. */ v4l2_ctrl_lock(sl); + /* + * A plain VIDIOC_S_EXT_CTRLS can also change the picture controls + * while the job is built. The checks below and the builder must see + * the same values, so take copies of those too. + */ + run->decode = avd_hevc_ctrl_dup(decode); + run->sps = avd_hevc_ctrl_dup(sps); + run->pps = avd_hevc_ctrl_dup(pps); + run->scaling_matrix = avd_hevc_ctrl_dup(scaling); run->num_slices = sl->elems; run->sl = kmemdup(sl->p_cur.p, sl->elems * sl->elem_size, GFP_KERNEL); run->num_entry_point_offsets = ep->elems; run->entry_point_offsets = kmemdup(ep->p_cur.p, ep->elems * ep->elem_size, GFP_KERNEL); v4l2_ctrl_unlock(sl); - if (!run->sl || !run->entry_point_offsets) { - kfree(run->sl); - kfree(run->entry_point_offsets); + if (!run->sl || !run->entry_point_offsets || !run->decode || + !run->sps || !run->pps || !run->scaling_matrix) { + avd_hevc_free_run(run); avd_run_postamble(ctx, &run->base); return -ENOMEM; } @@ -1612,10 +1641,7 @@ static int avd_hevc_run(struct avd_ctx *ctx) /* The request was applied; complete it on every way out. */ avd_run_postamble(ctx, &run.base); done: - kfree(run.tile_info.ctb_addr_rs_to_ts); - kfree(run.tile_info.tile_ids); - kfree(run.sl); - kfree(run.entry_point_offsets); + avd_hevc_free_run(&run); return ret; } diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 769383460342b1..71b80796fd090b 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -836,7 +836,7 @@ static int avd_vp9_validate_frame(struct avd_ctx *ctx, static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) { - struct v4l2_ctrl *ctrl; + struct v4l2_ctrl *ctrl, *hdr; const struct v4l2_ctrl_vp9_frame *dec_params; struct avd_vp9_ctx *vp9_ctx = ctx->priv; unsigned int fctx_idx; @@ -846,16 +846,25 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_VP9_COMPRESSED_HDR); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->prob_updates = ctrl->p_cur.p; - + hdr = v4l2_ctrl_find(&ctx->ctrl_hdl, + V4L2_CID_STATELESS_VP9_COMPRESSED_HDR); ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_VP9_FRAME); - if (WARN_ON(!ctrl)) + if (WARN_ON(!hdr || !ctrl)) return -EINVAL; - dec_params = ctrl->p_cur.p; + + /* + * A plain VIDIOC_S_EXT_CTRLS can change the controls while the job is + * built; check and build from copies taken under the control lock. + */ + v4l2_ctrl_lock(ctrl); + run->prob_updates = kmemdup(hdr->p_cur.p, sizeof(*run->prob_updates), + GFP_KERNEL); + run->decode_params = kmemdup(ctrl->p_cur.p, + sizeof(*run->decode_params), GFP_KERNEL); + v4l2_ctrl_unlock(ctrl); + if (!run->prob_updates || !run->decode_params) + return -ENOMEM; + dec_params = run->decode_params; ret = validate_dec_params(ctx, dec_params); if (ret) @@ -866,8 +875,6 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) if (ret) return ret; - run->decode_params = dec_params; - if (avd_backend_is_qfw(ctx->dev)) { struct avd_vp9_bank *bank = NULL; @@ -904,7 +911,7 @@ static void avd_vp9_update_probs(struct avd_ctx *ctx, static int avd_vp9_run(struct avd_ctx *ctx) { - struct avd_vp9_run run; + struct avd_vp9_run run = {}; struct avd_vp9_ctx *vp9_ctx; struct avd_decoded_buffer *dst; int ret; @@ -912,7 +919,7 @@ static int avd_vp9_run(struct avd_ctx *ctx) ret = avd_vp9_run_preamble(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } /* One segment per tile, bounded by avd_vp9_check_tiling(), and the header. */ @@ -921,7 +928,7 @@ static int avd_vp9_run(struct avd_ctx *ctx) run.decode_params->tile_cols_log2)) + 1); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } init_probs(ctx, &run); @@ -943,7 +950,11 @@ static int avd_vp9_run(struct avd_ctx *ctx) update_ctx_last_info(vp9_ctx); ctx->job_fifo = vp9_ctx->b->bufs.inst.addr; } - return avd_submit_job(ctx); + ret = avd_submit_job(ctx); +out: + kfree(run.decode_params); + kfree(run.prob_updates); + return ret; } #define copy_tx_and_skip(p1, p2) \ From be33a283e68fead18b2ccacb8e4cbf3a84b8e31d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:13:32 +1100 Subject: [PATCH 0585/1514] media: apple: avd: hevc: check slice addresses, references and data The slice builder indexed the CTB tables with each slice's slice_segment_addr, the reference list with collocated_ref_idx and the DPB with the list entry it found there, none of which were compared with the size of what they index. It also handed the decoder slice and entry point offsets and sizes without comparing them with the OUTPUT payload, so a size could underflow or point past the buffer. Before building the job, check every slice: its address must be a CTB of the picture, the collocated reference index must fit the reference list (and, with temporal MV prediction, its active part, H.265 7.4.7.1), the entry it selects must be a DPB entry, and each slice segment's data must lie inside the payload, using the same segment layout as the builder. Also stop building when the tile position runs past the tile boundary tables. Add KUnit cases for accepted and refused slices. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-hevc-test.c | 143 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-hevc.c | 110 ++++++++++++-- drivers/media/platform/apple/avd/avd.h | 6 + 3 files changed, 250 insertions(+), 9 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c index 50db548b19e287..efb0cf13b0d8f7 100644 --- a/drivers/media/platform/apple/avd/avd-hevc-test.c +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -138,10 +138,153 @@ static void avd_hevc_no_tiles_test(struct kunit *test) 0); } +struct avd_hevc_slices_case { + const char *desc; + bool tiles; + u8 type; + u32 flags; + u32 addr; + u8 col_idx; + u8 l0_last; + u8 l0_ref; + u32 bytes; + u32 data_offset; + u32 num_entry_points; + u32 entry_point; + u32 available_entry_points; + u32 payload; + int ret; +}; + +#define AVD_TMVP V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED + +static const struct avd_hevc_slices_case avd_hevc_slices_cases[] = { + { "I slice at the first CTB", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 100, .data_offset = 10, .payload = 100 }, + { "I slice at the last CTB", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = 15, .bytes = 100, .data_offset = 10, .payload = 100 }, + { "slice address past the picture", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = 16, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "slice address far past the picture", .type = V4L2_HEVC_SLICE_TYPE_I, + .addr = U32_MAX, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "slice data ends one byte after the payload", + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .payload = 99, .ret = -EINVAL }, + { "slice header longer than the slice", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 10, .data_offset = 11, .payload = 100, .ret = -EINVAL }, + { "payload beyond the 31-bit range", .type = V4L2_HEVC_SLICE_TYPE_I, + .bytes = 100, .payload = U32_MAX, .ret = -EINVAL }, + { "P slice, collocated picture in the list", + .type = V4L2_HEVC_SLICE_TYPE_P, .flags = AVD_TMVP, .col_idx = 1, + .l0_last = 1, .l0_ref = 15, .bytes = 100, .payload = 100 }, + { "P slice, collocated index past the active list", + .type = V4L2_HEVC_SLICE_TYPE_P, .flags = AVD_TMVP, .col_idx = 2, + .l0_last = 1, .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "P slice without TMVP, unused collocated index", + .type = V4L2_HEVC_SLICE_TYPE_P, .col_idx = 2, .l0_last = 1, + .bytes = 100, .payload = 100 }, + { "P slice, collocated index past the list array", + .type = V4L2_HEVC_SLICE_TYPE_P, .col_idx = 16, .l0_last = 15, + .bytes = 100, .payload = 100, .ret = -EINVAL }, + { "P slice, missing reference marked past the DPB", + .type = V4L2_HEVC_SLICE_TYPE_P, .l0_ref = 255, .bytes = 100, + .payload = 100 }, + { "B slice, missing L1 reference marked past the DPB", + .type = V4L2_HEVC_SLICE_TYPE_B, .l0_ref = 255, .bytes = 100, + .payload = 100 }, + { "two tiles, entry point inside the slice", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = 40, + .available_entry_points = 1, .payload = 100 }, + { "two tiles, entry point past the payload", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = 91, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, + { "two tiles, entry point far past the payload", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 1, .entry_point = U32_MAX, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, + { "two tiles, more entry points than given", .tiles = true, + .type = V4L2_HEVC_SLICE_TYPE_I, .bytes = 100, .data_offset = 10, + .num_entry_points = 2, .entry_point = 40, + .available_entry_points = 1, .payload = 100, .ret = -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_hevc_slices, avd_hevc_slices_cases, desc); + +static void avd_hevc_slices_test(struct kunit *test) +{ + const struct avd_hevc_slices_case *c = test->param_value; + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ep[2] = { c->entry_point, c->entry_point }; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kzalloc(test, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + if (c->tiles) { + pps.flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING; + pps.num_tile_columns_minus1 = 1; + } + decode->num_active_dpb_entries = 2; + sl->slice_type = c->type; + sl->flags = c->flags; + sl->slice_segment_addr = c->addr; + sl->collocated_ref_idx = c->col_idx; + sl->num_ref_idx_l0_active_minus1 = c->l0_last; + sl->num_ref_idx_l1_active_minus1 = c->l0_last; + memset(sl->ref_idx_l0, c->l0_ref, sizeof(sl->ref_idx_l0)); + memset(sl->ref_idx_l1, c->l0_ref, sizeof(sl->ref_idx_l1)); + sl->bit_size = c->bytes * 8; + sl->data_byte_offset = c->data_offset; + sl->num_entry_point_offsets = c->num_entry_points; + + KUNIT_EXPECT_EQ(test, + avd_hevc_check_slices(&sps, &pps, decode, sl, 1, ep, + c->available_entry_points, + c->payload), + c->ret); +} + +/* A slice only fits after the ones before it. */ +static void avd_hevc_two_slices_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = {}; + u32 ep = 0; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kcalloc(test, 2, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + sl[0].slice_type = V4L2_HEVC_SLICE_TYPE_I; + sl[0].bit_size = 60 * 8; + sl[0].data_byte_offset = 5; + sl[1] = sl[0]; + sl[1].slice_segment_addr = 8; + + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + &ep, 1, 120), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + &ep, 1, 119), -EINVAL); +} + static struct kunit_case avd_hevc_test_cases[] = { KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), KUNIT_CASE(avd_hevc_no_tiles_test), + KUNIT_CASE_PARAM(avd_hevc_slices_test, avd_hevc_slices_gen_params), + KUNIT_CASE(avd_hevc_two_slices_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 9c52f50586f884..1f283c2058e3ad 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -599,8 +599,9 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, { const struct v4l2_ctrl_hevc_decode_params *decode = run->decode; struct avd_decoded_buffer *dst, *ref; - bool ref_valid; + bool ref_valid, col_in_dpb; const u8 *ref_list; + u8 col; if (sl->slice_type == V4L2_HEVC_SLICE_TYPE_I) { push(AVD_OP_SL_REF | @@ -617,11 +618,17 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, sl->ref_idx_l1; dst = vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf); - ref = avd_get_ref_buf( - ctx, &dst->base.vb, - decode->dpb[ref_list[sl->collocated_ref_idx]].timestamp); + /* + * Clients mark a reference they do not have with an index past the + * DPB (0xff); there is no collocated picture to take MVs from then. + */ + col = ref_list[sl->collocated_ref_idx]; + col_in_dpb = col < ARRAY_SIZE(decode->dpb); + ref = col_in_dpb ? + avd_get_ref_buf(ctx, &dst->base.vb, decode->dpb[col].timestamp) : + dst; - ref_valid = !(sl->flags & + ref_valid = col_in_dpb && !(sl->flags & V4L2_HEVC_SLICE_PARAMS_FLAG_DEPENDENT_SLICE_SEGMENT) && (sl->flags & V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED) && @@ -662,8 +669,7 @@ static void stream_slice_mv(struct avd_ctx *ctx, struct avd_hevc_run *run, mv_color_size(fmt_width(ctx), fmt_height(ctx)), AVD_ALIGN); pusha(mv_color_addr, "slc_bd4_sps_tile_addr2_lsb8", - decode->dpb[ref_list[sl->collocated_ref_idx]] - .pic_order_cnt_val); + decode->dpb[col].pic_order_cnt_val); } } @@ -958,6 +964,10 @@ static int stream_slices(struct avd_ctx *ctx, struct avd_hevc_run *run) row = pos / num_cols; col = pos % num_cols; + /* More tiles than the boundary tables describe */ + if (tiles_enabled && (slice_flag & NEW_TILE_ID) && + row + 1 >= ARRAY_SIZE(tile_info->row_bd)) + return -EINVAL; /* * not a fan of this, in JCT-VC-HEVC_V1 only TILES_B_Cisco_1 @@ -1117,6 +1127,82 @@ VISIBLE_IF_KUNIT int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, } EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_tiles); +/* + * Check what the slice builder takes from the slice parameters before it + * uses them: the slice address must be a CTB of the picture, the collocated + * reference must be an entry of its reference list (H.265 7.4.7.1), and + * every slice segment's data must lie in the payload. The + * segment layout is the one stream_slices() programs. + * avd_hevc_check_sps_geometry() must have accepted the SPS. + */ +VISIBLE_IF_KUNIT int +avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + const struct v4l2_ctrl_hevc_decode_params *decode, + const struct v4l2_ctrl_hevc_slice_params *slices, + u32 num_slices, const u32 *entry_points, + u32 num_entry_points, u32 payload) +{ + bool tiles = pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED; + u32 width, height, ep = 0, s, i, to; + s64 offset = 0, seg_offset, size, next; + + if (payload > INT_MAX) + return -EINVAL; + avd_hevc_pic_in_ctbs(sps, &width, &height); + + for (s = 0; s < num_slices; s++) { + const struct v4l2_ctrl_hevc_slice_params *sl = &slices[s]; + s64 bytes = sl->bit_size / 8; + + if (sl->slice_segment_addr >= width * height) + return -EINVAL; + + if (sl->slice_type != V4L2_HEVC_SLICE_TYPE_I) { + bool l0 = sl->slice_type == V4L2_HEVC_SLICE_TYPE_P || + sl->flags & + V4L2_HEVC_SLICE_PARAMS_FLAG_COLLOCATED_FROM_L0; + u8 last = l0 ? sl->num_ref_idx_l0_active_minus1 : + sl->num_ref_idx_l1_active_minus1; + + if (sl->collocated_ref_idx >= ARRAY_SIZE(sl->ref_idx_l0)) + return -EINVAL; + if ((sl->flags & + V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED) && + sl->collocated_ref_idx > last) + return -EINVAL; + } + + to = tiles ? sl->num_entry_point_offsets + 1 : 1; + if (tiles && sl->num_entry_point_offsets > + num_entry_points - ep) + return -EINVAL; + + seg_offset = 0; + for (i = 0; i < to; i++) { + if (to > 1 && i < sl->num_entry_point_offsets) { + size = entry_points[ep++]; + next = size; + } else if (to > 1) { + size = bytes - sl->data_byte_offset - seg_offset; + next = size + sl->data_byte_offset; + } else { + size = bytes - sl->data_byte_offset; + next = size + sl->data_byte_offset; + } + if (size < 0 || + offset + seg_offset + sl->data_byte_offset + size > + payload) + return -EINVAL; + seg_offset += next; + } + offset += bytes; + } + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_slices); + static int avd_hevc_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_hevc_sps *sps) { @@ -1595,6 +1681,7 @@ static int avd_hevc_run(struct avd_ctx *ctx) struct avd_hevc_ctx *hevc_ctx = ctx->priv; struct avd_hevc_run run = {}; struct avd_decoded_buffer *dst; + u32 payload; int ret; ret = avd_hevc_run_preamble(ctx, &run); @@ -1606,8 +1693,13 @@ static int avd_hevc_run(struct avd_ctx *ctx) if (ret) goto complete; - avd_hevc_normalize_slices(&run, - vb2_get_plane_payload(&run.base.bufs.src->vb2_buf, 0)); + payload = vb2_get_plane_payload(&run.base.bufs.src->vb2_buf, 0); + avd_hevc_normalize_slices(&run, payload); + ret = avd_hevc_check_slices(run.sps, run.pps, run.decode, run.sl, + run.num_slices, run.entry_point_offsets, + run.num_entry_point_offsets, payload); + if (ret) + goto complete; dst = vb2_to_avd_decoded_buf(&run.base.bufs.dst->vb2_buf); update_dec_buf_info(dst, &run.sl[0]); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 6fee27521eed2d..fdf6be6cbe054c 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -380,6 +380,12 @@ bool avd_h264_scaling_is_flat(const struct v4l2_ctrl_h264_pps *pps, int avd_hevc_check_sps_geometry(const struct v4l2_ctrl_hevc_sps *sps); int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, const struct v4l2_ctrl_hevc_pps *pps); +int avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, + const struct v4l2_ctrl_hevc_pps *pps, + const struct v4l2_ctrl_hevc_decode_params *decode, + const struct v4l2_ctrl_hevc_slice_params *slices, + u32 num_slices, const u32 *entry_points, + u32 num_entry_points, u32 payload); int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, const struct v4l2_ctrl_hevc_pps *pps, u32 *tile_ids, size_t n); From 8e206693b3cabb99adb2927ee1e8ec177577e132 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:13:25 +1100 Subject: [PATCH 0586/1514] media: apple: avd: vp9: keep the tiles within the bitstream set_tiles() takes the tile data offset from the two header sizes of the frame control and reads the size of every tile but the last from the OUTPUT buffer, without comparing either with the payload. The remaining size is a u32 that wraps when the header sizes exceed the payload, and the "tile_size > size - 4" check wraps when fewer than four bytes are left, so the walk can read and hand to the decoder offsets and sizes outside the buffer. The buffer mapping is not checked for NULL either. Factor the step into avd_vp9_next_tile(): it requires a mapping, the tile offset within the payload, four bytes for a tile size and the tile within what is left, all without wrapping, and a non-empty tile (VP9 9.2.1). Every tile handed to the decoder, the last one included, then lies within the payload. On a bad layout set_tiles() fails the frame with -EINVAL instead of submitting the tiles it has so far. Add KUnit tests for the tile walk. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-vp9-test.c | 78 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-vp9.c | 66 ++++++++++++---- drivers/media/platform/apple/avd/avd.h | 2 + 3 files changed, 130 insertions(+), 16 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-vp9-test.c b/drivers/media/platform/apple/avd/avd-vp9-test.c index 469de409886183..f0b501dffde176 100644 --- a/drivers/media/platform/apple/avd/avd-vp9-test.c +++ b/drivers/media/platform/apple/avd/avd-vp9-test.c @@ -48,8 +48,86 @@ static void avd_vp9_tiling_test(struct kunit *test) KUNIT_EXPECT_EQ(test, avd_vp9_check_tiling(&frame), c->ret); } +#define AVD_TEST_MAX_TILES 2 + +struct avd_vp9_tiles_case { + const char *desc; + const u8 *data; + u32 payload; + u32 header; + unsigned int tiles; + int ret; + u32 offsets[AVD_TEST_MAX_TILES]; + u32 sizes[AVD_TEST_MAX_TILES]; +}; + +/* Two tiles after a 2-byte header: a 3-byte tile, then the rest. */ +static const u8 avd_test_two_tiles[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x03, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile's size reaches one byte past the payload. */ +static const u8 avd_test_long_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x06, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile's size is the largest u32. */ +static const u8 avd_test_huge_tile[] = { + 0xaa, 0xbb, 0xff, 0xff, 0xff, 0xff, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* The first tile fills the payload and leaves nothing for the last one. */ +static const u8 avd_test_no_last_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +/* An empty first tile. */ +static const u8 avd_test_empty_tile[] = { + 0xaa, 0xbb, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, +}; + +static const struct avd_vp9_tiles_case avd_vp9_tiles_cases[] = { + { "one tile", avd_test_two_tiles, 11, 2, 1, 0, { 2 }, { 9 } }, + { "two tiles", avd_test_two_tiles, 11, 2, 2, 0, { 6, 9 }, { 3, 2 } }, + { "headers beyond the payload", avd_test_two_tiles, 11, 12, 1, -EINVAL }, + { "headers fill the payload", avd_test_two_tiles, 11, 11, 1, -EINVAL }, + { "headers beyond the payload, two tiles", avd_test_two_tiles, 11, + 0xffff + 0xffff, 2, -EINVAL }, + { "three bytes for a tile size", avd_test_two_tiles, 5, 2, 2, -EINVAL }, + { "no bytes for a tile size", avd_test_two_tiles, 2, 2, 2, -EINVAL }, + { "tile beyond the payload", avd_test_long_tile, 11, 2, 2, -EINVAL }, + { "tile size wraps", avd_test_huge_tile, 11, 2, 2, -EINVAL }, + { "no data for the last tile", avd_test_no_last_tile, 11, 2, 2, -EINVAL, + { 6 }, { 5 } }, + { "empty tile", avd_test_empty_tile, 11, 2, 2, -EINVAL }, + { "no mapping", NULL, 11, 2, 1, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_vp9_tiles, avd_vp9_tiles_cases, desc); + +/* Walks the tiles as set_tiles() does. */ +static void avd_vp9_tiles_test(struct kunit *test) +{ + const struct avd_vp9_tiles_case *c = test->param_value; + u32 offset = c->header, size; + int ret = 0; + + for (unsigned int i = 0; i < c->tiles; i++) { + ret = avd_vp9_next_tile(c->data, c->payload, i == c->tiles - 1, + &offset, &size); + if (ret) + break; + KUNIT_EXPECT_EQ(test, offset, c->offsets[i]); + KUNIT_EXPECT_EQ(test, size, c->sizes[i]); + KUNIT_EXPECT_LE(test, (u64)offset + size, (u64)c->payload); + offset += size; + } + KUNIT_EXPECT_EQ(test, ret, c->ret); +} + static struct kunit_case avd_vp9_test_cases[] = { KUNIT_CASE_PARAM(avd_vp9_tiling_test, avd_vp9_tiling_gen_params), + KUNIT_CASE_PARAM(avd_vp9_tiles_test, avd_vp9_tiles_gen_params), {} }; diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 71b80796fd090b..e72aeb8dc2c2fd 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -493,19 +493,53 @@ static void set_header(struct avd_ctx *ctx, struct avd_vp9_run *run) set_refs(ctx, run); } -static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) +/* + * Find the next tile in the frame (VP9 6.4 decode_tiles()): at @offset each + * tile but the last starts with its size as a 32-bit big-endian word, the + * last one takes the rest of the payload. Returns the tile's data offset in + * @offset and its size in @size, both within @payload. A tile holds at least + * one byte (9.2.1: sz is at least 1). + */ +VISIBLE_IF_KUNIT int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, + u32 *offset, u32 *size) +{ + u32 off = *offset, tile_size; + + if (!data || off > payload) + return -EINVAL; + + if (last) { + tile_size = payload - off; + } else { + if (payload - off < 4) + return -EINVAL; + tile_size = get_unaligned_be32(&data[off]); + off += 4; + if (tile_size > payload - off) + return -EINVAL; + } + if (!tile_size) + return -EINVAL; + + *offset = off; + *size = tile_size; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_next_tile); + +static int set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) { const struct v4l2_ctrl_vp9_frame *frame = run->decode_params; struct avd_vp9_ctx *vp9_ctx = ctx->priv; struct vb2_v4l2_buffer *src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); const u8 *data = vb2_plane_vaddr(&src->vb2_buf, 0); - + u32 payload = vb2_get_plane_payload(&src->vb2_buf, 0); u32 offset = frame->uncompressed_header_size + frame->compressed_header_size; - u32 size = vb2_get_plane_payload(&src->vb2_buf, 0) - offset; u32 num_tile_rows = 1 << frame->tile_rows_log2; u32 num_tile_cols = 1 << frame->tile_cols_log2; u32 tile_size; + int ret; /* 6.2.6 Compute image size syntax */ u32 sb_64_cols = (((frame->frame_width_minus_1 + 8) >> 3) + 7) >> 3; @@ -513,18 +547,15 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) for (int row = 0; row < num_tile_rows; row++) for (int col = 0; col < num_tile_cols; col++) { + /* Every tile lies within the payload. */ + ret = avd_vp9_next_tile(data, payload, + row == num_tile_rows - 1 && + col == num_tile_cols - 1, + &offset, &tile_size); + if (ret) + return ret; + ctx->job.num++; - if (row == num_tile_rows - 1 && - col == num_tile_cols - 1) { - tile_size = size; - } else { - tile_size = get_unaligned_be32(&data[offset]); - /* i have crashed my computer because of this */ - if (tile_size > size - 4) - return; - offset += 4; - size -= 4; - } push(AVD_OP_CODED_DATA | AVD_OP_CODED_DATA_ADDR( run->base.coded_in >> 32), @@ -547,9 +578,10 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_vp9_run *run) "til_ac0_tile_dims"); offset += tile_size; - size -= tile_size; vp9_ctx->b->submit_num++; } + + return 0; } static void update_dec_buf_info(struct avd_decoded_buffer *buf, @@ -940,8 +972,10 @@ static int avd_vp9_run(struct avd_ctx *ctx) set_header(ctx, &run); vp9_ctx->b->submit_num = 0; - set_tiles(ctx, &run); + ret = set_tiles(ctx, &run); avd_run_postamble(ctx, &run.base); + if (ret) + goto out; if (avd_backend_is_qfw(ctx->dev)) { /* Forward updates need no hardware result; publish before next prepare. */ diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index fdf6be6cbe054c..73af6ba6f3eaf0 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -390,6 +390,8 @@ int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, const struct v4l2_ctrl_hevc_pps *pps, u32 *tile_ids, size_t n); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); +int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, u32 *offset, + u32 *size); #endif extern const struct avd_coded_fmt_ops avd_h264_fmt_ops; From 22919336fc6f232797fb4e8cc5d324dc6251e8b2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:11:39 +1100 Subject: [PATCH 0587/1514] media: apple: avd: av1: bound tile_row and tile_col of the tile entries set_tiles() looks up mi_row_starts[], mi_col_starts[], height_in_sbs_minus_1[] and width_in_sbs_minus_1[] of the frame's tile_info with the tile_row and tile_col fields of each tile-group entry. The control framework does not validate V4L2_CTRL_TYPE_AV1_TILE_GROUP_ENTRY, and avd_av1_check_tiles() only checked each tile's offset and size, so values past tile_rows/tile_cols indexed past the ends of those arrays. In a conformant stream TileRow < TileRows and TileCol < TileCols (AV1 5.11.1). Reject a frame whose tile entries are outside the frame's tile grid, and also check tile_rows and tile_cols against V4L2_AV1_MAX_TILE_ROWS/COLS in the same place so the helper does not depend on the core's frame validation for the array sizes. Make avd_av1_check_tiles() take the tile grid, the entries and the payload size directly so it can be exercised from KUnit, and add avd-av1-test.c covering the grid bounds, the entry count and the offset/size check. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 2 +- .../media/platform/apple/avd/avd-av1-test.c | 126 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-av1.c | 44 ++++-- drivers/media/platform/apple/avd/avd.h | 4 + 4 files changed, 162 insertions(+), 14 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-av1-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index be42b7f645da8a..e7d7da9f671a54 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -5,5 +5,5 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o \ - avd-vp9-test.o + avd-av1-test.o avd-vp9-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-av1-test.c b/drivers/media/platform/apple/avd/avd-av1-test.c new file mode 100644 index 00000000000000..33ad22165ce79e --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-av1-test.c @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the AV1 tile checks of the Apple video decoder. + */ + +#include + +#include "avd.h" + +#define AVD_TEST_PAYLOAD 4096 + +/* A rows x cols layout, entries in raster order, each tile 100 bytes. */ +static void avd_av1_test_layout(struct v4l2_ctrl_av1_tile_group_entry *e, + unsigned int rows, unsigned int cols) +{ + unsigned int r, c; + + for (r = 0; r < rows; r++) + for (c = 0; c < cols; c++, e++) { + e->tile_offset = (r * cols + c) * 100; + e->tile_size = 100; + e->tile_row = r; + e->tile_col = c; + } +} + +static void avd_av1_tiles_valid_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), 0); + /* Entries past the frame's tiles are not looked at. */ + e[5].tile_row = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 1, 3, e, 6, + AVD_TEST_PAYLOAD), 0); + /* No tiles, no entries. */ + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 0, 0, e, 0, + AVD_TEST_PAYLOAD), 0); +} + +static void avd_av1_tiles_count_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 5, + AVD_TEST_PAYLOAD), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, V4L2_AV1_MAX_TILE_ROWS + 1, + 1, e, 6, AVD_TEST_PAYLOAD), + -EINVAL); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 1, + V4L2_AV1_MAX_TILE_COLS + 1, + e, 6, AVD_TEST_PAYLOAD), + -EINVAL); +} + +static void avd_av1_tiles_extent_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + /* The last tile ends exactly at the payload's end. */ + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, 600), 0); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, 599), + -EINVAL); + e[2].tile_offset = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), -EINVAL); + e[2].tile_offset = 200; + e[2].tile_size = U32_MAX; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), -EINVAL); +} + +struct avd_av1_rowcol_case { + const char *desc; + unsigned int idx; + u32 tile_row; + u32 tile_col; + int ret; +}; + +/* Entry idx of a 2x3 layout gets tile_row/tile_col; every other entry is valid. */ +static const struct avd_av1_rowcol_case avd_av1_rowcol_cases[] = { + { "last row and column", 5, 1, 2, 0 }, + { "row equals tile_rows", 5, 2, 2, -EINVAL }, + { "column equals tile_cols", 5, 1, 3, -EINVAL }, + { "first entry, row equals tile_rows", 0, 2, 0, -EINVAL }, + { "row past the tile_info arrays", 3, V4L2_AV1_MAX_TILE_ROWS + 1, 0, -EINVAL }, + { "column past the tile_info arrays", 3, 0, V4L2_AV1_MAX_TILE_COLS + 1, -EINVAL }, + { "huge row", 1, 0x3fffffff, 0, -EINVAL }, + { "huge column", 1, 0, 0x3fffffff, -EINVAL }, + { "row U32_MAX", 4, U32_MAX, 1, -EINVAL }, + { "column U32_MAX", 4, 1, U32_MAX, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_av1_rowcol, avd_av1_rowcol_cases, desc); + +static void avd_av1_tiles_rowcol_test(struct kunit *test) +{ + const struct avd_av1_rowcol_case *c = test->param_value; + struct v4l2_ctrl_av1_tile_group_entry e[6] = {}; + + avd_av1_test_layout(e, 2, 3); + e[c->idx].tile_row = c->tile_row; + e[c->idx].tile_col = c->tile_col; + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, e, 6, + AVD_TEST_PAYLOAD), c->ret); +} + +static struct kunit_case avd_av1_test_cases[] = { + KUNIT_CASE(avd_av1_tiles_valid_test), + KUNIT_CASE(avd_av1_tiles_count_test), + KUNIT_CASE(avd_av1_tiles_extent_test), + KUNIT_CASE_PARAM(avd_av1_tiles_rowcol_test, avd_av1_rowcol_gen_params), + {} +}; + +static struct kunit_suite avd_av1_test_suite = { + .name = "apple-avd-av1", + .test_cases = avd_av1_test_cases, +}; + +kunit_test_suite(avd_av1_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index 8b3c2f34c542ca..c39c63adb4f089 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -16,6 +16,7 @@ * Tomasz Figa */ +#include #include #include "avd.h" @@ -1396,34 +1397,48 @@ static void update_dec_buf_info(struct avd_decoded_buffer *buf, buf->av1.ref_frame_idx[i] = frame->ref_frame_idx[i]; } -/* The engine fetches each tile from these: bad values make it read wild addresses. */ -static int avd_av1_check_tiles(struct avd_ctx *ctx, struct avd_av1_run *run, - unsigned int entries) +/* + * The engine fetches each tile from these: bad values make it read wild + * addresses. set_tiles() also looks each entry's tile_row and tile_col up in + * the frame's tile_info arrays; in a conformant stream they are below + * TileRows and TileCols (AV1 5.11.1, tile_group_obu()), and TileRows and + * TileCols are at most MAX_TILE_ROWS and MAX_TILE_COLS (AV1 section 3). + */ +VISIBLE_IF_KUNIT int +avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, + unsigned int tile_cols, + const struct v4l2_ctrl_av1_tile_group_entry *tile_group, + unsigned int entries, size_t payload) { - unsigned int tiles = run->frame->tile_info.tile_cols * - run->frame->tile_info.tile_rows; + unsigned int tiles = tile_cols * tile_rows; unsigned int t; - size_t payload; + if (tile_rows > V4L2_AV1_MAX_TILE_ROWS || + tile_cols > V4L2_AV1_MAX_TILE_COLS) + return -EINVAL; if (entries < tiles) { - dev_err_ratelimited(ctx->dev->dev, "AV1: %u tiles but %u tile entries\n", + dev_err_ratelimited(dev, "AV1: %u tiles but %u tile entries\n", tiles, entries); return -EINVAL; } - if (!tiles) - return 0; - payload = vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0); for (t = 0; t < tiles; t++) { - const struct v4l2_ctrl_av1_tile_group_entry *e = &run->tile_group[t]; + const struct v4l2_ctrl_av1_tile_group_entry *e = &tile_group[t]; if ((u64)e->tile_offset + e->tile_size > payload) { - dev_err_ratelimited(ctx->dev->dev, "AV1: tile %u at %u+%u past %zu bytes\n", + dev_err_ratelimited(dev, "AV1: tile %u at %u+%u past %zu bytes\n", t, e->tile_offset, e->tile_size, payload); return -EINVAL; } + if (e->tile_row >= tile_rows || e->tile_col >= tile_cols) { + dev_err_ratelimited(dev, "AV1: tile %u at row %u col %u of %ux%u\n", + t, e->tile_row, e->tile_col, + tile_rows, tile_cols); + return -EINVAL; + } } return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_tiles); /* * Only the AV1 Main profile at 4:2:0 (8 and 10 bits) decodes. A High @@ -1498,7 +1513,10 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (WARN_ON(!ctrl)) return -EINVAL; run->tile_group = ctrl->p_cur.p; - ret = avd_av1_check_tiles(ctx, run, ctrl->elems); + ret = avd_av1_check_tiles(ctx->dev->dev, run->frame->tile_info.tile_rows, + run->frame->tile_info.tile_cols, + run->tile_group, ctrl->elems, + vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0)); if (ret) return ret; diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 73af6ba6f3eaf0..45469d512e3cdb 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -389,6 +389,10 @@ int avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, int avd_hevc_kunit_compute_tiles(const struct v4l2_ctrl_hevc_sps *sps, const struct v4l2_ctrl_hevc_pps *pps, u32 *tile_ids, size_t n); +int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, + unsigned int tile_cols, + const struct v4l2_ctrl_av1_tile_group_entry *tile_group, + unsigned int entries, size_t payload); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, u32 *offset, u32 *size); From 765f07af1a6d5ade49c6a010e65b7be1c91cc986 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:16:05 +1100 Subject: [PATCH 0588/1514] media: apple: avd: Keep TRY_FMT(CAPTURE) from changing the context avd_fill_decoded_pixfmt() stored the compressed reference layout of the format it was given in ctx->comp. TRY_FMT(CAPTURE) shares it with S_FMT, so trying a format replaced the layout of the negotiated one, also while CAPTURE buffers were allocated or streaming. The run path places the compressed area at ctx->comp.start_offset in each CAPTURE buffer and hands ctx->comp.offsets to the decoder, so the decoder then used a layout that did not match the buffers, and the check that lets a format control change on a busy queue compared against the tried format. Compute the layout into a caller provided struct avd_comp. TRY_FMT discards it; ctx->comp is only stored by avd_reset_decoded_fmt() and avd_s_capture_fmt(), which do not run with CAPTURE buffers allocated, so ctx->comp always describes ctx->decoded_fmt. Add KUnit tests that TRY_FMT(CAPTURE) leaves ctx->comp and the decoded format unchanged, busy or not, and that S_FMT(CAPTURE) stores the layout of the format it sets. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 2 +- .../media/platform/apple/avd/avd-v4l2-test.c | 150 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-v4l2.c | 42 +++-- drivers/media/platform/apple/avd/avd.h | 2 + 4 files changed, 183 insertions(+), 13 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-v4l2-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index e7d7da9f671a54..926ebb1d8a73a6 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -5,5 +5,5 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o \ - avd-av1-test.o avd-vp9-test.o + avd-av1-test.o avd-v4l2-test.o avd-vp9-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-v4l2-test.c b/drivers/media/platform/apple/avd/avd-v4l2-test.c new file mode 100644 index 00000000000000..0c057d567b6152 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-v4l2-test.c @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the format ioctls of the Apple video decoder. + */ + +#include +#include +#include + +#include "avd.h" + +static const struct avd_coded_fmt_ops avd_test_ops = {}; + +static const struct avd_decoded_fmt_desc avd_test_decoded_fmts[] = { + { .fourcc = V4L2_PIX_FMT_NV12, .image_fmt = AVD_IMG_FMT_420_8BIT }, +}; + +static const struct avd_coded_fmt_desc avd_test_coded_desc = { + .fourcc = V4L2_PIX_FMT_H264_SLICE, + .frmsize = { + .min_width = 64, .max_width = 4096, .step_width = 64, + .min_height = 64, .max_height = 4096, .step_height = 16, + }, + .ops = &avd_test_ops, + .num_decoded_fmts = ARRAY_SIZE(avd_test_decoded_fmts), + .decoded_fmts = avd_test_decoded_fmts, +}; + +struct avd_test_fmt { + struct avd_ctx *ctx; + struct file *file; + struct vb2_queue *cap_q; +}; + +/* A 64x64 context with its default CAPTURE format, as after open(). */ +static void avd_test_fmt_init(struct kunit *test, struct avd_test_fmt *t) +{ + struct v4l2_m2m_ctx *m2m_ctx; + + t->ctx = kunit_kzalloc(test, sizeof(*t->ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + t->file = kunit_kzalloc(test, sizeof(*t->file), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t->file); + + t->ctx->fh.m2m_ctx = m2m_ctx; + t->file->private_data = &t->ctx->fh; + t->cap_q = &m2m_ctx->cap_q_ctx.q; + + t->ctx->coded_fmt_desc = &avd_test_coded_desc; + t->ctx->coded_fmt.fmt.pix_mp.width = 64; + t->ctx->coded_fmt.fmt.pix_mp.height = 64; + t->ctx->image_fmt = AVD_IMG_FMT_420_8BIT; + avd_reset_decoded_fmt(t->ctx); +} + +static void avd_test_capture_fmt(struct v4l2_format *f, u32 width, u32 height) +{ + memset(f, 0, sizeof(*f)); + f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + f->fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + f->fmt.pix_mp.width = width; + f->fmt.pix_mp.height = height; +} + +static void avd_test_expect_comp(struct kunit *test, + const struct avd_comp *got, + const struct avd_comp *want) +{ + KUNIT_EXPECT_EQ(test, got->size, want->size); + KUNIT_EXPECT_EQ(test, got->start_offset, want->start_offset); + KUNIT_EXPECT_MEMEQ(test, got->offsets, want->offsets, + sizeof(want->offsets)); +} + +/* TRY_FMT(CAPTURE) must leave the context's buffer layout alone. */ +static void avd_try_capture_fmt_test(struct kunit *test) +{ + struct avd_test_fmt t; + struct v4l2_format f, decoded; + struct avd_comp comp; + + avd_test_fmt_init(test, &t); + comp = t.ctx->comp; + decoded = t.ctx->decoded_fmt; + KUNIT_ASSERT_NE(test, comp.size, 0); + + /* CAPTURE buffers allocated, as when streaming. */ + t.cap_q->is_busy = 1; + avd_test_capture_fmt(&f, 4096, 4096); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + KUNIT_EXPECT_EQ(test, f.fmt.pix_mp.width, 4096); + KUNIT_EXPECT_GT(test, f.fmt.pix_mp.plane_fmt[0].sizeimage, + decoded.fmt.pix_mp.plane_fmt[0].sizeimage); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + KUNIT_EXPECT_MEMEQ(test, &t.ctx->decoded_fmt, &decoded, sizeof(decoded)); + + /* S_FMT is refused on the busy queue and changes nothing either. */ + avd_test_capture_fmt(&f, 4096, 4096); + KUNIT_EXPECT_EQ(test, avd_s_capture_fmt(t.file, NULL, &f), -EBUSY); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + + /* The same holds with no buffers. */ + t.cap_q->is_busy = 0; + avd_test_capture_fmt(&f, 1920, 1088); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + avd_test_expect_comp(test, &t.ctx->comp, &comp); + KUNIT_EXPECT_MEMEQ(test, &t.ctx->decoded_fmt, &decoded, sizeof(decoded)); +} + +/* S_FMT(CAPTURE) lays out the compressed area for the format it sets. */ +static void avd_s_capture_fmt_test(struct kunit *test) +{ + struct avd_test_fmt t; + struct v4l2_format f; + struct avd_comp want = {}; + + avd_test_fmt_init(test, &t); + + avd_test_capture_fmt(&f, 1920, 1088); + KUNIT_ASSERT_EQ(test, avd_s_capture_fmt(t.file, NULL, &f), 0); + + want.start_offset = 1920 * 1088 * 3 / 2; + fill_comp(&want, AVD_IMG_FMT_420_8BIT, 1920, 1088); + avd_test_expect_comp(test, &t.ctx->comp, &want); + KUNIT_EXPECT_EQ(test, t.ctx->decoded_fmt.fmt.pix_mp.width, 1920); + KUNIT_EXPECT_EQ(test, t.ctx->decoded_fmt.fmt.pix_mp.height, 1088); + KUNIT_EXPECT_EQ(test, + t.ctx->decoded_fmt.fmt.pix_mp.plane_fmt[0].sizeimage, + want.start_offset + want.size); + + /* A later TRY_FMT reports its own layout but stores nothing. */ + avd_test_capture_fmt(&f, 4096, 2176); + KUNIT_EXPECT_EQ(test, avd_try_capture_fmt(t.file, NULL, &f), 0); + avd_test_expect_comp(test, &t.ctx->comp, &want); +} + +static struct kunit_case avd_v4l2_test_cases[] = { + KUNIT_CASE(avd_try_capture_fmt_test), + KUNIT_CASE(avd_s_capture_fmt_test), + {} +}; + +static struct kunit_suite avd_v4l2_test_suite = { + .name = "apple-avd-v4l2", + .test_cases = avd_v4l2_test_cases, +}; + +kunit_test_suite(avd_v4l2_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 2a4903ee76aafb..5aabdefffc38d6 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -11,6 +11,7 @@ * Copyright (C) 2011 Samsung Electronics Co., Ltd. */ +#include #include #include @@ -103,15 +104,21 @@ static bool avd_is_valid_fmt(struct avd_ctx *ctx, u32 fourcc, return false; } +/* + * Lay out a decoded buffer: the picture, then the compressed reference area + * described by @comp, then any codec specific tail. Only @pix_mp and @comp + * are written, so TRY_FMT can use it on a context that is streaming. + */ static void avd_fill_decoded_pixfmt(struct avd_ctx *ctx, - struct v4l2_pix_format_mplane *pix_mp) + struct v4l2_pix_format_mplane *pix_mp, + struct avd_comp *comp) { v4l2_fill_pixfmt_mp(pix_mp, pix_mp->pixelformat, pix_mp->width, pix_mp->height); - ctx->comp.start_offset = pix_mp->plane_fmt[0].sizeimage; - fill_comp(&ctx->comp, ctx->image_fmt, pix_mp->width, pix_mp->height); - pix_mp->plane_fmt[0].sizeimage += ctx->comp.size; + comp->start_offset = pix_mp->plane_fmt[0].sizeimage; + fill_comp(comp, ctx->image_fmt, pix_mp->width, pix_mp->height); + pix_mp->plane_fmt[0].sizeimage += comp->size; if (ctx->coded_fmt_desc->ops->adjust_decoded_fmt) ctx->coded_fmt_desc->ops->adjust_decoded_fmt(ctx, pix_mp); } @@ -138,7 +145,7 @@ void avd_reset_decoded_fmt(struct avd_ctx *ctx) f->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; f->fmt.pix_mp.width = ctx->coded_fmt.fmt.pix_mp.width; f->fmt.pix_mp.height = ctx->coded_fmt.fmt.pix_mp.height; - avd_fill_decoded_pixfmt(ctx, &f->fmt.pix_mp); + avd_fill_decoded_pixfmt(ctx, &f->fmt.pix_mp, &ctx->comp); } static int avd_try_ctrl(struct v4l2_ctrl *ctrl) @@ -566,11 +573,10 @@ static int avd_querycap(struct file *file, void *priv, return 0; } -static int avd_try_capture_fmt(struct file *file, void *priv, - struct v4l2_format *f) +static int avd_try_decoded_fmt(struct avd_ctx *ctx, struct v4l2_format *f, + struct avd_comp *comp) { struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; - struct avd_ctx *ctx = file_to_ctx(file); const struct avd_coded_fmt_desc *coded_desc; /* @@ -594,12 +600,21 @@ static int avd_try_capture_fmt(struct file *file, void *priv, v4l2_apply_frmsize_constraints(&pix_mp->width, &pix_mp->height, &coded_desc->frmsize); - avd_fill_decoded_pixfmt(ctx, pix_mp); + avd_fill_decoded_pixfmt(ctx, pix_mp, comp); pix_mp->field = V4L2_FIELD_NONE; return 0; } +VISIBLE_IF_KUNIT int avd_try_capture_fmt(struct file *file, void *priv, + struct v4l2_format *f) +{ + struct avd_comp comp; + + return avd_try_decoded_fmt(file_to_ctx(file), f, &comp); +} +EXPORT_SYMBOL_IF_KUNIT(avd_try_capture_fmt); + static int avd_try_output_fmt(struct file *file, void *priv, struct v4l2_format *f) { @@ -627,10 +642,11 @@ static int avd_try_output_fmt(struct file *file, void *priv, return 0; } -static int avd_s_capture_fmt(struct file *file, void *priv, - struct v4l2_format *f) +VISIBLE_IF_KUNIT int avd_s_capture_fmt(struct file *file, void *priv, + struct v4l2_format *f) { struct avd_ctx *ctx = file_to_ctx(file); + struct avd_comp comp; struct vb2_queue *vq; int ret; @@ -640,13 +656,15 @@ static int avd_s_capture_fmt(struct file *file, void *priv, if (vb2_is_busy(vq)) return -EBUSY; - ret = avd_try_capture_fmt(file, priv, f); + ret = avd_try_decoded_fmt(ctx, f, &comp); if (ret) return ret; ctx->decoded_fmt = *f; + ctx->comp = comp; return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_s_capture_fmt); static int avd_s_output_fmt(struct file *file, void *priv, struct v4l2_format *f) diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 45469d512e3cdb..45e2da9edbe365 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -393,6 +393,8 @@ int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, unsigned int tile_cols, const struct v4l2_ctrl_av1_tile_group_entry *tile_group, unsigned int entries, size_t payload); +int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); +int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, u32 *offset, u32 *size); From 88bd419f6593f58c054df8d7575095872aa5a7b6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:16:25 +1100 Subject: [PATCH 0589/1514] media: apple: avd: h264: Check the SPS picture size against the format The picture size the hardware is programmed with comes from the SPS (pic_width_in_mbs_minus1, pic_height_in_map_units_minus1), while the CAPTURE buffers, the compressed reference and motion vector areas in them, and the per-row scratch are sized from the OUTPUT format. avd_h264_validate_sps() did not compare the two, so a picture larger than the negotiated format was decoded into buffers too small for it. Refuse an SPS whose picture (H.264 7.4.2.1.1: PicWidthInMbs by FrameHeightInMbs macroblocks) is larger than the OUTPUT format, as the HEVC SPS check does. S_FMT(OUTPUT) rounds the format up to whole macroblocks, so a 1920x1080 stream with its 1088 line coded picture still fits. The check applies when the control is set, at STREAMON and again when a request's controls are applied at run time. Add a KUnit test for pictures that fit, including 1080p with the OUTPUT format set to 1920x1080 or 1920x1088, and for pictures that are one macroblock or more too large. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-h264-test.c | 54 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 19 ++++++- drivers/media/platform/apple/avd/avd.h | 2 + 3 files changed, 73 insertions(+), 2 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index 54d2114f45e98d..bdeb90594b1d5d 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -5,6 +5,7 @@ #include #include +#include #include "avd.h" @@ -107,6 +108,58 @@ static void avd_slice_fits_test(struct kunit *test) c->fits); } +/* The H.264 OUTPUT frame size limits in avd-v4l2.c */ +static const struct v4l2_frmsize_stepwise avd_test_h264_frmsize = { + .min_width = 64, .max_width = 4096, .step_width = 64, + .min_height = 64, .max_height = 4096, .step_height = 16, +}; + +struct avd_sps_size_case { + const char *desc; + /* OUTPUT format as the client asks for it */ + u32 width; + u32 height; + u16 width_mbs; + u16 height_map_units; + int ret; +}; + +static const struct avd_sps_size_case avd_sps_size_cases[] = { + { "1080p, OUTPUT 1920x1080", 1920, 1080, 120, 68, 0 }, + { "1080p, OUTPUT 1920x1088", 1920, 1088, 120, 68, 0 }, + { "720p", 1280, 720, 80, 45, 0 }, + { "720p, one row over", 1280, 720, 80, 46, -EINVAL }, + { "720p, one column over", 1280, 720, 81, 45, -EINVAL }, + { "picture smaller than the format", 1920, 1088, 40, 30, 0 }, + { "64x64, matching picture", 64, 64, 4, 4, 0 }, + { "64x64, 4096x4096 picture", 64, 64, 256, 256, -EINVAL }, + { "64x64, largest SPS size", 64, 64, U16_MAX, U16_MAX, -EINVAL }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_sps_size, avd_sps_size_cases, desc); + +static void avd_sps_size_test(struct kunit *test) +{ + const struct avd_sps_size_case *c = test->param_value; + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = c->width_mbs - 1, + .pic_height_in_map_units_minus1 = c->height_map_units - 1, + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + struct avd_ctx *ctx; + u32 w = c->width, h = c->height; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + /* As S_FMT(OUTPUT) does */ + v4l2_apply_frmsize_constraints(&w, &h, &avd_test_h264_frmsize); + ctx->coded_fmt.fmt.pix_mp.width = w; + ctx->coded_fmt.fmt.pix_mp.height = h; + + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), c->ret); +} + static void avd_scaling_flat_test(struct kunit *test) { struct v4l2_ctrl_h264_pps pps = {}; @@ -134,6 +187,7 @@ static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE(avd_scaling_flat_test), KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), KUNIT_CASE_PARAM(avd_slice_fits_test, avd_slice_fits_gen_params), + KUNIT_CASE_PARAM(avd_sps_size_test, avd_sps_size_gen_params), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 6d2b4ff0643c30..66592f75dacb49 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -672,9 +672,23 @@ static int avd_h264_validate_slice(struct avd_ctx *ctx, return 0; } -static int avd_h264_validate_sps(struct avd_ctx *ctx, - const struct v4l2_ctrl_h264_sps *sps) +/* + * H.264 7.4.2.1.1: the picture is PicWidthInMbs macroblocks wide and + * FrameHeightInMbs = (2 - frame_mbs_only_flag) * PicHeightInMapUnits high. + * The decoded buffers and the per-row scratch are sized from the OUTPUT + * format, which S_FMT rounds up to whole macroblocks, so a picture must fit + * in it. + */ +VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps) { + u32 width = (sps->pic_width_in_mbs_minus1 + 1) * 16; + u32 height = (sps->pic_height_in_map_units_minus1 + 1) * 16 * + (sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY ? 1 : 2); + + if (width > ctx->coded_fmt.fmt.pix_mp.width || + height > ctx->coded_fmt.fmt.pix_mp.height) + return -EINVAL; if (sps->chroma_format_idc > 2) /* Only 4:0:0, 4:2:0 and 4:2:2 are supported */ return -EINVAL; @@ -697,6 +711,7 @@ static int avd_h264_validate_sps(struct avd_ctx *ctx, return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps); /* Free the slices held for one bank's picture. */ static void avd_h264_drop_bank_slices(struct avd_ctx *ctx, struct avd_bank *bank) diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 45e2da9edbe365..bb6e6c680f99cc 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -393,6 +393,8 @@ int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, unsigned int tile_cols, const struct v4l2_ctrl_av1_tile_group_entry *tile_group, unsigned int entries, size_t payload); +int avd_h264_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps); int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); From e91600dbdc8357b5c8ae73e771ef07bc34b0a995 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 22:56:07 +0100 Subject: [PATCH 0590/1514] drm/apple: iboot: leave the outputs to the DCPEXTs when iBoot lit nothing On the J873g, iBoot lights a display only on the back-right USB-C port, through the main DCP. With no monitor there it lit none in every boot seen, with HDMI alone too, so the comment that had the bootloader drive HDMI from the main DCP without a USB-C display is corrected. The main DCP was then never set up for a display: its SET_POWER never completes, on HDMI and on USB-C alike. The firmware sends nothing until the timeout, and the output stays black. The DCPEXTs start cold without trouble. The main DCP also probes first and powers the shared HDMI PHY. The DCPEXTs then see a source on it and never register the shared port, so the cold main DCP is the only HDMI candidate. Keep the main DCP unbound when the bootloader left it no display, as DCPEXT0 already is when HDMI is on the main DCP. The shared HDMI port and the USB-C displays then go to the DCPEXTs, so such a boot runs on two display controllers for HDMI and the three USB-C ports. Evict simpledrm from the bootloader's framebuffers too: nothing scans them out, and each would show up as an extra output. When the main DCP has a display from the bootloader, nothing changes. The decision reads the state the bootloader leaves in the hardware. The main DCP has a display when the HDMI PHY's source select names it, or when a USB-C port has the link atc_port_init() adopts: powered, routed from the main DCP by the crossbar, its common block up. The checks are shared with atc_port_init(). A port in USB4 runs its common block the same way but routes from no DCP. The ports are read once, by the first DCP to probe and under the port claim lock, before any DCP claims or powers one, so a deferred main DCP still gets the bootloader's state. Where a port cannot be read, the main DCP binds as before. The boot arguments cannot tell the cases apart: the video block's display flag is 1 when iBoot lit nothing as well, and /chosen then only differs by the size of iBoot's placeholder surface, which no firmware interface defines. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/iomfb_iboot.c | 49 ++++++++++++- drivers/gpu/drm/apple/t8152_atc.c | 99 ++++++++++++++++++++++++--- drivers/gpu/drm/apple/t8152_display.h | 1 + 3 files changed, 135 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_iboot.c b/drivers/gpu/drm/apple/iomfb_iboot.c index 757b122dc8e42e..da23461b32f1e2 100644 --- a/drivers/gpu/drm/apple/iomfb_iboot.c +++ b/drivers/gpu/drm/apple/iomfb_iboot.c @@ -135,6 +135,27 @@ static const struct apple_rtkit_ops dcp_iboot_rtkit_ops = { .syslog_is_debug = dcp_iboot_rtk_syslog_debug, }; +/* + * Nothing scans out the bootloader's framebuffers while the main DCP stays + * off: drop the simpledrm devices on them, outputs that would show nothing. + * This detaches a simpledrm that is bound already, as the built-in one is + * long before this probe; one loaded later would bind again. + */ +static void dcp_iboot_drop_boot_fbs(void) +{ + struct device_node *chosen __free(device_node) = of_find_node_by_path("/chosen"); + + for_each_child_of_node_scoped(chosen, np) { + struct resource res; + + if (!of_device_is_compatible(np, "simple-framebuffer") || + of_address_to_resource(np, 0, &res)) + continue; + aperture_remove_conflicting_devices(res.start, resource_size(&res), + dcp_iboot_driver_name()); + } +} + static bool dcp_iboot_handoff_quiesced(struct dcp_iboot *ib) { struct device_node *chosen __free(device_node) = of_find_node_by_path("/chosen"); @@ -708,17 +729,23 @@ static int dcp_iboot_start(struct dcp_iboot *ib) } /* - * Without a USB-C display the bootloader drives HDMI from the main DCP - * (source 0) and never starts DCPEXT0. hdmi_np: DCPEXT0's node, which - * describes the HDMI PHY. + * hdmi_np: DCPEXT0's node, which describes the HDMI PHY; its source select + * names the DCP driving HDMI (0 the main DCP, 1 DCPEXT0). On the J873g, + * iBoot lights only a monitor on the back-right port, through the main DCP, + * and leaves HDMI to the kernel even when HDMI is the only display. A + * source a bootloader did set is still adopted. */ int dcp_iboot_probe(struct apple_dcp *dcp) { struct device *dev = dcp->dev; + /* Read by whichever DCP probes first, before any DCP drives a port. */ + int boot_link = t8152_atc_boot_link(dev); struct device_node *hdmi_np __free(device_node) = t8152_hdmi_node(); int source = hdmi_np ? t8152_hdmi_source(hdmi_np) : -ENODEV; struct t8152_display *disp; struct dcp_iboot *ib; + u32 dp_source = 0; + bool main_dcp; u32 live; int ret; @@ -729,6 +756,22 @@ int dcp_iboot_probe(struct apple_dcp *dcp) return -ENODEV; } + /* + * A main DCP that the bootloader left without a display cannot power + * one: its SET_POWER never completes, on HDMI or USB-C. It has one + * when it drives HDMI or the bootloader's link on a USB-C port; none + * when iBoot found no monitor on back-right, with HDMI alone too. Then + * leave its outputs to the DCPEXTs, which start cold, and the shared + * HDMI port with them. If the ports could not be read, bind as before. + */ + of_property_read_u32(dev->of_node, "apple,dp-source", &dp_source); + main_dcp = dev->of_node != hdmi_np && !dp_source; + if (main_dcp && source != 0 && boot_link == 0) { + dcp_iboot_drop_boot_fbs(); + dev_info(dev, "no display from the bootloader: main DCP off, the DCPEXTs drive the outputs\n"); + return -ENODEV; + } + /* * The bootloader's AFK endpoint hand-off: without it there is no * telling whether an endpoint is live, and an INIT on a live one diff --git a/drivers/gpu/drm/apple/t8152_atc.c b/drivers/gpu/drm/apple/t8152_atc.c index ce4b6a84602de1..633bfd9d02d0c5 100644 --- a/drivers/gpu/drm/apple/t8152_atc.c +++ b/drivers/gpu/drm/apple/t8152_atc.c @@ -84,6 +84,9 @@ struct t8152_atc { /* J873 has one display crossbar. Claims outlive firmware PHY power cycles. */ static DEFINE_MUTEX(atc_owner_lock); static struct device *atc_owner[4]; +/* The bootloader's link from the main DCP, read once: t8152_atc_boot_link(). */ +static bool atc_boot_read; +static int atc_boot_link; /* All three DCPs borrow the same AP AUX controller for EDID reads. */ static DEFINE_MUTEX(atc_aux_lock); @@ -785,6 +788,27 @@ static void __iomem *atc_map(struct t8152_display *disp, struct device_node *np, return devm_ioremap(disp->dev, res.start, resource_size(&res)); } +/* + * The PHY block hangs the bus while it is power-gated: look at it only with + * its DP dependencies and the common PSD up. + */ +static bool atc_powered(void __iomem *ps, void __iomem *psd) +{ + return (readl(ps) & 0xf0) == 0xf0 && !(readl(psd + ATC_PSD_STATE) & 7); +} + +/* The crossbar routes the port from the DCP with this dp-source. */ +static bool atc_routed(void __iomem *base, u32 dp_source) +{ + return ((readl(base + ATC_XBAR + 0x44) >> 20) & 0xf) == dp_source * 2; +} + +/* Common block out of reset and AUX up, as the bootloader leaves a link. */ +static bool atc_link_up(u32 cfg) +{ + return (cfg & 0x1f) == 0x1b; +} + static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, struct device_node *np, void __iomem *dp_clock) { @@ -817,23 +841,15 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, port->tunable_len[1] /= sizeof(__be32); atc->nports++; - /* - * The PHY block hangs the bus while it is power-gated: look at it only - * with its DP dependencies and the common PSD up. - */ - if ((readl(port->ps) & 0xf0) != 0xf0 || - (readl(port->psd + ATC_PSD_STATE) & 7)) { + if (!atc_powered(port->ps, port->psd)) { dev_info(disp->dev, "ATC%u: powered down\n", port->index); return 0; } /* A different DCP may already be driving this port. */ - if (atc_owner[port->index] || - ((readl(port->base + ATC_XBAR + 0x44) >> 20) & 0xf) != - disp->dp_source * 2) + if (atc_owner[port->index] || !atc_routed(port->base, disp->dp_source)) return 0; - /* Common block out of reset and AUX up, as the bootloader leaves it. */ cfg = readl(port->base + ATC_CFG); - port->active = (cfg & 0x1f) == 0x1b; + port->active = atc_link_up(cfg); if ((readl(port->base + 0x4c) & 0x1f) == 0x10 || (readl(port->base + 0x4c) & 0x1f) == 0x11) { port->lanes = 2; @@ -857,6 +873,67 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, return 0; } +static void __iomem *atc_iomap(struct device_node *np, const char *name) +{ + int i = of_property_match_string(np, "reg-names", name); + + return i < 0 ? NULL : of_iomap(np, i); +} + +/* 1 with a bootloader link from this dp-source, 0 without, or an error. */ +static int atc_port_boot_link(struct device_node *np, u32 dp_source) +{ + void __iomem *base = atc_iomap(np, "atc"); + void __iomem *ps = atc_iomap(np, "atc-ps"); + void __iomem *psd = atc_iomap(np, "atc-psd"); + int ret = -ENODEV; + + /* What atc_port_init() adopts. A port in USB4 routes from no DCP. */ + if (base && ps && psd) + ret = atc_powered(ps, psd) && atc_routed(base, dp_source) && + atc_link_up(readl(base + ATC_CFG)); + if (psd) + iounmap(psd); + if (ps) + iounmap(ps); + if (base) + iounmap(base); + return ret; +} + +/* + * 1 when the bootloader left a DisplayPort link from the main DCP + * (dp-source 0) on one of the USB-C ports, 0 when every port was read and + * none has one, an error when a port could not be read. The DCPs share the + * ports (the DCPEXTs' apple,usb-c-ports name the main DCP), so the first DCP + * to probe reads them, before any DCP claims or powers one, and the others + * get its answer. + */ +int t8152_atc_boot_link(struct device *dev) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: dev->of_node; + bool children = false; + + guard(mutex)(&atc_owner_lock); + if (atc_boot_read) + return atc_boot_link; + atc_boot_read = true; + atc_boot_link = 0; + for_each_child_of_node_scoped(np, child) { + if (!of_property_present(child, "apple,dfp-endpoint")) + continue; + children = true; + atc_boot_link = atc_port_boot_link(child, 0); + if (atc_boot_link) + break; + } + if (!children) + atc_boot_link = atc_port_boot_link(np, 0); + return atc_boot_link; +} + int t8152_atc_init(struct t8152_display *disp) { struct device_node *ports __free(device_node) = diff --git a/drivers/gpu/drm/apple/t8152_display.h b/drivers/gpu/drm/apple/t8152_display.h index b26baf6b04924f..3e1cc9d7008b98 100644 --- a/drivers/gpu/drm/apple/t8152_display.h +++ b/drivers/gpu/drm/apple/t8152_display.h @@ -109,6 +109,7 @@ struct t8152_display { }; /* t8152_atc.c */ +int t8152_atc_boot_link(struct device *dev); int t8152_atc_init(struct t8152_display *disp); bool t8152_atc_release(struct t8152_display *disp); From 74837459057b4305a5cf0da5c68cee1a9f9a3453 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:14:34 +1100 Subject: [PATCH 0591/1514] media: apple: avd: vp9: refuse frames larger than the coded format avd_vp9_alloc_bufs() sizes the per-row and per-column scratch (color, ip_above, lf_above, seg, lf_left, az_left, above_info, ...) at STREAMON from the OUTPUT format. validate_dec_params() ties the frame size only to the CAPTURE format, which avd_try_capture_fmt() lets be larger than the coded size and which can be changed while OUTPUT streams, so a frame can be larger than the scratch was sized for. Also require the frame to fit the coded format, which cannot change while the scratch exists, as HEVC does for its SPS. Clients set the coded format to the stream size, and the CAPTURE format is at least the coded size, so conformant streams are not affected. Add a KUnit test for the size check. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-vp9-test.c | 30 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-vp9.c | 17 +++++++++++ drivers/media/platform/apple/avd/avd.h | 2 ++ 3 files changed, 49 insertions(+) diff --git a/drivers/media/platform/apple/avd/avd-vp9-test.c b/drivers/media/platform/apple/avd/avd-vp9-test.c index f0b501dffde176..4e0bcd09ed31c6 100644 --- a/drivers/media/platform/apple/avd/avd-vp9-test.c +++ b/drivers/media/platform/apple/avd/avd-vp9-test.c @@ -125,7 +125,37 @@ static void avd_vp9_tiles_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ret, c->ret); } +/* The frame size against a 1920x1088 coded format. */ +static void avd_vp9_frame_fits_test(struct kunit *test) +{ + struct v4l2_ctrl_vp9_frame frame = { + .frame_width_minus_1 = 1919, + .frame_height_minus_1 = 1079, + }; + + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_height_minus_1 = 1087; + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 959; + frame.frame_height_minus_1 = 539; + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + + frame.frame_width_minus_1 = 1920; + frame.frame_height_minus_1 = 1079; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 1919; + frame.frame_height_minus_1 = 1088; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 1920, 1088)); + frame.frame_width_minus_1 = 4095; + frame.frame_height_minus_1 = 2175; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 64, 64)); + frame.frame_width_minus_1 = 0xffff; + frame.frame_height_minus_1 = 0xffff; + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 4096, 4096)); +} + static struct kunit_case avd_vp9_test_cases[] = { + KUNIT_CASE(avd_vp9_frame_fits_test), KUNIT_CASE_PARAM(avd_vp9_tiling_test, avd_vp9_tiling_gen_params), KUNIT_CASE_PARAM(avd_vp9_tiles_test, avd_vp9_tiles_gen_params), {} diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index e72aeb8dc2c2fd..a0de2f7612f48d 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -698,6 +698,20 @@ static void init_probs(struct avd_ctx *ctx, const struct avd_vp9_run *run) sizeof(avd_probs->seg.tree_probs)); } +/* + * The row and column scratch is sized at STREAMON from the OUTPUT (coded) + * format, which cannot change while it streams. The CAPTURE format can be + * larger and can change meanwhile, so the frame must fit the coded size. + */ +VISIBLE_IF_KUNIT bool +avd_vp9_frame_fits(const struct v4l2_ctrl_vp9_frame *frame, u32 width, + u32 height) +{ + return frame->frame_width_minus_1 + 1 <= width && + frame->frame_height_minus_1 + 1 <= height; +} +EXPORT_SYMBOL_IF_KUNIT(avd_vp9_frame_fits); + static int validate_dec_params(struct avd_ctx *ctx, const struct v4l2_ctrl_vp9_frame *dec_params) { @@ -716,6 +730,9 @@ static int validate_dec_params(struct avd_ctx *ctx, dec_params->frame_height_minus_1 + 1 < 64)) return -EINVAL; + if (!avd_vp9_frame_fits(dec_params, fmt_width(ctx), fmt_height(ctx))) + return -EINVAL; + aligned_width = max_t(unsigned int, round_up(dec_params->frame_width_minus_1 + 1, 64), 64); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index bb6e6c680f99cc..e36f0d60c2d863 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -400,6 +400,8 @@ int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); int avd_vp9_next_tile(const u8 *data, u32 payload, bool last, u32 *offset, u32 *size); +bool avd_vp9_frame_fits(const struct v4l2_ctrl_vp9_frame *frame, u32 width, + u32 height); #endif extern const struct avd_coded_fmt_ops avd_h264_fmt_ops; From 83452e5df2aaa29adf0ae85383dc3a72071537ab Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:19:40 +1100 Subject: [PATCH 0592/1514] media: apple: avd: check the picture format against the buffers at run time The CAPTURE buffers, their compressed reference area and the per-context scratch are sized for ctx->image_fmt, but each codec programs the bit depth and chroma format from the current value of its format control (the H.264 or HEVC SPS, the VP9 frame, the AV1 sequence). The two were only compared in s_ctrl, which the control framework skips for an unchanged value and which ignores a control of a codec that is not selected, while an OUTPUT format change resets ctx->image_fmt and keeps the control. A job could then program, for example, a 10-bit picture into buffers sized for 8 bits. When a job is built, derive the picture format from the control value the job uses and refuse the job unless it is the one the buffers were sized for (ANY sizes them as 8-bit 4:2:0) and the negotiated CAPTURE format fits it. The format each codec derives is unchanged; get_image_fmt now shares it. Add KUnit cases for the check. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/Makefile | 2 +- drivers/media/platform/apple/avd/avd-av1.c | 21 +-- .../media/platform/apple/avd/avd-fmt-test.c | 128 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 37 +++-- drivers/media/platform/apple/avd/avd-hevc.c | 21 ++- drivers/media/platform/apple/avd/avd-v4l2.c | 26 ++++ drivers/media/platform/apple/avd/avd-vp9.c | 20 +-- drivers/media/platform/apple/avd/avd.h | 1 + 8 files changed, 216 insertions(+), 40 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-fmt-test.c diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index 926ebb1d8a73a6..f4e0864a52b0ef 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -5,5 +5,5 @@ apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ avd-queue-test.o avd-pm-test.o avd-hevc-test.o avd-job-test.o \ - avd-av1-test.o avd-v4l2-test.o avd-vp9-test.o + avd-fmt-test.o avd-av1-test.o avd-v4l2-test.o avd-vp9-test.o obj-$(CONFIG_VIDEO_APPLE_AVD) += apple-avd.o diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index c39c63adb4f089..851eebce2fee90 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -1448,6 +1448,14 @@ EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_tiles); * when the sequence is set and again when a frame runs, so it never * reaches the decoder. */ +static enum avd_image_fmt +avd_av1_seq_image_fmt(const struct v4l2_ctrl_av1_sequence *seq) +{ + /* avd_av1_validate_sequence() admits only Main profile 4:2:0. */ + return seq->bit_depth == 8 ? AVD_IMG_FMT_420_8BIT : + AVD_IMG_FMT_420_10BIT; +} + static int avd_av1_validate_sequence(struct avd_ctx *ctx, const struct v4l2_ctrl_av1_sequence *seq) { @@ -1482,6 +1490,9 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) /* The sequence may have been set, unchecked, while another codec was selected. */ ret = avd_av1_validate_sequence(ctx, run->seq); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_av1_seq_image_fmt(run->seq)); if (ret) return ret; @@ -1899,18 +1910,10 @@ static int avd_av1_start(struct avd_ctx *ctx) static enum avd_image_fmt avd_av1_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { -#define BIT_DEPTH(chroma) \ - (seq->bit_depth == 8 ? AVD_IMG_FMT_##chroma##_8BIT : \ - AVD_IMG_FMT_##chroma##_10BIT) - - const struct v4l2_ctrl_av1_sequence *seq = ctrl->p_new.p_av1_sequence; - if (ctrl->id != V4L2_CID_STATELESS_AV1_SEQUENCE) return AVD_IMG_FMT_ANY; - /* avd_av1_validate_sequence() admits only Main profile 4:2:0. */ - return BIT_DEPTH(420); -#undef BIT_DEPTH + return avd_av1_seq_image_fmt(ctrl->p_new.p_av1_sequence); } static unsigned int avd_av1_pp_kicks(struct avd_ctx *ctx) diff --git a/drivers/media/platform/apple/avd/avd-fmt-test.c b/drivers/media/platform/apple/avd/avd-fmt-test.c new file mode 100644 index 00000000000000..ca6ec6e4a8608a --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-fmt-test.c @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the run-time picture format check of the Apple video + * decoder. + */ + +#include +#include +#include + +#include "avd.h" + +static const struct avd_decoded_fmt_desc avd_fmt_test_decoded[] = { + { .fourcc = V4L2_PIX_FMT_NV12, .image_fmt = AVD_IMG_FMT_420_8BIT }, + { .fourcc = V4L2_PIX_FMT_P010, .image_fmt = AVD_IMG_FMT_420_10BIT }, + { .fourcc = V4L2_PIX_FMT_NV16, .image_fmt = AVD_IMG_FMT_422_8BIT }, +}; + +static const struct avd_coded_fmt_desc avd_fmt_test_desc = { + .num_decoded_fmts = ARRAY_SIZE(avd_fmt_test_decoded), + .decoded_fmts = avd_fmt_test_decoded, +}; + +/* A context whose CAPTURE format was negotiated for @sized as @fourcc. */ +static struct avd_ctx *avd_fmt_test_ctx(struct kunit *test, + enum avd_image_fmt sized, u32 fourcc) +{ + struct avd_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + struct avd_dev *avd = kunit_kzalloc(test, sizeof(*avd), GFP_KERNEL); + struct v4l2_pix_format_mplane *pix; + + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, avd); + avd->dev = kunit_device_register(test, "avd-fmt-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, avd->dev); + ctx->dev = avd; + ctx->coded_fmt_desc = &avd_fmt_test_desc; + ctx->image_fmt = sized; + pix = &ctx->decoded_fmt.fmt.pix_mp; + pix->pixelformat = fourcc; + pix->width = 64; + pix->height = 64; + fill_comp(&ctx->comp, sized, pix->width, pix->height); + return ctx; +} + +static void avd_fmt_any_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_ANY, + V4L2_PIX_FMT_NV12); + + /* Buffers sized for "any" are 8-bit 4:2:0. */ + KUNIT_EXPECT_EQ(test, avd_check_run_image_fmt(ctx, AVD_IMG_FMT_ANY), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_8BIT), + -EINVAL); +} + +/* "Any" with a 10-bit CAPTURE fourcc still has 8-bit sized storage. */ +static void avd_fmt_any_p010_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_ANY, + V4L2_PIX_FMT_P010); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); +} + +static void avd_fmt_10bit_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_10BIT, + V4L2_PIX_FMT_P010); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); +} + +static void avd_fmt_422_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_422_8BIT, + V4L2_PIX_FMT_NV16); + + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_8BIT), 0); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_422_10BIT), + -EINVAL); +} + +/* Compressed storage laid out for another size does not fit either. */ +static void avd_fmt_comp_mismatch_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_8BIT, + V4L2_PIX_FMT_NV12); + + fill_comp(&ctx->comp, AVD_IMG_FMT_420_8BIT, 32, 32); + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_8BIT), + -EINVAL); +} + +static struct kunit_case avd_fmt_test_cases[] = { + KUNIT_CASE(avd_fmt_any_test), + KUNIT_CASE(avd_fmt_any_p010_test), + KUNIT_CASE(avd_fmt_10bit_test), + KUNIT_CASE(avd_fmt_422_test), + KUNIT_CASE(avd_fmt_comp_mismatch_test), + {} +}; + +static struct kunit_suite avd_fmt_test_suite = { + .name = "apple-avd-fmt", + .test_cases = avd_fmt_test_cases, +}; + +kunit_test_suite(avd_fmt_test_suite); diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 66592f75dacb49..940412dd6c020f 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -672,6 +672,24 @@ static int avd_h264_validate_slice(struct avd_ctx *ctx, return 0; } +static enum avd_image_fmt +avd_h264_sps_image_fmt(const struct v4l2_ctrl_h264_sps *sps) +{ + if (sps->bit_depth_luma_minus8 == 0) { + if (sps->chroma_format_idc == 2) + return AVD_IMG_FMT_422_8BIT; + else + return AVD_IMG_FMT_420_8BIT; + } else if (sps->bit_depth_luma_minus8 == 2) { + if (sps->chroma_format_idc == 2) + return AVD_IMG_FMT_422_10BIT; + else + return AVD_IMG_FMT_420_10BIT; + } + + return AVD_IMG_FMT_ANY; +} + /* * H.264 7.4.2.1.1: the picture is PicWidthInMbs macroblocks wide and * FrameHeightInMbs = (2 - frame_mbs_only_flag) * PicHeightInMapUnits high. @@ -1024,6 +1042,9 @@ static int avd_h264_run(struct avd_ctx *ctx) /* Recheck controls applied from this request before building instructions. */ ret = avd_h264_validate_sps(ctx, run.sps); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_h264_sps_image_fmt(run.sps)); if (!ret) ret = avd_h264_validate_pps(ctx, run.pps); if (!ret) @@ -1182,24 +1203,10 @@ static void avd_h264_done(struct avd_ctx *ctx, struct vb2_v4l2_buffer *src_buf, static enum avd_image_fmt avd_h264_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - const struct v4l2_ctrl_h264_sps *sps = ctrl->p_new.p_h264_sps; - if (ctrl->id != V4L2_CID_STATELESS_H264_SPS) return AVD_IMG_FMT_ANY; - if (sps->bit_depth_luma_minus8 == 0) { - if (sps->chroma_format_idc == 2) - return AVD_IMG_FMT_422_8BIT; - else - return AVD_IMG_FMT_420_8BIT; - } else if (sps->bit_depth_luma_minus8 == 2) { - if (sps->chroma_format_idc == 2) - return AVD_IMG_FMT_422_10BIT; - else - return AVD_IMG_FMT_420_10BIT; - } - - return AVD_IMG_FMT_ANY; + return avd_h264_sps_image_fmt(ctrl->p_new.p_h264_sps); } static void avd_h264_adjust_decoded_fmt(struct avd_ctx *ctx, diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 1f283c2058e3ad..21c74fc6538694 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -1038,14 +1038,9 @@ static void avd_hevc_adjust_decoded_fmt(struct avd_ctx *ctx, mv_color_size(pix_mp->width, pix_mp->height); } -static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, - struct v4l2_ctrl *ctrl) +static enum avd_image_fmt +avd_hevc_sps_image_fmt(const struct v4l2_ctrl_hevc_sps *sps) { - const struct v4l2_ctrl_hevc_sps *sps = ctrl->p_new.p_hevc_sps; - - if (ctrl->id != V4L2_CID_STATELESS_HEVC_SPS) - return AVD_IMG_FMT_ANY; - /* avd_hevc_validate_sps() refuses 4:4:4 and depths other than 8/10. */ if (sps->bit_depth_luma_minus8 == 0) { if (sps->chroma_format_idc == 2) @@ -1062,6 +1057,15 @@ static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, return AVD_IMG_FMT_ANY; } +static enum avd_image_fmt avd_hevc_get_image_fmt(struct avd_ctx *ctx, + struct v4l2_ctrl *ctrl) +{ + if (ctrl->id != V4L2_CID_STATELESS_HEVC_SPS) + return AVD_IMG_FMT_ANY; + + return avd_hevc_sps_image_fmt(ctrl->p_new.p_hevc_sps); +} + /* * The picture must have at least one sample in each direction and the CTB * size must be one of those H.265 allows (CtbLog2SizeY 4 to 6, 7.4.3.2.1): @@ -1690,6 +1694,9 @@ static int avd_hevc_run(struct avd_ctx *ctx) /* Also validate controls applied from a queued request before submission. */ ret = avd_hevc_validate_sps(ctx, run.sps); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_hevc_sps_image_fmt(run.sps)); if (ret) goto complete; diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 5aabdefffc38d6..b540eb551a6b04 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -66,6 +66,32 @@ static bool avd_image_fmt_fits_capture(struct avd_ctx *ctx, !memcmp(comp.offsets, ctx->comp.offsets, sizeof(comp.offsets)); } +/* + * Whether a job may program @image_fmt, the picture format that the current + * value of the codec's format control describes. The CAPTURE buffers and the + * per-context scratch were sized for ctx->image_fmt (ANY sizes them as 8-bit + * 4:2:0), and the control's value can differ from it: it may have been set + * while another codec was selected, or kept over an OUTPUT format change, and + * an unchanged value never reaches s_ctrl. Refuse the job unless both are the + * same and the CAPTURE buffers fit it. + */ +int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt) +{ + enum avd_image_fmt sized = ctx->image_fmt; + + if (sized == AVD_IMG_FMT_ANY) + sized = AVD_IMG_FMT_420_8BIT; + if (image_fmt == AVD_IMG_FMT_ANY) + image_fmt = AVD_IMG_FMT_420_8BIT; + if (image_fmt != sized || !avd_image_fmt_fits_capture(ctx, image_fmt)) { + dev_dbg_ratelimited(ctx->dev->dev, + "picture format %d does not fit the buffers (%d)\n", + image_fmt, ctx->image_fmt); + return -EINVAL; + } + return 0; +} + static u32 avd_enum_decoded_fmt(struct avd_ctx *ctx, int index, enum avd_image_fmt image_fmt) { diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index a0de2f7612f48d..09f85671691091 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -698,6 +698,14 @@ static void init_probs(struct avd_ctx *ctx, const struct avd_vp9_run *run) sizeof(avd_probs->seg.tree_probs)); } +static enum avd_image_fmt +avd_vp9_frame_image_fmt(const struct v4l2_ctrl_vp9_frame *frame) +{ + /* avd_vp9_try_ctrl() admits only 4:2:0 (profiles 0 and 2). */ + return frame->bit_depth == 8 ? AVD_IMG_FMT_420_8BIT : + AVD_IMG_FMT_420_10BIT; +} + /* * The row and column scratch is sized at STREAMON from the OUTPUT (coded) * format, which cannot change while it streams. The CAPTURE format can be @@ -921,6 +929,9 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) /* The frame may have been set, unchecked, while another codec was selected. */ ret = avd_vp9_validate_frame(ctx, dec_params); + if (!ret) + ret = avd_check_run_image_fmt(ctx, + avd_vp9_frame_image_fmt(dec_params)); if (ret) return ret; @@ -1286,17 +1297,10 @@ static int avd_vp9_start(struct avd_ctx *ctx) static enum avd_image_fmt avd_vp9_get_image_fmt(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { -#define BIT_DEPTH(chroma) \ - (frame->bit_depth == 8 ? AVD_IMG_FMT_##chroma##_8BIT : \ - AVD_IMG_FMT_##chroma##_10BIT) - const struct v4l2_ctrl_vp9_frame *frame = ctrl->p_new.p_vp9_frame; - if (ctrl->id != V4L2_CID_STATELESS_VP9_FRAME) return AVD_IMG_FMT_ANY; - /* avd_vp9_try_ctrl() admits only 4:2:0 (profiles 0 and 2). */ - return BIT_DEPTH(420); -#undef BIT_DEPTH + return avd_vp9_frame_image_fmt(ctrl->p_new.p_vp9_frame); } static int avd_vp9_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index e36f0d60c2d863..7b1b6992b9621a 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -368,6 +368,7 @@ void avd_job_finish_no_pm(struct avd_ctx *ctx, enum vb2_buffer_state result); void avd_job_finish(struct avd_ctx *ctx, enum vb2_buffer_state result); void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run); +int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt); void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run); #if IS_ENABLED(CONFIG_KUNIT) From 4f35e8c1859a7a940b1f700da9c21f7ac45dd419 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:12:51 +1100 Subject: [PATCH 0593/1514] media: apple: avd: av1: copy the tile-group entries for the run V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY is a dynamic array. Setting a larger array through VIDIOC_S_EXT_CTRLS reallocates the control's storage and frees the old one under the control lock, but the run kept ctrl->p_cur.p and ctrl->elems and read the entries without that lock, in avd_av1_check_tiles() and again later in set_tiles(). The entries used to build the tiles could therefore be freed memory, or differ from the ones that were checked. Copy the entries and their count under v4l2_ctrl_lock(), as the HEVC code does for its dynamic arrays, check the copy and build the tiles from it, and free it on every exit of avd_av1_run(). Also take the tile grid (tile_rows, tile_cols) from the frame control once and use that same grid for the check, the job size and set_tiles(), so the number of entries read can not exceed the number that was checked if the frame control is set at the same time. Add a KUnit test that the copy holds the entries and count after the control's storage has been replaced and freed. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-av1-test.c | 62 +++++++++++++++++ drivers/media/platform/apple/avd/avd-av1.c | 69 ++++++++++++++----- drivers/media/platform/apple/avd/avd.h | 2 + 3 files changed, 114 insertions(+), 19 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-av1-test.c b/drivers/media/platform/apple/avd/avd-av1-test.c index 33ad22165ce79e..34768e5877ff8d 100644 --- a/drivers/media/platform/apple/avd/avd-av1-test.c +++ b/drivers/media/platform/apple/avd/avd-av1-test.c @@ -4,6 +4,7 @@ */ #include +#include #include "avd.h" @@ -110,11 +111,72 @@ static void avd_av1_tiles_rowcol_test(struct kunit *test) AVD_TEST_PAYLOAD), c->ret); } +/* + * The run takes its own copy of the tile-group entries: replacing and freeing + * the control's storage afterwards, as setting a larger array does, leaves + * the copy and its count intact. + */ +static void avd_av1_copy_tile_group_test(struct kunit *test) +{ + struct v4l2_ctrl_av1_tile_group_entry expect[6] = {}; + struct v4l2_ctrl_av1_tile_group_entry *src, *bigger, *copy; + struct v4l2_ctrl_handler *hdl; + struct v4l2_ctrl *ctrl; + unsigned int entries = 0; + + hdl = kunit_kzalloc(test, sizeof(*hdl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, hdl); + ctrl = kunit_kzalloc(test, sizeof(*ctrl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + KUNIT_ASSERT_EQ(test, v4l2_ctrl_handler_init(hdl, 0), 0); + + src = kcalloc(ARRAY_SIZE(expect), sizeof(*src), GFP_KERNEL); + bigger = kcalloc(V4L2_AV1_MAX_TILE_COUNT, sizeof(*bigger), GFP_KERNEL); + if (!src || !bigger) { + kfree(src); + kfree(bigger); + v4l2_ctrl_handler_free(hdl); + KUNIT_FAIL(test, "out of memory"); + return; + } + avd_av1_test_layout(expect, 2, 3); + memcpy(src, expect, sizeof(expect)); + ctrl->handler = hdl; + ctrl->elems = ARRAY_SIZE(expect); + ctrl->elem_size = sizeof(*src); + ctrl->p_cur.p = src; + + copy = avd_av1_copy_tile_group(ctrl, &entries); + KUNIT_EXPECT_EQ(test, entries, ARRAY_SIZE(expect)); + + /* A larger array replaces and frees the old storage. */ + memset(bigger, 0xff, V4L2_AV1_MAX_TILE_COUNT * sizeof(*bigger)); + ctrl->p_cur.p = bigger; + ctrl->elems = V4L2_AV1_MAX_TILE_COUNT; + memset(src, 0xff, sizeof(expect)); + kfree(src); + + if (copy) { + KUNIT_EXPECT_MEMEQ(test, copy, expect, sizeof(expect)); + KUNIT_EXPECT_EQ(test, avd_av1_check_tiles(NULL, 2, 3, copy, + entries, + AVD_TEST_PAYLOAD), 0); + } else { + KUNIT_FAIL(test, "no copy"); + } + KUNIT_EXPECT_EQ(test, entries, ARRAY_SIZE(expect)); + + kfree(copy); + kfree(bigger); + v4l2_ctrl_handler_free(hdl); +} + static struct kunit_case avd_av1_test_cases[] = { KUNIT_CASE(avd_av1_tiles_valid_test), KUNIT_CASE(avd_av1_tiles_count_test), KUNIT_CASE(avd_av1_tiles_extent_test), KUNIT_CASE_PARAM(avd_av1_tiles_rowcol_test, avd_av1_rowcol_gen_params), + KUNIT_CASE(avd_av1_copy_tile_group_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index 851eebce2fee90..1bbf54f9b83aa3 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -221,7 +221,12 @@ struct avd_av1_run { const struct v4l2_ctrl_av1_sequence *seq; const struct v4l2_ctrl_av1_frame *frame; - const struct v4l2_ctrl_av1_tile_group_entry *tile_group; + /* Private copy of the tile-group control, freed by avd_av1_run(). */ + struct v4l2_ctrl_av1_tile_group_entry *tile_group; + unsigned int tile_group_entries; + /* The tile grid tile_group was checked against */ + unsigned int tile_rows; + unsigned int tile_cols; const struct v4l2_ctrl_av1_film_grain *grain; }; @@ -1139,12 +1144,12 @@ static void set_tiles(struct avd_ctx *ctx, struct avd_av1_run *run) seq->flags & V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK ? 5 : 4; - av1_ctx->submit_num = tile_info->tile_cols * tile_info->tile_rows; + av1_ctx->submit_num = run->tile_cols * run->tile_rows; - for (row = 0; row < tile_info->tile_rows; row++) { - for (col = 0; col < tile_info->tile_cols; col++) { + for (row = 0; row < run->tile_rows; row++) { + for (col = 0; col < run->tile_cols; col++) { ctx->job.num++; - tile_id = row * tile_info->tile_cols + col; + tile_id = row * run->tile_cols + col; tile_group = &run->tile_group[tile_id]; push(AVD_OP_CODED_DATA | @@ -1440,6 +1445,25 @@ avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, } EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_tiles); +/* + * Setting a larger tile-group array reallocates the control's storage and + * frees the old one under the control lock, which the run does not otherwise + * hold. Copy the entries under that lock; the run checks and uses the copy. + */ +VISIBLE_IF_KUNIT struct v4l2_ctrl_av1_tile_group_entry * +avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries) +{ + struct v4l2_ctrl_av1_tile_group_entry *copy; + + v4l2_ctrl_lock(ctrl); + *entries = ctrl->elems; + copy = kmemdup_array(ctrl->p_cur.p, ctrl->elems, ctrl->elem_size, + GFP_KERNEL); + v4l2_ctrl_unlock(ctrl); + return copy; +} +EXPORT_SYMBOL_IF_KUNIT(avd_av1_copy_tile_group); + /* * Only the AV1 Main profile at 4:2:0 (8 and 10 bits) decodes. A High * profile (4:4:4) frame is never completed: it times out and the whole @@ -1523,10 +1547,14 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY); if (WARN_ON(!ctrl)) return -EINVAL; - run->tile_group = ctrl->p_cur.p; - ret = avd_av1_check_tiles(ctx->dev->dev, run->frame->tile_info.tile_rows, - run->frame->tile_info.tile_cols, - run->tile_group, ctrl->elems, + run->tile_group = avd_av1_copy_tile_group(ctrl, &run->tile_group_entries); + if (!run->tile_group) + return -ENOMEM; + /* The frame control can be set meanwhile too: use one tile grid throughout. */ + run->tile_rows = run->frame->tile_info.tile_rows; + run->tile_cols = run->frame->tile_info.tile_cols; + ret = avd_av1_check_tiles(ctx->dev->dev, run->tile_rows, run->tile_cols, + run->tile_group, run->tile_group_entries, vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0)); if (ret) return ret; @@ -1694,7 +1722,7 @@ static int avd_av1_alloc_work_bufs(struct avd_ctx *ctx, struct avd_av1_run *run) static int avd_av1_run(struct avd_ctx *ctx) { - struct avd_av1_run run; + struct avd_av1_run run = {}; struct avd_av1_stream *av1_ctx = ((struct avd_av1_ctx *)ctx->priv)->stream; struct avd_decoded_buffer *dst, *ref; int ret; @@ -1702,7 +1730,7 @@ static int avd_av1_run(struct avd_ctx *ctx) ret = avd_av1_run_preamble(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } /* The CDF and segmentation map copies need the CPU mappings. */ @@ -1716,7 +1744,8 @@ static int avd_av1_run(struct avd_ctx *ctx) if (!vb2_plane_vaddr(&dst->base.vb.vb2_buf, 0) || !vb2_plane_vaddr(&ref->base.vb.vb2_buf, 0)) { avd_run_postamble(ctx, &run.base); - return -ENOMEM; + ret = -ENOMEM; + goto out; } if (av1_ctx->nbanks > 1) { struct avd_av1_bank *bank = NULL; @@ -1728,7 +1757,8 @@ static int avd_av1_run(struct avd_ctx *ctx) } if (!bank) { avd_run_postamble(ctx, &run.base); - return -EBUSY; + ret = -EBUSY; + goto out; } av1_ctx->b = bank; smp_store_release(&ctx->priv, &bank->codec); @@ -1743,18 +1773,16 @@ static int avd_av1_run(struct avd_ctx *ctx) } ret = avd_init_job(ctx, AVD_CODEC_AV1, - run.frame->tile_info.tile_cols * - run.frame->tile_info.tile_rows + - 1); + run.tile_cols * run.tile_rows + 1); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } ret = avd_av1_alloc_work_bufs(ctx, &run); if (ret) { avd_run_postamble(ctx, &run.base); - return ret; + goto out; } update_dec_buf_info(dst, run.seq, run.frame); @@ -1771,7 +1799,10 @@ static int avd_av1_run(struct avd_ctx *ctx) avd_run_postamble(ctx, &run.base); - return avd_submit_job(ctx); + ret = avd_submit_job(ctx); +out: + kfree(run.tile_group); + return ret; } diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 7b1b6992b9621a..2f77cf975a9d0e 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -394,6 +394,8 @@ int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, unsigned int tile_cols, const struct v4l2_ctrl_av1_tile_group_entry *tile_group, unsigned int entries, size_t payload); +struct v4l2_ctrl_av1_tile_group_entry * +avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries); int avd_h264_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); From 9ffbad7fbea51c71a1d8b709a4485a2e846a371d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:16:35 +1100 Subject: [PATCH 0594/1514] media: apple: avd: h264: Bound the slice table made at STREAMON avd_h264_start() sized each bank's slice table, and through it the job table of the first picture, at one slice per row of the SPS, without the avd_h264_max_slices() limit the run path applies when the table grows. Take the smaller of the two, as avd_h264_realloc_slices() does. These tables and the codec context are allocated in the context of the STREAMON caller; charge them to it with GFP_KERNEL_ACCOUNT. Add a KUnit test that the initial count is one per row and never exceeds the slice table limit, whatever the SPS geometry. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-h264-test.c | 22 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 19 ++++++++++++---- drivers/media/platform/apple/avd/avd.h | 1 + 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index bdeb90594b1d5d..3b7fec1d7b51bf 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -160,6 +160,27 @@ static void avd_sps_size_test(struct kunit *test) KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), c->ret); } +static void avd_start_slices_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + + /* One slice per row */ + sps.pic_width_in_mbs_minus1 = 119; + sps.pic_height_in_map_units_minus1 = 67; + KUNIT_EXPECT_EQ(test, avd_h264_start_slices(&sps), 68); + + /* No more rows than macroblocks, and never more than the table */ + sps.pic_width_in_mbs_minus1 = 0; + sps.pic_height_in_map_units_minus1 = U16_MAX; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); + sps.pic_width_in_mbs_minus1 = U16_MAX; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); + sps.flags = 0; + KUNIT_EXPECT_LE(test, avd_h264_start_slices(&sps), AVD_TEST_MAX_SLICES); +} + static void avd_scaling_flat_test(struct kunit *test) { struct v4l2_ctrl_h264_pps pps = {}; @@ -188,6 +209,7 @@ static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), KUNIT_CASE_PARAM(avd_slice_fits_test, avd_slice_fits_gen_params), KUNIT_CASE_PARAM(avd_sps_size_test, avd_sps_size_gen_params), + KUNIT_CASE(avd_start_slices_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 940412dd6c020f..b5f87f6def9146 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -769,6 +769,9 @@ static void avd_h264_stop(struct avd_ctx *ctx) ctx->priv = NULL; } +VISIBLE_IF_KUNIT size_t +avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); + static int avd_h264_start(struct avd_ctx *ctx) { struct avd_h264_ctx *h264_ctx; @@ -783,7 +786,7 @@ static int avd_h264_start(struct avd_ctx *ctx) if (ret) return ret; - h264_ctx = kzalloc(sizeof(*h264_ctx), GFP_KERNEL); + h264_ctx = kzalloc(sizeof(*h264_ctx), GFP_KERNEL_ACCOUNT); if (!h264_ctx) return -ENOMEM; @@ -795,11 +798,10 @@ static int avd_h264_start(struct avd_ctx *ctx) for (unsigned int i = 0; i < h264_ctx->nbanks; i++) { struct avd_bank *bank = &h264_ctx->bank[i]; - /* assume one slice per row */ bank->alloc_slice_num = - ctrl->p_new.p_h264_sps->pic_height_in_map_units_minus1 + 1; + avd_h264_start_slices(ctrl->p_new.p_h264_sps); bank->slices = kcalloc(bank->alloc_slice_num, - sizeof(*bank->slices), GFP_KERNEL); + sizeof(*bank->slices), GFP_KERNEL_ACCOUNT); if (!bank->slices) { ret = -ENOMEM; goto err_free_ctx; @@ -956,6 +958,15 @@ static size_t avd_h264_max_slices(const struct v4l2_ctrl_h264_sps *sps) return min_t(size_t, mbs, MAX_SLICES); } +/* Slice table entries made at STREAMON: one slice per row to begin with. */ +VISIBLE_IF_KUNIT size_t +avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps) +{ + return min_t(size_t, sps->pic_height_in_map_units_minus1 + 1, + avd_h264_max_slices(sps)); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_start_slices); + /* * Coded data held for one picture. A picture of PCM macroblocks is about the * size of the decoded one and emulation prevention adds at most one byte for diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 2f77cf975a9d0e..54d9e8a48289b6 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -398,6 +398,7 @@ struct v4l2_ctrl_av1_tile_group_entry * avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries); int avd_h264_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); +size_t avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_vp9_check_tiling(const struct v4l2_ctrl_vp9_frame *frame); From b0471fb1fe907faed5897264752b1490ef130ae8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 08:16:35 +1100 Subject: [PATCH 0595/1514] media: apple: avd: Allocate the context FIFO at STREAMON Every open() allocated the context's 12 MB coherent instruction FIFO, although it is only handed to the hardware for frames, which run while the OUTPUT queue streams. Allocate it when OUTPUT starts streaming, before the codec's start(), and free it when OUTPUT stops, after the context's frames have been drained and the codec's own buffers freed. release() still frees it for a context closed while streaming. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-drv.c | 5 ----- drivers/media/platform/apple/avd/avd-v4l2.c | 11 ++++++++++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index c79379d2a50f25..c96a9e3b1c5716 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -190,10 +190,6 @@ static int avd_open(struct file *filp) ctx->dev = avd; - ret = avd_buf_alloc(avd, &ctx->inst, fifo_size()); - if (ret) - goto err_free_ctx; - INIT_LIST_HEAD(&ctx->queue_node); ctx->next_dep = AVD_DEP_PREV_DONE; @@ -221,7 +217,6 @@ static int avd_open(struct file *filp) v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); err_free_ctx: - avd_buf_free(avd, &ctx->inst); kfree(ctx); return ret; } diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index b540eb551a6b04..1cd84c6259d433 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -19,6 +19,7 @@ #include #include "avd.h" +#include "avd-inst.h" static bool avd_image_fmt_match(enum avd_image_fmt fmt1, enum avd_image_fmt fmt2) @@ -972,14 +973,21 @@ static int avd_start_streaming(struct vb2_queue *q, unsigned int count) goto err_return_buffers; } + /* The context's instruction FIFO is only used while OUTPUT streams. */ + ret = avd_buf_alloc(ctx->dev, &ctx->inst, fifo_size()); + if (ret) + goto err_return_buffers; + if (desc->ops->start) { ret = desc->ops->start(ctx); if (ret) - goto err_return_buffers; + goto err_free_inst; } return 0; +err_free_inst: + avd_buf_free(ctx->dev, &ctx->inst); err_return_buffers: /* Keep requests queued for a later STREAMON retry. */ while ((vbuf = v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx))) @@ -1021,6 +1029,7 @@ static void avd_stop_streaming(struct vb2_queue *q) if (desc->ops->stop) desc->ops->stop(ctx); + avd_buf_free(ctx->dev, &ctx->inst); /* Drop a job table left over from a frame that never finished. */ kvfree(ctx->job.segments); From e3ad16ebf95086ad77cec05075cef2bd0799fa7b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:52:06 +1100 Subject: [PATCH 0596/1514] media: apple: avd: refuse pictures deeper than the scratch was sized for H.264 and VP9 size their per-stream scratch rows at STREAMON(OUTPUT) from the picture format of that moment. s_ctrl only refuses a format change while CAPTURE buffers are allocated, so a format control set after STREAMON(OUTPUT) and before the CAPTURE buffers, or after they were freed, changed the picture format without resizing the scratch. Record the format the scratch was sized for, and have the run-time picture format check refuse a job whose bit depth differs from it. H.264 STREAMON now also checks and sizes from the SPS's current value rather than from the last value tried. Add a KUnit case for the scratch check. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-fmt-test.c | 22 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 8 +++++-- drivers/media/platform/apple/avd/avd-v4l2.c | 13 +++++++++-- drivers/media/platform/apple/avd/avd-vp9.c | 4 ++++ drivers/media/platform/apple/avd/avd.h | 6 +++++ 5 files changed, 49 insertions(+), 4 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-fmt-test.c b/drivers/media/platform/apple/avd/avd-fmt-test.c index ca6ec6e4a8608a..63a935a2ab0478 100644 --- a/drivers/media/platform/apple/avd/avd-fmt-test.c +++ b/drivers/media/platform/apple/avd/avd-fmt-test.c @@ -111,12 +111,34 @@ static void avd_fmt_comp_mismatch_test(struct kunit *test) -EINVAL); } +/* Scratch sized at STREAMON for 8 bits does not take a 10-bit picture. */ +static void avd_fmt_scratch_depth_test(struct kunit *test) +{ + struct avd_ctx *ctx = avd_fmt_test_ctx(test, AVD_IMG_FMT_420_10BIT, + V4L2_PIX_FMT_P010); + + ctx->scratch_sized = true; + ctx->scratch_fmt = AVD_IMG_FMT_ANY; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), + -EINVAL); + ctx->scratch_fmt = AVD_IMG_FMT_420_10BIT; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); + /* Codecs that size no scratch from the format are not limited. */ + ctx->scratch_sized = false; + ctx->scratch_fmt = AVD_IMG_FMT_ANY; + KUNIT_EXPECT_EQ(test, + avd_check_run_image_fmt(ctx, AVD_IMG_FMT_420_10BIT), 0); +} + static struct kunit_case avd_fmt_test_cases[] = { KUNIT_CASE(avd_fmt_any_test), KUNIT_CASE(avd_fmt_any_p010_test), KUNIT_CASE(avd_fmt_10bit_test), KUNIT_CASE(avd_fmt_422_test), KUNIT_CASE(avd_fmt_comp_mismatch_test), + KUNIT_CASE(avd_fmt_scratch_depth_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index b5f87f6def9146..e936875f2c9c3d 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -748,6 +748,7 @@ static void avd_h264_stop(struct avd_ctx *ctx) unsigned int i; ctx->max_frames = 1; + ctx->scratch_sized = false; if (!h264_ctx) return; @@ -782,7 +783,7 @@ static int avd_h264_start(struct avd_ctx *ctx) if (!ctrl) return -EINVAL; - ret = avd_h264_validate_sps(ctx, ctrl->p_new.p_h264_sps); + ret = avd_h264_validate_sps(ctx, ctrl->p_cur.p_h264_sps); if (ret) return ret; @@ -799,7 +800,7 @@ static int avd_h264_start(struct avd_ctx *ctx) struct avd_bank *bank = &h264_ctx->bank[i]; bank->alloc_slice_num = - avd_h264_start_slices(ctrl->p_new.p_h264_sps); + avd_h264_start_slices(ctrl->p_cur.p_h264_sps); bank->slices = kcalloc(bank->alloc_slice_num, sizeof(*bank->slices), GFP_KERNEL_ACCOUNT); if (!bank->slices) { @@ -812,6 +813,9 @@ static int avd_h264_start(struct avd_ctx *ctx) goto err_free_ctx; } ctx->max_frames = h264_ctx->nbanks; + /* avd_h264_alloc_bufs() sized the scratch rows for this depth */ + ctx->scratch_fmt = ctx->image_fmt; + ctx->scratch_sized = true; return 0; diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 1cd84c6259d433..3177ae15ed3fd6 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -74,8 +74,15 @@ static bool avd_image_fmt_fits_capture(struct avd_ctx *ctx, * 4:2:0), and the control's value can differ from it: it may have been set * while another codec was selected, or kept over an OUTPUT format change, and * an unchanged value never reaches s_ctrl. Refuse the job unless both are the - * same and the CAPTURE buffers fit it. + * same and the CAPTURE buffers fit it, and unless the scratch a codec sized at + * STREAMON has the bit depth of the picture (s_ctrl only refuses a change + * while CAPTURE buffers are allocated, not while OUTPUT streams). */ +static bool avd_image_fmt_10bit(enum avd_image_fmt fmt) +{ + return fmt == AVD_IMG_FMT_420_10BIT || fmt == AVD_IMG_FMT_422_10BIT; +} + int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt) { enum avd_image_fmt sized = ctx->image_fmt; @@ -84,7 +91,9 @@ int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt) sized = AVD_IMG_FMT_420_8BIT; if (image_fmt == AVD_IMG_FMT_ANY) image_fmt = AVD_IMG_FMT_420_8BIT; - if (image_fmt != sized || !avd_image_fmt_fits_capture(ctx, image_fmt)) { + if (image_fmt != sized || !avd_image_fmt_fits_capture(ctx, image_fmt) || + (ctx->scratch_sized && + avd_image_fmt_10bit(ctx->scratch_fmt) != avd_image_fmt_10bit(image_fmt))) { dev_dbg_ratelimited(ctx->dev->dev, "picture format %d does not fit the buffers (%d)\n", image_fmt, ctx->image_fmt); diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 09f85671691091..e3590e27d9c53e 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -1264,6 +1264,7 @@ static void avd_vp9_stop(struct avd_ctx *ctx) /* drain() excludes readiness callbacks before private storage is freed. */ avd_vp9_free(ctx, ctx->priv); ctx->priv = NULL; + ctx->scratch_sized = false; } static int avd_vp9_start(struct avd_ctx *ctx) @@ -1284,6 +1285,9 @@ static int avd_vp9_start(struct avd_ctx *ctx) avd_init_v4l2_vp9_count_tbl(&vp9_ctx->bank[i]); } ctx->max_frames = vp9_ctx->nbanks; + /* avd_vp9_alloc_bufs() sized the scratch for this depth */ + ctx->scratch_fmt = ctx->image_fmt; + ctx->scratch_sized = true; /* job_ready can run while STREAMON is still initializing this codec. */ smp_store_release(&ctx->priv, vp9_ctx); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 54d9e8a48289b6..a9c5f03e81d52b 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -345,6 +345,12 @@ struct avd_ctx { void *priv; struct avd_comp comp; + /* + * Picture format the codec sized its per-stream scratch for at + * STREAMON, if it sizes any from the picture format. + */ + bool scratch_sized; + enum avd_image_fmt scratch_fmt; int fifo_idx; /* Pictures of this context the queue may hold at once (0 or 1: one). */ unsigned int max_frames; From beb13940004d4587b7c9889b2abeaa789c4a2cf2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:54:59 +1100 Subject: [PATCH 0597/1514] media: apple: avd: add a helper to copy a control's value for a run A run reads the codec's parameters from the current value of the controls. The request's controls are applied before that, but a control can also be set directly while the run is in progress, and its value is then rewritten under the control lock, which the run does not hold. A run that checks a value and later reads it again from the control can see two different values. Add avd_ctrl_copy(), which copies the current value of a fixed-size control under the control lock and refuses a destination of another size, so that a run can check and use one private copy. The dynamic arrays are already copied this way. v4l2_ctrl_find() takes the same lock, so the lookup is done first and avd_ctrl_copy_value() copies a control that was already found. The KUnit cases check that a copy keeps its value when the control is set again, that the size is checked, and that the copy waits for the holder of the control lock. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-v4l2-test.c | 129 +++++++++++++++++- drivers/media/platform/apple/avd/avd-v4l2.c | 34 +++++ drivers/media/platform/apple/avd/avd.h | 2 + 3 files changed, 164 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/avd/avd-v4l2-test.c b/drivers/media/platform/apple/avd/avd-v4l2-test.c index 0c057d567b6152..3b2e09b6f6d9c6 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2-test.c +++ b/drivers/media/platform/apple/avd/avd-v4l2-test.c @@ -1,10 +1,13 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit tests for the format ioctls of the Apple video decoder. + * KUnit tests for the format ioctls and the control helpers of the Apple + * video decoder. */ #include +#include #include +#include #include #include "avd.h" @@ -136,9 +139,133 @@ static void avd_s_capture_fmt_test(struct kunit *test) avd_test_expect_comp(test, &t.ctx->comp, &want); } +/* A context whose control handler holds the VP9 frame control. */ +static struct v4l2_ctrl *avd_test_ctrl_init(struct kunit *test, + struct avd_ctx **ctxp) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_VP9_FRAME, + }; + struct avd_ctx *ctx; + struct v4l2_ctrl *ctrl; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + + *ctxp = ctx; + return ctrl; +} + +static int avd_test_set_vp9_width(struct v4l2_ctrl *ctrl, u16 width) +{ + struct v4l2_ctrl_vp9_frame frame = *ctrl->p_cur.p_vp9_frame; + + frame.frame_width_minus_1 = width - 1; + frame.frame_height_minus_1 = width - 1; + return v4l2_ctrl_s_ctrl_compound(ctrl, V4L2_CTRL_TYPE_VP9_FRAME, + &frame); +} + +/* A copy keeps the value it was taken from when the control is set again. */ +static void avd_ctrl_copy_test(struct kunit *test) +{ + struct v4l2_ctrl_vp9_frame *copy; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctrl = avd_test_ctrl_init(test, &ctx); + copy = kunit_kzalloc(test, sizeof(*copy) + 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 64), 0); + KUNIT_ASSERT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy)), 0); + KUNIT_EXPECT_MEMEQ(test, copy, ctrl->p_cur.p, sizeof(*copy)); + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(copy, 64, 64)); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 4096), 0); + KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(ctrl->p_cur.p_vp9_frame, + 64, 64)); + KUNIT_EXPECT_EQ(test, copy->frame_width_minus_1, 63); + KUNIT_EXPECT_EQ(test, copy->frame_height_minus_1, 63); + KUNIT_EXPECT_TRUE(test, avd_vp9_frame_fits(copy, 64, 64)); + + /* Only a destination of the control's own size is filled. */ + memset(copy, 0, sizeof(*copy)); + KUNIT_EXPECT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy) - 1), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_FRAME, + copy, sizeof(*copy) + 1), -EINVAL); + KUNIT_EXPECT_EQ(test, copy->frame_width_minus_1, 0); + /* So is a control that the handler does not have. */ + KUNIT_EXPECT_EQ(test, + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_VP9_COMPRESSED_HDR, + copy, sizeof(*copy)), -EINVAL); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + +struct avd_test_copy_work { + struct work_struct work; + struct completion done; + struct v4l2_ctrl *ctrl; + struct v4l2_ctrl_vp9_frame copy; + int ret; +}; + +static void avd_test_copy_work_fn(struct work_struct *work) +{ + struct avd_test_copy_work *w = + container_of(work, struct avd_test_copy_work, work); + + w->ret = avd_ctrl_copy_value(w->ctrl, &w->copy, sizeof(w->copy)); + complete(&w->done); +} + +/* The copy waits for whoever holds the control lock and sees its whole update. */ +static void avd_ctrl_copy_locked_test(struct kunit *test) +{ + struct avd_test_copy_work *w; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctrl = avd_test_ctrl_init(test, &ctx); + w = kunit_kzalloc(test, sizeof(*w), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, w); + w->ctrl = ctrl; + w->ret = -EINPROGRESS; + init_completion(&w->done); + INIT_WORK(&w->work, avd_test_copy_work_fn); + + KUNIT_ASSERT_EQ(test, avd_test_set_vp9_width(ctrl, 64), 0); + + v4l2_ctrl_lock(ctrl); + ctrl->p_cur.p_vp9_frame->frame_width_minus_1 = 4095; + schedule_work(&w->work); + KUNIT_EXPECT_EQ(test, + wait_for_completion_timeout(&w->done, + msecs_to_jiffies(200)), 0); + KUNIT_EXPECT_EQ(test, w->ret, -EINPROGRESS); + ctrl->p_cur.p_vp9_frame->frame_height_minus_1 = 4095; + v4l2_ctrl_unlock(ctrl); + + flush_work(&w->work); + KUNIT_EXPECT_EQ(test, w->ret, 0); + KUNIT_EXPECT_EQ(test, w->copy.frame_width_minus_1, 4095); + KUNIT_EXPECT_EQ(test, w->copy.frame_height_minus_1, 4095); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + static struct kunit_case avd_v4l2_test_cases[] = { KUNIT_CASE(avd_try_capture_fmt_test), KUNIT_CASE(avd_s_capture_fmt_test), + KUNIT_CASE(avd_ctrl_copy_test), + KUNIT_CASE(avd_ctrl_copy_locked_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 3177ae15ed3fd6..eafafb622295c0 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -1116,6 +1116,40 @@ void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run) v4l2_ctrl_request_complete(src_req, &ctx->ctrl_hdl); } +/* + * Copy the current value of a fixed-size control for a run. Requests are + * applied to the controls before a run reads them, but a control can also be + * set directly at any time, which rewrites its value under the control lock + * only. A run that checks a value and then reads it again from the control + * may see two different values. Take one copy under the lock; the run checks + * and uses that copy. @size must be the size of the control's value. + */ +VISIBLE_IF_KUNIT int avd_ctrl_copy_value(struct v4l2_ctrl *ctrl, void *dst, + size_t size) +{ + int ret = -EINVAL; + + v4l2_ctrl_lock(ctrl); + if ((size_t)ctrl->elems * ctrl->elem_size == size) { + memcpy(dst, ctrl->p_cur.p, size); + ret = 0; + } + v4l2_ctrl_unlock(ctrl); + + return ret; +} +EXPORT_SYMBOL_IF_KUNIT(avd_ctrl_copy_value); + +/* v4l2_ctrl_find() takes the control lock itself, so look up before copying. */ +int avd_ctrl_copy(struct avd_ctx *ctx, u32 id, void *dst, size_t size) +{ + struct v4l2_ctrl *ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, id); + + if (!ctrl) + return -EINVAL; + return avd_ctrl_copy_value(ctrl, dst, size); +} + static int avd_add_ctrls(struct avd_ctx *ctx, const struct avd_ctrls *ctrls) { unsigned int i; diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index a9c5f03e81d52b..af595381e3f47d 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -376,8 +376,10 @@ void avd_job_finish(struct avd_ctx *ctx, enum vb2_buffer_state result); void avd_run_preamble(struct avd_ctx *ctx, struct avd_run *run); int avd_check_run_image_fmt(struct avd_ctx *ctx, enum avd_image_fmt image_fmt); void avd_run_postamble(struct avd_ctx *ctx, struct avd_run *run); +int avd_ctrl_copy(struct avd_ctx *ctx, u32 id, void *dst, size_t size); #if IS_ENABLED(CONFIG_KUNIT) +int avd_ctrl_copy_value(struct v4l2_ctrl *ctrl, void *dst, size_t size); bool avd_h264_find_slice_data(const u8 *data, u32 len, u32 header_len, u32 *off); bool avd_h264_slice_fits(const struct v4l2_ctrl_h264_sps *sps, size_t held, From 575874da58d5cadfdf8f8f497e1143d6f1c28455 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:55:01 +1100 Subject: [PATCH 0598/1514] media: apple: avd: h264: use copies of the controls for a run The run validates the SPS, PPS and slice parameters and then builds the instructions from the same controls, reading them from the controls' current values each time. A control that is set directly meanwhile changes those values, so the builders could use parameters other than the ones that were checked. Copy the decode parameters, SPS, PPS, slice parameters, scaling matrix and prediction weights with avd_ctrl_copy() once the request has been applied, into storage that belongs to the context, and point the run at the copies. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-h264.c | 79 +++++++++++++-------- 1 file changed, 51 insertions(+), 28 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index e936875f2c9c3d..73d86270ca80c2 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -102,6 +102,16 @@ struct avd_h264_ctx { struct avd_bank bank[AVD_H264_BANKS]; /* bank of the picture being built */ struct avd_bank *b; + + /* What the run being built took from the controls, see avd_ctrl_copy(). */ + struct { + struct v4l2_ctrl_h264_decode_params decode_params; + struct v4l2_ctrl_h264_sps sps; + struct v4l2_ctrl_h264_pps pps; + struct v4l2_ctrl_h264_slice_params slice_params; + struct v4l2_ctrl_h264_scaling_matrix scaling_matrix; + struct v4l2_ctrl_h264_pred_weights pred_weights; + } params; }; /* ffmpeg submits wrong timestamp, use first_mb_in_slice as a workaround */ @@ -824,28 +834,11 @@ static int avd_h264_start(struct avd_ctx *ctx) return ret; } -static void avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) +static int avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) { - struct v4l2_ctrl *ctrl; + struct avd_h264_ctx *h264_ctx = ctx->priv; u32 dst_len, mv_color_len; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_DECODE_PARAMS); - run->decode_params = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_H264_SPS); - run->sps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_H264_PPS); - run->pps = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_SLICE_PARAMS); - run->slice_params = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_SCALING_MATRIX); - run->scaling_matrix = ctrl ? ctrl->p_cur.p : NULL; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_H264_PRED_WEIGHTS); - run->pred_weights = ctrl ? ctrl->p_cur.p : NULL; - avd_run_preamble(ctx, &run->base); dst_len = run->base.bufs.dst->vb2_buf.planes[0].length; @@ -853,6 +846,43 @@ static void avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) mv_color_len = mv_color_size(ctx, fmt_width(ctx), fmt_height(ctx)); run->addresses.mv_color = run->base.y_out + (dst_len - mv_color_len); + + if (run->base.setup_err) + return run->base.setup_err; + + /* + * The checks in avd_h264_run() and the builders must see the same + * parameters, and the controls can be set again at any time: use + * copies. + */ + if (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_PARAMS, + &h264_ctx->params.decode_params, + sizeof(h264_ctx->params.decode_params)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SPS, + &h264_ctx->params.sps, + sizeof(h264_ctx->params.sps)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PPS, + &h264_ctx->params.pps, + sizeof(h264_ctx->params.pps)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SLICE_PARAMS, + &h264_ctx->params.slice_params, + sizeof(h264_ctx->params.slice_params)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SCALING_MATRIX, + &h264_ctx->params.scaling_matrix, + sizeof(h264_ctx->params.scaling_matrix)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PRED_WEIGHTS, + &h264_ctx->params.pred_weights, + sizeof(h264_ctx->params.pred_weights))) + return -EINVAL; + + run->decode_params = &h264_ctx->params.decode_params; + run->sps = &h264_ctx->params.sps; + run->pps = &h264_ctx->params.pps; + run->slice_params = &h264_ctx->params.slice_params; + run->scaling_matrix = &h264_ctx->params.scaling_matrix; + run->pred_weights = &h264_ctx->params.pred_weights; + + return 0; } static int avd_h264_realloc_slices(struct avd_ctx *ctx, size_t max_slices) @@ -1044,16 +1074,9 @@ static int avd_h264_run(struct avd_ctx *ctx) h264_ctx->b->slice_num : 0; int ret; - avd_h264_run_preamble(ctx, &run); - - if (run.base.setup_err) { - ret = run.base.setup_err; - goto err_free_jobs; - } - if (!run.sps || !run.pps || !run.slice_params || !run.decode_params) { - ret = -EINVAL; + ret = avd_h264_run_preamble(ctx, &run); + if (ret) goto err_free_jobs; - } /* Recheck controls applied from this request before building instructions. */ ret = avd_h264_validate_sps(ctx, run.sps); From 4d9cdada98788f803756cdbc6ae345939333b758 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:55:02 +1100 Subject: [PATCH 0599/1514] media: apple: avd: av1: use copies of the controls for a run The run checks the sequence and the frame and then builds the instructions from the same controls, reading them from the controls' current values each time. A control that is set directly meanwhile changes those values, so the builders could use parameters other than the ones that were checked. Copy the sequence, frame and film grain with avd_ctrl_copy() once the request has been applied, into storage that belongs to the context, and point the run at the copies. The tile group entries are already a private copy. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-av1.c | 43 ++++++++++++++-------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index 1bbf54f9b83aa3..a94dbe0a491f06 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -273,6 +273,13 @@ struct avd_av1_stream { unsigned int nbanks; struct avd_av1_bank bank[AVD_AV1_BANKS]; struct avd_av1_bank *b; + + /* What the run being built took from the controls, see avd_ctrl_copy(). */ + struct { + struct v4l2_ctrl_av1_sequence seq; + struct v4l2_ctrl_av1_frame frame; + struct v4l2_ctrl_av1_film_grain grain; + } params; }; /* @@ -1500,6 +1507,7 @@ static int avd_av1_validate_sequence(struct avd_ctx *ctx, static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) { + struct avd_av1_stream *av1_ctx = ((struct avd_av1_ctx *)ctx->priv)->stream; struct v4l2_ctrl *ctrl; int dst_len, ret, tlb_len; @@ -1507,10 +1515,25 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (run->base.setup_err) return run->base.setup_err; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_AV1_SEQUENCE); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->seq = ctrl->p_cur.p; + /* + * The checks below and the builders must see the same parameters, and + * the controls can be set again at any time: use copies. + */ + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_SEQUENCE, + &av1_ctx->params.seq, sizeof(av1_ctx->params.seq)); + if (!ret) + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_FRAME, + &av1_ctx->params.frame, + sizeof(av1_ctx->params.frame)); + if (!ret) + ret = avd_ctrl_copy(ctx, V4L2_CID_STATELESS_AV1_FILM_GRAIN, + &av1_ctx->params.grain, + sizeof(av1_ctx->params.grain)); + if (WARN_ON(ret)) + return ret; + run->seq = &av1_ctx->params.seq; + run->frame = &av1_ctx->params.frame; + run->grain = &av1_ctx->params.grain; /* The sequence may have been set, unchecked, while another codec was selected. */ ret = avd_av1_validate_sequence(ctx, run->seq); @@ -1520,11 +1543,6 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (ret) return ret; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, V4L2_CID_STATELESS_AV1_FRAME); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->frame = ctrl->p_cur.p; - /* The map, CDFs and color data sit at the buffer's end, sized by the frame. */ if (run->frame->frame_width_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.width || run->frame->frame_height_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.height) @@ -1550,7 +1568,6 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) run->tile_group = avd_av1_copy_tile_group(ctrl, &run->tile_group_entries); if (!run->tile_group) return -ENOMEM; - /* The frame control can be set meanwhile too: use one tile grid throughout. */ run->tile_rows = run->frame->tile_info.tile_rows; run->tile_cols = run->frame->tile_info.tile_cols; ret = avd_av1_check_tiles(ctx->dev->dev, run->tile_rows, run->tile_cols, @@ -1559,12 +1576,6 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (ret) return ret; - ctrl = v4l2_ctrl_find(&ctx->ctrl_hdl, - V4L2_CID_STATELESS_AV1_FILM_GRAIN); - if (WARN_ON(!ctrl)) - return -EINVAL; - run->grain = ctrl->p_cur.p; - dst_len = run->base.bufs.dst->vb2_buf.planes[0].length; tlb_len = avd_color_size(run->frame->frame_width_minus_1 + 1, run->frame->frame_height_minus_1 + 1); From 30b1cc4784241734f2aadab71718b538c3cc984f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:55:45 +1100 Subject: [PATCH 0600/1514] media: apple: avd: av1: bound the upscaled width The frame's upscaled_width is written to the frame header and divides the superres scale factors, but nothing checked it. Only the frame width and height were compared with the CAPTURE format. Superres only widens a frame, from frame_width to upscaled_width, and without it the two are equal. Require, on the run's copy of the frame, that upscaled_width is at least the frame width and at most the CAPTURE width, and that it equals the frame width when superres is off. Move the existing frame size check into the same helper and compare the minus-one fields directly, so that the largest value cannot wrap to a size of zero. With superres the denominator is also written to the header less one; the stream codes it as 9 to 16 and the control core only bounds it from above, so require at least 9. Add KUnit cases for the helper. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-av1-test.c | 57 ++++++++++++++++++- drivers/media/platform/apple/avd/avd-av1.c | 46 +++++++++++++-- drivers/media/platform/apple/avd/avd.h | 2 + 3 files changed, 100 insertions(+), 5 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-av1-test.c b/drivers/media/platform/apple/avd/avd-av1-test.c index 34768e5877ff8d..feb87609ba937b 100644 --- a/drivers/media/platform/apple/avd/avd-av1-test.c +++ b/drivers/media/platform/apple/avd/avd-av1-test.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit tests for the AV1 tile checks of the Apple video decoder. + * KUnit tests for the AV1 tile and frame size checks of the Apple video + * decoder. */ #include @@ -171,12 +172,66 @@ static void avd_av1_copy_tile_group_test(struct kunit *test) v4l2_ctrl_handler_free(hdl); } +struct avd_av1_size_case { + const char *desc; + u32 width; + u32 height; + u32 upscaled_width; + bool superres; + int ret; + u8 denom; +}; + +/* Frames for 1920x1088 CAPTURE buffers. */ +static const struct avd_av1_size_case avd_av1_size_cases[] = { + { "frame of the buffer size", 1920, 1088, 1920, false, 0 }, + { "smaller frame", 1280, 720, 1280, false, 0 }, + { "one sample", 1, 1, 1, false, 0 }, + { "superres to the buffer width", 960, 1080, 1920, true, 0, 16 }, + { "superres to a smaller width", 1000, 1080, 1280, true, 0, 16 }, + { "superres with equal widths", 1920, 1080, 1920, true, 0, 16 }, + { "frame wider than the buffer", 1921, 1080, 1921, false, -EINVAL }, + { "frame higher than the buffer", 1920, 1089, 1920, false, -EINVAL }, + { "frame width wraps", 0, 1080, 1920, false, -EINVAL }, + { "frame height wraps", 1920, 0, 1920, false, -EINVAL }, + { "no upscaled width", 1920, 1080, 0, false, -EINVAL }, + { "no upscaled width, superres", 1920, 1080, 0, true, -EINVAL, 16 }, + { "upscaled width below the frame's", 1920, 1080, 1919, true, -EINVAL, 16 }, + { "upscaled width past the buffer", 960, 1080, 1921, true, -EINVAL, 16 }, + { "huge upscaled width", 960, 1080, U32_MAX, true, -EINVAL, 16 }, + { "upscaled width without superres", 960, 1080, 1920, false, -EINVAL }, + { "superres, smallest denominator", 1072, 1080, 1920, true, 0, 9 }, + { "superres, no denominator", 960, 1080, 1920, true, -EINVAL, 0 }, + { "superres, denominator below 9", 960, 1080, 1920, true, -EINVAL, 8 }, +}; + +KUNIT_ARRAY_PARAM_DESC(avd_av1_size, avd_av1_size_cases, desc); + +static void avd_av1_frame_size_test(struct kunit *test) +{ + const struct avd_av1_size_case *c = test->param_value; + struct v4l2_ctrl_av1_frame *frame; + + frame = kunit_kzalloc(test, sizeof(*frame), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, frame); + frame->frame_width_minus_1 = c->width - 1; + frame->frame_height_minus_1 = c->height - 1; + frame->upscaled_width = c->upscaled_width; + frame->superres_denom = c->denom; + if (c->superres) + frame->flags |= V4L2_AV1_FRAME_FLAG_USE_SUPERRES; + + KUNIT_EXPECT_EQ(test, avd_av1_check_frame_size(frame, 1920, 1088), + c->ret); +} + static struct kunit_case avd_av1_test_cases[] = { KUNIT_CASE(avd_av1_tiles_valid_test), KUNIT_CASE(avd_av1_tiles_count_test), KUNIT_CASE(avd_av1_tiles_extent_test), KUNIT_CASE_PARAM(avd_av1_tiles_rowcol_test, avd_av1_rowcol_gen_params), KUNIT_CASE(avd_av1_copy_tile_group_test), + KUNIT_CASE_PARAM(avd_av1_frame_size_test, avd_av1_size_gen_params), {} }; diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index a94dbe0a491f06..106024cfd806a0 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -1505,6 +1505,43 @@ static int avd_av1_validate_sequence(struct avd_ctx *ctx, return 0; } +/* + * The map, CDFs and color data sit at the end of the CAPTURE buffer, sized by + * the frame, so the frame must fit the CAPTURE format. So must the width it + * is upscaled to, which goes into the header as it is and divides the scale + * factors: superres only widens the frame, from frame_width to upscaled_width + * (AV1 7.16), and without it the two are equal (AV1 5.9.8, superres_params()). + */ +VISIBLE_IF_KUNIT int +avd_av1_check_frame_size(const struct v4l2_ctrl_av1_frame *frame, u32 width, + u32 height) +{ + u32 frame_width; + + if (frame->frame_width_minus_1 >= width || + frame->frame_height_minus_1 >= height) + return -EINVAL; + + frame_width = frame->frame_width_minus_1 + 1; + if (frame->upscaled_width < frame_width || + frame->upscaled_width > width) + return -EINVAL; + if (!(frame->flags & V4L2_AV1_FRAME_FLAG_USE_SUPERRES) && + frame->upscaled_width != frame_width) + return -EINVAL; + /* + * With superres the denominator goes into the header less one; the + * stream codes it as 9 to 16 (AV1 5.9.8), the control core only + * bounds it from above. + */ + if ((frame->flags & V4L2_AV1_FRAME_FLAG_USE_SUPERRES) && + frame->superres_denom < 9) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_av1_check_frame_size); + static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) { struct avd_av1_stream *av1_ctx = ((struct avd_av1_ctx *)ctx->priv)->stream; @@ -1543,10 +1580,11 @@ static int avd_av1_run_preamble(struct avd_ctx *ctx, struct avd_av1_run *run) if (ret) return ret; - /* The map, CDFs and color data sit at the buffer's end, sized by the frame. */ - if (run->frame->frame_width_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.width || - run->frame->frame_height_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.height) - return -EINVAL; + ret = avd_av1_check_frame_size(run->frame, + ctx->decoded_fmt.fmt.pix_mp.width, + ctx->decoded_fmt.fmt.pix_mp.height); + if (ret) + return ret; /* * The CDF and segmentation map loads index the reference arrays with diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index af595381e3f47d..3f0e2b0eaa5175 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -404,6 +404,8 @@ int avd_av1_check_tiles(struct device *dev, unsigned int tile_rows, unsigned int entries, size_t payload); struct v4l2_ctrl_av1_tile_group_entry * avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries); +int avd_av1_check_frame_size(const struct v4l2_ctrl_av1_frame *frame, + u32 width, u32 height); int avd_h264_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); size_t avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); From b36ff9b1dc3d79cf698e53482cbd59876bf52c64 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:56:36 +1100 Subject: [PATCH 0601/1514] media: apple: avd: check the VP9 and AV1 frame size when the control is set The VP9 and AV1 frame sizes are only compared with the formats when a frame runs. Compare them when the frame control is set as well, with the checks the run uses, so that a frame that cannot be decoded is refused at the control like an H.264 SPS is. A control may be set before the formats, so only check against a format that can no longer change: the OUTPUT format once the OUTPUT queue streams for VP9, whose scratch is sized from it, and the CAPTURE format once CAPTURE buffers are allocated for AV1, whose frame must fit them. The AV1 frame control gets the driver's control ops for this. Add KUnit cases for both. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-av1-test.c | 50 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-av1.c | 15 ++++++ drivers/media/platform/apple/avd/avd-v4l2.c | 1 + .../media/platform/apple/avd/avd-vp9-test.c | 49 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-vp9.c | 19 +++++-- 5 files changed, 131 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-av1-test.c b/drivers/media/platform/apple/avd/avd-av1-test.c index feb87609ba937b..c88815e38db479 100644 --- a/drivers/media/platform/apple/avd/avd-av1-test.c +++ b/drivers/media/platform/apple/avd/avd-av1-test.c @@ -6,6 +6,7 @@ #include #include +#include #include "avd.h" @@ -225,6 +226,54 @@ static void avd_av1_frame_size_test(struct kunit *test) c->ret); } +/* + * A frame that does not fit the CAPTURE format is refused when the control + * is set, once CAPTURE buffers are allocated and the format can no longer + * follow it. + */ +static void avd_av1_try_frame_size_test(struct kunit *test) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_AV1_FRAME, + }; + struct v4l2_m2m_ctx *m2m_ctx; + struct v4l2_ctrl_av1_frame *frame; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + ctx->fh.m2m_ctx = m2m_ctx; + ctx->decoded_fmt.fmt.pix_mp.width = 1920; + ctx->decoded_fmt.fmt.pix_mp.height = 1088; + + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + frame = ctrl->p_new.p_av1_frame; + + /* No buffers: the format may still be set to the stream's size. */ + frame->frame_width_minus_1 = 3839; + frame->frame_height_minus_1 = 2159; + frame->upscaled_width = 3840; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), 0); + + m2m_ctx->cap_q_ctx.q.is_busy = 1; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_width_minus_1 = 1919; + frame->frame_height_minus_1 = 1079; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->upscaled_width = 1920; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), 0); + frame->upscaled_width = 0; + KUNIT_EXPECT_EQ(test, avd_av1_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + static struct kunit_case avd_av1_test_cases[] = { KUNIT_CASE(avd_av1_tiles_valid_test), KUNIT_CASE(avd_av1_tiles_count_test), @@ -232,6 +281,7 @@ static struct kunit_case avd_av1_test_cases[] = { KUNIT_CASE_PARAM(avd_av1_tiles_rowcol_test, avd_av1_rowcol_gen_params), KUNIT_CASE(avd_av1_copy_tile_group_test), KUNIT_CASE_PARAM(avd_av1_frame_size_test, avd_av1_size_gen_params), + KUNIT_CASE(avd_av1_try_frame_size_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-av1.c b/drivers/media/platform/apple/avd/avd-av1.c index 106024cfd806a0..04d55dd7b0aad2 100644 --- a/drivers/media/platform/apple/avd/avd-av1.c +++ b/drivers/media/platform/apple/avd/avd-av1.c @@ -2036,10 +2036,25 @@ static void avd_av1_adjust_decoded_fmt(struct avd_ctx *ctx, static int avd_av1_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { + struct vb2_queue *vq; + if (ctrl->id == V4L2_CID_STATELESS_AV1_SEQUENCE) return avd_av1_validate_sequence(ctx, ctrl->p_new.p_av1_sequence); /* width should also be > 8 */ + if (ctrl->id != V4L2_CID_STATELESS_AV1_FRAME) + return 0; + + /* + * The CAPTURE format is fixed while its buffers are allocated: a frame + * that does not fit them cannot be decoded, as the run finds too. + * Before that the format may still be set to the stream's. + */ + vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); + if (vb2_is_busy(vq)) + return avd_av1_check_frame_size(ctrl->p_new.p_av1_frame, + ctx->decoded_fmt.fmt.pix_mp.width, + ctx->decoded_fmt.fmt.pix_mp.height); return 0; } diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index eafafb622295c0..5c010a7c9c66da 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -439,6 +439,7 @@ static const struct avd_ctrl_desc avd_av1_ctrl_descs[] = { }, { .cfg.id = V4L2_CID_STATELESS_AV1_FRAME, + .cfg.ops = &avd_ctrl_ops, }, { .cfg.id = V4L2_CID_STATELESS_AV1_FILM_GRAIN, diff --git a/drivers/media/platform/apple/avd/avd-vp9-test.c b/drivers/media/platform/apple/avd/avd-vp9-test.c index 4e0bcd09ed31c6..7bf89193a8f404 100644 --- a/drivers/media/platform/apple/avd/avd-vp9-test.c +++ b/drivers/media/platform/apple/avd/avd-vp9-test.c @@ -4,6 +4,7 @@ */ #include +#include #include "avd.h" @@ -154,8 +155,56 @@ static void avd_vp9_frame_fits_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd_vp9_frame_fits(&frame, 4096, 4096)); } +/* + * A frame larger than the OUTPUT format is refused when the control is set, + * once the OUTPUT queue streams and the format can no longer follow it. + */ +static void avd_vp9_try_frame_size_test(struct kunit *test) +{ + static const struct v4l2_ctrl_config cfg = { + .id = V4L2_CID_STATELESS_VP9_FRAME, + }; + struct v4l2_m2m_ctx *m2m_ctx; + struct v4l2_ctrl_vp9_frame *frame; + struct v4l2_ctrl *ctrl; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + m2m_ctx = kunit_kzalloc(test, sizeof(*m2m_ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, m2m_ctx); + ctx->fh.m2m_ctx = m2m_ctx; + ctx->coded_fmt.fmt.pix_mp.width = 1920; + ctx->coded_fmt.fmt.pix_mp.height = 1088; + + v4l2_ctrl_handler_init(&ctx->ctrl_hdl, 1); + ctrl = v4l2_ctrl_new_custom(&ctx->ctrl_hdl, &cfg, NULL); + KUNIT_ASSERT_EQ(test, ctx->ctrl_hdl.error, 0); + KUNIT_ASSERT_NOT_NULL(test, ctrl); + frame = ctrl->p_new.p_vp9_frame; + + /* Not streaming: the format may still be set to the stream's size. */ + frame->frame_width_minus_1 = 4095; + frame->frame_height_minus_1 = 2159; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + + m2m_ctx->out_q_ctx.q.streaming = 1; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_width_minus_1 = 1919; + frame->frame_height_minus_1 = 1088; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), -EINVAL); + frame->frame_height_minus_1 = 1087; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + frame->frame_width_minus_1 = 1279; + frame->frame_height_minus_1 = 719; + KUNIT_EXPECT_EQ(test, avd_vp9_fmt_ops.try_ctrl(ctx, ctrl), 0); + + v4l2_ctrl_handler_free(&ctx->ctrl_hdl); +} + static struct kunit_case avd_vp9_test_cases[] = { KUNIT_CASE(avd_vp9_frame_fits_test), + KUNIT_CASE(avd_vp9_try_frame_size_test), KUNIT_CASE_PARAM(avd_vp9_tiling_test, avd_vp9_tiling_gen_params), KUNIT_CASE_PARAM(avd_vp9_tiles_test, avd_vp9_tiles_gen_params), {} diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index e3590e27d9c53e..695ba69d9b03fa 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -1309,10 +1309,23 @@ static enum avd_image_fmt avd_vp9_get_image_fmt(struct avd_ctx *ctx, static int avd_vp9_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_VP9_FRAME) - return avd_vp9_validate_frame(ctx, ctrl->p_new.p_vp9_frame); + const struct v4l2_ctrl_vp9_frame *frame = ctrl->p_new.p_vp9_frame; + struct vb2_queue *vq; - return 0; + if (ctrl->id != V4L2_CID_STATELESS_VP9_FRAME) + return 0; + + /* + * The OUTPUT format is fixed while its queue streams and the scratch + * is sized from it: a larger frame cannot be decoded, as the run + * finds too. Before that the format may still be set to the stream's. + */ + vq = v4l2_m2m_get_vq(ctx->fh.m2m_ctx, V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE); + if (vb2_is_streaming(vq) && + !avd_vp9_frame_fits(frame, fmt_width(ctx), fmt_height(ctx))) + return -EINVAL; + + return avd_vp9_validate_frame(ctx, frame); } static unsigned int avd_vp9_pp_kicks(struct avd_ctx *ctx) From ae956871a89e6a13caef3055dba825d210514761 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:57:28 +1100 Subject: [PATCH 0602/1514] media: apple: avd: do not submit without the context FIFO The legacy transport programs the address of the context's instruction FIFO into the decoder for every submission. The FIFO is allocated when the OUTPUT queue starts streaming and freed when it stops, so the address is only valid in between. No path submits outside of that, but nothing in the submission says so. Refuse the submission with -EINVAL when the FIFO is not allocated, together with the other checks of the frame and before any register is written. Add a KUnit case. Signed-off-by: Ryan Murray --- .../platform/apple/avd/avd-backend-open.c | 3 ++ .../media/platform/apple/avd/avd-queue-test.c | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/drivers/media/platform/apple/avd/avd-backend-open.c b/drivers/media/platform/apple/avd/avd-backend-open.c index 2681eeb63b7776..6f6028ad5895ee 100644 --- a/drivers/media/platform/apple/avd/avd-backend-open.c +++ b/drivers/media/platform/apple/avd/avd-backend-open.c @@ -94,6 +94,9 @@ int avd_open_submit(struct avd_dev *avd, struct avd_frame *f) if (codec > AVD_CODEC_AV1 || !words || !f->prog_words || f->prog_words > f->prog->size / sizeof(u32)) return -EINVAL; + /* The context FIFO only exists while the OUTPUT queue streams. */ + if (!ctx->inst.cpu) + return -EINVAL; if (!(avd->capabilities & BIT(codec))) return -EOPNOTSUPP; for (i = 0; i < codec; i++) diff --git a/drivers/media/platform/apple/avd/avd-queue-test.c b/drivers/media/platform/apple/avd/avd-queue-test.c index 8d343b1b933995..7de5e49bdae261 100644 --- a/drivers/media/platform/apple/avd/avd-queue-test.c +++ b/drivers/media/platform/apple/avd/avd-queue-test.c @@ -207,6 +207,48 @@ static void avd_submit_order(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd_slot_submit_first(pool, &pool[1])); } +/* + * The legacy transport programs the context FIFO, which only exists while + * the OUTPUT queue streams. With no codec capability the submission stops + * before it touches the hardware either way. + */ +static void avd_open_submit_needs_fifo(struct kunit *test) +{ + static const struct avd_coded_fmt_desc desc = {}; + struct avd_dev *avd; + struct avd_ctx *ctx; + struct avd_frame *f; + struct avd_buf *prog; + u32 *words; + + avd = kunit_kzalloc(test, sizeof(*avd), GFP_KERNEL); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + prog = kunit_kzalloc(test, sizeof(*prog), GFP_KERNEL); + words = kunit_kcalloc(test, 4, sizeof(*words), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, avd); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, prog); + KUNIT_ASSERT_NOT_NULL(test, words); + + ctx->dev = avd; + ctx->coded_fmt_desc = &desc; + prog->cpu = words; + prog->size = 4 * sizeof(*words); + f->ctx = ctx; + f->prog = prog; + f->prog_words = 1; + f->cmd[0] = AVD_CODEC_H264; + + KUNIT_EXPECT_EQ(test, avd_open_backend.submit(avd, f), -EINVAL); + KUNIT_EXPECT_NULL(test, avd->compat_active); + + ctx->inst.cpu = words; + KUNIT_EXPECT_EQ(test, avd_open_backend.submit(avd, f), -EOPNOTSUPP); + KUNIT_EXPECT_NULL(test, avd->compat_active); +} + static struct kunit_case avd_queue_cases[] = { KUNIT_CASE(avd_slots_and_tags), KUNIT_CASE(avd_retirement_order), @@ -215,6 +257,7 @@ static struct kunit_case avd_queue_cases[] = { KUNIT_CASE(avd_command_builders), KUNIT_CASE(avd_dispatch_reservation), KUNIT_CASE(avd_submit_order), + KUNIT_CASE(avd_open_submit_needs_fifo), {} }; From 752c8813f2603a208ab5065db5ac3272096b32a6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:57:28 +1100 Subject: [PATCH 0603/1514] media: apple: avd: hevc: test entry point offsets that exceed their slice avd_hevc_check_slices() gives the last tile of a slice the bytes that the entry point offsets leave. Cover offsets that add up to more than the slice's data while each of them, and their sum, still lies inside the payload: in a single slice, and in the first and the second of two slices. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-hevc-test.c | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c index efb0cf13b0d8f7..d6c454005e370e 100644 --- a/drivers/media/platform/apple/avd/avd-hevc-test.c +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -279,12 +279,71 @@ static void avd_hevc_two_slices_test(struct kunit *test) &ep, 1, 119), -EINVAL); } +/* + * The entry point offsets split a slice's data into its tiles; the last tile + * takes what the others leave. Offsets that add up to more than the slice + * holds leave it less than nothing, even when each one fits the payload. + */ +static void avd_hevc_entry_points_sum_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_decode_params *decode; + struct v4l2_ctrl_hevc_slice_params *sl; + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING, + .num_tile_columns_minus1 = 3, + }; + u32 ep[6] = { 20, 20, 20, 20, 20, 20 }; + + decode = kunit_kzalloc(test, sizeof(*decode), GFP_KERNEL); + sl = kunit_kcalloc(test, 2, sizeof(*sl), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, decode); + KUNIT_ASSERT_NOT_NULL(test, sl); + + avd_hevc_test_sps(&sps); + sl[0].slice_type = V4L2_HEVC_SLICE_TYPE_I; + sl[0].bit_size = 100 * 8; + sl[0].data_byte_offset = 10; + sl[0].num_entry_point_offsets = 3; + sl[1] = sl[0]; + sl[1].slice_segment_addr = 8; + + /* 10 header bytes, three tiles of 20 bytes and a last one of 30. */ + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 1, + ep, 3, 100), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), 0); + + /* One byte more than the 90 data bytes of the slice. */ + ep[0] = 30; + ep[1] = 30; + ep[2] = 31; + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 1, + ep, 3, 100), -EINVAL); + /* + * The same in the first of two slices: every offset and their sum + * stay inside the payload, but not inside the slice. + */ + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), -EINVAL); + + /* And in the second slice. */ + ep[0] = 20; + ep[1] = 20; + ep[2] = 20; + ep[5] = 51; + KUNIT_EXPECT_EQ(test, avd_hevc_check_slices(&sps, &pps, decode, sl, 2, + ep, 6, 200), -EINVAL); +} + static struct kunit_case avd_hevc_test_cases[] = { KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), KUNIT_CASE(avd_hevc_no_tiles_test), KUNIT_CASE_PARAM(avd_hevc_slices_test, avd_hevc_slices_gen_params), KUNIT_CASE(avd_hevc_two_slices_test), + KUNIT_CASE(avd_hevc_entry_points_sum_test), {} }; From 226c7903c978c809c4931b977e015182f0fcad12 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 23 Nov 2026 05:56:04 +0100 Subject: [PATCH 0604/1514] ASoC: apple: macaudio: hold a fixed ceiling only at its amp level A fixed speaker ceiling (spk_fixed_ceiling) is a volume computed for one amp level. The driver takes each SN012776 amp's level from the apple,speaker-config the boot loader passes, and at another level the same volume drives the speaker differently. Let a fixed ceiling name the level it was computed for (spk_ceiling_level), log the level read, and keep the speakers off when any amp has another level. No board uses a fixed ceiling yet. The J873, for which it was written, stays off until its limit comes from the machine's own speaker data. A new amp-level KUnit case admits an amp at the ceiling's level 15 and refuses a link with an amp at 7 or one without a level. It fails when the level check is dropped. Signed-off-by: Thomas Glanzmann --- sound/soc/apple/macaudio-amp-level-test.h | 52 ++++++++++++++++++++--- sound/soc/apple/macaudio-kunit.dtso | 4 ++ sound/soc/apple/macaudio.c | 36 +++++++++++++--- 3 files changed, 79 insertions(+), 13 deletions(-) diff --git a/sound/soc/apple/macaudio-amp-level-test.h b/sound/soc/apple/macaudio-amp-level-test.h index 40130b1134f952..a684c616b4a62b 100644 --- a/sound/soc/apple/macaudio-amp-level-test.h +++ b/sound/soc/apple/macaudio-amp-level-test.h @@ -2,7 +2,8 @@ /* * KUnit tests of the SN012776 amp levels: each amp's level is the second byte * of its apple,speaker-config, which the boot loader copies from the Mac's - * ADT, and the speakers stay off when any amp lacks it. + * ADT, and the speakers stay off when any amp lacks it, or under a fixed + * ceiling when any amp has another level than the ceiling was computed for. */ #include #include @@ -16,6 +17,14 @@ static struct device_node *macaudio_level_test_node(struct kunit *test, const ch return np; } +/* Whether the speakers of the codec node @name would run under @cfg */ +static bool macaudio_level_test_present(struct kunit *test, struct device *dev, + const struct macaudio_platform_cfg *cfg, + const char *name) +{ + return macaudio_sn012776_levels_present(dev, cfg, macaudio_level_test_node(test, name)); +} + /* The level is the row's second byte, its low five bits */ static void macaudio_level_from_row(struct kunit *test) { @@ -41,13 +50,41 @@ static void macaudio_levels_every_amp(struct kunit *test) { struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + const struct macaudio_platform_cfg *cfg = &macaudio_j316_cfg; + + KUNIT_ASSERT_NOT_NULL(test, dev); + KUNIT_EXPECT_TRUE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-good")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-missing")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-high")); +} + +/* A fixed ceiling, here computed at level 15, holds only at that level */ +static const struct macaudio_platform_cfg macaudio_level_ceiling_cfg = { + .amp = AMP_SN012776, + .spk_fixed_ceiling = true, + .spk_ceiling_level = 15, +}; + +static void macaudio_levels_fixed_ceiling(struct kunit *test) +{ + struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + + const struct macaudio_platform_cfg *cfg = &macaudio_level_ceiling_cfg; + KUNIT_ASSERT_NOT_NULL(test, dev); - KUNIT_EXPECT_TRUE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-good"))); - KUNIT_EXPECT_FALSE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-one-missing"))); - KUNIT_EXPECT_FALSE(test, macaudio_sn012776_levels_present(dev, - macaudio_level_test_node(test, "macaudio-kunit-codec-one-high"))); + /* One amp at 0x0f */ + KUNIT_EXPECT_TRUE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-level-15")); + /* 0x0f and 0x07: the second amp's level is not the ceiling's */ + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-good")); + KUNIT_EXPECT_FALSE(test, macaudio_level_test_present(test, dev, cfg, + "macaudio-kunit-codec-one-missing")); + KUNIT_EXPECT_FALSE(test, macaudio_sn012776_level_allowed(cfg, 14)); + KUNIT_EXPECT_FALSE(test, macaudio_sn012776_level_allowed(cfg, 16)); } /* No board table carries an SN012776 gain any more */ @@ -78,6 +115,7 @@ static struct kunit_case macaudio_level_cases[] = { KUNIT_CASE(macaudio_level_from_row), KUNIT_CASE(macaudio_level_rejects), KUNIT_CASE(macaudio_levels_every_amp), + KUNIT_CASE(macaudio_levels_fixed_ceiling), KUNIT_CASE(macaudio_level_no_table), {} }; diff --git a/sound/soc/apple/macaudio-kunit.dtso b/sound/soc/apple/macaudio-kunit.dtso index 57e001d8b15bfc..724cf4fb965d2d 100644 --- a/sound/soc/apple/macaudio-kunit.dtso +++ b/sound/soc/apple/macaudio-kunit.dtso @@ -47,4 +47,8 @@ macaudio-kunit-codec-one-high { sound-dai = <&ma_amp_high>, <&ma_amp_a>; }; + + macaudio-kunit-codec-level-15 { + sound-dai = <&ma_amp_a>; + }; }; diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index 1b3b8fd0293b63..ae4c96a816fe4d 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -187,10 +187,17 @@ struct macaudio_platform_cfg { * No voltage or current sense reaches the AP, so no protection daemon * can govern the speakers, and there is no sense PCM. "Speaker Volume * Unlock" does not apply: the SN012776 volumes stay at the floor until - * a "Speaker Protection" lease is granted, which runs them at - * safe_vol, its operating gain and their ceiling. + * the interface is on the "Speaker Protection" lease, and playback + * starts only after a grant, which runs them at safe_vol, its + * operating gain and their ceiling. */ bool spk_fixed_ceiling; + /* + * With spk_fixed_ceiling: the amp level safe_vol was computed for. At + * any other level the same volume drives the speaker differently, so + * the speakers stay off. + */ + int spk_ceiling_level; }; static const char *volume_control_names[] = { @@ -2425,11 +2432,22 @@ static int macaudio_sn012776_level(struct device_node *amp) return level <= SN012776_LEVEL_MAX ? level : -ERANGE; } +/* + * A fixed ceiling holds only at the amp level it was computed for. + */ +static bool macaudio_sn012776_level_allowed(const struct macaudio_platform_cfg *cfg, + int level) +{ + return level >= 0 && (!cfg->spk_fixed_ceiling || level == cfg->spk_ceiling_level); +} + /* * Speakers on SN012776 amps run only when every amp has its level from the - * Mac; a boot loader that does not pass it leaves them off. + * Mac, and under a fixed ceiling only at the level that ceiling was computed + * for; otherwise they stay off. */ static bool macaudio_sn012776_levels_present(struct device *dev, + const struct macaudio_platform_cfg *cfg, struct device_node *codec) { struct of_phandle_args args; @@ -2444,8 +2462,13 @@ static bool macaudio_sn012776_levels_present(struct device *dev, if (level < 0) dev_err(dev, "%pOF: %s amp level from the boot loader\n", args.np, level == -ENOENT ? "no" : "out-of-range"); + else if (!macaudio_sn012776_level_allowed(cfg, level)) + dev_err(dev, "%pOF: amp level %d, the fixed ceiling holds only at %d\n", + args.np, level, cfg->spk_ceiling_level); + else if (cfg->spk_fixed_ceiling) + dev_info(dev, "%pOF: amp level %d from the boot loader\n", args.np, level); of_node_put(args.np); - if (level < 0) + if (!macaudio_sn012776_level_allowed(cfg, level)) return false; } return n > 0; @@ -2685,11 +2708,12 @@ static int macaudio_parse_of(struct macaudio_snd_data *ma) if (ma->cfg->amp == AMP_SN012776) { struct device_node *spk_codec = of_get_child_by_name(np, "codec"); bool levels = spk_codec && - macaudio_sn012776_levels_present(card->dev, spk_codec); + macaudio_sn012776_levels_present(card->dev, ma->cfg, + spk_codec); of_node_put(spk_codec); if (!levels) { - dev_err(card->dev, "the boot loader passed no amp levels, disabling speakers\n"); + dev_err(card->dev, "no usable amp levels from the boot loader, disabling speakers\n"); continue; } } From f8a66712676000fc5073343deba301770483eb2d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:34:15 +1100 Subject: [PATCH 0605/1514] drm/asahi: m5: clear pool storage before handing the job to another VM The M5 backend has one render pair and one compute queue for all clients. When a submission comes from a VM other than the current owner, rebind_vm() maps the retained USC pool, parameter buffer and compute storage into the new VM at the same addresses. Their contents were left as the previous VM's work wrote them. Zero the data storage before another VM maps it: the USC blocks, the parameter-buffer blocks, scene scratch and discard page, and the compute operand, preemption and robustness storage. rebind_vm() only runs once the pair has fully retired, and submissions are synchronous, so no work still uses the memory. Construction leaves the same storage zeroed. The USC directory and free list, the page list and the metrics are allocator and parameter-manager state that the retained firmware records and cursors refer to. They are kept unchanged. A same-VM resubmission does not clear anything. Add a host test that runs the production hand-over against mocks and checks every data object is zero when the next VM maps it, with the previous code and each clear removed as mutants. Signed-off-by: Ryan Murray --- .../drm/asahi/m5/resources/graphics_job.rs | 12 +- .../drm/asahi/m5/resources/graphics_usc.rs | 10 +- .../asahi/m5/resources/parameter_buffer.rs | 11 +- tools/asahi/m5-client-handoff-tests.py | 273 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 5 files changed, 303 insertions(+), 4 deletions(-) create mode 100644 tools/asahi/m5-client-handoff-tests.py diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs index 0245811e9b5dbe..c21d700c8ef362 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs @@ -8,6 +8,7 @@ use super::parameter_buffer::{M5ParameterBuffer, BLOCK_BYTES, PAGE_LIST_BYTES, P use super::target_memory::M5TargetMemory; use crate::{driver::AsahiDrmDevice, m5::render_desc, m5::render, mmu}; use crate::m5::completion::MAX_GRAPHICS_GENERATION; +use core::sync::atomic::{fence, Ordering}; use kernel::prelude::*; const HIGH: u64 = 0xffff_fc20_c100_0000; @@ -271,8 +272,9 @@ impl M5GraphicsJob { /// for the new VM and the pools are aliased into it. The previous VM's /// render targets are not used in the new VM: they stay cached under the /// previous VM for its next turn, and the next application frame takes or - /// allocates targets in the new VM. The caller publishes the new roots - /// before the next draw. + /// allocates targets in the new VM. Pool data storage is cleared before + /// the new VM maps it; allocator and parameter-manager state is kept. The + /// caller publishes the new roots before the next draw. pub(super) fn rebind_vm(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { if self.owns_vm(vm) { return Ok(()); } if self.scheduler_status()? != [2, 0] { return Err(EBUSY); } @@ -286,6 +288,12 @@ impl M5GraphicsJob { for alias in self.parameter_buffer.alias_into(vm)? { aliases.push(alias, GFP_KERNEL)?; } + // Compute operands and the preemption page released by the previous + // VM may still hold its data; clear them, and restore the zero + // robustness page, before another VM maps them. + self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + // Order the clears before the new roots and the next draw are published. + fence(Ordering::SeqCst); let storage = self.compute_storage.iova(); if let Some(alias) = self.compute_storage.map_alias_at_with_guards( vm, storage, mmu::PROT_GPU_SHARED_RW, 2)? { diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs index 1d5bd727ee719d..867ef48a346063 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs @@ -110,9 +110,17 @@ impl M5GraphicsUsc { /// addresses, reproducing each allocation's guard reservation, so every /// firmware record naming the directory, free list or blocks stays valid /// across a render client handoff. The returned aliases must be kept for - /// as long as that VM may submit. + /// as long as that VM may submit. The caller has verified that all work + /// using the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = crate::m5::vm_layout::auxiliary_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks released by the previous VM may still hold its shader stack + // and spill data; clear them before another VM maps them. The + // directory and free list are allocator state that the firmware's + // cursors refer to, so they are kept (see below). + for block in self.blocks.iter_mut() { + block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, size: usize, guards: usize, aliases: &mut KVec| -> Result { diff --git a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs index 3c6b955b6c799e..901c099eac795e 100644 --- a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs +++ b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs @@ -90,9 +90,18 @@ impl M5ParameterBuffer { /// Map the retained pool into another application VM at the same compact /// addresses with the original two-page guard reservations, so the /// firmware's parameter-manager records keep naming valid pages after a - /// render client handoff. + /// render client handoff. The caller has verified that all work using + /// the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks, scene scratch and the discard page released by the previous + // VM may still hold its scene data; clear them before another VM maps + // them. The page list and metrics are parameter-manager state named + // by the retained firmware records and are kept. + for object in Iterator::chain(self.blocks.iter_mut(), + [&mut self.scene_scratch, &mut self.discard]) { + object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, aliases: &mut KVec| -> Result { let end = object.iova() diff --git a/tools/asahi/m5-client-handoff-tests.py b/tools/asahi/m5-client-handoff-tests.py new file mode 100644 index 00000000000000..0ebd1c116441d0 --- /dev/null +++ b/tools/asahi/m5-client-handoff-tests.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the production M5 render-job handoff with mock mappings. + +M5GraphicsJob::rebind_vm, M5GraphicsMemory::rebind and both pools' +alias_into must clear the data storage the previous VM used (USC blocks, +parameter-buffer blocks, scene scratch, discard page, compute storage) before +another VM maps it, keep the allocator and parameter-manager state the +firmware refers to (USC directory and free list, page list, metrics), clear +nothing for a same-VM resubmission and nothing before full retirement. + +--mutations also runs the unfixed source and each clear removed; every one +must be killed. +""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +LINUX = Path(__file__).resolve().parents[2] +RESOURCES = 'drivers/gpu/drm/asahi/m5/resources/' +FILES = {'usc': 'graphics_usc.rs', 'pb': 'parameter_buffer.rs', + 'memory': 'graphics_memory.rs', 'job': 'graphics_job.rs'} +BASE = 'c5e25e0925351' + + +def item(source, signature): + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end].replace('pub(super) ', '') + + +def current(): + return {key: (LINUX / RESOURCES / name).read_text() for key, name in FILES.items()} + + +def original(): + return {key: subprocess.run(['git', '-C', str(LINUX), 'show', f'{BASE}:{RESOURCES}{name}'], + check=True, capture_output=True, text=True).stdout + for key, name in FILES.items()} + + +PRELUDE = r''' +#![allow(warnings)] +use std::cell::RefCell; +use std::sync::atomic::{fence, Ordering}; +type Error = i32; +type Result = core::result::Result; +const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const ERANGE: i32 = -34; +const EFAULT: i32 = -14; const EBUSY: i32 = -16; const ENOTSUPP: i32 = -524; +const GFP_KERNEL: () = (); +macro_rules! dev_dbg { ($($t:tt)*) => {} } +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl core::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +mod mmu { + pub type Prot = u32; + pub const PROT_GPU_SHARED_RW: Prot = 3; + pub const UAT_PGSZ: usize = 0x4000; + pub struct KernelMapping(pub &'static str, pub u64); + pub struct VmJobGuard(pub u64); + #[derive(Clone)] + pub struct Vm(pub u64); + impl Vm { + pub fn id(&self) -> u64 { self.0 } + pub fn kernel_range(&self) -> core::ops::Range { 0x10_0000_0000..0x20_0000_0000 } + pub fn retain_job(&self) -> super::Result { Ok(VmJobGuard(self.0)) } + } + pub struct M5ExecutionContext { pub vm: Vm } + impl M5ExecutionContext { + pub fn rebind(&mut self, vm: &Vm) -> super::Result { self.vm = vm.clone(); Ok(()) } + pub fn vm(&self) -> &Vm { &self.vm } + pub fn context_id(&self) -> u8 { 3 } + pub fn roots(&self) -> [u64; 2] { [0, 0] } + } +} +mod m5 { pub mod vm_layout { + pub fn compact_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } + pub fn auxiliary_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } +} } +use m5::vm_layout; +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } +thread_local! { static MAPS: RefCell> = RefCell::new(Vec::new()); } +struct MappedObject { name: &'static str, bytes: Vec, iova: u64, logical_size: usize, home: u64 } +impl MappedObject { + fn new(name: &'static str, iova: u64, logical_size: usize) -> Self { + Self { name, bytes: vec![0; 256], iova, logical_size, home: 1 } + } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { f(&mut self.bytes) } + fn map_alias_at_with_guards(&mut self, vm: &mmu::Vm, address: u64, _: mmu::Prot, _: usize) + -> Result> { + let zero = self.bytes.iter().all(|b| *b == 0); + MAPS.with(|m| m.borrow_mut().push((self.name, vm.id(), zero))); + if vm.id() == self.home { return if address == self.iova { Ok(None) } else { Err(EINVAL) }; } + Ok(Some(mmu::KernelMapping(self.name, vm.id()))) + } +} +// graphics_usc.rs +const DIRECTORY_ENTRIES: usize = 0x80000; +const BLOCK_BYTES: usize = 0x20_0000; +const BLOCK_COUNT: usize = 19; +struct M5GraphicsUsc { directory: MappedObject, freelist: MappedObject, blocks: KVec } +impl M5GraphicsUsc { + fn validate_mappings(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@USC@@ +} +// parameter_buffer.rs +struct M5ParameterBuffer { blocks: [MappedObject; 3], page_list: MappedObject, metrics: MappedObject, + scene_scratch: MappedObject, discard: MappedObject } +impl M5ParameterBuffer { + fn validate(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@PB@@ +} +// graphics_memory.rs +struct M5GraphicsMemory { context: mmu::M5ExecutionContext, user_mappings: Option, + pages: KVec, usc: M5GraphicsUsc, output_first: Option } +impl M5GraphicsMemory { + fn vm(&self) -> &mmu::Vm { self.context.vm() } +@@MEMORY@@ +} +// graphics_job.rs +struct M5GraphicsJob { program: M5GraphicsMemory, parameter_buffer: M5ParameterBuffer, + compute_storage: MappedObject, vm_aliases: KVec, generation: u32, + status: [u32; 2], stamps: [u32; 5] } +impl M5GraphicsJob { + fn scheduler_status(&mut self) -> Result<[u32; 2]> { Ok(self.status) } + fn progress(&mut self) -> Result<[u32; 5]> { Ok(self.stamps) } +@@OWNS@@ +@@JOB@@ +} +const DATA: [&str; 25] = ["usc0", "usc1", "usc2", "usc3", "usc4", "usc5", "usc6", "usc7", "usc8", + "usc9", "usc10", "usc11", "usc12", "usc13", "usc14", "usc15", "usc16", "usc17", "usc18", + "pb0", "pb1", "pb2", "scene", "discard", "compute"]; +const KEPT: [&str; 4] = ["directory", "freelist", "page_list", "metrics"]; +fn objects(job: &mut M5GraphicsJob) -> Vec<&mut MappedObject> { + let usc = &mut job.program.usc; + let pb = &mut job.parameter_buffer; + let mut out: Vec<&mut MappedObject> = vec![&mut usc.directory, &mut usc.freelist]; + out.extend(usc.blocks.0.iter_mut()); + out.extend(pb.blocks.iter_mut()); + out.extend([&mut pb.page_list, &mut pb.metrics, &mut pb.scene_scratch, &mut pb.discard, + &mut job.compute_storage]); + out +} +fn fill(job: &mut M5GraphicsJob, value: u8) { + for object in objects(job) { object.bytes.fill(value); } +} +fn snapshot(job: &mut M5GraphicsJob) -> Vec<(&'static str, Vec)> { + objects(job).into_iter().map(|o| (o.name, o.bytes.clone())).collect() +} +fn handoff(job: &mut M5GraphicsJob, vm: u64, value: u8) { + MAPS.with(|m| m.borrow_mut().clear()); + fill(job, value); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(vm)).unwrap(); + let maps = MAPS.with(|m| m.borrow().clone()); + for name in DATA.iter() { + let entry = maps.iter().find(|(n, v, _)| n == name && *v == vm) + .unwrap_or_else(|| panic!("{} not mapped into vm {}", name, vm)); + assert!(entry.2, "{} still holds the previous VM data when vm {} maps it", name, vm); + } + for object in objects(job) { + if KEPT.contains(&object.name) { + assert!(object.bytes.iter().all(|b| *b == value), "{} allocator state must be kept", object.name); + } + } + assert!(job.owns_vm(&mmu::Vm(vm))); +} +fn main() { + let mut iova = 0x10_0000_0000u64; + let mut next = |size: usize| { let at = iova; iova += (size as u64 + 0xc000 + 0x7fff) & !0x7fff; at }; + let usc_blocks = (0..BLOCK_COUNT).map(|i| MappedObject::new(DATA[i], next(BLOCK_BYTES), BLOCK_BYTES)).collect(); + let usc = M5GraphicsUsc { + directory: MappedObject::new("directory", next(DIRECTORY_ENTRIES * 8), DIRECTORY_ENTRIES * 8), + freelist: MappedObject::new("freelist", next(0x4000), 0x4000), blocks: KVec(usc_blocks) }; + let pb = M5ParameterBuffer { + blocks: [MappedObject::new("pb0", next(0x80000), 0x80000), MappedObject::new("pb1", next(0x80000), 0x80000), + MappedObject::new("pb2", next(0x80000), 0x80000)], + page_list: MappedObject::new("page_list", next(0x1c000), 0x1c000), + metrics: MappedObject::new("metrics", next(0x4000), 0x4000), + scene_scratch: MappedObject::new("scene", next(0x4000), 0x4000), + discard: MappedObject::new("discard", next(0x8000), 0x8000) }; + let mut job = M5GraphicsJob { + program: M5GraphicsMemory { context: mmu::M5ExecutionContext { vm: mmu::Vm(1) }, + user_mappings: None, pages: KVec::new(), usc, output_first: None }, + parameter_buffer: pb, compute_storage: MappedObject::new("compute", next(0x28000), 0x28000), + vm_aliases: KVec::new(), generation: 7, status: [2, 0], stamps: [2, 0x700, 0, 0x700, 0] }; + // Client 1 (first owner) hands to client 2, which hands back, then to 3. + handoff(&mut job, 2, 0xa5); + assert_eq!(job.vm_aliases.len(), DATA.len() + KEPT.len(), "views of every pool object in vm 2"); + handoff(&mut job, 1, 0x5a); + assert!(job.vm_aliases.is_empty(), "the first owner keeps its own mappings"); + handoff(&mut job, 3, 0x3c); + // Same-VM resubmission: no clear. + fill(&mut job, 0x77); + let before = snapshot(&mut job); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(3)).unwrap(); + assert!(before == snapshot(&mut job), "same-VM resubmission must not clear"); + // Not retired: nothing is cleared while firmware may still use the pools. + for (status, stamps) in [([1, 0], [2, 0x700, 0, 0x700, 0]), ([2, 0], [2, 0x600, 0, 0x700, 0]), + ([2, 0], [2, 0x700, 0, 0x600, 0]), ([2, 1], [2, 0x700, 0, 0x700, 0])] { + job.status = status; job.stamps = stamps; + assert_eq!(job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(4)).err(), Some(EBUSY)); + assert!(before == snapshot(&mut job), "busy job storage must be untouched"); + } + println!("PASS 3 client handoffs clear 25 data objects before the next VM maps them; allocator state kept; same-VM and 4 unretired cases untouched"); +} +''' + + +def fixture(src): + return (PRELUDE.replace('@@USC@@', item(src['usc'], 'pub(super) fn alias_into(')) + .replace('@@PB@@', item(src['pb'], 'pub(super) fn alias_into(')) + .replace('@@MEMORY@@', item(src['memory'], 'pub(super) fn rebind(')) + .replace('@@OWNS@@', item(src['job'], 'pub(super) fn owns_vm(')) + .replace('@@JOB@@', item(src['job'], 'pub(super) fn rebind_vm('))) + + +def run(tmp, name, code): + path = Path(tmp) / (name + '.rs') + binary = path.with_suffix('') + path.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), '-o', str(binary)], + check=True) + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def drop(src, key, text): + assert text in src[key], (key, text) + return {**src, key: src[key].replace(text, '')} + + +def main(): + src = current() + mutations = [ + ('unfixed-' + BASE, original), + ('no-usc-block-clear', lambda: drop(src, 'usc', 'block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-parameter-buffer-clear', lambda: drop(src, 'pb', 'object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-compute-storage-clear', lambda: drop(src, 'job', + 'self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ] + with tempfile.TemporaryDirectory(prefix='m5-client-handoff-') as tmp: + result = run(tmp, 'fixed', fixture(src)) + assert result.returncode == 0, result.stderr + print(result.stdout.strip()) + if '--mutations' not in sys.argv[1:]: + return + killed = 0 + for name, make in mutations: + result = run(tmp, name.replace('-', '_'), fixture(make())) + assert result.returncode != 0 and 'still holds the previous VM data' in result.stderr, \ + (name, result.stdout, result.stderr) + killed += 1 + print('PASS mutant killed:', name) + print(f'PASS {killed}/{len(mutations)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..ef6b042b17881d 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -206,6 +206,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', 'quarantine', 'epoch', 'cutoff', 'whole-batch', 'legacy-format', 'read-drain'), out()), From 01455ee8bbd3782bee57c18a01db3e04892634e0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:34:59 +1100 Subject: [PATCH 0606/1514] drm/asahi: g18: clear client storage when the render or compute job changes VM The single application render job and the application compute job are handed from one client VM to the next by re-aliasing their objects at the same addresses. Only the render targets were cleared, so PB blocks (including grown ones), the scene scratch, the discard page and the USC scratch blocks of the render and compute pools still held what the previous VM's work left there. Once the job has retired and the previous VM's views are dropped, clear that storage before another VM maps it. Allocator structures, the PB block table, page list and ring cursors, and the pool directory, block list and descriptor are kept as they are: they hold only the owners' addresses and their cursors are owned by the PM/USC. A replacement compute pool that retains the old scratch objects inherits the last VM. The same VM again clears nothing. The job context only reads the command graph (the RCE register lists), so map the client view read-only, as g17 maps M5 command storage. Add a host test that runs the production paths against a model of the mappings, with mutants including the previous code. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g18/buffer/pool.rs | 23 + .../drm/asahi/g18/buffer/pool_application.rs | 1 + .../asahi/g18/buffer/pool_shared_compute.rs | 2 + .../asahi/g18/queue/graphics_application.rs | 23 + .../g18/runtime/graphics_job_application.rs | 11 +- tools/asahi/g18-client-handoff-tests.py | 483 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 7 files changed, 543 insertions(+), 1 deletion(-) create mode 100644 tools/asahi/g18-client-handoff-tests.py diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool.rs b/drivers/gpu/drm/asahi/g18/buffer/pool.rs index f080fecd7afc33..2c70e112d7f97c 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool.rs @@ -86,6 +86,9 @@ pub(crate) struct G18UmaPoolMemory { low_bias: u64, hardware_slot: u32, block_stride: u64, + /// The client VM an application path last aliased the scratch blocks + /// into; None before the first. + client_vm: Option, } impl G18UmaPoolMemory { @@ -109,10 +112,29 @@ impl G18UmaPoolMemory { || !self.process_aliases.is_empty() { return Err(EINVAL); } + self.clear_scratch_for(vm)?; self.alias_into_process(dev, uat, vm)?; Ok(core::mem::replace(&mut self.process_aliases, KVec::new())) } + /// The scratch blocks hold the private memory of the last client VM's + /// threads. Storage released by that VM may still hold its data; clear + /// it before another VM maps it (construction leaves it zero). The + /// directory, block list, state and descriptor are kept: they name the + /// pool's own objects and the hardware owns their allocation cursors. + /// The caller proved the pool's last job retired and dropped the + /// previous VM's aliases. The same VM again clears nothing. + fn clear_scratch_for(&mut self, vm: &mmu::Vm) -> Result { + if self.client_vm.is_some_and(|id| id != vm.id()) { + for block in self.scratch.iter_mut() { + block.with_bytes_mut(|bytes| { bytes.fill(0); Ok(()) })?; + } + fence(Ordering::SeqCst); + } + self.client_vm = Some(vm.id()); + Ok(()) + } + /// The retained backing plan; application compute bounds its SMA pair by it. pub(crate) fn scratch_plan(&self) -> Option { self.scratch_plan @@ -283,6 +305,7 @@ impl G18UmaPoolMemory { descriptor_loaded: false, render: false, low_bias, hardware_slot, block_stride: if low_bias == 0 { BLOCK_DATA_STRIDE } else { 0x300000 }, + client_vm: None, }) } diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs index 3e1e012966a0c5..cd27b47a180160 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs @@ -23,6 +23,7 @@ impl G18UmaPoolMemory { pub(crate) fn application_aliases(&mut self, uat: &mmu::Uat, vm: &mmu::Vm) -> Result> { if !self.render || self.scratch_plan.is_none() {return Err(EINVAL);} + self.clear_scratch_for(vm)?; let mut aliases=KVec::new(); for (index,page) in self.directory.iter_mut().enumerate() { let address=DIRECTORY_BASE+self.layout.page_offset(index as u32).ok_or(EINVAL)?; diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs index f8e9a17cf7817d..6540fe263cb535 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs @@ -70,6 +70,8 @@ impl G18UmaPoolMemory { let mut pool = Self::new_layout(dev, uat, high.clone(), 12, true, false, bias, 1, G18_COMPUTE_BLOCK_BYTES)?; pool.prepare_shared_compute_retaining(dev, uat, high, plan, Some(self))?; + // The retained scratch objects carry the last client's data along. + pool.client_vm = self.client_vm; Ok(pool) } diff --git a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs index 6420db72320253..5efb185812dfd4 100644 --- a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs +++ b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs @@ -242,6 +242,29 @@ impl G18ParameterBuffer { Ok(aliases) } + /// Storage the previous VM's renders wrote (every block, grown ones + /// included, the scene scratch and the discard page) may still hold its + /// data; clear it before another VM maps it. Construction leaves it zero. + /// The page list, block table, scene records, metrics and ring cursors + /// are kept: they name the PB's own objects and the PM owns their + /// progress. The caller proved the render retired and dropped the + /// previous VM's aliases. + pub(crate) fn clear_client_data(&mut self) -> Result { + let clear = |object: &mut MappedObject| { + object.with_bytes_mut(|bytes| { + bytes.fill(0); + Ok(()) + }) + }; + for block in self.blocks.iter_mut() { + clear(block)?; + } + clear(&mut self.scene_scratch)?; + clear(&mut self.discard)?; + fence(Ordering::SeqCst); + Ok(()) + } + /// Blocks backed so far: the initial ones plus every growth. fn backed_blocks(&self) -> Result { let bytes: usize = self.blocks.iter().map(|block| block.logical_size).sum(); diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index be1f057c31be08..61390620e20dac 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -89,6 +89,10 @@ impl ApplicationJob { if remap { self.job.program.rebind_retired(&self.storage)?; self.user_aliases.clear();self.pool_aliases.clear(); + // The last frame retired (checked above) and the previous VM's + // views are gone: clear what its renders left before this VM + // maps the PB. The pool scratch is cleared as it is aliased. + if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;} } if self.generation==0 { let alias=self.job.graph.map_alias_at(uat.kernel_lower_vm(),va::GRAPHICS_JOB_LOW, @@ -110,8 +114,13 @@ impl ApplicationJob { } } if remap { + // The job context only reads the commands' register lists here + // (the RCE addresses encode_into places at GRAPHICS_JOB_LOW); + // firmware uses GRAPHICS_JOB_HIGH. The client view is read-only, + // as g17 maps M5 command storage, so the client's own GPU work + // cannot rewrite commands after the kernel encoded and audited them. self.user_aliases.push(self.job.graph.map_alias_at(vm,va::GRAPHICS_JOB_LOW, - mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?; + mmu::PROT_GPU_SHARED_RO)?,GFP_KERNEL)?; let aliases=self.job.parameter_buffer.application_aliases(vm)?; for alias in aliases {self.user_aliases.push(alias,GFP_KERNEL)?;} } diff --git a/tools/asahi/g18-client-handoff-tests.py b/tools/asahi/g18-client-handoff-tests.py new file mode 100644 index 00000000000000..13f55ea292f13c --- /dev/null +++ b/tools/asahi/g18-client-handoff-tests.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 client hand-over of the application render and compute owners against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 ApplicationJob and ApplicationJob::prepare() +(runtime/graphics_job_application.rs), G18ParameterBuffer::application_aliases() and +clear_client_data() (queue/graphics_application.rs), G18UmaPoolMemory::application_aliases() +(buffer/pool_application.rs), compute_application_aliases() and clear_scratch_for() +(buffer/pool.rs) and replacement_shared_compute() (buffer/pool_shared_compute.rs), and compiles +them with host rustc against a model of the GEM objects and their GPU mappings. The model's GPU +work of a VM writes the VM's id through each of its writable views of the PB blocks, scene +scratch, discard page, render targets and pool scratch blocks. + +What it shows: +- when the render job goes to another VM, no live view of that VM reaches a byte another VM + wrote, PB blocks added by growth included, and the previous VM's views are gone first; +- the same VM again, and a target regrowth of the same VM, clear nothing; +- the client view of the command graph is read-only; +- the compute pool's scratch blocks are cleared when another VM is given them, also when a + replacement pool retains the old scratch objects, and not for the same VM; +- source checks: both owners refuse a job that has not retired before any of this, the session + aliases the render pool only after prepare(), and the compute attempt drops the previous + aliases before it aliases the pool. + +--mutations runs every mutant, including the code at c5e25e0925351 (before the fix), and +requires each to fail. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G18 = 'drivers/gpu/drm/asahi/g18/' +PREPARE = G18 + 'runtime/graphics_job_application.rs' +PB = G18 + 'queue/graphics_application.rs' +POOL = G18 + 'buffer/pool.rs' +POOL_APP = G18 + 'buffer/pool_application.rs' +POOL_SHARED = G18 + 'buffer/pool_shared_compute.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +BASE = 'c5e25e0925351' + + +def item(source, signature, optional=False): + if optional and signature not in source: + return '' + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +MODEL = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::RefCell; +use std::ops::Range; +use std::rc::Rc; +use std::sync::atomic::{fence, Ordering}; +type Result = std::result::Result; +const EBUSY: i32 = 16; const EINVAL: i32 = 22; const EOVERFLOW: i32 = 75; const EFAULT: i32 = 14; +const ENOENT: i32 = 2; +#[derive(Clone, Copy)] struct Flags; +const GFP_KERNEL: Flags = Flags; +type KBox = Box; +struct KVec(Vec); +impl KVec { + fn new() -> Self { KVec(Vec::new()) } + fn push(&mut self, v: T, _: Flags) -> Result { self.0.push(v); Ok(()) } + fn clear(&mut self) { self.0.clear() } + fn len(&self) -> usize { self.0.len() } + fn is_empty(&self) -> bool { self.0.is_empty() } + fn iter(&self) -> std::slice::Iter<'_, T> { self.0.iter() } + fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { self.0.iter_mut() } +} +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +#[macro_export] +macro_rules! g18_kick_info { ($($t:tt)*) => {}; } +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } + +type Data = Rc>>; +struct Live { key: usize, vm: u64, addr: u64, prot: mmu::Prot, data: Data } +thread_local! { + static LIVE: RefCell> = RefCell::new(Vec::new()); + static NEXT: RefCell = RefCell::new(0); + static CLEARS: RefCell = RefCell::new(0); +} +mod mmu { + use super::*; + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Prot { Rw, Ro } + pub const PROT_GPU_SHARED_RW: Prot = Prot::Rw; + pub const PROT_GPU_SHARED_RO: Prot = Prot::Ro; + #[derive(Clone)] pub struct Vm { pub id: u64 } + impl Vm { + pub fn id(&self) -> u64 { self.id } + pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) } + pub fn translate_iova(&self, a: u64) -> Result { Ok(a) } + } + pub struct T8140VmJobGuard; + pub struct Uat { pub lower: Vm } + impl Uat { pub fn kernel_lower_vm(&self) -> &Vm { &self.lower } } + pub struct KernelMapping { key: usize } + impl KernelMapping { + pub fn new(vm: &Vm, addr: u64, prot: Prot, data: &Data) -> Self { + let key = NEXT.with(|n| { let mut n = n.borrow_mut(); *n += 1; *n }); + LIVE.with(|l| { + let mut l = l.borrow_mut(); + assert!(!l.iter().any(|m| m.vm == vm.id && m.addr == addr), + "VA {:#x} mapped twice in VM {}: the previous views were not dropped", addr, vm.id); + l.push(Live { key, vm: vm.id, addr, prot, data: data.clone() }); + }); + KernelMapping { key } + } + } + impl Drop for KernelMapping { + fn drop(&mut self) { LIVE.with(|l| l.borrow_mut().retain(|m| m.key != self.key)); } + } +} +struct MappedObject { data: Data, iova: u64, logical_size: usize } +impl MappedObject { + fn new(iova: u64, size: usize) -> Self { + MappedObject { data: Rc::new(RefCell::new(vec![0; size])), iova, logical_size: size } + } + fn shared(&self, iova: u64) -> Self { MappedObject { data: self.data.clone(), iova, logical_size: self.logical_size } } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { + let mut bytes = self.data.borrow_mut(); + let all_zero_before = bytes.iter().all(|&b| b == 0); + let r = f(&mut bytes[..]); + // Render targets are cleared every frame; count the hand-over clears only. + let target = (va::GRAPHICS_TARGET_OFFSET..va::GRAPHICS_TARGET_OFFSET + 0x30000).contains(&self.iova); + if !target && !all_zero_before && bytes.iter().all(|&b| b == 0) { CLEARS.with(|c| *c.borrow_mut() += 1); } + r + } + fn map_alias_at(&mut self, vm: &mmu::Vm, address: u64, prot: mmu::Prot) -> Result { + Ok(mmu::KernelMapping::new(vm, address, prot, &self.data)) + } + fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result { + if size > self.logical_size { *self.data.borrow_mut() = vec![0; size]; self.logical_size = size; } + Ok(()) + } +} +mod g18 { + pub mod address_map { pub const COMPACT_BIAS: u64 = 0x10_0000_0000; } + pub mod uapi { pub mod graphics_scratch { + #[derive(Clone, Copy)] pub struct G18RenderScratchSelection; + } } +} +mod va { + pub use crate::g18::address_map::COMPACT_BIAS; + pub const GRAPHICS_JOB_LOW: u64 = 0x70_1200_0000; + pub const GRAPHICS_TARGET_OFFSET: u64 = 0x0100_0000; +} +#[derive(Clone, Copy, Default)] +struct Params { + cycle: u64, record_index: u64, ta_hardware_buffer_id: u32, usc_flist_hardware_buffer_id: u32, + scissor_array: u64, depth_bias_array: u64, depth_buffer: u64, depth_aux_buffer: u64, + load_pipeline: u64, store_pipeline: u64, partial_load_pipeline: u64, partial_store_pipeline: u64, + target: usize, +} +#[derive(Clone, Copy, Default)] struct Controls; +struct RenderTarget { width: u32, height: u32 } +struct G18ApplicationRender { + parameters: Params, controls: Controls, + scratch: Option, + target: RenderTarget, vdm_base: u64, +} +mod assembly { + pub struct Plan { pub offsets: [u64; 3], pub sizes: [usize; 3] } + pub fn target_plan(p: &super::Params) -> Option { + Some(Plan { offsets: [0, 0x10000, 0x20000], sizes: [p.target; 3] }) + } + pub fn apply_target_plan(_: &mut super::Params, _: &Plan) {} + pub const TARGET_NAMES: [&str; 3] = ["a", "b", "c"]; +} +mod regs { pub fn initialize_g18_deflake(_: &mut [u8], _: u32, _: u32) -> Option<()> { Some(()) } } +#[derive(Clone, Copy)] struct Frame { generation: u32 } +impl Frame { fn new(generation: u32) -> Option { (generation != 0).then_some(Frame { generation }) } } +#[derive(Clone, Copy)] struct WalkKey; +struct Program { vm: mmu::Vm } +impl Program { + fn matches_vm(&self, vm: &mmu::Vm) -> bool { self.vm.id == vm.id } + fn rebind_retired(&mut self, vm: &mmu::Vm) -> Result { self.vm = vm.clone(); Ok(()) } +} +struct G18PbCommandFields { pb_slot: u32 } +#[derive(Clone, Copy)] +struct G18PbAddresses { page_list_low: u64, page_list_row: u64, metrics_low: u64, scene_scratch_low: u64, discard_low: u64 } +const PB_BLOCKS_LOW: u64 = 0x70_2000_0000; +const PB_BLOCK: u64 = 0x80000; +struct G18ParameterBuffer { + page_list: MappedObject, metrics: MappedObject, scene_scratch: MappedObject, + discard: MappedObject, blocks: KVec, addresses: G18PbAddresses, +} +impl G18ParameterBuffer { + fn application_scene(&mut self, _: Option<&[u8; 0x80]>) -> Result<[u8; 0x80]> { Ok([0; 0x80]) } + fn scene_cycle(&self) -> u64 { 0 } + fn metrics_record(&self) -> u64 { 0 } + fn command_fields(&self) -> G18PbCommandFields { G18PbCommandFields { pb_slot: 0 } } +@@PB@@ +} +struct G18GraphicsJob { + program: Program, targets: KVec, aliases: KVec, + graph: MappedObject, parameter_buffer: G18ParameterBuffer, parameters: Params, + controls: Controls, signals: MappedObject, encoded: Option<()>, +} +impl G18GraphicsJob { fn context_id(&self) -> u8 { 3 } } +@@JOB@@ +impl ApplicationJob { + fn encode_application(&mut self, _: &AsahiDrmDevice, _: Frame) -> Result { Ok(()) } + fn retired(&mut self) { self.retired = true; self.guard = None; } +@@PREPARE@@ +} +const DIRECTORY_BASE: u64 = 0x70_0200_0000; +const BLOCK_LIST_BASE: u64 = 0x70_0400_0000; +const BLOCK_DATA_BASE: u64 = 0x70_0500_0000; +const BLOCK_DATA_STRIDE: u64 = 0x20_0000; +const G18_COMPUTE_BLOCK_BYTES: u64 = 0x20_0000; +struct Layout; +impl Layout { fn page_offset(&self, i: u32) -> Option { Some(u64::from(i) * 0x4000) } } +#[derive(Clone, Copy)] struct G18ComputePlan; +struct G18UmaPoolMemory { + process_aliases: KVec, scratch: KVec, scratch_plan: Option<()>, + directory: KVec, block_list: MappedObject, layout: Layout, encoded: bool, + descriptor_loaded: bool, render: bool, low_bias: u64, hardware_slot: u32, client_vm: Option, +} +impl G18UmaPoolMemory { + fn model(render: bool, low_bias: u64, blocks: usize) -> Self { + let mut scratch = KVec::new(); + for i in 0..blocks { let _ = scratch.push(MappedObject::new(0x1000 * i as u64, 64), GFP_KERNEL); } + let mut directory = KVec::new(); + let _ = directory.push(MappedObject::new(0, 64), GFP_KERNEL); + G18UmaPoolMemory { process_aliases: KVec::new(), scratch, scratch_plan: Some(()), directory, + block_list: MappedObject::new(0, 64), layout: Layout, encoded: true, descriptor_loaded: true, + render, low_bias, hardware_slot: 1, client_vm: None } + } + // As the production constructor: a fresh pool has no client. + fn new_layout(_: &AsahiDrmDevice, _: &mmu::Uat, _: Range, _: u32, _: bool, _: bool, + low_bias: u64, _: u32, _: u64) -> Result { + let mut pool = Self::model(false, low_bias, 0); pool.scratch_plan = None; pool.encoded = false; + pool.descriptor_loaded = false; Ok(pool) + } + // The retained scratch objects are the same memory, plus one fresh block. + fn prepare_shared_compute_retaining(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, _: Range, + _: G18ComputePlan, retained: Option<&Self>) -> Result { + for (i, old) in retained.unwrap().scratch.iter().enumerate() { + self.scratch.push(old.shared(0x10_0000 + 0x1000 * i as u64), GFP_KERNEL)?; + } + self.scratch.push(MappedObject::new(0x20_0000, 64), GFP_KERNEL)?; + self.scratch_plan = Some(()); Ok(()) + } + fn alias_into_process(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, vm: &mmu::Vm) -> Result { + let mut aliases = KVec::new(); + for (i, block) in self.scratch.iter_mut().enumerate() { + aliases.push(block.map_alias_at(vm, BLOCK_DATA_BASE + self.low_bias + i as u64 * 0x30_0000, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + } + self.process_aliases = aliases; Ok(()) + } + fn audit_render_mappings(&self, _: &mmu::Uat, _: &mmu::Vm) -> Result { Ok(0) } +@@POOL@@ +} + +/// Kernel-only addresses: kept by design (they name the PB's and pool's own objects). +fn kept(addr: u64) -> bool { + let bias = va::COMPACT_BIAS; + [0x70_3000_0000u64, 0x70_3100_0000, DIRECTORY_BASE, BLOCK_LIST_BASE, va::GRAPHICS_JOB_LOW] + .iter().any(|&a| addr == a || addr == a + bias) +} +/// The GPU work of `vm` writes its id through each writable view it has. +fn gpu_work(vm: u64) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm && m.prot == mmu::Prot::Rw && !kept(m.addr) { m.data.borrow_mut().fill(vm as u8); } + }); +} +/// No live view of `vm` may reach a byte another VM wrote. +fn exposed(vm: u64, what: &str) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm { + let data = m.data.borrow(); + assert!(data.iter().all(|&b| b == 0 || b == vm as u8), + "{}: VM {} maps {:#x}, which holds VM {}'s data", what, vm, m.addr, + data.iter().find(|&&b| b != 0 && b != vm as u8).unwrap()); + } + }); +} +fn holds(object: &MappedObject, vm: u64) -> bool { object.data.borrow().iter().all(|&b| b == vm as u8) } +fn clears() -> usize { CLEARS.with(|c| *c.borrow()) } + +fn new_job() -> Box { + let mut blocks = KVec::new(); + for i in 0..2u64 { let _ = blocks.push(MappedObject::new(PB_BLOCKS_LOW + i * PB_BLOCK, 64), GFP_KERNEL); } + let pb = G18ParameterBuffer { + page_list: MappedObject::new(0x70_3000_0000, 64), metrics: MappedObject::new(0x70_3100_0000, 64), + scene_scratch: MappedObject::new(0x70_3200_0000, 64), discard: MappedObject::new(0x70_3300_0000, 64), + blocks, addresses: G18PbAddresses { page_list_low: 0x70_3000_0000, page_list_row: 0x70_3000_0000 + va::COMPACT_BIAS, + metrics_low: 0x70_3100_0000, scene_scratch_low: 0x70_3200_0000, discard_low: 0x70_3300_0000 }, + }; + let mut targets = KVec::new(); + for offset in [0u64, 0x10000, 0x20000] { + let _ = targets.push(MappedObject::new(va::GRAPHICS_TARGET_OFFSET + offset, 64), GFP_KERNEL); + } + let job = G18GraphicsJob { program: Program { vm: mmu::Vm { id: 100 } }, targets, aliases: KVec::new(), + graph: MappedObject::new(0xffff_0000, 64), parameter_buffer: pb, parameters: Params::default(), + controls: Controls, signals: MappedObject::new(0, 0xc020), encoded: None }; + Box::new(ApplicationJob { job: Box::new(job), storage: mmu::Vm { id: 100 }, user_aliases: KVec::new(), + pool_aliases: KVec::new(), guard: None, scene: [0; 0x80], generation: 0, retired: true, + client_frames: 0, scratch: None, walked: None }) +} +fn render(target: usize) -> G18ApplicationRender { + G18ApplicationRender { parameters: Params { target, ..Params::default() }, controls: Controls, + scratch: None, target: RenderTarget { width: 8, height: 8 }, vdm_base: 0 } +} +/// submit_application: prepare, the render pool once per remap, the frame, retirement. +fn frame(job: &mut ApplicationJob, pool: &mut G18UmaPoolMemory, uat: &mmu::Uat, vm: u64, target: usize) { + let vm = mmu::Vm { id: vm }; + job.prepare(&AsahiDrmDevice, uat, &vm, &render(target)).unwrap(); + if job.pool_aliases.is_empty() { job.pool_aliases = pool.application_aliases(uat, &vm).unwrap(); } + exposed(vm.id, "render hand-over"); + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm.id && (m.addr == va::GRAPHICS_JOB_LOW) { + assert_eq!(m.prot, mmu::Prot::Ro, "the client view of the command graph must be read-only"); + } + }); + gpu_work(vm.id); + job.retired(); +} + +fn main() { + let uat = mmu::Uat { lower: mmu::Vm { id: 0 } }; + let mut job = new_job(); + let mut pool = G18UmaPoolMemory::model(true, 0, 3); + frame(&mut job, &mut pool, &uat, 1, 64); + // A firmware TVB grow request backs a block for VM 1, aliased with its other PB views. + let mut grown = MappedObject::new(PB_BLOCKS_LOW + 2 * PB_BLOCK, 64); + for at in [grown.iova(), grown.iova() + va::COMPACT_BIAS] { + let alias = grown.map_alias_at(&mmu::Vm { id: 1 }, at, mmu::PROT_GPU_SHARED_RW).unwrap(); + job.user_aliases.push(alias, GFP_KERNEL).unwrap(); + } + job.job.parameter_buffer.blocks.push(grown, GFP_KERNEL).unwrap(); + gpu_work(1); + let before = clears(); + frame(&mut job, &mut pool, &uat, 1, 64); + frame(&mut job, &mut pool, &uat, 1, 128); + assert_eq!(clears(), before, "the same VM again (also with regrown targets) must not clear the PB or pool"); + assert!(job.job.parameter_buffer.blocks.iter().all(|b| holds(b, 1)) && pool.scratch.iter().all(|b| holds(b, 1)), + "the same VM's storage must be kept"); + for vm in [2, 2, 1, 3, 2] { frame(&mut job, &mut pool, &uat, vm, 128); } + println!("PASS render: 8 frames over 3 VMs, PB growth, target regrowth; no VM sees another's PB blocks, scene scratch, discard page or pool scratch; graph view read-only; same VM clears nothing"); + + let mut compute = G18UmaPoolMemory::model(false, 0x4000_0000, 2); + let mut owner = |pool: &mut G18UmaPoolMemory, vm: u64| { + let aliases = pool.compute_application_aliases(&AsahiDrmDevice, &uat, &mmu::Vm { id: vm }).unwrap(); + exposed(vm, "compute hand-over"); + gpu_work(vm); + aliases // the attempt keeps them until the next submission clears job.aliases + }; + let a = owner(&mut compute, 1); drop(a); + let before = clears(); + let a = owner(&mut compute, 1); drop(a); + assert_eq!(clears(), before, "the same VM's compute again must not clear the pool"); + assert!(compute.scratch.iter().all(|b| holds(b, 1))); + let a = owner(&mut compute, 2); drop(a); + let mut replacement = compute.replacement_shared_compute(&AsahiDrmDevice, &uat, 0..1, G18ComputePlan).unwrap(); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 3); drop(a); + println!("PASS compute: 6 submissions over 3 VMs and a replacement pool retaining the scratch objects; no VM sees another's scratch; same VM clears nothing"); +} +''' + + +def build(read): + prepare_src = read(PREPARE) + pb_src = read(PB) + pool_src = read(POOL) + job = item(prepare_src, 'pub(crate) struct ApplicationJob {') + prepare = item(prepare_src, 'pub(crate) fn prepare(') + pb = (item(pb_src, 'pub(crate) fn application_aliases(&mut self, vm: &mmu::Vm)') + '\n' + + item(pb_src, 'pub(crate) fn clear_client_data(', optional=True)) + pool = (item(read(POOL_APP), 'pub(crate) fn application_aliases(&mut self, uat') + '\n' + + item(pool_src, 'pub(crate) fn compute_application_aliases(') + '\n' + + item(pool_src, 'fn clear_scratch_for(', optional=True) + '\n' + + item(read(POOL_SHARED), 'pub(crate) fn replacement_shared_compute(')) + return (MODEL.replace('@@JOB@@', job).replace('@@PREPARE@@', prepare) + .replace('@@PB@@', pb).replace('@@POOL@@', pool)) + + +def sub(old, new): + def apply(code): + assert old in code, 'mutation anchor missing: ' + old + return code.replace(old, new, 1) + return apply + + +MUTATIONS = { + 'pb-clear-dropped': sub('if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;}', ''), + 'pb-clear-every-remap': sub('if new_client && self.generation!=0 {', 'if self.generation!=0 {'), + 'pb-grown-blocks-kept': sub('for block in self.blocks.iter_mut() {\n clear(block)', 'for block in self.blocks.iter_mut().take(2) {\n clear(block)'), + 'pb-scene-scratch-kept': sub('clear(&mut self.scene_scratch)?;', ''), + 'pb-discard-kept': sub('clear(&mut self.discard)?;', ''), + 'graph-view-writable': sub('va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RO)', 'va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RW)'), + 'render-pool-clear-dropped': sub('{return Err(EINVAL);}\n self.clear_scratch_for(vm)?;', '{return Err(EINVAL);}'), + 'compute-pool-clear-dropped': sub(' self.clear_scratch_for(vm)?;\n self.alias_into_process(', ' self.alias_into_process('), + 'pool-clear-every-alias': sub('self.client_vm.is_some_and(|id| id != vm.id())', 'self.client_vm.is_some()'), + 'replacement-forgets-client': sub('pool.client_vm = self.client_vm;', ''), +} + + +def source_checks(read): + prepare = item(read(PREPARE), 'pub(crate) fn prepare(') + assert prepare.index('if !self.retired {return Err(EBUSY);}') < prepare.index('clear_client_data'), 'prepare: retired first' + submit = item(read(SESSION), 'fn submit_application(') + assert submit.index('job.prepare(') < submit.index('.application_aliases(vm)'), 'session: pool aliased after prepare' + attempt = item(read(COMPUTE), 'fn prepare_application_compute_attempt(') + retired = attempt.index('if !job.retired') + dropped = attempt.index('job.aliases.clear();') + aliased = attempt.index('pool.compute_application_aliases(') + assert retired < dropped < aliased, 'compute: retired, previous aliases dropped, then the pool aliased' + print('PASS source: retirement is checked first; previous views are dropped before the pools are aliased') + + +def compile_run(code, out, name, rustc): + path = out / (name + '.rs') + path.write_text(code) + binary = out / name + built = subprocess.run(rustc + ['--edition=2021', '-O', str(path), '-o', str(binary)], + capture_output=True, text=True) + if built.returncode != 0: + raise SystemExit(f'{name}: host build failed\n{built.stderr}') + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-client-handoff-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, build(base)), (BASE + '-data-only', unchecked(build(base)))] + for name, apply in MUTATIONS.items(): + code = build(tip) + mutants.append((name, apply(code))) + killed = 0 + for name, code in mutants: + result = compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ef6b042b17881d..6d4c1b7cfd19e0 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -206,6 +206,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', From 0a4f6d6576a39c4879259de5efc295d064793555 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:54:21 +1100 Subject: [PATCH 0607/1514] drm/asahi: g18: fail a job refused before publication alone Every error a submission met after admission ended the firmware session: an address the client unmapped after admission, its VM closed, or a render target allocation it sized made submit_application() return Failure::Fatal, and no client could submit again until reboot. ApplicationJob::prepare() now commits the frame (guard, generation, retired) only after its last fallible step, so an error leaves the job retired and the next prepare() rebuilds what this one changed; the first frame's kernel alias is made once. Nothing of a render reaches the firmware before prepare() returns. A prepare error that leaves the job unpublished is a new JobFailure::Refused: the submitter gets its errno, the session and the path keep serving and the client's VM is not poisoned. The compute path does the same when the failed preparation left its owner retired with no process, command or context published. Anything else, and any error on a crashed firmware, stays fatal. Also correct the documented defaults of the g18_admit_* parameters, which are 1. Add a host test that drives the production prepare and outcome paths against the hand-over model, with the previous code as a mutant. Signed-off-by: Ryan Murray --- .../gpu/drm/asahi/g18/boot/compute_session.rs | 12 +- drivers/gpu/drm/asahi/g18/boot/recovery.rs | 5 + drivers/gpu/drm/asahi/g18/boot/session.rs | 16 +- drivers/gpu/drm/asahi/g18/drm.rs | 6 +- .../asahi/g18/initdata/application_compute.rs | 12 + .../g18/runtime/graphics_job_application.rs | 12 +- tools/asahi/g18-job-error-tests.py | 313 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 8 files changed, 368 insertions(+), 9 deletions(-) create mode 100644 tools/asahi/g18-job-error-tests.py diff --git a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs index 8af55d934298f9..a5c7d8b40900ba 100644 --- a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs @@ -8,8 +8,16 @@ impl G18Session { translated: &crate::g18::uapi::command::TranslatedComputeCommand) -> core::result::Result<(), Failure> { self.poll_idle_faults("application compute prepare")?; - let (command, pool, generation, knobs) = self.memory.as_mut().ok_or(EIO)? - .prepare_application_compute(&self.dev, vm, translated)?; + let memory = self.memory.as_mut().ok_or(EIO)?; + let (command, pool, generation, knobs) = + match memory.prepare_application_compute(&self.dev, vm, translated) { + Ok(prepared) => prepared, + // A refusal that left the owner retired and nothing + // published fails this job only. + Err(error) => return Err(if memory.application_compute_unpublished() { + Failure::Job(JobFailure::Refused(error)) + } else { Failure::Fatal(error) }), + }; if generation == 1 { self.queue_probe.as_mut().ok_or(EIO)?.prepare_initial_context(command.context_id)?; for phase in 1..=3 { diff --git a/drivers/gpu/drm/asahi/g18/boot/recovery.rs b/drivers/gpu/drm/asahi/g18/boot/recovery.rs index fca20c69a30ca9..fbdb4036c3f112 100644 --- a/drivers/gpu/drm/asahi/g18/boot/recovery.rs +++ b/drivers/gpu/drm/asahi/g18/boot/recovery.rs @@ -164,6 +164,11 @@ pub(super) enum JobFailure { Released, /// [`Self::Stranded`] as reported back to the submitting thread. Retained, + /// Refused while being prepared from the client's own state (its VM + /// closed, an address it names unmapped, an allocation it sized): nothing + /// of the job reached the firmware and its owner is back where the last + /// retirement left it. The session and the path keep serving. + Refused(Error), } /// How far a failed task reaches. diff --git a/drivers/gpu/drm/asahi/g18/boot/session.rs b/drivers/gpu/drm/asahi/g18/boot/session.rs index e0653fbd1b247b..cf03052bb7b81e 100644 --- a/drivers/gpu/drm/asahi/g18/boot/session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/session.rs @@ -105,6 +105,7 @@ impl ApplicationOwner { Err(Failure::Fatal(error))=>error.to_errno(), Err(Failure::Job(JobFailure::Recovered(_) | JobFailure::Unbound(..) | JobFailure::Released))=>JobOutcome::Recovered as i32, Err(Failure::Job(JobFailure::Stranded(..) | JobFailure::Retained))=>JobOutcome::Stranded as i32, + Err(Failure::Job(JobFailure::Refused(error)))=>JobOutcome::Refused as i32-error.to_errno(), } } @@ -114,6 +115,8 @@ impl ApplicationOwner { 0 => Ok(()), code if code==JobOutcome::Recovered as i32 => Err(Failure::Job(JobFailure::Released)), code if code==JobOutcome::Stranded as i32 => Err(Failure::Job(JobFailure::Retained)), + code if code>JobOutcome::Refused as i32 => + Err(Failure::Job(JobFailure::Refused(Error::from_errno(JobOutcome::Refused as i32-code)))), errno => Err(Failure::Fatal(Error::from_errno(errno))), } } @@ -125,6 +128,8 @@ impl ApplicationOwner { match result { Ok(()) => Ok(()), Err(Failure::Job(JobFailure::Released)) | Err(Failure::Job(JobFailure::Recovered(_))) => Err(EIO), + // Nothing ran: the client's VM stays usable. + Err(Failure::Job(JobFailure::Refused(error))) => Err(error), Err(Failure::Job(_)) => {if let Some(status)=vm.status(){status.record(EIO);}Err(EIO)} Err(Failure::Fatal(error)) => {if let Some(status)=vm.status(){status.record(error);}Err(error)} } @@ -137,6 +142,8 @@ const TICKET_RUNNING: i32 = 1; enum JobOutcome { Recovered = 2, Stranded = 3, + /// Plus the errno: [`JobFailure::Refused`]. + Refused = 0x1000, } impl G18Runtime for ApplicationOwner { @@ -200,6 +207,9 @@ fn log_job_failure(session:&G18Session,failure:&JobFailure) { JobFailure::Unbound(r,path,unready) => dev_err!(session.device(), "G18_APP_JOB_FAILED error={:?} recovery epoch={} host={} us={} reason={:#x} slot-mask={:#x} queues=retired unbound={} path={:?} quarantined session=live recoveries={}\n", EIO,r.epoch,r.host,r.us,r.cause.reason,r.cause.slot_mask,unready,path,recovery::recoveries()), + // The submitter's own error, returned to it: not logged above debug level. + JobFailure::Refused(error) => dev_dbg!(session.device(), + "G18_APP_JOB_REFUSED error={:?} unpublished session=live\n",error), // Only the submitting thread's summaries; the worker logs the rest. JobFailure::Released | JobFailure::Retained => {} } @@ -213,7 +223,11 @@ impl G18Session { self.application_job=Some(ApplicationJob::new(self.render_job.take().ok_or(EIO)?)?); } let job=self.application_job.as_mut().ok_or(EIO)?; - job.prepare(&self.dev,&self.uat,vm,render)?; + if let Err(error)=job.prepare(&self.dev,&self.uat,vm,render) { + // Nothing is published before prepare() commits the frame: a + // job it refused leaves the owner retired, the session serves on. + return Err(if job.unpublished() {Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}); + } if job.pool_aliases.is_empty() { job.pool_aliases=self.memory.as_mut().ok_or(EIO)?.application_aliases(vm)?; } diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index 14a726b24fc4cc..fccae19b1a722e 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -108,14 +108,14 @@ pub(crate) trait G18DrmRuntime: G18RenderJobSink { /// Adapter options fixed at registration. #[derive(Debug, Copy, Clone, Default)] pub(crate) struct G18DrmConfig { - /// Admit compute commands (module parameter `g18_admit_compute`, default 0). + /// Admit compute commands (module parameter `g18_admit_compute`, default 1). pub(crate) admit_compute: bool, /// Admit exactly the native 4x MSAA render set (module parameter - /// `g18_admit_msaa4`, default 0; msaa163). Off refuses every + /// `g18_admit_msaa4`, default 1; msaa163). Off refuses every /// multisampled render as before. pub(crate) admit_msaa4: bool, /// Admit renders carrying `DRM_ASAHI_RENDER_G18_RESOURCES` (module - /// parameter `g18_admit_graphics_scratch`, default 0). Off leaves the + /// parameter `g18_admit_graphics_scratch`, default 1). Off leaves the /// feature unadvertised and refuses the flag, so Mesa keeps refusing /// draws whose programs need a thread-private frame. pub(crate) admit_graphics_scratch: bool, diff --git a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs index 549324f6884671..28ca57d29cbd8f 100644 --- a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs +++ b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs @@ -455,6 +455,18 @@ impl G18FirmwareMemory { Ok((prepared, job.binding, generation, knobs)) } + /// Whether the compute owner is as the last retirement left it, with no + /// process, command or context published: a failed preparation that + /// leaves this true changed nothing the firmware uses. Before the owner + /// exists, its scheduler record must not be armed yet. + pub(crate) fn application_compute_unpublished(&self) -> bool { + self.compute.unpublished_idle() && match self.application_compute.as_ref() { + Some(job) => job.retired && job.guard.is_none() && job.aliases.is_empty() + && job.previous_pool.is_none() && job.previous_binding.is_none(), + None => self.scheduler.binding(0).is_err(), + } + } + /// The binding the firmware must still own before the next tag15. pub(crate) fn application_compute_previous_binding(&self) -> Result<(G18UmaPoolBinding, u32)> { let job = self.application_compute.as_ref().ok_or(EIO)?; diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index 61390620e20dac..de571e9c9f67c2 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -65,6 +65,9 @@ impl ApplicationJob { if let Some(status)=self.job.vm().status(){status.record(EIO);} } pub(crate) fn retired(&mut self) {self.retired=true;self.guard=None;} + /// No frame is committed: the last one retired and none was prepared + /// since, so the firmware holds nothing of this job beyond it. + pub(crate) fn unpublished(&self) -> bool {self.retired && self.guard.is_none()} /// One of the first frames of its client: logged even when job logging /// is sparse, so every isolated client leaves a kick/retirement pair. pub(crate) fn traced(&self) -> bool {self.client_frames<=3} @@ -94,7 +97,8 @@ impl ApplicationJob { // maps the PB. The pool scratch is cleared as it is aliased. if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;} } - if self.generation==0 { + // Once: a first frame refused after this keeps the alias. + if self.generation==0 && self.job.aliases.is_empty() { let alias=self.job.graph.map_alias_at(uat.kernel_lower_vm(),va::GRAPHICS_JOB_LOW, mmu::PROT_GPU_SHARED_RW)?; self.job.aliases.push(alias,GFP_KERNEL)?; @@ -127,8 +131,6 @@ impl ApplicationJob { // Retract even an unchanged root before publish_h1's fresh lease // publication. Retain the mappings when the actual VM is unchanged. self.job.program.rebind_retired(vm)?; - self.guard=Some(guard);self.generation=frame.generation;self.retired=false; - self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; if remap { crate::g18_kick_info!(dev.as_ref(),"G18_APP_VM frame={} vm={} context={} target={}x{} aliases={}\n", frame.generation,vm.id(),self.job.context_id(),render.target.width,render.target.height,self.user_aliases.len()); @@ -153,6 +155,10 @@ impl ApplicationJob { self.job.signals.with_bytes_mut(|out| {out[0xc000..0xc020].fill(0);Ok(())})?; self.job.encoded=None; self.encode_application(dev,frame)?; + // Commit the frame only now: until here an error leaves the job + // retired, and the next prepare() rebuilds whatever this one changed. + self.guard=Some(guard);self.generation=frame.generation;self.retired=false; + self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; Ok(()) } diff --git a/tools/asahi/g18-job-error-tests.py b/tools/asahi/g18-job-error-tests.py new file mode 100644 index 00000000000000..cbe7fe65eb5c5a --- /dev/null +++ b/tools/asahi/g18-job-error-tests.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 session's job-error classification, actual bodies, against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 JobFailure, Failure and From for +Failure (boot/recovery.rs); ApplicationOwner::outcome(), decode(), finish(), JobOutcome and the +prepare step of G18Session::submit_application() (boot/session.rs); ApplicationJob, prepare() +and unpublished() (runtime/graphics_job_application.rs, with the PB and pool bodies the hand-over +test uses, through its model); and G18FirmwareMemory::application_compute_unpublished() +(initdata/application_compute.rs). They run against a model whose client VMs can have an address +unmapped, be closed, or ask for a target larger than an allocation admits. + +What it shows: +- a render refused from the client's own state (an unmapped address it names, its VM closed, a + target allocation that fails, also on the first frame) fails that job only: its errno reaches + the submitter, the session stays live, no path is quarantined, the client's VM is not + poisoned, the job stays retired with its generation unchanged, and the next render of any + client runs; +- a prepare on a job that did not retire, and any job error on a crashed firmware, still end + the session; +- the compute owner counts as unpublished only while no process, command, context, previous + pool or held VM exists, and before it exists only while its scheduler record is unarmed; +- source checks: the compute submission classifies a failed preparation by that state, and + nothing in the render submission reaches the firmware before prepare(). + +--mutations runs every mutant, including the code at c5e25e0925351, and requires each to fail. +""" +import argparse +import importlib.util +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('g18_handoff', HERE / 'g18-client-handoff-tests.py') +handoff = importlib.util.module_from_spec(spec) +spec.loader.exec_module(handoff) +item, ROOT, BASE, G18 = handoff.item, handoff.ROOT, handoff.BASE, handoff.G18 +RECOVERY = G18 + 'boot/recovery.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE_SESSION = G18 + 'boot/compute_session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +PREPARE = handoff.PREPARE + +EXTRA = r''' +thread_local! { + static UNMAPPED: RefCell> = RefCell::new(Vec::new()); + static CLOSED: RefCell> = RefCell::new(Vec::new()); + static POISONED: RefCell> = RefCell::new(Vec::new()); + static STOPPED: RefCell = RefCell::new(false); +} +const ENOMEM: i32 = 12; const EIO: i32 = 5; +const ALLOC_LIMIT: usize = 0x10000; +type Error = i32; +trait Errno { fn to_errno(&self) -> i32; fn from_errno(errno: i32) -> Self; } +impl Errno for i32 { fn to_errno(&self) -> i32 { -*self } fn from_errno(errno: i32) -> Self { -errno } } +pub struct Status(u64); +impl Status { pub fn record(&self, _: Error) { POISONED.with(|p| p.borrow_mut().push(self.0)); } } +macro_rules! dev_err { ($($t:tt)*) => {}; } +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32}; +#[derive(Debug)] struct G18Recovery; +#[derive(Debug, Clone, Copy)] enum JobPath { Render, Compute } +impl JobPath { fn bit(&self) -> u32 { 1 << (*self as u32) } } +@@RECOVERY@@ +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Retained(Option); +impl Retained { fn stop(&mut self, _: &str) -> Result { STOPPED.with(|s| *s.borrow_mut() = true); Ok(()) } } +struct Memory; +impl Memory { fn quarantine_application_compute(&mut self) {} fn log_trace_journal(&self, _: &AsahiDrmDevice) {} } +struct G18Session { dev: AsahiDrmDevice, uat: mmu::Uat, application_job: Option>, + memory: Option, crashed: bool } +impl G18Session { + fn any_crashed(&self) -> bool { self.crashed } + fn device(&self) -> &AsahiDrmDevice { &self.dev } + fn dump_fault_evidence(&self, _: &str) {} + fn submit_prepare(&mut self, vm: &mmu::Vm, render: &G18ApplicationRender) -> core::result::Result<(), Failure> { +@@SUBMIT@@ + Ok(()) + } +} +fn log_job_failure(_: &G18Session, _: &JobFailure) {} +const TICKET_RUNNING: i32 = 1; +@@OUTCOME_ENUM@@ +struct ApplicationOwner; +impl ApplicationOwner { +@@OWNER@@ +} + +struct ComputeMemory { process: bool } +impl ComputeMemory { fn unpublished_idle(&self) -> bool { !self.process } } +struct ApplicationCompute { retired: bool, guard: Option, aliases: KVec, + previous_pool: Option<()>, previous_binding: Option<()> } +struct Scheduler { armed: bool } +impl Scheduler { fn binding(&self, _: usize) -> Result<()> { if self.armed { Ok(()) } else { Err(EINVAL) } } } +struct G18FirmwareMemory { compute: ComputeMemory, application_compute: Option>, scheduler: Scheduler } +impl G18FirmwareMemory { +@@COMPUTE@@ +} + +struct Device { session: Mutex, failed: AtomicBool, quarantined: AtomicU32 } +impl Device { + fn job(&self, f: impl FnOnce(&mut ApplicationJob) -> R) -> R { + f(self.session.lock().0.as_mut().unwrap().application_job.as_mut().unwrap()) + } + /// One render through the ticket, as submit_render: prepare, then retire on success. + fn render(&self, vm: u64, scissor: u64, target: usize, retire: bool) -> Result { + let v = mmu::Vm { id: vm }; + let mut r = render(target); + r.parameters.scissor_array = scissor; + let code = ApplicationOwner::outcome(&self.session, &self.failed, &self.quarantined, |s| s.submit_prepare(&v, &r)); + let result = ApplicationOwner::finish(&v, ApplicationOwner::decode(code)); + if result.is_ok() && retire { self.job(|j| j.retired()); } + result + } + fn live(&self) -> bool { !self.failed.load(Ordering::Acquire) && !STOPPED.with(|s| *s.borrow()) } +} +fn device(crashed: bool) -> Device { + let session = G18Session { dev: AsahiDrmDevice, uat: mmu::Uat { lower: mmu::Vm { id: 0 } }, + application_job: Some(new_job()), memory: Some(Memory), crashed }; + STOPPED.with(|s| *s.borrow_mut() = false); + Device { session: Mutex(std::sync::Mutex::new(Retained(Some(session)))), failed: AtomicBool::new(false), + quarantined: AtomicU32::new(0) } +} +fn refused(d: &Device, result: Result, errno: i32, what: &str, generation: u32) { + assert_eq!(result, Err(errno), "{}: the submitter must get the job's own errno", what); + assert!(d.live(), "{}: a client's own error must not end the session", what); + assert_eq!(d.quarantined.load(Ordering::Acquire), 0, "{}: no path may be quarantined", what); + assert!(POISONED.with(|p| p.borrow().is_empty()), "{}: nothing ran, the client's VM stays usable", what); + assert!(d.job(|job| job.unpublished() && job.generation == generation), + "{}: the refused job must stay retired at generation {}", what, generation); +} +const SCISSOR: u64 = 0x5000; + +fn main() { + let d = device(false); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(1, SCISSOR, 64, true).unwrap(); + UNMAPPED.with(|u| u.borrow_mut().push((2, SCISSOR))); + let r = d.render(2, SCISSOR, 64, true); refused(&d, r, EFAULT, "unmapped scissor", 2); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(2, SCISSOR, 64, true).unwrap(); + CLOSED.with(|c| c.borrow_mut().push(3)); + let r = d.render(3, SCISSOR, 64, true); refused(&d, r, ENOENT, "closed VM", 3); + let r = d.render(1, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation", 3); + let r = d.render(2, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation, another VM", 3); + d.render(1, SCISSOR, 64, true).unwrap(); + assert_eq!(d.job(|j| j.generation), 4); + d.render(2, SCISSOR, ALLOC_LIMIT, true).unwrap(); + println!("PASS render: unmapped address, closed VM and failed target allocation fail their job only; the session, its path and the client VMs serve on"); + + drop(d); + let d = device(false); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + let r = d.render(1, SCISSOR, 64, true); refused(&d, r, EFAULT, "first frame", 0); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(2, SCISSOR, 64, true).unwrap(); + println!("PASS render: a first frame refused after its kernel aliases were made is prepared again"); + + drop(d); + let d = device(false); + d.render(1, SCISSOR, 64, false).unwrap(); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a job that did not retire must still end the session"); + drop(d); + let d = device(true); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a crashed firmware must still end the session"); + UNMAPPED.with(|u| u.borrow_mut().clear()); + println!("PASS render: an unretired job and a crashed firmware stay fatal"); + compute(); +} +''' + +COMPUTE_MAIN = r''' +fn compute() { + let idle = || ApplicationCompute { retired: true, guard: None, aliases: KVec::new(), previous_pool: None, previous_binding: None }; + let memory = |job: Option, process: bool, armed: bool| G18FirmwareMemory { + compute: ComputeMemory { process }, application_compute: job.map(Box::new), scheduler: Scheduler { armed } }; + assert!(memory(Some(idle()), false, true).application_compute_unpublished(), "a retired idle owner is unpublished"); + assert!(memory(None, false, false).application_compute_unpublished(), "before the owner exists nothing is armed"); + for (name, m) in [ + ("bound process", memory(Some(idle()), true, true)), + ("unretired", memory(Some(ApplicationCompute { retired: false, ..idle() }), false, true)), + ("held VM", memory(Some(ApplicationCompute { guard: Some(mmu::T8140VmJobGuard), ..idle() }), false, true)), + ("previous pool", memory(Some(ApplicationCompute { previous_pool: Some(()), ..idle() }), false, true)), + ("previous binding", memory(Some(ApplicationCompute { previous_binding: Some(()), ..idle() }), false, true)), + ("armed record without owner", memory(None, false, true)), + ] { + assert!(!m.application_compute_unpublished(), "compute owner with {} must stay fatal", name); + } + println!("PASS compute: only a retired, unbound owner (or an unarmed one not yet built) makes a failed preparation a job failure"); +} +''' + + +def build(read): + code = handoff.build(read).replace('fn main() {', 'fn handoff_main() {', 1) + for old, new in [ + ('pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) }', + 'pub fn retain_t8140_job(&self) -> Result {\n' + ' if CLOSED.with(|c| c.borrow().contains(&self.id)) { Err(ENOENT) } else { Ok(T8140VmJobGuard) } }\n' + ' pub fn status(&self) -> Option { Some(Status(self.id)) }'), + ('pub fn translate_iova(&self, a: u64) -> Result { Ok(a) }', + 'pub fn translate_iova(&self, a: u64) -> Result {\n' + ' if UNMAPPED.with(|u| u.borrow().contains(&(self.id, a))) { Err(EFAULT) } else { Ok(a) } }'), + ('fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {', + 'fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {\n' + ' if size > ALLOC_LIMIT { return Err(ENOMEM); }'), + ('fn retired(&mut self) { self.retired = true; self.guard = None; }', + 'fn retired(&mut self) { self.retired = true; self.guard = None; }\n fn quarantine(&mut self) {}\n' + # The code before the fix has no such method; the model states the same property. + + (item(read(PREPARE), 'pub(crate) fn unpublished(', optional=True) + or 'fn unpublished(&self) -> bool { self.retired && self.guard.is_none() }')), + ]: + assert code.count(old) == 1, old + code = code.replace(old, new) + recovery = read(RECOVERY) + rec = '\n'.join(item(recovery, s).replace('pub(super) ', '') for s in + ('pub(super) enum JobFailure {', 'pub(super) enum Failure {', 'impl From for Failure {')) + session = read(SESSION) + submit = item(session, 'fn submit_application(') + start = submit.index('let job=self.application_job.as_mut().ok_or(EIO)?;') + end = submit.index('if job.pool_aliases.is_empty()') + owner = '\n'.join(item(session, s) for s in ('fn outcome(', 'fn decode(', 'fn finish(')) + compute = item(read(COMPUTE), 'pub(crate) fn application_compute_unpublished(', optional=True) + extra = (EXTRA.replace('@@RECOVERY@@', rec).replace('@@SUBMIT@@', submit[start:end]) + .replace('@@OUTCOME_ENUM@@', item(session, 'enum JobOutcome {')).replace('@@OWNER@@', owner) + .replace('@@COMPUTE@@', compute)) + extra += COMPUTE_MAIN if compute else 'fn compute() {}\n' + return code + extra + + +sub = handoff.sub +MUTATIONS = { + 'prepare-commits-early': lambda c: sub( + ' // Commit the frame only now: until here an error leaves the job\n' + ' // retired, and the next prepare() rebuilds whatever this one changed.\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n', '')( + sub(' self.job.program.rebind_retired(vm)?;\n', + ' self.job.program.rebind_retired(vm)?;\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n')(c)), + 'first-frame-alias-repeated': sub('if self.generation==0 && self.job.aliases.is_empty() {', 'if self.generation==0 {'), + 'refusal-always-fatal': sub('Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}', + 'Failure::Fatal(error)} else {Failure::Fatal(error)}'), + 'refusal-ignores-state': sub('if job.unpublished() {Failure::Job', 'if true {Failure::Job'), + 'refusal-lost-in-ticket': sub(' code if code>JobOutcome::Refused as i32 =>', ' code if false =>'), + 'refusal-poisons-vm': sub('Err(Failure::Job(JobFailure::Refused(error))) => Err(error),', + 'Err(Failure::Job(JobFailure::Refused(error))) => {if let Some(status)=vm.status(){status.record(error);}Err(error)}'), + 'compute-ignores-process': sub('self.compute.unpublished_idle() && match', 'match'), + 'compute-unbuilt-always': sub('None => self.scheduler.binding(0).is_err(),', 'None => true,'), + 'compute-ignores-previous-pool': sub('&& job.previous_pool.is_none() ', ''), +} + + +def source_checks(read): + compute = item(read(COMPUTE_SESSION), 'pub(super) fn submit_application_compute(') + arm = compute[compute.index('.prepare_application_compute(&self.dev, vm, translated)'):] + arm = arm[:arm.index('if generation == 1')] + assert 'memory.application_compute_unpublished()' in arm and 'Failure::Job(JobFailure::Refused(error))' in arm \ + and 'Failure::Fatal(error)' in arm, arm + submit = item(read(SESSION), 'fn submit_application(') + before = submit[:submit.index('job.prepare(')] + for word in ('send_message', 'publish', 'install_records'): + assert word not in before, 'render submission reaches the firmware before prepare: ' + word + print('PASS source: compute classifies a failed preparation by the owner state; nothing of a render is published before prepare()') + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-job-error-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = handoff.compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stdout + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + # The code before the fix with only the hand-over test's read-only graph check relaxed. + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, unchecked(build(base)))] + mutants += [(name, apply(build(tip))) for name, apply in MUTATIONS.items()] + killed = 0 + for name, code in mutants: + result = handoff.compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6d4c1b7cfd19e0..b48f571e842549 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -207,6 +207,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'g18-job-error-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', From 0ab4e6d7774a56adf9d46c3ba207614e2a2b8279 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 16:52:58 +1100 Subject: [PATCH 0608/1514] media: apple: jpeg: keep the client's colorimetry on the raw queue The raw (OUTPUT) format always came back as full-range BT.601 with the sRGB transfer function, whatever colorimetry the client asked for. GStreamer's v4l2jpegenc passes the upstream colorimetry through and gives up when S_FMT returns a different one ("Device wants 1:4:7:1 colorimetry"). The camera delivers Rec. 709 limited range, so camerabin (GNOME Snapshot) could not save a photo: encodebin picks v4l2jpegenc, negotiation fails, and the retry then trips over the buffer pool it had already set up ("Device is in streaming mode"). The engine encodes the samples as they arrive and converts neither range nor matrix, so the raw input's colorimetry is the client's to state, as for any stateful encoder, and CAPTURE already copies it. Keep what the client sets, clamp unknown enum values to the defaults, and fall back to JPEG's own full-range BT.601 only when the client gives no colorspace. That is what the software jpegenc does with the same input. Tested on a J413 (T8112) with fleet83: videotestsrc NV12 at bt709, bt601, 1:4:7:1 and jpeg through videoconvert into v4l2jpegenc, and the camera through encodebin profile=image/jpeg. Before: only 1:4:7:1 encodes and the camera path fails with "does not support bt709". After: all four encode, and the camera path writes 5/5 JPEGs at 1440x1920. Signed-off-by: Ryan Murray --- .../platform/apple/jpeg/apple-jpeg-drv.c | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c index 2a1b2b636241e9..8dc8aa933c6136 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c @@ -298,7 +298,34 @@ static const struct v4l2_m2m_ops aj_m2m_ops = { /* ---- formats ---------------------------------------------------------- */ -/* Raw input: Y rows then interleaved CbCr rows in one buffer, full range. */ +/* + * The engine encodes the samples as they arrive: it converts neither range + * nor matrix, so the colorimetry of the raw input is the client's to state, + * as for any stateful encoder, and CAPTURE reports the same. A client that + * gives none gets what JPEG itself carries, full-range BT.601. Refusing + * every other description makes clients fail: GStreamer's v4l2jpegenc + * passes the camera's colorimetry through and gives up when S_FMT returns + * another one. + */ +static void aj_fill_colorimetry(struct v4l2_pix_format_mplane *pix) +{ + if (pix->colorspace == V4L2_COLORSPACE_DEFAULT || + pix->colorspace > V4L2_COLORSPACE_DCI_P3) { + pix->colorspace = V4L2_COLORSPACE_SRGB; + pix->ycbcr_enc = V4L2_YCBCR_ENC_601; + pix->quantization = V4L2_QUANTIZATION_FULL_RANGE; + pix->xfer_func = V4L2_XFER_FUNC_SRGB; + return; + } + if (pix->ycbcr_enc > V4L2_YCBCR_ENC_SMPTE240M) + pix->ycbcr_enc = V4L2_YCBCR_ENC_DEFAULT; + if (pix->quantization > V4L2_QUANTIZATION_LIM_RANGE) + pix->quantization = V4L2_QUANTIZATION_DEFAULT; + if (pix->xfer_func > V4L2_XFER_FUNC_SMPTE2084) + pix->xfer_func = V4L2_XFER_FUNC_DEFAULT; +} + +/* Raw input: Y rows then interleaved CbCr rows in one buffer. */ static void aj_fill_raw(const struct apple_jpeg *jpeg, struct v4l2_pix_format_mplane *pix) { bool is422 = pix->pixelformat == V4L2_PIX_FMT_NV16 && @@ -319,11 +346,7 @@ static void aj_fill_raw(const struct apple_jpeg *jpeg, struct v4l2_pix_format_mp /* Chroma follows the visible luma rows; the tail covers the MCU rows. */ pix->plane_fmt[0].bytesperline = layout.bytesperline; pix->plane_fmt[0].sizeimage = layout.sizeimage; - /* JPEG carries full-range BT.601; the engine does no range conversion. */ - pix->colorspace = V4L2_COLORSPACE_SRGB; - pix->ycbcr_enc = V4L2_YCBCR_ENC_601; - pix->quantization = V4L2_QUANTIZATION_FULL_RANGE; - pix->xfer_func = V4L2_XFER_FUNC_SRGB; + aj_fill_colorimetry(pix); } /* From 3c5e2e259979749d165844f4a89cee7aac918c7a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:15:18 +1100 Subject: [PATCH 0609/1514] HID: magicmouse: play the MTP actuator firmware's own click from the host With host click feedback on (the default on every MTP Mac with an actuator node), each press and release was played at strength 0xff and softness 0x90, with one fixed waveform shape for every machine. The actuator firmware has its own click: feature reports 0x22 (press) and 0x23 (release) hold a version byte, the strength, the softness and the waveform's shape, which is exactly what the host's output report 0x53 takes. On a J713 the firmware click is press 0x23/0xa8 and release 0x14/0xa8 with a shape of its own; the fixed shape we sent is another machine's. Read on a J604 under macOS at the default (Medium) click setting, the reports hold the firmware's boot values too. Our clicks were several times stronger than that and felt firmer than macOS on every MTP Mac. Add apple_taptic_get_waveform() and apple_taptic_send_waveform() to read a firmware waveform and play a body from the host, and have hid-magicmouse play the firmware's press and release waveforms with their own strength and softness. They are read on first use and again after resume. The haptic_strength and haptic_softness module parameters still override them, and an FF effect's intensity still scales the strength. The deep click has no firmware waveform and keeps its own, as does a press or release the firmware does not report, and the SPI actuator is unchanged. Tested on a J713 with fleet81 and these modules loaded over the stock ones: the press and release are read from the firmware (0x23/0xa8, 18 bytes; 0x14/0xa8, 3 bytes) and a host press and release uploaded and played through the trackpad's FF_HAPTIC interface are taken by the actuator without errors. Stock modules restored after. Signed-off-by: Ryan Murray --- drivers/hid/hid-apple-mtp-haptic.c | 63 +++++++++++++ drivers/hid/hid-magicmouse.c | 140 ++++++++++++++++++++++------- include/linux/soc/apple/actuator.h | 17 ++++ 3 files changed, 187 insertions(+), 33 deletions(-) diff --git a/drivers/hid/hid-apple-mtp-haptic.c b/drivers/hid/hid-apple-mtp-haptic.c index 6264241a655768..60f0709a77219d 100644 --- a/drivers/hid/hid-apple-mtp-haptic.c +++ b/drivers/hid/hid-apple-mtp-haptic.c @@ -99,6 +99,69 @@ EXPORT_SYMBOL_GPL(apple_taptic_switch_modes); #define APPLE_TAPTIC_WAVEFORM_STRENGTH 2 #define APPLE_TAPTIC_WAVEFORM_MAX 64 +/* + * The click waveform the firmware plays itself while device-controlled, + * for a host that plays the same click: the host's output report 0x53 takes + * the body of feature report 0x22 (press) or 0x23 (release) unchanged, a + * version byte, the strength, the softness and then the waveform's shape, + * which differs between machines. Copies the body (without the report ID) + * into @body and returns its length. + */ +int apple_taptic_get_waveform(struct hid_device *haptic_hdev, u16 effect_type, + u8 *body, size_t size) +{ + u8 *buf __free(kfree) = NULL; + u8 report; + int len; + + switch (effect_type) { + case HID_HP_WAVEFORMPRESS & HID_USAGE: + report = APPLE_TAPTIC_PRESS_WAVEFORM; + break; + case HID_HP_WAVEFORMRELEASE & HID_USAGE: + report = APPLE_TAPTIC_RELEASE_WAVEFORM; + break; + default: + return -EINVAL; + } + + buf = kzalloc(APPLE_TAPTIC_WAVEFORM_MAX, GFP_KERNEL); + if (!buf) + return -ENOMEM; + len = hid_hw_raw_request(haptic_hdev, report, buf, + APPLE_TAPTIC_WAVEFORM_MAX, HID_FEATURE_REPORT, + HID_REQ_GET_REPORT); + if (len < 0) + return len; + /* At least the version, the strength and the softness. */ + if (len < 4 || buf[0] != report || !buf[APPLE_TAPTIC_WAVEFORM_STRENGTH]) + return -EPROTO; + if (len - 1 > size) + return -EMSGSIZE; + + memcpy(body, buf + 1, len - 1); + return len - 1; +} +EXPORT_SYMBOL_GPL(apple_taptic_get_waveform); + +/* Play a waveform body from apple_taptic_get_waveform() from the host. */ +int apple_taptic_send_waveform(struct hid_device *haptic_hdev, const u8 *body, + size_t len) +{ + u8 msg[APPLE_TAPTIC_WAVEFORM_MAX]; + int ret; + + if (len < 3 || len + 1 > sizeof(msg)) + return -EINVAL; + msg[0] = 0x53; + memcpy(msg + 1, body, len); + ret = hid_hw_raw_request(haptic_hdev, msg[0], msg, len + 1, + HID_OUTPUT_REPORT, HID_REQ_SET_REPORT); + + return ret < 0 ? ret : 0; +} +EXPORT_SYMBOL_GPL(apple_taptic_send_waveform); + static int apple_taptic_set_strength(struct hid_device *haptic_hdev, u8 report, u8 strength) { diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 4d8ffa36d77004..70648e3149cc3e 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -63,13 +63,13 @@ MODULE_PARM_DESC(report_undeciphered, "Report undeciphered multi-touch state fie /* * Waveform shaping, writable at runtime and applied on the next effect - * upload. Zero means "use the per-transport default": the MTP machines keep - * the values their firmware was tuned with, the SPI actuator in a J313 needs - * a much softer, weaker waveform. The SPI numbers were judged by feel there. + * upload. Zero means "use the default" (magicmouse_haptic_waveform()): on MTP + * the press and release follow the actuator firmware's own click, the SPI + * actuator in a J313 needs a much softer, weaker waveform. */ static u8 haptic_softness; module_param(haptic_softness, byte, 0644); -MODULE_PARM_DESC(haptic_softness, "softness of the press and release waveforms, 1-255 (0: 0xf0 on SPI, 0x90 on MTP)"); +MODULE_PARM_DESC(haptic_softness, "softness of the press and release waveforms, 1-255 (0: 0xf0 on SPI, the firmware click's on MTP)"); static u8 haptic_deep_softness; module_param(haptic_deep_softness, byte, 0644); @@ -77,7 +77,7 @@ MODULE_PARM_DESC(haptic_deep_softness, "softness of the deep-click waveform, 1-2 static u8 haptic_strength; module_param(haptic_strength, byte, 0644); -MODULE_PARM_DESC(haptic_strength, "strength at 100% intensity for press and release, 1-255 (0: 0x28 on SPI, 0xff on MTP)"); +MODULE_PARM_DESC(haptic_strength, "strength at 100% intensity for press and release, 1-255 (0: 0x28 on SPI, the firmware click's on MTP)"); static u8 haptic_deep_strength; module_param(haptic_deep_strength, byte, 0644); @@ -294,6 +294,9 @@ struct effect_job { * @haptic_button_down: The host-derived button is pressed. * @haptic_deep_down: The host-derived click is in its deep stage. * @haptic_suspended: The transport is suspending or suspended; send nothing. + * @fw_click: The MTP actuator firmware's own press and release waveforms + * (apple_taptic_get_waveform()), read on first use and again after + * resume; @len 0 when the firmware has none. * @hdev: Pointer to the underlying HID device. * @work: Workqueue to handle initialization retry for quirky devices. * @work_held: @work was pending at suspend and must run again on resume. @@ -340,6 +343,11 @@ struct magicmouse_sc { bool haptic_button_down; bool haptic_deep_down; bool haptic_suspended; + struct { + bool read; + u8 len; + u8 body[63]; + } fw_click[2]; struct hid_device *hdev; struct delayed_work work; @@ -1941,8 +1949,12 @@ static int magicmouse_switch_mode(struct input_dev *trackpad_idev, int mode) return apple_taptic_switch_modes(actuator, mode); } -static u8 magicmouse_haptic_softness(struct hid_device *hdev, bool deep); -static u8 magicmouse_haptic_strength(struct hid_device *hdev, bool deep); +static void magicmouse_haptic_waveform(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *strength, u8 *softness); +static int magicmouse_taptic_play(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 strength, u8 softness); static void magicmouse_haptic_release_mode(struct magicmouse_sc *msc); static void magicmouse_haptic_release_mode_locked(struct magicmouse_sc *msc); @@ -1988,13 +2000,13 @@ static void magicmouse_haptic_pulses(struct magicmouse_sc *msc, u16 usage, hid_info(msc->hdev, "host-driven click feedback active\n"); } - strength = magicmouse_haptic_strength(msc->hdev, deep); - softness = magicmouse_haptic_softness(msc->hdev, deep); + magicmouse_haptic_waveform(msc, actuator, usage, &strength, &softness); gap = (deep && haptic_deep_gap_ms) ? haptic_deep_gap_ms : haptic_pulse_gap_ms; for (i = 0; i < pulses; i++) { - ret = apple_taptic_send(actuator, usage, strength, softness); + ret = magicmouse_taptic_play(msc, actuator, usage, strength, + softness); if (ret) { hid_warn(msc->hdev, "click waveform failed (%d); returning click feedback to the firmware\n", @@ -2257,6 +2269,8 @@ static void magicmouse_haptic_resume(struct magicmouse_sc *msc) } msc->haptic_suspended = false; } + /* The firmware may have been restarted with other strengths. */ + memset(msc->fw_click, 0, sizeof(msc->fw_click)); if (haptic_press || magicmouse_haptic_effects_loaded(msc)) mode = HID_HAPTIC_MODE_HOST; @@ -2452,34 +2466,96 @@ static void magicmouse_battery_timer_tick(struct timer_list *t) } #if IS_ENABLED(CONFIG_HID_APPLE_MTP_HAPTIC) -static bool magicmouse_effect_is_deep(const struct ff_effect *effect) +/* + * The firmware's own click waveform for a press or release on an MTP + * actuator, or NULL. A host click plays the same waveform: macOS leaves the + * actuator with these strengths at its default (Medium) click setting, and + * the shape differs between machines. Read once, and again after resume. + */ +static const u8 *magicmouse_fw_click(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *len) { - return effect->u.haptic.hid_usage == - (APPLE_HP_WAVEFORMDEEPCLICK & HID_USAGE); + unsigned int i; + int ret; + + if (msc->hdev->bus == BUS_SPI || !actuator || + (usage != (HID_HP_WAVEFORMPRESS & HID_USAGE) && + usage != (HID_HP_WAVEFORMRELEASE & HID_USAGE))) + return NULL; + + i = usage == (HID_HP_WAVEFORMRELEASE & HID_USAGE); + if (!msc->fw_click[i].read) { + msc->fw_click[i].read = true; + ret = apple_taptic_get_waveform(actuator, usage, + msc->fw_click[i].body, + sizeof(msc->fw_click[i].body)); + msc->fw_click[i].len = ret > 0 ? ret : 0; + if (ret > 0) + hid_dbg(msc->hdev, + "%s waveform from the firmware: strength 0x%02x softness 0x%02x, %d bytes\n", + i ? "release" : "press", msc->fw_click[i].body[1], + msc->fw_click[i].body[2], ret); + else + hid_dbg(msc->hdev, "no firmware %s waveform (%d)\n", + i ? "release" : "press", ret); + } + *len = msc->fw_click[i].len; + return *len ? msc->fw_click[i].body : NULL; } -static u8 magicmouse_haptic_softness(struct hid_device *hdev, bool deep) +/* + * The strength and softness a host-played waveform uses. A module parameter + * wins; otherwise an MTP press or release takes the firmware click's own + * values (magicmouse_fw_click()). A full-scale host click felt firmer than + * macOS on every MTP Mac. The deep click has no firmware waveform and stays + * at full scale, as does a press or release the firmware does not report. + * The SPI actuator in a J313 needs a much softer, weaker waveform; its + * numbers were judged by feel there. + */ +static void magicmouse_haptic_waveform(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 *strength, u8 *softness) { - u8 configured = deep ? haptic_deep_softness : haptic_softness; + bool deep = usage == (APPLE_HP_WAVEFORMDEEPCLICK & HID_USAGE); + u8 set_strength = deep ? haptic_deep_strength : haptic_strength; + u8 set_softness = deep ? haptic_deep_softness : haptic_softness; + bool spi = msc->hdev->bus == BUS_SPI; + const u8 *fw; + u8 len; + + *strength = spi && !deep ? 0x28 : 0xff; + *softness = spi ? (deep ? 0xd0 : 0xf0) : 0x90; - if (configured) - return configured; - if (hdev->bus != BUS_SPI) - return 0x90; + fw = magicmouse_fw_click(msc, actuator, usage, &len); + if (fw) { + *strength = fw[1]; + *softness = fw[2]; + } - return deep ? 0xd0 : 0xf0; + if (set_strength) + *strength = set_strength; + if (set_softness) + *softness = set_softness; } -static u8 magicmouse_haptic_strength(struct hid_device *hdev, bool deep) +/* Play @usage: the firmware's own waveform where it has one, else ours. */ +static int magicmouse_taptic_play(struct magicmouse_sc *msc, + struct hid_device *actuator, u16 usage, + u8 strength, u8 softness) { - u8 configured = deep ? haptic_deep_strength : haptic_strength; + u8 body[sizeof(msc->fw_click[0].body)]; + const u8 *fw; + u8 len; - if (configured) - return configured; - if (hdev->bus != BUS_SPI) - return 0xff; + fw = magicmouse_fw_click(msc, actuator, usage, &len); + if (!fw) + return apple_taptic_send(actuator, usage, strength, softness); - return deep ? 0xff : 0x28; + memcpy(body, fw, len); + body[1] = strength; + body[2] = softness; + return apple_taptic_send_waveform(actuator, body, len); } static int apple_upload_effects(struct input_dev *trackpad_idev, @@ -2492,7 +2568,6 @@ static int apple_upload_effects(struct input_dev *trackpad_idev, struct effect_job *job = &msc->haptic_effects[effect->id]; unsigned long flags; u8 strength, softness; - bool deep; int ret; switch (effect->u.haptic.hid_usage) { @@ -2511,10 +2586,9 @@ static int apple_upload_effects(struct input_dev *trackpad_idev, if (!actuator) return -ENODEV; - deep = magicmouse_effect_is_deep(effect); - strength = min_t(u16, 100, effect->u.haptic.intensity) * - magicmouse_haptic_strength(trackpad_hdev, deep) / 100; - softness = magicmouse_haptic_softness(trackpad_hdev, deep); + magicmouse_haptic_waveform(msc, actuator, effect->u.haptic.hid_usage, + &strength, &softness); + strength = min_t(u16, 100, effect->u.haptic.intensity) * strength / 100; /* The actuator may have been rebound or reset since the last upload. */ ret = magicmouse_switch_mode(trackpad_idev, HID_HAPTIC_MODE_HOST); @@ -2565,7 +2639,7 @@ static void haptic_playback_worker(struct work_struct *ws) } WRITE_ONCE(job->msc->haptics->mode, HID_HAPTIC_MODE_HOST); } - if (apple_taptic_send(actuator, type, strength, softness)) + if (magicmouse_taptic_play(job->msc, actuator, type, strength, softness)) hid_warn(actuator, "cannot play the haptic effect\n"); } diff --git a/include/linux/soc/apple/actuator.h b/include/linux/soc/apple/actuator.h index 18e1bee0e266c5..2397d14e443948 100644 --- a/include/linux/soc/apple/actuator.h +++ b/include/linux/soc/apple/actuator.h @@ -22,6 +22,10 @@ static inline bool apple_taptic_is_actuator(struct hid_device *hdev) #if IS_ENABLED(CONFIG_HID_APPLE_MTP_HAPTIC) int apple_taptic_send(struct hid_device *hdev, u16 effect_type, u8 strength, u8 softness); int apple_taptic_switch_modes(struct hid_device *hdev, bool host_controlled); +int apple_taptic_get_waveform(struct hid_device *hdev, u16 effect_type, + u8 *body, size_t size); +int apple_taptic_send_waveform(struct hid_device *hdev, const u8 *body, + size_t len); #else static inline int apple_taptic_send(struct hid_device *hdev, u16 effect_type, @@ -35,5 +39,18 @@ static inline int apple_taptic_switch_modes(struct hid_device *hdev, { return -ENODEV; } + +static inline int apple_taptic_get_waveform(struct hid_device *hdev, + u16 effect_type, u8 *body, + size_t size) +{ + return -ENODEV; +} + +static inline int apple_taptic_send_waveform(struct hid_device *hdev, + const u8 *body, size_t len) +{ + return -ENODEV; +} #endif #endif /* __APPLE_MTP_ACTUATOR_H__ */ From f30c64e167040dc9f62d0832efa026d17d861743 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:15:18 +1100 Subject: [PATCH 0610/1514] arm64: dts: apple: t8112-j413: keep the firmware's click strength Commit 99768d194bf9 ("arm64: dts: apple: t8112-j413: set the trackpad click strength") raised the J413 actuator's click from the firmware's 0x23/0x14 to 0xc0/0x6e, when the firmware still played every click. Clicks are now played from the host with the firmware's own waveform and strength, and macOS keeps the firmware's values at its default (Medium) click setting, so the raised strength would make the J413 click several times firmer than macOS and than every other MTP Mac. Drop it; the actuator node stays so host clicks remain on. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-j413.dts | 1 - 1 file changed, 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index ff99c23afb7a96..7d4d6017f45254 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -270,7 +270,6 @@ }; actuator { - apple,click-strength = <0xc0 0x6e>; }; tp_accel { From 15d9bac9d8ff38ae334705feb635f67cbd7450da Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:52:25 +1100 Subject: [PATCH 0611/1514] media: apple: avd: tests: follow the job bound and the SPS geometry check The host program test models struct avd_job without the new max and overflow fields, so push() treats every job as full. Give the model the fields and set max wherever a test builds a segment table. avd_hevc_validate_sps() now calls avd_hevc_check_sps_geometry(), which the test did not extract, and the depth fixture used 8x8 CTBs, which the check refuses. Extract the helper and use 64x64 CTBs. Let the extractor find functions whose return type is on the previous line. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/tests/av1-test.py | 2 +- .../media/platform/apple/avd/tests/host_source.py | 3 ++- .../platform/apple/avd/tests/program-test.py | 15 +++++++++------ .../media/platform/apple/avd/tests/vp9-test.py | 2 +- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/drivers/media/platform/apple/avd/tests/av1-test.py b/drivers/media/platform/apple/avd/tests/av1-test.py index b073c8929fe69e..b133465c5a1b4f 100644 --- a/drivers/media/platform/apple/avd/tests/av1-test.py +++ b/drivers/media/platform/apple/avd/tests/av1-test.py @@ -106,7 +106,7 @@ static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;(void)run;} static int avd_init_job(struct avd_ctx *ctx,int codec,size_t segments){ free(ctx->job.segments);ctx->job.codec=codec;ctx->job.num=0; - ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));return ctx->job.segments?0:-ENOMEM; + ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));ctx->job.overflow=false;ctx->job.max=ctx->job.segments?segments:0;return ctx->job.segments?0:-ENOMEM; } static int avd_submit_job(struct avd_ctx *ctx); ''' diff --git a/drivers/media/platform/apple/avd/tests/host_source.py b/drivers/media/platform/apple/avd/tests/host_source.py index b473b65e3c4edf..0251d1e3b833cc 100644 --- a/drivers/media/platform/apple/avd/tests/host_source.py +++ b/drivers/media/platform/apple/avd/tests/host_source.py @@ -4,7 +4,8 @@ def function(source, name): - match = re.search(r"^[A-Za-z_][\w *]*\b" + re.escape(name) + + # The return type may sit on the line before the name. + match = re.search(r"^(?:[A-Za-z_][\w *]*\n)?(?:[A-Za-z_][\w *]*\b)?" + re.escape(name) + r"\([^;{}]*?\)\n\{", source, re.M) if not match: raise ValueError(name) diff --git a/drivers/media/platform/apple/avd/tests/program-test.py b/drivers/media/platform/apple/avd/tests/program-test.py index 5502470ca6aaed..8d681bda358860 100755 --- a/drivers/media/platform/apple/avd/tests/program-test.py +++ b/drivers/media/platform/apple/avd/tests/program-test.py @@ -91,7 +91,7 @@ dma_addr_t fifo_iova; u32 cmd[24], tag; unsigned long deadline; int state,status; struct avd_ctx *ctx; }; struct avd_segment { u32 instructions[AVD_MAX_INST]; size_t num; }; -struct avd_job { struct avd_segment *segments; unsigned int num, codec; }; +struct avd_job { struct avd_segment *segments; unsigned int num, codec; size_t max; bool overflow; }; struct avd_dev; struct avd_variant { unsigned int quirks, revision, fifo_slots, vp_slots[4], vp_slot_base[4]; void (*configure_stream)(struct avd_dev *,dma_addr_t,u8,u32); }; @@ -265,7 +265,7 @@ decode.flags=idx%3?0:V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC; decode.dpb[0].flags=idx%3?V4L2_H264_DPB_ENTRY_FLAG_VALID:0; sl.slice_type=idx%3==0?V4L2_H264_SLICE_TYPE_I:idx%3==1?V4L2_H264_SLICE_TYPE_P:V4L2_H264_SLICE_TYPE_B; - ctx.job.segments=calloc(3,sizeof(*ctx.job.segments)); assert(ctx.job.segments); + ctx.job.segments=calloc(3,sizeof(*ctx.job.segments)); assert(ctx.job.segments); ctx.job.max=3; stream_hdr(&ctx,&run); ctx.job.num=1;sl.first_mb_in_slice=0;slice.addr=0x200800000ULL; stream_slice(&ctx,&run); size_t continuation=1+ctx.job.segments[0].num+ctx.job.segments[1].num; @@ -425,8 +425,9 @@ def h264_prelude(): static size_t avd_h264_max_slices(const struct v4l2_ctrl_h264_sps *s) { (void)s;return 20; } static int avd_h264_realloc_slices(struct avd_ctx *c,size_t n) { (void)c;(void)n;abort(); } static int avd_init_job(struct avd_ctx *c,unsigned int codec,size_t n) { - free(c->job.segments);c->job.codec=codec;c->job.num=0; - c->job.segments=calloc(n,sizeof(*c->job.segments));return c->job.segments?0:-ENOMEM; + free(c->job.segments);c->job.codec=codec;c->job.num=0;c->job.overflow=false; + c->job.segments=calloc(n,sizeof(*c->job.segments));c->job.max=c->job.segments?n:0; + return c->job.segments?0:-ENOMEM; } static void avd_job_finish(struct avd_ctx *c,enum vb2_buffer_state s) { (void)c;assert(s==VB2_BUF_STATE_DONE);held_finishes++; } static int avd_submit_job(struct avd_ctx *c) { submissions++;return avd_open_build_program(c); } @@ -457,6 +458,7 @@ def h264_prelude(): } /* Applied SPS controls reject unequal depths for both codecs. */ struct v4l2_ctrl_hevc_sps hevc={.chroma_format_idc=1, + .log2_min_luma_coding_block_size_minus3=1,.log2_diff_max_min_luma_coding_block_size=2, .pic_width_in_luma_samples=1920,.pic_height_in_luma_samples=1088}; ctx.coded_fmt.fmt.pix_mp.width=1920;ctx.coded_fmt.fmt.pix_mp.height=1088; for(unsigned int luma=0;luma<5;luma++) for(unsigned int chroma=0;chroma<5;chroma++) { @@ -475,7 +477,7 @@ def h264_prelude(): assert(!avd_h264_run(&ctx));assert(submissions==1&&hc.bank[0].submitted&&dst[0].bank==1); /* Compare the complete header to one built with the emitted VALID count. */ struct avd_segment expected={0};struct avd_job saved=ctx.job; - ctx.job=(struct avd_job){.segments=&expected};fixture_run.num_valid=2;fixture_run.cur_poc=40; + ctx.job=(struct avd_job){.segments=&expected,.max=1};fixture_run.num_valid=2;fixture_run.cur_poc=40; stream_hdr(&ctx,&fixture_run); assert(!memcmp((u32 *)programs[0].cpu+1,expected.instructions,expected.num*sizeof(u32))); ctx.job=saved; @@ -546,6 +548,7 @@ def prepare_regressions(out): 'avd_h264_abort_picture', 'avd_h264_refs_valid', 'avd_h264_done'): code += function(source, name) code += function((ROOT / 'avd-backend-open.c').read_text(), 'avd_open_build_program') + code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_check_sps_geometry') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps') code += RUN_FIXTURE + function(source, 'avd_h264_run') + RUN_MAIN dest = out / 'prepare.c' @@ -568,7 +571,7 @@ def prepare_regressions(out): struct avd_decoded_buffer destination = {0}; struct avd_segment segments[2]; struct avd_ctx ctx_storage = { .priv = &hc, .dev = &dev, - .fh.m2m_ctx = &m2m, .job.segments = segments, .decomp = true }; + .fh.m2m_ctx = &m2m, .job.segments = segments, .job.max = 2, .decomp = true }; struct avd_ctx *ctx = &ctx_storage; struct v4l2_ctrl_h264_decode_params dec = {0}; struct v4l2_ctrl_h264_sps sps = { .chroma_format_idc = 1, diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 083c06e095a1f5..c6ccf836b4636a 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -84,7 +84,7 @@ static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *run) { (void)ctx;(void)run; } static int avd_init_job(struct avd_ctx *ctx,int codec,size_t segments) { free(ctx->job.segments);ctx->job.codec=codec;ctx->job.num=0; - ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));return ctx->job.segments?0:-ENOMEM; + ctx->job.segments=calloc(segments,sizeof(*ctx->job.segments));ctx->job.overflow=false;ctx->job.max=ctx->job.segments?segments:0;return ctx->job.segments?0:-ENOMEM; } static int avd_submit_job(struct avd_ctx *ctx); ''' From 5e263083adeb6e0f710aab4a5ddc271bd4f6ae5c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:52:26 +1100 Subject: [PATCH 0612/1514] media: apple: avd: hevc: bound the tile counts by the PPS arrays avd_hevc_check_tiles() reads column_width_minus1[] and row_height_minus1[] up to the tile counts and relied on the V4L2 control code to keep the counts below the array sizes. Check that in the helper too, so it holds for any caller. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-hevc-test.c | 29 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-hevc.c | 4 +++ 2 files changed, 33 insertions(+) diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c index 50db548b19e287..31aee3e1d542b4 100644 --- a/drivers/media/platform/apple/avd/avd-hevc-test.c +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -124,6 +124,34 @@ static void avd_hevc_tiles_test(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, ids, c->ids, sizeof(ids)); } +/* + * More tile columns or rows than the PPS control has size entries for are + * refused by the check itself, even for a picture wide or tall enough. + */ +static void avd_hevc_tiles_array_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps; + struct v4l2_ctrl_hevc_pps pps = { + .flags = V4L2_HEVC_PPS_FLAG_TILES_ENABLED | + V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING, + }; + + avd_hevc_test_sps(&sps); + sps.pic_width_in_luma_samples = 8192; + sps.pic_height_in_luma_samples = 4320; + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1) - 1; + pps.num_tile_rows_minus1 = ARRAY_SIZE(pps.row_height_minus1) - 1; + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), 0); + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), -EINVAL); + + pps.num_tile_columns_minus1 = ARRAY_SIZE(pps.column_width_minus1) - 1; + pps.num_tile_rows_minus1 = ARRAY_SIZE(pps.row_height_minus1); + KUNIT_EXPECT_EQ(test, avd_hevc_check_tiles(&sps, &pps), -EINVAL); +} + static void avd_hevc_no_tiles_test(struct kunit *test) { struct v4l2_ctrl_hevc_sps sps; @@ -141,6 +169,7 @@ static void avd_hevc_no_tiles_test(struct kunit *test) static struct kunit_case avd_hevc_test_cases[] = { KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), + KUNIT_CASE(avd_hevc_tiles_array_test), KUNIT_CASE(avd_hevc_no_tiles_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index 9c52f50586f884..d655ba8c648bfb 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -1096,6 +1096,10 @@ VISIBLE_IF_KUNIT int avd_hevc_check_tiles(const struct v4l2_ctrl_hevc_sps *sps, if (!(pps->flags & V4L2_HEVC_PPS_FLAG_TILES_ENABLED)) return 0; + if (pps->num_tile_columns_minus1 >= ARRAY_SIZE(pps->column_width_minus1) || + pps->num_tile_rows_minus1 >= ARRAY_SIZE(pps->row_height_minus1)) + return -EINVAL; + avd_hevc_pic_in_ctbs(sps, &width, &height); if (pps->num_tile_columns_minus1 >= width || pps->num_tile_rows_minus1 >= height) From 1b68ad86e50a6bc9f3009b426db00f103e249383 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:52:36 +1100 Subject: [PATCH 0613/1514] soc: apple: rtkit: acknowledge system notifications during late display stop Acknowledge SYSLOG and IOREPORT notifications in the atomic idle loop using the existing bounded echo path. An acknowledged record can be recycled, so leave it out of the deferred FIFO. Preserve the stop refusal for application traffic and replay only other system messages after a successful stop. Signed-off-by: Ryan Murray --- drivers/soc/apple/rtkit-v27-late.inc | 19 +++++------ tools/asahi/rtkit-v27-late-tests.py | 51 ++++++++++++++++++---------- 2 files changed, 43 insertions(+), 27 deletions(-) diff --git a/drivers/soc/apple/rtkit-v27-late.inc b/drivers/soc/apple/rtkit-v27-late.inc index 82d39de6f8cc00..16cb58e0ba3dcc 100644 --- a/drivers/soc/apple/rtkit-v27-late.inc +++ b/drivers/soc/apple/rtkit-v27-late.inc @@ -193,21 +193,20 @@ int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT && iop_sent && !done && type == APPLE_RTKIT_MGMT_IDLE_NOTIFY && !arg) { done = true; - } else if (apple_rtkit_oslog_owed_msg(rtk, msg.msg1, msg.msg0)) { - echo = msg; - echo_pending = true; } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT || - msg.msg1 == APPLE_RTKIT_EP_CRASHLOG) { - /* Off the power-state handshake, or a crash: no stop. */ + msg.msg1 == APPLE_RTKIT_EP_CRASHLOG || + msg.msg1 >= APPLE_RTKIT_APP_ENDPOINT_START) { + /* A crash, unexpected handshake, or live application RPC. */ kfifo_put(&s->deferred, msg); ret = -EPROTO; goto poison; + } else if (apple_rtkit_oslog_owed_msg(rtk, msg.msg1, msg.msg0) || + apple_rtkit_notification_msg(msg.msg1, msg.msg0)) { + /* Echo now. The ring entry can be reused after the echo. */ + echo = msg; + echo_pending = true; } else { - /* - * Ordinary traffic (a log line, a report, an endpoint's - * message): kept for the disarm's replay, and the wait - * for the power-state answers goes on. - */ + /* Other system messages are replayed on disarm. */ kfifo_put(&s->deferred, msg); } } diff --git a/tools/asahi/rtkit-v27-late-tests.py b/tools/asahi/rtkit-v27-late-tests.py index a40afaee4c3a86..5fa65af5fbada6 100755 --- a/tools/asahi/rtkit-v27-late-tests.py +++ b/tools/asahi/rtkit-v27-late-tests.py @@ -4,13 +4,13 @@ The bodies of apple_rtkit_v27_check() and apple_rtkit_v27_idle_atomic() are compiled from drivers/soc/apple/rtkit-v27-late.inc, the RTKit constants and apple_rtkit_oslog_owed_msg() -from rtkit.c. The fake firmware answers the AP and IOP power-state requests and can put -ordinary traffic (a syslog line, an endpoint message) into the receive queue at any point. +and notification classifier from rtkit.c. The fake firmware answers the AP and IOP power-state requests and can put +system notifications or application traffic into the receive queue at any point. Cases: before the commit a pending message refuses (kept for the disarm); after the commit the check leaves it in the mailbox and the stop completes; traffic during the stop's wait is -deferred into the scope FIFO in order and the stop completes; an unexpected management or a -crashlog message still fails the stop; no answer still times out; a full FIFO still fails. +either acknowledged inline or deferred in order; unexpected management, crashlog and +application messages fail the stop; no answer still times out; a full FIFO still fails. Mutations: --consume-committed (the committed check consumes and refuses as before), --fail-foreign (the stop fails on any foreign message as before). @@ -45,16 +45,19 @@ def scope_struct(): return inc[a:inc.index('};', a) + 2] -consts = [] +consts = [line for line in (root / "drivers/soc/apple/rtkit-internal.h").read_text().splitlines() + if line.startswith("#define APPLE_RTKIT_APP_ENDPOINT_START ")] for name in ['APPLE_RTKIT_PWR_STATE_IDLE', 'APPLE_RTKIT_PWR_STATE_ON', 'APPLE_RTKIT_EP_MGMT', 'APPLE_RTKIT_EP_CRASHLOG', 'APPLE_RTKIT_EP_SYSLOG', 'APPLE_RTKIT_EP_OSLOG', + 'APPLE_RTKIT_EP_IOREPORT', 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK', 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE', 'APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK', 'APPLE_RTKIT_MGMT_IDLE_NOTIFY']: m = re.search(r'\b' + name + r' = (0x[0-9a-fA-F]+|[0-9]+),', rtkit) consts.append(f'#define {name} {m.group(1)}') for name in ['APPLE_RTKIT_MGMT_TYPE', 'APPLE_RTKIT_MGMT_PWR_STATE', 'APPLE_RTKIT_SYSLOG_TYPE', - 'APPLE_RTKIT_SYSLOG_LOG', 'APPLE_RTKIT_OSLOG_TYPE', 'APPLE_RTKIT_OSLOG_LOG']: + 'APPLE_RTKIT_SYSLOG_LOG', 'APPLE_RTKIT_OSLOG_TYPE', 'APPLE_RTKIT_OSLOG_LOG', + 'APPLE_RTKIT_IOREPORT_UNKNOWN1', 'APPLE_RTKIT_IOREPORT_UNKNOWN2']: m = re.search(r'#define ' + name + r' (.+)', rtkit) consts.append(f'#define {name} {m.group(1)}') @@ -65,10 +68,11 @@ def scope_struct(): assert check.count(old) == 1 check = check.replace(old, '') if args.fail_foreign: - old = ('\t\t\t\t\t */\n\t\t\t\t\tkfifo_put(&s->deferred, msg);\n\t\t\t\t}') + old = ('\t\t\t\t\t/* Other system messages are replayed on disarm. */\n' + '\t\t\t\t\tkfifo_put(&s->deferred, msg);\n') assert idle.count(old) == 1 - idle = idle.replace(old, '\t\t\t\t\t */\n\t\t\t\t\tkfifo_put(&s->deferred, msg);\n' - '\t\t\t\t\tret = -EPROTO;\n\t\t\t\t\tgoto poison;\n\t\t\t\t}') + idle = idle.replace(old, old + '\t\t\t\t\tret = -EPROTO;\n' + '\t\t\t\t\tgoto poison;\n') pre = r''' #include @@ -152,7 +156,8 @@ def scope_struct(): return 0; } ''' -owed = function(rtkit, 'static bool apple_rtkit_oslog_owed_msg(') +owed = function(rtkit, 'static bool apple_rtkit_oslog_owed_msg(') + '\n' + \ + function(rtkit, 'static bool apple_rtkit_notification_msg(') main = r''' static struct apple_mbox mb; @@ -191,19 +196,30 @@ def scope_struct(): assert(kfifo_len(&sc.deferred) == 0 && mb.rx_in != mb.rx_out); assert(apple_rtkit_v27_idle_atomic(&sc) == 0); stopped_ok(); - assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_SYSLOG && m.msg0 == SYSLOG_LINE); assert(!kfifo_get(&sc.deferred, &m)); + { + unsigned echoes = 0; + for (unsigned i = 0; i < mb.tx_n; i++) + echoes += mb.tx[i].msg1 == APPLE_RTKIT_EP_SYSLOG && + mb.tx[i].msg0 == SYSLOG_LINE; + assert(echoes == 1); + } - /* Ordinary traffic in the middle of the wait: deferred in order, the stop completes. */ + /* Other system messages are retained in FIFO order. */ reset(); rk.inject_at = 1; rk.ninject = 2; - rk.inject[0] = (struct apple_mbox_msg){ .msg0 = SYSLOG_LINE, .msg1 = APPLE_RTKIT_EP_SYSLOG }; - rk.inject[1] = (struct apple_mbox_msg){ .msg0 = APP_MSG, .msg1 = 0x37 }; + rk.inject[0] = (struct apple_mbox_msg){ .msg0 = 0, .msg1 = APPLE_RTKIT_EP_SYSLOG }; + rk.inject[1] = (struct apple_mbox_msg){ .msg0 = 0, .msg1 = APPLE_RTKIT_EP_IOREPORT }; assert(apple_rtkit_v27_idle_atomic(&sc) == 0); stopped_ok(); assert(rk.injected == 2); assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_SYSLOG); - assert(kfifo_get(&sc.deferred, &m) && m.msg1 == 0x37 && m.msg0 == APP_MSG); + assert(kfifo_get(&sc.deferred, &m) && m.msg1 == APPLE_RTKIT_EP_IOREPORT); assert(!kfifo_get(&sc.deferred, &m)); + /* Application RPCs invalidate the stop. */ + reset(); push(&mb, APPLE_RTKIT_APP_ENDPOINT_START, APP_MSG); + assert(apple_rtkit_v27_idle_atomic(&sc) == -EPROTO); + assert(sc.failed && !sc.stopped && rk.strict_idle_poisoned); + /* An owed OSLOG counter is still echoed, not deferred. */ reset(); rk.oslog_echo = true; push(&mb, APPLE_RTKIT_EP_OSLOG, FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_LOG) | 7); @@ -234,7 +250,7 @@ def scope_struct(): /* A full FIFO: nothing more is consumed, the stop fails. */ reset(); for (unsigned i = 0; i < FIFO_N; i++) - push(&mb, APPLE_RTKIT_EP_SYSLOG, SYSLOG_LINE); + push(&mb, APPLE_RTKIT_EP_SYSLOG, 0); assert(apple_rtkit_v27_idle_atomic(&sc) == -ENOBUFS); assert(sc.failed && !sc.stopped && kfifo_is_full(&sc.deferred)); assert(apple_rtkit_v27_check(&sc, true) == -EBUSY); @@ -263,4 +279,5 @@ def build_and_run(out): if rc: sys.exit(1) print('PASS rtkit v27 late stop: committed check leaves a message to the stop, ' - 'foreign traffic deferred in order, owed OSLOG echoed, MGMT/crashlog/timeout/full FIFO still fail') + 'system traffic deferred in order, notification and OSLOG echoes, ' + 'MGMT/crashlog/application/timeout/full FIFO fail') From 305193da4ba7e79eecfb444394faf5cbc79344c6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 17:57:58 +1100 Subject: [PATCH 0614/1514] media: apple: avd: tests: follow the run-time copies and checks The H.264 and AV1 runs now take copies of their controls, check the picture format against the buffers and, for AV1, check the frame size and copy the tile group under the control lock. Update the host fixtures to match: - avd_h264_run_preamble() returns an int; avd_h264_sps_image_fmt() is extracted, and the fixtures use the driver's image format enum. - avd_check_run_image_fmt() is stubbed; avd-fmt-test.c covers it. - The AV1 fixtures provide the stream's control copies, the control lock, kmemdup_array() and the OUTPUT buffer the preamble reads, and set upscaled_width, which must now equal the frame width without superres. - The AV1 tail test extracts the new helpers, and its frame size mutation drops the frame size check in avd_av1_check_frame_size() as a whole: the upscaled width bound alone also bounds the width. Signed-off-by: Ryan Murray --- .../platform/apple/avd/tests/av1-test.py | 13 +++++- .../platform/apple/avd/tests/program-test.py | 10 +++-- tools/asahi/avd-av1-tail-tests.py | 44 ++++++++++++++----- 3 files changed, 51 insertions(+), 16 deletions(-) diff --git a/drivers/media/platform/apple/avd/tests/av1-test.py b/drivers/media/platform/apple/avd/tests/av1-test.py index b133465c5a1b4f..df9a0e4ae1afe2 100644 --- a/drivers/media/platform/apple/avd/tests/av1-test.py +++ b/drivers/media/platform/apple/avd/tests/av1-test.py @@ -77,7 +77,14 @@ static unsigned long vb2_get_plane_payload(struct vb2_buffer *b,unsigned int p){(void)b;(void)p;return 1UL<<20;} static struct vb2_v4l2_buffer *current_src,*current_dst; static struct vb2_v4l2_buffer *v4l2_m2m_next_src_buf(void *m){(void)m;return current_src;} -struct v4l2_ctrl {unsigned int id; unsigned int elems; union {void *p;} p_cur;}; +struct device; +struct v4l2_ctrl {unsigned int id; unsigned int elems, elem_size; union {void *p;} p_cur;}; +static void v4l2_ctrl_lock(struct v4l2_ctrl *c){(void)c;} +static void v4l2_ctrl_unlock(struct v4l2_ctrl *c){(void)c;} +static void *kmemdup_array(const void *p,size_t n,size_t size,int f){ + (void)f;void *d=calloc(n?n:1,size);if(d)memcpy(d,p,n*size);return d;} +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx,int f){(void)ctx;(void)f;return 0;} struct v4l2_ctrl_ref {struct v4l2_ctrl_ref *next; struct v4l2_ctrl *ctrl; bool p_req_valid; union {void *p;} p_req;}; struct v4l2_ctrl_handler {struct v4l2_ctrl_ref *ctrl_refs;}; #define list_for_each_entry(ref,head,node) for((ref)=*(head);(ref);(ref)=(ref)->next) @@ -92,12 +99,14 @@ static struct v4l2_ctrl_handler *v4l2_ctrl_request_hdl_find(void *req,void *h){(void)h;assert(req==&request_hdl);request_gets++;return &request_hdl;} static void v4l2_ctrl_request_hdl_put(struct v4l2_ctrl_handler *h){assert(h==&request_hdl);request_puts++;} static struct v4l2_ctrl *v4l2_ctrl_find(void *h,u32 id){ - (void)h;controls[0].p_cur.p=&seq;controls[1].p_cur.p=¶ms;controls[2].p_cur.p=&tile;controls[2].elems=1;controls[3].p_cur.p=&grain; + (void)h;controls[0].p_cur.p=&seq;controls[1].p_cur.p=¶ms;controls[2].p_cur.p=&tile;controls[2].elems=1;controls[2].elem_size=sizeof(tile);controls[3].p_cur.p=&grain; if(id==V4L2_CID_STATELESS_AV1_SEQUENCE)return &controls[0]; if(id==V4L2_CID_STATELESS_AV1_FRAME)return &controls[1]; if(id==V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY)return &controls[2]; return &controls[3]; } +static int avd_ctrl_copy(struct avd_ctx *ctx,u32 id,void *dst,size_t size){ + (void)ctx;memcpy(dst,v4l2_ctrl_find(NULL,id)->p_cur.p,size);return 0;} static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){ (void)ctx;memset(run,0,sizeof(*run));run->bufs.src=current_src;run->bufs.dst=current_dst; run->coded_in=current_src->vb2_buf.dma;run->comp_out=current_dst->vb2_buf.dma; diff --git a/drivers/media/platform/apple/avd/tests/program-test.py b/drivers/media/platform/apple/avd/tests/program-test.py index 8d681bda358860..a0ee9b1d3b95de 100755 --- a/drivers/media/platform/apple/avd/tests/program-test.py +++ b/drivers/media/platform/apple/avd/tests/program-test.py @@ -55,8 +55,8 @@ #define AVD_MAX_INST 512 #define AVD_CODEC_AV1 3 #define AVD_MAX_FRAMES 16 -#define AVD_IMG_FMT_420_10BIT 1 -#define AVD_IMG_FMT_422_10BIT 2 +enum avd_image_fmt { AVD_IMG_FMT_ANY, AVD_IMG_FMT_420_8BIT, AVD_IMG_FMT_420_10BIT, + AVD_IMG_FMT_422_8BIT, AVD_IMG_FMT_422_10BIT }; #define AVD_FRAME_SUBMITTED 2 #define AVD_FRAME_DONE 3 #define IRQ_HANDLED 1 @@ -418,7 +418,9 @@ def h264_prelude(): static struct vb2_v4l2_buffer *v4l2_m2m_next_src_buf(void *m) { (void)m;return fixture_run.base.bufs.src; } static size_t vb2_get_plane_payload(struct vb2_buffer *b,int p) { (void)b;(void)p;return valid_data?16:2; } static void *vb2_plane_vaddr(struct vb2_buffer *b,int p) { (void)b;(void)p;static u8 data[16];return data; } -static void avd_h264_run_preamble(struct avd_ctx *ctx,struct avd_h264_run *r) { (void)ctx;*r=fixture_run; } +static int avd_h264_run_preamble(struct avd_ctx *ctx,struct avd_h264_run *r) { (void)ctx;*r=fixture_run;return 0; } +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx,int f) { (void)ctx;(void)f;return 0; } static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *r) { (void)ctx;(void)r;postambles++; } static bool avd_h264_slice_fits(const struct v4l2_ctrl_h264_sps *s,size_t n,size_t b,u32 l,size_t z) { (void)s;(void)b;(void)l;(void)z;return n<20; } @@ -550,7 +552,7 @@ def prepare_regressions(out): code += function((ROOT / 'avd-backend-open.c').read_text(), 'avd_open_build_program') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_check_sps_geometry') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps') - code += RUN_FIXTURE + function(source, 'avd_h264_run') + RUN_MAIN + code += RUN_FIXTURE + function(source, 'avd_h264_sps_image_fmt') + function(source, 'avd_h264_run') + RUN_MAIN dest = out / 'prepare.c' dest.write_text(code) exe = dest.with_suffix('') diff --git a/tools/asahi/avd-av1-tail-tests.py b/tools/asahi/avd-av1-tail-tests.py index 6f1d5a98b8f3fd..df866290b8422f 100644 --- a/tools/asahi/avd-av1-tail-tests.py +++ b/tools/asahi/avd-av1-tail-tests.py @@ -15,7 +15,8 @@ def function(source, name): - match = re.search(r'^(?:static )?(?:int|void|u64)\s+' + name + r'\(', source, re.M) + # The return type may sit on the line before the name. + match = re.search(r'^(?:static |VISIBLE_IF_KUNIT )?(?:int|void|u64|enum \w+|struct \w+ \*)\s+' + name + r'\(', source, re.M) if not match: raise ValueError(name) start = match.start() @@ -55,6 +56,10 @@ def structure(source, name): #define WARN_ON(x) (x) #define DIV_ROUND_UP(n,d) (((n)+(d)-1)/(d)) #define dev_err_ratelimited(...) ((void)0) +#define VISIBLE_IF_KUNIT +#define GFP_KERNEL 0 +struct device; +enum avd_image_fmt { AVD_IMG_FMT_ANY, AVD_IMG_FMT_420_8BIT, AVD_IMG_FMT_420_10BIT }; @ALIGNMENT@ @CDF_HEADER@ @CDF_DEFAULTS@ @@ -67,10 +72,22 @@ def structure(source, name): struct avd_buf {void *cpu; dma_addr_t addr;}; struct avd_run {struct {struct vb2_v4l2_buffer *src,*dst;} bufs; dma_addr_t y_out; int setup_err;}; @RUN_STRUCT@ +/* The preamble only uses the stream's copies of the controls. */ +struct avd_av1_stream { + struct {struct v4l2_ctrl_av1_sequence seq; struct v4l2_ctrl_av1_frame frame; struct v4l2_ctrl_av1_film_grain grain;} params; +}; @CTX_STRUCT@ -struct v4l2_ctrl {unsigned int elems; struct {void *p;} p_cur;}; +struct v4l2_ctrl {unsigned int elems, elem_size; struct {void *p;} p_cur;}; +static void v4l2_ctrl_lock(struct v4l2_ctrl *c){(void)c;} +static void v4l2_ctrl_unlock(struct v4l2_ctrl *c){(void)c;} +/* avd_av1_run() frees the run's copy; these tests only run the preamble. */ +static struct v4l2_ctrl_av1_tile_group_entry tile_copy[4]; +static void *kmemdup_array(const void *p,size_t n,size_t size,int f){(void)f;assert(n*size<=sizeof(tile_copy));memcpy(tile_copy,p,n*size);return tile_copy;} +/* The run-time format check has its own KUnit suite (avd-fmt-test.c). */ +static int avd_check_run_image_fmt(void *ctx,enum avd_image_fmt f){(void)ctx;(void)f;return 0;} +struct avd_dev {struct device *dev;}; struct v4l2_pix_format_mplane {unsigned int width,height; struct {unsigned int sizeimage;} plane_fmt[1];}; -struct avd_ctx {void *priv; int ctrl_hdl; struct {struct {struct {unsigned int width,height;} pix_mp;} fmt;} decoded_fmt;}; +struct avd_ctx {struct avd_dev *dev; void *priv; int ctrl_hdl; struct {struct {struct {unsigned int width,height;} pix_mp;} fmt;} decoded_fmt;}; static struct avd_decoded_buffer *reference; static struct v4l2_ctrl_av1_frame frame; static struct v4l2_ctrl_av1_sequence sequence={.bit_depth=8,.flags=V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_X|V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_Y}; @@ -83,7 +100,9 @@ def structure(source, name): static dma_addr_t vb2_dma_contig_plane_dma_addr(struct vb2_buffer *b,unsigned int p){assert(p==0);return b->dma;} static struct avd_decoded_buffer *vb2_to_avd_decoded_buf(struct vb2_buffer *b){return (void *)b;} static struct avd_decoded_buffer *avd_get_ref_buf(struct avd_ctx *ctx,struct vb2_v4l2_buffer *dst,uint64_t timestamp){(void)ctx;(void)dst;assert(timestamp==1000);lookup_calls++;return reference;} -static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;(void)run;preamble_calls++;} +/* Like the real one, this hands the run its OUTPUT buffer. */ +static struct vb2_v4l2_buffer fixture_src; +static void avd_run_preamble(struct avd_ctx *ctx,struct avd_run *run){(void)ctx;if(!run->bufs.src)run->bufs.src=&fixture_src;preamble_calls++;} static struct v4l2_ctrl *v4l2_ctrl_find(int *h,unsigned int id){ (void)h; if(id==V4L2_CID_STATELESS_AV1_SEQUENCE)return &controls[0]; @@ -92,13 +111,17 @@ def structure(source, name): if(id==V4L2_CID_STATELESS_AV1_FILM_GRAIN)return &controls[3]; return NULL; } +static int avd_ctrl_copy(struct avd_ctx *ctx,unsigned int id,void *dst,size_t size){ + struct v4l2_ctrl *c=v4l2_ctrl_find(&ctx->ctrl_hdl,id);if(!c)return -EINVAL;memcpy(dst,c->p_cur.p,size);return 0;} ''' TESTS = r''' static size_t aligned_cdf(size_t length,size_t color){return (length&~255UL)-((color+255)&~255UL)-9216;} /* 3 bits per 4x4 block over 128x128 superblocks, 256-byte aligned. */ static size_t seg_bytes(size_t w,size_t h){return ALIGN(ALIGN(w,128)*ALIGN(h,128)/128*3,256);} -static void set_frame_ctx(struct avd_ctx *ctx){ctx->decoded_fmt.fmt.pix_mp.width=1920;ctx->decoded_fmt.fmt.pix_mp.height=1080;controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain;} +static struct avd_dev fixture_dev; +static struct avd_av1_stream fixture_stream; +static void set_frame_ctx(struct avd_ctx *ctx){ctx->dev=&fixture_dev;((struct avd_av1_ctx *)ctx->priv)->stream=&fixture_stream;ctx->decoded_fmt.fmt.pix_mp.width=1920;ctx->decoded_fmt.fmt.pix_mp.height=1080;controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain;} static void read_exact(const char *path,void *data,size_t n){FILE *f=fopen(path,"rb");assert(f);assert(fread(data,1,n,f)==n);assert(fgetc(f)==EOF);assert(fclose(f)==0);} static void inheritance(unsigned int residue,unsigned int mode,const char *neighbors,bool check_addresses){ const size_t ref_len=6964992+residue,dst_len=7000064+(residue?((residue+79)%256):0); @@ -112,7 +135,7 @@ def structure(source, name): avd_av1_default_coeff_probs(47,&expected);avd_av1_set_default_cdfs(&expected); if(neighbors){unsigned char observation[9728];read_exact(neighbors,observation,sizeof(observation));assert(residue==64);memcpy(src.base.vb.vb2_buf.memory+6817344,observation,sizeof(observation));memcpy(&expected,observation+192,sizeof(expected));} else {expected.intra_inter_cdf[0]^=37;expected.coeff_base_cdf[0][0][0][0]^=59;memcpy(src.base.vb.vb2_buf.memory+ref_offset,&expected,sizeof(expected));} - memset(&frame,0,sizeof(frame));frame.frame_width_minus_1=1919;frame.frame_height_minus_1=1079;frame.quantization.base_q_idx=47; + memset(&frame,0,sizeof(frame));frame.frame_width_minus_1=1919;frame.upscaled_width=1920;frame.frame_height_minus_1=1079;frame.quantization.base_q_idx=47; frame.frame_type=V4L2_AV1_INTER_FRAME;frame.primary_ref_frame=0;frame.ref_frame_idx[0]=0;frame.reference_frame_ts[0]=1000; if(mode){frame.frame_type=mode==1?V4L2_AV1_KEY_FRAME:mode==2?V4L2_AV1_INTRA_ONLY_FRAME:V4L2_AV1_INTER_FRAME;if(mode==3)frame.flags=V4L2_AV1_FRAME_FLAG_ERROR_RESILIENT_MODE;if(mode==4)frame.primary_ref_frame=7;memset(&expected,0,sizeof(expected));avd_av1_default_coeff_probs(47,&expected);avd_av1_set_default_cdfs(&expected);} controls[0].p_cur.p=&sequence;controls[1].p_cur.p=&frame;controls[2].p_cur.p=&tile;controls[3].p_cur.p=&grain; @@ -141,7 +164,7 @@ def structure(source, name): static int preamble(unsigned int w,unsigned int h,unsigned char primary,signed char idx){ struct avd_decoded_buffer dst={0};struct avd_av1_ctx av1={0};struct avd_ctx ctx={.priv=&av1};struct avd_av1_run run={0};set_frame_ctx(&ctx); dst.base.vb.vb2_buf.planes[0].length=7000064;memset(&frame,0,sizeof(frame)); - frame.frame_width_minus_1=w-1;frame.frame_height_minus_1=h-1;frame.primary_ref_frame=primary;if(primary<7)frame.ref_frame_idx[primary]=idx; + frame.frame_width_minus_1=w-1;frame.upscaled_width=w;frame.frame_height_minus_1=h-1;frame.primary_ref_frame=primary;if(primary<7)frame.ref_frame_idx[primary]=idx; run.base.bufs.dst=&dst.base.vb;run.base.y_out=0x120000000UL;return avd_av1_run_preamble(&ctx,&run); } static void guards(void){ @@ -165,7 +188,7 @@ def structure(source, name): memset(dst.base.vb.vb2_buf.memory,0xa5,len);memset(src.base.vb.vb2_buf.memory,0x3c,ref_len); for(size_t i=0;i', 'UNALIGNED_SEG_OFFSET(dst->'), 'seg-any-size': ('avd_av1_set_seg', 'DIV_ROUND_UP(ref->av1.width + 1, 8)', 'DIV_ROUND_UP(frame->frame_width_minus_1 + 1, 8)'), 'ref-index-upper': ('avd_av1_run_preamble', 'idx < 0 || idx >= V4L2_AV1_TOTAL_REFS_PER_FRAME', 'idx < 0'), - 'frame-width-unchecked': ('avd_av1_run_preamble', 'run->frame->frame_width_minus_1 + 1 > ctx->decoded_fmt.fmt.pix_mp.width ||', '0 ||'), + # The upscaled width bound also covers the frame width, so drop the frame size check as a whole. + 'frame-width-unchecked': ('avd_av1_check_frame_size', 'frame->frame_width_minus_1 >= width ||\n\t frame->frame_height_minus_1 >= height', '0'), } if args.mutation: target, old, new = mutations[args.mutation] From f2219746c1aef353661ee2da2fdf54f44942c5a8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:02:58 +1100 Subject: [PATCH 0615/1514] tools/asahi: update the MTP PM mocks for firmware clicks Model the waveform cache cleared on resume and stub the waveform helper used by FF uploads. Keep the older strength and softness mocks for the pre-waveform negative control. Signed-off-by: Ryan Murray --- tools/asahi/mtp-pm-tests.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/tools/asahi/mtp-pm-tests.py b/tools/asahi/mtp-pm-tests.py index 4846e41180ce48..ff78c0ac1e44b6 100644 --- a/tools/asahi/mtp-pm-tests.py +++ b/tools/asahi/mtp-pm-tests.py @@ -30,6 +30,7 @@ def function(source, name): #include #include #include +#include #define MAX_INTERFACES 16 #define PMSG_SUSPEND 1 #define HID_HAPTIC_MODE_DEVICE 0 @@ -66,6 +67,7 @@ def function(source, name): struct ff_effect { int id; struct { struct { u16 hid_usage, intensity; } haptic; } u; }; struct magicmouse_sc { struct hid_haptic_device *haptics; bool haptic_button_down, haptic_deep_down, haptic_suspended; int haptic_lock; + struct { bool read; u8 len, body[63]; } fw_click[2]; struct work_struct haptic_press_work, haptic_release_work, haptic_deep_work, haptic_deep_release_work; struct effect_job *haptic_effects; struct hid_device *hdev; struct delayed_work work; bool work_held; }; @@ -109,8 +111,6 @@ def function(source, name): switches++; switched_to = mode; return switch_error; } static bool magicmouse_effect_is_deep(struct ff_effect *e) { return e->u.haptic.hid_usage == APPLE_HP_WAVEFORMDEEPCLICK; } -static u8 magicmouse_haptic_strength(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } -static u8 magicmouse_haptic_softness(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } static int hid_driver_suspend(struct hid_device *h, int state) { assert(state == PMSG_SUSPEND && !transport->suspended); suspends[h->id]++; @@ -119,6 +119,18 @@ def function(source, name): return h->id == suspend_error_at ? -EBUSY : 0; } ''' +WAVEFORM = r''' +static void magicmouse_haptic_waveform(struct magicmouse_sc *m, struct hid_device *a, + u16 usage, u8 *strength, u8 *softness) { + assert(!transport->suspended); + *strength = *softness = 100; +} +''' +# Older sources used by --old-mouse predate the firmware waveform helper. +LEGACY_WAVEFORM = r''' +static u8 magicmouse_haptic_strength(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } +static u8 magicmouse_haptic_softness(struct hid_device *h, bool deep) { (void)h; (void)deep; return 100; } +''' MIDDLE = r''' static int hid_driver_resume(struct hid_device *h) { assert(!transport->suspended); @@ -237,7 +249,8 @@ def main(): 'magicmouse_haptic_effects_loaded', 'magicmouse_haptic_click', 'magicmouse_haptic_suspend', 'magicmouse_haptic_resume', 'magicmouse_switch_mode', 'apple_upload_effects', 'apple_taptic_playback', 'apple_taptic_erase')) + '\n' - c.write_text(PREFIX.replace('static int hid_driver_suspend', haptics + function(mouse, 'magicmouse_suspend') + + waveform = WAVEFORM if 'static void magicmouse_haptic_waveform(' in mouse else LEGACY_WAVEFORM + c.write_text(PREFIX.replace('static int hid_driver_suspend', waveform + haptics + function(mouse, 'magicmouse_suspend') + '\nstatic int hid_driver_suspend', 1) + function(mouse, 'magicmouse_resume') + function(mouse, 'magicmouse_reset_resume') + MIDDLE + function(source, 'dockchannel_hid_suspend') + '\n' + From 6cff81531d4fd5b6ef57c589b909c37a41b07823 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:08:15 +1100 Subject: [PATCH 0616/1514] accel/ane: t6021: keep the firmware buffer if its text cannot be remapped ane_t6021_fw_staged_protect() remaps the firmware's __TEXT pages read-only inside the coherent allocation. If a page can be neither mapped read-only nor put back read-write, or iommu_unmap() takes out only part of it, the error path frees the allocation with dma_free_coherent(), which then unmaps a range with a hole in it. Keep the allocation in that case (a bounded leak on a probe that fails anyway), and say why each step is all or nothing: one 16 KiB DART leaf, the IOTLB synced by iommu_unmap(). Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_t6021_fwload.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_fwload.c b/drivers/accel/ane/ane_t6021_fwload.c index 0cf57d0cf02922..69c7a0adc2c693 100644 --- a/drivers/accel/ane/ane_t6021_fwload.c +++ b/drivers/accel/ane/ane_t6021_fwload.c @@ -244,12 +244,20 @@ static int ane_t6021_pmu_map(struct ane_t6021 *ane, struct iommu_domain *dom) * fw_iova. Map the __TEXT pages there again, at the same IOVA and PA, * read-only. The IOVA range stays the DMA API's and the same number of * bytes stays mapped, so dma_free_coherent() unmaps it as before. + * + * Each step is one 16 KiB DART leaf (the coherent allocation is 16 KiB + * aligned in IOVA and PA, checked below), so iommu_unmap() takes it out + * whole or not at all, and it syncs the IOTLB before it returns. If a page + * can be neither mapped read-only nor put back read-write, the range has a + * hole that dma_free_coherent() would trip on: then the allocation is kept + * (fw_buf cleared, a bounded leak on a failed probe) instead of freed. */ static int ane_t6021_fw_staged_protect(struct ane_t6021 *ane) { const struct ane_t602x_soc *soc = of_device_get_match_data(ane->dev); struct iommu_domain *dom = iommu_get_domain_for_dev(ane->dev); int rw = IOMMU_READ | IOMMU_WRITE; + size_t unmapped; u64 off; int ret; @@ -268,15 +276,18 @@ static int ane_t6021_fw_staged_protect(struct ane_t6021 *ane) pa = iommu_iova_to_phys(dom, iova); if (!pa || pa & (ANE_T6021_FW_ALIAS_PAGE - 1)) return -EFAULT; - if (iommu_unmap(dom, iova, ANE_T6021_FW_ALIAS_PAGE) != - ANE_T6021_FW_ALIAS_PAGE) + unmapped = iommu_unmap(dom, iova, ANE_T6021_FW_ALIAS_PAGE); + if (unmapped != ANE_T6021_FW_ALIAS_PAGE) { + if (unmapped) + goto hole; return -EIO; + } ret = iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, prot, GFP_KERNEL); /* Never leave a hole for dma_free_coherent() to trip on. */ if (ret && iommu_map(dom, iova, pa, ANE_T6021_FW_ALIAS_PAGE, rw, GFP_KERNEL)) - dev_err(ane->dev, "fwload: +%#llx left unmapped\n", off); + goto hole; if (!ret && iommu_iova_to_phys(dom, iova) != pa) ret = -EIO; if (ret) { @@ -286,6 +297,13 @@ static int ane_t6021_fw_staged_protect(struct ane_t6021 *ane) } } return 0; + +hole: + dev_err(ane->dev, + "fwload: +%#llx left unmapped, keeping the firmware buffer\n", + off); + ane->fw_buf = NULL; + return -EIO; } static int ane_t6021_fw_alias_map(struct ane_t6021 *ane, bool reserved) From 4a460b5b560bec778cf50d828e1f67d6b5953eff Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:08:16 +1100 Subject: [PATCH 0617/1514] accel/ane: t6021: map the section copies read-only for the engine The kernel copies of a program's sections were dma_alloc_coherent() memory, which the DMA API maps read-write in the DART domain that also holds every client's buffers. A job on the engine could then change a shared program's copied task stream after PROG_LOAD checked it. Allocate the copies from kernel pages and map them DMA_TO_DEVICE, which dma-iommu maps read-only, as one IOVA range; the CPU fills them through a vmap and hands them to the device with a sync. The tail past the section is zeroed, as before. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_t6021_lifetime.h | 7 +- drivers/accel/ane/ane_t6021_rtclient_main.c | 111 ++++++++++++++++---- 2 files changed, 92 insertions(+), 26 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_lifetime.h b/drivers/accel/ane/ane_t6021_lifetime.h index 3a8307162c7d1c..5420e3f0da074d 100644 --- a/drivers/accel/ane/ane_t6021_lifetime.h +++ b/drivers/accel/ane/ane_t6021_lifetime.h @@ -223,9 +223,10 @@ struct ane_t6021_prog { /* * The sections of a program while PROG_LOAD builds it, by slot (id - 1). - * Each is a kernel copy no client can map: the cache key, the TD check and - * every LOAD of the program read the copy, never the caller's buffer, so - * what was keyed and checked is what the firmware reads. + * Each is a kernel copy no client can map and the engine maps read-only: + * the cache key, the TD check and every LOAD of the program read the copy, + * never the caller's buffer, so what was keyed and checked is what the + * firmware reads. */ struct ane_t6021_secs { void *mem[ANE_T6021_PROG_SECS]; /* driver allocation, NULL: no section */ diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 75e5a1a145b78f..ecb3242206e3e6 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -73,6 +73,7 @@ #include #include #include +#include #include #include #include @@ -1550,23 +1551,55 @@ static int ane_t6021_prog_unload_op(void *ctx, struct ane_t6021_prog *p) return ret; } -/* A program's kernel copy of one section: allocated for the same device as - * the BOs, so the firmware reaches it the same way, never mapped to - * userspace and not written after PROG_LOAD filled it. Counted against - * bo_total_max_mb like a BO. +/* A program's kernel copy of one section: kernel pages mapped for the same + * device as the BOs, never mapped to userspace and not written after + * PROG_LOAD filled it. The pages are mapped DMA_TO_DEVICE, which the DMA + * API maps read-only in the IOMMU: the engine, which runs every client's + * jobs in the same DART domain, can read the copy but not change it after + * it was checked. Counted against bo_total_max_mb like a BO. */ struct ane_t6021_sec_copy { struct device *dev; + struct page **pages; + unsigned int npages; + struct sg_table sgt; void *cpu; dma_addr_t dma; size_t size; /* allocated bytes, page aligned */ }; +static void ane_t6021_sec_copy_put_pages(struct ane_t6021_sec_copy *c) +{ + unsigned int i; + + for (i = 0; i < c->npages; i++) + if (c->pages[i]) + __free_page(c->pages[i]); + kvfree(c->pages); +} + +/* The mapping must be one IOVA range: a LOAD record names iova + size. */ +static bool ane_t6021_sec_copy_contiguous(const struct ane_t6021_sec_copy *c) +{ + struct scatterlist *sg; + dma_addr_t next = c->dma; + unsigned int i; + + for_each_sgtable_dma_sg(&c->sgt, sg, i) { + if (sg_dma_address(sg) != next) + return false; + next += sg_dma_len(sg); + } + return next - c->dma == c->size; +} + static struct ane_t6021_sec_copy * ane_t6021_sec_copy_alloc(struct ane_rtclient *ane, u64 size) { struct ane_t6021_sec_copy *c; size_t alloc; + unsigned int i; + int ret = -ENOMEM; /* No BO holds more, so a larger section is refused anyway. */ if (size > ANE_T6021_BO_MAX) @@ -1578,32 +1611,62 @@ ane_t6021_sec_copy_alloc(struct ane_rtclient *ane, u64 size) return ERR_PTR(-ENOSPC); } c = kzalloc_obj(*c); - if (!c) { - atomic64_sub(alloc, &ane_t6021_bo_total_bytes); - return ERR_PTR(-ENOMEM); - } - c->cpu = dma_alloc_coherent(ane->dev, alloc, &c->dma, GFP_KERNEL); - if (!c->cpu) { - atomic64_sub(alloc, &ane_t6021_bo_total_bytes); - kfree(c); - return ERR_PTR(-ENOMEM); + if (!c) + goto err_account; + c->dev = ane->dev; + c->size = alloc; + c->npages = alloc >> PAGE_SHIFT; + c->pages = kvcalloc(c->npages, sizeof(*c->pages), GFP_KERNEL); + if (!c->pages) + goto err_free; + /* Zeroed: the device reads the tail past the section too. */ + for (i = 0; i < c->npages; i++) { + c->pages[i] = alloc_page(GFP_KERNEL | __GFP_ZERO); + if (!c->pages[i]) + goto err_pages; } + if (sg_alloc_table_from_pages(&c->sgt, c->pages, c->npages, 0, alloc, + GFP_KERNEL)) + goto err_pages; + if (dma_map_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0)) + goto err_sgt; + c->dma = sg_dma_address(c->sgt.sgl); /* The same IOVA rules as a BO (see ane_t6021_bo_init_locked()). */ - if (!IS_ALIGNED(c->dma, SZ_16K) || + if (!ane_t6021_sec_copy_contiguous(c) || !IS_ALIGNED(c->dma, SZ_16K) || (ane->fw && !ane_t6021_fw_alias_iova_ok(ane->fw, c->dma, alloc))) { - dma_free_coherent(ane->dev, alloc, c->cpu, c->dma); - atomic64_sub(alloc, &ane_t6021_bo_total_bytes); - kfree(c); - return ERR_PTR(-ERANGE); + ret = -ERANGE; + goto err_unmap; } - c->dev = ane->dev; - c->size = alloc; + c->cpu = vmap(c->pages, c->npages, VM_MAP, PAGE_KERNEL); + if (!c->cpu) + goto err_unmap; return c; + +err_unmap: + dma_unmap_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0); +err_sgt: + sg_free_table(&c->sgt); +err_pages: + ane_t6021_sec_copy_put_pages(c); +err_free: + kfree(c); +err_account: + atomic64_sub(alloc, &ane_t6021_bo_total_bytes); + return ERR_PTR(ret); +} + +/* Hand what the CPU wrote to the copy over to the device. */ +static void ane_t6021_sec_copy_sync(struct ane_t6021_sec_copy *c) +{ + dma_sync_sgtable_for_device(c->dev, &c->sgt, DMA_TO_DEVICE); } static void ane_t6021_sec_copy_free(struct ane_t6021_sec_copy *c) { - dma_free_coherent(c->dev, c->size, c->cpu, c->dma); + vunmap(c->cpu); + dma_unmap_sgtable(c->dev, &c->sgt, DMA_TO_DEVICE, 0); + sg_free_table(&c->sgt); + ane_t6021_sec_copy_put_pages(c); atomic64_sub(c->size, &ane_t6021_bo_total_bytes); kfree(c); } @@ -1812,8 +1875,8 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, /* Copy every section out of the caller's buffer into kernel memory no * client can map, then key and check the copies: identical sections * share one firmware program (see the table), and the bytes keyed and - * checked here are the bytes every LOAD of the program names. The - * buffer is read once, under bo_lock. + * checked here are the bytes every LOAD of the program names. Each + * copy is made with one read of the buffer, under bo_lock. */ /* Every section must name a BO of this file that holds it. */ for (i = 0; i < user->section_count; i++) { @@ -1846,6 +1909,8 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, sections[i].offset, sections[i].size); mutex_unlock(&ane_t6021_bo_lock); + if (bo) + ane_t6021_sec_copy_sync(c); if (!bo) { ane_t6021_sec_copy_free(c); ret = -EINVAL; From c652d43833465a3e0265e0e6a94fcf1ac61a41bd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:08:16 +1100 Subject: [PATCH 0618/1514] accel/ane: t6021: find a loaded program before copying its sections PROG_LOAD now copies every section into kernel memory, charged to bo_total_max_mb, before it looks the program up in the table. Loading a program that is already there, which needs no copies, could then fail with -ENOSPC close to the cap. Key the caller's sections in place first and reuse a program found that way; only a new program gets copies, which are keyed and checked again. Bytes that change in between only change the key: the firmware only ever reads checked copies. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_t6021_lifetime.h | 3 +- drivers/accel/ane/ane_t6021_rtclient_main.c | 35 ++++++++++++++++++--- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/drivers/accel/ane/ane_t6021_lifetime.h b/drivers/accel/ane/ane_t6021_lifetime.h index 5420e3f0da074d..0d20f3687c41fa 100644 --- a/drivers/accel/ane/ane_t6021_lifetime.h +++ b/drivers/accel/ane/ane_t6021_lifetime.h @@ -226,7 +226,8 @@ struct ane_t6021_prog { * Each is a kernel copy no client can map and the engine maps read-only: * the cache key, the TD check and every LOAD of the program read the copy, * never the caller's buffer, so what was keyed and checked is what the - * firmware reads. + * firmware reads. PROG_LOAD also keys a view of the caller's buffers (mem + * the BOs) to find a program already loaded; that view is never loaded. */ struct ane_t6021_secs { void *mem[ANE_T6021_PROG_SECS]; /* driver allocation, NULL: no section */ diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index ecb3242206e3e6..bcbc1b96fff444 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -1878,18 +1878,43 @@ static int ane_rtclient_load_program(struct ane_rtclient *ane, * checked here are the bytes every LOAD of the program names. Each * copy is made with one read of the buffer, under bo_lock. */ - /* Every section must name a BO of this file that holds it. */ - for (i = 0; i < user->section_count; i++) { - bool ok; + /* Every section must name a BO of this file that holds it. A program + * already in the table has its own checked copies, so look it up from + * the caller's bytes first: loading it again takes no copies and no + * part of bo_total_max_mb. Bytes changed meanwhile only change the + * key; they are never what the firmware reads. + */ + { + struct ane_t6021_secs view = {}; mutex_lock(&ane_t6021_bo_lock); - ok = ane_t6021_sec_bo_locked(fd, §ions[i]); + for (i = 0; i < user->section_count; i++) { + struct ane_t6021_bo *bo; + unsigned int slot = sections[i].id - 1; + + bo = ane_t6021_sec_bo_locked(fd, §ions[i]); + if (!bo) + break; + view.mem[slot] = bo; + view.cpu[slot] = (u8 *)bo->cpu + sections[i].offset; + view.size[slot] = sections[i].size; + } + if (i == user->section_count) + ane_t6021_secs_key(&view, digest); mutex_unlock(&ane_t6021_bo_lock); - if (!ok) { + if (i < user->section_count) { ret = -EINVAL; goto out; } } + cached = ane_t6021_prog_find(digest); + if (cached) { + ret = ane_t6021_fdprogs_ref(&ane_t6021_progtab, &fd->progs, + cached); + if (!ret) + *prog_id = cached->prog_id; + goto out; + } for (i = 0; i < user->section_count; i++) { struct ane_t6021_sec_copy *c; struct ane_t6021_bo *bo; From 431ba9acd286438f7695368d155102bb9bab740d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:08:16 +1100 Subject: [PATCH 0619/1514] accel/ane: test the arena release after the warm-sleep commands ane_fw_suspend_firmware() releases the arena taken by EXCLAVE_MODE_STOP and SUSPEND once both are answered. Test that sequence on the transport: the release is refused while a command is pending, gives the arena back once both replies were read, and the next sleep's commands land where the previous ones did. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_transport_test.c | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/drivers/accel/ane/ane_fw_transport_test.c b/drivers/accel/ane/ane_fw_transport_test.c index c38415ada6c6b6..bb4ee79f0a3701 100644 --- a/drivers/accel/ane/ane_fw_transport_test.c +++ b/drivers/accel/ane/ane_fw_transport_test.c @@ -1273,6 +1273,46 @@ static void ane_transport_mode_stop_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->t.error, 0); } +/* + * A warm sleep publishes EXCLAVE_MODE_STOP and SUSPEND on a transport that + * survives the wake (ane_fw_suspend_firmware()). Once both are answered and + * the SUSPEND reply was read, releasing to the mark taken before them gives + * the arena back: the next command lands where 0x31 did, and sleep after + * sleep the arena does not shrink. + */ +static void ane_transport_sleep_release_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + u8 command[8] = {}; + u32 ch = f->t.control_ch; + size_t mark; + u64 first; + unsigned int i; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + mark = ane_fw_transport_mark(&f->t); + for (i = 0; i < 64; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_transport_publish_mode_stop(&f->t, TEST_DEADLINE), 0); + if (!i) + first = f->t.pending[ch].dva; + KUNIT_ASSERT_EQ(test, f->t.pending[ch].dva, first); + /* Released too early: a command is still pending. */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_release(&f->t, mark), -EBUSY); + ane_test_reply(f, ch); + KUNIT_ASSERT_EQ(test, ane_fw_transport_wait(&f->t, ch), 0); + + put_unaligned_le16(0x24, command + 4); /* SUSPEND */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_publish(&f->t, ANE_FW_IO, command, + sizeof(command), TEST_DEADLINE), 0); + KUNIT_ASSERT_GT(test, ane_fw_transport_mark(&f->t), mark); + ane_test_reply(f, ANE_FW_IO); + KUNIT_ASSERT_EQ(test, ane_fw_transport_wait(&f->t, ANE_FW_IO), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_release(&f->t, mark), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_mark(&f->t), mark); + } + KUNIT_EXPECT_EQ(test, f->t.error, 0); +} + /* * The control ring completes without clearing the result word (H17 C6): * DVA|1, length, and the published size still in word 2. Accepted there; @@ -1588,6 +1628,7 @@ static struct kunit_case ane_transport_cases[] = { KUNIT_CASE(ane_transport_wait_test), KUNIT_CASE(ane_transport_wait_polls_test), KUNIT_CASE(ane_transport_poll_sleep_test), + KUNIT_CASE(ane_transport_sleep_release_test), {} }; From f6802833eb5dcfe2fa5cb2ca47d953cdace53ac2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:22:47 +1100 Subject: [PATCH 0620/1514] drm/asahi: charge a client VM's heap blocks to the client The kernel heaps of a client VM grow with what the client submits: the legacy scene buffers (tile map, TPC, layer meta) are sized from its render targets, and the heaps never shrink until the VM goes away. Their blocks were kernel objects, counted towards the device total but attributed to no client, so the per-client limit never applied to them and one client could take memory every other client then lacked. When the heap's VM belongs to a client, admit each new block against that client's and the device's limits and count it as the client's held memory, as the G17 pools already do; a refused block fails with ENOMEM. The kernel VM's heaps are unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/alloc.rs | 24 +++++++++++++++++++++--- drivers/gpu/drm/asahi/gem.rs | 7 +++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/alloc.rs b/drivers/gpu/drm/asahi/alloc.rs index 10e367b1a15fae..d2f46dc0c9c76e 100644 --- a/drivers/gpu/drm/asahi/alloc.rs +++ b/drivers/gpu/drm/asahi/alloc.rs @@ -674,7 +674,13 @@ impl RawAllocation for HeapAllocation { struct HeapAllocatorInner { dev: AsahiDevRef, allocated: usize, - backing_objects: KVec<(crate::gem::ObjectRef, mmu::KernelMapping, u64)>, + /// Each block, its mapping, its GPU address and, for a client VM, its charge. + backing_objects: KVec<( + crate::gem::ObjectRef, + mmu::KernelMapping, + u64, + Option, + )>, garbage: Option>>, total_garbage: usize, name: CString, @@ -789,7 +795,19 @@ impl HeapAllocator { ); } - let mut obj = crate::gem::new_kernel_object(&self.dev, size_aligned)?; + // A client VM's heap grows with what the client submits (scene buffers are sized + // from its render targets), so its blocks count against that client's limit, like + // the client's own objects, and not as kernel memory. + let (mut obj, charge) = match self.vm.memory_client() { + Some(client) => { + let commit = crate::memacct::LEDGER.admit(client, size_aligned as u64)?; + let obj = crate::gem::new_kernel_object_user_charged(&self.dev, size_aligned)?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + (obj, Some(charge)) + } + None => (crate::gem::new_kernel_object(&self.dev, size_aligned)?, None), + }; if self.cpu_maps && debug_enabled(DebugFlags::FillAllocations) { let obj_size = obj.size(); if let Ok(vmap) = obj.vmap() { @@ -868,7 +886,7 @@ impl HeapAllocator { self.mm.with_inner(|inner| { inner .backing_objects - .push((obj, mapping, gpu_ptr), GFP_KERNEL) + .push((obj, mapping, gpu_ptr, charge), GFP_KERNEL) })?; self.top = new_top; diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index bad222981a6aef..82ca4bdcf08a23 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -291,6 +291,13 @@ pub(crate) fn new_kernel_object_wc(dev: &AsahiDrmDevice, size: usize) -> Result< new_kernel_object_mapped(dev, size, true, true) } +/// Create a new kernel-owned GEM object that is not counted as kernel memory: its owner holds a +/// user charge for it ([`memacct::Charge::user`]), and counting both would take its size twice +/// from the device limit. +pub(crate) fn new_kernel_object_user_charged(dev: &AsahiDrmDevice, size: usize) -> Result { + new_kernel_object_mapped(dev, size, false, false) +} + /// Create a new kernel-owned write-combined GEM object that is not counted as kernel memory: /// its owner holds a user charge for it ([`memacct::Charge::user`]), and counting both would /// take its size twice from the device limit. From 252865675ba6befcfc283f32cb2e05fbeb7a5dce Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:13:11 +1100 Subject: [PATCH 0621/1514] accel/ane: refuse a buffer size that rounds up past u64 ane_bo_check_size() compares the size, then the size rounded up to a page, with the device address range. With the H13 range of at most 4 GiB the first comparison rules out every size that round_up() would wrap, but for a range near U64_MAX the round_up() of a size in the last page below 2^64 wraps to 0 and the check passes. Refuse such a size before rounding it, so the check holds for any range. DRM_IOCTL_ANE_SUBMIT now puts the job's buffers into the device address space (they are mapped per job), so it can fail with -ENOMEM where only BO_INIT could before. Say so in the uapi comment. KUnit: ane-bo checks the size check against a range of U64_MAX with U64_MAX, a size one byte past the last whole page, and the last whole page. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_drv.c | 3 ++- drivers/accel/ane/ane_drv_test.c | 6 ++++++ include/uapi/drm/ane_accel.h | 4 +++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index 489bc6e3b0f14c..df842826b759d9 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -145,7 +145,8 @@ VISIBLE_IF_KUNIT int ane_bo_check_size(u64 size, u64 iova_span) { if (!size) return -EINVAL; - if (size > iova_span || round_up(size, PAGE_SIZE) > iova_span) + if (size > iova_span || size > U64_MAX - (PAGE_SIZE - 1) || + round_up(size, PAGE_SIZE) > iova_span) return -E2BIG; return 0; } diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index ae8f151c4dea77..55120a0e0510ec 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -182,6 +182,12 @@ static const struct ane_bo_size_case ane_bo_size_cases[] = { { "page count past u32", (u64)PAGE_SIZE << 32, ANE_TEST_SPAN, -E2BIG }, { "largest u64", U64_MAX, ANE_TEST_SPAN, -E2BIG }, { "rounds up past a smaller range", SZ_16K + 1, SZ_16K + 1, -E2BIG }, + /* round_up() would wrap to 0 below these, for any range. */ + { "largest u64, whole u64 range", U64_MAX, U64_MAX, -E2BIG }, + { "one byte past the last whole page, whole u64 range", + U64_MAX - (PAGE_SIZE - 1) + 1, U64_MAX, -E2BIG }, + { "last whole page, whole u64 range", U64_MAX - (PAGE_SIZE - 1), + U64_MAX, 0 }, }; KUNIT_ARRAY_PARAM_DESC(ane_bo_size, ane_bo_size_cases, desc); diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h index 584d138436a7bb..584551aac81daa 100644 --- a/include/uapi/drm/ane_accel.h +++ b/include/uapi/drm/ane_accel.h @@ -159,7 +159,9 @@ struct drm_ane_bo_free { * A successful SUBMIT returns after the engine completed the work, with the * output buffers visible to the CPU. While it runs, the engine reaches only * the buffers in @handles and @btsp_handle: an access outside them faults - * and fails the SUBMIT. + * and fails the SUBMIT. The buffers are put into the device address space + * by the SUBMIT that names them, not by BO_INIT, so a SUBMIT can also fail + * with -ENOMEM when there is no memory to map them. */ struct drm_ane_submit { __u64 tsk_size; From 401c4ce3a98724b60c5357e6accf67a7ae7eb8eb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 18:14:56 +1100 Subject: [PATCH 0622/1514] accel/ane: drain a fault in the range of a buffer not in the DART Since the DART holds only the running job's buffers, every other buffer object keeps its reserved IOVA range without PTEs, and the allocator packs those ranges back to back. So a job that reads or writes a few bytes past the end of one of its buffers, or whose descriptor points at another buffer of its own or of another file, faults inside a reserved range. ane_dart_drain_fault() reserves a drm_mm node for the scratch page; that fails there, the drain is refused and the job ends in a timeout and a power cycle instead of a contained -EIO; repeated, that wedges the engine for every file. Label each node of the allocator with what owns it (drm_mm_node.color; the allocator has no color_adjust): a BO range not in the DART, a BO range in the DART, a drain page, a wedge-preserved range. The drain puts its page into a hole as before (reserving a node for it), or into the range of a BO that is not in the DART, and records that BO's node. Ranges with PTEs are still refused. A drain page must never outlive the drain into a mapped buffer or a reused range. The scratch pages are released when the faulting job completes (ane_tm_execute(), under engine_lock), or, when the job wedged the engine, by ane_reclaim_preserved() after the recovery power cycle. No SUBMIT runs in between: it needs engine_lock and refuses a wedged engine. Close the remaining paths explicitly: - ane_bo_dart_map() refuses (and warns about) a BO whose range holds a drain page. Mapping over it would take the scratch PTE for a stray and clear it, and the scratch release would then unmap the BO's own page. - A BO freed while a drain page sits in its range is preserved like a wedged mapped BO, so its range stays reserved until the scratch is released; the reclaim unmaps only the pages of preserved BOs that were in the DART. - Driver remove releases the drain pages before it frees the BO ranges. KUnit: ane-bo checks where a drain page may go (the packed neighbour of a job's buffer, a buffer of another file, a hole; not a mapped buffer, a drain page, a preserved range or past the allocator range), and that a BO's range is seen as holding a drain page until the release. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane.h | 26 ++++++ drivers/accel/ane/ane_dart.c | 135 ++++++++++++++++++++++--------- drivers/accel/ane/ane_drv.c | 42 ++++++++-- drivers/accel/ane/ane_drv_test.c | 103 +++++++++++++++++++++++ 4 files changed, 262 insertions(+), 44 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index 8bf18a4f9ffb54..eb614547ddebdb 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -20,10 +20,33 @@ #define ANE_DART_MAX 3 #define ANE_DART_SCRATCH_MAX 16 +/* + * What owns a node of ane_device.mm, kept in drm_mm_node.color (the + * allocator has no color_adjust, so the color only labels the node). + * Written under iommu_lock. + */ +enum ane_mm_owner { + ANE_MM_NONE, + /* A BO's range, its pages not in the DART. */ + ANE_MM_BO_UNMAPPED, + /* A BO's range, its pages in the DART. */ + ANE_MM_BO_MAPPED, + /* A fault-drain page in a hole, reserved by the drain. */ + ANE_MM_SCRATCH, + /* The range of a BO freed while wedged (ane_preserve_bo()). */ + ANE_MM_PRESERVED, +}; + +/* + * A fault-drain page. @node is the node the drain reserved for a page in + * a hole; @host is the node of an unmapped BO whose range holds the page. + * Exactly one of them is set. + */ struct ane_dart_scratch { u64 iova; struct page *page; struct drm_mm_node *node; + struct drm_mm_node *host; }; struct ane_device { @@ -237,6 +260,8 @@ static inline bool ane_tm_failure_recoverable(bool tm_retention, u64 ane_bo_iova_size(u32 npages, unsigned int shift); int ane_bo_check_size(u64 size, u64 iova_span); struct page *ane_dart_alloc_scratch_page(void); +int ane_dart_scratch_slot(struct drm_mm *mm, u64 iova, u64 size, + struct drm_mm_node **host); int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, size_t btsp_size); #endif @@ -267,5 +292,6 @@ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, struct ane_dart_scratch *scratch, int *pages); void ane_dart_release_scratch(struct ane_device *ane, struct ane_dart_scratch *scratch, int pages); +bool ane_dart_scratch_in(struct ane_device *ane, struct drm_mm_node *host); #endif /* __ANE_H__ */ diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index 9b141774b463c4..152c8a1368b1ff 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -182,6 +182,55 @@ VISIBLE_IF_KUNIT struct page *ane_dart_alloc_scratch_page(void) } EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); +/* + * Where may a fault-drain page go? A fault is a missing PTE in one of two + * places. In a hole of the allocator (a wild address), the drain reserves + * a node for the page (@host stays NULL). Or in the range of a BO that is + * not in the DART: ane_submit() takes every BO that the job does not name + * out of the DART, so an access past the end of a job's buffer, or a + * descriptor that points at another buffer of this or another file, lands + * there; the ranges are packed, so this is the common case. The page then + * goes into that BO's range and @host is the BO's node. That BO cannot get + * its pages back into the DART, nor its range back to the allocator, while + * the page is there (ane_dart_scratch_in()), so no scratch PTE outlives + * the drain into a mapped BO. Anything else (a mapped BO, a scratch page, + * a wedge-preserved range) has PTEs and cannot fault: refuse it. + * + * Callers hold iommu_lock. + */ +VISIBLE_IF_KUNIT int ane_dart_scratch_slot(struct drm_mm *mm, u64 iova, + u64 size, struct drm_mm_node **host) +{ + struct drm_mm_node *node; + + *host = NULL; + if (iova + size < iova) + return -EINVAL; + drm_mm_for_each_node_in_range(node, mm, iova, iova + size) { + /* Past the end of the range that the allocator manages. */ + if (node == &mm->head_node) + return -ERANGE; + if (node->color != ANE_MM_BO_UNMAPPED || + node->start > iova || + node->start + node->size < iova + size) + return -EBUSY; + *host = node; + return 0; + } + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_scratch_slot); + +/* Does a drain page sit in the range of the BO that owns @host? */ +bool ane_dart_scratch_in(struct ane_device *ane, struct drm_mm_node *host) +{ + for (int i = 0; i < ane->scratch_pages; i++) + if (host && ane->scratch[i].host == host) + return true; + return false; +} +EXPORT_SYMBOL_IF_KUNIT(ane_dart_scratch_in); + /* * A fault is a missing PTE, nothing more: the page tables are provider * owned and unchanged, so the stream-restore apple-dart uses at reset @@ -191,69 +240,76 @@ EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); * completes and the engine drains on its own; the scratch pages are * unmapped once the request has been failed cleanly. * - * The throwaway page is mapped at the faulting address, which is - * allocator-free by definition of a translation fault - but the drm_mm - * allocator knows nothing about a raw iommu_map. A scratch PTE that - * outlives its release path (any future bug on the wedge side) would - * then sit, untracked, in a range the allocator considers free: the - * next BO_INIT maps onto it and fails with dart_init_pte's "we require - * an unmap first" WARN. So the scratch range is RESERVED in the - * allocator first: a node-tracked mapping can never collide with a - * later BO_INIT, and a scratch whose release is skipped degrades into - * a bounded, benign leak instead of a poisoned address space. Reserve - * failure means a live BO node already owns the faulting page (a wild - * descriptor, not a hole): a BO of another job, which ane_submit() took - * out of the DART for this one. Refuse and let the caller wedge and - * recover, fail closed. + * The drm_mm allocator knows nothing about a raw iommu_map, so a scratch + * PTE is always inside a node: one the drain reserves in a hole, or the + * node of the unmapped BO it landed in (ane_dart_scratch_slot()). A + * node-tracked mapping can never collide with a later BO_INIT, and a + * scratch whose release is skipped degrades into a bounded, benign leak + * instead of a poisoned address space. A page that no drain may take + * is refused, and the caller wedges and recovers, fail closed. + * + * Callers hold engine_lock, which keeps the BOs' DART state still. */ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, struct ane_dart_scratch *scratch, int *pages) { - struct drm_mm_node *node; + struct drm_mm_node *node = NULL, *host; struct page *page; u64 iova; int ret, i; + lockdep_assert_held(&ane->engine_lock); page = ane_dart_alloc_scratch_page(); if (!page) return -ENOMEM; iova = fault_iova & ~((1ULL << ane->shift) - 1); - node = kzalloc_obj(*node); - if (!node) { - __free_page(page); - return -ENOMEM; - } - node->start = iova; - node->size = BIT(ane->shift); - mutex_lock(&ane->iommu_lock); - ret = drm_mm_reserve_node(&ane->mm, node); - if (ret) { - mutex_unlock(&ane->iommu_lock); - kfree(node); - __free_page(page); - return ret; + ret = ane_dart_scratch_slot(&ane->mm, iova, BIT(ane->shift), &host); + if (ret) + goto refuse; + if (!host) { + node = kzalloc_obj(*node); + if (!node) { + ret = -ENOMEM; + goto refuse; + } + node->start = iova; + node->size = BIT(ane->shift); + node->color = ANE_MM_SCRATCH; + ret = drm_mm_reserve_node(&ane->mm, node); + if (ret) { + kfree(node); + goto refuse; + } } ret = iommu_map(ane->domain, iova, page_to_phys(page), BIT(ane->shift), IOMMU_READ | IOMMU_WRITE, GFP_KERNEL); - mutex_unlock(&ane->iommu_lock); if (ret) { - mutex_lock(&ane->iommu_lock); - drm_mm_remove_node(node); - mutex_unlock(&ane->iommu_lock); - kfree(node); - __free_page(page); - return ret; + if (node) { + drm_mm_remove_node(node); + kfree(node); + } + goto refuse; } + mutex_unlock(&ane->iommu_lock); + dev_dbg(ane->dev, "fault drain: page at %#llx in %s\n", iova, + host ? "an unmapped buffer's range" : "a hole"); scratch[*pages].iova = iova; scratch[*pages].page = page; scratch[*pages].node = node; + scratch[*pages].host = host; (*pages)++; for (i = 0; i < ane->dart_count; i++) ane_dart_invalidate(ane, &ane->darts[i]); return 0; + +refuse: + mutex_unlock(&ane->iommu_lock); + __free_page(page); + dev_dbg(ane->dev, "fault drain refused at %#llx: %d\n", iova, ret); + return ret; } void ane_dart_release_scratch(struct ane_device *ane, @@ -271,9 +327,12 @@ void ane_dart_release_scratch(struct ane_device *ane, dev_err(ane->dev, "scratch unmap short at %#llx: %zu\n", scratch[i].iova, unmapped); - drm_mm_remove_node(scratch[i].node); - kfree(scratch[i].node); + if (scratch[i].node) { + drm_mm_remove_node(scratch[i].node); + kfree(scratch[i].node); + } scratch[i].node = NULL; + scratch[i].host = NULL; __free_page(scratch[i].page); scratch[i].page = NULL; } diff --git a/drivers/accel/ane/ane_drv.c b/drivers/accel/ane/ane_drv.c index df842826b759d9..37c27a726071f5 100644 --- a/drivers/accel/ane/ane_drv.c +++ b/drivers/accel/ane/ane_drv.c @@ -302,7 +302,8 @@ static int ane_iommu_reserve(struct ane_device *ane, struct ane_bo *bo) /* reserve area from ANE address space */ err = drm_mm_insert_node_generic(&ane->mm, bo->mm, ane_bo_iova_size(bo->npages, ane->shift), - 1UL << ane->shift, 0, 0); + 1UL << ane->shift, ANE_MM_BO_UNMAPPED, + 0); mutex_unlock(&ane->iommu_lock); if (err < 0) { dev_err(ane->dev, "out of ANE space: %d\n", err); @@ -315,7 +316,15 @@ static int ane_iommu_reserve(struct ane_device *ane, struct ane_bo *bo) return 0; } -/* Put the pages of a BO with a reserved range into the DART. */ +/* + * Put the pages of a BO with a reserved range into the DART. A fault + * drain may have put a scratch page into the range of a BO that is not in + * the DART (ane_dart_drain_fault()); the scratch pages are released when + * the faulting job completes or at the recovery after it, both before any + * later SUBMIT gets here, so such a page is never found here. Refuse it + * anyway: mapping over it would take the scratch PTE for a stray and + * clear it, and the scratch release would then unmap the BO's page. + */ static int ane_bo_dart_map(struct ane_device *ane, struct ane_bo *bo) { int err; @@ -325,12 +334,16 @@ static int ane_bo_dart_map(struct ane_device *ane, struct ane_bo *bo) return 0; if (!bo->mm) return -EINVAL; + if (WARN_ON_ONCE(ane_dart_scratch_in(ane, bo->mm))) + return -EBUSY; mutex_lock(&ane->iommu_lock); if (READ_ONCE(map_batch)) err = ane_iommu_map_batch(ane, bo, bo->prot); else err = ane_iommu_map_each(ane, bo, bo->prot); + if (!err) + bo->mm->color = ANE_MM_BO_MAPPED; mutex_unlock(&ane->iommu_lock); if (err < 0) return err; @@ -361,6 +374,7 @@ static void ane_bo_dart_unmap(struct ane_device *ane, struct ane_bo *bo) bo->iova, size, unmapped); ane_iommu_clear_range(ane, bo->iova, bo->iova + size); } + bo->mm->color = ANE_MM_BO_UNMAPPED; mutex_unlock(&ane->iommu_lock); list_del_init(&bo->mapped_node); @@ -379,6 +393,8 @@ static void ane_iommu_unmap_pages(struct ane_device *ane, struct ane_bo *bo) list_del_init(&bo->node); ane_bo_dart_unmap(ane, bo); + /* ane_gem_free_object() preserves a range that holds a drain page. */ + WARN_ON_ONCE(ane_dart_scratch_in(ane, mm)); mutex_lock(&ane->iommu_lock); drm_mm_remove_node(mm); bo->mm = NULL; @@ -438,12 +454,17 @@ struct ane_preserved { struct drm_mm_node *mm; struct page **pages; u32 npages; + /* The BO's pages were in the DART, not only drain pages. */ + bool mapped; }; static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) { struct ane_preserved *p; + mutex_lock(&ane->iommu_lock); + bo->mm->color = ANE_MM_PRESERVED; + mutex_unlock(&ane->iommu_lock); p = kzalloc_obj(*p); if (!p) { /* Fail closed the old way: the node stays inserted and the @@ -457,6 +478,7 @@ static void ane_preserve_bo(struct ane_device *ane, struct ane_bo *bo) p->mm = bo->mm; p->pages = bo->pages; p->npages = bo->npages; + p->mapped = bo->mapped; list_add_tail(&p->list, &ane->preserved_list); bo->mm = NULL; bo->pages = NULL; @@ -475,7 +497,8 @@ void ane_reclaim_preserved(struct ane_device *ane) u64 iova = p->mm->start; mutex_lock(&ane->iommu_lock); - for (u32 i = 0; i < p->npages; i++) { + /* Its drain pages went with the scratch release above. */ + for (u32 i = 0; p->mapped && i < p->npages; i++) { size_t unmapped; unmapped = iommu_unmap(ane->domain, @@ -540,7 +563,13 @@ static void ane_gem_free_object(struct drm_gem_object *gem) mutex_lock(&ane->engine_lock); if (bo->mm) { - if (atomic_read(&ane->wedged) && bo->mapped) { + /* + * A drain page in the range of a BO that is not in the DART + * stays until the recovery that follows the wedge, and the + * range must stay reserved until then. + */ + if ((atomic_read(&ane->wedged) && bo->mapped) || + ane_dart_scratch_in(ane, bo->mm)) { /* Fail closed: keep the mapping and the pages so no * IOVA is torn down or page reused underneath active * DMA. The range's node stays reserved and tracked @@ -554,8 +583,8 @@ static void ane_gem_free_object(struct drm_gem_object *gem) dev_err(ane->dev, "wedged: preserving bo mapping\n"); list_del_init(&bo->node); list_del_init(&bo->mapped_node); - bo->mapped = false; ane_preserve_bo(ane, bo); + bo->mapped = false; } else { ane_iommu_unmap_pages(ane, bo); } @@ -1486,9 +1515,10 @@ static void ane_platform_remove(struct platform_device *pdev) return; } + /* Drain pages first: they may sit in the range of a listed BO. */ + ane_reclaim_preserved(ane); list_for_each_entry_safe(bo, tmp, &ane->bo_list, node) ane_iommu_unmap_pages(ane, bo); - ane_reclaim_preserved(ane); drm_mm_takedown(&ane->mm); ane_detach_genpd(ane); diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index 55120a0e0510ec..5065c94379e073 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -10,6 +10,8 @@ #include #include +#include + #include "ane.h" struct ane_submit_size_case { @@ -237,10 +239,111 @@ static void ane_dart_scratch_page_zeroed_test(struct kunit *test) } } +/* + * Where a fault-drain page may go. The H13 layout: 16 KiB DART pages, + * BO ranges packed back to back by the allocator. A job's buffer is in + * the DART (MAPPED); the next BO, of this or another file, is not + * (UNMAPPED), so a read a few bytes past the job's buffer faults in the + * neighbour's range. + */ +#define ANE_TEST_PG SZ_16K + +static struct drm_mm_node *ane_test_node(struct kunit *test, struct drm_mm *mm, + u64 page, u64 pages, + enum ane_mm_owner owner) +{ + struct drm_mm_node *node = kunit_kzalloc(test, sizeof(*node), + GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, node); + node->start = page * ANE_TEST_PG; + node->size = pages * ANE_TEST_PG; + node->color = owner; + KUNIT_ASSERT_EQ(test, drm_mm_reserve_node(mm, node), 0); + return node; +} + +static void ane_dart_scratch_slot_test(struct kunit *test) +{ + struct drm_mm_node *job, *next, *other, *scratch, *kept, *host; + struct drm_mm mm; + + /* One page above zero up to 64 pages. */ + drm_mm_init(&mm, ANE_TEST_PG, 63 * ANE_TEST_PG); + job = ane_test_node(test, &mm, 1, 4, ANE_MM_BO_MAPPED); + next = ane_test_node(test, &mm, 5, 3, ANE_MM_BO_UNMAPPED); + other = ane_test_node(test, &mm, 8, 2, ANE_MM_BO_UNMAPPED); + scratch = ane_test_node(test, &mm, 12, 1, ANE_MM_SCRATCH); + kept = ane_test_node(test, &mm, 13, 2, ANE_MM_PRESERVED); + + /* Past the end of the job's buffer: the packed neighbour. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 5 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); + /* Inside and at the last page of a buffer the job does not name. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 6 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 9 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, other); + /* A hole: the drain reserves its own node. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 10 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NULL(test, host); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 40 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NULL(test, host); + /* Ranges with PTEs cannot take a drain page. */ + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 4 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 12 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 14 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_NULL(test, host); + /* Past the end of the allocator range. */ + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(&mm, 64 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(&mm, U64_MAX & ~(u64)(ANE_TEST_PG - 1), + ANE_TEST_PG, &host), 0); + + drm_mm_remove_node(job); + drm_mm_remove_node(next); + drm_mm_remove_node(other); + drm_mm_remove_node(scratch); + drm_mm_remove_node(kept); + drm_mm_takedown(&mm); +} + +/* + * A BO whose range holds a drain page must not be mapped or have its + * range freed until the drain page is released. + */ +static void ane_dart_scratch_in_test(struct kunit *test) +{ + struct ane_device *ane = kunit_kzalloc(test, sizeof(*ane), GFP_KERNEL); + struct drm_mm_node a = {}, b = {}; + + KUNIT_ASSERT_NOT_NULL(test, ane); + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &a)); + ane->scratch[0].host = NULL; /* a page in a hole */ + ane->scratch[1].host = &b; + ane->scratch_pages = 2; + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &a)); + KUNIT_EXPECT_TRUE(test, ane_dart_scratch_in(ane, &b)); + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, NULL)); + /* Released: the count is what the drain and release maintain. */ + ane->scratch_pages = 0; + KUNIT_EXPECT_FALSE(test, ane_dart_scratch_in(ane, &b)); +} + static struct kunit_case ane_bo_test_cases[] = { KUNIT_CASE(ane_bo_iova_size_test), KUNIT_CASE_PARAM(ane_bo_check_size_test, ane_bo_size_gen_params), KUNIT_CASE(ane_dart_scratch_page_zeroed_test), + KUNIT_CASE(ane_dart_scratch_slot_test), + KUNIT_CASE(ane_dart_scratch_in_test), {} }; From ed1933742b48bfec18427afb713ed3e3f4125812 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 19:12:02 +1100 Subject: [PATCH 0623/1514] EDAC/apple: keep KUnit redirects out of the production driver Signed-off-by: Ryan Murray --- drivers/edac/apple_soc_edac-test.c | 1 + drivers/edac/apple_soc_edac.c | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/drivers/edac/apple_soc_edac-test.c b/drivers/edac/apple_soc_edac-test.c index 5d54283d1ce912..56e8e7b730b13b 100644 --- a/drivers/edac/apple_soc_edac-test.c +++ b/drivers/edac/apple_soc_edac-test.c @@ -170,6 +170,7 @@ static unsigned long edac_test_fire(struct kunit *test, before = jiffies; KUNIT_EXPECT_EQ(test, IRQ_HANDLED, apple_soc_edac_irq_thread(irq_data->irq, irq_data)); + KUNIT_EXPECT_EQ(test, ctx->fake.stray, 0U); after = jiffies; if (!delayed_work_pending(&irq_data->rearm)) { diff --git a/drivers/edac/apple_soc_edac.c b/drivers/edac/apple_soc_edac.c index 7bbc3230b1a396..311357066ccc21 100644 --- a/drivers/edac/apple_soc_edac.c +++ b/drivers/edac/apple_soc_edac.c @@ -5,7 +5,9 @@ * Copyright The Aurora Silicon Contributors */ +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) #include +#endif #include #include #include @@ -222,13 +224,17 @@ static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, /* Status register accessors; KUnit redirects them to a fake register block. */ static u32 apple_soc_edac_read(void __iomem *reg) { +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_read, reg); +#endif return readl(reg); } static void apple_soc_edac_write(void __iomem *reg, u32 val) { +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_write, reg, val); +#endif writel(val, reg); } From d64d9816b3ded241a0e1d9672db9f52856b14b89 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 19:12:14 +1100 Subject: [PATCH 0624/1514] drm/apple: audio: hold the DP audio domain only while the DCP firmware runs dcpaud_suspend_late() kept the DP audio domain whenever the linked DCP was on its wakeup path. The DCP's suspend also sets that path where it stops its firmware (the S2R stops, the T8132 external stop and power gate), so on those sleeps the domain stayed on with nothing using it. Have the DCP record whether its suspend left the coprocessor running (the default hold, a retained external DCP, a running T8132 DCP) and read that from the DP audio late suspend through dcp_sleep_keeps_firmware(). A DCP without a driver still counts as running, as before. The driver data is read under the DCP's device lock. The host test now builds dcp_sleep_keeps_firmware() too and checks the lock; its mutations cover holding for a stopped DCP, inverting the flag, dropping the unbound case and skipping the lock. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 16 ++++--- drivers/gpu/drm/apple/dcp-internal.h | 6 +++ drivers/gpu/drm/apple/dcp.c | 30 +++++++++++++ drivers/gpu/drm/apple/dcp.h | 1 + drivers/gpu/drm/apple/iomfb_m4.c | 17 ++++++++ drivers/gpu/drm/apple/iomfb_m4.h | 2 + tools/asahi/dcpaud-sleep-hold-tests.c | 51 ++++++++++++++++------ tools/asahi/dcpaud-sleep-hold-tests.py | 59 ++++++++++++++++++-------- tools/asahi/run-host-tests.py | 3 +- 9 files changed, 148 insertions(+), 37 deletions(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 4066f6e4781e32..1d6c5f73627d6b 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -2073,12 +2073,14 @@ static __maybe_unused int dcpaud_system_suspend(struct device *dev) /* * The DCP's firmware drives this block. A DCP that keeps its coprocessor - * running through a sleep keeps its own power domains for it (its suspend - * sets its wakeup path), and this block's domain must stay with them: - * cutting it at noirq under running DCP firmware resets the machine. A DCP - * device without a driver may still run firmware that a boot stage or an - * earlier bind left running, so its block is kept too. Every device's - * .suspend has run before this late phase, so the DCP's choice is known. + * running through a sleep keeps its own power domains for it, and this + * block's domain must stay with them: cutting it at noirq under running DCP + * firmware resets the machine. A DCP that stops its firmware for the sleep + * needs nothing held here, so the domain goes down as before. A DCP device + * without a driver may still run firmware that a boot stage or an earlier + * bind left running, so its block is kept too. Every device's .suspend has + * run before this late phase, so the DCP's choice is known + * (dcp_sleep_keeps_firmware()). */ static __maybe_unused int dcpaud_suspend_late(struct device *dev) { @@ -2094,7 +2096,7 @@ static __maybe_unused int dcpaud_suspend_late(struct device *dev) dcp_pdev = of_find_device_by_node(dcp_node); of_node_put(dcp_node); if (dcp_pdev) { - if (!device_is_bound(&dcp_pdev->dev) || device_wakeup_path(&dcp_pdev->dev)) + if (dcp_sleep_keeps_firmware(&dcp_pdev->dev)) device_set_wakeup_path(dev); put_device(&dcp_pdev->dev); } diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 515e6bf065f098..92bdd7f438441a 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -858,6 +858,12 @@ struct apple_dcp { struct delayed_work secure_poll_wq; /* Stopped and not restarted, which outlives a suspend that gets refused. */ bool s2r_fw_down; + /* + * Its last system suspend left the firmware running and its domains on + * (wakeup path), see dcp_sleep_keeps_firmware(). Cleared by the next + * suspend and resume. + */ + bool sleep_fw_runs; /* DCPEXT kept down through a dark wake, see dcp_s2r_dark_finish(). */ bool s2r_dark_held; struct notifier_block s2r_pm_nb; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index d1c2d02efdd4bb..b4ff87f88c24c3 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9740,10 +9740,36 @@ static void dcp_t8132_sleep_stopped(struct apple_dcp *dcp) WRITE_ONCE(dcp->t8132_release_late, false); } +/** + * dcp_sleep_keeps_firmware - whether a DCP's firmware runs through this sleep + * @dev: the DCP device + * + * For blocks the DCP's firmware drives (DP audio), from their late or noirq + * suspend, after every device's .suspend: true when the DCP's suspend left + * its coprocessor running with its domains on, or when no driver is bound + * (a boot stage or an earlier bind may have left the firmware running). + * False when the suspend stopped the firmware (S2R, the 27.x sleep, an M4 + * stop or power gate) or never ran it. + */ +bool dcp_sleep_keeps_firmware(struct device *dev) +{ + struct apple_dcp *dcp; + bool runs; + + device_lock(dev); + dcp = dev->driver ? dev_get_drvdata(dev) : NULL; + runs = !dev->driver || (dcp && dcp->sleep_fw_runs); + device_unlock(dev); + + return runs; +} +EXPORT_SYMBOL_GPL(dcp_sleep_keeps_firmware); + static int dcp_platform_suspend(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + dcp->sleep_fw_runs = false; /* Its power sequences may crash the DCP and blank the panel. */ if (dcp_takeover_was_aborted(dcp)) return -EBUSY; @@ -9799,6 +9825,7 @@ static int dcp_platform_suspend(struct device *dev) return ret; } dcp_t8132_sleep_stopped(dcp); + dcp->sleep_fw_runs = !iomfb_m4_sleep_stopped(dcp); device_set_wakeup_path(dev); return 0; } @@ -9854,6 +9881,7 @@ static int dcp_platform_suspend(struct device *dev) /* Pair with the H17P unpark; native26 has its own retained resume. */ if (dcp_is_external_h17p(dcp)) dcp_typec_route_park(dcp); + dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); if (dcp_is_ext26(dcp)) dev_dbg(dev, "native26 retained s2idle stop; firmware and supplier leases held\n"); @@ -9887,6 +9915,7 @@ static int dcp_platform_suspend(struct device *dev) * domains to stay on. We need this as we do not support full * shutdown properly yet. */ + dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); /* Last: the steps above still talk to the coprocessor. */ dcp_hold_for_sleep(dcp); @@ -9898,6 +9927,7 @@ static int dcp_platform_resume(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); + dcp->sleep_fw_runs = false; if (dcp_takeover_was_aborted(dcp)) return 0; diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f1d0f49026d601..41243ff65d8b0e 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -63,6 +63,7 @@ struct apple_encoder { #define to_apple_encoder(x) container_of(x, struct apple_encoder, base) void dcp_poweroff(struct platform_device *pdev); +bool dcp_sleep_keeps_firmware(struct device *dev); int dcp_typec_prepare_route(struct apple_dcp *dcp); void dcp_poweron(struct platform_device *pdev); void dcp_external_recover(struct platform_device *pdev); diff --git a/drivers/gpu/drm/apple/iomfb_m4.c b/drivers/gpu/drm/apple/iomfb_m4.c index 42caa27a508a06..a85010b15c719b 100644 --- a/drivers/gpu/drm/apple/iomfb_m4.c +++ b/drivers/gpu/drm/apple/iomfb_m4.c @@ -5836,6 +5836,23 @@ bool iomfb_m4_ext_stopped(struct apple_dcp *owner) return stopped; } +/* + * Its CPU is down for the sleep: an external DCP stopped for a deep sleep, or + * an internal one powered down with its domains (iomfb_m4_power_gate()). + */ +bool iomfb_m4_sleep_stopped(struct apple_dcp *owner) +{ + struct iomfb_m4 *dcp = owner->v26_6; + bool stopped; + + if (!dcp) + return false; + mutex_lock(&dcp->lock); + stopped = dcp->ext_stopped || dcp->gated; + mutex_unlock(&dcp->lock); + return stopped; +} + /* apple-drm, a consumer of this device, has blanked the panel before this. */ int iomfb_m4_suspend(struct apple_dcp *owner) { diff --git a/drivers/gpu/drm/apple/iomfb_m4.h b/drivers/gpu/drm/apple/iomfb_m4.h index 6e09d07e0c8994..cfd10118d0836b 100644 --- a/drivers/gpu/drm/apple/iomfb_m4.h +++ b/drivers/gpu/drm/apple/iomfb_m4.h @@ -81,6 +81,7 @@ void iomfb_m4_ext_relink_lost(struct apple_dcp *dcp); void iomfb_m4_ext_relink_wait(struct apple_dcp *dcp, unsigned long deadline); int iomfb_m4_ext_relink_end(struct apple_dcp *dcp); bool iomfb_m4_ext_stopped(struct apple_dcp *dcp); +bool iomfb_m4_sleep_stopped(struct apple_dcp *dcp); /* The caller has waited for the producer fence before publishing the DMA GEM. */ int iomfb_m4_present(struct apple_dcp *dcp, struct drm_framebuffer *fb, @@ -164,6 +165,7 @@ static inline void iomfb_m4_ext_relink_lost(struct apple_dcp *dcp) { } static inline void iomfb_m4_ext_relink_wait(struct apple_dcp *dcp, unsigned long deadline) { } static inline int iomfb_m4_ext_relink_end(struct apple_dcp *dcp) { return 0; } static inline bool iomfb_m4_ext_stopped(struct apple_dcp *dcp) { return false; } +static inline bool iomfb_m4_sleep_stopped(struct apple_dcp *dcp) { return false; } static inline int iomfb_m4_present(struct apple_dcp *dcp, struct drm_framebuffer *fb, dma_addr_t dva, size_t mapped) diff --git a/tools/asahi/dcpaud-sleep-hold-tests.c b/tools/asahi/dcpaud-sleep-hold-tests.c index 1c50ae05d68975..640472dce91d11 100644 --- a/tools/asahi/dcpaud-sleep-hold-tests.c +++ b/tools/asahi/dcpaud-sleep-hold-tests.c @@ -1,7 +1,8 @@ // SPDX-License-Identifier: GPL-2.0-only /* - * The actual dcp-dp-audio late sleep callback and dev_pm_ops against an OF - * graph and driver-core model that counts every node and device reference. + * The actual dcp-dp-audio late sleep callback and dev_pm_ops, and the DCP's + * dcp_sleep_keeps_firmware(), against an OF graph and driver-core model that + * counts every node and device reference and checks the device lock. */ #include #include @@ -12,6 +13,7 @@ /* The harness builds with -Wno-unused-function. */ #define __maybe_unused #define pm_sleep_ptr(fn) (fn) +#define EXPORT_SYMBOL_GPL(sym) /* ACTUAL_PM_MACROS */ @@ -20,10 +22,21 @@ struct device_node { bool available; }; +struct device_driver { + int unused; +}; + struct device { struct device_node *of_node; int refs; - bool bound, wakeup_path, set_wakeup_path; + const struct device_driver *driver; + void *drvdata; + bool locked, set_wakeup_path; +}; + +/* What the DCP's suspend left: see the sites setting it in dcp.c. */ +struct apple_dcp { + bool sleep_fw_runs; }; struct platform_device { @@ -52,6 +65,8 @@ struct dev_pm_ops { /* The model: the dpaudio node, its endpoint, the DCP node and device. */ static struct device_node audio_node, endpoint_node, dcp_node; static struct platform_device dcp_pdev; +static const struct device_driver dcp_driver; +static struct apple_dcp dcp_state; static struct device audio_dev = { .of_node = &audio_node }; static bool have_endpoint, have_remote, have_pdev; static int force_suspend_ret, force_suspend_calls, find_calls; @@ -112,16 +127,23 @@ static void put_device(struct device *dev) dev->refs--; } -static bool device_is_bound(struct device *dev) +/* The driver core's contract: driver and driver data are read under the lock. */ +static void device_lock(struct device *dev) { - assert(dev == &dcp_pdev.dev && dev->refs > 0); - return dev->bound; + assert(dev == &dcp_pdev.dev && dev->refs > 0 && !dev->locked); + dev->locked = true; } -static bool device_wakeup_path(struct device *dev) +static void device_unlock(struct device *dev) { - assert(dev == &dcp_pdev.dev && dev->refs > 0); - return dev->wakeup_path; + assert(dev == &dcp_pdev.dev && dev->locked); + dev->locked = false; +} + +static void *dev_get_drvdata(const struct device *dev) +{ + assert(dev == &dcp_pdev.dev && dev->locked && dev->driver); + return dev->drvdata; } static void device_set_wakeup_path(struct device *dev) @@ -168,6 +190,8 @@ static int dcpaud_resume(struct device *dev) return 4; } +/* ACTUAL_DCP_FUNCTION */ + /* ACTUAL_FUNCTION */ /* ACTUAL_PM_OPS */ @@ -184,8 +208,10 @@ int main(void) have_remote = bits & 2; dcp_node.available = bits & 4; have_pdev = bits & 8; - dcp_pdev.dev.bound = bits & 16; - dcp_pdev.dev.wakeup_path = bits & 32; + dcp_pdev.dev.driver = bits & 16 ? &dcp_driver : NULL; + dcp_pdev.dev.drvdata = bits & 16 ? &dcp_state : NULL; + dcp_state.sleep_fw_runs = bits & 32; + dcp_pdev.dev.locked = false; force_suspend_ret = bits & 64 ? -EBUSY : 0; endpoint_node.refs = dcp_node.refs = dcp_pdev.dev.refs = 0; audio_dev.set_wakeup_path = false; @@ -195,13 +221,14 @@ int main(void) ret = dcpaud_pm_ops.suspend_late(&audio_dev); expect = have_endpoint && have_remote && dcp_node.available && have_pdev && - (!dcp_pdev.dev.bound || dcp_pdev.dev.wakeup_path); + (!dcp_pdev.dev.driver || dcp_state.sleep_fw_runs); if (audio_dev.set_wakeup_path != expect) fprintf(stderr, "case %#x: wakeup path %d, expected %d\n", bits, audio_dev.set_wakeup_path, expect); assert(audio_dev.set_wakeup_path == expect); /* Every reference taken is dropped, whatever the topology. */ assert(!endpoint_node.refs && !dcp_node.refs && !dcp_pdev.dev.refs); + assert(!dcp_pdev.dev.locked); /* An unavailable or missing DCP node is never looked up. */ if (!(have_endpoint && have_remote && dcp_node.available)) assert(!find_calls); diff --git a/tools/asahi/dcpaud-sleep-hold-tests.py b/tools/asahi/dcpaud-sleep-hold-tests.py index 66a5475bf61177..142a69ccb941c3 100755 --- a/tools/asahi/dcpaud-sleep-hold-tests.py +++ b/tools/asahi/dcpaud-sleep-hold-tests.py @@ -5,12 +5,16 @@ genpd powers the dp-audio domain off at noirq unless the device is on the wakeup path, and cutting it under running DCP firmware resets the J473 on s2idle. dcpaud_suspend_late() puts dp-audio on the wakeup path when the DCP -linked by its OF graph exists and is unbound or on its own wakeup path. The +linked by its OF graph exists and is unbound or kept its firmware running +through the sleep (dcp_sleep_keeps_firmware()); a DCP that stopped its +firmware (S2R, the 27.x sleep, an M4 stop) leaves the domain to genpd. The fixture builds the real function and the real dcpaud_pm_ops (with the -kernel's PM_OPS macros) from drivers/gpu/drm/apple/audio.c against an OF -graph and driver-core model that counts every node and device reference. +kernel's PM_OPS macros) from drivers/gpu/drm/apple/audio.c, and the real +dcp_sleep_keeps_firmware() from dcp.c, against an OF graph and driver-core +model that counts every node and device reference and checks that the +DCP's driver data is read under its device lock. ---mutation names a change to the production function that the matrix must +--mutation names a change to a production function that the matrix must kill. --ref reads audio.c from an older revision: before the fix the late slot was pm_runtime_force_suspend, which never holds the domain, so the matrix fails (the old-code negative control). @@ -26,18 +30,26 @@ ROOT = Path(__file__).resolve().parents[2] AUDIO = "drivers/gpu/drm/apple/audio.c" +DCP = "drivers/gpu/drm/apple/dcp.c" PM = "include/linux/pm.h" +# (file, old, new): each must apply exactly once and the matrix must kill it. MUTATIONS = { - # Hold only for a DCP on its wakeup path; an unbound DCP loses the domain. - "bound-only": ("!device_is_bound(&dcp_pdev->dev) || device_wakeup_path(", - "device_wakeup_path("), + # Hold only for a bound DCP that kept its firmware; an unbound DCP loses the domain. + "bound-only": ("dcp", "runs = !dev->driver || (dcp && dcp->sleep_fw_runs);", + "runs = dcp && dcp->sleep_fw_runs;"), + # Hold for any bound DCP, also one that stopped its firmware for the sleep. + "stopped-holds": ("dcp", "(dcp && dcp->sleep_fw_runs)", "(dcp != NULL)"), + # Hold for a bound DCP that stopped its firmware, not for one that kept it. + "invert-runs": ("dcp", "(dcp && dcp->sleep_fw_runs)", "(dcp && !dcp->sleep_fw_runs)"), + # Read the driver data without the device lock. + "no-lock": ("dcp", "\tdevice_lock(dev);\n", ""), # Leak the DCP device reference from of_find_device_by_node(). - "leak-device": ("\t\tput_device(&dcp_pdev->dev);\n", ""), + "leak-device": ("audio", "\t\tput_device(&dcp_pdev->dev);\n", ""), # Leak the DCP node reference from of_graph_get_remote_port_parent(). - "leak-node": ("\tof_node_put(dcp_node);\n", ""), - # Hold for a bound DCP that is NOT on its wakeup path. - "invert-wakeup": ("|| device_wakeup_path(", "|| !device_wakeup_path("), + "leak-node": ("audio", "\tof_node_put(dcp_node);\n", ""), + # Back to the wakeup-path test that also held for a stopped DCP. + "ignore-dcp": ("audio", "if (dcp_sleep_keeps_firmware(&dcp_pdev->dev))", "if (true)"), } @@ -58,6 +70,13 @@ def function(text, name): return text[match.start():block(text, match.start())] +def dcp_function(text): + match = re.search(r"^bool dcp_sleep_keeps_firmware\(struct device \*dev\)\n\{", text, re.M) + if not match: + return None + return text[match.start():block(text, match.start())] + + def pm_ops(text): start = text.index("static const struct dev_pm_ops dcpaud_pm_ops = {") return text[start:block(text, start)] + ";\n" @@ -77,22 +96,28 @@ def main(): args = parser.parse_args() if args.ref: - audio = subprocess.check_output(["git", "show", f"{args.ref}:{AUDIO}"], - cwd=ROOT, text=True) + audio, dcp = (subprocess.check_output(["git", "show", f"{args.ref}:{path}"], + cwd=ROOT, text=True) for path in (AUDIO, DCP)) else: - audio = (ROOT / AUDIO).read_text() + audio, dcp = ((ROOT / path).read_text() for path in (AUDIO, DCP)) pm = (ROOT / PM).read_text() late = function(audio, "dcpaud_suspend_late") + keeps = dcp_function(dcp) if args.mutation: - old, new = MUTATIONS[args.mutation] - if not late or late.count(old) != 1: + where, old, new = MUTATIONS[args.mutation] + body = late if where == "audio" else keeps + if not body or body.count(old) != 1: raise RuntimeError(f"mutation {args.mutation} did not apply exactly once") - late = late.replace(old, new) + if where == "audio": + late = late.replace(old, new) + else: + keeps = keeps.replace(old, new) macros = "".join(macro(pm, name) for name in ("SYSTEM_SLEEP_PM_OPS", "LATE_SYSTEM_SLEEP_PM_OPS", "RUNTIME_PM_OPS")) code = (Path(__file__).with_suffix(".c").read_text() .replace("/* ACTUAL_PM_MACROS */", macros) + .replace("/* ACTUAL_DCP_FUNCTION */", keeps or "") .replace("/* ACTUAL_FUNCTION */", late or "") .replace("/* ACTUAL_PM_OPS */", pm_ops(audio))) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index c9e95d9d424517..c1017b5c1f84da 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -180,7 +180,8 @@ def mutations(flag, names, base, expect=KILL): # a7638d51880c, the parent of the fix, ran pm_runtime_force_suspend in the late # slot, so the dp-audio domain dropped under a running DCP. 'dcpaud-sleep-hold-tests.py': [(out(), PASS)] - + mutations('--mutation', ('bound-only', 'leak-device', 'leak-node', 'invert-wakeup'), out()) + + mutations('--mutation', ('bound-only', 'stopped-holds', 'invert-runs', 'no-lock', + 'leak-device', 'leak-node', 'ignore-dcp'), out()) + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], From 2bd81001a99c69b2546f518e01f62b7c2434bb06 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 19:13:09 +1100 Subject: [PATCH 0625/1514] perf: apple: test CPU PMU event mapping and counter allocation Signed-off-by: Ryan Murray --- drivers/perf/Kconfig | 12 + drivers/perf/apple_m1_cpu_pmu-test.c | 930 ++++++++++++++++++++++ drivers/perf/apple_m1_cpu_pmu.c | 4 + drivers/perf/apple_m1_cpu_pmu.kunitconfig | 8 + 4 files changed, 954 insertions(+) create mode 100644 drivers/perf/apple_m1_cpu_pmu-test.c create mode 100644 drivers/perf/apple_m1_cpu_pmu.kunitconfig diff --git a/drivers/perf/Kconfig b/drivers/perf/Kconfig index 245e7bb763b994..1263c9f5ac8dbb 100644 --- a/drivers/perf/Kconfig +++ b/drivers/perf/Kconfig @@ -264,6 +264,18 @@ config APPLE_M1_CPU_PMU Provides support for the non-architectural CPU PMUs present on the Apple M1 SoCs and derivatives. +config APPLE_M1_CPU_PMU_KUNIT_TEST + bool "KUnit tests for the Apple M1 CPU PMU driver" if !KUNIT_ALL_TESTS + depends on APPLE_M1_CPU_PMU && KUNIT=y + default KUNIT_ALL_TESTS + help + Build tests for the Apple CPU PMU driver's event logic: generic, + cache and raw event mapping per core type, counter allocation + under each event's counter affinity, the user/kernel/host/guest + filter bits, the PMUv3 event map used by KVM and the sysfs event + strings. No counter is programmed and no PMU is registered, so + the tests need no Apple hardware. + config ALIBABA_UNCORE_DRW_PMU tristate "Alibaba T-Head Yitian 710 DDR Sub-system Driveway PMU driver" depends on (ARM64 && ACPI) || COMPILE_TEST diff --git a/drivers/perf/apple_m1_cpu_pmu-test.c b/drivers/perf/apple_m1_cpu_pmu-test.c new file mode 100644 index 00000000000000..c7017ae5a79cdc --- /dev/null +++ b/drivers/perf/apple_m1_cpu_pmu-test.c @@ -0,0 +1,930 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * KUnit tests for the Apple M1 CPU PMU driver's event logic. + * + * Included at the end of apple_m1_cpu_pmu.c. The tests build an arm_pmu + * with each match-table init function and then only call the callbacks + * that never touch a register: map_event, set_event_filter, + * get_event_idx, clear_event_idx and map_pmuv3_event, plus the sysfs show + * helpers. Nothing is registered with perf and no Apple system register + * is accessed, so the tests run on any arm64 machine. + */ + +#include +#include + +/* A dynamic perf type: anything past the generic PERF_TYPE_* range. */ +#define M1PMU_TEST_PMU_TYPE (PERF_TYPE_MAX + 7) + +#define M1PMU_CACHE(type, op, result) \ + ((u64)PERF_COUNT_HW_CACHE_##type | \ + ((u64)PERF_COUNT_HW_CACHE_OP_##op << 8) | \ + ((u64)PERF_COUNT_HW_CACHE_RESULT_##result << 16)) + +static armpmu_init_fn m1pmu_test_init_fn(struct kunit *test, const char *compat) +{ + const struct of_device_id *id; + + for (id = m1_pmu_of_device_ids; id->compatible[0]; id++) + if (!strcmp(id->compatible, compat)) + return id->data; + + KUNIT_FAIL(test, "%s not in the match table", compat); + return NULL; +} + +static struct arm_pmu *m1pmu_test_pmu(struct kunit *test, const char *compat) +{ + struct arm_pmu *pmu; + armpmu_init_fn init; + + init = m1pmu_test_init_fn(test, compat); + KUNIT_ASSERT_NOT_NULL(test, init); + + pmu = kunit_kzalloc(test, sizeof(*pmu), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, pmu); + pmu->pmu.type = M1PMU_TEST_PMU_TYPE; + + KUNIT_ASSERT_EQ(test, init(pmu), 0); + return pmu; +} + +static struct pmu_hw_events *m1pmu_test_cpuc(struct kunit *test) +{ + struct pmu_hw_events *cpuc; + + cpuc = kunit_kzalloc(test, sizeof(*cpuc), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cpuc); + return cpuc; +} + +static struct perf_event *m1pmu_test_event(struct kunit *test, + struct arm_pmu *pmu, + u32 type, u64 config) +{ + struct perf_event *event; + + event = kunit_kzalloc(test, sizeof(*event), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, event); + event->pmu = &pmu->pmu; + event->attr.type = type; + event->attr.config = config; + event->attr.exclude_guest = 1; + event->hw.idx = -1; + return event; +} + +static int m1pmu_test_map(struct kunit *test, struct arm_pmu *pmu, + u32 type, u64 config) +{ + return pmu->map_event(m1pmu_test_event(test, pmu, type, config)); +} + +static int m1pmu_test_hw(struct kunit *test, struct arm_pmu *pmu, u64 config) +{ + return m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, config); +} + +static int m1pmu_test_cache(struct kunit *test, struct arm_pmu *pmu, + u64 config) +{ + return m1pmu_test_map(test, pmu, PERF_TYPE_HW_CACHE, config); +} + +/* + * The steps of the arm_pmu core's event init and add that reach the + * driver: map the event, apply the mode filter, then pick a counter. + * Returns the counter index or a negative errno. + */ +static int m1pmu_test_add(struct kunit *test, struct arm_pmu *pmu, + struct pmu_hw_events *cpuc, u32 type, u64 config, + struct perf_event **out) +{ + struct perf_event *event = m1pmu_test_event(test, pmu, type, config); + int mapping, ret; + + mapping = pmu->map_event(event); + if (mapping < 0) + return mapping; + + event->hw.config_base = 0; + ret = pmu->set_event_filter(&event->hw, &event->attr); + if (ret) + return ret; + event->hw.config_base |= mapping; + + ret = pmu->get_event_idx(cpuc, event); + if (ret >= 0) + event->hw.idx = ret; + if (out) + *out = event; + return ret; +} + +static int m1pmu_test_raw(struct kunit *test, struct arm_pmu *pmu, + struct pmu_hw_events *cpuc, u64 config) +{ + return m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, config, NULL); +} + +/* Match table: every compatible, its name, counters and callbacks. */ +struct m1pmu_test_variant { + const char *compat; + const char *name; + u64 cntr_mask; + int (*map_event)(struct perf_event *event); + int (*get_event_idx)(struct pmu_hw_events *cpuc, + struct perf_event *event); + int (*map_pmuv3_event)(unsigned int eventsel); + void (*enable)(struct perf_event *event); + const struct attribute_group *events; + const struct attribute_group *formats; + u32 evt_flag; +}; + +static const struct m1pmu_test_variant m1pmu_test_variants[] = { + { "apple,icestorm-pmu", "apple_icestorm_pmu", GENMASK(9, 0), + m1_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_47BIT }, + { "apple,firestorm-pmu", "apple_firestorm_pmu", GENMASK(9, 0), + m1_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_47BIT }, + { "apple,avalanche-pmu", "apple_avalanche_pmu", GENMASK(9, 0), + m2_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,blizzard-pmu", "apple_blizzard_pmu", GENMASK(9, 0), + m2_pmu_map_event, m1_pmu_get_event_idx, m1_pmu_map_pmuv3_event, + m1_pmu_enable_event, &m1_pmu_events_attr_group, + &m1_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t8140-pmu", "apple_t8140_pmu", GENMASK(7, 0), + m4_pmu_map_event, m4_pmu_get_event_idx, m4_pmu_map_pmuv3_event, + m4_pmu_enable_event, &m4_pmu_events_attr_group, + &m4_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t6040-pmu", "apple_t6040_pmu", GENMASK(7, 0), + m4_pmu_map_event, m4_pmu_get_event_idx, m4_pmu_map_pmuv3_event, + m4_pmu_enable_event, &m4_pmu_events_attr_group, + &m4_pmu_format_attr_group, ARMPMU_EVT_63BIT }, + { "apple,t6050-pmu", "apple_t6050_pmu", GENMASK(9, 0), + t6050_pmu_map_event, t6050_pmu_get_event_idx, + t6050_pmu_map_pmuv3_event, m4_pmu_enable_event, + &t6050_pmu_events_attr_group, &m4_pmu_format_attr_group, + ARMPMU_EVT_63BIT }, + { "apple,t8142-pmu", "apple_t8142_pmu", GENMASK(9, 0), + t6050_pmu_map_event, t6050_pmu_get_event_idx, + t6050_pmu_map_pmuv3_event, m4_pmu_enable_event, + &t6050_pmu_events_attr_group, &m4_pmu_format_attr_group, + ARMPMU_EVT_63BIT }, +}; + +static void m1pmu_test_variant_desc(const struct m1pmu_test_variant *v, + char *desc) +{ + strscpy(desc, v->compat, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(m1pmu_test_variant, m1pmu_test_variants, + m1pmu_test_variant_desc); + +static void m1pmu_test_match_table_complete(struct kunit *test) +{ + const struct of_device_id *id; + size_t n = 0, i; + + for (id = m1_pmu_of_device_ids; id->compatible[0]; id++) { + bool found = false; + + KUNIT_EXPECT_NOT_NULL(test, id->data); + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) + found |= !strcmp(id->compatible, + m1pmu_test_variants[i].compat); + KUNIT_EXPECT_TRUE_MSG(test, found, "%s has no test variant", + id->compatible); + n++; + } + KUNIT_EXPECT_EQ(test, n, ARRAY_SIZE(m1pmu_test_variants)); +} + +/* Each init function wires its own callbacks, counters and sysfs groups. */ +static void m1pmu_test_variant_init(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + DECLARE_BITMAP(want, ARMPMU_MAX_HWEVENTS); + struct perf_event *event; + + KUNIT_EXPECT_STREQ(test, pmu->name, v->name); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->map_event, (void *)v->map_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->get_event_idx, + (void *)v->get_event_idx); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->map_pmuv3_event, + (void *)v->map_pmuv3_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->enable, (void *)v->enable); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->clear_event_idx, + (void *)m1_pmu_clear_event_idx); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->set_event_filter, + (void *)m1_pmu_set_event_filter); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->disable, + (void *)m1_pmu_disable_event); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->reset, (void *)m1_pmu_reset); + KUNIT_EXPECT_PTR_EQ(test, (void *)pmu->handle_irq, + (void *)m1_pmu_handle_irq); + KUNIT_EXPECT_PTR_EQ(test, pmu->attr_groups[ARMPMU_ATTR_GROUP_EVENTS], + v->events); + KUNIT_EXPECT_PTR_EQ(test, pmu->attr_groups[ARMPMU_ATTR_GROUP_FORMATS], + v->formats); + + bitmap_zero(want, ARMPMU_MAX_HWEVENTS); + bitmap_from_u64(want, v->cntr_mask); + KUNIT_EXPECT_TRUE(test, bitmap_equal(pmu->cntr_mask, want, + ARMPMU_MAX_HWEVENTS)); + KUNIT_EXPECT_EQ(test, bitmap_weight(pmu->cntr_mask, + ARMPMU_MAX_HWEVENTS), + hweight64(v->cntr_mask)); + + /* map_event advertises the overflow bit width. */ + event = m1pmu_test_event(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES); + KUNIT_EXPECT_GE(test, pmu->map_event(event), 0); + KUNIT_EXPECT_EQ(test, event->hw.flags & (ARMPMU_EVT_47BIT | + ARMPMU_EVT_63BIT | + ARMPMU_EVT_64BIT), + v->evt_flag); +} + +/* Cycles and instructions always land on fixed counters 0 and 1. */ +static void m1pmu_test_variant_fixed_counters(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + KUNIT_EXPECT_EQ(test, m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES, NULL), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS, NULL), + 1); +} + +/* Filling the PMU with events of the default affinity uses each counter once. */ +static void m1pmu_test_variant_fill(struct kunit *test) +{ + const struct m1pmu_test_variant *v = test->param_value; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + DECLARE_BITMAP(used, ARMPMU_MAX_HWEVENTS); + unsigned int i, n; + int idx; + + /* Event 0xf0 has no special affinity on any variant. */ + bitmap_zero(used, ARMPMU_MAX_HWEVENTS); + for (n = 0; n < ARMPMU_MAX_HWEVENTS; n++) { + idx = m1pmu_test_raw(test, pmu, cpuc, 0xf0); + if (idx < 0) + break; + KUNIT_EXPECT_GE(test, idx, 2); + KUNIT_EXPECT_TRUE(test, test_bit(idx, pmu->cntr_mask)); + KUNIT_EXPECT_FALSE(test, test_bit(idx, used)); + __set_bit(idx, used); + } + KUNIT_EXPECT_EQ(test, idx, -EAGAIN); + + /* Every counter the PMU exposes, minus the two fixed ones. */ + KUNIT_EXPECT_EQ(test, n, hweight64(v->cntr_mask & ~GENMASK_ULL(1, 0))); + for (i = 0; i < n; i++) + KUNIT_EXPECT_TRUE(test, test_bit(i + 2, used)); +} + +/* Generic hardware events, per variant event numbering. */ +static void m1pmu_test_hw_map_m1(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct arm_pmu *m2 = m1pmu_test_pmu(test, "apple,blizzard-pmu"); + struct arm_pmu *p[] = { pmu, m2 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(p); i++) { + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_INSTRUCTIONS), + 0x8c); + KUNIT_EXPECT_EQ(test, + m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x8d); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, p[i], + PERF_COUNT_HW_BRANCH_MISSES), + 0xcb); + } +} + +static void m1pmu_test_hw_map_m4(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6040-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES), 0x02); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS), 0x08); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x21); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_MISSES), 0x22); +} + +static void m1pmu_test_hw_map_t6050(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_CPU_CYCLES), 0x011); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_INSTRUCTIONS), 0x008); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS), + 0x021); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + PERF_COUNT_HW_BRANCH_MISSES), 0x022); +} + +/* Generic events with no mapping, and out-of-range configs. */ +static void m1pmu_test_hw_map_unsupported(struct kunit *test) +{ + static const u64 unmapped[] = { + PERF_COUNT_HW_CACHE_REFERENCES, + PERF_COUNT_HW_CACHE_MISSES, + PERF_COUNT_HW_BUS_CYCLES, + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND, + PERF_COUNT_HW_STALLED_CYCLES_BACKEND, + PERF_COUNT_HW_REF_CPU_CYCLES, + }; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (j = 0; j < ARRAY_SIZE(unmapped); j++) + KUNIT_EXPECT_EQ(test, + m1pmu_test_hw(test, pmu, unmapped[j]), + -ENOENT); + KUNIT_EXPECT_EQ(test, m1pmu_test_hw(test, pmu, PERF_COUNT_HW_MAX), + -EINVAL); + /* A type that is neither generic nor this PMU's. */ + KUNIT_EXPECT_EQ(test, + m1pmu_test_map(test, pmu, PERF_TYPE_TRACEPOINT, 0), + -ENOENT); + } +} + +/* + * Generic cache events. Only the L1D read miss may ever be mapped (it is + * the one event with a known counter on every core), so leave it out. + */ +static void m1pmu_test_cache_map(struct kunit *test) +{ + static const u64 unmapped[] = { + M1PMU_CACHE(L1D, READ, ACCESS), + M1PMU_CACHE(L1D, WRITE, MISS), + M1PMU_CACHE(L1I, READ, MISS), + M1PMU_CACHE(LL, READ, MISS), + M1PMU_CACHE(DTLB, READ, MISS), + M1PMU_CACHE(ITLB, READ, MISS), + M1PMU_CACHE(BPU, READ, ACCESS), + M1PMU_CACHE(NODE, PREFETCH, MISS), + }; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (j = 0; j < ARRAY_SIZE(unmapped); j++) + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, unmapped[j]), + -ENOENT); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + PERF_COUNT_HW_CACHE_MAX), + -EINVAL); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + (u64)PERF_COUNT_HW_CACHE_OP_MAX << 8), + -EINVAL); + KUNIT_EXPECT_EQ(test, + m1pmu_test_cache(test, pmu, + (u64)PERF_COUNT_HW_CACHE_RESULT_MAX << 16), + -EINVAL); + } +} + +/* Raw events: 8-bit selectors on M1/M2, 16-bit from M4 on. */ +static void m1pmu_test_raw_mask(struct kunit *test) +{ + struct arm_pmu *m1 = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct arm_pmu *m2 = m1pmu_test_pmu(test, "apple,avalanche-pmu"); + struct arm_pmu *m4 = m1pmu_test_pmu(test, "apple,t8140-pmu"); + struct arm_pmu *m5 = m1pmu_test_pmu(test, "apple,t8142-pmu"); + + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m1, PERF_TYPE_RAW, 0x1a3), + 0xa3); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m2, PERF_TYPE_RAW, + 0xffff00cb), 0xcb); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m1, M1PMU_TEST_PMU_TYPE, + 0x38c), 0x8c); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m4, PERF_TYPE_RAW, + 0x30008), 0x0008); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m4, M1PMU_TEST_PMU_TYPE, + 0xabcd), 0xabcd); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m5, PERF_TYPE_RAW, + 0x105a3), 0x5a3); + KUNIT_EXPECT_EQ(test, m1pmu_test_map(test, m5, M1PMU_TEST_PMU_TYPE, + 0x895), 0x895); +} + +/* exclude_* bits become the count-user/kernel/host/guest config bits. */ +static void m1pmu_test_event_filter(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct perf_event_attr attr = { }; + struct hw_perf_event hw = { }; + + attr.exclude_guest = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_kernel = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_kernel = 0; + attr.exclude_user = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_HOST)); + + attr.exclude_host = 1; + attr.exclude_kernel = 1; + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, 0UL); + + /* Counting the guest needs VHE; without it, refuse. */ + memset(&attr, 0, sizeof(attr)); + hw.config_base = 0x5a; + if (is_kernel_in_hyp_mode()) { + KUNIT_ASSERT_EQ(test, pmu->set_event_filter(&hw, &attr), 0); + KUNIT_EXPECT_EQ(test, hw.config_base, + (unsigned long)(M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST | + M1_PMU_CFG_COUNT_GUEST)); + } else { + KUNIT_EXPECT_EQ(test, pmu->set_event_filter(&hw, &attr), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, hw.config_base, 0x5aUL); + } +} + +/* The filter bits must not change which counter an event gets. */ +static void m1pmu_test_idx_ignores_filter_bits(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + struct perf_event *event; + + event = m1pmu_test_event(test, pmu, PERF_TYPE_RAW, 0); + event->hw.config_base = M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_KERNEL | + M1_PMU_CFG_COUNT_HOST | + M1_PMU_CFG_COUNT_GUEST | + M1_PMU_PERFCTR_RETIRE_UOP; + KUNIT_EXPECT_EQ(test, pmu->get_event_idx(cpuc, event), 7); + + pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + cpuc = m1pmu_test_cpuc(test); + event->pmu = &pmu->pmu; + event->hw.config_base = M1_PMU_CFG_COUNT_USER | + M1_PMU_CFG_COUNT_HOST | 0x897; + KUNIT_EXPECT_EQ(test, pmu->get_event_idx(cpuc, event), 7); +} + +/* M1/M2 per-event affinities from m1_pmu_event_affinity. */ +static void m1pmu_test_m1_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + /* RETIRE_UOP only counts on counter 7. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 7); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), -EAGAIN); + + /* INST_ALL: counter 1, then 7, which is now taken. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8c), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8c), -EAGAIN); + + /* Branch events are confined to 5-7; only 5 and 6 are left. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8d), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xcb), 6); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xc5), -EAGAIN); + + /* 0xf5-0xf7 and 0xfd count on 2, 4, 6. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf5), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xfd), 4); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf6), -EAGAIN); + + /* 0xf8 counts on 2-7: only 3 is free there. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf8), 3); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf8), -EAGAIN); + + /* Anything else goes on 8 and 9, never on 0. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), 8); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x00), 9); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), -EAGAIN); + + /* Cycles still has its fixed counter, then nowhere to go. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), -EAGAIN); + KUNIT_EXPECT_EQ(test, bitmap_weight(cpuc->used_mask, + ARMPMU_MAX_HWEVENTS), 10); +} + +/* Only cycles and instructions may use counters 0 and 1 on M1. */ +static void m1pmu_test_m1_fixed_reserved(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,blizzard-pmu"); + unsigned int evt; + + for (evt = 0; evt <= M1_PMU_PERFCTR_LAST; evt++) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int first = m1pmu_test_raw(test, pmu, cpuc, evt); + + KUNIT_EXPECT_GE(test, first, 0); + if (evt == M1_PMU_PERFCTR_CORE_ACTIVE_CYCLE) + KUNIT_EXPECT_EQ(test, first, 0); + else if (evt == M1_PMU_PERFCTR_INST_ALL) + KUNIT_EXPECT_EQ(test, first, 1); + else + KUNIT_EXPECT_GE_MSG(test, first, 2, "event 0x%x", evt); + kunit_kfree(test, cpuc); + } +} + +/* A freed counter is handed out again; others stay taken. */ +static void m1pmu_test_clear_idx(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,icestorm-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + struct perf_event *a, *b, *c; + + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0xa3, &a), 2); + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0xa3, &b), 3); + KUNIT_ASSERT_EQ(test, m1pmu_test_add(test, pmu, cpuc, PERF_TYPE_RAW, + 0x01, &c), 7); + + pmu->clear_event_idx(cpuc, a); + KUNIT_EXPECT_FALSE(test, test_bit(2, cpuc->used_mask)); + KUNIT_EXPECT_TRUE(test, test_bit(3, cpuc->used_mask)); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xa3), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), -EAGAIN); + + pmu->clear_event_idx(cpuc, c); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 7); + + pmu->clear_event_idx(cpuc, b); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8d), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0xf0), 3); +} + +/* M4: cycles only on 0, instructions on 1 or 2-7, the rest on 2-7. */ +static void m1pmu_test_m4_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t8140-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + unsigned int i; + + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x02), -EAGAIN); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), 2); + + /* 16-bit selectors: 0x1008 is not INST_ALL. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x1008), 3); + /* The M1 RETIRE_UOP pin to counter 7 does not apply here. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x01), 4); + + for (i = 5; i <= 7; i++) + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x03), i); + /* Counters 8 and 9 are never handed out. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x03), -EAGAIN); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x08), -EAGAIN); + KUNIT_EXPECT_FALSE(test, test_bit(8, cpuc->used_mask)); + KUNIT_EXPECT_FALSE(test, test_bit(9, cpuc->used_mask)); +} + +/* T6050: cycles on 0 or 2-9, the instruction classes on 2-7 or only 7. */ +static void m1pmu_test_t6050_affinity(struct kunit *test) +{ + struct arm_pmu *pmu = m1pmu_test_pmu(test, "apple,t6050-pmu"); + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + unsigned int i, ev; + + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 0); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 2); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x008), 1); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x008), 3); + + /* The counter-7-only list. */ + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc7_events); i++) { + ev = t6050_pmu_pmc7_events[i]; + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(ev), BIT(7)); + } + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8a4), 7); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x897), -EAGAIN); + + /* The 2-7 list: 4, 5, 6 left, then full even with 8 and 9 free. */ + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc2_7_events); i++) { + ev = t6050_pmu_pmc2_7_events[i]; + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(ev), + GENMASK(7, 2) | + (ev == T6050_PMU_PERFCTR_INST_ALL ? BIT(1) : 0)); + } + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x895), 4); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x022), 5); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x8ca), 6); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x88e), -EAGAIN); + + /* Unlisted events, such as the L1D load miss, may use 8 and 9. */ + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x5a3), 8); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x011), 9); + KUNIT_EXPECT_EQ(test, m1pmu_test_raw(test, pmu, cpuc, 0x5a3), -EAGAIN); + KUNIT_EXPECT_EQ(test, bitmap_weight(cpuc->used_mask, + ARMPMU_MAX_HWEVENTS), 10); +} + +/* The 2-7 and 7-only lists must not overlap, or the order would matter. */ +static bool m1pmu_test_in_pmc2_7(unsigned int event) +{ + return t6050_pmu_event_in(t6050_pmu_pmc2_7_events, + ARRAY_SIZE(t6050_pmu_pmc2_7_events), event); +} + +static void m1pmu_test_t6050_lists_disjoint(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(t6050_pmu_pmc7_events); i++) + KUNIT_EXPECT_FALSE(test, + m1pmu_test_in_pmc2_7(t6050_pmu_pmc7_events[i])); + KUNIT_EXPECT_FALSE(test, m1pmu_test_in_pmc2_7(0x011)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x5a3), GENMASK(9, 2)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x8c8), GENMASK(7, 2)); + KUNIT_EXPECT_EQ(test, t6050_pmu_event_affinity(0x8c9), GENMASK(9, 2)); +} + +/* Every hardware event a variant maps can be placed on an empty PMU. */ +static void m1pmu_test_hw_events_placeable(struct kunit *test) +{ + unsigned int i, cfg; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for (cfg = 0; cfg < PERF_COUNT_HW_MAX; cfg++) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int idx; + + if (m1pmu_test_map(test, pmu, PERF_TYPE_HARDWARE, + cfg) < 0) + continue; + idx = m1pmu_test_add(test, pmu, cpuc, + PERF_TYPE_HARDWARE, cfg, NULL); + KUNIT_EXPECT_GE_MSG(test, idx, 0, "%s hw %u", + m1pmu_test_variants[i].compat, cfg); + if (idx >= 0) + KUNIT_EXPECT_TRUE(test, + test_bit(idx, pmu->cntr_mask)); + kunit_kfree(test, cpuc); + } + } +} + +/* PMUv3 events KVM exposes to guests, and the PMCEID bitmap built from them. */ +static void m1pmu_test_pmuv3_map(struct kunit *test) +{ + struct arm_pmu *m1 = m1pmu_test_pmu(test, "apple,firestorm-pmu"); + struct arm_pmu *m4 = m1pmu_test_pmu(test, "apple,t6040-pmu"); + struct arm_pmu *m5 = m1pmu_test_pmu(test, "apple,t6050-pmu"); + + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x8c); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_RETIRED), + 0x8d); + KUNIT_EXPECT_EQ(test, + m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED), + 0xcb); + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_L1D_CACHE), + -EOPNOTSUPP); + + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x02); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x08); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_RETIRED), + 0x21); + + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_CPU_CYCLES), + 0x011); + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_INST_RETIRED), + 0x008); + KUNIT_EXPECT_EQ(test, + m5->map_pmuv3_event(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED), + 0x022); + + /* Past the common event space. */ + KUNIT_EXPECT_EQ(test, m1->map_pmuv3_event(ARMV8_PMUV3_MAX_COMMON_EVENTS), + -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, m5->map_pmuv3_event(0xffff), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, m4->map_pmuv3_event(UINT_MAX), -EOPNOTSUPP); + + /* PMCEID advertises exactly the mapped events. */ + KUNIT_EXPECT_EQ(test, bitmap_weight(m1->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 4); + KUNIT_EXPECT_TRUE(test, test_bit(ARMV8_PMUV3_PERFCTR_CPU_CYCLES, + m1->pmceid_bitmap)); + KUNIT_EXPECT_TRUE(test, test_bit(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED, + m1->pmceid_bitmap)); + KUNIT_EXPECT_EQ(test, bitmap_weight(m4->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 3); + KUNIT_EXPECT_FALSE(test, test_bit(ARMV8_PMUV3_PERFCTR_BR_MIS_PRED_RETIRED, + m4->pmceid_bitmap)); + KUNIT_EXPECT_EQ(test, bitmap_weight(m5->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS), 4); + KUNIT_EXPECT_TRUE(test, bitmap_empty(m1->pmceid_ext_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS)); +} + +/* Each PMUv3 event KVM maps can be placed on the PMU that maps it. */ +static void m1pmu_test_pmuv3_placeable(struct kunit *test) +{ + unsigned int i, ev; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + struct arm_pmu *pmu = + m1pmu_test_pmu(test, m1pmu_test_variants[i].compat); + + for_each_set_bit(ev, pmu->pmceid_bitmap, + ARMV8_PMUV3_MAX_COMMON_EVENTS) { + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + int raw = pmu->map_pmuv3_event(ev); + + KUNIT_ASSERT_GE(test, raw, 0); + KUNIT_EXPECT_GE_MSG(test, + m1pmu_test_raw(test, pmu, cpuc, raw), + 0, "%s pmuv3 0x%x", + m1pmu_test_variants[i].compat, ev); + kunit_kfree(test, cpuc); + } + } +} + +static const char *m1pmu_test_show(struct kunit *test, + const struct attribute_group *grp, + const char *name) +{ + struct attribute **a; + char *page; + + page = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + if (!page) + return ""; + + for (a = grp->attrs; *a; a++) { + struct device_attribute *da; + + if (strcmp((*a)->name, name)) + continue; + da = container_of(*a, struct device_attribute, attr); + if (da->show(NULL, da, page) <= 0) + return ""; + return page; + } + return ""; +} + +static void m1pmu_test_expect_show(struct kunit *test, + const struct attribute_group *grp, + const char *name, const char *want) +{ + KUNIT_EXPECT_STREQ_MSG(test, m1pmu_test_show(test, grp, name), want, + "%s/%s", grp->name, name); +} + +/* sysfs events and format strings that perf tools parse. */ +static void m1pmu_test_sysfs(struct kunit *test) +{ + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, "cycles", + "event=0x0002\n"); + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, + "instructions", "event=0x008c\n"); + m1pmu_test_expect_show(test, &m1_pmu_events_attr_group, "branches", + ""); + m1pmu_test_expect_show(test, &m4_pmu_events_attr_group, + "l1d-load-misses", "event=0x0003\n"); + m1pmu_test_expect_show(test, &m4_pmu_events_attr_group, + "branch-misses", "event=0x0022\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, + "l1d-load-misses", "event=0x05a3\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, "loads", + "event=0x0895\n"); + m1pmu_test_expect_show(test, &t6050_pmu_events_attr_group, "cycles", + "event=0x0011\n"); + + m1pmu_test_expect_show(test, &m1_pmu_format_attr_group, "event", + "config:0-7\n"); + m1pmu_test_expect_show(test, &m4_pmu_format_attr_group, "event", + "config:0-15\n"); +} + +/* Every named sysfs event maps back to itself as a raw event. */ +static void m1pmu_test_sysfs_events_round_trip(struct kunit *test) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(m1pmu_test_variants); i++) { + const struct m1pmu_test_variant *v = &m1pmu_test_variants[i]; + struct arm_pmu *pmu = m1pmu_test_pmu(test, v->compat); + struct attribute **a; + + for (a = v->events->attrs; *a; a++) { + struct perf_pmu_events_attr *pa; + struct pmu_hw_events *cpuc = m1pmu_test_cpuc(test); + + pa = container_of(*a, struct perf_pmu_events_attr, + attr.attr); + KUNIT_EXPECT_EQ(test, + m1pmu_test_map(test, pmu, + M1PMU_TEST_PMU_TYPE, + pa->id), + (int)pa->id); + KUNIT_EXPECT_GE_MSG(test, + m1pmu_test_raw(test, pmu, cpuc, pa->id), + 0, "%s %s", v->compat, (*a)->name); + kunit_kfree(test, cpuc); + } + } +} + +static struct kunit_case m1pmu_test_cases[] = { + KUNIT_CASE(m1pmu_test_match_table_complete), + KUNIT_CASE_PARAM(m1pmu_test_variant_init, + m1pmu_test_variant_gen_params), + KUNIT_CASE_PARAM(m1pmu_test_variant_fixed_counters, + m1pmu_test_variant_gen_params), + KUNIT_CASE_PARAM(m1pmu_test_variant_fill, + m1pmu_test_variant_gen_params), + KUNIT_CASE(m1pmu_test_hw_map_m1), + KUNIT_CASE(m1pmu_test_hw_map_m4), + KUNIT_CASE(m1pmu_test_hw_map_t6050), + KUNIT_CASE(m1pmu_test_hw_map_unsupported), + KUNIT_CASE(m1pmu_test_cache_map), + KUNIT_CASE(m1pmu_test_raw_mask), + KUNIT_CASE(m1pmu_test_event_filter), + KUNIT_CASE(m1pmu_test_idx_ignores_filter_bits), + KUNIT_CASE(m1pmu_test_m1_affinity), + KUNIT_CASE(m1pmu_test_m1_fixed_reserved), + KUNIT_CASE(m1pmu_test_clear_idx), + KUNIT_CASE(m1pmu_test_m4_affinity), + KUNIT_CASE(m1pmu_test_t6050_affinity), + KUNIT_CASE(m1pmu_test_t6050_lists_disjoint), + KUNIT_CASE(m1pmu_test_hw_events_placeable), + KUNIT_CASE(m1pmu_test_pmuv3_map), + KUNIT_CASE(m1pmu_test_pmuv3_placeable), + KUNIT_CASE(m1pmu_test_sysfs), + KUNIT_CASE(m1pmu_test_sysfs_events_round_trip), + {} +}; + +static struct kunit_suite m1pmu_test_suite = { + .name = "apple-m1-cpu-pmu", + .test_cases = m1pmu_test_cases, +}; + +kunit_test_suite(m1pmu_test_suite); diff --git a/drivers/perf/apple_m1_cpu_pmu.c b/drivers/perf/apple_m1_cpu_pmu.c index d1aadc27164fb9..9bc510e5426863 100644 --- a/drivers/perf/apple_m1_cpu_pmu.c +++ b/drivers/perf/apple_m1_cpu_pmu.c @@ -1040,3 +1040,7 @@ static struct platform_driver m1_pmu_driver = { }; module_platform_driver(m1_pmu_driver); + +#if IS_ENABLED(CONFIG_APPLE_M1_CPU_PMU_KUNIT_TEST) +#include "apple_m1_cpu_pmu-test.c" +#endif diff --git a/drivers/perf/apple_m1_cpu_pmu.kunitconfig b/drivers/perf/apple_m1_cpu_pmu.kunitconfig new file mode 100644 index 00000000000000..efa2818f6209b9 --- /dev/null +++ b/drivers/perf/apple_m1_cpu_pmu.kunitconfig @@ -0,0 +1,8 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/perf/apple_m1_cpu_pmu.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PERF_EVENTS=y +CONFIG_ARM_PMU=y +CONFIG_APPLE_M1_CPU_PMU=y +CONFIG_APPLE_M1_CPU_PMU_KUNIT_TEST=y From 2764b928687a3b16d163c14c54e54d918a580241 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 19:13:10 +1100 Subject: [PATCH 0626/1514] soc: apple: add KUnit tests for regview Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 13 + drivers/soc/apple/regview-test.c | 608 ++++++++++++++++++++++++++ drivers/soc/apple/regview.c | 4 + drivers/soc/apple/regview.kunitconfig | 7 + 4 files changed, 632 insertions(+) create mode 100644 drivers/soc/apple/regview-test.c create mode 100644 drivers/soc/apple/regview.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 8dc9384bdc5d11..4be538da8ed19f 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -342,6 +342,19 @@ config APPLE_REGVIEW This is a development aid. If unsure, say 'n'. +config APPLE_REGVIEW_KUNIT_TEST + bool "KUnit tests for the Apple SoC read-only register views" if !KUNIT_ALL_TESTS + depends on APPLE_REGVIEW=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Check every built-in register list against the apertures it + needs, the bounds check for short, misnumbered, empty and + wrapping ranges, and the exact text of the views, on register + windows that the test backs with kernel memory. The tests touch + no hardware. + + If unsure, say N. + config APPLE_CLPC tristate "Apple host performance controller floors" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/soc/apple/regview-test.c b/drivers/soc/apple/regview-test.c new file mode 100644 index 00000000000000..83c2ed9adb830a --- /dev/null +++ b/drivers/soc/apple/regview-test.c @@ -0,0 +1,608 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SoC read-only register views. Included by + * regview.c. + * + * The register windows under test are zeroed buffers of kernel memory that + * stand in for the mapped DT reg entries of a struct apple_regview. The tests + * call the driver's own bounds check and seq_file show routine on the + * driver's own register lists. No device is probed and no MMIO is touched. + */ +#include +#include +#include + +#define REGVIEW_TEST_MAX_REGS 4 +#define REGVIEW_TEST_SEQ_SIZE (16 * 1024) + +struct regview_test_ctx { + struct apple_regview rv; + struct apple_regview_map maps[REGVIEW_TEST_MAX_REGS]; + void *buf[REGVIEW_TEST_MAX_REGS]; + char *seq_buf; + size_t seq_len; +}; + +KUNIT_DEFINE_ACTION_WRAPPER(regview_test_vfree, vfree, const void *); + +static const struct apple_regview_hw *regview_test_hw(const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) + return id->data; + return NULL; +} + +/* Bytes of reg entry @reg that the list of @hw reaches. */ +static u64 regview_test_extent(const struct apple_regview_hw *hw, + unsigned int reg) +{ + u64 end = 0; + unsigned int i; + + for (i = 0; i < hw->nr_ranges; i++) { + const struct apple_regview_range *r = &hw->ranges[i]; + u32 stride = r->stride ? r->stride : 4; + u64 last; + + if (r->reg != reg) + continue; + last = r->offset + (u64)(r->count - 1) * stride + 4; + end = max(end, last); + } + + return end; +} + +/* Back every reg entry of @hw with a buffer of the size it needs plus @extra. */ +static struct regview_test_ctx *regview_test_setup(struct kunit *test, + const struct apple_regview_hw *hw, + s64 extra) +{ + struct regview_test_ctx *ctx; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_ASSERT_LE(test, hw->nr_regs, REGVIEW_TEST_MAX_REGS); + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + for (i = 0; i < hw->nr_regs; i++) { + u64 size = regview_test_extent(hw, i); + + /* An entry no range uses still gets a word of its own. */ + size = max_t(u64, size, 4); + ctx->buf[i] = vzalloc(size + max_t(s64, extra, 0) + 4); + KUNIT_ASSERT_NOT_NULL(test, ctx->buf[i]); + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, regview_test_vfree, + ctx->buf[i])); + ctx->maps[i].base = (void __iomem *)ctx->buf[i]; + ctx->maps[i].size = size + extra; + } + + ctx->rv.hw = hw; + ctx->rv.maps = ctx->maps; + + return ctx; +} + +/* A value that names the reg entry and offset it was read from. */ +static u32 regview_test_tag(unsigned int reg, u32 off) +{ + return 0xa0000000 | (reg << 24) | off; +} + +static void regview_test_fill(struct regview_test_ctx *ctx) +{ + const struct apple_regview_hw *hw = ctx->rv.hw; + unsigned int i; + + for (i = 0; i < hw->nr_regs; i++) { + u32 *w = ctx->buf[i]; + u64 off; + + for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) + w[off / 4] = regview_test_tag(i, off); + } +} + +static void regview_test_show(struct kunit *test, struct regview_test_ctx *ctx) +{ + struct seq_file s = { }; + + ctx->seq_buf = kunit_kzalloc(test, REGVIEW_TEST_SEQ_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->seq_buf); + + s.buf = ctx->seq_buf; + s.size = REGVIEW_TEST_SEQ_SIZE - 1; + s.private = &ctx->rv; + + KUNIT_ASSERT_EQ(test, apple_regview_show(&s, NULL), 0); + KUNIT_ASSERT_FALSE(test, seq_has_overflowed(&s)); + ctx->seq_len = s.count; + ctx->seq_buf[s.count] = '\0'; +} + +static bool regview_test_has(const struct regview_test_ctx *ctx, const char *want) +{ + return strstr(ctx->seq_buf, want); +} + +static bool regview_test_starts(const struct regview_test_ctx *ctx, const char *want) +{ + return str_has_prefix(ctx->seq_buf, want); +} + +static unsigned int regview_test_lines(const char *buf) +{ + unsigned int n = 0; + + for (; *buf; buf++) + if (*buf == '\n') + n++; + return n; +} + +static unsigned int regview_test_nr_listed(const struct apple_regview_hw *hw) +{ + unsigned int i, n = 0; + + for (i = 0; i < hw->nr_ranges; i++) + n += hw->ranges[i].count; + return n; +} + +static void regview_test_stride_default(struct kunit *test) +{ + struct apple_regview_range r = { .stride = 0 }; + + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), 4); + r.stride = 0x10; + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), 0x10); + r.stride = MCC_PLANE_STRIDE; + KUNIT_EXPECT_EQ(test, apple_regview_stride(&r), MCC_PLANE_STRIDE); +} + +/* A run whose last word ends exactly at the end of the entry is accepted. */ +static void regview_test_check_exact_fit(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x10, 4, 0, "a" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x20 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + map.size = 0x1000; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); +} + +/* One byte or one word short of the last register is refused. */ +static void regview_test_check_one_past(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x10, 4, 0, "a" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x1c }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + map.size = 0x1f; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + map.size = 0; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* The stride, not 4, sets how far a strided run reaches. */ +static void regview_test_check_strided(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, MCC_PLANE_CACHE_STATUS, 4, MCC_PLANE_STRIDE, "s" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + const u64 need = MCC_PLANE_CACHE_STATUS + 3 * MCC_PLANE_STRIDE + 4; + struct apple_regview_map map = { .size = need }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + map.size = need - 4; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + /* Large enough for four packed words but not for four planes. */ + map.size = MCC_PLANE_CACHE_STATUS + 16; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* A range naming a reg entry the node need not have is refused. */ +static void regview_test_check_bad_reg(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0, 1, 0, "a" }, + { 2, 0, 1, 0, "b" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 2, .nr_regs = 2, + }; + struct apple_regview_map maps[3] = { + { .size = 0x100 }, { .size = 0x100 }, { .size = 0x100 }, + }; + struct apple_regview rv = { .hw = &hw, .maps = maps }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +static void regview_test_check_zero_count(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0, 0, 0, "empty" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x100 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* Offsets near 4 GiB must not wrap around into a small aperture. */ +static void regview_test_check_no_wrap(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0xfffffffc, 2, 0, "wrap" }, + }; + static const struct apple_regview_range ranges_stride[] = { + { 0, 0x10, 3, 0x80000000, "wrap" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 1, .nr_regs = 1, + }; + static const struct apple_regview_hw hw_stride = { + .ranges = ranges_stride, .nr_ranges = 1, .nr_regs = 1, + }; + struct apple_regview_map map = { .size = 0x1000 }; + struct apple_regview rv = { .hw = &hw, .maps = &map }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + rv.hw = &hw_stride; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* Each range is checked against its own reg entry, every range is checked. */ +static void regview_test_check_per_entry(struct kunit *test) +{ + static const struct apple_regview_range ranges[] = { + { 0, 0x0, 1, 0, "small" }, + { 1, 0x800, 1, 0, "big" }, + }; + static const struct apple_regview_hw hw = { + .ranges = ranges, .nr_ranges = 2, .nr_regs = 2, + }; + struct apple_regview_map maps[2] = { + { .size = 0x1000 }, { .size = 0x804 }, + }; + struct apple_regview rv = { .hw = &hw, .maps = maps }; + + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), 0); + /* reg 1 too small even though reg 0 is large */ + maps[1].size = 0x800; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); + /* the last range of the list fails, the first one fits */ + maps[1].size = 0x804; + maps[0].size = 0; + KUNIT_EXPECT_EQ(test, apple_regview_check(&rv), -EINVAL); +} + +/* + * Every built-in list fits the smallest apertures that hold it and is refused + * as soon as any entry it uses is a word smaller. + */ +static void regview_test_tables_fit(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + const struct apple_regview_hw *hw = id->data; + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + unsigned int i; + + KUNIT_EXPECT_EQ_MSG(test, apple_regview_check(&ctx->rv), 0, + "%s", id->compatible); + for (i = 0; i < hw->nr_regs; i++) { + if (!regview_test_extent(hw, i)) + continue; + ctx->maps[i].size -= 4; + KUNIT_EXPECT_EQ_MSG(test, apple_regview_check(&ctx->rv), + -EINVAL, "%s reg %u", id->compatible, i); + ctx->maps[i].size += 4; + } + } +} + +/* Lists are word aligned and name each register at most once. */ +static void regview_test_tables_sane(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + const struct apple_regview_hw *hw = id->data; + unsigned int i, j, a, b; + + KUNIT_ASSERT_NOT_NULL(test, hw); + KUNIT_EXPECT_GT(test, hw->nr_ranges, 0); + KUNIT_EXPECT_GT(test, hw->nr_regs, 0); + + for (i = 0; i < hw->nr_ranges; i++) { + const struct apple_regview_range *r = &hw->ranges[i]; + u32 sr = apple_regview_stride(r); + + KUNIT_EXPECT_LT_MSG(test, r->reg, hw->nr_regs, "%s %s", + id->compatible, r->name); + KUNIT_EXPECT_GT(test, r->count, 0); + KUNIT_EXPECT_EQ(test, r->offset % 4, 0); + KUNIT_EXPECT_EQ(test, sr % 4, 0); + KUNIT_EXPECT_NOT_NULL(test, r->name); + + for (j = i + 1; j < hw->nr_ranges; j++) { + const struct apple_regview_range *q = &hw->ranges[j]; + u32 sq = apple_regview_stride(q); + + if (q->reg != r->reg) + continue; + for (a = 0; a < r->count; a++) { + u32 ra = r->offset + a * sr; + + for (b = 0; b < q->count; b++) + KUNIT_EXPECT_NE_MSG(test, ra, q->offset + b * sq, + "%s: %s[%u] and %s[%u]", + id->compatible, r->name, + a, q->name, b); + } + } + } + } +} + +/* The number of registers each block exposes, as its comment describes. */ +static void regview_test_tables_counts(struct kunit *test) +{ + static const struct { + const char *compatible; + unsigned int regs; + unsigned int nr_regs; + } want[] = { + /* 4 regions x start/end/enable + 4 planes */ + { "apple,t8112-mcc", 16, 2 }, + /* the same on controller 0, plus 4 planes on the other three */ + { "apple,t6000-mcc", 28, 4 }, + /* ten bus fault and seven queue fault counters */ + { "apple,t8112-spmi-sideband", 17, 1 }, + /* sixteen fault counters of the primary bus */ + { "apple,t6000-spmi-monitor", 16, 2 }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(want); i++) { + const struct apple_regview_hw *hw = regview_test_hw(want[i].compatible); + + KUNIT_ASSERT_NOT_NULL_MSG(test, hw, "%s", want[i].compatible); + KUNIT_EXPECT_EQ_MSG(test, regview_test_nr_listed(hw), want[i].regs, + "%s", want[i].compatible); + KUNIT_EXPECT_EQ_MSG(test, hw->nr_regs, want[i].nr_regs, + "%s", want[i].compatible); + } +} + +/* + * Reading the SPMI monitor fault queue (reg[0]) pops an entry, so its list + * must only name the counter window. + */ +static void regview_test_spmi_monitor_no_queue(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t6000-spmi-monitor"); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + for (i = 0; i < hw->nr_ranges; i++) + KUNIT_EXPECT_EQ_MSG(test, hw->ranges[i].reg, SPMI_MON_COUNTERS, + "%s", hw->ranges[i].name); +} + +/* The T8112 MCC planes live in reg[1]; reg[0] is never read. */ +static void regview_test_t8112_mcc_layout(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t8112-mcc"); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, hw); + for (i = 0; i < hw->nr_ranges; i++) + KUNIT_EXPECT_EQ(test, hw->ranges[i].reg, 1); + KUNIT_EXPECT_EQ(test, regview_test_extent(hw, 1), + MCC_PLANE_CACHE_STATUS + 3 * MCC_PLANE_STRIDE + 4); +} + +/* Exact text of the sideband view: one line per register, in list order. */ +static void regview_test_show_format(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t8112-spmi-sideband"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *tail, *want; + char line[64]; + unsigned int j; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), + regview_test_nr_listed(hw)); + want = "0+0x0000200 bus-fault-count[0]: 0xa0000200\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); + want = "\n0+0x0000224 bus-fault-count[9]: 0xa0000224\n" + "0+0x000025c queue-fault-count[0]: 0xa000025c\n"; + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, want)); + tail = "\n0+0x0000274 queue-fault-count[6]: 0xa0000274\n"; + KUNIT_ASSERT_GE(test, ctx->seq_len, strlen(tail)); + KUNIT_EXPECT_STREQ(test, ctx->seq_buf + ctx->seq_len - strlen(tail), tail); + /* The words between the two runs are not shown. */ + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "0x0000228")); + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "[10]")); + + for (j = 0; j < SPMI_SB_NR_BUS_FAULTS; j++) { + snprintf(line, sizeof(line), "0+0x%07x bus-fault-count[%u]: 0x%08x\n", + SPMI_SB_BUS_FAULTS + 4 * j, j, + regview_test_tag(0, SPMI_SB_BUS_FAULTS + 4 * j)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } +} + +/* Values are printed as full 8-digit words, including 0 and all-ones. */ +static void regview_test_show_values(struct kunit *test) +{ + const struct apple_regview_hw *hw = + regview_test_hw("apple,t8112-spmi-sideband"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *want; + u32 *w; + + w = ctx->buf[0]; + w[SPMI_SB_BUS_FAULTS / 4] = 0xffffffff; + w[SPMI_SB_BUS_FAULTS / 4 + 1] = 0x1; + regview_test_show(test, ctx); + + want = "0+0x0000200 bus-fault-count[0]: 0xffffffff\n" + "0+0x0000204 bus-fault-count[1]: 0x00000001\n" + "0+0x0000208 bus-fault-count[2]: 0x00000000\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); +} + +/* A strided run reads the word of each plane, not consecutive words. */ +static void regview_test_show_strided(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t8112-mcc"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + const char *want; + char line[64]; + unsigned int j; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), 16); + want = "1+0x00006a0 tz-start[0]: 0xa10006a0\n" + "1+0x00006b0 tz-start[1]: 0xa10006b0\n"; + KUNIT_EXPECT_TRUE(test, regview_test_starts(ctx, want)); + for (j = 0; j < 4; j++) { + u32 off = MCC_PLANE_CACHE_STATUS + j * MCC_PLANE_STRIDE; + + snprintf(line, sizeof(line), "1+0x%07x cache-status[%u]: 0x%08x\n", + off, j, regview_test_tag(1, off)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, "1+0x00006a8 tz-enable[0]: 0xa10006a8\n")); + KUNIT_EXPECT_TRUE(test, regview_test_has(ctx, "1+0x00c1c04 cache-status[3]: ")); +} + +/* Each range reads the window of its own reg entry. */ +static void regview_test_show_multi_entry(struct kunit *test) +{ + const struct apple_regview_hw *hw = regview_test_hw("apple,t6000-mcc"); + struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); + char line[64]; + unsigned int reg; + + regview_test_fill(ctx); + regview_test_show(test, ctx); + + KUNIT_EXPECT_EQ(test, regview_test_lines(ctx->seq_buf), 28); + for (reg = 0; reg < 4; reg++) { + u32 off = MCC_PLANE_CACHE_STATUS + 2 * MCC_PLANE_STRIDE; + + snprintf(line, sizeof(line), "%u+0x%07x cache-status[2]: 0x%08x\n", + reg, off, regview_test_tag(reg, off)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, line), "%s", line); + } + /* The carveouts are only listed for controller 0. */ + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "1+0x00006a0")); +} + +/* Showing a view leaves every byte of every window as it was. */ +static void regview_test_show_never_writes(struct kunit *test) +{ + const struct of_device_id *id; + + for (id = apple_regview_of_match; id->compatible[0]; id++) { + struct regview_test_ctx *ctx = regview_test_setup(test, id->data, 0x100); + unsigned int i; + + regview_test_fill(ctx); + for (i = 0; i < ctx->rv.hw->nr_regs; i++) + memset(ctx->buf[i] + ctx->maps[i].size, 0x5a, 4); + + regview_test_show(test, ctx); + + for (i = 0; i < ctx->rv.hw->nr_regs; i++) { + u32 *w = ctx->buf[i]; + u64 off; + u32 guard; + + for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) + if (w[off / 4] != regview_test_tag(i, off)) + break; + KUNIT_EXPECT_EQ_MSG(test, off, (u64)ctx->maps[i].size, + "%s reg %u", id->compatible, i); + memcpy(&guard, ctx->buf[i] + ctx->maps[i].size, 4); + KUNIT_EXPECT_EQ(test, guard, 0x5a5a5a5a); + } + } +} + +/* The debugfs file has no write method. */ +static void regview_test_fops_read_only(struct kunit *test) +{ + KUNIT_EXPECT_NULL(test, apple_regview_fops.write); + KUNIT_EXPECT_NULL(test, apple_regview_fops.write_iter); + KUNIT_EXPECT_NOT_NULL(test, apple_regview_fops.read); +} + +static struct kunit_case regview_test_cases[] = { + KUNIT_CASE(regview_test_stride_default), + KUNIT_CASE(regview_test_check_exact_fit), + KUNIT_CASE(regview_test_check_one_past), + KUNIT_CASE(regview_test_check_strided), + KUNIT_CASE(regview_test_check_bad_reg), + KUNIT_CASE(regview_test_check_zero_count), + KUNIT_CASE(regview_test_check_no_wrap), + KUNIT_CASE(regview_test_check_per_entry), + KUNIT_CASE(regview_test_tables_fit), + KUNIT_CASE(regview_test_tables_sane), + KUNIT_CASE(regview_test_tables_counts), + KUNIT_CASE(regview_test_spmi_monitor_no_queue), + KUNIT_CASE(regview_test_t8112_mcc_layout), + KUNIT_CASE(regview_test_show_format), + KUNIT_CASE(regview_test_show_values), + KUNIT_CASE(regview_test_show_strided), + KUNIT_CASE(regview_test_show_multi_entry), + KUNIT_CASE(regview_test_show_never_writes), + KUNIT_CASE(regview_test_fops_read_only), + {} +}; + +static struct kunit_suite regview_test_suite = { + .name = "apple-regview", + .test_cases = regview_test_cases, +}; + +kunit_test_suite(regview_test_suite); diff --git a/drivers/soc/apple/regview.c b/drivers/soc/apple/regview.c index 27f562c6d5d73f..fb741ceb1c0ee8 100644 --- a/drivers/soc/apple/regview.c +++ b/drivers/soc/apple/regview.c @@ -300,3 +300,7 @@ module_exit(apple_regview_exit); MODULE_DESCRIPTION("Apple SoC read-only register views"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +#include "regview-test.c" +#endif diff --git a/drivers/soc/apple/regview.kunitconfig b/drivers/soc/apple/regview.kunitconfig new file mode 100644 index 00000000000000..ed7098ece9530b --- /dev/null +++ b/drivers/soc/apple/regview.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_DEBUG_FS=y +CONFIG_APPLE_REGVIEW=y +CONFIG_APPLE_REGVIEW_KUNIT_TEST=y From dafb8fe5cd95528caa871ed3bc42d79978d2d4b6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 19:13:12 +1100 Subject: [PATCH 0627/1514] soc: apple: add KUnit tests for dbgview Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 14 + drivers/soc/apple/dbgview-test.c | 455 ++++++++++++++++++++++++++ drivers/soc/apple/dbgview.c | 12 +- drivers/soc/apple/dbgview.kunitconfig | 7 + 4 files changed, 486 insertions(+), 2 deletions(-) create mode 100644 drivers/soc/apple/dbgview-test.c create mode 100644 drivers/soc/apple/dbgview.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 8dc9384bdc5d11..7f6828532e7bca 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -25,6 +25,20 @@ config APPLE_DBGVIEW Say m here if you debug an Apple SoC. +config APPLE_DBGVIEW_KUNIT_TEST + bool "KUnit tests for the Apple SoC debug register views" if !KUNIT_ALL_TESTS + depends on APPLE_DBGVIEW=y && KUNIT=y && PM + default KUNIT_ALL_TESTS + help + Read the regs and snapshot views of a register block that the + test backs with kernel memory: whole, partial, unaligned, short + and page-sized reads, end of block, runtime PM references and + failures, bad user buffers, the snapshot format and its size + parameter, and that no view writes the block. The tests touch no + hardware. + + If unsure, say N. + config APPLE_DOCKCHANNEL tristate "Apple DockChannel FIFO" depends on ARCH_APPLE || COMPILE_TEST diff --git a/drivers/soc/apple/dbgview-test.c b/drivers/soc/apple/dbgview-test.c new file mode 100644 index 00000000000000..6b85e7cae3e937 --- /dev/null +++ b/drivers/soc/apple/dbgview-test.c @@ -0,0 +1,455 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SoC read-only debug register views. Included by + * dbgview.c. + * + * The view under test is a struct dbgview whose register block is a buffer + * of kernel memory and whose device is a KUnit device with runtime PM and no + * callbacks. The tests call the driver's own read and snapshot handlers; the + * read handler copies to a KUnit user mapping. No device is probed and no + * MMIO is touched. + */ +#include +#include +#include +#include +#include +#include + +#define DBGVIEW_TEST_USER_SIZE (3 * PAGE_SIZE) +#define DBGVIEW_TEST_SEQ_SIZE (8 * 1024) + +struct dbgview_test_ctx { + struct dbgview dv; + struct file file; + u32 *regs; + u32 *copy; + char __user *ubuf; + u8 *kbuf; + char *seq_buf; +}; + +static u32 dbgview_test_word(size_t i) +{ + return 0xd0000000 | (i * 4); +} + +static struct dbgview_test_ctx *dbgview_test_setup(struct kunit *test, + resource_size_t size, + bool rpm) +{ + struct dbgview_test_ctx *ctx; + unsigned long uaddr; + struct device *dev; + size_t i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + + dev = kunit_device_register(test, "apple-dbgview-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + if (rpm) { + pm_runtime_no_callbacks(dev); + KUNIT_ASSERT_EQ(test, devm_pm_runtime_enable(dev), 0); + } + + /* One spare word past the end to catch a read beyond the block. */ + ctx->regs = kunit_kzalloc(test, size + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->regs); + ctx->copy = kunit_kzalloc(test, size + 4, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->copy); + for (i = 0; i < size / 4 + 1; i++) + ctx->regs[i] = dbgview_test_word(i); + memcpy(ctx->copy, ctx->regs, size + 4); + + ctx->dv.dev = dev; + ctx->dv.base = (void __iomem *)ctx->regs; + ctx->dv.size = size; + ctx->file.private_data = &ctx->dv; + + uaddr = kunit_vm_mmap(test, NULL, 0, DBGVIEW_TEST_USER_SIZE, + PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_NE_MSG(test, uaddr, 0, "no user mapping"); + KUNIT_ASSERT_LT(test, uaddr, (unsigned long)TASK_SIZE); + ctx->ubuf = (char __user *)uaddr; + + ctx->kbuf = kunit_kzalloc(test, DBGVIEW_TEST_USER_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->kbuf); + + return ctx; +} + +/* Fill the user buffer with a marker so that untouched bytes show up. */ +static void dbgview_test_poison_user(struct kunit *test, + struct dbgview_test_ctx *ctx) +{ + memset(ctx->kbuf, 0xee, DBGVIEW_TEST_USER_SIZE); + KUNIT_ASSERT_EQ(test, copy_to_user(ctx->ubuf, ctx->kbuf, + DBGVIEW_TEST_USER_SIZE), 0); +} + +static void dbgview_test_fetch_user(struct kunit *test, + struct dbgview_test_ctx *ctx) +{ + KUNIT_ASSERT_EQ(test, copy_from_user(ctx->kbuf, ctx->ubuf, + DBGVIEW_TEST_USER_SIZE), 0); +} + +static ssize_t dbgview_test_read(struct dbgview_test_ctx *ctx, size_t count, + loff_t *pos) +{ + return dbgview_regs_read(&ctx->file, ctx->ubuf, count, pos); +} + +static int dbgview_test_usage(struct dbgview_test_ctx *ctx) +{ + return atomic_read(&ctx->dv.dev->power.usage_count); +} + +/* Bytes [0, len) of the user buffer are the registers from @pos on. */ +static void dbgview_test_expect_words(struct kunit *test, + struct dbgview_test_ctx *ctx, + loff_t pos, size_t len) +{ + dbgview_test_fetch_user(test, ctx); + KUNIT_EXPECT_MEMEQ(test, ctx->kbuf, (u8 *)ctx->regs + pos, len); + /* nothing past the returned length was written */ + KUNIT_EXPECT_EQ(test, ctx->kbuf[len], 0xee); +} + +static void dbgview_test_read_whole(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x100, &pos), 0x40); + KUNIT_EXPECT_EQ(test, pos, 0x40); + dbgview_test_expect_words(test, ctx, 0, 0x40); +} + +static void dbgview_test_read_offset(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 8; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 8, &pos), 8); + KUNIT_EXPECT_EQ(test, pos, 16); + dbgview_test_expect_words(test, ctx, 8, 8); + KUNIT_EXPECT_EQ(test, *(u32 *)ctx->kbuf, dbgview_test_word(2)); +} + +/* At or beyond the end of the block a read returns 0 and copies nothing. */ +static void dbgview_test_read_eof(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0x40; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 0); + KUNIT_EXPECT_EQ(test, pos, 0x40); + pos = 0x1000; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 0); + KUNIT_EXPECT_EQ(test, pos, 0x1000); + dbgview_test_fetch_user(test, ctx); + KUNIT_EXPECT_EQ(test, ctx->kbuf[0], 0xee); +} + +/* Only whole, aligned words are read. */ +static void dbgview_test_read_unaligned_pos(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos; + + for (pos = 1; pos < 4; pos++) { + loff_t p = pos; + + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &p), -EINVAL); + KUNIT_EXPECT_EQ(test, p, pos); + } + pos = -4; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), -EINVAL); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +static void dbgview_test_read_short_count(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + size_t count; + + for (count = 0; count < 4; count++) { + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, count, &pos), -EINVAL); + KUNIT_EXPECT_EQ(test, pos, 0); + } + + /* A count that is not a whole number of words is rounded down. */ + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 7, &pos), 4); + KUNIT_EXPECT_EQ(test, pos, 4); + dbgview_test_expect_words(test, ctx, 0, 4); +} + +/* A read near the end stops at the end of the block. */ +static void dbgview_test_read_clamped(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0x3c; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x10, &pos), 4); + KUNIT_EXPECT_EQ(test, pos, 0x40); + dbgview_test_expect_words(test, ctx, 0x3c, 4); + KUNIT_EXPECT_EQ(test, *(u32 *)ctx->kbuf, dbgview_test_word(0xf)); +} + +/* One read never covers more than a page. */ +static void dbgview_test_read_page_cap(struct kunit *test) +{ + resource_size_t size = 2 * PAGE_SIZE + 0x40; + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, size, true); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, DBGVIEW_TEST_USER_SIZE, &pos), + PAGE_SIZE); + KUNIT_EXPECT_EQ(test, pos, PAGE_SIZE); + dbgview_test_expect_words(test, ctx, 0, PAGE_SIZE); +} + +/* Reading on until EOF returns every word once and nothing else. */ +static void dbgview_test_read_sequential(struct kunit *test) +{ + resource_size_t size = 2 * PAGE_SIZE + 0x40; + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, size, true); + u8 *all = kunit_kzalloc(test, size, GFP_KERNEL); + unsigned int reads = 0; + loff_t pos = 0; + ssize_t ret; + + KUNIT_ASSERT_NOT_NULL(test, all); + while ((ret = dbgview_test_read(ctx, 0x1000, &pos)) > 0) { + KUNIT_ASSERT_LE(test, pos, size); + KUNIT_ASSERT_EQ(test, copy_from_user(all + pos - ret, ctx->ubuf, ret), 0); + KUNIT_ASSERT_LT(test, ++reads, 1000); + } + KUNIT_EXPECT_EQ(test, ret, 0); + KUNIT_EXPECT_EQ(test, pos, size); + KUNIT_EXPECT_MEMEQ(test, all, (u8 *)ctx->regs, size); +} + +/* Every read takes and drops one runtime PM reference. */ +static void dbgview_test_read_rpm_balanced(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + int i; + + for (i = 0; i < 4; i++) { + pos = 0; + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x40, &pos), 0x40); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); + } +} + +/* If the block cannot be powered, nothing is read or copied. */ +static void dbgview_test_read_rpm_error(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, false); + loff_t pos = 0; + + dbgview_test_poison_user(test, ctx); + KUNIT_EXPECT_EQ(test, dbgview_test_read(ctx, 0x40, &pos), -EACCES); + KUNIT_EXPECT_EQ(test, pos, 0); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); + dbgview_test_fetch_user(test, ctx); + KUNIT_EXPECT_EQ(test, ctx->kbuf[0], 0xee); +} + +/* A bad user buffer fails the read and leaves the position alone. */ +static void dbgview_test_read_efault(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, true); + loff_t pos = 0; + + KUNIT_EXPECT_EQ(test, dbgview_regs_read(&ctx->file, (char __user *)NULL, + 0x40, &pos), -EFAULT); + KUNIT_EXPECT_EQ(test, pos, 0); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* Reads never change the block, nor the word past its end. */ +static void dbgview_test_read_never_writes(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x80, true); + loff_t pos = 0; + + while (dbgview_test_read(ctx, 0x14, &pos) > 0) + ; + KUNIT_EXPECT_MEMEQ(test, ctx->regs, ctx->copy, 0x80 + 4); +} + +static bool dbgview_test_has(const struct dbgview_test_ctx *ctx, const char *want) +{ + return strstr(ctx->seq_buf, want); +} + +static bool dbgview_test_starts(const struct dbgview_test_ctx *ctx, const char *want) +{ + return str_has_prefix(ctx->seq_buf, want); +} + +static unsigned int dbgview_test_lines(const char *buf) +{ + unsigned int n = 0; + + for (; *buf; buf++) + if (*buf == '\n') + n++; + return n; +} + +static int dbgview_test_snapshot(struct kunit *test, + struct dbgview_test_ctx *ctx, unsigned int bytes) +{ + struct seq_file s = { }; + int ret; + + ctx->seq_buf = kunit_kzalloc(test, DBGVIEW_TEST_SEQ_SIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->seq_buf); + s.buf = ctx->seq_buf; + s.size = DBGVIEW_TEST_SEQ_SIZE - 1; + s.private = &ctx->dv; + + ret = dbgview_snapshot(&s, bytes); + KUNIT_EXPECT_FALSE(test, seq_has_overflowed(&s)); + ctx->seq_buf[s.count] = '\0'; + return ret; +} + +/* Counter, one line per word, counter, frequency. */ +static void dbgview_test_snapshot_format(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x100, true); + unsigned long long before, after; + unsigned int frq; + char line[32]; + int n; + const char *p; + size_t i; + + KUNIT_ASSERT_EQ(test, dbgview_test_snapshot(test, ctx, 0x40), 0); + + KUNIT_EXPECT_EQ(test, dbgview_test_lines(ctx->seq_buf), 16 + 3); + n = sscanf(ctx->seq_buf, "cntvct_before %16llx\n", &before); + KUNIT_ASSERT_EQ(test, n, 1); + KUNIT_EXPECT_EQ(test, ctx->seq_buf[strlen("cntvct_before ") + 16], '\n'); + + p = strchr(ctx->seq_buf, '\n') + 1; + for (i = 0; i < 16; i++) { + snprintf(line, sizeof(line), "%04zx %08x\n", i * 4, + dbgview_test_word(i)); + KUNIT_EXPECT_TRUE_MSG(test, str_has_prefix(p, line), "%s", line); + p = strchr(p, '\n') + 1; + } + n = sscanf(p, "cntvct_after %16llx\n", &after); + KUNIT_ASSERT_EQ(test, n, 1); + p = strchr(p, '\n') + 1; + n = sscanf(p, "cntfrq %u\n", &frq); + KUNIT_ASSERT_EQ(test, n, 1); + + KUNIT_EXPECT_LE(test, before, after); + KUNIT_EXPECT_NE(test, before, 0); + KUNIT_EXPECT_EQ(test, frq, arch_timer_get_cntfrq()); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* The snapshot covers snap_bytes, rounded down to words, within the block. */ +static void dbgview_test_snapshot_sizes(struct kunit *test) +{ + static const struct { + resource_size_t size; + unsigned int snap; + unsigned int words; + } cases[] = { + { 0x100, 0x40, 16 }, + { 0x10, 0x40, 4 }, /* clamped to the block */ + { 0x100, 8, 2 }, + { 0x100, 6, 1 }, /* partial word dropped */ + { 0x100, 3, 0 }, + { 0x100, 0, 0 }, + { 0x100, 0x100, 64 }, + { 0x40, 0xffffffff, 16 }, + }; + char last[32]; + size_t i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct dbgview_test_ctx *ctx = + dbgview_test_setup(test, cases[i].size, true); + + KUNIT_ASSERT_EQ(test, dbgview_test_snapshot(test, ctx, cases[i].snap), 0); + KUNIT_EXPECT_EQ_MSG(test, dbgview_test_lines(ctx->seq_buf), + cases[i].words + 3, "case %zu", i); + if (cases[i].words) { + snprintf(last, sizeof(last), "\n%04x %08x\ncntvct_after ", + (cases[i].words - 1) * 4, + dbgview_test_word(cases[i].words - 1)); + KUNIT_EXPECT_NOT_NULL_MSG(test, strstr(ctx->seq_buf, last), + "case %zu", i); + } else { + KUNIT_EXPECT_TRUE(test, dbgview_test_has(ctx, "\ncntvct_after ")); + KUNIT_EXPECT_TRUE(test, dbgview_test_starts(ctx, "cntvct_before ")); + KUNIT_EXPECT_NULL(test, strstr(ctx->seq_buf, "\n0000 ")); + } + KUNIT_EXPECT_MEMEQ(test, ctx->regs, ctx->copy, cases[i].size + 4); + kunit_device_unregister(test, ctx->dv.dev); + } +} + +static void dbgview_test_snapshot_rpm_error(struct kunit *test) +{ + struct dbgview_test_ctx *ctx = dbgview_test_setup(test, 0x40, false); + + KUNIT_EXPECT_EQ(test, dbgview_test_snapshot(test, ctx, 0x40), -EACCES); + KUNIT_EXPECT_EQ(test, ctx->seq_buf[0], '\0'); + KUNIT_EXPECT_EQ(test, dbgview_test_usage(ctx), 0); +} + +/* Neither file has a write method. */ +static void dbgview_test_fops_read_only(struct kunit *test) +{ + KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write); + KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write_iter); + KUNIT_EXPECT_TRUE(test, dbgview_regs_fops.read == dbgview_regs_read); + KUNIT_EXPECT_NULL(test, dbgview_snapshot_fops.write); + KUNIT_EXPECT_NULL(test, dbgview_snapshot_fops.write_iter); +} + +static struct kunit_case dbgview_test_cases[] = { + KUNIT_CASE(dbgview_test_read_whole), + KUNIT_CASE(dbgview_test_read_offset), + KUNIT_CASE(dbgview_test_read_eof), + KUNIT_CASE(dbgview_test_read_unaligned_pos), + KUNIT_CASE(dbgview_test_read_short_count), + KUNIT_CASE(dbgview_test_read_clamped), + KUNIT_CASE(dbgview_test_read_page_cap), + KUNIT_CASE(dbgview_test_read_sequential), + KUNIT_CASE(dbgview_test_read_rpm_balanced), + KUNIT_CASE(dbgview_test_read_rpm_error), + KUNIT_CASE(dbgview_test_read_efault), + KUNIT_CASE(dbgview_test_read_never_writes), + KUNIT_CASE(dbgview_test_snapshot_format), + KUNIT_CASE(dbgview_test_snapshot_sizes), + KUNIT_CASE(dbgview_test_snapshot_rpm_error), + KUNIT_CASE(dbgview_test_fops_read_only), + {} +}; + +static struct kunit_suite dbgview_test_suite = { + .name = "apple-dbgview", + .test_cases = dbgview_test_cases, +}; + +kunit_test_suite(dbgview_test_suite); diff --git a/drivers/soc/apple/dbgview.c b/drivers/soc/apple/dbgview.c index f0eb987112848d..9f60ce7ccc5c5b 100644 --- a/drivers/soc/apple/dbgview.c +++ b/drivers/soc/apple/dbgview.c @@ -99,10 +99,10 @@ static const struct file_operations dbgview_regs_fops = { .llseek = default_llseek, }; -static int dbgview_snapshot_show(struct seq_file *s, void *unused) +static int dbgview_snapshot(struct seq_file *s, unsigned int bytes) { struct dbgview *dv = s->private; - size_t words = min_t(size_t, snap_bytes, dv->size) / 4; + size_t words = min_t(size_t, bytes, dv->size) / 4; unsigned long flags; u64 before, after; u32 *val; @@ -138,6 +138,10 @@ static int dbgview_snapshot_show(struct seq_file *s, void *unused) kfree(val); return 0; } +static int dbgview_snapshot_show(struct seq_file *s, void *unused) +{ + return dbgview_snapshot(s, snap_bytes); +} DEFINE_SHOW_ATTRIBUTE(dbgview_snapshot); static int dbgview_probe(struct platform_device *pdev) @@ -221,3 +225,7 @@ module_exit(dbgview_exit); MODULE_AUTHOR("Ryan Murray <81541646+RyanTheTide@users.noreply.github.com>"); MODULE_DESCRIPTION("Apple SoC read-only debug register views"); MODULE_LICENSE("Dual MIT/GPL"); + +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +#include "dbgview-test.c" +#endif diff --git a/drivers/soc/apple/dbgview.kunitconfig b/drivers/soc/apple/dbgview.kunitconfig new file mode 100644 index 00000000000000..e77e9bdc8bd832 --- /dev/null +++ b/drivers/soc/apple/dbgview.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_PM=y +CONFIG_DEBUG_FS=y +CONFIG_APPLE_DBGVIEW=y +CONFIG_APPLE_DBGVIEW_KUNIT_TEST=y From 306f769639f133d762cafb1b3290bcaba984d8aa Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 16 Nov 2026 19:49:11 +0000 Subject: [PATCH 0628/1514] drm/asahi: g17: scale the render pool floor from GPU shape With four-cluster tiling the 32-core M4 Max runs vertex shaders on every cluster at once beside fragment work. Roblox (Vulkan) then hangs the GPU about once a minute: the firmware kills a small depth/stencil render as no-progress (reason 0), with no MMU fault and a nearly empty tiler heap. The same hang showed up on this Mac with the earlier driver until its render pool had 96 blocks. G17 firmware has no grow-request event for the USC render pool (unlike TVB growth) and a published render pool cannot be resized in place, so the pool must be sized up front. Rather than gating a fixed 96-block pool on T6041 and firmware build 25G83, derive the render pool minimum from GPU shape (active cores and cluster count) inside g17::fw::render_rt::required_blocks(), before adding ray-query scratch extras: - One- and two-cluster GPUs keep the 44-block floor (RENDER_BLOCKS), preserving the A18 Pro shared pool window invariant and the M4 Pro's narrow pool window unchanged. - Above two clusters, the base pool scales at 3 blocks (3 MiB) per enabled core, floored at RENDER_BLOCKS (44). Note that 3 blocks/core is an empirical fit from one 32-core J616C measurement (96 / 32), not a hardware-derived bound; the 40-core J614C value (120 blocks) has not been run on hardware yet. Because it keys on GPU shape, every >2-cluster G17 firmware build (including 25F84 and 26B123 on T6041) gets this floor, not only 25G83. - Ray-query scratch is added on top of this base instead of competing with it. Capacity cost in WIDE_LOWER (~3.19 GiB, shared with other lower-window allocations): queue creation allocates no VA or backing; backing is placed lazily on first render (~98 MiB span on J616C, ~122 MiB span on J614C, vs ~46 MiB before), reducing the simultaneously resident pool budget from 58 (MAX_EXECUTION_CONTEXTS) to roughly 33 on J616C and 26 on J614C. When WIDE_LOWER fills, submit enters wait_render_capacity() -> reclaim_render_capacity(), which evicts idle render pools via FreeListRelease and transparently re-arms them on next use. Only when more than ~33 (J616C) / ~26 (J614C) distinct contexts are simultaneously active for longer than QUEUE_WAIT_NS does a new submission fail with EBUSY, leaving existing contexts intact. J616C has run with 96 blocks daily since 16 Nov without hitting the cap. Resulting base render pool blocks (pages = [0, 0]): Part Clusters Cores Base blocks A18 / A18 Pro (T8140) 1 5/6 44 (unchanged) M4 (T8132, uses g16) 1 8/10 44 (if on g17) M4 Pro (T6040) 2 16/20 44 (unchanged) M4 Max 32-core (J616C) 4 32 96 (measured fix) M4 Max 40-core (J614C) 4 40 120 (untested) M5 (T8142, M5 pool path) 1 8/10 44 (unchanged) M5 Pro (T6050, M5 pool) 2 16/20 44 (unchanged) M5 Max (T6050, M5 pool) 4 32/40 96/120 (M5 uses own) M5 Ultra (T6050, M5 pool) 8 64/80 192/240 (M5 uses own) Add KUnit tests (asahi_g17_render_pool) covering these shapes, ray-query scratch addition, and invalid/oversized rejections. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/fw/freelist.rs | 6 ++ drivers/gpu/drm/asahi/g17/fw/render_rt.rs | 91 ++++++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 7 +- 3 files changed, 96 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/freelist.rs b/drivers/gpu/drm/asahi/g17/fw/freelist.rs index 56c1f2324e2a17..fe5981b439666a 100644 --- a/drivers/gpu/drm/asahi/g17/fw/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/fw/freelist.rs @@ -10,6 +10,12 @@ pub(crate) const RUN_LIST_SIZE: usize = 0x1_0000; pub(crate) const TABLE_SIZE: usize = PAGE_LIST_SIZE + RUN_LIST_SIZE; pub(crate) const CONTROL_SIZE: usize = 0x4000; pub(crate) const RENDER_BLOCKS: usize = 44; +/// Minimum render pool per active USC core (in 1 MiB blocks) on GPUs with more +/// than two clusters. With clustered tiling running vertex work across all +/// clusters concurrently with fragment work, 44 blocks run out under Vulkan +/// vertex load (reason-0 no-progress recoveries); three blocks per enabled core +/// yield 96 blocks on 32-core T6041 and scale linearly on larger parts. +pub(crate) const MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE: usize = 3; pub(crate) const COMPUTE_BLOCKS: usize = 21; /// Render reserves eight run words per block; compute packs runs consecutively. diff --git a/drivers/gpu/drm/asahi/g17/fw/render_rt.rs b/drivers/gpu/drm/asahi/g17/fw/render_rt.rs index 666209690efde0..74679c34d18ae2 100644 --- a/drivers/gpu/drm/asahi/g17/fw/render_rt.rs +++ b/drivers/gpu/drm/asahi/g17/fw/render_rt.rs @@ -1,8 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -use super::{compute::{IntersectionTables, ScratchRequest}, compute_pool, - freelist::{PAGE_LIST_SIZE, RENDER_BLOCKS}, - initdata::{FREE_LIST_BLOCK_PAGES, FREE_LIST_BLOCK_SIZE}}; +use super::{ + compute::{IntersectionTables, ScratchRequest}, + compute_pool, + freelist::{MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE, PAGE_LIST_SIZE, RENDER_BLOCKS}, + initdata::{FREE_LIST_BLOCK_PAGES, FREE_LIST_BLOCK_SIZE}, +}; use kernel::prelude::*; #[derive(Clone, Copy)] @@ -33,18 +36,92 @@ impl RayQueryStage { } } +/// Minimum render pool in 1 MiB blocks for a GPU's cluster and active-core shape. +/// +/// One- and two-cluster parts (A18 Pro, M4 Pro) keep [`RENDER_BLOCKS`] (44), +/// which fits the narrow shared pool window and has been validated there. Above +/// two clusters, clustered tiling runs vertex shaders across every cluster +/// concurrently with fragment work, so the base pool scales linearly with +/// enabled cores at [`MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE`] (3) blocks per +/// core, floored at [`RENDER_BLOCKS`]. +pub(crate) fn base_blocks(active_cores: u32, clusters: u32) -> Result { + if active_cores == 0 || clusters == 0 { + return Err(EINVAL); + } + if clusters <= 2 { + return Ok(RENDER_BLOCKS); + } + let scaled = usize::try_from(active_cores) + .ok() + .and_then(|cores| cores.checked_mul(MULTI_CLUSTER_RENDER_BLOCKS_PER_CORE)) + .ok_or(EOVERFLOW)?; + Ok(scaled.max(RENDER_BLOCKS)) +} + /// The render pool of an owner is shared by its `pairs` render pairs, each with -/// its own compute-pool extras. -pub(crate) fn required_blocks(active_cores: u32, pages: [u16; 2], pairs: u8) -> Result { +/// its own compute-pool extras on top of the GPU-shape base pool. +pub(crate) fn required_blocks( + active_cores: u32, + clusters: u32, + pages: [u16; 2], + pairs: u8, +) -> Result { + let base = base_blocks(active_cores, clusters)?; let extra = compute_pool::extra_bytes(active_cores, pages[0])? .checked_add(compute_pool::extra_bytes(active_cores, pages[1])?) .and_then(|bytes| bytes.checked_mul(u64::from(pairs))) .ok_or(EOVERFLOW)?; - let bytes = extra.checked_add((RENDER_BLOCKS * FREE_LIST_BLOCK_SIZE) as u64) + let base_bytes = u64::try_from(base) + .ok() + .and_then(|blocks| blocks.checked_mul(FREE_LIST_BLOCK_SIZE as u64)) .ok_or(EOVERFLOW)?; + let bytes = extra.checked_add(base_bytes).ok_or(EOVERFLOW)?; let blocks = usize::try_from(bytes.div_ceil(FREE_LIST_BLOCK_SIZE as u64)) .map_err(|_| EOVERFLOW)?; let maximum = PAGE_LIST_SIZE / (FREE_LIST_BLOCK_PAGES as usize * 8); - if blocks > maximum { return Err(E2BIG); } + if blocks > maximum { + return Err(E2BIG); + } Ok(blocks) } + +#[kernel::macros::kunit_tests(asahi_g17_render_pool)] +mod tests { + use super::*; + + #[test] + fn one_and_two_cluster_parts_keep_default_floor() { + for (cores, clusters) in [(5, 1), (6, 1), (8, 1), (10, 1), (16, 2), (20, 2)] { + assert_eq!(base_blocks(cores, clusters), Ok(RENDER_BLOCKS)); + assert_eq!(required_blocks(cores, clusters, [0, 0], 1), Ok(RENDER_BLOCKS)); + } + } + + #[test] + fn multi_cluster_parts_scale_with_active_cores() { + // 32-core J616C (4 clusters): 96 blocks; 40-core J614C/J575C (4 clusters): 120 blocks. + assert_eq!(required_blocks(32, 4, [0, 0], 1), Ok(96)); + assert_eq!(required_blocks(40, 4, [0, 0], 1), Ok(120)); + // A small hypothetical >2-cluster part stays floored at RENDER_BLOCKS. + assert_eq!(required_blocks(8, 4, [0, 0], 1), Ok(RENDER_BLOCKS)); + // Eight-cluster M5 Ultra topologies (M5 allocates its own pools, but queue creation + // still checks required_blocks): 192 / 240 blocks, well within the table limit. + assert_eq!(required_blocks(64, 8, [0, 0], 2), Ok(192)); + assert_eq!(required_blocks(80, 8, [0, 0], 2), Ok(240)); + } + + #[test] + fn ray_query_scratch_adds_on_top_of_base_pool() { + // 64 pages per stage -> per_core = 64 + 1 + 8 = 73 pages = 299,008 bytes/core/stage. + assert_eq!(required_blocks(20, 2, [64, 64], 1), Ok(44 + 12)); + assert_eq!(required_blocks(32, 4, [64, 64], 1), Ok(96 + 19)); + assert_eq!(required_blocks(40, 4, [64, 64], 1), Ok(120 + 23)); + } + + #[test] + fn rejects_invalid_shape_and_oversized_pools() { + assert_eq!(required_blocks(0, 4, [0, 0], 1), Err(EINVAL)); + assert_eq!(required_blocks(32, 0, [0, 0], 1), Err(EINVAL)); + assert_eq!(required_blocks(400, 4, [0, 0], 1), Err(E2BIG)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f9d2999a4e1d59..f12626e7039b0d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -225,7 +225,12 @@ impl job::Backend for Backend { } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { - crate::g17::fw::render_rt::required_blocks(self.shared.active_cores, pages, self.pairs) + crate::g17::fw::render_rt::required_blocks( + self.shared.active_cores, + self.shared.clusters, + pages, + self.pairs, + ) } fn ensure_compute(&self, command: &crate::g17::command::Validated) -> Result { From e45c2b916dafff627814ff7112f0389c887d80f8 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Sun, 22 Nov 2026 16:10:26 +0000 Subject: [PATCH 0629/1514] drm/asahi: g17: take T6041 render pool identity at context creation Taking a context's render pool identity (one of 127 in firmware.render_ids) at context creation rather than lazily on the first render is pure host-side accounting in g17/runtime.rs and g17/context.rs with no firmware ABI dependency. If render graphs retained until firmware stop exhaust the remaining identities, queue creation fails cleanly with ENOSPC instead of succeeding and failing the context's first render with a lost device. Enable render_id_at_create on T6041's 25G83 and 26B123 variants (covering both 32-core and 40-core configurations). Keep objects_after_release disabled on 25G83/26B123: relaxing the strict control_fence() from commit 34b438de3df9 ("drm/asahi: g17: fence recycled firmware identities and storage"), which fixed an M4 Pro crash on a recycled work state, requires dedicated create/destroy queue churn stress testing on M4 hardware first. Test scope: compile-tested here; runtime verification on J616C (32-core T6041, 25G83) is pending, and 40-core configurations (J614C/J575C) and 26B123 have not been hardware-tested. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/fw/variant.rs | 4 ++-- drivers/gpu/drm/asahi/hw/t6041.rs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 3c40fba4aa8c00..d7a0cffd18bb47 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -99,8 +99,8 @@ pub(crate) struct Variant { /// A context takes its render pool identity when it is created, not at its first render, /// so that identities held by render graphs kept until the firmware stops refuse new /// contexts with an error instead of failing a context's first render. Set for the A18 - /// Pro only: the M4 Pro and Max keep the first-render claim until the claim at creation has - /// been tested on that hardware. + /// Pro and M4 Max (`25G83`/`26B123`); M4 Pro and M4 Max `25F84` keep the first-render + /// claim until tested on that hardware. pub(crate) render_id_at_create: bool, /// Cached descriptor storage, queue records and queue configuration that come back /// after their owner's release was consumed are reused once the firmware has consumed diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 516c5b1a9882f6..a57e1d0f47cdea 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -111,6 +111,7 @@ pub(super) const BUILD_26B123: fw::variant::Build = fw::variant::Build { }], variant: &fw::variant::Variant { ta_mode_1: true, + render_id_at_create: true, ..fw::variant::V26B123 }, config: None, @@ -212,6 +213,7 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { render_stage_prefixes: true, ta_mode_1: true, telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, + render_id_at_create: true, ..fw::variant::V25G83 }, config: None, From 492ea7e1395023fd3426acf25b0e0c01d8cebd3c Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 16 Nov 2026 19:49:11 +0000 Subject: [PATCH 0630/1514] drm/asahi: g17: tile clustered on the 32-core M4 Max (T6041 25G83) T6041 ran its 25G83 tiling passes in TA mode 1 (0x1c890 = 1), which tiles non-clustered: one of the four clusters runs the tiling and vertex work of a pass. Vertex shaders reached a quarter of the ALU rate of the GPU (2.95 vs 12.3 TFLOPS), and geometry-bound games were capped by it. Tile clustered instead on the 32-core T6041 (J616C) 25G83 build, while keeping the untested 40-core T6041 parts (J614C, J575C) on TA mode 1 until they have a hardware row. Clustered four-cluster passes receive: - Clustering metadata sized for more than two clusters, with metadata 2 at 0x1180 as macOS 26.6.2 writes on the 32-core M4 Max (metadata 2 at the M2 Pro/Max 0xc00 size allowed the tiler to write past it into metadata 3; metadata 3 and 4 keep their larger sizes). Because 25F84, 40-core 25G83, and 26B123 share RegisterPrograms::V25G83, four-cluster targets on those builds also receive the 0x1180 metadata 2 sizing while keeping TA mode 1 (non-clustered); that oversizing has not been booted on 25F84/26B123. - The four-cluster segment words of cluster_control(): 0x1c890 = 0x280540, 0x1c918 = 4, and v25g83_clustered_free_pages(clusters) = 28 + 16 * clusters free parameter-buffer pages in 0x1c9a8 (0x3c for two clusters, 0x5c for four, matching the macOS 26.6.2 capture). Two clusters keep the M4 Pro capture. - The full block table for Variant::tvb_normal_blocks on 32-core 25G83, because a clustered RD32 Minecraft frame needs about 1600-2200 blocks and never starts at the 0x45e default. 25F84, 40-core 25G83, and 26B123 keep TA mode 1 and the default heap maximum. Every other chip and build keeps its values. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/buffer.rs | 11 +- drivers/gpu/drm/asahi/g17/buffer/target.rs | 39 +++++- drivers/gpu/drm/asahi/g17/fw/buffer.rs | 6 +- drivers/gpu/drm/asahi/g17/fw/render.rs | 115 ++++++++++++++---- drivers/gpu/drm/asahi/g17/fw/variant.rs | 5 + drivers/gpu/drm/asahi/g17/queue/render.rs | 1 + .../gpu/drm/asahi/g17/queue/render/memory.rs | 1 + drivers/gpu/drm/asahi/hw/t6041.rs | 25 +++- drivers/gpu/drm/asahi/hw/t6041_25g83.rs | 2 +- 9 files changed, 172 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 2e2c79ae15123f..fd0aace6a42624 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -704,6 +704,8 @@ pub(crate) struct ManagerArgs { pub(crate) buffer_id: u8, pub(crate) generation: u64, pub(crate) first_ordinal: u64, + /// The heap's normal maximum in blocks (`Variant::tvb_normal_blocks`); NEO heaps only. + pub(crate) normal_blocks: usize, } /// A retained parameter-buffer graph and all of its sparse backing. Client @@ -793,7 +795,13 @@ impl Manager { ) -> Result { let geometry = tvb.geometry; let neo = geometry == BlockGeometry::NEO; - let layout = if neo { layout::Layout::NEO } else { layout::Layout::m5(geometry)? }; + let mut layout = if neo { layout::Layout::NEO } else { layout::Layout::m5(geometry)? }; + if neo { + if args.normal_blocks == 0 || args.normal_blocks > geometry.max_blocks() { + return Err(EINVAL); + } + layout.normal_blocks = args.normal_blocks; + } if metrics.scene_stride != layout.metric_stride { return Err(EINVAL); } @@ -827,6 +835,7 @@ impl Manager { discard: args.discard, buffer_id: args.buffer_id.into(), generation: args.generation, + normal_blocks: layout.normal_blocks, }; if neo { graph.initialize::(0, |view| view.init(&graph_args))?; diff --git a/drivers/gpu/drm/asahi/g17/buffer/target.rs b/drivers/gpu/drm/asahi/g17/buffer/target.rs index 8b87ccde7d9857..b8c2677cb66481 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/target.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/target.rs @@ -35,6 +35,14 @@ const GTP_FIXED_SIZES: [usize; 4] = [0xc00, 0xa00, GTP6_SIZE, 0x80]; const GTP_SLOTS: usize = 64; const GTP6_SIZE: usize = GTP_SLOTS * (((cfg::TVB_MAX_BLOCKS * cfg::TVB_BLOCK_SIZE).div_ceil(0x8000) + 0x17ff) / 24 * 8 + 8); +/// Clustering metadata 2-4 (0x1c948, 0x1c888, 0x16c41/0x1ca40) on GPUs with more than two +/// clusters, at the sizes the M2 Pro/Max path gives them (`hw/t602x.rs` clustering config). +/// Metadata 1 (0x1c920) is sized per target there: [`META1_BLOCK_SIZE`] per block of tiles. +/// +/// macOS 26.6.2 on the J616C spaces a clustered pass's metadata 2, 3 and 4 0x1180, 0x1400 +/// and 0x1600 apart: metadata 2 needs 0x1180, more than the M2 Pro/Max 0xc00. +const GTP_MULTI_CLUSTER_SIZES: [usize; 3] = [0x1180, 0x280 * 16, 0x10 * 128]; +const META1_BLOCK_SIZE: usize = 0x44; /// Per-command geometry, independent of the capacity already allocated. #[derive(Copy, Clone, Debug)] @@ -116,15 +124,38 @@ impl Layout { let mut gtp = [None; 8]; let mut tpc_end = tpc_size; if programs == RegisterPrograms::V25G83 { + // The fixed sizes are the two-cluster M4 Pro's. With four clusters (M4 Max) clustered + // tiling outgrows them: the firmware then never starts a heavy render and kills it as + // no-progress (reason 0). Size them as the M2 Pro/Max path does. + let [meta2, meta3, meta4, meta1] = if clusters > 2 { + let meta1_blocks = aligned(tiles_x, 2)? + .checked_mul(aligned(tiles_y, 4)?) + .and_then(|v| v.checked_mul(utiles)) + .ok_or(EOVERFLOW)? + .div_ceil(0x1980); + [ + GTP_MULTI_CLUSTER_SIZES[0], + GTP_MULTI_CLUSTER_SIZES[1], + // Partial renders need the larger size here too. + GTP_MULTI_CLUSTER_SIZES[2].max(GTP6_SIZE), + aligned( + meta1_blocks.checked_mul(META1_BLOCK_SIZE).ok_or(EOVERFLOW)?, + 0x80, + )? + .max(GTP_FIXED_SIZES[3]), + ] + } else { + GTP_FIXED_SIZES + }; let sizes = [ tpc_size, tilemap_size.checked_mul(64).ok_or(EOVERFLOW)?, if layers > 1 { 0x4000 } else { 0 }, 0, - GTP_FIXED_SIZES[0], - GTP_FIXED_SIZES[1], - GTP_FIXED_SIZES[2], - GTP_FIXED_SIZES[3], + meta2, + meta3, + meta4, + meta1, ]; let mut position = 0; for ((offset, size), alignment) in gtp.iter_mut().zip(sizes).zip(GTP_ALIGNMENTS) { diff --git a/drivers/gpu/drm/asahi/g17/fw/buffer.rs b/drivers/gpu/drm/asahi/g17/fw/buffer.rs index 9d430d50db365e..c6f9ef0819f756 100644 --- a/drivers/gpu/drm/asahi/g17/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/fw/buffer.rs @@ -22,6 +22,8 @@ pub(crate) const SIZE: usize = 0x48000; pub(crate) const METRICS_STRIDE: usize = SCENES * size_of::(); pub(crate) const METRICS_SLOTS: usize = cfg::METRICS_SIZE as usize / METRICS_STRIDE; pub(crate) const NORMAL_MAX_BLOCKS: usize = 0x45e; +/// The normal maximum of a four-cluster G17P heap: every slot of the block table. +pub(crate) const NORMAL_MAX_BLOCKS_FOUR_CLUSTERS: usize = cfg::TVB_MAX_BLOCKS; pub(crate) const GROW_BLOCKS: usize = 10; /// Firmware's active parameter-buffer state. Pointers at +0x44, +0x4c, @@ -136,6 +138,8 @@ pub(crate) struct GraphArgs<'a> { pub(crate) discard: u64, pub(crate) buffer_id: u32, pub(crate) generation: u64, + /// The heap's normal maximum in blocks (`Variant::tvb_normal_blocks`). + pub(crate) normal_blocks: usize, } pub(crate) fn compact_page(address: u64) -> Result { @@ -197,7 +201,7 @@ impl Graph { self.state.block_size = cfg::TVB_BLOCK_SIZE as u32; self.state.counter = offset_va(args.fw_va, COUNTER as u64)?; self.state.maximum_size = (cfg::TVB_BLOCK_SLOTS * 4) as u32; - self.state.normal_maximum_size = (NORMAL_MAX_BLOCKS * 4) as u32; + self.state.normal_maximum_size = (args.normal_blocks * 4) as u32; self.state.discard = discard; Ok(()) } diff --git a/drivers/gpu/drm/asahi/g17/fw/render.rs b/drivers/gpu/drm/asahi/g17/fw/render.rs index dc22354f9c2ded..023a633230c3c6 100644 --- a/drivers/gpu/drm/asahi/g17/fw/render.rs +++ b/drivers/gpu/drm/asahi/g17/fw/render.rs @@ -398,6 +398,9 @@ pub(crate) struct RenderArgs<'a> { pub(crate) programs: RegisterPrograms, /// Device/build policy for registers 0x1c890 and 0x1c918 in V25G83-format arrays. pub(crate) ta_mode_1: bool, + /// Clusters of the GPU: above two, clustered tiling takes the segment words of + /// `fw::m5::target::cluster_control` instead of the two-cluster capture. + pub(crate) clusters: u32, /// Deflake-buffer layout of the GPU. pub(crate) deflake: Deflake, } @@ -697,6 +700,13 @@ const T6041_TA_MODE_1: u64 = 1; /// Pages the tiler keeps out of a partial render's segments: without them the pages a pass /// returns shrink to none and the tiler can't advance. Fifteen blocks, macOS's minimum heap. const MIN_FREE_TVB_PAGES: u64 = 0x3c; +/// Free parameter-buffer pages (`0x1c9a8`) of a clustered V25G83 pass: `28 + 16 x clusters` +/// (`0x3c` for two clusters on M4 Pro, `0x5c` for four clusters on M4 Max as macOS 26.6.2 +/// writes it, four pages less than M5's `32 + 16 x clusters`). +const fn v25g83_clustered_free_pages(clusters: u32) -> u64 { + 0x1c + 0x10 * clusters as u64 +} +const _: () = assert!(v25g83_clustered_free_pages(2) == MIN_FREE_TVB_PAGES); /// The 25G83 tiling array: the A18 Pro's without 0x1748 and 0x1740 (and 0x17d9 unless the stage /// has SCS), with the tiler parameter sub-buffer registers and 0x10131 = 0x88, in the order the @@ -748,10 +758,20 @@ fn ta_registers_25g83( push(find(0x1c880, 0)?); push(RegisterWrite::new(0x1c948, gtp(4)?)); push(RegisterWrite::new(0x1c888, gtp(5)?)); - let (segment_control, segment_index) = if args.ta_mode_1 { - (T6041_TA_MODE_1, 0) - } else { - (VDM_SEGMENT_CONTROL, VDM_SEGMENT_INDEX) + let multi = (!args.ta_mode_1 && args.clusters > 2) + .then(|| { + super::m5::target::cluster_control( + args.clusters, + v25g83_clustered_free_pages(args.clusters), + ) + }) + .flatten(); + let (segment_control, segment_index, free_pages) = match (args.ta_mode_1, multi) { + (true, _) => (T6041_TA_MODE_1, 0, MIN_FREE_TVB_PAGES), + // Above two clusters (four-cluster M4 Max: 0x280540 / 4 / 0x5c): segment words from + // cluster_control() with the V25G83 free-page count (28 + 16 x clusters). + (false, Some([control, index, pages])) => (control, index, pages), + (false, None) => (VDM_SEGMENT_CONTROL, VDM_SEGMENT_INDEX, MIN_FREE_TVB_PAGES), }; push(RegisterWrite::new(0x1c890, segment_control)); push(RegisterWrite::new(0x1c918, segment_index)); @@ -761,7 +781,7 @@ fn ta_registers_25g83( push(RegisterWrite::new(0x1c9e0, gtp2)); push(RegisterWrite::new(0x16c41, gtp6)); push(RegisterWrite::new(0x1ca40, gtp6)); - push(RegisterWrite::new(0x1c9a8, MIN_FREE_TVB_PAGES)); + push(RegisterWrite::new(0x1c9a8, free_pages)); push(RegisterWrite::new(0x1c920, gtp(7)?)); for reg in [0x10151, 0x1c199, 0x1c1a1, 0x1c1a9, 0x1c1b1, 0x1c1b9, 0x1c8f8, 0x1c0b1, 0x1c850] { push(find(reg, 0)?); @@ -1753,49 +1773,69 @@ mod ta_mode_tests { } } - /// The variants of the builds T6041 admits: 25F84, then 25G83 and 26B123, each of which the - /// 40- and the 32-core configurations run with the same rules. - fn t6041_variants() -> [&'static Variant; 3] { + /// The variants of the builds T6041 admits: 25F84, 40-core 25G83, 32-core 25G83, and 26B123. + fn t6041_variants() -> [&'static Variant; 4] { let Firmware::Identified(builds) = crate::hw::t6041::CONFIG.firmware else { panic!("T6041 must identify its loaded firmware"); }; assert_eq!(builds.len(), 5); for (full, cut) in [(1, 2), (3, 4)] { let (full, cut) = (builds[full].variant, builds[cut].variant); - assert_eq!(full.ta_mode_1, cut.ta_mode_1); assert_eq!(full.compute, cut.compute); assert_eq!(full.programs, cut.programs); } - [builds[0].variant, builds[1].variant, builds[3].variant] + assert_eq!(builds[3].variant.ta_mode_1, builds[4].variant.ta_mode_1); + [ + builds[0].variant, + builds[1].variant, + builds[2].variant, + builds[3].variant, + ] } - /// The TA mode of every admitted T6041 build. + /// The TA mode of the non-clustered T6041 builds (25F84, 40-core 25G83, and 26B123). fn t6041_ta_mode_1() -> bool { - let [f84, g83, b123] = t6041_variants(); - assert_eq!(f84.ta_mode_1, g83.ta_mode_1); + let [f84, g83_40, _, b123] = t6041_variants(); + assert_eq!(f84.ta_mode_1, g83_40.ta_mode_1); assert_eq!(f84.ta_mode_1, b123.ta_mode_1); f84.ta_mode_1 } #[test] fn policy_is_local_to_the_admitted_t6041_builds() { - let [f84, g83, b123] = t6041_variants(); + let [f84, g83_40, g83_32, b123] = t6041_variants(); let pro = selected(&crate::hw::t6040::CONFIG.firmware); assert_eq!(f84.compute, crate::g17::fw::compute::ComputeProgram::V25F84); assert!(f84.split_firmware_area); // 25G83 keeps the M4 Pro's queue and compute rules on the M4 Max. - assert_eq!(g83.compute, pro.compute); - assert_eq!(g83.split_firmware_area, pro.split_firmware_area); - assert_eq!(g83.opening_record, pro.opening_record); - assert_eq!(g83.qid_floor, pro.qid_floor); - assert_eq!(g83.registration, pro.registration); + for g83 in [g83_40, g83_32] { + assert_eq!(g83.compute, pro.compute); + assert_eq!(g83.split_firmware_area, pro.split_firmware_area); + assert_eq!(g83.opening_record, pro.opening_record); + assert_eq!(g83.qid_floor, pro.qid_floor); + assert_eq!(g83.registration, pro.registration); + } // 26B123 runs 25F84's compute program with one firmware area. assert_eq!(b123.compute, f84.compute); assert!(!b123.split_firmware_area); - for max in [f84, g83, b123] { + for max in [f84, g83_40, g83_32, b123] { assert_eq!(max.programs, RegisterPrograms::V25G83); - assert!(max.ta_mode_1); } + // 25F84 and 40-core 25G83 keep TA mode 1; 32-core 25G83 tiles clustered with a heap that + // may fill the block table. + assert!(f84.ta_mode_1); + assert!(g83_40.ta_mode_1); + assert!(!g83_32.ta_mode_1); + assert_eq!( + g83_32.tvb_normal_blocks, + crate::g17::fw::buffer::NORMAL_MAX_BLOCKS_FOUR_CLUSTERS, + ); + assert_eq!(g83_40.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + assert_eq!(f84.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + assert_eq!(pro.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); + // 26B123 keeps 25F84's TA mode 1 and heap maximum. + assert!(b123.ta_mode_1); + assert_eq!(b123.tvb_normal_blocks, crate::g17::fw::buffer::NORMAL_MAX_BLOCKS); assert!(!pro.ta_mode_1); assert!(!V25F84.ta_mode_1); assert!(!V25G83.ta_mode_1); @@ -1848,6 +1888,7 @@ mod ta_mode_tests { fragment: stage, programs: RegisterPrograms::V25G83, ta_mode_1: false, + clusters: 2, deflake: Deflake::FOUR_CLUSTERS, } } @@ -1892,6 +1933,38 @@ mod ta_mode_tests { } } + #[test] + fn four_clusters_take_the_four_cluster_segment_words() { + let (pass, resources) = fixture(); + let geometry = Geometry::new(&pass).unwrap(); + let words = PassWords::new(&pass).unwrap(); + let find = |a: &[RegisterWrite], reg: u32| a.iter().find(|w| w.reg == reg).map(|w| w.value); + let mut args = args(&pass, &resources, false); + let (two, count) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(find(&two[..count], 0x1c890), Some(VDM_SEGMENT_CONTROL)); + assert_eq!(find(&two[..count], 0x1c918), Some(VDM_SEGMENT_INDEX)); + assert_eq!(find(&two[..count], 0x1c9a8), Some(MIN_FREE_TVB_PAGES)); + args.clusters = 4; + let (four, count4) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count4, count); + assert_eq!(find(&four[..count4], 0x1c890), Some(0x28_0540)); + assert_eq!(find(&four[..count4], 0x1c918), Some(4)); + assert_eq!(find(&four[..count4], 0x1c9a8), Some(0x5c)); + args.clusters = 8; + let (eight, count8) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count8, count); + assert_eq!(find(&eight[..count8], 0x1c890), Some(0x30_0640)); + assert_eq!(find(&eight[..count8], 0x1c918), Some(4)); + assert_eq!(find(&eight[..count8], 0x1c9a8), Some(0x9c)); + // TA mode 1 is unaffected by the cluster count. + args.clusters = 4; + args.ta_mode_1 = true; + let (mode1, count1) = ta_registers_25g83(&args, &geometry, &words).unwrap(); + assert_eq!(count1, count); + assert_eq!(find(&mode1[..count1], 0x1c890), Some(T6041_TA_MODE_1)); + assert_eq!(find(&mode1[..count1], 0x1c9a8), Some(MIN_FREE_TVB_PAGES)); + } + #[test] fn mode_does_not_change_fragment_or_g17p_arrays() { let (pass, resources) = fixture(); diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 3c40fba4aa8c00..2f6ae1846ccab4 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -84,6 +84,9 @@ pub(crate) struct Variant { pub(crate) programs: super::render::RegisterPrograms, /// Use 0x1c890 = 1, 0x1c918 = 0 in V25G83-format tiling arrays (device/build policy). pub(crate) ta_mode_1: bool, + /// The normal maximum of a G17P tiler heap in blocks, which bounds host growth and the + /// firmware's own (device/build policy). + pub(crate) tvb_normal_blocks: usize, pub(crate) compute: super::compute::ComputeProgram, pub(crate) opening_record: bool, pub(crate) split_firmware_area: bool, @@ -159,6 +162,7 @@ pub(crate) const V26A428: Variant = Variant { lead_commands: false, programs: super::render::RegisterPrograms::G17P, ta_mode_1: false, + tvb_normal_blocks: super::buffer::NORMAL_MAX_BLOCKS, compute: super::compute::ComputeProgram::G17P, opening_record: true, split_firmware_area: false, @@ -201,6 +205,7 @@ pub(crate) const V25G83: Variant = Variant { lead_commands: true, programs: super::render::RegisterPrograms::V25G83, ta_mode_1: false, + tvb_normal_blocks: super::buffer::NORMAL_MAX_BLOCKS, compute: super::compute::ComputeProgram::G17P, opening_record: true, split_firmware_area: false, diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 64d3f50a5df9d6..4257f421dafefa 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -612,6 +612,7 @@ impl Pair { }, programs: self.variant.programs, ta_mode_1: self.variant.ta_mode_1, + clusters: self.clusters, deflake: deflake_layout, }; self.memory.graph.claim(ordinal)?; diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index f7698a7e3b0b73..4cc04e2ac23e90 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -603,6 +603,7 @@ impl Memory { buffer_id: buffer_id.0, generation: pm_generation, first_ordinal: ordinal, + normal_blocks: variant.tvb_normal_blocks, }, )?; let predecessor = crate::g17::ids::OBJECTS.object()?; diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 516c5b1a9882f6..35b0aeb34ca601 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -79,9 +79,8 @@ const BUILDS: [fw::variant::Build; 5] = [ ..BUILD_25G83 }, fw::variant::Build { - name: "macOS 26.6.2 (25G83, iBoot mBoot-18000.161.10), 32 cores", config: Some(&super::t6041_25g83::CONFIG), - ..BUILD_25G83 + ..BUILD_25G83_32CORE }, fw::variant::Build { config: Some(&BASE), @@ -141,8 +140,8 @@ const BUILD_25F84: fw::variant::Build = fw::variant::Build { /// The macOS 26.6.2 boot firmware (iBoot mBoot-18000.161.10) loads the 25G83 build the M4 Pro /// runs. iBoot fills part of the loaded TEXT for each Mac, so each admitted image is a -/// measurement. Four are listed: the 32-core J616C's, which runs with -/// [`super::t6041_25g83::CONFIG`], and the 40-core J614C's and J575C's, which run with +/// measurement. Four are listed: the 32-core J616C's, which runs via [`BUILD_25G83_32CORE`] +/// with [`super::t6041_25g83::CONFIG`], and the 40-core J614C's and J575C's, which run with /// [`CONFIG_25G83`]. The J575C's is measured with its boot-filled ranges zeroed, as is the /// J614C's under system firmware 27.2, whose iBoot fills the same ranges. pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { @@ -203,7 +202,8 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { ], }, ], - // Four clusters: the tiler segment values of 25F84 on this machine. + // 40-core T6041 parts (J614C, J575C) stay on TA mode 1 until clustered tiling is tested on + // 40-core hardware; 32-core parts run [`BUILD_25G83_32CORE`] below. // T6041's 25G83 firmware emits pstate reports (tags 0x19/0x1b) and 8 ms // timestamped utilisation records (tag 0x13). variant: &fw::variant::Variant { @@ -217,6 +217,21 @@ pub(super) const BUILD_25G83: fw::variant::Build = fw::variant::Build { config: None, }; +/// 32-core T6041 (J616C) on 25G83: inherits the 25G83 image list (the 32- vs 40-core config +/// is chosen by probed core count) and tiles clustered with the four-cluster segment words +/// (`fw::m5::target::cluster_control`). A clustered RD32 Minecraft frame needs ~1600-2200 heap +/// blocks, past the 0x45e normal maximum, and at that maximum a four-cluster pass never starts +/// (reason 0 recoveries), so the heap may use every slot of the block table. +pub(super) const BUILD_25G83_32CORE: fw::variant::Build = fw::variant::Build { + name: "macOS 26.6.2 (25G83, iBoot mBoot-18000.161.10), 32 cores", + variant: &fw::variant::Variant { + ta_mode_1: false, + tvb_normal_blocks: crate::g17::fw::buffer::NORMAL_MAX_BLOCKS_FOUR_CLUSTERS, + ..*BUILD_25G83.variant + }, + ..BUILD_25G83 +}; + /// The 40-core M4 Max on 25G83: the 25F84 configuration with the 25G83 register map and /// [`CHIP_25G83`]. const CONFIG_25G83: Config = Config { diff --git a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs index 955e45e14d2c3c..6ccd27f2ddc118 100644 --- a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs +++ b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs @@ -47,7 +47,7 @@ pub(super) const CONFIG: Config = Config { perf: Some(&PERF), region_c: Some(®ION_C), chip: Some(&CHIP), - firmware: fw::variant::Firmware::Identified(&[t6041::BUILD_25G83, t6041::BUILD_26B123]), + firmware: fw::variant::Firmware::Identified(&[t6041::BUILD_25G83_32CORE, t6041::BUILD_26B123]), core_layout: CoreLayout { cores: Some((4, 32)), alternate_core_masks: None, From 1c420ea8bacae2ec2a896dc39be8579d9a197052 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 17 Nov 2026 20:54:56 +0000 Subject: [PATCH 0631/1514] drm/asahi: g17: a 16 KiB floor for four-cluster metadata 1 Four-cluster passes size clustering metadata 1 as the M2 Pro/Max path does, 0x44 bytes per block of tiles, with 0x80, the two-cluster M4 Pro size, as the floor. On a 3456x2234 Retina frame (Minecraft RD32) that formula yields 0x100 (32x32 utiles) or 0x180 (16x16), and on 10240x10240 (point_size_10000, 16x16 utiles) it yields 0x1100. Because metadata 1 is the last sub-buffer in the TPC object, neither macOS's allocation size nor the hardware's written high-water mark was visible in the J616C 26.6.2 capture. Give it a conservative 16 KiB floor until measured, document the formula sizes on those frames, and add a KUnit test covering the four-cluster V25G83 metadata layout. (Because this keys on RegisterPrograms::V25G83 && clusters > 2, 25F84 and 26B123 on T6041 also get this conservative floor.) The per-block size stays the M2 Pro/Max formula; the floor is our own choice, not a macOS value. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/buffer/target.rs | 35 +++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g17/buffer/target.rs b/drivers/gpu/drm/asahi/g17/buffer/target.rs index b8c2677cb66481..c17e6c3643f2e6 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/target.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/target.rs @@ -42,6 +42,15 @@ const GTP6_SIZE: usize = GTP_SLOTS /// macOS 26.6.2 on the J616C spaces a clustered pass's metadata 2, 3 and 4 0x1180, 0x1400 /// and 0x1600 apart: metadata 2 needs 0x1180, more than the M2 Pro/Max 0xc00. const GTP_MULTI_CLUSTER_SIZES: [usize; 3] = [0x1180, 0x280 * 16, 0x10 * 128]; +/// Floor for four-cluster metadata 1 (`0x1c920`, `gtp[7]`). +/// +/// The M2 Pro/Max per-block formula yields 0x100 (32x32 utiles) or 0x180 (16x16) on a +/// 3456x2234 Retina frame (Minecraft RD32) and 0x1100 on 10240x10240 (`point_size_10000`, +/// 16x16 utiles). Because metadata 1 is the last sub-buffer in the TPC object, neither +/// macOS's allocation size nor the hardware's written high-water mark was visible in the +/// J616C 26.6.2 capture; keep a conservative 16 KiB floor until a capture or hardware +/// high-water measurement shows the true upper bound. +const META1_MIN_SIZE: usize = 0x4000; const META1_BLOCK_SIZE: usize = 0x44; /// Per-command geometry, independent of the capacity already allocated. @@ -142,7 +151,7 @@ impl Layout { meta1_blocks.checked_mul(META1_BLOCK_SIZE).ok_or(EOVERFLOW)?, 0x80, )? - .max(GTP_FIXED_SIZES[3]), + .max(META1_MIN_SIZE), ] } else { GTP_FIXED_SIZES @@ -507,4 +516,28 @@ mod tests { layout.tpc_end = layout.tpc_size; assert_eq!(layout.tpc_capacity(), Err(ERANGE)); } + + #[test] + fn four_cluster_v25g83_metadata_layout() { + let mut retina = pass(3456, 32); + retina.height = 2234; + for (target, utile) in [(retina, 32), (retina, 16), (pass(10240, 16), 16)] { + let mut p = target; + p.utile_width = utile; + p.utile_height = utile; + let layout = Layout::new(&p, 4, RegisterPrograms::V25G83).unwrap(); + let gtp4 = layout.gtp[4].unwrap(); + let gtp5 = layout.gtp[5].unwrap(); + let gtp6 = layout.gtp[6].unwrap(); + let gtp7 = layout.gtp[7].unwrap(); + assert_eq!(gtp5 - gtp4, GTP_MULTI_CLUSTER_SIZES[0]); + assert!(gtp6 - gtp5 >= GTP_MULTI_CLUSTER_SIZES[1]); + assert!(gtp7 - gtp6 >= GTP_MULTI_CLUSTER_SIZES[2].max(GTP6_SIZE)); + assert_eq!(layout.tpc_end - gtp7, META1_MIN_SIZE); + } + // Two-cluster V25G83 (M4 Pro) keeps its original fixed metadata sizes. + let two = Layout::new(&retina, 2, RegisterPrograms::V25G83).unwrap(); + assert_eq!(two.gtp[5].unwrap() - two.gtp[4].unwrap(), GTP_FIXED_SIZES[0]); + assert_eq!(two.tpc_end - two.gtp[7].unwrap(), GTP_FIXED_SIZES[3]); + } } From b268f4d44615d8d7879eaffa572dce4fa225612a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:06:44 +1100 Subject: [PATCH 0632/1514] soc: apple: support modular regview KUnit tests Build the suite separately so modular KUnit and modular drivers can run the same cases as built-in configurations. Restrict the hooks to the KUnit export namespace and the selected test configuration. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 4 +- drivers/soc/apple/Makefile | 1 + drivers/soc/apple/regview-internal.h | 53 +++++++++++++++++++++++ drivers/soc/apple/regview-test.c | 32 ++++++++------ drivers/soc/apple/regview.c | 65 ++++++++++------------------ 5 files changed, 98 insertions(+), 57 deletions(-) create mode 100644 drivers/soc/apple/regview-internal.h diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 4be538da8ed19f..c42461497da18f 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -343,8 +343,8 @@ config APPLE_REGVIEW This is a development aid. If unsure, say 'n'. config APPLE_REGVIEW_KUNIT_TEST - bool "KUnit tests for the Apple SoC read-only register views" if !KUNIT_ALL_TESTS - depends on APPLE_REGVIEW=y && KUNIT=y + tristate "KUnit tests for the Apple SoC read-only register views" if !KUNIT_ALL_TESTS + depends on APPLE_REGVIEW && KUNIT default KUNIT_ALL_TESTS help Check every built-in register list against the apertures it diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 6ce2050c293e61..9e8f9e02e92e22 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -70,5 +70,6 @@ obj-$(CONFIG_APPLE_CLPC) += clpc.o obj-$(CONFIG_APPLE_REGVIEW) += apple-regview.o apple-regview-y := regview.o +obj-$(CONFIG_APPLE_REGVIEW_KUNIT_TEST) += regview-test.o obj-$(CONFIG_APPLE_AURORA_BOOT_SECURITY) += aurora-boot-security.o diff --git a/drivers/soc/apple/regview-internal.h b/drivers/soc/apple/regview-internal.h new file mode 100644 index 00000000000000..93fa5c1745ab7d --- /dev/null +++ b/drivers/soc/apple/regview-internal.h @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _REGVIEW_INTERNAL_H +#define _REGVIEW_INTERNAL_H + +#include +#include + +/* One run of 32-bit registers inside one DT reg entry. */ +struct apple_regview_range { + u8 reg; /* index into the node's reg property */ + u32 offset; /* byte offset from the start of that entry */ + u32 count; /* number of 32-bit registers */ + u32 stride; /* byte distance between registers; 0 means 4 */ + const char *name; +}; + +struct apple_regview_hw { + const struct apple_regview_range *ranges; + unsigned int nr_ranges; + unsigned int nr_regs; /* reg entries the node must have */ +}; + +struct apple_regview_map { + void __iomem *base; + resource_size_t size; +}; + +struct apple_regview { + struct device *dev; + const struct apple_regview_hw *hw; + struct apple_regview_map *maps; + struct dentry *dir; +}; + +#define MCC_TZ_BASE 0x6a0 +#define MCC_TZ_STRIDE 0x10 +#define MCC_TZ_REGIONS 4 + +#define MCC_PLANE_STRIDE 0x40000 +#define MCC_PLANE_CACHE_STATUS 0x1c04 +#define SPMI_SB_BUS_FAULTS 0x200 +#define SPMI_SB_NR_BUS_FAULTS 10 +#define SPMI_MON_COUNTERS 1 + +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +u32 apple_regview_stride(const struct apple_regview_range *r); +int apple_regview_check(const struct apple_regview *rv); +int apple_regview_show(struct seq_file *s, void *unused); +extern const struct of_device_id apple_regview_of_match[]; +const struct file_operations *apple_regview_test_fops(void); +#endif + +#endif diff --git a/drivers/soc/apple/regview-test.c b/drivers/soc/apple/regview-test.c index 83c2ed9adb830a..e0a61732e092ef 100644 --- a/drivers/soc/apple/regview-test.c +++ b/drivers/soc/apple/regview-test.c @@ -1,7 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* - * KUnit tests for the Apple SoC read-only register views. Included by - * regview.c. + * KUnit tests for the Apple SoC read-only register views. * * The register windows under test are zeroed buffers of kernel memory that * stand in for the mapped DT reg entries of a struct apple_regview. The tests @@ -12,6 +11,8 @@ #include #include +#include "regview-internal.h" + #define REGVIEW_TEST_MAX_REGS 4 #define REGVIEW_TEST_SEQ_SIZE (16 * 1024) @@ -80,7 +81,7 @@ static struct regview_test_ctx *regview_test_setup(struct kunit *test, KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, regview_test_vfree, ctx->buf[i])); - ctx->maps[i].base = (void __iomem *)ctx->buf[i]; + ctx->maps[i].base = (void __iomem __force *)ctx->buf[i]; ctx->maps[i].size = size + extra; } @@ -102,11 +103,11 @@ static void regview_test_fill(struct regview_test_ctx *ctx) unsigned int i; for (i = 0; i < hw->nr_regs; i++) { - u32 *w = ctx->buf[i]; + __le32 *w = ctx->buf[i]; u64 off; for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) - w[off / 4] = regview_test_tag(i, off); + w[off / 4] = cpu_to_le32(regview_test_tag(i, off)); } } @@ -475,11 +476,11 @@ static void regview_test_show_values(struct kunit *test) regview_test_hw("apple,t8112-spmi-sideband"); struct regview_test_ctx *ctx = regview_test_setup(test, hw, 0); const char *want; - u32 *w; + __le32 *w; w = ctx->buf[0]; - w[SPMI_SB_BUS_FAULTS / 4] = 0xffffffff; - w[SPMI_SB_BUS_FAULTS / 4 + 1] = 0x1; + w[SPMI_SB_BUS_FAULTS / 4] = cpu_to_le32(U32_MAX); + w[SPMI_SB_BUS_FAULTS / 4 + 1] = cpu_to_le32(1); regview_test_show(test, ctx); want = "0+0x0000200 bus-fault-count[0]: 0xffffffff\n" @@ -554,12 +555,12 @@ static void regview_test_show_never_writes(struct kunit *test) regview_test_show(test, ctx); for (i = 0; i < ctx->rv.hw->nr_regs; i++) { - u32 *w = ctx->buf[i]; + __le32 *w = ctx->buf[i]; u64 off; u32 guard; for (off = 0; off + 4 <= ctx->maps[i].size; off += 4) - if (w[off / 4] != regview_test_tag(i, off)) + if (le32_to_cpu(w[off / 4]) != regview_test_tag(i, off)) break; KUNIT_EXPECT_EQ_MSG(test, off, (u64)ctx->maps[i].size, "%s reg %u", id->compatible, i); @@ -572,9 +573,11 @@ static void regview_test_show_never_writes(struct kunit *test) /* The debugfs file has no write method. */ static void regview_test_fops_read_only(struct kunit *test) { - KUNIT_EXPECT_NULL(test, apple_regview_fops.write); - KUNIT_EXPECT_NULL(test, apple_regview_fops.write_iter); - KUNIT_EXPECT_NOT_NULL(test, apple_regview_fops.read); + const struct file_operations *fops = apple_regview_test_fops(); + + KUNIT_EXPECT_NULL(test, fops->write); + KUNIT_EXPECT_NULL(test, fops->write_iter); + KUNIT_EXPECT_NOT_NULL(test, fops->read); } static struct kunit_case regview_test_cases[] = { @@ -606,3 +609,6 @@ static struct kunit_suite regview_test_suite = { }; kunit_test_suite(regview_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/soc/apple/regview.c b/drivers/soc/apple/regview.c index fb741ceb1c0ee8..09302eb0f78edf 100644 --- a/drivers/soc/apple/regview.c +++ b/drivers/soc/apple/regview.c @@ -31,41 +31,17 @@ #include #include -/* One run of 32-bit registers inside one DT reg entry. */ -struct apple_regview_range { - u8 reg; /* index into the node's reg property */ - u32 offset; /* byte offset from the start of that entry */ - u32 count; /* number of 32-bit registers */ - u32 stride; /* byte distance between registers; 0 means 4 */ - const char *name; -}; - -struct apple_regview_hw { - const struct apple_regview_range *ranges; - unsigned int nr_ranges; - unsigned int nr_regs; /* reg entries the node must have */ -}; +#include "regview-internal.h" -struct apple_regview_map { - void __iomem *base; - resource_size_t size; -}; +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif static struct dentry *apple_regview_root; -struct apple_regview { - struct device *dev; - const struct apple_regview_hw *hw; - struct apple_regview_map *maps; - struct dentry *dir; -}; - -#define MCC_PLANE_STRIDE 0x40000 -#define MCC_PLANE_CACHE_STATUS 0x1c04 -#define MCC_TZ_BASE 0x6a0 -#define MCC_TZ_STRIDE 0x10 -#define MCC_TZ_REGIONS 4 - /* * Plane 0 carveout start, end and enable of each region, then the cache * status of each plane. @@ -107,8 +83,6 @@ static const struct apple_regview_hw apple_regview_t6000_mcc_hw = { * collisions) followed by seven queue and filter fault counters. Only the * counters are listed; how they wrap is not part of the interface. */ -#define SPMI_SB_BUS_FAULTS 0x200 -#define SPMI_SB_NR_BUS_FAULTS 10 #define SPMI_SB_QUEUE_FAULTS 0x25c #define SPMI_SB_NR_QUEUE_FAULTS 7 @@ -133,7 +107,6 @@ static const struct apple_regview_hw apple_regview_t8112_spmi_sb_hw = { * have no known meaning and are not read. reg[0] holds the fault queue, whose * data port pops an entry on every read, so nothing in reg[0] is listed. */ -#define SPMI_MON_COUNTERS 1 #define SPMI_MON_BUS_FAULTS 0x00 #define SPMI_MON_NR_BUS_FAULTS 3 #define SPMI_MON_PROTO_FAULTS 0x10 @@ -156,12 +129,13 @@ static const struct apple_regview_hw apple_regview_t6000_spmi_mon_hw = { .nr_regs = 2, }; -static u32 apple_regview_stride(const struct apple_regview_range *r) +VISIBLE_IF_KUNIT u32 apple_regview_stride(const struct apple_regview_range *r) { return r->stride ? r->stride : 4; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_stride); -static int apple_regview_check(const struct apple_regview *rv) +VISIBLE_IF_KUNIT int apple_regview_check(const struct apple_regview *rv) { const struct apple_regview_hw *hw = rv->hw; unsigned int i; @@ -179,8 +153,9 @@ static int apple_regview_check(const struct apple_regview *rv) return 0; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_check); -static int apple_regview_show(struct seq_file *s, void *unused) +VISIBLE_IF_KUNIT int apple_regview_show(struct seq_file *s, void *unused) { struct apple_regview *rv = s->private; const struct apple_regview_hw *hw = rv->hw; @@ -202,8 +177,17 @@ static int apple_regview_show(struct seq_file *s, void *unused) return 0; } +EXPORT_SYMBOL_IF_KUNIT(apple_regview_show); DEFINE_SHOW_ATTRIBUTE(apple_regview); +#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) +const struct file_operations *apple_regview_test_fops(void) +{ + return &apple_regview_fops; +} +EXPORT_SYMBOL_IF_KUNIT(apple_regview_test_fops); +#endif + static void apple_regview_remove_debugfs(void *data) { debugfs_remove_recursive(data); @@ -260,7 +244,7 @@ static int apple_regview_probe(struct platform_device *pdev) rv->dir); } -static const struct of_device_id apple_regview_of_match[] = { +VISIBLE_IF_KUNIT const struct of_device_id apple_regview_of_match[] = { { .compatible = "apple,t8112-mcc", .data = &apple_regview_t8112_mcc_hw }, { .compatible = "apple,t6000-mcc", .data = &apple_regview_t6000_mcc_hw }, { .compatible = "apple,t8112-spmi-sideband", @@ -269,6 +253,7 @@ static const struct of_device_id apple_regview_of_match[] = { .data = &apple_regview_t6000_spmi_mon_hw }, {} }; +EXPORT_SYMBOL_IF_KUNIT(apple_regview_of_match); MODULE_DEVICE_TABLE(of, apple_regview_of_match); static struct platform_driver apple_regview_driver = { @@ -300,7 +285,3 @@ module_exit(apple_regview_exit); MODULE_DESCRIPTION("Apple SoC read-only register views"); MODULE_LICENSE("Dual MIT/GPL"); - -#if IS_ENABLED(CONFIG_APPLE_REGVIEW_KUNIT_TEST) -#include "regview-test.c" -#endif From 397a8d96d8cad82c1d4f8659e55b5d96037db69d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:06:45 +1100 Subject: [PATCH 0633/1514] soc: apple: support modular dbgview KUnit tests Build the suite separately so modular KUnit and modular drivers can run the same cases as built-in configurations. Restrict the hooks to the KUnit export namespace and the selected test configuration. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 4 +-- drivers/soc/apple/Makefile | 1 + drivers/soc/apple/dbgview-internal.h | 23 ++++++++++++++++ drivers/soc/apple/dbgview-test.c | 40 ++++++++++++++++++++-------- drivers/soc/apple/dbgview.c | 37 +++++++++++++++---------- 5 files changed, 78 insertions(+), 27 deletions(-) create mode 100644 drivers/soc/apple/dbgview-internal.h diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 7f6828532e7bca..9db29d21ab0964 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -26,8 +26,8 @@ config APPLE_DBGVIEW Say m here if you debug an Apple SoC. config APPLE_DBGVIEW_KUNIT_TEST - bool "KUnit tests for the Apple SoC debug register views" if !KUNIT_ALL_TESTS - depends on APPLE_DBGVIEW=y && KUNIT=y && PM + tristate "KUnit tests for the Apple SoC debug register views" if !KUNIT_ALL_TESTS + depends on APPLE_DBGVIEW && KUNIT && PM default KUNIT_ALL_TESTS help Read the regs and snapshot views of a register block that the diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 6ce2050c293e61..6694337c7f2720 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -4,6 +4,7 @@ obj-$(CONFIG_APPLE_J613_DISPLAY_SYNC) += j613-display.o obj-$(CONFIG_APPLE_DBGVIEW) += apple-dbgview.o apple-dbgview-y = dbgview.o +obj-$(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) += dbgview-test.o obj-$(CONFIG_APPLE_DOCKCHANNEL) += apple-dockchannel.o apple-dockchannel-y = dockchannel.o diff --git a/drivers/soc/apple/dbgview-internal.h b/drivers/soc/apple/dbgview-internal.h new file mode 100644 index 00000000000000..ff7ac30da309ff --- /dev/null +++ b/drivers/soc/apple/dbgview-internal.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _DBGVIEW_INTERNAL_H +#define _DBGVIEW_INTERNAL_H + +#include +#include + +struct dbgview { + struct device *dev; + void __iomem *base; + resource_size_t size; + struct dentry *dir; +}; + +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, + size_t count, loff_t *ppos); +int dbgview_snapshot(struct seq_file *s, unsigned int bytes); +extern const struct file_operations dbgview_regs_fops; +const struct file_operations *dbgview_test_snapshot_fops(void); +#endif + +#endif diff --git a/drivers/soc/apple/dbgview-test.c b/drivers/soc/apple/dbgview-test.c index 6b85e7cae3e937..213b1328742deb 100644 --- a/drivers/soc/apple/dbgview-test.c +++ b/drivers/soc/apple/dbgview-test.c @@ -1,7 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* - * KUnit tests for the Apple SoC read-only debug register views. Included by - * dbgview.c. + * KUnit tests for the Apple SoC read-only debug register views. * * The view under test is a struct dbgview whose register block is a buffer * of kernel memory and whose device is a KUnit device with runtime PM and no @@ -13,17 +12,21 @@ #include #include #include +#include +#include #include #include +#include "dbgview-internal.h" + #define DBGVIEW_TEST_USER_SIZE (3 * PAGE_SIZE) #define DBGVIEW_TEST_SEQ_SIZE (8 * 1024) struct dbgview_test_ctx { struct dbgview dv; struct file file; - u32 *regs; - u32 *copy; + __le32 *regs; + __le32 *copy; char __user *ubuf; u8 *kbuf; char *seq_buf; @@ -59,11 +62,11 @@ static struct dbgview_test_ctx *dbgview_test_setup(struct kunit *test, ctx->copy = kunit_kzalloc(test, size + 4, GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, ctx->copy); for (i = 0; i < size / 4 + 1; i++) - ctx->regs[i] = dbgview_test_word(i); + ctx->regs[i] = cpu_to_le32(dbgview_test_word(i)); memcpy(ctx->copy, ctx->regs, size + 4); ctx->dv.dev = dev; - ctx->dv.base = (void __iomem *)ctx->regs; + ctx->dv.base = (void __iomem __force *)ctx->regs; ctx->dv.size = size; ctx->file.private_data = &ctx->dv; @@ -107,12 +110,22 @@ static int dbgview_test_usage(struct dbgview_test_ctx *ctx) } /* Bytes [0, len) of the user buffer are the registers from @pos on. */ +static void dbgview_test_compare_words(struct kunit *test, const u8 *buf, + size_t pos, size_t len) +{ + const u32 *words = (const u32 *)buf; + size_t i; + + for (i = 0; i < len / 4; i++) + KUNIT_EXPECT_EQ(test, words[i], dbgview_test_word(pos / 4 + i)); +} + static void dbgview_test_expect_words(struct kunit *test, struct dbgview_test_ctx *ctx, loff_t pos, size_t len) { dbgview_test_fetch_user(test, ctx); - KUNIT_EXPECT_MEMEQ(test, ctx->kbuf, (u8 *)ctx->regs + pos, len); + dbgview_test_compare_words(test, ctx->kbuf, pos, len); /* nothing past the returned length was written */ KUNIT_EXPECT_EQ(test, ctx->kbuf[len], 0xee); } @@ -236,7 +249,7 @@ static void dbgview_test_read_sequential(struct kunit *test) } KUNIT_EXPECT_EQ(test, ret, 0); KUNIT_EXPECT_EQ(test, pos, size); - KUNIT_EXPECT_MEMEQ(test, all, (u8 *)ctx->regs, size); + dbgview_test_compare_words(test, all, 0, size); } /* Every read takes and drops one runtime PM reference. */ @@ -341,7 +354,7 @@ static void dbgview_test_snapshot_format(struct kunit *test) KUNIT_ASSERT_EQ(test, dbgview_test_snapshot(test, ctx, 0x40), 0); - KUNIT_EXPECT_EQ(test, dbgview_test_lines(ctx->seq_buf), 16 + 3); + KUNIT_ASSERT_EQ(test, dbgview_test_lines(ctx->seq_buf), 16 + 3); n = sscanf(ctx->seq_buf, "cntvct_before %16llx\n", &before); KUNIT_ASSERT_EQ(test, n, 1); KUNIT_EXPECT_EQ(test, ctx->seq_buf[strlen("cntvct_before ") + 16], '\n'); @@ -420,11 +433,13 @@ static void dbgview_test_snapshot_rpm_error(struct kunit *test) /* Neither file has a write method. */ static void dbgview_test_fops_read_only(struct kunit *test) { + const struct file_operations *snapshot = dbgview_test_snapshot_fops(); + KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write); KUNIT_EXPECT_NULL(test, dbgview_regs_fops.write_iter); KUNIT_EXPECT_TRUE(test, dbgview_regs_fops.read == dbgview_regs_read); - KUNIT_EXPECT_NULL(test, dbgview_snapshot_fops.write); - KUNIT_EXPECT_NULL(test, dbgview_snapshot_fops.write_iter); + KUNIT_EXPECT_NULL(test, snapshot->write); + KUNIT_EXPECT_NULL(test, snapshot->write_iter); } static struct kunit_case dbgview_test_cases[] = { @@ -453,3 +468,6 @@ static struct kunit_suite dbgview_test_suite = { }; kunit_test_suite(dbgview_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/soc/apple/dbgview.c b/drivers/soc/apple/dbgview.c index 9f60ce7ccc5c5b..17047858ae1b58 100644 --- a/drivers/soc/apple/dbgview.c +++ b/drivers/soc/apple/dbgview.c @@ -31,17 +31,19 @@ #include +#include "dbgview-internal.h" + +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif + static unsigned int snap_bytes = 0x40; module_param(snap_bytes, uint, 0444); MODULE_PARM_DESC(snap_bytes, "Bytes of an MMIO view read by its snapshot file"); -struct dbgview { - struct device *dev; - void __iomem *base; - resource_size_t size; - struct dentry *dir; -}; - static struct dentry *dbgview_root; static u64 dbgview_cntvct(void) @@ -49,7 +51,7 @@ static u64 dbgview_cntvct(void) return __arch_counter_get_cntvct_stable(); } -static ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, +VISIBLE_IF_KUNIT ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { struct dbgview *dv = file->private_data; @@ -91,15 +93,17 @@ static ssize_t dbgview_regs_read(struct file *file, char __user *ubuf, *ppos = pos + len; return len; } +EXPORT_SYMBOL_IF_KUNIT(dbgview_regs_read); -static const struct file_operations dbgview_regs_fops = { +VISIBLE_IF_KUNIT const struct file_operations dbgview_regs_fops = { .owner = THIS_MODULE, .open = simple_open, .read = dbgview_regs_read, .llseek = default_llseek, }; +EXPORT_SYMBOL_IF_KUNIT(dbgview_regs_fops); -static int dbgview_snapshot(struct seq_file *s, unsigned int bytes) +VISIBLE_IF_KUNIT int dbgview_snapshot(struct seq_file *s, unsigned int bytes) { struct dbgview *dv = s->private; size_t words = min_t(size_t, bytes, dv->size) / 4; @@ -138,12 +142,21 @@ static int dbgview_snapshot(struct seq_file *s, unsigned int bytes) kfree(val); return 0; } +EXPORT_SYMBOL_IF_KUNIT(dbgview_snapshot); static int dbgview_snapshot_show(struct seq_file *s, void *unused) { return dbgview_snapshot(s, snap_bytes); } DEFINE_SHOW_ATTRIBUTE(dbgview_snapshot); +#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) +const struct file_operations *dbgview_test_snapshot_fops(void) +{ + return &dbgview_snapshot_fops; +} +EXPORT_SYMBOL_IF_KUNIT(dbgview_test_snapshot_fops); +#endif + static int dbgview_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -225,7 +238,3 @@ module_exit(dbgview_exit); MODULE_AUTHOR("Ryan Murray <81541646+RyanTheTide@users.noreply.github.com>"); MODULE_DESCRIPTION("Apple SoC read-only debug register views"); MODULE_LICENSE("Dual MIT/GPL"); - -#if IS_ENABLED(CONFIG_APPLE_DBGVIEW_KUNIT_TEST) -#include "dbgview-test.c" -#endif From 36bbec8e4b513e597ab670a234cda10ff1977209 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:06:46 +1100 Subject: [PATCH 0634/1514] EDAC/apple: support modular KUnit tests Build the suite separately so modular KUnit and modular drivers can run the same cases as built-in configurations. Restrict the hooks to the KUnit export namespace and the selected test configuration. Signed-off-by: Ryan Murray --- drivers/edac/Kconfig | 4 +- drivers/edac/Makefile | 1 + drivers/edac/apple_soc_edac-internal.h | 89 +++++++++++++ drivers/edac/apple_soc_edac-test.c | 173 +++++++++++++++++-------- drivers/edac/apple_soc_edac.c | 101 ++++----------- 5 files changed, 237 insertions(+), 131 deletions(-) create mode 100644 drivers/edac/apple_soc_edac-internal.h diff --git a/drivers/edac/Kconfig b/drivers/edac/Kconfig index 81739f3f61f3ce..633d8c3859ddb4 100644 --- a/drivers/edac/Kconfig +++ b/drivers/edac/Kconfig @@ -583,8 +583,8 @@ config EDAC_APPLE_SOC without status is masked. config EDAC_APPLE_SOC_KUNIT_TEST - bool "KUnit tests for Apple SoC error reporting" if !KUNIT_ALL_TESTS - depends on EDAC_APPLE_SOC=y && KUNIT=y + tristate "KUnit tests for Apple SoC error reporting" if !KUNIT_ALL_TESTS + depends on EDAC_APPLE_SOC && KUNIT default KUNIT_ALL_TESTS help Build KUnit tests for the Apple SoC error reporting driver: the diff --git a/drivers/edac/Makefile b/drivers/edac/Makefile index 2cd51f0046b0e1..553f5fd3caf4cb 100644 --- a/drivers/edac/Makefile +++ b/drivers/edac/Makefile @@ -92,3 +92,4 @@ obj-$(CONFIG_EDAC_LOONGSON) += loongson_edac.o obj-$(CONFIG_EDAC_VERSALNET) += versalnet_edac.o obj-$(CONFIG_EDAC_CORTEX_A72) += a72_edac.o obj-$(CONFIG_EDAC_APPLE_SOC) += apple_soc_edac.o +obj-$(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) += apple_soc_edac-test.o diff --git a/drivers/edac/apple_soc_edac-internal.h b/drivers/edac/apple_soc_edac-internal.h new file mode 100644 index 00000000000000..489cae0394f6f3 --- /dev/null +++ b/drivers/edac/apple_soc_edac-internal.h @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +#ifndef _APPLE_SOC_EDAC_INTERNAL_H +#define _APPLE_SOC_EDAC_INTERNAL_H + +#include +#include +#include + +#define APPLE_SOC_EDAC_NAME "apple_soc_edac" + +/* + * The sources' status registers have no established acknowledge contract, + * so a line is masked when it fires and unmasked again after a backoff. + * A line still asserted after APPLE_SOC_EDAC_MAX_RETRIES backoffs stays + * masked; its count keeps the record. + */ +#define APPLE_SOC_EDAC_BACKOFF_MS 1000 +#define APPLE_SOC_EDAC_BACKOFF_MAX_MS 60000 +#define APPLE_SOC_EDAC_MAX_RETRIES 8 + +#define T6041_NI_REGS 25 +#define T6041_NI_STATUS 0x416c + +struct apple_soc_edac_range { + u8 first; + u8 count; + const char *name; +}; + +/* + * A fabric NI whose error status sits in its aperture: a block of status words, + * one per error type, whose set bits name the port. They're acknowledged by + * writing the set bits back. + */ +struct apple_soc_edac_ni { + u8 index; /* interrupt index */ + u8 reg; /* reg index of the NI's aperture */ + u16 status; /* offset of the first status word */ + u32 words; /* bit n: a status word at status + 4 * n */ +}; + +struct apple_soc_edac_hw { + const struct apple_soc_edac_range *ranges; + size_t nranges; + const struct apple_soc_edac_ni *ni; + size_t nni; + unsigned int num_irqs; + unsigned int num_status_regs; + bool event_log; +}; + +struct apple_soc_edac; + +struct apple_soc_edac_irq { + struct apple_soc_edac *edac; + const char *source; + unsigned int index; + int irq; + const struct apple_soc_edac_ni *ni; + void __iomem *ni_base; + unsigned int retries; + unsigned int backoff_ms; + unsigned long armed_jiffies; + struct delayed_work rearm; +}; + +struct apple_soc_edac { + struct device *dev; + struct edac_device_ctl_info *dci; + const struct apple_soc_edac_hw *hw; + struct apple_soc_edac_irq *irqs; + void __iomem **status_regs; +}; + +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, + unsigned int index); +u32 apple_soc_edac_read(void __iomem *reg); +void apple_soc_edac_write(void __iomem *reg, u32 val); +bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, + bool *error, bool *cleared); +bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, + bool *cleared); +void apple_soc_edac_rearm(struct work_struct *work); +irqreturn_t apple_soc_edac_irq_thread(int irq, void *data); +extern const struct of_device_id apple_soc_edac_of_match[]; +#endif + +#endif diff --git a/drivers/edac/apple_soc_edac-test.c b/drivers/edac/apple_soc_edac-test.c index 56e8e7b730b13b..165325873c1a08 100644 --- a/drivers/edac/apple_soc_edac-test.c +++ b/drivers/edac/apple_soc_edac-test.c @@ -15,6 +15,9 @@ #include #include +#include "edac_module.h" +#include "apple_soc_edac-internal.h" + #define EDAC_TEST_WORDS 64 /* Not a valid interrupt: the IRQ core ignores masks and unmasks of it. */ #define EDAC_TEST_IRQ INT_MAX @@ -126,7 +129,7 @@ static struct edac_test_ctx *edac_test_line(struct kunit *test, /* T6041 line 45 + n reads its status word at fake word n. */ for (i = 0; i < T6041_NI_REGS; i++) ctx->status_regs[i] = (void __iomem __force *) - ((u8 *)&ctx->fake.regs[i] - T6041_NI_STATUS); + ((uintptr_t)&ctx->fake.regs[i] - T6041_NI_STATUS); if (hw->num_status_regs) ctx->edac.status_regs = ctx->status_regs; @@ -148,7 +151,7 @@ static struct edac_test_ctx *edac_test_line(struct kunit *test, continue; irq_data->ni = &hw->ni[i]; irq_data->ni_base = (void __iomem __force *) - ((u8 *)ctx->fake.regs - hw->ni[i].status); + ((uintptr_t)ctx->fake.regs - hw->ni[i].status); } return ctx; @@ -182,8 +185,8 @@ static unsigned long edac_test_fire(struct kunit *test, cancel_delayed_work_sync(&irq_data->rearm); delay = msecs_to_jiffies(expect_backoff_ms); KUNIT_EXPECT_NE(test, 0U, expect_backoff_ms); - KUNIT_EXPECT_GE(test, expires - before, delay); - KUNIT_EXPECT_LE(test, expires - after, delay); + KUNIT_EXPECT_TRUE(test, time_after_eq(expires, before + delay)); + KUNIT_EXPECT_TRUE(test, time_before_eq(expires, after + delay)); return expires - before; } @@ -205,14 +208,33 @@ static int edac_test_init(struct kunit *test) return 0; } -static const struct apple_soc_edac_hw *const edac_test_error_hws[] = { - &t6000_error_hw, &t6041_error_hw, &t8112_error_hw, &t8140_error_hw, +static const char *const edac_test_error_compatibles[] = { + "apple,t6000-error-handler", + "apple,t6041-error-handler", "apple,t8112-error-handler", + "apple,t8140-error-handler", }; -static const struct apple_soc_edac_hw *const edac_test_event_hws[] = { - &t6000_event_hw, &t6041_event_hw, &t8112_event_hw, &t8140_event_hw, +static const char *const edac_test_event_compatibles[] = { + "apple,t6000-event-log", + "apple,t6041-event-log", "apple,t8112-event-log", + "apple,t8140-event-log", }; +static const struct apple_soc_edac_hw *edac_test_hw(struct kunit *test, + const char *compatible) +{ + const struct of_device_id *id; + + for (id = apple_soc_edac_of_match; id->compatible[0]; id++) + if (!strcmp(id->compatible, compatible)) { + KUNIT_ASSERT_NOT_NULL(test, id->data); + return id->data; + } + + KUNIT_FAIL_AND_ABORT(test, "no match data for %s", compatible); + return NULL; +} + static void edac_test_expect_source(struct kunit *test, const struct apple_soc_edac_hw *hw, unsigned int index, const char *expect) @@ -243,11 +265,12 @@ static void edac_test_source_t6041(struct kunit *test) { 70, NULL }, { 88, NULL }, { 89, NULL }, { 255, NULL }, { UINT_MAX, NULL }, }; + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); unsigned int i; for (i = 0; i < ARRAY_SIZE(cases); i++) - edac_test_expect_source(test, &t6041_error_hw, cases[i].index, - cases[i].name); + edac_test_expect_source(test, hw, cases[i].index, cases[i].name); } /* Range edges of every SoC: first and last line in, neighbours per table. */ @@ -255,8 +278,9 @@ static void edac_test_source_edges(struct kunit *test) { unsigned int h, r, i, claimed; - for (h = 0; h < ARRAY_SIZE(edac_test_error_hws); h++) { - const struct apple_soc_edac_hw *hw = edac_test_error_hws[h]; + for (h = 0; h < ARRAY_SIZE(edac_test_error_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_error_compatibles[h]); claimed = 0; for (i = 0; i < hw->num_irqs; i++) @@ -282,8 +306,9 @@ static void edac_test_tables(struct kunit *test) { unsigned int h, r, end; - for (h = 0; h < ARRAY_SIZE(edac_test_error_hws); h++) { - const struct apple_soc_edac_hw *hw = edac_test_error_hws[h]; + for (h = 0; h < ARRAY_SIZE(edac_test_error_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_error_compatibles[h]); KUNIT_EXPECT_FALSE(test, hw->event_log); KUNIT_EXPECT_GT(test, hw->nranges, (size_t)0); @@ -301,17 +326,21 @@ static void edac_test_tables(struct kunit *test) } } - for (h = 0; h < ARRAY_SIZE(edac_test_event_hws); h++) { - KUNIT_EXPECT_TRUE(test, edac_test_event_hws[h]->event_log); - KUNIT_EXPECT_EQ(test, edac_test_event_hws[h]->nranges, (size_t)0); - KUNIT_EXPECT_EQ(test, edac_test_event_hws[h]->nni, (size_t)0); + for (h = 0; h < ARRAY_SIZE(edac_test_event_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_event_compatibles[h]); + + KUNIT_EXPECT_TRUE(test, hw->event_log); + KUNIT_EXPECT_EQ(test, hw->nranges, (size_t)0); + KUNIT_EXPECT_EQ(test, hw->nni, (size_t)0); } } /* T6041: exactly the NI lines 45-69 own one status aperture each. */ static void edac_test_t6041_status_lines(struct kunit *test) { - const struct apple_soc_edac_hw *hw = &t6041_error_hw; + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); unsigned int i; KUNIT_EXPECT_EQ(test, hw->num_status_regs, T6041_NI_REGS); @@ -328,7 +357,8 @@ static void edac_test_t6041_status_lines(struct kunit *test) /* T8140 NI blocks sit on claimed NI lines with a valid aperture and words. */ static void edac_test_t8140_ni_table(struct kunit *test) { - const struct apple_soc_edac_hw *hw = &t8140_error_hw; + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); unsigned int i, j; KUNIT_EXPECT_EQ(test, hw->nni, (size_t)6); @@ -357,8 +387,9 @@ static void edac_test_event_log_source(struct kunit *test) { unsigned int h; - for (h = 0; h < ARRAY_SIZE(edac_test_event_hws); h++) { - const struct apple_soc_edac_hw *hw = edac_test_event_hws[h]; + for (h = 0; h < ARRAY_SIZE(edac_test_event_compatibles); h++) { + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, edac_test_event_compatibles[h]); edac_test_expect_source(test, hw, 0, "event-log"); edac_test_expect_source(test, hw, hw->num_irqs - 1, "event-log"); @@ -393,7 +424,9 @@ static bool edac_test_t6041(struct edac_test_ctx *ctx, bool *error, /* A T6041 NI word that reads zero is left alone. */ static void edac_test_t6041_status_zero(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 50); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 50); bool error = true, cleared = false; KUNIT_EXPECT_FALSE(test, edac_test_t6041(ctx, &error, &cleared)); @@ -407,7 +440,9 @@ static void edac_test_t6041_status_zero(struct kunit *test) /* Each bit is acknowledged; only bits 0-2 and 4-7 are platform errors. */ static void edac_test_t6041_status_mask(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 45); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 45); unsigned int bit; bool error, cleared; @@ -433,7 +468,9 @@ static void edac_test_t6041_status_mask(struct kunit *test) /* A word that reads back set after the acknowledge is reported. */ static void edac_test_t6041_status_sticky(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 60); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 60); bool error, cleared; ctx->fake.regs[15] = 0x11; @@ -449,7 +486,9 @@ static void edac_test_t6041_status_sticky(struct kunit *test) /* Line 45 + n uses aperture n, and lines outside 45-69 touch none. */ static void edac_test_t6041_status_index(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 45); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 45); static const unsigned int outside[] = { 0, 9, 26, 44, 70, 88 }; bool error, cleared; unsigned int i; @@ -481,7 +520,9 @@ static void edac_test_t6041_status_index(struct kunit *test) static void edac_test_ni_status_words(struct kunit *test) { /* SoC NI 0: 0x1ffd7ff */ - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 18); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 18); unsigned int bit; bool cleared = false; @@ -507,7 +548,9 @@ static void edac_test_ni_status_words(struct kunit *test) /* No word set: nothing found and nothing written. */ static void edac_test_ni_status_none(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 22); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 22); bool cleared = false; KUNIT_ASSERT_NOT_NULL(test, ctx->irq.ni); @@ -521,7 +564,9 @@ static void edac_test_ni_status_none(struct kunit *test) /* One word of several staying set makes the NI not cleared. */ static void edac_test_ni_status_sticky(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 23); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 23); bool cleared = true; /* GFX NI: 0x3ff7ff, so words 0 and 21 are both in the mask. */ @@ -540,12 +585,14 @@ static void edac_test_ni_status_sticky(struct kunit *test) static void edac_test_ni_status_top_word(struct kunit *test) { static const struct apple_soc_edac_ni ni = { 18, 9, 0x100, BIT(31) }; - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 18); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 18); bool cleared; ctx->irq.ni = ∋ ctx->irq.ni_base = (void __iomem __force *) - ((u8 *)ctx->fake.regs - ni.status); + ((uintptr_t)ctx->fake.regs - ni.status); ctx->fake.regs[31] = 0xffffffff; ctx->fake.regs[30] = 0x1; KUNIT_EXPECT_TRUE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); @@ -555,9 +602,9 @@ static void edac_test_ni_status_top_word(struct kunit *test) KUNIT_EXPECT_EQ(test, ctx->fake.reads, 2U); /* Word 11 is outside SoC NI 0's mask. */ - ctx->irq.ni = &t8140_ni[0]; + ctx->irq.ni = &ctx->edac.hw->ni[0]; ctx->irq.ni_base = (void __iomem __force *) - ((u8 *)ctx->fake.regs - t8140_ni[0].status); + ((uintptr_t)ctx->fake.regs - ctx->edac.hw->ni[0].status); ctx->fake.regs[30] = 0; ctx->fake.regs[11] = 0x1; KUNIT_EXPECT_FALSE(test, apple_soc_edac_ni_status(&ctx->irq, &cleared)); @@ -568,7 +615,9 @@ static void edac_test_ni_status_top_word(struct kunit *test) /* T6041 NI error acknowledged: one UE, the line stays unmasked. */ static void edac_test_irq_t6041_error(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 47); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 47); ctx->fake.regs[2] = 0x4; KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); @@ -580,7 +629,9 @@ static void edac_test_irq_t6041_error(struct kunit *test) /* Bit 3 alone is acknowledged without an error count. */ static void edac_test_irq_t6041_bit3(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 69); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 69); ctx->fake.regs[24] = BIT(3); KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); @@ -591,7 +642,9 @@ static void edac_test_irq_t6041_bit3(struct kunit *test) /* An NI line with no status set is masked and backed off, not counted. */ static void edac_test_irq_t6041_empty(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 56); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 56); edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); @@ -602,7 +655,9 @@ static void edac_test_irq_t6041_empty(struct kunit *test) /* An acknowledge that does not take counts once and backs off. */ static void edac_test_irq_t6041_sticky(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6041_error_hw, 64); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6041-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 64); ctx->fake.regs[19] = 0x1; ctx->fake.sticky[19] = 0x1; @@ -615,36 +670,39 @@ static void edac_test_irq_t6041_sticky(struct kunit *test) static void edac_test_irq_no_status(struct kunit *test) { static const struct { - const struct apple_soc_edac_hw *hw; + const char *compatible; unsigned int index; } lines[] = { - { &t6041_error_hw, 3 }, /* sep */ - { &t6041_error_hw, 27 }, /* sram */ - { &t6000_error_hw, 33 }, /* ni0, no status on T6000 */ - { &t8112_error_hw, 2 }, /* sep */ - { &t8140_error_hw, 24 }, /* nsi */ - { &t6000_event_hw, 0 }, - { &t8140_event_hw, 8 }, + { "apple,t6041-error-handler", 3 }, /* sep */ + { "apple,t6041-error-handler", 27 }, /* sram */ + { "apple,t6000-error-handler", 33 }, /* ni0, no status on T6000 */ + { "apple,t8112-error-handler", 2 }, /* sep */ + { "apple,t8140-error-handler", 24 }, /* nsi */ + { "apple,t6000-event-log", 0 }, + { "apple,t8140-event-log", 8 }, }; unsigned int i; for (i = 0; i < ARRAY_SIZE(lines); i++) { + const struct apple_soc_edac_hw *hw; struct edac_test_ctx *ctx; - ctx = edac_test_line(test, lines[i].hw, lines[i].index); + hw = edac_test_hw(test, lines[i].compatible); + ctx = edac_test_line(test, hw, lines[i].index); KUNIT_EXPECT_NULL(test, ctx->irq.ni); edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); KUNIT_EXPECT_EQ_MSG(test, edac_test_ue(ctx), 1U, "line %u", i); KUNIT_EXPECT_EQ(test, ctx->fake.reads, 0U); KUNIT_EXPECT_EQ(test, ctx->fake.writes, 0U); - cancel_delayed_work_sync(&ctx->irq.rearm); } } /* T8140 NI: acknowledged status is one UE without a mask. */ static void edac_test_irq_ni_error(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 21); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 21); ctx->fake.regs[24] = 0x100; KUNIT_EXPECT_EQ(test, edac_test_fire(test, ctx, 0), 0UL); @@ -656,7 +714,9 @@ static void edac_test_irq_ni_error(struct kunit *test) /* T8140 NI asserted with no status: masked, no UE. Sticky: UE once + mask. */ static void edac_test_irq_ni_empty_sticky(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t8140_error_hw, 19); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8140-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 19); edac_test_fire(test, ctx, APPLE_SOC_EDAC_BACKOFF_MS); KUNIT_EXPECT_EQ(test, edac_test_ue(ctx), 0U); @@ -672,7 +732,9 @@ static void edac_test_irq_ni_empty_sticky(struct kunit *test) /* The backoff doubles to its cap; after the retry limit the line stays off. */ static void edac_test_irq_backoff_limit(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6000_error_hw, 0); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6000-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 0); unsigned int i, expect = APPLE_SOC_EDAC_BACKOFF_MS; for (i = 0; i < APPLE_SOC_EDAC_MAX_RETRIES; i++) { @@ -693,7 +755,9 @@ static void edac_test_irq_backoff_limit(struct kunit *test) /* A line that stayed quiet for a minute after its unmask starts over. */ static void edac_test_irq_backoff_reset(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t8112_error_hw, 1); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t8112-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 1); ctx->irq.retries = APPLE_SOC_EDAC_MAX_RETRIES + 1; ctx->irq.backoff_ms = APPLE_SOC_EDAC_BACKOFF_MAX_MS; @@ -713,7 +777,9 @@ static void edac_test_irq_backoff_reset(struct kunit *test) /* The rearm work unmasks and restarts the quiet-period clock. */ static void edac_test_rearm(struct kunit *test) { - struct edac_test_ctx *ctx = edac_test_line(test, &t6000_error_hw, 12); + const struct apple_soc_edac_hw *hw = + edac_test_hw(test, "apple,t6000-error-handler"); + struct edac_test_ctx *ctx = edac_test_line(test, hw, 12); unsigned long before; ctx->irq.armed_jiffies = jiffies - 10 * HZ; @@ -759,3 +825,6 @@ static struct kunit_suite apple_soc_edac_test_suite = { }; kunit_test_suite(apple_soc_edac_test_suite); + +MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); +MODULE_LICENSE("GPL"); diff --git a/drivers/edac/apple_soc_edac.c b/drivers/edac/apple_soc_edac.c index 311357066ccc21..bd48da07615cf8 100644 --- a/drivers/edac/apple_soc_edac.c +++ b/drivers/edac/apple_soc_edac.c @@ -19,71 +19,14 @@ #include "edac_module.h" -#define APPLE_SOC_EDAC_NAME "apple_soc_edac" +#include "apple_soc_edac-internal.h" -/* - * The sources' status registers have no established acknowledge contract, - * so a line is masked when it fires and unmasked again after a backoff. - * A line still asserted after APPLE_SOC_EDAC_MAX_RETRIES backoffs stays - * masked; its count keeps the record. - */ -#define APPLE_SOC_EDAC_BACKOFF_MS 1000 -#define APPLE_SOC_EDAC_BACKOFF_MAX_MS 60000 -#define APPLE_SOC_EDAC_MAX_RETRIES 8 - -#define T6041_NI_REGS 25 -#define T6041_NI_STATUS 0x416c - -struct apple_soc_edac_range { - u8 first; - u8 count; - const char *name; -}; - -/* - * A fabric NI whose error status sits in its aperture: a block of status words, - * one per error type, whose set bits name the port. They're acknowledged by - * writing the set bits back. - */ -struct apple_soc_edac_ni { - u8 index; /* interrupt index */ - u8 reg; /* reg index of the NI's aperture */ - u16 status; /* offset of the first status word */ - u32 words; /* bit n: a status word at status + 4 * n */ -}; - -struct apple_soc_edac_hw { - const struct apple_soc_edac_range *ranges; - size_t nranges; - const struct apple_soc_edac_ni *ni; - size_t nni; - unsigned int num_irqs; - unsigned int num_status_regs; - bool event_log; -}; - -struct apple_soc_edac; - -struct apple_soc_edac_irq { - struct apple_soc_edac *edac; - const char *source; - unsigned int index; - int irq; - const struct apple_soc_edac_ni *ni; - void __iomem *ni_base; - unsigned int retries; - unsigned int backoff_ms; - unsigned long armed_jiffies; - struct delayed_work rearm; -}; - -struct apple_soc_edac { - struct device *dev; - struct edac_device_ctl_info *dci; - const struct apple_soc_edac_hw *hw; - struct apple_soc_edac_irq *irqs; - void __iomem **status_regs; -}; +#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) +#include +#else +#define VISIBLE_IF_KUNIT static +#define EXPORT_SYMBOL_IF_KUNIT(symbol) +#endif /* * DCS IRQs drive a separate thermal loop and are intentionally omitted. @@ -203,8 +146,8 @@ static const struct apple_soc_edac_hw t8140_event_hw = { .event_log = true, }; -static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, - unsigned int index) +VISIBLE_IF_KUNIT const char * +apple_soc_edac_source(const struct apple_soc_edac_hw *hw, unsigned int index) { size_t i; @@ -220,30 +163,33 @@ static const char *apple_soc_edac_source(const struct apple_soc_edac_hw *hw, return NULL; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_source); /* Status register accessors; KUnit redirects them to a fake register block. */ -static u32 apple_soc_edac_read(void __iomem *reg) +VISIBLE_IF_KUNIT u32 apple_soc_edac_read(void __iomem *reg) { #if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_read, reg); #endif return readl(reg); } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_read); -static void apple_soc_edac_write(void __iomem *reg, u32 val) +VISIBLE_IF_KUNIT void apple_soc_edac_write(void __iomem *reg, u32 val) { #if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) KUNIT_STATIC_STUB_REDIRECT(apple_soc_edac_write, reg, val); #endif writel(val, reg); } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_write); /* * Read and acknowledge a T6041 NI status word. Returns whether it was set; * @error says whether a bit in the platform error policy was set and * @cleared whether the word reads back clear after the acknowledge. */ -static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, +VISIBLE_IF_KUNIT bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, bool *error, bool *cleared) { struct apple_soc_edac *edac = irq_data->edac; @@ -276,12 +222,13 @@ static bool apple_soc_edac_t6041_status(struct apple_soc_edac_irq *irq_data, return false; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_t6041_status); /* * Log and acknowledge an NI's set status words. Returns whether any was set; * @cleared says whether all of them read back clear. */ -static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, +VISIBLE_IF_KUNIT bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, bool *cleared) { const struct apple_soc_edac_ni *ni = irq_data->ni; @@ -308,8 +255,9 @@ static bool apple_soc_edac_ni_status(struct apple_soc_edac_irq *irq_data, return found; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_ni_status); -static void apple_soc_edac_rearm(struct work_struct *work) +VISIBLE_IF_KUNIT void apple_soc_edac_rearm(struct work_struct *work) { struct apple_soc_edac_irq *irq_data = container_of(to_delayed_work(work), struct apple_soc_edac_irq, @@ -318,8 +266,9 @@ static void apple_soc_edac_rearm(struct work_struct *work) irq_data->armed_jiffies = jiffies; enable_irq(irq_data->irq); } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_rearm); -static irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) +VISIBLE_IF_KUNIT irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) { struct apple_soc_edac_irq *irq_data = data; struct apple_soc_edac *edac = irq_data->edac; @@ -391,6 +340,7 @@ static irqreturn_t apple_soc_edac_irq_thread(int irq, void *data) return IRQ_HANDLED; } +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_irq_thread); static int apple_soc_edac_map_ni(struct platform_device *pdev, struct apple_soc_edac_irq *irq_data) @@ -535,7 +485,7 @@ static void apple_soc_edac_remove(struct platform_device *pdev) edac_device_free_ctl_info(edac->dci); } -static const struct of_device_id apple_soc_edac_of_match[] = { +VISIBLE_IF_KUNIT const struct of_device_id apple_soc_edac_of_match[] = { { .compatible = "apple,t6000-error-handler", .data = &t6000_error_hw }, { .compatible = "apple,t6041-error-handler", .data = &t6041_error_hw }, { .compatible = "apple,t8112-error-handler", .data = &t8112_error_hw }, @@ -546,6 +496,7 @@ static const struct of_device_id apple_soc_edac_of_match[] = { { .compatible = "apple,t8140-event-log", .data = &t8140_event_hw }, { } }; +EXPORT_SYMBOL_IF_KUNIT(apple_soc_edac_of_match); MODULE_DEVICE_TABLE(of, apple_soc_edac_of_match); static struct platform_driver apple_soc_edac_driver = { @@ -561,7 +512,3 @@ module_platform_driver(apple_soc_edac_driver); MODULE_AUTHOR("The Aurora Silicon Contributors"); MODULE_DESCRIPTION("Apple SoC platform error reporting driver"); MODULE_LICENSE("GPL"); - -#if IS_ENABLED(CONFIG_EDAC_APPLE_SOC_KUNIT_TEST) -#include "apple_soc_edac-test.c" -#endif From 48b7191062ea66c05643a991fe92aaeed323f5cf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:14:09 +1100 Subject: [PATCH 0635/1514] drm/apple: dcp: keep the display DART dark while DPMS has its domains off On a DCP that is power-cycled for DPMS (hw.s2r), DPMS off stops the firmware and lowers DISP_CPU, DISP_FE and DISP_SYS. The display DART, which maps every framebuffer, goes off with them. It was only marked dark (maps and unmaps to memory only, invalidations held until power-on) when the firmware's D572 reported 0 at the stop. The M4 MacBook Air's firmware (27.2) reports 1 there, so the DART stayed lit: the first unmap after DPMS off, e.g. a compositor freeing a framebuffer, wrote its TLB registers with the domain off, and the SoC reset with nothing logged. A runtime notch switch shows it every time: the compositor frees the old geometry's buffers some seconds after the switch, so a DPMS cycle in that window, or a switch while the display is off, reset the Mac. Mark the display DART dark before the domains go off, as the external DCP's power-off already does, and lit again as soon as the warm restart has them back up, which runs the held invalidations. Where D572(0) did mark it dark, the first call is a no-op; D572(1) at power-on still lights it as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 8f347c6c217df6..339d207c0d5ff0 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -8961,6 +8961,15 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) if (ret) goto out; + /* + * The display DART goes off with these domains, and every framebuffer is mapped + * into it: an unmap while they are off, a client freeing a buffer after DPMS off, + * would reach its registers and reset the SoC. The firmware's D572 does not say + * so on every firmware (27.2 reports 1 at the stop). Dark until the domains are + * back, as for an external DCP. + */ + if (dcp->s2r_disp_dart) + apple_dart_power_dark(dcp->s2r_disp_dart, true); if (pmc) dcp_pmc_set(dcp, pmc, false); val = readl(ps + l->disp_cpu); @@ -9270,6 +9279,9 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) ret = dcp_s2r_domains_on(dcp); if (ret) return ret; + /* Powered again: the invalidations held while it was dark run now. */ + if (dcp->s2r_disp_dart) + apple_dart_power_dark(dcp->s2r_disp_dart, false); /* After the domains, whose writes it would reject, the DART protects them again. */ if (dcp->s2r_dcp_dart) From 8a92c87c0f560eea0af33bcec764b747a996114f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:15:45 +1100 Subject: [PATCH 0636/1514] drm/asahi: bound GEM_USERPTR pins by the GPU memory limits, not RLIMIT_MEMLOCK GEM_USERPTR refused a range that would take the caller's pinned_vm past RLIMIT_MEMLOCK unless it had CAP_IPC_LOCK. The default limit is 8 MiB (systemd's DefaultLimitMEMLOCK), so VK_EXT_external_memory_host could import only small buffers. Geekbench 6 Vulkan imports a 90.7 MiB host buffer; the import failed with ENOMEM, Vulkan returned VK_ERROR_OUT_OF_DEVICE_MEMORY and the benchmark aborted on every default install. The pages of a user-memory object and the backing of a GEM_CREATE object are the same kind of memory: unevictable, held for the GPU until the object is freed. GEM_CREATE is bounded only by the client and device limits of the GPU memory ledger, and gem_userptr() already admits the user-memory object's size into that ledger. The memlock check bounded the same memory a second time, at a far lower level, and only for one of the two ways to get it. A process that may not import a buffer may still allocate one of the same size and copy into it. Other DRM drivers that pin user memory for buffer objects (i915, etnaviv) do not charge RLIMIT_MEMLOCK either; amdgpu and xe do not pin. Drop the check. The pages are still added to the mm's pinned_vm, so VmPin in /proc//status shows them and other long-term pinners keep counting them against their own limits. The UAPI comment says so, and the selftest's memlock_limit case becomes memlock_does_not_bound: it pins 64 pages with a soft limit of 0 and without CAP_IPC_LOCK. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gem.rs | 54 +++---------- include/uapi/drm/asahi_drm.h | 10 +-- .../drivers/gpu/asahi-userptr/userptr.c | 78 ++++--------------- 3 files changed, 32 insertions(+), 110 deletions(-) diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index bad222981a6aef..9980d5f16136b1 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -451,7 +451,14 @@ pub(crate) fn new_user_memory_object( } /// Pages of the calling process pinned as the backing of a user-memory object, and counted in its -/// mm's `pinned_vm` against RLIMIT_MEMLOCK. +/// mm's `pinned_vm`. +/// +/// RLIMIT_MEMLOCK does not bound them. The object is charged to the GPU memory limits instead +/// (`memacct`, by `gem_userptr()`), as an object of GEM_CREATE is: both kinds of backing are +/// unevictable pages that the GPU holds, so the limits bound one as well as the other, and an +/// application can choose either. GPU drivers that pin user memory for buffer objects (i915, +/// etnaviv) do not charge RLIMIT_MEMLOCK either. Its default of 8 MiB would leave +/// VK_EXT_external_memory_host unusable for buffers of ordinary size. pub(crate) struct UserPages { pages: KVVec<*mut kernel::bindings::page>, writable: bool, @@ -481,9 +488,9 @@ impl UserPages { /// be pinned: unmapped, a device or PFN mapping, or a writable pin of a mapping that is not /// writable or whose filesystem tracks writes (`FOLL_LONGTERM` refuses those). In a process /// whose page size is smaller than the native one, a native page is accepted only where the - /// process maps all of it, in order at consecutive addresses (`EFAULT` otherwise). Fails with - /// `ENOMEM` when the pages would take the process past RLIMIT_MEMLOCK without CAP_IPC_LOCK, - /// counting every page pinned this way or by other long-term pinners. + /// process maps all of it, in order at consecutive addresses (`EFAULT` otherwise). The pages + /// are added to the mm's `pinned_vm`, which other long-term pinners compare with + /// RLIMIT_MEMLOCK; this one does not (see [`UserPages`]). /// /// Anonymous pages pinned here stay with this process across fork(): the child gets copies. /// Pages unmapped by the process stay pinned, and backing the object, until it is freed. @@ -498,18 +505,8 @@ impl UserPages { .mm() .map(|mm| ARef::from(&**mm)) .ok_or(EFAULT)?; - let pinned_vm = Self::pinned_vm(&mm); let added = i64::try_from(count).map_err(|_| ENOMEM)?; - let total = pinned_vm - .fetch_add(added, Ordering::AcqRel) - .saturating_add(added); - if !memlock_allows(total, memlock_limit_pages()) { - // SAFETY: `capable()` has no preconditions. - if !unsafe { kernel::bindings::capable(kernel::bindings::CAP_IPC_LOCK as i32) } { - pinned_vm.fetch_sub(added, Ordering::AcqRel); - return Err(ENOMEM); - } - } + Self::pinned_vm(&mm).fetch_add(added, Ordering::AcqRel); // From here on, dropping `this` unpins what it holds and uncounts all `count` pages. let mut this = Self { pages: KVVec::new(), @@ -602,24 +599,6 @@ impl Drop for UserPages { } } -/// RLIMIT_MEMLOCK of the calling process, in pages. -fn memlock_limit_pages() -> u64 { - let task = kernel::current!().as_ptr(); - // SAFETY: The current task and its signal structure are live; the limit is read once, as - // `rlimit()` does. - let bytes = unsafe { - core::ptr::read_volatile(core::ptr::addr_of!( - (*(*task).signal).rlim[kernel::bindings::RLIMIT_MEMLOCK as usize].rlim_cur - )) - }; - (bytes >> kernel::page::PAGE_SHIFT) as u64 -} - -/// Whether `pinned` pages stay within a memlock limit of `limit` pages. -fn memlock_allows(pinned: i64, limit: u64) -> bool { - u64::try_from(pinned).is_ok_and(|pinned| pinned <= limit) -} - #[vtable] impl DriverObject for AsahiObject { type Driver = AsahiDrmDriver; @@ -871,15 +850,6 @@ mod user_memory_tests { }) } - #[test] - fn memlock_limit_policy() { - assert!(memlock_allows(0, 0)); - assert!(memlock_allows(512, 512)); - assert!(!memlock_allows(513, 512)); - assert!(!memlock_allows(-1, 512)); - assert!(memlock_allows(i64::MAX, u64::MAX)); - } - #[test] fn pins_anonymous_memory() -> Result { let addr = map(4 * PAGE_SIZE, PROT_READ | PROT_WRITE)?; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 95ff9a15ffdb29..697444f43924f3 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -774,12 +774,12 @@ struct drm_asahi_gem_create { * object stays the parent's memory. The CPU and GPU views are coherent * without cache maintenance. * - * The pinned pages count against the caller's RLIMIT_MEMLOCK, together with - * its other long-term pins, unless it has CAP_IPC_LOCK (ENOMEM otherwise), - * and their size against the client and device limits of + * The size of the object counts against the client and device limits of * drm_asahi_params_global::client_memory_limit and - * drm_asahi_params_global::memory_limit (ENOMEM). They are never released by - * memory-pressure reclaim. + * drm_asahi_params_global::memory_limit (ENOMEM), as that of a + * DRM_IOCTL_ASAHI_GEM_CREATE object does. The pinned pages are shown in the + * caller's VmPin (mm->pinned_vm) but are not limited by its RLIMIT_MEMLOCK. + * They are never released by memory-pressure reclaim. * * Without DRM_ASAHI_GEM_USERPTR_READ_ONLY, the whole range must be mapped * writable, and not be a shared mapping of a file whose filesystem tracks diff --git a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c index abb5ba2f5402cd..542aea41be5a62 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c +++ b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c @@ -3,9 +3,7 @@ * DRM_IOCTL_ASAHI_GEM_USERPTR on the GPU's render node: what it accepts and * refuses, and the accounting (VmPin in /proc/self/status, the client's * drm-total-system in its fdinfo). No GPU work is submitted. Skipped where - * the render node is not this driver's or lacks the feature, and where the - * caller has neither CAP_IPC_LOCK nor a RLIMIT_MEMLOCK hard limit with room - * for the four pages a test pins. + * the render node is not this driver's or lacks the feature. */ #include #include @@ -147,38 +145,9 @@ static int drop_cap_ipc_lock(void) return syscall(SYS_capset, &header, data) ? -errno : 0; } -/* The largest range a test binds, and the most one pins outside memlock_limit. */ +/* The largest range a test binds. */ #define BIND_MAX (4 * PAGE) -/* - * Whether this process may pin BIND_MAX more: it has CAP_IPC_LOCK, or - * RLIMIT_MEMLOCK has room for it, after raising the soft limit to the hard - * one if that takes it. - */ -static int memlock_room(void) -{ - struct __user_cap_header_struct header = { - .version = _LINUX_CAPABILITY_VERSION_3, - }; - struct __user_cap_data_struct data[_LINUX_CAPABILITY_U32S_3]; - long pin = vm_pin_kb(); - uint64_t need = (pin > 0 ? (uint64_t)pin << 10 : 0) + BIND_MAX; - struct rlimit lim; - - if (!syscall(SYS_capget, &header, data) && - (data[CAP_TO_INDEX(CAP_IPC_LOCK)].effective & - CAP_TO_MASK(CAP_IPC_LOCK))) - return 1; - if (getrlimit(RLIMIT_MEMLOCK, &lim)) - return 0; - if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= need) - return 1; - if (lim.rlim_max != RLIM_INFINITY && lim.rlim_max < need) - return 0; - lim.rlim_cur = lim.rlim_max; - return !setrlimit(RLIMIT_MEMLOCK, &lim); -} - /* * A GPU address at which BIND_MAX bytes can be bound. The driver keeps * ranges of every VM for its own mappings, where a bind fails with EINVAL, @@ -221,9 +190,6 @@ FIXTURE_SETUP(asahi) ASSERT_EQ(0, ioc(self->fd, DRM_IOCTL_ASAHI_GET_PARAMS, &get)); if (!(self->params.features & DRM_ASAHI_FEATURE_USERPTR)) SKIP(return, "no DRM_ASAHI_FEATURE_USERPTR"); - if (!memlock_room()) - SKIP(return, "RLIMIT_MEMLOCK has no room for the %lu bytes a test pins", - BIND_MAX); uint64_t kernel = self->params.vm_kernel_min_size > (32ULL << 30) ? self->params.vm_kernel_min_size : 32ULL << 30; @@ -360,48 +326,34 @@ TEST_F(asahi, read_only_file_pages) } /* - * RLIMIT_MEMLOCK bounds the pages of a caller without CAP_IPC_LOCK. The test - * gives the capability up first (the harness runs each test in a process of - * its own), so a request above the limit has to fail whoever runs it. It - * lowers the soft limit to what the process has pinned already plus 16 pages, - * or as many as the hard limit has room for, and is skipped where that is - * less than two. + * RLIMIT_MEMLOCK does not bound the pages: the GPU memory limits do, as for + * GEM_CREATE objects. The test gives CAP_IPC_LOCK up first (the harness runs + * each test in a process of its own) and lowers the soft limit to 0, so a + * memlock check would refuse whoever runs it. The pages still show in VmPin. */ -TEST_F(asahi, memlock_limit) +TEST_F(asahi, memlock_does_not_bound) { + const uint64_t size = 64 * PAGE; struct rlimit old, lim; long pin0 = vm_pin_kb(); - uint64_t pinned = pin0 > 0 ? (uint64_t)pin0 << 10 : 0; - uint64_t pages = 16, size; + long long total0 = client_total(self->fd); uint32_t h = 0; void *mem; ASSERT_EQ(0, drop_cap_ipc_lock()); ASSERT_EQ(0, getrlimit(RLIMIT_MEMLOCK, &old)); - if (old.rlim_max != RLIM_INFINITY) { - uint64_t room = old.rlim_max > pinned ? - (old.rlim_max - pinned) / PAGE : 0; - - if (room < pages) - pages = room; - } - if (pages < 2) - SKIP(return, "no room for two pages in the RLIMIT_MEMLOCK hard limit of %llu bytes", - (unsigned long long)old.rlim_max); - size = 4 * pages * PAGE; mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, mem); - lim.rlim_cur = pinned + pages * PAGE; + lim.rlim_cur = 0; lim.rlim_max = old.rlim_max; ASSERT_EQ(0, setrlimit(RLIMIT_MEMLOCK, &lim)); - ASSERT_EQ(-ENOMEM, userptr(self->fd, mem, size, 0, 0, &h)); - EXPECT_EQ(pin0, vm_pin_kb()); - EXPECT_EQ(0, userptr(self->fd, mem, pages / 2 * PAGE, 0, 0, &h)); - /* The pages already pinned count against the limit too. */ - EXPECT_EQ(-ENOMEM, userptr(self->fd, (char *)mem + pages / 2 * PAGE, - pages * PAGE, 0, 0, &h)); + ASSERT_EQ(0, userptr(self->fd, mem, size, 0, 0, &h)); + EXPECT_EQ(pin0 + (long)(size >> 10), vm_pin_kb()); + EXPECT_EQ(total0 + (long long)size, client_total(self->fd)); close_handle(self->fd, h); + EXPECT_EQ(pin0, vm_pin_kb()); + EXPECT_EQ(total0, client_total(self->fd)); setrlimit(RLIMIT_MEMLOCK, &old); munmap(mem, size); } From 702847ba24921e9b4ccd9d5bd2a09dc17caeea35 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 20:43:40 +1100 Subject: [PATCH 0637/1514] accel/ane: refuse a fault drain at an occupied scratch IOVA A scratch page inside an unmapped buffer shares the buffer reservation. Check the active scratch pages before reserving or mapping another page so repeated faults take the existing recovery path. Document that an address fault handled separately by the IOMMU can leave the SUBMIT return status unchanged. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane.h | 5 ++-- drivers/accel/ane/ane_dart.c | 23 +++++++++------ drivers/accel/ane/ane_drv_test.c | 50 ++++++++++++++++++++------------ drivers/accel/ane/ane_tm.c | 3 +- include/uapi/drm/ane_accel.h | 9 +++--- 5 files changed, 54 insertions(+), 36 deletions(-) diff --git a/drivers/accel/ane/ane.h b/drivers/accel/ane/ane.h index eb614547ddebdb..b6d1ad449d5b13 100644 --- a/drivers/accel/ane/ane.h +++ b/drivers/accel/ane/ane.h @@ -260,7 +260,7 @@ static inline bool ane_tm_failure_recoverable(bool tm_retention, u64 ane_bo_iova_size(u32 npages, unsigned int shift); int ane_bo_check_size(u64 size, u64 iova_span); struct page *ane_dart_alloc_scratch_page(void); -int ane_dart_scratch_slot(struct drm_mm *mm, u64 iova, u64 size, +int ane_dart_scratch_slot(struct ane_device *ane, u64 iova, u64 size, struct drm_mm_node **host); int ane_submit_check_sizes(const struct drm_ane_submit *args, size_t cmd_size, size_t btsp_size); @@ -288,8 +288,7 @@ int ane_dart_init(struct ane_device *ane); void ane_dart_mask(struct ane_device *ane); void ane_dart_unmask(struct ane_device *ane); bool ane_dart_faulted(struct ane_device *ane, u64 *iova, u32 *status); -int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, - struct ane_dart_scratch *scratch, int *pages); +int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova); void ane_dart_release_scratch(struct ane_device *ane, struct ane_dart_scratch *scratch, int pages); bool ane_dart_scratch_in(struct ane_device *ane, struct drm_mm_node *host); diff --git a/drivers/accel/ane/ane_dart.c b/drivers/accel/ane/ane_dart.c index 152c8a1368b1ff..47957fc6d8bf37 100644 --- a/drivers/accel/ane/ane_dart.c +++ b/drivers/accel/ane/ane_dart.c @@ -198,14 +198,19 @@ EXPORT_SYMBOL_IF_KUNIT(ane_dart_alloc_scratch_page); * * Callers hold iommu_lock. */ -VISIBLE_IF_KUNIT int ane_dart_scratch_slot(struct drm_mm *mm, u64 iova, +VISIBLE_IF_KUNIT int ane_dart_scratch_slot(struct ane_device *ane, u64 iova, u64 size, struct drm_mm_node **host) { + struct drm_mm *mm = &ane->mm; struct drm_mm_node *node; *host = NULL; if (iova + size < iova) return -EINVAL; + /* A drain in an unmapped BO has no separate drm_mm node. */ + for (int i = 0; i < ane->scratch_pages; i++) + if (ane->scratch[i].iova == iova) + return -EBUSY; drm_mm_for_each_node_in_range(node, mm, iova, iova + size) { /* Past the end of the range that the allocator manages. */ if (node == &mm->head_node) @@ -250,9 +255,9 @@ EXPORT_SYMBOL_IF_KUNIT(ane_dart_scratch_in); * * Callers hold engine_lock, which keeps the BOs' DART state still. */ -int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, - struct ane_dart_scratch *scratch, int *pages) +int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova) { + struct ane_dart_scratch *scratch; struct drm_mm_node *node = NULL, *host; struct page *page; u64 iova; @@ -265,7 +270,7 @@ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, iova = fault_iova & ~((1ULL << ane->shift) - 1); mutex_lock(&ane->iommu_lock); - ret = ane_dart_scratch_slot(&ane->mm, iova, BIT(ane->shift), &host); + ret = ane_dart_scratch_slot(ane, iova, BIT(ane->shift), &host); if (ret) goto refuse; if (!host) { @@ -296,11 +301,11 @@ int ane_dart_drain_fault(struct ane_device *ane, u64 fault_iova, mutex_unlock(&ane->iommu_lock); dev_dbg(ane->dev, "fault drain: page at %#llx in %s\n", iova, host ? "an unmapped buffer's range" : "a hole"); - scratch[*pages].iova = iova; - scratch[*pages].page = page; - scratch[*pages].node = node; - scratch[*pages].host = host; - (*pages)++; + scratch = &ane->scratch[ane->scratch_pages++]; + scratch->iova = iova; + scratch->page = page; + scratch->node = node; + scratch->host = host; for (i = 0; i < ane->dart_count; i++) ane_dart_invalidate(ane, &ane->darts[i]); return 0; diff --git a/drivers/accel/ane/ane_drv_test.c b/drivers/accel/ane/ane_drv_test.c index 5065c94379e073..c2e0876ab45035 100644 --- a/drivers/accel/ane/ane_drv_test.c +++ b/drivers/accel/ane/ane_drv_test.c @@ -265,47 +265,61 @@ static struct drm_mm_node *ane_test_node(struct kunit *test, struct drm_mm *mm, static void ane_dart_scratch_slot_test(struct kunit *test) { + struct ane_device *ane = kunit_kzalloc(test, sizeof(*ane), GFP_KERNEL); struct drm_mm_node *job, *next, *other, *scratch, *kept, *host; - struct drm_mm mm; + struct drm_mm *mm; + + KUNIT_ASSERT_NOT_NULL(test, ane); + mm = &ane->mm; /* One page above zero up to 64 pages. */ - drm_mm_init(&mm, ANE_TEST_PG, 63 * ANE_TEST_PG); - job = ane_test_node(test, &mm, 1, 4, ANE_MM_BO_MAPPED); - next = ane_test_node(test, &mm, 5, 3, ANE_MM_BO_UNMAPPED); - other = ane_test_node(test, &mm, 8, 2, ANE_MM_BO_UNMAPPED); - scratch = ane_test_node(test, &mm, 12, 1, ANE_MM_SCRATCH); - kept = ane_test_node(test, &mm, 13, 2, ANE_MM_PRESERVED); + drm_mm_init(mm, ANE_TEST_PG, 63 * ANE_TEST_PG); + job = ane_test_node(test, mm, 1, 4, ANE_MM_BO_MAPPED); + next = ane_test_node(test, mm, 5, 3, ANE_MM_BO_UNMAPPED); + other = ane_test_node(test, mm, 8, 2, ANE_MM_BO_UNMAPPED); + scratch = ane_test_node(test, mm, 12, 1, ANE_MM_SCRATCH); + kept = ane_test_node(test, mm, 13, 2, ANE_MM_PRESERVED); /* Past the end of the job's buffer: the packed neighbour. */ - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 5 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 5 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); KUNIT_EXPECT_PTR_EQ(test, host, next); /* Inside and at the last page of a buffer the job does not name. */ - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 6 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 6 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); KUNIT_EXPECT_PTR_EQ(test, host, next); - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 9 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 9 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); KUNIT_EXPECT_PTR_EQ(test, host, other); + /* An unmapped BO can host multiple drains at distinct IOVAs. */ + ane->scratch[0].iova = 5 * ANE_TEST_PG; + ane->scratch[0].host = next; + ane->scratch_pages = 1; + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 5 * ANE_TEST_PG, + ANE_TEST_PG, &host), -EBUSY); + KUNIT_EXPECT_NULL(test, host); + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 6 * ANE_TEST_PG, + ANE_TEST_PG, &host), 0); + KUNIT_EXPECT_PTR_EQ(test, host, next); /* A hole: the drain reserves its own node. */ - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 10 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 10 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); KUNIT_EXPECT_NULL(test, host); - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 40 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 40 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); KUNIT_EXPECT_NULL(test, host); /* Ranges with PTEs cannot take a drain page. */ - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 4 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 4 * ANE_TEST_PG, ANE_TEST_PG, &host), -EBUSY); - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 12 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 12 * ANE_TEST_PG, ANE_TEST_PG, &host), -EBUSY); - KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(&mm, 14 * ANE_TEST_PG, + KUNIT_EXPECT_EQ(test, ane_dart_scratch_slot(ane, 14 * ANE_TEST_PG, ANE_TEST_PG, &host), -EBUSY); KUNIT_EXPECT_NULL(test, host); /* Past the end of the allocator range. */ - KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(&mm, 64 * ANE_TEST_PG, + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(ane, 64 * ANE_TEST_PG, ANE_TEST_PG, &host), 0); - KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(&mm, U64_MAX & ~(u64)(ANE_TEST_PG - 1), + KUNIT_EXPECT_NE(test, ane_dart_scratch_slot(ane, U64_MAX & ~(u64)(ANE_TEST_PG - 1), ANE_TEST_PG, &host), 0); drm_mm_remove_node(job); @@ -313,7 +327,7 @@ static void ane_dart_scratch_slot_test(struct kunit *test) drm_mm_remove_node(other); drm_mm_remove_node(scratch); drm_mm_remove_node(kept); - drm_mm_takedown(&mm); + drm_mm_takedown(mm); } /* diff --git a/drivers/accel/ane/ane_tm.c b/drivers/accel/ane/ane_tm.c index 609a6e650b7626..0175a18f0a79ae 100644 --- a/drivers/accel/ane/ane_tm.c +++ b/drivers/accel/ane/ane_tm.c @@ -465,8 +465,7 @@ int ane_tm_execute(struct ane_device *ane, struct ane_request *req) err = -EIO; break; } - err = ane_dart_drain_fault(ane, fault_iova, scratch, - &ane->scratch_pages); + err = ane_dart_drain_fault(ane, fault_iova); if (err) break; /* The retried transaction now completes; poll on. */ diff --git a/include/uapi/drm/ane_accel.h b/include/uapi/drm/ane_accel.h index 584551aac81daa..69974af244f1e9 100644 --- a/include/uapi/drm/ane_accel.h +++ b/include/uapi/drm/ane_accel.h @@ -158,10 +158,11 @@ struct drm_ane_bo_free { * * A successful SUBMIT returns after the engine completed the work, with the * output buffers visible to the CPU. While it runs, the engine reaches only - * the buffers in @handles and @btsp_handle: an access outside them faults - * and fails the SUBMIT. The buffers are put into the device address space - * by the SUBMIT that names them, not by BO_INIT, so a SUBMIT can also fail - * with -ENOMEM when there is no memory to map them. + * the buffers in @handles and @btsp_handle. The driver reports an error + * if it handles an address fault. On devices where the IOMMU handles the + * fault separately, SUBMIT may still return success. The buffers are put + * into the device address space by the SUBMIT that names them. A SUBMIT + * can also fail with -ENOMEM when there is no memory to map them. */ struct drm_ane_submit { __u64 tsk_size; From e826551b910f0f2ae6d5ded4da1ade68ae9fc796 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:09:12 +1100 Subject: [PATCH 0638/1514] selftests/ane: match the drain signature of the revision under test Select the matching mock declaration for the current and historical revisions so the historical control fails its runtime assertions. Signed-off-by: Ryan Murray --- tools/asahi/ane-tm-transient-fault-tests.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tools/asahi/ane-tm-transient-fault-tests.py b/tools/asahi/ane-tm-transient-fault-tests.py index d095abcb1471c7..0ae1d6c896f15e 100755 --- a/tools/asahi/ane-tm-transient-fault-tests.py +++ b/tools/asahi/ane-tm-transient-fault-tests.py @@ -101,13 +101,18 @@ static void ane_dart_mask(struct ane_device *ane) { (void)ane; } static void ane_dart_unmask(struct ane_device *ane) { (void)ane; } static void ane_tm_push_tq(struct ane_device *ane, struct ane_request *req) { (void)ane; (void)req; } -static int ane_dart_drain_fault(struct ane_device *ane, u64 iova, struct ane_dart_scratch *s, int *pages) +#ifdef ANE_DRAIN_TAKES_SCRATCH +static int ane_dart_drain_fault(struct ane_device *ane, u64 iova, + struct ane_dart_scratch *scratch, int *pages) +#else +static int ane_dart_drain_fault(struct ane_device *ane, u64 iova) +#endif { - (void)iova; (void)s; + (void)iova; drains++; if (scenario == 4 && drains == 2) return -ENOMEM; - ane->scratch_pages = ++*pages; + ane->scratch_pages++; return 0; } static void ane_dart_release_scratch(struct ane_device *ane, struct ane_dart_scratch *s, int pages) @@ -254,7 +259,11 @@ def build(text, header, work): else: start = min(start, text.index('static int ane_tm_poll_step(')) end = text.index('\n/*\n * Recovery runs', start) - (work / 'tm.c').write_text(HARNESS + helper(header) + text[start:end] + MAIN) + execute = text[start:end] + signature = '' + if 'ane_dart_drain_fault(ane, fault_iova,' in execute: + signature = '#define ANE_DRAIN_TAKES_SCRATCH\n' + (work / 'tm.c').write_text(signature + HARNESS + helper(header) + execute + MAIN) subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', str(work / 'tm.c'), '-o', str(work / 'tm')], check=True) return subprocess.run([str(work / 'tm')], capture_output=True, text=True) From 4a894c5482e522350d4366ef11d7aaf1060f9099 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:16:35 +1100 Subject: [PATCH 0639/1514] arm64: dts: apple: keep J415 and J493 hwmon definitions unchanged Keep the new shared sensor descriptions on the J473 and J413. The trimmed change produces the same J473, J413 and J413-fw27 DTBs as the board tests, and the same J415 and J493 DTBs as the base. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-j415.dts | 1 - arch/arm64/boot/dts/apple/t8112-j493.dts | 1 - 2 files changed, 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8112-j415.dts b/arch/arm64/boot/dts/apple/t8112-j415.dts index 1ac373e638ea97..2eddcd7a5f3424 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415.dts +++ b/arch/arm64/boot/dts/apple/t8112-j415.dts @@ -288,7 +288,6 @@ }; #include "hwmon-laptop.dtsi" -#include "t8112-hwmon.dtsi" /* * Mesa fingerprint sensor on spi2 (J415 ADT /arm-io/spi2/mesa): power on AP * GPIO 178, active high, and data-ready on AP GPIO 177. The data-ready edge diff --git a/arch/arm64/boot/dts/apple/t8112-j493.dts b/arch/arm64/boot/dts/apple/t8112-j493.dts index 08ae955c5a1bac..536010e4a3636a 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493.dts +++ b/arch/arm64/boot/dts/apple/t8112-j493.dts @@ -316,7 +316,6 @@ #include "hwmon-laptop.dtsi" #include "hwmon-fan.dtsi" -#include "t8112-hwmon.dtsi" /* * SPI2 uses native chip select. The sensor power line is AP GPIO 178, * active high; the data-ready line is omitted so captures use polling. From 4b35702880a6145297b498397b42a563d6f1d8d2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:19:37 +1100 Subject: [PATCH 0640/1514] media: apple: ave: test the firmware size refusal path Use the same segment-size predicate when matching a build and when validating the fallback variant. Cover both valid M2 builds and near misses in KUnit. Include the two observed segment sizes in the probe diagnostic. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-abi-test.c | 9 ++++++++- drivers/media/platform/apple/ave/ave-fw.c | 17 +++++++++-------- drivers/media/platform/apple/ave/ave.h | 6 +++++- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index f8488c825e5cb9..20e83305a7c780 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1502,7 +1502,8 @@ static void ave_26b123_layout(struct kunit *test) /* * The M2 with the 27.2 stub: the reserved segment sizes select the 27.2 * build's own start (device 12, handshake type 12) and the 26B123 layout; - * the 13.5 build keeps the M2's 6070 start, and other sizes stay refused. + * the 13.5 build keeps the M2's 6070 start. Other sizes fall back to + * ave_t8112, whose size check in ave_fw_probe() then refuses them. */ static void ave_t8112_26b123_build(struct kunit *test) { @@ -1516,6 +1517,12 @@ static void ave_t8112_26b123_build(struct kunit *test) &ave_t8112); KUNIT_EXPECT_PTR_EQ(test, ave_fw_select_build(&ave_t8112, 0x134000, 0x128000), &ave_t8112); + /* The near misses are refused: no variant of the chain pins them. */ + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(&ave_t8112, 0x11c000, 0x12c000)); + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(&ave_t8112, 0x134000, 0x128000)); + KUNIT_EXPECT_FALSE(test, ave_fw_sizes_match(n, 0x11c000, 0x12c000)); + KUNIT_EXPECT_TRUE(test, ave_fw_sizes_match(&ave_t8112, 0xd0000, 0x128000)); + KUNIT_EXPECT_TRUE(test, ave_fw_sizes_match(n, 0x11c000, 0x128000)); KUNIT_EXPECT_NULL(test, n->next_build); KUNIT_EXPECT_TRUE(test, n->boot_qualified); KUNIT_EXPECT_PTR_EQ(test, n->regs, ave_t8112.regs); diff --git a/drivers/media/platform/apple/ave/ave-fw.c b/drivers/media/platform/apple/ave/ave-fw.c index fd2e056610a379..49f1da033411fe 100644 --- a/drivers/media/platform/apple/ave/ave-fw.c +++ b/drivers/media/platform/apple/ave/ave-fw.c @@ -235,9 +235,11 @@ static const struct ave_fw_build *ave_fw_find_build(const struct ave_variant *v, return NULL; } -/* Whether these are the segment sizes of one of v's builds */ -static bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, - size_t data) +/* + * Whether TEXT/DATA segments of these sizes are a build the variant pins. + * ave_fw_probe() refuses the firmware when they are not. + */ +bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, size_t data) { if (v->build_count) return ave_fw_find_build(v, text, data, 0); @@ -297,12 +299,11 @@ int ave_fw_probe(struct ave_dev *ave) want_crc = build->text_crc; } else if (!ave->variant->boot_qualified && !ave->variant->fw_text_size) { /* A probe-only variant that pins no build takes any segment sizes. */ - } else if (ave->text.size != ave->variant->fw_text_size || - (ave->data.size != ave->variant->fw_data_size && - (!ave->variant->fw_data_size_alt || - ave->data.size != ave->variant->fw_data_size_alt))) { + } else if (!ave_fw_sizes_match(ave->variant, ave->text.size, + ave->data.size)) { return dev_err_probe(dev, -EINVAL, - "unexpected firmware segment sizes\n"); + "unexpected firmware segment sizes (TEXT %#zx DATA %#zx)\n", + ave->text.size, ave->data.size); } if ((ave->text.phys < ave->data.phys + ave->data.size && ave->data.phys < ave->text.phys + ave->text.size) || diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index ec2328aed0d57c..a0bda7749166ad 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -259,7 +259,10 @@ struct ave_variant { * The same encoder running another firmware build that a newer * bootloader preloads, with a start and command protocol of its own. * The firmware segment sizes the bootloader reserved select it. - * NULL when there is none. + * NULL when there is none. Use builds[] when the builds differ only + * in TEXT CRC (and command layout) but start the same way; use + * next_build when a build needs other start fields (boot device, + * handshake type, boot word, DATA handling) and has sizes of its own. */ const struct ave_variant *next_build; @@ -580,6 +583,7 @@ extern const struct ave_variant ave_t6000, ave_t6041, ave_t8112, ave_t8132, /* ave-fw.c */ u64 ave_fw_vcbar(const struct ave_variant *variant, u64 text_iova); int ave_fw_probe(struct ave_dev *ave); +bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, size_t data); const struct ave_variant *ave_fw_select_build(const struct ave_variant *v, size_t text, size_t data); int ave_fw_text_id_crc(const void *text, size_t size, u32 cell_off, From a834150cfa5051ac670c113db22a908590e12e03 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:27:44 +1100 Subject: [PATCH 0641/1514] drm/apple: test DCP firmware admission and IOMFB method tables Cover 13.5 firmware with legacy and explicit compatibility, required legacy IOMFB commands, and firmware-27 method selection and refusal. Test the real driver with local OF properties and a copy of the 27.2 method table. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-firmware-test.c | 82 +++++++++++++++++++ drivers/gpu/drm/apple/dcp.c | 1 + .../gpu/drm/apple/iomfb-legacy-methods-test.c | 38 +++++++++ drivers/gpu/drm/apple/iomfb_v13_3.c | 4 + 4 files changed, 125 insertions(+) create mode 100644 drivers/gpu/drm/apple/dcp-firmware-test.c create mode 100644 drivers/gpu/drm/apple/iomfb-legacy-methods-test.c diff --git a/drivers/gpu/drm/apple/dcp-firmware-test.c b/drivers/gpu/drm/apple/dcp-firmware-test.c new file mode 100644 index 00000000000000..ac9dce35e71212 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-firmware-test.c @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by dcp.c to exercise probe's firmware admission without hardware. */ +#include + +static void dcp_firmware_13_5_compat(struct kunit *test) +{ + static const char primary[] = "apple,t8112-dcp\0apple,dcp"; + static const char external[] = "apple,t8112-dcpext\0apple,dcpext"; + __be32 firmware[] = { cpu_to_be32(13), cpu_to_be32(5), 0 }; + __be32 compat[] = { cpu_to_be32(13), cpu_to_be32(3), 0 }; + struct property properties[] = { + { .name = "apple,firmware-compat", .length = sizeof(compat), + .value = compat, .next = &properties[1] }, + { .name = "apple,firmware-version", .length = sizeof(firmware), + .value = firmware, .next = &properties[2] }, + { .name = "compatible", .length = sizeof(primary), .value = (void *)primary }, + }; + struct device_node node = { .properties = properties }; + struct device dev = { + .init_name = "dcp-firmware-test", + .of_node = &node, + .driver = &apple_platform_driver.driver, + }; + + /* The 13.5 stub can advertise 13.3 IOMFB compatibility. */ + KUNIT_ASSERT_NOT_NULL(test, of_device_get_match_data(&dev)); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); + firmware[1] = cpu_to_be32(3); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_UNKNOWN); + firmware[1] = cpu_to_be32(5); + + properties[2].length = sizeof(external); + properties[2].value = (void *)external; + KUNIT_ASSERT_NOT_NULL(test, of_device_get_match_data(&dev)); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); + compat[1] = cpu_to_be32(5); + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), DCP_FIRMWARE_V_13_5); +} + +static void dcp_firmware_27_method_admission(struct kunit *test) +{ + struct device dev = { .init_name = "dcp-firmware-test" }; + const struct dcp_method_entry *methods = iomfb_v27_methods("27.2.0"); + const struct dcp_method_entry *earlier = iomfb_v27_methods("27.0.0"); + struct dcp_method_entry *incomplete; + unsigned int missing; + + KUNIT_ASSERT_NOT_NULL(test, methods); + KUNIT_ASSERT_NOT_NULL(test, earlier); + KUNIT_EXPECT_PTR_NE(test, methods, earlier); + KUNIT_EXPECT_NE(test, memcmp(methods[dcpep_swap_submit].tag, + earlier[dcpep_swap_submit].tag, + sizeof(methods[dcpep_swap_submit].tag)), 0); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.2.0"), DCP_FIRMWARE_V_27_0); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.3.0"), DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_EQ(test, dcp_v27_method_table(&dev, "27.2.1"), DCP_FIRMWARE_UNKNOWN); + + incomplete = kunit_kmalloc(test, sizeof(*methods) * dcpep_num_methods, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, incomplete); + memcpy(incomplete, methods, sizeof(*methods) * dcpep_num_methods); + memset(incomplete[dcpep_dfb_ready_query].tag, 0, + sizeof(incomplete[dcpep_dfb_ready_query].tag)); + KUNIT_EXPECT_NULL(test, iomfb_v27_missing_method(incomplete, &missing)); + KUNIT_EXPECT_EQ(test, missing, 0U); + memset(incomplete[dcpep_swap_submit].tag, 0, sizeof(incomplete[dcpep_swap_submit].tag)); + KUNIT_EXPECT_STREQ(test, iomfb_v27_missing_method(incomplete, &missing), + methods[dcpep_swap_submit].name); + KUNIT_EXPECT_EQ(test, missing, 1U); +} + +static struct kunit_case dcp_firmware_cases[] = { + KUNIT_CASE(dcp_firmware_13_5_compat), + KUNIT_CASE(dcp_firmware_27_method_admission), + {} +}; + +static struct kunit_suite dcp_firmware_suite = { + .name = "apple-dcp-firmware", + .test_cases = dcp_firmware_cases, +}; + +kunit_test_suite(dcp_firmware_suite); diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 8f347c6c217df6..865612ad8e678f 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -10282,4 +10282,5 @@ void dcp_unregister(void) #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "dcp_external_audio_test.c" #include "dcp_handoff_test.c" +#include "dcp-firmware-test.c" #endif diff --git a/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c b/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c new file mode 100644 index 00000000000000..858cc605639ec3 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb-legacy-methods-test.c @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by the 13.3 IOMFB backend shared by firmware 13.5. */ +#include + +static void iomfb_legacy_required_methods(struct kunit *test) +{ + static const enum dcpep_method required[] = { + dcpep_start_signal, + dcpep_set_digital_out_mode, + dcpep_swap_start, + dcpep_swap_submit, + dcpep_set_power_state, + }; + char empty[sizeof(dcp_methods[0].tag)] = {}; + unsigned int i, j; + + for (i = 0; i < ARRAY_SIZE(required); i++) { + const struct dcp_method_entry *entry = &dcp_methods[required[i]]; + + KUNIT_EXPECT_NOT_NULL(test, entry->name); + KUNIT_EXPECT_MEMNEQ(test, entry->tag, empty, sizeof(entry->tag)); + for (j = 0; j < i; j++) + KUNIT_EXPECT_MEMNEQ(test, entry->tag, dcp_methods[required[j]].tag, + sizeof(entry->tag)); + } +} + +static struct kunit_case iomfb_legacy_methods_cases[] = { + KUNIT_CASE(iomfb_legacy_required_methods), + {} +}; + +static struct kunit_suite iomfb_legacy_methods_suite = { + .name = "apple-iomfb-legacy-methods", + .test_cases = iomfb_legacy_methods_cases, +}; + +kunit_test_suite(iomfb_legacy_methods_suite); diff --git a/drivers/gpu/drm/apple/iomfb_v13_3.c b/drivers/gpu/drm/apple/iomfb_v13_3.c index 83e687fd7c63af..1807791e92afb8 100644 --- a/drivers/gpu/drm/apple/iomfb_v13_3.c +++ b/drivers/gpu/drm/apple/iomfb_v13_3.c @@ -121,3 +121,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) #undef DCP_FW_VER #undef DCP_FW + +#if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) +#include "iomfb-legacy-methods-test.c" +#endif From 63cc9e444ee5a4a93e20fa1bb439cf809ec57858 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:27:44 +1100 Subject: [PATCH 0642/1514] media: apple: avd: repair the host recovery fixture The extracted recovery function now checks the variant before resetting the decoder. Model the variant and verify that the no-reset case keeps DMA parked without restarting the decoder. Fixes: 0c94baf620c7 ("media: apple: avd: don't reset the T6041 decoder in recovery") Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/tests/recovery-test.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/avd/tests/recovery-test.py b/drivers/media/platform/apple/avd/tests/recovery-test.py index 66c7e0cdd84536..915707e1e63e41 100755 --- a/drivers/media/platform/apple/avd/tests/recovery-test.py +++ b/drivers/media/platform/apple/avd/tests/recovery-test.py @@ -24,6 +24,7 @@ #define AVD_RECOVER_GAP_MS 20 #define AVD_STORM_MAX 2 #define AVD_STORM_WINDOW 60000 +#define AVD_QUIRK_NO_RECOVERY_RESET (1U << 5) #define msecs_to_jiffies(x) (x) #define jiffies_to_msecs(x) ((unsigned int)(x)) #define time_before(a,b) ((long)((a)-(b))<0) @@ -41,6 +42,7 @@ struct avd_dev; struct avd_ctx { bool session_started; }; struct frame { int state,status; }; +struct avd_variant { unsigned int quirks; }; struct avd_backend_ops { void (*shutdown)(struct avd_dev *); int (*resume)(struct avd_dev *); @@ -53,6 +55,7 @@ struct avd_dev { void *dev,*domain,*empty_domain,*rstc,*compat_active; const struct avd_backend_ops *backend; + const struct avd_variant *variant; struct { bool dart_active,dma_parked,irq_enabled,hw_on; int irq,hw_lock,lock;unsigned int irq_gen; @@ -98,6 +101,7 @@ MAIN = r''' static const struct avd_backend_ops backend={.shutdown=shutdown_backend}; +static const struct avd_variant no_recovery_reset = { .quirks = AVD_QUIRK_NO_RECOVERY_RESET }; static const struct queue queue={.idle=idle,.resubmit=resubmit}; static int domain_token,empty_token; static void init(void) { @@ -110,6 +114,11 @@ init();assert(!avd_pm_recover(&d));assert(resets==1&&boots==1&&attaches==1&&detaches==1); assert(!d.pm.dma_parked&&!d.pm.irq_enabled&&attached==d.domain); avd_pm_enable_irq(&d);assert(irq_opens==1); + init(); + d.variant = &no_recovery_reset; + assert(avd_pm_recover(&d) == -EIO); + assert(attaches == 1 && !resets && !boots && !detaches); + assert(d.pm.dma_parked && !d.pm.irq_enabled && attached == d.empty_domain); init();reset_error=-EIO;d.frames[0].state=AVD_FRAME_SUBMITTED;avd_reset_queue(&d,-ETIMEDOUT); assert(d.faulted&&resets==1&&!boots&&!detaches&&d.pm.dma_parked&&attached==d.empty_domain); assert(d.frames[0].state==AVD_FRAME_DONE&&!d.pm.irq_enabled); @@ -129,7 +138,7 @@ jiffies=d.rest_until;assert(!avd_pm_recover(&d));assert(resets==3&&!d.pm.dma_parked); init();attach_error=-EIO;assert(avd_pm_recover(&d)==-EIO);assert(!resets&&!boots&&!detaches); init();d.pm.dart_active=false;assert(avd_pm_park(&d)==-EHOSTDOWN);assert(!shutdowns&&!resets&&!attaches); - puts("PASS: production recovery/PM: park before reset, failed reset/boot stays blocked, budget rests, parked resume never boots, expiry recovery"); + puts("PASS: production recovery/PM: park before reset, no-reset variant stays parked, failed reset/boot stays blocked, budget rests, parked resume never boots, expiry recovery"); } ''' From 7a35c9e69e04451c2e20357dd399bef35d922dea Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:27:44 +1100 Subject: [PATCH 0643/1514] media: apple: avd: test T8112 device tree matching Use the probe match table and a local OF node to check the T8112 open firmware, codec mask and stream setup. Register the suite in the decoder so it also builds when the driver and tests are modules. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/avd-drv.c | 3 ++ .../platform/apple/avd/avd-variant-test.c | 43 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 drivers/media/platform/apple/avd/avd-variant-test.c diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index c79379d2a50f25..522988b3a0a973 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -845,6 +845,9 @@ static struct platform_driver avd_driver = { }, }; module_platform_driver(avd_driver); +#if IS_REACHABLE(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) +#include "avd-variant-test.c" +#endif MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Apple avd v4l2 sl m2m"); diff --git a/drivers/media/platform/apple/avd/avd-variant-test.c b/drivers/media/platform/apple/avd/avd-variant-test.c new file mode 100644 index 00000000000000..3ed43b1a7d74c6 --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-variant-test.c @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Included by avd-drv.c to use the same OF table as avd_probe(). */ +#include + +static void avd_t8112_of_variant(struct kunit *test) +{ + static const char compatible[] = "apple,t8112-avd"; + struct property prop = { + .name = "compatible", + .length = sizeof(compatible), + .value = (void *)compatible, + }; + struct device_node node = { .properties = &prop }; + const struct of_device_id *match; + const struct avd_variant *variant; + + match = of_match_node(avd_of_match, &node); + KUNIT_ASSERT_NOT_NULL(test, match); + variant = match->data; + KUNIT_ASSERT_NOT_NULL(test, variant); + + /* Both stubs use the same independently supplied decoder image. */ + KUNIT_EXPECT_STREQ(test, variant->fw_name, "apple/avd-fw-v3-t1.bin"); + KUNIT_EXPECT_NULL(test, variant->fw_name_fallback); + KUNIT_EXPECT_NULL(test, variant->apple); + KUNIT_EXPECT_PTR_EQ(test, variant->configure_stream, &t8112_configure_stream); + KUNIT_EXPECT_EQ(test, variant->revision, 4); + KUNIT_EXPECT_EQ(test, variant->quirks, (u32)AVD_QUIRK_LSR); + KUNIT_EXPECT_EQ(test, variant->capabilities, + (u32)(AVD_CAPABILITY_H264 | AVD_CAPABILITY_HEVC | AVD_CAPABILITY_VP9)); +} + +static struct kunit_case avd_variant_cases[] = { + KUNIT_CASE(avd_t8112_of_variant), + {} +}; + +static struct kunit_suite avd_variant_suite = { + .name = "apple-avd-variant", + .test_cases = avd_variant_cases, +}; + +kunit_test_suite(avd_variant_suite); From 951b3cf09188f74b616f66346d51f25992edefd2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:27:44 +1100 Subject: [PATCH 0644/1514] accel/ane: test DATA-first preload ranges Cover contiguous reverse physical placement, overlap in that direction, and overflow past the end of the second segment. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_platform_test.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/drivers/accel/ane/ane_fw_platform_test.c b/drivers/accel/ane/ane_fw_platform_test.c index 66b8a8565a507e..8dda9aed1aeb49 100644 --- a/drivers/accel/ane/ane_fw_platform_test.c +++ b/drivers/accel/ane/ane_fw_platform_test.c @@ -38,6 +38,27 @@ static void ane_preload_ranges_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&soc, phys, size, dva)); } +static void ane_preload_physical_order_test(struct kunit *test) +{ + const struct ane_fw_platform platform = { + .preload_dva = { SZ_1M, SZ_1M + SZ_16K }, + .preload_size = { SZ_16K, SZ_32K }, + }; + const u64 *size = platform.preload_size; + const u64 *dva = platform.preload_dva; + u64 phys[] = { SZ_2M + SZ_32K, SZ_2M }; + + /* DATA can precede TEXT and touch its boundary in physical memory. */ + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); + phys[0] -= SZ_16K; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); + + /* DATA's end must not wrap, even if its base is valid and aligned. */ + phys[0] = SZ_2M; + phys[1] = U64_MAX - SZ_16K + 1; + KUNIT_EXPECT_FALSE(test, ane_fw_preload_ranges_valid(&platform, phys, size, dva)); +} + /* * H16 and H17 devices (any firmware platform) take the backend's sleep path, * never the rtclient one; only the H13/H14 rtclient (no platform) does. @@ -164,6 +185,7 @@ static struct kunit_case ane_fw_platform_cases[] = { KUNIT_CASE(ane_platform_staged_bind_test), KUNIT_CASE(ane_platform_sleep_path_test), KUNIT_CASE(ane_preload_ranges_test), + KUNIT_CASE(ane_preload_physical_order_test), {} }; From c5f88ec678b85e384580b57c0e8be49d6af2e456 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:27:44 +1100 Subject: [PATCH 0645/1514] selftests: apple: verify the BCM4377 control ring head resets Include the host-owned ring head in the recovery fixture. Set it to a nonzero value before PCI reset and check that reset clears it. Signed-off-by: Ryan Murray --- tools/testing/selftests/drivers/apple/bcm4377-state-wait.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py index f72da9d9558276..25884752bc6f0e 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-state-wait.py @@ -27,7 +27,7 @@ def recovery_program(source): unsigned long reset_pending, dma_window_base;struct pci_dev *pdev;struct hci_dev *hdev; const struct bcm4377_hw *hw;bool needs_reset,own_reset;unsigned bootstage,rti_status; struct ring_state *ring_state; - struct { unsigned generation,n_entries;unsigned long msgids[1];unsigned *events; } control_h2d_ring; + struct { unsigned generation,n_entries,head;unsigned long msgids[1];unsigned *events; } control_h2d_ring; struct { bool enabled; } control_ack_ring; }; struct hci_dev { struct bcm4377_data *data; bool setup; }; @@ -94,7 +94,9 @@ def recovery_program(source): assert(errors==1 && !pci_resets && !irq_disables && !irq_enables && !boots); assert(b.needs_reset && ring.value==99); b.dma_window_base=0;b.control_h2d_ring.n_entries=4; + b.control_h2d_ring.head=3; assert(!bcm4377_pci_reset(&b) && pci_resets==1 && irq_disables==1 && irq_enables==1); + assert(b.control_h2d_ring.head==0); assert(!b.own_reset); assert(!b.needs_reset && !ring.value && boots==1); reset_error=-EIO; From b56051f86b40ffa508c85767af3af723c6ede09c Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 22 Nov 2026 21:08:08 -0300 Subject: [PATCH 0646/1514] arm64: dts: apple: t6041-j575c: let userspace set the fan speeds The J575c SMC has no F0Md/F1Md fan mode keys: it spells them F0md/F1md, as the T6050 SMC does, so macsmc-hwmon drops the mode key at probe ("Fan F0Ac: optional keys not found: mode F0Md") and fanX_target stays read-only. Name the keys this SMC has and mark both fans apple,fan-manual-control, as the J614c/J616c already are. This SMC has no Ftst unlock key either; the fans are in automatic mode and take the manual mode write directly. The SMC drives the fans until userspace writes a target, and writing 0 hands a fan back. The J775D Mac Studio uses the same key spelling but keeps its fans read-only for userspace only because they have not been tested this way yet (the J714s change, 7a479d4a41c9, left J716s and J775D out until then), not because of a known hardware difference. Tested on a J575c (7.3.0-1-106, integration/aurora f5fae3cbb) with a one-shot Stage 2 whose J575c DTB differs only by this change: both fanX_target are 0644 and the probe message is gone; fan 1 set to 2000 rpm ran at 2000 and returned to the SMC's 1000 rpm after 0 was written; both fans set to 3000 ran at 2994/2990 and returned the same way; with fan 1 held at 2000 an s2idle cycle handed it back to the SMC. After these cycles, a 15 min all-core load (84 W, die up to 99 C) had the SMC raise both fans from 1000 to 1569 rpm on its own. No macsmc-hwmon messages in the kernel log. Then on 7.3.0-1-108 (integration/aurora e892113c7, this commit's base) with this commit's DTB: both fans set to their 3625 rpm maximum ran at about 3640 rpm, and 5000 was clamped to 3625. With both fans held at their 1000 rpm minimum, the same 15 min all-core load (84-85 W) took the die to 96 C after 5 min, 104 C after 10 min and 106-108 C over the last 3 min. That is below the first cpu-die trip (112 C), so no cooling device engaged and the clocks stayed at 4512/2592/4512 MHz with the same throughput as under SMC control; the SMC did not trip, shut down or override the held fans, and took them to 2500 rpm on its own after 0 was written. With fan 1 held at 2000 rpm, both a reboot and a poweroff followed by power-on came up with the fans under SMC control (1000 rpm) on a boot whose device tree has no fan control. 0 failed units, and the same kernel errors and warnings as with the base DTB. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index a9b42e9a63ab1d..12677f9d797e87 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1089,6 +1089,24 @@ #include "hwmon-common.dtsi" #include "hwmon-fan-dual.dtsi" +&smc_hwmon { + /* + * This SMC spells the fan mode keys F0md/F1md, as the T6050 one does + * (it has no F0Md/F1Md and no Ftst unlock key). It accepts a manual + * speed for both fans from userspace and returns them to firmware + * control when the request is dropped. + */ + fan-F0Ac { + apple,fan-mode = "F0md"; + apple,fan-manual-control; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + apple,fan-manual-control; + }; +}; + &pinctrl { status = "okay"; From d80fe820d7e23e96ecc2dc4da9989e80bbecf3e7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:35:28 +1100 Subject: [PATCH 0647/1514] accel/ane: describe the H16 KUnit modules Add module descriptions for the pending request, HWX and preload suites so that modpost accepts the ANE firmware tests as modules. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_h16_hwx_test.c | 1 + drivers/accel/ane/ane_h16_pending_test.c | 1 + drivers/accel/ane/ane_h16_preload_test.c | 1 + 3 files changed, 3 insertions(+) diff --git a/drivers/accel/ane/ane_h16_hwx_test.c b/drivers/accel/ane/ane_h16_hwx_test.c index a6e3976cda8f3b..13846add097711 100644 --- a/drivers/accel/ane/ane_h16_hwx_test.c +++ b/drivers/accel/ane/ane_h16_hwx_test.c @@ -832,4 +832,5 @@ static struct kunit_suite hwx_suite = { }; kunit_test_suite(hwx_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE HWX loading"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_pending_test.c b/drivers/accel/ane/ane_h16_pending_test.c index ed866c45710d7f..fef233e2c8ed24 100644 --- a/drivers/accel/ane/ane_h16_pending_test.c +++ b/drivers/accel/ane/ane_h16_pending_test.c @@ -328,4 +328,5 @@ static struct kunit_suite pending_suite = { }; kunit_test_suite(pending_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE pending requests"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_preload_test.c b/drivers/accel/ane/ane_h16_preload_test.c index 54112eae618bff..e29071d92538f2 100644 --- a/drivers/accel/ane/ane_h16_preload_test.c +++ b/drivers/accel/ane/ane_h16_preload_test.c @@ -457,4 +457,5 @@ static struct kunit_suite preload_suite = { }; kunit_test_suite(preload_suite); +MODULE_DESCRIPTION("KUnit tests for Apple ANE firmware preload"); MODULE_LICENSE("Dual MIT/GPL"); From e15fd82527219ff5f9f20f744fa7db36309797a8 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Mon, 23 Nov 2026 02:43:14 -0800 Subject: [PATCH 0648/1514] iommu: apple-dart: check a firmware-named buffer once before a CPU maps it Several drivers map for the CPU a buffer that a co-processor's firmware names by its DVA, and each resolves it through the IOMMU by hand first: RTKit's crash log, the DCP's walks in drm/apple (dcp.c, iomfb_m4.c, iomfb_v14_7.c, iomfb_v26_6.c, afk.c), aop.rs, ave-fw.c and the ANE firmware loader. They differ in the stride (the IOMMU's smallest page, a fixed 16 KiB, or the CPU's page), in which mappings count (Linux's, those the firmware kept from the boot loader, or both) and in what the target may be (DRAM, a DT memory-region, or anything). Separate from the walk, dcp_fw_phys_in_dram() in drivers/gpu/drm/apple/dcp-internal.h (used by afk.c and dcp.c) carries its own copy of the "registers sit below the first System RAM" check. Add apple_dart_fw_range(). It resolves every IOMMU page the buffer touches, at the domain's smallest page and from page boundary to page boundary, through the mappings the caller names (APPLE_DART_FW_LINUX on a paging domain so identity domains never treat an unmapped DVA as a translation or shadow retained mappings, and APPLE_DART_FW_RETAINED). It returns the range's start only when the pages are contiguous and the CPU-page-rounded range is DRAM outside System RAM: at or above the first System RAM, as every device's registers on these SoCs sit below it, and not memory the kernel allocates from, which its linear map also covers with other attributes. A firmware carveout passes. A stub returns -ENODEV when the driver isn't reachable. RTKit's crash log is the first user. Converting the other walks and dcp_fw_phys_in_dram() is left to their owners. Signed-off-by: Jeff Queisser --- drivers/iommu/apple-dart.c | 85 ++++++++++++++++++++++++++++++++++ include/linux/soc/apple/dart.h | 19 ++++++++ 2 files changed, 104 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 33a29ce9beb045..9b2c6c1d0c4a7f 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -3000,6 +3000,91 @@ int apple_dart_fw_remote(struct device *dev, dma_addr_t iova, bool write, } EXPORT_SYMBOL_GPL(apple_dart_fw_remote); +/* + * Memory a co-processor's firmware may share with the host for a CPU mapping: DRAM, + * at or above the first System RAM (Apple SoCs place every device's registers below + * it), that isn't System RAM. That leaves the firmware's own carveouts, which the + * kernel doesn't use or map, and refuses memory the kernel allocates from, which its + * linear map also covers with other attributes. + */ +static bool apple_dart_fw_phys_shareable(phys_addr_t pa, size_t size) +{ + phys_addr_t page_start, page_end, end; + + if (!pa || !size || check_add_overflow(pa, (phys_addr_t)size, &end) || + end > (phys_addr_t)~(PAGE_SIZE - 1)) + return false; + page_start = ALIGN_DOWN(pa, PAGE_SIZE); + page_end = ALIGN(end, PAGE_SIZE); + return region_intersects(0, page_end, IORESOURCE_SYSTEM_RAM, + IORES_DESC_NONE) != REGION_DISJOINT && + region_intersects(page_start, page_end - page_start, + IORESOURCE_SYSTEM_RAM, + IORES_DESC_NONE) == REGION_DISJOINT; +} + +static phys_addr_t apple_dart_fw_range_page(struct device *dev, + struct iommu_domain *domain, + dma_addr_t iova, unsigned int flags) +{ + phys_addr_t phys = 0; + + /* + * On an identity domain iommu_iova_to_phys() returns iova verbatim: skip + * APPLE_DART_FW_LINUX there so an unmapped DVA is never treated as a + * translation and APPLE_DART_FW_RETAINED is still consulted. + */ + if ((flags & APPLE_DART_FW_LINUX) && (domain->type & __IOMMU_DOMAIN_PAGING)) + phys = iommu_iova_to_phys(domain, iova); + if (!phys && (flags & APPLE_DART_FW_RETAINED) && + apple_dart_fw_remote(dev, iova, false, &phys)) + phys = 0; + return phys; +} + +/* + * The physical range behind a buffer a co-processor's firmware names by its DVA, for + * a CPU mapping. @flags chooses what resolves a DVA: APPLE_DART_FW_LINUX, the + * mappings Linux made (on a paging domain), and APPLE_DART_FW_RETAINED, those the + * firmware kept from the boot loader (apple_dart_fw_remote()). Every IOMMU page the + * buffer touches is resolved, at the domain's smallest page and from page boundary + * to page boundary, as the buffer need not start on one. *@phys is set only when + * they translate to one contiguous range whose CPU-page-rounded span + * apple_dart_fw_phys_shareable() accepts. -EINVAL for an empty, wrapping or + * flagless request, -ENODEV without an IOMMU domain, -ENOENT when its first byte + * doesn't translate, -ERANGE when a later page lies elsewhere or doesn't translate, + * -EACCES when the range isn't such memory. + */ +int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys) +{ + struct iommu_domain *domain = iommu_get_domain_for_dev(dev); + unsigned long pgsize; + dma_addr_t addr, last; + phys_addr_t start, phys_last; + + if (!size || !(flags & (APPLE_DART_FW_LINUX | APPLE_DART_FW_RETAINED)) || + check_add_overflow(iova, (dma_addr_t)size - 1, &last)) + return -EINVAL; + if (!domain) + return -ENODEV; + start = apple_dart_fw_range_page(dev, domain, iova, flags); + if (!start) + return -ENOENT; + if (check_add_overflow(start, (phys_addr_t)size - 1, &phys_last)) + return -ERANGE; + pgsize = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : PAGE_SIZE; + for (addr = ALIGN_DOWN(iova, pgsize) + pgsize; addr && addr <= last; addr += pgsize) + if (apple_dart_fw_range_page(dev, domain, addr, flags) != + start + (addr - iova)) + return -ERANGE; + if (!apple_dart_fw_phys_shareable(start, size)) + return -EACCES; + *phys = start; + return 0; +} +EXPORT_SYMBOL_GPL(apple_dart_fw_range); + static phys_addr_t apple_dart_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova) { diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 0a7925025e6287..592e2c845df850 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -2,6 +2,7 @@ #ifndef __LINUX_SOC_APPLE_DART_H__ #define __LINUX_SOC_APPLE_DART_H__ +#include #include #include #include @@ -180,6 +181,24 @@ static inline int apple_dart_host_resume(struct device *dev) { return -EOPNOTSUP static inline int apple_dart_host_restart(struct device *dev) { return -EOPNOTSUPP; } #endif +/* + * The physical range behind a buffer a co-processor's firmware names, for a CPU mapping: + * contiguous over every IOMMU page it touches, in DRAM outside System RAM. The flags + * choose what resolves a DVA: Linux's own mappings, those the firmware kept, or both. + */ +#define APPLE_DART_FW_LINUX BIT(0) +#define APPLE_DART_FW_RETAINED BIT(1) +#if IS_REACHABLE(CONFIG_APPLE_DART) +int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys); +#else +static inline int apple_dart_fw_range(struct device *dev, dma_addr_t iova, size_t size, + unsigned int flags, phys_addr_t *phys) +{ + return -ENODEV; +} +#endif + /* For a consumer whose firmware gates itself around a firmware-driven suspend. */ #if IS_REACHABLE(CONFIG_APPLE_DART) bool apple_dart_sleep_listed(struct device *dev); From 27d1f77bb267eaea865880fe20c9fbda3223d313 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:57:08 +1100 Subject: [PATCH 0649/1514] drm/asahi: establish G14 compute ownership before firmware publication Stage both ring entries before changing the producers. Store the packet and VM binding in the in-flight list, publish the cursors, then notify the firmware. Keep that ownership if the kick fails or another command in the packet is still in flight. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 48 ++++++++++-------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 79 ++++++++++++++++++++---------- 2 files changed, 82 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 773693a0cdfcbc..9e6697eda1d2e4 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -395,6 +395,7 @@ impl Runtime { } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + if !self.healthy() { return Err(EIO); } state.pending.push((packet, 0), GFP_KERNEL)?; self.pump(state); Ok(()) @@ -417,7 +418,9 @@ impl Runtime { self.healthy.store(false, Ordering::Release); self.idle.notify_all(); for (packet, _) in state.pending.drain(..) { - packet.release_guard(); + if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { + packet.release_guard(); + } packet.finish(Err(error)); } // Published work stays owned: the firmware may still read it. @@ -447,7 +450,7 @@ impl Runtime { /// Publishes pending commands while pool slots are free. fn pump(&self, state: &mut State) { self.acknowledge(state); - if self.asleep.load(Ordering::Acquire) { return; } + if !self.healthy() || self.asleep.load(Ordering::Acquire) { return; } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { // A slot is reused only once the firmware has unlinked it from its tracking list // (+0x94), which its retirement scan does after the slot's cursor is advanced. @@ -485,10 +488,13 @@ impl Runtime { packet.finish(Err(EINVAL)); continue; }; - let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { + let slot = state.next_slot; + let stamp = state.last.next(); + let ordinal = state.published + 1; + let last = index + 1 == packet.commands.len(); + let result = (|| -> Result { let bind = self.graph.kernel_uat().bind(&packet.vm)?; let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); - let stamp = state.last.next(); let job = ComputeJob { context: bind.slot(), sequence: state.sequence, @@ -497,35 +503,33 @@ impl Runtime { usc_base: control.usc_base, preempt, }; - let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; + let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; + let publication = state.root.stage_compute(command)?; + state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); - state.root.publish(command)?; - state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; - Ok((bind, stamp)) + publication.commit(); + Ok(()) })(); match result { - Ok((bind, stamp)) => { + Ok(()) => { state.last = stamp; state.sequence += 1; - let slot = state.next_slot; state.busy |= 1 << slot; - state.published += 1; - let ordinal = state.published; - state.next_slot = (state.next_slot + 1) % POOL_SLOTS; + state.published = ordinal; + state.next_slot = (slot + 1) % POOL_SLOTS; state.submitted += 1; - let last = index + 1 == packet.commands.len(); - if state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - started: Instant::now(), _bind: bind }, GFP_KERNEL).is_err() { - self.fail_all(state, ENOMEM); + if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK) { + self.fail_all(state, err); return; } - if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } } + Err(EBUSY) if !state.inflight.is_empty() => return, Err(e) => { dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); let _ = state.pending.remove(0); - // Earlier commands of a published packet fail it when they retire. - if !(packet.may_be_published() && index != 0) { + if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { packet.release_guard(); } packet.finish(Err(e)); @@ -594,6 +598,10 @@ impl Runtime { state.retired += 1; if done.last { done.packet.retired(); + } else if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &done.packet)) + && !state.pending.iter().any(|(packet, _)| Arc::ptr_eq(packet, &done.packet)) + { + done.packet.release_guard(); } } continue; diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 8db6c0ded49fde..e4692492ff8b47 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -358,6 +358,27 @@ impl CommandPool { } } +/// Ring contents prepared while the firmware still owns the old producer. +pub(crate) struct ComputePublication<'a> { + positions: &'a fw::types::GpuArray, + indices: &'a fw::types::GpuArray, + head: &'a core::sync::atomic::AtomicU32, + producer: &'a core::sync::atomic::AtomicU32, + next_head: u32, + next_producer: u32, +} + +impl ComputePublication<'_> { + pub(crate) fn commit(self) { + self.head.store(self.next_head, Ordering::Release); + crate::pgtable::clean_poc(self.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + self.producer.store(self.next_producer, Ordering::Release); + crate::pgtable::clean_poc(self.indices.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + } +} + /// The firmware 27.2 root and every record it names. pub(crate) struct RootV27_2 { graph: Arc, @@ -410,42 +431,50 @@ impl RootV27_2 { Ok((Self::word(&self.boot.positions, 0x40)?, Self::word(&self.boot.positions, 0)?)) } - /// Publishes `command` as the queue's next command: pointer, queue head, then the compute - /// submission entry and its producer. - pub(crate) fn publish(&self, command: u64) -> Result { + /// Prepares a work pointer and channel entry without advancing either producer. + pub(crate) fn stage_compute(&self, command: u64) -> Result> { let job = &self.boot; + let indices = &self.channels[2 * SUBMISSION_RING]; + let ring = &self.channels[2 * SUBMISSION_RING + 1]; + crate::pgtable::clean_invalidate_poc(job.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(indices.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); let head = job.positions.shared_index(0x40)?; let old = head.load(Ordering::Acquire); let capacity = Self::word(&job.positions, 0x50)?; - if capacity == 0 || (old % capacity) as usize * 8 + 8 > job.pointers.as_slice().len() { - return Err(EINVAL); + let retired = Self::word(&job.positions, 0)?; + if capacity <= 1 || old >= capacity || retired >= capacity + || capacity as usize > job.pointers.len() / 8 + { + return Err(EIO); } - let at = (old % capacity) as usize * 8; + let next_head = (old + 1) % capacity; + if next_head == retired { return Err(EBUSY); } + + let producer = indices.shared_index(0x20)?; + let write = producer.load(Ordering::Acquire); + let read = Self::word(indices, 0)?; + let entries = crate::m3::m3_channel_format::SLOTS; + if write >= entries || read >= entries { return Err(EIO); } + let next_producer = (write + 1) % entries; + if next_producer == read { return Err(EBUSY); } + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), + u16::try_from(next_head).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + + let at = old as usize * 8; job.pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); job.pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); crate::pgtable::clean_poc(job.pointers.as_slice()[at..].as_ptr(), 8); - crate::pgtable::poc_barrier(); - let new = (old + 1) % capacity; - head.store(new, Ordering::Release); - crate::pgtable::clean_poc(job.positions.as_slice().as_ptr(), 0x60); - crate::pgtable::poc_barrier(); - let state = &self.channels[2 * SUBMISSION_RING]; - let ring = &self.channels[2 * SUBMISSION_RING + 1]; - let w = Self::word(state, 0x20)?; - if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } - let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; - let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), - u16::try_from(new).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; - let base = w as usize * entry.len(); - for (k, word) in entry.chunks(4).enumerate() { - ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + let base = write as usize * entry.len(); + for (index, word) in entry.chunks_exact(4).enumerate() { + ring.shared_index(base + 4 * index)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); } crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); crate::pgtable::poc_barrier(); - state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); - crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); - crate::pgtable::poc_barrier(); - Ok(()) + Ok(ComputePublication { positions: &job.positions, indices, head, producer, + next_head, next_producer }) } /// Publishes the boot job, whose command and ring entry the root already holds. The GPU From 19f90d0e8a3a1dffc753589b17f06ca2430a2baa Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 22:07:03 +1100 Subject: [PATCH 0650/1514] tools/asahi: model the DCP's firmware-runs flag in the retained-sleep test dcpext26-suspend-route-tests builds the retained-external block of dcp_platform_suspend() against its own struct apple_dcp, which now needs the sleep_fw_runs field that block sets. Add it, and check that the flag is set together with the wakeup path and stays clear when the retained sleep is refused (firmware not running, disconnect failure). Signed-off-by: Ryan Murray --- tools/asahi/dcpext26-suspend-route-tests.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/tools/asahi/dcpext26-suspend-route-tests.py b/tools/asahi/dcpext26-suspend-route-tests.py index 8067762a9fc1b6..67f13cf1bde289 100644 --- a/tools/asahi/dcpext26-suspend-route-tests.py +++ b/tools/asahi/dcpext26-suspend-route-tests.py @@ -58,7 +58,7 @@ def function(text, name): struct apple_dcp { struct { int iomfb_method_profile; } hw; void *coproc_reg; - bool crashed, ext26_blocked, external_suspended; + bool crashed, ext26_blocked, external_suspended, sleep_fw_runs; int external_error; }; static unsigned run=1, parks, unparks, wake_paths, disabled, enabled; @@ -81,19 +81,19 @@ def function(text, name): struct apple_dcp native={.hw.iomfb_method_profile=DCP_IOMFB_METHODS_J613_EXT26, .coproc_reg=(void *)0x1000,.external_suspended=true}; assert(suspend_path(&dev,&native)==0); - assert(parks==0 && disabled==0 && wake_paths==1); + assert(parks==0 && disabled==0 && wake_paths==1 && native.sleep_fw_runs); assert(resume_path(&dev,&native)==0 && unparks==0 && !native.external_suspended); - reset_counts();run=0; - assert(suspend_path(&dev,&native)==-EHOSTDOWN && parks==0 && wake_paths==0); + reset_counts();run=0;native.sleep_fw_runs=false; + assert(suspend_path(&dev,&native)==-EHOSTDOWN && parks==0 && wake_paths==0 && !native.sleep_fw_runs); assert(resume_path(&dev,&native)==-EHOSTDOWN && native.ext26_blocked && native.external_error==-EHOSTDOWN); run=1;reset_counts();disconnect_error=-EBUSY; assert(suspend_path(&dev,&native)==-EBUSY && parks==0 && wake_paths==0 && enabled==0); struct apple_dcp h17p={.hw.iomfb_method_profile=DCP_IOMFB_METHODS_H17P_EXTERNAL}; disconnect_error=0;reset_counts(); - assert(suspend_path(&dev,&h17p)==0 && parks==1 && disabled==1 && wake_paths==1); + assert(suspend_path(&dev,&h17p)==0 && parks==1 && disabled==1 && wake_paths==1 && h17p.sleep_fw_runs); assert(resume_path(&dev,&h17p)==0 && unparks==1); - reset_counts();disconnect_error=-EBUSY; - assert(suspend_path(&dev,&h17p)==-EBUSY && parks==0 && wake_paths==0 && disabled==1 && enabled==1); + reset_counts();disconnect_error=-EBUSY;h17p.sleep_fw_runs=false; + assert(suspend_path(&dev,&h17p)==-EBUSY && parks==0 && wake_paths==0 && disabled==1 && enabled==1 && !h17p.sleep_fw_runs); struct apple_dcp other={0};disconnect_error=0;reset_counts(); assert(suspend_path(&dev,&other)==0 && resume_path(&dev,&other)==0 && parks==0 && unparks==0); } @@ -106,4 +106,5 @@ def function(text, name): result = subprocess.run([str(path.with_suffix(''))]) if result.returncode: sys.exit(1) -print('PASS retained sleep: H17P park/unpark paired; native26 no park, RUN refusal; disconnect rollback preserved') +print('PASS retained sleep: H17P park/unpark paired; native26 no park, RUN refusal; disconnect rollback preserved; ' + 'firmware-runs flag set with the wakeup path only') From 0d3088096987e69d05fc0fd99b23af0e993da4ee Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 22 Nov 2026 19:11:34 -0300 Subject: [PATCH 0651/1514] usb: typec: tipd: J575c: renegotiate every inherited connection Since commit 1a774eeee49a ("usb: typec: tipd: renegotiate inherited J575c connections"), a J575c connection inherited from the boot chain has been renegotiated only when byte 7 of register 0x7e lacked bit 3. That bit was taken to mean "the controller has completed an attach with the OS running", and bit 2 to mean the inherited state. It does not mean that. Read at the very start of the probe, before any command, byte 7 is 0x08 on every connected port, including a boot-attached USB 3 drive whose SuperSpeed side is stuck in RxDetect. The 0x04 that the gate saw came from the probe itself: it used to send each port an LDCM command before the gate. That command starts a new liquid measurement, and afterwards the controller reports 0x04. Since commit 5b5032b33af3 ("usb: typec: tipd: sn201202x: Send no LDCM command to a dry port") a dry port gets no LDCM command. The gate now sees 0x08 and skips the renegotiation. A USB 3 device attached at boot then comes up at 480 Mb/s (usb-storage instead of uas) until it is replugged. The controller reports nothing else that tells an inherited connection whose SuperSpeed side is stuck from one that trains. Drop the gate and renegotiate every inherited J575c connection. That is what the probe did before the LDCM change: in every J575c boot log we have from before it, the gate let every connected port through. The renegotiation drops VBUS and CC for about 5 s, but it cannot take away a USB device that is in use. dwc3-apple does not start the port's xHCI before the port controller reports the first connection, and the probe reports it only after the renegotiation. A drive on a renegotiated port is first enumerated after it, at boot as well as for a disk that fstab or the initramfs waits for. Unbinding the port controller disconnects the partner first (the host role goes to none), so a later bind renegotiates a port whose devices are already gone. The ports probe asynchronously (sn201202x sets PROBE_PREFER_ASYNCHRONOUS), so the renegotiations run at the same time. With three connected ports the boot takes 5 to 6 s longer, as with the stock linux-aurora kernel, which renegotiates the same ports: systemd reports the boot finished at 13.5 s with the gate skipping them and at 18.6 to 19.9 s with this change (stock: 18.1 to 18.3 s). Tested on a J575c (Mac Studio, M4 Max) with a USB 3 drive (10 Gb/s) attached through each reboot on the same port, kernel built from integration/aurora f5fae3cbb, whose tipd sources match this base: tipd sources byte 7 at the gate drive at boot f5fae3cbb 0x08, skipped 480M usb-storage same, LDCM change reverted 0x04, renegotiated Gen 2x1 uas f5fae3cbb + this change no gate, renegotiated Gen 2x1 uas With the tipd sources from before the LDCM change on the same kernel, byte 7 is 0x08 at the start of the probe and 0x04 at the gate. A kernel built from this change on integration/aurora 48470aad gives the same: the three connected ports renegotiated by 18.4 s, the drive at Gen 2x1 uas, and a read-only fstab mount of it at 19.9 s. Unbinding the drive's port controller with the drive mounted removed the drive and shut its filesystem down at once; the bind renegotiated the port in 5.2 s and the drive came back at Gen 2x1. Fixes: 1a774eeee49a ("usb: typec: tipd: renegotiate inherited J575c connections") Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- drivers/usb/typec/tipd/core.c | 34 ++++------------------------------ 1 file changed, 4 insertions(+), 30 deletions(-) diff --git a/drivers/usb/typec/tipd/core.c b/drivers/usb/typec/tipd/core.c index 0294061aaaceba..85f1664e2076cb 100644 --- a/drivers/usb/typec/tipd/core.c +++ b/drivers/usb/typec/tipd/core.c @@ -3595,27 +3595,19 @@ static int cd321x_remove(struct tps6598x *tps) * J716c: the boot port keeps a USB2 repeater connection. * J575c: a connection that was up before Linux keeps its Type-C retimer set up * from before the host PHY ran, so SuperSpeed stays in RxDetect until the - * partner is replugged. Byte 7 of register 0x7e has bit 3 set once the - * controller has completed an attach with the OS running (after a replug, and - * under macOS) and bit 2 in the inherited state; renegotiate only without - * bit 3. A failure leaves the port as it was (USB2 only) instead of failing - * the probe. + * partner is replugged. Every such connection is renegotiated: the controller + * reports nothing that tells it apart from one whose SuperSpeed side trains. + * A failure leaves the port as it was (USB2 only) instead of failing the probe. */ -#define CD321X_ATTACH_STATE_REG 0x7e -#define CD321X_ATTACH_STATE_BYTE 7 -#define CD321X_ATTACH_STATE_DONE BIT(3) - struct cd321x_inherited_board { const char *compatible; u8 key[4]; - bool check_attach_state; bool best_effort; }; static const struct cd321x_inherited_board cd321x_inherited_boards[] = { { .compatible = "apple,j716c", .key = { '6', '1', '7', 'J' } }, - { .compatible = "apple,j575c", .key = { '5', '7', '5', 'J' }, - .check_attach_state = true, .best_effort = true }, + { .compatible = "apple,j575c", .key = { '5', '7', '5', 'J' }, .best_effort = true }, }; static const struct cd321x_inherited_board *cd321x_inherited_board(void) @@ -3628,19 +3620,6 @@ static const struct cd321x_inherited_board *cd321x_inherited_board(void) return NULL; } -static int cd321x_attach_state_done(struct tps6598x *tps) -{ - u8 state[CD321X_ATTACH_STATE_BYTE + 1]; - int ret; - - ret = tps6598x_block_read(tps, CD321X_ATTACH_STATE_REG, state, sizeof(state)); - if (ret) - return ret; - dev_dbg(tps->dev, "inherited connection, attach state 0x%02x\n", - state[CD321X_ATTACH_STATE_BYTE]); - return !!(state[CD321X_ATTACH_STATE_BYTE] & CD321X_ATTACH_STATE_DONE); -} - static int __cd321x_reset_inherited_connection(struct tps6598x *tps, const struct cd321x_inherited_board *board, u32 *status) @@ -3653,11 +3632,6 @@ static int __cd321x_reset_inherited_connection(struct tps6598x *tps, mode = tps6598x_check_mode(tps); if (mode != TPS_MODE_APP && mode != TPS_MODE_APP1) return 0; - if (board->check_attach_state) { - ret = cd321x_attach_state_done(tps); - if (ret) - return ret < 0 ? ret : 0; - } /* All suppliers are available, but no USB or router session has started. */ ret = tps6598x_exec_cmd(tps, "LOCK", sizeof(board->key), board->key, sizeof(result), From 3a1f8cd38e3f6e39ba15d8bd39a53d1df128b06c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 05:23:32 -0500 Subject: [PATCH 0652/1514] drm/asahi: g17: honor BusyRuns::bound in M5 submission effort On M5, InitData::submission_effort() previously published FULL_EFFORT only while a host thread blocked on an unsignalled export fence (waited), ignoring BusyRuns::bound. Pipelined submission loops that keep the GPU continuously busy without blocking on an unsignalled fence fell to effort 0 (base performance state P1, 338 MHz on J714 vs 1620 MHz at P13) and stayed there for the whole run. Honor waited || bound on M5 so continuously GPU-bound clients promote to FULL_EFFORT once a busy run exceeds IDLE_HOLD_NS while paced work with idle gaps of at least FIRMWARE_IDLE_OFF_MS continues to publish 0 and idle decay still clears back to 0 cleanly. Add a registered host test (tools/asahi/g17-m5-effort-tests.py) verifying the policy and idle decay with a mutation negative control. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/initdata.rs | 20 ++-- tools/asahi/g17-m5-effort-tests.py | 148 ++++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 3 files changed, 160 insertions(+), 10 deletions(-) create mode 100755 tools/asahi/g17-m5-effort-tests.py diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 66fe9d80558f89..addccd0040b9c1 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -1681,22 +1681,22 @@ impl InitData { /// (16.16); without one, its own controller raises the state for work that queues up behind /// the running command and otherwise lets it fall to the base state. /// - /// M5 publishes none while work streams, except while a host thread waits for it (`waited`): - /// then the full effort, so a submit-and-wait loop runs at the top state. - /// - /// The other G17 SoCs publish the full effort while a client has kept the GPU running + /// M5 publishes none while paced work streams, and publishes the full effort while either a + /// host thread waits for submitted work (`waited`) or a client has kept the GPU running /// without going idle for longer than the effort hold (`bound`, [`super::power::BusyRuns`]): - /// a submit-and-wait loop queues nothing behind its command, so the firmware alone keeps it - /// at the bottom state however busy the GPU is. Other work streams with the lowest effort - /// that keeps it above the base performance state ([`active_effort`]), and leaves the rest - /// to the firmware: work that the firmware let fall to the base state stalled the GPU under - /// concurrent load (a firmware recovery with no fault), and a full effort on every + /// pipelined compute and render loops that keep the GPU continuously busy without blocking on + /// an unsignalled fence would otherwise fall to the base performance state. + /// + /// The other G17 SoCs publish the full effort while `bound`, and stream other work with the + /// lowest effort that keeps it above the base performance state ([`active_effort`]), leaving + /// the rest to the firmware: work that the firmware let fall to the base state stalled the GPU + /// under concurrent load (a firmware recovery with no fault), and a full effort on every /// submission held the top state whatever the load. A waiter doesn't tell paced work from a /// submit-and-wait loop, because paced work has one too (the compositor, or the next frame's /// fence). pub(super) fn submission_effort(&self, effort: u32, waited: bool, bound: bool) -> u32 { if self.m5 { - return if waited { effort } else { 0 }; + return if waited || bound { effort } else { 0 }; } if bound { effort } else { effort.min(self.active_effort) } } diff --git a/tools/asahi/g17-m5-effort-tests.py b/tools/asahi/g17-m5-effort-tests.py new file mode 100755 index 00000000000000..ef59c909a67d72 --- /dev/null +++ b/tools/asahi/g17-m5-effort-tests.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 submission_effort() honoring BusyRuns::bound alongside waited. + +Extracts production `submission_effort()` from `drivers/gpu/drm/asahi/g17/initdata.rs` +and `Effort` / `BusyRuns` from `drivers/gpu/drm/asahi/g17/power.rs`, verifying: +1. M5 publishes FULL_EFFORT when a client is continuously GPU-bound (`bound == true`) + even when `waited == false` (pipelined submission loops). +2. M5 still publishes FULL_EFFORT when `waited == true` (submit-and-wait loops). +3. M5 publishes 0 when neither `waited` nor `bound` (paced work with idle gaps >= 2 ms) + and decays cleanly back to 0 after IDLE_HOLD_NS of idle. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + init_src = (G17 / 'initdata.rs').read_text() + power_src = (G17 / 'power.rs').read_text() + + sub_fn = item(init_src, 'pub(super) fn submission_effort(').replace('pub(super) ', '') + if mutation == 'm5-ignores-bound': + sub_fn = sub_fn.replace('if waited || bound', 'if waited', 1) + + effort_struct = item(power_src, 'pub(super) struct Effort') + effort_impl = item(power_src, 'impl Effort') + busy_struct = item(power_src, 'pub(super) struct BusyRuns') + busy_run_struct = item(power_src, 'struct BusyRun ') + busy_run_impl = item(power_src, 'impl BusyRun ') + busy_impl = item(power_src, 'impl BusyRuns') + + parts = '\n'.join([ + effort_struct, effort_impl, busy_run_struct, busy_run_impl, busy_struct, busy_impl, + ]).replace('pub(super) ', '') + + return f''' +const FULL_EFFORT: u32 = 0x10000; +const IDLE_HOLD_NS: u64 = 16_000_000; +const CLIENT_RUNS: usize = 16; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum IdleAction {{ None, Clear, Recheck(u64) }} + +{parts} + +struct MockInitData {{ + m5: bool, + active_effort: u32, +}} + +impl MockInitData {{ + {sub_fn} +}} + +fn main() {{ + let m5 = MockInitData {{ m5: true, active_effort: 0 }}; + let g17p = MockInitData {{ m5: false, active_effort: 0x5555 }}; + + // Direct policy matrix on M5 vs non-M5. + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, true), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, true), FULL_EFFORT); + assert_eq!(m5.submission_effort(0, true, true), 0); + + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false), 0x5555); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, true), FULL_EFFORT); + + // End-to-end pipelined compute loop on M5 without host waiters: + // 24 MHz clock -> idle_ticks = 2 ms = 48_000 ticks, hold_ticks = 16 ms = 384_000 ticks. + let idle_ticks = 48_000u64; + let hold_ticks = 384_000u64; + let mut runs = BusyRuns::new(); + let mut effort = Effort::new(); + + effort.submit(); + let mut tick = 100_000u64; + for _ in 0..500 {{ + // 40 us execution + 10 us gap (< 2 ms idle_ticks) -> sustained busy run (> 20 ms total). + runs.note(7, tick, tick + 960, idle_ticks); + tick += 1_200; + }} + assert!(runs.bound(tick, hold_ticks, idle_ticks)); + let changed = effort.note_bound(true); + assert!(changed); + assert_eq!( + m5.submission_effort(FULL_EFFORT, effort.waited(), effort.bound()), + FULL_EFFORT, + "M5 must publish FULL_EFFORT when BusyRuns::bound is true even without a waiter", + ); + + // Idle decay clears streaming, bound, and effort cleanly back to 0. + assert_eq!(effort.idle(1_000_000, false), IdleAction::Recheck(IDLE_HOLD_NS)); + assert_eq!(effort.idle(1_000_000 + IDLE_HOLD_NS, false), IdleAction::Clear); + runs.end(); + assert!(!effort.bound()); + assert!(!runs.bound(tick, hold_ticks, idle_ticks)); + assert_eq!(m5.submission_effort(0, effort.waited(), effort.bound()), 0); + + // Paced work with 5 ms idle gaps stays unbound and publishes 0 on M5. + let mut paced = 1_000_000u64; + for _ in 0..20 {{ + runs.note(9, paced, paced + 24_000, idle_ticks); + paced += 120_000; // 5 ms > 2 ms idle_ticks + }} + assert!(!runs.bound(paced, hold_ticks, idle_ticks)); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false), 0); + + println!("PASS g17-m5-effort-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['m5-ignores-bound']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-eff-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 326dccb7b85730..9ab397d1f85f04 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -231,6 +231,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), + 'g17-m5-effort-tests.py': [([], PASS)] + + mutations('--mutation', ('m5-ignores-bound',), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 38d93aa124a9b9dbb3e01c8269f2c08e40053c75 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:28 +1100 Subject: [PATCH 0653/1514] mfd: macsmc: initialize event handlers before RTKit The receive worker can dispatch a notification once the SMC sends its initial reply. Initialize the notifier chain with the rest of the callback state so it is ready before either RTKit path installs the callbacks. Signed-off-by: Ryan Murray --- drivers/mfd/macsmc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index f8deb3f4acfeca..b8b89256bd347b 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -645,6 +645,7 @@ static void apple_smc_init_state(struct apple_smc *smc) spin_lock_init(&smc->lock); init_completion(&smc->init_done); init_completion(&smc->cmd_done); + BLOCKING_INIT_NOTIFIER_HEAD(&smc->event_handlers); smc->boot_stage = APPLE_SMC_BOOTING; } @@ -712,7 +713,6 @@ static int apple_smc_probe(struct platform_device *pdev) } dev_set_drvdata(&pdev->dev, smc); - BLOCKING_INIT_NOTIFIER_HEAD(&smc->event_handlers); ret = apple_smc_read(smc, SMC_KEY(#KEY), &count, sizeof(count)); if (ret >= 0 && ret != sizeof(count)) { From 43e9e521ee7704b73cb312e1b19ed311363d2113 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:34 +1100 Subject: [PATCH 0654/1514] cpufreq: apple-soc: KUnit: retain the report node until cleanup Use the reference-counted OF iterator and release the selected node with a KUnit action. Keep the reference through driver initialization and release it even when an assertion aborts the test. Document that the policy suite skips when a CPUFreq driver is already registered. Signed-off-by: Ryan Murray --- drivers/cpufreq/Kconfig.arm | 3 ++- drivers/cpufreq/apple-soc-cpufreq-test.c | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/drivers/cpufreq/Kconfig.arm b/drivers/cpufreq/Kconfig.arm index 885564633bce7c..f1072141ae6e7c 100644 --- a/drivers/cpufreq/Kconfig.arm +++ b/drivers/cpufreq/Kconfig.arm @@ -44,7 +44,8 @@ config ARM_APPLE_SOC_CPUFREQ_KUNIT_TEST die-temperature limit and its devicetree parsing, and the board thermal ownership cap. The cluster registers are ordinary memory, which the MMIO accessors of arm64 can read and write; no hardware - is accessed. + is accessed. The policy suite skips when a CPUFreq driver is already + registered. If unsure, say N. diff --git a/drivers/cpufreq/apple-soc-cpufreq-test.c b/drivers/cpufreq/apple-soc-cpufreq-test.c index 818caf75f302ed..8a207c186d590e 100644 --- a/drivers/cpufreq/apple-soc-cpufreq-test.c +++ b/drivers/cpufreq/apple-soc-cpufreq-test.c @@ -1215,33 +1215,33 @@ static void cft_test_fast_die_init_required(struct kunit *test) KUNIT_EXPECT_EQ(test, cft_qos_max(ctx), FREQ_QOS_MAX_DEFAULT_VALUE); } +KUNIT_DEFINE_ACTION_WRAPPER(cft_put_report, of_node_put, struct device_node *); + /* The property names the PMP report node and the lane of the cluster. */ static void cft_test_fast_die_init_described(struct kunit *test) { struct cft_ctx *ctx = cft_fast_die_setup(test, &soc_t8140_info); - struct device_node *np, *report = NULL; + struct device_node *np, *report; struct apple_fast_die *fd; __be32 *value; + int ret; - /* - * Any node with a phandle can stand in for the report node. The walk - * takes no reference: take one for the time the test uses the node. - */ - for_each_of_allnodes(np) { - if (np->phandle) { - report = np; + /* Hold a reference to the first node that can stand in for the report. */ + for (report = of_find_all_nodes(NULL); report; + report = of_find_all_nodes(report)) { + if (report->phandle) break; - } } if (!report) kunit_skip(test, "no devicetree node with a phandle"); + ret = kunit_add_action_or_reset(test, cft_put_report, report); + KUNIT_ASSERT_EQ(test, ret, 0); value = kunit_kzalloc(test, 2 * sizeof(*value), GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, value); value[0] = cpu_to_be32(report->phandle); value[1] = cpu_to_be32(3); np = cft_cluster_node(test, value, 2); - of_node_put(report); KUNIT_ASSERT_EQ(test, apple_fast_die_init(ctx->policy, np), 0); fd = ctx->priv->fast_die; From 027f0b26de789e05f4ea094f559afbbdcd0ee7b5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:43 +1100 Subject: [PATCH 0655/1514] drm/asahi: drain G14 submissions before completing or stopping Close submission admission under the runtime mutex before unbind drains the queue. If staging a later command fails, retain the packet and its VM guard until the already-published prefix retires, then complete the fence with the staging error. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 43 +++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 9e6697eda1d2e4..682a23f0c96e2b 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -299,6 +299,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta struct Inflight { packet: Arc, last: bool, + publication_error: Option, stamp: event::EventValue, slot: usize, /// Queue publications up to and including this command, counted from take-over. @@ -335,10 +336,26 @@ struct State { capacity: u32, inflight: KVec, pending: KVec<(Arc, usize)>, + accepting: bool, submitted: u64, retired: u64, } +impl State { + /// Stop publishing this packet. Report failure only once any published prefix retires. + fn fail_publication(&mut self, packet: &Arc, err: Error) { + let _ = self.pending.remove(0); + if let Some(last) = self.inflight.iter_mut().rev() + .find(|flight| Arc::ptr_eq(&flight.packet, packet)) + { + last.publication_error = Some(err); + } else { + packet.release_guard(); + packet.finish(Err(err)); + } + } +} + #[pin_data(PinnedDrop)] pub(crate) struct Runtime { dev: ARef, @@ -396,6 +413,7 @@ impl Runtime { let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } + if !state.accepting { return Err(ENODEV); } state.pending.push((packet, 0), GFP_KERNEL)?; self.pump(state); Ok(()) @@ -483,9 +501,7 @@ impl Runtime { let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); let Command::Compute(control) = packet.commands[index] else { // Queues of this backend accept only compute commands (Queue::submit). - let _ = state.pending.remove(0); - if !(packet.may_be_published() && index != 0) { packet.release_guard(); } - packet.finish(Err(EINVAL)); + state.fail_publication(&packet, EINVAL); continue; }; let slot = state.next_slot; @@ -506,7 +522,7 @@ impl Runtime { let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; let publication = state.root.stage_compute(command)?; state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); publication.commit(); Ok(()) @@ -528,11 +544,7 @@ impl Runtime { Err(EBUSY) if !state.inflight.is_empty() => return, Err(e) => { dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); - let _ = state.pending.remove(0); - if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) { - packet.release_guard(); - } - packet.finish(Err(e)); + state.fail_publication(&packet, e); } } } @@ -596,7 +608,10 @@ impl Runtime { } state.busy &= !(1 << done.slot); state.retired += 1; - if done.last { + if let Some(err) = done.publication_error { + done.packet.release_guard(); + done.packet.finish(Err(err)); + } else if done.last { done.packet.retired(); } else if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &done.packet)) && !state.pending.iter().any(|(packet, _)| Arc::ptr_eq(packet, &done.packet)) @@ -666,17 +681,20 @@ impl Runtime { /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC /// with every mapping still in place (RTKit power-off if the firmware does not stop). pub(crate) fn stop(&self) { - // Let published work retire; the service signals `idle` when nothing is left. + // Close admission while the service retires work already accepted. { let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + state.accepting = false; let start = Instant::::now(); while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { let Some(state) = guard.as_ref() else { break; }; if state.inflight.is_empty() && state.pending.is_empty() { break; } let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); } + // Serialize the last permitted publication with the transition to shutdown. + self.healthy.store(false, Ordering::Release); } - self.healthy.store(false, Ordering::Release); // Nothing queues service work after the detach, and none is queued or running once the // drain returns, so no work outlives the module. drop(self.notify.detach()); @@ -790,6 +808,7 @@ impl Backend { capacity, inflight: KVec::new(), pending: KVec::new(), + accepting: true, submitted: 0, retired: 0, }); From 6f67df239dd57bc0bf8e24c631c75c4d714ee4bf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:43 +1100 Subject: [PATCH 0656/1514] drm/asahi: require the firmware handoff SRAM voltage table Read each SRAM operating-point voltage from the loader-provided ADT table. Refuse the handoff if the table is absent or inconsistent with the core operating points. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index e4692492ff8b47..37d09ac8a19be3 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -758,18 +758,11 @@ impl RootV27_2 { } for (i, state) in states.iter().enumerate() { let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; - let sram_mv = match &sram_table { - Some(table) => { - let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); - if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz { - return Err(EINVAL); - } - let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); - if value < *mv || value > 1100 { return Err(EINVAL); } - value - } - None => (*mv).max(850), - }; + let (freq, voltage) = sram_table[i * 8..i * 8 + 8].split_at(4); + let sram_mv = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || sram_mv < *mv || sram_mv == 0 { + return Err(EINVAL); + } let mhz = state.freq_hz / 1_000_000; for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { put32(hw, series + i * 4, mhz); @@ -911,8 +904,8 @@ impl RootV27_2 { } /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` - /// (frequency and SRAM millivolts per state), if it published one. The node itself must exist. - fn sram_table(states: usize) -> Result>> { + /// (frequency and SRAM millivolts per state). + fn sram_table(states: usize) -> Result> { let chosen = kernel::of::chosen().ok_or(ENODEV)?; let is = |name: Option>, want: &[u8]| { name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) @@ -921,8 +914,9 @@ impl RootV27_2 { if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } for child in parent.children() { if is(child.get_opt_property::>(c"name")?, b"sgx") { - let table = child.get_opt_property::>(c"adt-perf-states-sram")?; - if table.as_ref().is_some_and(|t| t.len() != states * 8) { return Err(EINVAL); } + let table = child.get_opt_property::>(c"adt-perf-states-sram")? + .ok_or(ENODEV)?; + if table.len() != states * 8 { return Err(EINVAL); } return Ok(table); } } From 4b0be5d855d1244f0438842caddbcfc4d54ee3f1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:38:25 +1100 Subject: [PATCH 0657/1514] media: apple: avd: repair the VP9 host control fixture The VP9 decoder copies request controls under the V4L2 control lock. Provide lock and allocation shims so the standalone host test builds. Exercise the busy-bank check through avd_vp9_run() so it also checks the production cleanup path under the sanitizers. Signed-off-by: Ryan Murray --- .../platform/apple/avd/tests/vp9-test.py | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index c6ccf836b4636a..0ea406aae17773 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -59,7 +59,7 @@ enum vb2_buffer_state { STATE_DUMMY }; #define dev_err(d,...) ((void)(d)) #define kzalloc(n,f) calloc(1,n) -#define kfree free +#define kfree(p) free((void *)(p)) static bool vp_feature = true; static bool avd_qfw_has_vp_done(const struct avd_dev *d) { return d->queued && vp_feature; } static bool avd_backend_is_open(const struct avd_dev *d) { return !d->queued; } @@ -72,6 +72,32 @@ static struct v4l2_ctrl_vp9_frame params; static struct v4l2_ctrl_vp9_compressed_hdr updates; static struct v4l2_ctrl frame_ctrl,update_ctrl; +static struct v4l2_ctrl *locked_ctrl; + +static void v4l2_ctrl_lock(struct v4l2_ctrl *ctrl) +{ + assert(!locked_ctrl); + locked_ctrl = ctrl; +} + +static void v4l2_ctrl_unlock(struct v4l2_ctrl *ctrl) +{ + assert(locked_ctrl == ctrl); + locked_ctrl = NULL; +} + +static void *kmemdup(const void *source, size_t size, int flags) +{ + void *copy; + + (void)flags; + assert(locked_ctrl); + copy = malloc(size); + if (copy) + memcpy(copy, source, size); + return copy; +} + static struct v4l2_ctrl *v4l2_ctrl_find(void *h,u32 id) { (void)h;frame_ctrl.p_cur.p=¶ms;update_ctrl.p_cur.p=&updates; return id==V4L2_CID_STATELESS_VP9_FRAME?&frame_ctrl:&update_ctrl; @@ -184,8 +210,7 @@ def without_includes(s): assert(!memcmp(&adapted,&p->bank[1].probability_tables,sizeof(adapted))); write_program(argv[1],"vp9-adaptive-1",&frame); assert(!avd_vp9_ready(&ctx)); - struct avd_vp9_run attempt; - current_dst=&dst[2].base.vb;assert(avd_vp9_run_preamble(&ctx,&attempt)==-EBUSY);assert(!dst[2].bank); + current_dst=&dst[2].base.vb;assert(avd_vp9_run(&ctx)==-EBUSY);assert(!dst[2].bank); /* PP(0) retires while b points to bank 1: only bank 0 may be released. */ avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); assert(!p->bank[0].busy&&p->bank[1].busy&&!dst[0].bank); From f793bc2dd546cdbb3b4c993aa8462ada0cb50d14 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:39:57 +1100 Subject: [PATCH 0658/1514] media: apple: ave: run the command KUnit suites with the module Link the ABI, MCTF and CMP420 suites with apple-ave so KUnit can run them when the encoder is built as a module. Keep the test option unavailable when a built-in encoder would call into modular KUnit. Use the driver metadata for the linked suites and describe the separate recovery test module. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/Kconfig | 3 ++- drivers/media/platform/apple/ave/Makefile | 2 +- drivers/media/platform/apple/ave/ave-abi-test.c | 3 --- drivers/media/platform/apple/ave/ave-cmp420-test.c | 4 ---- drivers/media/platform/apple/ave/ave-mctf-test.c | 4 ---- drivers/media/platform/apple/ave/ave-recovery-test.c | 1 + 6 files changed, 4 insertions(+), 13 deletions(-) diff --git a/drivers/media/platform/apple/ave/Kconfig b/drivers/media/platform/apple/ave/Kconfig index 0924ce46210276..efd51eedd4ff04 100644 --- a/drivers/media/platform/apple/ave/Kconfig +++ b/drivers/media/platform/apple/ave/Kconfig @@ -35,7 +35,8 @@ config VIDEO_APPLE_AVE_KUNIT_TEST config VIDEO_APPLE_AVE_CMD_KUNIT_TEST bool "KUnit tests for Apple AVE firmware ABIs" if !KUNIT_ALL_TESTS - depends on KUNIT && VIDEO_APPLE_AVE=y + depends on VIDEO_APPLE_AVE && KUNIT + depends on KUNIT=y || VIDEO_APPLE_AVE=m default KUNIT_ALL_TESTS help Compare AVC/HEVC 9003 Start and Process images byte for byte with diff --git a/drivers/media/platform/apple/ave/Makefile b/drivers/media/platform/apple/ave/Makefile index 03d3b1bba4978b..2d5d28d39454a4 100644 --- a/drivers/media/platform/apple/ave/Makefile +++ b/drivers/media/platform/apple/ave/Makefile @@ -4,4 +4,4 @@ obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave.o obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave-dma.o apple-ave-y := ave-drv.o ave-fw.o ave-ipc.o ave-cmd.o ave-writer.o ave-abi.o ave-layout.o ave-image.o ave-sess.o ave-v4l2.o ave-vb2.o ave-mctf.o ave-mctf-v4l2.o ave-cmp420.o obj-$(CONFIG_VIDEO_APPLE_AVE_KUNIT_TEST) += ave-sizes-test.o ave-recovery-test.o -obj-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o +apple-ave-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 20e83305a7c780..72b7d969169c34 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -2,7 +2,6 @@ /* Byte equality against the pre-ABI-refactor 9003 command builders. */ #include #include -#include #include #include #include @@ -1644,5 +1643,3 @@ static struct kunit_suite ave_abi_suite = { .test_cases = ave_abi_cases, }; kunit_test_suite(ave_abi_suite); - -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-cmp420-test.c b/drivers/media/platform/apple/ave/ave-cmp420-test.c index 1fb59e6a6c8158..e350f62c2f2164 100644 --- a/drivers/media/platform/apple/ave/ave-cmp420-test.c +++ b/drivers/media/platform/apple/ave/ave-cmp420-test.c @@ -9,7 +9,6 @@ * Copyright The Aurora Silicon Contributors */ #include -#include #include #include @@ -462,6 +461,3 @@ static struct kunit_suite ave_cmp420_suite = { .test_cases = ave_cmp420_cases, }; kunit_test_suite(ave_cmp420_suite); - -MODULE_DESCRIPTION("Apple AVE compressed 4:2:0 surface tests"); -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-mctf-test.c b/drivers/media/platform/apple/ave/ave-mctf-test.c index 519d1d09043b30..b75001659f882c 100644 --- a/drivers/media/platform/apple/ave/ave-mctf-test.c +++ b/drivers/media/platform/apple/ave/ave-mctf-test.c @@ -9,7 +9,6 @@ * Copyright The Aurora Silicon Contributors */ #include -#include #include #include #include @@ -439,6 +438,3 @@ static struct kunit_suite ave_mctf_suite = { .test_cases = ave_mctf_cases, }; kunit_test_suite(ave_mctf_suite); - -MODULE_DESCRIPTION("Apple AVE MCTF command image tests"); -MODULE_LICENSE("GPL"); diff --git a/drivers/media/platform/apple/ave/ave-recovery-test.c b/drivers/media/platform/apple/ave/ave-recovery-test.c index a5166265d826c8..7b0c3fbf414fa7 100644 --- a/drivers/media/platform/apple/ave/ave-recovery-test.c +++ b/drivers/media/platform/apple/ave/ave-recovery-test.c @@ -116,4 +116,5 @@ static struct kunit_suite ave_recovery_suite = { kunit_test_suite(ave_recovery_suite); +MODULE_DESCRIPTION("Apple AVE firmware recovery window tests"); MODULE_LICENSE("GPL"); From 002e5071067d1c7ae3cb28dd81aff48115c06652 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:57:29 +1100 Subject: [PATCH 0659/1514] drm/apple: dcp: say dcp_sleep_keeps_firmware() is for late suspend only It takes the DCP's device lock, which can sleep, so a noirq caller must not use it. Its only caller is the DP audio late suspend. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index b4ff87f88c24c3..7852d5e22a4920 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9744,8 +9744,9 @@ static void dcp_t8132_sleep_stopped(struct apple_dcp *dcp) * dcp_sleep_keeps_firmware - whether a DCP's firmware runs through this sleep * @dev: the DCP device * - * For blocks the DCP's firmware drives (DP audio), from their late or noirq - * suspend, after every device's .suspend: true when the DCP's suspend left + * For blocks the DCP's firmware drives (DP audio), from their late suspend, + * after every device's .suspend. It takes the DCP's device lock, which can + * sleep, so it is not for the noirq phase. True when the DCP's suspend left * its coprocessor running with its domains on, or when no driver is bound * (a boot stage or an earlier bind may have left the firmware running). * False when the suspend stopped the firmware (S2R, the 27.x sleep, an M4 From 41a02cefcf581d3905149bd012353d73ee69fc12 Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 23 Nov 2026 08:15:57 -0500 Subject: [PATCH 0660/1514] aurora-sep: selinux: allow catacomb publication by atomic replacement A kernel that publishes a catacomb by atomic replacement writes the complete file under a fixed temporary name, "..new", in /var/lib, and renames it over the catacomb. SELinux labels a file when it is created and rename keeps that label, so the temporary must be created with the state type, not var_lib_t. Give the three temporary names aurora_sep_state_t with type_transition rules and file contexts, and let the kernel set attributes on (to reset a temporary's mode to 0600 after a restrictive caller umask), rename and unlink state files. Bump the module to 1.4.0 and the package to 1-14. This policy has to be installed before a kernel with atomic catacomb replacement, so it lands and ships on its own first. It only adds labels and permissions; current kernels are unaffected. Signed-off-by: Matt --- tools/aurora-sep/aurora_sep.fc | 1 + tools/aurora-sep/aurora_sep.te | 11 +++++++++-- .../aurora-sep/packaging/fedora/aurora-sep.spec | 8 +++++++- .../aurora-sep/tests/test_sep_selinux_state.py | 17 +++++++++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/tools/aurora-sep/aurora_sep.fc b/tools/aurora-sep/aurora_sep.fc index 66e04fb5890441..45e11dbc682e7b 100644 --- a/tools/aurora-sep/aurora_sep.fc +++ b/tools/aurora-sep/aurora_sep.fc @@ -1,5 +1,6 @@ /dev/sep-bio -c gen_context(system_u:object_r:aurora_sep_device_t,s0) /var/lib/apple-sep-catacomb-(master|owner|user)\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) +/var/lib/\.apple-sep-catacomb-(master|owner|user)\.bin\.new -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-keybag\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-refkey(-v2)?\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) /var/lib/aurora-sep-host-state\.bin -- gen_context(system_u:object_r:aurora_sep_state_t,s0) diff --git a/tools/aurora-sep/aurora_sep.te b/tools/aurora-sep/aurora_sep.te index 55a33bea69b3f0..ff0189e4803238 100644 --- a/tools/aurora-sep/aurora_sep.te +++ b/tools/aurora-sep/aurora_sep.te @@ -1,4 +1,4 @@ -policy_module(aurora_sep, 1.3.0) +policy_module(aurora_sep, 1.4.0) ######################################## # @@ -39,10 +39,17 @@ gen_require(` # The driver opens its state files with kernel credentials (store_shim.c), so # the kernel creates them. Give each new file the state type by name: a file # that the kernel creates in /var/lib must never start out as var_lib_t. -allow kernel_t aurora_sep_state_t:file { create_file_perms rw_file_perms }; +allow kernel_t aurora_sep_state_t:file { create_file_perms rw_file_perms setattr_file_perms rename_file_perms delete_file_perms }; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-master.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-owner.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "apple-sep-catacomb-user.bin"; +# The driver publishes a catacomb by renaming a complete "..new" over it. +# Rename keeps the inode's label, so label the temporary too. The kernel resets +# the temporary's mode to 0600 when a caller's umask cleared bits from it, and +# unlinks a temporary left by an interrupted replacement. +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-master.bin.new"; +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-owner.bin.new"; +type_transition kernel_t var_lib_t:file aurora_sep_state_t ".apple-sep-catacomb-user.bin.new"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-keybag.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-refkey.bin"; type_transition kernel_t var_lib_t:file aurora_sep_state_t "aurora-sep-refkey-v2.bin"; diff --git a/tools/aurora-sep/packaging/fedora/aurora-sep.spec b/tools/aurora-sep/packaging/fedora/aurora-sep.spec index 7a1ba80b0514d6..81357466315c06 100644 --- a/tools/aurora-sep/packaging/fedora/aurora-sep.spec +++ b/tools/aurora-sep/packaging/fedora/aurora-sep.spec @@ -8,7 +8,7 @@ Name: aurora-sep Version: 1 -Release: 13%{?dist} +Release: 14%{?dist} Summary: Loader and desktop integration for the Apple SEP fingerprint driver License: GPL-2.0-only @@ -197,6 +197,12 @@ fi %ghost %verify(not md5 size mode mtime) %{_sharedstatedir}/selinux/%{selinuxtype}/active/modules/200/%{modulename} %changelog +* Mon Nov 23 2026 Matt - 1-14 +- aurora-sep-selinux 1.4.0: label the kernel's catacomb replacement files + (/var/lib/.apple-sep-catacomb-*.bin.new) as SEP state at creation, and let + the kernel set the mode of (setattr), rename and unlink state files. Install + it before a kernel that publishes catacombs by atomic replacement. + * Fri Nov 20 2026 Diljit Singh - 1-13 - SEP writes are always on: aurora-sep-load runs modprobe apple_sep with no options, since the driver no longer has xart_writes or provision_keybag diff --git a/tools/aurora-sep/tests/test_sep_selinux_state.py b/tools/aurora-sep/tests/test_sep_selinux_state.py index 764b760e5845d0..b41a4d5acbc13e 100644 --- a/tools/aurora-sep/tests/test_sep_selinux_state.py +++ b/tools/aurora-sep/tests/test_sep_selinux_state.py @@ -19,6 +19,8 @@ 'aurora-sep-host-state.bin', 'aurora-sep-xart-owned.bin', 'aurora-sep-xart-allow-once.bin', 'aurora-sep-xart-policy-previous.bin', ] +# Temporary names the kernel renames over the catacombs. +TEMPORARY = ['.%s.new' % name for name in STATE[:3]] class SelinuxModuleTests(unittest.TestCase): @@ -52,6 +54,21 @@ def test_the_kernel_creates_each_file_with_the_state_type(self): 'type_transition kernel_t var_lib_t:file aurora_sep_state_t "%s";' % name, self.te) + def test_replacement_temporaries_get_the_state_type(self): + # Rename keeps the temporary inode's label, so it must be created with + # the state type, not var_lib_t. + for name in TEMPORARY: + hits = [c for r, k, c in self.contexts() if r.match('/var/lib/' + name)] + self.assertEqual(len(hits), 1, name) + self.assertIn(':aurora_sep_state_t,', hits[0], name) + self.assertIn( + 'type_transition kernel_t var_lib_t:file aurora_sep_state_t "%s";' % name, + self.te) + # The kernel fixes the temporary's mode after a restrictive umask + # (setattr), renames it over the catacomb, and unlinks a leftover. + self.assertRegex(self.te, r'allow kernel_t aurora_sep_state_t:file \{[^}]*' + r'setattr_file_perms rename_file_perms delete_file_perms \};') + def test_no_access_to_generic_var_lib(self): self.assertNotRegex(self.te, r'allow\s+\S+\s+var_lib_t') From c66f5a48379d5d014543a88fc635afc96e79e81a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:36:23 +1100 Subject: [PATCH 0661/1514] selftests: apple-dcp: model the startup hotplug flush Stub the startup report flush in the readiness fixture and count its calls. Successful initialization flushes once, while failed or deferred initialization does not flush. Supply the panel predicate for this fixture and remove the obsolete sleep stub. The Apple DCP host suite passes all 88 cases. Signed-off-by: Ryan Murray --- .../drivers/gpu/apple-dcp/lifecycle.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index 9aa4f2041961b6..8a6ce6a311f1cc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1501,7 +1501,6 @@ def function(source, marker): #define DRM_MODE_CONNECTOR_HDMIA 11 #define DRM_MODE_CONNECTOR_eDP 14 #define DRM_MODE_CONNECTOR_USB 20 -#define msleep(x) ((void)(x)) #define component_compare_of 0 #define apple_dcp_id_tbl 0 static int dcp_comp_ops; @@ -1552,7 +1551,17 @@ def function(source, marker): static struct component_match matches; static bool machine_supported, absent_external; static unsigned int references, released, node_puts, probes[2], bind_attempts, disables; +static unsigned int start_report_flushes; static int preflight_error, external_probe_error, bind_result; +static void apple_drm_flush_start_reports(struct drm_device *drm) +{ + assert(drm == &priv.drm); + start_report_flushes++; +} +/* The J700 readiness scenarios do not have a J713 panel. */ +#ifndef iomfb_is_m4 +static bool iomfb_is_m4(struct apple_dcp *dcp) { (void)dcp; return false; } +#endif static void try_bind(void); static bool of_machine_is_compatible(const char *s) { assert(!strcmp(s,"apple,j700")); return machine_supported; } @@ -1668,6 +1677,7 @@ def function(source, marker): } absent_external = false; references = released = node_puts = bind_attempts = disables = 0; + start_report_flushes = 0; preflight_error = external_probe_error = bind_result = 0; } static int match_providers(void) @@ -1702,16 +1712,19 @@ def function(source, marker): assert(!dcp_h17p_external_ready(&nodes[1]) && references == 0); try_bind(); assert(bind_attempts == 1 && bind_result == 0 && probes[0] == 1 && !probes[1]); + assert(start_report_flushes == 1); /* Delayed external provider remains in the match; the master must wait. */ initial(true); assert(match_providers() == 2 && matches.includes[1]); try_bind(); assert(bind_attempts == 0 && !probes[0] && !probes[1]); + assert(start_report_flushes == 0); /* Last provider is prepared, but driver core bound is still false here. */ assert(publish_provider(&devices[1], &dcps[1]) == 0); assert(dcps[1].external_prepared && !devices[1].bound); assert(bind_attempts == 1 && bind_result == 0 && probes[0] == 1 && probes[1] == 1); + assert(start_report_flushes == 1); devices[1].bound = true; /* Permanent preflight failure cannot silently drop a requested provider. */ @@ -1756,6 +1769,7 @@ def function(source, marker): dcps[1].external_prepared = true; if (failure) start_error[0] = -EIO; else ready_error[0] = -ETIMEDOUT; assert(apple_drm_init_dcp(&master) == -ENODEV); + assert(start_report_flushes == 0); /* A processor that did not start is not waited for. */ assert(starts[0] == 1 && waits[0] == (int)!failure && waits[1] == 1); } @@ -1764,10 +1778,12 @@ def function(source, marker): dcps[1].external_prepared = true; ready_error[1] = -ETIMEDOUT; assert(apple_drm_init_dcp(&master) == 0); + assert(start_report_flushes == 1); initial(true); dcps[1].external_prepared = true; start_error[1] = -EIO; assert(apple_drm_init_dcp(&master) == 0 && waits[1] == 0); + assert(start_report_flushes == 1); puts("PASS: automatic hardware/firmware matching, delayed/preflight-failed providers, synchronous publication, readiness rejection, boot framebuffer kept without the panel processor"); return 0; } From e317c219a6426e4a99815261e802a65636f15be1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:43:04 +1100 Subject: [PATCH 0662/1514] drm/apple: preserve the 13.5 DCP compatibility fallback Keep the 13.3 compatibility alias for 13.5 firmware on the T8112 DCP paths. The firmware contract covers both the primary and external DCP. The orphan trace source deletion remains independent. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4d908cf3d2d79b..7cde46e009096f 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5934,6 +5934,16 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) if (strncmp(compat_str, "12.3.0", sizeof(compat_str)) == 0) return DCP_FIRMWARE_V_12_3; + /* + * m1n1 reports firmware version 13.5 as compatible with 13.3. This is + * only true for the iomfb endpoint. The interface for the dptx-port + * endpoint changed between 13.3 and 13.5. The driver will only support + * firmware 13.5. Check the actual firmware version for compat version + * 13.3 until m1n1 reports 13.5 as "firmware-compat". + */ + else if ((strncmp(compat_str, "13.3.0", sizeof(compat_str)) == 0) && + (strncmp(fw_str, "13.5.0", sizeof(compat_str)) == 0)) + return DCP_FIRMWARE_V_13_5; else if (strncmp(compat_str, "13.5.0", sizeof(compat_str)) == 0) return DCP_FIRMWARE_V_13_5; else if (strncmp(compat_str, "14.7.0", sizeof(compat_str)) == 0 && From 9111ff5b88741778a2f36778cf90eb80d8144034 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:43:45 +1100 Subject: [PATCH 0663/1514] drm/asahi: select G14 by firmware compatibility and signal suspend drain Select the wire layout from the loader compatibility tuple before starting the GPU and pass the register description selected by the GPU compatible. Notify suspend when the in-flight queue empties. Pending commands stay held until resume, and unrelated wakeups exhaust the original timeout budget. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 40 ++++++++++++++++-------------- drivers/gpu/drm/asahi/g14_v27_2.rs | 31 +++++++++++++---------- 2 files changed, 39 insertions(+), 32 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index ae25ebbd5255b3..95971eaac30315 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -153,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver { /// Firmware interface selected by the hardware compatible. pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), + LegacyWithG14Handoff(&'static hw::HwConfig), G17(&'static g17::Config), /// M5 Pro, Max and Ultra: the ID registers select the configuration. G17M5, @@ -200,7 +201,7 @@ macro_rules! asahi_of_device_table { ), ( of::DeviceId::new(c"apple,agx-t8112"), - ProbeConfig::Legacy(&hw::t8112::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8112::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t6000"), @@ -376,8 +377,9 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); - let cfg = match info.ok_or(ENODEV)? { - ProbeConfig::Legacy(cfg) => *cfg, + let (cfg, has_g14_handoff) = match info.ok_or(ENODEV)? { + ProbeConfig::Legacy(cfg) => (*cfg, false), + ProbeConfig::LegacyWithG14Handoff(cfg) => (*cfg, true), ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) } @@ -391,16 +393,19 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => return Err(ENODEV), }; - // G14 with firmware 27.2 has its own root and start sequence (g14_v27_2.rs). - if (cfg.gpu_gen, cfg.gpu_variant) == (hw::GpuGen::G14, hw::GpuVariant::G) { - let version: Option> = pdev.as_ref().fwnode().ok_or(EIO)? - .property_read_array_vec(c"apple,firmware-version", 3)?.optional(); - if version.as_deref() == Some(&[27, 2, 0]) { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] - return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg); - #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] - return Err(ENODEV); - } + let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; + let compat: KVec = fwnode + .property_read_array_vec(c"apple,firmware-compat", 3)? + .required_by(pdev.as_ref())?; + + // The loader advertises the supported wire layout independently of the image version. + if has_g14_handoff && compat.as_slice() == [27, 2, 0] { + #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + return AsahiPlatformDriver::probe_g14_v27_2( + pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2, + ); + #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] + return Err(ENODEV); } // SAFETY: The selected SoC's UAT output width bounds all device DMA. @@ -414,11 +419,6 @@ impl platform::Driver for AsahiPlatformDriver { // Start the coprocessor CPU, so UAT can initialize the handoff regs::Resources::start_cpu(pdev)?; - let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; - let compat: KVec = fwnode - .property_read_array_vec(c"apple,firmware-compat", 3)? - .required_by(pdev.as_ref())?; - let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; // probe errors drop this local owner while the bound callback is live. @@ -503,9 +503,11 @@ impl AsahiPlatformDriver { fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, ) -> Result> { let crate::g14_v27_2::Started { backend, drm, binding, resources } = - crate::g14_v27_2::start(pdev, cfg)?; + crate::g14_v27_2::start(pdev, cfg, registers, writable)?; let gpu = backend.clone() as Arc; let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); // SAFETY: The registration is stored in the platform data and unregistered when it is diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 682a23f0c96e2b..b77cd15cc9a20d 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -24,7 +24,7 @@ use kernel::{ platform, prelude::*, soc::apple::rtkit, - sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, workqueue::{impl_has_work, OwnedQueue, Work, WorkItem}, @@ -211,14 +211,14 @@ pub(crate) struct Started<'a> { } /// Starts the firmware and retires the boot job. -pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'static hw::HwConfig) - -> Result> { +pub(crate) fn start<'a>( + pdev: &'a platform::Device>, + cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, +) -> Result> { use kernel::dma::{Device as _, DmaMask}; let dev: &device::Device = pdev.as_ref(); - let (registers, writable) = match cfg.chip_id { - 0x8112 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), - _ => return Err(ENODEV), - }; let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; @@ -566,7 +566,11 @@ impl Runtime { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { return; }; self.service_locked(state); - if state.inflight.is_empty() && state.pending.is_empty() { self.idle.notify_all(); } + if state.inflight.is_empty() + && (state.pending.is_empty() || self.asleep.load(Ordering::Acquire)) + { + self.idle.notify_all(); + } } fn service_locked(&self, state: &mut State) { @@ -647,7 +651,7 @@ impl Runtime { // Hold publications first, then let what is published retire. User space is frozen by // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. self.asleep.store(true, Ordering::Release); - let start = Instant::::now(); + let mut remaining = msecs_to_jiffies(STOP_DRAIN_MS); loop { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } @@ -656,15 +660,16 @@ impl Runtime { state.submitted, state.retired, state.pending.len()); return Ok(()); } - if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) { + if remaining == 0 { dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len()); self.asleep.store(false, Ordering::Release); self.pump(state); return Err(EBUSY); } - // The service retires on notifications; `idle` is signalled only when nothing at all - // is left, so look again every 50 ms. - let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(50)); + remaining = match self.idle.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => jiffies, + _ => 0, + }; } } From 76652df07eebdd5ced405ec32c79b0f074f2fcbf Mon Sep 17 00:00:00 2001 From: Alyx-ML <256263590+Alyx-ML@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:10:51 +0000 Subject: [PATCH 0664/1514] power: supply: macsmc: set up work before the notifier, and wait for it at remove Probe registered the SMC notifier and then ran INIT_WORK() on critical_work again. devm_work_autocancel() had already set it up. An SMC critical-battery event that came in between could have its queued work reset under it. dbg_log_work was set up only after the notifier. Remove used cancel_work() and cancel_delayed_work(), which do not wait, and unregistered the notifier last. The debug work re-arms itself, so it could run, or queue itself again, after devm had freed the driver state. Set up both work items before anything can queue them, and drop the second INIT_WORK(). At remove, unregister the notifier and clear g_power first. Then disable_delayed_work_sync() the debug work and cancel_work_sync() the critical work. Two comments say what stays as it is. Probe does not reset the charge inhibitors, as commit b8e84d08eef5 ("power: supply: macsmc: Preserve firmware charge settings at probe") decided. The user's CHLS limit during a CHLS_HOLD is kept in RAM only, so a hold found at probe has no known limit. Probe now logs that case. Verified: read against the workqueue and devm helpers. Not compiled or run here (macOS host). KUnit for this file has no probe or remove case. Signed-off-by: Alyx-ML <256263590+Alyx-ML@users.noreply.github.com> --- drivers/power/supply/macsmc-power.c | 32 ++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/drivers/power/supply/macsmc-power.c b/drivers/power/supply/macsmc-power.c index 5bd714eaf1b276..edb2d769f78339 100644 --- a/drivers/power/supply/macsmc-power.c +++ b/drivers/power/supply/macsmc-power.c @@ -105,7 +105,11 @@ struct macsmc_power { /* * Where neither CHTE nor CH0C exists, inhibit-charge holds the charge * at the current level with CHLS_HOLD; the user's own CHLS limit is - * kept here meanwhile and restored when the hold ends. + * kept here meanwhile and restored when the hold ends. It is kept in + * RAM only: the SMC has no spare key for it. If the driver binds while + * a hold from an earlier boot or binding is still set, the earlier + * limit is unknown, so the end threshold reads 100 and ending the hold + * leaves no limit. Userspace that sets both should set the limit again. */ u8 chls_user_limit; /* Battery critical key (BCF0) is 1 byte (Modern firmware) */ @@ -1102,10 +1106,10 @@ static int macsmc_power_probe(struct platform_device *pdev) return ret; dev_set_drvdata(dev, power); - INIT_WORK(&power->critical_work, macsmc_power_critical_work); ret = devm_work_autocancel(dev, &power->critical_work, macsmc_power_critical_work); if (ret) return ret; + INIT_DELAYED_WORK(&power->dbg_log_work, macsmc_dbg_work); /* * Check for battery presence. @@ -1211,7 +1215,11 @@ static int macsmc_power_probe(struct platform_device *pdev) of_machine_is_compatible("apple,j700"); power->status_from_current = of_machine_is_compatible("apple,j700"); - /* Preserve firmware charge policy until userspace changes it. */ + /* + * Preserve firmware charge policy until userspace changes it: + * the inhibitors (CHTE, CH0C, CH0I) and CH0K/CH0B persist in the + * SMC, and binding the driver is not a request to reset them. + */ /* Detect charge limit method (CHWA vs CHLS) */ if (apple_smc_read_flag(power->smc, SMC_KEY(CHWA), &flag) == 0) power->has_chwa = true; @@ -1221,6 +1229,8 @@ static int macsmc_power_probe(struct platform_device *pdev) if (power->has_chls && (vu16 & CHLS_FORCE_DISCHARGE) && !macsmc_chls_has_limit(vu16)) dev_warn(dev, "CHLS force-discharge without a limit; select charge_behaviour=auto to clear\n"); + if (power->has_chls && macsmc_chls_holds(power, vu16)) + dev_info(dev, "CHLS holds the charge from an earlier boot; the charge limit before it is not known\n"); /* * CHLS carries auto-discharge, so a CHLS-only Mac can select auto @@ -1308,12 +1318,10 @@ static int macsmc_power_probe(struct platform_device *pdev) if (!power->batt && !power->ac) return -ENODEV; + /* Both work items were set up above, before anything can queue them. */ power->nb.notifier_call = macsmc_power_event; blocking_notifier_chain_register(&smc->event_handlers, &power->nb); - INIT_WORK(&power->critical_work, macsmc_power_critical_work); - INIT_DELAYED_WORK(&power->dbg_log_work, macsmc_dbg_work); - g_power = power; if (log_power) @@ -1326,12 +1334,16 @@ static void macsmc_power_remove(struct platform_device *pdev) { struct macsmc_power *power = dev_get_drvdata(&pdev->dev); - cancel_work(&power->critical_work); - cancel_delayed_work(&power->dbg_log_work); - + /* + * Stop new work first: the notifier queues the critical work and the + * log_power parameter queues the log through g_power. The debug work + * re-arms itself, so disable it and wait, as devm frees power next. + */ + blocking_notifier_chain_unregister(&power->smc->event_handlers, &power->nb); g_power = NULL; - blocking_notifier_chain_unregister(&power->smc->event_handlers, &power->nb); + disable_delayed_work_sync(&power->dbg_log_work); + cancel_work_sync(&power->critical_work); } /* From e5f348ef1f43ebd307f81c8e3f21615c90264d35 Mon Sep 17 00:00:00 2001 From: Friedrich <261542475+aeries0x@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:50:58 +0100 Subject: [PATCH 0665/1514] drm/asahi: g16: reuse a pass slot's retired PB epoch Every G16 render gets a fresh parameter buffer epoch at SUBMIT and an InitBM ahead of its TA work, so the firmware rebuilds the allocator state for each render. Reusing the epoch instead cuts a small triangle render at queue depth 1 on a base M4 MacBook Pro (J604) from 1121 to 492 us. With this change, the next render of the same VM on a pass slot gets the slot's owner epoch, without a reseed or InitBM, if that epoch's render retired normally and was exposed. InitBM binds the device-wide slot to one epoch and VM, so this happens only while no other epoch was handed to the slot since; after another VM's render on the slot, after a failed or aborted render, after any firmware recovery, or after a deep-sleep firmware restart, the next render starts fresh. SUBMIT still allocates a fresh epoch for every render, so one is always at hand. Renders are bound, published and retired one at a time, so the slot's owner is the epoch it is bound to whenever reuse is allowed. The reused epoch is the slot's existing owner lease, so this holds no epoch, VM or admission permit beyond what the lease already holds: a slot binding is tracked by a counter, not by a reference. A host test covers when an epoch may be reused and that nothing else holds it. The stats line counts reused and fresh bindings. Signed-off-by: Friedrich <261542475+aeries0x@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/engine.rs | 44 ++++++++-- drivers/gpu/drm/asahi/g16/poll.rs | 12 ++- drivers/gpu/drm/asahi/g16/pools.rs | 85 +++++++++++++++++-- drivers/gpu/drm/asahi/g16/recovery.rs | 3 + drivers/gpu/drm/asahi/g16/sleep.rs | 2 + .../drivers/gpu/asahi-m4/test-resources.py | 23 ++++- 6 files changed, 150 insertions(+), 19 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 5ee33d71432d1a..fcf1487f6e7d60 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -180,6 +180,10 @@ pub(crate) struct Flight { pub(crate) recovery_started_ns: u64, /// Publication time, ns. pub(crate) published_ns: u64, + /// The PB epoch this render prefix uses (its own, or a reused retired epoch). + pub(crate) pb: Option>, + /// Its pass slot binding (`Pools::bind`). + pub(crate) pb_binding: u64, } impl Flight { @@ -209,6 +213,8 @@ impl Flight { recovery_suspect: false, recovery_started_ns: 0, published_ns: 0, + pb: None, + pb_binding: 0, } } } @@ -872,12 +878,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)?)?; + // Reuse this VM's retired epoch of the pass slot: 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; + (e, true) + } + None => { + let e = job.resources.pb(job.progress.sent() as usize)?.clone(); + e.prepare(k, arena.pools.heap_gva(k)?)?; + 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 +932,8 @@ impl Firmware { usc_base: job.queue.usc_base, }, a.init_buffer, + epoch, + binding, )) } @@ -1033,8 +1059,8 @@ 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. @@ -1047,7 +1073,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. @@ -1263,7 +1289,9 @@ 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)?; + 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 +1350,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; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 4e9bfaef02e12f..ee18af8c20555f 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -494,9 +494,11 @@ 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| { - self.pools - .retire_binding(timestamp_claims.pass[0] as usize, 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)?; + self.pools.retire_epoch(k, f.pb_binding, result.is_ok()); + Ok(()) }); if let Err(error) = committed { self.retain(&f.job); @@ -518,6 +520,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); diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index d4a85cc6f3d361..fb73ff8ec17114 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -2,9 +2,11 @@ //! 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/heap units. 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,6 +69,10 @@ 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 { @@ -259,6 +265,12 @@ 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 or sleep restart. 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 +278,62 @@ 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 or sleep restart happened 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 or sleep restart 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 +343,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 pass +/// 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; diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index b0fc2ed96976cc..18975b812e2768 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/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index a383a09b8d9711..763407f9225b2c 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -59,6 +59,8 @@ impl Firmware { /// The run bit and the RTKit handshake, with the firmware's state as it was left. fn sleep_restart(&mut self) -> Result { + // Start the next render on each pass slot fresh after the firmware restarts. + self.pools.invalidate(); self.session.rtkit.warm_restart()?; let control = self.session.regs.asc_control()?; self.session.regs.set_asc_control(control | ASC_RUN)?; 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 a048447b1436a7..ca8e691bb84d7e 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -68,7 +68,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())}}} @@ -373,6 +373,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).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); + } } ''' From 8301fc463c47f39d2f29d3b062bf8e1c76466a0c Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Mon, 23 Nov 2026 02:43:17 -0800 Subject: [PATCH 0666/1514] soc: apple: rtkit: map a firmware-placed crash log only over checked DRAM apple_rtkit_crashlog_map() maps a crash log buffer the co-processor placed at its own address. It stepped by PAGE_SIZE from the buffer's address, which need not be page aligned, so the page holding its last bytes could go unchecked. It mapped whatever physical range the IOMMU named, without checking what memory that is. And it mapped it cacheable, although the co-processor's writes need not be coherent with the CPU's caches (the T6050 AOP's node isn't dma-coherent), while apple_rtkit_crashlog_late() polls the buffer, with no cache maintenance for a placed buffer, for a log written after the request. Take the range from apple_dart_fw_range(), through Linux's mappings and those the firmware kept, and map it write-combined. Whether such a buffer is mapped also had three answers, by how the firmware asked: a client flag kept it unmapped, a request on an announced crashlog endpoint was refused, and the crash report on an endpoint the firmware left out of its map was mapped, flag or not. apple_rtkit_maps_placed_crashlog() is now the one rule for both paths: unmapped when the client says the firmware owns the buffer, set up by the client when it has shmem_setup, and otherwise mapped through the checks above. A request on an announced endpoint from a client with neither is now mapped and acknowledged rather than refused. The host test tools/asahi/rtkit-crashlog-map-tests.py builds the functions unchanged against a 4 KiB-granular stand-in IOMMU and resource map. Aligned and unaligned buffers on contiguous pages, through either kind of mapping, are mapped write-combined; buffers that reach a page mapped elsewhere or not at all (at 16 KiB or 4 KiB stride), reach System RAM (including a carveout strictly past RAM sharing a 16 KiB CPU page with it), lie on registers, or run on an identity domain are refused. Routing via apple_rtkit_maps_placed_crashlog() is checked too. The code before this change fails the test. Fixes: d9b438c4ca41 ("arm64: apple: support coordinated suspend-to-RAM on T8140") Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/soc/apple/rtkit.c | 78 ++--- tools/asahi/rtkit-crashlog-map-tests.py | 391 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 3 files changed, 435 insertions(+), 37 deletions(-) create mode 100755 tools/asahi/rtkit-crashlog-map-tests.py diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6e..0dc8632ef29c5e 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -184,6 +184,21 @@ static bool apple_rtkit_firmware_owns_crashlog(struct apple_rtkit *rtk) return rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG; } +/* + * Whether RTKit maps a crash log the firmware placed at its own address: one rule for + * the buffer request on an endpoint the firmware announced and for the crash report on + * one it left out of its map. Not when the client says the firmware owns that buffer + * (taken unmapped) or sets placed buffers up itself (shmem_setup); otherwise it is + * mapped if apple_dart_fw_range() accepts it (apple_rtkit_crashlog_map()). + */ +static bool apple_rtkit_maps_placed_crashlog(struct apple_rtkit *rtk) +{ + return !apple_rtkit_firmware_owns_crashlog(rtk) && + !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep; +} + +static int apple_rtkit_crashlog_map(struct apple_rtkit *rtk, u64 msg); + /* The crashlog endpoint is started while the endpoint map is handled. */ static bool apple_rtkit_early_crashlog(struct apple_rtkit *rtk) { @@ -636,6 +651,14 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, return apple_rtkit_send_message(rtk, ep, msg, NULL, false); } + if (ep == APPLE_RTKIT_EP_CRASHLOG && request.iova && + apple_rtkit_maps_placed_crashlog(rtk)) { + err = apple_rtkit_crashlog_map(rtk, msg); + if (err) + goto error; + return 0; + } + if ((rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_LOGS) && request.iova && (ep == APPLE_RTKIT_EP_SYSLOG || ep == APPLE_RTKIT_EP_OSLOG)) { *buffer = request; @@ -936,52 +959,32 @@ static void apple_rtkit_memcpy(struct apple_rtkit *rtk, void *dst, len, DMA_FROM_DEVICE); } -/* - * Where a DVA of the crash buffer lands: in a mapping Linux made, or else in one the - * firmware kept from the bootloader in a root its DART inherited (the T8140 AOP's own - * slot). 0 when neither translates it. - */ -static phys_addr_t apple_rtkit_crashlog_phys(struct apple_rtkit *rtk, - struct iommu_domain *domain, dma_addr_t iova) -{ - phys_addr_t phys = iommu_iova_to_phys(domain, iova); - - if (!phys && IS_REACHABLE(CONFIG_APPLE_DART) && - apple_dart_fw_remote(rtk->dev, iova, false, &phys)) - phys = 0; - - return phys; -} - /* * The buffer a crashing firmware placed at its own address, mapped if its IOMMU - * translates every page of it to one contiguous range, and acknowledged as a placed + * translates every page of it, through Linux's mappings or those the firmware kept + * from the boot loader (the T8140 AOP's own slot), to one contiguous range of DRAM + * that nothing else claims (apple_dart_fw_range()), and acknowledged as a placed * buffer is. The firmware doesn't run again until a reboot. + * + * Write-combined, not cacheable: the co-processor isn't coherent with the CPU's + * caches, and apple_rtkit_crashlog_late() polls the buffer for a log written after + * the request, with no cache maintenance for a placed buffer, so a cacheable + * mapping could keep returning the header it read first. */ static int apple_rtkit_crashlog_map(struct apple_rtkit *rtk, u64 msg) { struct apple_rtkit_shmem *bfr = &rtk->crashlog_buffer; - struct iommu_domain *domain = iommu_get_domain_for_dev(rtk->dev); dma_addr_t iova = FIELD_GET(APPLE_RTKIT_BUFFER_REQUEST_IOVA, msg); size_t size = FIELD_GET(APPLE_RTKIT_BUFFER_REQUEST_SIZE, msg) << 12; - phys_addr_t phys, page; - size_t off; + phys_addr_t phys; void *va; + int ret; - if (!domain || !iova || !size) - return -ENODEV; - phys = apple_rtkit_crashlog_phys(rtk, domain, iova); - for (off = 0; phys && off < size; off += PAGE_SIZE) { - page = apple_rtkit_crashlog_phys(rtk, domain, iova + off); - if (page != phys + off) { - dev_err(rtk->dev, "RTKit: crash log at %pad isn't contiguous at +%#zx\n", - &iova, off); - return -EINVAL; - } - } - if (!phys) - return -ENOENT; - va = memremap(phys, size, MEMREMAP_WB); + ret = apple_dart_fw_range(rtk->dev, iova, size, + APPLE_DART_FW_LINUX | APPLE_DART_FW_RETAINED, &phys); + if (ret) + return ret; + va = memremap(phys, size, MEMREMAP_WC); if (!va) return -ENOMEM; bfr->buffer = va; @@ -1080,10 +1083,11 @@ static void apple_rtkit_crashlog_rx(struct apple_rtkit *rtk, u64 msg) * A firmware that never announced this endpoint asks for its buffer only when * it crashes, so there's no handshake to take the request for. Report the * crash now, as the log may never come. A client that sets such a buffer up - * itself takes the path below, which also reads a log written later. + * itself, or whose firmware owns it, takes the path below, which also reads a + * log written later (apple_rtkit_maps_placed_crashlog()). */ if (!rtk->crashlog_buffer.size && !test_bit(APPLE_RTKIT_EP_CRASHLOG, rtk->endpoints) && - !rtk->ops->shmem_setup && !rtk->ops->shmem_setup_ep) { + apple_rtkit_maps_placed_crashlog(rtk)) { int ret = apple_rtkit_crashlog_map(rtk, msg); dev_err(rtk->dev, "RTKit: co-processor has crashed: crash log buffer at %#llx %s (%d)\n", diff --git a/tools/asahi/rtkit-crashlog-map-tests.py b/tools/asahi/rtkit-crashlog-map-tests.py new file mode 100755 index 00000000000000..edebd17bc31e17 --- /dev/null +++ b/tools/asahi/rtkit-crashlog-map-tests.py @@ -0,0 +1,391 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check which crash log buffers a co-processor places that RTKit maps. + +apple_rtkit_crashlog_map(), apple_rtkit_maps_placed_crashlog() from +drivers/soc/apple/rtkit.c and apple_dart_fw_range() with its two helpers from +drivers/iommu/apple-dart.c are taken unchanged and built with ASan and UBSan +against a stand-in IOMMU (4 KiB granularity) and a stand-in resource map. The +buffer is mapped only when every IOMMU page it touches, through Linux's paging +mappings or those the firmware kept, translates at the same offset as its first +byte, and the CPU-page-rounded range is DRAM that isn't the kernel's System RAM. +Identity domains never answer APPLE_DART_FW_LINUX and are refused. Every +memremap() is checked against the pages the test gave the device and must be +write-combined. + +--old-ref REV runs the same checks on the driver at REV (its own walk, where +apple-dart.c has no apple_dart_fw_range()) and requires them to fail there. +""" +import argparse +from pathlib import Path +import re +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/soc/apple/rtkit.c' +DART = 'drivers/iommu/apple-dart.c' + + +def function(source, name): + """The definition of function name (a forward declaration is skipped).""" + pattern = r'^(?:static )?(?:void|int|bool|phys_addr_t)\s*\n?' + name + r'\(' + match = next((m for m in re.finditer(pattern, source, re.M) + if ';' not in source[m.end():source.index('{', m.end())]), None) + assert match, name + opening = source.index('{', match.end()) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[match.start():end] + '\n' + + +def constants(source): + out = [line for line in source.splitlines() + if re.match(r'#define APPLE_RTKIT_BUFFER_REQUEST_(SIZE|IOVA)\b', line)] + assert len(out) == 2, out + return '\n'.join(out) + '\n' + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef uint64_t dma_addr_t; typedef uint64_t phys_addr_t; +#define GENMASK_ULL(h,l) ((~0ULL << (l)) & (~0ULL >> (63-(h)))) +#define FIELD_GET(m,v) (((v) & (m)) >> __builtin_ctzll(m)) +#define PAGE_SIZE 16384UL +#define ALIGN_DOWN(x, a) ((x) & ~((__typeof__(x))(a) - 1)) +#define ALIGN(x, a) (((x) + ((__typeof__(x))(a) - 1)) & ~((__typeof__(x))(a) - 1)) +#define __ffs(x) ((unsigned long)__builtin_ctzl(x)) +#define check_add_overflow(a, b, d) __builtin_add_overflow(a, b, d) +#define IS_REACHABLE(x) 1 +#define CONFIG_APPLE_DART 1 +#define MEMREMAP_WB 1 +#define MEMREMAP_WC 4 +#define dev_err(...) ((void)0) +#define APPLE_RTKIT_EP_CRASHLOG 2 +#define APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG (1u << 0) +#define APPLE_DART_FW_LINUX (1u << 0) +#define APPLE_DART_FW_RETAINED (1u << 1) +#define EXPORT_SYMBOL_GPL(x) +#define __IOMMU_DOMAIN_PAGING (1u << 1) +#define IOMMU_DOMAIN_IDENTITY (1u << 2) +#define IOMMU_DOMAIN_DMA (__IOMMU_DOMAIN_PAGING | (1u << 3)) + +struct device { int unused; }; +struct iommu_domain { unsigned type; unsigned long pgsize_bitmap; }; +struct apple_rtkit_ops { + unsigned flags; + void *shmem_setup; + void *shmem_setup_ep; +}; +struct apple_rtkit_shmem { void *buffer; size_t size; dma_addr_t iova; bool is_mapped; }; +struct apple_rtkit { + struct device *dev; + const struct apple_rtkit_ops *ops; + struct apple_rtkit_shmem crashlog_buffer; + bool crashlog_placed; +}; +static bool apple_rtkit_firmware_owns_crashlog(struct apple_rtkit *rtk) +{ + return rtk->ops && (rtk->ops->flags & APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG); +} + +/* + * The device's IOMMU at 4 KiB granularity (4 subpages per 16 KiB block), so a + * 4 KiB pgsize_bitmap check genuinely tests subpage discontinuities. + */ +#define IOMMU_PAGE 0x4000ULL +#define SUB_PAGE 0x1000ULL +#define DVA_BASE 0x100000000ULL +#define NPAGES 16 +#define NSUB (NPAGES * 4) +static phys_addr_t table[NSUB], kept[NSUB]; +static struct iommu_domain the_domain = { + .type = IOMMU_DOMAIN_DMA, + .pgsize_bitmap = 0x4000 | 0x2000000, +}; + +static void map16(phys_addr_t *t, int page16, phys_addr_t phys) +{ + for (int s = 0; s < 4; s++) + t[page16 * 4 + s] = phys ? phys + s * SUB_PAGE : 0; +} + +static struct iommu_domain *iommu_get_domain_for_dev(struct device *dev) +{ + (void)dev; return &the_domain; +} +static phys_addr_t lookup(phys_addr_t *t, dma_addr_t iova) +{ + if (iova < DVA_BASE || iova >= DVA_BASE + NSUB * SUB_PAGE) + return 0; + phys_addr_t page = t[(iova - DVA_BASE) / SUB_PAGE]; + return page ? page + (iova & (SUB_PAGE - 1)) : 0; +} +static phys_addr_t iommu_iova_to_phys(struct iommu_domain *d, dma_addr_t iova) +{ + if (d->type == IOMMU_DOMAIN_IDENTITY) + return iova; + return lookup(table, iova); +} +/* + * As the driver's: identity domains have no owner (-ENODEV), and a DVA Linux + * mapped itself is refused (-EACCES). + */ +static int apple_dart_fw_remote(struct device *dev, dma_addr_t iova, bool write, phys_addr_t *phys) +{ + (void)dev; (void)write; + if (the_domain.type == IOMMU_DOMAIN_IDENTITY) + return -ENODEV; + if (lookup(table, iova)) + return -EACCES; + *phys = lookup(kept, iova); + return *phys ? 0 : -ENXIO; +} + +/* + * The resource map: registers below 0x800000000, System RAM (the kernel's) at + * 0x800000000-0x87fffcfff (ending mid-16 KiB CPU page so CPU-page rounding is + * genuinely exercised), and above it DRAM the kernel doesn't use (carveouts). + */ +#define IORESOURCE_MEM 0x200 +#define IORESOURCE_SYSTEM_RAM 0x1200 +#define IORES_DESC_NONE 0 +enum { REGION_INTERSECTS, REGION_DISJOINT, REGION_MIXED }; +#define RAM_START 0x800000000ULL +#define RAM_END 0x87fffd000ULL +static int region_intersects(phys_addr_t start, size_t size, unsigned long flags, unsigned long desc) +{ + phys_addr_t end = start + size; + (void)desc; + assert(flags == IORESOURCE_SYSTEM_RAM); + return start < RAM_END && end > RAM_START ? REGION_INTERSECTS : REGION_DISJOINT; +} + +/* Is the physical byte range [pa, pa + len) inside pages the device was given? */ +static bool device_owns(phys_addr_t pa, size_t len) +{ + for (phys_addr_t p = pa & ~(SUB_PAGE - 1); p < pa + len; p += SUB_PAGE) { + bool found = false; + for (int i = 0; i < NSUB; i++) + found |= table[i] == p || kept[i] == p; + if (!found) + return false; + } + return true; +} +static unsigned remaps; +static char backing[1]; +static void *memremap(phys_addr_t pa, size_t len, unsigned long flags) +{ + remaps++; + if (!device_owns(pa, len) || ALIGN_DOWN(pa, PAGE_SIZE) < RAM_END) { + fprintf(stderr, "FAIL: memremap(%#llx, %#zx) covers memory the device may not share\n", + (unsigned long long)pa, len); + assert(0); + } + if (flags != MEMREMAP_WC) { + fprintf(stderr, "FAIL: memremap(%#llx, %#zx) not write-combined\n", + (unsigned long long)pa, len); + assert(0); + } + return backing; +} +static unsigned acks; +static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool a) +{ + (void)rtk; (void)ep; (void)msg; (void)c; (void)a; acks++; return 0; +} +''' + +MAIN = r''' +static struct device dev; + +static u64 request(dma_addr_t iova, size_t size) +{ + return ((u64)(size >> 12) << 44) | iova; +} + +static int place(dma_addr_t iova, size_t size) +{ + struct apple_rtkit rtk = { .dev = &dev }; + int ret; + + remaps = acks = 0; + ret = apple_rtkit_crashlog_map(&rtk, request(iova, size)); + assert(ret || (remaps == 1 && acks == 1 && rtk.crashlog_placed && + rtk.crashlog_buffer.size == size && rtk.crashlog_buffer.iova == iova)); + assert(!ret || (remaps == 0 && acks == 0 && !rtk.crashlog_placed)); + return ret; +} + +int main(void) +{ + /* + * Linux's mappings: DVA pages 0-2 on contiguous physical pages, page 3 elsewhere, + * 4 unmapped; pages 6-7 straddle the end of System RAM; page 8 on registers. + */ + map16(table, 0, 0x900000000ULL); + map16(table, 1, 0x900004000ULL); + map16(table, 2, 0x900008000ULL); + map16(table, 3, 0x980000000ULL); + map16(table, 6, 0x87fffc000ULL); + map16(table, 7, 0x880000000ULL); + map16(table, 8, 0x200000000ULL); + /* The firmware's kept mappings: pages 10-11 contiguous, 12 elsewhere. */ + map16(kept, 10, 0xa00000000ULL); + map16(kept, 11, 0xa00004000ULL); + map16(kept, 12, 0xb00000000ULL); + + /* Aligned buffers on contiguous pages. */ + assert(place(DVA_BASE, 0x4000) == 0); + assert(place(DVA_BASE, 0xc000) == 0); + /* Unaligned, inside one page or across contiguous ones. */ + assert(place(DVA_BASE + 0x1000, 0x2000) == 0); + assert(place(DVA_BASE + 0x3000, 0x4000) == 0); + assert(place(DVA_BASE + 0x6000, 0x6000) == 0); + /* Through the firmware's kept mappings. */ + assert(place(DVA_BASE + 10 * IOMMU_PAGE + 0x2000, 0x4000) == 0); + + /* An aligned buffer whose second page lies elsewhere or isn't mapped. */ + assert(place(DVA_BASE + 0x8000, 0x8000) == -ERANGE); + assert(place(DVA_BASE + 0xc000, 0x8000) == -ERANGE); + assert(place(DVA_BASE + 11 * IOMMU_PAGE, 0x8000) == -ERANGE); + + /* + * Unaligned buffers whose last bytes are on a page that lies elsewhere + * or isn't mapped, including a last byte on byte 0 of the bad page + * (catches addr < last vs addr <= last). + */ + assert(place(DVA_BASE + 0x8001, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0xb000, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0xf000, 0x4000) == -ERANGE); + assert(place(DVA_BASE + 0x9000, 0x8000) == -ERANGE); + + /* Nothing at the first byte. */ + assert(place(DVA_BASE + 0x10000, 0x4000) == -ENOENT); + assert(place(DVA_BASE + 0x3c000, 0x1000) == -ENOENT); + + /* + * Contiguous, but reaching System RAM, wholly in it, sharing a 16 KiB + * CPU page with it (strictly past RAM_END), or on registers below DRAM; + * the first full CPU page past System RAM is a carveout and is mapped. + */ + assert(place(DVA_BASE + 6 * IOMMU_PAGE, 0x8000) == -EACCES); + assert(place(DVA_BASE + 6 * IOMMU_PAGE, 0x1000) == -EACCES); + assert(place(DVA_BASE + 6 * IOMMU_PAGE + 0x3000, 0x1000) == -EACCES); + assert(place(DVA_BASE + 8 * IOMMU_PAGE, 0x4000) == -EACCES); + assert(place(DVA_BASE + 7 * IOMMU_PAGE, 0x4000) == 0); + + /* A buffer that would wrap the DVA space. */ + assert(place(0xfffffffff000ULL, 0x2000) != 0); + + /* + * 4 KiB smallest IOMMU page: break only subpage 2 inside 16 KiB block 13. + * A 16 KiB walk misses it; the 4 KiB walk catches it. + */ + map16(table, 13, 0x910000000ULL); + table[13 * 4 + 2] = 0x920000000ULL; + the_domain.pgsize_bitmap = 0x1000 | 0x4000; + assert(place(DVA_BASE + 0x3000, 0x4000) == 0); + assert(place(DVA_BASE + 13 * IOMMU_PAGE, 0x4000) == -ERANGE); + /* + * 4 KiB carveout strictly past RAM_END (0x87fffd000) sharing a 16 KiB + * CPU page with System RAM is refused by CPU-page rounding. + */ + table[14 * 4 + 0] = 0x87ffff000ULL; + assert(place(DVA_BASE + 14 * IOMMU_PAGE, 0x1000) == -EACCES); + + /* + * Identity domain: APPLE_DART_FW_LINUX skips non-paging domains and + * apple_dart_fw_remote() returns -ENODEV on identity domains, so + * identity domains are refused. + */ + the_domain.type = IOMMU_DOMAIN_IDENTITY; + the_domain.pgsize_bitmap = 0x4000; + assert(place(0x900000000ULL, 0x4000) == -ENOENT); + assert(place(DVA_BASE + 10 * IOMMU_PAGE + 0x2000, 0x4000) == -ENOENT); + the_domain.type = IOMMU_DOMAIN_DMA; + +#ifdef HAVE_MAPS_PLACED_ROUTING + { + struct apple_rtkit_ops plain = {}; + struct apple_rtkit_ops fw_owned = { .flags = APPLE_RTKIT_FIRMWARE_OWNED_CRASHLOG }; + struct apple_rtkit_ops with_setup = { .shmem_setup = (void *)1 }; + struct apple_rtkit_ops with_setup_ep = { .shmem_setup_ep = (void *)1 }; + struct apple_rtkit r_plain = { .ops = &plain }; + struct apple_rtkit r_fw = { .ops = &fw_owned }; + struct apple_rtkit r_setup = { .ops = &with_setup }; + struct apple_rtkit r_setup_ep = { .ops = &with_setup_ep }; + + assert(apple_rtkit_maps_placed_crashlog(&r_plain)); + assert(!apple_rtkit_maps_placed_crashlog(&r_fw)); + assert(!apple_rtkit_maps_placed_crashlog(&r_setup)); + assert(!apple_rtkit_maps_placed_crashlog(&r_setup_ep)); + } +#endif + + puts("PASS crash log buffers are mapped, write-combined, only over pages that translate contiguously to DRAM outside System RAM"); + return 0; +} +''' + + +def show(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='require the driver at this revision to fail') + args = parser.parse_args() + source, dart = show(args.old_ref, DRIVER), show(args.old_ref, DART) + extra = '' + if 'int apple_dart_fw_range(' in dart: + walk = ''.join(function(dart, name) for name in + ('apple_dart_fw_phys_shareable', 'apple_dart_fw_range_page', 'apple_dart_fw_range')) + else: + walk = function(source, 'apple_rtkit_crashlog_phys') + if 'static bool apple_rtkit_maps_placed_crashlog(' in source: + extra = '#define HAVE_MAPS_PLACED_ROUTING 1\n' + function(source, 'apple_rtkit_maps_placed_crashlog') + code = PREFIX + constants(source) + walk + extra + function(source, 'apple_rtkit_crashlog_map') + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'crashlog-map.c', out / 'crashlog-map' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + result = subprocess.run([str(exe)], capture_output=True, text=True) + if args.old_ref: + if result.returncode == 0: + raise SystemExit(f'{args.old_ref} passed; the test does not catch the original code') + print(result.stderr, end='') + print('old revision fails as required') + return 0 + print(result.stdout + result.stderr, end='') + return result.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='rtkit-crashlog-map-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 350e45f0d663e1..0eccf4d6b9a6fe 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -286,6 +286,9 @@ def mutations(flag, names, base, expect=KILL): 'rtkit-crashlog-tests.py': [(out(), PASS)] + mutations('--mutation', ('buffer-header', 'section-header', 'section-size', 'footer-room', 'mailbox-minimum', 'version-string', 'message-string'), out()), + # cacf35543b4d steps from an unaligned crash log buffer by the page size and maps it cacheable, unchecked. + 'rtkit-crashlog-map-tests.py': [(out(), PASS), + (out() + ['--old-ref', 'cacf35543b4d534fccef3033bd2ddbb415a325b2'], PASS)], 'rtkit-oslog-tests.py': [(out(), PASS)] + mutations('--mutate', ('admission', 'channel', 'counter', 'reset', 'buffer'), out()), 'rtkit-retained-tests.py': [(out(), PASS)], From 0ba0b5ed9744f0974ea74815f4e4846e29e0fa80 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Sat, 21 Nov 2026 22:30:59 +0100 Subject: [PATCH 0667/1514] accel/ane: h17: park an idle engine through runtime PM The H17 engine stays off until its first request and is parked again after each system sleep, but once a request has brought it up it stays powered for the rest of the boot: ANE_SYS, the engine and its DARTs keep drawing power until the next sleep. Hand the engine's ANE_SYS reference to runtime PM once it serves programs, and park it through runtime autosuspend: - The bound device uses autosuspend with a 2 s delay. A request that finds the engine parked waits for a cold boot from the preload and the replay of its programs, ~18 ms on a J700; 2 s keeps that under 1% of a longer pause and the engine's power cycles at most one per 2 s. The standard power/autosuspend_delay_ms changes it, and a negative value keeps the engine up until the next system sleep. - The runtime suspend callback takes the way down a system sleep takes: close the session and wait for requests in flight, stop the firmware, power the engine off and leave it parked, with the session closed, as after a wake. A ring with something still pending refuses with -EBUSY and autosuspend tries again later. - A request for a parked engine resumes the device; the resume callback boots it from the preload and replays every open program, the path a wake already uses. If runtime PM never suspended the device (runtime PM forbidden) while a system sleep parked the engine, the request boots it itself. - An execute holds the device and its end restarts the delay. - A system sleep holds the device across its own way down and then suspends it at once, so ANE_SYS still goes off before the sleep. - A quarantined engine keeps its power: the quarantine pins the device. This applies to every engine whose firmware parks the macOS way (macos_sleep), T8140 and T8142 today. The callbacks take b->lock only when they have work to do (a powered engine to park, a parked engine at the program stage to boot), and the paths that call into runtime PM under b->lock do so only with the engine already powered off or before it serves programs, so neither waits for a callback that needs the lock. Suggested-by: Ryan Murray Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 261 ++++++++++++++++++-- drivers/accel/ane/ane_fw_cold.h | 2 + drivers/accel/ane/ane_fw_platform.c | 11 + drivers/accel/ane/ane_fw_platform.h | 2 + drivers/accel/ane/ane_t6021_rtclient_main.c | 13 +- 5 files changed, 266 insertions(+), 23 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 1cf7da420b3c97..e40598626fcca2 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -104,6 +104,12 @@ struct ane_fw_backend { bool pmu_base_set; /* The engine's own ANE_SYS reference (b->power) is held. */ bool power_ref; + /* + * In a runtime PM callback of b->power: genpd has ANE_SYS on (resume) + * or turns it off after the callback (suspend), so the power steps + * take and drop no reference of their own. + */ + bool in_rpm; struct list_head mappings; /* Serialize stage changes, command publication and retained lifetimes. */ struct mutex lock; @@ -198,6 +204,12 @@ static struct kexec_blocker ane_fw_kexec = { .reason = "ANE firmware retains private DMA mappings until hardware reset", }; +/* Engines that park have their power held by runtime PM between requests. */ +static bool ane_fw_rpm(const struct ane_fw_backend *b) +{ + return b->soc->macos_sleep; +} + static int ane_fw_quarantine(struct ane_fw_backend *b, int error) { unsigned int i; @@ -205,6 +217,11 @@ static int ane_fw_quarantine(struct ane_fw_backend *b, int error) b->stage = ANE_STAGE_QUARANTINED; dev_err(&b->pdev->dev, "ANE quarantined (%d); mappings and power retained, reboot required\n", error); + /* Runtime PM held a powered engine between requests: pin it on. */ + if (ane_fw_rpm(b) && b->powered && !b->power_ref) { + pm_runtime_get_noresume(&b->pdev->dev); + b->power_ref = true; + } /* The engine and DARTs are only readable once powered. */ if (!b->powered) return error; @@ -557,7 +574,7 @@ static int ane_fw_ps_off(struct ane_fw_backend *b, u32 offset) if (!ane_poll32(b, reg, ANE_FW_PS_OFF_MASK, 0, 1, 1000)) return 0; } - if (!apple_sleep_request_deep_once()) + if (b->in_rpm || !apple_sleep_request_deep_once()) return ret; dev_warn(&b->pdev->dev, "H17 ANE: power word %#x still stuck, taking the deep path\n", offset); return 0; @@ -583,7 +600,7 @@ static int ane_fw_power_down_staged(struct ane_fw_backend *b) if (ret) return ret; /* No engine or DART access from here until ANE_SYS is back on. */ - b->powered = false; + WRITE_ONCE(b->powered, false); b->power_ref = false; pm_runtime_put_sync(b->power); /* @@ -624,16 +641,19 @@ static int ane_fw_power_down(struct ane_fw_backend *b) if (ret) return ret; /* No engine or DART access from here until ANE_SYS is back on. */ - b->powered = false; - b->power_ref = false; + WRITE_ONCE(b->powered, false); /* * Our reference was the last one on ANE_SYS: genpd turns it off once the * ANE DARTs are idle, or at the latest in the noirq phase of the system * suspend. ane_fw_genpd_event() records that, and the resume reports a - * domain that stayed on. + * domain that stayed on. Between requests runtime PM holds the engine + * instead, and its runtime suspend lets the domain go. */ - pm_runtime_put_sync(b->power); - dev_info(&b->pdev->dev, "H17 ANE: powered down for system sleep\n"); + if (b->power_ref) { + b->power_ref = false; + pm_runtime_put_sync_suspend(b->power); + } + dev_info(&b->pdev->dev, "H17 ANE: powered down\n"); return 0; } @@ -1015,30 +1035,189 @@ static int ane_fw_cold_cycle_down(struct ane_fw_backend *b) return ane_fw_power_down(b); } -/* A request for a parked engine: boot it from the preload, as after a sleep. */ -static int ane_fw_session_wake(void *ctx) +/* + * The parked engine's autosuspend delay: a request that finds it parked waits + * for a cold boot from the preload and the replay of its programs, ~18 ms on + * a J700 (~10 ms for the boot alone on H16). Two seconds keep that under 1% of + * a pause longer than the delay, and keep the engine from cycling its power + * faster than every two seconds. power/autosuspend_delay_ms changes it; a + * negative value keeps the engine up until the next system sleep. + */ +#define ANE_FW_AUTOSUSPEND_MS 2000 + +/* + * After a bring-up or a boot for a request: hand the engine's ANE_SYS + * reference to runtime PM, which parks the engine once it has been idle for + * its autosuspend delay. A quarantined engine keeps its reference. + */ +static void ane_fw_rpm_idle(struct ane_fw_backend *b) +{ + lockdep_assert_held(&b->lock); + if (!ane_fw_rpm(b) || !b->power_ref || b->stage != ANE_STAGE_PROGRAM || + b->session.quarantined) + return; + b->power_ref = false; + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); +} + +/* + * Boot a parked engine from the preload, as after a sleep. ANE_SYS is on: + * runtime PM resumed the device, which holds the domain, so the power steps + * take no reference of their own. + */ +static void ane_fw_unpark(struct ane_fw_backend *b) { - struct ane_fw_backend *b = ctx; int ret; - if (READ_ONCE(b->stage) == ANE_STAGE_PROBED) - return READ_ONCE(b->in_sleep) ? -EAGAIN : ane_fw_first_bringup(b); - guard(mutex)(&b->lock); - if (!b->parked) - return 0; - /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ - if (b->in_sleep) - return -EAGAIN; + lockdep_assert_held(&b->lock); + if (!b->parked || READ_ONCE(b->in_sleep)) + return; + b->in_rpm = true; ret = ane_fw_cold_cycle_boot(b); + b->in_rpm = false; WRITE_ONCE(b->parked, false); WRITE_ONCE(b->session.parked, false); if (ret) { + /* Power and mappings stay for diagnosis: the quarantine pins the device. */ ane_fw_quarantine(b, ret); b->session.quarantined = true; } ane_h16_session_sleep(&b->session, false); dev_info(&b->pdev->dev, "H17 ANE: up for a request%s\n", ret ? " FAILED" : ""); - return ret; +} + +/* + * A request for a parked engine: runtime PM resumes the device, and its + * resume callback boots the engine. Called without b->lock, which the + * callback takes. + */ +static int ane_fw_session_wake(void *ctx) +{ + struct ane_fw_backend *b = ctx; + int ret; + + if (READ_ONCE(b->stage) == ANE_STAGE_PROBED) { + if (READ_ONCE(b->in_sleep)) + return -EAGAIN; + ret = ane_fw_first_bringup(b); + if (!ret) { + guard(mutex)(&b->lock); + ane_fw_rpm_idle(b); + } + return ret; + } + if (!READ_ONCE(b->parked)) + return 0; + /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ + if (READ_ONCE(b->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(&b->pdev->dev); + if (ret < 0) + return ret; + /* + * Still parked: either the device never suspended (runtime PM forbidden, + * or a negative autosuspend delay) and a system sleep parked the engine, + * or a system sleep began and prevented the resume callback from booting + * it. + */ + if (READ_ONCE(b->parked)) { + guard(mutex)(&b->lock); + ane_fw_unpark(b); + } + if (READ_ONCE(b->parked)) { + pm_runtime_put_sync_suspend(&b->pdev->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); + return READ_ONCE(b->session.quarantined) ? -EIO : 0; +} + +/* + * Runtime suspend after the autosuspend delay: the way down a system sleep + * takes, then parked as after a wake, with the session left closed. There + * is no firmware to send anything to: a close is deferred and a request + * waits in ane_h16_session_enter(), which wakes the engine; the wake reopens + * the session, and a program closed meanwhile is lost to the new firmware + * and only released. Outside a system sleep there is no deep path to fall + * back on, so a firmware stop that fails quarantines the engine, which keeps + * its power, as a failed sleep does. + */ +int ane_fw_staged_runtime_suspend(struct device *dev) +{ + struct ane_fw_backend *b = ane_backend; + int ret; + + /* Powered off by a power-down that held the reference: nothing to stop. */ + if (!b || &b->pdev->dev != dev || !ane_fw_rpm(b) || !READ_ONCE(b->powered)) + return 0; + guard(mutex)(&b->lock); + if (!b->powered) + return 0; + /* Bringing up, quarantined, or in a system sleep, which parks it itself. */ + if (b->stage != ANE_STAGE_PROGRAM || READ_ONCE(b->in_sleep)) + return -EBUSY; + if (READ_ONCE(b->session.quarantined)) { + ane_fw_quarantine(b, b->session.error ?: -EIO); + return -EBUSY; + } + /* Closes admission and waits for every request in flight. */ + ane_h16_session_sleep(&b->session, true); + if (READ_ONCE(b->session.quarantined)) { + ane_fw_quarantine(b, b->session.error ?: -EIO); + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } + /* + * An execute that raced the autosuspend boundary may have finished while + * draining and refreshed last_busy: wait out the new delay instead of + * parking right after it. + */ + if (pm_runtime_autosuspend_expiration(dev)) { + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } + for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { + if (b->transport.pending[ch].active) { + /* Something is still pending on a ring: autosuspend tries later. */ + ane_h16_session_sleep(&b->session, false); + pm_runtime_mark_last_busy(dev); + return -EBUSY; + } + } + b->in_rpm = true; + ret = ane_fw_clean_stop(b) ? ane_fw_firmware_stop(b) : 0; + if (!ret) + ret = ane_fw_power_down(b); + b->in_rpm = false; + if (ret) { + ane_fw_quarantine(b, ret); + b->session.quarantined = true; + ane_h16_session_sleep(&b->session, false); + dev_err(dev, "H17 ANE: idle park failed (%d): quarantined\n", ret); + return -EBUSY; + } + WRITE_ONCE(b->parked, true); + WRITE_ONCE(b->session.parked, true); + wake_up_all(&b->session.wake); + dev_info(dev, "H17 ANE: idle: parked until the next request\n"); + return 0; +} + +/* Runtime resume for a request (ane_fw_session_wake()): boot the parked engine. */ +int ane_fw_staged_runtime_resume(struct device *dev) +{ + struct ane_fw_backend *b = ane_backend; + + /* Only a parked engine that serves programs is booted here. */ + if (!b || &b->pdev->dev != dev || !ane_fw_rpm(b) || + READ_ONCE(b->stage) != ANE_STAGE_PROGRAM || !READ_ONCE(b->parked)) + return 0; + guard(mutex)(&b->lock); + ane_fw_unpark(b); + /* A failed boot is the quarantine's to report: the device itself is up. */ + return 0; } static int ane_fw_sleep_prepare(struct ane_fw_backend *b) @@ -1243,7 +1422,27 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void WRITE_ONCE(b->session.wake_blocked, true); } if (event == PM_SUSPEND_PREPARE && retained) { - if (!ane_fw_sleep_prepare(b)) + struct device *dev = &b->pdev->dev; + int ret; + + /* + * No idle park from here on: the sleep takes the engine down + * itself. A park that already began finishes first (the sleep + * waits for b->lock and finds the engine parked). + */ + if (ane_fw_rpm(b)) + pm_runtime_get_noresume(dev); + ret = ane_fw_sleep_prepare(b); + if (ane_fw_rpm(b)) { + if (!ret && !READ_ONCE(b->powered)) { + /* Off now, as before: genpd may turn ANE_SYS off. */ + pm_runtime_put_sync_suspend(dev); + } else { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } + } + if (!ret) return NOTIFY_DONE; ane_fw_sleep_unblock(b); dev_warn_once(&b->pdev->dev, ANE_FW_SLEEP_REFUSED); @@ -1505,7 +1704,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en int ret; /* Taken once; a failed attempt keeps it for the retry or the quarantine. */ - if (!b->power_ref) { + if (!b->power_ref && !b->in_rpm) { ret = pm_runtime_resume_and_get(b->power); if (ret < 0) return ret; @@ -1535,7 +1734,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en ret = ane_poll32(b, b->gate + 0x30, U32_MAX, 0, 1, 100000); if (ret) return ret; - b->powered = true; + WRITE_ONCE(b->powered, true); ane_fw_snapshot_engine(b); /* A warm resume finds a suspended firmware's state, not reset values. */ if (cold_engine && !ane_fw_cold_engine_valid(&b->cold, b->soc)) { @@ -2020,6 +2219,15 @@ static void ane_fw_program_busy(void *ctx, bool busy) struct ane_fw_backend *b = ctx; apple_clpc_ane_set_active(b->clpc, busy); + /* Under the session lock: no callback runs here, the park drains first. */ + if (!ane_fw_rpm(b)) + return; + if (busy) { + pm_runtime_get_noresume(&b->pdev->dev); + } else { + pm_runtime_mark_last_busy(&b->pdev->dev); + pm_runtime_put_autosuspend(&b->pdev->dev); + } } static const struct ane_h16_session_ops ane_fw_session_ops = { @@ -2582,10 +2790,17 @@ int ane_fw_staged_bind(struct platform_device *pdev) return ret; pm_runtime_get_noresume(dev); b->bind_held = true; + /* Idle, runtime PM parks the engine (ane_fw_staged_runtime_suspend()). */ + if (ane_fw_rpm(b)) { + pm_runtime_set_autosuspend_delay(dev, ANE_FW_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(dev); + } } ret = devm_pm_runtime_enable(dev); if (ret) { if (handoff) { + if (ane_fw_rpm(b)) + pm_runtime_dont_use_autosuspend(dev); b->bind_held = false; pm_runtime_put_noidle(dev); pm_runtime_set_suspended(dev); @@ -2615,6 +2830,8 @@ void ane_fw_staged_unbind(struct platform_device *pdev) if (b && b->pdev == pdev) { ane_fw_bind_release(b); + if (ane_fw_rpm(b)) + pm_runtime_dont_use_autosuspend(&pdev->dev); if (b->genpd_nb_added) dev_pm_genpd_remove_notifier(&pdev->dev); b->genpd_nb_added = false; diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index 0af12b6ca1bc81..83ee2dcb78901c 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -184,6 +184,8 @@ int ane_fw_staged_bind(struct platform_device *pdev); bool ane_fw_staged_bound(struct device *dev); void ane_fw_staged_unbind(struct platform_device *pdev); int ane_fw_staged_suspend(struct device *dev); +int ane_fw_staged_runtime_suspend(struct device *dev); +int ane_fw_staged_runtime_resume(struct device *dev); void ane_fw_staged_start(void); bool ane_fw_staged_exit(void); diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index 9a62c2f4ec8023..f95b5b6b5a3909 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -576,3 +576,14 @@ int ane_fw_platform_resume(struct device *dev) return 0; return ane_h16_backend_resume(dev); } + +/* Runtime PM callbacks: only the bound H17 device parks; H16 has none. */ +int ane_fw_platform_runtime_suspend(struct device *dev) +{ + return ane_fw_staged_bound(dev) ? ane_fw_staged_runtime_suspend(dev) : 0; +} + +int ane_fw_platform_runtime_resume(struct device *dev) +{ + return ane_fw_staged_bound(dev) ? ane_fw_staged_runtime_resume(dev) : 0; +} diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h index f203f426a91844..f3adbd59c6f6ec 100644 --- a/drivers/accel/ane/ane_fw_platform.h +++ b/drivers/accel/ane/ane_fw_platform.h @@ -180,6 +180,8 @@ int ane_fw_platform_probe(struct platform_device *pdev, void ane_fw_platform_remove(struct platform_device *pdev); int ane_fw_platform_suspend(struct device *dev); int ane_fw_platform_resume(struct device *dev); +int ane_fw_platform_runtime_suspend(struct device *dev); +int ane_fw_platform_runtime_resume(struct device *dev); int ane_fw_preload_range(struct device_node *np, unsigned int index, u64 *phys, u64 *size); const struct ane_fw_platform *ane_fw_platform_build(struct device_node *np, const struct ane_fw_platform *soc); diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index b565f31112ae79..65ed18f09c5800 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -3867,8 +3867,19 @@ static int __maybe_unused ane_rtclient_sleep_pm_resume(struct device *dev) return ane_t6021_pm_resume(ane_rtclient_get_sleep_pm(dev)); } +static int __maybe_unused ane_rtclient_runtime_suspend(struct device *dev) +{ + return ane_rtclient_is_platform(dev) ? ane_fw_platform_runtime_suspend(dev) : 0; +} + +static int __maybe_unused ane_rtclient_runtime_resume(struct device *dev) +{ + return ane_rtclient_is_platform(dev) ? ane_fw_platform_runtime_resume(dev) : 0; +} + static const struct dev_pm_ops __maybe_unused ane_rtclient_sleep_pm = { SYSTEM_SLEEP_PM_OPS(ane_rtclient_sleep_pm_suspend, ane_rtclient_sleep_pm_resume) + RUNTIME_PM_OPS(ane_rtclient_runtime_suspend, ane_rtclient_runtime_resume, NULL) }; static int ane_rtclient_probe_inner(struct platform_device *pdev, @@ -4526,7 +4537,7 @@ static struct platform_driver ane_rtclient_driver = { .name = "ane_t6021", .of_match_table = ane_rtclient_of_match, .dev_groups = ane_t6021_stats_groups, - .pm = pm_sleep_ptr(&ane_rtclient_sleep_pm), + .pm = pm_ptr(&ane_rtclient_sleep_pm), .suppress_bind_attrs = true, }, .probe = ane_rtclient_probe, From 4fa08b46555ab80adb3b40f95cc48055801711c3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:35:13 -0500 Subject: [PATCH 0668/1514] soc: apple: mailbox: drain G17 receive interrupts in hard IRQ ASCWrap v6 GPU mailboxes (APPLE_MBOX_ASCWRAP_V6_ROLE_GFX and APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1 across T6040/T6041, T8140, T8142, and T6050) previously registered their recv-not-empty interrupt as a pure threaded IRQ, paying an extra IRQ-thread wakeup on every GPU completion before apple_rtkit_rx() could enqueue the driver's event work item. All ASCWrap v6 GFX/GFX1 receive handlers already execute under spin_lock_irqsave(&mbox->rx_lock, flags) inside apple_mbox_poll_locked() and are strictly hard-IRQ safe: apple_rtkit_rx() performs only atomic FIFO/flag checks, GFP_ATOMIC work allocation, queue_work(), and non-sleeping recv_message_early() callbacks (AtomicBool stores, complete_all(), mod_delayed_work_on(), and workqueue enqueue), deferring all sleeping RTKit callbacks to process context on rtk->wq. Exclude ASCWrap v8 (apple,t8152-gfx-ascwrap-v8, hw->is_ascwrap_v8) from apple_mbox_is_g17() so v8 stays on apple_mbox_recv_irq() with its apple_mbox_v8_rx_irq_guard() storm guard intact. Split the ASCWrap v6 G17 receive path into a hard-IRQ handler (apple_mbox_g17_recv_irq) that drains apple_mbox_poll_locked() directly and returns IRQ_HANDLED on normal completions, waking the oneshot thread (apple_mbox_g17_recv_thread) via IRQ_WAKE_THREAD only when the per-IRQ budget (APPLE_G17_MBOX_RX_BUDGET) is saturated so the flood throttle sleep and thread-context uclamp adjustment stay off hard IRQ. Add KUnit test coverage verifying both hard-IRQ dispatch outcomes and that ASCWrap v8 GFX/GFX1 mailboxes remain excluded from apple_mbox_is_g17(). Signed-off-by: Diljit Singh --- drivers/soc/apple/mailbox-g17-test.h | 44 ++++++++++++++++++++++ drivers/soc/apple/mailbox.c | 55 ++++++++++++++++++++-------- include/linux/soc/apple/mailbox.h | 6 +-- 3 files changed, 86 insertions(+), 19 deletions(-) diff --git a/drivers/soc/apple/mailbox-g17-test.h b/drivers/soc/apple/mailbox-g17-test.h index c53e58c5060831..a7197d411c16dc 100644 --- a/drivers/soc/apple/mailbox-g17-test.h +++ b/drivers/soc/apple/mailbox-g17-test.h @@ -93,8 +93,52 @@ static void apple_g17_rx_util_min_test(struct kunit *test) #endif } +static void apple_g17_rx_hardirq_dispatch_test(struct kunit *test) +{ + const struct apple_mbox_hw hw = { + .i2a_control = 0, .i2a_recv0 = 8, .i2a_recv1 = 16, + .control_empty = BIT(17), + }; + struct apple_mbox mbox = { .hw = &hw, .rx = apple_g17_test_rx }; + unsigned int count = 0; + void *regs = kunit_kzalloc(test, 32, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, regs); + mbox.regs = (void __iomem *)regs; + const struct apple_mbox_hw hw_v8 = { + .i2a_control = 0, .i2a_recv0 = 8, .i2a_recv1 = 16, + .control_empty = BIT(17), + .is_ascwrap_v8 = true, + }; + struct apple_mbox mbox_v8 = { .hw = &hw_v8 }; + + mbox.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX; + mbox.cookie = &count; + spin_lock_init(&mbox.rx_lock); + + /* ASCWrap v6 GFX/GFX1 use the hard-IRQ split; ASCWrap v8 stays excluded + * so apple_mbox_recv_irq() keeps running apple_mbox_v8_rx_irq_guard(). + */ + KUNIT_EXPECT_TRUE(test, apple_mbox_is_g17(&mbox)); + mbox_v8.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX; + KUNIT_EXPECT_FALSE(test, apple_mbox_is_g17(&mbox_v8)); + mbox_v8.ascwrap_v6.role = APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1; + KUNIT_EXPECT_FALSE(test, apple_mbox_is_g17(&mbox_v8)); + + /* Empty FIFO finishes directly in hard IRQ without waking the thread. */ + writel(BIT(17), mbox.regs); + KUNIT_EXPECT_EQ(test, apple_mbox_g17_recv_irq(0, &mbox), IRQ_HANDLED); + KUNIT_EXPECT_EQ(test, count, 0U); + + /* Saturated budget wakes the oneshot throttle thread. */ + writel(0, mbox.regs); + KUNIT_EXPECT_EQ(test, apple_mbox_g17_recv_irq(0, &mbox), IRQ_WAKE_THREAD); + KUNIT_EXPECT_EQ(test, count, (unsigned int)APPLE_G17_MBOX_RX_BUDGET); +} + static struct kunit_case apple_g17_stall_cases[] = { KUNIT_CASE(apple_g17_rx_flood_bounded_test), + KUNIT_CASE(apple_g17_rx_hardirq_dispatch_test), KUNIT_CASE(apple_g17_tx_stall_bounded_test), KUNIT_CASE(apple_g17_rx_util_min_test), { } diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 5b5b69500db348..265e61e3f9899d 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -539,8 +539,9 @@ EXPORT_SYMBOL_GPL(apple_mbox_ascwrap_v6_cpu_stopped); static bool apple_mbox_is_g17(const struct apple_mbox *mbox) { - return mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX || - mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1; + return (!mbox->hw || !mbox->hw->is_ascwrap_v8) && + (mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX || + mbox->ascwrap_v6.role == APPLE_MBOX_ASCWRAP_V6_ROLE_GFX1); } int apple_mbox_ascwrap_v6_get_cpu_state(struct apple_mbox *mbox, u32 *control, u32 *status) @@ -912,9 +913,9 @@ static int apple_mbox_poll_locked(struct apple_mbox *mbox) } /* - * Threaded receive handler only: apply the consumer's minimum utilization to - * this thread. As an RT thread it otherwise runs with the RT default, which - * makes schedutil raise its CPU cluster to the top frequency on every message. + * Threaded receive handler only (woken on G17 budget saturation): apply the + * consumer's minimum utilization to this thread so flood throttling does not + * leave schedutil raising its CPU cluster to the top RT default frequency. */ static void apple_mbox_apply_rx_util_min(struct apple_mbox *mbox) { @@ -976,10 +977,6 @@ static irqreturn_t apple_mbox_recv_irq(int irq, void *data) unsigned long flags; int consumed = 0; - /* Only the G17 receive handler is threaded (see apple_mbox_probe()). */ - if (apple_mbox_is_g17(mbox)) - apple_mbox_apply_rx_util_min(mbox); - spin_lock_irqsave(&mbox->rx_lock, flags); if (likely(!READ_ONCE(mbox->removing))) consumed = apple_mbox_poll_locked(mbox); @@ -987,13 +984,38 @@ static irqreturn_t apple_mbox_recv_irq(int irq, void *data) apple_mbox_v8_rx_irq_guard(mbox, consumed); spin_unlock_irqrestore(&mbox->rx_lock, flags); - /* G17 uses a oneshot threaded IRQ. Leave it masked during this sleep - * so a firmware flood cannot monopolize a CPU at IRQ-thread priority. - * The level condition retriggers after return; no message is discarded. + return IRQ_HANDLED; +} + +static irqreturn_t apple_mbox_g17_recv_irq(int irq, void *data) +{ + struct apple_mbox *mbox = data; + unsigned long flags; + int consumed = 0; + + spin_lock_irqsave(&mbox->rx_lock, flags); + if (likely(!READ_ONCE(mbox->removing))) + consumed = apple_mbox_poll_locked(mbox); + spin_unlock_irqrestore(&mbox->rx_lock, flags); + + /* + * Normal completions drain completely in hard IRQ without waking the + * IRQ thread. Only a saturated budget hands off to the oneshot thread + * to sleep with the level line masked so a firmware flood cannot + * monopolize a CPU. */ - if (apple_mbox_is_g17(mbox) && consumed == APPLE_G17_MBOX_RX_BUDGET) - usleep_range(1000, 2000); + if (unlikely(consumed == APPLE_G17_MBOX_RX_BUDGET)) + return IRQ_WAKE_THREAD; + + return IRQ_HANDLED; +} + +static irqreturn_t apple_mbox_g17_recv_thread(int irq, void *data) +{ + struct apple_mbox *mbox = data; + apple_mbox_apply_rx_util_min(mbox); + usleep_range(1000, 2000); return IRQ_HANDLED; } @@ -1631,8 +1653,9 @@ static int apple_mbox_probe(struct platform_device *pdev) return -ENOMEM; if (apple_mbox_is_g17(mbox)) - ret = devm_request_threaded_irq(dev, mbox->irq_recv_not_empty, NULL, - apple_mbox_recv_irq, + ret = devm_request_threaded_irq(dev, mbox->irq_recv_not_empty, + apple_mbox_g17_recv_irq, + apple_mbox_g17_recv_thread, IRQF_ONESHOT | IRQF_NO_AUTOEN | IRQF_NO_SUSPEND, irqname, mbox); diff --git a/include/linux/soc/apple/mailbox.h b/include/linux/soc/apple/mailbox.h index 0159bbc356cfa1..3d7bc0d80d2d54 100644 --- a/include/linux/soc/apple/mailbox.h +++ b/include/linux/soc/apple/mailbox.h @@ -125,9 +125,9 @@ void apple_mbox_set_recv_enabled(struct apple_mbox *mbox, bool enabled); void apple_mbox_hold_rx(struct apple_mbox *mbox); void apple_mbox_release_rx(struct apple_mbox *mbox); /* - * Set the minimum utilization (0..1024) the threaded receive handler runs with, - * or -1 to restore the scheduler's default; the handler applies it to itself - * when it next runs. Only mailboxes with a threaded receive handler support it. + * Set the minimum utilization (0..1024) the G17 flood-throttle receive thread + * runs with, or -1 to restore the scheduler's default; the thread applies it + * when it next wakes. Only mailboxes with a threaded receive handler support it. */ int apple_mbox_set_rx_util_min(struct apple_mbox *mbox, int util_min); int apple_mbox_send(struct apple_mbox *mbox, struct apple_mbox_msg msg, From 513f7cb4cd6c75a45d4fe77079879127140b6452 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:35:16 -0500 Subject: [PATCH 0669/1514] drm/asahi: g17: relax interior MMIO writes on M5 command port G17Resources::submit_m5_work() and submit_m5_work_held() write a burst of 2 to 16 64-bit registers into the same non-posted SGX register block (Device-nGnRnE MMIO via nonposted-mmio / ioremap_np) for each M5 host command-port transaction: 2 writes for steady-state compute advances (0 interior writes relaxed), 4 for render pair advances, 6-8 for compute queue configuration/activation, and 12-16 for full render pair configuration and submission (HardwareSubmission::new()). Previously every register write in the burst used ordered try_write64(), emitting a full dma_wmb() (dmb oshst) before every interior register write. Keep ordered try_write64() on the first write (ordering all prior normal-memory descriptor, ring, and pool-counter stores before the first MMIO write) and on the final write (before the doorbell/advance strobe), while using relaxed().try_write64() for interior writes to the same non-posted SGX aperture where program order is guaranteed by Device-nGnRnE. In submit_m5_work_held(), core gating register reads and writes remain fully ordered around the burst. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/regs.rs | 45 ++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 1fde883e6c6df4..9b5e64011590e6 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -657,6 +657,26 @@ impl G17Resources { Ok(true) } + /// Writes an M5 host command-port transaction to the SGX register block. + /// Only the first and last writes carry the write barrier of an ordered + /// MMIO write; interior writes to the same non-posted register block stay + /// in program order without stalling on intermediate GPU round trips. + fn write_m5_submission( + sgx: &IoMem<'_, SGX_SIZE>, + submission: &crate::g17::fw::m5::queue::HardwareSubmission, + ) -> Result { + let sgx = sgx.as_view(); + let writes = submission.writes(); + for (index, &(offset, value)) in writes.iter().enumerate() { + if index != 0 && index + 1 != writes.len() { + sgx.relaxed().try_write64(value, offset)?; + } else { + sgx.try_write64(value, offset)?; + } + } + Ok(()) + } + /// Publishes through the M5 host command port, including the kick that /// makes an idle queue runnable. Core activity is not a prerequisite. pub(crate) fn submit_m5_work( @@ -667,11 +687,7 @@ impl G17Resources { return Ok(()); } let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - for &(offset, value) in submission.writes() { - sgx.try_write64(value, offset)?; - } - Ok(()) + Self::write_m5_submission(&*sgx, submission) } /// [`Self::submit_m5_work`] with core gating held off across the transaction, reading the @@ -686,17 +702,14 @@ impl G17Resources { return Ok(()); } let sgx = self.sgx.try_access().ok_or(ENODEV)?; - let sgx = (&*sgx).as_view(); - let gating = sgx.try_read32(G17_GATING_CONTROL)?; - sgx.try_write32(gating | G17_GATING_HOLD, G17_GATING_CONTROL)?; - sgx.try_read32(G17_GATING_CONTROL)?; - let result = submission - .writes() - .iter() - .try_for_each(|&(offset, value)| sgx.try_write64(value, offset)); - let gating = sgx.try_read32(G17_GATING_CONTROL)?; - sgx.try_write32(gating & !G17_GATING_HOLD, G17_GATING_CONTROL)?; - sgx.try_read32(G17_GATING_CONTROL)?; + let view = (&*sgx).as_view(); + let gating = view.try_read32(G17_GATING_CONTROL)?; + view.try_write32(gating | G17_GATING_HOLD, G17_GATING_CONTROL)?; + view.try_read32(G17_GATING_CONTROL)?; + let result = Self::write_m5_submission(&*sgx, submission); + let gating = view.try_read32(G17_GATING_CONTROL)?; + view.try_write32(gating & !G17_GATING_HOLD, G17_GATING_CONTROL)?; + view.try_read32(G17_GATING_CONTROL)?; result } From 19a96ebed052429f77388e6d4fe21b2b82810f7d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 12:52:46 -0500 Subject: [PATCH 0670/1514] accel/ane: h16, h17: accept 1000.0f in the program record trailer H16_LOAD refuses, with -ENOEXEC, each H16 and H17 HWX we built with macOS 27.3's ANECompiler (10.302). The validator compares the program record's fixed trailer with a template that has 0x461c4000 (10000.0f) at +0x880, or at +0x8a0 in the record form with scratch. ANECompiler 10.205 and mil-hwx-compiler write that value; ANECompiler 10.302 writes 0x447a0000 (1000.0f) there in both forms, and the rest of the trailer matches. Accept either value at that word and refuse any other, so the check stays exact. Add a KUnit case covering both values and five refused ones in all four fixture forms. Signed-off-by: Satya Benson --- drivers/accel/ane/ane_h16_hwx.c | 17 +++++++++++++++-- drivers/accel/ane/ane_h16_hwx_test.c | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/drivers/accel/ane/ane_h16_hwx.c b/drivers/accel/ane/ane_h16_hwx.c index a7ad970ba02af2..cb98778bab3bef 100644 --- a/drivers/accel/ane/ane_h16_hwx.c +++ b/drivers/accel/ane/ane_h16_hwx.c @@ -214,6 +214,19 @@ static int hwx_segment(struct hwx_parser *p, const u8 *c, u32 length) return 0; } +/* + * The fp32 trailer word at +0x880 (+0x8a0 with scratch) is 10000.0f in HWX + * from ANECompiler 10.205 and mil-hwx-compiler, and 1000.0f in H16 and H17 + * HWX from ANECompiler 10.302 (macOS 27.3). Both load; any other value is + * refused. + */ +static u32 hwx_trailer_value(const u8 *c, u32 offset) +{ + u32 value = get_unaligned_le32(c + offset); + + return value == 0x447a0000 ? value : 0x461c4000; +} + static int hwx_program(struct hwx_parser *p) { const u8 *c = p->bytes + p->info.program_offset; @@ -299,7 +312,7 @@ static int hwx_program(struct hwx_parser *p) put_unaligned_le32(mixed ? 4 : 2, expected + 0x870); put_unaligned_le32(mixed ? 2 : 7, expected + 0x878); put_unaligned_le32(8, expected + 0x87c); - put_unaligned_le32(mixed ? get_unaligned_le32(c + 0x858) : 0x461c4000, + put_unaligned_le32(mixed ? get_unaligned_le32(c + 0x858) : hwx_trailer_value(c, 0x880), expected + 0x880); put_unaligned_le32(mixed ? 3 : 9, expected + 0x888); put_unaligned_le32(8, expected + 0x88c); @@ -308,7 +321,7 @@ static int hwx_program(struct hwx_parser *p) put_unaligned_le32(8, expected + 0x894); put_unaligned_le32(7, expected + 0x898); put_unaligned_le32(8, expected + 0x89c); - put_unaligned_le32(0x461c4000, expected + 0x8a0); + put_unaligned_le32(hwx_trailer_value(c, 0x8a0), expected + 0x8a0); put_unaligned_le32(9, expected + 0x8a8); put_unaligned_le32(8, expected + 0x8ac); } diff --git a/drivers/accel/ane/ane_h16_hwx_test.c b/drivers/accel/ane/ane_h16_hwx_test.c index 13846add097711..05952de6b9ca13 100644 --- a/drivers/accel/ane/ane_h16_hwx_test.c +++ b/drivers/accel/ane/ane_h16_hwx_test.c @@ -275,6 +275,31 @@ static void hwx_program_test(struct kunit *test) } } +/* The fp32 trailer word: 10000.0f or 1000.0f, in every form; nothing else. */ +static void hwx_trailer_test(struct kunit *test) +{ + static const u32 refused[] = { 0, 0x3f800000, 0x42c80000, 0x461c4001, 0x447a0001 }; + unsigned int variant, i; + + for (variant = 0; variant < 4; variant++) { + struct hwx_fixture *f = fixture_create(test, variant & 1, variant & 2); + struct ane_h16_hwx info; + u8 *word; + + KUNIT_ASSERT_NOT_NULL(test, f); + word = f->bytes + f->program + ((variant & 1) ? 0x8a0 : 0x880); + KUNIT_ASSERT_EQ(test, get_unaligned_le32(word), 0x461c4000U); + put_unaligned_le32(0x447a0000, word); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0, + "form %u, 1000.0f", variant); + for (i = 0; i < ARRAY_SIZE(refused); i++) { + put_unaligned_le32(refused[i], word); + KUNIT_EXPECT_EQ_MSG(test, ane_h16_hwx_validate(f->bytes, f->size, &info), + -ENOEXEC, "form %u, word %#x", variant, refused[i]); + } + } +} + /* Build only structural tasks: no model bytes or hardware fixtures needed. */ static void fixture_tasks(struct hwx_fixture *f, u32 tasks, u32 records) { @@ -812,6 +837,7 @@ static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_element_format_test), KUNIT_CASE(hwx_surface_order_test), KUNIT_CASE(hwx_program_test), + KUNIT_CASE(hwx_trailer_test), KUNIT_CASE(hwx_staged_counts_test), KUNIT_CASE(hwx_final_task_end_test), KUNIT_CASE(hwx_geometry_test), From 1f2ff28d36d7364f13cba0a45b3d4c0c64507871 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Sat, 21 Nov 2026 22:32:04 +0100 Subject: [PATCH 0671/1514] accel/ane: h17: back program surfaces with discontiguous pages H17 program surfaces were one dma_alloc_noncoherent() block each. The memory device is dma-direct, so a block larger than the buddy allocator's largest order (32 MB with 16K pages) can only come from CMA. A 66 MB camera-denoise program then failed to load on the J700 with the default 32 MB CMA area, with a page allocator WARNING that any process loading a large program can trigger; it loaded only with cma=256M. The engine sees memory only through its DARTs, so a surface needs to be contiguous in its DVA range only. Build program surfaces from zeroed blocks of at least the IOMMU domain's smallest granule (derived from b->domain->pgsize_bitmap), as large as the remaining size allows (up to 2 MB) and smaller when a larger block is not available, split into order-0 pages. Charge the backing pages, page array, and sg_table to the caller's memcg with GFP_KERNEL_ACCOUNT. The CPU uses a vmap() alias, which also serves the in-place userspace mapping (vmalloc_to_page()), the pages are mapped through the memory device for cache maintenance only, and iommu_map_sgtable() places them at consecutive DVAs, followed by the same DART error check as before. Syncs walk the surface's sg_table. No allocation along the way warns; a failure returns -ENOMEM to the loader. Releasing a cached surface (on allocation or DVA-window failure before mapping, or in ane_fw_program_unmap() after iommu_unmap() succeeds) unmaps and frees the sg_table, vunmap()s the CPU alias, and returns the pages. Failed or partial IOMMU mappings and short unmaps keep their backing and DVA range, as before. Firmware memory (SHAREDMALLOC, pool, IPC, heap) stays coherent and contiguous. The page allocator lives in its own object so KUnit can check its blocks: physically contiguous and aligned granules, granule derivation from pgsize_bitmap, order-0 pages with one reference each, zeroed, one contiguous vmap() view, and the order choice for sizes that are no power of two. Suggested-by: Ryan Murray Suggested-by: Diljit Singh Signed-off-by: Bartosz Nitka --- drivers/accel/ane/Makefile | 3 +- drivers/accel/ane/ane_fw_cold.c | 138 +++++++++++++++++----- drivers/accel/ane/ane_fw_pages.c | 96 +++++++++++++++ drivers/accel/ane/ane_fw_pages.h | 41 +++++++ drivers/accel/ane/ane_fw_pages_test.c | 164 ++++++++++++++++++++++++++ 5 files changed, 414 insertions(+), 28 deletions(-) create mode 100644 drivers/accel/ane/ane_fw_pages.c create mode 100644 drivers/accel/ane/ane_fw_pages.h create mode 100644 drivers/accel/ane/ane_fw_pages_test.c diff --git a/drivers/accel/ane/Makefile b/drivers/accel/ane/Makefile index 4557afbf5ddc55..2dc4fd3340e787 100644 --- a/drivers/accel/ane/Makefile +++ b/drivers/accel/ane/Makefile @@ -3,13 +3,14 @@ obj-$(CONFIG_DRM_ACCEL_ANE) += ane.o ane_t6021.o obj-$(CONFIG_DRM_ACCEL_ANE_PM_KUNIT_TEST) += ane_pm_test.o ane_t6021_pm_test.o ane_fw_ids_test.o obj-$(CONFIG_DRM_ACCEL_ANE_H16_VALIDATION) += ane_h16_hwx.o ane_h16_preload.o ane_h16_load.o \ - ane_h16_program.o + ane_h16_program.o ane_fw_pages.o obj-$(CONFIG_DRM_ACCEL_ANE_KUNIT_TEST) += ane_drv_test.o obj-$(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) += ane_fw_platform_test.o \ ane_fw_protocol_test.o ane_h16_tasks_test.o ane_h16_execute_test.o \ ane_fw_transport_test.o ane_h16_boot_test.o \ ane_h16_pending_test.o ane_h16_hwx_test.o ane_h16_preload_test.o \ ane_h16_program_test.o ane_fw_cold_test.o ane_h16_accel_test.o \ + ane_fw_pages_test.o \ ane_t6021_lifetime_test.o ane-y := \ diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 1cf7da420b3c97..1c391f6c6b01f4 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -18,13 +18,16 @@ #include #include #include +#include #include #include #include #include #include +#include #include "ane_fw_cold.h" +#include "ane_fw_pages.h" #include "ane_fw_sleep.h" #include "ane_h16_accel.h" @@ -54,6 +57,13 @@ struct ane_fw_mapping { dma_addr_t physical; /* The DVA range, for a mapping in the window. */ struct drm_mm_node node; + /* + * A cached surface: discontiguous pages (ane_fw_pages_alloc()), mapped + * through b->memory for cache maintenance and at consecutive DVAs. + */ + struct page **pages; + struct sg_table sgt; + bool dma_mapped; }; struct ane_fw_backend { @@ -1285,20 +1295,87 @@ static int ane_fw_retain(struct ane_fw_backend *b) return 0; } +/* + * iommu_map and iommu_map_sgtable include the DART's normal range + * synchronization and propagate its timeout. Extra invalidates do not fix + * stale output BAR bindings between programs; the transport's queued first + * EXECUTE after a program change does. + */ +static int ane_fw_map_status(struct ane_fw_backend *b) +{ + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) + if (ane_rd32(b, b->dart[i] + 0x100)) + return -EIO; + return 0; +} + static int ane_fw_map(struct ane_fw_backend *b, u64 dva, phys_addr_t pa, size_t size, int prot) { int ret = iommu_map(b->domain, dva, pa, size, prot, GFP_KERNEL); + return ret ?: ane_fw_map_status(b); +} + +/* + * Pages, CPU alias and cache maintenance of a cached surface no longer mapped + * for the engine (failed allocation before mapping, or after iommu_unmap()). + */ +static void ane_fw_pages_release(struct ane_fw_backend *b, struct ane_fw_mapping *m) +{ + if (m->sgt.sgl) { + if (m->dma_mapped) + dma_unmap_sgtable(b->memory, &m->sgt, DMA_BIDIRECTIONAL, + DMA_ATTR_SKIP_CPU_SYNC); + sg_free_table(&m->sgt); + } + if (m->surface.cpu) + vunmap(m->surface.cpu); + ane_fw_pages_free(m->pages, m->surface.size); +} + +/* + * A cached surface from discontiguous pages: blocks of the DART granule or + * larger, charged to the caller's memcg, with a contiguous CPU alias (vmap) + * and DVA range. The firmware runs from whatever the DARTs map, so nothing + * needs a contiguous physical range the size of the program, which only CMA + * could give (a 66 MB H17 program needed cma=256M). b->memory is dma-direct; + * its mapping only does the cache maintenance, so its addresses must be the + * physical ones. + */ +static int ane_fw_alloc_pages(struct ane_fw_backend *b, size_t size, struct ane_fw_mapping *m) +{ + struct scatterlist *sg; + int min_order, ret; + unsigned int i; + + min_order = ane_fw_pages_granule_order(b->domain->pgsize_bitmap); + if (min_order < 0) + return min_order; + m->pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_RETRY_MAYFAIL); + if (IS_ERR(m->pages)) { + ret = PTR_ERR(m->pages); + m->pages = NULL; + return ret; + } + m->surface.size = size; + m->surface.cpu = vmap(m->pages, size >> PAGE_SHIFT, VM_MAP, PAGE_KERNEL); + if (!m->surface.cpu) + return -ENOMEM; + ret = sg_alloc_table_from_pages(&m->sgt, m->pages, size >> PAGE_SHIFT, 0, size, + GFP_KERNEL_ACCOUNT | __GFP_NOWARN); if (ret) return ret; - /* iommu_map includes the DART's normal range synchronization and - * propagates its timeout. Extra invalidates do not fix stale output - * BAR bindings between programs; the transport's queued first EXECUTE - * after a program change does. - */ - for (unsigned int i = 0; i < ANE_FW_DARTS; i++) - if (ane_rd32(b, b->dart[i] + 0x100)) + /* Writes the zeroes back before the engine sees the pages. */ + ret = dma_map_sgtable(b->memory, &m->sgt, DMA_BIDIRECTIONAL, 0); + if (ret) + return ret; + m->dma_mapped = true; + if (m->sgt.nents != m->sgt.orig_nents) + return -EIO; + for_each_sgtable_dma_sg(&m->sgt, sg, i) + if (sg_dma_address(sg) != sg_phys(sg) || sg_dma_len(sg) != sg->length) return -EIO; return 0; } @@ -1322,21 +1399,23 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, m = kzalloc_obj(*m); if (!m) return -ENOMEM; - if (cached) - m->surface.cpu = dma_alloc_noncoherent(b->memory, size, &m->physical, - DMA_BIDIRECTIONAL, GFP_KERNEL); - else + if (cached) { + ret = ane_fw_alloc_pages(b, size, m); + if (ret) { + /* Never mapped for the engine: free it all now. */ + ane_fw_pages_release(b, m); + kfree(m); + return ret; + } + /* The mapping: ane_fw_program_sync() maintains the whole of it. */ + m->surface.handle = (uintptr_t)m; + } else { m->surface.cpu = dma_alloc_coherent(b->memory, size, &m->physical, GFP_KERNEL); - if (!m->surface.cpu) { - kfree(m); - return -ENOMEM; - } - if (cached) { - /* Zero it and write the zeroes back before the engine sees it. */ - memset(m->surface.cpu, 0, size); - dma_sync_single_for_device(b->memory, m->physical, size, DMA_BIDIRECTIONAL); - m->surface.handle = m->physical; + if (!m->surface.cpu) { + kfree(m); + return -ENOMEM; + } } mutex_lock(&b->window_lock); if (dva == ANE_FW_WINDOW_ANY) { @@ -1347,8 +1426,7 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, if (ret) { mutex_unlock(&b->window_lock); if (cached) - dma_free_noncoherent(b->memory, size, m->surface.cpu, - m->physical, DMA_BIDIRECTIONAL); + ane_fw_pages_release(b, m); else dma_free_coherent(b->memory, size, m->surface.cpu, m->physical); kfree(m); @@ -1364,7 +1442,13 @@ static int ane_fw_alloc_mem(struct ane_fw_backend *b, u64 dva, size_t size, */ list_add_tail(&m->list, &b->mappings); mutex_unlock(&b->window_lock); - ret = ane_fw_map(b, dva, m->physical, size, prot); + if (cached) { + ssize_t mapped = iommu_map_sgtable(b->domain, dva, &m->sgt, prot); + + ret = mapped < 0 ? mapped : (size_t)mapped != size ? -EIO : ane_fw_map_status(b); + } else { + ret = ane_fw_map(b, dva, m->physical, size, prot); + } if (!ret) *s = m->surface; return ret; @@ -1989,8 +2073,7 @@ static void ane_fw_program_unmap(void *ctx, const struct ane_fw_surface *s) mutex_unlock(&b->window_lock); return; } - dma_free_noncoherent(b->memory, s->size, m->surface.cpu, m->physical, - DMA_BIDIRECTIONAL); + ane_fw_pages_release(b, m); mutex_lock(&b->window_lock); drm_mm_remove_node(&m->node); mutex_unlock(&b->window_lock); @@ -2008,11 +2091,12 @@ static void ane_fw_program_log(void *ctx, const char *item, u64 a, u64 c) static void ane_fw_program_sync(void *ctx, const struct ane_fw_surface *s, bool for_device) { struct ane_fw_backend *b = ctx; + struct ane_fw_mapping *m = (struct ane_fw_mapping *)(uintptr_t)s->handle; if (for_device) - dma_sync_single_for_device(b->memory, s->handle, s->size, DMA_BIDIRECTIONAL); + dma_sync_sgtable_for_device(b->memory, &m->sgt, DMA_BIDIRECTIONAL); else - dma_sync_single_for_cpu(b->memory, s->handle, s->size, DMA_BIDIRECTIONAL); + dma_sync_sgtable_for_cpu(b->memory, &m->sgt, DMA_BIDIRECTIONAL); } static void ane_fw_program_busy(void *ctx, bool busy) diff --git a/drivers/accel/ane/ane_fw_pages.c b/drivers/accel/ane/ane_fw_pages.c new file mode 100644 index 00000000000000..c0dba2a11f0766 --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages.c @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Discontiguous backing for ANE buffers. The engine sees memory only through + * its DARTs, so a buffer needs to be contiguous in the engine's address + * space only: it is built from blocks of at least 1 << min_order pages (the + * DART granule), each physically contiguous and naturally aligned, and the + * caller maps them at consecutive DVAs. A large program then loads without a + * contiguous allocation the size of the program (CMA, or the buddy + * allocator's largest order). + */ +#include +#include +#include +#include +#include +#include + +#include "ane_fw_pages.h" + +/** + * ane_fw_pages_alloc - zeroed pages for a buffer the engine sees through its DARTs + * @size: bytes, a nonzero multiple of PAGE_SIZE << @min_order + * @min_order: order of the smallest block: the DART granule + * @max_order: order of the largest block to try + * @gfp: allocation flags of the smallest blocks (__GFP_ACCOUNT also charges + * the page array) + * + * Blocks start at the largest order the remaining size fills, as dma-iommu + * builds its buffers, and fall back to smaller ones; an order that failed is + * not tried again for this buffer. Only the smallest blocks reclaim as @gfp + * permits: the larger ones are opportunistic (__GFP_NORETRY). No failure + * warns: userspace chooses the size. + * + * Every block is split into order-0 pages, so each page has its own + * reference, as vm_insert_pages() and vmap() want; pages[i * (1 << min_order)] + * starts a physically contiguous block of at least 1 << min_order pages, + * naturally aligned. + * + * Return: the page array (kvfree()d by ane_fw_pages_free()), or an ERR_PTR. + */ +struct page **ane_fw_pages_alloc(size_t size, unsigned int min_order, + unsigned int max_order, gfp_t gfp) +{ + unsigned long count = size >> PAGE_SHIFT, done = 0; + unsigned int order; + struct page **pages; + + if (!size || min_order > MAX_PAGE_ORDER || + !IS_ALIGNED(size, PAGE_SIZE << min_order) || (gfp & __GFP_COMP)) + return ERR_PTR(-EINVAL); + gfp |= __GFP_ZERO | __GFP_NOWARN; + pages = kvcalloc(count, sizeof(*pages), + GFP_KERNEL | (gfp & __GFP_ACCOUNT) | __GFP_NOWARN); + if (!pages) + return ERR_PTR(-ENOMEM); + order = clamp(max_order, min_order, (unsigned int)MAX_PAGE_ORDER); + while (done < count) { + struct page *page; + + order = ane_fw_pages_order(count - done, order, min_order); + page = alloc_pages(order > min_order ? + (gfp & ~__GFP_RETRY_MAYFAIL) | __GFP_NORETRY : gfp, + order); + if (!page) { + if (order == min_order) + goto fail; + order--; + continue; + } + if (order) + split_page(page, order); + for (unsigned long i = 0; i < 1UL << order; i++) + pages[done + i] = page + i; + done += 1UL << order; + } + return pages; + +fail: + ane_fw_pages_free(pages, done << PAGE_SHIFT); + return ERR_PTR(-ENOMEM); +} +EXPORT_SYMBOL_GPL(ane_fw_pages_alloc); + +/* Free the first @size bytes of pages and the array; NULL is a no-op. */ +void ane_fw_pages_free(struct page **pages, size_t size) +{ + if (!pages) + return; + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) + __free_page(pages[i]); + kvfree(pages); +} +EXPORT_SYMBOL_GPL(ane_fw_pages_free); + +MODULE_DESCRIPTION("Discontiguous page backing for Apple Neural Engine buffers"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_fw_pages.h b/drivers/accel/ane/ane_fw_pages.h new file mode 100644 index 00000000000000..500356577157f2 --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages.h @@ -0,0 +1,41 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef __ANE_FW_PAGES_H__ +#define __ANE_FW_PAGES_H__ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Minimum page allocation order for an IOMMU domain's smallest granule, or + * -EINVAL if @pgsize_bitmap has no page size set. + */ +static inline int ane_fw_pages_granule_order(unsigned long pgsize_bitmap) +{ + if (!pgsize_bitmap) + return -EINVAL; + return get_order(1UL << __ffs(pgsize_bitmap)); +} + +/* + * The order of the next block of a discontiguous buffer with @remaining + * pages to go, at most @order (the last order that worked) and at least + * @min_order: the largest power of two the rest still fills. @remaining is + * a nonzero multiple of 1 << @min_order. + */ +static inline unsigned int ane_fw_pages_order(unsigned long remaining, unsigned int order, + unsigned int min_order) +{ + return max(min_t(unsigned int, order, ilog2(remaining)), min_order); +} + +struct page **ane_fw_pages_alloc(size_t size, unsigned int min_order, + unsigned int max_order, gfp_t gfp); +void ane_fw_pages_free(struct page **pages, size_t size); + +#endif diff --git a/drivers/accel/ane/ane_fw_pages_test.c b/drivers/accel/ane/ane_fw_pages_test.c new file mode 100644 index 00000000000000..c27f81cbb78d1b --- /dev/null +++ b/drivers/accel/ane/ane_fw_pages_test.c @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include +#include +#include +#include +#include + +#include "ane_fw_pages.h" + +/* The largest block the rest fills, never above the last one that worked. */ +static void ane_pages_order_test(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(13, 7, 0), 3U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(5, 7, 0), 2U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(1, 7, 0), 0U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(4096, 7, 0), 7U); + /* After a failure at order 3, a 13-page rest takes order 2 blocks. */ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(13, 2, 0), 2U); + /* Never below the DART granule. */ + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(4, 7, 2), 2U); + KUNIT_EXPECT_EQ(test, ane_fw_pages_order(12, 1, 2), 2U); +} + +/* + * Every DART granule is physically contiguous and aligned, every page is an + * order-0 page with its own reference, and the memory is zeroed. + */ +static void ane_pages_check(struct kunit *test, struct page **pages, size_t size, + unsigned int min_order) +{ + unsigned long block = 1UL << min_order, count = size >> PAGE_SHIFT; + + for (unsigned long i = 0; i < count; i++) { + unsigned long first = page_to_pfn(pages[round_down(i, block)]); + + KUNIT_ASSERT_NOT_NULL(test, pages[i]); + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(first, block)); + KUNIT_EXPECT_EQ(test, page_to_pfn(pages[i]), first + i % block); + KUNIT_EXPECT_FALSE(test, PageCompound(pages[i])); + KUNIT_EXPECT_EQ(test, page_count(pages[i]), 1); + KUNIT_EXPECT_TRUE(test, mem_is_zero(page_address(pages[i]), PAGE_SIZE)); + } +} + +/* A size that is no power of two takes blocks of several orders. */ +static void ane_pages_mixed_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + size_t size = 13 * SZ_16K; + struct page **pages; + u8 *cpu; + + pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, size, min_order); + /* The CPU alias the backend makes: one contiguous view of every page. */ + cpu = vmap(pages, size >> PAGE_SHIFT, VM_MAP, PAGE_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cpu); + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) + cpu[i * PAGE_SIZE + 7] = i + 1; + for (unsigned long i = 0; i < size >> PAGE_SHIFT; i++) { + KUNIT_EXPECT_EQ(test, ((u8 *)page_address(pages[i]))[7], (u8)(i + 1)); + KUNIT_EXPECT_PTR_EQ(test, vmalloc_to_page(cpu + i * PAGE_SIZE), pages[i]); + } + vunmap(cpu); + ane_fw_pages_free(pages, size); +} + +/* The minimum block order follows the IOMMU domain's smallest page size. */ +static void ane_pages_granule_test(struct kunit *test) +{ + struct page **pages; + int min_order; + + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(0), -EINVAL); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_4K), get_order(SZ_4K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_16K), get_order(SZ_16K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_64K), get_order(SZ_64K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_16K | SZ_2M), get_order(SZ_16K)); + KUNIT_EXPECT_EQ(test, ane_fw_pages_granule_order(SZ_4K | SZ_16K), get_order(SZ_4K)); + + min_order = ane_fw_pages_granule_order(SZ_64K | SZ_2M); + KUNIT_ASSERT_GE(test, min_order, 0); + /* The helper enforces zeroing even when __GFP_ZERO is omitted. */ + pages = ane_fw_pages_alloc(3 * SZ_64K, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 3 * SZ_64K, min_order); + ane_fw_pages_free(pages, 3 * SZ_64K); +} + +/* A larger buffer, as a program region: granule blocks at the very least. */ +static void ane_pages_large_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + size_t size = SZ_8M + 3 * SZ_16K; + struct page **pages; + + pages = ane_fw_pages_alloc(size, min_order, get_order(SZ_2M), + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, size, min_order); + ane_fw_pages_free(pages, size); +} + +/* Orders out of the allocator's range are clamped, not tried (or warned about). */ +static void ane_pages_clamp_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + struct page **pages; + + pages = ane_fw_pages_alloc(2 * SZ_16K, min_order, MAX_PAGE_ORDER + 4, + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 2 * SZ_16K, min_order); + ane_fw_pages_free(pages, 2 * SZ_16K); + /* A maximum below the granule still allocates granules. */ + pages = ane_fw_pages_alloc(3 * SZ_16K, min_order, 0, + GFP_KERNEL_ACCOUNT | __GFP_ZERO); + KUNIT_ASSERT_FALSE(test, IS_ERR(pages)); + ane_pages_check(test, pages, 3 * SZ_16K, min_order); + ane_fw_pages_free(pages, 3 * SZ_16K); +} + +static void ane_pages_invalid_test(struct kunit *test) +{ + unsigned int min_order = get_order(SZ_16K); + + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(0, min_order, 7, GFP_KERNEL)), + -EINVAL); + /* Only whole DART granules. */ + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(5 * PAGE_SIZE, 2, 7, GFP_KERNEL)), + -EINVAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(SZ_16K, MAX_PAGE_ORDER + 1, + MAX_PAGE_ORDER + 1, GFP_KERNEL)), + -EINVAL); + KUNIT_EXPECT_EQ(test, PTR_ERR(ane_fw_pages_alloc(SZ_16K, min_order, min_order, + GFP_KERNEL | __GFP_COMP)), + -EINVAL); + /* Freeing nothing is fine. */ + ane_fw_pages_free(NULL, SZ_16K); +} + +static struct kunit_case ane_pages_cases[] = { + KUNIT_CASE(ane_pages_order_test), + KUNIT_CASE(ane_pages_granule_test), + KUNIT_CASE(ane_pages_mixed_test), + KUNIT_CASE(ane_pages_large_test), + KUNIT_CASE(ane_pages_clamp_test), + KUNIT_CASE(ane_pages_invalid_test), + {} +}; + +static struct kunit_suite ane_pages_suite = { + .name = "ane-fw-pages", + .test_cases = ane_pages_cases, +}; + +kunit_test_suite(ane_pages_suite); + +MODULE_DESCRIPTION("KUnit tests for the ANE discontiguous page backing"); +MODULE_LICENSE("Dual MIT/GPL"); From d51708aa33c203e1950a51a28efeed62f07f3ad3 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 13:32:40 -0500 Subject: [PATCH 0672/1514] drm/apple: let a preferred timing with unsafe SDR elements be the default A Dell S2725QS on a USB-C to HDMI cable (a Parade PS176 converter) came up at 1920x1080 120 Hz on a Mac Studio (M5 Max, dcpext0) instead of its native 3840x2160 60 Hz. The firmware marks 3840x2160 60 Hz IsPreferred and scores it highest, but lists every one of its color elements in UnsafeColorElementIDs, and the external default has skipped any timing without a safe SDR element since it was introduced. Of the timings the firmware prefers that left 1920x1080 120 Hz. The unsafe elements are those of the timings above 340 MHz (3840x2160 60 Hz at 594 MHz, 2560x1440 120 Hz at 498 MHz), the clock in the EDID's HDMI 1.4 block; its HDMI 2.x block takes 600 MHz. macOS reads the same list from the same firmware (its TimingElements match, unsafe lists included) and drives the 60 Hz timing, DPTimingModeId 50, over an HBR2 x4 link. Linux sets it too when asked: the firmware programs it and keeps the link up, with no IRQ_HPD or unplug. Let a timing stay a default candidate when its SDR elements are only unsafe and the firmware marks it IsPreferred. A timing only DSC can carry still never is, nor is an unsafe timing the firmware does not prefer. The T8140 external path (J700), which never offers unsafe elements outside its 1080p180 policy, is unchanged. Nothing falls back to another timing when the default fails to light up, so an unsafe timing is the default only when the firmware prefers no usable timing of the native resolution. When it prefers one, the unsafe timings are left out and the usable ones rank as they did before. On the Dell the only usable 3840x2160 timing is the 30 Hz one, which the firmware does not prefer, so 60 Hz is still the default. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/parser-test.c | 266 ++++++++++++++++++++++++++++ drivers/gpu/drm/apple/parser.c | 57 +++++- drivers/gpu/drm/apple/parser.h | 6 + 3 files changed, 322 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index e79da0fb0ad08e..2c277e32b33cde 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -2072,6 +2072,268 @@ static void parser_internal_v27_only_120hz(struct kunit *test) dcp_modes_release(dcp); } +struct parser_unsafe_timing { + s64 id, score; + s64 hactive, htotal, hporch, hsync; + s64 vactive, vtotal, vporch, vsync, refresh; + bool preferred, unsafe, dsc, second; +}; + +static void blob_color_ids(struct parser_blob *blob, const char *key, bool listed) +{ + blob_key(blob, key); + blob_tag(blob, 2, listed); + if (listed) { + blob_tag(blob, 4, 0); + put_unaligned_le64(80, blob->data + blob->size); + blob->size += 8; + } +} + +/* + * A timing as a desktop dcpext lists it for a monitor behind a DP to HDMI + * converter: one RGB element (ID 80), which UnsafeColorElementIDs and + * DSCRequiredColorElementIDs may list, and optionally a second (ID 81) that + * neither does. + */ +static void blob_unsafe_timing(struct parser_blob *blob, + const struct parser_unsafe_timing *t) +{ + blob_tag(blob, 1, 10); + blob_bool(blob, "IsVirtual", false); + blob_int(blob, "ID", t->id); + blob_int(blob, "Score", t->score); + blob_timing_dimension(blob, "HorizontalAttributes", t->hactive, t->htotal, + t->hporch, t->hsync, + ((u64)t->vtotal * t->refresh << 16) / 1000); + blob_timing_dimension(blob, "VerticalAttributes", t->vactive, t->vtotal, + t->vporch, t->vsync, t->refresh << 16); + blob_color_ids(blob, "UnsafeColorElementIDs", t->unsafe); + blob_color_ids(blob, "DSCRequiredColorElementIDs", t->dsc); + blob_key(blob, "ColorModes"); + blob_tag(blob, 2, 1 + t->second); + blob_color(blob, 80, 242999, 0, DCP_COLOR_FORMAT_RGB); + if (t->second) + blob_color(blob, 81, 242998, 0, DCP_COLOR_FORMAT_RGB); + blob_bool(blob, "IsPreferred", t->preferred); + blob_bool(blob, "IsInterlaced", false); +} + +static struct dcp_display_mode * +parser_unsafe_modes(struct kunit *test, struct parser_blob *blob, + const struct parser_unsafe_timing *timings, unsigned int n, + bool external_sdr, unsigned int *count) +{ + struct dcp_parse_ctx ctx; + unsigned int i; + + put_unaligned_le32(0xd3, blob->data); + blob->size = 4; + blob_tag(blob, 2, n); + for (i = 0; i < n; i++) + blob_unsafe_timing(blob, &timings[i]); + if (parse(blob->data, blob->size, &ctx)) + return ERR_PTR(-EINVAL); + ctx.dcp = &parser_dcp; + return enumerate_modes(&ctx, count, 600, 340, 0, false, external_sdr); +} + +static const struct dcp_display_mode * +parser_default_mode(const struct dcp_display_mode *modes, unsigned int count) +{ + const struct dcp_display_mode *found = NULL; + unsigned int i; + + for (i = 0; i < count; i++) + if (modes[i].mode.type & DRM_MODE_TYPE_PREFERRED) { + if (found) + return NULL; + found = &modes[i]; + } + return found; +} + +/* + * A Dell S2725QS behind a USB-C to HDMI cable: firmware marks 3840x2160 at + * 60 Hz IsPreferred with the highest score, but lists its only element as + * unsafe (594 MHz is above the 340 MHz of the EDID's HDMI 1.4 block), and + * also prefers 1920x1080 at 120 Hz. macOS drives the 60 Hz timing; so must + * the default. An unsafe timing the firmware does not prefer never is. + */ +static void parser_unsafe_preferred_default(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, false, false }, + { 77, 6442, 2560, 2720, 48, 32, 1440, 1525, 3, 5, 120, false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + for (i = 0; i < count; i++) { + KUNIT_EXPECT_EQ(test, modes[i].color_mode_id, 80); + KUNIT_EXPECT_EQ(test, modes[i].sdr_usable, !timings[i].unsafe); + KUNIT_EXPECT_EQ(test, modes[i].sdr_unsafe, timings[i].unsafe); + } + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 50); + KUNIT_EXPECT_EQ(test, def->mode.clock, 594000); + kfree(modes); + + /* Not preferred, the unsafe 60 Hz timing leaves 1920x1080 the default. */ + timings[1].preferred = false; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 72); + kfree(modes); +} + +/* + * A timing only DSC can carry is not an unsafe one: preferred or not, and + * whether or not its element is listed as unsafe too, it is never a default + * candidate. + */ +static void parser_unsafe_preferred_dsc(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, pass; + + KUNIT_ASSERT_NOT_NULL(test, blob); + for (pass = 0; pass < 2; pass++) { + timings[1].unsafe = pass; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, modes[1].timing_mode_id, 50); + KUNIT_EXPECT_TRUE(test, modes[1].firmware_preferred); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_usable); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_unsafe); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_candidate(&modes[1])); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_candidate(&modes[0])); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 72); + kfree(modes); + } +} + +/* + * The external SDR path (T8140) never records an unsafe element: it drops a + * timing whose only element is unsafe, and one with a safe element besides + * is plainly usable. The same catalog elsewhere records both. + */ +static void parser_unsafe_external_sdr(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, true, true, + false, true }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + true, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 2U); + KUNIT_EXPECT_EQ(test, modes[0].timing_mode_id, 72); + KUNIT_EXPECT_EQ(test, modes[1].timing_mode_id, 48); + KUNIT_EXPECT_EQ(test, modes[1].color_mode_id, 81); + for (i = 0; i < count; i++) { + KUNIT_EXPECT_TRUE(test, modes[i].firmware_preferred); + KUNIT_EXPECT_TRUE(test, modes[i].sdr_usable); + KUNIT_EXPECT_FALSE(test, modes[i].sdr_unsafe); + } + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, 48); + kfree(modes); + + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 3U); + KUNIT_EXPECT_FALSE(test, modes[1].sdr_usable); + KUNIT_EXPECT_TRUE(test, modes[1].sdr_unsafe); + KUNIT_EXPECT_TRUE(test, modes[2].sdr_usable); + KUNIT_EXPECT_TRUE(test, modes[2].sdr_unsafe); + kfree(modes); +} + +/* + * Two timings of the native resolution, both IsPreferred: the one with a + * usable SDR element is the default, whatever the refresh rate of the unsafe + * one, since nothing falls back to it when the unsafe timing fails. The + * unsafe timing is then out of the ranking altogether, as it was before it + * could be a candidate. + */ +static void parser_unsafe_preferred_usable_wins(struct kunit *test) +{ + struct parser_unsafe_timing timings[] = { + { 72, 16349, 1920, 2200, 88, 44, 1080, 1125, 4, 5, 120, true, false }, + { 50, 16598, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 60, true, true }, + { 48, 15379, 3840, 4400, 176, 88, 2160, 2250, 8, 10, 30, true, false }, + { 46, 15000, 3840, 5500, 1276, 88, 2160, 2250, 8, 10, 24, false, false }, + }; + static const struct { + bool preferred_30, preferred_24; + s64 expect; + } cases[] = { + /* Usable and preferred at 30 Hz beats unsafe and preferred at 60 Hz. */ + { true, false, 48 }, + /* No usable timing is preferred: the Dell S2725QS case, 60 Hz. */ + { false, false, 50 }, + /* + * Only the 24 Hz one is: the unsafe timing is out, and the + * usable ones rank as ever, the higher refresh rate first. + */ + { false, true, 48 }, + }; + struct parser_blob *blob = kunit_kzalloc(test, sizeof(*blob), GFP_KERNEL); + const struct dcp_display_mode *def; + struct dcp_display_mode *modes; + unsigned int count, i; + + KUNIT_ASSERT_NOT_NULL(test, blob); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + timings[2].preferred = cases[i].preferred_30; + timings[3].preferred = cases[i].preferred_24; + modes = parser_unsafe_modes(test, blob, timings, ARRAY_SIZE(timings), + false, &count); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, modes); + KUNIT_ASSERT_EQ(test, count, 4U); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_candidate(&modes[1])); + def = parser_default_mode(modes, count); + KUNIT_ASSERT_NOT_NULL(test, def); + KUNIT_EXPECT_EQ(test, def->timing_mode_id, cases[i].expect); + kfree(modes); + } +} + static struct kunit_case parser_cases[] = { KUNIT_CASE(parser_internal_v27_only_120hz), KUNIT_CASE(parser_panel_of_dimensions), @@ -2116,6 +2378,10 @@ static struct kunit_case parser_cases[] = { KUNIT_CASE(parser_catalog_release), KUNIT_CASE(parser_property_bounds), KUNIT_CASE(parser_desktop_metadata_timing), + KUNIT_CASE(parser_unsafe_preferred_default), + KUNIT_CASE(parser_unsafe_preferred_dsc), + KUNIT_CASE(parser_unsafe_external_sdr), + KUNIT_CASE(parser_unsafe_preferred_usable_wins), {} }; diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 28c429e48ecc75..de2cbc5a605aa7 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -639,6 +639,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, out->best.score = -1; out->pq.score = -1; out->sdr_usable = false; + out->sdr_unsafe = false; out->has_bootstrap = false; ret = iterator_begin(handle, &outer_it, false); @@ -730,6 +731,9 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, (!timing_color_contains(&limits->unsafe, cmode.id) && !timing_color_contains(&limits->dsc_required, cmode.id)))) out->sdr_usable = true; + else if (!external_sdr && cmode.eotf == DCP_EOTF_SDR_GAMMA && + !timing_color_contains(&limits->dsc_required, cmode.id)) + out->sdr_unsafe = true; if (external_sdr) { unsigned int rank; @@ -1186,9 +1190,9 @@ static bool dcp_180hz_ids_current(struct dcp_parse_ctx handle, /* * An external display defaults to its native resolution at the highest * refresh rate it can take, as other systems pick it, rather than to the - * timing its EDID lists first. Among the timings of that resolution with a - * usable SDR element, the higher refresh rate ranks first, then IsPreferred, - * then the firmware score. + * timing its EDID lists first. Among the default candidates of that + * resolution, the higher refresh rate ranks first, then IsPreferred, then the + * firmware score. */ VISIBLE_IF_KUNIT bool dcp_mode_default_above(const struct dcp_display_mode *mode, s64 score, @@ -1206,21 +1210,54 @@ VISIBLE_IF_KUNIT bool dcp_mode_default_above(const struct dcp_display_mode *mode return score > best_score; } +/* + * A timing the default may be. Firmware lists a color element as unsafe + * when the timing needs a faster link than it can vouch for: behind a USB-C + * to HDMI cable (a Parade PS176) a Dell S2725QS gets every 3840x2160 60 Hz + * element listed, the timings above the 340 MHz of its EDID's HDMI 1.4 block + * being unsafe though its HDMI 2.x block takes 600 MHz. The firmware still + * marks that timing IsPreferred and scores it highest, and macOS drives it + * at 60 Hz (DPTimingModeId 50, an HBR2 x4 link) from the same list. So a + * timing the firmware prefers stays a candidate when its SDR elements are + * unsafe; one only DSC can carry does not, and neither does an unsafe timing + * the firmware does not prefer. dcp_external_default() still passes it over + * when the firmware also prefers a usable timing of the same resolution. + */ +VISIBLE_IF_KUNIT bool dcp_mode_default_candidate(const struct dcp_display_mode *m) +{ + if (m->automatic_rgb8_quirk) + return false; + return m->sdr_usable || (m->sdr_unsafe && m->firmware_preferred); +} + +static bool dcp_mode_same_size(const struct dcp_display_mode *a, + const struct dcp_display_mode *b) +{ + return a->mode.hdisplay == b->mode.hdisplay && + a->mode.vdisplay == b->mode.vdisplay; +} + /* * The native resolution: the largest the firmware marks IsPreferred, or the * largest of all when it marks none. + * + * Nothing falls back to another timing when the default fails to light up, + * so a timing with only unsafe SDR elements is the default only when the + * firmware prefers no usable timing of the native resolution. With one, the + * unsafe timings are left out and the usable ones rank among themselves. */ static struct dcp_display_mode *dcp_external_default(struct dcp_display_mode *modes, unsigned int count) { struct dcp_display_mode *native = NULL, *best = NULL; + bool usable_preferred = false; unsigned int i; for (i = 0; i < count; i++) { const struct dcp_display_mode *m = &modes[i]; u64 area = (u64)m->mode.hdisplay * m->mode.vdisplay; - if (m->automatic_rgb8_quirk || !m->sdr_usable) + if (!dcp_mode_default_candidate(m)) continue; if (!native || (m->firmware_preferred && !native->firmware_preferred) || @@ -1230,12 +1267,18 @@ static struct dcp_display_mode *dcp_external_default(struct dcp_display_mode *mo } if (!native) return NULL; + for (i = 0; i < count; i++) { + const struct dcp_display_mode *m = &modes[i]; + + if (dcp_mode_default_candidate(m) && dcp_mode_same_size(m, native) && + m->sdr_usable && m->firmware_preferred) + usable_preferred = true; + } for (i = 0; i < count; i++) { struct dcp_display_mode *m = &modes[i]; - if (m->automatic_rgb8_quirk || !m->sdr_usable || - m->mode.hdisplay != native->mode.hdisplay || - m->mode.vdisplay != native->mode.vdisplay) + if (!dcp_mode_default_candidate(m) || !dcp_mode_same_size(m, native) || + (usable_preferred && !m->sdr_usable)) continue; if (!best || dcp_mode_default_above(m, m->score, best, best->score)) best = m; diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index f39ec76b9bb0bd..607aa029adca73 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -163,6 +163,11 @@ struct dcp_display_mode { bool firmware_preferred; /* An SDR color element that is neither unsafe nor DSC only */ bool sdr_usable; + /* + * An SDR color element the firmware lists as unsafe, but not DSC + * only, outside the external SDR path + */ + bool sdr_unsafe; /* The firmware score of the timing */ s64 score; /* The sync polarity flags of the timing, if it reports them */ @@ -202,6 +207,7 @@ bool dcp_property_complete(const void *blob, size_t received, size_t advertised) #if IS_ENABLED(CONFIG_KUNIT) bool dcp_mode_default_above(const struct dcp_display_mode *mode, s64 score, const struct dcp_display_mode *best, s64 best_score); +bool dcp_mode_default_candidate(const struct dcp_display_mode *m); bool dcp_mode_ranks_above(bool preferred, s64 score, bool best_preferred, s64 best_score); #endif From e7daf694732bf91042481030c7447c74be4b4d64 Mon Sep 17 00:00:00 2001 From: Alyx-ML <256263590+Alyx-ML@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:10:52 +0000 Subject: [PATCH 0673/1514] ci: build the Apple drivers and run their KUnit suites CI compiled only apple-sep.o and the DWC3 object. It ran only sep.kunitconfig and mt7932.kunitconfig. Most Apple drivers and their kunitconfig files had no CI at all. A change that broke them was only found on hardware. The new workflow has two jobs: - apple-build: arm64 defconfig plus asahi.config with LLVM=1 and Rust 1.96.0 (the host-tests pin), with the tree's own bindgen. It checks that every Apple driver is still in .config, so a driver that drops out cannot pass by building nothing. Then it compiles the Apple driver directories and the core files the user4k and KSM work touches. - kunit: one arm64 QEMU run per suite (ANE boot and PM; DCP fabric and topology; asahi; spi-hid; AVD; AVE; ISP; JPEG; ProRes; scaler; macsmc; CLPC; trusted keys). fail-fast is off. Suites that already have their own workflow are not repeated: sep, mt7932, the Apple display suite (apple-drm-kunit.yml) and pmgr-pwrstate. Two kunitconfigs are left out because another one runs the same suites: ane transport.kunitconfig (boot.kunitconfig also sets UBSAN_SHIFT, and KASAN_INLINE is the default) and avd-pm.kunitconfig (PM_SLEEP is on by default on arm64). push on integration/aurora uses the same paths filter as pull_request, as dt-checks.yml does, so an unrelated merge does not start the jobs. Two suites had no kunitconfig, so add them: - drivers/mfd/macsmc.kunitconfig runs the macsmc MFD and macsmc-power KUnit tests. - security/keys/trusted-keys/tests/.kunitconfig runs trusted_source, the tests for trust sources registered at runtime. PR #2697 adds the AVE host harnesses to host-tests. This does not overlap with it. Verified: the YAML parses, every matrix kunitconfig exists in this tree, and the push and pull_request paths lists are the same. Signed-off-by: Alyx-ML <256263590+Alyx-ML@users.noreply.github.com> --- .github/workflows/apple-build-kunit.yml | 189 ++++++++++++++++++ drivers/mfd/macsmc.kunitconfig | 11 + security/keys/trusted-keys/tests/.kunitconfig | 4 + 3 files changed, 204 insertions(+) create mode 100644 .github/workflows/apple-build-kunit.yml create mode 100644 drivers/mfd/macsmc.kunitconfig create mode 100644 security/keys/trusted-keys/tests/.kunitconfig diff --git a/.github/workflows/apple-build-kunit.yml b/.github/workflows/apple-build-kunit.yml new file mode 100644 index 00000000000000..431cc715d8dda2 --- /dev/null +++ b/.github/workflows/apple-build-kunit.yml @@ -0,0 +1,189 @@ +name: Apple build and KUnit + +# Compiles every Apple driver directory with the configuration a Mac runs +# (arm64 defconfig plus asahi.config, LLVM=1 and Rust), and runs each Apple +# KUnit suite on arm64 QEMU. The suites use synthetic devices and stubbed +# firmware, so no Apple hardware is needed. Suites that have their own +# workflow are not repeated here: sep.kunitconfig (sep-source.yml), +# mt7932.kunitconfig (mt7932-kunit.yml), display.kunitconfig +# (apple-drm-kunit.yml) and .kunitconfig.pmgr-pwrstate +# (pmgr-pwrstate-kunit.yml). + +on: + pull_request: + branches: [integration/aurora, aurora-wip] + paths: + - 'arch/arm64/configs/**' + - 'drivers/accel/ane/**' + - 'drivers/gpu/drm/apple/**' + - 'drivers/gpu/drm/asahi/**' + - 'drivers/hid/spi-hid/**' + - 'drivers/iommu/**' + - 'drivers/media/platform/apple/**' + - 'drivers/mfd/**' + - 'drivers/nvme/host/**' + - 'drivers/pci/controller/**' + - 'drivers/power/**' + - 'drivers/soc/apple/**' + - 'drivers/thunderbolt/**' + - 'fs/splice.c' + - 'include/**' + - 'kernel/sys.c' + - 'mm/**' + - 'rust/**' + - 'security/keys/**' + - 'tools/testing/selftests/drivers/ane/**' + - '**/Kconfig*' + - '**/Makefile' + - '.github/workflows/apple-build-kunit.yml' + # Same paths as pull_request, so an unrelated merge does not start the jobs. + push: + branches: [integration/aurora] + paths: + - 'arch/arm64/configs/**' + - 'drivers/accel/ane/**' + - 'drivers/gpu/drm/apple/**' + - 'drivers/gpu/drm/asahi/**' + - 'drivers/hid/spi-hid/**' + - 'drivers/iommu/**' + - 'drivers/media/platform/apple/**' + - 'drivers/mfd/**' + - 'drivers/nvme/host/**' + - 'drivers/pci/controller/**' + - 'drivers/power/**' + - 'drivers/soc/apple/**' + - 'drivers/thunderbolt/**' + - 'fs/splice.c' + - 'include/**' + - 'kernel/sys.c' + - 'mm/**' + - 'rust/**' + - 'security/keys/**' + - 'tools/testing/selftests/drivers/ane/**' + - '**/Kconfig*' + - '**/Makefile' + - '.github/workflows/apple-build-kunit.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: apple-build-kunit-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + RUST_VERSION: '1.96.0' + LIBCLANG_PATH: /usr/lib/llvm-18/lib + +jobs: + apple-build: + runs-on: ubuntu-24.04 + timeout-minutes: 120 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build dependencies + run: | + # Avoid the hosted runner's Azure mirror after repeated DNS failures. + # Keep signed Ubuntu archive/security suites and fail on update errors. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libclang-dev libelf-dev libssl-dev \ + flex bison bc pkg-config make perl + rustup toolchain install "$RUST_VERSION" --profile minimal --component rust-src --no-self-update + echo "RUSTUP_TOOLCHAIN=$RUST_VERSION" >> "$GITHUB_ENV" + - name: Prepare the layout-corrected bindgen + run: python3 tools/aurora-bindgen/build.py + - name: Configure as a Mac runs it + run: | + make LLVM=1 ARCH=arm64 rustavailable + make LLVM=1 ARCH=arm64 defconfig + scripts/kconfig/merge_config.sh -m .config arch/arm64/configs/asahi.config + make LLVM=1 ARCH=arm64 olddefconfig + # A driver that drops out of the configuration would build nothing and pass. + for opt in RUST=y DRM_ASAHI=m DRM_APPLE=m DRM_ACCEL_ANE=m VIDEO_APPLE_AVD=m \ + NVME_APPLE=m APPLE_DART=y PCIE_APPLE=y USB4=m USB4_APPLE_SOC=m \ + SPI_HID_APPLE_OF=m MFD_MACSMC=y MACSMC_POWER=m POWER_RESET_MACSMC=m \ + APPLE_SEP=m KSM=y MM_SUBPAGE=y; do + grep -qx "CONFIG_$opt" .config || { echo "::error::CONFIG_$opt is not set"; exit 1; } + done + - name: Compile the Apple drivers + run: | + make -j"$(nproc)" LLVM=1 ARCH=arm64 modules_prepare + make -j"$(nproc)" LLVM=1 ARCH=arm64 \ + drivers/accel/ane/ \ + drivers/gpu/drm/apple/ \ + drivers/gpu/drm/asahi/ \ + drivers/hid/spi-hid/ \ + drivers/iommu/ \ + drivers/media/platform/apple/ \ + drivers/mfd/ \ + drivers/nvme/host/ \ + drivers/pci/controller/ \ + drivers/power/ \ + drivers/soc/apple/ \ + drivers/thunderbolt/ \ + fs/splice.o kernel/sys.o mm/ksm.o mm/madvise.o mm/vma_exec.o + + kunit: + name: KUnit ${{ matrix.suite }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + strategy: + fail-fast: false + max-parallel: 4 + matrix: + include: + # boot.kunitconfig runs the same ANE suites as transport.kunitconfig. + # It also sets UBSAN_SHIFT, and KASAN_INLINE is the default, so it + # covers both. + - { suite: ane-boot, kunitconfig: drivers/accel/ane/boot.kunitconfig } + - { suite: ane-pm, kunitconfig: tools/testing/selftests/drivers/ane/pm.kunitconfig } + - { suite: dcp-fabric, kunitconfig: drivers/gpu/drm/apple/tests/.kunitconfig } + - { suite: dcp-topology, kunitconfig: drivers/gpu/drm/apple/tests/topology.kunitconfig } + - { suite: asahi, kunitconfig: drivers/gpu/drm/asahi/.kunitconfig, rust: true } + - { suite: spi-hid-apple, kunitconfig: drivers/hid/spi-hid/.kunitconfig } + # avd-pm.kunitconfig runs the same AVD suites. PM_SLEEP, which it + # adds, is already on by default on arm64. + - { suite: avd, kunitconfig: drivers/media/platform/apple/avd/tests/.kunitconfig } + - { suite: ave, kunitconfig: drivers/media/platform/apple/ave/.kunitconfig } + - { suite: isp, kunitconfig: drivers/media/platform/apple/isp/.kunitconfig } + - { suite: jpeg, kunitconfig: drivers/media/platform/apple/jpeg/.kunitconfig } + - { suite: prores, kunitconfig: drivers/media/platform/apple/prores/.kunitconfig } + - { suite: scaler, kunitconfig: drivers/media/platform/apple/scaler/.kunitconfig } + - { suite: macsmc, kunitconfig: drivers/mfd/macsmc.kunitconfig } + - { suite: clpc, kunitconfig: drivers/soc/apple/clpc.kunitconfig } + - { suite: trusted-keys, kunitconfig: security/keys/trusted-keys/tests/.kunitconfig } + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 1 + - name: Install kernel build and QEMU dependencies + run: | + # As sep-source.yml: avoid the hosted runner's Azure mirror. + if [ -f /etc/apt/apt-mirrors.txt ]; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu/' 'https://security.ubuntu.com/ubuntu/' | \ + sudo tee /etc/apt/apt-mirrors.txt >/dev/null + fi + sudo apt-get update -o APT::Update::Error-Mode=any + sudo apt-get install -y clang lld llvm libclang-dev libelf-dev libssl-dev \ + flex bison bc pkg-config make perl qemu-system-arm + - name: Pin the Rust toolchain and prepare bindgen + if: ${{ matrix.rust }} + run: | + rustup toolchain install "$RUST_VERSION" --profile minimal --component rust-src --no-self-update + echo "RUSTUP_TOOLCHAIN=$RUST_VERSION" >> "$GITHUB_ENV" + python3 tools/aurora-bindgen/build.py + - name: Run ${{ matrix.kunitconfig }} on arm64 QEMU + env: + KUNITCONFIG: ${{ matrix.kunitconfig }} + run: | + ./tools/testing/kunit/kunit.py run --arch=arm64 \ + --make_options LLVM=1 \ + --kunitconfig="$KUNITCONFIG" \ + --jobs="$(nproc)" --timeout=900 diff --git a/drivers/mfd/macsmc.kunitconfig b/drivers/mfd/macsmc.kunitconfig new file mode 100644 index 00000000000000..936dd1cab03136 --- /dev/null +++ b/drivers/mfd/macsmc.kunitconfig @@ -0,0 +1,11 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_POWER_SUPPLY=y +CONFIG_MACSMC_POWER=y +CONFIG_MACSMC_POWER_KUNIT_TEST=y diff --git a/security/keys/trusted-keys/tests/.kunitconfig b/security/keys/trusted-keys/tests/.kunitconfig new file mode 100644 index 00000000000000..3b5f98f28758fa --- /dev/null +++ b/security/keys/trusted-keys/tests/.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_KEYS=y +CONFIG_TRUSTED_KEYS=y +CONFIG_TRUSTED_SOURCE_KUNIT_TEST=y From c8d9878036247e24e7c5c10cce40930d05652d7c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 13:12:55 -0500 Subject: [PATCH 0674/1514] soc: apple: clpc: hold the ANE memory and fabric floor on T6050 The T6050 CLPC table has no ANE entry, so H17 ANE work on T6050 gets no DCS or fabric floor: with the CPUs idle both rails sit low while the engine runs. The ANE driver already publishes its in-flight work; add apple,t6050-clpc explicitly to apple_clpc_ane_providers[] and populate the T6050 ANE demand table entry. Hold DCS 6 and fabric 2 while ANE work is in flight, the top states the T6050 table already uses. On J775c, unet-320 (an 8-task conv UNet, 200 runs, ane-run.py) goes from a host p50 of 5504 us with no floor to 2551 us. Fabric 3 measured 2536 us, the same within run-to-run spread, so fabric stays at 2. Extend the KUnit and host CLPC demand tests to cover T6050 ANE demand, hold, and idle release. Signed-off-by: Satya Benson --- drivers/soc/apple/clpc.c | 25 +++++++++++++++++++++++++ tools/asahi/clpc-gpu-demand-tests.py | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index f0624d2a2563ce..11616667d7551d 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -483,6 +483,7 @@ EXPORT_SYMBOL_GPL(apple_clpc_ane_put); /* SoCs whose CLPC takes ANE input; each SoC has exactly one CLPC. */ static const struct of_device_id apple_clpc_ane_providers[] = { + { .compatible = "apple,t6050-clpc" }, { .compatible = "apple,t6041-max-clpc" }, { .compatible = "apple,t6041-clpc" }, { .compatible = "apple,t8140-clpc" }, @@ -2189,6 +2190,8 @@ static void apple_clpc_t6041_policy_test(struct kunit *test) apple_clpc_gpu_put(gpu); } +static const struct apple_clpc_hw apple_clpc_hw_t6050; + static void apple_clpc_ane_demand_hold_test(struct kunit *test) { struct apple_clpc_ane ane = {}; @@ -2243,6 +2246,20 @@ static void apple_clpc_ane_demand_hold_test(struct kunit *test) KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 7u); KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 3u); apple_clpc_ane_set_active(&ane, false); + /* T6050 holds DCS 6 and fabric 2 while ANE work is in flight. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6050.ane[APPLE_CLPC_DCS], 6); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6050.ane[APPLE_CLPC_SOC], 2); + clpc->hw = &apple_clpc_hw_t6050; + clpc->ane_states[APPLE_CLPC_DCS] = clpc->hw->ane[APPLE_CLPC_DCS]; + clpc->ane_states[APPLE_CLPC_SOC] = clpc->hw->ane[APPLE_CLPC_SOC]; + memset(demand, 0, sizeof(demand)); + apple_clpc_ane_set_active(&ane, true); + KUNIT_EXPECT_TRUE(test, apple_clpc_ane_input_demand(clpc, demand)); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_DCS], 6u); + KUNIT_EXPECT_EQ(test, demand[APPLE_CLPC_SOC], 2u); + apple_clpc_ane_set_active(&ane, false); + memset(demand, 0, sizeof(demand)); + KUNIT_EXPECT_FALSE(test, apple_clpc_ane_input_demand(clpc, demand)); } static void apple_clpc_ane_cluster_test(struct kunit *test) @@ -2405,6 +2422,14 @@ static const struct apple_clpc_hw apple_clpc_hw_t6050 = { [APPLE_CLPC_SOC] = { 1, 2, 2, 2 }, }, .gpu = { [APPLE_CLPC_DCS] = 6, [APPLE_CLPC_SOC] = 2 }, + /* + * ANE demand, measured on J775c (M5 Max, H17): DCS 6 and fabric 2, the + * top states this table already uses. unet-320 (8 tasks, 200 runs) + * host p50 is 5504 us with no ANE floor and 2551 us at (6, 2); (6, 3) + * measured 2536 us, the same within run-to-run spread, so fabric stays + * at 2. + */ + .ane = { [APPLE_CLPC_DCS] = 6, [APPLE_CLPC_SOC] = 2 }, .sustain = 3, .gpu_input = true, .idle_on_time = true, diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index 4cbdf9672d36bc..c377356d19361e 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -441,6 +441,24 @@ def cells(name): jiffies=1040; apple_clpc_sample(&c); assert(published==0 && queued_idle); } +// T6050 ANE work holds DCS 6 and fabric 2 while it runs (and keeps on-time +// idle sampling), sees a sub-sample request once, and releases after HOLD_MS. +static void check_t6050_ane(void) { + struct apple_clpc_ane ane={0}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6050,.agent=1,.mask=3,.ane=&ane}; + c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; + c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; + assert(c.hw->ane[APPLE_CLPC_DCS]==6 && c.hw->ane[APPLE_CLPC_SOC]==2 && c.hw->idle_on_time); + read_error=vote_error=0; pmgr_status=0; pmp_floor=0; jiffies=3000; published=~0u; + apple_clpc_sample(&c); assert(published==0 && c.last_reason==0); + ane.active=true; jiffies=3004; apple_clpc_sample(&c); + assert(published==0x26 && c.last_reason==32); + ane.active=false; ane.pending=true; jiffies=3008; apple_clpc_sample(&c); + assert(published==0x26 && c.last_reason==32 && !ane.pending); + jiffies=3012; apple_clpc_sample(&c); assert(published==0x26 && c.last_reason==16); + jiffies=3040; apple_clpc_sample(&c); assert(published==0 && c.last_reason==0 && queued_idle); +} + // T6040 ANE work also holds the second P cluster at its qualified frequency, // added on first use, for the vote hold after the last request, then drops it. static void check_t6040_ane(void) { @@ -752,6 +770,7 @@ def cells(name): check_t8140(); check_t8140_dense(); check_t8140_ane(); + check_t6050_ane(); check_low_power(); check_t6040_ane(); puts("PASS: T6040, T6041 and T8132 host demand; DT GPU busy share and down-step hold; T8140/T604x ANE, streaming, dense work, read errors and PMP backoff; idle release"); From b0a47e5ffaee91109327b25b395cb7b2ddb8d1a3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 06:57:56 +1100 Subject: [PATCH 0675/1514] drm/asahi: keep M3 packet rejection out of VM status The scheduler can reject an unpublished packet under queue pressure, and the runtime can reject a packet while preparing its next batch. Those errors terminate the packet fence. Recording them as a VM failure makes later binds fail even when the GPU can still run work for the VM. Complete rejected and cancelled packets without updating VM status. Keep the VM guard quarantined while a published prefix still owns resources, and preserve the permanent completion path for terminal GPU failures. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 2 +- drivers/gpu/drm/asahi/m3/m3_submit.rs | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 8bd242a483432b..08961e95b2a25b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -223,7 +223,7 @@ impl Inner { fn fail_front(&mut self,error:Error) { if let Ok((packet,_))=self.pending.remove(0) { if !self.packet_active(&packet) && !self.fault_captured {packet.release_guard();} - packet.finish(Err(error)); + packet.fail_packet(error); } } /// Signal every packet of `entries` (packets that continue past the batch included). diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9f..c2a94f4d695332 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -89,6 +89,14 @@ impl Packet { pub(crate) fn may_be_published(&self)->bool {self.published.load(Ordering::Relaxed)} pub(crate) fn retired(&self) {self.release_guard();self.finish(Ok(()));} pub(crate) fn finish(&self,result:Result) { + self.complete(result, true); + } + /// Fail the fence without making a packet rejection or cancellation a VM error. + /// A published prefix still owns its mappings until the runtime retires it. + pub(crate) fn fail_packet(&self,error:Error) { + self.complete(Err(error), false); + } + fn complete(&self,result:Result,fail_vm:bool) { // Retirement, cancellation and a queued scheduler timeout can race. // Claim error/signal ownership once; this flag is NOT proof that the // fence is signaled or that hardware DMA has stopped. @@ -99,7 +107,9 @@ impl Packet { // can't unmap memory under it. It stays with the packet until the runtime drops // the packet, after the firmware has provably stopped. if let Some(guard)=self.vm_job.lock().as_ref() {guard.quarantine();} - if let Some(status) = self.vm.status() { status.record(e); } + if fail_vm { + if let Some(status) = self.vm.status() { status.record(e); } + } self.completion.set_error(e); } // A scheduler job/fence and the runtime's last packet can outlive @@ -132,7 +142,7 @@ impl sched::JobImpl for Job { if let Err(e)=crate::m3::m3_runtime::Runtime::submit(&job.shared,job.packet.clone()) { pr_err!("M3 scheduler: submission failed {:?}\n",e); // submit() failed before this packet could be published. - job.packet.release_guard();job.packet.finish(Err(e)); + job.packet.release_guard();job.packet.fail_packet(e); } Ok(Some(Fence::from_fence(&job.packet.completion))) } @@ -160,7 +170,7 @@ impl sched::JobImpl for Job { } fn cancel(job:&mut Self) { crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); - job.packet.finish(Err(ECANCELED)); + job.packet.fail_packet(ECANCELED); } } struct AddressSpace<'a>(&'a mmu::Vm); From 6f14e0d084d0f450ff9a24e77459a7782671d9e4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 07:01:06 +1100 Subject: [PATCH 0676/1514] tools/asahi: test M3 packet and VM error completion Check that a rejected bystander can submit again, cancellation retains a live guard until retirement, and a terminal VM error remains visible. Build the packet completion methods against mock fences and VM status, and check that the tests fail when all fence errors become VM failures. Signed-off-by: Ryan Murray --- tools/asahi/m3-packet-completion-tests.py | 178 ++++++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 2 files changed, 179 insertions(+) create mode 100644 tools/asahi/m3-packet-completion-tests.py diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py new file mode 100644 index 00000000000000..34c45cf1cb2d4b --- /dev/null +++ b/tools/asahi/m3-packet-completion-tests.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Build a host test of M3's production packet completion with mock fences and VM state.""" +import argparse +from pathlib import Path +import subprocess + + +def method(source, signature): + start = source.index(signature) + body = source.index("{", start) + depth = 1 + end = body + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +MOCKS = r""" +use std::cell::Cell; +use std::sync::{Mutex, atomic::{AtomicBool, Ordering}}; +#[derive(Clone, Copy)] +struct Error(i32); +impl Error { + fn to_errno(self) -> i32 { self.0 } +} +type Result = std::result::Result<(), Error>; +const EIO: Error = Error(-5); +const EBUSY: Error = Error(-16); +const ECANCELED: Error = Error(-125); + +#[derive(Default)] +struct Vm { + error: Cell, +} +impl Vm { + fn status(&self) -> Option<&Self> { Some(self) } + fn id(&self) -> u32 { 1 } + fn record(&self, error: Error) { + if self.error.get() == 0 { + self.error.set(error.0); + } + } + fn submit(&self) -> Result { + match self.error.get() { + 0 => Ok(()), + code => Err(Error(code)), + } + } +} +#[derive(Default)] +struct Fence { + error: Cell, + signals: Cell, +} +impl Fence { + fn set_error(&self, error: Error) { self.error.set(error.0); } + fn signal(&self) { self.signals.set(self.signals.get() + 1); } +} +#[derive(Default)] +struct Guard(Cell); +impl Guard { + fn quarantine(&self) { self.0.set(true); } +} +struct Packet<'a> { + vm: &'a Vm, + vm_job: JobGuard, + finish_claimed: AtomicBool, + completion: Fence, + commands: [(); 1], +} +struct JobGuard(Mutex>); +impl JobGuard { + fn lock(&self) -> std::sync::MutexGuard<'_, Option> { self.0.lock().unwrap() } +} +macro_rules! pr_info { ($($arg:tt)*) => { let _ = format_args!($($arg)*); }; } +mod debug { + pub enum DebugFlags { M3PassTiming } + pub fn debug_enabled(_: DebugFlags) -> bool { false } +} +mod m3 { + pub mod agx_memory { pub fn publish() {} } + pub mod m3_runtime { pub fn physical_counter() -> u64 { 0 } } +} + +impl<'a> Packet<'a> { + fn new(vm: &'a Vm, guard: bool) -> Self { + Self { + vm, + vm_job: JobGuard(Mutex::new(guard.then(Guard::default))), + finish_claimed: AtomicBool::new(false), + completion: Fence::default(), + commands: [()], + } + } + fn profile_id(&self) -> usize { 0 } +""" + +TESTS = r""" +} + +#[test] +fn rejected_bystander_remains_admissible_after_another_vm_faults() { + let guilty = Vm::default(); + let bystander = Vm::default(); + let faulty = Packet::new(&guilty, true); + let rejected = Packet::new(&bystander, false); + faulty.finish(Err(EIO)); + rejected.fail_packet(EBUSY); + assert_eq!(guilty.error.get(), -5); + assert!(faulty.vm_job.lock().as_ref().unwrap().0.get()); + assert_eq!(rejected.completion.error.get(), -16); + assert_eq!(bystander.error.get(), 0); + assert!(bystander.submit().is_ok()); + + let later = Packet::new(&bystander, true); + later.retired(); + assert_eq!(later.completion.error.get(), 0); + assert_eq!(later.completion.signals.get(), 1); + assert!(later.vm_job.lock().is_none()); +} + +#[test] +fn cancellation_preserves_live_guard_and_signals_once() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.error.get(), -125); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); + packet.retired(); + assert!(packet.vm_job.lock().is_none()); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); +} + +#[test] +fn terminal_vm_error_remains_visible_and_blocks_the_same_vm() { + let vm = Vm::default(); + let faulty = Packet::new(&vm, true); + faulty.finish(Err(EIO)); + assert_eq!(vm.submit().unwrap_err().0, -5); + assert_eq!(faulty.completion.signals.get(), 1); + assert_eq!(faulty.completion.error.get(), -5); +} +""" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--static", action="store_true", help="link without guest libraries") + parser.add_argument("--mutate", action="store_true") + args = parser.parse_args() + repo = Path(__file__).resolve().parents[2] + path = repo / "drivers/gpu/drm/asahi/m3/m3_submit.rs" + source = path.read_text().split("impl Packet {", 1)[1] + if args.mutate: + source = source.replace( + "self.complete(Err(error), false);", "self.complete(Err(error), true);" + ) + methods = ("release_guard", "retired", "finish", "fail_packet", "complete") + extracted = [method(source, f"fn {name}(") for name in methods] + args.out.mkdir(parents=True, exist_ok=True) + program = args.out / "packet-completion.rs" + program.write_text(MOCKS + "\n".join(extracted) + TESTS) + binary = args.out.resolve() / "tests" + flags = ["-C", "target-feature=+crt-static"] if args.static else [] + subprocess.run( + ["rustc", "--test", "--edition=2021", *flags, str(program), "-o", str(binary)], + check=True, + ) + return subprocess.run([str(binary)], check=False).returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 326dccb7b85730..ed857d86fa9a1b 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -85,6 +85,7 @@ def mutations(flag, names, base, expect=KILL): 'pmp-native26-tests.py': [([], PASS)], + 'm3-packet-completion-tests.py': [(out(), PASS), (out() + ['--mutate'], KILL)], 'm3-stamp-admission-tests.py': [(out(), PASS), (out() + ['--mutation', 'live-reseed'], KILL)], 'hardware-defaults-tests.py': [([], PASS)], From f0140e6ab816ab71e4c70943e714692905fef68d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:05:37 -0500 Subject: [PATCH 0677/1514] arm64: idle: stop the Apple CPU PMU counters across WFI On M4 and later Apple cores, some cycle counters keep counting during WFI (for example, M5 Max Sawtooth cores count at ~1.5 GHz while idle), which inflates CPU-wide perf cycle counts with idle time unlike other arm64 PMUs. The PMU registers themselves survive WFI unchanged, so saving and restoring the full counter state is not needed. While perf events are active on a CPU, have the Apple CPU PMU driver set a per-CPU flag so the Apple WFI idle path clears the counter enable and IMODE bits in PMCR0_EL1 before WFI and restores PMCR0_EL1 on exit. When no perf events are active, the idle path does no extra register writes. Signed-off-by: Satya Benson --- arch/arm64/include/asm/apple-idle.h | 5 +++++ arch/arm64/kernel/idle.c | 33 ++++++++++++++++++++++++++++- drivers/perf/apple_m1_cpu_pmu.c | 14 ++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/arch/arm64/include/asm/apple-idle.h b/arch/arm64/include/asm/apple-idle.h index 619882f65d636e..62667f44becb7e 100644 --- a/arch/arm64/include/asm/apple-idle.h +++ b/arch/arm64/include/asm/apple-idle.h @@ -6,8 +6,13 @@ void apple_cpu_wfi(void); #ifdef CONFIG_ARCH_APPLE +#include + /* Called from smp_prepare_boot_cpu(): before the boot CPU's first idle. */ void apple_wfi_quirk_init(void); + +/* Set by the Apple CPU PMU driver while events are counting on this CPU. */ +DECLARE_PER_CPU(bool, apple_pmu_wfi_freeze); #else static inline void apple_wfi_quirk_init(void) { } #endif diff --git a/arch/arm64/kernel/idle.c b/arch/arm64/kernel/idle.c index 0d76030f78205b..70eba26d925835 100644 --- a/arch/arm64/kernel/idle.c +++ b/arch/arm64/kernel/idle.c @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -90,11 +91,41 @@ static __always_inline bool apple_wfi_needs_save(void) { return unlikely(READ_ONCE(apple_wfi_loses_regs)); } + +DEFINE_PER_CPU(bool, apple_pmu_wfi_freeze); +EXPORT_PER_CPU_SYMBOL_GPL(apple_pmu_wfi_freeze); + +/* + * On M4 and later Apple cores some cycle counters keep counting in WFI + * (for example, M5 Max Sawtooth cores at about 1.5 GHz), which inflates + * CPU-wide perf counts with idle time. Freeze the counters and their + * interrupt across WFI whenever perf events are active on this CPU. + */ +static __always_inline void apple_wfi(void) +{ + /* Idle runs with preemption disabled: the raw accessor is enough. */ + if (unlikely(__this_cpu_read(apple_pmu_wfi_freeze))) { + u64 pmcr0 = read_sysreg_s(SYS_IMP_APL_PMCR0_EL1); + + write_sysreg_s(pmcr0 & ~(PMCR0_CNT_ENABLE_0_7 | + PMCR0_CNT_ENABLE_8_9 | + PMCR0_IMODE), + SYS_IMP_APL_PMCR0_EL1); + isb(); + apple_cpu_wfi(); + write_sysreg_s(pmcr0, SYS_IMP_APL_PMCR0_EL1); + isb(); + } else { + apple_cpu_wfi(); + } +} #else static __always_inline bool apple_wfi_needs_save(void) { return false; } + +static __always_inline void apple_wfi(void) { } #endif /* @@ -120,7 +151,7 @@ void __cpuidle cpu_do_idle(void) * them, even when the same task resumes on this CPU. */ fpsimd_save_and_flush_cpu_state(); - apple_cpu_wfi(); + apple_wfi(); } else { dsb(sy); wfi(); diff --git a/drivers/perf/apple_m1_cpu_pmu.c b/drivers/perf/apple_m1_cpu_pmu.c index 9bc510e5426863..218dbe10bac97d 100644 --- a/drivers/perf/apple_m1_cpu_pmu.c +++ b/drivers/perf/apple_m1_cpu_pmu.c @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -770,14 +771,26 @@ static void __m1_pmu_set_mode(u8 mode) isb(); } +#ifdef CONFIG_ARCH_APPLE +static void apple_pmu_wfi_freeze_set(bool active) +{ + this_cpu_write(apple_pmu_wfi_freeze, active); +} +#else +static void apple_pmu_wfi_freeze_set(bool active) { } +#endif + static void m1_pmu_start(struct arm_pmu *cpu_pmu) { + /* arm_pmu only starts the PMU with at least one event on it. */ + apple_pmu_wfi_freeze_set(true); __m1_pmu_set_mode(PMCR0_IMODE_FIQ); } static void m1_pmu_stop(struct arm_pmu *cpu_pmu) { __m1_pmu_set_mode(PMCR0_IMODE_OFF); + apple_pmu_wfi_freeze_set(false); } static int m1_pmu_map_event(struct perf_event *event) @@ -856,6 +869,7 @@ static void m1_pmu_reset(void *info) int i; __m1_pmu_set_mode(PMCR0_IMODE_OFF); + apple_pmu_wfi_freeze_set(false); for (i = 0; i < M1_PMU_NR_COUNTERS; i++) { m1_pmu_disable_counter(i); From 50764ffbf03ee48367742fd38e14c72076e85cbc Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:05:39 -0500 Subject: [PATCH 0678/1514] wifi: apple: centauri: t6050: hand received frames to GRO Every received data frame went to the stack individually through netif_rx(), so TCP saw each segment separately and acknowledged every second one, generating heavy ACK traffic that contends with incoming data on the shared Wi-Fi channel. Queue each drained batch of frames onto a per-interface skb queue and deliver them via napi_gro_receive() from a NAPI poll context so GRO coalesces consecutive TCP segments before they reach the stack. The NAPI context is enabled while the interface is up and purged on stop/unregister. Signed-off-by: Satya Benson --- .../apple/centauri/t6050/centauri_wifi.c | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 61a421a58ec206..17f67587355c2f 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -111,6 +111,9 @@ struct centauri_t6050_wifi { u8 avoid_ssid[IEEE80211_MAX_SSID_LEN]; size_t avoid_ssid_len; unsigned long avoid_until; + /* Received frames wait here for rx_napi, whose poll hands them to GRO. */ + struct napi_struct rx_napi; + struct sk_buff_head rx_gro_queue; }; static int query_link_status(struct centauri_t6050_wifi *wifi); @@ -353,10 +356,30 @@ static bool data_rx_frame(const u8 *packet, unsigned int capacity, return *offset <= capacity && *frame_length <= capacity - *offset; } +static int rx_poll(struct napi_struct *napi, int budget) +{ + struct centauri_t6050_wifi *wifi = + container_of(napi, struct centauri_t6050_wifi, rx_napi); + struct sk_buff *skb; + int done = 0; + + while (done < budget && (skb = skb_dequeue(&wifi->rx_gro_queue))) { + napi_gro_receive(napi, skb); + done++; + } + if (done < budget && napi_complete_done(napi, done) && + !skb_queue_empty(&wifi->rx_gro_queue)) + napi_schedule(napi); + return done; +} + static void drain_data_rx(struct centauri_t6050_wifi *wifi) { u16 head, tail, post; unsigned int processed = 0; + struct sk_buff_head frames; + + __skb_queue_head_init(&frames); if (!(wifi->data_rings_open & BIT(4)) || readl(wifi->a.bar + 8) != 2) return; @@ -408,7 +431,7 @@ static void drain_data_rx(struct centauri_t6050_wifi *wifi) skb->ip_summed = CHECKSUM_NONE; wifi->netdev->stats.rx_packets++; wifi->netdev->stats.rx_bytes += frame_length; - netif_rx(skb); + __skb_queue_tail(&frames, skb); } else { wifi->netdev->stats.rx_dropped++; } @@ -431,6 +454,19 @@ static void drain_data_rx(struct centauri_t6050_wifi *wifi) dma_wmb(); writel(1, wifi->a.bar + 0x1050); } + /* + * Hand the batch to the NAPI context, so that GRO coalesces a flow's + * segments (and TCP acknowledges each coalesced run once, not every + * other segment) before they reach the stack. + */ + if (!skb_queue_empty(&frames)) { + spin_lock_bh(&wifi->rx_gro_queue.lock); + skb_queue_splice_tail_init(&frames, &wifi->rx_gro_queue); + spin_unlock_bh(&wifi->rx_gro_queue.lock); + local_bh_disable(); + napi_schedule(&wifi->rx_napi); + local_bh_enable(); + } } static bool data_tx_completion_span(u16 cookie, u16 wire_count, u8 flags, @@ -2392,9 +2428,13 @@ static int net_open(struct net_device *netdev) netif_carrier_off(netdev); netif_stop_queue(netdev); + skb_queue_purge(&wifi->rx_gro_queue); + napi_enable(&wifi->rx_napi); mutex_lock(&wifi->lock); ret = wifi->configured ? data_start(wifi) : -ENETDOWN; mutex_unlock(&wifi->lock); + if (ret) + napi_disable(&wifi->rx_napi); return ret; } @@ -2406,6 +2446,8 @@ static int net_stop(struct net_device *netdev) cancel_scan(wifi); netif_stop_queue(netdev); skb_queue_purge(&wifi->data_tx_queue); + napi_disable(&wifi->rx_napi); + skb_queue_purge(&wifi->rx_gro_queue); return 0; } @@ -2647,6 +2689,7 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) wifi->control = c; mutex_init(&wifi->lock); skb_queue_head_init(&wifi->data_tx_queue); + skb_queue_head_init(&wifi->rx_gro_queue); INIT_WORK(&wifi->scan_work, scan_worker); INIT_WORK(&wifi->connect_work, connect_worker); INIT_WORK(&wifi->link_work, link_worker); @@ -2662,6 +2705,7 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) } *(struct centauri_t6050_wifi **)wiphy_priv(wifi->wiphy) = wifi; *(struct centauri_t6050_wifi **)netdev_priv(wifi->netdev) = wifi; + netif_napi_add(wifi->netdev, &wifi->rx_napi, rx_poll); set_wiphy_dev(wifi->wiphy, &c->pdev->dev); wifi->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION); wifi->wiphy->max_scan_ssids = 1; @@ -2776,6 +2820,7 @@ void centauri_t6050_wifi_unregister(struct centauri_t6050 *c) skb_queue_purge(&wifi->data_tx_queue); if (wifi->netdev && wifi->netdev->reg_state == NETREG_REGISTERED) unregister_netdev(wifi->netdev); + skb_queue_purge(&wifi->rx_gro_queue); if (wifi->registered) wiphy_unregister(wifi->wiphy); if (wifi->wiphy) From 399c3ddfd60d0317bfb3fc118dfb061a996a5db3 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:06:13 -0500 Subject: [PATCH 0679/1514] wifi: apple: centauri: t6050: cap the frames queued to the firmware The transmit path consists of two shared FIFO queues: up to 2048 frames queued in the driver and up to 2047 posted to the firmware's ring (~6 MB combined). Because frames are freed once copied into the ring and the driver does not use BQL, neither BQL nor TCP Small Queues limits this queue depth, allowing a bulk upload to inflate latency for interactive flows. Cap the driver queue to 128 frames and in-flight firmware frames to 512 so excess packets wait in the qdisc where they are scheduled per flow. If no TX completion arrives for half a second, bypass the cap with a one-time warning so a lost firmware completion cannot wedge TX. Expose the existing data ring counters and cap statistics via read-only debugfs data_stats. Signed-off-by: Satya Benson --- .../apple/centauri/t6050/centauri_wifi.c | 58 ++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 17f67587355c2f..1002946d7cf878 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -26,7 +27,15 @@ #define DATA_TX_BUFFER (SZ_16M + SZ_8M) #define DATA_RX_SLOTS 2048 #define DATA_TX_SLOTS 2048 -#define DATA_TX_QUEUE_LIMIT DATA_TX_SLOTS +/* + * Frames waiting for a ring slot, and frames the firmware holds until it + * reports them sent. Both queues are first-in first-out and shared by every + * flow, so what does not fit waits in the qdisc instead, where it is + * scheduled per flow. 512 frames are about 25 ms at ~240 Mbit/s; the ring + * itself holds 2047 (about 100 ms). + */ +#define DATA_TX_QUEUE_LIMIT 128 +#define DATA_TX_INFLIGHT_MAX 512 static_assert(DATA_TX_BUFFER >= CEN_ALPHA_SCRATCH_OFFSET + CEN_ALPHA_SCRATCH_SIZE); @@ -90,6 +99,8 @@ struct centauri_t6050_wifi { bool data_tx_busy[DATA_TX_SLOTS]; u32 data_tx_submitted, data_tx_completed, data_tx_failed; u32 data_tx_coalesced, data_tx_bad; + u32 data_tx_capped, data_tx_cap_bypassed; + unsigned long data_tx_completed_at; s8 station_signal; bool station_signal_valid; unsigned long station_signal_at, connected_at; @@ -522,6 +533,7 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) } if (count > 1) wifi->data_tx_coalesced++; + wifi->data_tx_completed_at = jiffies; for (i = 0; i < count; i++) { unsigned int slot = (first + i) % DATA_TX_SLOTS; @@ -551,9 +563,28 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) u8 *descriptor = wifi->a.window + 0x540000 + post * 32; struct sk_buff *skb; u64 metadata = 6ULL << 27; + u32 inflight = wifi->data_tx_submitted - wifi->data_tx_completed; if (wifi->data_tx_busy[post] || next == index_read(wifi, 1, 25)) break; + /* + * Keep at most DATA_TX_INFLIGHT_MAX frames with the firmware. A + * completion that never comes would hold its frame's place for + * good, so the cap gives way once no completion has arrived for + * half a second (beacon reports keep this path running). + */ + if (inflight >= DATA_TX_INFLIGHT_MAX && + !skb_queue_empty(&wifi->data_tx_queue)) { + if (time_before(jiffies, + wifi->data_tx_completed_at + HZ / 2)) { + wifi->data_tx_capped++; + break; + } + if (!wifi->data_tx_cap_bypassed++) + dev_warn(&wifi->control->pdev->dev, + "Wi-Fi TX: no completion for %u in-flight frames; posting past the cap\n", + inflight); + } skb = skb_dequeue(&wifi->data_tx_queue); if (!skb) break; @@ -571,6 +602,8 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) metadata |= 4ULL << 15; put_unaligned_le64(metadata, descriptor + 16); put_unaligned_le64(2000000, descriptor + 24); + if (wifi->data_tx_submitted == wifi->data_tx_completed) + wifi->data_tx_completed_at = jiffies; wifi->data_tx_length[post] = skb->len; wifi->data_tx_busy[post] = true; wifi->data_tx_submitted++; @@ -2677,6 +2710,27 @@ static int query_link_status(struct centauri_t6050_wifi *wifi) return ret; } +static int data_stats_show(struct seq_file *m, void *unused) +{ + struct centauri_t6050_wifi *wifi = m->private; + + mutex_lock(&wifi->lock); + seq_printf(m, + "rx received %u reposted %u bad %u\n" + "tx submitted %u completed %u in_flight %u failed %u bad %u coalesced %u\n" + "tx queued %u capped %u cap_bypassed %u\n", + wifi->data_rx_received, wifi->data_rx_reposted, + wifi->data_rx_bad, wifi->data_tx_submitted, + wifi->data_tx_completed, + wifi->data_tx_submitted - wifi->data_tx_completed, + wifi->data_tx_failed, wifi->data_tx_bad, + wifi->data_tx_coalesced, skb_queue_len(&wifi->data_tx_queue), + wifi->data_tx_capped, wifi->data_tx_cap_bypassed); + mutex_unlock(&wifi->lock); + return 0; +} +DEFINE_SHOW_ATTRIBUTE(data_stats); + int centauri_t6050_wifi_register(struct centauri_t6050 *c) { struct centauri_t6050_wifi *wifi; @@ -2771,6 +2825,8 @@ int centauri_t6050_wifi_register(struct centauri_t6050 *c) &wifi->hw_channels_blob); debugfs_create_blob("system_caps", 0400, wifi->wiphy->debugfsdir, &wifi->system_caps_blob); + debugfs_create_file("data_stats", 0400, wifi->wiphy->debugfsdir, wifi, + &data_stats_fops); rtnl_lock(); channels_apply(wifi); rtnl_unlock(); From c8741fa2a4d7afff401b0302ac011d41a384bf76 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:06:53 -0500 Subject: [PATCH 0680/1514] wifi: apple: centauri: t6050: give TCP mac80211's pacing shift TCP scales its bursts, TCP Small Queues budget, and BBR's extra congestion window allowance to 2^-sk_pacing_shift seconds of its pacing rate (1 ms by default, shift 10). On a shared Wi-Fi channel where aggregation and contention raise loaded RTT well above minimum RTT, a 1 ms allowance starves the transmit path and leaves BBR cwnd-limited. Call sk_pacing_shift_update(skb->sk, 7) on transmitted frames, matching mac80211's 8 ms pacing shift so TCP keeps enough packets in flight for aggregation. Signed-off-by: Satya Benson --- .../net/wireless/apple/centauri/t6050/centauri_wifi.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 1002946d7cf878..067dc33cb8ed55 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -12,6 +12,7 @@ #include #include #include +#include #include "centauri_t6050.h" #define CR_BASE 0x100000 @@ -36,6 +37,13 @@ */ #define DATA_TX_QUEUE_LIMIT 128 #define DATA_TX_INFLIGHT_MAX 512 +/* + * TCP sizes its bursts, its small-queue budget and (BBR) the extra + * congestion window it allows for them at 1 ms of its pacing rate (shift + * 10). Aggregation on a shared Wi-Fi channel wants more: mac80211 sets 8 ms + * (shift 7) on every socket it transmits for, and so does this driver. + */ +#define DATA_TX_PACING_SHIFT 7 static_assert(DATA_TX_BUFFER >= CEN_ALPHA_SCRATCH_OFFSET + CEN_ALPHA_SCRATCH_SIZE); @@ -2503,6 +2511,7 @@ static netdev_tx_t net_transmit(struct sk_buff *skb, struct net_device *netdev) netif_stop_queue(netdev); return NETDEV_TX_BUSY; } + sk_pacing_shift_update(skb->sk, DATA_TX_PACING_SHIFT); skb_queue_tail(&wifi->data_tx_queue, skb); if (skb_queue_len(&wifi->data_tx_queue) >= DATA_TX_QUEUE_LIMIT) netif_stop_queue(netdev); From 0ed79c8be182d1450818fe276cf5d6eff257d5b4 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:06:53 -0500 Subject: [PATCH 0681/1514] wifi: apple: centauri: t6050: free sent frames as consumed, not dropped Every transmitted data frame was freed with dev_kfree_skb_any() after being copied into the firmware's ring, causing drop monitors and the skb:kfree_skb tracepoint to report every uploaded frame as dropped. Use dev_consume_skb_any() once a frame has been posted to the firmware ring, keeping dev_kfree_skb_any() for frames that are genuinely dropped. Signed-off-by: Satya Benson --- drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 067dc33cb8ed55..ffb4793934cc7e 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -615,7 +615,7 @@ static void drain_data_tx(struct centauri_t6050_wifi *wifi) wifi->data_tx_length[post] = skb->len; wifi->data_tx_busy[post] = true; wifi->data_tx_submitted++; - dev_kfree_skb_any(skb); + dev_consume_skb_any(skb); post = next; posted = true; } From 39ae54d0eac1a473248f18c7e9816cdbe06da1de Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0682/1514] drm/apple: send a paired mode set's calls in the engine's firmware 27 build The paired mode set (a mode too wide for one engine, run on two) sends its IOMFB calls through dcp_peer_video_call_stream() (and the opt-in peer setup diagnostic through peer_setup_test_store()), naming them by their 27.0 IDs. Firmware 27.2 renumbered the IOMobileFramebufferAP methods, and an ID the firmware does not know panics it: on a 27.2 stub the paired prepare's set_display_device went out as A411 and crashed both engines. Record every paired-mode and sleep method ID in each firmware 27 build's table (the shifted IDs on 27.2, plus the unchanged paired/DSC hand-off and sleep calls) while keeping them optional for single-engine boot admission in iomfb_v27_missing_method(). Translate each call's ID through iomfb_v27_tag(): on 27.0 (including the J714s copy) every ID is sent unchanged; on a renumbered build every ID must come from the build's table, returning -EOPNOTSUPP instead of sending an unmapped ID. Update the t6041-v27-admission host test fixture for the table helpers it extracts. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp-peer-probe-v27.inc | 9 +- .../drm/apple/dcp-peer-video-probe-v27.inc | 5 +- drivers/gpu/drm/apple/iomfb.h | 25 ++++ drivers/gpu/drm/apple/iomfb_v27.c | 111 +++++++++++++++++- .../selftests/drivers/gpu/apple-dcp/boot.py | 2 + 5 files changed, 146 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc index 33def11c752ea1..a1c017c98e0853 100644 --- a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc @@ -24,9 +24,7 @@ static ssize_t peer_setup_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - static const struct dcp_method_entry method = { - .name = "setup_peer_dcp", .tag = {'A', '3', '6', '6'}, - }; + struct dcp_method_entry method = { .name = "setup_peer_dcp" }; struct apple_dcp *dcp = dev_get_drvdata(dev); struct dcp_peer_probe_wait *wait; __le32 enabled = cpu_to_le32(1); @@ -55,6 +53,11 @@ static ssize_t peer_setup_test_store(struct device *dev, kref_put(&wait->refs, dcp_peer_probe_free); return -EBUSY; } + ret = iomfb_v27_tag(dcp->v27_methods, "A366", method.tag); + if (ret) { + kref_put(&wait->refs, dcp_peer_probe_free); + return ret; + } kref_get(&wait->refs); /* Peer-DCP setup (one bool argument): four input * bytes (boolean followed by zero padding), no output. diff --git a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc index 3560cfc447a99f..86b0f20b5823d4 100644 --- a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc @@ -37,6 +37,10 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, if (out_size > sizeof(wait->reply)) return -EINVAL; + /* The calls name 27.0 IDs: this engine's build may number them differently. */ + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; /* An unrelated AP thread gets its own firmware stream. A369/A367/etc. * must not be mistaken for nested callbacks of the pending A413. * Stream1 (the driver's OOB context) is independent of stream0. @@ -46,7 +50,6 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; - memcpy(method.tag, tag, sizeof(method.tag)); wait->size = out_size; init_completion(&wait->done); kref_init(&wait->refs); diff --git a/drivers/gpu/drm/apple/iomfb.h b/drivers/gpu/drm/apple/iomfb.h index e230a9eac9c5c1..0b2c04b7c61232 100644 --- a/drivers/gpu/drm/apple/iomfb.h +++ b/drivers/gpu/drm/apple/iomfb.h @@ -198,6 +198,28 @@ enum dcpep_method { dcpep_pipe_set_476, dcpep_unnamed_500, iomfbep_set_brightness_correction, + /* + * Firmware 27.x sleep and paired-mode calls named by their 27.0 ID. + * Optional for single-engine boot (iomfb_v27_missing_method() skips + * them); iomfb_v27_tag() refuses any call missing from a renumbered + * table. + */ + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, + dcpep_v27_peer_a360, + dcpep_v27_peer_a361, + dcpep_v27_peer_a362, + dcpep_v27_peer_a364, + dcpep_v27_peer_a365, + dcpep_v27_peer_a366, + dcpep_v27_peer_a367, + dcpep_v27_peer_a368, + dcpep_v27_peer_a369, + dcpep_v27_peer_a370, + dcpep_v27_peer_a371, + dcpep_v27_peer_a372, + dcpep_v27_peer_a373, + dcpep_v27_peer_a449, dcpep_num_methods }; @@ -220,6 +242,9 @@ struct dcp_method_entry { /* The IOMFB method table of a firmware 27.x build, by its compat string; NULL if unknown. */ const struct dcp_method_entry *iomfb_v27_methods(const char *compat); +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods); +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out); +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods); const struct dcp_method_entry *iomfb_v27_methods_j714s(struct device *dev, const struct dcp_method_entry *methods); /* The first method of a firmware 27.x table that has no ID, NULL if none. */ diff --git a/drivers/gpu/drm/apple/iomfb_v27.c b/drivers/gpu/drm/apple/iomfb_v27.c index a7d7d6b93f341d..041ce575f8823b 100644 --- a/drivers/gpu/drm/apple/iomfb_v27.c +++ b/drivers/gpu/drm/apple/iomfb_v27.c @@ -164,6 +164,22 @@ static const struct dcp_method_entry dcp_methods_27_0[dcpep_num_methods] = { * the IOMFB calls around it; 27.2 moved both to A550/A551. */ IOMFB_METHOD("A500", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A442", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A449", dcpep_v27_peer_a449), }; /* @@ -222,6 +238,22 @@ static const struct dcp_method_entry dcp_methods_27_2[dcpep_num_methods] = { * dispatch where 26A428's compares 'A500' (0x1df68c vs 0x1de0dc, same code). */ IOMFB_METHOD("A550", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A492", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A499", dcpep_v27_peer_a449), }; /* @@ -269,6 +301,76 @@ const struct dcp_method_entry *iomfb_v27_methods(const char *compat) return NULL; } +/* + * Translate @tag, a 27.0 ID named directly by sleep or paired-mode callers, + * into the build of @methods (4 bytes in @out). On 27.0 (including the J714s + * copy) the tag is sent unchanged. On a renumbered build every ID must come + * from @methods; a missing entry returns -EOPNOTSUPP instead of sending an + * unknown tag that would panic the firmware. + */ +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out) +{ + unsigned int i; + char in[4]; + + if (!methods) + return -EOPNOTSUPP; + memcpy(in, tag, 4); + if (!iomfb_v27_methods_renumbered(methods)) { + memcpy(out, in, 4); + return 0; + } + for (i = 0; i < dcpep_num_methods; i++) { + if (dcp_methods_27_0[i].tag[0] && !memcmp(dcp_methods_27_0[i].tag, in, 4)) { + if (!methods[i].tag[0]) + return -EOPNOTSUPP; + memcpy(out, methods[i].tag, 4); + return 0; + } + } + return -EOPNOTSUPP; +} + +/* Whether @methods is a build's table whose AP method IDs differ from 27.0's. */ +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods || methods == dcp_methods_27_0) + return false; + for (i = 0; i < dcpep_num_methods; i++) { + if (memcmp(methods[i].tag, dcp_methods_27_0[i].tag, 4) && + !(i == dcpep_swap_submit && !memcmp(methods[i].tag, "A407", 4))) + return true; + } + return false; +} + +static const enum dcpep_method iomfb_v27_sleep_methods[] = { + dcpep_is_main_display, + dcpep_pipe_cfg_414, + dcpep_set_power_state, + dcpep_pipe_set_476, + dcpep_pipe_query_478, + dcpep_unnamed_500, + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, +}; + +/* Whether @methods names an ID for every call the firmware 27 display sleep sends. */ +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods) + return false; + for (i = 0; i < ARRAY_SIZE(iomfb_v27_sleep_methods); i++) { + if (!methods[iomfb_v27_sleep_methods[i]].tag[0]) + return false; + } + return true; +} + /* * The 27.0 table for the J714s, the board the firmware 27 sleep has run on (dcp->v27_j714s): a * copy with the sleep's A500 added. The shared table keeps the methods it had, so every other @@ -309,9 +411,14 @@ const char *iomfb_v27_missing_method(const struct dcp_method_entry *methods, *count = 0; for (i = 0; i < dcpep_num_methods; i++) { - /* Only a firmware sleep sends unnamed_500, and it checks the build's table. */ + /* + * Only sleep and paired-mode paths send unnamed_500 and the + * v27-optional entries; each checks the build's table before + * sending. + */ if (!dcp_methods_27_0[i].tag[0] || methods[i].tag[0] || - i == dcpep_dfb_ready_query || i == dcpep_unnamed_500) + i == dcpep_dfb_ready_query || i == dcpep_unnamed_500 || + i >= dcpep_v27_sleep_a115) continue; if (!first) first = dcp_methods_27_0[i].name; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 7a23fdb3ff45f4..0f07b51a66b964 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -216,10 +216,12 @@ def _v27_prelude(root, helpers): method_table = block(dcp_c, 'static enum dcp_firmware_version dcp_v27_method_table(') return r''' #include +#include #include #include #include #include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef uint32_t u32; enum dcp_firmware_version { DCP_FIRMWARE_UNKNOWN, From 795bd7727eb1b4d9b238d035d03bd5cc789f12f1 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0683/1514] drm/apple: send the firmware 27 calls named by ID in the engine's build Besides the paired video calls, the firmware 27 paths name several calls by their 27.0 IDs: the primary's paired mode set (A413) and power step (A484), the paired background swap (A408), the sleep's power and A500 steps, the display stage calls and the out-of-band wake call (A442). On 27.2, which renumbered IOMobileFramebufferAP, several of those IDs are other methods: the paired mode's power step ran one and failed, and the second engine of a 4K240 mode never started. Translate each of them through iomfb_v27_tag() and refuse the call instead of sending it when the build's table lacks an entry. Zero the internal wake A442 payload's filler bytes on renumbered builds, where 27.2 rejects the 0xaa filler as an index count and block size. The J714s's A407 swap keeps its ID, which only its 27.0 table names, and its diagnostic now refuses a pair whose engines take different swap forms. 27.0 sends what it sent. Signed-off-by: Erik Bourget --- .../drm/apple/dcp-peer-modeset-probe-v27.inc | 18 ++++++++--- .../gpu/drm/apple/dcp-peer-swap-probe-v27.inc | 14 +++++++-- drivers/gpu/drm/apple/iomfb.c | 30 +++++++++++++------ 3 files changed, 47 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc index a5aa449b446dd0..0ac6d6c3447618 100644 --- a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc @@ -7,11 +7,16 @@ static int dcp_peer_probe_power(struct apple_dcp *dcp, struct apple_dcp *peer, bool on) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_power_test", - .tag = {'A', '4', '8', '4'} }; + struct dcp_method_entry method = { .name = "peer_power_test" }; u8 power[16] = {}, response[8]; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A484", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A484", peer_tag); + if (ret) + return ret; + wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; @@ -134,13 +139,18 @@ static int dcp_peer_probe_modeset(struct apple_dcp *dcp, struct apple_dcp *peer, bool firmware_requires_merge) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_modeset_test", - .tag = {'A', '4', '1', '3'} }; + struct dcp_method_entry method = { .name = "peer_modeset_test" }; __le32 mode[2] = {video->color_id, video->timing_id}; u32 primary_id, peer_id, phase, status; unsigned long deadline; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A413", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A413", peer_tag); + if (ret) + return ret; + { guard(mutex)(&dcp_peer_lock); if (dcp->peer_reserved != peer || peer->peer_owner != dcp || diff --git a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc index ed73f355eda7ec..343fa1872badae 100644 --- a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc @@ -6,6 +6,7 @@ struct dcp_peer_background { struct iomfb_transaction transaction; struct dcp_peer_video_wait *wait; struct dcp_swap_submit_req_v27 wire; + char tag[4]; bool sent; }; @@ -26,10 +27,11 @@ static void dcp_peer_background_start(struct apple_dcp *dcp, { struct dcp_peer_background *background = container_of(transaction, struct dcp_peer_background, transaction); - struct dcp_method_entry method = { .name = "peer_background_test", - .tag = {'A', '4', '0', '8'} }; + struct dcp_method_entry method = { .name = "peer_background_test" }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; + memcpy(method.tag, background->tag, sizeof(method.tag)); + background->sent = true; if (!dcp_present_begin_h17p(&dcp->present_state_h17p, background->wire.swap.swap_id)) { @@ -55,13 +57,18 @@ static int dcp_peer_queue_background(struct apple_dcp *dcp, struct dcp_peer_video_wait *wait) { struct dcp_peer_background *background; + char tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A408", tag); + if (ret) + return ret; background = kzalloc_obj(*background); if (!background) return -ENOMEM; background->wire = *wire; background->wait = wait; + memcpy(background->tag, tag, sizeof(background->tag)); kref_get(&wait->refs); background->transaction.start = dcp_peer_background_start; background->transaction.release = dcp_peer_background_release; @@ -185,6 +192,7 @@ static void dcp_peer_a407_background_start(struct apple_dcp *dcp, { struct dcp_peer_a407_background *background = container_of(transaction, struct dcp_peer_a407_background, transaction); + /* The J714s's 27.0 swap form, whose table names A407 (iomfb_v27_methods_j714s()). */ struct dcp_method_entry method = { .name = "peer_background_test", .tag = {'A', '4', '0', '7'} }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; @@ -345,6 +353,8 @@ static ssize_t peer_swap_test_store(struct device *dev, dcp->crtc->base.state->active || peer->crtc->base.state->active || dcp->fw_compat != DCP_FIRMWARE_V_27_0 || peer->fw_compat != DCP_FIRMWARE_V_27_0 || + /* Both engines must take the swap form the owner sends. */ + dcp->v27_a407 != peer->v27_a407 || !device_trylock(peer->dev)) { ret = -EBUSY; goto out; diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1de9af271a4020..0e877825b8dbab 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -899,11 +899,14 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, rpc->data, iomfb_v27_sleep_done, rpc); dcp->push_out_prefill = NULL; if ((rpc->a442 || rpc->a442_key) && !rpc->oob) { - static const struct dcp_method_entry a442 = { - .name = "v27_a442", .tag = { 'A', '4', '4', '2' }, - }; + struct dcp_method_entry a442 = { .name = "v27_a442" }; u8 in[92]; + if (iomfb_v27_tag(dcp->v27_methods, "A442", a442.tag)) { + dev_warn_once(dcp->dev, "skipping v27 wake A442: unmapped method tag\n"); + return; + } + memset(in, 0xaa, sizeof(in)); memset(in, 0, 16); in[8] = rpc->a442_key ?: 0x41; @@ -911,6 +914,9 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, if (rpc->a442_key) { memset(in + 80, 0, 12); in[84] = 0x20; + } else if (iomfb_v27_methods_renumbered(dcp->v27_methods)) { + /* 27.2 reads the filler as an index count and a block size. */ + memset(in + 16, 0, sizeof(in) - 16); } dcp_push(dcp, true, &a442, sizeof(in), 4100, in, iomfb_v27_a442_done, NULL); } @@ -988,6 +994,9 @@ int iomfb_v27_sleep_plain(struct apple_dcp *dcp, bool on) static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) { + struct dcp_method_entry method = { + .name = a500 ? "v27_sleep_500" : "v27_sleep_power", + }; struct iomfb_v27_sleep_rpc *rpc; u8 args[IOMFB_V27_SLEEP_ARGS]; int ret; @@ -998,6 +1007,9 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) (a500 || flags ? iomfb_v27_sleep_args(dcp, a500, args) : iomfb_v27_display_args(dcp, false, args))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, a500 ? "A500" : "A484", method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1006,10 +1018,7 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) rpc->status = ~0U; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { - .name = a500 ? "v27_sleep_500" : "v27_sleep_power", - }; - memcpy(rpc->method.tag, a500 ? "A500" : "A484", 4); + rpc->method = method; /* * Off, before each DCP's and DCPEXT's sleep idle: A484 with the sleep's flags, then * A500's sleep form. On, after the wake: A500's wake form, then A484 with the flags. @@ -1081,6 +1090,7 @@ int iomfb_v27_sleep_a115(struct apple_dcp *dcp, bool awake) static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in, u32 in_len, u32 out_len, bool inout, u8 a442_key) { + struct dcp_method_entry method = { .name = "v27_display_stage" }; struct iomfb_v27_sleep_rpc *rpc; int ret; @@ -1088,6 +1098,9 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in dcp->fw_compat != DCP_FIRMWARE_V_27_0 || in_len > sizeof(rpc->data) || (inout && out_len > sizeof(rpc->data))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1097,8 +1110,7 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in rpc->any_reply = true; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { .name = "v27_display_stage" }; - memcpy(rpc->method.tag, tag, 4); + rpc->method = method; rpc->input = in_len; rpc->output = out_len; rpc->inout = inout; From c984f50240ccefe00f5675e1e7dddc4e529953ae Mon Sep 17 00:00:00 2001 From: Isaac Duarte <31712685+Isaac-Duarte@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:04:06 -0700 Subject: [PATCH 0684/1514] thunderbolt: keep USB4 device routers out of the bi-directional HiFi quirk QUIRK_TMU_HIFI_BI puts every device router in bi-directional HiFi. On T6050 the host router's TMU is run by its firmware (QUIRK_HOST_TMU), and that firmware applies a mode only when the time sync of its lane adapter goes off and on again, which only the enhanced uni-directional path does. In bi-directional HiFi it never configures its TMU (no "TMU CONFIGURED" from the ACIO firmware), and a USB4 dock's DP OUT adapters have no time base: the DP links train and the displays read as connected, but the monitors get no picture and the next modeset times out. The quirk was made for a Studio Display, whose router is not USB4. Leave USB4 routers on the previous path, CL states included. Fixes: 253232bc7660 ("thunderbolt: apple: default device routers to bidirectional HiFi") Signed-off-by: Isaac Duarte <31712685+Isaac-Duarte@users.noreply.github.com> --- drivers/thunderbolt/tb.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/drivers/thunderbolt/tb.c b/drivers/thunderbolt/tb.c index b013696f0ff48a..41d9bdc44e8dfa 100644 --- a/drivers/thunderbolt/tb.c +++ b/drivers/thunderbolt/tb.c @@ -231,10 +231,6 @@ static int tb_enable_clx(struct tb_switch *sw) const struct tb_tunnel *tunnel; int ret; - /* Bi-directional HiFi does not support CL states. */ - if (sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) - return 0; - /* * Currently only enable CLx for the first link. This is enough * to allow the CPU to save energy at least on Intel hardware @@ -251,6 +247,10 @@ static int tb_enable_clx(struct tb_switch *sw) if (tb_switch_depth(sw) != 1) return 0; + /* Bi-directional HiFi (non-USB4 routers, see tb_enable_tmu()) does not support CL states. */ + if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && !tb_switch_is_usb4(sw)) + return 0; + /* * If we are re-enabling then check if there is an active DMA * tunnel and in that case bail out. @@ -367,7 +367,12 @@ static int tb_enable_tmu(struct tb_switch *sw) { int ret; - if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && tb_route(sw)) { + /* + * Not for USB4 routers: a host router whose firmware runs its TMU applies a mode only + * on the enhanced uni-directional path below, and a dock's DP OUT has no clock without it. + */ + if ((sw->tb->nhi->quirks & QUIRK_TMU_HIFI_BI) && tb_route(sw) && + !tb_switch_is_usb4(sw)) { ret = tb_switch_clx_disable(sw); if (ret < 0) return ret; From d88f46ba178cbf9e21610e64e4151cfd1498dc13 Mon Sep 17 00:00:00 2001 From: Isaac Duarte <31712685+Isaac-Duarte@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:10:56 -0700 Subject: [PATCH 0685/1514] thunderbolt: pulse time sync when enabling bi-directional HiFi on a host-managed TMU Where the host router's TMU is run by its firmware (QUIRK_HOST_TMU), the firmware applies a mode only when the time sync of its lane adapter goes off and on again. tb_switch_tmu_enable_enhanced() turns time sync off first for that reason. tb_switch_tmu_enable_bidirectional() only turns it on, and a router whose TMU reads as off has time sync on already, so the host router never sees the edge and never configures its TMU. That is the path a USB4 v1 router takes on T6050: it has no enhanced mode, CL1 is off (QUIRK_NO_HOST_CLX), so tb_enable_tmu() falls back to bi-directional HiFi. Turn time sync off first there too, as the enhanced path does. Signed-off-by: Isaac Duarte <31712685+Isaac-Duarte@users.noreply.github.com> --- drivers/thunderbolt/tmu.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/thunderbolt/tmu.c b/drivers/thunderbolt/tmu.c index ce494a044e4f03..151a60826c444d 100644 --- a/drivers/thunderbolt/tmu.c +++ b/drivers/thunderbolt/tmu.c @@ -720,6 +720,15 @@ static int tb_switch_tmu_enable_bidirectional(struct tb_switch *sw) up = tb_upstream_port(sw); down = tb_switch_downstream_port(sw); + /* The host's way: time sync off, on again below (see tb_switch_tmu_enable_enhanced()). */ + if (tb_switch_tmu_host_managed(sw)) { + ret = tb_port_tmu_time_sync_disable(up); + if (!ret) + ret = tb_port_tmu_time_sync_disable(down); + if (ret) + goto out; + } + ret = tb_port_tmu_unidirectional_disable(up); if (ret) return ret; From b4ecd93a595e99af22609c42d3c3be398a4ab557 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Mon, 23 Nov 2026 20:06:09 +0100 Subject: [PATCH 0686/1514] soc: apple: clpc: hold P-cluster frequency floor for ANE on T8142 Once the T8142 engine AXI2AF bridge tunables are applied, pure ANE execution time on T8142 also depends on the P-cluster frequency (cpu-map cluster1), independent of which CPU cluster submits the request. Measured on J813 (MacBook Air 13" M5, T8142; J815 and J704 share the compatible) pinned to an E-core with the DCS 7 / SOC 3 floor active, unet-320 firmware report_done drops from 660.5 us with no P-cluster floor to 350.7 us at 4176 MHz (host p50 954.4 us -> 616.5 us, 4.49 W average), with no further reduction at 4464 MHz (363.0 us, 5.31 W). Enable the existing CLPC ANE cluster frequency floor on apple_clpc_hw_t8142 for cluster 1 at 4176000 kHz, matching all T8142 machines via "apple,t8142" as required by the current apple_clpc_probe() check (no single-board gating; can move to apple,ane-cpu-opp once #2856 lands). Extend apple_clpc_ane_cluster_test accordingly. Signed-off-by: Bartosz Nitka --- drivers/soc/apple/clpc.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index f0624d2a2563ce..1d894e723f1fed 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -1991,6 +1991,17 @@ static const struct apple_clpc_hw apple_clpc_hw_t8142 = { * mm-512x2048). */ .ane = { [APPLE_CLPC_DCS] = 7, [APPLE_CLPC_SOC] = 3 }, + /* + * With the engine AXI2AF bridge tunables applied, pure ANE execution + * time on J813 also tracks the P-cluster frequency (cpu-map cluster1), + * independent of which cluster hosts the submitting thread (pinned to + * an E-core with DCS 7 / SOC 3, unet-320 firmware report_done drops + * from 660.5 us with no P-cluster floor to 350.7 us at 4176 MHz, + * 4.49 W, with no further gain at 4464 MHz, 5.31 W). + */ + .ane_cluster = 1, + .ane_cluster_khz = 4176000, + .ane_cluster_machine = "apple,t8142", }; #if IS_BUILTIN(CONFIG_KUNIT) && !defined(MODULE) @@ -2262,6 +2273,8 @@ static void apple_clpc_ane_cluster_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, time_before(now + msecs_to_jiffies(APPLE_CLPC_HOLD_MS), clpc->ane_until)); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t6040.ane_cluster, 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane_cluster, 1u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8142.ane_cluster_khz, 4176000u); KUNIT_EXPECT_EQ(test, apple_clpc_hw_t8140.ane_cluster_khz, 0u); } From a56f2a5df8db71c6ce1b0ff0c16e379675a9aeb7 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0687/1514] drm/apple: admit the T6050 display sleep transport by method table The T6050 display processors take part in a deep sleep through the firmware 27 endpoint transport, which previously gated on the J716c board compatible and a 27.0.0 compatibility string. On a 27.2 stub no processor registered for the sleep, and every deep sleep was refused ("display 0: no provider"). Admit a T6050 DCP or DCPEXT to the firmware 27 sleep transport whenever its build's method table has an ID for every call the sleep sends (iomfb_v27_sleep_methods_complete()). That covers 27.0 and 27.2 across T6050 boards without a board check while refusing 27.3 until its sleep methods are known. Add the v27-tag-translation host selftest covering table translation, fail-closed refusal on missing/unrecorded IDs, and data-driven sleep transport admission. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp.c | 18 +- .../selftests/drivers/gpu/apple-dcp/boot.py | 191 ++++++++++++++++++ .../selftests/drivers/gpu/apple-dcp/run.py | 1 + 3 files changed, 198 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 0666748f436d0d..b23ba12367334d 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5926,31 +5926,25 @@ static bool dcp_ext26_admitted(struct device_node *np) } /* - * J716c shares the 27.0 endpoint-control wire format, not the J714s normal - * IOMFB method or panel profile. Establish this before RTKit can receive any - * application traffic, including traffic that invalidates a later inventory. + * Firmware 27 (T6050) sleep endpoint-control transport. Establish this before + * RTKit can receive any application traffic, including traffic that invalidates + * a later inventory. Admitted for a T6050 DCP/DCPEXT whose firmware 27 method + * table has an ID for every call the sleep sends. */ static bool dcp_v27_sleep_transport_supported(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - char compat[DCP_FW_VERSION_STR_LEN]; if (!IS_ENABLED(CONFIG_APPLE_SOC_SLEEP)) return false; - if (dcp->v27_j714s) - return true; - if (!of_machine_is_compatible("apple,j716c") || - !of_machine_is_compatible("apple,t6050") || - !(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || + if (!(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || of_device_is_compatible(dev->of_node, "apple,t6050-dcpext")) || !dcp->hw.adopt_live_session || dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_DEFAULT || dcp->fw_compat != DCP_FIRMWARE_V_27_0) return false; - /* The enum also covers later 27.x method tables. */ - return dcp_read_fw_version(dev, "apple,firmware-compat", compat) >= 0 && - !strcmp(compat, "27.0.0"); + return iomfb_v27_sleep_methods_complete(dcp->v27_methods); } /* diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 0f07b51a66b964..a4e74b38a57d93 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -557,3 +557,194 @@ def t8122_dcpext_v27_admission(root): return 0; } ''' + + +def v27_tag_translation(root): + iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() + methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): + iomfb_h.index('#define IOMFB_MAX_CB')] + v27_c = (root / 'drivers/gpu/drm/apple/iomfb_v27.c').read_text() + v27_tables = v27_c[v27_c.index('static const struct dcp_method_entry dcp_methods_27_0'): + v27_c.index('/* The template\'s calls resolve through')] + dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + transport = block(dcp_c, 'static bool dcp_v27_sleep_transport_supported(') + return r''' +#include +#include +#include +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define CONFIG_APPLE_SOC_SLEEP 1 +#define IS_ENABLED(option) (option) +#define GFP_KERNEL 0 +enum dcp_firmware_version { + DCP_FIRMWARE_UNKNOWN, + DCP_FIRMWARE_V_27_0, +}; +enum dcp_iomfb_method_profile { + DCP_IOMFB_METHODS_DEFAULT, + DCP_IOMFB_METHODS_H17G, +}; +struct device_node { const char *compatible; }; +struct device { struct device_node *of_node; }; +struct apple_dcp_hw_data { + bool adopt_live_session; + enum dcp_iomfb_method_profile iomfb_method_profile; +}; +struct apple_dcp { + struct device *dev; + struct apple_dcp_hw_data hw; + enum dcp_firmware_version fw_compat; + const struct dcp_method_entry *v27_methods; +}; +static int of_device_is_compatible(const struct device_node *np, const char *s) +{ + return np && np->compatible && !strcmp(np->compatible, s); +} +static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) +{ + void *copy = malloc(len); + (void)dev; (void)gfp; + if (copy) + memcpy(copy, src, len); + return copy; +} +''' + methods_decl + '\n' + v27_tables + '\n' + transport + r''' +static void expect_tag(const struct dcp_method_entry *methods, const char *in, const char *want) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == 0); + assert(memcmp(out, want, 4) == 0); +} + +static void expect_tag_fail(const struct dcp_method_entry *methods, const char *in) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == -EOPNOTSUPP); + assert(memcmp(out, "XXXX", 4) == 0); +} + +int main(void) +{ + struct device_node node = { .compatible = "apple,t6050-dcp" }; + struct device dev = { .of_node = &node }; + const struct dcp_method_entry *m27_0 = iomfb_v27_methods("27.0.0"); + const struct dcp_method_entry *m27_2 = iomfb_v27_methods("27.2.0"); + const struct dcp_method_entry *m27_3 = iomfb_v27_methods("27.3.0"); + const struct dcp_method_entry *j714s = iomfb_v27_methods_j714s(&dev, m27_0); + struct dcp_method_entry partial_27_2[dcpep_num_methods]; + unsigned int missing_count; + + assert(m27_0 && m27_2 && m27_3 && j714s); + assert(!iomfb_v27_methods_renumbered(NULL)); + assert(!iomfb_v27_methods_renumbered(m27_0)); + assert(!iomfb_v27_methods_renumbered(j714s)); + assert(iomfb_v27_methods_renumbered(m27_2)); + assert(iomfb_v27_methods_renumbered(m27_3)); + + /* NULL table fails closed. */ + expect_tag_fail(NULL, "A411"); + assert(!iomfb_v27_sleep_methods_complete(NULL)); + + /* 27.0 and J714s copy keep 27.0 IDs unchanged. */ + expect_tag(m27_0, "A411", "A411"); + expect_tag(m27_0, "A484", "A484"); + expect_tag(m27_0, "A500", "A500"); + expect_tag(m27_0, "A442", "A442"); + expect_tag(m27_0, "A449", "A449"); + expect_tag(m27_0, "A115", "A115"); + expect_tag(m27_0, "A364", "A364"); + expect_tag(j714s, "A411", "A411"); + expect_tag(j714s, "A408", "A408"); + expect_tag(j714s, "A500", "A500"); + assert(iomfb_v27_sleep_methods_complete(m27_0)); + assert(iomfb_v27_sleep_methods_complete(j714s)); + assert(!iomfb_v27_missing_method(m27_0, &missing_count) && missing_count == 0); + + /* 27.2 translates every recorded shifted and unchanged paired/sleep tag. */ + const struct { const char *in, *out; } map_27_2[] = { + { "A406", "A456" }, { "A408", "A458" }, { "A411", "A461" }, { "A412", "A462" }, + { "A413", "A463" }, { "A414", "A464" }, { "A423", "A473" }, { "A428", "A478" }, + { "A442", "A492" }, { "A449", "A499" }, { "A450", "A500" }, { "A453", "A503" }, + { "A484", "A534" }, { "A487", "A537" }, { "A489", "A539" }, { "A500", "A550" }, + { "A115", "A115" }, + { "A360", "A360" }, { "A361", "A361" }, { "A362", "A362" }, { "A364", "A364" }, + { "A365", "A365" }, { "A366", "A366" }, { "A367", "A367" }, { "A368", "A368" }, + { "A369", "A369" }, { "A370", "A370" }, { "A371", "A371" }, { "A372", "A372" }, + { "A373", "A373" }, + }; + for (unsigned int i = 0; i < ARRAY_SIZE(map_27_2); i++) + expect_tag(m27_2, map_27_2[i].in, map_27_2[i].out); + assert(iomfb_v27_sleep_methods_complete(m27_2)); + assert(!iomfb_v27_missing_method(m27_2, &missing_count) && missing_count == 0); + + /* Unrecorded tags on 27.2 fail closed (no +50 arithmetic, no 27.0 fallback). */ + expect_tag_fail(m27_2, "A495"); + expect_tag_fail(m27_2, "A499"); + expect_tag_fail(m27_2, "A375"); + expect_tag_fail(m27_2, "A999"); + + /* Incomplete renumbered table (27.3) translates recorded entries and fails closed on missing ones. */ + expect_tag(m27_3, "A453", "A503"); + const char *missing_27_3[] = { + "A411", "A413", "A484", "A500", "A442", "A449", "A115", "A364", "A367", + }; + for (unsigned int i = 0; i < ARRAY_SIZE(missing_27_3); i++) + expect_tag_fail(m27_3, missing_27_3[i]); + assert(!iomfb_v27_sleep_methods_complete(m27_3)); + assert(iomfb_v27_missing_method(m27_3, &missing_count) && missing_count > 0); + + /* Dropping an optional sleep/paired entry does not block basic boot admission, + * but does mark sleep incomplete when a sleep entry is missing, and any table + * other than 27.0 or the J714s copy fails closed as renumbered. */ + memcpy(partial_27_2, m27_2, sizeof(partial_27_2)); + partial_27_2[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(partial_27_2)); + expect_tag_fail(partial_27_2, "A442"); + assert(!iomfb_v27_missing_method(partial_27_2, &missing_count) && missing_count == 0); + assert(!iomfb_v27_sleep_methods_complete(partial_27_2)); + + struct dcp_method_entry future_27_x[dcpep_num_methods]; + memcpy(future_27_x, m27_0, sizeof(future_27_x)); + memcpy(future_27_x[dcpep_start_signal].tag, "A501", 4); + future_27_x[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(future_27_x)); + expect_tag_fail(future_27_x, "A442"); + + /* + * Sleep transport admission keys on T6050 DCP/DCPEXT and table completeness. + * No of_machine_is_compatible() stub exists in this translation unit, enforcing + * at compile time that admission does not gate on a board model. + */ + struct apple_dcp dcp = { + .dev = &dev, + .hw = { .adopt_live_session = true, .iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT }, + .fw_compat = DCP_FIRMWARE_V_27_0, + }; + const char *t6050_compats[] = { "apple,t6050-dcp", "apple,t6050-dcpext" }; + for (unsigned int i = 0; i < ARRAY_SIZE(t6050_compats); i++) { + node.compatible = t6050_compats[i]; + dcp.v27_methods = m27_0; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = j714s; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_2; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_3; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = partial_27_2; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = NULL; assert(!dcp_v27_sleep_transport_supported(&dcp)); + } + dcp.v27_methods = m27_2; + node.compatible = "apple,t6041-dcp"; assert(!dcp_v27_sleep_transport_supported(&dcp)); + node.compatible = "apple,t6050-dcp"; + dcp.hw.adopt_live_session = false; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.adopt_live_session = true; + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_H17G; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; + dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; assert(!dcp_v27_sleep_transport_supported(&dcp)); + + free((void *)j714s); + puts("PASS v27 tag translation fail-closed and table-driven sleep transport admission"); + return 0; +} +''' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 87140d980dc955..f716cdbb5941bb 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -93,6 +93,7 @@ def main(): ('boot', 'syslog-policy', boot.syslog, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ('-Wno-unused-function',)), + ('boot', 'v27-tag-translation', boot.v27_tag_translation, ((),), ()), ('edid', 'dpavserv-start', edid.startup, ((),), ()), ('edid', 'service-rebind', edid.rebind, ((),), ()), ('edid', 'provider-admission', edid.admission, ((),), ()), From f20d4016ff9d25527f5bc60c06da2677d2ddc1f8 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:39:20 -0500 Subject: [PATCH 0688/1514] net: r8169: honour realtek,aspm-safe device property On fixed PCIe links integrated on DT-described boards, the RTL812x OCP ASPM-qualification fuse (0xc0b2) may not be programmed even when the board's fixed link has been qualified for ASPM L1. Check the boolean "realtek,aspm-safe" device property in rtl_aspm_is_safe() so boards that qualify their fixed Realtek link in device tree can permit ASPM L1 without disabling it during probe. Signed-off-by: Satya Benson --- drivers/net/ethernet/realtek/r8169_main.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/net/ethernet/realtek/r8169_main.c b/drivers/net/ethernet/realtek/r8169_main.c index ee1bc9bd04470c..d3cef6016c410f 100644 --- a/drivers/net/ethernet/realtek/r8169_main.c +++ b/drivers/net/ethernet/realtek/r8169_main.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -5598,6 +5599,10 @@ static void rtl_init_mac_address(struct rtl8169_private *tp) /* register is set if system vendor successfully tested ASPM 1.2 */ static bool rtl_aspm_is_safe(struct rtl8169_private *tp) { + if (device_property_read_bool(&tp->pci_dev->dev, + "realtek,aspm-safe")) + return true; + if (tp->mac_version >= RTL_GIGA_MAC_VER_46 && r8168_mac_ocp_read(tp, 0xc0b2) & 0xf) return true; From ed5c57ef2c58e34c0fab10d2123208efb9a212c0 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 18:26:41 -0300 Subject: [PATCH 0689/1514] irqchip/apple-aic: Keep a concurrent smp_affinity write on a CPU set change aic_irq_cpus_update() copied each IRQ's affinity mask into a static cpumask and then passed the copy to irq_set_affinity(). The copy was taken without the descriptor lock, so a /proc/irq/N/smp_affinity write (irqbalance, say) that lands between the copy and irq_set_affinity() was overwritten with the stale mask, and the user's setting was lost. Pass irq_get_affinity_mask() to irq_set_affinity() directly. The mask is then read under the descriptor lock, so the set change applies whatever affinity is current. genirq does the same when it restores a managed IRQ's affinity on CPU online (irq_restore_affinity_of_irq()). The static cpumask goes with it. If the IRQ's descriptor is gone by the time its mask is looked up, irq_get_affinity_mask() returns NULL. Skip that IRQ instead of passing NULL on to irq_set_affinity(). aic_irq_cpus_update() runs only on AICv2 and AICv3 at EL2, where aic2_routed_chip is used. There it changes the stored and effective affinity that is reported. It doesn't touch AICv1, or how the hardware delivers IRQs (SIQ_CFG decides that). Fixes: d3d404c0e448 ("irqchip/apple-aic: Keep the routed IRQ affinity across CPU hotplug") Signed-off-by: Jonathan Goyvaerts --- drivers/irqchip/irq-apple-aic.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 52a892164c3a46..dbd12920314425 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -1107,8 +1107,8 @@ static int aic_init_cpu(unsigned int cpu) */ static void aic_irq_cpus_update(unsigned int cpu, bool accepts) { - static struct cpumask aff; /* CPU hotplug is serialized */ struct aic_irq_chip *ic = aic_irqc; + const struct cpumask *aff; unsigned int die, i, virq; if (accepts == cpumask_test_cpu(cpu, &aic_irq_cpus)) @@ -1120,8 +1120,11 @@ static void aic_irq_cpus_update(unsigned int cpu, bool accepts) virq = irq_find_mapping(ic->hw_domain, AIC_IRQ_HWIRQ(die, i)); if (!virq || !irq_has_action(virq)) continue; - cpumask_copy(&aff, irq_get_affinity_mask(virq)); - irq_set_affinity(virq, &aff); + aff = irq_get_affinity_mask(virq); + if (!aff) + continue; + /* Read under the desc lock, so a concurrent smp_affinity write is kept */ + irq_set_affinity(virq, aff); } } } From c50540c8ef05eed17ef59c67dcf3d4a3958d4a02 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 18 Nov 2026 13:47:55 -0500 Subject: [PATCH 0690/1514] hwmon: macsmc: retain fan ownership until automatic mode is restored Allow the thermal worker to retry a failed AUTO write or unlock-key release, and keep the unlocked state set until the final readback confirms every fan has returned to system mode. Releasing a set of fans with no kernel-owned members succeeds. Signed-off-by: Erik Bourget --- drivers/hwmon/macsmc-hwmon-test.c | 135 +++++++++++++++++++++++++++++- drivers/hwmon/macsmc-hwmon.c | 64 +++++++++----- 2 files changed, 179 insertions(+), 20 deletions(-) diff --git a/drivers/hwmon/macsmc-hwmon-test.c b/drivers/hwmon/macsmc-hwmon-test.c index d2f1333f0571e8..1e4f5a4778763c 100644 --- a/drivers/hwmon/macsmc-hwmon-test.c +++ b/drivers/hwmon/macsmc-hwmon-test.c @@ -210,6 +210,9 @@ struct macsmc_fan_test { int manual_busy[2]; int target_writes; smc_key fail_key; + smc_key fail_read_key; + bool relock_stuck; + u8 relock_mode; }; static int fan_test_index(smc_key key) @@ -223,6 +226,9 @@ static int fan_test_read(struct apple_smc *smc, smc_key key, void *buf, size_t s u32 value; int i = fan_test_index(key); + if (key == t->fail_read_key) + return -EIO; + switch (key & 0xff00ffff) { case __SMC_KEY('F', 0, 'M', 'd'): t->mode_reads++; @@ -262,8 +268,10 @@ static int fan_test_write(struct apple_smc *smc, smc_key key, const void *buf, s for (i = 0; i < ARRAY_SIZE(t->mode); i++) { if (value && t->mode[i] == MACSMC_FAN_MODE_SYSTEM) t->mode[i] = MACSMC_FAN_MODE_AUTO; - else if (!value) + else if (!value && !t->relock_stuck) t->mode[i] = MACSMC_FAN_MODE_SYSTEM; + else if (!value) + t->mode[i] = t->relock_mode; } return size; } @@ -507,6 +515,127 @@ static void macsmc_fan_test_unlock_fails(struct kunit *test) KUNIT_EXPECT_EQ(test, t->refused, 0); } +static void fan_test_enable_controllable(struct macsmc_fan_test *t) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(t->fans); i++) + t->fans[i].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; +} + +/* A live AUTO write failure keeps ownership so the next release retries. */ +static void macsmc_fan_test_auto_write_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(F0Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->fans[0].manual); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].manual); + KUNIT_EXPECT_FALSE(test, t->fans[1].kernel); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* At suspend, failed AUTO writes still yield to the global relock. */ + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(F0Md); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_suspend(&dev), 0); + fan_test_released(test, t); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_resume(&dev), 0); +} + +/* A failed relock write leaves unlocked set so the next release retries. */ +static void macsmc_fan_test_relock_write_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_key = SMC_KEY(Ftst); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + +/* Relock stays pending across readback errors so repeated releases recheck. */ +static void macsmc_fan_test_relock_readback_fails(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + int ftst_writes; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_read_key = SMC_KEY(F1Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + /* Repeated release still fails and retries relock once while readback fails. */ + ftst_writes = t->ftst_writes; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_EQ(test, t->ftst_writes, ftst_writes + 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->fail_read_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* A fresh manual request after a readback failure re-unlocks Ftst. */ + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->fail_read_key = SMC_KEY(F1Md); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -EIO); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + t->fail_read_key = 0; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 2); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + +/* A relock readback timeout keeps unlocked set until a later release confirms system mode. */ +static void macsmc_fan_test_relock_timeout(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + fan_test_enable_controllable(t); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 1000, 0), 5777); + t->relock_stuck = true; + t->relock_mode = MACSMC_FAN_MODE_AUTO; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + + t->relock_stuck = false; + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); +} + /* A stopped fan may leave mode 3 before the manual-mode write is ready. */ static void macsmc_fan_test_stopped_manual_busy(struct kunit *test) { @@ -572,6 +701,10 @@ static struct kunit_case macsmc_fan_test_cases[] = { KUNIT_CASE(macsmc_fan_test_untouched), KUNIT_CASE(macsmc_fan_test_suspend_manual), KUNIT_CASE(macsmc_fan_test_unlock_fails), + KUNIT_CASE(macsmc_fan_test_auto_write_fails), + KUNIT_CASE(macsmc_fan_test_relock_write_fails), + KUNIT_CASE(macsmc_fan_test_relock_readback_fails), + KUNIT_CASE(macsmc_fan_test_relock_timeout), {} }; diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index 50591b3d1d55b2..8c70784ac3b801 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -403,7 +403,6 @@ static int macsmc_hwmon_fans_relock(struct macsmc_hwmon *hwmon) dev_err(hwmon->dev, "cannot hand the fans back to the SMC (%d)\n", ret); return ret; } - hwmon->fan.unlocked = false; timeout = jiffies + msecs_to_jiffies(MACSMC_FAN_MODE_TIMEOUT_MS); for (i = 0; i < hwmon->fan.count; i++) { @@ -426,30 +425,44 @@ static int macsmc_hwmon_fans_relock(struct macsmc_hwmon *hwmon) } } + hwmon->fan.unlocked = false; return 0; } -/* Return a fan to firmware control. Called with the fan lock held. */ -static int macsmc_hwmon_fan_auto(struct macsmc_hwmon *hwmon, - struct macsmc_hwmon_fan *fan) +static int macsmc_hwmon_fan_set_auto(struct macsmc_hwmon *hwmon, + struct macsmc_hwmon_fan *fan) { - int ret, relock; + int ret; if (!fan->manual) return 0; ret = macsmc_hwmon_write_key(hwmon->smc, &fan->mode, MACSMC_FAN_MODE_AUTO); + /* + * At shutdown or suspend the final unlock-key relock hands all + * fans back, even if one fan refuses its individual AUTO write. + */ + if (ret < 0 && !(hwmon->fan.stopped && hwmon->fan.unlocked)) + return ret; fan->manual = false; fan->kernel = false; hwmon->fan.manual--; + return 0; +} - if (hwmon->fan.unlocked && !hwmon->fan.manual) { - relock = macsmc_hwmon_fans_relock(hwmon); - if (relock) - return relock; - } +/* Return a fan to firmware control. Called with the fan lock held. */ +static int macsmc_hwmon_fan_auto(struct macsmc_hwmon *hwmon, + struct macsmc_hwmon_fan *fan) +{ + int ret = macsmc_hwmon_fan_set_auto(hwmon, fan); + + if (ret) + return ret; - return ret < 0 ? ret : 0; + if (hwmon->fan.unlocked && !hwmon->fan.manual) + return macsmc_hwmon_fans_relock(hwmon); + + return 0; } /* @@ -480,7 +493,11 @@ static int macsmc_hwmon_fan_manual(struct macsmc_hwmon *hwmon, if (!hwmon->fan.unlock_key) return -EOPNOTSUPP; - if (!hwmon->fan.unlocked) { + /* + * Re-unlock when no fan is manual so a prior relock that wrote + * 0 but failed readback does not wait on a locked SMC. + */ + if (!hwmon->fan.unlocked || !hwmon->fan.manual) { ret = apple_smc_write_u8(hwmon->smc, hwmon->fan.unlock_key, 1); if (ret < 0) { /* The key may have been set anyway; clear it. */ @@ -589,14 +606,16 @@ static int macsmc_hwmon_set_fan(struct macsmc_hwmon *hwmon, int channel, long va * returns to the SMC at suspend, shutdown and unbind. Only fans whose device * tree node names their mode, target, minimum and maximum keys take part. * - * Return: the first such fan's target in rpm (0 once handed back), -ENODEV - * without such a fan, -EBUSY while stopped, or the first error. + * Return: the first such fan's target in rpm for a non-zero @permille, or 0 + * when @permille is 0 (even when no fan is kernel-owned); -ENODEV if @dev is + * unbound or for a non-zero @permille without such a fan; -EBUSY while + * stopped for a non-zero @permille; or the first error. */ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm) { struct macsmc_hwmon *hwmon = dev_get_drvdata(dev); - long first = -ENODEV; + long first = permille ? -ENODEV : 0; int ret = 0; u32 i; @@ -622,9 +641,7 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, continue; if (!permille) { - if (first < 0) - first = 0; - err = macsmc_hwmon_fan_auto(hwmon, fan); + err = macsmc_hwmon_fan_set_auto(hwmon, fan); if (err && !ret) ret = err; continue; @@ -668,6 +685,13 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, } } + if (!permille && hwmon->fan.unlocked && !hwmon->fan.manual) { + int err = macsmc_hwmon_fans_relock(hwmon); + + if (err && !ret) + ret = err; + } + return ret ? ret : first; } EXPORT_SYMBOL_GPL(macsmc_hwmon_fans_request); @@ -698,7 +722,9 @@ static void macsmc_hwmon_fans_restore(struct macsmc_hwmon *hwmon) guard(mutex)(&hwmon->fan.lock); for (i = 0; i < hwmon->fan.count; i++) - macsmc_hwmon_fan_auto(hwmon, &hwmon->fan.fans[i]); + macsmc_hwmon_fan_set_auto(hwmon, &hwmon->fan.fans[i]); + if (hwmon->fan.unlocked && !hwmon->fan.manual) + macsmc_hwmon_fans_relock(hwmon); } static void macsmc_hwmon_fans_restore_action(void *data) From e2c950da0de1eb97c6a15072ae7b45ef995de15f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:39:20 -0500 Subject: [PATCH 0691/1514] dt-bindings: hwmon: apple,smc-hwmon: add SoC die fan-assistance trip properties Allow an SMC hwmon node that exposes a single SoC die sensor key to declare the machine-specific active fan-assistance trigger temperature, release hysteresis, and minimum hold time in the device tree. These properties are intended to be populated by the boot loader (Aura) from the machine's ADT or SMC rather than hardcoded in static board .dts files. All three properties must appear together alongside apple,soc-die-keys; boards that omit them leave kernel hotspot fan assistance disabled. Signed-off-by: Erik Bourget --- .../bindings/hwmon/apple,smc-hwmon.yaml | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml index b0b1dac1225ee3..79f372bb2db98e 100644 --- a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml +++ b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml @@ -69,6 +69,37 @@ properties: apple,no-data-below-millicelsius adds no channel; that child supplies the zone, and its readings below the threshold are left out of it. + apple,soc-die-fan-trip-millicelsius: + maxItems: 1 + description: + Active trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone for kernel hotspot fan assistance. Intended to be populated + by the boot loader (Aura) from the machine's ADT or SMC rather than + hardcoded in static board .dts files. Requires a single key in + apple,soc-die-keys, apple,soc-die-fan-hysteresis-millicelsius, and + apple,soc-die-fan-hold-ms. Without these properties, hotspot fan + assistance stays off. + + apple,soc-die-fan-hysteresis-millicelsius: + maxItems: 1 + description: + Hysteresis, in millidegrees Celsius, below + apple,soc-die-fan-trip-millicelsius for the macsmc_soc_die active trip + (release temperature is trip minus hysteresis). Intended to be populated + by the boot loader (Aura) from the machine's ADT or SMC rather than + hardcoded in static board .dts files. Must be strictly positive and less + than the trip temperature. + + apple,soc-die-fan-hold-ms: + minimum: 1 + description: + Minimum hold time, in milliseconds, that kernel hotspot fan assistance + keeps fans boosted after the GPU goes idle or the SoC die temperature + falls below the release temperature before returning them to SMC + automatic control. Intended to be populated by the boot loader (Aura) + from the machine's ADT or SMC rather than hardcoded in static board .dts + files. + apple,thermal-pressure-key: $ref: /schemas/types.yaml#/definitions/string pattern: "^[A-Za-z0-9]{4}$" @@ -151,6 +182,20 @@ patternProperties: $ref: "#/$defs/sensor" unevaluatedProperties: false +dependentRequired: + apple,soc-die-fan-trip-millicelsius: + - apple,soc-die-keys + - apple,soc-die-fan-hysteresis-millicelsius + - apple,soc-die-fan-hold-ms + apple,soc-die-fan-hysteresis-millicelsius: + - apple,soc-die-keys + - apple,soc-die-fan-trip-millicelsius + - apple,soc-die-fan-hold-ms + apple,soc-die-fan-hold-ms: + - apple,soc-die-keys + - apple,soc-die-fan-trip-millicelsius + - apple,soc-die-fan-hysteresis-millicelsius + allOf: - if: required: From f9add947c403771daf418fa70189f23d6328904e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:39:20 -0500 Subject: [PATCH 0692/1514] hwmon: macsmc: add manual-only fan request and DT hotspot-assist helpers Keep apple,smc-hwmon device-tree binding knowledge inside macsmc-hwmon instead of making consumer drivers parse its DT schema: - Add macsmc_hwmon_fans_request_manual(), which behaves like macsmc_hwmon_fans_request() but only drives fans whose device-tree node carries apple,fan-manual-control (leaving other fans untouched). - Parse apple,soc-die-fan-trip-millicelsius, apple,soc-die-fan-hysteresis-millicelsius, and apple,soc-die-fan-hold-ms when a single key is listed in apple,soc-die-keys, and register the matching THERMAL_TRIP_ACTIVE trip on the macsmc_soc_die thermal zone. - Export macsmc_hwmon_hotspot_assist_available() and macsmc_hwmon_hotspot_assist_policy() so thermal consumers can query whether the board enables hotspot fan assistance and read its machine-supplied thresholds and hold duration without hardcoding limits or SMC key names. - Add KUnit coverage for macsmc_hwmon_fans_request_manual() and macsmc_hwmon_hotspot_assist_policy(). Signed-off-by: Erik Bourget --- Documentation/hwmon/macsmc-hwmon.rst | 18 ++- drivers/hwmon/macsmc-hwmon-test.c | 60 +++++++ drivers/hwmon/macsmc-hwmon.c | 230 +++++++++++++++++++++++---- include/linux/mfd/macsmc.h | 30 ++++ 4 files changed, 306 insertions(+), 32 deletions(-) diff --git a/Documentation/hwmon/macsmc-hwmon.rst b/Documentation/hwmon/macsmc-hwmon.rst index c4df2eef90fbdc..2ce19711b42594 100644 --- a/Documentation/hwmon/macsmc-hwmon.rst +++ b/Documentation/hwmon/macsmc-hwmon.rst @@ -38,11 +38,19 @@ shutdown and removal release only fans taken over by such a request; resume does not reapply it. A new target write is required after resume. A kernel thermal policy (the M5 GPU governor) sets the fans through -macsmc_hwmon_fans_request(), as a share of each fan's range, on every fan -whose node names its mode, target, minimum and maximum keys, with or without -apple,fan-manual-control. It uses the same manual mode, leaves fans userspace -holds alone, and its fans return to the SMC at suspend, shutdown and removal -like userspace's. +macsmc_hwmon_fans_request() (every fan whose node names its mode, target, +minimum and maximum keys, with or without apple,fan-manual-control) or +macsmc_hwmon_fans_request_manual() (only fans with apple,fan-manual-control), +as a share of each fan's range. Both use the same manual mode, leave fans +userspace holds alone, and return their fans to the SMC at suspend, shutdown +and removal like userspace's. + +When a board's Devicetree also gives ``apple,soc-die-fan-trip-millicelsius``, +``apple,soc-die-fan-hysteresis-millicelsius`` and ``apple,soc-die-fan-hold-ms`` +beside a single key in ``apple,soc-die-keys``, ``macsmc_soc_die`` is registered +with that active trip and ``macsmc_hwmon_hotspot_assist_policy()`` exposes the +thresholds and hold time to hotspot fan assistance. Without those properties +from the Devicetree, hotspot fan assistance stays off. SoC die temperatures are described by the ``apple,soc-die-keys`` string list on the hwmon device node. The driver appends these temperature channels after diff --git a/drivers/hwmon/macsmc-hwmon-test.c b/drivers/hwmon/macsmc-hwmon-test.c index 1e4f5a4778763c..93a6a9c0195d77 100644 --- a/drivers/hwmon/macsmc-hwmon-test.c +++ b/drivers/hwmon/macsmc-hwmon-test.c @@ -686,6 +686,65 @@ static void macsmc_fan_test_spinning(struct kunit *test) KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); } +/* Manual-only kernel fan request touches only apple,fan-manual-control fans. */ +static void macsmc_fan_test_manual_only_request(struct kunit *test) +{ + struct macsmc_fan_test *t = test->priv; + struct macsmc_hwmon_fan_assist policy = {}; + struct device dev = {}; + + dev_set_drvdata(&dev, &t->hwmon); + t->fans[0].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; + t->fans[1].attrs = HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX; + t->fans[0].manual_control = true; + t->fans[1].manual_control = false; + t->hwmon.fan_assist.trigger_mc = 98000; + t->hwmon.fan_assist.release_mc = 82000; + t->hwmon.fan_assist.hold_ms = 30000; + t->hwmon.fan_assist_valid = true; + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, &policy), 0); + KUNIT_EXPECT_EQ(test, policy.trigger_mc, 98000); + KUNIT_EXPECT_EQ(test, policy.release_mc, 82000); + KUNIT_EXPECT_EQ(test, policy.hold_ms, 30000U); + + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 1000, 0), 5777); + KUNIT_EXPECT_EQ(test, t->mode[0], MACSMC_FAN_MODE_MANUAL); + KUNIT_EXPECT_EQ(test, t->target[0], FAN_TEST_F5777); + KUNIT_EXPECT_EQ(test, t->mode[1], MACSMC_FAN_MODE_AUTO); + KUNIT_EXPECT_EQ(test, t->target[1], 0); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[1].manual); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* Manual-only release leaves a non-manual fan held by the unrestricted API. */ + KUNIT_ASSERT_GT(test, macsmc_hwmon_fans_request(&dev, 500, 0), 0); + KUNIT_EXPECT_TRUE(test, t->fans[0].kernel); + KUNIT_EXPECT_TRUE(test, t->fans[1].kernel); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 0, 0), 0); + KUNIT_EXPECT_FALSE(test, t->fans[0].kernel); + KUNIT_EXPECT_FALSE(test, t->fans[0].manual); + KUNIT_EXPECT_TRUE(test, t->fans[1].kernel); + KUNIT_EXPECT_TRUE(test, t->fans[1].manual); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 1); + KUNIT_EXPECT_TRUE(test, t->hwmon.fan.unlocked); + KUNIT_ASSERT_EQ(test, macsmc_hwmon_fans_request(&dev, 0, 0), 0); + fan_test_released(test, t); + + /* Without any manual-control fan, policy and boost return -ENODEV. */ + t->fans[0].manual_control = false; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, NULL), -ENODEV); + KUNIT_EXPECT_EQ(test, macsmc_hwmon_fans_request_manual(&dev, 1000, 0), -ENODEV); + KUNIT_EXPECT_EQ(test, t->hwmon.fan.manual, 0); + + /* Without DT-supplied trip thresholds, policy returns -ENODEV. */ + t->fans[0].manual_control = true; + t->hwmon.fan_assist_valid = false; + KUNIT_EXPECT_EQ(test, macsmc_hwmon_hotspot_assist_policy(&dev, NULL), -ENODEV); +} + static struct kunit_case macsmc_fan_test_cases[] = { KUNIT_CASE(macsmc_fan_test_stopped_manual_busy), KUNIT_CASE(macsmc_fan_test_manual_busy_timeout), @@ -705,6 +764,7 @@ static struct kunit_case macsmc_fan_test_cases[] = { KUNIT_CASE(macsmc_fan_test_relock_write_fails), KUNIT_CASE(macsmc_fan_test_relock_readback_fails), KUNIT_CASE(macsmc_fan_test_relock_timeout), + KUNIT_CASE(macsmc_fan_test_manual_only_request), {} }; diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index 8c70784ac3b801..4b2fbf055ce90f 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -91,6 +91,9 @@ struct macsmc_hwmon_sensors { #define MACSMC_FAN_MODE_TIMEOUT_MS 10000 #define MACSMC_FAN_MODE_POLL_MS 100 +#define MACSMC_DIE_MIN_MC -40000 +#define MACSMC_DIE_MAX_MC 150000 + struct macsmc_hwmon_fans { struct hwmon_channel_info channel_info; struct macsmc_hwmon_fan *fans; @@ -126,6 +129,9 @@ struct macsmc_hwmon { /* SoC die temperature keys listed, and the ones present. */ u32 die_listed; u32 die_count; + /* DT-supplied hotspot fan-assistance trip on macsmc_soc_die. */ + struct macsmc_hwmon_fan_assist fan_assist; + bool fan_assist_valid; }; static ssize_t thermal_pressure_level_show(struct device *dev, @@ -593,26 +599,15 @@ static int macsmc_hwmon_set_fan(struct macsmc_hwmon *hwmon, int channel, long va return ret; } -/** - * macsmc_hwmon_fans_request() - set the fans for a kernel thermal policy - * @dev: the bound macsmc-hwmon device; the caller holds its device lock - * @permille: each fan's target as a share of its minimum-to-maximum range; - * 0 hands the fans this interface set back to the SMC - * @min_step_rpm: a fan already set by this interface whose target is closer - * than this to the new one keeps its target - * - * The fans go through the same manual mode as a userspace request, so the - * mode key has one owner: fans userspace holds are left alone, and every fan - * returns to the SMC at suspend, shutdown and unbind. Only fans whose device - * tree node names their mode, target, minimum and maximum keys take part. - * - * Return: the first such fan's target in rpm for a non-zero @permille, or 0 - * when @permille is 0 (even when no fan is kernel-owned); -ENODEV if @dev is - * unbound or for a non-zero @permille without such a fan; -EBUSY while - * stopped for a non-zero @permille; or the first error. - */ -int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, - unsigned int min_step_rpm) +static bool macsmc_hwmon_fan_controllable(const struct macsmc_hwmon_fan *fan) +{ + return fan->mode.macsmc_key && + (fan->attrs & (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) == + (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX); +} + +static int __macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, + unsigned int min_step_rpm, bool manual_only) { struct macsmc_hwmon *hwmon = dev_get_drvdata(dev); long first = permille ? -ENODEV : 0; @@ -633,9 +628,9 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, long min, max, now, target; int err; - if (!fan->mode.macsmc_key || - (fan->attrs & (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) != - (HWMON_F_TARGET | HWMON_F_MIN | HWMON_F_MAX)) + if (!macsmc_hwmon_fan_controllable(fan)) + continue; + if (manual_only && !fan->manual_control) continue; if (fan->manual && !fan->kernel) continue; @@ -694,8 +689,173 @@ int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, return ret ? ret : first; } + +/** + * macsmc_hwmon_fans_request() - set the fans for a kernel thermal policy + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @permille: each fan's target as a share of its minimum-to-maximum range; + * 0 hands the fans this interface set back to the SMC + * @min_step_rpm: a fan already set by this interface whose target is closer + * than this to the new one keeps its target + * + * The fans go through the same manual mode as a userspace request, so the + * mode key has one owner: fans userspace holds are left alone, and every fan + * returns to the SMC at suspend, shutdown and unbind. Only fans whose device + * tree node names their mode, target, minimum and maximum keys take part. + * + * Return: the first such fan's target in rpm for a non-zero @permille, or 0 + * when @permille is 0 (even when no fan is kernel-owned); -ENODEV if @dev is + * unbound or for a non-zero @permille without such a fan; -EBUSY while + * stopped for a non-zero @permille; or the first error. + */ +int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return __macsmc_hwmon_fans_request(dev, permille, min_step_rpm, false); +} EXPORT_SYMBOL_GPL(macsmc_hwmon_fans_request); +/** + * macsmc_hwmon_fans_request_manual() - set DT-manual fans for a kernel policy + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @permille: each fan's target as a share of its minimum-to-maximum range; + * 0 hands the fans this interface set back to the SMC + * @min_step_rpm: minimum delta before updating an already kernel-owned target + * + * Like macsmc_hwmon_fans_request(), but only drives fans whose device tree + * node carries apple,fan-manual-control. Fans without apple,fan-manual-control + * are left alone. + */ +int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return __macsmc_hwmon_fans_request(dev, permille, min_step_rpm, true); +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_fans_request_manual); + +static bool macsmc_hwmon_fan_settable(const struct device_node *fan) +{ + return of_property_present(fan, "apple,fan-mode") && + of_property_present(fan, "apple,fan-target") && + of_property_present(fan, "apple,fan-minimum") && + of_property_present(fan, "apple,fan-maximum"); +} + +/* + * Parse the DT-supplied hotspot fan-assistance thresholds for macsmc_soc_die: + * a single key in apple,soc-die-keys plus valid trigger temperature, + * hysteresis, and hold duration. + */ +static bool macsmc_hwmon_parse_fan_assist(const struct device_node *np, + struct macsmc_hwmon_fan_assist *policy) +{ + u32 trip, hyst, hold_ms; + + if (!np || of_property_count_strings(np, "apple,soc-die-keys") != 1) + return false; + if (of_property_read_u32(np, "apple,soc-die-fan-trip-millicelsius", &trip) || + of_property_read_u32(np, "apple,soc-die-fan-hysteresis-millicelsius", &hyst) || + of_property_read_u32(np, "apple,soc-die-fan-hold-ms", &hold_ms)) + return false; + if (!trip || trip > MACSMC_DIE_MAX_MC || !hyst || hyst >= trip || !hold_ms) + return false; + + if (policy) { + policy->trigger_mc = (int)trip; + policy->release_mc = (int)(trip - hyst); + policy->hold_ms = hold_ms; + } + return true; +} + +static bool macsmc_hwmon_node_hotspot_assist(const struct device_node *np, + struct macsmc_hwmon_fan_assist *policy) +{ + if (!macsmc_hwmon_parse_fan_assist(np, policy)) + return false; + for_each_child_of_node_with_prefix(np, child, "fan-") { + if (of_property_read_bool(child, "apple,fan-manual-control") && + macsmc_hwmon_fan_settable(child)) + return true; + } + return false; +} + +static bool macsmc_hwmon_node_path_available(const struct device_node *np) +{ + struct device_node *node = of_node_get((struct device_node *)np); + + while (node) { + struct device_node *parent; + + if (!of_device_is_available(node)) { + of_node_put(node); + return false; + } + parent = of_get_parent(node); + of_node_put(node); + node = parent; + } + return true; +} + +/** + * macsmc_hwmon_hotspot_assist_available() - whether the DT configures hotspot fan assistance + * + * Scans available apple,smc-hwmon nodes (with all parents available) for one + * describing a single SoC die key, valid hotspot fan-assistance trip + * thresholds and hold duration, and at least one settable fan with + * apple,fan-manual-control. + */ +bool macsmc_hwmon_hotspot_assist_available(void) +{ + struct device_node *np; + + for_each_compatible_node(np, NULL, "apple,smc-hwmon") { + if (macsmc_hwmon_node_path_available(np) && + macsmc_hwmon_node_hotspot_assist(np, NULL)) { + of_node_put(np); + return true; + } + } + return false; +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_available); + +/** + * macsmc_hwmon_hotspot_assist_policy() - read hotspot fan-assistance policy from @dev + * @dev: the bound macsmc-hwmon device; the caller holds its device lock + * @policy: optional destination for trigger/release temperatures and hold time + * + * Return: 0 if @dev has a single present SoC die sensor, DT-supplied active + * trip thresholds and hold time, and at least one probed fan with + * apple,fan-manual-control; -ENODEV otherwise. + */ +int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + struct macsmc_hwmon *hwmon = dev_get_drvdata(dev); + bool has_manual = false; + u32 i; + + if (!hwmon || !hwmon->fan_assist_valid) + return -ENODEV; + for (i = 0; i < hwmon->fan.count; i++) { + const struct macsmc_hwmon_fan *fan = &hwmon->fan.fans[i]; + + if (fan->manual_control && macsmc_hwmon_fan_controllable(fan)) { + has_manual = true; + break; + } + } + if (!has_manual) + return -ENODEV; + if (policy) + *policy = hwmon->fan_assist; + return 0; +} +EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_policy); + static int macsmc_hwmon_write_fan(struct device *dev, u32 attr, int channel, long val) { @@ -1380,8 +1540,6 @@ static void macsmc_hwmon_populate_fan_configs(u32 *configs, const struct macsmc_ */ #if IS_ENABLED(CONFIG_THERMAL) #define MACSMC_SOC_DIE_ZONE "macsmc_soc_die" -#define MACSMC_DIE_MIN_MC -40000 -#define MACSMC_DIE_MAX_MC 150000 static int macsmc_hwmon_die_hottest(struct macsmc_hwmon *hwmon, int *temp) { @@ -1451,8 +1609,22 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) key >> 24, (key >> 16) & 0xff, (key >> 8) & 0xff, key & 0xff); } - tz = thermal_tripless_zone_device_register(MACSMC_SOC_DIE_ZONE, hwmon, - &macsmc_hwmon_die_ops, NULL); + if (hwmon->fan_assist_valid) { + struct thermal_trip trip = { + .temperature = hwmon->fan_assist.trigger_mc, + .hysteresis = hwmon->fan_assist.trigger_mc - + hwmon->fan_assist.release_mc, + .type = THERMAL_TRIP_ACTIVE, + }; + + tz = thermal_zone_device_register_with_trips(MACSMC_SOC_DIE_ZONE, + &trip, 1, hwmon, + &macsmc_hwmon_die_ops, + NULL, 0, 0); + } else { + tz = thermal_tripless_zone_device_register(MACSMC_SOC_DIE_ZONE, hwmon, + &macsmc_hwmon_die_ops, NULL); + } if (IS_ERR(tz)) { dev_warn(hwmon->dev, "cannot register the SoC die temperature zone (%pe)\n", tz); return 0; @@ -1667,6 +1839,10 @@ static int macsmc_hwmon_probe(struct platform_device *pdev) if (ret) return dev_err_probe(hwmon->dev, ret, "Temperature discovery failed\n"); + if (hwmon->die_listed == 1 && hwmon->die_count == 1 && + macsmc_hwmon_parse_fan_assist(hwmon->dev->of_node, &hwmon->fan_assist)) + hwmon->fan_assist_valid = true; + if (!hwmon->curr.count && !hwmon->fan.count && !hwmon->power.count && !hwmon->temp.count && !hwmon->volt.count && !hwmon->pressure.macsmc_key) { diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 0bfd2079d0b969..16fde0aeb70cac 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -330,6 +330,17 @@ APPLE_SMC_TYPE_OPS(s8) struct device; +/* + * Hotspot fan-assistance thresholds read from the machine's SMC hwmon device + * tree node (macsmc_soc_die active trip temperature, hysteresis-derived + * release temperature, and minimum hold time). + */ +struct macsmc_hwmon_fan_assist { + int trigger_mc; + int release_mc; + unsigned int hold_ms; +}; + /* * The SMC hwmon cell's fan control for a kernel thermal policy (a GPU * governor): see drivers/hwmon/macsmc-hwmon.c. @@ -337,12 +348,31 @@ struct device; #if IS_REACHABLE(CONFIG_SENSORS_MACSMC_HWMON) int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm); +int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm); +bool macsmc_hwmon_hotspot_assist_available(void); +int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy); #else static inline int macsmc_hwmon_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm) { return -ENODEV; } +static inline int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + return -ENODEV; +} +static inline bool macsmc_hwmon_hotspot_assist_available(void) +{ + return false; +} +static inline int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + return -ENODEV; +} #endif static inline int apple_smc_read_flag(struct apple_smc *smc, smc_key key, bool *flag) From 16bd9275b6d4f71bc88e30c67303f2d746a159d4 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:39:20 -0500 Subject: [PATCH 0693/1514] drm/asahi: add hotspot fan assistance without host power budgeting Under sustained GPU load on boards whose SMC automatic curve lets the SoC hotspot climb high, add hotspot fan assistance in drivers/gpu/drm/asahi/g17/ that leaves the firmware's GPU power budget and CPU frequency limits alone: - Read the trigger temperature, release temperature (trip minus hysteresis), and hold duration from the bound macsmc-hwmon provider via macsmc_hwmon_hotspot_assist_policy(). When the board's device tree supplies no thresholds, or when no single-sensor macsmc_soc_die provider with a settable apple,fan-manual-control fan is bound, the assistance stays off and releases any active boost. - While the GPU is busy and the SoC hotspot reaches the DT trigger threshold, request rated speed on manual-control fans via macsmc_hwmon_fans_request_manual(). Return them to automatic control after the DT hold duration in which the GPU was idle or the hotspot stayed below the DT release threshold, or at once when the hotspot cannot be read. - A partial request (a later fan refusing after an earlier one accepted) is released before the next attempt, and failed budget boost or first curve requests are tracked as release-pending until unrestricted cleanup succeeds. While boosted, the request is repeated on each step on which the GPU is busy and the hotspot is at or above the release threshold, restoring rated speed if the hwmon provider was unbound and rebound in between. Whenever the host power budget controller (m5_thermal_governor bit 0) is enabled, it owns the fans with its own curve and hotspot assistance stays off. - No SMC key names, chip/board lists, or macsmc-hwmon DT schema walks live in the GPU driver: all DT selection, threshold parsing, and manual-control fan filtering are delegated to macsmc-hwmon helpers. tools/asahi/m5-hotspot-fans-dt-tests.py compiles the macsmc-hwmon DT checks and GPU fan wrappers against libfdt with a recording stand-in for macsmc_hwmon_fans_request_manual(), runs them across synthetic trees and the T6050 board trees (confirming J716c stays off without DT trips and governs with DT trips), compiles FanBoost from thermal.rs with rustc to test partial budget/hotspot request failure and handoff cleanup, verifies all 7 mutations are caught, and asserts no SMC key names or macsmc-hwmon DT binding strings appear in drivers/gpu/drm/asahi/g17/fans.c. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/fans.c | 38 +- drivers/gpu/drm/asahi/g17/fans.h | 6 + drivers/gpu/drm/asahi/g17/mod.rs | 5 + drivers/gpu/drm/asahi/g17/thermal.rs | 256 ++++++- tools/asahi/m5-hotspot-fans-dt-tests.py | 917 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 8 + 6 files changed, 1204 insertions(+), 26 deletions(-) create mode 100644 tools/asahi/m5-hotspot-fans-dt-tests.py diff --git a/drivers/gpu/drm/asahi/g17/fans.c b/drivers/gpu/drm/asahi/g17/fans.c index 6178a620686084..dbc63b68c4bccf 100644 --- a/drivers/gpu/drm/asahi/g17/fans.c +++ b/drivers/gpu/drm/asahi/g17/fans.c @@ -2,8 +2,10 @@ /* * The M5 thermal governor's sensor and fan calls (thermal.rs). The thermal * core and the SMC hwmon cell have stubs where they are not built; Rust - * reaches them through these. + * reaches them through these. All macsmc-hwmon device tree binding knowledge + * stays in drivers/hwmon/macsmc-hwmon.c. */ +#include #include #include #include @@ -22,3 +24,37 @@ int asahi_fans_request(struct device *dev, unsigned int permille, unsigned int m { return macsmc_hwmon_fans_request(dev, permille, min_step_rpm); } + +bool asahi_fans_hotspot_described(void) +{ + return macsmc_hwmon_hotspot_assist_available(); +} + +int asahi_fans_hotspot_policy(struct device *dev, int *trigger_mc, int *release_mc, + unsigned int *hold_ms) +{ + struct macsmc_hwmon_fan_assist policy; + int ret; + + ret = macsmc_hwmon_hotspot_assist_policy(dev, &policy); + if (ret) + return ret; + *trigger_mc = policy.trigger_mc; + *release_mc = policy.release_mc; + *hold_ms = policy.hold_ms; + return 0; +} + +/* + * A kernel fan request for hotspot fan assistance on the bound provider @dev: + * refused (-EPERM) unless the provider exposes a valid DT-configured hotspot + * assist policy, and only drives fans marked with apple,fan-manual-control. + * Handing the fans back (@permille 0) is always allowed. + */ +int asahi_fans_request_described(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + if (permille && macsmc_hwmon_hotspot_assist_policy(dev, NULL)) + return -EPERM; + return macsmc_hwmon_fans_request_manual(dev, permille, min_step_rpm); +} diff --git a/drivers/gpu/drm/asahi/g17/fans.h b/drivers/gpu/drm/asahi/g17/fans.h index 4bc18d80d3fe07..a29b4228c4987d 100644 --- a/drivers/gpu/drm/asahi/g17/fans.h +++ b/drivers/gpu/drm/asahi/g17/fans.h @@ -1,7 +1,13 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ #ifndef _ASAHI_G17_FANS_H #define _ASAHI_G17_FANS_H +#include struct device; int asahi_zone_temp(const char *name, int *temp); int asahi_fans_request(struct device *dev, unsigned int permille, unsigned int min_step_rpm); +bool asahi_fans_hotspot_described(void); +int asahi_fans_hotspot_policy(struct device *dev, int *trigger_mc, int *release_mc, + unsigned int *hold_ms); +int asahi_fans_request_described(struct device *dev, unsigned int permille, + unsigned int min_step_rpm); #endif diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d73d9cc68b5c97..7389df421a201e 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -974,6 +974,11 @@ impl Firmware { if self.effort.applied() != 0 && thermal::requested() { self.governor.note_activity(now); } + // Without the budget controller only the fan assistance runs (FanBoost::apply). + if !thermal::enabled() { + let busy = thermal::requested() && self.governor.recent_activity(now); + return (busy || fans, thermal::CpuAdvice::Release, busy); + } let Ok(current) = self.init.m5_power_budget() else { return (false, thermal::CpuAdvice::Release, false); }; diff --git a/drivers/gpu/drm/asahi/g17/thermal.rs b/drivers/gpu/drm/asahi/g17/thermal.rs index 6dd9bc7c2b15a6..45b267443ad2b6 100644 --- a/drivers/gpu/drm/asahi/g17/thermal.rs +++ b/drivers/gpu/drm/asahi/g17/thermal.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! GPU power budget governor for M5 (J714). +//! GPU thermal management for M5: opt-in host power budget governor (J714) and +//! DT-configured hotspot fan assistance. //! //! The firmware limits the GPU to the host power budget word in Region C within about a second //! (the calibrated maximum is written there at initialization). Left at that maximum under @@ -23,7 +24,7 @@ //! and at shutdown. Below the engage temperature nothing is written. use core::ffi::{c_char, c_int, c_uint, c_void, CStr}; -use core::sync::atomic::{AtomicI32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use kernel::{bindings, prelude::*}; // fans.c: the SMC hwmon cell's fan requests and thermal zone reads, which have stubs where @@ -31,6 +32,15 @@ use kernel::{bindings, prelude::*}; extern "C" { fn asahi_zone_temp(name: *const c_char, temp: *mut c_int) -> c_int; fn asahi_fans_request(dev: *mut c_void, permille: c_uint, min_step_rpm: c_uint) -> c_int; + fn asahi_fans_hotspot_described() -> bool; + fn asahi_fans_hotspot_policy( + dev: *mut c_void, + trigger_mc: *mut c_int, + release_mc: *mut c_int, + hold_ms: *mut c_uint, + ) -> c_int; + fn asahi_fans_request_described(dev: *mut c_void, permille: c_uint, min_step_rpm: c_uint) + -> c_int; } /// SoC hotspot temperature computed by the SMC (registered as a thermal zone by the SMC driver): @@ -109,9 +119,24 @@ const GPU_SLACK_PERCENT: i64 = 70; const CPU_HEAT_MARGIN_MC: i32 = 2000; const CPU_HEAT_FLOOR_SLACK_MW: i64 = 1000; -fn enabled() -> bool { +pub(super) fn enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 1 != 0 } + +/// Whether an available SMC hwmon node in the device tree describes hotspot fan assistance +/// (a single SoC die key, active trip thresholds and hold duration, and at least one settable +/// fan with apple,fan-manual-control, checked in macsmc-hwmon). Read at probe so a board +/// without a machine-supplied policy never arms the governor. +static HOTSPOT_FANS_DESCRIBED: AtomicBool = AtomicBool::new(false); + +/// Fan-only assistance: on wherever the SMC's device tree node describes fans a policy may set +/// and the hotspot, and the host power budget controller (m5_thermal_governor bit 0) is not +/// enabled. Whenever that controller is enabled it owns the fans with its own curve, so the +/// assistance never runs beside it; otherwise it leaves the firmware's power budget and CPU +/// policy in control. +pub(super) fn hotspot_fans_only() -> bool { + !enabled() && HOTSPOT_FANS_DESCRIBED.load(Ordering::Relaxed) +} fn cpu_balance_enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 4 != 0 } @@ -122,8 +147,10 @@ fn fan_boost_enabled() -> bool { fn fan_curve_enabled() -> bool { crate::module_parameters::m5_thermal_governor.value() & 16 == 0 } +/// Whether the governor work runs for a busy GPU: for the budget controller or the fan +/// assistance. pub(super) fn requested() -> bool { - enabled() + enabled() || hotspot_fans_only() } fn target_mc() -> i32 { let parameter = crate::module_parameters::m5_thermal_target_mc.value(); @@ -194,6 +221,11 @@ fn zone_temperature_mc(_provider: &SensorProvider, name: &CStr) -> Option { /// lookups and sensor reads may sleep. pub(crate) fn hotspot_temperature_mc() -> Option { let provider = SensorProvider::acquire()?; + if hotspot_fans_only() { + // The assistance reads only the input that selected it: the SoC die zone, whose one key + // is the hotspot. Without it the fans go back to the SMC. + return zone_temperature_mc(&provider, SOC_DIE_ZONE); + } zone_temperature_mc(&provider, J714_HOTSPOT_ZONE) .or_else(|| zone_temperature_mc(&provider, SOC_DIE_ZONE)) .or_else(|| { @@ -224,6 +256,8 @@ const FAN_CURVE_STEP_RPM: u32 = 150; /// Selects the board's thermal settings at probe; J714's until then. pub(crate) fn select_board(board: &super::fw::m5::initdata::Board) { FAN_CURVE_START_MC.store(board.fan_curve_start_mc, Ordering::Relaxed); + // SAFETY: a device tree lookup without arguments; called from probe, which may sleep. + HOTSPOT_FANS_DESCRIBED.store(unsafe { asahi_fans_hotspot_described() }, Ordering::Relaxed); } /// The permille of the fan range the curve asks for at hotspot `temp_mc`. @@ -247,18 +281,71 @@ fn fan_curve_permille(temp_mc: i32, target_mc: i32) -> i32 { /// serializes with its unbinding). A fan whose target is within `min_step_rpm` of the new one /// keeps it. Returns the first fan's target rpm, 0 once handed back. fn request_fans(permille: u32, min_step_rpm: u32) -> Option { - let provider = SensorProvider::acquire()?; + let Some(provider) = SensorProvider::acquire() else { + // Unbinding restores the provider's fans. + return (permille == 0).then_some(0); + }; // SAFETY: the provider lock keeps the device bound, as the request requires. let rpm = unsafe { asahi_fans_request(provider.0.cast(), permille, min_step_rpm) }; u32::try_from(rpm).ok() } +/// Machine-supplied hotspot fan-assistance thresholds read from the bound +/// macsmc-hwmon provider (`macsmc_soc_die` active trip temperature, release +/// temperature from its hysteresis, and minimum hold duration). +struct HotspotPolicy { + trigger_mc: i32, + release_mc: i32, + hold_ns: u64, +} + +fn hotspot_assist_policy() -> Option { + let provider = SensorProvider::acquire()?; + let (mut trigger_mc, mut release_mc, mut hold_ms): (c_int, c_int, c_uint) = (0, 0, 0); + // SAFETY: the provider lock keeps the device bound, and all output pointers are valid. + let ret = unsafe { + asahi_fans_hotspot_policy( + provider.0.cast(), + &mut trigger_mc, + &mut release_mc, + &mut hold_ms, + ) + }; + if ret != 0 || trigger_mc <= release_mc || hold_ms == 0 { + return None; + } + Some(HotspotPolicy { + trigger_mc, + release_mc, + hold_ns: u64::from(hold_ms) * 1_000_000, + }) +} + +/// [`request_fans`] for hotspot fan assistance: verifies the bound provider's +/// policy under its device lock and only drives fans marked with +/// `apple,fan-manual-control` in `macsmc-hwmon`. +fn request_fans_described(permille: u32, min_step_rpm: u32) -> Option { + let Some(provider) = SensorProvider::acquire() else { + // Unbinding restores the provider's fans. + return (permille == 0).then_some(0); + }; + // SAFETY: the provider lock keeps the device and its node bound, as the request requires. + let rpm = + unsafe { asahi_fans_request_described(provider.0.cast(), permille, min_step_rpm) }; + u32::try_from(rpm).ok() +} + /// Fan boost: while the governor limits the GPU, every fan runs at its hardware maximum instead of /// the SMC's automatic curve, which settles near two thirds of the maximum at the governor's /// target. /// Released (automatic mode) when the governor releases or the GPU goes idle, after a hold. pub(crate) struct FanBoost { - boosted: bool, + /// Budget-governor full boost (`request_fans`), active or retrying release. + budget_boosted: bool, + budget_release_pending: bool, + /// Hotspot-assistance boost (`request_fans_described`), active or retrying release. + hotspot_boosted: bool, + hotspot_release_pending: bool, since_ns: u64, /// The fan target the curve last wrote (rpm), 0 while the fans are automatic. curve_rpm: u32, @@ -266,7 +353,14 @@ pub(crate) struct FanBoost { impl FanBoost { const fn new() -> Self { - Self { boosted: false, since_ns: 0, curve_rpm: 0 } + Self { + budget_boosted: false, + budget_release_pending: false, + hotspot_boosted: false, + hotspot_release_pending: false, + since_ns: 0, + curve_rpm: 0, + } } /// Puts every fan in manual mode at `permille` of its minimum-to-maximum range, or back in @@ -283,6 +377,11 @@ impl FanBoost { // The target rpm moves with the range only when it moved enough. if let Some(rpm) = self.set_curve_if_moved(permille) { self.curve_rpm = rpm; + self.budget_release_pending = false; + } else if self.curve_rpm == 0 { + // Drop any partial first curve request and keep release pending + // until unrestricted cleanup succeeds. + self.budget_release_pending = !self.set_budget(false); } } else if self.curve_rpm != 0 && (!busy || temp_mc.is_none_or(|t| t < FAN_CURVE_RELEASE_MC)) @@ -299,46 +398,150 @@ impl FanBoost { request_fans(permille.clamp(1, 1000) as u32, step) } - fn set(&mut self, boost: bool) -> bool { + fn set_budget(&self, boost: bool) -> bool { request_fans(if boost { 1000 } else { 0 }, 0).is_some() } + fn set_hotspot(&self, boost: bool, step: u32) -> bool { + request_fans_described(if boost { 1000 } else { 0 }, step).is_some() + } + + fn release_budget(&mut self) -> bool { + if self.budget_boosted || self.budget_release_pending || self.curve_rpm != 0 { + let released = self.set_budget(false); + self.budget_release_pending = !released; + self.budget_boosted = false; + if released { + self.curve_rpm = 0; + } + } + !self.budget_boosted && !self.budget_release_pending && self.curve_rpm == 0 + } + + fn release_hotspot(&mut self) -> bool { + if self.hotspot_boosted || self.hotspot_release_pending { + self.hotspot_release_pending = !self.set_hotspot(false, 0); + self.hotspot_boosted = false; + } + !self.hotspot_boosted && !self.hotspot_release_pending + } + /// Applies one governor step's request. Called from the governor work without driver locks: /// SMC accesses sleep. fn apply(&mut self, want: bool, temp_mc: Option, now_ns: u64) { + if !enabled() { + // Explicit handoff: finish releasing any unrestricted budget-governor + // request before running or releasing manual-only hotspot assistance. + let had_budget = + self.budget_boosted || self.budget_release_pending || self.curve_rpm != 0; + if !self.release_budget() { + if !hotspot_fans_only() { + let _ = self.release_hotspot(); + } + return; + } + if had_budget { + self.since_ns = 0; + } + if !hotspot_fans_only() { + // The device tree describes no fans for it. + let _ = self.release_hotspot(); + return; + } + // Only ever request the SMC's rated maximum or release manual-control fans. + // Thresholds and hold duration come strictly from the bound + // macsmc-hwmon provider's device tree; without them assistance stays off. + if self.hotspot_release_pending { + let _ = self.release_hotspot(); + return; + } + let Some(policy) = hotspot_assist_policy() else { + let _ = self.release_hotspot(); + return; + }; + let threshold = if self.hotspot_boosted { + policy.release_mc + } else { + policy.trigger_mc + }; + if want && temp_mc.is_some_and(|temp| temp >= threshold) { + self.since_ns = now_ns; + // Requested on every busy, hot step, not only the first: a fan already at its + // rated speed for this policy is left alone, and one the SMC took back (the + // hwmon cell was unbound and bound again between two such steps, which restores + // automatic mode) is set again. Steps in the hold do not request. + let step = if self.hotspot_boosted { FAN_CURVE_STEP_RPM } else { 0 }; + self.hotspot_boosted = self.set_hotspot(true, step); + if !self.hotspot_boosted { + // No provider, or a later fan refused after an earlier one accepted. + // Drop any partial manual-only request before retrying on the next tick. + self.hotspot_release_pending = !self.set_hotspot(false, 0); + } + } else if self.hotspot_boosted + && (temp_mc.is_none() + || now_ns.saturating_sub(self.since_ns) >= policy.hold_ns) + { + // A lost hotspot reading ends the boost at once rather than after the hold: + // without the input that started it, the SMC's own policy owns the fans. A step + // that finds no provider (an unbound hwmon cell) reads no hotspot either, so a + // provider gap ends the boost the same way, and a new one starts at + // policy.trigger_mc. + let _ = self.release_hotspot(); + } + return; + } + // Explicit handoff: release any manual-only hotspot request before the + // budget governor takes unrestricted fan ownership. + let had_hotspot = self.hotspot_boosted || self.hotspot_release_pending; + if !self.release_hotspot() { + return; + } + if had_hotspot { + self.since_ns = 0; + } + if self.budget_release_pending && !(want && fan_boost_enabled()) && !self.release_budget() { + return; + } if !fan_boost_enabled() { if fan_curve_enabled() { self.apply_curve(want, temp_mc, target_mc(), now_ns); - } else if self.curve_rpm != 0 && self.set_curve(None).is_some() { - self.curve_rpm = 0; + } else if self.curve_rpm != 0 { + let _ = self.release_budget(); } } let want = want && fan_boost_enabled(); if want { self.since_ns = now_ns; } - if want && !self.boosted { - self.boosted = self.set(true); - } else if !want && self.boosted + if want && !self.budget_boosted { + self.budget_boosted = self.set_budget(true); + if self.budget_boosted { + self.budget_release_pending = false; + } else { + // Drop any partial unrestricted request and keep release pending + // until unrestricted cleanup succeeds. + self.budget_release_pending = !self.set_budget(false); + } + } else if !want + && self.budget_boosted && (!fan_boost_enabled() || now_ns.saturating_sub(self.since_ns) >= FAN_HOLD_NS) + && self.set_budget(false) { - if self.set(false) { - self.boosted = false; - } + self.budget_boosted = false; } } pub(crate) fn release(&mut self) { - if self.boosted && self.set(false) { - self.boosted = false; - } - if self.curve_rpm != 0 && self.set_curve(None).is_some() { - self.curve_rpm = 0; - } + let _ = self.release_budget(); + let _ = self.release_hotspot(); } pub(crate) fn boosted(&self) -> bool { - self.boosted || self.curve_rpm != 0 + self.budget_boosted + || self.budget_release_pending + || self.hotspot_boosted + || self.hotspot_release_pending + || self.curve_rpm != 0 } } @@ -679,10 +882,13 @@ impl Governor { } } + pub(super) fn recent_activity(&self, now_ns: u64) -> bool { + self.last_activity_ns != 0 && now_ns.saturating_sub(self.last_activity_ns) < IDLE_RESTORE_NS + } + /// Whether the fans should be boosted: while the controller governs a busy GPU. pub(crate) fn fans_wanted(&self, now_ns: u64) -> bool { - self.maximum_mw != 0 && self.active - && now_ns.saturating_sub(self.last_activity_ns) < IDLE_RESTORE_NS + self.maximum_mw != 0 && self.active && self.recent_activity(now_ns) } /// One control step with the hotspot temperature, the GPU's current draw (mW) and whether the diff --git a/tools/asahi/m5-hotspot-fans-dt-tests.py b/tools/asahi/m5-hotspot-fans-dt-tests.py new file mode 100644 index 00000000000000..91850204ac4558 --- /dev/null +++ b/tools/asahi/m5-hotspot-fans-dt-tests.py @@ -0,0 +1,917 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Check which device trees let the M5 hotspot fan assistance set fans. + +drivers/hwmon/macsmc-hwmon.c owns all apple,smc-hwmon DT binding knowledge: +- macsmc_hwmon_parse_fan_assist(): requires exactly one key in + apple,soc-die-keys (no hardcoded SMC key name) plus valid DT-supplied + apple,soc-die-fan-trip-millicelsius, apple,soc-die-fan-hysteresis-millicelsius, + and apple,soc-die-fan-hold-ms. +- macsmc_hwmon_hotspot_assist_available(): checks whether an available + apple,smc-hwmon node (with all parents available) carries that policy and + at least one settable fan with apple,fan-manual-control. +- macsmc_hwmon_fans_request_manual(): drives only fans marked with + apple,fan-manual-control, leaving closed siblings untouched. +- drivers/gpu/drm/asahi/g17/fans.c: asahi_fans_request_described() gates + boost requests on macsmc_hwmon_hotspot_assist_policy() and delegates to + macsmc_hwmon_fans_request_manual(). + +This compiles the real functions from drivers/hwmon/macsmc-hwmon.c and +drivers/gpu/drm/asahi/g17/fans.c against libfdt and runs them on synthetic +trees and the T6050 board trees, including J716c without #2208, with #2208 +alone (no trip properties -> must stay off), and with #2208 plus trip +properties, and also compiles FanBoost from drivers/gpu/drm/asahi/g17/thermal.rs +with rustc to test partial budget/hotspot request failure and handoff cleanup. +--mutation drops one condition, which a case must catch. +""" + +import argparse +import os +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] + +HWMON_FIRST = "static bool macsmc_hwmon_fan_settable(const struct device_node *fan)" +HWMON_LAST = "EXPORT_SYMBOL_GPL(macsmc_hwmon_hotspot_assist_available);" +FANS_FIRST = "int asahi_fans_request_described(struct device *dev, unsigned int permille," + +# Board trees: the exact fans the request may write there, or None when the tree +# does not select the assistance. +BOARDS = { + "t6050-j714s": None, + "t6050-j716s": None, + "t6050-j775d": None, +} +J716C_FANS = ["fan-F0Ac", "fan-F1Ac"] + +# J716c #2208 description without active trip properties (must stay off). +J716C_2208_NO_TRIP = """ +#include "hwmon-fan-dual.dtsi" +&smc_hwmon { + status = "okay"; + fan-F0Ac { apple,fan-mode = "F0md"; apple,fan-manual-control; }; + fan-F1Ac { apple,fan-mode = "F1md"; apple,fan-manual-control; }; +}; +""" + +# J716c #2208 description with active trip properties on macsmc_soc_die. +J716C_2208_WITH_TRIP = """ +#include "hwmon-fan-dual.dtsi" +&smc_hwmon { + status = "okay"; + apple,soc-die-fan-trip-millicelsius = <98000>; + apple,soc-die-fan-hysteresis-millicelsius = <16000>; + apple,soc-die-fan-hold-ms = <30000>; + fan-F0Ac { apple,fan-mode = "F0md"; apple,fan-manual-control; }; + fan-F1Ac { apple,fan-mode = "F1md"; apple,fan-manual-control; }; +}; +""" + +KEYS = ('apple,key-id = "F{n}Ac"; apple,fan-minimum = "F{n}Mn"; apple,fan-maximum = "F{n}Mx"; ' + 'apple,fan-target = "F{n}Tg"; ') +MODE = KEYS + 'apple,fan-mode = "F{n}md"; ' +MANUAL = "apple,fan-manual-control;" +TRIP = ('apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; ' + 'apple,soc-die-fan-hold-ms = <30000>;') +DIE_TCMB = 'apple,soc-die-keys = "TCMb"; ' + TRIP +DIE_OTHER = 'apple,soc-die-keys = "Tg0D"; ' + TRIP + +# name: (hwmon properties, [per-fan properties], fans written or None, expected policy or None) +SYNTHETIC = { + "both": (DIE_TCMB, [MODE + MANUAL, MODE + MANUAL], ["fan-F0Ac", "fan-F1Ac"], (98000, 82000, 30000)), + "one-fan": (DIE_TCMB, [MODE + MANUAL], ["fan-F0Ac"], (98000, 82000, 30000)), + # Any single SoC die key works (no hardcoded TCMb key name in driver). + "other-single-die-key": (DIE_OTHER, [MODE + MANUAL], ["fan-F0Ac"], (98000, 82000, 30000)), + # Manual-only request writes only fans with apple,fan-manual-control; closed siblings stay untouched. + "manual-and-monitor-only": (DIE_TCMB, [MODE + MANUAL, KEYS], ["fan-F0Ac"], (98000, 82000, 30000)), + "second-fan-only": (DIE_TCMB, [MODE, MODE + MANUAL], ["fan-F1Ac"], (98000, 82000, 30000)), + "first-fan-only": (DIE_TCMB, [MODE + MANUAL, MODE], ["fan-F0Ac"], (98000, 82000, 30000)), + # Opened, but without the keys to set it: nothing the request could write. + "manual-without-keys": (DIE_TCMB, ['apple,fan-mode = "F{n}md"; ' + MANUAL], None, None), + "manual-without-mode": (DIE_TCMB, [KEYS + MANUAL], None, None), + "no-manual-fan": (DIE_TCMB, [MODE], None, None), + "no-fans": (DIE_TCMB, [], None, None), + # Missing or invalid SoC die key list. + "no-die-zone": (TRIP, [MODE + MANUAL], None, None), + "die-zone-of-several": ('apple,soc-die-keys = "TCMb", "Tg0D"; ' + TRIP, [MODE + MANUAL], None, None), + "temperature-node-only": (TRIP + ' temperature-TCMb { apple,key-id = "TCMb"; };', + [MODE + MANUAL], None, None), + # Missing or invalid DT trip / hysteresis / hold properties (must stay off, no hardcoded fallback). + "no-trip": ('apple,soc-die-keys = "TCMb";', [MODE + MANUAL], None, None), + "missing-hyst": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hold-ms = <30000>;', [MODE + MANUAL], None, None), + "missing-hold": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>;', [MODE + MANUAL], None, None), + "zero-hyst": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <0>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "hyst-ge-trip": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <98000>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "trip-too-high": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <160000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; apple,soc-die-fan-hold-ms = <30000>;', + [MODE + MANUAL], None, None), + "zero-hold": ('apple,soc-die-keys = "TCMb"; apple,soc-die-fan-trip-millicelsius = <98000>; ' + 'apple,soc-die-fan-hysteresis-millicelsius = <16000>; apple,soc-die-fan-hold-ms = <0>;', + [MODE + MANUAL], None, None), +} + +HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include "libfdt.h" + +typedef uint32_t u32; +#define MACSMC_DIE_MAX_MC 150000 +#define EXPORT_SYMBOL_GPL(sym) + +struct macsmc_hwmon_fan_assist { + int trigger_mc; + int release_mc; + unsigned int hold_ms; +}; + +static const void *blob; +struct device_node { int offset; }; +struct device { struct device_node *of_node; }; + +static void free_node(struct device_node **node) { free(*node); } +#define __free(kind) __attribute__((cleanup(free_node))) + +static struct device_node *node_at(int offset) +{ + struct device_node *node = malloc(sizeof(*node)); + if (!node) + abort(); + node->offset = offset; + return node; +} + +static struct device_node *of_node_get(struct device_node *np) +{ + return np ? node_at(np->offset) : NULL; +} + +static void of_node_put(struct device_node *np) +{ + free(np); +} + +static struct device_node *of_get_parent(const struct device_node *np) +{ + int offset = fdt_parent_offset(blob, np->offset); + + return offset < 0 ? NULL : node_at(offset); +} + +static struct device_node *of_get_next_child_with_prefix(const struct device_node *parent, + struct device_node *prev, const char *prefix) +{ + int offset = prev ? fdt_next_subnode(blob, prev->offset) + : fdt_first_subnode(blob, parent->offset); + free(prev); + for (; offset >= 0; offset = fdt_next_subnode(blob, offset)) + if (!strncmp(fdt_get_name(blob, offset, NULL), prefix, strlen(prefix))) + return node_at(offset); + return NULL; +} + +#define for_each_child_of_node_with_prefix(parent, child, prefix) \ + for (struct device_node *child __free(device_node) = \ + of_get_next_child_with_prefix(parent, NULL, prefix); \ + child != NULL; \ + child = of_get_next_child_with_prefix(parent, child, prefix)) + +static struct device_node *of_find_compatible_node(struct device_node *from, const char *type, + const char *compatible) +{ + int offset = fdt_node_offset_by_compatible(blob, from ? from->offset : -1, compatible); + + (void)type; + free(from); + return offset < 0 ? NULL : node_at(offset); +} + +#define for_each_compatible_node(dn, type, compatible) \ + for (dn = of_find_compatible_node(NULL, type, compatible); dn; \ + dn = of_find_compatible_node(dn, type, compatible)) + +static bool of_device_is_available(const struct device_node *np) +{ + const char *status = fdt_getprop(blob, np->offset, "status", NULL); + + return !status || !strcmp(status, "okay") || !strcmp(status, "ok"); +} + +static bool of_property_read_bool(const struct device_node *np, const char *name) +{ + return fdt_getprop(blob, np->offset, name, NULL) != NULL; +} + +static bool of_property_present(const struct device_node *np, const char *name) +{ + return of_property_read_bool(np, name); +} + +static int of_property_count_strings(const struct device_node *np, const char *name) +{ + return fdt_stringlist_count(blob, np->offset, name); +} + +static int of_property_read_u32(const struct device_node *np, const char *name, u32 *out) +{ + int len; + const fdt32_t *val = fdt_getprop(blob, np->offset, name, &len); + + if (!val || len != 4) + return -EINVAL; + *out = fdt32_to_cpu(*val); + return 0; +} + +HWMON_BODY + +static int macsmc_hwmon_hotspot_assist_policy(struct device *dev, + struct macsmc_hwmon_fan_assist *policy) +{ + if (!dev || !dev->of_node) + return -ENODEV; + return macsmc_hwmon_node_hotspot_assist(dev->of_node, policy) ? 0 : -ENODEV; +} + +/* + * Stand-in for macsmc_hwmon_fans_request_manual(): models the real manual_only + * filter in drivers/hwmon/macsmc-hwmon.c (verified by assertion in extract()). + */ +static int requests; +static int macsmc_hwmon_fans_request_manual(struct device *dev, unsigned int permille, + unsigned int min_step_rpm) +{ + int fan; + int count = 0; + + (void)permille; + (void)min_step_rpm; + requests++; + fdt_for_each_subnode(fan, blob, dev->of_node->offset) { + const char *name = fdt_get_name(blob, fan, NULL); + bool manual = fdt_getprop(blob, fan, "apple,fan-manual-control", NULL) != NULL; + + if (strncmp(name, "fan-", 4) || + !fdt_getprop(blob, fan, "apple,fan-mode", NULL) || + !fdt_getprop(blob, fan, "apple,fan-target", NULL) || + !fdt_getprop(blob, fan, "apple,fan-minimum", NULL) || + !fdt_getprop(blob, fan, "apple,fan-maximum", NULL)) + continue; + if (MANUAL_FILTER) + continue; + printf(" %s=%s", name, manual ? "manual" : "closed"); + count++; + } + return count ? 5000 : -ENODEV; +} + +FANS_BODY + +int main(int argc, char **argv) +{ + static char buffer[1 << 22]; + FILE *file = fopen(argv[1], "rb"); + int hwmon; + + if (argc != 2 || !file || fread(buffer, 1, sizeof(buffer), file) == 0) + return 2; + blob = buffer; + printf("%s\n", macsmc_hwmon_hotspot_assist_available() ? "governs" : "idle"); + for (hwmon = fdt_node_offset_by_compatible(blob, -1, "apple,smc-hwmon"); hwmon >= 0; + hwmon = fdt_node_offset_by_compatible(blob, hwmon, "apple,smc-hwmon")) { + char path[256]; + struct device_node node = { .offset = hwmon }; + struct device dev = { .of_node = &node }; + struct macsmc_hwmon_fan_assist policy = {}; + int pret, ret; + + fdt_get_path(blob, hwmon, path, sizeof(path)); + printf("%s", path); + pret = macsmc_hwmon_hotspot_assist_policy(&dev, &policy); + requests = 0; + ret = asahi_fans_request_described(&dev, 1000, 0); + if (ret < 0) + printf(" refused\n"); + else if (pret == 0) + printf(" policy=%d,%d,%u accepted\n", + policy.trigger_mc, policy.release_mc, policy.hold_ms); + else + printf(" policy=none accepted\n"); + } + return 0; +} +""" + + +def extract(tree, mutation): + hwmon_src = (tree / "drivers/hwmon/macsmc-hwmon.c").read_text() + fans_src = (tree / "drivers/gpu/drm/asahi/g17/fans.c").read_text() + + # Verify the GPU driver no longer hardcodes TCMb or walks macsmc-hwmon DT bindings. + assert '"TCMb"' not in fans_src, "fans.c must not name an SMC key" + assert '"apple,fan-manual-control"' not in fans_src, "fans.c must not walk macsmc-hwmon DT" + assert '"apple,soc-die-keys"' not in fans_src, "fans.c must not walk macsmc-hwmon DT" + # Verify macsmc-hwmon.c actually applies the manual_only filter in __macsmc_hwmon_fans_request. + assert "if (manual_only && !fan->manual_control)\n\t\t\tcontinue;" in hwmon_src + + h_start = hwmon_src.index(HWMON_FIRST) + h_end = hwmon_src.index(HWMON_LAST, h_start) + len(HWMON_LAST) + hwmon_body = hwmon_src[h_start:h_end] + + f_start = fans_src.index(FANS_FIRST) + f_end = fans_src.index("\n}\n", f_start) + 3 + fans_body = fans_src[f_start:f_end] + + manual_filter = "!manual" + + if mutation == "drop-fans": + hwmon_body, n = re.subn( + r'of_property_read_bool\(child, "apple,fan-manual-control"\)', + "true", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + manual_filter = "false" + elif mutation == "drop-siblings": + manual_filter = "false" + elif mutation == "drop-hotspot": + hwmon_body, n = re.subn( + r'of_property_count_strings\(np, "apple,soc-die-keys"\) != 1', + "false", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-trip": + hwmon_body, n = re.subn( + r'if \(of_property_read_u32\(np, "apple,soc-die-fan-trip-millicelsius", &trip\) \|\|\n' + r'\s*of_property_read_u32\(np, "apple,soc-die-fan-hysteresis-millicelsius", &hyst\) \|\|\n' + r'\s*of_property_read_u32\(np, "apple,soc-die-fan-hold-ms", &hold_ms\)\)\n' + r'\s*return false;', + "trip = 98000; hyst = 16000; hold_ms = 30000;", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-settable": + hwmon_body, n = re.subn( + r'macsmc_hwmon_fan_settable\(child\)', + "true", + hwmon_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + elif mutation == "drop-provider-check": + fans_body, n = re.subn( + r'if \(permille && macsmc_hwmon_hotspot_assist_policy\(dev, NULL\)\)\n\s*return -EPERM;\n', + "", + fans_body, + ) + assert n == 1, f"mutation {mutation} did not apply" + return hwmon_body, fans_body, manual_filter + + +RUST_HARNESS = r""" +#![allow(dead_code)] + +use std::sync::Mutex; + +const FAN_HOLD_NS: u64 = 30_000_000_000; +const FAN_CURVE_RELEASE_MC: i32 = 82_000; +const FAN_CURVE_STEP_RPM: u32 = 150; + +#[derive(Clone, Copy)] +struct HotspotPolicy { + trigger_mc: i32, + release_mc: i32, + hold_ns: u64, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum FanCall { + Budget(u32, u32), + Hotspot(u32, u32), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReqMode { + Ok, + PartialFail, +} + +struct MockState { + enabled: bool, + hotspot_fans_only: bool, + fan_boost_enabled: bool, + fan_curve_enabled: bool, + budget_req: ReqMode, + budget_rel_ok: bool, + hotspot_req: ReqMode, + hotspot_rel_ok: bool, + budget_owned_mask: u32, + hotspot_owned_mask: u32, + calls: Vec, +} + +impl MockState { + const fn new() -> Self { + Self { + enabled: false, + hotspot_fans_only: false, + fan_boost_enabled: false, + fan_curve_enabled: true, + budget_req: ReqMode::Ok, + budget_rel_ok: true, + hotspot_req: ReqMode::Ok, + hotspot_rel_ok: true, + budget_owned_mask: 0, + hotspot_owned_mask: 0, + calls: Vec::new(), + } + } + + fn reset(&mut self) { + *self = Self::new(); + } +} + +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static MOCK: Mutex = Mutex::new(MockState::new()); + +fn enabled() -> bool { + MOCK.lock().unwrap().enabled +} + +fn hotspot_fans_only() -> bool { + let s = MOCK.lock().unwrap(); + !s.enabled && s.hotspot_fans_only +} + +fn fan_boost_enabled() -> bool { + MOCK.lock().unwrap().fan_boost_enabled +} + +fn fan_curve_enabled() -> bool { + MOCK.lock().unwrap().fan_curve_enabled +} + +fn target_mc() -> i32 { + 90_000 +} + +fn fan_curve_permille(temp_mc: i32, target_mc: i32) -> i32 { + if temp_mc <= 70_000 { + 0 + } else if temp_mc <= target_mc { + (temp_mc - 70_000) * 660 / (target_mc - 70_000).max(1000) + } else { + 800 + } +} + +fn hotspot_assist_policy() -> Option { + Some(HotspotPolicy { + trigger_mc: 98_000, + release_mc: 82_000, + hold_ns: 30_000_000_000, + }) +} + +fn request_fans(permille: u32, min_step_rpm: u32) -> Option { + let mut s = MOCK.lock().unwrap(); + s.calls.push(FanCall::Budget(permille, min_step_rpm)); + if permille == 0 { + if s.budget_rel_ok { + s.budget_owned_mask = 0; + Some(0) + } else { + None + } + } else { + match s.budget_req { + ReqMode::Ok => { + s.budget_owned_mask = 0b11; + Some(5000) + } + ReqMode::PartialFail => { + s.budget_owned_mask |= 0b01; + None + } + } + } +} + +fn request_fans_described(permille: u32, min_step_rpm: u32) -> Option { + let mut s = MOCK.lock().unwrap(); + s.calls.push(FanCall::Hotspot(permille, min_step_rpm)); + if permille == 0 { + if s.hotspot_rel_ok { + s.hotspot_owned_mask = 0; + Some(0) + } else { + None + } + } else { + match s.hotspot_req { + ReqMode::Ok => { + s.hotspot_owned_mask = 0b11; + Some(5000) + } + ReqMode::PartialFail => { + s.hotspot_owned_mask |= 0b01; + None + } + } + } +} + +FAN_BOOST_BODY + +fn take_calls() -> Vec { + core::mem::take(&mut MOCK.lock().unwrap().calls) +} + +#[test] +fn partial_budget_boost_failure_cleans_up_and_blocks_handoff_until_released() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = true; + s.fan_boost_enabled = true; + s.hotspot_fans_only = true; + s.budget_req = ReqMode::PartialFail; + s.budget_rel_ok = true; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(95_000), 1_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(1000, 0), FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0); + assert!(!fans.boosted()); + + // Now fail both the partial budget boost and its immediate cleanup; verify + // handoff keeps retrying unrestricted cleanup and blocks hotspot assist until + // cleanup succeeds. + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = false; + } + fans.apply(true, Some(95_000), 2_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(1000, 0), FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = false; + } + fans.apply(true, Some(99_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0b01); + assert_eq!(s.hotspot_owned_mask, 0); + } + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = true; + } + fans.apply(true, Some(99_000), 4_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0), FanCall::Hotspot(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0); + assert_eq!(s.hotspot_owned_mask, 0b11); + } + assert!(fans.boosted()); + fans.release(); +} + +#[test] +fn partial_first_curve_request_failure_cleans_up_and_blocks_handoff_until_released() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = true; + s.fan_boost_enabled = false; + s.fan_curve_enabled = true; + s.hotspot_fans_only = true; + s.budget_req = ReqMode::PartialFail; + s.budget_rel_ok = true; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(95_000), 1_000_000_000); + let calls = take_calls(); + assert_eq!(calls.len(), 2); + assert!(matches!(calls[0], FanCall::Budget(p, 0) if p > 0)); + assert_eq!(calls[1], FanCall::Budget(0, 0)); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0); + assert!(!fans.boosted()); + + // Fail immediate cleanup after partial first curve request, then verify both + // a subsequent budget-mode step and handoff retry unrestricted cleanup first. + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = false; + } + fans.apply(true, Some(95_000), 2_000_000_000); + let calls = take_calls(); + assert_eq!(calls.len(), 2); + assert!(matches!(calls[0], FanCall::Budget(p, 0) if p > 0)); + assert_eq!(calls[1], FanCall::Budget(0, 0)); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + fans.apply(true, Some(95_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + assert_eq!(MOCK.lock().unwrap().budget_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = false; + } + fans.apply(true, Some(99_000), 4_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0b01); + assert_eq!(s.hotspot_owned_mask, 0); + } + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.budget_rel_ok = true; + } + fans.apply(true, Some(99_000), 5_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Budget(0, 0), FanCall::Hotspot(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.budget_owned_mask, 0); + assert_eq!(s.hotspot_owned_mask, 0b11); + } + assert!(fans.boosted()); + fans.release(); +} + +#[test] +fn partial_hotspot_failure_blocks_budget_handoff_until_manual_cleanup_succeeds() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut s = MOCK.lock().unwrap(); + s.reset(); + s.enabled = false; + s.hotspot_fans_only = true; + s.hotspot_req = ReqMode::PartialFail; + s.hotspot_rel_ok = false; + } + + let mut fans = FanBoost::new(); + fans.apply(true, Some(99_000), 1_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(1000, 0), FanCall::Hotspot(0, 0)]); + assert_eq!(MOCK.lock().unwrap().hotspot_owned_mask, 0b01); + assert!(fans.boosted()); + + { + let mut s = MOCK.lock().unwrap(); + s.enabled = true; + s.fan_boost_enabled = true; + } + fans.apply(true, Some(95_000), 2_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(0, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.hotspot_owned_mask, 0b01); + assert_eq!(s.budget_owned_mask, 0); + } + + { + let mut s = MOCK.lock().unwrap(); + s.hotspot_rel_ok = true; + } + fans.apply(true, Some(95_000), 3_000_000_000); + assert_eq!(take_calls(), vec![FanCall::Hotspot(0, 0), FanCall::Budget(1000, 0)]); + { + let s = MOCK.lock().unwrap(); + assert_eq!(s.hotspot_owned_mask, 0); + assert_eq!(s.budget_owned_mask, 0b11); + } + fans.release(); +} +""" + + +def extract_fan_boost(tree, mutation): + thermal_src = (tree / "drivers/gpu/drm/asahi/g17/thermal.rs").read_text() + start = thermal_src.index("pub(crate) struct FanBoost {") + end_marker = "impl Drop for FanBoost {\n fn drop(&mut self) {\n self.release();\n }\n}" + end = thermal_src.index(end_marker, start) + len(end_marker) + body = thermal_src[start:end] + + if mutation == "drop-budget-release-pending": + body, n1 = re.subn( + r'if let Some\(rpm\) = self\.set_curve_if_moved\(permille\) \{\n' + r'\s*self\.curve_rpm = rpm;\n' + r'\s*self\.budget_release_pending = false;\n' + r'\s*\} else if self\.curve_rpm == 0 \{\n' + r'(?:\s*//[^\n]*\n)*' + r'\s*self\.budget_release_pending = !self\.set_budget\(false\);\n' + r'\s*\}', + 'if let Some(rpm) = self.set_curve_if_moved(permille) {\n self.curve_rpm = rpm;\n }', + body, + ) + assert n1 == 1, f"mutation {mutation} curve replace failed ({n1})" + body, n2 = re.subn( + r'if self\.budget_boosted \{\n' + r'\s*self\.budget_release_pending = false;\n' + r'\s*\} else \{\n' + r'(?:\s*//[^\n]*\n)*' + r'\s*self\.budget_release_pending = !self\.set_budget\(false\);\n' + r'\s*\}', + 'if self.budget_boosted {\n self.budget_release_pending = false;\n }', + body, + ) + assert n2 == 1, f"mutation {mutation} boost replace failed ({n2})" + return body + + +def run_fan_boost_tests(tree, output, mutation): + body = extract_fan_boost(tree, mutation) + src = output / "fan_boost_test.rs" + binary = output / "fan_boost_test" + src.write_text(RUST_HARNESS.replace("FAN_BOOST_BODY", body)) + rustc = os.environ.get("RUSTC", "rustc") + subprocess.run([rustc, "--edition=2021", "--test", "-Dwarnings", str(src), "-o", str(binary)], + check=True) + res = subprocess.run([str(binary)], capture_output=True, text=True) + if res.stdout: + print(res.stdout, end="") + if res.stderr: + print(res.stderr, end="", file=sys.stderr) + return res.returncode == 0 + + +def build(tree, output, mutation): + libfdt = tree / "scripts/dtc/libfdt" + hwmon_body, fans_body, manual_filter = extract(tree, mutation) + harness = output / "harness.c" + code = (HARNESS + .replace("HWMON_BODY", hwmon_body) + .replace("FANS_BODY", fans_body) + .replace("MANUAL_FILTER", manual_filter)) + harness.write_text(code) + binary = output / "harness" + sources = [libfdt / f for f in ("fdt.c", "fdt_ro.c", "fdt_strerror.c")] + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Werror", "-Wno-unused-function", + "-I", str(libfdt), "-o", str(binary), str(harness)] + [str(s) for s in sources], + check=True) + return binary + + +def run(binary, dtb): + """Returns (governs, {provider path: (written fans, policy_str) or None when refused}).""" + lines = subprocess.check_output([str(binary), str(dtb)], text=True).splitlines() + providers = {} + for line in lines[1:]: + path, *rest = line.split() + verdict = rest[-1] + if verdict != "accepted": + providers[path] = None + else: + policy_tok = rest[-2] + assert policy_tok.startswith("policy="), line + providers[path] = (rest[:-2], policy_tok.split("=", 1)[1]) + return lines[0] == "governs", providers + + +def dtc_compile(dtc, source, dtb): + subprocess.run([dtc, "-q", "-I", "dts", "-O", "dtb", "-o", str(dtb)], input=source, check=True) + + +def compile_board(tree, output, dtc, board, extra="", suffix=""): + apple = tree / "arch/arm64/boot/dts/apple" + source = (apple / f"{board}.dts").read_text() + extra + command = ["cpp", "-nostdinc", "-undef", "-D__DTS__", + "-I", str(tree / "scripts/dtc/include-prefixes"), "-I", str(apple), + "-x", "assembler-with-cpp", "-"] + dtb = output / f"{board}{suffix}.dtb" + dtc_compile(dtc, subprocess.check_output(command, input=source.encode(), cwd=apple), dtb) + return dtb + + +def hwmon_node(name, zone, fans, status=""): + nodes = "".join(f"\t\tfan-F{n}Ac {{ {props.format(n=n)} }};\n" for n, props in enumerate(fans)) + return (f"\t{name} {{ {status} hwmon {{ compatible = \"apple,smc-hwmon\";\n" + f"\t\t{zone}\n{nodes}\t}}; }};\n") + + +def compile_synthetic(output, dtc, name, nodes): + dtb = output / f"synthetic-{name}.dtb" + dtc_compile(dtc, ("/dts-v1/;\n/ {\n" + nodes + "};\n").encode(), dtb) + return dtb + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tree", type=Path, default=ROOT) + parser.add_argument("--dtc", required=True, help="this kernel's built scripts/dtc/dtc") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mutation", choices=("drop-fans", "drop-siblings", "drop-hotspot", + "drop-trip", "drop-settable", "drop-provider-check", + "drop-budget-release-pending")) + args = parser.parse_args() + tree = args.tree.resolve() + args.output.mkdir(parents=True, exist_ok=True) + failures = 0 + + if args.mutation != "drop-budget-release-pending": + binary = build(tree, args.output, args.mutation) + + def check(label, dtb, want, want_policy=None, governs=None): + """want: {provider path suffix: exact fans written, or None when refused}.""" + nonlocal failures + got_governs, providers = run(binary, dtb) + if governs is None: + governs = any(fans for fans in want.values()) + problems = [] + if got_governs != governs: + problems.append(f"governs {got_governs}, expected {governs}") + for suffix in want: + if not any(path.endswith(suffix) for path in providers): + problems.append(f"no provider ending in {suffix} was reported") + for path, res in providers.items(): + expected = next((fans for suffix, fans in want.items() if path.endswith(suffix)), None) + written = None if res is None else res[0] + pol = None if res is None else res[1] + names = None if written is None else [w.split("=")[0] for w in written] + if written is not None and (not written or any(w.endswith("=closed") for w in written)): + problems.append(f"{path} accepted and writes {written or 'no fan'}") + if names != expected: + problems.append(f"{path} writes {names}, expected {expected}") + if want_policy is not None and expected is not None: + want_str = f"{want_policy[0]},{want_policy[1]},{want_policy[2]}" + if pol != want_str: + problems.append(f"{path} policy {pol}, expected {want_str}") + if problems: + failures += 1 + print(f"FAIL line {sys._getframe(1).f_lineno}: {label}: {'; '.join(problems)}") + else: + print(f"ok {label}: {'governs' if got_governs else 'idle'} {providers}") + + if args.mutation != "drop-budget-release-pending": + for name, (zone, fans, written, pol) in SYNTHETIC.items(): + check(f"synthetic {name}", + compile_synthetic(args.output, args.dtc, name, hwmon_node("smc", zone, fans)), + {"/smc/hwmon": written}, want_policy=pol) + check("synthetic opted-in-under-disabled-parent", + compile_synthetic(args.output, args.dtc, "disabled-parent", + hwmon_node("smc0", DIE_TCMB, [MODE + MANUAL], 'status = "disabled";') + + hwmon_node("smc1", DIE_TCMB, [MODE])), + {"/smc0/hwmon": ["fan-F0Ac"], "/smc1/hwmon": None}, governs=False) + check("synthetic disabled-hwmon-node", + compile_synthetic(args.output, args.dtc, "disabled-node", + hwmon_node("smc", DIE_TCMB + ' status = "disabled";', [MODE + MANUAL])), + {"/hwmon": ["fan-F0Ac"]}, governs=False) + for board, written in BOARDS.items(): + check(board, compile_board(tree, args.output, args.dtc, board), {"/hwmon": written}) + + j716c_dts = (tree / "arch/arm64/boot/dts/apple/t6050-j716c.dts").read_text() + has_2208 = "hwmon-fan-dual.dtsi" in j716c_dts + has_trip = "apple,soc-die-fan-trip-millicelsius" in j716c_dts + check("t6050-j716c (in-tree)", + compile_board(tree, args.output, args.dtc, "t6050-j716c"), + {"/hwmon": J716C_FANS if (has_2208 and has_trip) else None}) + if not has_2208: + check("t6050-j716c with #2208 (no trip -> stays off)", + compile_board(tree, args.output, args.dtc, "t6050-j716c", J716C_2208_NO_TRIP, "-2208-notrip"), + {"/hwmon": None}) + check("t6050-j716c with #2208 + DT trip", + compile_board(tree, args.output, args.dtc, "t6050-j716c", J716C_2208_WITH_TRIP, "-2208-trip"), + {"/hwmon": J716C_FANS}, want_policy=(98000, 82000, 30000)) + if args.mutation in (None, "drop-budget-release-pending"): + if not run_fan_boost_tests(tree, args.output, args.mutation): + failures += 1 + if failures: + raise SystemExit(1) + print("PASS") + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 326dccb7b85730..deaa2bdbf9d91d 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -251,6 +251,14 @@ def mutations(flag, names, base, expect=KILL): 'isp-preview-flow-tests.py': [([], PASS)], 'isp-preview-tests.py': [([], PASS)], 'isp-tests.py': [(['--suite', suite] + out(), PASS) for suite in ['session', 'buffers', 'receive', 'returns', 'queue']] + [(['--suite', suite, '--control', control] + out(), KILL) for suite, controls in [('session', ['send', 'overwrite', 'stop', 'reset']), ('buffers', ['rollback']), ('receive', ['drain']), ('returns', ['address', 'pool', 'duplicate', 'snapshot']), ('queue', ['queue-error'])] for control in controls], + 'm5-hotspot-fans-dt-tests.py': [(out('--output') + ['--dtc', '{dtc}'], PASS), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-fans'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-siblings'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-hotspot'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-trip'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-settable'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-provider-check'], KILL), + (out('--output') + ['--dtc', '{dtc}', '--mutation', 'drop-budget-release-pending'], KILL)], 'mt7932-association-events-tests.py': [(out(), PASS)], 'mt7932-connect-result-tests.py': [(out('--output'), PASS)], 'mt7932-owe-retry-tests.py': [(out(), PASS)], From f7dc93cbbf5c737b1340c42320a06c92a52b573d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:05:25 -0500 Subject: [PATCH 0694/1514] usb: typec: tipd: sn201202x: retry the select of a waking controller sooner While a sleeping SN201202x controller wakes up, a register selection sent before it is ready is never confirmed. sn201202x_wake_poll() called regmap_sn201202x_select_reg(), which waits a full 100 ms per attempt before timing out and letting the wake loop retry; a single early attempt therefore added ~100 ms to every waking controller on resume. Split out sn201202x_select_reg() with an explicit timeout parameter, keep the 100 ms timeout for normal register selections, and use a 5 ms timeout while polling a waking controller so retries happen 20x sooner without changing the overall wake budget. Signed-off-by: Satya Benson --- drivers/usb/typec/tipd/spmi.c | 43 ++++++++++++++----- .../drivers/apple/sn201202x-transport.py | 6 ++- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/drivers/usb/typec/tipd/spmi.c b/drivers/usb/typec/tipd/spmi.c index 35314ddce15ea2..44e574400b6ec8 100644 --- a/drivers/usb/typec/tipd/spmi.c +++ b/drivers/usb/typec/tipd/spmi.c @@ -18,6 +18,13 @@ #define tps_to_sn(tps) container_of_const((tps), struct sn201202x, cd.tps) +/* How long a register selection may take to be confirmed. */ +#define SN201202X_SELECT_TIMEOUT_US 100000 +/* + * The same while the controller wakes up: a selection sent before it is + * awake is never confirmed, so sn201202x_wake_poll() retries after this. + */ +#define SN201202X_WAKE_SELECT_TIMEOUT_US 5000 /* A sleeping controller does not answer a select; give up on it sooner. */ #define SN201202X_ATOMIC_SELECT_MS 10 @@ -34,7 +41,8 @@ #define SN201202X_LDCM_RESULT GENMASK(5, 4) #define SN201202X_LDCM_RETRY_MS 500 -static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) +static int sn201202x_select_reg(struct spmi_device *sdev, u8 reg, + unsigned int timeout_us) { int err; u8 val; @@ -55,19 +63,23 @@ static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) if (sn->polled || sn->select_polled) { int poll_err; - if (sn->atomic) + if (sn->atomic) { + unsigned int atomic_us = min_t(unsigned int, timeout_us, + SN201202X_ATOMIC_SELECT_MS * 1000); + poll_err = read_poll_timeout_atomic(spmi_register_read, err, err || val == reg, 100, - SN201202X_ATOMIC_SELECT_MS * 1000, - false, sdev, 0, &val); - else + atomic_us, false, sdev, 0, &val); + } else { poll_err = read_poll_timeout(spmi_register_read, err, - err || val == reg, 100, 100000, + err || val == reg, 100, timeout_us, false, sdev, 0, &val); + } return err ?: poll_err; } - if (!wait_for_completion_timeout(&sn->select_completion, msecs_to_jiffies(100))) + if (!wait_for_completion_timeout(&sn->select_completion, + max(1UL, usecs_to_jiffies(timeout_us)))) return -ETIMEDOUT; while (--attempts) { @@ -91,6 +103,11 @@ static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) return -EIO; } +static int regmap_sn201202x_select_reg(struct spmi_device *sdev, u8 reg) +{ + return sn201202x_select_reg(sdev, reg, SN201202X_SELECT_TIMEOUT_US); +} + static int __regmap_sn201202x_read(void *context, const void *reg, size_t reg_size, void *val, size_t val_size) @@ -580,7 +597,12 @@ static int sn201202x_wake_poll(struct sn201202x *sn, bool poll) msecs_to_jiffies(100))) return 0; - /* A sleeping ACE3 ACKs commands but returns zeros until it is awake. */ + /* + * A sleeping ACE3 ACKs commands but returns zeros until it is awake, + * and does not confirm a register selection sent before then. Retry + * the selection after a few ms instead of waiting the full awake + * selection timeout on every polled wake. + */ deadline = jiffies + msecs_to_jiffies(500); do { if (++tries % 20 == 0) { @@ -588,9 +610,10 @@ static int sn201202x_wake_poll(struct sn201202x *sn, bool poll) if (ret) return ret; } - ret = regmap_sn201202x_select_reg(sn->sdev, TPS_REG_MODE); + ret = sn201202x_select_reg(sn->sdev, TPS_REG_MODE, + SN201202X_WAKE_SELECT_TIMEOUT_US); if (ret == -ETIMEDOUT) { - budget_ms -= SN201202X_ATOMIC_SELECT_MS; + budget_ms -= SN201202X_WAKE_SELECT_TIMEOUT_US / 1000; continue; } if (ret) diff --git a/tools/testing/selftests/drivers/apple/sn201202x-transport.py b/tools/testing/selftests/drivers/apple/sn201202x-transport.py index 1c37169ba45b53..0caa42c3541438 100755 --- a/tools/testing/selftests/drivers/apple/sn201202x-transport.py +++ b/tools/testing/selftests/drivers/apple/sn201202x-transport.py @@ -87,12 +87,16 @@ def main(): } #define read_poll_timeout(op,ret,condition,delay,bound,sleep_before,...) ({ \ int poll_ret=-ETIMEDOUT; \ + (void)(delay); (void)(bound); (void)(sleep_before); \ for(unsigned attempt=0;attempt<8;attempt++) { \ (ret)=op(__VA_ARGS__); if(condition) { poll_ret=0; break; } \ } poll_ret; }) +#define SN201202X_SELECT_TIMEOUT_US 100000 #define SN201202X_ATOMIC_SELECT_MS 10 +#define usecs_to_jiffies(x) (x) +#define max(a,b) ((a)>(b) ? (a) : (b)) #define read_poll_timeout_atomic read_poll_timeout -''' + function(source, "regmap_sn201202x_select_reg") + function(source, "__regmap_sn201202x_read") + r''' +''' + function(source, "sn201202x_select_reg") + function(source, "regmap_sn201202x_select_reg") + function(source, "__regmap_sn201202x_read") + r''' #define regmap_sn201202x_read __regmap_sn201202x_read static void clean(struct spmi_device *s) { From 52ae21ab450bb325962a90b098dc574bf48eb23c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0695/1514] dt-bindings: apple: describe T8142 USB4 and PCIe-C Allow the five ACIO register windows, LSTX GPIO and router firmware tunables used by T8142. Describe its native PCIe-C compatible and require the shared MSI vector base. Include the T8142 pinctrl fallback chain used by the AOP LSTX pin. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/pci/apple,pcie.yaml | 3 +++ .../thunderbolt/apple,t8103-usb4-acio.yaml | 27 +++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/pci/apple,pcie.yaml b/Documentation/devicetree/bindings/pci/apple,pcie.yaml index a9fd4822fd1272..06405f7179fe8c 100644 --- a/Documentation/devicetree/bindings/pci/apple,pcie.yaml +++ b/Documentation/devicetree/bindings/pci/apple,pcie.yaml @@ -101,6 +101,7 @@ properties: - const: apple,t8103-pciec - const: apple,t6000-pciec - const: apple,t6050-pciec + - const: apple,t8142-pciec - items: - const: apple,t8132-pciec - const: apple,t8122-pciec @@ -374,6 +375,7 @@ allOf: contains: enum: - apple,t8132-pciec + - apple,t8142-pciec - apple,t6040-pciec then: required: @@ -501,6 +503,7 @@ allOf: - apple,t6000-pciec - apple,t6040-pciec - apple,t6050-pciec + - apple,t8142-pciec then: properties: reg: diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml index 01592811223d23..29c64e3b3c33e4 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml @@ -52,8 +52,8 @@ properties: PCIe adapter configuration space of the USB4 router. Present where the root complex exposes the adapter separately, so that the tunnel can be configured before a PCIe-C link is brought up. - - description: MxWrap co-processor control registers, on T8132 and T6050 - - description: PCIe router AP firmware registers, on T6050 + - description: MxWrap co-processor control registers, on T8132, T8142 and T6050 + - description: PCIe router AP firmware registers, on T8142 and T6050 reg-names: oneOf: @@ -253,6 +253,7 @@ allOf: enum: - apple,t6040-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio then: properties: reg: @@ -267,6 +268,7 @@ allOf: - apple,t6040-usb4-acio - apple,t6050-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio then: properties: pinctrl-names: @@ -309,7 +311,28 @@ allOf: properties: power-domains: maxItems: 4 + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6050-usb4-acio + - apple,t8142-usb4-acio + then: + properties: apple,tunable-router-ap-fw: false + - if: + properties: + compatible: + contains: + const: apple,t8142-usb4-acio + then: + properties: + reg: + minItems: 5 + reg-names: + minItems: 5 additionalProperties: false From 2f1490ee0d04dbc902356ed8daccff6b3c1307c6 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0696/1514] PCI: apple: support T8142 PCIe-C MSI slices T8142 uses the Intr2AXI controller layout but its three-cell AIC interrupt specifier and MSI window differ from T6050. Match it natively. This allows a tunnelled NVMe controller to allocate working MSI-X interrupts. For T8132 and T8142 the slice is checked against the device tree alone. msi-ranges names the AIC input of global vector apple,msi-vector-base in a linear window, so the window's AIC base is msi-ranges minus apple,msi-vector-base, and the slice is checked by its shape: an edge-rising SPI, 32 vectors, 32-aligned, above the internal port's vectors and inside the 8-bit map target. This replaces T8132's table of ECAM apertures and its AIC base 1506 behind a machine check. The T8132 trees give 1602 - 0x60 = 1634 - 0x80 = 1506, and every J813 PCIe node gives 1741. Signed-off-by: Thomas Glanzmann --- drivers/pci/controller/pcie-apple.c | 53 ++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 8d7e9e72aabdab..467bc38a9af24b 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -481,6 +481,22 @@ static const struct hw_info t6050_pciec_hw = { .s2idle_hold_domain = true, }; +/* T8142 shares this register layout, with its own three-cell AIC MSI slice. */ +static const struct hw_info t8142_pciec_hw = { + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = PORT_MSIADDR + 4, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = PORT_T602X_MSIMAP, + .port_tunctrl = PORT_T6050_TUNCTRL, + .max_rid2sid = 256, + .tunneled = true, + .tunnel_intr2axi = true, + .no_port_reset = true, + .msimap_by_vector = true, + .mps_timers = true, +}; + static const struct of_device_id apple_pcie_of_match[]; /** @@ -3394,8 +3410,25 @@ static int apple_msi_init(struct apple_pcie *pcie) * 32-vector slice. Keep endpoint MSI data local, and route its table * entry to the corresponding shared-window vector. */ - if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) { + if (pcie->hw == &t8132_pciec_hw || pcie->hw == &t8142_pciec_hw) { + /* + * msi-ranges names the AIC input of global vector + * apple,msi-vector-base in a linear window, so the slice is + * checked by its shape only: an edge-rising SPI, 32 vectors, + * 32-aligned, above the internal port's vectors and inside the + * 8-bit map target. + */ + if (args.args_count != 3 || args.args[0] != 0 || + args.args[2] != IRQ_TYPE_EDGE_RISING || + of_property_read_u32(to_of_node(fwnode), + "apple,msi-vector-base", + &pcie->msi_vector_base) || + args.args[1] < pcie->msi_vector_base || + !apple_t6030_msi_slice_valid(pcie->msi_vector_base, + pcie->nvecs, args.args[1], + args.args[1] - pcie->msi_vector_base)) + goto invalid_slice; + } else if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t6040_pciec_hw) { struct resource ecam; u32 expected_base, aic_base; @@ -3432,19 +3465,6 @@ static int apple_msi_init(struct apple_pcie *pcie) default: goto invalid_slice; } - } else if (of_machine_is_compatible("apple,t8132")) { - aic_base = 1506; - switch (ecam.start) { - /* The internal port's bridges own vectors 0..95. */ - case 0x1c50000000ULL: - expected_base = 0x60; - break; - case 0x1c60000000ULL: - expected_base = 0x80; - break; - default: - goto invalid_slice; - } } else { goto invalid_slice; } @@ -3478,7 +3498,7 @@ static int apple_msi_init(struct apple_pcie *pcie) /* Keep map targets within the supported 8-bit range. */ if ((pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) && + pcie->hw == &t6040_pciec_hw || pcie->hw == &t8142_pciec_hw) && (!pcie->nvecs || pcie->nvecs > 256 || pcie->msi_vector_base > FIELD_MAX(PORT_MSIMAP_TARGET) + 1 - pcie->nvecs)) { @@ -7588,6 +7608,7 @@ static const struct dev_pm_ops apple_pcie_pm_ops = { static const struct of_device_id apple_pcie_of_match[] = { { .compatible = "apple,t6040-pciec", .data = &t6040_pciec_hw }, { .compatible = "apple,t6050-pciec", .data = &t6050_pciec_hw }, + { .compatible = "apple,t8142-pciec", .data = &t8142_pciec_hw }, { .compatible = "apple,t8132-pciec", .data = &t8132_pciec_hw }, { .compatible = "apple,t8122-pciec", .data = &t8122_pciec_hw }, { .compatible = "apple,t8112-pciec", .data = &t8112_pciec_hw }, From 19ece95446595304d0e46386bc8ac03b94876343 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0697/1514] thunderbolt: apple: support T8142 router startup and deep sleep Use the qualified MxWrap startup sequence: CIO reset leaves the CPU running, then RTKit readiness precedes the LSTX handoff. Admit native T8142 PCIe-C hosts without a T6050 fallback. Keep DP IN disabled. Deep sleep removes CIO power. Remove idle NVMe hierarchies before stopping the router and request fresh cable state on resume. Refuse sleep when a disk is open or another endpoint driver cannot be removed safely. A freeze removes no CIO domain, also with deep as the default, so it keeps the port up and refuses nothing. Extend the production-C admission tests with native T8142 and a negative control. The T8142 behaviours are named flags of its match data (sleep_removes_domains, restart_on_wake, phy_shared_with_dwc3), so a later SoC that behaves the same sets them instead of extending a comparison. Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/apple.c | 56 ++++++++++++--- tools/asahi/pciec-policy-tests.py | 112 ++++++++++++++++++++++++++++-- 2 files changed, 156 insertions(+), 12 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index e21cf99212ebae..11ecb4a280cd21 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -171,6 +171,15 @@ struct apple_cio_hw { bool gen4_link_recovery; /* Leave the host router's TMU to its firmware; host TMU constants. */ bool host_tmu; + /* Deep sleep removes the CIO domains, including an attached router. */ + bool sleep_removes_domains; + /* Start the router again at once after a wake. */ + bool restart_on_wake; + /* + * The PHY is shared with DWC3: release PCIe, or refuse the sleep, + * before DWC3's default-priority PM notifier queues its PHY shutdown. + */ + bool phy_shared_with_dwc3; const struct apple_dpin_policy *dp; }; @@ -206,9 +215,22 @@ static const struct apple_cio_hw apple_cio_t8132_hw = { .dp = &apple_dpin_m4, }; -/* Type 7 uses its existing ready-state check and has no qualified DP route. */ +/* + * T8142 has a Type 7 router with an MxWrap CPU already running after CIO + * reset. Hand LSTX to firmware only after RTKit is ready. DP IN is not yet + * qualified; the connector's DisplayPort alternate mode is independent. + */ static const struct apple_cio_hw apple_cio_t8142_hw = { + .mxwrap = true, .type7 = true, + .lstx_explicit = true, + .skip_run = true, + .lstx_after_boot = true, + .strict_fw_ready = true, + .no_host_clx = true, + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, .dp = &apple_dpin_disabled, }; @@ -1308,7 +1330,8 @@ static bool apple_cio_pciec_eligible(const struct device_node *np) return of_device_is_compatible(np, "apple,t6040-pciec") || of_device_is_compatible(np, "apple,t8103-pciec") || of_device_is_compatible(np, "apple,t6000-pciec") || - of_device_is_compatible(np, "apple,t6050-pciec"); + of_device_is_compatible(np, "apple,t6050-pciec") || + of_device_is_compatible(np, "apple,t8142-pciec"); } static bool @@ -4000,6 +4023,16 @@ static bool apple_cio_t6050_sleep(struct apple_cio *acio) apple_sleep_v27_late() && !pm_suspend_default_s2idle(); } +/* + * Deep sleep removes the CIO domains, including an attached router. A freeze + * does not, even with deep as the default. + */ +static bool apple_cio_sleep_removes_domains(struct apple_cio *acio) +{ + return acio->hw->sleep_removes_domains && !pm_suspend_default_s2idle() && + !pm_suspend_no_platform(); +} + /* The longest the displays behind a port may take to go before its router does. */ #define APPLE_CIO_SLEEP_DP_RELEASE_MS 3000 @@ -4102,7 +4135,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) scoped_guard(mutex, &acio->pcie_tunnel_lock) { if (READ_ONCE(acio->pcie_tunnel_requested) || acio->pcie_tunnel_populated) { struct platform_device *pcie; - int mode = READ_ONCE(t6050_sleep_pcie); + bool removes = apple_cio_sleep_removes_domains(acio); + int mode = removes ? 1 : READ_ONCE(t6050_sleep_pcie); int ret = 0; /* @@ -4111,7 +4145,7 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) * still carries them: only NVMe controllers, whose driver touches no * notifier chain on removal, and by default only with no disk in use. */ - if (!mode || !apple_cio_t6050_sleep(acio)) + if (!mode || (!removes && !apple_cio_t6050_sleep(acio))) return 0; pcie = apple_cio_find_pcie_tunnel(acio); if (pcie) { @@ -4122,7 +4156,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) dev_warn(acio->dev, "PCIe devices behind this port stay for the sleep (%d): the port is not powered off\n", ret); - return 0; + /* T8142 cannot retain this port through deep sleep. */ + return removes ? ret : 0; } } acio->pcie_tunnel_stopping = true; @@ -4131,7 +4166,7 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) dev_info(acio->dev, "powering off port for system sleep (cable info 0x%x)\n", acio->current_cable_info); t6050 = apple_cio_t6050_sleep(acio); - if (t6050) { + if (t6050 || apple_cio_sleep_removes_domains(acio)) { u64 activity; /* With no NHI the answer is "yes": then nothing is expected back. */ @@ -4199,7 +4234,7 @@ static void apple_cio_sleep_restart_work(struct work_struct *work) /* Is this port powered off for the sleep about to start? Asked at PM_SUSPEND_PREPARE. */ static bool apple_cio_sleep_tears_down(struct apple_cio *acio) { - if (READ_ONCE(s2idle_teardown)) + if (READ_ONCE(s2idle_teardown) || apple_cio_sleep_removes_domains(acio)) return true; /* A "freeze" is a suspend-to-idle with deep as the default too: the port stays up. */ if (pm_suspend_no_platform()) @@ -4229,7 +4264,7 @@ static int apple_cio_pm_notify(struct notifier_block *nb, unsigned long event, apple_cio_sleep_close_owed(acio); /* Before tasks freeze: tearing down the NHI needs unfrozen work. */ if (tears_down) { - /* Only the displays' release refuses, with the port as it was. */ + /* Refuse before powering off a port that cannot be released. */ ret = apple_cio_sleep_teardown(acio); if (ret) return notifier_from_errno(ret); @@ -4244,6 +4279,8 @@ static int apple_cio_pm_notify(struct notifier_block *nb, unsigned long event, } owed = acio->sleep_restart_owed; early = acio->sleep_aborted_early; + if (acio->hw->restart_on_wake) + delay = 0; /* TEST: macOS starts the router again straight after the wake. */ if (acio->sleep_t6050) { acio->sleep_t6050 = false; @@ -4728,6 +4765,9 @@ static int apple_cio_probe(struct platform_device *pdev) } acio->pm_notifier.notifier_call = apple_cio_pm_notify; + /* Before DWC3's default-priority notifier queues its PHY shutdown. */ + if (acio->hw->phy_shared_with_dwc3) + acio->pm_notifier.priority = 40; register_pm_notifier(&acio->pm_notifier); /* Before the notifiers of the default priority, after the port controllers' (30). */ acio->pm_notifier_dp.notifier_call = apple_cio_dp_pm_notify; diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index ef1c5d8836c4c6..3dce4b5fa2ed94 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -101,10 +101,11 @@ def function(source, name): int main(void) { struct device_node dart = { .tunables = true }; - const char *intr2axi[] = { "apple,t8112-pciec", "apple,t6000-pciec" }; - for (unsigned int i = 0; i < 2; i++) { + const char *intr2axi[] = { "apple,t8112-pciec", "apple,t6000-pciec", + "apple,t8142-pciec" }; + for (unsigned int i = 0; i < 3; i++) { /* M2 must win over its T8103 fallback, without a board allowlist. */ - struct device_node host = { .compat = { intr2axi[i], "apple,t8103-pciec" }, + struct device_node host = { .compat = { intr2axi[i], i < 2 ? "apple,t8103-pciec" : NULL }, .status = -1, .dart = &dart }; const struct of_device_id *id = of_match_node(apple_pcie_of_match, &host); assert(id && ((const struct hw_info *)id->data)->tunnel_intr2axi); @@ -133,7 +134,7 @@ def function(source, name): expect(®ular, false, false); regular.compat[0] = "apple,unknown-pciec"; expect(®ular, false, false); - puts("PASS: M1, M1 Pro, M2, firmware handoff, missing DART and DT opt-in"); + puts("PASS: M1, M1 Pro, M2, native T8142, firmware handoff, missing DART and DT opt-in"); return 0; } ''' @@ -426,6 +427,106 @@ def run_cases(out, cases, extra_flags=()): print('PASS negative control:', name) +def pm_registration(source, start, end): + first = source.index(start) + return source[first:source.index(end, first) + len(end)] + + +PM_FIXTURE = r''' +#include +#include +#include +struct notifier_block { int (*notifier_call)(void); int priority; }; +struct apple_cio_hw { bool phy_shared_with_dwc3; }; +struct apple_cio { const struct apple_cio_hw *hw; struct notifier_block pm_notifier; }; +struct dwc3_apple { struct notifier_block pm_nb; }; +static const struct apple_cio_hw apple_cio_t8142_hw = { .phy_shared_with_dwc3 = true }; +static struct notifier_block *chain[2]; +static int count; +static bool busy, phy_off, pci_off; +static int register_pm_notifier(struct notifier_block *nb) +{ + int i = count++; + assert(count <= 2); + while (i && chain[i - 1]->priority < nb->priority) { + chain[i] = chain[i - 1]; + i--; + } + chain[i] = nb; + return 0; +} +static int apple_cio_pm_notify(void) +{ + /* An open disk must be rejected while its PCIe link still works. */ + assert(!phy_off); + if (busy) + return 1; + pci_off = true; + return 0; +} +static int dwc3_apple_pm_notify(void) +{ + assert(pci_off); + phy_off = true; + return 0; +} +static void add_cio(struct apple_cio *acio) +{ + /* ACIO_REGISTRATION */ +} +static void add_dwc(struct dwc3_apple *appledwc) +{ + int ret; + /* DWC_REGISTRATION */ + assert(!ret); +} +int main(void) +{ + struct apple_cio acio = { .hw = &apple_cio_t8142_hw }; + struct dwc3_apple dwc = { 0 }; + /* DWC3 probes first on J813. Equal priority reproduces the failure. */ + add_dwc(&dwc); + add_cio(&acio); + for (int open = 0; open < 2; open++) { + busy = open; + phy_off = pci_off = false; + for (int i = 0; i < count; i++) + if (chain[i]->notifier_call()) + break; + assert(phy_off == !busy && pci_off == !busy); + } + puts("PASS: T8142 refuses an open disk before PHY shutdown; idle PCIe stops first"); + return 0; +} +''' + + +def test_pm_order(out, acio): + dwc = (ROOT / 'drivers/usb/dwc3/dwc3-apple.c').read_text() + code = PM_FIXTURE.replace('/* ACIO_REGISTRATION */', pm_registration( + acio, 'acio->pm_notifier.notifier_call = apple_cio_pm_notify;', + 'register_pm_notifier(&acio->pm_notifier);')) + code = code.replace('/* DWC_REGISTRATION */', pm_registration( + dwc, 'appledwc->pm_nb.notifier_call = dwc3_apple_pm_notify;', + 'ret = register_pm_notifier(&appledwc->pm_nb);')) + mutation = code.replace('acio->pm_notifier.priority = 40;', + 'acio->pm_notifier.priority = 0;') + assert mutation != code + for name, body in [('pm-order', code), ('phy-before-pcie', mutation)]: + source, binary = out / (name + '.c'), out / name + source.write_text(body) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Werror', str(source), + '-o', str(binary)], check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + '.log')).write_text(run.stdout + run.stderr) + if name == 'pm-order': + assert run.returncode == 0, run.stderr + print(run.stdout, end='') + else: + assert run.returncode < 0 and 'Assertion' in run.stderr + print('PASS negative control:', name) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=Path) @@ -486,10 +587,13 @@ def main(): with tempfile.TemporaryDirectory(prefix='pciec-policy-') as tmp: out = args.out or Path(tmp) out.mkdir(parents=True, exist_ok=True) + test_pm_order(out, acio) cases = { 'production': code, 'm2-fallback': code.replace( '{ .compatible = "apple,t8112-pciec",\t.data = &t8112_pciec_hw },', ''), + 't8142-admission': code.replace( + 'of_device_is_compatible(np, "apple,t8142-pciec")', 'false'), 'dart-bypass': code.replace( 'tunables = of_property_present(iommu_spec.np, "apple,tunable");', 'tunables = true;'), From 26f3957815d201f6531666406f0118e8f1636469 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0698/1514] arm64: dts: apple: enable the J813 rear USB4 port Describe ACIO1, its mailbox and LSTX pin, and the PCIe-C tunnel. Populate both DARTs under their powered parents. Use connector port 4 so the existing DisplayPort alternate-mode route can retain port 3. Name the PCIe-C tunable alias usb4-1-pcie, as t6040-usb4.dtsi does; aura looks it up under that spelling since aurora-silicon/aura#302. The DT carries no tunable values. The bootloader fills the router's, the AP firmware one included, through usb4-1-acio, the PCIe-C ones through usb4-1-pcie, and the router DART's through its generic DART copy, which finds the DART by its translated address (aurora-silicon/aura#435). Signed-off-by: Thomas Glanzmann --- .../arm64/boot/dts/apple/t8142-j813-usb4.dtsi | 288 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8142-j813.dts | 2 + 2 files changed, 290 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi diff --git a/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi new file mode 100644 index 00000000000000..03fe6a5be3ce9b --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* J813 rear USB-C port: the ACIO1 router and its PCIe-C tunnel. */ + +/ { + aliases { + + /* aura copies the router tunables here, the AP firmware one too. */ + usb4-1-acio = &acio1; + + usb4-1-pcie-adapter = &acio1; + + usb4-1-nhi = &acio1_nhi; + + /* aura copies the PCIe-C tunables here (needs aura#302). */ + usb4-1-pcie = &apciec1; + }; +}; + +&pmgr { + + ps_atc1_pcie: power-controller@3d8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_common>, <&ps_atc1_usb_aon>; + label = "atc1-pcie"; + }; + + ps_atc1_cio: power-controller@3e0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_common>; + label = "atc1-cio"; + }; + + ps_atc1_cio_pcie: power-controller@4e8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_cio>; + label = "atc1-cio-pcie"; + }; + + ps_atc1_cio_usb: power-controller@4f0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc1_cio>; + label = "atc1-cio-usb"; + }; +}; + +/* Populate these DARTs only after their parent is powered and configured. */ +/delete-node/ &acio1_dart; +/delete-node/ &pciec1_dart; + +&{/soc} { + + cio_reset: reset-controller@380780000 { + compatible = "apple,t8142-cio-reset"; + reg = <0x3 0x80780000 0x0 0x4000>; + #reset-cells = <1>; + }; + + pinctrl_aop: pinctrl@390824000 { + compatible = "apple,t8142-pinctrl", "apple,t8140-pinctrl", "apple,t8103-pinctrl"; + reg = <0x3 0x90824000 0x0 0x4000>; + gpio-controller; + #gpio-cells = <2>; + gpio-ranges = <&pinctrl_aop 0 0 77>; + apple,npins = <77>; + + /* Only LSTX pin 21 is ours; the AOP owns the rest of this bank. */ + gpio-reserved-ranges = <0 21>, <22 55>; + interrupt-controller; + #interrupt-cells = <2>; + interrupts = , + , + , + ; + apple,irq-group-base = <3>; + + acio1_lstx_pins: acio1-lstx-pins { + pinmux = <0x10015>; + }; + }; + + acio1_mbox: mailbox@409108000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x4 0x09108000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + acio1: acio@409ac0000 { + compatible = "apple,t8142-usb4-acio"; + reg = <0x4 0x09ac0000 0x0 0xc000>, + <0x4 0x09080000 0x0 0x26000>, + <0x4 0x09e44000 0x0 0x4000>, + <0x4 0x09100000 0x0 0x4000>, + <0x4 0x09c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "cpu", "router-ap-fw"; + mboxes = <&acio1_mbox>; + resets = <&cio_reset 1>; + + power-domains = <&ps_atc1_cio>, <&ps_atc1_cio_pcie>, + <&ps_atc1_cio_usb>, <&ps_atc1_pcie>; + thunderbolt-switch; + apple,pcie-tunnel = <&acio1_pcie_tunnel>; + + pinctrl-0 = <&acio1_lstx_pins>; + pinctrl-names = "lstx"; + lstx-gpios = <&pinctrl_aop 21 GPIO_ACTIVE_HIGH>; + + #address-cells = <1>; + #size-cells = <1>; + ranges = <0x0 0x4 0x09000000 0x1000000>; + nonposted-mmio; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + acio1_tbt: endpoint { + remote-endpoint = <&typec1_usb4>; + }; + }; + }; + + acio1_dart: iommu@a80000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0xa80000 0xc000>; + interrupts = ; + power-domains = <&ps_atc1_cio>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x4000 0x0 0xffff0000>; + apple,bypass-sids = <15>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + acio1_nhi: nhi@f00000 { + compatible = "apple,t8142-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", "txring3", + "txring4", "txring5", "txring6", "txring7", + "txring8", "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", "rxring3", + "rxring4", "rxring5", "rxring6", "rxring7", + "rxring8", "rxring9", "rxring10", "rxring11"; + + iommus = <&acio1_dart 0>, <&acio1_dart 1>, <&acio1_dart 2>, + <&acio1_dart 3>, <&acio1_dart 4>, <&acio1_dart 5>, + <&acio1_dart 6>, <&acio1_dart 7>, <&acio1_dart 8>, + <&acio1_dart 9>, <&acio1_dart 10>, <&acio1_dart 11>, + <&acio1_dart 16>, <&acio1_dart 17>, <&acio1_dart 18>, + <&acio1_dart 19>, <&acio1_dart 20>, <&acio1_dart 21>, + <&acio1_dart 22>, <&acio1_dart 23>, <&acio1_dart 24>, + <&acio1_dart 25>, <&acio1_dart 26>, <&acio1_dart 27>; + + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + }; +}; + +/ { + acio1_pcie_tunnel: pcie-tunnel-1 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + pciec1_dart: iommu@40c000000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0x4 0x0c000000 0x0 0xc000>; + interrupts = ; + power-domains = <&ps_atc1_pcie>; + #iommu-cells = <1>; + apple,bypass-sids = <253 255>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + apciec1: pcie@1c60000000 { + compatible = "apple,t8142-pciec"; + device_type = "pci"; + reg = <0x1c 0x60000000 0x0 0x10000000>, + <0x4 0x0c034000 0x0 0x4000>, + <0x4 0x0c020000 0x0 0x8000>, + <0x4 0x0c038000 0x0 0x4000>, + <0x4 0x0c060000 0x0 0x4000>, + <0x4 0x0c02c000 0x0 0x4000>, + <0x4 0x0c028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupts = ; + power-domains = <&ps_atc1_pcie>; + + apple,pciec-kernel-init; + + msi-controller; + msi-parent = <&apciec1>; + msi-ranges = <&aic AIC_IRQ 1869 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <128>; + + iommu-map = <0x0 &pciec1_dart 0x0 0x40>; + iommu-map-mask = <0x3f>; + + linux,pci-domain = <2>; + + bus-range = <0x0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + + ranges = <0x43000000 0xc 0x0 0xc 0x0 0x2 0x0>, + <0x02000000 0x0 0x00100000 0xe 0x00100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xe 0x40000000 0x0 0x40000000>; + + apciec1_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &apciec1_port 0 0 0 0>, + <0 0 0 2 &apciec1_port 0 0 0 1>, + <0 0 0 3 &apciec1_port 0 0 0 2>, + <0 0 0 4 &apciec1_port 0 0 0 3>; + }; + }; + }; +}; + +/* Port 3 is reserved for the board's DisplayPort alternate-mode route. */ +&typec1 { + ports { + port@4 { + reg = <4>; + typec1_usb4: endpoint { + remote-endpoint = <&acio1_tbt>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index c0ca420c87e36a..5260a5eed2ab7c 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -1283,3 +1283,5 @@ }; }; }; + +#include "t8142-j813-usb4.dtsi" From a42e7dccf46cb5f24b8b886dcfaa0f78ed58ef28 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 12:12:55 +0100 Subject: [PATCH 0699/1514] thunderbolt: apple: require the router AP firmware tuning with its window A host router whose node describes the router-ap-fw window gets its AP firmware tuning from the bootloader, which copies it from the machine into apple,tunable-router-ap-fw. A loader that leaves it out used to give a router that runs untuned, with nothing logged. Fail the probe instead, as a missing apple,tunable-rc does, so a too-old loader is seen. Every tree that describes the window today either carries the property or has it filled in by the loader: the T6050 host routers and the J813 rear port in the tree, the J813 front port through aura. Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/apple.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 11ecb4a280cd21..86cb3769993a16 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -4650,13 +4650,17 @@ static int apple_cio_probe(struct platform_device *pdev) acio->router_ap_fw_tunable = devm_apple_tunable_parse(dev, acio->np, "apple,tunable-router-ap-fw", ap_fw); - if (IS_ERR(acio->router_ap_fw_tunable)) { - if (PTR_ERR(acio->router_ap_fw_tunable) != -ENOENT) - return dev_err_probe(dev, - PTR_ERR(acio->router_ap_fw_tunable), - "Unable to load router AP firmware tunable\n"); - acio->router_ap_fw_tunable = NULL; - } + /* + * The bootloader copies this tuning from the machine. Without it + * the router would run untuned, so a loader that left it out fails + * the probe, like a missing RC tuning. + */ + if (PTR_ERR_OR_ZERO(acio->router_ap_fw_tunable) == -ENOENT) + return dev_err_probe(dev, -EINVAL, + "Missing bootloader router AP firmware tuning\n"); + if (IS_ERR(acio->router_ap_fw_tunable)) + return dev_err_probe(dev, PTR_ERR(acio->router_ap_fw_tunable), + "Unable to load router AP firmware tunable\n"); } } From 825f6e6b78bb23217a1eac84f454945d6bf378cf Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 08:50:09 +0100 Subject: [PATCH 0700/1514] arm64: dts: apple: enable the J813 front USB4 port Only the rear port's ACIO1 router and PCIe-C tunnel are described. The front connector's PD controller enters USB4 by itself when a USB4 device is attached (DATA_STATUS bit 23), and nothing in the kernel takes the link over: a USB4 NVMe enclosure that works on the rear port shows up neither as USB4 nor as USB on the front port. Describe ACIO0 like ACIO1, with the values of the ADT acio0, acio-cpu0, dart-acio0, apciec0 and dart-apciec0 nodes: router 0x401ac0000, mailbox 0x401108000, PCIe-C 0x404000000 with ECAM 0x1c50000000 and its MSI slice at vector 96 (AIC 1837), CIO reset 0, LSTX AOP pin 19 and the ATC0 power states 0x3c8, 0x3d0, 0x4d8 and 0x4e0. The bootloader fills the tunables and the DROM through the usb4-0-* aliases, as for the rear port. The router AP firmware tunable also comes from the bootloader, through usb4-0-acio, and the router DART's tunables through its generic DART copy, which finds the DART by its translated address (aura#435). Signed-off-by: Thomas Glanzmann --- .../arm64/boot/dts/apple/t8142-j813-usb4.dtsi | 256 +++++++++++++++++- 1 file changed, 252 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi index 03fe6a5be3ce9b..1062212dba17f2 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-j813-usb4.dtsi @@ -1,9 +1,22 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* J813 rear USB-C port: the ACIO1 router and its PCIe-C tunnel. */ +/* + * J813 USB-C ports: the ACIO0 (front) and ACIO1 (rear) routers and their + * PCIe-C tunnels. + */ / { aliases { + /* aura copies the router tunables here, the AP firmware one too. */ + usb4-0-acio = &acio0; + + usb4-0-pcie-adapter = &acio0; + + usb4-0-nhi = &acio0_nhi; + + /* aura copies the PCIe-C tunables here (needs aura#302). */ + usb4-0-pcie = &apciec0; + /* aura copies the router tunables here, the AP firmware one too. */ usb4-1-acio = &acio1; @@ -18,6 +31,24 @@ &pmgr { + ps_atc0_pcie: power-controller@3c8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_common>, <&ps_atc0_usb_aon>; + label = "atc0-pcie"; + }; + + ps_atc0_cio: power-controller@3d0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_common>; + label = "atc0-cio"; + }; + ps_atc1_pcie: power-controller@3d8 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x3d8 4>; @@ -36,6 +67,24 @@ label = "atc1-cio"; }; + ps_atc0_cio_pcie: power-controller@4d8 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_cio>; + label = "atc0-cio-pcie"; + }; + + ps_atc0_cio_usb: power-controller@4e0 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + power-domains = <&ps_atc0_cio>; + label = "atc0-cio-usb"; + }; + ps_atc1_cio_pcie: power-controller@4e8 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x4e8 4>; @@ -56,6 +105,8 @@ }; /* Populate these DARTs only after their parent is powered and configured. */ +/delete-node/ &acio0_dart; +/delete-node/ &pciec0_dart; /delete-node/ &acio1_dart; /delete-node/ &pciec1_dart; @@ -75,8 +126,8 @@ gpio-ranges = <&pinctrl_aop 0 0 77>; apple,npins = <77>; - /* Only LSTX pin 21 is ours; the AOP owns the rest of this bank. */ - gpio-reserved-ranges = <0 21>, <22 55>; + /* Only LSTX pins 19 and 21 are ours; the AOP owns the rest of this bank. */ + gpio-reserved-ranges = <0 19>, <20 1>, <22 55>; interrupt-controller; #interrupt-cells = <2>; interrupts = , @@ -85,11 +136,126 @@ ; apple,irq-group-base = <3>; + acio0_lstx_pins: acio0-lstx-pins { + pinmux = <0x10013>; + }; + acio1_lstx_pins: acio1-lstx-pins { pinmux = <0x10015>; }; }; + acio0_mbox: mailbox@401108000 { + compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x4 0x01108000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + acio0: acio@401ac0000 { + compatible = "apple,t8142-usb4-acio"; + reg = <0x4 0x01ac0000 0x0 0xc000>, + <0x4 0x01080000 0x0 0x26000>, + <0x4 0x01e44000 0x0 0x4000>, + <0x4 0x01100000 0x0 0x4000>, + <0x4 0x01c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "cpu", "router-ap-fw"; + mboxes = <&acio0_mbox>; + resets = <&cio_reset 0>; + + power-domains = <&ps_atc0_cio>, <&ps_atc0_cio_pcie>, + <&ps_atc0_cio_usb>, <&ps_atc0_pcie>; + thunderbolt-switch; + apple,pcie-tunnel = <&acio0_pcie_tunnel>; + + pinctrl-0 = <&acio0_lstx_pins>; + pinctrl-names = "lstx"; + lstx-gpios = <&pinctrl_aop 19 GPIO_ACTIVE_HIGH>; + + #address-cells = <1>; + #size-cells = <1>; + ranges = <0x0 0x4 0x01000000 0x1000000>; + nonposted-mmio; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + acio0_tbt: endpoint { + remote-endpoint = <&typec0_usb4>; + }; + }; + }; + + acio0_dart: iommu@a80000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0xa80000 0xc000>; + interrupts = ; + power-domains = <&ps_atc0_cio>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x4000 0x0 0xffff0000>; + apple,bypass-sids = <15>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + acio0_nhi: nhi@f00000 { + compatible = "apple,t8142-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", "txring3", + "txring4", "txring5", "txring6", "txring7", + "txring8", "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", "rxring3", + "rxring4", "rxring5", "rxring6", "rxring7", + "rxring8", "rxring9", "rxring10", "rxring11"; + + iommus = <&acio0_dart 0>, <&acio0_dart 1>, <&acio0_dart 2>, + <&acio0_dart 3>, <&acio0_dart 4>, <&acio0_dart 5>, + <&acio0_dart 6>, <&acio0_dart 7>, <&acio0_dart 8>, + <&acio0_dart 9>, <&acio0_dart 10>, <&acio0_dart 11>, + <&acio0_dart 16>, <&acio0_dart 17>, <&acio0_dart 18>, + <&acio0_dart 19>, <&acio0_dart 20>, <&acio0_dart 21>, + <&acio0_dart 22>, <&acio0_dart 23>, <&acio0_dart 24>, + <&acio0_dart 25>, <&acio0_dart 26>, <&acio0_dart 27>; + + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + }; + acio1_mbox: mailbox@409108000 { compatible = "apple,t8142-asc-mailbox", "apple,asc-mailbox-v4"; reg = <0x4 0x09108000 0x0 0x4000>; @@ -203,6 +369,77 @@ }; / { + acio0_pcie_tunnel: pcie-tunnel-0 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + pciec0_dart: iommu@404000000 { + compatible = "apple,t8142-dart", "apple,t8110-dart"; + reg = <0x4 0x04000000 0x0 0xc000>; + interrupts = ; + power-domains = <&ps_atc0_pcie>; + #iommu-cells = <1>; + apple,bypass-sids = <253 255>; + apple,full-error-reporting; + apple,ctc-flush; + }; + + apciec0: pcie@1c50000000 { + compatible = "apple,t8142-pciec"; + device_type = "pci"; + reg = <0x1c 0x50000000 0x0 0x10000000>, + <0x4 0x04034000 0x0 0x4000>, + <0x4 0x04020000 0x0 0x8000>, + <0x4 0x04038000 0x0 0x4000>, + <0x4 0x04060000 0x0 0x4000>, + <0x4 0x0402c000 0x0 0x4000>, + <0x4 0x04028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupts = ; + power-domains = <&ps_atc0_pcie>; + + apple,pciec-kernel-init; + + msi-controller; + msi-parent = <&apciec0>; + msi-ranges = <&aic AIC_IRQ 1837 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <96>; + + iommu-map = <0x0 &pciec0_dart 0x0 0x40>; + iommu-map-mask = <0x3f>; + + linux,pci-domain = <1>; + + bus-range = <0x0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + + ranges = <0x43000000 0x8 0x0 0x8 0x0 0x2 0x0>, + <0x02000000 0x0 0x00100000 0xa 0x00100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xa 0x40000000 0x0 0x40000000>; + + apciec0_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &apciec0_port 0 0 0 0>, + <0 0 0 2 &apciec0_port 0 0 0 1>, + <0 0 0 3 &apciec0_port 0 0 0 2>, + <0 0 0 4 &apciec0_port 0 0 0 3>; + }; + }; + }; + acio1_pcie_tunnel: pcie-tunnel-1 { #address-cells = <2>; #size-cells = <2>; @@ -275,7 +512,18 @@ }; }; -/* Port 3 is reserved for the board's DisplayPort alternate-mode route. */ +/* Port 3 of each connector is the board's DisplayPort alternate-mode route. */ +&typec0 { + ports { + port@4 { + reg = <4>; + typec0_usb4: endpoint { + remote-endpoint = <&acio0_tbt>; + }; + }; + }; +}; + &typec1 { ports { port@4 { From 791ebdb9fad826d239802c1c13e1b97bc8fbfa78 Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Sun, 22 Nov 2026 14:39:31 -0600 Subject: [PATCH 0701/1514] soc: apple: sep: latch only a key context's failed delete delete_unlock_evaluation() set key_context_failed on any failed delete, and every /dev/sep-bio verify closes its unlock evaluation through it. One failed delete at the end of a Touch ID prompt therefore turned off /dev/sep-key until reboot, while the verify that hit it still reported its match. That evaluation authorizes no key operation. Set the latch only where a key operation's context is deleted: in SepData's ContextDelete, which OwnedContext uses (including the context a touch-gated key operation hands to the prompt), and in the key.rs paths that delete a context directly. close_unlock_evaluation() and delete_unlock_evaluation() now only log a failed delete. Signed-off-by: Cameron Cooper --- drivers/soc/apple/key.rs | 73 +++++++++++++++++++++++++++++++++------- drivers/soc/apple/sep.rs | 3 +- 2 files changed, 62 insertions(+), 14 deletions(-) diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index d227fd887f5382..308139216b2e70 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -962,10 +962,25 @@ pub(crate) trait ContextDelete { impl ContextDelete for SepData { fn delete_context(&self, handle: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { - self.delete_unlock_evaluation(handle) + let result = latch_failed_delete(&self.key_context_failed, self.delete_unlock_evaluation(handle)); + if result.is_err() { + dev_warn_ratelimited!(self.dev, "sep-key: a key context was not deleted; private key operations disabled until reboot\n"); + } + result } } +/// A key operation's context that could not be deleted may still authorize +/// the key it was opened for, so /dev/sep-key stops until reboot. A Touch ID +/// unlock evaluation that /dev/sep-bio fails to delete authorizes no key and +/// is only logged (`close_unlock_evaluation`). +fn latch_failed_delete(failed: &kernel::sync::atomic::Atomic, result: Result<()>) -> Result<()> { + if result.is_err() { + failed.store(true, Relaxed); + } + result +} + /// A credential context the kernel opened for one operation: deleted when /// this is dropped, on every path out of the code that owns it (success, /// error, cancel, timeout, signal). Its handle never leaves the kernel. @@ -1694,7 +1709,7 @@ impl SepData { (out.reply.status == 0).then_some(()) })(); if ok.is_none() { - self.close_unlock_evaluation(&handle); + let _ = self.delete_context(&handle); return Err(EIO); } Ok(handle) @@ -1716,7 +1731,7 @@ impl SepData { let ctx = crate::scrd::tracked_create_reference(&out).filter(|_| status == 0).ok_or(EIO)?; let (status, _) = self.scrd_command(&crate::scrd::scrd_context_externalize(&ctx)).ok_or(EIO)?; if status != 0 { - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); return Err(EIO); } let mut verify = 0; @@ -1766,7 +1781,7 @@ impl SepData { req.result2 = v; self.last_key_status.store(0, Relaxed); let r = self.user_key_sign_in_bag(user, &record, &[0x5a; DIGEST_LEN], Some(&ctx)); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); req.result = r.err().map(|e| e.to_errno()).unwrap_or(0); req.enclave_status = self.last_key_status.load(Relaxed) as i32; dev_info_ratelimited!( @@ -1842,12 +1857,12 @@ impl SepData { r[2] = sign(None); let (fresh, v) = self.key_context_for(designated_id(user), Some((user.special_handle(), &pw[..len])))?; r[3] = if v == 0 { sign(Some(&fresh)) } else { v }; - self.close_unlock_evaluation(&fresh); + let _ = self.delete_context(&fresh); self.userbag_unlock(user, &pw[..len])?; r[7] = self.userbag_lock_phase(user).map(|p| p as i32).unwrap_or(-1); let (fresh2, v2) = self.key_context_for(designated_id(user), Some((user.special_handle(), &pw[..len])))?; r[4] = if v2 == 0 { sign(Some(&fresh2)) } else { v2 }; - self.close_unlock_evaluation(&fresh2); + let _ = self.delete_context(&fresh2); Ok(r) })(); pw.fill(0); @@ -1909,7 +1924,7 @@ impl SepData { } }; (req.result, req.enclave_status) = sign(&ctx); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); let second = if req.mode == SELFTEST_USERBAG_KEY_SAME_BAG { self.key_context_for(designated_id(user), None) } else { @@ -1918,7 +1933,7 @@ impl SepData { pw.fill(0); let (ctx2, v2) = second?; (req.result2, req.enclave_status2) = sign(&ctx2); - self.close_unlock_evaluation(&ctx2); + let _ = self.delete_context(&ctx2); dev_info_ratelimited!( self.dev, "sep-key: self-test {}: key under uid {}'s bag: first ({}) verify {} -> {} ({}); second ({}) verify {} -> {} ({})\n", @@ -1966,7 +1981,7 @@ impl SepData { let r = self.user_key_sign(&blob, &digest, Some(&ctx)); req.result = r.err().map(|e| e.to_errno()).unwrap_or(0); req.enclave_status = self.last_key_status.load(Relaxed) as i32; - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); dev_info_ratelimited!( self.dev, "sep-key: self-test presence key with a credential from uid {}'s bag: verify status {}, signature {} (enclave status {})\n", @@ -1989,11 +2004,11 @@ impl SepData { self.last_key_status.store(0, Relaxed); let ctx = self.passcode_context()?; (req.result, req.enclave_status) = record(self.user_key_sign(&blob, &digest, Some(&ctx)), self); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); self.last_key_status.store(0, Relaxed); let ctx = self.open_unlock_evaluation(user).ok_or(EIO)?; (req.result2, req.enclave_status2) = record(self.user_key_sign(&blob, &digest, Some(&ctx)), self); - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); dev_info_ratelimited!( self.dev, "sep-key: self-test presence probe: bag-secret context {} (enclave status {}), unsatisfied context {} (enclave status {})\n", @@ -2189,7 +2204,7 @@ impl SepData { } SELFTEST_DELETED => { let ctx = self.open_unlock_evaluation(user).ok_or(EIO)?; - self.close_unlock_evaluation(&ctx); + let _ = self.delete_context(&ctx); record(self.user_key_sign(&owned, &digest, Some(&ctx)), self) } SELFTEST_TOUCH_THEN_DELETED => { @@ -2625,6 +2640,40 @@ mod one_op_tests { assert!(selftest_mode_built(mode)); } } + + // Only a key context's failed delete stops /dev/sep-key: an owned + // context whose delete is confirmed leaves it running, one whose delete + // fails (finished or dropped) stops it, and a later confirmed delete + // does not restart it. Kept below the host harness's slice, which has + // no kernel atomics. + #[test] + fn only_a_failed_key_context_delete_latches() { + struct Latching { + failed: kernel::sync::atomic::Atomic, + result: Cell>, + } + + impl ContextDelete for Latching { + fn delete_context(&self, _: &[u8; crate::scrd::SCRD_ACM_HANDLE_LEN]) -> Result<()> { + latch_failed_delete(&self.failed, self.result.get()) + } + } + + let d = Latching { failed: kernel::sync::atomic::Atomic::new(false), result: Cell::new(Ok(())) }; + let h = [0x54; crate::scrd::SCRD_ACM_HANDLE_LEN]; + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Ok(7)); + drop(OwnedContext::new(&d, h)); + assert!(!d.failed.load(Relaxed)); + d.result.set(Err(EIO)); + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Err(EIO)); + assert!(d.failed.load(Relaxed)); + let d = Latching { failed: kernel::sync::atomic::Atomic::new(false), result: Cell::new(Err(EIO)) }; + drop(OwnedContext::new(&d, h)); + assert!(d.failed.load(Relaxed)); + d.result.set(Ok(())); + assert_eq!(OwnedContext::new(&d, h).finish(Ok(7)), Ok(7)); + assert!(d.failed.load(Relaxed)); + } } #[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index 715774d719d8ea..a71d3ff0be3fb3 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -2779,10 +2779,9 @@ impl SepData { match self.scrd_command(&crate::scrd::scrd_context_delete(handle)) { Some((0, _)) => Ok(()), other => { - self.key_context_failed.store(true, Relaxed); dev_warn_ratelimited!( self.dev, - "scrd: deleting the unlock evaluation answered {:?}; private key operations disabled until reboot\n", + "scrd: deleting the unlock evaluation answered {:?}\n", other.map(|(status, _)| status) ); Err(EIO) From 4fbabf61e49dcdbe732231f545705ad79db7af6b Mon Sep 17 00:00:00 2001 From: Cameron Cooper Date: Mon, 23 Nov 2026 11:41:50 -0600 Subject: [PATCH 0702/1514] soc: apple: sep: sep-key: delete a context whose externalize gets no reply key_context_for() creates a tracked context and then externalizes it. A refused externalize deleted the context, but one that got no reply returned EIO with the context still alive in the enclave, and nothing deleted it until the enclave restarted. Delete it on both: the context exists once it is created. A delete that then fails latches /dev/sep-key, as for any key context. Signed-off-by: Cameron Cooper --- drivers/soc/apple/key.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/key.rs b/drivers/soc/apple/key.rs index 308139216b2e70..6389a88c43e18c 100644 --- a/drivers/soc/apple/key.rs +++ b/drivers/soc/apple/key.rs @@ -1729,8 +1729,9 @@ impl SepData { } let (status, out) = self.scrd_command(&crate::scrd::scrd_context_create_tracked(uid)).ok_or(EIO)?; let ctx = crate::scrd::tracked_create_reference(&out).filter(|_| status == 0).ok_or(EIO)?; - let (status, _) = self.scrd_command(&crate::scrd::scrd_context_externalize(&ctx)).ok_or(EIO)?; - if status != 0 { + // The context exists once created: an externalize that is refused or + // gets no reply still deletes it. + if !matches!(self.scrd_command(&crate::scrd::scrd_context_externalize(&ctx)), Some((0, _))) { let _ = self.delete_context(&ctx); return Err(EIO); } From e04db3b4f021971fbeeac3fabae8741f461efd96 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 08:35:10 +0100 Subject: [PATCH 0703/1514] media: apple: avd: use VP9 temporal MVs only from a frame of the same size VP9 predicts motion vectors from the previous frame only if that frame has the same size (UsePrevFrameMvs in compute_image_size(), libvpx's use_prev_frame_mvs). avd_vp9_uses_prev_mv() does not compare sizes, so after a size change the decoder reads the previous frame's MV buffer, which is laid out for the other size. Frames of different sizes already pass validate_dec_params() when they share the 64x16 aligned capture format, e.g. 1920x1080 and 1900x1080. Accepting frames smaller than the capture format, as aurora-silicon/linux#2136 does, makes this common: with that change alone, every VP9 stream that changes size on an inter frame without error resilience fails at the first frame of the new size with "open firmware error 0x8", a timeout and a decoder reset. With this patch no frame fails in the firmware. Record the size of each frame and require the previous one to match. The host test decodes a 1900x1080 frame after a 1920x1088 one and checks that the prior bank's MV buffer is not used. Signed-off-by: Thomas Glanzmann --- drivers/media/platform/apple/avd/avd-vp9.c | 30 ++++++++++++++----- .../platform/apple/avd/tests/vp9-test.py | 12 ++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 71b80796fd090b..3d426655cc6a3c 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -160,6 +160,8 @@ struct avd_vp9_frame_info { u32 tx_mode : 3; u32 interpolation_filter : 3; u32 flags; + u32 width; + u32 height; u64 timestamp; dma_addr_t color; struct v4l2_vp9_segmentation seg; @@ -268,13 +270,25 @@ static void set_refs(struct avd_ctx *ctx, struct avd_vp9_run *run) } } -/* Temporal MV input is the previous shown inter picture, not the new bank. */ -static bool avd_vp9_uses_prev_mv(u32 flags, const struct avd_vp9_frame_info *last) +static bool avd_vp9_same_size(const struct v4l2_ctrl_vp9_frame *frame, + const struct avd_vp9_frame_info *last) { - return !(flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT) && - !(flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && last->valid && + return last->width == frame->frame_width_minus_1 + 1 && + last->height == frame->frame_height_minus_1 + 1; +} + +/* + * Temporal MV input is the previous shown inter picture, not the new bank. + * VP9 uses it only if that picture has the same frame size. + */ +static bool avd_vp9_uses_prev_mv(const struct v4l2_ctrl_vp9_frame *frame, + const struct avd_vp9_frame_info *last) +{ + return !(frame->flags & V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT) && + !(frame->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && last->valid && (last->flags & V4L2_VP9_FRAME_FLAG_SHOW_FRAME) && - !(last->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME); + !(last->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME) && + avd_vp9_same_size(frame, last); } static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run) @@ -328,7 +342,7 @@ static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run) flags |= VP9_SEG_ENABLED(frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED); - flags |= VP9_HAS_REF(avd_vp9_uses_prev_mv(frame->flags, &vp9_ctx->last)); + flags |= VP9_HAS_REF(avd_vp9_uses_prev_mv(frame, &vp9_ctx->last)); flags |= VP9_SEG_RESET( frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED && @@ -426,7 +440,7 @@ static void set_header(struct avd_ctx *ctx, struct avd_vp9_run *run) pusha(vp9_ctx->b->bufs.seg.addr, "seg", 1); pusha(vp9_ctx->b->bufs.seg.addr, "seg", 2); pusha(vp9_ctx->b->bufs.color.addr, "color", 3); - pusha(avd_vp9_uses_prev_mv(frame->flags, &vp9_ctx->last) ? + pusha(avd_vp9_uses_prev_mv(frame, &vp9_ctx->last) ? vp9_ctx->last.color : vp9_ctx->b->bufs.color.addr, "color", 4); @@ -568,6 +582,8 @@ static void update_ctx_cur_info(struct avd_vp9_ctx *vp9_ctx, vp9_ctx->b->cur.reference_mode = dec_params->reference_mode; vp9_ctx->b->cur.interpolation_filter = dec_params->interpolation_filter; vp9_ctx->b->cur.flags = dec_params->flags; + vp9_ctx->b->cur.width = dec_params->frame_width_minus_1 + 1; + vp9_ctx->b->cur.height = dec_params->frame_height_minus_1 + 1; vp9_ctx->b->cur.timestamp = buf->base.vb.vb2_buf.timestamp; vp9_ctx->b->cur.color = vp9_ctx->b->bufs.color.addr; vp9_ctx->b->cur.seg = dec_params->seg; diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 0ea406aae17773..b575b2762fc7bb 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -234,6 +234,18 @@ def without_includes(s): assert(p->bank[0].busy&&p->bank[1].busy); avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); } + /* After a frame size change the temporal-MV input is not the prior bank. */ + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=1919,.frame_height_minus_1=1087,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + struct avd_vp9_bank *shown=p->b; + params.frame_width_minus_1=1899;params.frame_height_minus_1=1079; + current_dst=&dst[1].base.vb;frame.idx=1;assert(!avd_vp9_run(&ctx)); + assert(p->b!=shown&&p->last.width==1900&&p->last.height==1080); + {bool prior_color=false;u32 *words=program.cpu; + for(size_t j=0;jbufs.color.addr>>8))prior_color=true; + assert(!prior_color);} + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); /* The firmware transport keeps the 64-pixel floor. */ ctx.decoded_fmt.fmt.pix_mp.width=64;ctx.decoded_fmt.fmt.pix_mp.height=64; ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=64; From 6fd057431b55e034a3b01e7f97d97e09ba55cb2a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 08:35:33 +0100 Subject: [PATCH 0704/1514] media: apple: avd: put the VP9 reference scale in the right halves set_refs() packs the horizontal reference scale into the upper 16 bits and the vertical one into the lower 16 bits. The decoder reads them the other way round. A reference scaled the same in both directions (2:1, 4:3) decodes either way, so only references whose aspect ratio differs from the frame's were wrong. A frame whose size changes within its 64x16 aligned capture format (1920x1080 to 1900x1080) already predicts from such a reference. Once frames smaller than the capture format are accepted (aurora-silicon/linux#2136), libvpx's vp90-2-05-resize.ivf (352x288 to 282x173) and vp90-2-18-resize.ivf (310x230 to 248x138) do too, and decode bit-exact against libvpx's MD5s: 10 of 10 and 100 of 100 frames, up from 3 and 94. Pack the vertical scale with AVD_HDR_HEIGHT() and the horizontal one with AVD_HDR_WIDTH(), as the reference size above it is. The host test checks the word for a 1440x1088 reference of a 1920x1088 frame. Signed-off-by: Thomas Glanzmann --- drivers/media/platform/apple/avd/avd-vp9.c | 2 +- drivers/media/platform/apple/avd/tests/vp9-test.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 3d426655cc6a3c..18a0717349f86f 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -263,7 +263,7 @@ static void set_refs(struct avd_ctx *ctx, struct avd_vp9_run *run) dst->vp9.width; yscale = (ref_buf[i]->vp9.height << VP9_REF_SCALE_SHIFT) / dst->vp9.height; - push(AVD_HDR_HEIGHT(xscale) | AVD_HDR_WIDTH(yscale), + push(AVD_HDR_HEIGHT(yscale) | AVD_HDR_WIDTH(xscale), "ref_scale"); push_comp(ctx, addr, ref_buf[i]->comp.offsets); diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index b575b2762fc7bb..e3a57861830d51 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -246,6 +246,13 @@ def without_includes(s): for(size_t j=0;jbufs.color.addr>>8))prior_color=true; assert(!prior_color);} avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE);avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); + /* A 1440x1088 reference of a 1920x1088 frame: vertical scale high, horizontal low. */ + params.frame_width_minus_1=1919;params.frame_height_minus_1=1087;reference.vp9.width=1440; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + {bool scale=false;u32 *words=program.cpu; + for(size_t j=0;j Date: Fri, 20 Nov 2026 15:16:43 -0800 Subject: [PATCH 0705/1514] accel/ane: h16: copy EXECUTE buffers without user faults under the node lock Without DRM_ANE_H16_EXEC_IN_PLACE, H16_EXEC copied each input from user memory into its surface, and each output back, with the node lock held and the request counted active. A page fault in those copies waits for whatever backs the page, and for that long every other client's LOAD, EXECUTE, mmap and close waited on the lock, as did the PM notifier's drain at suspend, which waits for no request to be active. The fault also takes the mmap lock, while mmap() of a surface takes the file and node locks under it. Pin the user pages of every buffer with no driver lock held: outputs with FOLL_WRITE, so a buffer that cannot be written fails here with EFAULT instead of after the request ran. The buffers are checked against the loaded program before pinning, and again under the file lock after it, since the program may have changed in between. Under the node lock the copies go through the kernel mapping of the pinned pages and cannot fault; the pages are unpinned, outputs marked dirty, after both locks are dropped. There is still one copy each way. Pages in a VM_PFNMAP or VM_IO mapping cannot be pinned, and EXECUTE from a mapped GEM-shmem or dma-buf heap buffer worked with copy_from_user() before. A buffer that reaches such a mapping is bounced instead: an input is copied into a kernel buffer when it is taken, with no lock held, and an output is copied back to user memory after both locks are dropped, only if the request ran. Unmapped memory and read-only outputs still fail before the request. The comment on ane_h16_export_put() said an EXECUTE may wait for the mmap lock while holding the node lock, which is no longer true. It now gives the order that must not happen, the mmap lock or a user fault under the node lock, and what the deferral to a work item still avoids: a last put from h16_give_back(), which holds the node lock, and a munmap() that would wait under the mmap lock for a running request. KUnit: ane_h16_accel_user_pages_test pins an input and an output that cross a page boundary, compares the copies with copy_from_user() and copy_to_user(), and fails the pin, holding nothing, for an unmapped buffer, a read-only output, a range that wraps and a size whose page count would wrap; ane_h16_accel_user_bounce_test finds a VM_IO mapping in a range, takes an input and an output through the bounce copy, leaves an output the request did not write unchanged, and still fails a read-only output when taken. On a J775D (die 0, 27.2 firmware) another client's LOAD and EXECUTEs complete while one client's input page fault is outstanding, where they waited for it before. The add programs stay bit exact, and the mobilenet program classifies 16 of 16 images at a p50 request latency of 2.55 ms, as before (2.56 to 2.59 ms). EXECUTE with its buffers in a dma-buf system heap mmap stays bit exact (all buffers, only the inputs, only the output). Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Bartosz Nitka Signed-off-by: Jeff Queisser --- drivers/accel/ane/ane_h16_accel.c | 239 ++++++++++++++++++++++--- drivers/accel/ane/ane_h16_accel_test.c | 179 +++++++++++++++++- drivers/accel/ane/ane_h16_program.c | 10 +- 3 files changed, 404 insertions(+), 24 deletions(-) diff --git a/drivers/accel/ane/ane_h16_accel.c b/drivers/accel/ane/ane_h16_accel.c index 8ae375af68ed72..9a2d2526d2944a 100644 --- a/drivers/accel/ane/ane_h16_accel.c +++ b/drivers/accel/ane/ane_h16_accel.c @@ -7,6 +7,7 @@ * commands. A process may map its program's surfaces (inputs and outputs * only) and run requests on them in place, without copies. */ +#include #include #include #include @@ -157,12 +158,180 @@ static int ane_h16_load_ioctl(struct drm_device *drm, void *data, struct drm_fil return ret; } +/* + * The user memory of one EXECUTE buffer, taken before any driver lock: its + * pages pinned, or, where they cannot be pinned (VM_PFNMAP and VM_IO + * mappings, such as a GEM-shmem or dma-buf heap mmap), a kernel bounce copy. + * Faulting user memory in can wait for as long as whoever backs it likes, and + * mmap() of the node takes the file and node locks under the process mmap + * lock, so no lock of ours is held then. Under the node lock the request + * copies through the kernel mapping of the pinned pages or the bounce copy, + * neither of which faults; a bounced output goes back to user memory after + * both locks are dropped. + */ +struct ane_h16_user_buffer { + struct page **pages; + void *bounce; + u64 ptr; + unsigned int count; + size_t offset; + size_t size; + bool write, dirty; +}; + +static int ane_h16_user_pin(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + int ret; + + *u = (struct ane_h16_user_buffer) { + .offset = offset_in_page(ptr), + .size = size, + .write = write, + }; + /* At most INT_MAX pages, checked before the page count can wrap. */ + if (!size || ptr + size < ptr || size > (size_t)INT_MAX * PAGE_SIZE - u->offset) + return -EFAULT; + u->count = DIV_ROUND_UP(u->offset + size, PAGE_SIZE); + u->pages = kvmalloc_array(u->count, sizeof(*u->pages), GFP_KERNEL); + if (!u->pages) + return -ENOMEM; + ret = pin_user_pages_fast(ptr & PAGE_MASK, u->count, write ? FOLL_WRITE : 0, u->pages); + if (ret == u->count) + return 0; + if (ret > 0) + unpin_user_pages(u->pages, ret); + kvfree(u->pages); + u->pages = NULL; + return ret < 0 ? ret : -EFAULT; +} + +static void ane_h16_user_unpin(struct ane_h16_user_buffer *u) +{ + if (!u->pages) + return; + unpin_user_pages_dirty_lock(u->pages, u->count, u->dirty); + kvfree(u->pages); + u->pages = NULL; +} + +/* + * Whether [ptr, ptr + size) is completely mapped with the requested access + * and reaches a VM_PFNMAP or VM_IO mapping, whose pages cannot be pinned. + */ +static bool ane_h16_user_unpinnable(u64 ptr, size_t size, bool write) +{ + struct mm_struct *mm = current->mm; + struct vm_area_struct *vma; + unsigned long need = write ? VM_WRITE : VM_READ; + u64 addr = ptr, end = ptr + size; + bool unpinnable = false; + + if (!size || end < ptr) + return false; + mmap_read_lock(mm); + while (addr < end) { + vma = find_vma(mm, addr); + if (!vma || vma->vm_start > addr || !(vma->vm_flags & need)) { + unpinnable = false; + break; + } + if (vma->vm_flags & (VM_PFNMAP | VM_IO)) + unpinnable = true; + addr = vma->vm_end; + } + mmap_read_unlock(mm); + return unpinnable; +} + +/* A kernel copy of the buffer; an input is read into it now. */ +static int ane_h16_user_bounce(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + *u = (struct ane_h16_user_buffer) { .size = size, .write = write }; + u->bounce = kvmalloc(size, GFP_KERNEL_ACCOUNT); + if (!u->bounce) + return -ENOMEM; + u->ptr = ptr; + if (!write && copy_from_user(u->bounce, u64_to_user_ptr(ptr), size)) { + kvfree(u->bounce); + u->bounce = NULL; + return -EFAULT; + } + return 0; +} + +/* + * Take one buffer with no lock held: pin it, or bounce it when it lies in a + * mapping whose pages cannot be pinned. An input is read into the bounce copy + * now, and fails here as copy_from_user() would; an output is written back by + * ane_h16_user_put(). Unmapped memory and read-only outputs still fail here. + */ +static int ane_h16_user_get(struct ane_h16_user_buffer *u, u64 ptr, size_t size, bool write) +{ + int ret = ane_h16_user_pin(u, ptr, size, write); + + if (ret != -EFAULT || !ane_h16_user_unpinnable(ptr, size, write)) + return ret; + return ane_h16_user_bounce(u, ptr, size, write); +} + +/* Release one buffer after both locks are dropped; a bounced output goes back now. */ +static int ane_h16_user_put(struct ane_h16_user_buffer *u) +{ + int ret = 0; + + if (!u->bounce) { + ane_h16_user_unpin(u); + return 0; + } + if (u->dirty && copy_to_user(u64_to_user_ptr(u->ptr), u->bounce, u->size)) + ret = -EFAULT; + kvfree(u->bounce); + u->bounce = NULL; + return ret; +} + +/* + * Copy between cpu and the pinned pages or the bounce copy. It cannot fault: + * safe under the node lock. + */ +static void ane_h16_user_copy(struct ane_h16_user_buffer *u, void *cpu, bool to_user) +{ + size_t done = 0, offset = u->offset; + unsigned int i; + + if (u->bounce) { + if (to_user) + memcpy(u->bounce, cpu, u->size); + else + memcpy(cpu, u->bounce, u->size); + u->dirty |= to_user; + return; + } + for (i = 0; i < u->count; i++) { + size_t n = min_t(size_t, PAGE_SIZE - offset, u->size - done); + u8 *page = kmap_local_page(u->pages[i]); + + if (to_user) { + memcpy(page + offset, (u8 *)cpu + done, n); + flush_dcache_page(u->pages[i]); + } else { + memcpy((u8 *)cpu + done, page + offset, n); + } + kunmap_local(page); + done += n; + offset = 0; + } + if (to_user) + u->dirty = true; +} + static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_file *file) { struct ane_h16_accel *a = to_h16_accel(drm); struct ane_h16_accel_file *f = file->driver_priv; struct drm_ane_h16_exec *args = data; struct drm_ane_h16_buffer buffers[ANE_H16_SURFACES]; + struct ane_h16_user_buffer user[ANE_H16_SURFACES] = {}; struct ane_h16_program *p; u64 start, locked, copied, done; unsigned int i; @@ -177,22 +346,48 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil array_size(args->count, sizeof(*buffers)))) return -EFAULT; start = ktime_get_ns(); + /* + * Check the buffers against the loaded program, then take them (pin or + * bounce) with no lock held: user memory is not touched under a lock of + * ours. The program can change while unlocked, so the taken buffers are + * checked against it again under the file lock, which then pins the + * program through the request. + */ mutex_lock(&f->lock); - ret = ane_h16_session_enter(a->session, file->filp->f_flags & O_NONBLOCK); - if (ret) { - mutex_unlock(&f->lock); - return ret; - } p = f->program; - if (!p || p->closed || args->count != p->resource_count) { + if (!p || args->count != p->resource_count) ret = -EINVAL; - goto unlock; + for (i = 0; i < args->count && !in_place && !ret; i++) { + if (buffers[i].size != p->resources[i].buffer.size) + ret = -EINVAL; + user[i].write = p->resources[i].permissions == 2; } + mutex_unlock(&f->lock); + if (ret) + return ret; for (i = 0; i < args->count && !in_place; i++) { - if (buffers[i].size != p->resources[i].buffer.size) { + ret = ane_h16_user_get(&user[i], buffers[i].ptr, buffers[i].size, + user[i].write); + if (ret) + goto unpin; + } + mutex_lock(&f->lock); + p = f->program; + if (!p || args->count != p->resource_count) + ret = -EINVAL; + for (i = 0; i < args->count && !in_place && !ret; i++) { + bool write = p->resources[i].permissions == 2; + + if (buffers[i].size != p->resources[i].buffer.size || user[i].write != write) ret = -EINVAL; - goto unlock; - } + } + if (!ret) + ret = ane_h16_session_enter(a->session, file->filp->f_flags & O_NONBLOCK); + if (ret) + goto unlock_file; + if (p->closed) { + ret = -EINVAL; + goto unlock; } ret = ane_h16_session_acquire(a->session, p); if (ret) @@ -202,14 +397,10 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil for (i = 0; i < args->count && !in_place; i++) { void *cpu = p->surfaces[i]->cpu; - if (p->resources[i].permissions == 1) { - if (copy_from_user(cpu, u64_to_user_ptr(buffers[i].ptr), buffers[i].size)) { - ret = -EFAULT; - goto release; - } - } else { + if (p->resources[i].permissions == 1) + ane_h16_user_copy(&user[i], cpu, false); + else memset(cpu, 0xff, buffers[i].size); - } } ane_h16_session_sync(a->session, p, true); copied = ktime_get_ns(); @@ -219,10 +410,8 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil done = ktime_get_ns(); ane_h16_session_sync(a->session, p, false); for (i = 0; i < args->count && !in_place; i++) - if (p->resources[i].permissions == 2 && - copy_to_user(u64_to_user_ptr(buffers[i].ptr), p->surfaces[i]->cpu, - buffers[i].size)) - ret = -EFAULT; + if (p->resources[i].permissions == 2) + ane_h16_user_copy(&user[i], p->surfaces[i]->cpu, true); if (!ret) { u64 end = ktime_get_ns(); const u64 *ns = a->session->timing.ns; @@ -248,7 +437,15 @@ static int ane_h16_exec_ioctl(struct drm_device *drm, void *data, struct drm_fil ane_h16_session_release(a->session, p); unlock: mutex_unlock(&a->lock); +unlock_file: mutex_unlock(&f->lock); +unpin: + for (i = 0; i < args->count && !in_place; i++) { + int put = ane_h16_user_put(&user[i]); + + if (put && !ret) + ret = put; + } return ret; } diff --git a/drivers/accel/ane/ane_h16_accel_test.c b/drivers/accel/ane/ane_h16_accel_test.c index b88a8d70336e5b..7e6bd043a315b1 100644 --- a/drivers/accel/ane/ane_h16_accel_test.c +++ b/drivers/accel/ane/ane_h16_accel_test.c @@ -5,6 +5,7 @@ */ #include #include +#include #include #include @@ -60,9 +61,185 @@ static void ane_h16_accel_open_test(struct kunit *test) drm_dev_unregister(&a->drm); } +/* + * EXECUTE pins a plain buffer's pages before it takes the node lock and copies + * through them under it. The copies equal what copy_from_user() and + * copy_to_user() move, at an offset that crosses pages; an unmapped buffer, + * a read-only output and a wrapping range fail at the pin, holding nothing. + */ +static void ane_h16_accel_user_pages_test(struct kunit *test) +{ + const size_t size = 2 * PAGE_SIZE, off = PAGE_SIZE - 24; + struct ane_h16_user_buffer u; + unsigned long user, ro; + u8 *src, *dst; + size_t i; + + user = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, 0); + ro = kunit_vm_mmap(test, NULL, 0, PAGE_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_TRUE(test, user && !IS_ERR_VALUE(user)); + KUNIT_ASSERT_TRUE(test, ro && !IS_ERR_VALUE(ro)); + src = kunit_kzalloc(test, size, GFP_KERNEL); + dst = kunit_kzalloc(test, size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, src); + KUNIT_ASSERT_NOT_NULL(test, dst); + for (i = 0; i < size; i++) + src[i] = i * 7 + 3; + KUNIT_ASSERT_EQ(test, copy_to_user((void __user *)(user + off), src, size), 0); + + /* An input: three pages for a buffer that starts 24 bytes before a page end. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_pin(&u, user + off, size, false), 0); + KUNIT_EXPECT_EQ(test, u.count, 3U); + ane_h16_user_copy(&u, dst, false); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + KUNIT_EXPECT_FALSE(test, u.dirty); + ane_h16_user_unpin(&u); + KUNIT_EXPECT_NULL(test, u.pages); + + /* An output: written through the pinned pages, read back from user memory. */ + for (i = 0; i < size; i++) + src[i] ^= 0x5a; + KUNIT_ASSERT_EQ(test, ane_h16_user_pin(&u, user + off, size, true), 0); + ane_h16_user_copy(&u, src, true); + KUNIT_EXPECT_TRUE(test, u.dirty); + ane_h16_user_unpin(&u); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, 0, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, ro, 64, false), 0); + ane_h16_user_unpin(&u); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, U64_MAX - 8, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + /* A size whose page count would wrap to 0 without its own check. */ + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, PAGE_SIZE - 1, + SIZE_MAX - (PAGE_SIZE - 1), false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_EQ(test, ane_h16_user_pin(&u, 0, (size_t)INT_MAX * PAGE_SIZE + 1, false), + -EFAULT); + KUNIT_EXPECT_NULL(test, u.pages); +} + +/* Set or clear VM_IO on the mapping at @addr, which pin_user_pages_fast() then refuses. */ +static void ane_h16_accel_test_vm_io(unsigned long addr, bool on) +{ + struct mm_struct *mm = current->mm; + struct vm_area_struct *vma; + + mmap_write_lock(mm); + vma = find_vma(mm, addr); + if (vma && vma->vm_start <= addr) { + if (on) + vm_flags_set(vma, VM_IO); + else + vm_flags_clear(vma, VM_IO); + } + mmap_write_unlock(mm); +} + +/* + * A buffer in a mapping whose pages cannot be pinned (VM_PFNMAP or VM_IO: a + * GEM-shmem or dma-buf heap mmap) is bounced: an input is read when it is + * taken, with no lock held, an output is written back when it is put, after + * the locks drop, and only once the request copied into it. A VM_IO flag set + * on anonymous memory is seen by the range check but not by the lockless + * pin, so the bounce itself is called directly here. + */ +static void ane_h16_accel_user_bounce_test(struct kunit *test) +{ + const size_t size = 2 * PAGE_SIZE, off = PAGE_SIZE - 24; + struct ane_h16_user_buffer u; + unsigned long user, ro; + u8 *src, *dst; + size_t i; + + user = kunit_vm_mmap(test, NULL, 0, 3 * PAGE_SIZE, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, 0); + ro = kunit_vm_mmap(test, NULL, 0, PAGE_SIZE, PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, 0); + KUNIT_ASSERT_TRUE(test, user && !IS_ERR_VALUE(user)); + KUNIT_ASSERT_TRUE(test, ro && !IS_ERR_VALUE(ro)); + src = kunit_kzalloc(test, size, GFP_KERNEL); + dst = kunit_kzalloc(test, size, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, src); + KUNIT_ASSERT_NOT_NULL(test, dst); + for (i = 0; i < size; i++) + src[i] = i * 5 + 1; + KUNIT_ASSERT_EQ(test, copy_to_user((void __user *)(user + off), src, size), 0); + + /* The range check finds a VM_IO mapping anywhere in the range and checks access. */ + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(user + off, size, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(user + off, size, true)); + ane_h16_accel_test_vm_io(user, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(user + off, size, false)); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(user + off, size, true)); + /* A VM_IO mapping extending into an unmapped hole fails before bouncing. */ + { + unsigned long hole = kunit_vm_mmap(test, NULL, 0, 2 * PAGE_SIZE, + PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, 0); + + KUNIT_ASSERT_TRUE(test, hole && !IS_ERR_VALUE(hole)); + KUNIT_ASSERT_EQ(test, vm_munmap(hole + PAGE_SIZE, PAGE_SIZE), 0); + ane_h16_accel_test_vm_io(hole, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(hole, PAGE_SIZE, true)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(hole, 2 * PAGE_SIZE, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(hole, 2 * PAGE_SIZE, true)); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, hole, 2 * PAGE_SIZE, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); + ane_h16_accel_test_vm_io(hole, false); + } + /* A read-only VM_IO mapping is readable as an input, but fails as an output. */ + ane_h16_accel_test_vm_io(ro, true); + KUNIT_EXPECT_TRUE(test, ane_h16_user_unpinnable(ro, 64, false)); + KUNIT_EXPECT_FALSE(test, ane_h16_user_unpinnable(ro, 64, true)); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); + ane_h16_accel_test_vm_io(ro, false); + ane_h16_accel_test_vm_io(user, false); + + /* An input: read into the bounce copy when taken. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, false), 0); + KUNIT_EXPECT_NULL(test, u.pages); + KUNIT_EXPECT_NOT_NULL(test, u.bounce); + ane_h16_user_copy(&u, dst, false); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_EXPECT_NULL(test, u.bounce); + + /* An output the request never wrote: user memory is left as it was. */ + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, true), 0); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + /* An output: written back at the put. */ + for (i = 0; i < size; i++) + src[i] ^= 0xa5; + KUNIT_ASSERT_EQ(test, ane_h16_user_bounce(&u, user + off, size, true), 0); + ane_h16_user_copy(&u, src, true); + KUNIT_EXPECT_EQ(test, ane_h16_user_put(&u), 0); + KUNIT_ASSERT_EQ(test, copy_from_user(dst, (void __user *)(user + off), size), 0); + KUNIT_EXPECT_MEMEQ(test, dst, src, size); + + /* Unmapped memory, and an output in a read-only mapping, still fail when taken. */ + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, 0, 64, false), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_EQ(test, ane_h16_user_get(&u, ro, 64, true), -EFAULT); + KUNIT_EXPECT_NULL(test, u.bounce); + KUNIT_EXPECT_NULL(test, u.pages); +} + static struct kunit_case ane_h16_accel_cases[] = { KUNIT_CASE(ane_h16_accel_fops_test), KUNIT_CASE(ane_h16_accel_open_test), + KUNIT_CASE(ane_h16_accel_user_pages_test), + KUNIT_CASE(ane_h16_accel_user_bounce_test), {} }; @@ -73,5 +250,5 @@ static struct kunit_suite ane_h16_accel_suite = { kunit_test_suite(ane_h16_accel_suite); -MODULE_DESCRIPTION("KUnit open test for the H16 ANE accel node"); +MODULE_DESCRIPTION("KUnit open and user-buffer tests for the H16 ANE accel node"); MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index dd0a5a59e1e641..4a8844a665a1c2 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -966,8 +966,14 @@ EXPORT_SYMBOL_GPL(ane_h16_export_get); /* * Drop a reference. The last one returns a released surface to the spares - * from a work item: a mapping's last put runs under the process mmap lock, - * which an EXECUTE may wait for while holding the node lock. + * from a work item, because the spares need the node lock and the last put + * can come from two places that cannot take it: h16_give_back(), which + * already holds it, and a mapping's close in munmap() or process exit, which + * would then wait under the process mmap lock for a running request to end. + * Taking the node lock under the mmap lock is the order ane_h16_mmap() uses; + * the order that must not happen is the reverse, so nothing that faults user + * memory or takes the mmap lock runs under the node lock (EXECUTE pins or + * bounces its buffers before taking it). */ void ane_h16_export_put(struct ane_h16_export *e) { From ec6ae209d790eb48ced87505ee54bffb2163d945 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 17:30:28 -0300 Subject: [PATCH 0706/1514] drm/asahi: g17: bound a submission's command stream before copying it The submit ioctl copies the whole command stream from userspace before any parser sees it, and refuses only one longer than the GPU's max_cmdbuf_size(). G17 never set one, so it kept the default of usize::MAX: any cmdbuf_size up to 4 GiB was handed to the allocator. The copy is one kmalloc(), and past KMALLOC_MAX_SIZE (32 MiB with 16K pages) the page allocator refuses it with a WARN_ON_ONCE(), so userspace could trigger a kernel warning. Anything below that became a physically contiguous allocation as large as userspace asked for. The format has a real maximum, so take it from there. Each entry is a command header and a payload of at most u16::MAX bytes. A submission holds at most MAX_COMMANDS_PER_SUBMISSION work commands, and the rest of the stream sets what the work commands after it use: three attachment lists, the render resources and the compute resources. A set that a later one replaces before any work, or one after the last work command, changes nothing. The largest stream in which every entry has an effect is therefore 64 work commands, each after at most one set of each of the five kinds, every entry at its largest: 64 * 6 * (8 + 65535) bytes, about 24 MiB. A build-time assert keeps it within INT_MAX, the kvmalloc() limit, and on arm64 also within KMALLOC_MAX_SIZE, which depends on the architecture's page orders. Longer streams only repeat sets, so refuse them with E2BIG before copying, as G16 does with its own 4 MiB bound. The asahi-m4 command-stream selftest builds the G17 parser on the host; it now also takes ATTACHMENT_KINDS from the source. A KUnit test parses a submission of 64 largest work commands, checks that it fits the bound, and checks that a 65th is refused. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/command.rs | 65 ++++++++++++++++++- drivers/gpu/drm/asahi/g17/mod.rs | 4 ++ .../gpu/asahi-m4/test-command-stream.py | 2 +- 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/command.rs b/drivers/gpu/drm/asahi/g17/command.rs index da60d6b456d7eb..333ce9af520393 100644 --- a/drivers/gpu/drm/asahi/g17/command.rs +++ b/drivers/gpu/drm/asahi/g17/command.rs @@ -15,6 +15,26 @@ use super::render_resources::{ComputePrograms, Programs}; const _: () = assert!(uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_AS_BUILD == 1 << 2); +/// The vertex, fragment and compute attachment lists a [`Parser`] keeps. +const ATTACHMENT_KINDS: usize = 3; +/// What a stream sets for the work commands after it: the attachment lists, the render +/// resources (either version) and the compute resources. +const SET_KINDS: usize = ATTACHMENT_KINDS + 2; + +/// The largest command stream in which every entry has an effect: as many work commands as +/// a submission may hold, each after at most one set of each kind, and every entry at its +/// largest. A set that a later one replaces before any work, or one after the last work +/// command, changes nothing, so a longer stream only repeats them. The submit ioctl refuses +/// a longer stream before copying it. +pub(crate) const MAX_STREAM: usize = crate::file::MAX_COMMANDS_PER_SUBMISSION as usize + * (1 + SET_KINDS) + * (size_of::() + u16::MAX as usize); +// kvmalloc() warns past INT_MAX. A plain kmalloc() copy warns past KMALLOC_MAX_SIZE, which depends +// on the architecture; on arm64 with 16K pages, as Apple GPUs run, it is 32 MiB. +const _: () = assert!(MAX_STREAM <= i32::MAX as usize); +#[cfg(CONFIG_ARM64)] +const _: () = assert!(MAX_STREAM <= kernel::bindings::KMALLOC_MAX_SIZE as usize); + const MAX_ATTACHMENTS: usize = crate::microseq::MAX_ATTACHMENTS; const USC_WINDOW_SIZE: u64 = 1 << 32; const MAX_SAMPLERS: u32 = 1024; @@ -184,7 +204,7 @@ pub(crate) struct Command { pub(crate) struct Parser<'a> { bytes: &'a [u8], counts: [u16; 2], - attachments: [Attachments; 3], + attachments: [Attachments; ATTACHMENT_KINDS], render_resources: Option>, compute_resources: Option>, } @@ -194,7 +214,7 @@ impl<'a> Parser<'a> { Self { bytes, counts: [0; 2], - attachments: [Attachments::EMPTY; 3], + attachments: [Attachments::EMPTY; ATTACHMENT_KINDS], render_resources: None, compute_resources: None, } @@ -878,3 +898,44 @@ mod attachment_tests { assert_eq!(list(&[]).validate_hint(), Ok(())); } } + +#[kunit_tests(asahi_g17_stream)] +mod stream_tests { + use super::*; + + const COMMANDS: usize = crate::file::MAX_COMMANDS_PER_SUBMISSION as usize; + + /// Appends a zeroed render command whose payload is `size` bytes long. + fn push_render(stream: &mut KVVec, size: u16) { + let render = uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER as u16; + // cmd_type, size, vdm_barrier, cdm_barrier. + for field in [render, size, 0, 0] { + stream.extend_from_slice(&field.to_le_bytes(), GFP_KERNEL).unwrap(); + } + stream.extend_with(size.into(), 0, GFP_KERNEL).unwrap(); + } + + fn parsed(stream: &[u8]) -> Result { + let mut parser = Parser::new(stream); + let mut count = 0; + while parser.next()?.is_some() { + count += 1; + } + parser.finish()?; + Ok(count) + } + + #[test] + fn the_largest_work_commands_a_submission_holds_fit_the_stream_bound() { + assert_eq!(size_of::(), 8); + let mut stream = KVVec::new(); + for _ in 0..COMMANDS { + push_render(&mut stream, u16::MAX); + } + assert_eq!(parsed(&stream), Ok(COMMANDS)); + assert!(stream.len() <= MAX_STREAM); + // One more work command is refused, so the bound counts every command it may hold. + push_render(&mut stream, size_of::() as u16); + assert_eq!(parsed(&stream), Err(EINVAL)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index d73d9cc68b5c97..b78e38cab8fd52 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2493,6 +2493,10 @@ impl Gpu { } impl gpu::Gpu for Gpu { + fn max_cmdbuf_size(&self) -> usize { + command::MAX_STREAM + } + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { self.shared.feed.wait_hint() } 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 b0c92c63fd0282..b2f6293acef69a 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 @@ -61,7 +61,7 @@ g17 = (ROOT / 'drivers/gpu/drm/asahi/g17/command.rs').read_text() # The stage-prefix offset and the render payload reader precede the parser. g17_parser = g17[g17.index('/// Where a render command\'s stage-prefix fields start'):g17.index('#[derive(Clone, Copy, PartialEq, Eq)]')] -g17_constants = '\n'.join(re.findall(r'const (?:RENDER_BASE_SIZE|COMPUTE_BASE_SIZE): usize = .*?;|const (?:RENDER_TIMESTAMP_COPIES|COMPUTE_TIMESTAMP_COPIES): Range = .*?;', g17, re.S)) +g17_constants = '\n'.join(re.findall(r'const (?:RENDER_BASE_SIZE|COMPUTE_BASE_SIZE|ATTACHMENT_KINDS): usize = .*?;|const (?:RENDER_TIMESTAMP_COPIES|COMPUTE_TIMESTAMP_COPIES): Range = .*?;', g17, re.S)) reader = (ROOT / 'drivers/gpu/drm/asahi/util.rs').read_text() reader = reader[reader.index('pub(crate) unsafe trait AnyBitPattern:'):] harness = r''' From b30c01cad8473de0326dd5896a96936e98315026 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 16:43:25 -0500 Subject: [PATCH 0707/1514] PCI: allow host bridges to preserve firmware bus numbers Add a per-host-bridge no_reassign_bus flag to struct pci_host_bridge and honor it in pci_scan_bridge_extend() alongside pcibios_assign_all_busses(). This lets a host controller that must preserve bootloader-assigned bus numbers opt out of bus renumbering for its own hierarchy without clearing the global PCI_REASSIGN_ALL_BUS flag for unrelated PCI host bridges in the same system. Signed-off-by: Satya Benson --- drivers/pci/probe.c | 6 ++++-- include/linux/pci.h | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index d625dd5e778a83..c38a60df06d81d 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -1402,6 +1402,8 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, u8 primary, secondary, subordinate; int broken = 0; bool fixed_buses; + bool reassign = pcibios_assign_all_busses() && + !pci_find_host_bridge(bus)->no_reassign_bus; u8 fixed_sec, fixed_sub; int next_busnr; @@ -1449,7 +1451,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, } if ((secondary || subordinate) && - !pcibios_assign_all_busses() && !broken) { + !reassign && !broken) { unsigned int cmax, buses; /* @@ -1491,7 +1493,7 @@ static int pci_scan_bridge_extend(struct pci_bus *bus, struct pci_dev *dev, * do in the second pass. */ if (!pass) { - if (pcibios_assign_all_busses() || broken) + if (reassign || broken) /* * Temporarily disable forwarding of the diff --git a/include/linux/pci.h b/include/linux/pci.h index c0d76d93a78f50..eb2ccfc21b750f 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -676,6 +676,8 @@ struct pci_host_bridge { * Immutable after probing; driver-coordinated resets remain permitted. */ unsigned int reset_sensitive:1; + /* Keep firmware-assigned bus numbers on this host bridge hierarchy. */ + unsigned int no_reassign_bus:1; /* Resource alignment requirements */ resource_size_t (*align_resource)(struct pci_dev *dev, From 0c355d539c7f030e10439bcb57776e0b579abe1b Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 16:43:25 -0500 Subject: [PATCH 0708/1514] PCI: apple: keep bootloader bus numbers on adopted hosts When a host uses adopt_link, the firmware-handed device tree's iommu-map names each adopted endpoint by the RID the bootloader assigned it, and the RID-to-SID routes are programmed for that RID. If PCI_REASSIGN_ALL_BUS is set, pci_scan_bridge_extend() renumbers buses across only the adopted root ports, changing the secondary bus whenever the bootloader numbered a port that Linux does not adopt (for example after a reset where only a subset of links trained) and leaving endpoints unreachable. Set bridge->no_reassign_bus on adopt_link hosts before calling pci_host_common_init() so only adopted hierarchies keep the bootloader's bus numbers while non-adopted controllers keep normal bus assignment. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index cd41ec78277d67..5ae2761e62c00a 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -5734,11 +5734,25 @@ int apple_pcie_t6050_port_recycle(struct pci_dev *bridge) } EXPORT_SYMBOL_GPL(apple_pcie_t6050_port_recycle); +/* + * An adopting host must keep the bootloader's bus numbers: the handed-over + * device tree's iommu-map names each adopted endpoint by the RID the + * bootloader gave it, and the RID-to-SID routes are programmed for that RID. + * Reassigning bus numbers over only the adopted root ports changes the + * secondary bus whenever the bootloader numbered a port that Linux does not + * adopt (for example after a reset where only a subset of links trained), + * leaving the endpoint unreachable because config cycles go only to the + * adopted bus. + */ static int apple_pcie_host_init(struct platform_device *pdev, struct pci_host_bridge *bridge) { struct apple_pcie *pcie = pci_host_bridge_priv(bridge); - int ret = pci_host_common_init(pdev, bridge, &apple_pcie_cfg_ecam_ops); + int ret; + + if (pcie->hw->adopt_link) + bridge->no_reassign_bus = true; + ret = pci_host_common_init(pdev, bridge, &apple_pcie_cfg_ecam_ops); if (!ret && pcie->hw->adopt_link) pci_walk_bus(bridge->bus, apple_pcie_adopted_no_clkpm_walk, NULL); return ret; From 5436ab37740a1fc680272c695420deb0fddf9226 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 17:36:50 -0300 Subject: [PATCH 0709/1514] drm/asahi: g17: charge a submission's resource tables to the caller SET_RENDER_RESOURCES, SET_RENDER_RESOURCES_V2 and SET_COMPUTE_RESOURCES each copy a program table from the command stream into a KVec. The table is as long as userspace makes the command, up to its u16 size, and the legacy render records are widened to the 104-byte v2 form, so one table can need more than 64 KiB of contiguous pages. Nothing reads it except the submission that carries it. Make the tables KVVecs, so a large one does not need contiguous pages, and charge them to the caller's memory cgroup (GFP_KERNEL_ACCOUNT), since userspace decides their size, and so are the Arcs that hold them. They are released with the parsed command, in the ioctl or with its job's packet, where vfree() may sleep. KUnit cases parse the largest legacy, v2 and compute tables a command can carry and check the widened legacy table outgrows its command. The asahi-m4 command-stream selftest, which builds the parser on the host, gets the GFP_KERNEL_ACCOUNT stand-in. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/command.rs | 8 +- drivers/gpu/drm/asahi/g17/render_resources.rs | 75 ++++++++++++++++--- .../gpu/asahi-m4/test-command-stream.py | 1 + 3 files changed, 71 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/command.rs b/drivers/gpu/drm/asahi/g17/command.rs index da60d6b456d7eb..1437fe00429c1d 100644 --- a/drivers/gpu/drm/asahi/g17/command.rs +++ b/drivers/gpu/drm/asahi/g17/command.rs @@ -290,19 +290,21 @@ impl<'a> Parser<'a> { return Err(EINVAL); } self.render_resources = if bytes.is_empty() { None } - else { Some(Arc::new(Programs::parse(bytes)?, GFP_KERNEL)?) }; + else { Some(Arc::new(Programs::parse(bytes)?, GFP_KERNEL_ACCOUNT)?) }; } uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_RENDER_RESOURCES_V2 => { if barriers != [uapi::DRM_ASAHI_BARRIER_NONE as u16; 2] { return Err(EINVAL); } self.render_resources = if bytes.is_empty() { None } - else { Some(Arc::new(Programs::parse_v2(bytes)?, GFP_KERNEL)?) }; + else { Some(Arc::new(Programs::parse_v2(bytes)?, GFP_KERNEL_ACCOUNT)?) }; } uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMPUTE_RESOURCES => { if barriers != [uapi::DRM_ASAHI_BARRIER_NONE as u16; 2] { return Err(EINVAL); } self.compute_resources = if bytes.is_empty() { None } - else { Some(Arc::new(ComputePrograms::parse(bytes)?, GFP_KERNEL)?) }; + else { + Some(Arc::new(ComputePrograms::parse(bytes)?, GFP_KERNEL_ACCOUNT)?) + }; } _ => return Err(EINVAL), } diff --git a/drivers/gpu/drm/asahi/g17/render_resources.rs b/drivers/gpu/drm/asahi/g17/render_resources.rs index fb9f6a2bfd5042..d5396935dc21a5 100644 --- a/drivers/gpu/drm/asahi/g17/render_resources.rs +++ b/drivers/gpu/drm/asahi/g17/render_resources.rs @@ -17,28 +17,29 @@ unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_render_program {} unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_render_program_v2 {} pub(crate) struct Programs { - entries: KVec, + /// As many as userspace sends in one command: charged to it, no contiguous pages. + entries: KVVec, } impl Programs { pub(crate) fn parse(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_render_program = reader.read()?; Self::validate(&entry)?; - entries.push(Self::wrap(entry), GFP_KERNEL)?; + entries.push(Self::wrap(entry), GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } pub(crate) fn from_entries(values: &[uapi::drm_asahi_render_program]) -> Result { if values.is_empty() { return Err(EINVAL); } - let mut entries = KVec::with_capacity(values.len(), GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(values.len(), GFP_KERNEL_ACCOUNT)?; for entry in values { Self::validate(entry)?; - entries.push(Self::wrap(*entry), GFP_KERNEL)?; + entries.push(Self::wrap(*entry), GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } @@ -54,7 +55,7 @@ impl Programs { pub(crate) fn parse_v2(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_render_program_v2 = reader.read()?; @@ -76,7 +77,7 @@ impl Programs { || (!scratch.enabled() && (entry.scs_layout != 0 || entry.auxiliary_allocation != 0)) { return Err(EINVAL); } - entries.push(entry, GFP_KERNEL)?; + entries.push(entry, GFP_KERNEL_ACCOUNT)?; } let programs = Self { entries }; // A render kick has one SCS layout and one intersection-table binding @@ -304,19 +305,73 @@ impl M5Policy { unsafe impl crate::util::AnyBitPattern for uapi::drm_asahi_compute_program {} pub(crate) struct ComputePrograms { - entries: KVec, + /// As many as userspace sends in one command: charged to it, no contiguous pages. + entries: KVVec, } impl ComputePrograms { pub(crate) fn parse(bytes: &[u8]) -> Result { let stride = size_of::(); if bytes.is_empty() || bytes.len() % stride != 0 { return Err(EINVAL); } - let mut entries = KVec::with_capacity(bytes.len() / stride, GFP_KERNEL)?; + let mut entries = KVVec::with_capacity(bytes.len() / stride, GFP_KERNEL_ACCOUNT)?; let mut reader = Reader::new(bytes); for _ in 0..bytes.len() / stride { let entry: uapi::drm_asahi_compute_program = reader.read()?; if entry.flags != 0 || entry.threads == 0 { return Err(EINVAL); } - entries.push(entry, GFP_KERNEL)?; + entries.push(entry, GFP_KERNEL_ACCOUNT)?; } Ok(Self { entries }) } } + +#[kunit_tests(asahi_g17_render_resources)] +mod tests { + use super::*; + + /// The largest table a command can carry (its header's size is a u16), of zeroed records. + fn largest(stride: usize) -> KVVec { + let mut bytes = KVVec::new(); + bytes + .extend_with(u16::MAX as usize / stride * stride, 0, GFP_KERNEL) + .unwrap(); + bytes + } + + #[test] + fn the_largest_legacy_render_table_is_widened_whole() { + let stride = size_of::(); + let bytes = largest(stride); + let programs = Programs::parse(&bytes).unwrap(); + assert_eq!(programs.entries.len(), bytes.len() / stride); + // Widened to the v2 records: larger than the command that carried them. + assert!( + programs.entries.len() * size_of::() + > u16::MAX as usize + ); + assert_eq!(Programs::parse(&bytes[..stride + 1]).err(), Some(EINVAL)); + assert_eq!(Programs::parse(&[]).err(), Some(EINVAL)); + } + + #[test] + fn the_largest_v2_render_table_parses() { + let stride = size_of::(); + let bytes = largest(stride); + assert_eq!(Programs::parse_v2(&bytes).unwrap().entries.len(), bytes.len() / stride); + assert_eq!(Programs::parse_v2(&bytes[..stride - 1]).err(), Some(EINVAL)); + } + + #[test] + fn the_largest_compute_table_parses() { + let stride = size_of::(); + let mut bytes = largest(stride); + let threads = core::mem::offset_of!(uapi::drm_asahi_compute_program, threads); + for record in bytes.chunks_exact_mut(stride) { + record[threads..threads + 4].copy_from_slice(&1u32.to_le_bytes()); + } + let programs = ComputePrograms::parse(&bytes).unwrap(); + assert_eq!(programs.entries.len(), bytes.len() / stride); + // A program without threads is refused, wherever it is. + let last = bytes.len() - stride; + bytes[last + threads..last + threads + 4].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(ComputePrograms::parse(&bytes).err(), Some(EINVAL)); + } +} 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 b0c92c63fd0282..a6b18cf26494e1 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 @@ -99,6 +99,7 @@ const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const GFP_KERNEL: u32 = 0; + const GFP_KERNEL_ACCOUNT: u32 = 0; pub struct Arc(std::rc::Rc); impl Arc { fn new(value: T, _: u32) -> Result { Ok(Self(std::rc::Rc::new(value))) } } impl Clone for Arc { fn clone(&self) -> Self { Self(self.0.clone()) } } From 1485c6934f916c1b524fbec4b92a22a18b846a32 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Mon, 23 Nov 2026 20:06:08 +0100 Subject: [PATCH 0710/1514] accel/ane: T8142: apply engine bridge setup at power-up Without the T8142 engine bus-bridge setup (engine + 0x0000..0x400c), the bridge remains at its reset configuration after power-on and bottlenecks compute-bound ANE models by 1.4x-3.1x on T8142 (M5), even with the CLPC DCS/SOC floor active. Inspecting /arm-io/ane in the T8142 ADT shows no bridge tunable properties (only the ANE DARTs carry dart-tunables-instance-*), so the bootloader cannot supply these registers from ADT. Derive the 25 active register updates directly from clean-room Aura Stage-2 hypervisor MMIO traces of engine + 0x0000..0x401c across two consecutive ANE power-up cycles on J813 (T8142): each struct ane_fw_bridge_op records only the bits observed to change (clear = R32 & ~W32, set = W32 & ~R32), omitting the 8 traced no-op writes where W32 == R32 and preserving all unmodified reset bits without inferred field masks. Attach ane_t8142_bridge_ops[] to ANE_T8142_PLATFORM (shared across all T8142 boards and firmware builds), apply them via ane_fw_apply_bridge_ops() at the end of ane_fw_power_up() after CE bring-up so initial bring-up, parked wake, and post-sleep power cycles all receive them, and add the ane_t8142_bridge_ops_test KUnit test. Other H17 SoCs leave bridge_op_count == 0 and are unaffected. Standalone A/B on J813 (MacBook Air 13" M5, T8142, Linux 7.3.0-air-m5-pr3008+, schedutil, 200 runs, without the CLPC P-cluster floor): unet-320 p50 drops from 2594.4 us to 1023.2 us pinned cpu2 (2.54x) and 2634.0 us to 941.5 us unpinned (2.80x), denoise-320 from 4370.6 us to 1419.3 us (3.08x), and denoise-640 from 13841.8 us to 5246.5 us (2.64x), with bit-exact SHA-256 outputs across all 6 workloads and a 30 s deep sleep/resume cycle. Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 17 ++++++++- drivers/accel/ane/ane_fw_platform.c | 48 ++++++++++++++++++++++++ drivers/accel/ane/ane_fw_platform.h | 15 ++++++++ drivers/accel/ane/ane_fw_platform_test.c | 44 ++++++++++++++++++++++ 4 files changed, 122 insertions(+), 2 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 1c391f6c6b01f4..6b3686f1a01815 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1576,10 +1576,22 @@ static int ane_fw_power(struct ane_fw_backend *b, bool raw_boot) return ret; } +static void ane_fw_apply_bridge_ops(struct ane_fw_backend *b) +{ + unsigned int i; + + for (i = 0; i < b->soc->bridge_op_count; i++) { + const struct ane_fw_bridge_op *op = &b->soc->bridge_ops[i]; + void __iomem *reg = b->engine + op->offset; + + ane_wr32(b, ane_fw_bridge_op_apply(ane_rd32(b, reg), op), reg); + } +} + /* * ANE_SYS on, then the child power steps from the cold state, then (for a - * cold boot) the engine's reset values, and CE. At boot and again after a - * power-down for sleep. + * cold boot) the engine's reset values, CE, and any per-SoC engine bridge + * register updates. At boot and again after a power-down for sleep. */ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_engine) { @@ -1635,6 +1647,7 @@ static int ane_fw_power_up(struct ane_fw_backend *b, bool raw_boot, bool cold_en if ((ane_rd64(b, b->engine + 0x18a4010) & 3) != 3 || ane_rd64(b, b->engine + 0x18a4018)) return -EIO; + ane_fw_apply_bridge_ops(b); dev_dbg(dev, "ANE power: ANE_SYS on, child/PWGATE/CE ready\n"); return 0; } diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index b020192b4d8082..6f1d3a29161f2a 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -318,7 +318,55 @@ const struct ane_fw_platform ane_t6050_platform = { * T8140's order: sub-block, PWGATE request 3, acknowledge 0, CPU, then * ANE_SYS. So sleep and the parked start follow T8140. */ +/* + * T8142 engine bus-bridge setup (engine + 0x0000..0x400c), written after + * CE bring-up and before releasing the ANE CPU on every power-up. Without + * these register updates the bridge remains at its reset configuration and + * bottlenecks compute-bound models by 1.4x-3.1x on J813. + * + * Derived directly from clean-room Aura Stage-2 hypervisor MMIO traces of + * engine + 0x0000..0x401c across two consecutive ANE power-up cycles on + * J813 (T8142); /arm-io/ane in the T8142 ADT carries no bridge tunable + * properties. Each entry records only the bits observed to change + * (clear = R32 & ~W32, set = W32 & ~R32) on the 25 registers whose value + * changed (8 traced no-op writes where W32 == R32 are omitted), preserving + * all unmodified reset bits without inferred field masks. + */ +static const struct ane_fw_bridge_op ane_t8142_bridge_ops[] = { + /* Engine bridge block +0x0000..0x0034. */ + { 0x0000, 0x00000000, 0x8000001a }, + { 0x0004, 0x00000002, 0x800c000c }, + { 0x0008, 0x00000002, 0x800c000c }, + { 0x000c, 0x00000002, 0x800c000c }, + { 0x0010, 0x00000000, 0x80000001 }, + { 0x0014, 0x00000000, 0x80000001 }, + { 0x0018, 0x00000008, 0x80000012 }, + { 0x001c, 0x00000000, 0x80000010 }, + { 0x0020, 0x00000002, 0x8010000c }, + { 0x0024, 0x00000002, 0x80000004 }, + { 0x0028, 0x00000002, 0x80000004 }, + { 0x002c, 0x00000000, 0x80000004 }, + { 0x0030, 0x00000008, 0x80000010 }, + { 0x0034, 0x00000008, 0x80000010 }, + /* Engine bridge block +0x0100..0x0108. */ + { 0x0100, 0x00000000, 0x000000ff }, + { 0x0104, 0x00000000, 0x00000003 }, + { 0x0108, 0x00000006, 0x00000001 }, + /* Engine bridge block +0x0300..0x0404. */ + { 0x0300, 0x00000000, 0x1c000001 }, + { 0x0304, 0x00000000, 0x02020000 }, + { 0x0314, 0x00000000, 0x80000000 }, + { 0x031c, 0x00000000, 0x80000000 }, + { 0x0324, 0x00000000, 0x80000000 }, + { 0x0404, 0xffee0000, 0x00000041 }, + /* Engine bridge registers +0x0b00 and +0x400c. */ + { 0x0b00, 0x00000000, 0x7fffffff }, + { 0x400c, 0x00000001, 0x00000000 }, +}; + #define ANE_T8142_PLATFORM \ + .bridge_ops = ane_t8142_bridge_ops, \ + .bridge_op_count = ARRAY_SIZE(ane_t8142_bridge_ops), \ .soc = 0x8142, \ .chip_family = 17, \ .ane_type = 0x210, \ diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h index f203f426a91844..483f2aef828db8 100644 --- a/drivers/accel/ane/ane_fw_platform.h +++ b/drivers/accel/ane/ane_fw_platform.h @@ -27,6 +27,12 @@ enum ane_fw_irq_role { ANE_FW_IRQ_CHANNELS, }; +struct ane_fw_bridge_op { + u32 offset; + u32 clear; + u32 set; +}; + /* Later firmware generations must never enter the H14 staging path. */ struct ane_fw_platform { const struct ane_h16_profile *h16_profiles; @@ -34,6 +40,9 @@ struct ane_fw_platform { /* DART/DAPF register tables, one per supported DART revision. */ const struct ane_h16_mmio *h16_mmio; unsigned int h16_mmio_count; + /* Engine AXI2AF bridge register updates applied after CE bring-up at every power-up. */ + const struct ane_fw_bridge_op *bridge_ops; + unsigned int bridge_op_count; /* DART PARAMS3, the one DART register read before a table is chosen. */ u32 dart_params; /* The DAPF bank: iommus entry that owns it, offset from its reg, size. */ @@ -125,6 +134,12 @@ struct ane_fw_platform { const char *build_name; }; +static inline u32 ane_fw_bridge_op_apply(u32 current_val, + const struct ane_fw_bridge_op *op) +{ + return (current_val & ~op->clear) | op->set; +} + /* Pure range check: the boot loader supplies the physical addresses. */ static inline bool ane_fw_preload_ranges_valid(const struct ane_fw_platform *soc, const u64 phys[2], diff --git a/drivers/accel/ane/ane_fw_platform_test.c b/drivers/accel/ane/ane_fw_platform_test.c index 8dda9aed1aeb49..70e7bc1167e29a 100644 --- a/drivers/accel/ane/ane_fw_platform_test.c +++ b/drivers/accel/ane/ane_fw_platform_test.c @@ -174,6 +174,49 @@ static void ane_t6050_builds_test(struct kunit *test) i == j); } } + +/* + * T8142: both firmware builds carry the AXI2AF bridge register updates with + * aligned offsets inside the engine window, disjoint clear/set masks, and + * non-empty transitions; other H17 platforms stay untouched. + */ +static void ane_t8142_bridge_ops_test(struct kunit *test) +{ + const struct ane_fw_platform *b27_0 = &ane_t8142_platform, *b27_2 = b27_0->next_build; + const struct ane_fw_platform *builds[] = { b27_0, b27_2 }; + unsigned int i, j; + + KUNIT_ASSERT_NOT_NULL(test, b27_2); + KUNIT_EXPECT_NULL(test, b27_2->next_build); + KUNIT_EXPECT_EQ(test, ane_h17_platform.bridge_op_count, 0U); + KUNIT_EXPECT_EQ(test, ane_t6050_platform.bridge_op_count, 0U); + for (i = 0; i < ARRAY_SIZE(builds); i++) { + const struct ane_fw_platform *b = builds[i]; + + KUNIT_EXPECT_EQ(test, b->soc, 0x8142U); + KUNIT_ASSERT_NOT_NULL(test, b->bridge_ops); + KUNIT_ASSERT_EQ(test, b->bridge_op_count, 25U); + for (j = 0; j < b->bridge_op_count; j++) { + const struct ane_fw_bridge_op *op = &b->bridge_ops[j]; + + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(op->offset, 4)); + KUNIT_EXPECT_LE(test, op->offset + 4, b->reg_sizes[0]); + KUNIT_EXPECT_EQ(test, op->clear & op->set, 0U); + KUNIT_EXPECT_NE(test, op->clear | op->set, 0U); + } + } + /* Preserves untouched reset bits and stays idempotent once applied. */ + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x10000008U, &b27_0->bridge_ops[12]), + 0x90000010U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x90000010U, &b27_0->bridge_ops[12]), + 0x90000010U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x000413b6U, &b27_0->bridge_ops[16]), + 0x000413b1U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0xffff0030U, &b27_0->bridge_ops[22]), + 0x00110071U); + KUNIT_EXPECT_EQ(test, ane_fw_bridge_op_apply(0x00000001U, &b27_0->bridge_ops[24]), + 0x00000000U); +} #endif static struct kunit_case ane_fw_platform_cases[] = { @@ -181,6 +224,7 @@ static struct kunit_case ane_fw_platform_cases[] = { KUNIT_CASE(ane_t8132_platform_test), KUNIT_CASE(ane_t8132_builds_test), KUNIT_CASE(ane_t6050_builds_test), + KUNIT_CASE(ane_t8142_bridge_ops_test), #endif KUNIT_CASE(ane_platform_staged_bind_test), KUNIT_CASE(ane_platform_sleep_path_test), From defa62d30d996c993b6f1b5b34111eaaafe6d47c Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 21:59:26 +0000 Subject: [PATCH 0711/1514] arm64: dts: apple: t6041: wire pmc_soc_max perf floor to the Neural Engine Wire the T6041 SoC fabric VMAX floor (&pmc_soc_max, rail 1 state 2, 815 mV / 2004 MHz SOC_AFC) as the optional sixth "perf" power domain on &ane, matching &avd and &ave in t6041.dtsi and &ane on T6040. The H16 ANE backend (ane_h16_backend.c) already attaches the "perf" domain when six power-domains and power-domain-names are provided, holding it only while EXECUTE requests are in flight with a 100 ms autosuspend delay. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041.dtsi | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 6d3b1605927cd8..e79cafa256a1e0 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -20,6 +20,12 @@ power-domain-names = "dma", "pipe4", "pipe5", "me0", "me1", "perf"; }; +&ane { + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>, <&pmc_soc_max>; + power-domain-names = "sys", "cpu", "mpm", "td", "base", "perf"; +}; + /* * The main PMIC is a Chapel at 0xb (ADT nub-spmi0 spmi-chapelL1-b), not the * J616s's Abbey at 0xe. Its nvmem cells and RTC alarm registers are at the From c6f184698a7e95e6f2d1ed490abfd077f07d5781 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 21:41:19 +0000 Subject: [PATCH 0712/1514] drm/asahi: g17: lift CLPC busy share immediately when a sustained busy run begins When a light desktop compositor keeps BusyShare below the top CLPC memory and fabric column (e.g. DCS 1 / fabric 0 on T6041), BusyShare::sample() only lifts early mid-window if a single unretired command exceeds BUSY_LONG_COMMAND_NS (50 ms). A burst of short (<50 ms) back-to-back compute or render dispatches therefore stays trapped at a low memory and fabric floor for up to BUSY_WINDOW_NS (200 ms), or longer if prior idle time dilutes the closing window, even after BusyRuns::bound has already raised GPU core effort to FULL_EFFORT at 16 ms. Add BusyShare::lift_saturated() and Port::lift_busy_if_below_top() so that once BusyRuns::bound becomes true while below the top CLPC column, the driver immediately reports 1000 permille and re-baselines the 200 ms measurement window. Paced compositors never trigger BusyRuns::bound, and the next 200 ms window returns cleanly to the lower column once the burst ends. Add a KUnit test covering the mid-window lift and return to light activity. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/mod.rs | 9 +++- drivers/gpu/drm/asahi/g17/port.rs | 22 ++++++++++ drivers/gpu/drm/asahi/g17/power.rs | 61 ++++++++++++++++++++++++++++ drivers/gpu/drm/asahi/g17/runtime.rs | 6 ++- 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 53f127f188b589..6310cda69865e2 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -949,12 +949,16 @@ impl Firmware { /// Called at actual submission publication, not while a queued job is merely being built. fn note_submission(&mut self) -> Result { + let now = now_ns(); self.primary.state.shared.note_submitter(); self.port.note_gpu_activity(); self.primary.state.shared.note_gpu_activity(); self.effort.submit(); - self.effort.note_waiters(now_ns(), fence::waiters()); + self.effort.note_waiters(now, fence::waiters()); self.effort.note_bound(self.primary.state.shared.feed.busy_run()); + if self.effort.bound() { + self.port.lift_busy_if_below_top(now); + } self.apply_effort(power::FULL_EFFORT) } @@ -1057,6 +1061,9 @@ impl Firmware { if self.effort.streaming() { let waiters = self.effort.note_waiters(now_ns, fence::waiters()); let bound = self.effort.note_bound(self.primary.state.shared.feed.busy_run()); + if self.effort.bound() { + self.port.lift_busy_if_below_top(now_ns); + } if waiters || bound { self.apply_effort(power::FULL_EFFORT)?; } diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 2a535f81429c8b..51ba0302762907 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -630,6 +630,28 @@ impl Port { .store(busy.below_top(), Ordering::Relaxed); } + /// Lifts CLPC to the top memory/fabric column immediately when a sustained busy run + /// ([`super::power::BusyRuns::bound`]) begins while the last reported share is below + /// the top column. Lock-free once at the top column. + pub(super) fn lift_busy_if_below_top(&self, now_ns: u64) { + if !self.demand.has_provider() || !self.busy_below_top.load(Ordering::Relaxed) { + return; + } + let retired = crate::usage::ENGINE_NS + .each_ref() + .map(|ns| ns.load(Ordering::Acquire)); + let oldest = self.qos.lock().oldest_in_flight(); + let now_ns = super::now_ns().max(now_ns); + let mut busy = self.busy.lock(); + if let Some(permille) = busy.lift_saturated(now_ns, retired, oldest) { + self.demand.set_busy(permille); + } + self.busy_window_start + .store(busy.window_start().map_or(0, |s| s.max(1)), Ordering::Relaxed); + self.busy_below_top + .store(busy.below_top(), Ordering::Relaxed); + } + /// Wake delay (ns) for `idle_check` while a solo long command is running below /// the top CLPC busy column, or `None` when already at top or idle. pub(super) fn busy_recheck_delay(&self, now_ns: u64) -> Option { diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index cf1fe38cbea5e7..cc3137b8a36b9e 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -474,6 +474,33 @@ impl BusyShare { self.below_top } + /// Immediately lifts the reported share to 1000 permille when a sustained busy run + /// ([`BusyRuns::bound`]) begins while below the top CLPC column, and re-baselines the + /// measurement window at `now_ns` so short back-to-back commands are neither trapped + /// at a low memory/fabric floor for up to [`BUSY_WINDOW_NS`] nor diluted by prior + /// light activity. + pub(super) fn lift_saturated( + &mut self, + now_ns: u64, + retired_ns: [u64; crate::usage::NUM_ENGINES], + oldest_in_flight: [u64; crate::usage::NUM_ENGINES], + ) -> Option { + if !self.below_top { + return None; + } + self.start_ns = Some(now_ns); + self.retired_ns = retired_ns; + for (slot, &since) in self.in_flight_ns.iter_mut().zip(oldest_in_flight.iter()) { + *slot = if since != 0 { + now_ns.saturating_sub(since) + } else { + 0 + }; + } + self.below_top = false; + Some(1000) + } + pub(super) fn window_start(&self) -> Option { self.start_ns } @@ -848,6 +875,40 @@ mod tests { assert_eq!(share.sample(2190 * NS_MS, [0, 414 * NS_MS, 0], [0, 0, 0]), None); assert_eq!(share.sample(2200 * NS_MS, [0, 420 * NS_MS, 0], [0, 0, 0]), Some(600)); } + + #[test] + fn sustained_busy_run_lifts_short_dispatches_mid_window() { + const NS_MS: u64 = 1_000_000; + let mut share = BusyShare::new(); + // Light compositor establishes a 50 permille floor (below top). + assert_eq!(share.sample(1000 * NS_MS, [0, 0, 0], [0, 0, 0]), None); + assert_eq!(share.sample(1200 * NS_MS, [0, 10 * NS_MS, 0], [0, 0, 0]), Some(50)); + assert!(share.below_top()); + // Short (<50 ms) compute dispatches saturate the GPU starting at t=1300 ms. + // At t=1316 ms BusyRuns::bound triggers lift_saturated(), lifting immediately. + assert_eq!( + share.lift_saturated(1316 * NS_MS, [0, 14 * NS_MS, 16 * NS_MS], [0, 0, 0]), + Some(1000) + ); + assert!(!share.below_top()); + // Repeated calls while already at top are a no-op. + assert_eq!( + share.lift_saturated(1332 * NS_MS, [0, 14 * NS_MS, 32 * NS_MS], [0, 0, 0]), + None + ); + // The re-baselined 200 ms window [1316, 1516] measures the burst cleanly (1000 permille). + assert_eq!( + share.sample(1516 * NS_MS, [0, 14 * NS_MS, 216 * NS_MS], [0, 0, 0]), + Some(1000) + ); + assert!(!share.below_top()); + // Once the burst ends, the next window returns cleanly to the light compositor share. + assert_eq!( + share.sample(1716 * NS_MS, [0, 24 * NS_MS, 216 * NS_MS], [0, 0, 0]), + Some(50) + ); + assert!(share.below_top()); + } } unsafe extern "C" { diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index b7ad8e336735c3..eae53058170ac2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1597,12 +1597,16 @@ impl compute::Host for ComputeHost<'_> { self.port.notify(message) } fn note_submission(&mut self) -> Result { + let now = super::now_ns(); self.shared.note_submitter(); self.port.note_gpu_activity(); self.shared.note_gpu_activity(); self.effort.submit(); - self.effort.note_waiters(super::now_ns(), super::fence::waiters()); + self.effort.note_waiters(now, super::fence::waiters()); self.effort.note_bound(self.shared.feed.busy_run()); + if self.effort.bound() { + self.port.lift_busy_if_below_top(now); + } super::Firmware::apply_shared_effort(self.init, self.effort, self.port, super::power::FULL_EFFORT) } fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { From 301965e2dad8269550c37ad942b2d4446d1cc3be Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:39:18 -0500 Subject: [PATCH 0713/1514] thunderbolt: allow NHIs to opt into router DMA credit preferences Allow a host interface to opt into its host router's preferred DMA tunnel credit budget (`sw->max_dma_credits`) while preserving the 14-credit legacy default for other NHIs and routers without a preference. Apply the same helper to both DMA tunnel allocation and lane-adapter credit headroom reservation, keeping explicit `dma_credits` module-parameter overrides capped as before and using 0 to select the NHI policy. Apply the host NHI preference only on the host router (`!tb_route(sw)`), cap the helper at `TB_MAX_CREDITS` so `tb_available_credits()` and `tb_tunnel_alloc_dma()` always agree, and guard `credits > usb3 + pcie + spare` before dividing in `tb_available_credits()` so downstream or tight-budget routers cannot underflow `ndp`. Enable `use_dma_credit_preferences` uniformly for Apple USB4 NHIs in `apple_nhi_probe()` so every Apple host router uses its advertised USB4 buffer allocation preference (`baMaxHI`) while falling back to `TB_DMA_CREDITS` when zero. Signed-off-by: Satya Benson --- drivers/thunderbolt/apple.c | 1 + drivers/thunderbolt/tunnel.c | 40 ++++++++++++++++++++++++++---------- include/linux/thunderbolt.h | 2 ++ 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index e21cf99212ebae..475d773fc3cc11 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -2669,6 +2669,7 @@ static int apple_nhi_probe(struct platform_device *pdev) spin_lock_init(&anhi->nhi.lock); anhi->nhi.iommu_dma_protection = true; + anhi->nhi.use_dma_credit_preferences = true; /* * DP tunnel display support (and with it the host DP IN handling in * the connection manager) only where it is enabled and known to work. diff --git a/drivers/thunderbolt/tunnel.c b/drivers/thunderbolt/tunnel.c index dac96ef66149ea..0739d981d124ac 100644 --- a/drivers/thunderbolt/tunnel.c +++ b/drivers/thunderbolt/tunnel.c @@ -97,10 +97,10 @@ MODULE_PARM_DESC(dprx_timeout, "DPRX capability read timeout in ms, -1 waits forever (default: " __MODULE_STRING(TB_DPRX_TIMEOUT) ")"); -static unsigned int dma_credits = TB_DMA_CREDITS; +static unsigned int dma_credits; module_param(dma_credits, uint, 0444); -MODULE_PARM_DESC(dma_credits, "specify custom credits for DMA tunnels (default: " - __MODULE_STRING(TB_DMA_CREDITS) ")"); +MODULE_PARM_DESC(dma_credits, + "DMA tunnel credits (0: NHI policy, otherwise capped override)"); static bool bw_alloc_mode = true; module_param(bw_alloc_mode, bool, 0444); @@ -160,6 +160,28 @@ static inline unsigned int tb_usable_credits(const struct tb_port *port) return port->total_credits - port->ctl_credits; } +/* + * Preserve legacy defaults unless the NHI opts into router preferences. + * Only apply the host NHI opt-in to the host router itself so downstream + * routers keep their conservative DMA reservation, and cap at TB_MAX_CREDITS + * so reservations match what tb_tunnel_alloc_dma() can program into a hop. + */ +static unsigned int tb_dma_credits(const struct tb_switch *sw) +{ + unsigned int credits = dma_credits; + + if (!credits) { + if (!tb_route(sw) && sw->tb && sw->tb->nhi && + sw->tb->nhi->use_dma_credit_preferences) + credits = sw->max_dma_credits; + if (!credits) + credits = TB_DMA_CREDITS; + } + + credits = min_not_zero(credits, sw->max_dma_credits); + return min_t(unsigned int, credits, TB_MAX_CREDITS); +} + /** * tb_available_credits() - Available credits for PCIe and DMA * @port: Lane adapter to check @@ -179,7 +201,7 @@ static unsigned int tb_available_credits(const struct tb_port *port, pcie = tb_acpi_may_tunnel_pcie() ? sw->max_pcie_credits : 0; if (tb_acpi_is_xdomain_allowed()) { - spare = min_not_zero(sw->max_dma_credits, dma_credits); + spare = tb_dma_credits(sw); /* Add some credits for potential second DMA tunnel */ spare += TB_MIN_DMA_CREDITS; } else { @@ -192,7 +214,8 @@ static unsigned int tb_available_credits(const struct tb_port *port, * Maximum number of DP streams possible through the * lane adapter. */ - if (sw->min_dp_aux_credits + sw->min_dp_main_credits) + if (sw->min_dp_aux_credits + sw->min_dp_main_credits && + credits > usb3 + pcie + spare) ndp = (credits - (usb3 + pcie + spare)) / (sw->min_dp_aux_credits + sw->min_dp_main_credits); else @@ -2549,12 +2572,7 @@ struct tb_tunnel *tb_tunnel_alloc_dma(struct tb *tb, struct tb_port *nhi, tunnel->dst_port = dst; tunnel->destroy = tb_dma_destroy; - credits = min_not_zero(dma_credits, nhi->sw->max_dma_credits); - if (credits > TB_MAX_CREDITS) { - tb_tunnel_dbg(tunnel, "%u credits do not fit a hop, using %u\n", - credits, TB_MAX_CREDITS); - credits = TB_MAX_CREDITS; - } + credits = tb_dma_credits(nhi->sw); if (receive_ring > 0) { path = tb_path_alloc(tb, dst, receive_path, nhi, receive_ring, 0, diff --git a/include/linux/thunderbolt.h b/include/linux/thunderbolt.h index bf1b07f993b8e8..41496caea46e3f 100644 --- a/include/linux/thunderbolt.h +++ b/include/linux/thunderbolt.h @@ -519,6 +519,7 @@ void tb_service_properties_changed(struct tb_service *svc); * @iommu_dma_protection: An IOMMU will isolate external-facing ports. * @interrupt_work: Work scheduled to handle ring interrupt when no * MSI-X is used. + * @use_dma_credit_preferences: Use the router preferred DMA credit allocation * @hop_count: Number of rings (end point hops) supported by NHI. * @quirks: NHI specific quirks if any * @host_dp_policy: Host display tunnel policies supplied by the NHI glue @@ -542,6 +543,7 @@ struct tb_nhi { bool iommu_dma_protection; struct work_struct interrupt_work; u32 hop_count; + bool use_dma_credit_preferences; unsigned long quirks; unsigned long host_dp_policy; bool host_dp_dual_stream; From 5bf9b71aee899207c72c1fa274fbef91cbf1bfe4 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 21:43:48 +0000 Subject: [PATCH 0714/1514] drm/asahi: mmu: cache dcache line size and stream scatterlist page-table maps Mapping a multi-segment shmem GEM BO through VmInner::sm_step_map() or VmInner::map_node_prepared() previously invoked UatPageTable::map_pages() once per scatterlist segment. On SoCs with UatQuirks::clean_tables (such as T6041/G17P), every individual 16 KiB segment performed a full L0->L1->L2 walk, an FFI call to read_sanitised_ftr_reg(SYS_CTR_EL0), redundant dc cvac maintenance on the same 64-byte leaf-table cache lines, and a system-wide dsb sy barrier. Cache the sanitized DminLine cache-line stride in an AtomicUsize, add UatPageTable::map_segments() (backed by a streaming SegmentCursor with KUnit coverage) to fill all scatterlist segments in a single walk with one PoC clean per leaf-table slice and a single final dsb sy barrier, and switch sm_step_map() and map_node_prepared() to use it. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/mmu.rs | 109 ++++-------------- drivers/gpu/drm/asahi/pgtable.rs | 189 ++++++++++++++++++++++++++++++- 2 files changed, 209 insertions(+), 89 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index a3b98ca76fc1a6..65587d80cfc785 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -671,9 +671,8 @@ impl gpuvm::DriverGpuVm for VmInner { ).map_err(|_| EOVERFLOW)? + 1; let _mutation = self.mapping_addition(); let (map_addr, map_length) = (op.addr(), op.length() as usize); - let mut iova = op.addr(); let mut left = op.length() as usize; - let mut offset = op.gem_offset() as usize; + let offset = op.gem_offset() as usize; let one_page = op.flags().contains(gpuvm::GpuVaFlag::REPEAT); @@ -696,7 +695,7 @@ impl gpuvm::DriverGpuVm for VmInner { if is_sparse_tile(op.flags()) { // Kernel tile fill: the GEM only anchors the GPUVA. let result = if one_page { - self.map_sparse_tile(iova..iova + left as u64, ctx.prot) + self.map_sparse_tile(map_addr..map_addr + left as u64, ctx.prot) } else { Err(EINVAL) }; @@ -710,53 +709,25 @@ impl gpuvm::DriverGpuVm for VmInner { // Never acquire the object reservation from inside the GPUVM map callback. let segments = op.vm_bo().data().segments.lock(); let sgt = segments.as_ref().ok_or(EFAULT)?; - for &(dma_address, dma_len) in sgt.iter() { - let mut addr = dma_address as usize; - let mut len = dma_len as usize; - - if left == 0 { - break; - } - - if offset > 0 { - let skip = len.min(offset); - addr += skip; - len -= skip; - offset -= skip; - } - if len == 0 { - continue; - } - - assert!(offset == 0); - - if one_page { - len = left; - } else { - len = len.min(left); - } - + if left > 0 { mod_dev_dbg!( self.dev, - "MMU: map: {:#x}:{:#x} -> {:#x} [OP={}]\n", - addr, - len, - iova, + "MMU: map_segments: {:#x}+{:#x} [OP={}]\n", + map_addr, + left, one_page ); - - if let Err(error) = self.page_table.map_pages( - iova..(iova + len as u64), - addr as PhysicalAddr, + if let Err(error) = self.page_table.map_segments( + map_addr..(map_addr + left as u64), + sgt.iter() + .map(|&(dma_address, dma_len)| (dma_address as PhysicalAddr, dma_len as usize)), + offset, ctx.prot, one_page, ) { self.rollback_failed_map(map_addr, map_length as u64); return Err(error); } - - left -= len; - iova += len as u64; } drop(segments); @@ -1140,7 +1111,7 @@ impl VmInner { /// Install only into the empty range reserved by `map_node`. fn map_node_prepared(&mut self, node: &mm::Node<(), KernelMappingInner>, prot: Prot) -> Result { - let mut iova = node.start(); + let iova = node.start(); let segments = node .bo .as_ref() @@ -1149,60 +1120,24 @@ impl VmInner { .data() .segments .lock(); - let mut offset = node.offset; - let mut left = node.mapped_size; if let Some(segments) = &*segments { - for (dma_address, dma_len) in segments.iter() { - if left == 0 { - break; - } - - // TODO: proper DMA address/length handling - let mut addr = *dma_address as usize; - let mut len: usize = *dma_len as usize; - - if (offset | addr | len | iova as usize) & UAT_PGMSK != 0 { - dev_err!( - self.dev.as_ref(), - "MMU: KernelMapping {:#x}:{:#x} -> {:#x} is not page-aligned\n", - addr, - len, - iova - ); - return Err(EINVAL); - } - - if offset > 0 { - let skip = len.min(offset); - addr += skip; - len -= skip; - offset -= skip; - } - - len = len.min(left); - - if len == 0 { - continue; - } - + if node.mapped_size > 0 { mod_dev_dbg!( self.dev, - "MMU: map: {:#x}:{:#x} -> {:#x}\n", - addr, - len, - iova + "MMU: map_node_prepared: {:#x}+{:#x}\n", + iova, + node.mapped_size ); - - self.page_table.map_pages( - iova..(iova + len as u64), - addr as PhysicalAddr, + self.page_table.map_segments( + iova..(iova + node.mapped_size as u64), + segments + .iter() + .map(|&(dma_address, dma_len)| (dma_address as PhysicalAddr, dma_len as usize)), + node.offset, prot, false, )?; - - iova += len as u64; - left -= len; } } diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 9fb2d0652e01eb..a6e757c22176a0 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -11,6 +11,7 @@ use core::mem::size_of; use core::ops::Range; use core::sync::atomic::{ AtomicU64, + AtomicUsize, Ordering, // }; @@ -54,10 +55,18 @@ const UAT_LEVELS: usize = 3; /// Number of address bits below the index of a top-level page table entry. pub(crate) const UAT_TOP_LEVEL_SHIFT: usize = UAT_PGBIT + (UAT_LEVELS - 1) * UAT_LVBIT; +/// Cached system-wide minimum CPU data cache line size (bytes), populated lazily from +/// the arm64 sanitized `CTR_EL0` feature register. +static DCACHE_LINE_SIZE: AtomicUsize = AtomicUsize::new(0); + /// The system-wide minimum CPU line size, including heterogeneous CPUs. A local /// CTR_EL0 read can select too large a stride if the task migrates during the loop. #[inline(always)] fn dcache_line_size() -> usize { + let cached = DCACHE_LINE_SIZE.load(Ordering::Relaxed); + if cached != 0 { + return cached; + } use kernel::bindings; let ctr = (bindings::SYS_CTR_EL0_Op0 << 19) | (bindings::SYS_CTR_EL0_Op1 << 16) @@ -65,9 +74,12 @@ fn dcache_line_size() -> usize { | (bindings::SYS_CTR_EL0_CRm << 8) | (bindings::SYS_CTR_EL0_Op2 << 5); // SAFETY: Read-only lookup of the arm64 sanitized feature register. DminLine - // uses the architecture's LOWER_SAFE merge policy across all admitted CPUs. + // uses the architecture's LOWER_SAFE merge policy across all admitted CPUs + // and remains constant once SMP boot has completed. let value = unsafe { bindings::read_sanitised_ftr_reg(ctr) }; - 4 << ((value >> bindings::CTR_EL0_DminLine_SHIFT) & 0xf) + let line = 4 << ((value >> bindings::CTR_EL0_DminLine_SHIFT) & 0xf); + DCACHE_LINE_SIZE.store(line, Ordering::Relaxed); + line } /// Cleans the CPU data cache lines covering `len` bytes at `ptr` to the point of coherency, for an @@ -1057,6 +1069,53 @@ impl UatPageTable { }) } + /// Maps a scatterlist of contiguous `(phys, len)` segments into `iova_range` in a single + /// page-table walk, emitting at most one point-of-coherency clean per leaf-table slice and + /// a single `dsb sy` barrier at the end instead of one walk and barrier per segment. + pub(crate) fn map_segments( + &mut self, + iova_range: Range, + segments: impl Iterator, + offset: usize, + prot: Prot, + one_page: bool, + ) -> Result { + if iova_range.is_empty() { + return Ok(()); + } + if (iova_range.start | iova_range.end) & (UAT_PGMSK as u64) != 0 || offset & UAT_PGMSK != 0 { + pr_err!( + "UATPageTable::map_segments: range {:#x?} or offset {:#x} not page-aligned\n", + iova_range, + offset + ); + return Err(EINVAL); + } + + let prot_bits = self.stored(prot).as_pte() | self.pte_bits(); + let mut cursor = SegmentCursor::new(segments, offset, one_page)?; + + self.walk(iova_range, true, false, true, |iova, ptes| { + for (idx, pte) in ptes.iter().enumerate() { + let phys = cursor.next_page(iova + (idx * UAT_PGSZ) as u64)?; + let ptev = pte.load(Ordering::Relaxed); + if ptev != 0 { + // Never replace a live leaf: it belongs to another mapping. The callers + // check their whole range first (`ensure_unmapped`), so this is reached + // only by a collision they missed. + pr_err!( + "UATPageTable::map_segments: Page at IOVA {:#x} is mapped (PTE: {:#x})\n", + iova + (idx * UAT_PGSZ) as u64, + ptev + ); + return Err(EBUSY); + } + pte.store(phys | prot_bits, Ordering::Relaxed); + } + Ok(()) + }) + } + /// Refuses with `EBUSY`, writing nothing, when any leaf of `iova_range` is live. /// /// Every PTE store writes either zero or a complete entry, so a nonzero leaf belongs to @@ -1162,3 +1221,129 @@ impl Drop for UatPageTable { } } } + +/// Streams page-aligned physical addresses out of a `(phys, len)` scatterlist iterator, +/// optionally repeating the first page after `offset` (`one_page`). +struct SegmentCursor { + segments: I, + cur_phys: PhysicalAddr, + cur_len: usize, + one_page: bool, +} + +impl> SegmentCursor { + fn new(mut segments: I, mut offset: usize, one_page: bool) -> Result { + if offset & UAT_PGMSK != 0 { + return Err(EINVAL); + } + let mut cur_phys: PhysicalAddr = 0; + let mut cur_len: usize = 0; + for (dma_addr, dma_len) in segments.by_ref() { + if (dma_addr & (UAT_PGMSK as PhysicalAddr)) != 0 || (dma_len & UAT_PGMSK) != 0 { + pr_err!( + "UATPageTable::map_segments: segment {:#x}:{:#x} not page-aligned\n", + dma_addr, + dma_len + ); + return Err(EINVAL); + } + let mut addr = dma_addr; + let mut len = dma_len; + if offset > 0 { + let skip = len.min(offset); + addr += skip as PhysicalAddr; + len -= skip; + offset -= skip; + } + if len > 0 { + cur_phys = addr; + cur_len = len; + break; + } + } + if cur_len == 0 { + return Err(EINVAL); + } + Ok(Self { + segments, + cur_phys, + cur_len, + one_page, + }) + } + + fn next_page(&mut self, iova: u64) -> Result { + if !self.one_page && self.cur_len == 0 { + loop { + let Some((dma_addr, dma_len)) = self.segments.next() else { + pr_err!( + "UATPageTable::map_segments: scatterlist ended before IOVA {:#x}\n", + iova + ); + return Err(EINVAL); + }; + if (dma_addr & (UAT_PGMSK as PhysicalAddr)) != 0 || (dma_len & UAT_PGMSK) != 0 { + pr_err!( + "UATPageTable::map_segments: segment {:#x}:{:#x} not page-aligned\n", + dma_addr, + dma_len + ); + return Err(EINVAL); + } + if dma_len > 0 { + self.cur_phys = dma_addr; + self.cur_len = dma_len; + break; + } + } + } + let phys = self.cur_phys; + if !self.one_page { + self.cur_phys += UAT_PGSZ as PhysicalAddr; + self.cur_len -= UAT_PGSZ; + } + Ok(phys) + } +} + +#[kernel::macros::kunit_tests(asahi_pgtable_segments)] +mod tests { + use super::*; + + const PG: usize = UAT_PGSZ; + const PGU: PhysicalAddr = UAT_PGSZ as PhysicalAddr; + + #[test] + fn streams_multi_segment_with_offset_and_zero_len() { + let segs = [ + (0x10_0000, 2 * PG), + (0x20_0000, 0), + (0x30_0000, PG), + (0x40_0000, 2 * PG), + ]; + let mut cursor = SegmentCursor::new(segs.into_iter(), PG, false).unwrap(); + assert_eq!(cursor.next_page(0), Ok(0x10_0000 + PGU)); + assert_eq!(cursor.next_page(PGU), Ok(0x30_0000)); + assert_eq!(cursor.next_page(2 * PGU), Ok(0x40_0000)); + assert_eq!(cursor.next_page(3 * PGU), Ok(0x40_0000 + PGU)); + assert_eq!(cursor.next_page(4 * PGU), Err(EINVAL)); + } + + #[test] + fn repeats_single_page_after_offset() { + let segs = [(0x10_0000, PG), (0x50_0000, 2 * PG)]; + let mut cursor = SegmentCursor::new(segs.into_iter(), 2 * PG, true).unwrap(); + for i in 0..4u64 { + assert_eq!(cursor.next_page(i * PGU), Ok(0x50_0000 + PGU)); + } + } + + #[test] + fn rejects_unaligned_and_short_inputs() { + let segs = [(0x10_0000, PG)]; + assert!(SegmentCursor::new(segs.into_iter(), 0x100, false).is_err()); + assert!(SegmentCursor::new([(0x10_0004, PG)].into_iter(), 0, false).is_err()); + assert!(SegmentCursor::new([(0x10_0000, PG + 4)].into_iter(), 0, false).is_err()); + assert!(SegmentCursor::new([(0x10_0000, PG)].into_iter(), PG, false).is_err()); + } +} From e253a9740d879539bfd115b0ae695135823a3035 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 21:39:14 +0000 Subject: [PATCH 0715/1514] drm/asahi: g17: skip M5 outer-ring locks and rx_applied spinlock on hot paths Two unnecessary lock acquisitions occur on every non-M5 submission and completion path: - Backend::outer_domain() acquires the global Shared::state device mutex on every prepare_compute() and compute_packet() call even when !context.is_m5() (where init.outer_available() is always Err), Backend::publish_claimed() locks outer_compute on every compute publication, and Backend::release_outer() locks outer_compute or outer_render on every publish(), try_render_early(), cancel() and release_queue(). Short-circuit all three immediately off M5, matching Backend::claim_outer(). - Port::rx_update() runs on every qos_publish, qos_publish_pair and qos_complete and previously took the rx_applied SpinLock unconditionally even when the desired receive-thread utilization had not changed. Mirror the applied state in an AtomicU8 so steady-state calls return lock-free; on transitions, mark the mirror RX_STATE_UNSET before re-reading feed.gpu_bound() under rx_applied so concurrent callers cannot skip a state change in flight. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/port.rs | 37 +++++++++++++++++++++++++--- drivers/gpu/drm/asahi/g17/runtime.rs | 9 +++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 2a535f81429c8b..a53ee3bc53ea5f 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -18,7 +18,7 @@ use super::{ }, qos, }; -use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering}; use kernel::{ new_mutex, new_spinlock, prelude::*, @@ -35,6 +35,9 @@ const PRIORITIES: usize = Policy::PRIORITIES as usize; /// work bound by host refills. While the GPU is the bottleneck the burst gains nothing, and at the /// SoC's thermal limit the power it takes comes out of the GPU's clock. const RX_UTIL_MIN_GPU_BOUND: u32 = 256; +const RX_STATE_UNSET: u8 = 0; +const RX_STATE_DEFAULT: u8 = 1; +const RX_STATE_GPU_BOUND: u8 = 2; /// One priority class's compute work ring: its slot array and the cursors of its two firmware /// consumers and of the host producer. @@ -104,6 +107,8 @@ pub(super) struct Port { /// The request last made, `None` before the first. #[pin] rx_applied: SpinLock>>, + /// Lock-free mirror of `rx_applied` (`RX_STATE_*`) so steady-state updates avoid locking. + rx_state: AtomicU8, /// Serializes every render publication, with or without the device mutex: the tiling /// and fragment work rings have one host producer at a time, and same-VM attachment /// overlaps are ordered by publication order (see hazard.rs). @@ -176,6 +181,7 @@ impl Port { rx: SetOnce::new(), feed, rx_applied <- new_spinlock!(None, "g17::Port::rx_applied"), + rx_state: AtomicU8::new(RX_STATE_UNSET), render <- new_mutex!((), "g17::Port::render"), generation: AtomicU64::new(0), publications: AtomicU64::new(0), @@ -515,10 +521,33 @@ impl Port { let Some(rx) = self.rx.as_ref() else { return; }; - let want = self.feed.gpu_bound().then_some(RX_UTIL_MIN_GPU_BOUND); + let want_state = if self.feed.gpu_bound() { + RX_STATE_GPU_BOUND + } else { + RX_STATE_DEFAULT + }; + if self.rx_state.load(Ordering::SeqCst) == want_state { + return; + } let mut applied = self.rx_applied.lock(); - if *applied != Some(want) && rx.set(want).is_ok() { - *applied = Some(want); + // Publish the transitioning state before re-reading `feed.gpu_bound()`, + // so a concurrent caller observing a newer feed state cannot return + // early against the stale mirrored value while this update is in flight. + self.rx_state.store(RX_STATE_UNSET, Ordering::SeqCst); + let gpu_bound = self.feed.gpu_bound(); + let want = gpu_bound.then_some(RX_UTIL_MIN_GPU_BOUND); + let want_state = if gpu_bound { + RX_STATE_GPU_BOUND + } else { + RX_STATE_DEFAULT + }; + if *applied != Some(want) { + if rx.set(want).is_ok() { + *applied = Some(want); + self.rx_state.store(want_state, Ordering::Release); + } + } else { + self.rx_state.store(want_state, Ordering::Release); } } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index b7ad8e336735c3..1f2d672b62ea3f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2131,6 +2131,9 @@ impl Backend { /// M5: the domain outer-ring claims wait on. None off M5 or without firmware. fn outer_domain(&self) -> Option> { + if !self.context.is_m5() { + return None; + } self.shared.state.lock().as_deref().and_then(|firmware| firmware.init.outer_available().ok()) } @@ -2173,6 +2176,9 @@ impl Backend { dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch, ) -> Result { + if !firmware.init.is_m5() { + return firmware.publish_compute(self.owner, packet.clone(), dependencies, deferred); + } let mut held = self.outer_compute.lock(); let _scope = (*held) .as_mut() @@ -2185,6 +2191,9 @@ impl Backend { /// Returns an engine's unspent outer claim after its publication, cancellation or close. /// Outside the device mutex: returned credits notify waiters. pub(super) fn release_outer(&self, engine: crate::g17::job::Engine) { + if !self.context.is_m5() { + return; + } let held = match engine { crate::g17::job::Engine::Compute => &self.outer_compute, crate::g17::job::Engine::Render => &self.outer_render, From 1f779e9c220736769906b8eae5ee65ce322d9325 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 15:39:19 -0500 Subject: [PATCH 0716/1514] nvme: apple: map the I/O queue for polled I/O The Apple NVMe driver already provides a .poll callback, but its tag set only has a single queue map, so the block layer never sets QUEUE_FLAG_POLL and polled I/O (io_uring IOPOLL, RWF_HIPRI) silently falls back to the interrupt path. Map a second hardware context of type HCTX_TYPE_POLL onto the existing I/O queue with BLK_MQ_F_TAG_HCTX_SHARED so tags stay unique across both contexts as the NVMMU requires, and preserve the hardware queue count across controller resets. With nr_hw_queues > 1 and REQ_POLLED, blk_mq_complete_request_remote() returns false and runs completions synchronously instead of deferring to softirq. Move apple_nvme_complete_batch() and unbatched apple_nvme_complete_rq() calls outside anv->lock so completion callbacks that immediately submit follow-up I/O cannot deadlock on anv->lock. Perform queue-state checks and CQ draining in apple_nvme_poll() under anv->lock via apple_nvme_drain_cq(), and serialize apple_nvme_disable_queue() with anv->lock so polling cannot race with queue teardown or CQ wrap. Because the shared completion queue keeps its interrupt enabled, track in-flight non-polled (admin and interrupt I/O) requests under anv->lock and record when apple_nvme_poll() reaps completions. Clear polled_cqes on every interrupt and on controller disable, skip apple_nvme_wait_late_cqe() only when no non-polled request is in flight, and still claim the interrupt when a poller reaped completions so polled I/O neither spins nor triggers spurious-IRQ disable while never stranding a late CQE on concurrent interrupt or admin work. Signed-off-by: Satya Benson --- drivers/nvme/host/apple.c | 205 ++++++++++++++++++++++++++++++-------- 1 file changed, 162 insertions(+), 43 deletions(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 435ef9b7ae0829..508930d3937aae 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -192,11 +192,6 @@ static inline void apple_nvme_enable_queue(struct apple_nvme_queue *q) smp_store_release(&q->enabled, true); } -static inline void apple_nvme_disable_queue(struct apple_nvme_queue *q) -{ - WRITE_ONCE(q->enabled, false); -} - /* * The apple_nvme_iod describes the data in an I/O. * @@ -212,6 +207,7 @@ struct apple_nvme_iod { dma_addr_t first_dma; unsigned int dma_len; /* length of single DMA segment mapping */ struct scatterlist *sg; + bool irq_counted; }; struct apple_nvme_hw { @@ -312,6 +308,10 @@ struct apple_nvme { int irq; spinlock_t lock; + /* Non-polled (admin + interrupt I/O) requests submitted to hardware. */ + unsigned int irq_inflight; + /* A poller consumed completions the CQ interrupt was raised for. */ + bool polled_cqes; /* * Delayed cache flush handling state @@ -470,6 +470,41 @@ static inline struct apple_nvme *queue_to_apple_nvme(struct apple_nvme_queue *q) return container_of(q, struct apple_nvme, ioq); } +static inline void apple_nvme_disable_queue(struct apple_nvme_queue *q) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + unsigned long flags; + + spin_lock_irqsave(&anv->lock, flags); + WRITE_ONCE(q->enabled, false); + spin_unlock_irqrestore(&anv->lock, flags); +} + +static inline void apple_nvme_account_irq_submit(struct apple_nvme_queue *q, + struct request *req) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + struct apple_nvme_iod *iod = blk_mq_rq_to_pdu(req); + + lockdep_assert_held(&anv->lock); + if (q->is_adminq || !(req->cmd_flags & REQ_POLLED)) { + iod->irq_counted = true; + anv->irq_inflight++; + } +} + +static inline void apple_nvme_account_irq_done(struct apple_nvme *anv, + struct request *req) +{ + struct apple_nvme_iod *iod = blk_mq_rq_to_pdu(req); + + lockdep_assert_held(&anv->lock); + if (iod->irq_counted) { + iod->irq_counted = false; + anv->irq_inflight--; + } +} + static unsigned int apple_nvme_queue_depth(struct apple_nvme_queue *q) { struct apple_nvme *anv = queue_to_apple_nvme(q); @@ -656,7 +691,8 @@ static void apple_nvmmu_inval(struct apple_nvme_queue *q, unsigned int tag) } static void apple_nvme_submit_cmd_t8015(struct apple_nvme_queue *q, - struct nvme_command *cmd) + struct nvme_command *cmd, + struct request *req) { struct apple_nvme *anv = queue_to_apple_nvme(q); @@ -671,6 +707,7 @@ static void apple_nvme_submit_cmd_t8015(struct apple_nvme_queue *q, if (++q->sq_tail == apple_nvme_queue_depth(q)) q->sq_tail = 0; + apple_nvme_account_irq_submit(q, req); writel(q->sq_tail, q->sq_db); spin_unlock_irq(&anv->lock); } @@ -720,6 +757,7 @@ static void apple_nvme_submit_cmd_t8103(struct apple_nvme_queue *q, * and the final CQ update. */ spin_lock_irq(&anv->lock); + apple_nvme_account_irq_submit(q, req); writel(tag, q->sq_db); spin_unlock_irq(&anv->lock); } @@ -987,6 +1025,22 @@ static void apple_nvme_complete_batch(struct io_comp_batch *iob) nvme_complete_batch(iob, apple_nvme_unmap_rq); } +static void apple_nvme_complete_direct(struct rq_list *list) +{ + struct request *req; + + while ((req = rq_list_pop(list)) != NULL) + apple_nvme_complete_rq(req); +} + +static void apple_nvme_finish_completions(struct io_comp_batch *iob, + struct rq_list *direct) +{ + if (!rq_list_empty(&iob->req_list)) + apple_nvme_complete_batch(iob); + apple_nvme_complete_direct(direct); +} + static inline bool apple_nvme_cqe_pending(struct apple_nvme_queue *q) { struct nvme_completion *hcqe = &q->cqes[q->cq_head]; @@ -1004,7 +1058,8 @@ apple_nvme_queue_tagset(struct apple_nvme *anv, struct apple_nvme_queue *q) } static inline void apple_nvme_handle_cqe(struct apple_nvme_queue *q, - struct io_comp_batch *iob, u16 idx) + struct io_comp_batch *iob, + struct rq_list *direct, u16 idx) { struct apple_nvme *anv = queue_to_apple_nvme(q); struct nvme_completion *cqe = &q->cqes[idx]; @@ -1020,11 +1075,13 @@ static inline void apple_nvme_handle_cqe(struct apple_nvme_queue *q, return; } + apple_nvme_account_irq_done(anv, req); + if (!nvme_try_complete_req(req, cqe->status, cqe->result) && !blk_mq_add_to_batch(req, iob, nvme_req(req)->status != NVME_SC_SUCCESS, apple_nvme_complete_batch)) - apple_nvme_complete_rq(req); + rq_list_add_tail(direct, req); } static inline void apple_nvme_update_cq_head(struct apple_nvme_queue *q) @@ -1040,7 +1097,8 @@ static inline void apple_nvme_update_cq_head(struct apple_nvme_queue *q) } static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, - struct io_comp_batch *iob) + struct io_comp_batch *iob, + struct rq_list *direct) { bool found = false; @@ -1052,7 +1110,7 @@ static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, * the cqe requires a full read memory barrier */ dma_rmb(); - apple_nvme_handle_cqe(q, iob, q->cq_head); + apple_nvme_handle_cqe(q, iob, direct, q->cq_head); apple_nvme_update_cq_head(q); } @@ -1062,27 +1120,39 @@ static bool apple_nvme_poll_cq(struct apple_nvme_queue *q, return found; } -static bool apple_nvme_handle_cq(struct apple_nvme_queue *q, bool force) +static bool apple_nvme_drain_cq(struct apple_nvme_queue *q, bool force, + struct io_comp_batch *iob, + struct rq_list *direct) { - bool found; - DEFINE_IO_COMP_BATCH(iob); - if (!apple_nvme_queue_enabled(q) && !force) return false; - found = apple_nvme_poll_cq(q, &iob); + return apple_nvme_poll_cq(q, iob, direct); +} + +static bool apple_nvme_handle_cq(struct apple_nvme_queue *q, bool force) +{ + struct apple_nvme *anv = queue_to_apple_nvme(q); + DEFINE_IO_COMP_BATCH(iob); + struct rq_list direct = {}; + unsigned long flags; + bool found; - if (!rq_list_empty(&iob.req_list)) - apple_nvme_complete_batch(&iob); + spin_lock_irqsave(&anv->lock, flags); + found = apple_nvme_drain_cq(q, force, &iob, &direct); + spin_unlock_irqrestore(&anv->lock, flags); + apple_nvme_finish_completions(&iob, &direct); return found; } -static bool apple_nvme_handle_queues(struct apple_nvme *anv) +static bool apple_nvme_handle_queues(struct apple_nvme *anv, + struct io_comp_batch *iob, + struct rq_list *direct) { - bool found = apple_nvme_handle_cq(&anv->ioq, false); + bool found = apple_nvme_drain_cq(&anv->ioq, false, iob, direct); - found |= apple_nvme_handle_cq(&anv->adminq, false); + found |= apple_nvme_drain_cq(&anv->adminq, false, iob, direct); return found; } @@ -1095,7 +1165,9 @@ static bool apple_nvme_handle_queues(struct apple_nvme *anv) */ #define APPLE_NVME_LATE_CQE_US 100 -static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) +static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv, + struct io_comp_batch *iob, + struct rq_list *direct) { ktime_t end; @@ -1106,7 +1178,7 @@ static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) end = ktime_add_us(ktime_get(), APPLE_NVME_LATE_CQE_US); do { udelay(1); - if (apple_nvme_handle_queues(anv)) + if (apple_nvme_handle_queues(anv, iob, direct)) return true; } while (ktime_before(ktime_get(), end)); @@ -1116,17 +1188,30 @@ static bool apple_nvme_wait_late_cqe(struct apple_nvme *anv) static irqreturn_t apple_nvme_irq(int irq, void *data) { struct apple_nvme *anv = data; + DEFINE_IO_COMP_BATCH(iob); + struct rq_list direct = {}; unsigned long flags; - bool handled; + bool handled, polled; if (apple_nvme_m5_fenced(anv)) return IRQ_NONE; spin_lock_irqsave(&anv->lock, flags); - handled = apple_nvme_handle_queues(anv); - if (!handled) - handled = apple_nvme_wait_late_cqe(anv); + handled = apple_nvme_handle_queues(anv, &iob, &direct); + polled = anv->polled_cqes; + anv->polled_cqes = false; + /* + * The CQ keeps its interrupt when the queue is also polled, and a + * poller usually reaps the entry before this handler runs. Skip the + * late-CQE wait only when no interrupt-driven or admin command is in + * flight, and still claim the interrupt if a poller reaped entries. + */ + if (!handled && (anv->irq_inflight || !polled)) + handled = apple_nvme_wait_late_cqe(anv, &iob, &direct); + if (!handled && polled) + handled = true; spin_unlock_irqrestore(&anv->lock, flags); + apple_nvme_finish_completions(&iob, &direct); return handled ? IRQ_HANDLED : IRQ_NONE; } @@ -1233,6 +1318,7 @@ static blk_status_t apple_nvme_queue_rq(struct blk_mq_hw_ctx *hctx, iod->npages = -1; iod->nents = 0; + iod->irq_counted = false; /* * We should not need to do this, but we're still using this to @@ -1280,7 +1366,7 @@ static blk_status_t apple_nvme_queue_rq(struct blk_mq_hw_ctx *hctx, if (anv->hw->has_lsq_nvmmu) apple_nvme_submit_cmd_t8103(q, cmnd, req); else - apple_nvme_submit_cmd_t8015(q, cmnd); + apple_nvme_submit_cmd_t8015(q, cmnd, req); return BLK_STS_OK; @@ -1372,14 +1458,17 @@ static void apple_nvme_disable_legacy(struct apple_nvme *anv, bool shutdown) nvme_quiesce_admin_queue(&anv->ctrl); /* last chance to complete any requests before nvme_cancel_request */ - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(&anv->ioq, true); apple_nvme_handle_cq(&anv->adminq, true); - spin_unlock_irqrestore(&anv->lock, flags); nvme_cancel_tagset(&anv->ctrl); nvme_cancel_admin_tagset(&anv->ctrl); + spin_lock_irqsave(&anv->lock, flags); + anv->irq_inflight = 0; + anv->polled_cqes = false; + spin_unlock_irqrestore(&anv->lock, flags); + /* * The driver will not be starting up queues again if shutting down so * must flush all entered requests to their failed completion to avoid @@ -1469,12 +1558,14 @@ static int apple_nvme_disable_locked(struct apple_nvme *anv, bool shutdown) return ret; } - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(&anv->ioq, true); apple_nvme_handle_cq(&anv->adminq, true); - spin_unlock_irqrestore(&anv->lock, flags); nvme_cancel_tagset(&anv->ctrl); nvme_cancel_admin_tagset(&anv->ctrl); + spin_lock_irqsave(&anv->lock, flags); + anv->irq_inflight = 0; + anv->polled_cqes = false; + spin_unlock_irqrestore(&anv->lock, flags); if (shutdown) { nvme_unquiesce_io_queues(&anv->ctrl); nvme_unquiesce_admin_queue(&anv->ctrl); @@ -1560,7 +1651,6 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) struct apple_nvme *anv = queue_to_apple_nvme(q); struct nvme_completion *cqe = &q->cqes[q->cq_head]; enum nvme_ctrl_state state = nvme_ctrl_state(&anv->ctrl); - unsigned long flags; u32 cc, csts; if (blk_mq_request_completed(req)) @@ -1576,9 +1666,7 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) * interrupt cannot turn a completed initialization command into a reset. */ if (!apple_rtkit_is_crashed(anv->rtk) && !(csts & NVME_CSTS_CFS)) { - spin_lock_irqsave(&anv->lock, flags); apple_nvme_handle_cq(q, false); - spin_unlock_irqrestore(&anv->lock, flags); if (blk_mq_request_completed(req)) { dev_warn(anv->dev, "I/O %d(aq:%d) timeout in state %d: completion polled\n", @@ -1652,6 +1740,11 @@ static enum blk_eh_timer_return apple_nvme_timeout(struct request *req) READ_ONCE(cqe->command_id)); if (blk_mq_request_started(req) && !blk_mq_request_completed(req)) { + unsigned long flags; + + spin_lock_irqsave(&anv->lock, flags); + apple_nvme_account_irq_done(anv, req); + spin_unlock_irqrestore(&anv->lock, flags); nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD; nvme_req(req)->flags |= NVME_REQ_CANCELLED; blk_mq_complete_request(req); @@ -1679,19 +1772,41 @@ static int apple_nvme_poll(struct blk_mq_hw_ctx *hctx, { struct apple_nvme_queue *q = hctx->driver_data; struct apple_nvme *anv = queue_to_apple_nvme(q); - bool found; + struct rq_list direct = {}; + bool found = false; unsigned long flags; - if (apple_nvme_m5_retained(anv) || READ_ONCE(anv->detached) || - apple_nvme_m5_fenced(anv)) - return 0; spin_lock_irqsave(&anv->lock, flags); - found = apple_nvme_poll_cq(q, iob); + if (!apple_nvme_m5_retained(anv) && !READ_ONCE(anv->detached) && + !apple_nvme_m5_fenced(anv)) { + found = apple_nvme_drain_cq(q, false, iob, &direct); + if (found) + anv->polled_cqes = true; + } spin_unlock_irqrestore(&anv->lock, flags); + apple_nvme_complete_direct(&direct); return found; } +/* + * There is one I/O queue. Map a second hardware context (HCTX_TYPE_POLL) onto + * it with shared tags so polled I/O (io_uring IOPOLL, RWF_HIPRI) works while + * keeping tags unique across both contexts as the NVMMU requires. + */ +static void apple_nvme_map_queues(struct blk_mq_tag_set *set) +{ + set->map[HCTX_TYPE_DEFAULT].nr_queues = 1; + set->map[HCTX_TYPE_DEFAULT].queue_offset = 0; + blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]); + if (set->nr_maps <= HCTX_TYPE_POLL) + return; + set->map[HCTX_TYPE_READ].nr_queues = 0; + set->map[HCTX_TYPE_POLL].nr_queues = 1; + set->map[HCTX_TYPE_POLL].queue_offset = 1; + blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]); +} + static const struct blk_mq_ops apple_nvme_mq_admin_ops = { .queue_rq = apple_nvme_queue_rq, .complete = apple_nvme_complete_rq, @@ -1707,6 +1822,7 @@ static const struct blk_mq_ops apple_nvme_mq_ops = { .init_request = apple_nvme_init_request, .timeout = apple_nvme_timeout, .poll = apple_nvme_poll, + .map_queues = apple_nvme_map_queues, }; static void apple_nvme_init_queue(struct apple_nvme_queue *q) @@ -2163,7 +2279,7 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) } else { nvme_wait_freeze(&anv->ctrl); } - blk_mq_update_nr_hw_queues(&anv->tagset, 1); + blk_mq_update_nr_hw_queues(&anv->tagset, anv->tagset.nr_hw_queues); if (!READ_ONCE(anv->m5.rebuild_active)) { nvme_unfreeze(&anv->ctrl); if (anv->hw->m5_sleep) @@ -2356,8 +2472,8 @@ static int apple_nvme_alloc_tagsets(struct apple_nvme *anv) return ret; anv->tagset.ops = &apple_nvme_mq_ops; - anv->tagset.nr_hw_queues = 1; - anv->tagset.nr_maps = 1; + anv->tagset.nr_hw_queues = 2; + anv->tagset.nr_maps = HCTX_MAX_TYPES; /* * Tags are used as an index to the NVMMU and must be unique across * both queues. The admin queue gets the first APPLE_NVME_AQ_DEPTH which @@ -2376,8 +2492,11 @@ static int apple_nvme_alloc_tagsets(struct apple_nvme *anv) * dispatched from a kblockd worker instead of the submitting task, * which adds a context switch to each I/O. Start without a scheduler, * as PCIe NVMe controllers do; one can still be selected through sysfs. + * Share tags across the default and poll hardware contexts so every + * tag maps to a unique NVMMU TCB slot. */ - anv->tagset.flags = BLK_MQ_F_NO_SCHED_BY_DEFAULT; + anv->tagset.flags = BLK_MQ_F_TAG_HCTX_SHARED | + BLK_MQ_F_NO_SCHED_BY_DEFAULT; ret = blk_mq_alloc_tag_set(&anv->tagset); if (ret) From 3443921084c10987a1db72d28f3907169a62ff4f Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 22:23:28 +0000 Subject: [PATCH 0717/1514] arm64: dts: apple: t6041: retain GPU power across short submission gaps Set apple,idle-off-delay-ms = <16> on the T6041 GPU node in t6041-j614c-j616c.dtsi and t6041-j575c.dts, matching T6040 (t604x-j614-j616.dtsi and t6040-j773s.dts). Without this property, the G17P driver defaults to FIRMWARE_IDLE_OFF_MS (2 ms) and leaves the host idle hold disabled; on J616C (T6041, 25G83) this lets the GPU cores power-cycle between synchronous depth=1 submissions, adding ~570 us of wake penalty per submission. With a 16 ms bounded hold, long idle still releases and powers off the GPU while interactive and synchronous compute/render bursts stay warm. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 2 ++ arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi | 2 ++ 2 files changed, 4 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 5b766cbc58d5fa..416f0431d7bef7 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1806,6 +1806,8 @@ operating-points-v2 = <&gpu_opp>; apple,cs-opp = <&gpu_cs_opp>; apple,afr-opp = <&gpu_afr_opp>; + /* Avoid a core power cycle between interactive submissions, then release. */ + apple,idle-off-delay-ms = <16>; apple,firmware-version = <26 5 2>; }; diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index f326f2aa740577..bbf91d45662fd0 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -2308,6 +2308,8 @@ operating-points-v2 = <&gpu_opp>; apple,cs-opp = <&gpu_cs_opp>; apple,afr-opp = <&gpu_afr_opp>; + /* Avoid a core power cycle between interactive submissions, then release. */ + apple,idle-off-delay-ms = <16>; apple,firmware-version = <26 5 2>; }; From 152822e24034640e37265684c25aec0d5ac8422c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 17:35:45 -0500 Subject: [PATCH 0718/1514] drm/asahi: move TTBAT slot PoC clean into UatShared::publish_slot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bind_inner() cleaned the TTBAT slot directly when UatInner::clean_poc was set without quirks.clean_tables, leaving VmInner::drop() — which clears ttb0/ttb1 and calls only UatShared::publish_slot() — without a cache clean on adopted non-snooping UATs. If the walker later reads the cleared slot before the cache line is evicted, it can still see the stale root after the VM's page tables are freed. Mirror clean_poc onto UatShared (true in new_adopted_inner, matching quirks.clean_tables in make_inner), check self.clean_poc || self.quirks.clean_tables in UatShared::publish_slot(), and drop the bind-only duplicate in bind_inner(). Extend the asahi-m4 retention host harness to assert that both bind() and VmInner::drop() write back the TTBAT slot once when clean_poc or clean_tables is set and not at all for a coherent walker. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/mmu.rs | 16 ++++---- .../gpu/asahi-m4/test-mmu-retention.py | 39 +++++++++++++++---- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 484a471f1190cc..2c6eef966db725 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -2051,6 +2051,7 @@ struct UatShared { map_kernel_to_user: bool, handoff_rgn: UatRegion, ttbs_rgn: UatRegion, + clean_poc: bool, quirks: UatQuirks, } @@ -2080,9 +2081,11 @@ impl UatShared { } } - /// Writes back context-table slot `idx` after it changed, where this SoC needs it. + /// Writes back context-table slot `idx` after it changed, where the UAT + /// walker does not snoop the CPU caches (either an adopted UAT or a SoC + /// with `quirks.clean_tables`). fn publish_slot(&self, idx: usize) { - if self.quirks.clean_tables { + if self.clean_poc || self.quirks.clean_tables { let slot = core::ptr::from_ref(&self.ttbs()[idx]).cast::(); pgtable::clean_poc(slot, size_of::()); pgtable::poc_barrier(); @@ -3631,6 +3634,7 @@ impl Uat { map_kernel_to_user, handoff_rgn, ttbs_rgn, + clean_poc: true, quirks: UatQuirks::DEFAULT, }, "uat_shared" @@ -3867,13 +3871,6 @@ impl Uat { uat_inner.owned_user_roots[idx] = ttb; binding.generation = binding_wire_generation(incarnation); uat_inner.publish_slot(idx); - if self.inner.clean_poc && !uat_inner.quirks.clean_tables { - // A table walker that does not snoop the CPU caches must also see the new - // TTBAT words, not only the new tables. - let slot = core::ptr::from_ref(&uat_inner.ttbs()[idx]).cast::(); - pgtable::clean_poc(slot, size_of::()); - pgtable::poc_barrier(); - } drop(transaction); // Make sure all TLB entries from the previous owner of this ASID are gone @@ -4247,6 +4244,7 @@ impl Uat { map_kernel_to_user: false, handoff_rgn, ttbs_rgn, + clean_poc: shared_quirks.clean_tables, quirks: shared_quirks, }, "uat_shared" diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index a40521662daaa0..8b39a4ce54783b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -40,7 +40,7 @@ def body(source,marker): mid=r''' } struct Quirks{handoff_lock:bool,clean_tables:bool} -struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],quirks:Quirks} +struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],clean_poc:bool,quirks:Quirks} impl UatShared{fn handoff(&self)->&Handoff{&self.handoff}fn ttbs(&self)->&[SlotTTBS;64]{&self.ttbs}} struct UatInner{firmware:UatFirmware,m4_adopted:bool,clean_poc:bool,failed:AtomicBool,shared:Mutex} ''' @@ -52,7 +52,7 @@ def body(source,marker): inner='impl UatInner{\n'+'\n'.join(body(mm,m) for m in ['fn lock(&self) -> Guard', 'fn check_m4(', 'fn lock_handoff(', 'fn lock_m4_upper('])+'\n}\n' models=r''' fn uat(m4:bool,firmware:UatFirmware)->Rc{uat_with(m4,firmware,false,false)} -fn uat_with(m4:bool,firmware:UatFirmware,clean_poc:bool,clean_tables:bool)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables}})})} +fn uat_with(m4:bool,firmware:UatFirmware,clean_poc:bool,clean_tables:bool)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],clean_poc,quirks:Quirks{handoff_lock:true,clean_tables}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}} @@ -108,10 +108,35 @@ def body(source,marker): // A previously faulted M4 is refused before any new lock or TTBAT generation mutation. let u=uat(true,UatFirmware::Handoff);u.failed.store(true,Ordering::Release);let backend=Uat{inner:u.clone(),slots:Allocator};assert!(backend.bind(&Vm{id:9,binding:new_binding()}).is_err());assert_eq!(u.shared.lock().binding_generations[4],0); } -// A non-snooping walker sees the TTBAT slot bind fills written back exactly once: by bind for an -// adopted UAT without the clean_tables quirk (clean_poc only), by publish_slot with the quirk. -// A coherent walker (neither) gets no clean. -fn ttbat_clean_tests(){for (clean_poc,clean_tables,cleaned) in [(false,false,false),(true,false,true),(true,true,true)]{reset();let u=uat_with(false,UatFirmware::Handoff,clean_poc,clean_tables);let backend=Uat{inner:u.clone(),slots:Allocator};let bound=backend.bind(&Vm{id:9,binding:new_binding()}).unwrap();assert_eq!(bound.1,4);let s=u.shared.lock();let slot=(core::ptr::from_ref(&s.ttbs[4]) as usize,size_of::());let cleans=CLEANS.lock().unwrap();assert_eq!(cleans.iter().filter(|c|**c==slot).count(),usize::from(cleaned));assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0x804000001|(4<<48));}} +// A non-snooping walker sees the TTBAT slot written back exactly once on both bind and +// VmInner::drop through UatShared::publish_slot: for an adopted UAT without the clean_tables +// quirk (clean_poc only) and with the quirk. A coherent walker (neither) gets no clean. +fn ttbat_clean_tests(){ + for (clean_poc,clean_tables,cleaned) in [(false,false,false),(true,false,true),(false,true,true),(true,true,true)]{ + reset(); + let u=uat_with(false,UatFirmware::Handoff,clean_poc,clean_tables); + let backend=Uat{inner:u.clone(),slots:Allocator}; + let binding=new_binding(); + let bound=backend.bind(&Vm{id:9,binding:binding.clone()}).unwrap(); + assert_eq!(bound.1,4); + let slot={ + let s=u.shared.lock(); + let slot=(core::ptr::from_ref(&s.ttbs[4]) as usize,size_of::()); + assert_eq!(CLEANS.lock().unwrap().iter().filter(|c|**c==slot).count(),usize::from(cleaned)); + assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0x804000001|(4<<48)); + slot + }; + CLEANS.lock().unwrap().clear(); + binding.lock().active_users=0; + drop(bound); + drop(VmInner{id:9,binding,uat_inner:u.clone(),page_table:UatPageTable::new()}); + let s=u.shared.lock(); + assert_eq!(CLEANS.lock().unwrap().iter().filter(|c|**c==slot).count(),usize::from(cleaned)); + assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),0); + assert_eq!(s.ttbs[4].ttb1.load(Ordering::Relaxed),0); + assert_eq!(s.owned_user_roots[4],0); + } +} fn generation_churn_test(){ let u=uat(true,UatFirmware::Handoff);let backend=Uat{inner:u.clone(),slots:Allocator}; let published=backend.bind(&Vm{id:1,binding:new_binding()}).unwrap();assert_eq!(published.0.binding.lock().generation,1); @@ -121,7 +146,7 @@ def body(source,marker): let next=backend.bind(&Vm{id:999,binding:new_binding()}).unwrap();assert_eq!(next.0.binding.lock().generation,3); } fn vm_drop_tests(){for (m4,blocked,pre_failed) in [(false,false,false),(true,false,false),(true,true,false),(true,false,true)]{reset();let u=uat(m4,UatFirmware::Handoff);let binding=new_binding();binding.lock().bind_token=Some(Token(3));let low=0x804000001|(4<<48);{let mut s=u.shared.lock();s.ttbs[4].ttb0.store(low,Ordering::Release);s.owned_user_roots[4]=low;s.handoff.lock_fw.store(u8::from(blocked),Ordering::Release);}u.failed.store(pre_failed,Ordering::Release);drop(VmInner{id:9,binding,uat_inner:u.clone(),page_table:UatPageTable::new()});let uncertain=blocked||pre_failed;assert_eq!(ROOT_FREES.load(Ordering::Relaxed),usize::from(!uncertain));assert_eq!(TREE_FREES.load(Ordering::Relaxed),usize::from(!uncertain));let s=u.shared.lock();assert_eq!(s.ttbs[4].ttb0.load(Ordering::Relaxed),if uncertain{low}else{0});assert_eq!(s.owned_user_roots[4],if uncertain{low}else{0});assert_eq!(s.handoff.lock_ap.load(Ordering::Relaxed),0);assert_eq!(u.failed.load(Ordering::Acquire),uncertain);}} -fn main(){ttbat_clean_tests();generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition; a non-snooping adopted UAT writes back the bound TTBAT slot once (mock hardware)");} +fn main(){ttbat_clean_tests();generation_churn_test();mapping_tests();page_tests();bind_tests();vm_drop_tests();fail_stop_race_tests();println!("Shared Rust fault injection passed: G15/Neo normal and cached frees exactly once; M4 cached/timeout/partial-unmap retains node+backing+VA; guards released before free; M4 bind timeout changes no TTBAT/generation; VM-drop timeout retains physical tables/root; faulted M4 admission rejects before and after lock acquisition; a non-snooping adopted UAT writes back the TTBAT slot once on bind and once on VM teardown (mock hardware)");} ''' source=pre+handoff+mid+raii+inner+models+map_drop+pages+bindings+helpers+bind+vm+main (OUT/'check-mmu-retention.rs').write_text(source) From 55bde9d43181c3730f3a809eed59d8d9fdc8c4c7 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 22:00:28 +0000 Subject: [PATCH 0719/1514] arm64: dts: apple: t6041: describe apr0 ProRes engine and enable it on J616c Describe the first T6041 ProRes engine (/arm-io/apr0), its DART (/arm-io/dart-apr0, SID 1, IRQ 1959) and its PMGR power domains (FAB1_SOC 0x2d0, SCODEC 0x328, SCODEC_STREAMING 0x330 in pmgr_aux), all verified against the J616c ADT, and enable them on t6041-j616c. apr0 uses the existing apple,t6041-prores binding (core, wrapper and aux windows) and the apple-prores driver's built-in T6041 power-up rows (with optional apple/prores-t6041-init.bin override). The second engine (apr1, outside SCODEC with no aux window) stays omitted here pending its IRQ routing and driver support. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j616c.dts | 25 +++++++++ arch/arm64/boot/dts/apple/t6041.dtsi | 65 +++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index aaebd20dc588aa..7445115f601c5f 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -107,3 +107,28 @@ &aes { status = "okay"; }; + +/* + * First ProRes encoder (apr0) and its DART. Runs with SCODEC_STREAMING (and + * SCODEC) powered; uses the driver's built-in T6041 power-up rows, optionally + * overridden by apple/prores-t6041-init.bin. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 6d3b1605927cd8..9de3ffce84760a 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -713,6 +713,71 @@ }; }; +/* + * First ProRes engine (ADT /arm-io/apr0) and its DART, from the J616c ADT. + * apr0 sits in the SCODEC block (PMGR bank 0 / pmgr_aux: FAB1_SOC 0x2d0, + * SCODEC 0x328, SCODEC_STREAMING 0x330) with core, wrapper and aux windows. + */ +&pmgr_aux { + ps_fab1_soc: power-controller@2d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab1_soc"; + power-domains = <&ps_afi>; + apple,always-on; + status = "disabled"; + }; + + ps_scodec: power-controller@328 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x328 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "scodec"; + power-domains = <&ps_fab1_soc>; + status = "disabled"; + }; + + ps_scodec_streaming: power-controller@330 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x330 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "scodec_streaming"; + power-domains = <&ps_scodec>; + status = "disabled"; + }; +}; + +/ { + apr0: video-codec@301000000 { + compatible = "apple,t6041-prores", "apple,prores"; + reg = <0x3 0x01000000 0x0 0x4000>, + <0x3 0x00000000 0x0 0x1000000>, + <0x3 0x010c0000 0x0 0x4000>; + reg-names = "core", "wrapper", "aux"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_scodec_streaming>; + iommus = <&apr0_dart 1>; + resets = <&ps_scodec>; + status = "disabled"; + }; + + apr0_dart: iommu@301020000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x01020000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&ps_scodec>; + status = "disabled"; + }; +}; + /* * The first video encoder (ADT ave0, soc-id t6040), its DARTs and its power * domains. It has no board wiring, so it is enabled on every M4 Max board. From c8ebbce0c85e92974471affff0240c74f979f8d3 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Mon, 23 Nov 2026 22:01:14 +0000 Subject: [PATCH 0720/1514] arm64: dts: apple: t6041-j616c: enable both MSR scalers (scaler0, scaler1) Enable scaler0, scaler1, their DARTs (scaler0_dart, scaler1_dart) and their PMGR power domains (ps_fab5_soc, ps_msr0, ps_msr0_ase_core, ps_msr1, ps_msr1_ase_core; ps_fab6_soc is already enabled in t604x-pmgr.dtsi) on the J616c. All register apertures, IRQ pairs (1547/1549 and 1553/1555), DART streams (0, 1) and PMGR offsets in t6041-j614-j616-j575-scaler.dtsi match the J616c ADT, and the apple-scaler driver already supports apple,t6041-scaler (MSR21) including the V4L2_PIX_FMT_APPLE_L8V0 lossless 4:2:0 format used by hardware camera temporal denoising. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j616c.dts | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index aaebd20dc588aa..046d815ddbe0ab 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -107,3 +107,40 @@ &aes { status = "okay"; }; + +/* Both MSR scalers/CSCs (scaler0, scaler1) and their DARTs. */ +&ps_fab5_soc { + status = "okay"; +}; + +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + +&ps_msr1 { + status = "okay"; +}; + +&ps_msr1_ase_core { + status = "okay"; +}; + +&scaler1_dart { + status = "okay"; +}; + +&scaler1 { + status = "okay"; +}; From f3497c695381c018fa055582e569804ee99a7749 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Mon, 23 Nov 2026 18:11:48 -0500 Subject: [PATCH 0721/1514] drm/asahi: fix detached spare ownership and release publication guard Detach idle drained published siblings in Registry::reclaim_unused_render_spare() via Pool::release_unused_sibling(..., true) instead of reassign_unused_spare(), keeping admission.owners[slot] synced with entry.reservation.owner and entry.context in the released state until the requester acquires the slot. Skip reclamation when the caller already owns a live pair. Share State::mark_published() between Pool::note_published() and RenderLease::note_publication() so an off-lock direct publication cannot re-set published on a slot concurrently released by release_owner(). Add KUnit (render_lease_note_publication_ignores_released_slot) and host (spare_detach_keeps_exit_kill_ownership, --mutation spare-detach-reassigns) regression tests. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/queue/admission.rs | 62 +++++++-- drivers/gpu/drm/asahi/g17/runtime/render.rs | 15 ++- tools/asahi/g17-admission-order-tests.py | 125 +++++++++++++++++-- tools/asahi/run-host-tests.py | 2 +- 4 files changed, 179 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index e0daa71b28c421..07198cb2b10395 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -134,6 +134,15 @@ impl State { fn has_live_owner(&self, owner: u64) -> bool { (1..cfg::RENDER_SLOTS).any(|slot| self.owns_live(owner, slot)) } + fn mark_published(&mut self, slot: u8) { + let index = usize::from(slot); + if index > 0 && index < cfg::RENDER_SLOTS { + let bit = 1u64 << index; + if self.owners[index] != 0 && self.released & bit == 0 { + self.published |= bit; + } + } + } fn live_owners(&self) -> usize { let mut count = 0usize; for slot in 1..cfg::RENDER_SLOTS { @@ -1186,15 +1195,11 @@ impl Pool { pub(crate) fn owns_slot(&self, owner: u64, slot: usize) -> bool { self.state.lock().owns_live(owner, slot) } + pub(crate) fn owns_live_slot(&self, owner: u64) -> bool { + self.state.lock().has_live_owner(owner) + } pub(crate) fn note_published(&self, slot: u8) { - let index = usize::from(slot); - if index > 0 && index < cfg::RENDER_SLOTS { - let bit = 1u64 << index; - let mut state = self.state.lock(); - if state.owners[index] != 0 && state.released & bit == 0 { - state.published |= bit; - } - } + self.state.lock().mark_published(slot); } pub(crate) fn release_owner(&self, owner: u64) { let mut state = self.state.lock(); @@ -1505,7 +1510,7 @@ impl RenderLease { /// including a replay, which supersedes the earlier kick. pub(crate) fn note_publication(&self, fragment: KickDependency) { let mut state = self.pool.state.lock(); - state.published |= (1u64 << self.slot) & State::MASK; + state.mark_published(self.slot); let Some(record) = self.record else { return; }; @@ -2325,6 +2330,45 @@ mod two_pair_tests { drop(q1); crate::g17::pairs::set_sibling_backlog(1); } + + #[test] + fn render_lease_note_publication_ignores_released_slot() { + use crate::g17::fw::kick::KickTimestamp; + + let kick = KickDependency::new(10, KickTimestamp::new(1).unwrap()).unwrap(); + let mut footprint = Footprint::new(1, false); + footprint.push_vm(0, 0x1000); + let footprint = Arc::new(footprint, GFP_KERNEL).unwrap(); + let request = Request { + footprint: &footprint, + sequence: 1, + prefix: None, + }; + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 2); + let q1 = pool.try_reserve_queue(2).unwrap(); + let lease = pool + .acquire_render(1, 1, Some(request), u64::MAX, || Ok(())) + .unwrap(); + let slot = lease.slot(); + let bit = 1u64 << slot; + // Concurrent owner release while the pair is lent out off-lock must not + // have `published` re-set when `lease.note_publication()` acquires the lock. + pool.release_owner(1); + lease.note_publication(kick); + { + let state = pool.state.lock(); + assert_eq!(state.published & bit, 0); + assert_ne!(state.released & bit, 0); + assert_eq!(state.owners[usize::from(slot)], 1); + assert!(state + .footprints + .iter() + .any(|entry| entry.slot == Some(slot) && entry.fragment.is_some())); + } + drop(lease); + drop(q1); + } } #[kunit_tests(asahi_g17_admission_deadline)] diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index a24fb888354bce..a46a4ab3230d9e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -286,6 +286,9 @@ impl Registry { owner: Option, require_ids: bool, ) -> Result> { + if owner.is_some_and(|owner| owner == 0 || self.admission.owns_live_slot(owner)) { + return Ok(None); + } // Prefer an empty reservation or an already parked channel, then a // reusable or warmed unpublished pair, then an idle drained published // sibling (render only). @@ -361,10 +364,14 @@ impl Registry { } None }; - if !self - .admission - .reassign_unused_spare(slot as u8, expected, owner) - { + let claimed = if detach { + self.admission + .release_unused_sibling(slot as u8, expected, true) + } else { + self.admission + .reassign_unused_spare(slot as u8, expected, owner) + }; + if !claimed { continue; } if owner.is_none() { diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 8397c06ac7c9ca..2cdcf55a0d87ac 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -361,6 +361,7 @@ def release_fixture(): render_teardown = (ROOT / 'runtime/render/teardown.rs').read_text() backend = (ROOT / 'runtime/backend.rs').read_text() pair = (ROOT / 'queue/render.rs').read_text() + render_exit = (ROOT / 'runtime/render/exit.rs').read_text() hw = (ROOT.parent / 'hw/t8140.rs').read_text() constants = '\n'.join(re.search(r'pub\(crate\) const ' + name + r': [^;]+;', hw).group(0) for name in ['RENDER_SLOTS', 'RENDER_PAIRS_MAX', 'RENDER_DEPTH']) @@ -372,15 +373,24 @@ def release_fixture(): 'fn take_idle(', 'fn acquire(', 'fn acquire_for(', 'fn live_owners(', 'fn live_siblings(', 'fn reclaimable_siblings_in(', 'fn reclaimable_siblings(', 'fn promotes_reclaimable_sibling(', 'fn can_lease_slot(', 'fn unavailable_released(', 'fn total_pair_demand(', 'fn pair_demand(', - 'fn claim_sibling(', 'fn usable(', 'fn set_held(', 'fn sync_held(', 'fn retained(', 'fn used(']) + 'fn claim_sibling(', 'fn usable(', 'fn can_reassign_unused_spare(', 'fn reassign_unused_spare(', + 'fn release_unused_sibling(', 'fn hold_for_exit_kill(', 'fn set_held(', 'fn sync_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ + 'pub(crate) fn can_reassign_unused_spare(', 'pub(crate) fn reassign_unused_spare(', + 'pub(crate) fn release_unused_sibling(', 'pub(crate) fn owns_live_slot(', + 'pub(crate) fn hold_render_slots_for_exit_kill(', 'pub(crate) fn set_held(', 'pub(crate) fn sync_held(', 'pub(crate) fn release_owner(']) pending = '\n'.join(item(teardown, name) for name in [ 'pub(crate) fn new(', 'pub(crate) fn releasing(', 'fn find(', 'fn insert(', 'pub(crate) fn close(', 'pub(crate) fn take_consumed(']) runtime = '\n'.join(item(render, name) for name in [ + 'pub(super) fn reclaim_unused_render_spare(', 'pub(super) fn hold_render_slot(', 'pub(super) fn sync_render_holds(', - 'fn render_slot_held(']).replace('pub(super) fn', 'pub fn') + 'fn render_slot_held(']).replace('pub(super) fn', 'pub fn').replace('KBox::into_inner(pair).park()', '(*pair).park()') + render_state = '\n'.join(item(render_exit, name) for name in [ + 'pub(in crate::g17::runtime) fn exit_scope(', + 'pub(in crate::g17::runtime) fn slot_owner(', + 'pub(in crate::g17::runtime) fn qids_for_slot(']).replace('pub(in crate::g17::runtime) fn', 'pub fn') firmware = '\n'.join('pub ' + item(render, name) for name in ['fn with_render(', 'fn with_render_at(']) return r""" #![allow(dead_code, unused_macros, unused_imports, unused_variables)] @@ -468,23 +478,54 @@ def release_fixture(): """ + item(pair, 'pub(crate) fn unreusable_work(') + r""" pub fn context(&self) -> &Arc { &self.context } pub fn release_owner(&mut self) { self.owner = None; } + pub fn detachable(&self) -> Result { Ok(!self.quarantined && self.active.is_empty()) } + pub fn reusable(&self) -> Result { Ok(self.owner.is_none() && self.detachable()?) } + pub fn can_yield_unused(&self) -> Result { Ok(false) } + pub fn buffer_id(&self) -> u8 { 0 } + pub fn park(self) -> ((), ()) { ((), ()) } } - pub struct Reservation { pub owner: u64 } + #[derive(Clone, Copy)] + pub struct Qid(pub u8); + impl Qid { pub fn qid(self) -> u8 { self.0 } } + pub struct Qids; + impl Qids { + pub fn can_cancel_unpublished(&self, _: Qid) -> bool { false } + pub fn cancel_unpublished(&mut self, _: Qid) -> Result { Ok(()) } + } + pub struct Buffers; + impl Buffers { pub fn unreserve_owner(&mut self, _: u8) -> Result { Ok(()) } } + pub struct UnusedRenderSpare { _entry: Option, _binding: Option<()> } + pub struct Reservation { pub owner: u64, pub ids: [Qid; 2] } pub struct Entry { pub reservation: Reservation, pub context: Option>, pub pair: Option>, - pub parked: bool, + pub pool: Option<()>, + pub parked: Option<()>, pub preparing: Option<()>, + pub constructing: bool, pub growing: bool, pub pending_owner: Option, pub pending_owner_closed: bool, + pub pending_error: Option<()>, + pub pending_timeout: bool, pub closed: bool, } pub struct RenderState { pub entries: Vec> } - pub struct Registry { pub admission: Arc, pub render: RenderState, pub teardown: Pending } + impl RenderState { + pub fn collect_retired(&mut self, _: usize) -> Result { Ok(()) } +""" + render_state + r""" + } + pub struct Registry { + pub admission: Arc, + pub render: RenderState, + pub teardown: Pending, + pub qids: Qids, + pub buffers: Buffers, + } impl Registry { pub fn release_compute(&mut self, _: u64) -> Result { Ok(()) } + pub fn note_build_room(&self) {} """ + item(render_teardown, 'pub(in crate::g17::runtime) fn release_render(') + '\n' + runtime + r""" } """ + item(render, 'fn render_hold(') + r""" @@ -549,7 +590,7 @@ def release_fixture(): } use g17::context::Context; -use g17::runtime::{Active, Entry, Firmware, Pair, Registry, RenderState, Reservation}; +use g17::runtime::{Active, Buffers, Entry, Firmware, Pair, Qid, Qids, Registry, RenderState, Reservation}; use g17::runtime::backend::{Backend, Channels, Lock as DeviceLock, Shared}; const SLOTS: usize = cfg::RENDER_SLOTS; const NEW: u64 = 5000; @@ -573,7 +614,7 @@ def release_fixture(): let mut entries: Vec> = (0..SLOTS).map(|_| None).collect(); for (slot, context) in pairs { entries[*slot] = Some(Entry { - reservation: Reservation { owner: owner(*slot) }, + reservation: Reservation { owner: owner(*slot), ids: [Qid((*slot * 2) as u8), Qid((*slot * 2 + 1) as u8)] }, context: Some((*context).clone()), pair: Some(Box::new(Pair { quarantined: false, @@ -581,15 +622,25 @@ def release_fixture(): context: (*context).clone(), owner: Some(owner(*slot)), })), - parked: false, + pool: Some(()), + parked: None, preparing: None, + constructing: false, growing: false, pending_owner: None, pending_owner_closed: false, + pending_error: None, + pending_timeout: false, closed: false, }); } - let queues = Registry { admission, render: RenderState { entries }, teardown: g17::teardown::Pending::new().unwrap() }; + let queues = Registry { + admission, + render: RenderState { entries }, + teardown: g17::teardown::Pending::new().unwrap(), + qids: Qids, + buffers: Buffers, + }; Arc::new(Shared { state: DeviceLock(Mutex::new(Some(Box::new(Firmware { queues })))), channels: Channels }) } fn backend(shared: &Arc, slot: usize, context: &Arc) -> Backend { @@ -615,7 +666,7 @@ def release_fixture(): for entry in self.render.entries.iter_mut().flatten() { if entry.pair.as_ref().is_some_and(|pair| Arc::ptr_eq(pair.context(), context)) { entry.pair = None; - entry.parked = true; + entry.parked = Some(()); } } Ok(()) @@ -761,16 +812,68 @@ def release_fixture(): assert_eq!(admission(&shared).held, bit(20), "only the quarantined pair stays held"); } +/// Detaching an idle published sibling in `reclaim_unused_render_spare` must keep +/// `admission.owners[slot]` synced with `entry.reservation.owner`/`entry.context` in +/// `released` state so `exit_scope` + `hold_render_slots_for_exit_kill` still succeed if +/// the prior owner exits before the requester binds the slot. +fn spare_detach_keeps_exit_kill_ownership() { + let old_ctx = context(0x40); + let shared = device(&[(1, &old_ctx), (2, &old_ctx)]); + let old_owner = owner(1); + with(&shared, |firmware| { + let mut state = firmware.queues.admission.state.lock(); + state.owners[2] = old_owner; + state.refs[1] = 1; + state.active |= bit(1); + state.published |= bit(1) | bit(2); + let entry2 = firmware.queues.render.entries[2].as_mut().unwrap(); + entry2.reservation.owner = old_owner; + entry2.pair.as_mut().unwrap().owner = Some(old_owner); + }); + let spare = with(&shared, |firmware| { + firmware + .queues + .reclaim_unused_render_spare(Some(NEW), false) + .unwrap() + }); + assert!(spare.is_some()); + drop(spare); + let state = admission(&shared); + assert_eq!(state.owners[2], old_owner); + assert_ne!(state.released & bit(2), 0); + assert_eq!(state.published & bit(2), 0); + with(&shared, |firmware| { + { + let mut state = firmware.queues.admission.state.lock(); + state.refs[1] = 0; + state.active &= !bit(1); + } + let (own, _, slots) = firmware.queues.render.exit_scope(&old_ctx); + assert_ne!(slots & bit(2), 0); + assert_eq!(firmware.queues.render.slot_owner(2), Some(old_owner)); + let qids = own; + let hold = (0..SLOTS as u8) + .filter(|slot| slots & bit(usize::from(*slot)) != 0 + && firmware.queues.render.qids_for_slot(*slot) & qids != 0) + .fold(0u64, |acc, slot| acc | bit(usize::from(slot))); + firmware.queues.admission.release_owner(old_owner); + assert!(firmware.queues.admission.hold_render_slots_for_exit_kill(old_owner, hold, 0)); + }); +} + fn main() { closed_owner_release(); work_and_lent_pairs(); - println!("PASS release holds: a closed owner's idle pair is held from its close, before admission releases its slot, through retirement passes and resyncs, until its scheduler release is consumed and the pair parked; no new owner is given it meanwhile; quarantined and owed pairs are held by the same rule and their own owner keeps them; a lent pair keeps its bit and is held when its owner closes meanwhile; a missing or parked pair is never held"); + spare_detach_keeps_exit_kill_ownership(); + println!("PASS release holds: a closed owner's idle pair is held from its close, before admission releases its slot, through retirement passes and resyncs, until its scheduler release is consumed and the pair parked; no new owner is given it meanwhile; quarantined and owed pairs are held by the same rule and their own owner keeps them; a lent pair keeps its bit and is held when its owner closes meanwhile; a missing or parked pair is never held; detaching a published spare preserves exit-kill ownership"); } """ # Each drops one part of the runtime's hold rule. RELEASE_MUTATIONS = { + 'spare-detach-reassigns': ('let claimed = if detach {\n self.admission\n .release_unused_sibling(slot as u8, expected, true)\n } else {\n self.admission\n .reassign_unused_spare(slot as u8, expected, owner)\n };', + 'let claimed = self.admission.reassign_unused_spare(slot as u8, expected, owner);'), 'hold-ignores-release': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'pair.unreusable_work()'), 'hold-ignores-work': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'teardown.releasing(pair.context())'), 'close-unheld': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 64f040d04a627f..5cd01c4dfd617e 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -209,7 +209,7 @@ def mutations(flag, names, base, expect=KILL): 'held-blocks-owner', 'hold-ignores-release', 'hold-ignores-work', 'close-unheld', 'hold-after-release', 'put-back-own-work', 'sync-skips-lent', 'lent-close-unheld', 'parked-stays-held', - 'sync-clobbers', 'sync-no-wake'), []), + 'sync-clobbers', 'sync-no-wake', 'spare-detach-reassigns'), []), 'g17-capacity-backoff-tests.py': [([], PASS)], 'g17-capacity-fault-tests.py': [([], PASS)], 'g17-compute-constructor-tests.py': [([], PASS)], From 54e6600c85c60a1ba9571d62a20e123eb6d0ba28 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:45:58 +0100 Subject: [PATCH 0722/1514] arm64: dts: apple: j873: SMC temperature sensors and CPU thermal zones Describe the 125 SMC temperature channels that read back stable values on the J873g. The SMC hwmon node becomes an indexed thermal sensor provider instead of discovering its temperature keys, so that thermal zones can refer to the channels, and the CPU nodes become cooling devices. Give the SMC's CPU die channels a thermal zone each: Te* for the E cluster and Tp* for the P/M cluster, 30 in all. The J873g ADT's PMP temp-sensor table gives every CPU die sensor a 110 C target and a 125 C maximum, the same two values the M4 Max (J614c/J616c) die zone takes from its ADT. Each zone has a passive trip at the target, which throttles both clusters through cpufreq cooling, and a critical trip at the maximum. The other 95 channels stay reported through hwmon without a zone, since the ADT gives them no limit. The SMC's fan policy is no limit either: in its automatic mode it leaves the fan at its 1000 RPM minimum even at 93 C under sustained full load. The sensor list is that of Acelogic's J873 bring-up on linux-aurora j873. Signed-off-by: Thomas Glanzmann --- .../boot/dts/apple/t8152-j873-thermal.dtsi | 993 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 17 +- 2 files changed, 1008 insertions(+), 2 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi new file mode 100644 index 00000000000000..e5fcb164591238 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-thermal.dtsi @@ -0,0 +1,993 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Apple Mac mini (M6, J873g): SMC temperature sensors and CPU thermal zones. + * + * The SMC float temperature channels that read back stable values on the + * J873g; their physical locations are not established, so each keeps its SMC + * key as label. TVMD and the Tz* channels that read zero are left out. + * + * The limits are the machine's own: the J873g ADT's PMP temp-sensor table + * gives every CPU die sensor a 110 C target and a 125 C maximum, as on the + * other M4/M5-class Macs. The SMC's CPU die channels, Te* for the E cluster + * and Tp* for the P/M cluster, therefore each get a zone with a passive trip + * at the target, throttling both CPU clusters through cpufreq cooling, and a + * critical trip at the maximum. The other channels are reported only: the + * ADT gives them no limit. The SMC's own fan policy is no limit either; in + * its automatic mode it leaves the fan at its 1000 RPM minimum even at 93 C + * under sustained full load. + * + * Sensor list from Acelogic's J873 bring-up (linux-aurora j873). + */ + +#include + +&m6_smc_hwmon { + temperature-TCMb { apple,key-id = "TCMb"; label = "SMC TCMb"; }; + temperature-TH0a { apple,key-id = "TH0a"; label = "SMC TH0a"; }; + temperature-TH0b { apple,key-id = "TH0b"; label = "SMC TH0b"; }; + temperature-TH0x { apple,key-id = "TH0x"; label = "SMC TH0x"; }; + temperature-THSP { apple,key-id = "THSP"; label = "SMC THSP"; }; + temperature-TIED { apple,key-id = "TIED"; label = "SMC TIED"; }; + temperature-TMVR { apple,key-id = "TMVR"; label = "SMC TMVR"; }; + temperature-TN00 { apple,key-id = "TN00"; label = "SMC TN00"; }; + temperature-TN01 { apple,key-id = "TN01"; label = "SMC TN01"; }; + temperature-TPD0 { apple,key-id = "TPD0"; label = "SMC TPD0"; }; + temperature-TPD1 { apple,key-id = "TPD1"; label = "SMC TPD1"; }; + temperature-TPD2 { apple,key-id = "TPD2"; label = "SMC TPD2"; }; + temperature-TPD3 { apple,key-id = "TPD3"; label = "SMC TPD3"; }; + temperature-TPD4 { apple,key-id = "TPD4"; label = "SMC TPD4"; }; + temperature-TPD7 { apple,key-id = "TPD7"; label = "SMC TPD7"; }; + temperature-TPD9 { apple,key-id = "TPD9"; label = "SMC TPD9"; }; + temperature-TPDB { apple,key-id = "TPDB"; label = "SMC TPDB"; }; + temperature-TPDD { apple,key-id = "TPDD"; label = "SMC TPDD"; }; + temperature-TPDG { apple,key-id = "TPDG"; label = "SMC TPDG"; }; + temperature-TPDH { apple,key-id = "TPDH"; label = "SMC TPDH"; }; + temperature-TPDI { apple,key-id = "TPDI"; label = "SMC TPDI"; }; + temperature-TPDJ { apple,key-id = "TPDJ"; label = "SMC TPDJ"; }; + temperature-TPDK { apple,key-id = "TPDK"; label = "SMC TPDK"; }; + temperature-TPDL { apple,key-id = "TPDL"; label = "SMC TPDL"; }; + temperature-TPDM { apple,key-id = "TPDM"; label = "SMC TPDM"; }; + temperature-TPDN { apple,key-id = "TPDN"; label = "SMC TPDN"; }; + temperature-TPDX { apple,key-id = "TPDX"; label = "SMC TPDX"; }; + temperature-TPMP { apple,key-id = "TPMP"; label = "SMC TPMP"; }; + temperature-TPSD { apple,key-id = "TPSD"; label = "SMC TPSD"; }; + temperature-TPSP { apple,key-id = "TPSP"; label = "SMC TPSP"; }; + temperature-TRD5 { apple,key-id = "TRD5"; label = "SMC TRD5"; }; + temperature-TRD6 { apple,key-id = "TRD6"; label = "SMC TRD6"; }; + temperature-TRD8 { apple,key-id = "TRD8"; label = "SMC TRD8"; }; + temperature-TRDA { apple,key-id = "TRDA"; label = "SMC TRDA"; }; + temperature-TRDC { apple,key-id = "TRDC"; label = "SMC TRDC"; }; + temperature-TRDE { apple,key-id = "TRDE"; label = "SMC TRDE"; }; + temperature-TRDF { apple,key-id = "TRDF"; label = "SMC TRDF"; }; + temperature-TRDG { apple,key-id = "TRDG"; label = "SMC TRDG"; }; + temperature-TRDX { apple,key-id = "TRDX"; label = "SMC TRDX"; }; + temperature-TSCB { apple,key-id = "TSCB"; label = "SMC TSCB"; }; + temperature-TSCD { apple,key-id = "TSCD"; label = "SMC TSCD"; }; + temperature-TT0P { apple,key-id = "TT0P"; label = "SMC TT0P"; }; + temperature-TUVS { apple,key-id = "TUVS"; label = "SMC TUVS"; }; + temperature-TVD0 { apple,key-id = "TVD0"; label = "SMC TVD0"; }; + temperature-TVDA { apple,key-id = "TVDA"; label = "SMC TVDA"; }; + temperature-TVDC { apple,key-id = "TVDC"; label = "SMC TVDC"; }; + temperature-TVDE { apple,key-id = "TVDE"; label = "SMC TVDE"; }; + temperature-TVDG { apple,key-id = "TVDG"; label = "SMC TVDG"; }; + temperature-TVDP { apple,key-id = "TVDP"; label = "SMC TVDP"; }; + temperature-TVN0 { apple,key-id = "TVN0"; label = "SMC TVN0"; }; + temperature-TVN1 { apple,key-id = "TVN1"; label = "SMC TVN1"; }; + temperature-TVNS { apple,key-id = "TVNS"; label = "SMC TVNS"; }; + temperature-TVS0 { apple,key-id = "TVS0"; label = "SMC TVS0"; }; + temperature-TW0P { apple,key-id = "TW0P"; label = "SMC TW0P"; }; + temperature-Ta0O { apple,key-id = "Ta0O"; label = "SMC Ta0O"; }; + temperature-Ta0P { apple,key-id = "Ta0P"; label = "SMC Ta0P"; }; + temperature-Ta0Q { apple,key-id = "Ta0Q"; label = "SMC Ta0Q"; }; + temperature-Ta0S { apple,key-id = "Ta0S"; label = "SMC Ta0S"; }; + temperature-Ta0T { apple,key-id = "Ta0T"; label = "SMC Ta0T"; }; + temperature-Ta0V { apple,key-id = "Ta0V"; label = "SMC Ta0V"; }; + temperature-Ta0b { apple,key-id = "Ta0b"; label = "SMC Ta0b"; }; + temperature-Ta0c { apple,key-id = "Ta0c"; label = "SMC Ta0c"; }; + temperature-Ta0e { apple,key-id = "Ta0e"; label = "SMC Ta0e"; }; + temperature-Ta0f { apple,key-id = "Ta0f"; label = "SMC Ta0f"; }; + temperature-Ta0g { apple,key-id = "Ta0g"; label = "SMC Ta0g"; }; + temperature-Ta0h { apple,key-id = "Ta0h"; label = "SMC Ta0h"; }; + temperature-Te07 { apple,key-id = "Te07"; label = "SMC Te07"; }; + temperature-Te08 { apple,key-id = "Te08"; label = "SMC Te08"; }; + temperature-Te09 { apple,key-id = "Te09"; label = "SMC Te09"; }; + temperature-Te0c { apple,key-id = "Te0c"; label = "SMC Te0c"; }; + temperature-Te0e { apple,key-id = "Te0e"; label = "SMC Te0e"; }; + temperature-Te0f { apple,key-id = "Te0f"; label = "SMC Te0f"; }; + temperature-Te0g { apple,key-id = "Te0g"; label = "SMC Te0g"; }; + temperature-Te0h { apple,key-id = "Te0h"; label = "SMC Te0h"; }; + temperature-Te0i { apple,key-id = "Te0i"; label = "SMC Te0i"; }; + temperature-TfC1 { apple,key-id = "TfC1"; label = "SMC TfC1"; }; + temperature-TfCD { apple,key-id = "TfCD"; label = "SMC TfCD"; }; + temperature-Tg01 { apple,key-id = "Tg01"; label = "SMC Tg01"; }; + temperature-Tg07 { apple,key-id = "Tg07"; label = "SMC Tg07"; }; + temperature-Tg08 { apple,key-id = "Tg08"; label = "SMC Tg08"; }; + temperature-Tg09 { apple,key-id = "Tg09"; label = "SMC Tg09"; }; + temperature-Tg0a { apple,key-id = "Tg0a"; label = "SMC Tg0a"; }; + temperature-Tg0b { apple,key-id = "Tg0b"; label = "SMC Tg0b"; }; + temperature-Tg0c { apple,key-id = "Tg0c"; label = "SMC Tg0c"; }; + temperature-Tg0d { apple,key-id = "Tg0d"; label = "SMC Tg0d"; }; + temperature-Tg10 { apple,key-id = "Tg10"; label = "SMC Tg10"; }; + temperature-Tg17 { apple,key-id = "Tg17"; label = "SMC Tg17"; }; + temperature-Tg1a { apple,key-id = "Tg1a"; label = "SMC Tg1a"; }; + temperature-Tg1b { apple,key-id = "Tg1b"; label = "SMC Tg1b"; }; + temperature-Tg1c { apple,key-id = "Tg1c"; label = "SMC Tg1c"; }; + temperature-Tg1d { apple,key-id = "Tg1d"; label = "SMC Tg1d"; }; + temperature-Tg1e { apple,key-id = "Tg1e"; label = "SMC Tg1e"; }; + temperature-Tg1f { apple,key-id = "Tg1f"; label = "SMC Tg1f"; }; + temperature-Tg1g { apple,key-id = "Tg1g"; label = "SMC Tg1g"; }; + temperature-Tg1h { apple,key-id = "Tg1h"; label = "SMC Tg1h"; }; + temperature-Tp05 { apple,key-id = "Tp05"; label = "SMC Tp05"; }; + temperature-Tp07 { apple,key-id = "Tp07"; label = "SMC Tp07"; }; + temperature-Tp09 { apple,key-id = "Tp09"; label = "SMC Tp09"; }; + temperature-Tp0A { apple,key-id = "Tp0A"; label = "SMC Tp0A"; }; + temperature-Tp0E { apple,key-id = "Tp0E"; label = "SMC Tp0E"; }; + temperature-Tp0G { apple,key-id = "Tp0G"; label = "SMC Tp0G"; }; + temperature-Tp0I { apple,key-id = "Tp0I"; label = "SMC Tp0I"; }; + temperature-Tp0L { apple,key-id = "Tp0L"; label = "SMC Tp0L"; }; + temperature-Tp0b { apple,key-id = "Tp0b"; label = "SMC Tp0b"; }; + temperature-Tp0d { apple,key-id = "Tp0d"; label = "SMC Tp0d"; }; + temperature-Tp0g { apple,key-id = "Tp0g"; label = "SMC Tp0g"; }; + temperature-Tp0j { apple,key-id = "Tp0j"; label = "SMC Tp0j"; }; + temperature-Tp0m { apple,key-id = "Tp0m"; label = "SMC Tp0m"; }; + temperature-Tp0o { apple,key-id = "Tp0o"; label = "SMC Tp0o"; }; + temperature-Tp0r { apple,key-id = "Tp0r"; label = "SMC Tp0r"; }; + temperature-Tp0t { apple,key-id = "Tp0t"; label = "SMC Tp0t"; }; + temperature-Tp0u { apple,key-id = "Tp0u"; label = "SMC Tp0u"; }; + temperature-Tp0w { apple,key-id = "Tp0w"; label = "SMC Tp0w"; }; + temperature-Tp0x { apple,key-id = "Tp0x"; label = "SMC Tp0x"; }; + temperature-Tp0y { apple,key-id = "Tp0y"; label = "SMC Tp0y"; }; + temperature-Tp0z { apple,key-id = "Tp0z"; label = "SMC Tp0z"; }; + temperature-Ts00 { apple,key-id = "Ts00"; label = "SMC Ts00"; }; + temperature-Ts01 { apple,key-id = "Ts01"; label = "SMC Ts01"; }; + temperature-Ts02 { apple,key-id = "Ts02"; label = "SMC Ts02"; }; + temperature-Ts03 { apple,key-id = "Ts03"; label = "SMC Ts03"; }; + temperature-Ts04 { apple,key-id = "Ts04"; label = "SMC Ts04"; }; + temperature-Ts05 { apple,key-id = "Ts05"; label = "SMC Ts05"; }; + temperature-Ts06 { apple,key-id = "Ts06"; label = "SMC Ts06"; }; + temperature-Ts07 { apple,key-id = "Ts07"; label = "SMC Ts07"; }; + temperature-Ts08 { apple,key-id = "Ts08"; label = "SMC Ts08"; }; +}; +/ { + thermal-zones { + smc-te07-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 66>; + + trips { + m6_Te07_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te07_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te08-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 67>; + + trips { + m6_Te08_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te08_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te09-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 68>; + + trips { + m6_Te09_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te09_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0c-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 69>; + + trips { + m6_Te0c_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0c_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0e-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 70>; + + trips { + m6_Te0e_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0e_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0f-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 71>; + + trips { + m6_Te0f_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0f_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0g-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 72>; + + trips { + m6_Te0g_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0g_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0h-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 73>; + + trips { + m6_Te0h_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0h_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-te0i-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 74>; + + trips { + m6_Te0i_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Te0i_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp05-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 95>; + + trips { + m6_Tp05_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp05_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp07-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 96>; + + trips { + m6_Tp07_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp07_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp09-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 97>; + + trips { + m6_Tp09_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp09_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0a-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 98>; + + trips { + m6_Tp0A_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0A_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0e-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 99>; + + trips { + m6_Tp0E_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0E_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0g-2-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 100>; + + trips { + m6_Tp0G_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0G_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0i-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 101>; + + trips { + m6_Tp0I_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0I_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0l-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 102>; + + trips { + m6_Tp0L_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0L_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0b-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 103>; + + trips { + m6_Tp0b_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0b_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0d-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 104>; + + trips { + m6_Tp0d_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0d_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0g-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 105>; + + trips { + m6_Tp0g_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0g_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0j-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 106>; + + trips { + m6_Tp0j_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0j_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0m-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 107>; + + trips { + m6_Tp0m_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0m_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0o-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 108>; + + trips { + m6_Tp0o_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0o_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0r-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 109>; + + trips { + m6_Tp0r_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0r_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0t-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 110>; + + trips { + m6_Tp0t_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0t_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0u-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 111>; + + trips { + m6_Tp0u_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0u_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0w-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 112>; + + trips { + m6_Tp0w_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0w_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0x-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 113>; + + trips { + m6_Tp0x_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0x_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0y-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 114>; + + trips { + m6_Tp0y_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0y_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + + smc-tp0z-thermal { + polling-delay = <2000>; + polling-delay-passive = <500>; + thermal-sensors = <&m6_smc_hwmon 115>; + + trips { + m6_Tp0z_passive: passive { + temperature = <110000>; + hysteresis = <5000>; + type = "passive"; + }; + + critical { + temperature = <125000>; + hysteresis = <0>; + type = "critical"; + }; + }; + + cooling-maps { + map0 { + trip = <&m6_Tp0z_passive>; + cooling-device = <&cpu0 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>, + <&cpu6 THERMAL_NO_LIMIT THERMAL_NO_LIMIT>; + }; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 5c229e74d5b0a7..a4e97ce08f1b4a 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -69,6 +69,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu1: cpu@1 { @@ -79,6 +80,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu2: cpu@2 { @@ -89,6 +91,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu3: cpu@3 { @@ -99,6 +102,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu4: cpu@4 { @@ -109,6 +113,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu5: cpu@5 { @@ -119,6 +124,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; performance-domains = <&m6_e_cpufreq>; + #cooling-cells = <2>; }; cpu6: cpu@10100 { @@ -129,6 +135,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu7: cpu@10101 { @@ -139,6 +146,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu8: cpu@40102 { @@ -149,6 +157,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu9: cpu@40103 { @@ -159,6 +168,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu10: cpu@40104 { @@ -169,6 +179,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; cpu11: cpu@40105 { @@ -179,6 +190,7 @@ cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; performance-domains = <&m6_pm_cpufreq>; + #cooling-cells = <2>; }; }; @@ -332,9 +344,9 @@ "boot_error_count", "panic_count"; }; - hwmon { + m6_smc_hwmon: hwmon { compatible = "apple,smc-hwmon"; - apple,discover-temperatures; + #thermal-sensor-cells = <1>; fan-F0Ac { apple,key-id = "F0Ac"; @@ -504,3 +516,4 @@ #include "t8152-j873-audio.dtsi" #include "t8152-j873-dcp.dtsi" #include "t8152-j873-avd.dtsi" +#include "t8152-j873-thermal.dtsi" From dca7305f39ce1aa6baaa39943fdc36cbf5d045b6 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:46:04 +0100 Subject: [PATCH 0723/1514] arm64: dts: apple: j873: all CPU performance states The J873g exposes only the two lowest performance states per cluster until its cooling is described. With the SMC thermal zones in place, add the rest: E up to 2940 MHz (voltage-states1-sram) and P/M up to 4788 MHz (voltage-states5-sram), as the ADT pmgr lists them. opp-level is the hardware P-state, the table index plus two (the ADT's cpu-perf-state0-index), as for the two existing states. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873g.dts | 92 +++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index a4e97ce08f1b4a..8a52cf7e8d3286 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -205,6 +205,26 @@ opp-hz = /bits/ 64 <1152000000>; opp-level = <3>; }; + opp-1584000000 { + opp-hz = /bits/ 64 <1584000000>; + opp-level = <4>; + }; + opp-1980000000 { + opp-hz = /bits/ 64 <1980000000>; + opp-level = <5>; + }; + opp-2304000000 { + opp-hz = /bits/ 64 <2304000000>; + opp-level = <6>; + }; + opp-2640000000 { + opp-hz = /bits/ 64 <2640000000>; + opp-level = <7>; + }; + opp-2940000000 { + opp-hz = /bits/ 64 <2940000000>; + opp-level = <8>; + }; }; m6_pm_opp: opp-table-pm { compatible = "operating-points-v2"; @@ -217,6 +237,78 @@ opp-hz = /bits/ 64 <1728000000>; opp-level = <3>; }; + opp-2040000000 { + opp-hz = /bits/ 64 <2040000000>; + opp-level = <4>; + }; + opp-2340000000 { + opp-hz = /bits/ 64 <2340000000>; + opp-level = <5>; + }; + opp-2640000000 { + opp-hz = /bits/ 64 <2640000000>; + opp-level = <6>; + }; + opp-2940000000 { + opp-hz = /bits/ 64 <2940000000>; + opp-level = <7>; + }; + opp-3216000000 { + opp-hz = /bits/ 64 <3216000000>; + opp-level = <8>; + }; + opp-3468000000 { + opp-hz = /bits/ 64 <3468000000>; + opp-level = <9>; + }; + opp-3696000000 { + opp-hz = /bits/ 64 <3696000000>; + opp-level = <10>; + }; + opp-3924000000 { + opp-hz = /bits/ 64 <3924000000>; + opp-level = <11>; + }; + opp-4092000000 { + opp-hz = /bits/ 64 <4092000000>; + opp-level = <12>; + }; + opp-4272000000 { + opp-hz = /bits/ 64 <4272000000>; + opp-level = <13>; + }; + opp-4416000000 { + opp-hz = /bits/ 64 <4416000000>; + opp-level = <14>; + }; + opp-4476000000 { + opp-hz = /bits/ 64 <4476000000>; + opp-level = <15>; + }; + opp-4512000000 { + opp-hz = /bits/ 64 <4512000000>; + opp-level = <16>; + }; + opp-4536000000 { + opp-hz = /bits/ 64 <4536000000>; + opp-level = <17>; + }; + opp-4584000000 { + opp-hz = /bits/ 64 <4584000000>; + opp-level = <18>; + }; + opp-4644000000 { + opp-hz = /bits/ 64 <4644000000>; + opp-level = <19>; + }; + opp-4692000000 { + opp-hz = /bits/ 64 <4692000000>; + opp-level = <20>; + }; + opp-4788000000 { + opp-hz = /bits/ 64 <4788000000>; + opp-level = <21>; + }; }; /* The 24 MHz timebase (ADT timebase-frequency), as on T8103. */ From 395cf5c2e9b773322b70680d3648716c5cc058d6 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 13 Nov 2026 09:46:35 +0100 Subject: [PATCH 0724/1514] cpufreq: apple-soc: lift the T8152 ceiling where the DT cools the CPUs T8152 keeps the ceiling at its two lowest P-states because no thermal policy had been provided for it, as commit 4c3405d11d29 ("cpufreq: apple: retain the unmanaged P-state ceiling on T8152") put it. Its needs_thermal_policy, without a PMP fast die-temperature loop (apple,fast-die-effort, not available on T8152), also holds each cluster at the fallback limit, a third of its top state: 1440 MHz on the P/M cluster even with only two states. The J873g DT now supplies a thermal policy: SMC thermal zones with passive trips that throttle both clusters through cpufreq cooling. Let a T8152 board DT qualify the higher states that way. With the new zone_cooling_qualifies, a cluster whose cpufreq cooling device (the node of policy->cpu) is named in a cooling map of a thermal zone is no longer held to max_unmanaged_pstate, and needs_thermal_policy no longer asks it for a fast die-temperature limit. Any other T8152 tree keeps both: a board runs the higher states only once its own DT throttles them. WFxT, which the transition polling would otherwise execute, is already treated as absent on T8152. Signed-off-by: Thomas Glanzmann --- drivers/cpufreq/apple-soc-cpufreq.c | 68 +++++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 09233d4b4208d7..4ea968ae087e34 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -211,6 +211,12 @@ struct apple_soc_cpufreq_info { u32 transition_timeout_us; /* Highest P-state allowed without a thermal policy; 0 if not capped. */ u32 max_unmanaged_pstate; + /* + * A board DT whose thermal zones list the cluster's CPU as a cooling + * device is that thermal policy: it lifts max_unmanaged_pstate and + * stands in for needs_thermal_policy's fast die-temperature limit. + */ + bool zone_cooling_qualifies; u64 min_pstate; u64 max_pstate; u64 cur_pstate_mask; @@ -228,6 +234,8 @@ struct apple_cpu_priv { unsigned int expected_pstate; struct freq_qos_request unmanaged_cap; bool thermal_owned; + /* zone_cooling_qualifies, and the DT's thermal zones cool the cluster */ + bool zone_cooled; /* * Lazy verification, see apple_soc_cpufreq_lazy_request(): the lock * serialises the command register, expected_pstate and @@ -314,12 +322,17 @@ static const struct apple_soc_cpufreq_info soc_t8142_info = { .ps1_shift = APPLE_DVFS_CMD_PS1_SHIFT, }; -/* T8152 ACC uses state 2 as the first OPP and shares P/M requests. */ +/* + * T8152 ACC uses state 2 as the first OPP and shares P/M requests. Above + * state 3 it needs a board thermal policy: thermal zones in the DT that + * throttle the cluster's CPUs (the J873g's SMC zones). + */ static const struct apple_soc_cpufreq_info soc_t8152_info = { .verify_transition = true, .needs_thermal_policy = true, .transition_timeout_us = 2000, .max_unmanaged_pstate = 3, + .zone_cooling_qualifies = true, .min_pstate = 2, .max_pstate = 31, .ps1_mask = APPLE_DVFS_CMD_PS1, @@ -1180,7 +1193,8 @@ static int apple_fast_die_init(struct cpufreq_policy *policy, parsed = of_parse_phandle_with_fixed_args(cluster, "apple,fast-die-effort", 1, 0, &args); /* Required thermal admission must fail closed with an older DT. */ - if (parsed == -ENOENT && !priv->info->needs_thermal_policy) + if (parsed == -ENOENT && + (!priv->info->needs_thermal_policy || priv->zone_cooled)) return 0; while (policy->freq_table[n].frequency != CPUFREQ_TABLE_END) @@ -1387,6 +1401,50 @@ int apple_soc_cpufreq_set_thermal_owner(struct cpufreq_policy *policy, bool owne } EXPORT_SYMBOL_GPL(apple_soc_cpufreq_set_thermal_owner); +/* Whether a cooling map of a thermal zone in zones lists cpu as a device */ +static bool apple_soc_cpufreq_cpu_cooled(struct device_node *zones, + struct device_node *cpu) +{ + for_each_available_child_of_node_scoped(zones, zone) { + struct device_node *maps __free(device_node) = + of_get_child_by_name(zone, "cooling-maps"); + + if (!maps) + continue; + for_each_child_of_node_scoped(maps, map) { + struct of_phandle_args args; + int i; + + for (i = 0;; i++) { + if (of_parse_phandle_with_args(map, "cooling-device", + "#cooling-cells", i, + &args)) + break; + of_node_put(args.np); + if (args.np == cpu) + return true; + } + } + } + return false; +} + +/* + * Whether the DT's thermal zones throttle the cluster: the board thermal + * policy that zone_cooling_qualifies accepts. The cluster's cpufreq cooling + * device is registered for the node of policy->cpu, so that is the node a + * cooling map has to name. A tree without one keeps the SoC's ceiling. + */ +static bool apple_soc_cpufreq_zone_cooled(struct cpufreq_policy *policy) +{ + struct device_node *zones __free(device_node) = + of_find_node_by_path("/thermal-zones"); + struct device_node *np __free(device_node) = + of_cpu_device_node_get(policy->cpu); + + return zones && np && apple_soc_cpufreq_cpu_cooled(zones, np); +} + static int apple_soc_cpufreq_init(struct cpufreq_policy *policy) { struct cpufreq_frequency_table *p; @@ -1487,8 +1545,12 @@ static int apple_soc_cpufreq_init(struct cpufreq_policy *policy) priv->expected_pstate = state; } + priv->zone_cooled = info->zone_cooling_qualifies && + apple_soc_cpufreq_zone_cooled(policy); + /* SoCs without a qualified thermal policy keep their bootstrap ceiling. */ - if (info->max_unmanaged_pstate && !info->needs_thermal_owner) { + if (info->max_unmanaged_pstate && !info->needs_thermal_owner && + !priv->zone_cooled) { cpufreq_for_each_valid_entry(p, freq_table) { if (p->driver_data <= info->max_unmanaged_pstate) continue; From 1d2c710dc94c377aefd7dbc23ce30ad7dc0e2b40 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 01:34:11 +0100 Subject: [PATCH 0725/1514] arm64: dts: apple: j873: describe the CPU clusters and their capacities The J873g's CPUs had no cpu-map and no capacity-dmips-mhz. The arch topology code parses capacity-dmips-mhz only while walking a cpu-map, so every CPU got capacity 1024 and cluster_id -1. The scheduler then treats the six E cores like the P and M cores: on the M6 desktop, the busiest threads of a browser dragging Google Maps run 65-77 % of their time on E cores. Describe the three clusters (E: cpu@0-5, P: cpu@10100-10101, M: cpu@40102-40105, as their MPIDR affinities group them) and give each core type its single-thread work per MHz relative to a P core. The values are the mean of three single-thread loops run at each cluster's top P-state with the performance governor (Python integer loop, zlib compression, sort/JSON). Relative to a P core at 4788 MHz, M cores manage 80 % at the same clock, and E cores 48 % at 2940 MHz, which is 78 % per MHz: E 800, P 1024, M 819 With these, cpu_capacity reads E 491, P 1024, M 819, and the clusters show as 0, 1 and 2. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873g.dts | 65 +++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 8a52cf7e8d3286..6b0cdc25d227ba 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -61,6 +61,59 @@ #address-cells = <2>; #size-cells = <0>; + /* + * Three clusters: E (6 cores), P (2) and M (4); P and M share a + * performance domain. capacity-dmips-mhz is single-thread work per + * MHz relative to a P core, from integer, compression and sort + * loops at each cluster's top P-state. + */ + cpu-map { + cluster0 { + core0 { + cpu = <&cpu0>; + }; + core1 { + cpu = <&cpu1>; + }; + core2 { + cpu = <&cpu2>; + }; + core3 { + cpu = <&cpu3>; + }; + core4 { + cpu = <&cpu4>; + }; + core5 { + cpu = <&cpu5>; + }; + }; + + cluster1 { + core0 { + cpu = <&cpu6>; + }; + core1 { + cpu = <&cpu7>; + }; + }; + + cluster2 { + core0 { + cpu = <&cpu8>; + }; + core1 { + cpu = <&cpu9>; + }; + core2 { + cpu = <&cpu10>; + }; + core3 { + cpu = <&cpu11>; + }; + }; + }; + cpu0: cpu@0 { compatible = "apple,t8152-e"; device_type = "cpu"; @@ -68,6 +121,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -79,6 +133,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -90,6 +145,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -101,6 +157,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -112,6 +169,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -123,6 +181,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_e_opp>; + capacity-dmips-mhz = <800>; performance-domains = <&m6_e_cpufreq>; #cooling-cells = <2>; }; @@ -134,6 +193,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <1024>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; @@ -145,6 +205,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <1024>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; @@ -156,6 +217,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; @@ -167,6 +229,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; @@ -178,6 +241,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; @@ -189,6 +253,7 @@ enable-method = "spin-table"; cpu-release-addr = <0 0>; /* Filled by the loader. */ operating-points-v2 = <&m6_pm_opp>; + capacity-dmips-mhz = <819>; performance-domains = <&m6_pm_cpufreq>; #cooling-cells = <2>; }; From 3f9912b0710e6a62b5e22a9f31f802c522742112 Mon Sep 17 00:00:00 2001 From: zoan37 <104385984+zoan37@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:24:49 -0500 Subject: [PATCH 0726/1514] wifi: mt7932: join WPA2-PSK APs with a TKIP group key An AP in WPA/WPA2 mixed mode offers CCMP and TKIP pairwise ciphers with a TKIP group cipher. The driver registers only CCMP, so iwd refuses the BSS with NotSupported before any association attempt, and the failure looks like a wrong password. The firmware runs the handshake and owns the keys, and it joined such an AP and passed unicast and group traffic with no other change. Register TKIP and accept it as the group cipher for WPA2-PSK. Pairwise TKIP, WPA1, and a TKIP group with SAE or OWE stay refused. Tested on J700 against one AP's 5 GHz network: gateway and internet traffic, DNS, and mDNS discovery of other LAN devices through the group key. Link: https://github.com/omacom/linux-aurora/issues/398 Signed-off-by: zoan37 <104385984+zoan37@users.noreply.github.com> Signed-off-by: Scott Jones --- .../mediatek/mt7932/association-test.c | 33 +++++++++++++++++-- .../wireless/mediatek/mt7932/association.h | 10 +++++- .../net/wireless/mediatek/mt7932/startup.c | 1 + 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/drivers/net/wireless/mediatek/mt7932/association-test.c b/drivers/net/wireless/mediatek/mt7932/association-test.c index 08dc14c6f89e49..8f828f2b299858 100644 --- a/drivers/net/wireless/mediatek/mt7932/association-test.c +++ b/drivers/net/wireless/mediatek/mt7932/association-test.c @@ -176,6 +176,7 @@ enum mt_auth_change { MT_AUTH_NO_PASSWORD, MT_AUTH_WPA, MT_AUTH_PAIR_COUNT, MT_AUTH_PAIR, MT_AUTH_GROUP, MT_AUTH_NO_AKM, MT_AUTH_PSK_FIRST, MT_AUTH_SAE_FIRST, MT_AUTH_OTHER_FIRST, MT_AUTH_OTHER_AKM, MT_AUTH_PSK, + MT_AUTH_OWE, }; static void mt_connect_auth_test(struct kunit *test) @@ -189,6 +190,13 @@ static void mt_connect_auth_test(struct kunit *test) { "pure PSK", MT_AUTH_PSK, 0, WLAN_AKM_SUITE_PSK }, { "PSK missing PMK", MT_AUTH_PSK, 1, -EOPNOTSUPP }, { "PSK required MFP", MT_AUTH_PSK, 2, WLAN_AKM_SUITE_PSK }, + { "PSK TKIP group", MT_AUTH_PSK, 3, WLAN_AKM_SUITE_PSK }, + { "PSK TKIP pairwise", MT_AUTH_PSK, 4, -EOPNOTSUPP }, + { "PSK WEP group", MT_AUTH_PSK, 5, -EOPNOTSUPP }, + { "PSK TKIP group missing PMK", MT_AUTH_PSK, 6, -EOPNOTSUPP }, + { "PSK TKIP group WPA1", MT_AUTH_PSK, 7, -EOPNOTSUPP }, + { "OWE", MT_AUTH_OWE, WLAN_CIPHER_SUITE_CCMP, WLAN_AKM_SUITE_OWE }, + { "OWE TKIP group", MT_AUTH_OWE, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, { "pure SAE", MT_AUTH_NONE, 0, WLAN_AKM_SUITE_SAE }, { "optional MFP", MT_AUTH_MFP, NL80211_MFP_OPTIONAL, WLAN_AKM_SUITE_SAE }, { "no MFP", MT_AUTH_MFP, NL80211_MFP_NO, -EOPNOTSUPP }, @@ -213,7 +221,7 @@ static void mt_connect_auth_test(struct kunit *test) { "no pairwise", MT_AUTH_PAIR_COUNT, 0, -EOPNOTSUPP }, { "multiple pairwise", MT_AUTH_PAIR_COUNT, 2, -EOPNOTSUPP }, { "TKIP pairwise", MT_AUTH_PAIR, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, - { "TKIP group", MT_AUTH_GROUP, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, + { "SAE TKIP group", MT_AUTH_GROUP, WLAN_CIPHER_SUITE_TKIP, -EOPNOTSUPP }, { "no AKM", MT_AUTH_NO_AKM, 0, -EOPNOTSUPP }, { "SAE EXT KEY", MT_AUTH_OTHER_AKM, SUITE(0x000fac, 24), -EOPNOTSUPP }, { "PSK SHA256", MT_AUTH_OTHER_AKM, WLAN_AKM_SUITE_PSK_SHA256, -EOPNOTSUPP }, @@ -226,6 +234,8 @@ static void mt_connect_auth_test(struct kunit *test) { "PSK first mixed versions", MT_AUTH_PSK_FIRST, 4, WLAN_AKM_SUITE_PSK }, { "PSK first VERSION_3 only", MT_AUTH_PSK_FIRST, 5, -EOPNOTSUPP }, { "SAE first mixed versions", MT_AUTH_SAE_FIRST, 2, WLAN_AKM_SUITE_SAE }, + { "SAE first TKIP group", MT_AUTH_SAE_FIRST, 3, -EOPNOTSUPP }, + { "PSK first TKIP group", MT_AUTH_PSK_FIRST, 6, WLAN_AKM_SUITE_PSK }, { "unsupported AKM before SAE", MT_AUTH_OTHER_FIRST, 0, -EOPNOTSUPP }, }; u8 password[64] = {}, pmk[32] = {}; @@ -287,11 +297,26 @@ static void mt_connect_auth_test(struct kunit *test) case MT_AUTH_PSK: p.crypto.wpa_versions = NL80211_WPA_VERSION_2; p.crypto.akm_suites[0] = WLAN_AKM_SUITE_PSK; - p.crypto.psk = value == 1 ? NULL : pmk; + p.crypto.psk = value == 1 || value == 6 ? NULL : pmk; p.crypto.sae_pwd = NULL; p.crypto.sae_pwd_len = 0; p.auth_type = NL80211_AUTHTYPE_AUTOMATIC; p.mfp = value == 2 ? NL80211_MFP_REQUIRED : NL80211_MFP_NO; + if (value == 3 || value == 4 || value == 6 || value == 7) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; + if (value == 4) + p.crypto.ciphers_pairwise[0] = WLAN_CIPHER_SUITE_TKIP; + if (value == 5) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_WEP40; + if (value == 7) + p.crypto.wpa_versions = NL80211_WPA_VERSION_1; + break; + case MT_AUTH_OWE: + p.crypto.akm_suites[0] = WLAN_AKM_SUITE_OWE; + p.crypto.cipher_group = value; + p.crypto.sae_pwd = NULL; + p.crypto.sae_pwd_len = 0; + p.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; break; case MT_AUTH_PSK_FIRST: p.crypto.wpa_versions = value == 5 ? NL80211_WPA_VERSION_3 : @@ -305,6 +330,8 @@ static void mt_connect_auth_test(struct kunit *test) p.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; p.mfp = value == 2 ? NL80211_MFP_REQUIRED : value == 3 ? NL80211_MFP_NO : NL80211_MFP_OPTIONAL; + if (value == 6) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; break; case MT_AUTH_SAE_FIRST: p.crypto.n_akm_suites = 2; @@ -314,6 +341,8 @@ static void mt_connect_auth_test(struct kunit *test) p.crypto.sae_pwd = NULL; if (value == 2) p.crypto.wpa_versions |= NL80211_WPA_VERSION_2; + if (value == 3) + p.crypto.cipher_group = WLAN_CIPHER_SUITE_TKIP; p.mfp = NL80211_MFP_OPTIONAL; break; case MT_AUTH_OTHER_FIRST: diff --git a/drivers/net/wireless/mediatek/mt7932/association.h b/drivers/net/wireless/mediatek/mt7932/association.h index 78189eab6b279e..20d5f5c58e9042 100644 --- a/drivers/net/wireless/mediatek/mt7932/association.h +++ b/drivers/net/wireless/mediatek/mt7932/association.h @@ -42,6 +42,7 @@ static inline int mt7932_connect_auth(const struct cfg80211_connect_params *p) { u32 versions = p->crypto.wpa_versions; + bool tkip_group = p->crypto.cipher_group == WLAN_CIPHER_SUITE_TKIP; /* SAE offload clients use VERSION_3; older clients use VERSION_2. * A transition request can carry both. The selected AKM still owns @@ -51,7 +52,7 @@ mt7932_connect_auth(const struct cfg80211_connect_params *p) (versions & ~(NL80211_WPA_VERSION_2 | NL80211_WPA_VERSION_3)) || p->crypto.n_ciphers_pairwise != 1 || p->crypto.ciphers_pairwise[0] != WLAN_CIPHER_SUITE_CCMP || - p->crypto.cipher_group != WLAN_CIPHER_SUITE_CCMP || + (p->crypto.cipher_group != WLAN_CIPHER_SUITE_CCMP && !tkip_group) || p->crypto.n_akm_suites < 1) return -EOPNOTSUPP; @@ -60,6 +61,13 @@ mt7932_connect_auth(const struct cfg80211_connect_params *p) p->crypto.sae_pwe)) return -EOPNOTSUPP; + /* WPA/WPA2 mixed-mode APs pair a CCMP unicast key with a TKIP group + * key. The firmware owns the handshake and both keys. Only plain + * WPA2-PSK may do this; pairwise TKIP stays refused. + */ + if (tkip_group && p->crypto.akm_suites[0] != WLAN_AKM_SUITE_PSK) + return -EOPNOTSUPP; + switch (p->crypto.akm_suites[0]) { case WLAN_AKM_SUITE_PSK: /* iwd and wpa_supplicant both send REQUIRED once they have diff --git a/drivers/net/wireless/mediatek/mt7932/startup.c b/drivers/net/wireless/mediatek/mt7932/startup.c index 7f72432235a2cf..44135f806803fd 100644 --- a/drivers/net/wireless/mediatek/mt7932/startup.c +++ b/drivers/net/wireless/mediatek/mt7932/startup.c @@ -820,6 +820,7 @@ int mt_register_regulatory_gate(struct mt7932 *m) { static const int rates[] = {10,20,55,110,60,90,120,180,240,360,480,540}; static const u32 ciphers[] = { WLAN_CIPHER_SUITE_CCMP, + WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_AES_CMAC }; static const u32 akms[] = { WLAN_AKM_SUITE_PSK, From aa9a88625ced6c3aa19457c604158d28bb0c514d Mon Sep 17 00:00:00 2001 From: zoan37 <104385984+zoan37@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:28:59 -0500 Subject: [PATCH 0727/1514] docs: wifi: mt7932: describe the TKIP group key The station security notes still say CCMP only. Describe what the driver accepts, and record that MIC failure reporting and TKIP countermeasures are left to firmware and have not been verified. Link: https://github.com/omacom/linux-aurora/issues/398 Signed-off-by: zoan37 <104385984+zoan37@users.noreply.github.com> Signed-off-by: Scott Jones --- .../networking/device_drivers/wifi/mt7932-neo.rst | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst index 3fd4a1c81853e3..b4ae52ee79856f 100644 --- a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst +++ b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst @@ -113,7 +113,8 @@ Station security ---------------- The driver advertises PSK, PSK-SHA256, SAE and OWE with CCMP, plus -BIP-CMAC-128 for management protection. Firmware performs SAE +BIP-CMAC-128 for management protection. PSK also accepts a TKIP group key, +described below. Firmware performs SAE authentication and the four-way handshake and owns PTK, GTK and IGTK; there is no host key-install interface or external-auth exchange. @@ -154,6 +155,18 @@ a host PWE field. Exact PWE policy behavior on 2.4 and 5 GHz still needs qualification. SAE-PK, SAE-EXT-KEY and additional ciphers are not advertised. OWE and 6 GHz support are described below. +TKIP is registered so that WPA2-PSK can join a WPA/WPA2 mixed-mode access point, +which pairs a CCMP unicast key with a TKIP group key. Pairwise TKIP, WPA1, and a +TKIP group key with SAE or OWE are refused. Firmware owns the TKIP group key like +any other. MIC failure reporting and TKIP countermeasures are left to firmware and +have not been verified: firmware runs the four-way handshake, so the host has no +KCK and calling ``cfg80211_michael_mic_failure()`` would do nothing. + +J700 hardware testing joined one mixed-mode router on 2.4 and 5 GHz, and stayed +connected to a hostapd access point through 14 group rekeys at 60 second intervals +with ARP and mDNS still received. DHCP renewal, IPv6 router advertisements and a +commercial access point's own rekey still need qualification. + J700 hardware testing with NetworkManager and wpa_supplicant on a PSK+SAE transition network has confirmed, on 2.4 GHz channel 6 and 5 GHz channel 149: From 7bac81fc1f845802c66a48b8f0ff2c58f28420f3 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sat, 14 Nov 2026 10:38:49 -0500 Subject: [PATCH 0728/1514] cpufreq: apple-soc: offer no boost control without turbo-mode OPPs Since commit f677f7c87b7c ("cpufreq: apple-soc: start with boost enabled") the driver turns boost on when it registers. On SoCs whose device tree marks no OPP as turbo-mode, such as the MacBook Neo (T8140), no policy supports boost. The driver still sets .set_boost, so the core creates the global boost file anyway, and enabling it fails: cpufreq: cpufreq_boost_trigger_state: Cannot enable BOOST cpufreq: store_boost: Cannot enable BOOST! power-profiles-daemon writes that file when it applies a profile, so on these Macs it fails, and power-saver no longer lowers the CPU limit. Leave .set_boost unset when the tree has no turbo-mode OPP, so no boost file appears there. SoCs with turbo-mode OPPs keep boost control as before. Tested on a MacBook Neo, and on an M3 MacBook Air (J613) before commit 1135a0a122fc ("arm64: dts: apple: t8122: mark the P-core boost states turbo-mode") gave its tree turbo-mode OPPs: no boost errors, and power-saver caps the P-cores (J613: 4056 to 2424 MHz). On a 16" M4 Pro (J616s) the boost file is still there: power-saver runs the P-cores at 4104 MHz and performance at 4512 MHz. Signed-off-by: Scott Jones --- drivers/cpufreq/apple-soc-cpufreq.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 09233d4b4208d7..9f606b37e3662a 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -1626,6 +1626,19 @@ static int __init apple_soc_cpufreq_module_init(void) if (!of_machine_is_compatible("apple,arm-platform")) return -ENODEV; + + /* + * Boost only means something with turbo-mode OPPs. Without any, no + * policy supports it, and turning it on through the global "boost" + * file fails with -EINVAL; power-profiles-daemon then cannot set its + * profile. Offer no boost control on such SoCs. + */ + np = of_find_node_with_property(NULL, "turbo-mode"); + if (np) + of_node_put(np); + else + apple_soc_cpufreq_driver.set_boost = NULL; + if (of_machine_is_compatible("apple,t8132")) { apple_soc_cpufreq_driver.online = apple_soc_cpufreq_online; apple_soc_cpufreq_driver.offline = apple_soc_cpufreq_offline; From 1102ece017fda1bd9755504711d8233922211289 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Thu, 22 Oct 2026 18:45:06 -0500 Subject: [PATCH 0729/1514] PCI: apple: enable the root-port prefetchable window on cold-initialized tunnel ports apple_pcie_config_write() tells the port block about the root port's prefetchable window (PORT_PREFMEM_ENABLE, port register 0x994) when the PCI core programs PREF_MEMORY_BASE/LIMIT, but only if pcie->kernel_init is set. kernel_init is true for apple,t8103-pciec with apple,pciec-kernel-init. The T600x/T602x tunnel ports use pcie->tunnel_cold_init instead, so on those ports the hook never runs and the enable bit stays 0. Measured on a 16-inch M1 Max (T6001), Intel Arc Pro B60 in a Sonnet Breakaway Box on USB4 tunnel 2 (pcie@f30000000), kernel 7.1.12-2-20261013.18: - Every CPU read of a BAR behind the root port's prefetchable window returned all-ones, with no AER, abort or UR bits on any bridge. This held for the 64-bit window with the identity DT range, for the 32-bit prefetchable window, and with the BARs placed inside the working non-prefetchable CPU window. A function behind the same chain in the non-prefetchable window read correct data in every configuration. - A runtime bisect with setpci gave each bridge in turn its prefetchable window while the others forwarded through widened non-prefetchable windows: the windows of 04:01.0, 03:00.0, 02:00.0 and 01:00.0 each read data; only the root port's own prefetchable window (0001:00:00.0) read all-ones. - PORT_PREFMEM_ENABLE (phys 0xf21000994) read 0 on that boot (0x990 read 1). With the kernel's original bridge windows in place and the BARs reachable only through the prefetchable windows, reads returned all-ones; after one 32-bit write of 1 to the register (writel_relaxed, mb, isb, non-posted mapping) the same reads returned correct data (B60 BAR0 registers and VRAM). The register reads back 0 after the write, so it is a write strobe. Run the existing hook for tunnel_cold_init ports too. This reaches every tunnel port the driver cold-initializes: Intr2AXI controllers (apple,t6000-pciec, apple,t8112-pciec, apple,t6050-pciec) whose PCIe-C DART carries tunables. Today that is the T600x, T602x and T6050 trees; the T8112 trees have no PCIe-C DART tunables yet. The register write was measured only on the T6001. On a 14-inch M2 Max (T6021) the prefetchable window forwarded once the DT range was identity. Tested: the register write above (direct, from a test module). The hook path itself has not been booted: a rebuilt kernel changes the BTF base of the modules. (cherry picked from commit 4466fe2ad955d47290fc79c13963c51c0b253706) Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Signed-off-by: Scott Jones --- drivers/pci/controller/pcie-apple.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index a3671bf39d196d..e7d60f0ceb2f54 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -3959,7 +3959,7 @@ static int apple_pcie_config_write(struct pci_bus *bus, unsigned int devfn, if (pcie->hw->mps_timers && where == PCIEC_RP_DEVCTL) apple_pcie_update_mps_timers(pcie, FIELD_GET(PCI_EXP_DEVCTL_PAYLOAD, val)); - if (!pcie->kernel_init) + if (!(pcie->kernel_init || pcie->tunnel_cold_init)) return ret; /* Root-port prefetchable window. The port block has to be told too. */ if (where < 0x24 || where >= 0x30) From e87e13858b5d84b8950a15fa05484b412e8904be Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 17:37:56 -0800 Subject: [PATCH 0730/1514] drm/asahi: g17: M5: refuse render target layouts that cannot fit the compact window before allocating them On M5 a render pair's target records, TPC object and initial parameter buffer are sized from the client's render pass. The record and TPC limits apply only to the other G17 parts, so on M5 these sizes were bounded only by integer overflow. A pair allocated and zeroed each object in full before mapping it into the client's compact window, so a layout too large for the window was allocated first and then failed at the mapping, and the render was retried while the runtime waited for capacity. The other parts are bounded by the window their targets live in. On M5 that window is the client's compact window, which the firmware addresses with 32-bit offsets: 4 GiB. A pair maps there its target records (one stride of the page-rounded record for each of the 32 command slots), its TPC object, its initial parameter blocks at 0x88000 bytes each, about 3.8 MiB of objects its layout does not size (the context state of each command slot, the parameter buffer's scene scratch, discard and page list, and its metrics entry) and, while the task-stage binding is enabled, the 32 MiB of mesh storage it maps on its first task-stage kick and keeps for the passes that follow. A layout whose pair does not fit in the window can never be mapped, so deriving the layout, which SUBMIT already does for every M5 render, now refuses it with ENOMEM before anything is queued or allocated. The window's objects are described once (buffer::compact::PairObject): each with its alignment and guard, used by its mapping and by the room check before its allocation, and SUBMIT's bound sums the same list, so the bound cannot leave out an object a pair maps or disagree with its placement. Each size in the bound is the one the allocation uses: the context state comes from the board's layout, as the pair allocates it. The mesh storage counts in every pair, whether or not the pass has a task stage, as the pair keeps it. The bound depends on the pass's tile size and on whether it is marked as drawing few primitives, which sets how much of the TPC object is needed. On the M5 Ultra, for a single-sample pass with 32x32 tiles, the size the Borealis Vulkan driver uses for such a pass, this admits a 16384x16384 target of up to 21 layers when the pass draws more than four primitives, and up to 53 layers when it draws four or fewer; 2048 layers of a target up to 1024x1024, or up to 2048x2048 with few primitives. With 16x16 tiles it admits up to 5 layers at 16384x16384 and 2048 layers up to 512x512. KUnit pins these sizes, their first refused neighbours, and the mesh storage at the window's edge. The window is shared by the client's pairs, so a layout that fits on its own can still find too little room. Before allocating a target object, parameter-buffer blocks or the mesh storage, a pair now checks that the window has a hole for the object and room for all the blocks, and fails with ENOSPC, as the mapping would, without allocating them. Other G17 parts are unchanged. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Suggested-by: DjDeveloperr Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/buffer.rs | 46 +-- drivers/gpu/drm/asahi/g17/buffer/compact.rs | 266 ++++++++++++++++++ drivers/gpu/drm/asahi/g17/buffer/geometry.rs | 9 +- drivers/gpu/drm/asahi/g17/buffer/target.rs | 27 +- drivers/gpu/drm/asahi/g17/fw/m5/pool.rs | 2 + drivers/gpu/drm/asahi/g17/queue/render.rs | 12 +- .../drm/asahi/g17/queue/render/generation.rs | 10 +- .../g17/queue/render/m5_render_submission.rs | 168 ++++++++++- .../gpu/drm/asahi/g17/queue/render/memory.rs | 43 ++- .../gpu/drm/asahi/g17/queue/render/parked.rs | 1 + drivers/gpu/drm/asahi/g17/runtime/backend.rs | 3 +- 11 files changed, 513 insertions(+), 74 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g17/buffer/compact.rs diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index fd0aace6a42624..5eb4f66e343d89 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -9,6 +9,7 @@ use super::fw::buffer as fw; use crate::hw::t8140::resources as cfg; pub(crate) mod target; +pub(crate) mod compact; mod geometry; pub(crate) use geometry::BlockGeometry; mod layout; @@ -414,6 +415,16 @@ impl Tvb { } geometry.backing_bytes(blocks) } + /// Backing for `blocks` blocks to be mapped into `vm`. M5 blocks are mapped one by one in + /// the compact window, which is checked for room for all of them first. + fn allocate(dev: &AsahiDrmDevice, vm: &mmu::Vm, geometry: BlockGeometry, blocks: usize) + -> Result { + let bytes = Self::backing_bytes(geometry, blocks)?; + if geometry != BlockGeometry::NEO { + compact::PairObject::ParameterBlock.check_room(vm, geometry.block_bytes, blocks)?; + } + KernelObject::backing(dev, bytes, CpuMap::WriteCombined) + } fn map_block( object: &KernelObject, vm: &mmu::Vm, @@ -423,9 +434,8 @@ impl Tvb { if geometry != BlockGeometry::NEO { let start = relative.checked_mul(geometry.backing_stride).ok_or(EOVERFLOW)?; let source = start..start.checked_add(geometry.block_bytes).ok_or(EOVERFLOW)?; - let guard = geometry.stride - geometry.block_bytes; - let mapping = object.map_range(vm, source, geometry.base..geometry.end, - BlockGeometry::PAGE as u64, mmu::PROT_GPU_SHARED_RW, guard)?; + let mapping = compact::PairObject::ParameterBlock.map(object, vm, source, + mmu::PROT_GPU_SHARED_RW)?; geometry.compact_page(mapping.iova())?; return Ok(mapping); } @@ -458,8 +468,7 @@ impl Tvb { if blocks == 0 || blocks > geometry.max_blocks() { return Err(ERANGE); } - let backing = KernelObject::backing(dev, Self::backing_bytes(geometry, blocks)?, - CpuMap::WriteCombined)?; + let backing = Self::allocate(dev, vm, geometry, blocks)?; let mut mappings = KVec::with_capacity(blocks, GFP_KERNEL)?; let mut addresses = KVec::with_capacity(blocks, GFP_KERNEL)?; for index in 0..blocks { @@ -511,8 +520,7 @@ impl Tvb { let added = target - self.blocks(); self.extensions.reserve(1, GFP_KERNEL)?; self.addresses.reserve(added, GFP_KERNEL)?; - let backing = KernelObject::backing(dev, Self::backing_bytes(self.geometry, added)?, - CpuMap::WriteCombined)?; + let backing = Self::allocate(dev, vm, self.geometry, added)?; let mut mappings = KVec::with_capacity(added, GFP_KERNEL)?; let mut addresses = KVec::with_capacity(added, GFP_KERNEL)?; for relative in 0..added { @@ -568,15 +576,18 @@ impl MetricsIds { /// backing each lease is taken from. pub(crate) fn with_stride(scene_stride: usize) -> Result { if scene_stride < 4 || scene_stride % 4 != 0 { return Err(EINVAL); } - let entry_pitch = scene_stride.checked_mul(fw::SCENES) - .and_then(|bytes| bytes.checked_next_multiple_of(mmu::UAT_PGSZ)) - .ok_or(EOVERFLOW)?; Ok(Self { used: [AtomicU64::new(0), AtomicU64::new(0)], scene_stride, - entry_pitch, + entry_pitch: Self::entry_pitch(scene_stride)?, }) } + /// The pitch of entries of `scene_stride`-byte scenes: each starts its own pages. + pub(crate) fn entry_pitch(scene_stride: usize) -> Result { + scene_stride.checked_mul(fw::SCENES) + .and_then(|bytes| bytes.checked_next_multiple_of(mmu::UAT_PGSZ)) + .ok_or(EOVERFLOW) + } /// Backing required for every entry owned by this allocator. pub(crate) fn storage_bytes(&self) -> Result { self.entry_pitch.checked_mul(self.used.len() * u64::BITS as usize) @@ -607,14 +618,14 @@ impl MetricsLease { // window's start (InitData::bind_m5_metrics), so place the entry where its offset puts // it there. let fixed = super::J813_FORMS.load(Ordering::Relaxed).then(|| { - let at = BlockGeometry::M5_COMPACT.start + offset as u64; - self.backing.map_range(vm, offset..offset + pitch, at..at + pitch as u64, - mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, 0).ok() + let at = compact::WINDOW.start + offset as u64; + compact::PairObject::Metrics.map_at(&self.backing, vm, offset..offset + pitch, at, + mmu::PROT_GPU_SHARED_RW).ok() }).flatten(); let client = match fixed { Some(client) => client, - None => self.backing.map_range(vm, offset..offset + pitch, BlockGeometry::M5_COMPACT, - mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, 0)?, + None => compact::PairObject::Metrics.map(&self.backing, vm, offset..offset + pitch, + mmu::PROT_GPU_SHARED_RW)?, }; self.addresses.client = client.iova(); self.client = Some(client); @@ -822,8 +833,7 @@ impl Manager { mmu::UAT_PGSZ, )? } else { - graph.map_range(vm, source, geometry.base..geometry.end, - cfg::TVB_PAGE, mmu::PROT_GPU_FW_SHARED_RW, mmu::UAT_PGSZ)? + compact::PairObject::PageList.map(&graph, vm, source, mmu::PROT_GPU_FW_SHARED_RW)? }; let address = graph.gpu_va(); let graph_args = fw::GraphArgs { diff --git a/drivers/gpu/drm/asahi/g17/buffer/compact.rs b/drivers/gpu/drm/asahi/g17/buffer/compact.rs new file mode 100644 index 00000000000000..af491dc8c7167e --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/buffer/compact.rs @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The objects a render pair maps in its client's M5 compact window. +//! +//! The firmware addresses the window with 32-bit offsets, so it is 4 GiB, and every render pair +//! of the client maps its objects there. [`PairObject`] names each such object and fixes how it +//! is placed: every mapping of one goes through [`PairObject::map`] (or +//! [`PairObject::placement`]), and every room check before allocating one through +//! [`PairObject::check_room`]. SUBMIT's bound ([`PairSizes::window_bytes`]) counts the same +//! objects with the same placement, so an object cannot be mapped there without a size in the +//! bound, and the bound cannot disagree with a mapping on its alignment or guard. + +use super::BlockGeometry; +use crate::g17::object::{KernelObject, Placement}; +use crate::{ + hw::t8140::{queues, resources as cfg}, + mmu, +}; +use core::ops::Range; +use kernel::prelude::*; + +/// The client's M5 compact window. +pub(crate) const WINDOW: Range = BlockGeometry::M5_COMPACT; +/// Its size: 4 GiB. +pub(crate) const WINDOW_BYTES: u64 = WINDOW.end - WINDOW.start; + +const DEPTH: usize = queues::RENDER_DEPTH as usize; + +/// The task-stage mesh storage chunk: chunk bases are 64 KiB aligned, and the storage register +/// counts 64 KiB chunks. +pub(crate) const MESH_STORAGE_CHUNK: usize = 0x10000; + +/// The task-stage mesh storage a render pair maps on its first task-stage kick and keeps, as +/// (chunks, bytes); `None` when the module parameter disables the binding. +pub(crate) fn mesh_storage() -> Result> { + let chunks = crate::module_parameters::m5_mesh_storage_chunks.value(); + if chunks == 0 { + return Ok(None); + } + if chunks > 0xffff { + return Err(EINVAL); + } + let bytes = (chunks as usize).checked_mul(MESH_STORAGE_CHUNK).ok_or(EOVERFLOW)?; + Ok(Some((chunks, bytes))) +} + +/// Bytes of a pair's parameter-buffer scene scratch for `geometry`. +pub(crate) fn scratch_bytes(geometry: BlockGeometry) -> Result { + use crate::g17::fw::m5::pool; + pool::parameter_scratch_stride(geometry.capacity, 0) + .map_err(|_| EINVAL)? + .checked_mul(pool::SCENE_TABLE_ENTRIES) + .ok_or(EOVERFLOW) +} + +/// Bytes of the page list of a pair's block manager for `geometry`. +pub(crate) fn page_list_bytes(geometry: BlockGeometry) -> Result { + Ok(super::layout::Layout::m5(geometry)?.page_bytes) +} + +/// Bytes of a pair's metrics entry for `geometry`. +fn metrics_bytes(geometry: BlockGeometry) -> Result { + super::MetricsIds::entry_pitch(super::layout::Layout::m5(geometry)?.metric_stride) +} + +/// An object a render pair maps in its client's M5 compact window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PairObject { + /// The target records: one record stride for each command slot. + Records = 0, + /// The TPC object. + Tpc, + /// One parameter block, initial or grown, mapped at the M5 block stride. + ParameterBlock, + /// The context state of one command slot. + SlotState, + /// The parameter buffer's scene scratch. + Scratch, + /// The parameter buffer's discard. + Discard, + /// The block manager's page list. + PageList, + /// The pair's metrics entry. + Metrics, + /// The task-stage mesh storage, mapped on the pair's first task-stage kick and kept for the + /// pair's lifetime. + MeshStorage, +} + +impl PairObject { + /// Every object, in declaration order. + pub(crate) const ALL: [Self; 9] = [ + Self::Records, + Self::Tpc, + Self::ParameterBlock, + Self::SlotState, + Self::Scratch, + Self::Discard, + Self::PageList, + Self::Metrics, + Self::MeshStorage, + ]; + + /// The alignment it is placed at. + pub(crate) const fn align(self) -> u64 { + match self { + Self::MeshStorage => MESH_STORAGE_CHUNK as u64, + Self::Metrics => mmu::UAT_PGSZ as u64, + Self::ParameterBlock => BlockGeometry::PAGE as u64, + Self::Records + | Self::Tpc + | Self::SlotState + | Self::Scratch + | Self::Discard + | Self::PageList => cfg::TVB_PAGE, + } + } + + /// The unmapped guard that follows it. + pub(crate) const fn guard(self) -> usize { + match self { + Self::Metrics => 0, + Self::ParameterBlock => BlockGeometry::M5_BLOCK_STRIDE - BlockGeometry::M5_BLOCK_BYTES, + Self::Records + | Self::Tpc + | Self::SlotState + | Self::Scratch + | Self::Discard + | Self::PageList + | Self::MeshStorage => mmu::UAT_PGSZ, + } + } + + /// The bytes one mapping of an object of `bytes` takes in one hole: its pages and its guard. + fn mapped_bytes(self, bytes: usize) -> Result { + bytes + .checked_next_multiple_of(mmu::UAT_PGSZ) + .and_then(|n| n.checked_add(self.guard())) + .ok_or(EOVERFLOW) + } + + /// The window bytes an object of `bytes` can take: its pages and its guard, rounded up to + /// its alignment and at least to the 32 KiB most of these objects are placed at, plus, for + /// an object aligned beyond 32 KiB, the hole that alignment can leave before it. + pub(crate) fn window_bytes(self, bytes: usize) -> Result { + let base = cfg::TVB_PAGE as usize; + let align = (self.align() as usize).max(base); + self.mapped_bytes(bytes)? + .checked_next_multiple_of(align) + .and_then(|n| n.checked_add(align - base)) + .ok_or(EOVERFLOW) + } + + /// Maps `source` of `object` into `vm`'s window as this object. + pub(crate) fn map( + self, + object: &KernelObject, + vm: &mmu::Vm, + source: Range, + prot: mmu::Prot, + ) -> Result { + let mapping = object.map_range(vm, source, WINDOW, self.align(), prot, self.guard())?; + if mapping.iova() % self.align() != 0 { + return Err(EINVAL); + } + Ok(mapping) + } + + /// [`Self::map`] at `at`, where the firmware expects this object. + pub(crate) fn map_at( + self, + object: &KernelObject, + vm: &mmu::Vm, + source: Range, + at: u64, + prot: mmu::Prot, + ) -> Result { + let end = at.checked_add(self.mapped_bytes(source.len())? as u64).ok_or(EOVERFLOW)?; + if at < WINDOW.start || end > WINDOW.end { + return Err(EINVAL); + } + object.map_range(vm, source, at..end, self.align(), prot, self.guard()) + } + + /// The [`Placement`] of a [`KernelObject::new`] of this object in the window, whose guard is + /// one page. + pub(crate) fn placement(self) -> Result { + if self.guard() != mmu::UAT_PGSZ { + return Err(EINVAL); + } + Ok(Placement::In(WINDOW, self.align())) + } + + /// Refuses with ENOSPC, as the mapping would and before any backing is allocated, `count` + /// of this object of `bytes` each that `vm`'s window has no room for: a hole for one, and + /// room for all of them. The window is shared, so room seen here is no placement promise: + /// the mapping can still fail, but only after allocating backing that could fit. + pub(crate) fn check_room(self, vm: &mmu::Vm, bytes: usize, count: usize) -> Result { + let (used, largest) = vm.capacity(WINDOW)?; + let one = self.mapped_bytes(bytes)?; + let all = one.checked_mul(count).ok_or(EOVERFLOW)?; + if one as u64 > largest || all as u64 > WINDOW_BYTES.saturating_sub(used) { + return Err(ENOSPC); + } + Ok(()) + } +} + +// `PairObject::ALL` holds every object once, in order. +const _: () = { + let mut index = 0; + while index < PairObject::ALL.len() { + assert!(PairObject::ALL[index] as usize == index); + index += 1; + } + assert!(PairObject::ALL.len() == PairObject::MeshStorage as usize + 1); +}; + +/// The sizes of the objects a render pair built for one layout maps in the window. +pub(crate) struct PairSizes { + /// The target records object: one record stride for each command slot. + pub(crate) records: usize, + /// The TPC object. + pub(crate) tpc: usize, + /// The initial parameter blocks, of `geometry`'s block size. + pub(crate) blocks: usize, + /// The parameter-buffer geometry, which sizes the blocks, scratch, page list and metrics. + pub(crate) geometry: BlockGeometry, + /// One command slot's context state. + pub(crate) state: usize, + /// The task-stage mesh storage the pair may map ([`mesh_storage`]). + pub(crate) mesh_storage: Option, +} + +impl PairSizes { + /// How many of `object` the pair maps, and the bytes of each. + fn of(&self, object: PairObject) -> Result<(usize, usize)> { + Ok(match object { + PairObject::Records => (1, self.records), + PairObject::Tpc => (1, self.tpc), + PairObject::ParameterBlock => (self.blocks, self.geometry.block_bytes), + PairObject::SlotState => (DEPTH, self.state), + PairObject::Scratch => (1, scratch_bytes(self.geometry)?), + PairObject::Discard => (1, crate::g17::fw::m5::pool::DISCARD_BYTES), + PairObject::PageList => (1, page_list_bytes(self.geometry)?), + PairObject::Metrics => (1, metrics_bytes(self.geometry)?), + PairObject::MeshStorage => match self.mesh_storage { + Some(bytes) => (1, bytes), + None => (0, 0), + }, + }) + } + + /// The window bytes of `object` in the pair. + pub(crate) fn object_bytes(&self, object: PairObject) -> Result { + let (count, bytes) = self.of(object)?; + object.window_bytes(bytes)?.checked_mul(count).ok_or(EOVERFLOW) + } + + /// The window bytes of every object of the pair. + pub(crate) fn window_bytes(&self) -> Result { + PairObject::ALL.into_iter().try_fold(0usize, |sum, object| { + sum.checked_add(self.object_bytes(object)?).ok_or(EOVERFLOW) + }) + } +} diff --git a/drivers/gpu/drm/asahi/g17/buffer/geometry.rs b/drivers/gpu/drm/asahi/g17/buffer/geometry.rs index c871f470c1a153..71c5e18dc48f17 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/geometry.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/geometry.rs @@ -20,6 +20,9 @@ impl BlockGeometry { pub(crate) const PAGE: usize = 0x8000; /// M5 parameter resources use 32-bit offsets from this compact base. pub(crate) const M5_COMPACT: core::ops::Range = 0x10_0000_0000..0x11_0000_0000; + /// An M5 parameter block, and the stride it is mapped at, its guard included. + pub(crate) const M5_BLOCK_BYTES: usize = 0x80000; + pub(crate) const M5_BLOCK_STRIDE: usize = 0x88000; pub(crate) const NEO: Self = Self { base: cfg::USER_BASE, end: cfg::USER_END, @@ -40,9 +43,9 @@ impl BlockGeometry { Ok(Self { base: Self::M5_COMPACT.start, end: Self::M5_COMPACT.end, - block_bytes: 0x80000, - backing_stride: 0x80000, - stride: 0x88000, + block_bytes: Self::M5_BLOCK_BYTES, + backing_stride: Self::M5_BLOCK_BYTES, + stride: Self::M5_BLOCK_STRIDE, capacity, }) } diff --git a/drivers/gpu/drm/asahi/g17/buffer/target.rs b/drivers/gpu/drm/asahi/g17/buffer/target.rs index c17e6c3643f2e6..b6de4817718d2c 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/target.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/target.rs @@ -4,6 +4,7 @@ //! Larger targets replace only the objects that need more capacity. Every old //! backing keeps the exact commands that still reference it until retirement. +use super::compact::PairObject; use super::compact_alias; use crate::g17::{ fw::render::{RegisterPrograms, RenderPass}, @@ -237,14 +238,17 @@ struct Object { backing: KernelObject, } impl Object { - fn new(dev: &AsahiDrmDevice, vm: &mmu::Vm, size: usize, m5: bool) -> Result { + /// An object of `size` bytes, on M5 mapped in the client's compact window as `m5`. + fn new(dev: &AsahiDrmDevice, vm: &mmu::Vm, size: usize, m5: Option) + -> Result { + if let Some(object) = m5 { + object.check_room(vm, size, 1)?; + } let backing = KernelObject::backing(dev, size, CpuMap::WriteCombined)?; let prot = mmu::PROT_GPU_FW_SHARED_RW; - let mapping = if m5 { - backing.map_range(vm, 0..size, super::BlockGeometry::M5_COMPACT, - cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)? - } else { - compact_alias(&backing, vm, 0..size, cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)? + let mapping = match m5 { + Some(object) => object.map(&backing, vm, 0..size, prot)?, + None => compact_alias(&backing, vm, 0..size, cfg::TVB_PAGE, prot, mmu::UAT_PGSZ)?, }; Ok(Self { address: mapping.iova(), @@ -281,8 +285,8 @@ impl Target { let stride = layout.record_stride()?; layout.check_capacity(stride)?; let m5 = layout.m5.is_some(); - let records = Object::new(dev, vm, stride * DEPTH, m5)?; - let tpc = Object::new(dev, vm, tpc, m5)?; + let records = Object::new(dev, vm, stride * DEPTH, m5.then_some(PairObject::Records))?; + let tpc = Object::new(dev, vm, tpc, m5.then_some(PairObject::Tpc))?; KBox::new( Self { records, @@ -387,7 +391,8 @@ impl Target { layout.check_capacity(stride)?; let mut grew = false; if tpc > self.tpc.backing.size() { - Self::replace(&mut self.retired, &mut self.tpc, dev, vm, tpc, owners, self.m5)?; + Self::replace(&mut self.retired, &mut self.tpc, dev, vm, tpc, owners, + self.m5.then_some(PairObject::Tpc))?; grew = true; } if stride > self.stride { @@ -398,7 +403,7 @@ impl Target { vm, stride * DEPTH, owners, - self.m5, + self.m5.then_some(PairObject::Records), )?; self.stride = stride; self.slots = [None; DEPTH]; @@ -413,7 +418,7 @@ impl Target { vm: &mmu::Vm, size: usize, owners: &[Option; DEPTH], - m5: bool, + m5: Option, ) -> Result { let retain = owners.iter().any(Option::is_some); if retain { diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs b/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs index 7a457322fb64e7..6c1283f988b1c3 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/pool.rs @@ -54,6 +54,8 @@ pub(crate) const SAVED_FIELDS: [usize; 8] = [0x28, 0x20, 0x24, 0x2c, 0x3c, 0x48, const GPU_PAGE: usize = 0x4000; const PRIVATE_TOP: u64 = 1 << 42; pub(crate) const SCENE_TABLE_ENTRIES: usize = 0x50; +/// Bytes of a render pair's parameter-buffer discard object. +pub(crate) const DISCARD_BYTES: usize = 0x8000; pub(crate) const SCENE_STRIDE: usize = 0x80; pub(crate) const SCENE_TRAILER_SIZE: usize = 0x40; diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index de4760aec5f0a3..b06588ccad557b 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -347,7 +347,8 @@ impl Pair { if word == u32::MAX { return Err(EINVAL); } - let layout = m5_render_submission::layout(&first.command, clusters, variant.programs)?; + let layout = + m5_render_submission::layout(&first.command, clusters, variant.programs, board)?; let storage = KBox::::new_uninit(GFP_KERNEL)?; let (tiling, ta_alias) = kick::Queue::render(alloc, ids[0], context.vm(), rings)?; let (fragment, fragment_alias) = kick::Queue::render(alloc, ids[1], context.vm(), rings)?; @@ -539,7 +540,8 @@ impl Pair { let node = work.node_va()?; let word = work.word(); let layout = - m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs)?; + m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs, + self.board)?; let deflake_layout = self.deflake; let owners = self.memory.owners(); self.memory @@ -1831,7 +1833,8 @@ impl Pair { /// keeps its current capacity and lets firmware request growth as needed. pub(crate) fn host_growth_target(&mut self, packet: &Packet) -> Result> { let mut required = - m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs)? + m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs, + self.board)? .tvb_blocks; // A mesh workgroup whose output is in flight when the tiler heap runs out loses part of // it, whether the firmware then grows the heap or partial-renders, and the tile-count @@ -3281,7 +3284,8 @@ impl Pair { let buffer_id = buffer_id.ok_or(EINVAL)?; let pm_generation = pm_generation.ok_or(EINVAL)?; let layout = - m5_render_submission::layout(&first.command, self.clusters, self.variant.programs)?; + m5_render_submission::layout(&first.command, self.clusters, self.variant.programs, + self.board)?; // A context of another VM gets the rings cleared before its VM is given its view, // so it cannot read the entries earlier owners' commands left, as for a parked pair. // The pair is bindable, hence idle: the firmware consumed every entry. diff --git a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index 4ebe4220921c0b..f281c38a7117ae 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -4,7 +4,7 @@ //! their backing owners; a generation is reusable only after paired retirement. use crate::g17::{ - buffer::{self, BlockGeometry}, + buffer::{self, compact::PairObject}, fw::{ m5::{initdata::Board, render_registers::ContextStore}, render::{storage, RenderPass}, @@ -101,10 +101,10 @@ pub(in crate::g17) struct Generation { impl Generation { pub(in crate::g17) fn allocate_state(alloc: &Allocator<'_>, vm: &mmu::Vm, board: Option<&'static Board>) -> Result { - let (range, layout) = if alloc.uat.is_m5() { - (BlockGeometry::M5_COMPACT, Layout::m5(board.ok_or(EINVAL)?)) - } else { (vm.client_private_range(), Layout::NEO) }; - KernelObject::new(alloc.dev, vm, Placement::In(range, cfg::TVB_PAGE), layout.bytes, + let (placement, layout) = if alloc.uat.is_m5() { + (PairObject::SlotState.placement()?, Layout::m5(board.ok_or(EINVAL)?)) + } else { (Placement::In(vm.client_private_range(), cfg::TVB_PAGE), Layout::NEO) }; + KernelObject::new(alloc.dev, vm, placement, layout.bytes, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) } diff --git a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs index 333846d3f83c6f..e337cfefc7849e 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs @@ -3,7 +3,7 @@ use kernel::prelude::*; use crate::g17::fw::m5::{render as cmd, render_registers as regs}; -use crate::g17::{buffer::target, command::Validated, fw::render::{RenderArgs, RenderPass, RegisterPrograms}}; +use crate::g17::{buffer::{compact, target}, command::Validated, fw::render::{RenderArgs, RenderPass, RegisterPrograms}}; /// Compressed single-layer MSAA ZLS admission: D32 depth with optional plain /// stencil, and the compressed Z/S form. @@ -120,25 +120,74 @@ pub(crate) fn parameter_geometry(blocks: usize) -> Result Result { +/// The target layout of a render: G17P's for a command without an M5 plan. `board` is the M5 +/// board, which an M5 plan needs. +pub(crate) fn layout(command: &Validated, clusters: u32, programs: RegisterPrograms, + board: Option<&'static crate::g17::fw::m5::initdata::Board>) -> Result { let Validated::Render { pass, plan, .. } = command else { return Err(EINVAL); }; let layout = target::Layout::new(pass, clusters, programs)?; if plan.is_none() { return Ok(layout); } validate(pass)?; + let geometry = parameter_geometry(layout.tvb_blocks)?; + let mesh_storage = compact::mesh_storage()?.map(|(_, bytes)| bytes); + // The context state a pair allocates for each command slot (`Generation::allocate_state`). + let state = super::generation::Layout::m5(board.ok_or(EINVAL)?).bytes; + Ok(m5_layout(layout, pass, clusters, geometry, mesh_storage, state)?.0) +} + +/// The M5 layout of `pass` from its G17P layout, and the compact-window bytes a pair built for +/// it reserves ([`pair_window_bytes`]) with `mesh_storage` bytes of task-stage mesh storage. +fn m5_layout(layout: target::Layout, pass: &RenderPass, clusters: u32, + geometry: crate::g17::buffer::BlockGeometry, mesh_storage: Option, state: usize) + -> Result<(target::Layout, usize)> { // One target group per cluster unless the pass asks for few primitives. // Both target storage and the segment controls use the physical cluster count. - let geometry = parameter_geometry(layout.tvb_blocks)?; // The auxiliary tables cover the complete parameter inventory, including // future growth, rather than just the initially resident physical blocks. let bytes = geometry.capacity.checked_mul(geometry.block_bytes).ok_or(EOVERFLOW)?; let groups = if pass.few_primitives { 1 } else { clusters }; - layout.with_m5_slices(pass, clusters, groups, 64, bytes) + let layout = layout.with_m5_slices(pass, clusters, groups, 64, bytes)?; + // A pair maps its objects in the client's compact window, whose 32-bit offsets make it + // 4 GiB. A layout whose pair does not fit there on its own can never be mapped: refuse it + // as memory that cannot be had, before any of it is allocated. SUBMIT derives the layout, + // so the refusal is the ioctl's. + let reserved = pair_window_bytes(&layout, geometry, state, mesh_storage)?; + if reserved as u64 > compact::WINDOW_BYTES { + return Err(ENOMEM); + } + Ok((layout, reserved)) +} + +/// The objects a render pair built for `layout` maps in the client's M5 compact window +/// ([`compact::PairObject`]): its target records (a page-rounded record for each command slot), +/// its TPC object and its initial parameter blocks, which the layout sizes, the context state +/// of each command slot (`state` bytes each), the parameter buffer's scratch, discard and page +/// list, its metrics entry, and, while the binding is enabled, the task-stage mesh storage. A +/// pair maps that storage on its first task-stage kick and keeps it for the passes that follow, +/// so every pair counts it, whether or not this pass has a task stage. +fn pair_sizes(layout: &target::Layout, geometry: crate::g17::buffer::BlockGeometry, + state: usize, mesh_storage: Option) -> Result { + let depth = crate::hw::t8140::queues::RENDER_DEPTH as usize; + Ok(compact::PairSizes { + records: layout.record_stride()?.checked_mul(depth).ok_or(EOVERFLOW)?, + tpc: layout.tpc_capacity()?, + blocks: layout.tvb_blocks, + geometry, + state, + mesh_storage, + }) +} + +/// Bytes of the client's M5 compact window that a render pair built for `layout` reserves +/// ([`pair_sizes`]). +fn pair_window_bytes(layout: &target::Layout, geometry: crate::g17::buffer::BlockGeometry, + state: usize, mesh_storage: Option) -> Result { + pair_sizes(layout, geometry, state, mesh_storage)?.window_bytes() } pub(crate) fn controls( @@ -216,3 +265,108 @@ pub(crate) fn inputs(args: &RenderArgs<'_>, usage: [u64; 2]) -> Result = Some(0x200 * compact::MESH_STORAGE_CHUNK); + /// The J775D's context state per command slot. + const STATE: usize = + super::super::generation::Layout::m5(&crate::g17::fw::m5::initdata::J775D).bytes; + + /// A single-sample pass as Borealis sends it: `utile` tiles, and few-primitives for a pass + /// of at most four primitives. + fn pass(size: u32, layers: u16, utile: u8, few: bool) -> RenderPass { + // SAFETY: RenderPass and its nested surfaces/programs contain only + // integers and bools, for which the all-zero representation is valid. + let mut pass: RenderPass = unsafe { core::mem::zeroed() }; + pass.width = size; + pass.height = size; + pass.layers = layers; + pass.utile_width = utile; + pass.utile_height = utile; + pass.few_primitives = few; + pass + } + + /// The window bytes of a pair for that pass with `mesh` bytes of mesh storage. + fn reserved_with(size: u32, layers: u16, utile: u8, few: bool, mesh: Option) + -> Result { + let pass = pass(size, layers, utile, few); + let layout = target::Layout::new(&pass, 8, RegisterPrograms::G17P)?; + let geometry = BlockGeometry::m5(RAM, + (layout.tvb_blocks * BlockGeometry::M5_BLOCK_BYTES) as u64)?; + m5_layout(layout, &pass, 8, geometry, mesh, STATE).map(|(_, bytes)| bytes) + } + + /// The same with the default mesh storage. + fn reserved(size: u32, layers: u16, utile: u8, few: bool) -> Result { + reserved_with(size, layers, utile, few, MESH) + } + + #[test] + fn borealis_32x32_passes_of_more_than_four_primitives() { + assert!(reserved(16384, 21, 32, false).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 22, 32, false), Err(ENOMEM)); + assert!(reserved(512, 2048, 32, false).unwrap() <= WINDOW); + assert!(reserved(1024, 2048, 32, false).unwrap() <= WINDOW); + assert_eq!(reserved(1152, 2048, 32, false), Err(ENOMEM)); + } + + #[test] + fn borealis_32x32_passes_of_few_primitives() { + assert!(reserved(16384, 53, 32, true).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 54, 32, true), Err(ENOMEM)); + assert!(reserved(2048, 2047, 32, true).unwrap() <= WINDOW); + assert!(reserved(2048, 2048, 32, true).unwrap() <= WINDOW); + assert_eq!(reserved(2112, 2048, 32, true), Err(ENOMEM)); + assert!(reserved(1152, 2048, 32, true).unwrap() <= WINDOW); + } + + #[test] + fn passes_with_16x16_tiles() { + assert!(reserved(16384, 5, 16, false).unwrap() <= WINDOW); + assert_eq!(reserved(16384, 6, 16, false), Err(ENOMEM)); + assert!(reserved(512, 2048, 16, false).unwrap() <= WINDOW); + assert_eq!(reserved(1024, 2048, 16, false), Err(ENOMEM)); + } + + #[test] + fn mesh_storage_counts_at_the_4_gib_edge() { + // A pass that fits only without the mesh storage a pair keeps once it has run a + // task-stage pass is refused while the binding is enabled. + assert!(reserved_with(16384, 22, 32, false, None).unwrap() <= WINDOW); + assert_eq!(reserved_with(16384, 22, 32, false, MESH), Err(ENOMEM)); + let with = reserved_with(16384, 21, 32, false, MESH).unwrap(); + let without = reserved_with(16384, 21, 32, false, None).unwrap(); + assert_eq!(with - without, PairObject::MeshStorage.window_bytes(MESH.unwrap()).unwrap()); + assert!(with - without >= 32 * MIB); + } + + #[test] + fn a_pair_counts_the_objects_its_layout_does_not_size() { + // A trace of a pair on the J775D found 3824 KiB of these objects, guards included and + // alignment holes not. + let geometry = BlockGeometry::m5(RAM, 32 * BlockGeometry::M5_BLOCK_BYTES as u64).unwrap(); + let sizes = compact::PairSizes { + records: 0, tpc: 0, blocks: 0, geometry, + state: STATE, mesh_storage: None, + }; + let sized = [PairObject::Records, PairObject::Tpc, PairObject::ParameterBlock] + .into_iter().map(|object| sizes.object_bytes(object).unwrap()).sum::(); + let fixed = sizes.window_bytes().unwrap() - sized; + assert!(fixed >= 3824 * 1024); + assert!(fixed <= 5 * MIB); + // Each block takes its stride, guard included. + assert_eq!(PairObject::ParameterBlock.window_bytes(geometry.block_bytes).unwrap(), + geometry.stride); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index 4cc04e2ac23e90..b6f2b07f961de2 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -5,7 +5,7 @@ use super::retirement::Cursors; use crate::g17::{ - buffer::{self, target}, + buffer::{self, compact::PairObject, target}, context::Context, fw::{ self, queue, @@ -319,23 +319,19 @@ struct Compact { address: u64, _backing: KernelObject, } -/// The mesh storage chunk: chunk bases are 64 KiB aligned and the storage -/// register counts 64 KiB chunks. -const MESH_STORAGE_CHUNK: usize = 0x10000; impl Compact { - /// M5 shared-RW object in the compact window with an explicit VA alignment. - fn new_aligned(alloc: &Allocator<'_>, vm: &mmu::Vm, size: usize, align: u64) -> Result { - let size = size.checked_add(mmu::UAT_PGSZ - 1).ok_or(EOVERFLOW)? & !(mmu::UAT_PGSZ - 1); + /// M5: a shared-RW object of `size` bytes mapped in the client's compact window as `object`. + fn m5(alloc: &Allocator<'_>, vm: &mmu::Vm, object: PairObject, size: usize) -> Result { + let size = size.checked_next_multiple_of(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; - let mapping = backing.map_range(vm, 0..size, buffer::BlockGeometry::M5_COMPACT, - align, mmu::PROT_GPU_SHARED_RW, mmu::UAT_PGSZ)?; - if mapping.iova() % align != 0 { return Err(EINVAL); } + let mapping = object.map(&backing, vm, 0..size, mmu::PROT_GPU_SHARED_RW)?; Ok(Self { address: mapping.iova(), mapping: Some(mapping), _backing: backing }) } + /// Off M5: a shared-RW object of `size` bytes in a compact alias range. fn new(alloc: &Allocator<'_>, vm: &mmu::Vm, size: usize) -> Result { if alloc.uat.is_m5() { - return Self::new_aligned(alloc, vm, size, cfg::TVB_PAGE); + return Err(EINVAL); } let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; let mapping = buffer::compact_alias( @@ -560,12 +556,10 @@ impl Memory { let state = Generation::allocate_state(alloc, vm, board)?; let (tvb, mappings, scratch, discard) = if m5 { let geometry = super::m5_render_submission::parameter_geometry(layout.tvb_blocks)?; - let bytes = fw::m5::pool::parameter_scratch_stride(geometry.capacity, 0) - .map_err(|_| EINVAL)?.checked_mul(fw::m5::pool::SCENE_TABLE_ENTRIES) - .ok_or(EOVERFLOW)?; + let bytes = buffer::compact::scratch_bytes(geometry)?; let (tvb, mappings) = buffer::Tvb::with_geometry(alloc.dev, vm, layout.tvb_blocks, geometry)?; - let scratch = Compact::new(alloc, vm, bytes)?; - let discard = Compact::new(alloc, vm, 0x8000)?; + let scratch = Compact::m5(alloc, vm, PairObject::Scratch, bytes)?; + let discard = Compact::m5(alloc, vm, PairObject::Discard, fw::m5::pool::DISCARD_BYTES)?; (tvb, mappings, scratch, discard) } else { let scratch = Compact::new(alloc, vm, cfg::SCENE_SIZE as usize)?; @@ -667,18 +661,17 @@ impl Memory { )) } /// The mesh storage register value of a task-stage kick. The buffer is - /// allocated on the queue's first such kick and kept for the queue's lifetime, + /// allocated on the pair's first such kick and kept for the pair's lifetime, /// so other contexts pay nothing. A failed allocation leaves no partial state. - /// A zero chunk parameter disables the binding. + /// A zero chunk parameter disables the binding. SUBMIT's compact-window bound + /// counts this buffer in every pair while the binding is enabled, since a pair + /// keeps it for the passes that follow. pub(super) fn mesh_storage_register(&mut self, alloc: &Allocator<'_>) -> Result { if self.mesh_storage.is_none() { - let chunks = crate::module_parameters::m5_mesh_storage_chunks.value(); - if chunks == 0 { return Ok(0); } - if chunks > 0xffff { return Err(EINVAL); } - let bytes = (chunks as usize).checked_mul(MESH_STORAGE_CHUNK).ok_or(EOVERFLOW)?; - let storage = Compact::new_aligned(alloc, self.context.vm(), bytes, - MESH_STORAGE_CHUNK as u64)?; - self.mesh_storage = Some(storage); + let Some((chunks, bytes)) = buffer::compact::mesh_storage()? else { return Ok(0); }; + let vm = self.context.vm(); + PairObject::MeshStorage.check_room(vm, bytes, 1)?; + self.mesh_storage = Some(Compact::m5(alloc, vm, PairObject::MeshStorage, bytes)?); self.mesh_storage_chunks = chunks; } let storage = self.mesh_storage.as_ref().ok_or(ENOMEM)?; diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index 35e39e2130b855..60935d5795acaf 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -220,6 +220,7 @@ impl ParkedPair { &first.command, self.clusters, self.variant.programs, + self.board, )?; let aliases = [ kicks[0].prepare_client_alias(context.vm())?, diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f12626e7039b0d..c5188121aa1278 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -209,7 +209,8 @@ impl job::Backend for Backend { // The M5 target layout refuses the passes the M5 path cannot run. Derive it // here, so that SUBMIT returns the refusal before anything is queued. crate::g17::queue::render::m5_render_submission::layout( - command, self.shared.clusters, self.shared.variant.programs)?; + command, self.shared.clusters, self.shared.variant.programs, + self.shared.m5_board)?; } Validated::Compute { resources, plan, m5_scratch, cdm_auxiliary_allocation, .. } => { if let Some(programs) = resources { From f587245669153c17c33f17d80d685cae9b2ef3a1 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 17:37:57 -0800 Subject: [PATCH 0731/1514] drm/asahi: g17: M5: account render target memory to the client that sizes it On M5 a render pair's target records, TPC object and parameter buffer are sized from its client's passes and geometry: up to the 4 GiB of the client's compact window for each pair, and a client can hold a pair on each of its queues. They were allocated as kernel memory, which counts toward the device total but is not refused and is attributed to no client, so the client's memory limit and fdinfo did not include it. Charge that backing as the M5 pool backing is charged: admitted against the client's and the device's memory limits before it is allocated, as a user buffer of the same size would be, and counted as the client's held memory instead of kernel memory until it is freed. This covers the target records and TPC object when a pair is built for a client and when a larger target replaces them, and the parameter buffer's initial blocks and every growth. A refusal fails the allocation with ENOMEM: building or growing the pair for a render fails that render, and a growth the firmware asks for is declined, as when the buffer is at its largest. The client's fdinfo now includes this memory. Other G17 parts are unchanged. Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/buffer.rs | 10 +++++---- drivers/gpu/drm/asahi/g17/buffer/target.rs | 7 +++++- drivers/gpu/drm/asahi/g17/object.rs | 26 ++++++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 5eb4f66e343d89..0d9bdd33ba1ed7 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -416,14 +416,16 @@ impl Tvb { geometry.backing_bytes(blocks) } /// Backing for `blocks` blocks to be mapped into `vm`. M5 blocks are mapped one by one in - /// the compact window, which is checked for room for all of them first. + /// the compact window, which is checked for room for all of them first, and the client's + /// passes and geometry size them, so they are charged to the client. fn allocate(dev: &AsahiDrmDevice, vm: &mmu::Vm, geometry: BlockGeometry, blocks: usize) -> Result { let bytes = Self::backing_bytes(geometry, blocks)?; - if geometry != BlockGeometry::NEO { - compact::PairObject::ParameterBlock.check_room(vm, geometry.block_bytes, blocks)?; + if geometry == BlockGeometry::NEO { + return KernelObject::backing(dev, bytes, CpuMap::WriteCombined); } - KernelObject::backing(dev, bytes, CpuMap::WriteCombined) + compact::PairObject::ParameterBlock.check_room(vm, geometry.block_bytes, blocks)?; + KernelObject::client_backing(dev, bytes, vm.memory_client()) } fn map_block( object: &KernelObject, diff --git a/drivers/gpu/drm/asahi/g17/buffer/target.rs b/drivers/gpu/drm/asahi/g17/buffer/target.rs index b6de4817718d2c..c037c9f7914d76 100644 --- a/drivers/gpu/drm/asahi/g17/buffer/target.rs +++ b/drivers/gpu/drm/asahi/g17/buffer/target.rs @@ -244,7 +244,12 @@ impl Object { if let Some(object) = m5 { object.check_room(vm, size, 1)?; } - let backing = KernelObject::backing(dev, size, CpuMap::WriteCombined)?; + // An M5 target is sized by the client's pass: charge it to the client. + let backing = if m5.is_some() { + KernelObject::client_backing(dev, size, vm.memory_client())? + } else { + KernelObject::backing(dev, size, CpuMap::WriteCombined)? + }; let prot = mmu::PROT_GPU_FW_SHARED_RW; let mapping = match m5 { Some(object) => object.map(&backing, vm, 0..size, prot)?, diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index de422808e8e668..6899b2743f1cfa 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -58,6 +58,8 @@ pub(crate) struct KernelObject { obj: gem::ObjectRef, ptr: NonNull, size: usize, + /// The client charge of backing from [`Self::client_backing`], released with the object. + charge: Option, } // SAFETY: The object only refers to kernel memory; concurrent access goes through `&self` @@ -108,6 +110,29 @@ impl KernelObject { }, size) } + /// Write-combined [`Self::backing`] that a client's commands size, charged to that client + /// (`client`) as a user buffer of the same size would be: admitted against its and the + /// device's memory limits before it is allocated, failing with ENOMEM over either, and then + /// counted as its held memory instead of kernel memory, until the object is dropped. + /// Without a client (a kernel VM's object) it is kernel memory, as [`Self::backing`]. + pub(crate) fn client_backing( + dev: &AsahiDrmDevice, + size: usize, + client: Option<&kernel::sync::Arc>, + ) -> Result { + let Some(client) = client else { + return Self::backing(dev, size, CpuMap::WriteCombined); + }; + let bytes = gem::checked_object_size(size)? as u64; + let commit = crate::memacct::LEDGER.admit(client, bytes)?; + let mut object = + Self::with_object(gem::new_kernel_object_wc_user_charged(dev, size)?, size)?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + object.charge = Some(charge); + Ok(object) + } + fn with_object(mut obj: gem::ObjectRef, size: usize) -> Result { let vmap = obj.vmap()?; let ptr = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; @@ -121,6 +146,7 @@ impl KernelObject { obj, ptr, size, + charge: None, }) } From 4fd2974238b17937ba757b1983513c0886979b29 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Fri, 20 Nov 2026 01:45:10 -0800 Subject: [PATCH 0732/1514] drm/asahi: g17: M5: run a pass the compact window holds only once on one render pair, so it renders instead of failing after 26 s On the M5 Ultra a render queue may hold two render pairs. Each pair maps its own target records, TPC object and parameter blocks, sized from the pass, in the client's 4 GiB compact window. The first render of a pass warms the second pair at the same layout, and admission spreads a queue's renders over both. A pass whose pair takes more than half the window, such as a single-sample 512x512 pass of 2048 layers or a 16384x16384 pass of 22 layers (2.2 to 2.4 GiB a pair), never rendered: building the second pair failed with ENOSPC, the render waited for room that its own first pair held, and after about 26 seconds failed with EBUSY, which the client saw as a lost device. Skipping the second pair when it does not fit is not enough: with three such renders in flight the third went to the unbuilt pair and failed the same way. Decide per render how many pairs its queue uses: both for a layout the window holds twice, else one (g17::pairs::for_window). SUBMIT, which already derives the layout, keeps the window bytes of one pair on the command, and the decision reads them there. A render that runs on one pair goes, through admission, only to the pair that took its queue's previous such render, so the large layout's objects exist in one pair, and it claims and warms no sibling. The scheduler's admission check applies the same rule, so it waits for that pair rather than for any. Smaller renders of the same queue still use both pairs. The optional warm-up of a sibling for which the window or the client's memory limit has no room is skipped as a busy one is, and the render runs on its pair. Which slot took those renders is kept with the slot's owner, as part of the owner's tenure of it: a slot that leaves the queue, whether its build was cancelled, it was given to another queue as a spare, or the processors stopped, comes back unmarked, so the renders stay on the pair that holds the large layout's objects, and a queue has at most one such slot. The rule only narrows a queue's renders to a slot it already holds: a held, quarantined or killed slot is handled as before, and no slot goes to another queue. On the M5 Ultra, Borealis (Vulkan) renders of 512x512x2048 (one, and two, three or four in flight), 16384x16384x22, 2048x2048x2047 and 1152x1152x2048 are now correct; heavy 1080p fill and geometry rows at depth 8 still run on both pairs, at the same time per submit as before (38.2 and 36.9 us) and 7-10% faster than on one pair. KUnit covers the decision and the admission routing: renders that run on one pair stay on the same pair up to its depth and never move to the other, a new queue whose renders need one pair claims no sibling, a slot lost and claimed back, or given to another queue and claimed back, does not take them from the pair that holds the layout, and the mesh storage moves a pass at the window's half to one pair. The admission fixtures of the host tests (tools/asahi) take the new State helpers, so they build the code they test. Other G17 parts, which hold one pair per queue, are unchanged. Fixes: b1c9a2143f39 ("drm/asahi: g17: restore two render pairs per queue on G17D within the shared QID capacity, 9-15% faster heavy 1080p rows at depth 8") Suggested-by: Ryan Murray Suggested-by: DjDeveloperr Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/command.rs | 12 ++ drivers/gpu/drm/asahi/g17/pairs.rs | 39 ++++ drivers/gpu/drm/asahi/g17/queue/admission.rs | 180 ++++++++++++++++-- .../g17/queue/render/m5_render_submission.rs | 27 ++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 13 +- .../drm/asahi/g17/runtime/render/prepare.rs | 13 +- .../drm/asahi/g17/runtime/render/submit.rs | 21 +- tools/asahi/g17-admission-order-tests.py | 8 +- tools/asahi/g17-quarantine-drain-tests.py | 2 +- tools/asahi/g17-resource-tests.py | 2 +- 10 files changed, 284 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/command.rs b/drivers/gpu/drm/asahi/g17/command.rs index da60d6b456d7eb..baab6673658ce7 100644 --- a/drivers/gpu/drm/asahi/g17/command.rs +++ b/drivers/gpu/drm/asahi/g17/command.rs @@ -466,6 +466,9 @@ pub(crate) enum Validated { ray_query: [RayQueryStage; 2], resources: Option>, plan: Option, + /// Bytes of the client's M5 compact window that each render pair built for this render + /// reserves, from the layout SUBMIT derives with the plan (`None` without an M5 plan). + pair_window: Option, attachments: [Attachments; 2], timestamps: [uapi::drm_asahi_timestamps; 2], }, @@ -510,6 +513,14 @@ impl Validated { Self::Render { long_job, .. } | Self::Compute { long_job, .. } => *long_job, } } + /// The compact-window bytes of each render pair kept by SUBMIT (`Render::pair_window`); + /// `None` for a compute command. + pub(crate) fn pair_window(&self) -> Option { + match self { + Self::Render { pair_window, .. } => *pair_window, + Self::Compute { .. } => None, + } + } pub(crate) fn allow_long_job(&mut self) { match self { Self::Render { long_job, .. } | Self::Compute { long_job, .. } => *long_job = true, @@ -738,6 +749,7 @@ impl Payload { ray_query: *ray_query, resources: resources.clone(), plan: None, + pair_window: None, attachments: *attachments, timestamps: [cmd.ts_vtx, cmd.ts_frag], }) diff --git a/drivers/gpu/drm/asahi/g17/pairs.rs b/drivers/gpu/drm/asahi/g17/pairs.rs index c7515c1c764171..1c63edf888564d 100644 --- a/drivers/gpu/drm/asahi/g17/pairs.rs +++ b/drivers/gpu/drm/asahi/g17/pairs.rs @@ -45,3 +45,42 @@ pub(crate) fn sibling_backlog() -> u8 { pub(crate) fn set_sibling_backlog(renders: u8) { BACKLOG.store(renders, Relaxed); } + + +/// The pairs a queue of `queue` pairs uses for a render each of whose pairs reserves +/// `window_bytes` of the client's M5 compact window of `window` bytes (`None`: no M5 footprint). +/// Each pair maps its own copy of a layout's objects in that one window, so a second pair is +/// built and used only for a layout the window holds twice. Any other layout runs on one of the +/// queue's pairs, always the same one, as on a part with one pair per queue +/// (`Pool::acquire_render`). SUBMIT has already refused a layout that one pair cannot hold. +pub(crate) fn for_window(queue: u8, window_bytes: Option, window: u64) -> u8 { + match window_bytes { + Some(bytes) if queue > 1 && bytes.saturating_mul(u64::from(queue)) > window => 1, + _ => queue, + } +} + +#[kernel::macros::kunit_tests(asahi_g17_pair_count)] +mod tests { + use super::*; + + const WINDOW: u64 = 1 << 32; + + #[test] + fn a_layout_the_window_holds_twice_keeps_both_pairs() { + assert_eq!(for_window(2, Some(WINDOW / 2), WINDOW), 2); + assert_eq!(for_window(2, Some(64 << 20), WINDOW), 2); + } + + #[test] + fn a_larger_layout_runs_on_one_pair() { + assert_eq!(for_window(2, Some(WINDOW / 2 + 1), WINDOW), 1); + assert_eq!(for_window(2, Some(WINDOW), WINDOW), 1); + } + + #[test] + fn a_one_pair_queue_and_a_render_without_footprint_are_unchanged() { + assert_eq!(for_window(1, Some(WINDOW), WINDOW), 1); + assert_eq!(for_window(2, None, WINDOW), 2); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index cc93cb6167981b..c40d449284ee37 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -65,6 +65,7 @@ fn wait_slice_ms(deadline_ns: u64, now_ns: u64) -> Result { struct State { active: u64, refs: [u8; cfg::RENDER_SLOTS], + /// The owner of each slot. Written only by [`Self::set_owner`], which keeps `wide` with it. owners: [u64; cfg::RENDER_SLOTS], epochs: [u64; cfg::RENDER_SLOTS], quarantined: u64, @@ -90,6 +91,11 @@ struct State { /// The physical queue table still has room for a pair built in an unowned slot. The /// runtime updates this whenever the table changes. build_room: bool, + /// Slots that take their owner's renders that run on one of a two-pair queue's pairs + /// ([`crate::g17::pairs::for_window`]), so the objects of a layout too large for two pairs + /// exist in that pair only: at most one per owner ([`Self::mark_wide`]). A mark belongs to its + /// owner's tenure of the slot: [`Self::set_owner`] drops it whenever the slot changes hands. + wide: u64, released: u64, epoch: u64, footprints: KVec, @@ -112,6 +118,7 @@ impl State { killed_at: [0; cfg::RENDER_SLOTS], held: 0, build_room: true, + wide: 0, released: 0, epoch: 0, footprints: KVec::new(), @@ -158,6 +165,14 @@ impl State { self.epoch = self.epoch.wrapping_add(1); self.epochs[slot] = self.epoch; } + /// Gives `slot` to `owner` (0: to nobody): the one writer of `owners`. A new owner starts + /// without the slot's one-pair mark. + fn set_owner(&mut self, slot: usize, owner: u64) { + if self.owners[slot] != owner { + self.wide &= !(1u64 << slot); + } + self.owners[slot] = owner; + } fn take_idle(&mut self, slot: usize, owner: u64) -> u8 { if self.owners[slot] != owner { crate::g17::trace::teardown( @@ -171,7 +186,7 @@ impl State { self.refs[slot] += 1; self.active |= 1u64 << slot; self.released &= !(1u64 << slot); - self.owners[slot] = owner; + self.set_owner(slot, owner); self.advance(slot); slot as u8 } @@ -277,7 +292,7 @@ impl State { }); if let Some(slot) = sibling { self.released &= !(1u64 << slot); - self.owners[slot] = owner; + self.set_owner(slot, owner); // A speculative sibling has no GPU-use recency yet. self.epochs[slot] = 0; } @@ -321,7 +336,7 @@ impl State { { return false; } - self.owners[slot] = owner.unwrap_or(0); + self.set_owner(slot, owner.unwrap_or(0)); self.released &= !bit; self.epochs[slot] = 0; true @@ -353,7 +368,7 @@ impl State { && self.refs[slot] == 1 && (self.quarantined | self.kill_hold | self.held) & bit == 0 { - self.owners[slot] = 0; + self.set_owner(slot, 0); self.released &= !bit; self.epochs[slot] = 0; true @@ -402,8 +417,49 @@ impl State { } } + /// The one pair a one-pair render (`pairs` 1) of an owner holding two pairs goes to: the pair + /// its previous one-pair render took, while the owner holds it (`wide`). Its layout's objects + /// then exist in that pair only. + fn wide(&self, owner: u64, pairs: usize) -> Option { + if pairs != 1 || self.owners.iter().filter(|id| **id == owner).count() < 2 { + return None; + } + (0..cfg::RENDER_SLOTS) + .find(|slot| self.wide & (1u64 << slot) != 0 && self.owners[*slot] == owner) + } + + /// Marks `slot` as taking its owner's one-pair renders, instead of any other slot. + fn mark_wide(&mut self, slot: usize) { + for other in 0..cfg::RENDER_SLOTS { + if self.owners[other] == self.owners[slot] { + self.wide &= !(1u64 << other); + } + } + self.wide |= 1u64 << slot; + } + + /// [`Self::can_pick`] for a render that may use `pairs` of the owner's pairs. + fn can_pick_render(&self, owner: u64, pairs: usize, plan: Plan) -> bool { + match (self.wide(owner, pairs), plan) { + (None, plan) => self.can_pick(owner, plan), + (Some(_), Plan::Wait) => false, + (Some(wide), Plan::Pair(slot)) if usize::from(slot) != wide => false, + (Some(wide), _) => self.usable(owner, wide), + } + } + fn pick(&mut self, owner: u64, pairs: usize, plan: Plan) -> Option { - match plan { + // A one-pair render of an owner holding two pairs goes only to the pair its previous + // one-pair render took, while the owner holds it (see `wide`). + if let Some(wide) = self.wide(owner, pairs) { + return match plan { + Plan::Wait => None, + Plan::Pair(slot) if usize::from(slot) != wide => None, + // The publication barrier orders a Join's overlap from this pair. + Plan::Any | Plan::Pair(_) | Plan::Join(_) => self.join(owner, wide), + }; + } + let slot = match plan { Plan::Any => self.acquire(owner, pairs), Plan::Wait => None, Plan::Pair(slot) => self.join(owner, usize::from(slot)), @@ -415,7 +471,11 @@ impl State { .min_by_key(|other| (self.refs[*other], u64::MAX - self.epochs[*other]))?; self.join(owner, other) }), + }?; + if pairs == 1 { + self.mark_wide(usize::from(slot)); } + Some(slot) } fn usable(&self, owner: u64, slot: usize) -> bool { self.owners.get(slot) == Some(&owner) @@ -630,7 +690,8 @@ impl Pool { self.state.lock().owner_quarantine(owner) == Some(true) } - /// For an owner that may hold `pairs` render pairs. + /// For an owner that may hold `pairs` render pairs: its queue's count, or 1 for a render + /// that runs on one of a two-pair queue's pairs ([`crate::g17::pairs::for_window`]). pub(crate) fn acquire_render( self: &Arc, owner: u64, @@ -749,7 +810,7 @@ impl Pool { } /// Whether `acquire_render` would admit this request now, without /// admitting it: the scheduler's prepare step waits for this. - pub(crate) fn admits_render(&self, owner: u64, request: Option>) -> bool { + pub(crate) fn admits_render(&self, owner: u64, pairs: usize, request: Option>) -> bool { let state = self.state.lock(); if owner == 0 || state.refusal(owner).is_err() { return false; @@ -758,7 +819,7 @@ impl Pool { return false; } let plan = state.plan(owner, request, None); - state.can_pick(owner, plan) + state.can_pick_render(owner, pairs, plan) } pub(crate) fn warmable_sibling( self: &Arc, @@ -805,7 +866,7 @@ impl Pool { let released = state.released & !state.active; for slot in 1..cfg::RENDER_SLOTS { if released & (1u64 << slot) != 0 { - state.owners[slot] = 0; + state.set_owner(slot, 0); state.epochs[slot] = 0; } } @@ -1448,16 +1509,16 @@ mod owner_pair_tests { state.owners[1] = 1; state.owners[2] = 1; for _ in 0..cfg::RENDER_DEPTH { - assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + assert_eq!(state.pick(1, 2, Plan::Pair(1)), Some(1)); } assert!(!state.can_pick(1, Plan::Pair(1))); - assert_eq!(state.pick(1, 1, Plan::Pair(1)), None); + assert_eq!(state.pick(1, 2, Plan::Pair(1)), None); assert!(state.can_pick(1, Plan::Join(1))); - assert_eq!(state.pick(1, 1, Plan::Join(1)), Some(2)); + assert_eq!(state.pick(1, 2, Plan::Join(1)), Some(2)); // With one pair a preference is the pair. state.owners[2] = 0; assert!(!state.can_pick(1, Plan::Join(1))); - assert_eq!(state.pick(1, 1, Plan::Join(1)), None); + assert_eq!(state.pick(1, 2, Plan::Join(1)), None); } #[test] @@ -1576,6 +1637,99 @@ mod two_pair_tests { assert!(state.reassign_unused_spare(6, Some(3), Some(2))); } + #[test] + fn a_one_pair_render_of_a_two_pair_owner_stays_on_one_pair() { + crate::g17::pairs::set_sibling_backlog(1); + let mut state = State::new(); + // Small renders take the first pair and, with a backlog there, the sibling. + let first = state.pick(1, 2, Plan::Any).unwrap(); + assert_eq!(state.pick(1, 2, Plan::Any), Some(first)); + let sibling = state.pick(1, 2, Plan::Any).unwrap(); + assert_ne!(sibling, first); + // A render whose layout the window holds once takes one of them, and every later such + // render goes there too, even when the other pair is idle or less loaded. + let wide = state.pick(1, 1, Plan::Any).unwrap(); + let other = if wide == first { sibling } else { first }; + state.release(other); + for _ in state.refs[usize::from(wide)]..cfg::RENDER_DEPTH { + assert_eq!(state.pick(1, 1, Plan::Any), Some(wide)); + } + // At full depth it waits for that pair instead of taking the other. + assert!(state.can_pick(1, Plan::Any)); + assert!(!state.can_pick_render(1, 1, Plan::Any)); + assert!(state.can_pick_render(1, 2, Plan::Any)); + assert_eq!(state.pick(1, 1, Plan::Any), None); + assert_eq!(state.pick(1, 1, Plan::Join(other)), None); + state.release(wide); + assert_eq!(state.pick(1, 1, Plan::Join(other)), Some(wide)); + assert_eq!(state.pick(1, 1, Plan::Pair(other)), None); + state.release(wide); + assert_eq!(state.pick(1, 1, Plan::Pair(wide)), Some(wide)); + // A small render may still use either pair. + assert_eq!(state.pick(1, 2, Plan::Pair(other)), Some(other)); + } + + #[test] + fn a_two_pair_owner_whose_first_render_needs_one_pair_claims_no_sibling() { + let mut state = State::new(); + // Two large renders in flight on a new queue share its one pair. + let first = state.pick(1, 1, Plan::Any).unwrap(); + assert_eq!(state.pick(1, 1, Plan::Any), Some(first)); + assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); + } + + #[test] + fn a_slot_lost_and_claimed_back_drops_its_one_pair_mark() { + let mut state = State::new(); + // A one-pair render of owner 1 takes slot `a`; its build fails before publication and + // the slot goes back unowned. + let a = state.pick(1, 1, Plan::Any).unwrap(); + assert!(state.cancel_empty_slot(a, 1)); + state.release(a); + // Owner 2 takes `a` meanwhile, so owner 1's next one-pair render, which builds its + // large layout's objects there, takes a slot `b` above it. + state.build_room = false; + assert_eq!(state.pick(2, 2, Plan::Any), Some(a)); + state.build_room = true; + let b = state.pick(1, 1, Plan::Any).unwrap(); + assert!(b > a); + state.release(b); + // Owner 2 closes, and a small render of owner 1 claims `a` back as its sibling. + state.release(a); + state.released |= 1u64 << a; + assert_eq!(state.pick(1, 2, Plan::Any), Some(b)); + assert_eq!(state.owners[usize::from(a)], 1); + state.release(b); + // The large layout's objects are in `b` alone, and its one-pair renders stay there. + assert_eq!(state.pick(1, 1, Plan::Any), Some(b)); + assert!(state.can_pick_render(1, 1, Plan::Pair(b))); + assert!(!state.can_pick_render(1, 1, Plan::Pair(a))); + assert_eq!(state.pick(1, 1, Plan::Join(a)), Some(b)); + } + + #[test] + fn a_slot_given_to_another_owner_drops_its_one_pair_mark() { + let mut state = State::new(); + // Owner 1 holds two pairs, and its one-pair renders went to the lower one. + state.owners[1] = 1; + state.owners[2] = 1; + assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + state.release(1); + // That pair is given to owner 2 as its spare, and owner 1's next one-pair render, with + // one pair left, builds its layout in the other. + assert!(state.reassign_unused_spare(1, Some(1), Some(2))); + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + state.release(2); + // Owner 2 closes, owner 1 claims the pair back, and its one-pair renders stay on the + // pair that holds the layout. + state.released |= 1u64 << 1; + assert_eq!(state.pick(1, 2, Plan::Any), Some(2)); + assert_eq!(state.owners[1], 1); + state.release(2); + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + assert!(!state.can_pick_render(1, 1, Plan::Pair(1))); + } + #[test] fn a_one_pair_owner_claims_no_sibling() { let mut state = State::new(); diff --git a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs index e337cfefc7849e..5b2afea2a8ca78 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/m5_render_submission.rs @@ -129,15 +129,24 @@ pub(crate) fn parameter_geometry(blocks: usize) -> Result) -> Result { + Ok(layout_and_window(command, clusters, programs, board)?.0) +} + +/// The target layout of a render and, for an M5 render, the bytes of the client's compact +/// window that each render pair built for it reserves. +pub(crate) fn layout_and_window(command: &Validated, clusters: u32, programs: RegisterPrograms, + board: Option<&'static crate::g17::fw::m5::initdata::Board>) + -> Result<(target::Layout, Option)> { let Validated::Render { pass, plan, .. } = command else { return Err(EINVAL); }; let layout = target::Layout::new(pass, clusters, programs)?; - if plan.is_none() { return Ok(layout); } + if plan.is_none() { return Ok((layout, None)); } validate(pass)?; let geometry = parameter_geometry(layout.tvb_blocks)?; let mesh_storage = compact::mesh_storage()?.map(|(_, bytes)| bytes); // The context state a pair allocates for each command slot (`Generation::allocate_state`). let state = super::generation::Layout::m5(board.ok_or(EINVAL)?).bytes; - Ok(m5_layout(layout, pass, clusters, geometry, mesh_storage, state)?.0) + let (layout, reserved) = m5_layout(layout, pass, clusters, geometry, mesh_storage, state)?; + Ok((layout, Some(reserved))) } /// The M5 layout of `pass` from its G17P layout, and the compact-window bytes a pair built for @@ -312,6 +321,12 @@ mod tests { reserved_with(size, layers, utile, few, MESH) } + /// The pairs a two-pair queue uses for that pass. + fn pairs(size: u32, layers: u16, utile: u8, few: bool, mesh: Option) -> u8 { + let bytes = reserved_with(size, layers, utile, few, mesh).unwrap() as u64; + crate::g17::pairs::for_window(2, Some(bytes), compact::WINDOW_BYTES) + } + #[test] fn borealis_32x32_passes_of_more_than_four_primitives() { assert!(reserved(16384, 21, 32, false).unwrap() <= WINDOW); @@ -351,6 +366,14 @@ mod tests { assert!(with - without >= 32 * MIB); } + #[test] + fn mesh_storage_counts_at_the_2_gib_edge() { + // A pass whose pair the window holds twice only without mesh storage runs on one pair. + assert_eq!(pairs(16384, 17, 32, true, None), 2); + assert_eq!(pairs(16384, 17, 32, true, MESH), 1); + assert_eq!(pairs(16384, 16, 32, true, MESH), 2); + } + #[test] fn a_pair_counts_the_objects_its_layout_does_not_size() { // A trace of a pair on the J775D found 3824 KiB of these objects, guards included and diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index c5188121aa1278..19bdf733ea088b 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -207,10 +207,15 @@ impl job::Backend for Backend { let programs = resources.as_deref().ok_or(EINVAL)?; *plan = Some(policy.plan(programs, priority)?); // The M5 target layout refuses the passes the M5 path cannot run. Derive it - // here, so that SUBMIT returns the refusal before anything is queued. - crate::g17::queue::render::m5_render_submission::layout( - command, self.shared.clusters, self.shared.variant.programs, - self.shared.m5_board)?; + // here, so that SUBMIT returns the refusal before anything is queued, and keep + // the window its pairs reserve for choosing their count (`render_pairs`). + let (_, window) = + crate::g17::queue::render::m5_render_submission::layout_and_window( + command, self.shared.clusters, self.shared.variant.programs, + self.shared.m5_board)?; + if let Validated::Render { pair_window, .. } = command { + *pair_window = window; + } } Validated::Compute { resources, plan, m5_scratch, cdm_auxiliary_allocation, .. } => { if let Some(programs) = resources { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 215ae50e3b22c9..c1f34c936753da 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -822,8 +822,8 @@ impl super::super::Backend { pub(super) fn ensure_render(&self, packet: &Arc, slot: u8, sleep: bool) -> Result { self.build_render_pair(slot, packet, false, sleep)?; - // An owner held to one pair has no sibling to warm. - if self.pairs == 1 { + // An owner held to one pair, or running this layout on one, has no sibling to warm. + if self.render_pairs(packet) == 1 { return Ok(()); } let sibling = { @@ -840,8 +840,15 @@ impl super::super::Backend { // construction and its final device-locked install have finished. // An optional sibling may be borrowed or waiting for recovery. // The selected pair is revalidated by prepare_render before publication. + // A sibling for which the client's window or memory limit has no room now, as the + // queue's other objects hold it, is not built either: this render runs on its pair. match self.build_render_pair(sibling.slot(), packet, true, sleep) { - Err(error) if error == EBUSY || error == EAGAIN || error == super::submit::FALLBACK => {} + Err(error) + if error == EBUSY + || error == EAGAIN + || error == super::submit::FALLBACK + || error == ENOSPC + || error == ENOMEM => {} result => result?, } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 70efc3cbb0f2b5..d2e7951ededbb9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -37,6 +37,16 @@ impl Backend { }) } + /// The render pairs this queue uses for `packet`: its own count, or one for an M5 layout + /// whose pairs the client's compact window cannot hold side by side + /// ([`crate::g17::pairs::for_window`]). + pub(in crate::g17::runtime) fn render_pairs(&self, packet: &Packet) -> u8 { + // SUBMIT derived the layout and kept its window bytes on the command. + crate::g17::pairs::for_window(self.pairs, + packet.command.pair_window().map(|bytes| bytes as u64), + crate::g17::buffer::compact::WINDOW_BYTES) + } + pub(in crate::g17) fn render_packet( &self, packet: &Arc, @@ -87,7 +97,7 @@ impl Backend { if !sleep { return Err(FALLBACK); } - match pool.acquire_render(self.owner, self.pairs.into(), Request::of(packet), deadline_ns, || { + match pool.acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet), deadline_ns, || { // Atomics only: the callback runs under the pool mutex. if packet.cancel_requested() || self.closed.load(Ordering::Acquire) { return Err(ECANCELED); @@ -190,11 +200,12 @@ impl Backend { Ok(_) => {} } let request = Request::of(packet); - if self.admission.admits_render(self.owner, request) { + let pairs = self.render_pairs(packet).into(); + if self.admission.admits_render(self.owner, pairs, request) { return None; } let observed = self.shared.renders.observe(); - if self.admission.admits_render(self.owner, request) { + if self.admission.admits_render(self.owner, pairs, request) { return None; } self.shared.queue_events(); @@ -411,7 +422,7 @@ impl Backend { Some(lease) => Some(lease), None if known != 0 => self .admission - .try_acquire_render(self.owner, self.pairs.into(), Request::of(packet)) + .try_acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet)) .ok() .flatten(), None => None, @@ -574,7 +585,7 @@ impl Backend { if !self.traversal_inline(packet) { return false; } - let admission = match self.admission.try_acquire_render(self.owner, self.pairs.into(), Request::of(packet)) { + let admission = match self.admission.try_acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet)) { Ok(Some(lease)) => lease, _ => return false, }; diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 89c9dc15c809d0..9aa69e45c52122 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -161,9 +161,9 @@ def held_fixture(): backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', - 'fn cancel_empty_slot(', 'fn can_pick(', 'fn pick(', 'fn usable(', 'fn join(', 'fn release(', - 'fn set_held(', 'fn retained(', 'fn used(']) + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', + 'fn cancel_empty_slot(', 'fn can_pick(', 'fn wide(', 'fn mark_wide(', 'fn pick(', 'fn usable(', + 'fn join(', 'fn release(', 'fn set_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn set_held(', 'pub(crate) fn release_retained_owners_after_processor_stop(', 'pub(crate) fn killed_pair_free(']) @@ -355,7 +355,7 @@ def release_fixture(): backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn set_held(', + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn set_held(', 'fn sync_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn set_held(', 'pub(crate) fn sync_held(', 'pub(crate) fn release_owner(']) diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 53204a179edd66..06a1826288d641 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -85,7 +85,7 @@ def fixture(): backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(admission, name) for name in [ 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', + 'fn set_owner(', 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn usable(', 'fn position(', 'fn release(', 'fn rehabilitate(', 'fn pair_drained(&mut self', 'fn retained(', 'fn used(']) pool = '\n'.join(item(admission, name) for name in [ 'pub(crate) fn release_owner(', 'pub(crate) fn release_retained_owners_after_processor_stop(', diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index 560f15a9b92da0..8e989a105c3e9c 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -39,7 +39,7 @@ def item(start): macro_rules! resource_exhausted { ($s:literal)=>{ENOSPC}; } type KVec = Vec; struct InFlight; mod cfg {\n'''+constants+'}\n'+limits+'\n' - methods=['const fn new','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn take_idle','fn acquire','fn usable','fn claim_sibling','fn reassign_unused_spare','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release'] + methods=['const fn new','fn exhausted','fn owner_quarantine','fn refusal','fn advance','fn set_owner','fn take_idle','fn acquire','fn usable','fn claim_sibling','fn reassign_unused_spare','fn warmable_sibling','fn borrow_warm_sibling','fn cancel_empty_slot','fn release'] code=header+item('struct State')+'\nimpl State {\n'+re.search(r' const MASK: u64 = .*;',s).group(0)+'\n'+'\n'.join(item(n) for n in methods)+'\n}\n'+''' // A queue holds g17::pairs::per_owner() pairs (Backend::pairs): one, or // RENDER_PAIRS_MAX on G17D. Both admissions run. From 652a2495c5d315189ae859de7753867fd01ccf7b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 08:36:13 +0100 Subject: [PATCH 0733/1514] media: apple: avd: reset the VP9 segmentation map when the frame size changes VP9 clears the segmentation map when the frame size changes (compute_image_size(); libvpx zeroes last_frame_seg_map). The driver sets VP9_SEG_RESET only for key frames and after an intra frame without segmentation, and the decoder keeps part of the map in the seg buffer across frames. After a size change, a frame that predicts its segment IDs from the previous frame or keeps them (update_map 0) used the old map, laid out for the other size. After a size change, set VP9_SEG_RESET for every frame that uses segmentation until one updates the map. The decoder does not carry a reset map forward: a frame that keeps the map (update_map 0) after one with VP9_SEG_RESET reads the old map again, so the reset is repeated until a frame has written a new map. Clear each bank's seg buffer before the bank next runs: a bank still busy with an earlier frame belongs to the hardware until it retires, so its buffer is cleared when it is next taken. Test streams from libvpx with internal scaling (VP8E_SET_SCALEMODE: full, half, full size on inter frames) and segmentation AQ, no error resilience, against libvpx-equivalent software decoding, with frames smaller than the capture format accepted (later in this series): 640x360 cyclic refresh (temporal map) 25/40 -> 40/40 variance, complexity (kept map) 10/40, 25/40 -> 40/40 1280x720 all three 40/40 1920x1080 all three 40/40 With the reset on the first frame of the new size only, the kept-map streams at 1280x720 and 1920x1080 went wrong from the second frame after the size grew back (26/40, 26/40, 28/40, 29/40). These streams ran on the legacy transport, which has one VP9 bank, and use segmentation on every frame. The host test checks, with two banks, that only a size change clears the buffers, that a busy bank's buffer waits until the bank is taken, and that the reset stays until a frame updates the map. Signed-off-by: Thomas Glanzmann --- drivers/media/platform/apple/avd/avd-vp9.c | 31 +++++++++++++++++ .../platform/apple/avd/tests/vp9-test.py | 34 +++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 18a0717349f86f..3c69c9586cf4b4 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -200,6 +200,8 @@ struct avd_vp9_bank { struct avd_vp9_frame_info cur; struct avd_vp9_frame_info last; u8 submit_num; + /* The seg buffer holds a map laid out for another frame size. */ + bool seg_clear; }; struct avd_vp9_ctx { @@ -208,6 +210,8 @@ struct avd_vp9_ctx { unsigned int nbanks; struct avd_vp9_bank bank[AVD_VP9_BANKS]; struct avd_vp9_bank *b; + /* The size changed, and no frame has updated the segmentation map since. */ + bool seg_reset; }; static bool avd_vp9_needs_counts(u32 flags) @@ -347,6 +351,7 @@ static u32 make_flags1(struct avd_ctx *ctx, struct avd_vp9_run *run) flags |= VP9_SEG_RESET( frame->seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED && (frame->flags & V4L2_VP9_FRAME_FLAG_KEY_FRAME || + vp9_ctx->seg_reset || (vp9_ctx->last.valid && !(vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED) && @@ -593,6 +598,14 @@ static void update_ctx_cur_info(struct avd_vp9_ctx *vp9_ctx, static void update_ctx_last_info(struct avd_vp9_ctx *vp9_ctx) { vp9_ctx->last = vp9_ctx->b->cur; + /* + * The decoder does not carry a reset map forward: a frame that keeps the + * map after one with VP9_SEG_RESET reads the old map again. So the reset + * stays until a frame has written a new map. + */ + if ((vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_ENABLED) && + (vp9_ctx->last.seg.flags & V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP)) + vp9_ctx->seg_reset = false; } static void copy_vp9_frame_mv(struct avd_vp9_probs *avd_probs, @@ -909,6 +922,24 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) bank - vp9_ctx->bank + 1; } + /* + * VP9 clears the segmentation map when the frame size changes, and the + * decoder carries part of it over in the seg buffer. Every bank's buffer + * holds the old map, but a busy bank's belongs to the hardware until the + * frame retires: clear each bank's when it is next taken. The map reset + * goes to every frame that uses segmentation until one updates the map + * (make_flags1(), update_ctx_last_info()). + */ + if (vp9_ctx->last.valid && !avd_vp9_same_size(dec_params, &vp9_ctx->last)) { + for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) + vp9_ctx->bank[i].seg_clear = true; + vp9_ctx->seg_reset = true; + } + if (vp9_ctx->b->seg_clear) { + memset(vp9_ctx->b->bufs.seg.cpu, 0, vp9_ctx->b->bufs.seg.size); + vp9_ctx->b->seg_clear = false; + } + vp9_ctx->b->cur.tx_mode = run->prob_updates->tx_mode; fctx_idx = v4l2_vp9_reset_frame_ctx(dec_params, vp9_ctx->frame_context); diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index e3a57861830d51..01610c847a2324 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -253,6 +253,40 @@ def without_includes(s): for(size_t j=0;jnbanks;i++)memset(p->bank[i].bufs.seg.cpu,0xa5,p->bank[i].bufs.seg.size); + /* Frame A writes a map, so no reset is owed from the earlier size changes. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED|V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[0]&&((u8 *)p->bank[0].bufs.seg.cpu)[0]==0xa5&&!p->seg_reset); + /* Bank 0 stays busy; the next frame is smaller and has no segmentation. */ + params.seg.flags=0;params.frame_width_minus_1=1899;params.frame_height_minus_1=1079; + current_dst=&dst[1].base.vb;frame.idx=1;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[1]&&p->seg_reset&&p->bank[0].seg_clear&&!p->bank[1].seg_clear); + {u8 *seg=p->bank[1].bufs.seg.cpu;for(size_t j=0;jbank[1].bufs.seg.size;j++)assert(!seg[j]);} + assert(((u8 *)p->bank[0].bufs.seg.cpu)[0]==0xa5); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE); + /* Same size again, segmentation on without a map update: the reset is still owed, and it stays + * owed after that frame, as the decoder would read the old map again. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED;current_dst=&dst[0].base.vb; + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(make_flags1(&ctx,&r)&VP9_SEG_RESET(1));} + frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(p->b==&p->bank[0]&&!p->bank[0].seg_clear&&p->seg_reset); + {u8 *seg=p->bank[0].bufs.seg.cpu;for(size_t j=0;jbank[0].bufs.seg.size;j++)assert(!seg[j]);} + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + /* The next frame updates the map: it still gets the reset, and after it the reset is gone. */ + params.seg.flags=V4L2_VP9_SEGMENTATION_FLAG_ENABLED|V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP; + current_dst=&dst[1].base.vb; + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(make_flags1(&ctx,&r)&VP9_SEG_RESET(1));} + frame.idx=1;assert(!avd_vp9_run(&ctx));assert(!p->seg_reset); + {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; + assert(!(make_flags1(&ctx,&r)&VP9_SEG_RESET(1)));} + avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE);params.seg.flags=0; /* The firmware transport keeps the 64-pixel floor. */ ctx.decoded_fmt.fmt.pix_mp.width=64;ctx.decoded_fmt.fmt.pix_mp.height=64; ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=64; From a8e9047aac5025ec881cbe436a76663dfbbbd46e Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 08:41:32 +0100 Subject: [PATCH 0734/1514] media: apple: avd: decode VP9 frames smaller than the capture format VP9 inter frames can change the frame size and keep predicting from references of the old size. validate_dec_params() refuses every frame whose aligned size differs from the capture format, so userspace has to reallocate the capture buffers and loses those references. FFmpeg's V4L2 request VP9 hwaccel can instead keep the buffers and decode a frame that fits in place (FFmpeg PR 20847, fix 5), and the decoder already handles what this needs: each reference carries its own size and scale (set_refs()), the frame is written with the format's stride, and the scratch buffers are sized for the format. On the legacy transport, accept frames whose aligned size fits the capture format and keep refusing larger ones. The firmware transports (open-queue and the Apple backend) keep requiring the format's size, as they keep the 64-pixel floor: an input their firmware does not expect can reset the engine instead of failing the frame, and this has not been measured there yet. The host test runs a 960x540 frame in a 1920x1088 format on the legacy transport, refuses it on the firmware transport, and refuses a 1984x1088 one on both. On a J813 (legacy transport) with FFmpeg PR 20847 v2 (decoding in place) and the earlier patches of this series, the libvpx VP9 conformance vectors match libvpx's MD5s in 299 of 304 4:2:0 vectors, up from 273. The 26 are the 24 vp90-2-21-resize_inter vectors, vp90-2-05-resize and vp90-2-18-resize. No vector stopped matching, and no frame fails in the firmware. Userspace that renegotiates the format on every size change, such as FFmpeg's current code, decodes as before (273). H.264, HEVC, VP9 and AV1 test clips stay bit-exact. Signed-off-by: Thomas Glanzmann --- drivers/media/platform/apple/avd/avd-vp9.c | 17 ++++++++++++----- .../media/platform/apple/avd/tests/vp9-test.py | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index 3c69c9586cf4b4..93b6404ce593f4 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -698,7 +698,7 @@ static void init_probs(struct avd_ctx *ctx, const struct avd_vp9_run *run) static int validate_dec_params(struct avd_ctx *ctx, const struct v4l2_ctrl_vp9_frame *dec_params) { - unsigned int aligned_width, aligned_height; + unsigned int aligned_width, aligned_height, width, height; /* * The CAPTURE format is at least 64x64, the minimum of the VP9 frame @@ -721,11 +721,18 @@ static int validate_dec_params(struct avd_ctx *ctx, 64); /* - * Userspace should update the capture/decoded format when the - * resolution changes. + * A larger frame needs a new capture format. On the legacy transport + * a smaller one is decoded into the current buffers with their + * stride: VP9 inter frames can change size and keep predicting from + * references of the old size, which set_refs() scales, so userspace + * may keep the buffers. The firmware transports keep requiring the + * format's size until that is measured there, as for the floor above. */ - if (aligned_width != ctx->decoded_fmt.fmt.pix_mp.width || - aligned_height != ctx->decoded_fmt.fmt.pix_mp.height) { + width = ctx->decoded_fmt.fmt.pix_mp.width; + height = ctx->decoded_fmt.fmt.pix_mp.height; + if (avd_backend_is_open(ctx->dev) ? + (aligned_width > width || aligned_height > height) : + (aligned_width != width || aligned_height != height)) { dev_err(ctx->dev->dev, "unexpected bitstream resolution %dx%d\n", aligned_width, aligned_height); diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 01610c847a2324..13801c76ae1218 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -287,6 +287,11 @@ def without_includes(s): {struct avd_vp9_run r={.decode_params=¶ms};r.base.bufs.dst=current_dst; assert(!(make_flags1(&ctx,&r)&VP9_SEG_RESET(1)));} avd_vp9_done(&ctx,&src,&dst[1].base.vb,VB2_BUF_STATE_DONE);params.seg.flags=0; + /* The firmware transport still needs the format's size: smaller and larger frames are refused. */ + params.frame_width_minus_1=959;params.frame_height_minus_1=539; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); + params.frame_width_minus_1=1983;params.frame_height_minus_1=1087; + current_dst=&dst[1].base.vb;frame.idx=1;assert(avd_vp9_run(&ctx)==-EINVAL); /* The firmware transport keeps the 64-pixel floor. */ ctx.decoded_fmt.fmt.pix_mp.width=64;ctx.decoded_fmt.fmt.pix_mp.height=64; ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=64; @@ -307,6 +312,18 @@ def without_includes(s): params.frame_width_minus_1=1919;params.frame_height_minus_1=1087; assert(avd_vp9_run(&ctx)==-EINVAL); avd_vp9_stop(&ctx); + /* On the legacy transport a frame smaller than the capture format runs in it, a larger one is refused. */ + ctx.decoded_fmt.fmt.pix_mp.width=1920;ctx.decoded_fmt.fmt.pix_mp.height=1088; + ctx.decoded_fmt.fmt.pix_mp.plane_fmt[0].bytesperline=1920; + dev.queued=false;vp_feature=false;assert(!avd_vp9_start(&ctx));p=ctx.priv; + params=(struct v4l2_ctrl_vp9_frame){.flags=V4L2_VP9_FRAME_FLAG_KEY_FRAME|V4L2_VP9_FRAME_FLAG_SHOW_FRAME, + .frame_width_minus_1=959,.frame_height_minus_1=539,.bit_depth=8}; + current_dst=&dst[0].base.vb;frame.idx=0;assert(!avd_vp9_run(&ctx)); + assert(dst[0].vp9.width==960&&dst[0].vp9.height==540); + avd_vp9_done(&ctx,&src,&dst[0].base.vb,VB2_BUF_STATE_DONE); + params.frame_width_minus_1=1983;params.frame_height_minus_1=1087; + current_dst=&dst[0].base.vb;frame.idx=0;assert(avd_vp9_run(&ctx)==-EINVAL); + avd_vp9_stop(&ctx); dev.queued=true;vp_feature=true;fail_alloc_after=13;allocating_ctx=&ctx; assert(avd_vp9_start(&ctx)==-ENOMEM);allocating_ctx=NULL; assert(!ctx.priv&&!avd_vp9_ready(&ctx)&&ctx.max_frames==1); From c58cfabc16a92f0d76b7fa18d1e65353dda042e7 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Tue, 24 Nov 2026 00:25:40 +0100 Subject: [PATCH 0735/1514] accel/ane: h17: recover a hung engine instead of keeping it until reboot On H17 a request that never completes quarantines the session (h16_fail()), and the backend has no ops->hung: every later LOAD fails with -EIO until reboot. A system sleep does not help either. The sleep path sends a STOP the hung firmware never answers, powers the engine off on the deep path and boots it again from the preload on resume, but nothing ends the session's quarantine, so the new firmware sits unused. macOS restarts the firmware after a request timeout: it powers the engine off, going on when the firmware never answers the stop, starts it again cold and reloads the open programs. The H16 and T8112 paths do the same. Do it on H17, at runtime and across a system sleep: - ops->hung queues a recovery. It closes the session, polls every ANE DART port for idle (up to 100 ms per port) so no DMA is cut off mid-flight, and powers the engine off under the firmware with the power-down a sleep and a park already use: sub-block, PWGATE and its ack, CPU, then ANE_SYS through genpd, which deactivates the DARTs right before it goes off. The firmware is not asked to stop, and no new register is written. Outside a sleep, busy DART ports or a stuck power word fail the runtime recovery and leave recovery to the next system sleep instead of deferring to a deep path that does not come. - A system sleep with a quarantined session (or one the closing gate release quarantines) powers the engine off the same way, without the futile STOP, and takes the deep path as the failed STOP made it do. - Runtime suspend checks the session before and after closing it and returns -EBUSY without permanently quarantining the backend, leaving a quarantined session to the recovery work or the next system sleep. Nothing the old firmware could reach is reused until it is proven gone: after our power-down began, genpd must report ANE_SYS off with its PMGR actual state (bits 7:4) reading off, nothing may hold ANE_SYS or the child power states again, and the ANE CPU and sub-block power states must read off now (PMGR, readable in any power state). We hold ANE_SYS until the power-down puts it, so no earlier OFF can count. Only then does the cold boot clear and reuse the pool, IPC ring, heap and heap tail, copy TEXT and DATA from the kernel-held preload again (their digests checked), and does ane_h16_session_recovered() end the quarantine and give back the memory of programs closed while it lasted; the open programs are then replayed behind their handles. The power-up before the boot repeats the cold PMGR, PWGATE and DART checks of every boot. Without that proof the session stays quarantined, its memory held, and the next sleep tries again; a resume that cannot prove it does not boot the engine at all. A boot or replay that fails after the proof quarantines the engine until reboot, as any failed boot does. debugfs ane-h17// gains recoveries and recover_failures. Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 302 +++++++++++++++++++++-- drivers/accel/ane/ane_fw_cold.h | 30 +++ drivers/accel/ane/ane_fw_cold_test.c | 46 ++++ drivers/accel/ane/ane_h16_program_test.c | 61 +++++ 4 files changed, 419 insertions(+), 20 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index d1b0eec0aecc4c..a7efd9a4220b14 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -149,6 +149,18 @@ struct ane_fw_backend { struct work_struct start; /* ANE_SYS and the child power states are on: the engine is readable. */ bool powered; + /* + * Recovery of a session quarantined by a hung request (ane_fw_hung()): + * at runtime by the recover work, else by the next system sleep. + * hung_down: the quarantined engine was powered off under its firmware; + * from then on genpd's next ANE_SYS OFF, with the PMGR actual state off, + * sets hung_off (ane_fw_genpd_event()), the proof the firmware is gone. + */ + struct work_struct recover; + bool hung_down, hung_off; + /* A power-down outside a sleep: a stuck power word cannot wait for one. */ + bool runtime_off; + u64 recoveries, recover_failures; }; /* One ANE per SoC. The observer exists before platform driver registration: @@ -584,7 +596,7 @@ static int ane_fw_ps_off(struct ane_fw_backend *b, u32 offset) if (!ane_poll32(b, reg, ANE_FW_PS_OFF_MASK, 0, 1, 1000)) return 0; } - if (b->in_rpm || !apple_sleep_request_deep_once()) + if (b->in_rpm || b->runtime_off || !apple_sleep_request_deep_once()) return ret; dev_warn(&b->pdev->dev, "H17 ANE: power word %#x still stuck, taking the deep path\n", offset); return 0; @@ -774,8 +786,10 @@ static int ane_fw_reload_segment(struct ane_fw_backend *b, unsigned int i) * and startup as start-at-boot does. The shared allocations are carried * into the new transport and served again; programs loaded before are lost. * Every wait is bounded (power polls, READY, ANE_FW_TIMEOUT_NS commands). + * With @recover the old firmware was a quarantined one, proven gone + * (ane_fw_hung_gone()): its quarantine ends before the replay. */ -static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b) +static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b, bool recover) { struct device *dev = &b->pdev->dev; struct ane_fw_transport *old; @@ -841,6 +855,9 @@ static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b) div_u64(b->resume_ready_ns - start, NSEC_PER_MSEC)); /* Every open program back behind its handle, as the application left it. */ ane_h16_session_restart(&b->session); + /* Programs closed while quarantined go back to the spares. */ + if (recover) + ane_h16_session_recovered(&b->session); ret = ane_h16_session_replay(&b->session, &b->resume_replayed, &b->resume_first_ns); if (ret) { dev_err(dev, "H17 ANE: PROGRAM REPLAY FAILED %d after %u programs; session quarantined\n", @@ -896,15 +913,20 @@ static int ane_fw_stop_wait(struct ane_fw_backend *b) return 0; } -/* Every port of every ANE DART idle: what macOS checks before it powers one down. */ -static int ane_fw_dart_idle(struct ane_fw_backend *b) +/* + * Every port of every ANE DART idle: what macOS checks before it powers one down. + * Polls each active port for up to @timeout_us (sleeping @sleep_us between reads). + */ +static int ane_fw_dart_idle_wait(struct ane_fw_backend *b, unsigned long sleep_us, + u64 timeout_us) { for (unsigned int i = 0; i < ANE_FW_DARTS; i++) { u32 params = ane_rd32(b, b->dart[i] + 4); unsigned int ports = max((params >> 16) & 7, (params >> 20) & 7); for (unsigned int p = 0; p < min(ports, 4U); p++) { - int ret = ane_poll32(b, b->dart[i] + 0x230 + 4 * p, U32_MAX, 0, 1, 10000); + int ret = ane_poll32(b, b->dart[i] + 0x230 + 4 * p, U32_MAX, 0, + sleep_us, timeout_us); if (ret) { dev_err(&b->pdev->dev, "H17 ANE: DART %u port %u not idle: %#x\n", @@ -916,6 +938,11 @@ static int ane_fw_dart_idle(struct ane_fw_backend *b) return 0; } +static int ane_fw_dart_idle(struct ane_fw_backend *b) +{ + return ane_fw_dart_idle_wait(b, 1, 10000); +} + /* * Each DART as macOS leaves it before the power words (recorded, 25G83): its counters * cleared, error status acknowledged, every enabled stream disabled one at a time, then @@ -1084,7 +1111,7 @@ static void ane_fw_unpark(struct ane_fw_backend *b) if (!b->parked || READ_ONCE(b->in_sleep)) return; b->in_rpm = true; - ret = ane_fw_cold_cycle_boot(b); + ret = ane_fw_cold_cycle_boot(b, false); b->in_rpm = false; WRITE_ONCE(b->parked, false); WRITE_ONCE(b->session.parked, false); @@ -1097,6 +1124,196 @@ static void ane_fw_unpark(struct ane_fw_backend *b) dev_info(&b->pdev->dev, "H17 ANE: up for a request%s\n", ret ? " FAILED" : ""); } +/* + * Recovery of a session quarantined by a hung request, as the H16 and T8112 + * paths do it and as macOS restarts the firmware after a request timeout: + * the engine is powered off under the firmware, proven off, booted again + * from the preload, and every open program is replayed behind its handle. + * + * The firmware is not asked for anything: a STOP to a hung firmware times + * out and changes nothing, and macOS goes on with the power-off when its + * stop is not answered. No new register is written either: the power-down + * is the one a sleep and a park use (sub-block, PWGATE and its ack, CPU, + * then ANE_SYS through genpd, which deactivates the DARTs right before it). + * At runtime we power down only once every ANE DART port reads idle, so no + * DMA is cut off mid-flight; ports that stay busy leave recovery to the + * next system sleep, which takes the deep path. + * + * Nothing the old firmware could reach is reused before ane_fw_hung_proven(): + * genpd reported ANE_SYS off after our power-down, with its PMGR actual + * state off, and the CPU and sub-block power states read off. Only then does + * the cold boot clear pool, IPC, heap and heap tail, copy TEXT and DATA from + * the preload again (digests checked) and give back the memory of programs + * closed while quarantined. The power-up before it repeats the cold PMGR, + * PWGATE and DART checks of every boot. + */ +#define ANE_FW_HUNG_DRAIN_MS 100U +#define ANE_FW_HUNG_OFF_MS 2000 + +/* + * Power a quarantined engine off under its firmware. From here on, genpd's + * next ANE_SYS OFF proves it off: we hold ANE_SYS until the power-down puts + * it, so no OFF can come earlier. + */ +static int ane_fw_hung_down(struct ane_fw_backend *b, bool runtime) +{ + int ret; + + if (!b->hung_down) { + WRITE_ONCE(b->hung_off, false); + /* Seen by ane_fw_genpd_event() before the put below can turn ANE_SYS off. */ + smp_store_release(&b->hung_down, true); + } + if (!b->powered) { + /* Off already: an earlier attempt, whose proof may still come. */ + if (b->power_ref) { + b->power_ref = false; + pm_runtime_put_sync_suspend(b->power); + } + return 0; + } + /* At runtime there is no deep path: a stuck power word fails it. */ + b->runtime_off = runtime; + ret = ane_fw_power_down(b); + b->runtime_off = false; + return ret; +} + +static bool ane_fw_hung_proven(struct ane_fw_backend *b) +{ + struct ane_fw_hung_proof p = { + .down = b->hung_down, + .sys_off = READ_ONCE(b->hung_off), + .held = b->powered || b->power_ref, + }; + + /* PMGR only: readable whatever ANE_SYS does. */ + ane_fw_snapshot_pmgr(b); + return ane_fw_hung_gone(&p, &b->cold); +} + +/* At runtime genpd turns ANE_SYS off once the ANE DARTs are idle too. */ +static bool ane_fw_hung_wait_off(struct ane_fw_backend *b) +{ + u64 deadline = ktime_get_ns() + ANE_FW_HUNG_OFF_MS * NSEC_PER_MSEC; + + while (!READ_ONCE(b->hung_off) && ktime_get_ns() < deadline) + usleep_range(10000, 20000); + return READ_ONCE(b->hung_off); +} + +/* The new firmware is up: the next hang starts its proof afresh. */ +static void ane_fw_hung_recovered(struct ane_fw_backend *b) +{ + b->hung_down = false; + WRITE_ONCE(b->hung_off, false); + b->recoveries++; +} + +static void ane_fw_recover_work(struct work_struct *work) +{ + struct ane_fw_backend *b = container_of(work, struct ane_fw_backend, recover); + struct device *dev = &b->pdev->dev; + bool rpm = ane_fw_rpm(b), held = false, reschedule = false; + u64 start = ktime_get_ns(); + int ret; + + /* + * Keep runtime PM from starting a park, and wait for any park in + * flight before taking b->lock so dropping ANE_SYS under b->lock + * cannot wait on a callback that needs b->lock. + */ + if (rpm) { + pm_runtime_get_noresume(dev); + pm_runtime_barrier(dev); + held = true; + } + scoped_guard(mutex, &b->lock) { + /* A system sleep recovers it itself (ane_fw_sleep_prepare()). */ + if (READ_ONCE(b->in_sleep) || b->slept || b->parked || + b->stage != ANE_STAGE_PROGRAM || !b->session.quarantined) { + reschedule = b->stage == ANE_STAGE_PROGRAM && !b->parked && !b->slept && + !READ_ONCE(b->in_sleep) && !b->session.quarantined; + break; + } + /* Closes admission: requests wait in ane_h16_session_enter() meanwhile. */ + ane_h16_session_sleep(&b->session, true); + /* + * Wait for every ANE DART port to drain before cutting power under a + * firmware that did not stop, as the clean stop and macOS do. + */ + if (b->powered && + ane_fw_dart_idle_wait(b, 1000, ANE_FW_HUNG_DRAIN_MS * USEC_PER_MSEC)) { + b->recover_failures++; + dev_err(dev, + "H17 ANE: hung engine still has DMA in flight after %u ms; no power cut at runtime, quarantined until the next system sleep\n", + ANE_FW_HUNG_DRAIN_MS); + ane_h16_session_sleep(&b->session, false); + break; + } + /* Hand our reference to b->power_ref so ane_fw_hung_down() drops ANE_SYS. */ + if (held) { + if (b->power_ref) + pm_runtime_put_noidle(dev); + else + b->power_ref = true; + held = false; + } + ret = ane_fw_hung_down(b, true); + if (!ret && !ane_fw_hung_wait_off(b)) + ret = -ETIMEDOUT; + if (!ret && !ane_fw_hung_proven(b)) + ret = -EIO; + if (ret) { + b->recover_failures++; + dev_err(dev, + "H17 ANE: hung engine not proven off (%d; ANE_SYS %#x CPU %#x sub-block %#x); quarantined until the next system sleep\n", + ret, ane_rd32(b, b->pmgr + b->soc->pmgr_sys), + ane_rd32(b, b->pmgr + b->soc->pmgr_cpu), + ane_rd32(b, b->pmgr + b->soc->pmgr_subblock)); + ane_h16_session_sleep(&b->session, false); + break; + } + b->resume_replayed = 0; + b->resume_first_ns = 0; + ret = ane_fw_cold_cycle_boot(b, true); + if (ret) { + b->recover_failures++; + /* Booted over memory proven free: as any failed boot, until reboot. */ + ane_fw_quarantine(b, ret); + b->session.quarantined = true; + } else { + ane_fw_hung_recovered(b); + ane_fw_rpm_idle(b); + } + ane_h16_session_sleep(&b->session, false); + dev_info(dev, + "H17 ANE: %s after a hung request in %llu ms, %u programs replayed\n", + ret ? "recovery FAILED" : "firmware recovered", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), b->resume_replayed); + } + if (held) { + if (reschedule) { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } else { + pm_runtime_put_noidle(dev); + } + } +} + +/* Session ops->hung: may run under the session lock, so only queue. */ +static void ane_fw_hung(void *ctx, int error) +{ + struct ane_fw_backend *b = ctx; + + if (READ_ONCE(b->in_sleep)) + return; + dev_warn(&b->pdev->dev, "H17 ANE: session quarantined (%d); restarting the engine\n", + error); + queue_work(system_dfl_wq, &b->recover); +} + /* * A request for a parked engine: runtime PM resumes the device, and its * resume callback boots the engine. Called without b->lock, which the @@ -1166,16 +1383,13 @@ int ane_fw_staged_runtime_suspend(struct device *dev) if (!b->powered) return 0; /* Bringing up, quarantined, or in a system sleep, which parks it itself. */ - if (b->stage != ANE_STAGE_PROGRAM || READ_ONCE(b->in_sleep)) - return -EBUSY; - if (READ_ONCE(b->session.quarantined)) { - ane_fw_quarantine(b, b->session.error ?: -EIO); + if (b->stage != ANE_STAGE_PROGRAM || READ_ONCE(b->in_sleep) || + READ_ONCE(b->session.quarantined)) return -EBUSY; - } /* Closes admission and waits for every request in flight. */ ane_h16_session_sleep(&b->session, true); + /* The gate release on the way quarantined it: that is the recovery's (ane_fw_hung()). */ if (READ_ONCE(b->session.quarantined)) { - ane_fw_quarantine(b, b->session.error ?: -EIO); ane_h16_session_sleep(&b->session, false); return -EBUSY; } @@ -1269,6 +1483,26 @@ static int ane_fw_sleep_prepare(struct ane_fw_backend *b) b->sys_off_at = 0; b->sys_off_pmgr = 0; b->sys_on_pmgr = 0; + /* + * A session quarantined by a hung request (or by the gate release just + * now): the firmware can't be asked for anything, so the engine goes + * off under it, and this sleep takes the deep path, as after a failed + * stop. The resume ends the quarantine once the power-off is proven. + */ + if (b->session.quarantined) { + if (b->powered || !READ_ONCE(b->hung_off)) + apple_sleep_request_deep_once(); + ret = ane_fw_hung_down(b, false); + dev_info(&b->pdev->dev, "H17 ANE: hung engine powered off for system sleep (%d)\n", + ret); + if (ret) { + ane_fw_quarantine(b, ret); + ane_h16_session_sleep(&b->session, false); + return ret; + } + b->slept = true; + return 0; + } if (!ane_fw_sleep_warm(b)) { ret = ane_fw_cold_cycle_down(b); if (ret == -EBUSY) { @@ -1330,6 +1564,9 @@ static int ane_fw_genpd_event(struct notifier_block *nb, unsigned long action, v b->sys_offs++; b->sys_off_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); b->sys_off_at = now; + /* After a hung engine's power-down: the proof it is gone. */ + if (smp_load_acquire(&b->hung_down) && ane_fw_sys_off(b->sys_off_pmgr)) + WRITE_ONCE(b->hung_off, true); } else if (action == GENPD_NOTIFY_ON) { b->sys_ons++; b->sys_on_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); @@ -1342,6 +1579,7 @@ static int ane_fw_genpd_event(struct notifier_block *nb, unsigned long action, v static void ane_fw_sleep_resume(struct ane_fw_backend *b) { + bool recover = false, warm; s64 ready, first; u64 start; int ret; @@ -1350,8 +1588,19 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) if (!b->slept) return; b->slept = false; + /* A hung engine went off for this sleep: a cold boot once proven gone. */ + if (b->session.quarantined) { + if (!ane_fw_hung_proven(b)) { + dev_err(&b->pdev->dev, + "H17 ANE: hung engine not proven off across the sleep (ANE_SYS genpd off %u, PMGR %#x at off; CPU %#x sub-block %#x); kept quarantined\n", + b->sys_offs, b->sys_off_pmgr, b->cold.cpu, b->cold.subblock); + ane_h16_session_sleep(&b->session, false); + return; + } + recover = true; + } /* Stay off until a request needs the engine, as macOS does. */ - if (b->soc->macos_sleep && !b->session.quarantined) { + if (b->soc->macos_sleep && !recover) { WRITE_ONCE(b->parked, true); WRITE_ONCE(b->session.parked, true); dev_info(&b->pdev->dev, "H17 ANE: resume ok: parked until the next request\n"); @@ -1361,19 +1610,25 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) b->resume_ready_ns = 0; b->resume_first_ns = 0; b->resume_replayed = 0; - ret = ane_fw_sleep_warm(b) ? ane_fw_warm_boot(b) : ane_fw_cold_cycle_boot(b); - if (ret && ane_fw_sleep_warm(b)) { + /* The firmware of a hung engine was not suspended: only a cold boot. */ + warm = ane_fw_sleep_warm(b) && !recover; + ret = warm ? ane_fw_warm_boot(b) : ane_fw_cold_cycle_boot(b, recover); + if (ret && warm) { /* Fall back to the cold cycle: off again, then boot from the preload. */ dev_warn(&b->pdev->dev, "H17 ANE: warm boot failed (%d); cold boot and program replay\n", ret); ret = b->powered ? ane_fw_power_down(b) : 0; if (!ret) - ret = ane_fw_cold_cycle_boot(b); + ret = ane_fw_cold_cycle_boot(b, false); } if (ret) { /* Every mapping and backing stays for diagnosis. */ ane_fw_quarantine(b, ret); b->session.quarantined = true; + } else if (recover) { + ane_fw_hung_recovered(b); + ane_fw_rpm_idle(b); + dev_info(&b->pdev->dev, "H17 ANE: quarantined engine recovered by system sleep\n"); } ane_h16_session_sleep(&b->session, false); /* genpd's record of the domain across this sleep (boot time, so it counts s2idle). */ @@ -1430,6 +1685,8 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void if (event == PM_SUSPEND_PREPARE) { WRITE_ONCE(b->in_sleep, true); WRITE_ONCE(b->session.wake_blocked, true); + /* A recovery under way finishes first; one not yet started is left to sleep. */ + cancel_work_sync(&b->recover); } if (event == PM_SUSPEND_PREPARE && retained) { struct device *dev = &b->pdev->dev; @@ -2334,6 +2591,7 @@ static const struct ane_h16_session_ops ane_fw_session_ops = { .sync = ane_fw_program_sync, .busy = ane_fw_program_busy, .wake = ane_fw_session_wake, + .hung = ane_fw_hung, }; /* @@ -2376,14 +2634,16 @@ static const struct file_operations ane_fw_execute_fops = { static void ane_fw_debugfs(struct ane_fw_backend *b) { - struct dentry *root = debugfs_lookup("ane-h17", NULL); + struct dentry *root = debugfs_lookup("ane-h17", NULL), *dir; bool found = root; if (!found) root = debugfs_create_dir("ane-h17", NULL); - debugfs_create_file("execute", 0600, - debugfs_create_dir(dev_name(&b->pdev->dev), root), - &b->session, &ane_fw_execute_fops); + dir = debugfs_create_dir(dev_name(&b->pdev->dev), root); + debugfs_create_file("execute", 0600, dir, &b->session, &ane_fw_execute_fops); + /* Hung-request recoveries (ane_fw_hung()), at runtime or by a sleep. */ + debugfs_create_u64("recoveries", 0400, dir, &b->recoveries); + debugfs_create_u64("recover_failures", 0400, dir, &b->recover_failures); if (found) dput(root); } @@ -2855,6 +3115,7 @@ int ane_fw_staged_init(struct platform_device *pdev, const struct ane_fw_platfor } dev_info(&pdev->dev, "H17 ANE: loader hand-off verified; starting the engine\n"); INIT_WORK(&b->start, ane_fw_start_work); + INIT_WORK(&b->recover, ane_fw_recover_work); return 0; fail: ane_fw_observer_free(b); @@ -2970,6 +3231,7 @@ bool ane_fw_staged_exit(void) if (!b) return false; cancel_work_sync(&b->start); + cancel_work_sync(&b->recover); /* A retained backend pins the module. No unload or in-place retry. */ if (WARN_ON(b->retained)) return true; diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index 83ee2dcb78901c..e47becd6e777a9 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -86,6 +86,36 @@ static inline bool ane_fw_cold_engine_restartable(const struct ane_fw_cold_state return true; } +/* ANE_SYS's actual power state (PMGR bits 7:4) reads off. */ +static inline bool ane_fw_sys_off(u32 sys) +{ + return !(sys & 0xf0); +} + +/* + * A session quarantined by a hung request, powered off under its firmware + * without a stop. down: our power-down of the quarantined engine began + * (ANE_SYS was still held by us then, so no earlier OFF counts); sys_off: + * genpd then reported ANE_SYS off with its PMGR actual state off; held: we + * hold ANE_SYS or the child power states again. + */ +struct ane_fw_hung_proof { + bool down, sys_off, held; +}; + +/* + * The old firmware is gone, and the memory it could reach (pool, IPC, heap, + * heap tail, DATA, programs closed while quarantined) may be reused, only + * when ANE_SYS really went off after our power-down and the ANE CPU and + * sub-block power states read off now (@pmgr, read from PMGR, which is + * readable in any power state). Anything less keeps the quarantine. + */ +static inline bool ane_fw_hung_gone(const struct ane_fw_hung_proof *p, + const struct ane_fw_cold_state *pmgr) +{ + return p->down && p->sys_off && !p->held && ane_fw_cold_pmgr_valid(pmgr, true); +} + /* * RVBAR (engine +0x1050000) and the TEXT entry: latched at TEXT (bit 0 set) * is ready; with bit 0 clear the entry may be written; latched at any other diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index cc6052dea2ca21..f4e9c9cece99cb 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -365,7 +365,53 @@ static void ane_cold_no_clpc_test(struct kunit *test) #endif } +/* + * Recovery of a hung engine reuses its memory only with the whole proof: our + * power-down began, ANE_SYS then went off as PMGR reads it, nothing is held + * again, and the ANE CPU and sub-block read off now. + */ +static void ane_cold_hung_gone_test(struct kunit *test) +{ + const struct ane_fw_hung_proof proven = { .down = true, .sys_off = true }; + struct ane_fw_cold_state off = ane_cold_fixture(), s; + struct ane_fw_hung_proof p; + + KUNIT_EXPECT_TRUE(test, ane_fw_sys_off(0x200)); + KUNIT_EXPECT_TRUE(test, ane_fw_sys_off(0x20f)); + KUNIT_EXPECT_FALSE(test, ane_fw_sys_off(0x23ff)); + KUNIT_EXPECT_FALSE(test, ane_fw_sys_off(0x10)); + + KUNIT_EXPECT_TRUE(test, ane_fw_hung_gone(&proven, &off)); + /* No power-down of ours, so an OFF proves nothing about the hung firmware. */ + p = proven; + p.down = false; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* ANE_SYS never reported off (runtime DARTs held it, or no genpd notifier). */ + p = proven; + p.sys_off = false; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* Powered again, or a reference still held. */ + p = proven; + p.held = true; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&p, &off)); + /* The ANE CPU power state targets or reads on. */ + s = off; + s.cpu |= 0xf; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + s = off; + s.cpu |= 0xf0; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + /* A sub-block word left on, or BUSY latched as a stuck power-down leaves it. */ + s = off; + s.subblock = 0x3ff; + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); + s = off; + s.subblock = 0x300 | BIT(11); + KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); +} + static struct kunit_case ane_cold_cases[] = { + KUNIT_CASE(ane_cold_hung_gone_test), KUNIT_CASE(ane_cold_no_clpc_test), KUNIT_CASE(ane_cold_restartable_test), KUNIT_CASE(ane_cold_rvbar_test), diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index a72ee6616f8d7a..b4a2555cd3a0bc 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -2142,6 +2142,66 @@ static void program_sleep_gate_test(struct kunit *test) mutex_unlock(lock); } +/* + * Closing the session for a park or a sleep releases a held gate. When that + * fails, the session is quarantined there and the backend told once, so a + * backend checks for the quarantine after closing (the H17 park and sleep + * do) and recovers it with a verified power cycle: the open program is + * replayed and runs again behind its handle. + */ +static void program_sleep_gate_quarantine_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + unsigned int replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + + /* + * The firmware takes nothing any more: the closing gate fails. The + * session lock is set only around the sleep gate, so no idle gate work + * outlives the test (as in program_gate_hold_test). + */ + f->t.armed = false; + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + KUNIT_EXPECT_TRUE(test, f->s.asleep); + KUNIT_EXPECT_FALSE(test, f->s.gate_held); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + /* Closed again while quarantined: no second report. */ + ane_h16_session_sleep(&f->s, false); + ane_h16_session_sleep(&f->s, true); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* Powered off, proven off, booted again from the preload. */ + f->t.armed = true; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + KUNIT_ASSERT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), 0); + KUNIT_EXPECT_EQ(test, replayed, 1U); + ane_h16_session_sleep(&f->s, false); + f->s.lock = NULL; + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + f->now += 1000; + KUNIT_EXPECT_EQ(test, ane_h16_session_gate_expire(&f->s), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + ane_h16_session_put(&f->s, p); + cancel_delayed_work_sync(&f->s.gate_work); +} + /* A program survives a sleep: the same handle executes afterwards. */ static void program_sleep_keeps_program_test(struct kunit *test) { @@ -3383,6 +3443,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_sleep_replay_failure_test), KUNIT_CASE(program_sleep_replay_deferred_test), KUNIT_CASE(program_sleep_gate_test), + KUNIT_CASE(program_sleep_gate_quarantine_test), KUNIT_CASE(program_sleep_keeps_program_test), KUNIT_CASE(program_sleep_restart_test), KUNIT_CASE(program_sleep_restart_deferred_test), From 00d223c6de6485188e7790e3ed21b6cb07585fe6 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Tue, 24 Nov 2026 00:26:54 +0100 Subject: [PATCH 0736/1514] accel/ane: h17: limit hung-engine recoveries Every runtime recovery of a quarantined H17 session powers the engine off under its firmware and boots it again, at once and as often as the session is quarantined. On the J700 a client that kept loading programs past the shared quota had its session quarantined again 0.6-1.2 s after each recovery: eight recoveries in six seconds, each a forced ANE_SYS power cycle, and right after the eighth the whole SoC locked up (no network, a hard reset needed). Single recoveries had worked all day. Limit them. The first recovery in a 60 s window runs at once; each later one in the window waits 1 s after the one before, twice that for every recovery already in the window, at most the window. A sixth hang within the window stops runtime recoveries: the engine stays quarantined, requests fail with -EIO and nothing reaches it, until a system sleep powers it off and boots it again (which also resets the limit). While a recovery waits out its backoff the session stays quarantined the same way; a sleep drops the waiting recovery and recovers the engine itself. Recoveries are logged with their place in the window, a backoff and the stop each once; debugfs recover_limited counts refused recoveries. The storm above would have recovered at 0, 1, 3, 7 and 15 s and stopped at its sixth hang. The limit is a pure state machine in ane_fw_cold.h. KUnit: the storm's timeline, backoff doubling and its cap, the sliding window, the burst bounds, a clock that went back, and reset. Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 97 +++++++++++++++++--- drivers/accel/ane/ane_fw_cold.h | 100 +++++++++++++++++++++ drivers/accel/ane/ane_fw_cold_test.c | 128 +++++++++++++++++++++++++++ 3 files changed, 313 insertions(+), 12 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index a7efd9a4220b14..76615c9c72d0ba 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -156,11 +156,13 @@ struct ane_fw_backend { * from then on genpd's next ANE_SYS OFF, with the PMGR actual state off, * sets hung_off (ane_fw_genpd_event()), the proof the firmware is gone. */ - struct work_struct recover; + struct delayed_work recover; bool hung_down, hung_off; + /* Runtime recoveries, limited (ane_fw_recover_admit()); under lock. */ + struct ane_fw_recover_limit recover_limit; /* A power-down outside a sleep: a stuck power word cannot wait for one. */ bool runtime_off; - u64 recoveries, recover_failures; + u64 recoveries, recover_failures, recover_limited; }; /* One ANE per SoC. The observer exists before platform driver registration: @@ -1210,12 +1212,61 @@ static void ane_fw_hung_recovered(struct ane_fw_backend *b) b->recoveries++; } +/* + * Runtime recovery limit (ane_fw_recover_admit()): at most five recoveries + * within a minute, backing off from 1 s (doubling each time) so a client that + * hangs the engine again right away cannot storm ANE_SYS power cycles. A sixth + * hang within the window leaves the engine quarantined until a system sleep. + */ +#define ANE_FW_RECOVER_BURST 5U +#define ANE_FW_RECOVER_WINDOW_S 60U +#define ANE_FW_RECOVER_BACKOFF_MS 1000U + +static const struct ane_fw_recover_policy ane_fw_recover_default = { + .burst = ANE_FW_RECOVER_BURST, + .window_ns = (u64)ANE_FW_RECOVER_WINDOW_S * NSEC_PER_SEC, + .backoff_ns = (u64)ANE_FW_RECOVER_BACKOFF_MS * NSEC_PER_MSEC, +}; + +/* + * Whether this recovery may run now. Called under b->lock; a recovery that + * must wait is queued again for then, with the session left quarantined + * (requests fail with -EIO meanwhile and nothing reaches the engine). + */ +static bool ane_fw_recover_admitted(struct ane_fw_backend *b, u64 now) +{ + bool tripped = b->recover_limit.tripped; + u64 wait; + + switch (ane_fw_recover_admit(&b->recover_limit, &ane_fw_recover_default, now, &wait)) { + case ANE_FW_RECOVER_NOW: + ane_fw_recover_note(&b->recover_limit, now); + return true; + case ANE_FW_RECOVER_LATER: + dev_warn(&b->pdev->dev, + "H17 ANE: hung again within %u s: recovery backs off %llu ms\n", + ANE_FW_RECOVER_WINDOW_S, div_u64(wait, NSEC_PER_MSEC)); + mod_delayed_work(system_dfl_wq, &b->recover, + nsecs_to_jiffies(wait) + 1); + return false; + case ANE_FW_RECOVER_STOP: + default: + b->recover_limited++; + if (!tripped) + dev_err(&b->pdev->dev, + "H17 ANE: %u recoveries within %u s: no more runtime recoveries; quarantined until the next system sleep\n", + ANE_FW_RECOVER_BURST, ANE_FW_RECOVER_WINDOW_S); + return false; + } +} + static void ane_fw_recover_work(struct work_struct *work) { - struct ane_fw_backend *b = container_of(work, struct ane_fw_backend, recover); + struct ane_fw_backend *b = container_of(to_delayed_work(work), struct ane_fw_backend, + recover); struct device *dev = &b->pdev->dev; bool rpm = ane_fw_rpm(b), held = false, reschedule = false; - u64 start = ktime_get_ns(); + u64 start, last; int ret; /* @@ -1236,6 +1287,9 @@ static void ane_fw_recover_work(struct work_struct *work) !READ_ONCE(b->in_sleep) && !b->session.quarantined; break; } + start = ktime_get_ns(); + if (!ane_fw_recover_admitted(b, ktime_get_boottime_ns())) + break; /* Closes admission: requests wait in ane_h16_session_enter() meanwhile. */ ane_h16_session_sleep(&b->session, true); /* @@ -1288,9 +1342,12 @@ static void ane_fw_recover_work(struct work_struct *work) } ane_h16_session_sleep(&b->session, false); dev_info(dev, - "H17 ANE: %s after a hung request in %llu ms, %u programs replayed\n", + "H17 ANE: %s after a hung request in %llu ms, %u programs replayed; recovery %u of %u within %u s\n", ret ? "recovery FAILED" : "firmware recovered", - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), b->resume_replayed); + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), b->resume_replayed, + ane_fw_recover_recent(&b->recover_limit, ktime_get_boottime_ns(), + ane_fw_recover_default.window_ns, &last), + ANE_FW_RECOVER_BURST, ANE_FW_RECOVER_WINDOW_S); } if (held) { if (reschedule) { @@ -1309,9 +1366,16 @@ static void ane_fw_hung(void *ctx, int error) if (READ_ONCE(b->in_sleep)) return; + if (READ_ONCE(b->recover_limit.tripped)) { + dev_warn(&b->pdev->dev, + "H17 ANE: session quarantined (%d); recovery limit reached, left quarantined\n", + error); + return; + } dev_warn(&b->pdev->dev, "H17 ANE: session quarantined (%d); restarting the engine\n", error); - queue_work(system_dfl_wq, &b->recover); + /* A recovery already waiting out its backoff keeps its time. */ + queue_delayed_work(system_dfl_wq, &b->recover, 0); } /* @@ -1601,6 +1665,8 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) } /* Stay off until a request needs the engine, as macOS does. */ if (b->soc->macos_sleep && !recover) { + /* Powered off for the sleep: runtime recoveries start counting afresh. */ + ane_fw_recover_reset(&b->recover_limit); WRITE_ONCE(b->parked, true); WRITE_ONCE(b->session.parked, true); dev_info(&b->pdev->dev, "H17 ANE: resume ok: parked until the next request\n"); @@ -1628,7 +1694,9 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) } else if (recover) { ane_fw_hung_recovered(b); ane_fw_rpm_idle(b); - dev_info(&b->pdev->dev, "H17 ANE: quarantined engine recovered by system sleep\n"); + dev_info(&b->pdev->dev, "H17 ANE: quarantined engine recovered by system sleep%s\n", + b->recover_limit.tripped ? "; recovery limit reset" : ""); + ane_fw_recover_reset(&b->recover_limit); } ane_h16_session_sleep(&b->session, false); /* genpd's record of the domain across this sleep (boot time, so it counts s2idle). */ @@ -1685,8 +1753,11 @@ static int ane_fw_pm_event(struct notifier_block *nb, unsigned long event, void if (event == PM_SUSPEND_PREPARE) { WRITE_ONCE(b->in_sleep, true); WRITE_ONCE(b->session.wake_blocked, true); - /* A recovery under way finishes first; one not yet started is left to sleep. */ - cancel_work_sync(&b->recover); + /* + * A recovery under way finishes first; one still waiting out its + * backoff is dropped: the sleep recovers the engine itself. + */ + cancel_delayed_work_sync(&b->recover); } if (event == PM_SUSPEND_PREPARE && retained) { struct device *dev = &b->pdev->dev; @@ -2644,6 +2715,8 @@ static void ane_fw_debugfs(struct ane_fw_backend *b) /* Hung-request recoveries (ane_fw_hung()), at runtime or by a sleep. */ debugfs_create_u64("recoveries", 0400, dir, &b->recoveries); debugfs_create_u64("recover_failures", 0400, dir, &b->recover_failures); + /* Recoveries refused by the limit (ane_fw_recover_admit()). */ + debugfs_create_u64("recover_limited", 0400, dir, &b->recover_limited); if (found) dput(root); } @@ -3115,7 +3188,7 @@ int ane_fw_staged_init(struct platform_device *pdev, const struct ane_fw_platfor } dev_info(&pdev->dev, "H17 ANE: loader hand-off verified; starting the engine\n"); INIT_WORK(&b->start, ane_fw_start_work); - INIT_WORK(&b->recover, ane_fw_recover_work); + INIT_DELAYED_WORK(&b->recover, ane_fw_recover_work); return 0; fail: ane_fw_observer_free(b); @@ -3231,7 +3304,7 @@ bool ane_fw_staged_exit(void) if (!b) return false; cancel_work_sync(&b->start); - cancel_work_sync(&b->recover); + cancel_delayed_work_sync(&b->recover); /* A retained backend pins the module. No unload or in-place retry. */ if (WARN_ON(b->retained)) return true; diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index e47becd6e777a9..b5d1279048900f 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -116,6 +116,106 @@ static inline bool ane_fw_hung_gone(const struct ane_fw_hung_proof *p, return p->down && p->sys_off && !p->held && ane_fw_cold_pmgr_valid(pmgr, true); } +/* + * Runtime recoveries of a hung engine are limited. Each one powers the + * engine off under its firmware and boots it again; a client that hangs it + * again right away turns that into a storm of power cycles, and eight of them + * within six seconds locked the whole SoC up on a J700. So: + * + * - the first recovery in @window_ns runs at once; each later one in the + * window waits @backoff_ns after the one before it, twice as long for each + * recovery already in the window, at most @window_ns; + * - a recovery that would be the (@burst + 1)th within @window_ns trips the + * limit: no more runtime recoveries, the engine stays quarantined until a + * system sleep powers it off and boots it again. + * + * Every attempt counts, failed or not, from when it starts. + */ +#define ANE_FW_RECOVER_BURST_MAX 16 + +struct ane_fw_recover_policy { + unsigned int burst; + u64 window_ns, backoff_ns; +}; + +struct ane_fw_recover_limit { + /* Start times of the latest attempts, a ring of count entries before next. */ + u64 at[ANE_FW_RECOVER_BURST_MAX]; + unsigned int next, count; + bool tripped; +}; + +enum ane_fw_recover_verdict { + ANE_FW_RECOVER_NOW, + ANE_FW_RECOVER_LATER, + ANE_FW_RECOVER_STOP, +}; + +/* Attempts that started less than @window_ns before @now, and the latest start. */ +static inline unsigned int ane_fw_recover_recent(const struct ane_fw_recover_limit *l, + u64 now, u64 window_ns, u64 *last) +{ + unsigned int i, recent = 0; + + *last = 0; + for (i = 0; i < l->count; i++) { + u64 at = l->at[(l->next + ANE_FW_RECOVER_BURST_MAX - 1 - i) % + ANE_FW_RECOVER_BURST_MAX]; + + if (at > now || now - at >= window_ns) + break; + if (!recent++) + *last = at; + } + return recent; +} + +/* + * May a recovery start at @now? LATER sets *@wait_ns, after which to ask + * again; STOP trips the limit, which stays tripped until + * ane_fw_recover_reset(). + */ +static inline enum ane_fw_recover_verdict +ane_fw_recover_admit(struct ane_fw_recover_limit *l, const struct ane_fw_recover_policy *p, + u64 now, u64 *wait_ns) +{ + unsigned int burst = clamp(p->burst, 1U, (unsigned int)ANE_FW_RECOVER_BURST_MAX); + u64 last, delay = p->backoff_ns; + unsigned int recent, i; + + *wait_ns = 0; + if (l->tripped) + return ANE_FW_RECOVER_STOP; + recent = ane_fw_recover_recent(l, now, p->window_ns, &last); + if (recent >= burst) { + l->tripped = true; + return ANE_FW_RECOVER_STOP; + } + if (!recent) + return ANE_FW_RECOVER_NOW; + for (i = 1; i < recent && delay < p->window_ns; i++) + delay *= 2; + delay = min(delay, p->window_ns); + if (now - last >= delay) + return ANE_FW_RECOVER_NOW; + *wait_ns = last + delay - now; + return ANE_FW_RECOVER_LATER; +} + +/* A recovery attempt starts at @now. */ +static inline void ane_fw_recover_note(struct ane_fw_recover_limit *l, u64 now) +{ + l->at[l->next] = now; + l->next = (l->next + 1) % ANE_FW_RECOVER_BURST_MAX; + if (l->count < ANE_FW_RECOVER_BURST_MAX) + l->count++; +} + +static inline void ane_fw_recover_reset(struct ane_fw_recover_limit *l) +{ + memset(l, 0, sizeof(*l)); +} + /* * RVBAR (engine +0x1050000) and the TEXT entry: latched at TEXT (bit 0 set) * is ready; with bit 0 clear the entry may be written; latched at any other diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index f4e9c9cece99cb..465fcd2d1c3932 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -410,7 +410,135 @@ static void ane_cold_hung_gone_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, ane_fw_hung_gone(&proven, &s)); } +#define REC_S(x) ((u64)(x) * NSEC_PER_SEC) +#define REC_MS(x) ((u64)(x) * NSEC_PER_MSEC) + +/* Ask at @now and, when admitted, start the attempt then (as the recover work does). */ +static enum ane_fw_recover_verdict rec_try(struct ane_fw_recover_limit *l, + const struct ane_fw_recover_policy *p, + u64 now, u64 *wait) +{ + enum ane_fw_recover_verdict v = ane_fw_recover_admit(l, p, now, wait); + + if (v == ANE_FW_RECOVER_NOW) + ane_fw_recover_note(l, now); + return v; +} + +/* + * A storm of hangs (0.6 s after each recovery): with the policy (5 in 60 s, + * 1 s backoff) the recoveries spread out to 0, 1, 3, 7 and 15 s, and the + * sixth hang stops them until a system sleep resets the limit. + */ +static void ane_cold_recover_storm_test(struct kunit *test) +{ + const struct ane_fw_recover_policy p = { + .burst = 5, .window_ns = REC_S(60), .backoff_ns = REC_S(1), + }; + static const u64 expect[] = { 0, 1, 3, 7, 15 }; + struct ane_fw_recover_limit l = {}; + u64 now = REC_S(100), wait, started[ARRAY_SIZE(expect)]; + unsigned int done = 0, refused = 0; + + /* Hang 0.6 s after each recovery; a refused one is asked again when told. */ + while (done < ARRAY_SIZE(expect)) { + enum ane_fw_recover_verdict v = rec_try(&l, &p, now, &wait); + + KUNIT_ASSERT_NE(test, v, ANE_FW_RECOVER_STOP); + if (v == ANE_FW_RECOVER_LATER) { + KUNIT_ASSERT_GT(test, wait, 0ULL); + refused++; + now += wait; + continue; + } + started[done++] = now; + now += REC_MS(600); + } + for (unsigned int i = 0; i < ARRAY_SIZE(expect); i++) + KUNIT_EXPECT_EQ(test, started[i] - started[0], REC_S(expect[i])); + KUNIT_EXPECT_EQ(test, refused, 4U); + /* The sixth hang within the minute trips the limit, and it stays tripped. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_STOP); + KUNIT_EXPECT_TRUE(test, l.tripped); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3600), &wait), ANE_FW_RECOVER_STOP); + KUNIT_EXPECT_EQ(test, wait, 0ULL); + /* A system sleep clears it: the next one runs at once. */ + ane_fw_recover_reset(&l); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3601), &wait), ANE_FW_RECOVER_NOW); +} + +/* Backoff doubling, its cap, the sliding window and the burst bounds. */ +static void ane_cold_recover_backoff_test(struct kunit *test) +{ + struct ane_fw_recover_policy p = { + .burst = 16, .window_ns = REC_S(10), .backoff_ns = REC_S(1), + }; + struct ane_fw_recover_limit l = {}; + u64 now = REC_S(1), wait; + + /* First in the window: at once. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, wait, 0ULL); + /* Second: 1 s after the first; asked 0.25 s after it, wait 0.75 s. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_MS(250), &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_MS(750)); + now += REC_S(1); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + /* Third: 2 s after the second; fourth: 4 s; fifth: capped at the window. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(2)); + now += REC_S(2); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(4)); + now += REC_S(4); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + /* Started at 0, 1, 3 and 7 s; at 7 s all four are in the 10 s window. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(8)); + /* At 10 s the first has left the window: three recent, 4 s after the latest. */ + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + REC_S(3), &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(1)); + /* At 11 s the first two have: two recent, 2 s after the latest, due. */ + now += REC_S(4); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_FALSE(test, l.tripped); + /* Quiet for a whole window: no backoff at all. */ + now += REC_S(10); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + + /* Delays never exceed the window, whatever the backoff. */ + ane_fw_recover_reset(&l); + p.backoff_ns = REC_S(60); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_LATER); + KUNIT_EXPECT_EQ(test, wait, REC_S(10)); + + /* No backoff: only the burst limits. A burst of 0 counts as 1. */ + ane_fw_recover_reset(&l); + p.backoff_ns = 0; + p.burst = 0; + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + 1, &wait), ANE_FW_RECOVER_STOP); + + /* A burst above the ring is the ring: 16 at once, the 17th stops. */ + ane_fw_recover_reset(&l); + p.burst = 100; + for (unsigned int i = 0; i < ANE_FW_RECOVER_BURST_MAX; i++) + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + i, &wait), ANE_FW_RECOVER_NOW); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now + 16, &wait), ANE_FW_RECOVER_STOP); + + /* A clock that went back (a stamp after now) is not counted as recent. */ + ane_fw_recover_reset(&l); + p.burst = 2; + p.backoff_ns = REC_S(1); + ane_fw_recover_note(&l, now + REC_S(5)); + KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); +} + static struct kunit_case ane_cold_cases[] = { + KUNIT_CASE(ane_cold_recover_storm_test), + KUNIT_CASE(ane_cold_recover_backoff_test), KUNIT_CASE(ane_cold_hung_gone_test), KUNIT_CASE(ane_cold_no_clpc_test), KUNIT_CASE(ane_cold_restartable_test), From 1c42437392bbaf28e650794c9ca8259ca58e29cc Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Tue, 24 Nov 2026 00:27:37 +0100 Subject: [PATCH 0737/1514] accel/ane: h17: keep a hung engine off before booting it again A runtime recovery booted the engine again as soon as genpd reported ANE_SYS off: the proof was followed by the cold boot's power-up at once, so the domain stayed off for about a millisecond. Every other power cycle of this engine keeps it off for seconds (an idle park for at least its autosuspend delay, a system sleep for the whole sleep). On the J700 a storm of eight such recoveries in six seconds, each with ANE_SYS back on within a millisecond, ended in a SoC lockup. Record when genpd's OFF proved the hung engine gone and keep ANE_SYS off for 100 ms from then before the proof is checked and the engine booted again. The recovery log line gives the time waited. KUnit: the wait from the OFF, with no OFF recorded, one in the future, and no minimum. Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 44 ++++++++++++++++++++++++---- drivers/accel/ane/ane_fw_cold.h | 12 ++++++++ drivers/accel/ane/ane_fw_cold_test.c | 20 +++++++++++++ 3 files changed, 71 insertions(+), 5 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 76615c9c72d0ba..b64e624820009f 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -158,6 +159,8 @@ struct ane_fw_backend { */ struct delayed_work recover; bool hung_down, hung_off; + /* Boot time of the OFF that set hung_off. */ + u64 hung_off_at; /* Runtime recoveries, limited (ane_fw_recover_admit()); under lock. */ struct ane_fw_recover_limit recover_limit; /* A power-down outside a sleep: a stuck power word cannot wait for one. */ @@ -1204,6 +1207,28 @@ static bool ane_fw_hung_wait_off(struct ane_fw_backend *b) return READ_ONCE(b->hung_off); } +#define ANE_FW_RECOVER_OFF_MS 100U + +/* + * A recovery used to power ANE_SYS on again within about a millisecond of + * genpd turning it off: the cold boot's power-up followed the proof at once. + * Every other power cycle of the engine (idle park, system sleep) keeps it + * off for seconds. Keep it off for ANE_FW_RECOVER_OFF_MS; returns the ms + * waited. + */ +static unsigned int ane_fw_hung_stay_off(struct ane_fw_backend *b) +{ + u64 min_ns = (u64)ANE_FW_RECOVER_OFF_MS * NSEC_PER_MSEC; + /* Acquire: pairs with the release in ane_fw_genpd_event(), after hung_off_at. */ + u64 off_at = smp_load_acquire(&b->hung_off) ? READ_ONCE(b->hung_off_at) : 0; + u64 wait = ane_fw_recover_off_wait(off_at, ktime_get_boottime_ns(), min_ns); + unsigned int ms = DIV_ROUND_UP_ULL(wait, NSEC_PER_MSEC); + + if (ms) + msleep(ms); + return ms; +} + /* The new firmware is up: the next hang starts its proof afresh. */ static void ane_fw_hung_recovered(struct ane_fw_backend *b) { @@ -1266,6 +1291,7 @@ static void ane_fw_recover_work(struct work_struct *work) recover); struct device *dev = &b->pdev->dev; bool rpm = ane_fw_rpm(b), held = false, reschedule = false; + unsigned int off = 0; u64 start, last; int ret; @@ -1316,6 +1342,8 @@ static void ane_fw_recover_work(struct work_struct *work) ret = ane_fw_hung_down(b, true); if (!ret && !ane_fw_hung_wait_off(b)) ret = -ETIMEDOUT; + if (!ret) + off = ane_fw_hung_stay_off(b); if (!ret && !ane_fw_hung_proven(b)) ret = -EIO; if (ret) { @@ -1342,9 +1370,9 @@ static void ane_fw_recover_work(struct work_struct *work) } ane_h16_session_sleep(&b->session, false); dev_info(dev, - "H17 ANE: %s after a hung request in %llu ms, %u programs replayed; recovery %u of %u within %u s\n", + "H17 ANE: %s after a hung request in %llu ms (off %u ms), %u programs replayed; recovery %u of %u within %u s\n", ret ? "recovery FAILED" : "firmware recovered", - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), b->resume_replayed, + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), off, b->resume_replayed, ane_fw_recover_recent(&b->recover_limit, ktime_get_boottime_ns(), ane_fw_recover_default.window_ns, &last), ANE_FW_RECOVER_BURST, ANE_FW_RECOVER_WINDOW_S); @@ -1628,9 +1656,15 @@ static int ane_fw_genpd_event(struct notifier_block *nb, unsigned long action, v b->sys_offs++; b->sys_off_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); b->sys_off_at = now; - /* After a hung engine's power-down: the proof it is gone. */ - if (smp_load_acquire(&b->hung_down) && ane_fw_sys_off(b->sys_off_pmgr)) - WRITE_ONCE(b->hung_off, true); + /* + * After a hung engine's power-down (acquire: pairs with the release in + * ane_fw_hung_down()): the proof it is gone. + */ + if (smp_load_acquire(&b->hung_down) && ane_fw_sys_off(b->sys_off_pmgr)) { + WRITE_ONCE(b->hung_off_at, now); + /* hung_off_at is read after hung_off (ane_fw_hung_stay_off()). */ + smp_store_release(&b->hung_off, true); + } } else if (action == GENPD_NOTIFY_ON) { b->sys_ons++; b->sys_on_pmgr = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index b5d1279048900f..b38e8793b49087 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -116,6 +116,18 @@ static inline bool ane_fw_hung_gone(const struct ane_fw_hung_proof *p, return p->down && p->sys_off && !p->held && ane_fw_cold_pmgr_valid(pmgr, true); } +/* + * How long a recovery still keeps ANE_SYS off, @min_ns from the OFF at + * @off_at (boot time) given @now: the whole of it when the OFF time is + * unknown or lies ahead. + */ +static inline u64 ane_fw_recover_off_wait(u64 off_at, u64 now, u64 min_ns) +{ + if (!off_at || now < off_at) + return min_ns; + return now - off_at >= min_ns ? 0 : min_ns - (now - off_at); +} + /* * Runtime recoveries of a hung engine are limited. Each one powers the * engine off under its firmware and boots it again; a client that hangs it diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index 465fcd2d1c3932..e68e601fdce070 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -536,7 +536,27 @@ static void ane_cold_recover_backoff_test(struct kunit *test) KUNIT_EXPECT_EQ(test, rec_try(&l, &p, now, &wait), ANE_FW_RECOVER_NOW); } +/* A recovery keeps ANE_SYS off for its minimum, counted from genpd's OFF. */ +static void ane_cold_recover_off_test(struct kunit *test) +{ + const u64 min = 100 * NSEC_PER_MSEC, off = 5 * NSEC_PER_SEC; + + /* The storm's recoveries powered up again within about a millisecond. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + NSEC_PER_MSEC, min), + 99 * NSEC_PER_MSEC); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off, min), min); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + min, min), 0ULL); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off + NSEC_PER_SEC, min), 0ULL); + /* No OFF recorded, or one in the future: wait the whole minimum. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(0, off, min), min); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off - 1, min), min); + /* No minimum: never wait. */ + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(off, off, 0), 0ULL); + KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(0, off, 0), 0ULL); +} + static struct kunit_case ane_cold_cases[] = { + KUNIT_CASE(ane_cold_recover_off_test), KUNIT_CASE(ane_cold_recover_storm_test), KUNIT_CASE(ane_cold_recover_backoff_test), KUNIT_CASE(ane_cold_hung_gone_test), From 3963bf32061eeadc813163dee370cdf80ae51348 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Tue, 24 Nov 2026 00:28:28 +0100 Subject: [PATCH 0738/1514] accel/ane: h17: let a recovered engine settle before requests After a recovery's cold boot the session reopened at once: open programs were replayed and waiting requests went in right after the firmware's startup commands, with nothing checked of the engine the power cycle left behind. On the J700, after the eighth recovery of a storm a waiting client sent LOAD and CREATE within a millisecond of the reopen; its log ends at the third LOAD, where the SoC locked up. Before the replay and before the session reopens, serve what the new firmware posts (its own SHAREDMALLOCs) until it has been quiet for 100 ms (at most a second more), then read the engine: ANE_SYS and the ANE CPU power state on, no DART fault, and the transport not failed. The sub-block power state and CE are not judged: the running firmware gates the engine itself. Requests wait in ane_h16_session_enter() meanwhile, as during the rest of the recovery. An engine that reads anything else fails the recovery and is quarantined, with what it read logged. A system sleep that recovers a quarantined engine takes the same step. KUnit: the health check, field by field; and at the session level, what the gating relies on: while a recovery waits out its backoff the quarantined session refuses requests with -EIO and no traffic; while it runs, a client's LOAD waits, also through the cold boot and the replay, and goes through on the new firmware only once the session reopens. Signed-off-by: Bartosz Nitka --- drivers/accel/ane/ane_fw_cold.c | 42 +++++++ drivers/accel/ane/ane_fw_cold.h | 27 ++++ drivers/accel/ane/ane_fw_cold_test.c | 33 +++++ drivers/accel/ane/ane_h16_program_test.c | 151 +++++++++++++++++++++++ 4 files changed, 253 insertions(+) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index b64e624820009f..3b2e98e7ac0c89 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -783,6 +783,42 @@ static int ane_fw_reload_segment(struct ane_fw_backend *b, unsigned int i) -EKEYREJECTED : 0; } +#define ANE_FW_RECOVER_QUIET_MS 100U + +/* + * A recovered engine takes requests only once it has settled: the new + * firmware has posted nothing for ANE_FW_RECOVER_QUIET_MS (what it posts + * meanwhile, such as its own SHAREDMALLOCs, is served), and its power, DARTs + * and transport read healthy (ane_fw_recover_settled()). Until then the + * session stays closed: the replay waits, and requests wait in + * ane_h16_session_enter(). + */ +static int ane_fw_recover_settle(struct ane_fw_backend *b) +{ + struct ane_fw_settled st = {}; + u64 start = ktime_get_ns(); + int served; + + served = ane_fw_transport_settle(&b->transport, + (u64)ANE_FW_RECOVER_QUIET_MS * NSEC_PER_MSEC, + ((u64)ANE_FW_RECOVER_QUIET_MS + 1000) * NSEC_PER_MSEC); + st.transport_error = served < 0 ? served : b->transport.error; + st.sys = ane_rd32(b, b->pmgr + b->soc->pmgr_sys); + st.cpu = ane_rd32(b, b->pmgr + b->soc->pmgr_cpu); + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) + st.dart_error[i] = ane_rd32(b, b->dart[i] + 0x100); + if (!ane_fw_recover_settled(&st)) { + dev_err(&b->pdev->dev, + "H17 ANE: recovered engine not settled: transport %d, ANE_SYS %#x CPU %#x, DART errors %#x %#x %#x\n", + st.transport_error, st.sys, st.cpu, st.dart_error[0], st.dart_error[1], + st.dart_error[2]); + return st.transport_error ?: -EIO; + } + dev_dbg(&b->pdev->dev, "H17 ANE: recovered engine settled in %llu ms, %d posts served\n", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), served); + return 0; +} + /* * After resume, the cold way: power up from the cold state with the same * checks as at boot (the engine and DARTs must read their reset values), @@ -855,6 +891,12 @@ static int ane_fw_cold_cycle_boot(struct ane_fw_backend *b, bool recover) if (ret) return ret; b->transport.allow_free = true; + /* Nothing reaches a recovered engine before it settled, the replay included. */ + if (recover) { + ret = ane_fw_recover_settle(b); + if (ret) + return ret; + } b->resume_ready_ns = ktime_get_ns(); dev_dbg(dev, "H17 ANE: booted again from the preload after system sleep in %llu ms\n", div_u64(b->resume_ready_ns - start, NSEC_PER_MSEC)); diff --git a/drivers/accel/ane/ane_fw_cold.h b/drivers/accel/ane/ane_fw_cold.h index b38e8793b49087..10cc760ef29453 100644 --- a/drivers/accel/ane/ane_fw_cold.h +++ b/drivers/accel/ane/ane_fw_cold.h @@ -128,6 +128,33 @@ static inline u64 ane_fw_recover_off_wait(u64 off_at, u64 now, u64 min_ns) return now - off_at >= min_ns ? 0 : min_ns - (now - off_at); } +/* + * After a recovery's cold boot, before any request (the replay of open + * programs included) reaches the new firmware: ANE_SYS and the ANE CPU power + * state still target and read on, no DART reports a fault, and the + * transport, after serving what the firmware posted while it went quiet, has + * not failed. Anything less fails the recovery. The sub-block power state and + * CE are left to the firmware once it runs (it gates the engine itself), so + * they are not judged. + */ +struct ane_fw_settled { + u32 sys, cpu; + u32 dart_error[ANE_FW_DARTS]; + int transport_error; +}; + +static inline bool ane_fw_recover_settled(const struct ane_fw_settled *s) +{ + unsigned int i; + + if ((s->sys & 0xff) != 0xff || (s->cpu & 0xff) != 0xff || s->transport_error) + return false; + for (i = 0; i < ANE_FW_DARTS; i++) + if (s->dart_error[i]) + return false; + return true; +} + /* * Runtime recoveries of a hung engine are limited. Each one powers the * engine off under its firmware and boots it again; a client that hangs it diff --git a/drivers/accel/ane/ane_fw_cold_test.c b/drivers/accel/ane/ane_fw_cold_test.c index e68e601fdce070..8aa8b3949dfcde 100644 --- a/drivers/accel/ane/ane_fw_cold_test.c +++ b/drivers/accel/ane/ane_fw_cold_test.c @@ -555,7 +555,40 @@ static void ane_cold_recover_off_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_fw_recover_off_wait(0, off, 0), 0ULL); } +/* A recovered engine takes requests only with everything reading healthy. */ +static void ane_cold_recover_settled_test(struct kunit *test) +{ + const struct ane_fw_settled up = { .sys = 0x23ff, .cpu = 0x0f0003ff }; + struct ane_fw_settled s; + + KUNIT_EXPECT_TRUE(test, ane_fw_recover_settled(&up)); + /* ANE_SYS or the CPU not (yet) on, in target or actual state. */ + s = up; + s.sys = 0x230f; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.sys = 0x23f0; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.cpu = 0x0f0003f0; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + s = up; + s.cpu = 0x0f000300; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + /* A DART fault on any of the three. */ + for (unsigned int i = 0; i < ANE_FW_DARTS; i++) { + s = up; + s.dart_error[i] = 0x80000001; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); + } + /* The transport failed while serving the new firmware's posts. */ + s = up; + s.transport_error = -ENOSPC; + KUNIT_EXPECT_FALSE(test, ane_fw_recover_settled(&s)); +} + static struct kunit_case ane_cold_cases[] = { + KUNIT_CASE(ane_cold_recover_settled_test), KUNIT_CASE(ane_cold_recover_off_test), KUNIT_CASE(ane_cold_recover_storm_test), KUNIT_CASE(ane_cold_recover_backoff_test), diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index b4a2555cd3a0bc..ad746c14c7fa8a 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -3415,6 +3415,156 @@ static void program_unmap_refused_load_test(struct kunit *test) KUNIT_EXPECT_EQ(test, fw_cycle(f), 0); } +/* A LOAD that comes in while the backend recovers the engine, as a client does. */ +struct recover_client { + struct prog_fw *f; + /* The session lock, kept here: the test clears f->s.lock before the end. */ + struct mutex *lock; + struct ane_h16_hwx_snapshot *snapshot; + struct ane_h16_program *program; + struct task_struct *task; + struct completion entered, done; + int enter, load; + /* Firmware commands seen when the request got in. */ + unsigned int sent_at_entry; +}; + +static int recover_client_run(void *arg) +{ + struct recover_client *c = arg; + struct ane_h16_session *s = &c->f->s; + + complete(&c->entered); + c->enter = ane_h16_session_enter(s, false); + if (!c->enter) { + c->sent_at_entry = c->f->count; + c->load = fw_load_snapshot(c->f, c->snapshot, &c->program); + mutex_unlock(s->lock); + } + complete(&c->done); + set_current_state(TASK_INTERRUPTIBLE); + while (!kthread_should_stop()) { + schedule(); + set_current_state(TASK_INTERRUPTIBLE); + } + __set_current_state(TASK_RUNNING); + return 0; +} + +/* Also after a failed assertion: let a waiting client in, then stop it. */ +static void recover_client_stop(void *arg) +{ + struct recover_client *c = arg; + struct ane_h16_session *s = &c->f->s; + + mutex_lock(c->lock); + s->asleep = false; + wake_up_all(&s->wake); + mutex_unlock(c->lock); + kthread_stop(c->task); + cancel_delayed_work_sync(&s->gate_work); +} + +/* + * What the H17 recovery relies on to keep requests off an engine that is + * not back yet. While a recovery waits out its backoff, the quarantined + * session refuses requests with -EIO and nothing reaches the firmware. + * While the recovery runs (session closed), a request waits in + * ane_h16_session_enter(): nothing is sent before the backend reopens the + * session, which it does only after the cold boot, the settle and the + * replay; then the request runs on the new firmware. + */ +static void program_recover_gate_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL, *q = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + struct recover_client *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + unsigned int sent, replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + KUNIT_ASSERT_NOT_NULL(test, c); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + + /* The engine stops answering: quarantined, the backend told once. */ + f->t.armed = false; + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + ane_h16_session_sleep(&f->s, false); + KUNIT_ASSERT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* Backoff: open but quarantined. Requests fail at once, with no traffic. */ + sent = f->count; + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, fw_load_program(f, &q), -EIO); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), -EIO); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, f->count, sent); + KUNIT_EXPECT_NULL(test, q); + + /* The recovery closes the session; a client's LOAD comes in and waits. */ + ane_h16_session_sleep(&f->s, true); + c->f = f; + c->lock = lock; + c->snapshot = fw_snapshot(test, false, false); + KUNIT_ASSERT_NOT_NULL(test, c->snapshot); + init_completion(&c->entered); + init_completion(&c->done); + c->task = kthread_run(recover_client_run, c, "ane-recover-client"); + KUNIT_ASSERT_FALSE(test, IS_ERR(c->task)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, recover_client_stop, c), 0); + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&c->entered, HZ) > 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_enter(&f->s, true), -EAGAIN); + + /* Powered off, kept off, booted again: still closed, the client waits. */ + f->t.armed = true; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + KUNIT_EXPECT_EQ(test, wait_for_completion_timeout(&c->done, HZ / 10), 0UL); + /* The replay is the first traffic on the new firmware. */ + KUNIT_ASSERT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), 0); + KUNIT_EXPECT_EQ(test, replayed, 1U); + KUNIT_EXPECT_EQ(test, wait_for_completion_timeout(&c->done, HZ / 10), 0UL); + sent = f->count; + + /* Settled: the backend reopens the session and the LOAD goes through. */ + ane_h16_session_sleep(&f->s, false); + KUNIT_ASSERT_TRUE(test, wait_for_completion_timeout(&c->done, 5 * HZ) > 0); + KUNIT_EXPECT_EQ(test, c->enter, 0); + KUNIT_EXPECT_EQ(test, c->sent_at_entry, sent); + KUNIT_EXPECT_EQ(test, c->load, 0); + KUNIT_EXPECT_GT(test, f->count, sent); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + + /* + * Both the replayed program and the new one run on the new firmware. + * The session lock is dropped first, so no idle gate work outlives + * the test (as in program_sleep_gate_quarantine_test). + */ + f->s.lock = NULL; + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + if (c->program) + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, c->program), 0); + f->now += 1000; + KUNIT_EXPECT_EQ(test, ane_h16_session_gate_expire(&f->s), 0); + if (c->program) { + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, c->program), 0); + ane_h16_session_put(&f->s, c->program); + } + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + ane_h16_session_put(&f->s, p); +} + static struct kunit_case program_cases[] = { KUNIT_CASE_SLOW(program_pool_rewind_test), KUNIT_CASE_SLOW(program_pool_resident_test), @@ -3444,6 +3594,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_sleep_replay_deferred_test), KUNIT_CASE(program_sleep_gate_test), KUNIT_CASE(program_sleep_gate_quarantine_test), + KUNIT_CASE(program_recover_gate_test), KUNIT_CASE(program_sleep_keeps_program_test), KUNIT_CASE(program_sleep_restart_test), KUNIT_CASE(program_sleep_restart_deferred_test), From 471dc3cf21bda561a2f4cc99ada17cc8ad0ed60e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 14:00:19 +1100 Subject: [PATCH 0739/1514] drm/asahi: G14 firmware 27.2: set the compute start word the 13.5 path sets The 27.2 G14 compute start operation keeps the 13.5 G14 StartCompute positions for its pointers (unk_pointer +0x04, job parameters +0x0c, stats +0x14, queue +0x1c, VM slot +0x24), and its +0x28 word is at the place of 13.5's unk_28. The 13.5 path always writes 1 there (queue/compute.rs); this one wrote 0. With 0, an integer dot-product kernel and a maximum threadgroup-memory dispatch never retire, and the GPU is unusable until reboot. Write 1, as 13.5 does. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 8db6c0ded49fde..0ce309d51dc768 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -119,6 +119,8 @@ fn encode_compute( put64(cmd, 0x334, timestamps + 0x20); put32(stream, 0, 11); + // 13.5 StartCompute.unk_28, at the same place in this layout (the 13.5 G14 path writes 1). + put32(stream, 0x28, 1); put64(stream, 0x160, job.sequence); put64(stream, 0x04, cmd_va + 0x18); put64(stream, 0x0c, cmd_va + 0x68); From cb9cf343bc5db45ea38b90e0b890b827828c21a0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 21:25:53 +1100 Subject: [PATCH 0740/1514] drm/asahi: submit paired tiler and fragment work through G14 firmware The G14 firmware 27.2 runtime refused render commands and reported the device compute-only. Render work needs a tiler and a fragment command that the firmware runs on separate engines and that share one scene. Keep the firmware root and compute bootstrap as they are. Stage both work rings before a render is published, keep its scene and VM binding until both engines retire, and let one DRM packet continue across compute and render commands. Keep the parameter-buffer bindings across render passes and answer the firmware's growth requests only after the new backing blocks are published. The render path reuses the common submission carrier and UAPI parser with the G14 queue and event layouts, so the device no longer reports itself compute-only. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/Kconfig | 6 +- drivers/gpu/drm/asahi/asahi_core.rs | 4 + drivers/gpu/drm/asahi/buffer.rs | 69 +- drivers/gpu/drm/asahi/g14_v27_2.rs | 391 +++++--- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 151 +++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 1021 +++++++++++++++++++++ drivers/gpu/drm/asahi/gpu/v27_2.rs | 382 ++++++-- drivers/gpu/drm/asahi/m3/m3_submit.rs | 27 +- drivers/gpu/drm/asahi/m3/mod.rs | 4 +- drivers/gpu/drm/asahi/queue/render.rs | 2 +- 10 files changed, 1863 insertions(+), 194 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g14_v27_2_abi.rs create mode 100644 drivers/gpu/drm/asahi/g14_v27_2_render.rs diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index c4402190207791..8a3a65597b65d4 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -96,15 +96,15 @@ config DRM_ASAHI_M3_T8122 are not affected. config DRM_ASAHI_G14_V27_2 - bool "Apple M2 (G14G) on GPU firmware 27.2, compute only" + bool "Apple G14G on GPU firmware 27.2" depends on DRM_ASAHI # The firmware's UAT is adopted through the G15 backend's handoff helpers. depends on DRM_ASAHI_G15 default y help Start an M2 GPU (G14G) whose boot loader reports GPU firmware - 27.2, and register a compute-only DRM device on it. Clients use - the 26.x submission interface; render commands are refused. + 27.2, and register a DRM device on it. Clients use + the shared submission interface for compute and rendering. Other GPUs and firmware versions are not affected. config DRM_ASAHI_G15 diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index e0de39368342d6..3671bf0d20e304 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -29,6 +29,10 @@ mod m5; mod gpu; #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod g14_v27_2; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod g14_v27_2_abi; +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +mod g14_v27_2_render; mod hw; mod initdata; mod m3; diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 314087edcd3a9f..a1d7fdd486b989 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -289,6 +289,50 @@ impl Drop for Scene::ver { } } +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl SceneG14V13_5 { + pub(crate) fn render_addresses(&self) -> (u64, u64) { + self.object.with(|raw, _| (raw.user_buffer.or(0).into(), raw.stats.into())) + } +} + +/// Host-owned parameter-buffer inputs that persist across firmware submissions. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) struct ParameterBufferInfo { + pub(crate) page_list: u64, + pub(crate) page_list_size: u32, + pub(crate) max_blocks: u32, + pub(crate) block_list: u64, + pub(crate) block_control: u64, + pub(crate) block_size: u32, + pub(crate) counter: u64, + pub(crate) max_pages: u32, + pub(crate) max_linear_pages: u32, +} + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +impl BufferG14V13_5 { + pub(crate) fn parameter_info(&self) -> ParameterBufferInfo { + self.inner.lock().info.with(|raw, inner| ParameterBufferInfo { + page_list: inner.page_list.gpu_va().get(), + page_list_size: raw.page_list_size, + max_blocks: raw.max_blocks, + block_list: inner.block_list.gpu_va().get(), + block_control: inner.block_ctl.gpu_va().get(), + block_size: raw.block_size, + counter: inner.counter.gpu_va().get(), + max_pages: raw.max_pages, + max_linear_pages: raw.max_pages_nomemless, + }) + } + + /// The 27.2 firmware owns the page list once bound. Publish only new block descriptors + /// and the block-control producer, using the legacy manager for backing allocation. + pub(crate) fn ensure_parameter_blocks(&self, count: usize) -> Result { + self.ensure_blocks_inner(count, false, true) + } +} + /// Inner data for a single TVB buffer object. #[versions(AGX)] struct BufferInner { @@ -486,16 +530,18 @@ impl Buffer::ver { /// The buffer manager owns the buffer while scenes on it are in flight, so the new size is only /// published if no scene is active. pub(crate) fn ensure_blocks(&self, min_blocks: usize) -> Result { - self.ensure_blocks_inner(min_blocks, false) + self.ensure_blocks_inner(min_blocks, false, false) } /// [`Self::ensure_blocks`] for a caller that guarantees all work that used this buffer has /// completed: the new size is published although scenes of completed jobs may still be held. pub(crate) fn ensure_blocks_idle(&self, min_blocks: usize) -> Result { - self.ensure_blocks_inner(min_blocks, true) + self.ensure_blocks_inner(min_blocks, true, false) } - fn ensure_blocks_inner(&self, min_blocks: usize, fw_idle: bool) -> Result { + fn ensure_blocks_inner( + &self, min_blocks: usize, fw_idle: bool, firmware_pages: bool, + ) -> Result { let mut inner = self.inner.lock(); let cur_count = inner.blocks.len(); @@ -529,18 +575,29 @@ impl Buffer::ver { .push(block, GFP_KERNEL) .expect("push() failed after reserve()"); inner.info.block_list[2 * (cur_count + i)] = page_num; - for j in 0..PAGES_PER_BLOCK { - inner.info.page_list[(cur_count + i) * PAGES_PER_BLOCK + j] = page_num + j as u32; + if !firmware_pages { + for j in 0..PAGES_PER_BLOCK { + inner.info.page_list[(cur_count + i) * PAGES_PER_BLOCK + j] = page_num + j as u32; + } } } + if firmware_pages { + let added = &inner.info.block_list.as_slice()[2 * cur_count..2 * new_count]; + crate::pgtable::clean_poc(added.as_ptr().cast(), core::mem::size_of_val(added)); + crate::pgtable::poc_barrier(); + } inner.info.block_ctl.with(|raw, _inner| { raw.total.store(new_count as u32, Ordering::SeqCst); raw.wptr.store(new_count as u32, Ordering::SeqCst); + if firmware_pages { + crate::pgtable::clean_poc(core::ptr::from_ref(raw).cast(), core::mem::size_of_val(raw)); + crate::pgtable::poc_barrier(); + } }); /* Only do this update if the buffer manager is idle (which means we own it) */ - if inner.active_scenes == 0 || fw_idle { + if !firmware_pages && (inner.active_scenes == 0 || fw_idle) { let page_count = (new_count * PAGES_PER_BLOCK) as u32; inner.info.with(|raw, _inner| { raw.page_count.store(page_count, Ordering::Relaxed); diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 1f6b8a0359b35c..6879bfaa952f2f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1,13 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! G14 GPUs on GPU firmware 27.2: start the firmware and run compute work on it. +//! G14 GPU firmware boot, submission and retirement. //! //! [`start`] builds the 27.2 root (`gpu/v27_2.rs`) on the records of a 13.5 G14 manager, //! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the //! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients -//! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the -//! 27.2 layout and published, in order, on the root's queue. Render commands are refused, and the device -//! reports `DRM_ASAHI_FEATURE_COMPUTE_ONLY`. +//! through the common submission front end (`m3_submit`). Compute uses the bootstrap +//! queue. A render owns a separate tiler and fragment submission and their parameter buffer +//! until both data masters have retired. //! //! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after //! publishing records on its event, statistics and log rings: each one runs the service, which @@ -32,8 +32,9 @@ use kernel::{ }; use crate::{ - alloc, event, gem, + alloc, event, g14_v27_2_render as render, gem, gpu::{self, CommandPool, ComputeJob, GpuManagerG14V13_5, QueueInfo, RootV27_2, POOL_SLOTS}, + gpu::{FirmwareEvent, FRAGMENT, TILER}, hw, mmu, queue, m3::m3_submit::{Command, Packet}, }; @@ -308,6 +309,17 @@ struct Inflight { _bind: mmu::VmBind, } +struct RenderFlight { + packet: Arc, + last: bool, + bind: mmu::VmBind, + scene: render::Prep, + slots: [usize; 2], + stamps: [event::EventValue; 2], + targets: [u32; 2], + started: Instant, +} + struct State { peer: Peer, root: crate::fw::types::GpuObject, @@ -335,11 +347,35 @@ struct State { retired_raw: u32, capacity: u32, inflight: KVec, + rendering: Option, pending: KVec<(Arc, usize)>, submitted: u64, retired: u64, } +impl State { + fn running(&self) -> bool { + !self.inflight.is_empty() || self.rendering.is_some() + } + + fn owns(&self, packet: &Arc) -> bool { + self.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, packet)) + || self.rendering.as_ref().is_some_and(|flight| Arc::ptr_eq(&flight.packet, packet)) + } + + fn pending(&self, packet: &Arc) -> bool { + self.pending.iter().any(|(current, _)| Arc::ptr_eq(current, packet)) + } + + fn advance_packet(&mut self, last: bool) { + if last { + let _ = self.pending.remove(0); + } else { + self.pending[0].1 += 1; + } + } +} + #[pin_data(PinnedDrop)] pub(crate) struct Runtime { dev: ARef, @@ -396,6 +432,7 @@ impl Runtime { } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + if !self.healthy() { return Err(EIO); } state.pending.push((packet, 0), GFP_KERNEL)?; self.pump(state); Ok(()) @@ -408,7 +445,7 @@ impl Runtime { if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { let _ = state.pending.remove(i); } - if !state.inflight.iter().any(|f| Arc::ptr_eq(&f.packet, packet)) { + if !state.owns(packet) { packet.release_guard(); } } @@ -417,10 +454,15 @@ impl Runtime { fn fail_all(&self, state: &mut State, error: Error) { self.healthy.store(false, Ordering::Release); self.idle.notify_all(); - for (packet, _) in state.pending.drain(..) { - packet.release_guard(); + while let Some((packet, _)) = state.pending.pop() { + if !state.owns(&packet) { + packet.release_guard(); + } packet.finish(Err(error)); } + if let Some(flight) = &state.rendering { + flight.packet.finish(Err(error)); + } // Published work stays owned: the firmware may still read it. for f in state.inflight.iter() { if let Some(status) = f.packet.vm.status() { status.record(error); } @@ -445,96 +487,218 @@ impl Runtime { } } - /// Publishes pending commands while pool slots are free. + /// Finds unlinked slots without moving any publication cursor. + fn free_slots(&self, state: &mut State, count: usize) -> Result> { + let mut slots = [0; 2]; + let mut found = 0; + for k in 0..POOL_SLOTS { + let slot = (state.next_slot + k) % POOL_SLOTS; + if state.busy & (1 << slot) != 0 { continue; } + if state.pool.registered(slot)? { + state.skipped += 1; + continue; + } + slots[found] = slot; + found += 1; + if found == count { + state.waiting_unlink = false; + return Ok(Some(slots)); + } + } + if !state.waiting_unlink { + state.waiting_unlink = true; + state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + } + Ok(None) + } + + /// Compute commands may pipeline. A render pair is a scheduling boundary so its buffer, + /// timestamps and dependencies remain owned until both data masters retire. fn pump(&self, state: &mut State) { self.acknowledge(state); - if self.asleep.load(Ordering::Acquire) { return; } + if !self.healthy() || self.asleep.load(Ordering::Acquire) || state.rendering.is_some() { + return; + } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { - // A slot is reused only once the firmware has unlinked it from its tracking list - // (+0x94), which its retirement scan does after the slot's cursor is advanced. - // Slots retire in order but are unlinked whenever the scan runs; take the next - // free slot that is unlinked. - let mut chosen = None; - for k in 0..POOL_SLOTS { - let slot = (state.next_slot + k) % POOL_SLOTS; - if state.busy & (1 << slot) != 0 { continue; } - match state.pool.registered(slot) { - Ok(false) => { chosen = Some(slot); break; } - Ok(true) => state.skipped += 1, - Err(e) => { self.fail_all(state, e); return; } - } - } - let Some(slot) = chosen else { - if !state.waiting_unlink { - // Every free slot is held: wake the firmware's service once so its - // retirement scan runs. The scan sends nothing; the next notification, - // submission or scheduler timeout retries. - state.waiting_unlink = true; - let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK); - } - return; - }; - state.next_slot = slot; - state.waiting_unlink = false; - // Unlinked already: its cursor needs no further advance. - state.unacked &= !(1 << slot); let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); - let Command::Compute(control) = packet.commands[index] else { - // Queues of this backend accept only compute commands (Queue::submit). - let _ = state.pending.remove(0); - if !(packet.may_be_published() && index != 0) { packet.release_guard(); } - packet.finish(Err(EINVAL)); - continue; + let command = packet.commands[index]; + let paired = matches!(command, Command::Render { .. }); + if paired && state.running() { return; } + let count = if paired { 2 } else { 1 }; + let slots = match self.free_slots(state, count) { + Ok(Some(slots)) => slots, + Ok(None) => return, + Err(err) => { self.fail_all(state, err); return; } + }; + let last = index + 1 == packet.commands.len(); + let result = match command { + Command::Compute(control) => self.publish_compute(state, &packet, control, last, slots[0]), + Command::Render { command, usc } => + self.publish_render(state, &packet, index, &command, usc, last, slots), }; - let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { - let bind = self.graph.kernel_uat().bind(&packet.vm)?; - let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); - let stamp = state.last.next(); - let job = ComputeJob { - context: bind.slot(), - sequence: state.sequence, - cdm_base: control.base, - cdm_end: control.end, - usc_base: control.usc_base, - preempt, - }; - let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; - packet.mark_published(); - state.root.publish(command)?; - state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; - Ok((bind, stamp)) - })(); match result { - Ok((bind, stamp)) => { - state.last = stamp; - state.sequence += 1; - let slot = state.next_slot; - state.busy |= 1 << slot; - state.published += 1; - let ordinal = state.published; - state.next_slot = (state.next_slot + 1) % POOL_SLOTS; - state.submitted += 1; - let last = index + 1 == packet.commands.len(); - if state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - started: Instant::now(), _bind: bind }, GFP_KERNEL).is_err() { - self.fail_all(state, ENOMEM); - return; - } - if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } - } - Err(e) => { - dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e); + Ok(()) if paired || !self.healthy() => return, + Ok(()) => {} + Err(EBUSY) if state.running() => return, + Err(err) => { + dev_err!(self.dev, "GPU: command publication failed {:?}\n", err); let _ = state.pending.remove(0); - // Earlier commands of a published packet fail it when they retire. - if !(packet.may_be_published() && index != 0) { + if !state.owns(&packet) { packet.release_guard(); } - packet.finish(Err(e)); + packet.finish(Err(err)); } } } } + fn publish_compute( + &self, state: &mut State, packet: &Arc, + control: crate::m3::agx_compute::Control, last: bool, slot: usize, + ) -> Result { + let bind = self.graph.kernel_uat().bind(&packet.vm)?; + let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); + let stamp = state.last.next(); + let job = ComputeJob { + context: bind.slot(), + sequence: state.sequence, + cdm_base: control.base, + cdm_end: control.end, + usc_base: control.usc_base, + preempt, + }; + let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; + let submission = state.root.stage_compute(command)?; + let ordinal = state.published + 1; + // Commit ownership before the firmware can see the new work. + state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, + started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + packet.mark_published(); + submission.publish(); + state.last = stamp; + state.sequence += 1; + state.unacked &= !(1 << slot); + state.busy |= 1 << slot; + state.published = ordinal; + state.next_slot = (slot + 1) % POOL_SLOTS; + state.submitted += 1; + state.advance_packet(last); + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK) { + self.fail_all(state, err); + } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + fn publish_render( + &self, state: &mut State, packet: &Arc, index: usize, + command: &crate::m3::agx_uapi::UapiRenderCommand, usc: u64, last: bool, slots: [usize; 2], + ) -> Result { + let queue = packet.render_queue.as_ref().ok_or(EINVAL)?; + let scene = queue.prepare(command, usc)?; + let bind = self.graph.kernel_uat().bind(&packet.vm)?; + let context = bind.slot(); + let (tiler, tiler_stamp) = state.root.render_queue(TILER); + let (fragment, fragment_stamp) = state.root.render_queue(FRAGMENT); + let stamps = [tiler_stamp.next(), fragment_stamp.next()]; + let with_buffer = scene.buffer_op.is_some(); + let timestamps = packet.render_timestamp_addresses(index); + let attachments = &packet.render_attachments[index]; + let ta = state.pool.encode_with(slots[TILER], context, state.sequence, stamps[TILER].raw(), + |cmd, stream, common| { + render::encode_vertex(cmd, stream, &common, &tiler, tiler.compute_state, + command, &scene, stamps[FRAGMENT].raw(), fragment.slot, + timestamps[TILER], &attachments[TILER])?; + if let Some(op) = scene.buffer_op { + render::encode_buffer_op(&mut cmd[render::INITBUF_AT..][..0x20], &common, &scene, op); + } + Ok(()) + })?; + let fs = state.pool.encode_with(slots[FRAGMENT], context, state.sequence + 1, stamps[FRAGMENT].raw(), + |cmd, stream, common| { + render::encode_fragment(cmd, stream, &common, &fragment, fragment.compute_state, + command, &scene, timestamps[FRAGMENT], &attachments[FRAGMENT])?; + render::encode_own_barrier(&mut cmd[render::OWN_BARRIER_AT..][..render::OWN_BARRIER_SIZE], + &tiler, stamps[TILER].raw(), stamps[FRAGMENT].raw()); + Ok(()) + })?; + let ta_work = [ta + render::INITBUF_AT as u64, ta]; + let fs_work = [fs + render::OWN_BARRIER_AT as u64, fs]; + let ta_post = state.root.stage_render(TILER, &ta_work[usize::from(!with_buffer)..])?; + let fs_post = state.root.stage_render(FRAGMENT, &fs_work)?; + state.rendering = Some(RenderFlight { + packet: packet.clone(), last, bind, scene, slots, stamps, + targets: [ta_post.target(), fs_post.target()], started: Instant::now(), + }); + queue.published(); + packet.mark_published(); + // Queue the fragment dependency before kicking the tiler that satisfies it. + fs_post.publish(); + ta_post.publish(); + for slot in slots { + state.busy |= 1 << slot; + state.unacked &= !(1 << slot); + } + state.next_slot = (slots[FRAGMENT] + 1) % POOL_SLOTS; + state.sequence += 2; + state.submitted += 2; + state.advance_packet(last); + for dm in [FRAGMENT, TILER] { + if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, RootV27_2::render_kick(dm)) { + self.fail_all(state, err); + break; + } + } + Ok(()) + } + + fn retire_slot(&self, state: &mut State, slot: usize) { + match state.pool.retire(slot) { + Ok(true) => {} + Ok(false) => { + state.unacked |= 1 << slot; + state.deferred += 1; + } + Err(err) => dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", err), + } + state.busy &= !(1 << slot); + state.retired += 1; + } + + fn retire_render(&self, state: &mut State) -> Result { + let Some(flight) = state.rendering.as_ref() else { return Ok(()); }; + let mut ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; + let mut fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + if !(ta_done && fs_done) + && state.root.render_queue(TILER).1 >= flight.stamps[TILER] + && state.root.render_queue(FRAGMENT).1 >= flight.stamps[FRAGMENT] + { + // As on the compute queue, the final stamp precedes the retired cursor and + // there may be no separate notification when the cursor changes. + let start = Instant::::now(); + while !(ta_done && fs_done) && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { + fsleep(Delta::from_micros(20)); + ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; + fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + } + } + if ta_done && fs_done { + let flight = state.rendering.take().ok_or(EIO)?; + for slot in flight.slots { + self.retire_slot(state, slot); + } + if flight.last { + flight.packet.retired(); + } else if !state.pending(&flight.packet) { + flight.packet.release_guard(); + } + } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); + return Err(ETIMEDOUT); + } + Ok(()) + } + /// Reads the queue's retired position into `retired_total`. fn advance(&self, state: &mut State) -> Result { let (_, raw) = state.root.progress()?; @@ -551,7 +715,33 @@ impl Runtime { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { return; }; self.service_locked(state); - if state.inflight.is_empty() && state.pending.is_empty() { self.idle.notify_all(); } + if !state.running() && state.pending.is_empty() { self.idle.notify_all(); } + } + + fn process_events(&self, state: &mut State) -> Result { + // Limit one pass to the ring capacity. Further arrivals notify the worker again. + for _ in 0..256 { + let Some((cursor, event)) = state.root.peek_event()? else { break; }; + match event { + FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { + let Some(reply) = state.root.reserve_control_reply()? else { break; }; + let granted = state.rendering.as_ref() + .filter(|flight| flight.bind.slot() == request.vm && flight.scene.slot() == request.buffer) + .and_then(|flight| flight.packet.render_queue.as_ref()) + .is_some_and(|queue| queue.grow().unwrap_or(false)); + reply.grow(request, granted)?; + state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; + } + FirmwareEvent::ChannelError => { + dev_err!(self.dev, "GPU firmware rejected a channel record\n"); + state.root.consume_event(cursor)?; + return Err(EIO); + } + FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} + } + state.root.consume_event(cursor)?; + } + Ok(()) } fn service_locked(&self, state: &mut State) { @@ -562,6 +752,8 @@ impl Runtime { self.fail_all(state, EIO); return; } + if let Err(err) = self.process_events(state) { self.fail_all(state, err); return; } + if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } // The completion stamp is written before the firmware's post-processing advances the // retired position, and that advance sends no message. If the front command's stamp @@ -581,20 +773,11 @@ impl Runtime { let front = &state.inflight[0]; if state.retired_total >= front.ordinal { if let Ok(done) = state.inflight.remove(0) { - match state.pool.retire(done.slot) { - Ok(true) => {} - // The firmware has not recorded the cursor value yet; `acknowledge` - // retries on its next notification. - Ok(false) => { - state.unacked |= 1 << done.slot; - state.deferred += 1; - } - Err(e) => dev_err!(self.dev, "GPU: tracking retirement failed {:?}\n", e), - } - state.busy &= !(1 << done.slot); - state.retired += 1; + self.retire_slot(state, done.slot); if done.last { done.packet.retired(); + } else if !state.owns(&done.packet) && !state.pending(&done.packet) { + done.packet.release_guard(); } } continue; @@ -629,7 +812,7 @@ impl Runtime { loop { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } - if state.inflight.is_empty() { + if !state.running() { dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", state.submitted, state.retired, state.pending.len()); return Ok(()); @@ -665,7 +848,7 @@ impl Runtime { let start = Instant::::now(); while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { let Some(state) = guard.as_ref() else { break; }; - if state.inflight.is_empty() && state.pending.is_empty() { break; } + if !state.running() && state.pending.is_empty() { break; } let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); } } @@ -782,6 +965,7 @@ impl Backend { retired_raw: head, capacity, inflight: KVec::new(), + rendering: None, pending: KVec::new(), submitted: 0, retired: 0, @@ -831,12 +1015,9 @@ impl gpu::Gpu for Backend { Ok(()) } fn supports_vm_status(&self) -> bool { true } - /// Render commands are refused (`m3_submit`), so the device also reports itself - /// compute-only: graphics userspace then leaves it alone instead of failing its first render. fn feature_flags(&self) -> u64 { uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 - | uapi::DRM_ASAHI_FEATURE_COMPUTE_ONLY as u64 } fn tracked_submission(&self) -> bool { true } fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } @@ -844,11 +1025,13 @@ impl gpu::Gpu for Backend { fn new_vm(&self, range: Range) -> Result { self.graph.kernel_uat().new_vm(self.ids.vm.next(), range)?.with_tracked_status() } - fn new_queue(&self, vm: mmu::Vm, _ualloc: Arc>, + fn new_queue(&self, vm: mmu::Vm, ualloc: Arc>, ualloc_priv: Arc>, priority: u32, usc_exec_base: u64, _usage: Arc) -> Result> { + let render = Arc::new(render::QueueRender::new(self.graph.clone(), ualloc, ualloc_priv.clone())?, + GFP_KERNEL)?; Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), - vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes)?, GFP_KERNEL)?) + vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes, render)?, GFP_KERNEL)?) } fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { // Timestamp buffers would need new tables in the firmware window after boot. diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs new file mode 100644 index 00000000000000..535313f91126cf --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 firmware queue and event records with no kernel or MMIO dependencies. + +#[cfg(not(test))] +use kernel::prelude::kunit_tests; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum QueueError { + Geometry, + Full, +} + +/// Compute the next producer after validating the shared cursor range and available space. +pub(crate) fn queue_head( + capacity: u32, + write: u32, + retired: u32, + count: u32, +) -> Result { + if capacity < 2 + || capacity > u16::MAX.into() + || write >= capacity + || retired >= capacity + || count == 0 + || count >= capacity + { + return Err(QueueError::Geometry); + } + let free = (retired + capacity - write - 1) % capacity; + if count > free { + return Err(QueueError::Full); + } + Ok((write + count) % capacity) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct GrowRequest { + pub(crate) vm: u32, + pub(crate) buffer: u32, + pub(crate) counter: u32, + pub(crate) subpipe: u32, + pub(crate) halt_count: u64, +} + +impl GrowRequest { + pub(crate) fn decode([vm, buffer, counter, subpipe, halt_low, halt_high]: [u32; 6]) -> Self { + Self { + vm, + buffer, + counter, + subpipe, + halt_count: u64::from(halt_low) | (u64::from(halt_high) << 32), + } + } + + pub(crate) fn reply(self, granted: bool) -> [u32; 16] { + const GROW_REPLY: u32 = 8; + let mut record = [0; 16]; + record[..8].copy_from_slice(&[ + GROW_REPLY, + u32::from(granted), + self.buffer, + self.vm, + self.counter, + self.subpipe, + self.halt_count as u32, + (self.halt_count >> 32) as u32, + ]); + record + } +} + +#[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] +#[cfg_attr(test, allow(dead_code))] +mod tests { + use super::*; + + #[test] + fn head_wraps_and_keeps_one_entry_free() { + assert_eq!(queue_head(8, 7, 7, 2), Ok(1)); + assert_eq!(queue_head(8, 7, 2, 2), Ok(1)); + assert_eq!(queue_head(8, 7, 2, 3), Err(QueueError::Full)); + assert_eq!(queue_head(8, 7, 0, 1), Err(QueueError::Full)); + } + + #[test] + fn corrupted_cursors_and_invalid_depth_fail_before_publication() { + for (capacity, write, read, count) in [ + (0, 0, 0, 1), + (8, 8, 0, 1), + (8, 0, 8, 1), + (8, 0, 0, 0), + (8, 0, 0, 8), + (1 << 16, 0, 0, 1), + ] { + assert_eq!( + queue_head(capacity, write, read, count), + Err(QueueError::Geometry) + ); + } + } + + #[test] + fn growth_replies_echo_request_identity_and_clear_unused_words() { + let request = GrowRequest::decode([2, 9, 31, 1, 0x789a_bcde, 0x1234_5678]); + assert_eq!(request.halt_count, 0x1234_5678_789a_bcde); + assert_eq!( + request.reply(true), + [ + 8, + 1, + 9, + 2, + 31, + 1, + 0x789a_bcde, + 0x1234_5678, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ] + ); + assert_eq!( + request.reply(false), + [ + 8, + 0, + 9, + 2, + 31, + 1, + 0x789a_bcde, + 0x1234_5678, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ] + ); + } +} diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs new file mode 100644 index 00000000000000..a1c2b02ed49a4c --- /dev/null +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -0,0 +1,1021 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! G14 firmware render command and parameter buffer encoders. +//! +//! The TA and fragment data masters consume distinct records. The render runtime owns both +//! records and the scene until both queues retire. Each logical queue owns its parameter +//! buffer, including the firmware-written page and block cursors, across submissions. + +use crate::alloc::Allocator as _; +use crate::fw::types::GpuArray; +use crate::gpu::QueueInfo; +use crate::m3::agx_attachments::Attachments; +use crate::m3::agx_uapi::UapiRenderCommand; +use crate::{buffer, fw}; +use core::mem::offset_of; +use kernel::{ + new_mutex, + prelude::*, + sync::{Arc, Mutex}, +}; + +type Rv = fw::vertex::raw::RunVertexG14V13_5<'static>; +type Rf = fw::fragment::raw::RunFragmentG14V13_5<'static>; +type Meta = fw::job::raw::JobMeta; + +pub(crate) const INITBUF_AT: usize = 0xf00; +pub(crate) const OWN_BARRIER_AT: usize = 0xf40; +pub(crate) const OWN_BARRIER_SIZE: usize = 0x40; + +/// G14 stamp dependency queued on FS immediately before RunFragment. +pub(crate) fn encode_own_barrier( + record: &mut [u8], + ta: &QueueInfo, + ta_target: u32, + fs_target: u32, +) { + put32(record, 0, 4); + put64(record, 0x04, ta.fw_stamp); + put64(record, 0x0c, ta.fw_stamp); + put32(record, 0x14, ta_target); + put32(record, 0x20, ta.slot); + put32(record, 0x24, fs_target); +} + +struct Binding { + info: GpuArray, + slot: u32, + blocks: u32, + initialized: bool, +} + +pub(crate) struct QueueRender { + graph: Arc, + buffer: buffer::BufferG14V13_5, + ualloc: Arc>, + binding: Pin>>>, +} + +pub(crate) struct Prep { + scene: buffer::SceneG14V13_5, + aux_fb: GpuArray, + tile: buffer::TileInfo, + scene27: GpuArray, + info_va: u64, + usc: u64, + pub(crate) buffer_op: Option, +} + +#[derive(Clone, Copy)] +pub(crate) enum BufferOp { + Rebuild, + Grow, +} + +impl Prep { + pub(crate) fn slot(&self) -> u32 { + self.scene.slot() + } +} + +fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { + // SAFETY: the UAPI struct is plain data; all-zero is a valid value. + let mut c: kernel::uapi::drm_asahi_cmd_render = unsafe { core::mem::zeroed() }; + // This path has one cluster. The shared tiler only needs dimensions and sample geometry. + c.isp_zls_pixels = r.depth_dimensions; + c.width_px = r.width; + c.height_px = r.height; + c.layers = r.layers; + c.utile_width_px = r.utile_width; + c.utile_height_px = r.utile_height; + c.samples = r.samples; + c.sample_size_B = r.sample_size; + c.ppp_ctrl = r.ppp_control; + c.ppp_multisamplectl = r.multisample_control; + c +} + +impl QueueRender { + pub(crate) fn new( + graph: Arc, + ualloc: Arc>, + ualloc_priv: Arc>, + ) -> Result { + let buffer = graph.new_render_buffer(ualloc.clone(), ualloc_priv)?; + Ok(Self { + graph, + buffer, + ualloc, + binding: KBox::pin_init(new_mutex!(None), GFP_KERNEL)?, + }) + } + + /// Called with the render data masters idle, so making a fresh binding cannot free memory + /// which a previous flight still owns. + pub(crate) fn prepare(&self, r: &UapiRenderCommand, usc: u64) -> Result { + let tile = crate::queue::QueueInnerG14V13_5::get_tiling_params(&to_cmdbuf(r), 1)?; + self.buffer.ensure_parameter_blocks(tile.min_tvb_blocks)?; + let mut alloc = + ::alloc(&self.graph); + let scene = self.buffer.new_scene(&mut alloc, &tile)?; + let mut scene27 = alloc.shared.array_empty::(0x48)?; + let aux_fb = self.ualloc.lock().array_empty_tagged(0x8000, b"AXFB")?; + let (user_buffer, stats) = scene.render_addresses(); + put64(scene27.as_mut_slice(), 0x18, user_buffer); + put64(scene27.as_mut_slice(), 0x30, stats); + crate::pgtable::clean_poc(scene27.as_slice().as_ptr(), scene27.len()); + + let mut guard = self.binding.lock(); + if guard + .as_ref() + .is_none_or(|binding| binding.slot != scene.slot()) + || scene.rebind() + { + // Remember a failed rebind too. The slot allocator may return the same token on retry. + *guard = None; + let mut info = alloc.shared.array_empty::(0x90)?; + let p = self.buffer.parameter_info(); + let record = info.as_mut_slice(); + put32(record, 0x08, scene.slot()); + put64(record, 0x18, p.page_list); + put64(record, 0x20, p.page_list); + put32(record, 0x28, p.page_list_size); + put32(record, 0x30, p.max_blocks); + put64(record, 0x3c, p.block_list); + put64(record, 0x44, p.block_control); + put32(record, 0x4c, u32::MAX); + put32(record, 0x50, p.block_size); + put64(record, 0x5c, p.counter); + put32(record, 0x74, p.max_pages); + put32(record, 0x78, p.max_linear_pages); + crate::pgtable::clean_poc(record.as_ptr(), record.len()); + *guard = Some(Binding { + info, + slot: scene.slot(), + blocks: 0, + initialized: false, + }); + } + let binding = guard.as_ref().ok_or(EIO)?; + let buffer_op = if !binding.initialized { + Some(BufferOp::Rebuild) + } else if self.buffer.block_count() > binding.blocks { + Some(BufferOp::Grow) + } else { + None + }; + Ok(Prep { + scene, + aux_fb, + tile, + scene27, + info_va: binding.info.gpu_va().get(), + usc, + buffer_op, + }) + } + + pub(crate) fn published(&self) { + if let Some(binding) = Option::as_mut(&mut *self.binding.lock()) { + binding.initialized = true; + binding.blocks = self.buffer.block_count(); + self.buffer.increment(); + } + } + + /// A running TA can request more backing. The firmware computes the page list itself. + pub(crate) fn grow(&self) -> Result { + let mut guard = self.binding.lock(); + let binding = Option::as_mut(&mut *guard).ok_or(EIO)?; + let count = self.buffer.block_count() as usize; + let grown = self.buffer.ensure_parameter_blocks(count + 1)?; + binding.blocks = self.buffer.block_count(); + Ok(grown) + } +} + +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Inputs both records share. +pub(crate) struct Common { + pub(crate) cmd_va: u64, + pub(crate) stream_va: u64, + pub(crate) tracking: u64, + pub(crate) timestamps: u64, + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) stamp_value: u32, +} + +/// Header shared by every 27.2 record (as compute): type, sequence, context, tracking. +fn header(b: &mut [u8], kind: u32, c: &Common) { + put32(b, 0, kind); + put64(b, 4, c.sequence); + put32(b, 0xc, c.context); + put64(b, 0x10, c.tracking); +} + +/// Write the destinations used by both internal timestamp paths. +fn timestamp_op( + s: &mut [u8], + at: usize, + start: bool, + q: &QueueInfo, + command_time: u64, + ts_pointers: u64, + internal0: u64, + internal1: u64, + user: [u64; 2], +) { + put32(s, at, if start { 0x8000_0003 } else { 3 }); + put64(s, at + 0x04, command_time); + put64(s, at + 0x0c, ts_pointers); + put64( + s, + at + 0x14, + if start { ts_pointers } else { ts_pointers + 8 }, + ); + put64(s, at + 0x1c, q.queue); + put64(s, at + 0x24, user[usize::from(!start)]); + put64(s, at + 0x2c, internal0); + put64(s, at + 0x34, internal1); +} + +pub(crate) fn encode_buffer_op(rec: &mut [u8], c: &Common, p: &Prep, op: BufferOp) { + put32( + rec, + 0, + match op { + BufferOp::Rebuild => 6, + BufferOp::Grow => 5, + }, + ); + put32(rec, 4, c.context); + put32(rec, 8, p.slot()); + // Rebuild is a range operation with zero count. Grow uses the published block producer. + let info = match op { + BufferOp::Rebuild => 0x14, + BufferOp::Grow => 0x0c, + }; + put64(rec, info, p.info_va); + put32(rec, info + 8, c.stamp_value); +} + +/// Encodes the tiler command and its stream. The fragment stamp is its wakeup target. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_vertex( + cmd: &mut [u8], + stream: &mut [u8], + c: &Common, + q: &QueueInfo, + vertex_state: u64, + r: &UapiRenderCommand, + p: &Prep, + frag_stamp: u32, + frag_slot: u32, + timestamps: [u64; 2], + attachments: &Attachments, +) -> Result { + let jp1 = |field: usize| 0x38 + field - offset_of!(Rv, job_params1); + let jp2 = |field: usize| 0x488 + field - offset_of!(Rv, job_params2); + header(cmd, 0, c); + let scene = &p.scene; + let (info_va, scene_va) = (p.info_va, p.scene27.gpu_va().get()); + // StartVertex and FinalizeVertex point past the state header word. + let vertex_state = vertex_state + 4; + let samples_log2 = match r.samples { + 1 => 0, + 2 => 1, + 4 => 2, + _ => return Err(EINVAL), + }; + let utile_config = + ((p.tile.utile_width / 16) << 12) | ((p.tile.utile_height / 16) << 14) | samples_log2; + put32(cmd, 0x18, scene.slot()); + put64(cmd, 0x20, info_va); + put64(cmd, 0x28, scene_va); + put64(cmd, 0x30, scene.kernel_buffer_pointer().into()); + // JobParameters1 at 0x38, 13.5 G14 internal layout. + put64(cmd, jp1(offset_of!(Rv, job_params1.unk_0)), 0x200); + put32(cmd, jp1(offset_of!(Rv, job_params1.unk_8)), 0x1e3c_e508); + put32(cmd, jp1(offset_of!(Rv, job_params1.unk_c)), 0x1e3c_e508); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.tvb_tilemap)), + scene.tvb_tilemap_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.tpc)), + scene.tpc_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.tvb_heapmeta)), + scene + .tvb_heapmeta_pointer() + .or(0x8000_0000_0000_0000) + .into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.iogpu_unk_54)), + 0x3a_0012_006b_0003, + ); + put64(cmd, jp1(offset_of!(Rv, job_params1.iogpu_unk_56)), 1); + put32( + cmd, + jp1(offset_of!(Rv, job_params1.utile_config)), + utile_config, + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.ppp_multisamplectl)), + r.multisample_control, + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.tvb_layermeta)), + scene.tvb_layermeta_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.preempt_buf1)), + scene.preempt_buf_1_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.preempt_buf2)), + scene.preempt_buf_2_pointer().into(), + ); + put64(cmd, jp1(offset_of!(Rv, job_params1.unk_80)), 1); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.preempt_buf3)), + scene.preempt_buf_3_pointer().or(0x4_0000_0000_0000).into(), + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.vdm_ctrl_stream_base)), + r.vdm_base, + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.usc_exec_base_ta)), + p.usc, + ); + put64(cmd, jp1(offset_of!(Rv, job_params1.unk_f8)), 0x8c60); + put32( + cmd, + jp1(offset_of!(Rv, job_params1.helper_program)), + r.vertex_helper.binary, + ); + put64( + cmd, + jp1(offset_of!(Rv, job_params1.helper_arg)), + r.vertex_helper.data, + ); + put32(cmd, jp1(offset_of!(Rv, job_params1.unk_118)), 0x1c); + // Tiling parameters at 0x3bc (13.5 block), + the new word at +0x30. + { + let at = 0x3bc; + let n = core::mem::size_of::(); + // SAFETY: `TilingParameters` is a `repr(C)` plain-data struct of `n` bytes. + let src = unsafe { + core::slice::from_raw_parts(core::ptr::from_ref(&p.tile.params).cast::(), n) + }; + cmd[at..at + n].copy_from_slice(src); + put32(cmd, at + 0x30, scene.slot()); + } + put64(cmd, 0x45c, scene.tpc_pointer().into()); + put64(cmd, 0x464, p.tile.tpc_size as u64); + let mseq = 0x46c; + const STREAM: u32 = 0x300; + put64(cmd, mseq, c.stream_va); + put32(cmd, mseq + 8, STREAM); + put32(cmd, 0x478, frag_slot); + put32(cmd, 0x47c, frag_stamp); + put64( + cmd, + jp2(offset_of!(Rv, job_params2.preempt_buf1)), + scene.preempt_buf_1_pointer().into(), + ); + put64(cmd, 0x558, r.sampler_heap); + put32(cmd, 0x560, u32::from(r.sampler_count)); + put32(cmd, 0x564, u32::from(r.sampler_count)); + // Allow a synchronous parameter-buffer request. + put32(cmd, 0x570, 1); + // Job meta at 0x580. + put64(cmd, 0x584, q.stamp); + put64(cmd, 0x58c, q.fw_stamp); + put32(cmd, 0x594, c.stamp_value); + put32(cmd, 0x598, q.slot); + // The event-control index is independent of the completion stamp slot. + put64(cmd, 0x5a4, 0); // uuid (compute leaves it 0) + let command_time = c.cmd_va + 0x5cc; + let ts = c.cmd_va + 0x5d4; + put64(cmd, 0x5d4, c.timestamps); + put64(cmd, 0x5dc, c.timestamps + 8); + put64(cmd, 0x5e4, timestamps[0]); + put64(cmd, 0x5ec, timestamps[1]); + let internal0 = c.cmd_va + 0x61c; + let internal1 = c.cmd_va + 0x538; + let flag = c.cmd_va + 0x568; + let unk_pointee = c.cmd_va + 0x480; + let unk_buf_0 = c.cmd_va + 0x5b4; + let tiling = c.cmd_va + 0x3bc; + let jp1_va = c.cmd_va + 0x38; + + // Stream: StartVertex (0x19c), Timestamp, wait for the vertex pipe, Timestamp, + // FinalizeVertex (0x9c), end. + let s = stream; + put32(s, 0, 5); + put64(s, 0x04, tiling); + put64(s, 0x0c, jp1_va); + put64(s, 0x14, info_va); + put64(s, 0x1c, scene_va); + put64(s, 0x24, vertex_state); + put64(s, 0x2c, q.queue); + put64(s, 0x34, flag); + put32(s, 0x3c, c.context); + put32(s, 0x40, 1); + put32(s, 0x48, scene.slot()); + put32(s, 0x54, q.slot); + put64(s, 0x5c, unk_pointee); + put64(s, 0x64, unk_buf_0); + s[0x80..0x180].copy_from_slice(&attachments.0[..0x100]); + put32(s, 0x180, u32::from(attachments.count())); + put64(s, 0x188, c.sequence); + put32(s, 0x190, q.slot); + put32(s, 0x194, 1); // The tiler command uses the single-cluster layout. + timestamp_op( + s, + 0x19c, + true, + q, + command_time, + ts, + internal0, + internal1, + timestamps, + ); + put32(s, 0x1e8, 0x0000_0100); + timestamp_op( + s, + 0x1ec, + false, + q, + command_time, + ts, + internal0, + internal1, + timestamps, + ); + let fin = 0x238; + put32(s, fin, 6); + put64(s, fin + 0x04, scene_va); + put64(s, fin + 0x0c, info_va); + put64(s, fin + 0x14, vertex_state); + put64(s, fin + 0x1c, q.queue); + put64(s, fin + 0x24, flag); + put32(s, fin + 0x2c, c.context); + put64(s, fin + 0x34, unk_pointee); + put64(s, fin + 0x48, q.fw_stamp); + put32(s, fin + 0x50, c.stamp_value); + put32(s, fin + 0x78, (-(fin as i32)) as u32); + put64(s, fin + 0x8d, c.cmd_va + 0x60c); + put32(s, fin + 0x9c, 0x4000_0002); + debug_assert!(fin + 0xa0 <= STREAM as usize); + Ok(()) +} + +/// Translate the legacy common fragment fields around the wider metadata and sampler tail. +const fn frag_at(offset: usize) -> usize { + let meta = offset_of!(Rf, meta); + let event_seq = meta + offset_of!(Meta, event_seq); + if offset < FRAG_SAMPLERS13 { + offset + } else if offset < meta { + offset + 0x10 + } else if offset < event_seq { + offset + 0x14 + } else { + offset + 0x18 + } +} + +/// 13.5 offset of the sampler array (encoder_params), where the 27.2 +0x10 band starts. +const FRAG_SAMPLERS13: usize = 0x8ac; +/// 27.2 fragment stream: op 7 (0x1b4), Timestamp, WFI 0x00010000, Timestamp, op 8 (0xbc), end. +const FRAG_STREAM: u32 = 0x340; +/// Encodes the fragment command and its stream. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fragment( + cmd: &mut [u8], + stream: &mut [u8], + c: &Common, + q: &QueueInfo, + fragment_state: u64, + r: &UapiRenderCommand, + p: &Prep, + timestamps: [u64; 2], + attachments: &Attachments, +) -> Result { + let fragment_state = fragment_state + 4; + // Anchors of the 13.5 layout this mapping assumes. + if offset_of!(Rf, meta) != 0x8d0 + || offset_of!(Rf, encoder_params) + offset_of!(fw::job::raw::EncoderParams, sampler_array) + != FRAG_SAMPLERS13 + || offset_of!(Rf, job_params1) != 0x80 + || offset_of!(Rf, job_params2) != 0x3c8 + || offset_of!(Rf, job_params3) != 0x4b8 + || cmd.len() < 0x9b0 + || stream.len() < FRAG_STREAM as usize + { + return Err(EINVAL); + } + let scene = &p.scene; + let samples_log2 = match r.samples { + 1 => 0u32, + 2 => 1, + 4 => 2, + _ => return Err(EINVAL), + }; + let utile_config = + ((p.tile.utile_width / 16) << 12) | ((p.tile.utile_height / 16) << 14) | samples_log2; + let mut tile_config: u64 = 0x280; + if r.layers > 1 { + tile_config |= 1; + } + if r.flags & 2 != 0 { + tile_config |= 0x10000; + } // process empty tiles + let pixels_per_utile = u32::from(r.utile_width) * u32::from(r.utile_height); + let tib_blocks = (u32::from(r.sample_size) * (pixels_per_utile << samples_log2)).div_ceil(2048); + let isp_ctl = 0xc000u32 | (r.flags & (1 << 18)); // depth bias is integer + let rgn_size = u64::from(p.tile.params.rgn_size); + let (info_va, scene_va) = (p.info_va, p.scene27.gpu_va().get()); + let va = |o: usize| c.cmd_va + o as u64; + let w32 = |b: &mut [u8], o13: usize, v: u32| put32(b, frag_at(o13), v); + let w64 = |b: &mut [u8], o13: usize, v: u64| put64(b, frag_at(o13), v); + let w16 = |b: &mut [u8], o13: usize, v: u16| { + let a = frag_at(o13); + b[a..a + 2].copy_from_slice(&v.to_le_bytes()); + }; + + // Header: 0x10 stays 0; microsequence at 0x14/0x1c; tracking slot at 0x20. + put32(cmd, 0, 1); + put64(cmd, 4, c.sequence); + put32(cmd, 0xc, c.context); + let mseq = 0x14; + put64(cmd, mseq, c.stream_va); + put32(cmd, mseq + 8, FRAG_STREAM); + put64(cmd, 0x20, c.tracking); + put64(cmd, 0x28, info_va); + put64(cmd, 0x30, scene_va); + w64( + cmd, + offset_of!(Rf, unk_buffer_buf), + scene.kernel_buffer_pointer().into(), + ); + w64( + cmd, + offset_of!(Rf, tvb_tilemap), + scene.tvb_tilemap_pointer().into(), + ); + w64( + cmd, + offset_of!(Rf, ppp_multisamplectl), + r.multisample_control, + ); + w32(cmd, offset_of!(Rf, samples), u32::from(r.samples)); + w16( + cmd, + offset_of!(Rf, tiles_per_mtile_y), + p.tile.tiles_per_mtile_y as u16, + ); + w16( + cmd, + offset_of!(Rf, tiles_per_mtile_x), + p.tile.tiles_per_mtile_x as u16, + ); + w32(cmd, offset_of!(Rf, isp_merge_upper_x), r.merge_upper_x); + w32(cmd, offset_of!(Rf, isp_merge_upper_y), r.merge_upper_y); + w64(cmd, offset_of!(Rf, tile_count), u64::from(p.tile.tiles)); + // Job parameters 1. + w32(cmd, offset_of!(Rf, job_params1.utile_config), utile_config); + w64( + cmd, + offset_of!(Rf, job_params1.bg.rsrc_spec), + r.background.resource_spec, + ); + w64( + cmd, + offset_of!(Rf, job_params1.bg.address), + u64::from(r.background.usc), + ); + w64( + cmd, + offset_of!(Rf, job_params1.ppp_multisamplectl), + r.multisample_control, + ); + w64( + cmd, + offset_of!(Rf, job_params1.isp_scissor_base), + r.scissor_base, + ); + w64( + cmd, + offset_of!(Rf, job_params1.isp_dbias_base), + r.depth_bias_base, + ); + w64( + cmd, + offset_of!(Rf, job_params1.isp_oclqry_base), + r.occlusion_query_base, + ); + for base in [ + offset_of!(Rf, job_params1.aux_fb_info), + offset_of!(Rf, job_params3.aux_fb_info), + ] { + w32(cmd, base, isp_ctl); + w32(cmd, base + 8, u32::from(r.width)); + w32(cmd, base + 0xc, u32::from(r.height)); + w64(cmd, base + 0x10, 0x10_0000); + } + w64( + cmd, + offset_of!(Rf, job_params1.isp_zls_pixels), + u64::from(r.depth_dimensions), + ); + w64(cmd, offset_of!(Rf, job_params1.zls_ctrl), r.zls_control); + w64(cmd, offset_of!(Rf, job_params1.unk_58_g14_0), 0x404_0404); + for (o, v) in [ + (offset_of!(Rf, job_params1.z_load), r.depth.base), + (offset_of!(Rf, job_params1.z_store), r.depth.base), + (offset_of!(Rf, job_params1.s_load), r.stencil.base), + (offset_of!(Rf, job_params1.s_store), r.stencil.base), + ( + offset_of!(Rf, job_params1.z_load_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!(Rf, job_params1.z_store_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!(Rf, job_params1.s_load_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!(Rf, job_params1.s_store_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!(Rf, job_params1.z_load_comp), + r.depth.compression_base, + ), + ( + offset_of!(Rf, job_params1.z_load_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!(Rf, job_params1.z_store_comp), + r.depth.compression_base, + ), + ( + offset_of!(Rf, job_params1.z_store_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!(Rf, job_params1.s_load_comp), + r.stencil.compression_base, + ), + ( + offset_of!(Rf, job_params1.s_load_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!(Rf, job_params1.s_store_comp), + r.stencil.compression_base, + ), + ( + offset_of!(Rf, job_params1.s_store_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!(Rf, job_params1.tvb_tilemap), + scene.tvb_tilemap_pointer().into(), + ), + ( + offset_of!(Rf, job_params1.tvb_layermeta), + scene.tvb_layermeta_pointer().into(), + ), + ( + offset_of!(Rf, job_params1.mtile_stride_dwords), + (4 * rgn_size) << 24, + ), + ( + offset_of!(Rf, job_params1.tvb_heapmeta), + scene.tvb_heapmeta_pointer().into(), + ), + (offset_of!(Rf, job_params1.tile_config), tile_config), + (offset_of!(Rf, job_params1.aux_fb), p.aux_fb.gpu_va().get()), + (offset_of!(Rf, job_params1.usc_exec_base_isp), p.usc), + (offset_of!(Rf, job_params1.unk_140), 0x8c60), + ( + offset_of!(Rf, job_params1.helper_arg), + r.fragment_helper.data, + ), + (offset_of!(Rf, job_params1.unk_158), 0x1c), + ] { + w64(cmd, o, v); + } + w32( + cmd, + offset_of!(Rf, job_params1.helper_program), + r.fragment_helper.binary, + ); + // Job parameters 2, + the new JP2+0x44 = buffer slot (cmd+0x40c). + w32( + cmd, + offset_of!(Rf, job_params2.eot_rsrc_spec), + r.end_of_tile.resource_spec as u32, + ); + w32(cmd, offset_of!(Rf, job_params2.eot_usc), r.end_of_tile.usc); + w32( + cmd, + offset_of!(Rf, job_params2.isp_merge_upper_x), + r.merge_upper_x, + ); + w32( + cmd, + offset_of!(Rf, job_params2.isp_merge_upper_y), + r.merge_upper_y, + ); + w16( + cmd, + offset_of!(Rf, job_params2.utiles_per_mtile_y), + p.tile.utiles_per_mtile_y as u16, + ); + w16( + cmd, + offset_of!(Rf, job_params2.utiles_per_mtile_x), + p.tile.utiles_per_mtile_x as u16, + ); + w32( + cmd, + offset_of!(Rf, job_params2.tile_counts), + ((p.tile.tiles_y - 1) << 12) | (p.tile.tiles_x - 1), + ); + w32(cmd, offset_of!(Rf, job_params2.tib_blocks), tib_blocks); + w32( + cmd, + offset_of!(Rf, job_params2.isp_bgobjdepth), + r.depth_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params2.isp_bgobjvals), + r.stencil_clear, + ); + w32(cmd, offset_of!(Rf, job_params2.unk_3c), 1); + w32( + cmd, + offset_of!(Rf, job_params2.helper_cfg), + r.fragment_helper.config, + ); + put32(cmd, 0x40c, scene.slot()); + // Job parameters 3 (13.5 fill). + for (o, v) in [ + ( + offset_of!(Rf, job_params3.isp_dbias_base.ptr), + r.depth_bias_base, + ), + ( + offset_of!(Rf, job_params3.isp_scissor_base.ptr), + r.scissor_base, + ), + ( + offset_of!(Rf, job_params3.isp_oclqry_base), + r.occlusion_query_base, + ), + ( + offset_of!(Rf, job_params3.unk_partial_bg.rsrc_spec), + r.partial_background.resource_spec, + ), + ( + offset_of!(Rf, job_params3.unk_partial_bg.address), + u64::from(r.partial_background.usc), + ), + ( + offset_of!(Rf, job_params3.partial_bg.rsrc_spec), + r.partial_background.resource_spec, + ), + ( + offset_of!(Rf, job_params3.partial_bg.address), + u64::from(r.partial_background.usc), + ), + (offset_of!(Rf, job_params3.zls_ctrl), r.zls_control), + (offset_of!(Rf, job_params3.unk_290), 0x404_0404), + (offset_of!(Rf, job_params3.z_load), r.depth.base), + ( + offset_of!(Rf, job_params3.z_partial_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!(Rf, job_params3.z_partial_comp_stride), + u64::from(r.depth.compression_stride), + ), + (offset_of!(Rf, job_params3.z_store), r.depth.base), + (offset_of!(Rf, job_params3.z_partial), r.depth.base), + ( + offset_of!(Rf, job_params3.z_partial_comp), + r.depth.compression_base, + ), + (offset_of!(Rf, job_params3.s_load), r.stencil.base), + ( + offset_of!(Rf, job_params3.s_partial_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!(Rf, job_params3.s_partial_comp_stride), + u64::from(r.stencil.compression_stride), + ), + (offset_of!(Rf, job_params3.s_store), r.stencil.base), + (offset_of!(Rf, job_params3.s_partial), r.stencil.base), + ( + offset_of!(Rf, job_params3.s_partial_comp), + r.stencil.compression_base, + ), + (offset_of!(Rf, job_params3.tile_config), tile_config), + ( + offset_of!(Rf, job_params3.isp_zls_pixels), + u64::from(r.depth_dimensions), + ), + ] { + w64(cmd, o, v); + } + w32(cmd, offset_of!(Rf, job_params3.tib_blocks), tib_blocks); + for base in [ + offset_of!(Rf, job_params3.unk_partial_eot), + offset_of!(Rf, job_params3.partial_eot), + ] { + w32( + cmd, + base + offset_of!(fw::fragment::raw::EotProgram, rsrc_spec), + r.partial_end_of_tile.resource_spec as u32, + ); + w32( + cmd, + base + offset_of!(fw::fragment::raw::EotProgram, address), + r.partial_end_of_tile.usc, + ); + } + w32( + cmd, + offset_of!(Rf, job_params3.isp_bgobjdepth), + r.depth_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params3.isp_bgobjvals), + r.stencil_clear, + ); + w32( + cmd, + offset_of!(Rf, job_params3.sample_size), + u32::from(r.sample_size), + ); + put64(cmd, 0x8bc, r.sampler_heap); + put32(cmd, 0x8c4, u32::from(r.sampler_count)); + put32(cmd, 0x8c8, u32::from(r.sampler_count)); + w32(cmd, offset_of!(Rf, encoder_params.unk_mask), u32::MAX); + w32( + cmd, + offset_of!(Rf, process_empty_tiles), + u32::from(r.flags & 2 != 0), + ); + w32(cmd, offset_of!(Rf, no_clear_pipeline_textures), 1); + // 0x8d8 unk_pointee, 0x8dc skip/done flag, 0x770, 0x888, 0x88c stay 0. + let meta = offset_of!(Rf, meta); + w64(cmd, meta + offset_of!(Meta, stamp), q.stamp); + w64(cmd, meta + offset_of!(Meta, fw_stamp), q.fw_stamp); + w32(cmd, meta + offset_of!(Meta, stamp_value), c.stamp_value); + w32(cmd, meta + offset_of!(Meta, stamp_slot), q.slot); + // evctl_index 0 (13.5 fixed), flush_stamps 0, uuid (u64 at 0x908) 0, event_seq 0. + w64(cmd, offset_of!(Rf, unk_buf_10), 1); + w64( + cmd, + offset_of!(Rf, timestamp_pointers.start_addr), + c.timestamps, + ); + w64( + cmd, + offset_of!(Rf, timestamp_pointers.end_addr), + c.timestamps + 8, + ); + let command_time = va(frag_at(offset_of!(Rf, command_time))); + let ts = va(frag_at(offset_of!(Rf, timestamp_pointers))); + put64(cmd, 0x948, timestamps[0]); + put64(cmd, 0x950, timestamps[1]); + let internal0 = va(0x980); + let internal1 = va(0x89c); + let (jp1, jp2) = (va(0x80), va(0x3c8)); + let busy = va(frag_at(offset_of!(Rf, busy_flag))); + let unk_pointee = va(frag_at(offset_of!(Rf, unk_pointee))); + let flag = va(frag_at(offset_of!(Rf, unk_v13_3))); + let flag758 = va(frag_at(offset_of!(Rf, unk_758_flag))); + let unk_buf_0 = va(frag_at(offset_of!(Rf, unk_buf_0))); + if (busy, unk_pointee, flag, flag758, unk_buf_0, command_time) + != ( + va(0x888), + va(0x8d8), + va(0x8dc), + va(0x770), + va(0x918), + va(0x930), + ) + { + return Err(EINVAL); + } + + // op 7 StartFragment (0x1b4). + let s = stream; + put32(s, 0, 7); + put64(s, 0x04, jp2); + put64(s, 0x0c, jp1); + put64(s, 0x14, scene_va); + put64(s, 0x1c, fragment_state); + put64(s, 0x24, busy); + put64(s, 0x2c, scene_va + 0x3c); + put64(s, 0x34, unk_pointee); + put64(s, 0x3c, flag); + put64(s, 0x44, q.queue); + put64(s, 0x4c, c.cmd_va); + put32(s, 0x54, c.context); + put32(s, 0x58, 1); + put32(s, 0x60, scene.slot()); + put32(s, 0x64, 0); // sync_grow + put32(s, 0x68, 0); // event_seq + put32(s, 0x6c, 0); // evctl_index + put64(s, 0x74, flag758); + put64(s, 0x7c, unk_buf_0); + put64(s, 0x98, 0); // uuid + s[0xa0..0x1a0].copy_from_slice(&attachments.0[..0x100]); + put32(s, 0x1a0, u32::from(attachments.count())); + put64(s, 0x1a8, c.sequence); + put32(s, 0x1b0, q.slot); + timestamp_op( + s, + 0x1b4, + true, + q, + command_time, + ts, + internal0, + internal1, + timestamps, + ); + put32(s, 0x200, 0x0001_0000); // wait for the fragment pipe + timestamp_op( + s, + 0x204, + false, + q, + command_time, + ts, + internal0, + internal1, + timestamps, + ); + // op 8 FinalizeFragment (0xbc). + let fin = 0x250; + put32(s, fin, 8); + put64(s, fin + 0x04, 0); // uuid + put64(s, fin + 0x0c, q.fw_stamp); + put32(s, fin + 0x14, c.stamp_value); + put64(s, fin + 0x1c, scene_va); + put64(s, fin + 0x24, info_va); + put32(s, fin + 0x2c, 1); + put64(s, fin + 0x30, fragment_state); + put64(s, fin + 0x38, unk_pointee); + put64(s, fin + 0x40, flag); + put64(s, fin + 0x48, busy); + put64(s, fin + 0x50, q.queue); + put64(s, fin + 0x58, c.cmd_va); + put32(s, fin + 0x60, c.context); + put64(s, fin + 0x64, flag758); + put32(s, fin + 0x98, (-(fin as i32)) as u32); + s[fin + 0x9c] = 0; + put64(s, fin + 0xad, va(0x970)); + put32(s, fin + 0xb5, q.slot); + put32(s, fin + 0xbc, 0x4000_0002); + debug_assert!(fin + 0xc0 <= FRAG_STREAM as usize); + Ok(()) +} diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 0ce309d51dc768..211a30b598a3c1 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -9,6 +9,7 @@ //! that manager's own root. use super::*; +use crate::g14_v27_2_abi::{self, GrowRequest, QueueError}; use crate::g17::fw::m5::initdata as abi; use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; use crate::m3::m3_init_26 as directory26; @@ -26,6 +27,9 @@ const COMPUTE: usize = 2; const PRIORITY_GROUP: usize = 2; const PRIORITY_ROW: usize = 2; /// The submission descriptor the queue publishes on (three per group). +const RENDER_GROUP: usize = 0; +pub(crate) const TILER: usize = 0; +pub(crate) const FRAGMENT: usize = 1; const SUBMISSION_RING: usize = 3 * PRIORITY_GROUP + COMPUTE; /// Firmware event, log, trace and statistics rings in the 34-entry channel list. const EVENT_RING: usize = 13; @@ -154,8 +158,99 @@ fn encode_compute( put32(stream, finish + 0x84, 0x4000_0002); } -/// The root's queue and the kernel-owned boot job published on it: one compute dispatch of an -/// empty control stream in context 0, which the firmware must retire before clients run. +/// A persistent firmware queue with a separate scheduler context and stamp slot per data master. +struct DmQueue { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + pointers: fw::types::GpuArray, + event: event::Event, + announced: core::sync::atomic::AtomicBool, + _scheduler: fw::types::GpuArray, + _stamps: fw::types::GpuArray, +} + +impl DmQueue { + fn new(alloc: &mut KernelAllocators, event: event::Event, priority: usize) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut queue_stamps = alloc.shared.array_empty::(0x18)?; + let queue_stamps_va = queue_stamps.gpu_va().get(); + put64(queue_stamps.as_mut_slice(), 8, queue_stamps_va); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, queue_stamps_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + put64(q, offset, value); + } + // The kernel-owned queue has no owning process. + for offset in [0x2c, 0x4c, 0x50] { + put32(q, offset, u32::MAX); + } + let row = crate::fw::workqueue::raw::PRIORITY[priority]; + put32(q, 0x30, row.0); + put32(q, 0x34, row.1); + put64(q, 0x38, row.2.0); + put32(q, 0x40, row.3); + put32(q, 0x44, row.4); + // The current lane stays at the all-ones sentinel; the firmware assigns it. + put32(q, 0x48, u32::MAX); + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + put32(positions.as_mut_slice(), 0x50, QUEUE_CAPACITY); + for mapping in [&positions, &pointers, &scheduler, &queue_stamps] { + crate::pgtable::clean_poc(mapping.as_slice().as_ptr(), mapping.as_slice().len()); + } + Ok(Self { queue, positions, pointers, event, + announced: core::sync::atomic::AtomicBool::new(false), + _scheduler: scheduler, _stamps: queue_stamps }) + } + + fn info(&self, engine_state: u64) -> QueueInfo { + QueueInfo { + queue: self.queue.gpu_va().get(), + slot: self.event.slot(), + stamp: u64::from(self.event.stamp_pointer()), + fw_stamp: u64::from(self.event.fw_stamp_pointer()), + compute_state: engine_state, + } + } +} + +/// A prepared submission has written only unowned ring entries. Publishing its cursors is +/// infallible, so a pair can be staged before either of its queues becomes firmware-visible. +pub(crate) struct Submission<'a> { + head: &'a core::sync::atomic::AtomicU32, + positions: &'a [u8], + target: u32, + producer: &'a core::sync::atomic::AtomicU32, + indices: &'a [u8], + next: u32, + announced: Option<&'a core::sync::atomic::AtomicBool>, +} + +impl Submission<'_> { + pub(crate) fn target(&self) -> u32 { self.target } + + pub(crate) fn publish(self) { + self.head.store(self.target, Ordering::Release); + crate::pgtable::clean_poc(self.positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + self.producer.store(self.next, Ordering::Release); + crate::pgtable::clean_poc(self.indices.as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + if let Some(announced) = self.announced { + announced.store(true, Ordering::Release); + } + } +} + +/// The kernel-owned boot dispatch must retire before clients use the compute queue. struct BootJob { queue: fw::types::GpuArray, positions: fw::types::GpuArray, @@ -280,6 +375,9 @@ impl BootJob { /// translates. Slots are reused in order. pub(crate) const POOL_SLOTS: usize = 48; +const COMMAND_STRIDE: usize = 0x1000; +const STREAM_STRIDE: usize = 0x400; + pub(crate) struct CommandPool { commands: fw::types::GpuArray, streams: fw::types::GpuArray, @@ -291,8 +389,8 @@ pub(crate) struct CommandPool { impl CommandPool { pub(crate) fn new(alloc: &mut KernelAllocators, cfg: &'static hw::HwConfig) -> Result { - let commands = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; - let streams = alloc.private.array_empty::(POOL_SLOTS * 0x400)?; + let commands = alloc.private.array_empty::(POOL_SLOTS * COMMAND_STRIDE)?; + let streams = alloc.private.array_empty::(POOL_SLOTS * STREAM_STRIDE)?; let mut tracking = alloc.private.array_empty::(POOL_SLOTS * 0x100)?; // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. let cursors = alloc.shared.array_empty::(POOL_SLOTS * 0x40)?; @@ -307,24 +405,37 @@ impl CommandPool { /// Builds slot `i` for `job` and returns the command's firmware VA. pub(crate) fn encode(&mut self, i: usize, q: &QueueInfo, stamp_value: u32, job: &ComputeJob) -> Result { + let preempt1 = self.preempt1; + self.encode_with(i, job.context, job.sequence, stamp_value, |cmd, stream, common| { + encode_compute(cmd, common.cmd_va, stream, common.stream_va, common.tracking, + common.timestamps, preempt1, q, stamp_value, job); + Ok(()) + }) + } + + pub(crate) fn encode_with( + &mut self, i: usize, context: u32, sequence: u64, stamp_value: u32, + encode: impl FnOnce(&mut [u8], &mut [u8], crate::g14_v27_2_render::Common) -> Result, + ) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } - let cmd_va = self.commands.gpu_va().get() + (i * 0x400) as u64; - let stream_va = self.streams.gpu_va().get() + (i * 0x400) as u64; + let cmd_va = self.commands.gpu_va().get() + (i * COMMAND_STRIDE) as u64; + let stream_va = self.streams.gpu_va().get() + (i * STREAM_STRIDE) as u64; let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; - // The firmware keeps 0xc8 bytes of the tracking slot; start each use cleared. let tracking = &mut self.tracking.as_mut_slice()[i * 0x100..(i + 1) * 0x100]; tracking[8..].fill(0); crate::pgtable::clean_poc(tracking.as_ptr(), tracking.len()); let stamps = &mut self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80]; stamps.fill(0); - crate::pgtable::clean_poc(stamps.as_ptr(), 0x80); - let cmd = &mut self.commands.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + crate::pgtable::clean_poc(stamps.as_ptr(), stamps.len()); + let cmd = &mut self.commands.as_mut_slice()[i * COMMAND_STRIDE..(i + 1) * COMMAND_STRIDE]; cmd.fill(0); - let stream = &mut self.streams.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + let stream = &mut self.streams.as_mut_slice()[i * STREAM_STRIDE..(i + 1) * STREAM_STRIDE]; stream.fill(0); - encode_compute(cmd, cmd_va, stream, stream_va, tracking_va, timestamps_va, self.preempt1, - q, stamp_value, job); + encode(cmd, stream, crate::g14_v27_2_render::Common { + cmd_va, stream_va, tracking: tracking_va, timestamps: timestamps_va, + context, sequence, stamp_value, + })?; crate::pgtable::clean_poc(stream.as_ptr(), stream.len()); crate::pgtable::clean_poc(cmd.as_ptr(), cmd.len()); crate::pgtable::poc_barrier(); @@ -360,11 +471,41 @@ impl CommandPool { } } +pub(crate) enum FirmwareEvent { + Grow(GrowRequest), + ChannelError, + Notification, +} + +pub(crate) struct ControlReply<'a> { + state: &'a fw::types::GpuArray, + ring: &'a fw::types::GpuArray, + cursor: u32, +} + +impl ControlReply<'_> { + pub(crate) fn grow(self, request: GrowRequest, granted: bool) -> Result { + let record = request.reply(granted); + let at = self.cursor as usize * core::mem::size_of_val(&record); + for (index, word) in record.into_iter().enumerate() { + self.ring.shared_index(at + index * 4)?.store(word, Ordering::Relaxed); + } + crate::pgtable::clean_poc(self.ring.as_slice()[at..].as_ptr(), core::mem::size_of_val(&record)); + crate::pgtable::poc_barrier(); + self.state.shared_index(0x20)?.store((self.cursor + 1) % RING_RECORDS, Ordering::Release); + crate::pgtable::clean_poc(self.state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(()) + } +} + /// The firmware 27.2 root and every record it names. pub(crate) struct RootV27_2 { graph: Arc, boot: BootJob, compute_state: u64, + render_states: [u64; 2], + render_queues: [DmQueue; 2], channels: KVec>, _owners: KVec>, _register_mappings: KVec, @@ -412,42 +553,86 @@ impl RootV27_2 { Ok((Self::word(&self.boot.positions, 0x40)?, Self::word(&self.boot.positions, 0)?)) } - /// Publishes `command` as the queue's next command: pointer, queue head, then the compute - /// submission entry and its producer. - pub(crate) fn publish(&self, command: u64) -> Result { - let job = &self.boot; - let head = job.positions.shared_index(0x40)?; - let old = head.load(Ordering::Acquire); - let capacity = Self::word(&job.positions, 0x50)?; - if capacity == 0 || (old % capacity) as usize * 8 + 8 > job.pointers.as_slice().len() { - return Err(EINVAL); - } - let at = (old % capacity) as usize * 8; - job.pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); - job.pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); - crate::pgtable::clean_poc(job.pointers.as_slice()[at..].as_ptr(), 8); + pub(crate) fn render_queue(&self, dm: usize) -> (QueueInfo, event::EventValue) { + let queue = &self.render_queues[dm]; + (queue.info(self.render_states[dm]), queue.event.current()) + } + + pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); crate::pgtable::poc_barrier(); - let new = (old + 1) % capacity; - head.store(new, Ordering::Release); - crate::pgtable::clean_poc(job.positions.as_slice().as_ptr(), 0x60); + Ok(Self::word(&queue.positions, 0)? == target && queue.event.current() >= stamp) + } + + pub(crate) fn render_kick(dm: usize) -> u64 { + MSG_TX_DOORBELL | (4 * RENDER_GROUP + dm) as u64 + } + + pub(crate) fn stage_render(&self, dm: usize, commands: &[u64]) -> Result> { + let queue = self.render_queues.get(dm).ok_or(EINVAL)?; + self.stage_work(&queue.positions, &queue.pointers, queue.info(0), + Some(&queue.announced), RENDER_GROUP, dm, commands) + } + + pub(crate) fn stage_compute(&self, command: u64) -> Result> { + self.stage_work(&self.boot.positions, &self.boot.pointers, self.boot.info(self.compute_state), + None, PRIORITY_GROUP, COMPUTE, &[command]) + } + + #[allow(clippy::too_many_arguments)] + fn stage_work<'a>( + &'a self, positions: &'a fw::types::GpuArray, pointers: &fw::types::GpuArray, + queue: QueueInfo, announced: Option<&'a core::sync::atomic::AtomicBool>, + group: usize, dm: usize, commands: &[u64], + ) -> Result> { + let ring_index = 3 * group + dm; + let indices = &self.channels[2 * ring_index]; + let ring = &self.channels[2 * ring_index + 1]; + crate::pgtable::clean_invalidate_poc(positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(indices.as_slice().as_ptr(), 0x30); crate::pgtable::poc_barrier(); - let state = &self.channels[2 * SUBMISSION_RING]; - let ring = &self.channels[2 * SUBMISSION_RING + 1]; - let w = Self::word(state, 0x20)?; - if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } - let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; - let entry = crate::m3::submission_entry(COMPUTE as u32, job.queue.gpu_va().get(), - u16::try_from(new).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + + let head = positions.shared_index(0x40)?; + let old = head.load(Ordering::Acquire); + let capacity = Self::word(positions, 0x50)?; + let retired = Self::word(positions, 0)?; + let first = announced.is_some_and(|first| !first.load(Ordering::Acquire)); + if capacity as usize > pointers.len() / 8 || (first && old != retired) { + return Err(EIO); + } + let count = u32::try_from(commands.len()).map_err(|_| EINVAL)?; + let target = g14_v27_2_abi::queue_head(capacity, old, retired, count).map_err(|error| { + match error { + QueueError::Geometry => EIO, + QueueError::Full => EBUSY, + } + })?; + + let producer = indices.shared_index(0x20)?; + let w = producer.load(Ordering::Acquire); + let r = Self::word(indices, 0)?; + if w >= RING_RECORDS || r >= RING_RECORDS { return Err(EIO); } + let next = (w + 1) % RING_RECORDS; + if next == r { return Err(EBUSY); } + let slot = u8::try_from(queue.slot).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(dm as u32, queue.queue, + u16::try_from(target).map_err(|_| EINVAL)?, slot, first).map_err(|_| EINVAL)?; let base = w as usize * entry.len(); - for (k, word) in entry.chunks(4).enumerate() { - ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + for (index, &command) in commands.iter().enumerate() { + let at = ((old as usize + index) % capacity as usize) * 8; + pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); + pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); + crate::pgtable::clean_poc(pointers.as_slice()[at..].as_ptr(), 8); + } + for (index, word) in entry.chunks_exact(4).enumerate() { + ring.shared_index(base + 4 * index)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); } crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); crate::pgtable::poc_barrier(); - state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); - crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); - crate::pgtable::poc_barrier(); - Ok(()) + Ok(Submission { head, positions: positions.as_slice(), target, producer, + indices: indices.as_slice(), next, announced }) } /// Publishes the boot job, whose command and ring entry the root already holds. The GPU @@ -486,10 +671,61 @@ impl RootV27_2 { && job.event.current().raw() == job.expected_stamp) } - /// Consumes everything the firmware published on its statistics, event, log and trace - /// rings. The firmware waits for space when one is full, and host consumer advancement is - /// the acknowledgement; completion is followed through the queue's position block, so the - /// records are not kept. + pub(crate) fn peek_event(&self) -> Result> { + use crate::m3::m3_channel_format::RECEIVE_BYTES; + let state = &self.channels[2 * EVENT_RING]; + let ring = &self.channels[2 * EVENT_RING + 1]; + crate::pgtable::clean_invalidate_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + let (read, write) = (Self::word(state, 0)?, Self::word(state, 0x20)?); + if read >= RING_RECORDS || write >= RING_RECORDS { return Err(EIO); } + if read == write { return Ok(None); } + let at = read as usize * RECEIVE_BYTES; + crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); + crate::pgtable::poc_barrier(); + let word = |offset| Self::word(ring, at + offset); + let event = match word(0)? { + 6 => FirmwareEvent::Grow(GrowRequest::decode([ + word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, + ])), + 7 => FirmwareEvent::ChannelError, + _ => FirmwareEvent::Notification, + }; + Ok(Some((read, event))) + } + + pub(crate) fn consume_event(&self, cursor: u32) -> Result { + let state = &self.channels[2 * EVENT_RING]; + state.shared_index(0)?.store((cursor + 1) % RING_RECORDS, Ordering::Release); + crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(()) + } + + pub(crate) fn halt_count(&self) -> Result { + const OFFSET: usize = 0x4bf0; + crate::pgtable::clean_invalidate_poc(self.control.as_slice()[OFFSET..].as_ptr(), 8); + crate::pgtable::poc_barrier(); + Ok(u64::from(Self::word(&self.control, OFFSET)?) + | (u64::from(Self::word(&self.control, OFFSET + 4)?) << 32)) + } + + pub(crate) fn reserve_control_reply(&self) -> Result>> { + let state = &self.channels[2 * crate::m3::DEVICE_CONTROL]; + crate::pgtable::clean_invalidate_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + let write = Self::word(state, 0x20)?; + let consumers = [Self::word(state, 0)?, Self::word(state, 0x10)?]; + if write >= RING_RECORDS || consumers.iter().any(|&cursor| cursor >= RING_RECORDS) { + return Err(EIO); + } + let next = (write + 1) % RING_RECORDS; + if consumers.contains(&next) { return Ok(None); } + Ok(Some(ControlReply { state, ring: &self.channels[2 * crate::m3::DEVICE_CONTROL + 1], + cursor: write })) + } + + /// Drain the telemetry rings. The event ring is consumed separately after servicing each event. pub(crate) fn drain(&self) -> Result { let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { let write = Self::word(state, base + 0x20)?; @@ -501,7 +737,6 @@ impl RootV27_2 { Ok(()) }; consume(&self.channels[2 * STATISTICS_RING], 0, RING_RECORDS)?; - consume(&self.channels[2 * EVENT_RING], 0, RING_RECORDS)?; // One log ring per log thread, state blocks 0x30 apart. for thread in 0..directory26::LOG_THREADS { consume(&self.channels[2 * LOG_RINGS], thread * 0x30, RING_RECORDS)?; @@ -537,26 +772,30 @@ impl RootV27_2 { Ok([Self::word(ring, 0)?, Self::word(ring, 0x10)?, Self::word(ring, 0x20)?]) } - /// Publishes one of the two pre-encoded idle-policy records on the device-control ring: - /// keep powered first, then allow off. Returns the ring cursor and the counted generation - /// the firmware acknowledges, which follows the larger of the host's last publication and - /// the firmware's consumed count. + /// Publishes an idle action and its acknowledged generation on an idle control channel. pub(crate) fn publish_idle_policy(&self, allow_off: bool) -> Result<(u32, u32)> { - let cursor = u32::from(allow_off); let host = self.globals.shared_index(0xe40)?; let firmware = self.idle_acknowledgement()?; let producer = self.channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; - if Self::word(&self.status, 0x14)? != 1 || - crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)? != cursor { - return Err(EAGAIN); - } + if Self::word(&self.status, 0x14)? != 1 { return Err(EAGAIN); } + let cursor = crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)?; let action = crate::m3::Action::Idle { enabled: allow_off }; let generation = action.generation(host.load(Ordering::Acquire), firmware).map_err(|_| EOVERFLOW)?; + let mut record = [0; crate::m3::CONTROL_BYTES]; + action.encode(&mut record).map_err(|_| EINVAL)?; + let ring = &self.channels[2 * crate::m3::DEVICE_CONTROL + 1]; + let at = cursor as usize * record.len(); + for (i, word) in record.chunks_exact(4).enumerate() { + ring.shared_index(at + i * 4)?.store( + u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[at..].as_ptr(), record.len()); host.store(generation, Ordering::Release); crate::pgtable::poc_barrier(); - producer.store(cursor + 1, Ordering::Release); + let next = (cursor + 1) % RING_RECORDS; + producer.store(next, Ordering::Release); crate::pgtable::poc_barrier(); - Ok((cursor + 1, generation)) + Ok((next, generation)) } /// Builds the root, the boot job and every record they name. @@ -618,15 +857,7 @@ impl RootV27_2 { ring[..entry.len()].copy_from_slice(&entry); crate::pgtable::clean_poc(ring.as_ptr(), ring.len()); } - { - // The two idle-policy records: keep powered, then allow off. - let records = &mut channels[2 * crate::m3::DEVICE_CONTROL + 1].as_mut_slice() - [..2 * crate::m3::CONTROL_BYTES]; - for (index, record) in records.chunks_exact_mut(crate::m3::CONTROL_BYTES).enumerate() { - crate::m3::Action::Idle { enabled: index == 1 }.encode(record).map_err(|_| EINVAL)?; - } - crate::pgtable::clean_poc(records.as_ptr(), records.len()); - } + let mut directory = alloc.private.array_empty::(0x4c8)?; let bytes = directory.as_mut_slice(); @@ -761,6 +992,7 @@ impl RootV27_2 { let mut owners = KVec::new(); let mut controller = None; let mut compute_state = 0; + let mut render_states = [0; 2]; for (offset, size) in [(0x10, 0x88), (0x254, 0x678), (0x25c, 0x760), (0x264, 0x6d0), (0x26c, 0x60), (0x485, 0x6c48)] { let mut owner = alloc.private.array_empty::(size)?; @@ -772,6 +1004,8 @@ impl RootV27_2 { if offset == 0x10 { put64(bytes, 8, address); } + if offset == 0x254 { render_states[TILER] = address; } + if offset == 0x25c { render_states[FRAGMENT] = address; } if offset == 0x264 { // The compute engine state the start and finish records name. compute_state = address; @@ -846,6 +1080,10 @@ impl RootV27_2 { crate::pgtable::clean_poc(data.as_ptr(), data.len()); } + let render_queues = [ + DmQueue::new(&mut alloc, graph.event_manager.try_get_polled()?, RENDER_GROUP)?, + DmQueue::new(&mut alloc, graph.event_manager.try_get_polled()?, RENDER_GROUP)?, + ]; boot.encode(&boot.info(compute_state)); let (page_size, page_bits, levels, descriptors) = graph.initdata.with(|r, _| (r.uat_page_size, r.uat_page_bits, r.uat_num_levels, r.uat_level_info)); @@ -853,7 +1091,7 @@ impl RootV27_2 { core::mem::drop(alloc); let root = fw::types::GpuObject::::new_init_prealloc(root, |_| try_init!(Self { - graph: graph.clone(), boot, compute_state, channels, _owners: owners, + graph: graph.clone(), boot, compute_state, render_states, render_queues, channels, _owners: owners, _register_mappings: register_mappings, _controller: controller, _directory: directory, boot_page, globals, status, control, power, extra, }), @@ -1022,3 +1260,11 @@ impl RootV27_2 { fn old_max_pstate(base: &fw::initdata::RuntimePointersG14V13_5) -> Result { Ok(base.hwdata_b.with(|old, _| old.max_pstate)) } + +impl GpuManagerG14V13_5 { + pub(crate) fn new_render_buffer(&self, ualloc: Arc>, + ualloc_priv: Arc>) -> Result { + let mut alloc = self.alloc(); + buffer::BufferG14V13_5::new(self, &mut alloc, ualloc, ualloc_priv, &self.buffer_mgr) + } +} diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index df0a26e4babc9d..ef478a2dab1acf 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -58,6 +58,8 @@ pub(crate) struct Packet { vm_job:Pin>>>, /// G14 firmware 27.2: the compute preemption buffer in the packet's VM, kept until retirement. pub(crate) preempt:Option>, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) render_queue: Option>, } /// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. #[derive(Clone)] @@ -238,6 +240,8 @@ pub(crate) struct Queue { /// preemption buffer it provides. preempt_alloc:Option<(Arc>,usize)>, /// Whether the SoC advertises early tiling (`m3_soc::Features::fragment_dependency`). + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: Option>, early_tiling:bool, wide_visibility:bool, urgency:u8, @@ -253,19 +257,23 @@ impl Queue { 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency,preempt_alloc:None}) + early_tiling,wide_visibility,urgency,preempt_alloc:None, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: None}) } /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, - ualloc_priv:Arc>,preempt_bytes:usize)->Result { + ualloc_priv:Arc>,preempt_bytes:usize, + render_queue: Arc)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; let urgency=3u8.saturating_sub(priority.min(3) as u8); let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, shared:Sink::G14V27_2(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_g14_queue"),kernel::static_lock_class!())?, - early_tiling:false,wide_visibility:false,urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes))}) + early_tiling:false,wide_visibility:false,urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), + render_queue: Some(render_queue)}) } } impl queue::Queue for Queue { @@ -274,12 +282,7 @@ impl queue::Queue for Queue { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { - // Only the M3 runtime renders; the G14 firmware-27.2 runtime is compute-only. - #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] - if let agx_uapi::ParsedHardwareCommand::Render{..}=command {return Err(EINVAL);} - #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); @@ -331,7 +334,9 @@ impl queue::Queue for Queue { Some(alloc.lock().array_empty::(*bytes)?), _ => None, }; - let packet=Arc::new(Packet{preempt,vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, + let packet=Arc::new(Packet{preempt, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + render_queue: self.render_queue.clone(),vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; @@ -364,14 +369,16 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) Ok(out) } -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, early_tiling: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; if r.sample_size % 8 != 0 {return Err(ENOTSUPP);} let empty = agx_uapi::UapiHelperProgram { binary:0, config:0, data:0 }; // Early tiling (render flag bit 5) only where it is advertised. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let stage_scope=if early_tiling && crate::m3::m3_params::early_tiling() {1<<5} else {0}; + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + let stage_scope = { let _ = early_tiling; 0 }; if r.flags & !(2|16|(1<<18)|stage_scope) != 0 || !matches!(r.samples, 1 | 2 | 4) || r.sampler_count != 0 || r.sampler_heap != 0 || r.vertex_helper != empty || r.fragment_helper != empty diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eec633d1301991..74ed39974f7590 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -72,9 +72,9 @@ pub(crate) fn t8122_admitted(pdev: &platform::Device>) -> Result<&'stat // The T8122 runtime, ported from the 7.1.12 release-20 kernel (c46d7dcdb871). // The 26.x submission front end, shared with the G14 firmware-27.2 runtime. #[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] -mod agx_attachments; +pub(crate) mod agx_attachments; #[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] -mod agx_compute; +pub(crate) mod agx_compute; #[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] diff --git a/drivers/gpu/drm/asahi/queue/render.rs b/drivers/gpu/drm/asahi/queue/render.rs index fa837163297196..490ebd1cd7c5cd 100644 --- a/drivers/gpu/drm/asahi/queue/render.rs +++ b/drivers/gpu/drm/asahi/queue/render.rs @@ -47,7 +47,7 @@ impl super::QueueInner::ver { /// This validates the flags and dimensions of the command first, so that every caller, /// including the submission-wide TVB sizing pass that runs before [`Self::submit_render`], /// rejects a malformed command with `EINVAL` before any arithmetic on its dimensions. - fn get_tiling_params( + pub(crate) fn get_tiling_params( cmdbuf: &uapi::drm_asahi_cmd_render, num_clusters: u32, ) -> Result { From 645c79a53654d61cbd624069178005b93f17670b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 22:04:55 +1100 Subject: [PATCH 0741/1514] drm/asahi: synchronize G14 completion stamps for the firmware UAT Clean initial shared stamps and parameter-buffer counters before publication. Read the firmware-driven stamp after cache maintenance when observing retirement. Keep the tiler event-control index consistent between the record and the start operation, and report queue progress on timeout. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 9 +++++++ drivers/gpu/drm/asahi/event.rs | 20 +++++++++++++++ drivers/gpu/drm/asahi/g14_v27_2.rs | 2 ++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 4 +-- drivers/gpu/drm/asahi/gpu/v27_2.rs | 31 +++++++++++++++++++---- 5 files changed, 59 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index a1d7fdd486b989..31f1dd881255df 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -326,6 +326,15 @@ impl BufferG14V13_5 { }) } + pub(crate) fn increment_parameter_counter(&self) { + self.increment(); + let inner = self.inner.lock(); + inner.info.counter.with(|raw, _| { + crate::pgtable::clean_poc(core::ptr::from_ref(raw).cast(), core::mem::size_of_val(raw)); + }); + crate::pgtable::poc_barrier(); + } + /// The 27.2 firmware owns the page list once bound. Publish only new block descriptors /// and the block-control producer, using the legacy manager for backing allocation. pub(crate) fn ensure_parameter_blocks(&self, count: usize) -> Result { diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index dbea26792b6c0c..28e70c2fb09f75 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -124,6 +124,14 @@ impl EventInner { // keeps the GpuObject the stamp is contained within alive. EventValue(unsafe { &*self.stamp }.load(Ordering::Acquire)) } + + /// Read a completion stamp written by an agent outside the CPU coherency domain. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn current_noncoherent(&self) -> EventValue { + crate::pgtable::clean_invalidate_poc(self.stamp.cast(), core::mem::size_of::()); + crate::pgtable::poc_barrier(); + self.current() + } } impl slotalloc::SlotItem for EventInner { @@ -204,6 +212,18 @@ impl EventManager { Ok(ev) } + /// Make freshly initialized stamps visible before a non-coherent firmware starts. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn sync_initial_stamps(&self) { + self.alloc.with_inner(|inner| { + let stamps = inner.stamps.as_slice(); + let fw_stamps = inner.fw_stamps.as_slice(); + crate::pgtable::clean_poc(stamps.as_ptr().cast(), core::mem::size_of_val(stamps)); + crate::pgtable::clean_poc(fw_stamps.as_ptr().cast(), core::mem::size_of_val(fw_stamps)); + }); + crate::pgtable::poc_barrier(); + } + /// Reserve the normal stamp pair for a kernel queue that polls its own completion. #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn try_get_polled(&self) -> Result { diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 6879bfaa952f2f..44212aad4a19c3 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -694,6 +694,7 @@ impl Runtime { } } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); + state.root.log_timeout(&self.dev); return Err(ETIMEDOUT); } Ok(()) @@ -785,6 +786,7 @@ impl Runtime { if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); + state.root.log_timeout(&self.dev); self.fail_all(state, ETIMEDOUT); return; } diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index a1c2b02ed49a4c..c6c7a2b4766cd5 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -179,7 +179,7 @@ impl QueueRender { if let Some(binding) = Option::as_mut(&mut *self.binding.lock()) { binding.initialized = true; binding.blocks = self.buffer.block_count(); - self.buffer.increment(); + self.buffer.increment_parameter_counter(); } } @@ -445,7 +445,7 @@ pub(crate) fn encode_vertex( put32(s, 0x3c, c.context); put32(s, 0x40, 1); put32(s, 0x48, scene.slot()); - put32(s, 0x54, q.slot); + // Match the command metadata: the default event-control index is zero. put64(s, 0x5c, unk_pointee); put64(s, 0x64, unk_buf_0); s[0x80..0x180].copy_from_slice(&attachments.0[..0x100]); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 211a30b598a3c1..db9bf1a3bc8fdf 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -9,6 +9,7 @@ //! that manager's own root. use super::*; +use kernel::device; use crate::g14_v27_2_abi::{self, GrowRequest, QueueError}; use crate::g17::fw::m5::initdata as abi; use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; @@ -335,7 +336,7 @@ impl BootJob { for owner in [queue_stamps, scheduler, cursor] { owners.push(owner, GFP_KERNEL)?; } - let expected_stamp = event.current().next().raw(); + let expected_stamp = event.current_noncoherent().next().raw(); Ok(Self { queue, positions, pointers, command, stream, tracking, timestamps, event, expected_stamp, _owners: owners, _client: (mapping, object), client_va, preempt1: preempt1 as u64 }) @@ -537,7 +538,7 @@ impl RootV27_2 { /// The queue's identity for client commands, and the stamp value it last reached. pub(crate) fn queue(&self) -> (QueueInfo, event::EventValue) { - (self.boot.info(self.compute_state), self.boot.event.current()) + (self.boot.info(self.compute_state), self.boot.event.current_noncoherent()) } /// The queue's capacity (position block +0x50). @@ -555,14 +556,33 @@ impl RootV27_2 { pub(crate) fn render_queue(&self, dm: usize) -> (QueueInfo, event::EventValue) { let queue = &self.render_queues[dm]; - (queue.info(self.render_states[dm]), queue.event.current()) + (queue.info(self.render_states[dm]), queue.event.current_noncoherent()) } pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { let queue = &self.render_queues[dm]; crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); crate::pgtable::poc_barrier(); - Ok(Self::word(&queue.positions, 0)? == target && queue.event.current() >= stamp) + Ok(Self::word(&queue.positions, 0)? == target && queue.event.current_noncoherent() >= stamp) + } + + fn log_queue( + dev: &device::Device, name: &str, positions: &fw::types::GpuArray, + queue: &fw::types::GpuArray, stamp: &event::Event, + ) { + crate::pgtable::clean_invalidate_poc(positions.as_slice().as_ptr(), 0x60); + crate::pgtable::clean_invalidate_poc(queue.as_slice().as_ptr(), 0x90); + crate::pgtable::poc_barrier(); + dev_err!(dev, "GPU: {} queue head={:?} fetched={:?} retired={:?} scheduler={:?} stamp={:#x}\n", + name, Self::word(positions, 0x40), Self::word(positions, 0x30), + Self::word(positions, 0), Self::word(queue, 0x74), stamp.current_noncoherent().raw()); + } + + pub(crate) fn log_timeout(&self, dev: &device::Device) { + Self::log_queue(dev, "compute", &self.boot.positions, &self.boot.queue, &self.boot.event); + for (name, queue) in ["tiler", "fragment"].into_iter().zip(&self.render_queues) { + Self::log_queue(dev, name, &queue.positions, &queue.queue, &queue.event); + } } pub(crate) fn render_kick(dm: usize) -> u64 { @@ -668,7 +688,7 @@ impl RootV27_2 { Ok(Self::word(&self.channels[2 * SUBMISSION_RING], 0)? == 1 && Self::word(&job.positions, 0x30)? == 1 && Self::word(&job.positions, 0)? == 1 - && job.event.current().raw() == job.expected_stamp) + && job.event.current_noncoherent().raw() == job.expected_stamp) } pub(crate) fn peek_event(&self) -> Result> { @@ -829,6 +849,7 @@ impl RootV27_2 { let sram_table = Self::sram_table(states.len())?; let mut alloc = graph.alloc(); + graph.event_manager.sync_initial_stamps(); let mut boot = BootJob::new(&mut alloc, graph.event_manager.try_get_polled()?, graph.kernel_uat(), &graph.dev, cfg)?; // The 0x60-byte root child and the eight-byte temperature generation occupy From f15f3d1fee55fec1a261b8a6f37df9684da34b26 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:44 +1100 Subject: [PATCH 0742/1514] drm/asahi: drain G14 submissions before completing or stopping Close submission admission under the runtime mutex before unbind drains the queue. If staging a later command fails, retain the packet and its VM guard until the already-published prefix retires, then complete the fence with the staging error. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 37 ++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 44212aad4a19c3..3e805875ebdef6 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -301,6 +301,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'sta struct Inflight { packet: Arc, last: bool, + publication_error: Option, stamp: event::EventValue, slot: usize, /// Queue publications up to and including this command, counted from take-over. @@ -349,11 +350,25 @@ struct State { inflight: KVec, rendering: Option, pending: KVec<(Arc, usize)>, + accepting: bool, submitted: u64, retired: u64, } impl State { + /// Stop publishing this packet. Report failure only once any published prefix retires. + fn fail_publication(&mut self, packet: &Arc, err: Error) { + let _ = self.pending.remove(0); + if let Some(last) = self.inflight.iter_mut().rev() + .find(|flight| Arc::ptr_eq(&flight.packet, packet)) + { + last.publication_error = Some(err); + } else { + packet.release_guard(); + packet.finish(Err(err)); + } + } + fn running(&self) -> bool { !self.inflight.is_empty() || self.rendering.is_some() } @@ -433,6 +448,7 @@ impl Runtime { let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } + if !state.accepting { return Err(ENODEV); } state.pending.push((packet, 0), GFP_KERNEL)?; self.pump(state); Ok(()) @@ -542,11 +558,7 @@ impl Runtime { Err(EBUSY) if state.running() => return, Err(err) => { dev_err!(self.dev, "GPU: command publication failed {:?}\n", err); - let _ = state.pending.remove(0); - if !state.owns(&packet) { - packet.release_guard(); - } - packet.finish(Err(err)); + state.fail_publication(&packet, err); } } } @@ -572,7 +584,7 @@ impl Runtime { let ordinal = state.published + 1; // Commit ownership before the firmware can see the new work. state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); submission.publish(); state.last = stamp; @@ -775,7 +787,10 @@ impl Runtime { if state.retired_total >= front.ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); - if done.last { + if let Some(err) = done.publication_error { + done.packet.release_guard(); + done.packet.finish(Err(err)); + } else if done.last { done.packet.retired(); } else if !state.owns(&done.packet) && !state.pending(&done.packet) { done.packet.release_guard(); @@ -844,17 +859,20 @@ impl Runtime { /// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC /// with every mapping still in place (RTKit power-off if the firmware does not stop). pub(crate) fn stop(&self) { - // Let published work retire; the service signals `idle` when nothing is left. + // Close admission while the service retires work already accepted. { let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return; }; + state.accepting = false; let start = Instant::::now(); while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) { let Some(state) = guard.as_ref() else { break; }; if !state.running() && state.pending.is_empty() { break; } let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS)); } + // Serialize the last permitted publication with the transition to shutdown. + self.healthy.store(false, Ordering::Release); } - self.healthy.store(false, Ordering::Release); // Nothing queues service work after the detach, and none is queued or running once the // drain returns, so no work outlives the module. drop(self.notify.detach()); @@ -969,6 +987,7 @@ impl Backend { inflight: KVec::new(), rendering: None, pending: KVec::new(), + accepting: true, submitted: 0, retired: 0, }); From 4758c76371595ce576ce2c620bd475d9f4eac9bf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:32:45 +1100 Subject: [PATCH 0743/1514] drm/asahi: require the firmware handoff SRAM voltage table Read each SRAM operating-point voltage from the loader-provided ADT table. Refuse the handoff if the table is absent or inconsistent with the core operating points. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index db9bf1a3bc8fdf..ede5ceb0dc787b 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -983,18 +983,11 @@ impl RootV27_2 { } for (i, state) in states.iter().enumerate() { let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; - let sram_mv = match &sram_table { - Some(table) => { - let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); - if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz { - return Err(EINVAL); - } - let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); - if value < *mv || value > 1100 { return Err(EINVAL); } - value - } - None => (*mv).max(850), - }; + let (freq, voltage) = sram_table[i * 8..i * 8 + 8].split_at(4); + let sram_mv = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || sram_mv < *mv || sram_mv == 0 { + return Err(EINVAL); + } let mhz = state.freq_hz / 1_000_000; for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { put32(hw, series + i * 4, mhz); @@ -1143,8 +1136,8 @@ impl RootV27_2 { } /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` - /// (frequency and SRAM millivolts per state), if it published one. The node itself must exist. - fn sram_table(states: usize) -> Result>> { + /// (frequency and SRAM millivolts per state). + fn sram_table(states: usize) -> Result> { let chosen = kernel::of::chosen().ok_or(ENODEV)?; let is = |name: Option>, want: &[u8]| { name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) @@ -1153,8 +1146,9 @@ impl RootV27_2 { if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } for child in parent.children() { if is(child.get_opt_property::>(c"name")?, b"sgx") { - let table = child.get_opt_property::>(c"adt-perf-states-sram")?; - if table.as_ref().is_some_and(|t| t.len() != states * 8) { return Err(EINVAL); } + let table = child.get_opt_property::>(c"adt-perf-states-sram")? + .ok_or(ENODEV)?; + if table.len() != states * 8 { return Err(EINVAL); } return Ok(table); } } From c73aedd34bfbe00815aaee616c9cb40fb0e4fb1c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 23:35:45 +1100 Subject: [PATCH 0744/1514] drm/asahi: retry G14 firmware queue backpressure Firmware can release a command slot or consume a device-control entry without sending another notification. Recheck those resources on the ordered service queue when progress is blocked and bound the wait before reporting a timeout. Keep a pending growth request on the event ring until its reply is published. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 120 +++++++++++++++++++++++++---- drivers/gpu/drm/asahi/gpu/v27_2.rs | 4 + 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 3e805875ebdef6..6471ce82af343d 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -13,7 +13,8 @@ //! publishing records on its event, statistics and log rings: each one runs the service, which //! consumes those rings (the firmware waits for space in them) and retires completed commands. //! Completion follows the queue's retired position, which the firmware advances in order. There -//! is no timer: the DRM scheduler's job timeout runs the service as the backstop for a hang. +//! is a delayed service run while waiting for firmware to free a pool slot or make room on +//! the device-control ring. These changes need not generate a notification. use core::ops::Range; use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -21,14 +22,14 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ device, drm::sched, - new_condvar, new_mutex, new_spinlock, new_work, + new_condvar, new_delayed_work, new_mutex, new_spinlock, new_work, platform, prelude::*, soc::apple::rtkit, sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, - workqueue::{impl_has_work, OwnedQueue, Work, WorkItem}, + workqueue::{impl_has_delayed_work, impl_has_work, DelayedWork, OwnedQueue, Work, WorkItem}, }; use crate::{ @@ -53,6 +54,33 @@ const COMMAND_TIMEOUT_MS: i64 = 5000; const STOP_DRAIN_MS: u32 = 2000; /// Bound on the wait between a command's completion stamp and its retired position. const RETIRE_WAIT_US: i64 = 2000; +/// Poll interval when firmware can release a resource without an interrupt. +const RESOURCE_RETRY_MS: u32 = 10; +/// Work item for the poll. Ordinary firmware notifications can still queue immediate work. +const RETRY_WORK: u64 = 1; + +struct FirmwareWait { + since: Instant, + last_kick: Option>, +} + +impl FirmwareWait { + /// Bound the wait even if the blocked command has not been published yet. + fn kick_due(wait: &mut Option) -> Result { + let now = Instant::now(); + let wait = wait.get_or_insert(Self { since: now, last_kick: None }); + if now - wait.since >= Delta::from_millis(COMMAND_TIMEOUT_MS) { + return Err(ETIMEDOUT); + } + if wait.last_kick.is_some_and(|last| { + now - last < Delta::from_millis(RESOURCE_RETRY_MS.into()) + }) { + return Ok(false); + } + wait.last_kick = Some(now); + Ok(true) + } +} /// The ASC control page, kept mapped until the firmware is stopped. pub(crate) struct AscControl(*mut u8); @@ -115,6 +143,17 @@ impl Notify { } } + /// Queues a poll while attached. Detaching also fences off poll requests before teardown. + fn retry(&self) { + if let Some(runtime) = self.runtime.lock().as_ref() { + if runtime.healthy() { + let _ = runtime.queue.enqueue_delayed::, RETRY_WORK>( + runtime.clone(), msecs_to_jiffies(RESOURCE_RETRY_MS), + ); + } + } + } + fn attach(&self, runtime: Arc) { *self.runtime.lock() = Some(runtime); } @@ -330,7 +369,8 @@ struct State { last: event::EventValue, sequence: u64, next_slot: usize, - waiting_unlink: bool, + waiting_unlink: Option, + waiting_control: Option, /// Publications and retirements counted on the queue's position block. published: u64, /// Completion stamps seen before the retired position they precede. @@ -400,7 +440,7 @@ pub(crate) struct Runtime { /// published across a system sleep. asleep: AtomicBool, notify: Arc, - /// Runs the service; only `Notify::wake` queues on it, and `stop` drains it. + /// Runs the service. Only `Notify` queues on it, and `stop` drains it. queue: OwnedQueue, #[pin] state: Mutex>, @@ -409,6 +449,8 @@ pub(crate) struct Runtime { idle: CondVar, #[pin] work: Work, + #[pin] + retry: DelayedWork, } impl_has_work! { @@ -422,6 +464,19 @@ impl WorkItem for Runtime { } } +impl_has_delayed_work! { + impl HasDelayedWork for Runtime { self.retry } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + if this.healthy() { + this.service(); + } + } +} + #[pinned_drop] impl PinnedDrop for Runtime { fn drop(self: Pin<&mut Self>) { @@ -464,6 +519,9 @@ impl Runtime { if !state.owns(packet) { packet.release_guard(); } + if state.pending.is_empty() { + state.waiting_unlink = None; + } } } @@ -517,14 +575,19 @@ impl Runtime { slots[found] = slot; found += 1; if found == count { - state.waiting_unlink = false; + state.waiting_unlink = None; return Ok(Some(slots)); } } - if !state.waiting_unlink { - state.waiting_unlink = true; + if FirmwareWait::kick_due(&mut state.waiting_unlink)? { state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?; + for dm in [TILER, FRAGMENT] { + if state.root.render_queue_announced(dm) { + state.peer.as_mut().send_message(EP_DOORBELL, RootV27_2::render_kick(dm))?; + } + } } + self.notify.retry(); Ok(None) } @@ -544,7 +607,11 @@ impl Runtime { let slots = match self.free_slots(state, count) { Ok(Some(slots)) => slots, Ok(None) => return, - Err(err) => { self.fail_all(state, err); return; } + Err(err) => { + dev_err!(self.dev, "GPU: command pool stalled: {:?}\n", err); + self.fail_all(state, err); + return; + } }; let last = index + 1 == packet.commands.len(); let result = match command { @@ -737,7 +804,17 @@ impl Runtime { let Some((cursor, event)) = state.root.peek_event()? else { break; }; match event { FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { - let Some(reply) = state.root.reserve_control_reply()? else { break; }; + let Some(reply) = state.root.reserve_control_reply()? else { + // Leave the GrowTVB request at the head of the event ring until + // there is space for its reply. + if FirmwareWait::kick_due(&mut state.waiting_control)? { + state.peer.as_mut().send_message( + EP_DOORBELL, gpu::DEVICE_CONTROL_KICK, + )?; + } + self.notify.retry(); + return Ok(()); + }; let granted = state.rendering.as_ref() .filter(|flight| flight.bind.slot() == request.vm && flight.scene.slot() == request.buffer) .and_then(|flight| flight.packet.render_queue.as_ref()) @@ -752,6 +829,7 @@ impl Runtime { } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } + state.waiting_control = None; state.root.consume_event(cursor)?; } Ok(()) @@ -759,13 +837,18 @@ impl Runtime { fn service_locked(&self, state: &mut State) { let _ = state.root.drain(); + if !self.healthy() { return; } if state.peer.is_crashed() { dev_err!(self.dev, "GPU firmware crashed; failing {} pending and {} published commands\n", state.pending.len(), state.inflight.len()); self.fail_all(state, EIO); return; } - if let Err(err) = self.process_events(state) { self.fail_all(state, err); return; } + if let Err(err) = self.process_events(state) { + dev_err!(self.dev, "GPU: event service failed: {:?}\n", err); + self.fail_all(state, err); + return; + } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } // The completion stamp is written before the firmware's post-processing advances the @@ -853,6 +936,7 @@ impl Runtime { let Some(state) = Option::as_mut(&mut *guard) else { return; }; dev_info!(self.dev, "GPU released after sleep: running={:?} pending={}\n", state.root.firmware_running(), state.pending.len()); + state.waiting_unlink = None; if self.healthy() { self.pump(state); } } @@ -873,9 +957,15 @@ impl Runtime { // Serialize the last permitted publication with the transition to shutdown. self.healthy.store(false, Ordering::Release); } - // Nothing queues service work after the detach, and none is queued or running once the - // drain returns, so no work outlives the module. + // Detach prevents new enqueues. Flush the delayed item before draining the queue, + // since a pending timer may not have queued its work yet. drop(self.notify.detach()); + // SAFETY: This is the initialized, pinned retry item. It cannot rearm after detach. + unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(&self.retry)); + let delayed = kernel::container_of!(work, kernel::bindings::delayed_work, work); + kernel::bindings::flush_delayed_work(delayed); + } self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; @@ -946,6 +1036,7 @@ impl Backend { state <- new_mutex!(None, "g14_v27_2::Runtime::state"), idle <- new_condvar!("g14_v27_2::Runtime::idle"), work <- new_work!("g14_v27_2::Runtime::work"), + retry <- new_delayed_work!("g14_v27_2::Runtime::retry"), }), GFP_KERNEL)) { Ok(runtime) => runtime, Err(e) => { @@ -974,7 +1065,8 @@ impl Backend { peer, root, pool, asc, queue, last, sequence: u64::from(head), next_slot: 0, - waiting_unlink: false, + waiting_unlink: None, + waiting_control: None, published: 0, late: 0, busy: 0, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index ede5ceb0dc787b..538e88eb6c1ba3 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -589,6 +589,10 @@ impl RootV27_2 { MSG_TX_DOORBELL | (4 * RENDER_GROUP + dm) as u64 } + pub(crate) fn render_queue_announced(&self, dm: usize) -> bool { + self.render_queues[dm].announced.load(Ordering::Acquire) + } + pub(crate) fn stage_render(&self, dm: usize, commands: &[u64]) -> Result> { let queue = self.render_queues.get(dm).ok_or(EINVAL)?; self.stage_work(&queue.positions, &queue.pointers, queue.info(0), From c17c2705e7c661077c1bbc7d9352d68f2cdb6c31 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:32:15 +1100 Subject: [PATCH 0745/1514] drm/asahi: map G14 parameter-buffer lists GPU read-write The parameter manager writes the parameter-buffer page and block lists while the tiler runs, and the firmware rebuilds the page list when the buffer grows. With the lists in a read-only GPU mapping, the first render on the J473 (G14G, firmware 27.2) left a pending MMU fault: a write to a read-only page by the parameter manager, in the client context's VM slot. The firmware then waited forever for the context's cache flush after the render, so no host completion stamp was written and later work stalled. Allocate both lists from the kernel GPU read-write range, owned by the buffer, and keep one allocation of that range alive from initialization so its page tables exist before the firmware window is mirrored. The 13.5 queue keeps its per-VM placement. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 44 ++++++++++++++++++++++-------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 9 +++++- drivers/gpu/drm/asahi/queue/mod.rs | 4 ++- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 31f1dd881255df..1680fd05d035b7 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -371,6 +371,13 @@ pub(crate) struct Buffer { inner: Arc>, } +/// Address space in which the parameter-buffer lists are visible to their consumers. +pub(crate) enum ParameterListPlacement { + VmPrivate, + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + KernelGpu, +} + #[versions(AGX)] impl Buffer::ver { /// Create a new Buffer for a given VM, given the per-VM allocators. @@ -380,6 +387,7 @@ impl Buffer::ver { ualloc: Arc>, ualloc_priv: Arc>, mgr: &BufferManager::ver, + list_placement: ParameterListPlacement, ) -> Result { // These are the typical max numbers on macOS. // 8GB machines have this halved. @@ -402,19 +410,33 @@ impl Buffer::ver { let preempt2_size = num_clusters_adj * gpu.get_cfg().preempt2_size; let preempt3_size = num_clusters_adj * gpu.get_cfg().preempt3_size; + let (page_list, block_list) = { + let mut vm_private; + let lists = match list_placement { + ParameterListPlacement::VmPrivate => { + vm_private = ualloc_priv.lock(); + &mut *vm_private + } + // The lists live in the kernel half of the UAT so the firmware can rebuild them. + // The parameter manager writes them while the render engines run, so the GPU + // mapping must be writable: a read-only mapping leaves a stalled write fault + // that blocks the context flush after the render and every later completion. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + ParameterListPlacement::KernelGpu => &mut alloc.gpu, + }; + ( + lists.array_empty_tagged(max_pages, b"PLST")?, + lists.array_empty_tagged(max_blocks * 2, b"BLST")?, + ) + }; let shared = &mut alloc.shared; let info = alloc.private.new_init( - { - let ualloc_priv = &ualloc_priv; - try_init!(buffer::Info::ver { - block_ctl: shared.new_default::()?, - counter: shared.new_default::()?, - page_list: ualloc_priv.lock().array_empty_tagged(max_pages, b"PLST")?, - block_list: ualloc_priv - .lock() - .array_empty_tagged(max_blocks * 2, b"BLST")?, - }) - }, + try_init!(buffer::Info::ver { + block_ctl: shared.new_default::()?, + counter: shared.new_default::()?, + page_list, + block_list, + }), |inner, _p| { try_init!(buffer::raw::Info::ver { gpu_counter: 0x0, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 538e88eb6c1ba3..8ea0fd153c82c3 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -1082,6 +1082,10 @@ impl RootV27_2 { put32(control.as_mut_slice(), 0x4c24, 1); owners.push(flush, GFP_KERNEL)?; } + // The firmware window mirrors only the kernel page tables that exist when it is + // installed. Keep one allocation of the GPU read-write range alive from here, so the + // tables that later hold the parameter-buffer lists are already visible to the firmware. + owners.push(alloc.gpu.array_empty::(0x4000)?, GFP_KERNEL)?; let mut power = alloc.shared.array_empty::(0x6a0)?; { // Cold mirrors of the controller's power and temperature-loop values. @@ -1284,6 +1288,9 @@ impl GpuManagerG14V13_5 { pub(crate) fn new_render_buffer(&self, ualloc: Arc>, ualloc_priv: Arc>) -> Result { let mut alloc = self.alloc(); - buffer::BufferG14V13_5::new(self, &mut alloc, ualloc, ualloc_priv, &self.buffer_mgr) + buffer::BufferG14V13_5::new( + self, &mut alloc, ualloc, ualloc_priv, &self.buffer_mgr, + buffer::ParameterListPlacement::KernelGpu, + ) } } diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 54891a1735f9a3..25622ca7e9946b 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -717,7 +717,9 @@ impl Queue::ver { )?; let entity = sched::Entity::new(&sched, sched::Priority::Kernel)?; - let buffer = buffer::Buffer::ver::new(gpu, alloc, ualloc.clone(), ualloc_priv, mgr)?; + let buffer = buffer::Buffer::ver::new( + gpu, alloc, ualloc.clone(), ualloc_priv, mgr, buffer::ParameterListPlacement::VmPrivate, + )?; let gpu_context = Arc::new( workqueue::GpuContext::new(dev.clone(), alloc, buffer.any_ref())?, From ec59bb6f2572dbcc6c26830d98b22d98d64c7c0f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 00:43:45 +1100 Subject: [PATCH 0746/1514] drm/asahi: select G14 by firmware compatibility and signal suspend drain Select the wire layout from the loader compatibility tuple before starting the GPU and pass the register description selected by the GPU compatible. Notify suspend when the in-flight queue empties. Pending commands stay held until resume, and unrelated wakeups exhaust the original timeout budget. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 40 ++++++++++++++++-------------- drivers/gpu/drm/asahi/g14_v27_2.rs | 29 ++++++++++++---------- 2 files changed, 37 insertions(+), 32 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 03ffba4433a865..bf014730a868e8 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -153,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver { /// Firmware interface selected by the hardware compatible. pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), + LegacyWithG14Handoff(&'static hw::HwConfig), G17(&'static g17::Config), /// M5 Pro, Max and Ultra: the ID registers select the configuration. G17M5, @@ -200,7 +201,7 @@ macro_rules! asahi_of_device_table { ), ( of::DeviceId::new(c"apple,agx-t8112"), - ProbeConfig::Legacy(&hw::t8112::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8112::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t6000"), @@ -376,8 +377,9 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); - let cfg = match info.ok_or(ENODEV)? { - ProbeConfig::Legacy(cfg) => *cfg, + let (cfg, has_g14_handoff) = match info.ok_or(ENODEV)? { + ProbeConfig::Legacy(cfg) => (*cfg, false), + ProbeConfig::LegacyWithG14Handoff(cfg) => (*cfg, true), ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) } @@ -391,16 +393,19 @@ impl platform::Driver for AsahiPlatformDriver { ProbeConfig::M5 => return Err(ENODEV), }; - // G14 with firmware 27.2 has its own root and start sequence (g14_v27_2.rs). - if (cfg.gpu_gen, cfg.gpu_variant) == (hw::GpuGen::G14, hw::GpuVariant::G) { - let version: Option> = pdev.as_ref().fwnode().ok_or(EIO)? - .property_read_array_vec(c"apple,firmware-version", 3)?.optional(); - if version.as_deref() == Some(&[27, 2, 0]) { - #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] - return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg); - #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] - return Err(ENODEV); - } + let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; + let compat: KVec = fwnode + .property_read_array_vec(c"apple,firmware-compat", 3)? + .required_by(pdev.as_ref())?; + + // The loader advertises the supported wire layout independently of the image version. + if has_g14_handoff && compat.as_slice() == [27, 2, 0] { + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + return AsahiPlatformDriver::probe_g14_v27_2( + pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2, + ); + #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] + return Err(ENODEV); } // SAFETY: The selected SoC's UAT output width bounds all device DMA. @@ -414,11 +419,6 @@ impl platform::Driver for AsahiPlatformDriver { // Start the coprocessor CPU, so UAT can initialize the handoff regs::Resources::start_cpu(pdev)?; - let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?; - let compat: KVec = fwnode - .property_read_array_vec(c"apple,firmware-compat", 3)? - .required_by(pdev.as_ref())?; - let drm = drm::UnregisteredDevice::::new(pdev, Ok(()))?; // SAFETY: Every adapter calls close_binding in unbind before devres; // probe errors drop this local owner while the bound callback is live. @@ -503,9 +503,11 @@ impl AsahiPlatformDriver { fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, ) -> Result> { let crate::g14_v27_2::Started { backend, drm, binding, resources } = - crate::g14_v27_2::start(pdev, cfg)?; + crate::g14_v27_2::start(pdev, cfg, registers, writable)?; let gpu = backend.clone() as Arc; let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); // SAFETY: The registration is stored in the platform data and unregistered when it is diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 6471ce82af343d..a119b246270118 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -26,7 +26,7 @@ use kernel::{ platform, prelude::*, soc::apple::rtkit, - sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock}, + sync::{aref::ARef, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock}, time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic}, uapi, workqueue::{impl_has_delayed_work, impl_has_work, DelayedWork, OwnedQueue, Work, WorkItem}, @@ -252,14 +252,14 @@ pub(crate) struct Started<'a> { } /// Starts the firmware and retires the boot job. -pub(crate) fn start<'a>(pdev: &'a platform::Device>, cfg: &'static hw::HwConfig) - -> Result> { +pub(crate) fn start<'a>( + pdev: &'a platform::Device>, + cfg: &'static hw::HwConfig, + registers: &'static [hw::RegisterV27_2], + writable: u64, +) -> Result> { use kernel::dma::{Device as _, DmaMask}; let dev: &device::Device = pdev.as_ref(); - let (registers, writable) = match cfg.chip_id { - 0x8112 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), - _ => return Err(ENODEV), - }; let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; @@ -795,7 +795,9 @@ impl Runtime { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { return; }; self.service_locked(state); - if !state.running() && state.pending.is_empty() { self.idle.notify_all(); } + if !state.running() && (state.pending.is_empty() || self.asleep.load(Ordering::Acquire)) { + self.idle.notify_all(); + } } fn process_events(&self, state: &mut State) -> Result { @@ -908,7 +910,7 @@ impl Runtime { // Hold publications first, then let what is published retire. User space is frozen by // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. self.asleep.store(true, Ordering::Release); - let start = Instant::::now(); + let mut remaining = msecs_to_jiffies(STOP_DRAIN_MS); loop { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } @@ -917,15 +919,16 @@ impl Runtime { state.submitted, state.retired, state.pending.len()); return Ok(()); } - if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) { + if remaining == 0 { dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len()); self.asleep.store(false, Ordering::Release); self.pump(state); return Err(EBUSY); } - // The service retires on notifications; `idle` is signalled only when nothing at all - // is left, so look again every 50 ms. - let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(50)); + remaining = match self.idle.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => jiffies, + _ => 0, + }; } } From ea2ab5856b783922a9bc61bdd9cd32b730093215 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 04:13:48 +1100 Subject: [PATCH 0747/1514] drm/asahi: set the G14 tiler and fragment kick masks Initialization wrote only the compute engine's kick mask in the G14 firmware 27.2 hardware data. The tiler and fragment masks stayed zero, so the firmware never gave the tiler a kick slot and the first render never started on the J473. Set the tiler mask from the cluster count and the fragment mask from the active core count, as for compute. Both counts come from the GPU's ID registers. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 8ea0fd153c82c3..4dae019c64191a 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -958,10 +958,14 @@ impl RootV27_2 { (0x109c, 0), (0x1064, 0), (0x2728, 0)] { put32(hw, offset as usize, value); } - // Compute resource mask, one low bit per configured core; the firmware seeds the - // compute engine's population from it. - let cores = id.total_active_cores; - put32(hw, 0x2670, if cores < 32 { (1u32 << cores) - 1 } else { u32::MAX }); + // Per-engine kick masks. The firmware gives an engine a kick slot only for bits set + // here, so an engine whose mask is left zero is never scheduled. The tiler takes one + // bit per cluster; the fragment and compute engines take one bit per configured core. + let low_bits = |n: u32| if n < 32 { (1u32 << n) - 1 } else { u32::MAX }; + put32(hw, 0x2668, low_bits(id.num_clusters)); + for offset in [0x266c, 0x2670] { + put32(hw, offset, low_bits(id.total_active_cores)); + } // Firmware-managed operating points, CRE and event-assisted operating-point completion. for offset in [0xfc0, 0x26b8, 0x1054] { put32(hw, offset, 1); From d2812fec2564e1df667a8433383e13833450bcbb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 04:14:10 +1100 Subject: [PATCH 0748/1514] drm/asahi: request completion flushes for G14 render commands On G14 firmware 27.2 the tiler and fragment commands left the job meta's flush_stamps word clear. The firmware's completion walk then stopped at those commands: the GPU finished them and reached the firmware stamps, but the host stamps were never written, the queues never retired, and the next job timed out. Set flush_stamps on both render commands, as the G15 firmware 27.2 path does for every command. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_render.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index c6c7a2b4766cd5..c21904da32966b 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -415,6 +415,9 @@ pub(crate) fn encode_vertex( put64(cmd, 0x58c, q.fw_stamp); put32(cmd, 0x594, c.stamp_value); put32(cmd, 0x598, q.slot); + // flush_stamps: the firmware's per-queue completion walk stops at a command whose meta + // leaves this clear, so the host stamp is never written and later commands never retire. + put32(cmd, 0x5a0, 1); // The event-control index is independent of the completion stamp slot. put64(cmd, 0x5a4, 0); // uuid (compute leaves it 0) let command_time = c.cmd_va + 0x5cc; @@ -908,7 +911,9 @@ pub(crate) fn encode_fragment( w64(cmd, meta + offset_of!(Meta, fw_stamp), q.fw_stamp); w32(cmd, meta + offset_of!(Meta, stamp_value), c.stamp_value); w32(cmd, meta + offset_of!(Meta, stamp_slot), q.slot); - // evctl_index 0 (13.5 fixed), flush_stamps 0, uuid (u64 at 0x908) 0, event_seq 0. + // evctl_index 0 (13.5 fixed), uuid (u64 at 0x908) 0, event_seq 0. flush_stamps (0x904) is + // set, as for the tiler: without it the completion walk stops at this command. + put32(cmd, 0x904, 1); w64(cmd, offset_of!(Rf, unk_buf_10), 1); w64( cmd, From cf467644e1f65ec1e89bae795d68c250fde559b5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 05:04:45 +1100 Subject: [PATCH 0749/1514] drm/asahi: admit depth/stencil compression the G14 render builder encodes The render admission shared with the M3 queues refuses stencil compression outright and admits compressed depth only for one sample and one layer, the layouts the M3 render path has been qualified for. The G14 firmware-27.2 queue builds its render command from the same UAPI fields, and that builder writes the depth and stencil load, store and partial compression addresses and strides in every layout. Mesa compresses depth and stencil by default, so every compositor frame of GNOME Shell (depth/stencil, one sample) and every WebRender frame of Firefox (4x MSAA, compressed depth) was rejected with ENOTSUPP on the G14 queue. Record per queue whether its render command builder carries the compression words for every sample and layer count, and admit compression by that property instead of by the M3 envelope. The M3 queues keep their current envelope. The choice follows the command builder the queue uses, not a chip or firmware version. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_submit.rs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index ef478a2dab1acf..8771370bab3da2 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -244,6 +244,10 @@ pub(crate) struct Queue { render_queue: Option>, early_tiling:bool, wide_visibility:bool, + /// Whether this queue's render command builder encodes depth and stencil compression + /// for every sample count and layer count. Otherwise only the single-sample, + /// single-layer compressed depth layout is admitted. + zls_compression_all_layouts:bool, urgency:u8, } impl Queue { @@ -257,7 +261,7 @@ impl Queue { 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency,preempt_alloc:None, + early_tiling,wide_visibility,zls_compression_all_layouts:false,urgency,preempt_alloc:None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] render_queue: None}) } @@ -272,7 +276,11 @@ impl Queue { 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, shared:Sink::G14V27_2(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_g14_queue"),kernel::static_lock_class!())?, - early_tiling:false,wide_visibility:false,urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), + early_tiling:false,wide_visibility:false, + // The G14 render command carries the depth and stencil load, store and partial + // compression words in every layout (g14_v27_2_render.rs). + zls_compression_all_layouts:true, + urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), render_queue: Some(render_queue)}) } } @@ -283,7 +291,8 @@ impl queue::Queue for Queue { let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { + if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling, + self.zls_compression_all_layouts) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); } @@ -370,7 +379,7 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) } fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, - early_tiling: bool) -> Result { + early_tiling: bool, zls_compression_all_layouts: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; if r.sample_size % 8 != 0 {return Err(ENOTSUPP);} let empty = agx_uapi::UapiHelperProgram { binary:0, config:0, data:0 }; @@ -382,11 +391,12 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac if r.flags & !(2|16|(1<<18)|stage_scope) != 0 || !matches!(r.samples, 1 | 2 | 4) || r.sampler_count != 0 || r.sampler_heap != 0 || r.vertex_helper != empty || r.fragment_helper != empty - || r.stencil.compression_base != 0 || r.stencil.compression_stride != 0 + || (!zls_compression_all_layouts + && (r.stencil.compression_base != 0 || r.stencil.compression_stride != 0)) || r.ppp_control & !0x203 != 0 { return Err(ENOTSUPP); } // Native 26A428 descriptors witness the ZLS metadata registers and mirrors // for single-sample, single-layer depth. Keep other layouts unqualified. - if (r.depth.compression_base != 0 || r.stencil.compression_base != 0) + if !zls_compression_all_layouts && (r.depth.compression_base != 0 || r.stencil.compression_base != 0) && (r.samples != 1 || r.layers != 1) {return Err(ENOTSUPP);} // sample_size describes color tilebuffer storage. Depth/stencil-only // passes legitimately require zero bytes of color storage. From 82671c76347a31aa2dfd7ea6311e554e147e4040 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 07:21:53 +1100 Subject: [PATCH 0750/1514] drm/asahi: never unwrap the RTKit transport on device-control paths The G14 firmware 27.2 runtime builds its records on a GpuManager graph but drives the firmware over its own RTKit peer, so that graph's `rtkit` stays None. Its render path still allocates scenes through GpuManager::alloc(). Once the freed firmware-private objects passed the collection limit, alloc() flushed the firmware cache with a legacy device-control message, and the doorbell unwrapped the missing transport: rust_kernel: panicked at gpu.rs:1882:51: called `Option::unwrap()` on a `None` value ... GpuManager::alloc <- g14_v27_2 Backend::new_queue <- ASAHI_QUEUE_CREATE Any client that creates enough queues (piglit textureGather here) could panic the kernel. Ring every doorbell through helpers that return ENODEV when the manager has no transport. A device-control message is queued only after the transport is known, so no caller waits for an answer that never comes. alloc() now asks whether the manager has device control: without one it keeps holding freed firmware memory, because reusing it could hand the firmware stale cached lines. It warns once instead of failing every allocation. The 27.2 runtime still needs its own cache-flush request before that memory can be reused. Add KUnit tests for the collection decision. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu.rs | 238 +++++++++++++++++++++++------------ 1 file changed, 159 insertions(+), 79 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index e9b715aeca9801..732d4fa70d3ea6 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -183,6 +183,36 @@ const MAX_FW_ALLOC_GARBAGE_BYTES: usize = 16 * 1024 * 1024; /// within the safe range for kmalloc (on 16K page systems). const MAX_FW_ALLOC_GARBAGE_OBJECTS: usize = 2048; +/// What [`GpuManager::alloc`] does with the freed firmware-private objects it holds. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum GarbageAction { + /// Under the collection limits: keep holding them. + Keep, + /// Over a limit: flush the firmware cache, then make them reusable. + Collect, + /// Over a limit, but this manager has no device-control channel to flush the firmware + /// cache with. Reusing the memory could hand the firmware stale cached lines, so it stays + /// held. + Hold, +} + +/// Decide the garbage action from the (count, bytes) held by the private and GPU read-only +/// allocators and whether this manager owns a device-control channel. +fn garbage_action( + private: (usize, usize), + gpu_ro: (usize, usize), + device_control: bool, +) -> GarbageAction { + let over = |(count, bytes): (usize, usize)| { + count > MAX_FW_ALLOC_GARBAGE_OBJECTS || bytes > MAX_FW_ALLOC_GARBAGE_BYTES + }; + match (over(private) || over(gpu_ro), device_control) { + (false, _) => GarbageAction::Keep, + (true, true) => GarbageAction::Collect, + (true, false) => GarbageAction::Hold, + } +} + /// Global allocators used for kernel-half structures. pub(crate) struct KernelAllocators { pub(crate) private: alloc::DefaultAllocator, @@ -297,6 +327,8 @@ pub(crate) struct GpuManager { pub(crate) initdata: fw::types::GpuObject, uat: mmu::Uat, crashed: AtomicBool, + /// Set once the over-limit firmware-private garbage was reported as held. + garbage_held: AtomicBool, #[pin] alloc: Mutex, io_mappings: KVec, @@ -1081,6 +1113,7 @@ impl GpuManager::ver { next_mmio_iova: IOVA_KERN_MMIO_RANGE.start, rtkit <- new_mutex!(None, "rtkit"), crashed: AtomicBool::new(false), + garbage_held: AtomicBool::new(false), event_manager, stats: stats_snap.clone(), raw_stats: raw_stats_snap.clone(), @@ -1483,12 +1516,7 @@ impl GpuManager::ver { job.run(&mut pipe); mod_dev_dbg!(self.dev, "GPU: run_job: ring doorbell\n"); - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message( - EP_DOORBELL, - MSG_TX_DOORBELL | pipe_type as u64 | ((index as u64) << 2), - )?; + self.ring_doorbell(MSG_TX_DOORBELL | pipe_type as u64 | ((index as u64) << 2))?; mod_dev_dbg!(self.dev, "GPU: run_job: done\n"); Ok(()) @@ -1554,15 +1582,7 @@ impl GpuManager::ver { mod_dev_dbg!(self.dev, "Context invalidation command: {:?}\n", &dc); let mut txch = self.tx_channels.lock(); - - let token = txch.device_control.send(&dc); - - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; - } - + let token = self.send_device_control(&mut txch, &dc)?; txch.device_control.wait_for(token)?; mod_dev_dbg!( @@ -1577,6 +1597,34 @@ impl GpuManager::ver { Ok(()) } + + /// Whether this manager drives its firmware over its own RTKit transport and device-control + /// channel. A manager whose records serve another runtime (the G14 firmware 27.2 graph) has + /// none: that firmware never reads the legacy channels. + fn has_device_control(&self) -> bool { + self.rtkit.lock().is_some() + } + + /// Ring a doorbell on this manager's RTKit transport, or fail with ENODEV without one. + fn ring_doorbell(&self, message: u64) -> Result { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + rtk.send_message(EP_DOORBELL, message) + } + + /// Queue a device-control message and ring its doorbell. Without a transport nothing is + /// queued, so no caller waits for a firmware that will never answer. + fn send_device_control( + &self, + txch: &mut TxChannels::ver, + msg: &fw::channels::DeviceControlMsg::ver, + ) -> Result { + let mut guard = self.rtkit.lock(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let token = txch.device_control.send(msg); + rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; + Ok(token) + } } extern "C" { @@ -1634,7 +1682,7 @@ impl Gpu for GpuManager::ver { let initdata = self.initdata.gpu_va().get(); let mut guard = self.rtkit.lock(); - let mut rtk = guard.as_mut().as_pin_mut().unwrap(); + let mut rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; rtk.as_mut().boot()?; rtk.as_mut().start_endpoint(EP_FIRMWARE)?; @@ -1804,24 +1852,39 @@ impl GpuManager for GpuManager::ver { let (garbage_count, garbage_bytes) = guard.private.garbage(); let (ro_garbage_count, ro_garbage_bytes) = guard.gpu_ro.garbage(); - if garbage_bytes > MAX_FW_ALLOC_GARBAGE_BYTES - || ro_garbage_bytes > MAX_FW_ALLOC_GARBAGE_BYTES - || garbage_count > MAX_FW_ALLOC_GARBAGE_OBJECTS - || ro_garbage_count > MAX_FW_ALLOC_GARBAGE_OBJECTS - { - mod_dev_dbg!( - self.dev, - "Collecting kalloc garbage (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", - garbage_count, - garbage_bytes, - ro_garbage_count, - ro_garbage_bytes - ); - if self.flush_fw_cache().is_err() { - dev_err!(self.dev.as_ref(), "Failed to flush FW cache\n"); - } else { - guard.private.collect_garbage(garbage_count); - guard.gpu_ro.collect_garbage(ro_garbage_count); + match garbage_action( + (garbage_count, garbage_bytes), + (ro_garbage_count, ro_garbage_bytes), + self.has_device_control(), + ) { + GarbageAction::Keep => {} + GarbageAction::Hold => { + if !self.garbage_held.swap(true, Ordering::Relaxed) { + dev_warn!( + self.dev.as_ref(), + "No firmware cache flush on this firmware: holding freed firmware memory (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", + garbage_count, + garbage_bytes, + ro_garbage_count, + ro_garbage_bytes + ); + } + } + GarbageAction::Collect => { + mod_dev_dbg!( + self.dev, + "Collecting kalloc garbage (private: {} objects, {} bytes, gpuro: {} objects, {} bytes)\n", + garbage_count, + garbage_bytes, + ro_garbage_count, + ro_garbage_bytes + ); + if self.flush_fw_cache().is_err() { + dev_err!(self.dev.as_ref(), "Failed to flush FW cache\n"); + } else { + guard.private.collect_garbage(garbage_count); + guard.gpu_ro.collect_garbage(ro_garbage_count); + } } } @@ -1837,11 +1900,7 @@ impl GpuManager for GpuManager::ver { return Err(ENODEV); } - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_KICKFW)?; - - Ok(()) + self.ring_doorbell(MSG_TX_DOORBELL | DOORBELL_KICKFW) } fn flush_fw_cache(&self) -> Result { @@ -1875,14 +1934,7 @@ impl GpuManager for GpuManager::ver { }; let mut txch = self.tx_channels.lock(); - - let token = txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - rtk.send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; - } - + let token = self.send_device_control(&mut txch, &dc)?; txch.device_control.wait_for(token)?; Ok(()) } @@ -2012,26 +2064,16 @@ impl GpuManager for GpuManager::ver { mod_dev_dbg!(self.dev, "Recover Channel command: {:?}\n", &dc); let mut txch = self.tx_channels.lock(); - let token = txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - if rtk - .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL) - .is_err() - { - dev_err!( - self.dev.as_ref(), - "Failed to send Recover Channel command\n" - ); - } - } - - if txch.device_control.wait_for(token).is_err() { - dev_err!( + match self.send_device_control(&mut txch, &dc) { + Err(_) => dev_err!( + self.dev.as_ref(), + "Failed to send Recover Channel command\n" + ), + Ok(token) if txch.device_control.wait_for(token).is_err() => dev_err!( self.dev.as_ref(), "Timed out waiting for Recover Channel command\n" - ); + ), + Ok(_) => {} } if debug_enabled(DebugFlags::VerboseFaults) { @@ -2059,16 +2101,8 @@ impl GpuManager for GpuManager::ver { let mut txch = self.tx_channels.lock(); - txch.device_control.send(&dc); - { - let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); - if rtk - .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL) - .is_err() - { - dev_err!(self.dev.as_ref(), "Failed to send TVB Grow Ack command\n"); - } + if self.send_device_control(&mut txch, &dc).is_err() { + dev_err!(self.dev.as_ref(), "Failed to send TVB Grow Ack command\n"); } } @@ -2078,12 +2112,13 @@ impl GpuManager for GpuManager::ver { } let mut fwctl = self.fwctl_channel.lock(); - let token = fwctl.send(&msg); - { + let token = { let mut guard = self.rtkit.lock(); - let rtk = guard.as_mut().as_pin_mut().unwrap(); + let rtk = guard.as_mut().as_pin_mut().ok_or(ENODEV)?; + let token = fwctl.send(&msg); rtk.send_message(EP_DOORBELL, MSG_FWCTL)?; - } + token + }; fwctl.wait_for(token)?; Ok(()) } @@ -2137,3 +2172,48 @@ impl GpuManagerPriv for GpuManager::ver { unsafe { kernel::bindings::apple_pmp_agx_activity_end() }; } } + +#[kunit_tests(asahi_gpu_garbage)] +mod tests { + use super::*; + + const UNDER: (usize, usize) = (MAX_FW_ALLOC_GARBAGE_OBJECTS, MAX_FW_ALLOC_GARBAGE_BYTES); + const OVER_COUNT: (usize, usize) = (MAX_FW_ALLOC_GARBAGE_OBJECTS + 1, 0); + const OVER_BYTES: (usize, usize) = (1, MAX_FW_ALLOC_GARBAGE_BYTES + 1); + + #[test] + fn under_the_limits_keeps_holding() { + assert_eq!(garbage_action(UNDER, UNDER, true), GarbageAction::Keep); + assert_eq!(garbage_action(UNDER, UNDER, false), GarbageAction::Keep); + } + + #[test] + fn over_a_limit_collects_with_device_control() { + assert_eq!( + garbage_action(OVER_COUNT, UNDER, true), + GarbageAction::Collect + ); + assert_eq!( + garbage_action(UNDER, OVER_BYTES, true), + GarbageAction::Collect + ); + } + + /// The G14 firmware 27.2 graph has no device-control channel. Its scene allocations used + /// to reach the legacy cache flush here and panic on the missing RTKit transport. + #[test] + fn over_a_limit_holds_without_device_control() { + assert_eq!( + garbage_action(OVER_COUNT, UNDER, false), + GarbageAction::Hold + ); + assert_eq!( + garbage_action(UNDER, OVER_BYTES, false), + GarbageAction::Hold + ); + assert_eq!( + garbage_action(OVER_BYTES, OVER_COUNT, false), + GarbageAction::Hold + ); + } +} From 9884f9b46ea2874498bdd173df1440d751450bc0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 07:29:27 +1100 Subject: [PATCH 0751/1514] drm/asahi: report the MMU fault status on a G14 firmware 27.2 timeout When a render or compute command times out on the G14 firmware 27.2 runtime, the log shows the queue stamps but not whether the GPU took a page fault. The native firmware path reads the MMU fault status at that point; this runtime had no register mapping to do the same. Map the page that holds the fault status registers when the runtime starts, choosing the registers by the GPU core as the native path does, and log the status at every timeout. A pending fault is decoded into address and unit. An empty status says the work stalled without a page fault. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 61 +++++++++++++++++++++++++++++- drivers/gpu/drm/asahi/regs.rs | 10 +++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index a119b246270118..71742629628a8c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -117,6 +117,58 @@ impl Drop for AscControl { } } +/// The GPU MMU fault status, read when a command times out: a pending fault names the faulting +/// address and unit, an empty status says the work stalled without a page fault. +struct FaultStatus { + page: *mut u8, + info: usize, + addr: Option, + g14x: bool, +} +// SAFETY: a device register page that is only read, one 32-bit MMIO load at a time. +unsafe impl Send for FaultStatus {} +// SAFETY: as above. +unsafe impl Sync for FaultStatus {} + +impl FaultStatus { + fn new(sgx: u64, cfg: &'static hw::HwConfig) -> Result { + let (info, addr, g14x) = crate::regs::Resources::fault_registers(cfg); + let base = info & !0xfff; + if addr.is_some_and(|a| a & !0xfff != base) { + return Err(EINVAL); + } + // SAFETY: the page lies inside this platform device's SGX register window. + let page = unsafe { kernel::bindings::ioremap(sgx + base as u64, 0x1000) }; + if page.is_null() { return Err(ENOMEM); } + Ok(Self { page: page.cast(), info: info - base, addr: addr.map(|a| a - base), g14x }) + } + fn read64(&self, at: usize) -> u64 { + // SAFETY: `at` and `at + 4` are register offsets inside the mapped page. + let (lo, hi) = unsafe { + (kernel::bindings::readl(self.page.add(at).cast()), + kernel::bindings::readl(self.page.add(at + 4).cast())) + }; + u64::from(lo) | (u64::from(hi) << 32) + } + fn log(&self, dev: &device::Device) { + let info = self.read64(self.info); + if info & 1 == 0 { + dev_err!(dev, "GPU: no MMU fault pending at the timeout (FAULT_INFO={:#x})\n", info); + return; + } + let addr = self.addr.map_or(info >> 30, |at| self.read64(at)); + dev_err!(dev, "GPU: MMU fault pending at the timeout: FAULT_INFO={:#x} {:?}\n", info, + crate::regs::decode_fault(info, addr, self.g14x)); + } +} + +impl Drop for FaultStatus { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { kernel::bindings::iounmap(self.page.cast()) } + } +} + /// Where the firmware's messages go: the runtime once it exists, nowhere before or after. #[pin_data] pub(crate) struct Notify { @@ -271,6 +323,7 @@ pub(crate) fn start<'a>( GFP_KERNEL)?; let resources = crate::regs::Resources::new(pdev)?; let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let fault = FaultStatus::new(sgx.start(), cfg)?; let copy_bytes: u32 = dev.fwnode().ok_or(ENODEV)? .property_read(c"apple,coredump-copy-buffer").required_by(dev)?; let board = gpu::BoardV27_2 { @@ -333,7 +386,7 @@ pub(crate) fn start<'a>( } // The firmware keeps using the window until it is stopped; it stays for the life of the boot. core::mem::forget(window); - let backend = Backend::start(&drm, dev, notify, peer, root, graph, pool, asc, cfg)?; + let backend = Backend::start(&drm, dev, notify, peer, root, graph, pool, asc, fault, cfg)?; Ok(Started { backend, drm, binding, resources }) } @@ -365,6 +418,7 @@ struct State { root: crate::fw::types::GpuObject, pool: CommandPool, asc: AscControl, + fault: FaultStatus, queue: QueueInfo, last: event::EventValue, sequence: u64, @@ -774,6 +828,7 @@ impl Runtime { } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); return Err(ETIMEDOUT); } Ok(()) @@ -887,6 +942,7 @@ impl Runtime { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); self.fail_all(state, ETIMEDOUT); return; } @@ -1021,6 +1077,7 @@ impl Backend { graph: Arc, pool: CommandPool, asc: AscControl, + fault: FaultStatus, cfg: &'static hw::HwConfig, ) -> Result> { // The runtime is created empty first, so no allocation failure can drop firmware-visible @@ -1065,7 +1122,7 @@ impl Backend { } }; *runtime.state.lock() = Some(State { - peer, root, pool, asc, queue, last, + peer, root, pool, asc, fault, queue, last, sequence: u64::from(head), next_slot: 0, waiting_unlink: None, diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 7e40d4b137ba9f..df6f7cd2d328f9 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -488,6 +488,16 @@ impl Resources<'_> { }) } + /// The MMU fault status registers of this GPU core: the status word, the address register + /// (`None` where the address is part of the status word) and whether it uses the G14X layout. + pub(crate) fn fault_registers(cfg: &'static hw::HwConfig) -> (usize, Option, bool) { + if cfg.gpu_core as u32 >= hw::GpuCore::G14S as u32 { + (FAULT_INFO_G14X, Some(FAULT_ADDR_G14X), true) + } else { + (FAULT_INFO, None, false) + } + } + /// Get the fault information from the MMU status register, if one occurred. pub(crate) fn get_fault_info(&self, cfg: &'static hw::HwConfig) -> Option { let g14x = cfg.gpu_core as u32 >= hw::GpuCore::G14S as u32; From 1a81530166e3e452ce1996243d818adee83cfae1 Mon Sep 17 00:00:00 2001 From: Kazuhide Takahashi Date: Sat, 21 Nov 2026 04:56:09 +0000 Subject: [PATCH 0752/1514] irqchip/apple-aic: treat T8132 VM_TMR_FIQ_ENA_EL2 as read-only without a CTXR window On a J715 (Mac16,13) booted through a stage 1 that arms no CTXR exec window, the kernel dies before the console in aic_init_cpu(): Internal error: Oops - Undefined instruction ... pc : aic_init_cpu+0x8c (msr s3_5_c15_c1_3, x9 -- VM_TMR_FIQ_ENA_EL2) T8142 already avoids this write through vm_timer_fiq_readonly (EL02 timer masks), which is cleared when the loader publishes aurora,ctxr-exec-window. Apply the same policy to T8132, so an aura-booted T8132 is unchanged, and say in the two comments that the policy now covers T8132 as well. Tested on J715 with OS firmware 26.5 and 26.6.2 (no CTXR window): boots with all 10 CPUs. The vGIC maintenance write (ICH_HCR_EL2) does not trap there and is left as is. Signed-off-by: Kazuhide Takahashi --- drivers/irqchip/irq-apple-aic.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 0a9aeced277217..bc1fb7b3c3ab13 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -366,6 +366,7 @@ static const struct aic_info aic3_t8132_info __initconst = { .irq_cfg = AIC3_IRQ_CFG, .fast_ipi = true, .local_fast_ipi = true, + .vm_timer_fiq_readonly = true, .fw_suspend = true, }; @@ -665,8 +666,9 @@ static unsigned long aic_fiq_get_idx(struct irq_data *d) } /* - * T8142 traps writes to VM_TMR_FIQ_ENA_EL2. Mask the guest timers through - * their architectural EL02 controls instead, leaving the older SoCs alone. + * T8132 and T8142 trap writes to VM_TMR_FIQ_ENA_EL2 outside a CTXR execute + * window. Mask the guest timers through their architectural EL02 controls + * instead, leaving the older SoCs alone. */ static void aic_vm_timer_mask(u64 timers, bool mask) { @@ -1324,12 +1326,13 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p irqc->info = *(struct aic_info *)match->data; /* - * The VM_TMR_FIQ_ENA_EL2 write that traps on T8142 was seen under - * SPTM. A loader that runs the OS at EL2 in a CTXR execute window - * starts no SPTM and says so with this property, and there the - * register takes writes. Masking through the EL02 controls instead - * sets IMASK in the guest's own timer, which KVM then keeps as - * guest state: the guest gets no timer interrupt again. + * The VM_TMR_FIQ_ENA_EL2 write traps on T8142 under SPTM, and on T8132 + * booted by a stage 1 that arms no CTXR execute window. A loader that + * runs the OS at EL2 in a CTXR execute window starts no SPTM and says + * so with this property, and there the register takes writes. + * Masking through the EL02 controls instead sets IMASK in the guest's + * own timer, which KVM then keeps as guest state: the guest gets no + * timer interrupt again. */ if (irqc->info.vm_timer_fiq_readonly && is_kernel_in_hyp_mode() && of_property_present(of_chosen, "aurora,ctxr-exec-window")) From b8b4948c6035a3b75cc59fcbf6a77ecf27f5aba3 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 15:00:11 -0800 Subject: [PATCH 0753/1514] media: apple: ave: admit the J775D's encoder by its build's per-boot word On the Mac Studio (J775D) the encoder's TEXT CRC differs on every boot, so probe refuses it as "unsupported firmware". The firmware is the 26A428 build the T6050 variant already admits: with the build's per-boot word zeroed, the probe's TEXT CRC matches the admitted 26A428 CRC on every J775D boot tested. The T6041, T8132 and T8112 26B123 variants already handle the same word, with a text_boot_word on the variant: a TEXT CRC that is not a known build is retried with that word zeroed. The word belongs to a firmware build, though, not to a chip. On T6050 a variant-wide offset would also apply to the 26C5035 build, whose TEXT is 0x4000 larger and which has not been checked for such a word. So move text_boot_word into struct ave_fw_build and set it on the builds that have it: 26A428 on T6050, and the builds T6041, T8132 and T8112 26B123 already retried. 26C5035 keeps exact matching. Those variants now list their builds (sizes, CRC and word) instead of variant-wide sizes, which also replaces T6041's second DATA size, fw_data_size_alt, with its second build. A known CRC is still taken as it is. The KUnit cases that pin the offsets check them per build, including that 26C5035 has none. On the J775D this takes effect together with aurora-silicon/linux#2278, which enables that board's encoder node; without it the encoder is not probed there. Tested on a J775D (Mac Studio, M5 Ultra). Signed-off-by: Jeff Queisser --- .../media/platform/apple/ave/ave-abi-test.c | 32 ++++++++++---- drivers/media/platform/apple/ave/ave-drv.c | 43 +++++++++++-------- drivers/media/platform/apple/ave/ave-fw.c | 20 ++++----- drivers/media/platform/apple/ave/ave.h | 25 ++++++----- 4 files changed, 70 insertions(+), 50 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 72b7d969169c34..87859a739a8cfb 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1533,16 +1533,17 @@ static void ave_t8112_26b123_build(struct kunit *test) KUNIT_EXPECT_TRUE(test, n->restore_data_first); KUNIT_EXPECT_EQ(test, n->text_link_cell, 0U); /* The Mac mini's loader sets the word at TEXT 0x4224 on every boot. */ - KUNIT_EXPECT_EQ(test, n->text_boot_word, 0x4224U); + KUNIT_ASSERT_EQ(test, n->build_count, 1U); + KUNIT_EXPECT_EQ(test, n->builds[0].text_boot_word, 0x4224U); /* The 27.2 builds' reference buffer sizing, as on the M3 and M4. */ KUNIT_EXPECT_EQ(test, n->lfs_ref_scale, 2U); KUNIT_EXPECT_EQ(test, ave_t8112.lfs_ref_scale, 1U); KUNIT_EXPECT_EQ(test, n->extra0_size, 0U); KUNIT_EXPECT_EQ(test, n->vcbar_flags, (u64)AVE_COPROC_VCBAR_VALID); KUNIT_EXPECT_EQ(test, ave_fw_vcbar(n, 0x800000000ULL), 0x800000001ULL); - KUNIT_EXPECT_EQ(test, n->text_crc, AVE_FW_TEXT_CRC_T8112_26B123); + KUNIT_EXPECT_EQ(test, n->builds[0].text_crc, AVE_FW_TEXT_CRC_T8112_26B123); { - const u32 off = n->text_boot_word, size = off + 0x40; + const u32 off = n->builds[0].text_boot_word, size = off + 0x40; u8 *text = kunit_kzalloc(test, size, GFP_KERNEL); u32 zeroed, a, b; @@ -1556,25 +1557,40 @@ static void ave_t8112_26b123_build(struct kunit *test) KUNIT_EXPECT_EQ(test, a, zeroed); KUNIT_EXPECT_EQ(test, b, zeroed); } - KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(n->text_crc), &ave_layout_26b123); + KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(n->builds[0].text_crc), &ave_layout_26b123); KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(ave_t8112.text_crc), &ave_layout_6070_11_1); } static void ave_t6041_text_boot_word(struct kunit *test) { - const u32 off = ave_t6041.text_boot_word, size = off + 0x100; + const struct ave_fw_build *m4 = ave_t6041.builds; + const u32 off = m4[0].text_boot_word, size = off + 0x100; u8 *text = kunit_kzalloc(test, size, GFP_KERNEL); u32 image, a, b; KUNIT_ASSERT_NOT_NULL(test, text); KUNIT_EXPECT_EQ(test, off, 0x4224U); - KUNIT_EXPECT_EQ(test, ave_t6041.fw_data_size_alt, 0x130000U); + /* The M4 Pro and M4 Max builds: the same word, the Max with a larger DATA. */ + KUNIT_ASSERT_EQ(test, ave_t6041.build_count, 2U); + KUNIT_EXPECT_EQ(test, m4[1].data_size, 0x130000U); + KUNIT_EXPECT_EQ(test, m4[1].text_boot_word, off); KUNIT_EXPECT_EQ(test, ave_t6041.text_link_cell, 0U); /* The M4 27.2 build: the same word, set per boot by some loaders. */ - KUNIT_EXPECT_EQ(test, ave_t8132.text_boot_word, off); - KUNIT_EXPECT_EQ(test, ave_t8132.text_crc, AVE_FW_TEXT_CRC_T8132_26B123); + KUNIT_ASSERT_EQ(test, ave_t8132.build_count, 1U); + KUNIT_EXPECT_EQ(test, ave_t8132.builds[0].text_boot_word, off); + KUNIT_EXPECT_EQ(test, ave_t8132.builds[0].text_crc, AVE_FW_TEXT_CRC_T8132_26B123); KUNIT_EXPECT_EQ(test, ave_t8132.text_link_cell, 0U); + /* + * The M5 Pro/Max 26A428 build: the same word, which differs per boot on + * the J775D. The 26C5035 build has none set: its CRC matches as it is. + */ + KUNIT_ASSERT_EQ(test, ave_t6050.build_count, 2U); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[0].text_boot_word, off); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[0].text_crc, AVE_FW_TEXT_CRC_T6050_26A428); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[1].text_boot_word, 0U); + KUNIT_EXPECT_EQ(test, ave_t6050.builds[1].text_crc, AVE_FW_TEXT_CRC_T6050_26C5035); + KUNIT_EXPECT_EQ(test, ave_t6050.text_link_cell, 0U); for (u32 i = 0; i < size; i++) text[i] = i * 7 + 3; memset(text + off, 0, 4); diff --git a/drivers/media/platform/apple/ave/ave-drv.c b/drivers/media/platform/apple/ave/ave-drv.c index a5897fe998f6c6..bd3568d34deaeb 100644 --- a/drivers/media/platform/apple/ave/ave-drv.c +++ b/drivers/media/platform/apple/ave/ave-drv.c @@ -79,10 +79,14 @@ const struct ave_variant ave_t6000 = { * the bootloader's code base (marked valid) left as it is, and DATA restored * from the boot snapshot before every start. */ +static const struct ave_fw_build ave_t8112_26b123_builds[] = { + { "26B123", 0x11c000, 0x128000, AVE_FW_TEXT_CRC_T8112_26B123, 0x4224 }, +}; + static const struct ave_variant ave_t8112_26b123 = { .regs = &ave_coproc_6070, - .fw_text_size = 0x11c000, - .fw_data_size = 0x128000, + .builds = ave_t8112_26b123_builds, + .build_count = ARRAY_SIZE(ave_t8112_26b123_builds), .boot_device_id = 12, .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, .timebase_multiplier = 1, @@ -90,8 +94,6 @@ static const struct ave_variant ave_t8112_26b123 = { .vcbar_flags = AVE_COPROC_VCBAR_VALID, .device_type = 12, .lfs_ref_scale = 2, - .text_crc = AVE_FW_TEXT_CRC_T8112_26B123, - .text_boot_word = 0x4224, .mbox_idle = 0x38, .restore_data_first = true, .boot_qualified = true, @@ -123,12 +125,16 @@ const struct ave_variant ave_t8112 = { * with soc-id t6040, the same way; iBoot 25G83 preloads it with a 0x130000 * DATA and sets a word at TEXT 0x4224 differently on every boot. */ +static const struct ave_fw_build ave_t6041_builds[] = { + { "25G83", 0x14c000, 0x12c000, 0, 0x4224 }, + /* The M4 Max's first encoder */ + { "25G83", 0x14c000, 0x130000, 0, 0x4224 }, +}; + const struct ave_variant ave_t6041 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x14c000, - .fw_data_size = 0x12c000, - .fw_data_size_alt = 0x130000, - .text_boot_word = 0x4224, + .builds = ave_t6041_builds, + .build_count = ARRAY_SIZE(ave_t6041_builds), .boot_device_id = 27, .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, .timebase_multiplier = 1, @@ -174,10 +180,14 @@ static const struct ave_variant ave_t8122 = { * unknown CRC is retried with it zeroed. The coprocessor and its start are * the M4 Pro's; this build boots as device 23 and takes handshake type 23. */ +static const struct ave_fw_build ave_t8132_builds[] = { + { "26B123", 0x154000, 0x12c000, AVE_FW_TEXT_CRC_T8132_26B123, 0x4224 }, +}; + const struct ave_variant ave_t8132 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x154000, - .fw_data_size = 0x12c000, + .builds = ave_t8132_builds, + .build_count = ARRAY_SIZE(ave_t8132_builds), .boot_device_id = 23, .boot_arg_value = AVE_COPROC_BOOT_ARG_VALUE, .timebase_multiplier = 1, @@ -185,8 +195,6 @@ const struct ave_variant ave_t8132 = { .vcbar_flags = AVE_COPROC_VCBAR_VALID, .device_type = 23, .lfs_ref_scale = 2, - .text_crc = AVE_FW_TEXT_CRC_T8132_26B123, - .text_boot_word = 0x4224, .boot_qualified = true, }; @@ -209,10 +217,12 @@ static const struct ave_variant ave_t8140 = { * 0x154000 and DATA 0x134000 (ADT ave0 segment-ranges). macOS starts the coprocessor as on the * A18 Pro, after clearing the SVE idle word at mailbox +0x118. Its boot configuration names * device 28, and so does its handshake's device type. The macOS 27.3 beta 1 build is admitted - * beside it. + * beside it. As on the M4 Max, the 26A428 build's TEXT word at 0x4224 differs on every boot + * (the Mac Studio, J775D), so an unknown TEXT CRC of that build is retried with the word zeroed. + * The 26C5035 build has not been checked for such a word, so its CRC must match as it is. */ static const struct ave_fw_build ave_t6050_builds[] = { - { "26A428", 0x154000, 0x134000, AVE_FW_TEXT_CRC_T6050_26A428 }, + { "26A428", 0x154000, 0x134000, AVE_FW_TEXT_CRC_T6050_26A428, 0x4224 }, /* * macOS 27.3 beta 1 (iBoot 20457.60.65): TEXT is 0x4000 larger, DATA * keeps its size. It starts as 26A428 does and takes 26A428's command @@ -221,10 +231,8 @@ static const struct ave_fw_build ave_t6050_builds[] = { { "26C5035", 0x158000, 0x134000, AVE_FW_TEXT_CRC_T6050_26C5035 }, }; -static const struct ave_variant ave_t6050 = { +const struct ave_variant ave_t6050 = { .regs = &ave_coproc_v40, - .fw_text_size = 0x154000, - .fw_data_size = 0x134000, .builds = ave_t6050_builds, .build_count = ARRAY_SIZE(ave_t6050_builds), .boot_device_id = 28, @@ -234,7 +242,6 @@ static const struct ave_variant ave_t6050 = { .vcbar_flags = AVE_COPROC_VCBAR_VALID, .device_type = 28, .lfs_ref_scale = 2, - .text_crc = AVE_FW_TEXT_CRC_T6050_26A428, .mbox_idle = 0x118, .boot_qualified = true, }; diff --git a/drivers/media/platform/apple/ave/ave-fw.c b/drivers/media/platform/apple/ave/ave-fw.c index 49f1da033411fe..95226720407119 100644 --- a/drivers/media/platform/apple/ave/ave-fw.c +++ b/drivers/media/platform/apple/ave/ave-fw.c @@ -185,9 +185,9 @@ int ave_fw_text_boot_crc(const void *text, size_t size, u32 word_off, /* * A known TEXT CRC (the M4 Pro build) stays as it is; any other is retried - * with the per-boot word zeroed (the M4 Max and M4 27.2 builds). + * with the build's per-boot word at @word_off zeroed. */ -static int ave_fw_text_boot_id(struct ave_dev *ave, u32 *crc) +static int ave_fw_text_boot_id(struct ave_dev *ave, u32 word_off, u32 *crc) { void *va; int ret; @@ -197,20 +197,20 @@ static int ave_fw_text_boot_id(struct ave_dev *ave, u32 *crc) va = memremap(ave->text.phys, ave->text.size, MEMREMAP_WB); if (!va) return -ENOMEM; - ret = ave_fw_text_boot_crc(va, ave->text.size, - ave->variant->text_boot_word, crc); + ret = ave_fw_text_boot_crc(va, ave->text.size, word_off, crc); memunmap(va); return ret; } -static int ave_fw_text_id(struct ave_dev *ave, u32 *crc) +static int ave_fw_text_id(struct ave_dev *ave, const struct ave_fw_build *build, + u32 *crc) { void *va; int ret; if (!ave->variant->text_link_cell) - return ave->variant->text_boot_word ? - ave_fw_text_boot_id(ave, crc) : 0; + return build && build->text_boot_word ? + ave_fw_text_boot_id(ave, build->text_boot_word, crc) : 0; va = memremap(ave->text.phys, ave->text.size, MEMREMAP_WB); if (!va) return -ENOMEM; @@ -243,9 +243,7 @@ bool ave_fw_sizes_match(const struct ave_variant *v, size_t text, size_t data) { if (v->build_count) return ave_fw_find_build(v, text, data, 0); - return text == v->fw_text_size && - (data == v->fw_data_size || - (v->fw_data_size_alt && data == v->fw_data_size_alt)); + return text == v->fw_text_size && data == v->fw_data_size; } /* @@ -337,7 +335,7 @@ int ave_fw_probe(struct ave_dev *ave) if (ret || text_crc != want) return dev_err_probe(dev, -ENODEV, "firmware text differs from loader CRC\n"); - ret = ave_fw_text_id(ave, &text_crc); + ret = ave_fw_text_id(ave, build, &text_crc); if (ret) return dev_err_probe(dev, ret, "firmware text link cell is not the DATA address\n"); diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index a0bda7749166ad..11504b4ba5f0c9 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -213,15 +213,20 @@ struct ave_fw_build { const char *name; u32 text_size; u32 data_size; + /* 0: any build in the known list */ u32 text_crc; + /* + * TEXT offset of a 32-bit word this build's loader sets differently on + * every boot; a TEXT CRC that is not a known build is retried with it + * zeroed. 0 when there is none, and the CRC must match as it is. + */ + u32 text_boot_word; }; struct ave_variant { const struct ave_coproc_regs *regs; u32 fw_text_size; u32 fw_data_size; - /* A second DATA size the variant accepts (the M4 Max build), or 0 */ - u32 fw_data_size_alt; /* * When set, the builds the variant admits. They replace fw_text_size, * fw_data_size and text_crc: the segment sizes select the build, and @@ -242,12 +247,6 @@ struct ave_variant { * address; it is zero in the firmware image. 0 when there is none. */ u32 text_link_cell; - /* - * TEXT offset of a 32-bit word the loader sets differently on every - * boot; a TEXT CRC that is not a known build is retried with it zeroed. - * 0 when there is none. - */ - u32 text_boot_word; /* * Mailbox offset of the SVE idle (clock gating) word that must read 0 * before the firmware starts, or 0 when the variant has none. @@ -260,9 +259,9 @@ struct ave_variant { * bootloader preloads, with a start and command protocol of its own. * The firmware segment sizes the bootloader reserved select it. * NULL when there is none. Use builds[] when the builds differ only - * in TEXT CRC (and command layout) but start the same way; use - * next_build when a build needs other start fields (boot device, - * handshake type, boot word, DATA handling) and has sizes of its own. + * in TEXT CRC, boot word (and command layout) but start the same way; + * use next_build when a build needs other start fields (boot device, + * handshake type, DATA handling) and has sizes of its own. */ const struct ave_variant *next_build; @@ -577,8 +576,8 @@ static inline struct ave_ctx *ave_file_to_ctx(struct file *file) return container_of(file_to_v4l2_fh(file), struct ave_ctx, fh); } -extern const struct ave_variant ave_t6000, ave_t6041, ave_t8112, ave_t8132, - ave_m3; +extern const struct ave_variant ave_t6000, ave_t6041, ave_t6050, ave_t8112, + ave_t8132, ave_m3; /* ave-fw.c */ u64 ave_fw_vcbar(const struct ave_variant *variant, u64 text_iova); From 37fee82e714ea1e66eb87358aff5d9916ea9bb2f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 18 Nov 2026 13:42:49 -0500 Subject: [PATCH 0754/1514] arm64: dts: apple: enable J716c fan and hotspot monitoring Enable the J716c SMC hwmon node and include hwmon-fan-dual.dtsi with the T6050 F0md/F1md mode keys and manual fan control enabled. Keep both apple,discover-temperatures and apple,soc-die-keys ("TCMb") inherited from t6050-die0.dtsi so all readable T* float sensors are discovered while the discovered TCMb channel also supplies the macsmc_soc_die thermal zone. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t6050-j716c.dts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index acc1034a340e79..8a8532336400d3 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -15,6 +15,7 @@ #define T6050_J716C #include "t6050-max.dtsi" +#include "hwmon-fan-dual.dtsi" / { compatible = "apple,j716c", "apple,t6050", "apple,arm-platform"; @@ -184,9 +185,24 @@ gpio-reserved-ranges = <0 80>, <81 57>, <139 82>; }; -/* This board's SMC fan and power keys are not yet checked */ +/* + * Inherit apple,discover-temperatures and apple,soc-die-keys ("TCMb") from + * t6050-die0.dtsi so all readable T* float sensors are discovered and TCMb + * supplies the macsmc_soc_die thermal zone for the GPU thermal governor. + * T6050 spells the fan mode keys F0md/F1md and accepts manual fan targets. + */ &smc_hwmon { - status = "disabled"; + status = "okay"; + + fan-F0Ac { + apple,fan-mode = "F0md"; + apple,fan-manual-control; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + apple,fan-manual-control; + }; }; /* From 80220ba4d4025b7cca3f771bc3c9891258716f12 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 18 Nov 2026 14:06:11 -0500 Subject: [PATCH 0755/1514] drm/asahi: select GPU completion inputs by firmware interface Whether a compute kick's explicit waits on other kicks take the completion class, held in firmware until the producer completes, was a per-board flag that only the J714 set. It is a property of the firmware interface and the host encodings, not of the board: derive it from them and drop the field. Boards on the T6050 firmware's M5 graph layout (J714G17S26A428) with the G17S/G17C host encodings take completion inputs. The layout is matched positively, so a board on any other layout keeps them off. This turns them on for the J716c (G17C) as well as the J714. The common interface (the J813) keeps its own kick forms, and the G17D keeps its qualified tuple and pipelined firmware waits; the reason for each is beside Board::completion_inputs(). A compile-time check pins the result for every board. On the J716c every compute kick now takes the counted form. A wait on a producer that does not declare a visible completion still waits on the host. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 31 +++++++++++++++------ 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index c0317461c2f6c3..c716a15e387c9c 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -2435,9 +2435,6 @@ pub(crate) struct Board { /// Whether the host encodings are the G17D ones measured on the M5 Ultra /// ([`Board::g17d_forms`]). g17d_forms: bool, - /// Whether explicit waits on other kicks take the completion class - /// ([`Board::completion_inputs`]). - completion_inputs: bool, /// Whether firmware accepts tiling kicks without an entry signal and retained /// render pairs kicked through the host port alone. pub(crate) host_only_render_kicks: bool, @@ -2469,7 +2466,6 @@ pub(crate) const J714: Board = Board { hw_words: &[], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: true, host_only_render_kicks: false, }; @@ -2501,7 +2497,6 @@ pub(crate) const J716C: Board = Board { hw_words: &[], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: false, // Qualified on G17C's 26A428 image. G17S uses completion-class inputs, // G17D has distinct kick encodings, and common 26A428 publishes descriptors // on the item ring. Qualify those interfaces separately. @@ -2546,7 +2541,6 @@ pub(crate) const J775D: Board = Board { // above the SMC's own start rather than below it. fan_curve_start_mc: 97_000, g17d_forms: true, - completion_inputs: false, host_only_render_kicks: false, }; @@ -2586,7 +2580,6 @@ pub(crate) const J813: Board = Board { (0x10d4, 0x17), (0x1118, 0), (0x2660, 4), (0x2720, 1), (0x2724, 0)], fan_curve_start_mc: 84_000, g17d_forms: false, - completion_inputs: false, host_only_render_kicks: false, }; @@ -2603,6 +2596,14 @@ const _: () = { assert!(J775D.min_parameter_buffer as u64 == min_parameter_buffer_pages(J775D.clusters) << 15); }; +// Completion inputs follow the firmware interface and host encodings: the M5 graph's G17S and +// G17C boards take them, the G17D and the common-interface boards keep their own forms. +const _: () = { + assert!(J714.completion_inputs() && J716C.completion_inputs()); + assert!(!J775D.completion_inputs() && !J813.completion_inputs()); + assert!(!J813_26B123.completion_inputs()); +}; + /// Populate the enabled-USC count from the device's sampled core masks. /// This count covers the whole device, not one cluster. pub(crate) fn set_m5_enabled_cores(board: &Board, out: &mut [u8], enabled: u32) @@ -2962,8 +2963,22 @@ impl Board { /// producers) take the completion class, which holds them in firmware until those kicks /// complete. A wait on another queue's compute stays in firmware only for work that declares /// a visible completion (DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION); others wait on the host. + /// + /// This keys on the board's static graph family and host encodings: every board on [`M5_GRAPH`] + /// (whose static profile is [`RootProfile::J714G17S26A428`]) without the G17D host encodings + /// (`!self.g17d_forms`) takes these waits, with the counted descriptor forms + /// [`super::compute::kick_tuple`] gives them. Any other graph family keeps them off until its + /// kicks are known to take that form. + /// - The common interface (the J813) encodes its kicks in its own forms + /// ([`Board::j813_forms`]): it already gives explicit dependencies the completion class, + /// but its kicks carry no submission sequence and no retired-parent relaxation, which the + /// M5 graph's form adds, so its waits stay on the host. + /// - The G17D host encodings ([`Board::g17d_forms`]) run compute only with the qualified + /// tuple and the entry-signal gate, and take their firmware waits in the pipelined class + /// ([`super::compute::explicit_dependency`]); the counted G17S form's tuple does not apply + /// there and has not been run on a G17D, where a wrong kick form never completes. pub(crate) const fn completion_inputs(&self) -> bool { - self.completion_inputs + matches!(self.graph.profile, RootProfile::J714G17S26A428) && !self.g17d_forms } /// Whether this is the J813, whose register programs macOS 27.0 writes in the common 26A428 From 970588310858ba182bc9b785a9c922db2a979556 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 11:27:29 +1100 Subject: [PATCH 0756/1514] arm64: dts: apple: t8112-j473-fw27: keep the GFX domain through system sleep On macOS 27 system firmware the J473's GPU firmware (27.2) keeps running through suspend-to-idle, as on the J413. With the GFX domain gated under it, the J473 reset at the first s2idle on a GPU desktop (2/2). With the domain kept on through system sleep, the same desktop resumed 4/4 with the GPU still rendering after each wake. Add t8112-j473-fw27, the J473 with macOS 27 system firmware, and set apple,sleep-retained on its ps_gfx as t8112-j413-fw27 does. Runtime PM is unchanged, and a GFX domain that is already off stays off. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/Makefile | 1 + arch/arm64/boot/dts/apple/t8112-j473-fw27.dts | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8112-j473-fw27.dts diff --git a/arch/arm64/boot/dts/apple/Makefile b/arch/arm64/boot/dts/apple/Makefile index 25b14626c655b7..256662c18acd6f 100644 --- a/arch/arm64/boot/dts/apple/Makefile +++ b/arch/arm64/boot/dts/apple/Makefile @@ -116,6 +116,7 @@ dtb-$(CONFIG_ARCH_APPLE) += t8112-j413.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j413-fw27.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j415.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j473.dtb +dtb-$(CONFIG_ARCH_APPLE) += t8112-j473-fw27.dtb dtb-$(CONFIG_ARCH_APPLE) += t8112-j493.dtb dtb-$(CONFIG_ARCH_APPLE) += t8122-j433.dtb dtb-$(CONFIG_ARCH_APPLE) += t8122-j434.dtb diff --git a/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts b/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts new file mode 100644 index 00000000000000..d71e8ac486ba23 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8112-j473-fw27.dts @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* J473 with macOS 27 system firmware (27.2 stub). */ +#include "t8112-j473.dts" + +/* + * The 27.2 GPU firmware keeps running through suspend-to-idle. Gating the GFX + * domain under it leaves the domain unable to power on at the wake, as on the + * t8112-j413-fw27 board. + */ +&ps_gfx { + apple,sleep-retained; +}; From 08fa25353657ea8233f51a37c3018a32a2c6bf02 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 20 Nov 2026 02:10:16 -0500 Subject: [PATCH 0757/1514] arm64: dts: apple: t6050: describe the single-die system cache controller Single-die T6050 boards all include t6050-max.dtsi. M5 Pro parts enable four of the eight die-0 AMCCs (AMCC 0..3, 16 planes, amcc-enable-mask 0xf on J714s), while M5 Max ships in both 460 GB/s (binned) and 614 GB/s (eight AMCCs, 32 planes, amcc-enable-mask 0xff) variants under the same board device trees. Describe the die-0 memory cache controller (apple,t6050-mcc) in t6050-max.dtsi with status = "disabled", apple,boot-dma-devices = <&dcp>, and the base four AMCCs (16 planes) in reg, sizing the parent bus ranges for all eight die-0 AMCCs. Because the binned 460 GB/s M5 Max's amcc-enable-mask has not been read from hardware yet and apple-mcc reads every listed plane aperture before rejecting it, keeping the node disabled ensures no unverified AMCC aperture is read until the boot loader populates reg from the live ADT's amcc-enable-mask and enables the node (or a board whose enable mask is verified across all its SKUs opts in). Add display = <&dcp> to the boot framebuffer node on every single-die T6050 laptop (J714c, J714s, J716c, J716s, and the K114/K116 base) so once mcc is enabled, apple-mcc waits for the internal DCP to retire the boot scanout before enabling cache allocation, including when the bootloader keeps the boot framebuffer and leaves the DCP disabled. Desktop boards (t6050-j775c.dts and t6050-j873s.dts) inherit the disabled MCC node, have no boot framebuffer, and keep &dcp disabled. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 2 + arch/arm64/boot/dts/apple/t6050-j714s.dts | 2 + arch/arm64/boot/dts/apple/t6050-j716c.dts | 2 + arch/arm64/boot/dts/apple/t6050-j716s.dts | 2 + .../arm64/boot/dts/apple/t6050-k114-k116.dtsi | 2 + arch/arm64/boot/dts/apple/t6050-max.dtsi | 44 +++++++++++++++++++ 6 files changed, 54 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index cf1d62c690fcc7..3dd4666d150f98 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -38,6 +38,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index 383ec08bedbe28..5c09df0d90daa0 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -56,6 +56,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index 8fdea5242027b6..34b018fa54d6d0 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -47,6 +47,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j716s.dts b/arch/arm64/boot/dts/apple/t6050-j716s.dts index 43747a4ce6be7b..47f1a4195b174f 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716s.dts @@ -41,6 +41,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index f7cedd1a4c854f..63cc834dc0fb51 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -46,6 +46,8 @@ compatible = "apple,simple-framebuffer", "simple-framebuffer"; reg = <0 0 0 0>; /* To be filled by the loader */ /* Format properties will be added by the loader */ + /* Scanned out by the internal DCP, handed off or not. */ + display = <&dcp>; status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 7952525ab1d3c2..b22e2e22912c0a 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -477,3 +477,47 @@ }; }; #endif + +/* + * Die 0's memory cache controllers (ADT /arm-io/mcc: amcc-count 8, + * dcs-count-per-amcc 4, AMCC a at 0x2220000000 + a * 0x2000000, four 16 KiB + * planes at +0x40000). Both M5 Pro and M5 Max boards include this file; M5 Pro + * enables AMCC 0..3 only (ADT amcc-enable-mask = 0xf, 16 planes), and M5 Max + * ships in both 460 GB/s (binned) and 614 GB/s (amcc-enable-mask = 0xff, + * 8 AMCCs) variants under the same board DTS. Because the binned 460 GB/s M5 + * Max's amcc-enable-mask has not been read from hardware yet and apple-mcc + * reads every listed plane aperture before rejecting it, keep mcc disabled + * here until the boot loader populates reg from the live ADT's + * amcc-enable-mask and enables the node (or a board whose enable mask is + * verified across all SKUs enables it); ranges covers all eight AMCCs for + * that update. + * + * The boot loader leaves every enabled plane's ways powered with allocation + * disabled until apple-mcc allows it. On laptops, each board's framebuffer0 + * names &dcp as its display so once mcc is enabled, allocation waits for the + * DCP to retire the boot scanout (and stays off when the boot loader keeps + * simpledrm). + */ +/ { + soc@2220000000 { + compatible = "simple-bus"; + #address-cells = <2>; + #size-cells = <2>; + ranges = <0x22 0x20000000 0x22 0x20000000 0x0 0x10000000>; + nonposted-mmio; + + mcc: memory-controller@2220000000 { + compatible = "apple,t6050-mcc"; + reg = <0x22 0x20000000 0x0 0x4000>, <0x22 0x20040000 0x0 0x4000>, + <0x22 0x20080000 0x0 0x4000>, <0x22 0x200c0000 0x0 0x4000>, + <0x22 0x22000000 0x0 0x4000>, <0x22 0x22040000 0x0 0x4000>, + <0x22 0x22080000 0x0 0x4000>, <0x22 0x220c0000 0x0 0x4000>, + <0x22 0x24000000 0x0 0x4000>, <0x22 0x24040000 0x0 0x4000>, + <0x22 0x24080000 0x0 0x4000>, <0x22 0x240c0000 0x0 0x4000>, + <0x22 0x26000000 0x0 0x4000>, <0x22 0x26040000 0x0 0x4000>, + <0x22 0x26080000 0x0 0x4000>, <0x22 0x260c0000 0x0 0x4000>; + apple,boot-dma-devices = <&dcp>; + status = "disabled"; + }; + }; +}; From d1571ebf73417edbbc9ac733da9db770438894bb Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:07:33 -0500 Subject: [PATCH 0758/1514] PCI: apple: keep adopted links across s2idle on every adopted host pcie-apple restricted suspend-to-idle with boot-loader-trained ("adopted") links to an explicit list of four board compatibles (J716c, K114c, K116s, J714s). That allowlist recorded which boards had been exercised, not a hardware distinction. Remove the board compatible allowlist from apple_pcie_check_adopted_s2idle(). The function is only reached for hosts whose links the boot loader trains (hw->adopt_link), and the existing hardware checks remain as the guard before and after sleep: the root complex is running and ready, every port link is up and not busy with no link-down interrupt pending, and every device below a boot-trained port answers in D0. Deeper sleep remains rejected. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 8d7e9e72aabdab..9b6f1940aa4019 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -6870,15 +6870,13 @@ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) int error = 0; /* - * Qualified on the J716c, the K114c, the K116s and the J714s: the same - * T6050 host with the N1 adopted on port 0. The K116s and the J714s - * (16- and 14-inch M5 Pro) also have a kernel-trained SD reader port. - * Other adopted platforms and deeper sleep remain unqualified. + * Every host whose links the boot loader trained (hw->adopt_link) keeps + * them across suspend-to-idle: the root complex, every port's link and + * the devices below must still be up and in D0, which the checks below + * read from the hardware, before and after the sleep. Deeper sleep + * remains unqualified. */ - if (!(of_machine_is_compatible("apple,j716c") || - of_machine_is_compatible("apple,k114c") || - of_machine_is_compatible("apple,k116s") || - of_machine_is_compatible("apple,j714s")) || !pm_suspend_no_platform()) + if (!pm_suspend_no_platform()) return -EBUSY; if (!(readl(pcie->base + CORE_RC_CTL) & CORE_RC_CTL_RUN) || From 15e9687f11208642118bfa45b5a659d38c964ae1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:07:33 -0500 Subject: [PATCH 0759/1514] arm64: dts: apple: t6050: give each P core a private L2 in front of the cluster L3 The P-tier (apple,everest) cores are described with one 16 MiB L2 per cluster. The hardware has one more level there: - CLIDR_EL1 reports three cache levels on a P core (L1D, L1I, L2, L3) and two on an M-tier core. - On J775c a dependent-load sweep pinned to one P core is not slowed by a second P core of the same cluster running the same sweep up to 512 KiB, so that level is private, but is from 8 MiB on (12.9 vs 8.0 ns at 8 MiB, 27.7 vs 8.6 ns at 12 MiB), half of a shared 16 MiB. An M-tier core running the sweep slows neither. - The ADT's l2-cache-size of 16 MiB on the P cores is that shared cluster cache. Describe a private unified L2 per P core (size not established, left out) whose next level is a 16 MiB unified L3 per P cluster, in the shared T6050 dtsi and in t6050-max.dtsi and t6050-ultra.dtsi (both dies), so the DT matches the three-level hardware hierarchy and CLIDR_EL1 (and avoids a CLIDR level-count mismatch if init_cache_level() runs without early OF levels). The M-tier clusters are unchanged. Signed-off-by: Satya Benson --- arch/arm64/boot/dts/apple/t6050-base.dtsi | 32 ++++++++++++++++--- arch/arm64/boot/dts/apple/t6050-max.dtsi | 22 ++++++++----- arch/arm64/boot/dts/apple/t6050-ultra.dtsi | 36 ++++++++++++++-------- 3 files changed, 64 insertions(+), 26 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-base.dtsi b/arch/arm64/boot/dts/apple/t6050-base.dtsi index 323033b71e5653..6a588396cf93ff 100644 --- a/arch/arm64/boot/dts/apple/t6050-base.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-base.dtsi @@ -68,10 +68,18 @@ T6050_CPU(label, mpidr, "apple,everest", pcluster_opp, cluster, 1024, l2, 0x30000, 0x20000) /* - * Caches. Every cluster has its own unified L2, shared by its six cores: the ADT's /cpus/cpuN - * l2-cache-size is 8 MiB on the M-tier (apple,sawtooth) cores and 16 MiB on the P-tier - * (apple,everest) cores in the J714c/s, J716c/s, J775c/d and J873s ADTs, and macOS reports - * hw.perflevelN.cpusperl2 = 6 on both tiers. The L1 sizes are macOS's + * Caches. Every M-tier (apple,sawtooth) cluster has a unified L2 shared by its cores: the ADT's + * /cpus/cpuN l2-cache-size is 8 MiB on those cores in the J714c/s, J716c/s, J775c/d and J873s + * ADTs, and macOS reports hw.perflevelN.cpusperl2 = 6. A P-tier (apple,everest) core has one + * more level: CLIDR_EL1 reports three cache levels there and two on an M-tier core. Each P core + * has a private unified L2 (its size is not established) in front of a 16 MiB unified L3 shared + * by the cluster, which is the cluster cache the ADT lists as the P cores' l2-cache-size. On + * J775c, a dependent-load sweep on one P core is not slowed by a second P core of the same + * cluster running the same sweep up to 512 KiB (private), but is from 8 MiB on (shared, half + * of 16 MiB); a core of an M-tier cluster slows neither. Describing all three levels matches the + * hardware and CLIDR_EL1 (and avoids a CLIDR level-count mismatch if init_cache_level() runs + * without early OF levels). + * The L1 sizes are macOS's * hw.perflevelN.l1icachesize/l1dcachesize: 128 KiB I and 64 KiB D on the M tier, 192 KiB I and * 128 KiB D on the P tier. The system level cache sits behind the memory controllers and is * shared with every agent; it is not part of the CPUs' cache hierarchy and is not described here. @@ -84,7 +92,21 @@ cache-size = ; \ } #define T6050_M_L2(label, name) T6050_L2(label, name, 0x800000) -#define T6050_P_L2(label, name) T6050_L2(label, name, 0x1000000) +/* A P core's private L2, in front of its cluster's L3. */ +#define T6050_P_L2(label, name, l3) \ + label: name { \ + compatible = "cache"; \ + cache-level = <2>; \ + cache-unified; \ + next-level-cache = <&l3>; \ + } +#define T6050_P_L3(label, name) \ + label: name { \ + compatible = "cache"; \ + cache-level = <3>; \ + cache-unified; \ + cache-size = <0x1000000>; \ + } / { compatible = "apple,t6050", "apple,arm-platform"; diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 6d76d01cbda273..87da86910ddff2 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -39,12 +39,12 @@ T6050_M_CPU(cpu9, 40103, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu10, 40104, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu11, 40105, cpufreq_mc1, l2_cache_mc1); - T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu17, 10205, cpufreq_pc, l2_cache_pc); + T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_p0); + T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_p1); + T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_p2); + T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_p3); + T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_p4); + T6050_P_CPU(cpu17, 10205, cpufreq_pc, l2_cache_p5); /* * The clusters are MPIDR Aff1 (M0, M1, then P), each with its own L2. The boot @@ -116,10 +116,16 @@ }; }; - /* One L2 per cluster (t6050-base.dtsi, "Caches"). */ + /* L2 per M cluster, L2 per P core, L3 per P cluster (t6050-base.dtsi, "Caches"). */ T6050_M_L2(l2_cache_mc0, l2-cache-mcluster0); T6050_M_L2(l2_cache_mc1, l2-cache-mcluster1); - T6050_P_L2(l2_cache_pc, l2-cache-pcluster); + T6050_P_L3(l3_cache_pc, l3-cache-pcluster); + T6050_P_L2(l2_cache_p0, l2-cache-pcore0, l3_cache_pc); + T6050_P_L2(l2_cache_p1, l2-cache-pcore1, l3_cache_pc); + T6050_P_L2(l2_cache_p2, l2-cache-pcore2, l3_cache_pc); + T6050_P_L2(l2_cache_p3, l2-cache-pcore3, l3_cache_pc); + T6050_P_L2(l2_cache_p4, l2-cache-pcore4, l3_cache_pc); + T6050_P_L2(l2_cache_p5, l2-cache-pcore5, l3_cache_pc); }; #define DIE diff --git a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi index 449708caa229b3..1dbff1f6ecbcf5 100644 --- a/arch/arm64/boot/dts/apple/t6050-ultra.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-ultra.dtsi @@ -37,11 +37,11 @@ T6050_M_CPU(cpu8, 40102, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu9, 40103, cpufreq_mc1, l2_cache_mc1); T6050_M_CPU(cpu10, 40104, cpufreq_mc1, l2_cache_mc1); - T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_pc); - T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_pc); + T6050_P_CPU(cpu12, 10200, cpufreq_pc, l2_cache_p0); + T6050_P_CPU(cpu13, 10201, cpufreq_pc, l2_cache_p1); + T6050_P_CPU(cpu14, 10202, cpufreq_pc, l2_cache_p2); + T6050_P_CPU(cpu15, 10203, cpufreq_pc, l2_cache_p3); + T6050_P_CPU(cpu16, 10204, cpufreq_pc, l2_cache_p4); T6050_M_CPU(cpu18, 41000, cpufreq_mc0_die1, l2_cache_mc0_die1); T6050_M_CPU(cpu19, 41001, cpufreq_mc0_die1, l2_cache_mc0_die1); T6050_M_CPU(cpu20, 41002, cpufreq_mc0_die1, l2_cache_mc0_die1); @@ -52,11 +52,11 @@ T6050_M_CPU(cpu26, 41102, cpufreq_mc1_die1, l2_cache_mc1_die1); T6050_M_CPU(cpu27, 41103, cpufreq_mc1_die1, l2_cache_mc1_die1); T6050_M_CPU(cpu28, 41104, cpufreq_mc1_die1, l2_cache_mc1_die1); - T6050_P_CPU(cpu30, 11200, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu31, 11201, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu32, 11202, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu33, 11203, cpufreq_pc_die1, l2_cache_pc_die1); - T6050_P_CPU(cpu34, 11204, cpufreq_pc_die1, l2_cache_pc_die1); + T6050_P_CPU(cpu30, 11200, cpufreq_pc_die1, l2_cache_p0_die1); + T6050_P_CPU(cpu31, 11201, cpufreq_pc_die1, l2_cache_p1_die1); + T6050_P_CPU(cpu32, 11202, cpufreq_pc_die1, l2_cache_p2_die1); + T6050_P_CPU(cpu33, 11203, cpufreq_pc_die1, l2_cache_p3_die1); + T6050_P_CPU(cpu34, 11204, cpufreq_pc_die1, l2_cache_p4_die1); /* * The clusters are MPIDR Aff1 (die 0's M0, M1 and P, then die 1's), each with its @@ -174,13 +174,23 @@ }; }; - /* One L2 per cluster (t6050-base.dtsi, "Caches"). */ + /* L2 per M cluster, L2 per P core, L3 per P cluster (t6050-base.dtsi, "Caches"). */ T6050_M_L2(l2_cache_mc0, l2-cache-mcluster0); T6050_M_L2(l2_cache_mc1, l2-cache-mcluster1); - T6050_P_L2(l2_cache_pc, l2-cache-pcluster); + T6050_P_L3(l3_cache_pc, l3-cache-pcluster); + T6050_P_L2(l2_cache_p0, l2-cache-pcore0, l3_cache_pc); + T6050_P_L2(l2_cache_p1, l2-cache-pcore1, l3_cache_pc); + T6050_P_L2(l2_cache_p2, l2-cache-pcore2, l3_cache_pc); + T6050_P_L2(l2_cache_p3, l2-cache-pcore3, l3_cache_pc); + T6050_P_L2(l2_cache_p4, l2-cache-pcore4, l3_cache_pc); T6050_M_L2(l2_cache_mc0_die1, l2-cache-mcluster0-die1); T6050_M_L2(l2_cache_mc1_die1, l2-cache-mcluster1-die1); - T6050_P_L2(l2_cache_pc_die1, l2-cache-pcluster-die1); + T6050_P_L3(l3_cache_pc_die1, l3-cache-pcluster-die1); + T6050_P_L2(l2_cache_p0_die1, l2-cache-pcore0-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p1_die1, l2-cache-pcore1-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p2_die1, l2-cache-pcore2-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p3_die1, l2-cache-pcore3-die1, l3_cache_pc_die1); + T6050_P_L2(l2_cache_p4_die1, l2-cache-pcore4-die1, l3_cache_pc_die1); /* Die 1 MMIO. The boot loader needs each die's bus. */ die1: soc@4200000000 { From 64d353bc0cd0d4ab1e75fd6d024197eb7bfbb339 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:07:34 -0500 Subject: [PATCH 0760/1514] arm64: dts: apple: t6050: let AFR and GFX auto-PM reach power-gated The T6050 boot chain hands the GPU's AFR and GFX power domains to Linux with PS_MIN (bits 19:16 of the PMGR power-state word) set to 4, clock-gated. apple_pmgr_ps_set() reads the word and writes it back whole, so Linux keeps that floor and the idle GFX domain rests at actual state 4 (0x1404034f). macOS writes PS_MIN as 0 and rests at 0x1000030f (actual state 0, power-gated). Set apple,min-state = <0> on the shared ps_afr and ps_gfx nodes in t6050-peripherals.dtsi. The existing apple_pmgr_ps_probe() path clears PS_MIN once before the first power-on, and every later whole-word write carries 0. On J775c, idle GFX reaches actual state 0 about 55 ms after POWER_ON_DONE under both 26A428 and 26B123 firmware, leaves it for work, and returns to state 0 cleanly. No wall-power saving was measured from this change. Signed-off-by: Satya Benson --- arch/arm64/boot/dts/apple/t6050-peripherals.dtsi | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index b85b06baf5453a..3dcf2659707fd2 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -1006,12 +1006,20 @@ label = "gpx"; status = "disabled"; }; + /* + * The T6050 boot chain hands AFR and GFX over with an auto-PM floor of + * clock-gated (PS_MIN = 4), and the power-state driver writes back the + * floor it reads, holding idle GFX at state 4. macOS runs both domains + * with a floor of power-gated, where idle GFX rests at state 0; request + * the same for all T6050 boards inheriting these domains. + */ ps_afr: power-controller@100 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x100 4>; #power-domain-cells = <0>; #reset-cells = <0>; label = "afr"; + apple,min-state = <0>; status = "disabled"; }; ps_gfx: power-controller@110 { @@ -1021,6 +1029,7 @@ #reset-cells = <0>; label = "gfx"; power-domains = <&ps_afr>, <&ps_gpx>; + apple,min-state = <0>; status = "disabled"; }; }; From 410f5bebf1f18a1b5d104f0ace047dc6b8d8cae1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 14:13:52 -0500 Subject: [PATCH 0761/1514] PCI: apple: refuse an adopted-link sleep in prepare, before devices suspend apple_pcie_suspend_noirq() refuses suspend-to-idle for an adopted-link host whose root complex or port links aren't up, or for a sleep other than suspend-to-idle without platform. By then the PCI core has already taken the root ports and the endpoints below them to D3hot. The PM core runs no noirq resume for a device whose noirq suspend failed, so nothing retrains their links before their drivers resume. On J775c a refusal at noirq left the RTL8127 behind root port 00:02.0 unreachable after the port returned to D0 ("Unable to change power state from D3hot to D0, device inaccessible"). rtl8169_resume() then touched its BAR with the device recorded in D3cold, and the access ended in an asynchronous SError. Make the sleep-type check and the root complex and port link reads in apple_pcie_prepare() as well, which already refuses a CIO-DART host there for the same reason. The devices' D0 reads stay in noirq, as part of the full check. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 45 ++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 9b6f1940aa4019..2cb74854a3f117 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -6863,19 +6863,15 @@ static int apple_pcie_check_d0(struct pci_dev *pdev, void *data) return *error; } -static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) +/* + * Every host whose links the boot loader trained (hw->adopt_link) keeps them + * across suspend-to-idle: the root complex and every port's link must still + * be up, read from the hardware. Deeper sleep remains unqualified. + */ +static int apple_pcie_adopted_links_ready(struct apple_pcie *pcie) { - struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); struct apple_pcie_port *port; - int error = 0; - /* - * Every host whose links the boot loader trained (hw->adopt_link) keeps - * them across suspend-to-idle: the root complex, every port's link and - * the devices below must still be up and in D0, which the checks below - * read from the hardware, before and after the sleep. Deeper sleep - * remains unqualified. - */ if (!pm_suspend_no_platform()) return -EBUSY; @@ -6891,6 +6887,17 @@ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) (apple_pcie_port_readl(port, PORT_INTSTAT) & BIT(PORT_INT_LINK_DOWN))) return -ENOLINK; } + return 0; +} + +/* ... and the devices below must still be in D0, before and after the sleep. */ +static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) +{ + struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); + int error = apple_pcie_adopted_links_ready(pcie); + + if (error) + return error; pci_walk_bus(bridge->bus, apple_pcie_check_d0, &error); return error; } @@ -7572,6 +7579,24 @@ static int apple_pcie_prepare(struct device *dev) dev_warn(dev, "no CIO sleep transaction from the NHI; refusing sleep\n"); return -EBUSY; } + /* + * An adopted link that apple_pcie_suspend_noirq() would refuse to keep: + * refuse now. Refused there, the root ports and endpoints below have + * already suspended to D3hot, this host gets no noirq resume, and nothing + * retrains their links before their drivers resume. + */ + if (pcie && !pcie->cio_prepared && !pcie->neo_sleep_armed && + !pcie->managed_sids && pcie->hw->adopt_link && + !READ_ONCE(pcie->t6050_down) && + pm_suspend_target_state != PM_SUSPEND_ON && !pm_suspend_via_firmware()) { + int ret = apple_pcie_adopted_links_ready(pcie); + + if (ret) { + dev_warn(dev, "adopted link not kept for this sleep (%d); refusing\n", + ret); + return ret; + } + } return apple_radio_prepare(dev); } From ce21cd4eded61c9ea8382e7094fce4cab0236cf1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 14:33:39 -0500 Subject: [PATCH 0762/1514] PCI: apple: decide the adopted-link s2idle check by one predicate apple_pcie_prepare() refuses an adopted-link sleep on the same terms that apple_pcie_suspend_noirq() reaches apple_pcie_check_adopted_s2idle() on, but spelled out a second copy of those terms. Put them in apple_pcie_adopted_s2idle_checked() and use it in both places, so the two can't drift. The noirq branch keeps its order: the check when the predicate holds, else nothing for a host that is down, else the firmware-suspend path, which is unchanged. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 50 ++++++++++++++++++----------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 2cb74854a3f117..e0b0e31224bc2f 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -6890,6 +6890,19 @@ static int apple_pcie_adopted_links_ready(struct apple_pcie *pcie) return 0; } +/* + * Whether apple_pcie_suspend_noirq() ends in apple_pcie_check_adopted_s2idle() + * for this host, given that it passed the CIO-DART refusal: not in a CIO or + * NEO sleep transaction, not a managed radio, an adopted host that is up, and + * no firmware suspend. apple_pcie_prepare() refuses on the same terms. + */ +static bool apple_pcie_adopted_s2idle_checked(struct apple_pcie *pcie) +{ + return !pcie->cio_prepared && !pcie->neo_sleep_armed && !pcie->managed_sids && + pcie->hw->adopt_link && !READ_ONCE(pcie->t6050_down) && + !pm_suspend_via_firmware(); +} + /* ... and the devices below must still be in D0, before and after the sleep. */ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) { @@ -6948,20 +6961,22 @@ static int apple_pcie_suspend_noirq(struct device *dev) if (!pcie->managed_sids && pcie->hw->adopt_link) { int ret; + if (apple_pcie_adopted_s2idle_checked(pcie)) { + ret = apple_pcie_check_adopted_s2idle(pcie); + pcie->link_kept = !ret; + return ret; + } /* Down since a wake that failed: nothing to keep or shut down, nothing read */ if (READ_ONCE(pcie->t6050_down)) return 0; - if (pm_suspend_via_firmware()) { - /* The root ports below are suspended: from here a parked port's is not read */ - WRITE_ONCE(pcie->t6050_cold_lost, pcie->t6050_parked); - ret = apple_pcie_t6050_sleep_down(pcie); - if (!ret && pcie->t6050_reset_before_sleep) - ret = apple_pcie_t6050_reset_for_sleep(pcie); - return ret; - } - ret = apple_pcie_check_adopted_s2idle(pcie); - - pcie->link_kept = !ret; + /* + * A firmware suspend. The root ports below are suspended: from here a + * parked port's is not read. + */ + WRITE_ONCE(pcie->t6050_cold_lost, pcie->t6050_parked); + ret = apple_pcie_t6050_sleep_down(pcie); + if (!ret && pcie->t6050_reset_before_sleep) + ret = apple_pcie_t6050_reset_for_sleep(pcie); return ret; } if (!pcie->hw->tunneled) { @@ -7580,15 +7595,14 @@ static int apple_pcie_prepare(struct device *dev) return -EBUSY; } /* - * An adopted link that apple_pcie_suspend_noirq() would refuse to keep: - * refuse now. Refused there, the root ports and endpoints below have + * An adopted link that apple_pcie_suspend_noirq() would already refuse to + * keep: refuse now. Refused there, the root ports and endpoints below have * already suspended to D3hot, this host gets no noirq resume, and nothing - * retrains their links before their drivers resume. + * retrains their links before their drivers resume. A link that drops + * after this is still refused only there. */ - if (pcie && !pcie->cio_prepared && !pcie->neo_sleep_armed && - !pcie->managed_sids && pcie->hw->adopt_link && - !READ_ONCE(pcie->t6050_down) && - pm_suspend_target_state != PM_SUSPEND_ON && !pm_suspend_via_firmware()) { + if (pcie && pm_suspend_target_state != PM_SUSPEND_ON && + apple_pcie_adopted_s2idle_checked(pcie)) { int ret = apple_pcie_adopted_links_ready(pcie); if (ret) { From c8a1558ca87ec45a7c48b949df88188ff546490d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sat, 21 Nov 2026 16:22:55 -0500 Subject: [PATCH 0763/1514] PCI: apple: refuse a firmware suspend the adopted host can't take, and skip parked ports apple_pcie_prepare() refused an adopted-link suspend-to-idle it couldn't keep, but not a firmware suspend: that one is refused only in apple_pcie_t6050_sleep_down(), at noirq, when the host has no T6050 sleep port or its DART isn't bound. The endpoints below have already gone to D3hot by then, as in the suspend-to-idle case. Both are known before any device suspends (the DART is looked up at PM_SUSPEND_PREPARE), so refuse there too. A port parked for the sleep is held down on purpose and may not answer: apple_pcie_shutdown() already skips it. Skip it in the link readiness reads as well. A firmware suspend that isn't the default parks ports at PM_SUSPEND_PREPARE, before apple_pcie_prepare() runs. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 32 +++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index e0b0e31224bc2f..fb2aed80ec54b4 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -6880,6 +6880,9 @@ static int apple_pcie_adopted_links_ready(struct apple_pcie *pcie) return -ENOLINK; list_for_each_entry(port, &pcie->ports, entry) { + /* Parked for this sleep: held down on purpose, and may not answer */ + if (pcie->t6050_parked & BIT(port->idx)) + continue; if (READ_ONCE(port->link_failed) || !(apple_pcie_port_readl(port, PORT_STATUS) & PORT_STATUS_READY) || (apple_pcie_port_readl(port, PORT_LINKSTS) & @@ -6891,16 +6894,21 @@ static int apple_pcie_adopted_links_ready(struct apple_pcie *pcie) } /* - * Whether apple_pcie_suspend_noirq() ends in apple_pcie_check_adopted_s2idle() - * for this host, given that it passed the CIO-DART refusal: not in a CIO or - * NEO sleep transaction, not a managed radio, an adopted host that is up, and - * no firmware suspend. apple_pcie_prepare() refuses on the same terms. + * An adopted host that apple_pcie_suspend_noirq() puts to sleep itself, given + * that it passed the CIO-DART refusal: not in a CIO or NEO sleep transaction, + * not a managed radio, and up. For suspend-to-idle it ends in + * apple_pcie_check_adopted_s2idle(); for a firmware suspend in + * apple_pcie_t6050_sleep_down(). apple_pcie_prepare() refuses on the same terms. */ -static bool apple_pcie_adopted_s2idle_checked(struct apple_pcie *pcie) +static bool apple_pcie_adopted_sleep_host(struct apple_pcie *pcie) { return !pcie->cio_prepared && !pcie->neo_sleep_armed && !pcie->managed_sids && - pcie->hw->adopt_link && !READ_ONCE(pcie->t6050_down) && - !pm_suspend_via_firmware(); + pcie->hw->adopt_link && !READ_ONCE(pcie->t6050_down); +} + +static bool apple_pcie_adopted_s2idle_checked(struct apple_pcie *pcie) +{ + return apple_pcie_adopted_sleep_host(pcie) && !pm_suspend_via_firmware(); } /* ... and the devices below must still be in D0, before and after the sleep. */ @@ -7602,8 +7610,14 @@ static int apple_pcie_prepare(struct device *dev) * after this is still refused only there. */ if (pcie && pm_suspend_target_state != PM_SUSPEND_ON && - apple_pcie_adopted_s2idle_checked(pcie)) { - int ret = apple_pcie_adopted_links_ready(pcie); + apple_pcie_adopted_sleep_host(pcie)) { + int ret; + + /* A firmware suspend: the port and DART apple_pcie_t6050_sleep_down() takes down */ + if (pm_suspend_via_firmware()) + ret = pcie->t6050_port && pcie->t6050_dart ? 0 : -EBUSY; + else + ret = apple_pcie_adopted_links_ready(pcie); if (ret) { dev_warn(dev, "adopted link not kept for this sleep (%d); refusing\n", From 47b6a0b9843cdb0fd2e0c31e7f761aedf9ce697c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:41:08 -0500 Subject: [PATCH 0764/1514] arm64: dts: apple: t6050: give the ATC COMMON states their fabric parents In the T6050 ADT PMGR table, ATC0_COMMON and ATC1_COMMON hang off FAB3_SOC, while ATC2_COMMON and ATC3_COMMON hang off FAB5_SOC; both fabrics sit under FAB0_PIOGW. Link ps_atc1_common, ps_atc2_common, and ps_atc3_common to their fabric parents in t6050-peripherals.dtsi and enable ps_fab0_piogw, ps_fab3_soc, and ps_fab5_soc as apple,firmware-owned so every board gets a live genpd parent without letting pmgr-pwrstate write the hardware-owned fabric registers at probe or after firmware-driven resume. Drop the now-stale power-domains deletion on ps_atc0_common in t6050-j714s-left-back.dtsi. Signed-off-by: Satya Benson --- .../boot/dts/apple/t6050-j714s-left-back.dtsi | 7 ----- .../boot/dts/apple/t6050-peripherals.dtsi | 27 ++++++++++++++++--- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi index e9de93f3d042d0..03181b7d1165f8 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-left-back.dtsi @@ -20,14 +20,7 @@ * and exporting this machine's ADT tunables. Older producers leave the port reserved. */ -/* - * The inventory gives ATC0_COMMON the FAB3 SoC domain as a parent, which is not described here. - * ATC1's and ATC2's common domains have none: do the same. J716c enables ps_fab3_soc instead, - * which would hand that fabric domain, and its other undescribed users, to genpd's unused - * power-off; left out, it stays as the boot loader leaves it, on. - */ &ps_atc0_common { - /delete-property/ power-domains; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index b85b06baf5453a..8a298c667b9d0b 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -128,7 +128,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "fab0-piogw"; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_fab3_soc: power-controller@1e0 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -137,7 +138,8 @@ #reset-cells = <0>; label = "fab3-soc"; power-domains = <&ps_fab0_piogw>; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_fab5_soc: power-controller@1f0 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -146,7 +148,8 @@ #reset-cells = <0>; label = "fab5-soc"; power-domains = <&ps_fab0_piogw>; - status = "disabled"; + apple,firmware-owned; + status = "okay"; }; ps_sbr: power-controller@1f8 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -363,6 +366,24 @@ }; }; +/* + * The ADT's PMGR device table gives every ATC's COMMON state a fabric parent: ATC0 and ATC1 + * hang off FAB3_SOC, ATC2 and ATC3 off FAB5_SOC. Without the link, genpd counts no + * powered child under the fabric while a port's PHY domains are held on, asks for the + * fabric to go off, and the PMGR refuses the write. + */ +&ps_atc1_common { + power-domains = <&ps_fab3_soc>; +}; + +&ps_atc2_common { + power-domains = <&ps_fab5_soc>; +}; + +&ps_atc3_common { + power-domains = <&ps_fab5_soc>; +}; + &pmgr1 { ps_ispsens0: power-controller@100 { compatible = "apple,t6050-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; From 2667b1b9b3b33d06fa968584c8633a380efc8826 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:41:13 -0500 Subject: [PATCH 0765/1514] phy: apple: dptx: let the T6050 PHY's power domain follow its link The T6050 DPTX PHY powers its blocks up and down with the display link in t6050_activate() and t6050_deactivate(), but previously never enabled runtime PM so its power domain stayed on whenever the link was parked. Enable runtime PM on T6050 DPTX PHYs and hold a runtime-PM reference for each active DP link: - Take an initial probe-time reference (boot_hold) with a devm release action so a live bootloader simplefb link is protected from genpd unused power-off until DCP's first mode switch, without leaking the reference if probe fails later or the driver unbinds first. - Reject unsupported PHY modes with -EINVAL before touching boot_hold or taking the mutex. - Drop the active link's reference on deactivation (even if PLL power-down reports an error, since t6050_deactivate() always clears active and powers down the blocks) and log runtime-PM put errors instead of overriding a completed deactivation. Signed-off-by: Satya Benson --- drivers/phy/apple/dptx.c | 99 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 95 insertions(+), 4 deletions(-) diff --git a/drivers/phy/apple/dptx.c b/drivers/phy/apple/dptx.c index f191efe4c62866..7405b7d1c7ad0f 100644 --- a/drivers/phy/apple/dptx.c +++ b/drivers/phy/apple/dptx.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -75,6 +76,8 @@ struct apple_dptx_phy { u32 source_select; bool pclkdrv_select; bool active; + /* T6050: the domain reference taken at probe, until the first mode switch */ + bool boot_hold; u32 rate; /* Mbit/s; 0: none programmed */ struct phy *phy_dp; @@ -932,14 +935,55 @@ static int dptx_phy_set_mode(struct phy *phy, enum phy_mode mode, int submode) struct apple_dptx_phy *dptx_phy = phy_get_drvdata(phy); if (dptx_phy->hw.type == DPTX_PHY_T6050) { - int ret = -EINVAL; + struct device *dev = dptx_phy->dev; + bool was_active, boot_hold; + int pm_ret, ret = -EINVAL; + + if (mode != PHY_MODE_DP && mode != PHY_MODE_INVALID) + return -EINVAL; mutex_lock(&dptx_phy->lock); - if (mode == PHY_MODE_INVALID) + /* An active link holds the PHY's power domain, see dptx_phy_probe(). */ + if (mode == PHY_MODE_DP && dptx_phy->active) { + mutex_unlock(&dptx_phy->lock); + return 0; + } + if (mode == PHY_MODE_DP) { + ret = phy_pm_runtime_get_sync(phy); + if (ret < 0) { + mutex_unlock(&dptx_phy->lock); + return ret; + } + } + was_active = dptx_phy->active; + if (mode == PHY_MODE_INVALID) { ret = t6050_deactivate(dptx_phy); - else if (mode == PHY_MODE_DP) - ret = dptx_phy->active ? 0 : t6050_activate(dptx_phy); + } else if (mode == PHY_MODE_DP) { + ret = t6050_activate(dptx_phy); + if (ret) + t6050_deactivate(dptx_phy); + } + boot_hold = dptx_phy->boot_hold; + dptx_phy->boot_hold = false; mutex_unlock(&dptx_phy->lock); + + /* + * t6050_deactivate() powers the blocks down and clears ->active + * even when the PLL power-down reports an error, so an active + * link's reference goes with it whatever it returned. A put that + * fails after the PHY is already down is only reported: failing + * the mode switch would leave the PHY core's mode at DP. + */ + pm_ret = 0; + if (mode == PHY_MODE_DP && ret) + pm_ret = phy_pm_runtime_put_sync(phy); + else if (mode == PHY_MODE_INVALID && was_active) + pm_ret = phy_pm_runtime_put_sync(phy); + if (pm_ret < 0) + dev_warn(dev, "runtime PM put failed: %d\n", pm_ret); + /* The DCP owns the link from its first mode switch on. */ + if (boot_hold) + pm_runtime_put(dev); return ret; } @@ -1045,10 +1089,25 @@ static const struct phy_ops apple_atc_dp_phy_ops = { .set_mode = dptx_phy_set_mode, }; +static void dptx_phy_drop_boot_hold(void *data) +{ + struct apple_dptx_phy *dptx_phy = data; + bool drop; + + mutex_lock(&dptx_phy->lock); + drop = dptx_phy->boot_hold; + dptx_phy->boot_hold = false; + mutex_unlock(&dptx_phy->lock); + + if (drop) + pm_runtime_put_noidle(dptx_phy->dev); +} + static int dptx_phy_probe(struct platform_device *pdev) { struct apple_dptx_phy *dptx_phy; struct device *dev = &pdev->dev; + int ret; dptx_phy = devm_kzalloc(dev, sizeof(*dptx_phy), GFP_KERNEL); if (!dptx_phy) @@ -1070,6 +1129,38 @@ static int dptx_phy_probe(struct platform_device *pdev) if (IS_ERR(dptx_phy->regs.dptx)) return PTR_ERR(dptx_phy->regs.dptx); + /* + * The T6050 PHY powers its blocks up and down with the link + * (t6050_activate(), t6050_deactivate()); runtime PM lets its power + * domain follow. + */ + if (dptx_phy->hw.type == DPTX_PHY_T6050) { + /* + * The boot loader may leave an HDMI link up for simplefb, and + * nothing else holds the domain before the DCP's first mode + * switch, which can come late (or never, if the DCP fails). + * Start active with a reference which that switch drops, so + * genpd's unused power-off cannot take the domain from a live + * link before then. + */ + pm_runtime_get_noresume(dev); + ret = pm_runtime_set_active(dev); + if (ret) { + pm_runtime_put_noidle(dev); + return ret; + } + ret = devm_pm_runtime_enable(dev); + if (ret) { + pm_runtime_put_noidle(dev); + return ret; + } + dptx_phy->boot_hold = true; + ret = devm_add_action_or_reset(dev, dptx_phy_drop_boot_hold, + dptx_phy); + if (ret) + return ret; + } + /* create phy */ dptx_phy->phy_dp = devm_phy_create(dptx_phy->dev, NULL, &apple_atc_dp_phy_ops); From 8f3d074923d050617fdad2ff9e8165aec0ba1710 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:43:58 -0500 Subject: [PATCH 0766/1514] tools/asahi: pciec-policy-tests: cover adopted-link prepare refusals Extend the pciec-policy-tests.py s2idle harness so apple_pcie_prepare() builds against the adopted-link refusal helpers (apple_pcie_adopted_links_ready and apple_pcie_adopted_sleep_host), and add positive and negative-control cases for s2idle root-complex and port link checks, parked-port skipping, and firmware-suspend port/DART prerequisites. Signed-off-by: Satya Benson --- tools/asahi/pciec-policy-tests.py | 157 +++++++++++++++++++++++++++++- 1 file changed, 156 insertions(+), 1 deletion(-) diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index ef1c5d8836c4c6..ca32f33965e774 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -146,6 +146,7 @@ def function(source, name): #include #include #include +typedef uint8_t u8; typedef uint32_t u32; #define BIT(n) (1U << (n)) #define GENMASK(h, l) ((~0U << (l)) & (~0U >> (31 - (h)))) @@ -187,24 +188,72 @@ def function(source, name): }; struct apple_dart_cio { int dummy; }; struct hw_info; +struct list_head { + struct list_head *next, *prev; +}; +#define list_for_each_entry(pos, head, member) for (pos = container_of((head)->next, typeof(*pos), member); &pos->member != (head); pos = container_of(pos->member.next, typeof(*pos), member)) +static void list_init(struct list_head *head) +{ + head->next = head; + head->prev = head; +} +static void list_add_tail(struct list_head *entry, struct list_head *head) +{ + entry->next = head; + entry->prev = head->prev; + head->prev->next = entry; + head->prev = entry; +} +struct apple_pcie_port { + struct list_head entry; + unsigned int idx; + bool link_failed; + u8 regs[0x900]; +}; struct apple_pcie { struct device *dev; const struct hw_info *hw; + u8 *base; + struct list_head ports; bool power_retained, kernel_init, tunnel_cold_init; bool bus_stopped, resume_failed, link_kept; struct apple_pcie_pd *pds; unsigned int num_pds, pd_held; struct apple_dart_cio *cio_dart; - bool cio_prepared; + bool cio_prepared, neo_sleep_armed, t6050_down; + unsigned int managed_sids; + void *t6050_port, *t6050_dart; + u32 t6050_parked; }; static bool s2idle_keep_link = true; static int pm_suspend_target_state = PM_SUSPEND_TO_IDLE; +static bool suspend_via_firmware; static bool link_healthy = true; static unsigned int radio_prepare_calls, warn_calls; +static u32 readl(const void *addr) +{ + u32 v; + + memcpy(&v, addr, sizeof(v)); + return v; +} +static void writel(u32 v, void *addr) +{ + memcpy(addr, &v, sizeof(v)); +} +static u32 apple_pcie_port_readl(struct apple_pcie_port *port, u32 reg) +{ + assert(reg + sizeof(u32) <= sizeof(port->regs)); + return readl(port->regs + reg); +} static bool pm_suspend_no_platform(void) { return pm_suspend_target_state == PM_SUSPEND_TO_IDLE; } +static bool pm_suspend_via_firmware(void) +{ + return suspend_via_firmware; +} static struct apple_pcie *apple_pcie_lookup(struct device *dev) { return dev ? dev->pcie : NULL; @@ -274,8 +323,10 @@ def function(source, name): pcie->pds = pd; pcie->num_pds = 1; pcie->cio_dart = cio_dart; + list_init(&pcie->ports); s2idle_keep_link = true; pm_suspend_target_state = PM_SUSPEND_TO_IDLE; + suspend_via_firmware = false; link_healthy = true; radio_prepare_calls = 0; warn_calls = 0; @@ -401,6 +452,98 @@ def function(source, name): assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); assert(apple_pcie_keep_link(&pcie) && pcie.pd_held == 0 && dev.add_calls == 0); + /* Adopted T6050 host: s2idle and firmware-suspend refusals in prepare. */ + const struct hw_info *t6050_adopt = match_compat("apple,t6050-pcie"); + assert(t6050_adopt && t6050_adopt->adopt_link); + + u8 rc_regs[0x100]; + struct apple_pcie_port p0, p1; + int dummy_port = 1, dummy_dart = 1; + + #define RESET_ADOPTED() do { reset_host(&dev, &pcie, &pd, t6050_adopt, NULL); memset(rc_regs, 0, sizeof(rc_regs)); pcie.base = rc_regs; writel(CORE_RC_CTL_RUN, rc_regs + CORE_RC_CTL); writel(CORE_RC_STAT_READY, rc_regs + CORE_RC_STAT); memset(&p0, 0, sizeof(p0)); p0.idx = 0; writel(PORT_STATUS_READY, p0.regs + PORT_STATUS); writel(PORT_LINKSTS_UP, p0.regs + PORT_LINKSTS); list_add_tail(&p0.entry, &pcie.ports); memset(&p1, 0, sizeof(p1)); p1.idx = 1; writel(PORT_STATUS_READY, p1.regs + PORT_STATUS); writel(PORT_LINKSTS_UP, p1.regs + PORT_LINKSTS); list_add_tail(&p1.entry, &pcie.ports); } while (0) + + /* Healthy adopted host passes s2idle prepare. */ + RESET_ADOPTED(); + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Non-s2idle without firmware suspend refuses with -EBUSY in prepare. */ + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + /* Root complex not running or not ready refuses with -ENOLINK. */ + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_STAT); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + /* Unparked port link_failed / not ready / link down / interrupt refuses with -ENOLINK. */ + RESET_ADOPTED(); + p1.link_failed = true; + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(0, p1.regs + PORT_STATUS); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(PORT_LINKSTS_UP | PORT_LINKSTS_BUSY, p1.regs + PORT_LINKSTS); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + writel(BIT(PORT_INT_LINK_DOWN), p1.regs + PORT_INTSTAT); + assert(apple_pcie_prepare(&dev) == -ENOLINK && radio_prepare_calls == 0 && warn_calls == 1); + + /* Parked port with dead link registers is skipped and passes prepare. */ + RESET_ADOPTED(); + p1.link_failed = true; + writel(0, p1.regs + PORT_STATUS); + writel(0, p1.regs + PORT_LINKSTS); + writel(BIT(PORT_INT_LINK_DOWN), p1.regs + PORT_INTSTAT); + pcie.t6050_parked = BIT(p1.idx); + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Firmware suspend refuses without both t6050_port and t6050_dart, passes with both. */ + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_port = &dummy_port; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_dart = &dummy_dart; + assert(apple_pcie_prepare(&dev) == -EBUSY && radio_prepare_calls == 0 && warn_calls == 1); + + RESET_ADOPTED(); + pm_suspend_target_state = PM_SUSPEND_MEM; + suspend_via_firmware = true; + pcie.t6050_port = &dummy_port; + pcie.t6050_dart = &dummy_dart; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + /* Already-down, managed-radio, or NEO/CIO-prepared adopted host bypasses adopted check. */ + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + pcie.t6050_down = true; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + RESET_ADOPTED(); + writel(0, rc_regs + CORE_RC_CTL); + pcie.managed_sids = 1; + assert(apple_pcie_prepare(&dev) == 0 && radio_prepare_calls == 1 && warn_calls == 0); + + #undef RESET_ADOPTED + puts("PASS: T6050 PCIe-C s2idle domain hold, release, deep sleep and prepare refusal"); return 0; } @@ -447,6 +590,8 @@ def main(): 'apple_pcie_hold_domains', 'apple_pcie_can_keep_link', 'apple_pcie_keep_link', + 'apple_pcie_adopted_links_ready', + 'apple_pcie_adopted_sleep_host', 'apple_pcie_prepare')))) s2idle_code = S2IDLE_FIXTURE.replace('/* PRODUCTION */', s2idle_prod) t6050_old = '\t.mps_timers\t\t= true,\n\t.s2idle_hold_domain\t= true,\n' @@ -478,6 +623,16 @@ def main(): 'dev_pm_genpd_remove_notifier(pd->dev);', '(void)pd;'), 'ignore-domain-off': ( 'if (!dev_pm_genpd_is_on(pd->dev)) {', 'if (false) {'), + 'drop-adopted-prepare-guard': ( + 'if (pcie && pm_suspend_target_state != PM_SUSPEND_ON &&\n' + '\t apple_pcie_adopted_sleep_host(pcie)) {', + 'if (false) {'), + 'drop-adopted-fw-sleep-guard': ( + 'ret = pcie->t6050_port && pcie->t6050_dart ? 0 : -EBUSY;', + 'ret = 0;'), + 'drop-adopted-parked-skip': ( + 'if (pcie->t6050_parked & BIT(port->idx))\n\t\t\tcontinue;', + 'if (false)\n\t\t\tcontinue;'), } s2idle_cases = {'s2idle-production': s2idle_code} for name, (old, new) in s2idle_muts.items(): From 3133760aed498ba0cbba0a75d89b2f22e42acfca Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:52:04 -0500 Subject: [PATCH 0767/1514] sched/fair: Wake brief tasks on the waking CPU when the waker is brief too A pipe or futex ping-pong between two threads costs 13-17 us per round trip on an M5 Max (T6050) against 2.4-2.7 us on macOS on the same machine, and 1.1 us when both threads are pinned to one CPU. Traced with sched_waking/ipi/cpu_idle/sched_switch events, every wake-up of the partner's idle CPU takes about 3 us from the IPI to the core leaving WFI (the hardware powers idle cores down in WFI) and about 5 us until the wakee runs; and with each CPU busy only ~10% of the time, schedutil keeps the clusters at 1.3-2.3 GHz instead of 4.4-4.6 GHz. Even with the performance governor a cross-CPU round trip stays at 5-7 us. When the wakee and the waker both run only briefly between sleeps and the waker is alone on its CPU, wake the wakee there. Such a pair takes turns, so the wakee runs as soon as the waker sleeps, without an IPI or a core wake-up, and the pair keeps one CPU busy at a high clock. "Briefly" is a decaying average of the run time between sleeps below sysctl_sched_migration_cost / 8 (62.5 us by default) for both tasks, and the waker's runtime since its last sleep below the same limit. Include the unaccounted portion from exec_start to the refreshed rq task clock under the local rq lock (clamping negative deltas like update_se()), so a scheduler tick is not needed to see it, and check sched_cpu_cookie_match() under the rq lock so core scheduling cookies are respected. Requiring the waker to be alone stacks at most one wakee on a CPU. wake_wide() still spreads tasks that wake many others. The run time between sleeps is accounted in dequeue_task_fair() when a task sleeps (including throttled sleeps) and prev_sleep_sum_runtime is resynced in switched_to_fair() so prior non-fair execution is not folded into the first fair burst. Give energy-aware scheduling first choice. This keeps its placement when it finds a CPU and leaves the short-wake heuristic for the normal fair wake path. The T6050 tables on this base have neither OPP power nor a CPU dynamic-power coefficient, so the DT-based cpufreq energy model is unavailable. The WAKE_SHORT_LOCAL scheduler feature turns it off at run time. Signed-off-by: Satya Benson --- include/linux/sched.h | 8 ++++ kernel/sched/core.c | 2 + kernel/sched/fair.c | 87 ++++++++++++++++++++++++++++++++++++++++- kernel/sched/features.h | 7 ++++ 4 files changed, 103 insertions(+), 1 deletion(-) diff --git a/include/linux/sched.h b/include/linux/sched.h index 57ef9a060eb653..a6f978d4f3fe9f 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -598,6 +598,14 @@ struct sched_entity { u64 nr_migrations; + /* + * Run time between sleeps: sum_exec_runtime when the task last went + * to sleep, and the decaying average of the run time between two + * sleeps. See wake_short_local(). + */ + u64 prev_sleep_sum_runtime; + u64 burst_avg; + #ifdef CONFIG_FAIR_GROUP_SCHED int depth; struct sched_entity *parent; diff --git a/kernel/sched/core.c b/kernel/sched/core.c index c481404713aaa5..b0719d48538186 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -4666,6 +4666,8 @@ static void __sched_fork(u64 clone_flags, struct task_struct *p) p->se.sum_exec_runtime = 0; p->misfit_runtime = 0; p->se.prev_sum_exec_runtime = 0; + p->se.prev_sleep_sum_runtime = 0; + p->se.burst_avg = 0; p->se.nr_migrations = 0; p->se.vruntime = 0; p->se.vlag = 0; diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 5c8f84186e2cc5..f51fff11a97295 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -8414,6 +8414,15 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) return true; } +/* Account the run time since @p last slept, as it goes to sleep again. */ +static inline void update_burst_avg(struct task_struct *p) +{ + u64 burst = p->se.sum_exec_runtime - p->se.prev_sleep_sum_runtime; + + p->se.prev_sleep_sum_runtime = p->se.sum_exec_runtime; + update_avg(&p->se.burst_avg, burst); +} + /* * The dequeue_task method is called before nr_running is * decreased. We remove the task from the rbtree and @@ -8421,16 +8430,29 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) */ static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) { + bool sleep = (flags & (DEQUEUE_SLEEP | DEQUEUE_DELAYED)) == DEQUEUE_SLEEP; + if (task_is_throttled(p)) { dequeue_throttled_task(p, flags); + if (sleep) + update_burst_avg(p); return true; } if (!p->se.sched_delayed) util_est_dequeue(&rq->cfs, p); - if (!__dequeue_task(rq, p, flags)) + /* + * After the dequeue, which updated sum_exec_runtime. Without + * DEQUEUE_DELAYED, @p is the task going to sleep and stays valid. + */ + if (!__dequeue_task(rq, p, flags)) { + if (sleep) + update_burst_avg(p); return false; + } + if (sleep) + update_burst_avg(p); /* * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED). @@ -9916,6 +9938,63 @@ static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) return target; } +/* + * Wake @p on @cpu, the waking CPU, rather than on an idle CPU, when @p and the + * waker both run only briefly between sleeps and the waker is alone on @cpu. + * + * Such a pair takes turns: one wakes the other and soon sleeps, as in a pipe + * or futex ping-pong, or a thread waking the thread that joins it. On an idle + * CPU every turn costs an IPI and the wake-up of a sleeping core, several + * microseconds on Apple cores, whose WFI lets the hardware power them down, + * and each CPU stays so lightly loaded that schedutil keeps the cluster at a + * low clock. On the waking CPU the wakee runs as soon as the waker sleeps, + * and the pair keeps one CPU busy at a high clock. + * + * Only brief runs qualify, so a task that keeps running after a wake-up does + * not hold up its wakee for longer than that; and only a waker alone on its + * CPU, so at most one wakee is stacked on it. Tasks that wake many others are + * spread by wake_wide() before this is considered. + */ +static bool wake_short_local(struct task_struct *p, int cpu) +{ + u64 limit = sysctl_sched_migration_cost / 8; + struct task_struct *waker = current; + struct rq *rq = cpu_rq(cpu); + struct rq_flags rf; + bool brief = false; + + if (!in_task() || waker->sched_class != &fair_sched_class) + return false; + if (p->se.burst_avg > limit || waker->se.burst_avg > limit) + return false; + if (sched_asym_cpucap_active() && !task_fits_cpu(p, cpu)) + return false; + + /* + * The wakeup path has IRQs disabled and holds p->pi_lock. Skip this + * heuristic if the local rq lock is already held or contended. + */ + if (!raw_spin_rq_trylock(rq)) + return false; + rq_pin_lock(rq, &rf); + + if (rq->nr_running - cfs_h_nr_delayed(rq) == 1 && + task_current_donor(rq, waker) && + sched_cpu_cookie_match(rq, p)) { + u64 burst = waker->se.sum_exec_runtime - waker->se.prev_sleep_sum_runtime; + s64 delta; + + update_rq_clock(rq); + delta = rq_clock_task(rq) - waker->se.exec_start; + if (delta > 0) + burst += delta; + brief = burst <= limit; + } + rq_unlock(rq, &rf); + + return brief; +} + /* * select_task_rq_fair: Select target runqueue for the waking task in domains * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, @@ -9956,6 +10035,11 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) } want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); + + /* Preserve a placement selected by EAS above. */ + if (sched_feat(WAKE_SHORT_LOCAL) && want_affine && + wake_short_local(p, cpu)) + return cpu; } for_each_domain(cpu, tmp) { @@ -15653,6 +15737,7 @@ static void switched_to_fair(struct rq *rq, struct task_struct *p) WARN_ON_ONCE(p->se.sched_delayed); attach_task_cfs_rq(p); + p->se.prev_sleep_sum_runtime = p->se.sum_exec_runtime; set_task_max_allowed_capacity(p); diff --git a/kernel/sched/features.h b/kernel/sched/features.h index 07132f33d1e4a3..ecab475582cf0f 100644 --- a/kernel/sched/features.h +++ b/kernel/sched/features.h @@ -94,6 +94,13 @@ SCHED_FEAT(TTWU_QUEUE, true) */ SCHED_FEAT(SIS_UTIL, true) +/* + * Wake a task that runs only briefly between sleeps on the waking CPU when + * the waker also runs briefly and is alone there, instead of on an idle CPU. + * See wake_short_local(). + */ +SCHED_FEAT(WAKE_SHORT_LOCAL, true) + /* * Issue a WARN when we do multiple update_rq_clock() calls * in a single rq->lock section. Default disabled because the From a052cab0076b2d1bca8b12f4b1745386d566944c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:52:17 -0500 Subject: [PATCH 0768/1514] sched/fair: Start new threads on an idle CPU of the creating CPU's LLC Fork balancing starts a new task in the idlest group of the widest domain with SD_BALANCE_FORK. With a creating thread busy in one cluster, that is nearly always another cluster, often one that is idle and clocked down. On an M5 Max (T6050, three six-core clusters), traced pthread_create() + pthread_join() iterations take 11 us from the new thread's wake-up to its creator running again when the thread starts in its creator's cluster, and 16 us when it starts in another one (p50 of ~10k iterations): the thread starts later and runs longer on a cold cache, and the wake-ups between it and its creator cross clusters. The whole create+join loop costs 25-32 us against 12 us on macOS. Start a new thread, a task sharing its creator's mm, on an idle CPU in the creating CPU's LLC domain when there is one, provided the LLC domain has SD_BALANCE_FORK, the candidate CPU lies within the enclosing fork-balance domain span, and its core-scheduling cookie matches. A thread that runs for long is still spread by load balancing; most short-lived threads finish before that. New processes keep the usual fork and exec balancing. On asymmetric systems, skip CPUs that cannot fit the new task, including its utilization clamps. Fall back to normal fork balancing if no suitable local CPU is idle. FORK_LOCAL is disabled by default pending throughput tests across architectures. The heuristic follows the scheduler's LLC domains. T6050 needs next-level-cache links to describe its per-cluster caches; without those links this base groups the J775c CPUs into one LLC. T8103 and T8132 already describe per-cluster L2 caches and need hardware qualification when the feature is enabled. Signed-off-by: Satya Benson --- kernel/sched/fair.c | 44 ++++++++++++++++++++++++++++++++++++++++- kernel/sched/features.h | 6 ++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index f51fff11a97295..e78c96646532c2 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -9995,6 +9995,40 @@ static bool wake_short_local(struct task_struct *p, int cpu) return brief; } +/* + * Returns an idle CPU sharing the last-level cache with @cpu, the CPU creating + * the thread @p, or -1. + * + * Fork balancing otherwise starts @p in the idlest group of the widest domain, + * which on a system of several clusters is usually another cluster: the + * thread then starts on a core of a cold, often clocked-down cluster, misses + * in a cache that does not hold its parent's data, and the wake-ups between + * it and its parent cross clusters. A thread that runs for long is spread by + * load balancing anyway; most short-lived threads are done before then. New + * processes keep the usual fork and exec balancing. + */ +static int fork_local_idle_cpu(struct sched_domain *sd, + struct task_struct *p, int cpu) +{ + struct sched_domain *llc_sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); + int i; + + if (!llc_sd || !(llc_sd->flags & SD_BALANCE_FORK)) + return -1; + for_each_cpu_wrap(i, sched_domain_span(llc_sd), cpu + 1) { + if (i == cpu || !cpumask_test_cpu(i, sched_domain_span(sd)) || + !cpumask_test_cpu(i, p->cpus_ptr)) + continue; + if (!sched_core_cookie_match(cpu_rq(i), p)) + continue; + if (sched_asym_cpucap_active() && !task_fits_cpu(p, i)) + continue; + if (choose_idle_cpu(i, p)) + return i; + } + return -1; +} + /* * select_task_rq_fair: Select target runqueue for the waking task in domains * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, @@ -10068,8 +10102,16 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) } /* Slow path */ - if (unlikely(sd)) + if (unlikely(sd)) { + if (sched_feat(FORK_LOCAL) && (wake_flags & WF_FORK) && + p->mm && p->mm == current->mm) { + int i = fork_local_idle_cpu(sd, p, cpu); + + if (i >= 0) + return i; + } return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); + } /* Fast path */ if (wake_flags & WF_TTWU) diff --git a/kernel/sched/features.h b/kernel/sched/features.h index ecab475582cf0f..bbcbb5a4c3180c 100644 --- a/kernel/sched/features.h +++ b/kernel/sched/features.h @@ -101,6 +101,12 @@ SCHED_FEAT(SIS_UTIL, true) */ SCHED_FEAT(WAKE_SHORT_LOCAL, true) +/* + * Start a new thread on an idle CPU that shares the last-level cache with + * the thread creating it, before looking further. See fork_local_idle_cpu(). + */ +SCHED_FEAT(FORK_LOCAL, false) + /* * Issue a WARN when we do multiple update_rq_clock() calls * in a single rq->lock section. Default disabled because the From c412d8fd15192b84238f074d72756e283656fcc0 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 20:52:17 -0500 Subject: [PATCH 0769/1514] sched/fair: Start new processes on an idle CPU of the parent's LLC too FORK_LOCAL starts a new thread on an idle CPU of its creator's LLC; a new process still goes to the idlest group of the widest domain, on an M5 Max (T6050) nearly always another cluster, often idle and clocked down. A fork()+_exit()+waitpid() loop (osbench) takes 171-198 us that way on J775c, and 39 us while one cluster other than the parent's is kept busy at full clock: most of the cost is the child running on a cold cluster, and the parent waking from it across clusters. Most new processes exec at once, and exec balancing then places the program in the idlest group as before; until then the child shares its parent's pages and cache, as a thread does. Start new processes like new threads. Both paths use the opt-in FORK_LOCAL feature. A same-boot J775c comparison with the cache topology present found a 12-16% posix_spawn slowdown with the feature enabled. Keep it disabled by default until that cost is explained and throughput is qualified across architectures. Signed-off-by: Satya Benson --- kernel/sched/fair.c | 10 ++++++---- kernel/sched/features.h | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index e78c96646532c2..98dcd6d33d15d4 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -10004,8 +10004,11 @@ static bool wake_short_local(struct task_struct *p, int cpu) * thread then starts on a core of a cold, often clocked-down cluster, misses * in a cache that does not hold its parent's data, and the wake-ups between * it and its parent cross clusters. A thread that runs for long is spread by - * load balancing anyway; most short-lived threads are done before then. New - * processes keep the usual fork and exec balancing. + * load balancing anyway; most short-lived threads are done before then. + * + * A new process gets the same start: most new processes exec at once, and + * exec balancing still places the program they run in the idlest group; + * until then the child shares its parent's pages and cache. */ static int fork_local_idle_cpu(struct sched_domain *sd, struct task_struct *p, int cpu) @@ -10103,8 +10106,7 @@ select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) /* Slow path */ if (unlikely(sd)) { - if (sched_feat(FORK_LOCAL) && (wake_flags & WF_FORK) && - p->mm && p->mm == current->mm) { + if (sched_feat(FORK_LOCAL) && (wake_flags & WF_FORK) && p->mm) { int i = fork_local_idle_cpu(sd, p, cpu); if (i >= 0) diff --git a/kernel/sched/features.h b/kernel/sched/features.h index bbcbb5a4c3180c..71afc624b09b58 100644 --- a/kernel/sched/features.h +++ b/kernel/sched/features.h @@ -102,8 +102,9 @@ SCHED_FEAT(SIS_UTIL, true) SCHED_FEAT(WAKE_SHORT_LOCAL, true) /* - * Start a new thread on an idle CPU that shares the last-level cache with - * the thread creating it, before looking further. See fork_local_idle_cpu(). + * Start a new thread or process on an idle CPU that shares the last-level + * cache with the task creating it, before looking further. See + * fork_local_idle_cpu(). */ SCHED_FEAT(FORK_LOCAL, false) From 48737a07affc0b94250e39633925a4ca0085371d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 21:07:26 -0500 Subject: [PATCH 0770/1514] drm/apple: assert fixed HDMI HPD before waiting for its link A fixed HDMI port inherited from the boot loader can already have a configured default surface. When Linux calls dptxport_request_display() while AP HPD is still withheld, the firmware does not issue a fresh link configuration callback and dcp_dptx_wait_linkcfg() times out after two seconds, causing Linux to withdraw the display. Extract dcp_assert_hpd_before_link_wait() and assert AP HPD before the link-configuration wait on non-Type-C fixed HDMI connectors with an HPD GPIO, sampling the converter GPIO first and unwinding through out_release on unplug or RPC error. Keep Type-C, T6020 tunnel, and late-HPD ordering unchanged, and skip the early assertion when dp2hdmi is active so paths with their own HPD ownership (13.5 DP2HDMI from #527 and adopted sessions) keep their existing behavior without double-asserting HPD. Log a transient low-GPIO unplug race (-ENOLINK) at dev_dbg rather than dev_err. Update the apple-dcp fast-replug-bounce host fixture for the extracted helper and add apple-dcp-early-hpd.py covering the early-HPD ordering, GPIO/RPC error unwind, dp2hdmi exclusion, late-HPD, Type-C, and tunnel paths. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/dcp.c | 49 +++++++--- .../drivers/gpu/apple-dcp-early-hpd.py | 89 +++++++++++++++++++ .../drivers/gpu/apple-dcp/lifecycle.py | 9 ++ 3 files changed, 137 insertions(+), 10 deletions(-) create mode 100755 tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 0666748f436d0d..04e7d08211d07b 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2308,6 +2308,37 @@ static unsigned long dcp_dptx_wait_linkcfg(struct apple_dcp *dcp, u32 port, } } +/* + * A fixed HDMI port can come up from the boot loader with a default surface + * already active, in which case the firmware does not start fresh link + * training while AP HPD is withheld. Assert AP HPD from the converter's real + * HPD GPIO before waiting for link configuration, except on paths where HPD + * has another owner (such as 13.5 DP2HDMI, where the converter holds HPD on + * its own and linkcfg timeout is non-fatal, or an adopted session whose + * post-wait path drives HPD). + */ +static int dcp_assert_hpd_before_link_wait(struct apple_dcp *dcp, u32 port, + bool late_hpd, bool skip_fixed_hdmi) +{ + bool typec = dcp_is_typec_output(dcp); + bool fixed_hdmi = !typec && !skip_fixed_hdmi && + dcp->fixed_connector_type == DRM_MODE_CONNECTOR_HDMIA && + dcp->hdmi_hpd; + int level; + + if (late_hpd || (!typec && !fixed_hdmi)) + return 0; + if (fixed_hdmi) { + level = gpiod_get_value_cansleep(dcp->hdmi_hpd); + if (level <= 0) + return level < 0 ? level : -ENOLINK; + } + if (dcp_uses_t6020_tunnel_flow(dcp)) + return dptxport_set_hpd_timeout(dcp->dptxport[port].service, + true, 8000); + return dptxport_set_hpd(dcp->dptxport[port].service, true); +} + /* * Connect DPTX port @port. On failure, @retryable (if given) tells whether * the attempt left nothing outstanding in the firmware, so that a later @@ -2460,19 +2491,17 @@ static int dcp_dptx_connect_raw(struct apple_dcp *dcp, u32 port, bool *retryable goto out_release; } dcp->dptxport[port].connected = true; - if (dcp_is_typec_output(dcp) && !late_hpd) { - if (dcp_uses_t6020_tunnel_flow(dcp)) - ret = dptxport_set_hpd_timeout(dcp->dptxport[port].service, - true, 8000); + ret = dcp_assert_hpd_before_link_wait(dcp, port, late_hpd, dp2hdmi); + if (ret) { + if (ret == -ENOLINK) + dev_dbg(dcp->dev, + "dcp_dptx_connect: HDMI HPD dropped before assert\n"); else - ret = dptxport_set_hpd(dcp->dptxport[port].service, true); - if (ret) { dev_err(dcp->dev, - "dcp_dptx_connect: failed to assert Type-C HPD: %d\n", + "dcp_dptx_connect: failed to assert AP HPD: %d\n", ret); - dcp->dptxport[port].connected = false; - goto out_release; - } + dcp->dptxport[port].connected = false; + goto out_release; } mutex_unlock(&dcp->hpd_mutex); diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py b/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py new file mode 100755 index 00000000000000..577d6cb04c7573 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/apple-dcp-early-hpd.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the real early-HPD helper with GPIO/RemotePort leaves modelled. + +No kernel or hardware executes. Tests that an inherited HDMI link can receive +its training trigger before the waiter, plus detach/read/RPC failure behavior +and the existing Type-C, tunnel and late-HPD paths. +""" +import os +from pathlib import Path +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[5] +source = Path(os.environ.get('DCP_SOURCE', root / 'drivers/gpu/drm/apple/dcp.c')).read_text() +a = source.index('static int dcp_assert_hpd_before_link_wait(') +b = source.index('\n}\n', a) + 3 +body = source[a:b] +prefix = r''' +#include +#include +#include +#include +#include +typedef uint32_t u32; +#define DRM_MODE_CONNECTOR_HDMIA 11 +struct apple_dcp { + int fixed_connector_type; void *hdmi_hpd; + bool typec, tunnel; struct {void *service;} dptxport[2]; +}; +static int level=1, rpc_error, samples, calls, timeout_ms; +static bool link_configured; +static bool dcp_is_typec_output(struct apple_dcp*d){return d->typec;} +static bool dcp_uses_t6020_tunnel_flow(struct apple_dcp*d){return d->tunnel;} +static int gpiod_get_value_cansleep(void*p){assert(p);samples++;return level;} +static int dptxport_set_hpd(void*p,bool high) +{assert(p==(void*)123&&high);calls++;if(!rpc_error)link_configured=true;return rpc_error;} +static int dptxport_set_hpd_timeout(void*p,bool high,unsigned ms) +{timeout_ms=ms;return dptxport_set_hpd(p,high);} +''' +cases = r''' +int main(void) +{ + struct apple_dcp d={.fixed_connector_type=DRM_MODE_CONNECTOR_HDMIA,.hdmi_hpd=(void*)1, + .dptxport={{(void*)123},{0}}}; + /* Model the observed inherited-display dependency: without AP HPD the + * request is accepted but the link waiter receives no training event. */ + assert(!link_configured);assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false)); + assert(link_configured&&samples==1&&calls==1&&!timeout_ms); + calls=samples=0;link_configured=false;level=0; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-ENOLINK); + assert(samples==1&&!calls&&!link_configured); + level=-EIO;samples=0; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-EIO); + assert(samples==1&&!calls); + level=1;rpc_error=-ETIMEDOUT; + assert(dcp_assert_hpd_before_link_wait(&d,0,false,false)==-ETIMEDOUT); + assert(!link_configured);rpc_error=0; + calls=samples=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,true,false));assert(!calls&&!samples); + /* 13.5 DP2HDMI and adopted sessions keep their own HPD owner. */ + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,true));assert(!calls&&!samples); + d.fixed_connector_type=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(!calls&&!samples); + d.fixed_connector_type=DRM_MODE_CONNECTOR_HDMIA; + /* A borrowed Type-C route on an HDMI-capable pipe must not sample HDMI. */ + d.typec=true;level=0;calls=samples=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,true));assert(calls==1&&!samples); + d.tunnel=true;calls=timeout_ms=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(calls==1&&timeout_ms==8000&&!samples); + d.typec=d.tunnel=false;d.hdmi_hpd=0;calls=0; + assert(!dcp_assert_hpd_before_link_wait(&d,0,false,false));assert(!calls&&!samples); + puts("early AP HPD: inherited HDMI trigger, errors, late-HPD, Type-C and tunnel regressions pass"); +} +''' +# Check real call ordering/error unwind in the production caller as well. +start = source.index('static int dcp_dptx_connect_raw(') +caller = source[start:source.index('\n}\n', start)] +request = caller.index('dptxport_request_display(') +hpd = caller.index('dcp_assert_hpd_before_link_wait(') +wait = caller.index('dcp_dptx_wait_linkcfg(') +assert request < hpd < wait +assert 'goto out_release;' in caller[hpd:wait] +with tempfile.TemporaryDirectory(prefix='dcp-hpd-') as tmp: + p=Path(tmp);(p/'test.c').write_text(prefix+body+cases) + for mode,flags in [('normal',[]),('sanitizer',['-fsanitize=address,undefined','-fno-sanitize-recover=all'])]: + exe=p/mode + subprocess.run([os.environ.get('CC','cc'),'-std=gnu11','-O1','-g','-Wall','-Wextra','-Werror',*flags,str(p/'test.c'),'-o',str(exe)],check=True) + subprocess.run([exe],check=True) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..732d675dc49861 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -795,6 +795,15 @@ def swap(old, new): 'static bool dcp_tb_tunnel_withdrawn(struct apple_dcp *d, u32 port)\n' '{ (void)d; (void)port; assert(!"tunnel watch in an H17P scenario"); return false; }\n' + apple_function(root, 'dcp_dptx_wait_linkcfg')) + if 'dcp_assert_hpd_before_link_wait(' in raw: + # The HPD assertion before the link wait, as the driver has it. This scenario is a + # Type-C H17P link, so the fixed-HDMI branch is not taken. + swap(' bool hdmi_hpd;', + ' int fixed_connector_type; void *hdmi_hpd;') + firmware += ('static int __attribute__((unused)) gpiod_get_value_cansleep(void *gpio)\n' + '{ (void)gpio; assert(!"fixed HDMI GPIO in a Type-C scenario"); return 0; }\n' + '#ifndef DRM_MODE_CONNECTOR_HDMIA\n#define DRM_MODE_CONNECTOR_HDMIA 11\n#endif\n' + + apple_function(root, 'dcp_assert_hpd_before_link_wait')) # unless the update work already needed the clock clock = 'static unsigned jiffies_to_msecs(unsigned long t) { return t; }\n' if clock in unit: From 53ffd323537c79774fcec999e6f3dc4ded29f0d2 Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Wed, 11 Nov 2026 17:31:12 -0500 Subject: [PATCH 0771/1514] phy: apple: atc: Serve USB2 for USB4/TBT on T8132 without CIO calibration The SN201202x port controllers of the Mac mini (J773g) enter USB4 by themselves with a USB4 dock or another Mac, and Thunderbolt 3 alt mode with a Thunderbolt 3 dock. atcphy_typec_target_mode() maps those states to the USB4 and TBT PHY modes, which atcphy_mux_check() refuses with -ENODEV on a T8132 PHY without the CIO calibration. The J773g device tree has none. The failed mux update makes cd321x_update_work() retry before it sets the USB role, so the port ends up with sn201202x 1-08: failed to configure Type-C connection: -19 sn201202x 1-08: cable revalidation failed after 3 attempts and its dwc3 controller never starts an xHCI. USB 2.0 on D+/D- does not depend on the USB4 or Thunderbolt link. As is already done for the DisplayPort pin assignments this PHY cannot carry, serve the partner's USB2 instead of refusing the mode. The CIO fallback has to come before the DisplayPort fallback picks its USB mode: that one compares its result with target_mode, and started from the USB4 mode it would put USB4 back. Ports with the CIO calibration are unchanged. A KUnit case covers both. Signed-off-by: Sean Dolbec --- drivers/phy/apple/atc-test.c | 35 +++++++++++++++++++++++++++++++++++ drivers/phy/apple/atc.c | 16 +++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 09eec7f9d6185f..7acde177f69bd1 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -104,6 +104,40 @@ static void atcphy_test_target_mode_t8132(struct kunit *test) KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_OFF); } +/* Without the CIO calibration, a T8132 port serves a USB4 or TBT partner's USB2 */ +static void atcphy_test_target_mode_t8132_cio(struct kunit *test) +{ + struct typec_altmode tbt = { .svid = USB_TYPEC_TBT_SID }; + struct enter_usb_data eusb = { + .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB4), + }; + struct typec_mux_state state = { .mode = TYPEC_MODE_USB4, .data = &eusb }; + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + + atcphy->hw = &atcphy_hw_t8132; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + /* The same on a SuperSpeed port. */ + atcphy->t8132_ss = true; + atcphy->ss_tunables = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + state.alt = NULL; + state.mode = TYPEC_MODE_USB4; + state.data = &eusb; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB2); + + /* With the calibration, the link itself is served. */ + atcphy->cio_tunables = true; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_USB4); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_typec_target_mode(atcphy, &state), APPLE_ATCPHY_MODE_TBT); +} + static void atcphy_test_noop_same_mode(struct kunit *test) { struct apple_atcphy *atcphy = atcphy_test_alloc(test, true); @@ -1391,6 +1425,7 @@ static struct kunit_case atcphy_mux_test_cases[] = { KUNIT_CASE(atcphy_test_target_mode), KUNIT_CASE(atcphy_test_target_mode_fixed_hub), KUNIT_CASE(atcphy_test_target_mode_t8132), + KUNIT_CASE(atcphy_test_target_mode_t8132_cio), KUNIT_CASE(atcphy_test_noop_same_mode), KUNIT_CASE(atcphy_test_noop_needs_work), KUNIT_CASE(atcphy_test_usb3_port_ready), diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..9baadfe102d6db 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -5772,10 +5772,24 @@ static enum atcphy_mode atcphy_typec_target_mode(struct apple_atcphy *atcphy, * its USB on the other wires: USB2 next to four DP lanes (pin * assignments C and E), USB3 next to two (D). Serve that USB rather * than refuse the mode, which would leave the port without USB at all. + * + * The same goes for USB4 and Thunderbolt on a port without the CIO + * calibration, such as those of the Mac mini (J773g). Its port + * controller enters USB4 or Thunderbolt 3 by itself with a USB4 dock + * or another Mac, and USB 2.0 on D+/D- does not depend on that link. + * Do this first, so that the DisplayPort fallback below starts from + * the mode actually served rather than putting USB4 back. */ if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) { - enum atcphy_mode usb_mode = target_mode; + enum atcphy_mode usb_mode; + + if (atcphy_mode_is_cio(target_mode) && !atcphy->cio_tunables) { + dev_info(atcphy->dev, + "USB4/Thunderbolt is not available on this port: serving its USB2 only\n"); + target_mode = APPLE_ATCPHY_MODE_USB2; + } + usb_mode = target_mode; /* 4-lane DP stays DP only on a port wired for DP alt mode */ if (target_mode == APPLE_ATCPHY_MODE_DP && !atcphy_t8132_dp_on(atcphy)) usb_mode = APPLE_ATCPHY_MODE_USB2; From bcdc5193a3eb6e6f0294e58fdb3feac4eca88307 Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Fri, 13 Nov 2026 14:01:00 -0500 Subject: [PATCH 0772/1514] tools: asahi, selftests: apple-dcp: stub dev_info in the ATC host tests The ATC USB3 host test and the apple-dcp phy, pm, quiesce and dwc3 host tests compile functions taken from drivers/phy/apple/atc.c. Define dev_info() as a no-op beside their existing logging shims so the generated host C keeps compiling when one of those functions prints an informational message. Signed-off-by: Sean Dolbec --- tools/asahi/atc-usb3-tests.py | 1 + tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c | 1 + tools/testing/selftests/drivers/gpu/apple-dcp/phy.py | 3 +++ tools/testing/selftests/drivers/gpu/apple-dcp/pm.py | 1 + 4 files changed, 6 insertions(+) diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..e660768d56ff45 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -62,6 +62,7 @@ def block(source, marker): static unsigned reports; #define dev_warn(...) ((void)reports++) #define dev_err(...) ((void)reports++) +#define dev_info(...) ((void)0) #define dev_dbg(...) ((void)0) #define lockdep_assert_held(...) ((void)0) #define guard(which) (void) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c index 8c0bfb426e8a05..81a66a396ba0a7 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/prefix.c @@ -28,6 +28,7 @@ static void warning(const char *message) generic_warnings++; } #define dev_warn(d, message, ...) warning(message) +#define dev_info(...) ((void)0) #define dev_err(...) ((void)0) #define dev_dbg(...) ((void)0) #define lockdep_assert_held(p) assert(*(p)) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 26c0f62dabb254..066d6a22d4a65b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -225,6 +225,7 @@ def function(source, name): #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report #define lockdep_assert_held(...) ((void)0) @@ -2048,6 +2049,7 @@ def function(name): #define field_prep FIELD_PREP #define dev_dbg(...) ((void)0) #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) #define dev_err(...) ((void)0) #define lockdep_assert_held(...) ((void)0) #define WARN_ON_ONCE(v) assert(!(v)) @@ -2468,6 +2470,7 @@ def function(source, name): #define dev_info_once(...) ((void)0) #define dev_dbg(...) ((void)0) #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static void report(void *dev, const char *fmt, ...) { (void)dev; (void)fmt; } #define dev_err report #define lockdep_assert_held(...) ((void)0) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py index 0c403fa4e7c0d1..4dfe6186300eca 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/pm.py @@ -570,6 +570,7 @@ def function(text, name): ' struct notifier_block tbt_watch;\n bool tbt_watch_registered;\n', 1) mocks = mocks.replace('static void cd321x_stop_work(struct cd321x *c) {\n', r'''#define INIT_WORK(p,fn) ((p)->pending=false) #define dev_warn(...) ((void)0) +#define dev_info(...) ((void)0) static int watches, watch_error; /* Like the real watch, hold the port fwnode until the port is unregistered. */ static int cd321x_tbt_watch_late(struct cd321x *c,struct fwnode_handle *f) { From a04672137e3a365f9c89059c762fbe8923ba1575 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 21:20:34 -0500 Subject: [PATCH 0773/1514] dt-bindings: power: apple,pmc: add the CLPC's apple,cpu-busy-floor Let a board give the DCS and fabric state pair a CPU cluster busy in the top quarter of its frequency range requests outside the low-power platform profile, taken from the CLPC floor residency macOS shows on that board in its default energy mode. Without it, or under low-power, the SoC's table applies. Signed-off-by: Satya Benson --- .../devicetree/bindings/power/apple,pmc.yaml | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Documentation/devicetree/bindings/power/apple,pmc.yaml b/Documentation/devicetree/bindings/power/apple,pmc.yaml index 5311f37ff7b6f4..9f2d9f1b3eafe1 100644 --- a/Documentation/devicetree/bindings/power/apple,pmc.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmc.yaml @@ -313,6 +313,27 @@ patternProperties: items: maximum: 1000 + apple,cpu-busy-floor: + $ref: /schemas/types.yaml#/definitions/uint32-array + items: + - description: + DCS state index on the CLPC's DCS rail, 0 for the lowest state + minimum: 0 + maximum: 15 + - description: + Fabric state index on the CLPC's fabric rail, 0 for the lowest + state + minimum: 0 + maximum: 15 + description: + The DCS and fabric state pair a CPU cluster busy in the top quarter + of its frequency range requests on this board outside the low-power + platform profile, taken from the CLPC floor residency macOS shows on + it in its default energy mode. Each index is a 4-bit PMC rail field; + an index above 15, or a cell count other than two, is rejected and + the SoC's table applies. Without the property, or while the + low-power platform profile is active, the SoC's table applies. + dependentRequired: apple,gpu-busy-memory-states: - apple,gpu-busy-permille From 150faf6b98ca4e3814d1c57452a01d3cee0e505b Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 21:20:34 -0500 Subject: [PATCH 0774/1514] soc: apple: clpc: take the busy CPU floor from apple,cpu-busy-floor A CPU cluster busy in the top quarter of its frequency range requests the top entry of the SoC's map. Where the board's DT gives apple,cpu-busy-floor and the low-power platform profile is not active, request that DCS and fabric pair instead. Under low-power (where macOS drops the single-thread busy floor), GPU and ANE demand, or a malformed value, the SoC's table applies. T6050's table is shared by the M5 Pro and the M5 Max, and their macOS behaviour differs: J714sAP (26A428) shows no vote for one CPU-bound thread and DCS 5 / fabric 2 for 18 threads, while J775c (26B123) holds its top two DCS/fabric floor pairs for one thread in Automatic mode and drops them in Low Power mode. Keep the shared table at 5/2 while the board property carries J775c's non-low-power value. Signed-off-by: Satya Benson --- drivers/soc/apple/clpc.c | 89 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 3e786e7cf1c39d..b2ef35e6f135e4 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -202,6 +202,14 @@ struct apple_clpc { struct device *dev; struct device *pmc; const struct apple_clpc_hw *hw; + /* + * The board's states for a CPU cluster busy in the top quarter of its + * range (apple,cpu-busy-floor) outside the low-power profile, in place + * of the top of @hw->map; GPU and ANE demand still use @hw. Unset: + * @hw->map applies. + */ + u8 cpu_top[APPLE_CLPC_RAILS]; + bool cpu_top_set; unsigned int agent; /* Samples while a vote is held; idle_work defers to busy CPUs. */ struct delayed_work work; @@ -600,6 +608,20 @@ static void apple_clpc_find_clusters(struct apple_clpc *clpc) } } +/* + * The state a busy CPU cluster in frequency quarter @q asks @rail for. + * The board's override applies outside the low-power platform profile, + * where macOS drops the single-thread busy floor. + */ +static unsigned int apple_clpc_cpu_state(const struct apple_clpc *clpc, + unsigned int rail, unsigned int q) +{ + if (clpc->cpu_top_set && q == APPLE_CLPC_LEVELS - 1 && + !READ_ONCE(clpc->low_power)) + return clpc->cpu_top[rail]; + return clpc->hw->map[rail][q]; +} + static void apple_clpc_sample_cluster(struct apple_clpc *clpc, struct apple_clpc_cluster *cl) { @@ -649,7 +671,7 @@ static void apple_clpc_sample_cluster(struct apple_clpc *clpc, for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) cl->request[rail] = busy >= APPLE_CLPC_BUSY_PCT && cl->streak >= clpc->hw->sustain ? - clpc->hw->map[rail][q] : 0; + apple_clpc_cpu_state(clpc, rail, q) : 0; } static unsigned int apple_clpc_vote(struct apple_clpc_vote *vote, @@ -1120,6 +1142,37 @@ static void apple_clpc_idle_work(struct work_struct *work) apple_clpc_run(container_of(to_delayed_work(work), struct apple_clpc, idle_work)); } +/* + * apple,cpu-busy-floor: the DCS and fabric states, in that order, for a CPU + * cluster busy in the top quarter of its frequency range outside the low-power + * profile, where the board's measurement differs from the SoC's table. A bad + * value costs the override, not the driver. + */ +static void apple_clpc_cpu_top_init(struct apple_clpc *clpc) +{ + u32 top[APPLE_CLPC_RAILS]; + unsigned int rail; + int ret; + + if (!of_property_present(clpc->dev->of_node, "apple,cpu-busy-floor")) + return; + ret = of_property_read_u32_array(clpc->dev->of_node, "apple,cpu-busy-floor", + top, APPLE_CLPC_RAILS); + for (rail = 0; !ret && rail < APPLE_CLPC_RAILS; rail++) + if (top[rail] > 0xf) + ret = -ERANGE; + if (ret || of_property_count_u32_elems(clpc->dev->of_node, + "apple,cpu-busy-floor") != APPLE_CLPC_RAILS) { + dev_warn(clpc->dev, "invalid apple,cpu-busy-floor; using the SoC's states\n"); + return; + } + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + clpc->cpu_top[rail] = top[rail]; + clpc->cpu_top_set = true; + dev_info(clpc->dev, "busy CPU floor: DCS %u, fabric %u\n", + clpc->cpu_top[APPLE_CLPC_DCS], clpc->cpu_top[APPLE_CLPC_SOC]); +} + static int apple_clpc_status_show(struct seq_file *s, void *unused) { struct apple_clpc *clpc = s->private; @@ -1134,8 +1187,10 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) clpc->hw->rail[rail], clpc->vote[rail].state, apple_pmc_voter_enabled(clpc->pmc, clpc->agent, clpc->hw->rail[rail]), - clpc->hw->map[rail][0], clpc->hw->map[rail][1], - clpc->hw->map[rail][2], clpc->hw->map[rail][3]); + apple_clpc_cpu_state(clpc, rail, 0), + apple_clpc_cpu_state(clpc, rail, 1), + apple_clpc_cpu_state(clpc, rail, 2), + apple_clpc_cpu_state(clpc, rail, 3)); seq_printf(s, "last_vote: %#x reason_bits %#x sampled_ns %llu (cpu=1 host_gpu=2 streaming_gpu=4 dense_gpu=8 hold=16 ane=32)\n", READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), READ_ONCE(clpc->last_vote_ns)); @@ -1605,6 +1660,7 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->hw = apple_clpc_dt_hw(dev, of_device_get_match_data(dev)); if (IS_ERR(clpc->hw)) return PTR_ERR(clpc->hw); + apple_clpc_cpu_top_init(clpc); /* T6040 firmware keeps GFX powered for its whole lifetime. A separate * host publication/idle input, not that supplier state, drives demand; * the T8132 and M5 (T8142) GPU drivers report through the same input. @@ -2364,7 +2420,34 @@ static void apple_clpc_ane_wake_removal_test(struct kunit *test) apple_clpc_ane_put(ane); } +static void apple_clpc_cpu_busy_floor_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, clpc); + clpc->hw = &apple_clpc_hw_t6050; + + /* Without the board override, the top quarter uses the SoC map. */ + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 2u); + + /* With the override active outside low-power, only the top quarter changes. */ + clpc->cpu_top[APPLE_CLPC_DCS] = 6; + clpc->cpu_top[APPLE_CLPC_SOC] = 3; + clpc->cpu_top_set = true; + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 2), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 2), 2u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 6u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 3u); + + /* Under the low-power platform profile, fall back to the SoC map. */ + WRITE_ONCE(clpc->low_power, true); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_DCS, 3), 5u); + KUNIT_EXPECT_EQ(test, apple_clpc_cpu_state(clpc, APPLE_CLPC_SOC, 3), 2u); +} + static struct kunit_case apple_clpc_cases[] = { + KUNIT_CASE(apple_clpc_cpu_busy_floor_test), KUNIT_CASE(apple_clpc_ane_demand_hold_test), KUNIT_CASE(apple_clpc_ane_states_test), KUNIT_CASE(apple_clpc_ane_cluster_test), From 97f18f01f792bae50ad83f308b25e10725993eba Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 21:20:34 -0500 Subject: [PATCH 0775/1514] arm64: dts: apple: t6050-j775c: request DCS 6 and fabric 3 for a busy CPU Under one CPU-bound thread (7-Zip, 3 runs), macOS 27.2 (26B123) on J775c in Automatic energy mode holds the CLPC's DCS floor at F7 for about 52% of the run and F8 for about 41%, and its SOC floor at VMAX for about 43% and VOVD for about 50%. The two move together, as the pairs F7/VMAX and F8/VOVD. Read in state order, those pairs are DCS 5 / fabric 2, the SoC table's top entry, and DCS 6 / fabric 3. That reading is not verified: it rests on the order of the states, 7 DCS floor states as Linux has 7 DCS states, and 5 SOC states (one never used) where Linux has 4 fabric states. Under Low Power mode macOS drops the single-thread floor (F1 85-87%, VMIN 99%), so the driver applies this property only outside low-power. Same-boot A/B, interleaved over 3 rounds; median (range): arm (PMC floor read back) 5/2 (0x25) 6/3 (0x36) 7-Zip 1T on cpu0 9635 (9584-9648) 9884 (9883-9894) 7-Zip 18T 183857 (183753-185843) 189748 (187715-192740) STREAM triad 18T (MB/s) 328493 (321023-333930) 361656 (360632-365305) STREAM triad 1T (MB/s) 132306 (131183-132523) 131313 (130854-132691) 64 MiB latency, cpu0 (ns) 21.3 (21.1-21.4) 18.6 (18.1-18.8) Signed-off-by: Satya Benson --- arch/arm64/boot/dts/apple/t6050-j775c.dts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j775c.dts b/arch/arm64/boot/dts/apple/t6050-j775c.dts index 65d92d3a174800..0f38e351ad11ee 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775c.dts @@ -27,6 +27,16 @@ }; }; +/* + * From this board's macOS 27.2 (26B123) Automatic energy-mode CLPC floor + * residency under one CPU-bound thread: the top of the two DCS/fabric pairs + * it alternates between, read as DCS 6 and fabric 3 (state order, not + * verified). Low Power mode drops this floor and uses the SoC table instead. + */ +&clpc { + apple,cpu-busy-floor = <6 3>; +}; + /* PCIe port 0 is not described for this board yet */ &pcie0 { status = "disabled"; From 3437a5a3730eaedf6708bc1cabcdb808235e32c7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 13:45:12 +1100 Subject: [PATCH 0776/1514] drm/apple: dcp: keep the DP PHY of a DCP whose firmware runs through a sleep A DCP that keeps its coprocessor running through a sleep puts itself on the wakeup path, so genpd leaves its own domains up. The DP PHY that its firmware drives is a separate device under its own domain, and genpd powers that domain off at noirq like any other. With the firmware still running, that resets the SoC: on the M2 Mac mini (J473) with firmware 27.2, s2idle reset in the first freeze whenever a DCP driver was bound, both for the HDMI dcpext (dptx_ext_phy) and for the USB-C primary (its route's ATC PHY). Holding both PHY domains on through the sleep was enough for the sleep to pass; holding either one alone was not. Where the suspend leaves the firmware running (sleep_fw_runs), also put the provider devices of the DCP's dp-phy and of its active Type-C route's PHY on the wakeup path. A DCP that stops its firmware for the sleep leaves its PHYs to genpd as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 7852d5e22a4920..78464acdb2e075 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9766,6 +9766,27 @@ bool dcp_sleep_keeps_firmware(struct device *dev) } EXPORT_SYMBOL_GPL(dcp_sleep_keeps_firmware); +/* + * A DCP whose firmware runs through a sleep keeps driving the DP PHY of its + * output, so the PHY's power domain has to stay up with the DCP's own: cut at + * noirq under the running firmware, it resets the SoC (J473, firmware 27.2). + * Put the PHY devices in use on the wakeup path, as the DCP itself is. + */ +static void dcp_phy_set_wakeup_path(struct phy *phy) +{ + if (!IS_ERR_OR_NULL(phy) && phy->dev.parent) + device_set_wakeup_path(phy->dev.parent); +} + +static void dcp_sleep_hold_phys(struct apple_dcp *dcp) +{ + struct apple_dcp_typec_route *route = READ_ONCE(dcp->active_typec_route); + + dcp_phy_set_wakeup_path(dcp->phy); + if (route) + dcp_phy_set_wakeup_path(route->phy); +} + static int dcp_platform_suspend(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); @@ -9828,6 +9849,8 @@ static int dcp_platform_suspend(struct device *dev) dcp_t8132_sleep_stopped(dcp); dcp->sleep_fw_runs = !iomfb_m4_sleep_stopped(dcp); device_set_wakeup_path(dev); + if (dcp->sleep_fw_runs) + dcp_sleep_hold_phys(dcp); return 0; } if (dcp_is_ext26(dcp) && pm_suspend_target_state != PM_SUSPEND_TO_IDLE) { @@ -9884,6 +9907,7 @@ static int dcp_platform_suspend(struct device *dev) dcp_typec_route_park(dcp); dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); + dcp_sleep_hold_phys(dcp); if (dcp_is_ext26(dcp)) dev_dbg(dev, "native26 retained s2idle stop; firmware and supplier leases held\n"); return 0; @@ -9918,6 +9942,7 @@ static int dcp_platform_suspend(struct device *dev) */ dcp->sleep_fw_runs = true; device_set_wakeup_path(dev); + dcp_sleep_hold_phys(dcp); /* Last: the steps above still talk to the coprocessor. */ dcp_hold_for_sleep(dcp); From c672252ba5d2569273cf90b1bc6b01fbf5ba8361 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 13:45:12 +1100 Subject: [PATCH 0777/1514] tools/asahi: test the DCP sleep PHY hold Build the real dcp_phy_set_wakeup_path() and dcp_sleep_hold_phys() from dcp.c against a small driver-core model and check which PHY providers end up on the wakeup path: a dcpext's own dp-phy, a primary's Type-C route PHY, both, neither, an error pointer from the optional lookup and a PHY without a provider. Four mutations (no route PHY, no own PHY, the class device instead of the provider, no error check) must fail. Signed-off-by: Ryan Murray --- tools/asahi/dcp-sleep-phy-hold-tests.py | 134 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 2 files changed, 137 insertions(+) create mode 100755 tools/asahi/dcp-sleep-phy-hold-tests.py diff --git a/tools/asahi/dcp-sleep-phy-hold-tests.py b/tools/asahi/dcp-sleep-phy-hold-tests.py new file mode 100755 index 00000000000000..05105c3c8dcefe --- /dev/null +++ b/tools/asahi/dcp-sleep-phy-hold-tests.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual DCP sleep PHY hold over every PHY topology. + +A DCP whose firmware keeps running through a sleep keeps driving the DP PHY +of its output. genpd powers the PHY's domain off at noirq unless the PHY's +device is on the wakeup path, and cutting it under the running firmware +resets the J473 (firmware 27.2) on s2idle. dcp_sleep_hold_phys() puts the +provider device of the DCP's own dp-phy and of its active Type-C route's PHY +on the wakeup path. The fixture builds the real dcp_phy_set_wakeup_path() and +dcp_sleep_hold_phys() from drivers/gpu/drm/apple/dcp.c against a small +driver-core model and checks which devices end up on the wakeup path. + +--mutation names a change to the production functions that the matrix must +kill. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DCP = "drivers/gpu/drm/apple/dcp.c" + +MUTATIONS = { + # Forget the Type-C route's PHY (the USB-C output of a primary DCP). + "no-route": ("\tif (route)\n\t\tdcp_phy_set_wakeup_path(route->phy);\n", ""), + # Forget the DCP's own dp-phy (the HDMI output of a dcpext). + "no-own-phy": ("\tdcp_phy_set_wakeup_path(dcp->phy);\n", ""), + # Mark the PHY class device instead of the provider genpd sees. + "class-device": ("device_set_wakeup_path(phy->dev.parent);", "device_set_wakeup_path(&phy->dev);"), + # Trust an error pointer. + "no-err-check": ("!IS_ERR_OR_NULL(phy) && ", "phy && "), +} + +HARNESS = r''' +#include +#include +#include +#include +#include +#include +static volatile int cur_line; +static void on_segv(int sig) { char b[64]; int n = snprintf(b, sizeof(b), "FAIL line %d (signal %d)\n", cur_line, sig); write(1, b, n); _exit(1); } +#define READ_ONCE(x) (x) +#define MAX_ERRNO 4095 +#define IS_ERR_VALUE(x) ((unsigned long)(void *)(x) >= (unsigned long)-MAX_ERRNO) +static inline bool IS_ERR_OR_NULL(const void *p) { return !p || IS_ERR_VALUE((unsigned long)p); } +struct device { struct device *parent; bool wakeup_path; }; +static void device_set_wakeup_path(struct device *dev) +{ + if (IS_ERR_VALUE((unsigned long)dev)) { printf("FAIL line %d error pointer\n", cur_line); exit(1); } + dev->wakeup_path = true; +} +struct phy { struct device dev; }; +struct apple_dcp_typec_route { struct phy *phy; }; +struct apple_dcp { struct phy *phy; struct apple_dcp_typec_route *active_typec_route; }; +@@FUNCS@@ +int main(void) +{ + struct device own_prov = {0}, route_prov = {0}, other_prov = {0}; + struct phy own = { .dev = { .parent = &own_prov } }; + struct phy rphy = { .dev = { .parent = &route_prov } }; + struct phy orphan = { .dev = { .parent = NULL } }; + struct apple_dcp_typec_route route = { .phy = &rphy }, noroute_phy = { .phy = NULL }; + struct apple_dcp d; + int fail = 0; + + signal(SIGSEGV, on_segv); +#define RESET() do { own_prov.wakeup_path = route_prov.wakeup_path = other_prov.wakeup_path = false; \ + own.dev.wakeup_path = rphy.dev.wakeup_path = orphan.dev.wakeup_path = false; } while (0) +#define CHECK(name, cond) do { if (!(cond)) { printf("FAIL line %d %s\n", __LINE__, name); fail++; } else printf("ok %s\n", name); } while (0) +#define HOLD(dcp) do { cur_line = __LINE__; fflush(stdout); dcp_sleep_hold_phys(dcp); } while (0) + /* dcpext: its own dp-phy, no Type-C route */ + RESET(); d.phy = &own; d.active_typec_route = NULL; HOLD(&d); + CHECK("dcpext dp-phy provider held", own_prov.wakeup_path && !own.dev.wakeup_path); + /* primary with a Type-C route and no own phy */ + RESET(); d.phy = NULL; d.active_typec_route = &route; HOLD(&d); + CHECK("route phy provider held", route_prov.wakeup_path && !rphy.dev.wakeup_path && !own_prov.wakeup_path); + /* both */ + RESET(); d.phy = &own; d.active_typec_route = &route; HOLD(&d); + CHECK("both held", own_prov.wakeup_path && route_prov.wakeup_path); + /* nothing to hold */ + RESET(); d.phy = NULL; d.active_typec_route = NULL; HOLD(&d); + CHECK("none", !own_prov.wakeup_path && !route_prov.wakeup_path && !other_prov.wakeup_path); + /* an optional phy lookup error and a route without a phy */ + RESET(); d.phy = (struct phy *)(intptr_t)-19; d.active_typec_route = &noroute_phy; HOLD(&d); + CHECK("error phy and phy-less route ignored", !own_prov.wakeup_path && !route_prov.wakeup_path); + /* a phy without a provider parent */ + RESET(); d.phy = &orphan; d.active_typec_route = NULL; HOLD(&d); + CHECK("parentless phy ignored", !orphan.dev.wakeup_path); + printf("%d failures\n", fail); + return fail != 0; +} +''' + +def extract(src, name): + m = re.search(r'^static void %s\(.*?^}\n' % re.escape(name), src, re.S | re.M) + if not m: + sys.exit(f"{name} not found in {DCP}") + return m.group(0) + +def run(mutation): + src = (ROOT / DCP).read_text() + funcs = extract(src, "dcp_phy_set_wakeup_path") + "\n" + extract(src, "dcp_sleep_hold_phys") + if mutation: + old, new = MUTATIONS[mutation] + if funcs.count(old) != 1: + sys.exit(f"mutation {mutation} does not apply exactly once") + funcs = funcs.replace(old, new) + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "t.c" + exe = Path(tmp) / "t" + c.write_text(HARNESS.replace("@@FUNCS@@", funcs)) + flags = ["-std=gnu11", "-Wall"] + ([] if mutation else ["-Werror"]) + subprocess.run([os.environ.get("CC", "cc"), *flags, "-o", exe, c], check=True) + r = subprocess.run([exe], capture_output=True, text=True) + out = r.stdout + r.stderr + bad = r.returncode != 0 + return bad, out + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mutation", choices=sorted(MUTATIONS)) + a = ap.parse_args() + bad, out = run(a.mutation) + print(out, end="") + sys.exit(1 if bad else 0) + +if __name__ == "__main__": + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index c1017b5c1f84da..d82fd59b625ce7 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -183,6 +183,9 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('bound-only', 'stopped-holds', 'invert-runs', 'no-lock', 'leak-device', 'leak-node', 'ignore-dcp'), out()) + [(out() + ['--ref', 'a7638d51880ce077cfb3edfa7ff638de2be74c85'], KILL)], + # A DCP whose firmware runs through the sleep holds its DP PHYs' domains. + 'dcp-sleep-phy-hold-tests.py': [([], PASS)] + + mutations('--mutation', ('no-route', 'no-own-phy', 'class-device', 'no-err-check'), []), 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), From 7ba8b9396566f794104bb72bb09b5a6628602d7e Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Thu, 19 Nov 2026 13:52:18 -0500 Subject: [PATCH 0778/1514] drm: apple: dcp: take no device lock for a mode set without a peer dcp_peer_modeset_v27() takes the DCP's device lock with a trylock before it looks whether the display has a reserved peer at all, and returns -EBUSY when the lock is held. Without a peer the answer is -EOPNOTSUPP, "set the mode on this engine alone", and needs no lock. The lock is held by the DCP's own probe while the DRM device is bound and registered from it. A display that is already connected at that moment gets its first mode set from the fbdev client inside the registration, so under that lock: the mode set is refused before anything is sent to the firmware, apple-dcp 30ae00000.dcp: paired mode set failed: -16 while the requested mode is already recorded as the current one. The pipe then runs on whatever mode the boot loader left until the next real mode change. Whether it happens depends on the order of the sink's hot-plug and the registration, a few milliseconds apart on the J773g's fixed HDMI output on firmware 27.2: four boots had the hot-plug after the registration, one had it 0.3 ms before and logged the line twice, with no mode set reaching the firmware until a mode change 95 s later. Answer for a display without a reserved peer under the peer lock alone, before the device lock is tried. A display with a peer is handled as before. A display with a reserved peer still gets -EBUSY while its device lock is held, with the mode already recorded; that is unchanged. Every firmware 27 display without a peer takes the new return. Not tested: any display with a peer. Signed-off-by: Sean Dolbec --- drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index cd8340105b37bf..cfe41845b3360f 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -120,8 +120,13 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v return ret; if (timing > U32_MAX - 10000 || color > U32_MAX - 10000) return -EINVAL; - /* No paired call, nor wait for one, for a display the limit leaves no pair. */ + /* + * No paired call, nor wait for one, for a display without a peer or one + * the limit leaves no pair. The device lock below may be the probe's. + */ scoped_guard(mutex, &dcp_peer_lock) { + if (!dcp->peer_reserved) + return ret; limited = dcp_peer_limited_pair_locked(dcp, &prepared); if (limited && !prepared) return ret; From 36f71e4985302c4f4841e5b7323cca1f415c8c50 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Mon, 23 Nov 2026 22:07:16 -0500 Subject: [PATCH 0779/1514] pmdomain: apple: pmc: wait out pending votes on DCS writes apple_pmc_dcs_vote() wrote the AP agent's DCS vote directly with writel() instead of going through __apple_pmc_floor_update(). On PMCs with has_pending = true (T8132, T6050), if a previous vote on the AP agent was still pending in the reg + 4 pending word (BIT(agent)), the direct write bypassed the pending-bit poll and could race with the PMC consuming the earlier update. Route apple_pmc_dcs_vote() through __apple_pmc_floor_update() and propagate its return value through apple_pmc_dcs_limit(), apple_pmc_floor_apply(), and apple_pmc_resume_early(). Keep pmc->dcs_state synchronized with the hardware rail_enable mask on partial failure in apple_pmc_dcs_limit(), including rolling rail_enable back to the AP agent when leaving a DCS limit fails on a pending AP vote. Add KUnit tests for both a pending DCS floor write and a pending DCS limit release rollback. Signed-off-by: Satya Benson --- drivers/pmdomain/apple/pmc-test.c | 68 ++++++++++++++++++++++++++++++ drivers/pmdomain/apple/pmc.c | 69 +++++++++++++++++++------------ 2 files changed, 110 insertions(+), 27 deletions(-) diff --git a/drivers/pmdomain/apple/pmc-test.c b/drivers/pmdomain/apple/pmc-test.c index 4e7f19d47317a1..010f0fd9f7cb67 100644 --- a/drivers/pmdomain/apple/pmc-test.c +++ b/drivers/pmdomain/apple/pmc-test.c @@ -543,6 +543,72 @@ static void apple_pmc_test_interface_boot_state(struct kunit *test) KUNIT_EXPECT_EQ(test, readl(pmc->rails + hw->boost_enable), BIT(0) | BIT(1)); } +/* + * The AP's DCS vote waits for the PMC to take the previous vote, as other + * floor writes do, instead of writing over it. + */ +static void apple_pmc_test_dcs_floor_pending(struct kunit *test) +{ + struct apple_pmc *pmc = apple_pmc_test_alloc(test); + struct apple_pmc_domain *dom; + void __iomem *reg; + + INIT_LIST_HEAD(&pmc->domains); + pmc->hw = &apple_pmc_hw_t8132; + reg = pmc->voters + pmc->hw->ap_agent * pmc->hw->agent_stride; + writel(BIT(pmc->hw->ap_agent), reg + 4); + dom = apple_pmc_test_floor(test, pmc, pmc->hw->dcs_rail, 2); + KUNIT_EXPECT_EQ(test, apple_pmc_floor_set(dom, true), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, dom->on); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 0U); + writel(0, reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_floor_set(dom, true), 0); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 2U); +} + +/* + * Leaving a DCS limit when the AP's vote is still pending rolls back the + * rail enable so dcs_state and hardware stay in sync until a retry clears it. + */ +static void apple_pmc_test_dcs_limit_release_pending(struct kunit *test) +{ + struct apple_pmc *pmc = apple_pmc_test_alloc(test); + const struct apple_pmc_hw *hw = &apple_pmc_hw_t8132; + struct thermal_cooling_device cdev = { .devdata = pmc }; + void __iomem *reg; + + pmc->hw = hw; + INIT_DELAYED_WORK(&pmc->dcs_work, apple_pmc_dcs_work); + apple_pmc_test_set_dcs_vote(pmc, hw->ap_agent, 1); + apple_pmc_test_set_dcs_vote(pmc, 0, hw->dcs_max); + pmc->ap_dcs_vote = apple_pmc_ap_dcs_read(pmc); + pmc->enable[hw->dcs_rail] = BIT(0) | BIT(hw->ap_agent); + writel(pmc->enable[hw->dcs_rail], + pmc->rails + hw->rail_enable + 4 * hw->dcs_rail); + + KUNIT_ASSERT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 2), 0); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 2UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), hw->dcs_max - 2); + + reg = pmc->voters + hw->ap_agent * hw->agent_stride; + writel(BIT(hw->ap_agent), reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 2UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), hw->dcs_max - 2); + + writel(0, reg + 4); + KUNIT_EXPECT_EQ(test, apple_pmc_dcs_set_cur_state(&cdev, 0), 0); + KUNIT_EXPECT_EQ(test, pmc->dcs_state, 0UL); + KUNIT_EXPECT_EQ(test, apple_pmc_enable_read(pmc, hw->dcs_rail), + BIT(0) | BIT(hw->ap_agent)); + KUNIT_EXPECT_EQ(test, apple_pmc_ap_dcs_read(pmc), 1U); + cancel_delayed_work_sync(&pmc->dcs_work); +} + static struct kunit_case apple_pmc_test_cases[] = { KUNIT_CASE(apple_pmc_test_dcs_floor), KUNIT_CASE(apple_pmc_test_partial_enable), @@ -553,6 +619,8 @@ static struct kunit_case apple_pmc_test_cases[] = { KUNIT_CASE(apple_pmc_test_dcs_limit_restores_ap_vote), KUNIT_CASE(apple_pmc_test_floor_aggregate), KUNIT_CASE(apple_pmc_test_floor_pending_timeout), + KUNIT_CASE(apple_pmc_test_dcs_floor_pending), + KUNIT_CASE(apple_pmc_test_dcs_limit_release_pending), KUNIT_CASE(apple_pmc_test_interface), KUNIT_CASE(apple_pmc_test_interface_stuck), KUNIT_CASE(apple_pmc_test_interface_consumer), diff --git a/drivers/pmdomain/apple/pmc.c b/drivers/pmdomain/apple/pmc.c index e93dc40bc10c1b..10b5d41f8824f8 100644 --- a/drivers/pmdomain/apple/pmc.c +++ b/drivers/pmdomain/apple/pmc.c @@ -85,6 +85,8 @@ * @agent_rails: rails on which an agent is enabled; 0 for every rail * @ap_agent: voter agent of the application processor, which a DCS limit * votes through + * @has_pending: true if the PMC exposes a per-agent pending word at reg + 4 + * after each voter floor word (BIT(agent) set while a vote is pending) * @bwr_enable: offset of the bandwidth request (BWR) interface enable word * in the "rails" region; 0 if the PMC has none * @boost_enable: offset of the boost interface enable word in the "rails" @@ -425,24 +427,21 @@ static unsigned int apple_pmc_ap_dcs_read(struct apple_pmc *pmc) * Caller holds pmc->lock. Vote through the AP's agent for what the other * agents ask for and the DCS floors held, capped by the limit; without a * limit, the vote the AP's agent had before probe or the floors, if higher. + * Like any other floor write, wait out a vote the PMC has not taken yet. */ -static void apple_pmc_dcs_vote(struct apple_pmc *pmc) +static int apple_pmc_dcs_vote(struct apple_pmc *pmc) { const struct apple_pmc_hw *hw = pmc->hw; - void __iomem *reg = pmc->voters + hw->ap_agent * hw->agent_stride; - u32 mask = APPLE_PMC_RAIL_MASK(hw->dcs_rail); unsigned int state = max(pmc->ap_dcs_vote, pmc->dcs_floor); - u32 old, val; if (pmc->dcs_state) state = min_t(unsigned int, max(apple_pmc_dcs_demand(pmc), pmc->dcs_floor), hw->dcs_max - pmc->dcs_state); - old = readl(reg); - val = (old & ~mask) | (state << APPLE_PMC_RAIL_SHIFT(hw->dcs_rail)); - if (val != old) - writel(val, reg); + return __apple_pmc_floor_update(pmc, hw->ap_agent, + APPLE_PMC_RAIL_MASK(hw->dcs_rail), + state << APPLE_PMC_RAIL_SHIFT(hw->dcs_rail)); } static void apple_pmc_dcs_work(struct work_struct *work) @@ -489,18 +488,42 @@ static int apple_pmc_dcs_get_cur_state(struct thermal_cooling_device *cdev, static int apple_pmc_dcs_limit(struct apple_pmc *pmc, unsigned long state) { unsigned int rail = pmc->hw->dcs_rail; + unsigned long old = pmc->dcs_state; int ret; WRITE_ONCE(pmc->dcs_state, state); if (state) { - apple_pmc_dcs_vote(pmc); - return apple_pmc_enable_write(pmc, rail); + ret = apple_pmc_dcs_vote(pmc); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + return ret; + } + ret = apple_pmc_enable_write(pmc, rail); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + apple_pmc_dcs_vote(pmc); + } + return ret; } ret = apple_pmc_enable_write(pmc, rail); - if (!ret) - apple_pmc_dcs_vote(pmc); + if (ret) { + WRITE_ONCE(pmc->dcs_state, old); + return ret; + } + ret = apple_pmc_dcs_vote(pmc); + if (ret) { + /* + * All agents are already enabled, while the AP still holds + * the old capped vote. Re-restrict rail_enable so dcs_state + * stays synchronized with hardware; if that fails too, leave + * dcs_state at 0 to match the uncapped rail_enable. + */ + WRITE_ONCE(pmc->dcs_state, old); + if (apple_pmc_enable_write(pmc, rail)) + WRITE_ONCE(pmc->dcs_state, 0); + } return ret; } @@ -508,7 +531,7 @@ static int apple_pmc_dcs_set_cur_state(struct thermal_cooling_device *cdev, unsigned long state) { struct apple_pmc *pmc = cdev->devdata; - unsigned long flags, old; + unsigned long flags; bool limited; int ret = 0; @@ -516,17 +539,8 @@ static int apple_pmc_dcs_set_cur_state(struct thermal_cooling_device *cdev, return -EINVAL; raw_spin_lock_irqsave(&pmc->lock, flags); - old = pmc->dcs_state; - if (state != old) { + if (state != pmc->dcs_state) ret = apple_pmc_dcs_limit(pmc, state); - /* - * The rail enable did not change, so neither did the limit: - * go back to the old state, which the next call then retries - * to leave. - */ - if (ret) - apple_pmc_dcs_limit(pmc, old); - } limited = pmc->dcs_state; raw_spin_unlock_irqrestore(&pmc->lock, flags); @@ -659,8 +673,7 @@ static int apple_pmc_floor_apply(struct apple_pmc *pmc, unsigned int rail) /* The AP's DCS vote also carries the DCS limit; it combines both. */ if (rail == pmc->hw->dcs_rail) { pmc->dcs_floor = level; - apple_pmc_dcs_vote(pmc); - return 0; + return apple_pmc_dcs_vote(pmc); } return __apple_pmc_floor_update(pmc, pmc->hw->ap_agent, @@ -1557,8 +1570,10 @@ static int apple_pmc_resume_early(struct device *dev) * The AP agent's word also holds its DCS vote, which a deep sleep's commit zeroes * (apple-sleep, T8132 and T8142). Cast it again: a no-op if it stayed. */ - if (!(pmc->floor_rails & BIT(pmc->hw->dcs_rail))) - apple_pmc_dcs_vote(pmc); + if (!(pmc->floor_rails & BIT(pmc->hw->dcs_rail))) { + err = apple_pmc_dcs_vote(pmc); + ret = ret ?: err; + } raw_spin_unlock_irqrestore(&pmc->lock, flags); if (ret) dev_err(dev, "state not restored after sleep: %d\n", ret); From c45890492123f832693d1932c454491930988670 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 14:30:11 +1100 Subject: [PATCH 0780/1514] drm/asahi: drop "compute-only" from the G14 firmware-27.2 probe message The G14 firmware-27.2 device renders now, but its probe still logged "compute-only DRM device registered", which reads as if render commands were refused. Say that the DRM device is registered, and update the function's comment to match. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index bf014730a868e8..d06656bbc6e85d 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -498,7 +498,7 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { - /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. + /// G14 with firmware 27.2: start the firmware and register its DRM device. #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, @@ -519,7 +519,7 @@ impl AsahiPlatformDriver { return Err(error); } }; - dev_info!(pdev.as_ref(), "G14 firmware 27.2 running; compute-only DRM device registered\n"); + dev_info!(pdev.as_ref(), "G14 firmware 27.2 running; DRM device registered\n"); Ok(AsahiPlatformDriverData { binding, _device: reg.device().into(), From 3c9f4c80e609197a28170b0be6ab5b37759c0f84 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 14:37:16 +1100 Subject: [PATCH 0781/1514] HID: magicmouse: report the force click as KEY_INFO by default The host already tells a deep click (the second, firmer stage of a Force Touch click) from an ordinary one and plays its haptic, but reports it to userspace only if haptic_deep_keycode names a key, and nothing names one. So a force click does nothing on the desktop, where macOS opens Quick Look on the item under the pointer. Default the key to KEY_INFO. Linux has no force-click key; KEY_INFO (keysym XF86Info) has no default binding on the desktops we ship, so the key is inert until the desktop binds it to what a force click does there (in GNOME Files: the preview of the item clicked). It stays on the separate " Force Click" input device, held for as long as the deep stage lasts; haptic_deep_keycode=0 still turns it off. This applies to every trackpad with host-derived clicks (the MTP pads with an actuator); the SPI pads have no deep-click detection yet. Signed-off-by: Ryan Murray --- drivers/hid/hid-magicmouse.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 4d8ffa36d77004..c89f657daf5b44 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -148,16 +148,18 @@ module_param(haptic_deep_gap_ms, byte, 0644); MODULE_PARM_DESC(haptic_deep_gap_ms, "milliseconds between deep-click pulses, 0 to use haptic_pulse_gap_ms (default 15)"); /* - * Linux has no key for a force click, so which one to send is the user's - * choice; nothing is sent unless one is named. It is held down for as long as + * Linux has no key for a force click. KEY_INFO (XF86Info) stands for it: the + * desktop binds that keysym to what a force click does there (in GNOME Files, + * the preview of the item clicked), and nothing binds it by default, so the + * key does nothing where no one asks for it. It is held down for as long as * the deep stage lasts. The key comes from a separate input device: libinput * drives a touchpad with its own dispatcher, which drops every key that is not * a button, so a key on the trackpad's own device never reaches userspace. It * is read at probe because that device is set up there. */ -static u16 haptic_deep_keycode; +static u16 haptic_deep_keycode = KEY_INFO; module_param(haptic_deep_keycode, ushort, 0444); -MODULE_PARM_DESC(haptic_deep_keycode, "key code held during a deep click on a separate \"Force Click\" input device, 0 for none (default 0)"); +MODULE_PARM_DESC(haptic_deep_keycode, "key code held during a deep click on a separate \"Force Click\" input device, 0 for none (default KEY_INFO)"); static u8 haptic_pulse_gap_ms = 25; module_param(haptic_pulse_gap_ms, byte, 0644); From 295c9494ddf116bc2066bfe85be4a42d1c565bf9 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 15:49:06 +0700 Subject: [PATCH 0782/1514] media: apple: scaler: T8142 (M5) MSR23 The M5's scaler (MSR23) is fronted by a Cortex-M core: the driver no longer programs the engine's registers but hands the core block lists in a DMA ring. Bring it up: - start the image iBoot pre-loads into the core's SRAM (or upload the variant's firmware file when the SRAM holds none and the core has never run: writing the SRAM under a core that has run hangs the machine); - write the engine's power-up registers, start the core, take its hello, and send the init message and the four shared pages; - submit jobs through the block-list ring and collect their status from the status ring. A job whose status is an error, or whose status entry belongs to another job, fails and takes the core out of service, as a timeout does. The firmware file name and the power-up writes, each with the time to wait after it (1 ms after the reset release on T8142), are variant data, so a later MSR23 SoC can reuse the code. Each job is a register image the firmware streams into the engine. The driver builds it from the job's parameters (apple-scaler-msr23.c): sizes, strides and plane codes per side, the scaler's steps, initial phases and polyphase filter bins per axis, the colour matrix (asc_csc_compute()), chroma up/downsampling, the dither of a 10-bit source written at 8 bits, and the spill buffer size. Words that are the same in every job are a defaults table. The polyphase filter taps (8 bins of 9 taps, 32 phases) are generated from a stated design, a Kaiser-windowed sinc per scaling ratio, by tools/media/apple-scaler/msr23_filters.py, which also documents how the engine stores them. The firmware tiles the job itself (job word 0x72000000), so no tile array is built. The engine takes B,G,R,A (V4L2 ABGR32, added for MSR23 only), NV12, NV16, NV24, P010 and GREY, even sizes from 64 to 4096 wide and up to 4K UHD in area, and scales up to 4x down or up per axis. Y'CbCr to Y'CbCr keeps the matrix and range. Formats are limited to that range, and STREAMON refuses a pair outside it. Tested on the MacBook Air 15" M5 (J815) against macOS 27.2's output for the same input, over 76 jobs: BGRA <-> NV12 at BT.601/709/2020, video and full range; BGRA -> P010, NV16 and NV24 and P010 -> BGRA; BGRA scaling from 1/4 to 4x, on both axes or one; NV12, P010 and GREY scaling; 4K BGRA -> 1080p NV12 and back; the conversions at seven sizes from VGA to 4K; and crops, rotations and flips. With the coefficient set captured from macOS's own jobs loaded in place of the generated one, all 76 are byte-identical, which checks everything but the taps. With the generated taps, 52 are byte-identical and 24 differ by at most one code value per sample (PSNR 57.8 dB or better). Add KUnit tests for the builder: a BGRA -> NV12 conversion, scaling steps and phases, the rejected jobs and the block list. Signed-off-by: Nick --- MAINTAINERS | 1 + drivers/media/platform/apple/scaler/Kconfig | 11 +- drivers/media/platform/apple/scaler/Makefile | 2 +- .../platform/apple/scaler/apple-scaler-drv.c | 1161 ++++++++++++++++- .../platform/apple/scaler/apple-scaler-hw.c | 26 + .../platform/apple/scaler/apple-scaler-hw.h | 2 + .../apple/scaler/apple-scaler-msr23.c | 598 +++++++++ .../apple/scaler/apple-scaler-msr23.h | 103 ++ .../platform/apple/scaler/apple-scaler-test.c | 146 +++ tools/media/apple-scaler/msr23_filters.py | 155 +++ 10 files changed, 2133 insertions(+), 72 deletions(-) create mode 100644 drivers/media/platform/apple/scaler/apple-scaler-msr23.c create mode 100644 drivers/media/platform/apple/scaler/apple-scaler-msr23.h create mode 100755 tools/media/apple-scaler/msr23_filters.py diff --git a/MAINTAINERS b/MAINTAINERS index 3f919f3e327f30..b591f4dcfb7e00 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2877,6 +2877,7 @@ S: Maintained W: https://aurora-silicon.github.io F: Documentation/devicetree/bindings/media/apple,scaler.yaml F: drivers/media/platform/apple/scaler/ +F: tools/media/apple-scaler/ ARM/ARTPEC MACHINE SUPPORT M: Jesper Nilsson diff --git a/drivers/media/platform/apple/scaler/Kconfig b/drivers/media/platform/apple/scaler/Kconfig index dcfb18859d6890..67e716da04e1c9 100644 --- a/drivers/media/platform/apple/scaler/Kconfig +++ b/drivers/media/platform/apple/scaler/Kconfig @@ -7,11 +7,12 @@ config VIDEO_APPLE_SCALER depends on OF_ADDRESS && IOMMU_API && PM select V4L2_MEM2MEM_DEV select VIDEOBUF2_DMA_CONTIG + select CRC32 help V4L2 memory-to-memory driver for the image scaler and - colour-space converter (MSR) in Apple silicon SoCs (M1 to M4 + colour-space converter (MSR) in Apple silicon SoCs (M1 to M5 generations and A18 Pro). It converts between Y'CbCr (NV12, - P010) and 32-bit RGB at the same size; scaling follows. + P010) and 32-bit RGB; on M5 it also scales. To compile this driver as a module, choose M here: the module will be called apple-scaler. @@ -21,6 +22,6 @@ config VIDEO_APPLE_SCALER_KUNIT_TEST depends on KUNIT && VIDEO_APPLE_SCALER default KUNIT_ALL_TESTS help - Check the colour-conversion matrices, offsets, scale ratios and - format encodings the scaler driver programs. No hardware is - needed. + Check the colour-conversion matrices, offsets, scale ratios, + format encodings and M5 job images the scaler driver programs. + No hardware is needed. diff --git a/drivers/media/platform/apple/scaler/Makefile b/drivers/media/platform/apple/scaler/Makefile index d6a9dcbe9b33ef..64288df5253dc9 100644 --- a/drivers/media/platform/apple/scaler/Makefile +++ b/drivers/media/platform/apple/scaler/Makefile @@ -1,5 +1,5 @@ # SPDX-License-Identifier: GPL-2.0-only obj-$(CONFIG_VIDEO_APPLE_SCALER) += apple-scaler.o -apple-scaler-y := apple-scaler-drv.o apple-scaler-hw.o +apple-scaler-y := apple-scaler-drv.o apple-scaler-hw.o apple-scaler-msr23.o obj-$(CONFIG_VIDEO_APPLE_SCALER_KUNIT_TEST) += apple-scaler-test.o diff --git a/drivers/media/platform/apple/scaler/apple-scaler-drv.c b/drivers/media/platform/apple/scaler/apple-scaler-drv.c index d9707d2aec0687..0af9f7fad4606c 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-drv.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-drv.c @@ -6,14 +6,18 @@ * scalers with a programmable colour-space converter, chroma resampling, * flip/rotate and alpha fill. Hardware-version 10 (M1) through 22 (A18 Pro) * are programmed directly through MMIO and report completion with an - * interrupt; later generations front the engine with firmware and are not - * handled here. + * interrupt. Hardware-version 23 (M5) fronts the engine with firmware: the + * driver builds each job's register image and queues it to the firmware. * * The OUTPUT queue takes the source image, the CAPTURE queue the result. - * This version converts between formats at the same size: Y'CbCr <-> + * The MMIO engines convert between formats at the same size: Y'CbCr <-> * R'G'B' with the colorimetry of the Y'CbCr side, chroma resampling and - * alpha fill. Scaling comes once the filter path is qualified. + * alpha fill. MSR23 converts and scales (up to 4x either way per axis). */ +#include +#include +#include +#include #include #include #include @@ -22,10 +26,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -41,6 +47,7 @@ #include "../apple-video-nr.h" #include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" #include "apple-scaler-regs.h" #define ASC_NAME "apple-scaler" @@ -56,15 +63,29 @@ * @hw_version: MSR hardware-version of this SoC (from the hardware description) * @num_reg: number of register apertures the binding describes * @msr20: the engine has the MSR20-generation control block + * @fw_fronted: hardware-version 23 and later: jobs go through firmware queues + * (see asc_v23_probe()) + * @fw_name: fw_fronted: the core's image, uploaded only when the SRAM holds none + * @powerup: fw_fronted: the register writes that prepare the engine before its + * core starts + * @num_powerup: the number of @powerup writes */ struct apple_scaler_variant { u32 hw_version; unsigned int num_reg; bool msr20; + bool fw_fronted; + const char *fw_name; + const struct msr23_wr *powerup; + unsigned int num_powerup; }; +struct msr23; +struct msr23_wr; + struct apple_scaler { struct device *dev; + struct msr23 *msr; /* MSR23 (fw_fronted): firmware core and job queues */ void __iomem *regs; resource_size_t regs_size; const struct apple_scaler_variant *variant; @@ -90,6 +111,11 @@ struct apple_scaler_ctx { struct apple_scaler *asc; struct v4l2_pix_format_mplane src; /* OUTPUT queue */ struct v4l2_pix_format_mplane dst; /* CAPTURE queue */ + /* + * The CAPTURE colorimetry asked for (an RGB -> YUV conversion target), + * whichever queue is set first. + */ + u32 dst_ycbcr_req, dst_quant_req; u32 sequence; }; @@ -110,7 +136,6 @@ static void asc_write(struct apple_scaler *asc, u32 reg, u32 val) /* ---- hardware --------------------------------------------------------- */ - /* * After power-up or a failed job: wait for idle, pulse the engine reset * (no register may be read while it is held), clear stale status and @@ -260,6 +285,8 @@ static void asc_image(struct asc_image *img, const struct v4l2_pix_format_mplane } } +static void msr23_device_run(struct apple_scaler *asc, struct apple_scaler_ctx *ctx); + static void asc_device_run(void *priv) { struct apple_scaler_ctx *ctx = priv; @@ -270,6 +297,10 @@ static void asc_device_run(void *priv) unsigned long flags; int n, ret; + if (asc->variant->fw_fronted) { + msr23_device_run(asc, ctx); + return; + } src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); ret = pm_runtime_resume_and_get(asc->dev); @@ -349,17 +380,52 @@ static const struct v4l2_m2m_ops asc_m2m_ops = { * colorimetry; the R'G'B' side is full range with the same primaries and * transfer function, since the engine converts only the encoding. */ -static void asc_fill(struct v4l2_pix_format_mplane *pix, const struct v4l2_pix_format_mplane *ref, - u32 default_fourcc) +/* + * MSR23 builds its jobs (apple-scaler-msr23.c) for B,G,R,A, NV12, NV16, NV24, + * P010 and GREY. The older engines never offer the MSR23-only formats. + */ +static bool asc_fmt_ok(const struct apple_scaler *asc, const struct asc_format *f) +{ + if (!f) + return false; + if (asc->variant->fw_fronted) { + switch (f->fourcc) { + case V4L2_PIX_FMT_ABGR32: + case V4L2_PIX_FMT_NV12: + case V4L2_PIX_FMT_NV12M: + case V4L2_PIX_FMT_NV16: + case V4L2_PIX_FMT_NV24: + case V4L2_PIX_FMT_P010: + case V4L2_PIX_FMT_GREY: + return true; + } + return false; + } + return !f->msr23_only; +} + +static void asc_fill(const struct apple_scaler *asc, struct v4l2_pix_format_mplane *pix, + const struct v4l2_pix_format_mplane *ref, u32 default_fourcc) { const struct asc_format *f = asc_find_format(pix->pixelformat); - u32 w = ref ? ref->width : pix->width, h = ref ? ref->height : pix->height; + /* MSR23 scales: its CAPTURE side keeps its own size. */ + bool own = asc->variant->fw_fronted || !ref; + u32 w = own ? pix->width : ref->width, h = own ? pix->height : ref->height; struct v4l2_pix_format_mplane in = *pix; - if (!f) + if (!asc_fmt_ok(asc, f) && asc->variant->fw_fronted) + f = asc_find_format(default_fourcc == V4L2_PIX_FMT_ARGB32 ? + V4L2_PIX_FMT_ABGR32 : V4L2_PIX_FMT_NV12); + else if (!asc_fmt_ok(asc, f)) f = asc_find_format(default_fourcc); - w = clamp_t(u32, ALIGN(w, f->hsub), ASC_MIN_SIZE, ASC_MAX_SIZE); - h = clamp_t(u32, ALIGN(h, f->vsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + if (asc->variant->fw_fronted) { + /* the builder's range: even sizes, 64 to 4096 */ + w = clamp_t(u32, ALIGN(w, 2), MSR23_MIN_SIZE, MSR23_MAX_WIDTH); + h = clamp_t(u32, ALIGN(h, 2), MSR23_MIN_SIZE, MSR23_MAX_WIDTH); + } else { + w = clamp_t(u32, ALIGN(w, f->hsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + h = clamp_t(u32, ALIGN(h, f->vsub), ASC_MIN_SIZE, ASC_MAX_SIZE); + } memset(pix, 0, sizeof(*pix)); if (f->lossless) { @@ -373,7 +439,12 @@ static void asc_fill(struct v4l2_pix_format_mplane *pix, const struct v4l2_pix_f pix->plane_fmt[0].bytesperline = g.y_pitch; pix->plane_fmt[0].sizeimage = g.bytes; } else { - v4l2_fill_pixfmt_mp_aligned(pix, f->fourcc, w, h, ASC_STRIDE_ALIGN); + /* + * MSR23: 16-byte aligned strides (NV12 1440 wide: 1440 bytes); + * the engine takes them. + */ + v4l2_fill_pixfmt_mp_aligned(pix, f->fourcc, w, h, + asc->variant->fw_fronted ? 16 : ASC_STRIDE_ALIGN); } pix->field = V4L2_FIELD_NONE; @@ -416,24 +487,37 @@ static int asc_querycap(struct file *file, void *priv, struct v4l2_capability *c static int asc_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *f) { - const struct asc_format *fmt = asc_format_by_index(f->index); - - if (!fmt) - return -EINVAL; - f->pixelformat = fmt->fourcc; - return 0; + const struct apple_scaler *asc = asc_file_to_ctx(file)->asc; + const struct asc_format *fmt; + unsigned int i, n = 0; + + for (i = 0; (fmt = asc_format_by_index(i)); i++) { + if (!asc_fmt_ok(asc, fmt)) + continue; + if (n++ == f->index) { + f->pixelformat = fmt->fourcc; + return 0; + } + } + return -EINVAL; } static int asc_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { + const struct apple_scaler *asc = asc_file_to_ctx(file)->asc; const struct asc_format *f = asc_find_format(fs->pixel_format); - if (fs->index || !f) + if (fs->index || !asc_fmt_ok(asc, f)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; - fs->stepwise = (struct v4l2_frmsize_stepwise){ - ASC_MIN_SIZE, ASC_MAX_SIZE, f->hsub, ASC_MIN_SIZE, ASC_MAX_SIZE, f->vsub, - }; + if (asc->variant->fw_fronted) + fs->stepwise = (struct v4l2_frmsize_stepwise){ + MSR23_MIN_SIZE, MSR23_MAX_WIDTH, 2, MSR23_MIN_SIZE, MSR23_MAX_WIDTH, 2, + }; + else + fs->stepwise = (struct v4l2_frmsize_stepwise){ + ASC_MIN_SIZE, ASC_MAX_SIZE, f->hsub, ASC_MIN_SIZE, ASC_MAX_SIZE, f->vsub, + }; return 0; } @@ -451,13 +535,15 @@ static int asc_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) static int asc_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { - asc_fill(&f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(asc_file_to_ctx(file)->asc, &f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); return 0; } static int asc_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { - asc_fill(&f->fmt.pix_mp, &asc_file_to_ctx(file)->src, V4L2_PIX_FMT_ARGB32); + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + + asc_fill(ctx->asc, &f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); return 0; } @@ -468,9 +554,16 @@ static int asc_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) if (vb2_is_busy(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; - asc_fill(&f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(asc_file_to_ctx(file)->asc, &f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); ctx->src = f->fmt.pix_mp; - asc_fill(&ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + /* + * Re-derive CAPTURE from the new source, with the matrix and range it was asked for: a + * CAPTURE format set before this (v4l2-ctl sets CAPTURE first) took them from the previous + * source, the open-time NV12 default. + */ + ctx->dst.ycbcr_enc = ctx->dst_ycbcr_req; + ctx->dst.quantization = ctx->dst_quant_req; + asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); return 0; } @@ -480,7 +573,9 @@ static int asc_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) if (vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; - asc_fill(&f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); + ctx->dst_ycbcr_req = f->fmt.pix_mp.ycbcr_enc; + ctx->dst_quant_req = f->fmt.pix_mp.quantization; + asc_fill(ctx->asc, &f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); ctx->dst = f->fmt.pix_mp; return 0; } @@ -563,10 +658,43 @@ static void asc_buf_queue(struct vb2_buffer *vb) v4l2_m2m_buf_queue(ctx->fh.m2m_ctx, to_vb2_v4l2_buffer(vb)); } +static void asc_return_bufs(struct vb2_queue *q, enum vb2_buffer_state state) +{ + struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_v4l2_buffer *vbuf; + + for (;;) { + vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : + v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); + if (!vbuf) + break; + v4l2_m2m_buf_done(vbuf, state); + } +} + +static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *job); + static int asc_start_streaming(struct vb2_queue *q, unsigned int count) { struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_queue *other = V4L2_TYPE_IS_OUTPUT(q->type) ? + v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx) : + v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx); + struct msr23_job job; + /* + * MSR23: both formats are fixed once both queues stream; refuse here a + * pair the job builder does not cover (size ratio, area, conversion) + * rather than fail every job. + */ + if (ctx->asc->variant->fw_fronted && vb2_is_streaming(other) && + msr23_job_of(ctx, &job)) { + dev_dbg(ctx->asc->dev, "MSR23: %.4s %ux%u -> %.4s %ux%u not supported\n", + (char *)&ctx->src.pixelformat, ctx->src.width, ctx->src.height, + (char *)&ctx->dst.pixelformat, ctx->dst.width, ctx->dst.height); + asc_return_bufs(q, VB2_BUF_STATE_QUEUED); + return -EINVAL; + } if (V4L2_TYPE_IS_OUTPUT(q->type)) ctx->sequence = 0; return 0; @@ -574,16 +702,7 @@ static int asc_start_streaming(struct vb2_queue *q, unsigned int count) static void asc_stop_streaming(struct vb2_queue *q) { - struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); - struct vb2_v4l2_buffer *vbuf; - - for (;;) { - vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : - v4l2_m2m_dst_buf_remove(ctx->fh.m2m_ctx); - if (!vbuf) - break; - v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); - } + asc_return_bufs(q, VB2_BUF_STATE_ERROR); } static const struct vb2_ops asc_qops = { @@ -630,9 +749,11 @@ static int asc_open(struct file *file) ctx->src.width = 1920; ctx->src.height = 1080; ctx->src.pixelformat = V4L2_PIX_FMT_NV12M; - asc_fill(&ctx->src, NULL, V4L2_PIX_FMT_NV12M); + asc_fill(ctx->asc, &ctx->src, NULL, V4L2_PIX_FMT_NV12M); + ctx->dst.width = 1920; + ctx->dst.height = 1080; ctx->dst.pixelformat = V4L2_PIX_FMT_ARGB32; - asc_fill(&ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); v4l2_fh_init(&ctx->fh, video_devdata(file)); ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(asc->m2m_dev, ctx, asc_queue_init); @@ -689,10 +810,14 @@ static int asc_suspend(struct device *dev) { struct apple_scaler *asc = dev_get_drvdata(dev); - v4l2_m2m_suspend(asc->m2m_dev); + /* MSR23: the core loses its state; asc_resume() restarts it. */ + if (asc->m2m_dev) + v4l2_m2m_suspend(asc->m2m_dev); return pm_runtime_force_suspend(dev); } +static void msr23_restart(struct msr23 *m); + static int asc_resume(struct device *dev) { struct apple_scaler *asc = dev_get_drvdata(dev); @@ -700,7 +825,10 @@ static int asc_resume(struct device *dev) if (ret) return ret; - v4l2_m2m_resume(asc->m2m_dev); + if (asc->variant->fw_fronted && asc->msr) + msr23_restart(asc->msr); + if (asc->m2m_dev) + v4l2_m2m_resume(asc->m2m_dev); return 0; } @@ -735,21 +863,930 @@ static int asc_identify(struct apple_scaler *asc) return 0; } +/* + * MSR23 (M5): firmware-fronted. + * + * - The engine is fronted by a Cortex-M core (the "MSR ASE core", power + * domain msr-ase-core). Its code is __TEXT of the "msrf" image (0x11650 + * bytes, linked at 0x100000) in SRAM at reg[5] + 0x0; its data RAM + * (0x10000000 in the core's view) is reg[5] + 0x80000; its mailbox and + * control registers (0x50000000) are reg[5] + 0x100000. + * - iBoot pre-loads __TEXT (ADT scaler0: pre-loaded = 1, segment-ranges). + * - Start-up: the engine's power-up register writes, then the core starts + * with reg[5]+0x100028 = 0xe then 0 and reports reg[0]+0x78 = 2, sends a + * hello through the mailbox, takes one init message and four shared + * pages, and writes "LIVE", later "STAR", to reg[5]+0x80038. + * + * The driver checks the image iBoot left in SRAM (S0), uploads the variant's + * firmware file only when the SRAM holds none and the core has never run + * (S1), then starts the core (S2) and sends the init pages (S3). + */ + +#define MSR23_TEXT_SIZE 0x11650 +#define MSR23_SRAM_TEXT_MAX 0x80000 +#define MSR23_SP_INIT 0x1000fffc +#define MSR23_TEXT_BASE 0x100000 +#define MSR23_DRAM 0x80000 /* reg[5]: core data RAM */ +#define MSR23_DRAM_MAGIC (MSR23_DRAM + 0x38) /* "LIVE", "STAR" */ +#define MSR23_LOG_WPTR (MSR23_DRAM + 0x80) +#define MSR23_LOG (MSR23_DRAM + 0x200) +#define MSR23_CPU_START 0x100028 +#define MSR23_STATUS 0x100124 +#define MSR23_A2I_CTRL 0x108110 +#define MSR23_I2A_CTRL 0x108114 +#define MSR23_A2I_SEND 0x108800 +#define MSR23_I2A_RECV 0x108830 +#define MSR23_MBOX_EMPTY BIT(17) +#define MSR23_FW_STATE 0x78 /* reg[0] */ +#define MSR23_MAGIC_LIVE 0x4556494c +#define MSR23_MAGIC_STAR 0x52415453 +#define MSR23_SHMEM_SIZE SZ_16K +#define MAGIC_FDBE 0xfdbefdbe + +struct msr23_wr { + u8 win; + u32 off; + u32 val; + u16 settle_us; /* wait this long after the write */ +}; + +/* + * T8142: the writes that prepare the engine before its core starts, in order. + * The ADT names no fields; by aperture: + * - reg[0] (engine control): a reset pulse at +0x4 (the core needs ~1 ms + * after it, so the release write carries settle_us), then +0x48/+0x50 + * and, at the end, +0x28..+0x54 and the +0x10288.. and +0x10688.. tables; + * - reg[3]: +0x0..+0x34, +0x100.., +0x300.., +0x404.. and +0x4008..; + * - reg[8] and reg[6]: one group each. + */ +static const struct msr23_wr msr23_t8142_powerup[] = { + {0, 0x00004, 0x00000001}, {0, 0x00004, 0x00000000, 1000}, {0, 0x00050, 0x00000000}, + {0, 0x00048, 0x00000000}, {0, 0x00050, 0x00000003}, + {3, 0x00000, 0x8000001b}, {3, 0x00004, 0x800c000d}, {3, 0x00008, 0x800c000d}, + {3, 0x0000c, 0x800c000d}, {3, 0x00010, 0x80000003}, {3, 0x00014, 0x80000003}, + {3, 0x00018, 0x80000011}, {3, 0x0001c, 0x80000014}, {3, 0x00020, 0x8014000c}, + {3, 0x00024, 0x80000004}, {3, 0x00028, 0x80000004}, {3, 0x0002c, 0x80000015}, + {3, 0x00030, 0x9000000f}, {3, 0x00034, 0x9000000f}, {3, 0x00100, 0x000000ff}, + {3, 0x00104, 0x00010003}, {3, 0x00108, 0x000413b1}, {3, 0x00300, 0x1c000211}, + {3, 0x00304, 0x04040000}, {3, 0x00314, 0x80000002}, {3, 0x0031c, 0x80000009}, + {3, 0x00404, 0x00100071}, {3, 0x00748, 0x00200000}, {3, 0x00848, 0x02000120}, + {3, 0x00a00, 0x7fffffff}, {3, 0x00a04, 0x00000101}, {3, 0x04008, 0x00000000}, + {3, 0x0400c, 0x00000000}, {3, 0x04014, 0x00000000}, {3, 0x04018, 0x00000000}, + {3, 0x0401c, 0x00000001}, + {8, 0x00000, 0x00000000}, {8, 0x00010, 0x0001fbf2}, {8, 0x00014, 0x0001fbf2}, + {8, 0x00018, 0x0001fbf3}, {8, 0x0001c, 0x0001fbf0}, {8, 0x00020, 0x0001fbf0}, + {6, 0x00000, 0x00100011}, + {0, 0x00028, 0x0101005f}, {0, 0x0002c, 0x0000005e}, {0, 0x00030, 0x0000015c}, + {0, 0x0004c, 0x01ffffff}, {0, 0x00050, 0x00000003}, {0, 0x00054, 0x00000003}, + {0, 0x10288, 0x0000000c}, {0, 0x1028c, 0x00000006}, {0, 0x10290, 0x00000004}, + {0, 0x10294, 0x00000002}, {0, 0x10298, 0x00000001}, + {0, 0x10688, 0x00010012}, {0, 0x1068c, 0x0002001c}, {0, 0x10690, 0x00040030}, + {0, 0x10694, 0x00080042}, {0, 0x106a4, 0x4ec20040}, {0, 0x106b8, 0x4ec20040}, + {0, 0x106cc, 0x4ec20040}, {0, 0x106e0, 0x4ec20040}, {0, 0x106e4, 0x00200028}, + {0, 0x106f4, 0x4ec2004c}, {0, 0x106f8, 0x0040003c}, {0, 0x10708, 0x4ec20040}, + {0, 0x1070c, 0x0020000c}, {0, 0x1071c, 0x4ec20010}, {0, 0x10720, 0x0020000c}, + {0, 0x10730, 0x4ec20040}, {0, 0x10744, 0x4ec20040}, {0, 0x10758, 0x4ec2006c}, + {0, 0x1075c, 0x00400054}, {0, 0x1076c, 0x4ec200d8}, {0, 0x10770, 0x008000a4}, + {0, 0x10780, 0x4ec200b0}, {0, 0x10784, 0x00400088}, {0, 0x10794, 0x4ec20040}, + {0, 0x107a8, 0x4ec20040}, {0, 0x107bc, 0x4ec200ac}, {0, 0x107c0, 0x00400084}, + {0, 0x107d0, 0x4ec20040}, {0, 0x107d4, 0x00400024}, {0, 0x107e4, 0x4ec20040}, + {0, 0x107f8, 0x4ec20040}, {0, 0x107fc, 0x00400014}, {0, 0x1080c, 0x4ec20034}, + {0, 0x10810, 0x00400028}, {0, 0x10820, 0x4ec2001c}, {0, 0x10824, 0x00400014}, + {0, 0x10834, 0x4ec20040}, {0, 0x10848, 0x4ec20040}, +}; + +/* + * Jobs. + * Everything the firmware reads is DMA memory addressed by its offset in the + * DART window that starts at 1 << 40: + * - a ring of block-list records in shared page 0x02 (0x400 words); the AP + * writes a record, then reg[4]+0x10038 = its write pointer in words + * (bit 31 flips on wrap). A record: 0xfdbefdbe, seq << 8 | 2, a job word, + * pair count << 16, then (block word, size word) pairs. A block word is + * (offset >> 7) << 8 | block id; a size word holds the size in 32-byte + * units from bit 20; + * - the blocks: a register image (80 KiB) and a spill buffer. The job word + * 0x72000000 has the firmware tile the job; with bit 31, the AP builds the + * tile array (block 15) instead, which this driver does not; + * - completion: the status ring at reg[5]+0x83a00 (0x200 words, 20-word + * entries), its write pointer reg[4]+0x30008, the AP acknowledges with + * reg[4]+0x10010. + * The driver builds the register image from the job's parameters + * (apple-scaler-msr23.c). + */ +#define MSR23_WIN BIT_ULL(40) +#define MSR23_WIN_SPAN SZ_2G /* block words hold offset >> 7 in 24 bits */ +#define MSR23_RING_WORDS 0x400 +#define MSR23_STS_BASE 0x83a00 /* reg[5] */ +#define MSR23_STS_WORDS 0x200 +#define MSR23_STS_ENTRY 0x14 +#define MSR23_STS_OK0 0x00140007 /* status words 0 and 2 of a job that completed */ +#define MSR23_STS_OK2 0x00000200 +#define MSR23_Q_SUBMIT 0x10038 /* reg[4], 64-bit */ +#define MSR23_Q_STAMP 0x100f8 +#define MSR23_Q_STS_READ 0x10010 +#define MSR23_Q_STS_WRITE 0x30008 +#define MSR23_Q_SUB_DONE 0x30040 +#define MSR23_JOB_TIMEOUT_US 1000000 + +struct msr23 { + struct device *dev; + struct apple_scaler *asc; + void __iomem *w[10]; + void __iomem *dart; /* read only: the window registers and the error word */ + resource_size_t w5_phys; + /* shared pages, in the order of S3's messages (ids 0x10, 0x01, 0x02, 0x23) */ + void *page[4]; + dma_addr_t page_iova[4]; + bool window; /* IOVAs are inside the 1 << 40 window */ + bool started; /* S3 saw LIVE/STAR */ + u64 ring_wptr, sts_rptr; + u32 seq; + struct work_struct work; + struct apple_scaler_ctx *ctx; +}; + +/* + * The DART window the firmware addresses through: dart+0x300 = 1, +0x308 = + * 0x10000000 (base 1 << 40 in 4K pages), +0x310 = 0x3fffffff. + */ +static void msr23_dart(struct msr23 *m, const char *when) +{ + if (!m->dart) + return; + dev_dbg(m->dev, + "MSR23 %s: dart +0x300 %#x +0x308 %#x +0x310 %#x error +0x100 %#x tcr0/1 %#x %#x ttbr0/1 %#x %#x\n", + when, readl(m->dart + 0x300), readl(m->dart + 0x308), readl(m->dart + 0x310), + readl(m->dart + 0x100), readl(m->dart + 0x1000), readl(m->dart + 0x1004), + readl(m->dart + 0x1400), readl(m->dart + 0x1404)); +} + +static bool msr23_text_valid(const u32 *vec) +{ + return vec[0] == MSR23_SP_INIT && vec[1] >= MSR23_TEXT_BASE && + vec[1] < MSR23_TEXT_BASE + MSR23_SRAM_TEXT_MAX; +} + +/* S0: what the SRAM holds. Returns 1 (valid, matches the file or no file), 0 (absent/different). */ +static int msr23_s0(struct msr23 *m, const struct firmware *fw) +{ + void __iomem *w0 = m->w[0], *w5 = m->w[5]; + size_t len; + u32 vec[2], crc_sram, crc_file = 0; + bool valid, same = false; + void *buf; + + /* a file shorter than the vector or larger than the SRAM is no image: compare nothing */ + if (fw && (fw->size < sizeof(vec) || fw->size > MSR23_SRAM_TEXT_MAX)) { + dev_warn(m->dev, "MSR23 S0: %s has %zu bytes: not an MSR __TEXT image, ignored\n", + m->asc->variant->fw_name, fw->size); + fw = NULL; + } + len = fw ? fw->size : MSR23_TEXT_SIZE; + buf = kvmalloc(len, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy_fromio(buf, w5, len); + memcpy(vec, buf, sizeof(vec)); + valid = msr23_text_valid(vec); + crc_sram = crc32_le(0, buf, len); + if (fw) { + crc_file = crc32_le(0, fw->data, fw->size); + same = !memcmp(buf, fw->data, fw->size); + } + kvfree(buf); + + dev_dbg(m->dev, + "MSR23 S0: SRAM vector SP %#x reset %#x (%s), crc32 %#x over %#zx; file %s crc32 %#x: %s\n", + vec[0], vec[1], valid ? "an MSR image" : "no image", crc_sram, len, + fw ? m->asc->variant->fw_name : "(none)", crc_file, + !fw ? "no file to compare" : + same ? "SRAM == file (pre-loaded by iBoot)" : + valid ? "SRAM holds a different image" : "SRAM empty"); + dev_dbg(m->dev, + "MSR23 S0: state +0x78 %#x status %#x magic %#x log wptr %#x mbox a2i %#x i2a %#x/%#x %#x/%#x (before the start: 0, -, -, -, 0x20001 x4)\n", + readl(w0 + MSR23_FW_STATE), readl(w5 + MSR23_STATUS), readl(w5 + MSR23_DRAM_MAGIC), + readl(w5 + MSR23_LOG_WPTR), readl(w5 + MSR23_A2I_CTRL), readl(w5 + MSR23_I2A_CTRL), + readl(w5 + 0x124110), readl(w5 + 0x124114), readl(w5 + 0x100058)); + return valid && (same || !fw); +} + +/* S1: write __TEXT into the SRAM and read it back. */ +static int msr23_s1(struct msr23 *m, const struct firmware *fw) +{ + void *buf; + int ret = 0; + + if (fw->size < 2 * sizeof(u32) || fw->size > MSR23_SRAM_TEXT_MAX || + !msr23_text_valid((const u32 *)fw->data)) { + dev_err(m->dev, "MSR23 S1: %s is not an MSR __TEXT image (%zu bytes)\n", + m->asc->variant->fw_name, fw->size); + return -EINVAL; + } + memcpy_toio(m->w[5], fw->data, fw->size); + /* the ring record before the write pointer that hands it over */ + wmb(); + buf = kvmalloc(fw->size, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy_fromio(buf, m->w[5], fw->size); + if (memcmp(buf, fw->data, fw->size)) { + size_t i; + + for (i = 0; i < fw->size && ((u8 *)buf)[i] == fw->data[i]; i++) + ; + dev_err(m->dev, + "MSR23 S1: upload FAILED: readback differs from %#zx (the SRAM is not AP-writable this way)\n", + i); + ret = -EIO; + } else { + dev_dbg(m->dev, "MSR23 S1: uploaded %#zx bytes of %s to SRAM, readback ok\n", + fw->size, m->asc->variant->fw_name); + } + kvfree(buf); + return ret; +} + +static void msr23_log_tail(struct msr23 *m, const char *when) +{ + void __iomem *w5 = m->w[5]; + u32 e[4]; + int i; + + dev_dbg(m->dev, + "MSR23 %s: magic %#x status %#x log wptr %#x/%#x dram+0x18 %#x %#x %#x %#x +0x30 %#x %#x\n", + when, readl(w5 + MSR23_DRAM_MAGIC), readl(w5 + MSR23_STATUS), + readl(w5 + MSR23_LOG_WPTR), readl(w5 + MSR23_LOG_WPTR + 4), + readl(w5 + MSR23_DRAM + 0x18), readl(w5 + MSR23_DRAM + 0x1c), + readl(w5 + MSR23_DRAM + 0x20), readl(w5 + MSR23_DRAM + 0x24), + readl(w5 + MSR23_DRAM + 0x30), readl(w5 + MSR23_DRAM + 0x34)); + for (i = 0; i < 8; i++) { + memcpy_fromio(e, w5 + MSR23_LOG + 16 * i, sizeof(e)); + if (!e[0] && !e[1]) + break; + dev_dbg(m->dev, "MSR23 %s: log[%d] %08x %08x %08x %08x\n", when, i, e[0], e[1], + e[2], e[3]); + } +} + +static int msr23_recv(struct msr23 *m, u32 msg[4], unsigned int timeout_us) +{ + u32 ctl; + int ret; + + ret = readl_poll_timeout(m->w[5] + MSR23_I2A_CTRL, ctl, !(ctl & MSR23_MBOX_EMPTY), 100, + timeout_us); + if (ret) + return ret; + msg[0] = readl(m->w[5] + MSR23_I2A_RECV + 0x0); + msg[1] = readl(m->w[5] + MSR23_I2A_RECV + 0x4); + msg[2] = readl(m->w[5] + MSR23_I2A_RECV + 0x8); + msg[3] = readl(m->w[5] + MSR23_I2A_RECV + 0xc); /* the last read pops */ + return 0; +} + +static int msr23_send(struct msr23 *m, u64 msg0, u64 msg1) +{ + u32 ctl = readl(m->w[5] + MSR23_A2I_CTRL); + + writel(lower_32_bits(msg0), m->w[5] + MSR23_A2I_SEND + 0x0); + writel(upper_32_bits(msg0), m->w[5] + MSR23_A2I_SEND + 0x4); + writel(lower_32_bits(msg1), m->w[5] + MSR23_A2I_SEND + 0x8); + writel(upper_32_bits(msg1), m->w[5] + MSR23_A2I_SEND + 0xc); + dev_dbg(m->dev, "MSR23 S3: sent %#018llx %#llx (a2i before %#x after %#x)\n", msg0, msg1, + ctl, readl(m->w[5] + MSR23_A2I_CTRL)); + return 0; +} + +/* S2: power-up table, then the start handshake. */ +static int msr23_s2(struct msr23 *m) +{ + static const u32 mbox[] = { MSR23_A2I_CTRL, MSR23_I2A_CTRL, 0x124110, 0x124114 }; + void __iomem *w0 = m->w[0], *w5 = m->w[5]; + const struct apple_scaler_variant *var = m->asc->variant; + u32 v, a, b, msg[4]; + unsigned int i; + int ret; + + for (i = 0; i < var->num_powerup; i++) { + const struct msr23_wr *wr = &var->powerup[i]; + + writel(wr->val, m->w[wr->win] + wr->off); + if (wr->settle_us) + usleep_range(wr->settle_us, 2 * wr->settle_us); + } + + for (i = 0; i < ARRAY_SIZE(mbox); i++) { + v = readl(w5 + mbox[i]); + writel(v & ~1U, w5 + mbox[i]); + } + v = readl(w0 + MSR23_FW_STATE); + writel(0xe, w5 + MSR23_CPU_START); + a = readl(w5 + 0x100058); + b = readl(w5 + 0x10005c); + writel(0, w0 + MSR23_FW_STATE); + writel(0, w5 + MSR23_CPU_START); + ret = readl_poll_timeout(w0 + MSR23_FW_STATE, v, v == 2, 100, 200000); + dev_dbg(m->dev, + "MSR23 S2: start: +0x58/+0x5c %#x %#x (want 1 1), state +0x78 -> %#x: %s\n", a, b, + v, ret ? "NO ANSWER in 200 ms" : "core running (2)"); + if (ret) { + msr23_log_tail(m, "S2"); + return ret; + } + ret = msr23_recv(m, msg, 100000); + if (ret) + dev_warn(m->dev, "MSR23 S2: no hello in the mailbox (i2a %#x)\n", + readl(w5 + MSR23_I2A_CTRL)); + else + dev_dbg(m->dev, + "MSR23 S2: hello %08x %08x %08x %08x (want 00000100 0 0 00100100)\n", + msg[0], msg[1], msg[2], msg[3]); + msr23_log_tail(m, "S2"); + return 0; +} + +/* S3: the init message and the four shared pages. */ +/* The firmware's view of an IOVA: its offset in the 1 << 40 window. */ +static u32 msr23_off(dma_addr_t iova) +{ + return lower_32_bits(iova - MSR23_WIN); +} + +static bool msr23_in_window(dma_addr_t iova, size_t len) +{ + return iova >= MSR23_WIN && iova + len <= MSR23_WIN + MSR23_WIN_SPAN; +} + +/* every plane of a buffer, over its whole mapped length */ +static bool msr23_vb_in_window(struct vb2_buffer *vb) +{ + unsigned int p; + + for (p = 0; p < vb->num_planes; p++) + if (!msr23_in_window(vb2_dma_contig_plane_dma_addr(vb, p), vb2_plane_size(vb, p))) + return false; + return true; +} + +static int msr23_s3(struct msr23 *m) +{ + static const u8 page_id[] = { 0x10, 0x01, 0x02, 0x23 }; + u64 dram = m->w5_phys + MSR23_DRAM; + u32 msg[4], v; + unsigned int i; + int ret; + + m->window = true; + for (i = 0; i < ARRAY_SIZE(page_id); i++) { + if (!m->page[i]) /* a restart after sleep reuses them */ + m->page[i] = dmam_alloc_coherent(m->dev, MSR23_SHMEM_SIZE, &m->page_iova[i], + GFP_KERNEL); + if (!m->page[i]) + return -ENOMEM; + memset(m->page[i], 0, MSR23_SHMEM_SIZE); + if (!msr23_in_window(m->page_iova[i], MSR23_SHMEM_SIZE)) + m->window = false; + } + /* + * Boot 35740333 sent raw IOVAs below 4 GiB (0xffffc000...): the firmware + * took them (STAR) but never touched the pages. The job path needs the + * window (1 << 40 + 0x0/0x8000/0x10000/0x18000 work). + */ + if (!m->window) + dev_warn(m->dev, "MSR23 S3: pages outside the 1 << 40 window (%pad): no job path\n", + &m->page_iova[0]); + msr23_dart(m, "S3 before"); + /* init message 0x00080200 on endpoint 3; the high word is the core RAM's address. */ + msr23_send(m, ((u64)lower_32_bits(dram) << 32) | 0x00080200, 3); + for (i = 0; i < ARRAY_SIZE(page_id); i++) { + u32 off = m->window ? msr23_off(m->page_iova[i]) : lower_32_bits(m->page_iova[i]); + + msr23_send(m, ((u64)off << 32) | 0x40000500 | (page_id[i] << 16), 0x100); + } + for (i = 0; i < 4; i++) { + if (msr23_recv(m, msg, 100000)) + break; + dev_dbg(m->dev, "MSR23 S3: reply %08x %08x %08x %08x\n", msg[0], msg[1], msg[2], + msg[3]); + } + ret = readl_poll_timeout(m->w[5] + MSR23_DRAM_MAGIC, v, + v == MSR23_MAGIC_LIVE || v == MSR23_MAGIC_STAR, 1000, 500000); + dev_dbg(m->dev, "MSR23 S3: pages %pad %pad %pad %pad (window %s); magic %#x: %s\n", + &m->page_iova[0], &m->page_iova[1], &m->page_iova[2], &m->page_iova[3], + m->window ? "yes" : "NO", v, + ret ? "no LIVE/STAR in 500 ms" : v == MSR23_MAGIC_STAR ? "STAR (started)" : "LIVE"); + msr23_log_tail(m, "S3"); + msr23_dart(m, "S3 after"); + m->started = !ret; + return ret; +} + +/* ---- MSR23 jobs ----------------------------------------------------------- */ + +static void msr23_cancel_work(void *data) +{ + struct msr23 *m = data; + + cancel_work_sync(&m->work); +} + +/* + * Chroma subsampling of a MSR23 format (not v4l2_format_info(): it gives P010 + * vdiv 1). 0: no chroma plane (R'G'B' or grey). + */ +static void msr23_sub(u32 v4l2, u32 *hs, u32 *vs) +{ + switch (v4l2) { + case V4L2_PIX_FMT_NV12: + case V4L2_PIX_FMT_NV12M: + case V4L2_PIX_FMT_P010: + *hs = 2; + *vs = 2; + return; + case V4L2_PIX_FMT_NV16: + *hs = 2; + *vs = 1; + return; + case V4L2_PIX_FMT_NV24: + *hs = 1; + *vs = 1; + return; + } + *hs = 0; + *vs = 0; +} + +static void msr23_pic(struct msr23_pic *p, const struct v4l2_pix_format_mplane *f) +{ + u32 hs, vs; + + msr23_sub(f->pixelformat, &hs, &vs); + p->fourcc = f->pixelformat; + p->width = f->width; + p->height = f->height; + p->stride[0] = f->plane_fmt[0].bytesperline; + if (!hs) + p->stride[1] = 0; + else if (f->num_planes > 1) + p->stride[1] = f->plane_fmt[1].bytesperline; + else + p->stride[1] = f->plane_fmt[0].bytesperline * 2 / hs; +} + +static enum v4l2_ycbcr_encoding msr23_enc(const struct v4l2_pix_format_mplane *f) +{ + if (f->ycbcr_enc == V4L2_YCBCR_ENC_601 || f->ycbcr_enc == V4L2_YCBCR_ENC_BT2020) + return f->ycbcr_enc; + return V4L2_YCBCR_ENC_709; +} + +static bool msr23_full(const struct v4l2_pix_format_mplane *f) +{ + return f->quantization == V4L2_QUANTIZATION_FULL_RANGE; +} + +/* + * The job for a context's formats. The Y'CbCr side carries the matrix and the + * range. Y'CbCr to Y'CbCr only scales: a matrix or range change is a + * conversion the engine would do through R'G'B', which the builder does not + * cover. + */ +static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *job) +{ + const struct v4l2_pix_format_mplane *s = &ctx->src, *d = &ctx->dst; + bool ys = v4l2_is_format_yuv(v4l2_format_info(s->pixelformat)); + bool yd = v4l2_is_format_yuv(v4l2_format_info(d->pixelformat)); + const struct v4l2_pix_format_mplane *y = ys ? s : d; + + if (ys && yd && (msr23_enc(s) != msr23_enc(d) || msr23_full(s) != msr23_full(d))) + return -EINVAL; + memset(job, 0, sizeof(*job)); + msr23_pic(&job->src, s); + msr23_pic(&job->dst, d); + job->enc = msr23_enc(y); + job->full = msr23_full(y); + return msr23_check(job); +} + +static dma_addr_t msr23_plane(const struct v4l2_pix_format_mplane *pix, struct vb2_buffer *vb, + unsigned int p) +{ + if (pix->num_planes > 1) + return vb2_dma_contig_plane_dma_addr(vb, p); + return vb2_dma_contig_plane_dma_addr(vb, 0) + + (dma_addr_t)p * pix->plane_fmt[0].bytesperline * pix->height; +} + +static void msr23_ptr(u32 *img, u32 at, u64 a) +{ + img[at / 4] = lower_32_bits(a); + img[at / 4 + 1] = upper_32_bits(a); +} + +static u64 msr23_advance(u64 ptr, u32 n, u32 size) +{ + u64 idx = (ptr & 0x7fffffff) + n; + + if (idx >= size) { + idx -= size; + ptr ^= BIT_ULL(31); + } + return (ptr & BIT_ULL(31)) | idx; +} + +/* One job, synchronous: build it at our IOVAs, submit, wait for its status entry. */ +static int msr23_run(struct msr23 *m, struct apple_scaler_ctx *ctx, struct vb2_buffer *src, + struct vb2_buffer *dst) +{ + void __iomem *w4 = m->w[4], *w5 = m->w[5]; + u32 *ring = m->page[2], *img, st[MSR23_STS_ENTRY], rec[4 + 2 * MSR23_NBLOCKS]; + char id[40]; + struct msr23_job job; + struct msr23_built out; + dma_addr_t img_iova, spill_iova; + void *spill = NULL; + size_t spill_len = 0; + u32 k, seq, err0, idx, nwords; + u64 wptr, sts; + int ret; + + snprintf(id, sizeof(id), "%.4s %ux%u -> %.4s %ux%u", (char *)&ctx->src.pixelformat, + ctx->src.width, ctx->src.height, (char *)&ctx->dst.pixelformat, ctx->dst.width, + ctx->dst.height); + ret = msr23_job_of(ctx, &job); + if (ret) { + dev_warn_ratelimited(m->dev, "MSR23 job %s: not supported\n", id); + return ret; + } + /* zeroed: the builder writes only the words a job sets */ + img = dma_alloc_coherent(m->dev, MSR23_IMG_LEN, &img_iova, GFP_KERNEL); + if (!img) + return -ENOMEM; + ret = msr23_build(&job, img, &out); + if (ret) + goto out; + spill_len = (size_t)(out.nc0 + out.nc1) * MSR23_NC_PAGE; + spill = dma_alloc_coherent(m->dev, spill_len, &spill_iova, GFP_KERNEL); + ret = -ENOMEM; + if (!spill) + goto out; + ret = -ERANGE; + if (!msr23_in_window(img_iova, MSR23_IMG_LEN) || + !msr23_in_window(spill_iova, spill_len) || + !msr23_vb_in_window(src) || !msr23_vb_in_window(dst)) { + dev_err_ratelimited(m->dev, "MSR23 job: a buffer is outside the 1 << 40 window\n"); + goto out; + } + + /* NC0 at the start of the spill buffer, NC1 after it */ + msr23_ptr(img, MSR23_PTR_NC0, spill_iova); + msr23_ptr(img, MSR23_PTR_NC1, spill_iova + (dma_addr_t)out.nc0 * MSR23_NC_PAGE); + for (k = 0; k < out.planes[0]; k++) + msr23_ptr(img, MSR23_PTR_SRC(k), msr23_plane(&ctx->src, src, k)); + for (k = 0; k < out.planes[1]; k++) + msr23_ptr(img, MSR23_PTR_DST(k), msr23_plane(&ctx->dst, dst, k)); + /* + * Block 0 +0x60 is the frame id too: it must equal the record's word 1 + * (the tiler refuses a job where they differ). + */ + seq = ++m->seq & 0xffffff; + img[MSR23_FRAME_ID / 4] = seq << 8 | 2; + + /* The record: header, then the block list. */ + rec[0] = MAGIC_FDBE; + rec[1] = seq << 8 | 2; + rec[2] = MSR23_HDR2_FW_TILING; + rec[3] = (2 * MSR23_NBLOCKS) << 16; + for (k = 0; k < MSR23_NBLOCKS; k++) { + u32 off = msr23_off(img_iova + msr23_blocks[k].off); + + rec[4 + 2 * k] = (off >> 7) << 8 | msr23_blocks[k].id; + rec[5 + 2 * k] = msr23_blocks[k].size; + } + nwords = ARRAY_SIZE(rec); + wptr = m->ring_wptr; + idx = wptr & 0x7fffffff; + for (k = 0; k < nwords; k++) + ring[(idx + k) % MSR23_RING_WORDS] = rec[k]; + + err0 = m->dart ? readl(m->dart + 0x100) : 0; + dma_wmb(); + m->ring_wptr = msr23_advance(wptr, nwords, MSR23_RING_WORDS); + writeq(ktime_get_ns() & 0xffffffff, w4 + MSR23_Q_STAMP); + writeq(m->ring_wptr, w4 + MSR23_Q_SUBMIT); + /* around each submission: interrupt acknowledge/unmask */ + writel(0x80000000, w5 + 0x100170); + writel(1, w5 + 0x100178); + writel(0x80000000, w5 + 0x100178); + + ret = readq_poll_timeout(w4 + MSR23_Q_STS_WRITE, sts, sts != m->sts_rptr, 200, + MSR23_JOB_TIMEOUT_US); + if (ret) { + dev_err(m->dev, + "MSR23 job %s seq %u: no status in 1 s (submit %#llx, firmware took %#llx, status %#llx/%#llx, dart error %#x, magic %#x)\n", + id, seq, m->ring_wptr, readq(w4 + MSR23_Q_SUB_DONE), + readq(w4 + MSR23_Q_STS_WRITE), m->sts_rptr, + m->dart ? readl(m->dart + 0x100) : 0, readl(w5 + MSR23_DRAM_MAGIC)); + msr23_log_tail(m, "job"); + /* + * The firmware may still be working on this job and DMA into its buffers later: + * keep them (leak them) and take the core out of service, so no further job reaches + * it until a resume restarts it. + */ + m->started = false; + img = NULL; + spill = NULL; + dev_err(m->dev, + "MSR23: job timed out; core out of service, job buffers kept (leaked) until reboot\n"); + goto out; + } + for (k = 0; k < MSR23_STS_ENTRY; k++) + st[k] = readl(w5 + MSR23_STS_BASE + + 4 * (((m->sts_rptr & 0x7fffffff) + k) % MSR23_STS_WORDS)); + m->sts_rptr = msr23_advance(m->sts_rptr, MSR23_STS_ENTRY, MSR23_STS_WORDS); + writeq(m->sts_rptr, w4 + MSR23_Q_STS_READ); + if (m->dart && readl(m->dart + 0x100) != err0) { + dev_err(m->dev, "MSR23 job %s: DART error %#x\n", id, readl(m->dart + 0x100)); + ret = -EIO; + } else if ((st[1] & 0xffffff00) != (seq << 8)) { + /* + * The firmware is out of step: after a job it aborted, every later + * status entry was the previous one or zeros and the outputs were + * untouched. It may still own this job's buffers: keep them, as on a + * timeout, and take the core out of service rather than return + * empty frames as done. + */ + dev_err(m->dev, + "MSR23 job %s: status entry %08x %08x %08x %08x is not for seq %u; core out of service\n", + id, st[0], st[1], st[2], st[3], seq); + msr23_log_tail(m, "job"); + m->started = false; + img = NULL; + spill = NULL; + ret = -EIO; + } else if (st[0] != MSR23_STS_OK0 || st[2] != MSR23_STS_OK2) { + /* + * Every completed job ends 00140007 00000200. A job the + * engine aborted ended 0015000f 00001201, and the firmware + * wrote no status entry after it. + */ + dev_err(m->dev, + "MSR23 job %s seq %u: error status %08x %08x %08x %08x; core out of service\n", + id, seq, st[0], st[1], st[2], st[3]); + msr23_log_tail(m, "job"); + m->started = false; + ret = -EIO; + } else { + dev_dbg(m->dev, "MSR23 job %s seq %u done (NC %u + %u pages)\n", id, seq, + out.nc0, out.nc1); + } +out: + if (spill) + dma_free_coherent(m->dev, spill_len, spill, spill_iova); + if (img) + dma_free_coherent(m->dev, MSR23_IMG_LEN, img, img_iova); + return ret; +} + +static void msr23_work(struct work_struct *work) +{ + struct msr23 *m = container_of(work, struct msr23, work); + struct apple_scaler_ctx *ctx = m->ctx; + struct vb2_v4l2_buffer *src, *dst; + int ret; + + src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); + dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); + if (!m->started) + ret = -EIO; /* the core did not come back (resume): fail, never touch it */ + else + ret = src && dst ? msr23_run(m, ctx, &src->vb2_buf, &dst->vb2_buf) : -EINVAL; + m->ctx = NULL; + asc_finish(m->asc, ctx, ret); +} + +/* After system sleep: start the core again from what the SRAM holds (never an upload here). */ +static void msr23_restart(struct msr23 *m) +{ + u32 vec[2]; + + memcpy_fromio(vec, m->w[5], sizeof(vec)); + if (!msr23_text_valid(vec)) { + dev_warn(m->dev, + "MSR23: resumed with no image in the SRAM (SP %#x): the core stays down\n", + vec[0]); + m->started = false; + return; + } + if (msr23_s2(m) || msr23_s3(m)) { + dev_warn(m->dev, "MSR23: restart after resume failed\n"); + m->started = false; + return; + } + m->ring_wptr = readq(m->w[4] + MSR23_Q_SUBMIT); + m->sts_rptr = readq(m->w[4] + MSR23_Q_STS_READ); + m->seq = 0; + dev_dbg(m->dev, "MSR23: restarted after resume (submit %#llx, status %#llx)\n", + m->ring_wptr, m->sts_rptr); +} + +static void msr23_device_run(struct apple_scaler *asc, struct apple_scaler_ctx *ctx) +{ + /* asc_finish() drops one runtime-PM reference per job. */ + pm_runtime_get_noresume(asc->dev); + asc->msr->ctx = ctx; + queue_work(system_dfl_wq, &asc->msr->work); +} + +static void msr23_put(void *data) +{ + pm_runtime_put_sync_suspend(data); +} + +static int asc_register_video(struct apple_scaler *asc); + +static int asc_v23_probe(struct apple_scaler *asc, struct platform_device *pdev) +{ + struct device *dev = asc->dev; + const struct firmware *fw = NULL; + struct msr23 *m; + unsigned int i; + int ret, have; + + m = devm_kzalloc(dev, sizeof(*m), GFP_KERNEL); + if (!m) + return -ENOMEM; + m->dev = dev; + m->asc = asc; + asc->msr = m; + INIT_WORK(&m->work, msr23_work); + ret = devm_add_action_or_reset(dev, msr23_cancel_work, m); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(m->w); i++) { + struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, i); + + if (!res) + return dev_err_probe(dev, -EINVAL, "MSR23: no reg[%u]\n", i); + /* reg[1] and reg[8] are the same window: map without claiming. */ + m->w[i] = devm_ioremap(dev, res->start, resource_size(res)); + if (!m->w[i]) + return -ENOMEM; + if (i == 5) + m->w5_phys = res->start; + } + { + struct device_node *dn = of_parse_phandle(dev->of_node, "iommus", 0); + struct resource dr; + + if (dn && !of_address_to_resource(dn, 0, &dr)) + m->dart = devm_ioremap(dev, dr.start, 0x2000); + of_node_put(dn); + } + /* + * Every address a job holds is an offset in the DART window at 1 << 40 + * (dart +0x308 = 0x10000000), and block words keep offset >> 7 in 24 + * bits: top-down IOVA allocation below this limit lands in + * [1 << 40, 1 << 40 + 2 GiB). + */ + ret = dma_set_mask_and_coherent(dev, MSR23_WIN + MSR23_WIN_SPAN - 1); + if (ret) + return ret; + ret = devm_pm_runtime_enable(dev); + if (ret) + return ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return dev_err_probe(dev, ret, "MSR23: failed to power up\n"); + + if (firmware_request_nowarn(&fw, m->asc->variant->fw_name, dev)) + fw = NULL; + dev_dbg(dev, "MSR23: version %#x, %s %s\n", readl(m->w[0]), m->asc->variant->fw_name, + fw ? "loaded" : "not found"); + + msr23_dart(m, "S0"); + have = msr23_s0(m, fw); + if (have < 0) { + ret = have; + goto out_put; + } + if (!have) { + u32 state = readl(m->w[0] + MSR23_FW_STATE); + u32 magic = readl(m->w[5] + MSR23_DRAM_MAGIC); + + /* + * Never write the SRAM under a core that has run since power-up: + * an upload after a module reload (state 2, magic "ABRT") hung + * the machine. Only a cold core (state 0, no magic) can take an + * image. + */ + if (state || magic) { + dev_warn(dev, + "MSR23: the core has run (state %#x magic %#x), not uploading; starting what the SRAM holds\n", + state, magic); + goto start; + } + if (!fw) { + dev_err(dev, "MSR23: the SRAM holds no image and %s is missing\n", + m->asc->variant->fw_name); + ret = -ENOENT; + goto out_put; + } + ret = msr23_s1(m, fw); + if (ret) + goto out_put; + } + +start: + ret = msr23_s2(m); + if (ret) + goto out_put; + ret = msr23_s3(m); + if (ret) + dev_warn(dev, "MSR23: init incomplete (%d)\n", ret); + release_firmware(fw); + /* Keep the runtime-PM reference while bound (SRAM and core stay up); drop it on unbind. */ + ret = devm_add_action_or_reset(dev, msr23_put, dev); + if (ret) + return ret; + if (!m->started || !m->window) { + dev_warn(dev, + "MSR23: firmware core up but not ready (started %d, window %d): no job path\n", + m->started, m->window); + return 0; + } + m->ring_wptr = readq(m->w[4] + MSR23_Q_SUBMIT); + m->sts_rptr = readq(m->w[4] + MSR23_Q_STS_READ); + dev_dbg(dev, + "MSR23 queues: submit %#llx (firmware took %#llx), status read %#llx (firmware wrote %#llx)\n", + m->ring_wptr, readq(m->w[4] + MSR23_Q_SUB_DONE), m->sts_rptr, + readq(m->w[4] + MSR23_Q_STS_WRITE)); + ret = asc_register_video(asc); + if (ret) + return ret; + dev_info(dev, "MSR23: job path up: %s\n", video_device_node_name(&asc->vdev)); + return 0; + +out_put: + release_firmware(fw); + pm_runtime_put_sync_suspend(dev); + return ret; +} + static void asc_cleanup(void *data) { struct apple_scaler *asc = data; cancel_delayed_work_sync(&asc->watchdog); + /* + * devres unwinds in reverse: this runs before msr23_put() powers the + * core down and before msr23_cancel_work(). A job still queued or + * running would touch the m2m device and the registers after them. + */ + if (asc->msr) + cancel_work_sync(&asc->msr->work); if (asc->m2m_dev) v4l2_m2m_release(asc->m2m_dev); v4l2_device_unregister(&asc->v4l2_dev); } +static int asc_register_video(struct apple_scaler *asc) +{ + struct device *dev = asc->dev; + struct video_device *vdev; + int ret; + + ret = v4l2_device_register(dev, &asc->v4l2_dev); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, asc_cleanup, asc); + if (ret) + return ret; + asc->m2m_dev = v4l2_m2m_init(&asc_m2m_ops); + if (IS_ERR(asc->m2m_dev)) { + ret = PTR_ERR(asc->m2m_dev); + asc->m2m_dev = NULL; + return ret; + } + + vdev = &asc->vdev; + strscpy(vdev->name, ASC_NAME, sizeof(vdev->name)); + vdev->fops = &asc_fops; + vdev->ioctl_ops = &asc_ioctl_ops; + vdev->release = video_device_release_empty; + vdev->lock = &asc->lock; + vdev->v4l2_dev = &asc->v4l2_dev; + vdev->vfl_dir = VFL_DIR_M2M; + vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + video_set_drvdata(vdev, asc); + return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); +} + static int asc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct apple_scaler *asc; - struct video_device *vdev; struct resource *res; int ret; @@ -789,6 +1826,8 @@ static int asc_probe(struct platform_device *pdev) if (!platform_get_resource(pdev, IORESOURCE_MEM, asc->variant->num_reg - 1)) return dev_err_probe(dev, -EINVAL, "expected %u register ranges\n", asc->variant->num_reg); + if (asc->variant->fw_fronted) + return asc_v23_probe(asc, pdev); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (resource_size(res) < ASC_MIN_REG_SIZE) return dev_err_probe(dev, -EINVAL, "MSR aperture too small\n"); @@ -823,30 +1862,7 @@ static int asc_probe(struct platform_device *pdev) if (ret) return ret; - ret = v4l2_device_register(dev, &asc->v4l2_dev); - if (ret) - return ret; - ret = devm_add_action_or_reset(dev, asc_cleanup, asc); - if (ret) - return ret; - asc->m2m_dev = v4l2_m2m_init(&asc_m2m_ops); - if (IS_ERR(asc->m2m_dev)) { - ret = PTR_ERR(asc->m2m_dev); - asc->m2m_dev = NULL; - return ret; - } - - vdev = &asc->vdev; - strscpy(vdev->name, ASC_NAME, sizeof(vdev->name)); - vdev->fops = &asc_fops; - vdev->ioctl_ops = &asc_ioctl_ops; - vdev->release = video_device_release_empty; - vdev->lock = &asc->lock; - vdev->v4l2_dev = &asc->v4l2_dev; - vdev->vfl_dir = VFL_DIR_M2M; - vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; - video_set_drvdata(vdev, asc); - return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + return asc_register_video(asc); } static void asc_remove(struct platform_device *pdev) @@ -891,6 +1907,17 @@ static const struct apple_scaler_variant apple_scaler_t8140 = { .msr20 = true, }; +/* M5: MSR23, firmware-fronted: the driver builds each job and queues it to the firmware. */ +static const struct apple_scaler_variant apple_scaler_t8142 = { + .hw_version = 23, + .num_reg = 10, + .msr20 = true, + .fw_fronted = true, + .fw_name = "apple/msr-t8142.bin", + .powerup = msr23_t8142_powerup, + .num_powerup = ARRAY_SIZE(msr23_t8142_powerup), +}; + static const struct of_device_id asc_of_match[] = { { .compatible = "apple,t8103-scaler", .data = &apple_scaler_t8103 }, { .compatible = "apple,t6000-scaler", .data = &apple_scaler_t6000 }, @@ -898,6 +1925,7 @@ static const struct of_device_id asc_of_match[] = { { .compatible = "apple,t8132-scaler", .data = &apple_scaler_t8132 }, { .compatible = "apple,t6041-scaler", .data = &apple_scaler_t6041 }, { .compatible = "apple,t8140-scaler", .data = &apple_scaler_t8140 }, + { .compatible = "apple,t8142-scaler", .data = &apple_scaler_t8142 }, { } }; MODULE_DEVICE_TABLE(of, asc_of_match); @@ -915,3 +1943,4 @@ module_platform_driver(asc_driver); MODULE_DESCRIPTION("Apple silicon scaler and colour-space converter"); MODULE_LICENSE("GPL"); +MODULE_FIRMWARE("apple/msr-t8142.bin"); diff --git a/drivers/media/platform/apple/scaler/apple-scaler-hw.c b/drivers/media/platform/apple/scaler/apple-scaler-hw.c index bc766c47e19481..7730716b81d0f5 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-hw.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-hw.c @@ -52,6 +52,32 @@ static const struct asc_format asc_formats[] = { .fourcc = V4L2_PIX_FMT_P010, .layout = 0xc, .code = 0x2, .sampling = 0x12, .swizzle = ASC_SWIZZLE_CBCR, .planes = 2, .bpp = { 2, 4 }, .hsub = 2, .vsub = 2, .yuv = true, .wide = true, + }, { + /* + * Bytes B, G, R, A with the alpha carried through (V4L2 ABGR32). + * MSR23 (M5) only: its jobs write the source's alpha byte to a + * BGRA output (J815 outputs matched the reference byte for byte, + * alpha included). How the earlier engines treat alpha is not + * checked, so they offer only ARGB32 and XRGB32. + */ + .fourcc = V4L2_PIX_FMT_ABGR32, .layout = 0x1, .code = 0x1e, + .sampling = 0x0, .swizzle = ASC_SWIZZLE_IDENTITY, .planes = 1, + .bpp = { 4 }, .hsub = 1, .vsub = 1, .alpha = true, .msr23_only = true, + }, { + /* + * MSR23 only. .code is the MSR23 plane code; MSR23 uses neither + * sampling nor swizzle, and .layout only keeps the table's rule + * (0x1 for one plane of R'G'B' or grey, 0xc for two planes). + */ + .fourcc = V4L2_PIX_FMT_NV16, .layout = 0xc, .code = 0x1, .planes = 2, + .bpp = { 1, 2 }, .hsub = 2, .vsub = 1, .yuv = true, .msr23_only = true, + }, { + .fourcc = V4L2_PIX_FMT_NV24, .layout = 0xc, .code = 0x1, .planes = 2, + .bpp = { 1, 2 }, .hsub = 1, .vsub = 1, .yuv = true, .msr23_only = true, + }, { + /* One 8-bit component, no colorimetry: GREY to GREY only. */ + .fourcc = V4L2_PIX_FMT_GREY, .layout = 0x1, .code = 0x1, .planes = 1, + .bpp = { 1 }, .hsub = 1, .vsub = 1, .msr23_only = true, }, { /* The AVE temporal filter's picture form; one buffer, four regions. */ .fourcc = V4L2_PIX_FMT_APPLE_L8V0, .layout = 0xc, .code = 0x78, diff --git a/drivers/media/platform/apple/scaler/apple-scaler-hw.h b/drivers/media/platform/apple/scaler/apple-scaler-hw.h index 46410b78eae4fc..b1106ca1dcf0ca 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-hw.h +++ b/drivers/media/platform/apple/scaler/apple-scaler-hw.h @@ -58,6 +58,7 @@ struct asc_csc { * @alpha: carries an alpha channel * @wide: samples are 16 bits in memory (more than 8 significant bits) * @lossless: Apple lossless compressed 4:2:0 in one buffer (asc_lossless_geom()) + * @msr23_only: offered only by the firmware-fronted MSR23 engine */ struct asc_format { u32 fourcc; @@ -73,6 +74,7 @@ struct asc_format { bool alpha; bool wide; bool lossless; + bool msr23_only; }; /** diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.c b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c new file mode 100644 index 00000000000000..67a992b0fd5d1f --- /dev/null +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c @@ -0,0 +1,598 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Apple silicon scaler (MSR23, M5): job builder. + * + * The engine's firmware streams a register image into the hardware for each + * job: one block per register group (pipe, source and destination DMA, + * chroma resampling, colour matrix, scaler, dither). This builds that image + * from the job's parameters: the words that depend on the sizes, formats and + * matrix are computed, the others hold the fixed values below. + * + * The firmware tiles the job itself, so no tile array is built. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" + +/* + * The blocks of every job, in list order. Blocks 0, 1 and 14 hold the pipe, + * the source and the destination. + */ +const struct msr23_block msr23_blocks[MSR23_NBLOCKS] = { + { 0, MSR23_B0, 0x00c00200 }, { 1, MSR23_B1, 0x00c00200 }, { 3, 0x1e00, 0x00400200 }, + { 4, 0x1e80, 0x31c00200 }, { 5, 0x8200, 0x00400200 }, { 8, 0x9080, 0x03c00200 }, + { 11, 0xa600, 0x23c00200 }, { 12, 0xed80, 0x01400200 }, { 13, 0xf000, 0x09000200 }, + { 14, MSR23_B14, 0x00c00200 }, +}; +EXPORT_SYMBOL_IF_KUNIT(msr23_blocks); + +#define MSR23_B3 0x1e00 +#define MSR23_B8 0x9080 +#define MSR23_B11 0xa600 +#define MSR23_B12 0xed80 + +struct msr23_default { + u8 block; + u16 off; + u32 val; +}; + +#define MSR23_FILTER_BINS 8 +#define MSR23_FILTER_TAPS 144 + +struct msr23_filter { + u32 ratio; + s16 extra; + s16 taps[MSR23_FILTER_TAPS]; +}; + +/* + * Register defaults: words every firmware-tiled job carries with the same + * value (block, offset, value). + */ +static const struct msr23_default msr23_defaults[] = { + { 1, 0x84, 0x7d35d }, { 1, 0x88, 0x7d35d }, { 1, 0x8c, 0x7d35d }, { 1, 0x90, 0x7d35d }, + { 1, 0x94, 0x708 }, { 1, 0x98, 0x708 }, { 1, 0x9c, 0x708 }, { 1, 0xa0, 0x708 }, + { 1, 0xa4, 0x20 }, { 1, 0xa8, 0x20 }, { 1, 0xac, 0x20 }, { 1, 0xb0, 0x20 }, + { 1, 0xd4, 0x1 }, { 1, 0xe4, 0xffffffff }, { 1, 0x10c, 0x12345678 }, { 14, 0xc, 0x8000 }, + { 14, 0x64, 0xac25d }, { 14, 0x68, 0xac25d }, { 14, 0x6c, 0xac25d }, + { 14, 0x70, 0xc0ac208 }, { 14, 0x74, 0xc0ac208 }, { 14, 0x78, 0xc0ac208 }, + { 14, 0x7c, 0x4000600 }, { 14, 0x80, 0x4000600 }, { 14, 0x84, 0x4000600 }, + { 14, 0xe4, 0x4048 }, { 14, 0xe8, 0x4048 }, { 14, 0xec, 0x4048 }, { 14, 0xf0, 0x4048 }, + { 14, 0xf4, 0x4048 }, { 14, 0xf8, 0x4048 }, { 14, 0xfc, 0x4048 }, { 14, 0x100, 0x4048 }, + { 14, 0x104, 0x4048 }, { 14, 0x108, 0x4048 }, { 14, 0x10c, 0x4048 }, { 14, 0x110, 0x4048 }, + { 14, 0x114, 0x12402046 }, { 14, 0x118, 0x2000 }, { 14, 0x168, 0x12345678 }, + { 3, 0x24, 0xc }, { 3, 0x64, 0x12345678 }, { 4, 0x6300, 0x2804008 }, + { 4, 0x6304, 0xa0a0a0a0 }, { 4, 0x6308, 0x2550000 }, { 4, 0x630c, 0x2550255 }, + { 4, 0x6314, 0x100008 }, { 4, 0x6318, 0x2550000 }, { 5, 0x20, 0xff }, { 11, 0x0, 0xe0000 }, + { 11, 0x4, 0xc }, { 11, 0x50, 0x44000 }, { 11, 0x54, 0x44000 }, { 11, 0x58, 0x44000 }, + { 11, 0x68, 0x12345678 }, { 11, 0x6c, 0xc }, { 11, 0xac, 0xc }, { 11, 0xec, 0x3d0 }, + { 11, 0xf0, 0x6186318 }, { 11, 0xf4, 0x18 }, { 11, 0x134, 0xc30c00 }, + { 11, 0x138, 0xffffffff }, { 11, 0x13c, 0x80000001 }, { 11, 0x140, 0x80000001 }, + { 11, 0x144, 0x80000001 }, { 11, 0x148, 0x7fffffff }, { 11, 0x14c, 0x7fffffff }, + { 11, 0x150, 0x7fffffff }, { 11, 0x154, 0x80000001 }, { 11, 0x158, 0x80000001 }, + { 11, 0x15c, 0x80000001 }, { 11, 0x160, 0x7fffffff }, { 11, 0x164, 0x7fffffff }, + { 11, 0x168, 0x7fffffff }, { 11, 0x16c, 0xffffffff }, { 11, 0x170, 0xffffffff }, + { 11, 0x174, 0xffffffff }, { 11, 0x178, 0xffffffff }, { 11, 0x17c, 0xffffffff }, + { 11, 0x180, 0xffffffff }, { 11, 0x184, 0x80000001 }, { 11, 0x188, 0x80000001 }, + { 11, 0x18c, 0x80000001 }, { 11, 0x190, 0x7fffffff }, { 11, 0x194, 0x7fffffff }, + { 11, 0x198, 0x7fffffff }, { 11, 0x19c, 0x80000001 }, { 11, 0x1a0, 0x80000001 }, + { 11, 0x1a4, 0x80000001 }, { 11, 0x1a8, 0x7fffffff }, { 11, 0x1ac, 0x7fffffff }, + { 11, 0x1b0, 0x7fffffff }, { 11, 0x1b4, 0x80000001 }, { 11, 0x1b8, 0x80000001 }, + { 11, 0x1bc, 0x80000001 }, { 11, 0x1c0, 0x7fffffff }, { 11, 0x1c4, 0x7fffffff }, + { 11, 0x1c8, 0x7fffffff }, { 11, 0x1cc, 0x183c }, { 11, 0x1fc, 0x1 }, { 11, 0x200, 0xc }, + { 11, 0x240, 0xc }, { 11, 0x280, 0xc }, { 11, 0x2c0, 0x80000001 }, + { 11, 0x2c4, 0x80000001 }, { 11, 0x2c8, 0x80000001 }, { 11, 0x2cc, 0x7fffffff }, + { 11, 0x2d0, 0x7fffffff }, { 11, 0x2d4, 0x7fffffff }, { 11, 0x2d8, 0x80000001 }, + { 11, 0x2dc, 0x80000001 }, { 11, 0x2e0, 0x80000001 }, { 11, 0x2e4, 0x7fffffff }, + { 11, 0x2e8, 0x7fffffff }, { 11, 0x2ec, 0x7fffffff }, { 11, 0x2f0, 0x80000001 }, + { 11, 0x2f4, 0x80000001 }, { 11, 0x2f8, 0x80000001 }, { 11, 0x2fc, 0x7fffffff }, + { 11, 0x300, 0x7fffffff }, { 11, 0x304, 0x7fffffff }, { 11, 0x308, 0x80000001 }, + { 11, 0x30c, 0x80000001 }, { 11, 0x310, 0x80000001 }, { 11, 0x314, 0x7fffffff }, + { 11, 0x318, 0x7fffffff }, { 11, 0x31c, 0x7fffffff }, { 11, 0x320, 0x80000001 }, + { 11, 0x324, 0x80000001 }, { 11, 0x328, 0x80000001 }, { 11, 0x32c, 0x7fffffff }, + { 11, 0x330, 0x7fffffff }, { 11, 0x334, 0x7fffffff }, { 11, 0x338, 0x80000001 }, + { 11, 0x33c, 0x80000001 }, { 11, 0x340, 0x80000001 }, { 11, 0x344, 0x7fffffff }, + { 11, 0x348, 0x7fffffff }, { 11, 0x34c, 0x7fffffff }, { 11, 0x37c, 0x1 }, + { 11, 0x2e80, 0x40000000 }, { 12, 0x4, 0x1 }, { 12, 0x120, 0x12345678 }, + { 12, 0x184, 0xffff }, { 12, 0x188, 0xffff }, { 12, 0x18c, 0xffff }, { 12, 0x190, 0xffff }, + { 12, 0x194, 0xffff }, { 12, 0x198, 0xffff }, { 12, 0x19c, 0xffff }, { 12, 0x1a0, 0xffff }, + { 12, 0x1a4, 0xffff }, { 12, 0x1a8, 0xffff }, { 12, 0x1ac, 0xffff }, { 12, 0x1b0, 0xffff }, + { 12, 0x1b4, 0xffff }, { 12, 0x1b8, 0xffff }, { 12, 0x1bc, 0xffff }, { 12, 0x1c0, 0xffff }, + { 12, 0x1c4, 0xffff }, { 12, 0x1c8, 0xffff }, { 12, 0x1cc, 0xffff }, { 12, 0x1d0, 0xffff }, + { 12, 0x1d4, 0xffff }, { 12, 0x1d8, 0xffff }, { 12, 0x1dc, 0xffff }, { 12, 0x1e0, 0xffff }, + { 12, 0x1e4, 0xffff }, { 12, 0x1e8, 0xffff }, { 12, 0x1ec, 0xffff }, { 12, 0x1f0, 0xffff }, + { 12, 0x1f4, 0xffff }, { 12, 0x1f8, 0xffff }, { 12, 0x1fc, 0xffff }, + { 12, 0x240, 0xfff00000 }, { 12, 0x244, 0xfff00000 }, { 13, 0x80, 0x18e0 }, + { 13, 0xc4, 0x80000001 }, { 13, 0xc8, 0x80000001 }, { 13, 0xcc, 0x80000001 }, + { 13, 0xd0, 0x7fffffff }, { 13, 0xd4, 0x7fffffff }, { 13, 0xd8, 0x7fffffff }, + { 13, 0xdc, 0x80000001 }, { 13, 0xe0, 0x80000001 }, { 13, 0xe4, 0x80000001 }, + { 13, 0xe8, 0x7fffffff }, { 13, 0xec, 0x7fffffff }, { 13, 0xf0, 0x7fffffff }, +}; + +/* + * The scaler's polyphase filters, one set per ratio bin (src/dst in Q19; a + * step uses the first bin whose ratio is at least the step). Each set is a + * symmetric kernel sampled at 9 source pixels around the output position, + * 32 phases per pixel, in Q12 (4096 = 1.0), every phase summing to 4096: + * + * - downscaling (ratio s > 1): sinc(x / s), a low-pass at the output's + * Nyquist frequency, under a Kaiser window of radius 3.5 s, beta 6.5; + * - upscaling (steps below 1): an interpolating 4-tap kernel, sinc(x) under + * a Kaiser window of radius 31/16, beta 5; + * - 1:1: the source passes through (centre tap 1.0, extra word 1.0). + * + * Phases 1-15 are stored as they are (index tap * 16 + phase); 17-31 are + * their mirror images. Column 0 holds two phases: taps 4-8 are phase 0, taps + * 0-3 are taps 1-4 of phase 16 (half a pixel), and .extra is that phase's + * tap 0. + * + * Generated by tools/media/apple-scaler/msr23_filters.py, which documents + * the design; regenerate rather than edit. + */ +static const struct msr23_filter msr23_filters[MSR23_FILTER_BINS] = { + { .ratio = 0x7ffff, .extra = 0, .taps = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, -177, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 2225, -63, -116, -160, -196, -223, -242, -255, -261, -262, -259, -251, + -240, -227, -211, -194, 4096, 4086, 4056, 4015, 3953, 3873, 3776, 3665, + 3540, 3402, 3256, 3098, 2933, 2762, 2586, 2406, 0, 73, 156, 250, + 353, 467, 591, 724, 866, 1017, 1174, 1339, 1509, 1684, 1862, 2043, + 0, 0, 0, -9, -14, -21, -29, -38, -49, -61, -75, -90, + -106, -123, -141, -159, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + } }, + { .ratio = 0x80000, .extra = 4096, .taps = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, + 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + } }, + { .ratio = 0x92492, .extra = 0, .taps = { + -4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 79, 50, 45, 40, 35, 30, 25, 21, + 17, 13, 10, 7, 4, 2, -1, -2, -468, -181, -156, -130, + -106, -83, -61, -40, -20, -2, 14, 29, 42, 54, 64, 72, + 2442, 312, 217, 128, 45, -32, -103, -167, -225, -276, -321, -360, + -393, -420, -441, -457, 3578, 3575, 3560, 3535, 3500, 3457, 3404, 3341, + 3268, 3189, 3101, 3006, 2905, 2796, 2682, 2564, 412, 518, 629, 745, + 865, 989, 1116, 1246, 1379, 1512, 1647, 1782, 1917, 2051, 2184, 2313, + -208, -235, -261, -288, -314, -339, -363, -386, -407, -426, -442, -456, + -466, -473, -475, -474, 55, 61, 66, 71, 76, 80, 84, 88, + 91, 93, 94, 95, 94, 92, 89, 85, 0, -4, -4, -5, + -5, -6, -6, -7, -7, -7, -7, -7, -7, -6, -6, -5, + } }, + { .ratio = 0xaaaaa, .extra = -5, .taps = { + 47, -1, -3, -4, -4, -5, -5, -6, -6, -6, -6, -6, + -6, -6, -5, -5, -79, 79, 80, 81, 81, 80, 79, 77, + 75, 72, 69, 66, 63, 59, 55, 51, -242, -354, -339, -323, + -306, -288, -269, -250, -231, -211, -191, -172, -152, -133, -115, -97, + 2325, 712, 625, 540, 458, 379, 304, 232, 164, 99, 38, -18, + -71, -120, -165, -205, 3072, 3068, 3059, 3044, 3019, 2991, 2956, 2917, + 2870, 2819, 2762, 2700, 2632, 2562, 2487, 2408, 802, 895, 989, 1084, + 1182, 1280, 1378, 1478, 1577, 1675, 1773, 1870, 1965, 2059, 2150, 2239, + -367, -379, -389, -397, -403, -406, -407, -406, -401, -393, -382, -368, + -350, -329, -304, -275, 77, 74, 71, 66, 61, 55, 47, 39, + 30, 19, 8, -4, -17, -32, -47, -63, 0, 2, 3, 5, + 8, 10, 13, 15, 18, 22, 25, 28, 32, 36, 40, 43, + } }, + { .ratio = 0xccccc, .extra = 15, .taps = { + 57, 54, 51, 49, 46, 43, 41, 38, 35, 32, 30, 27, + 25, 22, 20, 18, -274, -54, -43, -32, -22, -13, -3, 5, + 13, 21, 27, 34, 39, 45, 49, 53, 137, -320, -327, -333, + -336, -338, -339, -338, -335, -332, -326, -320, -313, -304, -295, -285, + 2120, 1023, 956, 889, 822, 757, 693, 630, 568, 508, 450, 393, + 338, 284, 233, 184, 2552, 2552, 2546, 2536, 2525, 2509, 2489, 2467, + 2441, 2412, 2379, 2341, 2304, 2263, 2218, 2171, 1092, 1160, 1229, 1298, + 1367, 1435, 1503, 1571, 1637, 1703, 1767, 1831, 1892, 1952, 2011, 2067, + -310, -299, -286, -270, -253, -233, -211, -187, -160, -131, -100, -66, + -30, 8, 48, 91, -66, -78, -90, -103, -116, -129, -143, -157, + -170, -184, -198, -211, -225, -238, -250, -263, 56, 58, 60, 62, + 63, 65, 66, 67, 67, 67, 67, 67, 66, 64, 62, 60, + } }, + { .ratio = 0x100000, .extra = 53, .taps = { + -121, 6, 11, 16, 20, 25, 29, 32, 36, 39, 42, 44, + 46, 48, 50, 51, -254, -244, -238, -231, -224, -216, -208, -200, + -192, -183, -175, -166, -157, -148, -139, -130, 545, -25, -49, -71, + -92, -112, -131, -149, -165, -180, -194, -207, -219, -229, -238, -247, + 1852, 1208, 1164, 1119, 1074, 1029, 984, 939, 894, 849, 804, 760, + 716, 673, 630, 587, 2092, 2090, 2088, 2082, 2077, 2067, 2055, 2044, + 2029, 2012, 1996, 1975, 1956, 1931, 1905, 1879, 1252, 1296, 1339, 1382, + 1424, 1465, 1506, 1545, 1584, 1622, 1658, 1694, 1728, 1761, 1793, 1823, + 0, 26, 53, 82, 111, 142, 174, 207, 241, 276, 312, 349, + 386, 425, 464, 505, -250, -255, -260, -265, -269, -272, -274, -276, + -277, -277, -277, -275, -273, -270, -265, -260, 0, -6, -12, -18, + -25, -32, -39, -46, -54, -62, -70, -78, -87, -95, -104, -112, + } }, + { .ratio = 0x155555, .extra = -115, .taps = { + -200, -182, -179, -175, -171, -167, -163, -158, -154, -149, -145, -140, + -135, -130, -125, -120, 82, -131, -139, -146, -153, -160, -166, -171, + -177, -181, -185, -189, -192, -195, -197, -199, 789, 382, 360, 337, + 315, 294, 272, 251, 231, 211, 191, 171, 153, 134, 116, 99, + 1433, 1154, 1131, 1109, 1086, 1063, 1039, 1015, 991, 966, 941, 916, + 891, 865, 840, 814, 1550, 1550, 1549, 1547, 1543, 1538, 1535, 1527, + 1522, 1513, 1504, 1496, 1485, 1475, 1461, 1449, 1175, 1196, 1217, 1237, + 1256, 1275, 1293, 1311, 1327, 1344, 1359, 1374, 1388, 1401, 1413, 1425, + 405, 428, 452, 475, 499, 523, 547, 571, 595, 619, 644, 668, + 692, 716, 741, 765, -122, -113, -104, -94, -83, -72, -61, -48, + -36, -23, -9, 5, 19, 34, 50, 65, -185, -188, -191, -194, + -196, -198, -200, -202, -203, -204, -204, -205, -205, -204, -203, -202, + } }, + { .ratio = 0x200000, .extra = -72, .taps = { + 106, -5, -11, -16, -21, -26, -31, -36, -40, -45, -49, -53, + -57, -61, -65, -69, 392, 229, 220, 211, 203, 194, 186, 177, + 169, 161, 152, 144, 136, 129, 121, 113, 695, 536, 527, 517, + 507, 498, 488, 479, 469, 459, 450, 440, 430, 421, 411, 402, + 891, 802, 796, 789, 783, 776, 769, 762, 755, 748, 741, 733, + 726, 718, 711, 703, 912, 912, 912, 912, 910, 910, 908, 908, + 905, 905, 904, 902, 901, 898, 896, 894, 808, 814, 820, 826, + 832, 838, 843, 849, 854, 859, 864, 869, 873, 878, 882, 887, + 546, 555, 565, 574, 584, 593, 603, 612, 622, 631, 640, 650, + 659, 668, 677, 686, 238, 247, 256, 266, 275, 284, 294, 303, + 313, 323, 332, 342, 352, 362, 372, 382, 0, 6, 11, 17, + 23, 29, 36, 42, 49, 55, 62, 69, 76, 83, 91, 98, + } }, +}; + +/* De-ringing constants of a scaled axis, in pairs (two channels): downscale and upscale. */ +static const u32 msr23_dering[2][13] = { + { 0xcd, 0x266, 0x39a, 0x4cd, 0x355e3a6, 0x400, 0xb33, 0x266, 0x733, 0x11c79b, + 0x1aa98e, 0x666, 0x333 }, + { 0xcd, 0x266, 0x39a, 0x99a, 0xaaaaab, 0x400, 0xb33, 0x266, 0x733, 0x11c79b, + 0x1aa98e, 0x666, 0x333 }, +}; + +/* + * The 2x2 ordered dither (Bayer [[0, 2], [3, 1]], tiled 4x4) for a 10-bit + * source written at 8 bits. + */ +static const u32 msr23_dither[16] = { 0, 2, 0, 2, 3, 1, 3, 1, 0, 2, 0, 2, 3, 1, 3, 1 }; + +/** + * struct msr23_fmt - a pixel format as the engine sees it + * @fourcc: V4L2 pixel format + * @rgb: R'G'B' (else Y'CbCr or grey) + * @grey: luma only + * @sub: chroma subsampling code (0 4:4:4, 1 4:2:2, 3 4:2:0) + * @code: memory format code of plane 0 and of the chroma plane + * @swizzle: component order (0 identity, else CbCr) + * @hs: horizontal chroma subsampling + * @vs: vertical chroma subsampling + * @bits: bits per component of the four channels (0: 8) + */ +struct msr23_fmt { + u32 fourcc; + bool rgb, grey; + u8 sub; + u8 code[2]; + u8 swizzle, hs, vs; + u8 bits[4]; +}; + +static const struct msr23_fmt msr23_fmts[] = { + { V4L2_PIX_FMT_ABGR32, .rgb = true, .code = { 0x1e } }, + { V4L2_PIX_FMT_NV12, .sub = 3, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 2 }, + { V4L2_PIX_FMT_NV12M, .sub = 3, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 2 }, + { V4L2_PIX_FMT_NV16, .sub = 1, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 1 }, + { V4L2_PIX_FMT_NV16M, .sub = 1, .code = { 1, 6 }, .swizzle = 2, .hs = 2, .vs = 1 }, + { V4L2_PIX_FMT_NV24, .code = { 1, 6 }, .swizzle = 2, .hs = 1, .vs = 1 }, + { V4L2_PIX_FMT_P010, .sub = 3, .code = { 2, 0x12 }, .swizzle = 2, .hs = 2, .vs = 2, + .bits = { 10, 10, 10, 0 } }, + { V4L2_PIX_FMT_GREY, .grey = true, .code = { 1 }, .swizzle = 2 }, +}; + +static const struct msr23_fmt *msr23_fmt(u32 fourcc) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(msr23_fmts); i++) + if (msr23_fmts[i].fourcc == fourcc) + return &msr23_fmts[i]; + return NULL; +} + +bool msr23_format_ok(u32 fourcc) +{ + return msr23_fmt(fourcc); +} +EXPORT_SYMBOL_IF_KUNIT(msr23_format_ok); + +static u8 msr23_bits(const struct msr23_fmt *f, unsigned int c) +{ + return f->bits[c] ?: 8; +} + +#define W(img, o, v) ((img)[(o) / 4] = (v)) + +/* + * One side's DMA words: plane codes, strides, sizes, swizzle (block 1 for the + * source, block 14 for the destination). + */ +static void msr23_side(u32 *img, const struct msr23_pic *p, const struct msr23_fmt *f, bool dst) +{ + u32 b = dst ? MSR23_B14 : MSR23_B1; + u32 so = dst ? 0x40 : 0x58, wo = dst ? 0x5c : 0x7c; + u32 po = dst ? 0x88 : 0xb4, ho = dst ? 0x94 : 0xc4; + bool chroma = !f->rgb && !f->grey; + u32 cw = chroma ? p->width / f->hs : p->width, ch = chroma ? p->height / f->vs : p->height; + unsigned int i; + + for (i = 0; i < 2; i++) + W(img, b + 4 + 4 * i, (dst ? 0x8000 : 0) | f->code[i]); + W(img, b + so, p->stride[0]); + W(img, b + so + 4, chroma ? p->stride[1] : 0); + W(img, b + wo, p->width); + W(img, b + wo + 4, p->height); + for (i = 0; i < 3; i++) { + W(img, b + po + 4 * i, i == 1 ? cw : p->width); + W(img, b + ho + 4 * i, i == 1 ? ch : p->height); + } + W(img, b + (dst ? 0x58 : 0x78), f->swizzle ? 0x03000102 : 0x03020100); +} + +static u32 msr23_dup(s16 v) +{ + return (u16)v | (u32)(u16)v << 16; +} + +/* + * One axis of the scaler (block 8: the vertical half at +0x80, the + * horizontal half at +0x400): step and inverse in Q22 (the vertical half at + * 20-bit precision), initial phase when upscaling, de-ringing, and the filter + * of the first bin whose ratio is at least the step. + * A Y'CbCr source at 1:1 runs no filter. + */ +static int msr23_axis(u32 *img, u32 src, u32 dst, bool horizontal, bool yuv_src) +{ + u32 b = MSR23_B8 + (horizontal ? 0x400 : 0x80); + unsigned int prec = horizontal ? 22 : 20, i; + u32 step = (u32)div_u64((u64)src << prec, dst) << (22 - prec); + u32 inv = (u32)div_u64((u64)dst << prec, src) << (22 - prec); + bool scaled = src != dst; + + W(img, b, yuv_src ? 2 : 0); + if (step < BIT(22)) { + s32 init = ((s32)step - (s32)BIT(22)) >> 1; + + W(img, b + 0x4, init & 0xffffff); + W(img, b + 0x8, (yuv_src ? init >> 1 : init) & 0xffffff); + } + W(img, b + 0xc, step); + W(img, b + 0x10, step); + W(img, b + 0x14, inv); + W(img, b + 0x18, inv); + if (scaled) + for (i = 0; i < ARRAY_SIZE(msr23_dering[0]); i++) { + W(img, b + 0x1c + 8 * i, msr23_dering[step < BIT(22)][i]); + W(img, b + 0x20 + 8 * i, msr23_dering[step < BIT(22)][i]); + } + W(img, b + (horizontal ? 0xe0 : 0xfc), 0x12345678); + if (scaled || !yuv_src) { + const struct msr23_filter *f = NULL; + + for (i = 0; i < MSR23_FILTER_BINS; i++) + if (msr23_filters[i].ratio >= step >> 3) { + f = &msr23_filters[i]; + break; + } + if (!f) + return -EINVAL; + for (i = 0; i < MSR23_FILTER_TAPS; i++) + W(img, b + 0x100 + 4 * i, msr23_dup(f->taps[i])); + W(img, b + 0x340, msr23_dup(f->extra)); + } + return 0; +} + +/* + * Block 0 +0x78..+0x84: the channels' component sizes, source in the low + * half, destination in the high half. + */ +static void msr23_map(u32 *img, const struct msr23_fmt *s, const struct msr23_fmt *d, bool scaled) +{ + unsigned int c; + + for (c = 0; c < 4; c++) { + u32 lo, hi; + + if (!scaled) + lo = 0x30; + else if (!s->rgb) + lo = c ? 0x20 | (c < 3 ? msr23_bits(s, c) : 0) : msr23_bits(s, c); + else + lo = s->bits[0] ? msr23_bits(s, c) : 8; + if (d->rgb) + hi = 8; + else + hi = c ? 0x20 | (c < 3 ? msr23_bits(d, c) : 0) : msr23_bits(d, c); + W(img, MSR23_B0 + 0x78 + 4 * c, hi << 16 | lo); + } +} + +/* The colour matrix: block 3 at 1:1, block 11 when the job also scales. */ +static int msr23_matrix(u32 *img, const struct msr23_job *job, bool to_yuv, bool scaled) +{ + struct asc_csc csc; + unsigned int r, c; + u32 b; + + if (asc_csc_compute(job->enc, + job->full ? V4L2_QUANTIZATION_FULL_RANGE : V4L2_QUANTIZATION_LIM_RANGE, + !to_yuv, &csc)) + return -EINVAL; + b = scaled ? MSR23_B11 + 0x14 : MSR23_B3 + 0x34; + for (r = 0; r < 3; r++) + for (c = 0; c < 3; c++) + W(img, b + 12 * r + 4 * c, (u16)csc.coef[r][c]); + for (r = 0; r < 3; r++) { + /* offsets: block 11 in 2^-24 of full scale (26 bits), block 3 in 2^-16 (17 bits) */ + if (to_yuv) + W(img, b + 0x24 + 4 * r, scaled ? (u32)csc.post[r] : (u32)csc.post[r] >> 8); + else + W(img, b - 0xc + 4 * r, scaled ? (u32)csc.pre[r] & 0x3ffffff : + (u32)(csc.pre[r] >> 8) & 0x1ffff); + } + return 0; +} + +static bool msr23_size_ok(const struct msr23_pic *p) +{ + return !((p->width | p->height) & 1) && min(p->width, p->height) >= MSR23_MIN_SIZE && + p->width <= MSR23_MAX_WIDTH && (u64)p->width * p->height <= MSR23_MAX_PIXELS; +} + +/** + * msr23_check - whether the builder covers a job + * @job: the conversion + * + * Return: 0, or -EINVAL for a format, size or ratio the builder was not checked over. + */ +int msr23_check(const struct msr23_job *job) +{ + const struct msr23_pic *sp = &job->src, *dp = &job->dst; + const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); + u32 sw = sp->width, sh = sp->height, dw = dp->width, dh = dp->height; + + if (!s || !d || !msr23_size_ok(sp) || !msr23_size_ok(dp) || s->grey != d->grey) + return -EINVAL; + if (sw > MSR23_MAX_RATIO * dw || dw > MSR23_MAX_RATIO * sw || + sh > MSR23_MAX_RATIO * dh || dh > MSR23_MAX_RATIO * sh) + return -EINVAL; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(msr23_check); + +/** + * msr23_build - the register image of a job + * @job: the conversion + * @img: MSR23_IMG_LEN bytes, zeroed by the caller + * @out: NC sizes and plane counts + * + * The pointers and the frame id are left zero: the caller writes them + * (MSR23_PTR_*, MSR23_FRAME_ID). + * + * Return: 0, or -EINVAL for a job the builder does not cover. + */ +int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) +{ + const struct msr23_pic *sp = &job->src, *dp = &job->dst; + const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); + u32 sw = sp->width, sh = sp->height, dw = dp->width, dh = dp->height; + bool yuv_src, yuv_dst, csc_on, scaled, ups, wide; + u64 px; + u32 cds, k, rows; + unsigned int i; + int ret; + + ret = msr23_check(job); + if (ret) + return ret; + + yuv_src = !s->rgb; + yuv_dst = !d->rgb; + csc_on = yuv_src != yuv_dst; + scaled = sw != dw || sh != dh; + /* chroma upsampling: a subsampled Y'CbCr source */ + ups = yuv_src && (s->hs > 1 || s->vs > 1); + px = max((u64)sw * sh, (u64)dw * dh); + + for (i = 0; i < ARRAY_SIZE(msr23_defaults); i++) { + const struct msr23_block *b = NULL; + unsigned int j; + + for (j = 0; j < MSR23_NBLOCKS && !b; j++) + if (msr23_blocks[j].id == msr23_defaults[i].block) + b = &msr23_blocks[j]; + W(img, b->off + msr23_defaults[i].off, msr23_defaults[i].val); + } + + /* Block 0: the pipe. */ + W(img, MSR23_B0 + 0xc, 0xffff | (yuv_src && csc_on ? BIT(31) : 0)); + /* a time budget: 40e6 (80e6 above 1080p) + 8/15 per pixel of the larger side */ + W(img, MSR23_B0 + 0x18, 40000000U * (px > 1920 * 1080 ? 2 : 1) + (u32)div_u64(px * 8, 15)); + W(img, MSR23_B0 + 0x64, 0x38d800 | s->rgb | s->sub << 1 | d->rgb << 7 | d->sub << 8 | + (csc_on && !scaled ? BIT(16) : 0) | (ups ? BIT(13) : 0)); + /* scaler enables per axis: off at 1:1, the low 3 bits upscaling, all 5 downscaling */ + W(img, MSR23_B0 + 0x68, (sw == dw ? 0 : (dw > sw ? 0x7 : 0x1f) << 11) | + (sh == dh ? 0 : (dh > sh ? 0x7 : 0x1f) << 6)); + /* chroma downsampling of a subsampled Y'CbCr destination */ + cds = 0xc | (yuv_dst && d->hs == 2 ? 1 : 0) | (yuv_dst && d->vs == 2 ? 2 : 0); + W(img, MSR23_B0 + 0x6c, cds << 16 | (csc_on && scaled ? 3 : 0)); + W(img, MSR23_B0 + 0x70, (dh - 1) << 16 | (dw - 1)); + msr23_map(img, s, d, scaled); + + msr23_side(img, sp, s, false); + msr23_side(img, dp, d, true); + + ret = msr23_axis(img, sh, dh, false, yuv_src); + if (!ret) + ret = msr23_axis(img, sw, dw, true, yuv_src); + if (ret) + return ret; + W(img, MSR23_B8 + 0x4e4, 1); + + /* + * Block 3: chroma upsampling terms; the matrix at 1:1. Block 11: the + * matrix when scaling too. + */ + for (i = 0; i < 4; i++) + W(img, MSR23_B3 + (i < 2 ? 0x8 : 0x10) + 4 * i, ups ? 0x800 : 0); + if (csc_on) { + ret = msr23_matrix(img, job, yuv_dst, scaled); + if (ret) + return ret; + } + + /* + * Block 12: chroma downsampling per subsampled axis, and the dither of a + * 10-bit source written at 8 bits. + */ + W(img, MSR23_B12 + 0xc, yuv_dst && d->hs == 2 ? 0x1000 : 0); + W(img, MSR23_B12 + 0x1c, yuv_dst && d->vs == 2 ? 0x1000 : 0); + if (msr23_bits(s, 0) > msr23_bits(d, 0)) { + W(img, MSR23_B12 + 0x180, 0x02020200); + for (i = 0; i < ARRAY_SIZE(msr23_dither); i++) + W(img, MSR23_B12 + 0x200 + 4 * i, msr23_dither[i]); + } + + /* + * Spill (NC) buffers in 16 KiB pages, for the units' line buffers: + * about 0.018 page per source row and 0.004 per destination row at + * 8 bits (24 pages at 1080p, 43 for 4K -> 1080p), twice that with + * 16-bit samples. Larger than needed is harmless (the jobs give the + * same output), so round generously, and never below 48 pages per + * byte of sample. + */ + wide = s->bits[0] || d->bits[0]; + k = wide ? 2 : 1; + rows = 320 * sh + 64 * dh; + out->nc0 = max(DIV_ROUND_UP(rows * k, MSR23_NC_PAGE) + 2, 48 * k); + out->nc1 = wide ? 8 : 4; + W(img, MSR23_B0 + 0xec, out->nc1 << 16 | out->nc0); + out->planes[0] = s->code[1] ? 2 : 1; + out->planes[1] = d->code[1] ? 2 : 1; + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(msr23_build); diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.h b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h new file mode 100644 index 00000000000000..ca0e76be30491e --- /dev/null +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * Apple silicon scaler (MSR23, M5): job builder. + * + * A MSR23 job is a register image the engine's firmware streams into the + * hardware, described by a list of blocks. This builds the image for a + * conversion from its parameters. The pointers (surfaces, spill buffer) and + * the frame id are left to the caller. + */ +#ifndef _APPLE_SCALER_MSR23_H_ +#define _APPLE_SCALER_MSR23_H_ + +#include +#include + +/* The image: every block of a job lives in it. */ +#define MSR23_IMG_LEN 0x14000 + +/* Block list record word 2: the firmware tiles the job itself (no tile array). */ +#define MSR23_HDR2_FW_TILING 0x72000000 + +/* Offsets in the image of the blocks the caller writes into. */ +#define MSR23_B0 0x80 +#define MSR23_B1 0x200 +#define MSR23_B14 0x380 + +/* 64-bit pointers in the image (low word, then high word). */ +#define MSR23_PTR_NC0 (MSR23_B0 + 0x50) /* spill buffer, NC0 pages */ +#define MSR23_PTR_NC1 (MSR23_B0 + 0x58) /* spill buffer after NC0 */ +#define MSR23_PTR_SRC(p) (MSR23_B1 + 0x18 + 8 * (p)) +#define MSR23_PTR_DST(p) (MSR23_B14 + 0x10 + 8 * (p)) +/* Block 0 +0x60: the frame id, as in the record's word 1. */ +#define MSR23_FRAME_ID (MSR23_B0 + 0x60) + +/* + * The sizes the builder was checked over on hardware: even, 64 pixels to + * 4096 wide and 4K UHD in area, at most 4x down or up per axis. + */ +#define MSR23_MIN_SIZE 64 +#define MSR23_MAX_WIDTH 4096 +#define MSR23_MAX_PIXELS (3840 * 2160) +#define MSR23_MAX_RATIO 4 + +/* NC buffer pages. */ +#define MSR23_NC_PAGE 0x4000 + +/** + * struct msr23_block - one block of a job + * @id: block (register group) id + * @off: offset in the image + * @size: size word of the block list (size in 32-byte units at bit 20) + */ +struct msr23_block { + u8 id; + u32 off; + u32 size; +}; + +#define MSR23_NBLOCKS 10 +extern const struct msr23_block msr23_blocks[MSR23_NBLOCKS]; + +/** + * struct msr23_pic - one side of a job + * @fourcc: V4L2 pixel format + * @width: width in pixels + * @height: height in pixels + * @stride: bytes per line of plane 0 and of the chroma plane (0 if none) + */ +struct msr23_pic { + u32 fourcc; + u32 width, height; + u32 stride[2]; +}; + +/** + * struct msr23_job - a conversion + * @src: source picture + * @dst: destination picture + * @enc: Y'CbCr encoding of the Y'CbCr side (both sides: the same) + * @full: that side is full range + */ +struct msr23_job { + struct msr23_pic src, dst; + enum v4l2_ycbcr_encoding enc; + bool full; +}; + +/** + * struct msr23_built - what the builder computed besides the image + * @nc0: NC0 spill pages (16 KiB each) + * @nc1: NC1 spill pages + * @planes: number of planes of the source and of the destination + */ +struct msr23_built { + u32 nc0, nc1; + u8 planes[2]; +}; + +bool msr23_format_ok(u32 fourcc); +int msr23_check(const struct msr23_job *job); +int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out); + +#endif diff --git a/drivers/media/platform/apple/scaler/apple-scaler-test.c b/drivers/media/platform/apple/scaler/apple-scaler-test.c index 763d8a40109829..fa39305b2d01a9 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-test.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-test.c @@ -9,9 +9,11 @@ #include #include #include +#include #include #include "apple-scaler-hw.h" +#include "apple-scaler-msr23.h" #include "apple-scaler-regs.h" struct asc_csc_case { @@ -638,6 +640,146 @@ static void asc_test_job_rejects(struct kunit *test) KUNIT_EXPECT_EQ(test, asc_job_build(&job, w, ASC_JOB_MAX_WRITES), -EINVAL); } +/* ---- MSR23 job builder ---- */ + +static u32 msr23_word(const u32 *img, u32 off) +{ + return img[off / 4]; +} + +static void msr23_pic(struct msr23_pic *p, u32 fourcc, u32 w, u32 h, u32 bpp, u32 cstride_mul) +{ + *p = (struct msr23_pic){ fourcc, w, h, { w * bpp, cstride_mul * w } }; +} + +/* + * BGRA -> NV12 BT.709 at 1080p: sizes, plane codes and the matrix of block 3 + * as asc_csc_compute() gives it. + */ +static void asc_test_msr23_csc(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = { .enc = V4L2_YCBCR_ENC_709 }; + struct msr23_built out; + struct asc_csc csc; + unsigned int r, c; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 1079 << 16 | 1919); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x58), 7680); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x4), 0x8001); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8), 0x8006); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8c), 960); /* chroma width */ + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x98), 540); /* chroma height */ + KUNIT_ASSERT_EQ(test, asc_csc_compute(V4L2_YCBCR_ENC_709, V4L2_QUANTIZATION_LIM_RANGE, + false, &csc), 0); + for (r = 0; r < 3; r++) + for (c = 0; c < 3; c++) + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x34 + 12 * r + 4 * c), + (u16)csc.coef[r][c]); + /* the output offsets: limited-range black and the chroma midpoint */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x58), 0x1010); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x1e00 + 0x5c), 0x8020); + KUNIT_EXPECT_EQ(test, out.planes[0], 1); + KUNIT_EXPECT_EQ(test, out.planes[1], 2); + /* no scaling: both filter axes at unit step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), BIT(22)); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), BIT(22)); +} + +/* + * BGRA 4K -> 1080p: Q22 steps and inverses per axis; 1080p -> 4K: the centre + * initial phase -1/4. + */ +static void asc_test_msr23_scale(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), 2 << 22); /* vertical step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x94), 1 << 21); /* its inverse */ + /* horizontal step */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), 2 << 22); + /* no initial phase when downscaling */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x84), 0); + KUNIT_EXPECT_GE(test, out.nc0, 43); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0xec), out.nc1 << 16 | out.nc0); + + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), 1 << 21); + /* -1/4 in 24-bit Q22 */ + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x84), 0xf00000); + /* one axis only: the other stays at a unit step */ + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 960, 1080, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x8c), BIT(22)); + KUNIT_EXPECT_EQ(test, msr23_word(img, 0x9080 + 0x40c), 2 << 22); +} + +/* What the builder does not cover. */ +static void asc_test_msr23_rejects(struct kunit *test) +{ + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + + KUNIT_ASSERT_NOT_NULL(test, img); + msr23_pic(&job.src, V4L2_PIX_FMT_GREY, 1920, 1080, 1, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + /* grey only to grey */ + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 3840, 2160, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 480, 270, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* 8x down */ + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1919, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* odd width */ + msr23_pic(&job.dst, V4L2_PIX_FMT_ARGB2101010, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_build(&job, img, &out), -EINVAL); /* no 2:10:10:10 */ + KUNIT_EXPECT_FALSE(test, msr23_format_ok(V4L2_PIX_FMT_ARGB2101010)); + KUNIT_EXPECT_TRUE(test, msr23_format_ok(V4L2_PIX_FMT_P010)); + /* above 4K UHD in area, and 4x up per axis (allowed) */ + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 4096, 2304, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 480, 270 * 2, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); +} + +/* + * The block list: each block inside the image, at a 128-byte boundary (block + * words hold offset >> 7), and no two overlapping. + */ +static void asc_test_msr23_blocks(struct kunit *test) +{ + unsigned int i, j; + + for (i = 0; i < MSR23_NBLOCKS; i++) { + u32 a = msr23_blocks[i].off, end = a + (msr23_blocks[i].size >> 20) * 32; + + KUNIT_EXPECT_LE(test, end, MSR23_IMG_LEN); + KUNIT_EXPECT_EQ(test, a % 0x80, 0); + for (j = 0; j < i; j++) { + u32 b = msr23_blocks[j].off, bend = b + (msr23_blocks[j].size >> 20) * 32; + + KUNIT_EXPECT_TRUE(test, end <= b || bend <= a); + } + } +} + static struct kunit_case asc_test_cases[] = { KUNIT_CASE_PARAM(asc_test_csc, asc_csc_gen_params), KUNIT_CASE(asc_test_csc_rejects), @@ -648,6 +790,10 @@ static struct kunit_case asc_test_cases[] = { KUNIT_CASE(asc_test_job_rejects), KUNIT_CASE(asc_test_lossless_geom), KUNIT_CASE(asc_test_job_lossless), + KUNIT_CASE(asc_test_msr23_csc), + KUNIT_CASE(asc_test_msr23_scale), + KUNIT_CASE(asc_test_msr23_rejects), + KUNIT_CASE(asc_test_msr23_blocks), {} }; diff --git a/tools/media/apple-scaler/msr23_filters.py b/tools/media/apple-scaler/msr23_filters.py new file mode 100755 index 00000000000000..f67b9e52810535 --- /dev/null +++ b/tools/media/apple-scaler/msr23_filters.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Generate the MSR23 scaler's polyphase filter table (apple-scaler-msr23.c). + +The engine filters each axis with 9 taps and picks one of 8 coefficient sets +("bins") by the step, src/dst in Q19: a step uses the first bin whose ratio is +at least the step. Each set is one symmetric kernel h(x), sampled at 9 source +pixels around the output position with 32 sub-pixel phases per pixel. + +Design + Downscaling bins (ratio s > 1, s = 8/7, 4/3, 8/5, 2, 8/3, 4): + h(x) = sinc(x / s) * kaiser(x; R = 3.5 s, beta = 6.5) + A low-pass at the output's Nyquist frequency (cutoff 1/s of the source + rate), Kaiser-windowed over three and a half lobes of the scaled sinc. + Upscaling bin (steps below 1): + h(x) = sinc(x) * kaiser(x; R = 31/16, beta = 5) + An interpolating 4-tap kernel: h(0) = 1, h(+-1) = 0, nothing at |x| >= 2. + The 1:1 bin passes the source through: the centre tap is 1.0 in every + phase, and its extra word is 1.0. + Window: kaiser(x; R, beta) = I0(beta * sqrt(1 - (x/R)^2)) / I0(beta) for + |x| < R, else 0. + +Sampling and quantisation + Phase f = p/32 (p = 0..16) places the output f source pixels right of tap 4, + so tap k sits at x = k - 4 - f. Each phase is normalised to unit gain and + rounded to Q12 (4096 = 1.0); the rounding residual goes to the largest tap, + so every phase sums to exactly 4096. + +Storage (16 words per tap, index tap * 16 + phase) + Phases 1..15 are stored as they are, in columns 1..15. The kernel is + symmetric, so phases 17..31 are the mirror images of 15..1 and are not + stored. Column 0 holds two phases: its taps 4..8 are f = 0 (taps 0..3 are + their mirror), and its taps 0..3 hold taps 1..4 of f = 1/2. The per-bin + extra word is tap 0 of f = 1/2 (taps 5..8 are the mirror of 1..4). + +Against the coefficient set captured from the engine's own jobs (pass it +with --compare), every word is within 5/4096 and every phase's absolute +difference sums to at most 14/4096: under 0.9 of an 8-bit code value per +axis, so a scaled 8-bit sample differs by at most 2. + +Usage: msr23_filters.py print the C initializer + msr23_filters.py --check F exit 1 unless source file F holds exactly this table + msr23_filters.py --compare F per-bin differences against the table in F +""" +import math +import re +import sys + +PHASES = 32 +TAPS = 9 +ONE = 4096 +# Bin upper bounds, src/dst in Q19 (the 1:1 bin is exactly 1 << 19). +BINS = [ + ("up", (1 << 19) - 1), + ("one", 1 << 19), + ("down", 8 * (1 << 19) // 7), + ("down", 4 * (1 << 19) // 3), + ("down", 8 * (1 << 19) // 5), + ("down", 2 << 19), + ("down", 8 * (1 << 19) // 3), + ("down", 4 << 19), +] + + +def i0(x): + """Modified Bessel function of the first kind, order 0 (power series).""" + s, t, k = 1.0, 1.0, 1 + while t > 1e-17 * s: + t *= (x / (2 * k)) ** 2 + s += t + k += 1 + return s + + +def sinc(x): + return 1.0 if x == 0 else math.sin(math.pi * x) / (math.pi * x) + + +def kaiser(x, r, beta): + if abs(x) >= r: + return 0.0 + return i0(beta * math.sqrt(1.0 - (x / r) ** 2)) / i0(beta) + + +def kernel(kind, ratio): + s = ratio / (1 << 19) + if kind == "up": + return lambda x: sinc(x) * kaiser(x, 31 / 16, 5.0) + return lambda x: sinc(x / s) * kaiser(x, 3.5 * s, 6.5) + + +def phase(h, f): + w = [h(k - 4 - f) for k in range(TAPS)] + total = sum(w) + q = [w[k] / total * ONE for k in range(TAPS)] + r = [int(math.floor(v + 0.5)) if v >= 0 else -int(math.floor(-v + 0.5)) for v in q] + big = max(range(TAPS), key=lambda k: q[k]) + r[big] += ONE - sum(r) + return r + + +def bin_words(kind, ratio): + if kind == "one": + taps = [ONE if k == 4 else 0 for k in range(TAPS) for _ in range(16)] + return ONE, taps + h = kernel(kind, ratio) + cols = {p: phase(h, p / PHASES) for p in range(17)} + taps = [0] * (TAPS * 16) + for k in range(TAPS): + for p in range(1, 16): + taps[k * 16 + p] = cols[p][k] + for k in range(4, TAPS): + taps[k * 16] = cols[0][k] + for k in range(4): + taps[k * 16] = cols[16][k + 1] + return cols[16][0], taps + + +def table(): + return [(ratio,) + bin_words(kind, ratio) for kind, ratio in BINS] + + +def emit(): + out = [] + for ratio, extra, taps in table(): + out.append(f"\t{{ .ratio = 0x{ratio:x}, .extra = {extra}, .taps = {{") + for i in range(0, len(taps), 12): + out.append("\t\t" + ", ".join(str(v) for v in taps[i:i + 12]) + ",") + out.append("\t} },") + return "\n".join(out) + + +def parse(path): + src = open(path).read() + bins = re.findall(r"\.ratio = (0x[0-9a-f]+), \.extra = (-?\d+), \.taps = \{(.*?)\}", src, re.S) + return [(int(r, 16), int(e), [int(v) for v in re.findall(r"-?\d+", t)]) for r, e, t in bins] + + +def main(): + if len(sys.argv) == 3 and sys.argv[1] in ("--check", "--compare"): + ref = parse(sys.argv[2]) + worst = 0 + for (r0, e0, t0), (r1, e1, t1) in zip(table(), ref): + d = max([abs(a - b) for a, b in zip(t0, t1)] + [abs(e0 - e1)]) + n = sum(a != b for a, b in zip(t0, t1)) + (e0 != e1) + print(f"bin 0x{r0:x}: ratio {'ok' if r0 == r1 else 'DIFF'}, {n} words differ, max {d}") + worst = max(worst, d) + if sys.argv[1] == "--check": + sys.exit(0 if worst == 0 else 1) + return + print(emit()) + + +if __name__ == "__main__": + main() From 80d9d36b455e44415c53a203ddd9d243984cbe68 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 19:43:33 +0700 Subject: [PATCH 0783/1514] media: apple: scaler: Add MSR23 crop, compose, rotation and flips The M5 (MSR23) engine reads a rectangle of the source, writes into a rectangle of the destination, rotates in quarter turns and mirrors. Expose these as the OUTPUT crop and CAPTURE compose selections and the V4L2_CID_ROTATE, V4L2_CID_HFLIP and V4L2_CID_VFLIP controls. - Crop: the source region's size, and its origin per plane in samples of that plane; plane sizes and pointers stay those of the whole picture. - Compose: a picture of the rectangle's size at an offset into the destination planes. The rest of the CAPTURE buffer is left as it is. - Rotation and flips: block 0 +0x64 bits 3-6, a quarter-turn count, then mirrors of the rotated picture. The reader rotates, so the scaler and the output window work in the destination's orientation. - A conversion at 1:1 with a quarter turn runs its matrix where a scaled job does (block 11); in block 3 the rotated output is wrong. With a mirror or a half turn, a 1:1 conversion has not been checked and is refused, as are quarter turns of 4:2:2. - Rectangles are even and at least 64 pixels, like the formats. They survive a format change they still fit (v4l2-ctl sets the CAPTURE format again when it starts streaming). - Rotation and both mirrors are fixed while either queue streams: the job worker reads them without the device lock, and a mirror can make a checked 1:1 pair invalid. Same-format jobs at 1:1 now take the source's component sizes in the channel map, as scaled jobs do: before, luma above half scale came out 1 lower. Tested on the MacBook Air 15" M5 (J815): with the coefficient set captured from macOS's jobs loaded in place of the generated taps, 26 geometry jobs give output byte-identical to macOS 27.2 for the same input: quarter and half turns and flips of BGRA, NV12, NV24, P010 and GREY up to 4K, with and without scaling and conversion; crops of BGRA, NV12 and P010 with and without scaling and conversion; and compose. The 50 jobs without geometry still match. With the generated taps, these 26 are part of the previous commit's 76-job result (52 byte-identical, 24 within one code value). v4l2-compliance: cropping and composing pass. Add KUnit tests for the crop and compose words, the orientation codes, the rejected rectangles and rotations, and the channel map. Signed-off-by: Nick --- drivers/media/platform/apple/scaler/Kconfig | 3 +- .../platform/apple/scaler/apple-scaler-drv.c | 212 +++++++++++++++++- .../apple/scaler/apple-scaler-msr23.c | 152 +++++++++++-- .../apple/scaler/apple-scaler-msr23.h | 18 +- .../platform/apple/scaler/apple-scaler-test.c | 167 ++++++++++++++ 5 files changed, 529 insertions(+), 23 deletions(-) diff --git a/drivers/media/platform/apple/scaler/Kconfig b/drivers/media/platform/apple/scaler/Kconfig index 67e716da04e1c9..4abf05a8d9902a 100644 --- a/drivers/media/platform/apple/scaler/Kconfig +++ b/drivers/media/platform/apple/scaler/Kconfig @@ -12,7 +12,8 @@ config VIDEO_APPLE_SCALER V4L2 memory-to-memory driver for the image scaler and colour-space converter (MSR) in Apple silicon SoCs (M1 to M5 generations and A18 Pro). It converts between Y'CbCr (NV12, - P010) and 32-bit RGB; on M5 it also scales. + P010) and 32-bit RGB; on M5 it also scales, crops, rotates and + mirrors. To compile this driver as a module, choose M here: the module will be called apple-scaler. diff --git a/drivers/media/platform/apple/scaler/apple-scaler-drv.c b/drivers/media/platform/apple/scaler/apple-scaler-drv.c index 0af9f7fad4606c..3b266744d89c10 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-drv.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-drv.c @@ -12,7 +12,11 @@ * The OUTPUT queue takes the source image, the CAPTURE queue the result. * The MMIO engines convert between formats at the same size: Y'CbCr <-> * R'G'B' with the colorimetry of the Y'CbCr side, chroma resampling and - * alpha fill. MSR23 converts and scales (up to 4x either way per axis). + * alpha fill. MSR23 converts and scales (up to 4x either way per axis). It + * also reads a crop of the source (OUTPUT crop selection), writes into a + * rectangle of the destination (CAPTURE compose selection), rotates in + * quarter turns and mirrors (V4L2_CID_ROTATE, _HFLIP, _VFLIP: the mirrors + * apply to the rotated picture). */ #include #include @@ -117,6 +121,15 @@ struct apple_scaler_ctx { */ u32 dst_ycbcr_req, dst_quant_req; u32 sequence; + + /* MSR23 geometry: the source region read, the destination region written. */ + struct v4l2_rect crop, compose; + struct v4l2_ctrl_handler hdl; + struct v4l2_ctrl *rotate_ctrl; + /* fixed while either queue streams: msr23_work() reads them without asc->lock */ + struct v4l2_ctrl *job_ctrl[3]; + u16 rotate; + bool hflip, vflip; }; static struct apple_scaler_ctx *asc_file_to_ctx(struct file *file) @@ -478,6 +491,27 @@ static void asc_fill(const struct apple_scaler *asc, struct v4l2_pix_format_mpla pix->xfer_func = V4L2_MAP_XFER_FUNC_DEFAULT(pix->colorspace); } +static struct v4l2_rect asc_full_rect(const struct v4l2_pix_format_mplane *pix) +{ + return (struct v4l2_rect){ 0, 0, pix->width, pix->height }; +} + +/* + * After a format change: a rectangle that covered the whole old picture + * covers the whole new one; one set by the application stays while it fits + * (v4l2-ctl sets the CAPTURE format again after the selection, when it starts + * streaming). + */ +static void asc_fit_rect(struct v4l2_rect *r, u32 old_w, u32 old_h, + const struct v4l2_pix_format_mplane *pix) +{ + bool whole = !r->left && !r->top && r->width == old_w && r->height == old_h; + + if (whole || (u64)r->left + r->width > pix->width || + (u64)r->top + r->height > pix->height) + *r = asc_full_rect(pix); +} + static int asc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { strscpy(cap->driver, ASC_NAME, sizeof(cap->driver)); @@ -550,12 +584,16 @@ static int asc_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) static int asc_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + u32 w, h; if (vb2_is_busy(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; asc_fill(asc_file_to_ctx(file)->asc, &f->fmt.pix_mp, NULL, V4L2_PIX_FMT_NV12M); + w = ctx->src.width; + h = ctx->src.height; ctx->src = f->fmt.pix_mp; + asc_fit_rect(&ctx->crop, w, h, &ctx->src); /* * Re-derive CAPTURE from the new source, with the matrix and range it was asked for: a * CAPTURE format set before this (v4l2-ctl sets CAPTURE first) took them from the previous @@ -563,20 +601,98 @@ static int asc_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) */ ctx->dst.ycbcr_enc = ctx->dst_ycbcr_req; ctx->dst.quantization = ctx->dst_quant_req; + w = ctx->dst.width; + h = ctx->dst.height; asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + asc_fit_rect(&ctx->compose, w, h, &ctx->dst); return 0; } static int asc_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + u32 w, h; if (vb2_is_busy(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) return -EBUSY; ctx->dst_ycbcr_req = f->fmt.pix_mp.ycbcr_enc; ctx->dst_quant_req = f->fmt.pix_mp.quantization; asc_fill(ctx->asc, &f->fmt.pix_mp, &ctx->src, V4L2_PIX_FMT_ARGB32); + w = ctx->dst.width; + h = ctx->dst.height; ctx->dst = f->fmt.pix_mp; + asc_fit_rect(&ctx->compose, w, h, &ctx->dst); + return 0; +} + +/* + * MSR23: crop on the OUTPUT queue is the part of the source read, compose on + * the CAPTURE queue the part of the destination written. The engine leaves + * the rest of the CAPTURE buffer as it is, so COMPOSE_PADDED is the compose + * rectangle. Rectangles are even and at least 64 pixels, like the formats. + */ +static int asc_g_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + bool out = s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT; + + if (!out && s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) + return -EINVAL; + switch (s->target) { + case V4L2_SEL_TGT_CROP: + if (!out) + return -EINVAL; + s->r = ctx->crop; + return 0; + case V4L2_SEL_TGT_CROP_DEFAULT: + case V4L2_SEL_TGT_CROP_BOUNDS: + if (!out) + return -EINVAL; + s->r = asc_full_rect(&ctx->src); + return 0; + case V4L2_SEL_TGT_COMPOSE: + case V4L2_SEL_TGT_COMPOSE_PADDED: + if (out) + return -EINVAL; + s->r = ctx->compose; + return 0; + case V4L2_SEL_TGT_COMPOSE_DEFAULT: + case V4L2_SEL_TGT_COMPOSE_BOUNDS: + if (out) + return -EINVAL; + s->r = asc_full_rect(&ctx->dst); + return 0; + } + return -EINVAL; +} + +static int asc_s_selection(struct file *file, void *priv, struct v4l2_selection *s) +{ + struct apple_scaler_ctx *ctx = asc_file_to_ctx(file); + bool out = s->type == V4L2_BUF_TYPE_VIDEO_OUTPUT; + const struct v4l2_pix_format_mplane *pix = out ? &ctx->src : &ctx->dst; + struct v4l2_rect r; + bool le; + + if (out ? s->target != V4L2_SEL_TGT_CROP : + (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE || s->target != V4L2_SEL_TGT_COMPOSE)) + return -EINVAL; + if (vb2_is_streaming(v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx)) || + vb2_is_streaming(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx))) + return -EBUSY; + /* even: round outwards, or inwards when only V4L2_SEL_FLAG_LE is set */ + le = (s->flags & (V4L2_SEL_FLAG_LE | V4L2_SEL_FLAG_GE)) == V4L2_SEL_FLAG_LE; + r.width = clamp_t(u32, le ? ALIGN_DOWN(s->r.width, 2) : ALIGN(s->r.width, 2), + MSR23_MIN_SIZE, pix->width); + r.height = clamp_t(u32, le ? ALIGN_DOWN(s->r.height, 2) : ALIGN(s->r.height, 2), + MSR23_MIN_SIZE, pix->height); + r.left = clamp_t(s32, le ? ALIGN(s->r.left, 2) : s->r.left & ~1, 0, pix->width - r.width); + r.top = clamp_t(s32, le ? ALIGN(s->r.top, 2) : s->r.top & ~1, 0, pix->height - r.height); + if (out) + ctx->crop = r; + else + ctx->compose = r; + s->r = r; return 0; } @@ -591,6 +707,8 @@ static const struct v4l2_ioctl_ops asc_ioctl_ops = { .vidioc_try_fmt_vid_cap_mplane = asc_try_fmt_cap, .vidioc_s_fmt_vid_out_mplane = asc_s_fmt_out, .vidioc_s_fmt_vid_cap_mplane = asc_s_fmt_cap, + .vidioc_g_selection = asc_g_selection, + .vidioc_s_selection = asc_s_selection, .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, @@ -674,6 +792,15 @@ static void asc_return_bufs(struct vb2_queue *q, enum vb2_buffer_state state) static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *job); +static void asc_grab_ctrls(struct apple_scaler_ctx *ctx, bool grab) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(ctx->job_ctrl); i++) + if (ctx->job_ctrl[i]) + v4l2_ctrl_grab(ctx->job_ctrl[i], grab); +} + static int asc_start_streaming(struct vb2_queue *q, unsigned int count) { struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); @@ -695,6 +822,12 @@ static int asc_start_streaming(struct vb2_queue *q, unsigned int count) asc_return_bufs(q, VB2_BUF_STATE_QUEUED); return -EINVAL; } + /* + * Every control a job reads is fixed while either queue streams: a + * rotation changes which sizes fit, a mirror can make a checked pair + * invalid, and msr23_work() reads them without asc->lock. + */ + asc_grab_ctrls(ctx, true); if (V4L2_TYPE_IS_OUTPUT(q->type)) ctx->sequence = 0; return 0; @@ -702,7 +835,14 @@ static int asc_start_streaming(struct vb2_queue *q, unsigned int count) static void asc_stop_streaming(struct vb2_queue *q) { + struct apple_scaler_ctx *ctx = vb2_get_drv_priv(q); + struct vb2_queue *other = V4L2_TYPE_IS_OUTPUT(q->type) ? + v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx) : + v4l2_m2m_get_src_vq(ctx->fh.m2m_ctx); + asc_return_bufs(q, VB2_BUF_STATE_ERROR); + if (!vb2_is_streaming(other)) + asc_grab_ctrls(ctx, false); } static const struct vb2_ops asc_qops = { @@ -734,6 +874,52 @@ static int asc_queue_init(void *priv, struct vb2_queue *src, struct vb2_queue *d return ret ?: asc_init_queue(priv, dst, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); } +/* ---- controls --------------------------------------------------------- */ + +static int asc_s_ctrl(struct v4l2_ctrl *c) +{ + struct apple_scaler_ctx *ctx = container_of(c->handler, struct apple_scaler_ctx, hdl); + + switch (c->id) { + case V4L2_CID_ROTATE: + ctx->rotate = c->val; + return 0; + case V4L2_CID_HFLIP: + ctx->hflip = c->val; + return 0; + case V4L2_CID_VFLIP: + ctx->vflip = c->val; + return 0; + } + return -EINVAL; +} + +static const struct v4l2_ctrl_ops asc_ctrl_ops = { + .s_ctrl = asc_s_ctrl, +}; + +/* MSR23: rotation in quarter turns and the mirrors (of the rotated picture). */ +static int asc_ctrls_init(struct apple_scaler_ctx *ctx) +{ + struct v4l2_ctrl_handler *hdl = &ctx->hdl; + + v4l2_ctrl_handler_init(hdl, 3); + ctx->rotate_ctrl = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_ROTATE, 0, 270, 90, 0); + ctx->job_ctrl[0] = ctx->rotate_ctrl; + ctx->job_ctrl[1] = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); + ctx->job_ctrl[2] = v4l2_ctrl_new_std(hdl, &asc_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); + if (hdl->error) { + int ret = hdl->error; + + v4l2_ctrl_handler_free(hdl); + ctx->rotate_ctrl = NULL; + memset(ctx->job_ctrl, 0, sizeof(ctx->job_ctrl)); + return ret; + } + ctx->fh.ctrl_handler = hdl; + return 0; +} + /* ---- file operations -------------------------------------------------- */ static int asc_open(struct file *file) @@ -754,12 +940,23 @@ static int asc_open(struct file *file) ctx->dst.height = 1080; ctx->dst.pixelformat = V4L2_PIX_FMT_ARGB32; asc_fill(ctx->asc, &ctx->dst, &ctx->src, V4L2_PIX_FMT_ARGB32); + ctx->crop = asc_full_rect(&ctx->src); + ctx->compose = asc_full_rect(&ctx->dst); v4l2_fh_init(&ctx->fh, video_devdata(file)); + if (asc->variant->fw_fronted) { + ret = asc_ctrls_init(ctx); + if (ret) { + v4l2_fh_exit(&ctx->fh); + kfree(ctx); + return ret; + } + } ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(asc->m2m_dev, ctx, asc_queue_init); if (IS_ERR(ctx->fh.m2m_ctx)) { ret = PTR_ERR(ctx->fh.m2m_ctx); v4l2_fh_exit(&ctx->fh); + v4l2_ctrl_handler_free(&ctx->hdl); kfree(ctx); return ret; } @@ -777,6 +974,7 @@ static int asc_release(struct file *file) mutex_unlock(&asc->lock); v4l2_fh_del(&ctx->fh, file); v4l2_fh_exit(&ctx->fh); + v4l2_ctrl_handler_free(&ctx->hdl); kfree(ctx); return 0; } @@ -1366,6 +1564,11 @@ static int msr23_job_of(const struct apple_scaler_ctx *ctx, struct msr23_job *jo msr23_pic(&job->dst, d); job->enc = msr23_enc(y); job->full = msr23_full(y); + job->crop = ctx->crop; + job->compose = ctx->compose; + job->rotate = ctx->rotate; + job->hflip = ctx->hflip; + job->vflip = ctx->vflip; return msr23_check(job); } @@ -1445,7 +1648,7 @@ static int msr23_run(struct msr23 *m, struct apple_scaler_ctx *ctx, struct vb2_b for (k = 0; k < out.planes[0]; k++) msr23_ptr(img, MSR23_PTR_SRC(k), msr23_plane(&ctx->src, src, k)); for (k = 0; k < out.planes[1]; k++) - msr23_ptr(img, MSR23_PTR_DST(k), msr23_plane(&ctx->dst, dst, k)); + msr23_ptr(img, MSR23_PTR_DST(k), msr23_plane(&ctx->dst, dst, k) + out.dst_off[k]); /* * Block 0 +0x60 is the frame id too: it must equal the record's word 1 * (the tiler refuses a job where they differ). @@ -1779,6 +1982,11 @@ static int asc_register_video(struct apple_scaler *asc) vdev->v4l2_dev = &asc->v4l2_dev; vdev->vfl_dir = VFL_DIR_M2M; vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + /* crop and compose: MSR23 only (the MMIO engines convert at the same size) */ + if (!asc->variant->fw_fronted) { + v4l2_disable_ioctl(vdev, VIDIOC_G_SELECTION); + v4l2_disable_ioctl(vdev, VIDIOC_S_SELECTION); + } video_set_drvdata(vdev, asc); return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); } diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.c b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c index 67a992b0fd5d1f..bdf79fedf9c70d 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-msr23.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.c @@ -8,6 +8,11 @@ * from the job's parameters: the words that depend on the sizes, formats and * matrix are computed, the others hold the fixed values below. * + * Crop is the source region's size and origin, rotation and mirroring a + * field of the pipe word; the reader rotates, so the rest of the pipe works + * in the destination's orientation. Compose writes a picture of the + * rectangle's size at an offset into the destination. + * * The firmware tiles the job itself, so no tile array is built. */ @@ -327,13 +332,16 @@ static u8 msr23_bits(const struct msr23_fmt *f, unsigned int c) #define W(img, o, v) ((img)[(o) / 4] = (v)) /* - * One side's DMA words: plane codes, strides, sizes, swizzle (block 1 for the - * source, block 14 for the destination). + * One side's DMA words: plane codes, strides, the region's size and its + * origin per plane, the planes' sizes, swizzle (block 1 for the source, block + * 14 for the destination). The origins are in samples of each plane (y << 16 + * | x); the plane pointers stay at the start of the planes. */ -static void msr23_side(u32 *img, const struct msr23_pic *p, const struct msr23_fmt *f, bool dst) +static void msr23_side(u32 *img, const struct msr23_pic *p, const struct v4l2_rect *r, + const struct msr23_fmt *f, bool dst) { u32 b = dst ? MSR23_B14 : MSR23_B1; - u32 so = dst ? 0x40 : 0x58, wo = dst ? 0x5c : 0x7c; + u32 so = dst ? 0x40 : 0x58, wo = dst ? 0x5c : 0x7c, oo = dst ? 0x4c : 0x68; u32 po = dst ? 0x88 : 0xb4, ho = dst ? 0x94 : 0xc4; bool chroma = !f->rgb && !f->grey; u32 cw = chroma ? p->width / f->hs : p->width, ch = chroma ? p->height / f->vs : p->height; @@ -343,8 +351,11 @@ static void msr23_side(u32 *img, const struct msr23_pic *p, const struct msr23_f W(img, b + 4 + 4 * i, (dst ? 0x8000 : 0) | f->code[i]); W(img, b + so, p->stride[0]); W(img, b + so + 4, chroma ? p->stride[1] : 0); - W(img, b + wo, p->width); - W(img, b + wo + 4, p->height); + W(img, b + wo, r->width); + W(img, b + wo + 4, r->height); + W(img, b + oo, (u32)r->top << 16 | r->left); + if (chroma) + W(img, b + oo + 4, (u32)r->top / f->vs << 16 | (u32)r->left / f->hs); for (i = 0; i < 3; i++) { W(img, b + po + 4 * i, i == 1 ? cw : p->width); W(img, b + ho + 4 * i, i == 1 ? ch : p->height); @@ -408,16 +419,19 @@ static int msr23_axis(u32 *img, u32 src, u32 dst, bool horizontal, bool yuv_src) /* * Block 0 +0x78..+0x84: the channels' component sizes, source in the low - * half, destination in the high half. + * half, destination in the high half. A conversion at 1:1 (the matrix in + * block 3) takes 0x30 on the source side; without a conversion, as with a + * scaled one, the source's own sizes (with 0x30, values above half scale + * come out 1 lower: v * 255 / 256). */ -static void msr23_map(u32 *img, const struct msr23_fmt *s, const struct msr23_fmt *d, bool scaled) +static void msr23_map(u32 *img, const struct msr23_fmt *s, const struct msr23_fmt *d, bool csc11) { unsigned int c; for (c = 0; c < 4; c++) { u32 lo, hi; - if (!scaled) + if (csc11) lo = 0x30; else if (!s->rgb) lo = c ? 0x20 | (c < 3 ? msr23_bits(s, c) : 0) : msr23_bits(s, c); @@ -463,23 +477,94 @@ static bool msr23_size_ok(const struct msr23_pic *p) p->width <= MSR23_MAX_WIDTH && (u64)p->width * p->height <= MSR23_MAX_PIXELS; } +/* A job's crop or compose rectangle: all of the picture when its width is 0. */ +static void msr23_region(const struct msr23_pic *p, const struct v4l2_rect *r, + struct v4l2_rect *out) +{ + if (r->width) + *out = *r; + else + *out = (struct v4l2_rect){ 0, 0, p->width, p->height }; +} + +/* Even, at least the minimum size, and inside the picture. */ +static bool msr23_region_ok(const struct msr23_pic *p, const struct v4l2_rect *r) +{ + return r->left >= 0 && r->top >= 0 && !((r->left | r->top | r->width | r->height) & 1) && + min(r->width, r->height) >= MSR23_MIN_SIZE && + (u64)r->left + r->width <= p->width && (u64)r->top + r->height <= p->height; +} + +/* + * Block 0 +0x64 bits 3-6: the rotation (bits 3-4: 1, 2, 3 quarter turns + * clockwise), then a mirror of the result left to right (bit 5) and top to + * bottom (bit 6). A mirror both ways is a half turn, and a half turn and one + * mirror is the other mirror: each orientation is sent in one form only. + */ +static u32 msr23_orient(const struct msr23_job *job) +{ + unsigned int rot = job->rotate / 90; + bool h = job->hflip, v = job->vflip; + + if (h && v) { + rot = (rot + 2) & 3; + h = false; + v = false; + } + if (rot == 2 && (h || v)) { + rot = 0; + swap(h, v); + } + return rot << 3 | h << 5 | v << 6; +} + +/* The source region's size as the pipe sees it: after the rotation. */ +static void msr23_turned(const struct msr23_job *job, const struct v4l2_rect *c, u32 *w, u32 *h) +{ + bool quarter = job->rotate == 90 || job->rotate == 270; + + *w = quarter ? c->height : c->width; + *h = quarter ? c->width : c->height; +} + /** * msr23_check - whether the builder covers a job * @job: the conversion * - * Return: 0, or -EINVAL for a format, size or ratio the builder was not checked over. + * Return: 0, or -EINVAL for a format, size, rectangle, rotation or ratio the + * builder was not checked over. */ int msr23_check(const struct msr23_job *job) { const struct msr23_pic *sp = &job->src, *dp = &job->dst; const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); - u32 sw = sp->width, sh = sp->height, dw = dp->width, dh = dp->height; + struct v4l2_rect c, o; + u32 sw, sh, dw, dh; if (!s || !d || !msr23_size_ok(sp) || !msr23_size_ok(dp) || s->grey != d->grey) return -EINVAL; + if (job->rotate % 90 || job->rotate > 270) + return -EINVAL; + /* a quarter turn of 4:2:2 moves its subsampling to the other axis: not checked */ + if (job->rotate % 180 && (s->sub == 1 || d->sub == 1)) + return -EINVAL; + msr23_region(sp, &job->crop, &c); + msr23_region(dp, &job->compose, &o); + if (!msr23_region_ok(sp, &c) || !msr23_region_ok(dp, &o)) + return -EINVAL; + msr23_turned(job, &c, &sw, &sh); + dw = o.width; + dh = o.height; if (sw > MSR23_MAX_RATIO * dw || dw > MSR23_MAX_RATIO * sw || sh > MSR23_MAX_RATIO * dh || dh > MSR23_MAX_RATIO * sh) return -EINVAL; + /* + * A conversion at 1:1 with a mirror or a half turn: not checked on + * hardware (with a quarter turn it is; see msr23_build()). + */ + if (s->rgb != d->rgb && sw == dw && sh == dh && !(job->rotate % 180) && + (msr23_orient(job) & 0x70)) + return -EINVAL; return 0; } EXPORT_SYMBOL_IF_KUNIT(msr23_check); @@ -499,8 +584,10 @@ int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) { const struct msr23_pic *sp = &job->src, *dp = &job->dst; const struct msr23_fmt *s = msr23_fmt(sp->fourcc), *d = msr23_fmt(dp->fourcc); - u32 sw = sp->width, sh = sp->height, dw = dp->width, dh = dp->height; - bool yuv_src, yuv_dst, csc_on, scaled, ups, wide; + struct v4l2_rect c, o, whole; + struct msr23_pic sub; + u32 sw, sh, dw, dh, ybpp; + bool yuv_src, yuv_dst, csc_on, scaled, csc_pre, ups, wide; u64 px; u32 cds, k, rows; unsigned int i; @@ -509,11 +596,26 @@ int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) ret = msr23_check(job); if (ret) return ret; + /* + * The source is read rotated: from the reader on, the pipe (scaler, + * window) works in the destination's orientation. + */ + msr23_region(sp, &job->crop, &c); + msr23_region(dp, &job->compose, &o); + msr23_turned(job, &c, &sw, &sh); + dw = o.width; + dh = o.height; yuv_src = !s->rgb; yuv_dst = !d->rgb; csc_on = yuv_src != yuv_dst; scaled = sw != dw || sh != dh; + /* + * A conversion at 1:1 runs its matrix in block 3, ahead of the scaler; + * with a quarter turn it runs where a scaled job's does (block 11): in + * block 3 the rotated output is wrong. + */ + csc_pre = csc_on && !scaled && !(job->rotate % 180); /* chroma upsampling: a subsampled Y'CbCr source */ ups = yuv_src && (s->hs > 1 || s->vs > 1); px = max((u64)sw * sh, (u64)dw * dh); @@ -533,18 +635,30 @@ int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) /* a time budget: 40e6 (80e6 above 1080p) + 8/15 per pixel of the larger side */ W(img, MSR23_B0 + 0x18, 40000000U * (px > 1920 * 1080 ? 2 : 1) + (u32)div_u64(px * 8, 15)); W(img, MSR23_B0 + 0x64, 0x38d800 | s->rgb | s->sub << 1 | d->rgb << 7 | d->sub << 8 | - (csc_on && !scaled ? BIT(16) : 0) | (ups ? BIT(13) : 0)); + (csc_pre ? BIT(16) : 0) | (ups ? BIT(13) : 0) | msr23_orient(job)); /* scaler enables per axis: off at 1:1, the low 3 bits upscaling, all 5 downscaling */ W(img, MSR23_B0 + 0x68, (sw == dw ? 0 : (dw > sw ? 0x7 : 0x1f) << 11) | (sh == dh ? 0 : (dh > sh ? 0x7 : 0x1f) << 6)); /* chroma downsampling of a subsampled Y'CbCr destination */ cds = 0xc | (yuv_dst && d->hs == 2 ? 1 : 0) | (yuv_dst && d->vs == 2 ? 2 : 0); - W(img, MSR23_B0 + 0x6c, cds << 16 | (csc_on && scaled ? 3 : 0)); + W(img, MSR23_B0 + 0x6c, cds << 16 | (csc_on && !csc_pre ? 3 : 0)); W(img, MSR23_B0 + 0x70, (dh - 1) << 16 | (dw - 1)); - msr23_map(img, s, d, scaled); + msr23_map(img, s, d, csc_pre); - msr23_side(img, sp, s, false); - msr23_side(img, dp, d, true); + msr23_side(img, sp, &c, s, false); + /* + * The destination rectangle is written as a picture of its own: its + * size, at an offset into the planes the caller adds to the pointers. + */ + sub = *dp; + sub.width = o.width; + sub.height = o.height; + whole = (struct v4l2_rect){ 0, 0, o.width, o.height }; + msr23_side(img, &sub, &whole, d, true); + ybpp = d->rgb ? 4 : msr23_bits(d, 0) > 8 ? 2 : 1; + out->dst_off[0] = (u32)o.top * dp->stride[0] + (u32)o.left * ybpp; + out->dst_off[1] = d->rgb || d->grey ? 0 : + (u32)o.top / d->vs * dp->stride[1] + (u32)o.left / d->hs * 2 * ybpp; ret = msr23_axis(img, sh, dh, false, yuv_src); if (!ret) @@ -560,7 +674,7 @@ int msr23_build(const struct msr23_job *job, u32 *img, struct msr23_built *out) for (i = 0; i < 4; i++) W(img, MSR23_B3 + (i < 2 ? 0x8 : 0x10) + 4 * i, ups ? 0x800 : 0); if (csc_on) { - ret = msr23_matrix(img, job, yuv_dst, scaled); + ret = msr23_matrix(img, job, yuv_dst, !csc_pre); if (ret) return ret; } diff --git a/drivers/media/platform/apple/scaler/apple-scaler-msr23.h b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h index ca0e76be30491e..67cc2d678e76a9 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-msr23.h +++ b/drivers/media/platform/apple/scaler/apple-scaler-msr23.h @@ -34,7 +34,8 @@ /* * The sizes the builder was checked over on hardware: even, 64 pixels to - * 4096 wide and 4K UHD in area, at most 4x down or up per axis. + * 4096 wide and 4K UHD in area, at most 4x down or up per axis. The same + * holds for the crop and compose rectangles. */ #define MSR23_MIN_SIZE 64 #define MSR23_MAX_WIDTH 4096 @@ -76,11 +77,23 @@ struct msr23_pic { * struct msr23_job - a conversion * @src: source picture * @dst: destination picture + * @crop: the part of the source read (a zero width: all of it) + * @compose: the part of the destination written (a zero width: all of it); + * the rest of the destination is left as it is. The caller adds + * &msr23_built.dst_off to the destination pointers. + * @rotate: clockwise rotation in degrees: 0, 90, 180 or 270 + * @hflip: mirror the result left to right, after the rotation + * @vflip: mirror the result top to bottom, after the rotation * @enc: Y'CbCr encoding of the Y'CbCr side (both sides: the same) * @full: that side is full range + * + * The rectangles are in pixels, with even origins and sizes. */ struct msr23_job { struct msr23_pic src, dst; + struct v4l2_rect crop, compose; + u16 rotate; + bool hflip, vflip; enum v4l2_ycbcr_encoding enc; bool full; }; @@ -90,10 +103,13 @@ struct msr23_job { * @nc0: NC0 spill pages (16 KiB each) * @nc1: NC1 spill pages * @planes: number of planes of the source and of the destination + * @dst_off: bytes to add to each destination plane's pointer (the compose + * rectangle's origin) */ struct msr23_built { u32 nc0, nc1; u8 planes[2]; + u32 dst_off[2]; }; bool msr23_format_ok(u32 fourcc); diff --git a/drivers/media/platform/apple/scaler/apple-scaler-test.c b/drivers/media/platform/apple/scaler/apple-scaler-test.c index fa39305b2d01a9..bca3331c6026ac 100644 --- a/drivers/media/platform/apple/scaler/apple-scaler-test.c +++ b/drivers/media/platform/apple/scaler/apple-scaler-test.c @@ -757,6 +757,172 @@ static void asc_test_msr23_rejects(struct kunit *test) msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 480, 270 * 2, 4, 0); msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + + /* geometry: odd, outside, too small; rotations other than quarter turns */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 960, 540, 1, 1); + job.crop = (struct v4l2_rect){ 101, 50, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){ 1000, 50, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){ -2, 0, 960, 540 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.crop = (struct v4l2_rect){}; + job.compose = (struct v4l2_rect){ 0, 0, 960, 32 }; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.compose = (struct v4l2_rect){}; + job.rotate = 45; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + /* the ratio is the rotated source's: 1080 -> 256 is beyond 4x */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 256, 1920, 1, 1); + job.rotate = 0; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.rotate = 90; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 540, 960, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + /* 4:2:2 turns only by half turns */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV16, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV16, 1080, 1920, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV16, 1920, 1080, 1, 1); + job.rotate = 180; + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); +} + +/* Crop, compose, rotation and mirrors: region sizes, origins and the pipe word's orientation. */ +static void asc_test_msr23_geometry(struct kunit *test) +{ + static const struct { + u16 rotate; + bool hflip, vflip; + u32 code; + } orient[] = { + { 0, false, false, 0 }, { 0, true, false, 0x20 }, + { 0, false, true, 0x40 }, { 0, true, true, 0x10 }, + { 90, false, false, 0x08 }, { 90, true, false, 0x28 }, + { 90, false, true, 0x48 }, { 90, true, true, 0x18 }, + { 180, false, false, 0x10 }, { 180, true, false, 0x40 }, + { 180, false, true, 0x20 }, { 270, false, false, 0x18 }, + { 270, true, false, 0x38 }, { 270, false, true, 0x58 }, + }; + u32 *img = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + u32 *ref = kunit_kzalloc(test, MSR23_IMG_LEN, GFP_KERNEL); + struct msr23_job job = {}; + struct msr23_built out; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, img); + KUNIT_ASSERT_NOT_NULL(test, ref); + + /* 960x540 at (100, 50) of an NV12 1080p source: origins per plane, planes whole */ + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 960, 540, 1, 1); + job.crop = (struct v4l2_rect){ 100, 50, 960, 540 }; + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x68), 50 << 16 | 100); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x6c), 25 << 16 | 50); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 960); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x80), 540); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xb4), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xb8), 960); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0xc4), 1080); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), 0); /* no scaling */ + + /* 1920x1080 into 1280x720 at (0, 280) of 1280x1280: the scaler of 1280x720 */ + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1280, 720, 4, 0); + KUNIT_ASSERT_EQ(test, msr23_build(&job, ref, &out), 0); + memset(img, 0, MSR23_IMG_LEN); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1280, 1280, 4, 0); + job.compose = (struct v4l2_rect){ 0, 280, 1280, 720 }; + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + /* written as a 1280x720 picture 280 rows into the planes */ + KUNIT_EXPECT_EQ(test, out.dst_off[0], 280 * 1280 * 4); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x4c), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x40), 1280 * 4); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x5c), 1280); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x60), 720); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x94), 720); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 719 << 16 | 1279); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), msr23_word(ref, MSR23_B0 + 0x68)); + KUNIT_EXPECT_MEMEQ(test, img + 0x9080 / 4, ref + 0x9080 / 4, 0x500); + /* NV12: the chroma plane's offset is in CbCr pairs and chroma rows */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1280, 1280, 1, 1); + job.compose = (struct v4l2_rect){ 64, 280, 1152, 720 }; + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, out.dst_off[0], 280 * 1280 + 64); + KUNIT_EXPECT_EQ(test, out.dst_off[1], 140 * 1280 + 64); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B14 + 0x8c), 576); /* chroma width */ + + /* the source side of the channel map: 0x30 for a conversion at 1:1 only */ + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x7c) & 0xffff, 0x28); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 0x30); + + /* a quarter turn: the source keeps its own size, the pipe the destination's */ + job = (struct msr23_job){}; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1080, 1920, 4, 0); + job.rotate = 90; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x7c), 1920); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B1 + 0x58), 7680); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x68), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x70), 1919 << 16 | 1079); + + /* a conversion at 1:1 with a quarter turn: the matrix where a scaled job has it */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1080, 1920, 1, 1); + job.enc = V4L2_YCBCR_ENC_709; + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x64) & BIT(16), 0); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x6c) & 3, 3); + KUNIT_EXPECT_EQ(test, msr23_word(img, MSR23_B0 + 0x78) & 0xffff, 8); + /* ... and with a mirror or half turn it is refused, unless the job scales */ + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1920, 1080, 1, 1); + job.rotate = 0; + job.hflip = true; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + job.hflip = false; + job.rotate = 180; + KUNIT_EXPECT_EQ(test, msr23_check(&job), -EINVAL); + msr23_pic(&job.dst, V4L2_PIX_FMT_NV12, 1280, 720, 1, 1); + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); + job.rotate = 0; + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + job.hflip = true; + KUNIT_EXPECT_EQ(test, msr23_check(&job), 0); /* same format */ + + /* the orientation codes */ + for (i = 0; i < ARRAY_SIZE(orient); i++) { + bool quarter = orient[i].rotate % 180; + + job = (struct msr23_job){ .rotate = orient[i].rotate, .hflip = orient[i].hflip, + .vflip = orient[i].vflip }; + msr23_pic(&job.src, V4L2_PIX_FMT_ABGR32, 1920, 1080, 4, 0); + msr23_pic(&job.dst, V4L2_PIX_FMT_ABGR32, quarter ? 1080 : 1920, + quarter ? 1920 : 1080, 4, 0); + memset(img, 0, MSR23_IMG_LEN); + KUNIT_ASSERT_EQ(test, msr23_build(&job, img, &out), 0); + KUNIT_EXPECT_EQ_MSG(test, msr23_word(img, MSR23_B0 + 0x64) & 0x78, orient[i].code, + "rotate %u hflip %d vflip %d", orient[i].rotate, + orient[i].hflip, orient[i].vflip); + } } /* @@ -793,6 +959,7 @@ static struct kunit_case asc_test_cases[] = { KUNIT_CASE(asc_test_msr23_csc), KUNIT_CASE(asc_test_msr23_scale), KUNIT_CASE(asc_test_msr23_rejects), + KUNIT_CASE(asc_test_msr23_geometry), KUNIT_CASE(asc_test_msr23_blocks), {} }; From 5f370f8cde82dffd0d39ad4264fd755cefa0b72d Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 21:21:44 +0700 Subject: [PATCH 0784/1514] arm64: dts: apple: t8142: Enable the scaler The MSR23 scaler, its DART and its two power domains are part of the T8142 SoC: enable them in the SoC's peripherals, not per board. A board whose SRAM holds no pre-loaded core image and that has no firmware file fails the probe cleanly (-ENOENT). Tested on the MacBook Air 15" M5 (J815). Signed-off-by: Nick --- arch/arm64/boot/dts/apple/t8142-peripherals.dtsi | 4 ---- 1 file changed, 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi index 949f6da167a896..f2b4ab511ff4df 100644 --- a/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8142-peripherals.dtsi @@ -223,7 +223,6 @@ /* No DART gate in the ADT: powered with its engine. */ power-domains = <&ps_msr>; #iommu-cells = <1>; - status = "disabled"; }; /* ADT dart-jpeg: one DART for both engines, jpeg0 on SID 0, jpeg1 on SID 1. */ @@ -581,7 +580,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "msr"; - status = "disabled"; }; ps_msr_ase_core: power-controller@320 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -590,7 +588,6 @@ #reset-cells = <0>; label = "msr-ase-core"; power-domains = <&ps_msr>; - status = "disabled"; }; /* @@ -803,6 +800,5 @@ clocks = <&peripheral_clocks 399>; power-domains = <&ps_msr>, <&ps_msr_ase_core>; resets = <&ps_msr>; - status = "disabled"; }; }; From f1effbd17a55f3ed3f95d18846963c4718d4a7af Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 14:17:34 +1100 Subject: [PATCH 0785/1514] phy: apple: atc: keep a CIO link when its USB host stops, on every generation The PHY returns to its off mode when the dwc3 host or device on the port stops, except in a CIO mode (USB4 or Thunderbolt) on T8132, where the Type-C mux owns the mode and takes it down when the connection ends. Other generations power the PHY off under a live CIO link instead. dwc3 stops for every data role swap, not only for a cable change. On the M2 Mac mini (J473) with a host-to-host USB4 peer, a partner that leaves and comes back during s2idle can come back with the data roles swapped. At resume dwc3 goes from device to host, which takes the PHY off and back to USB4 within the same millisecond, while the peer is still training the link. The peer times out, the link never trains again, and the XDomain is gone until the next replug or sleep. A partner event in the next s2idle then stops the J473 for good (5 of 6 such sleeps hung on the bench). Nothing about this is specific to T8132: the router owns the lanes in a CIO mode on every generation, and the PIPE is parked before the check either way. Drop the generation from the condition. The Type-C mux still takes a CIO mode down on a real disconnect, an ordinary USB mode still ends with its host, and a CIO mode whose last transition failed is still taken down. Extend the USB3 host model: the CIO cases now run on the T8103 sequence (which T8112 and T600x use) as well as on T8132, and a mutation that restores the T8132-only condition is caught. Signed-off-by: Ryan Murray --- drivers/phy/apple/atc.c | 16 +++++++++------- tools/asahi/atc-usb3-tests.py | 29 +++++++++++++++++------------ 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..a2ca45a8e8b90c 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -4638,14 +4638,16 @@ static int atcphy_usb3_power_off(struct phy *phy) return ret; atcphy->t8103_usb3_retry = false; /* - * T8132 keeps DWC3 on the dummy PIPE while USB4/Thunderbolt owns the - * lanes. Stopping that USB host must not take the dock's PCIe and DP - * tunnels down before their drivers suspend. The Type-C mux owns the - * CIO mode and releases it when the connection ends. A CIO mode whose - * last transition failed is still taken down, as before. + * In USB4/Thunderbolt the router owns the lanes: dwc3 only had its PIPE + * on the router's USB3 adapter (or on the dummy backend), and that is + * parked above. Stopping the USB host, for a cable change or only for a + * data role swap, must not take the router's link down with it: that + * drops a host-to-host link, and a dock's PCIe and DP tunnels, before + * their drivers know. The Type-C mux owns the CIO mode and releases it + * when the connection ends. A CIO mode whose last transition failed is + * still taken down, as before. */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode) && - !atcphy->mode_dirty) + if (atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty) return 0; /* * dwc3 can tear its host down while a DisplayPort alt mode link is up, diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..2894ca2bd5e8da 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -9,7 +9,7 @@ T600x/T8112/T602x still match the T8103 PHY fallback but keep their previous single-poll/BIST/role behavior. OF compatible lookup is a modeled boundary. The DT-to-driver match contract is checked from the actual sources. -T8132 cases cover CIO ownership during USB host shutdown; its lane setup +CIO ownership during USB host shutdown is covered on T8103 and T8132; T8132 lane setup and electrical behavior are not modeled. Hardware qualification remains necessary. Run --mutations for sensitivity checks. """ @@ -398,14 +398,17 @@ def block(source, marker): assert(atcphy_usb3_power_off(&phy)==-ETIMEDOUT);assert(!configure_calls); unlock_ret=0;assert(!atcphy_usb3_power_off(&phy));assert(p.mode==APPLE_ATCPHY_MODE_USB3_DP&&!configure_calls&&!p.t8103_usb3_retry&&!p.t8103_dummy_pending); } -static void t8132_usb_stop_keeps_cio_until_mux_disconnect(void) { +static void usb_stop_keeps_cio_until_mux_disconnect(void) { const enum atcphy_mode modes[] = { APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_USB4 }; - for (unsigned i=0;i<2;i++) { - reset(ATCPHY_GENERATION_T8132,false);p.mode=modes[i];p.typec_mode=modes[i];p.host_active=true; + /* Every generation: T8112 and T600x run the T8103 PHY sequence. */ + const enum atcphy_generation gens[] = { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8132 }; + for (unsigned g=0;g<2;g++) for (unsigned i=0;i<2;i++) { + reset(gens[g],false);p.mode=modes[i];p.typec_mode=modes[i];p.host_active=true; assert(!atcphy_usb3_power_off(&phy)); assert(!p.host_active&&p.mode==modes[i]&&!configure_calls&&atcphy_rpm_busy(&p)); assert(!atcphy_dwc3_reset_assert(&p.rcdev,0)); assert(p.mode==modes[i]&&!configure_calls&&atcphy_rpm_busy(&p)&&usb2_power_off_calls==1); + if (gens[g]!=ATCPHY_GENERATION_T8132) continue; /* the OFF lane setup is modeled for T8132 only */ model_t8132_off=true; assert(!atcphy_mux_switch(&p,APPLE_ATCPHY_MODE_OFF)); assert(p.mode==APPLE_ATCPHY_MODE_OFF&&configure_calls==1&&!atcphy_rpm_busy(&p)); @@ -614,7 +617,7 @@ def block(source, marker): TEST(usb4_and_dead_parking_single_poll);TEST(early_host_and_device);TEST(early_admission_and_failure);TEST(later_off_and_bist_unchanged);TEST(success_only_all_generations); TEST(live_lock_failure_restores_masks);TEST(live_park_then_pending_completion);TEST(legacy_live_dispatch_and_generation);TEST(pending_blocks_lane_and_backend); TEST(canceled_lane_change_reconnects);TEST(role_finishes_pending);TEST(target_failure_preserves_reconnect);TEST(nonusb_commit_clears_retry);TEST(dp_assignment_d_retains_usb3);TEST(modern_safe_refusal_retained); - TEST(fixed_hub_host_dispatch);TEST(reset_release_retries_before_writes);TEST(reset_assert_failure_and_stop);TEST(power_off_preserves_dp_and_finishes_pending);TEST(t8132_usb_stop_keeps_cio_until_mux_disconnect);TEST(setup_known_reset_clears_obligations);TEST(target_mode_table_and_dirty); + TEST(fixed_hub_host_dispatch);TEST(reset_release_retries_before_writes);TEST(reset_assert_failure_and_stop);TEST(power_off_preserves_dp_and_finishes_pending);TEST(usb_stop_keeps_cio_until_mux_disconnect);TEST(setup_known_reset_clears_obligations);TEST(target_mode_table_and_dirty); TEST(lock_timeout_left_to_caller); printf("%u ATCPHY USB3 host cases passed\n",tests); } @@ -731,13 +734,15 @@ def harness(source): return PRELUDE + defines + "\n" + "\n".join(usb_defines) + "\n" + types + "\n" + table + stubs + functions + scope_c + TESTS -MUTATIONS = {'t8132-usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', - '&&\n\t !atcphy->mode_dirty)', ')'), - 't8132-usb-stop-drops-cio': ('atcphy_usb3_power_off', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode)', 'false'), - 't8132-usb-stop-keeps-usb-too': ('atcphy_usb3_power_off', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode)', - 'atcphy->hw->gen == ATCPHY_GENERATION_T8132'), +MUTATIONS = {'usb-stop-keeps-dirty-cio': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty)', 'atcphy_mode_is_cio(atcphy->mode))'), + 'usb-stop-drops-cio': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', 'false'), + 'usb-stop-keeps-usb-too': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', '!atcphy->mode_dirty'), + 'usb-stop-keeps-cio-t8132-only': ('atcphy_usb3_power_off', + 'atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty', + 'atcphy->hw->gen == ATCPHY_GENERATION_T8132 && atcphy_mode_is_cio(atcphy->mode) && !atcphy->mode_dirty'), 'no-live-retry': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 1 : 1;'), 'retry-later-generations': ('atcphy_pipehandler_lock_live', '? 10 : 1;', '? 10 : 10;'), 'sleep-after-last': ('atcphy_pipehandler_lock_live', 'if (attempt + 1 < attempts)', 'if (true)'), From a9654421c21282bc4d092fa9d7b1bf04514c00c2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:32:56 +1100 Subject: [PATCH 0786/1514] drm/apple: dcp: disable the Type-C routes of a processor whose firmware is refused A display processor whose firmware-compat is not supported fails its probe with -ENODEV and never registers the Type-C display routes under its node. The USB-C port controllers that name such a route as their mode switch then wait for it for good: fwnode_typec_mux_get() keeps returning -EPROBE_DEFER, so the port is never registered and USB2, USB3, USB4 and the role switch stay down on every port the processor routes, not only DP alt mode. On the M2 Mac mini (J473) the routes of both USB-C ports sit on the primary DCP, which refuses the 27.2 firmware: both CD321x stay in "deferred probe pending" and neither USB-C port works at all. The firmware cannot change before the next boot, so disable the routes in the device tree on this refusal, as the processor failure paths that already give up for good do (dcp_native_routes_error(), dcp_ext_give_up(), dcp_platform_probe_t8132_ext()). The connector's graph lookup then skips the disabled route endpoints (fwnode_graph_devcon_matches()), the port takes the PHY mode switch alone, and the ports come up without DP alt mode on that processor. The routes stay disabled for the rest of the boot: a driver that would accept the firmware gets them back after a reboot, not by loading a newer module in the same boot. Selected by what the device tree describes (a typec-routes child of the refusing processor); a processor without one is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 0666748f436d0d..b6b5fe71c25336 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7197,8 +7197,16 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) } fw_compat = dcp_check_firmware_version(dev); - if (fw_compat == DCP_FIRMWARE_UNKNOWN) + if (fw_compat == DCP_FIRMWARE_UNKNOWN) { + /* + * The firmware does not change until the next boot, so this + * processor never registers its Type-C display routes: disable + * them, so that the port controllers that name them as their + * mode switch do not wait for them, and USB on the ports goes on. + */ + dcp_typec_routes_disable_dev(dev); return -ENODEV; + } if (fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t6041-dcp"))) { From 1f033871260a9878d42903b1e6674495d85a2aee Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:07:20 +1100 Subject: [PATCH 0787/1514] HID: magicmouse: create the Force Click device after the FF device magicmouse_setup_force_input() ran before input_ff_create(). When input_ff_create() failed, the trackpad was left without haptics but with a registered " Force Click" input device that could never send anything, until the driver was unbound. Set the Force Click device up only once the FF device exists. Signed-off-by: Ryan Murray --- drivers/hid/hid-magicmouse.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index c89f657daf5b44..e4df604fcfcd3f 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -2730,9 +2730,6 @@ static int apple_taptic_init_mtp(struct magicmouse_sc *msc, INIT_WORK(&msc->haptic_deep_release_work, magicmouse_deep_release_worker); - if (haptic_deep_keycode) - magicmouse_setup_force_input(msc); - /* FF_HAPTIC has to be in ffbit before the FF device is created. */ input_set_capability(msc->input, EV_FF, FF_HAPTIC); @@ -2752,6 +2749,13 @@ static int apple_taptic_init_mtp(struct magicmouse_sc *msc, return ret; } + /* + * Only now: if the FF device could not be created there are no + * haptics, and no Force Click device must be left registered. + */ + if (haptic_deep_keycode) + magicmouse_setup_force_input(msc); + ff = msc->input->ff; ff->private = haptic_dev; ff->upload = apple_upload_effects; From 42964d56f523f8f3d2b973340ef3ef955876b03d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:23:46 +1100 Subject: [PATCH 0788/1514] drm/asahi: release G14 27.2 firmware memory after a confirmed stop Two review items on the G14 firmware-27.2 runtime: - fail_all() finished the in-flight render pair without recording the error on its VM, so the client did not see the device failure the compute path reports. Record it for the render pair as for compute. - stop() kept the firmware graph and runtime state for the rest of the boot even when nothing could still reach them. Release them when the stop is confirmed: the drain retired every published command, the firmware reports itself stopped and no RTKit power-off was needed. The state lock is dropped first, so the RTKit teardown does not run under it. Any other stop keeps everything the firmware's page tables name, as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 71742629628a8c..d299bfe2700464 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -589,6 +589,7 @@ impl Runtime { packet.finish(Err(error)); } if let Some(flight) = &state.rendering { + if let Some(status) = flight.packet.vm.status() { status.record(error); } flight.packet.finish(Err(error)); } // Published work stays owned: the firmware may still read it. @@ -1028,6 +1029,8 @@ impl Runtime { self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; + // Nothing published is outstanding: the drain retired every command it accepted. + let drained = !state.running(); self.fail_all(&mut state, ENODEV); let allowed = set_idle_policy(&state.root, &mut state.peer, true); let root = &state.root; @@ -1044,8 +1047,16 @@ impl Runtime { if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } - // Keep everything the firmware could reach for the rest of the boot, halted or not: - // its page tables still name these pages. + // A confirmed stop (no work outstanding, the firmware reports itself stopped without an + // RTKit power-off) leaves nothing that can reach this memory, so it is released and a + // later probe starts over. Otherwise keep everything the firmware could reach for the + // rest of the boot, halted or not: its page tables still name these pages. + if drained && running == Ok(0) && forced.is_none() { + dev_info!(self.dev, "GPU firmware stopped with no work outstanding; memory released\n"); + drop(guard); + drop(state); + return; + } core::mem::forget(state); core::mem::forget(self.graph.clone()); } From 027080fdc15b1386f204f46b01c5fb8cc36b98cc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:28:02 +1100 Subject: [PATCH 0789/1514] drm/asahi: take the G14 27.2 render tiling cluster count from the GPU QueueRender::prepare() passed a literal cluster count of 1 to the tiling parameters. Use the GPU's own num_clusters, as the 13.5 render queue does. The sleep refusal message counted only compute commands; name the in-flight render pair too, since it also holds sleep off. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 3 ++- drivers/gpu/drm/asahi/g14_v27_2_render.rs | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index d299bfe2700464..5876bbfa76703b 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -977,7 +977,8 @@ impl Runtime { return Ok(()); } if remaining == 0 { - dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len()); + dev_err!(self.dev, "GPU: sleep refused, {} compute commands and {} render pairs still running\n", + state.inflight.len(), usize::from(state.rendering.is_some())); self.asleep.store(false, Ordering::Release); self.pump(state); return Err(EBUSY); diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index c21904da32966b..10ce122708dbde 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -113,7 +113,11 @@ impl QueueRender { /// Called with the render data masters idle, so making a fresh binding cannot free memory /// which a previous flight still owns. pub(crate) fn prepare(&self, r: &UapiRenderCommand, usc: u64) -> Result { - let tile = crate::queue::QueueInnerG14V13_5::get_tiling_params(&to_cmdbuf(r), 1)?; + let clusters = + ::get_dyncfg(&self.graph) + .id + .num_clusters; + let tile = crate::queue::QueueInnerG14V13_5::get_tiling_params(&to_cmdbuf(r), clusters)?; self.buffer.ensure_parameter_blocks(tile.min_tvb_blocks)?; let mut alloc = ::alloc(&self.graph); From 25ac88ae153c432faafdf64d5096a6f63e501f39 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 04:28:05 -0500 Subject: [PATCH 0790/1514] drm/asahi: build the G14 firmware-27.2 path without the M3 runtime The G14 firmware-27.2 runtime reuses the 26.x submission front end (m3_submit, agx_uapi and their helpers), so it was built only with CONFIG_DRM_ASAHI_M3_T8122. Give it its own option, DRM_ASAHI_G14_V27_2 (default y), and build the shared front end when either user is enabled: - m3/mod.rs: agx_uapi, agx_compute, agx_attachments, agx_memory and m3_submit build with DRM_ASAHI_M3_T8122 or DRM_ASAHI_G14_V27_2. - m3_submit.rs: the M3 sink, queue constructor, render validation, CDM launch check, timeout handling and fence-timing profile build only with the M3 runtime; without it a render command gets EINVAL. task_comm() moves here from m3_client.rs, which now calls it here. - The G14 path's own code is gated on the new option. Like the M3 runtime, the option depends on DRM_ASAHI_G15: the firmware's UAT is adopted through that backend's handoff helpers (Uat::new_adopted, the G15 UAT table cleaning). Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/Kconfig | 12 +++++ drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/driver.rs | 30 +++++------ drivers/gpu/drm/asahi/event.rs | 4 +- drivers/gpu/drm/asahi/gpu.rs | 10 ++-- drivers/gpu/drm/asahi/hw/mod.rs | 4 +- drivers/gpu/drm/asahi/hw/t8112.rs | 6 +-- drivers/gpu/drm/asahi/m3/m3_client.rs | 15 +----- drivers/gpu/drm/asahi/m3/m3_submit.rs | 72 +++++++++++++++++++++------ drivers/gpu/drm/asahi/m3/mod.rs | 15 +++--- drivers/gpu/drm/asahi/mmu.rs | 6 +-- drivers/gpu/drm/asahi/object.rs | 2 +- drivers/gpu/drm/asahi/regs.rs | 2 +- 13 files changed, 110 insertions(+), 70 deletions(-) diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index d383802ee8825f..c4402190207791 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -95,6 +95,18 @@ config DRM_ASAHI_M3_T8122 boards and firmware do not gain automatic admission. Other GPUs are not affected. +config DRM_ASAHI_G14_V27_2 + bool "Apple M2 (G14G) on GPU firmware 27.2, compute only" + depends on DRM_ASAHI + # The firmware's UAT is adopted through the G15 backend's handoff helpers. + depends on DRM_ASAHI_G15 + default y + help + Start an M2 GPU (G14G) whose boot loader reports GPU firmware + 27.2, and register a compute-only DRM device on it. Clients use + the 26.x submission interface; render commands are refused. + Other GPUs and firmware versions are not affected. + config DRM_ASAHI_G15 bool "Apple M3 Pro/Max (G15) support" depends on DRM_ASAHI diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 5f180203f8369c..e0de39368342d6 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,7 +27,7 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod g14_v27_2; mod hw; mod initdata; diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 95971eaac30315..bf014730a868e8 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -54,7 +54,7 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { pub(crate) g16: Option>, m3: Option, /// The G14 firmware-27.2 backend, whose firmware must be stopped on unbind. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. @@ -276,7 +276,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that // is refused. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { // SAFETY: Reads a global flag word. if unsafe { bindings::pm_suspend_via_firmware() } { @@ -298,7 +298,7 @@ unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_i unsafe extern "C" fn sleep_complete(dev: *mut bindings::device) { // SAFETY: Called by the PM core. let data = unsafe { sleep_data(dev) }; - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { backend.sleep_complete(); } @@ -357,7 +357,7 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = this.g14_v27_2.as_ref() { backend.stop(); } @@ -400,11 +400,11 @@ impl platform::Driver for AsahiPlatformDriver { // The loader advertises the supported wire layout independently of the image version. if has_g14_handoff && compat.as_slice() == [27, 2, 0] { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] return AsahiPlatformDriver::probe_g14_v27_2( pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2, ); - #[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))] + #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] return Err(ENODEV); } @@ -484,7 +484,7 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -499,7 +499,7 @@ impl platform::Driver for AsahiPlatformDriver { impl AsahiPlatformDriver { /// G14 with firmware 27.2: start the firmware and register a compute-only DRM device. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] fn probe_g14_v27_2<'bound>( pdev: &'bound platform::Device>, cfg: &'static hw::HwConfig, @@ -561,7 +561,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -605,7 +605,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), @@ -683,7 +683,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -732,7 +732,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -773,7 +773,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, g16: Some(gpu), raw_dev, @@ -831,7 +831,7 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] g14_v27_2: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, @@ -866,7 +866,7 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = self.g14_v27_2.as_ref() { backend.stop(); } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index a993bca69f5072..dbea26792b6c0c 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,7 +54,7 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn raw(self) -> u32 { self.0 } @@ -205,7 +205,7 @@ impl EventManager { } /// Reserve the normal stamp pair for a kernel queue that polls its own completion. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn try_get_polled(&self) -> Result { self.alloc.try_get(None) } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 2166a7e3dce1ec..e9b715aeca9801 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -112,9 +112,9 @@ pub(crate) const fn init_message(address: u64) -> u64 { } /// The G14 firmware-27.2 root and the records only it uses. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] mod v27_2; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use v27_2::*; const RX_WORK_PENDING: u32 = 1 << 0; @@ -140,7 +140,7 @@ const DOORBELL_DEVCTRL: u64 = 0x11; const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; /// The G14 firmware-27.2 timestamp aperture, inside the private range: the private allocator /// stays below it in that profile. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const IOVA_G14_V27_2_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; @@ -200,7 +200,7 @@ pub(crate) enum GraphProfile { Native, /// The G14 firmware-27.2 root (gpu/v27_2.rs) built on these records: no register /// mappings, and the private range ends below that firmware's timestamp aperture. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] G14V27_2, } @@ -712,7 +712,7 @@ impl GpuManager::ver { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; let private_end = match profile { GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, }; diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index 2fd17c298d68d4..934c52380c43db 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -123,7 +123,7 @@ pub(crate) struct PowerZone { } /// Base of a window in the firmware 27.2 register table. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) enum RegisterBaseV27_2 { /// A fixed physical address. @@ -133,7 +133,7 @@ pub(crate) enum RegisterBaseV27_2 { } /// One record of the firmware 27.2 register table: 60 slots, each naming one window. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] #[derive(Debug, Copy, Clone)] pub(crate) struct RegisterV27_2 { pub(crate) slot: usize, diff --git a/drivers/gpu/drm/asahi/hw/t8112.rs b/drivers/gpu/drm/asahi/hw/t8112.rs index 1879be7f8ceade..d22238d90247b1 100644 --- a/drivers/gpu/drm/asahi/hw/t8112.rs +++ b/drivers/gpu/drm/asahi/hw/t8112.rs @@ -105,7 +105,7 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_size: None, }; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, install: Option) -> RegisterV27_2 { RegisterV27_2 { slot, base, size, relative, install } } @@ -113,7 +113,7 @@ const fn reg(slot: usize, base: RegisterBaseV27_2, size: u32, relative: u64, ins /// The firmware 27.2 register table. Writable windows outside SGX are left unmapped, except /// the push-telemetry window (slot 9), which the firmware shares with the PMP; it is mapped /// apart from the others. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { use RegisterBaseV27_2::{Physical, Sgx}; &[ @@ -136,7 +136,7 @@ pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { }; /// Slots of the 27.2 register table whose stock mode is read-write. -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) const WRITABLE_V27_2: u64 = { let mut mask = 0u64; let mut slot = 0; diff --git a/drivers/gpu/drm/asahi/m3/m3_client.rs b/drivers/gpu/drm/asahi/m3/m3_client.rs index c1a07d61120d13..7d9169fe1ecc0f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_client.rs +++ b/drivers/gpu/drm/asahi/m3/m3_client.rs @@ -63,7 +63,7 @@ pub(crate) fn admit_vm_for( let refusals = REFUSALS.fetch_add(1, Ordering::Relaxed).saturating_add(1); if refusals <= REFUSALS_LOGGED { let task = kernel::current!(); - let comm = task_comm(task); + let comm = super::m3_submit::task_comm(task); let len = comm.iter().position(|&b| b == 0).unwrap_or(comm.len()); let name = core::str::from_utf8(&comm[..len]).unwrap_or("?"); let last = if refusals == REFUSALS_LOGGED { @@ -87,19 +87,6 @@ pub(crate) fn admit_vm_for( } } -/// The name of `task`, for log lines only. -pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { - let mut name = [0u8; 16]; - // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with - // volatile loads because a concurrent rename may change it; a torn name is only printed. - unsafe { - let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); - for (i, byte) in name.iter_mut().enumerate() { - *byte = comm.add(i).read_volatile(); - } - } - name -} /// Bytes at the start of a compute control stream whose launch records are checked. const LAUNCH_WINDOW: usize = 4096; diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index b8a377264be8fa..df0a26e4babc9d 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -1,7 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; -use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::{file,m3::agx_uapi,mmu,queue}; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +use crate::m3::m3_drm::Shared; use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] @@ -59,7 +61,12 @@ pub(crate) struct Packet { } /// The runtime a queue's packets go to: the M3 runtime or the G14 firmware-27.2 compute runtime. #[derive(Clone)] -pub(crate) enum Sink { M3(Shared), G14V27_2(Arc) } +pub(crate) enum Sink { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + M3(Shared), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + G14V27_2(Arc), +} /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -68,8 +75,7 @@ impl Owner { fn current()->Self { let task=kernel::current!(); let leader=task.group_leader(); - Self {pid:leader.pid(),process:crate::m3::m3_client::task_comm(leader), - thread:crate::m3::m3_client::task_comm(task)} + Self {pid:leader.pid(),process:task_comm(leader),thread:task_comm(task)} } fn name(comm:&[u8;16])->&str { let len=comm.iter().position(|&b|b==0).unwrap_or(comm.len()); @@ -78,6 +84,19 @@ impl Owner { pub(crate) fn process(&self)->&str {Self::name(&self.process)} pub(crate) fn thread(&self)->&str {Self::name(&self.thread)} } +/// The name of `task`, for log lines only. +pub(crate) fn task_comm(task: &kernel::task::Task) -> [u8; 16] { + let mut name = [0u8; 16]; + // SAFETY: `comm` is a fixed-size array inside the live task. It is read byte by byte with + // volatile loads because a concurrent rename may change it; a torn name is only printed. + unsafe { + let comm = core::ptr::addr_of!((*task.as_ptr()).comm).cast::(); + for (i, byte) in name.iter_mut().enumerate() { + *byte = comm.add(i).read_volatile(); + } + } + name +} impl Packet { pub(crate) fn profile_id(&self)->usize {self as *const Self as usize} pub(crate) fn timestamp_addresses(&self,index:usize)->[u64;2] { @@ -113,9 +132,12 @@ impl Packet { // nonzero: GEM closes otherwise accumulate across completed frames. // Signalling an error is not retirement. crate::m3::agx_memory::publish(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let profile=crate::debug::debug_enabled(crate::debug::DebugFlags::M3PassTiming); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] let before=if profile {crate::m3::m3_runtime::physical_counter()} else {0}; self.completion.signal(); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if profile { let after=crate::m3::m3_runtime::physical_counter(); let status=match result {Ok(())=>0,Err(e)=>e.to_errno()}; @@ -136,7 +158,9 @@ impl sched::JobImpl for Job { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. let submitted=match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>runtime.submit(job.packet.clone()), }; if let Err(e)=submitted { @@ -147,8 +171,10 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { - let shared=match &job.shared { - Sink::M3(shared)=>shared.clone(), + match job.shared.clone() { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>Self::timed_out_m3(shared,job), + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] Sink::G14V27_2(runtime)=>{ // The runtime's own command timeout fails a hung GPU; a healthy one is late. // Run its service once, so a hang is found without a notification. @@ -156,9 +182,23 @@ impl sched::JobImpl for Job { if runtime.healthy() {return sched::Status::NoHang;} runtime.withdraw(&job.packet); job.packet.finish(Err(EIO)); - return sched::Status::NoDevice; + sched::Status::NoDevice } - }; + } + } + fn cancel(job:&mut Self) { + match &job.shared { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), + } + job.packet.finish(Err(ECANCELED)); + } +} +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +impl Job { + fn timed_out_m3(shared:Shared,job:&mut JobTimeout)->sched::Status { // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} @@ -180,13 +220,6 @@ impl sched::JobImpl for Job { job.packet.finish(Err(EIO)); sched::Status::NoDevice } - fn cancel(job:&mut Self) { - match &job.shared { - Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} - Sink::G14V27_2(runtime)=>runtime.withdraw(&job.packet), - } - job.packet.finish(Err(ECANCELED)); - } } struct AddressSpace<'a>(&'a mmu::Vm); impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { @@ -210,6 +243,7 @@ pub(crate) struct Queue { urgency:u8, } impl Queue { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] pub(crate) fn new(shared:Shared,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, early_tiling:bool, wide_visibility:bool)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -222,6 +256,7 @@ impl Queue { early_tiling,wide_visibility,urgency,preempt_alloc:None}) } /// A G14 firmware-27.2 compute queue: the same front end, published by that runtime. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn new_g14_v27_2(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, ualloc_priv:Arc>,preempt_bytes:usize)->Result { agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; @@ -239,8 +274,11 @@ impl queue::Queue for Queue { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { + // Only the M3 runtime renders; the G14 firmware-27.2 runtime is compute-only. + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + if let agx_uapi::ParsedHardwareCommand::Render{..}=command {return Err(EINVAL);} + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { - // The G14 firmware-27.2 runtime is compute-only. if self.preempt_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); @@ -279,6 +317,7 @@ impl queue::Queue for Queue { EINVAL })?; // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] if self.preempt_alloc.is_none() { crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; } @@ -325,6 +364,7 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) Ok(out) } +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, early_tiling: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index cb64aa8f1ecbcc..eec633d1301991 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -70,17 +70,18 @@ pub(crate) fn t8122_admitted(pdev: &platform::Device>) -> Result<&'stat } // The T8122 runtime, ported from the 7.1.12 release-20 kernel (c46d7dcdb871). -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +// The 26.x submission front end, shared with the G14 firmware-27.2 runtime. +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_attachments; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_compute; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] mod agx_memory; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; @@ -124,7 +125,7 @@ mod m3_resources; mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; -#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[cfg(any(CONFIG_DRM_ASAHI_M3_T8122, CONFIG_DRM_ASAHI_G14_V27_2))] pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; @@ -209,7 +210,7 @@ pub(crate) mod m3_mmio_26; mod m3_power_26; pub(crate) mod m3_channel_format; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_channel_format::{idle_cursor, submission_entry, Action, CONTROL_BYTES}; -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 053dccbcc965cd..3cca4f5a37fe6b 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -4521,13 +4521,13 @@ mod execution_context_tests { } /// The word GPU firmware 27.2 on G14 exchanges through the handoff region's magic fields. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] const MAGIC_G14_V27_2: u64 = 0x4b1d000000000003; /// The loader's UAT regions as GPU firmware 27.2 on G14 uses them. The driver mirrors its /// kernel window into the firmware's shared second-level table and names its own trees in /// TTBAT context 0 before the ASC starts. -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) struct FirmwareWindow { handoff: UatRegion, ttbs: UatRegion, @@ -4538,7 +4538,7 @@ pub(crate) struct FirmwareWindow { pa_mask: u64, } -#[cfg(CONFIG_DRM_ASAHI_G15)] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl FirmwareWindow { /// Maps the four regions. Fails with `EBUSY` unless the handoff is idle and the shared /// table and context 0 are empty. diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index e3ce17cb7cb7ee..ef7027ff1a6363 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -697,7 +697,7 @@ impl> GpuArray { } } -#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] impl> GpuArray { /// Aligned index in a shared firmware ring, accessed without borrowing its payload. pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { diff --git a/drivers/gpu/drm/asahi/regs.rs b/drivers/gpu/drm/asahi/regs.rs index 658c98de1e77ac..7e40d4b137ba9f 100644 --- a/drivers/gpu/drm/asahi/regs.rs +++ b/drivers/gpu/drm/asahi/regs.rs @@ -351,7 +351,7 @@ impl Resources<'_> { /// The G14 Fender operating-point word: requested index in bits 3:0, request pending in /// bit 4. Sampled while the firmware holds the GPU powered. - #[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] pub(crate) fn operating_point(&self) -> u32 { self.sgx_read32::<0xd01000>() } From 6a15a79e84dca1420ad94ecc07e4923da3813b3d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 20 Nov 2026 15:32:27 -0500 Subject: [PATCH 0791/1514] drm/asahi: report the G14 firmware-27.2 device as compute-only The G14 firmware-27.2 runtime refuses render commands, but nothing in GET_PARAMS says so. Graphics userspace therefore takes the device for GL: on phellos (J413) with the GPU published, kmsro picked the aurora render node for the internal panel, and the greeter's Hyprland and sddm-greeter-qt aborted after their first renders failed with EINVAL. Add DRM_ASAHI_FEATURE_COMPUTE_ONLY (bit 41; bits 39 and 40 are claimed by open PRs #2059 and #2523) and set it on that runtime. It is a property of the device, not of a board or chip list: Mesa can decline to create a graphics screen or a graphics queue on a device that reports it, and fall back to software rendering, while compute keeps working. Kernels without the bit keep their current behaviour. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g14_v27_2.rs | 6 +++++- include/uapi/drm/asahi_drm.h | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index b77cd15cc9a20d..ac8fcc907db5f8 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -6,7 +6,8 @@ //! installs the driver's kernel window in the loader's UAT regions, starts the ASC, holds the //! GPU powered and retires one kernel-owned compute job. [`Backend`] then serves clients //! through the 26.x submission front end (`m3_submit`): each compute command is encoded in the -//! 27.2 layout and published, in order, on the root's queue. Render commands are refused. +//! 27.2 layout and published, in order, on the root's queue. Render commands are refused, and the device +//! reports `DRM_ASAHI_FEATURE_COMPUTE_ONLY`. //! //! The runtime is driven by the firmware's endpoint-0x20 notifications, which it sends after //! publishing records on its event, statistics and log rings: each one runs the service, which @@ -862,9 +863,12 @@ impl gpu::Gpu for Backend { Ok(()) } fn supports_vm_status(&self) -> bool { true } + /// Render commands are refused (`m3_submit`), so the device also reports itself + /// compute-only: graphics userspace then leaves it alone instead of failing its first render. fn feature_flags(&self) -> u64 { uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 + | uapi::DRM_ASAHI_FEATURE_COMPUTE_ONLY as u64 } fn tracked_submission(&self) -> bool { true } fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 75301a90c564c0..7193c1ef7e4546 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -535,6 +535,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_RENDER_MESH_OUTPUT ((1ULL) << 38) +/* + * DRM_ASAHI_FEATURE_COMPUTE_ONLY: the device runs compute commands only. + * DRM_ASAHI_CMD_RENDER is refused, so the device cannot serve graphics APIs; + * userspace should not offer it for them. Compute commands, the VM and GEM + * interfaces are unaffected. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 From 3cc633f67993d888abbd2794f64b8f7175531212 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:36:28 +1100 Subject: [PATCH 0792/1514] drm/asahi: keep G14 27.2 firmware memory after every stop The release added for a confirmed stop freed the runtime state and the firmware graph while the boot handoff window, which start() keeps for the life of the boot, still references the graph's page tables. That leaves stale roots behind and can break a later bind. Keep everything the firmware could reach after any stop again, as before, and say why; releasing it needs the window torn down first. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 5876bbfa76703b..e9edc12813ab43 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1030,8 +1030,6 @@ impl Runtime { self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; - // Nothing published is outstanding: the drain retired every command it accepted. - let drained = !state.running(); self.fail_all(&mut state, ENODEV); let allowed = set_idle_policy(&state.root, &mut state.peer, true); let root = &state.root; @@ -1048,16 +1046,10 @@ impl Runtime { if running != Ok(0) && forced != Some(Ok(())) { dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); } - // A confirmed stop (no work outstanding, the firmware reports itself stopped without an - // RTKit power-off) leaves nothing that can reach this memory, so it is released and a - // later probe starts over. Otherwise keep everything the firmware could reach for the - // rest of the boot, halted or not: its page tables still name these pages. - if drained && running == Ok(0) && forced.is_none() { - dev_info!(self.dev, "GPU firmware stopped with no work outstanding; memory released\n"); - drop(guard); - drop(state); - return; - } + // Keep everything the firmware could reach for the rest of the boot, halted or not: + // its page tables still name these pages, and the boot handoff window that start() + // keeps for the life of the boot still references the graph's tables. Releasing them + // needs that window torn down first, which this runtime does not do. core::mem::forget(state); core::mem::forget(self.graph.clone()); } From 7fa1b919892457dd443ea7d2947909a1cbac8be3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:38:05 +1100 Subject: [PATCH 0793/1514] drm/apple: dpavservep: take a fixed output's AV service again after a sleep A DP AV service is taken only while the attachment it was announced for is current: the announcement's generation must be the DCP's, and once the generation has moved on, a Type-C output waits for its cable again. Every sleep and DPMS cycle moves the generation on (dcp_disable_typec_work()), also on a DCP whose output is fixed and has no Type-C cable at all. On the M2 Mac mini the HDMI port is such a fixed output: its MCDP29xx converter's AV service was admitted at boot, but after the first s2idle the re-announced service was refused (-ENODEV, generation 2, no cable) on every wake, so HDMI lost the service that publishes its EDID. A fixed output that no Type-C display has borrowed has no cable to wait for. Admit its services from the current generation; one announced before the sleep still is not taken after it. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index 655fe1e5e58cde..b3460c45c1f564 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -17,6 +17,7 @@ #include "../afk.h" #include "../dcp.h" #include "../dcp-internal.h" +#include "../dcp-fabric.h" #include "../connector.h" #include "../trace.h" @@ -66,10 +67,15 @@ static bool dcpavserv_identity(struct apple_epic_service *service, const char *n static bool dcpavserv_admission_current(struct apple_dcp *dcp, u64 generation) { lockdep_assert_held(&dcp->hpd_mutex); - /* Initial service discovery may precede the first Type-C attachment. */ + /* + * Initial service discovery may precede the first Type-C attachment. A + * fixed output that no Type-C display has borrowed (the HDMI port) has no + * Type-C cable to wait for: every sleep and DPMS cycle still moves the + * generation on, so a service announced before it is not taken after it. + */ return !READ_ONCE(dcp->quiescing) && !READ_ONCE(dcp->external_physically_absent) && generation == dcp->typec_generation && - (!generation || dcp->typec_cable_connected); + (!generation || dcp->typec_cable_connected || !dcp_is_typec_output(dcp)); } /* Admission runs before AFKV2 OPEN and before readers can pin the service. */ From 06e155e8efacb74ddef7d1ebf3af5ba9c5d68f8e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 15:38:06 +1100 Subject: [PATCH 0794/1514] tools/asahi: test the DP AV service admission across sleeps Build the real dcpavserv_admission_current() and dcp_is_typec_output() against a small model: a fixed HDMI output at boot and after a sleep, a stale announcement, quiescing, a physically absent display, a Type-C output before attach, unplugged and plugged, an HDMI port a Type-C display borrowed, and a fixed USB-C output. Four mutations (the old cable wait, no generation check, no cable check, no quiescing check) must fail. Signed-off-by: Ryan Murray --- tools/asahi/dpavserv-admission-tests.py | 117 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 2 files changed, 121 insertions(+) create mode 100755 tools/asahi/dpavserv-admission-tests.py diff --git a/tools/asahi/dpavserv-admission-tests.py b/tools/asahi/dpavserv-admission-tests.py new file mode 100755 index 00000000000000..22e200283b483c --- /dev/null +++ b/tools/asahi/dpavserv-admission-tests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the actual DP AV service admission check over the output states. + +A DCP takes a DP AV service only while the attachment it was announced for +is current. Every sleep and DPMS cycle moves the DCP's generation on; a +Type-C output then waits for its cable again. A fixed output that no Type-C +display has borrowed (the M2 Mac mini's HDMI port) has no Type-C cable: once +the generation had moved, its converter's AV service was refused for good, +so HDMI lost its EDID and stayed dark after the first sleep. The fixture +builds the real dcpavserv_admission_current() from epic/dpavservep.c and the +real dcp_is_typec_output() from dcp-fabric.c against a small model. + +--mutation names a change to the production function that the matrix must +kill. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DPAV = "drivers/gpu/drm/apple/epic/dpavservep.c" +FABRIC = "drivers/gpu/drm/apple/dcp-fabric.c" + +MUTATIONS = { + # The old check: a fixed output waits for a Type-C cable it never gets. + "old-cable-wait": (DPAV, " || !dcp_is_typec_output(dcp))", ")"), + # Admit a stale announcement from before a sleep. + "ignore-generation": (DPAV, "generation == dcp->typec_generation &&", ""), + # Admit on a borrowed (Type-C) route without its cable. + "ignore-cable": (DPAV, "dcp->typec_cable_connected ||", "true ||"), + # Admit while the DCP is quiescing. + "ignore-quiescing": (DPAV, "!READ_ONCE(dcp->quiescing) && ", ""), +} + +HARNESS = r''' +#include +#include +#include +typedef uint64_t u64; +#define READ_ONCE(x) (x) +#define lockdep_assert_held(x) ((void)(x)) +#define DRM_MODE_CONNECTOR_HDMIA 11 +#define DRM_MODE_CONNECTOR_USB 20 +struct apple_dcp { + int hpd_mutex; + bool quiescing, external_physically_absent, typec_cable_connected; + u64 typec_generation; + void *active_typec_route; + int fixed_connector_type; +}; +@@FUNCS@@ +int main(void) +{ + int route, fail = 0; + struct apple_dcp d; +#define CASE(name, expect, ...) do { d = (struct apple_dcp){ __VA_ARGS__ }; \ + bool got = dcpavserv_admission_current(&d, d.typec_generation); \ + if (got != (expect)) { printf("FAIL line %d %s: got %d\n", __LINE__, name, got); fail++; } \ + else printf("ok %s\n", name); } while (0) +#define STALE(name, ...) do { d = (struct apple_dcp){ __VA_ARGS__ }; \ + bool got = dcpavserv_admission_current(&d, d.typec_generation - 1); \ + if (got) { printf("FAIL line %d %s: stale admitted\n", __LINE__, name); fail++; } \ + else printf("ok %s\n", name); } while (0) + CASE("hdmi at boot", true, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA); + CASE("hdmi after a sleep", true, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3); + STALE("hdmi stale announcement", .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3); + CASE("hdmi quiescing", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .typec_generation = 3, .quiescing = true); + CASE("hdmi physically absent", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .external_physically_absent = true); + CASE("typec before first attach", true, .active_typec_route = &route); + CASE("typec unplugged", false, .active_typec_route = &route, .typec_generation = 2); + CASE("typec plugged", true, .active_typec_route = &route, .typec_generation = 2, .typec_cable_connected = true); + STALE("typec stale announcement", .active_typec_route = &route, .typec_generation = 2, .typec_cable_connected = true); + CASE("hdmi borrowed by typec, unplugged", false, .fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA, .active_typec_route = &route, .typec_generation = 2); + CASE("fixed usb-c output unplugged", false, .fixed_connector_type = DRM_MODE_CONNECTOR_USB, .typec_generation = 2); + printf("%d failures\n", fail); + return fail != 0; +} +''' + +def extract(path, sig): + src = (ROOT / path).read_text() + m = re.search(r'^%s\(struct apple_dcp \*dcp[^)]*\)\n\{.*?^\}\n' % re.escape(sig), src, re.S | re.M) + if not m: + sys.exit(f"{sig} not found in {path}") + return path, m.group(0) + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mutation", choices=sorted(MUTATIONS)) + a = ap.parse_args() + parts = [extract(FABRIC, "bool dcp_is_typec_output"), + extract(DPAV, "static bool dcpavserv_admission_current")] + code = [] + for path, text in parts: + if a.mutation and MUTATIONS[a.mutation][0] == path: + old, new = MUTATIONS[a.mutation][1:] + if text.count(old) != 1: + sys.exit(f"mutation {a.mutation} does not apply exactly once") + text = text.replace(old, new) + code.append(text) + with tempfile.TemporaryDirectory() as tmp: + c = Path(tmp) / "t.c" + exe = Path(tmp) / "t" + c.write_text(HARNESS.replace("@@FUNCS@@", "\n".join(code))) + flags = ["-std=gnu11", "-Wall"] + ([] if a.mutation else ["-Werror"]) + subprocess.run([os.environ.get("CC", "cc"), *flags, "-o", exe, c], check=True) + r = subprocess.run([exe], capture_output=True, text=True) + print(r.stdout + r.stderr, end="") + sys.exit(r.returncode) + +if __name__ == "__main__": + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 3d4e02c2ce8f50..20563ad452f74f 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -177,6 +177,10 @@ def mutations(flag, names, base, expect=KILL): 'missing-control-firmware', 'missing-control-descriptor', 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), + # A fixed (non-Type-C) output takes its DP AV service again after a sleep. + 'dpavserv-admission-tests.py': [([], PASS)] + + mutations('--mutation', ('old-cable-wait', 'ignore-generation', 'ignore-cable', + 'ignore-quiescing'), []), 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), From f6664294c29b16757b53cfb04c0659bace80074e Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Mon, 23 Nov 2026 18:27:56 -0500 Subject: [PATCH 0795/1514] wifi: mt7932: admit a TKIP group cipher on WPA2-PSK at connect time mt7932_connect_auth() accepts a TKIP group cipher for WPA2-PSK, but mt_connect_prepare() then checks the target BSS's RSN element with mt7932_rsn_admit(), which still required a CCMP group cipher. A WPA/WPA2 mixed-mode AP advertises TKIP as its group cipher, so the connect was refused with -EINVAL before the firmware was asked to join. Accept a TKIP group cipher in mt7932_rsn_admit() for AKM 2 (PSK) only. CCMP stays required in the pairwise list, and mt7932_rsn_admit() still requires a CCMP group cipher for PSK-SHA256 and SAE. The connect path calls it for PSK and PSK-SHA256 only. Add KUnit coverage for a mixed-mode RSN element: admitted on PSK with and without MFPC, refused on PSK-SHA256 and SAE while the same element with a CCMP group admits them, and refused when the pairwise list lacks CCMP or the group cipher is WEP-40. Note in the documentation that a supplicant may now list TKIP-only and WPA1 networks, which the connect request then refuses. Signed-off-by: Scott Jones --- .../device_drivers/wifi/mt7932-neo.rst | 4 +- .../wireless/mediatek/mt7932/association.h | 11 ++- .../wireless/mediatek/mt7932/pmf-lpi-test.c | 67 +++++++++++++++++++ 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst index b4ae52ee79856f..236b6e1dfeb647 100644 --- a/Documentation/networking/device_drivers/wifi/mt7932-neo.rst +++ b/Documentation/networking/device_drivers/wifi/mt7932-neo.rst @@ -157,7 +157,9 @@ qualification. SAE-PK, SAE-EXT-KEY and additional ciphers are not advertised. OW TKIP is registered so that WPA2-PSK can join a WPA/WPA2 mixed-mode access point, which pairs a CCMP unicast key with a TKIP group key. Pairwise TKIP, WPA1, and a -TKIP group key with SAE or OWE are refused. Firmware owns the TKIP group key like +TKIP group key with SAE or OWE are refused. Because TKIP is in the cipher list, +a supplicant may offer a TKIP-only or WPA1 network as selectable; the connect +request then fails with ``-EOPNOTSUPP``. Firmware owns the TKIP group key like any other. MIC failure reporting and TKIP countermeasures are left to firmware and have not been verified: firmware runs the four-way handshake, so the host has no KCK and calling ``cfg80211_michael_mic_failure()`` would do nothing. diff --git a/drivers/net/wireless/mediatek/mt7932/association.h b/drivers/net/wireless/mediatek/mt7932/association.h index 20d5f5c58e9042..e6e161c84700bf 100644 --- a/drivers/net/wireless/mediatek/mt7932/association.h +++ b/drivers/net/wireless/mediatek/mt7932/association.h @@ -127,6 +127,9 @@ static inline int mt7932_connect_psk_akm(u8 *body, size_t length, u32 akm) /* Validate the entire RSN payload before using capabilities for admission. * The group management suite defaults to BIP-CMAC-128 when omitted. Reject * unsupported explicit suites rather than letting firmware choose one. + * A WPA/WPA2 mixed-mode AP advertises a TKIP group cipher. Admit it for + * WPA2-PSK (AKM 2) only, as mt7932_connect_auth() does; the pairwise list + * must still offer CCMP. */ static inline int mt7932_rsn_admit(const u8 *rsn, size_t length, u32 akm, enum nl80211_mfp mfp, bool *pmf) @@ -134,11 +137,15 @@ static inline int mt7932_rsn_admit(const u8 *rsn, size_t length, u32 akm, unsigned int count, i; u16 caps = 0; bool selected = false, ccmp = false; + u32 group; *pmf = false; if (mfp > NL80211_MFP_OPTIONAL || length < 8 || - get_unaligned_le16(rsn) != 1 || - get_unaligned_be32(rsn + 2) != WLAN_CIPHER_SUITE_CCMP) + get_unaligned_le16(rsn) != 1) + return -EINVAL; + group = get_unaligned_be32(rsn + 2); + if (group != WLAN_CIPHER_SUITE_CCMP && + (group != WLAN_CIPHER_SUITE_TKIP || akm != WLAN_AKM_SUITE_PSK)) return -EINVAL; rsn += 6; length -= 6; diff --git a/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c b/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c index 59c9633c954df0..2dfa0eb23d00d7 100644 --- a/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c +++ b/drivers/net/wireless/mediatek/mt7932/pmf-lpi-test.c @@ -146,6 +146,72 @@ static void mt_pmf_admission_test(struct kunit *test) 0); } +/* WPA/WPA2 mixed mode: TKIP group, CCMP and TKIP pairwise, AKMs 2, 6 and 8, + * MFPC set so that only the group cipher decides admission. + */ +static const u8 mixed_rsn[] = { + 48, 32, 1, 0, 0, 15, 172, 2, 2, 0, 0, 15, 172, 4, 0, 15, 172, 2, + 3, 0, 0, 15, 172, 2, 0, 15, 172, 6, 0, 15, 172, 8, 128, 0, +}; + +static void mt_tkip_group_admission_test(struct kunit *test) +{ + static const u32 akms[] = { WLAN_AKM_SUITE_PSK_SHA256, + WLAN_AKM_SUITE_SAE }; + u8 ies[sizeof(mixed_rsn)]; + unsigned int i; + bool pmf; + + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(mixed_rsn, sizeof(mixed_rsn), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + 0); + KUNIT_EXPECT_TRUE(test, pmf); + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[32] = 0; /* no MFPC, as most mixed-mode APs */ + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_NO, &pmf), + 0); + KUNIT_EXPECT_FALSE(test, pmf); + /* A TKIP group stays refused for every other AKM; with a CCMP group + * the same element admits them, so the group cipher is the reason. + */ + for (i = 0; i < ARRAY_SIZE(akms); i++) { + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(mixed_rsn, + sizeof(mixed_rsn), akms[i], + NL80211_MFP_OPTIONAL, + &pmf), + -EINVAL); + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[7] = 4; /* CCMP group */ + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), akms[i], + NL80211_MFP_OPTIONAL, + &pmf), + 0); + } + /* The pairwise list must still offer CCMP. */ + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[13] = 2; + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + -EINVAL); + /* WEP-40 and other group suites stay refused on AKM 2. */ + memcpy(ies, mixed_rsn, sizeof(ies)); + ies[7] = 1; + KUNIT_EXPECT_EQ(test, + mt7932_connect_admit(ies, sizeof(ies), + WLAN_AKM_SUITE_PSK, + NL80211_MFP_OPTIONAL, &pmf), + -EINVAL); +} + static void mt_pmf_body_test(struct kunit *test) { static const struct mt7932_peer_ids ids = { { 1, 2 }, { 3, 4, 5, 6 } }; @@ -442,6 +508,7 @@ static void mt_6g_tpe_golden_test(struct kunit *test) static struct kunit_case mt_pmf_lpi_cases[] = { KUNIT_CASE(mt_pmf_admission_test), + KUNIT_CASE(mt_tkip_group_admission_test), KUNIT_CASE(mt_pmf_body_test), KUNIT_CASE(mt_6g_ap_test), KUNIT_CASE(mt_6g_tpe_body_test), From f3c1254bab8c99c235c56f65bc0a4ea3e0690fd7 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Mon, 23 Nov 2026 18:37:24 -0500 Subject: [PATCH 0796/1514] dt-bindings: display: apple: intersect the common scanout aperture The display subsystem's apple,dma-range was described as overriding the aperture of each referenced DART stream. The DART driver now keeps the bits above a DART's address width as the alias and intersects the rest with each stream's window, so the aperture never extends past any of them. Describe that. Signed-off-by: Scott Jones --- .../bindings/display/apple,display-subsystem.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml index d2f0438188560e..2bff1703d7c945 100644 --- a/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml +++ b/Documentation/devicetree/bindings/display/apple,display-subsystem.yaml @@ -56,9 +56,11 @@ properties: minItems: 2 maxItems: 2 description: - Common scanout DMA aperture, encoded as a base and nonzero size. This - overrides the default aperture of each referenced DART stream. Other - consumers of the same DART retain their own apertures. + Common scanout DMA aperture, encoded as a base and nonzero size. Bits + above a DART's address width select the alias the display uses; the + remaining bits are intersected with the window of each referenced DART + stream, so the aperture never extends past any of them. Other consumers + of the same DART retain their own apertures. required: - compatible From 7e604265b39b28802f681b6b55d9dda9abcb6d75 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Mon, 23 Nov 2026 18:37:24 -0500 Subject: [PATCH 0797/1514] iommu/apple-dart: intersect consumer apertures with each stream window A consumer's apple,dma-range replaced the window of every DART stream it used, and domain allocation then used the raw consumer window again. The DART translates only the low ias bits of an IOVA, so the consumer window could reach addresses that one of its streams excludes. On T8122 the display subsystem's aperture is 0x10000000000..0x10fffffffff and dispext0_dart excludes its top 64 KiB (0xfffff0000..0xfffffffff). Once dispext0_dart joins the display, the top 64 KiB of the shared aperture masks into that excluded range, and iommu-dma allocates top-down, so the first buffers land there. Keep the consumer's bits above ias as the alias, intersect its low bits with the stream's window masked the same way, and refuse a consumer window that does not overlap a stream's window. of_xlate already intersects the streams, so finalize the domain with that master window and drop the separate consumer window kept by domain allocation. Every other in-tree consumer with apple,dma-range sits on a DART whose window is the full ias range, or one that covers the consumer window (the T6041 JPEG DARTs, which need ias >= 42 to probe), so its window does not change. Update the J613 consumer case to expect 0x10000000000..0x10ffffeffff for the external DART and for a five-cell stream window, and add cases for disjoint and single-page overlaps. Fixes: 6245efd7da26 ("iommu/apple-dart: honor consumer apertures before intersecting streams") Signed-off-by: Scott Jones --- drivers/iommu/apple-dart-test.c | 62 ++++++++++++++++++++++++++++++--- drivers/iommu/apple-dart.c | 49 +++++++++++++------------- 2 files changed, 83 insertions(+), 28 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index f5c8efc52e7f9e..b5cfa8b1ccd9b4 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -113,7 +113,11 @@ static void apple_dart_test_consumer_window(struct kunit *test) dart->pgsize = SZ_16K; dev->of_node = &node; - /* J613's common scanout aperture must survive both DART defaults. */ + /* + * J613's common scanout alias survives both DART defaults, but only + * inside each stream's own window: the external DART excludes its top + * 64 KiB, so the shared aperture must too. + */ for (i = 0; i < 2; i++) { dart->dma_min = i ? 0 : 0x10000000000; dart->dma_max = i ? 0xffffeffff : 0x10fffffffff; @@ -121,17 +125,18 @@ static void apple_dart_test_consumer_window(struct kunit *test) &dma_min, &dma_max); KUNIT_EXPECT_EQ(test, ret, 0); KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); - KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10fffffffff); + KUNIT_EXPECT_EQ(test, dma_max, + (dma_addr_t)(i ? 0x10ffffeffff : 0x10fffffffff)); } - /* Domain allocation gives the consumer priority over five-cell args too. */ + /* A five-cell stream window narrows the consumer aperture the same way. */ args.args_count = 5; args.args[3] = 0xf; args.args[4] = 0xffff0000; ret = apple_dart_parse_dma_window(dev, dart, &args, &dma_min, &dma_max); KUNIT_EXPECT_EQ(test, ret, 0); KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10000000000); - KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10fffffffff); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10ffffeffff); /* An override must not make a malformed stream specifier acceptable. */ args.args[3] = 0; @@ -149,6 +154,54 @@ static void apple_dart_test_consumer_window(struct kunit *test) KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0xffffeffff); } +static void apple_dart_test_disjoint_consumer_window(struct kunit *test) +{ + /* 2 GiB at the 1 TiB alias; its low bits start at 2 GiB. */ + __be64 value[] = { cpu_to_be64(0x10080000000), cpu_to_be64(SZ_2G) }; + struct property property = { + .name = "apple,dma-range", + .length = sizeof(value), + .value = value, + }; + struct device_node node = { .properties = &property }; + struct of_phandle_args args = { .args_count = 1 }; + struct apple_dart *dart; + struct device *dev; + dma_addr_t dma_min, dma_max; + + dev = kunit_device_register(test, "apple-dart-disjoint-window-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->ias = 36; + dart->pgsize = SZ_16K; + dev->of_node = &node; + + /* The stream's window ends where the consumer's low bits begin. */ + dart->dma_min = 0; + dart->dma_max = SZ_2G - 1; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* The same holds for a stream window given by a five-cell specifier. */ + dart->dma_max = DMA_BIT_MASK(dart->ias); + args.args_count = 5; + args.args[1] = 0x100; + args.args[2] = 0; + args.args[3] = 0; + args.args[4] = 0x80000000; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), -EINVAL); + + /* One page of overlap is enough, and only that page is returned. */ + args.args[4] = 0x80004000; + KUNIT_EXPECT_EQ(test, apple_dart_parse_dma_window(dev, dart, &args, + &dma_min, &dma_max), 0); + KUNIT_EXPECT_EQ(test, dma_min, (dma_addr_t)0x10080000000); + KUNIT_EXPECT_EQ(test, dma_max, (dma_addr_t)0x10080003fff); + dev->of_node = NULL; +} + static void apple_dart_test_invalid_consumer_window(struct kunit *test) { static const struct { @@ -1277,6 +1330,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_topology), KUNIT_CASE(apple_dart_test_iommu_specifiers), KUNIT_CASE(apple_dart_test_consumer_window), + KUNIT_CASE(apple_dart_test_disjoint_consumer_window), KUNIT_CASE(apple_dart_test_invalid_consumer_window), KUNIT_CASE(apple_dart_test_independent_remap_roots), KUNIT_CASE(apple_dart_test_before_attach), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index c7ebb762d515ed..5483b4db3e3b78 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -826,9 +826,6 @@ struct apple_dart_domain { struct apple_dart_dcp *dcp; bool finalized; - bool has_dma_range; - dma_addr_t dma_min; - dma_addr_t dma_max; u64 mask; dma_addr_t dma_offset; struct mutex init_lock; @@ -3234,8 +3231,9 @@ static int __apple_dart_finalize_domain(struct apple_dart_domain *dart_domain, { struct apple_dart *dart = cfg->stream_maps[0].dart; struct io_pgtable_cfg pgtbl_cfg; - dma_addr_t dma_min = dart_domain->has_dma_range ? dart_domain->dma_min : cfg->dma_min; - dma_addr_t dma_max = dart_domain->has_dma_range ? dart_domain->dma_max : cfg->dma_max; + /* of_xlate already narrowed this to any consumer apple,dma-range. */ + dma_addr_t dma_min = cfg->dma_min; + dma_addr_t dma_max = cfg->dma_max; u64 translated_max; u32 ias; int ret = 0; @@ -3753,22 +3751,8 @@ static struct iommu_domain *apple_dart_domain_alloc_paging(struct device *dev) if (dev) { struct apple_dart_master_cfg *cfg = dev_iommu_priv_get(dev); - u64 window[2]; int ret; - if (of_property_present(dev->of_node, "apple,dma-range")) { - ret = of_property_read_u64_array(dev->of_node, "apple,dma-range", - window, 2); - if (!ret) - ret = apple_dart_dma_window(window[0], window[1], - &dart_domain->dma_max); - if (ret) { - kfree(dart_domain); - return ERR_PTR(ret); - } - dart_domain->dma_min = window[0]; - dart_domain->has_dma_range = true; - } ret = apple_dart_finalize_domain(dart_domain, cfg); if (ret) { kfree(dart_domain); @@ -3879,7 +3863,10 @@ static int apple_dart_validate_dma_window(struct device *dev, * Work out the DMA window of one "iommus" specifier. One cell is the stream * ID alone and keeps the window of the DART node. Five cells add the 64-bit * start and length of the window that the device uses. A consumer's - * apple,dma-range overrides either default, as it does at domain allocation. + * apple,dma-range narrows either window: its bits above the DART's ias pick + * the alias the consumer uses, and its low bits are intersected with the + * stream's own window, masked the same way. The DART translates only the low + * bits, so an address outside the stream's window must never be handed out. */ static int apple_dart_parse_dma_window(struct device *dev, const struct apple_dart *dart, @@ -3887,7 +3874,8 @@ static int apple_dart_parse_dma_window(struct device *dev, dma_addr_t *dma_min, dma_addr_t *dma_max) { - dma_addr_t length; + dma_addr_t length, consumer_max, low_min, low_max; + u64 mask = DMA_BIT_MASK(dart->ias); u64 window[2]; int ret; @@ -3906,15 +3894,28 @@ static int apple_dart_parse_dma_window(struct device *dev, return ret; } - /* Apply the consumer aperture before intersecting its DART windows. */ + /* Narrow to the consumer aperture before intersecting its DART windows. */ if (!of_property_present(dev->of_node, "apple,dma-range")) return 0; ret = of_property_read_u64_array(dev->of_node, "apple,dma-range", window, ARRAY_SIZE(window)); if (ret) return ret; - *dma_min = window[0]; - return apple_dart_validate_dma_window(dev, dart, *dma_min, window[1], dma_max); + ret = apple_dart_validate_dma_window(dev, dart, window[0], window[1], + &consumer_max); + if (ret) + return ret; + + low_min = max(window[0] & mask, *dma_min & mask); + low_max = min(consumer_max & mask, *dma_max & mask); + if (low_min > low_max) { + dev_err(dev, "DMA window %#llx..%#llx does not overlap stream window %pad..%pad\n", + window[0], (u64)consumer_max, dma_min, dma_max); + return -EINVAL; + } + *dma_min = (window[0] & ~mask) | low_min; + *dma_max = (window[0] & ~mask) | low_max; + return 0; } static int apple_dart_of_xlate(struct device *dev, From 89134432a946946a93f3665a0e43aab99c1f7358 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Mon, 23 Nov 2026 18:40:23 -0500 Subject: [PATCH 0798/1514] aurora-sep: mesa-m3: admit system Mesa on any T8122 or T6030 board The system handoff admitted only the J613 and the J516S, and the helper required the exact renderer strings "Apple M3 (G15G C0)" and "Apple M3 Pro (G15S B1)". Other boards with the same GPU (J615, J504, J514S, and the J433 and J434 iMacs) and other steppings stayed on the software fallback even when /usr Mesa works, as review pointed out. Key the admission on the SoC instead. The device tree must name exactly one board and exactly one SoC, and the SoC must be T8122 or T6030; the existing checks then apply as before: the single asahi render node is apple,agx-, the native display is apple,-display-subsystem, and the loaded EGL and gallium libraries come from /usr/lib. The helper accepts the renderer only when it names the admitted SoC's chip and GPU, with any stepping: "Apple M3 (G15G " on T8122 and "Apple M3 Pro (G15S " on T6030. That prefix also rules out llvmpipe, softpipe, swrast, lavapipe and zink, which stay refused by name as well. Without a board table the hook can no longer tell that a board belongs to another SoC; the GPU and display checks are keyed on the SoC compatible instead. The board and session tests move J615, J504 and J514S to admitted, keep two boards, two SoCs and no board refused, and add renderer controls: each SoC's GPU at any stepping is accepted, and the other SoC's GPU, an M2 (G14G), an M3 Max (G15C) and software renderers are refused. The PKGBUILD checksums follow the two sources. Signed-off-by: Scott Jones --- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 4 +- .../recipes/mesa-m3/mesa-m3-session-env | 16 +++---- .../recipes/mesa-m3/mesa-m3-system-check.c | 42 ++++++++++++++----- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 13 +++--- .../recipes/mesa-m3/tests/test-session-env.sh | 18 ++++++-- .../recipes/mesa-m3/tests/test-system-board.c | 29 +++++++++++-- 6 files changed, 92 insertions(+), 30 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index 2c80497680e0af..43a280e01d367b 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -85,7 +85,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '10abda78df16e650a77443f50cc46a15e418c42d4d9680c6a61616b232c9bdef' '6c98fab6f9d70449bd7f5258c34eac773836908e060ce5bef86dc5b0ce595e61' '826016665cd0424a614b67add921c0c79c3c698a4d104ea5712518449b75f27c' - '9cbc38f4bee27ab72d4a288f2741ab1eeb70112ca473a5c98a9695cdfcbe56f7' + 'e94accb088b3a49f16bc6f3bbefd9577d65e9481e303ae99a0f725f140e9bb6a' '6144af8b2e0f04ea615e8c4149e69c45ac49e630c46b2a58f0d1095d977798b2' '530948fc1a124de21c030a497e2ef5351742ba4ad4653484fe30fd1697ad7141' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' @@ -97,7 +97,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051' - 'e80947130044c2dc3671c24c7bff4f523dcc033f7e96f71e334d89a663e2742e') + '76f2661e715a96e3095168efa380c78d6303a84a4a11bbdfb573b09a22df65d6') # The qualified M3 Pro build's generated kernel files and libclc. build() stops # when one of ours differs. libagx_shaders.c is compared through kernel-digest.py: diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env index a90c3b5d2bc143..6348c4be48ab83 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env @@ -69,7 +69,7 @@ # decides. The state file says which (fallback=software|none). # # A file opt-out (/etc/mesa-m3/disable or the user's mesa-m3/disable) on a -# J613 (T8122) or a J516S (T6030) is the exception: when the same node, +# single-board T8122 or T6030 is the exception: when the same node, # display, kernel-log, user-setup and same-boot attempt checks pass and # mesa-m3-system-check admits /usr, the session keeps system Mesa # (fallback=none, no new attempt). The whole check runs in its own sh and is @@ -385,7 +385,7 @@ _mm3_legacy_attempt_clear() { return 0 } -# File opt-out on J613/T8122 or J516S/T6030 may keep the system Mesa. Prints +# File opt-out on a single-board T8122 or T6030 may keep the system Mesa. Prints # one detail line and returns 0 only when every check below passes. A helper # exit of 0 is not enough on its own. Does not write an attempt or touch a # marker. mesa_m3=off is not a file opt-out. @@ -404,11 +404,13 @@ _mm3_system_admit() { _mm3_chip= _mm3_identity=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,j') _mm3_socs=$(printf '%s\n' "$_mm3_dt" | grep -E '^apple,t') - case "$_mm3_soc:$_mm3_identity:$_mm3_socs" in - t8122:apple,j613:apple,t8122) _mm3_chip=t8122 ;; - t6030:apple,j516s:apple,t6030) _mm3_chip=t6030 ;; - *) return 1 ;; - esac + # Any board of this SoC: exactly one board compatible, and exactly one SoC + # compatible, which is the SoC the GPU checks below are keyed on. + case "$_mm3_soc" in t8122|t6030) ;; *) return 1 ;; esac + [ "$_mm3_socs" = "apple,$_mm3_soc" ] || return 1 + [ -n "$_mm3_identity" ] && + [ "$(printf '%s\n' "$_mm3_identity" | wc -l)" -eq 1 ] || return 1 + _mm3_chip=$_mm3_soc # Exactly one render node, and it is this SoC's asahi GPU, and this user # can open it. An any-node match is not enough. _mm3_nodes=0 diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c index 8f6177750196d5..10012e6c67945e 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-system-check.c @@ -18,9 +18,10 @@ static bool board_compat_matches(const char *bytes, size_t length, const char *soc) { - const char *board = !strcmp(soc, "t8122") ? "apple,j613" : - !strcmp(soc, "t6030") ? "apple,j516s" : NULL; - if (!board || !length || bytes[length - 1] != '\0') + /* Any board of this SoC: one board compatible and one SoC compatible. */ + if (strcmp(soc, "t8122") && strcmp(soc, "t6030")) + return false; + if (!length || bytes[length - 1] != '\0') return false; unsigned boards = 0, socs = 0; size_t offset = 0; @@ -31,8 +32,6 @@ board_compat_matches(const char *bytes, size_t length, const char *soc) return false; const char *value = bytes + offset; if (!strncmp(value, "apple,j", 7)) { - if (strcmp(value, board)) - return false; boards++; } else if (!strncmp(value, "apple,t", 7)) { if (strncmp(value + 6, soc, strlen(soc) + 1)) @@ -44,6 +43,32 @@ board_compat_matches(const char *bytes, size_t length, const char *soc) return boards == 1 && socs == 1; } +/* The asahi driver names its renderer "Apple ( )". + * Accept the chip and GPU of the admitted SoC with any stepping. The prefix + * already excludes software and layered renderers; refuse them by name too. + */ +static bool +native_renderer(const char *renderer, const char *soc) +{ + static const char *const refused[] = { + "llvmpipe", "softpipe", "swrast", "lavapipe", "zink", + }; + const char *prefix; + if (!strcmp(soc, "t8122")) + prefix = "Apple M3 (G15G "; + else if (!strcmp(soc, "t6030")) + prefix = "Apple M3 Pro (G15S "; + else + return false; + if (!renderer || strncmp(renderer, prefix, strlen(prefix))) + return false; + for (size_t i = 0; i < sizeof(refused) / sizeof(refused[0]); i++) { + if (strcasestr(renderer, refused[i])) + return false; + } + return true; +} + static bool qualified_board(const char *soc) { @@ -104,9 +129,7 @@ main(int argc, char **argv) fprintf(stderr, "usage: mesa-m3-system-check /dev/dri/renderD t8122|t6030\n"); return 2; } - const char *expected = !strcmp(argv[2], "t8122") ? "Apple M3 (G15G C0)" : - !strcmp(argv[2], "t6030") ? "Apple M3 Pro (G15S B1)" : NULL; - if (!expected) + if (strcmp(argv[2], "t8122") && strcmp(argv[2], "t6030")) return 2; const char *node_prefix = "/dev/dri/renderD"; size_t prefix_length = strlen(node_prefix); @@ -206,8 +229,7 @@ main(int argc, char **argv) !make_current(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) goto done; const char *renderer = (const char *)get_string(GL_RENDERER); - accepted = renderer && !strcmp(renderer, expected) && - system_implementation(); + accepted = native_renderer(renderer, argv[2]) && system_implementation(); if (accepted) printf("system-mesa=available renderer=%s\n", renderer); done: diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md index c5b7c978049197..cb85c0ac381f54 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -5,12 +5,15 @@ With native Mesa installed in `/usr`, the legacy file opt-out still forced system driver worked. The legacy package owns this hook, so the native Mesa package must not overwrite it or add an unconditional late unset. -This change allows a file opt-out on J613/T8122 and J516S/T6030 to leave system -Mesa selected. It requires one accessible Asahi render node, the matching +This change allows a file opt-out on any T8122 or T6030 board to leave system +Mesa selected. The device tree must name exactly one board and one SoC. It requires one accessible Asahi render node, the matching native display, a readable healthy kernel journal, no unmatched same-boot legacy login attempt, and no conflicting environment or later user settings. A bounded helper then opens the exact EGL device using only `/usr` libraries -and verifies its native renderer and loaded implementation paths. It creates +and verifies that its renderer string starts with the admitted SoC's chip +and GPU (`Apple M3 (G15G ` on T8122, `Apple M3 Pro (G15S ` on T6030, any +stepping; this also rules out llvmpipe, softpipe, swrast, lavapipe and +zink) and its loaded implementation paths. It creates a context but makes no draw, swap or compute calls. With `--system-provider`, the user-setup check also refuses settings the @@ -26,8 +29,8 @@ scanner refuses instead of holding the login. The helper keeps its own 5-second timeout. A failed check keeps the existing software fallback. `mesa_m3=off` and -`nomodeset` remain recovery choices. Other boards, including J615, remain -outside this system handoff. Explicit legacy profile selection is unchanged. +`nomodeset` remain recovery choices. Other SoCs remain outside this system +handoff. Explicit legacy profile selection is unchanged. No opt-in flags, attempt records or success markers are added or removed. Only the exact software-fallback pair previously exported by this hook can be cleared. The state remains `inactive`, `reason=opt-out`, `fallback=none` diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh index f10616501ea707..30a577cbf2299c 100755 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh @@ -775,9 +775,21 @@ for journal in noperm error match bank dcp g15g verdict; do HR=$(system_root "journal-$journal" pro) handoff "$HR" software no FAKE_JOURNAL="$journal" done -for dt in 'apple,j615 apple,t8122' 'apple,j514s apple,t6030' \ - 'apple,j614s apple,t6030' 'apple,j613 apple,j615 apple,t8122' \ - 'apple,j613 apple,t6030' 'apple,j516s apple,t6030 apple,t8122'; do +# Any single board of the SoC reaches the helper, which decides on the GPU. +HR=$(system_root board-j615 air) +nul apple,j615 apple,t8122 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +HR=$(system_root board-j504 air) +nul apple,j504 apple,t8122 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +HR=$(system_root board-j514s pro) +nul apple,j514s apple,t6030 > "$HR/proc/device-tree/compatible" +handoff "$HR" none yes +# Two boards, two SoCs or no board stay refused. Without a board table the +# hook cannot tell which SoC a board belongs to; the GPU and display checks +# are keyed on the SoC compatible instead. +for dt in 'apple,j613 apple,j615 apple,t8122' 'apple,t6030' \ + 'apple,j516s apple,t6030 apple,t8122'; do HR=$(system_root "board-$(printf '%s' "$dt" | tr ' ,' '--')" pro) nul $dt > "$HR/proc/device-tree/compatible" # Match the GPU to the ambiguous board's first SoC so the old fallback diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c index 1aa86befdcdba2..1832d2249ff7f5 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-system-board.c @@ -13,8 +13,10 @@ int main(void) CHECK(true, "t8122", "apple,j613\0apple,t8122\0apple,arm-platform\0"); CHECK(true, "t6030", "apple,j516s\0apple,t6030\0apple,arm-platform\0"); CHECK(true, "t6030", "apple,arm-platform\0apple,t6030\0apple,j516s\0"); - CHECK(false, "t8122", "apple,j615\0apple,t8122\0"); - CHECK(false, "t6030", "apple,j514s\0apple,t6030\0"); + /* Any single board of the SoC, not a list of boards. */ + CHECK(true, "t8122", "apple,j615\0apple,t8122\0"); + CHECK(true, "t8122", "apple,j504\0apple,t8122\0"); + CHECK(true, "t6030", "apple,j514s\0apple,t6030\0"); CHECK(false, "t6030", "apple,j516s\0apple,t6031\0"); CHECK(false, "t8122", "apple,j613\0apple,j615\0apple,t8122\0"); CHECK(false, "t8122", "apple,j613\0apple,j613\0apple,t8122\0"); @@ -27,6 +29,27 @@ int main(void) CHECK(false, "t6030", "apple,j516s\0"); CHECK(false, "t8140", "apple,j516s\0apple,t6030\0"); CHECK(false, "t6030", ""); - puts("17 board parser controls passed"); + /* The admitted SoC's chip and GPU, with any stepping. */ + assert(native_renderer("Apple M3 (G15G C0)", "t8122")); + assert(native_renderer("Apple M3 (G15G B0)", "t8122")); + assert(native_renderer("Apple M3 Pro (G15S B1)", "t6030")); + assert(native_renderer("Apple M3 Pro (G15S C0)", "t6030")); + /* The other SoC's GPU, another chip, or a software renderer. */ + assert(!native_renderer("Apple M3 Pro (G15S B1)", "t8122")); + assert(!native_renderer("Apple M3 (G15G C0)", "t6030")); + assert(!native_renderer("Apple M2 (G14G B1)", "t8122")); + assert(!native_renderer("Apple M2 (G14G B1)", "t6030")); + assert(!native_renderer("Apple M3 Max (G15C C0)", "t6030")); + assert(!native_renderer("Apple M3 Unknown (G15X C0)", "t8122")); + assert(!native_renderer("Apple M3 (G15G", "t8122")); + assert(!native_renderer("Apple M3 (G15G C0)", "t6031")); + assert(!native_renderer(NULL, "t8122")); + assert(!native_renderer("", "t8122")); + assert(!native_renderer("llvmpipe (LLVM 21.1.0, 128 bits)", "t8122")); + assert(!native_renderer("softpipe", "t6030")); + assert(!native_renderer("zink Vulkan 1.4(Apple M3 (G15G C0) (MESA_ASAHI))", "t8122")); + assert(!native_renderer("Apple M3 (G15G llvmpipe)", "t8122")); + assert(!native_renderer("AppleM3", "t8122")); + puts("18 board parser and 19 renderer controls passed"); return 0; } From 181fe1878c158e60c3b55a24f246b114d4262f8b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:01:30 +1100 Subject: [PATCH 0799/1514] drm/asahi: take the G14 27.2 thermal controller values from the chip config RootV27_2::controller() wrote the fast-die target, its offset, the SoC-hot alarm and the per-sensor corrections as literals. They are the values the 13.5 InitData takes from the T8112 chip config, so take them from there: HwDataA unk_8cc, unk_87c and unk_e24 (cfg.da), and the corrections from unk_coef_a/unk_coef_b, indexed from the first fast-die sensor id (7). A sensor without a coefficient refuses the start. The three remaining words (filter stages, unity scale, alarm enable) are controller constants that the 13.5 InitData also sets; they are named here. What the firmware receives is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 37d09ac8a19be3..a8812643dd54d6 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -950,14 +950,29 @@ impl RootV27_2 { let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; policy.get_mut(at..at + width).ok_or(EINVAL)?.copy_from_slice(&value.to_le_bytes()[..width]); } - // Thermal thresholds and corrections, then the SoC-hot alarm selection. - for (at, value) in [(0x22d4, 11000), (0x2284, 900), (0x2288, 4), - (0x229c, crate::f32!(1.0).to_bits()), (0x2f30, 125), (0x2f34, 1)] { + // Thermal thresholds, then the SoC-hot alarm selection: the chip's values, as the 13.5 + // InitData writes them (HwDataA unk_8cc, unk_87c and unk_e24). + for (at, value) in [(0x22d4, cfg.da.unk_8cc), (0x2284, cfg.da.unk_87c as u32), + (0x2f30, cfg.da.unk_e24)] { put32(policy, at, value); } - for at in [0x2320, 0x2420, 0x2f38, 0x3038] { - for sid in (0..64).filter(|sid| sensors & (1u64 << sid) != 0) { - put32(policy, at + 4 * sid, crate::f32!(5.3).to_bits()); + // Controller constants the 13.5 InitData also sets (unk_880, unk_894 = 1.0, unk_e28). + const FILTER_STAGES: u32 = 4; + const ALARM_ENABLE: u32 = 1; + for (at, value) in [(0x2288, FILTER_STAGES), (0x229c, crate::f32!(1.0).to_bits()), + (0x2f34, ALARM_ENABLE)] { + put32(policy, at, value); + } + // Per-sensor corrections from the chip's coefficient tables (13.5 unk_coef_a/unk_coef_b), + // indexed from the first fast-die sensor id. A sensor without a coefficient refuses. + const FIRST_SENSOR: usize = 7; + let coef_a = cfg.unk_coef_a.first().ok_or(EINVAL)?; + let coef_b = cfg.unk_coef_b.first().ok_or(EINVAL)?; + for (at, coef) in [(0x2320, coef_a), (0x2420, coef_a), (0x2f38, coef_b), (0x3038, coef_b)] { + for sid in (0..64usize).filter(|sid| sensors & (1u64 << sid) != 0) { + let value = sid.checked_sub(FIRST_SENSOR).and_then(|index| coef.get(index)) + .ok_or(EINVAL)?; + put32(policy, at + 4 * sid, value.to_bits()); } } put64(policy, 0x2f28, sensors); From 2267280d9c771a7df3b616272977b18c6a19c698 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:12:49 +1100 Subject: [PATCH 0800/1514] drm/apple: dcp: keep a still-attached HDMI link through a sleep The system suspend of a DCP whose firmware keeps running reported its fixed HDMI output unplugged and released its link on every sleep, since 0b1c93b9 ("drm: apple: dptx: Issue HPD event early on gpio/type-c disconnect"), also with the display still attached. After the wake nothing connects it again: HPD stayed high through the sleep, so no edge comes, and the CRTC that userspace turned off for the unplug never runs dcp_poweron(). On the M2 Mac mini (firmware 27.2) the release also timed out (RemotePort call 7, -110) and the converter pulsed HPD after the relink, and HDMI stayed dark after the first s2idle. Release it only when its HPD reads low, as DPMS off does (dcp_poweroff()). A display that stays attached keeps its link through the sleep, as through DPMS off, and resume lights it again through dcp_poweron(). A display that is unplugged during the sleep is still reported and released as when awake. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 78464acdb2e075..52fce51dbec2f9 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9930,7 +9930,18 @@ static int dcp_platform_suspend(struct device *dev) if (dcp->hdmi_hpd_irq) { disable_irq(dcp->hdmi_hpd_irq); - if (!dcp->active_typec_route) { + /* + * The firmware runs through this sleep, so the HDMI output + * keeps its link as through DPMS off (see dcp_poweroff()), and + * resume lights it again through dcp_poweron(). Only a display + * that is gone is reported and released here. Releasing one + * that stays attached reports it unplugged, and nothing + * connects it again after the wake: its HPD stays high, so no + * edge comes, and a CRTC userspace turned off for the unplug + * never runs dcp_poweron(). + */ + if (!dcp->active_typec_route && + gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0) { disconnected_hpd_event(dcp->connector); dcp_dptx_disconnect(dcp, 0); } From 8da4dbcce37475e5a8b3db8d0e8a37492fb5d093 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 14:42:25 +1100 Subject: [PATCH 0801/1514] drm/asahi: recover from G14 firmware 27.2 command timeouts and faults per client When a command runs past its execution allowance or faults, the G14 firmware 27.2 reports it on the event ring (kind 4 timeout with the named slot at +0xc, kind 0 fault) and stops every queue in a recovery handshake: it publishes phase 1 at control +0x4c00, advances the u64 generation at +0x4bf0 and records the stopped work at +0x4298 as {flags, target} pairs. It runs nothing until the host answers 2 and, at its phase 3, 0. This is the order G16 and M3 answer in their firmware data. The runtime decoded neither event. A stuck command stopped the whole GPU until the host's own timeout failed every client, so a single test client took the compositor down with it. Decode both events and answer the handshake. Mark the stopped work: the published render pair (a render is always published alone) or the oldest unretired compute command and the rest of its packet. Clear the TPC storage of a stopped tiler (snapshot flags 0x9) before answering 2, as G16 does. Then wait for phase 3 with an unchanged generation, answer 0, and wait for the stopped work to leave its queue. Its stamp is not written, so its position is what counts. It fails only its own packet and VM, so the client sees a lost context. Work queued behind it has its clocks restarted and retires normally. Further recoveries while the work drains are answered up to four times. If the firmware does not enter recovery, reach phase 3 or drain, all work fails as before. A host timeout that finds phase 1 without a seen event takes the same path. A doomed packet records the error in its VM status even if a racing scheduler timeout claimed its fence first. The handshake decisions are G16's: which phase the host may answer, how a snapshot entry decodes and the recovery-storm window (32 in 10 s) come from its pure, host-tested g16/recovery/logic.rs, included by path rather than copied. The G14 27.2 record kinds, recovery offsets and the stopped-tiler rule move to g14_v27_2_abi.rs with host tests (tools/asahi/g14-v27-2-abi-tests.rs, registered in run-host-tests.py). Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 14 ++ drivers/gpu/drm/asahi/g14_v27_2.rs | 269 ++++++++++++++++++++-- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 77 +++++++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 5 + drivers/gpu/drm/asahi/gpu/v27_2.rs | 77 ++++++- tools/asahi/g14-v27-2-abi-tests.rs | 5 + tools/asahi/run-host-tests.py | 2 + 7 files changed, 429 insertions(+), 20 deletions(-) create mode 100644 tools/asahi/g14-v27-2-abi-tests.rs diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 1680fd05d035b7..cd79a762cb3e6a 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -198,6 +198,20 @@ impl Scene::ver { self.object.tpc.gpu_pointer() } + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + #[allow(dead_code)] + pub(crate) fn clear_tpc(&self, bytes: usize) -> Result { + let tpc = self.object.tpc.as_slice(); + if bytes > tpc.len() { return Err(ERANGE); } + // SAFETY: the TPC belongs to this scene, whose tiler was stopped by the firmware and is + // halted; nothing else writes it until the scene's fragment pass runs or is dropped. + unsafe { core::ptr::write_bytes(tpc.as_ptr().cast_mut(), 0, bytes) }; + crate::pgtable::clean_poc(tpc.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } + /// Returns the GPU pointer to the first preemption scratch buffer. pub(crate) fn preempt_buf_1_pointer(&self) -> GpuPointer<'_, &'_ [u8]> { self.object.preempt_buf.gpu_pointer() diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index e9edc12813ab43..a6c9056771ab4e 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -40,6 +40,14 @@ use crate::{ m3::m3_submit::{Command, Packet}, }; +/// The recovery handshake is the one G16 answers: share its decisions (which phase the host may +/// answer, how a snapshot entry decodes, the recovery-storm window) instead of restating them. +/// Its FirmwareData offsets are G16's own and unused here. +#[path = "g16/recovery/logic.rs"] +#[allow(dead_code)] +mod recovery_logic; +use recovery_logic::{RecoveryAction, SnapshotEntry}; + /// RTKit endpoints of the GPU firmware. const EP_FIRMWARE: u8 = 0x20; const EP_DOORBELL: u8 = 0x21; @@ -58,6 +66,14 @@ const RETIRE_WAIT_US: i64 = 2000; const RESOURCE_RETRY_MS: u32 = 10; /// Work item for the poll. Ordinary firmware notifications can still queue immediate work. const RETRY_WORK: u64 = 1; +/// The firmware's recovery handshake (the G16/M3 order and limits): phase 1 follows the error +/// event within 50 ms; the whole handshake within 1 s; then the stopped work leaves its queue. +const PHASE1_WAIT_MS: i64 = 50; +const HANDSHAKE_MS: i64 = 1000; +const RECOVERY_DRAIN_MS: i64 = 1000; +/// Further recoveries answered while the stopped work drains (work behind it can time out in +/// turn) before the runtime gives up. +const FURTHER_RECOVERIES: u32 = 4; struct FirmwareWait { since: Instant, @@ -399,6 +415,8 @@ struct Inflight { /// Queue publications up to and including this command, counted from take-over. ordinal: u64, started: Instant, + /// Set when the firmware stopped this command: it fails its packet when it leaves the queue. + doomed: Option, _bind: mmu::VmBind, } @@ -411,6 +429,7 @@ struct RenderFlight { stamps: [event::EventValue; 2], targets: [u32; 2], started: Instant, + doomed: Option, } struct State { @@ -447,6 +466,12 @@ struct State { accepting: bool, submitted: u64, retired: u64, + /// A fault or timeout the firmware reported (error, named slot), answered by `recover`. + firmware_error: Option<(Error, i32)>, + recoveries: u64, + /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. + recovery_window: u64, + recovery_count: u32, } impl State { @@ -706,7 +731,8 @@ impl Runtime { let ordinal = state.published + 1; // Commit ownership before the firmware can see the new work. state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), doomed: None, _bind: bind }, + GFP_KERNEL)?; packet.mark_published(); submission.publish(); state.last = stamp; @@ -762,7 +788,7 @@ impl Runtime { let fs_post = state.root.stage_render(FRAGMENT, &fs_work)?; state.rendering = Some(RenderFlight { packet: packet.clone(), last, bind, scene, slots, stamps, - targets: [ta_post.target(), fs_post.target()], started: Instant::now(), + targets: [ta_post.target(), fs_post.target()], started: Instant::now(), doomed: None, }); queue.published(); packet.mark_published(); @@ -801,19 +827,26 @@ impl Runtime { fn retire_render(&self, state: &mut State) -> Result { let Some(flight) = state.rendering.as_ref() else { return Ok(()); }; - let mut ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - let mut fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + let (targets, stamps, doomed, started) = + (flight.targets, flight.stamps, flight.doomed, flight.started); + let done = |root: &RootV27_2, dm: usize| -> Result { + // A command the firmware stopped leaves its queue without reaching its stamp. + if doomed.is_some() { root.render_retired(dm, targets[dm]) } + else { root.render_done(dm, targets[dm], stamps[dm]) } + }; + let mut ta_done = done(&state.root, TILER)?; + let mut fs_done = done(&state.root, FRAGMENT)?; if !(ta_done && fs_done) - && state.root.render_queue(TILER).1 >= flight.stamps[TILER] - && state.root.render_queue(FRAGMENT).1 >= flight.stamps[FRAGMENT] + && state.root.render_queue(TILER).1 >= stamps[TILER] + && state.root.render_queue(FRAGMENT).1 >= stamps[FRAGMENT] { // As on the compute queue, the final stamp precedes the retired cursor and // there may be no separate notification when the cursor changes. let start = Instant::::now(); while !(ta_done && fs_done) && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { fsleep(Delta::from_micros(20)); - ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + ta_done = done(&state.root, TILER)?; + fs_done = done(&state.root, FRAGMENT)?; } } if ta_done && fs_done { @@ -821,13 +854,19 @@ impl Runtime { for slot in flight.slots { self.retire_slot(state, slot); } - if flight.last { + if let Some(err) = flight.doomed { + self.fail_doomed(state, &flight.packet, err); + } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { flight.packet.release_guard(); } - } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); + if state.root.recovery_phase()? == 1 && doomed.is_none() { + // The firmware stopped it and halted, but its event was not seen. + return self.recover(state, ETIMEDOUT, -1); + } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); return Err(ETIMEDOUT); @@ -835,6 +874,176 @@ impl Runtime { Ok(()) } + /// Fails a packet the firmware stopped, once none of its commands is in a queue: its + /// unpublished commands are withdrawn, and its VM records the error (the client sees a + /// lost context). Other clients' work is not touched. + fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { + if state.owns(packet) { return; } + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + packet.release_guard(); + // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). + if let Some(status) = packet.vm.status() { status.record(err); } + packet.finish(Err(err)); + } + + /// Marks the work the firmware stopped: the render pair if one is published (a render is + /// published alone), else the oldest unretired compute command and the rest of its packet. + /// Returns whether anything was published. + fn blame(&self, state: &mut State, error: Error, slot: i32) -> bool { + if let Some(flight) = state.rendering.as_mut() { + flight.doomed = Some(error); + let owner = &flight.packet.owner; + dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", + owner.process(), owner.pid, slot, error); + return true; + } + let Some(packet) = state.inflight.first().map(|f| f.packet.clone()) else { + dev_err!(self.dev, "GPU: firmware stopped with nothing published (slot {})\n", slot); + return false; + }; + for flight in state.inflight.iter_mut().filter(|f| Arc::ptr_eq(&f.packet, &packet)) { + flight.doomed = Some(error); + } + dev_err!(self.dev, "GPU: stopped compute of {}[{}] (slot {}, {:?})\n", + packet.owner.process(), packet.owner.pid, slot, error); + true + } + + /// Whether every command marked by `blame` has left its queue. + fn doomed_retired(&self, state: &mut State) -> Result { + if let Some(flight) = state.rendering.as_ref() { + if flight.doomed.is_some() { + return Ok(state.root.render_retired(TILER, flight.targets[TILER])? + && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); + } + } + let Some(ordinal) = + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal) + else { return Ok(true); }; + self.advance(state)?; + Ok(state.retired_total >= ordinal) + } + + /// Waits up to `ms` for the firmware's next recovery phase: 1 before the host answered, + /// 3 with the same `generation` after it answered 2. Ok(None) on timeout; Err(EPROTO) on + /// any phase the protocol does not allow (`recovery_logic::action`). + fn wait_recovery(&self, state: &mut State, answered: bool, generation: u64, ms: i64) + -> Result> { + let start = Instant::::now(); + loop { + let phase = state.root.recovery_phase()?; + let same = !answered || state.root.halt_count()? == generation; + match recovery_logic::action(phase, answered, same) { + RecoveryAction::Wait => {} + RecoveryAction::ProtocolError => { + dev_err!(self.dev, "GPU: recovery phase {} (answered {}, same generation {})\n", + phase, answered, same); + return Err(EPROTO); + } + found => return Ok(Some(found)), + } + if start.elapsed() > Delta::from_millis(ms) { return Ok(None); } + if state.peer.is_crashed() { return Err(EIO); } + let _ = state.root.drain(); + fsleep(Delta::from_millis(1)); + } + } + + /// The firmware recovery handshake after a fault or command timeout (the G16/M3 protocol). + /// The firmware stops every queue and publishes phase 1 with a generation and a snapshot of + /// the stopped work; the host marks that work (`blame`), clears the tiler storage of a + /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped + /// work then leaves its queue and fails only its own packet and VM; the next recoveries + /// while it drains are answered the same way, a bounded number of times. Errors here fail + /// all work (the runtime is not trusted). + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + state.root.log_timeout(&self.dev); + let mut rounds = 0; + let mut blamed = false; + loop { + if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + return Err(ETIMEDOUT); + } + let now = ::ktime_get() as u64; + if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { + dev_err!(self.dev, "GPU: {} recoveries in {} s; not answering more\n", + recovery_logic::WINDOW_LIMIT, recovery_logic::WINDOW_NS / 1_000_000_000); + return Err(EIO); + } + let generation = state.root.halt_count()?; + let mut entries = 0; + let mut stopped_tiler = false; + for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { + let (flags, target) = state.root.recovery_entry(i)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; + entries += 1; + stopped_tiler |= gpu::stopped_tiler(entry.flags); + if entries <= 8 { + dev_err!(self.dev, + "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", + generation, i, entry.flags, entry.event, entry.target); + } + } + if !blamed { + blamed = true; + self.blame(state, error, slot); + } + if stopped_tiler { + if let Some(flight) = state.rendering.as_ref() { + let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; + if !ta_left { + flight.scene.clear_tpc()?; + dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); + } + } + } + let start = Instant::::now(); + state.root.answer_recovery(2)?; + let mut reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + if reached.is_none() { + dev_warn!(self.dev, "GPU: no recovery phase 3 in {} ms; ringing the device-control doorbell\n", + HANDSHAKE_MS / 2); + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK); + reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + } + if reached != Some(RecoveryAction::Resume) { + return Err(ETIMEDOUT); + } + state.root.answer_recovery(0)?; + dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", + generation, start.elapsed().as_millis(), entries); + let start = Instant::::now(); + loop { + let _ = state.root.drain(); + if self.doomed_retired(state)? { + state.recoveries += 1; + // Work behind the stopped command waited out the recovery: restart its clocks. + let now = Instant::now(); + for flight in state.inflight.iter_mut() { flight.started = now; } + dev_err!(self.dev, + "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", + state.recoveries, start.elapsed().as_millis()); + return Ok(()); + } + if state.root.recovery_phase()? == 1 { break; } + if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { + dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); + state.root.log_timeout(&self.dev); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + rounds += 1; + dev_err!(self.dev, "GPU: firmware entered recovery again while the stopped work drained ({})\n", + rounds); + if rounds > FURTHER_RECOVERIES { return Err(EIO); } + } + } + /// Reads the queue's retired position into `retired_total`. fn advance(&self, state: &mut State) -> Result { let (_, raw) = state.root.progress()?; @@ -885,6 +1094,15 @@ impl Runtime { state.root.consume_event(cursor)?; return Err(EIO); } + FirmwareEvent::Timeout { slot } => { + dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); + state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + } + FirmwareEvent::Fault => { + dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); + state.fault.log(&self.dev); + state.firmware_error.get_or_insert((EIO, -1)); + } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } state.waiting_control = None; @@ -907,6 +1125,13 @@ impl Runtime { self.fail_all(state, err); return; } + if let Some((error, slot)) = state.firmware_error.take() { + if let Err(err) = self.recover(state, error, slot) { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } // The completion stamp is written before the firmware's post-processing advances the @@ -925,10 +1150,14 @@ impl Runtime { } while !state.inflight.is_empty() { let front = &state.inflight[0]; - if state.retired_total >= front.ordinal { + let (ordinal, started, unblamed, expected) = + (front.ordinal, front.started, front.doomed.is_none(), front.stamp.raw()); + if state.retired_total >= ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); - if let Some(err) = done.publication_error { + if let Some(err) = done.doomed { + self.fail_doomed(state, &done.packet, err); + } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); } else if done.last { @@ -939,9 +1168,17 @@ impl Runtime { } continue; } - if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", - state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); + state.queue_stamp(), expected, state.submitted, state.retired); + if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { + // The firmware stopped it and halted, but its event was not seen. + if let Err(err) = self.recover(state, ETIMEDOUT, -1) { + self.fail_all(state, err); + return; + } + continue; + } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); self.fail_all(state, ETIMEDOUT); @@ -1146,6 +1383,10 @@ impl Backend { accepting: true, submitted: 0, retired: 0, + firmware_error: None, + recoveries: 0, + recovery_window: 0, + recovery_count: 0, }); // From here the firmware's messages run the service; one run consumes anything it // published before. diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 535313f91126cf..501be19bdd1a6a 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -71,6 +71,52 @@ impl GrowRequest { } } +/// Control-object recovery words (the recovery block G16 and M3 answer in their FirmwareData): +/// the u64 recovery generation, which growth requests also carry; 0x10 on, the recovery phase +/// (firmware 1 -> host 2 -> firmware 3 -> host 0); the snapshot of the work the firmware +/// stopped, {flags u32, target u32} pairs, at the same offset as in the M3 object, up to the +/// next recovery field. Seen on the J473: a stopped tiler {0x1f, its next stamp}, a stopped +/// compute {0x7, its next stamp}. +pub(crate) const RECOVERY_GENERATION: usize = 0x4bf0; +pub(crate) const RECOVERY_PHASE: usize = 0x4c00; +pub(crate) const RECOVERY_SNAPSHOT: usize = 0x4298; +const RECOVERY_SNAPSHOT_END: usize = 0x4b20; +pub(crate) const RECOVERY_SNAPSHOT_ENTRIES: usize = (RECOVERY_SNAPSHOT_END - RECOVERY_SNAPSHOT) / 8; + +/// A snapshot entry of a stopped tiler (valid + tiler bits): its TPC storage must be cleared +/// before the host answers phase 2, as G16 does. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// Event ring record kinds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum EventKind { + /// 0: the firmware stopped on a GPU fault and entered recovery. + Fault, + /// 4: the firmware timed out a command (slot at `TIMEOUT_SLOT_OFFSET`) and entered recovery. + Timeout, + /// 6: a buffer growth request. + Grow, + /// 7: the firmware rejected a channel record. + ChannelError, + /// Anything else (stage flags, statistics): nothing for the host to answer. + Notification, +} + +/// Byte offset of the slot a timeout record names. +pub(crate) const TIMEOUT_SLOT_OFFSET: usize = 0x0c; + +pub(crate) const fn event_kind(kind: u32) -> EventKind { + match kind { + 0 => EventKind::Fault, + 4 => EventKind::Timeout, + 6 => EventKind::Grow, + 7 => EventKind::ChannelError, + _ => EventKind::Notification, + } +} + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -148,4 +194,35 @@ mod tests { ] ); } + + #[test] + fn recovery_events_are_decoded_and_others_stay_notifications() { + assert_eq!(event_kind(0), EventKind::Fault); + assert_eq!(event_kind(4), EventKind::Timeout); + assert_eq!(event_kind(6), EventKind::Grow); + assert_eq!(event_kind(7), EventKind::ChannelError); + for kind in [1, 2, 3, 5, 8, u32::MAX] { + assert_eq!(event_kind(kind), EventKind::Notification); + } + // The H1 record [4, 0, 0, 1, ...]: slot in the fourth word. + assert_eq!(TIMEOUT_SLOT_OFFSET / 4, 3); + } + + #[test] + fn recovery_block_geometry_matches_the_g16_order() { + // Phase 0x10 above the u64 generation, as in the G16/M3 FirmwareData. + assert_eq!(RECOVERY_PHASE - RECOVERY_GENERATION, 0x10); + assert_eq!(RECOVERY_SNAPSHOT_ENTRIES, 273); + assert!(RECOVERY_SNAPSHOT + 8 * RECOVERY_SNAPSHOT_ENTRIES <= RECOVERY_SNAPSHOT_END); + assert!(RECOVERY_SNAPSHOT_END <= RECOVERY_GENERATION); + } + + #[test] + fn only_a_valid_tiler_entry_clears_tiler_storage() { + // J473 snapshots: stopped tiler {0x1f, ..}, stopped compute {0x7, ..}. + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(stopped_tiler(0x9 | (0x70 << 4))); + } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index 10ce122708dbde..c81b3b46997462 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -76,6 +76,11 @@ impl Prep { pub(crate) fn slot(&self) -> u32 { self.scene.slot() } + + /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. + pub(crate) fn clear_tpc(&self) -> Result { + self.scene.clear_tpc(self.tile.tpc_size) + } } fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index c3b3dd9b99520a..9e23697fcec5f8 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -10,7 +10,7 @@ use super::*; use kernel::device; -use crate::g14_v27_2_abi::{self, GrowRequest, QueueError}; +use crate::g14_v27_2_abi::{self, EventKind, GrowRequest, QueueError}; use crate::g17::fw::m5::initdata as abi; use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; use crate::m3::m3_init_26 as directory26; @@ -40,6 +40,11 @@ const STATISTICS_RING: usize = 16; /// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; +use crate::g14_v27_2_abi::{ + RECOVERY_GENERATION as CONTROL_RECOVERY_GENERATION, RECOVERY_PHASE as CONTROL_RECOVERY_PHASE, + RECOVERY_SNAPSHOT as CONTROL_RECOVERY_SNAPSHOT, +}; +pub(crate) use crate::g14_v27_2_abi::{stopped_tiler, RECOVERY_SNAPSHOT_ENTRIES}; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; /// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. @@ -473,6 +478,11 @@ impl CommandPool { } pub(crate) enum FirmwareEvent { + /// Kind 0: the firmware stopped on a GPU fault and halted for recovery. + Fault, + /// Kind 4: the firmware timed out a command (the slot it names at +0xc) and halted for + /// recovery. + Timeout { slot: i32 }, Grow(GrowRequest), ChannelError, Notification, @@ -559,6 +569,15 @@ impl RootV27_2 { (queue.info(self.render_states[dm]), queue.event.current_noncoherent()) } + /// Whether the render queue's retired position reached `target`, stamp or not: a command + /// the firmware stopped for recovery leaves the queue without writing its stamp. + pub(crate) fn render_retired(&self, dm: usize, target: u32) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok(Self::word(&queue.positions, 0)? == target) + } + pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { let queue = &self.render_queues[dm]; crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); @@ -708,16 +727,39 @@ impl RootV27_2 { crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); crate::pgtable::poc_barrier(); let word = |offset| Self::word(ring, at + offset); - let event = match word(0)? { - 6 => FirmwareEvent::Grow(GrowRequest::decode([ + let event = match g14_v27_2_abi::event_kind(word(0)?) { + EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, ])), - 7 => FirmwareEvent::ChannelError, - _ => FirmwareEvent::Notification, + EventKind::Fault => FirmwareEvent::Fault, + EventKind::Timeout => FirmwareEvent::Timeout { + slot: word(g14_v27_2_abi::TIMEOUT_SLOT_OFFSET)? as i32, + }, + EventKind::ChannelError => FirmwareEvent::ChannelError, + EventKind::Notification => FirmwareEvent::Notification, }; Ok(Some((read, event))) } + /// Reads control words from `from` into `out`. + pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + let at = self.control.as_slice()[from..].as_ptr(); + crate::pgtable::clean_invalidate_poc(at, out.len() * 4); + crate::pgtable::poc_barrier(); + for (i, w) in out.iter_mut().enumerate() { + *w = Self::word(&self.control, from + 4 * i)?; + } + Ok(()) + } + + /// Writes one control word and makes it visible to the firmware. + pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + self.control.shared_index(at)?.store(value, Ordering::Release); + crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); + crate::pgtable::poc_barrier(); + Ok(()) + } + pub(crate) fn consume_event(&self, cursor: u32) -> Result { let state = &self.channels[2 * EVENT_RING]; state.shared_index(0)?.store((cursor + 1) % RING_RECORDS, Ordering::Release); @@ -726,8 +768,31 @@ impl RootV27_2 { Ok(()) } + /// The recovery phase. The firmware publishes 1 after it reported a fault or a command + /// timeout and stopped every queue; it runs nothing until the host's answers. + pub(crate) fn recovery_phase(&self) -> Result { + let mut word = [0u32]; + self.control_snapshot(CONTROL_RECOVERY_PHASE, &mut word)?; + Ok(word[0]) + } + + /// Answers a recovery phase (2 at phase 1, 0 at phase 3). + pub(crate) fn answer_recovery(&self, phase: u32) -> Result { + self.control_store(CONTROL_RECOVERY_PHASE, phase) + } + + /// Snapshot entry `i` of the stopped work: (flags, target). Bit 0 of flags marks a valid + /// entry; the first invalid one ends the snapshot. + pub(crate) fn recovery_entry(&self, i: usize) -> Result<(u32, u32)> { + if i >= RECOVERY_SNAPSHOT_ENTRIES { return Err(EINVAL); } + let mut words = [0u32; 2]; + self.control_snapshot(CONTROL_RECOVERY_SNAPSHOT + 8 * i, &mut words)?; + Ok((words[0], words[1])) + } + + /// The recovery generation (u64). Growth requests carry the value current when sent. pub(crate) fn halt_count(&self) -> Result { - const OFFSET: usize = 0x4bf0; + const OFFSET: usize = CONTROL_RECOVERY_GENERATION; crate::pgtable::clean_invalidate_poc(self.control.as_slice()[OFFSET..].as_ptr(), 8); crate::pgtable::poc_barrier(); Ok(u64::from(Self::word(&self.control, OFFSET)?) diff --git a/tools/asahi/g14-v27-2-abi-tests.rs b/tools/asahi/g14-v27-2-abi-tests.rs new file mode 100644 index 00000000000000..04ae20680f7ca6 --- /dev/null +++ b/tools/asahi/g14-v27-2-abi-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Host tests of the production G14 firmware 27.2 queue, event and recovery records. +#![allow(dead_code)] +#[path = "../../drivers/gpu/drm/asahi/g14_v27_2_abi.rs"] +mod g14_v27_2_abi; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..310a3c8a0fb193 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -322,6 +322,8 @@ def mutations(flag, names, base, expect=KILL): # Production G17 decoder vectors also build directly with rustc --test. ASAHI_RUST += ['g17-telemetry-tests.rs', 'legacy-frequency-tests.rs'] ASAHI_RUST.append('m3-firmware-tests.rs') +# G14 firmware 27.2 queue, event and recovery records (its KUnit suite, run on the host). +ASAHI_RUST.append('g14-v27-2-abi-tests.rs') # Python that runs on the host but imports its neighbours, so it keeps the # script directory on sys.path (-E -s instead of -I). From 2e95be317a1bb370e4ca64b8db15100c7c9df4aa Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:25:41 +1100 Subject: [PATCH 0802/1514] selftests: apple-dcp: give the AV admission scenarios their output kind dcpavserv_admission_current() now asks dcp_is_typec_output() whether the output waits for a Type-C cable. The service-rebind, provider-admission, publication-hpd and panel-dimensions units build it from dpavservep.c and model a Type-C output: declare the helper there, and define it as such where the scenario does not already. Signed-off-by: Ryan Murray --- tools/testing/selftests/drivers/gpu/apple-dcp/edid.py | 4 ++-- tools/testing/selftests/drivers/gpu/apple-dcp/rate.py | 8 +++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 6898b7b368801f..476c35ff89f7da 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -173,7 +173,7 @@ def function(file,signature): function('afk.h','static inline bool\nafk_service_reinit('),function('afk.h','static inline void afk_service_discard('), function('afk.h','static inline void afk_service_publish('), function('epic/dpavservep.c','static void dcpavserv_notify_edid('),function('epic/dpavservep.c','static bool dcpavserv_identity('), - function('epic/dpavservep.c','static bool dcpavserv_admission_current('),function('epic/dpavservep.c','static int dcpavserv_prepare('), + '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n'+function('epic/dpavservep.c','static bool dcpavserv_admission_current('),function('epic/dpavservep.c','static int dcpavserv_prepare('), function('epic/dpavservep.c','static int dcpavserv_revalidate('),function('epic/dpavservep.c','static void dcpavserv_init('),function('epic/dpavservep.c','static void dcpavserv_invalidate_edid('), function('epic/dpavservep.c','static void dcpavserv_teardown('),function('epic/dpavservep.c','void dpavservep_detach('), function('afk.c','static const struct apple_epic_service_ops *\nafk_match_service('), @@ -698,7 +698,7 @@ def function(file, signature): function('dcp.c', 'static struct apple_dcp_afkep *dcp_afkep('), function('dcp.c', 'static void dcp_recv_msg('), function('epic/dpavservep.c', 'static bool dcpavserv_identity('), - function('epic/dpavservep.c', 'static bool dcpavserv_admission_current('), + '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n' + function('epic/dpavservep.c', 'static bool dcpavserv_admission_current('), function('epic/dpavservep.c', 'static int dcpavserv_prepare('), function('epic/dpavservep.c', 'static int dcpdpserv_prepare('), function('epic/dpavservep.c', 'static void dcpavserv_init('), diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 1df2c17f68a9a9..7a0ee164cf8595 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -920,6 +920,10 @@ def publication(root): 'static void dcpavserv_teardown(', 'void dpavservep_detach(', 'bool dcpavserv_edid_current(', 'bool dcpavserv_edid_service_current(', ]) + # dcp-fabric.c decides it in the driver; each scenario below defines it. + transport = transport.replace('static bool dcpavserv_admission_current(', + 'static bool dcp_is_typec_output(struct apple_dcp *d);\n' + 'static bool dcpavserv_admission_current(', 1) mode_helpers = iomfb[iomfb.index('static struct dcp_display_mode *dcp_modes_snapshot('):iomfb.index('int dcp_get_modes(')] # The link line of a processor whose hardware description asks for it # (hw.link_report, T6050's external ones): no processor here does. @@ -1251,8 +1255,10 @@ def panel_dimensions(root): puts("PASS: internal panel dimensions survive repeated EDID clears; firmware size and DT fallback; external EDID size preserved"); } """ + # The panel scenarios model a Type-C output, as the hotplug ones. unit = unit.replace('int main(int argc,char **argv) {', - checks + 'int main(int argc,char **argv) {') + 'static bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n' + + checks + 'int main(int argc,char **argv) {') return unit.replace(' transport_edid=raw;', ' transport_edid=raw;panel_dimension_probes();', 1) From 245f899b2725ea8111f6ceb71bdd15a90fb2693f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:25:45 +1100 Subject: [PATCH 0803/1514] tools/asahi: stub the DP PHY hold in the dcpext26 suspend route test The test builds dcp_platform_suspend() from dcp.c, which now also holds the DP PHYs of a DCP whose firmware runs through the sleep. That hold has its own test; stub it here. Signed-off-by: Ryan Murray --- tools/asahi/dcpext26-suspend-route-tests.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/asahi/dcpext26-suspend-route-tests.py b/tools/asahi/dcpext26-suspend-route-tests.py index 67f13cf1bde289..5201f36841e497 100644 --- a/tools/asahi/dcpext26-suspend-route-tests.py +++ b/tools/asahi/dcpext26-suspend-route-tests.py @@ -70,6 +70,8 @@ def function(text, name): static void dcp_enable_typec_work(struct apple_dcp *d) { enabled++; } static int dcp_external_disconnect(struct apple_dcp *d,bool wait) { return disconnect_error; } static void device_set_wakeup_path(struct device *d) { wake_paths++; } +/* The DP PHY hold has its own test (dcp-sleep-phy-hold-tests.py). */ +static void dcp_sleep_hold_phys(struct apple_dcp *d) { (void)d; } static void reset_counts(void) { parks=unparks=wake_paths=disabled=enabled=0; } ''' code = pre + function(header, 'dcp_is_ext26') + '\n' + function(source, 'dcp_is_external_h17p') + '\n' + function(source, 'dcp_is_retained_external') From 702e0c301cfb4745597920aba7aaf8df80e7d384 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:45:21 +1100 Subject: [PATCH 0804/1514] drm/apple: read the sleep PHYs under the fabric lock Read the selected Type-C route and the PHY pointers together while the display fabric holds its route lock. Mark those provider devices before a route handoff can change the selected PHY. The host fixture checks that the provider is marked under the same lock. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-fabric.c | 23 +++++++++++++++++++++++ drivers/gpu/drm/apple/dcp-fabric.h | 1 + drivers/gpu/drm/apple/dcp.c | 21 --------------------- tools/asahi/dcp-sleep-phy-hold-tests.py | 21 +++++++++++++++++---- 4 files changed, 41 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 08f5057cf1a9d7..b81598df13062e 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -4995,6 +4995,29 @@ int dcp_register_typec_routes(struct apple_dcp *dcp) return dcp_fabric_run_probe(!!routes, dcp_register_typec_routes_present, &ctx); } +/* + * A DCP whose firmware runs through a sleep keeps driving the DP PHY of its + * output, so the PHY's power domain has to stay up with the DCP's own: cut at + * noirq under the running firmware, it resets the SoC (J473, firmware 27.2). + * Put the PHY devices in use on the wakeup path, as the DCP itself is. + */ +static void dcp_phy_set_wakeup_path(struct phy *phy) +{ + if (!IS_ERR_OR_NULL(phy) && phy->dev.parent) + device_set_wakeup_path(phy->dev.parent); +} + +void dcp_sleep_hold_phys(struct apple_dcp *dcp) +{ + struct apple_dcp_typec_route *route; + + guard(mutex)(&dcp_typec_fabric_lock); + route = dcp->active_typec_route; + dcp_phy_set_wakeup_path(dcp->phy); + if (route) + dcp_phy_set_wakeup_path(route->phy); +} + /* * A sleep that reaches its commit powers the crossbar off. Take the output of a direct * route down while it still has power, as a released display's is, and select it again diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index 65082081e2b1bd..a7d13d80942785 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -131,6 +131,7 @@ bool dcp_is_t8132_ext(const struct apple_dcp *dcp); /* DCP probe, resume and endpoint teardown hooks. */ int dcp_register_typec_routes(struct apple_dcp *dcp); +void dcp_sleep_hold_phys(struct apple_dcp *dcp); void dcp_typec_route_park(struct apple_dcp *dcp); void dcp_typec_route_unpark(struct apple_dcp *dcp); int dcp_fabric_sleep_release(struct apple_dcp *dcp, s64 ms[2]); diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 52fce51dbec2f9..6792821229e167 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9766,27 +9766,6 @@ bool dcp_sleep_keeps_firmware(struct device *dev) } EXPORT_SYMBOL_GPL(dcp_sleep_keeps_firmware); -/* - * A DCP whose firmware runs through a sleep keeps driving the DP PHY of its - * output, so the PHY's power domain has to stay up with the DCP's own: cut at - * noirq under the running firmware, it resets the SoC (J473, firmware 27.2). - * Put the PHY devices in use on the wakeup path, as the DCP itself is. - */ -static void dcp_phy_set_wakeup_path(struct phy *phy) -{ - if (!IS_ERR_OR_NULL(phy) && phy->dev.parent) - device_set_wakeup_path(phy->dev.parent); -} - -static void dcp_sleep_hold_phys(struct apple_dcp *dcp) -{ - struct apple_dcp_typec_route *route = READ_ONCE(dcp->active_typec_route); - - dcp_phy_set_wakeup_path(dcp->phy); - if (route) - dcp_phy_set_wakeup_path(route->phy); -} - static int dcp_platform_suspend(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); diff --git a/tools/asahi/dcp-sleep-phy-hold-tests.py b/tools/asahi/dcp-sleep-phy-hold-tests.py index 05105c3c8dcefe..b0cf23c94c5d1b 100755 --- a/tools/asahi/dcp-sleep-phy-hold-tests.py +++ b/tools/asahi/dcp-sleep-phy-hold-tests.py @@ -8,7 +8,7 @@ resets the J473 (firmware 27.2) on s2idle. dcp_sleep_hold_phys() puts the provider device of the DCP's own dp-phy and of its active Type-C route's PHY on the wakeup path. The fixture builds the real dcp_phy_set_wakeup_path() and -dcp_sleep_hold_phys() from drivers/gpu/drm/apple/dcp.c against a small +dcp_sleep_hold_phys() from drivers/gpu/drm/apple/dcp-fabric.c against a small driver-core model and checks which devices end up on the wakeup path. --mutation names a change to the production functions that the matrix must @@ -23,7 +23,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[2] -DCP = "drivers/gpu/drm/apple/dcp.c" +DCP = "drivers/gpu/drm/apple/dcp-fabric.c" MUTATIONS = { # Forget the Type-C route's PHY (the USB-C output of a primary DCP). @@ -44,14 +44,27 @@ #include #include static volatile int cur_line; +static bool dcp_typec_fabric_lock; +static bool *lock_acquire(bool *held) +{ + if (*held) + abort(); + *held = true; + return held; +} +static void lock_release(bool **held) { **held = false; } +#define guard(kind) bool *__attribute__((cleanup(lock_release))) held = lock_acquire static void on_segv(int sig) { char b[64]; int n = snprintf(b, sizeof(b), "FAIL line %d (signal %d)\n", cur_line, sig); write(1, b, n); _exit(1); } -#define READ_ONCE(x) (x) #define MAX_ERRNO 4095 #define IS_ERR_VALUE(x) ((unsigned long)(void *)(x) >= (unsigned long)-MAX_ERRNO) static inline bool IS_ERR_OR_NULL(const void *p) { return !p || IS_ERR_VALUE((unsigned long)p); } struct device { struct device *parent; bool wakeup_path; }; static void device_set_wakeup_path(struct device *dev) { + if (!dcp_typec_fabric_lock) { + printf("FAIL line %d wakeup mark without fabric lock\n", cur_line); + exit(1); + } if (IS_ERR_VALUE((unsigned long)dev)) { printf("FAIL line %d error pointer\n", cur_line); exit(1); } dev->wakeup_path = true; } @@ -98,7 +111,7 @@ ''' def extract(src, name): - m = re.search(r'^static void %s\(.*?^}\n' % re.escape(name), src, re.S | re.M) + m = re.search(r'^(?:static )?void %s\(.*?^}\n' % re.escape(name), src, re.S | re.M) if not m: sys.exit(f"{name} not found in {DCP}") return m.group(0) From 1274718dc5fde504e2ea7ac670d938556640764c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:45:21 +1100 Subject: [PATCH 0805/1514] arm64: dts: apple: t8112: allow the display PHY domains to wake Describe active wakeup for the external DPTX and two ATC USB domains. A domain that is off at PMGR probe can be powered by a later display attachment. The property lets genpd honor a subsequent consumer wakeup-path mark while the DCP keeps running through suspend. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-pmgr.dtsi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi index e2564eac95e501..ba14aa4eac3099 100644 --- a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi @@ -715,6 +715,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "dptx_ext_phy"; + apple,sleep-wakeup-path; }; ps_dispdfr_fe: power-controller@3e0 { @@ -1288,6 +1289,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_usb"; + apple,sleep-wakeup-path; power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; }; @@ -1297,6 +1299,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_usb"; + apple,sleep-wakeup-path; power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; }; From 31ba92a7d68c1a3c733d58f1e091dc2f9c6cef5a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 16:51:49 +1100 Subject: [PATCH 0806/1514] drm/apple: dcp: release an HDMI display unplugged during a sleep A DCP whose firmware runs through a sleep keeps an attached HDMI display's link, so the display lights again on wake. Its HPD IRQ is masked through the sleep, and on a fixed HDMI output nothing else sees an unplug made then: the connector stayed connected after the wake. On resume, before the HPD IRQ is enabled again, release a display whose HPD now reads low, as an unplug while awake is: report the hotplug, release the DPTX link and tell the fabric. An edge from then on is replayed when the IRQ comes back. A failed GPIO read cannot establish absence and leaves the display connected; a pipeline a Type-C display owns is not touched. A T6030 native HDMI output still releases its link at suspend, attached or not: its resume sets the converter, PHY and crossbar up again (dcp_fabric_hdmi_reinit()), which needs the link down. tools/asahi/dcp-hdmi-sleep-unplug-tests.py runs the real suspend HDMI block and the resume release over kept, unplugged-in-sleep, gone-before, GPIO error, borrowed and T6030 native cases, and checks the release runs before the IRQ comes back; five mutations are killed. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 27 ++- tools/asahi/dcp-hdmi-sleep-unplug-tests.py | 188 +++++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 3 files changed, 217 insertions(+), 2 deletions(-) create mode 100755 tools/asahi/dcp-hdmi-sleep-unplug-tests.py diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 6792821229e167..210c95547a484e 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9917,10 +9917,13 @@ static int dcp_platform_suspend(struct device *dev) * that stays attached reports it unplugged, and nothing * connects it again after the wake: its HPD stays high, so no * edge comes, and a CRTC userspace turned off for the unplug - * never runs dcp_poweron(). + * never runs dcp_poweron(). A T6030 native output's resume sets + * its PHY and crossbar up again (dcp_fabric_hdmi_reinit()), + * which needs the link down, so it is still released. */ if (!dcp->active_typec_route && - gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0) { + (dcp->external_native || + gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)) { disconnected_hpd_event(dcp->connector); dcp_dptx_disconnect(dcp, 0); } @@ -9939,6 +9942,23 @@ static int dcp_platform_suspend(struct device *dev) return 0; } +/* + * The suspend kept an attached HDMI display's link (dcp_platform_suspend()). + * One unplugged during the sleep made no edge the masked HPD IRQ saw, and + * nothing else reports it: release it now, as an unplug while awake is. + */ +static void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp) +{ + if (READ_ONCE(dcp->active_typec_route) || !dcp->connector || + !READ_ONCE(dcp->connector->connected) || + gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0) + return; + dev_info(dcp->dev, "HDMI display unplugged during sleep\n"); + disconnected_hpd_event(dcp->connector); + dcp_dptx_disconnect(dcp, 0); + dcp_fabric_hdmi_unplugged(dcp); +} + static int dcp_platform_resume(struct device *dev) { struct apple_dcp *dcp = dev_get_drvdata(dev); @@ -9985,6 +10005,9 @@ static int dcp_platform_resume(struct device *dev) /* The HDMI output's PHY and crossbar may have lost their setup in sleep. */ if (dcp->external_native) dcp_fabric_hdmi_reinit(dcp, "after system sleep"); + /* Before the HPD IRQ comes back: an edge from now on is replayed. */ + if (dcp->hdmi_hpd_irq) + dcp_hdmi_unplugged_in_sleep(dcp); /* Observe future edges before sampling any edges lost in sleep. */ if (dcp->hdmi_hpd_irq) dcp_fabric_run_resume(&dcp_resume_ops, dcp); diff --git a/tools/asahi/dcp-hdmi-sleep-unplug-tests.py b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py new file mode 100755 index 00000000000000..df588dcdc16e21 --- /dev/null +++ b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the real HDMI sleep keep-link and the unplugged-in-sleep release. + +A DCP whose firmware runs through a sleep keeps an attached HDMI display's +link (dcp_platform_suspend()), so the display lights again on wake. Its HPD +IRQ is masked through the sleep, so a display unplugged during it makes no +edge anyone sees: dcp_hdmi_unplugged_in_sleep() releases it on resume, before +the IRQ comes back. A T6030 native output still releases the link at suspend, +because its resume sets the PHY and crossbar up again. + +The fixture compiles the HDMI block of dcp_platform_suspend() and +dcp_hdmi_unplugged_in_sleep() from drivers/gpu/drm/apple/dcp.c against mocks +and checks which displays are released. --mutation names a change to the +production code that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +DCP = 'drivers/gpu/drm/apple/dcp.c' +RESUME_CALL = '\tif (dcp->hdmi_hpd_irq)\n\t\tdcp_hdmi_unplugged_in_sleep(dcp);\n' + +MUTATIONS = { + # Keep a T6030 native output's link, which its resume reinit tears down. + 'keep-native': ('(dcp->external_native ||\n\t\t gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)', + '(gpiod_get_value_cansleep(dcp->hdmi_hpd) <= 0)'), + # Release on a failed GPIO read, which cannot establish absence. + 'gpio-error': ('gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0)\n\t\treturn;', + 'gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0)\n\t\treturn;'), + # Release the HDMI connector while a Type-C display owns the pipeline. + 'ignore-borrowed': ('if (READ_ONCE(dcp->active_typec_route) || !dcp->connector ||', + 'if (!dcp->connector ||'), + # Leave the hybrid fabric thinking HDMI is still there. + 'no-fabric': ('\tdcp_dptx_disconnect(dcp, 0);\n\tdcp_fabric_hdmi_unplugged(dcp);\n}', + '\tdcp_dptx_disconnect(dcp, 0);\n}'), + # Never look for an unplug after the sleep. + 'no-resume-check': (RESUME_CALL, ''), +} + +def block(text, start): + opening = text.index('{', start) + depth = 0 + for end in range(opening, len(text)): + depth += text[end] == '{' + depth -= text[end] == '}' + if not depth: + return text[start:end + 1] + raise AssertionError('unbalanced production block') + +def function(text, name): + match = re.search(r'\n(static [^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) + assert match, name + return block(text, match.start(1)) + +HARNESS = r''' +#include +#include +#include +#define READ_ONCE(x) (x) +#define dev_info(...) ((void)0) +struct device { int unused; }; +struct gpio_desc { int level; }; +struct apple_connector { bool connected; }; +struct apple_dcp { + struct device *dev; + void *active_typec_route; + struct apple_connector *connector; + struct gpio_desc *hdmi_hpd; + int hdmi_hpd_irq; + bool external_native; +}; +static unsigned hpd_events, disconnects, fabric_unplugs, irq_off; +static int gpiod_get_value_cansleep(struct gpio_desc *g) { return g->level; } +static void disable_irq(int irq) { irq_off++; } +static void disconnected_hpd_event(struct apple_connector *c) { c->connected = false; hpd_events++; } +static int dcp_dptx_disconnect(struct apple_dcp *d, int port) { disconnects++; return 0; } +static void dcp_fabric_hdmi_unplugged(struct apple_dcp *d) { fabric_unplugs++; } +static void reset(void) { hpd_events = disconnects = fabric_unplugs = irq_off = 0; } +''' + +CHECKS = r''' +static void suspend_hdmi(struct apple_dcp *dcp) { SUSPEND } + +static int failures; +#define CHECK(c) do { if (!(c)) { printf("FAIL line %d (%s: %s)\n", __LINE__, case_name, #c); failures++; } } while (0) + +int main(void) +{ + const char *case_name; + struct apple_connector con; + struct gpio_desc hpd; + struct apple_dcp dcp; + int route; + +#define SETUP(name, L, N) do { case_name = name; reset(); con.connected = true; \ + hpd.level = L; dcp = (struct apple_dcp){ .connector = &con, .hdmi_hpd = &hpd, \ + .hdmi_hpd_irq = 7, .external_native = N }; } while (0) + + /* Attached through the sleep: kept, lit again on wake. */ + SETUP("kept", 1, false); + suspend_hdmi(&dcp); + CHECK(irq_off == 1 && con.connected && !disconnects); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects && !fabric_unplugs); + + /* Unplugged during the sleep: released on resume, fabric told. */ + SETUP("unplugged-in-sleep", 1, false); + suspend_hdmi(&dcp); + hpd.level = 0; + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(!con.connected && hpd_events == 1 && disconnects == 1 && fabric_unplugs == 1); + + /* Gone before the sleep: released at suspend, nothing on resume. */ + SETUP("gone-before", 0, false); + suspend_hdmi(&dcp); + CHECK(!con.connected && disconnects == 1); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(disconnects == 1 && hpd_events == 1 && !fabric_unplugs); + + /* A failed GPIO read cannot establish absence. */ + SETUP("gpio-error", 1, false); + suspend_hdmi(&dcp); + hpd.level = -5; + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects); + + /* A Type-C display owns the pipeline: the HDMI side is not touched. */ + SETUP("borrowed", 0, false); + dcp.active_typec_route = &route; + suspend_hdmi(&dcp); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(con.connected && !disconnects && !hpd_events && !fabric_unplugs); + + /* T6030 native output: released at suspend even while attached. */ + SETUP("native", 1, true); + suspend_hdmi(&dcp); + CHECK(!con.connected && disconnects == 1); + dcp_hdmi_unplugged_in_sleep(&dcp); + CHECK(disconnects == 1); + + if (failures) + return 1; + puts("PASS HDMI sleep: attached kept, unplugged-in-sleep released on resume, " + "gone-before released at suspend, GPIO error and borrowed pipeline untouched, " + "T6030 native released"); + return 0; +} +''' + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + + source = (ROOT / DCP).read_text() + if args.mutation: + old, new = MUTATIONS[args.mutation] + assert source.count(old) == 1, args.mutation + source = source.replace(old, new) + + resume = function(source, 'dcp_platform_resume') + # The release runs while the HPD IRQ is still masked: an edge from then + # on is replayed when dcp_fabric_run_resume() enables it. + if RESUME_CALL not in resume or \ + resume.index(RESUME_CALL) > resume.index('dcp_fabric_run_resume(&dcp_resume_ops, dcp)'): + print('FAIL line 0 (resume: no unplugged-in-sleep release before the HPD IRQ comes back)') + sys.exit(1) + + suspend = function(source, 'dcp_platform_suspend') + hdmi = block(suspend, suspend.index('\tif (dcp->hdmi_hpd_irq) {\n\t\tdisable_irq')) + code = HARNESS + function(source, 'dcp_hdmi_unplugged_in_sleep') + \ + CHECKS.replace('SUSPEND', hdmi) + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'check.c' + path.write_text(code) + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-fsanitize=address,undefined', str(path), '-o', str(path.with_suffix(''))], + check=True) + sys.exit(subprocess.run([str(path.with_suffix(''))]).returncode) + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index d82fd59b625ce7..48f7fb10a528a5 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -186,6 +186,10 @@ def mutations(flag, names, base, expect=KILL): # A DCP whose firmware runs through the sleep holds its DP PHYs' domains. 'dcp-sleep-phy-hold-tests.py': [([], PASS)] + mutations('--mutation', ('no-route', 'no-own-phy', 'class-device', 'no-err-check'), []), + # An HDMI display kept through a sleep but unplugged during it is released on resume. + 'dcp-hdmi-sleep-unplug-tests.py': [([], PASS)] + + mutations('--mutation', ('keep-native', 'gpio-error', 'ignore-borrowed', 'no-fabric', + 'no-resume-check'), []), 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), From 52166ad98c80677784ee2cd77dcb69cf5bf8e1eb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 17:05:19 +1100 Subject: [PATCH 0807/1514] drm/asahi: attribute G14 27.2 recoveries by the stopped command's stamp The recovery blamed the first command still in the host's compute list. That list can hold a command the firmware already completed but the host has not yet retired, ahead of the one the firmware stopped, so a healthy client could lose its context while the guilty one carried on. Each recovery snapshot entry's target is the completion stamp the stopped command would have written (on the J473: compute stamp 0x7900 written, entry {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). Refresh the retired position, then match every valid entry against the published render pair's stamps and the unretired compute commands' stamps. Blame only when all entries of a round name the same tracked command. A stopped tiler can only be the render pair. Anything unnamed, mixed or colliding keeps the fail-stop. Attribute every round, not just the first: work queued behind the first stopped command can time out while it drains. A further round must carry a new recovery generation. The attribution and round rules live in g14_v27_2_abi.rs, with host tests for a completed entry ahead of the stopped one, render pairs, ambiguous snapshots and generation changes while draining. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 73 ++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 102 +++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index a6c9056771ab4e..571c320dd2d63e 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -47,6 +47,7 @@ use crate::{ #[allow(dead_code)] mod recovery_logic; use recovery_logic::{RecoveryAction, SnapshotEntry}; +use crate::g14_v27_2_abi::{self, Stopped}; /// RTKit endpoints of the GPU firmware. const EP_FIRMWARE: u8 = 0x20; @@ -888,27 +889,30 @@ impl Runtime { packet.finish(Err(err)); } - /// Marks the work the firmware stopped: the render pair if one is published (a render is - /// published alone), else the oldest unretired compute command and the rest of its packet. - /// Returns whether anything was published. - fn blame(&self, state: &mut State, error: Error, slot: i32) -> bool { - if let Some(flight) = state.rendering.as_mut() { - flight.doomed = Some(error); - let owner = &flight.packet.owner; - dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", - owner.process(), owner.pid, slot, error); - return true; - } - let Some(packet) = state.inflight.first().map(|f| f.packet.clone()) else { - dev_err!(self.dev, "GPU: firmware stopped with nothing published (slot {})\n", slot); - return false; - }; - for flight in state.inflight.iter_mut().filter(|f| Arc::ptr_eq(&f.packet, &packet)) { - flight.doomed = Some(error); + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the + /// published render pair, or the compute command with that completion stamp and the rest of + /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. + fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { + match work { + Stopped::Render => { + let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; + flight.doomed = Some(error); + let owner = &flight.packet.owner; + dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", + owner.process(), owner.pid, slot, error); + } + Stopped::Compute(stamp) => { + let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) + .map(|f| f.packet.clone()) else { return Err(EIO); }; + let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); + for flight in state.inflight.iter_mut().filter(owned) { + flight.doomed.get_or_insert(error); + } + dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", + stamp, packet.owner.process(), packet.owner.pid, slot, error); + } } - dev_err!(self.dev, "GPU: stopped compute of {}[{}] (slot {}, {:?})\n", - packet.owner.process(), packet.owner.pid, slot, error); - true + Ok(()) } /// Whether every command marked by `blame` has left its queue. @@ -961,7 +965,7 @@ impl Runtime { fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { state.root.log_timeout(&self.dev); let mut rounds = 0; - let mut blamed = false; + let mut previous = None; loop { if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", @@ -975,6 +979,16 @@ impl Runtime { return Err(EIO); } let generation = state.root.halt_count()?; + if !g14_v27_2_abi::new_round(previous, generation) { + dev_err!(self.dev, "GPU: recovery generation {} repeated\n", generation); + return Err(EPROTO); + } + previous = Some(generation); + // Retired work must not be blamed: refresh the retired position first. + self.advance(state)?; + let render = state.rendering.as_ref() + .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); + let mut attribution = g14_v27_2_abi::Attribution::default(); let mut entries = 0; let mut stopped_tiler = false; for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { @@ -982,16 +996,25 @@ impl Runtime { let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; entries += 1; stopped_tiler |= gpu::stopped_tiler(entry.flags); + let retired = state.retired_total; + let inflight = &state.inflight; + attribution.add(entry.flags, entry.target, render, |stamp| { + inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) + }); if entries <= 8 { dev_err!(self.dev, "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", generation, i, entry.flags, entry.event, entry.target); } } - if !blamed { - blamed = true; - self.blame(state, error, slot); - } + // Every round is attributed: work behind the first stopped command can time out in + // turn. Unnamed or ambiguous stopped work keeps the fail-stop. + let Some(work) = attribution.result() else { + dev_err!(self.dev, "GPU: recovery {} names no single tracked command ({} entries)\n", + generation, entries); + return Err(EIO); + }; + self.blame(state, error, slot, work)?; if stopped_tiler { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 501be19bdd1a6a..74488ed60be911 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -89,6 +89,63 @@ pub(crate) const fn stopped_tiler(flags: u32) -> bool { flags & 9 == 9 } +/// The tracked work a recovery snapshot names. A snapshot entry's target is the completion +/// stamp the stopped command would have written (J473: compute stamp 0x7900 written, entry +/// {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Stopped { + /// The published render pair (either of its completion stamps). + Render, + /// The published compute command with this completion stamp. + Compute(u32), +} + +/// Attribution of one recovery round: every valid snapshot entry must name the same tracked, +/// unretired work, else the round is ambiguous and the caller fails all work (fail-stop). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct Attribution { + work: Option, + ambiguous: bool, +} + +impl Attribution { + /// Adds a valid entry. `render` holds the published render pair's completion stamps; + /// `compute(stamp)` says whether an unretired compute command carries that stamp. + pub(crate) fn add(&mut self, flags: u32, target: u32, render: Option<[u32; 2]>, + compute: impl Fn(u32) -> bool) { + let as_render = render.is_some_and(|stamps| stamps.contains(&target)); + // A stopped tiler can only be the render pair. + let as_compute = !stopped_tiler(flags) && compute(target); + let work = match (as_render, as_compute) { + (true, false) => Stopped::Render, + (false, true) => Stopped::Compute(target), + _ => { + self.ambiguous = true; + return; + } + }; + match self.work { + None => self.work = Some(work), + Some(seen) if seen == work => {} + Some(_) => self.ambiguous = true, + } + } + + /// The stopped work, if the round named exactly one tracked command. + pub(crate) fn result(self) -> Option { + if self.ambiguous { None } else { self.work } + } +} + +/// A further recovery round while stopped work drains must carry a new generation; the same +/// generation again means the host misread the handshake. +pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { + match previous { + None => true, + Some(p) => generation != p, + } +} + /// Event ring record kinds. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum EventKind { @@ -225,4 +282,49 @@ mod tests { assert!(!stopped_tiler(0x8)); assert!(stopped_tiler(0x9 | (0x70 << 4))); } + + #[test] + fn a_completed_front_entry_is_not_blamed_for_a_later_stop() { + // Host list: 0x7900 completed but not yet retired by the host, 0x7a00 stopped. + let unretired = [0x7900u32, 0x7a00, 0x7b00]; + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| unretired.contains(&s)); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + } + + #[test] + fn render_entries_name_the_published_pair() { + let pair = Some([0x2156600, 0x3156600]); + let mut a = Attribution::default(); + a.add(0x1f, 0x2156600, pair, |_| false); + a.add(0x7, 0x3156600, pair, |_| false); + assert_eq!(a.result(), Some(Stopped::Render)); + // A stopped tiler that matches no published pair is not pinned on compute. + let mut a = Attribution::default(); + a.add(0x1f, 0x7a00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + } + + #[test] + fn untracked_mixed_or_colliding_entries_fail_stop() { + let mut a = Attribution::default(); + assert_eq!(a.result(), None); + a.add(0x7, 0x7c00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| s == 0x7a00 || s == 0x7b00); + a.add(0x7, 0x7b00, None, |s| s == 0x7a00 || s == 0x7b00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x3156600, Some([0x2156600, 0x3156600]), |s| s == 0x3156600); + assert_eq!(a.result(), None); + } + + #[test] + fn recovery_rounds_while_draining_need_a_new_generation() { + assert!(new_round(None, 1)); + assert!(new_round(Some(1), 2)); + assert!(!new_round(Some(2), 2)); + assert!(new_round(Some(u64::MAX), 0)); + } } From fc96d3c36d44db96dddc95d693ccbc271acc319c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 17:10:21 +1100 Subject: [PATCH 0808/1514] drm/apple: take the desktop audio role only on firmware 27's own layout dcp_is_v27_external() was true for every firmware-27 DCP with DPTX ports. It is meant for the T6050 and firmware-27 T6041 DCPEXTs, whose ports are on DPTX_ENDPOINT_V2 and whose DP/HDMI audio service is the desktop one, compact EPIC on endpoint 0x2b. The T8112 DCPs (Mac mini M2) on 27.2 firmware advertise the classic layout, ports on DPTX_ENDPOINT. On them 0x2b announces only dcpdptx-hdcp-interface, and the audio service is the classic dcpav-audio-interface-epic on AV_ENDPOINT (0x29), as macOS binds it on the same machine. Taking the desktop role there waited on 0x2b for an audio service that never comes: no audio service started, the ELD stayed empty, and the HDMI and DP jacks stayed off. Take the desktop role only where the DPTX ports are on DPTX_ENDPOINT_V2 as set at probe, so that the DP audio driver, which binds before the DCP starts, sees the same role as the DCP. Every other firmware-27 DCP takes the classic audio service on AV_ENDPOINT with the firmware-27 command table. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 14 +++++++++++--- .../selftests/drivers/gpu/apple-dcp/edid.py | 3 ++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index f55c05d9f17931..94423cbca3e287 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1397,12 +1397,20 @@ static inline bool dcp_is_v14_7_external(const struct apple_dcp *dcp) } /* - * Firmware 27's external processors (the T6050 DCPEXTs): their DP/HDMI - * audio service is the desktop one, on endpoint 0x2b (see av.c). + * Firmware 27's external processors with its own DPTX endpoint layout (the + * T6050 and firmware-27 T6041 DCPEXTs, ports on DPTX_ENDPOINT_V2): their + * DP/HDMI audio service is the desktop one, on endpoint 0x2b (see av.c). + * + * A firmware-27 DCP on the classic layout (the T8112 DCPs, whose 27.2 + * firmware advertises its ports on DPTX_ENDPOINT, dcp_v27_dptx_layout()) + * has the classic audio service on AV_ENDPOINT: there 0x2b is HDCP only. + * The layout is read as set at probe, so that the DP audio driver, which + * binds before the DCP starts, sees the same role as the DCP. */ static inline bool dcp_is_v27_external(const struct apple_dcp *dcp) { - return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.num_dptx_ports; + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.num_dptx_ports && + dcp->hw.dptx_endpoint == DPTX_ENDPOINT_V2; } /* The 14.7 internal panel (J514S/J516S), presented through DCPLink. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 6898b7b368801f..19fea36e9f5ab5 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -101,7 +101,7 @@ def function(file,signature): struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; bool external_physically_absent,hpd_mutex,quiescing,typec_cable_connected;u64 typec_generation;unsigned int nr_modes; - struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints,afk_announced_names; unsigned int num_dptx_ports; } hw; bool ext_dead,external_native; + struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints,afk_announced_names; unsigned int num_dptx_ports; unsigned char dptx_endpoint; } hw; bool ext_dead,external_native; struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; u64 opened_epoch,close_gen,terminated_epoch,close_epoch;bool opening;struct work_struct close_wq; } dcpavserv; /* A J714s firmware 27 processor's: this one is not. */ @@ -109,6 +109,7 @@ def function(file,signature): /* Not a dcpext: none of these scenarios is an external processor. */ bool dcpext; }; +#define DPTX_ENDPOINT_V2 0x2c '''+internal_inline(root,'dcp_fw_is_14_7')+internal_inline(root,'dcp_is_v14_7_external')+internal_inline(root,'dcp_is_v27_external')+r'''struct epic_cmd { u32 retcode;u64 rxbuf,txbuf;u32 rxlen,txlen; }; static unsigned int dma_frees,opens; From f55ae32f692706ff409508610b3a39e969f3f508 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 17:52:31 +1100 Subject: [PATCH 0809/1514] drm/asahi: keep the G14 27.2 recovery's isolation contract Review of the G14 27.2 per-client recovery found these gaps: - A stopped command leaves its queue without a completion stamp. That proves queue progress, not that the GPU no longer reaches its memory, which is the G16 Retirement::Aborted rule. The runtime still released the command's VM job guard, binding and scene. Now the error completion quarantines the guard, and the stopped command's flight (packet, binding, scene) is kept for the rest of the boot, as stop() does for everything. Pool slots are still reused only after the firmware unregisters them. - The guilty VM was not barred from running more work. Blaming now latches its VmStatus (note_recovery_guilty + record) before the work drains. submit() refuses packets of a failed VM, and pump() fails the ones already queued instead of publishing them, as G16 does. - A render timeout that found the firmware in recovery recovered but left the render flight in place. Nothing then signalled its fence or published the queue behind it until the scheduler timeout. Retire it right after the recovery. - Scene::clear_tpc wrote through a shared slice and was available to every GPU generation. It is now an unsafe fn of the G14 27.2 scene only, and zeroes through a raw-pointer GpuArray helper with its exclusivity precondition stated. - While stopped work drains, a crashed coprocessor or a phase the protocol does not allow now fails the recovery. The whole recovery starts no round after 5 s, so the state lock is released inside the scheduler's job timeout. Control-object reads and writes validate their byte range first. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/buffer.rs | 26 ++++---- drivers/gpu/drm/asahi/g14_v27_2.rs | 77 +++++++++++++++++++++-- drivers/gpu/drm/asahi/g14_v27_2_render.rs | 10 ++- drivers/gpu/drm/asahi/gpu/v27_2.rs | 10 +++ drivers/gpu/drm/asahi/object.rs | 18 ++++++ 5 files changed, 120 insertions(+), 21 deletions(-) diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index cd79a762cb3e6a..7a19153a9096f9 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -198,20 +198,6 @@ impl Scene::ver { self.object.tpc.gpu_pointer() } - /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after - /// a firmware recovery stopped its tiler finds no tiles. - #[allow(dead_code)] - pub(crate) fn clear_tpc(&self, bytes: usize) -> Result { - let tpc = self.object.tpc.as_slice(); - if bytes > tpc.len() { return Err(ERANGE); } - // SAFETY: the TPC belongs to this scene, whose tiler was stopped by the firmware and is - // halted; nothing else writes it until the scene's fragment pass runs or is dropped. - unsafe { core::ptr::write_bytes(tpc.as_ptr().cast_mut(), 0, bytes) }; - crate::pgtable::clean_poc(tpc.as_ptr(), bytes); - crate::pgtable::poc_barrier(); - Ok(()) - } - /// Returns the GPU pointer to the first preemption scratch buffer. pub(crate) fn preempt_buf_1_pointer(&self) -> GpuPointer<'_, &'_ [u8]> { self.object.preempt_buf.gpu_pointer() @@ -308,6 +294,18 @@ impl SceneG14V13_5 { pub(crate) fn render_addresses(&self) -> (u64, u64) { self.object.with(|raw, _| (raw.user_buffer.or(0).into(), raw.stats.into())) } + + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + /// + /// # Safety + /// + /// The GPU must not access the TPC during the call (its tiler is stopped and no other + /// render using this buffer is in flight), and no CPU reference into it may be live. + pub(crate) unsafe fn clear_tpc(&self, bytes: usize) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.object.tpc.zero_prefix(bytes) } + } } /// Host-owned parameter-buffer inputs that persist across firmware submissions. diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 571c320dd2d63e..561673b82155e4 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -75,6 +75,10 @@ const RECOVERY_DRAIN_MS: i64 = 1000; /// Further recoveries answered while the stopped work drains (work behind it can time out in /// turn) before the runtime gives up. const FURTHER_RECOVERIES: u32 = 4; +/// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + +/// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler +/// job timeout. +const RECOVERY_BUDGET_MS: i64 = 5000; struct FirmwareWait { since: Instant, @@ -407,6 +411,27 @@ pub(crate) fn start<'a>( Ok(Started { backend, drm, binding, resources }) } +/// Whether the packet's VM has failed (`VmStatus` latched): its work is no longer admitted. +fn vm_failed(packet: &Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +/// Latches the VM of work a recovery stopped as guilty, before the work drains: from here on +/// `submit` refuses it and `pump` publishes none of its queued packets. +fn latch_guilty(packet: &Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + +/// Keeps a command the firmware stopped, and everything it owns (packet and VM job guard, VM +/// binding, scene), for the rest of the boot: see `Runtime::fail_doomed`. Bounded by the +/// recovery-storm window; the same as `stop` does for everything at shutdown. +fn quarantine(flight: T) { + core::mem::forget(flight); +} + struct Inflight { packet: Arc, last: bool, @@ -580,6 +605,9 @@ impl Runtime { if packet.commands.is_empty() { return Err(ENOTSUPP); } + // A VM that lost its context (a recovery found it guilty, or its work failed) runs + // nothing more on the GPU. + if vm_failed(&packet) { return Err(EIO); } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } @@ -681,6 +709,11 @@ impl Runtime { } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); + if vm_failed(&packet) { + // Queued before its VM failed: none of it is published from now on. + state.fail_publication(&packet, EIO); + continue; + } let command = packet.commands[index]; let paired = matches!(command, Command::Render { .. }); if paired && state.running() { return; } @@ -857,6 +890,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); + quarantine(flight); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -865,8 +899,11 @@ impl Runtime { } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); if state.root.recovery_phase()? == 1 && doomed.is_none() { - // The firmware stopped it and halted, but its event was not seen. - return self.recover(state, ETIMEDOUT, -1); + // The firmware stopped it and halted, but its event was not seen. Recovery + // marks it and waits until it left both queues: retire it now, so its fence + // is signalled and the queue behind it runs without waiting for another message. + self.recover(state, ETIMEDOUT, -1)?; + return self.retire_render(state); } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -878,12 +915,18 @@ impl Runtime { /// Fails a packet the firmware stopped, once none of its commands is in a queue: its /// unpublished commands are withdrawn, and its VM records the error (the client sees a /// lost context). Other clients' work is not touched. + /// + /// A stopped command left its queue without a completion stamp: that proves queue progress, + /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So + /// its VM job guard is not released: the error completion quarantines it (no mapping + /// changes), and the caller keeps the flight that owns the packet, its VM binding and + /// scene for the rest of the boot (`quarantine`). Pool slots are reused only after the + /// firmware unregisters them (`free_slots`). fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { if state.owns(packet) { return; } if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { let _ = state.pending.remove(i); } - packet.release_guard(); // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). if let Some(status) = packet.vm.status() { status.record(err); } packet.finish(Err(err)); @@ -897,6 +940,7 @@ impl Runtime { Stopped::Render => { let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); + latch_guilty(&flight.packet, error); let owner = &flight.packet.owner; dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", owner.process(), owner.pid, slot, error); @@ -908,6 +952,7 @@ impl Runtime { for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); } + latch_guilty(&packet, error); dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", stamp, packet.owner.process(), packet.owner.pid, slot, error); } @@ -966,7 +1011,14 @@ impl Runtime { state.root.log_timeout(&self.dev); let mut rounds = 0; let mut previous = None; + let began = Instant::::now(); loop { + // The state lock is held throughout: keep the whole recovery, including a last round + // started at the budget, inside the DRM scheduler's job timeout. + if began.elapsed() > Delta::from_millis(RECOVERY_BUDGET_MS) { + dev_err!(self.dev, "GPU: recovery took more than {} ms\n", RECOVERY_BUDGET_MS); + return Err(ETIMEDOUT); + } if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", error, slot); @@ -1019,7 +1071,10 @@ impl Runtime { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; if !ta_left { - flight.scene.clear_tpc()?; + // SAFETY: the firmware is in recovery phase 1 with every queue stopped, + // so the GPU does not access the stopped tiler's TPC; the CPU reads it + // nowhere, and the state lock (held) serializes every render flight. + unsafe { flight.scene.clear_tpc()? }; dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); } } @@ -1052,7 +1107,18 @@ impl Runtime { state.recoveries, start.elapsed().as_millis()); return Ok(()); } - if state.root.recovery_phase()? == 1 { break; } + if state.peer.is_crashed() { return Err(EIO); } + // Phase 0 = still draining; 1 = a new recovery (a new generation is checked + // at the next round); the host's own phases mean the handshake was misread. + match recovery_logic::action(state.root.recovery_phase()?, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => break, + _ => { + dev_err!(self.dev, "GPU: recovery phase {} while the stopped work drained\n", + state.root.recovery_phase()?); + return Err(EPROTO); + } + } if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); state.root.log_timeout(&self.dev); @@ -1180,6 +1246,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); + quarantine(done); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index c81b3b46997462..02b2b3be55ed9d 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -78,8 +78,14 @@ impl Prep { } /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. - pub(crate) fn clear_tpc(&self) -> Result { - self.scene.clear_tpc(self.tile.tpc_size) + /// Zeroes the scene's TPC after a firmware recovery stopped its tiler. + /// + /// # Safety + /// + /// As [`crate::buffer::Scene::clear_tpc`]. + pub(crate) unsafe fn clear_tpc(&self) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.scene.clear_tpc(self.tile.tpc_size) } } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 9e23697fcec5f8..d34991feb3b94e 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -741,8 +741,17 @@ impl RootV27_2 { Ok(Some((read, event))) } + /// Validates a byte range of the control object before it is sliced or cache-maintained. + fn control_range(control: &fw::types::GpuArray, from: usize, bytes: usize) -> Result { + match from.checked_add(bytes) { + Some(end) if end <= control.as_slice().len() && from % 4 == 0 => Ok(()), + _ => Err(EINVAL), + } + } + /// Reads control words from `from` into `out`. pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + Self::control_range(&self.control, from, out.len() * 4)?; let at = self.control.as_slice()[from..].as_ptr(); crate::pgtable::clean_invalidate_poc(at, out.len() * 4); crate::pgtable::poc_barrier(); @@ -754,6 +763,7 @@ impl RootV27_2 { /// Writes one control word and makes it visible to the firmware. pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + Self::control_range(&self.control, at, 4)?; self.control.shared_index(at)?.store(value, Ordering::Release); crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); crate::pgtable::poc_barrier(); diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index ef7027ff1a6363..90e492a2b1b979 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -712,6 +712,24 @@ impl> GpuArray { // this word only in aligned 32-bit transactions while the ring is live. Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) } + + /// Zeroes the first `bytes` through the raw CPU mapping, without creating a Rust reference + /// to the payload, and cleans them to the point of coherency for the GPU. + /// + /// # Safety + /// + /// No CPU reference into the range may be live, and no device may access it during the call. + pub(crate) unsafe fn zero_prefix(&self, bytes: usize) -> Result { + if bytes > self.len { + return Err(ERANGE); + } + // SAFETY: `raw` is valid for `len` bytes (type invariant) and `bytes <= len`; the caller + // guarantees that nothing else accesses the range meanwhile. + unsafe { core::ptr::write_bytes(self.raw, 0, bytes) }; + crate::pgtable::clean_poc(self.raw.cast_const(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } } impl> Deref for GpuArray { From ca69a305525df1b2f7b18e9c4dfd095908f376d4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 18:04:58 +1100 Subject: [PATCH 0810/1514] arm64: dts: apple: revert T8112 display PHY wakeup flags The J473 combined kernel stalled before journald with the newly composed Stage 2 and reached userspace with the earlier Stage 2 on the same kernel. The compiled device trees differ by the three wakeup properties added by 1274718dc5fd. Remove those properties while the handoff is investigated. The J473 and J413 device trees compile, and the combined J473 firmware-27 DTB built after this revert is byte-identical to the booted reference. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-pmgr.dtsi | 3 --- 1 file changed, 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi index ba14aa4eac3099..e2564eac95e501 100644 --- a/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-pmgr.dtsi @@ -715,7 +715,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "dptx_ext_phy"; - apple,sleep-wakeup-path; }; ps_dispdfr_fe: power-controller@3e0 { @@ -1289,7 +1288,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_usb"; - apple,sleep-wakeup-path; power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; }; @@ -1299,7 +1297,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_usb"; - apple,sleep-wakeup-path; power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; }; From 26fcdf5859dd1f2a63470eef70fa89e3b4522b90 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 18:13:07 +1100 Subject: [PATCH 0811/1514] media: apple: avd: repair the VP9 host fixture The extracted VP9 test no longer compiles after the shared scratch format check and context fields were added. Give the fixture the two scratch fields and model the shared format check at the host-test boundary. The format validator has coverage in avd-fmt-test.c. The original fixture fails to compile and this change passes the standalone suite with ASan and UBSan on the same integration base. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/avd/tests/vp9-test.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/avd/tests/vp9-test.py b/drivers/media/platform/apple/avd/tests/vp9-test.py index 0ea406aae17773..81fd4e7481416c 100644 --- a/drivers/media/platform/apple/avd/tests/vp9-test.py +++ b/drivers/media/platform/apple/avd/tests/vp9-test.py @@ -32,7 +32,7 @@ 'struct vb2_buffer { struct { size_t length; } planes[1]; dma_addr_t dma; void *cpu; size_t payload; u64 timestamp; };') pre = pre.replace('struct avd_comp comp; unsigned int bank;', 'struct avd_comp comp; unsigned int bank; struct { unsigned int width,height,bit_depth; } vp9;') pre = pre.replace('struct vb2_v4l2_buffer *dst; } bufs;', 'struct vb2_v4l2_buffer *src,*dst; } bufs;') -pre = pre.replace('unsigned int fifo_idx, pp_total;', 'unsigned int fifo_idx, pp_total, max_frames; int ctrl_hdl;') +pre = pre.replace('unsigned int fifo_idx, pp_total;', 'unsigned int fifo_idx, pp_total, max_frames; int ctrl_hdl; bool scratch_sized; enum avd_image_fmt scratch_fmt;') pre = pre.replace('static int avd_buf_alloc(struct avd_dev *d, struct avd_buf *b, size_t n)', '#ifdef AVD_TEST_VP_READY\nstatic struct avd_ctx *allocating_ctx;\nstatic int fail_alloc_after;\nstatic bool avd_vp9_ready(struct avd_ctx *);\n#endif\nstatic int avd_buf_alloc(struct avd_dev *d, struct avd_buf *b, size_t n)') pre = pre.replace('{ (void)d; free(b->cpu); b->cpu = calloc(1,n);', @@ -107,6 +107,11 @@ run->coded_in=current_src->vb2_buf.dma;run->comp_out=current_dst->vb2_buf.dma; run->y_out=run->comp_out+0x100000;run->uv_out=run->comp_out+0x300000; } +/* avd-fmt-test.c independently exercises the run image format check. */ +static int avd_check_run_image_fmt(struct avd_ctx *ctx, int fmt) +{ + (void)ctx;(void)fmt;return 0; +} static void avd_run_postamble(struct avd_ctx *ctx,struct avd_run *run) { (void)ctx;(void)run; } static int avd_init_job(struct avd_ctx *ctx,int codec,size_t segments) { free(ctx->job.segments);ctx->job.codec=codec;ctx->job.num=0; From 20cf2487e0a9c07256b9a7f24222c2ab9c3a5987 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:39:46 -0500 Subject: [PATCH 0812/1514] 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 864a1e9bc3f654..1bbc1fafa0b10f 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 2ef40886e69c55..f8421689ef133e 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 b82324d7647fef..a5765e8c4546de 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 0813/1514] 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 691fc1dc42a59c..75caf7a98ecd31 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 63238572b27eee..c7461db6b643eb 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 01e6176bdea5ec..be56ee126d4b9f 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 0814/1514] 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 75caf7a98ecd31..06d435e7646026 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 24b8dd2de3fb03..767df69e03f3e9 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 d9dabde95472b9..bf036bc95f14d3 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 70e250a3b8ef74..15f86bd2b5b996 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 f04d6add674f89..b345b944197c55 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 be56ee126d4b9f..12f9d498866c96 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 0815/1514] 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 06d435e7646026..975a9774638997 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 4c30ad932be62b..c840f3c7d92f9b 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 bcf52a272ca928..9e9389f4973152 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 d59521d36719bc..c9b23923cebf6a 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 c4a77c99f425ab07d102710344f9b0a03c039fff Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 23:49:14 -0500 Subject: [PATCH 0816/1514] drm/asahi: g16: retire completed flights inline on submit and trim poll overhead Pipelined submissions previously never retired completed flights inside submit_locked(), forcing a workqueue round-trip whenever in-flight slots filled and producing hold[0] stalls and 300-500 us tail bubbles. At the same time, every EP 0x20 interrupt triggered full housekeeping in submit_locked(), every publish_checked() ran Session::check() (including the cross-core UAT handoff lock and full TTB scan), every TA (0x70) completion triggered a 50 us EVENT_RETIRE_POLLS busy-spin while FS was still running, every retire_once() polled all nine log sub-rings and the trace ring, and retired timestamps were re-read from WC memory for both accounting and empty timestamp outputs. Deferring the full Session::check() checks (ASC_RUN, pstate > top, and check_adopted_bindings()) to the 1 ms housekeeping tick is safe because: - publish_checked() still runs Session::transport() on every submit so RTKit crashes and latched transport errors stop publication immediately; - host VM bind/unbind updates ttbs[slot] and owned_user_roots[slot] atomically under uat.inner.lock() before submit/publish, so check_adopted_bindings() detects only unexpected firmware/external TTBAT corruption rather than normal host binding races; - the host never writes pstate > top (policy::limit() bounds every published selector to 1..=top), avoiding per-submit PPL handoff lock contention; - full Session::check() still runs on every >=1 ms housekeeping tick, on the first submit after >=1 ms idle, and whenever recovery_pending() is true. Fix the hot submit and retirement paths: - Eagerly retire completed flights inside submit_locked() when an EP 0x20 event arrived, housekeeping/recovery is due, or the oldest flight's terminal fw_stamp has reached its target, leaving evented cleared when work retires so queued poll work does not spin. - Separate 1 ms housekeeping (Session::check, object health, power, auxiliary log/trace ring drain) from per-submit fast publication, using Session::transport() in publish_checked(). - Track fragment completion events (0x71) alongside stage events so TA-only (0x70) interrupts do not trigger receipt-tail busy-spins or short-repoll storms while FS is still executing, and step the initial receipt-tail backoff from 1 us -> 2 us -> 5 us. - Split channel draining into fast event+stats draining on retirement and auxiliary log/trace draining on 1 ms housekeeping, skip ktime_get() on empty event rings, reuse retired_snapshot() GPU ticks in stat_retire(), and skip WC timestamp reads when timestamp_outputs is empty. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/channel.rs | 51 +- drivers/gpu/drm/asahi/g16/engine.rs | 13 +- drivers/gpu/drm/asahi/g16/event.rs | 9 +- drivers/gpu/drm/asahi/g16/poll.rs | 308 +++++++++---- .../drivers/gpu/asahi-m4/test-poll-retire.py | 436 ++++++++++++++++++ .../drivers/gpu/asahi-m4/test-publication.py | 18 +- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 8 +- .../drivers/gpu/asahi-m4/test-timestamps.py | 9 + 8 files changed, 753 insertions(+), 99 deletions(-) create mode 100755 tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index b01a419641a027..17b5aef14c6178 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -236,12 +236,25 @@ impl Channels { Ok(()) } - /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace - /// 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 { + /// Drains the event and statistics receive rings, which carry completion notifications and + /// firmware recovery announcements. Hot retirement passes use this to avoid polling the + /// auxiliary log and trace rings on every flight; periodic housekeeping drains the rest. + pub(crate) fn drain_events_and_stats( + &self, + dev: &kernel::device::Device, + events: &mut Events, + ) -> Result { let mut result = events.drain(dev, &self.event); + let stats = events.drain_statistics(dev, &self.stats); + if result.is_ok() { + result = stats; + } + result + } + + /// Drains the nine log sub-rings and the ktrace receive ring. + pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + let mut result = Ok(()); let mut keep = |r: Result| { if result.is_ok() { result = r; @@ -251,7 +264,19 @@ impl Channels { keep(Self::drain_one(&self.log, i * 0x30, 256)); } keep(self.drain_trace(dev)); - keep(events.drain_statistics(dev, &self.stats)); + result + } + + /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace + /// and stats, 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 { + let mut result = self.drain_events_and_stats(dev, events); + let aux = self.drain_auxiliary_rings(dev); + if result.is_ok() { + result = aux; + } result } @@ -382,9 +407,21 @@ impl Firmware { self.session.transport().err() } - /// Drains the receive rings and decodes events. Called first in every poll pass. + /// Drains the receive rings and decodes events. Called on full housekeeping and idle passes. pub(crate) fn drain_rings(&mut self) -> Result { let dev = self.session.dev.clone(); self.channels.drain_rings(&dev, &mut self.events) } + + /// Drains only the event and statistics rings on the hot retirement path. + pub(crate) fn drain_events_and_stats(&mut self) -> Result { + let dev = self.session.dev.clone(); + self.channels.drain_events_and_stats(&dev, &mut self.events) + } + + /// Drains the auxiliary log and trace rings on periodic housekeeping passes. + pub(crate) fn drain_auxiliary_rings(&mut self) -> Result { + let dev = self.session.dev.clone(); + self.channels.drain_auxiliary_rings(&dev) + } } diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 0a008b0c550d74..942ac2e75b1097 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -413,6 +413,10 @@ pub(crate) struct Engine { /// The device's shared state, for the transport-error latch; set by the first poll or /// submission. pub(crate) shared: Option>, + /// Authenticated GPU tick tuple captured by [`Firmware::retired_snapshot`] for the oldest + /// flight (`[start, end, 0, 0]` for compute; `[ta_start, ta_end, fs_start, fs_end]` for + /// render), reused by accounting without re-reading WC cells. + pub(crate) retired_ticks: [u64; 4], /// Host compute ordinal and draw ordinal of the last publication. pub(crate) ordinal: u64, pub(crate) draw: u64, @@ -457,6 +461,7 @@ impl Engine { frozen: false, turn: 0, shared: None, + retired_ticks: [0; 4], ordinal: 0, draw: 0, target: 0, @@ -772,9 +777,9 @@ impl Firmware { 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. + /// [`Self::publish`] for a fast submit or poll pass that already drained/retired under this + /// device lock; verifies RTKit/transport liveness without repeating the 1 ms `Session::check` + /// register and UAT table walk on every command. pub(crate) fn publish_checked(&mut self, done: &mut Completions) -> Result { if self .session @@ -784,7 +789,7 @@ impl Firmware { { return Ok(()); } - self.session.check()?; + self.session.transport()?; // 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. diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index 26ef79a2c3a9a3..0f161367e67ac9 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -36,6 +36,7 @@ impl ErrorEvent { pub(crate) struct Events { pub(crate) compute_events: u32, + pub(crate) fs_events: u32, pub(crate) stage_events: u32, pub(crate) errors: u32, pub(crate) last_error: Option, @@ -54,6 +55,7 @@ impl Events { pub(crate) fn new() -> Self { Self { compute_events: 0, + fs_events: 0, stage_events: 0, errors: 0, last_error: None, @@ -94,6 +96,9 @@ impl Events { /// Decode notifications, copying every record before returning its slot. pub(crate) fn drain(&mut self, dev: &device::Device, ring: &Ring) -> Result { let (mut read, producer) = Self::indices(ring)?; + if read == producer { + return Ok(()); + } // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; let mut error = None; @@ -108,7 +113,9 @@ impl Events { } self.event_ns[stage] = now; self.stage_events = self.stage_events.wrapping_add(1); - if stage == 2 { + if stage == 1 { + self.fs_events = self.fs_events.wrapping_add(1); + } else if stage == 2 { self.compute_events = self.compute_events.wrapping_add(1); } } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 3070e4636d156b..76dc54a08472db 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -43,8 +43,8 @@ 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; +/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/5 us, ~48 us total). +const EVENT_RETIRE_POLLS: u32 = 11; /// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). const BACKUP_REARM_NS: u64 = 2_000_000; @@ -139,9 +139,14 @@ impl Shared { if !retry_tail { break; } + let delay_us = match step { + 0 => 1, + 1 => 2, + _ => 5, + }; tail -= 1; step += 1; - delay::udelay(Delta::from_micros(5)); + delay::udelay(Delta::from_micros(delay_us)); } if housekeeping_deferred && !self.sleeping.load(Ordering::Acquire) { @@ -175,21 +180,51 @@ impl Shared { let accepted = firmware.enqueue(job); 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) - || 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)) - }; + let housekeeping_due = + now.wrapping_sub(firmware.last_housekeeping_ns) >= HOUSEKEEPING_NS; + let had_flights = !firmware.engine.flights.is_empty(); + let was_evented = had_flights && self.evented.swap(false, Ordering::AcqRel); + let recovery_pending = firmware.recovery_pending().unwrap_or(true); + let mut pub_res = Ok(()); + if had_flights + && (was_evented + || housekeeping_due + || recovery_pending + || firmware.oldest_stamp_reached()) + { + let stage_before = firmware.events.stage_events; + let term_before = firmware.oldest_terminal_events(); + pub_res = firmware.session.transport().and_then(|()| { + let retired_any = firmware.retire_once(done)?; + firmware.answer_growth()?; + if firmware.recovery.receipt_fault || firmware.recovery_pending()? { + firmware.check_hangs(done)?; + } + if was_evented && !retired_any && !firmware.engine.flights.is_empty() { + let non_terminal_only = term_before.is_some() + && firmware.events.stage_events != stage_before + && firmware.oldest_terminal_events() == term_before + && !firmware.oldest_stamp_reached() + && !firmware.recovery.receipt_fault + && !firmware.recovery_pending().unwrap_or(true); + if !non_terminal_only { + self.evented.store(true, Ordering::Release); + } + } + Ok(()) + }); + } + if pub_res.is_ok() { + pub_res = if housekeeping_due || recovery_pending { + let r = firmware.publish(done); + if r.is_ok() { + firmware.last_housekeeping_ns = now; + } + r + } else { + firmware.publish_checked(done) + }; + } if let Err(error) = pub_res { firmware.fail_stop(error, done); self.fail_stop(error); @@ -382,6 +417,8 @@ impl Firmware { return Ok(false); } } + let stage_before = self.events.stage_events; + let term_before = self.oldest_terminal_events(); let mut lap = Lap::start(); let start = lap.on().then(now_ns); let retired_any = self.retire_once(done)?; @@ -409,12 +446,22 @@ impl Firmware { self.engine.prof.poll_ns += now_ns().wrapping_sub(start); } published?; + // A TA-only (0x70) EP 0x20 interrupt while FS is still running does not signal flight + // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it. + let non_terminal_only = !retired_any + && term_before.is_some() + && self.events.stage_events != stage_before + && self.oldest_terminal_events() == term_before + && !self.oldest_stamp_reached() + && !self.recovery.receipt_fault + && !self.recovery_pending().unwrap_or(true); // 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. + // flight retires, stop spinning so deeper queues do not burn tail waits per interrupt. if evented && had_flights && !retired_any + && !non_terminal_only && tail != 0 && !self.engine.flights.is_empty() && !self.recovery.receipt_fault @@ -431,18 +478,22 @@ impl Firmware { 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(); + // If a terminal 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 + && !non_terminal_only + && !self.engine.flights.is_empty(); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() || self.engine.frozen) } - /// Periodic 1 ms housekeeping (session/object health, power governor, administrative hang - /// checks), run after retired completion fences have been signalled when work retired. + /// Periodic 1 ms housekeeping (session/object health, power governor, auxiliary log/trace + /// ring drain, 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(()); @@ -451,6 +502,7 @@ impl Firmware { self.session.check()?; self.objects.health()?; self.service_power()?; + self.drain_auxiliary_rings()?; self.last_housekeeping_ns = now_ns(); if !self.engine.flights.is_empty() || self.recovery.receipt_fault @@ -461,12 +513,62 @@ impl Firmware { Ok(()) } - /// Drains the rings and retires all currently complete flights without sleeping. Returns - /// whether at least one flight retired. A receipt fault is left in + /// Terminal completion-event counter for the oldest in-flight command (`fs_events` for a + /// render-only flight, `compute_events` for a compute-only flight). + fn oldest_terminal_events(&self) -> Option { + let f = self.engine.oldest()?; + if f.renders != 0 && f.computes == 0 { + Some(self.events.fs_events) + } else if f.computes != 0 && f.renders == 0 { + Some(self.events.compute_events) + } else { + None + } + } + + /// Cheap single-stage stamp check for the oldest flight's terminal stage so `submit_locked()` + /// can eagerly retire finished work without scanning all rings when nothing has completed. + fn oldest_stamp_reached(&self) -> bool { + let Some(f) = self.engine.oldest() else { + return false; + }; + rmb(); + let behind = self.engine.flights.len() > 1; + let compute_ok = if f.computes != 0 { + let Ok(obs) = self.graph.compute.fw_stamp.r32(0) else { + return false; + }; + if behind { + stamp_reached(obs, f.target, self.engine.target) + } else { + obs == f.target + } + } else { + true + }; + if !compute_ok { + return false; + } + if f.renders != 0 { + let Ok(obs) = self.graph.render.fw_stamp[1].r32(0) else { + return false; + }; + if behind { + stamp_reached(obs, f.fs_target, self.engine.fs_target) + } else { + obs == f.fs_target + } + } else { + true + } + } + + /// Drains the event/stats 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()?; + self.drain_events_and_stats()?; 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()? { @@ -613,6 +715,7 @@ impl Firmware { }; rmb(); let mut full = true; + let mut ticks = [0u64; 4]; // 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. @@ -629,6 +732,7 @@ impl Firmware { let unit = f.job.resources.compute_unit(k)?; let submitted = unit.counter.r64(0)?; let (start, end) = self.compute_ticks(unit)?; + ticks = [start, end, 0, 0]; let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; full &= stamp_reached(stamp, f.target, e.target) && (stamp != f.target @@ -649,6 +753,7 @@ impl Firmware { let unit = f.job.resources.compute_unit(k)?; let submitted = unit.counter.r64(0)?; let (start, end) = self.compute_ticks(unit)?; + ticks = [start, end, 0, 0]; full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot && submitted != 0 @@ -674,6 +779,9 @@ impl Firmware { let ta_end = unit.scene.r64(0x608)?; let fs_start = unit.scene.r64(0x620)?; let fs_end = unit.scene.r64(0x628)?; + if f.computes == 0 { + ticks = [ta_start, ta_end, fs_start, fs_end]; + } 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) @@ -721,6 +829,9 @@ impl Firmware { let ta_end = unit.scene.r64(0x608)?; let fs_start = unit.scene.r64(0x620)?; let fs_end = unit.scene.r64(0x628)?; + if f.computes == 0 { + ticks = [ta_start, ta_end, fs_start, fs_end]; + } full &= g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target && g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot @@ -734,6 +845,7 @@ impl Firmware { && fs_end > fs_start; } if full { + self.engine.retired_ticks = ticks; return Ok(Retirement::Full); } if f.recovery_suspect && now_ns().saturating_sub(f.recovery_started_ns) >= 20_000_000 { @@ -789,8 +901,10 @@ impl Firmware { return; }; let timestamp_claims = f.claims; + let retired_ticks = self.engine.retired_ticks; + self.engine.retired_ticks = [0; 4]; if result.is_ok() { - self.stat_retire(&f); + self.stat_retire(&f, retired_ticks); } if receipt.owner_retired() { if let Err(error) = self.slots.retire(&mut f.claims) { @@ -991,25 +1105,29 @@ 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_unit(index)?; - let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; - command - .timestamp_outputs - .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + if !command.timestamp_outputs.is_empty() { + let unit = flight.job.resources.compute_unit(index)?; + let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } compute += 1; } super::command::Command::Render(command) => { let index = *passes.get(render).ok_or(EINVAL)? as usize; - let pass = flight.job.resources.render_pass(index)?; - let ticks = [ - pass.scene.r64(0x600)?, - pass.scene.r64(0x608)?, - pass.scene.r64(0x620)?, - pass.scene.r64(0x628)?, - ]; - command - .timestamp_outputs - .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + if !command.timestamp_outputs.is_empty() { + let pass = flight.job.resources.render_pass(index)?; + let ticks = [ + pass.scene.r64(0x600)?, + pass.scene.r64(0x608)?, + pass.scene.r64(0x620)?, + pass.scene.r64(0x628)?, + ]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } render += 1; } } @@ -1019,7 +1137,7 @@ impl Firmware { /// A retired prefix: publication to retirement (including any wait behind its /// predecessor), event times, internal stage times of its members. - fn stat_retire(&mut self, f: &Flight) { + fn stat_retire(&mut self, f: &Flight, ticks: [u64; 4]) { let now = now_ns(); let d = now.wrapping_sub(f.published_ns); let kind = if f.computes != 0 && f.renders != 0 { @@ -1033,51 +1151,77 @@ impl Firmware { let (mut first, mut last) = (u64::MAX, 0u64); let s = &mut self.engine.stats; - // Add one stage interval read from internal timestamp cells (start, end). - let mut stage = |o: &super::object::FwObject, - off: usize, - sum: &mut u64, - engine: crate::usage::Engine| { - let (Ok(start_lo), Ok(start_hi), Ok(end_lo), Ok(end_hi)) = - (o.r32(off), o.r32(off + 4), o.r32(off + 8), o.r32(off + 12)) - else { - return; - }; - let start = u64::from(start_hi) << 32 | u64::from(start_lo); - let end = u64::from(end_hi) << 32 | u64::from(end_lo); - if start == 0 || end < start { - return; - } - f.job - .queue - .usage - .add(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); - *sum = sum.saturating_add(end - start); - lo = lo.min(start); - hi = hi.max(end); - }; - for k in 0..f.renders as usize { - let Ok(p) = f.job.resources.render_pass(f.claims.pass[k] as usize) else { - return; + let mut add_interval = + |start: u64, end: u64, sum: &mut u64, engine: crate::usage::Engine| { + if start == 0 || end < start { + return; + } + f.job + .queue + .usage + .add(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); + *sum = sum.saturating_add(end - start); + lo = lo.min(start); + hi = hi.max(end); }; - stage( - &p.scene, - 0x600, + if f.renders == 1 && f.computes == 0 && ticks[0] != 0 { + add_interval( + ticks[0], + ticks[1], &mut s.ta_ticks, crate::usage::Engine::Vertex, ); - stage( - &p.scene, - 0x620, + add_interval( + ticks[2], + ticks[3], &mut s.fs_ticks, crate::usage::Engine::Fragment, ); - } - for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { - let Ok(c) = f.job.resources.compute_unit(f.claims.slot[k] as usize) else { - return; + } else if f.computes == 1 && f.renders == 0 && ticks[0] != 0 { + add_interval( + ticks[0], + ticks[1], + &mut s.cdm_ticks, + crate::usage::Engine::Compute, + ); + } else { + // Multi-command prefix fallback: read each member's internal timestamp cells. + let mut stage = |o: &super::object::FwObject, + off: usize, + sum: &mut u64, + engine: crate::usage::Engine| { + let (Ok(start_lo), Ok(start_hi), Ok(end_lo), Ok(end_hi)) = + (o.r32(off), o.r32(off + 4), o.r32(off + 8), o.r32(off + 12)) + else { + return; + }; + let start = u64::from(start_hi) << 32 | u64::from(start_lo); + let end = u64::from(end_hi) << 32 | u64::from(end_lo); + add_interval(start, end, sum, engine); }; - stage(&c.its, 0, &mut s.cdm_ticks, crate::usage::Engine::Compute); + for k in 0..f.renders as usize { + let Ok(p) = f.job.resources.render_pass(f.claims.pass[k] as usize) else { + return; + }; + stage( + &p.scene, + 0x600, + &mut s.ta_ticks, + crate::usage::Engine::Vertex, + ); + stage( + &p.scene, + 0x620, + &mut s.fs_ticks, + crate::usage::Engine::Fragment, + ); + } + for k in 0..(f.computes as usize).min(f.claims.slot_count as usize) { + let Ok(c) = f.job.resources.compute_unit(f.claims.slot[k] as usize) else { + return; + }; + stage(&c.its, 0, &mut s.cdm_ticks, crate::usage::Engine::Compute); + } } if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py new file mode 100755 index 00000000000000..76aed513a624d7 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -0,0 +1,436 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Execute production G16 inline submit retirement and EP 0x20 poll-step logic.""" +from common import kernel_root, output_dir, rustc, sha +import json +import subprocess + +production = kernel_root() / 'drivers/gpu/drm/asahi/g16/poll.rs' +source = production.read_text() +output = output_dir() + + +def item(declaration): + start = source.index(declaration) + at = source.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +harness = r''' +#![allow(dead_code, unused_variables)] +use std::cell::Cell; +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct Error(i32); +type Result = std::result::Result; + +const HOUSEKEEPING_NS: u64 = 1_000_000; +const EVENT_RETIRE_POLLS: u32 = 11; + +thread_local! { + static CLOCK: Cell = const { Cell::new(0) }; +} +fn now_ns() -> u64 { + CLOCK.with(|c| c.get()) +} +fn rmb() {} +fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { + let diff = obs.wrapping_sub(own) as i32; + let span = tail.wrapping_sub(own) as i32; + diff >= 0 && diff <= span +} + +struct Job { + id: u32, +} +type Completions = Vec; + +struct Lap; +impl Lap { + fn start() -> Self { + Self + } + fn on(&self) -> bool { + false + } + fn lap(&mut self, _acc: &mut u64) {} +} + +struct Cell32(Cell); +impl Cell32 { + fn new(v: u32) -> Self { + Self(Cell::new(v)) + } + fn r32(&self, _off: usize) -> Result { + Ok(self.0.get()) + } +} + +struct ComputeGraph { + fw_stamp: Cell32, +} +struct RenderGraph { + fw_stamp: [Cell32; 2], +} +struct Graph { + compute: ComputeGraph, + render: RenderGraph, +} + +#[derive(Default)] +struct Stats { + idle_from_ns: u64, + starve_from_ns: u64, +} +#[derive(Default)] +struct Prof { + retire_ns: u64, + polls: u64, + poll_ns: u64, +} + +struct Flight { + computes: u32, + renders: u32, + target: u32, + fs_target: u32, +} + +struct Engine { + shared: Option>, + flights: Vec, + pending: Vec>, + target: u32, + fs_target: u32, + chan_wait: bool, + short_repoll: bool, + frozen: bool, + stats: Stats, + prof: Prof, +} +impl Engine { + fn oldest(&self) -> Option<&Flight> { + self.flights.first() + } +} + +#[derive(Default)] +struct Events { + stage_events: u32, + fs_events: u32, + compute_events: u32, +} + +#[derive(Default)] +struct Recovery { + receipt_fault: bool, + pending: bool, + failed: Option, +} +impl Recovery { + fn failed(&self) -> Option { + self.failed + } + fn needs_repoll(&self) -> bool { + self.pending + } +} + +struct Session; +impl Session { + fn transport(&self) -> Result { + Ok(()) + } + fn check(&self) -> Result { + Ok(()) + } +} +struct Objects; +impl Objects { + fn health(&self) -> Result { + Ok(()) + } +} + +struct Shared { + sleeping: AtomicBool, + evented: AtomicBool, + rearmed: Cell, +} +impl Shared { + fn new() -> Arc { + Arc::new(Self { + sleeping: AtomicBool::new(false), + evented: AtomicBool::new(false), + rearmed: Cell::new(0), + }) + } + fn rearm(&self, _soon: bool) { + self.rearmed.set(self.rearmed.get() + 1); + } + fn fail_stop(&self, _e: Error) {} + __SUBMIT_LOCKED__ +} + +struct Firmware { + session: Session, + objects: Objects, + graph: Graph, + engine: Engine, + events: Events, + recovery: Recovery, + last_housekeeping_ns: u64, + // Test script knobs for retire_once / publish / housekeeping observation. + retire_on_call: bool, + drain_stage_delta: u32, + drain_fs_delta: u32, + drain_compute_delta: u32, + retire_calls: u32, + publish_full_calls: u32, + publish_checked_calls: u32, + housekeeping_calls: u32, +} + +impl Firmware { + fn new() -> Self { + Self { + session: Session, + objects: Objects, + graph: Graph { + compute: ComputeGraph { + fw_stamp: Cell32::new(0), + }, + render: RenderGraph { + fw_stamp: [Cell32::new(0), Cell32::new(0)], + }, + }, + engine: Engine { + shared: None, + flights: vec![], + pending: vec![], + target: 0, + fs_target: 0, + chan_wait: false, + short_repoll: false, + frozen: false, + stats: Stats::default(), + prof: Prof::default(), + }, + events: Events::default(), + recovery: Recovery::default(), + last_housekeeping_ns: 0, + retire_on_call: false, + drain_stage_delta: 0, + drain_fs_delta: 0, + drain_compute_delta: 0, + retire_calls: 0, + publish_full_calls: 0, + publish_checked_calls: 0, + housekeeping_calls: 0, + } + } + + fn enqueue(&mut self, job: Arc) -> Result { + self.engine.pending.push(job); + Ok(()) + } + fn recovery_pending(&self) -> Result { + Ok(self.recovery.pending) + } + fn recovery_idle(&mut self) -> Result { + Ok(!self.recovery.pending) + } + fn service_power(&mut self) -> Result { + Ok(()) + } + fn drain_rings(&mut self) -> Result { + Ok(()) + } + fn answer_growth(&mut self) -> Result { + Ok(()) + } + fn check_hangs(&mut self, _done: &mut Completions) -> Result { + Ok(()) + } + fn fail_stop(&mut self, error: Error, _done: &mut Completions) { + self.recovery.failed = Some(error); + } + fn run_housekeeping(&mut self, _done: &mut Completions) -> Result { + self.housekeeping_calls += 1; + self.last_housekeeping_ns = now_ns(); + Ok(()) + } + fn retire_once(&mut self, done: &mut Completions) -> Result { + self.retire_calls += 1; + self.events.stage_events += self.drain_stage_delta; + self.events.fs_events += self.drain_fs_delta; + self.events.compute_events += self.drain_compute_delta; + if self.retire_on_call && !self.engine.flights.is_empty() { + self.engine.flights.remove(0); + done.push(1); + return Ok(true); + } + Ok(false) + } + fn publish(&mut self, _done: &mut Completions) -> Result { + self.publish_full_calls += 1; + Ok(()) + } + fn publish_checked(&mut self, _done: &mut Completions) -> Result { + self.publish_checked_calls += 1; + Ok(()) + } + + __POLL_STEP__ + __OLDEST_TERMINAL_EVENTS__ + __OLDEST_STAMP_REACHED__ +} + +#[test] +fn submit_locked_retires_inline_on_reached_stamp_without_full_housekeeping() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + shared.evented.store(true, Ordering::Release); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.target = 0x100; + fw.graph.compute.fw_stamp.0.set(0x100); + fw.retire_on_call = true; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert_eq!(done, vec![1]); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.publish_full_calls, 0); + assert!(!shared.evented.load(Ordering::Acquire)); +} + +#[test] +fn submit_locked_preserves_evented_when_irq_precedes_receipt() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + shared.evented.store(true, Ordering::Release); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert!(shared.evented.load(Ordering::Acquire)); +} + +#[test] +fn ta_only_event_does_not_spin_or_arm_short_repoll() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + // Simulate draining a TA (0x70) stage event with no FS (0x71) event and FS stamp unreached. + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + let active = fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); +} + +#[test] +fn fs_event_without_settled_receipt_still_polls_tail_and_sets_short_repoll() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 1; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + let active = fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(retry_tail); + + retry_tail = false; + let active = fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert!(active); + assert!(!retry_tail); + assert!(fw.engine.short_repoll); +} +''' + +for token, decl in { + '__SUBMIT_LOCKED__': 'fn submit_locked(', + '__POLL_STEP__': 'pub(crate) fn poll_step(', + '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', + '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', +}.items(): + harness = harness.replace(token, item(decl)) + +unit = output / 'poll-retire.rs' +unit.write_text(harness) +log = '' +for command in [ + rustc() + ['--edition=2021', '--test', str(unit), '-o', str(output / 'poll-retire')], + [str(output / 'poll-retire'), '--nocapture'], +]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + log += result.stdout + print(result.stdout, end='') + (output / 'poll-retire.log').write_text(log) + if result.returncode: + raise SystemExit(result.returncode) +(output / 'poll-retire.json').write_text( + json.dumps( + { + 'passed': True, + 'tests': 4, + 'cpu_only': True, + 'hardware_execution': False, + 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', + 'source_sha256': sha(production), + }, + indent=2, + ) + + '\n' +) 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 ba322395c26f16..36e31ac2cb0a24 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -61,9 +61,10 @@ 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,rings:Vec,ring_fail:bool} +struct Session{shared:Shared,rings:Vec,ring_fail:bool,checks:AtomicU32,transports:AtomicU32} impl Session{ - fn check(&self)->Result{Ok(())} + fn check(&self)->Result{self.checks.fetch_add(1,Ordering::Relaxed);Ok(())} + fn transport(&self)->Result{self.transports.fetch_add(1,Ordering::Relaxed);Ok(())} fn ring(&mut self,channel:Channel)->Result{ if self.ring_fail{return Err(EIO);} self.rings.push(channel); @@ -174,7 +175,7 @@ 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)},rings:vec![],ring_fail: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,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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(), @@ -435,6 +436,17 @@ def item(declaration): p.engine.flights[0].recovery_suspect=true; assert!(!p.can_queue_behind(&r2)); } + #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ + let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); + let mut done=vec![]; + fw.publish_checked(&mut done).unwrap(); + assert_eq!(fw.session.checks.load(Ordering::Relaxed),0); + assert_eq!(fw.session.transports.load(Ordering::Relaxed),1); + let mut fw2=firmware(vec![job(2,false,0,Ok(()))],vec![(Ok(()),true)]); + fw2.publish(&mut done).unwrap(); + assert_eq!(fw2.session.checks.load(Ordering::Relaxed),1); + assert_eq!(fw2.session.transports.load(Ordering::Relaxed),1); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) 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 1ff81b81410d86..85b1af454e929b 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 @@ -46,7 +46,7 @@ def function(text, name): 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],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} +struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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} @@ -70,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,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}, + 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,retired_ticks:[0;4]}, 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,completed:2},queue_passed:true, }; @@ -172,6 +172,10 @@ def function(text, name): assert_eq!(f.retired(),Ok(Retirement::Pending)); f.engine.flights[0].job.resources.compute[0].its.unstable=false; assert_eq!(f.retired(),Ok(Retirement::Full)); + assert_eq!(f.engine.retired_ticks,[100,101,0,0]); + let mut r=firmware(true,1); + assert_eq!(r.retired(),Ok(Retirement::Full)); + assert_eq!(r.engine.retired_ticks,[100,101,102,103]); } '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) 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 064f8b39215839..ed8087e3f2b320 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -63,6 +63,7 @@ def function(source, marker): impl Destination { __WRITE__ } struct Destinations([Option;4]); impl Destinations { + fn is_empty(&self)->bool{self.0.iter().all(Option::is_none)} fn iter(&self)->core::slice::Iter<'_,Option>{self.0.iter()} __PUBLISH__ } @@ -197,6 +198,14 @@ def function(source, marker): assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EINVAL)); assert_eq!(memory.words[0].load(Ordering::Relaxed),u64::MAX); } +#[test]fn empty_timestamp_outputs_skip_hardware_cell_reads(){ + let flight=Flight{job:Job{commands:vec![ + command::Command::Compute(command::Compute{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), + command::Command::Render(command::Render{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), + ],resources:Resources{compute:vec![],passes:vec![]}},first:0,count:2,renders:1}; + let claims=slots::Claims{slot:[0,0],slot_count:1,pass:[0,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); +} '''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) path = out / 'timestamps-host.rs' path.write_text(source) From 8a125d5cbfe340b427f4bdf2ba2690eca30d9df7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:16 -0500 Subject: [PATCH 0817/1514] 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 975a9774638997..c96d68cffc52b5 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 d79d5892d31f49..15740f7d5ee9c6 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 b3dbc6bd3c73b8..dfef940d5b25a9 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 bf036bc95f14d3..72f897fd6b8f11 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 a383a09b8d9711..bb4069ec02171d 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 efe5a60fd2cfdc..b2a4cc45ac7d35 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 fcf936c3db6ee43bd8318d4361acf3ec93e08294 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 06:58:37 -0500 Subject: [PATCH 0818/1514] drm/asahi: g16: expand render pass slots to 16 and trim clean-reuse work writes With RENDER_SLOTS = 8, render pipelining capped out at 7 in-flight passes (stalling depth 8 and 16 workloads), while each render pass recomputed Geometry::new() three times and rewrote the untouched zero middle gaps of both ta_work (0x360..0x740, 992 bytes) and fs_work (0x460..0x780, 800 bytes) into write-combining memory on every clean same-VM reuse. Both WORK_STRIDE and RENDER_SLOTS are host client-VA layout choices rather than firmware bounds: firmware receives explicit 64-bit VAs for each pass object rather than indexing by stride. Each pass slot spans +0x0..+0x1c00000 (28 MiB: TILEMAP at +0x1400000 plus 8 MiB TILEMAP_SIZE), which rounds to a 32 MiB power-of-two stride (4 MiB guard) and yields 16 slots inside the 512 MiB window 0x7020000000..0x7040000000 (matching COMPUTE_UNITS = 16). - Halve WORK_STRIDE / PASS_STRIDE from 64 MiB to 32 MiB and expand RENDER_SLOTS from 8 to 16 inside the existing 0x7020000000..0x7040000000 window, raising pipelined render depth from 7 to 15. - Keep full 16 MiB TPC / 8 MiB tilemap capacity on the two base pass slots (0..BASE_RENDER_SLOTS) and size extension slots (2..16) to 2 MiB TPC / 1 MiB tilemap so bursting VMs support 15 concurrent passes up to 4K multi-layer and 8K without inflating per-VM RAM. - Track RenderOwners::last_full (mirroring ComputeOwners::last_full) and write only the active head and tail spans of ta_work and fs_work on clean same-VM reuse, saving 1,792 bytes of WC writes per render pass while full-scrub claims still write the complete images. - Compute render Geometry once per publication and update only layer_metadata after claiming the pass slot. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 27 ++++++++--- drivers/gpu/drm/asahi/g16/fw/work.rs | 16 +++++++ drivers/gpu/drm/asahi/g16/hw.rs | 23 +++++++--- drivers/gpu/drm/asahi/g16/resources.rs | 2 +- drivers/gpu/drm/asahi/g16/slots.rs | 16 ++++++- .../drivers/gpu/asahi-m4/test-publication.py | 2 +- .../drivers/gpu/asahi-m4/test-resources.py | 45 +++++++++++++------ 7 files changed, 101 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 942ac2e75b1097..92a9b9b0814dd0 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1307,7 +1307,7 @@ impl Firmware { 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, behind)?; + self.prefix_render(job, r, geometry, &mut prefix, f, behind)?; } } f.first = index as usize; @@ -1584,6 +1584,7 @@ impl Firmware { &mut self, job: &Arc, cmd: &RenderCommand, + mut geometry: Geometry, pf: &mut Prefix, f: &mut Flight, behind: bool, @@ -1592,10 +1593,9 @@ 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), tilemap_bytes)?; + .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.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)?; @@ -1605,7 +1605,7 @@ impl Firmware { 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.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; job.resources .set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; @@ -1649,8 +1649,23 @@ impl Firmware { init_buffer, &mut scratch.scene[..], ); - p.ta_work.write(0, &scratch.ta[..])?; - p.fs_work.write(0, &scratch.fs[..])?; + if self.slots.render_needs_full_work(k) { + p.ta_work.write(0, &scratch.ta[..])?; + p.fs_work.write(0, &scratch.fs[..])?; + } else { + p.ta_work + .write(0, &scratch.ta[..work::ta::HEAD_ACTIVE_SIZE])?; + p.ta_work.write( + work::ta::TAIL_ACTIVE_START, + &scratch.ta[work::ta::TAIL_ACTIVE_START..], + )?; + p.fs_work + .write(0, &scratch.fs[..work::fs::HEAD_ACTIVE_SIZE])?; + p.fs_work.write( + work::fs::TAIL_ACTIVE_START, + &scratch.fs[work::fs::TAIL_ACTIVE_START..], + )?; + } p.ta_seq.write(0, &scratch.tas[..])?; p.fs_seq.write(0, &scratch.fss[..])?; p.scene.write(0, &scratch.scene[..])?; diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index 11b470b52330d0..0341c5f6116daa 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -65,6 +65,11 @@ pub(crate) mod compute; /// TA work image and microsequence. pub(crate) mod ta { pub(crate) const WORK_SIZE: usize = 0x940; + /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) + /// spans of a TA work image. The intervening zero gap is cleared on full scrubs and skipped + /// on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x360; + pub(crate) const TAIL_ACTIVE_START: usize = 0x740; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x40; @@ -107,6 +112,9 @@ pub(crate) mod ta { && l.auxiliary + 8 <= WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); + const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); + const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); 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, @@ -121,6 +129,11 @@ pub(crate) mod ta { /// FS work image and microsequence. pub(crate) mod fs { pub(crate) const WORK_SIZE: usize = 0xca0; + /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) + /// spans of an FS work image. The intervening zero gap is cleared on full scrubs and skipped + /// on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x460; + pub(crate) const TAIL_ACTIVE_START: usize = 0x780; pub(crate) const SEQ_SIZE: usize = 0x380; pub(crate) const SEQ_OBJECT: usize = 0x1000; pub(crate) const REGS: usize = 0x80; @@ -166,6 +179,9 @@ pub(crate) mod fs { && l.flag < WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); + const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); + const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); 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/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 3aa108e85827f2..435d83ac8c5593 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -633,12 +633,16 @@ 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 64 MiB interval within 0x7020000000..0x7040000000. + // Host-chosen client VA layout for render pass slots within 0x7020000000..0x7040000000 + // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than + // indexing by stride. One pass slot spans +0x0..+0x1c00000 (28 MiB: TILEMAP at +0x1400000 + // plus TILEMAP_SIZE = 0x800000), rounded up to a 32 MiB power-of-two stride (4 MiB guard) + // so 16 slots fill the 512 MiB window (matching COMPUTE_UNITS = 16). 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 = 0x04000000; + pub(crate) const WORK_STRIDE: u64 = 0x02000000; pub(crate) const PASS_STRIDE: u64 = WORK_STRIDE; pub(crate) const PRE0_PAGE: u64 = 0x7020080000; pub(crate) const PRE1_PAGE: u64 = 0x70200a0000; @@ -653,8 +657,10 @@ pub(crate) mod client { pub(crate) const TPC_SIZE: u64 = 0x1000000; 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; + /// Extension pass slot TPC/tilemap sizes (2 MiB / 1 MiB, covering 4K multi-layer and 8K + /// passes); base slots keep full `TPC_SIZE` / `TILEMAP_SIZE` for worst-case geometries. + pub(crate) const TPC_SLOT_SIZE: u64 = 0x200000; + pub(crate) const TILEMAP_SLOT_SIZE: u64 = 0x100000; pub(crate) const TPC_SLOT_STRIDE: u64 = WORK_STRIDE; pub(crate) const CT: u64 = 0x7080000000; pub(crate) const CT_STRIDE: u64 = 0x1000000; @@ -668,9 +674,12 @@ 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; - /// 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; + /// Base render pass slots allocated on first render (full TPC/tilemap capacity). + pub(crate) const BASE_RENDER_SLOTS: usize = 2; + /// Retained render pass slots per VM at most (host client-VA budget: 512 MiB / 32 MiB + /// stride = 16, not a firmware limit). 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 = 16; 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); diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index f53be8b55c3362..066a757fbc7c57 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -82,7 +82,7 @@ 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; +pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLOTS; pub(crate) struct RenderArena(crate::cleanup::Deferred); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 6b0fa2d5b0b3e5..eab8062e25261b 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -154,12 +154,12 @@ impl PassSlot { pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { let sh = Class::Shared; let (ps, ws) = (i * client::PASS_STRIDE, i * client::WORK_STRIDE); - let tpc = if i != 0 { + let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TPC_SLOT_SIZE } else { client::TPC_SIZE }; - let tilemap = if i != 0 { + let tilemap = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TILEMAP_SLOT_SIZE } else { client::TILEMAP_SIZE @@ -447,6 +447,8 @@ pub(crate) struct RenderOwners { 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], + /// Whether the most recent claim of each render pass slot required a full scrub/work write. + last_full: [bool; sizes::RENDER_SLOTS], } pub(crate) struct Slots { @@ -490,6 +492,7 @@ impl Slots { arena: [const { None }; sizes::RENDER_SLOTS], pending_arena: [const { None }; sizes::RENDER_SLOTS], scrub_full: [true; sizes::RENDER_SLOTS], + last_full: [true; sizes::RENDER_SLOTS], }, GFP_KERNEL, )?, @@ -675,6 +678,13 @@ impl Slots { } None } + /// Whether the most recent claim of render pass slot `k` requires writing the entire + /// TA/FS work images (first use, cross-VM switch, cancelled preparation, error, or + /// firmware recovery) rather than only the active non-zero spans. + pub(crate) fn render_needs_full_work(&self, k: usize) -> bool { + self.render.last_full.get(k).copied().unwrap_or(true) + } + #[allow(dead_code)] pub(crate) fn claim_pass(&mut self, arena: &super::resources::RenderArena, k: usize) -> Result { self.claim_pass_for(arena, k, None) @@ -709,6 +719,7 @@ impl Slots { self.render.lifetime.cancel(k); return Err(e); } + self.render.last_full[k] = full; if full { arena.tpc_dirty[k].store(0, Ordering::Relaxed); } @@ -756,6 +767,7 @@ impl Slots { self.render.lifetime.cancel(k); return Err(e); } + self.render.last_full[k] = full; if full { tpc_dirty.store(0, Ordering::Relaxed); tilemap_dirty.store(0, Ordering::Relaxed); 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 36e31ac2cb0a24..d32170ca87370a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -341,7 +341,7 @@ def item(declaration): 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} pub fn render_flights()->usize{7} } + mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{15} } impl QueueBehindHost { __CAN_QUEUE_BEHIND__ } 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 9b4789b9f6d2a5..e27f000089eb33 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -161,7 +161,7 @@ def module(text, name): 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;8],pub tilemap_dirty:[AtomicU64;8]} + pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} @@ -179,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)};8],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};8]}} + Arenas{compute:g16::resources::ComputeArena{compute},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<=Vec::new(); - // Publish 7 concurrent passes in flight (slots 0..7). - for k in 0..7usize { + // Publish 15 concurrent passes in flight (slots 0..15). + for k in 0..15usize { 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. + assert_eq!(s.render_published(),15); + assert!(s.pass_available(16)); // slot 15 is still fresh + // Retire 0 and 1 -> slot 0 is displaced and reusable while 13 others remain in flight. s.retire(&mut live[0]).unwrap(); - assert!(!s.pass_available(7)); // slot 0 not displaced yet + assert!(!s.pass_available(15)); // slot 0 not displaced yet s.retire(&mut live[1]).unwrap(); - assert!(s.pass_available(7)); // slot 0 displaced by slot 1! + assert!(s.pass_available(15)); // slot 0 displaced by slot 1! + // Clean same-VM reuse of displaced slot 0 does not need full work write. + s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); + assert!(!s.render_needs_full_work(0)); + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.release(&mut c0); + // Cancelled preparation or cross-VM switch forces full work write again. + s.claim_pass_for(&arena,0,Some(b.id)).unwrap(); + assert!(s.render_needs_full_work(0)); + s.release(&mut c0); for c in live.iter_mut().skip(2) { s.retire(c).unwrap(); } From 4c0aaf1e1b3eeb629ce6b017b4d4c0d0775419b7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:41 -0500 Subject: [PATCH 0819/1514] 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 d949013e462060..064b297f75bc51 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 c96d68cffc52b5..6936b40afd35ca 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 c840f3c7d92f9b..f92bea3be3d377 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 72f897fd6b8f11..a655094bfd1397 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 739cfd1510de4b..3eeb2cf794f217 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 c7461db6b643eb..98165ef4abe696 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 b345b944197c55..ba266654343021 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 cbe759e73feb5a..d93aa65b30fee4 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 12f9d498866c96..a4dd5e322e2abc 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 41a8c1a9dd217d..fe522d3c800c52 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 2abd69cf194e18..064f8b39215839 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 4adab97f652b424a8bc411c4174a9d6ac9e460ae Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 23:55:34 -0500 Subject: [PATCH 0820/1514] drm/asahi: g16: batch VM coverage checks and trim SUBMIT CPU overhead Every SUBMIT ioctl currently takes 10-40 separate gpuvm.lock_inner() holds across command root validation, attachment checks, and per-record stream-gate walks, decodes the command stream twice, calls ktime_get() on every submit even after extension arenas are allocated, and unconditionally notifies the standby condvar even with zero waiters. - Batch page-aligned VM range checks in g16/command.rs through a 48-entry stack SpanBatch calling vm.covers_ranges_batch() once per render or compute command, preserving exact per-span EINVAL/ENOENT/EACCES error reporting on failure. - Collapse command::prepare()'s two stream decode passes into one. - Reuse page coverage across 256-byte window cache hits in g16/gate.rs instead of calling cover() on every record in the same page. - Skip ktime_get() burst tracking in g16/resources.rs once extension arenas are already allocated, and skip standby_available.notify_all() when no waiter is blocked. - Add a host unit test in test-stream-gate.py verifying window-cached coverage reuse. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 161 ++++++++++++------ drivers/gpu/drm/asahi/g16/gate.rs | 10 +- drivers/gpu/drm/asahi/g16/resources.rs | 133 ++++++++------- .../drivers/gpu/asahi-m4/test-stream-gate.py | 20 +++ 4 files changed, 208 insertions(+), 116 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index d798c399f2075e..2e666bba9f1bb4 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -405,10 +405,9 @@ pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { Ok(()) } -/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested -/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a -/// page without the access EACCES. -pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { +/// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and +/// outside every driver-reserved range, returning `(first_page, byte_size)`. +fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { let mask = mmu::UAT_PGMSK as u64; if end <= start { return Err(EINVAL); @@ -428,17 +427,86 @@ pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) if first < range.start || last > range.end { return Err(EINVAL); } - if vm.covers_range(first, last - first, read, write) { + Ok((first, last - first)) +} + +/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested +/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a +/// page without the access EACCES. +pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + let (first, size) = align_span(start, end)?; + if vm.covers_range(first, size, read, write) { Ok(()) - } else if vm.covers_range(first, last - first, false, false) { + } else if vm.covers_range(first, size, false, false) { Err(EACCES) } else { Err(ENOENT) } } +/// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while +/// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. +struct SpanBatch { + ranges: [(u64, u64, u8); 48], + len: usize, +} + +impl SpanBatch { + const fn new() -> Self { + Self { + ranges: [(0, 0, 0); 48], + len: 0, + } + } + + fn push(&mut self, vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + let (first, size) = align_span(start, end)?; + let access = u8::from(read) | (u8::from(write) << 1); + if self.ranges[..self.len] + .iter() + .any(|&(a, s, acc)| a == first && s == size && (acc & access) == access) + { + return Ok(()); + } + if self.len == self.ranges.len() { + self.flush(vm)?; + } + self.ranges[self.len] = (first, size, access); + self.len += 1; + Ok(()) + } + + fn flush(&mut self, vm: &mmu::Vm) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + if vm.covers_ranges_batch(&self.ranges[..n]).0 { + return Ok(()); + } + for &(first, size, access) in &self.ranges[..n] { + let read = access & 1 != 0; + let write = access & 2 != 0; + if !vm.covers_range(first, size, read, write) { + return if vm.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + }; + } + } + Ok(()) + } +} + /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. -fn check_attachments(vm: &mmu::Vm, list: &[uapi::drm_asahi_attachment], write: bool) -> Result { +fn check_attachments( + batch: &mut SpanBatch, + vm: &mmu::Vm, + list: &[uapi::drm_asahi_attachment], + write: bool, +) -> Result { for attachment in list { let end = attachment .pointer @@ -452,7 +520,7 @@ fn check_attachments(vm: &mmu::Vm, list: &[uapi::drm_asahi_attachment], write: b if (last - first) / 128 > u64::from(u32::MAX) { return Err(EINVAL); } - cover(vm, first, last, true, write)?; + batch.push(vm, first, last, true, write)?; } Ok(()) } @@ -486,6 +554,7 @@ fn compact(gva: u64) -> bool { /// does not describe the complete ZLS surface layout. The encoded stride is a /// register word, not a byte distance (the C HAL200 contract). fn check_zls_plane( + batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render, stencil: bool, @@ -511,7 +580,7 @@ fn check_zls_plane( .checked_mul(u64::from(cmd.layers - 1)) .and_then(|bytes| bytes.checked_add(1)) .ok_or(EINVAL)?; - cover( + batch.push( context.vm, z.base, z.base.checked_add(minimum).ok_or(EINVAL)?, @@ -529,7 +598,12 @@ fn check_zls_plane( } /// Per-command render admission. -fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { +fn check_render( + context: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], +) -> Result { check_render_helpers(cmd)?; let vm = context.vm; let allowed = PROCESS_EMPTY_TILES @@ -576,9 +650,9 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu if vdm & 3 != 0 || !compact(vdm) || scissor == 0 || scissor & 3 != 0 { return Err(EINVAL); } - cover(vm, vdm, vdm + 4, true, false)?; - gate::vdm(vm, vdm)?; - cover( + let mut batch = SpanBatch::new(); + batch.push(vm, vdm, vdm + 4, true, false)?; + batch.push( vm, scissor, scissor.checked_add(4).ok_or(EINVAL)?, @@ -590,7 +664,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu if base & 3 != 0 { return Err(EINVAL); } - cover(vm, base, base.checked_add(4).ok_or(EINVAL)?, true, false)?; + batch.push(vm, base, base.checked_add(4).ok_or(EINVAL)?, true, false)?; } else if cmd.flags & DBIAS_IS_INT != 0 { return Err(EINVAL); } @@ -599,7 +673,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu return Err(EINVAL); } let base = cmd.isp_oclqry_base; - cover(vm, base, base.checked_add(8).ok_or(EINVAL)?, true, true)?; + batch.push(vm, base, base.checked_add(8).ok_or(EINVAL)?, true, true)?; } for program in [&cmd.bg, &cmd.eot, &cmd.partial_bg, &cmd.partial_eot] { if program.usc == 0 { @@ -609,7 +683,7 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu .usc_base .checked_add(u64::from(program.usc & !63)) .ok_or(EINVAL)?; - cover( + batch.push( vm, address, address.checked_add(64).ok_or(EINVAL)?, @@ -617,8 +691,12 @@ fn check_render(context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Resu false, )?; } - check_zls_plane(context, cmd, false)?; - check_zls_plane(context, cmd, true)?; + check_zls_plane(&mut batch, context, cmd, false)?; + check_zls_plane(&mut batch, context, cmd, true)?; + check_attachments(&mut batch, vm, vertex, true)?; + check_attachments(&mut batch, vm, fragment, true)?; + batch.flush(vm)?; + gate::vdm(vm, vdm)?; Ok(()) } @@ -641,9 +719,11 @@ fn check_compute( { return Err(EINVAL); } - cover(vm, base, end, true, false)?; - gate::cdm(vm, context.usc_base, base, end)?; - check_attachments(vm, attachments, true) + let mut batch = SpanBatch::new(); + batch.push(vm, base, end, true, false)?; + check_attachments(&mut batch, vm, attachments, true)?; + batch.flush(vm)?; + gate::cdm(vm, context.usc_base, base, end) } /// Resolves timestamps and exact historical-prefix dependencies of a valid stream @@ -655,43 +735,28 @@ pub(crate) fn prepare<'a>( objects: Pin<&xarray::XArray>>, ) -> Result> { let mut resolved = KVec::new(); + let mut orders = KVec::new(); + let mut preceding = [0u16; 2]; for entry in stream(bytes) { let entry = entry?; - let outputs = match entry.kind { + let (outputs, engine, prior) = match entry.kind { CMD_RENDER => { let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - let cmd = &packet; - crate::timestamp::Destinations::resolve_aligned( + let outputs = crate::timestamp::Destinations::resolve_aligned( objects, - &[cmd.ts_vtx, cmd.ts_frag], - )? + &[packet.ts_vtx, packet.ts_frag], + )?; + (outputs, RENDER, [packet.prior_vdm, packet.prior_cdm]) } CMD_COMPUTE => { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - crate::timestamp::Destinations::resolve_aligned(objects, &[cmd.ts])? + let outputs = + crate::timestamp::Destinations::resolve_aligned(objects, &[packet.ts])?; + (outputs, COMPUTE, [packet.prior_vdm, packet.prior_cdm]) } _ => continue, }; resolved.push(outputs, GFP_KERNEL)?; - } - - // Historical priors and header barriers. - let mut preceding = [0u16; 2]; - let mut orders = KVec::with_capacity(resolved.len(), GFP_KERNEL)?; - for entry in stream(bytes) { - let entry = entry?; - let (engine, prior) = match entry.kind { - CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; - (RENDER, [packet.prior_vdm, packet.prior_cdm]) - } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - (COMPUTE, [packet.prior_vdm, packet.prior_cdm]) - } - _ => continue, - }; orders.push( Order::new(accepted, preceding, entry.barriers, prior, engine)?, GFP_KERNEL, @@ -732,9 +797,7 @@ impl Prepared<'_> { let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; let cmd = &packet; let outputs = resolved.next().ok_or(EINVAL)?; - check_render(context, cmd)?; - check_attachments(context.vm, &vertex, true)?; - check_attachments(context.vm, &fragment, true)?; + check_render(context, cmd, &vertex, &fragment)?; commands.push( Command::Render(KBox::new( RenderCommand { diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 0de0aeb5bfdc0e..d44682d39eabae 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -60,15 +60,13 @@ impl Window { /// unless the record crosses it). Unreadable memory: EFAULT. fn words(&mut self, vm: &mmu::Vm, va: u64, count: usize) -> Result<[u32; 10]> { let n = count.checked_mul(4).filter(|&n| n <= 40).ok_or(EINVAL)?; - cover(vm, va, va.checked_add(n as u64).ok_or(EINVAL)?, true, false)?; - let cached = self.len != 0 - && va >= self.va - && va - .checked_add(n as u64) - .is_some_and(|end| end <= self.va + self.len as u64); + let end = va.checked_add(n as u64).ok_or(EINVAL)?; + let cached = self.len != 0 && va >= self.va && end <= self.va + self.len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); let len = n.max(self.bytes.len().min(in_page)); + let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; + cover(vm, va, cover_end, true, false)?; self.len = 0; vm.read_user(va, &mut self.bytes[..len]) .map_err(|_| EFAULT)?; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 066a757fbc7c57..3798b1a77a4c12 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -212,6 +212,8 @@ struct Standby { epochs: KVec>, /// Accepted, not-yet-published render commands of this VM. reserved: u32, + /// `SUBMIT` callers currently sleeping on `standby_available`. + waiters: u32, } #[pin_data] @@ -243,7 +245,14 @@ impl Cache { 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"), - standby <- new_spinlock_irq!(Standby { epochs, reserved: 0 }, "g16::spare_epochs"), + standby <- new_spinlock_irq!( + Standby { + epochs, + reserved: 0, + waiters: 0, + }, + "g16::spare_epochs" + ), standby_available <- new_condvar!(), closed: AtomicBool::new(false), factory, bind, live, budget }), @@ -289,29 +298,29 @@ impl Cache { 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 - } + let (mut wake, excess) = { + let mut standby = self.standby.lock(); + standby.reserved = standby.reserved.saturating_sub(count); + let wake = standby.waiters != 0; + let keep = if self.closed.load(Ordering::Acquire) { + standby.reserved as usize + } else { + (standby.reserved as usize).max(SPARE_EPOCHS) }; - if excess.is_none() { - break; - } + let excess = if standby.epochs.len() > keep { + standby.epochs.pop() + } else { + None + }; + (wake, excess) + }; + if let Some(excess) = excess { drop(excess); // Subsequent iterations only trim remaining surplus; count was already subtracted. loop { let more = { let mut standby = self.standby.lock(); + wake |= standby.waiters != 0; let keep = if self.closed.load(Ordering::Acquire) { standby.reserved as usize } else { @@ -328,9 +337,10 @@ impl Cache { } drop(more); } - break; } - self.standby_available.notify_all(); + if wake { + self.standby_available.notify_all(); + } } /// The VM's client closed. Lets go of the arenas and surplus standby epochs: accepted @@ -398,29 +408,28 @@ impl Cache { 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; + if compute && ready.compute_ext.is_none() { 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 units > BASE_COMPUTE_UNITS { + // 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; + if 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() { @@ -432,22 +441,22 @@ 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 ready.render_ext.is_none() && EXT_RENDER_SLOTS != 0 { + // 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_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(); + } } } ( @@ -482,10 +491,12 @@ impl Cache { } needed - standby.epochs.len() as u32 } else { - match self + standby.waiters += 1; + let waited = self .standby_available - .wait_interruptible_timeout(&mut standby, remaining) - { + .wait_interruptible_timeout(&mut standby, remaining); + standby.waiters -= 1; + match waited { CondVarTimeoutResult::Woken { jiffies } => { remaining = jiffies; continue; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index c701dd84471fa3..f114ed73ed913c 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -72,8 +72,15 @@ pub mod params { pub fn stream_gate() -> bool { true } } pub mod command { use crate::{mmu, kernel::prelude::*}; + use std::cell::Cell; pub const USC_WINDOW: u64 = 1 << 32; + std::thread_local! { + static COVER_CALLS: Cell = const { Cell::new(0) }; + } + pub fn reset_cover_calls() { COVER_CALLS.with(|c| c.set(0)); } + pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } pub fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + COVER_CALLS.with(|c| c.set(c.get() + 1)); if end <= start || start < 0x4000 || end > (1u64 << 42) - 0x8000 { return Err(EINVAL); } @@ -229,6 +236,19 @@ assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); } #[test] +fn cached_window_reuses_page_coverage_without_rechecking_every_record() { + let mut words = Vec::new(); + for _ in 0..5 { + words.extend(launch(0, USC, 0)); + } + words.push(0x40000000); + // 5 launches * 40B + 4B terminate = 204 bytes, all within one 256-byte window. + g16::command::reset_cover_calls(); + assert!(run(&words)); + // Expect 1 cover() call for the 256B stream window + 1 for the cached USC program page. + assert_eq!(g16::command::cover_calls(), 2); +} +#[test] fn pending_signal_interrupts_walk() { let words = [0x60000160, 0x40000000]; let vm = vm_for(&words); From fee0f3edbb4ddedb04bd8c469dcac1f51ba868f4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 16:47:43 -0500 Subject: [PATCH 0821/1514] 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 ea6f6882eff6a1..6d905e6354688b 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 6936b40afd35ca..444dc69da3dcee 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 f92bea3be3d377..3aa108e85827f2 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 15740f7d5ee9c6..1068c0b0a668f9 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 dfef940d5b25a9..cf2bf38f387993 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 9e9389f4973152..d122bc6fef82dc 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 a655094bfd1397..2c10b565b602b1 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 ba266654343021..cdc9a931b087b8 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 22ff751a2e4159..5c3daf85881cef 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 c9b23923cebf6a..584d4bd161e6b9 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 fe522d3c800c52..1ff81b81410d86 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 d886526f7cdfcd20a31746a173488cac90d66767 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:03:50 -0500 Subject: [PATCH 0822/1514] drm/asahi: g16: allow concurrent compute and render flights with cross-engine barriers Previously, G16 serialized compute and render work strictly: can_queue_behind() rejected any mixed-class overlap, Order::ready() forced cross-engine dependencies to wait for full host retirement, and poll.rs only retired flights[0], leaving the compute and TA/FS hardware pipelines unable to overlap. Enable concurrent same-VM compute and render flights with per-class retirement, per-class hang deadlines, drain fairness, and hardware ring barriers: - Allow healthy same-VM non-InitBM compute and render commands to queue concurrently up to their respective per-class flight caps, while preserving cross-VM, InitBM, and query_access serialization. - Gate alt-class fallback selection on !needs_engine_drain(&job) so class-cap overlap runs concurrently on primed same-VM queues while drain-requiring head jobs (unprimed same-VM InitBM render, cross-VM switch, failed VM, or doomed/recovery/InitBM flight in progress) are never starved; advance queue fairness turns only after publish_prefix() succeeds so transient EAGAIN does not burn a turn. - Emit hardware Hold ring barriers for same-queue cross-engine dependencies (fs2c0 on the compute ring using the FS fw_stamp, and c2ta0 on the TA ring using the compute fw_stamp via a dedicated PassSlot::compute_barrier FwObject), walking all commands of a flight so multi-command compute batches resolve their exact member stamp and defer with EAGAIN if an unretired predecessor is missing. - Retire the oldest compute flight and oldest render flight independently in poll.rs, track progress and administrative/warning deadlines per class (render deadline_ns vs compute_deadline_ns) so an advancing class never masks a hung flight on the other class, and convert Job::full_retired to a 64-bit command bitmask so mixed-class jobs can retire out of class order while preserving completion proofs. - Read only the published engine's WC qstate WRITE register(s) during publication instead of touching both compute and render rings. - Add host selftests covering concurrent compute+render publication, drain fairness and EAGAIN turn preservation, fs2c0/c2ta0 barriers across multi-command flights, out-of-order per-class retirement, and independent per-class progress/timeout enforcement. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 17 +- drivers/gpu/drm/asahi/g16/engine.rs | 273 ++++++++++++---- drivers/gpu/drm/asahi/g16/job.rs | 45 ++- drivers/gpu/drm/asahi/g16/poll.rs | 239 +++++++++----- drivers/gpu/drm/asahi/g16/recovery.rs | 81 +++-- drivers/gpu/drm/asahi/g16/slots.rs | 2 + .../gpu/asahi-m4/test-command-stream.py | 10 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 14 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 25 ++ .../gpu/asahi-m4/test-progress-wrap.py | 139 ++++++-- .../drivers/gpu/asahi-m4/test-publication.py | 296 +++++++++++++++--- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 35 ++- 12 files changed, 919 insertions(+), 257 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 2e666bba9f1bb4..aeac172cecf399 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -111,16 +111,15 @@ 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. + /// A same-engine command cannot jump a hole in its queue's published frontier. + /// Cross-engine dependencies may also follow published predecessors via hardware + /// ring barriers (FS -> CDM and CDM -> TA) while same-VM work pipelines; cross-VM + /// switches, InitBM and timestamp query accesses still drain to completion. pub(crate) fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { - // 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; - frontier[self.engine] = published[self.engine].max(completed[self.engine]); + let frontier = [ + published[RENDER].max(completed[RENDER]), + published[COMPUTE].max(completed[COMPUTE]), + ]; 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 92a9b9b0814dd0..023713080d3d9c 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -438,8 +438,8 @@ pub(crate) struct Engine { 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, + /// Progress tracking of the oldest compute and render flights. + pub(crate) progress_flight: [u64; 2], pub(crate) progress: [Option; 3], /// Boxed with [`Self::prof`]: `Firmware` is built on the probe's stack. pub(crate) stats: KBox, @@ -477,7 +477,7 @@ impl Engine { ta_registered: false, chan_wait: false, short_repoll: false, - progress_flight: 0, + progress_flight: [0; 2], progress: [None; 3], stats: KBox::new(Stats::default(), GFP_KERNEL)?, prof: KBox::new(Prof::default(), GFP_KERNEL)?, @@ -805,14 +805,45 @@ impl Firmware { let Some(index) = self.engine.pick() else { break; }; - let job = self.engine.pending[index].clone(); + let mut 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: only a - // healthy compute command queues behind in-flight compute; everything else - // (and every failure path below) waits for the engine to drain. + // error fence must not race that command's access to user buffers: only + // healthy same-VM non-InitBM commands queue behind active flights; when the + // head queue cannot queue behind (e.g. its class hit its flight cap), still + // allow another ready queue of the other class to run concurrently, unless + // the head job itself requires `flights` to drain to empty first (cross-VM + // switch, unprimed InitBM render, failed VM, or recovery/InitBM in flight). if !self.engine.flights.is_empty() && !self.can_queue_behind(&job) { - self.engine.stats.hold[0] += 1; - break; + if self.needs_engine_drain(&job) { + self.engine.stats.hold[0] += 1; + break; + } + let mut alt: Option = None; + for (i, cand) in self.engine.pending.iter().enumerate() { + if i == index || !self.can_queue_behind(cand) { + continue; + } + let better = match alt { + None => true, + Some(best) => { + let prev = &self.engine.pending[best]; + cand.queue.priority < prev.queue.priority + || (cand.queue.priority == prev.queue.priority + && cand.queue.turn.load(Ordering::Relaxed) + < prev.queue.turn.load(Ordering::Relaxed)) + } + }; + if better { + alt = Some(i); + } + } + match alt { + Some(i) => job = self.engine.pending[i].clone(), + None => { + self.engine.stats.hold[0] += 1; + break; + } + } } if job.vm.status.get() != 0 { self.engine.unpend(&job); @@ -893,10 +924,10 @@ impl Firmware { continue; } } - self.engine.turn += 1; - job.queue.turn.store(self.engine.turn, Ordering::Relaxed); match self.publish_prefix(&job, done, &mut pending_rings) { Ok(()) => { + self.engine.turn += 1; + job.queue.turn.store(self.engine.turn, Ordering::Relaxed); batch_published += 1; self.recovery.publication_wait_deadline = None; if job.progress.sent() == job.progress.count() { @@ -1004,25 +1035,37 @@ impl Firmware { Ok(()) } + /// Whether `job` requires `self.engine.flights` to drain to empty before it can + /// publish (so `alt`-class bypass must not keep refilling the engine ahead of it). + fn needs_engine_drain(&self, job: &Arc) -> bool { + job.vm.status.get() != 0 + || self.engine.flights.iter().any(|f| { + f.doomed || f.recovery_suspect || f.initbm || !Arc::ptr_eq(&f.job.vm, &job.vm) + }) + || (matches!(command(job, job.progress.sent()), Some(Command::Render(_))) + && !self.pools.can_pipeline(&job.vm)) + } + /// 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`), 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 - /// 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. + /// - Compute queues behind healthy same-VM non-InitBM compute and/or render flights (up to + /// [`params::compute_flights`] active computes), each in its own `ComputeSlot` + /// (`its`/`work`), unless `query_access` is set and a same-queue predecessor in its + /// compute or render 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 and/or compute flights (up to + /// [`params::render_flights`] active renders), rotating `PassSlot` (`0..RENDER_SLOTS`) + /// while sharing the active exposed PB/UMA allocator slot (`Pools::can_pipeline`). + /// Hardware barriers on the CDM/TA/FS rings preserve exact same-engine and cross-engine + /// ordering while barrier-free or independent-queue compute and render run concurrently. + /// - Cross-VM switches, 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 job.vm.status.get() != 0 + || e.flights.len() >= super::hw::sizes::FLIGHTS || e.flights.iter().any(|f| { - f.doomed || f.recovery_suspect || !Arc::ptr_eq(&f.job.vm, &job.vm) + f.doomed || f.recovery_suspect || f.initbm || !Arc::ptr_eq(&f.job.vm, &job.vm) }) { return false; @@ -1034,21 +1077,29 @@ impl Firmware { match command(job, sent) { 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) + && job.command_order(sent).is_some_and(|o| { + let waits_class = |class: usize| { + o.wait_through[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && 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_class(super::command::COMPUTE) || waits_class(super::command::RENDER) + }); + let compute_count = e.flights.iter().filter(|f| f.computes != 0).count(); !waits_for_timestamps - && e.flights.len() < params::compute_flights() - && e.flights.iter().all(|f| f.renders == 0) + && compute_count < params::compute_flights() && !self.slots.compute_exhausted() && super::recovery::logic::next_ordinal(e.ordinal).is_some() && job @@ -1057,8 +1108,8 @@ impl Firmware { .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) + let render_count = e.flights.iter().filter(|f| f.renders != 0).count(); + render_count < params::render_flights() && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() @@ -1072,6 +1123,49 @@ impl Firmware { } } + /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` + /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> + /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited + /// prefix has already retired. + fn cross_engine_wait(&self, job: &Arc, index: u32, other: usize) -> Result> { + let Some(last) = job + .command_order(index) + .and_then(|o| o.wait_through[other]) + else { + return Ok(None); + }; + if job.queue.completed[other].load(Ordering::Acquire) >= last { + return Ok(None); + } + for flight in &self.engine.flights { + if !Arc::ptr_eq(&flight.job.queue, &job.queue) { + continue; + } + if other == super::command::COMPUTE && flight.computes != 0 { + for member in 0..flight.count { + if flight + .job + .command_order((flight.first + member) as u32) + .is_some_and(|fo| fo.sequence == last) + { + return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + } + } + } else if other == super::command::RENDER && flight.renders != 0 { + for member in 0..flight.count { + if flight + .job + .command_order((flight.first + member) as u32) + .is_some_and(|fo| fo.sequence == last) + { + return Ok(Some(flight.fs_target)); + } + } + } + } + Err(EAGAIN) + } + /// 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 { @@ -1084,11 +1178,14 @@ impl Firmware { alloc_slot: usize, job: &Job, draw: u64, - pipelined: bool, + render_pipelined: bool, + engine_behind: bool, ) -> Result<(RenderRefs, bool, Arc, u64)> { let generation = job.vm.generation; let arena = job.resources.render()?; - let mut a = arena.pools.prepare_in_flight(alloc_slot, draw, pipelined)?; + let mut a = arena + .pools + .prepare_in_flight(alloc_slot, draw, render_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) => { @@ -1097,7 +1194,7 @@ impl Firmware { (e, true) } None => { - if pipelined { + if engine_behind { return Err(EAGAIN); } let e = job.resources.take_pb()?; @@ -1212,6 +1309,11 @@ impl Firmware { let index = job.progress.sent(); let cmd = command(job, index).ok_or(EINVAL)?; let render = matches!(cmd, Command::Render(_)); + let class_behind = self + .engine + .flights + .iter() + .any(|f| if render { f.renders != 0 } else { f.computes != 0 }); if job.vm.status.get() != 0 { return Err(EIO); } @@ -1230,8 +1332,8 @@ impl Firmware { for &channel in channels { let pipe = self.channels.channel(channel); let producer = self.channels.producer(channel); - let busy = if behind { - // Behind in-flight commands: post after their unconsumed records, with room. + let busy = if class_behind { + // Behind in-flight commands on this class: post after their unconsumed records. pipe.write()? != producer || producer.wrapping_sub(pipe.read()?) % RING_SLOTS >= sizes::AHEAD_RECORDS } else { @@ -1248,18 +1350,27 @@ impl Firmware { return Err(EIO); } self.engine.stats.prep_from_ns = now_ns(); + let (c_head, ta_head, fs_head) = if render { + ( + 0, + self.graph.render.qstate[0].r32(qstate::WRITE)?, + self.graph.render.qstate[1].r32(qstate::WRITE)?, + ) + } else { + (self.graph.compute.qstate.r32(qstate::WRITE)?, 0, 0) + }; let mut prefix = Prefix { n: self.engine.ordinal, draw: self.engine.draw, - c_head: self.graph.compute.qstate.r32(qstate::WRITE)?, - ta_head: self.graph.render.qstate[0].r32(qstate::WRITE)?, - fs_head: self.graph.render.qstate[1].r32(qstate::WRITE)?, + c_head, + ta_head, + fs_head, ..Default::default() }; if prefix.c_head >= 256 || prefix.ta_head >= 256 || prefix.fs_head >= 256 { return Err(super::boot::eproto()); } - if behind { + if class_behind { if render { let ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; let fs_read = self.graph.render.qstate[1].r32(qstate::READ)?; @@ -1273,10 +1384,10 @@ impl Firmware { return Err(EAGAIN); } } else { - // Room for one more compute entry behind the unconsumed ones. + // Room for an optional cross-engine barrier plus compute work entry. 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 + || prefix.c_head.wrapping_sub(read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 { return Err(EAGAIN); } @@ -1307,7 +1418,7 @@ impl Firmware { f.claims.pass[0] = k as u32; f.claims.pass_mask = 1 << k; self.slots.pass_busy |= 1 << k; - self.prefix_render(job, r, geometry, &mut prefix, f, behind)?; + self.prefix_render(job, r, geometry, &mut prefix, f, behind, class_behind)?; } } f.first = index as usize; @@ -1411,7 +1522,7 @@ impl Firmware { event, new_queue: u8::from(fresh), }; - if behind { + if class_behind { self.channels.post_ahead(channel, &record)?; } else { self.channels.post(channel, &record)?; @@ -1448,9 +1559,14 @@ impl Firmware { self.engine.stage_seen = self.events.stage_events; f.behind = behind; self.stat_publish(f); - if !behind { - // A command behind others keeps the oldest's deadline: it starts only after them. - self.renew_deadlines(); + if !class_behind { + // First in-flight command on this class starts about now; commands queued behind + // their own class keep that class's oldest deadline without renewing the other. + if render { + self.renew_render_deadline(); + } else { + self.renew_compute_deadline(); + } } job.progress.set_sent(index + 1); job.command_published(index); @@ -1564,13 +1680,33 @@ impl Firmware { &w[work::compute::BODY_ACTIVE_START..work::compute::BODY_ACTIVE_END], )?; } + let wait_render = + self.cross_engine_wait(job, job.progress.sent(), super::command::RENDER)?; + if let Some(wait_fs) = wait_render { + let bar = encode::barrier( + self.graph.render.fw_stamp[1].va, + wait_fs, + 0x71, + target, + 0, + BarrierType::Hold, + ); + s.barrier.write(0, &bar)?; + } f.uma_submitted = submitted; f.has_timestamps = !cmd.timestamp_outputs.is_empty(); wmb(); + if let Some(wait_fs) = wait_render { + g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + self.engine.stats.fs2c0 += 1; + f.cwait[0] = wait_fs; + } else { + f.cwait[0] = 0; + } g.ring.w64(8 * pf.c_head as usize, s.work.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; f.cstamp[0] = target; - f.cwait[0] = 0; pf.computes = 1; pf.n = n; pf.last_ct = target; @@ -1588,21 +1724,26 @@ impl Firmware { pf: &mut Prefix, f: &mut Flight, behind: bool, + class_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); + let wait_compute = + self.cross_engine_wait(job, job.progress.sent(), super::command::COMPUTE)?; // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.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)?; + let (refs, init_buffer, epoch, binding) = + self.render_refs(alloc_slot, job, draw, class_behind, behind)?; f.pb = Some(epoch); f.pb_slot = alloc_slot as u32; f.pb_binding = binding; f.initbm = init_buffer; + f.has_timestamps = !cmd.timestamp_outputs.is_empty(); let p = job.resources.render_pass(k)?; let pass = p.refs(); geometry.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; @@ -1692,8 +1833,8 @@ impl Firmware { 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 early = class_behind && params::early_tiling() && (frag_only || no_render_barrier); + if class_behind { let (wait_va, wait_stamp, wait_event) = if early { (r.fw_stamp[0].va, self.engine.ta_target, 0x70) } else { @@ -1725,6 +1866,20 @@ impl Firmware { self.engine.stats.early += 1; } } + if let Some(wait_c) = wait_compute { + let cbar = encode::barrier( + self.graph.compute.fw_stamp.va, + wait_c, + 15, + target, + work::barrier::RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.compute_barrier.write(0, &cbar)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + self.engine.stats.c2ta0 += 1; + } // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( r.fw_stamp[0].va, diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 3613d91234f129..e4d09ceaf20f9d 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -29,7 +29,7 @@ //! [`mmu::VmJobGuard`] keeps the VM's mappings and its VM state keeps the VM's TTBAT slot until //! the last `Arc` drops. -use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ c_str, cpu::CpuId, @@ -107,8 +107,10 @@ pub(crate) struct Job { pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. inputs: KVec, - /// Consecutive commands with full owner-retirement proof; an aborted receipt never counts. - full_retired: AtomicU32, + /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted + /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render + /// commands within one job may retire in either hardware completion order. + full_retired: AtomicU64, /// No future publication and every previously published owner fully retired. This proof /// is separate from an error result: an affected full receipt may still fail the job. terminal_retired: AtomicBool, @@ -159,7 +161,7 @@ impl Job { fence, progress, inputs, - full_retired: AtomicU32::new(0), + full_retired: AtomicU64::new(0), terminal_retired: AtomicBool::new(false), // Scheduler free can race the final off-lock completion reference. // Prepare destruction work before acceptance; dropping a completed job @@ -370,17 +372,33 @@ impl Job { Ok(()) } - /// Records a consecutive full owner receipt independently of success/error attribution. + /// Records a unique full owner receipt independently of success/error attribution. /// Only the receipt owner may call this after successful resource-ledger retirement. pub(crate) fn note_full_retirement(&self, first: u32, count: u32) -> Result { let end = first.checked_add(count).ok_or(EOVERFLOW)?; - if count == 0 || end > self.progress.sent() { + if count == 0 || end > self.progress.sent() || end > 64 { return Err(EINVAL); } - self.full_retired - .compare_exchange(first, end, Ordering::AcqRel, Ordering::Acquire) - .map_err(|_| EIO)?; - Ok(()) + let bits = if count == 64 { + u64::MAX + } else { + ((1u64 << count) - 1) << first + }; + let mut current = self.full_retired.load(Ordering::Acquire); + loop { + if current & bits != 0 { + return Err(EIO); + } + match self.full_retired.compare_exchange_weak( + current, + current | bits, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return Ok(()), + Err(observed) => current = observed, + } + } } /// Certifies a terminal job before publishing its error. The caller first removes it @@ -389,9 +407,14 @@ impl Job { /// A never-published job has the same proof with all three counters equal to zero. pub(crate) fn mark_terminal_retired(&self) -> Result { let sent = self.progress.sent(); + let expected = if sent >= 64 { + u64::MAX + } else { + (1u64 << sent) - 1 + }; if self.progress.is_pending() || self.progress.next() != sent - || self.full_retired.load(Ordering::Acquire) != sent + || self.full_retired.load(Ordering::Acquire) != expected { return Err(EIO); } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 76dc54a08472db..5c8666273d65c1 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -513,59 +513,85 @@ impl Firmware { Ok(()) } - /// Terminal completion-event counter for the oldest in-flight command (`fs_events` for a - /// render-only flight, `compute_events` for a compute-only flight). - fn oldest_terminal_events(&self) -> Option { - let f = self.engine.oldest()?; - if f.renders != 0 && f.computes == 0 { - Some(self.events.fs_events) - } else if f.computes != 0 && f.renders == 0 { - Some(self.events.compute_events) - } else { - None - } + /// Terminal completion-event counters for the oldest active flight of each class + /// (`(compute_events, fs_events)`), used to distinguish TA-only (0x70) non-terminal events. + fn oldest_terminal_events(&self) -> Option<(Option, Option)> { + if self.engine.flights.is_empty() + || self + .engine + .flights + .iter() + .any(|f| f.computes != 0 && f.renders != 0) + { + return None; + } + let compute = self + .engine + .flights + .iter() + .any(|f| f.computes != 0) + .then_some(self.events.compute_events); + let render = self + .engine + .flights + .iter() + .any(|f| f.renders != 0) + .then_some(self.events.fs_events); + Some((compute, render)) } - /// Cheap single-stage stamp check for the oldest flight's terminal stage so `submit_locked()` - /// can eagerly retire finished work without scanning all rings when nothing has completed. + /// Cheap single-stage stamp check for the oldest compute and oldest render flights' terminal + /// stages so `submit_locked()` can eagerly retire finished work without scanning all rings + /// when nothing has completed. fn oldest_stamp_reached(&self) -> bool { - let Some(f) = self.engine.oldest() else { + if self.engine.flights.is_empty() { return false; - }; + } rmb(); - let behind = self.engine.flights.len() > 1; - let compute_ok = if f.computes != 0 { - let Ok(obs) = self.graph.compute.fw_stamp.r32(0) else { - return false; - }; - if behind { - stamp_reached(obs, f.target, self.engine.target) - } else { - obs == f.target + let compute_behind = self + .engine + .flights + .iter() + .filter(|f| f.computes != 0) + .count() + > 1; + if let Some(f) = self.engine.flights.iter().find(|f| f.computes != 0) { + if let Ok(obs) = self.graph.compute.fw_stamp.r32(0) { + let reached = if compute_behind { + stamp_reached(obs, f.target, self.engine.target) + } else { + obs == f.target + }; + if reached { + return true; + } } - } else { - true - }; - if !compute_ok { - return false; } - if f.renders != 0 { - let Ok(obs) = self.graph.render.fw_stamp[1].r32(0) else { - return false; - }; - if behind { - stamp_reached(obs, f.fs_target, self.engine.fs_target) - } else { - obs == f.fs_target + let render_behind = self + .engine + .flights + .iter() + .filter(|f| f.renders != 0) + .count() + > 1; + if let Some(f) = self.engine.flights.iter().find(|f| f.renders != 0) { + if let Ok(obs) = self.graph.render.fw_stamp[1].r32(0) { + let reached = if render_behind { + stamp_reached(obs, f.fs_target, self.engine.fs_target) + } else { + obs == f.fs_target + }; + if reached { + return true; + } } - } else { - true } + false } - /// Drains the event/stats 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. + /// Drains the event/stats rings and retires all currently complete oldest compute and render + /// flights independently 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_events_and_stats()?; @@ -575,15 +601,12 @@ impl Firmware { self.check_hangs(done)?; } let mut retired_any = false; - let mut ret = self.retired(); - while let Ok(receipt) = ret { - if !receipt.complete() { - break; - } - let outcome = self.retire_outcome(receipt); - self.retire_oldest(receipt, outcome, done); + let mut ret = self.retired_flight(); + while let Ok(Some((index, receipt))) = ret { + let outcome = self.retire_outcome_at(index, receipt); + self.retire_oldest(index, receipt, outcome, done); retired_any = true; - ret = self.retired(); + ret = self.retired_flight(); } self.recovery.receipt_fault = ret.is_err(); Ok(retired_any) @@ -702,25 +725,60 @@ impl Firmware { /// receipt omits only the writes firmware does not make for an aborted command, /// after the recovery grace period and its queue/pipe/stage passed proof. pub(crate) fn retired(&mut self) -> Result { - match self.retired_snapshot() { + self.retired_at(0) + } + + fn retired_at(&mut self, index: usize) -> Result { + match self.retired_snapshot_at(index) { // A changing packed receipt is not an authenticated firmware failure. Err(error) if error == EAGAIN => Ok(Retirement::Pending), result => result, } } + /// Inspects the oldest compute flight and oldest render flight independently so either + /// class can retire as soon as its hardware receipt settles without waiting on the other. + pub(crate) fn retired_flight(&mut self) -> Result> { + let compute_idx = self.engine.flights.iter().position(|f| f.computes != 0); + let render_idx = self.engine.flights.iter().position(|f| f.renders != 0); + for index in [compute_idx, render_idx].into_iter().flatten() { + let receipt = self.retired_at(index)?; + if receipt.complete() { + return Ok(Some((index, receipt))); + } + } + Ok(None) + } + fn retired_snapshot(&mut self) -> Result { - let Some(f) = self.engine.oldest() else { + self.retired_snapshot_at(0) + } + + fn retired_snapshot_at(&mut self, index: usize) -> Result { + let Some(f) = self.engine.flights.get(index) else { return Ok(Retirement::Pending); }; rmb(); let mut full = true; let mut ticks = [0u64; 4]; - // 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 { + // Later flights of the same engine class queued behind this one: that class's queue, + // pipe and stamp cells already moved on, so its receipt is "passed", in order; the + // newest flight of a class keeps the exact receipt. + let compute_behind = self + .engine + .flights + .iter() + .filter(|f| f.computes != 0) + .count() + > 1; + let render_behind = self + .engine + .flights + .iter() + .filter(|f| f.renders != 0) + .count() + > 1; + if f.computes != 0 && compute_behind { let g = &self.graph.compute; let e = &self.engine; if !stamp_reached(g.fw_stamp.r32(0)?, f.target, e.target) @@ -762,7 +820,7 @@ impl Firmware { && start != 0 && end > start; } - if f.renders != 0 && behind { + if f.renders != 0 && render_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) @@ -851,7 +909,7 @@ impl Firmware { if f.recovery_suspect && now_ns().saturating_sub(f.recovery_started_ns) >= 20_000_000 { // Queues, pipes and every participating stage passed the retained command. // The firmware recovered it without normal completion: fail and quarantine. - if let Some(f) = self.engine.flights.first_mut() { + if let Some(f) = self.engine.flights.get_mut(index) { f.doomed = true; } return Ok(Retirement::Aborted); @@ -885,19 +943,20 @@ impl Firmware { } } - /// Retire the oldest prefix's scheduling ownership. Only a full normal receipt retires - /// its storage; a passed abort quarantines it. Job failure independently drops remaining - /// unpublished commands even when the storage fully retired. + /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt + /// retires its storage; a passed abort quarantines it. Job failure independently drops + /// remaining unpublished commands even when the storage fully retired. pub(crate) fn retire_oldest( &mut self, + index: usize, receipt: Retirement, result: Result, done: &mut Completions, ) { - if self.engine.flights.is_empty() { + if index >= self.engine.flights.len() { return; } - let Ok(mut f) = self.engine.flights.remove(0) else { + let Ok(mut f) = self.engine.flights.remove(index) else { return; }; let timestamp_claims = f.claims; @@ -992,8 +1051,13 @@ impl Firmware { self.engine.stats.idle_from_ns = now_ns(); self.power.utilization.idle(self.engine.stats.idle_from_ns); } - // The next prefix starts executing about now. - self.renew_deadlines(); + // The next prefix on the retired flight's class(es) starts executing about now. + if f.renders != 0 { + self.renew_render_deadline(); + } + if f.computes != 0 { + self.renew_compute_deadline(); + } let job = f.job.clone(); let p = &job.progress; p.next.store(p.next() + f.count as u32, Ordering::Relaxed); @@ -1058,31 +1122,42 @@ impl Firmware { } } - /// Progress of the oldest prefix: a FW stamp of an engine on which it still has unreached - /// work moved since the last poll (later prefixes' work on other engines does not count). - /// Renews the deadline; the first call for a prefix only records its position. + /// Progress of the oldest compute and oldest render flights: a FW stamp of an engine on + /// which its oldest flight still has unreached work moved since the last poll. Renews the + /// deadline; the first call for a flight pair only records its position. /// [`Self::check_hangs`] calls it while no firmware recovery notification is pending. pub(crate) fn progress(&mut self) { - let Some(f) = self.engine.oldest() else { + if self.engine.flights.is_empty() { return; - }; + } let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); // None denotes an inactive/reached stage. A real unreached stamp may be zero // immediately after native wrap and must remain distinguishable from completion. let pending = |observed, own, tail| (!stamp_reached(observed, own, tail)).then_some(observed); let (mut c, mut ta, mut fs) = (None, None, None); - if f.computes != 0 { - c = pending(g.fw_stamp.r32(0).unwrap_or(0), f.target, e.target); - } - if f.renders != 0 { - ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), f.ta_target, e.ta_target); - fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), f.fs_target, e.fs_target); - } - let moved = e.progress_flight == f.published_ns && [c, ta, fs] != e.progress; - let published = f.published_ns; - if moved { - self.renew_deadlines(); + let mut published = [0u64; 2]; + let fc = e.flights.iter().find(|f| f.computes != 0); + if let Some(fc) = fc { + c = pending(g.fw_stamp.r32(0).unwrap_or(0), fc.target, e.target); + published[0] = fc.published_ns; + } + let fr = e.flights.iter().find(|f| f.renders != 0); + if let Some(fr) = fr { + ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), fr.ta_target, e.ta_target); + fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); + published[1] = fr.published_ns; + } + let compute_moved = + fc.is_some() && e.progress_flight[0] == published[0] && c != e.progress[0]; + let render_moved = fr.is_some() + && e.progress_flight[1] == published[1] + && [ta, fs] != [e.progress[1], e.progress[2]]; + if compute_moved { + self.renew_compute_deadline(); + } + if render_moved { + self.renew_render_deadline(); } self.engine.progress_flight = published; self.engine.progress = [c, ta, fs]; diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 15f86bd2b5b996..70eca890d75d15 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -53,8 +53,8 @@ pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Re pub(crate) struct Recovery { pub(crate) deadline_ns: u64, pub(crate) compute_deadline_ns: u64, - /// A long command warning is diagnostic, not evidence that the GPU has stopped. - warning_deadline_ns: u64, + /// Per-class (render, compute) long-command warning deadlines; diagnostic only. + warning_deadline_ns: [u64; 2], pub(crate) long_commands: u64, pub(crate) publication_wait_deadline: Option, /// Last fully retired compute/TA/FS identity, for late recovery snapshots. @@ -81,7 +81,7 @@ impl Recovery { Self { deadline_ns: logic::EXPIRED, compute_deadline_ns: logic::EXPIRED, - warning_deadline_ns: u64::MAX, + warning_deadline_ns: [u64::MAX; 2], long_commands: 0, publication_wait_deadline: None, last_retired: [None; 3], @@ -114,15 +114,24 @@ impl Firmware { &self.pools.dev } + pub(crate) fn renew_render_deadline(&mut self) { + let now = now_ns(); + self.recovery.deadline_ns = logic::renew(now, params::deadline_ms(), 0).0; + self.recovery.warning_deadline_ns[super::command::RENDER] = + now.saturating_add(5_000_000_000); + } + + pub(crate) fn renew_compute_deadline(&mut self) { + let now = now_ns(); + self.recovery.compute_deadline_ns = + logic::renew(now, 0, params::compute_deadline_ms()).1; + self.recovery.warning_deadline_ns[super::command::COMPUTE] = + now.saturating_add(5_000_000_000); + } + pub(crate) fn renew_deadlines(&mut self) { - let (deadline, compute) = logic::renew( - now_ns(), - params::deadline_ms(), - params::compute_deadline_ms(), - ); - self.recovery.deadline_ns = deadline; - self.recovery.compute_deadline_ns = compute; - self.recovery.warning_deadline_ns = now_ns().saturating_add(5_000_000_000); + self.renew_render_deadline(); + self.renew_compute_deadline(); } fn new_recovery(&self) -> bool { @@ -147,11 +156,11 @@ impl Firmware { /// A full hardware receipt still fails an explicitly affected job. Merely /// suspect work can complete normally; the poll owner separately proves an /// abort before retiring it without a full receipt. - pub(crate) fn retire_outcome(&mut self, receipt: Retirement) -> Result { + pub(crate) fn retire_outcome_at(&mut self, index: usize, receipt: Retirement) -> Result { let affected = self .engine .flights - .first() + .get(index) .is_some_and(|flight| flight.doomed); if receipt.job_failed(affected) { Err(EIO) @@ -190,21 +199,41 @@ impl Firmware { if !self.engine.flights.is_empty() { self.progress(); let now = now_ns(); - if logic::expired(now, self.recovery.warning_deadline_ns) { - self.recovery.warning_deadline_ns = u64::MAX; + let has_render = self.engine.flights.iter().any(|flight| flight.renders != 0); + let has_compute = self + .engine + .flights + .iter() + .any(|flight| flight.computes != 0); + if has_render + && logic::expired( + now, + self.recovery.warning_deadline_ns[super::command::RENDER], + ) + { + self.recovery.warning_deadline_ns[super::command::RENDER] = u64::MAX; + self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); + dev_warn!( + self.dev(), + "M4 GPU render command has no completion-stamp progress for 5s; execution may still be active\n" + ); + } + if has_compute + && logic::expired( + now, + self.recovery.warning_deadline_ns[super::command::COMPUTE], + ) + { + self.recovery.warning_deadline_ns[super::command::COMPUTE] = u64::MAX; self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); - dev_warn!(self.dev(), "M4 GPU command has no completion-stamp progress for 5s; execution may still be active\n"); + dev_warn!( + self.dev(), + "M4 GPU compute command has no completion-stamp progress for 5s; execution may still be active\n" + ); } - let compute_only = self - .engine - .oldest() - .is_some_and(|flight| flight.computes != 0 && flight.renders == 0); - let deadline = if compute_only { - self.recovery.compute_deadline_ns - } else { - self.recovery.deadline_ns - }; - if logic::expired(now, deadline) { + if (has_render && logic::expired(now, self.recovery.deadline_ns)) + || (has_compute && logic::expired(now, self.recovery.compute_deadline_ns)) + { dev_err!( self.dev(), "M4 GPU administrative command deadline exceeded without firmware recovery; retaining owners and fail-stop (not proof of quiescence)\n" diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index eab8062e25261b..e74e92b3b50827 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -147,6 +147,7 @@ pub(crate) struct PassSlot { pub(crate) prev_barrier: Arc, #[allow(dead_code)] pub(crate) fs_dep: Arc, + pub(crate) compute_barrier: Arc, } impl PassSlot { @@ -268,6 +269,7 @@ impl PassSlot { own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + compute_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, }) } 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 ebb773c7b72181..bfb6c793d55b3e 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 @@ -366,14 +366,18 @@ assert_eq!(order.wait_through,[Some(5),Some(7)]); assert!(!order.ready([6,6],[6,6])); assert!(order.ready([6,7],[6,7])); - // Same-engine commands may follow published predecessors (ordered on the hardware - // engine rings); every cross-engine dependency still needs completion. + // Same-engine and same-VM cross-engine commands may follow published predecessors + // (ordered on the hardware engine rings and cross-engine ring barriers). 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,1],[0,1])); + assert!(render.ready([0,1],[0,2])); assert!(render.ready([0,2],[0,2])); + let compute_after_render=Order::new([2,0],[0,0],[NONE,NONE],[2,0],COMPUTE).unwrap(); + assert!(!compute_after_render.ready([1,0],[1,0])); + assert!(compute_after_render.ready([1,0],[2,0])); 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])); 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 b2a4cc45ac7d35..b4861355cf8110 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 @@ -43,7 +43,7 @@ def function(text, name): type Result = 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 COMPUTE:usize=1; +const EOVERFLOW:Error=Error(-75); const NONE:u16=u16::MAX; const RENDER:usize=0; 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 } @@ -98,7 +98,7 @@ def function(text, name): mod command { pub(crate) use super::Order; } 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 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:AtomicU64,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,sleeping:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { @@ -126,7 +126,7 @@ def function(text, name): Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)},started:AtomicBool::new(false),accepted:AtomicBool::new(true), fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,orders,queue, - full_retired:AtomicU32::new(0),terminal_retired:AtomicBool::new(false)}) + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false)}) } #[test] fn a_failed_vm_is_rejected_without_an_input_error() { @@ -383,17 +383,21 @@ def function(text, name): assert_eq!(*shared.submitted.lock().unwrap(),vec![2]);assert_eq!(status.get(),0); } #[test] -fn full_receipts_are_consecutive_bounded_and_once() { +fn full_receipts_are_unique_bounded_and_allow_cross_engine_order() { let queued=job(1,Arc::new(Status::new())); assert_eq!(queued.note_full_retirement(0,1),Err(EINVAL)); queued.progress.sent.store(2,Ordering::Release); assert_eq!(queued.note_full_retirement(0,0),Err(EINVAL)); + // Command 1 may retire before command 0 when compute and render run concurrently. + queued.note_full_retirement(1,1).unwrap(); assert_eq!(queued.note_full_retirement(1,1),Err(EIO)); + assert_eq!(queued.mark_terminal_retired(),Err(EIO)); queued.note_full_retirement(0,1).unwrap(); assert_eq!(queued.note_full_retirement(0,1),Err(EIO)); assert_eq!(queued.note_full_retirement(1,2),Err(EINVAL)); assert_eq!(queued.note_full_retirement(u32::MAX,1),Err(EOVERFLOW)); - queued.note_full_retirement(1,1).unwrap(); + queued.progress.next.store(2,Ordering::Release); + queued.mark_terminal_retired().unwrap(); } #[test] fn inline_start_submits_once_and_falls_back_on_pending_input_or_contention() { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 76aed513a624d7..add6cbaf0ace55 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -397,6 +397,31 @@ def item(declaration): assert!(!retry_tail); assert!(fw.engine.short_repoll); } + +#[test] +fn concurrent_compute_completion_behind_pending_render_wakes_submit_retire() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x200, + }); + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.fs_target = 0x200; + fw.engine.target = 0x100; + // Render still running, compute reached its stamp. + fw.graph.render.fw_stamp[1].0.set(0x100); + fw.graph.compute.fw_stamp.0.set(0x100); + assert!(fw.oldest_stamp_reached()); + assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); +} ''' for token, decl in { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index f73ba928dc4914..a5906f690c6a95 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -4,7 +4,7 @@ from common import kernel_root, output_dir, rustc, sha import subprocess,json root=kernel_root();out=output_dir();backend=root/'drivers/gpu/drm/asahi/g16' -source=(backend/'poll.rs').read_text();engine=(backend/'engine.rs').read_text() +source=(backend/'poll.rs').read_text();engine=(backend/'engine.rs').read_text();recovery_src=(backend/'recovery.rs').read_text() def function(text,name): marker=text.index('fn '+name+'(');start=text.rfind('\n',0,marker)+1;at=text.index('{',marker);depth,end=1,at+1 while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1 @@ -15,36 +15,139 @@ def function(text,name): use std::cell::Cell; #[path="__LOGIC__"]mod logic; use logic::stamp_reached; -struct Object(Cell);impl Object{fn r32(&self,_off:usize)->Result{Ok(self.0.get())}} +#[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); +const EIO:Error=Error(5);const ETIMEDOUT:Error=Error(110); +type Result=core::result::Result; +mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} +mod params{ + pub fn recovery()->bool{true} + pub fn deadline_ms()->u32{1000} + pub fn compute_deadline_ms()->u32{5000} +} +thread_local!{static CLOCK:Cell=const{Cell::new(0)};} +fn now_ns()->u64{CLOCK.with(|c|c.get())} +fn set_now_ns(v:u64){CLOCK.with(|c|c.set(v));} +macro_rules! dev_warn{($($tt:tt)*)=>{};} +macro_rules! dev_err{($($tt:tt)*)=>{};} +struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:Compute,render:Render} struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} -struct Engine{flight:Flight,target:u32,ta_target:u32,fs_target:u32,progress_flight:u64,progress:[__TYPE__;3]} -impl Engine{fn oldest(&self)->Option<&Flight>{Some(&self.flight)}} -struct Firmware{graph:Graph,engine:Engine,renewed:u32} -impl Firmware{fn renew_deadlines(&mut self){self.renewed+=1;} __PROGRESS__ } +struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,progress_flight:[u64;2],progress:[__TYPE__;3]} +impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} +struct Recovery{deadline_ns:u64,compute_deadline_ns:u64,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} +struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,fail_stops:Vec} +impl Firmware{ + fn dev(&self){} + fn transport_error(&self)->Option{None} + fn recovery_pending(&self)->Result{Ok(false)} + fn recover(&mut self)->Result{Ok(())} + fn fail_stop(&mut self,error:Error,_done:&mut ()){self.recovery.failed=Some(error);self.fail_stops.push(error);} + fn renew_render_deadline(&mut self){ + let now=now_ns(); + self.recovery.deadline_ns=logic::renew(now,params::deadline_ms(),0).0; + self.recovery.warning_deadline_ns[command::RENDER]=now.saturating_add(5_000_000_000); + self.render_renewed+=1; + } + fn renew_compute_deadline(&mut self){ + let now=now_ns(); + self.recovery.compute_deadline_ns=logic::renew(now,0,params::compute_deadline_ms()).1; + self.recovery.warning_deadline_ns[command::COMPUTE]=now.saturating_add(5_000_000_000); + self.compute_renewed+=1; + } + __PROGRESS__ + __CHECK_HANGS__ +} +type Completions=(); fn firmware(render:bool,target:u32,previous:u32)->Firmware{ - Firmware{graph:Graph{compute:Compute{fw_stamp:Object(Cell::new(previous))},render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flight:Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1},target,ta_target:target,fs_target:target,progress_flight:0,progress:[__ZERO__;3]},renewed:0} + set_now_ns(1_000_000_000); + let mut f=Firmware{graph:Graph{compute:Compute{fw_stamp:Object(Cell::new(previous))},render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target,ta_target:target,fs_target:target,progress_flight:[0;2],progress:[__ZERO__;3]}, + recovery:Recovery{deadline_ns:u64::MAX,compute_deadline_ns:u64::MAX,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, + render_renewed:0,compute_renewed:0,fail_stops:vec![]}; + f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f } #[test]fn pending_native_zero_and_reached_are_distinct_progress_states(){ - let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.renewed,0);f.progress();assert_eq!(f.renewed,0); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.renewed,1,"completion following real wire zero renews deadline before retirement check"); - f.progress();assert_eq!(f.renewed,1,"repeated completed stamp is not new progress"); + let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.compute_renewed,0);f.progress();assert_eq!(f.compute_renewed,0); + f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); + assert_eq!(f.render_renewed,0); + f.progress();assert_eq!(f.compute_renewed,1,"repeated completed stamp is not new progress"); } #[test]fn paired_ta_fs_zero_each_renews_once_without_lending_other_engine_progress(){ let mut f=firmware(true,0x100,0);f.progress(); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.renewed,0); - f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.renewed,1); - f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.renewed,2);f.progress();assert_eq!(f.renewed,2); + f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); + f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.render_renewed,1);assert_eq!(f.compute_renewed,0); + f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.render_renewed,2);assert_eq!(f.compute_renewed,0); + f.progress();assert_eq!(f.render_renewed,2); } #[test]fn before_at_and_after_zero_completions_have_the_same_progress_contract(){ for target in [0x7fffff00u32,0x80000000,0xffffff00,0,0x100]{ - let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.renewed,0); - f.graph.compute.fw_stamp.0.set(target);f.progress();assert_eq!(f.renewed,1); - f.engine.flight.published_ns=2;f.progress();assert_eq!(f.renewed,1,"new flight first sample is not forward progress"); + let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.compute_renewed,0); + f.graph.compute.fw_stamp.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); + f.engine.flights[0].published_ns=2;f.progress();assert_eq!(f.compute_renewed,1,"new flight first sample is not forward progress"); + } +} +#[test]fn concurrent_compute_and_render_renew_deadlines_independently(){ + let mut f=firmware(true,0x200,0x100); + f.engine.flights.push(Flight{computes:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target=0x300; + f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); + f.graph.compute.fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); + f.graph.render.fw_stamp[0].0.set(0x200);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(1,1)); +} +#[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ + let mut f=firmware(true,0x200,0x100); + f.engine.flights.push(Flight{computes:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + // Compute keeps advancing and retiring every 400 ms across 1.2 s while render stays stuck at 0x100. + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 400_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.compute.fw_stamp.0.set(next_target - 0x100); + f.engine.flights[1].target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.target = next_target; + f.renew_compute_deadline(); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "render deadline (1s) not yet expired at step {step}"); + assert_eq!(f.render_renewed, 0, "compute progress/retirement must never renew render deadline"); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck render must fail-stop at 1.2s despite active compute"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } + } +} +#[test]fn stuck_compute_times_out_while_render_keeps_advancing_and_retiring(){ + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{computes:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); + f.engine.ta_target=0x300;f.engine.fs_target=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + // Render keeps advancing and retiring every 2 s across 6 s while compute stays stuck at 0x100. + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 2_000_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.render.fw_stamp[0].0.set(next_target - 0x100); + f.graph.render.fw_stamp[1].0.set(next_target - 0x100); + f.engine.flights[1].ta_target = next_target; + f.engine.flights[1].fs_target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.ta_target = next_target; + f.engine.fs_target = next_target; + f.renew_render_deadline(); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "compute deadline (5s) not yet expired at step {step}"); + assert_eq!(f.compute_renewed, 0, "render progress/retirement must never renew compute deadline"); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck compute must fail-stop at 6s despite active render"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } } } -'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') +'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') unit=out/'progress-wrap.rs';unit.write_text(harness);log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'progress-wrap')],[str(out/'progress-wrap'),'--nocapture']]: result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True);log+=result.stdout;print(result.stdout,end='');(out/'progress-wrap.log').write_text(log) 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 d32170ca87370a..7101edc16a010c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -34,7 +34,7 @@ def item(declaration): #[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 } +struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2] } struct Progress { sent:AtomicU32,count:u32,pending:AtomicBool } impl Progress { fn sent(&self)->u32{self.sent.load(Ordering::Relaxed)} @@ -42,7 +42,7 @@ def item(declaration): fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } 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 } +struct Job { id:u32,vm:Arc,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(())} @@ -52,8 +52,8 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[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![]}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],doomed:false,recovery_suspect:false,initbm:false}}} struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool} impl Engine { __PICK__ @@ -81,10 +81,11 @@ def item(declaration): 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} +struct Pools{exhausted:bool,exhausted_vm:Option,block_pipeline_vm:Option} impl Pools{ fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} + fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -92,6 +93,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -130,11 +132,18 @@ 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, + allow_behind:bool,block_render_behind:bool,block_compute_behind:bool, } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} - fn can_queue_behind(&self,_job:&Arc)->bool{self.allow_behind} + __NEEDS_ENGINE_DRAIN__ + fn can_queue_behind(&self,job:&Arc)->bool{ + if !self.allow_behind{return false;} + if self.needs_engine_drain(job){return false;} + if self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(()))){return false;} + if self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_))){return false;} + true + } fn service_power(&self)->Result{Ok(())} fn drain_rings(&mut self)->Result{Ok(())} fn check_hangs(&mut self,_done:&mut Completions)->Result{Ok(())} @@ -155,11 +164,15 @@ def item(declaration): if stage.result.is_ok(){ assert!(stage.visible); let idx=job.progress.sent.fetch_add(1,Ordering::Relaxed); + let mut fl=Flight::new(job.clone()); match command(job,idx){ - Some(Command::Render(()))=>{*pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8));} + Some(Command::Render(()))=>{ + *pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8)); + fl.initbm=!self.pools.can_pipeline(&job.vm); + } _=>{*pending_rings|=1<<(Channel::Compute as u8);} } - self.engine.flights.push(Flight::new(job.clone())); + self.engine.flights.push(fl); } stage.result } @@ -168,18 +181,22 @@ def item(declaration): __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}, +fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} +fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ + Arc::new(Job{id,vm, + queue:Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}, progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, 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 job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ + job_on_vm(id,mk_vm(id),render,sent,dependency) +} fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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(), + slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false} + retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false} } #[cfg(test)]mod tests{ use super::*; @@ -273,8 +290,9 @@ def item(declaration): 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 vm1=mk_vm(1); let mut f=firmware( - vec![job(1,false,0,Ok(())),job(2,false,0,Ok(())),job(3,false,0,Ok(()))], + vec![job_on_vm(1,vm1.clone(),false,0,Ok(())),job_on_vm(2,vm1.clone(),false,0,Ok(())),job_on_vm(3,vm1,false,0,Ok(()))], vec![(Ok(()),true),(Ok(()),true),(Ok(()),true)], ); f.allow_behind=true; @@ -285,8 +303,9 @@ def item(declaration): assert_eq!(f.engine.stats.grouped,2); } #[test]fn batched_render_publications_coalesce_in_fs_then_ta_order(){ + let vm1=mk_vm(1); let mut f=firmware( - vec![job(1,true,0,Ok(())),job(2,true,0,Ok(()))], + vec![job_on_vm(1,vm1.clone(),true,0,Ok(())),job_on_vm(2,vm1,true,0,Ok(()))], vec![(Ok(()),true),(Ok(()),true)], ); f.allow_behind=true; @@ -297,8 +316,9 @@ def item(declaration): assert_eq!(f.engine.stats.grouped,1); } #[test]fn batched_doorbell_flushes_after_later_deferral_and_fail_stops_on_ring_error(){ + let vm1=mk_vm(1); let mut f=firmware( - vec![job(1,false,0,Ok(())),job(2,false,0,Ok(()))], + vec![job_on_vm(1,vm1.clone(),false,0,Ok(())),job_on_vm(2,vm1,false,0,Ok(()))], vec![(Ok(()),true),(Err(EAGAIN),false)], ); f.allow_behind=true; @@ -314,15 +334,115 @@ def item(declaration): assert_eq!(f.publish(&mut done),Err(EIO)); assert_eq!(f.fail_stops,1); } + #[test]fn alt_class_fallback_prefers_higher_priority_smaller_value(){ + let vm1=mk_vm(1); + let mk_prio=|id:u32,render:bool,priority:u32|Arc::new(Job{ + id,vm:vm1.clone(), + queue:Queue{turn:AtomicU64::new(0),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)]}, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // Head render (prio 2) is blocked behind active render flight; alt-class fallback + // must select prio 2 (MEDIUM) compute ahead of prio 3 (LOW) compute. + let r_head=mk_prio(1,true,2); + let c_low=mk_prio(2,false,3); + let c_med=mk_prio(3,false,2); + let mut f=firmware(vec![r_head.clone(),c_low,c_med],vec![(Ok(()),true),(Ok(()),true)]); + f.engine.flights.push(Flight::new(r_head)); + f.allow_behind=true; + f.block_render_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3,2]); + assert_eq!(f.engine.pending.len(),1); + } + #[test]fn alt_bypass_does_not_starve_same_vm_initbm_render(){ + let vm1=mk_vm(1); + let c_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let r_initbm=job_on_vm(2,vm1.clone(),true,0,Ok(())); + let c_pending=job_on_vm(3,vm1.clone(),false,0,Ok(())); + c_pending.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![r_initbm,c_pending],vec![(Ok(()),true),(Ok(()),true)]); + f.engine.flights.push(Flight::new(c_active)); + f.allow_behind=true; + f.pools.block_pipeline_vm=Some(vm1.slot); + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert_eq!(f.engine.stats.hold[0],1); + assert_eq!(f.engine.pending.len(),2); + f.engine.flights.clear(); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2]); + assert_eq!(f.engine.pending.len(),1); + f.engine.flights.clear(); + f.pools.block_pipeline_vm=None; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2,3]); + } + #[test]fn alt_bypass_does_not_starve_cross_vm(){ + let vm1=mk_vm(1); + let vm2=mk_vm(2); + let vm1_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let vm2_head=job_on_vm(2,vm2,false,0,Ok(())); + let vm1_pending=job_on_vm(3,vm1,false,0,Ok(())); + vm1_pending.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![vm2_head,vm1_pending],vec![(Ok(()),true)]); + f.engine.flights.push(Flight::new(vm1_active)); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert_eq!(f.engine.stats.hold[0],1); + assert_eq!(f.engine.pending.len(),2); + f.engine.flights.clear(); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2]); + } + #[test]fn alt_bypass_still_allows_same_vm_class_cap_overlap(){ + let vm1=mk_vm(1); + let c_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); + let c_head=job_on_vm(2,vm1.clone(),false,0,Ok(())); + let r_pipelined=job_on_vm(3,vm1,true,0,Ok(())); + r_pipelined.queue.turn.store(5,Ordering::Relaxed); + let mut f=firmware(vec![c_head,r_pipelined],vec![(Ok(()),true)]); + f.engine.flights.push(Flight::new(c_active)); + f.allow_behind=true; + f.block_compute_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3]); + assert_eq!(f.engine.pending.len(),1); + } + #[test]fn deferred_eagain_does_not_burn_queue_turn(){ + let j1=job(1,false,0,Ok(())); + let j2=job(2,false,0,Ok(())); + j1.queue.turn.store(1,Ordering::Relaxed); + j2.queue.turn.store(2,Ordering::Relaxed); + let mut f=firmware(vec![j1.clone(),j2.clone()],vec![(Err(EAGAIN),false),(Ok(()),true)]); + f.engine.turn=10; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[1]); + assert_eq!(j1.queue.turn.load(Ordering::Relaxed),1); + assert_eq!(f.engine.turn,10); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[1,1]); + assert_eq!(j1.queue.turn.load(Ordering::Relaxed),11); + assert_eq!(f.engine.turn,11); + } } #[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} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,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)} + fn command_order(&self,index:u32)->Option{ + if self.extra_orders.is_empty(){Some(self.order)}else{self.extra_orders.get(index as usize).copied()} + } } -struct QueueBehindFlight{job:Arc,first:usize,computes:u32,renders:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],fs_target: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{ @@ -344,56 +464,62 @@ def item(declaration): mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{15} } impl QueueBehindHost { __CAN_QUEUE_BEHIND__ + __CROSS_ENGINE_WAIT__ } - #[test]fn timed_compute_queues_behind_same_vm_and_blocks_cross_vm_or_render(){ + #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_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 q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(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, + extra_orders:vec![],dependency:Ok(()),resources:Resources, }); 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,first:0,computes:1,renders:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,first:0,count:1,computes:1,renders:0,target:0x100,cstamp:{let mut a=[0;16];a[0]=0x100;a},fs_target: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}, }; assert!(p.can_queue_behind(&j2)); assert!(!p.can_queue_behind(&j_other_vm)); - assert!(!p.can_queue_behind(&j_render)); + 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; + p.engine.flights[0].computes=0; + assert!(p.can_queue_behind(&j2)); + p.engine.flights[0].initbm=true; assert!(!p.can_queue_behind(&j2)); + p.engine.flights[0].initbm=false; p.engine.flights[0].renders=0; + p.engine.flights[0].computes=1; 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{ + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,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, + order:Order{sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, + extra_orders:vec![],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 timed=mk(1,q1.clone(),true,None,None); + let query_copy=mk(2,q1.clone(),true,None,Some(1)); + let no_query=mk(2,q1.clone(),false,None,Some(1)); + let no_barrier=mk(2,q1.clone(),true,None,None); + let other_queue=mk(2,q2.clone(),true,None,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}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,first:0,count:1,computes:1,renders:0,target:0x100,cstamp:{let mut a=[0;16];a[0]=0x100;a},fs_target: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}, }; @@ -401,40 +527,122 @@ def item(declaration): assert!(p.can_queue_behind(&no_query)); assert!(p.can_queue_behind(&no_barrier)); assert!(p.can_queue_behind(&other_queue)); + // Cross-engine render timestamp predecessor also blocks query_access compute. + let timed_render=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let pr=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,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!(!pr.can_queue_behind(&mk(2,q1.clone(),true,Some(1),None))); + assert!(pr.can_queue_behind(&mk(2,q1.clone(),false,Some(1),None))); + assert!(pr.can_queue_behind(&mk(2,q1.clone(),true,None,None))); } - #[test]fn render_queues_behind_same_vm_and_blocks_initbm_cross_vm_or_compute(){ + #[test]fn render_queues_behind_same_vm_and_coexists_with_compute_while_blocking_initbm(){ 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 q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ 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, + extra_orders:vec![],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,first:0,computes:0,renders:1,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,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}, }; assert!(p.can_queue_behind(&r2)); assert!(!p.can_queue_behind(&r_other_vm)); - assert!(!p.can_queue_behind(&c1)); + assert!(p.can_queue_behind(&c1)); p.engine.flights[0].initbm=true; assert!(!p.can_queue_behind(&r2)); + assert!(!p.can_queue_behind(&c1)); p.engine.flights[0].initbm=false; p.pools.can_pipeline=false; assert!(!p.can_queue_behind(&r2)); + assert!(p.can_queue_behind(&c1)); 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)); + assert!(!p.can_queue_behind(&c1)); + } + #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),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:false})}], + order:Order{sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let r1=mk(1,q1.clone(),true,1,[None,None]); + let c1=mk(2,q1.clone(),false,1,[Some(1),None]); + let c_nobarrier=mk(3,q1.clone(),false,2,[None,None]); + let r2_after_c1=mk(4,q1.clone(),true,2,[Some(1),Some(1)]); + let c_other_q=mk(5,q2.clone(),false,1,[None,None]); + let p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![ + QueueBehindFlight{job:r1,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},fs_target: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}, + }; + // Same-queue FS -> CDM barrier resolves render's fs_target; CDM -> TA resolves compute's target. + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(0x500))); + assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(0x700))); + // No-barrier / independent-queue submits emit no cross-engine barrier. + assert_eq!(p.cross_engine_wait(&c_nobarrier,0,command::RENDER),Ok(None)); + assert_eq!(p.cross_engine_wait(&c_other_q,0,command::RENDER),Ok(None)); + // Already-retired cross-engine prefix emits no barrier. + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(None)); + // Multi-command same-job compute flight resolves non-first member's exact cstamp + // and defers with EAGAIN if an unretired predecessor is missing. + let multi_c=Arc::new(QueueBehindJob{ + id:6,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false});3], + order:Order{sequence:1,wait_through:[None,None]}, + extra_orders:vec![ + Order{sequence:1,wait_through:[None,None]}, + Order{sequence:2,wait_through:[None,None]}, + Order{sequence:3,wait_through:[None,None]}, + ], + dependency:Ok(()),resources:Resources, + }); + let r_wait_c2=mk(7,q1.clone(),true,3,[None,Some(2)]); + let r_wait_c3=mk(8,q1.clone(),true,4,[None,Some(3)]); + let r_wait_missing=mk(9,q1.clone(),true,5,[None,Some(99)]); + let mut cstamp=[0u32;16]; + cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; + let pm=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:3,draw:1,flights:vec![ + QueueBehindFlight{job:multi_c,first:0,count:3,computes:3,renders:0,target:0x300,cstamp,fs_target: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}, + }; + assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); + assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + assert_eq!(pm.cross_engine_wait(&r_wait_missing,0,command::COMPUTE),Err(EAGAIN)); } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); @@ -458,11 +666,13 @@ def item(declaration): '__PUBLISH_PREFIX__': 'fn publish_prefix(', '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', + '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' @@ -475,7 +685,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 23, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 24, '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 85b1af454e929b..435e4ce3d943c5 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 @@ -63,7 +63,10 @@ def function(text, name): // 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_AT__ + __RETIRED_FLIGHT__ __RETIRED_SNAPSHOT__ + __RETIRED_SNAPSHOT_AT__ } fn firmware(render:bool,ordinal:u64)->Firmware{ let target=encode::stamp(ordinal); @@ -178,8 +181,38 @@ def function(text, name): assert_eq!(r.engine.retired_ticks,[100,101,102,103]); } +#[test]fn concurrent_compute_and_render_retire_independently_by_class(){ + // Render at index 0 (pending) + Compute at index 1 (complete): compute retires ahead of render. + let mut f=firmware(true,10); + let c=firmware(false,20).engine.flights.remove(0); + f.engine.flights.push(c); + f.engine.target=encode::stamp(20); + f.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(20))); + f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(20))); + f.graph.compute.notifier.set(notifier_page::COMPUTE_CONTEXT,2); + // Keep render FS stamp unreached so render at index 0 stays pending. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(9))); + assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + // Now finish render: render retires cleanly with exact single-class receipt. + f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(10))); + assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); + // Reverse order: Compute at index 0 (pending) + Render at index 1 (complete). + let mut f2=firmware(false,30); + let r=firmware(true,40).engine.flights.remove(0); + f2.engine.flights.push(r); + f2.engine.ta_target=encode::stamp(40); + f2.engine.fs_target=encode::stamp(40); + for stage in 0..2 { f2.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(40))); } + f2.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(40))); + f2.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(40))); + f2.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(29))); + assert_eq!(f2.retired_flight(),Ok(Some((1,Retirement::Full)))); +} + '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot')]: +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: harness=harness.replace(token,function((backend/path).read_text(),name)) unit=out/'stamp-wrap.rs';unit.write_text(harness) log='' From 4f44fd665d2ffcb6ea5bded3a4dd80ad18557296 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:11:54 -0500 Subject: [PATCH 0823/1514] 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 1068c0b0a668f9..858efa71b4f7ee 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 2c10b565b602b1..784c2fa3915eb1 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 b511188b206f3fd55e6b0670a5a84ef8e8d1784a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:05:15 -0500 Subject: [PATCH 0824/1514] drm/asahi: g16: add CLPC idle-hold hysteresis and fast-ramp DVFS governor On depth-1 submission loops, the engine briefly drains between consecutive jobs, causing Power::report_work(false) to toggle apple_clpc_gpu_set_active() on every job boundary (triggering mod_delayed_work(..., 0) flushes in drivers/soc/apple/clpc.c even though CLPC itself already holds rails for APPLE_CLPC_HOLD_MS = 32 ms on a 4 ms sampling cadence) and forcing the utilization governor to wait a full 20 ms window before stepping up from FLOOR. Add short 2 ms CLPC idle-hold hysteresis and an asymmetric 5 ms fast-ramp upward path to the G16 power governor: - Hold the CLPC active hint for 2 ms (CLPC_IDLE_HOLD_NS, half of clpc.c's APPLE_CLPC_SAMPLE_MS = 4 ms) across brief sub-ms depth-1 inter-job gaps via policy::ClpcHold, releasing it from service_power() once expired and re-arming run_poll() while held idle. This suppresses redundant mod_delayed_work flushes without holding across 60 Hz (16.67 ms) or 120 Hz (8.33 ms) frames. - Release CLPC immediately via Power::release_clpc_now() on fail-stop (fail_flights) and system sleep commit (sleep_down). - Add a 5 ms upward-only ramp window (RAMP_WINDOW_NS = SAMPLE_NS, aligned with the existing PMP sampling cadence) and ramp_demand() matching demand()'s upward thresholds (>= 70% -> top, >= 40% -> +1) so sustained bursts reach top within 5 ms while light 60 Hz desktop frames stay near FLOOR and 20 ms slow decay is preserved. Clamp stored Governor::demand to the active thermal/user limit on the fast-ramp path so cooling relaxation steps cleanly instead of jumping. - Add unit tests in g16/power/policy.rs and wiring checks in test-thermal-policy.py covering fast ramp, 60 Hz non-pumping, decay preservation, clamped cooling ceilings, and CLPC idle-hold expiry/reset. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/poll.rs | 21 +- drivers/gpu/drm/asahi/g16/power.rs | 36 ++- drivers/gpu/drm/asahi/g16/power/policy.rs | 207 +++++++++++++++++- drivers/gpu/drm/asahi/g16/recovery.rs | 2 +- drivers/gpu/drm/asahi/g16/sleep.rs | 1 + .../drivers/gpu/asahi-m4/test-poll-retire.py | 15 ++ .../gpu/asahi-m4/test-thermal-policy.py | 4 + 7 files changed, 276 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 5c8666273d65c1..520435930e9702 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -123,7 +123,20 @@ impl Shared { && firmware.power.utilization.decaying() => { self.mod_poll(kernel::time::msecs_to_jiffies( - (super::power::policy::WINDOW_NS / 1_000_000) as u32, + (if firmware.power.clpc_holding() { + super::power::policy::CLPC_IDLE_HOLD_NS + } else { + super::power::policy::WINDOW_NS + } / 1_000_000) as u32, + )); + self.cancel_resnap(); + } + Ok(false) + if firmware.recovery.failed().is_none() + && firmware.power.clpc_holding() => + { + self.mod_poll(kernel::time::msecs_to_jiffies( + (super::power::policy::CLPC_IDLE_HOLD_NS / 1_000_000) as u32, )); self.cancel_resnap(); } @@ -225,6 +238,12 @@ impl Shared { firmware.publish_checked(done) }; } + if pub_res.is_ok() + && !firmware.engine.flights.is_empty() + && firmware.power.needs_ramp(now) + { + pub_res = firmware.service_power(); + } if let Err(error) = pub_res { firmware.fail_stop(error, done); self.fail_stop(error); diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index 1de8da0bdcc4c9..0d227673eb7976 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -155,8 +155,8 @@ impl Drop for Demand { /// provider sample the shared cooling policy keeps the ceiling at S1. pub(crate) struct Power { clpc: Demand, - /// The work-in-flight state last reported to `clpc`. - reported: Option, + /// Work-in-flight state and 2 ms idle-hold hysteresis reported to `clpc`. + clpc_hold: policy::ClpcHold, cooling: Cooling, sample: Sample, last_sample_ns: Option, @@ -183,7 +183,7 @@ impl Power { Ok(Self { // First: a CLPC that has not probed yet defers before the PMP vote. clpc: Demand::new(dev)?, - reported: None, + clpc_hold: policy::ClpcHold::new(), cooling: Cooling::new(dev)?, sample: Sample { temperature_mc: 0, @@ -220,14 +220,33 @@ impl Power { } /// Reports a change of work in flight to the CLPC: the memory and fabric - /// floor follows it, not the GFX power state. + /// floor follows it, held for [`policy::CLPC_IDLE_HOLD_NS`] after drain. pub(crate) fn report_work(&mut self, in_flight: bool) { - if self.reported != Some(in_flight) { - self.clpc.set_active(in_flight); - self.reported = Some(in_flight); + if let Some(active) = self.clpc_hold.report(in_flight, now_ns()) { + self.clpc.set_active(active); } } + /// Immediately drops the CLPC memory and fabric floor (fail-stop or sleep). + pub(crate) fn release_clpc_now(&mut self) { + if self.clpc_hold.release_now() { + self.clpc.set_active(false); + } + } + + /// Whether the CLPC floor is held across an idle gap awaiting expiry. + pub(crate) fn clpc_holding(&self) -> bool { + self.clpc_hold.holding() + } + + /// Whether an active burst below the current ceiling can ramp early. + pub(crate) fn needs_ramp(&self, now: u64) -> bool { + let level = self.governor.max(self.budget).max(self.sample.backstop); + let ceiling = policy::cooling_ceiling(self.top, level); + let limit = policy::limit(self.configured, ceiling, self.user); + self.utilization.ramp_due(now, limit) + } + fn ceiling(&mut self, now: u64, idle: bool) -> (u32, bool) { if policy::read_due(self.last_sample_ns, now) { self.last_sample_ns = Some(now); @@ -270,6 +289,9 @@ impl Firmware { } let now = now_ns(); let idle = self.engine.flights.is_empty(); + if idle && self.power.clpc_hold.expire(now) { + self.power.clpc.set_active(false); + } let (limit, decision) = self.power.ceiling(now, idle); let target = self .power diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index d1d34b6245f522..fefc677481b512 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -13,8 +13,18 @@ pub(crate) const PSTATE_MAX: u32 = 10; 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. +/// Utilization window of the governor (slow decay cadence). pub(crate) const WINDOW_NS: u64 = 20_000_000; +/// Fast upward ramp window aligned with the PMP sampling cadence ([`SAMPLE_NS`], 5 ms = 1/4 +/// of [`WINDOW_NS`]) so active bursts step up before the full window closes without +/// overshooting on light periodic desktop frames. +pub(crate) const RAMP_WINDOW_NS: u64 = SAMPLE_NS; +/// Short idle hold before dropping the CLPC active hint between consecutive jobs. +/// `drivers/soc/apple/clpc.c` already holds DCS/fabric rails for `APPLE_CLPC_HOLD_MS` (32 ms) +/// on a `APPLE_CLPC_SAMPLE_MS` (4 ms) cadence; a 2 ms hold (half of `APPLE_CLPC_SAMPLE_MS`) +/// bridges sub-ms depth-1 inter-job gaps and avoids redundant `mod_delayed_work(..., 0)` +/// flushes without holding across 60 Hz (16.67 ms) or 120 Hz (8.33 ms) frame periods. +pub(crate) const CLPC_IDLE_HOLD_NS: u64 = 2_000_000; /// Lowest governed state. On the J713 S1-S3 draw under 0.1 W for a desktop /// load and S4 several times that; S3 runs at 2.4 times the clock of S1. pub(crate) const FLOOR: u32 = 3; @@ -88,6 +98,91 @@ pub(crate) fn demand(current: u32, util: u32, average: u32, top: u32) -> u32 { next.clamp(FLOOR, top) } +/// Fast upward-only demand step for partial burst windows ([`RAMP_WINDOW_NS`]): +/// matches [`demand`]'s upward thresholds (`>= 70%` -> `top`, `>= 40%` -> `+1`) and +/// never decays, so light periodic frames cannot pump to `top` while sustained bursts +/// still reach `top` within one 5 ms sample. +pub(crate) fn ramp_demand(current: u32, util: u32, top: u32) -> u32 { + let top = top.clamp(FLOOR, PSTATE_MAX); + let next = if util >= 70 { + top + } else if util >= 40 { + current.saturating_add(1) + } else { + current + }; + next.max(current).clamp(FLOOR, top) +} + +/// CLPC active-floor hysteresis: keeps the memory and fabric floor raised for +/// [`CLPC_IDLE_HOLD_NS`] after flights drain so short `d=1` inter-job gaps do +/// not drop and re-raise CLPC on every submission. +pub(crate) struct ClpcHold { + reported: Option, + idle_since: Option, +} + +impl ClpcHold { + pub(crate) const fn new() -> Self { + Self { + reported: None, + idle_since: None, + } + } + + /// Updates work-in-flight state. Returns `Some(active)` only when the + /// CLPC provider must transition immediately. + pub(crate) fn report(&mut self, in_flight: bool, now: u64) -> Option { + if in_flight { + self.idle_since = None; + if self.reported != Some(true) { + self.reported = Some(true); + return Some(true); + } + return None; + } + if self.reported == Some(true) { + self.idle_since.get_or_insert(now); + None + } else if self.reported.is_none() { + self.reported = Some(false); + Some(false) + } else { + None + } + } + + /// Releases a held CLPC floor once [`CLPC_IDLE_HOLD_NS`] has elapsed idle. + pub(crate) fn expire(&mut self, now: u64) -> bool { + if self.reported == Some(true) + && self + .idle_since + .is_some_and(|since| now.wrapping_sub(since) >= CLPC_IDLE_HOLD_NS) + { + self.idle_since = None; + self.reported = Some(false); + return true; + } + false + } + + /// Immediately drops the CLPC floor (fail-stop or system sleep). + pub(crate) fn release_now(&mut self) -> bool { + self.idle_since = None; + if self.reported != Some(false) { + self.reported = Some(false); + true + } else { + false + } + } + + /// Whether the CLPC floor is currently being held across an idle gap. + pub(crate) fn holding(&self) -> bool { + self.reported == Some(true) && self.idle_since.is_some() + } +} + /// Busy-time accounting over the governor's windows. The engine reports each /// publication and drain; each power service closes the window once it is due. pub(crate) struct Governor { @@ -131,6 +226,22 @@ impl Governor { self.busy_since.is_none() && self.demand > FLOOR } + /// Whether a busy engine below its ceiling has enough partial-window + /// utilization to step up before the full [`WINDOW_NS`] window closes. + pub(crate) fn ramp_due(&self, now: u64, limit: u32) -> bool { + let cap = self.top.min(limit); + if self.demand >= cap || self.busy_since.is_none() { + return false; + } + let window = now.wrapping_sub(self.window_ns); + if window < RAMP_WINDOW_NS { + return false; + } + let active = self.busy_since.map_or(0, |s| now.saturating_sub(s)); + let util = utilization(self.busy_ns.saturating_add(active), window); + ramp_demand(self.demand, util, self.top).min(limit) > self.demand + } + /// Closes the window once it is due and returns the state to publish /// under the ceiling `limit`; `busy` is whether flights are outstanding. pub(crate) fn govern(&mut self, now: u64, limit: u32, busy: bool) -> u32 { @@ -149,6 +260,13 @@ impl Governor { self.demand = demand(self.demand.min(limit), util, self.average, self.top); self.window_ns = now; self.busy_ns = 0; + } else if busy && window >= RAMP_WINDOW_NS && self.demand < self.top.min(limit) { + let active = self.busy_since.map_or(0, |since| now.saturating_sub(since)); + let util = utilization(self.busy_ns.saturating_add(active), window); + let next = ramp_demand(self.demand.min(limit), util, self.top).min(limit); + if next > self.demand { + self.demand = next; + } } self.demand.min(limit) } @@ -387,4 +505,91 @@ mod tests { assert_eq!(cooling_ceiling(10, u32::MAX), 1); assert_eq!(limit(10, cooling_ceiling(10, 0), 10), 10); } + + #[test] + fn fast_ramp_raises_active_bursts_while_preserving_decay_and_cooling_ceiling() { + let mut g = started(); + g.top = PSTATE_MAX; + // Simulate d=1 back-to-back burst (80% busy) from FLOOR: reaches S10 at 5 ms. + let mut t = T; + for _ in 0..20 { + g.busy(t); + g.idle(t + 200_000); + t += 250_000; + } + assert_eq!(t, T + RAMP_WINDOW_NS); + g.busy(t); + assert!(g.ramp_due(t, PSTATE_MAX)); + assert_eq!(g.govern(t, PSTATE_MAX, true), PSTATE_MAX); + assert!(!g.ramp_due(t, PSTATE_MAX)); + + // Moderate 50% active load steps +1 (aligned with demand()), never jumps to top + // and never decays before the full 20 ms window. + let mut g = started(); + g.top = PSTATE_MAX; + g.busy(T); + g.idle(T + 2_500_000); + g.busy(T + RAMP_WINDOW_NS); + assert!(g.ramp_due(T + RAMP_WINDOW_NS, PSTATE_MAX)); + assert_eq!(g.govern(T + RAMP_WINDOW_NS, PSTATE_MAX, true), FLOOR + 1); + g.idle(T + RAMP_WINDOW_NS); + assert_eq!(g.govern(T + WINDOW_NS - 1, PSTATE_MAX, false), FLOOR + 1); + + // Light 60 Hz compositor frames (2.5 ms busy every 16.67 ms -> 15% over 20 ms) + // never pump to top and settle back at FLOOR. + let mut g = started(); + g.top = PSTATE_MAX; + let mut now = T; + for _ in 0..10 { + g.busy(now); + assert!(g.govern(now + 2_500_000, PSTATE_MAX, true) <= FLOOR + 1); + g.idle(now + 2_500_000); + now += 16_666_667; + let state = g.govern(now, PSTATE_MAX, false); + assert!(state <= FLOOR + 1); + } + assert_eq!(g.demand, FLOOR); + + // Thermal cooling ceiling clamps stored demand too: relaxing by one level steps + // cleanly to cap + 1 rather than jumping straight to top. + let mut g = started(); + g.top = PSTATE_MAX; + g.busy(T); + let cap = cooling_ceiling(PSTATE_MAX, 5); + assert_eq!(g.govern(T + RAMP_WINDOW_NS, cap, true), cap); + assert_eq!(g.demand, cap); + assert!(!g.ramp_due(T + RAMP_WINDOW_NS, cap)); + // Even if the ceiling opens to TOP right after the capped ramp, stored demand + // stays at `cap` until new utilization above `cap` is observed. + g.idle(T + RAMP_WINDOW_NS + 1); + assert_eq!(g.govern(T + RAMP_WINDOW_NS + 2, PSTATE_MAX, false), cap); + assert_eq!(g.demand, cap); + } + + #[test] + fn clpc_hold_keeps_floor_across_short_gaps_and_releases_on_expiry_or_reset() { + let mut hold = ClpcHold::new(); + assert!(!hold.holding()); + assert_eq!(hold.report(true, T), Some(true)); + assert!(!hold.holding()); + // Short idle gap (< 2 ms): CLPC stays active without toggling. + assert_eq!(hold.report(false, T + 200_000), None); + assert!(hold.holding()); + assert!(!hold.expire(T + 200_000 + CLPC_IDLE_HOLD_NS - 1)); + assert_eq!(hold.report(true, T + 500_000), None); + assert!(!hold.holding()); + // Full 2 ms idle expires and releases the CLPC floor (well below 60/120 Hz frames). + assert_eq!(hold.report(false, T + 1_000_000), None); + assert!(hold.holding()); + assert!(hold.expire(T + 1_000_000 + CLPC_IDLE_HOLD_NS)); + assert!(!hold.holding()); + assert!(!hold.expire(T + 1_000_000 + 2 * CLPC_IDLE_HOLD_NS)); + // Fail-stop / sleep drops CLPC immediately regardless of hold timer. + assert_eq!(hold.report(true, T + 30_000_000), Some(true)); + assert_eq!(hold.report(false, T + 30_100_000), None); + assert!(hold.holding()); + assert!(hold.release_now()); + assert!(!hold.holding()); + assert!(!hold.release_now()); + } } diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 70eca890d75d15..cf53ae99bdc81d 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -345,7 +345,7 @@ impl Firmware { pub(crate) fn fail_flights(&mut self, error: Error, done: &mut Completions) { let flights = core::mem::take(&mut self.engine.flights); // A failed device never publishes again: release the memory floor now. - self.power.report_work(false); + self.power.release_clpc_now(); for flight in flights.iter() { for job in Iterator::chain(core::iter::once(&flight.job), flight.group.iter()) { push_completion(done, job, Err(error)); diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index bb4069ec02171d..123060b17c8985 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -198,6 +198,7 @@ impl Shared { .and_then(|quiet| if quiet { Ok(()) } else { Err(EBUSY) }) .and_then(|_| { if self.leave_for_commit(firmware) { + firmware.power.release_clpc_now(); Ok(()) } else { Err(EBUSY) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index add6cbaf0ace55..b8466380197088 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -177,6 +177,16 @@ def item(declaration): __SUBMIT_LOCKED__ } +#[derive(Default)] +struct Power { + ramp: bool, +} +impl Power { + fn needs_ramp(&self, _now: u64) -> bool { + self.ramp + } +} + struct Firmware { session: Session, objects: Objects, @@ -184,6 +194,7 @@ def item(declaration): engine: Engine, events: Events, recovery: Recovery, + power: Power, last_housekeeping_ns: u64, // Test script knobs for retire_once / publish / housekeeping observation. retire_on_call: bool, @@ -194,6 +205,7 @@ def item(declaration): publish_full_calls: u32, publish_checked_calls: u32, housekeeping_calls: u32, + power_calls: u32, } impl Firmware { @@ -223,6 +235,7 @@ def item(declaration): }, events: Events::default(), recovery: Recovery::default(), + power: Power::default(), last_housekeeping_ns: 0, retire_on_call: false, drain_stage_delta: 0, @@ -232,6 +245,7 @@ def item(declaration): publish_full_calls: 0, publish_checked_calls: 0, housekeeping_calls: 0, + power_calls: 0, } } @@ -246,6 +260,7 @@ def item(declaration): Ok(!self.recovery.pending) } fn service_power(&mut self) -> Result { + self.power_calls += 1; Ok(()) } fn drain_rings(&mut self) -> Result { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py index 2df317430ea52f..70bdb24c9e6f81 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py @@ -202,6 +202,10 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, ('poll.rs', 'Ok(false)\n if firmware.recovery.failed().is_none()\n' ' && firmware.power.utilization.decaying() =>\n' ' {\n self.mod_poll('), + ('poll.rs', '&& firmware.power.clpc_holding() =>'), + ('power.rs', 'if idle && self.power.clpc_hold.expire(now) {'), + ('recovery.rs', 'self.power.release_clpc_now();'), + ('sleep.rs', 'firmware.power.release_clpc_now();'), ]: assert (G16/path).read_text().count(call) == 1, (path, call) print('Governor connected at publication, drain, power service and idle re-arm') From 29b2312ba4928497df88e04e8d72ad157200584a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:14:21 -0500 Subject: [PATCH 0825/1514] 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 6d905e6354688b..d798c399f2075e 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 444dc69da3dcee..62c403d9f9a8c1 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 d122bc6fef82dc..1b8bf9b6edb4e1 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 5c3daf85881cef..ebb773c7b72181 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 584d4bd161e6b9..365e670819a6c0 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 ad6f00d3b6fdedd5eeb8d4833317fab980bf9860 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 01:09:14 -0500 Subject: [PATCH 0826/1514] drm/asahi: g16: pre-scrub displaced render pass slots off-lock Every render pass claim previously ran PassSlot::scrub() synchronously while holding the device mutex (Shared::state), stalling concurrent submissions and retirement behind WC tilemap/heap/preemption zeroing. Move clean same-VM pass slot scrubbing outside Shared::state with a race-free synchronous fallback: - Record clean render retirements in Slots::note_render_retired() and stage remaining idle displaced, cleanly retired render pass slots (never Published or undisplaced Retired slots) right before dropping Shared::state via stage_and_take_scrubs(), only when the engine is neither failed nor frozen. Staging after publication avoids self-blocking immediate slot reuse within the same lock hold and skips staging on pure compute workloads. - Run staged scrubs in run_poll(), submit(), and try_submit_inline() after dropping Shared::state and after signalling retired completion fences via job::complete_all(). - Coordinate slot selection (pass_available, pick_pass, pick_pass_in) and off-lock scrub completion via SeqCst scrubbing/waiter atomics so in-flight scrubbing slots are skipped, pre-cleaned slots are preferred, and blocked waiters trigger an immediate poll_now(). - Skip synchronous WC fills in claim_pass_in()/claim_pass_for() when a same-VM slot was pre-cleaned, while falling back synchronously on first use, cross-VM switch, recovery invalidation, error/cancel, or any failed/dropped off-lock scrub. - Wait for active off-lock scrubs to drain in sleep_quiet() before entering system sleep. - Add host selftests in test-resources.py covering displaced-only staging, post-publish staging without blocking immediate reuse, off-lock scrub + zero-fill claim, waiter wakeup, dropped batch cleanup, and synchronous fallback on error/recovery/cross-VM. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/poll.rs | 34 +- drivers/gpu/drm/asahi/g16/resources.rs | 13 + drivers/gpu/drm/asahi/g16/sleep.rs | 1 + drivers/gpu/drm/asahi/g16/slots.rs | 423 +++++++++++++++--- .../drivers/gpu/asahi-m4/test-resources.py | 154 ++++++- 5 files changed, 555 insertions(+), 70 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 520435930e9702..928c2ba879db06 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -93,6 +93,7 @@ impl Shared { break; } let mut done = Completions::new(); + let mut scrubs = super::slots::ScrubBatch::new(); let mut retry_tail = false; if let Some(firmware) = self.state.lock().as_deref_mut() { if self.sleeping.load(Ordering::Acquire) { @@ -147,8 +148,13 @@ impl Shared { self.fail_stop(error); } } + let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); } job::complete_all(done); + if scrubs.run() { + self.poll_now(); + } if !retry_tail { break; } @@ -261,12 +267,17 @@ impl Shared { pub(crate) fn submit(self: &Arc, job: Arc) -> Result { let signalling = kernel::dma_fence::SignallingGuard::new(); let mut done = Completions::new(); - let accepted = { + let (accepted, scrubs) = { let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; - self.submit_locked(firmware, job, &mut done) + let res = self.submit_locked(firmware, job, &mut done); + let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + (res, firmware.slots.stage_and_take_scrubs(allow_stage)) }; job::complete_all(done); + if scrubs.run() { + self.poll_now(); + } drop(signalling); self.notify_wedged(); accepted @@ -277,17 +288,27 @@ impl Shared { pub(crate) fn try_submit_inline(self: &Arc, job: Arc) -> Option { let signalling = kernel::dma_fence::SignallingGuard::new(); let mut done = Completions::new(); + let mut scrubs = super::slots::ScrubBatch::new(); let accepted = { let mut state = self.state.try_lock()?; if self.sleeping.load(Ordering::Acquire) { return None; } match state.as_deref_mut() { - Some(firmware) => self.submit_locked(firmware, job, &mut done), + Some(firmware) => { + let res = self.submit_locked(firmware, job, &mut done); + let allow_stage = + firmware.recovery.failed().is_none() && !firmware.engine.frozen; + scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); + res + } None => Err(ENODEV), } }; job::complete_all(done); + if scrubs.run() { + self.poll_now(); + } drop(signalling); self.notify_wedged(); Some(accepted) @@ -1064,6 +1085,9 @@ impl Firmware { return; } } + if receipt.owner_retired() && f.renders != 0 { + self.slots.note_render_retired(); + } } if self.engine.flights.is_empty() { // Drained: a gap until the next publication. @@ -1526,7 +1550,9 @@ impl Firmware { writeln!( f, "pass_scrub: passes {} tpc_clear_bytes {} tilemap_clear_bytes {}", - slots.pass_scrubs, slots.tpc_clear_bytes, slots.tilemap_clear_bytes + self.slots.pass_scrubs_total(), + slots.tpc_clear_bytes, + self.slots.tilemap_clear_bytes_total() )?; writeln!(f, "type0: fs2c {} c2ta {}", s.fs2c0, s.c2ta0)?; write!(f, "horizon:")?; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 3798b1a77a4c12..b3fa26dee9f79a 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -191,6 +191,19 @@ pub(crate) enum PassOwnerArena { Ext(Arc), } +impl PassOwnerArena { + /// Returns the pass slot and its tilemap dirty high-water mark for global slot `k`. + pub(crate) fn pass_and_tilemap_dirty(&self, k: usize) -> Option<(&PassSlot, &AtomicU64)> { + match self { + Self::Base(arena) => Some((arena.passes.get(k)?, arena.tilemap_dirty.get(k)?)), + Self::Ext(arena) => { + let idx = k.checked_sub(BASE_RENDER_SLOTS)?; + Some((arena.passes.get(idx)?, arena.tilemap_dirty.get(idx)?)) + } + } + } +} + #[derive(Default)] struct Ready { compute: Option>, diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 123060b17c8985..ae23cc8e0dc56c 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -54,6 +54,7 @@ impl Firmware { Ok(self.engine.flights.is_empty() && self.engine.pending.is_empty() && !self.engine.frozen + && !self.slots.scrubbing_active() && self.recovery_idle()?) } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index e74e92b3b50827..6e3c5006331224 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -8,7 +8,7 @@ //! Private backing and old VM leases survive until a distinct replacement fully retires. //! Aborted storage remains mapped and quarantined. Pool cursors are never scrubbed. -use core::sync::atomic::Ordering; +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; @@ -282,6 +282,19 @@ impl PassSlot { /// 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`. + /// Clean same-VM reset of the active per-pass WC spans (used both synchronously on fallback + /// and off-lock after displacement). + pub(crate) fn scrub_clean(&self, pre_records: u32, tilemap_dirty: u64) -> Result { + let r = pre_records as usize; + self.its.fill(0, 0, 32)?; + self.tilemap.fill(0, 0, tilemap_dirty as usize)?; + 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)?; + Ok(()) + } + fn scrub( &self, pre_records: u32, @@ -290,16 +303,9 @@ impl PassSlot { full: bool, stats: &mut SlotStats, ) -> Result { - let r = pre_records as usize; - if !full { - self.its.fill(0, 0, 32)?; - self.tilemap.fill(0, 0, tilemap_dirty as usize)?; + self.scrub_clean(pre_records, tilemap_dirty)?; 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(()); } @@ -436,6 +442,133 @@ pub(crate) struct ComputeOwners { /// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). const PASS_MASK: u32 = (1u32 << sizes::RENDER_SLOTS) - 1; +/// Shared atomic coordination between `Shared::state` slot selection/claims and off-lock +/// pre-scrubbing of displaced render pass slots. +struct ScrubState { + /// Pass slots currently being scrubbed outside `Shared::state`; never picked or claimed. + scrubbing: AtomicU32, + /// Displaced pass slots whose clean same-VM spans were zeroed off-lock. + clean_mask: AtomicU32, + /// Set if slot selection found eligible slots blocked only by an in-flight off-lock scrub. + waiter: AtomicBool, + /// Off-lock scrub counters folded into [`SlotStats`] on subsequent locked access. + pass_scrubs: AtomicU64, + tilemap_clear_bytes: AtomicU64, +} + +impl ScrubState { + const fn new() -> Self { + Self { + scrubbing: AtomicU32::new(0), + clean_mask: AtomicU32::new(0), + waiter: AtomicBool::new(false), + pass_scrubs: AtomicU64::new(0), + tilemap_clear_bytes: AtomicU64::new(0), + } + } + + fn is_scrubbing(&self, k: usize) -> bool { + self.scrubbing.load(Ordering::Acquire) & (1u32 << k) != 0 + } + + fn is_clean(&self, k: usize) -> bool { + self.clean_mask.load(Ordering::Acquire) & (1u32 << k) != 0 + } + + fn take_clean(&self, k: usize) -> bool { + let bit = 1u32 << k; + self.clean_mask.fetch_and(!bit, Ordering::AcqRel) & bit != 0 + } + + fn clear_clean(&self, k: usize) { + self.clean_mask.fetch_and(!(1u32 << k), Ordering::Release); + } + + fn clear_all_clean(&self) { + self.clean_mask.store(0, Ordering::Release); + } +} + +/// One displaced render pass slot staged for off-lock WC scrubbing. +pub(crate) struct PendingScrub { + slot: usize, + arena: super::resources::PassOwnerArena, + state: Arc, + done: bool, +} + +impl PendingScrub { + fn run_one(&mut self) -> bool { + let bit = 1u32 << self.slot; + let ok = if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { + let dirty = tilemap_dirty.load(Ordering::Acquire); + match pass.scrub_clean(1, dirty) { + Ok(()) => { + tilemap_dirty.store(0, Ordering::Release); + self.state.pass_scrubs.fetch_add(1, Ordering::Relaxed); + self.state + .tilemap_clear_bytes + .fetch_add(dirty, Ordering::Relaxed); + true + } + Err(_) => false, + } + } else { + false + }; + if ok { + self.state.clean_mask.fetch_or(bit, Ordering::Release); + } + self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); + self.done = true; + self.state.waiter.swap(false, Ordering::SeqCst) + } +} + +impl Drop for PendingScrub { + fn drop(&mut self) { + if !self.done { + let bit = 1u32 << self.slot; + self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); + } + } +} + +/// Zero-allocation batch of displaced render pass slots to scrub after dropping `Shared::state`. +pub(crate) struct ScrubBatch { + items: [Option; sizes::RENDER_SLOTS], + len: usize, +} + +impl ScrubBatch { + pub(crate) const fn new() -> Self { + Self { + items: [const { None }; sizes::RENDER_SLOTS], + len: 0, + } + } + + fn push(&mut self, item: PendingScrub) -> bool { + if self.len >= sizes::RENDER_SLOTS { + return false; + } + self.items[self.len] = Some(item); + self.len += 1; + true + } + + /// Runs every staged off-lock pass scrub. Returns `true` if a waiting submitter needs wakeup. + pub(crate) fn run(mut self) -> bool { + let mut wake = false; + for slot in &mut self.items[..self.len] { + if let Some(mut item) = slot.take() { + wake |= item.run_one(); + } + } + wake + } +} + /// Displacement ledger and VM leases of the render pass slots (see [`Slots`]). pub(crate) struct RenderOwners { lifetime: Lifetime<{ sizes::RENDER_SLOTS }>, @@ -451,6 +584,11 @@ pub(crate) struct RenderOwners { scrub_full: [bool; sizes::RENDER_SLOTS], /// Whether the most recent claim of each render pass slot required a full scrub/work write. last_full: [bool; sizes::RENDER_SLOTS], + /// Displaced pass slots staged after publication to run once `Shared::state` is released. + staged: ScrubBatch, + /// A clean render retired since the last unlock; stage any remaining displaced pass slots + /// only after publication finishes so a freshly displaced slot never blocks immediate reuse. + scrub_pending: bool, } pub(crate) struct Slots { @@ -459,6 +597,8 @@ pub(crate) struct Slots { pub(crate) pass_cursor: u32, scrub_gen: u64, pub(crate) stats: SlotStats, + /// Shared atomic state for off-lock pre-scrubbing of displaced render pass slots. + scrub: Arc, /// 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, @@ -472,6 +612,7 @@ impl Slots { pass_cursor: 0, scrub_gen: 0, stats: SlotStats::default(), + scrub: Arc::new(ScrubState::new(), GFP_KERNEL)?, compute: KBox::new( ComputeOwners { lifetime: Lifetime::new(true), @@ -495,6 +636,8 @@ impl Slots { pending_arena: [const { None }; sizes::RENDER_SLOTS], scrub_full: [true; sizes::RENDER_SLOTS], last_full: [true; sizes::RENDER_SLOTS], + staged: ScrubBatch::new(), + scrub_pending: false, }, GFP_KERNEL, )?, @@ -544,8 +687,99 @@ impl Slots { /// 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)) + let mut saw_scrubbing = false; + let limit = n.min(sizes::RENDER_SLOTS); + for k in 0..limit { + if self.pass_busy & (1 << k) == 0 && self.render.lifetime.available(k) { + if !self.scrub.is_scrubbing(k) { + return true; + } + saw_scrubbing = true; + } + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + for k in 0..limit { + if self.pass_busy & (1 << k) == 0 + && self.render.lifetime.available(k) + && !self.scrub.is_scrubbing(k) + { + return true; + } + } + } + false + } + /// Whether any render pass slot is currently being scrubbed off-lock. + pub(crate) fn scrubbing_active(&self) -> bool { + self.scrub.scrubbing.load(Ordering::Acquire) != 0 + } + /// Total pass scrubs including completed off-lock pre-scrubs. + pub(crate) fn pass_scrubs_total(&self) -> u64 { + self.stats + .pass_scrubs + .saturating_add(self.scrub.pass_scrubs.load(Ordering::Relaxed)) + } + /// Total tilemap bytes cleared including completed off-lock pre-scrubs. + pub(crate) fn tilemap_clear_bytes_total(&self) -> u64 { + self.stats + .tilemap_clear_bytes + .saturating_add(self.scrub.tilemap_clear_bytes.load(Ordering::Relaxed)) + } + fn fold_scrub_stats(&mut self) { + let scrubs = self.scrub.pass_scrubs.swap(0, Ordering::Relaxed); + let bytes = self.scrub.tilemap_clear_bytes.swap(0, Ordering::Relaxed); + self.stats.pass_scrubs = self.stats.pass_scrubs.saturating_add(scrubs); + self.stats.tilemap_clear_bytes = self.stats.tilemap_clear_bytes.saturating_add(bytes); + } + /// Records that a clean render retired so displaced pass slots left idle after + /// publication are staged for off-lock pre-scrubbing right before dropping `Shared::state`. + pub(crate) fn note_render_retired(&mut self) { + self.render.scrub_pending = true; + } + /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing. + /// Never touches `Published` or undisplaced `Retired` slots. + pub(crate) fn stage_displaced_pass_scrubs(&mut self) { + self.render.scrub_pending = false; + self.fold_scrub_stats(); + for k in 0..sizes::RENDER_SLOTS { + let bit = 1u32 << k; + if self.pass_busy & bit != 0 + || !self.render.lifetime.available(k) + || self.render.scrub_full[k] + || self.scrub.is_scrubbing(k) + || self.scrub.is_clean(k) + { + continue; + } + let Some(arena) = self.render.arena[k].clone() else { + continue; + }; + self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); + let item = PendingScrub { + slot: k, + arena, + state: self.scrub.clone(), + done: false, + }; + if !self.render.staged.push(item) { + break; + } + } + } + /// Removes all staged off-lock pass scrubs so the caller can run them outside `Shared::state`. + pub(crate) fn take_staged_scrubs(&mut self) -> ScrubBatch { + core::mem::replace(&mut self.render.staged, ScrubBatch::new()) + } + /// Stages idle displaced render pass slots after publication (when `allow_stage` and a + /// clean render retired since the last unlock) and hands them off for off-lock execution. + pub(crate) fn stage_and_take_scrubs(&mut self, allow_stage: bool) -> ScrubBatch { + if allow_stage && core::mem::take(&mut self.render.scrub_pending) { + self.stage_displaced_pass_scrubs(); + } else if !allow_stage { + self.render.scrub_pending = false; + } + self.take_staged_scrubs() } /// Compute units published and not yet retired. pub(crate) fn compute_published(&self) -> u32 { @@ -558,7 +792,11 @@ impl Slots { } #[allow(dead_code)] pub(crate) fn free_compute(&self) -> u32 { - (0..super::params::compute_units()) + self.free_compute_in(super::params::compute_units()) + } + /// Available compute units within the first `n` units (a VM's prepared count). + pub(crate) fn free_compute_in(&self, n: usize) -> u32 { + (0..n.min(sizes::COMPUTE_UNITS)) .filter(|&k| self.compute.lifetime.available(k)) .count() as u32 } @@ -568,6 +806,8 @@ impl Slots { 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]; + self.render.scrub_pending = false; + self.scrub.clear_all_clean(); } /// Forces a full scrub on the next claim of the units in `f` (after an affected error). @@ -581,6 +821,7 @@ impl Slots { for k in 0..sizes::RENDER_SLOTS { if f.pass_mask & (1 << k) != 0 { self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } } } @@ -608,7 +849,7 @@ impl Slots { f: &mut Claims, vm_id: Option, ) -> Result> { - if f.slot_count != 0 { + if f.slot_count as usize >= f.slot.len() { return Ok(None); } // Round robin over this VM's units: the next one in publication order is the @@ -628,8 +869,8 @@ impl Slots { return Err(e); } self.compute.last_full[k] = full; - f.slot[0] = k as u32; - f.slot_count = 1; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; self.cursor = ((k + 1) % n) as u32; return Ok(Some(k)); } @@ -644,6 +885,8 @@ impl Slots { picked: u32, ) -> Option { let n = arena.passes.len().min(sizes::RENDER_SLOTS); + let mut fallback = None; + let mut saw_scrubbing = false; for i in 0..n { let k = (self.pass_cursor as usize + i) % n; let p = &arena.passes[k]; @@ -652,7 +895,32 @@ impl Slots { && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 { - return Some(k); + if self.scrub.is_scrubbing(k) { + saw_scrubbing = true; + continue; + } + if self.scrub.is_clean(k) { + return Some(k); + } + fallback.get_or_insert(k); + } + } + if fallback.is_some() { + return fallback; + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + 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.render.lifetime.available(k) + && !self.scrub.is_scrubbing(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + return Some(k); + } } } None @@ -665,6 +933,8 @@ impl Slots { picked: u32, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); + let mut fallback = None; + let mut saw_scrubbing = false; for i in 0..n { let k = (self.pass_cursor as usize + i) % n; let Ok(p) = resources.render_pass(k) else { @@ -675,7 +945,34 @@ impl Slots { && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 { - return Some(k); + if self.scrub.is_scrubbing(k) { + saw_scrubbing = true; + continue; + } + if self.scrub.is_clean(k) { + return Some(k); + } + fallback.get_or_insert(k); + } + } + if fallback.is_some() { + return fallback; + } + if saw_scrubbing { + self.scrub.waiter.store(true, Ordering::SeqCst); + 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) + && !self.scrub.is_scrubbing(k) + && geo.tpc_bytes <= p.tpc.size as u64 + && geo.tilemap_bytes <= p.tilemap.size as u64 + { + return Some(k); + } } } None @@ -700,9 +997,10 @@ impl Slots { vm_id: Option, ) -> Result { let n = arena.passes.len().min(sizes::RENDER_SLOTS); - if k >= n || !self.render.lifetime.claim(k) { + if k >= n || self.scrub.is_scrubbing(k) || !self.render.lifetime.claim(k) { return Err(EBUSY); } + self.fold_scrub_stats(); // Only a retired displaced owner may reach here; no in-flight storage is reset. let full = self.render.scrub_full[k] || vm_id.is_none_or(|id| { @@ -710,22 +1008,25 @@ impl Slots { .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.render.lifetime.cancel(k); - return Err(e); + let pre_cleaned = self.scrub.take_clean(k); + if full || !pre_cleaned { + 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.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.render.last_full[k] = full; - if full { - arena.tpc_dirty[k].store(0, Ordering::Relaxed); - } - arena.tilemap_dirty[k].store(0, Ordering::Relaxed); self.pass_cursor = ((k + 1) % n) as u32; Ok(()) } @@ -739,41 +1040,45 @@ impl Slots { tilemap_bytes: u64, ) -> Result { let n = resources.render_passes()?.min(sizes::RENDER_SLOTS); - if k >= n || !self.render.lifetime.claim(k) { + if k >= n || self.scrub.is_scrubbing(k) || !self.render.lifetime.claim(k) { return Err(EBUSY); } + self.fold_scrub_stats(); 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)?; - // 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), - clear_tilemap, - full, - &mut self.stats, - ) { - self.render.lifetime.cancel(k); - return Err(e); + let pre_cleaned = self.scrub.take_clean(k); + if full || !pre_cleaned { + 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), + clear_tilemap, + 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.render.last_full[k] = full; - if full { - tpc_dirty.store(0, Ordering::Relaxed); - tilemap_dirty.store(0, Ordering::Relaxed); - } self.pass_cursor = ((k + 1) % n) as u32; Ok(()) } @@ -821,7 +1126,7 @@ impl Slots { /// Retains each actual owner's VM/ASID binding through the firmware's last-owner era. /// 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 + if f.slot_count as usize > f.slot.len() || f.slot[..f.slot_count as usize] .iter() .any(|&k| k as usize >= sizes::COMPUTE_UNITS) @@ -932,6 +1237,7 @@ impl Slots { self.render.lifetime.quarantine(k); self.render.pending_retarget[k] = None; self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } } self.pass_busy &= !f.pass_mask; @@ -955,6 +1261,7 @@ impl Slots { self.render.pending_owner[k] = None; self.render.pending_arena[k] = None; self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } } 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 e27f000089eb33..0310690cf36d10 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -146,20 +146,25 @@ def module(text, name): } pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; - pub struct ComputeArena{pub compute:KVec} + pub struct ComputeArena{pub compute:KVec,pub render:Option>} // A job's compute units; here one arena. pub type Prepared=ComputeArena; #[derive(Clone)] pub enum PassOwnerArena{Base(crate::sync::Arc)} + impl PassOwnerArena{ + pub fn pass_and_tilemap_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,&AtomicU64)>{ + match self{Self::Base(a)=>Some((a.passes.get(k)?,a.tilemap_dirty.get(k)?))} + } + } 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 fn render_arena(&self)->Option>{self.render.clone()} + pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} + pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} + pub fn render_pass_dirty(&self,k:usize)->Result<(&AtomicU64,&AtomicU64)>{let r=self.render.as_deref().ok_or(EINVAL)?;if k>=r.passes.len(){return Err(EINVAL);}Ok((&r.tpc_dirty[k],&r.tilemap_dirty[k]))} + pub fn pass_owner_arena(&self,_k:usize)->Option{self.render.as_ref().map(|r|PassOwnerArena::Base(r.clone()))} } pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } @@ -179,7 +184,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)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} + Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<fills_before); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); + // Cancel, re-displace, pre-scrub clean, then invalidate_scrub() or cross-VM forces full scrub. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + let _=s.take_staged_scrubs().run(); + s.invalidate_scrub(); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + let _=s.take_staged_scrubs().run(); + s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + } + #[test]fn post_publish_scrub_staging_does_not_block_immediate_slot_reuse(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let render=sync::Arc::new(arena.render,0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let a=vm(1); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + // Prime slot 0, then displace it by retiring slot 1; record retirement without staging yet. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + render.set_dirty(0,0x1000,0x2000).unwrap(); + render.passes[0].tilemap.fill(0,0x77,0x2000).unwrap(); + s.retire(&mut c0).unwrap(); + s.note_render_retired(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.retire(&mut c1).unwrap(); + s.note_render_retired(); + // Immediate publication in the same lock hold sees slot 0 available and NOT scrubbing. + assert!(!s.scrubbing_active()); + assert!(s.pass_available(2)); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + // Disallowed staging (fail-stop / frozen) stages nothing and clears pending flag. + assert!(!s.stage_and_take_scrubs(false).run()); + assert!(!s.scrubbing_active()); + // Allowed staging after publication stages idle displaced slot 0 and scrubs it off-lock. + s.note_render_retired(); + let batch=s.stage_and_take_scrubs(true); + assert!(s.scrubbing_active()); + assert!(!batch.run()); + assert!(!s.scrubbing_active()); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); + // Calling stage_and_take_scrubs again without a new render retirement is a no-op. + assert!(!s.stage_and_take_scrubs(true).run()); + assert!(!s.scrubbing_active()); + } + } ''' budget=(production/'budget.rs').read_text() @@ -799,7 +937,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 26, + 'result': 'pass', 'tests': 27, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 05d7362e95a8418aeccbfd9f929ed7c05f31dc24 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:16:21 -0500 Subject: [PATCH 0827/1514] 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 62c403d9f9a8c1..31bf2db0d28844 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 365e670819a6c0..ba322395c26f16 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 5be89f660c41be5c12e34f25af9bc2e9137233f3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 01:16:11 -0500 Subject: [PATCH 0828/1514] drm/asahi: g16: bypass drm_sched on ready inline submits and signal timelines off-lock Ready submissions with already-signalled inputs previously still allocated and armed a drm_sched job and woke the scheduler kworker even when inline publication succeeded, and `try_submit_inline()` used `try_lock()` on `Shared::state`, bouncing bursts during brief poll-lock windows onto `drm_sched` wakeups and causing 350-520 us gap95 tail stalls on multi-depth workloads. In addition, `Timeline::complete()` held `Timeline::pending` across `dma_fence_signal()` callbacks. Bypass `drm_sched` allocation and kworker wakeup in `Scheduler::push()` when `prev_started` is true and `Job::try_start_inline()` succeeds, rolling back `accepted` and falling through to `drm_sched` otherwise. Track active firmware recovery in `Shared::recovering` (guarded via RAII in `Firmware::recover()`) so `Shared::try_submit_inline()` can bail out only during sleep or recovery and otherwise acquire `Shared::state` directly. Finally, split `Timeline::complete()` so ready head fences are drained in fixed stack batches under `signaller -> pending` and signalled without holding `Timeline::pending`. Extend `test-job-failure.py` and `test-fence-signalling.py` to cover `Scheduler::push()` inline bypass/fallback rollback, recovery bailout, and off-pending FIFO batch signalling. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/fence.rs | 75 +++++-- drivers/gpu/drm/asahi/g16/job.rs | 45 ++-- drivers/gpu/drm/asahi/g16/mod.rs | 3 + drivers/gpu/drm/asahi/g16/poll.rs | 13 +- drivers/gpu/drm/asahi/g16/recovery.rs | 16 ++ .../gpu/asahi-m4/test-fence-signalling.py | 205 +++++++++++++++++- .../drivers/gpu/asahi-m4/test-job-failure.py | 100 ++++++++- 7 files changed, 401 insertions(+), 56 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 01ba768b313b72..1083760da3646d 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -84,6 +84,9 @@ impl FenceOps for JobFenceOps { } } +/// Stack batch size for signalling completed fences outside `Timeline::pending`. +const SIGNAL_BATCH: usize = 8; + /// An accepted fence of a timeline that has not signalled yet. struct Pending { fence: UserFence, @@ -98,6 +101,11 @@ pub(crate) struct Timeline { jobs: FenceContexts, /// One context for the error fences of refused submissions, each signalled at creation. errors: FenceContexts, + /// Serializes dma-fence signalling outside `pending` so fences of this context always + /// signal in creation order without holding `pending` across callbacks. + /// Lock order: `signaller` -> `pending` (never reversed; `next()` locks only `pending`). + #[pin] + signaller: Mutex<()>, /// Accepted fences that have not signalled, oldest first. #[pin] pending: Mutex>, @@ -113,6 +121,7 @@ impl Timeline { try_pin_init!(Self { jobs: FenceContexts::new(1, c_str!("aurora_g16_queue"), TIMELINE_KEY)?, errors, + signaller <- new_mutex!((), "g16::Timeline::signaller"), pending <- new_mutex!(KVec::new(), "g16::Timeline::pending"), allocation_failure, }), @@ -141,32 +150,60 @@ impl Timeline { }) } - /// Records the result of `fence` and signals every completed fence at the head, in order. + /// Records the result of `fence` and signals every completed fence at the head, in order, + /// without holding `pending` across `dma_fence_signal` callbacks. fn complete(&self, fence: &UserFence, result: Result) { - let mut pending = self.pending.lock(); - let Some(entry) = pending - .iter_mut() - .find(|entry| entry.fence.raw() == fence.raw()) - else { - // Already signalled. - return; + let head_ready = { + let mut pending = self.pending.lock(); + let Some(entry) = pending + .iter_mut() + .find(|entry| entry.fence.raw() == fence.raw()) + else { + // Already signalled. + return; + }; + if entry.result.is_some() { + return; + } + entry.result = Some(result); + pending.first().is_some_and(|entry| entry.result.is_some()) }; - if entry.result.is_some() { + if !head_ready { return; } - entry.result = Some(result); - let mut signalled = 0; - for entry in pending.iter() { - let Some(result) = entry.result else { - break; + let _signaller = self.signaller.lock(); + loop { + let mut batch: [Option<(UserFence, Result)>; SIGNAL_BATCH] = + [const { None }; SIGNAL_BATCH]; + let (count, more) = { + let mut pending = self.pending.lock(); + let ready = pending + .iter() + .take(SIGNAL_BATCH) + .take_while(|entry| entry.result.is_some()) + .count(); + let mut idx = 0; + for entry in pending.drain(..ready) { + if let Some(res) = entry.result { + batch[idx] = Some((entry.fence, res)); + idx += 1; + } + } + let more = pending.first().is_some_and(|entry| entry.result.is_some()); + (idx, more) }; - if let Err(error) = result { - entry.fence.set_error(error); + for item in &mut batch[..count] { + if let Some((fence, res)) = item.take() { + if let Err(error) = res { + fence.set_error(error); + } + fence.signal(); + } + } + if !more { + break; } - entry.fence.signal(); - signalled += 1; } - drop(pending.drain(..signalled)); } /// A signalled fence carrying `error`, for the output syncs of a refused submission. diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index e4d09ceaf20f9d..39415ba5ef31cd 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -243,31 +243,34 @@ impl Job { 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) { + /// Attempts to submit a ready job directly from SUBMIT ioctl context, bypassing `drm_sched`. + /// Only runs when all input fences are already signalled, the device and VM are healthy, + /// and the GPU is neither sleeping nor recovering; returns `true` when the job was started + /// inline (accepted or already finished with error), or `false` to fall back to `drm_sched`. + pub(crate) fn try_start_inline(self: &Arc, shared: &Arc) -> bool { if shared.crashed.load(Ordering::Acquire) || shared.sleeping.load(Ordering::Acquire) + || shared.recovering.load(Ordering::Acquire) || self.vm.status.get() != 0 { - return; + return false; } if let Some(order) = self.orders.first() { if self.queue.check(order).is_err() { - return; + return false; } } if super::fence::check_dependencies(&self.inputs).is_err() { - return; + return false; } 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); } + true + } else { + false } } @@ -584,8 +587,10 @@ impl Scheduler { }) } - /// 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. + /// Pushes a job that waits for its retained inputs. When the predecessor has already + /// started and all inputs are signalled, submits directly inline and bypasses `drm_sched` + /// allocation and kworker wakeup. 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 = match &self.last_scheduled { @@ -597,12 +602,19 @@ impl Scheduler { None => true, }; let handle = job.clone(); + if prev_started { + handle.accepted.store(true, Ordering::Release); + if handle.try_start_inline(&shared) { + return Ok(()); + } + handle.accepted.store(false, Ordering::Release); + } let scheduled = Arc::new(AtomicBool::new(false), GFP_KERNEL)?; let mut pending = self.entity.new_job( 1, SchedJob { job, - shared: shared.clone(), + shared, scheduled: scheduled.clone(), }, )?; @@ -611,14 +623,7 @@ impl Scheduler { } let armed = pending.arm(); handle.accepted.store(true, Ordering::Release); - if prev_started { - handle.try_start_inline(&shared); - } - if handle.is_started() { - scheduled.store(true, Ordering::Release); - } else { - self.last_scheduled = Some(scheduled); - } + self.last_scheduled = Some(scheduled); armed.push(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index cf2bf38f387993..7d758bebb6b32e 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -234,6 +234,8 @@ pub(crate) struct Shared { /// From a system sleep's `.prepare` until the firmware restarted: nothing reads its /// registers and nothing is published. pub(crate) sleeping: AtomicBool, + /// Firmware recovery is active under `Shared::state` (may sleep up to 1000 ms). + pub(crate) recovering: AtomicBool, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -471,6 +473,7 @@ impl Gpu { rtkit_buffer: AtomicU64::new(0), orphaned: AtomicBool::new(false), sleeping: AtomicBool::new(false), + recovering: AtomicBool::new(false), sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 928c2ba879db06..63c3aa56960eb8 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -283,15 +283,20 @@ impl Shared { 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. + /// Inline SUBMIT ioctl publication: acquires `Shared::state` directly when the GPU is + /// neither sleeping nor recovering so brief poll-lock overlap does not bounce ready + /// submissions onto `drm_sched` kworker wakeups. Returns `None` during sleep or recovery + /// so `drm_sched` handles those paths without stalling SUBMIT. pub(crate) fn try_submit_inline(self: &Arc, job: Arc) -> Option { + if self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { + return None; + } let signalling = kernel::dma_fence::SignallingGuard::new(); let mut done = Completions::new(); let mut scrubs = super::slots::ScrubBatch::new(); let accepted = { - let mut state = self.state.try_lock()?; - if self.sleeping.load(Ordering::Acquire) { + let mut state = self.state.lock(); + if self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { return None; } match state.as_deref_mut() { diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index cf53ae99bdc81d..f8b5c9bd568567 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -402,6 +402,22 @@ impl Firmware { } fn recover(&mut self) -> Result { + struct RecoveringGuard(Option>); + impl Drop for RecoveringGuard { + fn drop(&mut self) { + if let Some(shared) = &self.0 { + shared + .recovering + .store(false, core::sync::atomic::Ordering::Release); + } + } + } + if let Some(shared) = &self.engine.shared { + shared + .recovering + .store(true, core::sync::atomic::Ordering::Release); + } + let _recovering = RecoveringGuard(self.engine.shared.clone()); let start = self.events.recovery_started_ns.unwrap_or_else(now_ns); self.recovery.running = true; self.engine.frozen = true; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index c9863ae62a03f3..15a62acd017406 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -1,9 +1,11 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Exercise the production task-local DMA-fence lockdep guard with and without LOCKDEP.""" +"""Exercise production DMA-fence lockdep guard and Timeline off-pending signalling.""" from common import kernel_root, output_dir, rustc, sha import json +import pathlib import subprocess +import tempfile root = kernel_root() out = output_dir() @@ -65,8 +67,205 @@ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) (out / 'fence-signalling-not-send.log').write_text(result.stdout) assert result.returncode and 'E0277' in result.stdout and 'cannot be sent between threads safely' in result.stdout, result.stdout + +fence_source_path = root / 'drivers/gpu/drm/asahi/g16/fence.rs' +fence_source = fence_source_path.read_text() + + +def extract_function(text, name): + marker = text.index('fn ' + name + '(') + start = text.rfind('\n', 0, marker) + 1 + first = text.index('{', marker) + depth = 1 + at = first + 1 + while depth: + depth += (text[at] == '{') - (text[at] == '}') + at += 1 + return text[start:at] + + +signal_batch_line = [ + line for line in fence_source.splitlines() if line.startswith('const SIGNAL_BATCH:') +][0] +timeline_complete_fn = extract_function(fence_source, 'complete') + +timeline_harness = r''' +#![allow(dead_code)] +use std::sync::{Arc, Barrier, Mutex as StdMutex}; +use std::sync::atomic::{AtomicI32, AtomicU64, Ordering}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Error(i32); +const EIO: Error = Error(-5); +const ECANCELED: Error = Error(-125); +type Result = std::result::Result; + +struct Mutex(StdMutex); +impl Mutex { + fn new(v: T) -> Self { Self(StdMutex::new(v)) } + fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } + fn try_lock(&self) -> std::sync::TryLockResult> { + self.0.try_lock() + } +} + +#[derive(Clone)] +struct JobFenceOps; +struct FenceInner { + seqno: u64, + error: AtomicI32, + log: Arc>>, + on_signal: Option>, +} +#[derive(Clone)] +struct UserFence(Arc, core::marker::PhantomData); +impl UserFence { + fn new( + seqno: u64, + log: Arc>>, + on_signal: Option>, + ) -> Self { + Self( + Arc::new(FenceInner { + seqno, + error: AtomicI32::new(0), + log, + on_signal, + }), + core::marker::PhantomData, + ) + } + fn raw(&self) -> *const FenceInner { Arc::as_ptr(&self.0) } + fn set_error(&self, error: Error) { self.0.error.store(error.0, Ordering::Release); } + fn signal(&self) { + if let Some(cb) = &self.0.on_signal { + cb(self.0.seqno); + } + self.0.log.lock().unwrap().push((self.0.seqno, self.0.error.load(Ordering::Acquire))); + } +} + +SIGNAL_BATCH_LINE + +struct Pending { + fence: UserFence, + result: Option, +} + +struct Timeline { + next_seq: AtomicU64, + signaller: Mutex<()>, + pending: Mutex>, + log: Arc>>, +} + +impl Timeline { + fn new() -> Arc { + Arc::new(Self { + next_seq: AtomicU64::new(1), + signaller: Mutex::new(()), + pending: Mutex::new(Vec::new()), + log: Arc::new(StdMutex::new(Vec::new())), + }) + } + + fn next(&self, on_signal: Option>) -> UserFence { + let seq = self.next_seq.fetch_add(1, Ordering::AcqRel); + let fence = UserFence::new(seq, self.log.clone(), on_signal); + self.pending.lock().push(Pending { fence: fence.clone(), result: None }); + fence + } + + TIMELINE_COMPLETE_FN +} + +#[test] +fn out_of_order_and_large_batches_signal_strictly_in_order() { + let tl = Timeline::new(); + let count = SIGNAL_BATCH * 3 + 2; + let fences: Vec<_> = (0..count).map(|_| tl.next(None)).collect(); + for i in (1..count).rev() { + let res = if i % 7 == 0 { Err(EIO) } else { Ok(()) }; + tl.complete(&fences[i], res); + } + assert!(tl.log.lock().unwrap().is_empty()); + tl.complete(&fences[1], Err(ECANCELED)); + tl.complete(&fences[0], Ok(())); + let log = tl.log.lock().unwrap().clone(); + assert_eq!(log.len(), count); + for (idx, (seq, err)) in log.iter().enumerate() { + assert_eq!(*seq, (idx + 1) as u64); + assert_eq!(*err, if idx != 0 && idx % 7 == 0 { EIO.0 } else { 0 }); + } + assert!(tl.pending.lock().is_empty()); + tl.complete(&fences[0], Err(EIO)); + assert_eq!(tl.log.lock().unwrap().len(), count); +} + +#[test] +fn signal_callbacks_do_not_hold_pending_lock_and_allow_next() { + let tl = Timeline::new(); + let tl_cb = tl.clone(); + let f1 = tl.next(Some(Arc::new(move |_| { + assert!(tl_cb.pending.try_lock().is_ok()); + let _f_nested = tl_cb.next(None); + }))); + tl.complete(&f1, Ok(())); + assert_eq!(tl.log.lock().unwrap().len(), 1); + assert_eq!(tl.pending.lock().len(), 1); +} + +#[test] +fn concurrent_completers_preserve_strict_fifo_signal_order() { + for _ in 0..64 { + let tl = Timeline::new(); + let n = 16usize; + let fences: Vec<_> = (0..n).map(|_| tl.next(None)).collect(); + let barrier = Arc::new(Barrier::new(n)); + let mut threads = Vec::with_capacity(n); + for (i, fence) in fences.into_iter().enumerate() { + let tl = tl.clone(); + let barrier = barrier.clone(); + threads.push(std::thread::spawn(move || { + barrier.wait(); + tl.complete(&fence, if i == 5 { Err(ECANCELED) } else { Ok(()) }); + })); + } + for t in threads { + t.join().unwrap(); + } + let log = tl.log.lock().unwrap().clone(); + assert_eq!(log.len(), n); + for (idx, (seq, err)) in log.iter().enumerate() { + assert_eq!(*seq, (idx + 1) as u64); + assert_eq!(*err, if idx == 5 { ECANCELED.0 } else { 0 }); + } + assert!(tl.pending.lock().is_empty()); + } +} +'''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( + 'TIMELINE_COMPLETE_FN', timeline_complete_fn +) + +with tempfile.TemporaryDirectory(prefix='m4-rust-timeline-') as directory: + directory = pathlib.Path(directory) + tl_unit = directory / 'timeline.rs' + tl_unit.write_text(timeline_harness) + tl_bin = directory / 'timeline' + for command in [ + rustc() + ['--edition=2021', '--test', '-Dwarnings', str(tl_unit), '-o', str(tl_bin)], + [str(tl_bin), '--nocapture'], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 4, 'negative_compile_checks': 1, 'cpu_only': True, - 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants with task-cookie mock; does not exercise kernel lockdep or GPU lock ordering.', + 'passed': True, 'tests': 7, 'negative_compile_checks': 1, 'cpu_only': True, + 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants and g16 Timeline::complete() off-pending FIFO batch signalling.', 'source_sha256': sha(production), + 'timeline_source_sha256': sha(fence_source_path), }, indent=2) + '\n') 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 b4861355cf8110..1cee63b7c52a17 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 @@ -18,8 +18,8 @@ queue_source = (SOURCE.parent / 'queue.rs').read_text() order_source = command_source[command_source.index('/// Exact queue-local command ordinal'):command_source.index('/// A validated render command.')] -def function(text, name): - marker = text.index('fn ' + name + '(') +def function_from(text, marker_text): + marker = text.index(marker_text) start = text.rfind('\n', 0, marker) + 1 first = text.index('{', marker) depth = 1 @@ -29,8 +29,12 @@ def function(text, name): at += 1 return text[start:at] +def function(text, name): + return function_from(text, 'fn ' + name + '(') + 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', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) +push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' #![allow(dead_code)] @@ -99,22 +103,51 @@ 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:AtomicU64,terminal_retired:AtomicBool } -struct Shared { crashed:AtomicBool,sleeping:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } +struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { - Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) + Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) } + fn note_submitter(&self) {} 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; } + if self.contended.load(Ordering::Acquire) || self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { return None; } Some(self.submit(job)) } } impl Job { METHODS } +struct SchedJob { job:Arc, shared:Arc } +struct ArmedJob { job:SchedJob, pushed:Arc>> } +impl ArmedJob { + fn push(self) { self.pushed.lock().unwrap().push(self.job.job.id); } +} +struct PendingJob { job:SchedJob, deps:Vec, pushed:Arc>>, fail_dep:bool } +impl PendingJob { + fn add_dependency(&mut self, fence:InputFence)->Result { + if self.fail_dep { return Err(ENOMEM); } + self.deps.push(fence); + Ok(()) + } + fn arm(self)->ArmedJob { ArmedJob { job:self.job, pushed:self.pushed } } +} +struct Entity { new_jobs:AtomicUsize, pushed:Arc>>, fail_new:bool, fail_dep:bool } +impl Entity { + fn new()->Self { Self { new_jobs:AtomicUsize::new(0), pushed:Arc::new(Mutex::new(vec![])), fail_new:false, fail_dep:false } } + fn new_job(&mut self, _credits:u32, job:SchedJob)->Result { + self.new_jobs.fetch_add(1, Ordering::AcqRel); + if self.fail_new { return Err(ENOMEM); } + Ok(PendingJob { job, deps:vec![], pushed:self.pushed.clone(), fail_dep:self.fail_dep }) + } +} +struct Scheduler { entity:Entity, last_job:Option> } +impl Scheduler { + fn new()->Self { Self { entity:Entity::new(), last_job:None } } + PUSH_METHOD +} fn job(id:u64,status:Arc)->Arc { job_with_inputs(id,status,vec![]) } @@ -374,7 +407,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),sleeping:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Err(ENOMEM)}); + let shared=Arc::new(Shared{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering: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); @@ -405,20 +438,26 @@ def function(text, name): 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.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.try_start_inline(&shared)); assert!(!pending.is_started()); assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); + // Recovering device defers to drm_sched without blocking or marking started. + shared.recovering.store(true,Ordering::Release); + let rec=job(13,status.clone()); + assert!(!rec.try_start_inline(&shared)); + assert!(!rec.is_started()); + shared.recovering.store(false,Ordering::Release); // 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.try_start_inline(&shared)); assert!(!contended.is_started()); assert_eq!(*shared.submitted.lock().unwrap(),vec![10]); shared.contended.store(false,Ordering::Release); @@ -426,7 +465,48 @@ def function(text, name): 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::')) +#[test] +fn scheduler_push_bypasses_drm_sched_on_inline_start_and_rolls_back_on_fallback_enomem() { + let status=Arc::new(Status::new()); + let shared=Shared::new(); + let mut sched=Scheduler::new(); + // Ready jobs bypass entity.new_job() and armed.push() completely. + let j1=job_with_inputs(1,status.clone(),vec![InputFence::new(1)]); + j1.accepted.store(false,Ordering::Release); + sched.push(j1.clone(),shared.clone()).unwrap(); + assert!(j1.is_started()); + assert!(j1.accepted.load(Ordering::Acquire)); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),0); + assert!(sched.entity.pushed.lock().unwrap().is_empty()); + assert_eq!(*shared.submitted.lock().unwrap(),vec![1]); + // Second ready job also bypasses drm_sched because j1 is already started. + let j2=job(2,status.clone()); + sched.push(j2.clone(),shared.clone()).unwrap(); + assert!(j2.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),0); + assert_eq!(*shared.submitted.lock().unwrap(),vec![1,2]); + // Unsignalled input falls back to drm_sched; subsequent job waits for predecessor start. + let j3=job_with_inputs(3,status.clone(),vec![InputFence::new(0)]); + sched.push(j3.clone(),shared.clone()).unwrap(); + assert!(!j3.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),1); + assert_eq!(*sched.entity.pushed.lock().unwrap(),vec![3]); + let j4=job(4,status.clone()); + sched.push(j4.clone(),shared.clone()).unwrap(); + assert!(!j4.is_started()); + assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),2); + assert_eq!(*sched.entity.pushed.lock().unwrap(),vec![3,4]); + // Fallback ENOMEM rolls back accepted so the failed push never poisons queue ordinals. + j3.started.store(true,Ordering::Release); + j4.started.store(true,Ordering::Release); + sched.entity.fail_new=true; + let j5=job_with_inputs(5,status.clone(),vec![InputFence::new(0)]); + j5.accepted.store(false,Ordering::Release); + assert_eq!(sched.push(j5.clone(),shared.clone()),Err(ENOMEM)); + assert!(!j5.accepted.load(Ordering::Acquire)); + assert!(!j5.is_started()); +} +'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: directory=pathlib.Path(directory); test=directory/'test.rs'; test.write_text(harness) From b3d0336aa5e39b41063eb14d0fbfd6016575d1ef Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 21 Nov 2026 17:18:48 -0500 Subject: [PATCH 0829/1514] 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 064b297f75bc51..2ebe9f2e5ed50f 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 31bf2db0d28844..5b57a40a8828a7 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 faa407bceb4c46..11b470b52330d0 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 c45d6772038f82..b6e9a734b4dad9 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 cdc9a931b087b8..38004c8d535706 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 a4dd5e322e2abc..bbfac08651d445 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 09f81edd3d35fd686cca7becce1f8859d82e2ee3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:09:39 -0500 Subject: [PATCH 0830/1514] drm/asahi: g16: expose independent queue limits Mirror the G15 logical-queue contract on G16: - Add params::queue_limits() (max_queues = MAX_QUEUES = 58, max_in_flight_per_queue = FLIGHTS = 32) and return it from Gpu::queue_limits(), which enables DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES and DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS in the shared frontend. - Track live logical queues per open DRM file in usage::Client via an RAII QueueCredit guard (ENOSPC at MAX_QUEUES), stored after Scheduler in Queue so capacity returns only after scheduler drain. Because G16 logical queues own no firmware execution contexts, keeping QueueCredit per-file while file.rs enforces per-process queue_share::Share bounds ensures a client that opens MAX_QUEUES queues cannot starve a later process (such as a compositor) from creating its own queue. - Extend test-publication.py and usage.rs unit tests to cover queue limits, INDEPENDENT_QUEUES, per-file QueueCredit isolation and release, and multi-queue compute+render concurrency on one VM. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 2 +- drivers/gpu/drm/asahi/g16/params.rs | 18 +- drivers/gpu/drm/asahi/g16/queue.rs | 33 +++- drivers/gpu/drm/asahi/usage.rs | 53 +++++- .../drivers/gpu/asahi-m4/test-publication.py | 155 +++++++++++++++++- 5 files changed, 248 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 7d758bebb6b32e..2233ba2eb3178e 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -662,7 +662,7 @@ impl gpu::Gpu for Gpu { } fn queue_limits(&self) -> Option { - None + Some(params::queue_limits()) } fn base_clock_hz(&self) -> u32 { diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 1b8bf9b6edb4e1..5238cd4445d51a 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`), 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. +//! SOFT_FAULTS suppressed by `soft_faults`, and `INDEPENDENT_QUEUES` from `queue_limits`), G16 +//! advertises per-command input readiness/errors, exact queue-local historical prefixes, +//! fragment-only render barriers, independent logical queues, and `COMPUTE_NO_QUERY_ACCESS`. +//! Ray queries are not advertised. use kernel::{prelude::*, uapi}; @@ -108,3 +108,13 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res } Ok(()) } + +/// QUEUE_LIMITS: a policy bound on logical queues (they own no firmware state) and the +/// number of prefixes in flight. +pub(crate) fn queue_limits() -> uapi::drm_asahi_queue_limits { + uapi::drm_asahi_queue_limits { + max_queues: hw::sizes::MAX_QUEUES, + max_in_flight_per_queue: hw::sizes::FLIGHTS as u32, + ..Default::default() + } +} diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index ada1946bb79835..2b6f5871abdc38 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -3,7 +3,12 @@ //! Logical queues: `crate::queue::Queue` for G16. //! //! Logical queues own no firmware state: they are independent scheduling entities over the one -//! shared graph, executed in one total order across queues and VMs. QUEUE_CREATE validates +//! shared graph, sharing the device's compute and render engines across queues and VMs. A +//! per-file host credit bounds each open DRM file's live logical queues to the advertised +//! `MAX_QUEUES` (ENOSPC when full) while `file.rs`'s `queue_share::Share` bounds multi-file +//! hoarding per process, so one client cannot exhaust logical-queue creation for another +//! process (such as a compositor). It reserves no hardware graph or execution context. +//! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or //! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are //! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). @@ -93,6 +98,28 @@ impl QueueState { } } +/// One per-file logical-queue credit, released after the queue scheduler drains. +struct QueueCredit { + usage: Arc, +} + +impl QueueCredit { + fn acquire(usage: &Arc) -> Result { + if !usage.try_acquire_queue(hw::sizes::MAX_QUEUES) { + return Err(ENOSPC); + } + Ok(Self { + usage: usage.clone(), + }) + } +} + +impl Drop for QueueCredit { + fn drop(&mut self) { + self.usage.release_queue(); + } +} + /// A G16 logical queue. pub(crate) struct Queue { // Dropped first: QUEUE_DESTROY drains the scheduler before anything else goes. @@ -103,6 +130,8 @@ pub(crate) struct Queue { vm: Arc, shared: Arc, timeline: Arc, + // Last field: all preceding fields (especially scheduler) drop before capacity returns. + _credit: QueueCredit, } impl Queue { @@ -134,6 +163,7 @@ impl Queue { if vm_state.status.get() != 0 { return Err(EIO); } + let credit = QueueCredit::acquire(&usage)?; let timeline = Timeline::new()?; let scheduler = Scheduler::new(&gpu.shared.dev)?; let state = Arc::new( @@ -157,6 +187,7 @@ impl Queue { vm: vm_state, shared: gpu.shared.clone(), timeline, + _credit: credit, }) } diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index aa817d2d417687..eee128207aeff0 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -9,7 +9,7 @@ //! A backend whose firmware overlaps the commands of one queue charges through a [`Lane`] //! per queue, so each engine of a queue counts the union of its stage intervals. -use core::sync::atomic::{AtomicU64, Ordering}; +use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; #[derive(Clone, Copy)] pub(crate) enum Engine { @@ -21,15 +21,47 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { ns: [AtomicU64; 3], + queues: AtomicU32, } impl Client { pub(crate) const fn new() -> Self { Self { ns: [const { AtomicU64::new(0) }; 3], + queues: AtomicU32::new(0), } } + /// Reserves one logical queue credit against this DRM file up to `limit`. + pub(crate) fn try_acquire_queue(&self, limit: u32) -> bool { + let mut count = self.queues.load(Ordering::Acquire); + loop { + if count >= limit { + return false; + } + match self.queues.compare_exchange_weak( + count, + count + 1, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return true, + Err(value) => count = value, + } + } + } + + /// Releases one logical queue credit previously acquired from this DRM file. + pub(crate) fn release_queue(&self) { + let previous = self.queues.fetch_sub(1, Ordering::AcqRel); + debug_assert!(previous != 0); + } + + #[cfg(test)] + pub(crate) fn queues(&self) -> u32 { + self.queues.load(Ordering::Acquire) + } + /// Called exactly once per retired stage, while its internal timestamps are retained. /// Missing, reversed or reset timestamps contribute nothing. Sub-nanosecond fractions /// are rounded down per stage. Saturation keeps fdinfo monotonic even on overflow. @@ -318,4 +350,23 @@ mod tests { } assert_eq!(client.snapshot(), [0, 0, 80_000_000]); } + + #[test] + fn per_file_queue_credits_are_bounded_and_isolated() { + let a = Client::new(); + let b = Client::new(); + for i in 0..4u32 { + assert!(a.try_acquire_queue(4)); + assert_eq!(a.queues(), i + 1); + } + assert!(!a.try_acquire_queue(4)); + assert_eq!(a.queues(), 4); + assert!(b.try_acquire_queue(4)); + assert_eq!(b.queues(), 1); + a.release_queue(); + assert_eq!(a.queues(), 3); + assert!(a.try_acquire_queue(4)); + b.release_queue(); + assert_eq!(b.queues(), 0); + } } 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 7101edc16a010c..3c921fe10e1a43 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -7,21 +7,45 @@ production = kernel_root() / 'drivers/gpu/drm/asahi/g16/engine.rs' source = production.read_text() +params_src = (production.parent / 'params.rs').read_text() +queue_src = (production.parent / 'queue.rs').read_text() +mod_src = (production.parent / 'mod.rs').read_text() +hw_src = (production.parent / 'hw.rs').read_text() +gpu_src = (production.parent.parent / 'gpu.rs').read_text() output = output_dir() -def item(declaration): - start = source.index(declaration) - at = source.index('{', start) +def item_in(src, declaration): + start = src.index(declaration) + at = src.index('{', start) depth, end = 1, at + 1 while depth: - depth += (source[end] == '{') - (source[end] == '}') + depth += (src[end] == '{') - (src[end] == '}') end += 1 - return source[start:end] + return src[start:end] + + +def item(declaration): + return item_in(source, declaration) + + +# Verify Queue struct declares `_credit: QueueCredit` after `scheduler: Scheduler`. +queue_struct = item_in(queue_src, 'pub(crate) struct Queue {') +sched_pos = queue_struct.index('scheduler: Scheduler') +credit_pos = queue_struct.index('_credit: QueueCredit') +assert sched_pos < credit_pos, 'QueueCredit must drop after Scheduler' +assert queue_struct[credit_pos:].strip().endswith('}'), '_credit must be last Queue field' +gpu_limits_fn = item_in(mod_src, 'fn queue_limits(&self) -> Option') +assert 'Some(params::queue_limits())' in gpu_limits_fn, gpu_limits_fn +assert 'DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES' in gpu_src +max_queues_line = next(line for line in hw_src.splitlines() if 'const MAX_QUEUES:' in line) +flights_line = next(line for line in hw_src.splitlines() if 'const FLIGHTS:' in line) harness = r''' #![allow(dead_code, unused_variables)] +#[path = "__USAGE__"] +mod usage; use std::sync::{Arc, atomic::{AtomicU32,AtomicU64,AtomicBool,Ordering}}; use std::collections::VecDeque; #[derive(Copy,Clone,Debug,PartialEq,Eq)] struct Error(i32); @@ -655,9 +679,128 @@ def item(declaration): assert_eq!(fw2.session.checks.load(Ordering::Relaxed),1); assert_eq!(fw2.session.transports.load(Ordering::Relaxed),1); } + #[test]fn multi_queue_concurrent_compute_and_render_on_same_vm(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q_comp=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q_rend=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let c_job=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q_comp.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{sequence:1,wait_through:[None,None]}, + extra_orders:vec![], + dependency:Ok(()),resources:Resources, + }); + let r_job=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q_rend.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{sequence:1,wait_through:[None,None]}, + extra_orders:vec![], + dependency:Ok(()),resources:Resources, + }); + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:0,flights:vec![QueueBehindFlight{ + job:c_job.clone(),first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target: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}, + }; + // Queue 1 render queues directly behind Queue 0 compute on the same VM with no cross-engine barrier. + assert!(p.can_queue_behind(&r_job)); + assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); + // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. + p.engine.flights[0]=QueueBehindFlight{ + job:r_job,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert!(p.can_queue_behind(&c_job)); + assert_eq!(p.cross_engine_wait(&c_job,0,command::RENDER),Ok(None)); + } +} +#[allow(non_camel_case_types, deprecated)] +mod queue_limits_scope { + use std::sync::Arc; + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + struct Error(i32); + const ENOSPC: Error = Error(28); + type Result = std::result::Result; + mod uapi { + pub const DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES: u64 = 1 << 2; + #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] + pub struct drm_asahi_queue_limits { + pub max_queues: u32, + pub max_in_flight_per_queue: u32, + pub flags: u32, + pub pad: u32, + } + } + mod hw { + pub mod sizes { + __FLIGHTS_LINE__ + __MAX_QUEUES_LINE__ + } + } + mod params { + use super::{hw, uapi}; + __QUEUE_LIMITS_FN__ + } + struct Gpu; + impl Gpu { __GPU_QUEUE_LIMITS_FN__ } + __QUEUE_CREDIT_STRUCT__ + __QUEUE_CREDIT_IMPL__ + __QUEUE_CREDIT_DROP__ + #[test] + fn queue_limits_and_independent_queues_feature_match_g16_bounds() { + let gpu = Gpu; + let limits = gpu.queue_limits().expect("G16 must expose queue_limits"); + assert_eq!(limits.max_queues, 58); + assert_eq!(limits.max_in_flight_per_queue, 32); + assert_eq!(limits.flags, 0); + assert_eq!(limits.pad, 0); + let mut features = 0u64; + if gpu.queue_limits().is_some() { + features |= uapi::DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES; + } + assert_ne!(features & uapi::DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES, 0); + } + #[test] + fn queue_credit_enforces_per_file_max_queues_without_starving_other_clients() { + let client_a = Arc::new(crate::usage::Client::new()); + let client_b = Arc::new(crate::usage::Client::new()); + let mut held_a = Vec::new(); + for i in 0..hw::sizes::MAX_QUEUES { + held_a.push(QueueCredit::acquire(&client_a).expect("credit within MAX_QUEUES")); + assert_eq!(client_a.queues(), i + 1); + } + assert_eq!(QueueCredit::acquire(&client_a).err(), Some(ENOSPC)); + assert_eq!(client_a.queues(), hw::sizes::MAX_QUEUES); + // A second DRM file (e.g. a compositor) keeps its own queue budget. + let compositor = QueueCredit::acquire(&client_b) + .expect("client A hitting MAX_QUEUES must not starve client B"); + assert_eq!(client_b.queues(), 1); + drop(held_a.pop()); + assert_eq!(client_a.queues(), hw::sizes::MAX_QUEUES - 1); + let reused = QueueCredit::acquire(&client_a).expect("dropped credit reusable"); + assert_eq!(QueueCredit::acquire(&client_a).err(), Some(ENOSPC)); + drop(compositor); + assert_eq!(client_b.queues(), 0); + drop(reused); + drop(held_a); + assert_eq!(client_a.queues(), 0); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) +harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) +harness = harness.replace('__FLIGHTS_LINE__', flights_line.strip()) +harness = harness.replace('__MAX_QUEUES_LINE__', max_queues_line.strip()) +harness = harness.replace('__QUEUE_LIMITS_FN__', item_in(params_src, 'pub(crate) fn queue_limits()')) +harness = harness.replace('__GPU_QUEUE_LIMITS_FN__', gpu_limits_fn) +harness = harness.replace('__QUEUE_CREDIT_STRUCT__', item_in(queue_src, 'struct QueueCredit {')) +harness = harness.replace('__QUEUE_CREDIT_IMPL__', item_in(queue_src, 'impl QueueCredit {')) +harness = harness.replace('__QUEUE_CREDIT_DROP__', item_in(queue_src, 'impl Drop for QueueCredit {')) for token, declaration in { '__PUBLICATION_ERROR__': 'enum PublicationError {', '__PICK__': 'fn pick(&self)', @@ -685,7 +828,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 24, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 57, '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') From 9f14889356cd497b805734355f637352fde64df7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 23:03:22 -0500 Subject: [PATCH 0831/1514] 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 5b57a40a8828a7..0a008b0c550d74 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 858efa71b4f7ee..3613d91234f129 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 784c2fa3915eb1..3070e4636d156b 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 3eeb2cf794f217..bdaa2aecbb4882 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 98165ef4abe696..f53be8b55c3362 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 38004c8d535706..6b0fa2d5b0b3e5 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 bbfac08651d445..9b4789b9f6d2a5 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< Date: Sun, 22 Nov 2026 07:13:57 -0500 Subject: [PATCH 0832/1514] drm/asahi: g16: batch barrier-free compute horizons into one doorbell Allow compute-only barrier-free command runs within a job and across consecutive ready compute-only jobs on the same queue and VM to share one firmware publication and one doorbell, bounded by free compute units, available compute ring slots, and the compute flight budget. Each batched compute member claims its own hardware compute unit, writes its own submitted counter before the shared barrier, and records its own completion stamp and work descriptor so retirement verifies every claimed unit receipt, publishes timestamps for every grouped job, and lets cross-engine waits and firmware recovery snapshots resolve interior stamps. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 264 +++++++++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 7 +- drivers/gpu/drm/asahi/g16/job.rs | 52 ++++ drivers/gpu/drm/asahi/g16/poll.rs | 187 ++++++++--- .../drivers/gpu/asahi-m4/test-publication.py | 292 ++++++++++++++++-- .../drivers/gpu/asahi-m4/test-resources.py | 37 +++ .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 33 +- .../drivers/gpu/asahi-m4/test-timestamps.py | 36 ++- 8 files changed, 782 insertions(+), 126 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 023713080d3d9c..39eb2c252ba5dc 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -170,10 +170,11 @@ pub(crate) struct Flight { pub(crate) fs_start: u32, /// Channel producers (TA, FS, compute) after the prefix's records. pub(crate) rec: [u32; 3], - /// Compute member j's FW stamp target, and the FS target it waits on directly (0: none): - /// its predecessors in the prefix (for the compute-hang check). + /// Compute member j's FW stamp target, the FS target it waits on directly (0: none), and + /// its private UMA counter value after publication. pub(crate) cstamp: [u32; sizes::COMPUTE_SLOTS], pub(crate) cwait: [u32; sizes::COMPUTE_SLOTS], + pub(crate) csubmitted: [u64; sizes::COMPUTE_SLOTS], /// Compute slots, pass slots and clustering buffers it holds. pub(crate) claims: Claims, /// A kill or recovery ended this prefix's VM: later prefixes of it fail with EIO. @@ -220,6 +221,7 @@ impl Flight { rec: [0; 3], cstamp: [0; sizes::COMPUTE_SLOTS], cwait: [0; sizes::COMPUTE_SLOTS], + csubmitted: [0; sizes::COMPUTE_SLOTS], claims: Claims::new(), doomed: false, uma_submitted: 0, @@ -668,7 +670,10 @@ impl Firmware { .flights .iter_mut() .find(|f| match event { - 15 => f.computes != 0 && f.target == target, + 15 => { + f.computes != 0 + && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) + } 0x70 => f.renders != 0 && f.ta_target == target, 0x71 => f.renders != 0 && f.fs_target == target, _ => false, @@ -1097,7 +1102,7 @@ impl Firmware { }; waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) }); - let compute_count = e.flights.iter().filter(|f| f.computes != 0).count(); + let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() @@ -1137,31 +1142,44 @@ impl Firmware { if job.queue.completed[other].load(Ordering::Acquire) >= last { return Ok(None); } - for flight in &self.engine.flights { - if !Arc::ptr_eq(&flight.job.queue, &job.queue) { - continue; - } - if other == super::command::COMPUTE && flight.computes != 0 { - for member in 0..flight.count { - if flight - .job - .command_order((flight.first + member) as u32) - .is_some_and(|fo| fo.sequence == last) - { + if other == super::command::COMPUTE { + for flight in &self.engine.flights { + if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + continue; + } + let mut member = 0usize; + for k in flight.first..flight.first + flight.count { + if flight.job.command_order(k as u32).is_some_and(|fo| { + fo.engine == super::command::COMPUTE && fo.sequence == last + }) { return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); } + member += 1; } - } else if other == super::command::RENDER && flight.renders != 0 { - for member in 0..flight.count { - if flight - .job - .command_order((flight.first + member) as u32) - .is_some_and(|fo| fo.sequence == last) - { - return Ok(Some(flight.fs_target)); + for j2 in flight.group.iter() { + for k in 0..j2.progress.count() { + if j2.command_order(k).is_some_and(|fo| { + fo.engine == super::command::COMPUTE && fo.sequence == last + }) { + return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + } + member += 1; } } } + return Err(EAGAIN); + } + for flight in &self.engine.flights { + if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + continue; + } + for k in flight.first..flight.first + flight.count { + if flight.job.command_order(k as u32).is_some_and(|fo| { + fo.engine == super::command::RENDER && fo.sequence == last + }) { + return Ok(Some(flight.fs_target)); + } + } } Err(EAGAIN) } @@ -1253,7 +1271,7 @@ impl Firmware { fn publish_prefix( &mut self, job: &Arc, - done: &mut Completions, + _done: &mut Completions, pending_rings: &mut u8, ) -> core::result::Result<(), PublicationError> { let mut f = Flight::new(job.clone()); @@ -1261,12 +1279,10 @@ impl Firmware { 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 - // fail with it. + // Never published: its storage is free again. Horizon candidates are removed + // from `pending` only after visibility begins, so they remain untouched here. self.slots.release(&mut f.claims); - for j2 in f.group.iter() { - complete(done, j2, Err(e)); - } + f.group.clear(); Err(PublicationError::Unpublished(e)) } Err(e) => Err(PublicationError::Uncertain(e)), @@ -1370,6 +1386,7 @@ impl Firmware { if prefix.c_head >= 256 || prefix.ta_head >= 256 || prefix.fs_head >= 256 { return Err(super::boot::eproto()); } + let mut c_read = prefix.c_head; if class_behind { if render { let ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; @@ -1385,9 +1402,9 @@ impl Firmware { } } else { // Room for an optional cross-engine barrier plus compute work entry. - let read = self.graph.compute.qstate.r32(qstate::READ)?; - if read >= 256 - || prefix.c_head.wrapping_sub(read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 + c_read = self.graph.compute.qstate.r32(qstate::READ)?; + if c_read >= 256 + || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 { return Err(EAGAIN); } @@ -1396,8 +1413,115 @@ impl Firmware { f.c_start = prefix.c_head; f.ta_start = prefix.ta_head; f.fs_start = prefix.fs_head; + let mut end = index + 1; + let mut hz_stop: Option = None; match cmd { - Command::Compute(c) => self.prefix_compute(job, c, &mut prefix, f, false)?, + Command::Compute(c) => { + self.prefix_compute(job, &job.resources, index, c, &mut prefix, f, false)?; + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let vm_units = job.resources.compute_units()?.min(sizes::COMPUTE_UNITS); + let free_c = self.slots.free_compute_in(vm_units) as usize; + let active_computes: usize = + self.engine.flights.iter().map(|fl| fl.computes as usize).sum(); + let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; + let ring_more = (sizes::QUEUE_CAP.saturating_sub(3)).saturating_sub(used) as usize; + let mut more_slots = free_c + .min(params::compute_flights().saturating_sub(active_computes + 1)) + .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) + .min(ring_more); + // Fold trailing barrier-free compute commands of the base job first. + while more_slots > 0 && end < job.progress.count() { + let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !job.can_fold_horizon_cmd(end, next_seq) + || super::recovery::logic::next_ordinal(prefix.n).is_none() + { + break; + } + let Some(Command::Compute(c2)) = command(job, end) else { + break; + }; + self.prefix_compute(job, &job.resources, end, c2, &mut prefix, f, false)?; + last_seq = Some(next_seq); + end += 1; + more_slots -= 1; + } + // Compute horizon: fold subsequent ready, barrier-free compute-only jobs of + // the same queue and VM into the same CDM producer advance and doorbell. + // Any non-qualifying job of this queue ends the scan so no later job overtakes it. + if end == job.progress.count() { + hz_stop = Some(0); + let mut idx = 0; + while idx < self.engine.pending.len() { + let j2 = self.engine.pending[idx].clone(); + idx += 1; + if Arc::ptr_eq(&j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + continue; + } + if 1 + f.group.len() >= sizes::HORIZON_JOBS as usize { + hz_stop = Some(1); + break; + } + let n2 = j2.progress.count(); + let Some(first_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + hz_stop = Some(3); + break; + }; + if !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.progress.sent() != 0 + || n2 == 0 + || !j2.can_fold_horizon_job(first_seq) + { + hz_stop = Some(3); + break; + } + let n2_usize = n2 as usize; + if n2_usize > more_slots { + hz_stop = Some(2); + break; + } + let mut test_n = prefix.n; + let mut ord_ok = true; + for _ in 0..n2 { + match super::recovery::logic::next_ordinal(test_n) { + Some(next) => test_n = next, + None => { + ord_ok = false; + break; + } + } + } + if !ord_ok { + hz_stop = Some(2); + break; + } + if f.group.reserve(1, GFP_NOWAIT).is_err() { + hz_stop = Some(1); + break; + } + for k in 0..n2 { + match command(&j2, k).ok_or(EINVAL)? { + Command::Compute(c2) => { + self.prefix_compute( + &j2, + &job.resources, + k, + c2, + &mut prefix, + f, + false, + )?; + } + Command::Render(_) => return Err(EINVAL), + } + } + last_seq = Some(first_seq + u64::from(n2 - 1)); + more_slots -= n2_usize; + let _ = f.group.push_within_capacity(j2); + } + } + } Command::Render(r) => { let geometry = Geometry::new(&r.cmd, 0); let n = job.resources.render_passes()?; @@ -1422,7 +1546,7 @@ impl Firmware { } } f.first = index as usize; - f.count = 1; + f.count = (end - index) as usize; f.computes = prefix.computes; f.renders = prefix.renders; f.target = prefix.last_ct; @@ -1468,11 +1592,13 @@ impl Firmware { self.graph.render.threshold.w32(0, prefix.draw as u32)?; self.graph.render.threshold.w32(8, prefix.draw as u32)?; } else { - let k = f.claims.slot[0] as usize; - job.resources - .compute_unit(k)? - .counter - .w64(0, f.uma_submitted)?; + for m in 0..f.claims.slot_count as usize { + let k = f.claims.slot[m] as usize; + job.resources + .compute_unit(k)? + .counter + .w64(0, f.csubmitted[m])?; + } self.graph.compute.threshold.w32(0, prefix.n as u32)?; } wmb(); @@ -1568,8 +1694,34 @@ impl Firmware { self.renew_compute_deadline(); } } - job.progress.set_sent(index + 1); - job.command_published(index); + job.progress.set_sent(end); + for k in index..end { + job.command_published(k); + } + for j2 in f.group.iter() { + let n2 = j2.progress.count(); + j2.progress.set_sent(n2); + for k in 0..n2 { + j2.command_published(k); + } + self.engine.turn += 1; + j2.queue.turn.store(self.engine.turn, Ordering::Relaxed); + j2.progress.set_pending(false); + self.engine.pending.retain(|p| !Arc::ptr_eq(p, j2)); + } + if !render { + let s = &mut self.engine.stats; + let jobs = 1 + f.group.len(); + let bucket = (jobs - 1).min(s.hz.len() - 1); + s.hz[bucket] += 1; + if let Some(stop) = hz_stop { + s.hz_stop[stop] += 1; + } + if class_behind { + s.hz_behind += 1; + } + s.grouped = s.grouped.saturating_add(f.group.len() as u64); + } let mut flight = Flight::new(job.clone()); core::mem::swap(&mut flight, f); self.engine @@ -1587,24 +1739,34 @@ impl Firmware { } /// Encodes one command into its retained compute unit and appends it to the CDM ring. + #[expect( + clippy::too_many_arguments, + reason = "Encodes one compute member into a shared flight and prefix state." + )] fn prefix_compute( &mut self, job: &Arc, + resources: &super::resources::Prepared, + cmd_index: u32, cmd: &ComputeCommand, pf: &mut Prefix, f: &mut Flight, _later_render: bool, ) -> Result { + let member = pf.computes as usize; + if member >= sizes::COMPUTE_SLOTS { + return Err(EAGAIN); + } let n = super::recovery::logic::next_ordinal(pf.n).ok_or(EOVERFLOW)?; let target = encode::stamp(n); let index = self .slots - .claim_compute_for(&job.resources, &mut f.claims, Some(job.vm.id))? + .claim_compute_for(resources, &mut f.claims, Some(job.vm.id))? .ok_or(EAGAIN)?; let generation = job.vm.generation; self.slots.hold_vm(&f.claims, &job.vm)?; - self.slots.hold_arenas(&f.claims, &job.resources); - let s = job.resources.compute_unit(index)?; + self.slots.hold_arenas(&f.claims, resources); + let s = resources.compute_unit(index)?; let g = &self.graph.compute; let before = s.counter.r64(0)?; let submitted = before.checked_add(1).ok_or(EOVERFLOW)?; @@ -1680,8 +1842,7 @@ impl Firmware { &w[work::compute::BODY_ACTIVE_START..work::compute::BODY_ACTIVE_END], )?; } - let wait_render = - self.cross_engine_wait(job, job.progress.sent(), super::command::RENDER)?; + let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; if let Some(wait_fs) = wait_render { let bar = encode::barrier( self.graph.render.fw_stamp[1].va, @@ -1694,20 +1855,21 @@ impl Firmware { s.barrier.write(0, &bar)?; } f.uma_submitted = submitted; - f.has_timestamps = !cmd.timestamp_outputs.is_empty(); + f.csubmitted[member] = submitted; + f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); wmb(); if let Some(wait_fs) = wait_render { g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; self.engine.stats.fs2c0 += 1; - f.cwait[0] = wait_fs; + f.cwait[member] = wait_fs; } else { - f.cwait[0] = 0; + f.cwait[member] = 0; } g.ring.w64(8 * pf.c_head as usize, s.work.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; - f.cstamp[0] = target; - pf.computes = 1; + f.cstamp[member] = target; + pf.computes += 1; pf.n = n; pf.last_ct = target; pf.prev = Prev::Compute; diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 435d83ac8c5593..6ebc45434aeda0 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -673,7 +673,8 @@ pub(crate) mod sizes { pub(crate) const POOL_SIZE: u64 = 0x200000; pub(crate) const FREELIST_SEED: u32 = 8192; pub(crate) const QUEUE_CAP: u32 = 256; - pub(crate) const COMPUTE_SLOTS: usize = 2; + /// Compute units claimable in one batched compute prefix (matches `COMPUTE_UNITS`). + pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most (host client-VA budget: 512 MiB / 32 MiB @@ -707,8 +708,8 @@ pub(crate) mod sizes { /// (it displaced the unit), so `n` units keep up to `n - 1` compute commands in flight. 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; + /// Maximum jobs folded into one barrier-free compute horizon prefix. + pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; /// 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. diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 39415ba5ef31cd..cd02b2b677e4e1 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -317,6 +317,58 @@ impl Job { self.orders.get(index as usize).copied() } + /// Whether command `index` is a ready, barrier-free compute command continuing a compute + /// horizon at queue-local compute ordinal `expected`. + pub(crate) fn can_fold_horizon_cmd(&self, index: u32, expected: u64) -> bool { + if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + return false; + } + let Some(Command::Compute(_)) = self.commands.get(index as usize) else { + return false; + }; + let Some(order) = self.orders.get(index as usize) else { + return false; + }; + order.engine == super::command::COMPUTE + && order.sequence == expected + && order.wait_through == [None, None] + && self.queue.check(order).is_ok() + && super::fence::check_dependencies(&self.inputs).is_ok() + } + + /// Whether every command of this job is a ready, barrier-free compute command continuing + /// sequentially from `first_expected`. + pub(crate) fn can_fold_horizon_job(&self, first_expected: u64) -> bool { + let count = self.progress.count(); + if count == 0 + || self.progress.sent() != 0 + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + for k in 0..count { + let Some(expected) = first_expected.checked_add(u64::from(k)) else { + return false; + }; + let Some(Command::Compute(_)) = self.commands.get(k as usize) else { + return false; + }; + let Some(order) = self.orders.get(k as usize) else { + return false; + }; + if order.engine != super::command::COMPUTE + || order.sequence != expected + || order.wait_through != [None, None] + || self.queue.check(order).is_err() + { + return false; + } + } + true + } + /// 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. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 63c3aa56960eb8..7c19497eb590b3 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -666,11 +666,18 @@ impl Firmware { /// 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)> { + Self::compute_ticks_with(self.init.abi.compute().work_ticks, unit) + } + + fn compute_ticks_with( + work_ticks: Option<(usize, usize)>, + 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 { + let Some((start_off, end_off)) = work_ticks else { return Ok((start, end)); }; let w = &unit.work; @@ -831,20 +838,32 @@ impl Firmware { { 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, end) = self.compute_ticks(unit)?; - ticks = [start, end, 0, 0]; 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; + || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot); + let count = f.claims.slot_count as usize; + full &= count != 0 && count == f.computes as usize; + if full { + for m in 0..count { + let k = f.claims.slot[m] as usize; + let unit = f.job.resources.compute_unit(k)?; + let submitted = f.csubmitted[m]; + let (start, end) = self.compute_ticks(unit)?; + if m == 0 && count == 1 { + ticks = [start, end, 0, 0]; + } + full &= submitted != 0 + && unit.counter.r64(0)? == submitted + && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted + && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va + && start != 0 + && end > start; + if !full { + break; + } + } + } } else if f.computes != 0 { let g = &self.graph.compute; if g.fw_stamp.r32(0)? != f.target @@ -852,18 +871,30 @@ impl Firmware { { 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, end) = self.compute_ticks(unit)?; - ticks = [start, end, 0, 0]; full &= g.notifier.r32(notifier_page::COMPUTE_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; + && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; + let count = f.claims.slot_count as usize; + full &= count != 0 && count == f.computes as usize; + if full { + for m in 0..count { + let k = f.claims.slot[m] as usize; + let unit = f.job.resources.compute_unit(k)?; + let submitted = f.csubmitted[m]; + let (start, end) = self.compute_ticks(unit)?; + if m == 0 && count == 1 { + ticks = [start, end, 0, 0]; + } + full &= submitted != 0 + && unit.counter.r64(0)? == submitted + && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted + && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va + && start != 0 + && end > start; + if !full { + break; + } + } + } } if f.renders != 0 && render_behind { let g = &self.graph.render; @@ -1015,6 +1046,10 @@ impl Firmware { self.slots.quarantine(&mut f.claims); self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; @@ -1041,9 +1076,20 @@ impl Firmware { return; } } - if let Err(error) = f.job.note_full_retirement(f.first as u32, f.count as u32) { + let retired_ok = (|| -> Result { + f.job.note_full_retirement(f.first as u32, f.count as u32)?; + for j2 in f.group.iter() { + j2.note_full_retirement(0, j2.progress.count())?; + } + Ok(()) + })(); + if let Err(error) = retired_ok { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; @@ -1063,6 +1109,9 @@ impl Firmware { } self.slots.quarantine(&mut f.claims); self.retain(&f.job); + for j2 in f.group.iter() { + self.retain(j2); + } self.recovery.aborted_receipts = self.recovery.aborted_receipts.saturating_add(1); } if self.slots.compute_exhausted() { @@ -1075,6 +1124,10 @@ impl Firmware { if let Err(error) = self.publish_timestamps(&f, ×tamp_claims) { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; @@ -1085,11 +1138,29 @@ impl Firmware { if let Err(error) = f.job.command_retired(index as u32) { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; } } + for j2 in f.group.iter() { + for index in 0..j2.progress.count() { + if let Err(error) = j2.command_retired(index) { + self.retain(&f.job); + complete(done, &f.job, Err(error)); + for j3 in f.group.iter() { + self.retain(j3); + complete(done, j3, Err(error)); + } + self.fail_stop(error, done); + return; + } + } + } if receipt.owner_retired() && f.renders != 0 { self.slots.note_render_retired(); } @@ -1137,6 +1208,10 @@ impl Firmware { if let Err(proof_error) = job.mark_terminal_retired() { self.retain(&job); complete(done, &job, Err(proof_error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(proof_error)); + } self.fail_stop(proof_error, done); core::mem::forget(f); return; @@ -1144,29 +1219,46 @@ impl Firmware { } complete(done, &job, Err(error)); } - if p.next() < p.sent() || p.sent() < p.count() { - return; // more of it published or still to publish - } - let s = &mut self.engine.stats; - if result.is_ok() { - s.jobs += 1; - s.job_cmds += u64::from(p.count()); - s.job_max = s.job_max.max(u64::from(p.count())); + let job_done = p.next() >= p.sent() && p.sent() >= p.count(); + if job_done { + let s = &mut self.engine.stats; + if result.is_ok() { + s.jobs += 1; + s.job_cmds += u64::from(p.count()); + s.job_max = s.job_max.max(u64::from(p.count())); + } + complete(done, &job, Ok(())); } - complete(done, &job, Ok(())); - // The rest of a compute horizon, after the first job (fence order). + // Complete folded compute-horizon jobs unconditionally (even if an earlier render + // command of `job` is still in flight; `Timeline` preserves queue fence order). for j2 in f.group.iter() { let p2 = &j2.progress; p2.next.store(p2.count(), Ordering::Relaxed); match result { - Err(error) => complete(done, j2, Err(error)), + Err(error) => { + if receipt.owner_retired() + && self.engine.flights.iter().all(|other| { + !Arc::ptr_eq(&other.job, j2) + && other.group.iter().all(|member| !Arc::ptr_eq(member, j2)) + }) + { + if let Err(proof_error) = j2.mark_terminal_retired() { + self.retain(j2); + complete(done, j2, Err(proof_error)); + self.fail_stop(proof_error, done); + return; + } + } + complete(done, j2, Err(error)); + } Ok(()) => { + let s = &mut self.engine.stats; s.jobs += 1; s.job_cmds += u64::from(p2.count()); s.job_max = s.job_max.max(u64::from(p2.count())); + complete(done, j2, Ok(())); } } - complete(done, j2, Ok(())); } } @@ -1255,6 +1347,24 @@ impl Firmware { } } } + for member in flight.group.iter() { + for command in member.commands.iter() { + match command { + super::command::Command::Compute(command) => { + let index = *slots.get(compute).ok_or(EINVAL)? as usize; + if !command.timestamp_outputs.is_empty() { + let unit = flight.job.resources.compute_unit(index)?; + let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } + compute += 1; + } + super::command::Command::Render(_) => return Err(EINVAL), + } + } + } Ok(()) } @@ -1272,6 +1382,7 @@ impl Firmware { }; let (mut lo, mut hi) = (u64::MAX, 0u64); let (mut first, mut last) = (u64::MAX, 0u64); + let work_ticks = self.init.abi.compute().work_ticks; let s = &mut self.engine.stats; let mut add_interval = @@ -1343,7 +1454,9 @@ impl Firmware { let Ok(c) = f.job.resources.compute_unit(f.claims.slot[k] as usize) else { return; }; - stage(&c.its, 0, &mut s.cdm_ticks, crate::usage::Engine::Compute); + if let Ok((start, end)) = Self::compute_ticks_with(work_ticks, c) { + add_interval(start, end, &mut s.cdm_ticks, crate::usage::Engine::Compute); + } } } if hi > lo { 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 3c921fe10e1a43..3479b5265dbf7f 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -9,6 +9,7 @@ source = production.read_text() params_src = (production.parent / 'params.rs').read_text() queue_src = (production.parent / 'queue.rs').read_text() +job_src = (production.parent / 'job.rs').read_text() mod_src = (production.parent / 'mod.rs').read_text() hw_src = (production.parent / 'hw.rs').read_text() gpu_src = (production.parent.parent / 'gpu.rs').read_text() @@ -40,6 +41,8 @@ def item(declaration): assert 'DRM_ASAHI_FEATURE_INDEPENDENT_QUEUES' in gpu_src max_queues_line = next(line for line in hw_src.splitlines() if 'const MAX_QUEUES:' in line) flights_line = next(line for line in hw_src.splitlines() if 'const FLIGHTS:' in line) +assert 'const COMPUTE_SLOTS: usize = COMPUTE_UNITS;' in hw_src +assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src harness = r''' @@ -458,7 +461,7 @@ def item(declaration): } } -#[derive(Copy,Clone)]struct Order{sequence:u64,wait_through:[Option;2]} +#[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources} impl QueueBehindJob{ fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -466,7 +469,7 @@ def item(declaration): if self.extra_orders.is_empty(){Some(self.order)}else{self.extra_orders.get(index as usize).copied()} } } -struct QueueBehindFlight{job:Arc,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],fs_target: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{ @@ -497,7 +500,7 @@ def item(declaration): 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]}, + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let j1=mk(1,vm1.clone(),q1.clone(),false); @@ -505,7 +508,7 @@ def item(declaration): 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,first:0,count:1,computes:1,renders:0,target:0x100,cstamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target: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}, }; @@ -534,7 +537,7 @@ def item(declaration): 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:[wait_vdm,wait_cdm]}, + order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let timed=mk(1,q1.clone(),true,None,None); @@ -543,7 +546,7 @@ def item(declaration): let no_barrier=mk(2,q1.clone(),true,None,None); let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,first:0,count:1,computes:1,renders:0,target:0x100,cstamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target: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}, }; @@ -556,11 +559,11 @@ def item(declaration): id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], - order:Order{sequence:1,wait_through:[None,None]}, + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let pr=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,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}, }; @@ -575,7 +578,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ 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]}, + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let r1=mk(1,vm1.clone(),true); @@ -583,7 +586,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,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,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}, }; @@ -613,7 +616,7 @@ def item(declaration): id,vm:vm1.clone(),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:false})}], - order:Order{sequence:seq,wait_through:wait}, + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let r1=mk(1,q1.clone(),true,1,[None,None]); @@ -623,8 +626,8 @@ def item(declaration): let c_other_q=mk(5,q2.clone(),false,1,[None,None]); let p=QueueBehindHost{ engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![ - QueueBehindFlight{job:r1,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},fs_target: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}, @@ -644,11 +647,11 @@ def item(declaration): id:6,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false});3], - order:Order{sequence:1,wait_through:[None,None]}, + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![ - Order{sequence:1,wait_through:[None,None]}, - Order{sequence:2,wait_through:[None,None]}, - Order{sequence:3,wait_through:[None,None]}, + Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, + Order{engine:command::COMPUTE,sequence:3,wait_through:[None,None]}, ], dependency:Ok(()),resources:Resources, }); @@ -659,7 +662,7 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let pm=QueueBehindHost{ engine:QueueBehindEngine{ordinal:3,draw:1,flights:vec![ - QueueBehindFlight{job:multi_c,first:0,count:3,computes:3,renders:0,target:0x300,cstamp,fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,fs_target: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}, @@ -687,7 +690,7 @@ def item(declaration): id:1,vm:vm1.clone(),queue:q_comp.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], - order:Order{sequence:1,wait_through:[None,None]}, + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![], dependency:Ok(()),resources:Resources, }); @@ -695,13 +698,13 @@ def item(declaration): id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], - order:Order{sequence:1,wait_through:[None,None]}, + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![], dependency:Ok(()),resources:Resources, }); let mut p=QueueBehindHost{ engine:QueueBehindEngine{ordinal:1,draw:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target: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}, @@ -712,12 +715,46 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); assert_eq!(p.cross_engine_wait(&c_job,0,command::RENDER),Ok(None)); } + #[test]fn cross_engine_wait_and_compute_flight_cap_account_for_batched_horizon_members(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),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:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![], + dependency:Ok(()),resources:Resources, + }); + let c1=mk(1,false,1,[None,None]); + let c2=mk(2,false,2,[None,None]); + let c3=mk(3,false,3,[None,None]); + let r_wait_c2=mk(4,true,1,[None,Some(2)]); + let r_wait_c3=mk(5,true,2,[None,Some(3)]); + let c4=mk(6,false,4,[None,None]); + let mut cstamp=[0u32;16]; + cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:3,draw:0,flights:vec![QueueBehindFlight{ + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,fs_target: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}, + }; + assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); + assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + // Active computes sum flight.computes: 16 batched computes saturates compute_flights(). + assert!(p.can_queue_behind(&c4)); + p.engine.flights[0].computes=16; + assert!(!p.can_queue_behind(&c4)); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -791,6 +828,197 @@ def item(declaration): assert_eq!(client_a.queues(), 0); } } +mod compute_horizon_scope { + use super::{Error, Result, EAGAIN, now_ns}; + const ENOENT: Error = Error(2); + const ERANGE: Error = Error(34); + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + mod command { pub const RENDER: usize = 0; pub const COMPUTE: usize = 1; } + #[derive(Copy, Clone)] + struct Order { engine: usize, sequence: u64, wait_through: [Option; 2] } + #[derive(Copy, Clone)] + enum Command { Compute(()), Render(()) } + mod fence { + use super::{Result, EAGAIN}; + pub fn check_dependencies(inputs: &[bool]) -> Result { + if inputs.iter().all(|&ready| ready) { Ok(()) } else { Err(EAGAIN) } + } + } + struct Status(AtomicU32); + impl Status { fn get(&self) -> u32 { self.0.load(Ordering::Relaxed) } } + struct Vm { status: Status } + struct Queue { cancelled_compute: u64 } + impl Queue { + fn check(&self, order: &Order) -> Result { + if self.cancelled_compute != 0 && order.sequence >= self.cancelled_compute { + Err(Error(125)) + } else { + Ok(()) + } + } + } + struct Progress { sent: u32, count: u32 } + impl Progress { + fn sent(&self) -> u32 { self.sent } + fn count(&self) -> u32 { self.count } + } + struct Job { + vm: Vm, + queue: Queue, + progress: Progress, + commands: Vec, + orders: Vec, + inputs: Vec, + terminal_retired: AtomicBool, + } + impl Job { + __CAN_FOLD_CMD__ + __CAN_FOLD_JOB__ + } + #[test] + fn compute_horizon_eligibility_rejects_barriers_renders_unready_fences_and_gaps() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, cancelled: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { cancelled_compute: cancelled }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + terminal_retired: AtomicBool::new(false), + }; + let ok_job = mk( + vec![Command::Compute(()), Command::Compute(())], + vec![ + Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }, + Order { engine: command::COMPUTE, sequence: 3, wait_through: [None, None] }, + ], + vec![true], + 0, + ); + assert!(ok_job.can_fold_horizon_cmd(0, 2)); + assert!(ok_job.can_fold_horizon_cmd(1, 3)); + assert!(!ok_job.can_fold_horizon_cmd(0, 5)); + assert!(ok_job.can_fold_horizon_job(2)); + assert!(!ok_job.can_fold_horizon_job(3)); + + // Render barrier or compute barrier breaks the batch. + let r_bar = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [Some(1), None] }], + vec![], + 0, + ); + assert!(!r_bar.can_fold_horizon_job(2)); + let c_bar = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, Some(1)] }], + vec![], + 0, + ); + assert!(!c_bar.can_fold_horizon_job(2)); + + // Render interleaved breaks the batch. + let mixed = mk( + vec![Command::Compute(()), Command::Render(())], + vec![ + Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + ], + vec![], + 0, + ); + assert!(!mixed.can_fold_horizon_job(2)); + + // Pending input fence or cancelled queue breaks the batch. + let unready = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![false], + 0, + ); + assert!(!unready.can_fold_horizon_job(2)); + let cancelled = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 2, + ); + assert!(!cancelled.can_fold_horizon_job(2)); + } + + mod recovery { + pub mod logic { + pub fn last_retired_target(last: &[Option; 3], event: u32, target: u32) -> bool { + let idx = match event { 15 => 0, 0x70 => 1, 0x71 => 2, _ => return false }; + last[idx] == Some(target) + } + } + } + mod poll { + pub fn stamp_reached(_obs: u32, _own: u32, _tail: u32) -> bool { true } + } + mod work { pub mod ta { pub const TPC_BYTES: usize = 0; } } + fn wmb() {} + struct PassBuf { size: usize } + impl PassBuf { + fn r64(&self, _o: usize) -> Result { Ok(0) } + fn fill(&self, _o: usize, _v: u8, _n: usize) -> Result { Ok(()) } + } + struct Pass { ta_work: PassBuf, tpc: PassBuf } + struct Resources; + impl Resources { fn render_pass(&self, _k: usize) -> Result<&Pass> { Err(ENOENT) } } + struct RecJob { resources: Resources } + struct RecClaims { pass: [u32; 2] } + struct RecFlight { + job: RecJob, + claims: RecClaims, + computes: u32, + renders: u32, + target: u32, + ta_target: u32, + fs_target: u32, + cstamp: [u32; 16], + doomed: bool, + recovery_suspect: bool, + recovery_started_ns: u64, + } + struct RecEngine { flights: Vec, ta_target: u32 } + struct RecState { last_retired: [Option; 3] } + struct RecFirmware { engine: RecEngine, recovery: RecState } + impl RecFirmware { + __RECOVERY_PREPARE__ + } + #[test] + fn recovery_prepare_matches_interior_cstamp_in_batched_compute_horizon() { + let mut cstamp = [0u32; 16]; + cstamp[0] = 0x100; + cstamp[1] = 0x200; + cstamp[2] = 0x300; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![RecFlight { + job: RecJob { resources: Resources }, + claims: RecClaims { pass: [0; 2] }, + computes: 3, + renders: 0, + target: 0x300, + ta_target: 0, + fs_target: 0, + cstamp, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + }], + ta_target: 0, + }, + recovery: RecState { last_retired: [None; 3] }, + }; + assert_eq!(fw.recovery_prepare(1, 15, 0x200, [0, 0, 0x100]), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0x100]), Err(ENOENT)); + } +} ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) @@ -801,6 +1029,24 @@ def item(declaration): harness = harness.replace('__QUEUE_CREDIT_STRUCT__', item_in(queue_src, 'struct QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_IMPL__', item_in(queue_src, 'impl QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_DROP__', item_in(queue_src, 'impl Drop for QueueCredit {')) +harness = harness.replace( + '__CAN_FOLD_CMD__', + item_in(job_src, 'pub(crate) fn can_fold_horizon_cmd(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__CAN_FOLD_JOB__', + item_in(job_src, 'pub(crate) fn can_fold_horizon_job(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) +harness = harness.replace( + '__RECOVERY_PREPARE__', + item('pub(crate) fn recovery_prepare(') + .replace('super::recovery::', 'recovery::') + .replace('super::poll::', 'poll::'), +) for token, declaration in { '__PUBLICATION_ERROR__': 'enum PublicationError {', '__PICK__': 'fn pick(&self)', @@ -828,7 +1074,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 57, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 60, '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-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 0310690cf36d10..78a09e8da3a532 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -892,6 +892,43 @@ def module(text, name): assert!(!s.stage_and_take_scrubs(true).run()); assert!(!s.scrubbing_active()); } + #[test]fn multi_unit_compute_horizon_claims_publish_retire_and_release(){ + use crate::g16::{hw, slots::ComputeSlot, resources::ComputeArena, vm}; + use crate::sync::Arc; + let mut o=Objects::new(); + let mut units=KVec::new(); + for k in 0..hw::sizes::COMPUTE_UNITS { + units.push(ComputeSlot::new(&mut o,k as u64).unwrap(),0).unwrap(); + } + let prep=ComputeArena{compute:units,render:None}; + let a=Arc::new(vm::VmState{id:1,slot:1,generation:1,vm:()},0).unwrap(); + let mut s=Slots::new().unwrap(); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),hw::sizes::COMPUTE_UNITS as u32); + // Claim 4 units into one Claims for a compute horizon, publish, and retire in order. + let mut claims=Claims::new(); + for i in 0..4 { + let k=s.claim_compute_for(&prep,&mut claims,Some(a.id)).unwrap().expect("free unit"); + assert_eq!(k,i); + assert_eq!(claims.slot_count,(i+1) as u32); + assert_eq!(claims.slot[i],k as u32); + } + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-4) as u32); + s.hold_vm(&claims,&a).unwrap(); + s.hold_arenas(&claims,&prep); + s.publish(&claims).unwrap(); + assert_eq!(s.compute_published(),4); + s.retire(&mut claims).unwrap(); + assert_eq!(s.compute_published(),0); + // Unit 3 (the newest retired) holds the displacement slot; 15 units remain free. + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-1) as u32); + // Claiming all remaining free units then releasing restores availability cleanly. + let mut batch=Claims::new(); + while s.claim_compute_for(&prep,&mut batch,Some(a.id)).unwrap().is_some() {} + assert_eq!(batch.slot_count as usize,hw::sizes::COMPUTE_UNITS-1); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),0); + s.release(&mut batch); + assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-1) as u32); + } } ''' 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 435e4ce3d943c5..ef21accd412542 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 @@ -44,8 +44,8 @@ def function(text, name): 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)}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],pb_slot:u32,uma_submitted:u64,recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} +struct Claims{slot:[u32;16],slot_count:u32,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],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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()}} @@ -73,7 +73,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,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,retired_ticks:[0;4]}, + 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;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, 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,completed:2},queue_passed:true, }; @@ -210,6 +210,33 @@ def function(text, name): f2.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(29))); assert_eq!(f2.retired_flight(),Ok(Some((1,Retirement::Full)))); } +#[test]fn multi_compute_horizon_requires_every_claimed_unit_receipt(){ + let mut f=firmware(false,12); + let mk_unit=|sub:u64,start:u64,end:u64|{ + let mut u=CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}; + u.counter.set(0,sub); + u.its.set(0,start);u.its.set(8,end); + u.work.set(compute::DESCRIPTOR_COMPLETED,sub); + u.work.set(compute::DESCRIPTOR_COUNTER,0x1234); + u + }; + let fl=&mut f.engine.flights[0]; + fl.computes=3; + fl.claims.slot_count=3; + fl.claims.slot[0]=0;fl.claims.slot[1]=1;fl.claims.slot[2]=2; + fl.csubmitted[0]=10;fl.csubmitted[1]=11;fl.csubmitted[2]=12; + fl.job.resources.compute=vec![mk_unit(10,100,110),mk_unit(11,110,120),mk_unit(12,120,130)]; + assert_eq!(f.retired(),Ok(Retirement::Full)); + // Missing interior unit completion keeps the whole batched flight pending. + f.engine.flights[0].job.resources.compute[1].work.set(compute::DESCRIPTOR_COMPLETED,10); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.compute[1].work.set(compute::DESCRIPTOR_COMPLETED,11); + // Missing tail unit ticks keeps the whole batched flight pending. + f.engine.flights[0].job.resources.compute[2].its.set(8,0); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.compute[2].its.set(8,130); + assert_eq!(f.retired(),Ok(Retirement::Full)); +} '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: 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 ed8087e3f2b320..e72860d955fff4 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -148,7 +148,7 @@ def function(source, marker): mod backend { use super::*; pub mod hw{pub const COMMAND_TIMESTAMP_HZ:u64=24_000_000;} - pub mod slots{pub struct Claims{pub slot:[u8;2],pub slot_count:u32,pub pass:[u8;2]}} + pub mod slots{pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;2]}} pub mod command{ use super::*; pub struct Compute{pub timestamp_outputs:Destinations} @@ -164,13 +164,13 @@ def function(source, marker): 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)}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 struct Flight{pub job:Job,pub group:Vec,pub first:usize,pub count:usize,pub renders:u32} pub mod poll{use super::*;impl Firmware{ __RETIRE__ }} } use backend::*; fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}}}} fn resources()->Resources{Resources{ - compute:vec![Compute{its:Cells([10,20,0,0])},Compute{its:Cells([30,40,0,0])}], + compute:vec![Compute{its:Cells([10,20,0,0])},Compute{its:Cells([30,40,0,0])},Compute{its:Cells([50,60,0,0])}], passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ @@ -178,8 +178,9 @@ def function(source, marker): let flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:outputs(&compute)}), command::Command::Render(command::Render{timestamp_outputs:outputs(&render)}) - ],resources:resources()},first:0,count:2,renders:1}; - let claims=slots::Claims{slot:[1,0],slot_count:1,pass:[1,0]}; + ],resources:resources()},group:vec![],first:0,count:2,renders:1}; + let mut slot=[0u8;16];slot[0]=1; + let claims=slots::Claims{slot,slot_count:1,pass:[1,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); assert_eq!(compute.words[0].load(Ordering::Relaxed),expected(30)); assert_eq!(compute.words[1].load(Ordering::Relaxed),expected(40)); @@ -187,11 +188,28 @@ def function(source, marker): assert_eq!(render.words[index].load(Ordering::Relaxed),expected(ticks)); } } +#[test]fn batched_compute_horizon_group_timestamps_publish_for_all_members(){ + let c0=backing();let c1=backing();let c2=backing(); + let flight=Flight{ + job:Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c0)})],resources:resources()}, + group:vec![ + Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c1)})],resources:Resources{compute:vec![],passes:vec![]}}, + Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c2)})],resources:Resources{compute:vec![],passes:vec![]}}, + ], + first:0,count:1,renders:0, + }; + let mut slot=[0u8;16];slot[0]=0;slot[1]=1;slot[2]=2; + let claims=slots::Claims{slot,slot_count:3,pass:[0,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); + assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(10),expected(20))); + assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(30),expected(40))); + assert_eq!((c2.words[0].load(Ordering::Relaxed),c2.words[1].load(Ordering::Relaxed)),(expected(50),expected(60))); +} #[test]fn invalid_command_span_and_missing_claim_are_rejected(){ let memory=backing();let mut flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:outputs(&memory)}) - ],resources:resources()},first:usize::MAX,count:2,renders:0}; - let mut claims=slots::Claims{slot:[0,0],slot_count:1,pass:[0,0]}; + ],resources:resources()},group:vec![],first:usize::MAX,count:2,renders:0}; + let mut claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0]}; assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EOVERFLOW)); flight.first=1;assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EINVAL)); flight.first=0;flight.count=1;claims.slot_count=0; @@ -202,8 +220,8 @@ def function(source, marker): let flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), command::Command::Render(command::Render{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), - ],resources:Resources{compute:vec![],passes:vec![]}},first:0,count:2,renders:1}; - let claims=slots::Claims{slot:[0,0],slot_count:1,pass:[0,0]}; + ],resources:Resources{compute:vec![],passes:vec![]}},group:vec![],first:0,count:2,renders:1}; + let claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); } '''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) From 7881307e77fde3f9fd157852d6c41e4c1bfe65b1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:14:30 -0500 Subject: [PATCH 0833/1514] drm/asahi: g16: skip inactive WC poll reads and trim submit allocations Avoid redundant uncached write-combining reads and barriers during poll and retirement: - Track per-class check state across retire_once() so retiring a burst of one class does not re-poll an already pending flight of the other class or double-poll a mixed flight. - Collapse oldest_stamp_reached() and progress() into single flight passes that touch only active classes, and skip the empty-ring rmb() in event and statistics draining. - Check FS firmware stamp before TA, and check notifier/descriptor receipts before reading scene or ITS timestamps so unsettled polls fail fast. Trim hot-path SUBMIT ioctl heap allocations without unsafe code: - Add inline 0..2 storage (Commands, Orders, Resolved, InputFences) that spills to KVec only above two entries, eliminating per-submit kmalloc traffic on single- and two-command submissions. - Move attachment lists into the final render or compute command of a stream via core::mem::take instead of duplicating them with copy_list(). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 228 +++++++++-- drivers/gpu/drm/asahi/g16/event.rs | 4 +- drivers/gpu/drm/asahi/g16/fence.rs | 50 +++ drivers/gpu/drm/asahi/g16/job.rs | 16 +- drivers/gpu/drm/asahi/g16/poll.rs | 353 ++++++++++-------- drivers/gpu/drm/asahi/g16/queue.rs | 8 +- .../gpu/asahi-m4/test-command-stream.py | 96 +++++ .../gpu/asahi-m4/test-fence-signalling.py | 71 +++- .../drivers/gpu/asahi-m4/test-poll-retire.py | 57 ++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 65 +++- 10 files changed, 727 insertions(+), 221 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index aeac172cecf399..cce8a5b52b2057 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -157,12 +157,158 @@ pub(crate) enum Command { Compute(KBox), } +/// Inline storage for the common 1-2 command submission, spilling to a heap `KVec` above 2. +pub(crate) enum Commands { + Empty, + One([Command; 1]), + Two([Command; 2]), + Heap(KVec), +} + +impl Commands { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, command: Command) -> Result { + match self { + Self::Heap(vec) => vec.push(command, GFP_KERNEL)?, + Self::Two(_) => { + // Allocate before moving inline entries so OOM leaves `self` intact. + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(command); + } + *self = Self::Heap(vec); + } + Self::One(_) => { + if let Self::One([a]) = core::mem::replace(self, Self::Empty) { + *self = Self::Two([a, command]); + } + } + Self::Empty => *self = Self::One([command]), + } + Ok(()) + } +} + +impl core::ops::Deref for Commands { + type Target = [Command]; + + fn deref(&self) -> &[Command] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Inline storage for the common 1-2 command ordinals, spilling to a heap `KVec` above 2. +pub(crate) enum Orders { + Empty, + One([Order; 1]), + Two([Order; 2]), + Heap(KVec), +} + +impl Orders { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, order: Order) -> Result { + match self { + Self::Heap(vec) => vec.push(order, GFP_KERNEL)?, + Self::Two([a, b]) => { + let (a, b) = (*a, *b); + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(order); + *self = Self::Heap(vec); + } + Self::One([a]) => *self = Self::Two([*a, order]), + Self::Empty => *self = Self::One([order]), + } + Ok(()) + } +} + +impl core::ops::Deref for Orders { + type Target = [Order]; + + fn deref(&self) -> &[Order] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Inline storage for transient resolved timestamp destinations during SUBMIT validation. +enum Resolved { + Empty, + One(Option), + Two([Option; 2]), + Heap { + items: KVec>, + index: usize, + }, +} + +impl Resolved { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, dest: crate::timestamp::Destinations) -> Result { + match self { + Self::Heap { items, .. } => items.push(Some(dest), GFP_KERNEL)?, + Self::Two(_) => { + let mut items = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { + let _ = items.push_within_capacity(a); + let _ = items.push_within_capacity(b); + let _ = items.push_within_capacity(Some(dest)); + } + *self = Self::Heap { items, index: 0 }; + } + Self::One(_) => { + if let Self::One(a) = core::mem::replace(self, Self::Empty) { + *self = Self::Two([a, Some(dest)]); + } + } + Self::Empty => *self = Self::One(Some(dest)), + } + Ok(()) + } + + fn next(&mut self) -> Option { + match self { + Self::Empty => None, + Self::One(slot) => slot.take(), + Self::Two(slots) => slots[0].take().or_else(|| slots[1].take()), + Self::Heap { items, index } => { + let item = items.get_mut(*index)?.take(); + *index += 1; + item + } + } + } +} + /// A validated SUBMIT. pub(crate) struct Submission { /// The commands, in submission order. - pub(crate) commands: KVec, + pub(crate) commands: Commands, /// Exact per-command queue-local ordinals, allocated before scheduler acceptance. - pub(crate) orders: KVec, + pub(crate) orders: Orders, /// Render and compute commands, for the queue's accepted-command accounting. pub(crate) counts: [u64; 2], } @@ -180,8 +326,8 @@ pub(crate) struct Context<'a> { pub(crate) struct Prepared<'a> { bytes: &'a [u8], /// CPU views and their backing resolved before scheduler acceptance. - resolved: KVec, - orders: KVec, + resolved: Resolved, + orders: Orders, counts: [u64; 2], } @@ -733,8 +879,8 @@ pub(crate) fn prepare<'a>( accepted: [u64; 2], objects: Pin<&xarray::XArray>>, ) -> Result> { - let mut resolved = KVec::new(); - let mut orders = KVec::new(); + let mut resolved = Resolved::new(); + let mut orders = Orders::new(); let mut preceding = [0u16; 2]; for entry in stream(bytes) { let entry = entry?; @@ -755,11 +901,14 @@ pub(crate) fn prepare<'a>( } _ => continue, }; - resolved.push(outputs, GFP_KERNEL)?; - orders.push( - Order::new(accepted, preceding, entry.barriers, prior, engine)?, - GFP_KERNEL, - )?; + resolved.push(outputs)?; + orders.push(Order::new( + accepted, + preceding, + entry.barriers, + prior, + engine, + )?)?; preceding[engine] += 1; } @@ -777,15 +926,16 @@ impl Prepared<'_> { pub(crate) fn validate(self, context: &Context<'_>) -> Result { let Prepared { bytes, - resolved, + mut resolved, orders, counts, } = self; - let mut commands = KVec::with_capacity(resolved.len(), GFP_KERNEL)?; + let mut commands = Commands::new(); let mut vertex = KVec::new(); let mut fragment = KVec::new(); let mut compute = KVec::new(); - let mut resolved = resolved.into_iter(); + let mut rem_renders = counts[RENDER]; + let mut rem_computes = counts[COMPUTE]; for entry in stream(bytes) { let entry = entry?; match entry.kind { @@ -797,36 +947,42 @@ impl Prepared<'_> { let cmd = &packet; let outputs = resolved.next().ok_or(EINVAL)?; check_render(context, cmd, &vertex, &fragment)?; - commands.push( - Command::Render(KBox::new( - RenderCommand { - cmd: *cmd, - timestamp_outputs: outputs, - vertex_attachments: copy_list(&[&vertex])?, - fragment_attachments: copy_list(&[&fragment])?, - }, - GFP_KERNEL, - )?), + rem_renders = rem_renders.checked_sub(1).ok_or(EINVAL)?; + let (vertex_attachments, fragment_attachments) = if rem_renders == 0 { + (core::mem::take(&mut vertex), core::mem::take(&mut fragment)) + } else { + (copy_list(&[&vertex])?, copy_list(&[&fragment])?) + }; + commands.push(Command::Render(KBox::new( + RenderCommand { + cmd: *cmd, + timestamp_outputs: outputs, + vertex_attachments, + fragment_attachments, + }, GFP_KERNEL, - )?; + )?))?; } CMD_COMPUTE => { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; check_compute(context, cmd, &compute)?; let outputs = resolved.next().ok_or(EINVAL)?; - commands.push( - Command::Compute(KBox::new( - ComputeCommand { - cmd: *cmd, - attachments: copy_list(&[&compute])?, - timestamp_outputs: outputs, - query_access: cmd.flags & COMPUTE_NO_QUERY_ACCESS == 0, - }, - GFP_KERNEL, - )?), + rem_computes = rem_computes.checked_sub(1).ok_or(EINVAL)?; + let attachments = if rem_computes == 0 { + core::mem::take(&mut compute) + } else { + copy_list(&[&compute])? + }; + commands.push(Command::Compute(KBox::new( + ComputeCommand { + cmd: *cmd, + attachments, + timestamp_outputs: outputs, + query_access: cmd.flags & COMPUTE_NO_QUERY_ACCESS == 0, + }, GFP_KERNEL, - )?; + )?))?; } _ => return Err(EINVAL), } diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index 0f161367e67ac9..f4fd9b723b634b 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -89,7 +89,9 @@ impl Events { if producer >= RING_SLOTS || consumer >= RING_SLOTS { return Err(super::boot::eproto()); } - rmb(); + if consumer != producer { + rmb(); + } Ok((consumer, producer)) } diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 1083760da3646d..5c2fafc3d5d4ba 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -23,6 +23,56 @@ use kernel::{ use crate::file::SyncItem; +/// Inline storage for the common 0-2 input fences, spilling to a heap `KVec` above 2. +pub(crate) enum InputFences { + Empty, + One([Fence; 1]), + Two([Fence; 2]), + Heap(KVec), +} + +impl InputFences { + pub(crate) const fn new() -> Self { + Self::Empty + } + + pub(crate) fn push(&mut self, fence: Fence) -> Result { + match self { + Self::Heap(vec) => vec.push(fence, GFP_KERNEL)?, + Self::Two(_) => { + // Allocate before moving inline entries so OOM leaves `self` intact. + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(fence); + } + *self = Self::Heap(vec); + } + Self::One(_) => { + if let Self::One([a]) = core::mem::replace(self, Self::Empty) { + *self = Self::Two([a, fence]); + } + } + Self::Empty => *self = Self::One([fence]), + } + Ok(()) + } +} + +impl core::ops::Deref for InputFences { + type Target = [Fence]; + + fn deref(&self) -> &[Fence] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + /// Reads a retained dependency's completion status without waiting or invoking callbacks. pub(crate) fn dependency_status(fence: &Fence) -> i32 { // SAFETY: The Fence reference keeps its dma_fence alive throughout the status read. diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index cd02b2b677e4e1..5fc8e426e188fd 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -44,8 +44,8 @@ use kernel::{ }; use super::{ - command::{Command, Order}, - fence::JobFence, + command::{Command, Commands, Order, Orders}, + fence::{InputFences, JobFence}, hw, queue::QueueState, vm::VmState, @@ -97,16 +97,16 @@ pub(crate) struct Job { /// The job's VM (TTBAT slot, status). pub(crate) vm: Arc, /// Validated commands, in submission order (at most 64). - pub(crate) commands: KVec, + pub(crate) commands: Commands, pub(crate) resources: super::resources::Prepared, /// Immutable dependency/order ledger, one entry for every accepted command. - orders: KVec, + orders: Orders, /// The job's hardware fence. pub(crate) fence: JobFence, /// The engine's bookkeeping; `progress.signaled` makes [`Job::complete`] act once. pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. - inputs: KVec, + inputs: InputFences, /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render /// commands within one job may retire in either hardware completion order. @@ -135,12 +135,12 @@ impl Job { id: u64, queue: Arc, vm: Arc, - commands: KVec, - orders: KVec, + commands: Commands, + orders: Orders, resources: super::resources::Prepared, fence: JobFence, guard: mmu::VmJobGuard, - inputs: KVec, + inputs: InputFences, ) -> Result> { if commands.len() != orders.len() { return Err(EINVAL); diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 7c19497eb590b3..f80c7a91790abe 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -592,15 +592,31 @@ impl Firmware { if self.engine.flights.is_empty() { return false; } + let mut oldest_compute: Option<&Flight> = None; + let mut compute_behind = false; + let mut oldest_render: Option<&Flight> = None; + let mut render_behind = false; + for f in self.engine.flights.iter() { + if f.computes != 0 { + if oldest_compute.is_none() { + oldest_compute = Some(f); + } else { + compute_behind = true; + } + } + if f.renders != 0 { + if oldest_render.is_none() { + oldest_render = Some(f); + } else { + render_behind = true; + } + } + if compute_behind && render_behind { + break; + } + } rmb(); - let compute_behind = self - .engine - .flights - .iter() - .filter(|f| f.computes != 0) - .count() - > 1; - if let Some(f) = self.engine.flights.iter().find(|f| f.computes != 0) { + if let Some(f) = oldest_compute { if let Ok(obs) = self.graph.compute.fw_stamp.r32(0) { let reached = if compute_behind { stamp_reached(obs, f.target, self.engine.target) @@ -612,14 +628,7 @@ impl Firmware { } } } - let render_behind = self - .engine - .flights - .iter() - .filter(|f| f.renders != 0) - .count() - > 1; - if let Some(f) = self.engine.flights.iter().find(|f| f.renders != 0) { + if let Some(f) = oldest_render { if let Ok(obs) = self.graph.render.fw_stamp[1].r32(0) { let reached = if render_behind { stamp_reached(obs, f.fs_target, self.engine.fs_target) @@ -646,12 +655,13 @@ impl Firmware { self.check_hangs(done)?; } let mut retired_any = false; - let mut ret = self.retired_flight(); + let (mut check_compute, mut check_render) = (true, true); + let mut ret = self.retired_flight_classes(&mut check_compute, &mut check_render); while let Ok(Some((index, receipt))) = ret { let outcome = self.retire_outcome_at(index, receipt); self.retire_oldest(index, receipt, outcome, done); retired_any = true; - ret = self.retired_flight(); + ret = self.retired_flight_classes(&mut check_compute, &mut check_render); } self.recovery.receipt_fault = ret.is_err(); Ok(retired_any) @@ -791,13 +801,56 @@ impl Firmware { /// Inspects the oldest compute flight and oldest render flight independently so either /// class can retire as soon as its hardware receipt settles without waiting on the other. pub(crate) fn retired_flight(&mut self) -> Result> { - let compute_idx = self.engine.flights.iter().position(|f| f.computes != 0); - let render_idx = self.engine.flights.iter().position(|f| f.renders != 0); - for index in [compute_idx, render_idx].into_iter().flatten() { + let (mut check_compute, mut check_render) = (true, true); + self.retired_flight_classes(&mut check_compute, &mut check_render) + } + + /// Like [`Self::retired_flight`], skipping classes that are inactive or already known + /// pending in the current [`Self::retire_once`] pass and never polling a mixed flight twice. + fn retired_flight_classes( + &mut self, + check_compute: &mut bool, + check_render: &mut bool, + ) -> Result> { + let (mut compute_idx, mut render_idx) = (None, None); + if *check_compute || *check_render { + for (i, f) in self.engine.flights.iter().enumerate() { + if *check_compute && compute_idx.is_none() && f.computes != 0 { + compute_idx = Some(i); + } + if *check_render && render_idx.is_none() && f.renders != 0 { + render_idx = Some(i); + } + if (!*check_compute || compute_idx.is_some()) + && (!*check_render || render_idx.is_some()) + { + break; + } + } + } + if compute_idx.is_none() { + *check_compute = false; + } + if render_idx.is_none() { + *check_render = false; + } + if let Some(index) = compute_idx { let receipt = self.retired_at(index)?; if receipt.complete() { return Ok(Some((index, receipt))); } + *check_compute = false; + if render_idx == Some(index) { + *check_render = false; + render_idx = None; + } + } + if let Some(index) = render_idx { + let receipt = self.retired_at(index)?; + if receipt.complete() { + return Ok(Some((index, receipt))); + } + *check_render = false; } Ok(None) } @@ -816,32 +869,35 @@ impl Firmware { // Later flights of the same engine class queued behind this one: that class's queue, // pipe and stamp cells already moved on, so its receipt is "passed", in order; the // newest flight of a class keeps the exact receipt. - let compute_behind = self - .engine - .flights - .iter() - .filter(|f| f.computes != 0) - .count() - > 1; - let render_behind = self - .engine - .flights - .iter() - .filter(|f| f.renders != 0) - .count() - > 1; - if f.computes != 0 && compute_behind { + if f.computes != 0 { + let compute_behind = self + .engine + .flights + .iter() + .filter(|o| o.computes != 0) + .nth(1) + .is_some(); 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); + if compute_behind { + 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 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); + } else { + if g.fw_stamp.r32(0)? != f.target + || !self.queue_receipt(Channel::Compute, &g.qstate, &g.qinfo, f.head, f.rec[2])? + { + return Ok(Retirement::Pending); + } + full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target + && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; } - 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); let count = f.claims.slot_count as usize; full &= count != 0 && count == f.computes as usize; if full { @@ -849,134 +905,101 @@ impl Firmware { let k = f.claims.slot[m] as usize; let unit = f.job.resources.compute_unit(k)?; let submitted = f.csubmitted[m]; - let (start, end) = self.compute_ticks(unit)?; - if m == 0 && count == 1 { - ticks = [start, end, 0, 0]; - } - full &= submitted != 0 - && unit.counter.r64(0)? == submitted - && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted - && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va - && start != 0 - && end > start; - if !full { + if submitted == 0 + || unit.counter.r64(0)? != submitted + || unit.work.r64(compute::DESCRIPTOR_COMPLETED)? != submitted + || unit.work.r64(compute::DESCRIPTOR_COUNTER)? != unit.counter.va + { + full = false; break; } - } - } - } 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])? - { - return Ok(Retirement::Pending); - } - full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target - && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; - let count = f.claims.slot_count as usize; - full &= count != 0 && count == f.computes as usize; - if full { - for m in 0..count { - let k = f.claims.slot[m] as usize; - let unit = f.job.resources.compute_unit(k)?; - let submitted = f.csubmitted[m]; let (start, end) = self.compute_ticks(unit)?; + if start == 0 || end <= start { + full = false; + break; + } if m == 0 && count == 1 { ticks = [start, end, 0, 0]; } - full &= submitted != 0 - && unit.counter.r64(0)? == submitted - && unit.work.r64(compute::DESCRIPTOR_COMPLETED)? == submitted - && unit.work.r64(compute::DESCRIPTOR_COUNTER)? == unit.counter.va - && start != 0 - && end > start; - if !full { - break; - } } } } - if f.renders != 0 && render_behind { + if f.renders != 0 { + let render_behind = self + .engine + .flights + .iter() + .filter(|o| o.renders != 0) + .nth(1) + .is_some(); 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)?; - if f.computes == 0 { - ticks = [ta_start, ta_end, fs_start, fs_end]; - } - 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 + if render_behind { + let e = &self.engine; + // Check FS (terminal stage) before TA so running renders fail fast on 1 WC read. + if !stamp_reached(g.fw_stamp[1].r32(0)?, f.fs_target, e.fs_target) + || !stamp_reached(g.fw_stamp[0].r32(0)?, f.ta_target, e.ta_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 fs_stamp = g.notifier.r32(notifier_page::FS_STAMP)?; + let ta_stamp = g.notifier.r32(notifier_page::TA_STAMP)?; + full &= 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) + && stamp_reached(ta_stamp, f.ta_target, e.ta_target) + && (ta_stamp != f.ta_target + || g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot) + && f.job + .resources + .render()? + .pools + .retired_at(a, f.uma_submitted)?; + } else { + // Check FS (terminal stage) before TA so running renders fail fast on 1 WC read. + if g.fw_stamp[1].r32(0)? != f.fs_target + || g.fw_stamp[0].r32(0)? != f.ta_target + || !self.queue_receipt( + Channel::Ta, + &g.qstate[0], + &g.qinfo[0], + f.ta_head, + f.rec[0], + )? + || !self.queue_receipt( + Channel::Fs, + &g.qstate[1], + &g.qinfo[1], + f.fs_head, + f.rec[1], + )? + { + return Ok(Retirement::Pending); + } + full &= g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target + && g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target + && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot + && 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 - || !self.queue_receipt( - Channel::Ta, - &g.qstate[0], - &g.qinfo[0], - f.ta_head, - f.rec[0], - )? - || !self.queue_receipt( - Channel::Fs, - &g.qstate[1], - &g.qinfo[1], - f.fs_head, - f.rec[1], - )? - { - return Ok(Retirement::Pending); + == f.job.vm.slot + && f.job.resources.render()?.pools.retired(a)?; } - 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)?; - if f.computes == 0 { - ticks = [ta_start, ta_end, fs_start, fs_end]; + if full { + 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)?; + if f.computes == 0 { + ticks = [ta_start, ta_end, fs_start, fs_end]; + } + full &= ta_start != 0 && ta_end > ta_start && fs_start != 0 && fs_end > fs_start; } - full &= g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target - && g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target - && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot - && g.notifier - .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? - == f.job.vm.slot - && f.job.resources.render()?.pools.retired(a)? - && ta_start != 0 - && ta_end > ta_start - && fs_start != 0 - && fs_end > fs_start; } if full { self.engine.retired_ticks = ticks; @@ -1271,18 +1294,28 @@ impl Firmware { return; } let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let (mut fc, mut fr) = (None, None); + for f in e.flights.iter() { + if fc.is_none() && f.computes != 0 { + fc = Some(f); + } + if fr.is_none() && f.renders != 0 { + fr = Some(f); + } + if fc.is_some() && fr.is_some() { + break; + } + } // None denotes an inactive/reached stage. A real unreached stamp may be zero // immediately after native wrap and must remain distinguishable from completion. let pending = |observed, own, tail| (!stamp_reached(observed, own, tail)).then_some(observed); let (mut c, mut ta, mut fs) = (None, None, None); let mut published = [0u64; 2]; - let fc = e.flights.iter().find(|f| f.computes != 0); if let Some(fc) = fc { c = pending(g.fw_stamp.r32(0).unwrap_or(0), fc.target, e.target); published[0] = fc.published_ns; } - let fr = e.flights.iter().find(|f| f.renders != 0); if let Some(fr) = fr { ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), fr.ta_target, e.ta_target); fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 2b6f5871abdc38..2dfd7de2a5337d 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -34,7 +34,7 @@ use kernel::{dma_fence::Fence, prelude::*, sync::Arc, uapi, xarray}; use super::{ command::{self, USC_WINDOW}, - fence::{Syncs, Timeline}, + fence::{InputFences, Syncs, Timeline}, hw, job::{Job, Scheduler}, params, @@ -219,13 +219,13 @@ impl Queue { })?; // Refused jobs add no accepted ordinals; check every prepared dependency before // publishing a fence or extending the queue's accepted frontier. - for order in &submission.orders { + for order in submission.orders.iter() { self.state.check(order)?; } - let mut inputs = KVec::with_capacity(syncs.inputs().len(), GFP_KERNEL)?; + let mut inputs = InputFences::new(); for sync in syncs.inputs() { if let Some(fence) = &sync.fence { - inputs.push(fence.clone(), GFP_KERNEL)?; + inputs.push(fence.clone())?; } } // Allocate and map private backing before a fence or accepted ordinal exists. 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 bfb6c793d55b3e..35d36e3587c43e 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 @@ -58,6 +58,7 @@ 'drm_asahi_timestamp', 'drm_asahi_timestamps', 'drm_asahi_helper_program', 'drm_asahi_render_ray_query_stage'] constants = command[command.index('/// Largest command buffer.'):command.index('/// A validated render command.')] +inline_containers = command[command.index('/// Inline storage for the common 1-2 command submission'):command.index('/// A validated SUBMIT.')] parser = command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] g17 = (ROOT / 'drivers/gpu/drm/asahi/g17/command.rs').read_text() # The stage-prefix offset and the render payload reader precede the parser. @@ -416,12 +417,107 @@ assert_eq!(result,Err(E2BIG)); assert_eq!(publications,0,"a rejected render must prevent the earlier compute publishing"); } +mod inline_submit_containers { + use super::{Order, Result, COMPUTE, NONE, RENDER}; + use std::cell::Cell; + + const ENOMEM: i32 = -12; + const GFP_KERNEL: u32 = 0; + + std::thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; + static FAIL_NEXT: Cell = const { Cell::new(false) }; + } + + pub(crate) mod timestamp { + #[derive(Debug, PartialEq, Eq)] + pub(crate) struct Destinations(pub(crate) u32); + } + + #[derive(Debug, PartialEq, Eq)] + pub(crate) struct Command(pub(crate) u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + ALLOCS.with(|a| a.set(a.get() + 1)); + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + fn get_mut(&mut self, idx: usize) -> Option<&mut T> { + self.0.get_mut(idx) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + + INLINE_CONTAINERS + + #[test] + fn inline_commands_orders_and_resolved_skip_heap_up_to_two_and_spill_safely() { + ALLOCS.with(|a| a.set(0)); + let mut cmds = Commands::new(); + let mut orders = Orders::new(); + let mut resolved = Resolved::new(); + let o0 = Order::new([0, 0], [0, 0], [NONE; 2], [0; 2], COMPUTE).unwrap(); + let o1 = Order::new([0, 0], [0, 1], [NONE; 2], [0; 2], RENDER).unwrap(); + let o2 = Order::new([0, 0], [1, 1], [NONE; 2], [0; 2], COMPUTE).unwrap(); + cmds.push(Command(1)).unwrap(); + cmds.push(Command(2)).unwrap(); + orders.push(o0).unwrap(); + orders.push(o1).unwrap(); + resolved.push(timestamp::Destinations(11)).unwrap(); + resolved.push(timestamp::Destinations(22)).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + assert_eq!(&*cmds, &[Command(1), Command(2)]); + assert_eq!(&*orders, &[o0, o1]); + + // OOM on 2 -> 3 spill preserves inline entries. + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(cmds.push(Command(3)), Err(ENOMEM)); + assert_eq!(&*cmds, &[Command(1), Command(2)]); + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(orders.push(o2), Err(ENOMEM)); + assert_eq!(&*orders, &[o0, o1]); + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(resolved.push(timestamp::Destinations(33)), Err(ENOMEM)); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + + // Spill to heap preserves exact FIFO order across all 3 containers. + cmds.push(Command(3)).unwrap(); + orders.push(o2).unwrap(); + resolved.push(timestamp::Destinations(33)).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 3); + assert_eq!(&*cmds, &[Command(1), Command(2), Command(3)]); + assert_eq!(&*orders, &[o0, o1, o2]); + assert_eq!(resolved.next(), Some(timestamp::Destinations(11))); + assert_eq!(resolved.next(), Some(timestamp::Destinations(22))); + assert_eq!(resolved.next(), Some(timestamp::Destinations(33))); + assert_eq!(resolved.next(), None); + } +} ''' replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), 'FW_WORK': str(SOURCE.parent/'fw/work.rs'), 'FULL_ENCODER': str(SOURCE.parent/'encode.rs'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), 'PRODUCTION_CONSTANTS': constants, 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} for key in sorted(replacements,key=len,reverse=True): harness = harness.replace(key,replacements[key]) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 15a62acd017406..0409bc0b4157d4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -88,6 +88,10 @@ def extract_function(text, name): line for line in fence_source.splitlines() if line.startswith('const SIGNAL_BATCH:') ][0] timeline_complete_fn = extract_function(fence_source, 'complete') +input_fences_src = fence_source[ + fence_source.index('/// Inline storage for the common 0-2 input fences'): + fence_source.index('/// Reads a retained dependency') +] timeline_harness = r''' #![allow(dead_code)] @@ -97,9 +101,74 @@ def extract_function(text, name): #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Error(i32); const EIO: Error = Error(-5); +const ENOMEM: Error = Error(-12); const ECANCELED: Error = Error(-125); +const GFP_KERNEL: u32 = 0; type Result = std::result::Result; +mod input_fences_test { + use super::{Result, ENOMEM, GFP_KERNEL}; + use std::cell::Cell; + + std::thread_local! { + static ALLOCS: Cell = const { Cell::new(0) }; + static FAIL_NEXT: Cell = const { Cell::new(false) }; + } + + #[derive(Clone, Debug, PartialEq, Eq)] + pub(crate) struct Fence(pub(crate) u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + ALLOCS.with(|a| a.set(a.get() + 1)); + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + if FAIL_NEXT.with(|f| f.replace(false)) { + return Err(ENOMEM); + } + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + + INPUT_FENCES_SRC + + #[test] + fn input_fences_inline_zero_to_two_and_spill_safely() { + ALLOCS.with(|a| a.set(0)); + let mut inputs = InputFences::new(); + assert_eq!(&*inputs, &[]); + inputs.push(Fence(10)).unwrap(); + assert_eq!(&*inputs, &[Fence(10)]); + inputs.push(Fence(20)).unwrap(); + assert_eq!(&*inputs, &[Fence(10), Fence(20)]); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + // OOM during 2 -> 3 spill preserves the 2 inline fences intact. + FAIL_NEXT.with(|f| f.set(true)); + assert_eq!(inputs.push(Fence(30)), Err(ENOMEM)); + assert_eq!(&*inputs, &[Fence(10), Fence(20)]); + assert_eq!(ALLOCS.with(|a| a.get()), 0); + // Spill succeeds with one allocation and keeps exact order. + inputs.push(Fence(30)).unwrap(); + inputs.push(Fence(40)).unwrap(); + assert_eq!(ALLOCS.with(|a| a.get()), 1); + assert_eq!(&*inputs, &[Fence(10), Fence(20), Fence(30), Fence(40)]); + } +} + struct Mutex(StdMutex); impl Mutex { fn new(v: T) -> Self { Self(StdMutex::new(v)) } @@ -245,7 +314,7 @@ def extract_function(text, name): } '''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( 'TIMELINE_COMPLETE_FN', timeline_complete_fn -) +).replace('INPUT_FENCES_SRC', input_fences_src) with tempfile.TemporaryDirectory(prefix='m4-rust-timeline-') as directory: directory = pathlib.Path(directory) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index b8466380197088..4a381034c3caa4 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -61,13 +61,23 @@ def item(declaration): fn lap(&mut self, _acc: &mut u64) {} } -struct Cell32(Cell); +struct Cell32 { + val: Cell, + reads: Cell, +} impl Cell32 { fn new(v: u32) -> Self { - Self(Cell::new(v)) + Self { + val: Cell::new(v), + reads: Cell::new(0), + } + } + fn set(&self, v: u32) { + self.val.set(v); } fn r32(&self, _off: usize) -> Result { - Ok(self.0.get()) + self.reads.set(self.reads.get() + 1); + Ok(self.val.get()) } } @@ -319,7 +329,7 @@ def item(declaration): fs_target: 0, }); fw.engine.target = 0x100; - fw.graph.compute.fw_stamp.0.set(0x100); + fw.graph.compute.fw_stamp.set(0x100); fw.retire_on_call = true; let mut done = vec![]; @@ -432,11 +442,46 @@ def item(declaration): fw.engine.fs_target = 0x200; fw.engine.target = 0x100; // Render still running, compute reached its stamp. - fw.graph.render.fw_stamp[1].0.set(0x100); - fw.graph.compute.fw_stamp.0.set(0x100); + fw.graph.render.fw_stamp[1].set(0x100); + fw.graph.compute.fw_stamp.set(0x100); assert!(fw.oldest_stamp_reached()); + assert_eq!(fw.graph.compute.fw_stamp.reads.get(), 1); + assert_eq!(fw.graph.render.fw_stamp[1].reads.get(), 0); assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); } + +#[test] +fn oldest_stamp_reached_skips_inactive_class_wc_reads() { + // Compute-only workload never reads render fw_stamp. + let mut fc = Firmware::new(); + fc.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fc.engine.target = 0x200; + fc.graph.compute.fw_stamp.set(0x100); + assert!(!fc.oldest_stamp_reached()); + assert_eq!(fc.graph.compute.fw_stamp.reads.get(), 1); + assert_eq!(fc.graph.render.fw_stamp[0].reads.get(), 0); + assert_eq!(fc.graph.render.fw_stamp[1].reads.get(), 0); + + // Render-only workload never reads compute fw_stamp. + let mut fr = Firmware::new(); + fr.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x200, + }); + fr.engine.fs_target = 0x200; + fr.graph.render.fw_stamp[1].set(0x100); + assert!(!fr.oldest_stamp_reached()); + assert_eq!(fr.graph.compute.fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); + assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); +} ''' for token, decl in { 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 ef21accd412542..774f0d01e1193d 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 @@ -21,18 +21,20 @@ def function(text, name): harness = r''' #![allow(dead_code)] +use std::cell::Cell; use std::collections::BTreeMap; #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EINVAL:Error=Error(-22);const EAGAIN:Error=Error(-11);type Result = std::result::Result; #[path="__LOGIC__"]mod logic; use logic::Retirement; mod encode { __STAMP_SEED__ __STAMP__ } -struct Object{cells:BTreeMap,va:u64,unstable:bool} -impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false}}} +struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} +impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} impl Object { - fn r32(&self,off:usize)->Result{Ok(*self.cells.get(&off).unwrap_or(&0) as u32)} - fn r64(&self,off:usize)->Result{if self.unstable{return Err(EAGAIN)}Ok(*self.cells.get(&off).unwrap_or(&0))} + fn r32(&self,off:usize)->Result{self.reads.set(self.reads.get()+1);Ok(*self.cells.get(&off).unwrap_or(&0) as u32)} + fn r64(&self,off:usize)->Result{self.reads.set(self.reads.get()+1);if self.unstable{return Err(EAGAIN)}Ok(*self.cells.get(&off).unwrap_or(&0))} fn set(&mut self,off:usize,v:u64){self.cells.insert(off,v);} + fn reset_reads(&self){self.reads.set(0);} } #[derive(Clone,Copy)]enum Channel{Compute,Ta,Fs} mod notifier_page {pub const COMPUTE_STAMP:usize=0;pub const COMPUTE_CONTEXT:usize=4;pub const TA_STAMP:usize=8;pub const FS_STAMP:usize=12;pub const FS_RECORD:usize=32;} @@ -65,6 +67,7 @@ def function(text, name): __RETIRED__ __RETIRED_AT__ __RETIRED_FLIGHT__ + __RETIRED_FLIGHT_CLASSES__ __RETIRED_SNAPSHOT__ __RETIRED_SNAPSHOT_AT__ } @@ -237,9 +240,61 @@ def function(text, name): f.engine.flights[0].job.resources.compute[2].its.set(8,130); assert_eq!(f.retired(),Ok(Retirement::Full)); } +#[test]fn inactive_class_and_unreached_stage_skip_wc_reads(){ + // Compute-only retirement performs zero render WC reads. + let mut fc=firmware(false,5); + assert_eq!(fc.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(fc.graph.render.fw_stamp[0].reads.get(),0); + assert_eq!(fc.graph.render.fw_stamp[1].reads.get(),0); + assert_eq!(fc.graph.render.notifier.reads.get(),0); + // Render-only retirement performs zero compute WC reads. + let mut fr=firmware(true,5); + assert_eq!(fr.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(fr.graph.compute.fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute.notifier.reads.get(),0); + // In-progress render (TA done, FS still running) fails fast on FS stamp without reading TA or scene. + let mut fp=firmware(true,7); + fp.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(6))); + assert_eq!(fp.retired_flight(),Ok(None)); + assert_eq!(fp.graph.render.fw_stamp[1].reads.get(),1); + assert_eq!(fp.graph.render.fw_stamp[0].reads.get(),0); + assert_eq!(fp.engine.flights[0].job.resources.passes[0].scene.reads.get(),0); + // Unsettled notifier skips scene WC timestamp reads. + fp.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(7))); + fp.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(6))); + assert_eq!(fp.retired_flight(),Ok(None)); + assert_eq!(fp.engine.flights[0].job.resources.passes[0].scene.reads.get(),0); + // Mixed flight pending is polled once, not twice. + let mut fm=firmware(false,9); + fm.engine.flights[0].renders=1; + fm.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(8))); + assert_eq!(fm.retired_flight(),Ok(None)); + assert_eq!(fm.graph.compute.fw_stamp.reads.get(),1); + assert_eq!(fm.graph.render.fw_stamp[1].reads.get(),0); + // Pending compute class is not re-polled while retiring a burst of render flights. + let mut fmix=firmware(false,30); + let r1=firmware(true,40).engine.flights.remove(0); + let r2=firmware(true,41).engine.flights.remove(0); + fmix.engine.flights.push(r1); + fmix.engine.flights.push(r2); + fmix.engine.ta_target=encode::stamp(41); + fmix.engine.fs_target=encode::stamp(41); + for stage in 0..2 { fmix.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(41))); } + fmix.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(41))); + fmix.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(41))); + fmix.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(29))); + let (mut check_c,mut check_r)=(true,true); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); + assert!(!check_c && check_r); + fmix.engine.flights.remove(1); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); + fmix.engine.flights.remove(1); + assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); + assert_eq!(fmix.graph.compute.fw_stamp.reads.get(),1); +} '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: harness=harness.replace(token,function((backend/path).read_text(),name)) unit=out/'stamp-wrap.rs';unit.write_text(harness) log='' From 634ee93a088694e0a187ceefa4b5c28f38c37dd7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:05:48 -0500 Subject: [PATCH 0834/1514] drm/asahi: g16: skip no-op publishes, batch event ring drains, and smooth receipt-tail backoff Reduce G16 completion-poll overhead while preserving per-CPU completion locality and the full post-event receipt-tail window: 1. Skip redundant `publish_checked()` walks in `Firmware::poll_step()` when flights are active and nothing changed (no retirement, no ring headroom wait, no recovery unfreeze, no off-lock scrub wakeup, no external `publish_wake`, and no 1 ms housekeeping tick). Add `Shared::publish_wake` / `Shared::wake_publish()` so external state transitions (VM close, unstarted queue cancellation) re-evaluate `engine.pending` immediately without waiting for the 1 ms tick; `Prepared::drop` only releases standby PB reservations for `Cache::prepare` waiters, whose woken `SUBMIT` enters `submit_locked()` directly. 2. Keep `aurora_g16_events` per-CPU (`new_percpu_reclaim`) and `EVENT_RETIRE_POLLS = 11`, smoothing the trailing receipt-poll backoff from `1/2/5 us` (~48 us) to `1/2/3/4/5 us` (45 us total) so post-EP 0x20 retirement finishes inline without falling back to the repoll timer. 3. Batch `Events::drain()` and `Events::drain_statistics()` ring advances: read only the active words of common type-1 stage events (3 WC reads vs 18) and non-recovery statistics records (1 WC read vs 18), and write `STATE_READ` once per drained burst (flushing partial progress on mid-burst errors). 4. Cache `recovery_pending()` once per `submit_locked()` / `poll_step()` pass and short-circuit `retire_once()` when `flights` is empty. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/event.rs | 101 +++++- drivers/gpu/drm/asahi/g16/job.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 14 + drivers/gpu/drm/asahi/g16/poll.rs | 44 ++- drivers/gpu/drm/asahi/g16/slots.rs | 14 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 1 + .../drivers/gpu/asahi-m4/test-poll-retire.py | 320 +++++++++++++++++- 7 files changed, 468 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index f4fd9b723b634b..6716d3332a539e 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -104,13 +104,46 @@ impl Events { // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; let mut error = None; + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - match words[0] { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + match kind { 1 => { + // Type 1 carries 128 completion bits across words 1..=4; STAGE_EVENTS + // ([0x70, 0x71, 15]) only inspects word 1 (compute 15) and word 4 (TA/FS). + let (w1, w4) = match ring.ring.r32(base + 4).and_then(|w1| { + Ok((w1, ring.ring.r32(base + 16)?)) + }) { + Ok(pair) => pair, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; for (stage, event) in STAGE_EVENTS.iter().enumerate() { - let word = 1 + *event as usize / 32; - if words[word] & (1u32 << (*event % 32)) == 0 { + let bits = match 1 + *event as usize / 32 { + 1 => w1, + 4 => w4, + _ => continue, + }; + if bits & (1u32 << (*event % 32)) == 0 { continue; } self.event_ns[stage] = now; @@ -123,6 +156,15 @@ impl Events { } } 4 => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; self.recovery_started_ns.get_or_insert(now); self.last_error = Some(ErrorEvent { kind: 4, @@ -133,6 +175,15 @@ impl Events { dev_warn!(dev, "M4 firmware recovery event: {:08x?}\n", words); } kind => { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // The qualified M4 provider accepts only stage and recovery events. // Do not apply another firmware's context-kill or PB-growth protocol. dev_err!( @@ -146,19 +197,46 @@ impl Events { } } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; error.map_or(Ok(()), Err) } /// Preserve recovery statistics instead of silently discarding their notification. pub(crate) fn drain_statistics(&mut self, dev: &device::Device, ring: &Ring) -> Result { let (mut read, producer) = Self::indices(ring)?; + if read == producer { + return Ok(()); + } + let mut drained = false; + let flush_read = |ring: &Ring, read: u32| -> Result { + mb(); + ring.state.w32(STATE_READ, read)?; + wmb(); + Ok(()) + }; while read != producer { - let words = Self::words(ring, read)?; - if words[0] == 0x16 { + let base = read as usize * rings::EVENT_RECORD; + let kind = match ring.ring.r32(base) { + Ok(kind) => kind, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; + if kind == 0x16 { + let words = match Self::words(ring, read) { + Ok(words) => words, + Err(err) => { + if drained { + let _ = flush_read(ring, read); + } + return Err(err); + } + }; // SAFETY: ktime_get has no preconditions. let now = unsafe { bindings::ktime_get() } as u64; self.recovery_started_ns.get_or_insert(now); @@ -167,10 +245,9 @@ impl Events { dev_warn!(dev, "M4 firmware recovery statistics: {:08x?}\n", words); } read = (read + 1) % RING_SLOTS; - mb(); - ring.state.w32(STATE_READ, read)?; - wmb(); + drained = true; } + flush_read(ring, read)?; Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 98dc58c951296c..1464f1151738f8 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -302,6 +302,7 @@ impl Job { // before signalling; later accepted ordinals must not jump this hole. self.queue.cancel(&self.orders, self.progress.sent()); self.finish(Err(ECANCELED), false); + shared.wake_publish(); return; } // `Shared::submit`: enqueue, publish and rearm under the device lock, diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 024acf667f1ac4..090e09312a55f1 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -212,6 +212,9 @@ 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, + /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next + /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. + pub(crate) publish_wake: 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. @@ -341,6 +344,15 @@ impl Shared { self.poll_now(); } + /// Marks external publish-relevant state dirty and queues a poll so pending jobs re-evaluate + /// without waiting for the 1 ms housekeeping tick. + pub(crate) fn wake_publish(self: &Arc) { + self.publish_wake.store(true, Ordering::Release); + if self.started.load(Ordering::Acquire) && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } + /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { let _ = @@ -481,6 +493,7 @@ impl Gpu { wedged_notified: AtomicBool::new(false), crashed: AtomicBool::new(false), evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), last_submit_ns: AtomicU64::new(0), wait_hint_streak: AtomicU32::new(0), @@ -731,6 +744,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); + self.shared.wake_publish(); } fn new_queue( diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index f00ee3ab3fbe1a..906fce855c7aa0 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -43,7 +43,7 @@ use crate::module_parameters; /// Cadence of periodic housekeeping (power governor, window health, administrative hang check). const HOUSEKEEPING_NS: u64 = 1_000_000; -/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/5 us, ~48 us total). +/// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/3/4/5 us, 45 us total). const EVENT_RETIRE_POLLS: u32 = 11; /// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). const BACKUP_REARM_NS: u64 = 2_000_000; @@ -158,6 +158,8 @@ impl Shared { let delay_us = match step { 0 => 1, 1 => 2, + 2 => 3, + 3 => 4, _ => 5, }; tail -= 1; @@ -215,7 +217,7 @@ impl Shared { pub_res = firmware.session.transport().and_then(|()| { let retired_any = firmware.retire_once(done)?; firmware.answer_growth()?; - if firmware.recovery.receipt_fault || firmware.recovery_pending()? { + if firmware.recovery.receipt_fault || recovery_pending { firmware.check_hangs(done)?; } if was_evented && !retired_any && !firmware.engine.flights.is_empty() { @@ -224,7 +226,7 @@ impl Shared { && firmware.oldest_terminal_events() == term_before && !firmware.oldest_stamp_reached() && !firmware.recovery.receipt_fault - && !firmware.recovery_pending().unwrap_or(true); + && !recovery_pending; if !non_terminal_only { self.evented.store(true, Ordering::Release); } @@ -464,6 +466,7 @@ impl Firmware { return Ok(false); } } + let was_frozen = self.engine.frozen; let stage_before = self.events.stage_events; let term_before = self.oldest_terminal_events(); let mut lap = Lap::start(); @@ -471,13 +474,35 @@ impl Firmware { let retired_any = self.retire_once(done)?; lap.lap(&mut self.engine.prof.retire_ns); self.answer_growth()?; - if self.recovery.receipt_fault || self.recovery_pending()? { + let recovery_pending = self.recovery.receipt_fault || self.recovery_pending()?; + if recovery_pending { self.check_hangs(done)?; } - let published = if self.engine.pending.is_empty() { - Ok(()) - } else { + let unfrozen = was_frozen && !self.engine.frozen; + let scrub_woke = self.slots.take_scrub_woke(); + let publish_woke = self + .engine + .shared + .as_ref() + .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + // Skip redundant `publish_checked()` walks on busy polls where nothing could have + // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for + // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), + // while `publish_woke` covers external state changes (VM close, unstarted queue + // cancellation) so pending jobs never wait on the 1 ms housekeeping tick. + let should_publish = !self.engine.pending.is_empty() + && (retired_any + || !had_flights + || self.engine.flights.is_empty() + || self.engine.chan_wait + || unfrozen + || scrub_woke + || publish_woke + || housekeeping_due); + let published = if should_publish { self.publish_checked(done) + } else { + Ok(()) }; if self.engine.flights.is_empty() { self.power.report_work(false); @@ -501,7 +526,7 @@ impl Firmware { && self.oldest_terminal_events() == term_before && !self.oldest_stamp_reached() && !self.recovery.receipt_fault - && !self.recovery_pending().unwrap_or(true); + && !recovery_pending; // 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 tail waits per interrupt. @@ -656,6 +681,9 @@ impl Firmware { if self.recovery.receipt_fault || self.recovery_pending()? { self.check_hangs(done)?; } + if self.engine.flights.is_empty() { + return Ok(false); + } let mut retired_any = false; let (mut check_compute, mut check_render) = (true, true); let mut ret = self.retired_flight_classes(&mut check_compute, &mut check_render); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 5e8e3c93d18b1a..e70c639be33704 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -457,6 +457,9 @@ struct ScrubState { clean_mask: AtomicU32, /// Set if slot selection found eligible slots blocked only by an in-flight off-lock scrub. waiter: AtomicBool, + /// Set when an off-lock scrub finished while `waiter` was pending so the next `poll_step()` + /// retries `publish_checked()` even if no flight retired. + woke: AtomicBool, /// Off-lock scrub counters folded into [`SlotStats`] on subsequent locked access. pass_scrubs: AtomicU64, tilemap_clear_bytes: AtomicU64, @@ -468,6 +471,7 @@ impl ScrubState { scrubbing: AtomicU32::new(0), clean_mask: AtomicU32::new(0), waiter: AtomicBool::new(false), + woke: AtomicBool::new(false), pass_scrubs: AtomicU64::new(0), tilemap_clear_bytes: AtomicU64::new(0), } @@ -527,7 +531,11 @@ impl PendingScrub { } self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); self.done = true; - self.state.waiter.swap(false, Ordering::SeqCst) + let woke = self.state.waiter.swap(false, Ordering::SeqCst); + if woke { + self.state.woke.store(true, Ordering::Release); + } + woke } } @@ -732,6 +740,10 @@ impl Slots { pub(crate) fn scrubbing_active(&self) -> bool { self.scrub.scrubbing.load(Ordering::Acquire) != 0 } + /// Consumes the wakeup flag set when an off-lock scrub unblocks a waiting render submitter. + pub(crate) fn take_scrub_woke(&self) -> bool { + self.scrub.woke.swap(false, Ordering::AcqRel) + } /// Total pass scrubs including completed off-lock pre-scrubs. pub(crate) fn pass_scrubs_total(&self) -> u64 { self.stats 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 a178d24d2288dd..d7058193d57395 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 @@ -109,6 +109,7 @@ def function(text, name): Arc::new(Self{crashed:AtomicBool::new(false),sleeping:AtomicBool::new(false),recovering:AtomicBool::new(false),contended:AtomicBool::new(false),submitted:Mutex::new(vec![]),submit_result:Ok(())}) } fn note_submitter(&self) {} + fn wake_publish(&self) {} fn submit(&self,job:Arc)->Result { self.submitted.lock().unwrap().push(job.id); self.submit_result } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 38a0e6112d8b00..2e3a44450f4b94 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -6,18 +6,25 @@ import subprocess production = kernel_root() / 'drivers/gpu/drm/asahi/g16/poll.rs' +event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() +mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() source = production.read_text() output = output_dir() +assert 'const EVENT_RETIRE_POLLS: u32 = 11;' in source, 'EVENT_RETIRE_POLLS expected to be 11' +assert ( + 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source +), 'aurora_g16_events must use new_percpu_reclaim(..., true)' -def item(declaration): - start = source.index(declaration) - at = source.index('{', start) + +def item(declaration, text=source): + start = text.index(declaration) + at = text.index('{', start) depth, end = 1, at + 1 while depth: - depth += (source[end] == '{') - (source[end] == '}') + depth += (text[end] == '{') - (text[end] == '}') end += 1 - return source[start:end] + return text[start:end] harness = r''' @@ -170,6 +177,7 @@ def item(declaration): struct Shared { sleeping: AtomicBool, evented: AtomicBool, + publish_wake: AtomicBool, rearmed: Cell, } impl Shared { @@ -177,6 +185,7 @@ def item(declaration): Arc::new(Self { sleeping: AtomicBool::new(false), evented: AtomicBool::new(false), + publish_wake: AtomicBool::new(false), rearmed: Cell::new(0), }) } @@ -199,6 +208,16 @@ def item(declaration): fn report_work(&mut self, _in_flight: bool) {} } +#[derive(Default)] +struct Slots { + scrub_woke: AtomicBool, +} +impl Slots { + fn take_scrub_woke(&self) -> bool { + self.scrub_woke.swap(false, Ordering::AcqRel) + } +} + struct Firmware { session: Session, objects: Objects, @@ -207,9 +226,11 @@ def item(declaration): events: Events, recovery: Recovery, power: Power, + slots: Slots, last_housekeeping_ns: u64, // Test script knobs for retire_once / publish / housekeeping observation. retire_on_call: bool, + unfreeze_on_hang_check: bool, drain_stage_delta: u32, drain_fs_delta: u32, drain_compute_delta: u32, @@ -248,8 +269,10 @@ def item(declaration): events: Events::default(), recovery: Recovery::default(), power: Power::default(), + slots: Slots::default(), last_housekeeping_ns: 0, retire_on_call: false, + unfreeze_on_hang_check: false, drain_stage_delta: 0, drain_fs_delta: 0, drain_compute_delta: 0, @@ -282,6 +305,10 @@ def item(declaration): Ok(()) } fn check_hangs(&mut self, _done: &mut Completions) -> Result { + if self.unfreeze_on_hang_check { + self.engine.frozen = false; + self.recovery.pending = false; + } Ok(()) } fn fail_stop(&mut self, error: Error, _done: &mut Completions) { @@ -484,6 +511,282 @@ def item(declaration): assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); } + +#[test] +fn poll_step_skips_publish_when_pending_blocked_and_nothing_retired() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.fs_target = 0x100; + fw.drain_stage_delta = 1; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Waking via scrub_woke triggers publish_checked once. + fw.slots.scrub_woke.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + + // Waking via chan_wait triggers publish_checked. + fw.engine.chan_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + fw.engine.chan_wait = false; + + // Waking via unfreeze triggers publish_checked. + fw.engine.frozen = true; + fw.recovery.pending = true; + fw.unfreeze_on_hang_check = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 3); + + // Waking via external publish_wake (e.g. VM close or unstarted queue cancel) triggers + // publish_checked once while flights remain active, then skips again on the next busy poll. + let shared = Shared::new(); + fw.engine.shared = Some(shared.clone()); + shared.publish_wake.store(true, Ordering::Release); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 4); + + // Waking via retirement triggers publish_checked (and returns false since flights drained). + fw.retire_on_call = true; + assert!(!fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 5); +} + +mod boot { + pub fn eproto() -> super::Error { + super::Error(-71) + } +} + +mod event_drain_test { + use super::{Error, Result}; + use std::cell::{Cell, RefCell}; + + const EIO: Error = Error(-5); + const STATE_READ: usize = 0; + const STATE_WRITE: usize = 0x40; + const RING_SLOTS: u32 = 128; + const RECORD_WORDS: usize = 18; + const STAGE_EVENTS: [u32; 3] = [0x70, 0x71, 15]; + mod rings { + pub const EVENT_RECORD: usize = 0x48; + } + mod bindings { + pub unsafe fn ktime_get() -> i64 { + 12345 + } + } + mod device { + pub struct Device; + } + macro_rules! dev_warn { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + macro_rules! dev_err { ($dev:expr, $($arg:tt)*) => {{ let _ = ($dev, format_args!($($arg)*)); }}; } + fn rmb() {} + fn wmb() {} + fn mb() {} + + struct Mem { + words: RefCell>, + reads: Cell, + writes: Cell, + fail_at_offset: Cell>, + } + impl Mem { + fn new(n_words: usize) -> Self { + Self { + words: RefCell::new(vec![0u32; n_words]), + reads: Cell::new(0), + writes: Cell::new(0), + fail_at_offset: Cell::new(None), + } + } + fn r32(&self, off: usize) -> Result { + self.reads.set(self.reads.get() + 1); + if self.fail_at_offset.get() == Some(off) { + return Err(EIO); + } + Ok(self.words.borrow()[off / 4]) + } + fn w32(&self, off: usize, val: u32) -> Result { + self.writes.set(self.writes.get() + 1); + self.words.borrow_mut()[off / 4] = val; + Ok(()) + } + } + + struct Ring { + state: Mem, + ring: Mem, + } + impl Ring { + fn new() -> Self { + Self { + state: Mem::new(0x40), + ring: Mem::new(RING_SLOTS as usize * RECORD_WORDS), + } + } + fn put_record(&self, slot: u32, words: &[u32]) { + let mut buf = self.ring.words.borrow_mut(); + let base = slot as usize * RECORD_WORDS; + for (i, &w) in words.iter().enumerate() { + buf[base + i] = w; + } + } + fn set_indices(&self, read: u32, write: u32) { + let mut st = self.state.words.borrow_mut(); + st[STATE_READ / 4] = read; + st[STATE_WRITE / 4] = write; + } + fn read_idx(&self) -> u32 { + self.state.words.borrow()[STATE_READ / 4] + } + } + + #[derive(Clone, Copy)] + struct ErrorEvent { + kind: u32, + slot: i32, + raw: [u32; RECORD_WORDS], + } + + #[derive(Default)] + struct Events { + stage_events: u32, + ta_events: u32, + fs_events: u32, + compute_events: u32, + event_ns: [u64; 3], + errors: u32, + channel_errors: u32, + recovery_started_ns: Option, + last_error: Option, + last_statistics: Option<[u32; RECORD_WORDS]>, + recovery_statistics: u32, + } + + impl Events { + fn indices(ring: &Ring) -> Result<(u32, u32)> { + let read = ring.state.r32(STATE_READ)?; + let producer = ring.state.r32(STATE_WRITE)?; + if read >= RING_SLOTS || producer >= RING_SLOTS { + return Err(EIO); + } + rmb(); + Ok((read, producer)) + } + fn words(ring: &Ring, slot: u32) -> Result<[u32; RECORD_WORDS]> { + let base = slot as usize * rings::EVENT_RECORD; + let mut out = [0u32; RECORD_WORDS]; + for (i, word) in out.iter_mut().enumerate() { + *word = ring.ring.r32(base + i * 4)?; + } + Ok(out) + } + __EVENT_DRAIN__ + __EVENT_DRAIN_STATS__ + } + + #[test] + fn event_drain_batches_state_read_and_minimizes_wc_reads() { + let ring = Ring::new(); + // 3 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), Compute (15 -> word 1 bit 15). + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 16; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 1; + r1[4] = 1 << 17; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 1; + r2[1] = 1 << 15; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.set_indices(0, 3); + + let mut ev = Events::default(); + ev.drain(&device::Device, &ring).unwrap(); + assert_eq!(ev.event_ns[0], 12345); + assert_eq!(ev.fs_events, 1); + assert_eq!(ev.compute_events, 1); + assert_eq!(ev.stage_events, 3); + assert_eq!(ring.read_idx(), 3); + // Exactly ONE STATE_READ write for all 3 records! + assert_eq!(ring.state.writes.get(), 1); + // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 9 reads (not 54)! + assert_eq!(ring.ring.reads.get(), 9); + } + + #[test] + fn event_drain_flushes_progress_on_mid_burst_error() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 1; + r0[4] = 1 << 17; + ring.put_record(0, &r0); + ring.set_indices(0, 2); + // Fail reading record 1's kind word. + ring.ring.fail_at_offset.set(Some(rings::EVENT_RECORD)); + let mut ev = Events::default(); + assert_eq!(ev.drain(&device::Device, &ring), Err(EIO)); + // Record 0 progress must still have been flushed to STATE_READ = 1. + assert_eq!(ring.read_idx(), 1); + assert_eq!(ring.state.writes.get(), 1); + assert_eq!(ev.fs_events, 1); + } + + #[test] + fn stats_drain_batches_state_read_and_reads_single_word_for_non_recovery() { + let ring = Ring::new(); + let mut r0 = [0u32; RECORD_WORDS]; + r0[0] = 0x10; + let mut r1 = [0u32; RECORD_WORDS]; + r1[0] = 0x11; + let mut r2 = [0u32; RECORD_WORDS]; + r2[0] = 0x16; + ring.put_record(0, &r0); + ring.put_record(1, &r1); + ring.put_record(2, &r2); + ring.set_indices(0, 3); + + let mut ev = Events::default(); + ev.drain_statistics(&device::Device, &ring).unwrap(); + assert_eq!(ev.recovery_statistics, 1); + assert!(ev.last_statistics.is_some()); + assert_eq!(ring.read_idx(), 3); + assert_eq!(ring.state.writes.get(), 1); + // 1 read each for r0, r1 + 1 (kind) + 18 (full words) for r2 = 21 reads (vs 54). + assert_eq!(ring.ring.reads.get(), 21); + } +} ''' for token, decl in { @@ -493,6 +796,11 @@ def item(declaration): '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', }.items(): harness = harness.replace(token, item(decl)) +for token, decl in { + '__EVENT_DRAIN__': 'pub(crate) fn drain(', + '__EVENT_DRAIN_STATS__': 'pub(crate) fn drain_statistics(', +}.items(): + harness = harness.replace(token, item(decl, event_source)) unit = output / 'poll-retire.rs' unit.write_text(harness) @@ -511,7 +819,7 @@ def item(declaration): json.dumps( { 'passed': True, - 'tests': 4, + 'tests': 10, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', From a11f4247807ed0c0f8de300c663cdc2fd5873e2c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:14:41 -0500 Subject: [PATCH 0835/1514] drm/asahi: g16: use stamp-only barriers for pipelined same-VM renders When pipelining a healthy same-VM non-InitBM render behind an in-flight render (class_behind), prefix_render() encoded both prev_barrier (TA->TA under early tiling or TA->FS otherwise) and fs_dep (FS->FS under early tiling) with BarrierType::Hold (type 1), holding each consecutive TA/FS stage for the predecessor software-job teardown even though own_barrier on the same FS ring already uses BarrierType::Stamp (type 0). Use BarrierType::from_stamp_only(!init_buffer) for both same-class render->render barriers (prev_barrier and fs_dep), matching own_barrier and G15's proven RENDER_INTERNAL_HOLD = 0 policy while keeping cross-engine barriers (fs2c and c2ta) strictly BarrierType::Hold on G16's class-2 queues. G16 uses firmware-initiated phase recovery and never writes G15 kill controls, and any failed/suspect/cross-VM/InitBM transition still drains the engine first. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 9 +++++++-- .../selftests/drivers/gpu/asahi-m4/test-publication.py | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 39eb2c252ba5dc..fc8488c706c00c 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1997,6 +1997,11 @@ impl Firmware { .is_some_and(|o| o.wait_through[super::command::RENDER].is_none()); let early = class_behind && params::early_tiling() && (frag_only || no_render_barrier); if class_behind { + // Pipelined same-VM non-InitBM render->render barriers wait on the producer's + // firmware stamp only (type 0), matching `own_barrier` and G15's + // `RENDER_INTERNAL_HOLD = 0`, so consecutive TA/FS stages hand off without a + // software-job hold bubble. Cross-engine barriers (`fs2c`/`c2ta`) stay `Hold`. + let render_bar = BarrierType::from_stamp_only(!init_buffer); let (wait_va, wait_stamp, wait_event) = if early { (r.fw_stamp[0].va, self.engine.ta_target, 0x70) } else { @@ -2008,7 +2013,7 @@ impl Firmware { wait_event, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.prev_barrier.write(0, &prev)?; r.ring[0].w64(8 * pf.ta_head as usize, p.prev_barrier.va)?; @@ -2020,7 +2025,7 @@ impl Firmware { 0x71, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.fs_dep.write(0, &dep)?; r.ring[1].w64(8 * pf.fs_head as usize, p.fs_dep.va)?; 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 3479b5265dbf7f..83a62c0979aa59 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -43,6 +43,14 @@ def item(declaration): flights_line = next(line for line in hw_src.splitlines() if 'const FLIGHTS:' in line) assert 'const COMPUTE_SLOTS: usize = COMPUTE_UNITS;' in hw_src assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src +prefix_render_fn = item('fn prefix_render(') +prefix_compute_fn = item('fn prefix_compute(') +assert 'let render_bar = BarrierType::from_stamp_only(!init_buffer);' in prefix_render_fn +assert prefix_render_fn.count('render_bar,') == 2, prefix_render_fn +assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn +assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('wait_compute'):prefix_render_fn.index('p.compute_barrier.write')] +assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] +assert 'BarrierType::Hold,' in prefix_compute_fn[prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write')] harness = r''' From 27a96a7cb80dfbf7b9961c7b8ce7edf0b2800d67 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 05:40:34 -0500 Subject: [PATCH 0836/1514] drm/asahi: g16: offload displaced render pass scrubbing to an unbound workqueue Move off-lock write-combining zeroing of displaced render pass slots out of `Shared::try_submit_inline()`, `Shared::submit()`, and `run_poll()` onto a dedicated unbound reclaim workqueue (`aurora_g16_scrub`): - Add a zero-allocation slot-indexed `ScrubQueue` protected by `Shared::scrub_queue` (`SpinLock`) and a `SCRUB_WORK` work item on `Shared::scrub_wq` so SUBMIT ioctls and completion polls never stall on WC fills. Drop the `scrub_queue` spinlock before `item.run_one()` and `poll_now()` so WC zeroing never runs under the spinlock. - Issue `wmb()` (`dsb st` on aarch64) after `PassSlot::scrub_clean()` completes and before clearing `tilemap_dirty` or publishing `clean_mask`, ordering scrubbed WC bytes globally before firmware or another CPU can claim and reuse the slot. - Preserve strict slot-reuse exclusion (`scrubbing` bitmask) and wake waiting render submitters via `poll_now()` immediately when a waited slot finishes scrubbing. - Guard async `clean_mask` publication with a monotonic `generation` counter incremented by `invalidate_scrub()` so a scrub staged before firmware recovery can never leave a stale clean bit afterward. - Drain `scrub_queue` and `scrub_wq` cleanly in `sleep.rs::join_workers()` after `sleeping` is set and `events` is drained so S2R and teardown never overlap workqueue draining with concurrent enqueues. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 28 +++++- drivers/gpu/drm/asahi/g16/poll.rs | 64 ++++++++++--- drivers/gpu/drm/asahi/g16/sleep.rs | 9 ++ drivers/gpu/drm/asahi/g16/slots.rs | 72 +++++++++++--- .../drivers/gpu/asahi-m4/test-resources.py | 93 +++++++++++++++++-- 5 files changed, 229 insertions(+), 37 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 090e09312a55f1..6be4c343beba11 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -81,9 +81,10 @@ use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU32, AtomicU64, use kernel::{ c_str, device::{self, Core}, - impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_work, of, platform, + impl_has_delayed_work, impl_has_work, new_delayed_work, new_mutex, new_spinlock, new_work, of, + platform, prelude::*, - sync::{aref::ARef, Arc, Mutex}, + sync::{aref::ARef, Arc, Mutex, SpinLock}, time::hrtimer::{ArcHrTimerHandle, HrTimer}, uapi, workqueue::{DelayedWork, OwnedQueue, Work, WorkItem}, @@ -191,6 +192,8 @@ 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; +/// Work item ID of the asynchronous displaced pass-slot scrub work. +const SCRUB_WORK: u64 = 2; /// 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; @@ -255,12 +258,18 @@ pub(crate) struct Shared { sleep_commit: AtomicPtr, /// Dedicated high-priority per-CPU workqueue for immediate completion polling. pub(crate) events: OwnedQueue, + /// Dedicated unbound workqueue for asynchronous off-lock pass-slot WC scrubbing. + pub(crate) scrub_wq: OwnedQueue, #[pin] pub(crate) orphan: Mutex>>, #[pin] pub(crate) poll: DelayedWork, #[pin] pub(crate) fast_poll: Work, + #[pin] + pub(crate) scrub_queue: SpinLock, + #[pin] + pub(crate) scrub_work: Work, // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it // cancels the expiry; see `Shared::rearm`). --- #[pin] @@ -280,6 +289,10 @@ impl_has_work! { impl HasWork for Shared { self.fast_poll } } +impl_has_work! { + impl HasWork for Shared { self.scrub_work } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -302,6 +315,13 @@ impl WorkItem for Shared { } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + this.run_scrubs(); + } +} + impl Shared { /// Records the submitting CPU and burst cadence for completion placement and wait hints. pub(crate) fn note_submitter(&self) { @@ -485,6 +505,7 @@ impl Gpu { // 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 scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -513,9 +534,12 @@ impl Gpu { sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, + scrub_wq, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), + scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), + scrub_work <- new_work!("g16::Shared::scrub_work"), resnap <- HrTimer::new(), resnap_handle <- new_mutex!(None, "g16::Shared::resnap_handle"), state <- new_mutex!(None, "g16::Shared::state"), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 906fce855c7aa0..e0019b9bab0d57 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -38,7 +38,7 @@ 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, FAST_POLL_WORK, POLL_WORK}; +use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK}; use crate::module_parameters; /// Cadence of periodic housekeeping (power governor, window health, administrative hang check). @@ -145,13 +145,13 @@ impl Shared { self.fail_stop(error); } } - let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); } job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); if !retry_tail { break; } @@ -275,13 +275,13 @@ impl Shared { let mut state = self.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; let res = self.submit_locked(firmware, job, &mut done); - let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); (res, firmware.slots.stage_and_take_scrubs(allow_stage)) }; job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); drop(signalling); self.notify_wedged(); accepted @@ -306,8 +306,9 @@ impl Shared { match state.as_deref_mut() { Some(firmware) => { let res = self.submit_locked(firmware, job, &mut done); - let allow_stage = - firmware.recovery.failed().is_none() && !firmware.engine.frozen; + let allow_stage = firmware.recovery.failed().is_none() + && !firmware.engine.frozen + && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); res } @@ -315,14 +316,49 @@ impl Shared { } }; job::complete_all(done); - if scrubs.run() { - self.poll_now(); - } + self.enqueue_scrubs(scrubs); drop(signalling); self.notify_wedged(); Some(accepted) } + /// Hands staged displaced pass scrubs to the dedicated unbound scrub workqueue so SUBMIT + /// and completion polling never stall on write-combining zeroing. + pub(crate) fn enqueue_scrubs(self: &Arc, batch: super::slots::ScrubBatch) { + if batch.is_empty() { + return; + } + let mut queue = self.scrub_queue.lock(); + if self.sleeping.load(Ordering::Acquire) { + drop(queue); + drop(batch); + return; + } + if queue.push_batch(batch) { + // Queue under `scrub_queue` so `sleep.rs::join_workers()` cannot overlap + // `scrub_wq.drain()` with a concurrent enqueue once `sleeping` is set. + let _ = self + .scrub_wq + .enqueue::, SCRUB_WORK>(self.clone()); + } + } + + /// Drains queued displaced pass scrubs on the dedicated unbound scrub workqueue. + pub(crate) fn run_scrubs(self: &Arc) { + loop { + let Some(mut item) = self.scrub_queue.lock().pop() else { + break; + }; + if self.sleeping.load(Ordering::Acquire) { + drop(item); + break; + } + if item.run_one() && !self.sleeping.load(Ordering::Acquire) { + self.poll_now(); + } + } + } + /// Deliver userspace notification outside the device mutex and fence completion path. fn notify_wedged(&self) { if self.wedged.load(Ordering::Acquire) && !self.wedged_notified.swap(true, Ordering::AcqRel) diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index ae23cc8e0dc56c..2f555c3af3fbef 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -114,6 +114,15 @@ impl Shared { drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } self.events.drain(); + // `sleeping` is already set, so taking the queued scrubs under `scrub_queue` + // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` + // while `scrub_wq.drain()` runs. Drop the drained batch outside the spinlock. + let pending_scrubs = { + let mut queue = self.scrub_queue.lock(); + core::mem::replace(&mut *queue, super::slots::ScrubQueue::new()) + }; + drop(pending_scrubs); + self.scrub_wq.drain(); } /// Waits for what's been published to retire. The poll work keeps running meanwhile. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index e70c639be33704..110af8019022ca 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -455,6 +455,9 @@ struct ScrubState { scrubbing: AtomicU32, /// Displaced pass slots whose clean same-VM spans were zeroed off-lock. clean_mask: AtomicU32, + /// Incremented by [`Self::clear_all_clean`] on recovery so an in-flight async scrub that + /// started before recovery can never publish a stale `clean_mask` bit afterwards. + generation: AtomicU64, /// Set if slot selection found eligible slots blocked only by an in-flight off-lock scrub. waiter: AtomicBool, /// Set when an off-lock scrub finished while `waiter` was pending so the next `poll_step()` @@ -470,6 +473,7 @@ impl ScrubState { Self { scrubbing: AtomicU32::new(0), clean_mask: AtomicU32::new(0), + generation: AtomicU64::new(0), waiter: AtomicBool::new(false), woke: AtomicBool::new(false), pass_scrubs: AtomicU64::new(0), @@ -495,7 +499,8 @@ impl ScrubState { } fn clear_all_clean(&self) { - self.clean_mask.store(0, Ordering::Release); + self.generation.fetch_add(1, Ordering::SeqCst); + self.clean_mask.store(0, Ordering::SeqCst); } } @@ -504,16 +509,21 @@ pub(crate) struct PendingScrub { slot: usize, arena: super::resources::PassOwnerArena, state: Arc, + generation: u64, done: bool, } impl PendingScrub { - fn run_one(&mut self) -> bool { + pub(crate) fn run_one(&mut self) -> bool { let bit = 1u32 << self.slot; - let ok = if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { + let ok = if self.state.generation.load(Ordering::Acquire) != self.generation { + false + } else if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { let dirty = tilemap_dirty.load(Ordering::Acquire); match pass.scrub_clean(1, dirty) { Ok(()) => { + // Order scrubbed WC bytes before clearing dirty / publishing clean_mask. + super::engine::wmb(); tilemap_dirty.store(0, Ordering::Release); self.state.pass_scrubs.fetch_add(1, Ordering::Relaxed); self.state @@ -526,8 +536,11 @@ impl PendingScrub { } else { false }; - if ok { - self.state.clean_mask.fetch_or(bit, Ordering::Release); + if ok && self.state.generation.load(Ordering::SeqCst) == self.generation { + self.state.clean_mask.fetch_or(bit, Ordering::SeqCst); + if self.state.generation.load(Ordering::SeqCst) != self.generation { + self.state.clean_mask.fetch_and(!bit, Ordering::SeqCst); + } } self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); self.done = true; @@ -562,6 +575,10 @@ impl ScrubBatch { } } + pub(crate) fn is_empty(&self) -> bool { + self.len == 0 + } + fn push(&mut self, item: PendingScrub) -> bool { if self.len >= sizes::RENDER_SLOTS { return false; @@ -570,16 +587,45 @@ impl ScrubBatch { self.len += 1; true } +} - /// Runs every staged off-lock pass scrub. Returns `true` if a waiting submitter needs wakeup. - pub(crate) fn run(mut self) -> bool { - let mut wake = false; - for slot in &mut self.items[..self.len] { - if let Some(mut item) = slot.take() { - wake |= item.run_one(); +/// Zero-allocation slot-indexed queue handed to the async pass-scrub workqueue. +/// +/// Each pass slot `0..sizes::RENDER_SLOTS` keeps its `scrubbing` bit set while a +/// [`PendingScrub`] is queued or running, so at most one entry per slot exists at once. +pub(crate) struct ScrubQueue { + slots: [Option; sizes::RENDER_SLOTS], +} + +impl ScrubQueue { + pub(crate) const fn new() -> Self { + Self { + slots: [const { None }; sizes::RENDER_SLOTS], + } + } + + /// Moves every staged scrub from `batch` into the queue. Returns `true` if any was queued. + pub(crate) fn push_batch(&mut self, mut batch: ScrubBatch) -> bool { + let mut pushed = false; + for slot in &mut batch.items[..batch.len] { + if let Some(item) = slot.take() { + let idx = item.slot; + self.slots[idx] = Some(item); + pushed = true; + } + } + batch.len = 0; + pushed + } + + /// Pops the next queued pass scrub, if any. + pub(crate) fn pop(&mut self) -> Option { + for slot in &mut self.slots { + if slot.is_some() { + return slot.take(); } } - wake + None } } @@ -786,10 +832,12 @@ impl Slots { continue; }; self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); + let generation = self.scrub.generation.load(Ordering::Acquire); let item = PendingScrub { slot: k, arena, state: self.scrub.clone(), + generation, done: false, }; if !self.render.staged.push(item) { 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 9806d05718bf26..0bf80de699bdfd 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -176,6 +176,14 @@ def module(text, name): __RENDER_BURST__ } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} + pub mod engine { + use core::sync::atomic::{AtomicU32, Ordering}; + pub static WMB_CALLS: AtomicU32 = AtomicU32::new(0); + pub fn wmb() { + WMB_CALLS.fetch_add(1, Ordering::SeqCst); + core::sync::atomic::fence(Ordering::SeqCst); + } + } // 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]>} @@ -193,6 +201,7 @@ def module(text, name): Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<bool{let mut q=g16::slots::ScrubQueue::new();q.push_batch(batch);let mut wake=false;while let Some(mut item)=q.pop(){wake|=item.run_one();}wake} #[test]fn render_reuse_clears_only_previous_write_spans(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); s.claim_pass(&arena.render,0).unwrap(); @@ -864,7 +873,7 @@ def module(text, name): s.retire(&mut c0).unwrap(); s.stage_displaced_pass_scrubs(); assert!(!s.scrubbing_active()); - assert!(!s.take_staged_scrubs().run()); + assert!(!drain_scrubs(s.take_staged_scrubs())); // Publish and retire slot 1: displaces slot 0, staging slot 0 for off-lock scrub. let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); @@ -877,7 +886,7 @@ def module(text, name): assert_eq!(s.pick_pass_in(&prep,&geo,0),None); assert_eq!(s.claim_pass_in(&prep,0,Some(a.id),0x4000),Err(EBUSY)); let batch=s.take_staged_scrubs(); - assert!(batch.run()); + assert!(drain_scrubs(batch)); assert!(!s.scrubbing_active()); assert!(render.passes[0].tilemap.snapshot()[..0x4000].iter().all(|&b|b==0)); assert!(render.passes[0].its.snapshot()[..32].iter().all(|&b|b==0)); @@ -916,7 +925,7 @@ def module(text, name): // Failed off-lock scrub preserves tilemap_dirty and falls back synchronously. s.stage_displaced_pass_scrubs(); render.passes[0].tilemap.fail_fill.store(true,std::sync::atomic::Ordering::Relaxed); - assert!(!s.take_staged_scrubs().run()); + assert!(!drain_scrubs(s.take_staged_scrubs())); assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0x2000); let fills_before=render.passes[0].tilemap.fills.lock().unwrap().len(); s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); @@ -929,7 +938,7 @@ def module(text, name): s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); - let _=s.take_staged_scrubs().run(); + let _=drain_scrubs(s.take_staged_scrubs()); s.invalidate_scrub(); s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); assert!(s.render_needs_full_work(0)); @@ -939,7 +948,7 @@ def module(text, name): s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); - let _=s.take_staged_scrubs().run(); + let _=drain_scrubs(s.take_staged_scrubs()); s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); assert!(s.render_needs_full_work(0)); } @@ -967,17 +976,17 @@ def module(text, name): assert!(s.pass_available(2)); assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); // Disallowed staging (fail-stop / frozen) stages nothing and clears pending flag. - assert!(!s.stage_and_take_scrubs(false).run()); + assert!(!drain_scrubs(s.stage_and_take_scrubs(false))); assert!(!s.scrubbing_active()); // Allowed staging after publication stages idle displaced slot 0 and scrubs it off-lock. s.note_render_retired(); let batch=s.stage_and_take_scrubs(true); assert!(s.scrubbing_active()); - assert!(!batch.run()); + assert!(!drain_scrubs(batch)); assert!(!s.scrubbing_active()); assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); // Calling stage_and_take_scrubs again without a new render retirement is a no-op. - assert!(!s.stage_and_take_scrubs(true).run()); + assert!(!drain_scrubs(s.stage_and_take_scrubs(true))); assert!(!s.scrubbing_active()); } #[test]fn multi_unit_compute_horizon_claims_publish_retire_and_release(){ @@ -1198,8 +1207,74 @@ def module(text, name): assert!(!s.render_exhausted_within(2)); } + #[test]fn async_scrub_queue_and_recovery_generation_guard(){ + use crate::g16::slots::ScrubQueue; + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + let render=sync::Arc::new(arena.render,0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let a=vm(1); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + // Prime and displace slot 0. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + render.set_dirty(0,0x1000,0x2000).unwrap(); + render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); + s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.retire(&mut c1).unwrap(); + + // Hand staged scrub off via ScrubQueue; waiter is woken on completion and woke flag is set. + s.stage_displaced_pass_scrubs(); + let batch=s.take_staged_scrubs(); + assert!(!batch.is_empty()); + let mut q=ScrubQueue::new(); + assert!(q.push_batch(batch)); + assert!(s.scrubbing_active()); + assert_eq!(s.pick_pass_in(&prep,&geo,0),None); + let mut item=q.pop().expect("queued scrub"); + assert!(q.pop().is_none()); + let wmb_before=g16::engine::WMB_CALLS.load(std::sync::atomic::Ordering::SeqCst); + assert!(item.run_one()); + assert!(g16::engine::WMB_CALLS.load(std::sync::atomic::Ordering::SeqCst)>wmb_before); + assert!(!s.scrubbing_active()); + assert!(s.take_scrub_woke()); + assert!(!s.take_scrub_woke()); + assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(!s.render_needs_full_work(0)); + + // Re-displace slot 0, stage scrub, then simulate recovery invalidate_scrub() BEFORE + // the async scrub runs: it must clear scrubbing without marking clean, so next claim + // performs a full scrub. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.stage_displaced_pass_scrubs(); + assert!(q.push_batch(s.take_staged_scrubs())); + assert!(s.scrubbing_active()); + s.invalidate_scrub(); + let mut stale=q.pop().expect("stale scrub"); + assert!(!stale.run_one()); + assert!(!s.scrubbing_active()); + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert!(s.render_needs_full_work(0)); + } + } ''' +poll_source = (production/'poll.rs').read_text() +mod_source = (production/'mod.rs').read_text() +sleep_source = (production/'sleep.rs').read_text() +assert 'scrubs.run()' not in poll_source, 'poll.rs must hand scrubs off asynchronously via enqueue_scrubs' +assert 'while let Some(mut item) = self.scrub_queue.lock().pop()' not in poll_source, 'run_scrubs must drop scrub_queue spinlock before run_one()' +assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' +assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source +assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' budget=(production/'budget.rs').read_text() budget=budget.replace('new_condvar, new_mutex,','').replace('#[pin_data]','').replace(' #[pin]\n','') constructor=item(budget,'pub(crate) fn new()') @@ -1247,7 +1322,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 32, + 'result': 'pass', 'tests': 33, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From b2c5f6a9a1061dad06cda872cb210b5e16f5a9c1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 03:10:45 -0500 Subject: [PATCH 0837/1514] drm/asahi: g16: support compressed ZLS depth and stencil attachments Wire the HAL200 compressed ZLS metadata registers (`fs::SEL[44..52]`) and the four `JobParameters3` partial-render mirrors (`0x958`, `0x970`, `0x988`, `0x9a0`) in `encode_fs_for()`, all of which lie inside the clean-reuse active work spans (`0..fs::HEAD_ACTIVE_SIZE` and `fs::TAIL_ACTIVE_START..fs::WORK_SIZE`). Widen `zls_ctrl` admission in `g16/command.rs` to admit the four load and store compression bits (`0x154`, mask `0x00000000060cc1fe`), enforce symmetric load/store compression bits per plane, remove the `EOPNOTSUPP` refusal on `comp_base`/`comp_stride`, and validate compressed metadata alignment, stride encoding, and read-write VM span coverage through the layer count via `SpanBatch`. Add host selftests covering 1x, 2x, and layered compressed depth/stencil admission, invalid control/alignment/span rejection, 25G83/26B123 FS encoding parity, and clean-reuse scrubbing of compressed ZLS fields. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 56 ++++-- drivers/gpu/drm/asahi/g16/encode/render.rs | 20 +- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 58 +++++- .../gpu/asahi-m4/test-command-stream.py | 171 ++++++++++++++++++ 4 files changed, 280 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index cce8a5b52b2057..33bcaa4f7feaa0 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -49,6 +49,7 @@ const SET_COMPUTE_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMP const MAX_DIMENSION: u16 = 16384; const MAX_LAYERS: u16 = 2048; const MAX_TILE_BUFFER: u32 = 32768; +const ZLS_METADATA_STRIDE: u64 = 0x80; /// Size of a queue's USC window. pub(crate) const USC_WINDOW: u64 = 1 << 32; @@ -694,28 +695,42 @@ fn compact(gva: u64) -> bool { (0x1000000000..0x9000000000).contains(&gva) } -/// Validate uncompressed Z/S register state and coverage through each layer base. -/// This is a minimum span check, not a complete plane-extent validation: the UAPI -/// does not describe the complete ZLS surface layout. The encoded stride is a -/// register word, not a byte distance (the C HAL200 contract). +/// Validate Z/S register state (including compressed metadata) and coverage through each layer +/// base. This is a minimum span check, not a complete plane-extent validation: the UAPI does +/// not describe the complete ZLS surface layout. The encoded stride is a register word, not a +/// byte distance (the C HAL200 contract). fn check_zls_plane( batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render, stencil: bool, ) -> Result { - let (z, mask) = if stencil { - (&cmd.stencil, (1u64 << 3) | (1 << 7) | (1 << 14) | (1 << 18)) + let (z, mask, comp_mask) = if stencil { + ( + &cmd.stencil, + (1u64 << 3) | (1 << 4) | (1 << 7) | (1 << 8) | (1 << 14) | (1 << 18), + (1u64 << 4) | (1 << 8), + ) } else { ( &cmd.depth, - (1u64 << 1) | (1 << 5) | (1 << 15) | (1 << 19) | (3 << 25), + (1u64 << 1) | (1 << 2) | (1 << 5) | (1 << 6) | (1 << 15) | (1 << 19) | (3 << 25), + (1u64 << 2) | (1 << 6), ) }; - if (z.base == 0 && (z.stride != 0 || cmd.zls_ctrl & mask != 0)) + let compressed = cmd.zls_ctrl & comp_mask != 0; + if (z.base == 0 + && (z.stride != 0 + || z.comp_base != 0 + || z.comp_stride != 0 + || cmd.zls_ctrl & mask != 0)) || (z.base != 0 && cmd.layers > 1 && z.stride == 0) || (z.stride != 0 && z.stride & 0x3fff != 1) || z.base & 3 != 0 + || (z.comp_base == 0 && z.comp_stride != 0) + || (z.comp_base != 0) != compressed + || z.comp_base & 3 != 0 + || z.comp_stride & 0x3fff != 0 { return Err(EINVAL); } @@ -733,6 +748,20 @@ fn check_zls_plane( true, )?; } + if z.comp_base != 0 { + let distance = (u64::from(z.comp_stride >> 14) + 1) * ZLS_METADATA_STRIDE; + let minimum = distance + .checked_mul(u64::from(cmd.layers - 1)) + .and_then(|bytes| bytes.checked_add(1)) + .ok_or(EINVAL)?; + batch.push( + context.vm, + z.comp_base, + z.comp_base.checked_add(minimum).ok_or(EINVAL)?, + true, + true, + )?; + } if cmd.depth.base == 0 && cmd.stencil.base == 0 && (cmd.zls_ctrl != 0 || cmd.isp_zls_pixels != 0) @@ -774,21 +803,16 @@ fn check_render( || cmd.sampler_heap != 0 || cmd.sampler_count != 0 || cmd.ppp_ctrl & !0x203 != 0 - || cmd.zls_ctrl & !0x00000000060cc0aa != 0 + || cmd.zls_ctrl & !0x00000000060cc1fe != 0 || cmd.isp_zls_pixels & 0xc0000000 != 0 || !matches!((cmd.zls_ctrl >> 25) & 3, 0 | 2) || ((cmd.zls_ctrl >> 1) & 1) != ((cmd.zls_ctrl >> 5) & 1) + || ((cmd.zls_ctrl >> 2) & 1) != ((cmd.zls_ctrl >> 6) & 1) || ((cmd.zls_ctrl >> 3) & 1) != ((cmd.zls_ctrl >> 7) & 1) + || ((cmd.zls_ctrl >> 4) & 1) != ((cmd.zls_ctrl >> 8) & 1) { return Err(EINVAL); } - if cmd.stencil.comp_base != 0 - || cmd.stencil.comp_stride != 0 - || cmd.depth.comp_base != 0 - || cmd.depth.comp_stride != 0 - { - return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); - } // VDM: compact-addressable and readable; scissor: four-byte aligned. let vdm = cmd.vdm_ctrl_stream_base; let scissor = cmd.isp_scissor_base; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 2ebe9f2e5ed50f..f84571dcbe987e 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -402,14 +402,14 @@ pub(crate) fn encode_fs_for( u64::from(u.depth.stride), u64::from(u.stencil.stride), u64::from(u.stencil.stride), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), p.tilemap_gva, geo.layer_metadata, u64::from(geo.region_stride) << 26, @@ -476,12 +476,16 @@ pub(crate) fn encode_fs_for( put64(w, 0x940, 0x04040404); put64(w, 0x948, u.depth.base); put64(w, 0x950, u64::from(u.depth.stride)); + put64(w, 0x958, u64::from(u.depth.comp_stride)); put64(w, 0x960, u.depth.base); put64(w, 0x968, u.depth.base); + put64(w, 0x970, u.depth.comp_base); put64(w, 0x978, u.stencil.base); put64(w, 0x980, u64::from(u.stencil.stride)); + put64(w, 0x988, u64::from(u.stencil.comp_stride)); put64(w, 0x990, u.stencil.base); put64(w, 0x998, u.stencil.base); + put64(w, 0x9a0, u.stencil.comp_base); put64(w, 0x9b8, u64::from(geo.tilebuffer_control)); put64(w, 0x9c0, u64::from(geo.isp_control)); put64( 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 f8421689ef133e..4809b1d85de46b 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 @@ -109,7 +109,17 @@ fn render(out: &std::path::Path) { 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.zls_ctrl = (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) + | (1 << 5) | (1 << 6) | (1 << 7) | (1 << 8) + | (1 << 14) | (1 << 15) | (1 << 18) | (1 << 19); + u.depth.base = g + 0xe00000; + u.depth.stride = (2 << 14) | 1; + u.depth.comp_base = g + 0xe80000; + u.depth.comp_stride = 3 << 14; + u.stencil.base = g + 0xf00000; + u.stencil.stride = (1 << 14) | 1; + u.stencil.comp_base = g + 0xf80000; + u.stencil.comp_stride = 2 << 14; u.bg.usc = 0x10000; u.eot.usc = 0x20000; let r = encode::RenderRefs { notifier: f + 0x800000, qinfo: [f + 0xf00000, f + 0x1000000], @@ -159,6 +169,52 @@ fn render(out: &std::path::Path) { // 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)); + // Compressed ZLS register records (fs::SEL[44..52]) and JobParameters3 mirrors. + let expected_zls_regs = [ + (44, 0x153c1u32, u.depth.comp_base), + (45, 0x15411, u64::from(u.depth.comp_stride)), + (46, 0x153c9, u.depth.comp_base), + (47, 0x15431, u64::from(u.depth.comp_stride)), + (48, 0x153d1, u.stencil.comp_base), + (49, 0x15419, u64::from(u.stencil.comp_stride)), + (50, 0x153d9, u.stencil.comp_base), + (51, 0x15439, u64::from(u.stencil.comp_stride)), + ]; + for (_, _, fw_img, _) in &images { + for &(slot, sel, val) in &expected_zls_regs { + let at = fs::REGS + slot * 12; + assert_eq!(r32(fw_img, at), sel); + assert_eq!(r64(fw_img, at + 4), val); + } + assert_eq!(r64(fw_img, 0x938), u.zls_ctrl); + assert_eq!(r64(fw_img, 0x958), u64::from(u.depth.comp_stride)); + assert_eq!(r64(fw_img, 0x970), u.depth.comp_base); + assert_eq!(r64(fw_img, 0x988), u64::from(u.stencil.comp_stride)); + assert_eq!(r64(fw_img, 0x9a0), u.stencil.comp_base); + } + // Clean same-VM reuse overwrites only 0..HEAD_ACTIVE_SIZE and TAIL_ACTIVE_START..WORK_SIZE; + // verify an uncompressed pass leaves no stale compressed ZLS register or mirror values. + let mut plain = u; + plain.zls_ctrl = 0; + plain.depth = Default::default(); + plain.stencil = Default::default(); + let mut plain_fw = [0xa5; fs::WORK_SIZE]; + let mut plain_fq = [0xa5; fs::SEQ_SIZE]; + encode::encode_fs_for( + &fs::V26B123, &r, &p, &plain, &ts, 7, 1 << 40, 2, 0x400, &geo, + &mut plain_fw, &mut plain_fq, + ); + let mut reused = *fw_; + reused[..fs::HEAD_ACTIVE_SIZE].copy_from_slice(&plain_fw[..fs::HEAD_ACTIVE_SIZE]); + reused[fs::TAIL_ACTIVE_START..].copy_from_slice(&plain_fw[fs::TAIL_ACTIVE_START..]); + for &(slot, sel, _) in &expected_zls_regs { + let at = fs::REGS + slot * 12; + assert_eq!(r32(&reused, at), sel); + assert_eq!(r64(&reused, at + 4), 0); + } + for off in [0x938usize, 0x958, 0x970, 0x988, 0x9a0] { + assert_eq!(r64(&reused, off), 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(); 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 35d36e3587c43e..4d9c4a50b88ce6 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 @@ -60,6 +60,10 @@ constants = command[command.index('/// Largest command buffer.'):command.index('/// A validated render command.')] inline_containers = command[command.index('/// Inline storage for the common 1-2 command submission'):command.index('/// A validated SUBMIT.')] parser = command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] +render_admission = ( + command[command.index('/// Checks that `[start, end)`'):command.index('/// Parses the attachment list')] + + command[command.index('/// Whether a GVA can be named by a 32-bit compact pointer.'):command.index('/// Per-command compute admission.')] +) g17 = (ROOT / 'drivers/gpu/drm/asahi/g17/command.rs').read_text() # The stage-prefix offset and the render payload reader precede the parser. g17_parser = g17[g17.index('/// Where a render command\'s stage-prefix fields start'):g17.index('#[derive(Clone, Copy, PartialEq, Eq)]')] @@ -511,6 +515,172 @@ assert_eq!(resolved.next(), None); } } +mod render_admission_tests { + use super::{ + check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FRAGMENT_BARRIERS, + MAX_DIMENSION, MAX_LAYERS, MAX_TILE_BUFFER, PROCESS_EMPTY_TILES, RSRC_SPEC_HI, + ZLS_METADATA_STRIDE, + }; + const ENOENT: i32 = -2; + const EACCES: i32 = -13; + + pub(crate) mod vm { + pub(crate) fn reserved_ranges() -> &'static [core::ops::Range] { + &[] + } + } + pub(crate) mod params { + pub(crate) fn early_tiling() -> bool { true } + } + pub(crate) mod gate { + use super::{mmu, Result}; + pub(crate) fn vdm(_vm: &mmu::Vm, _va: u64) -> Result { Ok(()) } + } + pub(crate) mod mmu { + pub(crate) const UAT_PGMSK: usize = 0x3fff; + pub(crate) struct Vm { + pub(crate) maps: Vec<(u64, u64, bool, bool)>, + } + impl Vm { + pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { + let Some(end) = start.checked_add(size) else { return false }; + self.maps.iter().any(|&(s, e, r, w)| { + start >= s && end <= e && (!read || r) && (!write || w) + }) + } + pub(crate) fn covers_ranges_batch(&self, ranges: &[(u64, u64, u8)]) -> (bool, usize) { + for (i, &(start, size, acc)) in ranges.iter().enumerate() { + if !self.covers_range(start, size, acc & 1 != 0, acc & 2 != 0) { + return (false, i); + } + } + (true, ranges.len()) + } + } + } + pub(crate) struct Context<'a> { + pub(crate) vm: &'a mmu::Vm, + pub(crate) usc_base: u64, + } + RENDER_ADMISSION + + const BASE_GVA: u64 = 0x10_0000_0000; + fn base_vm() -> mmu::Vm { + mmu::Vm { + maps: vec![ + (BASE_GVA, BASE_GVA + 0x10_0000, true, false), + (BASE_GVA + 0x20_0000, BASE_GVA + 0x40_0000, true, true), + (BASE_GVA + 0x50_0000, BASE_GVA + 0x51_0000, true, false), + ], + } + } + fn base_cmd() -> uapi::drm_asahi_cmd_render { + uapi::drm_asahi_cmd_render { + width_px: 64, + height_px: 64, + layers: 1, + samples: 1, + utile_width_px: 32, + utile_height_px: 32, + sample_size_B: 8, + vdm_ctrl_stream_base: BASE_GVA, + isp_scissor_base: BASE_GVA + 0x100, + ..Default::default() + } + } + const Z_COMP: u64 = (1 << 1) | (1 << 2) | (1 << 5) | (1 << 6) | (1 << 15) | (1 << 19); + const S_COMP: u64 = (1 << 3) | (1 << 4) | (1 << 7) | (1 << 8) | (1 << 14) | (1 << 18); + + #[test] + fn compressed_zls_1x_layered_and_2x_accepted() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + // 1x compressed D32F depth + stencil. + let mut cmd = base_cmd(); + cmd.zls_ctrl = Z_COMP | S_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000; + cmd.stencil.base = BASE_GVA + 0x28_0000; + cmd.stencil.comp_base = BASE_GVA + 0x2c_0000; + assert_eq!(check_render(&ctx, &cmd, &[], &[]), Ok(())); + // 1x compressed D16 depth (Z Format = 2 at bits 25..26). + let mut d16 = base_cmd(); + d16.zls_ctrl = Z_COMP | (2 << 25); + d16.depth.base = BASE_GVA + 0x20_0000; + d16.depth.comp_base = BASE_GVA + 0x24_0000; + assert_eq!(check_render(&ctx, &d16, &[], &[]), Ok(())); + // 2x MSAA compressed depth. + let mut msaa2 = d16; + msaa2.samples = 2; + assert_eq!(check_render(&ctx, &msaa2, &[], &[]), Ok(())); + // Layered compressed depth/stencil with comp_stride == 0 (1 line = 0x80) and nonzero stride. + let mut layered = cmd; + layered.layers = 4; + layered.depth.stride = (1 << 14) | 1; + layered.stencil.stride = (1 << 14) | 1; + assert_eq!(check_render(&ctx, &layered, &[], &[]), Ok(())); + layered.depth.comp_stride = 3 << 14; + layered.stencil.comp_stride = 2 << 14; + assert_eq!(check_render(&ctx, &layered, &[], &[]), Ok(())); + } + + #[test] + fn compressed_zls_invalid_ctrl_alignment_and_vm_spans_rejected() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let valid = || { + let mut cmd = base_cmd(); + cmd.zls_ctrl = Z_COMP | S_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000; + cmd.stencil.base = BASE_GVA + 0x28_0000; + cmd.stencil.comp_base = BASE_GVA + 0x2c_0000; + cmd + }; + // Asymmetric compress bits per plane. + for bit in [1u64 << 2, 1 << 6, 1 << 4, 1 << 8] { + let mut bad = valid(); + bad.zls_ctrl ^= bit; + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + } + // Unaligned comp_stride or comp_base. + for bad_stride in [1u32, 0x4001, 0x3fff] { + let mut bad = valid(); + bad.depth.comp_stride = bad_stride; + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + } + let mut bad = valid(); + bad.depth.comp_base += 2; + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + // comp_base without compress bits, compress bits without comp_base, stride without base. + let mut bad = valid(); + bad.zls_ctrl &= !((1 << 2) | (1 << 6)); + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + let mut bad = valid(); + bad.depth.comp_base = 0; + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + let mut bad = valid(); + bad.zls_ctrl = Z_COMP; + bad.stencil = Default::default(); + bad.stencil.comp_stride = 1 << 14; + assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + // Unmapped comp_base -> ENOENT; read-only comp_base -> EACCES. + let mut unmapped = valid(); + unmapped.depth.comp_base = BASE_GVA + 0x60_0000; + assert_eq!(check_render(&ctx, &unmapped, &[], &[]), Err(ENOENT)); + let mut ro = valid(); + ro.depth.comp_base = BASE_GVA + 0x50_0000; + assert_eq!(check_render(&ctx, &ro, &[], &[]), Err(EACCES)); + // Layered metadata span extending past mapped range -> ENOENT. + let mut past_end = valid(); + past_end.layers = 4; + past_end.depth.stride = 1; + past_end.stencil.stride = 1; + past_end.depth.comp_base = BASE_GVA + 0x3f_c000; + past_end.depth.comp_stride = 0x100 << 14; + assert_eq!(check_render(&ctx, &past_end, &[], &[]), Err(ENOENT)); + } +} ''' replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), @@ -518,6 +688,7 @@ 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), 'PRODUCTION_CONSTANTS': constants, 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), + 'RENDER_ADMISSION': render_admission.replace('super::vm::', 'vm::').replace('super::params::', 'params::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} for key in sorted(replacements,key=len,reverse=True): harness = harness.replace(key,replacements[key]) From 1d446f255c275a09000b6c499fbeb4ecda51af6e Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:12:09 -0500 Subject: [PATCH 0838/1514] drm/asahi: g16: expand render pass slots to 32 in demand-grown tiers and compute units to 18 Eliminate the 15-flight displacement cap at queue depth 16 and 32 for both render and compute on G16 without imposing a 107.8 MiB per-VM memory jump on compositors or shallow desktop VMs: - Pack lazy extension render pass slots (`2..32`) at an 8 MiB VA stride (`EXT_PASS_STRIDE = 0x00800000`, tilemap at `+0x600000`) starting at `0x7024000000`, while keeping base slots `0..2` at their full 32 MiB intervals (`16 MiB` TPC / `8 MiB` tilemap). All 32 pass slots occupy `0x7020000000..0x7033000000` (208 MiB spare below `0x7040000000`), raising `render_flights()` from 15 to 31. - Tie both `RENDER_SLOTS = 32` and `COMPUTE_UNITS = 18` explicitly to firmware's own ring, UMA, channel, and recovery capacities (enforced with compile-time assertions against `QUEUE_CAP`): - Work rings (`QUEUE_CAP = 256` entries, 255 usable): at most 4 entries/pass on TA (`prev_barrier`, `ta_fs_barrier`, `compute_barrier`, `ta_work`) and FS (`fs_dep`, `fs_compute_barrier`, `own_barrier`, `fs_work`), so 31 concurrent renders use <= 124/255 entries (49%); at most 2 entries/compute (`fs2c` barrier + `work`), so 17 concurrent computes use <= 34/255 entries (13%). - Channel rings (`RING_SLOTS = 256`, `AHEAD_RECORDS = 128`): bounded by `FLIGHTS = 32` `SubmitRecord`s (25% of `AHEAD_RECORDS`). - Hardware UMA slots: compute units own `COMPUTE_UMA_SLOT + 0..18` (`1..19`, within `RENDER_UMA_SLOT = 33`), while all renders share `RENDER_UMA_SLOT = 33` through the active PB/UMA descriptor. - Recovery affected-work snapshot: `snapshot_entries = 448` in `initdata.rs`, far above `31 + 17 = 48` max in-flight commands. - Grow extension pass slots in three demand-grown `RenderExtArena` tiers (`EXT_RENDER_TIERS = [(2, 8), (8, 18), (18, 32)]`) sized against live render pass count (`active_render_passes + render_count + 1`). Each base slot backs 24.59 MiB (25,184 KiB: 16 MiB TPC + 8 MiB tilemap + 608 KiB metadata/scratch/barriers) and each extension slot backs 3.59 MiB (3,680 KiB: 2 MiB TPC + 1 MiB tilemap + 608 KiB): - Base only (`0..2`, steady 60/120 Hz single-pass): 49.19 MiB pass backing (0 MiB ext). - Tier 0 (`2..8`, +6 slots, compositors / 2-pass / shallow depth): +21.56 MiB ext (80% less than eager 30-slot allocation). - Tier 1 (`8..18`, +10 slots, moderate multi-pass bursts): +35.94 MiB (+57.50 MiB cum ext). - Tier 2 (`18..32`, +14 slots, deep multi-pass bursts): +50.31 MiB (+107.81 MiB cum ext). - Fix `PASS_MASK` in `g16/slots.rs` to `u32::MAX >> (32 - RENDER_SLOTS)` so `RENDER_SLOTS = 32` does not overflow `1u32 << 32`, and raise `MAX_CLIENT` from 320 to 512 for headroom. - Expand `COMPUTE_UNITS` from 16 to 18 (17 concurrent compute flights, covering `d=16` without displacement stalls), fitting directly inside the existing 64 MiB VA layout (`compute_base(18) == PB_HEAP`), and simplify `params::compute_units()` with a compile-time `COMPUTE_UNITS >= 2` assertion in `g16/hw.rs`. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/hw.rs | 82 +++++-- drivers/gpu/drm/asahi/g16/params.rs | 2 +- drivers/gpu/drm/asahi/g16/resources.rs | 217 +++++++++++++----- drivers/gpu/drm/asahi/g16/slots.rs | 35 ++- .../drivers/gpu/asahi-m4/test-resources.py | 161 +++++++++---- 5 files changed, 353 insertions(+), 144 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 684d96df83bdc4..392bc7cbac1468 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -640,17 +640,23 @@ pub(crate) mod client { pub(crate) const PB_PAGE_LIST: u64 = 0x7012040000; pub(crate) const PB_PAGE_LIST_SIZE: u64 = 0x8000; - // Host-chosen client VA layout for render pass slots within 0x7020000000..0x7040000000 - // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than - // indexing by stride. One pass slot spans +0x0..+0x1c00000 (28 MiB: TILEMAP at +0x1400000 - // plus TILEMAP_SIZE = 0x800000), rounded up to a 32 MiB power-of-two stride (4 MiB guard) - // so 16 slots fill the 512 MiB window (matching COMPUTE_UNITS = 16). + // Host-chosen client VA layout for render pass resources within 0x7020000000..0x7040000000 + // (512 MiB). Firmware takes explicit 64-bit VAs for each pass object rather than indexing + // by stride: + // - Base slots `0..BASE_RENDER_SLOTS` keep 32 MiB intervals with full 16 MiB TPC / 8 MiB + // tilemap capacity for worst-case geometries. + // - Extension slots `BASE_RENDER_SLOTS..RENDER_SLOTS` pack into 8 MiB intervals starting at + // `EXT_PASS_BASE` (`0x7024000000`) with 2 MiB TPC / 1 MiB tilemap capacity, fitting 32 + // total pass slots (`0x7020000000..0x7033000000`, leaving 208 MiB free below 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 = 0x02000000; pub(crate) const PASS_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_PASS_STRIDE: u64 = 0x00800000; + pub(crate) const EXT_PASS_BASE: u64 = + FS_WORK_PAGE + (super::sizes::BASE_RENDER_SLOTS as u64) * PASS_STRIDE; pub(crate) const PRE0_PAGE: u64 = 0x7020080000; pub(crate) const PRE1_PAGE: u64 = 0x70200a0000; pub(crate) const PRE2_PAGE: u64 = 0x70200c0000; @@ -669,6 +675,27 @@ pub(crate) mod client { pub(crate) const TPC_SLOT_SIZE: u64 = 0x200000; pub(crate) const TILEMAP_SLOT_SIZE: u64 = 0x100000; pub(crate) const TPC_SLOT_STRIDE: u64 = WORK_STRIDE; + pub(crate) const EXT_TILEMAP_OFF: u64 = (TPC - FS_WORK_PAGE) + TPC_SLOT_SIZE; + + pub(crate) const fn pass_base(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + FS_WORK_PAGE + i * PASS_STRIDE + } else { + EXT_PASS_BASE + (i - super::sizes::BASE_RENDER_SLOTS as u64) * EXT_PASS_STRIDE + } + } + + pub(crate) const fn pass_off(i: u64) -> u64 { + pass_base(i) - FS_WORK_PAGE + } + + pub(crate) const fn pass_tilemap(i: u64) -> u64 { + if i < super::sizes::BASE_RENDER_SLOTS as u64 { + TILEMAP + i * PASS_STRIDE + } else { + pass_base(i) + EXT_TILEMAP_OFF + } + } pub(crate) const CT: u64 = 0x7080000000; pub(crate) const CT_STRIDE: u64 = 0x1000000; pub(crate) const CT_SIZE: u64 = 0x400000; @@ -695,12 +722,27 @@ pub(crate) mod sizes { assert!(super::client::render_descriptor(3) + 0x4000 <= super::client::FS_WORK_PAGE); const _: () = assert!(super::client::render_descriptor(5) + 0x4000 <= super::client::render_base(0)); + /// Worst-case firmware work-ring entries consumed per pipelined render pass on TA + /// (`prev_barrier`, `ta_fs_barrier`, `compute_barrier`, `ta_work`) and FS (`fs_dep`, + /// `fs_compute_barrier`, `own_barrier`, `fs_work`). `InitBM` runs only on an idle engine + /// (`initbm` + `ta_work` = 2 entries). + pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 4; + /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + `work`). + pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 2; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; - /// Retained render pass slots per VM at most (host client-VA budget: 512 MiB / 32 MiB - /// stride = 16, not a firmware limit). 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 = 16; + /// 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. + /// + /// Sized inside both the host client-VA window (`0x7020000000..0x7040000000`) and firmware + /// queue/recovery capacities: `31` in-flight passes consume at most `31 * 4 = 124` entries of + /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable), share hardware UMA slot + /// `RENDER_UMA_SLOT` (33) via the active PB/UMA descriptor, post at most `FLIGHTS = 32` + /// `SubmitRecord`s (vs `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay far below the + /// firmware recovery `snapshot_entries = 448` limit. + pub(crate) const RENDER_SLOTS: usize = 32; + const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 32); + const _: () = assert!((RENDER_SLOTS - 1) * MAX_RENDER_RING_ENTRIES < QUEUE_CAP as usize); 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); @@ -709,13 +751,14 @@ pub(crate) mod sizes { <= 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 + super::client::EXT_TILEMAP_OFF + super::client::TILEMAP_SLOT_SIZE + <= super::client::EXT_PASS_STRIDE ); + const _: () = assert!(super::client::pass_base(RENDER_SLOTS as u64) <= 0x7040000000); pub(crate) const CT_BUFS: usize = 0; pub(crate) const CLUSTER_PB_PAGES: u32 = 0x3c; pub(crate) const MAX_ATTACHMENTS: usize = 16; - pub(crate) const MAX_CLIENT: usize = 320; + pub(crate) const MAX_CLIENT: usize = 512; pub(crate) const PB_PAGES: u32 = 8192; pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; @@ -724,10 +767,19 @@ pub(crate) mod sizes { /// 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. - pub(crate) const COMPUTE_UNITS: usize = 16; + /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). 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 (`17 * 2 = 34` entries of the 256-entry compute work + /// ring `QUEUE_CAP`, well inside `AHEAD_RECORDS = 128`, `RING_SLOTS = 256`, and recovery + /// `snapshot_entries = 448`). + pub(crate) const COMPUTE_UNITS: usize = 18; + const _: () = assert!(COMPUTE_UNITS >= 2); + const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); + const _: () = assert!( + super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) + <= super::engine::RENDER_UMA_SLOT + ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index bb6aae1ae434aa..a88a005a9cf13d 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 { - 16usize.clamp(2, hw::sizes::COMPUTE_UNITS) + hw::sizes::COMPUTE_UNITS } /// Compute commands in flight at most. diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 0f12d12b373eb1..55ecfd6f3a9749 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -80,13 +80,30 @@ 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 the VM actually -/// pipelines renders or submits a multi-pass/burst frame. +/// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are grown lazily in bounded tiers once the VM +/// pipelines renders or submits multi-pass/burst frames. pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; -const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLOTS; +/// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). +/// +/// Each extension `PassSlot` backs 3.59 MiB (2 MiB TPC + 1 MiB tilemap + 608 KiB metadata, +/// scratch, and barriers). Growing in bounded chunks keeps compositor and shallow desktop VMs +/// on Tier 0 (~21.6 MiB) instead of allocating all 30 extension slots (~107.8 MiB) on a 2-pass +/// submission: +/// - Tier 0 (`2..8`, 6 slots, 21.56 MiB): compositors, 2-6 pass frames, depth 1-2. +/// - Tier 1 (`8..18`, 10 slots, +35.94 MiB / 57.50 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..RENDER_SLOTS`, 14 slots / +50.31 MiB at 32 slots): deep multi-pass bursts. +pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 3] = [ + (BASE_RENDER_SLOTS, 8), + (8, 18), + (18, super::hw::sizes::RENDER_SLOTS), +]; +const _: () = assert!(EXT_RENDER_TIERS[0].0 == BASE_RENDER_SLOTS); +const _: () = assert!(EXT_RENDER_TIERS[0].1 == EXT_RENDER_TIERS[1].0); +const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); +const _: () = assert!(EXT_RENDER_TIERS[2].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; -/// Single-submission render command count that expands extension slots immediately: +/// Single-submission render command count that expands Tier 0 extension slots immediately: /// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; @@ -123,33 +140,57 @@ fn should_expand_compute_ext( base_quarantined || *burst >= BURST_SUBMITS || computes >= BURST_COMMANDS } -/// Updates the consecutive-render burst counter and reports whether this submission -/// qualifies to allocate extension pass slots (`RenderExtArena`). +/// Updates the consecutive-render burst counter and returns the target render pass slot count +/// (`BASE_RENDER_SLOTS..=hw::sizes::RENDER_SLOTS`) this VM should have backed before admission. /// /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives -/// (`active_renders == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay -/// on the two base pass slots. Extension slots allocate when a base pass slot is quarantined, -/// a VM actually overlaps an in-flight render (`active_renders != 0`, including multi-ms -/// 1080p/4K pipelined frames), submits a multi-pass command stream -/// (`render_count >= BASE_RENDER_SLOTS`), or sustains a sub-2 ms back-to-back burst. -fn should_expand_render_ext( +/// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay +/// on the two base pass slots (~49.2 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, +/// +21.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a +/// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission +/// and one displacement slot exceed the currently backed capacity. +fn target_render_slots( last_render_ns: &mut u64, render_burst: &mut u32, now: u64, render_count: usize, - active_renders: u32, + active_passes: u32, base_quarantined: bool, -) -> bool { + current_slots: usize, +) -> usize { *render_burst = if *last_render_ns != 0 && now.wrapping_sub(*last_render_ns) < BURST_GAP_NS { render_burst.saturating_add(1) } else { 0 }; *last_render_ns = now; - base_quarantined - || active_renders != 0 - || *render_burst >= BURST_SUBMITS - || render_count >= RENDER_BURST_COMMANDS + let live_need = (active_passes as usize) + .saturating_add(render_count) + .saturating_add(1); + let want = if current_slots <= BASE_RENDER_SLOTS { + if base_quarantined + || active_passes != 0 + || *render_burst >= BURST_SUBMITS + || render_count >= RENDER_BURST_COMMANDS + { + live_need.max(BASE_RENDER_SLOTS + 1) + } else { + BASE_RENDER_SLOTS + } + } else { + live_need + }; + let mut target = current_slots.max(BASE_RENDER_SLOTS); + for &(start, end) in &EXT_RENDER_TIERS { + if target >= want { + break; + } + if target < end && want > start { + target = end; + } + } + target.min(super::hw::sizes::RENDER_SLOTS) } pub(crate) struct RenderArena(crate::cleanup::Deferred); @@ -206,9 +247,8 @@ 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. +/// One demand-grown tier of extension render pass slots (`slots`), allocated lazily so idle, +/// single-pass, and shallow multi-pass VMs back only the tiers their concurrency requires. pub(crate) struct RenderExtArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderExtArena { type Target = RenderExtInner; @@ -217,9 +257,10 @@ impl core::ops::Deref for RenderExtArena { } } pub(crate) struct RenderExtInner { + pub(crate) start: usize, pub(crate) passes: KVec, - pub(crate) tpc_dirty: [AtomicU64; EXT_RENDER_SLOTS], - pub(crate) tilemap_dirty: [AtomicU64; EXT_RENDER_SLOTS], + pub(crate) tpc_dirty: KVec, + pub(crate) tilemap_dirty: KVec, _objects: Objects, _bind: mmu::VmBind, _live: Arc, @@ -230,18 +271,25 @@ impl RenderExtArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + slots: core::ops::Range, ) -> Result> { + let count = slots.len(); 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 { + let mut passes = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tpc_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + for k in slots.clone() { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; } objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderExtInner { + start: slots.start, passes, - tpc_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], - tilemap_dirty: [const { AtomicU64::new(0) }; EXT_RENDER_SLOTS], + tpc_dirty, + tilemap_dirty, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -312,7 +360,7 @@ impl PassOwnerArena { match self { Self::Base(arena) => Some((arena.passes.get(k)?, arena.tilemap_dirty.get(k)?)), Self::Ext(arena) => { - let idx = k.checked_sub(BASE_RENDER_SLOTS)?; + let idx = k.checked_sub(arena.start)?; Some((arena.passes.get(idx)?, arena.tilemap_dirty.get(idx)?)) } } @@ -325,8 +373,8 @@ struct Ready { /// 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>, + /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). + render_ext: [Option>; EXT_RENDER_TIERS.len()], /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], /// Last compute submission and the back-to-back run it continues. @@ -360,8 +408,8 @@ pub(crate) struct Cache { standby_available: CondVar, /// The VM's client closed: no arena or surplus spare is kept here any more. closed: AtomicBool, - /// Prepared render jobs on this VM that have not yet retired and dropped. - active_renders: AtomicU32, + /// Render passes across prepared jobs on this VM that have not yet retired and dropped. + active_render_passes: AtomicU32, pub(crate) factory: Factory, bind: mmu::VmBind, live: Arc, @@ -387,7 +435,7 @@ impl Cache { ), standby_available <- new_condvar!(), closed: AtomicBool::new(false), - active_renders: AtomicU32::new(0), + active_render_passes: AtomicU32::new(0), factory, bind, live, budget }), GFP_KERNEL, ) @@ -503,7 +551,7 @@ impl Cache { ready.compute.take(), ready.compute_ext.take(), ready.render.take(), - ready.render_ext.take(), + core::mem::take(&mut ready.render_ext), core::mem::take(&mut ready.pb_ext), ) }; @@ -601,25 +649,54 @@ impl Cache { } } } - if ready.render_ext.is_none() && EXT_RENDER_SLOTS != 0 { + let current_slots = BASE_RENDER_SLOTS + + ready + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum::(); + if current_slots < super::hw::sizes::RENDER_SLOTS { // SAFETY: ktime_get has no preconditions. let now = unsafe { kernel::bindings::ktime_get() } as u64; let state = &mut *ready; - let active = self.active_renders.load(Ordering::Acquire); - if should_expand_render_ext( + let active_passes = self.active_render_passes.load(Ordering::Acquire); + let target = target_render_slots( &mut state.last_render_ns, &mut state.render_burst, now, render_count as usize, - active, + active_passes, hints.expand_render_ext, - ) { - // Best effort: without extension slots the VM keeps two base pass slots. - state.render_ext = - RenderExtArena::new(&self.factory, &self.bind, &vm.vm, &self.live).ok(); + current_slots, + ); + for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { + if start >= target { + break; + } + if state.render_ext[idx].is_none() { + // Best effort: stop on allocation failure, keeping lower tiers. + state.render_ext[idx] = RenderExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + start..end, + ) + .ok(); + if state.render_ext[idx].is_none() { + break; + } + } } } } + let render_ext = if render { + core::array::from_fn(|idx| ready.render_ext[idx].clone()) + } else { + [const { None }; EXT_RENDER_TIERS.len()] + }; let pb_ext = if render { core::array::from_fn(|idx| ready.pb_ext[idx].clone()) } else { @@ -629,7 +706,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 }, - if render { ready.render_ext.clone() } else { None }, + render_ext, pb_ext, ) }; @@ -718,7 +795,8 @@ impl Cache { return Err(EIO); } let cache = if render_count != 0 { - self.active_renders.fetch_add(1, Ordering::AcqRel); + self.active_render_passes + .fetch_add(render_count, Ordering::AcqRel); Some(self.clone()) } else { None @@ -729,6 +807,7 @@ impl Cache { render: render_arena, render_ext, pb_ext, + total_renders: render_count, unpublished_renders: AtomicU32::new(render_count), cache, }) @@ -741,10 +820,12 @@ 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>, + /// The VM's demand-grown extension render pass tiers when the job was prepared. + pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], + /// Total render commands accounted against `Cache::active_render_passes`. + total_renders: u32, /// 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. @@ -756,8 +837,10 @@ impl Drop for Prepared { let Some(cache) = self.cache.take() else { return; }; - let previous = cache.active_renders.fetch_sub(1, Ordering::AcqRel); - debug_assert!(previous != 0); + let previous = cache + .active_render_passes + .fetch_sub(self.total_renders, Ordering::AcqRel); + debug_assert!(previous >= self.total_renders); let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); cache.release_reserved(remaining); } @@ -836,20 +919,35 @@ impl Prepared { .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone())) } } + fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { + for tier in self.render_ext.iter().take_while(|t| t.is_some()).flatten() { + if let Some(idx) = k.checked_sub(tier.start) { + if idx < tier.passes.len() { + return Some((tier, idx)); + } + } + } + None + } /// 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())) + let ext: usize = self + .render_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.passes.len()) + .sum(); + Ok(self.render()?.passes.len() + ext) } - /// Render pass slot `k`: the VM's base slots, then its extension slots. + /// Render pass slot `k`: the VM's base slots, then its demand-grown extension tiers. 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())) + .render_ext_for(k) + .and_then(|(tier, idx)| tier.passes.get(idx)) .ok_or(EINVAL), } } @@ -859,12 +957,8 @@ impl Prepared { 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])) + let (tier, idx) = self.render_ext_for(k).ok_or(EINVAL)?; + Ok((&tier.tpc_dirty[idx], &tier.tilemap_dirty[idx])) } } /// Updates dirty high-water marks for pass slot `k` (base or extension). @@ -884,7 +978,8 @@ impl Prepared { if k < base.passes.len() { Some(PassOwnerArena::Base(base.clone())) } else { - self.render_ext.as_ref().map(|e| PassOwnerArena::Ext(e.clone())) + self.render_ext_for(k) + .map(|(tier, _)| PassOwnerArena::Ext(tier.clone())) } } /// Compute unit `k`: the VM's base units, then its extension units. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 110af8019022ca..6b3c4877dfb2e5 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -156,7 +156,7 @@ impl PassSlot { /// Allocates pass slot `i`'s objects, with their client leaf classes. pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { let sh = Class::Shared; - let (ps, ws) = (i * client::PASS_STRIDE, i * client::WORK_STRIDE); + let off = client::pass_off(i); let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { client::TPC_SLOT_SIZE } else { @@ -169,32 +169,25 @@ impl PassSlot { }; let _ = pre_records; - let aux = alloc( - o, - 0x20000, - sh, - Client::nc(client::AUX + i * client::AUX_STRIDE), - 0, - false, - )?; + let aux = alloc(o, 0x20000, sh, Client::nc(client::AUX + off), 0, false)?; let mut pre = KVec::with_capacity(3, GFP_KERNEL)?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE0_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE1_PAGE + off), 0, false)?, GFP_KERNEL, )?; pre.push( - alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + ps), 0, false)?, + alloc(o, 0x4000, sh, Client::nc(client::PRE2_PAGE + off), 0, false)?, GFP_KERNEL, )?; let tpc = alloc( o, tpc as usize, sh, - Client::nc(client::TPC + i * client::TPC_SLOT_STRIDE), + Client::nc(client::TPC + off), 0, false, )?; @@ -202,7 +195,7 @@ impl PassSlot { o, tilemap as usize, sh, - Client::nc(client::TILEMAP + i * client::TPC_SLOT_STRIDE), + Client::nc(client::pass_tilemap(i)), 0, false, )?; @@ -210,7 +203,7 @@ impl PassSlot { o, 0x4000, sh, - Client::nc(client::HEAP_META_PAGE + ps), + Client::nc(client::HEAP_META_PAGE + off), 0, false, )?; @@ -218,7 +211,7 @@ impl PassSlot { o, 0x10000, sh, - Client::nc(client::SCENE_USER + ps), + Client::nc(client::SCENE_USER + off), 0, false, )?; @@ -226,7 +219,7 @@ impl PassSlot { o, super::fw::buffer::SCENE_LIST_SIZE, sh, - Client::nc(client::SCENE_LIST + ps), + Client::nc(client::SCENE_LIST + off), 0, false, )?; @@ -234,20 +227,20 @@ impl PassSlot { o, 0x10000, sh, - Client::nc(client::FS_SCRATCH + ps), + Client::nc(client::FS_SCRATCH + off), 0, false, )?; let fs_work = alloc_work( o, fs::WORK_SIZE, - client::FS_WORK_PAGE + ws, + client::FS_WORK_PAGE + off, client::FS_WORK_OFF as usize, )?; let ta_work = alloc_work( o, ta::WORK_SIZE, - client::TA_WORK_PAGE + ws, + client::TA_WORK_PAGE + off, client::TA_WORK_OFF as usize, )?; Ok(Self { @@ -446,7 +439,7 @@ pub(crate) struct ComputeOwners { } /// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). -const PASS_MASK: u32 = (1u32 << sizes::RENDER_SLOTS) - 1; +const PASS_MASK: u32 = u32::MAX >> (32 - sizes::RENDER_SLOTS); /// Shared atomic coordination between `Shared::state` slot selection/claims and off-lock /// pre-scrubbing of displaced render pass slots. 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 0bf80de699bdfd..e76430e00c6ebe 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -573,7 +573,9 @@ def module(text, name): assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); } - #[test]fn eight_render_passes_and_sixteen_compute_units_are_disjoint_in_mesa_hole(){ + #[test]fn thirty_two_render_passes_and_eighteen_compute_units_are_disjoint_in_mesa_hole(){ + assert_eq!(g16::hw::sizes::RENDER_SLOTS, 32); + assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 18); let mut o=Objects::new(); let pools=PoolSet::new(&mut o).unwrap(); for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { @@ -803,7 +805,7 @@ def module(text, name): assert_eq!(arena.render.passes[0].scene.fills.lock().unwrap().len(),2); } - #[test]fn pipelined_render_pass_slots_keep_fifteen_in_flight(){ + #[test]fn pipelined_render_pass_slots_keep_thirty_one_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 { @@ -825,23 +827,30 @@ def module(text, name): let a=vm(1); let b=vm(2); let mut live:Vec=Vec::new(); - // Publish 15 concurrent passes in flight (slots 0..15). - for k in 0..15usize { + // Publish 31 concurrent passes in flight (slots 0..31), exercising bit 31 on the last slot. + for k in 0..31usize { let mut c=Claims::new(); - c.pass[0]=k as u32;c.pass_mask=1< slot 0 is displaced and reusable while 13 others remain in flight. + assert_eq!(s.render_published(),31); + assert!(s.pass_available(32)); // slot 31 is still fresh + assert!(!s.pass_available(31)); + // Retire 0 and 1 -> slot 0 is displaced and reusable while 29 others remain in flight. s.retire(&mut live[0]).unwrap(); - assert!(!s.pass_available(15)); // slot 0 not displaced yet + assert!(!s.pass_available(31)); // slot 0 not displaced yet s.retire(&mut live[1]).unwrap(); - assert!(s.pass_available(15)); // slot 0 displaced by slot 1! + assert!(s.pass_available(31)); // slot 0 displaced by slot 1! + // Claim and publish bit 31 (slot 31) explicitly to prove zero 32-bit mask overflow. + let mut c31=Claims::new(); + c31.pass[0]=31;c31.pass_count=1;c31.pass_mask=1u32<<31; + s.claim_pass_for(&arena,31,Some(a.id)).unwrap(); + s.hold_vm(&c31,&a).unwrap(); + s.publish(&c31).unwrap(); // Clean same-VM reuse of displaced slot 0 does not need full work write. s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); assert!(!s.render_needs_full_work(0)); @@ -854,6 +863,7 @@ def module(text, name): for c in live.iter_mut().skip(2) { s.retire(c).unwrap(); } + s.retire(&mut c31).unwrap(); assert_eq!(s.render_published(),0); } @@ -1041,23 +1051,23 @@ def module(text, name): },0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; let a=vm(1); - // Wrapped submission order [14, 15, 0]: retiring in order leaves slot 0 as last_retired - // while slots 14 and 15 are displaced and reusable immediately. - let order=[14usize,15,0]; + // Wrapped submission order [30, 31, 0]: retiring in order leaves slot 0 as last_retired + // while slots 30 and 31 are displaced and reusable immediately. + let order=[30usize,31,0]; let mut c=Claims::new(); for (i,&k) in order.iter().enumerate() { s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); c.pass[i]=k as u32; c.pass_count+=1; - c.pass_mask|=1<= 1) and expand immediately. + // A 2-pass compositor or shallow depth-2 overlap grows ONLY to Tier 0 (8 slots), + // never allocating Tier 1 or Tier 2 until live concurrency actually requires them. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 6_000_000, 1, 1, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 22_600_000, 1, 1, false)); + assert_eq!( + target_render_slots(&mut last, &mut burst, 100_000_000, 2, 0, false, BASE_RENDER_SLOTS), + tier0_end + ); + // Back-to-back 2-pass frames with 2 active passes (need = 2 + 2 + 1 = 5 <= 8) stay on Tier 0. + assert_eq!( + target_render_slots(&mut last, &mut burst, 108_333_333, 2, 2, false, tier0_end), + tier0_end + ); - // Sub-2 ms back-to-back single-pass bursts still expand after 3 consecutive gaps. + // Heavy multi-ms pipelined renders (5 ms and 16.6 ms apart) overlap an already-active + // pass and grow progressively: Tier 0 -> Tier 1 -> Tier 2 only as depth climbs. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 2_000_000, 1, 0, false)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 3_000_000, 1, 0, false)); - assert!(should_expand_render_ext(&mut last, &mut burst, 4_000_000, 1, 0, false)); + let mut backed = BASE_RENDER_SLOTS; + backed = target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, backed); + assert_eq!(backed, BASE_RENDER_SLOTS); + backed = target_render_slots(&mut last, &mut burst, 6_000_000, 1, 1, false, backed); + assert_eq!(backed, tier0_end); + backed = target_render_slots(&mut last, &mut burst, 22_600_000, 1, 6, false, backed); + assert_eq!(backed, tier0_end); // 6 + 1 + 1 == 8 fits in Tier 0 + backed = target_render_slots(&mut last, &mut burst, 39_200_000, 1, 7, false, backed); + assert_eq!(backed, tier1_end); // 7 + 1 + 1 == 9 grows to Tier 1 (18 slots) + backed = target_render_slots(&mut last, &mut burst, 55_800_000, 1, 16, false, backed); + assert_eq!(backed, tier1_end); // 16 + 1 + 1 == 18 fits in Tier 1 + backed = target_render_slots(&mut last, &mut burst, 72_400_000, 1, 17, false, backed); + assert_eq!(backed, full_end); // 17 + 1 + 1 == 19 grows to Tier 2 (32 slots) + + // Sub-2 ms back-to-back single-pass bursts grow only to Tier 0 after 3 consecutive gaps. + let mut last = 0u64; + let mut burst = 0u32; + assert_eq!(target_render_slots(&mut last, &mut burst, 1_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 2_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 3_000_000, 1, 0, false, BASE_RENDER_SLOTS), BASE_RENDER_SLOTS); + assert_eq!(target_render_slots(&mut last, &mut burst, 4_000_000, 1, 0, false, BASE_RENDER_SLOTS), tier0_end); assert_eq!(burst, 3); + assert_eq!(target_render_slots(&mut last, &mut burst, 5_000_000, 1, 0, false, tier0_end), tier0_end); - // A single multi-pass SUBMIT with >= BASE_RENDER_SLOTS (2) renders expands immediately. + // A single large multi-pass SUBMIT jumps directly to the tier covering render_count + 1. let mut last = 0u64; let mut burst = 0u32; - assert!(should_expand_render_ext(&mut last, &mut burst, 100_000_000, 2, 0, false)); + assert_eq!(target_render_slots(&mut last, &mut burst, 10_000_000, 8, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 20_000_000, 20, 0, false, BASE_RENDER_SLOTS), full_end); + + // Verify exact per-slot mapped backing bytes for Base vs Ext slots. + let mut o_base = Objects::new(); + g16::slots::PassSlot::new(&mut o_base, 0, 1).unwrap(); + let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 608) * 1024); + let mut o_ext = Objects::new(); + g16::slots::PassSlot::new(&mut o_ext, 2, 1).unwrap(); + let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 608) * 1024); + // Tier 0 (6 ext slots) is 21.5625 MiB vs 107.8125 MiB for all 30 ext slots. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 22_080 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 58_880 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 110_400 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -1171,7 +1229,7 @@ def module(text, name): } #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ - use crate::g16::resources::should_expand_render_ext; + use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..4u64 { @@ -1195,9 +1253,12 @@ def module(text, name): assert!(s.base_render_quarantined()); assert!(s.render_exhausted_within(2)); assert!(!s.render_exhausted_within(4)); - // Fresh single-pass VM expands RenderExtArena immediately because a base pass slot is quarantined. + // Fresh single-pass VM expands Tier 0 RenderExtArena immediately because a base pass slot is quarantined. let mut last=0u64;let mut burst=0u32; - assert!(should_expand_render_ext(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined())); + assert_eq!( + target_render_slots(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined(),BASE_RENDER_SLOTS), + EXT_RENDER_TIERS[0].1 + ); // Expanded VM picks and retires pass slot 2, displacing base pass slot 0 back to reusable. let k=s.pick_pass_in(&prep,&geo,0).unwrap(); assert_eq!(k,2); @@ -1301,10 +1362,18 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() -render_burst_lines = '\n'.join( - line for line in resources_source.splitlines() - if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const BURST_COMMANDS:', 'const RENDER_BURST_COMMANDS:')) -) + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn should_expand_render_ext(') +ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') +ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 +render_burst_lines = ( + resources_source[ext_tiers_start:ext_tiers_end] + + '\n' + + '\n'.join( + line for line in resources_source.splitlines() + if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const BURST_COMMANDS:', 'const RENDER_BURST_COMMANDS:')) + ) + + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') +) source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) From 021468eacc4b87fab557e6f1add7b79cc9042482 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:15:15 -0500 Subject: [PATCH 0839/1514] drm/asahi: g16: support DRM_ASAHI_RENDER_STAGE_PREFIXES_V2 Accept the 480-byte drm_asahi_cmd_render_m5 render payload when DRM_ASAHI_RENDER_STAGE_PREFIXES is set, decode the 32-byte drm_asahi_render_stage_prefixes tail with compile-time layout assertions, and record per-stage TA compute and render wait-through prefixes on Order via narrow_tiling() (refusing any TA wait later than the FS wait, nonzero reserved words, or combination with DRM_ASAHI_RENDER_FRAGMENT_BARRIERS). Add per-pass ta_fs_barrier and fs_compute_barrier objects to PassSlot, resolve independent TA and FS compute/render barrier stamps in prefix_render() via plan_render_barriers(), and advertise DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2 in G16 params so Mesa can emit independent TA and FS waits on G16G. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 156 ++++++++++++++-- drivers/gpu/drm/asahi/g16/engine.rs | 168 +++++++++++++++--- drivers/gpu/drm/asahi/g16/params.rs | 7 +- drivers/gpu/drm/asahi/g16/slots.rs | 4 + .../gpu/asahi-m4/test-command-stream.py | 81 ++++++++- .../drivers/gpu/asahi-m4/test-publication.py | 106 ++++++++++- 6 files changed, 471 insertions(+), 51 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 33bcaa4f7feaa0..8ded81f21bd467 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -37,9 +37,29 @@ 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 STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const COMPUTE_NO_QUERY_ACCESS: u32 = uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS as u32; +const RENDER_STAGE_PREFIXES_OFF: usize = + offset_of!(uapi::drm_asahi_cmd_render_m5, stage_prefixes); +const RENDER_M5_SIZE: usize = size_of::(); + +const _: () = { + assert!(RENDER_STAGE_PREFIXES_OFF == size_of::()); + assert!(size_of::() == 448); + assert!(RENDER_M5_SIZE == 480); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_cdm_barrier) == 0); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved0) == 2); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved1) == 4); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_prior_cdm) == 8); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_vdm_barrier) == 16); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved2) == 18); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, reserved3) == 20); + assert!(offset_of!(uapi::drm_asahi_render_stage_prefixes, ta_prior_vdm) == 24); + assert!(size_of::() == 32); +}; + 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; const SET_VERTEX_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_VERTEX_ATTACHMENTS; @@ -66,6 +86,7 @@ pub(crate) struct Order { pub(crate) engine: usize, pub(crate) sequence: u64, pub(crate) wait_through: [Option; 2], + pub(crate) ta_wait_through: [Option; 2], } impl Order { @@ -109,9 +130,22 @@ impl Order { engine, sequence: sequences[engine], wait_through, + ta_wait_through: wait_through, }) } + /// Narrows the tiling half's prefixes to `tiling` (`DRM_ASAHI_RENDER_STAGE_PREFIXES`), + /// requiring each stage prefix to stay within the command's full fragment prefix. + pub(crate) fn narrow_tiling(&mut self, tiling: &Self) -> Result { + for index in 0..2 { + if tiling.wait_through[index].unwrap_or(0) > self.wait_through[index].unwrap_or(0) { + return Err(EINVAL); + } + } + self.ta_wait_through = tiling.wait_through; + Ok(()) + } + /// A same-engine command cannot jump a hole in its queue's published frontier. /// Cross-engine dependencies may also follow published predecessors via hardware /// ring barriers (FS -> CDM and CDM -> TA) while same-VM work pipelines; cross-VM @@ -393,6 +427,71 @@ fn payload(bytes: &[u8]) -> Result { Reader::new(bytes).read_up_to(bytes.len()) } +/// Decodes the 32-byte `drm_asahi_render_stage_prefixes` tail from a 480-byte +/// `drm_asahi_cmd_render_m5` payload without adding a duplicate `AnyBitPattern` impl. +fn decode_stage_prefixes(tail: &[u8]) -> Result { + let bytes: &[u8; 32] = tail.try_into().map_err(|_| EINVAL)?; + let u16_at = |o: usize| u16::from_le_bytes([bytes[o], bytes[o + 1]]); + let u32_at = |o: usize| { + u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]) + }; + let u64_at = |o: usize| { + u64::from_le_bytes([ + bytes[o], + bytes[o + 1], + bytes[o + 2], + bytes[o + 3], + bytes[o + 4], + bytes[o + 5], + bytes[o + 6], + bytes[o + 7], + ]) + }; + Ok(uapi::drm_asahi_render_stage_prefixes { + ta_cdm_barrier: u16_at(0), + reserved0: u16_at(2), + reserved1: u32_at(4), + ta_prior_cdm: u64_at(8), + ta_vdm_barrier: u16_at(16), + reserved2: u16_at(18), + reserved3: u32_at(20), + ta_prior_vdm: u64_at(24), + }) +} + +/// Decodes a render command. With `DRM_ASAHI_RENDER_STAGE_PREFIXES`, the payload must be +/// the exact 480-byte `drm_asahi_cmd_render_m5` with zero reserved fields and without +/// `DRM_ASAHI_RENDER_FRAGMENT_BARRIERS`. Without the flag, any trailing bytes must be zero. +fn render_payload( + bytes: &[u8], +) -> Result<( + uapi::drm_asahi_cmd_render, + Option, +)> { + let head_len = bytes.len().min(RENDER_STAGE_PREFIXES_OFF); + let cmd: uapi::drm_asahi_cmd_render = Reader::new(&bytes[..head_len]).read_up_to(head_len)?; + let tail = bytes.get(RENDER_STAGE_PREFIXES_OFF..).unwrap_or(&[]); + if cmd.flags & STAGE_PREFIXES != 0 { + if bytes.len() != RENDER_M5_SIZE || cmd.flags & FRAGMENT_BARRIERS != 0 { + return Err(EINVAL); + } + let prefixes = decode_stage_prefixes(tail)?; + if prefixes.reserved0 != 0 + || prefixes.reserved1 != 0 + || prefixes.reserved2 != 0 + || prefixes.reserved3 != 0 + { + return Err(EINVAL); + } + Ok((cmd, Some(prefixes))) + } else { + if tail.iter().any(|&byte| byte != 0) { + return Err(EINVAL); + } + Ok((cmd, None)) + } +} + /// Whether `[start, start + size)` is a nonempty range inside `range`. fn inside(start: u64, size: u64, range: &Range) -> bool { size != 0 && start >= range.start && start < range.end && size <= range.end - start @@ -459,20 +558,38 @@ pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { } match entry.kind { CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + let (packet, prefixes) = render_payload(entry.payload)?; let cmd = &packet; // Ray-query extensions belong to G17; reject every nonzero byte - // beyond the common historical-prefix fields on G16. + // between the common historical-prefix fields and the stage-prefix tail. let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); - if entry.payload.get(end..).is_some_and(|tail| tail.iter().any(|&b| b != 0)) { + let rq_end = entry.payload.len().min(RENDER_STAGE_PREFIXES_OFF); + if entry + .payload + .get(end..rq_end) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { return Err(EINVAL); } + if let Some(prefixes) = prefixes { + if (prefixes.ta_vdm_barrier != NONE + && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) + || (prefixes.ta_cdm_barrier != NONE + && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) + { + return Err(EINVAL); + } + } check_render_helpers(cmd)?; // M4 HAL200 resource words carry all four high halves. let allowed = PROCESS_EMPTY_TILES | DBIAS_IS_INT | RSRC_SPEC_HI - | if early_tiling { FRAGMENT_BARRIERS } else { 0 }; + | if early_tiling { + FRAGMENT_BARRIERS | STAGE_PREFIXES + } else { + 0 + }; if cmd.flags & !allowed != 0 || !(1..=MAX_DIMENSION).contains(&cmd.width_px) || !(1..=MAX_DIMENSION).contains(&cmd.height_px) @@ -784,7 +901,7 @@ fn check_render( | RSRC_SPEC_HI | DBIAS_IS_INT | if super::params::early_tiling() { - FRAGMENT_BARRIERS + FRAGMENT_BARRIERS | STAGE_PREFIXES } else { 0 }; @@ -908,31 +1025,36 @@ pub(crate) fn prepare<'a>( let mut preceding = [0u16; 2]; for entry in stream(bytes) { let entry = entry?; - let (outputs, engine, prior) = match entry.kind { + let (outputs, engine, prior, prefixes) = match entry.kind { CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + let (packet, prefixes) = render_payload(entry.payload)?; let outputs = crate::timestamp::Destinations::resolve_aligned( objects, &[packet.ts_vtx, packet.ts_frag], )?; - (outputs, RENDER, [packet.prior_vdm, packet.prior_cdm]) + (outputs, RENDER, [packet.prior_vdm, packet.prior_cdm], prefixes) } CMD_COMPUTE => { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let outputs = crate::timestamp::Destinations::resolve_aligned(objects, &[packet.ts])?; - (outputs, COMPUTE, [packet.prior_vdm, packet.prior_cdm]) + (outputs, COMPUTE, [packet.prior_vdm, packet.prior_cdm], None) } _ => continue, }; resolved.push(outputs)?; - orders.push(Order::new( - accepted, - preceding, - entry.barriers, - prior, - engine, - )?)?; + let mut order = Order::new(accepted, preceding, entry.barriers, prior, engine)?; + if let Some(prefixes) = prefixes { + let tiling = Order::new( + accepted, + preceding, + [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], + [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], + RENDER, + )?; + order.narrow_tiling(&tiling)?; + } + orders.push(order)?; preceding[engine] += 1; } @@ -967,7 +1089,7 @@ impl Prepared<'_> { SET_FRAGMENT_ATTACHMENTS => fragment = attachment_list(entry.payload)?, SET_COMPUTE_ATTACHMENTS => compute = attachment_list(entry.payload)?, CMD_RENDER => { - let packet: uapi::drm_asahi_cmd_render = payload(entry.payload)?; + let (packet, _) = render_payload(entry.payload)?; let cmd = &packet; let outputs = resolved.next().ok_or(EINVAL)?; check_render(context, cmd, &vertex, &fragment)?; diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index fc8488c706c00c..75a51c320912fd 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -136,6 +136,53 @@ impl Progress { } } +/// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or +/// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct RenderBarrierPlan { + early: bool, + ta_fs_wait: Option, + ta_compute_wait: Option, + fs_compute_wait: Option, +} + +/// Computes TA/FS hardware ring barriers for a render command from its flags, prior render +/// FS stamp, and resolved `[ta, fs]` compute wait stamps. +fn plan_render_barriers( + flags: u32, + class_behind: bool, + early_tiling: bool, + prev_fs: u32, + no_render_barrier: bool, + ta_wait_fs: Option, + compute_waits: [Option; 2], +) -> RenderBarrierPlan { + let staged = + flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; + let frag_only = + flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; + let early = class_behind + && early_tiling + && if staged { + ta_wait_fs != Some(prev_fs) + } else { + frag_only || no_render_barrier + }; + let ta_fs_wait = if early && staged { ta_wait_fs } else { None }; + let [ta_compute_wait, fs_wait] = compute_waits; + let fs_compute_wait = if fs_wait != ta_compute_wait { + fs_wait + } else { + None + }; + RenderBarrierPlan { + early, + ta_fs_wait, + ta_compute_wait, + fs_compute_wait, + } +} + /// Engine of the previous member. #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub(crate) enum Prev { @@ -1128,21 +1175,22 @@ impl Firmware { } } - /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` - /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> - /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited - /// prefix has already retired. - fn cross_engine_wait(&self, job: &Arc, index: u32, other: usize) -> Result> { - let Some(last) = job - .command_order(index) - .and_then(|o| o.wait_through[other]) - else { + /// Resolves a same-queue target stamp for `class` (`RENDER` -> `fs_target`, `COMPUTE` -> + /// `target`) when `target_seq` names an in-flight command of `job.queue`. Returns `Ok(None)` + /// when no barrier was requested or the waited prefix has already retired. + fn wait_stamp_for( + &self, + job: &Arc, + class: usize, + target_seq: Option, + ) -> Result> { + let Some(last) = target_seq else { return Ok(None); }; - if job.queue.completed[other].load(Ordering::Acquire) >= last { + if job.queue.completed[class].load(Ordering::Acquire) >= last { return Ok(None); } - if other == super::command::COMPUTE { + if class == super::command::COMPUTE { for flight in &self.engine.flights { if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { continue; @@ -1184,6 +1232,17 @@ impl Firmware { Err(EAGAIN) } + /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` + /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> + /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited + /// prefix has already retired. + fn cross_engine_wait(&self, job: &Arc, index: u32, other: usize) -> Result> { + let target_seq = job + .command_order(index) + .and_then(|o| o.wait_through[other]); + self.wait_stamp_for(job, other, target_seq) + } + /// 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 { @@ -1389,14 +1448,16 @@ impl Firmware { let mut c_read = prefix.c_head; if class_behind { if render { + // Room for up to 4 TA entries (prev_barrier, ta_fs_barrier, compute_barrier, + // ta_work) and 4 FS entries (fs_dep, fs_compute_barrier, own_barrier, fs_work). 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 + >= sizes::QUEUE_CAP - 5 || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP - >= sizes::QUEUE_CAP - 4 + >= sizes::QUEUE_CAP - 5 { return Err(EAGAIN); } @@ -1892,8 +1953,38 @@ 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 wait_compute = - self.cross_engine_wait(job, job.progress.sent(), super::command::COMPUTE)?; + let order = job.command_order(job.progress.sent()); + let staged = cmd.cmd.flags + & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES + != 0; + let ta_wait_compute = self.wait_stamp_for( + job, + super::command::COMPUTE, + order.and_then(|o| o.ta_wait_through[super::command::COMPUTE]), + )?; + let fs_wait_compute = self.wait_stamp_for( + job, + super::command::COMPUTE, + order.and_then(|o| o.wait_through[super::command::COMPUTE]), + )?; + let ta_wait_fs = if class_behind && staged && params::early_tiling() { + self.wait_stamp_for( + job, + super::command::RENDER, + order.and_then(|o| o.ta_wait_through[super::command::RENDER]), + )? + } else { + None + }; + let plan = plan_render_barriers( + cmd.cmd.flags, + class_behind, + params::early_tiling(), + self.engine.fs_target, + order.is_some_and(|o| o.wait_through[super::command::RENDER].is_none()), + ta_wait_fs, + [ta_wait_compute, fs_wait_compute], + ); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; @@ -1986,23 +2077,17 @@ impl Firmware { pf.ta_head = (pf.ta_head + 1) % cap; } // 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 = class_behind && params::early_tiling() && (frag_only || no_render_barrier); + // barriers on the TA/FS rings. Fragment-only, barrier-free, or staged renders whose TA + // prefix stops before the newest in-flight FS overlap TA(N) with FS(N-1) (TA waits on + // prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior FS + // then own TA); otherwise TA(N) waits on prior FS to preserve full vertex-stage visibility. if class_behind { // Pipelined same-VM non-InitBM render->render barriers wait on the producer's // firmware stamp only (type 0), matching `own_barrier` and G15's // `RENDER_INTERNAL_HOLD = 0`, so consecutive TA/FS stages hand off without a // software-job hold bubble. Cross-engine barriers (`fs2c`/`c2ta`) stay `Hold`. let render_bar = BarrierType::from_stamp_only(!init_buffer); - let (wait_va, wait_stamp, wait_event) = if early { + let (wait_va, wait_stamp, wait_event) = if plan.early { (r.fw_stamp[0].va, self.engine.ta_target, 0x70) } else { (r.fw_stamp[1].va, self.engine.fs_target, 0x71) @@ -2018,7 +2103,20 @@ impl Firmware { 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 { + if plan.early { + if let Some(older_fs) = plan.ta_fs_wait { + let ta_fs = encode::barrier( + r.fw_stamp[1].va, + older_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.ta_fs_barrier.write(0, &ta_fs)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } let dep = encode::barrier( r.fw_stamp[1].va, self.engine.fs_target, @@ -2033,7 +2131,7 @@ impl Firmware { self.engine.stats.early += 1; } } - if let Some(wait_c) = wait_compute { + if let Some(wait_c) = plan.ta_compute_wait { let cbar = encode::barrier( self.graph.compute.fw_stamp.va, wait_c, @@ -2047,6 +2145,20 @@ impl Firmware { pf.ta_head = (pf.ta_head + 1) % cap; self.engine.stats.c2ta0 += 1; } + if let Some(wait_c) = plan.fs_compute_wait { + let fcbar = encode::barrier( + self.graph.compute.fw_stamp.va, + wait_c, + 15, + target, + work::barrier::RENDER_WAIT_UUID, + BarrierType::Hold, + ); + p.fs_compute_barrier.write(0, &fcbar)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va)?; + pf.fs_head = (pf.fs_head + 1) % cap; + self.engine.stats.c2ta0 += 1; + } // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( r.fw_stamp[0].va, diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 5238cd4445d51a..bb6aae1ae434aa 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -5,8 +5,8 @@ //! With the shared `file.rs` additions (VM_STATUS and VM_STATUS_MIRROR from `supports_vm_status`, //! SOFT_FAULTS suppressed by `soft_faults`, and `INDEPENDENT_QUEUES` from `queue_limits`), G16 //! advertises per-command input readiness/errors, exact queue-local historical prefixes, -//! fragment-only render barriers, independent logical queues, and `COMPUTE_NO_QUERY_ACCESS`. -//! Ray queries are not advertised. +//! fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent logical +//! queues, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not advertised. use kernel::{prelude::*, uapi}; @@ -90,7 +90,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_COMPUTE_NO_QUERY_ACCESS); + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) + | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; 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/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 6e3c5006331224..e5484d32981367 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -145,9 +145,11 @@ pub(crate) struct PassSlot { pub(crate) own_barrier: Arc, #[allow(dead_code)] pub(crate) prev_barrier: Arc, + pub(crate) ta_fs_barrier: Arc, #[allow(dead_code)] pub(crate) fs_dep: Arc, pub(crate) compute_barrier: Arc, + pub(crate) fs_compute_barrier: Arc, } impl PassSlot { @@ -268,8 +270,10 @@ impl PassSlot { _uts: alloc(o, 32, Class::Fw, None, 0, false)?, own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + ta_fs_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, compute_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + fs_compute_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, }) } 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 4d9c4a50b88ce6..14c1c870fe0e3d 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 @@ -311,6 +311,85 @@ } } #[test] +fn g16_stage_prefixes_v2_framing_and_tiling_narrowing() { + let mut m5 = uapi::drm_asahi_cmd_render_m5 { legacy: render(), ..Default::default() }; + m5.legacy.flags = STAGE_PREFIXES; + m5.legacy.prior_vdm = 5; + m5.legacy.prior_cdm = 9; + m5.stage_prefixes.ta_vdm_barrier = NONE; + m5.stage_prefixes.ta_cdm_barrier = NONE; + m5.stage_prefixes.ta_prior_vdm = 3; + m5.stage_prefixes.ta_prior_cdm = 0; + + // Rejected when early_tiling is disabled; accepted when enabled. + let wire = entry(CMD_RENDER, &data(&m5), [NONE; 2]); + assert!(check_stream(&wire, false).is_err()); + assert!(check_stream(&wire, true).is_ok()); + + // Exact 480-byte payload, zero reserved fields, zero ray-query bytes, mutually exclusive with FRAGMENT_BARRIERS. + assert!(check_stream(&entry(CMD_RENDER, &data(&m5)[..448], [NONE; 2]), true).is_err()); + let mut over = data(&m5); + over.extend([0u8; 8]); + assert!(check_stream(&entry(CMD_RENDER, &over, [NONE; 2]), true).is_err()); + for field in 0..4 { + let mut bad = m5; + match field { + 0 => bad.stage_prefixes.reserved0 = 1, + 1 => bad.stage_prefixes.reserved1 = 1, + 2 => bad.stage_prefixes.reserved2 = 1, + _ => bad.stage_prefixes.reserved3 = 1, + } + assert!(check_stream(&entry(CMD_RENDER, &data(&bad), [NONE; 2]), true).is_err()); + } + let mut both = m5; + both.legacy.flags |= FRAGMENT_BARRIERS; + assert!(check_stream(&entry(CMD_RENDER, &data(&both), [NONE; 2]), true).is_err()); + let mut rq = m5; + rq.legacy.ray_query[0].scs_layout = 1; + assert!(check_stream(&entry(CMD_RENDER, &data(&rq), [NONE; 2]), true).is_err()); + + // Without STAGE_PREFIXES, nonzero trailing bytes past 448 are rejected; zero tail is accepted. + let mut plain = m5; + plain.legacy.flags = 0; + assert!(check_stream(&entry(CMD_RENDER, &data(&plain), [NONE; 2]), true).is_err()); + plain.stage_prefixes = Default::default(); + assert!(check_stream(&entry(CMD_RENDER, &data(&plain), [NONE; 2]), true).is_ok()); + + // Out-of-bounds in-stream ta_vdm_barrier / ta_cdm_barrier are rejected by check_stream. + let mut bad_bar = m5; + bad_bar.stage_prefixes.ta_vdm_barrier = 1; + assert!(check_stream(&entry(CMD_RENDER, &data(&bad_bar), [NONE; 2]), true).is_err()); + let mut bad_cdm = m5; + bad_cdm.stage_prefixes.ta_cdm_barrier = 1; + assert!(check_stream(&entry(CMD_RENDER, &data(&bad_cdm), [NONE; 2]), true).is_err()); + + // In-stream barriers following prior compute + render succeed in check_stream. + let mut seq = entry(CMD_COMPUTE, &data(&compute())[..64], [NONE; 2]); + seq.extend(entry(CMD_RENDER, &data(&render())[..256], [NONE; 2])); + let mut staged = m5; + staged.stage_prefixes.ta_vdm_barrier = 1; + staged.stage_prefixes.ta_cdm_barrier = 1; + seq.extend(entry(CMD_RENDER, &data(&staged), [1, 1])); + assert!(check_stream(&seq, true).is_ok()); + + // Order::narrow_tiling allows narrower TA prefixes (including TA-no-compute while FS waits) + // and rejects any TA prefix wider than the fragment prefix. + let mut full = Order::new([10, 20], [2, 1], [2, 1], [10, 20], RENDER).unwrap(); + assert_eq!(full.wait_through, [Some(12), Some(21)]); + assert_eq!(full.ta_wait_through, [Some(12), Some(21)]); + let ta_narrow = Order::new([10, 20], [2, 1], [1, NONE], [0, 0], RENDER).unwrap(); + assert_eq!(full.narrow_tiling(&ta_narrow), Ok(())); + assert_eq!(full.wait_through, [Some(12), Some(21)]); + assert_eq!(full.ta_wait_through, [Some(11), None]); + + let ta_too_wide_vdm = Order::new([10, 20], [2, 1], [2, NONE], [0, 0], RENDER).unwrap(); + let mut full_vdm1 = Order::new([10, 20], [2, 1], [1, 1], [0, 0], RENDER).unwrap(); + assert_eq!(full_vdm1.narrow_tiling(&ta_too_wide_vdm), Err(EINVAL)); + let ta_too_wide_cdm = Order::new([10, 20], [2, 1], [NONE, 1], [0, 0], RENDER).unwrap(); + let mut full_nocdm = Order::new([10, 20], [2, 1], [2, NONE], [0, 0], RENDER).unwrap(); + assert_eq!(full_nocdm.narrow_tiling(&ta_too_wide_cdm), Err(EINVAL)); +} +#[test] fn unsupported_flags_and_compute_fields() { for flag in [1u32,4,1<<19,FRAGMENT_BARRIERS] { let mut r=render(); r.flags=flag; @@ -519,7 +598,7 @@ use super::{ check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FRAGMENT_BARRIERS, MAX_DIMENSION, MAX_LAYERS, MAX_TILE_BUFFER, PROCESS_EMPTY_TILES, RSRC_SPEC_HI, - ZLS_METADATA_STRIDE, + STAGE_PREFIXES, ZLS_METADATA_STRIDE, }; const ENOENT: i32 = -2; const EACCES: i32 = -13; 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 83a62c0979aa59..da646563367f4f 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -46,11 +46,15 @@ def item(declaration): prefix_render_fn = item('fn prefix_render(') prefix_compute_fn = item('fn prefix_compute(') assert 'let render_bar = BarrierType::from_stamp_only(!init_buffer);' in prefix_render_fn -assert prefix_render_fn.count('render_bar,') == 2, prefix_render_fn +assert prefix_render_fn.count('render_bar,') == 3, prefix_render_fn +assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn -assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('wait_compute'):prefix_render_fn.index('p.compute_barrier.write')] +assert 'p.fs_compute_barrier.write(0, &fcbar)?;' in prefix_render_fn +assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write')] +assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write')] assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] assert 'BarrierType::Hold,' in prefix_compute_fn[prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write')] +assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src harness = r''' @@ -497,8 +501,18 @@ def item(declaration): 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} pub fn render_flights()->usize{15} } + mod kernel { + pub mod uapi { + pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS: u32 = 1 << 20; + pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES: u32 = 1 << 23; + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + __RENDER_BARRIER_PLAN__ + __PLAN_RENDER_BARRIERS__ impl QueueBehindHost { __CAN_QUEUE_BEHIND__ + __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_render(){ @@ -763,6 +777,91 @@ def item(declaration): p.engine.flights[0].computes=16; assert!(!p.can_queue_behind(&c4)); } + #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ + const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; + const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + // 1. Compute->FS-only wait (common texture-write-by-compute -> fragment-read): + // TA runs immediately (no TA compute barrier); FS gets fs_compute_barrier. + assert_eq!( + plan_render_barriers(STAGED, false, true, 0, false, None, [None, Some(0x700)]), + RenderBarrierPlan { + early: false, + ta_fs_wait: None, + ta_compute_wait: None, + fs_compute_wait: Some(0x700), + } + ); + // 2. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier). + assert_eq!( + plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + RenderBarrierPlan { + early: true, + ta_fs_wait: None, + ta_compute_wait: Some(0x700), + fs_compute_wait: None, + } + ); + // 3. Different compute targets on TA (0x600) vs FS (0x700): TA waits on 0x600, FS waits on 0x700. + assert_eq!( + plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x600), Some(0x700)]), + RenderBarrierPlan { + early: true, + ta_fs_wait: None, + ta_compute_wait: Some(0x600), + fs_compute_wait: Some(0x700), + } + ); + // 4. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200): + // overlaps TA with 0x200's FS while waiting on 0x100's FS via ta_fs_barrier. + assert_eq!( + plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x100), [None, None]), + RenderBarrierPlan { + early: true, + ta_fs_wait: Some(0x100), + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 5. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): + // no early overlap; prev_barrier waits on 0x200 directly. + assert_eq!( + plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x200), [None, None]), + RenderBarrierPlan { + early: false, + ta_fs_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 6. Legacy FRAGMENT_BARRIERS and plain render remain unchanged. + assert_eq!( + plan_render_barriers(FRAG, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + RenderBarrierPlan { + early: true, + ta_fs_wait: None, + ta_compute_wait: Some(0x700), + fs_compute_wait: None, + } + ); + assert_eq!( + plan_render_barriers(0, true, true, 0x200, false, None, [None, None]), + RenderBarrierPlan { + early: false, + ta_fs_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + assert_eq!( + plan_render_barriers(0, true, true, 0x200, true, None, [None, None]), + RenderBarrierPlan { + early: true, + ta_fs_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -1067,7 +1166,10 @@ def item(declaration): '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', + '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', + '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::")) unit = output / 'publication.rs' From 513c15bc949e31b818b70f1b513b7e0695ac0258 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:15:07 -0500 Subject: [PATCH 0840/1514] drm/asahi: g16: parse SUBMIT streams in one pass, batch CDM gate locking, and synchronize resnap Eliminate repeated SUBMIT-path CPU work across stream parsing, CDM stream gating, and completion timer management: - Replace the three-pass SUBMIT stream walk (check_stream -> prepare -> validate) with single-pass parse_stream() -> ParsedStream::prepare() -> Prepared::validate(). Structural validation and attachment parsing run once before device-state checks, preserving exact EINVAL/EOPNOTSUPP precedence over crashed/vm.status EIO. Attachment KVecs move directly into the first consuming command with zero copy, timestamp destinations resolve in place via timestamp::Destinations::empty() (G16-only), and validate() operates on the already-decoded commands. Remove the now-dead check_stream, cover, and Resolved helpers from g16/command.rs. - Expose VmReadGuard::covers_range() to G16 in mmu.rs and add command::cover_locked() so gate::cdm() holds a single vm.read_lock() across stream window reads, USC program checks, and indirect parameter checks, dropping the lock and invalidating cached window/program proofs before might_sleep() every CDM_RESCHED_RECORDS records. - Double-check resnap_deadline_ns and sleeping under resnap_handle.lock() in rearm(), and unconditionally acquire resnap_handle.lock() in cancel_resnap() before clearing resnap_deadline_ns and dropping the handle. This avoids redundant cancel+start cycles under racing callers while strictly ordering sleep_down() (sleeping = true then cancel_resnap()) against concurrent rearm() so no hrtimer handle can leak into suspend. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 735 ++++++++++-------- drivers/gpu/drm/asahi/g16/gate.rs | 44 +- drivers/gpu/drm/asahi/g16/poll.rs | 23 +- drivers/gpu/drm/asahi/g16/queue.rs | 4 +- drivers/gpu/drm/asahi/mmu.rs | 1 - drivers/gpu/drm/asahi/timestamp.rs | 6 + .../gpu/asahi-m4/test-command-stream.py | 67 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 155 +++- .../drivers/gpu/asahi-m4/test-stream-gate.py | 59 +- 9 files changed, 731 insertions(+), 363 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index e7cad14e4afe3f..86d7e2ddea756a 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -242,6 +242,17 @@ impl core::ops::Deref for Commands { } } +impl core::ops::DerefMut for Commands { + fn deref_mut(&mut self) -> &mut [Command] { + match self { + Self::Empty => &mut [], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + /// Inline storage for the common 1-2 command ordinals, spilling to a heap `KVec` above 2. pub(crate) enum Orders { Empty, @@ -286,58 +297,6 @@ impl core::ops::Deref for Orders { } } -/// Inline storage for transient resolved timestamp destinations during SUBMIT validation. -enum Resolved { - Empty, - One(Option), - Two([Option; 2]), - Heap { - items: KVec>, - index: usize, - }, -} - -impl Resolved { - fn new() -> Self { - Self::Empty - } - - fn push(&mut self, dest: crate::timestamp::Destinations) -> Result { - match self { - Self::Heap { items, .. } => items.push(Some(dest), GFP_KERNEL)?, - Self::Two(_) => { - let mut items = KVec::with_capacity(4, GFP_KERNEL)?; - if let Self::Two([a, b]) = core::mem::replace(self, Self::Empty) { - let _ = items.push_within_capacity(a); - let _ = items.push_within_capacity(b); - let _ = items.push_within_capacity(Some(dest)); - } - *self = Self::Heap { items, index: 0 }; - } - Self::One(_) => { - if let Self::One(a) = core::mem::replace(self, Self::Empty) { - *self = Self::Two([a, Some(dest)]); - } - } - Self::Empty => *self = Self::One(Some(dest)), - } - Ok(()) - } - - fn next(&mut self) -> Option { - match self { - Self::Empty => None, - Self::One(slot) => slot.take(), - Self::Two(slots) => slots[0].take().or_else(|| slots[1].take()), - Self::Heap { items, index } => { - let item = items.get_mut(*index)?.take(); - *index += 1; - item - } - } - } -} - /// A validated SUBMIT. pub(crate) struct Submission { /// The commands, in submission order. @@ -356,12 +315,10 @@ pub(crate) struct Context<'a> { pub(crate) usc_base: u64, } -/// A stream whose timestamps and ordinals are resolved ([`prepare`]), before its spans are -/// checked ([`Prepared::validate`]). -pub(crate) struct Prepared<'a> { - bytes: &'a [u8], - /// CPU views and their backing resolved before scheduler acceptance. - resolved: Resolved, +/// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its +/// spans are checked ([`Prepared::validate`]). +pub(crate) struct Prepared { + commands: Commands, orders: Orders, counts: [u64; 2], } @@ -520,152 +477,134 @@ fn check_geometry(cmd: &uapi::drm_asahi_cmd_render) -> Result { .validate_capacity(hw::client::TPC_SIZE, hw::client::TILEMAP_SIZE) } -/// Structural validation of a whole command stream, before anything is looked up. -pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { - if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { +fn validate_attachments_header(entry: &Entry<'_>) -> Result { + if entry.barriers != [NONE; 2] + || entry.payload.len() % ATTACHMENT_SIZE != 0 + || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS + { return Err(EINVAL); } - let range = hw::USER_RANGE; - let mut counts = [0u32; 2]; - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { - if entry.barriers != [NONE; 2] - || entry.payload.len() % ATTACHMENT_SIZE != 0 - || entry.payload.len() / ATTACHMENT_SIZE > hw::sizes::MAX_ATTACHMENTS - { - return Err(EINVAL); - } - for bytes in entry.payload.chunks_exact(ATTACHMENT_SIZE) { - let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; - if attachment.pad != 0 - || attachment.flags != 0 - || !inside(attachment.pointer, attachment.size, &range) - { - return Err(EINVAL); - } - } - continue; - } - _ => {} - } - if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) - || (entry.barriers[COMPUTE] != NONE - && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + Ok(()) +} + +fn validate_attachment(attachment: &uapi::drm_asahi_attachment, range: &Range) -> Result { + if attachment.pad != 0 + || attachment.flags != 0 + || !inside(attachment.pointer, attachment.size, range) + { + return Err(EINVAL); + } + Ok(()) +} + +fn validate_render_entry( + entry: &Entry<'_>, + counts: [u32; 2], + early_tiling: bool, +) -> Result<( + uapi::drm_asahi_cmd_render, + Option, +)> { + let (packet, prefixes) = render_payload(entry.payload)?; + let cmd = &packet; + // Ray-query extensions belong to G17; reject every nonzero byte + // between the common historical-prefix fields and the stage-prefix tail. + let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); + let rq_end = entry.payload.len().min(RENDER_STAGE_PREFIXES_OFF); + if entry + .payload + .get(end..rq_end) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + if let Some(prefixes) = prefixes { + if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) + || (prefixes.ta_cdm_barrier != NONE + && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) { return Err(EINVAL); } - match entry.kind { - CMD_RENDER => { - let (packet, prefixes) = render_payload(entry.payload)?; - let cmd = &packet; - // Ray-query extensions belong to G17; reject every nonzero byte - // between the common historical-prefix fields and the stage-prefix tail. - let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); - let rq_end = entry.payload.len().min(RENDER_STAGE_PREFIXES_OFF); - if entry - .payload - .get(end..rq_end) - .is_some_and(|tail| tail.iter().any(|&b| b != 0)) - { - return Err(EINVAL); - } - if let Some(prefixes) = prefixes { - if (prefixes.ta_vdm_barrier != NONE - && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) - || (prefixes.ta_cdm_barrier != NONE - && u32::from(prefixes.ta_cdm_barrier) > counts[COMPUTE]) - { - return Err(EINVAL); - } - } - check_render_helpers(cmd)?; - // M4 HAL200 resource words carry all four high halves. - let allowed = PROCESS_EMPTY_TILES - | DBIAS_IS_INT - | RSRC_SPEC_HI - | if early_tiling { - FRAGMENT_BARRIERS | STAGE_PREFIXES - } else { - 0 - }; - if cmd.flags & !allowed != 0 - || !(1..=MAX_DIMENSION).contains(&cmd.width_px) - || !(1..=MAX_DIMENSION).contains(&cmd.height_px) - || !(1..=MAX_LAYERS).contains(&cmd.layers) - || !matches!(cmd.samples, 1 | 2 | 4) - { - return Err(EINVAL); - } - check_geometry(cmd)?; - // Timestamp copies are reserved for another runtime. No copy - // feature is advertised, and zero handles do not waive MBZ offsets. - if cmd - .ts_frag_end_copies - .iter() - .any(|ts| ts.handle != 0 || ts.offset != 0) - { - return Err(EINVAL); - } - // `payload` rejects nonzero ray-query bytes beyond the prior - // extension. RENDER_RAY_QUERY is never advertised on G16. - // Never discard unflagged high words, nor accept the flag without them. - if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { - return Err(EINVAL); - } - if cmd.flags & RSRC_SPEC_HI == 0 - && (cmd.bg_eot_rsrc_spec_hi != 0 - || cmd.bg_eot_partial_rsrc_spec_hi != 0 - || cmd.bg_rsrc_spec_hi != 0 - || cmd.bg_partial_rsrc_spec_hi != 0) - { - return Err(EINVAL); - } - counts[RENDER] += 1; - } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 - || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base - || !inside( - cmd.cdm_ctrl_stream_base, - cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, - &range, - ) - { - return Err(EINVAL); - } - // The G17P scratch layout and intersection tables: never on G16. - if cmd - .ts_end_copies - .iter() - .any(|ts| ts.handle != 0 || ts.offset != 0) - || packet.scs_layout != 0 - || packet.cdm_auxiliary_allocation != 0 - || packet.reserved != 0 - || packet.intersection_pool != 0 - || packet.intersection_pool_bytes != 0 - || packet.intersection_first != 0 - || packet.intersection_count != 0 - || packet.intersection_default_program != 0 - || packet.intersection_default_control != 0 - { - return Err(EINVAL); - } - counts[COMPUTE] += 1; - } - _ => return Err(EINVAL), - } - if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { - return Err(EINVAL); - } } - if counts == [0; 2] { + check_render_helpers(cmd)?; + // M4 HAL200 resource words carry all four high halves. + let allowed = PROCESS_EMPTY_TILES + | DBIAS_IS_INT + | RSRC_SPEC_HI + | if early_tiling { + FRAGMENT_BARRIERS | STAGE_PREFIXES + } else { + 0 + }; + if cmd.flags & !allowed != 0 + || !(1..=MAX_DIMENSION).contains(&cmd.width_px) + || !(1..=MAX_DIMENSION).contains(&cmd.height_px) + || !(1..=MAX_LAYERS).contains(&cmd.layers) + || !matches!(cmd.samples, 1 | 2 | 4) + { return Err(EINVAL); } - Ok(()) + check_geometry(cmd)?; + // Timestamp copies are reserved for another runtime. No copy + // feature is advertised, and zero handles do not waive MBZ offsets. + if cmd + .ts_frag_end_copies + .iter() + .any(|ts| ts.handle != 0 || ts.offset != 0) + { + return Err(EINVAL); + } + // `payload` rejects nonzero ray-query bytes beyond the prior + // extension. RENDER_RAY_QUERY is never advertised on G16. + // Never discard unflagged high words, nor accept the flag without them. + if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { + return Err(EINVAL); + } + if cmd.flags & RSRC_SPEC_HI == 0 + && (cmd.bg_eot_rsrc_spec_hi != 0 + || cmd.bg_eot_partial_rsrc_spec_hi != 0 + || cmd.bg_rsrc_spec_hi != 0 + || cmd.bg_partial_rsrc_spec_hi != 0) + { + return Err(EINVAL); + } + Ok((packet, prefixes)) +} + +fn validate_compute_entry( + entry: &Entry<'_>, + range: &Range, +) -> Result { + let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; + let cmd = &packet; + if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 + || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base + || !inside( + cmd.cdm_ctrl_stream_base, + cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, + range, + ) + { + return Err(EINVAL); + } + // The G17P scratch layout and intersection tables: never on G16. + if cmd + .ts_end_copies + .iter() + .any(|ts| ts.handle != 0 || ts.offset != 0) + || packet.scs_layout != 0 + || packet.cdm_auxiliary_allocation != 0 + || packet.reserved != 0 + || packet.intersection_pool != 0 + || packet.intersection_pool_bytes != 0 + || packet.intersection_first != 0 + || packet.intersection_count != 0 + || packet.intersection_default_program != 0 + || packet.intersection_default_control != 0 + { + return Err(EINVAL); + } + Ok(packet) } /// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and @@ -693,20 +632,6 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { Ok((first, last - first)) } -/// Checks that `[start, end)` (rounded out to pages) is user memory mapped with the requested -/// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a -/// page without the access EACCES. -pub(crate) fn cover(vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { - let (first, size) = align_span(start, end)?; - if vm.covers_range(first, size, read, write) { - Ok(()) - } else if vm.covers_range(first, size, false, false) { - Err(EACCES) - } else { - Err(ENOENT) - } -} - /// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while /// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. struct SpanBatch { @@ -788,11 +713,16 @@ fn check_attachments( Ok(()) } -/// Parses the attachment list of a SET_*_ATTACHMENTS command. -fn attachment_list(bytes: &[u8]) -> Result> { +/// Parses the attachment list of a SET_*_ATTACHMENTS command, validating every entry in one pass. +fn attachment_list_checked( + bytes: &[u8], + range: &Range, +) -> Result> { let mut list = KVec::with_capacity(bytes.len() / ATTACHMENT_SIZE, GFP_KERNEL)?; for bytes in bytes.chunks_exact(ATTACHMENT_SIZE) { - list.push(Reader::new(bytes).read()?, GFP_KERNEL)?; + let attachment: uapi::drm_asahi_attachment = Reader::new(bytes).read()?; + validate_attachment(&attachment, range)?; + list.push(attachment, GFP_KERNEL)?; } Ok(list) } @@ -807,6 +737,25 @@ fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result Result { + let (first, size) = align_span(start, end)?; + if guard.covers_range(first, size, read, write) { + Ok(()) + } else if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + } +} + /// Whether a GVA can be named by a 32-bit compact pointer. fn compact(gva: u64) -> bool { (0x1000000000..0x9000000000).contains(&gva) @@ -1011,138 +960,292 @@ fn check_compute( gate::cdm(vm, context.usc_base, base, end) } -/// Resolves timestamps and exact historical-prefix dependencies of a valid stream -/// ([`check_stream`]) for a queue that accepted `accepted` render and compute commands before -/// this ioctl. -pub(crate) fn prepare<'a>( - bytes: &'a [u8], - accepted: [u64; 2], - objects: Pin<&xarray::XArray>>, -) -> Result> { - let mut resolved = Resolved::new(); - let mut orders = Orders::new(); - let mut preceding = [0u16; 2]; +/// Per-command barrier and stage-prefix metadata captured during single-pass parsing. +#[derive(Copy, Clone)] +struct OrderMeta { + barriers: [u16; 2], + prefixes: Option, +} + +/// Inline storage for 1-2 command barrier metadata records, spilling to a heap `KVec` above 2. +enum OrderMetas { + Empty, + One([OrderMeta; 1]), + Two([OrderMeta; 2]), + Heap(KVec), +} + +impl OrderMetas { + fn new() -> Self { + Self::Empty + } + + fn push(&mut self, meta: OrderMeta) -> Result { + match self { + Self::Heap(vec) => vec.push(meta, GFP_KERNEL)?, + Self::Two([a, b]) => { + let (a, b) = (*a, *b); + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + let _ = vec.push_within_capacity(a); + let _ = vec.push_within_capacity(b); + let _ = vec.push_within_capacity(meta); + *self = Self::Heap(vec); + } + Self::One([a]) => *self = Self::Two([*a, meta]), + Self::Empty => *self = Self::One([meta]), + } + Ok(()) + } +} + +impl core::ops::Deref for OrderMetas { + type Target = [OrderMeta]; + + fn deref(&self) -> &[OrderMeta] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Two(items) => items, + Self::Heap(vec) => vec, + } + } +} + +/// Tracks the active attachment list during single-pass parsing so the first consuming command +/// takes ownership without copying, while later commands sharing the same list clone from it. +enum AttachmentState { + Empty, + Fresh(KVec), + FromCommand(usize), +} + +/// A structurally valid, decoded command stream before timestamp/ordinal resolution and VM checks. +pub(crate) struct ParsedStream { + commands: Commands, + meta: OrderMetas, + counts: [u64; 2], +} + +/// Structurally validates and decodes a command stream in a single pass, before anything is +/// looked up or device state is consulted. +pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { + if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { + return Err(EINVAL); + } + let range = hw::USER_RANGE; + let mut counts = [0u32; 2]; + let mut commands = Commands::new(); + let mut meta = OrderMetas::new(); + let mut vertex = AttachmentState::Empty; + let mut fragment = AttachmentState::Empty; + let mut compute = AttachmentState::Empty; + for entry in stream(bytes) { let entry = entry?; - let (outputs, engine, prior, prefixes) = match entry.kind { + match entry.kind { + SET_VERTEX_ATTACHMENTS | SET_FRAGMENT_ATTACHMENTS | SET_COMPUTE_ATTACHMENTS => { + validate_attachments_header(&entry)?; + let list = attachment_list_checked(entry.payload, &range)?; + let state = if list.is_empty() { + AttachmentState::Empty + } else { + AttachmentState::Fresh(list) + }; + match entry.kind { + SET_VERTEX_ATTACHMENTS => vertex = state, + SET_FRAGMENT_ATTACHMENTS => fragment = state, + SET_COMPUTE_ATTACHMENTS => compute = state, + _ => {} + } + continue; + } + _ => {} + } + if (entry.barriers[RENDER] != NONE && u32::from(entry.barriers[RENDER]) > counts[RENDER]) + || (entry.barriers[COMPUTE] != NONE + && u32::from(entry.barriers[COMPUTE]) > counts[COMPUTE]) + { + return Err(EINVAL); + } + let next_idx = commands.len(); + match entry.kind { CMD_RENDER => { - let (packet, prefixes) = render_payload(entry.payload)?; - let outputs = crate::timestamp::Destinations::resolve_aligned( - objects, - &[packet.ts_vtx, packet.ts_frag], - )?; - (outputs, RENDER, [packet.prior_vdm, packet.prior_cdm], prefixes) + let (packet, prefixes) = validate_render_entry(&entry, counts, early_tiling)?; + counts[RENDER] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let take_render = |state: &mut AttachmentState, is_fragment: bool| { + match core::mem::replace(state, AttachmentState::Empty) { + AttachmentState::Empty => Ok(KVec::new()), + AttachmentState::Fresh(list) => { + *state = AttachmentState::FromCommand(next_idx); + Ok(list) + } + AttachmentState::FromCommand(prev_idx) => { + *state = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Render(prev) => { + let src = if is_fragment { + &prev.fragment_attachments + } else { + &prev.vertex_attachments + }; + copy_list(&[src]) + } + Command::Compute(_) => Err(EINVAL), + } + } + } + }; + let vertex_attachments = take_render(&mut vertex, false)?; + let fragment_attachments = take_render(&mut fragment, true)?; + commands.push(Command::Render(KBox::new( + RenderCommand { + cmd: packet, + timestamp_outputs: crate::timestamp::Destinations::empty(), + vertex_attachments, + fragment_attachments, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes, + })?; } CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let outputs = - crate::timestamp::Destinations::resolve_aligned(objects, &[packet.ts])?; - (outputs, COMPUTE, [packet.prior_vdm, packet.prior_cdm], None) + let packet = validate_compute_entry(&entry, &range)?; + counts[COMPUTE] += 1; + if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { + return Err(EINVAL); + } + let attachments = match core::mem::replace(&mut compute, AttachmentState::Empty) { + AttachmentState::Empty => KVec::new(), + AttachmentState::Fresh(list) => { + compute = AttachmentState::FromCommand(next_idx); + list + } + AttachmentState::FromCommand(prev_idx) => { + compute = AttachmentState::FromCommand(prev_idx); + match &commands[prev_idx] { + Command::Compute(prev) => copy_list(&[&prev.attachments])?, + Command::Render(_) => return Err(EINVAL), + } + } + }; + commands.push(Command::Compute(KBox::new( + ComputeCommand { + cmd: packet, + attachments, + timestamp_outputs: crate::timestamp::Destinations::empty(), + query_access: packet.flags & COMPUTE_NO_QUERY_ACCESS == 0, + }, + GFP_KERNEL, + )?))?; + meta.push(OrderMeta { + barriers: entry.barriers, + prefixes: None, + })?; } - _ => continue, - }; - resolved.push(outputs)?; - let mut order = Order::new(accepted, preceding, entry.barriers, prior, engine)?; - if let Some(prefixes) = prefixes { - let tiling = Order::new( - accepted, - preceding, - [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], - [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], - RENDER, - )?; - order.narrow_tiling(&tiling)?; + _ => return Err(EINVAL), } - orders.push(order)?; - preceding[engine] += 1; } - - Ok(Prepared { - bytes, - resolved, - orders, - counts: [u64::from(preceding[RENDER]), u64::from(preceding[COMPUTE])], + if counts == [0; 2] { + return Err(EINVAL); + } + Ok(ParsedStream { + commands, + meta, + counts: [u64::from(counts[RENDER]), u64::from(counts[COMPUTE])], }) } -impl Prepared<'_> { +impl ParsedStream { + /// Resolves timestamps in place and computes exact historical-prefix dependencies for a queue + /// that accepted `accepted` render and compute commands before this ioctl. + pub(crate) fn prepare( + mut self, + accepted: [u64; 2], + objects: Pin<&xarray::XArray>>, + ) -> Result { + let mut orders = Orders::new(); + let mut preceding = [0u16; 2]; + for (command, meta) in self.commands.iter_mut().zip(self.meta.iter()) { + let (engine, prior) = match command { + Command::Render(render) => { + render.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[render.cmd.ts_vtx, render.cmd.ts_frag], + )?; + (RENDER, [render.cmd.prior_vdm, render.cmd.prior_cdm]) + } + Command::Compute(compute) => { + compute.timestamp_outputs = crate::timestamp::Destinations::resolve_aligned( + objects, + &[compute.cmd.ts], + )?; + (COMPUTE, [compute.cmd.prior_vdm, compute.cmd.prior_cdm]) + } + }; + let mut order = Order::new(accepted, preceding, meta.barriers, prior, engine)?; + if let Some(prefixes) = meta.prefixes { + let tiling = Order::new( + accepted, + preceding, + [prefixes.ta_vdm_barrier, prefixes.ta_cdm_barrier], + [prefixes.ta_prior_vdm, prefixes.ta_prior_cdm], + RENDER, + )?; + order.narrow_tiling(&tiling)?; + } + orders.push(order)?; + preceding[engine] += 1; + } + Ok(Prepared { + commands: self.commands, + orders, + counts: self.counts, + }) + } +} + +impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. pub(crate) fn validate(self, context: &Context<'_>) -> Result { let Prepared { - bytes, - mut resolved, + commands, orders, counts, } = self; - let mut commands = Commands::new(); - let mut vertex = KVec::new(); - let mut fragment = KVec::new(); - let mut compute = KVec::new(); + if commands.is_empty() { + return Err(EINVAL); + } let mut batch = SpanBatch::new(); let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; let mut vdm_count = 0usize; - let mut rem_renders = counts[RENDER]; - let mut rem_computes = counts[COMPUTE]; - for entry in stream(bytes) { - let entry = entry?; - match entry.kind { - SET_VERTEX_ATTACHMENTS => vertex = attachment_list(entry.payload)?, - SET_FRAGMENT_ATTACHMENTS => fragment = attachment_list(entry.payload)?, - SET_COMPUTE_ATTACHMENTS => compute = attachment_list(entry.payload)?, - CMD_RENDER => { - let (packet, _) = render_payload(entry.payload)?; - let cmd = &packet; - let outputs = resolved.next().ok_or(EINVAL)?; - check_render(&mut batch, context, cmd, &vertex, &fragment)?; + for command in commands.iter() { + match command { + Command::Render(render) => { + check_render( + &mut batch, + context, + &render.cmd, + &render.vertex_attachments, + &render.fragment_attachments, + )?; if vdm_count >= vdm_vas.len() { return Err(EINVAL); } - vdm_vas[vdm_count] = cmd.vdm_ctrl_stream_base; + vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; vdm_count += 1; - rem_renders = rem_renders.checked_sub(1).ok_or(EINVAL)?; - let (vertex_attachments, fragment_attachments) = if rem_renders == 0 { - (core::mem::take(&mut vertex), core::mem::take(&mut fragment)) - } else { - (copy_list(&[&vertex])?, copy_list(&[&fragment])?) - }; - commands.push(Command::Render(KBox::new( - RenderCommand { - cmd: *cmd, - timestamp_outputs: outputs, - vertex_attachments, - fragment_attachments, - }, - GFP_KERNEL, - )?))?; } - CMD_COMPUTE => { - let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; - let cmd = &packet; - check_compute(&mut batch, context, cmd, &compute)?; - let outputs = resolved.next().ok_or(EINVAL)?; - rem_computes = rem_computes.checked_sub(1).ok_or(EINVAL)?; - let attachments = if rem_computes == 0 { - core::mem::take(&mut compute) - } else { - copy_list(&[&compute])? - }; - commands.push(Command::Compute(KBox::new( - ComputeCommand { - cmd: *cmd, - attachments, - timestamp_outputs: outputs, - query_access: cmd.flags & COMPUTE_NO_QUERY_ACCESS == 0, - }, - GFP_KERNEL, - )?))?; + Command::Compute(compute) => { + check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; } - _ => return Err(EINVAL), } } - if commands.is_empty() { - return Err(EINVAL); - } batch.flush(context.vm)?; gate::vdm_batch(context.vm, &vdm_vas[..vdm_count])?; Ok(Submission { diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 94d3580aa32e29..2798f8fc313ae6 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -17,7 +17,7 @@ use core::sync::atomic::{AtomicU32, Ordering}; use kernel::prelude::*; -use super::{command::cover, command::USC_WINDOW, params}; +use super::{command::cover_locked, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; @@ -57,8 +57,8 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page - /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mmu::Vm, va: u64, count: usize) -> Result<[u32; 10]> { + /// unless the record crosses it) under an already-held VM read lock. Unreadable memory: EFAULT. + fn words(&mut self, guard: &mut mmu::VmReadGuard, va: u64, count: usize) -> Result<[u32; 10]> { let n = count.checked_mul(4).filter(|&n| n <= 40).ok_or(EINVAL)?; let end = va.checked_add(n as u64).ok_or(EINVAL)?; let cached = self.len != 0 && va >= self.va && end <= self.va + self.len as u64; @@ -66,9 +66,10 @@ impl Window { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); let len = n.max(self.bytes.len().min(in_page)); let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; - cover(vm, va, cover_end, true, false)?; + cover_locked(guard, va, cover_end, true, false)?; self.len = 0; - vm.read_user(va, &mut self.bytes[..len]) + guard + .read_user(va, &mut self.bytes[..len]) .map_err(|_| EFAULT)?; self.va = va; self.len = len; @@ -87,7 +88,12 @@ impl Window { /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// `checked` caches the last proven program page. -fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> Result { +fn program( + guard: &mut mmu::VmReadGuard, + usc: u64, + address: u64, + checked: &mut Option, +) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -96,7 +102,7 @@ fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> R if *checked == Some(page) { return Ok(()); } - cover(vm, address, address + 64, true, false)?; + cover_locked(guard, address, address + 64, true, false)?; *checked = Some(page); Ok(()) } @@ -161,6 +167,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { let mut power = 1u64; let mut first = true; let mut resched = 0; + let mut guard: Option = None; loop { if first { first = false; @@ -176,10 +183,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } } if resched == 0 { - // No VM lock is held between reads. Keep a long userspace stream - // preemptible and allow its submitting task to be interrupted. + // Release the VM lock and clear cached window/program proofs before + // rescheduling so any mapping change while unlocked is re-verified. // might_sleep() includes might_resched() (cond_resched on voluntary kernels). // It is a real scheduling point, not only a debug assertion. + guard = None; + window.len = 0; + checked = None; kernel::task::might_sleep(); if kernel::current!().signal_pending() { return Err(ERESTARTSYS); @@ -187,6 +197,10 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { resched = CDM_RESCHED_RECORDS; } resched -= 1; + let guard = match guard.as_mut() { + Some(guard) => guard, + None => guard.insert(vm.read_lock().map_err(|_| EFAULT)?), + }; let root_bytes = |va: u64, bytes: u64| -> Result { if !linked && (va < base || va.checked_add(bytes).is_none_or(|at| at > end)) { return Err(EINVAL); @@ -194,7 +208,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { Ok(()) }; root_bytes(va, 4)?; - let w = window.words(vm, va, 1)?; + let w = window.words(guard, va, 1)?; if w[0] == CDM_TERMINATE { return Ok(()); } @@ -214,7 +228,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } if w[0] & 0xffff0000 == CDM_LINK { root_bytes(va, 8)?; - let w = window.words(vm, va, 2)?; + let w = window.words(guard, va, 2)?; let target = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); if target & 3 != 0 || target == va { return Err(reject("CDM link", va, &w)); @@ -234,9 +248,9 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { _ => return Err(reject("CDM launch mode", va, &w)), }; root_bytes(va, (words * 4) as u64)?; - let w = window.words(vm, va, words)?; + let w = window.words(guard, va, words)?; let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); - match program(vm, usc, address, &mut checked) { + match program(guard, usc, address, &mut checked) { Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), result => result?, } @@ -256,8 +270,8 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { if indirect & 3 != 0 { return Err(reject("CDM indirect parameters", va, &w)); } - cover( - vm, + cover_locked( + guard, indirect, indirect.checked_add(bytes).ok_or(EINVAL)?, true, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e0019b9bab0d57..5f03b4337bb493 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -386,9 +386,15 @@ impl Shared { } /// Disarms the completion hrtimer when idle or entering system sleep. + /// + /// Always takes `resnap_handle` rather than checking a lock-free shadow flag so + /// `sleep::join_workers()` strictly orders with any concurrent `rearm()`: `sleep_down()` + /// stores `sleeping = true` before calling `cancel_resnap()`, and `rearm()` re-checks + /// `sleeping` under `resnap_handle.lock()` before installing a new handle. pub(crate) fn cancel_resnap(&self) { + let mut handle = self.resnap_handle.lock(); self.resnap_deadline_ns.store(0, Ordering::Release); - drop(self.resnap_handle.lock().take()); + drop(handle.take()); } /// Queues the backup poll on `system_highpri_wq` after `delay` jiffies, or moves an already @@ -413,6 +419,9 @@ impl Shared { /// 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) { + if self.sleeping.load(Ordering::Acquire) { + return; + } let mut us = params::resnap_us(); if soon && module_parameters::g16_repoll_us.value() != 0 { us = params::repoll_us(); @@ -422,9 +431,15 @@ impl Shared { 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(); - drop(handle.take()); - self.resnap_deadline_ns.store(target_ns, Ordering::Release); - *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + if self.sleeping.load(Ordering::Acquire) { + return; + } + 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 { + drop(handle.take()); + self.resnap_deadline_ns.store(target_ns, Ordering::Release); + *handle = Some(self.clone().start(Delta::from_micros(i64::from(us)))); + } } let backup_ns = self.backup_deadline_ns.load(Ordering::Acquire); if now >= backup_ns { diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 5150716b563d17..81da0703496cb3 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -203,14 +203,14 @@ impl Queue { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } - command::check_stream(bytes, params::early_tiling())?; + let parsed = command::parse_stream(bytes, params::early_tiling())?; if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } if self.vm.status.get() != 0 { return Err(EIO); } - let prepared = command::prepare(bytes, self.accepted, objects)?; + let prepared = parsed.prepare(self.accepted, objects)?; // The job reference first, so that the mappings checked below stay retained. let guard = self.vm.vm.retain_first_job()?; let submission = prepared.validate(&command::Context { diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 59533ae47e2bb9..d2935c1423e352 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -510,7 +510,6 @@ pub(crate) struct VmReadGuard(VmExecGuard); #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] impl VmReadGuard { - #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 7118cffde33013..04c0cc1162610b 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -203,6 +203,12 @@ pub(crate) struct Destinations(Option Self { + Self(None) + } + /// No timestamp is written for this command. #[allow(dead_code)] pub(crate) fn is_empty(&self) -> bool { 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 e654fbbb95bedf..b4e607ee01aebc 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 @@ -51,6 +51,21 @@ if errors: raise RuntimeError('Kernel UAPI ABI differs from the M5 bindings: ' + json.dumps(errors)) command = SOURCE.read_text() +queue_src = (SOURCE.parent / 'queue.rs').read_text() +poll_src = (SOURCE.parent / 'poll.rs').read_text() +assert 'command::parse_stream(bytes, params::early_tiling())?' in queue_src +assert 'parsed.prepare(self.accepted, objects)?' in queue_src +assert 'command::check_stream(' not in queue_src +parse_idx = command.index('pub(crate) fn parse_stream(') +prep_idx = command.index('impl ParsedStream {') +assert 'stream(bytes)' in command[parse_idx:prep_idx] +assert 'stream(bytes)' not in command[prep_idx:] +assert 'resnap_has_handle' not in poll_src +assert 'let mut handle = self.resnap_handle.lock();' in poll_src +assert 'if self.sleeping.load(Ordering::Acquire)' in poll_src +assert 'fn check_stream(' not in command +assert 'fn cover(' not in command +assert 'enum Resolved' not in command hardware = (SOURCE.parent / 'hw.rs').read_text() capacities = '\n'.join(re.findall(r'pub\(crate\) const (?:TPC_SIZE|TILEMAP_SIZE): u64 = .*?;', hardware)) names = ['drm_asahi_cmd_header', 'drm_asahi_attachment', 'drm_asahi_cmd_render', @@ -58,8 +73,13 @@ 'drm_asahi_timestamp', 'drm_asahi_timestamps', 'drm_asahi_helper_program', 'drm_asahi_render_ray_query_stage'] constants = command[command.index('/// Largest command buffer.'):command.index('/// A validated render command.')] +parse_types = command[command.index('/// A validated render command.'):command.index('/// Inline storage for the common 1-2 command ordinals')] inline_containers = command[command.index('/// Inline storage for the common 1-2 command submission'):command.index('/// A validated SUBMIT.')] -parser = command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] +parser = ( + command[command.index('/// One command of the stream.'):command.index('/// Checks that `[start, end)`')] + + command[command.index('/// Parses the attachment list'):command.index('/// Checks that `[start, end)` (rounded out to pages) is user memory mapped')] + + command[command.index('/// Per-command barrier and stage-prefix metadata'):command.index('impl ParsedStream {')] +) render_admission = ( command[command.index('/// Checks that `[start, end)`'):command.index('/// Parses the attachment list')] + command[command.index('/// Whether a GVA can be named by a 32-bit compact pointer.'):command.index('/// Per-command compute admission.')] @@ -77,12 +97,29 @@ const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const E2BIG: i32 = -7; +const GFP_KERNEL: u32 = 0; struct Error; impl Error { fn from_errno(error:i32)->i32 { error } } extern crate self as kernel; // The parser logs why it refuses a command; check the format arguments, print nothing. macro_rules! pr_warn { ($($arg:tt)*) => {{ let _ = format_args!($($arg)*); }}; } pub mod bindings { pub const EOPNOTSUPP:i32=95; } pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=-7; } +pub(crate) mod timestamp { + pub(crate) struct Destinations; + impl Destinations { pub(crate) const fn empty() -> Self { Self } } +} +pub(crate) struct KBox(Box); +impl KBox { fn new(v: T, _: u32) -> Result { Ok(Self(Box::new(v))) } } +impl core::ops::Deref for KBox { type Target = T; fn deref(&self) -> &T { &self.0 } } +pub(crate) struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(cap: usize, _: u32) -> Result { Ok(Self(Vec::with_capacity(cap))) } + fn push(&mut self, v: T, _: u32) -> Result { self.0.push(v); Ok(()) } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { self.0.push(v); Ok(()) } +} +impl core::ops::Deref for KVec { type Target = [T]; fn deref(&self) -> &[T] { &self.0 } } +impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } } mod uapi { include!("FULL_UAPI"); } mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } mod hw { @@ -98,9 +135,13 @@ READER IMPLS PRODUCTION_CONSTANTS +PARSE_TYPES PRODUCTION_PARSER +fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { + parse_stream(bytes, early_tiling).map(|_| ()) +} mod g17 { - use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, offset_of, Range}; + use super::{uapi, AnyBitPattern, Reader, Result, EINVAL, size_of, Range}; G17_CONSTANTS const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; @@ -548,15 +589,17 @@ type Target = [T]; fn deref(&self) -> &[T] { &self.0 } } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } INLINE_CONTAINERS #[test] - fn inline_commands_orders_and_resolved_skip_heap_up_to_two_and_spill_safely() { + fn inline_commands_and_orders_skip_heap_up_to_two_and_spill_safely() { ALLOCS.with(|a| a.set(0)); let mut cmds = Commands::new(); let mut orders = Orders::new(); - let mut resolved = Resolved::new(); let o0 = Order::new([0, 0], [0, 0], [NONE; 2], [0; 2], COMPUTE).unwrap(); let o1 = Order::new([0, 0], [0, 1], [NONE; 2], [0; 2], RENDER).unwrap(); let o2 = Order::new([0, 0], [1, 1], [NONE; 2], [0; 2], COMPUTE).unwrap(); @@ -564,8 +607,6 @@ cmds.push(Command(2)).unwrap(); orders.push(o0).unwrap(); orders.push(o1).unwrap(); - resolved.push(timestamp::Destinations(11)).unwrap(); - resolved.push(timestamp::Destinations(22)).unwrap(); assert_eq!(ALLOCS.with(|a| a.get()), 0); assert_eq!(&*cmds, &[Command(1), Command(2)]); assert_eq!(&*orders, &[o0, o1]); @@ -577,21 +618,14 @@ FAIL_NEXT.with(|f| f.set(true)); assert_eq!(orders.push(o2), Err(ENOMEM)); assert_eq!(&*orders, &[o0, o1]); - FAIL_NEXT.with(|f| f.set(true)); - assert_eq!(resolved.push(timestamp::Destinations(33)), Err(ENOMEM)); assert_eq!(ALLOCS.with(|a| a.get()), 0); - // Spill to heap preserves exact FIFO order across all 3 containers. + // Spill to heap preserves exact FIFO order across both containers. cmds.push(Command(3)).unwrap(); orders.push(o2).unwrap(); - resolved.push(timestamp::Destinations(33)).unwrap(); - assert_eq!(ALLOCS.with(|a| a.get()), 3); + assert_eq!(ALLOCS.with(|a| a.get()), 2); assert_eq!(&*cmds, &[Command(1), Command(2), Command(3)]); assert_eq!(&*orders, &[o0, o1, o2]); - assert_eq!(resolved.next(), Some(timestamp::Destinations(11))); - assert_eq!(resolved.next(), Some(timestamp::Destinations(22))); - assert_eq!(resolved.next(), Some(timestamp::Destinations(33))); - assert_eq!(resolved.next(), None); } } mod render_admission_tests { @@ -812,7 +846,8 @@ 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), 'FW_WORK': str(SOURCE.parent/'fw/work.rs'), 'FULL_ENCODER': str(SOURCE.parent/'encode.rs'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), - 'PRODUCTION_CONSTANTS': constants, 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'PRODUCTION_CONSTANTS': constants, 'PARSE_TYPES': parse_types, + 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), 'RENDER_ADMISSION': render_admission.replace('super::vm::', 'vm::').replace('super::params::', 'params::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 2e3a44450f4b94..7135221e2594f2 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -787,6 +787,157 @@ def item(declaration, text=source): assert_eq!(ring.ring.reads.get(), 21); } } + +mod resnap_sync_test { + use std::sync::{ + Arc, Barrier, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }; + + const BACKUP_REARM_NS: u64 = 1_000_000; + static CLOCK: AtomicU64 = AtomicU64::new(0); + fn now_ns() -> u64 { + CLOCK.load(Ordering::Acquire) + } + + mod params { + pub fn resnap_us() -> u32 { + 100 + } + pub fn repoll_us() -> u32 { + 25 + } + } + #[allow(non_upper_case_globals)] + mod module_parameters { + pub struct Param(u32); + impl Param { + pub fn value(&self) -> u32 { + self.0 + } + } + pub static g16_repoll_us: Param = Param(25); + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + struct Delta(i64); + impl Delta { + fn from_micros(us: i64) -> Self { + Self(us) + } + } + + struct Handle { + drops: Arc, + } + impl Drop for Handle { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::AcqRel); + } + } + + struct Lock(Mutex); + impl Lock { + fn new(v: T) -> Self { + Self(Mutex::new(v)) + } + fn lock(&self) -> std::sync::MutexGuard<'_, T> { + self.0.lock().unwrap() + } + } + + struct Shared { + sleeping: AtomicBool, + resnap_deadline_ns: AtomicU64, + backup_deadline_ns: AtomicU64, + resnap_handle: Lock>, + starts: AtomicU32, + drops: Arc, + mod_polls: AtomicU32, + } + + impl Shared { + fn new() -> Arc { + Arc::new(Self { + sleeping: AtomicBool::new(false), + resnap_deadline_ns: AtomicU64::new(0), + backup_deadline_ns: AtomicU64::new(0), + resnap_handle: Lock::new(None), + starts: AtomicU32::new(0), + drops: Arc::new(AtomicU32::new(0)), + mod_polls: AtomicU32::new(0), + }) + } + fn start(self: Arc, _delta: Delta) -> Handle { + self.starts.fetch_add(1, Ordering::AcqRel); + Handle { + drops: self.drops.clone(), + } + } + fn mod_poll(self: &Arc, _delay: u64) { + self.mod_polls.fetch_add(1, Ordering::AcqRel); + } + + __CANCEL_RESNAP__ + __REARM__ + } + + #[test] + fn resnap_rearm_coalesces_and_cancel_disarms_unconditionally() { + CLOCK.store(100_000, Ordering::Release); + let shared = Shared::new(); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 200_000); + assert!(shared.resnap_handle.lock().is_some()); + + // Same-window rearm coalesces without cancelling/restarting the handle. + CLOCK.store(102_000, Ordering::Release); + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Sooner repoll (>5 us earlier) replaces the handle cleanly. + shared.rearm(true); + assert_eq!(shared.starts.load(Ordering::Acquire), 2); + assert_eq!(shared.drops.load(Ordering::Acquire), 1); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 127_000); + + // cancel_resnap unconditionally clears deadline and drops handle. + shared.cancel_resnap(); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + assert!(shared.resnap_handle.lock().is_none()); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + } + + #[test] + fn sleep_cancel_resnap_never_leaves_handle_armed_under_concurrent_rearm() { + CLOCK.store(1_000_000, Ordering::Release); + for _ in 0..200 { + let shared = Shared::new(); + shared.rearm(false); + let start = Arc::new(Barrier::new(2)); + let s1 = shared.clone(); + let b1 = start.clone(); + let t = std::thread::spawn(move || { + b1.wait(); + for _ in 0..32 { + s1.rearm(true); + } + }); + start.wait(); + // Exact sleep_down() + join_workers() sequence: sleeping = true, then cancel_resnap(). + shared.sleeping.store(true, Ordering::Release); + shared.cancel_resnap(); + t.join().unwrap(); + assert!( + shared.resnap_handle.lock().is_none(), + "rearm leaked an hrtimer handle past sleep_down() + cancel_resnap()" + ); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + } + } +} ''' for token, decl in { @@ -794,6 +945,8 @@ def item(declaration, text=source): '__POLL_STEP__': 'pub(crate) fn poll_step(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', + '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', + '__REARM__': 'pub(crate) fn rearm(', }.items(): harness = harness.replace(token, item(decl)) for token, decl in { @@ -819,7 +972,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 10, + 'tests': 12, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index c70f563174ac30..22970b5b9a4388 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -51,10 +51,17 @@ pub lock_calls: std::cell::Cell, pub read_calls: std::cell::Cell, } - pub struct VmReadGuard<'a>(&'a Vm); - impl VmReadGuard<'_> { + pub struct VmReadGuard(*const Vm); + impl VmReadGuard { + pub fn covers_range(&mut self, address: u64, size: u64, _read: bool, _write: bool) -> bool { + let vm = unsafe { &*self.0 }; + address + .checked_add(size) + .is_some_and(|end| vm.contains(address, end)) + } pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { - self.0.read_user(va, out) + let vm = unsafe { &*self.0 }; + vm.read_user(va, out) } } impl Vm { @@ -65,9 +72,9 @@ self.regions.iter().any(|r| r.readable && va >= r.base && end >= va && end <= r.base + r.bytes.len() as u64) } - pub fn read_lock(&self) -> Result> { + pub fn read_lock(&self) -> Result { self.lock_calls.set(self.lock_calls.get() + 1); - Ok(VmReadGuard(self)) + Ok(VmReadGuard(self as *const Vm)) } pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { self.read_calls.set(self.read_calls.get() + 1); @@ -94,7 +101,13 @@ } pub fn reset_cover_calls() { COVER_CALLS.with(|c| c.set(0)); } pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } - pub fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + pub fn cover_locked( + guard: &mut mmu::VmReadGuard, + start: u64, + end: u64, + read: bool, + write: bool, + ) -> Result { COVER_CALLS.with(|c| c.set(c.get() + 1)); if end <= start || start < 0x4000 || end > (1u64 << 42) - 0x8000 { return Err(EINVAL); @@ -103,7 +116,7 @@ || start < 0x1000010000 && end > 0x1000000000 { return Err(EACCES); } - if vm.contains(start, end) { Ok(()) } else { Err(EFAULT) } + if guard.covers_range(start, end - start, read, write) { Ok(()) } else { Err(EFAULT) } } } #[path = "PRODUCTION_SOURCE"] pub mod gate; @@ -318,6 +331,36 @@ assert_eq!(vm.lock_calls.get(), 1); assert_eq!(vm.read_calls.get(), 3); } +#[test] +fn cdm_batches_vm_read_lock_and_releases_on_resched() { + let target = 0x600000000u64; + let mut root = Vec::new(); + root.extend(launch(0, USC, 0)); + root.extend(launch(1, USC + 0x80, 0x400000000)); + root.extend(launch(2, USC + 0x100, 0x400000040)); + root.extend([0x20000000 | (target >> 32) as u32, target as u32]); + let mut vm = vm_for(&root); + let mut linked_words = launch(0, USC + 0x4000, 0); + linked_words.push(0x40000000); + let mut linked = bytes(&linked_words); + linked.resize(0x4000, 0); + vm.region(target, linked); + vm.region(USC + 0x4000, vec![0; 0x4000]); + + // Multi-launch mode 0/1/2 + linked segment acquires the VM read lock only once. + assert!(g16::gate::cdm(&vm, USC, BASE, BASE + root.len() as u64 * 4).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + + // Streams longer than CDM_RESCHED_RECORDS (1024) drop and re-acquire the lock on each resched. + let mut long = vec![0x60000160; 2500]; + long.push(0x40000000); + let long_vm = vm_for(&long); + let sched_before = kernel::task::scheduled(); + assert!(g16::gate::cdm(&long_vm, USC, BASE, BASE + long.len() as u64 * 4).is_ok()); + let sched_delta = kernel::task::scheduled() - sched_before; + assert_eq!(sched_delta, 3); + assert_eq!(long_vm.lock_calls.get(), sched_delta); +} ''' with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: @@ -331,7 +374,7 @@ (OUT / 'stream-gate-host.log').write_text(result.stdout + result.stderr) (OUT / 'stream-gate-host.json').write_text(json.dumps({ 'source': str(SOURCE), 'sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result': 'pass', 'test_groups': 10, + 'result': 'pass', 'test_groups': 11, 'mesa_sources': ['src/asahi/genxml/agx3_cmdstream.h', 'src/asahi/lib/agx3_cdm_decode_core.c', 'src/asahi/lib/agx_vdm_barrier_core.c'], 'limitations': 'Host VM model validates parser, addresses, cycles and interruption; hardware and kernel cache behavior require target tests.' From 2e29ad63a6fbfbf23f23eaf881152bb254d7f61e Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:16:56 -0500 Subject: [PATCH 0841/1514] drm/asahi: g16: batch multi-pass render validation and publication Multi-pass render frames (shadow maps, deferred G-buffer + lighting, post-processing, and Zink multi-pass submits) currently pay per-pass VM span coverage locks, per-pass VDM root reads, and per-pass TA/FS ring publications with individual SubmitRecords and UMA submitted counter updates. Batch validation and publication across consecutive render passes within a single SUBMIT without delaying fence completion for separate jobs: - Lift SpanBatch to Prepared::validate() so render passes within a SUBMIT deduplicate shared VM spans and flush coverage in one lock acquisition, and replace gate::vdm() with gate::vdm_batch() to verify all render VDM root words under a single Vm::read_lock() with a 256-byte intra-page read window. - Add ordered multi-pass slot tracking (Claims::pass_count), replace PoolSet::publish() with PoolSet::publish_batch() (submitted += 2 * renders), and add Job::can_fold_render_cmd() so consecutive ready non-InitBM render passes in one SUBMIT fold into a single Flight, one TA/FS producer advance, one SubmitRecord kick, and one UMA submitted update while preserving exact per-pass barriers (wait_stamp_for_with), recovery matching (r_ta_stamp/r_fs_stamp), per-pass scene ITS verification, and ordered pass-slot retirement. - Add host selftests covering batched VDM root admission, submit-wide span deduplication, ordered wrapped multi-pass retirement and publish_batch(), same-batch render wait stamps, can_fold_render_cmd, and interior render-stamp recovery preparation. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 33 +- drivers/gpu/drm/asahi/g16/engine.rs | 338 ++++++++++++++---- drivers/gpu/drm/asahi/g16/gate.rs | 34 +- drivers/gpu/drm/asahi/g16/job.rs | 35 ++ drivers/gpu/drm/asahi/g16/poll.rs | 27 +- drivers/gpu/drm/asahi/g16/pools.rs | 12 +- drivers/gpu/drm/asahi/g16/slots.rs | 55 ++- .../gpu/asahi-m4/test-command-stream.py | 75 +++- .../drivers/gpu/asahi-m4/test-publication.py | 253 +++++++++++-- .../drivers/gpu/asahi-m4/test-resources.py | 75 +++- .../drivers/gpu/asahi-m4/test-stream-gate.py | 59 ++- 11 files changed, 848 insertions(+), 148 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 8ded81f21bd467..e7cad14e4afe3f 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -888,8 +888,10 @@ fn check_zls_plane( Ok(()) } -/// Per-command render admission. +/// Per-command render admission. Pushes VM spans into `batch` so a multi-pass SUBMIT flushes +/// coverage once across all passes. fn check_render( + batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_render, vertex: &[uapi::drm_asahi_attachment], @@ -936,7 +938,6 @@ fn check_render( if vdm & 3 != 0 || !compact(vdm) || scissor == 0 || scissor & 3 != 0 { return Err(EINVAL); } - let mut batch = SpanBatch::new(); batch.push(vm, vdm, vdm + 4, true, false)?; batch.push( vm, @@ -977,17 +978,16 @@ fn check_render( false, )?; } - check_zls_plane(&mut batch, context, cmd, false)?; - check_zls_plane(&mut batch, context, cmd, true)?; - check_attachments(&mut batch, vm, vertex, true)?; - check_attachments(&mut batch, vm, fragment, true)?; - batch.flush(vm)?; - gate::vdm(vm, vdm)?; + check_zls_plane(batch, context, cmd, false)?; + check_zls_plane(batch, context, cmd, true)?; + check_attachments(batch, vm, vertex, true)?; + check_attachments(batch, vm, fragment, true)?; Ok(()) } /// Per-command compute admission. fn check_compute( + batch: &mut SpanBatch, context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], @@ -1005,9 +1005,8 @@ fn check_compute( { return Err(EINVAL); } - let mut batch = SpanBatch::new(); batch.push(vm, base, end, true, false)?; - check_attachments(&mut batch, vm, attachments, true)?; + check_attachments(batch, vm, attachments, true)?; batch.flush(vm)?; gate::cdm(vm, context.usc_base, base, end) } @@ -1080,6 +1079,9 @@ impl Prepared<'_> { let mut vertex = KVec::new(); let mut fragment = KVec::new(); let mut compute = KVec::new(); + let mut batch = SpanBatch::new(); + let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; + let mut vdm_count = 0usize; let mut rem_renders = counts[RENDER]; let mut rem_computes = counts[COMPUTE]; for entry in stream(bytes) { @@ -1092,7 +1094,12 @@ impl Prepared<'_> { let (packet, _) = render_payload(entry.payload)?; let cmd = &packet; let outputs = resolved.next().ok_or(EINVAL)?; - check_render(context, cmd, &vertex, &fragment)?; + check_render(&mut batch, context, cmd, &vertex, &fragment)?; + if vdm_count >= vdm_vas.len() { + return Err(EINVAL); + } + vdm_vas[vdm_count] = cmd.vdm_ctrl_stream_base; + vdm_count += 1; rem_renders = rem_renders.checked_sub(1).ok_or(EINVAL)?; let (vertex_attachments, fragment_attachments) = if rem_renders == 0 { (core::mem::take(&mut vertex), core::mem::take(&mut fragment)) @@ -1112,7 +1119,7 @@ impl Prepared<'_> { CMD_COMPUTE => { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; - check_compute(context, cmd, &compute)?; + check_compute(&mut batch, context, cmd, &compute)?; let outputs = resolved.next().ok_or(EINVAL)?; rem_computes = rem_computes.checked_sub(1).ok_or(EINVAL)?; let attachments = if rem_computes == 0 { @@ -1136,6 +1143,8 @@ impl Prepared<'_> { if commands.is_empty() { return Err(EINVAL); } + batch.flush(context.vm)?; + gate::vdm_batch(context.vm, &vdm_vas[..vdm_count])?; Ok(Submission { counts, commands, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 75a51c320912fd..aae0c7a57f79cf 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -222,6 +222,9 @@ pub(crate) struct Flight { pub(crate) cstamp: [u32; sizes::COMPUTE_SLOTS], pub(crate) cwait: [u32; sizes::COMPUTE_SLOTS], pub(crate) csubmitted: [u64; sizes::COMPUTE_SLOTS], + /// Render member j's TA and FS FW stamp targets. + pub(crate) r_ta_stamp: [u32; sizes::RENDER_SLOTS], + pub(crate) r_fs_stamp: [u32; sizes::RENDER_SLOTS], /// Compute slots, pass slots and clustering buffers it holds. pub(crate) claims: Claims, /// A kill or recovery ended this prefix's VM: later prefixes of it fail with EIO. @@ -269,6 +272,8 @@ impl Flight { cstamp: [0; sizes::COMPUTE_SLOTS], cwait: [0; sizes::COMPUTE_SLOTS], csubmitted: [0; sizes::COMPUTE_SLOTS], + r_ta_stamp: [0; sizes::RENDER_SLOTS], + r_fs_stamp: [0; sizes::RENDER_SLOTS], claims: Claims::new(), doomed: false, uma_submitted: 0, @@ -302,6 +307,7 @@ struct Prefix { n: u64, draw: u64, last_ct: u32, + last_ta: u32, last_fs: u32, } @@ -711,7 +717,7 @@ impl Firmware { // owner, not the next command that happens to occupy the flight list. return Ok(()); } - // The named owner: the oldest flight, or with compute queued behind it a later one. + // The named owner: the oldest flight, or with compute/render queued behind it a later one. let f = self .engine .flights @@ -721,26 +727,41 @@ impl Firmware { f.computes != 0 && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) } - 0x70 => f.renders != 0 && f.ta_target == target, - 0x71 => f.renders != 0 && f.fs_target == target, + 0x70 => { + f.renders != 0 + && f.r_ta_stamp[..(f.renders as usize).min(f.r_ta_stamp.len())] + .contains(&target) + } + 0x71 => { + f.renders != 0 + && f.r_fs_stamp[..(f.renders as usize).min(f.r_fs_stamp.len())] + .contains(&target) + } _ => false, }) .ok_or(ENOENT)?; if flags & 1 == 0 { return Err(ENOENT); } - if flags & 9 == 9 - && f.renders != 0 - && !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_pass(k)?; - let bytes = pass.ta_work.r64(work::ta::TPC_BYTES)?; - if bytes == 0 || bytes > pass.tpc.size as u64 { - return Err(ERANGE); + if flags & 9 == 9 && f.renders != 0 { + let mut cleaned = false; + let count = (f.renders as usize).min(f.r_ta_stamp.len()); + for m in 0..count { + if super::poll::stamp_reached(stage[0], f.r_ta_stamp[m], self.engine.ta_target) { + continue; + } + let k = f.claims.pass[m] as usize; + 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); + } + pass.tpc.fill(0, 0, bytes as usize)?; + cleaned = true; + } + if cleaned { + wmb(); } - pass.tpc.fill(0, 0, bytes as usize)?; - wmb(); } f.doomed = true; f.recovery_suspect = true; @@ -1160,7 +1181,7 @@ impl Firmware { .is_ok_and(|units| self.slots.compute_available(units)) } Some(Command::Render(_)) => { - let render_count = e.flights.iter().filter(|f| f.renders != 0).count(); + let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); render_count < params::render_flights() && !self.slots.render_exhausted() && !self.pools.exhausted() @@ -1175,14 +1196,16 @@ impl Firmware { } } - /// Resolves a same-queue target stamp for `class` (`RENDER` -> `fs_target`, `COMPUTE` -> - /// `target`) when `target_seq` names an in-flight command of `job.queue`. Returns `Ok(None)` - /// when no barrier was requested or the waited prefix has already retired. - fn wait_stamp_for( + /// Resolves a same-queue target stamp for `class` (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> + /// `cstamp`) when `target_seq` names an in-flight command of `job.queue` or an earlier member + /// of an in-progress render batch `current`. Returns `Ok(None)` when no barrier was requested + /// or the waited prefix has already retired. + fn wait_stamp_for_with( &self, job: &Arc, class: usize, target_seq: Option, + current: Option<&Flight>, ) -> Result> { let Some(last) = target_seq else { return Ok(None); @@ -1217,21 +1240,44 @@ impl Firmware { } return Err(EAGAIN); } - for flight in &self.engine.flights { + let find_render = |flight: &Flight| -> Option { if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - continue; + return None; } - for k in flight.first..flight.first + flight.count { - if flight.job.command_order(k as u32).is_some_and(|fo| { - fo.engine == super::command::RENDER && fo.sequence == last - }) { - return Ok(Some(flight.fs_target)); + let count = (flight.renders as usize).min(flight.r_fs_stamp.len()); + for member in 0..count { + let k = (flight.first + member) as u32; + if flight + .job + .command_order(k) + .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) + { + return Some(flight.r_fs_stamp[member]); } } + None + }; + if let Some(stamp) = current.and_then(find_render) { + return Ok(Some(stamp)); + } + for flight in &self.engine.flights { + if let Some(stamp) = find_render(flight) { + return Ok(Some(stamp)); + } } Err(EAGAIN) } + /// Resolves a same-queue target stamp for `class` across published in-flight flights. + fn wait_stamp_for( + &self, + job: &Arc, + class: usize, + target_seq: Option, + ) -> Result> { + self.wait_stamp_for_with(job, class, target_seq, None) + } + /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited @@ -1323,6 +1369,47 @@ impl Firmware { )) } + /// Allocator references for subsequent passes (`member > 0`) in a non-InitBM multi-pass + /// render flight, reusing the active slot and PB epoch while advancing `uma_submitted` by 2. + fn render_refs_batched( + &self, + alloc_slot: usize, + job: &Job, + draw: u64, + epoch: &super::pools::PbEpoch, + prev_uma_submitted: u64, + ) -> Result { + let arena = job.resources.render()?; + let a = arena.pools.allocator_refs_for(alloc_slot)?; + let r = &self.graph.render; + let stage = draw.checked_mul(2).ok_or(EOVERFLOW)?; + let uma_submitted = prev_uma_submitted.checked_add(2).ok_or(EOVERFLOW)?; + Ok(RenderRefs { + notifier: r.notifier.va, + legacy_empty: r.legacy_empty.va, + qinfo: [r.qinfo[0].va, r.qinfo[1].va], + user_stamp: [ + r.notifier.va + notifier_page::TA_STAMP as u64, + r.notifier.va + notifier_page::FS_STAMP as u64, + ], + fw_stamp: [r.fw_stamp[0].va, r.fw_stamp[1].va], + uma_mgr: a.uma_mgr, + uma_aux: a.uma_aux, + uma_gpu: a.uma_gpu, + pb_mgr: epoch.manager.va, + scene_list: 0, + mgr_misc: epoch.misc.va, + pb_init_blocks: a.init_blocks, + parameter_id: a.parameter_id, + generation: job.vm.generation, + activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], + counter: [stage, stage - 1], + uma_submitted, + uuid: (draw as u32).wrapping_add(1), + usc_base: job.queue.usc_base, + }) + } + /// Publishes the next command of `job`. All images and ring entries precede the host /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; /// The error records whether firmware may see a counter/producer update, independently @@ -1446,12 +1533,14 @@ impl Firmware { return Err(super::boot::eproto()); } let mut c_read = prefix.c_head; + let mut ta_read = prefix.ta_head; + let mut fs_read = prefix.fs_head; if class_behind { if render { // Room for up to 4 TA entries (prev_barrier, ta_fs_barrier, compute_barrier, // ta_work) and 4 FS entries (fs_dep, fs_compute_barrier, own_barrier, fs_work). - let ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; - let fs_read = self.graph.render.qstate[1].r32(qstate::READ)?; + ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; + 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 @@ -1471,6 +1560,7 @@ impl Firmware { } } } + f.first = index as usize; f.c_start = prefix.c_head; f.ta_start = prefix.ta_head; f.fs_start = prefix.fs_head; @@ -1601,9 +1691,102 @@ impl Firmware { .pick_pass_in(&job.resources, &geometry, 0) .ok_or(EAGAIN)?; f.claims.pass[0] = k as u32; + f.claims.pass_count = 1; f.claims.pass_mask = 1 << k; self.slots.pass_busy |= 1 << k; self.prefix_render(job, r, geometry, &mut prefix, f, behind, class_behind)?; + // Batch consecutive ready non-InitBM render passes of the same SUBMIT into + // one TA/FS producer advance, one UMA submitted update, and one SubmitRecord. + if !f.initbm { + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let active_renders: usize = self + .engine + .flights + .iter() + .map(|fl| fl.renders as usize) + .sum(); + let mut more_renders = params::render_flights() + .saturating_sub(active_renders + 1) + .min(sizes::RENDER_SLOTS.saturating_sub(1)); + while more_renders > 0 && end < job.progress.count() { + let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !job.can_fold_render_cmd(end, next_seq) + || super::recovery::logic::next_ordinal(prefix.draw).is_none() + { + break; + } + let Some(Command::Render(r2)) = command(job, end) else { + break; + }; + let Some(o2) = job.command_order(end) else { + break; + }; + let ta_used = prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP; + let fs_used = prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP; + if ta_used >= sizes::QUEUE_CAP - 5 || fs_used >= sizes::QUEUE_CAP - 5 { + break; + } + let geo2 = Geometry::new(&r2.cmd, 0); + let Some(k2) = self.slots.pick_pass_in( + &job.resources, + &geo2, + f.claims.pass_mask, + ) else { + break; + }; + let staged2 = r2.cmd.flags + & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES + != 0; + if self + .wait_stamp_for_with( + job, + super::command::COMPUTE, + o2.ta_wait_through[super::command::COMPUTE], + None, + ) + .is_err() + || self + .wait_stamp_for_with( + job, + super::command::COMPUTE, + o2.wait_through[super::command::COMPUTE], + None, + ) + .is_err() + || (staged2 + && params::early_tiling() + && self + .wait_stamp_for_with( + job, + super::command::RENDER, + o2.ta_wait_through[super::command::RENDER], + Some(f), + ) + .is_err()) + { + break; + } + let member = prefix.renders as usize; + f.claims.pass[member] = k2 as u32; + f.claims.pass_count += 1; + f.claims.pass_mask |= 1 << k2; + self.slots.pass_busy |= 1 << k2; + self.prefix_render( + job, + r2, + geo2, + &mut prefix, + f, + behind, + class_behind, + )?; + last_seq = Some(next_seq); + end += 1; + more_renders -= 1; + } + } } } f.first = index as usize; @@ -1611,11 +1794,7 @@ impl Firmware { f.computes = prefix.computes; f.renders = prefix.renders; f.target = prefix.last_ct; - f.ta_target = if render { - encode::stamp(prefix.draw) - } else { - 0 - }; + f.ta_target = if render { prefix.last_ta } else { 0 }; f.fs_target = prefix.last_fs; f.head = prefix.c_head; f.ta_head = prefix.ta_head; @@ -1646,7 +1825,10 @@ impl Firmware { let a = f.pb_slot as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); job.resources.commit_render(); - job.resources.render()?.pools.publish(a, f.uma_submitted)?; + job.resources + .render()? + .pools + .publish_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); // Notifier service dereferences u32 counters; the host ordering ledger // remains u64. Eight-byte spacing is retained allocation padding. @@ -1949,38 +2131,51 @@ impl Firmware { behind: bool, class_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 member = pf.renders as usize; + if member >= sizes::RENDER_SLOTS { + return Err(EAGAIN); + } + let cmd_index = (f.first + member) as u32; + let k = f.claims.pass[member] as usize; let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); - let order = job.command_order(job.progress.sent()); + let has_prior_render = class_behind || member > 0; + let (prev_ta, prev_fs) = if member > 0 { + (pf.last_ta, pf.last_fs) + } else { + (self.engine.ta_target, self.engine.fs_target) + }; + let order = job.command_order(cmd_index); let staged = cmd.cmd.flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; - let ta_wait_compute = self.wait_stamp_for( + let ta_wait_compute = self.wait_stamp_for_with( job, super::command::COMPUTE, order.and_then(|o| o.ta_wait_through[super::command::COMPUTE]), + None, )?; - let fs_wait_compute = self.wait_stamp_for( + let fs_wait_compute = self.wait_stamp_for_with( job, super::command::COMPUTE, order.and_then(|o| o.wait_through[super::command::COMPUTE]), + None, )?; - let ta_wait_fs = if class_behind && staged && params::early_tiling() { - self.wait_stamp_for( + let ta_wait_fs = if has_prior_render && staged && params::early_tiling() { + self.wait_stamp_for_with( job, super::command::RENDER, order.and_then(|o| o.ta_wait_through[super::command::RENDER]), + Some(f), )? } else { None }; let plan = plan_render_barriers( cmd.cmd.flags, - class_behind, + has_prior_render, params::early_tiling(), - self.engine.fs_target, + prev_fs, order.is_some_and(|o| o.wait_through[super::command::RENDER].is_none()), ta_wait_fs, [ta_wait_compute, fs_wait_compute], @@ -1990,13 +2185,30 @@ impl Firmware { .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.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, class_behind, behind)?; - f.pb = Some(epoch); - f.pb_slot = alloc_slot as u32; - f.pb_binding = binding; - f.initbm = init_buffer; - f.has_timestamps = !cmd.timestamp_outputs.is_empty(); + let (refs, init_buffer) = if member == 0 { + let alloc_slot = self.pools.pick_slot(&job.vm, behind).ok_or(EAGAIN)?; + let (refs, init_buffer, epoch, binding) = + self.render_refs(alloc_slot, job, draw, class_behind, behind)?; + f.pb = Some(epoch); + f.pb_slot = alloc_slot as u32; + f.pb_binding = binding; + f.initbm = init_buffer; + (refs, init_buffer) + } else { + if f.initbm { + return Err(EAGAIN); + } + let epoch = f.pb.as_ref().ok_or(EINVAL)?; + let refs = self.render_refs_batched( + f.pb_slot as usize, + job, + draw, + epoch, + f.uma_submitted, + )?; + (refs, false) + }; + f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); let p = job.resources.render_pass(k)?; let pass = p.refs(); geometry.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; @@ -2064,7 +2276,7 @@ impl Firmware { p.fs_seq.write(0, &scratch.fss[..])?; p.scene.write(0, &scratch.scene[..])?; // One retained descriptor is shared by TA and FS; its private submitted counter - // advances by two. Reused descriptors and their pool/list bytes remain intact. + // advances by two per pass. Reused descriptors and their pool/list bytes remain intact. f.uma_submitted = refs.uma_submitted; let r = &self.graph.render; let cap = sizes::QUEUE_CAP; @@ -2076,21 +2288,21 @@ impl Firmware { r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } - // When pipelining behind an in-flight same-VM render, insert explicit hardware ordering - // barriers on the TA/FS rings. Fragment-only, barrier-free, or staged renders whose TA - // prefix stops before the newest in-flight FS overlap TA(N) with FS(N-1) (TA waits on - // prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior FS - // then own TA); otherwise TA(N) waits on prior FS to preserve full vertex-stage visibility. - if class_behind { + // When pipelining behind an in-flight or same-batch same-VM render, insert explicit + // hardware ordering barriers on the TA/FS rings. Fragment-only, barrier-free, or staged + // renders whose TA prefix stops before the prior FS overlap TA(N) with FS(N-1) (TA waits + // on prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior + // FS then own TA); otherwise TA(N) waits on prior FS to preserve full vertex visibility. + if has_prior_render { // Pipelined same-VM non-InitBM render->render barriers wait on the producer's // firmware stamp only (type 0), matching `own_barrier` and G15's // `RENDER_INTERNAL_HOLD = 0`, so consecutive TA/FS stages hand off without a // software-job hold bubble. Cross-engine barriers (`fs2c`/`c2ta`) stay `Hold`. let render_bar = BarrierType::from_stamp_only(!init_buffer); let (wait_va, wait_stamp, wait_event) = if plan.early { - (r.fw_stamp[0].va, self.engine.ta_target, 0x70) + (r.fw_stamp[0].va, prev_ta, 0x70) } else { - (r.fw_stamp[1].va, self.engine.fs_target, 0x71) + (r.fw_stamp[1].va, prev_fs, 0x71) }; let prev = encode::barrier( wait_va, @@ -2119,7 +2331,7 @@ impl Firmware { } let dep = encode::barrier( r.fw_stamp[1].va, - self.engine.fs_target, + prev_fs, 0x71, target, work::barrier::RENDER_WAIT_UUID, @@ -2175,8 +2387,12 @@ impl Firmware { pf.fs_head = (pf.fs_head + 1) % cap; r.ring[1].w64(8 * pf.fs_head as usize, p.fs_work.va)?; pf.fs_head = (pf.fs_head + 1) % cap; - pf.renders = 1; + f.r_ta_stamp[member] = target; + f.r_fs_stamp[member] = target; + pf.renders += 1; + f.renders = pf.renders; pf.draw = draw; + pf.last_ta = target; pf.last_fs = target; pf.prev = Prev::Render; Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index d44682d39eabae..94d3580aa32e29 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -101,16 +101,34 @@ fn program(vm: &mmu::Vm, usc: u64, address: u64, checked: &mut Option) -> R Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G16 barrier. -pub(crate) fn vdm(vm: &mmu::Vm, va: u64) -> Result { - if !params::stream_gate() { +/// VDM admission for a batch of root streams under a single VM read lock, caching up to +/// 256 intra-page bytes across adjacent VDM roots (for example in a multi-pass render SUBMIT). +pub(crate) fn vdm_batch(vm: &mmu::Vm, vas: &[u64]) -> Result { + if vas.is_empty() || !params::stream_gate() { return Ok(()); } - let mut bytes = [0u8; 4]; - vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; - let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { - return Err(reject("VDM root", va, &[word])); + let mut guard = vm.read_lock().map_err(|_| EFAULT)?; + let mut win_va = 0u64; + let mut win_len = 0usize; + let mut buf = [0u8; 256]; + for &va in vas { + let end = va.checked_add(4).ok_or(EINVAL)?; + let cached = win_len != 0 && va >= win_va && end <= win_va + win_len as u64; + if !cached { + let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); + let len = buf.len().min(in_page); + if len < 4 { + return Err(EINVAL); + } + guard.read_user(va, &mut buf[..len]).map_err(|_| EFAULT)?; + win_va = va; + win_len = len; + } + let off = (va - win_va) as usize; + let word = u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]); + if word != VDM_ROOT { + return Err(reject("VDM root", va, &[word])); + } } Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 5fc8e426e188fd..ee954a1a9bdfd9 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -369,6 +369,41 @@ impl Job { true } + /// Whether command `index` is a ready render command continuing a same-SUBMIT render batch + /// at queue-local render ordinal `expected` (treating `expected - 1` as already published + /// within the in-progress render flight). + pub(crate) fn can_fold_render_cmd(&self, index: u32, expected: u64) -> bool { + if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + return false; + } + let Some(Command::Render(_)) = self.commands.get(index as usize) else { + return false; + }; + let Some(order) = self.orders.get(index as usize) else { + return false; + }; + if order.engine != super::command::RENDER + || order.sequence != expected + || self.queue.check(order).is_err() + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + let completed = self + .queue + .completed + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + let mut published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + published[super::command::RENDER] = + published[super::command::RENDER].max(expected.saturating_sub(1)); + order.ready(completed, published) + } + /// 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. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index f80c7a91790abe..aa90e9dbeae395 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -933,7 +933,6 @@ impl Firmware { .nth(1) .is_some(); let g = &self.graph.render; - let k = f.claims.pass[0] as usize; let a = f.pb_slot as usize; if render_behind { let e = &self.engine; @@ -990,15 +989,25 @@ impl Firmware { && f.job.resources.render()?.pools.retired(a)?; } if full { - 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)?; - if f.computes == 0 { - ticks = [ta_start, ta_end, fs_start, fs_end]; + let count = (f.renders as usize).min(f.claims.pass.len()); + for m in 0..count { + let k = f.claims.pass[m] 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)?; + if count == 1 && f.computes == 0 { + ticks = [ta_start, ta_end, fs_start, fs_end]; + } + full &= ta_start != 0 + && ta_end > ta_start + && fs_start != 0 + && fs_end > fs_start; + if !full { + break; + } } - full &= ta_start != 0 && ta_end > ta_start && fs_start != 0 && fs_end > fs_start; } } if full { diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index bdaa2aecbb4882..b3d0ec8e3cd47c 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -255,9 +255,17 @@ impl PoolSet { } u.refs() } - pub(crate) fn publish(&self, k: usize, submitted: u64) -> Result { + pub(crate) fn publish_batch(&self, k: usize, submitted: u64, renders: u32) -> Result { + if renders == 0 { + return Err(EINVAL); + } let u = self.units.get(k).ok_or(EINVAL)?; - if submitted != read64(&u.submitted, 0)?.checked_add(2).ok_or(EOVERFLOW)? { + let delta = u64::from(renders).checked_mul(2).ok_or(EOVERFLOW)?; + if submitted + != read64(&u.submitted, 0)? + .checked_add(delta) + .ok_or(EOVERFLOW)? + { return Err(EINVAL); } u.submitted.w64(0, submitted)?; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index e5484d32981367..d8a5da7c22aa23 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -374,6 +374,7 @@ pub(crate) struct Claims { pub(crate) slot: [u32; sizes::COMPUTE_SLOTS], pub(crate) slot_count: u32, pub(crate) pass: [u32; sizes::RENDER_SLOTS], + pub(crate) pass_count: u32, pub(crate) pass_mask: u32, #[allow(dead_code)] pub(crate) ct: [u32; sizes::RENDER_SLOTS], @@ -390,6 +391,7 @@ impl Claims { slot: [0; sizes::COMPUTE_SLOTS], slot_count: 0, pass: [0; sizes::RENDER_SLOTS], + pass_count: 0, pass_mask: 0, ct: [0; sizes::RENDER_SLOTS], ct_count: 0, @@ -1134,10 +1136,27 @@ impl Slots { || f.slot[..f.slot_count as usize] .iter() .any(|&k| k as usize >= sizes::COMPUTE_UNITS) + || f.pass_count as usize > f.pass.len() || f.pass_mask & !PASS_MASK != 0 { return Err(EINVAL); } + if f.pass_count != 0 { + let mut mask = 0u32; + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS { + return Err(EINVAL); + } + let bit = 1u32 << k; + if mask & bit != 0 { + return Err(EINVAL); + } + mask |= bit; + } + if mask != f.pass_mask { + return Err(EINVAL); + } + } for &k in &f.slot[..f.slot_count as usize] { let k = k as usize; self.compute.pending_retarget[k] = self.compute.owner[k] @@ -1181,9 +1200,20 @@ impl Slots { return Err(EBUSY); } } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 && !p.publish(k) { - return Err(EBUSY); + if f.pass_count != 0 { + if f.pass_count as usize > f.pass.len() { + return Err(EINVAL); + } + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS || !p.publish(k as usize) { + return Err(EBUSY); + } + } + } else { + for k in 0..sizes::RENDER_SLOTS { + if f.pass_mask & (1 << k) != 0 && !p.publish(k) { + return Err(EBUSY); + } } } self.compute.lifetime = c; @@ -1200,10 +1230,22 @@ impl Slots { return Err(EINVAL); } } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 && !p.retire(k) { + if f.pass_count != 0 { + if f.pass_count as usize > f.pass.len() { return Err(EINVAL); } + // Retire in submission order so displacement retains the newest hardware pass slot. + for &k in &f.pass[..f.pass_count as usize] { + if k as usize >= sizes::RENDER_SLOTS || !p.retire(k as usize) { + return Err(EINVAL); + } + } + } else { + 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.render.lifetime = p; @@ -1226,6 +1268,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; Ok(()) @@ -1246,6 +1289,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; } @@ -1270,6 +1314,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; } 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 14c1c870fe0e3d..e654fbbb95bedf 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 @@ -619,6 +619,7 @@ pub(crate) const UAT_PGMSK: usize = 0x3fff; pub(crate) struct Vm { pub(crate) maps: Vec<(u64, u64, bool, bool)>, + pub(crate) batch_calls: std::cell::Cell, } impl Vm { pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { @@ -628,6 +629,7 @@ }) } pub(crate) fn covers_ranges_batch(&self, ranges: &[(u64, u64, u8)]) -> (bool, usize) { + self.batch_calls.set(self.batch_calls.get() + 1); for (i, &(start, size, acc)) in ranges.iter().enumerate() { if !self.covers_range(start, size, acc & 1 != 0, acc & 2 != 0) { return (false, i); @@ -643,6 +645,17 @@ } RENDER_ADMISSION + fn check_render_one( + ctx: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], + ) -> Result { + let mut batch = SpanBatch::new(); + check_render(&mut batch, ctx, cmd, vertex, fragment)?; + batch.flush(ctx.vm) + } + const BASE_GVA: u64 = 0x10_0000_0000; fn base_vm() -> mmu::Vm { mmu::Vm { @@ -651,6 +664,7 @@ (BASE_GVA + 0x20_0000, BASE_GVA + 0x40_0000, true, true), (BASE_GVA + 0x50_0000, BASE_GVA + 0x51_0000, true, false), ], + batch_calls: std::cell::Cell::new(0), } } fn base_cmd() -> uapi::drm_asahi_cmd_render { @@ -681,26 +695,26 @@ cmd.depth.comp_base = BASE_GVA + 0x24_0000; cmd.stencil.base = BASE_GVA + 0x28_0000; cmd.stencil.comp_base = BASE_GVA + 0x2c_0000; - assert_eq!(check_render(&ctx, &cmd, &[], &[]), Ok(())); + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); // 1x compressed D16 depth (Z Format = 2 at bits 25..26). let mut d16 = base_cmd(); d16.zls_ctrl = Z_COMP | (2 << 25); d16.depth.base = BASE_GVA + 0x20_0000; d16.depth.comp_base = BASE_GVA + 0x24_0000; - assert_eq!(check_render(&ctx, &d16, &[], &[]), Ok(())); + assert_eq!(check_render_one(&ctx, &d16, &[], &[]), Ok(())); // 2x MSAA compressed depth. let mut msaa2 = d16; msaa2.samples = 2; - assert_eq!(check_render(&ctx, &msaa2, &[], &[]), Ok(())); + assert_eq!(check_render_one(&ctx, &msaa2, &[], &[]), Ok(())); // Layered compressed depth/stencil with comp_stride == 0 (1 line = 0x80) and nonzero stride. let mut layered = cmd; layered.layers = 4; layered.depth.stride = (1 << 14) | 1; layered.stencil.stride = (1 << 14) | 1; - assert_eq!(check_render(&ctx, &layered, &[], &[]), Ok(())); + assert_eq!(check_render_one(&ctx, &layered, &[], &[]), Ok(())); layered.depth.comp_stride = 3 << 14; layered.stencil.comp_stride = 2 << 14; - assert_eq!(check_render(&ctx, &layered, &[], &[]), Ok(())); + assert_eq!(check_render_one(&ctx, &layered, &[], &[]), Ok(())); } #[test] @@ -720,36 +734,36 @@ for bit in [1u64 << 2, 1 << 6, 1 << 4, 1 << 8] { let mut bad = valid(); bad.zls_ctrl ^= bit; - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); } // Unaligned comp_stride or comp_base. for bad_stride in [1u32, 0x4001, 0x3fff] { let mut bad = valid(); bad.depth.comp_stride = bad_stride; - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); } let mut bad = valid(); bad.depth.comp_base += 2; - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); // comp_base without compress bits, compress bits without comp_base, stride without base. let mut bad = valid(); bad.zls_ctrl &= !((1 << 2) | (1 << 6)); - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); let mut bad = valid(); bad.depth.comp_base = 0; - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); let mut bad = valid(); bad.zls_ctrl = Z_COMP; bad.stencil = Default::default(); bad.stencil.comp_stride = 1 << 14; - assert_eq!(check_render(&ctx, &bad, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&ctx, &bad, &[], &[]), Err(EINVAL)); // Unmapped comp_base -> ENOENT; read-only comp_base -> EACCES. let mut unmapped = valid(); unmapped.depth.comp_base = BASE_GVA + 0x60_0000; - assert_eq!(check_render(&ctx, &unmapped, &[], &[]), Err(ENOENT)); + assert_eq!(check_render_one(&ctx, &unmapped, &[], &[]), Err(ENOENT)); let mut ro = valid(); ro.depth.comp_base = BASE_GVA + 0x50_0000; - assert_eq!(check_render(&ctx, &ro, &[], &[]), Err(EACCES)); + assert_eq!(check_render_one(&ctx, &ro, &[], &[]), Err(EACCES)); // Layered metadata span extending past mapped range -> ENOENT. let mut past_end = valid(); past_end.layers = 4; @@ -757,7 +771,40 @@ past_end.stencil.stride = 1; past_end.depth.comp_base = BASE_GVA + 0x3f_c000; past_end.depth.comp_stride = 0x100 << 14; - assert_eq!(check_render(&ctx, &past_end, &[], &[]), Err(ENOENT)); + assert_eq!(check_render_one(&ctx, &past_end, &[], &[]), Err(ENOENT)); + } + + #[test] + fn submit_wide_span_batch_dedups_and_flushes_once_across_passes() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let mut batch = SpanBatch::new(); + for pass in 0..4u64 { + let mut cmd = base_cmd(); + cmd.vdm_ctrl_stream_base = BASE_GVA + pass * 0x20; + cmd.zls_ctrl = Z_COMP; + cmd.depth.base = BASE_GVA + 0x20_0000 + pass * 0x4000; + cmd.depth.comp_base = BASE_GVA + 0x24_0000 + pass * 0x4000; + assert_eq!(check_render(&mut batch, &ctx, &cmd, &[], &[]), Ok(())); + } + assert_eq!(vm.batch_calls.get(), 0); + assert_eq!(batch.flush(&vm), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + + // Unmapped or read-only span on a later pass still reports exact ENOENT / EACCES. + let mut bad_unmapped = base_cmd(); + bad_unmapped.zls_ctrl = Z_COMP; + bad_unmapped.depth.base = BASE_GVA + 0x20_0000; + bad_unmapped.depth.comp_base = BASE_GVA + 0x60_0000; + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(check_render(&mut batch, &ctx, &bad_unmapped, &[], &[]), Ok(())); + assert_eq!(batch.flush(&vm), Err(ENOENT)); + + let mut bad_ro = bad_unmapped; + bad_ro.depth.comp_base = BASE_GVA + 0x50_0000; + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(check_render(&mut batch, &ctx, &bad_ro, &[], &[]), Ok(())); + assert_eq!(batch.flush(&vm), Err(EACCES)); } } ''' 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 da646563367f4f..c4fcb1fbe9ff3f 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -478,10 +478,14 @@ def item(declaration): impl QueueBehindJob{ fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn command_order(&self,index:u32)->Option{ - if self.extra_orders.is_empty(){Some(self.order)}else{self.extra_orders.get(index as usize).copied()} + if !self.extra_orders.is_empty() { + self.extra_orders.get(index as usize).copied() + } else { + Some(self.order) + } } } -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],r_fs_stamp:[u32;16],fs_target: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{ @@ -499,8 +503,10 @@ def item(declaration): mod queue_behind_scope { use super::*; type Job = QueueBehindJob; + type Flight = QueueBehindFlight; fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{15} } + #[allow(non_upper_case_globals)] mod kernel { pub mod uapi { pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS: u32 = 1 << 20; @@ -512,6 +518,7 @@ def item(declaration): __PLAN_RENDER_BARRIERS__ impl QueueBehindHost { __CAN_QUEUE_BEHIND__ + __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ } @@ -530,7 +537,7 @@ def item(declaration): 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,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target: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}, }; @@ -568,7 +575,7 @@ def item(declaration): let no_barrier=mk(2,q1.clone(),true,None,None); let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target: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}, }; @@ -585,7 +592,7 @@ def item(declaration): extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let pr=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, }; @@ -608,7 +615,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,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, }; @@ -648,8 +655,8 @@ def item(declaration): let c_other_q=mk(5,q2.clone(),false,1,[None,None]); let p=QueueBehindHost{ engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_fs_stamp:[0;16],fs_target: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}, @@ -684,7 +691,7 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let pm=QueueBehindHost{ engine:QueueBehindEngine{ordinal:3,draw:1,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,r_fs_stamp:[0;16],fs_target: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}, @@ -713,20 +720,18 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, - extra_orders:vec![], - dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![], - dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let mut p=QueueBehindHost{ engine:QueueBehindEngine{ordinal:1,draw:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target: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}, @@ -737,7 +742,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -751,8 +756,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![], - dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let c1=mk(1,false,1,[None,None]); let c2=mk(2,false,2,[None,None]); @@ -764,7 +768,7 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let mut p=QueueBehindHost{ engine:QueueBehindEngine{ordinal:3,draw:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,r_fs_stamp:[0;16],fs_target: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}, @@ -777,6 +781,56 @@ def item(declaration): p.engine.flights[0].computes=16; assert!(!p.can_queue_behind(&c4)); } + #[test]fn multi_pass_render_flight_wait_stamp_and_render_cap(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let multi=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(()),Command::Render(()),Command::Render(())], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![ + Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + Order{engine:command::RENDER,sequence:2,wait_through:[Some(1),None]}, + Order{engine:command::RENDER,sequence:3,wait_through:[Some(2),None]}, + ], + dependency:Ok(()),resources:Resources, + }); + let next_r=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let mut r_fs=[0u32;16]; + r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:0,draw:3,flights:vec![QueueBehindFlight{ + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,target:0,cstamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + 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}, + }; + // Lookup into published multi-pass render flight resolves interior and tail passes. + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(0x100))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(0x200))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(0x300))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(4)),Err(EAGAIN)); + // Lookup against an in-progress same-batch flight resolves earlier pass before publish. + let mut cur_fs=[0u32;16]; + cur_fs[0]=0x400; + let cur=QueueBehindFlight{ + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(0x400))); + // Active renders sum flight.renders: 15 batched renders saturates render_flights(). + assert!(p.can_queue_behind(&next_r)); + p.engine.flights[0].renders=15; + assert!(!p.can_queue_behind(&next_r)); + } #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; @@ -939,10 +993,24 @@ def item(declaration): use super::{Error, Result, EAGAIN, now_ns}; const ENOENT: Error = Error(2); const ERANGE: Error = Error(34); - use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; mod command { pub const RENDER: usize = 0; pub const COMPUTE: usize = 1; } #[derive(Copy, Clone)] struct Order { engine: usize, sequence: u64, wait_through: [Option; 2] } + impl Order { + fn ready(&self, completed: [u64; 2], published: [u64; 2]) -> bool { + let mut i = 0; + while i < 2 { + if let Some(last) = self.wait_through[i] { + if completed[i].max(published[i]) < last { + return false; + } + } + i += 1; + } + true + } + } #[derive(Copy, Clone)] enum Command { Compute(()), Render(()) } mod fence { @@ -954,7 +1022,11 @@ def item(declaration): struct Status(AtomicU32); impl Status { fn get(&self) -> u32 { self.0.load(Ordering::Relaxed) } } struct Vm { status: Status } - struct Queue { cancelled_compute: u64 } + struct Queue { + cancelled_compute: u64, + completed: [AtomicU64; 2], + published: [AtomicU64; 2], + } impl Queue { fn check(&self, order: &Order) -> Result { if self.cancelled_compute != 0 && order.sequence >= self.cancelled_compute { @@ -981,12 +1053,17 @@ def item(declaration): impl Job { __CAN_FOLD_CMD__ __CAN_FOLD_JOB__ + __CAN_FOLD_RENDER_CMD__ } #[test] fn compute_horizon_eligibility_rejects_barriers_renders_unready_fences_and_gaps() { let mk = |cmds: Vec, orders: Vec, inputs: Vec, cancelled: u64| Job { vm: Vm { status: Status(AtomicU32::new(0)) }, - queue: Queue { cancelled_compute: cancelled }, + queue: Queue { + cancelled_compute: cancelled, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(0)], + }, progress: Progress { sent: 0, count: cmds.len() as u32 }, commands: cmds, orders, @@ -1053,6 +1130,52 @@ def item(declaration): assert!(!cancelled.can_fold_horizon_job(2)); } + #[test] + fn can_fold_render_cmd_accepts_same_batch_render_dep_and_rejects_unready_compute() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, pub_c: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { + cancelled_compute: 0, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(pub_c)], + }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + terminal_retired: AtomicBool::new(false), + }; + let multi = mk( + vec![Command::Render(()), Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + Order { engine: command::RENDER, sequence: 3, wait_through: [Some(2), Some(5)] }, + ], + vec![true], + 4, + ); + // Pass 1 waits on pass 0 (not yet globally published): foldable at expected=2. + assert!(multi.can_fold_render_cmd(1, 2)); + // Wrong sequence is rejected. + assert!(!multi.can_fold_render_cmd(1, 3)); + // Pass 2 waits on unpublished compute 5 (published=4): rejected until compute 5 publishes. + assert!(!multi.can_fold_render_cmd(2, 3)); + multi.queue.published[command::COMPUTE].store(5, Ordering::Release); + assert!(multi.can_fold_render_cmd(2, 3)); + // Unready input fence blocks folding. + let unready = mk( + vec![Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 1, wait_through: [None, None] }, + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + ], + vec![false], + 0, + ); + assert!(!unready.can_fold_render_cmd(1, 2)); + } + mod recovery { pub mod logic { pub fn last_retired_target(last: &[Option; 3], event: u32, target: u32) -> bool { @@ -1062,20 +1185,31 @@ def item(declaration): } } mod poll { - pub fn stamp_reached(_obs: u32, _own: u32, _tail: u32) -> bool { true } + pub fn stamp_reached(obs: u32, own: u32, _tail: u32) -> bool { obs >= own } } mod work { pub mod ta { pub const TPC_BYTES: usize = 0; } } fn wmb() {} - struct PassBuf { size: usize } + struct PassBuf { + size: usize, + tpc_bytes: u64, + cleared: std::cell::Cell, + } impl PassBuf { - fn r64(&self, _o: usize) -> Result { Ok(0) } - fn fill(&self, _o: usize, _v: u8, _n: usize) -> Result { Ok(()) } + fn r64(&self, _o: usize) -> Result { Ok(self.tpc_bytes) } + fn fill(&self, _o: usize, _v: u8, n: usize) -> Result { + self.cleared.set(self.cleared.get() + n); + Ok(()) + } } struct Pass { ta_work: PassBuf, tpc: PassBuf } - struct Resources; - impl Resources { fn render_pass(&self, _k: usize) -> Result<&Pass> { Err(ENOENT) } } + struct Resources { passes: Vec } + impl Resources { + fn render_pass(&self, k: usize) -> Result<&Pass> { + self.passes.get(k).ok_or(ENOENT) + } + } struct RecJob { resources: Resources } - struct RecClaims { pass: [u32; 2] } + struct RecClaims { pass: [u32; 16] } struct RecFlight { job: RecJob, claims: RecClaims, @@ -1085,6 +1219,8 @@ def item(declaration): ta_target: u32, fs_target: u32, cstamp: [u32; 16], + r_ta_stamp: [u32; 16], + r_fs_stamp: [u32; 16], doomed: bool, recovery_suspect: bool, recovery_started_ns: u64, @@ -1104,14 +1240,16 @@ def item(declaration): let mut fw = RecFirmware { engine: RecEngine { flights: vec![RecFlight { - job: RecJob { resources: Resources }, - claims: RecClaims { pass: [0; 2] }, + job: RecJob { resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, computes: 3, renders: 0, target: 0x300, ta_target: 0, fs_target: 0, cstamp, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], doomed: false, recovery_suspect: false, recovery_started_ns: 0, @@ -1125,6 +1263,54 @@ def item(declaration): assert!(fw.engine.flights[0].recovery_suspect); assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0x100]), Err(ENOENT)); } + #[test] + fn recovery_prepare_matches_interior_render_stamps_and_cleans_only_unfinished_tpc() { + let mk_pass = |bytes: u64| Pass { + ta_work: PassBuf { size: 0x1000, tpc_bytes: bytes, cleared: std::cell::Cell::new(0) }, + tpc: PassBuf { size: 0x10000, tpc_bytes: 0, cleared: std::cell::Cell::new(0) }, + }; + let mut r_ta = [0u32; 16]; + let mut r_fs = [0u32; 16]; + r_ta[0] = 0x100; r_ta[1] = 0x200; r_ta[2] = 0x300; + r_fs[0] = 0x100; r_fs[1] = 0x200; r_fs[2] = 0x300; + let mut pass = [0u32; 16]; + pass[0] = 0; pass[1] = 1; pass[2] = 2; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![RecFlight { + job: RecJob { + resources: Resources { + passes: vec![mk_pass(0x1000), mk_pass(0x2000), mk_pass(0x3000)], + }, + }, + claims: RecClaims { pass }, + computes: 0, + renders: 3, + target: 0, + ta_target: 0x300, + fs_target: 0x300, + cstamp: [0; 16], + r_ta_stamp: r_ta, + r_fs_stamp: r_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + }], + ta_target: 0x300, + }, + recovery: RecState { last_retired: [None; 3] }, + }; + // Pass 0 TA finished (stage[0] == 0x100); interior TA target 0x200 matches and cleans + // TPC only for unfinished passes 1 and 2. + assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, [0x100, 0, 0]), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert_eq!(fw.engine.flights[0].job.resources.passes[0].tpc.cleared.get(), 0); + assert_eq!(fw.engine.flights[0].job.resources.passes[1].tpc.cleared.get(), 0x2000); + assert_eq!(fw.engine.flights[0].job.resources.passes[2].tpc.cleared.get(), 0x3000); + // Interior FS target 0x200 also matches; unrelated target 0x400 returns ENOENT. + assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, [0x300, 0x100, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, [0x300, 0x100, 0]), Err(ENOENT)); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) @@ -1148,6 +1334,12 @@ def item(declaration): .replace('super::command::', 'command::') .replace('super::fence::', 'fence::'), ) +harness = harness.replace( + '__CAN_FOLD_RENDER_CMD__', + item_in(job_src, 'pub(crate) fn can_fold_render_cmd(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) harness = harness.replace( '__RECOVERY_PREPARE__', item('pub(crate) fn recovery_prepare(') @@ -1166,6 +1358,7 @@ def item(declaration): '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', 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 78a09e8da3a532..8b94fd4348147d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -333,8 +333,8 @@ def module(text, name): #[test]fn production_render_descriptors_preserve_firmware_bytes_and_exact_counter(){ let mut o=Objects::new();let mut pools=PoolSet::new(&mut o).unwrap(); let a=pools.prepare(0,1).unwrap();assert!(a.init_buffer);assert_eq!(a.uma_submitted,2); - assert!(!pools.retired(0).unwrap());pools.publish(0,2).unwrap(); - assert!(pools.publish(0,2).is_err());assert!(pools.prepare(0,2).is_err()); + assert!(!pools.retired(0).unwrap());pools.publish_batch(0,2,1).unwrap(); + assert!(pools.publish_batch(0,2,1).is_err());assert!(pools.prepare(0,2).is_err()); let d=o.objects.iter().find(|o|o.va==a.uma_mgr[0]).unwrap(); d.w64(0x54,2).unwrap();d.w64(0x60,0x5a5aa5a5).unwrap(); let original=d.snapshot();assert!(pools.retired(0).unwrap()); @@ -603,7 +603,7 @@ def module(text, name): 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); + pools.publish_batch(0,2,1).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(); @@ -614,7 +614,7 @@ def module(text, name): 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(); + pools.publish_batch(0,refs.uma_submitted,1).unwrap(); p.publish_flight(0); } assert!(!pools.retired_at(0,4).unwrap()); @@ -930,6 +930,73 @@ def module(text, name): assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-1) as u32); } + #[test]fn multi_pass_render_batch_claims_ordered_retirement_and_publish_batch(){ + use crate::g16::pools::PoolSet; + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + 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 render=sync::Arc::new(g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + },0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let a=vm(1); + // Wrapped submission order [14, 15, 0]: retiring in order leaves slot 0 as last_retired + // while slots 14 and 15 are displaced and reusable immediately. + let order=[14usize,15,0]; + let mut c=Claims::new(); + for (i,&k) in order.iter().enumerate() { + s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); + c.pass[i]=k as u32; + c.pass_count+=1; + c.pass_mask|=1<, pub readable: bool } #[derive(Default)] - pub struct Vm { pub regions: Vec } + pub struct Vm { + pub regions: Vec, + pub lock_calls: std::cell::Cell, + pub read_calls: std::cell::Cell, + } + pub struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { + pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { + self.0.read_user(va, out) + } + } impl Vm { pub fn region(&mut self, base: u64, bytes: Vec) { self.regions.push(Region { base, bytes, readable: true }); @@ -55,7 +65,12 @@ self.regions.iter().any(|r| r.readable && va >= r.base && end >= va && end <= r.base + r.bytes.len() as u64) } + pub fn read_lock(&self) -> Result> { + self.lock_calls.set(self.lock_calls.get() + 1); + Ok(VmReadGuard(self)) + } pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { + self.read_calls.set(self.read_calls.get() + 1); let end = va.checked_add(out.len() as u64).ok_or(EFAULT)?; for r in &self.regions { if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { @@ -260,10 +275,48 @@ } #[test] fn vdm_m4_root_barrier() { - assert!(g16::gate::vdm(&vm_for(&[0x21000960]), BASE).is_ok()); + assert!(g16::gate::vdm_batch(&vm_for(&[0x21000960]), &[BASE]).is_ok()); for word in [0, 0x21000964, 0x40000000] { - assert!(g16::gate::vdm(&vm_for(&[word]), BASE).is_err()); + assert!(g16::gate::vdm_batch(&vm_for(&[word]), &[BASE]).is_err()); + } +} +#[test] +fn vdm_batch_shares_lock_caches_window_and_rejects_bad_root() { + let mut vm = mmu::Vm::default(); + let mut page0 = vec![0u8; 0x4000]; + let mut page1 = vec![0u8; 0x4000]; + let root = 0x21000960u32.to_le_bytes(); + for off in [0usize, 0x20, 0x40, 0x80, 0x3ffc] { + page0[off..off + 4].copy_from_slice(&root); } + page1[0x10..0x14].copy_from_slice(&root); + vm.region(BASE, page0); + vm.region(BASE + 0x4000, page1); + + // Empty batch acquires no VM lock. + assert!(g16::gate::vdm_batch(&vm, &[]).is_ok()); + assert_eq!(vm.lock_calls.get(), 0); + assert_eq!(vm.read_calls.get(), 0); + + // Four adjacent VDM roots within 256 bytes share one lock and one read_user. + assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 1); + + // A bad root inside the same cached 256-byte window is still rejected. + vm.regions[0].bytes[0x80..0x84].copy_from_slice(&0xdeadbeefu32.to_le_bytes()); + assert_eq!( + g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), + Err(kernel::prelude::EINVAL) + ); + vm.regions[0].bytes[0x80..0x84].copy_from_slice(&root); + + // Cross-page and end-of-page roots share one lock and never over-read past UAT_PGSZ. + vm.lock_calls.set(0); + vm.read_calls.set(0); + assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 3); } ''' From 1563d4bf37dcc1dc22c039ce68b5313a0e70cad7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:19:20 -0500 Subject: [PATCH 0842/1514] drm/asahi: g16: use stamp-only cross-engine barriers for same-VM non-InitBM handoffs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use BarrierType::Stamp (type 0) instead of BarrierType::Hold (type 1) for same-VM non-InitBM cross-engine barriers (fs2c in prefix_compute() and c2ta/c2fs in prefix_render()), eliminating software-job hold bubbles on compute <-> render handoffs (such as postfx and deferred shading). Why G16 differs from G15 (`g15/hw.rs:566-567`, "Never both type 0"): On G15, `CROSS_ENGINE_HOLD` keeps at least one cross-engine direction at type 1 (`Hold`). On G16 (M4 firmware 25G83/26B123), every GPU stage (CDM, TA, FS) executes its `FINALIZE` micro-sequence — flushing stage caches to the shared coherent fabric — before firmware advances `fw_stamp`, so waiting on `fw_stamp` via `BarrierType::Stamp` (type 0) in both directions (`fs2c` and `c2ta`/`c2fs`) avoids hold bubbles within one VM (same ASID and UAT page tables). Zero-fault M4 J773g runs (13,873 `fs2c` and 20,506 `c2ta` type-0 handoffs on mixed postfx / deferred shading) confirm no GPU wedge or hang, while CTS synchronization / pipeline-barrier coverage validates producer-to-consumer memory visibility. Safety gates preserved: - Whenever either the waited producer, any live in-flight command (`self.engine.flights.iter().any(|fl| fl.initbm)`), or the consumer carries `InitBM`, keep `BarrierType::Hold` via `cross_engine_barrier_type(producer_initbm, consumer_initbm)` across `fs2c`, `c2ta`, `c2fs`, and pipelined render->render barriers (with `WaitTarget` propagating producer `InitBM` state from `wait_stamp_for_with()` and `cross_engine_wait()`). - Cross-VM transitions, recovery paths, and `query_access` CPU-timestamp waits drain `flights` completely before publishing. Audited `waits_for_timestamps` in `can_queue_behind()`: because G16 copies timestamp results into user query-pool BOs on CPU upon flight retirement (`publish_timestamps`), keeping the retirement wait when `query_access` is true (userspace did not pass `DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS`) remains required for query-pool correctness and is documented inline. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 140 +++++++++++++----- .../drivers/gpu/asahi-m4/test-publication.py | 100 +++++++++++-- 2 files changed, 188 insertions(+), 52 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index cfdd218c71b42b..12a6f70d391515 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -136,6 +136,33 @@ impl Progress { } } +/// Resolved in-flight producer target for a hardware ring barrier. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct WaitTarget { + stamp: u32, + /// True if the waited producer flight carries `InitBM` (buffer-manager initialization). + initbm: bool, +} + +/// Selects the hardware ring barrier type for a same-VM handoff. +/// +/// Unlike G15 (`g15/hw.rs: CROSS_ENGINE_HOLD` — "Never both type 0"), G16 (M4 25G83/26B123) +/// does not require a software-job hold on one cross-engine direction when neither side +/// carries `InitBM`. On G16, every stage (CDM, TA, FS) executes its `FINALIZE` +/// micro-sequence — flushing stage caches to the shared coherent fabric — before firmware +/// advances `fw_stamp`, so waiting on `fw_stamp` with `BarrierType::Stamp` (type 0) in both +/// directions (`fs2c` and `c2ta`/`c2fs`) avoids hold bubbles within one VM (same ASID and +/// UAT page tables). Zero-fault M4 J773g runs (13,873 `fs2c` and 20,506 `c2ta` type-0 +/// handoffs) confirm no GPU wedge or hang, while CTS synchronization / pipeline-barrier +/// coverage validates producer-to-consumer memory visibility. +/// +/// Keep `BarrierType::Hold` (type 1) whenever either producer or consumer carries `InitBM` +/// (checked against both the waited target and any live `InitBM` flight). Cross-VM switches, +/// recovery paths, and `query_access` CPU-timestamp waits drain `flights` completely first. +const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) -> BarrierType { + BarrierType::from_stamp_only(!producer_initbm && !consumer_initbm) +} + /// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or /// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -1149,6 +1176,9 @@ impl Firmware { } match command(job, sent) { Some(Command::Compute(c)) => { + // G16 publishes timestamp results into user query-pool BOs on CPU during flight + // retirement, so dispatches without DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS must wait + // for prior timestamped flights in their dependency prefix to retire first. let waits_for_timestamps = c.query_access && job.command_order(sent).is_some_and(|o| { let waits_class = |class: usize| { @@ -1199,17 +1229,17 @@ impl Firmware { } } - /// Resolves a same-queue target stamp for `class` (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> - /// `cstamp`) when `target_seq` names an in-flight command of `job.queue` or an earlier member - /// of an in-progress render batch `current`. Returns `Ok(None)` when no barrier was requested - /// or the waited prefix has already retired. + /// Resolves a same-queue target stamp and producer `InitBM` state for `class` (`RENDER` -> + /// `r_fs_stamp`, `COMPUTE` -> `cstamp`) when `target_seq` names an in-flight command of + /// `job.queue` or an earlier member of an in-progress render batch `current`. Returns + /// `Ok(None)` when no barrier was requested or the waited prefix has already retired. fn wait_stamp_for_with( &self, job: &Arc, class: usize, target_seq: Option, current: Option<&Flight>, - ) -> Result> { + ) -> Result> { let Some(last) = target_seq else { return Ok(None); }; @@ -1226,7 +1256,10 @@ impl Firmware { if flight.job.command_order(k as u32).is_some_and(|fo| { fo.engine == super::command::COMPUTE && fo.sequence == last }) { - return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + return Ok(Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + })); } member += 1; } @@ -1235,7 +1268,10 @@ impl Firmware { if j2.command_order(k).is_some_and(|fo| { fo.engine == super::command::COMPUTE && fo.sequence == last }) { - return Ok(Some(*flight.cstamp.get(member).ok_or(EAGAIN)?)); + return Ok(Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + })); } member += 1; } @@ -1243,7 +1279,7 @@ impl Firmware { } return Err(EAGAIN); } - let find_render = |flight: &Flight| -> Option { + let find_render = |flight: &Flight| -> Option { if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { return None; } @@ -1255,17 +1291,20 @@ impl Firmware { .command_order(k) .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) { - return Some(flight.r_fs_stamp[member]); + return Some(WaitTarget { + stamp: flight.r_fs_stamp[member], + initbm: flight.initbm, + }); } } None }; - if let Some(stamp) = current.and_then(find_render) { - return Ok(Some(stamp)); + if let Some(target) = current.and_then(find_render) { + return Ok(Some(target)); } for flight in &self.engine.flights { - if let Some(stamp) = find_render(flight) { - return Ok(Some(stamp)); + if let Some(target) = find_render(flight) { + return Ok(Some(target)); } } Err(EAGAIN) @@ -1277,15 +1316,20 @@ impl Firmware { job: &Arc, class: usize, target_seq: Option, - ) -> Result> { + ) -> Result> { self.wait_stamp_for_with(job, class, target_seq, None) } - /// Resolves a same-queue cross-engine barrier target stamp when `job`'s command `index` - /// waits on an in-flight command of `other` engine (`RENDER` -> `fs_target`, `COMPUTE` -> - /// `target`). Returns `Ok(None)` when no cross-engine barrier was requested or the waited - /// prefix has already retired. - fn cross_engine_wait(&self, job: &Arc, index: u32, other: usize) -> Result> { + /// Resolves a same-queue cross-engine barrier target when `job`'s command `index` waits on + /// an in-flight command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`). + /// Returns `Ok(None)` when no cross-engine barrier was requested or the waited prefix has + /// already retired. + fn cross_engine_wait( + &self, + job: &Arc, + index: u32, + other: usize, + ) -> Result> { let target_seq = job .command_order(index) .and_then(|o| o.wait_through[other]); @@ -2086,25 +2130,36 @@ impl Firmware { )?; } let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; - if let Some(wait_fs) = wait_render { + let fs2c_bar = if let Some(wait_fs) = wait_render { + // Check producer InitBM explicitly in addition to the scheduler drain guard so + // FS -> CDM handoff: downgrade to `BarrierType::Stamp` (type 0) only when neither + // the waited render nor any live flight carries `InitBM`; G16 FS `FINALIZE` flushes + // caches before advancing `fw_stamp[1]` (see `cross_engine_barrier_type`). + let producer_initbm = wait_fs.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); let bar = encode::barrier( self.graph.render.fw_stamp[1].va, - wait_fs, + wait_fs.stamp, 0x71, target, 0, - BarrierType::Hold, + bar_type, ); s.barrier.write(0, &bar)?; - } + Some((wait_fs.stamp, bar_type)) + } else { + None + }; f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); wmb(); - if let Some(wait_fs) = wait_render { + if let Some((wait_fs, bar_type)) = fs2c_bar { g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; - self.engine.stats.fs2c0 += 1; + if bar_type == BarrierType::Stamp { + self.engine.stats.fs2c0 += 1; + } f.cwait[member] = wait_fs; } else { f.cwait[member] = 0; @@ -2177,8 +2232,11 @@ impl Firmware { params::early_tiling(), prev_fs, order.is_some_and(|o| o.wait_through[super::command::RENDER].is_none()), - ta_wait_fs, - [ta_wait_compute, fs_wait_compute], + ta_wait_fs.map(|w| w.stamp), + [ + ta_wait_compute.map(|w| w.stamp), + fs_wait_compute.map(|w| w.stamp), + ], ); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots @@ -2292,17 +2350,23 @@ impl Firmware { r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } + // Pipelined same-VM render->render and cross-engine (CDM->TA, CDM->FS) barriers use + // `BarrierType::Stamp` (type 0) only when neither producer, any live flight, nor this + // consumer carries `InitBM`: G16 `FINALIZE` flushes producer caches before advancing + // `fw_stamp` (unlike G15's `CROSS_ENGINE_HOLD`; see `cross_engine_barrier_type`). + // Cross-VM transitions and recovery paths drain completely before publishing. + let producer_initbm = pf.initbm + || self.engine.flights.iter().any(|fl| fl.initbm) + || ta_wait_compute.is_some_and(|w| w.initbm) + || fs_wait_compute.is_some_and(|w| w.initbm) + || ta_wait_fs.is_some_and(|w| w.initbm); + let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); // When pipelining behind an in-flight or same-batch same-VM render, insert explicit // hardware ordering barriers on the TA/FS rings. Fragment-only, barrier-free, or staged // renders whose TA prefix stops before the prior FS overlap TA(N) with FS(N-1) (TA waits // on prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior // FS then own TA); otherwise TA(N) waits on prior FS to preserve full vertex visibility. if has_prior_render { - // Pipelined same-VM non-InitBM render->render barriers wait on the producer's - // firmware stamp only (type 0), matching `own_barrier` and G15's - // `RENDER_INTERNAL_HOLD = 0`, so consecutive TA/FS stages hand off without a - // software-job hold bubble. Cross-engine barriers (`fs2c`/`c2ta`) stay `Hold`. - let render_bar = BarrierType::from_stamp_only(!init_buffer); let (wait_va, wait_stamp, wait_event) = if plan.early { (r.fw_stamp[0].va, prev_ta, 0x70) } else { @@ -2354,12 +2418,14 @@ impl Firmware { 15, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.compute_barrier.write(0, &cbar)?; r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va)?; pf.ta_head = (pf.ta_head + 1) % cap; - self.engine.stats.c2ta0 += 1; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } if let Some(wait_c) = plan.fs_compute_wait { let fcbar = encode::barrier( @@ -2368,12 +2434,14 @@ impl Firmware { 15, target, work::barrier::RENDER_WAIT_UUID, - BarrierType::Hold, + render_bar, ); p.fs_compute_barrier.write(0, &fcbar)?; r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va)?; pf.fs_head = (pf.fs_head + 1) % cap; - self.engine.stats.c2ta0 += 1; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } // The paired fragment always requires the native explicit TA dependency. let own = encode::barrier( 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 9dd42f19a2c50a..0305f3ac5149b0 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -45,15 +45,31 @@ def item(declaration): assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src prefix_render_fn = item('fn prefix_render(') prefix_compute_fn = item('fn prefix_compute(') -assert 'let render_bar = BarrierType::from_stamp_only(!init_buffer);' in prefix_render_fn -assert prefix_render_fn.count('render_bar,') == 3, prefix_render_fn +can_queue_behind_fn = item('fn can_queue_behind(') +assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn +assert ( + prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') + < prefix_render_fn.rindex('if has_prior_render') +), 'render_bar must be hoisted ahead of has_prior_render for c2ta/c2fs barriers' +assert prefix_render_fn.count('render_bar,') == 5, prefix_render_fn assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn assert 'p.fs_compute_barrier.write(0, &fcbar)?;' in prefix_render_fn -assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write')] -assert 'BarrierType::Hold,' in prefix_render_fn[prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write')] +c2ta_slice = prefix_render_fn[ + prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write') +] +c2fs_slice = prefix_render_fn[ + prefix_render_fn.index('plan.fs_compute_wait'):prefix_render_fn.index('p.fs_compute_barrier.write') +] +fs2c_slice = prefix_compute_fn[ + prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write') +] +assert 'render_bar,' in c2ta_slice and 'BarrierType::Hold' not in c2ta_slice +assert 'render_bar,' in c2fs_slice and 'BarrierType::Hold' not in c2fs_slice assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] -assert 'BarrierType::Hold,' in prefix_compute_fn[prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write')] +assert 'cross_engine_barrier_type(producer_initbm, false)' in fs2c_slice +assert 'bar_type,' in fs2c_slice and 'BarrierType::Hold' not in fs2c_slice +assert 'let waits_for_timestamps = c.query_access' in can_queue_behind_fn assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src @@ -518,6 +534,19 @@ def item(declaration): } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] + enum BarrierType { + Stamp = 0, + Hold = 1, + } + impl BarrierType { + const fn from_stamp_only(stamp_only: bool) -> Self { + if stamp_only { Self::Stamp } else { Self::Hold } + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + __WAIT_TARGET__ + __CROSS_ENGINE_BARRIER_TYPE__ + #[derive(Copy, Clone, Debug, PartialEq, Eq)] __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ impl QueueBehindHost { @@ -666,8 +695,8 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; // Same-queue FS -> CDM barrier resolves render's fs_target; CDM -> TA resolves compute's target. - assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(0x500))); - assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(0x700))); + assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r2_after_c1,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x700,initbm:false}))); // No-barrier / independent-queue submits emit no cross-engine barrier. assert_eq!(p.cross_engine_wait(&c_nobarrier,0,command::RENDER),Ok(None)); assert_eq!(p.cross_engine_wait(&c_other_q,0,command::RENDER),Ok(None)); @@ -700,10 +729,47 @@ def item(declaration): slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; - assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); - assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); assert_eq!(pm.cross_engine_wait(&r_wait_missing,0,command::COMPUTE),Err(EAGAIN)); } + #[test]fn cross_engine_barrier_keeps_hold_when_producer_or_consumer_carries_initbm(){ + // Healthy same-VM non-InitBM handoffs downgrade to BarrierType::Stamp (type 0). + assert_eq!(cross_engine_barrier_type(false, false), BarrierType::Stamp); + // Any InitBM on either producer (including FS -> CDM) or consumer keeps BarrierType::Hold. + assert_eq!(cross_engine_barrier_type(true, false), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(false, true), BarrierType::Hold); + assert_eq!(cross_engine_barrier_type(true, true), BarrierType::Hold); + + // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),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:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let r_initbm=mk(1,true,1,[None,None]); + let c_after_r=mk(2,false,1,[Some(1),None]); + let r_after_r=mk(3,true,2,[Some(1),None]); + let host=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,target:0, + cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, + initbm:true,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}, + }; + let fs2c = host.cross_engine_wait(&c_after_r, 0, command::RENDER).unwrap().unwrap(); + assert_eq!(fs2c, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(fs2c.initbm, false), BarrierType::Hold); + let r2r = host.wait_stamp_for(&r_after_r, command::RENDER, Some(1)).unwrap().unwrap(); + assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); + assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); + } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); let mut done=vec![]; @@ -778,8 +844,8 @@ def item(declaration): slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; - assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(0x200))); - assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(0x300))); + assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); // Active computes sum flight.computes: 16 batched computes saturates compute_flights(). assert!(p.can_queue_behind(&c4)); p.engine.flights[0].computes=16; @@ -818,9 +884,9 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; // Lookup into published multi-pass render flight resolves interior and tail passes. - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(0x100))); - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(0x200))); - assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(0x300))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(WaitTarget{stamp:0x100,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(2)),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(3)),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(4)),Err(EAGAIN)); // Lookup against an in-progress same-batch flight resolves earlier pass before publish. let mut cur_fs=[0u32;16]; @@ -829,7 +895,7 @@ def item(declaration): job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; - assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(0x400))); + assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); // Active renders sum flight.renders: 15 batched renders saturates render_flights(). assert!(p.can_queue_behind(&next_r)); p.engine.flights[0].renders=15; @@ -1362,6 +1428,8 @@ def item(declaration): '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', + '__WAIT_TARGET__': 'struct WaitTarget {', + '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): @@ -1378,7 +1446,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 60, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 61, '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') From e7944794bfa57d48cc90934dc1562ec49688f038 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 07:18:02 -0500 Subject: [PATCH 0843/1514] drm/asahi: g16: expand render extension slots on overlap or burst Cache::prepare() previously gated RenderExtArena allocation on compute's 2 ms BURST_GAP_NS and 3-command BURST_COMMANDS thresholds. Heavy multi-millisecond pipelined renders arrive more than 2 ms apart and would reset render_burst to 0 on every submit, staying capped at BASE_RENDER_SLOTS (2 slots), whereas simply widening the idle gap to cover 60/120 Hz frame periods would force every steady depth-1 compositor or window client to allocate 14 extension pass slots it never uses. Track live prepared render jobs per VM in Cache::active_renders (incremented on returning Prepared and decremented in Prepared::drop), keep the 2 ms BURST_GAP_NS for back-to-back single-pass bursts, and expand RenderExtArena when a render overlaps an active in-flight render (active_renders != 0), submits at least BASE_RENDER_SLOTS passes in one SUBMIT, or sustains a sub-2 ms burst. Add a host unit test covering steady 60/120 fps depth-1 non-expansion, multi-ms overlap, sub-2 ms bursts, and multi-pass submits. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/resources.rs | 65 +++++++++++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 48 +++++++++++++- 2 files changed, 98 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index b3fa26dee9f79a..68de11188884b8 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -80,10 +80,38 @@ 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. +/// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are added lazily once the VM actually +/// pipelines renders or submits a multi-pass/burst frame. pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLOTS; +/// Single-submission render command count that expands extension slots immediately: +/// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. +const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; + +/// Updates the consecutive-render burst counter and reports whether this submission +/// qualifies to allocate extension pass slots (`RenderExtArena`). +/// +/// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives +/// (`active_renders == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay +/// on the two base pass slots. Extension slots allocate when a VM actually overlaps an +/// in-flight render (`active_renders != 0`, including multi-ms 1080p/4K pipelined frames), +/// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a +/// sub-2 ms back-to-back burst. +fn should_expand_render_ext( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_renders: u32, +) -> bool { + *render_burst = if *last_render_ns != 0 && now.wrapping_sub(*last_render_ns) < BURST_GAP_NS { + render_burst.saturating_add(1) + } else { + 0 + }; + *last_render_ns = now; + active_renders != 0 || *render_burst >= BURST_SUBMITS || render_count >= RENDER_BURST_COMMANDS +} pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { @@ -243,6 +271,8 @@ pub(crate) struct Cache { standby_available: CondVar, /// The VM's client closed: no arena or surplus spare is kept here any more. closed: AtomicBool, + /// Prepared render jobs on this VM that have not yet retired and dropped. + active_renders: AtomicU32, pub(crate) factory: Factory, bind: mmu::VmBind, live: Arc, @@ -268,6 +298,7 @@ impl Cache { ), standby_available <- new_condvar!(), closed: AtomicBool::new(false), + active_renders: AtomicU32::new(0), factory, bind, live, budget }), GFP_KERNEL, ) @@ -457,17 +488,17 @@ impl Cache { if ready.render_ext.is_none() && EXT_RENDER_SLOTS != 0 { // 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_burst >= BURST_SUBMITS - || render_count as usize >= BURST_COMMANDS - { + let state = &mut *ready; + let active = self.active_renders.load(Ordering::Acquire); + if should_expand_render_ext( + &mut state.last_render_ns, + &mut state.render_burst, + now, + render_count as usize, + active, + ) { // Best effort: without extension slots the VM keeps two base pass slots. - ready.render_ext = + state.render_ext = RenderExtArena::new(&self.factory, &self.bind, &vm.vm, &self.live).ok(); } } @@ -563,13 +594,19 @@ impl Cache { } return Err(EIO); } + let cache = if render_count != 0 { + self.active_renders.fetch_add(1, Ordering::AcqRel); + Some(self.clone()) + } else { + None + }; Ok(Prepared { compute, compute_ext, render: render_arena, render_ext, unpublished_renders: AtomicU32::new(render_count), - cache: (render_count != 0).then(|| self.clone()), + cache, }) } } @@ -593,6 +630,8 @@ impl Drop for Prepared { let Some(cache) = self.cache.take() else { return; }; + let previous = cache.active_renders.fetch_sub(1, Ordering::AcqRel); + debug_assert!(previous != 0); let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); cache.release_reserved(remaining); } 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 8b94fd4348147d..a786f17346c1e2 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -168,6 +168,8 @@ def module(text, name): } pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } + pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; + __RENDER_BURST__ } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} // Arenas here have the two base units. @@ -997,6 +999,43 @@ def module(text, name): assert!(!pools.retired_at(0,6).unwrap()); } + #[test]fn render_burst_expands_on_overlap_multipass_or_sub2ms_burst_not_steady_60_120fps(){ + use crate::g16::resources::should_expand_render_ext; + // Steady 60 fps (16.67 ms) and 120 fps (8.33 ms) single-pass depth-1 clients + // finish each frame before the next arrives (active_renders == 0) and stay on + // the two base pass slots without allocating RenderExtArena. + for period_ns in [16_666_667u64, 8_333_333u64] { + let mut last = 0u64; + let mut burst = 0u32; + for step in 1u64..=10 { + assert!(!should_expand_render_ext(&mut last, &mut burst, step * period_ns, 1, 0)); + assert_eq!(burst, 0); + } + } + + // Heavy multi-ms pipelined renders (e.g. 5 ms and 16.6 ms apart) overlap an + // already-active render (active_renders >= 1) and expand immediately. + let mut last = 0u64; + let mut burst = 0u32; + assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0)); + assert!(should_expand_render_ext(&mut last, &mut burst, 6_000_000, 1, 1)); + assert!(should_expand_render_ext(&mut last, &mut burst, 22_600_000, 1, 1)); + + // Sub-2 ms back-to-back single-pass bursts still expand after 3 consecutive gaps. + let mut last = 0u64; + let mut burst = 0u32; + assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 2_000_000, 1, 0)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 3_000_000, 1, 0)); + assert!(should_expand_render_ext(&mut last, &mut burst, 4_000_000, 1, 0)); + assert_eq!(burst, 3); + + // A single multi-pass SUBMIT with >= BASE_RENDER_SLOTS (2) renders expands immediately. + let mut last = 0u64; + let mut burst = 0u32; + assert!(should_expand_render_ext(&mut last, &mut burst, 100_000_000, 2, 0)); + } + } ''' budget=(production/'budget.rs').read_text() @@ -1024,7 +1063,12 @@ def module(text, name): ''' source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) -source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item((production/'resources.rs').read_text(),'pub(crate) fn set_dirty(')) +resources_source = (production/'resources.rs').read_text() +render_burst_lines = '\n'.join( + line for line in resources_source.splitlines() + if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const RENDER_BURST_COMMANDS:')) +) + '\npub(crate) ' + item(resources_source, 'fn should_expand_render_ext(') +source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) (out/'check-resources.rs').write_text(source) @@ -1041,7 +1085,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 27, + 'result': 'pass', 'tests': 28, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 0764260fe6630057d1c8c819ce299b9ed4e1e645 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 06:37:29 -0500 Subject: [PATCH 0844/1514] drm/asahi: use VM reservation lock for VmReadGuard and merge G16 render validation Vm::read_lock() previously called lock_vm(&self.gpuvm, None, false), which allocates a KBox, runs drm_exec_init() (allocating a page-sized object array), and locks every external BO reservation on the VM (O(external BOs)) on every G16/G15 SUBMIT. Because every mapping mutation in mmu.rs holds the VM's shared reservation, read-only page-table coverage walks and user-memory copies need only self.gpuvm.lock_inner(), matching covers_ranges_batch(): 1. Back VmReadGuard<'a> with GpuVmInnerGuard<'a, VmInner> via self.gpuvm.lock_inner(), eliminating the per-SUBMIT KBox, drm_exec object-array allocation, and O(external BOs) lock walk. 2. In G16 Prepared::validate(), validate render VM spans and VDM root barriers under one Vm::read_lock() hold via SpanBatch::flush_locked() and gate::vdm_batch_locked(). 3. Minimize PoC cache maintenance (dc civac + dsb sy) in G16 stream gates: read only 4 bytes (1 cache line) for single-pass VDM roots and clamp CDM root-stream window reads to the validated root end. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g15/command.rs | 12 ++-- drivers/gpu/drm/asahi/g15/gate.rs | 12 ++-- drivers/gpu/drm/asahi/g16/command.rs | 31 +++++++++- drivers/gpu/drm/asahi/g16/gate.rs | 40 ++++++++----- drivers/gpu/drm/asahi/mmu.rs | 15 +++-- .../gpu/asahi-m4/test-command-stream.py | 14 +++++ .../drivers/gpu/asahi-m4/test-stream-gate.py | 56 +++++++++++++------ 7 files changed, 128 insertions(+), 52 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs index 66e52e69811977..c88979e00d47d8 100644 --- a/drivers/gpu/drm/asahi/g15/command.rs +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -146,8 +146,8 @@ pub(crate) struct Context<'a> { pub(crate) usc_base: u64, } -struct CheckedContext<'a> { - vm: &'a mut mmu::VmReadGuard, +struct CheckedContext<'a, 'b> { + vm: &'a mut mmu::VmReadGuard<'b>, usc_base: u64, } @@ -383,7 +383,7 @@ impl Timestamps<'_> { /// GPU access: a driver range ENOENT, outside the user range EINVAL, an unmapped page ENOENT, a /// page without the access EACCES. pub(crate) fn cover( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, read: bool, @@ -419,7 +419,7 @@ pub(crate) fn cover( /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. fn check_attachments( - vm: &mut mmu::VmReadGuard, + vm: &mut mmu::VmReadGuard<'_>, list: &[uapi::drm_asahi_attachment], write: bool, ) -> Result { @@ -482,7 +482,7 @@ fn geometry_bytes(cmd: &uapi::drm_asahi_cmd_render) -> (u64, u64) { } /// Per-command render admission. -fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { +fn check_render(context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_render) -> Result { let vm = &mut *context.vm; let allowed = PROCESS_EMPTY_TILES | NO_VERTEX_CLUSTERING @@ -567,7 +567,7 @@ fn check_render(context: &mut CheckedContext<'_>, cmd: &uapi::drm_asahi_cmd_rend /// Per-command compute admission. fn check_compute( - context: &mut CheckedContext<'_>, + context: &mut CheckedContext<'_, '_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], ) -> Result { diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs index 590f5e6f0a5c11..09e4d1855031db 100644 --- a/drivers/gpu/drm/asahi/g15/gate.rs +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -71,7 +71,7 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page /// unless the record crosses it). Unreadable memory: EFAULT. - fn words(&mut self, vm: &mut mmu::VmReadGuard, va: u64, count: usize) -> Result<[u32; 10]> { + fn words(&mut self, vm: &mut mmu::VmReadGuard<'_>, va: u64, count: usize) -> Result<[u32; 10]> { let n = count * 4; let cached = self.len != 0 && va >= self.va @@ -108,7 +108,7 @@ struct Checked { /// One page check of `[start, end)` under the walk's page budget: ENOSPC once the budget is /// spent. -fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Result { +fn check(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, count: &mut u32) -> Result { if *count >= CDM_MAX_PAGE_CHECKS { return Err(ENOSPC); } @@ -118,7 +118,7 @@ fn check(vm: &mut mmu::VmReadGuard, start: u64, end: u64, count: &mut u32) -> Re /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// The last proven program page is not checked again. -fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Checked) -> Result { +fn program(vm: &mut mmu::VmReadGuard<'_>, usc: u64, address: u64, checked: &mut Checked) -> Result { if address < usc || address - usc >= USC_WINDOW || address & 63 != 0 { return Err(EINVAL); } @@ -134,7 +134,7 @@ fn program(vm: &mut mmu::VmReadGuard, usc: u64, address: u64, checked: &mut Chec /// An indirect launch's 12 argument bytes: readable. The last proven argument page is not /// checked again; arguments that cross a page are checked each time. -fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> Result { +fn arguments(vm: &mut mmu::VmReadGuard<'_>, address: u64, checked: &mut Checked) -> Result { let end = address.checked_add(12).ok_or(EINVAL)?; let page = address & !(mmu::UAT_PGMSK as u64); let within = (end - 1) & !(mmu::UAT_PGMSK as u64) == page; @@ -149,7 +149,7 @@ fn arguments(vm: &mut mmu::VmReadGuard, address: u64, checked: &mut Checked) -> } /// VDM admission: a normal root stream opens with exactly the G15 barrier. -pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { +pub(crate) fn vdm(vm: &mut mmu::VmReadGuard<'_>, va: u64) -> Result { if !params::stream_gate() { return Ok(()); } @@ -165,7 +165,7 @@ pub(crate) fn vdm(vm: &mut mmu::VmReadGuard, va: u64) -> Result { /// CDM admission: walks the stream from its base through no-return links until TERMINATE, /// admitting only the known G15S records: direct launch (40), indirect launch (36/24), barriers /// (4), link (8). -pub(crate) fn cdm(vm: &mut mmu::VmReadGuard, usc: u64, base: u64) -> Result { +pub(crate) fn cdm(vm: &mut mmu::VmReadGuard<'_>, usc: u64, base: u64) -> Result { if !params::stream_gate() { return Ok(()); } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 86d7e2ddea756a..65927544b46d1e 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -686,6 +686,26 @@ impl SpanBatch { } Ok(()) } + + fn flush_locked(&mut self, guard: &mut mmu::VmReadGuard<'_>) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + for &(first, size, access) in &self.ranges[..n] { + let read = access & 1 != 0; + let write = access & 2 != 0; + if !guard.covers_range(first, size, read, write) { + return if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + }; + } + } + Ok(()) + } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. @@ -740,7 +760,7 @@ fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result, start: u64, end: u64, read: bool, @@ -1246,8 +1266,13 @@ impl Prepared { } } } - batch.flush(context.vm)?; - gate::vdm_batch(context.vm, &vdm_vas[..vdm_count])?; + if vdm_count != 0 { + let mut guard = context.vm.read_lock().map_err(|_| EFAULT)?; + batch.flush_locked(&mut guard)?; + gate::vdm_batch_locked(&mut guard, &vdm_vas[..vdm_count])?; + } else { + batch.flush(context.vm)?; + } Ok(Submission { counts, commands, diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 2798f8fc313ae6..06050e5d83fe57 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -57,14 +57,26 @@ struct Window { impl Window { /// The `count` words at `va`, reading whole spans of up to 256 bytes (not past the page - /// unless the record crosses it) under an already-held VM read lock. Unreadable memory: EFAULT. - fn words(&mut self, guard: &mut mmu::VmReadGuard, va: u64, count: usize) -> Result<[u32; 10]> { + /// or an optional root-stream `limit` unless the record crosses it) under an already-held + /// VM read lock. Unreadable memory: EFAULT. + fn words( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + va: u64, + count: usize, + limit: Option, + ) -> Result<[u32; 10]> { let n = count.checked_mul(4).filter(|&n| n <= 40).ok_or(EINVAL)?; let end = va.checked_add(n as u64).ok_or(EINVAL)?; let cached = self.len != 0 && va >= self.va && end <= self.va + self.len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = n.max(self.bytes.len().min(in_page)); + let mut max_len = self.bytes.len().min(in_page); + if let Some(limit_va) = limit { + let rem = usize::try_from(limit_va.saturating_sub(va)).unwrap_or(usize::MAX); + max_len = max_len.min(rem); + } + let len = n.max(max_len); let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; cover_locked(guard, va, cover_end, true, false)?; self.len = 0; @@ -89,7 +101,7 @@ impl Window { /// A launch's program: inside the queue's 4 GiB USC window, 64-aligned, first block readable. /// `checked` caches the last proven program page. fn program( - guard: &mut mmu::VmReadGuard, + guard: &mut mmu::VmReadGuard<'_>, usc: u64, address: u64, checked: &mut Option, @@ -107,22 +119,23 @@ fn program( Ok(()) } -/// VDM admission for a batch of root streams under a single VM read lock, caching up to -/// 256 intra-page bytes across adjacent VDM roots (for example in a multi-pass render SUBMIT). -pub(crate) fn vdm_batch(vm: &mmu::Vm, vas: &[u64]) -> Result { +/// VDM admission for a batch of root streams under an already-held VM read lock. +/// Reads only the 4-byte root word for a single pass to minimize PoC cache maintenance, +/// and caches up to 256 intra-page bytes across multi-pass batches. +pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Result { if vas.is_empty() || !params::stream_gate() { return Ok(()); } - let mut guard = vm.read_lock().map_err(|_| EFAULT)?; let mut win_va = 0u64; let mut win_len = 0usize; let mut buf = [0u8; 256]; + let max_read = if vas.len() == 1 { 4 } else { buf.len() }; for &va in vas { let end = va.checked_add(4).ok_or(EINVAL)?; let cached = win_len != 0 && va >= win_va && end <= win_va + win_len as u64; if !cached { let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = buf.len().min(in_page); + let len = max_read.min(in_page); if len < 4 { return Err(EINVAL); } @@ -167,7 +180,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { let mut power = 1u64; let mut first = true; let mut resched = 0; - let mut guard: Option = None; + let mut guard: Option> = None; loop { if first { first = false; @@ -207,8 +220,9 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } Ok(()) }; + let limit = (!linked).then_some(end); root_bytes(va, 4)?; - let w = window.words(guard, va, 1)?; + let w = window.words(guard, va, 1, limit)?; if w[0] == CDM_TERMINATE { return Ok(()); } @@ -228,7 +242,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } if w[0] & 0xffff0000 == CDM_LINK { root_bytes(va, 8)?; - let w = window.words(guard, va, 2)?; + let w = window.words(guard, va, 2, limit)?; let target = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); if target & 3 != 0 || target == va { return Err(reject("CDM link", va, &w)); @@ -248,7 +262,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { _ => return Err(reject("CDM launch mode", va, &w)), }; root_bytes(va, (words * 4) as u64)?; - let w = window.words(guard, va, words)?; + let w = window.words(guard, va, words, limit)?; let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); match program(guard, usc, address, &mut checked) { Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index d2935c1423e352..9714f96993d0d9 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -506,10 +506,10 @@ fn lock_vm( } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -pub(crate) struct VmReadGuard(VmExecGuard); +pub(crate) struct VmReadGuard<'a>(gpuvm::GpuVmInnerGuard<'a, VmInner>); #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] -impl VmReadGuard { +impl VmReadGuard<'_> { pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } @@ -2622,15 +2622,18 @@ impl Vm { /// Every page must be mapped GPU-readable and be RAM; otherwise EFAULT. The lines are cleaned /// and invalidated to the point of coherency first (never only invalidated: CPU-written lines /// may be dirty), so the copy sees what the GPU or a write-combined CPU view stored. The - /// mappings cannot change during the copy (GPUVM exec lock). + /// mappings cannot change during the copy (VM reservation lock). #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] pub(crate) fn read_user(&self, va: u64, buf: &mut [u8]) -> Result { self.read_lock()?.read_user(va, buf) } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] - pub(crate) fn read_lock(&self) -> Result { - Ok(VmReadGuard(lock_vm(&self.gpuvm, None, false)?)) + pub(crate) fn read_lock(&self) -> Result> { + // Every mapping change holds the VM reservation, so read-only page-table walks and + // user-memory copies need only that reservation. The full exec lock would allocate a + // `drm_gpuvm_exec` context and lock every external BO, making each submit O(external BOs). + Ok(VmReadGuard(self.gpuvm.lock_inner())) } #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] @@ -2650,7 +2653,7 @@ impl Vm { } let phys = inner.page_table.translate_iova(page).map_err(|_| EFAULT)?; // SAFETY: `phys` is checked to be a RAM page; it stays mapped (and its backing pinned) - // while the exec lock is held, and is only read here. + // while the VM reservation lock is held, and is only read here. let ram = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; let target = &mut buf[done..done + count]; ram.with_pointer_into_page(within, count, |p| { 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 b4e607ee01aebc..1d42a67358760e 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 @@ -651,11 +651,20 @@ } pub(crate) mod mmu { pub(crate) const UAT_PGMSK: usize = 0x3fff; + pub(crate) struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { + pub(crate) fn covers_range(&mut self, start: u64, size: u64, read: bool, write: bool) -> bool { + self.0.covers_range(start, size, read, write) + } + } pub(crate) struct Vm { pub(crate) maps: Vec<(u64, u64, bool, bool)>, pub(crate) batch_calls: std::cell::Cell, } impl Vm { + pub(crate) fn read_lock(&self) -> super::Result> { + Ok(VmReadGuard(self)) + } pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { let Some(end) = start.checked_add(size) else { return false }; self.maps.iter().any(|&(s, e, r, w)| { @@ -824,6 +833,11 @@ assert_eq!(vm.batch_calls.get(), 0); assert_eq!(batch.flush(&vm), Ok(())); assert_eq!(vm.batch_calls.get(), 1); + let mut guard = vm.read_lock().unwrap(); + assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); + assert_eq!(batch.flush_locked(&mut guard), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + drop(guard); // Unmapped or read-only span on a later pass still reports exact ENOENT / EACCES. let mut bad_unmapped = base_cmd(); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index 22970b5b9a4388..b8be082c0b5503 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -50,18 +50,17 @@ pub regions: Vec, pub lock_calls: std::cell::Cell, pub read_calls: std::cell::Cell, + pub last_read_len: std::cell::Cell, } - pub struct VmReadGuard(*const Vm); - impl VmReadGuard { + pub struct VmReadGuard<'a>(&'a Vm); + impl VmReadGuard<'_> { pub fn covers_range(&mut self, address: u64, size: u64, _read: bool, _write: bool) -> bool { - let vm = unsafe { &*self.0 }; address .checked_add(size) - .is_some_and(|end| vm.contains(address, end)) + .is_some_and(|end| self.0.contains(address, end)) } pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { - let vm = unsafe { &*self.0 }; - vm.read_user(va, out) + self.0.read_user(va, out) } } impl Vm { @@ -72,12 +71,13 @@ self.regions.iter().any(|r| r.readable && va >= r.base && end >= va && end <= r.base + r.bytes.len() as u64) } - pub fn read_lock(&self) -> Result { + pub fn read_lock(&self) -> Result> { self.lock_calls.set(self.lock_calls.get() + 1); - Ok(VmReadGuard(self as *const Vm)) + Ok(VmReadGuard(self)) } pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { self.read_calls.set(self.read_calls.get() + 1); + self.last_read_len.set(out.len()); let end = va.checked_add(out.len() as u64).ok_or(EFAULT)?; for r in &self.regions { if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { @@ -102,7 +102,7 @@ pub fn reset_cover_calls() { COVER_CALLS.with(|c| c.set(0)); } pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } pub fn cover_locked( - guard: &mut mmu::VmReadGuard, + guard: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, read: bool, @@ -286,11 +286,15 @@ assert_eq!(result, Err(kernel::prelude::ERESTARTSYS)); assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); } +fn vdm_check(vm: &mmu::Vm, vas: &[u64]) -> kernel::prelude::Result { + let mut guard = vm.read_lock()?; + g16::gate::vdm_batch_locked(&mut guard, vas) +} #[test] fn vdm_m4_root_barrier() { - assert!(g16::gate::vdm_batch(&vm_for(&[0x21000960]), &[BASE]).is_ok()); + assert!(vdm_check(&vm_for(&[0x21000960]), &[BASE]).is_ok()); for word in [0, 0x21000964, 0x40000000] { - assert!(g16::gate::vdm_batch(&vm_for(&[word]), &[BASE]).is_err()); + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_err()); } } #[test] @@ -306,20 +310,20 @@ vm.region(BASE, page0); vm.region(BASE + 0x4000, page1); - // Empty batch acquires no VM lock. - assert!(g16::gate::vdm_batch(&vm, &[]).is_ok()); - assert_eq!(vm.lock_calls.get(), 0); + // Empty batch performs no reads. + assert!(vdm_check(&vm, &[]).is_ok()); assert_eq!(vm.read_calls.get(), 0); // Four adjacent VDM roots within 256 bytes share one lock and one read_user. - assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); + vm.lock_calls.set(0); + assert!(vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); assert_eq!(vm.read_calls.get(), 1); // A bad root inside the same cached 256-byte window is still rejected. vm.regions[0].bytes[0x80..0x84].copy_from_slice(&0xdeadbeefu32.to_le_bytes()); assert_eq!( - g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), + vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), Err(kernel::prelude::EINVAL) ); vm.regions[0].bytes[0x80..0x84].copy_from_slice(&root); @@ -327,7 +331,7 @@ // Cross-page and end-of-page roots share one lock and never over-read past UAT_PGSZ. vm.lock_calls.set(0); vm.read_calls.set(0); - assert!(g16::gate::vdm_batch(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); + assert!(vdm_check(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); assert_eq!(vm.read_calls.get(), 3); } @@ -361,6 +365,22 @@ assert_eq!(sched_delta, 3); assert_eq!(long_vm.lock_calls.get(), sched_delta); } +#[test] +fn single_vdm_and_short_cdm_root_minimize_poc_read_len() { + let vm = vm_for(&[0x21000960]); + assert!(vdm_check(&vm, &[BASE]).is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(vm.read_calls.get(), 1); + assert_eq!(vm.last_read_len.get(), 4); + + let mut words = launch(0, USC, 0); + words.push(0x40000000); + let cdm_vm = vm_for(&words); + assert!(g16::gate::cdm(&cdm_vm, USC, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert_eq!(cdm_vm.lock_calls.get(), 1); + assert_eq!(cdm_vm.read_calls.get(), 1); + assert_eq!(cdm_vm.last_read_len.get(), words.len() * 4); +} ''' with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: @@ -374,7 +394,7 @@ (OUT / 'stream-gate-host.log').write_text(result.stdout + result.stderr) (OUT / 'stream-gate-host.json').write_text(json.dumps({ 'source': str(SOURCE), 'sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result': 'pass', 'test_groups': 11, + 'result': 'pass', 'test_groups': 12, 'mesa_sources': ['src/asahi/genxml/agx3_cmdstream.h', 'src/asahi/lib/agx3_cdm_decode_core.c', 'src/asahi/lib/agx_vdm_barrier_core.c'], 'limitations': 'Host VM model validates parser, addresses, cycles and interruption; hardware and kernel cache behavior require target tests.' From 19c5d8aa25e500d5ef25c3292f97c8fde03f562b Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 10:21:42 -0500 Subject: [PATCH 0845/1514] drm/asahi: g16: elide redundant independent FS and TA-FS render barriers Previously prefix_render() unconditionally emitted a same-ring FS(N-1)->FS(N) barrier (fs_dep) on every pipelined early render pass, even when vdm_barrier was NONE or the render dependency had already retired or been satisfied by TA. Resolve the exact in-flight render wait stamp (fs_wait_render) in prefix_render() and plan_render_barriers(): - Keep the TA(N-1)->TA(N) prev_barrier (matching G15) whenever a prior render is in flight and plan.ta_fs_wait does not already serialize TA behind prev_fs (which dominates prev_ta via own_barrier): consecutive pipelined renders share one parameter-buffer / UMA epoch (RENDER_UMA_SLOT), so TA(N) must still wait on TA(N-1) before writing into the shared PB. - Emit cross-ring FS->TA (ta_fs_barrier) only when plan.ta_fs_wait names an in-flight FS stamp (legacy dependent renders, conservative early_tiling=false, or staged TA waits). - Emit FS->FS (fs_dep) only when plan.fs_render_wait names an in-flight FS dependency not already dominated by plan.ta_fs_wait. - Pre-check wait_stamp_for_with() for o2.wait_through[RENDER] in the multi-pass render batch fold loop so prefix_render() never defers after claiming a pass slot. Independent multi-pass renders drop fs_dep (from 3 hardware barrier records / 5 ring entries per pass to 2 barrier records / 4 ring entries) while preserving TA->TA serialization on the shared PB epoch, exact FS->FS coherence on dependent passes, and cross-VM / InitBM boundaries. Expand test-publication.py to cover independent multi-pass renders, dependent FRAGMENT_BARRIERS/STAGE_PREFIXES renders (including TA-dominated waits and older-FS waits), legacy renders, early_tiling=false, and cross-VM/InitBM boundaries. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 154 +++++++++++----- drivers/gpu/drm/asahi/g16/slots.rs | 2 - .../drivers/gpu/asahi-m4/test-publication.py | 164 +++++++++++++++--- 3 files changed, 247 insertions(+), 73 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 606d824a28ad59..84427844f6f5c8 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -168,19 +168,27 @@ const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct RenderBarrierPlan { early: bool, + ta_prev_wait: bool, ta_fs_wait: Option, + fs_render_wait: Option, ta_compute_wait: Option, fs_compute_wait: Option, } /// Computes TA/FS hardware ring barriers for a render command from its flags, prior render -/// FS stamp, and resolved `[ta, fs]` compute wait stamps. +/// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), and resolved `[ta, fs]` +/// compute wait stamps. +/// +/// Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so TA(N) +/// must still wait on TA(N-1) (`ta_prev_wait`, matching G15's `prev_barrier`) whenever +/// `ta_fs_wait` does not already wait on `prev_fs` (which dominates `prev_ta` via +/// `own_barrier`). Independent FS passes still omit `fs_dep`. fn plan_render_barriers( flags: u32, class_behind: bool, early_tiling: bool, prev_fs: u32, - no_render_barrier: bool, + fs_wait_render: Option, ta_wait_fs: Option, compute_waits: [Option; 2], ) -> RenderBarrierPlan { @@ -188,6 +196,7 @@ fn plan_render_barriers( flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; let frag_only = flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; + let no_render_barrier = fs_wait_render.is_none(); let early = class_behind && early_tiling && if staged { @@ -195,7 +204,27 @@ fn plan_render_barriers( } else { frag_only || no_render_barrier }; - let ta_fs_wait = if early && staged { ta_wait_fs } else { None }; + let ta_fs_wait = if !class_behind { + None + } else if !early { + if !early_tiling { + Some(prev_fs) + } else if staged { + ta_wait_fs.or(Some(prev_fs)) + } else { + fs_wait_render.or(Some(prev_fs)) + } + } else if staged { + ta_wait_fs + } else { + None + }; + let ta_prev_wait = class_behind && ta_fs_wait != Some(prev_fs); + let fs_render_wait = if class_behind && early && fs_wait_render != ta_fs_wait { + fs_wait_render + } else { + None + }; let [ta_compute_wait, fs_wait] = compute_waits; let fs_compute_wait = if fs_wait != ta_compute_wait { fs_wait @@ -204,7 +233,9 @@ fn plan_render_barriers( }; RenderBarrierPlan { early, + ta_prev_wait, ta_fs_wait, + fs_render_wait, ta_compute_wait, fs_compute_wait, } @@ -1800,6 +1831,14 @@ impl Firmware { None, ) .is_err() + || self + .wait_stamp_for_with( + job, + super::command::RENDER, + o2.wait_through[super::command::RENDER], + Some(f), + ) + .is_err() || (staged2 && params::early_tiling() && self @@ -2195,10 +2234,15 @@ impl Firmware { let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); let has_prior_render = class_behind || member > 0; - let (prev_ta, prev_fs) = if member > 0 { - (pf.last_ta, pf.last_fs) + let prev_ta = if member > 0 { + pf.last_ta + } else { + self.engine.ta_target + }; + let prev_fs = if member > 0 { + pf.last_fs } else { - (self.engine.ta_target, self.engine.fs_target) + self.engine.fs_target }; let order = job.command_order(cmd_index); let staged = cmd.cmd.flags @@ -2216,6 +2260,22 @@ impl Firmware { order.and_then(|o| o.wait_through[super::command::COMPUTE]), None, )?; + let fs_wait_render = if has_prior_render { + match order { + Some(o) => self.wait_stamp_for_with( + job, + super::command::RENDER, + o.wait_through[super::command::RENDER], + Some(f), + )?, + None => Some(WaitTarget { + stamp: prev_fs, + initbm: false, + }), + } + } else { + None + }; let ta_wait_fs = if has_prior_render && staged && params::early_tiling() { self.wait_stamp_for_with( job, @@ -2231,7 +2291,7 @@ impl Firmware { has_prior_render, params::early_tiling(), prev_fs, - order.is_some_and(|o| o.wait_through[super::command::RENDER].is_none()), + fs_wait_render.map(|w| w.stamp), ta_wait_fs.map(|w| w.stamp), [ ta_wait_compute.map(|w| w.stamp), @@ -2359,23 +2419,19 @@ impl Firmware { || self.engine.flights.iter().any(|fl| fl.initbm) || ta_wait_compute.is_some_and(|w| w.initbm) || fs_wait_compute.is_some_and(|w| w.initbm) + || fs_wait_render.is_some_and(|w| w.initbm) || ta_wait_fs.is_some_and(|w| w.initbm); let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); - // When pipelining behind an in-flight or same-batch same-VM render, insert explicit - // hardware ordering barriers on the TA/FS rings. Fragment-only, barrier-free, or staged - // renders whose TA prefix stops before the prior FS overlap TA(N) with FS(N-1) (TA waits - // on prior TA plus any older in-flight FS named by `ta_wait_through`; FS waits on prior - // FS then own TA); otherwise TA(N) waits on prior FS to preserve full vertex visibility. - if has_prior_render { - let (wait_va, wait_stamp, wait_event) = if plan.early { - (r.fw_stamp[0].va, prev_ta, 0x70) - } else { - (r.fw_stamp[1].va, prev_fs, 0x71) - }; + // Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so keep + // the TA(N-1)->TA(N) `prev_barrier` (matching G15) whenever `plan.ta_fs_wait` does not + // already serialize behind `prev_fs`. Emit `ta_fs_barrier` only when `plan.ta_fs_wait` + // names an in-flight FS stamp, and `fs_dep` only when `plan.fs_render_wait` names an + // in-flight FS dependency not already dominated by TA. + if plan.ta_prev_wait { let prev = encode::barrier( - wait_va, - wait_stamp, - wait_event, + r.fw_stamp[0].va, + prev_ta, + 0x70, target, work::barrier::RENDER_WAIT_UUID, render_bar, @@ -2383,33 +2439,35 @@ impl Firmware { 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 plan.early { - if let Some(older_fs) = plan.ta_fs_wait { - let ta_fs = encode::barrier( - r.fw_stamp[1].va, - older_fs, - 0x71, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - p.ta_fs_barrier.write(0, &ta_fs)?; - r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; - pf.ta_head = (pf.ta_head + 1) % cap; - } - let dep = encode::barrier( - r.fw_stamp[1].va, - prev_fs, - 0x71, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - 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; - } + } + if let Some(wait_fs) = plan.ta_fs_wait { + let ta_fs = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.ta_fs_barrier.write(0, &ta_fs)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.ta_fs_barrier.va)?; + pf.ta_head = (pf.ta_head + 1) % cap; + } + if let Some(wait_fs) = plan.fs_render_wait { + let dep = encode::barrier( + r.fw_stamp[1].va, + wait_fs, + 0x71, + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + 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; + } + if plan.early { + self.engine.stats.early += 1; } if let Some(wait_c) = plan.ta_compute_wait { let cbar = encode::barrier( diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 6b3c4877dfb2e5..c0f6aae6b7ddb3 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -143,10 +143,8 @@ pub(crate) struct PassSlot { /// Part of the slot's firmware layout; the host does not use it. _uts: Arc, pub(crate) own_barrier: Arc, - #[allow(dead_code)] pub(crate) prev_barrier: Arc, pub(crate) ta_fs_barrier: Arc, - #[allow(dead_code)] pub(crate) fs_dep: Arc, pub(crate) compute_barrier: Arc, pub(crate) fs_compute_barrier: Arc, 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 0305f3ac5149b0..d30bdf511e086e 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -49,10 +49,12 @@ def item(declaration): assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn assert ( prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') - < prefix_render_fn.rindex('if has_prior_render') -), 'render_bar must be hoisted ahead of has_prior_render for c2ta/c2fs barriers' + < prefix_render_fn.index('if plan.ta_prev_wait') +), 'render_bar must be hoisted ahead of barrier emission' assert prefix_render_fn.count('render_bar,') == 5, prefix_render_fn +assert 'p.prev_barrier.write(0, &prev)?;' in prefix_render_fn assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn +assert 'p.fs_dep.write(0, &dep)?;' in prefix_render_fn assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn assert 'p.fs_compute_barrier.write(0, &fcbar)?;' in prefix_render_fn c2ta_slice = prefix_render_fn[ @@ -904,83 +906,199 @@ def item(declaration): #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; - // 1. Compute->FS-only wait (common texture-write-by-compute -> fragment-read): - // TA runs immediately (no TA compute barrier); FS gets fs_compute_barrier. + // 1. Cross-VM / InitBM / empty render pipe (`class_behind = false`): zero render barriers, + // compute->FS-only wait routes directly to fs_compute_barrier. assert_eq!( - plan_render_barriers(STAGED, false, true, 0, false, None, [None, Some(0x700)]), + plan_render_barriers(STAGED, false, true, 0, None, None, [None, Some(0x700)]), RenderBarrierPlan { early: false, + ta_prev_wait: false, ta_fs_wait: None, + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: Some(0x700), } ); - // 2. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier). + // 2. Independent multi-pass render (`fs_wait_render = None`, e.g. compress.bw array / + // render.shadow or already-retired predecessor): overlaps early while keeping + // TA(N-1)->TA(N) `prev_barrier` on the shared PB/UMA epoch, with ZERO FS->TA and + // ZERO FS->FS barriers (only own_barrier on FS). + for flags in [0u32, FRAG, STAGED] { + assert_eq!( + plan_render_barriers(flags, true, true, 0x200, None, None, [None, None]), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + } + // 3. Same compute target on TA and FS: only TA waits (FS is ordered via own_barrier); + // shared-PB TA->TA `prev_barrier` is kept and dependent FS wait on 0x200 emits fs_dep. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + None, + [Some(0x700), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: Some(0x200), ta_compute_wait: Some(0x700), fs_compute_wait: None, } ); - // 3. Different compute targets on TA (0x600) vs FS (0x700): TA waits on 0x600, FS waits on 0x700. + // 4. Different compute targets on TA (0x600) vs FS (0x700) with no FS render dep: + // TA waits on prev_ta and 0x600, FS waits on 0x700, zero FS->FS render barriers. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, None, [Some(0x600), Some(0x700)]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + None, + None, + [Some(0x600), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: None, ta_compute_wait: Some(0x600), fs_compute_wait: Some(0x700), } ); - // 4. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200): - // overlaps TA with 0x200's FS while waiting on 0x100's FS via ta_fs_barrier. + // 5. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200) + // while FS depends on 0x200: TA waits on prev_ta and 0x100, FS waits on 0x200. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x100), + [None, None], + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: Some(0x200), + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 6. Staged render where TA and FS wait on the same older in-flight FS (0x100): + // TA still waits on prev_ta for the shared PB, and TA wait dominates FS wait via + // own_barrier so fs_render_wait is omitted. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x100), [None, None]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x100), + Some(0x100), + [None, None], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: Some(0x100), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); - // 5. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): - // no early overlap; prev_barrier waits on 0x200 directly. + // 7. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): + // no early overlap; TA waits on 0x200 directly (which dominates prev_ta) and omits both + // prev_barrier and fs_dep. assert_eq!( - plan_render_barriers(STAGED, true, true, 0x200, false, Some(0x200), [None, None]), + plan_render_barriers( + STAGED, + true, + true, + 0x200, + Some(0x200), + Some(0x200), + [None, None], + ), RenderBarrierPlan { early: false, - ta_fs_wait: None, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); - // 6. Legacy FRAGMENT_BARRIERS and plain render remain unchanged. + // 8. Dependent FRAGMENT_BARRIERS render (e.g. render.postfx): TA runs early with + // shared-PB prev_barrier; FS waits on exact fs_wait_render (0x200). assert_eq!( - plan_render_barriers(FRAG, true, true, 0x200, false, None, [Some(0x700), Some(0x700)]), + plan_render_barriers( + FRAG, + true, + true, + 0x200, + Some(0x200), + None, + [Some(0x700), Some(0x700)], + ), RenderBarrierPlan { early: true, + ta_prev_wait: true, ta_fs_wait: None, + fs_render_wait: Some(0x200), ta_compute_wait: Some(0x700), fs_compute_wait: None, } ); + // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): + // TA waits on 0x200 (FS->TA, dominating prev_ta); prev_barrier and fs_dep omitted. assert_eq!( - plan_render_barriers(0, true, true, 0x200, false, None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x200), None, [None, None]), RenderBarrierPlan { early: false, - ta_fs_wait: None, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } ); + // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): + // TA still needs prev_barrier on the shared PB in addition to ta_fs_wait(0x100). assert_eq!( - plan_render_barriers(0, true, true, 0x200, true, None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None]), RenderBarrierPlan { - early: true, - ta_fs_wait: None, + early: false, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when + // fs_wait_render is None, dominating prev_ta and omitting fs_dep. + assert_eq!( + plan_render_barriers(FRAG, true, false, 0x200, None, None, [None, None]), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, ta_compute_wait: None, fs_compute_wait: None, } From b56e9b8155e04d9b7b4c6c615b34ed9e6f2eb5cb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 09:25:06 -0500 Subject: [PATCH 0846/1514] drm/asahi: g16: expand extension compute and render slots when a base slot is quarantined Fresh user VMs start with only BASE_COMPUTE_UNITS (2) compute units and BASE_RENDER_SLOTS (2) render pass slots, allocating extension slots lazily on bursts, overlap, or multi-pass submits. After a hang recovery quarantines one base compute unit (0 or 1) while the other base unit is the newest-retired undisplaced owner, compute_exhausted_within(2) becomes true even though 14+ extension compute units remain healthy. Every subsequent fresh single-command compute client then submits with only 2 units, hits compute_exhausted_within(2) in engine publication, and fails immediately with ECANCELED without ever running on an extension unit to displace the surviving base unit. The same deadlock occurs for fresh single-pass render clients when a base pass slot is quarantined. Track base-slot quarantine state in Lifetime::any_quarantined_within(), publish lockless hints on Shared whenever Slots::quarantine() runs, and pass them via PrepareHints into Cache::prepare() so fresh VMs expand compute_ext / render_ext immediately once a base slot is quarantined. Add host unit tests covering both compute and render base-slot quarantine recovery and displacement. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 6 ++ drivers/gpu/drm/asahi/g16/poll.rs | 15 +++ drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 4 + drivers/gpu/drm/asahi/g16/queue.rs | 6 +- drivers/gpu/drm/asahi/g16/resources.rs | 66 +++++++++--- drivers/gpu/drm/asahi/g16/slots.rs | 12 +++ .../drivers/gpu/asahi-m4/test-publication.py | 1 + .../drivers/gpu/asahi-m4/test-resources.py | 101 +++++++++++++++--- 9 files changed, 185 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index aae0c7a57f79cf..af7c7f941a972e 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2073,6 +2073,7 @@ impl Firmware { // refusal. Keep the unit and its previous VM lease mapped forever; cancelling // preparation would make the corrupt descriptor available to another job. self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); return Err(EIO); } } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2233ba2eb3178e..2f165d0da96537 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -236,6 +236,10 @@ pub(crate) struct Shared { pub(crate) sleeping: AtomicBool, /// Firmware recovery is active under `Shared::state` (may sleep up to 1000 ms). pub(crate) recovering: AtomicBool, + /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) has been quarantined. + pub(crate) base_compute_quarantined: AtomicBool, + /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. + pub(crate) base_render_quarantined: AtomicBool, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -474,6 +478,8 @@ impl Gpu { orphaned: AtomicBool::new(false), sleeping: AtomicBool::new(false), recovering: AtomicBool::new(false), + base_compute_quarantined: AtomicBool::new(false), + base_render_quarantined: AtomicBool::new(false), sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index aa90e9dbeae395..7870aff8c887bc 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1051,6 +1051,19 @@ impl Firmware { } } + /// Publishes lockless quarantine hints so `SUBMIT` expands extension slots immediately + /// when a base slot has been permanently quarantined. + pub(crate) fn sync_quarantine_hints(&self) { + if let Some(shared) = &self.engine.shared { + shared + .base_compute_quarantined + .store(self.slots.base_compute_quarantined(), Ordering::Release); + shared + .base_render_quarantined + .store(self.slots.base_render_quarantined(), Ordering::Release); + } + } + /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt /// retires its storage; a passed abort quarantines it. Job failure independently drops /// remaining unpublished commands even when the storage fully retired. @@ -1076,6 +1089,7 @@ impl Firmware { if receipt.owner_retired() { if let Err(error) = self.slots.retire(&mut f.claims) { self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); self.retain(&f.job); complete(done, &f.job, Err(error)); for j2 in f.group.iter() { @@ -1140,6 +1154,7 @@ impl Firmware { self.pools.quarantine_flight(f.pb_slot as usize, f.pb.take()); } self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); self.retain(&f.job); for j2 in f.group.iter() { self.retain(j2); diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 2f156546ab3077..65aadde6637d2b 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -113,6 +113,10 @@ impl Lifetime { .iter() .any(|u| matches!(u.state, State::Preparing | State::Published)) } + /// Whether any owner in `0..n` is permanently quarantined. + pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { + (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) + } pub(crate) fn claim(&mut self, k: usize) -> bool { if !self.available(k) { return false; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 2dfd7de2a5337d..564af7f926ae97 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -230,12 +230,16 @@ impl Queue { } // Allocate and map private backing before a fence or accepted ordinal exists. // No GPU completion lock is held; reclaim can wait for earlier hardware work. + let hints = super::resources::PrepareHints { + expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), + expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), + }; let resources = self .vm .resources .as_ref() .ok_or(EIO)? - .prepare(&self.vm, &submission.commands)?; + .prepare(&self.vm, &submission.commands, hints)?; let fence = self.timeline.next()?; let job = Job::new( id, diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 68de11188884b8..dea5b3501ccd1f 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -88,21 +88,53 @@ const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLO /// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; +/// Device-wide hints read locklessly in `SUBMIT` to size per-VM extension backing. +#[derive(Copy, Clone, Default)] +pub(crate) struct PrepareHints { + /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. + pub(crate) expand_compute_ext: bool, + /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. + pub(crate) expand_render_ext: bool, +} + +/// Updates the consecutive-compute burst counter and reports whether this submission +/// qualifies to allocate extension compute units (`compute_ext`). +/// +/// If a base compute unit (`0..BASE_COMPUTE_UNITS`) has been permanently quarantined, fresh +/// single-command VMs must expand immediately so they can claim a healthy extension unit and +/// displace the remaining retired base unit rather than hitting `compute_exhausted_within(2)`. +fn should_expand_compute_ext( + last_compute_ns: &mut u64, + burst: &mut u32, + now: u64, + computes: usize, + base_quarantined: bool, +) -> bool { + *burst = if *last_compute_ns != 0 && now.wrapping_sub(*last_compute_ns) < BURST_GAP_NS { + burst.saturating_add(1) + } else { + 0 + }; + *last_compute_ns = now; + base_quarantined || *burst >= BURST_SUBMITS || computes >= BURST_COMMANDS +} + /// Updates the consecutive-render burst counter and reports whether this submission /// qualifies to allocate extension pass slots (`RenderExtArena`). /// /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives /// (`active_renders == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay -/// on the two base pass slots. Extension slots allocate when a VM actually overlaps an -/// in-flight render (`active_renders != 0`, including multi-ms 1080p/4K pipelined frames), -/// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a -/// sub-2 ms back-to-back burst. +/// on the two base pass slots. Extension slots allocate when a base pass slot is quarantined, +/// a VM actually overlaps an in-flight render (`active_renders != 0`, including multi-ms +/// 1080p/4K pipelined frames), submits a multi-pass command stream +/// (`render_count >= BASE_RENDER_SLOTS`), or sustains a sub-2 ms back-to-back burst. fn should_expand_render_ext( last_render_ns: &mut u64, render_burst: &mut u32, now: u64, render_count: usize, active_renders: u32, + base_quarantined: bool, ) -> bool { *render_burst = if *last_render_ns != 0 && now.wrapping_sub(*last_render_ns) < BURST_GAP_NS { render_burst.saturating_add(1) @@ -110,7 +142,10 @@ fn should_expand_render_ext( 0 }; *last_render_ns = now; - active_renders != 0 || *render_burst >= BURST_SUBMITS || render_count >= RENDER_BURST_COMMANDS + base_quarantined + || active_renders != 0 + || *render_burst >= BURST_SUBMITS + || render_count >= RENDER_BURST_COMMANDS } pub(crate) struct RenderArena(crate::cleanup::Deferred); @@ -424,6 +459,7 @@ impl Cache { self: &Arc, vm: &Arc, commands: &[Command], + hints: PrepareHints, ) -> Result { let computes = commands .iter() @@ -457,15 +493,16 @@ impl Cache { if units > BASE_COMPUTE_UNITS { // 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; - if ready.burst >= BURST_SUBMITS || computes >= BURST_COMMANDS { - // Best effort: without them the VM keeps one command in flight. - ready.compute_ext = ComputeArena::new( + let state = &mut *ready; + if should_expand_compute_ext( + &mut state.last_compute_ns, + &mut state.burst, + now, + computes, + hints.expand_compute_ext, + ) { + // Best effort: without them the VM keeps the base compute units. + state.compute_ext = ComputeArena::new( &self.factory, &self.bind, &vm.vm, @@ -496,6 +533,7 @@ impl Cache { now, render_count as usize, active, + hints.expand_render_ext, ) { // Best effort: without extension slots the VM keeps two base pass slots. state.render_ext = diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index d8a5da7c22aa23..5e8e3c93d18b1a 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -683,6 +683,18 @@ impl Slots { pub(crate) fn render_exhausted_within(&self, n: usize) -> bool { self.render.lifetime.exhausted_within(n) } + /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) is permanently quarantined. + pub(crate) fn base_compute_quarantined(&self) -> bool { + self.compute + .lifetime + .any_quarantined_within(super::resources::BASE_COMPUTE_UNITS) + } + /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) is permanently quarantined. + pub(crate) fn base_render_quarantined(&self) -> bool { + self.render + .lifetime + .any_quarantined_within(super::resources::BASE_RENDER_SLOTS) + } pub(crate) fn lifetime_counts(&self) -> [super::pools::lifetime::Counts; 2] { [self.compute.lifetime.counts(), self.render.lifetime.counts()] } 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 c4fcb1fbe9ff3f..3089703990d7f7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -175,6 +175,7 @@ def item(declaration): } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} + fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ fn can_queue_behind(&self,job:&Arc)->bool{ if !self.allow_behind{return false;} 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 a786f17346c1e2..53aa97dc635f63 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -168,6 +168,7 @@ def module(text, name): } pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } + pub(crate) const BASE_COMPUTE_UNITS: usize = 2; pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; __RENDER_BURST__ } @@ -1008,7 +1009,7 @@ def module(text, name): let mut last = 0u64; let mut burst = 0u32; for step in 1u64..=10 { - assert!(!should_expand_render_ext(&mut last, &mut burst, step * period_ns, 1, 0)); + assert!(!should_expand_render_ext(&mut last, &mut burst, step * period_ns, 1, 0, false)); assert_eq!(burst, 0); } } @@ -1017,23 +1018,99 @@ def module(text, name): // already-active render (active_renders >= 1) and expand immediately. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0)); - assert!(should_expand_render_ext(&mut last, &mut burst, 6_000_000, 1, 1)); - assert!(should_expand_render_ext(&mut last, &mut burst, 22_600_000, 1, 1)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); + assert!(should_expand_render_ext(&mut last, &mut burst, 6_000_000, 1, 1, false)); + assert!(should_expand_render_ext(&mut last, &mut burst, 22_600_000, 1, 1, false)); // Sub-2 ms back-to-back single-pass bursts still expand after 3 consecutive gaps. let mut last = 0u64; let mut burst = 0u32; - assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 2_000_000, 1, 0)); - assert!(!should_expand_render_ext(&mut last, &mut burst, 3_000_000, 1, 0)); - assert!(should_expand_render_ext(&mut last, &mut burst, 4_000_000, 1, 0)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 1_000_000, 1, 0, false)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 2_000_000, 1, 0, false)); + assert!(!should_expand_render_ext(&mut last, &mut burst, 3_000_000, 1, 0, false)); + assert!(should_expand_render_ext(&mut last, &mut burst, 4_000_000, 1, 0, false)); assert_eq!(burst, 3); // A single multi-pass SUBMIT with >= BASE_RENDER_SLOTS (2) renders expands immediately. let mut last = 0u64; let mut burst = 0u32; - assert!(should_expand_render_ext(&mut last, &mut burst, 100_000_000, 2, 0)); + assert!(should_expand_render_ext(&mut last, &mut burst, 100_000_000, 2, 0, false)); + } + + #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ + use crate::g16::resources::should_expand_compute_ext; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut units=KVec::new(); + for k in 0..4u64 { + units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + } + let prep_full=g16::resources::ComputeArena{compute:units,render:None}; + let a=vm(1);let b=vm(2); + // Retire base unit 0, then hang and quarantine base unit 1 (or vice versa): + // unit 0 is now retired-undisplaced and unit 1 is quarantined -> base [0..2] exhausted. + let mut c=Claims::new(); + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(0)); + s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(1)); + s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.quarantine(&mut c); + assert!(s.base_compute_quarantined()); + assert!(s.compute_exhausted_within(2)); + assert!(!s.compute_exhausted_within(4)); + // Fresh single-command VM expands extension units immediately because a base unit is quarantined. + let mut last=0u64;let mut burst=0u32; + assert!(!should_expand_compute_ext(&mut last,&mut burst,10_000_000,1,false)); + let mut last=0u64;let mut burst=0u32; + assert!(should_expand_compute_ext(&mut last,&mut burst,10_000_000,1,s.base_compute_quarantined())); + // Expanded fresh VM claims unit 2, retires cleanly, and displaces base unit 0 back to reusable. + assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(b.id)).unwrap(),Some(2)); + s.hold_vm(&c,&b).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // A base-only (2-unit) VM can now claim displaced base unit 0 again. + let mut base_units=KVec::new(); + for k in 0..2u64 { + base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + } + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); + s.release(&mut c); + } + + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ + use crate::g16::resources::should_expand_render_ext; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..4u64 { + passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + } + let render=sync::Arc::new(g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + },0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render)}; + let a=vm(1);let b=vm(2); + let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x1000}; + // Retire base pass slot 0, then hang and quarantine base pass slot 1 -> base [0..2] exhausted. + let mut c0=Claims::new();c0.pass[0]=0;c0.pass_count=1;c0.pass_mask=1<<0; + s.claim_pass_in(&prep,0,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + let mut c1=Claims::new();c1.pass[0]=1;c1.pass_count=1;c1.pass_mask=1<<1; + s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.publish(&c1).unwrap();s.quarantine(&mut c1); + assert!(s.base_render_quarantined()); + assert!(s.render_exhausted_within(2)); + assert!(!s.render_exhausted_within(4)); + // Fresh single-pass VM expands RenderExtArena immediately because a base pass slot is quarantined. + let mut last=0u64;let mut burst=0u32; + assert!(should_expand_render_ext(&mut last,&mut burst,10_000_000,1,0,s.base_render_quarantined())); + // Expanded VM picks and retires pass slot 2, displacing base pass slot 0 back to reusable. + let k=s.pick_pass_in(&prep,&geo,0).unwrap(); + assert_eq!(k,2); + let mut c2=Claims::new();c2.pass[0]=k as u32;c2.pass_count=1;c2.pass_mask=1< Date: Sun, 22 Nov 2026 11:21:48 -0500 Subject: [PATCH 0847/1514] drm/asahi: reuse per-queue SUBMIT cmdbuf staging and bulk-read syncs Avoid per-SUBMIT heap allocations without placing a large command buffer on the kernel stack across queue.lock().submit() or holding the queue mutex across userspace copies: - Store a reusable KVec staging buffer on TableQueue (retained up to 4096 bytes between submissions, releasing oversized buffers on completion or error). - Take the cached KVec out of TableQueue under a brief queue.lock(), drop the queue mutex before copy_from_user() and SyncItem::parse_array() (preventing queue.lock() -> mmap_lock lock-order inversion), then re-acquire queue.lock() only for inner.submit() and returning the cleared buffer (or return on early error). - Read drm_asahi_sync entries in 8-entry (128-byte) stack chunks rather than issuing a separate copy_from_user per sync. - Preserve the pre-syncobj failure boundary on guarded (G16/G17) paths by snapshotting the command buffer before resolving output syncobjs, and keep parsing syncs first on unguarded paths. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 141 +++++++++++++++++++++++++--------- 1 file changed, 103 insertions(+), 38 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 6f9a89cc311b63..1505a9ac5dc410 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -294,34 +294,45 @@ impl SyncItem { let count = in_count.checked_add(out_count).ok_or(EOVERFLOW)?; const STRIDE: usize = core::mem::size_of::(); + const CHUNK: usize = 8; let size = STRIDE.checked_mul(count as usize).ok_or(EOVERFLOW)?; let mut vec = KVec::with_capacity(count as usize, GFP_KERNEL)?; let mut anchor = None; - // Read each record once so validation and use see the same retained bytes. + // Read each record once in small stack chunks so validation and use see the + // same retained bytes without a per-entry copy_from_user. let mut reader = UserSlice::new(UserPtr::from_addr(ptr as usize), size).reader(); + let mut buf = MaybeUninit::<[uapi::drm_asahi_sync; CHUNK]>::uninit(); - for i in 0..count { - let mut sync: MaybeUninit = MaybeUninit::uninit(); + let mut base = 0u32; + while base < count { + let chunk = ((count - base) as usize).min(CHUNK); + let raw = buf.as_mut_ptr().cast::(); - // SAFETY: The size of `sync` is STRIDE + // SAFETY: `buf` holds `CHUNK` contiguous `drm_asahi_sync` entries and + // `chunk <= CHUNK`, so `chunk * STRIDE` bytes are writable. reader.read_raw(unsafe { - core::slice::from_raw_parts_mut(sync.as_mut_ptr().cast::>(), STRIDE) + core::slice::from_raw_parts_mut(raw.cast::>(), chunk * STRIDE) })?; - // SAFETY: All bit patterns in the struct are valid - let sync = unsafe { sync.assume_init() }; + for offset in 0..chunk { + let i = base + offset as u32; + // SAFETY: `read_raw` initialized `chunk` contiguous entries starting at `raw`, + // `offset < chunk`, and all bit patterns in the struct are valid. + let sync = unsafe { raw.add(offset).read() }; - if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { - if !allow_cumulative || i < in_count || anchor.is_some() { - return Err(EINVAL); + if sync.sync_type == crate::g17::sync_output::SYNC_CUMULATIVE { + if !allow_cumulative || i < in_count || anchor.is_some() { + return Err(EINVAL); + } + anchor = Some(i as usize); } - anchor = Some(i as usize); + vec.push( + Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, + GFP_KERNEL, + )?; } - vec.push( - Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, - GFP_KERNEL, - )?; + base += chunk as u32; } if let Some(anchor) = anchor { let bundle = crate::g17::sync_output::SignalBundle::new( @@ -350,9 +361,42 @@ pub(crate) enum Object { /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { queue: KBox, + /// Reusable staging buffer for `SUBMIT` command buffers, avoiding per-submit heap + /// allocations and keeping large command buffers off the kernel stack. + cmdbuf: KVec, _share: Option, } +impl TableQueue { + /// Maximum command-buffer capacity retained on a queue between submissions. + const REUSE_CMDBUF_CAP: usize = 4096; + + /// Takes the cached command-buffer staging allocation so userspace copies run outside the + /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). + fn take_cmdbuf(&mut self) -> KVec { + core::mem::take(&mut self.cmdbuf) + } + + /// Returns a cleared command-buffer allocation to the per-queue cache when within the + /// reuse capacity cap; oversized buffers are dropped. + fn return_cmdbuf(&mut self, mut buf: KVec) { + buf.clear(); + if buf.capacity() > 0 + && buf.capacity() <= Self::REUSE_CMDBUF_CAP + && buf.capacity() >= self.cmdbuf.capacity() + { + self.cmdbuf = buf; + } + } +} + +fn copy_cmdbuf_from_user(buf: &mut KVec, addr: u64, size: usize) -> Result { + buf.clear(); + UserSlice::new(UserPtr::from_addr(addr as usize), size) + .reader() + .read_all(buf, GFP_KERNEL) +} + impl Deref for TableQueue { type Target = dyn queue::Queue; @@ -1744,6 +1788,7 @@ impl File { resv.fill(Arc::pin_init( new_mutex!(TableQueue { queue, + cmdbuf: KVec::new(), _share: share, }), GFP_KERNEL, @@ -1815,28 +1860,37 @@ impl File { data.queue_id, id ); - let mut vec = KVec::new(); - let copy_commands = |bytes: &mut KVec| { - UserSlice::new( - UserPtr::from_addr(data.cmdbuf as usize), - data.cmdbuf_size as usize, - ) - .reader() - .read_all(bytes, GFP_KERNEL) - }; + let cmdbuf_size = data.cmdbuf_size as usize; let guarded = gpu.as_any().is::() || gpu.tracked_submission(); // Once G17 output syncobjs are resolved, its queue must install a fence - // on every failure. Take the fallible userspace snapshot before that point. - if guarded { - copy_commands(&mut vec)?; - } - let syncs = SyncItem::parse_array( + // on every failure. Take the fallible userspace snapshot before that point, + // staging into a buffer taken from the queue's reusable cache so user + // copies never execute under `queue.lock()`. + let mut cmdbuf = if guarded { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + Some(buf) + } else { + None + }; + let syncs = match SyncItem::parse_array( file, data.syncs, data.in_sync_count, data.out_sync_count, gpu.as_any().is::(), - )?; + ) { + Ok(syncs) => syncs, + Err(e) => { + if let Some(buf) = cmdbuf { + queue.lock().return_cmdbuf(buf); + } + return Err(e); + } + }; mod_dev_dbg!( device, @@ -1846,22 +1900,33 @@ impl File { id ); - // Copy the command buffer into the kernel. Because we need to iterate - // the command buffer twice, we do this in one big copy_from_user to - // avoid TOCTOU issues. - if !guarded { - copy_commands(&mut vec)?; - } + // Copy the command buffer into the kernel outside `queue.lock()`. Because we + // need to iterate the command buffer twice, we do this in one big copy_from_user + // to avoid TOCTOU issues. + let cmdbuf = match cmdbuf.take() { + Some(buf) => buf, + None => { + let mut buf = queue.lock().take_cmdbuf(); + if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { + queue.lock().return_cmdbuf(buf); + return Err(e); + } + buf + } + }; let objects = file.inner().objects(); - let ret = queue.lock().submit( + let mut guard = queue.lock(); + let ret = guard.queue.submit( reg_data, id, syncs, data.in_sync_count as usize, - &vec, + cmdbuf.as_slice(), objects, ); + guard.return_cmdbuf(cmdbuf); + drop(guard); if ret.is_ok() { if let Some((util_min, duration_ms)) = gpu.syncobj_wait_hint() { From 94a03f5b30ea536f9d31b4e4aea74457fe9c0186 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:28:57 -0500 Subject: [PATCH 0848/1514] drm/asahi: g16: raise render pass slots to 48 and tighten slot-wait repoll Deep multi-pass render benchmarks (such as 11-pass render.postfx at depth 3, 7-pass compress.bw array at depth 5, and 4-pass render.shadow at depth 8) saturated the 32-slot pass cap (31 active + 1 displacement) and stalled between passes waiting for the 100 us resnap timer to free retired pass slots. - Raise hw::sizes::RENDER_SLOTS from 32 to 48 (47 in-flight passes + 1 displacement slot) and widen pass_busy/pass_mask/clean_mask/scrubbing in g16/slots.rs from u32 to u64. Both TA and FS work rings hold QUEUE_CAP = 256 entries (255 usable); at worst-case 4 ring entries per pipelined pass (MAX_RENDER_RING_ENTRIES = 4), 47 in-flight passes consume at most 188 entries (67 spare), bounded by compile-time assertion in hw.rs and clamped in params::render_flights() to (QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES (63), well within AHEAD_RECORDS = 128, RING_SLOTS = 256, FLIGHTS = 32, and firmware recovery snapshot_entries = 448. - Split EXT_RENDER_TIERS in g16/resources.rs into four demand-grown tiers so 20-31 pass workloads do not pay for 48 slots upfront (per base slot = 25,184 KiB / 24.59 MiB; per ext slot = 3,680 KiB / 3.59 MiB): - Base (0..2, 2 slots): 50,368 KiB (49.19 MiB), ext 0 KiB - Tier 0 (2..8, +6 ext): +22,080 KiB (+21.56 MiB), ext 21.56 MiB - Tier 1 (8..18, +10 ext): +36,800 KiB (+35.94 MiB), ext 57.50 MiB - Tier 2 (18..32, +14 ext): +51,520 KiB (+50.31 MiB), ext 107.81 MiB - Tier 3 (32..48, +16 ext): +58,880 KiB (+57.50 MiB), ext 165.31 MiB - Add Engine::slot_wait and Firmware::blocked_on_slot_headroom() so poll_step() arms short_repoll (repoll_us) when pending work is specifically blocked on same-VM flight, pass/compute slot, or work-ring headroom, without arming short_repoll for cross-VM drains, InitBM/PB-unprimed waits, external sync fences, or CPU timestamp waits. Update host selftests in test-resources.py, test-publication.py, and test-poll-retire.py to verify 48 pass slots, all four demand-grown tier boundaries and exact byte footprints, blocked_on_slot_headroom() filtering, and slot_wait-gated short_repoll behavior. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 70 +++++++++-- drivers/gpu/drm/asahi/g16/hw.rs | 18 +-- drivers/gpu/drm/asahi/g16/params.rs | 11 +- drivers/gpu/drm/asahi/g16/poll.rs | 11 +- drivers/gpu/drm/asahi/g16/resources.rs | 20 +-- drivers/gpu/drm/asahi/g16/slots.rs | 46 +++---- .../drivers/gpu/asahi-m4/test-poll-retire.py | 56 +++++++++ .../drivers/gpu/asahi-m4/test-publication.py | 86 ++++++++++++- .../drivers/gpu/asahi-m4/test-resources.py | 116 ++++++++++++------ 9 files changed, 334 insertions(+), 100 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 84427844f6f5c8..80a92ec8c8021b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -549,6 +549,10 @@ 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, + /// A ready same-VM pending job is blocked solely on flight, pass/compute slot, or work-ring + /// headroom (not cross-VM/InitBM drain, external fences, or CPU timestamp waits): repoll + /// sooner to refill freed slots promptly. + pub(crate) slot_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 compute and render flights. @@ -589,6 +593,7 @@ impl Engine { render_registered: false, ta_registered: false, chan_wait: false, + slot_wait: false, short_repoll: false, progress_flight: [0; 2], progress: [None; 3], @@ -923,6 +928,7 @@ impl Firmware { let mut batch_published = 0u64; self.engine.chan_wait = false; + self.engine.slot_wait = false; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -965,6 +971,11 @@ impl Firmware { match alt { Some(i) => job = self.engine.pending[i].clone(), None => { + self.engine.slot_wait = self + .engine + .pending + .iter() + .any(|cand| self.blocked_on_slot_headroom(cand)); self.engine.stats.hold[0] += 1; break; } @@ -1177,6 +1188,47 @@ impl Firmware { .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n))) } + /// Whether `job` is ready to run on the same VM but currently blocked solely on + /// flight-depth or pass/compute-slot headroom (not on cross-VM/InitBM/recovery drain, + /// external sync dependencies, or CPU timestamp-publish waits). + fn blocked_on_slot_headroom(&self, job: &Arc) -> bool { + let e = &self.engine; + if e.flights.is_empty() || self.needs_engine_drain(job) { + return false; + } + let sent = job.progress.sent(); + if job.check_command_dependencies(sent).is_err() { + return false; + } + if e.flights.len() >= super::hw::sizes::FLIGHTS { + return true; + } + match command(job, sent) { + Some(Command::Compute(_)) => { + let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); + compute_count > 0 + && !self.slots.compute_exhausted() + && (compute_count >= params::compute_flights() + || job + .resources + .compute_units() + .is_ok_and(|units| !self.slots.compute_available(units))) + } + Some(Command::Render(_)) => { + let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + render_count > 0 + && !self.slots.render_exhausted() + && !self.pools.exhausted() + && (render_count >= params::render_flights() + || job + .resources + .render_passes() + .is_ok_and(|passes| !self.slots.pass_available(passes))) + } + None => false, + } + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy same-VM non-InitBM compute and/or render flights (up to @@ -1624,6 +1676,7 @@ impl Firmware { || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 5 { + self.engine.slot_wait = true; return Err(EAGAIN); } } else { @@ -1632,6 +1685,7 @@ impl Firmware { if c_read >= 256 || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 { + self.engine.slot_wait = true; return Err(EAGAIN); } } @@ -1762,14 +1816,14 @@ impl Firmware { }) { return Err(E2BIG); } - let k = self - .slots - .pick_pass_in(&job.resources, &geometry, 0) - .ok_or(EAGAIN)?; + let Some(k) = self.slots.pick_pass_in(&job.resources, &geometry, 0) else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; f.claims.pass[0] = k as u32; f.claims.pass_count = 1; - f.claims.pass_mask = 1 << k; - self.slots.pass_busy |= 1 << k; + f.claims.pass_mask = 1u64 << k; + self.slots.pass_busy |= 1u64 << k; self.prefix_render(job, r, geometry, &mut prefix, f, behind, class_behind)?; // Batch consecutive ready non-InitBM render passes of the same SUBMIT into // one TA/FS producer advance, one UMA submitted update, and one SubmitRecord. @@ -1855,8 +1909,8 @@ impl Firmware { let member = prefix.renders as usize; f.claims.pass[member] = k2 as u32; f.claims.pass_count += 1; - f.claims.pass_mask |= 1 << k2; - self.slots.pass_busy |= 1 << k2; + f.claims.pass_mask |= 1u64 << k2; + self.slots.pass_busy |= 1u64 << k2; self.prefix_render( job, r2, diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 392bc7cbac1468..d1215627955c4c 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -646,8 +646,8 @@ pub(crate) mod client { // - Base slots `0..BASE_RENDER_SLOTS` keep 32 MiB intervals with full 16 MiB TPC / 8 MiB // tilemap capacity for worst-case geometries. // - Extension slots `BASE_RENDER_SLOTS..RENDER_SLOTS` pack into 8 MiB intervals starting at - // `EXT_PASS_BASE` (`0x7024000000`) with 2 MiB TPC / 1 MiB tilemap capacity, fitting 32 - // total pass slots (`0x7020000000..0x7033000000`, leaving 208 MiB free below 0x7040000000). + // `EXT_PASS_BASE` (`0x7024000000`) with 2 MiB TPC / 1 MiB tilemap capacity, fitting 48 + // total pass slots (`0x7020000000..0x703b000000`, leaving 80 MiB free below 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; @@ -735,13 +735,13 @@ pub(crate) mod sizes { /// retired (displacing it), so `n` slots keep up to `n - 1` renders in flight. /// /// Sized inside both the host client-VA window (`0x7020000000..0x7040000000`) and firmware - /// queue/recovery capacities: `31` in-flight passes consume at most `31 * 4 = 124` entries of - /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable), share hardware UMA slot - /// `RENDER_UMA_SLOT` (33) via the active PB/UMA descriptor, post at most `FLIGHTS = 32` - /// `SubmitRecord`s (vs `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay far below the - /// firmware recovery `snapshot_entries = 448` limit. - pub(crate) const RENDER_SLOTS: usize = 32; - const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 32); + /// queue/recovery capacities: `47` in-flight passes consume at most `47 * 4 = 188` entries of + /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), share + /// hardware UMA slot `RENDER_UMA_SLOT` (33) via the active PB/UMA descriptor, post at most + /// `FLIGHTS = 32` `SubmitRecord`s (vs `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay + /// far below the firmware recovery `snapshot_entries = 448` limit. + pub(crate) const RENDER_SLOTS: usize = 48; + const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 64); const _: () = assert!((RENDER_SLOTS - 1) * MAX_RENDER_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!(super::client::AUX + 0x20000 <= super::client::SCENE_LIST); const _: () = assert!(super::client::SCENE_LIST + 0x4000 <= super::client::TPC); diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index a88a005a9cf13d..0ebae97fe47bb0 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -48,11 +48,18 @@ pub(crate) fn compute_flights() -> usize { 32usize.clamp(1, hw::sizes::FLIGHTS) } -/// Render commands in flight at most (`RENDER_SLOTS - 1` so one slot holds displacement). +/// Render commands in flight at most: bounded by both retained pass slots +/// (`RENDER_SLOTS - 1`, leaving one slot for displacement) and firmware TA/FS work-ring +/// capacity (`(QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES`, worst case 4 ring entries per pass). +/// Decoupled from `hw::sizes::FLIGHTS` because multi-pass render batches pack multiple passes +/// into one `Flight`. pub(crate) fn render_flights() -> usize { + let ring_cap = + (hw::sizes::QUEUE_CAP as usize).saturating_sub(1) / hw::sizes::MAX_RENDER_RING_ENTRIES; hw::sizes::RENDER_SLOTS .saturating_sub(1) - .clamp(1, hw::sizes::FLIGHTS) + .min(ring_cap) + .max(1) } /// Repoll while a ready prefix waits for record consumption, us. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 5f03b4337bb493..ee90bf5ec2cc6c 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -602,12 +602,13 @@ impl Firmware { } } // If a terminal 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 + // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring + // headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. + self.engine.short_repoll = !self.engine.flights.is_empty() + && !self.engine.frozen && !non_terminal_only - && !self.engine.flights.is_empty(); + && ((evented && had_flights && !retired_any) + || (!self.engine.pending.is_empty() && self.engine.slot_wait)); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 9b841aca8c710b..1bd581ee22a165 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -86,21 +86,25 @@ pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; /// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). /// /// Each extension `PassSlot` backs 3.59 MiB (2 MiB TPC + 1 MiB tilemap + 608 KiB metadata, -/// scratch, and barriers). Growing in bounded chunks keeps compositor and shallow desktop VMs -/// on Tier 0 (~21.6 MiB) instead of allocating all 30 extension slots (~107.8 MiB) on a 2-pass -/// submission: -/// - Tier 0 (`2..8`, 6 slots, 21.56 MiB): compositors, 2-6 pass frames, depth 1-2. +/// scratch, and barriers). Growing in four bounded chunks keeps compositor and shallow desktop +/// VMs on Tier 0 (~21.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, +/// and keeps every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +21.56 MiB / 21.56 MiB cum): compositors, 2-6 pass frames. /// - Tier 1 (`8..18`, 10 slots, +35.94 MiB / 57.50 MiB cum): moderate multi-pass bursts. -/// - Tier 2 (`18..RENDER_SLOTS`, 14 slots / +50.31 MiB at 32 slots): deep multi-pass bursts. -pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 3] = [ +/// - Tier 2 (`18..32`, 14 slots, +50.31 MiB / 107.81 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +57.50 MiB / 165.31 MiB cum at 48 slots): deep +/// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). +pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ (BASE_RENDER_SLOTS, 8), (8, 18), - (18, super::hw::sizes::RENDER_SLOTS), + (18, 32), + (32, super::hw::sizes::RENDER_SLOTS), ]; const _: () = assert!(EXT_RENDER_TIERS[0].0 == BASE_RENDER_SLOTS); const _: () = assert!(EXT_RENDER_TIERS[0].1 == EXT_RENDER_TIERS[1].0); const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); -const _: () = assert!(EXT_RENDER_TIERS[2].1 == super::hw::sizes::RENDER_SLOTS); +const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); +const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; /// Single-submission render command count that expands Tier 0 extension slots immediately: diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index c0f6aae6b7ddb3..68d48b717d70b2 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -8,7 +8,7 @@ //! Private backing and old VM leases survive until a distinct replacement fully retires. //! Aborted storage remains mapped and quarantined. Pool cursors are never scrubbed. -use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; @@ -366,7 +366,7 @@ pub(crate) struct Claims { pub(crate) slot_count: u32, pub(crate) pass: [u32; sizes::RENDER_SLOTS], pub(crate) pass_count: u32, - pub(crate) pass_mask: u32, + pub(crate) pass_mask: u64, #[allow(dead_code)] pub(crate) ct: [u32; sizes::RENDER_SLOTS], pub(crate) ct_count: u32, @@ -437,15 +437,15 @@ pub(crate) struct ComputeOwners { } /// Bitmask of valid render pass slot indices (`0..sizes::RENDER_SLOTS`). -const PASS_MASK: u32 = u32::MAX >> (32 - sizes::RENDER_SLOTS); +const PASS_MASK: u64 = u64::MAX >> (64 - sizes::RENDER_SLOTS); /// Shared atomic coordination between `Shared::state` slot selection/claims and off-lock /// pre-scrubbing of displaced render pass slots. struct ScrubState { /// Pass slots currently being scrubbed outside `Shared::state`; never picked or claimed. - scrubbing: AtomicU32, + scrubbing: AtomicU64, /// Displaced pass slots whose clean same-VM spans were zeroed off-lock. - clean_mask: AtomicU32, + clean_mask: AtomicU64, /// Incremented by [`Self::clear_all_clean`] on recovery so an in-flight async scrub that /// started before recovery can never publish a stale `clean_mask` bit afterwards. generation: AtomicU64, @@ -462,8 +462,8 @@ struct ScrubState { impl ScrubState { const fn new() -> Self { Self { - scrubbing: AtomicU32::new(0), - clean_mask: AtomicU32::new(0), + scrubbing: AtomicU64::new(0), + clean_mask: AtomicU64::new(0), generation: AtomicU64::new(0), waiter: AtomicBool::new(false), woke: AtomicBool::new(false), @@ -473,20 +473,20 @@ impl ScrubState { } fn is_scrubbing(&self, k: usize) -> bool { - self.scrubbing.load(Ordering::Acquire) & (1u32 << k) != 0 + self.scrubbing.load(Ordering::Acquire) & (1u64 << k) != 0 } fn is_clean(&self, k: usize) -> bool { - self.clean_mask.load(Ordering::Acquire) & (1u32 << k) != 0 + self.clean_mask.load(Ordering::Acquire) & (1u64 << k) != 0 } fn take_clean(&self, k: usize) -> bool { - let bit = 1u32 << k; + let bit = 1u64 << k; self.clean_mask.fetch_and(!bit, Ordering::AcqRel) & bit != 0 } fn clear_clean(&self, k: usize) { - self.clean_mask.fetch_and(!(1u32 << k), Ordering::Release); + self.clean_mask.fetch_and(!(1u64 << k), Ordering::Release); } fn clear_all_clean(&self) { @@ -506,7 +506,7 @@ pub(crate) struct PendingScrub { impl PendingScrub { pub(crate) fn run_one(&mut self) -> bool { - let bit = 1u32 << self.slot; + let bit = 1u64 << self.slot; let ok = if self.state.generation.load(Ordering::Acquire) != self.generation { false } else if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { @@ -546,7 +546,7 @@ impl PendingScrub { impl Drop for PendingScrub { fn drop(&mut self) { if !self.done { - let bit = 1u32 << self.slot; + let bit = 1u64 << self.slot; self.state.scrubbing.fetch_and(!bit, Ordering::SeqCst); } } @@ -644,7 +644,7 @@ pub(crate) struct RenderOwners { pub(crate) struct Slots { pub(crate) cursor: u32, - pub(crate) pass_busy: u32, + pub(crate) pass_busy: u64, pub(crate) pass_cursor: u32, scrub_gen: u64, pub(crate) stats: SlotStats, @@ -810,7 +810,7 @@ impl Slots { self.render.scrub_pending = false; self.fold_scrub_stats(); for k in 0..sizes::RENDER_SLOTS { - let bit = 1u32 << k; + let bit = 1u64 << k; if self.pass_busy & bit != 0 || !self.render.lifetime.available(k) || self.render.scrub_full[k] @@ -951,7 +951,7 @@ impl Slots { &self, arena: &super::resources::RenderArena, geo: &Geometry, - picked: u32, + picked: u64, ) -> Option { let n = arena.passes.len().min(sizes::RENDER_SLOTS); let mut fallback = None; @@ -959,7 +959,7 @@ impl 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 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 @@ -982,7 +982,7 @@ impl 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 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && !self.scrub.is_scrubbing(k) && geo.tpc_bytes <= p.tpc.size as u64 @@ -999,7 +999,7 @@ impl Slots { &self, resources: &super::resources::Prepared, geo: &Geometry, - picked: u32, + picked: u64, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); let mut fallback = None; @@ -1009,7 +1009,7 @@ impl Slots { let Ok(p) = resources.render_pass(k) else { continue; }; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && geo.tpc_bytes <= p.tpc.size as u64 && geo.tilemap_bytes <= p.tilemap.size as u64 @@ -1034,7 +1034,7 @@ impl Slots { let Ok(p) = resources.render_pass(k) else { continue; }; - if (self.pass_busy | picked) & (1 << k) == 0 + if (self.pass_busy | picked) & (1u64 << k) == 0 && self.render.lifetime.available(k) && !self.scrub.is_scrubbing(k) && geo.tpc_bytes <= p.tpc.size as u64 @@ -1205,12 +1205,12 @@ impl Slots { return Err(EINVAL); } if f.pass_count != 0 { - let mut mask = 0u32; + let mut mask = 0u64; for &k in &f.pass[..f.pass_count as usize] { if k as usize >= sizes::RENDER_SLOTS { return Err(EINVAL); } - let bit = 1u32 << k; + let bit = 1u64 << k; if mask & bit != 0 { return Err(EINVAL); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 7135221e2594f2..649995e70f6364 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -125,6 +125,7 @@ def item(declaration, text=source): target: u32, fs_target: u32, chan_wait: bool, + slot_wait: bool, short_repoll: bool, frozen: bool, stats: Stats, @@ -261,6 +262,7 @@ def item(declaration, text=source): target: 0, fs_target: 0, chan_wait: false, + slot_wait: false, short_repoll: false, frozen: false, stats: Stats::default(), @@ -580,6 +582,60 @@ def item(declaration, text=source): assert_eq!(fw.publish_checked_calls, 5); } +#[test] +fn pending_slot_wait_arms_short_repoll_without_breaking_ta_only_or_frozen() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 11, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + + // No pending work on a timer poll -> keep normal resnap_us interval. + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job NOT blocked on slot headroom (e.g. external fence / cross-VM / InitBM) -> + // keep normal resnap_us interval without arming short_repoll. + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.slot_wait = false; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + + // Pending job waiting on slot headroom on a non-event poll -> arm short_repoll. + fw.engine.slot_wait = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + + // TA-only EP 0x20 event still suppresses short_repoll. + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); + fw.drain_stage_delta = 0; + + // Frozen engine suppresses short_repoll even with pending work. + fw.engine.frozen = true; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!fw.engine.short_repoll); +} + mod boot { pub fn eproto() -> super::Error { super::Error(-71) 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 d30bdf511e086e..a14f9c99371148 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -111,7 +111,7 @@ def item(declaration): struct Claims; struct Flight{job:Arc,claims:Claims,group:Vec>,doomed:bool,recovery_suspect:bool,initbm:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],doomed:false,recovery_suspect:false,initbm:false}}} -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool} impl Engine { __PICK__ __UNPEND__ @@ -197,6 +197,12 @@ def item(declaration): fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ + if self.engine.flights.is_empty()||self.needs_engine_drain(job){return false;} + if job.check_command_dependencies(job.progress.sent()).is_err(){return false;} + (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(())))) + ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) + } fn can_queue_behind(&self,job:&Arc)->bool{ if !self.allow_behind{return false;} if self.needs_engine_drain(job){return false;} @@ -253,7 +259,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false} @@ -527,7 +533,7 @@ def item(declaration): type Job = QueueBehindJob; type Flight = QueueBehindFlight; fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} - mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{15} } + mod params { pub fn compute_flights()->usize{16} pub fn render_flights()->usize{47} } #[allow(non_upper_case_globals)] mod kernel { pub mod uapi { @@ -552,6 +558,8 @@ def item(declaration): __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ impl QueueBehindHost { + __NEEDS_ENGINE_DRAIN__ + __BLOCKED_ON_SLOT_HEADROOM__ __CAN_QUEUE_BEHIND__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ @@ -898,11 +906,78 @@ def item(declaration): initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); - // Active renders sum flight.renders: 15 batched renders saturates render_flights(). + // Active renders sum flight.renders: 44 passes (4x11-pass postfx) still pipelines + // behind, while 47 batched renders saturates render_flights(). + assert!(p.can_queue_behind(&next_r)); + p.engine.flights[0].renders=44; assert!(p.can_queue_behind(&next_r)); - p.engine.flights[0].renders=15; + p.engine.flights[0].renders=47; assert!(!p.can_queue_behind(&next_r)); } + #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ + 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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ + 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})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, + extra_orders:vec![],dependency:dep,resources:Resources, + }); + let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); + let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); + let r_cross_vm=mk(3,vm2.clone(),true,Ok(()),false,[None,None]); + let r_ext_fence=mk(4,vm1.clone(),true,Err(EAGAIN),false,[None,None]); + let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); + let mut p=QueueBehindHost{ + engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16], + r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, + 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}, + }; + // Not blocked on slots when pass_available is true and render_flights has headroom. + assert!(!p.blocked_on_slot_headroom(&r_same)); + // Waiting on CPU timestamp publish (query_access) is NOT a slot-headroom block. + assert!(!p.can_queue_behind(&c_ts_wait)); + assert!(!p.blocked_on_slot_headroom(&c_ts_wait)); + // Render pass slot exhaustion IS a slot-headroom block for a ready same-VM render... + p.slots.pass_available=false; + assert!(p.blocked_on_slot_headroom(&r_same)); + // ...but NOT for cross-VM, external-fence, or InitBM/PB-unprimed jobs. + assert!(!p.blocked_on_slot_headroom(&r_cross_vm)); + assert!(!p.blocked_on_slot_headroom(&r_ext_fence)); + p.pools.can_pipeline=false; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.pools.can_pipeline=true; + p.engine.flights[0].initbm=true; + assert!(!p.blocked_on_slot_headroom(&r_same)); + p.engine.flights[0].initbm=false; + // Render flight cap (47) also counts as a slot-headroom block. + p.slots.pass_available=true; + p.engine.flights[0].renders=47; + assert!(p.blocked_on_slot_headroom(&r_same)); + + // End-to-end publish_checked: cross-VM drain leaves slot_wait=false; same-VM slot block sets slot_wait=true. + let v1=mk_vm(1); + let v2=mk_vm(2); + let mut fc=firmware(vec![job_on_vm(2,v2,true,0,Ok(()))],vec![]); + fc.engine.flights.push(super::Flight::new(job_on_vm(1,v1.clone(),true,0,Ok(())))); + fc.allow_behind=true; + let mut done=vec![]; + assert_eq!(fc.publish_checked(&mut done),Ok(())); + assert!(!fc.engine.slot_wait); + + let mut fs=firmware(vec![job_on_vm(2,v1.clone(),true,0,Ok(()))],vec![]); + fs.engine.flights.push(super::Flight::new(job_on_vm(1,v1,true,0,Ok(())))); + fs.allow_behind=true; + fs.block_render_behind=true; + assert_eq!(fs.publish_checked(&mut done),Ok(())); + assert!(fs.engine.slot_wait); + } #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; @@ -1540,6 +1615,7 @@ def item(declaration): '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', + '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', 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 e76430e00c6ebe..9124bf1eb8a98f 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -573,8 +573,8 @@ def module(text, name): assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); } - #[test]fn thirty_two_render_passes_and_eighteen_compute_units_are_disjoint_in_mesa_hole(){ - assert_eq!(g16::hw::sizes::RENDER_SLOTS, 32); + #[test]fn forty_eight_render_passes_and_eighteen_compute_units_are_disjoint_in_mesa_hole(){ + assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 18); let mut o=Objects::new(); let pools=PoolSet::new(&mut o).unwrap(); @@ -586,6 +586,7 @@ def module(text, name): g16::slots::ComputeSlot::new(&mut o,k).unwrap(); } let mut scene_lists=Vec::new(); + let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { let pass=g16::slots::PassSlot::new(&mut o,k,1).unwrap(); let va=pass.refs().scene_list; @@ -593,6 +594,18 @@ def module(text, name): assert!(!scene_lists.contains(&va),"each pass slot must own a distinct scene_list"); scene_lists.push(va); } + // Every demand-grown extension tier stays strictly within MAX_CLIENT (512) per batch. + for &(start, end) in &g16::resources::EXT_RENDER_TIERS { + let mut ot = Objects::new(); + for k in start..end { + g16::slots::PassSlot::new(&mut ot, k as u64, 1).unwrap(); + } + let tier_maps = count_client(&ot); + assert!( + tier_maps <= g16::hw::sizes::MAX_CLIENT, + "tier {start}..{end} client maps {tier_maps} > MAX_CLIENT" + ); + } let mut aliases=Vec::new(); for a in &o.objects { if let Some(g)=a.gva { @@ -805,7 +818,7 @@ def module(text, name): assert_eq!(arena.render.passes[0].scene.fills.lock().unwrap().len(),2); } - #[test]fn pipelined_render_pass_slots_keep_thirty_one_in_flight(){ + #[test]fn pipelined_render_pass_slots_keep_forty_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 { @@ -827,30 +840,31 @@ def module(text, name): let a=vm(1); let b=vm(2); let mut live:Vec=Vec::new(); - // Publish 31 concurrent passes in flight (slots 0..31), exercising bit 31 on the last slot. - for k in 0..31usize { + // Publish 47 concurrent passes in flight (slots 0..47), covering 4x11-pass and 6x7-pass + // multi-pass bursts and exercising 64-bit pass_mask bits above bit 31. + for k in 0..47usize { let mut c=Claims::new(); - c.pass[0]=k as u32;c.pass_mask=1u32< slot 0 is displaced and reusable while 29 others remain in flight. + assert_eq!(s.render_published(),47); + assert!(s.pass_available(48)); // slot 47 is still fresh + assert!(!s.pass_available(47)); + // Retire 0 and 1 -> slot 0 is displaced and reusable while 45 others remain in flight. s.retire(&mut live[0]).unwrap(); - assert!(!s.pass_available(31)); // slot 0 not displaced yet + assert!(!s.pass_available(47)); // slot 0 not displaced yet s.retire(&mut live[1]).unwrap(); - assert!(s.pass_available(31)); // slot 0 displaced by slot 1! - // Claim and publish bit 31 (slot 31) explicitly to prove zero 32-bit mask overflow. - let mut c31=Claims::new(); - c31.pass[0]=31;c31.pass_count=1;c31.pass_mask=1u32<<31; - s.claim_pass_for(&arena,31,Some(a.id)).unwrap(); - s.hold_vm(&c31,&a).unwrap(); - s.publish(&c31).unwrap(); + assert!(s.pass_available(47)); // slot 0 displaced by slot 1! + // Claim and publish bit 47 (slot 47) explicitly to prove zero 64-bit mask overflow. + let mut c47=Claims::new(); + c47.pass[0]=47;c47.pass_count=1;c47.pass_mask=1u64<<47; + s.claim_pass_for(&arena,47,Some(a.id)).unwrap(); + s.hold_vm(&c47,&a).unwrap(); + s.publish(&c47).unwrap(); // Clean same-VM reuse of displaced slot 0 does not need full work write. s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); assert!(!s.render_needs_full_work(0)); @@ -863,7 +877,7 @@ def module(text, name): for c in live.iter_mut().skip(2) { s.retire(c).unwrap(); } - s.retire(&mut c31).unwrap(); + s.retire(&mut c47).unwrap(); assert_eq!(s.render_published(),0); } @@ -1051,23 +1065,23 @@ def module(text, name): },0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; let a=vm(1); - // Wrapped submission order [30, 31, 0]: retiring in order leaves slot 0 as last_retired - // while slots 30 and 31 are displaced and reusable immediately. - let order=[30usize,31,0]; + // Wrapped submission order [46, 47, 0]: retiring in order leaves slot 0 as last_retired + // while high slots 46 and 47 (bits above 31) are displaced and reusable immediately. + let order=[46usize,47,0]; let mut c=Claims::new(); for (i,&k) in order.iter().enumerate() { s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); c.pass[i]=k as u32; c.pass_count+=1; - c.pass_mask|=1u32< Tier 2, depth 3 (34) -> Tier 3; + // 7-pass compress.bw array: depth 3 (22) -> Tier 2, depth 5 (36) -> Tier 3; + // 4-pass render.shadow: depth 5 (21) -> Tier 2, depth 8 (33) -> Tier 3. let mut last = 0u64; let mut burst = 0u32; - assert_eq!(target_render_slots(&mut last, &mut burst, 10_000_000, 8, 0, false, BASE_RENDER_SLOTS), tier1_end); - assert_eq!(target_render_slots(&mut last, &mut burst, 20_000_000, 20, 0, false, BASE_RENDER_SLOTS), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 10_000_000, 11, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 15_000_000, 11, 11, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 18_000_000, 11, 22, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 20_000_000, 7, 7, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 25_000_000, 7, 14, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 28_000_000, 7, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 30_000_000, 4, 12, false, tier1_end), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 35_000_000, 4, 16, false, tier1_end), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 38_000_000, 4, 28, false, tier2_end), full_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 40_000_000, 8, 0, false, BASE_RENDER_SLOTS), tier1_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 50_000_000, 20, 0, false, BASE_RENDER_SLOTS), tier2_end); + assert_eq!(target_render_slots(&mut last, &mut burst, 60_000_000, 32, 0, false, BASE_RENDER_SLOTS), full_end); // Verify exact per-slot mapped backing bytes for Base vs Ext slots. let mut o_base = Objects::new(); @@ -1183,10 +1216,13 @@ def module(text, name): g16::slots::PassSlot::new(&mut o_ext, 2, 1).unwrap(); let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 608) * 1024); - // Tier 0 (6 ext slots) is 21.5625 MiB vs 107.8125 MiB for all 30 ext slots. + // Cumulative extension backing across the 4 demand-grown tiers: + // Tier 0 (6 ext): 21.5625 MiB, Tier 1 (16 ext): 57.50 MiB, + // Tier 2 (30 ext): 107.8125 MiB, Tier 3 (46 ext): 165.3125 MiB. assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 22_080 * 1024); assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 58_880 * 1024); - assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 110_400 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 110_400 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 169_280 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ From 9862ccf8d92f6daff56f238cbde948bcd9f6c4d3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 09:25:07 -0500 Subject: [PATCH 0849/1514] drm/asahi: g16: add lazy recovery PB/UMA allocator slots to survive render hangs Physical render PB/UMA allocators (hardware UMA slot 33) were previously capped at two fixed slots (parameter_id 0 and 1). Once both slots had been used across VMs (for example compositor plus benchmark), a single render hang on the active slot called pools.invalidate() and pools.quarantine_flight(), leaving the other slot undisplaced and immediately tripping Pools::exhausted() -> render_failed=1, degraded=1, and device wedged even with 14+ healthy render pass slots remaining. Expand the client-VA render allocator window to PB_SLOTS = 6 (parameter_id 0..6 in a 64 MiB stride across 0x7008000000..0x7020000000, disjoint from base compute units, render pass slots, dynamic PB page lists, and extension compute units). Keep non-fault VMs at BASE_PB_SLOTS = 2 with zero extra RAM overhead; lazily allocate per-slot PoolExtArena recovery allocators sharing the VM's existing PB heap only after a render hang quarantines an allocator slot, signaled locklessly via Shared::needed_pb_slots. Generalize Pools selection, displacement, and exhaustion checks to PB_SLOTS while preserving the two-slot working set in normal cross-VM switching and per-job limit checks (pick_slot_within / can_pipeline_within / exhausted_for_within) so pre-hang jobs cancel cleanly instead of spinning on EAGAIN. Add host unit tests covering the exact cross-VM single-render-hang recovery and survivor displacement path, multi-hang survival up to four quarantines, and clean exhaustion at the slot limit. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 41 ++- drivers/gpu/drm/asahi/g16/hw.rs | 24 +- drivers/gpu/drm/asahi/g16/mod.rs | 3 + drivers/gpu/drm/asahi/g16/poll.rs | 13 +- drivers/gpu/drm/asahi/g16/pools.rs | 290 +++++++++++------- drivers/gpu/drm/asahi/g16/queue.rs | 1 + drivers/gpu/drm/asahi/g16/resources.rs | 147 ++++++++- .../drivers/gpu/asahi-m4/test-publication.py | 5 +- .../drivers/gpu/asahi-m4/test-resources.py | 137 +++++++-- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 2 +- 10 files changed, 492 insertions(+), 171 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index af7c7f941a972e..ab93ae19480d10 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -967,7 +967,10 @@ impl Firmware { // 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 + .pb_slots() + .is_ok_and(|n| self.pools.exhausted_for_within(&job.vm, n)) || job .resources .render_passes() @@ -1116,7 +1119,10 @@ impl Firmware { f.doomed || f.recovery_suspect || f.initbm || !Arc::ptr_eq(&f.job.vm, &job.vm) }) || (matches!(command(job, job.progress.sent()), Some(Command::Render(_))) - && !self.pools.can_pipeline(&job.vm)) + && !job + .resources + .pb_slots() + .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n))) } /// Whether `job`'s next command may be published behind the flights in flight: @@ -1186,7 +1192,10 @@ impl Firmware { && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() - && self.pools.can_pipeline(&job.vm) + && job + .resources + .pb_slots() + .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n)) && job .resources .render_passes() @@ -1305,10 +1314,9 @@ impl Firmware { engine_behind: bool, ) -> Result<(RenderRefs, bool, Arc, u64)> { let generation = job.vm.generation; - let arena = job.resources.render()?; - let mut a = arena - .pools - .prepare_in_flight(alloc_slot, draw, render_pipelined)?; + let mut a = job + .resources + .prepare_pb_in_flight(alloc_slot, draw, render_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) => { @@ -1323,8 +1331,8 @@ impl Firmware { let e = job.resources.take_pb()?; if let Err(err) = e.prepare( alloc_slot, - arena.pools.heap_gva(alloc_slot)?, - arena.pools.heap_blocks(), + job.resources.pb_heap_gva(alloc_slot)?, + job.resources.pb_heap_blocks()?, ) { job.resources.return_pb(e); return Err(err); @@ -1379,8 +1387,7 @@ impl Firmware { epoch: &super::pools::PbEpoch, prev_uma_submitted: u64, ) -> Result { - let arena = job.resources.render()?; - let a = arena.pools.allocator_refs_for(alloc_slot)?; + let a = job.resources.pb_allocator_refs(alloc_slot)?; let r = &self.graph.render; let stage = draw.checked_mul(2).ok_or(EOVERFLOW)?; let uma_submitted = prev_uma_submitted.checked_add(2).ok_or(EOVERFLOW)?; @@ -1809,7 +1816,7 @@ impl Firmware { self.pools.hold_alloc( f.pb_slot as usize, &job.vm, - job.resources.render_arena(), + job.resources.pb_owner_arena(f.pb_slot as usize), )?; } // Reserve lifetime ownership before any counter or producer becomes reachable. @@ -1826,9 +1833,7 @@ impl Firmware { f.pb.as_ref().ok_or(EINVAL)?.expose(); job.resources.commit_render(); job.resources - .render()? - .pools - .publish_batch(a, f.uma_submitted, f.renders)?; + .publish_pb_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); // Notifier service dereferences u32 counters; the host ordering ledger // remains u64. Eight-byte spacing is retained allocation padding. @@ -2187,7 +2192,11 @@ impl Firmware { self.slots.hold_vm(&f.claims, &job.vm)?; self.slots.hold_arenas(&f.claims, &job.resources); let (refs, init_buffer) = if member == 0 { - let alloc_slot = self.pools.pick_slot(&job.vm, behind).ok_or(EAGAIN)?; + let pb_slots = job.resources.pb_slots()?; + let alloc_slot = self + .pools + .pick_slot_within(&job.vm, behind, pb_slots) + .ok_or(EAGAIN)?; let (refs, init_buffer, epoch, binding) = self.render_refs(alloc_slot, job, draw, class_behind, behind)?; f.pb = Some(epoch); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 6ebc45434aeda0..684d96df83bdc4 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -605,9 +605,16 @@ pub(crate) mod client { pub(crate) const WORK_OFF: u64 = 0; pub(crate) const CWORK_STRIDE: u64 = 0x4000; - // Render allocator units contain one 32 MiB UMA pool and its persistent lists. + // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a + // 64 MiB stride. Slots 0..4 live in 0x7010000000..0x7020000000; slots 4..PB_SLOTS + // live in 0x7008000000..0x7010000000, above base compute units 0..2 (ending at + // 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). pub(crate) const fn render_base(k: u64) -> u64 { - 0x7010000000 + k * 0x08000000 + if k < 4 { + 0x7010000000 + k * 0x04000000 + } else { + 0x7008000000 + (k - 4) * 0x04000000 + } } pub(crate) const fn render_pool(k: u64) -> u64 { render_base(k) @@ -675,6 +682,19 @@ pub(crate) mod sizes { pub(crate) const QUEUE_CAP: u32 = 256; /// Compute units claimable in one batched compute prefix (matches `COMPUTE_UNITS`). pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; + /// Base physical PB/UMA allocator slots allocated per VM on first render. + pub(crate) const BASE_PB_SLOTS: usize = 2; + /// Physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware UMA slot 33). + /// Base slots `0..BASE_PB_SLOTS` serve normal cross-VM switching; extra slots are allocated + /// lazily per VM only after a render hang permanently quarantines an allocator slot. + pub(crate) const PB_SLOTS: usize = 6; + const _: () = assert!(PB_SLOTS >= BASE_PB_SLOTS && PB_SLOTS <= 6); + const _: () = + assert!(super::client::compute_context(1) + 0x40000 <= super::client::render_base(4)); + const _: () = + assert!(super::client::render_descriptor(3) + 0x4000 <= super::client::FS_WORK_PAGE); + const _: () = + assert!(super::client::render_descriptor(5) + 0x4000 <= super::client::render_base(0)); /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most (host client-VA budget: 512 MiB / 32 MiB diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2f165d0da96537..527488b4a2a267 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -240,6 +240,8 @@ pub(crate) struct Shared { pub(crate) base_compute_quarantined: AtomicBool, /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. pub(crate) base_render_quarantined: AtomicBool, + /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. + pub(crate) needed_pb_slots: AtomicU32, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -480,6 +482,7 @@ impl Gpu { recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), base_render_quarantined: AtomicBool::new(false), + needed_pb_slots: AtomicU32::new(hw::sizes::BASE_PB_SLOTS as u32), sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 7870aff8c887bc..7507c986ffccf4 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -956,9 +956,7 @@ impl Firmware { || g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot) && f.job .resources - .render()? - .pools - .retired_at(a, f.uma_submitted)?; + .pb_retired_at(a, f.uma_submitted)?; } else { // Check FS (terminal stage) before TA so running renders fail fast on 1 WC read. if g.fw_stamp[1].r32(0)? != f.fs_target @@ -986,7 +984,7 @@ impl Firmware { && g.notifier .r32(notifier_page::FS_RECORD + notifier::CONTEXT)? == f.job.vm.slot - && f.job.resources.render()?.pools.retired(a)?; + && f.job.resources.pb_retired(a)?; } if full { let count = (f.renders as usize).min(f.claims.pass.len()); @@ -1051,8 +1049,8 @@ impl Firmware { } } - /// Publishes lockless quarantine hints so `SUBMIT` expands extension slots immediately - /// when a base slot has been permanently quarantined. + /// Publishes lockless quarantine hints so `SUBMIT` expands extension and recovery slots + /// immediately when a base or PB allocator slot has been permanently quarantined. pub(crate) fn sync_quarantine_hints(&self) { if let Some(shared) = &self.engine.shared { shared @@ -1061,6 +1059,9 @@ impl Firmware { shared .base_render_quarantined .store(self.slots.base_render_quarantined(), Ordering::Release); + shared + .needed_pb_slots + .store(self.pools.needed_slots() as u32, Ordering::Release); } } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index b3d0ec8e3cd47c..797bf9f1e63f26 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -14,7 +14,7 @@ pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; -use super::hw::{client, engine, pte}; +use super::hw::{client, engine, pte, sizes}; use super::object::{Class, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; @@ -46,7 +46,7 @@ pub(crate) struct AllocatorRefs { pub(crate) init_buffer: bool, } -struct Allocator { +pub(crate) struct Allocator { descriptor: Arc, auxiliary: Arc, #[allow(dead_code)] @@ -77,6 +77,7 @@ pub(crate) struct PbStats { pub(crate) struct PoolSet { units: KVec, + heap: Arc, /// Blocks of the shared heap (the PB managers' lists cover the whole 256 MiB window). heap_blocks: u32, } @@ -130,7 +131,7 @@ fn write_records( Ok(()) } impl Allocator { - fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { + pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { 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 @@ -177,7 +178,7 @@ impl Allocator { id: k as u32, }) } - fn refs(&self) -> Result { + pub(crate) fn refs(&self) -> Result { let prior = read64(&self.submitted, 0)?; if prior & 1 != 0 { return Err(EINVAL); @@ -197,15 +198,50 @@ impl Allocator { init_buffer: true, }) } - fn retired(&self) -> Result { + /// Prepares this UMA/PB allocator slot. 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, _draw: u64, pipelined: bool) -> Result { + if !pipelined && self.published.load(Ordering::Acquire) && !self.retired()? { + return Err(EBUSY); + } + // Descriptor pointer/counter and slot must still identify this exact retained unit. + if read64(&self.descriptor, 0)? != self.descriptor.va + || self.descriptor.r32(8)? != engine::RENDER_UMA_SLOT + || read64(&self.descriptor, 0x4c)? != self.submitted.va + { + return Err(EINVAL); + } + self.refs() + } + pub(crate) fn publish_batch(&self, submitted: u64, renders: u32) -> Result { + if renders == 0 { + return Err(EINVAL); + } + let delta = u64::from(renders).checked_mul(2).ok_or(EOVERFLOW)?; + if submitted + != read64(&self.submitted, 0)? + .checked_add(delta) + .ok_or(EOVERFLOW)? + { + return Err(EINVAL); + } + self.submitted.w64(0, submitted)?; + self.published.store(true, Ordering::Release); + Ok(()) + } + pub(crate) fn retired(&self) -> Result { let submitted = read64(&self.submitted, 0)?; let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; Ok(submitted != 0 && submitted == completed) } - fn retired_at(&self, target: u64) -> Result { + pub(crate) fn retired_at(&self, target: u64) -> Result { let completed = read64(&self.descriptor, uma_manager::COMPLETED)?; Ok(target != 0 && completed >= target) } + pub(crate) fn heap_gva(&self) -> Result { + gva(&self.heap) + } } impl PoolSet { pub(crate) fn new(o: &mut Objects) -> Result { @@ -219,11 +255,23 @@ impl PoolSet { Some((client::pb_heap(0), pte::LEAF_NC)), false, )?; - let mut units = KVec::with_capacity(2, GFP_KERNEL)?; - for k in 0..2 { + let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; + for k in 0..sizes::BASE_PB_SLOTS as u64 { units.push(Allocator::new(o, k, &heap)?, GFP_KERNEL)?; } - Ok(Self { units, heap_blocks }) + Ok(Self { + units, + heap, + heap_blocks, + }) + } + #[allow(dead_code)] + pub(crate) fn unit(&self, k: usize) -> Option<&Allocator> { + self.units.get(k) + } + #[allow(dead_code)] + pub(crate) fn heap(&self) -> &Arc { + &self.heap } #[allow(dead_code)] pub(crate) fn allocator_refs_for(&self, k: usize) -> Result { @@ -233,45 +281,27 @@ impl PoolSet { 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. + /// Prepares base UMA/PB allocator slot `k` (`0..BASE_PB_SLOTS`). + #[allow(dead_code)] pub(crate) fn prepare_in_flight( &self, k: usize, - _draw: u64, + draw: u64, pipelined: bool, ) -> Result { - let u = self.units.get(k).ok_or(EINVAL)?; - if !pipelined && u.published.load(Ordering::Acquire) && !u.retired()? { - return Err(EBUSY); - } - // Descriptor pointer/counter and slot must still identify this exact retained unit. - if read64(&u.descriptor, 0)? != u.descriptor.va - || u.descriptor.r32(8)? != engine::RENDER_UMA_SLOT - || read64(&u.descriptor, 0x4c)? != u.submitted.va - { - return Err(EINVAL); - } - u.refs() + self.units + .get(k) + .ok_or(EINVAL)? + .prepare_in_flight(draw, pipelined) } + #[allow(dead_code)] pub(crate) fn publish_batch(&self, k: usize, submitted: u64, renders: u32) -> Result { - if renders == 0 { - return Err(EINVAL); - } - let u = self.units.get(k).ok_or(EINVAL)?; - let delta = u64::from(renders).checked_mul(2).ok_or(EOVERFLOW)?; - if submitted - != read64(&u.submitted, 0)? - .checked_add(delta) - .ok_or(EOVERFLOW)? - { - return Err(EINVAL); - } - u.submitted.w64(0, submitted)?; - u.published.store(true, Ordering::Release); - Ok(()) + self.units + .get(k) + .ok_or(EINVAL)? + .publish_batch(submitted, renders) } + #[allow(dead_code)] pub(crate) fn retired(&self, k: usize) -> Result { self.units.get(k).ok_or(EINVAL)?.retired() } @@ -279,65 +309,85 @@ impl PoolSet { pub(crate) fn retired_at(&self, k: usize, target: u64) -> Result { self.units.get(k).ok_or(EINVAL)?.retired_at(target) } + #[allow(dead_code)] pub(crate) fn heap_gva(&self, k: usize) -> Result { - gva(&self.units.get(k).ok_or(EINVAL)?.heap) + self.units.get(k).ok_or(EINVAL)?.heap_gva() } pub(crate) fn heap_blocks(&self) -> u32 { self.heap_blocks } } -/// Device-wide physical PB-slot leases (`parameter_id` 0 and 1, hardware UMA slot 33). +/// Device-wide physical PB-slot leases (`parameter_id` `0..PB_SLOTS`, 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. +/// while cross-VM switches or post-recovery/error renders drain and switch to a displaced or +/// fresh alternate `pb_slot` so the previous VM's UMA/PB storage remains mapped through +/// displacement. Under normal non-fault operation the working set stays on the two base slots; +/// recovery slots `BASE_PB_SLOTS..PB_SLOTS` are claimed only after a render hang permanently +/// quarantines a slot. pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, - owners: [Option>; 2], + owners: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] - owner_vms: [Option>; 2], + owner_vms: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] - owner_arenas: [Option>; 2], - pending_vms: [Option>; 2], - pending_arenas: [Option>; 2], + owner_arenas: [Option; sizes::PB_SLOTS], + pending_vms: [Option>; sizes::PB_SLOTS], + pending_arenas: [Option; sizes::PB_SLOTS], /// 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], + binds: [u64; sizes::PB_SLOTS], /// 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`). + keep: [bool; sizes::PB_SLOTS], + /// Most recently published allocator slot (`0..PB_SLOTS`). active: Option, - /// Most recently cleanly retired allocator slot (proves the alternate slot is displaced). + /// Most recently cleanly retired allocator slot (proves every other slot is displaced). last_clean_retired: Option, /// Live in-flight render count per allocator slot. - inflight: [u32; 2], + inflight: [u32; sizes::PB_SLOTS], /// Permanently quarantined allocator slots after an aborted receipt. - quarantined: [bool; 2], + quarantined: [bool; sizes::PB_SLOTS], /// Fresh PB epoch retained when an aborted render had not yet replaced `owners[k]`. - quarantined_epochs: [Option>; 2], + quarantined_epochs: [Option>; sizes::PB_SLOTS], } impl Pools { pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { Self { 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], + owners: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], active: None, last_clean_retired: None, - inflight: [0, 0], - quarantined: [false, false], - quarantined_epochs: [None, None], + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], } } + /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare + /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. + #[allow(dead_code)] + pub(crate) fn needed_slots(&self) -> usize { + let quarantined = self.quarantined.iter().filter(|&&q| q).count(); + sizes::BASE_PB_SLOTS + .saturating_add(quarantined) + .min(sizes::PB_SLOTS) + } + /// Whether slot `k` is healthy, not active, and either fresh or displaced by a clean + /// retirement of some other slot. + fn slot_displaced(&self, k: usize) -> bool { + !self.quarantined[k] + && self.active != Some(k) + && (self.owners[k].is_none() || self.last_clean_retired.is_some_and(|r| r != k)) + } /// 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 @@ -351,81 +401,91 @@ impl Pools { (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`. + /// Selects a physical PB/UMA allocator slot within `0..limit` 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 { + /// be within `0..limit`, healthy, and reusable for `vm`. When `behind` is false (engine + /// drained), a same-VM render stays on its reusable active slot if within `0..limit`; + /// otherwise it switches to an already-used displaced slot first (preserving the 2-slot + /// working set) or claims the lowest fresh slot. + pub(crate) fn pick_slot_within( + &self, + vm: &Arc, + behind: bool, + limit: usize, + ) -> Option { + let n = limit.min(sizes::PB_SLOTS); if behind { let a = self.active?; - return (!self.quarantined[a] && self.reusable(a, vm).is_some()).then_some(a); + return (a < n && !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) + if let Some(a) = self.active { + if a < n && !self.quarantined[a] && self.reusable(a, vm).is_some() { + return Some(a); } } + // Prefer reusing a displaced slot over claiming a fresh recovery slot. + (0..n) + .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) + } + /// Selects a physical PB/UMA allocator slot across all `0..PB_SLOTS` for `vm`. + #[allow(dead_code)] + pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { + self.pick_slot_within(vm, behind, sizes::PB_SLOTS) + } + /// Whether `vm` can pipeline another render behind active same-VM renders within `0..limit`. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within(&self, vm: &Arc, limit: usize) -> bool { + self.pick_slot_within(vm, true, limit).is_some() } /// 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() + self.can_pipeline_within(vm, sizes::PB_SLOTS) } /// 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] { + if self.inflight.iter().any(|&c| c != 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 + if let Some(a) = self.active { + let can_reuse_active = !self.quarantined[a] + && self.keep[a] + && self.owners[a] + .as_ref() + .is_some_and(|o| o.exposed.load(Ordering::Acquire)); + if can_reuse_active { + return false; } } + !(0..sizes::PB_SLOTS).any(|k| self.slot_displaced(k)) } - /// Whether no allocator slot can accept a render for `vm` once the engine is drained. + /// Whether no allocator slot within `0..limit` can accept a render for `vm` once 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 + /// When a VM prepared fewer PB slots than needed after a render hang (or when only one + /// surviving slot remains and belongs to another VM), that job must cancel immediately /// instead of spinning on `EAGAIN` until the administrative publication deadline fails the GPU. #[allow(dead_code)] + pub(crate) fn exhausted_for_within(&self, vm: &Arc, limit: usize) -> bool { + self.inflight.iter().all(|&c| c == 0) && self.pick_slot_within(vm, false, limit).is_none() + } + /// Whether no allocator slot can accept a render for `vm` once the engine is drained. + #[allow(dead_code)] pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { - self.inflight == [0, 0] && self.pick_slot(vm, false).is_none() + self.exhausted_for_within(vm, sizes::PB_SLOTS) } - /// Retains the candidate VM and render arena (holding the `PoolSet` UMA descriptors) before - /// publication visibility. + /// Retains the candidate VM and owning render/recovery arena (holding the UMA descriptors) + /// before publication visibility. #[allow(dead_code)] pub(crate) fn hold_alloc( &mut self, k: usize, vm: &Arc, - arena: Option>, + arena: Option, ) -> Result { - if k >= 2 || self.quarantined[k] { + if k >= sizes::PB_SLOTS || self.quarantined[k] { return Err(EINVAL); } self.pending_vms[k] = Some(vm.clone()); @@ -435,7 +495,7 @@ impl Pools { /// Cancels unpublished candidate retention for allocator slot `k`. #[allow(dead_code)] pub(crate) fn cancel_alloc(&mut self, k: usize) { - if k < 2 { + if k < sizes::PB_SLOTS { self.pending_vms[k] = None; self.pending_arenas[k] = None; } @@ -443,7 +503,7 @@ impl Pools { /// 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 { + if k < sizes::PB_SLOTS { self.active = Some(k); self.inflight[k] = self.inflight[k].saturating_add(1); } @@ -457,7 +517,7 @@ impl Pools { binding: u64, completed: bool, ) -> Result { - if k >= 2 { + if k >= sizes::PB_SLOTS { return Err(EINVAL); } self.inflight[k] = self.inflight[k].saturating_sub(1); @@ -479,7 +539,7 @@ impl Pools { /// including any fresh epoch published on the aborted flight alongside `owners[k]`. #[allow(dead_code)] pub(crate) fn quarantine_flight(&mut self, k: usize, pb: Option>) { - if k < 2 { + if k < sizes::PB_SLOTS { self.inflight[k] = self.inflight[k].saturating_sub(1); self.quarantined[k] = true; self.keep[k] = false; @@ -609,7 +669,7 @@ 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, heap_blocks: u32) -> Result { - if k >= 2 + if k >= sizes::PB_SLOTS || self.exposed.load(Ordering::Acquire) || heap_blocks == 0 || heap_blocks > buffer::MAX_BLOCKS diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 564af7f926ae97..5150716b563d17 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -233,6 +233,7 @@ impl Queue { let hints = super::resources::PrepareHints { expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), + pb_slots: self.shared.needed_pb_slots.load(Ordering::Acquire) as usize, }; let resources = self .vm diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index dea5b3501ccd1f..a24050a97e9485 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -84,6 +84,8 @@ impl ComputeArena { /// pipelines renders or submits a multi-pass/burst frame. pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; const EXT_RENDER_SLOTS: usize = super::hw::sizes::RENDER_SLOTS - BASE_RENDER_SLOTS; +const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; +const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; /// Single-submission render command count that expands extension slots immediately: /// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; @@ -95,6 +97,8 @@ pub(crate) struct PrepareHints { pub(crate) expand_compute_ext: bool, /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. pub(crate) expand_render_ext: bool, + /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. + pub(crate) pb_slots: usize, } /// Updates the consecutive-compute burst counter and reports whether this submission @@ -247,6 +251,54 @@ impl RenderExtArena { } } +/// One lazily allocated recovery PB/UMA allocator slot (`BASE_PB_SLOTS..PB_SLOTS`), +/// sharing the VM's base PB heap so non-fault VMs pay zero extra allocator memory. +pub(crate) struct PoolExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for PoolExtArena { + type Target = PoolExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct PoolExtInner { + pub(crate) allocator: super::pools::Allocator, + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl PoolExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + slot: usize, + heap: &Arc, + ) -> Result> { + let mut objects = factory.objects(vm); + let allocator = super::pools::Allocator::new(&mut objects, slot as u64, heap)?; + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(PoolExtInner { + allocator, + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// Keeps the arena owning a retained PB/UMA allocator slot alive through displacement. +/// The wrapped `Arc`s are held solely for their `Drop` lifetime and never read back. +#[derive(Clone)] +#[allow(dead_code)] +pub(crate) enum PbOwnerArena { + Base(Arc), + Ext(Arc), +} + /// Keeps the arena owning a retained pass slot alive through displacement. #[derive(Clone)] pub(crate) enum PassOwnerArena { @@ -275,6 +327,8 @@ struct Ready { render: Option>, /// Pass slots from [`BASE_RENDER_SLOTS`] on, for a VM that keeps renders queued. render_ext: Option>, + /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. + pb_ext: [Option>; EXT_PB_SLOTS], /// Last compute submission and the back-to-back run it continues. last_compute_ns: u64, burst: u32, @@ -450,6 +504,7 @@ impl Cache { ready.compute_ext.take(), ready.render.take(), ready.render_ext.take(), + core::mem::take(&mut ready.pb_ext), ) }; drop(ready); @@ -472,7 +527,7 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; - let (compute, compute_ext, render_arena, render_ext) = { + let (compute, compute_ext, render_arena, render_ext, pb_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(); @@ -522,6 +577,30 @@ impl Cache { )?); } if render { + let target_pb = hints.pb_slots.clamp(BASE_PB_SLOTS, super::hw::sizes::PB_SLOTS); + if target_pb > BASE_PB_SLOTS { + if let Some(base) = ready.render.as_ref() { + let heap = base.pools.heap().clone(); + for k in BASE_PB_SLOTS..target_pb { + let idx = k - BASE_PB_SLOTS; + if ready.pb_ext[idx].is_none() { + // Best effort: without recovery slots, keep prior PB slots. + ready.pb_ext[idx] = PoolExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + k, + &heap, + ) + .ok(); + if ready.pb_ext[idx].is_none() { + break; + } + } + } + } + } if ready.render_ext.is_none() && EXT_RENDER_SLOTS != 0 { // SAFETY: ktime_get has no preconditions. let now = unsafe { kernel::bindings::ktime_get() } as u64; @@ -541,11 +620,17 @@ impl Cache { } } } + let pb_ext = if render { + core::array::from_fn(|idx| ready.pb_ext[idx].clone()) + } else { + [const { None }; EXT_PB_SLOTS] + }; ( 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 }, + pb_ext, ) }; if render { @@ -643,6 +728,7 @@ impl Cache { compute_ext, render: render_arena, render_ext, + pb_ext, unpublished_renders: AtomicU32::new(render_count), cache, }) @@ -657,6 +743,8 @@ pub(crate) struct Prepared { pub(crate) render: Option>, /// The VM's extension render pass slots when the job was prepared. pub(crate) render_ext: Option>, + /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. + pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], /// 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. @@ -692,9 +780,60 @@ impl Prepared { self.compute_ext.clone() } } - /// The base render arena (owning the PB/UMA `PoolSet`). - pub(crate) fn render_arena(&self) -> Option> { - self.render.clone() + /// Contiguous PB/UMA allocator slots (`0..n`) this job can use. + pub(crate) fn pb_slots(&self) -> Result { + let _ = self.render()?; + let ext = self.pb_ext.iter().take_while(|slot| slot.is_some()).count(); + Ok(BASE_PB_SLOTS + ext) + } + fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { + let base = self.render()?; + if k < BASE_PB_SLOTS { + base.pools.unit(k).ok_or(EINVAL) + } else { + self.pb_ext + .get(k - BASE_PB_SLOTS) + .and_then(|slot| slot.as_deref()) + .map(|arena| &arena.allocator) + .ok_or(EINVAL) + } + } + pub(crate) fn prepare_pb_in_flight( + &self, + k: usize, + draw: u64, + pipelined: bool, + ) -> Result { + self.pb_allocator(k)?.prepare_in_flight(draw, pipelined) + } + pub(crate) fn pb_allocator_refs(&self, k: usize) -> Result { + self.pb_allocator(k)?.refs() + } + pub(crate) fn publish_pb_batch(&self, k: usize, submitted: u64, renders: u32) -> Result { + self.pb_allocator(k)?.publish_batch(submitted, renders) + } + pub(crate) fn pb_retired(&self, k: usize) -> Result { + self.pb_allocator(k)?.retired() + } + pub(crate) fn pb_retired_at(&self, k: usize, target: u64) -> Result { + self.pb_allocator(k)?.retired_at(target) + } + pub(crate) fn pb_heap_gva(&self, k: usize) -> Result { + self.pb_allocator(k)?.heap_gva() + } + pub(crate) fn pb_heap_blocks(&self) -> Result { + Ok(self.render()?.pools.heap_blocks()) + } + /// The arena owning PB/UMA allocator slot `k`. + pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { + if k < BASE_PB_SLOTS { + self.render.as_ref().map(|r| PbOwnerArena::Base(r.clone())) + } else { + self.pb_ext + .get(k - BASE_PB_SLOTS) + .and_then(|slot| slot.as_ref()) + .map(|ext| PbOwnerArena::Ext(ext.clone())) + } } /// Render pass slots this job can use. pub(crate) fn render_passes(&self) -> Result { 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 3089703990d7f7..9ba9f6cb7f265b 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -80,7 +80,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)}fn render_passes(&self)->Result{Ok(8)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}} struct Job { id:u32,vm:Arc,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} @@ -124,7 +124,9 @@ def item(declaration): impl Pools{ fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} + fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} + fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -499,6 +501,7 @@ def item(declaration): impl QueueBehindPools{ fn exhausted(&self)->bool{self.exhausted} fn can_pipeline(&self,_vm:&Arc)->bool{self.can_pipeline} + fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { 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 53aa97dc635f63..1fb10b463554d9 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -151,6 +151,9 @@ def module(text, name): pub type Prepared=ComputeArena; #[derive(Clone)] pub enum PassOwnerArena{Base(crate::sync::Arc)} + pub struct PoolExtArena; + #[derive(Clone)] + pub enum PbOwnerArena{Base(crate::sync::Arc),Ext(crate::sync::Arc)} impl PassOwnerArena{ pub fn pass_and_tilemap_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,&AtomicU64)>{ match self{Self::Base(a)=>Some((a.passes.get(k)?,a.tilemap_dirty.get(k)?))} @@ -563,7 +566,11 @@ def module(text, name): #[test]fn eight_render_passes_and_sixteen_compute_units_are_disjoint_in_mesa_hole(){ let mut o=Objects::new(); - let _pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o).unwrap(); + for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { + let ext=g16::pools::Allocator::new(&mut o,k,pools.heap()).unwrap(); + assert_eq!(ext.refs().unwrap().parameter_id,k as u32); + } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { g16::slots::ComputeSlot::new(&mut o,k).unwrap(); } @@ -637,40 +644,118 @@ def module(text, name): p.publish_flight(1); p.retire_flight(1,&e2,b2,true).unwrap(); assert!(!p.exhausted()); - // 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.needed_slots(),g16::hw::sizes::BASE_PB_SLOTS); + // Normal cross-VM switch back to VM1 reuses displaced slot 0 rather than claiming slot 2. assert_eq!(p.pick_slot(&vm1,false),Some(0)); - p.publish_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); + } + + #[test]fn render_hang_after_cross_vm_use_recovers_via_lazy_pb_slot_and_displaces_survivor(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3);let vm4=vm(4); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Exact live cross-VM sequence: VM1 on slot 0 -> VM2 on slot 1 -> VM1 on slot 0. + let e1=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1,b,true).unwrap(); + let e2=mk_epoch(&vm2,1); + assert_eq!(p.pick_slot_within(&vm2,false,2),Some(1)); + let b=p.bind(1,false);p.publish_flight(1);p.retire_flight(1,&e2,b,true).unwrap(); + let e1b=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1b,b,true).unwrap(); + // VM3 switches to slot 1 with a fresh epoch and hangs: recovery invalidates epochs + // and quarantines slot 1 while retaining BOTH the prior owner (e2) and fresh epoch (e3). + let e3=mk_epoch(&vm3,1); + assert_eq!(p.pick_slot_within(&vm3,false,2),Some(1)); + let _=p.bind(1,false);p.publish_flight(1); + p.invalidate(); + p.quarantine_flight(1,Some(e3.clone())); + assert_eq!(sync::Arc::strong_count(&e2),2,"prior slot owner epoch must stay mapped"); + assert_eq!(sync::Arc::strong_count(&e3),2,"aborted fresh epoch must stay mapped"); + // Render class must NOT wedge: slot 2 is fresh and needed_slots advances to 3. + assert!(!p.exhausted()); + assert_eq!(p.needed_slots(),3); + // Pre-hang job with only 2 prepared PB slots sees per-job exhaustion (no EAGAIN spin), + // while a post-hang job with 3 prepared PB slots claims recovery slot 2. + assert!(p.exhausted_for_within(&vm4,2)); + assert!(!p.exhausted_for_within(&vm4,3)); + assert_eq!(p.pick_slot_within(&vm4,false,3),Some(2)); + let e4=mk_epoch(&vm4,2); + let b=p.bind(2,false);p.publish_flight(2);p.retire_flight(2,&e4,b,true).unwrap(); + // Clean retirement on slot 2 displaces surviving slot 0 back to reusable! + assert!(!p.exhausted_for_within(&vm1,3)); + assert_eq!(p.pick_slot_within(&vm1,false,3),Some(0)); + let e1c=mk_epoch(&vm1,0); + let b=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1c,b,true).unwrap(); + // Subsequent cross-VM render reuses displaced slot 2 (does not consume slot 3). + assert_eq!(p.pick_slot_within(&vm2,false,3),Some(2)); + // An unrelated compute hang calling invalidate() does not wedge render either. + p.invalidate(); + assert!(!p.exhausted()); + assert_eq!(p.pick_slot_within(&vm2,false,3),Some(2)); + } + + #[test]fn pb_recovery_slots_survive_four_render_hangs_and_exhaust_cleanly_at_limit(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Quarantine 4 slots (0..4): 2 healthy slots (4 and 5) remain for cross-VM switching. + for hang in 0..4usize { + let n=p.needed_slots(); + let slot=p.pick_slot_within(&vm1,false,n).unwrap(); + assert_eq!(slot,hang); + p.publish_flight(slot); + p.invalidate(); + p.quarantine_flight(slot,None); + assert!(!p.exhausted()); + assert_eq!(p.needed_slots(),(2+hang+1).min(g16::hw::sizes::PB_SLOTS)); + } + assert_eq!(p.needed_slots(),g16::hw::sizes::PB_SLOTS); + // Cross-VM switching still works cleanly across slots 4 and 5. + assert_eq!(p.pick_slot(&vm1,false),Some(4)); + let e4=mk_epoch(&vm1,4); + let b=p.bind(4,false);p.publish_flight(4);p.retire_flight(4,&e4,b,true).unwrap(); + assert_eq!(p.pick_slot(&vm2,false),Some(5)); + let e5=mk_epoch(&vm2,5); + let b=p.bind(5,false);p.publish_flight(5);p.retire_flight(5,&e5,b,true).unwrap(); + assert_eq!(p.pick_slot(&vm1,false),Some(4)); + // 5th hang quarantines slot 4: only slot 5 survives (reuse-only for VM2; other VMs exhausted). + p.publish_flight(4); + p.quarantine_flight(4,None); + // Slot 5 was the last_clean_retired slot (undisplaced) and slot 4 is quarantined -> exhausted. assert!(p.exhausted()); - assert!(p.exhausted_for(&vm1)); - // Quarantine slot 0 while slot 1 is still fresh: VM2 claims and reuses slot 1, while + // Quarantine 5 fresh slots leaving slot 5 fresh: VM2 claims and reuses slot 5 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,None); - assert!(!q.exhausted()); - assert_eq!(q.pick_slot(&vm2,false),Some(1)); - let qb2=q.bind(1,false); - q.publish_flight(1); + for _ in 0..5 { + let slot=q.pick_slot(&vm1,false).unwrap(); + q.publish_flight(slot); + q.quarantine_flight(slot,None); + assert!(!q.exhausted()); + } + assert_eq!(q.pick_slot(&vm2,false),Some(5)); + let qe5=mk_epoch(&vm2,5); + let qb=q.bind(5,false); + q.publish_flight(5); assert!(!q.exhausted_for(&vm3)); // in-flight: waits for drain first - q.retire_flight(1,&e2,qb2,true).unwrap(); + q.retire_flight(5,&qe5,qb,true).unwrap(); assert!(!q.exhausted()); assert!(!q.exhausted_for(&vm2)); - assert_eq!(q.pick_slot(&vm2,false),Some(1)); + assert_eq!(q.pick_slot(&vm2,false),Some(5)); assert!(q.exhausted_for(&vm1)); assert!(q.exhausted_for(&vm3)); - // Recovery invalidates the surviving slot's epoch -> global pool exhaustion. + // Recovery invalidates the last surviving slot's epoch -> global pool exhaustion. q.invalidate(); assert!(q.exhausted()); assert!(q.exhausted_for(&vm2)); @@ -1162,7 +1247,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 30, + 'result': 'pass', 'tests': 32, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', 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 774f0d01e1193d..26afcd4f09cedd 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 @@ -45,7 +45,7 @@ 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)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.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)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} struct Claims{slot:[u32;16],slot_count:u32,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],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} From 87c8f9192dd23f7f5bbc15a8d8f17133606db4f7 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 06:40:37 -0500 Subject: [PATCH 0850/1514] drm/asahi: g16: release full batched render count in commit_render() When multiple render commands are batched into a single G16 flight, engine publication previously called commit_render() once, leaving (f.renders - 1) standby PB reservations held until Prepared::drop on the deferred cleanup worker. Pass f.renders to commit_render() so all published render commands release their standby reservations immediately upon firmware visibility. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 2 +- drivers/gpu/drm/asahi/g16/resources.rs | 22 ++++++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 12a6f70d391515..606d824a28ad59 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1869,7 +1869,7 @@ impl Firmware { if render { let a = f.pb_slot as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); - job.resources.commit_render(); + job.resources.commit_render(f.renders); job.resources .publish_pb_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 55ecfd6f3a9749..9b841aca8c710b 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -1005,15 +1005,21 @@ impl Prepared { cache.return_standby(epoch); } } - /// Commits one render command's standby reservation once it reaches firmware visibility. - pub(crate) fn commit_render(&self) { + /// Commits `count` render commands' standby reservations once they reach firmware visibility. + pub(crate) fn commit_render(&self, count: u32) { + if count == 0 { + return; + } 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); + if let Ok(prev) = self.unpublished_renders.fetch_update( + Ordering::AcqRel, + Ordering::Acquire, + |n| Some(n.saturating_sub(count)), + ) { + let released = prev.min(count); + if released != 0 { + cache.release_reserved(released); + } } } } From c29c4656c213647513adc4763fb3f1465ab062ab Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 02:20:06 -0500 Subject: [PATCH 0851/1514] drm/asahi: g16: use usage::Lane, harden suspect aborts, calibrate watchdogs Wrap per-queue fdinfo engine accounting in crate::usage::Lane while keeping real per-stage firmware TA/FS/CDM timestamps, preventing pipelined double-counting and vertex==fragment skew. Add an rmb() between stage/queue gate checks and receipt reads in retired_snapshot_at(), and require two consecutive unsettled polls spanning ABORT_GRACE_NS from the first gate-passed poll before aborting a recovery_suspect flight so innocent flights finishing > 20 ms after recovery cannot falsely abort. Raise the firmware DM2 (compute) progress-watchdog thresholds (~4 ms per tick) in GLOBALS_FIXED: secondary DM2 soft-preempt watchdog 0x9c8 (26B123 0x9cc) from 40 (~0.16 s) to 750 (~3.0 s) and primary DM2 recovery watchdog 0x9cc (26B123 0x9d0) from 50 (~0.20 s) to 800 (~3.2 s) so legitimate long/contended compute dispatches (such as 1.5 s solo workloads) complete without premature firmware recovery while real hangs still recover strictly below the 5 s host fail-stop deadline. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 10 ++++ drivers/gpu/drm/asahi/g16/fw/initdata.rs | 11 ++++- drivers/gpu/drm/asahi/g16/poll.rs | 32 ++++++++++--- drivers/gpu/drm/asahi/g16/queue.rs | 5 +- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 4 ++ .../drivers/gpu/asahi-m4/check-initdata.rs | 8 ++++ .../drivers/gpu/asahi-m4/test-poll-retire.py | 48 ++++++++++++++++++- .../drivers/gpu/asahi-m4/test-publication.py | 6 +++ .../drivers/gpu/asahi-m4/test-resources.py | 10 ++-- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 44 +++++++++++++++-- 10 files changed, 156 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 80a92ec8c8021b..f47b4faea4a02f 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -292,6 +292,10 @@ pub(crate) struct Flight { pub(crate) uma_submitted: u64, pub(crate) recovery_suspect: bool, pub(crate) recovery_started_ns: u64, + /// First time this suspect flight passed its stage/queue gates with unsettled receipts, and + /// how many consecutive unsettled polls have observed it since then. + pub(crate) gate_passed_ns: Option, + pub(crate) unsettled_polls: u32, /// Publication time, ns. pub(crate) published_ns: u64, /// Published behind another flight. @@ -337,6 +341,8 @@ impl Flight { uma_submitted: 0, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, published_ns: 0, behind: false, pb: None, @@ -823,6 +829,8 @@ impl Firmware { f.doomed = true; f.recovery_suspect = true; f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; Ok(()) } @@ -849,6 +857,8 @@ impl Firmware { if unfinished { f.recovery_suspect = true; f.recovery_started_ns = now_ns(); + f.gate_passed_ns = None; + f.unsettled_polls = 0; if fault_asid.is_some_and(|asid| asid >= 1 && asid == f.job.vm.slot) { f.doomed = true; } diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 1bbc1fafa0b10f..18a3c8065537a9 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -425,8 +425,15 @@ const GLOBALS_FIXED: &[(usize, u32)] = &[ (0x9b8, 2), (0x9bc, 40), (0x9c0, 5), - (0x9c8, 40), - (0x9cc, 50), + // Firmware DM2 (compute) progress-watchdog thresholds (~4 ms/tick): + // - 0x9c8 (26B123 0x9cc): secondary DM2 soft-preempt watchdog, raised from 40 (~0.16 s) + // to 750 (~3.0 s) so legitimate long/contended compute dispatches (e.g. 1.5 s solo + // workloads) complete without premature kill while staying below the 5 s host fail-stop. + // - 0x9cc (26B123 0x9d0): primary DM2 recovery watchdog, raised from 50 (~0.20 s) to 800 + // (~3.2 s) so legitimate compute dispatches complete while real hangs still trigger + // firmware recovery well before the 5 s host fail-stop deadline. + (0x9c8, 750), + (0x9cc, 800), ]; /// Fixed 25G83 POWER_PERFORMANCE offsets remapped into every ABI; shared by `encode_for` and diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index ee90bf5ec2cc6c..72e06e65e656ba 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -36,7 +36,7 @@ use super::engine::{complete, now_ns, rmb, Flight, Lap}; use super::fw::graph::{notifier, notifier_page, qstate}; use super::fw::work::compute; use super::job::{self, Completions, Job}; -use super::recovery::logic::Retirement; +use super::recovery::logic::{Retirement, ABORT_GRACE_NS}; use super::regs::EngineState; use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK}; use crate::module_parameters; @@ -967,6 +967,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; full &= stamp_reached(stamp, f.target, e.target) && (stamp != f.target @@ -977,6 +978,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; } @@ -1026,6 +1028,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); let fs_stamp = g.notifier.r32(notifier_page::FS_STAMP)?; let ta_stamp = g.notifier.r32(notifier_page::TA_STAMP)?; full &= stamp_reached(fs_stamp, f.fs_target, e.fs_target) @@ -1060,6 +1063,7 @@ impl Firmware { { return Ok(Retirement::Pending); } + rmb(); full &= g.notifier.r32(notifier_page::FS_STAMP)? == f.fs_target && g.notifier.r32(notifier_page::TA_STAMP)? == f.ta_target && g.notifier.r32(notifier::CONTEXT)? == f.job.vm.slot @@ -1094,13 +1098,27 @@ impl Firmware { self.engine.retired_ticks = ticks; return Ok(Retirement::Full); } - if f.recovery_suspect && now_ns().saturating_sub(f.recovery_started_ns) >= 20_000_000 { - // Queues, pipes and every participating stage passed the retained command. - // The firmware recovered it without normal completion: fail and quarantine. - if let Some(f) = self.engine.flights.get_mut(index) { - f.doomed = true; + if f.recovery_suspect { + // Queues, pipes and every participating stage passed the retained command, yet normal + // receipts have not settled. Measure the abort grace from this first gate-passed poll + // and require a second unsettled poll so an innocent suspect flight finishing > 20 ms + // after recovery cannot race a transient WC/notifier write into a false abort. + let now = now_ns(); + let aborted = if let Some(f) = self.engine.flights.get_mut(index) { + let first = *f.gate_passed_ns.get_or_insert(now); + f.unsettled_polls = f.unsettled_polls.saturating_add(1); + if f.unsettled_polls >= 2 && now.saturating_sub(first) >= ABORT_GRACE_NS { + f.doomed = true; + true + } else { + false + } + } else { + false + }; + if aborted { + return Ok(Retirement::Aborted); } - return Ok(Retirement::Aborted); } Ok(Retirement::Pending) } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 81da0703496cb3..aa2cb8117d0848 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -48,8 +48,8 @@ pub(crate) struct QueueState { /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (MEDIUM 2, /// LOW 3; `file.rs` refuses HIGH and REALTIME). Smaller is served first. pub(crate) priority: u32, - /// Completed stage time of the DRM file that created this queue. - pub(crate) usage: Arc, + /// Completed stage time of the DRM file that created this queue (deduplicated per lane). + pub(crate) usage: Arc>>, /// USC executable window base. pub(crate) usc_base: u64, /// First cancelled accepted ordinal per engine; zero means none. Later scheduler @@ -164,6 +164,7 @@ impl Queue { return Err(EIO); } let credit = QueueCredit::acquire(&usage)?; + let usage = Arc::new(crate::usage::Lane::new(usage), GFP_KERNEL)?; let timeline = Timeline::new()?; let scheduler = Scheduler::new(&gpu.shared.dev)?; let state = Arc::new( 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 4809b1d85de46b..d766bcdbb9646a 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 @@ -421,6 +421,10 @@ fn main() { 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]); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9c8), 750); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9cc), 750); + assert_eq!(r32(object(&v25, &wire::V25G83, id::GLOBALS), 0x9cc), 800); + assert_eq!(r32(object(&v26, l, id::GLOBALS), 0x9d0), 800); std::fs::write(out.join("initdata-25g83.bin"), &v25).unwrap(); std::fs::write(out.join("initdata-26b123.bin"), &v26).unwrap(); render(&out); 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 03ab056cc5e465..bf002c5a597646 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs @@ -63,6 +63,14 @@ fn main() { expected[at..at+4].copy_from_slice(&value.to_le_bytes()); } }} + // Substitute calibrated DM2 compute watchdogs (40 -> 750, 50 -> 800) in the frozen C + // golden. + let globals: usize = initdata::OBJECT_SIZE[..initdata::id::GLOBALS].iter().sum(); + for (offset, old, new) in [(0x9c8usize, 40u32, 750u32), (0x9ccusize, 50u32, 800u32)] { + let wd = globals + offset; + assert_eq!(u32::from_le_bytes(expected[wd..wd+4].try_into().unwrap()), old); + expected[wd..wd+4].copy_from_slice(&new.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]); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 649995e70f6364..32e096a68a9ebf 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -6,6 +6,7 @@ import subprocess production = kernel_root() / 'drivers/gpu/drm/asahi/g16/poll.rs' +queue_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/queue.rs').read_text() event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() source = production.read_text() @@ -15,6 +16,12 @@ assert ( 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source ), 'aurora_g16_events must use new_percpu_reclaim(..., true)' +assert ( + 'pub(crate) usage: Arc>>' in queue_source +), 'QueueState::usage must deduplicate per-queue pipelined stages via usage::Lane' +assert ( + 'crate::usage::Lane::new(usage)' in queue_source +), 'Queue::new must wrap client usage in usage::Lane' def item(declaration, text=source): @@ -180,6 +187,7 @@ def item(declaration, text=source): evented: AtomicBool, publish_wake: AtomicBool, rearmed: Cell, + idle_power_polls: Cell, } impl Shared { fn new() -> Arc { @@ -188,12 +196,15 @@ def item(declaration, text=source): evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), rearmed: Cell::new(0), + idle_power_polls: Cell::new(0), }) } fn rearm(&self, _soon: bool) { self.rearmed.set(self.rearmed.get() + 1); } - fn arm_idle_power_poll(&self, _firmware: &Firmware) {} + fn arm_idle_power_poll(&self, _firmware: &Firmware) { + self.idle_power_polls.set(self.idle_power_polls.get() + 1); + } fn fail_stop(&self, _e: Error) {} __SUBMIT_LOCKED__ } @@ -201,12 +212,17 @@ def item(declaration, text=source): #[derive(Default)] struct Power { ramp: bool, + idle_reports: u32, } impl Power { fn needs_ramp(&self, _now: u64) -> bool { self.ramp } - fn report_work(&mut self, _in_flight: bool) {} + fn report_work(&mut self, in_flight: bool) { + if !in_flight { + self.idle_reports += 1; + } + } } #[derive(Default)] @@ -994,8 +1010,36 @@ def item(declaration, text=source): } } } + +#[path = "__USAGE_PATH__"] +mod usage; + +#[test] +fn per_queue_usage_lane_charges_distinct_stages_and_deduplicates_overlap() { + let client = Arc::new(usage::Client::new()); + let lane = usage::Lane::new(client.clone()); + const HZ: u32 = 24_000_000; + // Two pipelined renders whose TA and FS intervals overlap across flights. + lane.add(usage::Engine::Vertex, 24_000, 48_000, HZ); + lane.add(usage::Engine::Fragment, 40_000, 88_000, HZ); + lane.add(usage::Engine::Vertex, 36_000, 72_000, HZ); + lane.add(usage::Engine::Fragment, 64_000, 120_000, HZ); + lane.add(usage::Engine::Compute, 100_000, 124_000, HZ); + let [v_ns, f_ns, c_ns] = client.snapshot(); + // Vertex union: [24k, 72k] = 48k ticks = 2_000_000 ns (not 60k ticks = 2.5 ms). + assert_eq!(v_ns, 2_000_000); + // Fragment union: [40k, 120k] = 80k ticks = 3_333_333 ns (distinct from Vertex). + assert_eq!(f_ns, 3_333_333); + assert_ne!(v_ns, f_ns); + // Compute: [100k, 124k] = 24k ticks = 1_000_000 ns. + assert_eq!(c_ns, 1_000_000); +} ''' +harness = harness.replace( + '__USAGE_PATH__', str(kernel_root() / 'drivers/gpu/drm/asahi/usage.rs') +) + for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', '__POLL_STEP__': 'pub(crate) fn poll_step(', 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 a14f9c99371148..b909d40dffb1a8 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -1484,6 +1484,8 @@ def item(declaration): doomed: bool, recovery_suspect: bool, recovery_started_ns: u64, + gate_passed_ns: Option, + unsettled_polls: u32, } struct RecEngine { flights: Vec, ta_target: u32 } struct RecState { last_retired: recovery::logic::RetiredStamps } @@ -1513,6 +1515,8 @@ def item(declaration): doomed: false, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, }], ta_target: 0, }, @@ -1555,6 +1559,8 @@ def item(declaration): doomed: false, recovery_suspect: false, recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, }], ta_target: 0x300, }, 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 9124bf1eb8a98f..6098ef1a133d57 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -864,7 +864,7 @@ def module(text, name): c47.pass[0]=47;c47.pass_count=1;c47.pass_mask=1u64<<47; s.claim_pass_for(&arena,47,Some(a.id)).unwrap(); s.hold_vm(&c47,&a).unwrap(); - s.publish(&c47).unwrap(); + s.publish(&mut c47).unwrap(); // Clean same-VM reuse of displaced slot 0 does not need full work write. s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); assert!(!s.render_needs_full_work(0)); @@ -1314,13 +1314,13 @@ def module(text, name): // Prime and displace slot 0. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x1000,0x2000).unwrap(); render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); s.retire(&mut c1).unwrap(); // Hand staged scrub off via ScrubQueue; waiter is woken on completion and woke flag is set. @@ -1347,10 +1347,10 @@ def module(text, name): // the async scrub runs: it must clear scrubbing without marking clean, so next claim // performs a full scrub. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); assert!(q.push_batch(s.take_staged_scrubs())); assert!(s.scrubbing_active()); 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 26afcd4f09cedd..90ff43dcb2e8d6 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 @@ -26,7 +26,7 @@ def function(text, name): #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EINVAL:Error=Error(-22);const EAGAIN:Error=Error(-11);type Result = std::result::Result; #[path="__LOGIC__"]mod logic; -use logic::Retirement; +use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} @@ -47,7 +47,7 @@ def function(text, name): 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)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} struct Claims{slot:[u32;16],slot_count:u32,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],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,doomed:bool} +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,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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()}} @@ -58,7 +58,8 @@ def function(text, name): 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} +thread_local!{static CLOCK:Cell = const { Cell::new(100_000_000) };} +fn rmb(){}fn now_ns()->u64{CLOCK.with(|c| c.get())} 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)} @@ -76,7 +77,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,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, + 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;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, 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,completed:2},queue_passed:true, }; @@ -292,6 +293,41 @@ def function(text, name): assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); assert_eq!(fmix.graph.compute.fw_stamp.reads.get(),1); } +#[test]fn innocent_suspect_flight_does_not_false_abort_after_recovery_grace(){ + let mut f=firmware(true,15); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + // Long after recovery started (>20 ms), flight finishes its stage/queue gates while scene + // timestamps are briefly unsettled on the first poll. + CLOCK.with(|c| c.set(100_000_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,0); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].gate_passed_ns,Some(100_000_000)); + assert_eq!(f.engine.flights[0].unsettled_polls,1); + // Receipts settle before ABORT_GRACE_NS from gate_passed_ns -> full normal retirement. + CLOCK.with(|c| c.set(100_500_000)); + f.engine.flights[0].job.resources.passes[0].scene.set(0x628,103); + assert_eq!(f.retired(),Ok(Retirement::Full)); + assert!(!f.engine.flights[0].doomed); +} +#[test]fn truly_aborted_suspect_requires_two_polls_and_grace_from_gate_passed(){ + let mut f=firmware(false,22); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + f.engine.flights[0].job.resources.compute[0].its.set(8,0); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Second poll before ABORT_GRACE_NS stays pending. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS - 1)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + // Once both >=2 polls and >=ABORT_GRACE_NS elapsed from gate_passed_ns, abort and doom. + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS)); + assert_eq!(f.retired(),Ok(Retirement::Aborted)); + assert!(f.engine.flights[0].doomed); +} '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: From c2c00850e2455c2f38d0081c8a67c66551ba9ab1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 02:01:38 -0500 Subject: [PATCH 0852/1514] drm/asahi: g16: harden recovery history, PB/scheduler lifetimes and idle power Address adversarial review findings and idle power regressions across the pipelined G16 submission stack: - Replace single-entry last_retired with a 64-entry per-stage RetiredStamps ring recording every retired compute/TA/FS member so late recovery snapshots after pipelined bursts still resolve safely. - Use Firmware::compute_ticks() in publish_timestamps() so 26B123 work_ticks fallback works for client timestamp queries as well as stats. - Retain base RenderArena alongside PoolExtArena in PbOwnerArena::Ext so shared PB heap mappings outlive Cache::close() until displacement. - Track queued drm_sched jobs via Scheduler::pending_sched counter instead of per-push Arc allocations or retaining Arc, ensuring VmJobGuard drops immediately on completion. - Remove dead recovering check under Shared::state in try_submit_inline() and ensure retire_oldest() forgets failed-stop flights on every early return. - Extract Shared::arm_idle_power_poll() across all three idle-exit paths, call power.report_work(false) on drain, and gate syncobj_wait_hint on a G17-style 8-submit burst streak with 8 ms auto-expiry. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 8 +- drivers/gpu/drm/asahi/g16/job.rs | 49 ++++++------ drivers/gpu/drm/asahi/g16/mod.rs | 32 +++++--- drivers/gpu/drm/asahi/g16/poll.rs | 69 +++++++++------- drivers/gpu/drm/asahi/g16/recovery.rs | 6 +- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 79 ++++++++++++++----- drivers/gpu/drm/asahi/g16/resources.rs | 7 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 65 +++++++++++---- .../drivers/gpu/asahi-m4/test-poll-retire.py | 2 + .../drivers/gpu/asahi-m4/test-publication.py | 13 ++- .../drivers/gpu/asahi-m4/test-resources.py | 38 ++++----- .../gpu/asahi-m4/test-thermal-policy.py | 8 +- .../drivers/gpu/asahi-m4/test-timestamps.py | 70 +++++++++++++--- 13 files changed, 299 insertions(+), 147 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index ab93ae19480d10..cfdd218c71b42b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -706,13 +706,7 @@ impl Firmware { target: u32, stage: [u32; 3], ) -> Result { - if flags & 1 != 0 - && super::recovery::logic::last_retired_target( - &self.recovery.last_retired, - event, - target, - ) - { + if flags & 1 != 0 && self.recovery.last_retired.contains(event, target) { // A notification may follow the full receipt. It names the retained old // owner, not the next command that happens to occupy the flight list. return Ok(()); diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index ee954a1a9bdfd9..98dc58c951296c 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -596,9 +596,20 @@ 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, + /// Count of queued (unstarted) `drm_sched` jobs on this queue. Decremented once when + /// `run()`, `cancel()`, or `drop()` completes so inline submission preserves queue order + /// without retaining `Arc` in [`Scheduler`]. + pending_sched: Arc, + counted: bool, +} + +impl SchedJob { + fn finish_pending(&mut self) { + if self.counted { + self.counted = false; + self.pending_sched.fetch_sub(1, Ordering::AcqRel); + } + } } impl sched::JobImpl for SchedJob { @@ -612,7 +623,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); + job.finish_pending(); Ok(Some(fence)) } @@ -623,7 +634,7 @@ impl sched::JobImpl for SchedJob { fn cancel(job: &mut Self) { job.job.cancel_unstarted(); - job.scheduled.store(true, Ordering::Release); + job.finish_pending(); } } @@ -631,7 +642,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); + self.finish_pending(); } } @@ -641,10 +652,10 @@ pub(crate) struct Scheduler { // drains), and only then the scheduler is finalized. entity: sched::Entity, _scheduler: sched::Scheduler, - /// 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>, + /// Number of jobs currently queued in `drm_sched` that have not yet started or cancelled. + /// Inline submit is permitted only when zero, preserving strict queue order without + /// retaining any `Arc` (or its `VmJobGuard` / prepared arenas). + pending_sched: Arc, } impl Scheduler { @@ -667,10 +678,11 @@ impl Scheduler { )?; // With one run queue, only the kernel priority is valid. let entity = sched::Entity::new(&scheduler, sched::Priority::Kernel)?; + let pending_sched = Arc::new(core::sync::atomic::AtomicUsize::new(0), GFP_KERNEL)?; Ok(Self { entity, _scheduler: scheduler, - last_scheduled: None, + pending_sched, }) } @@ -680,14 +692,7 @@ impl Scheduler { /// 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 = match &self.last_scheduled { - Some(done) if done.load(Ordering::Acquire) => { - self.last_scheduled = None; - true - } - Some(_) => false, - None => true, - }; + let prev_started = self.pending_sched.load(Ordering::Acquire) == 0; let handle = job.clone(); if prev_started { handle.accepted.store(true, Ordering::Release); @@ -696,13 +701,14 @@ impl Scheduler { } handle.accepted.store(false, Ordering::Release); } - let scheduled = Arc::new(AtomicBool::new(false), GFP_KERNEL)?; + self.pending_sched.fetch_add(1, Ordering::AcqRel); let mut pending = self.entity.new_job( 1, SchedJob { job, shared, - scheduled: scheduled.clone(), + pending_sched: self.pending_sched.clone(), + counted: true, }, )?; for fence in handle.inputs.iter() { @@ -710,7 +716,6 @@ impl Scheduler { } let armed = pending.arm(); handle.accepted.store(true, Ordering::Release); - self.last_scheduled = Some(scheduled); armed.push(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 527488b4a2a267..024acf667f1ac4 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -194,7 +194,9 @@ 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; +const WAIT_HINT_GAP_NS: u64 = 4_000_000; +const WAIT_HINT_STREAK_ON: u32 = 8; +const WAIT_HINT_LINGER_NS: u64 = 8_000_000; /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] @@ -214,8 +216,10 @@ pub(crate) struct Shared { 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, + /// Consecutive back-to-back submits within [`WAIT_HINT_GAP_NS`]. + pub(crate) wait_hint_streak: AtomicU32, + /// Monotonic deadline (ns) until which `syncobj_wait_hint` stays active (0 when expired). + pub(crate) wait_hint_until_ns: AtomicU64, /// 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). @@ -302,15 +306,24 @@ impl Shared { .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, - ); + if prev != 0 && now.wrapping_sub(prev) <= WAIT_HINT_GAP_NS { + let streak = self + .wait_hint_streak + .fetch_add(1, Ordering::Relaxed) + .saturating_add(1); + if streak >= WAIT_HINT_STREAK_ON { + self.wait_hint_until_ns + .store(now.saturating_add(WAIT_HINT_LINGER_NS), Ordering::Relaxed); + } + } else { + self.wait_hint_streak.store(1, 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) { + let until = self.wait_hint_until_ns.load(Ordering::Relaxed); + if cfg!(CONFIG_UCLAMP_TASK) && until != 0 && engine::now_ns() <= until { Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) } else { None @@ -470,7 +483,8 @@ impl Gpu { evented: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), last_submit_ns: AtomicU64::new(0), - wait_hint_active: AtomicBool::new(false), + wait_hint_streak: AtomicU32::new(0), + wait_hint_until_ns: AtomicU64::new(0), resnap_deadline_ns: AtomicU64::new(0), backup_deadline_ns: AtomicU64::new(0), error: AtomicI32::new(0), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 7507c986ffccf4..f00ee3ab3fbe1a 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -76,6 +76,22 @@ fn stats_show(shared: &Arc, f: &mut fmt::Formatter<'_>) -> fmt::Result { } impl Shared { + /// Schedules a delayed poll while idle so DVFS utilization decays to S1 and a held CLPC + /// memory/fabric floor expires cleanly after all flights drain. + fn arm_idle_power_poll(self: &Arc, firmware: &Firmware) { + if firmware.recovery.failed().is_some() { + return; + } + let delay_ns = if firmware.power.clpc_holding() { + super::power::policy::CLPC_IDLE_HOLD_NS + } else if firmware.power.utilization.decaying() { + super::power::policy::WINDOW_NS + } else { + return; + }; + self.mod_poll(kernel::time::msecs_to_jiffies((delay_ns / 1_000_000) as u32).max(1)); + } + /// One poll pass (the poll work item). pub(crate) fn run_poll(self: Arc) { // The domain may be off. The sleep's end queues a pass. @@ -117,31 +133,12 @@ impl Shared { 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) - if firmware.recovery.failed().is_none() - && firmware.power.utilization.decaying() => - { - self.mod_poll(kernel::time::msecs_to_jiffies( - (if firmware.power.clpc_holding() { - super::power::policy::CLPC_IDLE_HOLD_NS - } else { - super::power::policy::WINDOW_NS - } / 1_000_000) as u32, - )); - self.cancel_resnap(); - } - Ok(false) - if firmware.recovery.failed().is_none() - && firmware.power.clpc_holding() => - { - self.mod_poll(kernel::time::msecs_to_jiffies( - (super::power::policy::CLPC_IDLE_HOLD_NS / 1_000_000) as u32, - )); + // Idle: arm a delayed poll while DVFS utilization is decaying or a CLPC + // floor hold is still pending so both expire cleanly to idle power. + Ok(false) => { + self.arm_idle_power_poll(firmware); self.cancel_resnap(); } - Ok(false) => self.cancel_resnap(), Err(error) => { self.cancel_resnap(); firmware.fail_stop(error, &mut done); @@ -178,6 +175,8 @@ impl Shared { self.fail_stop(error); } else if firmware.recovery.needs_repoll() || firmware.engine.frozen { self.rearm(false); + } else if firmware.engine.flights.is_empty() { + self.arm_idle_power_poll(firmware); } } } @@ -256,6 +255,9 @@ impl Shared { } if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { self.rearm(firmware.engine.chan_wait); + } else { + firmware.power.report_work(false); + self.arm_idle_power_poll(firmware); } } accepted @@ -296,7 +298,7 @@ impl Shared { let mut scrubs = super::slots::ScrubBatch::new(); let accepted = { let mut state = self.state.lock(); - if self.sleeping.load(Ordering::Acquire) || self.recovering.load(Ordering::Acquire) { + if self.sleeping.load(Ordering::Acquire) { return None; } match state.as_deref_mut() { @@ -1101,12 +1103,14 @@ impl Firmware { core::mem::forget(f); return; } - if f.computes != 0 { - self.recovery.last_retired[0] = Some(f.target); + for &stamp in &f.cstamp[..(f.computes as usize).min(f.cstamp.len())] { + self.recovery.last_retired.push(0, stamp); } if f.renders != 0 { - self.recovery.last_retired[1] = Some(f.ta_target); - self.recovery.last_retired[2] = Some(f.fs_target); + for m in 0..(f.renders as usize).min(f.r_ta_stamp.len()) { + self.recovery.last_retired.push(1, f.r_ta_stamp[m]); + self.recovery.last_retired.push(2, f.r_fs_stamp[m]); + } let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { self.pools.retire_flight( f.pb_slot as usize, @@ -1205,6 +1209,7 @@ impl Firmware { complete(done, j3, Err(error)); } self.fail_stop(error, done); + core::mem::forget(f); return; } } @@ -1217,6 +1222,7 @@ impl Firmware { // Drained: a gap until the next publication. self.engine.stats.idle_from_ns = now_ns(); self.power.utilization.idle(self.engine.stats.idle_from_ns); + self.power.report_work(false); } // The next prefix on the retired flight's class(es) starts executing about now. if f.renders != 0 { @@ -1294,6 +1300,7 @@ impl Firmware { self.retain(j2); complete(done, j2, Err(proof_error)); self.fail_stop(proof_error, done); + core::mem::forget(f); return; } } @@ -1380,7 +1387,8 @@ impl Firmware { let index = *slots.get(compute).ok_or(EINVAL)? as usize; if !command.timestamp_outputs.is_empty() { let unit = flight.job.resources.compute_unit(index)?; - let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; + let (start, end) = self.compute_ticks(unit)?; + let ticks = [start, end, 0, 0]; command .timestamp_outputs .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); @@ -1412,7 +1420,8 @@ impl Firmware { let index = *slots.get(compute).ok_or(EINVAL)? as usize; if !command.timestamp_outputs.is_empty() { let unit = flight.job.resources.compute_unit(index)?; - let ticks = [unit.its.r64(0)?, unit.its.r64(8)?, 0, 0]; + let (start, end) = self.compute_ticks(unit)?; + let ticks = [start, end, 0, 0]; command .timestamp_outputs .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index f8b5c9bd568567..a72e4b9c7819f5 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -57,8 +57,8 @@ pub(crate) struct Recovery { warning_deadline_ns: [u64; 2], pub(crate) long_commands: u64, pub(crate) publication_wait_deadline: Option, - /// Last fully retired compute/TA/FS identity, for late recovery snapshots. - pub(crate) last_retired: [Option; 3], + /// Recently retired compute/TA/FS stamps, for late recovery snapshots. + pub(crate) last_retired: logic::RetiredStamps, /// Queue engine order: render, compute. A quarantined/exhausted class stays offline. pub(crate) unavailable: [Option; 2], pub(crate) errors_seen: u32, @@ -84,7 +84,7 @@ impl Recovery { warning_deadline_ns: [u64::MAX; 2], long_commands: 0, publication_wait_deadline: None, - last_retired: [None; 3], + last_retired: logic::RetiredStamps::new(), unavailable: [None; 2], errors_seen: 0, statistics_seen: 0, diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index 5a7aca6dd0ab2f..a8eeb00b9591d0 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -123,15 +123,50 @@ impl SnapshotEntry { } } -/// A late snapshot can name the last complete receipt even after its flight was removed. -pub(crate) fn last_retired_target(last: &[Option; 3], event: u32, target: u32) -> bool { - let index = match event { - 15 => 0, - 0x70 => 1, - 0x71 => 2, - _ => return false, - }; - last[index] == Some(target) +/// Bounded per-stage history of recently retired firmware stamps. +pub(crate) const RETIRED_STAMPS_CAP: usize = 64; + +/// Bounded per-stage ring of recently retired compute/TA/FS firmware stamps so a late +/// recovery snapshot arriving after pipelined retirement resolves any recently retired +/// member, not only the single newest flight. +#[derive(Clone, Debug)] +pub(crate) struct RetiredStamps { + stamps: [[u32; RETIRED_STAMPS_CAP]; 3], + len: [u8; 3], + next: [u8; 3], +} + +impl RetiredStamps { + pub(crate) const fn new() -> Self { + Self { + stamps: [[0; RETIRED_STAMPS_CAP]; 3], + len: [0; 3], + next: [0; 3], + } + } + + pub(crate) fn push(&mut self, stage: usize, target: u32) { + if stage >= 3 { + return; + } + let idx = self.next[stage] as usize; + self.stamps[stage][idx] = target; + self.next[stage] = ((idx + 1) % RETIRED_STAMPS_CAP) as u8; + if (self.len[stage] as usize) < RETIRED_STAMPS_CAP { + self.len[stage] += 1; + } + } + + pub(crate) fn contains(&self, event: u32, target: u32) -> bool { + let stage = match event { + 15 => 0, + 0x70 => 1, + 0x71 => 2, + _ => return false, + }; + let len = self.len[stage] as usize; + self.stamps[stage][..len].contains(&target) + } } pub(crate) const fn expired(now: u64, deadline: u64) -> bool { @@ -176,17 +211,25 @@ mod tests { #[test] fn late_snapshot_requires_exact_stage_target_and_real_full_receipt() { - assert!(!last_retired_target(&[None; 3], 0x70, 0)); - let last = [Some(0x100), Some(0), Some(0x200)]; + let mut retired = RetiredStamps::new(); + assert!(!retired.contains(0x70, 0)); + retired.push(0, 0x100); + retired.push(1, 0); + retired.push(2, 0x200); for (event, target) in [(15, 0x100), (0x70, 0), (0x71, 0x200)] { - assert!(last_retired_target(&last, event, target)); - assert!(!last_retired_target( - &last, - event, - target.wrapping_add(0x100) - )); + assert!(retired.contains(event, target)); + assert!(!retired.contains(event, target.wrapping_add(0x100))); + } + assert!(!retired.contains(0x72, 0)); + // Pipelined bursts retain all recent stamps up to RETIRED_STAMPS_CAP and evict oldest. + let mut ring = RetiredStamps::new(); + for i in 0..(RETIRED_STAMPS_CAP as u32 + 4) { + ring.push(0, (i + 1) << 8); } - assert!(!last_retired_target(&last, 0x72, 0)); + assert!(!ring.contains(15, 0x100)); + assert!(!ring.contains(15, 0x400)); + assert!(ring.contains(15, 0x500)); + assert!(ring.contains(15, (RETIRED_STAMPS_CAP as u32 + 4) << 8)); } #[test] diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index a24050a97e9485..0f12d12b373eb1 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -296,7 +296,7 @@ impl PoolExtArena { #[allow(dead_code)] pub(crate) enum PbOwnerArena { Base(Arc), - Ext(Arc), + Ext(Arc, Arc), } /// Keeps the arena owning a retained pass slot alive through displacement. @@ -826,13 +826,14 @@ impl Prepared { } /// The arena owning PB/UMA allocator slot `k`. pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { + let base = self.render.as_ref()?; if k < BASE_PB_SLOTS { - self.render.as_ref().map(|r| PbOwnerArena::Base(r.clone())) + Some(PbOwnerArena::Base(base.clone())) } else { self.pb_ext .get(k - BASE_PB_SLOTS) .and_then(|slot| slot.as_ref()) - .map(|ext| PbOwnerArena::Ext(ext.clone())) + .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone())) } } /// Render pass slots this job can use. 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 1cee63b7c52a17..a178d24d2288dd 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 @@ -120,32 +120,58 @@ def function(text, name): impl Job { METHODS } -struct SchedJob { job:Arc, shared:Arc } -struct ArmedJob { job:SchedJob, pushed:Arc>> } +struct SchedJob { job:Arc, shared:Arc, pending_sched:Arc, counted:bool } +impl SchedJob { + fn finish_pending(&mut self) { + if self.counted { + self.counted = false; + self.pending_sched.fetch_sub(1, Ordering::AcqRel); + } + } + fn run(&mut self) { + self.job.start(&self.shared); + self.finish_pending(); + } +} +impl Drop for SchedJob { + fn drop(&mut self) { + self.finish_pending(); + } +} +struct ArmedJob { job:SchedJob, pushed:Arc>>, queue:Arc>> } impl ArmedJob { - fn push(self) { self.pushed.lock().unwrap().push(self.job.job.id); } + fn push(self) { + self.pushed.lock().unwrap().push(self.job.job.id); + self.queue.lock().unwrap().push(self.job); + } } -struct PendingJob { job:SchedJob, deps:Vec, pushed:Arc>>, fail_dep:bool } +struct PendingJob { job:SchedJob, deps:Vec, pushed:Arc>>, queue:Arc>>, fail_dep:bool } impl PendingJob { fn add_dependency(&mut self, fence:InputFence)->Result { if self.fail_dep { return Err(ENOMEM); } self.deps.push(fence); Ok(()) } - fn arm(self)->ArmedJob { ArmedJob { job:self.job, pushed:self.pushed } } + fn arm(self)->ArmedJob { ArmedJob { job:self.job, pushed:self.pushed, queue:self.queue } } } -struct Entity { new_jobs:AtomicUsize, pushed:Arc>>, fail_new:bool, fail_dep:bool } +struct Entity { new_jobs:AtomicUsize, pushed:Arc>>, queue:Arc>>, fail_new:bool, fail_dep:bool } impl Entity { - fn new()->Self { Self { new_jobs:AtomicUsize::new(0), pushed:Arc::new(Mutex::new(vec![])), fail_new:false, fail_dep:false } } + fn new()->Self { Self { new_jobs:AtomicUsize::new(0), pushed:Arc::new(Mutex::new(vec![])), queue:Arc::new(Mutex::new(vec![])), fail_new:false, fail_dep:false } } fn new_job(&mut self, _credits:u32, job:SchedJob)->Result { self.new_jobs.fetch_add(1, Ordering::AcqRel); if self.fail_new { return Err(ENOMEM); } - Ok(PendingJob { job, deps:vec![], pushed:self.pushed.clone(), fail_dep:self.fail_dep }) + Ok(PendingJob { job, deps:vec![], pushed:self.pushed.clone(), queue:self.queue.clone(), fail_dep:self.fail_dep }) + } + fn drain_run(&self) { + let mut jobs = core::mem::take(&mut *self.queue.lock().unwrap()); + for mut job in jobs.drain(..) { + job.run(); + } } } -struct Scheduler { entity:Entity, last_job:Option> } +struct Scheduler { entity:Entity, pending_sched:Arc } impl Scheduler { - fn new()->Self { Self { entity:Entity::new(), last_job:None } } + fn new()->Self { Self { entity:Entity::new(), pending_sched:Arc::new(AtomicUsize::new(0)) } } PUSH_METHOD } fn job(id:u64,status:Arc)->Arc { @@ -486,7 +512,8 @@ def function(text, name): assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),0); assert_eq!(*shared.submitted.lock().unwrap(),vec![1,2]); // Unsignalled input falls back to drm_sched; subsequent job waits for predecessor start. - let j3=job_with_inputs(3,status.clone(),vec![InputFence::new(0)]); + let f3=InputFence::new(0); + let j3=job_with_inputs(3,status.clone(),vec![f3.clone()]); sched.push(j3.clone(),shared.clone()).unwrap(); assert!(!j3.is_started()); assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),1); @@ -496,15 +523,25 @@ def function(text, name): assert!(!j4.is_started()); assert_eq!(sched.entity.new_jobs.load(Ordering::Acquire),2); assert_eq!(*sched.entity.pushed.lock().unwrap(),vec![3,4]); - // Fallback ENOMEM rolls back accepted so the failed push never poisons queue ordinals. - j3.started.store(true,Ordering::Release); - j4.started.store(true,Ordering::Release); + // Fallback ENOMEM rolls back accepted and pending_sched without poisoning queue ordering. + f3.signal(1); + sched.entity.drain_run(); + assert_eq!(sched.pending_sched.load(Ordering::Acquire),0); sched.entity.fail_new=true; let j5=job_with_inputs(5,status.clone(),vec![InputFence::new(0)]); j5.accepted.store(false,Ordering::Release); assert_eq!(sched.push(j5.clone(),shared.clone()),Err(ENOMEM)); assert!(!j5.accepted.load(Ordering::Acquire)); assert!(!j5.is_started()); + assert_eq!(sched.pending_sched.load(Ordering::Acquire),0); + // Scheduler retains zero Arc references after inline or drm_sched completion. + let w1=Arc::downgrade(&j1); + let w3=Arc::downgrade(&j3); + let w4=Arc::downgrade(&j4); + drop((j1,j2,j3,j4,j5)); + assert!(w1.upgrade().is_none(), "inline job must not be retained by Scheduler"); + assert!(w3.upgrade().is_none(), "drm_sched job must not be retained by Scheduler after run"); + assert!(w4.upgrade().is_none(), "queued job must not be retained by Scheduler after run"); } '''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::')).replace('PUSH_METHOD', push_method) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 4a381034c3caa4..38a0e6112d8b00 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -183,6 +183,7 @@ def item(declaration): fn rearm(&self, _soon: bool) { self.rearmed.set(self.rearmed.get() + 1); } + fn arm_idle_power_poll(&self, _firmware: &Firmware) {} fn fail_stop(&self, _e: Error) {} __SUBMIT_LOCKED__ } @@ -195,6 +196,7 @@ def item(declaration): fn needs_ramp(&self, _now: u64) -> bool { self.ramp } + fn report_work(&mut self, _in_flight: bool) {} } struct Firmware { 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 9ba9f6cb7f265b..9dd42f19a2c50a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -1181,11 +1181,8 @@ def item(declaration): } mod recovery { - pub mod logic { - pub fn last_retired_target(last: &[Option; 3], event: u32, target: u32) -> bool { - let idx = match event { 15 => 0, 0x70 => 1, 0x71 => 2, _ => return false }; - last[idx] == Some(target) - } + pub(crate) mod logic { + pub(crate) use crate::recovery::logic::RetiredStamps; } } mod poll { @@ -1230,7 +1227,7 @@ def item(declaration): recovery_started_ns: u64, } struct RecEngine { flights: Vec, ta_target: u32 } - struct RecState { last_retired: [Option; 3] } + struct RecState { last_retired: recovery::logic::RetiredStamps } struct RecFirmware { engine: RecEngine, recovery: RecState } impl RecFirmware { __RECOVERY_PREPARE__ @@ -1260,7 +1257,7 @@ def item(declaration): }], ta_target: 0, }, - recovery: RecState { last_retired: [None; 3] }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; assert_eq!(fw.recovery_prepare(1, 15, 0x200, [0, 0, 0x100]), Ok(())); assert!(fw.engine.flights[0].doomed); @@ -1302,7 +1299,7 @@ def item(declaration): }], ta_target: 0x300, }, - recovery: RecState { last_retired: [None; 3] }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; // Pass 0 TA finished (stage[0] == 0x100); interior TA target 0x200 matches and cleans // TPC only for unfinished passes 1 and 2. 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 1fb10b463554d9..9806d05718bf26 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -153,7 +153,7 @@ def module(text, name): pub enum PassOwnerArena{Base(crate::sync::Arc)} pub struct PoolExtArena; #[derive(Clone)] - pub enum PbOwnerArena{Base(crate::sync::Arc),Ext(crate::sync::Arc)} + pub enum PbOwnerArena{Base(crate::sync::Arc),Ext(crate::sync::Arc,crate::sync::Arc)} impl PassOwnerArena{ pub fn pass_and_tilemap_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,&AtomicU64)>{ match self{Self::Base(a)=>Some((a.passes.get(k)?,a.tilemap_dirty.get(k)?))} @@ -857,7 +857,7 @@ def module(text, name): // Publish and retire slot 0: not displaced yet, so nothing is staged. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; s.claim_pass_in(&prep,0,Some(a.id),0x4000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x2000,0x4000).unwrap(); render.passes[0].tilemap.fill(0,0xab,0x4000).unwrap(); render.passes[0].its.fill(0,0xcd,32).unwrap(); @@ -868,7 +868,7 @@ def module(text, name): // Publish and retire slot 1: displaces slot 0, staging slot 0 for off-lock scrub. let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); assert!(s.scrubbing_active()); @@ -900,13 +900,13 @@ def module(text, name): // Prime and displace slot 0. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x1000,0x2000).unwrap(); render.passes[0].tilemap.fill(0,0x55,0x2000).unwrap(); s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); s.retire(&mut c1).unwrap(); // Dropped batch clears scrubbing bit without marking clean. s.stage_displaced_pass_scrubs(); @@ -924,20 +924,20 @@ def module(text, name): assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&b|b==0)); // Cancel, re-displace, pre-scrub clean, then invalidate_scrub() or cross-VM forces full scrub. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); let _=s.take_staged_scrubs().run(); s.invalidate_scrub(); s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); assert!(s.render_needs_full_work(0)); let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); let _=s.take_staged_scrubs().run(); s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); @@ -952,14 +952,14 @@ def module(text, name): // Prime slot 0, then displace it by retiring slot 1; record retirement without staging yet. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x1000,0x2000).unwrap(); render.passes[0].tilemap.fill(0,0x77,0x2000).unwrap(); s.retire(&mut c0).unwrap(); s.note_render_retired(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); s.retire(&mut c1).unwrap(); s.note_render_retired(); // Immediate publication in the same lock hold sees slot 0 available and NOT scrubbing. @@ -1003,7 +1003,7 @@ def module(text, name): assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),(hw::sizes::COMPUTE_UNITS-4) as u32); s.hold_vm(&claims,&a).unwrap(); s.hold_arenas(&claims,&prep); - s.publish(&claims).unwrap(); + s.publish(&mut claims).unwrap(); assert_eq!(s.compute_published(),4); s.retire(&mut claims).unwrap(); assert_eq!(s.compute_published(),0); @@ -1053,7 +1053,7 @@ def module(text, name): s.hold_vm(&c,&a).unwrap(); s.hold_arenas(&c,&prep); - s.publish(&c).unwrap(); + s.publish(&mut c).unwrap(); assert_eq!(s.render_published(),3); s.retire(&mut c).unwrap(); assert_eq!(s.render_published(),0); @@ -1135,9 +1135,9 @@ def module(text, name): // unit 0 is now retired-undisplaced and unit 1 is quarantined -> base [0..2] exhausted. let mut c=Claims::new(); assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(0)); - s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(a.id)).unwrap(),Some(1)); - s.hold_vm(&c,&a).unwrap();s.publish(&c).unwrap();s.quarantine(&mut c); + s.hold_vm(&c,&a).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); assert!(s.base_compute_quarantined()); assert!(s.compute_exhausted_within(2)); assert!(!s.compute_exhausted_within(4)); @@ -1148,7 +1148,7 @@ def module(text, name): assert!(should_expand_compute_ext(&mut last,&mut burst,10_000_000,1,s.base_compute_quarantined())); // Expanded fresh VM claims unit 2, retires cleanly, and displaces base unit 0 back to reusable. assert_eq!(s.claim_compute_for(&prep_full,&mut c,Some(b.id)).unwrap(),Some(2)); - s.hold_vm(&c,&b).unwrap();s.publish(&c).unwrap();s.retire(&mut c).unwrap(); + s.hold_vm(&c,&b).unwrap();s.publish(&mut c).unwrap();s.retire(&mut c).unwrap(); assert!(!s.compute_exhausted_within(2)); assert!(s.compute_available(2)); // A base-only (2-unit) VM can now claim displaced base unit 0 again. @@ -1179,10 +1179,10 @@ def module(text, name): // Retire base pass slot 0, then hang and quarantine base pass slot 1 -> base [0..2] exhausted. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_count=1;c0.pass_mask=1<<0; s.claim_pass_in(&prep,0,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_count=1;c1.pass_mask=1<<1; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.publish(&c1).unwrap();s.quarantine(&mut c1); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap();s.quarantine(&mut c1); assert!(s.base_render_quarantined()); assert!(s.render_exhausted_within(2)); assert!(!s.render_exhausted_within(4)); @@ -1194,7 +1194,7 @@ def module(text, name): assert_eq!(k,2); let mut c2=Claims::new();c2.pass[0]=k as u32;c2.pass_count=1;c2.pass_mask=1<\n' - ' {\n self.mod_poll('), - ('poll.rs', '&& firmware.power.clpc_holding() =>'), + ('poll.rs', 'fn arm_idle_power_poll(self: &Arc, firmware: &Firmware)'), + ('poll.rs', 'if firmware.power.clpc_holding() {'), + ('poll.rs', 'else if firmware.power.utilization.decaying() {'), ('power.rs', 'if idle && self.power.clpc_hold.expire(now) {'), ('recovery.rs', 'self.power.release_clpc_now();'), ('sleep.rs', 'firmware.power.release_clpc_now();'), ]: assert (G16/path).read_text().count(call) == 1, (path, call) +assert (G16/'poll.rs').read_text().count('self.arm_idle_power_poll(firmware);') == 3 print('Governor connected at publication, drain, power service and idle re-arm') print(json.dumps(report,indent=2)) 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 e72860d955fff4..c765d42b1dca50 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -29,6 +29,8 @@ def function(source, marker): checked_offset = function(shared, 'fn checked_offset(') publish = function(shared, 'pub(crate) fn publish(&self, ticks: [u64; 4], frequency_hz: u64)') retire = function(poll, 'fn publish_timestamps(&self, flight: &Flight, claims: &super::slots::Claims)') +compute_ticks = function(poll, 'fn compute_ticks(&self, unit: &super::slots::ComputeSlot)') +compute_ticks_with = function(poll, 'fn compute_ticks_with(') source = r''' #![allow(dead_code)] use core::sync::atomic::{AtomicU8, AtomicU64, Ordering, fence as barrier}; @@ -148,29 +150,55 @@ def function(source, marker): mod backend { use super::*; pub mod hw{pub const COMMAND_TIMESTAMP_HZ:u64=24_000_000;} - pub mod slots{pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;2]}} + pub mod slots{ + use super::*; + pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;2]} + pub type ComputeSlot = Compute; + } pub mod command{ use super::*; pub struct Compute{pub timestamp_outputs:Destinations} pub struct Render{pub timestamp_outputs:Destinations} pub enum Command{Compute(Compute),Render(Render)} } - pub struct Cells(pub [u64;4]);impl Cells{pub fn r64(&self,offset:usize)->Result{ - match offset{0=>Ok(self.0[0]),8=>Ok(self.0[1]),0x600=>Ok(self.0[0]),0x608=>Ok(self.0[1]),0x620=>Ok(self.0[2]),0x628=>Ok(self.0[3]),_=>Err(EINVAL)} - }} - pub struct Compute{pub its:Cells}pub struct Pass{pub scene:Cells} + pub struct Cells(pub [u64;4]);impl Cells{ + pub fn r64(&self,offset:usize)->Result{ + match offset{0=>Ok(self.0[0]),8=>Ok(self.0[1]),0x600=>Ok(self.0[0]),0x608=>Ok(self.0[1]),0x620=>Ok(self.0[2]),0x628=>Ok(self.0[3]),_=>Err(EINVAL)} + } + pub fn r32(&self,offset:usize)->Result{ + let v=match offset{0x100=>self.0[0],0x104=>self.0[0]>>32,0x108=>self.0[1],0x10c=>self.0[1]>>32,_=>return Err(EINVAL)}; + Ok(v as u32) + } + } + pub struct Compute{pub its:Cells,pub work:Cells}pub struct Pass{pub scene:Cells} + pub struct ComputeAbi{pub work_ticks:Option<(usize,usize)>} + pub struct Abi{pub compute:ComputeAbi} + impl Abi{pub fn compute(&self)->&ComputeAbi{&self.compute}} + pub struct Init{pub abi:Abi} pub struct Scrub{pub compute:Vec,pub passes:Vec} - pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots} + pub struct Slots{pub scrub:Scrub}pub struct Firmware{pub slots:Slots,pub init:Init} 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)}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 group:Vec,pub first:usize,pub count:usize,pub renders:u32} - pub mod poll{use super::*;impl Firmware{ __RETIRE__ }} + pub mod poll{ + use super::*; + const EIO:i32=-5; + impl Firmware{ + __COMPUTE_TICKS__ + __COMPUTE_TICKS_WITH__ + __RETIRE__ + } + } } use backend::*; -fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}}}} +fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}},init:Init{abi:Abi{compute:ComputeAbi{work_ticks:None}}}}} fn resources()->Resources{Resources{ - compute:vec![Compute{its:Cells([10,20,0,0])},Compute{its:Cells([30,40,0,0])},Compute{its:Cells([50,60,0,0])}], + compute:vec![ + Compute{its:Cells([10,20,0,0]),work:Cells([0,0,0,0])}, + Compute{its:Cells([30,40,0,0]),work:Cells([0,0,0,0])}, + Compute{its:Cells([50,60,0,0]),work:Cells([0,0,0,0])}, + ], passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ @@ -224,7 +252,29 @@ def function(source, marker): let claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); } -'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) +#[test]fn work_ticks_fallback_publishes_compute_timestamps_for_26b123(){ + let c0=backing();let c1=backing(); + let mut fw=firmware(); + fw.init.abi.compute.work_ticks=Some((0x100,0x108)); + let res=Resources{ + compute:vec![ + Compute{its:Cells([0,0,0,0]),work:Cells([0x1_0000_0070,0x1_0000_0090,0,0])}, + Compute{its:Cells([0,0,0,0]),work:Cells([0x2_0000_0010,0x2_0000_0040,0,0])}, + ], + passes:vec![], + }; + let flight=Flight{ + job:Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c0)})],resources:res}, + group:vec![Job{commands:vec![command::Command::Compute(command::Compute{timestamp_outputs:outputs(&c1)})],resources:Resources{compute:vec![],passes:vec![]}}], + first:0,count:1,renders:0, + }; + let mut slot=[0u8;16];slot[0]=0;slot[1]=1; + let claims=slots::Claims{slot,slot_count:2,pass:[0,0]}; + fw.publish_timestamps(&flight,&claims).unwrap(); + assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); + assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); +} +'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) path = out / 'timestamps-host.rs' path.write_text(source) subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'timestamps-host')], check=True) From 6bc1ca4a9a7b3c608c4ed74ade9ada5c30069627 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 02:06:05 -0500 Subject: [PATCH 0853/1514] selftests: asahi-g15: add lifetime parameter to mocked VmReadGuard Match the VmReadGuard<'a> lifetime introduced when switching VM_BIND gate reads to the VM reservation lock so asahi-g15/run.py builds and passes all host tests. Signed-off-by: Diljit Singh --- tools/testing/selftests/drivers/gpu/asahi-g15/run.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py index b0c3105235f7b8..571ad60f59e707 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py @@ -114,7 +114,7 @@ pub const UAT_PGSZ: usize = 0x4000; pub const UAT_PGMSK: usize = UAT_PGSZ - 1; pub struct Vm(pub Vec); - pub type VmReadGuard = Vm; + pub type VmReadGuard<'a> = Vm; impl Vm { pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { let start = usize::try_from(va).map_err(|_| EFAULT)?; @@ -134,7 +134,7 @@ /// cover() calls: the page checks the walk made. pub static COVERS: Cell = Cell::new(0); } - pub fn cover(vm: &mut mmu::VmReadGuard, start: u64, end: u64, _: bool, _: bool) -> Result { + pub fn cover(vm: &mut mmu::VmReadGuard<'_>, start: u64, end: u64, _: bool, _: bool) -> Result { COVERS.with(|c| c.set(c.get() + 1)); if start >= SYNTHETIC { return Ok(()); From d1f88bb1eab6e269a0a35eb2a9d1ec7910fb4787 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:41:58 -0500 Subject: [PATCH 0854/1514] drm/asahi: g16: deduplicate fdinfo per DRM file and accept equal timestamps With sibling kernel queues sharing one DRM file (such as Borealis's per-VkQueue sibling queues across multiple flights or dual CDM pipes), usage::Lane only deduplicated intervals per queue, allowing concurrent sibling queues on the same DRM file to exceed 100% of wall time in drm-engine-*. Add Client::add_union() backed by a per-engine atomic watermark on usage::Client (sharing union_mark() with Lane::add() and preserving existing Client::add() and Lane::add() semantics for other backends). Have G16 QueueState hold Arc directly and charge retired stages via Client::add_union() so overlapping intervals on the same DRM file union cleanly to <= 100% of wall time while keeping distinct files isolated. Also accept end >= start (with start != 0) on 24 MHz (41.67 ns) compute ITS and render TA/FS stage timestamps so sub-tick draws or dispatches retire cleanly instead of remaining pending while still rejecting zero or reversed intervals. Signed-off-by: Diljit Singh --- Documentation/gpu/asahi-usage-stats.rst | 11 ++- drivers/gpu/drm/asahi/g16/poll.rs | 10 +-- drivers/gpu/drm/asahi/g16/queue.rs | 5 +- drivers/gpu/drm/asahi/usage.rs | 83 ++++++++++++++----- .../drivers/gpu/asahi-m4/test-poll-retire.py | 27 +++--- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 30 +++++++ 6 files changed, 122 insertions(+), 44 deletions(-) diff --git a/Documentation/gpu/asahi-usage-stats.rst b/Documentation/gpu/asahi-usage-stats.rst index c2cda44ce1e459..5af47253552e1e 100644 --- a/Documentation/gpu/asahi-usage-stats.rst +++ b/Documentation/gpu/asahi-usage-stats.rst @@ -48,10 +48,13 @@ start and end operations. The shared G17 backend runs several commands of one queue at once, so their stages overlap. It charges each engine of a queue the union of that queue's stage intervals (exact, because a queue's stages retire in the order they started), so a queue never counts more than the wall time on one -engine. Queues of one file still add up. The other backends sum their intervals -without merging overlapping commands on the same engine. Missing, zero-start or -reversed intervals are ignored. Failed or cancelled commands do not contribute -incomplete intervals; +engine. Queues of one file still add up on G17. Native G16 executes pipelined +commands and dual-pipe compute across sibling queues of one DRM file, so it +unions overlapping stage intervals per file (``Client::add_union``) to keep each +engine bounded by wall time. The other backends sum their intervals without +merging overlapping commands on the same engine. Missing, zero-start or reversed +intervals are ignored. Failed or cancelled commands do not contribute incomplete +intervals; successful stages that retired before a later failure remain counted. An unexecuted G17 replay contributes only when it eventually retires successfully. There is no submit-to-completion wall-time fallback in the current backends. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 72e06e65e656ba..4ed5e8b49fac0a 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -766,7 +766,7 @@ impl Firmware { unit: &super::slots::ComputeSlot, ) -> Result<(u64, u64)> { let (start, end) = (unit.its.r64(0)?, unit.its.r64(8)?); - if start != 0 && end > start { + if start != 0 && end >= start { return Ok((start, end)); } let Some((start_off, end_off)) = work_ticks else { @@ -998,7 +998,7 @@ impl Firmware { break; } let (start, end) = self.compute_ticks(unit)?; - if start == 0 || end <= start { + if start == 0 || end < start { full = false; break; } @@ -1085,9 +1085,9 @@ impl Firmware { ticks = [ta_start, ta_end, fs_start, fs_end]; } full &= ta_start != 0 - && ta_end > ta_start + && ta_end >= ta_start && fs_start != 0 - && fs_end > fs_start; + && fs_end >= fs_start; if !full { break; } @@ -1558,7 +1558,7 @@ impl Firmware { f.job .queue .usage - .add(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); + .add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32); *sum = sum.saturating_add(end - start); lo = lo.min(start); hi = hi.max(end); diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index aa2cb8117d0848..bb6866e5fdf01a 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -48,8 +48,8 @@ pub(crate) struct QueueState { /// Host priority: `DRM_ASAHI_PRIORITY_REALTIME - priority` as `file.rs` passes it (MEDIUM 2, /// LOW 3; `file.rs` refuses HIGH and REALTIME). Smaller is served first. pub(crate) priority: u32, - /// Completed stage time of the DRM file that created this queue (deduplicated per lane). - pub(crate) usage: Arc>>, + /// Completed stage time of the DRM file that created this queue (deduplicated per file). + pub(crate) usage: Arc, /// USC executable window base. pub(crate) usc_base: u64, /// First cancelled accepted ordinal per engine; zero means none. Later scheduler @@ -164,7 +164,6 @@ impl Queue { return Err(EIO); } let credit = QueueCredit::acquire(&usage)?; - let usage = Arc::new(crate::usage::Lane::new(usage), GFP_KERNEL)?; let timeline = Timeline::new()?; let scheduler = Scheduler::new(&gpu.shared.dev)?; let state = Arc::new( diff --git a/drivers/gpu/drm/asahi/usage.rs b/drivers/gpu/drm/asahi/usage.rs index eee128207aeff0..5125a237b50937 100644 --- a/drivers/gpu/drm/asahi/usage.rs +++ b/drivers/gpu/drm/asahi/usage.rs @@ -21,6 +21,7 @@ pub(crate) enum Engine { /// One ledger per DRM file, shared by all of its queues and VMs. pub(crate) struct Client { ns: [AtomicU64; 3], + covered: [AtomicU64; 3], queues: AtomicU32, } @@ -28,6 +29,7 @@ impl Client { pub(crate) const fn new() -> Self { Self { ns: [const { AtomicU64::new(0) }; 3], + covered: [const { AtomicU64::new(0) }; 3], queues: AtomicU32::new(0), } } @@ -85,17 +87,48 @@ impl Client { } } + /// As [`Self::add`], deduplicating overlapping stage intervals across all queues of this + /// DRM file (including sibling queues running concurrently on multiple hardware pipes). + /// Only the part of `start..end` after the file's per-engine mark is charged, and the + /// mark advances to `end`. + pub(crate) fn add_union(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.add(engine, from, end, frequency_hz); + } + } + /// Vertex, fragment and compute, in ns. No cross-engine atomic snapshot is promised. pub(crate) fn snapshot(&self) -> [u64; 3] { self.ns.each_ref().map(|ns| ns.load(Ordering::Relaxed)) } } -/// A stage this far behind its lane's mark is not an overlap, since no stage runs this -/// long: the timestamps jumped, so the mark restarts at the stage instead of holding every +/// A stage this far behind its mark is not an overlap, since no stage runs this long: +/// the timestamps jumped, so the mark restarts at the stage instead of holding every /// later charge back. const DISCONTINUITY_S: u64 = 60; +/// Advances `mark` to cover `start..end`, returning the uncovered sub-interval start `from` +/// when `from < end`, or `None` when the interval is invalid or already covered. +fn union_mark(mark: &AtomicU64, start: u64, end: u64, frequency_hz: u32) -> Option { + if start == 0 || end <= start || frequency_hz == 0 { + return None; + } + let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); + let mut covered = mark.load(Ordering::Relaxed); + loop { + let jumped = covered.saturating_sub(start) > limit; + let from = if jumped { start } else { start.max(covered) }; + if from >= end { + return None; + } + match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Some(from), + Err(value) => covered = value, + } + } +} + /// The engine time of one queue, charged to its file's [`Client`]. /// /// Firmware can run several commands of one queue at once. A queue that keeps several @@ -121,24 +154,9 @@ impl> Lane

{ /// As [`Client::add`], for one retired stage of this lane's queue: only the part of /// `start..end` after the engine's mark is charged, and the mark moves to `end`. pub(crate) fn add(&self, engine: Engine, start: u64, end: u64, frequency_hz: u32) { - if start == 0 || end <= start || frequency_hz == 0 { - return; + if let Some(from) = union_mark(&self.covered[engine as usize], start, end, frequency_hz) { + self.client.add(engine, from, end, frequency_hz); } - let limit = u64::from(frequency_hz).saturating_mul(DISCONTINUITY_S); - let mark = &self.covered[engine as usize]; - let mut covered = mark.load(Ordering::Relaxed); - let from = loop { - let jumped = covered.saturating_sub(start) > limit; - let from = if jumped { start } else { start.max(covered) }; - if from >= end { - return; - } - match mark.compare_exchange_weak(covered, end, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => break from, - Err(value) => covered = value, - } - }; - self.client.add(engine, from, end, frequency_hz); } } @@ -290,6 +308,33 @@ mod tests { assert_eq!(client.snapshot(), [0, 0, 4_000]); } + #[test] + fn client_union_deduplicates_dual_pipe_siblings_and_isolates_files() { + let file_a = Client::new(); + let file_b = Client::new(); + // Two sibling queues on the same DRM file overlapping across two CDM pipes + // (e.g., 543 us dispatches at depth 4). + const PERIOD: u64 = 13_032; // 543 us at 24 MHz + for i in 0..100u64 { + let p0_start = 1_000 + i * PERIOD; + let p1_start = p0_start + PERIOD / 4; + file_a.add_union(Engine::Compute, p0_start, p0_start + PERIOD, HZ); + file_a.add_union(Engine::Compute, p1_start, p1_start + PERIOD, HZ); + } + let wall = ticks_to_ns(99 * PERIOD + PERIOD / 4 + PERIOD, HZ); + assert_eq!(file_a.snapshot()[2], wall); + // Separate DRM file keeps its own union mark. + file_b.add_union(Engine::Compute, 1_000, 1_000 + PERIOD, HZ); + assert_eq!(file_b.snapshot()[2], ticks_to_ns(PERIOD, HZ)); + // Timestamp jump > 60 s behind the mark restarts the file mark cleanly. + let far = 61 * u64::from(HZ); + file_b.add_union(Engine::Compute, 1, far, HZ); + let before = file_b.snapshot()[2]; + file_b.add_union(Engine::Compute, 24, 48, HZ); + file_b.add_union(Engine::Compute, 36, 72, HZ); + assert_eq!(file_b.snapshot()[2] - before, 2_000); + } + #[test] fn a_timestamp_jump_restarts_the_mark() { let client = Client::new(); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 32e096a68a9ebf..5befe96f289b76 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -17,11 +17,11 @@ 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source ), 'aurora_g16_events must use new_percpu_reclaim(..., true)' assert ( - 'pub(crate) usage: Arc>>' in queue_source -), 'QueueState::usage must deduplicate per-queue pipelined stages via usage::Lane' + 'pub(crate) usage: Arc' in queue_source +), 'QueueState::usage must reference the per-file usage::Client' assert ( - 'crate::usage::Lane::new(usage)' in queue_source -), 'Queue::new must wrap client usage in usage::Lane' + '.add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32)' in source +), 'G16 poll retirement must deduplicate per-file intervals via Client::add_union' def item(declaration, text=source): @@ -1015,24 +1015,25 @@ def item(declaration, text=source): mod usage; #[test] -fn per_queue_usage_lane_charges_distinct_stages_and_deduplicates_overlap() { +fn per_file_usage_union_deduplicates_pipelined_and_dual_pipe_siblings() { let client = Arc::new(usage::Client::new()); - let lane = usage::Lane::new(client.clone()); const HZ: u32 = 24_000_000; // Two pipelined renders whose TA and FS intervals overlap across flights. - lane.add(usage::Engine::Vertex, 24_000, 48_000, HZ); - lane.add(usage::Engine::Fragment, 40_000, 88_000, HZ); - lane.add(usage::Engine::Vertex, 36_000, 72_000, HZ); - lane.add(usage::Engine::Fragment, 64_000, 120_000, HZ); - lane.add(usage::Engine::Compute, 100_000, 124_000, HZ); + client.add_union(usage::Engine::Vertex, 24_000, 48_000, HZ); + client.add_union(usage::Engine::Fragment, 40_000, 88_000, HZ); + client.add_union(usage::Engine::Vertex, 36_000, 72_000, HZ); + client.add_union(usage::Engine::Fragment, 64_000, 120_000, HZ); + // Two sibling queues on the same DRM file overlapping across dual CDM pipes. + client.add_union(usage::Engine::Compute, 100_000, 124_000, HZ); + client.add_union(usage::Engine::Compute, 106_000, 130_000, HZ); let [v_ns, f_ns, c_ns] = client.snapshot(); // Vertex union: [24k, 72k] = 48k ticks = 2_000_000 ns (not 60k ticks = 2.5 ms). assert_eq!(v_ns, 2_000_000); // Fragment union: [40k, 120k] = 80k ticks = 3_333_333 ns (distinct from Vertex). assert_eq!(f_ns, 3_333_333); assert_ne!(v_ns, f_ns); - // Compute: [100k, 124k] = 24k ticks = 1_000_000 ns. - assert_eq!(c_ns, 1_000_000); + // Compute union: [100k, 130k] = 30k ticks = 1_250_000 ns (not 48k ticks = 2.0 ms). + assert_eq!(c_ns, 1_250_000); } ''' 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 90ff43dcb2e8d6..eb884621a68083 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 @@ -328,6 +328,36 @@ def function(text, name): assert_eq!(f.retired(),Ok(Retirement::Aborted)); assert!(f.engine.flights[0].doomed); } +#[test]fn same_tick_stage_timestamps_retire_full_while_zero_or_reversed_stay_pending(){ + // 24 MHz (41.67 ns) stage timestamps can legitimately record end == start on tiny draws + // or dispatches; accept end >= start while still rejecting 0 or reversed intervals. + let mut r=firmware(true,50); + r.engine.flights[0].job.resources.passes[0].scene.set(0x600,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x620,200); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,200); + assert_eq!(r.retired(),Ok(Retirement::Full)); + assert_eq!(r.engine.retired_ticks,[100,100,200,200]); + + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,0); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,99); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + r.engine.flights[0].job.resources.passes[0].scene.set(0x608,100); + r.engine.flights[0].job.resources.passes[0].scene.set(0x628,199); + assert_eq!(r.retired(),Ok(Retirement::Pending)); + + let mut c=firmware(false,51); + c.engine.flights[0].job.resources.compute[0].its.set(0,300); + c.engine.flights[0].job.resources.compute[0].its.set(8,300); + assert_eq!(c.retired(),Ok(Retirement::Full)); + assert_eq!(c.engine.retired_ticks,[300,300,0,0]); + + c.engine.flights[0].job.resources.compute[0].its.set(8,0); + assert_eq!(c.retired(),Ok(Retirement::Pending)); + c.engine.flights[0].job.resources.compute[0].its.set(8,299); + assert_eq!(c.retired(),Ok(Retirement::Pending)); +} '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: From ea6e158cbbb1d71e4cdd2974683bef4a850bc19a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 11:53:36 -0500 Subject: [PATCH 0855/1514] drm/asahi: g16: make slot VM/arena holding and mask scans O(claims) Replace O(RENDER_SLOTS) 0..48 loops over Claims::pass_mask in Slots (mark_dirty, note_published, hold_vm, hold_arenas, publish, retire, quarantine, release) with bit-set iteration over set bits only. Add O(1) per-unit helpers hold_compute_slot() and hold_render_pass() called directly during prefix_compute() and prefix_render(), plus verify_held() at publish_prefix_body() time so multi-pass render and compute horizon batches no longer re-scan every slot and redundantly clone/drop Arc VM and arena leases on every pass and again at publication. Add host selftest coverage for per-unit holding, verify_held() bounds and mask validation, and bit-set cross-VM retarget accounting on high render pass slots. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 9 +- drivers/gpu/drm/asahi/g16/slots.rs | 193 +++++++++++++----- .../drivers/gpu/asahi-m4/test-resources.py | 65 +++++- 3 files changed, 211 insertions(+), 56 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index f47b4faea4a02f..ccd9a6663bca55 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1962,8 +1962,7 @@ impl Firmware { } // 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.verify_held(&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. @@ -2153,8 +2152,7 @@ impl Firmware { .claim_compute_for(resources, &mut f.claims, Some(job.vm.id))? .ok_or(EAGAIN)?; let generation = job.vm.generation; - self.slots.hold_vm(&f.claims, &job.vm)?; - self.slots.hold_arenas(&f.claims, resources); + self.slots.hold_compute_slot(index, &job.vm, resources)?; let s = resources.compute_unit(index)?; let g = &self.graph.compute; let before = s.counter.r64(0)?; @@ -2365,8 +2363,7 @@ impl Firmware { // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; - self.slots.hold_vm(&f.claims, &job.vm)?; - self.slots.hold_arenas(&f.claims, &job.resources); + self.slots.hold_render_pass(k, &job.vm, &job.resources)?; let (refs, init_buffer) = if member == 0 { let pb_slots = job.resources.pb_slots()?; let alloc_slot = self diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 68d48b717d70b2..39e588e768649b 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -887,11 +887,12 @@ impl Slots { *dirty = true; } } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - self.render.scrub_full[k] = true; - self.scrub.clear_clean(k); - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } } @@ -1181,19 +1182,101 @@ impl Slots { self.stats.last_retarget[0] = proof; } } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - 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; + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + 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; + } + } + } + + /// Retains one newly claimed compute unit's VM/ASID lease and owner arena in O(1). + pub(crate) fn hold_compute_slot( + &mut self, + k: usize, + vm: &Arc, + resources: &super::resources::Prepared, + ) -> Result { + if k >= sizes::COMPUTE_UNITS { + return Err(EINVAL); + } + self.compute.pending_retarget[k] = self.compute.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.compute.pending_owner[k] = Some(vm.clone()); + self.compute.pending_arena[k] = resources.compute_arena(k); + Ok(()) + } + + /// Retains one newly claimed render pass slot's VM/ASID lease and owner arena in O(1). + pub(crate) fn hold_render_pass( + &mut self, + k: usize, + vm: &Arc, + resources: &super::resources::Prepared, + ) -> Result { + if k >= sizes::RENDER_SLOTS { + return Err(EINVAL); + } + self.render.pending_retarget[k] = self.render.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.render.pending_owner[k] = Some(vm.clone()); + self.render.pending_arena[k] = resources.pass_owner_arena(k); + Ok(()) + } + + /// Validates claim bounds/masks and confirms every claimed slot already holds a pending + /// VM lease without re-cloning `Arc` leases at publication time. + pub(crate) fn verify_held(&self, f: &Claims) -> Result { + if f.slot_count as usize > f.slot.len() + || f.pass_count as usize > f.pass.len() + || f.pass_mask & !PASS_MASK != 0 + { + return Err(EINVAL); + } + for &k in &f.slot[..f.slot_count as usize] { + let k = k as usize; + if k >= sizes::COMPUTE_UNITS || self.compute.pending_owner[k].is_none() { + return Err(EINVAL); + } + } + if f.pass_count != 0 { + let mut mask = 0u64; + for &k in &f.pass[..f.pass_count as usize] { + let k = k as usize; + if k >= sizes::RENDER_SLOTS || self.render.pending_owner[k].is_none() { + return Err(EINVAL); + } + let bit = 1u64 << k; + if mask & bit != 0 { + return Err(EINVAL); + } + mask |= bit; + } + if mask != f.pass_mask { + return Err(EINVAL); + } + } else { + let mut mask = f.pass_mask; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if self.render.pending_owner[k].is_none() { + return Err(EINVAL); } } } + Ok(()) } /// Retains each actual owner's VM/ASID binding through the firmware's last-owner era. /// A previous lease is replaced only after the new publication fully retires. + #[allow(dead_code)] pub(crate) fn hold_vm(&mut self, f: &Claims, vm: &Arc) -> Result { if f.slot_count as usize > f.slot.len() || f.slot[..f.slot_count as usize] @@ -1227,29 +1310,32 @@ impl Slots { .and_then(|old| Self::vm_retarget(k, old, vm)); self.compute.pending_owner[k] = Some(vm.clone()); } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - self.render.pending_retarget[k] = self.render.owner[k] - .as_ref() - .and_then(|old| Self::vm_retarget(k, old, vm)); - self.render.pending_owner[k] = Some(vm.clone()); - } + let mut mask = f.pass_mask; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.pending_retarget[k] = self.render.owner[k] + .as_ref() + .and_then(|old| Self::vm_retarget(k, old, vm)); + self.render.pending_owner[k] = Some(vm.clone()); } 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. + #[allow(dead_code)] 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..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - self.render.pending_arena[k] = resources.pass_owner_arena(k); - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.pending_arena[k] = resources.pass_owner_arena(k); } } @@ -1273,8 +1359,11 @@ impl Slots { } } } else { - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 && !p.publish(k) { + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if !p.publish(k) { return Err(EBUSY); } } @@ -1304,8 +1393,11 @@ impl Slots { } } } else { - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 && !p.retire(k) { + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + if !p.retire(k) { return Err(EINVAL); } } @@ -1320,13 +1412,14 @@ impl Slots { 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(); - if clean_scrub { - self.render.scrub_full[k] = false; - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.owner[k] = self.render.pending_owner[k].take(); + self.render.arena[k] = self.render.pending_arena[k].take(); + if clean_scrub { + self.render.scrub_full[k] = false; } } self.pass_busy &= !f.pass_mask; @@ -1342,13 +1435,14 @@ impl Slots { self.compute.pending_retarget[k as usize] = None; self.compute.scrub_full[k as usize] = true; } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - self.render.lifetime.quarantine(k); - self.render.pending_retarget[k] = None; - self.render.scrub_full[k] = true; - self.scrub.clear_clean(k); - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + self.render.lifetime.quarantine(k); + self.render.pending_retarget[k] = None; + self.render.scrub_full[k] = true; + self.scrub.clear_clean(k); } self.pass_busy &= !f.pass_mask; f.slot_count = 0; @@ -1365,15 +1459,16 @@ impl Slots { self.compute.pending_arena[k as usize] = None; self.compute.scrub_full[k as usize] = true; } - for k in 0..sizes::RENDER_SLOTS { - if f.pass_mask & (1 << k) != 0 { - 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.scrub.clear_clean(k); - } + let mut mask = f.pass_mask & PASS_MASK; + while mask != 0 { + let k = mask.trailing_zeros() as usize; + mask &= mask - 1; + 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.scrub.clear_clean(k); } self.pass_busy &= !f.pass_mask; f.slot_count = 0; 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 6098ef1a133d57..66e9a9fe79f52a 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1118,6 +1118,69 @@ def module(text, name): assert!(!pools.retired_at(0,6).unwrap()); } + #[test]fn per_unit_hold_and_verify_held_match_batch_and_reject_unheld_slots(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); + 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 render=sync::Arc::new(g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + },0).unwrap(); + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let a=vm(1);let b=vm(2); + + // Per-unit compute hold_compute_slot + verify_held + note_published. + let mut cc=Claims::new(); + let k0=s.claim_compute_for(&prep,&mut cc,Some(a.id)).unwrap().unwrap(); + assert_eq!(s.verify_held(&cc),Err(EINVAL)); + assert_eq!(s.hold_compute_slot(g16::hw::sizes::COMPUTE_UNITS,&a,&prep),Err(EINVAL)); + s.hold_compute_slot(k0,&a,&prep).unwrap(); + s.verify_held(&cc).unwrap(); + s.publish(&cc).unwrap(); + s.note_published(&cc); + s.retire(&mut cc).unwrap(); + + // High render pass slots (46, 47) held individually via hold_render_pass. + let mut cr=Claims::new(); + for (i,&k) in [46usize,47].iter().enumerate() { + s.claim_pass_in(&prep,k,Some(a.id),0x1000).unwrap(); + cr.pass[i]=k as u32; + cr.pass_count+=1; + cr.pass_mask|=1u64< Date: Sun, 22 Nov 2026 12:03:11 -0500 Subject: [PATCH 0856/1514] drm/asahi: g16: add host-refill CPU boost and active-burst GPU ramp Mirror G17's host-refill CPU capacity actuator on G16 and bridge short sub-2 ms inter-flight gaps in the G16 GPU power governor: - Add g16/feed.rs and lock-free g16/feed/detector.rs tracking monotonic flight [published_ns, retired_ns] intervals (independent of firmware microsequence timestamps). After 8 consecutive sub-2 ms back-to-back completions with host refill idle >= 25% of busy time, request a cpufreq FREQ_QOS_MIN boost on an unbound workqueue outside Shared::state with an 8 ms linger and uclamp wait hint. Pause, drain, and release the CPU floor across S2R suspend/resume and fail-stop. - In g16/power/policy.rs, track consecutive sub-2 ms inter-flight gaps (BURST_GAP_NS = CLPC_IDLE_HOLD_NS, BURST_STREAK_ON = 4) and bridge those active-burst gaps in Governor::busy() so low-duty d=1 bursts ramp out of P1 without affecting 60/120 Hz paced rendering (6.8/15.2 ms gaps) or idle P-state decay. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/feed.rs | 413 ++++++++++++++++++ drivers/gpu/drm/asahi/g16/feed/detector.rs | 259 +++++++++++ drivers/gpu/drm/asahi/g16/mod.rs | 45 +- drivers/gpu/drm/asahi/g16/poll.rs | 6 + drivers/gpu/drm/asahi/g16/power/policy.rs | 76 +++- drivers/gpu/drm/asahi/g16/sleep.rs | 6 + .../gpu/asahi-m4/check-thermal-policy.rs | 2 + .../gpu/asahi-m4/test-thermal-policy.py | 9 +- 8 files changed, 809 insertions(+), 7 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g16/feed.rs create mode 100644 drivers/gpu/drm/asahi/g16/feed/detector.rs diff --git a/drivers/gpu/drm/asahi/g16/feed.rs b/drivers/gpu/drm/asahi/g16/feed.rs new file mode 100644 index 00000000000000..f0c46b2d31bd27 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/feed.rs @@ -0,0 +1,413 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Detects sustained host refill gaps on G16 and temporarily raises CPU frequency +//! floors via `cpufreq` `FREQ_QOS_MIN` constraints (mirroring G17's feed actuator). +//! +//! Detector updates are lock-free and run in the monotonic nanosecond domain so they +//! work identically whether or not firmware microsequence timestamps are enabled. +//! The dedicated unbound feed worker and cpufreq policy notifier serialize frequency +//! requests under `Feed::requests`, never nesting inside `Shared::state`. + +pub(crate) mod detector; + +use core::{ + pin::Pin, + sync::atomic::{AtomicBool, Ordering}, +}; +use kernel::{ + prelude::*, + sync::Arc, + time::{delay::fsleep, ClockSource, Delta, Monotonic}, +}; + +#[cfg(CONFIG_CPU_FREQ)] +use core::ptr; +#[cfg(CONFIG_CPU_FREQ)] +use kernel::{bindings, new_mutex, sync::Mutex, types::Opaque}; + +use detector::Detector; + +const POLL_MS: i64 = 2; +#[cfg(CONFIG_CPU_FREQ)] +const FLOOR_PERCENT: u64 = 100; +const WAIT_UTIL_MIN: u32 = 512; +const WAIT_HINT_MS: u32 = 8; +#[cfg(CONFIG_CPU_FREQ)] +const MAX_POLICIES: usize = 8; + +#[cfg(CONFIG_CPU_FREQ)] +#[pin_data] +struct Requests { + #[pin] + requests: Opaque<[bindings::freq_qos_request; MAX_POLICIES]>, + policies: [*mut bindings::cpufreq_policy; MAX_POLICIES], + maxima: [u32; MAX_POLICIES], + applied: [u32; MAX_POLICIES], +} + +// SAFETY: Each nonnull policy owns a kobject reference. The device requests mutex +// serializes the pinned slots with the worker and policy callbacks. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Send for Requests {} + +#[cfg(CONFIG_CPU_FREQ)] +impl Requests { + fn new() -> Self { + Self { + requests: Opaque::zeroed(), + policies: [ptr::null_mut(); MAX_POLICIES], + maxima: [0; MAX_POLICIES], + applied: [0; MAX_POLICIES], + } + } + + fn target_floor(maximum: u32, enabled: bool) -> u32 { + if enabled { + (u64::from(maximum) * FLOOR_PERCENT / 100) as u32 + } else { + bindings::FREQ_QOS_MIN_DEFAULT_VALUE as u32 + } + } + + /// Add a policy to the pinned requests. + /// + /// # Safety + /// + /// The caller holds the policy's read or write lock and keeps it alive. + /// Policy removal must subsequently pass through this device's notifier. + unsafe fn add(self: Pin<&mut Self>, policy: *mut bindings::cpufreq_policy) { + let this = self.project(); + if this.policies.contains(&policy) { + return; + } + let Some(index) = this.policies.iter().position(|entry| entry.is_null()) else { + return; + }; + // SAFETY: The caller keeps the initialized policy alive. The vacant request + // slot is pinned and exclusively owned under the requests mutex. + let result = unsafe { + bindings::freq_qos_add_request( + ptr::addr_of_mut!((*policy).constraints), + this.requests + .get() + .cast::() + .add(index), + bindings::freq_qos_req_type_FREQ_QOS_MIN, + bindings::FREQ_QOS_MIN_DEFAULT_VALUE as i32, + ) + }; + if result >= 0 { + // SAFETY: The caller's policy reference or CREATE callback keeps the + // kobject alive until REMOVE or shutdown removes this request. + unsafe { + bindings::kobject_get(ptr::addr_of_mut!((*policy).kobj)); + this.maxima[index] = (*policy).cpuinfo.max_freq; + } + this.policies[index] = policy; + this.applied[index] = bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + } + + fn apply(self: Pin<&mut Self>, enabled: bool) -> bool { + let this = self.project(); + let mut applied = false; + for index in 0..MAX_POLICIES { + if this.policies[index].is_null() { + continue; + } + let value = Self::target_floor(this.maxima[index], enabled); + if this.applied[index] != value { + // SAFETY: This slot is registered, pinned and exclusively locked; + // the policy reference keeps its constraints alive through REMOVE. + let result = unsafe { + bindings::freq_qos_update_request( + this.requests + .get() + .cast::() + .add(index), + value as i32, + ) + }; + if result >= 0 { + this.applied[index] = value; + } + } + applied |= this.applied[index] != bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + applied + } + + fn remove(self: Pin<&mut Self>, policy: *mut bindings::cpufreq_policy) { + let this = self.project(); + let Some(index) = this.policies.iter().position(|entry| *entry == policy) else { + return; + }; + // SAFETY: This registered pinned slot is exclusively locked. Keep all other + // request slots at their original addresses when releasing this slot. + unsafe { + bindings::freq_qos_remove_request( + this.requests + .get() + .cast::() + .add(index), + ); + bindings::cpufreq_cpu_put(policy); + } + this.policies[index] = ptr::null_mut(); + this.maxima[index] = 0; + this.applied[index] = bindings::FREQ_QOS_MIN_DEFAULT_VALUE; + } + + fn clear(mut self: Pin<&mut Self>) { + for index in 0..MAX_POLICIES { + let policy = self.policies[index]; + if !policy.is_null() { + self.as_mut().remove(policy); + } + } + } +} + +/// Only the blocking notifier core accesses this block after registration. +#[cfg(CONFIG_CPU_FREQ)] +#[pin_data] +struct PolicyNotifier { + #[pin] + block: Opaque, +} + +// SAFETY: The pinned notifier is registered once before publishing Feed and +// unregistered at shutdown. The blocking notifier core serializes its links; +// callbacks use only Feed's atomic state and request mutex. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Send for PolicyNotifier {} +// SAFETY: As above; no Rust access mutates the registered block. +#[cfg(CONFIG_CPU_FREQ)] +unsafe impl Sync for PolicyNotifier {} + +#[pin_data(PinnedDrop)] +pub(crate) struct Feed { + detector: Detector, + #[cfg(CONFIG_CPU_FREQ)] + #[pin] + requests: Mutex, + #[cfg(CONFIG_CPU_FREQ)] + #[pin] + notifier: PolicyNotifier, + #[cfg(CONFIG_CPU_FREQ)] + registered: AtomicBool, + applied: AtomicBool, +} + +impl Feed { + pub(crate) fn new() -> Result> { + let feed = Arc::pin_init( + pin_init!(Self { + detector: Detector::new(), + #[cfg(CONFIG_CPU_FREQ)] + requests <- new_mutex!(Requests::new(), "G16 CPU feed"), + #[cfg(CONFIG_CPU_FREQ)] + notifier <- pin_init!(PolicyNotifier { + block: Opaque::new(bindings::notifier_block { + notifier_call: Some(Self::policy_event), + next: ptr::null_mut(), + priority: 0, + }), + }), + #[cfg(CONFIG_CPU_FREQ)] + registered: AtomicBool::new(false), + applied: AtomicBool::new(false), + }), + GFP_KERNEL, + )?; + #[cfg(CONFIG_CPU_FREQ)] + feed.register_policies(); + Ok(feed) + } + + /// Seed existing policies once; later creation/removal is event driven. + #[cfg(CONFIG_CPU_FREQ)] + fn register_policies(&self) { + // SAFETY: Feed is pinned in its Arc and has not been published. The + // notifier block lives until shutdown unregisters and joins callbacks. + let result = unsafe { + bindings::cpufreq_register_notifier( + self.notifier.block.get(), + bindings::CPUFREQ_POLICY_NOTIFIER, + ) + }; + if result < 0 { + return; + } + self.registered.store(true, Ordering::Release); + // SAFETY: nr_cpu_ids is initialized before driver probe. + let cpus = unsafe { bindings::nr_cpu_ids }; + for cpu in 0..cpus { + // SAFETY: The bounded CPU index is valid; a nonnull result owns a reference. + let policy = unsafe { bindings::cpufreq_cpu_get(cpu) }; + if policy.is_null() { + continue; + } + // SAFETY: The retained reference keeps the policy and rwsem alive. + unsafe { bindings::down_read(ptr::addr_of_mut!((*policy).rwsem)) }; + { + let mut requests = self.requests.lock(); + // SAFETY: The CPU index is valid; balance this extra reference below. + let current = unsafe { bindings::cpufreq_cpu_get(cpu) }; + // SAFETY: The policy read lock excludes unfinished CREATE. + let initialized = + current == policy && unsafe { !(*policy).max_freq_req.qos.is_null() }; + if initialized { + // SAFETY: The reference and read lock keep the policy alive. + unsafe { requests.as_mut().add(policy) }; + } + if !current.is_null() { + // SAFETY: Balances the second lookup. + unsafe { bindings::cpufreq_cpu_put(current) }; + } + } + // SAFETY: Balance the read lock and first lookup after releasing requests. + unsafe { + bindings::up_read(ptr::addr_of_mut!((*policy).rwsem)); + bindings::cpufreq_cpu_put(policy); + } + } + } + + /// Process a cpufreq policy notification. + /// + /// # Safety + /// + /// `block` must be this pinned Feed's registered notifier, and `data` must + /// point to the live policy supplied by the cpufreq notifier core. + #[cfg(CONFIG_CPU_FREQ)] + unsafe extern "C" fn policy_event( + block: *mut bindings::notifier_block, + event: c_ulong, + data: *mut core::ffi::c_void, + ) -> core::ffi::c_int { + // SAFETY: Installed only on Feed::notifier.block; owner stays pinned until unregister. + let notifier = + unsafe { kernel::container_of!(Opaque::cast_from(block), PolicyNotifier, block) }; + // SAFETY: The notifier is the embedded, pinned field of this live Feed. + let feed = unsafe { &*kernel::container_of!(notifier, Feed, notifier) }; + let policy = data.cast::(); + let mut requests = feed.requests.lock(); + if event == bindings::CPUFREQ_REMOVE_POLICY as c_ulong { + requests.as_mut().remove(policy); + } else if event == bindings::CPUFREQ_CREATE_POLICY as c_ulong + && !feed.detector.is_stopped_or_paused() + { + // SAFETY: CREATE supplies an initialized policy with its write lock held. + unsafe { requests.as_mut().add(policy) }; + } else { + return bindings::NOTIFY_DONE as i32; + } + let enabled = feed.detector.wanted(Self::now()); + let applied = requests.as_mut().apply(enabled); + feed.applied.store(applied, Ordering::Relaxed); + bindings::NOTIFY_OK as i32 + } + + fn now() -> u64 { + Monotonic::ktime_get() as u64 + } + + /// Records a completed flight's monotonic `[published_ns, retired_ns]` interval. + pub(crate) fn note_flight(&self, published_ns: u64, retired_ns: u64) { + if cfg!(CONFIG_CPU_FREQ) { + self.detector.note(published_ns, retired_ns, retired_ns); + } + } + + /// Consumes a pending boost request after a poll/submit pass outside `Shared::state`. + pub(crate) fn take_pending(&self) -> bool { + self.detector.take_pending() + } + + #[cfg(CONFIG_CPU_FREQ)] + fn apply(&self, enabled: bool) { + let mut requests = self.requests.lock(); + let enabled = enabled && !self.detector.is_stopped_or_paused(); + let applied = requests.as_mut().apply(enabled); + self.applied.store(applied, Ordering::Relaxed); + } + + #[cfg(not(CONFIG_CPU_FREQ))] + fn apply(&self, _enabled: bool) {} + + /// Worker context; keeps the CPU floor active until the linger deadline expires. + pub(crate) fn run(&self) { + loop { + if self.detector.wanted(Self::now()) { + self.apply(true); + fsleep(Delta::from_millis(POLL_MS)); + continue; + } + self.apply(false); + self.detector.clear_active(); + if self.detector.wanted(Self::now()) && self.detector.try_claim_active() { + continue; + } + return; + } + } + + pub(crate) fn wait_hint(&self) -> Option<(u32, u32)> { + if cfg!(CONFIG_UCLAMP_TASK) + && self.detector.wanted(Self::now()) + && self.applied.load(Ordering::Relaxed) + { + Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) + } else { + None + } + } + + /// Pauses boosting before entering system sleep; call before draining `feed_wq`. + pub(crate) fn pause(&self) { + self.detector.pause(); + } + + /// Releases any active CPU floor after `feed_wq` has drained for system sleep. + pub(crate) fn release_floor(&self) { + self.apply(false); + self.detector.clear_active(); + } + + /// Resumes refill-pressure detection after system wake or a refused sleep. + pub(crate) fn resume(&self) { + self.detector.resume(); + } + + /// Closes the detector on fail-stop or teardown. + pub(crate) fn begin_shutdown(&self) { + self.detector.begin_shutdown(); + } + + /// Unregisters cpufreq policy callbacks and removes all frequency requests. + pub(crate) fn shutdown(&self) { + self.begin_shutdown(); + #[cfg(CONFIG_CPU_FREQ)] + { + if self.registered.swap(false, Ordering::AcqRel) { + // SAFETY: The block was registered successfully and remains pinned until return. + unsafe { + bindings::cpufreq_unregister_notifier( + self.notifier.block.get(), + bindings::CPUFREQ_POLICY_NOTIFIER, + ); + } + } + self.requests.lock().as_mut().clear(); + } + self.applied.store(false, Ordering::Relaxed); + } +} + +#[pinned_drop] +impl PinnedDrop for Feed { + fn drop(self: Pin<&mut Self>) { + self.shutdown(); + } +} diff --git a/drivers/gpu/drm/asahi/g16/feed/detector.rs b/drivers/gpu/drm/asahi/g16/feed/detector.rs new file mode 100644 index 00000000000000..124ba7a92bceb4 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/feed/detector.rs @@ -0,0 +1,259 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Lock-free host-refill pressure detector for G16 CPU frequency boosting. +//! +//! Tracks monotonic flight `[published_ns, retired_ns]` intervals so detection works +//! identically whether or not firmware microsequence timestamps are enabled. + +use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +/// Maximum inter-flight idle gap (2 ms) that still counts as an active back-to-back burst +/// rather than paced desktop/compositor rendering (60 Hz = 16.67 ms, 120 Hz = 8.33 ms). +pub(crate) const MAX_REFILL_NS: u64 = 2_000_000; +/// Consecutive sub-`MAX_REFILL_NS` flight completions required before engaging CPU boost. +pub(crate) const STREAK_ON: u32 = 8; +/// Upper saturation bound on the consecutive-burst streak counter. +pub(crate) const STREAK_MAX: u32 = 64; +/// How long CPU capacity boost lingers after the most recent refill-pressure sample. +pub(crate) const LINGER_NS: u64 = 8_000_000; + +/// Lock-free refill-gap detector shared between completion retirement and the feed worker. +pub(crate) struct Detector { + last_end: AtomicU64, + idle: AtomicU64, + busy: AtomicU64, + streak: AtomicU32, + until: AtomicU64, + bound_until: AtomicU64, + active: AtomicBool, + pending: AtomicBool, + paused: AtomicBool, + stopping: AtomicBool, +} + +impl Detector { + pub(crate) const fn new() -> Self { + Self { + last_end: AtomicU64::new(0), + idle: AtomicU64::new(0), + busy: AtomicU64::new(0), + streak: AtomicU32::new(0), + until: AtomicU64::new(0), + bound_until: AtomicU64::new(0), + active: AtomicBool::new(false), + pending: AtomicBool::new(false), + paused: AtomicBool::new(false), + stopping: AtomicBool::new(false), + } + } + + fn decay_add(sum: &AtomicU64, add: u64) -> u64 { + let mut value = sum.load(Ordering::Acquire); + loop { + let next = value - value / 8 + add; + match sum.compare_exchange_weak(value, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return next, + Err(observed) => value = observed, + } + } + } + + /// Records one completed flight's monotonic `[start_ns, end_ns]` span. + pub(crate) fn note(&self, start_ns: u64, end_ns: u64, now_ns: u64) { + if start_ns == 0 + || end_ns <= start_ns + || self.paused.load(Ordering::Acquire) + || self.stopping.load(Ordering::Acquire) + { + return; + } + let previous = self.last_end.fetch_max(end_ns, Ordering::AcqRel); + let (idle, busy, paced) = if previous == 0 { + (0, end_ns - start_ns, true) + } else if start_ns >= previous { + let gap = start_ns - previous; + if gap < MAX_REFILL_NS { + (gap, end_ns - start_ns, false) + } else { + (0, end_ns - start_ns, true) + } + } else if end_ns > previous { + (0, end_ns - previous, false) + } else { + (0, 0, false) + }; + let idle_sum = Self::decay_add(&self.idle, idle); + let busy_sum = Self::decay_add(&self.busy, busy); + let streak = if paced { + self.streak.store(0, Ordering::Release); + 0 + } else { + let mut value = self.streak.load(Ordering::Acquire); + loop { + let next = (value + 1).min(STREAK_MAX); + match self.streak.compare_exchange_weak( + value, + next, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => break next, + Err(observed) => value = observed, + } + } + }; + if streak < STREAK_ON { + return; + } + if idle_sum.saturating_mul(4) >= busy_sum { + self.until + .store(now_ns.saturating_add(LINGER_NS), Ordering::Release); + if !self.active.swap(true, Ordering::AcqRel) { + self.pending.store(true, Ordering::Release); + } + } else { + self.bound_until + .store(now_ns.saturating_add(LINGER_NS), Ordering::Release); + } + } + + pub(crate) fn wanted(&self, now_ns: u64) -> bool { + !self.stopping.load(Ordering::Acquire) + && !self.paused.load(Ordering::Acquire) + && now_ns < self.until.load(Ordering::Acquire) + } + + #[allow(dead_code)] + pub(crate) fn bound(&self, now_ns: u64) -> bool { + !self.stopping.load(Ordering::Acquire) + && !self.paused.load(Ordering::Acquire) + && now_ns < self.bound_until.load(Ordering::Acquire) + } + + pub(crate) fn take_pending(&self) -> bool { + self.pending.swap(false, Ordering::AcqRel) + } + + pub(crate) fn clear_active(&self) { + self.active.store(false, Ordering::SeqCst); + } + + pub(crate) fn try_claim_active(&self) -> bool { + !self.active.swap(true, Ordering::AcqRel) + } + + pub(crate) fn pause(&self) { + self.paused.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + self.until.store(0, Ordering::Release); + self.bound_until.store(0, Ordering::Release); + self.streak.store(0, Ordering::Release); + } + + pub(crate) fn resume(&self) { + self.last_end.store(0, Ordering::Release); + self.idle.store(0, Ordering::Release); + self.busy.store(0, Ordering::Release); + self.streak.store(0, Ordering::Release); + self.paused.store(false, Ordering::Release); + } + + pub(crate) fn begin_shutdown(&self) { + self.stopping.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + } + + pub(crate) fn is_stopped_or_paused(&self) -> bool { + self.stopping.load(Ordering::Acquire) || self.paused.load(Ordering::Acquire) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(detector: &Detector, flights: u64, busy_ns: u64, gap_ns: u64) -> u64 { + let mut start = 10_000_000; + for _ in 0..flights { + let end = start + busy_ns; + detector.note(start, end, end); + start = end + gap_ns; + } + start - gap_ns + } + + #[test] + fn cpu_refill_bound_burst_requests_boost_and_expires_after_linger() { + let d = Detector::new(); + // 170 us GPU flight with 450 us host recording gap (d=1 bindless_ubo / mdi). + let now = run(&d, 16, 170_000, 450_000); + assert!(d.wanted(now)); + assert!(d.take_pending()); + assert!(!d.take_pending()); + assert!(!d.bound(now)); + assert!(!d.wanted(now + LINGER_NS)); + } + + #[test] + fn gpu_bound_back_to_back_flights_do_not_boost_cpu() { + let d = Detector::new(); + // 2 ms GPU flights with 40 us host gaps: GPU-bound, not host-refill-bound. + let now = run(&d, 16, 2_000_000, 40_000); + assert!(d.bound(now)); + assert!(!d.wanted(now)); + assert!(!d.take_pending()); + assert!(!d.bound(now + LINGER_NS)); + } + + #[test] + fn desktop_60hz_and_120hz_pacing_never_triggers_boost() { + for period_ns in [16_666_667u64, 8_333_333u64] { + let d = Detector::new(); + let now = run(&d, 20, 1_500_000, period_ns - 1_500_000); + assert!(!d.wanted(now)); + assert!(!d.bound(now)); + assert!(!d.take_pending()); + } + } + + #[test] + fn short_runs_and_pause_resume_lifecycle_gate_boost_cleanly() { + let d = Detector::new(); + // Fewer than STREAK_ON back-to-back flights cannot arm boost. + let now = run(&d, u64::from(STREAK_ON), 100_000, 300_000); + assert!(!d.wanted(now)); + assert!(!d.take_pending()); + + // One more flight reaches streak == STREAK_ON and arms boost. + let start = now + 300_000; + let end = start + 100_000; + d.note(start, end, end); + assert!(d.wanted(end)); + assert!(d.take_pending()); + + // Suspend pause drops wanted immediately and ignores samples until resume. + assert!(!d.is_stopped_or_paused()); + assert!(!d.try_claim_active()); + d.pause(); + assert!(d.is_stopped_or_paused()); + assert!(!d.wanted(end)); + d.note(end + 100_000, end + 200_000, end + 200_000); + assert!(!d.wanted(end + 200_000)); + + // After resume + worker clear_active, try_claim_active works and a fresh burst re-arms. + d.clear_active(); + assert!(d.try_claim_active()); + d.clear_active(); + d.resume(); + assert!(!d.is_stopped_or_paused()); + let resumed_now = run(&d, 16, 150_000, 400_000); + assert!(d.wanted(resumed_now)); + assert!(d.take_pending()); + + // Shutdown permanently suppresses boost. + d.begin_shutdown(); + assert!(d.is_stopped_or_paused()); + assert!(!d.wanted(resumed_now)); + assert!(!d.take_pending()); + } +} diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 6be4c343beba11..3d1c01610ad3fa 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -52,6 +52,7 @@ mod command; mod encode; mod engine; mod event; +mod feed; mod fence; pub(crate) mod fw; mod gate; @@ -194,6 +195,8 @@ const POLL_WORK: u64 = 0; const FAST_POLL_WORK: u64 = 1; /// Work item ID of the asynchronous displaced pass-slot scrub work. const SCRUB_WORK: u64 = 2; +/// Work item ID of the asynchronous CPU feed-boost work. +const FEED_WORK: u64 = 3; /// 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; @@ -260,6 +263,10 @@ pub(crate) struct Shared { pub(crate) events: OwnedQueue, /// Dedicated unbound workqueue for asynchronous off-lock pass-slot WC scrubbing. pub(crate) scrub_wq: OwnedQueue, + /// Host-refill CPU frequency floor actuator (mirroring G17's feed worker). + pub(crate) feed: Arc, + /// Dedicated unbound workqueue for cpufreq `FREQ_QOS_MIN` updates outside `Shared::state`. + pub(crate) feed_wq: OwnedQueue, #[pin] pub(crate) orphan: Mutex>>, #[pin] @@ -270,6 +277,8 @@ pub(crate) struct Shared { pub(crate) scrub_queue: SpinLock, #[pin] pub(crate) scrub_work: Work, + #[pin] + pub(crate) feed_work: Work, // --- The completion/repoll hrtimer and the handle of its current expiry (dropping it // cancels the expiry; see `Shared::rearm`). --- #[pin] @@ -293,6 +302,10 @@ impl_has_work! { impl HasWork for Shared { self.scrub_work } } +impl_has_work! { + impl HasWork for Shared { self.feed_work } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -322,6 +335,13 @@ impl WorkItem for Shared { } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + this.feed.run(); + } +} + impl Shared { /// Records the submitting CPU and burst cadence for completion placement and wait hints. pub(crate) fn note_submitter(&self) { @@ -345,11 +365,20 @@ impl Shared { /// Temporary `drm_syncobj_wait` capacity hint while a client is submitting back to back. pub(crate) fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { - let until = self.wait_hint_until_ns.load(Ordering::Relaxed); - if cfg!(CONFIG_UCLAMP_TASK) && until != 0 && engine::now_ns() <= until { - Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) - } else { - None + self.feed.wait_hint().or_else(|| { + let until = self.wait_hint_until_ns.load(Ordering::Relaxed); + if cfg!(CONFIG_UCLAMP_TASK) && until != 0 && engine::now_ns() <= until { + Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) + } else { + None + } + }) + } + + /// Wakes the CPU feed-boost worker outside `Shared::state` when refill gaps cross threshold. + pub(crate) fn queue_feed(self: &Arc) { + if !self.sleeping.load(Ordering::Acquire) && self.feed.take_pending() { + let _ = self.feed_wq.enqueue::, FEED_WORK>(self.clone()); } } @@ -375,6 +404,7 @@ impl Shared { /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { + self.feed.begin_shutdown(); let _ = self.error .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire); @@ -506,6 +536,8 @@ impl Gpu { let drm_device: ARef = dev.into(); let events = OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)?; let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; + let feed = feed::Feed::new()?; + let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -535,11 +567,14 @@ impl Gpu { sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, scrub_wq, + feed, + feed_wq, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), scrub_work <- new_work!("g16::Shared::scrub_work"), + feed_work <- new_work!("g16::Shared::feed_work"), resnap <- HrTimer::new(), resnap_handle <- new_mutex!(None, "g16::Shared::resnap_handle"), state <- new_mutex!(None, "g16::Shared::state"), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 4ed5e8b49fac0a..adbd93d23784d6 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -152,6 +152,7 @@ impl Shared { } job::complete_all(done); self.enqueue_scrubs(scrubs); + self.queue_feed(); if !retry_tail { break; } @@ -282,6 +283,7 @@ impl Shared { }; job::complete_all(done); self.enqueue_scrubs(scrubs); + self.queue_feed(); drop(signalling); self.notify_wedged(); accepted @@ -317,6 +319,7 @@ impl Shared { }; job::complete_all(done); self.enqueue_scrubs(scrubs); + self.queue_feed(); drop(signalling); self.notify_wedged(); Some(accepted) @@ -1186,6 +1189,9 @@ impl Firmware { self.engine.retired_ticks = [0; 4]; if result.is_ok() { self.stat_retire(&f, retired_ticks); + if let Some(shared) = &self.engine.shared { + shared.feed.note_flight(f.published_ns, now_ns()); + } } if receipt.owner_retired() { if let Err(error) = self.slots.retire(&mut f.claims) { diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index fefc677481b512..2118802c2733df 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -183,6 +183,14 @@ impl ClpcHold { } } +/// Maximum inter-flight idle gap bridged for active-burst GPU demand. +/// Matches [`CLPC_IDLE_HOLD_NS`] (2 ms): back-to-back `d=1` CPU-recording bursts +/// sit well below 2 ms while 60 Hz (16.67 ms) and 120 Hz (8.33 ms) desktop frames +/// exceed it cleanly and stay at [`FLOOR`]. +const BURST_GAP_NS: u64 = CLPC_IDLE_HOLD_NS; +/// Consecutive sub-`BURST_GAP_NS` turnarounds required before bridging short gaps. +const BURST_STREAK_ON: u32 = 4; + /// Busy-time accounting over the governor's windows. The engine reports each /// publication and drain; each power service closes the window once it is due. pub(crate) struct Governor { @@ -193,6 +201,8 @@ pub(crate) struct Governor { pub(crate) top: u32, window_ns: u64, busy_since: Option, + idle_since: Option, + burst_streak: u32, busy_ns: u64, } @@ -204,19 +214,35 @@ impl Governor { top: TOP_DEFAULT, window_ns: 0, busy_since: None, + idle_since: None, + burst_streak: 0, busy_ns: 0, } } /// The engine published work; it stays busy until [`Governor::idle`]. pub(crate) fn busy(&mut self, now: u64) { - self.busy_since.get_or_insert(now); + if self.busy_since.is_none() { + if let Some(idle_at) = self.idle_since.take() { + let gap = now.saturating_sub(idle_at); + if gap < BURST_GAP_NS { + self.burst_streak = self.burst_streak.saturating_add(1); + if self.burst_streak >= BURST_STREAK_ON { + self.busy_ns = self.busy_ns.saturating_add(gap); + } + } else { + self.burst_streak = 0; + } + } + self.busy_since = Some(now); + } } /// The engine drained. pub(crate) fn idle(&mut self, now: u64) { if let Some(since) = self.busy_since.take() { self.busy_ns += now.saturating_sub(since); + self.idle_since = Some(now); } } @@ -248,6 +274,12 @@ impl Governor { // Recovery can drop flights without a drain. if !busy { self.idle(now); + if self + .idle_since + .is_some_and(|at| now.saturating_sub(at) >= BURST_GAP_NS) + { + self.burst_streak = 0; + } } let window = now.wrapping_sub(self.window_ns); if window >= WINDOW_NS { @@ -592,4 +624,46 @@ mod tests { assert!(!hold.holding()); assert!(!hold.release_now()); } + + #[test] + fn active_burst_demand_ramps_low_duty_d1_while_preserving_120hz_and_idle_decay() { + // Low-duty d=1 CPU-recording-bound burst: 170 us GPU + 600 us host gap (22% raw duty, + // < 2 ms turnaround). Bridges short refill gaps after BURST_STREAK_ON and ramps to top. + let mut g = started(); + g.top = PSTATE_MAX; + let mut t = T; + for _ in 0..8 { + g.busy(t); + g.idle(t + 170_000); + t += 770_000; + } + assert!(t - T >= RAMP_WINDOW_NS); + g.busy(t); + assert!(g.ramp_due(t, PSTATE_MAX)); + assert_eq!(g.govern(t, PSTATE_MAX, true), PSTATE_MAX); + + // Once idle, burst streak resets after 2 ms and demand decays cleanly back to FLOOR. + g.idle(t + 170_000); + let mut now = t + 170_000; + for _ in 0..20 { + now += WINDOW_NS; + let _ = g.govern(now, PSTATE_MAX, false); + } + assert_eq!(g.demand, FLOOR); + assert!(!g.decaying()); + + // 120 Hz desktop pacing (2 ms busy every 8.33 ms -> 6.33 ms gap >= 2 ms) never bridges + // gaps and stays bounded at FLOOR. + let mut g = started(); + g.top = PSTATE_MAX; + let mut now = T; + for _ in 0..16 { + g.busy(now); + assert!(g.govern(now + 2_000_000, PSTATE_MAX, true) <= FLOOR + 1); + g.idle(now + 2_000_000); + now += 8_333_333; + assert!(g.govern(now, PSTATE_MAX, false) <= FLOOR + 1); + } + assert_eq!(g.demand, FLOOR); + } } diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 2f555c3af3fbef..8f9a10f898c3f6 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -123,6 +123,9 @@ impl Shared { }; drop(pending_scrubs); self.scrub_wq.drain(); + self.feed.pause(); + self.feed_wq.drain(); + self.feed.release_floor(); } /// Waits for what's been published to retire. The poll work keeps running meanwhile. @@ -220,6 +223,7 @@ impl Shared { match left { Ok(()) => Ok(()), Err(error) => { + self.feed.resume(); self.sleeping.store(false, Ordering::Release); self.poll_now(); Err(error) @@ -260,6 +264,7 @@ impl Shared { "GPU firmware back in {} us\n", now_ns().saturating_sub(started) / 1000 ); + self.feed.resume(); self.poll_now(); Ok(()) } @@ -294,6 +299,7 @@ impl Gpu { self.shared.dev.as_ref(), "sleep refused before the commit: GPU firmware never stopped\n" ); + self.shared.feed.resume(); self.shared.sleeping.store(false, Ordering::Release); self.shared.poll_now(); return; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs index 6d01e7cfdb846e..400e8b1753e326 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-thermal-policy.rs @@ -1,4 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/power/policy.rs"] mod policy; +#[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/feed/detector.rs"] +mod feed_detector; fn main() {} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py index 1d37a11e9e99f2..422e766dd712e4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py @@ -205,10 +205,17 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, ('power.rs', 'if idle && self.power.clpc_hold.expire(now) {'), ('recovery.rs', 'self.power.release_clpc_now();'), ('sleep.rs', 'firmware.power.release_clpc_now();'), + ('poll.rs', 'shared.feed.note_flight(f.published_ns, now_ns());'), + ('mod.rs', 'self.feed.begin_shutdown();'), + ('sleep.rs', 'self.feed.pause();'), + ('sleep.rs', 'self.feed_wq.drain();'), + ('sleep.rs', 'self.feed.release_floor();'), ]: assert (G16/path).read_text().count(call) == 1, (path, call) assert (G16/'poll.rs').read_text().count('self.arm_idle_power_poll(firmware);') == 3 -print('Governor connected at publication, drain, power service and idle re-arm') +assert (G16/'poll.rs').read_text().count('self.queue_feed();') == 3 +assert (G16/'sleep.rs').read_text().count('feed.resume();') == 3 +print('Governor and CPU feed actuator connected at publication, drain, power service, sleep and idle re-arm') print(json.dumps(report,indent=2)) # Read/reattach interleavings exercise the provider's actual epoch state helpers. From fd60c5e8662754ae28eb20c9463058f3a0f33342 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 02:26:16 -0500 Subject: [PATCH 0857/1514] drm/asahi: g16: reuse clean same-VM compute WC descriptor in place On clean same-VM compute reuse (compute_needs_full_work == false && before != 0), keep the already-authenticated DESCRIPTOR (0xe00..0xea0), static NOTIFIER (0xc00..0xd18), and tail (0xee0..0xf08) intact in place, writing only 0..HEAD_ACTIVE_SIZE and BODY_ACTIVE_START..SEQ_EMBEDDED+SEQ_SIZE while preserving real firmware compute timestamps. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 36 +++++++++++++++++------------ 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index ccd9a6663bca55..0410578ce225f5 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2207,27 +2207,33 @@ impl Firmware { image(&mut scratch.cq)?, ) .map_err(|_| EINVAL)?; - if before != 0 { - // Slots::claim_compute proved a different fully retired unit displaced this - // descriptor in the same hardware slot. Keep every firmware-mutated byte. - let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; - s.work.read(work::compute::DESCRIPTOR, &mut descriptor)?; - if encode::preserve_compute_descriptor(&refs, &descriptor, before, w).is_err() { - // This is retained allocator identity/completion corruption, not a client - // refusal. Keep the unit and its previous VM lease mapped forever; cancelling - // preparation would make the corrupt descriptor available to another job. - self.slots.quarantine(&mut f.claims); - self.sync_quarantine_hints(); - return Err(EIO); + let full_work = self.slots.compute_needs_full_work(index) || before == 0; + if full_work { + if before != 0 { + // Slots::claim_compute proved a different fully retired unit displaced this + // descriptor in the same hardware slot. Keep every firmware-mutated byte. + let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; + s.work.read(work::compute::DESCRIPTOR, &mut descriptor)?; + if encode::preserve_compute_descriptor(&refs, &descriptor, before, w).is_err() { + // This is retained allocator identity/completion corruption, not a client + // refusal. Keep the unit and its previous VM lease mapped forever; cancelling + // preparation would make the corrupt descriptor available to another job. + self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); + return Err(EIO); + } } - } - if self.slots.compute_needs_full_work(index) { s.work.write(0, w)?; } else { + // Clean same-VM reuse: DESCRIPTOR (0xe00..0xea0) was already authenticated on + // retirement for this exact unit and VM, and static NOTIFIER (0xc00..0xd18) and + // tail (0xee0..0xf08) remain intact in place. Skip the 160-byte WC read-back and + // write only the active head and encoded body through the microsequence end. + let body_end = work::compute::SEQ_EMBEDDED + work::compute::SEQ_SIZE; 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], + &w[work::compute::BODY_ACTIVE_START..body_end], )?; } let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; From 30d091b8dafb7f7cfe8efb8788303090b2f538aa Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 12:08:43 -0500 Subject: [PATCH 0858/1514] drm/asahi: g16: route pipelined completion polls to an unbound workqueue Keep single-flight (d=1) completion wakeups pinned to submitter_cpu() so the sleeping drm_syncobj_wait thread wakes cache-hot, while routing pipelined (active_flights >= 2) completion wakeups onto a dedicated high-priority unbound workqueue (aurora_g16_events_unbound) so fast poll workers do not preempt an actively encoding submitter thread: - Add Shared::active_flights (published under Shared::state in run_poll, submit, try_submit_inline, and cleared on sleep_down), events_unbound, and UNBOUND_POLL_WORK / fast_poll_unbound in g16/mod.rs. - Update Shared::poll_now() in g16/poll.rs to enqueue UNBOUND_POLL_WORK on events_unbound when active_flights >= 2 and keep per-CPU FAST_POLL_WORK placement on events when active_flights <= 1. - Drain events_unbound alongside events in sleep.rs::join_workers(). - Add verbatim poll_now() placement unit tests and workqueue/sleep wiring assertions in test-poll-retire.py. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 28 ++++++ drivers/gpu/drm/asahi/g16/poll.rs | 22 ++++- drivers/gpu/drm/asahi/g16/sleep.rs | 2 + .../drivers/gpu/asahi-m4/test-poll-retire.py | 95 ++++++++++++++++++- 4 files changed, 144 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 3d1c01610ad3fa..44822839967964 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -197,6 +197,8 @@ const FAST_POLL_WORK: u64 = 1; const SCRUB_WORK: u64 = 2; /// Work item ID of the asynchronous CPU feed-boost work. const FEED_WORK: u64 = 3; +/// Work item ID of the unbound fast event poll work used when pipelined (`active_flights >= 2`). +const UNBOUND_POLL_WORK: u64 = 4; /// 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; @@ -223,6 +225,8 @@ pub(crate) struct Shared { pub(crate) publish_wake: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, + /// Number of flights currently active under `Shared::state`, for poll worker placement. + pub(crate) active_flights: AtomicU32, /// Monotonic timestamp (ns) of the previous submit, for active-burst wait hints. pub(crate) last_submit_ns: AtomicU64, /// Consecutive back-to-back submits within [`WAIT_HINT_GAP_NS`]. @@ -261,6 +265,8 @@ pub(crate) struct Shared { sleep_commit: AtomicPtr, /// Dedicated high-priority per-CPU workqueue for immediate completion polling. pub(crate) events: OwnedQueue, + /// Dedicated high-priority unbound workqueue for pipelined (`active_flights >= 2`) polling. + pub(crate) events_unbound: OwnedQueue, /// Dedicated unbound workqueue for asynchronous off-lock pass-slot WC scrubbing. pub(crate) scrub_wq: OwnedQueue, /// Host-refill CPU frequency floor actuator (mirroring G17's feed worker). @@ -274,6 +280,8 @@ pub(crate) struct Shared { #[pin] pub(crate) fast_poll: Work, #[pin] + pub(crate) fast_poll_unbound: Work, + #[pin] pub(crate) scrub_queue: SpinLock, #[pin] pub(crate) scrub_work: Work, @@ -306,6 +314,10 @@ impl_has_work! { impl HasWork for Shared { self.feed_work } } +impl_has_work! { + impl HasWork for Shared { self.fast_poll_unbound } +} + impl WorkItem for Shared { type Pointer = Arc; fn run(this: Arc) { @@ -342,6 +354,17 @@ 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 and burst cadence for completion placement and wait hints. pub(crate) fn note_submitter(&self) { @@ -535,6 +558,8 @@ impl Gpu { // 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 events_unbound = + OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_events_unbound"), true)?; let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; @@ -548,6 +573,7 @@ impl Gpu { evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), + active_flights: AtomicU32::new(0), last_submit_ns: AtomicU64::new(0), wait_hint_streak: AtomicU32::new(0), wait_hint_until_ns: AtomicU64::new(0), @@ -566,12 +592,14 @@ impl Gpu { sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, + events_unbound, scrub_wq, feed, feed_wq, orphan <- new_mutex!(None, "g16::Shared::orphan"), poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), + fast_poll_unbound <- new_work!("g16::Shared::fast_poll_unbound"), scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), scrub_work <- new_work!("g16::Shared::scrub_work"), feed_work <- new_work!("g16::Shared::feed_work"), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index adbd93d23784d6..21f917a450703e 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -38,7 +38,7 @@ use super::fw::work::compute; use super::job::{self, Completions, Job}; use super::recovery::logic::{Retirement, ABORT_GRACE_NS}; use super::regs::EngineState; -use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK}; +use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK, UNBOUND_POLL_WORK}; use crate::module_parameters; /// Cadence of periodic housekeeping (power governor, window health, administrative hang check). @@ -149,6 +149,7 @@ impl Shared { && !firmware.engine.frozen && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); + self.sync_active_flights(firmware); } job::complete_all(done); self.enqueue_scrubs(scrubs); @@ -181,6 +182,7 @@ impl Shared { } else if firmware.engine.flights.is_empty() { self.arm_idle_power_poll(firmware); } + self.sync_active_flights(firmware); } } job::complete_all(done); @@ -279,6 +281,7 @@ impl Shared { let allow_stage = firmware.recovery.failed().is_none() && !firmware.engine.frozen && !self.sleeping.load(Ordering::Acquire); + self.sync_active_flights(firmware); (res, firmware.slots.stage_and_take_scrubs(allow_stage)) }; job::complete_all(done); @@ -312,6 +315,7 @@ impl Shared { && !firmware.engine.frozen && !self.sleeping.load(Ordering::Acquire); scrubs = firmware.slots.stage_and_take_scrubs(allow_stage); + self.sync_active_flights(firmware); res } None => Err(ENODEV), @@ -376,8 +380,22 @@ impl Shared { } } - /// Queues the fast poll work immediately on the submitting CPU. Callable from any context. + /// Publishes the active flight depth for lock-free completion worker placement. + fn sync_active_flights(&self, firmware: &Firmware) { + self.active_flights + .store(firmware.engine.flights.len() as u32, Ordering::Release); + } + + /// Queues fast completion polling: pinned to the submitting CPU for single-flight (`d=1`) + /// wakeups so the sleeping waiter stays cache-hot, and unbound when pipelined (`d>=2`) so + /// completion polling does not preempt an actively recording submitter. pub(crate) fn poll_now(self: &Arc) { + if self.active_flights.load(Ordering::Acquire) >= 2 { + let _ = self + .events_unbound + .enqueue::, UNBOUND_POLL_WORK>(self.clone()); + return; + } let _ = match self.submitter_cpu() { Some(cpu) => self .events diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 8f9a10f898c3f6..261d872d2113a7 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -114,6 +114,7 @@ impl Shared { drop(unsafe { Arc::from_raw(Arc::as_ptr(self)) }); } self.events.drain(); + self.events_unbound.drain(); // `sleeping` is already set, so taking the queued scrubs under `scrub_queue` // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` // while `scrub_wq.drain()` runs. Drop the drained batch outside the spinlock. @@ -212,6 +213,7 @@ impl Shared { .and_then(|_| { if self.leave_for_commit(firmware) { firmware.power.release_clpc_now(); + self.active_flights.store(0, Ordering::Release); Ok(()) } else { Err(EBUSY) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 5befe96f289b76..b76baf312ec579 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -9,6 +9,7 @@ queue_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/queue.rs').read_text() event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() +sleep_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/sleep.rs').read_text() source = production.read_text() output = output_dir() @@ -22,6 +23,12 @@ assert ( '.add_union(engine, start, end, super::hw::COMMAND_TIMESTAMP_HZ as u32)' in source ), 'G16 poll retirement must deduplicate per-file intervals via Client::add_union' +assert ( + 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_events_unbound"), true)' in mod_source +), 'aurora_g16_events_unbound must use new_unbound_reclaim(..., true)' +assert ( + 'self.events_unbound.drain();' in sleep_source +), 'sleep.rs must drain events_unbound on suspend' def item(declaration, text=source): @@ -1035,6 +1042,91 @@ def item(declaration, text=source): // Compute union: [100k, 130k] = 30k ticks = 1_250_000 ns (not 48k ticks = 2.0 ms). assert_eq!(c_ns, 1_250_000); } + +mod poll_placement_test { + use std::sync::{ + Arc, Mutex, + atomic::{AtomicU32, Ordering}, + }; + + const FAST_POLL_WORK: u64 = 1; + const UNBOUND_POLL_WORK: u64 = 4; + + #[derive(Default)] + struct Queue { + calls: Mutex, u64)>>, + } + impl Queue { + fn enqueue(&self, _item: P) -> Result<(), ()> { + self.calls.lock().unwrap().push((None, ID)); + Ok(()) + } + fn enqueue_on(&self, cpu: u32, _item: P) -> Result<(), ()> { + self.calls.lock().unwrap().push((Some(cpu), ID)); + Ok(()) + } + fn take(&self) -> Vec<(Option, u64)> { + std::mem::take(&mut *self.calls.lock().unwrap()) + } + } + + struct Shared { + active_flights: AtomicU32, + submitter: AtomicU32, + events: Queue, + events_unbound: Queue, + } + impl Shared { + fn new() -> Arc { + Arc::new(Self { + active_flights: AtomicU32::new(0), + submitter: AtomicU32::new(u32::MAX), + events: Queue::default(), + events_unbound: Queue::default(), + }) + } + fn submitter_cpu(&self) -> Option { + let v = self.submitter.load(Ordering::Relaxed); + (v != u32::MAX).then_some(v) + } + __POLL_NOW__ + } + + #[test] + fn poll_now_pins_single_flight_and_routes_pipelined_flights_unbound() { + let shared = Shared::new(); + shared.submitter.store(3, Ordering::Relaxed); + + // d=0 and d=1 pin FAST_POLL_WORK onto the submitting CPU. + shared.active_flights.store(0, Ordering::Release); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(Some(3), FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + shared.active_flights.store(1, Ordering::Release); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(Some(3), FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + // Without a recorded submitter CPU, d=1 falls back to events.enqueue(). + shared.submitter.store(u32::MAX, Ordering::Relaxed); + shared.poll_now(); + assert_eq!(shared.events.take(), vec![(None, FAST_POLL_WORK)]); + assert!(shared.events_unbound.take().is_empty()); + + // d>=2 routes UNBOUND_POLL_WORK onto events_unbound even with a valid submitter CPU. + shared.submitter.store(3, Ordering::Relaxed); + for depth in [2u32, 4, 16] { + shared.active_flights.store(depth, Ordering::Release); + shared.poll_now(); + assert!(shared.events.take().is_empty()); + assert_eq!( + shared.events_unbound.take(), + vec![(None, UNBOUND_POLL_WORK)] + ); + } + } +} ''' harness = harness.replace( @@ -1048,6 +1140,7 @@ def item(declaration, text=source): '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', '__REARM__': 'pub(crate) fn rearm(', + '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): harness = harness.replace(token, item(decl)) for token, decl in { @@ -1073,7 +1166,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 12, + 'tests': 14, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', From 55ac312d04469c7ef3e1a18d66098c8a1106c43b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 19 Nov 2026 23:17:09 -0500 Subject: [PATCH 0859/1514] drm/asahi: admit the USC cache invalidate in the G15/G16 VDM root barrier The G15 (M3 Pro/Max) and G16 (M4) VDM stream gates admit a render only when its VDM stream starts with exactly 0x21000960. Mesa's AGX3 render-start barrier sets bit 3, the USC cache invalidate (0x21000968), so that the USC sees memory written since the previous render; on those GPUs it has to leave the bit out, or the render is refused with EINVAL. Admit the root barrier with or without the invalidate in both gates. The other backends do not check the root word, so every GPU now admits it: report that on every GPU with DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE, so userspace can set the bit whenever the kernel reports it and keep the plain word on older kernels. Bit 40 is unused in both the canonical and the G15 feature numbering. Signed-off-by: Erik Bourget Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 2 ++ drivers/gpu/drm/asahi/g15/gate.rs | 11 ++++++++--- drivers/gpu/drm/asahi/g15/params.rs | 7 ++++--- drivers/gpu/drm/asahi/g16/gate.rs | 5 ++++- drivers/gpu/drm/asahi/g16/params.rs | 8 ++++---- include/uapi/drm/asahi_drm.h | 9 +++++++++ .../drivers/gpu/asahi-m4/test-stream-gate.py | 4 +++- 7 files changed, 34 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 1505a9ac5dc410..8f080ae83a41f6 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -629,6 +629,8 @@ impl File { gpu.get_params(&mut params)?; params.features |= gpu.feature_flags(); + // Every backend admits the USC cache invalidate in the VDM root barrier. + params.features |= uapi::DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE as u64; if Self::supports_user_memory(reg_data) { params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64; } diff --git a/drivers/gpu/drm/asahi/g15/gate.rs b/drivers/gpu/drm/asahi/g15/gate.rs index 09e4d1855031db..c4a233e5917991 100644 --- a/drivers/gpu/drm/asahi/g15/gate.rs +++ b/drivers/gpu/drm/asahi/g15/gate.rs @@ -2,7 +2,9 @@ //! Stream admission gates (safety nets for userspace encoders). //! -//! VDM: the root stream's first word is 0x21000960. CDM walk from `cdm_ctrl_stream_base` through +//! VDM: the root stream's first word is 0x21000960, or 0x21000968 with the USC cache invalidate. +//! +//! CDM walk from `cdm_ctrl_stream_base` through //! links until TERMINATE (0x40000000), at most 64 links and [`CDM_MAX_BYTES`] of records (a //! longer or cyclic stream is rejected): barriers 0x60000160, 0x60001560, 0x600215fe, 0x600201fe; //! link 0x2000XXXX; direct launch (40 B, the G15 layout), indirect launches 36 B @@ -20,6 +22,8 @@ use super::{command::cover, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -148,7 +152,8 @@ fn arguments(vm: &mut mmu::VmReadGuard<'_>, address: u64, checked: &mut Checked) Ok(()) } -/// VDM admission: a normal root stream opens with exactly the G15 barrier. +/// VDM admission: a normal root stream opens with the G15 barrier, with or +/// without the USC cache invalidate. pub(crate) fn vdm(vm: &mut mmu::VmReadGuard<'_>, va: u64) -> Result { if !params::stream_gate() { return Ok(()); @@ -156,7 +161,7 @@ pub(crate) fn vdm(vm: &mut mmu::VmReadGuard<'_>, va: u64) -> Result { let mut bytes = [0u8; 4]; vm.read_user(va, &mut bytes).map_err(|_| EFAULT)?; let word = u32::from_le_bytes(bytes); - if word != VDM_ROOT { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { return Err(reject("VDM root", va, &[word])); } Ok(()) diff --git a/drivers/gpu/drm/asahi/g15/params.rs b/drivers/gpu/drm/asahi/g15/params.rs index c2c34864750611..17ac71c28aa225 100644 --- a/drivers/gpu/drm/asahi/g15/params.rs +++ b/drivers/gpu/drm/asahi/g15/params.rs @@ -3,9 +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`, -//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`), the feature -//! word is exactly 0x3e (0xbe with `g15_early_tiling`). Never advertise SOFT_FAULTS, -//! FEW_PRIMITIVES or RENDER_RAY_QUERY on G15S. +//! INDEPENDENT_QUEUES from `queue_limits`, SOFT_FAULTS suppressed by `soft_faults`, and +//! VDM_USC_INVALIDATE, bit 40 in both numberings), the feature word is exactly 0x3e (0xbe with +//! `g15_early_tiling`) plus bit 40. Never advertise SOFT_FAULTS, FEW_PRIMITIVES or +//! RENDER_RAY_QUERY on G15S. use kernel::prelude::*; diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 06050e5d83fe57..ea630e19456acd 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -21,6 +21,8 @@ use super::{command::cover_locked, command::USC_WINDOW, params}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; +/// USC cache invalidate bit of the VDM root barrier (DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE). +const VDM_ROOT_USC_INVAL: u32 = 0x8; const CDM_TERMINATE: u32 = 0x40000000; const CDM_BARRIERS: [u32; 4] = [0x60000160, 0x600215fe, 0x60001560, 0x600201fe]; const CDM_LINK: u32 = 0x20000000; @@ -120,6 +122,7 @@ fn program( } /// VDM admission for a batch of root streams under an already-held VM read lock. +/// Each root stream opens with the G16 barrier, with or without the USC cache invalidate. /// Reads only the 4-byte root word for a single pass to minimize PoC cache maintenance, /// and caches up to 256 intra-page bytes across multi-pass batches. pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Result { @@ -145,7 +148,7 @@ pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> } let off = (va - win_va) as usize; let word = u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]); - if word != VDM_ROOT { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { return Err(reject("VDM root", va, &[word])); } } diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 0ebae97fe47bb0..7a3c99563a1019 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`, and `INDEPENDENT_QUEUES` from `queue_limits`), G16 -//! advertises per-command input readiness/errors, exact queue-local historical prefixes, -//! fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent logical -//! queues, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not advertised. +//! SOFT_FAULTS suppressed by `soft_faults`, VDM_USC_INVALIDATE, and `INDEPENDENT_QUEUES` from +//! `queue_limits`), G16 advertises per-command input readiness/errors, exact queue-local historical +//! prefixes, fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent +//! logical queues, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not advertised. use kernel::{prelude::*, uapi}; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index c0f82e8f0d2454..db053aef622781 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -531,6 +531,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_RENDER_MESH_OUTPUT ((1ULL) << 38) +/* + * DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE: the render-start VDM barrier at the + * root of a render's VDM stream may set the USC cache invalidate (bit 3). + * Reported on every GPU: the kernel's stream checks admit the barrier word + * with or without it. A feature bit like those of enum drm_asahi_feature, + * defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE ((1ULL) << 40) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index b8be082c0b5503..38eb620a86d788 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -292,7 +292,9 @@ } #[test] fn vdm_m4_root_barrier() { - assert!(vdm_check(&vm_for(&[0x21000960]), &[BASE]).is_ok()); + for word in [0x21000960, 0x21000968] { + assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_ok()); + } for word in [0, 0x21000964, 0x40000000] { assert!(vdm_check(&vm_for(&[word]), &[BASE]).is_err()); } From 60b9af8b9dbfb77a61961194fb8291b01df77e67 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 15:06:30 -0500 Subject: [PATCH 0860/1514] drm/asahi: g16: support DRM_ASAHI_RENDER_FEW_PRIMITIVES Advertise DRM_ASAHI_FEATURE_FEW_PRIMITIVES in G16 GET_PARAMS, admit DRM_ASAHI_RENDER_FEW_PRIMITIVES in both parse_stream() and check_render(), and forward it to bit 0 of ISP register 0x15021 via Geometry::isp_control. This lets Mesa avoid full-tile-list overhead on tiny draws and clears on M4 (G16G). Keep this strictly isolated from VDM_USC_INVALIDATE so G16G hardware can be verified independently (M4 Pro T6040 previously exhibited a hang with 0x15021 bit 0 set). Add host selftest coverage in test-command-stream.py and check-abi-26b123.rs for both stream admission and 0x15021 encoding. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 3 ++ drivers/gpu/drm/asahi/g16/encode.rs | 4 +- drivers/gpu/drm/asahi/g16/params.rs | 4 +- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 17 ++++++++ .../gpu/asahi-m4/test-command-stream.py | 40 +++++++++++++++++-- 5 files changed, 62 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 65927544b46d1e..e20d4c11c2ff53 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -36,6 +36,7 @@ const VERTEX_SCRATCH: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_VERTEX const PROCESS_EMPTY_TILES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES; 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 FEW_PRIMITIVES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES; const FRAGMENT_BARRIERS: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGE_PREFIXES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; const COMPUTE_NO_QUERY_ACCESS: u32 = @@ -530,6 +531,7 @@ fn validate_render_entry( // M4 HAL200 resource words carry all four high halves. let allowed = PROCESS_EMPTY_TILES | DBIAS_IS_INT + | FEW_PRIMITIVES | RSRC_SPEC_HI | if early_tiling { FRAGMENT_BARRIERS | STAGE_PREFIXES @@ -871,6 +873,7 @@ fn check_render( let allowed = PROCESS_EMPTY_TILES | RSRC_SPEC_HI | DBIAS_IS_INT + | FEW_PRIMITIVES | if super::params::early_tiling() { FRAGMENT_BARRIERS | STAGE_PREFIXES } else { diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index af7c52237c5cd6..a18e33dcdd1946 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -174,7 +174,9 @@ impl Geometry { ) as u32 | log2s << 17; g.tile_mode = 0x280 | u32::from(l > 1) | if empty { 1 << 16 } else { 0 }; - g.isp_control = 0xc000 | (u.flags & (1 << 18)); + let few_primitives = + u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES != 0; + g.isp_control = 0xc000 | (u.flags & (1 << 18)) | u32::from(few_primitives); g.native_tiles = 0x3717fu64 | u64::from(l > 1) << 32 | u64::from(g.tx.wrapping_sub(1)) << 44 diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 7a3c99563a1019..b49f4459ebb328 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -6,7 +6,8 @@ //! SOFT_FAULTS suppressed by `soft_faults`, VDM_USC_INVALIDATE, and `INDEPENDENT_QUEUES` from //! `queue_limits`), G16 advertises per-command input readiness/errors, exact queue-local historical //! prefixes, fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent -//! logical queues, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not advertised. +//! logical queues, `FEW_PRIMITIVES`, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not +//! advertised. use kernel::{prelude::*, uapi}; @@ -98,6 +99,7 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | 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_COMPUTE_NO_QUERY_ACCESS) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = GPU_GENERATION; params.gpu_variant = gpu.cfg.gpu_variant as u32; 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 d766bcdbb9646a..fb18eeabdaf83e 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 @@ -139,6 +139,14 @@ fn render(out: &std::path::Path) { aux_gva: g + 0xb00000, ..Default::default() }; let geo = encode::Geometry::new(&u, p.heap_gva); + assert_eq!(geo.isp_control, 0xc000); + let mut u_few = u; + u_few.flags |= uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES; + let geo_few = encode::Geometry::new(&u_few, p.heap_gva); + assert_eq!(geo_few.isp_control, 0xc001); + let mut u_few_dbias = u_few; + u_few_dbias.flags |= uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_DBIAS_IS_INT; + assert_eq!(encode::Geometry::new(&u_few_dbias, p.heap_gva).isp_control, 0x4c001); 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)] { @@ -146,6 +154,15 @@ fn render(out: &std::path::Path) { 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); + // Verify FEW_PRIMITIVES sets bit 0 of ISP register 0x15021 (fs::SEL[21]). + let mut fw_few = [0xa5; fs::WORK_SIZE]; + let mut fq_few = [0xa5; fs::SEQ_SIZE]; + encode::encode_fs_for( + fs_layout, &r, &p, &u_few, &ts, 7, 1 << 40, 1, 0x300, &geo_few, + &mut fw_few, &mut fq_few, + ); + assert_eq!(r32(&fw_few, fs::REGS + 21 * 12), 0x15021); + assert_eq!(r64(&fw_few, fs::REGS + 21 * 12 + 4), 0xc001); images.push((tw, tq, fw_, fq)); } // The 25G83 entry points are the 25G83 layouts. 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 1d42a67358760e..f82db0888f8071 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 @@ -432,7 +432,7 @@ } #[test] fn unsupported_flags_and_compute_fields() { - for flag in [1u32,4,1<<19,FRAGMENT_BARRIERS] { + for flag in [1u32,4,1<<21,FRAGMENT_BARRIERS] { let mut r=render(); r.flags=flag; assert!(check_stream(&entry(CMD_RENDER,&data(&r)[..256],[NONE;2]),false).is_err()); } @@ -630,9 +630,9 @@ } mod render_admission_tests { use super::{ - check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FRAGMENT_BARRIERS, - MAX_DIMENSION, MAX_LAYERS, MAX_TILE_BUFFER, PROCESS_EMPTY_TILES, RSRC_SPEC_HI, - STAGE_PREFIXES, ZLS_METADATA_STRIDE, + check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FEW_PRIMITIVES, + FRAGMENT_BARRIERS, MAX_DIMENSION, MAX_LAYERS, MAX_TILE_BUFFER, PROCESS_EMPTY_TILES, + RSRC_SPEC_HI, STAGE_PREFIXES, ZLS_METADATA_STRIDE, }; const ENOENT: i32 = -2; const EACCES: i32 = -13; @@ -854,6 +854,38 @@ assert_eq!(check_render(&mut batch, &ctx, &bad_ro, &[], &[]), Ok(())); assert_eq!(batch.flush(&vm), Err(EACCES)); } + + #[test] + fn few_primitives_flag_admitted_in_parse_and_render_check() { + let vm = base_vm(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let mut r = super::render(); + r.flags = FEW_PRIMITIVES; + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + false, + ) + .is_ok()); + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + true, + ) + .is_ok()); + r.flags = FEW_PRIMITIVES | DBIAS_IS_INT; + assert!(super::check_stream( + &super::entry(super::CMD_RENDER, &super::data(&r)[..256], [super::NONE; 2]), + false, + ) + .is_ok()); + let mut cmd = base_cmd(); + cmd.flags |= FEW_PRIMITIVES; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); + cmd.isp_dbias_base = BASE_GVA + 0x200; + cmd.flags |= DBIAS_IS_INT; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Ok(())); + cmd.flags |= 1 << 21; + assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Err(EINVAL)); + } } ''' replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, From e355c7ee379252198d6205e3edf4398a14bbf384 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 15:39:56 -0500 Subject: [PATCH 0861/1514] drm/asahi: g16: defer housekeeping off SUBMIT, adapt repoll, and pin unbound cluster Eliminate 300-648 us p95 latency bubbles and cross-cluster completion bounces on G16: - Never run synchronous full housekeeping (publish(), power service, auxiliary ring drains, hang checks) on the SUBMIT thread when the 1 ms housekeeping period expires; keep submit_locked() on publish_checked() unless recovery is pending and kick poll_now() so run_housekeeping() executes asynchronously after completion fences are signalled. - Throttle auxiliary log/ktrace/stats ring drains in run_housekeeping() to 10 ms while flights are active, preserving immediate drains when idle or recovering. - Arm a short repoll when submit_locked() consumes an EP 0x20 event and retires an older flight while later flights remain active, so a coalesced completion does not wait a full resnap window. - Adapt the fallback hrtimer repoll interval smoothly down to clamp(ewma_flight_us / 2, repoll_us, resnap_us) on sub-2*resnap_us bursts while respecting g16_repoll_us=0. - Restrict aurora_g16_events_unbound to the submitter's CPU cluster when the cluster changes during SUBMIT so pipelined completions stay in the submitter's cluster instead of migrating onto E-cores. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 51 ++++++- drivers/gpu/drm/asahi/g16/poll.rs | 71 +++++++--- .../drivers/gpu/asahi-m4/test-poll-retire.py | 133 +++++++++++++++++- .../gpu/asahi-m4/test-thermal-policy.py | 2 +- 4 files changed, 230 insertions(+), 27 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 44822839967964..2065837eaf959f 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -225,8 +225,16 @@ pub(crate) struct Shared { pub(crate) publish_wake: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, + /// CPU whose cluster currently restricts `events_unbound` (`u32::MAX` before first pin). + unbound_cluster_cpu: AtomicU32, + /// Serializes best-effort `events_unbound.restrict()` updates without blocking concurrent + /// submitters on `wq_pool_mutex`. + unbound_pinning: AtomicBool, /// Number of flights currently active under `Shared::state`, for poll worker placement. pub(crate) active_flights: AtomicU32, + /// Smoothed recent flight duration in microseconds (0 before first retirement), used to + /// shorten the fallback hrtimer interval on sub-100 us workloads. + pub(crate) ewma_flight_us: AtomicU32, /// Monotonic timestamp (ns) of the previous submit, for active-burst wait hints. pub(crate) last_submit_ns: AtomicU64, /// Consecutive back-to-back submits within [`WAIT_HINT_GAP_NS`]. @@ -367,9 +375,31 @@ impl WorkItem for Shared { impl Shared { /// Records the submitting CPU and burst cadence for completion placement and wait hints. + /// Runs in process context during SUBMIT; keeps `events_unbound` pinned to the submitter's + /// CPU cluster so pipelined completion polls stay on the same cluster (avoiding E-core + /// wake bounces while still sparing the submitter CPU itself). pub(crate) fn note_submitter(&self) { - self.submitter - .store(kernel::cpu::CpuId::current().as_u32(), Ordering::Relaxed); + let cpu = kernel::cpu::CpuId::current(); + self.submitter.store(cpu.as_u32(), Ordering::Relaxed); + let pinned = self.unbound_cluster_cpu.load(Ordering::Acquire); + if pinned != cpu.as_u32() + && !kernel::cpu::CpuId::from_u32(pinned) + .is_some_and(|p| kernel::cpumask::Cpumask::cluster_of(p).test(cpu)) + && self + .unbound_pinning + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) + .is_ok() + { + if self + .events_unbound + .restrict(kernel::cpumask::Cpumask::cluster_of(cpu)) + .is_ok() + { + self.unbound_cluster_cpu + .store(cpu.as_u32(), Ordering::Release); + } + self.unbound_pinning.store(false, Ordering::Release); + } let now = engine::now_ns(); let prev = self.last_submit_ns.swap(now, Ordering::Relaxed); if prev != 0 && now.wrapping_sub(prev) <= WAIT_HINT_GAP_NS { @@ -386,6 +416,17 @@ impl Shared { } } + /// Updates the lock-free EWMA of recent retired flight durations (microseconds). + pub(crate) fn note_flight_us(&self, us: u32) { + let prev = self.ewma_flight_us.load(Ordering::Relaxed); + let next = if prev == 0 { + us + } else { + (prev.saturating_mul(3).saturating_add(us)) / 4 + }; + self.ewma_flight_us.store(next, 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)> { self.feed.wait_hint().or_else(|| { @@ -522,6 +563,8 @@ pub(crate) struct Firmware { pub(crate) vms: Arc, /// Monotonic timestamp (ns) of the last full housekeeping pass (power, health, hang poll). pub(crate) last_housekeeping_ns: u64, + /// Monotonic timestamp (ns) of the last auxiliary (log/ktrace/stats) ring drain. + pub(crate) last_aux_drain_ns: u64, } /// A G16 GPU. @@ -573,7 +616,10 @@ impl Gpu { evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), + unbound_cluster_cpu: AtomicU32::new(u32::MAX), + unbound_pinning: AtomicBool::new(false), active_flights: AtomicU32::new(0), + ewma_flight_us: AtomicU32::new(0), last_submit_ns: AtomicU64::new(0), wait_hint_streak: AtomicU32::new(0), wait_hint_until_ns: AtomicU64::new(0), @@ -723,6 +769,7 @@ impl Firmware { pools, vms, last_housekeeping_ns: 0, + last_aux_drain_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 21f917a450703e..fd4669660e7fda 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -43,6 +43,8 @@ use crate::module_parameters; /// Cadence of periodic housekeeping (power governor, window health, administrative hang check). const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Minimum interval between auxiliary log/ktrace/stats ring drains while flights are active. +const AUX_DRAIN_NS: u64 = 10_000_000; /// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/3/4/5 us, 45 us total). const EVENT_RETIRE_POLLS: u32 = 11; /// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). @@ -208,17 +210,15 @@ impl Shared { let had_flights = !firmware.engine.flights.is_empty(); let was_evented = had_flights && self.evented.swap(false, Ordering::AcqRel); let recovery_pending = firmware.recovery_pending().unwrap_or(true); + let mut retired_any = false; let mut pub_res = Ok(()); if had_flights - && (was_evented - || housekeeping_due - || recovery_pending - || firmware.oldest_stamp_reached()) + && (was_evented || recovery_pending || firmware.oldest_stamp_reached()) { let stage_before = firmware.events.stage_events; let term_before = firmware.oldest_terminal_events(); pub_res = firmware.session.transport().and_then(|()| { - let retired_any = firmware.retire_once(done)?; + retired_any = firmware.retire_once(done)?; firmware.answer_growth()?; if firmware.recovery.receipt_fault || recovery_pending { firmware.check_hangs(done)?; @@ -238,10 +238,11 @@ impl Shared { }); } if pub_res.is_ok() { - pub_res = if housekeeping_due || recovery_pending { + pub_res = if recovery_pending { let r = firmware.publish(done); if r.is_ok() { firmware.last_housekeeping_ns = now; + firmware.last_aux_drain_ns = now; } r } else { @@ -259,11 +260,19 @@ impl Shared { self.fail_stop(error); } if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { - self.rearm(firmware.engine.chan_wait); + // If an EP 0x20 event retired an older flight while later flights remain active, + // arm a short repoll in case another completion coalesced into that interrupt. + self.rearm( + firmware.engine.chan_wait + || (was_evented && retired_any && !firmware.engine.flights.is_empty()), + ); } else { firmware.power.report_work(false); self.arm_idle_power_poll(firmware); } + if housekeeping_due && !recovery_pending && pub_res.is_ok() { + self.poll_now(); + } } accepted } @@ -437,16 +446,33 @@ impl Shared { }; } + /// Computes the hrtimer repoll delay in microseconds: `repoll_us` when `soon`, otherwise + /// adapts down to `clamp(ewma_flight_us / 2, repoll_us, resnap_us)` on sub-`2 * resnap_us` + /// bursts while respecting `g16_repoll_us == 0` as a full disable of shortened repolls. + pub(crate) fn rearm_us(&self, soon: bool) -> u32 { + let resnap = params::resnap_us(); + if module_parameters::g16_repoll_us.value() == 0 { + return resnap; + } + let repoll = params::repoll_us(); + if soon { + return repoll; + } + let ewma = self.ewma_flight_us.load(Ordering::Relaxed); + if ewma != 0 && ewma < resnap.saturating_mul(2) { + (ewma / 2).clamp(repoll, resnap) + } else { + resnap + } + } + /// 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) { if self.sleeping.load(Ordering::Acquire) { return; } - let mut us = params::resnap_us(); - if soon && module_parameters::g16_repoll_us.value() != 0 { - us = params::repoll_us(); - } + let us = self.rearm_us(soon); let now = now_ns(); let target_ns = now.saturating_add(u64::from(us) * 1000); let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); @@ -532,6 +558,7 @@ impl Firmware { self.objects.health()?; self.service_power()?; self.last_housekeeping_ns = now; + self.last_aux_drain_ns = now; ran_housekeeping = true; self.drain_rings()?; if self.recovery_idle()? && self.engine.pending.is_empty() { @@ -647,12 +674,17 @@ impl Firmware { self.session.check()?; self.objects.health()?; self.service_power()?; - self.drain_auxiliary_rings()?; - self.last_housekeeping_ns = now_ns(); - if !self.engine.flights.is_empty() - || self.recovery.receipt_fault - || self.recovery_pending()? + let now = now_ns(); + let recovery_pending = self.recovery.receipt_fault || self.recovery_pending()?; + if self.engine.flights.is_empty() + || recovery_pending + || now.wrapping_sub(self.last_aux_drain_ns) >= AUX_DRAIN_NS { + self.drain_auxiliary_rings()?; + self.last_aux_drain_ns = now; + } + self.last_housekeeping_ns = now; + if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; } Ok(()) @@ -1208,7 +1240,12 @@ impl Firmware { if result.is_ok() { self.stat_retire(&f, retired_ticks); if let Some(shared) = &self.engine.shared { - shared.feed.note_flight(f.published_ns, now_ns()); + let now = now_ns(); + shared.feed.note_flight(f.published_ns, now); + if f.published_ns != 0 && now > f.published_ns { + let dur_us = ((now - f.published_ns) / 1000).clamp(1, 10_000) as u32; + shared.note_flight_us(dur_us); + } } } if receipt.owner_retired() { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index b76baf312ec579..c765ada5b31b81 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -51,6 +51,7 @@ def item(declaration, text=source): type Result = std::result::Result; const HOUSEKEEPING_NS: u64 = 1_000_000; +const AUX_DRAIN_NS: u64 = 10_000_000; const EVENT_RETIRE_POLLS: u32 = 11; thread_local! { @@ -195,6 +196,8 @@ def item(declaration, text=source): publish_wake: AtomicBool, rearmed: Cell, idle_power_polls: Cell, + rearm_soon: Cell, + poll_now_calls: Cell, } impl Shared { fn new() -> Arc { @@ -204,10 +207,18 @@ def item(declaration, text=source): publish_wake: AtomicBool::new(false), rearmed: Cell::new(0), idle_power_polls: Cell::new(0), + rearm_soon: Cell::new(0), + poll_now_calls: Cell::new(0), }) } - fn rearm(&self, _soon: bool) { + fn rearm(&self, soon: bool) { self.rearmed.set(self.rearmed.get() + 1); + if soon { + self.rearm_soon.set(self.rearm_soon.get() + 1); + } + } + fn poll_now(&self) { + self.poll_now_calls.set(self.poll_now_calls.get() + 1); } fn arm_idle_power_poll(&self, _firmware: &Firmware) { self.idle_power_polls.set(self.idle_power_polls.get() + 1); @@ -252,6 +263,7 @@ def item(declaration, text=source): power: Power, slots: Slots, last_housekeeping_ns: u64, + last_aux_drain_ns: u64, // Test script knobs for retire_once / publish / housekeeping observation. retire_on_call: bool, unfreeze_on_hang_check: bool, @@ -262,6 +274,7 @@ def item(declaration, text=source): publish_full_calls: u32, publish_checked_calls: u32, housekeeping_calls: u32, + aux_drain_calls: u32, power_calls: u32, } @@ -296,6 +309,7 @@ def item(declaration, text=source): power: Power::default(), slots: Slots::default(), last_housekeeping_ns: 0, + last_aux_drain_ns: 0, retire_on_call: false, unfreeze_on_hang_check: false, drain_stage_delta: 0, @@ -305,6 +319,7 @@ def item(declaration, text=source): publish_full_calls: 0, publish_checked_calls: 0, housekeeping_calls: 0, + aux_drain_calls: 0, power_calls: 0, } } @@ -326,6 +341,10 @@ def item(declaration, text=source): fn drain_rings(&mut self) -> Result { Ok(()) } + fn drain_auxiliary_rings(&mut self) -> Result { + self.aux_drain_calls += 1; + Ok(()) + } fn answer_growth(&mut self) -> Result { Ok(()) } @@ -339,11 +358,7 @@ def item(declaration, text=source): fn fail_stop(&mut self, error: Error, _done: &mut Completions) { self.recovery.failed = Some(error); } - fn run_housekeeping(&mut self, _done: &mut Completions) -> Result { - self.housekeeping_calls += 1; - self.last_housekeeping_ns = now_ns(); - Ok(()) - } + __RUN_HOUSEKEEPING__ fn retire_once(&mut self, done: &mut Completions) -> Result { self.retire_calls += 1; self.events.stage_events += self.drain_stage_delta; @@ -419,6 +434,86 @@ def item(declaration, text=source): assert!(shared.evented.load(Ordering::Acquire)); } +#[test] +fn submit_locked_defers_housekeeping_and_arms_short_repoll_on_coalesced_event() { + // Housekeeping due (> 1 ms): submit_locked must NOT run synchronous publish(); it + // calls publish_checked() and kicks poll_now() so housekeeping runs off SUBMIT. + CLOCK.with(|c| c.set(5_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw.engine.target = 0x200; + + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_full_calls, 0); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.retire_calls, 0); + assert_eq!(shared.poll_now_calls.get(), 1); + assert_eq!(shared.rearm_soon.get(), 0); + + // Coalesced EP 0x20 event retires flight 0 while flight 1 stays active -> short repoll. + shared.evented.store(true, Ordering::Release); + fw.retire_on_call = true; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 4 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 1); + assert_eq!(fw.engine.flights.len(), 1); + assert_eq!(shared.rearm_soon.get(), 1); +} + +#[test] +fn run_housekeeping_throttles_auxiliary_ring_drain_while_flights_active() { + CLOCK.with(|c| c.set(1_000_000)); + let mut fw = Firmware::new(); + fw.last_aux_drain_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + let mut done = vec![]; + + // Within AUX_DRAIN_NS (10 ms) while busy: skip auxiliary ring drain. + CLOCK.with(|c| c.set(5_000_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 0); + + // Past AUX_DRAIN_NS while busy: drain once and advance timestamp. + CLOCK.with(|c| c.set(11_000_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 1); + + // Recovery pending bypasses throttle immediately. + CLOCK.with(|c| c.set(12_000_000)); + fw.recovery.pending = true; + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 2); + + // Idle bypasses throttle immediately. + CLOCK.with(|c| c.set(13_000_000)); + fw.recovery.pending = false; + fw.engine.flights.clear(); + fw.run_housekeeping(&mut done).unwrap(); + assert_eq!(fw.aux_drain_calls, 3); +} + #[test] fn ta_only_event_does_not_spin_or_arm_short_repoll() { CLOCK.with(|c| c.set(100_000)); @@ -927,6 +1022,7 @@ def item(declaration, text=source): struct Shared { sleeping: AtomicBool, + ewma_flight_us: AtomicU32, resnap_deadline_ns: AtomicU64, backup_deadline_ns: AtomicU64, resnap_handle: Lock>, @@ -939,6 +1035,7 @@ def item(declaration, text=source): fn new() -> Arc { Arc::new(Self { sleeping: AtomicBool::new(false), + ewma_flight_us: AtomicU32::new(0), resnap_deadline_ns: AtomicU64::new(0), backup_deadline_ns: AtomicU64::new(0), resnap_handle: Lock::new(None), @@ -958,9 +1055,29 @@ def item(declaration, text=source): } __CANCEL_RESNAP__ + __REARM_US__ __REARM__ } + #[test] + fn adaptive_rearm_us_scales_with_short_flight_ewma() { + let shared = Shared::new(); + assert_eq!(shared.rearm_us(false), 100); + assert_eq!(shared.rearm_us(true), 25); + + // Very short 30 us flights clamp to repoll_us (25 us). + shared.ewma_flight_us.store(30, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 25); + + // 100 us flights halve to 50 us. + shared.ewma_flight_us.store(100, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 50); + + // Heavy 250+ us flights stay at full resnap_us (100 us). + shared.ewma_flight_us.store(250, Ordering::Relaxed); + assert_eq!(shared.rearm_us(false), 100); + } + #[test] fn resnap_rearm_coalesces_and_cancel_disarms_unconditionally() { CLOCK.store(100_000, Ordering::Release); @@ -1136,9 +1253,11 @@ def item(declaration, text=source): for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', '__POLL_STEP__': 'pub(crate) fn poll_step(', + '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', + '__REARM_US__': 'pub(crate) fn rearm_us(', '__REARM__': 'pub(crate) fn rearm(', '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): @@ -1166,7 +1285,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 14, + 'tests': 17, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py index 422e766dd712e4..4d7690a185e50b 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py @@ -205,7 +205,7 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, ('power.rs', 'if idle && self.power.clpc_hold.expire(now) {'), ('recovery.rs', 'self.power.release_clpc_now();'), ('sleep.rs', 'firmware.power.release_clpc_now();'), - ('poll.rs', 'shared.feed.note_flight(f.published_ns, now_ns());'), + ('poll.rs', 'shared.feed.note_flight(f.published_ns, now);'), ('mod.rs', 'self.feed.begin_shutdown();'), ('sleep.rs', 'self.feed.pause();'), ('sleep.rs', 'self.feed_wq.drain();'), From 703cbfb8ec121c48ac7d0d40eeabfe26d0f2ff48 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 15:41:28 -0500 Subject: [PATCH 0862/1514] drm/asahi: g16: support DRM_ASAHI_FEATURE_CUMULATIVE_SIGNALS Enable DRM_ASAHI_FEATURE_CUMULATIVE_SIGNALS (bit 29) on G16, reusing the shared g17::sync_output::SignalBundle and asahi_g17_scope chain already compiled into aurora-y: - Allow SYNC_CUMULATIVE output sync parsing for G16 in file.rs. - Advertise FEATURE_CUMULATIVE_SIGNALS in g16/params.rs. - Consume SignalBundle in g16::fence::Syncs, publishing cumulative scopes before scheduler enqueue so ENOMEM refuses cleanly via bundle.fail() without leaving an accepted job behind, and signalling completed job fences through asahi_g17_signal_fence() so ready scopes drain synchronously on the signalling CPU instead of bouncing through irq_work. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 2 +- drivers/gpu/drm/asahi/g16/fence.rs | 43 ++++++- drivers/gpu/drm/asahi/g16/params.rs | 1 + drivers/gpu/drm/asahi/g16/queue.rs | 23 ++-- .../gpu/asahi-m4/test-fence-signalling.py | 111 +++++++++++++++++- .../gpu/asahi-m4/test-submit-restart.py | 4 +- 6 files changed, 162 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 8f080ae83a41f6..97cb20b64714a4 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -1883,7 +1883,7 @@ impl File { data.syncs, data.in_sync_count, data.out_sync_count, - gpu.as_any().is::(), + gpu.as_any().is::() || gpu.as_any().is::(), ) { Ok(syncs) => syncs, Err(e) => { diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 5c2fafc3d5d4ba..2890428717f577 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -137,6 +137,17 @@ impl FenceOps for JobFenceOps { /// Stack batch size for signalling completed fences outside `Timeline::pending`. const SIGNAL_BATCH: usize = 8; +unsafe extern "C" { + fn asahi_g17_signal_fence(fence: *mut kernel::bindings::dma_fence); +} + +/// Signals a completed job fence, draining any attached cumulative output scopes on the +/// current CPU instead of bouncing each scope through `irq_work`. +fn signal_fence(fence: &UserFence) { + // SAFETY: `fence` is a live `dma_fence` reference kept alive for the call. + unsafe { asahi_g17_signal_fence(fence.raw()) }; +} + /// An accepted fence of a timeline that has not signalled yet. struct Pending { fence: UserFence, @@ -247,7 +258,7 @@ impl Timeline { if let Err(error) = res { fence.set_error(error); } - fence.signal(); + signal_fence(&fence); } } if !more { @@ -311,15 +322,22 @@ fn install(outputs: impl Iterator, fence: &Fence) { /// The syncs of one SUBMIT. Every output sync gets a fence: the job's fence once the job is /// accepted, a signalled error fence when the submission is refused (the shared `file.rs` -/// contract of `tracked_submission`). +/// contract of `tracked_submission`). Cumulative output bundles reuse the shared +/// `g17::sync_output::SignalBundle` scope chain. pub(crate) struct Syncs { syncs: KVec, input_count: usize, + cumulative: Option, } impl Syncs { - pub(crate) fn new(syncs: KVec, input_count: usize) -> Self { - Self { syncs, input_count } + pub(crate) fn new(mut syncs: KVec, input_count: usize) -> Self { + let cumulative = syncs.iter_mut().find_map(|sync| sync.cumulative.take()); + Self { + syncs, + input_count, + cumulative, + } } /// The input syncs (all resolved to fences or already signalled). @@ -327,14 +345,27 @@ impl Syncs { &self.syncs[..self.input_count.min(self.syncs.len())] } - /// Publishes the accepted job's fence in every output sync. - pub(crate) fn accept(mut self, fence: &Fence) { + /// Publishes the job's fence in every output sync before enqueuing the job. If publishing a + /// cumulative bundle fails (`ENOMEM`), the bundle remains unpublished so [`Self::refuse`] + /// installs a signalled error fence in every target. + pub(crate) fn publish(&mut self, fence: &Fence) -> Result { let first = self.input_count.min(self.syncs.len()); + if let Some(bundle) = &mut self.cumulative { + bundle.publish(fence)?; + self.cumulative = None; + self.syncs.truncate(first); + return Ok(()); + } install(self.syncs.drain(first..), fence); + Ok(()) } /// Publishes a signalled error fence in every output sync of a refused submission. pub(crate) fn refuse(mut self, timeline: &Timeline, error: Error) { + if let Some(mut bundle) = self.cumulative.take() { + bundle.fail(&timeline.refused(error)); + return; + } let first = self.input_count.min(self.syncs.len()); if first < self.syncs.len() { install(self.syncs.drain(first..), &timeline.refused(error)); diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index b49f4459ebb328..44e7a61cdaf304 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -100,6 +100,7 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) + | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = GPU_GENERATION; params.gpu_variant = gpu.cfg.gpu_variant as u32; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index bb6866e5fdf01a..3f828490184ad6 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -30,7 +30,7 @@ //! ordinal, or depending on its failed prefix, cannot execute. The VM remains usable. use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use kernel::{dma_fence::Fence, prelude::*, sync::Arc, uapi, xarray}; +use kernel::{prelude::*, sync::Arc, uapi, xarray}; use super::{ command::{self, USC_WINDOW}, @@ -191,15 +191,15 @@ impl Queue { }) } - /// Validates a SUBMIT and pushes its job; returns the job's fence. + /// Validates a SUBMIT, publishes its output syncs, and pushes its job. fn submit_job( &mut self, id: u64, - syncs: &Syncs, + syncs: &mut Syncs, sync_count: usize, bytes: &[u8], objects: Pin<&xarray::XArray>>, - ) -> Result { + ) -> Result { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } @@ -254,11 +254,15 @@ impl Queue { inputs, )?; let published = job.fence.fence(); + // Publish output syncs (including fallible cumulative scope allocation) before pushing + // to the scheduler so ENOMEM refuses cleanly without leaving an accepted job behind. + // If `scheduler.push` later fails, dropping `job` signals `published` with ECANCELED. + syncs.publish(&published)?; self.scheduler.push(job, self.shared.clone())?; // Accepted: retain bounded per-engine accounting for later submissions. self.accepted[command::RENDER] += submission.counts[command::RENDER]; self.accepted[command::COMPUTE] += submission.counts[command::COMPUTE]; - Ok(published) + Ok(()) } } @@ -273,12 +277,9 @@ impl crate::queue::Queue for Queue { objects: Pin<&xarray::XArray>>, ) -> Result { let sync_count = syncs.len(); - let syncs = Syncs::new(syncs, in_sync_count); - match self.submit_job(id, &syncs, sync_count, cmdbuf_raw, objects) { - Ok(fence) => { - syncs.accept(&fence); - Ok(()) - } + let mut syncs = Syncs::new(syncs, in_sync_count); + match self.submit_job(id, &mut syncs, sync_count, cmdbuf_raw, objects) { + Ok(()) => Ok(()), Err(error) => { // A refused submission leaves the VM usable unless the device is lost. self.vm.status.record_if_device_loss(error); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 0409bc0b4157d4..c0dd3e2616dcc9 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -92,6 +92,9 @@ def extract_function(text, name): fence_source.index('/// Inline storage for the common 0-2 input fences'): fence_source.index('/// Reads a retained dependency') ] +syncs_src = fence_source[ + fence_source.index('/// The syncs of one SUBMIT.'): +] timeline_harness = r''' #![allow(dead_code)] @@ -214,6 +217,10 @@ def extract_function(text, name): } } +fn signal_fence(fence: &UserFence) { + fence.signal(); +} + SIGNAL_BATCH_LINE struct Pending { @@ -312,9 +319,109 @@ def extract_function(text, name): assert!(tl.pending.lock().is_empty()); } } + +mod cumulative_syncs_test { + use super::{Error, Result, EIO, ENOMEM}; + use std::cell::RefCell; + use std::rc::Rc; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Fence(pub(crate) i32); + + pub(crate) struct Timeline; + impl Timeline { + pub(crate) fn refused(&self, error: Error) -> Fence { + Fence(error.0) + } + } + + pub(crate) mod g17 { + pub(crate) mod sync_output { + use super::super::{Fence, Result, ENOMEM}; + use std::cell::RefCell; + use std::rc::Rc; + + #[derive(Default)] + pub(crate) struct BundleLog { + pub(crate) published: Vec, + pub(crate) failed: Vec, + pub(crate) fail_publish: bool, + } + + pub(crate) struct SignalBundle(pub(crate) Rc>); + impl SignalBundle { + pub(crate) fn publish(&mut self, fence: &Fence) -> Result { + let mut log = self.0.borrow_mut(); + if log.fail_publish { + return Err(ENOMEM); + } + log.published.push(*fence); + Ok(()) + } + pub(crate) fn fail(&mut self, fence: &Fence) { + self.0.borrow_mut().failed.push(*fence); + } + } + } + } + + pub(crate) struct SyncItem { + pub(crate) installed: Rc>>, + pub(crate) cumulative: Option, + } + + pub(crate) type KVec = Vec; + + fn install(outputs: impl Iterator, fence: &Fence) { + for sync in outputs { + sync.installed.borrow_mut().push(*fence); + } + } + + SYNCS_SRC + + #[test] + fn cumulative_bundle_publishes_and_handles_oom_refusal_cleanly() { + let log = Rc::new(RefCell::new(g17::sync_output::BundleLog::default())); + let out_log = Rc::new(RefCell::new(Vec::new())); + let items = vec![ + SyncItem { installed: out_log.clone(), cumulative: None }, + SyncItem { + installed: out_log.clone(), + cumulative: Some(g17::sync_output::SignalBundle(log.clone())), + }, + ]; + let mut syncs = Syncs::new(items, 1); + assert_eq!(syncs.inputs().len(), 1); + syncs.publish(&Fence(42)).unwrap(); + assert_eq!(log.borrow().published, vec![Fence(42)]); + assert!(log.borrow().failed.is_empty()); + assert!(out_log.borrow().is_empty()); + // Calling refuse() after successful publish() is a no-op. + syncs.refuse(&Timeline, EIO); + assert!(log.borrow().failed.is_empty()); + + // ENOMEM during publish() leaves bundle armed so refuse() installs error fence. + let log2 = Rc::new(RefCell::new(g17::sync_output::BundleLog { + fail_publish: true, + ..Default::default() + })); + let items2 = vec![SyncItem { + installed: out_log.clone(), + cumulative: Some(g17::sync_output::SignalBundle(log2.clone())), + }]; + let mut syncs2 = Syncs::new(items2, 0); + assert_eq!(syncs2.publish(&Fence(99)), Err(ENOMEM)); + assert!(log2.borrow().published.is_empty()); + syncs2.refuse(&Timeline, ENOMEM); + assert_eq!(log2.borrow().failed, vec![Fence(ENOMEM.0)]); + } +} '''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( 'TIMELINE_COMPLETE_FN', timeline_complete_fn -).replace('INPUT_FENCES_SRC', input_fences_src) +).replace('INPUT_FENCES_SRC', input_fences_src).replace( + 'SYNCS_SRC', syncs_src.replace('crate::g17::', 'g17::') +) with tempfile.TemporaryDirectory(prefix='m4-rust-timeline-') as directory: directory = pathlib.Path(directory) @@ -333,7 +440,7 @@ def extract_function(text, name): raise SystemExit(result.returncode) (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 7, 'negative_compile_checks': 1, 'cpu_only': True, + 'passed': True, 'tests': 8, 'negative_compile_checks': 1, 'cpu_only': True, 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants and g16 Timeline::complete() off-pending FIFO batch signalling.', 'source_sha256': sha(production), 'timeline_source_sha256': sha(fence_source_path), diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py index a920eae57ee3aa..adbbf7cdaa39f6 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py @@ -16,10 +16,10 @@ mod file{pub struct SyncItem;pub struct Object;} mod driver{pub struct AsahiRegData<'a>(pub &'a ());} static ACCEPTED:AtomicU32=AtomicU32::new(0);static REFUSED:AtomicU32=AtomicU32::new(0); -struct Syncs;impl Syncs{fn new(_v:Vec,_n:usize)->Self{Self}fn accept(&self,_f:&u32){ACCEPTED.fetch_add(1,Ordering::SeqCst);}fn refuse(&self,_t:&(),error:i32){assert_ne!(error,ERESTARTSYS);REFUSED.fetch_add(1,Ordering::SeqCst);}} +struct Syncs;impl Syncs{fn new(_v:Vec,_n:usize)->Self{Self}fn publish(&mut self,_f:&u32)->Result{ACCEPTED.fetch_add(1,Ordering::SeqCst);Ok(())}fn refuse(&self,_t:&(),error:i32){assert_ne!(error,ERESTARTSYS);REFUSED.fetch_add(1,Ordering::SeqCst);}} struct Status;impl Status{fn record_if_device_loss(&self,_e:i32){}} struct Vm{status:Status}struct Queue{vm:Vm,timeline:(),next:Result} -impl Queue{fn submit_job(&self,_id:u64,_syncs:&Syncs,_count:usize,_raw:&[u8],_objects:Pin<&xarray::XArray>>)->Result{self.next} +impl Queue{fn submit_job(&self,_id:u64,syncs:&mut Syncs,_count:usize,_raw:&[u8],_objects:Pin<&xarray::XArray>>)->Result{let fence=self.next?;syncs.publish(&fence)} __SUBMIT__ } #[test]fn restart_has_no_output_fence_and_retry_accepts_once(){ From c168ccc429a677a8339f58dfb7a9a316b54db4d3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 15:49:11 -0500 Subject: [PATCH 0863/1514] drm/asahi: g16: cache VM-epoch span proofs and unify CDM validation lock Reuse validated page-aligned GPUVM span proofs across submits on each G16 logical queue while the VM's mapping epoch is unchanged, and unify compute span validation and CDM stream gating under a single VmReadGuard hold: - Enable `mmu::MappingEpoch` tracking for adopted M4 VMs (`m4_adopted`) and expose `VmReadGuard::epoch()` so locked and lockless validation observe the same committed page-table epoch. - Add `g16::command::SpanProof` (128 merged equal-permission ranges, boxed per logical queue) mirroring `g17::validation::Proof`, skipping GPUVM interval-tree walks on epoch hits and invalidating immediately on any epoch change, mutation in progress, or validation failure. - Move `gate::cdm_locked()` out of `check_compute()` into `Prepared::validate()` so render spans, compute spans, VDM root checks, and CDM stream walks share one `VmReadGuard` and one `SpanProof` cache, dropping and re-syncing the epoch only on the 1024-record reschedule boundary. - Extend `test-command-stream.py` and `test-stream-gate.py` to cover epoch reuse, partial walks, invalidation on unmap, and single-lock CDM gate sharing. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 288 ++++++++++++++++-- drivers/gpu/drm/asahi/g16/gate.rs | 74 ++++- drivers/gpu/drm/asahi/g16/queue.rs | 15 +- drivers/gpu/drm/asahi/mmu.rs | 8 +- .../gpu/asahi-m4/test-command-stream.py | 93 +++++- .../drivers/gpu/asahi-m4/test-stream-gate.py | 145 ++++++++- 6 files changed, 556 insertions(+), 67 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index e20d4c11c2ff53..10311e618483d2 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -634,6 +634,133 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { Ok((first, last - first)) } +/// Maximum page-aligned GPUVM spans retained in one logical queue's validation cache. +const MAX_PROOF_RANGES: usize = 128; + +/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions. +/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never +/// reused across unmaps or remaps. +pub(crate) struct SpanProof { + epoch: Option, + ranges: [(u64, u64, u8); MAX_PROOF_RANGES], + count: usize, + overflow: bool, +} + +impl SpanProof { + pub(crate) const fn new() -> Self { + Self { + epoch: None, + ranges: [(0, 0, 0); MAX_PROOF_RANGES], + count: 0, + overflow: false, + } + } + + fn contains(outer: (u64, u64, u8), inner: (u64, u64, u8)) -> bool { + outer.2 & inner.2 == inner.2 + && inner.0 >= outer.0 + && inner.0.checked_add(inner.1).is_some_and(|end| { + outer + .0 + .checked_add(outer.1) + .is_some_and(|limit| end <= limit) + }) + } + + pub(crate) fn invalidate(&mut self) { + self.epoch = None; + self.count = 0; + self.overflow = false; + } + + fn covers_entry(&self, req: (u64, u64, u8)) -> bool { + self.ranges[..self.count] + .iter() + .any(|&range| Self::contains(range, req)) + } + + pub(crate) fn covers_aligned( + &self, + epoch: Option, + first: u64, + size: u64, + access: u8, + ) -> bool { + self.epoch.is_some() && self.epoch == epoch && self.covers_entry((first, size, access)) + } + + fn insert_entry(&mut self, mut req: (u64, u64, u8)) { + if req.1 == 0 || req.2 == 0 || req.2 & !3 != 0 { + return; + } + if self.covers_entry(req) { + return; + } + // Merge only equal permissions so an adjacent writable span never widens a read-only + // span. Restart after each merge because the widened range may join an earlier entry. + let mut index = 0; + while index < self.count { + let range = self.ranges[index]; + let end = req.0.saturating_add(req.1); + let other_end = range.0.saturating_add(range.1); + if Self::contains(req, range) + || (req.2 == range.2 && req.0 <= other_end && range.0 <= end) + { + if req.2 == range.2 { + let start = req.0.min(range.0); + req = (start, end.max(other_end) - start, req.2); + } + self.count -= 1; + self.ranges[index] = self.ranges[self.count]; + index = 0; + } else { + index += 1; + } + } + if self.count == self.ranges.len() { + self.overflow = true; + return; + } + self.ranges[self.count] = req; + self.count += 1; + } + + pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch != epoch || self.overflow { + self.epoch = epoch; + self.count = 0; + self.overflow = false; + } + self.insert_entry((first, size, access)); + } + + fn record_slice(&mut self, epoch: Option, ranges: &[(u64, u64, u8)]) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch == epoch && !self.overflow { + for &req in ranges { + self.insert_entry(req); + } + if !self.overflow { + return; + } + } + self.epoch = epoch; + self.count = 0; + self.overflow = false; + for &req in ranges { + self.insert_entry(req); + } + } +} + /// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while /// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. struct SpanBatch { @@ -666,16 +793,8 @@ impl SpanBatch { Ok(()) } - fn flush(&mut self, vm: &mmu::Vm) -> Result { - let n = self.len; - if n == 0 { - return Ok(()); - } - self.len = 0; - if vm.covers_ranges_batch(&self.ranges[..n]).0 { - return Ok(()); - } - for &(first, size, access) in &self.ranges[..n] { + fn report_failure(vm: &mmu::Vm, ranges: &[(u64, u64, u8)]) -> Result { + for &(first, size, access) in ranges { let read = access & 1 != 0; let write = access & 2 != 0; if !vm.covers_range(first, size, read, write) { @@ -689,16 +808,78 @@ impl SpanBatch { Ok(()) } - fn flush_locked(&mut self, guard: &mut mmu::VmReadGuard<'_>) -> Result { + fn flush(&mut self, vm: &mmu::Vm) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + if vm.covers_ranges_batch(&self.ranges[..n]).0 { + return Ok(()); + } + Self::report_failure(vm, &self.ranges[..n]) + } + + fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { let n = self.len; if n == 0 { return Ok(()); } self.len = 0; + let epoch = vm.mapping_validation_epoch(); + if proof.epoch.is_some() && proof.epoch == epoch { + let mut missing = [(0u64, 0u64, 0u8); 48]; + let mut missing_len = 0usize; + for &req in &self.ranges[..n] { + if !proof.covers_entry(req) { + missing[missing_len] = req; + missing_len += 1; + } + } + if missing_len == 0 { + return Ok(()); + } + let (mut covered, mut walked) = vm.covers_ranges_batch(&missing[..missing_len]); + if covered && walked != proof.epoch { + (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); + } + if covered { + proof.record_slice(walked, &self.ranges[..n]); + return Ok(()); + } + proof.invalidate(); + return Self::report_failure(vm, &self.ranges[..n]); + } + let (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); + if covered { + proof.record_slice(walked, &self.ranges[..n]); + return Ok(()); + } + proof.invalidate(); + Self::report_failure(vm, &self.ranges[..n]) + } + + fn flush_locked_with_proof( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: &mut SpanProof, + ) -> Result { + let n = self.len; + if n == 0 { + return Ok(()); + } + self.len = 0; + let mut had_miss = false; for &(first, size, access) in &self.ranges[..n] { + if proof.covers_aligned(epoch, first, size, access) { + continue; + } + had_miss = true; let read = access & 1 != 0; let write = access & 2 != 0; if !guard.covers_range(first, size, read, write) { + proof.invalidate(); return if guard.covers_range(first, size, false, false) { Err(EACCES) } else { @@ -706,6 +887,9 @@ impl SpanBatch { }; } } + if had_miss { + proof.record_slice(epoch, &self.ranges[..n]); + } Ok(()) } } @@ -760,21 +944,39 @@ fn copy_list(lists: &[&[uapi::drm_asahi_attachment]]) -> Result, + epoch: Option, + mut proof: Option<&mut SpanProof>, start: u64, end: u64, read: bool, write: bool, ) -> Result { let (first, size) = align_span(start, end)?; + let access = u8::from(read) | (u8::from(write) << 1); + if proof + .as_deref() + .is_some_and(|cache| cache.covers_aligned(epoch, first, size, access)) + { + return Ok(()); + } if guard.covers_range(first, size, read, write) { + if let Some(cache) = proof.as_deref_mut() { + cache.record_one(epoch, first, size, access); + } Ok(()) - } else if guard.covers_range(first, size, false, false) { - Err(EACCES) } else { - Err(ENOENT) + if let Some(cache) = proof.as_deref_mut() { + cache.invalidate(); + } + if guard.covers_range(first, size, false, false) { + Err(EACCES) + } else { + Err(ENOENT) + } } } @@ -963,7 +1165,7 @@ fn check_compute( context: &Context<'_>, cmd: &uapi::drm_asahi_cmd_compute, attachments: &[uapi::drm_asahi_attachment], -) -> Result { +) -> Result<(u64, u64)> { let vm = context.vm; let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 @@ -979,8 +1181,7 @@ fn check_compute( } batch.push(vm, base, end, true, false)?; check_attachments(batch, vm, attachments, true)?; - batch.flush(vm)?; - gate::cdm(vm, context.usc_base, base, end) + Ok((base, end)) } /// Per-command barrier and stage-prefix metadata captured during single-pass parsing. @@ -1236,7 +1437,11 @@ impl ParsedStream { impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. - pub(crate) fn validate(self, context: &Context<'_>) -> Result { + pub(crate) fn validate( + self, + context: &Context<'_>, + proof: &mut SpanProof, + ) -> Result { let Prepared { commands, orders, @@ -1248,6 +1453,8 @@ impl Prepared { let mut batch = SpanBatch::new(); let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; let mut vdm_count = 0usize; + let mut cdm_ranges = [(0u64, 0u64); MAX_COMMANDS as usize]; + let mut cdm_count = 0usize; for command in commands.iter() { match command { Command::Render(render) => { @@ -1265,16 +1472,47 @@ impl Prepared { vdm_count += 1; } Command::Compute(compute) => { - check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; + let range = + check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; + if cdm_count >= cdm_ranges.len() { + return Err(EINVAL); + } + cdm_ranges[cdm_count] = range; + cdm_count += 1; } } } - if vdm_count != 0 { - let mut guard = context.vm.read_lock().map_err(|_| EFAULT)?; - batch.flush_locked(&mut guard)?; - gate::vdm_batch_locked(&mut guard, &vdm_vas[..vdm_count])?; + let stream_gate = super::params::stream_gate(); + let need_vdm = vdm_count != 0 && stream_gate; + let need_cdm = cdm_count != 0 && stream_gate; + if need_vdm || need_cdm { + if need_cdm { + kernel::task::might_sleep(); + if kernel::current!().signal_pending() { + return Err(ERESTARTSYS); + } + } + let mut guard = Some(context.vm.read_lock().map_err(|_| EFAULT)?); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + if let Some(g) = guard.as_mut() { + batch.flush_locked_with_proof(g, epoch, proof)?; + if need_vdm { + gate::vdm_batch_locked(g, &vdm_vas[..vdm_count])?; + } + } + for &(base, end) in &cdm_ranges[..cdm_count] { + gate::cdm_locked( + context.vm, + &mut guard, + &mut epoch, + context.usc_base, + base, + end, + Some(&mut *proof), + )?; + } } else { - batch.flush(context.vm)?; + batch.flush_with_proof(context.vm, proof)?; } Ok(Submission { counts, diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index ea630e19456acd..7987b22bd0d0fe 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -17,7 +17,10 @@ use core::sync::atomic::{AtomicU32, Ordering}; use kernel::prelude::*; -use super::{command::cover_locked, command::USC_WINDOW, params}; +use super::{ + command::{cover_locked, SpanProof, USC_WINDOW}, + params, +}; use crate::mmu; const VDM_ROOT: u32 = 0x21000960; @@ -64,6 +67,8 @@ impl Window { fn words( &mut self, guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: Option<&mut SpanProof>, va: u64, count: usize, limit: Option, @@ -80,7 +85,7 @@ impl Window { } let len = n.max(max_len); let cover_end = va.checked_add(len as u64).ok_or(EINVAL)?; - cover_locked(guard, va, cover_end, true, false)?; + cover_locked(guard, epoch, proof, va, cover_end, true, false)?; self.len = 0; guard .read_user(va, &mut self.bytes[..len]) @@ -104,6 +109,8 @@ impl Window { /// `checked` caches the last proven program page. fn program( guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: Option<&mut SpanProof>, usc: u64, address: u64, checked: &mut Option, @@ -116,7 +123,7 @@ fn program( if *checked == Some(page) { return Ok(()); } - cover_locked(guard, address, address + 64, true, false)?; + cover_locked(guard, epoch, proof, address, address + 64, true, false)?; *checked = Some(page); Ok(()) } @@ -155,12 +162,22 @@ pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Ok(()) } -/// CDM admission: walks the root and no-return linked streams to TERMINATE. +/// CDM admission: walks the root and no-return linked streams to TERMINATE under an optional +/// caller-held VM read lock, sharing both the lock and epoch-validated [`SpanProof`] across +/// span checks and stream gates. /// All requested bytes are proven readable; the root cannot end inside a record. /// Mode 0 has six inline grid words, mode 1 three inline local-size words and /// an indirect global grid, mode 2 an indirect six-word grid. The remaining /// launch-template payload words stay opaque, as in Mesa's raw AGX3 decoder. -pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { +pub(crate) fn cdm_locked<'a>( + vm: &'a mmu::Vm, + guard: &mut Option>, + epoch: &mut Option, + usc: u64, + base: u64, + end: u64, + mut proof: Option<&mut SpanProof>, +) -> Result { if !params::stream_gate() { return Ok(()); } @@ -182,8 +199,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { let mut distance = 0u64; let mut power = 1u64; let mut first = true; - let mut resched = 0; - let mut guard: Option> = None; + // A caller that already holds `guard` checked signals before locking; reuse the + // held guard for the first window of records instead of dropping it on record 0. + let mut resched = if guard.is_some() { + CDM_RESCHED_RECORDS + } else { + 0 + }; loop { if first { first = false; @@ -203,7 +225,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { // rescheduling so any mapping change while unlocked is re-verified. // might_sleep() includes might_resched() (cond_resched on voluntary kernels). // It is a real scheduling point, not only a debug assertion. - guard = None; + *guard = None; window.len = 0; checked = None; kernel::task::might_sleep(); @@ -213,9 +235,13 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { resched = CDM_RESCHED_RECORDS; } resched -= 1; - let guard = match guard.as_mut() { - Some(guard) => guard, - None => guard.insert(vm.read_lock().map_err(|_| EFAULT)?), + let active_guard = match guard.as_mut() { + Some(active) => active, + None => { + let active = guard.insert(vm.read_lock().map_err(|_| EFAULT)?); + *epoch = active.epoch(); + active + } }; let root_bytes = |va: u64, bytes: u64| -> Result { if !linked && (va < base || va.checked_add(bytes).is_none_or(|at| at > end)) { @@ -225,7 +251,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { }; let limit = (!linked).then_some(end); root_bytes(va, 4)?; - let w = window.words(guard, va, 1, limit)?; + let w = window.words(active_guard, *epoch, proof.as_deref_mut(), va, 1, limit)?; if w[0] == CDM_TERMINATE { return Ok(()); } @@ -245,7 +271,7 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { } if w[0] & 0xffff0000 == CDM_LINK { root_bytes(va, 8)?; - let w = window.words(guard, va, 2, limit)?; + let w = window.words(active_guard, *epoch, proof.as_deref_mut(), va, 2, limit)?; let target = (u64::from(w[0] & 0xffff) << 32) | u64::from(w[1]); if target & 3 != 0 || target == va { return Err(reject("CDM link", va, &w)); @@ -265,9 +291,23 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { _ => return Err(reject("CDM launch mode", va, &w)), }; root_bytes(va, (words * 4) as u64)?; - let w = window.words(guard, va, words, limit)?; + let w = window.words( + active_guard, + *epoch, + proof.as_deref_mut(), + va, + words, + limit, + )?; let address = (u64::from(w[1] >> 22) << 38) | (u64::from(w[2]) << 6); - match program(guard, usc, address, &mut checked) { + match program( + active_guard, + *epoch, + proof.as_deref_mut(), + usc, + address, + &mut checked, + ) { Err(error) if error == EINVAL => return Err(reject("CDM program", va, &w)), result => result?, } @@ -288,7 +328,9 @@ pub(crate) fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> Result { return Err(reject("CDM indirect parameters", va, &w)); } cover_locked( - guard, + active_guard, + *epoch, + proof.as_deref_mut(), indirect, indirect.checked_add(bytes).ok_or(EINVAL)?, true, diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 3f828490184ad6..f85ff71b7058a5 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -127,6 +127,8 @@ pub(crate) struct Queue { pub(crate) state: Arc, /// Commands accepted per engine (render, compute) since creation (checked for accounting overflow). pub(crate) accepted: [u64; 2], + /// Epoch-validated GPUVM span cache reused across submits on this logical queue. + proof: KBox, vm: Arc, shared: Arc, timeline: Arc, @@ -180,10 +182,12 @@ impl Queue { }, GFP_KERNEL, )?; + let proof = KBox::new(command::SpanProof::new(), GFP_KERNEL)?; Ok(Self { scheduler, state, accepted: [0; 2], + proof, vm: vm_state, shared: gpu.shared.clone(), timeline, @@ -213,10 +217,13 @@ impl Queue { let prepared = parsed.prepare(self.accepted, objects)?; // The job reference first, so that the mappings checked below stay retained. let guard = self.vm.vm.retain_first_job()?; - let submission = prepared.validate(&command::Context { - vm: &self.vm.vm, - usc_base: self.state.usc_base, - })?; + let submission = prepared.validate( + &command::Context { + vm: &self.vm.vm, + usc_base: self.state.usc_base, + }, + &mut self.proof, + )?; // Refused jobs add no accepted ordinals; check every prepared dependency before // publishing a fence or extending the queue's accepted frontier. for order in submission.orders.iter() { diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 9714f96993d0d9..0e70b5a568add6 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -510,6 +510,10 @@ pub(crate) struct VmReadGuard<'a>(gpuvm::GpuVmInnerGuard<'a, VmInner>); #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] impl VmReadGuard<'_> { + pub(crate) fn epoch(&self) -> Option { + self.0.epoch + } + pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } @@ -2516,7 +2520,7 @@ impl Vm { GFP_KERNEL, )?; - let mapping_epoch = if uat_inner.firmware != UatFirmware::Handoff { + let mapping_epoch = if uat_inner.firmware != UatFirmware::Handoff || uat_inner.m4_adopted { Some(Arc::new(MappingEpoch::new(), GFP_KERNEL)?) } else { None @@ -2535,7 +2539,7 @@ impl Vm { page_table, mapping_epoch: mapping_epoch.clone(), bind_sequence: bind_sequence.clone(), - epoch: Some(0), + epoch: mapping_epoch.is_some().then_some(0), mm, uat_inner, binding: binding.clone(), 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 f82db0888f8071..4b852323520115 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 @@ -653,32 +653,43 @@ pub(crate) const UAT_PGMSK: usize = 0x3fff; pub(crate) struct VmReadGuard<'a>(&'a Vm); impl VmReadGuard<'_> { + pub(crate) fn epoch(&self) -> Option { + self.0.epoch.get() + } pub(crate) fn covers_range(&mut self, start: u64, size: u64, read: bool, write: bool) -> bool { self.0.covers_range(start, size, read, write) } } pub(crate) struct Vm { pub(crate) maps: Vec<(u64, u64, bool, bool)>, + pub(crate) epoch: std::cell::Cell>, pub(crate) batch_calls: std::cell::Cell, + pub(crate) cover_calls: std::cell::Cell, + pub(crate) batch_ranges: std::cell::Cell, } impl Vm { pub(crate) fn read_lock(&self) -> super::Result> { Ok(VmReadGuard(self)) } + pub(crate) fn mapping_validation_epoch(&self) -> Option { + self.epoch.get() + } pub(crate) fn covers_range(&self, start: u64, size: u64, read: bool, write: bool) -> bool { + self.cover_calls.set(self.cover_calls.get() + 1); let Some(end) = start.checked_add(size) else { return false }; self.maps.iter().any(|&(s, e, r, w)| { start >= s && end <= e && (!read || r) && (!write || w) }) } - pub(crate) fn covers_ranges_batch(&self, ranges: &[(u64, u64, u8)]) -> (bool, usize) { + pub(crate) fn covers_ranges_batch(&self, ranges: &[(u64, u64, u8)]) -> (bool, Option) { self.batch_calls.set(self.batch_calls.get() + 1); - for (i, &(start, size, acc)) in ranges.iter().enumerate() { + self.batch_ranges.set(self.batch_ranges.get() + ranges.len()); + for &(start, size, acc) in ranges { if !self.covers_range(start, size, acc & 1 != 0, acc & 2 != 0) { - return (false, i); + return (false, self.epoch.get()); } } - (true, ranges.len()) + (true, self.epoch.get()) } } } @@ -707,7 +718,10 @@ (BASE_GVA + 0x20_0000, BASE_GVA + 0x40_0000, true, true), (BASE_GVA + 0x50_0000, BASE_GVA + 0x51_0000, true, false), ], + epoch: std::cell::Cell::new(Some(1)), batch_calls: std::cell::Cell::new(0), + cover_calls: std::cell::Cell::new(0), + batch_ranges: std::cell::Cell::new(0), } } fn base_cmd() -> uapi::drm_asahi_cmd_render { @@ -834,8 +848,10 @@ assert_eq!(batch.flush(&vm), Ok(())); assert_eq!(vm.batch_calls.get(), 1); let mut guard = vm.read_lock().unwrap(); + let mut proof = SpanProof::new(); + let epoch = guard.epoch(); assert_eq!(check_render(&mut batch, &ctx, &base_cmd(), &[], &[]), Ok(())); - assert_eq!(batch.flush_locked(&mut guard), Ok(())); + assert_eq!(batch.flush_locked_with_proof(&mut guard, epoch, &mut proof), Ok(())); assert_eq!(vm.batch_calls.get(), 1); drop(guard); @@ -886,6 +902,73 @@ cmd.flags |= 1 << 21; assert_eq!(check_render_one(&ctx, &cmd, &[], &[]), Err(EINVAL)); } + + #[test] + fn span_proof_reuses_epoch_partial_walks_and_invalidates_on_unmap() { + let mut vm = base_vm(); + let mut proof = SpanProof::new(); + let cmd = base_cmd(); + + // First flush populates the proof for epoch 1. + let mut batch = SpanBatch::new(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + + // Second flush at unchanged epoch hits the proof with zero VM walks. + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 1); + + // A new attachment triggers a partial walk of only the uncovered span. + let att = uapi::drm_asahi_attachment { + pointer: BASE_GVA + 0x20_0000, + size: 0x4000, + ..Default::default() + }; + let ranges_before = vm.batch_ranges.get(); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), 2); + assert_eq!(vm.batch_ranges.get() - ranges_before, 1); + + // Locked flush under a held VmReadGuard also skips already-proven spans. + let covers_before = vm.cover_calls.get(); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + let mut guard = vm.read_lock().unwrap(); + let epoch = guard.epoch(); + assert_eq!(batch.flush_locked_with_proof(&mut guard, epoch, &mut proof), Ok(())); + drop(guard); + assert_eq!(vm.cover_calls.get(), covers_before); + + // Adjacent read-only and read-write ranges never merge to grant write on RO memory. + let mut rw_batch = SpanBatch::new(); + rw_batch.push(&vm, BASE_GVA, BASE_GVA + 0x4000, true, true).unwrap(); + assert_eq!(rw_batch.flush_with_proof(&vm, &mut proof), Err(EACCES)); + + // Repopulate, then simulate an unmap that bumps the epoch: cached proof is invalidated. + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + vm.maps.remove(1); + vm.epoch.set(Some(2)); + let mut batch = SpanBatch::new(); + let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Err(ENOENT)); + + // Epoch None (concurrent mutation) never serves a stale cached proof. + vm.epoch.set(None); + let mut batch = SpanBatch::new(); + check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); + let calls_before = vm.batch_calls.get(); + assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); + assert_eq!(vm.batch_calls.get(), calls_before + 1); + } } ''' replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index 38eb620a86d788..eb48e6ce3ee651 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -48,12 +48,16 @@ #[derive(Default)] pub struct Vm { pub regions: Vec, + pub epoch: std::cell::Cell>, pub lock_calls: std::cell::Cell, pub read_calls: std::cell::Cell, pub last_read_len: std::cell::Cell, } pub struct VmReadGuard<'a>(&'a Vm); impl VmReadGuard<'_> { + pub fn epoch(&self) -> Option { + self.0.epoch.get() + } pub fn covers_range(&mut self, address: u64, size: u64, _read: bool, _write: bool) -> bool { address .checked_add(size) @@ -96,6 +100,36 @@ use crate::{mmu, kernel::prelude::*}; use std::cell::Cell; pub const USC_WINDOW: u64 = 1 << 32; + #[derive(Default)] + pub struct SpanProof { + epoch: Option, + ranges: Vec<(u64, u64, u8)>, + } + impl SpanProof { + pub fn new() -> Self { Self::default() } + pub fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { + self.epoch.is_some() + && self.epoch == epoch + && self.ranges.iter().any(|&(s, l, a)| { + (a & access) == access && first >= s && first + size <= s + l + }) + } + pub fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + if epoch.is_none() { + self.invalidate(); + return; + } + if self.epoch != epoch { + self.epoch = epoch; + self.ranges.clear(); + } + self.ranges.push((first, size, access)); + } + pub fn invalidate(&mut self) { + self.epoch = None; + self.ranges.clear(); + } + } std::thread_local! { static COVER_CALLS: Cell = const { Cell::new(0) }; } @@ -103,20 +137,39 @@ pub fn cover_calls() -> usize { COVER_CALLS.with(Cell::get) } pub fn cover_locked( guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + mut proof: Option<&mut SpanProof>, start: u64, end: u64, read: bool, write: bool, ) -> Result { - COVER_CALLS.with(|c| c.set(c.get() + 1)); if end <= start || start < 0x4000 || end > (1u64 << 42) - 0x8000 { return Err(EINVAL); } + let first = start & !(mmu::UAT_PGMSK as u64); + let last = (end + mmu::UAT_PGMSK as u64) & !(mmu::UAT_PGMSK as u64); + let size = last - first; + let access = u8::from(read) | (u8::from(write) << 1); if start < 0x7100000000 && end > 0x7000000000 || start < 0x1000010000 && end > 0x1000000000 { return Err(EACCES); } - if guard.covers_range(start, end - start, read, write) { Ok(()) } else { Err(EFAULT) } + if proof.as_deref().is_some_and(|p| p.covers_aligned(epoch, first, size, access)) { + return Ok(()); + } + COVER_CALLS.with(|c| c.set(c.get() + 1)); + if guard.covers_range(start, end - start, read, write) { + if let Some(p) = proof.as_deref_mut() { + p.record_one(epoch, first, size, access); + } + Ok(()) + } else { + if let Some(p) = proof.as_deref_mut() { + p.invalidate(); + } + Err(EFAULT) + } } } #[path = "PRODUCTION_SOURCE"] pub mod gate; @@ -142,8 +195,13 @@ vm.region(BASE, stream); vm.region(USC, vec![0; 0x4000]); vm.region(0x400000000, vec![0; 0x4000]); vm } +fn cdm(vm: &mmu::Vm, usc: u64, base: u64, end: u64) -> kernel::prelude::Result { + let mut guard = None; + let mut epoch = None; + g16::gate::cdm_locked(vm, &mut guard, &mut epoch, usc, base, end, None) +} fn run(words: &[u32]) -> bool { - g16::gate::cdm(&vm_for(words), USC, BASE, BASE + words.len() as u64 * 4).is_ok() + cdm(&vm_for(words), USC, BASE, BASE + words.len() as u64 * 4).is_ok() } #[test] fn direct_modes_and_program_split() { @@ -155,7 +213,7 @@ for usc in [0x3f00000000u64, 0x4000000000, 0x8100000000, 0x30000000000] { let mut words = launch(0, usc + 0x80, 0); words.push(0x40000000); let mut vm = vm_for(&words); vm.region(usc, vec![0; 0x4000]); - assert!(g16::gate::cdm(&vm, usc, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert!(cdm(&vm, usc, BASE, BASE + words.len() as u64 * 4).is_ok()); } } #[test] @@ -180,7 +238,7 @@ let mut vm = vm_for(&words); let mut linked = bytes(&[0x60000160, 0x40000000]); linked.resize(0x4000, 0); vm.region(target, linked); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); assert!(!run(&[0x30000006, 0])); // Call/return form is not qualified. } #[test] @@ -209,11 +267,11 @@ assert!(!run(&words)); let mut words = launch(0, USC, 0); words.push(0x40000000); let mut vm = vm_for(&words); vm.regions[1].readable = false; - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 44).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 44).is_err()); let target = 0x7000000000u64; let words = [0x20000000 | (target >> 32) as u32, target as u32]; let mut vm = vm_for(&words); vm.region(target, vec![0; 0x4000]); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); } #[test] fn cycles_are_rejected() { @@ -221,7 +279,7 @@ let words = [0x20000000 | (b >> 32) as u32, b as u32]; let mut vm = vm_for(&words); vm.regions[0].bytes[0x100..0x108].copy_from_slice(&bytes(&[0x20000000 | (a >> 32) as u32, a as u32])); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); assert!(!run(&[0x20000000 | (a >> 32) as u32, a as u32])); // A loop beyond the old record budget must also be detected. let mut words = vec![0x60000160; 20000]; @@ -258,10 +316,10 @@ let mut data = bytes(&words); data.resize(0x4000, 0); vm.region(address, data); } - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); let tail = vm.regions.last_mut().unwrap(); tail.bytes[..8].copy_from_slice(&bytes(&root)); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_err()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_err()); } #[test] fn cached_window_reuses_page_coverage_without_rechecking_every_record() { @@ -281,10 +339,10 @@ let words = [0x60000160, 0x40000000]; let vm = vm_for(&words); kernel::task::pending(true); - let result = g16::gate::cdm(&vm, USC, BASE, BASE + 8); + let result = cdm(&vm, USC, BASE, BASE + 8); kernel::task::pending(false); assert_eq!(result, Err(kernel::prelude::ERESTARTSYS)); - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + 8).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + 8).is_ok()); } fn vdm_check(vm: &mmu::Vm, vas: &[u64]) -> kernel::prelude::Result { let mut guard = vm.read_lock()?; @@ -354,7 +412,7 @@ vm.region(USC + 0x4000, vec![0; 0x4000]); // Multi-launch mode 0/1/2 + linked segment acquires the VM read lock only once. - assert!(g16::gate::cdm(&vm, USC, BASE, BASE + root.len() as u64 * 4).is_ok()); + assert!(cdm(&vm, USC, BASE, BASE + root.len() as u64 * 4).is_ok()); assert_eq!(vm.lock_calls.get(), 1); // Streams longer than CDM_RESCHED_RECORDS (1024) drop and re-acquire the lock on each resched. @@ -362,7 +420,7 @@ long.push(0x40000000); let long_vm = vm_for(&long); let sched_before = kernel::task::scheduled(); - assert!(g16::gate::cdm(&long_vm, USC, BASE, BASE + long.len() as u64 * 4).is_ok()); + assert!(cdm(&long_vm, USC, BASE, BASE + long.len() as u64 * 4).is_ok()); let sched_delta = kernel::task::scheduled() - sched_before; assert_eq!(sched_delta, 3); assert_eq!(long_vm.lock_calls.get(), sched_delta); @@ -378,11 +436,68 @@ let mut words = launch(0, USC, 0); words.push(0x40000000); let cdm_vm = vm_for(&words); - assert!(g16::gate::cdm(&cdm_vm, USC, BASE, BASE + words.len() as u64 * 4).is_ok()); + assert!(cdm(&cdm_vm, USC, BASE, BASE + words.len() as u64 * 4).is_ok()); assert_eq!(cdm_vm.lock_calls.get(), 1); assert_eq!(cdm_vm.read_calls.get(), 1); assert_eq!(cdm_vm.last_read_len.get(), words.len() * 4); } +#[test] +fn cdm_locked_shares_held_guard_and_hits_span_proof() { + let mut words = launch(1, USC + 0x80, 0x400000000); + words.push(0x40000000); + let vm = vm_for(&words); + vm.epoch.set(Some(7)); + let mut proof = g16::command::SpanProof::new(); + + // Caller holds one VmReadGuard across two cdm_locked walks; first pass populates proof, + // second pass hits proof with zero additional cover_locked walks and still 1 lock_calls. + let mut guard = Some(vm.read_lock().unwrap()); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + g16::command::reset_cover_calls(); + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(g16::command::cover_calls(), 3); + + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + drop(guard); + assert_eq!(vm.lock_calls.get(), 1); + assert_eq!(g16::command::cover_calls(), 3); + + // Epoch bump invalidates the cached proof and forces cover_locked to re-verify spans. + vm.epoch.set(Some(8)); + let mut guard = Some(vm.read_lock().unwrap()); + let mut epoch = guard.as_ref().and_then(|g| g.epoch()); + assert!(g16::gate::cdm_locked( + &vm, + &mut guard, + &mut epoch, + USC, + BASE, + BASE + words.len() as u64 * 4, + Some(&mut proof), + ) + .is_ok()); + assert_eq!(vm.lock_calls.get(), 2); + assert_eq!(g16::command::cover_calls(), 6); +} ''' with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: From 7db1b4a15221577ebe68649d085c0a51f7503c5d Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 15:51:27 -0500 Subject: [PATCH 0864/1514] drm/asahi: g16: sustain CPU boost on short d>=2 pipelines and raise compute units to 24 Address the two remaining G16 pipelining ceilings without adding knobs: - In `g16::feed::detector`, overlapping (`d >= 2`) flights have zero inter-flight idle gap, which previously caused `idle_sum * 4 >= busy_sum` to drop the host-refill CPU boost on short CPU-recording- bound pipelines. Sustain boost while `overlapped && busy_sum <= SHORT_PIPELINE_BUSY_SUM_NS` (4.8 ms, ~8x 600 us incremental flight time), preserving non-boost for GPU-bound 2 ms pipelines, desktop 60/120 Hz pacing, and the 8 ms idle linger decay. - Raise `g16::hw::sizes::COMPUTE_UNITS` from 18 to 24 (keeping 23 compute flights concurrent, `46 < QUEUE_CAP = 256`, UMA slots `1..25 <= RENDER_UMA_SLOT = 33`, and `22 * 7 = 154 <= MAX_CLIENT`). Tighten extension compute unit VA stride (`k >= 2`) from 64 MiB to 40 MiB (`EXT_COMPUTE_STRIDE = 0x02800000`, 7.25 MiB guard above each unit's `0x20c0000` footprint) so all 24 units fit cleanly below `PB_HEAP` (`0x70c0000000`) with 144 MiB headroom. - Add host tests for overlapping `d = 2` CPU-bound boost and GPU-bound non-boost in `detector.rs` and update `test-resources.py` to verify disjointness across all 48 render passes and 24 compute units. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/feed/detector.rs | 45 ++++++++++++++++++- drivers/gpu/drm/asahi/g16/hw.rs | 24 ++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 4 +- 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/feed/detector.rs b/drivers/gpu/drm/asahi/g16/feed/detector.rs index 124ba7a92bceb4..3473faf8a3b549 100644 --- a/drivers/gpu/drm/asahi/g16/feed/detector.rs +++ b/drivers/gpu/drm/asahi/g16/feed/detector.rs @@ -16,6 +16,9 @@ pub(crate) const STREAK_ON: u32 = 8; pub(crate) const STREAK_MAX: u32 = 64; /// How long CPU capacity boost lingers after the most recent refill-pressure sample. pub(crate) const LINGER_NS: u64 = 8_000_000; +/// EWMA busy-sum ceiling (~8x 600 us incremental flight time) below which overlapping +/// pipelined (`d >= 2`) flights are still host-recording-bound rather than GPU-bound. +pub(crate) const SHORT_PIPELINE_BUSY_SUM_NS: u64 = 4_800_000; /// Lock-free refill-gap detector shared between completion retirement and the feed worker. pub(crate) struct Detector { @@ -68,6 +71,7 @@ impl Detector { return; } let previous = self.last_end.fetch_max(end_ns, Ordering::AcqRel); + let overlapped = previous != 0 && start_ns < previous; let (idle, busy, paced) = if previous == 0 { (0, end_ns - start_ns, true) } else if start_ns >= previous { @@ -105,7 +109,9 @@ impl Detector { if streak < STREAK_ON { return; } - if idle_sum.saturating_mul(4) >= busy_sum { + if idle_sum.saturating_mul(4) >= busy_sum + || (overlapped && busy_sum <= SHORT_PIPELINE_BUSY_SUM_NS) + { self.until .store(now_ns.saturating_add(LINGER_NS), Ordering::Release); if !self.active.swap(true, Ordering::AcqRel) { @@ -256,4 +262,41 @@ mod tests { assert!(!d.wanted(resumed_now)); assert!(!d.take_pending()); } + + #[test] + fn pipelined_d2_cpu_recording_burst_sustains_boost_and_expires_after_linger() { + let d = Detector::new(); + // Overlapping d=2 short flights (~300 us GPU duration, 200 us host submit cadence): + // idle gap is 0 while overlapping, so EWMA busy_sum (~1.6 ms) sustains CPU boost. + let mut start = 10_000_000u64; + let mut last_end = 0u64; + for _ in 0..20 { + let end = start + 300_000; + d.note(start, end, end); + last_end = end; + start += 200_000; + } + assert!(d.wanted(last_end)); + assert!(d.take_pending()); + assert!(!d.bound(last_end)); + assert!(!d.wanted(last_end + LINGER_NS)); + } + + #[test] + fn pipelined_d2_gpu_bound_flights_do_not_boost_cpu() { + let d = Detector::new(); + // Overlapping d=2 long GPU-bound flights (2 ms GPU duration, 1.8 ms cadence): + // EWMA busy_sum (~14.4 ms >> SHORT_PIPELINE_BUSY_SUM_NS) stays GPU-bound without boost. + let mut start = 10_000_000u64; + let mut last_end = 0u64; + for _ in 0..20 { + let end = start + 2_000_000; + d.note(start, end, end); + last_end = end; + start += 1_800_000; + } + assert!(d.bound(last_end)); + assert!(!d.wanted(last_end)); + assert!(!d.take_pending()); + } } diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index d1215627955c4c..5468c0e0edbf96 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -571,16 +571,17 @@ pub(crate) mod client { pub(crate) const CLIENT_APERTURE: Range = 0x7000000000..0x7100000000; pub(crate) const COMPACT_WINDOW: Range = 0x1000000000..0x9000000000; - // 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 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. + // Persistent compute units reused across application queues. Units 0 and 1 keep their + // original 64 MiB placement below the render allocators; extension units (2..COMPUTE_UNITS) + // pack at a 40 MiB stride from 0x7080000000 up to the PB heap (0x70c0000000), clear of the + // dynamic PB page-list range 0x7040000000..0x7080000000 and leaving 7.25 MiB guard above + // each unit's 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. + pub(crate) const EXT_COMPUTE_STRIDE: u64 = 0x02800000; pub(crate) const fn compute_base(k: u64) -> u64 { if k < 2 { 0x7001000000 + k * 0x04000000 } else { - 0x7080000000 + (k - 2) * 0x04000000 + 0x7080000000 + (k - 2) * EXT_COMPUTE_STRIDE } } pub(crate) const fn compute_pool(k: u64) -> u64 { @@ -769,13 +770,18 @@ pub(crate) mod sizes { /// Retained compute units per VM at most; each unit owns its own hardware UMA slot /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). 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 (`17 * 2 = 34` entries of the 256-entry compute work + /// `n - 1` compute commands in flight (`23 * 2 = 46` entries of the 256-entry compute work /// ring `QUEUE_CAP`, well inside `AHEAD_RECORDS = 128`, `RING_SLOTS = 256`, and recovery /// `snapshot_entries = 448`). - pub(crate) const COMPUTE_UNITS: usize = 18; + pub(crate) const COMPUTE_UNITS: usize = 24; const _: () = assert!(COMPUTE_UNITS >= 2); const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); - const _: () = assert!(super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP); + const _: () = assert!( + super::client::compute_context(2) + 0x40000 <= super::client::compute_base(3) + ); + const _: () = assert!( + super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP + ); const _: () = assert!( super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT 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 66e9a9fe79f52a..239510672e7339 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -573,9 +573,9 @@ def module(text, name): assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); } - #[test]fn forty_eight_render_passes_and_eighteen_compute_units_are_disjoint_in_mesa_hole(){ + #[test]fn forty_eight_render_passes_and_twenty_four_compute_units_are_disjoint_in_mesa_hole(){ assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); - assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 18); + assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); let pools=PoolSet::new(&mut o).unwrap(); for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { From 11727d50060d0cac8c3e4d3b3a593e5a77f7edf2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:16:25 -0500 Subject: [PATCH 0865/1514] drm/asahi: mmu: make Vm::is_closed() lock-free with AtomicBool Cache::prepare() in g16/resources.rs calls vm.vm.is_closed() while holding Cache::standby (SpinLockIrq). Previously Vm::is_closed() acquired VmLifetime::state (a sleeping Mutex), which triggered "BUG: scheduling while atomic" under PREEMPT(full) whenever lifetime.state was contended during SUBMIT, corrupting preempt_count / ref-counted local_interrupt_disable() depth and cascading into an interrupt_rc.h:63 WARN_ON_ONCE(in_nmi()) on the subsequent Cache::release_reserved() lock. Mirror state.closed in a lock-free AtomicBool on VmLifetime, published with Release ordering under lifetime.state in Vm::unmap_user_ranges() and read with Acquire ordering in Vm::is_closed(). This keeps all spinlock callers strictly atomic and removes sleeping mutex contention on SUBMIT. Add host selftest assertions in test-resources.py verifying Vm::is_closed() never acquires a lock and reads lifetime.closed with Acquire ordering. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/mmu/lifetime.rs | 9 +++++++-- .../selftests/drivers/gpu/asahi-m4/test-resources.py | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 9da7820dd92f65..a05486d08448f1 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -74,6 +74,8 @@ struct State { pub(super) struct VmLifetime { #[pin] state: Mutex, + /// Lock-free mirror of `state.closed`, set once in [`Vm::unmap_user_ranges`]. + closed: AtomicBool, #[pin] changed: CondVar, #[pin] @@ -99,6 +101,7 @@ impl VmLifetime { state <- new_mutex!(State { active:0, commits:0, blocked:false, quarantined:false, draining:false, closed:false, cleanup_failed:false, close_ranges:None, unmaps:KVec::new(), objects:KVec::new() }, "VM job lifetime"), + closed: AtomicBool::new(false), changed <- new_condvar!("VM mapping admission"), driver <- new_mutex!(None, "VM driver mappings"), }), @@ -393,11 +396,12 @@ impl Vm { } /// Whether the client's handle of this VM is gone ([`Self::unmap_user_ranges`] closed - /// admission for good). G15 releases its per-VM state after that. + /// admission for good). Lock-free so callers holding spinlocks (such as G16's standby + /// epoch lock) can test close state without sleeping. pub(crate) fn is_closed(&self) -> bool { self.lifetime .as_ref() - .is_some_and(|lifetime| lifetime.state.lock().closed) + .is_some_and(|lifetime| lifetime.closed.load(Ordering::Acquire)) } /// Tests mappings and reservations which userspace must never replace. @@ -666,6 +670,7 @@ impl Vm { lifetime.changed.wait(&mut state); } state.closed = true; + lifetime.closed.store(true, Ordering::Release); if state.active != 0 { state.close_ranges = Some((user, kernel)); return Ok(()); 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 239510672e7339..ab43a6aaa12c21 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1435,6 +1435,12 @@ def module(text, name): assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' +lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() +is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') +assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' +assert 'lifetime.closed.load(Ordering::Acquire)' in is_closed_fn +unmap_fn = item(lifetime_source, 'pub(crate) fn unmap_user_ranges(') +assert 'lifetime.closed.store(true, Ordering::Release)' in unmap_fn budget=(production/'budget.rs').read_text() budget=budget.replace('new_condvar, new_mutex,','').replace('#[pin_data]','').replace(' #[pin]\n','') constructor=item(budget,'pub(crate) fn new()') From 9a5155e9f01bc9e6c44ae174c81d4b677527c207 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 16:57:40 -0500 Subject: [PATCH 0866/1514] drm/asahi/g16: slim pass_scrub and selectively write clean render scenes Trim clean same-VM render pass preparation so steady-state reuse stops writing dead zero spans to WC memory under and off Shared::state: - Skip unused render `its` and preemption save areas (`pre[0..2]`) in `PassSlot::scrub_clean()`, retaining full zeroing on first use, cross-VM retarget, cancel, error, and recovery. - Track per-slot `heap_dirty` (`0x200` for single-layer passes, `0x1000` for multi-layer passes), `tilemap_last`, and `tilemap_clean`. Off-lock `PendingScrub::run_one()` zeroes only `already..min(dirty, last)` plus `heap_dirty` while preserving `tilemap_dirty` high-water marks for cross-VM or recovery full scrubs. - Prefer exact zero-fill clean slots in `pick_pass_in()` before falling back to partial-clean slots (which zero only the uncleaned delta `already..need`) or uncleaned slots. - On clean same-VM `prefix_render()`, skip the 2 KiB `scratch.scene` memset and write only the active scene header (`0x00..0x80`), firmware state block (`0x80..0x300`), active prefix (`0x300..0x380`), `uma_submitted` (`0x500..0x508`), and internal timestamp cells (`0x600..0x640`). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode.rs | 2 +- drivers/gpu/drm/asahi/g16/encode/render.rs | 27 ++- drivers/gpu/drm/asahi/g16/engine.rs | 40 ++-- drivers/gpu/drm/asahi/g16/resources.rs | 94 ++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 171 +++++++++++------- .../drivers/gpu/asahi-m4/test-resources.py | 141 +++++++++++---- 6 files changed, 353 insertions(+), 122 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index a18e33dcdd1946..9fdc397dc3cfc7 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -282,5 +282,5 @@ 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_fs_for, encode_ta, encode_ta_for, fill_scene, - initbm, render_attachments, scene, scene_render, PassRefs, RenderRefs, + initbm, render_attachments, scene, scene_prefix, scene_render, PassRefs, RenderRefs, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index f84571dcbe987e..0d7f569c9a54ac 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -609,7 +609,6 @@ pub(crate) fn fill_scene(r: &RenderRefs, p: &PassRefs, out: &mut [u8]) { } /// Small scene header for direct writes into a zeroed retained firmware object. -#[allow(dead_code)] 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); @@ -619,6 +618,32 @@ pub(crate) fn scene(r: &RenderRefs, p: &PassRefs, _n: u64) -> [u8; 0x80] { out } +/// Active scene prefix block (`0x300..0x380`: optional InitBM record + own-TA wait barrier) +/// for direct clean same-VM writes without zeroing dead gaps in the 2 KiB scene scratch image. +pub(crate) fn scene_prefix(r: &RenderRefs, ctx: u32, target: u32, init: bool) -> [u8; 0x80] { + let mut out = [0u8; 0x80]; + if init { + put( + &mut out, + 0, + &initbm(ctx, r.parameter_id, r.pb_mgr, target), + ); + } + put( + &mut out, + 0x40, + &barrier( + r.fw_stamp[0], + target, + 0x70, + target, + 0, + work::BarrierType::Stamp, + ), + ); + out +} + /// Populate the scene-owned InitBM and own-TA wait before exposing either work. pub(crate) fn scene_render( r: &RenderRefs, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 0410578ce225f5..d5aad8a6aa3183 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2400,10 +2400,11 @@ impl Firmware { f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); let p = job.resources.render_pass(k)?; let pass = p.refs(); + let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; geometry.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; job.resources - .set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes)?; + .set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; encode::encode_ta_for( self.init.abi.ta(), @@ -2434,17 +2435,18 @@ impl Firmware { ); encode::render_attachments(&mut scratch.tas[..], 0, &cmd.vertex_attachments); encode::render_attachments(&mut scratch.fss[..], 1, &cmd.fragment_attachments); - encode::fill_scene(&refs, &pass, &mut scratch.scene[..]); - encode::scene_render( - &refs, - &pass, - &[0; 4], - job.vm.slot, - target, - init_buffer, - &mut scratch.scene[..], - ); - if self.slots.render_needs_full_work(k) { + let full_work = self.slots.render_needs_full_work(k); + if full_work { + encode::fill_scene(&refs, &pass, &mut scratch.scene[..]); + encode::scene_render( + &refs, + &pass, + &[0; 4], + job.vm.slot, + target, + init_buffer, + &mut scratch.scene[..], + ); p.ta_work.write(0, &scratch.ta[..])?; p.fs_work.write(0, &scratch.fs[..])?; } else { @@ -2463,7 +2465,19 @@ impl Firmware { } p.ta_seq.write(0, &scratch.tas[..])?; p.fs_seq.write(0, &scratch.fss[..])?; - p.scene.write(0, &scratch.scene[..])?; + if full_work { + p.scene.write(0, &scratch.scene[..])?; + } else { + let hdr = encode::scene(&refs, &pass, 0); + let pfx = encode::scene_prefix(&refs, job.vm.slot, target, init_buffer); + p.scene.write(0, &hdr)?; + p.scene.fill(0x80, 0, 0x280)?; + p.scene.write(0x300, &pfx)?; + p.scene.w64(0x500, refs.uma_submitted)?; + // Zero TA/FS internal timestamp cells and targets so recovery FS execution + // proof and timestamp queries can never observe stale ticks from a prior pass. + p.scene.fill(0x600, 0, 0x40)?; + } // One retained descriptor is shared by TA and FS; its private submitted counter // advances by two per pass. Reused descriptors and their pool/list bytes remain intact. f.uma_submitted = refs.uma_submitted; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 1bd581ee22a165..4ce13702bc4de3 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -209,10 +209,22 @@ pub(crate) struct RenderInner { pub(crate) pools: PoolSet, pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) tilemap_clean: [AtomicU64; BASE_RENDER_SLOTS], + pub(crate) heap_dirty: [AtomicU64; BASE_RENDER_SLOTS], _objects: Objects, _bind: mmu::VmBind, _live: Arc, } +/// Per-pass dirty and pre-cleaned WC byte spans for one render pass slot. +#[derive(Copy, Clone)] +pub(crate) struct PassDirty<'a> { + pub(crate) tpc: &'a AtomicU64, + pub(crate) tilemap: &'a AtomicU64, + pub(crate) tilemap_last: &'a AtomicU64, + pub(crate) tilemap_clean: &'a AtomicU64, + pub(crate) heap: &'a AtomicU64, +} impl RenderArena { fn new( factory: &Factory, @@ -233,6 +245,9 @@ impl RenderArena { pools, tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + tilemap_clean: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], + heap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -247,6 +262,9 @@ impl RenderArena { } self.tpc_dirty[k].fetch_max(tpc, Ordering::Relaxed); self.tilemap_dirty[k].fetch_max(tilemap, Ordering::Relaxed); + self.tilemap_last[k].store(tilemap, Ordering::Relaxed); + self.tilemap_clean[k].store(0, Ordering::Relaxed); + self.heap_dirty[k].fetch_max(0x200, Ordering::Relaxed); Ok(()) } } @@ -265,6 +283,9 @@ pub(crate) struct RenderExtInner { pub(crate) passes: KVec, pub(crate) tpc_dirty: KVec, pub(crate) tilemap_dirty: KVec, + pub(crate) tilemap_last: KVec, + pub(crate) tilemap_clean: KVec, + pub(crate) heap_dirty: KVec, _objects: Objects, _bind: mmu::VmBind, _live: Arc, @@ -282,10 +303,16 @@ impl RenderExtArena { let mut passes = KVec::with_capacity(count, GFP_KERNEL)?; let mut tpc_dirty = KVec::with_capacity(count, GFP_KERNEL)?; let mut tilemap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_last = KVec::with_capacity(count, GFP_KERNEL)?; + let mut tilemap_clean = KVec::with_capacity(count, GFP_KERNEL)?; + let mut heap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; for k in slots.clone() { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_last.push(AtomicU64::new(0), GFP_KERNEL)?; + tilemap_clean.push(AtomicU64::new(0), GFP_KERNEL)?; + heap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; } objects.finish_private()?; Ok(Arc::new( @@ -294,6 +321,9 @@ impl RenderExtArena { passes, tpc_dirty, tilemap_dirty, + tilemap_last, + tilemap_clean, + heap_dirty, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -359,13 +389,31 @@ pub(crate) enum PassOwnerArena { } impl PassOwnerArena { - /// Returns the pass slot and its tilemap dirty high-water mark for global slot `k`. - pub(crate) fn pass_and_tilemap_dirty(&self, k: usize) -> Option<(&PassSlot, &AtomicU64)> { + /// Returns the pass slot and its dirty/clean WC span trackers for global slot `k`. + pub(crate) fn pass_and_dirty(&self, k: usize) -> Option<(&PassSlot, PassDirty<'_>)> { match self { - Self::Base(arena) => Some((arena.passes.get(k)?, arena.tilemap_dirty.get(k)?)), + Self::Base(arena) => Some(( + arena.passes.get(k)?, + PassDirty { + tpc: arena.tpc_dirty.get(k)?, + tilemap: arena.tilemap_dirty.get(k)?, + tilemap_last: arena.tilemap_last.get(k)?, + tilemap_clean: arena.tilemap_clean.get(k)?, + heap: arena.heap_dirty.get(k)?, + }, + )), Self::Ext(arena) => { let idx = k.checked_sub(arena.start)?; - Some((arena.passes.get(idx)?, arena.tilemap_dirty.get(idx)?)) + Some(( + arena.passes.get(idx)?, + PassDirty { + tpc: arena.tpc_dirty.get(idx)?, + tilemap: arena.tilemap_dirty.get(idx)?, + tilemap_last: arena.tilemap_last.get(idx)?, + tilemap_clean: arena.tilemap_clean.get(idx)?, + heap: arena.heap_dirty.get(idx)?, + }, + )) } } } @@ -955,25 +1003,43 @@ impl Prepared { .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)> { + /// The dirty high-water marks and clean prefix trackers for pass slot `k`. + pub(crate) fn render_pass_dirty(&self, k: usize) -> Result> { let base = self.render()?; if k < base.passes.len() { - Ok((&base.tpc_dirty[k], &base.tilemap_dirty[k])) + Ok(PassDirty { + tpc: &base.tpc_dirty[k], + tilemap: &base.tilemap_dirty[k], + tilemap_last: &base.tilemap_last[k], + tilemap_clean: &base.tilemap_clean[k], + heap: &base.heap_dirty[k], + }) } else { let (tier, idx) = self.render_ext_for(k).ok_or(EINVAL)?; - Ok((&tier.tpc_dirty[idx], &tier.tilemap_dirty[idx])) + Ok(PassDirty { + tpc: &tier.tpc_dirty[idx], + tilemap: &tier.tilemap_dirty[idx], + tilemap_last: &tier.tilemap_last[idx], + tilemap_clean: &tier.tilemap_clean[idx], + heap: &tier.heap_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 { + /// Updates dirty high-water marks and last-used spans for pass slot `k` (base or extension). + pub(crate) fn set_pass_dirty(&self, k: usize, tpc: u64, tilemap: u64, heap: u64) -> Result { let pass = self.render_pass(k)?; - if tpc > pass.tpc.size as u64 || tilemap > pass.tilemap.size as u64 { + if tpc > pass.tpc.size as u64 + || tilemap > pass.tilemap.size as u64 + || heap > pass.heap.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); + let dirty = self.render_pass_dirty(k)?; + dirty.tpc.fetch_max(tpc, Ordering::Relaxed); + dirty.tilemap.fetch_max(tilemap, Ordering::Relaxed); + dirty.tilemap_last.store(tilemap, Ordering::Relaxed); + dirty.tilemap_clean.store(0, Ordering::Relaxed); + dirty.heap.fetch_max(heap, Ordering::Relaxed); Ok(()) } /// The arena owning render pass slot `k`. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 39e588e768649b..bb85a172bebc6d 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -272,35 +272,42 @@ impl PassSlot { /// 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`. + /// `prefix_render`), unused scratch objects (`ta_scratch`, `fs_scratch`, `its`), bulk + /// scratch (`aux`, `scene_user`), preemption save areas (`pre[0..2]`), and `tpc` + /// (overwritten by TA hardware), zeroing only the active `tilemap` delta span and the + /// active `heap` metadata header (`0x200` single-layer, `0x1000` multi-layer). First use, + /// cross-VM switch, cancelled preparation, or post-recovery/error reuse runs the full + /// scrub including `tpc_dirty`, `its`, `scene`, `pre[0..2]`, and full `heap`. /// Clean same-VM reset of the active per-pass WC spans (used both synchronously on fallback /// and off-lock after displacement). - pub(crate) fn scrub_clean(&self, pre_records: u32, tilemap_dirty: u64) -> Result { - let r = pre_records as usize; - self.its.fill(0, 0, 32)?; - self.tilemap.fill(0, 0, tilemap_dirty as usize)?; - 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)?; + pub(crate) fn scrub_clean( + &self, + tilemap_start: u64, + tilemap_len: u64, + heap_dirty: u64, + ) -> Result { + if tilemap_len != 0 { + self.tilemap + .fill(tilemap_start as usize, 0, tilemap_len as usize)?; + } + if heap_dirty != 0 { + self.heap.fill(0, 0, heap_dirty as usize)?; + } Ok(()) } fn scrub( &self, - pre_records: u32, tpc_dirty: u64, - tilemap_dirty: u64, + tilemap_start: u64, + tilemap_len: u64, + heap_dirty: u64, full: bool, stats: &mut SlotStats, ) -> Result { if !full { - self.scrub_clean(pre_records, tilemap_dirty)?; - stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_dirty); + self.scrub_clean(tilemap_start, tilemap_len, heap_dirty)?; + stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_len); stats.pass_scrubs = stats.pass_scrubs.saturating_add(1); return Ok(()); } @@ -314,8 +321,8 @@ impl PassSlot { self.its.fill(0, 0, 32)?; self.tpc.fill(0, 0, tpc_dirty as usize)?; stats.tpc_clear_bytes = stats.tpc_clear_bytes.saturating_add(tpc_dirty); - self.tilemap.fill(0, 0, tilemap_dirty as usize)?; - stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_dirty); + self.tilemap.fill(0, 0, tilemap_len as usize)?; + stats.tilemap_clear_bytes = stats.tilemap_clear_bytes.saturating_add(tilemap_len); self.aux.fill(0, 0, 0x20000)?; self.heap.fill(0, 0, 0x4000)?; self.scene.fill(0, 0, super::fw::work::scene::SIZE)?; @@ -509,17 +516,28 @@ impl PendingScrub { let bit = 1u64 << self.slot; let ok = if self.state.generation.load(Ordering::Acquire) != self.generation { false - } else if let Some((pass, tilemap_dirty)) = self.arena.pass_and_tilemap_dirty(self.slot) { - let dirty = tilemap_dirty.load(Ordering::Acquire); - match pass.scrub_clean(1, dirty) { + } else if let Some((pass, d)) = self.arena.pass_and_dirty(self.slot) { + let dirty = d.tilemap.load(Ordering::Acquire); + let last = d.tilemap_last.load(Ordering::Acquire); + let already = d.tilemap_clean.load(Ordering::Acquire); + let heap = d.heap.load(Ordering::Acquire); + let target = if last != 0 { dirty.min(last) } else { dirty }; + let len = target.saturating_sub(already); + match pass.scrub_clean(already, len, heap) { Ok(()) => { // Order scrubbed WC bytes before clearing dirty / publishing clean_mask. super::engine::wmb(); - tilemap_dirty.store(0, Ordering::Release); + d.heap.store(0, Ordering::Release); + if target >= dirty { + d.tilemap.store(0, Ordering::Release); + d.tilemap_clean.store(0, Ordering::Release); + } else { + d.tilemap_clean.store(target, Ordering::Release); + } self.state.pass_scrubs.fetch_add(1, Ordering::Relaxed); self.state .tilemap_clear_bytes - .fetch_add(dirty, Ordering::Relaxed); + .fetch_add(len, Ordering::Relaxed); true } Err(_) => false, @@ -1003,6 +1021,7 @@ impl Slots { picked: u64, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); + let mut clean_partial = None; let mut fallback = None; let mut saw_scrubbing = false; for i in 0..n { @@ -1020,13 +1039,22 @@ impl Slots { continue; } if self.scrub.is_clean(k) { - return Some(k); + if let Ok(d) = resources.render_pass_dirty(k) { + let need = d.tilemap.load(Ordering::Acquire).min(geo.tilemap_bytes); + if need <= d.tilemap_clean.load(Ordering::Acquire) + && d.heap.load(Ordering::Acquire) == 0 + { + return Some(k); + } + } + clean_partial.get_or_insert(k); + continue; } fallback.get_or_insert(k); } } - if fallback.is_some() { - return fallback; + if let Some(k) = clean_partial.or(fallback) { + return Some(k); } if saw_scrubbing { self.scrub.waiter.store(true, Ordering::SeqCst); @@ -1079,22 +1107,33 @@ impl Slots { .is_none_or(|prev| prev.id != id) }); let pre_cleaned = self.scrub.take_clean(k); - if full || !pre_cleaned { - 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, - ) { + let p = &arena.passes[k]; + if full { + let prev_tpc = arena.tpc_dirty[k].load(Ordering::Acquire); + let prev_tilemap = arena.tilemap_dirty[k].load(Ordering::Acquire); + if let Err(e) = p.scrub(prev_tpc, 0, prev_tilemap, 0x4000, true, &mut self.stats) { self.render.lifetime.cancel(k); return Err(e); } - if full { - arena.tpc_dirty[k].store(0, Ordering::Relaxed); - } + arena.tpc_dirty[k].store(0, Ordering::Relaxed); arena.tilemap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_last[k].store(0, Ordering::Relaxed); + arena.tilemap_clean[k].store(0, Ordering::Relaxed); + arena.heap_dirty[k].store(0, Ordering::Relaxed); + } else { + let prev_dirty = arena.tilemap_dirty[k].load(Ordering::Acquire); + let already = arena.tilemap_clean[k].load(Ordering::Acquire); + let heap = arena.heap_dirty[k].load(Ordering::Acquire); + let delta = prev_dirty.saturating_sub(already); + if !(pre_cleaned && delta == 0 && heap == 0) { + if let Err(e) = p.scrub(0, already, delta, heap, false, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + arena.heap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_dirty[k].store(0, Ordering::Relaxed); + arena.tilemap_clean[k].store(0, Ordering::Relaxed); + } } self.render.last_full[k] = full; self.pass_cursor = ((k + 1) % n) as u32; @@ -1121,31 +1160,41 @@ impl Slots { .is_none_or(|prev| prev.id != id) }); let pre_cleaned = self.scrub.take_clean(k); - if full || !pre_cleaned { - 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), - clear_tilemap, - full, - &mut self.stats, - ) { + let p = resources.render_pass(k)?; + let d = resources.render_pass_dirty(k)?; + if full { + let prev_tpc = d.tpc.load(Ordering::Acquire); + let prev_tilemap = d.tilemap.load(Ordering::Acquire); + if let Err(e) = p.scrub(prev_tpc, 0, prev_tilemap, 0x4000, true, &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); + d.tpc.store(0, Ordering::Relaxed); + d.tilemap.store(0, Ordering::Relaxed); + d.tilemap_last.store(0, Ordering::Relaxed); + d.tilemap_clean.store(0, Ordering::Relaxed); + d.heap.store(0, Ordering::Relaxed); + } else { + // On clean same-VM reuse, zero only the uncleaned overlap with the current pass's + // tilemap (`already..need`) and the active heap span; preserve the high-water mark + // in `d.tilemap` for cross-VM or recovery full scrubs. + let prev_dirty = d.tilemap.load(Ordering::Acquire); + let already = d.tilemap_clean.load(Ordering::Acquire); + let heap = d.heap.load(Ordering::Acquire); + let need = prev_dirty.min(tilemap_bytes); + let delta = need.saturating_sub(already); + if !(pre_cleaned && delta == 0 && heap == 0) { + if let Err(e) = p.scrub(0, already, delta, heap, false, &mut self.stats) { + self.render.lifetime.cancel(k); + return Err(e); + } + d.heap.store(0, Ordering::Relaxed); + if prev_dirty != 0 && need >= prev_dirty { + d.tilemap.store(0, Ordering::Relaxed); + d.tilemap_clean.store(0, Ordering::Relaxed); + } else if delta != 0 { + d.tilemap_clean.store(need, Ordering::Relaxed); + } } } self.render.last_full[k] = full; 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 ab43a6aaa12c21..5409982dc89545 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -146,6 +146,7 @@ def module(text, name): } pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; + pub struct PassDirty<'a>{pub tpc:&'a AtomicU64,pub tilemap:&'a AtomicU64,pub tilemap_last:&'a AtomicU64,pub tilemap_clean:&'a AtomicU64,pub heap:&'a AtomicU64} pub struct ComputeArena{pub compute:KVec,pub render:Option>} // A job's compute units; here one arena. pub type Prepared=ComputeArena; @@ -155,8 +156,8 @@ def module(text, name): #[derive(Clone)] pub enum PbOwnerArena{Base(crate::sync::Arc),Ext(crate::sync::Arc,crate::sync::Arc)} impl PassOwnerArena{ - pub fn pass_and_tilemap_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,&AtomicU64)>{ - match self{Self::Base(a)=>Some((a.passes.get(k)?,a.tilemap_dirty.get(k)?))} + pub fn pass_and_dirty(&self,k:usize)->Option<(&super::slots::PassSlot,PassDirty<'_>)>{ + match self{Self::Base(a)=>Some((a.passes.get(k)?,PassDirty{tpc:a.tpc_dirty.get(k)?,tilemap:a.tilemap_dirty.get(k)?,tilemap_last:a.tilemap_last.get(k)?,tilemap_clean:a.tilemap_clean.get(k)?,heap:a.heap_dirty.get(k)?}))} } } impl ComputeArena{ @@ -166,10 +167,11 @@ def module(text, name): pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} - pub fn render_pass_dirty(&self,k:usize)->Result<(&AtomicU64,&AtomicU64)>{let r=self.render.as_deref().ok_or(EINVAL)?;if k>=r.passes.len(){return Err(EINVAL);}Ok((&r.tpc_dirty[k],&r.tilemap_dirty[k]))} + pub fn render_pass_dirty(&self,k:usize)->Result>{let r=self.render.as_deref().ok_or(EINVAL)?;if k>=r.passes.len(){return Err(EINVAL);}Ok(PassDirty{tpc:&r.tpc_dirty[k],tilemap:&r.tilemap_dirty[k],tilemap_last:&r.tilemap_last[k],tilemap_clean:&r.tilemap_clean[k],heap:&r.heap_dirty[k]})} + pub fn set_pass_dirty(&self,k:usize,tpc:u64,tilemap:u64,heap:u64)->Result{let p=self.render_pass(k)?;if tpc>p.tpc.size as u64||tilemap>p.tilemap.size as u64||heap>p.heap.size as u64{return Err(E2BIG);}let d=self.render_pass_dirty(k)?;d.tpc.fetch_max(tpc,Ordering::Relaxed);d.tilemap.fetch_max(tilemap,Ordering::Relaxed);d.tilemap_last.store(tilemap,Ordering::Relaxed);d.tilemap_clean.store(0,Ordering::Relaxed);d.heap.fetch_max(heap,Ordering::Relaxed);Ok(())} pub fn pass_owner_arena(&self,_k:usize)->Option{self.render.as_ref().map(|r|PassOwnerArena::Base(r.clone()))} } - pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} + pub struct RenderArena{pub passes:KVec,pub tpc_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_last:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub tilemap_clean:[AtomicU64;super::hw::sizes::RENDER_SLOTS],pub heap_dirty:[AtomicU64;super::hw::sizes::RENDER_SLOTS]} impl RenderArena{ __SET_DIRTY__ } pub(crate) const BASE_COMPUTE_UNITS: usize = 2; pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; @@ -195,10 +197,20 @@ def module(text, name): #[cfg(test)]mod resources { use super::*;use g16::{object::Objects,slots::{Slots,Claims},pools::PoolSet}; struct Arenas{compute:g16::resources::ComputeArena,render:g16::resources::RenderArena} + fn render_arena(passes:KVec)->g16::resources::RenderArena{ + g16::resources::RenderArena{ + passes, + tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_last:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + tilemap_clean:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + heap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], + } + } 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:None},render:g16::resources::RenderArena{passes,tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS],tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS]}} + Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<bool{let mut q=g16::slots::ScrubQueue::new();q.push_batch(batch);let mut wake=false;while let Some(mut item)=q.pop(){wake|=item.run_one();}wake} @@ -547,7 +559,7 @@ def module(text, name): 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/scene. + // Same-VM clean reuse of slot 0: clears tilemap and active heap(0x200) only; skips aux/tpc/scratch/scene/its/pre. 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); @@ -556,9 +568,12 @@ def module(text, name): assert_eq!(p0.scene_user.fills.lock().unwrap().len(),1); assert_eq!(p0.scene_list.fills.lock().unwrap().len(),1); assert_eq!(p0.tpc.fills.lock().unwrap().len(),1); + assert_eq!(p0.its.fills.lock().unwrap().len(),1); + assert_eq!(p0.pre[0].fills.lock().unwrap().len(),1); + assert_eq!(p0.pre[1].fills.lock().unwrap().len(),1); + assert_eq!(p0.pre[2].fills.lock().unwrap().len(),1); assert_eq!(p0.tilemap.fills.lock().unwrap().last(),Some(&(0,0x4000))); - assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x1000))); - assert_eq!(p0.pre[0].fills.lock().unwrap().last(),Some(&(0,0x540))); + assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x200))); // Preserved tpc_dirty high-water mark is still cleared on cross-VM switch. arena.render.set_dirty(0,0x2000,0x1000).unwrap(); retire(&mut s,0,&a); @@ -568,6 +583,8 @@ def module(text, name): 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.its.fills.lock().unwrap().len(),2); + assert_eq!(p0.pre[0].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))); assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); @@ -832,11 +849,7 @@ def module(text, name): } passes.push(pass,0).unwrap(); } - let arena=g16::resources::RenderArena{ - passes, - tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - }; + let arena=render_arena(passes); let a=vm(1); let b=vm(2); let mut live:Vec=Vec::new(); @@ -893,7 +906,9 @@ def module(text, name): s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x2000,0x4000).unwrap(); render.passes[0].tilemap.fill(0,0xab,0x4000).unwrap(); - render.passes[0].its.fill(0,0xcd,32).unwrap(); + render.passes[0].heap.fill(0,0xcd,0x200).unwrap(); + let its_before=render.passes[0].its.fills.lock().unwrap().len(); + let pre0_before=render.passes[0].pre[0].fills.lock().unwrap().len(); s.retire(&mut c0).unwrap(); s.stage_displaced_pass_scrubs(); assert!(!s.scrubbing_active()); @@ -913,16 +928,21 @@ def module(text, name): assert!(drain_scrubs(batch)); assert!(!s.scrubbing_active()); assert!(render.passes[0].tilemap.snapshot()[..0x4000].iter().all(|&b|b==0)); - assert!(render.passes[0].its.snapshot()[..32].iter().all(|&b|b==0)); + assert!(render.passes[0].heap.snapshot()[..0x200].iter().all(|&b|b==0)); + assert_eq!(render.passes[0].its.fills.lock().unwrap().len(),its_before); + assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); + assert_eq!(render.heap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); // Next same-VM claim picks pre-cleaned slot 0 and performs zero WC fills under lock. let fills_before=render.passes[0].tilemap.fills.lock().unwrap().len(); - let its_before=render.passes[0].its.fills.lock().unwrap().len(); + let heap_before=render.passes[0].heap.fills.lock().unwrap().len(); assert_eq!(s.pick_pass_in(&prep,&geo,0),Some(0)); s.claim_pass_in(&prep,0,Some(a.id),0x4000).unwrap(); assert!(!s.render_needs_full_work(0)); assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().len(),fills_before); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().len(),heap_before); assert_eq!(render.passes[0].its.fills.lock().unwrap().len(),its_before); + assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); } #[test]fn offlock_scrub_falls_back_on_error_drop_recovery_and_cross_vm(){ @@ -1058,11 +1078,7 @@ def module(text, name): 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 render=sync::Arc::new(g16::resources::RenderArena{ - passes, - tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - },0).unwrap(); + let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; let a=vm(1); // Wrapped submission order [46, 47, 0]: retiring in order leaves slot 0 as last_retired @@ -1124,11 +1140,7 @@ def module(text, name): 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 render=sync::Arc::new(g16::resources::RenderArena{ - passes, - tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - },0).unwrap(); + let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; let a=vm(1);let b=vm(2); @@ -1334,11 +1346,7 @@ def module(text, name): for k in 0..4u64 { passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } - let render=sync::Arc::new(g16::resources::RenderArena{ - passes, - tpc_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - tilemap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], - },0).unwrap(); + let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render)}; let a=vm(1);let b=vm(2); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x1000}; @@ -1425,6 +1433,75 @@ def module(text, name): assert!(s.render_needs_full_work(0)); } + #[test]fn lazy_tilemap_prefix_scrub_and_classed_slot_selection_avoid_overscrub(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..3u64 { + passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes),0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone())}; + let a=vm(1);let b=vm(2); + let pub_retire=|s:&mut Slots,k:usize,vm:&sync::Arc|{ + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1u64< dirty=0x10000, last=0x2000. + s.claim_pass_in(&prep,0,Some(a.id),0x10000).unwrap(); + prep.set_pass_dirty(0,0x2000,0x10000,0x200).unwrap(); + render.passes[0].tilemap.fill(0,0x55,0x10000).unwrap(); + pub_retire(&mut s,0,&a); + s.claim_pass_in(&prep,1,Some(a.id),0x2000).unwrap(); + prep.set_pass_dirty(1,0x1000,0x2000,0x200).unwrap(); + pub_retire(&mut s,1,&a); + // Synchronous small claim on slot 0 only zeroes 0..0x2000 and leaves 0x2000..0x10000 dirty. + s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0,0x2000))); + assert_eq!(render.passes[0].tilemap.snapshot()[0x2000],0x55); + prep.set_pass_dirty(0,0x1000,0x2000,0x1000).unwrap(); // multi-layer heap=0x1000 + render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); + render.passes[0].heap.fill(0,0x77,0x1000).unwrap(); + pub_retire(&mut s,0,&a); + // Slot 2 retires to displace slot 0; both slot 0 (partial) and slot 1 (fully clean) scrub off-lock. + s.claim_pass_in(&prep,2,Some(a.id),0x2000).unwrap(); + prep.set_pass_dirty(2,0x1000,0x2000,0x200).unwrap(); + pub_retire(&mut s,2,&a); + s.stage_displaced_pass_scrubs(); + let _=drain_scrubs(s.take_staged_scrubs()); + // Slot 0 off-lock scrubbed ONLY 0..0x2000 tilemap and 0..0x1000 heap; high-water 0x10000 preserved! + assert_eq!(render.tilemap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0x10000); + assert_eq!(render.tilemap_clean[0].load(std::sync::atomic::Ordering::Acquire),0x2000); + assert_eq!(render.heap_dirty[0].load(std::sync::atomic::Ordering::Acquire),0); + assert!(render.passes[0].tilemap.snapshot()[..0x2000].iter().all(|&x|x==0)); + assert_eq!(render.passes[0].tilemap.snapshot()[0x2000],0x55); + assert!(render.passes[0].heap.snapshot()[..0x1000].iter().all(|&x|x==0)); + // Slot 1 off-lock scrubbed fully (dirty=0, clean=0). + assert_eq!(render.tilemap_dirty[1].load(std::sync::atomic::Ordering::Acquire),0); + assert_eq!(render.tilemap_clean[1].load(std::sync::atomic::Ordering::Acquire),0); + // Cursor starts at 0 (after slot 2): small pass (0x2000) picks slot 0 (exact clean prefix), + // while large pass (0x8000) prefers slot 1 (zero sync delta) over partial-clean slot 0! + let small=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; + let large=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x8000}; + assert_eq!(s.pick_pass_in(&prep,&small,0),Some(0)); + assert_eq!(s.pick_pass_in(&prep,&large,0),Some(1)); + // Claiming partial-clean slot 0 for a medium pass (0x6000) zeroes ONLY tail delta (0x2000, 0x4000) + // and performs zero heap fills. + let heap_before=render.passes[0].heap.fills.lock().unwrap().len(); + s.claim_pass_in(&prep,0,Some(a.id),0x6000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0x2000,0x4000))); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().len(),heap_before); + assert!(render.passes[0].tilemap.snapshot()[..0x6000].iter().all(|&x|x==0)); + assert_eq!(render.passes[0].tilemap.snapshot()[0x6000],0x55); + pub_retire(&mut s,0,&a); + // Cross-VM switch on slot 0 still full-scrubs the preserved high-water mark (0x10000) + full heap (0x4000). + s.claim_pass_in(&prep,1,Some(a.id),0x2000).unwrap(); + pub_retire(&mut s,1,&a); + s.claim_pass_in(&prep,0,Some(b.id),0x2000).unwrap(); + assert_eq!(render.passes[0].tilemap.fills.lock().unwrap().last(),Some(&(0,0x10000))); + assert_eq!(render.passes[0].heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); + assert!(render.passes[0].tilemap.snapshot()[..0x10000].iter().all(|&x|x==0)); + } + } ''' poll_source = (production/'poll.rs').read_text() @@ -1496,7 +1573,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 34, + 'result': 'pass', 'tests': 35, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 0f9e744f583c183c90edc3b903f8a236e0151fb2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:02:07 -0500 Subject: [PATCH 0867/1514] drm/asahi/g16: pace unfinished TA passes in <=3-pass waves with immediate doorbells Keep multi-pass render bursts from flooding TA work ahead of the tiler while leaving single-pass pipelining (where TA completes well ahead of FS) unthrottled: - Add `sizes::TA_WAVE_PASSES = 3` and `Firmware::ta_pending_passes()`, which skips WC reads whenever active render passes are already below the threshold and otherwise counts active render passes whose `r_ta_stamp` has not yet been reached by `render.fw_stamp[0]`. - Cap multi-pass batching in `publish_prefix_body()` and gate `can_queue_behind()` on `ta_pending_passes() < TA_WAVE_PASSES`. - Flush FS+TA doorbells immediately in `publish_checked()` once a render wave reaches `TA_WAVE_PASSES` so the GPU begins tiling without waiting behind further loop iterations or alt-class compute publications. - Record `Engine::ta_wave_wait` when a ready render job pauses solely on the TA wave cap, and wake `publish_checked()` in `poll_step()` via `ta_wave_ready()` when a `0x70` TA event advances TA without spinning `retry_tail` or arming `short_repoll`. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 64 ++++++- drivers/gpu/drm/asahi/g16/hw.rs | 4 + drivers/gpu/drm/asahi/g16/poll.rs | 9 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 57 ++++++- .../drivers/gpu/asahi-m4/test-publication.py | 156 ++++++++++++++---- 5 files changed, 254 insertions(+), 36 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index d5aad8a6aa3183..2199432543ca03 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -559,6 +559,8 @@ pub(crate) struct Engine { /// headroom (not cross-VM/InitBM drain, external fences, or CPU timestamp waits): repoll /// sooner to refill freed slots promptly. pub(crate) slot_wait: bool, + /// A ready same-VM render job is paused by `TA_WAVE_PASSES` pacing until TA advances. + pub(crate) ta_wave_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 compute and render flights. @@ -600,6 +602,7 @@ impl Engine { ta_registered: false, chan_wait: false, slot_wait: false, + ta_wave_wait: false, short_repoll: false, progress_flight: [0; 2], progress: [None; 3], @@ -939,6 +942,7 @@ impl Firmware { self.engine.chan_wait = false; self.engine.slot_wait = false; + self.engine.ta_wave_wait = false; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -986,6 +990,17 @@ impl Firmware { .pending .iter() .any(|cand| self.blocked_on_slot_headroom(cand)); + self.engine.ta_wave_wait = self.ta_pending_passes() + >= super::hw::sizes::TA_WAVE_PASSES + && self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(_)) + ) && !self.needs_engine_drain(cand) + && cand + .check_command_dependencies(cand.progress.sent()) + .is_ok() + }); self.engine.stats.hold[0] += 1; break; } @@ -1082,6 +1097,24 @@ impl Firmware { if job.progress.sent() == job.progress.count() { self.engine.unpend(&job); // fully published } + // Ring TA/FS immediately once a render wave fills TA_WAVE_PASSES so the GPU + // starts tiling right away instead of waiting behind another loop iteration + // or an alt-class compute publication. + if pending_rings & ((1u8 << (Channel::Fs as u8)) | (1u8 << (Channel::Ta as u8))) + != 0 + && self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES + { + if let Err(e) = self.flush_doorbells(&mut pending_rings) { + dev_err!( + self.graph.dev.as_ref(), + "G16: render wave doorbell ring failed after visibility began ({:?})\n", + e + ); + self.fail_stop(EIO, done); + result = Err(EIO); + break; + } + } continue; } Err(PublicationError::Unpublished(e)) @@ -1239,6 +1272,33 @@ impl Firmware { } } + /// Unfinished TA passes across active render flights. Returns immediately without reading + /// WC memory when total active render passes are already below `TA_WAVE_PASSES`. + pub(crate) fn ta_pending_passes(&self) -> usize { + let active_renders: usize = self + .engine + .flights + .iter() + .map(|f| f.renders as usize) + .sum(); + if active_renders < super::hw::sizes::TA_WAVE_PASSES { + return active_renders; + } + let Ok(obs) = self.graph.render.fw_stamp[0].r32(0) else { + return active_renders; + }; + let tail = self.engine.ta_target; + let mut pending = 0usize; + for f in &self.engine.flights { + for &stamp in &f.r_ta_stamp[..(f.renders as usize).min(f.r_ta_stamp.len())] { + if !super::recovery::logic::stamp_reached(obs, stamp, tail) { + pending += 1; + } + } + } + pending + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy same-VM non-InitBM compute and/or render flights (up to @@ -1306,6 +1366,7 @@ impl Firmware { Some(Command::Render(_)) => { let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); render_count < params::render_flights() + && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() @@ -1847,7 +1908,8 @@ impl Firmware { .sum(); let mut more_renders = params::render_flights() .saturating_sub(active_renders + 1) - .min(sizes::RENDER_SLOTS.saturating_sub(1)); + .min(sizes::RENDER_SLOTS.saturating_sub(1)) + .min(sizes::TA_WAVE_PASSES.saturating_sub(self.ta_pending_passes() + 1)); while more_renders > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { break; diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 5468c0e0edbf96..0642bd6b9f3209 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -730,6 +730,10 @@ pub(crate) mod sizes { pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 4; /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + `work`). pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 2; + /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts pace + /// TA in `<= 3`-pass waves without throttling single-pass pipelining (where TA finishes + /// well ahead of FS). + pub(crate) const TA_WAVE_PASSES: usize = 3; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most. A slot is reused only after a later render diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index fd4669660e7fda..533d6a37c063a0 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -588,7 +588,8 @@ impl Firmware { // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), // while `publish_woke` covers external state changes (VM close, unstarted queue - // cancellation) so pending jobs never wait on the 1 ms housekeeping tick. + // cancellation) and `ta_wave_ready()` wakes TA-wave-paced renders when a `0x70` TA + // pass finishes while FS is still running. let should_publish = !self.engine.pending.is_empty() && (retired_any || !had_flights @@ -597,6 +598,7 @@ impl Firmware { || unfrozen || scrub_woke || publish_woke + || self.ta_wave_ready() || housekeeping_due); let published = if should_publish { self.publish_checked(done) @@ -717,6 +719,11 @@ impl Firmware { Some((compute, render)) } + /// Whether a render job paused by `TA_WAVE_PASSES` pacing can publish its next wave now. + fn ta_wave_ready(&self) -> bool { + self.engine.ta_wave_wait && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES + } + /// Cheap single-stage stamp check for the oldest compute and oldest render flights' terminal /// stages so `submit_locked()` can eagerly retire finished work without scanning all rings /// when nothing has completed. diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index c765ada5b31b81..b9fbd6a0e67bd2 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -53,6 +53,11 @@ def item(declaration, text=source): const HOUSEKEEPING_NS: u64 = 1_000_000; const AUX_DRAIN_NS: u64 = 10_000_000; const EVENT_RETIRE_POLLS: u32 = 11; +mod hw { + pub mod sizes { + pub const TA_WAVE_PASSES: usize = 3; + } +} thread_local! { static CLOCK: Cell = const { Cell::new(0) }; @@ -141,6 +146,7 @@ def item(declaration, text=source): fs_target: u32, chan_wait: bool, slot_wait: bool, + ta_wave_wait: bool, short_repoll: bool, frozen: bool, stats: Stats, @@ -270,6 +276,7 @@ def item(declaration, text=source): drain_stage_delta: u32, drain_fs_delta: u32, drain_compute_delta: u32, + ta_pending: usize, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, @@ -299,6 +306,7 @@ def item(declaration, text=source): fs_target: 0, chan_wait: false, slot_wait: false, + ta_wave_wait: false, short_repoll: false, frozen: false, stats: Stats::default(), @@ -315,6 +323,7 @@ def item(declaration, text=source): drain_stage_delta: 0, drain_fs_delta: 0, drain_compute_delta: 0, + ta_pending: 0, retire_calls: 0, publish_full_calls: 0, publish_checked_calls: 0, @@ -379,9 +388,13 @@ def item(declaration, text=source): self.publish_checked_calls += 1; Ok(()) } + fn ta_pending_passes(&self) -> usize { + self.ta_pending + } __POLL_STEP__ __OLDEST_TERMINAL_EVENTS__ + __TA_WAVE_READY__ __OLDEST_STAMP_REACHED__ } @@ -754,6 +767,45 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn ta_only_irq_wakes_ta_wave_wait_without_spinning_retry_tail() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + renders: 3, + target: 0, + fs_target: 0x300, + }); + fw.engine.fs_target = 0x300; + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.engine.ta_wave_wait = true; + fw.ta_pending = 3; + fw.drain_stage_delta = 1; + fw.drain_fs_delta = 0; + + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + // TA still full (3 >= 3): no publish_checked wakeup and no retry_tail spin. + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); + + // TA finishes one pass (ta_pending drops to 2 < 3) on a TA-only 0x70 IRQ while FS is still + // running: immediately wakes publish_checked() without spinning retry_tail or short_repoll. + fw.ta_pending = 2; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); +} + mod boot { pub fn eproto() -> super::Error { super::Error(-71) @@ -1255,13 +1307,14 @@ def item(declaration, text=source): '__POLL_STEP__': 'pub(crate) fn poll_step(', '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', + '__TA_WAVE_READY__': 'fn ta_wave_ready(', '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', '__REARM_US__': 'pub(crate) fn rearm_us(', '__REARM__': 'pub(crate) fn rearm(', '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): - harness = harness.replace(token, item(decl)) + harness = harness.replace(token, item(decl).replace('super::hw::', 'hw::')) for token, decl in { '__EVENT_DRAIN__': 'pub(crate) fn drain(', '__EVENT_DRAIN_STATS__': 'pub(crate) fn drain_statistics(', @@ -1285,7 +1338,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 17, + 'tests': 18, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', 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 b909d40dffb1a8..e8db28b2452282 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -109,9 +109,9 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],doomed:false,recovery_suspect:false,initbm:false}}} -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool} +struct Flight{job:Arc,claims:Claims,group:Vec>,renders:u32,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],renders:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ __UNPEND__ @@ -152,7 +152,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=3; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -203,10 +203,15 @@ def item(declaration): (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(())))) ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) } + fn ta_pending_passes(&self)->usize{ + self.engine.flights.iter().map(|f|f.renders as usize).sum() + } fn can_queue_behind(&self,job:&Arc)->bool{ if !self.allow_behind{return false;} if self.needs_engine_drain(job){return false;} - if self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(()))){return false;} + if matches!(command(job,job.progress.sent()),Some(Command::Render(()))){ + if self.block_render_behind||self.ta_pending_passes()>=hw::sizes::TA_WAVE_PASSES{return false;} + } if self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_))){return false;} true } @@ -234,6 +239,7 @@ def item(declaration): match command(job,idx){ Some(Command::Render(()))=>{ *pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8)); + fl.renders=1; fl.initbm=!self.pools.can_pipeline(&job.vm); } _=>{*pending_rings|=1<<(Channel::Compute as u8);} @@ -259,7 +265,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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,slot_wait:false}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false} @@ -498,6 +504,28 @@ def item(declaration): assert_eq!(j1.queue.turn.load(Ordering::Relaxed),11); assert_eq!(f.engine.turn,11); } + #[test]fn ta_wave_pacing_flushes_doorbell_at_three_passes_and_arms_ta_wave_wait(){ + let vm1=mk_vm(1); + let r1=job_on_vm(1,vm1.clone(),true,0,Ok(())); + let r2=job_on_vm(2,vm1.clone(),true,0,Ok(())); + let r3=job_on_vm(3,vm1.clone(),true,0,Ok(())); + let r4=job_on_vm(4,vm1.clone(),true,0,Ok(())); + let c5=job_on_vm(5,vm1,false,0,Ok(())); + let mut f=firmware( + vec![r1,r2,r3,r4,c5], + vec![(Ok(()),true),(Ok(()),true),(Ok(()),true),(Ok(()),true)], + ); + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + // Passes 1..3 fill TA_WAVE_PASSES (3) and ring FS+TA immediately; pass 4 pauses with + // ta_wave_wait=true while alt compute job 5 still publishes on Compute. + assert_eq!(f.attempted,[1,2,3,5]); + assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); + assert!(f.engine.ta_wave_wait); + assert!(!f.engine.slot_wait); + assert_eq!(f.engine.pending.len(),1); + } } #[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} @@ -512,8 +540,16 @@ def item(declaration): } } } -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} -struct QueueBehindEngine{ordinal:u64,draw:u64,flights:Vec} +struct QueueBehindStamp{val:std::cell::Cell,reads:std::cell::Cell} +impl QueueBehindStamp{ + fn new(v:u32)->Self{Self{val:std::cell::Cell::new(v),reads:std::cell::Cell::new(0)}} + fn r32(&self,_off:usize)->Result{self.reads.set(self.reads.get()+1);Ok(self.val.get())} +} +struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} +struct QueueBehindGraph{render:QueueBehindRenderGraph} +impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,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} @@ -527,7 +563,7 @@ def item(declaration): fn can_pipeline(&self,_vm:&Arc)->bool{self.can_pipeline} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} } -struct QueueBehindHost{engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} +struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { use super::*; type Job = QueueBehindJob; @@ -560,6 +596,7 @@ def item(declaration): impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ __BLOCKED_ON_SLOT_HEADROOM__ + __TA_PENDING_PASSES__ __CAN_QUEUE_BEHIND__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ @@ -580,7 +617,8 @@ def item(declaration): 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,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, }; @@ -618,7 +656,8 @@ def item(declaration): let no_barrier=mk(2,q1.clone(),true,None,None); let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, }; @@ -635,7 +674,8 @@ def item(declaration): extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let pr=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, }; @@ -658,7 +698,8 @@ 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,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, }; @@ -697,9 +738,10 @@ def item(declaration): let r2_after_c1=mk(4,q1.clone(),true,2,[Some(1),Some(1)]); let c_other_q=mk(5,q2.clone(),false,1,[None,None]); let p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![ + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -733,8 +775,9 @@ def item(declaration): let mut cstamp=[0u32;16]; cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let pm=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:3,draw:1,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,flights:vec![ + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -765,9 +808,10 @@ def item(declaration): let c_after_r=mk(2,false,1,[Some(1),None]); let r_after_r=mk(3,true,2,[Some(1),None]); let host=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{ job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,target:0, - cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, + cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -810,8 +854,9 @@ def item(declaration): extra_orders:vec![],dependency:Ok(()),resources:Resources, }); let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_fs_stamp:[0;16],fs_target:0, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,flights:vec![QueueBehindFlight{ + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -822,7 +867,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -847,8 +892,9 @@ def item(declaration): let mut cstamp=[0u32;16]; cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:3,draw:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,r_fs_stamp:[0;16],fs_target:0, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,flights:vec![QueueBehindFlight{ + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -886,8 +932,9 @@ def item(declaration): let mut r_fs=[0u32;16]; r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:0,draw:3,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,target:0,cstamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,flights:vec![QueueBehindFlight{ + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -902,18 +949,61 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); // Active renders sum flight.renders: 44 passes (4x11-pass postfx) still pipelines - // behind, while 47 batched renders saturates render_flights(). + // behind once TA has finished, while 47 batched renders saturates render_flights(). assert!(p.can_queue_behind(&next_r)); p.engine.flights[0].renders=44; assert!(p.can_queue_behind(&next_r)); p.engine.flights[0].renders=47; assert!(!p.can_queue_behind(&next_r)); } + #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let r_live=mk(1); + let next_r=mk(2); + let mut r_ta=[0u32;16]; + r_ta[0]=0x100;r_ta[1]=0x200;r_ta[2]=0x300; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0x300,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:3,computes:0,renders:2,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x300, + 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}, + }; + // Below TA_WAVE_PASSES (2 < 3): zero WC fw_stamp reads. + assert_eq!(p.ta_pending_passes(),2); + assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); + assert!(p.can_queue_behind(&next_r)); + // 3 unfinished TA passes: paces render queue_behind until TA advances. + p.engine.flights[0].renders=3; + assert_eq!(p.ta_pending_passes(),3); + assert!(p.graph.render.fw_stamp[0].reads.get()>0); + assert!(!p.can_queue_behind(&next_r)); + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 2. + p.graph.render.fw_stamp[0].val.set(0x100); + assert_eq!(p.ta_pending_passes(),2); + assert!(p.can_queue_behind(&next_r)); + // Even with 16 active FS passes, finished TA (obs=0x300) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x300); + p.engine.flights[0].renders=16; + assert_eq!(p.ta_pending_passes(),0); + assert!(p.can_queue_behind(&next_r)); + } #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let vm2=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:2}); @@ -931,9 +1021,10 @@ def item(declaration): let r_ext_fence=mk(4,vm1.clone(),true,Err(EAGAIN),false,[None,None]); let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); let mut p=QueueBehindHost{ - engine:QueueBehindEngine{ordinal:1,draw:1,flights:vec![QueueBehindFlight{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{ job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16], - r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, + r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1624,6 +1715,7 @@ def item(declaration): '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', + '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', @@ -1646,7 +1738,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 61, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 68, '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') From b5afc5584de2d54b6b4535fe86a2a3932847cf05 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:06:11 -0500 Subject: [PATCH 0868/1514] drm/asahi/g16: cache firmware-owned queue graph records and skip qinfo WC reads Keep command-pool allocations uncached (`tuning::FW_CACHED = false`), but map firmware-owned queue graph records (`qinfo`, `qscratch`, `job_list`) with `Class::FwCached` (`AP_RW` | `NormalWB` | `Inner` | `PXN` | `UXN` | `AF`) while keeping `sched_ctx` uncached (`Class::Fw`) to preserve the macOS 26B123 `t8132_queue_graph` memory contract. In `queue_receipt()` and `queue_passed()`, read `qstate::READ` from the existing NC `qstate` mapping instead of `qinfo::READ` so receipt/pass tracking never reads cached `qinfo` and skips unnecessary WC `qinfo` reads on the hot path. Add host unit tests in `test-resources.py` and `test-stamp-wrap.py` verifying `Class::FwCached` mapping for `qinfo`/`qscratch`/`job_list`, uncached `Class::Fw` for `sched_ctx`, `tuning::FW_CACHED == false`, and `queue_receipt()`/`queue_passed()` reading `qstate::READ`. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/graph.rs | 22 ++- drivers/gpu/drm/asahi/g16/poll.rs | 4 +- .../drivers/gpu/asahi-m4/test-resources.py | 64 ++++++++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 126 +++++++++++++++++- 4 files changed, 205 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 43e3bf90e24cd5..de1a19b1a08177 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -18,6 +18,15 @@ use super::object::{Class, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; +/// Firmware-owned queue graph records initialized once before `register_context()`. +/// Firmware reads and writes them through the ASC-cached mapping after initialization; +/// host receipt checks authenticate on NC `qstate::READ` and submit-pipe cursors. +pub(crate) const fn graph_fw() -> Class { + Class::FwCached +} +pub(crate) const fn qinfo_cached() -> bool { + matches!(graph_fw(), Class::FwCached) +} pub(crate) const fn cmd_fw() -> Class { if tuning::FW_CACHED { Class::FwCached @@ -42,7 +51,7 @@ pub(crate) const fn manager_class(class: Class) -> Class { } #[allow(dead_code)] pub(crate) const fn queue_scratch() -> Class { - cmd_fw() + graph_fw() } /// A private client alias uses the working M4 driver's AttrIndex-2 NC policy. @@ -127,7 +136,7 @@ struct QueueObjects { impl QueueObjects { fn new(o: &mut Objects) -> Result { Ok(Self { - qinfo: alloc(o, qinfo::SIZE, cmd_fw(), None, 0, false)?, + qinfo: alloc(o, qinfo::SIZE, graph_fw(), None, 0, false)?, qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, ring: alloc(o, sizes::QUEUE_CAP as usize * 8, cmd_fw(), None, 0, false)?, user_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, @@ -168,10 +177,11 @@ impl ComputeGraph { fn new(o: &mut Objects) -> Result { let q = QueueObjects::new(o)?; Ok(Self { - sched_ctx: alloc(o, sched_ctx::SIZE, cmd_fw(), None, 0, false)?, + // Host polls sched_ctx from WC during register_context(); keep uncached. + sched_ctx: alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, - job_list: alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, + job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, qscratch: q.qinfo.clone(), qinfo: q.qinfo, qstate: q.qstate, @@ -229,8 +239,8 @@ impl RenderGraph { notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: [ - alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, - alloc(o, job_list::SIZE, cmd_fw(), None, 0, false)?, + alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, + alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, ], legacy_empty: alloc(o, 0x40, Class::Shared, None, 0, false)?, registration_barrier: alloc( diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 533d6a37c063a0..800eae00d7aed6 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -868,7 +868,7 @@ impl Firmware { return Ok(false); } } - if !super::hw::tuning::FW_CACHED { + if !super::hw::tuning::FW_CACHED && !super::graph::qinfo_cached() { for offset in [0x20, 0x24, 0x28] { if info.r32(offset)? != head { return Ok(false); @@ -909,7 +909,7 @@ impl Firmware { if !ring_passed(state.r32(qstate::READ)?, start, head, tail, cap) { return Ok(false); } - if !super::hw::tuning::FW_CACHED { + if !super::hw::tuning::FW_CACHED && !super::graph::qinfo_cached() { for offset in [0x20, 0x24, 0x28] { if !ring_passed(info.r32(offset)?, start, head, tail, cap) { return Ok(false); 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 5409982dc89545..2d1655087e428f 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -118,11 +118,20 @@ def module(text, name): } pub mod graph { use crate::*;use crate::sync::Arc;use super::object::*; - use super::hw::{pte,tuning}; + use super::fw::graph::{self, job_list, notifier_page, qinfo, qstate, sched_ctx}; + use super::hw::{pte, sizes, tuning}; + #[derive(Copy, Clone)] + pub(crate) struct FwAbi; + impl FwAbi { + pub(crate) fn qinfo(self) -> &'static graph::qinfo::Layout { + &graph::qinfo::V25G83 + } + } __CLIENT__ __CMD_CLASSES__ __ALLOC__ __ALLOC_WORK__ + __GRAPH_TYPES__ } pub mod encode { pub struct Geometry{pub tpc_bytes:u64,pub tilemap_bytes:u64} @@ -1501,6 +1510,43 @@ def module(text, name): assert_eq!(render.passes[0].heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); assert!(render.passes[0].tilemap.snapshot()[..0x10000].iter().all(|&x|x==0)); } + #[test]fn queue_graph_objects_cache_only_firmware_owned_records(){ + use g16::object::Class; + use g16::graph::{ComputeGraph, FwAbi, RenderGraph, cmd_fw, cmd_shared, graph_fw, qinfo_cached}; + assert_eq!(graph_fw(), Class::FwCached); + assert!(qinfo_cached()); + assert_eq!(cmd_fw(), Class::Fw); + assert_eq!(cmd_shared(), Class::Shared); + let mut o = Objects::new(); + let c = ComputeGraph::new(&mut o).unwrap(); + let r = RenderGraph::new(&mut o, c.sched_ctx.clone()).unwrap(); + c.init(FwAbi).unwrap(); + r.init(FwAbi).unwrap(); + assert_eq!(c.qinfo.class, Class::FwCached); + assert_eq!(c.qscratch.class, Class::FwCached); + assert_eq!(c.job_list.class, Class::FwCached); + assert_eq!(c.sched_ctx.class, Class::Fw); + assert_eq!(c.qstate.class, Class::Fw); + assert_eq!(c.notifier.class, Class::Fw); + assert_eq!(c.threshold.class, Class::Fw); + assert_eq!(c.ring.class, Class::Fw); + assert_eq!(c.user_stamp.class, Class::Shared); + assert_eq!(c.fw_stamp.class, Class::Shared); + for stage in 0..2 { + assert_eq!(r.qinfo[stage].class, Class::FwCached); + assert_eq!(r.qscratch[stage].class, Class::FwCached); + assert_eq!(r.job_list[stage].class, Class::FwCached); + assert_eq!(r.qstate[stage].class, Class::Fw); + assert_eq!(r.ring[stage].class, Class::Fw); + assert_eq!(r.user_stamp[stage].class, Class::Shared); + assert_eq!(r.fw_stamp[stage].class, Class::Shared); + } + assert_eq!(r.sched_ctx.class, Class::Fw); + assert_eq!(r.notifier.class, Class::Fw); + assert_eq!(r.threshold.class, Class::Fw); + assert_eq!(r.legacy_empty.class, Class::Shared); + assert_eq!(r.registration_barrier.class, Class::Fw); + } } ''' @@ -1556,7 +1602,21 @@ def module(text, name): + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') ) -source = source.replace('__CMD_CLASSES__',item(graph_source,'pub(crate) const fn cmd_fw(')+'\n'+item(graph_source,'pub(crate) const fn cmd_shared(')).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) +source = source.replace('__CMD_CLASSES__', '\n'.join(item(graph_source, decl) for decl in ('pub(crate) const fn graph_fw(', 'pub(crate) const fn qinfo_cached(', 'pub(crate) const fn cmd_fw(', 'pub(crate) const fn cmd_shared('))).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) +graph_types = '\n'.join( + item(graph_source, decl) + for decl in ( + 'pub(crate) struct ComputeGraph {', + 'struct QueueObjects {', + 'impl QueueObjects {', + 'fn init_queue(', + 'fn init_notifier(', + 'impl ComputeGraph {', + 'pub(crate) struct RenderGraph {', + 'impl RenderGraph {', + ) +).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') +source = source.replace('__GRAPH_TYPES__', graph_types) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) (out/'check-resources.rs').write_text(source) 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 eb884621a68083..40cb941328485d 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 @@ -359,9 +359,133 @@ def function(text, name): assert_eq!(c.retired(),Ok(Retirement::Pending)); } +mod queue_proof { + use super::{Channel, Object, Result, EINVAL}; + use super::logic::ring_passed; + pub(crate) mod object { + pub(crate) type FwObject = super::Object; + } + pub(crate) mod hw { + __HW_CLIENT__ + __HW_ENGINE__ + __HW_TUNING__ + __HW_SIZES__ + } + pub(crate) mod fw { + pub(crate) mod channels { + pub(crate) const RING_SLOTS: u32 = 256; + } + } + pub(crate) mod graph { + #[derive(Copy, Clone, Debug, PartialEq, Eq)] + pub(crate) enum Class { Fw, FwCached } + __GRAPH_FW__ + __QINFO_CACHED__ + } + mod qstate { + pub(crate) const READ: usize = 0x10; + pub(crate) const WRITE: usize = 0x14; + } + struct QInfoLayout { busy: usize } + struct Abi; + impl Abi { fn qinfo(&self) -> QInfoLayout { QInfoLayout { busy: 0x30 } } } + struct Init { abi: Abi } + struct Pipe { read: u32, completion: u32, write: u32 } + impl Pipe { + fn read(&self) -> Result { Ok(self.read) } + fn completion(&self) -> Result { Ok(self.completion) } + fn write(&self) -> Result { Ok(self.write) } + } + struct Channels { compute: Pipe, ta: Pipe, fs: Pipe } + impl Channels { + fn channel(&self, ch: Channel) -> &Pipe { + match ch { Channel::Compute => &self.compute, Channel::Ta => &self.ta, Channel::Fs => &self.fs } + } + fn producer(&self, ch: Channel) -> u32 { self.channel(ch).write } + } + struct Engine { head: u32, ta_head: u32, fs_head: u32 } + struct Flight { c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3] } + struct Firmware { init: Init, channels: Channels, engine: Engine } + mod inner { + use super::*; + impl Firmware { + __QUEUE_RECEIPT__ + __QUEUE_PASSED__ + } + #[test] + fn cached_qinfo_skips_info_wc_reads_and_authenticates_on_nc_qstate_and_pipe() { + assert!(!hw::tuning::FW_CACHED); + assert!(graph::qinfo_cached()); + let mut fw = Firmware { + init: Init { abi: Abi }, + channels: Channels { + compute: Pipe { read: 5, completion: 5, write: 5 }, + ta: Pipe { read: 7, completion: 7, write: 7 }, + fs: Pipe { read: 9, completion: 9, write: 9 }, + }, + engine: Engine { head: 10, ta_head: 20, fs_head: 30 }, + }; + let mut state = Object::default(); + let mut info = Object::default(); + // Deliberately poison qinfo with stale consumer cursors and nonzero busy flag. + info.set(0x20, 0); + info.set(0x24, 0); + info.set(0x28, 0); + info.set(0x30, 1); + state.set(qstate::READ, 10); + state.set(qstate::WRITE, 10); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(true)); + assert_eq!(info.reads.get(), 0); + // Lagging NC qstate::READ or qstate::WRITE rejects receipt. + state.set(qstate::READ, 9); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + state.set(qstate::READ, 10); + state.set(qstate::WRITE, 11); + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + state.set(qstate::WRITE, 10); + // Lagging submit pipe completion rejects receipt. + fw.channels.compute.completion = 4; + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 10, 5), Ok(false)); + fw.channels.compute.completion = 5; + assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 256, 5), Err(EINVAL)); + assert_eq!(info.reads.get(), 0); + + // queue_passed with queued work behind flight (including wrap-around) never reads qinfo. + fw.engine.ta_head = 2; + fw.channels.ta = Pipe { read: 2, completion: 2, write: 3 }; + let f = Flight { c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; + state.set(qstate::READ, 1); + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(true)); + assert_eq!(info.reads.get(), 0); + // Unpassed NC qstate::READ rejects queue_passed. + state.set(qstate::READ, 255); + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(false)); + state.set(qstate::READ, 1); + // Unpassed pipe completion rejects queue_passed. + fw.channels.ta.completion = 0; + assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(false)); + assert_eq!(info.reads.get(), 0); + } + } +} + '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at')]: +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: harness=harness.replace(token,function((backend/path).read_text(),name)) +hw_text=(backend/'hw.rs').read_text() +def mod_block(text, name): + start=text.index('pub(crate) mod '+name+' {') + at=text.index('{',start) + depth,end=1,at+1 + while depth: + depth+=(text[end]=='{')-(text[end]=='}') + end+=1 + return text[start:end] +harness=(harness + .replace('__HW_CLIENT__',mod_block(hw_text,'client')) + .replace('__HW_ENGINE__',mod_block(hw_text,'engine')) + .replace('__HW_TUNING__',mod_block(hw_text,'tuning')) + .replace('__HW_SIZES__',mod_block(hw_text,'sizes'))) unit=out/'stamp-wrap.rs';unit.write_text(harness) log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'stamp-wrap')],[str(out/'stamp-wrap'),'--nocapture']]: From 47ede202464f4f5f3b51da408f820e15d112f162 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:12:50 -0500 Subject: [PATCH 0869/1514] drm/asahi/g16: fold cross-job same-queue render horizons up to TA wave cap Extend multi-pass render batching in `publish_prefix_body()` across consecutive ready, render-only same-queue and same-VM jobs in `self.engine.pending` up to the remaining `TA_WAVE_PASSES` (<= 3) wave budget, sharing one TA/FS producer advance, one UMA submitted update, and one SubmitRecord/doorbell pair: - Add `Job::can_fold_render_horizon_job()` verifying sequential render ordinals, ready inputs, healthy VM, and per-command dependency readiness treating earlier passes in the in-progress flight as published. - Parameterize `prefix_render()` with explicit `resources` and `cmd_index` (always binding pass slots and batched PB allocator refs against the primary flight's `Prepared`), and update `wait_stamp_for_with()` to walk `flight.group` members when resolving render `r_fs_stamp` barriers. - Commit per-job standby render reservations for both `f.job` and every folded member in `f.group`, handle `f.group` on `pools.retire_flight()` errors, and publish user timestamps for folded render `f.group` members in `publish_timestamps()`. - Add host unit tests for `can_fold_render_horizon_job()`, `flight.group` render wait-stamp resolution, and folded render group timestamp publication. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 224 ++++++++++++++++-- drivers/gpu/drm/asahi/g16/job.rs | 49 ++++ drivers/gpu/drm/asahi/g16/poll.rs | 25 +- .../drivers/gpu/asahi-m4/test-publication.py | 83 +++++++ .../drivers/gpu/asahi-m4/test-timestamps.py | 32 ++- 5 files changed, 389 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 2199432543ca03..d3a462d98c0334 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1437,12 +1437,15 @@ impl Firmware { if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { return None; } - let count = (flight.renders as usize).min(flight.r_fs_stamp.len()); - for member in 0..count { - let k = (flight.first + member) as u32; + let max_members = (flight.renders as usize).min(flight.r_fs_stamp.len()); + let mut member = 0usize; + for k in flight.first..flight.first + flight.count { + if member >= max_members { + return None; + } if flight .job - .command_order(k) + .command_order(k as u32) .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) { return Some(WaitTarget { @@ -1450,6 +1453,23 @@ impl Firmware { initbm: flight.initbm, }); } + member += 1; + } + for j2 in flight.group.iter() { + for k in 0..j2.progress.count() { + if member >= max_members { + return None; + } + if j2.command_order(k).is_some_and(|fo| { + fo.engine == super::command::RENDER && fo.sequence == last + }) { + return Some(WaitTarget { + stamp: flight.r_fs_stamp[member], + initbm: flight.initbm, + }); + } + member += 1; + } } None }; @@ -1895,10 +1915,23 @@ impl Firmware { f.claims.pass_count = 1; f.claims.pass_mask = 1u64 << k; self.slots.pass_busy |= 1u64 << k; - self.prefix_render(job, r, geometry, &mut prefix, f, behind, class_behind)?; + self.prefix_render( + job, + &job.resources, + index, + r, + geometry, + &mut prefix, + f, + behind, + class_behind, + )?; + f.count = 1; // Batch consecutive ready non-InitBM render passes of the same SUBMIT into // one TA/FS producer advance, one UMA submitted update, and one SubmitRecord. if !f.initbm { + let stage_prefix = + kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; let mut last_seq = job.command_order(index).map(|o| o.sequence); let active_renders: usize = self .engine @@ -1985,6 +2018,8 @@ impl Firmware { self.slots.pass_busy |= 1u64 << k2; self.prefix_render( job, + &job.resources, + end, r2, geo2, &mut prefix, @@ -1994,8 +2029,159 @@ impl Firmware { )?; last_seq = Some(next_seq); end += 1; + f.count = (end - index) as usize; more_renders -= 1; } + // Cross-job render horizon: fold subsequent ready render-only jobs of + // the same queue and VM into the same <= TA_WAVE_PASSES flight, sharing + // one TA/FS producer advance, one UMA submitted update, and one doorbell. + // Any non-qualifying job of this queue ends the scan so no later job + // overtakes it. + if end == job.progress.count() && more_renders > 0 { + let mut idx = 0; + while more_renders > 0 && idx < self.engine.pending.len() { + let j2 = self.engine.pending[idx].clone(); + idx += 1; + if Arc::ptr_eq(&j2, job) || !Arc::ptr_eq(&j2.queue, &job.queue) { + continue; + } + if 1 + f.group.len() >= sizes::HORIZON_JOBS as usize { + break; + } + let n2 = j2.progress.count(); + let n2_usize = n2 as usize; + let Some(first_seq) = last_seq.and_then(|s| s.checked_add(1)) else { + break; + }; + if !Arc::ptr_eq(&j2.vm, &job.vm) + || n2 == 0 + || n2_usize > more_renders + || !j2.can_fold_render_horizon_job(first_seq) + { + break; + } + let mut test_draw = prefix.draw; + let mut ord_ok = true; + for _ in 0..n2 { + match super::recovery::logic::next_ordinal(test_draw) { + Some(next) => test_draw = next, + None => { + ord_ok = false; + break; + } + } + } + if !ord_ok { + break; + } + let ta_used = + (prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP) as usize; + let fs_used = + (prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP) as usize; + let need_ring = n2_usize * 5; + if ta_used + need_ring >= sizes::QUEUE_CAP as usize + || fs_used + need_ring >= sizes::QUEUE_CAP as usize + { + break; + } + let mut picked = [0usize; sizes::TA_WAVE_PASSES]; + let mut picked_mask = f.claims.pass_mask; + let mut precheck_ok = true; + for k in 0..n2 { + let Some(Command::Render(r2)) = command(&j2, k) else { + precheck_ok = false; + break; + }; + let Some(o2) = j2.command_order(k) else { + precheck_ok = false; + break; + }; + let geo2 = Geometry::new(&r2.cmd, 0); + let Some(slot) = self.slots.pick_pass_in( + &job.resources, + &geo2, + picked_mask, + ) else { + precheck_ok = false; + break; + }; + let staged2 = r2.cmd.flags & stage_prefix != 0; + let render_wait_ok = |target: Option| -> bool { + match target { + None => true, + Some(seq) if seq >= first_seq => { + seq < first_seq + u64::from(k) + } + Some(seq) => self + .wait_stamp_for_with( + &j2, + super::command::RENDER, + Some(seq), + Some(f), + ) + .is_ok(), + } + }; + if self + .wait_stamp_for_with( + &j2, + super::command::COMPUTE, + o2.ta_wait_through[super::command::COMPUTE], + None, + ) + .is_err() + || self + .wait_stamp_for_with( + &j2, + super::command::COMPUTE, + o2.wait_through[super::command::COMPUTE], + None, + ) + .is_err() + || !render_wait_ok(o2.wait_through[super::command::RENDER]) + || (staged2 + && params::early_tiling() + && !render_wait_ok( + o2.ta_wait_through[super::command::RENDER], + )) + { + precheck_ok = false; + break; + } + picked[k as usize] = slot; + picked_mask |= 1u64 << slot; + } + if !precheck_ok || f.group.reserve(1, GFP_NOWAIT).is_err() { + break; + } + let _ = f.group.push_within_capacity(j2.clone()); + for k in 0..n2 { + let Some(Command::Render(r2)) = command(&j2, k) else { + return Err(EINVAL); + }; + let geo2 = Geometry::new(&r2.cmd, 0); + let slot = picked[k as usize]; + let member = prefix.renders as usize; + f.claims.pass[member] = slot as u32; + f.claims.pass_count += 1; + f.claims.pass_mask |= 1u64 << slot; + self.slots.pass_busy |= 1u64 << slot; + self.prefix_render( + &j2, + &job.resources, + k, + r2, + geo2, + &mut prefix, + f, + behind, + class_behind, + )?; + } + last_seq = Some(first_seq + u64::from(n2 - 1)); + more_renders -= n2_usize; + } + } } } } @@ -2033,7 +2219,10 @@ impl Firmware { if render { let a = f.pb_slot as usize; f.pb.as_ref().ok_or(EINVAL)?.expose(); - job.resources.commit_render(f.renders); + job.resources.commit_render(f.count as u32); + for j2 in f.group.iter() { + j2.resources.commit_render(j2.progress.count()); + } job.resources .publish_pb_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); @@ -2171,6 +2360,9 @@ impl Firmware { s.hz_behind += 1; } s.grouped = s.grouped.saturating_add(f.group.len() as u64); + } else if !f.group.is_empty() { + let s = &mut self.engine.stats; + s.grouped = s.grouped.saturating_add(f.group.len() as u64); } let mut flight = Flight::new(job.clone()); core::mem::swap(&mut flight, f); @@ -2345,9 +2537,15 @@ impl Firmware { /// Encodes paired TA/FS work and the fragment's explicit TA dependency in one retained /// pass unit. + #[expect( + clippy::too_many_arguments, + reason = "Encodes one render member into a shared flight and prefix state." + )] fn prefix_render( &mut self, job: &Arc, + resources: &super::resources::Prepared, + cmd_index: u32, cmd: &RenderCommand, mut geometry: Geometry, pf: &mut Prefix, @@ -2359,7 +2557,6 @@ impl Firmware { if member >= sizes::RENDER_SLOTS { return Err(EAGAIN); } - let cmd_index = (f.first + member) as u32; let k = f.claims.pass[member] as usize; let draw = super::recovery::logic::next_ordinal(pf.draw).ok_or(EOVERFLOW)?; let target = encode::stamp(draw); @@ -2430,10 +2627,10 @@ impl Firmware { ); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots - .claim_pass_in(&job.resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; - self.slots.hold_render_pass(k, &job.vm, &job.resources)?; + .claim_pass_in(resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; + self.slots.hold_render_pass(k, &job.vm, resources)?; let (refs, init_buffer) = if member == 0 { - let pb_slots = job.resources.pb_slots()?; + let pb_slots = resources.pb_slots()?; let alloc_slot = self .pools .pick_slot_within(&job.vm, behind, pb_slots) @@ -2452,7 +2649,7 @@ impl Firmware { let epoch = f.pb.as_ref().ok_or(EINVAL)?; let refs = self.render_refs_batched( f.pb_slot as usize, - job, + &f.job, draw, epoch, f.uma_submitted, @@ -2460,13 +2657,12 @@ impl Firmware { (refs, false) }; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); - let p = job.resources.render_pass(k)?; + let p = resources.render_pass(k)?; let pass = p.refs(); let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; geometry.layer_metadata = pass.heap_gva + if cmd.cmd.layers > 1 { 0x200 } else { 0 }; geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; - job.resources - .set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_bytes)?; + resources.set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_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/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 1464f1151738f8..3ab52248337680 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -405,6 +405,55 @@ impl Job { order.ready(completed, published) } + /// Whether every command of this job is a ready render command continuing a render + /// horizon sequentially from `first_expected` (treating earlier passes in the in-progress + /// render flight as already published). + pub(crate) fn can_fold_render_horizon_job(&self, first_expected: u64) -> bool { + let count = self.progress.count(); + if count == 0 + || self.progress.sent() != 0 + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + || super::fence::check_dependencies(&self.inputs).is_err() + { + return false; + } + let completed = self + .queue + .completed + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + let base_published = self + .queue + .published + .each_ref() + .map(|value| value.load(Ordering::Acquire)); + for k in 0..count { + let Some(expected) = first_expected.checked_add(u64::from(k)) else { + return false; + }; + let Some(Command::Render(_)) = self.commands.get(k as usize) else { + return false; + }; + let Some(order) = self.orders.get(k as usize) else { + return false; + }; + if order.engine != super::command::RENDER + || order.sequence != expected + || self.queue.check(order).is_err() + { + return false; + } + let mut published = base_published; + published[super::command::RENDER] = + published[super::command::RENDER].max(expected.saturating_sub(1)); + if !order.ready(completed, published) { + return false; + } + } + true + } + /// 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. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 800eae00d7aed6..ba67ff8354388a 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1288,6 +1288,10 @@ impl Firmware { if let Err(error) = committed { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; @@ -1449,8 +1453,8 @@ impl Firmware { } complete(done, &job, Ok(())); } - // Complete folded compute-horizon jobs unconditionally (even if an earlier render - // command of `job` is still in flight; `Timeline` preserves queue fence order). + // Complete folded horizon jobs unconditionally (even if an earlier command of `job` + // is still in flight; `Timeline` preserves queue fence order). for j2 in f.group.iter() { let p2 = &j2.progress; p2.next.store(p2.count(), Ordering::Relaxed); @@ -1594,7 +1598,22 @@ impl Firmware { } compute += 1; } - super::command::Command::Render(_) => return Err(EINVAL), + super::command::Command::Render(command) => { + let index = *passes.get(render).ok_or(EINVAL)? as usize; + if !command.timestamp_outputs.is_empty() { + let pass = flight.job.resources.render_pass(index)?; + let ticks = [ + pass.scene.r64(0x600)?, + pass.scene.r64(0x608)?, + pass.scene.r64(0x620)?, + pass.scene.r64(0x628)?, + ]; + command + .timestamp_outputs + .publish(ticks, super::hw::COMMAND_TIMESTAMP_HZ); + } + render += 1; + } } } } 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 e8db28b2452282..2c7d6f18c20fba 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -953,6 +953,30 @@ def item(declaration): initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); + // Cross-job render horizon flight resolves folded flight.group member stamps too. + let r_fold_a=Arc::new(QueueBehindJob{ + id:10,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let r_fold_b=Arc::new(QueueBehindJob{ + id:11,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let mut grp_fs=[0u32;16]; + grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; + let cur_grp=QueueBehindFlight{ + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(5),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); + assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(6),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x600,initbm:false}))); // Active renders sum flight.renders: 44 passes (4x11-pass postfx) still pipelines // behind once TA has finished, while 47 batched renders saturates render_flights(). assert!(p.can_queue_behind(&next_r)); @@ -1408,6 +1432,7 @@ def item(declaration): __CAN_FOLD_CMD__ __CAN_FOLD_JOB__ __CAN_FOLD_RENDER_CMD__ + __CAN_FOLD_RENDER_JOB__ } #[test] fn compute_horizon_eligibility_rejects_barriers_renders_unready_fences_and_gaps() { @@ -1530,6 +1555,58 @@ def item(declaration): assert!(!unready.can_fold_render_cmd(1, 2)); } + #[test] + fn can_fold_render_horizon_job_accepts_render_only_jobs_and_rejects_mixed_or_unready() { + let mk = |cmds: Vec, orders: Vec, inputs: Vec, pub_c: u64| Job { + vm: Vm { status: Status(AtomicU32::new(0)) }, + queue: Queue { + cancelled_compute: 0, + completed: [AtomicU64::new(0), AtomicU64::new(0)], + published: [AtomicU64::new(0), AtomicU64::new(pub_c)], + }, + progress: Progress { sent: 0, count: cmds.len() as u32 }, + commands: cmds, + orders, + inputs, + terminal_retired: AtomicBool::new(false), + }; + // Two-pass render job waiting on primary flight pass 1 and its own pass 2. + let r_job = mk( + vec![Command::Render(()), Command::Render(())], + vec![ + Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }, + Order { engine: command::RENDER, sequence: 3, wait_through: [Some(2), Some(5)] }, + ], + vec![true], + 4, + ); + // Compute dep 5 not yet published (published=4) -> rejected. + assert!(!r_job.can_fold_render_horizon_job(2)); + r_job.queue.published[command::COMPUTE].store(5, Ordering::Release); + assert!(r_job.can_fold_render_horizon_job(2)); + // Wrong sequence is rejected. + assert!(!r_job.can_fold_render_horizon_job(3)); + // Mixed compute+render job is rejected. + let mixed = mk( + vec![Command::Render(()), Command::Compute(())], + vec![ + Order { engine: command::RENDER, sequence: 2, wait_through: [None, None] }, + Order { engine: command::COMPUTE, sequence: 1, wait_through: [None, None] }, + ], + vec![true], + 5, + ); + assert!(!mixed.can_fold_render_horizon_job(2)); + // Pending input fence is rejected. + let unready = mk( + vec![Command::Render(())], + vec![Order { engine: command::RENDER, sequence: 2, wait_through: [Some(1), None] }], + vec![false], + 5, + ); + assert!(!unready.can_fold_render_horizon_job(2)); + } + mod recovery { pub(crate) mod logic { pub(crate) use crate::recovery::logic::RetiredStamps; @@ -1697,6 +1774,12 @@ def item(declaration): .replace('super::command::', 'command::') .replace('super::fence::', 'fence::'), ) +harness = harness.replace( + '__CAN_FOLD_RENDER_JOB__', + item_in(job_src, 'pub(crate) fn can_fold_render_horizon_job(') + .replace('super::command::', 'command::') + .replace('super::fence::', 'fence::'), +) harness = harness.replace( '__RECOVERY_PREPARE__', item('pub(crate) fn recovery_prepare(') 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 c765d42b1dca50..f0e9c9ffb0d4ca 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -152,7 +152,7 @@ def function(source, marker): pub mod hw{pub const COMMAND_TIMESTAMP_HZ:u64=24_000_000;} pub mod slots{ use super::*; - pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;2]} + pub struct Claims{pub slot:[u8;16],pub slot_count:u32,pub pass:[u8;4]} pub type ComputeSlot = Compute; } pub mod command{ @@ -199,7 +199,7 @@ def function(source, marker): Compute{its:Cells([30,40,0,0]),work:Cells([0,0,0,0])}, Compute{its:Cells([50,60,0,0]),work:Cells([0,0,0,0])}, ], - passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])}] + passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])},Pass{scene:Cells([900,1000,1100,1200])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ let compute=backing();let render=backing(); @@ -208,7 +208,7 @@ def function(source, marker): command::Command::Render(command::Render{timestamp_outputs:outputs(&render)}) ],resources:resources()},group:vec![],first:0,count:2,renders:1}; let mut slot=[0u8;16];slot[0]=1; - let claims=slots::Claims{slot,slot_count:1,pass:[1,0]}; + let claims=slots::Claims{slot,slot_count:1,pass:[1,0,0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); assert_eq!(compute.words[0].load(Ordering::Relaxed),expected(30)); assert_eq!(compute.words[1].load(Ordering::Relaxed),expected(40)); @@ -227,17 +227,35 @@ def function(source, marker): first:0,count:1,renders:0, }; let mut slot=[0u8;16];slot[0]=0;slot[1]=1;slot[2]=2; - let claims=slots::Claims{slot,slot_count:3,pass:[0,0]}; + let claims=slots::Claims{slot,slot_count:3,pass:[0,0,0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(10),expected(20))); assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(30),expected(40))); assert_eq!((c2.words[0].load(Ordering::Relaxed),c2.words[1].load(Ordering::Relaxed)),(expected(50),expected(60))); } +#[test]fn batched_render_horizon_group_timestamps_publish_for_all_members(){ + let r0=backing();let r1=backing();let r2=backing(); + let flight=Flight{ + job:Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r0)})],resources:resources()}, + group:vec![ + Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r1)})],resources:Resources{compute:vec![],passes:vec![]}}, + Job{commands:vec![command::Command::Render(command::Render{timestamp_outputs:outputs(&r2)})],resources:Resources{compute:vec![],passes:vec![]}}, + ], + first:0,count:1,renders:3, + }; + let claims=slots::Claims{slot:[0;16],slot_count:0,pass:[0,1,2,0]}; + firmware().publish_timestamps(&flight,&claims).unwrap(); + for (buf, ticks) in [(&r0,[100,200,300,400]),(&r1,[500,600,700,800]),(&r2,[900,1000,1100,1200])] { + for (index, tick) in ticks.into_iter().enumerate() { + assert_eq!(buf.words[index].load(Ordering::Relaxed), expected(tick)); + } + } +} #[test]fn invalid_command_span_and_missing_claim_are_rejected(){ let memory=backing();let mut flight=Flight{job:Job{commands:vec![ command::Command::Compute(command::Compute{timestamp_outputs:outputs(&memory)}) ],resources:resources()},group:vec![],first:usize::MAX,count:2,renders:0}; - let mut claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0]}; + let mut claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0,0,0]}; assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EOVERFLOW)); flight.first=1;assert_eq!(firmware().publish_timestamps(&flight,&claims),Err(EINVAL)); flight.first=0;flight.count=1;claims.slot_count=0; @@ -249,7 +267,7 @@ def function(source, marker): command::Command::Compute(command::Compute{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), command::Command::Render(command::Render{timestamp_outputs:Destinations(core::array::from_fn(|_|None))}), ],resources:Resources{compute:vec![],passes:vec![]}},group:vec![],first:0,count:2,renders:1}; - let claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0]}; + let claims=slots::Claims{slot:[0;16],slot_count:1,pass:[0,0,0,0]}; firmware().publish_timestamps(&flight,&claims).unwrap(); } #[test]fn work_ticks_fallback_publishes_compute_timestamps_for_26b123(){ @@ -269,7 +287,7 @@ def function(source, marker): first:0,count:1,renders:0, }; let mut slot=[0u8;16];slot[0]=0;slot[1]=1; - let claims=slots::Claims{slot,slot_count:2,pass:[0,0]}; + let claims=slots::Claims{slot,slot_count:2,pass:[0,0,0,0]}; fw.publish_timestamps(&flight,&claims).unwrap(); assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); From 9c19eb25948f9ff5bb9cb709c2143e7e84ab93e8 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:42:42 -0500 Subject: [PATCH 0870/1514] drm/asahi: g16: allow cross-VM compute overlap with recovery proof Allow G16 compute jobs to overlap healthy non-InitBM compute flights of another VM without draining the engine first (while still draining across cross-VM compute/render switches so long compute dispatches cannot starve another client's fragment shading into a firmware DM1 timeout): - Each compute unit already owns a private ComputeSlot, per-command ASID and binding generation, disjoint hardware UMA slot (1..24), full cross-VM scrub/work write on retarget, and queue-local barrier lookup. Relax needs_engine_drain() and can_queue_behind() for cross-VM compute-behind-compute while keeping cross-VM compute-behind-render, InitBM, failed-VM, and recovery drain gates intact. - Preserve per-queue FIFO in publish_checked()'s alt-class scan by skipping any candidate that has an earlier pending job on the same queue. - Mirror Wave 7's render FS timestamp recovery proof on compute: keep paired compute timestamps in prefix_compute() while gating hot-path ITS WC reads on compute_ts_mask, and read unit.its on the cold recovery_suspect path in poll.rs. Innocent cross-VM computes co-resident during another client's hang recovery now prove execution and retire Full instead of timing out as Aborted, while truly aborted computes (scrubbed zero ITS) still abort after the 20 ms grace period. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 62 +++++-- .../drivers/gpu/asahi-m4/test-publication.py | 163 ++++++++++++++++-- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 16 ++ 3 files changed, 209 insertions(+), 32 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index d3a462d98c0334..8fea292c4b5246 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -953,11 +953,12 @@ impl Firmware { let mut 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: only - // healthy same-VM non-InitBM commands queue behind active flights; when the - // head queue cannot queue behind (e.g. its class hit its flight cap), still - // allow another ready queue of the other class to run concurrently, unless - // the head job itself requires `flights` to drain to empty first (cross-VM - // switch, unprimed InitBM render, failed VM, or recovery/InitBM in flight). + // healthy non-InitBM commands (cross-VM compute or same-VM render) queue + // behind active flights; when the head queue cannot queue behind (e.g. its + // class hit its flight cap), still allow another ready queue to run + // concurrently while preserving per-queue FIFO, unless the head job itself + // requires `flights` to drain to empty first (cross-VM render switch, + // unprimed InitBM render, failed VM, or recovery/InitBM in flight). if !self.engine.flights.is_empty() && !self.can_queue_behind(&job) { if self.needs_engine_drain(&job) { self.engine.stats.hold[0] += 1; @@ -968,6 +969,14 @@ impl Firmware { if i == index || !self.can_queue_behind(cand) { continue; } + // Preserve per-queue FIFO: never jump a later job of a queue ahead + // of an earlier pending job of the same queue. + if self.engine.pending[..i] + .iter() + .any(|earlier| Arc::ptr_eq(&earlier.queue, &cand.queue)) + { + continue; + } let better = match alt { None => true, Some(best) => { @@ -1220,11 +1229,18 @@ impl Firmware { /// Whether `job` requires `self.engine.flights` to drain to empty before it can /// publish (so `alt`-class bypass must not keep refilling the engine ahead of it). fn needs_engine_drain(&self, job: &Arc) -> bool { + let cmd = command(job, job.progress.sent()); + let is_render = matches!(cmd, Some(Command::Render(_))); + let is_compute = matches!(cmd, Some(Command::Compute(_))); job.vm.status.get() != 0 || self.engine.flights.iter().any(|f| { - f.doomed || f.recovery_suspect || f.initbm || !Arc::ptr_eq(&f.job.vm, &job.vm) + f.doomed + || f.recovery_suspect + || f.initbm + || ((is_render || (is_compute && f.renders != 0)) + && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) - || (matches!(command(job, job.progress.sent()), Some(Command::Render(_))) + || (is_render && !job .resources .pb_slots() @@ -1301,29 +1317,36 @@ impl Firmware { /// Whether `job`'s next command may be published behind the flights in flight: /// - /// - Compute queues behind healthy same-VM non-InitBM compute and/or render flights (up to - /// [`params::compute_flights`] active computes), each in its own `ComputeSlot` - /// (`its`/`work`), unless `query_access` is set and a same-queue predecessor in its - /// compute or render barrier prefix has CPU-published timestamp outputs that have not - /// retired yet (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). + /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM + /// render flights (up to [`params::compute_flights`] active computes), each in its own + /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` + /// is set and a same-queue predecessor in its compute or render barrier prefix has + /// CPU-published timestamp outputs that have not retired yet + /// (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). Cross-VM compute never + /// overlaps an active render of another VM so long compute dispatches cannot starve + /// another client's fragment shading into a firmware DM1 timeout. /// - Render queues behind healthy same-VM non-InitBM render and/or compute flights (up to /// [`params::render_flights`] active renders), rotating `PassSlot` (`0..RENDER_SLOTS`) /// while sharing the active exposed PB/UMA allocator slot (`Pools::can_pipeline`). /// Hardware barriers on the CDM/TA/FS rings preserve exact same-engine and cross-engine /// ordering while barrier-free or independent-queue compute and render run concurrently. - /// - Cross-VM switches, InitBM priming renders, and every failure or recovery path still - /// drain the engine first. + /// - Cross-VM render switches, 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; + let sent = job.progress.sent(); + let is_render = matches!(command(job, sent), Some(Command::Render(_))); if job.vm.status.get() != 0 || e.flights.len() >= super::hw::sizes::FLIGHTS || e.flights.iter().any(|f| { - f.doomed || f.recovery_suspect || f.initbm || !Arc::ptr_eq(&f.job.vm, &job.vm) + f.doomed + || f.recovery_suspect + || f.initbm + || (is_render && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) { return false; } - let sent = job.progress.sent(); if job.check_command_dependencies(sent).is_err() { return false; } @@ -1353,8 +1376,13 @@ impl Firmware { }; waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) }); + let cross_vm_render = e + .flights + .iter() + .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); - !waits_for_timestamps + !cross_vm_render + && !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() && super::recovery::logic::next_ordinal(e.ordinal).is_some() 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 2c7d6f18c20fba..8e92f467928cca 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -99,7 +99,7 @@ def item(declaration): fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}} -struct Job { id:u32,vm:Arc,queue:Queue,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } +struct Job { id:u32,vm:Arc,queue:Arc,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(())} @@ -109,8 +109,8 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,renders:u32,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],renders:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,doomed:false,recovery_suspect:false,initbm:false}}} struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ @@ -242,7 +242,7 @@ def item(declaration): fl.renders=1; fl.initbm=!self.pools.can_pipeline(&job.vm); } - _=>{*pending_rings|=1<<(Channel::Compute as u8);} + _=>{*pending_rings|=1<<(Channel::Compute as u8);fl.computes=1;} } self.engine.flights.push(fl); } @@ -256,7 +256,7 @@ def item(declaration): fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, - queue:Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}, + queue:Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, 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}) } @@ -410,7 +410,7 @@ def item(declaration): let vm1=mk_vm(1); let mk_prio=|id:u32,render:bool,priority:u32|Arc::new(Job{ id,vm:vm1.clone(), - queue:Queue{turn:AtomicU64::new(0),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)]}, + queue:Arc::new(Queue{turn:AtomicU64::new(0),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)]}), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, @@ -453,14 +453,14 @@ def item(declaration): assert_eq!(f.publish_checked(&mut done),Ok(())); assert_eq!(f.attempted,[2,3]); } - #[test]fn alt_bypass_does_not_starve_cross_vm(){ + #[test]fn alt_bypass_does_not_starve_cross_vm_render_while_compute_overlaps(){ let vm1=mk_vm(1); let vm2=mk_vm(2); let vm1_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); - let vm2_head=job_on_vm(2,vm2,false,0,Ok(())); - let vm1_pending=job_on_vm(3,vm1,false,0,Ok(())); + let vm2_render=job_on_vm(2,vm2.clone(),true,0,Ok(())); + let vm1_pending=job_on_vm(3,vm1.clone(),false,0,Ok(())); vm1_pending.queue.turn.store(5,Ordering::Relaxed); - let mut f=firmware(vec![vm2_head,vm1_pending],vec![(Ok(()),true)]); + let mut f=firmware(vec![vm2_render,vm1_pending],vec![(Ok(()),true),(Ok(()),true)]); f.engine.flights.push(Flight::new(vm1_active)); f.allow_behind=true; let mut done=vec![]; @@ -470,7 +470,61 @@ def item(declaration): assert_eq!(f.engine.pending.len(),2); f.engine.flights.clear(); assert_eq!(f.publish_checked(&mut done),Ok(())); + // VM2 render publishes first; VM1 compute waits for VM2 render to drain (no cross-VM R<->C overlap). assert_eq!(f.attempted,[2]); + assert_eq!(f.engine.pending.len(),1); + f.engine.flights.clear(); + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[2,3]); + + // Cross-VM compute queues immediately behind another VM's active compute without drain, + // but drains behind another VM's active render so compute cannot starve cross-VM FS. + let vm1_c=job_on_vm(10,vm1.clone(),false,0,Ok(())); + let vm2_c=job_on_vm(11,vm2.clone(),false,0,Ok(())); + let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); + let mut fl=Flight::new(vm1_c); + fl.computes=1; + fc.engine.flights.push(fl); + fc.allow_behind=true; + assert_eq!(fc.publish_checked(&mut done),Ok(())); + assert_eq!(fc.attempted,[11]); + assert_eq!(fc.engine.stats.hold[0],0); + + let vm1_r=job_on_vm(12,vm1,true,0,Ok(())); + let vm2_c2=job_on_vm(13,vm2,false,0,Ok(())); + let mut fcr=firmware(vec![vm2_c2],vec![(Ok(()),true)]); + let mut flr=Flight::new(vm1_r); + flr.renders=1; + fcr.engine.flights.push(flr); + fcr.allow_behind=true; + assert_eq!(fcr.publish_checked(&mut done),Ok(())); + assert!(fcr.attempted.is_empty()); + assert_eq!(fcr.engine.stats.hold[0],1); + } + #[test]fn alt_bypass_preserves_per_queue_fifo_order(){ + let vm1=mk_vm(1); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q2=Arc::new(Queue{turn:AtomicU64::new(1),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ + id,vm:vm1.clone(),queue:q, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; + // q2 has ready compute job 3. alt-bypass must NOT jump q1's job 2 ahead of job 1, + // and must select q2's job 3 instead. + let q1_r1=mk_q(1,q1.clone(),true); + let q1_c2=mk_q(2,q1,false); + let q2_c3=mk_q(3,q2,false); + let mut f=firmware(vec![q1_r1.clone(),q1_c2,q2_c3],vec![(Ok(()),true)]); + f.engine.flights.push(Flight::new(q1_r1)); + f.allow_behind=true; + f.block_render_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[3]); + assert_eq!(f.engine.pending.len(),2); } #[test]fn alt_bypass_still_allows_same_vm_class_cap_overlap(){ let vm1=mk_vm(1); @@ -623,16 +677,23 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true}, }; assert!(p.can_queue_behind(&j2)); - assert!(!p.can_queue_behind(&j_other_vm)); + // Cross-VM compute queues behind another VM's healthy compute, but drains behind + // another VM's render. + assert!(p.can_queue_behind(&j_other_vm)); + assert!(!p.needs_engine_drain(&j_other_vm)); assert!(p.can_queue_behind(&j_render)); p.engine.flights[0].doomed=true; assert!(!p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); p.engine.flights[0].doomed=false; p.engine.flights[0].renders=1; p.engine.flights[0].computes=0; assert!(p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(p.needs_engine_drain(&j_other_vm)); p.engine.flights[0].initbm=true; assert!(!p.can_queue_behind(&j2)); + assert!(!p.can_queue_behind(&j_other_vm)); p.engine.flights[0].initbm=false; p.engine.flights[0].renders=0; p.engine.flights[0].computes=1; @@ -1609,7 +1670,7 @@ def item(declaration): mod recovery { pub(crate) mod logic { - pub(crate) use crate::recovery::logic::RetiredStamps; + pub(crate) use crate::recovery::logic::{stamp_reached, RetiredStamps}; } } mod poll { @@ -1636,7 +1697,8 @@ def item(declaration): self.passes.get(k).ok_or(ENOENT) } } - struct RecJob { resources: Resources } + struct RecVm { slot: u32 } + struct RecJob { vm: RecVm, resources: Resources } struct RecClaims { pass: [u32; 16] } struct RecFlight { job: RecJob, @@ -1655,11 +1717,12 @@ def item(declaration): gate_passed_ns: Option, unsettled_polls: u32, } - struct RecEngine { flights: Vec, ta_target: u32 } + struct RecEngine { flights: Vec, target: u32, ta_target: u32, fs_target: u32 } struct RecState { last_retired: recovery::logic::RetiredStamps } struct RecFirmware { engine: RecEngine, recovery: RecState } impl RecFirmware { __RECOVERY_PREPARE__ + __RECOVERY_PREPARE_SUSPECTS__ } #[test] fn recovery_prepare_matches_interior_cstamp_in_batched_compute_horizon() { @@ -1670,7 +1733,7 @@ def item(declaration): let mut fw = RecFirmware { engine: RecEngine { flights: vec![RecFlight { - job: RecJob { resources: Resources { passes: vec![] } }, + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, claims: RecClaims { pass: [0; 16] }, computes: 3, renders: 0, @@ -1686,7 +1749,9 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], + target: 0x300, ta_target: 0, + fs_target: 0, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; @@ -1711,6 +1776,7 @@ def item(declaration): engine: RecEngine { flights: vec![RecFlight { job: RecJob { + vm: RecVm { slot: 1 }, resources: Resources { passes: vec![mk_pass(0x1000), mk_pass(0x2000), mk_pass(0x3000)], }, @@ -1730,7 +1796,9 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], + target: 0, ta_target: 0x300, + fs_target: 0x300, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; @@ -1745,6 +1813,66 @@ def item(declaration): assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, [0x300, 0x100, 0]), Ok(())); assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, [0x300, 0x100, 0]), Err(ENOENT)); } + #[test] + fn cross_vm_recovery_prepare_isolates_blame_to_faulting_vm() { + let mut r_ta = [0u32; 16]; + let mut r_fs = [0u32; 16]; + r_ta[0] = 0x100; r_fs[0] = 0x100; + let mut cstamp = [0u32; 16]; + cstamp[0] = 0x500; + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![ + RecFlight { + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 0, + renders: 1, + target: 0, + ta_target: 0x100, + fs_target: 0x100, + cstamp: [0; 16], + r_ta_stamp: r_ta, + r_fs_stamp: r_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + target: 0x500, + ta_target: 0, + fs_target: 0, + cstamp, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + ], + target: 0x500, + ta_target: 0x100, + fs_target: 0x100, + }, + recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, + }; + // VM 1 (ASID 1) faults on FS 0x100 while VM 2 (ASID 2) has co-resident compute 0x500. + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x100, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare_suspects([0x100, 0, 0], 0x71, Some(1)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + // VM 2's co-resident compute is suspect-only (checked via hardware ITS ticks), NEVER doomed! + assert!(!fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) @@ -1786,6 +1914,11 @@ def item(declaration): .replace('super::recovery::', 'recovery::') .replace('super::poll::', 'poll::'), ) +harness = harness.replace( + '__RECOVERY_PREPARE_SUSPECTS__', + item('pub(crate) fn recovery_prepare_suspects(') + .replace('super::recovery::', 'recovery::'), +) for token, declaration in { '__PUBLICATION_ERROR__': 'enum PublicationError {', '__PICK__': 'fn pick(&self)', 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 40cb941328485d..6fd443776de7dc 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 @@ -358,6 +358,22 @@ def function(text, name): c.engine.flights[0].job.resources.compute[0].its.set(8,299); assert_eq!(c.retired(),Ok(Retirement::Pending)); } +#[test]fn recovery_suspect_compact_compute_retires_full_with_hw_ticks(){ + // An innocent cross-VM compact compute (compute_ts_mask == 0) marked recovery_suspect + // during another VM's hang still proves stage execution via cold-path ITS ticks and + // retires Full without false Aborted or VM blame. + CLOCK.with(|c|c.set(100_000_000)); + let mut f=firmware(false,29); + f.engine.flights[0].compute_ts_mask=0; + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=90_000_000; + f.engine.flights[0].job.resources.compute[0].its.set(0,500); + f.engine.flights[0].job.resources.compute[0].its.set(8,525); + assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].job.resources.compute[0].its.reads.get(),2); + assert_eq!(f.engine.retired_ticks,[0;4]); +} mod queue_proof { use super::{Channel, Object, Result, EINVAL}; From 6d688005f92f62809ee1cb816ee77857113c3297 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:44:33 -0500 Subject: [PATCH 0871/1514] drm/asahi: g16: assign per-slot render UMA descriptors and multi-active Pools Give each G16 render PB/UMA allocator slot its own hardware UMA slot ID and extend Pools slot selection so multiple VMs can hold simultaneously warm PB epochs without aliasing a single firmware UMA slot: - Pass engine::RENDER_UMA_SLOT + k (33..38, compile-time asserted within M4 firmware's 33..64 render UMA window and disjoint from compute UMA slots 1..24) in Allocator::new() and validate RENDER_UMA_SLOT + self.id in Allocator::prepare_in_flight(). - Add Pools::slot_inflight() and guard Pools::slot_displaced() with self.inflight[k] == 0 so an in-flight slot can never be treated as displaced. - Update Pools::pick_slot_within() so behind=true returns any healthy warm reusable slot bound to vm (preferring self.active, then 0..limit) while still returning None for cold VMs requiring InitBM, ensuring the engine drains before any InitBM or slot displacement. Check all slots in Pools::exhausted(). - Add host tests in test-resources.py covering per-slot render UMA IDs, tamper rejection, multi-active warm cross-VM slot reuse, cold InitBM gating, and post-recovery invalidation across all slots. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/hw.rs | 10 ++- drivers/gpu/drm/asahi/g16/pools.rs | 54 +++++++------ .../drivers/gpu/asahi-m4/test-resources.py | 76 ++++++++++++++++++- 3 files changed, 112 insertions(+), 28 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 0642bd6b9f3209..84b67762863794 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -741,12 +741,14 @@ pub(crate) mod sizes { /// /// Sized inside both the host client-VA window (`0x7020000000..0x7040000000`) and firmware /// queue/recovery capacities: `47` in-flight passes consume at most `47 * 4 = 188` entries of - /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), share - /// hardware UMA slot `RENDER_UMA_SLOT` (33) via the active PB/UMA descriptor, post at most - /// `FLIGHTS = 32` `SubmitRecord`s (vs `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay - /// far below the firmware recovery `snapshot_entries = 448` limit. + /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), use + /// per-allocator hardware UMA slots `RENDER_UMA_SLOT + slot` (`33..38`, strictly inside the + /// firmware render slot range `33..64`), post at most `FLIGHTS = 32` `SubmitRecord`s (vs + /// `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay far below the firmware recovery + /// `snapshot_entries = 448` limit. pub(crate) const RENDER_SLOTS: usize = 48; const _: () = assert!(RENDER_SLOTS >= BASE_RENDER_SLOTS && RENDER_SLOTS <= 64); + const _: () = assert!(super::engine::RENDER_UMA_SLOT + (PB_SLOTS as u32) <= 65); const _: () = assert!((RENDER_SLOTS - 1) * MAX_RENDER_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!(super::client::AUX + 0x20000 <= super::client::SCENE_LIST); const _: () = assert!(super::client::SCENE_LIST + 0x4000 <= super::client::TPC); diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 797bf9f1e63f26..c570665604e671 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -160,7 +160,7 @@ impl Allocator { 0, &buffer::uma_manager_image( descriptor.va, - engine::RENDER_UMA_SLOT, + engine::RENDER_UMA_SLOT + k as u32, gva(&state)?, gva(&list)?, submitted.va, @@ -207,7 +207,7 @@ impl Allocator { } // Descriptor pointer/counter and slot must still identify this exact retained unit. if read64(&self.descriptor, 0)? != self.descriptor.va - || self.descriptor.r32(8)? != engine::RENDER_UMA_SLOT + || self.descriptor.r32(8)? != engine::RENDER_UMA_SLOT + self.id || read64(&self.descriptor, 0x4c)? != self.submitted.va { return Err(EINVAL); @@ -381,10 +381,16 @@ impl Pools { .saturating_add(quarantined) .min(sizes::PB_SLOTS) } - /// Whether slot `k` is healthy, not active, and either fresh or displaced by a clean + /// Number of in-flight render prefixes currently active on allocator slot `k`. + #[allow(dead_code)] + pub(crate) fn slot_inflight(&self, k: usize) -> u32 { + self.inflight.get(k).copied().unwrap_or(0) + } + /// Whether slot `k` is healthy, idle, not active, and either fresh or displaced by a clean /// retirement of some other slot. fn slot_displaced(&self, k: usize) -> bool { !self.quarantined[k] + && self.inflight[k] == 0 && self.active != Some(k) && (self.owners[k].is_none() || self.last_clean_retired.is_some_and(|r| r != k)) } @@ -403,11 +409,12 @@ impl Pools { } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. /// - /// When `behind` is true (pipelining behind in-flight same-VM renders), the active slot must - /// be within `0..limit`, healthy, and reusable for `vm`. When `behind` is false (engine - /// drained), a same-VM render stays on its reusable active slot if within `0..limit`; - /// otherwise it switches to an already-used displaced slot first (preserving the 2-slot - /// working set) or claims the lowest fresh slot. + /// When `behind` is true (pipelining behind active flights), only a healthy warm reusable + /// slot already bound to `vm` (preferring `self.active`, then any other slot in `0..limit`) + /// is eligible; cold VMs requiring `InitBM` return `None` so the engine drains first. + /// When `behind` is false (engine drained), a warm reusable slot for `vm` is preferred; + /// otherwise an already-used displaced slot is chosen first (preserving the 2-slot working + /// set) or the lowest fresh slot is claimed. pub(crate) fn pick_slot_within( &self, vm: &Arc, @@ -415,15 +422,17 @@ impl Pools { limit: usize, ) -> Option { let n = limit.min(sizes::PB_SLOTS); - if behind { - let a = self.active?; - return (a < n && !self.quarantined[a] && self.reusable(a, vm).is_some()).then_some(a); - } if let Some(a) = self.active { - if a < n && !self.quarantined[a] && self.reusable(a, vm).is_some() { + if a < n && self.reusable(a, vm).is_some() { return Some(a); } } + if let Some(k) = (0..n).find(|&k| self.reusable(k, vm).is_some()) { + return Some(k); + } + if behind { + return None; + } // Prefer reusing a displaced slot over claiming a fresh recovery slot. (0..n) .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) @@ -434,12 +443,12 @@ impl Pools { pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { self.pick_slot_within(vm, behind, sizes::PB_SLOTS) } - /// Whether `vm` can pipeline another render behind active same-VM renders within `0..limit`. + /// Whether `vm` has a warm reusable PB slot within `0..limit` and can pipeline without InitBM. #[allow(dead_code)] pub(crate) fn can_pipeline_within(&self, vm: &Arc, limit: usize) -> bool { self.pick_slot_within(vm, true, limit).is_some() } - /// Whether `vm` can pipeline another render behind the currently active same-VM renders. + /// Whether `vm` has a warm reusable PB slot and can pipeline without InitBM. #[allow(dead_code)] pub(crate) fn can_pipeline(&self, vm: &Arc) -> bool { self.can_pipeline_within(vm, sizes::PB_SLOTS) @@ -450,15 +459,14 @@ impl Pools { if self.inflight.iter().any(|&c| c != 0) { return false; } - if let Some(a) = self.active { - let can_reuse_active = !self.quarantined[a] - && self.keep[a] - && self.owners[a] + if (0..sizes::PB_SLOTS).any(|k| { + !self.quarantined[k] + && self.keep[k] + && self.owners[k] .as_ref() - .is_some_and(|o| o.exposed.load(Ordering::Acquire)); - if can_reuse_active { - return false; - } + .is_some_and(|o| o.exposed.load(Ordering::Acquire)) + }) { + return false; } !(0..sizes::PB_SLOTS).any(|k| self.slot_displaced(k)) } 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 2d1655087e428f..9160894ea0eaa5 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -699,6 +699,74 @@ def module(text, name): assert_eq!(p.pick_slot(&vm1,false),Some(0)); } + #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ + let mut o=Objects::new(); + let pools=PoolSet::new(&mut o).unwrap(); + let mut uma_slots=Vec::new(); + for k in 0..g16::hw::sizes::PB_SLOTS { + let alloc=g16::pools::Allocator::new(&mut o,k as u64,pools.heap()).unwrap(); + let refs=alloc.prepare_in_flight(1,false).unwrap(); + assert_eq!(refs.parameter_id,k as u32); + let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let slot_id=desc.r32(8).unwrap(); + let expected=g16::hw::engine::RENDER_UMA_SLOT+k as u32; + assert_eq!(slot_id,expected); + assert!(slot_id>=33 && slot_id<=64); + assert!(!uma_slots.contains(&slot_id)); + uma_slots.push(slot_id); + // Tampering with the descriptor UMA slot ID is rejected before publication. + desc.write(8,&(expected+1).to_le_bytes()).unwrap(); + assert_eq!(alloc.prepare_in_flight(1,false).err(),Some(EINVAL)); + } + } + + #[test]fn multi_active_pools_allow_warm_cross_vm_reuse_and_gate_cold_initbm(){ + let vm1=vm(1);let vm2=vm(2);let vm3=vm(3); + let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); + let mk_epoch=|owner:&sync::Arc,slot:usize|{ + let e=g16::pools::PbEpoch::new(&factory,owner,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); + e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); + e + }; + let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + // Prime VM1 on slot 0 and VM2 on slot 1 (drained InitBM). + let e1=mk_epoch(&vm1,0); + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + let b1=p.bind(0,false);p.publish_flight(0);p.retire_flight(0,&e1,b1,true).unwrap(); + let e2=mk_epoch(&vm2,1); + assert_eq!(p.pick_slot_within(&vm2,false,2),Some(1)); + let b2=p.bind(1,false);p.publish_flight(1);p.retire_flight(1,&e2,b2,true).unwrap(); + // VM1 starts a render on warm slot 0 (no InitBM). + assert_eq!(p.pick_slot_within(&vm1,false,2),Some(0)); + assert!(p.reusable(0,&vm1).is_some()); + let b1=p.bind(0,true);p.publish_flight(0); + assert_eq!(p.slot_inflight(0),1); + assert_eq!(p.slot_inflight(1),0); + // While VM1 is live on slot 0 (behind=true): + // - Warm VM2 pipelines onto its own slot 1 without InitBM or drain. + // - Cold VM3 has no warm slot and returns None so the engine drains before InitBM. + assert!(p.can_pipeline_within(&vm2,2)); + assert_eq!(p.pick_slot_within(&vm2,true,2),Some(1)); + assert!(!p.can_pipeline_within(&vm3,2)); + assert_eq!(p.pick_slot_within(&vm3,true,2),None); + // VM2 publishes on slot 1 concurrently with VM1 on slot 0. + let b2=p.bind(1,true);p.publish_flight(1); + assert_eq!(p.slot_inflight(0),1); + assert_eq!(p.slot_inflight(1),1); + // Neither in-flight slot is displaced while live. + assert!(!p.exhausted()); + // Both retire cleanly in order. + p.retire_flight(0,&e1,b1,true).unwrap(); + assert_eq!(p.slot_inflight(0),0); + assert_eq!(p.slot_inflight(1),1); + p.retire_flight(1,&e2,b2,true).unwrap(); + assert_eq!(p.slot_inflight(1),0); + // Recovery invalidation clears warm reuse for BOTH slots so both VMs drain for InitBM. + p.invalidate(); + assert!(!p.can_pipeline_within(&vm1,2)); + assert!(!p.can_pipeline_within(&vm2,2)); + } + #[test]fn render_hang_after_cross_vm_use_recovers_via_lazy_pb_slot_and_displaces_survivor(){ let vm1=vm(1);let vm2=vm(2);let vm3=vm(3);let vm4=vm(4); let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); @@ -782,7 +850,13 @@ def module(text, name): // 5th hang quarantines slot 4: only slot 5 survives (reuse-only for VM2; other VMs exhausted). p.publish_flight(4); p.quarantine_flight(4,None); - // Slot 5 was the last_clean_retired slot (undisplaced) and slot 4 is quarantined -> exhausted. + assert!(!p.exhausted()); + assert!(!p.exhausted_for(&vm2)); + assert_eq!(p.pick_slot(&vm2,false),Some(5)); + assert!(p.exhausted_for(&vm1)); + assert!(p.exhausted_for(&vm3)); + // Recovery invalidation clears slot 5's warm epoch -> global pool exhaustion. + p.invalidate(); assert!(p.exhausted()); // Quarantine 5 fresh slots leaving slot 5 fresh: VM2 claims and reuses slot 5 while From 23d0ffd82d7d734df8e8804cc88519e78ec05ee9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 11:08:42 -0500 Subject: [PATCH 0872/1514] drm/asahi/g16: eliminate multi-kilobyte kernel stack frames in probe and hot paths Kernel VMAP_STACK (32 KiB with 16 KiB pages) overflowed in g16::Firmware::start_backend (22,688 B frame) during probe. Keep large G16 boot, backend, scrub, and command-validation structures off the kernel stack: - Allocate ComputeOwners, RenderOwners, Pools, ScrubQueue, GpuAdt, Admitted, Booted, Stats, Prof, Scratch, Firmware, and SpanProof in- place on the heap (KBox::init / KBox::try_init / KBox::zeroed / write_init). - Retain failed Booted/Firmware sessions directly as KBox variants instead of unpacking Firmware back onto the stack with KBox::into_inner. - Bound stack-resident ScrubBatch to 8 displaced slots per pass and drain ScrubQueue entries one-by-one in join_workers. - Reuse heap-resident ValidateScratch inside SpanProof for Prepared::validate and SpanBatch::flush_with_proof. - Mark probe/boot/engine phase boundaries #[inline(never)] so unrelated large frames do not merge. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/fwid.rs | 1 + drivers/gpu/drm/asahi/g16/adt.rs | 26 +- drivers/gpu/drm/asahi/g16/boot.rs | 93 ++++--- drivers/gpu/drm/asahi/g16/command.rs | 226 +++++++++++++----- drivers/gpu/drm/asahi/g16/engine.rs | 36 +-- drivers/gpu/drm/asahi/g16/graph.rs | 2 + drivers/gpu/drm/asahi/g16/initdata.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 146 +++++------ drivers/gpu/drm/asahi/g16/poll.rs | 1 + drivers/gpu/drm/asahi/g16/pools.rs | 26 ++ drivers/gpu/drm/asahi/g16/queue.rs | 2 +- drivers/gpu/drm/asahi/g16/recovery.rs | 1 + drivers/gpu/drm/asahi/g16/sleep.rs | 16 +- drivers/gpu/drm/asahi/g16/slots.rs | 46 +++- .../gpu/asahi-m4/test-command-stream.py | 1 + .../drivers/gpu/asahi-m4/test-resources.py | 3 +- 16 files changed, 427 insertions(+), 200 deletions(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index 62dc0452e78183..2f9d086c3efe0a 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -287,6 +287,7 @@ impl fmt::Display for Identity { /// Identifies the firmware build loaded at `text` (DATA `data_size` bytes) among `builds`, /// before any firmware-visible write. #[cfg_attr(not(CONFIG_DRM_ASAHI_G16), allow(dead_code))] +#[inline(never)] pub(crate) fn identify( dev: &device::Device, text: Range, diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index d885732c02194f..3c639f054c4ec2 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -139,7 +139,8 @@ pub(crate) fn layout(dev: &device::Device) -> Option<&'static hw::FwLayout> { } /// Validates the FDT contract and returns the reserved physical regions, read-only. -pub(crate) fn read(dev: &device::Device) -> Result { +#[inline(never)] +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"))?; @@ -223,14 +224,17 @@ pub(crate) fn read(dev: &device::Device) -> Result { performance.count ); let [ttbs, tables, handoff, shared_l2, text, data] = regions; - Ok(GpuAdt { - ttbs, - tables, - handoff, - shared_l2, - text, - data, - performance, - layout, - }) + Ok(KBox::init( + init!(GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + performance, + layout, + }), + GFP_KERNEL, + )?) } diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index fdef6c7c908dad..353c576b247d18 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -462,7 +462,7 @@ impl Rtkit { /// The result of admission: everything probe-time checks established, nothing written. pub(crate) struct Admitted { pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, } /// The running firmware session: RTKit, MMIO and the adopted UAT. (The @@ -472,7 +472,7 @@ pub(crate) struct Session { pub(crate) shared: Arc, pub(crate) rtkit: Rtkit, pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, 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. @@ -602,7 +602,7 @@ pub(crate) fn admit( _dev: &AsahiDrmDevice, cfg: &'static Config, res: shared_regs::G16Resources, -) -> Result { +) -> Result> { let dev = pdev.as_ref(); // 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 @@ -677,7 +677,7 @@ pub(crate) fn admit( return Err(Error::from_errno(-(bindings::EHOSTDOWN as i32))); } dev_info!(dev, "T8132 G16G admitted, ASC={:#x}\n", regs.asc_control()?); - Ok(Admitted { regs, adt }) + Ok(KBox::init(init!(Admitted { regs, adt }), GFP_KERNEL)?) } /// Posts one device control with only the opcode and waits for it. @@ -758,6 +758,7 @@ fn publish_loader_table(session: &Session, init: &InitData, offset: u64) -> Resu } /// Wake the sole firmware instance, publish its loader table, then qualify NOP and policy. +#[inline(never)] fn run( session: &mut Session, events: &mut Events, @@ -900,15 +901,54 @@ fn run( Ok(()) } +/// Retains a failed firmware start out-of-line so [`start`] never reserves an [`Orphan`] slot on +/// its normal stack frame. +#[cold] +#[inline(never)] +fn retain_start_failure( + shared: &Shared, + session: Session, + objects: Objects, + built: Option<(InitData, Channels, u32)>, + events: Events, +) { + let (init, channels) = match built { + Some((init, channels, _)) => (Some(init), Some(channels)), + None => (None, None), + }; + match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => { + let orphan = slot + .write_init(init!(Orphan { + session, + _objects: objects, + channels, + _init: init, + events, + })) + .unwrap_or_else(|e| match e {}); + shared.retain_failed(super::Retained::Orphan(orphan)); + } + Err(_) => { + dev_err!( + shared.dev.as_ref(), + "G16: cannot keep the failed session; leaked\n" + ); + // Without memory for the box, leak the firmware-reachable parts. + core::mem::forget((session, objects, channels, init, events)); + } + } +} + /// Brings the firmware to READY. #[inline(never)] pub(crate) fn start( - admitted: Admitted, + admitted: KBox, dev: &AsahiDrmDevice, cfg: &'static Config, shared: &Arc, -) -> Result { - let Admitted { regs, adt } = admitted; +) -> Result> { + let Admitted { regs, adt } = KBox::into_inner(admitted); let d: ARef = shared.dev.clone(); // Cold ownership must hold before the PMP vote as well as immediately before RUN. if regs.asc_control()? & regs::ASC_RUN != 0 { @@ -1005,6 +1045,13 @@ pub(crate) fn start( return Err(e); } }; + let booted_slot = match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => slot, + Err(e) => { + core::mem::forget(objects); + return Err(e.into()); + } + }; let mut session = Session { dev: d.clone(), shared: shared.clone(), @@ -1074,27 +1121,19 @@ pub(crate) fn start( "G16 start failed: {:?}; session retained until reboot\n", e ); - let (init, channels) = match built { - Some((init, channels, _)) => (Some(init), Some(channels)), - None => (None, None), - }; - shared.orphan(Orphan { - session, - _objects: objects, - channels, - _init: init, - events, - }); + retain_start_failure(shared, session, objects, built, events); return Err(e); } let (init, channels, max_frequency_khz) = built.ok_or(EINVAL)?; - Ok(Booted { - session, - init, - objects, - channels, - events, - id, - max_frequency_khz, - }) + Ok(booted_slot + .write_init(init!(Booted { + session, + init, + objects, + channels, + events, + id, + max_frequency_khz, + })) + .unwrap_or_else(|e| match e {})) } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 10311e618483d2..3d6e66ff8bdfd0 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -637,18 +637,16 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { /// Maximum page-aligned GPUVM spans retained in one logical queue's validation cache. const MAX_PROOF_RANGES: usize = 128; -/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions. -/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never -/// reused across unmaps or remaps. -pub(crate) struct SpanProof { +/// Bounded cache of validated page-aligned GPUVM spans and permissions. +struct ProofCache { epoch: Option, ranges: [(u64, u64, u8); MAX_PROOF_RANGES], count: usize, overflow: bool, } -impl SpanProof { - pub(crate) const fn new() -> Self { +impl ProofCache { + const fn new() -> Self { Self { epoch: None, ranges: [(0, 0, 0); MAX_PROOF_RANGES], @@ -668,7 +666,7 @@ impl SpanProof { }) } - pub(crate) fn invalidate(&mut self) { + fn invalidate(&mut self) { self.epoch = None; self.count = 0; self.overflow = false; @@ -680,13 +678,7 @@ impl SpanProof { .any(|&range| Self::contains(range, req)) } - pub(crate) fn covers_aligned( - &self, - epoch: Option, - first: u64, - size: u64, - access: u8, - ) -> bool { + fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { self.epoch.is_some() && self.epoch == epoch && self.covers_entry((first, size, access)) } @@ -726,7 +718,7 @@ impl SpanProof { self.count += 1; } - pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { if epoch.is_none() { self.invalidate(); return; @@ -761,6 +753,63 @@ impl SpanProof { } } +/// Heap-resident validation scratch paired with [`ProofCache`] so `Prepared::validate` never +/// stages kilobytes of span/command arrays on the kernel stack. +struct ValidateScratch { + batch: SpanBatch, + missing: [(u64, u64, u8); 48], + vdm_vas: [u64; MAX_COMMANDS as usize], + cdm_ranges: [(u64, u64); MAX_COMMANDS as usize], +} + +impl ValidateScratch { + const fn new() -> Self { + Self { + batch: SpanBatch::new(), + missing: [(0, 0, 0); 48], + vdm_vas: [0; MAX_COMMANDS as usize], + cdm_ranges: [(0, 0); MAX_COMMANDS as usize], + } + } +} + +/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions, +/// together with reusable scratch buffers for `Prepared::validate`. +/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never +/// reused across unmaps or remaps. +pub(crate) struct SpanProof { + cache: ProofCache, + scratch: ValidateScratch, +} + +impl SpanProof { + #[allow(dead_code)] + pub(crate) const fn new() -> Self { + Self { + cache: ProofCache::new(), + scratch: ValidateScratch::new(), + } + } + + pub(crate) fn invalidate(&mut self) { + self.cache.invalidate(); + } + + pub(crate) fn covers_aligned( + &self, + epoch: Option, + first: u64, + size: u64, + access: u8, + ) -> bool { + self.cache.covers_aligned(epoch, first, size, access) + } + + pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + self.cache.record_one(epoch, first, size, access); + } +} + /// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while /// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. struct SpanBatch { @@ -820,18 +869,26 @@ impl SpanBatch { Self::report_failure(vm, &self.ranges[..n]) } - fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + fn clear(&mut self) { + self.len = 0; + } + + fn flush_with_proof_parts( + &mut self, + vm: &mmu::Vm, + cache: &mut ProofCache, + missing: &mut [(u64, u64, u8); 48], + ) -> Result { let n = self.len; if n == 0 { return Ok(()); } self.len = 0; let epoch = vm.mapping_validation_epoch(); - if proof.epoch.is_some() && proof.epoch == epoch { - let mut missing = [(0u64, 0u64, 0u8); 48]; + if cache.epoch.is_some() && cache.epoch == epoch { let mut missing_len = 0usize; for &req in &self.ranges[..n] { - if !proof.covers_entry(req) { + if !cache.covers_entry(req) { missing[missing_len] = req; missing_len += 1; } @@ -840,30 +897,35 @@ impl SpanBatch { return Ok(()); } let (mut covered, mut walked) = vm.covers_ranges_batch(&missing[..missing_len]); - if covered && walked != proof.epoch { + if covered && walked != cache.epoch { (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); } if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); return Self::report_failure(vm, &self.ranges[..n]); } let (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); Self::report_failure(vm, &self.ranges[..n]) } - fn flush_locked_with_proof( + #[allow(dead_code)] + fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + self.flush_with_proof_parts(vm, &mut proof.cache, &mut proof.scratch.missing) + } + + fn flush_locked_with_cache( &mut self, guard: &mut mmu::VmReadGuard<'_>, epoch: Option, - proof: &mut SpanProof, + cache: &mut ProofCache, ) -> Result { let n = self.len; if n == 0 { @@ -872,14 +934,14 @@ impl SpanBatch { self.len = 0; let mut had_miss = false; for &(first, size, access) in &self.ranges[..n] { - if proof.covers_aligned(epoch, first, size, access) { + if cache.covers_aligned(epoch, first, size, access) { continue; } had_miss = true; let read = access & 1 != 0; let write = access & 2 != 0; if !guard.covers_range(first, size, read, write) { - proof.invalidate(); + cache.invalidate(); return if guard.covers_range(first, size, false, false) { Err(EACCES) } else { @@ -888,10 +950,20 @@ impl SpanBatch { } } if had_miss { - proof.record_slice(epoch, &self.ranges[..n]); + cache.record_slice(epoch, &self.ranges[..n]); } Ok(()) } + + #[allow(dead_code)] + fn flush_locked_with_proof( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: &mut SpanProof, + ) -> Result { + self.flush_locked_with_cache(guard, epoch, &mut proof.cache) + } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. @@ -1434,6 +1506,34 @@ impl ParsedStream { } } +impl SpanProof { + /// Allocates a [`SpanProof`] directly on the heap without staging its range or scratch arrays + /// on the kernel stack. + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + cache <- init!(ProofCache { + epoch: None, + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + count: 0, + overflow: false, + }), + scratch <- init!(ValidateScratch { + batch <- init!(SpanBatch { + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + len: 0, + }), + missing <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + vdm_vas <- ::pin_init::init_array_from_fn(|_| 0), + cdm_ranges <- ::pin_init::init_array_from_fn(|_| (0, 0)), + }), + }), + GFP_KERNEL, + )?) + } +} + impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. @@ -1450,35 +1550,40 @@ impl Prepared { if commands.is_empty() { return Err(EINVAL); } - let mut batch = SpanBatch::new(); - let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; let mut vdm_count = 0usize; - let mut cdm_ranges = [(0u64, 0u64); MAX_COMMANDS as usize]; let mut cdm_count = 0usize; - for command in commands.iter() { - match command { - Command::Render(render) => { - check_render( - &mut batch, - context, - &render.cmd, - &render.vertex_attachments, - &render.fragment_attachments, - )?; - if vdm_count >= vdm_vas.len() { - return Err(EINVAL); + { + let scratch = &mut proof.scratch; + scratch.batch.clear(); + for command in commands.iter() { + match command { + Command::Render(render) => { + check_render( + &mut scratch.batch, + context, + &render.cmd, + &render.vertex_attachments, + &render.fragment_attachments, + )?; + if vdm_count >= scratch.vdm_vas.len() { + return Err(EINVAL); + } + scratch.vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; + vdm_count += 1; } - vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; - vdm_count += 1; - } - Command::Compute(compute) => { - let range = - check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; - if cdm_count >= cdm_ranges.len() { - return Err(EINVAL); + Command::Compute(compute) => { + let range = check_compute( + &mut scratch.batch, + context, + &compute.cmd, + &compute.attachments, + )?; + if cdm_count >= scratch.cdm_ranges.len() { + return Err(EINVAL); + } + scratch.cdm_ranges[cdm_count] = range; + cdm_count += 1; } - cdm_ranges[cdm_count] = range; - cdm_count += 1; } } } @@ -1495,12 +1600,14 @@ impl Prepared { let mut guard = Some(context.vm.read_lock().map_err(|_| EFAULT)?); let mut epoch = guard.as_ref().and_then(|g| g.epoch()); if let Some(g) = guard.as_mut() { - batch.flush_locked_with_proof(g, epoch, proof)?; + let SpanProof { cache, scratch } = proof; + scratch.batch.flush_locked_with_cache(g, epoch, cache)?; if need_vdm { - gate::vdm_batch_locked(g, &vdm_vas[..vdm_count])?; + gate::vdm_batch_locked(g, &scratch.vdm_vas[..vdm_count])?; } } - for &(base, end) in &cdm_ranges[..cdm_count] { + for i in 0..cdm_count { + let (base, end) = proof.scratch.cdm_ranges[i]; gate::cdm_locked( context.vm, &mut guard, @@ -1512,7 +1619,10 @@ impl Prepared { )?; } } else { - batch.flush_with_proof(context.vm, proof)?; + let SpanProof { cache, scratch } = proof; + scratch + .batch + .flush_with_proof_parts(context.vm, cache, &mut scratch.missing)?; } Ok(Submission { counts, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 6d7286fdd66104..53e5d968c64675 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -407,7 +407,7 @@ enum PublicationError { } /// Engine statistics, printed by `aurora-g16/stats`. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Stats { pub(crate) pub_ns: u64, pub(crate) idle_from_ns: u64, @@ -465,7 +465,7 @@ pub(crate) struct Stats { /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 /// (`Debug1`); printed as the `prof:` line of `aurora-g16/stats`. A measurement aid: nothing is /// timed while the flag is off. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Prof { /// Published prefixes timed. pub(crate) prefixes: u64, @@ -520,17 +520,21 @@ struct Scratch { } impl Scratch { - fn new() -> Result { + #[inline(never)] + fn new_boxed() -> Result> { let z = |n| KVec::from_elem(0u8, n, GFP_KERNEL); - Ok(Self { - cw: z(work::compute::WORK_SIZE)?, - cq: z(work::compute::SEQ_SIZE)?, - ta: z(work::ta::WORK_SIZE)?, - tas: z(work::ta::SEQ_SIZE)?, - fs: z(work::fs::WORK_SIZE)?, - fss: z(work::fs::SEQ_SIZE)?, - scene: z(work::scene::ACTIVE_SIZE)?, - }) + KBox::try_init( + try_init!(Self { + cw: z(work::compute::WORK_SIZE)?, + cq: z(work::compute::SEQ_SIZE)?, + ta: z(work::ta::WORK_SIZE)?, + tas: z(work::ta::SEQ_SIZE)?, + fs: z(work::fs::WORK_SIZE)?, + fss: z(work::fs::SEQ_SIZE)?, + scene: z(work::scene::ACTIVE_SIZE)?, + }), + GFP_KERNEL, + ) } } @@ -601,6 +605,7 @@ pub(crate) struct Engine { } impl Engine { + #[inline(never)] pub(crate) fn new() -> Result { // Wrapped native stamps are safe only while pending references fit within the // signed half-window: at most FLIGHTS commands are published at once, far inside it. @@ -633,12 +638,12 @@ impl Engine { short_repoll: false, progress_flight: [0; 3], progress: [None; 4], - stats: KBox::new(Stats::default(), GFP_KERNEL)?, - prof: KBox::new(Prof::default(), GFP_KERNEL)?, + stats: KBox::zeroed(GFP_KERNEL)?, + prof: KBox::zeroed(GFP_KERNEL)?, debugfs: 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)?), + scratch: Some(Scratch::new_boxed()?), }) } @@ -1844,6 +1849,7 @@ impl Firmware { /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; /// The error records whether firmware may see a counter/producer update, independently /// of errno; unpublished EIO is still an ordinary job failure. + #[inline(never)] fn publish_prefix( &mut self, job: &Arc, diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 4514454acbe15b..f23f4936ab3aa1 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -278,6 +278,7 @@ pub(crate) struct Graphs { pub(crate) render: RenderGraph, } impl Graphs { + #[inline(never)] pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. @@ -295,6 +296,7 @@ impl Graphs { } } impl Firmware { + #[inline(never)] pub(crate) fn init_graphs(&mut self) -> Result { for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { if self.channels.read(ch)? != 0 || self.channels.write_cell(ch)? != 0 { diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 01861b790a62d1..e4898529be5c7d 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -93,6 +93,7 @@ fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { /// Builds the complete unpublished M4 graph. The return shape is shared with /// the other backend, while all object layouts and policy are M4-specific. +#[inline(never)] pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 670a85634528af..30c26d3bc62a51 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -206,6 +206,33 @@ const WAIT_HINT_GAP_NS: u64 = 4_000_000; const WAIT_HINT_STREAK_ON: u32 = 8; const WAIT_HINT_LINGER_NS: u64 = 8_000_000; +/// A firmware session retained until reboot after a failed boot or backend start. +pub(crate) enum Retained { + Orphan(KBox), + Booted(KBox), + Firmware(KBox), +} + +impl Retained { + fn drain(&mut self) -> Result { + match self { + Self::Orphan(orphan) => orphan.drain(), + Self::Booted(booted) => { + let booted = &mut **booted; + booted + .channels + .drain_rings(&booted.session.dev, &mut booted.events) + } + Self::Firmware(firmware) => { + let firmware = &mut **firmware; + firmware + .channels + .drain_rings(&firmware.session.dev, &mut firmware.events) + } + } + } +} + /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] pub(crate) struct Shared { @@ -282,7 +309,7 @@ pub(crate) struct Shared { /// Dedicated unbound workqueue for cpufreq `FREQ_QOS_MIN` updates outside `Shared::state`. pub(crate) feed_wq: OwnedQueue, #[pin] - pub(crate) orphan: Mutex>>, + pub(crate) orphan: Mutex>, #[pin] pub(crate) poll: DelayedWork, #[pin] @@ -290,7 +317,7 @@ pub(crate) struct Shared { #[pin] pub(crate) fast_poll_unbound: Work, #[pin] - pub(crate) scrub_queue: SpinLock, + pub(crate) scrub_queue: SpinLock>, #[pin] pub(crate) scrub_work: Work, #[pin] @@ -499,36 +526,26 @@ impl Shared { /// Keeps a firmware session that did not complete until reboot; its receive rings stay /// drained by the poll work. - pub(crate) fn orphan(&self, orphan: boot::Orphan) { + #[cold] + #[inline(never)] + pub(crate) fn retain_failed(&self, retained: Retained) { let mut slot = self.orphan.lock(); if slot.is_some() { // Never replace and drop an already firmware-reachable session. - core::mem::forget(orphan); + core::mem::forget(retained); dev_err!( self.dev.as_ref(), "G16: additional failed session retained without drain\n" ); return; } - match KBox::::new_uninit(GFP_KERNEL) { - Ok(storage) => { - *slot = Some(KBox::write(storage, orphan)); - self.orphaned.store(true, Ordering::Release); - } - // Without memory for the box, leak the parts as they are. - Err(_) => { - core::mem::forget(orphan); - dev_err!( - self.dev.as_ref(), - "G16: cannot keep the failed session; leaked\n" - ); - } - } + *slot = Some(retained); + self.orphaned.store(true, Ordering::Release); } /// Drains the receive rings of an orphaned session. fn drain_orphan(&self) { - if let Some(orphan) = self.orphan.lock().as_deref_mut() { + if let Some(orphan) = &mut *self.orphan.lock() { let _ = orphan.drain(); } } @@ -562,7 +579,7 @@ pub(crate) struct Firmware { /// PMP thermal vote and firmware DVFS ceiling state. pub(crate) power: power::Power, /// Render UMA/PB allocators, their spare set and parameter-buffer growth. - pub(crate) pools: pools::Pools, + pub(crate) pools: KBox, /// 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). @@ -591,6 +608,7 @@ impl Gpu { /// Admits and boots a G16 GPU: identity checks, PMP AGX vote, RTKit, UAT handoff, initdata, /// READY, then the compute and render graphs. On success the module is pinned: the /// firmware session lasts until reboot. + #[inline(never)] pub(crate) fn new( pdev: &platform::Device>, dev: &AsahiDrmDevice, @@ -610,6 +628,7 @@ impl Gpu { let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; + let scrub_queue = slots::ScrubQueue::new_boxed()?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -650,7 +669,7 @@ impl Gpu { poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), fast_poll_unbound <- new_work!("g16::Shared::fast_poll_unbound"), - scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), + scrub_queue <- new_spinlock!(scrub_queue, "g16::Shared::scrub_queue"), scrub_work <- new_work!("g16::Shared::scrub_work"), feed_work <- new_work!("g16::Shared::feed_work"), resnap <- HrTimer::new(), @@ -705,48 +724,19 @@ impl Firmware { #[inline(never)] fn start_backend( dev: &AsahiDrmDevice, - booted: boot::Booted, + mut booted: KBox, shared: &Arc, mut power: power::Power, ) -> Result> { - let boot::Booted { - session, - init, - mut objects, - channels, - events, - .. - } = booted; dev_info!( 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, - init: initdata::InitData, - events: event::Events, - error: Error| - -> Error { - dev_err!( - dev.as_ref(), - "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", - error - ); - shared.orphan(boot::Orphan { - session, - _objects: objects, - channels: Some(channels), - _init: Some(init), - events, - }); - error - }; + power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut objects)?; + let graph = graph::Graphs::new(dev, &mut booted.objects)?; let slots = slots::Slots::new()?; - let pools = pools::Pools::new(dev); + let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; let slot = KBox::::new_uninit(GFP_KERNEL)?; @@ -754,14 +744,30 @@ impl Firmware { })(); let (graph, slots, pools, vms, engine, slot) = match backend { Ok(backend) => backend, - Err(e) => return Err(orphan(session, objects, channels, init, events, e)), + Err(error) => { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Booted(booted)); + return Err(error); + } }; - let mut firmware = KBox::write( - slot, - Firmware { + let boot::Booted { + session, + init, + mut objects, + channels, + events, + .. + } = KBox::into_inner(booted); + let private_factory = objects.private_factory(); + let mut firmware = slot + .write_init(init!(Firmware { session, init, - private_factory: objects.private_factory(), + private_factory, objects, channels, events, @@ -774,18 +780,16 @@ impl Firmware { vms, last_housekeeping_ns: 0, last_aux_drain_ns: 0, - }, - ); - if let Err(e) = firmware.init_graphs() { - let Firmware { - session, - init, - objects, - channels, - events, - .. - } = KBox::into_inner(firmware); - return Err(orphan(session, objects, channels, init, events, e)); + })) + .unwrap_or_else(|e| match e {}); + if let Err(error) = firmware.init_graphs() { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Firmware(firmware)); + return Err(error); } Ok(firmware) } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 61567df95f16b4..cdc0359c33a0c9 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1358,6 +1358,7 @@ impl Firmware { /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt /// retires its storage; a passed abort quarantines it. Job failure independently drops /// remaining unpublished commands even when the storage fully retired. + #[inline(never)] pub(crate) fn retire_oldest( &mut self, index: usize, diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c1860860642925..54306b109d66ca 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -380,6 +380,7 @@ pub(crate) struct Pools { quarantined_epochs: [Option>; sizes::PB_SLOTS], } impl Pools { + #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { Self { dev: dev.as_ref().as_ref().into(), @@ -398,6 +399,31 @@ impl Pools { quarantined_epochs: [const { None }; sizes::PB_SLOTS], } } + /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the + /// per-slot lease arrays on the kernel stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed(dev: &AsahiDrmDevice) -> Result> { + Ok(KBox::init( + init!(Self { + dev: dev.as_ref().as_ref().into(), + stats: PbStats::default(), + owners: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], + active: None, + last_clean_retired: None, + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], + }), + GFP_KERNEL, + )?) + } /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. #[allow(dead_code)] diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 08cf2543c9c244..4dc9d7d2f837c5 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -198,7 +198,7 @@ impl Queue { }, GFP_KERNEL, )?; - let proof = KBox::new(command::SpanProof::new(), GFP_KERNEL)?; + let proof = command::SpanProof::new_boxed()?; Ok(Self { scheduler, state, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 9f20506a0b0f95..8e9b9a61e3bab9 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -172,6 +172,7 @@ impl Firmware { /// Protocol errors and transport loss always retain uncertain owners. /// A deadline without a firmware recovery notification is not permission /// to manipulate undocumented preemption controls. + #[inline(never)] pub(crate) fn check_hangs(&mut self, done: &mut Completions) -> Result { if let Some(error) = self.recovery.failed { return Err(error); diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 261d872d2113a7..08ae0c679aa881 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -115,14 +115,16 @@ impl Shared { } self.events.drain(); self.events_unbound.drain(); - // `sleeping` is already set, so taking the queued scrubs under `scrub_queue` + // `sleeping` is already set, so draining queued scrubs under `scrub_queue` // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` - // while `scrub_wq.drain()` runs. Drop the drained batch outside the spinlock. - let pending_scrubs = { - let mut queue = self.scrub_queue.lock(); - core::mem::replace(&mut *queue, super::slots::ScrubQueue::new()) - }; - drop(pending_scrubs); + // while `scrub_wq.drain()` runs. Drop each drained item outside the spinlock. + loop { + let item = self.scrub_queue.lock().pop(); + let Some(item) = item else { + break; + }; + drop(item); + } self.scrub_wq.drain(); self.feed.pause(); self.feed_wq.drain(); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 7bcb1ca24913c4..7a4cfeb10aeb63 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -594,16 +594,21 @@ impl Drop for PendingScrub { } } +/// Maximum displaced render pass slots staged in one stack-resident [`ScrubBatch`]. +/// Keeping the batch bounded avoids multi-kilobyte stack frames in poll/submit paths while +/// any additional displaced slots remain flagged for the next pass. +const MAX_SCRUB_BATCH: usize = 8; + /// Zero-allocation batch of displaced render pass slots to scrub after dropping `Shared::state`. pub(crate) struct ScrubBatch { - items: [Option; sizes::RENDER_SLOTS], + items: [Option; MAX_SCRUB_BATCH], len: usize, } impl ScrubBatch { pub(crate) const fn new() -> Self { Self { - items: [const { None }; sizes::RENDER_SLOTS], + items: [const { None }; MAX_SCRUB_BATCH], len: 0, } } @@ -612,8 +617,12 @@ impl ScrubBatch { self.len == 0 } + fn is_full(&self) -> bool { + self.len >= MAX_SCRUB_BATCH + } + fn push(&mut self, item: PendingScrub) -> bool { - if self.len >= sizes::RENDER_SLOTS { + if self.len >= MAX_SCRUB_BATCH { return false; } self.items[self.len] = Some(item); @@ -637,6 +646,19 @@ impl ScrubQueue { } } + /// Allocates an empty [`ScrubQueue`] directly on the heap to keep `Shared` setup off the + /// probe stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + slots: [const { None }; sizes::RENDER_SLOTS], + }), + GFP_KERNEL, + )?) + } + /// Moves every staged scrub from `batch` into the queue. Returns `true` if any was queued. pub(crate) fn push_batch(&mut self, mut batch: ScrubBatch) -> bool { let mut pushed = false; @@ -698,6 +720,7 @@ pub(crate) struct Slots { render: KBox, } impl Slots { + #[inline(never)] pub(crate) fn new() -> Result { Ok(Self { cursor: 0, @@ -706,8 +729,8 @@ impl Slots { scrub_gen: 0, stats: SlotStats::default(), scrub: Arc::new(ScrubState::new(), GFP_KERNEL)?, - compute: KBox::new( - ComputeOwners { + compute: KBox::init( + init!(ComputeOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::COMPUTE_UNITS], pending_retarget: [None; sizes::COMPUTE_UNITS], @@ -716,11 +739,11 @@ impl Slots { pending_arena: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], last_full: [true; sizes::COMPUTE_UNITS], - }, + }), GFP_KERNEL, )?, - render: KBox::new( - RenderOwners { + render: KBox::init( + init!(RenderOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::RENDER_SLOTS], pending_retarget: [None; sizes::RENDER_SLOTS], @@ -731,7 +754,7 @@ impl Slots { last_full: [true; sizes::RENDER_SLOTS], staged: ScrubBatch::new(), scrub_pending: false, - }, + }), GFP_KERNEL, )?, }) @@ -876,6 +899,10 @@ impl Slots { let Some(arena) = self.render.arena[k].clone() else { continue; }; + if self.render.staged.is_full() { + self.render.scrub_pending = true; + break; + } self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); let generation = self.scrub.generation.load(Ordering::Acquire); let item = PendingScrub { @@ -886,6 +913,7 @@ impl Slots { done: false, }; if !self.render.staged.push(item) { + self.render.scrub_pending = true; break; } } 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 4b852323520115..3d1e261e301bc8 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 @@ -697,6 +697,7 @@ pub(crate) vm: &'a mmu::Vm, pub(crate) usc_base: u64, } + use super::MAX_COMMANDS; RENDER_ADMISSION fn check_render_one( 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 5f3741b9824d65..be994dc4e53eb7 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -44,9 +44,10 @@ 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; +macro_rules! init { ($($tt:tt)*) => { $($tt)* }; } 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)))}} +implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} pub fn init(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); From 69d1023293376eac44cdab4b30018989e8050229 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 17:49:53 -0500 Subject: [PATCH 0873/1514] drm/asahi: g16: pipeline warm cross-VM renders and eliminate hold[0] drains Allow warm cross-VM renders (reusing a VM's already-primed PB/UMA slot) to pipeline behind active non-InitBM render flights of another VM while preserving exact cross-VM FS ordering and disallowing cross-VM render/compute overlap in both directions (so long compute dispatches cannot starve another client's fragment shading into a firmware DM1 timeout): - Relax needs_engine_drain() and can_queue_behind() for warm cross-VM render-behind-render while draining on cold InitBM renders and on any cross-VM render/compute switch in either direction. - Preserve per-VM hardware FS barriers on cross-VM render overlap while allowing cross-VM TA to overlap the preceding VM's FS. - Add host regression tests covering the full cross-VM render/compute overlap matrix and hold[0] drain behavior. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 111 +++++--- drivers/gpu/drm/asahi/g16/hw.rs | 4 +- .../drivers/gpu/asahi-m4/test-publication.py | 240 +++++++++++++++--- .../drivers/gpu/asahi-m4/test-recovery.py | 17 ++ .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 50 ++++ 5 files changed, 338 insertions(+), 84 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 8fea292c4b5246..94c73d55727754 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -176,13 +176,21 @@ struct RenderBarrierPlan { } /// Computes TA/FS hardware ring barriers for a render command from its flags, prior render -/// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), and resolved `[ta, fs]` -/// compute wait stamps. +/// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), resolved `[ta, fs]` +/// compute wait stamps, and whether the immediately preceding in-flight render belongs to a +/// different VM (`cross_vm_prev`). /// -/// Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so TA(N) -/// must still wait on TA(N-1) (`ta_prev_wait`, matching G15's `prev_barrier`) whenever +/// Same-VM pipelined renders share one parameter-buffer / UMA slot, and cross-VM pipelined +/// renders use distinct UMA slots (`RENDER_UMA_SLOT + slot`) on the shared TA/FS pipes: TA(N) +/// always waits on TA(N-1) (`ta_prev_wait`, matching G15's `prev_barrier`) whenever /// `ta_fs_wait` does not already wait on `prev_fs` (which dominates `prev_ta` via -/// `own_barrier`). Independent FS passes still omit `fs_dep`. +/// `own_barrier`). Same-VM independent FS passes omit `fs_dep`, while `cross_vm_prev` forces +/// `fs_render_wait = Some(prev_fs)` (whenever `ta_fs_wait != Some(prev_fs)`) so cross-VM TA +/// overlaps the previous VM's FS without ever overlapping two VMs' FS/PB teardowns. +#[expect( + clippy::too_many_arguments, + reason = "Pure barrier-plan helper mirrors the exact render barrier inputs." +)] fn plan_render_barriers( flags: u32, class_behind: bool, @@ -191,6 +199,7 @@ fn plan_render_barriers( fs_wait_render: Option, ta_wait_fs: Option, compute_waits: [Option; 2], + cross_vm_prev: bool, ) -> RenderBarrierPlan { let staged = flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; @@ -220,8 +229,16 @@ fn plan_render_barriers( None }; let ta_prev_wait = class_behind && ta_fs_wait != Some(prev_fs); - let fs_render_wait = if class_behind && early && fs_wait_render != ta_fs_wait { + let effective_fs_wait = if cross_vm_prev && class_behind { + Some(prev_fs) + } else { fs_wait_render + }; + let fs_render_wait = if class_behind + && (early || (cross_vm_prev && ta_fs_wait != Some(prev_fs))) + && effective_fs_wait != ta_fs_wait + { + effective_fs_wait } else { None }; @@ -952,13 +969,13 @@ impl Firmware { }; let mut 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: only - // healthy non-InitBM commands (cross-VM compute or same-VM render) queue - // behind active flights; when the head queue cannot queue behind (e.g. its - // class hit its flight cap), still allow another ready queue to run - // concurrently while preserving per-queue FIFO, unless the head job itself - // requires `flights` to drain to empty first (cross-VM render switch, - // unprimed InitBM render, failed VM, or recovery/InitBM in flight). + // error fence must not race that command's access to user buffers: healthy + // non-InitBM commands (compute or warm-PB render of any VM) queue behind + // active flights; when the head queue cannot queue behind (e.g. its class + // hit its flight cap), still allow another ready queue to run concurrently + // while preserving per-queue FIFO, unless the head job itself requires + // `flights` to drain to empty first (unprimed cold InitBM render, failed + // VM, or recovery/InitBM in flight). if !self.engine.flights.is_empty() && !self.can_queue_behind(&job) { if self.needs_engine_drain(&job) { self.engine.stats.hold[0] += 1; @@ -1237,7 +1254,7 @@ impl Firmware { f.doomed || f.recovery_suspect || f.initbm - || ((is_render || (is_compute && f.renders != 0)) + || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) || (is_render @@ -1247,9 +1264,9 @@ impl Firmware { .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n))) } - /// Whether `job` is ready to run on the same VM but currently blocked solely on - /// flight-depth or pass/compute-slot headroom (not on cross-VM/InitBM/recovery drain, - /// external sync dependencies, or CPU timestamp-publish waits). + /// Whether `job` is ready to run without an engine drain but currently blocked solely on + /// flight-depth or pass/compute-slot headroom (not on InitBM/recovery drain, external sync + /// dependencies, or CPU timestamp-publish waits). fn blocked_on_slot_headroom(&self, job: &Arc) -> bool { let e = &self.engine; if e.flights.is_empty() || self.needs_engine_drain(job) { @@ -1322,28 +1339,26 @@ impl Firmware { /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` /// is set and a same-queue predecessor in its compute or render barrier prefix has /// CPU-published timestamp outputs that have not retired yet - /// (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). Cross-VM compute never - /// overlaps an active render of another VM so long compute dispatches cannot starve - /// another client's fragment shading into a firmware DM1 timeout. - /// - Render queues behind healthy same-VM non-InitBM render and/or compute flights (up to - /// [`params::render_flights`] active renders), rotating `PassSlot` (`0..RENDER_SLOTS`) - /// while sharing the active exposed PB/UMA allocator slot (`Pools::can_pipeline`). - /// Hardware barriers on the CDM/TA/FS rings preserve exact same-engine and cross-engine - /// ordering while barrier-free or independent-queue compute and render run concurrently. - /// - Cross-VM render switches, InitBM priming renders, and every failure or recovery path + /// (`DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS` clears `query_access`). + /// - Render queues behind healthy non-InitBM render flights of any VM or same-VM compute + /// flights (up to [`params::render_flights`] active renders), rotating `PassSlot` + /// (`0..RENDER_SLOTS`) while reusing that VM's warm PB/UMA allocator slot + /// (`Pools::can_pipeline_within`, each owning its own hardware UMA slot + /// `RENDER_UMA_SLOT + slot`). Hardware barriers on the CDM/TA/FS rings preserve exact + /// same-engine, cross-engine, and cross-VM FS ordering while allowing cross-VM TA to + /// overlap the preceding VM's FS. + /// - Cross-VM compute/render overlap is disallowed in both directions so a long compute + /// dispatch from one client cannot starve another client's fragment shading into a + /// firmware DM1 timeout. Cold 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; let sent = job.progress.sent(); - let is_render = matches!(command(job, sent), Some(Command::Render(_))); if job.vm.status.get() != 0 || e.flights.len() >= super::hw::sizes::FLIGHTS - || e.flights.iter().any(|f| { - f.doomed - || f.recovery_suspect - || f.initbm - || (is_render && !Arc::ptr_eq(&f.job.vm, &job.vm)) - }) + || e.flights + .iter() + .any(|f| f.doomed || f.recovery_suspect || f.initbm) { return false; } @@ -1392,8 +1407,13 @@ impl Firmware { .is_ok_and(|units| self.slots.compute_available(units)) } Some(Command::Render(_)) => { + let cross_vm_compute = e + .flights + .iter() + .any(|f| f.computes != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); - render_count < params::render_flights() + !cross_vm_compute + && render_count < params::render_flights() && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES && !self.slots.render_exhausted() && !self.pools.exhausted() @@ -2641,6 +2661,15 @@ impl Firmware { } else { None }; + let cross_vm_prev = member == 0 + && class_behind + && self + .engine + .flights + .iter() + .rev() + .find(|fl| fl.renders != 0) + .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); let plan = plan_render_barriers( cmd.cmd.flags, has_prior_render, @@ -2652,6 +2681,7 @@ impl Firmware { ta_wait_compute.map(|w| w.stamp), fs_wait_compute.map(|w| w.stamp), ], + cross_vm_prev, ); // Claim performs only a qualified per-use scrub, never allocator/list reset. self.slots @@ -2663,8 +2693,9 @@ impl Firmware { .pools .pick_slot_within(&job.vm, behind, pb_slots) .ok_or(EAGAIN)?; + let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = - self.render_refs(alloc_slot, job, draw, class_behind, behind)?; + self.render_refs(alloc_slot, job, draw, slot_pipelined, behind)?; f.pb = Some(epoch); f.pb_slot = alloc_slot as u32; f.pb_binding = binding; @@ -2777,11 +2808,11 @@ impl Firmware { r.ring[0].w64(8 * pf.ta_head as usize, epoch.initbm.va)?; pf.ta_head = (pf.ta_head + 1) % cap; } - // Pipelined same-VM render->render and cross-engine (CDM->TA, CDM->FS) barriers use + // Pipelined render->render and cross-engine (CDM->TA, CDM->FS) barriers use // `BarrierType::Stamp` (type 0) only when neither producer, any live flight, nor this // consumer carries `InitBM`: G16 `FINALIZE` flushes producer caches before advancing // `fw_stamp` (unlike G15's `CROSS_ENGINE_HOLD`; see `cross_engine_barrier_type`). - // Cross-VM transitions and recovery paths drain completely before publishing. + // Cold `InitBM` transitions and recovery paths drain completely before publishing. let producer_initbm = pf.initbm || self.engine.flights.iter().any(|fl| fl.initbm) || ta_wait_compute.is_some_and(|w| w.initbm) @@ -2789,11 +2820,11 @@ impl Firmware { || fs_wait_render.is_some_and(|w| w.initbm) || ta_wait_fs.is_some_and(|w| w.initbm); let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); - // Pipelined renders share one parameter-buffer / UMA epoch (`RENDER_UMA_SLOT`), so keep + // Pipelined renders share TA/FS pipes across same-VM and cross-VM flights, so keep // the TA(N-1)->TA(N) `prev_barrier` (matching G15) whenever `plan.ta_fs_wait` does not // already serialize behind `prev_fs`. Emit `ta_fs_barrier` only when `plan.ta_fs_wait` - // names an in-flight FS stamp, and `fs_dep` only when `plan.fs_render_wait` names an - // in-flight FS dependency not already dominated by TA. + // names an in-flight FS stamp, and `fs_dep` when `plan.fs_render_wait` names an + // in-flight FS dependency (or cross-VM `prev_fs`) not already dominated by TA. if plan.ta_prev_wait { let prev = encode::barrier( r.fw_stamp[0].va, diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 84b67762863794..5311de8e0f6a2b 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -770,8 +770,8 @@ 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. Same-VM compute or render commands may pipeline behind - /// each other on their engine rings while cross-VM and cross-engine transitions drain. + /// Published prefixes at most. Warm compute and render commands may pipeline across VMs + /// on disjoint hardware UMA slots while cold `InitBM` renders and recovery paths 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`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused 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 8e92f467928cca..496ee218749313 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -453,16 +453,18 @@ def item(declaration): assert_eq!(f.publish_checked(&mut done),Ok(())); assert_eq!(f.attempted,[2,3]); } - #[test]fn alt_bypass_does_not_starve_cross_vm_render_while_compute_overlaps(){ + #[test]fn alt_bypass_does_not_starve_cold_cross_vm_initbm_while_warm_overlaps(){ let vm1=mk_vm(1); let vm2=mk_vm(2); let vm1_active=job_on_vm(1,vm1.clone(),false,0,Ok(())); - let vm2_render=job_on_vm(2,vm2.clone(),true,0,Ok(())); + let vm2_cold_render=job_on_vm(2,vm2.clone(),true,0,Ok(())); let vm1_pending=job_on_vm(3,vm1.clone(),false,0,Ok(())); vm1_pending.queue.turn.store(5,Ordering::Relaxed); - let mut f=firmware(vec![vm2_render,vm1_pending],vec![(Ok(()),true),(Ok(()),true)]); + let mut f=firmware(vec![vm2_cold_render,vm1_pending],vec![(Ok(()),true),(Ok(()),true)]); f.engine.flights.push(Flight::new(vm1_active)); f.allow_behind=true; + // Cold cross-VM render (requires InitBM) must drain without starvation. + f.pools.block_pipeline_vm=Some(vm2.slot); let mut done=vec![]; assert_eq!(f.publish_checked(&mut done),Ok(())); assert!(f.attempted.is_empty()); @@ -470,36 +472,57 @@ def item(declaration): assert_eq!(f.engine.pending.len(),2); f.engine.flights.clear(); assert_eq!(f.publish_checked(&mut done),Ok(())); - // VM2 render publishes first; VM1 compute waits for VM2 render to drain (no cross-VM R<->C overlap). + // Once drained, VM2's InitBM render publishes (fl.initbm=true blocks vm1_pending behind it). assert_eq!(f.attempted,[2]); assert_eq!(f.engine.pending.len(),1); - f.engine.flights.clear(); - assert_eq!(f.publish_checked(&mut done),Ok(())); - assert_eq!(f.attempted,[2,3]); - // Cross-VM compute queues immediately behind another VM's active compute without drain, - // but drains behind another VM's active render so compute cannot starve cross-VM FS. - let vm1_c=job_on_vm(10,vm1.clone(),false,0,Ok(())); - let vm2_c=job_on_vm(11,vm2.clone(),false,0,Ok(())); + // Warm cross-VM render queues directly behind another VM's active render with zero hold[0]. + let vm1_r=job_on_vm(10,vm1.clone(),true,0,Ok(())); + let vm2_warm_r=job_on_vm(11,vm2.clone(),true,0,Ok(())); + let mut fw=firmware(vec![vm2_warm_r],vec![(Ok(()),true)]); + let mut fl=Flight::new(vm1_r); + fl.renders=1; + fw.engine.flights.push(fl); + fw.allow_behind=true; + assert_eq!(fw.publish_checked(&mut done),Ok(())); + assert_eq!(fw.attempted,[11]); + assert_eq!(fw.engine.stats.hold[0],0); + + // Cross-VM compute queues immediately behind another VM's active compute without drain. + let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); + let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); - let mut fl=Flight::new(vm1_c); - fl.computes=1; - fc.engine.flights.push(fl); + let mut flc=Flight::new(vm1_c); + flc.computes=1; + fc.engine.flights.push(flc); fc.allow_behind=true; assert_eq!(fc.publish_checked(&mut done),Ok(())); - assert_eq!(fc.attempted,[11]); + assert_eq!(fc.attempted,[13]); assert_eq!(fc.engine.stats.hold[0],0); - let vm1_r=job_on_vm(12,vm1,true,0,Ok(())); - let vm2_c2=job_on_vm(13,vm2,false,0,Ok(())); + // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). + let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); + let vm2_c2=job_on_vm(15,vm2.clone(),false,0,Ok(())); let mut fcr=firmware(vec![vm2_c2],vec![(Ok(()),true)]); - let mut flr=Flight::new(vm1_r); + let mut flr=Flight::new(vm1_r2); flr.renders=1; fcr.engine.flights.push(flr); fcr.allow_behind=true; assert_eq!(fcr.publish_checked(&mut done),Ok(())); assert!(fcr.attempted.is_empty()); assert_eq!(fcr.engine.stats.hold[0],1); + + // Symmetrically, warm cross-VM render drains behind another VM's active compute. + let vm1_c2=job_on_vm(16,vm1,false,0,Ok(())); + let vm2_r2=job_on_vm(17,vm2,true,0,Ok(())); + let mut frc=firmware(vec![vm2_r2],vec![(Ok(()),true)]); + let mut flc2=Flight::new(vm1_c2); + flc2.computes=1; + frc.engine.flights.push(flc2); + frc.allow_behind=true; + assert_eq!(frc.publish_checked(&mut done),Ok(())); + assert!(frc.attempted.is_empty()); + assert_eq!(frc.engine.stats.hold[0],1); } #[test]fn alt_bypass_preserves_per_queue_fifo_order(){ let vm1=mk_vm(1); @@ -611,10 +634,10 @@ def item(declaration): 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} +struct QueueBehindPools{exhausted:bool,can_pipeline:bool,block_pipeline_vm:Option} impl QueueBehindPools{ fn exhausted(&self)->bool{self.exhausted} - fn can_pipeline(&self,_vm:&Arc)->bool{self.can_pipeline} + fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} @@ -674,7 +697,7 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&j2)); // Cross-VM compute queues behind another VM's healthy compute, but drains behind @@ -720,7 +743,7 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(!p.can_queue_behind(&query_copy)); assert!(p.can_queue_behind(&no_query)); @@ -738,7 +761,7 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(!pr.can_queue_behind(&mk(2,q1.clone(),true,Some(1),None))); assert!(pr.can_queue_behind(&mk(2,q1.clone(),false,Some(1),None))); @@ -762,13 +785,19 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&r2)); + // Warm cross-VM render queues behind healthy non-InitBM render; cold InitBM VM drains. + assert!(p.can_queue_behind(&r_other_vm)); + p.pools.block_pipeline_vm=Some(vm2.slot); assert!(!p.can_queue_behind(&r_other_vm)); + assert!(p.needs_engine_drain(&r_other_vm)); + p.pools.block_pipeline_vm=None; assert!(p.can_queue_behind(&c1)); p.engine.flights[0].initbm=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=false; p.pools.can_pipeline=false; @@ -782,6 +811,48 @@ def item(declaration): assert!(!p.can_queue_behind(&r2)); assert!(!p.can_queue_behind(&c1)); } + #[test]fn cross_vm_render_compute_overlap_matrix(){ + 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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(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:false})}], + order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let vm1_r=mk(1,vm1.clone(),q1.clone(),true); + let vm1_c=mk(2,vm1.clone(),q1.clone(),false); + let vm2_r=mk(3,vm2.clone(),q2.clone(),true); + let vm2_c=mk(4,vm2.clone(),q2.clone(),false); + let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ + job,group:vec![],first:0,count:1,computes:c,renders:r, + target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, + fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Active VM1 Render: same-VM R & C allowed; cross-VM R allowed; cross-VM C blocked + drains. + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + // Active VM1 Compute: same-VM R & C allowed; cross-VM C allowed; cross-VM R blocked + drains. + p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); + assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. + p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + } #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); @@ -805,7 +876,7 @@ def item(declaration): QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Same-queue FS -> CDM barrier resolves render's fs_target; CDM -> TA resolves compute's target. assert_eq!(p.cross_engine_wait(&c1,0,command::RENDER),Ok(Some(WaitTarget{stamp:0x500,initbm:false}))); @@ -841,7 +912,7 @@ def item(declaration): QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert_eq!(pm.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); assert_eq!(pm.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); @@ -876,7 +947,7 @@ def item(declaration): initbm:true,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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; let fs2c = host.cross_engine_wait(&c_after_r, 0, command::RENDER).unwrap().unwrap(); assert_eq!(fs2c, WaitTarget { stamp: 0x900, initbm: true }); @@ -921,7 +992,7 @@ def item(declaration): 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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Queue 1 render queues directly behind Queue 0 compute on the same VM with no cross-engine barrier. assert!(p.can_queue_behind(&r_job)); @@ -959,7 +1030,7 @@ def item(declaration): 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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert_eq!(p.cross_engine_wait(&r_wait_c2,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); assert_eq!(p.cross_engine_wait(&r_wait_c3,0,command::COMPUTE),Ok(Some(WaitTarget{stamp:0x300,initbm:false}))); @@ -999,7 +1070,7 @@ def item(declaration): 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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Lookup into published multi-pass render flight resolves interior and tail passes. assert_eq!(p.wait_stamp_for(&next_r,command::RENDER,Some(1)),Ok(Some(WaitTarget{stamp:0x100,initbm:false}))); @@ -1068,7 +1139,7 @@ def item(declaration): 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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Below TA_WAVE_PASSES (2 < 3): zero WC fw_stamp reads. assert_eq!(p.ta_pending_passes(),2); @@ -1113,18 +1184,21 @@ def item(declaration): 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}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Not blocked on slots when pass_available is true and render_flights has headroom. assert!(!p.blocked_on_slot_headroom(&r_same)); // Waiting on CPU timestamp publish (query_access) is NOT a slot-headroom block. assert!(!p.can_queue_behind(&c_ts_wait)); assert!(!p.blocked_on_slot_headroom(&c_ts_wait)); - // Render pass slot exhaustion IS a slot-headroom block for a ready same-VM render... + // Render pass slot exhaustion IS a slot-headroom block for ready same-VM and warm cross-VM renders... p.slots.pass_available=false; assert!(p.blocked_on_slot_headroom(&r_same)); - // ...but NOT for cross-VM, external-fence, or InitBM/PB-unprimed jobs. + assert!(p.blocked_on_slot_headroom(&r_cross_vm)); + // ...but NOT for cold InitBM cross-VM, external-fence, or live-InitBM jobs. + p.pools.block_pipeline_vm=Some(vm2.slot); assert!(!p.blocked_on_slot_headroom(&r_cross_vm)); + p.pools.block_pipeline_vm=None; assert!(!p.blocked_on_slot_headroom(&r_ext_fence)); p.pools.can_pipeline=false; assert!(!p.blocked_on_slot_headroom(&r_same)); @@ -1137,12 +1211,14 @@ def item(declaration): p.engine.flights[0].renders=47; assert!(p.blocked_on_slot_headroom(&r_same)); - // End-to-end publish_checked: cross-VM drain leaves slot_wait=false; same-VM slot block sets slot_wait=true. + // End-to-end publish_checked: cold InitBM cross-VM drain leaves slot_wait=false; + // warm render slot block sets slot_wait=true. let v1=mk_vm(1); let v2=mk_vm(2); - let mut fc=firmware(vec![job_on_vm(2,v2,true,0,Ok(()))],vec![]); + let mut fc=firmware(vec![job_on_vm(2,v2.clone(),true,0,Ok(()))],vec![]); fc.engine.flights.push(super::Flight::new(job_on_vm(1,v1.clone(),true,0,Ok(())))); fc.allow_behind=true; + fc.pools.block_pipeline_vm=Some(v2.slot); let mut done=vec![]; assert_eq!(fc.publish_checked(&mut done),Ok(())); assert!(!fc.engine.slot_wait); @@ -1157,10 +1233,10 @@ def item(declaration): #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; - // 1. Cross-VM / InitBM / empty render pipe (`class_behind = false`): zero render barriers, + // 1. Cold InitBM / empty render pipe (`class_behind = false`): zero render barriers, // compute->FS-only wait routes directly to fs_compute_barrier. assert_eq!( - plan_render_barriers(STAGED, false, true, 0, None, None, [None, Some(0x700)]), + plan_render_barriers(STAGED, false, true, 0, None, None, [None, Some(0x700)], false), RenderBarrierPlan { early: false, ta_prev_wait: false, @@ -1176,7 +1252,7 @@ def item(declaration): // ZERO FS->FS barriers (only own_barrier on FS). for flags in [0u32, FRAG, STAGED] { assert_eq!( - plan_render_barriers(flags, true, true, 0x200, None, None, [None, None]), + plan_render_barriers(flags, true, true, 0x200, None, None, [None, None], false), RenderBarrierPlan { early: true, ta_prev_wait: true, @@ -1198,6 +1274,7 @@ def item(declaration): Some(0x200), None, [Some(0x700), Some(0x700)], + false, ), RenderBarrierPlan { early: true, @@ -1219,6 +1296,7 @@ def item(declaration): None, None, [Some(0x600), Some(0x700)], + false, ), RenderBarrierPlan { early: true, @@ -1240,6 +1318,7 @@ def item(declaration): Some(0x200), Some(0x100), [None, None], + false, ), RenderBarrierPlan { early: true, @@ -1262,6 +1341,7 @@ def item(declaration): Some(0x100), Some(0x100), [None, None], + false, ), RenderBarrierPlan { early: true, @@ -1284,6 +1364,7 @@ def item(declaration): Some(0x200), Some(0x200), [None, None], + false, ), RenderBarrierPlan { early: false, @@ -1305,6 +1386,7 @@ def item(declaration): Some(0x200), None, [Some(0x700), Some(0x700)], + false, ), RenderBarrierPlan { early: true, @@ -1318,7 +1400,7 @@ def item(declaration): // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): // TA waits on 0x200 (FS->TA, dominating prev_ta); prev_barrier and fs_dep omitted. assert_eq!( - plan_render_barriers(0, true, true, 0x200, Some(0x200), None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x200), None, [None, None], false), RenderBarrierPlan { early: false, ta_prev_wait: false, @@ -1331,7 +1413,7 @@ def item(declaration): // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): // TA still needs prev_barrier on the shared PB in addition to ta_fs_wait(0x100). assert_eq!( - plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None]), + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None], false), RenderBarrierPlan { early: false, ta_prev_wait: true, @@ -1344,7 +1426,50 @@ def item(declaration): // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when // fs_wait_render is None, dominating prev_ta and omitting fs_dep. assert_eq!( - plan_render_barriers(FRAG, true, false, 0x200, None, None, [None, None]), + plan_render_barriers(FRAG, true, false, 0x200, None, None, [None, None], false), + RenderBarrierPlan { + early: false, + ta_prev_wait: false, + ta_fs_wait: Some(0x200), + fs_render_wait: None, + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 12. Cross-VM warm render behind another VM's render (`cross_vm_prev = true`, no + // own-queue render barrier): TA runs early behind prev_ta (overlapping VM A's FS) + // for all flag styles (legacy/FRAG/STAGED) while FS ALWAYS waits on prev_fs (0x200). + for flags in [0u32, FRAG, STAGED] { + assert_eq!( + plan_render_barriers(flags, true, true, 0x200, None, None, [None, None], true), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: Some(0x200), + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + } + // 13. Cross-VM legacy render that also has an own-queue barrier on an older FS (0x100): + // TA waits on own older FS (0x100) and prev_ta, while FS still waits on cross-VM + // prev_fs (0x200) so two VMs' FS/PB teardowns never overlap. + assert_eq!( + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None], true), + RenderBarrierPlan { + early: false, + ta_prev_wait: true, + ta_fs_wait: Some(0x100), + fs_render_wait: Some(0x200), + ta_compute_wait: None, + fs_compute_wait: None, + } + ); + // 14. Cross-VM with `early_tiling = false`: TA already waits on prev_fs, so fs_dep + // is dominated and omitted. + assert_eq!( + plan_render_barriers(STAGED, true, false, 0x200, None, None, [None, None], true), RenderBarrierPlan { early: false, ta_prev_wait: false, @@ -1872,6 +1997,37 @@ def item(declaration): // VM 2's co-resident compute is suspect-only (checked via hardware ITS ticks), NEVER doomed! assert!(!fw.engine.flights[1].doomed); assert!(fw.engine.flights[1].recovery_suspect); + + // Two co-resident cross-VM renders: VM 1 faults on FS 0x100 while VM 2 has live render 0x200. + let mut r2_ta = [0u32; 16]; + let mut r2_fs = [0u32; 16]; + r2_ta[0] = 0x200; r2_fs[0] = 0x200; + fw.engine.flights[0].doomed = false; + fw.engine.flights[0].recovery_suspect = false; + fw.engine.flights[1] = RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 0, + renders: 1, + target: 0, + ta_target: 0x200, + fs_target: 0x200, + cstamp: [0; 16], + r_ta_stamp: r2_ta, + r_fs_stamp: r2_fs, + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }; + fw.engine.ta_target = 0x200; + fw.engine.fs_target = 0x200; + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x200, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare_suspects([0x200, 0, 0], 0x71, Some(1)), Ok(())); + assert!(fw.engine.flights[0].doomed); + assert!(!fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); } } ''' 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 031d918925c002..4f6e79e6857594 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-recovery.py @@ -133,6 +133,23 @@ assert_eq!(before.quarantined, 0); assert!(logic::admit(logic::WINDOW_NS + 2, &mut window, &mut count)); } + + #[test] + fn cross_vm_render_abort_isolates_innocent_flight_and_quarantines_only_aborted_slot() { + let mut owners = Lifetime::<6>::new(true); + // Client A claims slot 0; Client B concurrently claims slot 1. + assert!(owners.claim(0)); + assert!(owners.publish(0)); + assert!(owners.claim(1)); + assert!(owners.publish(1)); + // Client A aborts (affected=true) -> slot 0 quarantined, Client A fails. + assert!(finish(&mut owners, 0, Retirement::Aborted, true)); + // Client B retires Full (affected=false) -> slot 1 cleanly retired, Client B succeeds. + assert!(!finish(&mut owners, 1, Retirement::Full, false)); + assert!(!owners.exhausted()); + assert_eq!(owners.counts().quarantined, 1); + assert_eq!(owners.counts().retired, 1); + } } '''.replace('__ROOT__', str(production)) 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 6fd443776de7dc..fd5c07ea64e104 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 @@ -374,6 +374,56 @@ def function(text, name): assert_eq!(f.engine.flights[0].job.resources.compute[0].its.reads.get(),2); assert_eq!(f.engine.retired_ticks,[0;4]); } +#[test]fn cross_vm_render_hang_recovery_isolates_innocent_client_flight(){ + // VM A (slot 0, ASID 1) hangs/aborts on render n=30 while innocent VM B (slot 1, ASID 2, + // compact stage_ts_mask=0) has a co-resident render n=31 with real FS ticks and independent + // allocator slot completion. VM A aborts; VM B retires Full without blame or error. + CLOCK.with(|c|c.set(100_000_000)); + let mut f=firmware(true,30); + f.engine.flights[0].job.vm.slot=1; + f.engine.flights[0].pb_slot=0; + f.engine.flights[0].stage_ts_mask=0; + f.engine.flights[0].doomed=true; + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=90_000_000; + f.engine.flights[0].job.resources.passes[0].scene=Object::default(); + + let mut innocent=firmware(true,31).engine.flights.remove(0); + innocent.job.vm.slot=2; + innocent.pb_slot=1; + innocent.uma_submitted=2; + innocent.stage_ts_mask=0; + innocent.doomed=false; + innocent.recovery_suspect=true; + innocent.recovery_started_ns=90_000_000; + innocent.job.resources.pools=Pools{full:true,completed:2}; + innocent.job.resources.passes[0].scene=Object::default(); + innocent.job.resources.passes[0].scene.set(0x620,400); + innocent.job.resources.passes[0].scene.set(0x628,430); + f.engine.flights.push(innocent); + + let t31=encode::stamp(31); + f.engine.ta_target=t31; + f.engine.fs_target=t31; + for stage in 0..2 { f.graph.render.fw_stamp[stage].set(0,u64::from(t31)); } + f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(t31)); + f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(t31)); + f.graph.render.notifier.set(notifier::CONTEXT,2); + f.graph.render.notifier.set(notifier_page::FS_RECORD+notifier::CONTEXT,2); + + // After 20 ms recovery grace, hanging VM A aborts on slot 0. + CLOCK.with(|c|c.set(110_000_000)); + let (idx_a,ret_a)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_a,ret_a),(0,Retirement::Aborted)); + assert!(ret_a.job_failed(f.engine.flights[0].doomed)); + f.engine.flights.remove(0); + + // Innocent VM B on slot 1 proves FS execution via cold-path FS ticks and retires Full. + let (idx_b,ret_b)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_b,ret_b),(0,Retirement::Full)); + assert!(!f.engine.flights[0].doomed); + assert!(!ret_b.job_failed(f.engine.flights[0].doomed)); +} mod queue_proof { use super::{Channel, Object, Result, EINVAL}; From 6a873a29fcb9d7ab66d273bfdd6ab6339f2fa2a9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 08:32:53 -0500 Subject: [PATCH 0874/1514] drm/asahi: g16: resolve same-VM cross-queue fences into firmware barriers Cross-queue Vulkan binary and timeline semaphore waits on the same G16 device and VM previously fell through to drm_sched, forcing the producer job to retire on the CPU and wake the scheduler worker before the consumer could enter the engine. Tag G16 queue output fences with their originating GPU, VM, queue, and per-engine ordinals (FenceOrigin), and mark the origin enqueued once Firmware::enqueue accepts the job. On submission, walk the input fence tree via g17::sync_input::collect and, when every unsignalled leaf is an already-enqueued same-GPU same-VM G16 fence (bounded to 8 waits), convert them into job.fw_waits so try_start_inline hands the consumer straight to the firmware engine. Extend dependency checking, timestamp-query serialization, compute and render stamp resolution, single-pipe compute selection, and transitive failure doom propagation in poll.rs to cover job.fw_waits, while keeping horizon folding disabled when cross-queue waits are present. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 301 ++++++++++++------ drivers/gpu/drm/asahi/g16/fence.rs | 197 +++++++++++- drivers/gpu/drm/asahi/g16/job.rs | 43 ++- drivers/gpu/drm/asahi/g16/poll.rs | 29 +- drivers/gpu/drm/asahi/g16/queue.rs | 28 +- drivers/gpu/drm/asahi/g17/mod.rs | 2 +- drivers/gpu/drm/asahi/g17/sync_input.rs | 8 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 67 +++- .../drivers/gpu/asahi-m4/test-publication.py | 129 ++++++-- 9 files changed, 662 insertions(+), 142 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 53e5d968c64675..8e098a6e0eed07 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -929,6 +929,7 @@ impl Firmware { } self.engine.pending.push(job.clone(), GFP_NOWAIT)?; job.progress.set_pending(true); + job.origin.mark_enqueued(); let q = &job.queue; let owned = self.engine.queue_published(&job) + self @@ -1418,7 +1419,7 @@ impl Firmware { // retirement, so dispatches without DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS must wait // for prior timestamped flights in their dependency prefix to retire first. let waits_for_timestamps = c.query_access - && job.command_order(sent).is_some_and(|o| { + && (job.command_order(sent).is_some_and(|o| { let waits_class = |class: usize| { o.wait_through[class].is_some_and(|last| { e.flights.iter().any(|f| { @@ -1437,7 +1438,25 @@ impl Firmware { }) }; waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) - }); + }) || job.fw_waits.iter().any(|w| { + (0..2).any(|class| { + w.last_ordinal[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &w.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }) + }) + })); let cross_vm_render = e .flights .iter() @@ -1481,10 +1500,10 @@ impl Firmware { } } - /// Resolves a same-queue target stamp and producer `InitBM` state for `class` (`RENDER` -> - /// `r_fs_stamp`, `COMPUTE` -> `cstamp`) when `target_seq` names an in-flight command of - /// `job.queue` or an earlier member of an in-progress render batch `current`. Returns - /// `Ok(None)` when no barrier was requested or the waited prefix has already retired. + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` + /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` + /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch + /// `current`). Returns `Ok(None)` when no barrier is needed or every waited prefix retired. fn wait_stamp_for_with( &self, job: &Arc, @@ -1492,97 +1511,128 @@ impl Firmware { target_seq: Option, current: Option<&Flight>, ) -> Result> { - let Some(last) = target_seq else { - return Ok(None); - }; - if job.queue.completed[class].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[class].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[class] else { + continue; + }; + if wait.queue.completed[class].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok(None); } - if class == super::command::COMPUTE { - for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - continue; - } - let mut member = 0usize; - for k in flight.first..flight.first + flight.count { - if flight.job.command_order(k as u32).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } - for j2 in flight.group.iter() { - for k in 0..j2.progress.count() { - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } + let mut newest: Option = None; + let scan_flight = |flight: &Flight, + targets: &mut [Option<(&Arc, u64, bool)>], + newest: &mut Option| + -> Result { + if class == super::command::COMPUTE { + if flight.computes == 0 { + return Ok(()); } + } else if flight.renders == 0 { + return Ok(()); } - return Err(EAGAIN); - } - let find_render = |flight: &Flight| -> Option { - if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - return None; + if !targets + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { + return Ok(()); } - let max_members = (flight.renders as usize).min(flight.r_fs_stamp.len()); + let max_members = if class == super::command::COMPUTE { + (flight.computes as usize).min(flight.cstamp.len()) + } else { + (flight.renders as usize).min(flight.r_fs_stamp.len()) + }; let mut member = 0usize; for k in flight.first..flight.first + flight.count { if member >= max_members { - return None; + break; } - if flight - .job - .command_order(k as u32) - .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) - { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if member >= max_members { - return None; + break; } - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::RENDER && fo.sequence == last - }) { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = j2.command_order(k) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } } - None + Ok(()) }; - if let Some(target) = current.and_then(find_render) { - return Ok(Some(target)); - } for flight in &self.engine.flights { - if let Some(target) = find_render(flight) { - return Ok(Some(target)); - } + scan_flight(flight, &mut targets[..count], &mut newest)?; + } + if let Some(cur) = current { + scan_flight(cur, &mut targets[..count], &mut newest)?; } - Err(EAGAIN) + if targets[..count].iter().flatten().any(|(_, _, found)| !*found) { + return Err(EAGAIN); + } + Ok(newest) } - /// Resolves a same-queue target stamp for `class` across published in-flight flights. + /// Resolves a same-queue or cross-queue target stamp for `class` across published flights. fn wait_stamp_for( &self, job: &Arc, @@ -1592,10 +1642,9 @@ impl Firmware { self.wait_stamp_for_with(job, class, target_seq, None) } - /// Resolves a same-queue cross-engine barrier target when `job`'s command `index` waits on - /// an in-flight command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`). - /// Returns `Ok(None)` when no cross-engine barrier was requested or the waited prefix has - /// already retired. + /// Resolves a cross-engine barrier target when `job`'s command `index` waits on an in-flight + /// command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`), including + /// cross-queue `fw_waits`. Returns `Ok(None)` when no barrier is needed or retired. fn cross_engine_wait( &self, job: &Arc, @@ -1608,26 +1657,55 @@ impl Firmware { self.wait_stamp_for(job, other, target_seq) } - /// Resolves the newest in-flight same-queue compute producer on each compute pipe with - /// ordinal `<= target_seq`. Returns `Ok([None; COMPUTE_PIPES])` when no barrier was - /// requested or the entire prefix through `target_seq` has already retired, and `Err(EAGAIN)` - /// if `target_seq` is neither in flight nor retired. + /// Resolves the newest in-flight compute producer on each compute pipe across `job`'s + /// same-queue `target_seq` and any cross-queue `job.fw_waits`. Returns + /// `Ok([None; COMPUTE_PIPES])` when no barrier is needed or every waited prefix retired, + /// and `Err(EAGAIN)` if any unretired target ordinal is missing from `flights`. fn wait_compute_stamps_for( &self, job: &Arc, target_seq: Option, ) -> Result<[Option; sizes::COMPUTE_PIPES]> { - let Some(last) = target_seq else { - return Ok([None; sizes::COMPUTE_PIPES]); - }; - if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[super::command::COMPUTE] else { + continue; + }; + if wait.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok([None; sizes::COMPUTE_PIPES]); } let mut waits = [None; sizes::COMPUTE_PIPES]; - let mut best_seq = [0u64; sizes::COMPUTE_PIPES]; - let mut found_last = false; for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + if flight.computes == 0 + || !targets[..count] + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { continue; } let pipe = flight.compute_pipe as usize; @@ -1637,12 +1715,17 @@ impl Firmware { let mut member = 0usize; for k in flight.first..flight.first + flight.count { if let Some(fo) = flight.job.command_order(k as u32) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1655,12 +1738,17 @@ impl Firmware { for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if let Some(fo) = j2.command_order(k) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1672,8 +1760,10 @@ impl Firmware { } } } - if !found_last && !job.queue.is_compute_retired(last) { - return Err(EAGAIN); + for (q, last, found) in targets[..count].iter().flatten() { + if !*found && !q.is_compute_retired(*last) { + return Err(EAGAIN); + } } Ok(waits) } @@ -2919,8 +3009,19 @@ impl Firmware { .rev() .find(|fl| fl.renders != 0) .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); + let plan_flags = if !staged + && job + .fw_waits + .iter() + .any(|w| w.last_ordinal[super::command::RENDER].is_some()) + { + cmd.cmd.flags + & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS + } else { + cmd.cmd.flags + }; let plan = plan_render_barriers( - cmd.cmd.flags, + plan_flags, has_prior_render, params::early_tiling(), prev_fs, diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 2890428717f577..1e90a148b3d0b0 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -12,6 +12,7 @@ //! queue teardown). Fences of one context must signal in order, so a [`Timeline`] holds a //! completed fence back until every earlier fence of the queue has completed. +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, @@ -21,6 +22,7 @@ use kernel::{ sync::{Arc, LockClassKey, Mutex}, }; +use super::queue::QueueState; use crate::file::SyncItem; /// Inline storage for the common 0-2 input fences, spilling to a heap `KVec` above 2. @@ -119,9 +121,105 @@ pub(crate) fn wait_dependencies(inputs: &[Fence]) -> Result { static TIMELINE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); static ERROR_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); +static JOB_FENCE_OPS: AtomicUsize = AtomicUsize::new(0); + +/// Maximum distinct cross-queue firmware waits carried inline/on-heap by one job. +pub(crate) const MAX_FW_WAITS: usize = 8; + +/// Immutable origin and atomic lifecycle flags attached to every G16 job fence so another +/// logical queue on the same GPU and VM can resolve a binary or timeline semaphore into an +/// in-firmware ring barrier instead of round-tripping through `drm_sched` and CPU retirement. +pub(crate) struct FenceOrigin { + pub(crate) gpu_id: usize, + pub(crate) vm_id: u64, + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + enqueued: AtomicBool, + failed: AtomicBool, +} + +impl FenceOrigin { + pub(crate) fn new( + gpu_id: usize, + vm_id: u64, + queue: Arc, + last_ordinal: [Option; 2], + ) -> Self { + Self { + gpu_id, + vm_id, + queue, + last_ordinal, + enqueued: AtomicBool::new(false), + failed: AtomicBool::new(false), + } + } + + pub(crate) fn mark_enqueued(&self) { + self.enqueued.store(true, Ordering::Release); + } + + pub(crate) fn is_enqueued(&self) -> bool { + self.enqueued.load(Ordering::Acquire) + } + + pub(crate) fn mark_failed(&self) { + self.failed.store(true, Ordering::Release); + } + + pub(crate) fn is_failed(&self) -> bool { + self.failed.load(Ordering::Acquire) + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 entries, bounded to +/// [`MAX_FW_WAITS`]). +pub(crate) enum FwWaits { + Empty, + One([Arc; 1]), + Heap(KVec>), +} + +impl FwWaits { + fn push_unique(&mut self, origin: Arc) -> Result { + if self.iter().any(|existing| Arc::ptr_eq(existing, &origin)) { + return Ok(()); + } + if self.len() >= MAX_FW_WAITS { + return Err(E2BIG); + } + match self { + Self::Empty => *self = Self::One([origin]), + Self::One(_) => { + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::One([first]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(first); + let _ = vec.push_within_capacity(origin); + } + *self = Self::Heap(vec); + } + Self::Heap(vec) => vec.push(origin, GFP_KERNEL)?, + } + Ok(()) + } +} + +impl core::ops::Deref for FwWaits { + type Target = [Arc]; + + fn deref(&self) -> &[Arc] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Heap(vec) => vec, + } + } +} /// Fence operations of G16 job fences. -pub(crate) struct JobFenceOps; +pub(crate) struct JobFenceOps { + origin: Arc, +} #[vtable] impl FenceOps for JobFenceOps { @@ -134,6 +232,85 @@ impl FenceOps for JobFenceOps { } } +/// Fence operations of pre-signalled refused-submission fences (distinct vtable from +/// [`JobFenceOps`] so refused error fences never match [`origin_from_raw`]). +struct RefusedFenceOps; + +#[vtable] +impl FenceOps for RefusedFenceOps { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("aurora") + } + + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("g16-refused") + } +} + +/// Resolves a G16 [`FenceOrigin`] from a raw `dma_fence` pointer if and only if its vtable +/// pointer matches the registered [`JobFenceOps`] vtable. +/// +/// # Safety +/// +/// `raw` must be null or point to a live, initialized `dma_fence` whose reference is held for +/// the duration of this call. +unsafe fn origin_from_raw(raw: *mut kernel::bindings::dma_fence) -> Option> { + let expected = JOB_FENCE_OPS.load(Ordering::Acquire); + if expected == 0 || raw.is_null() { + return None; + } + // SAFETY: Caller retains a live dma_fence reference. `JobFenceOps` has a distinct timeline + // name and nontrivial payload drop (`Arc`). No cast precedes the exact + // registered vtable check, and `FenceObject` begins with its `dma_fence`. + let object = unsafe { + if (*raw).ops as usize != expected { + return None; + } + &*(raw as *const FenceObject) + }; + Some(object.origin.clone()) +} + +/// Resolves `inputs` into same-GPU, same-VM in-firmware cross-queue waits outside the device +/// lock. Returns `None` if any leaf is failed, foreign, cross-VM, not yet enqueued, or exceeds +/// [`MAX_FW_WAITS`], leaving the caller to retain normal `drm_sched` / `InputFences` waits. +pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> Option { + if inputs.is_empty() { + return Some(FwWaits::Empty); + } + let mut waits = FwWaits::Empty; + for input in inputs { + let status = dependency_status(input); + if status < 0 { + return None; + } + if status > 0 { + continue; + } + let leaves = crate::g17::sync_input::collect(input)?; + for leaf in leaves.iter() { + if leaf.status < 0 { + return None; + } + if leaf.status > 0 { + continue; + } + // SAFETY: `leaf` retains an owned reference to `leaf.fence` until dropped. + let origin = unsafe { origin_from_raw(leaf.fence) }?; + if origin.gpu_id != gpu_id + || origin.vm_id != vm_id + || !origin.is_enqueued() + || origin.is_failed() + || origin.last_ordinal == [None, None] + { + return None; + } + waits.push_unique(origin).ok()?; + } + } + Some(waits) +} + /// Stack batch size for signalling completed fences outside `Timeline::pending`. const SIGNAL_BATCH: usize = 8; @@ -192,11 +369,23 @@ impl Timeline { /// Creates the fence of the next accepted job. Fences are created in submission order: the /// caller holds the queue (SUBMIT is serialized per queue). - pub(crate) fn next(self: &Arc) -> Result { + pub(crate) fn next(self: &Arc, origin: Arc) -> Result { // SUBMIT already holds the logical queue, so allocating the next sequence before // taking pending preserves creation order. Fence completion needs pending too: // never enter reclaim while holding that mutex. - let fence: UserFence = self.jobs.new_fence(0, JobFenceOps)?.into(); + let fence: UserFence = self.jobs.new_fence(0, JobFenceOps { origin })?.into(); + // SAFETY: `fence` is a live `UserFence` whose `dma_fence::ops` is static. + let ops = unsafe { (*fence.raw()).ops as usize }; + let previous = JOB_FENCE_OPS.load(Ordering::Acquire); + if previous == 0 { + match JOB_FENCE_OPS.compare_exchange(0, ops, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => {} + Err(existing) if existing == ops => {} + Err(_) => return Err(EIO), + } + } else if previous != ops { + return Err(EIO); + } let mut pending = self.pending.lock(); pending.reserve(1, GFP_NOWAIT)?; pending @@ -276,7 +465,7 @@ impl Timeline { /// A fence on `contexts` signalled with `error`. Every fence of an error context signals at /// creation, so the context's fences signal in order. fn error_fence(contexts: &FenceContexts, error: Error) -> Result { - let fence = contexts.new_fence(0, JobFenceOps)?; + let fence = contexts.new_fence(0, RefusedFenceOps)?; fence.set_error(error); fence.signal(); Ok(Fence::from_fence(&fence)) diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 6547895cceef8c..c52f60a11e2b8b 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -45,7 +45,7 @@ use kernel::{ use super::{ command::{Command, Commands, Order, Orders}, - fence::{InputFences, JobFence}, + fence::{FenceOrigin, FwWaits, InputFences, JobFence}, hw, queue::QueueState, vm::VmState, @@ -107,6 +107,10 @@ pub(crate) struct Job { pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. inputs: InputFences, + /// Exported fence identity for same-GPU, same-VM cross-queue firmware handoff. + pub(crate) origin: Arc, + /// Same-GPU, same-VM cross-queue waits resolved into firmware ring barriers. + pub(crate) fw_waits: FwWaits, /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render /// commands within one job may retire in either hardware completion order. @@ -141,6 +145,8 @@ impl Job { fence: JobFence, guard: mmu::VmJobGuard, inputs: InputFences, + origin: Arc, + fw_waits: FwWaits, ) -> Result> { if commands.len() != orders.len() { return Err(EINVAL); @@ -161,6 +167,8 @@ impl Job { fence, progress, inputs, + origin, + fw_waits, full_retired: AtomicU64::new(0), terminal_retired: AtomicBool::new(false), // Scheduler free can race the final off-lock completion reference. @@ -178,6 +186,7 @@ impl Job { /// Latches a hardware/publication failure before any later work can be published. /// Called under the device lock; it deliberately does not signal the fence. pub(crate) fn latch_failure(&self, error: Error) { + self.origin.mark_failed(); if error == ECANCELED || (self.terminal_retired.load(Ordering::Acquire) && error != EIO @@ -217,6 +226,7 @@ impl Job { return; } if let Err(error) = result { + self.origin.mark_failed(); if error == ECANCELED || ((!engine || self.terminal_retired.load(Ordering::Acquire)) && error != EIO @@ -321,7 +331,10 @@ impl Job { /// Whether command `index` is a ready, barrier-free compute command continuing a compute /// horizon at queue-local compute ordinal `expected`. pub(crate) fn can_fold_horizon_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Compute(_)) = self.commands.get(index as usize) else { @@ -342,6 +355,7 @@ impl Job { pub(crate) fn can_fold_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -374,7 +388,10 @@ impl Job { /// at queue-local render ordinal `expected` (treating `expected - 1` as already published /// within the in-progress render flight). pub(crate) fn can_fold_render_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Render(_)) = self.commands.get(index as usize) else { @@ -411,6 +428,7 @@ impl Job { pub(crate) fn can_fold_render_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -471,6 +489,19 @@ impl Job { let order = self.orders.get(index as usize).ok_or(EINVAL)?; self.queue.check(order)?; super::fence::check_dependencies(&self.inputs)?; + for wait in self.fw_waits.iter() { + if wait.is_failed() { + return Err(ECANCELED); + } + for engine in 0..2 { + if let Some(seq) = wait.last_ordinal[engine] { + wait.queue.cancelled_through(engine, seq)?; + if wait.queue.published[engine].load(Ordering::Acquire) < seq { + return Err(EAGAIN); + } + } + } + } let completed = self .queue .completed @@ -599,6 +630,11 @@ impl Job { Ok(()) } + /// Whether this job holds a cross-queue firmware wait on `queue`. + pub(crate) fn waits_on_queue(&self, queue: &Arc) -> bool { + self.fw_waits.iter().any(|w| Arc::ptr_eq(&w.queue, queue)) + } + /// Cancels a job the scheduler never ran (queue teardown, or a failed submission). fn cancel_unstarted(&self) { if self.started.swap(true, Ordering::AcqRel) { @@ -608,6 +644,7 @@ impl Job { self.finish(Err(ECANCELED), false); } else if !self.progress.signaled.swap(true, Ordering::AcqRel) { // A refused submission's job: its fence orders nothing and was never published. + self.origin.mark_failed(); self.fence.signal(Err(ECANCELED)); } } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index cdc0359c33a0c9..103423bee36260 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1539,11 +1539,34 @@ impl Firmware { 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. + // Later commands of this queue, and any cross-queue flights transitively waiting + // on it via firmware handoff, fail with it so no dependent command reports success + // after an upstream failure. + let mut changed = false; for later in self.engine.flights.iter_mut() { - if Arc::ptr_eq(&later.job.queue, &job.queue) { + if !later.doomed + && (Arc::ptr_eq(&later.job.queue, &job.queue) + || later.job.waits_on_queue(&job.queue)) + { later.doomed = true; + changed = true; + } + } + while changed { + changed = false; + for i in 0..self.engine.flights.len() { + if self.engine.flights[i].doomed { + continue; + } + let dep_doomed = self.engine.flights.iter().any(|other| { + other.doomed + && (Arc::ptr_eq(&other.job.queue, &self.engine.flights[i].job.queue) + || self.engine.flights[i].job.waits_on_queue(&other.job.queue)) + }); + if dep_doomed { + self.engine.flights[i].doomed = true; + changed = true; + } } } } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 4dc9d7d2f837c5..bc4423839f133f 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -101,6 +101,15 @@ impl QueueState { Ok(()) } + /// Whether any accepted ordinal of `engine` at or before `seq` was cancelled. + pub(crate) fn cancelled_through(&self, engine: usize, seq: u64) -> Result { + let first = self.cancelled_at[engine].load(Ordering::Acquire); + if first != 0 && first <= seq { + return Err(ECANCELED); + } + Ok(()) + } + /// Whether compute ordinal `seq` already has a full successful firmware receipt, either /// at or below the contiguous `completed[COMPUTE]` frontier or recorded in `compute_ooo`. pub(crate) fn is_compute_retired(&self, seq: u64) -> bool { @@ -264,7 +273,22 @@ impl Queue { .as_ref() .ok_or(EIO)? .prepare(&self.vm, &submission.commands, hints)?; - let fence = self.timeline.next()?; + let gpu_id = Arc::as_ptr(&self.shared) as usize; + let last_ordinal = [ + (submission.counts[command::RENDER] != 0) + .then_some(self.accepted[command::RENDER] + submission.counts[command::RENDER]), + (submission.counts[command::COMPUTE] != 0) + .then_some(self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]), + ]; + let origin = Arc::new( + super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), + GFP_KERNEL, + )?; + let (inputs, fw_waits) = match super::fence::resolve_fw_waits(&inputs, gpu_id, self.vm.id) { + Some(waits) => (InputFences::new(), waits), + None => (inputs, super::fence::FwWaits::Empty), + }; + let fence = self.timeline.next(origin.clone())?; let job = Job::new( id, self.state.clone(), @@ -275,6 +299,8 @@ impl Queue { fence, guard, inputs, + origin, + fw_waits, )?; let published = job.fence.fence(); // Publish output syncs (including fallible cumulative scope allocation) before pushing diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5c..6ab44208a4f847 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -34,7 +34,7 @@ mod completion; pub(crate) mod context; mod data_segment; mod dependency; -mod sync_input; +pub(crate) mod sync_input; pub(crate) mod exec_share; pub(crate) mod sync_output; mod trace; diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f214..356fca680b23c2 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -6,9 +6,9 @@ use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] -pub(super) struct Leaf { - pub(super) fence: *mut bindings::dma_fence, - pub(super) status: i32, +pub(crate) struct Leaf { + pub(crate) fence: *mut bindings::dma_fence, + pub(crate) status: i32, } unsafe extern "C" { @@ -43,7 +43,7 @@ impl Drop for Leaf { } /// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(super) fn collect(input: &Fence) -> Option> { +pub(crate) fn collect(input: &Fence) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; 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 6cbe422995dffb..fe6818252cc83d 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 @@ -32,8 +32,8 @@ def function_from(text, marker_text): def function(text, name): return function_from(text, 'fn ' + name + '(') -queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'is_compute_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']) +queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'cancelled_through', 'is_compute_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', 'waits_on_queue']) push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' @@ -102,7 +102,13 @@ def function(text, name): mod command { pub(crate) use super::{Order, COMPUTE}; } struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2],compute_ooo:AtomicU64 } 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:AtomicU64,terminal_retired:AtomicBool } +struct FenceOrigin { queue:Arc, last_ordinal:[Option;2], failed:AtomicBool } +impl FenceOrigin { + fn new(queue:Arc, last_ordinal:[Option;2])->Arc { Arc::new(Self{queue,last_ordinal,failed:AtomicBool::new(false)}) } + fn mark_failed(&self) { self.failed.store(true,Ordering::Release); } + fn is_failed(&self)->bool { self.failed.load(Ordering::Acquire) } +} +struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,origin:Arc,fw_waits:Vec>,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { @@ -183,9 +189,10 @@ def function(text, name): 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],compute_ooo:AtomicU64::new(0)})) } fn job_with_orders(id:u64,status:Arc,inputs:Vec,orders:Vec,queue:Arc)->Arc { + let origin=FenceOrigin::new(queue.clone(),[None,Some(orders.len() as u64)]); Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)},started:AtomicBool::new(false),accepted:AtomicBool::new(true), - fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,orders,queue, + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,origin,fw_waits:vec![],orders,queue, full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false)}) } #[test] @@ -581,6 +588,56 @@ def function(text, name): assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),4); assert_eq!(queue.compute_ooo.load(Ordering::Acquire),0); } +#[test] +fn fw_wait_defers_until_producer_queue_publishes_and_propagates_failure() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders,q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2.clone(), + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert!(cons.waits_on_queue(&q1)); + assert!(!cons.waits_on_queue(&q2)); + // Producer not yet published -> consumer defers with EAGAIN. + assert_eq!(cons.check_command_dependencies(0),Err(EAGAIN)); + // Once producer publishes ordinal 1, consumer is ready for firmware handoff. + q1.published[COMPUTE].store(1,Ordering::Release); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + // Producer failure marks origin failed and cancels consumer with ECANCELED. + prod.latch_failure(ECANCELED); + assert!(prod.origin.is_failed()); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} +#[test] +fn fw_wait_cancels_when_producer_queue_cancels_ordinal() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(1)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders.clone(),q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2, + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + q1.cancel(&p_orders,0); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} '''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: @@ -592,6 +649,6 @@ def function(text, name): (OUT/'job-failure-host.log').write_text(result.stdout+result.stderr) (OUT/'job-failure-host.json').write_text(json.dumps({ 'source':str(SOURCE),'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result':'pass','test_groups':23, + 'result':'pass','test_groups':25, 'limitations':'Production Job methods with host VM/fence mocks; actual DRM scheduler and firmware publication gates require kernel and execution integration validation.' },indent=2)+'\n') 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 e01576c044d1ad..f15af074a62211 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -698,8 +698,15 @@ def item(declaration): } } +mod fence { + pub const MAX_FW_WAITS: usize = 8; + pub struct FwWait { + pub queue: std::sync::Arc, + pub last_ordinal: [Option; 2], + } +} #[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} -struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources,fw_waits:Vec} impl QueueBehindJob{ fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn command_order(&self,index:u32)->Option{ @@ -788,7 +795,7 @@ def item(declaration): 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{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let j1=mk(1,vm1.clone(),q1.clone(),false); let j2=mk(2,vm1.clone(),q1.clone(),false); @@ -833,7 +840,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access})], order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let timed=mk(1,q1.clone(),true,None,None); let query_copy=mk(2,q1.clone(),true,None,Some(1)); @@ -856,7 +863,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), @@ -876,7 +883,7 @@ def item(declaration): 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{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,vm1.clone(),true); let r2=mk(2,vm1.clone(),true); @@ -921,7 +928,7 @@ def item(declaration): 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:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let vm1_r=mk(1,vm1.clone(),q1.clone(),true); let vm1_c=mk(2,vm1.clone(),q1.clone(),false); @@ -963,7 +970,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,q1.clone(),true,1,[None,None]); let c1=mk(2,q1.clone(),false,1,[Some(1),None]); @@ -1000,7 +1007,7 @@ def item(declaration): Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, Order{engine:command::COMPUTE,sequence:3,wait_through:[None,None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_wait_c2=mk(7,q1.clone(),true,3,[None,Some(2)]); let r_wait_c3=mk(8,q1.clone(),true,4,[None,Some(3)]); @@ -1035,7 +1042,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_initbm=mk(1,true,1,[None,None]); let c_after_r=mk(2,false,1,[Some(1),None]); @@ -1077,14 +1084,14 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), @@ -1114,7 +1121,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,false,1,[None,None]); let c2=mk(2,false,2,[None,None]); @@ -1153,14 +1160,14 @@ def item(declaration): Order{engine:command::RENDER,sequence:2,wait_through:[Some(1),None]}, Order{engine:command::RENDER,sequence:3,wait_through:[Some(2),None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let next_r=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut r_fs=[0u32;16]; r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; @@ -1192,14 +1199,14 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_fold_b=Arc::new(QueueBehindJob{ id:11,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; @@ -1226,7 +1233,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_live=mk(1); let next_r=mk(2); @@ -1272,7 +1279,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, - extra_orders:vec![],dependency:dep,resources:Resources, + extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); @@ -1616,7 +1623,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,vm1.clone(),q1.clone(),1); let c2=mk(2,vm1.clone(),q1.clone(),2); @@ -1661,7 +1668,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,1,None); let c2=mk(2,2,None); @@ -1712,6 +1719,73 @@ def item(declaration): q1.compute_ooo.store(0, Ordering::Release); assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None, None])); } + #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Queue::new(0,2); + let q2=Queue::new(0,2); + let c1=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c2_wait_q1=Arc::new(QueueBehindJob{ + id:3,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[Some(1),Some(1)]}], + }); + let c2_query_wait_q1=Arc::new(QueueBehindJob{ + id:4,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:true})], + order:Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[None,Some(1)]}], + }); + let host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + QueueBehindFlight{ + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, + }, + QueueBehindFlight{ + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + 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,block_pipeline_vm:None}, + }; + // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). + let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); + assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); + assert_eq!(host.choose_compute_pipe(cw,24),0); + // Cross-queue render wait resolves q1's FS stamp 0x200. + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; + // non-query compute queues directly behind q1 in firmware. + assert!(!host.can_queue_behind(&c2_query_wait_q1)); + assert!(host.can_queue_behind(&c2_wait_q1)); + // Once q1 retires, fw_waits resolves to no barriers. + q1.completed[command::COMPUTE].store(1,Ordering::Release); + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None,None])); + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(None)); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -1844,6 +1918,7 @@ def item(declaration): commands: Vec, orders: Vec, inputs: Vec, + fw_waits: Vec<()>, terminal_retired: AtomicBool, } impl Job { @@ -1865,6 +1940,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let ok_job = mk( @@ -1925,6 +2001,15 @@ def item(declaration): 2, ); assert!(!cancelled.can_fold_horizon_job(2)); + let mut with_fw_wait = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 0, + ); + with_fw_wait.fw_waits.push(()); + assert!(!with_fw_wait.can_fold_horizon_cmd(0, 2)); + assert!(!with_fw_wait.can_fold_horizon_job(2)); } #[test] @@ -1940,6 +2025,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let multi = mk( @@ -1986,6 +2072,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; // Two-pass render job waiting on primary flight pass 1 and its own pass 2. @@ -2417,7 +2504,7 @@ def item(declaration): '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::fence::", "crate::fence::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' From 0cdc039f6c99196b04705377b0642316808e0210 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 18:17:28 -0500 Subject: [PATCH 0875/1514] drm/asahi: g16: tighten completion wakeup and housekeeping cadence Eliminate avoidable completion wakeup delays and hot-path lock churn on short G16 compute and render bursts: - When submit_locked() consumes an EP 0x20 event before the oldest flight's wire receipt settles (and the event is not a TA-only 0x70 stage tick), restore evented, arm a short repoll instead of resnap_us, and kick poll_now() so trailing completions do not stall onto 100 us. - Recheck Shared::evented in run_poll() after signalling completed fences (bounded by MAX_EVENT_RECHECKS = 8) so back-to-back completions during fence signalling retire immediately without an extra workqueue wakeup. - Raise the active-burst housekeeping cadence from 1 ms to 5 ms (aligned with power::policy::SAMPLE_NS and well below the 100 ms minimum hang deadline) and defer housekeeping off the hot poll_step() lock while flights remain active. - Relax healthy idle hrtimer transitions via idle_resnap() to keep short (<= resnap_us) already-armed timers intact across sub-100 us d=1 inter-job gaps, while keeping cancel_resnap() unconditional for system sleep and fail-stop paths. Lower the default g16_repoll_us from 15 us to 8 us and decay ewma_flight_us faster downward on burst transitions. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/g16/mod.rs | 4 + drivers/gpu/drm/asahi/g16/poll.rs | 79 +++++++++-- .../drivers/gpu/asahi-m4/test-poll-retire.py | 131 +++++++++++++++++- 4 files changed, 202 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b9706916510321..e4790bb50a0055 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -262,7 +262,7 @@ module! { description: "G16: compute completion-stamp deadline, ms (0 permits unbounded compute; firmware recovery stays active)", }, g16_repoll_us: u32 { - default: 15, + default: 8, description: "G16: repoll interval while publication waits for record consumption, us", }, g16_resnap_us: u32 { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2065837eaf959f..670a85634528af 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -417,10 +417,14 @@ impl Shared { } /// Updates the lock-free EWMA of recent retired flight durations (microseconds). + /// Decays faster downward than upward so transitions from heavy flights into short + /// bursts tighten the adaptive repoll window within a few completions. pub(crate) fn note_flight_us(&self, us: u32) { let prev = self.ewma_flight_us.load(Ordering::Relaxed); let next = if prev == 0 { us + } else if us < prev { + prev.saturating_add(us) / 2 } else { (prev.saturating_mul(3).saturating_add(us)) / 4 }; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index ba67ff8354388a..b651f331d350c6 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -12,7 +12,7 @@ //! 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 +//! published, or `g16_repoll_us` (8) 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; @@ -41,12 +41,18 @@ use super::regs::EngineState; use super::{params, Firmware, Shared, FAST_POLL_WORK, POLL_WORK, SCRUB_WORK, UNBOUND_POLL_WORK}; use crate::module_parameters; -/// Cadence of periodic housekeeping (power governor, window health, administrative hang check). +/// Cadence of periodic housekeeping when idle or entering recovery (1 ms). const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Cadence of periodic housekeeping while flights are active (5 ms, aligned with +/// `power::policy::SAMPLE_NS` and far below the 100 ms minimum hang deadline). +const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000; /// Minimum interval between auxiliary log/ktrace/stats ring drains while flights are active. const AUX_DRAIN_NS: u64 = 10_000_000; /// Maximum trailing receipt polls after an EP 0x20 event (stepped 1/2/3/4/5 us, 45 us total). const EVENT_RETIRE_POLLS: u32 = 11; +/// Maximum consecutive in-place EP 0x20 rechecks in `run_poll()` before yielding back to +/// the workqueue so short bursts avoid extra worker round-trips without starving housekeeping. +const MAX_EVENT_RECHECKS: u32 = 8; /// Minimum interval between 1-jiffy delayed-work safety backup rearms (2 ms). const BACKUP_REARM_NS: u64 = 2_000_000; @@ -105,6 +111,7 @@ impl Shared { let mut tail = 0u32; let mut housekeeping_deferred = false; let mut step = 0u32; + let mut rechecks = 0u32; loop { if self.sleeping.load(Ordering::Acquire) { @@ -113,6 +120,7 @@ impl Shared { let mut done = Completions::new(); let mut scrubs = super::slots::ScrubBatch::new(); let mut retry_tail = false; + let mut poll_ok = true; if let Some(firmware) = self.state.lock().as_deref_mut() { if self.sleeping.load(Ordering::Acquire) { return; @@ -139,9 +147,14 @@ impl Shared { // floor hold is still pending so both expire cleanly to idle power. Ok(false) => { self.arm_idle_power_poll(firmware); - self.cancel_resnap(); + if firmware.recovery.failed().is_some() { + self.cancel_resnap(); + } else { + self.idle_resnap(); + } } Err(error) => { + poll_ok = false; self.cancel_resnap(); firmware.fail_stop(error, &mut done); self.fail_stop(error); @@ -157,6 +170,20 @@ impl Shared { self.enqueue_scrubs(scrubs); self.queue_feed(); if !retry_tail { + if poll_ok + && !self.sleeping.load(Ordering::Acquire) + && !self.crashed.load(Ordering::Acquire) + && self.evented.load(Ordering::Acquire) + { + if rechecks < MAX_EVENT_RECHECKS { + rechecks += 1; + step = 0; + evented = false; + tail = 0; + continue; + } + self.poll_now(); + } break; } let delay_us = match step { @@ -205,12 +232,18 @@ impl Shared { let accepted = firmware.enqueue(job); if accepted.is_ok() && !self.sleeping.load(Ordering::Acquire) { let now = now_ns(); - let housekeeping_due = - now.wrapping_sub(firmware.last_housekeeping_ns) >= HOUSEKEEPING_NS; let had_flights = !firmware.engine.flights.is_empty(); + let housekeeping_interval = if had_flights { + ACTIVE_HOUSEKEEPING_NS + } else { + HOUSEKEEPING_NS + }; + let housekeeping_due = + now.wrapping_sub(firmware.last_housekeeping_ns) >= housekeeping_interval; let was_evented = had_flights && self.evented.swap(false, Ordering::AcqRel); let recovery_pending = firmware.recovery_pending().unwrap_or(true); let mut retired_any = false; + let mut restored_event = false; let mut pub_res = Ok(()); if had_flights && (was_evented || recovery_pending || firmware.oldest_stamp_reached()) @@ -232,6 +265,7 @@ impl Shared { && !recovery_pending; if !non_terminal_only { self.evented.store(true, Ordering::Release); + restored_event = true; } } Ok(()) @@ -261,16 +295,20 @@ impl Shared { } if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { // If an EP 0x20 event retired an older flight while later flights remain active, - // arm a short repoll in case another completion coalesced into that interrupt. + // or arrived before the oldest receipt became visible, arm a short repoll so + // trailing completions never fall back to `resnap_us`. self.rearm( firmware.engine.chan_wait + || restored_event || (was_evented && retired_any && !firmware.engine.flights.is_empty()), ); } else { firmware.power.report_work(false); self.arm_idle_power_poll(firmware); } - if housekeeping_due && !recovery_pending && pub_res.is_ok() { + if pub_res.is_ok() + && (restored_event || (housekeeping_due && !recovery_pending)) + { self.poll_now(); } } @@ -427,6 +465,23 @@ impl Shared { drop(handle.take()); } + /// Relaxes the completion hrtimer on healthy idle transitions without cancelling a + /// short (`<= resnap_us`) already-armed timer so back-to-back `d=1` bursts avoid + /// per-job cancel/restart mutex and hrtimer-rbtree churn. System sleep and fail-stop + /// paths still call [`Self::cancel_resnap`] unconditionally. + pub(crate) fn idle_resnap(&self) { + let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); + if armed_ns == 0 { + return; + } + let now = now_ns(); + let keep_ns = u64::from(params::resnap_us()).saturating_mul(1000); + if armed_ns > now && armed_ns.saturating_sub(now) <= keep_ns { + return; + } + self.cancel_resnap(); + } + /// 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) { @@ -544,8 +599,14 @@ impl Firmware { self.engine.short_repoll = false; self.session.transport()?; let now = now_ns(); - let housekeeping_due = now.wrapping_sub(self.last_housekeeping_ns) >= HOUSEKEEPING_NS; let had_flights = !self.engine.flights.is_empty(); + let housekeeping_interval = if had_flights { + ACTIVE_HOUSEKEEPING_NS + } else { + HOUSEKEEPING_NS + }; + let housekeeping_due = + now.wrapping_sub(self.last_housekeeping_ns) >= housekeeping_interval; 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 @@ -645,7 +706,7 @@ impl Firmware { return Ok(true); } if !ran_housekeeping && housekeeping_due { - if !done.is_empty() { + if !done.is_empty() || !self.engine.flights.is_empty() { *housekeeping_deferred = true; } else { self.run_housekeeping(done)?; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index b9fbd6a0e67bd2..b7e6acb29bae64 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -10,10 +10,16 @@ event_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/event.rs').read_text() mod_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() sleep_source = (kernel_root() / 'drivers/gpu/drm/asahi/g16/sleep.rs').read_text() +core_source = (kernel_root() / 'drivers/gpu/drm/asahi/asahi_core.rs').read_text() source = production.read_text() output = output_dir() assert 'const EVENT_RETIRE_POLLS: u32 = 11;' in source, 'EVENT_RETIRE_POLLS expected to be 11' +assert 'const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000;' in source, 'ACTIVE_HOUSEKEEPING_NS expected to be 5 ms' +assert 'const MAX_EVENT_RECHECKS: u32 = 8;' in source, 'MAX_EVENT_RECHECKS expected to be 8' +assert 'rechecks < MAX_EVENT_RECHECKS' in source, 'run_poll must loop-recheck evented completions' +assert 'self.idle_resnap();' in source, 'run_poll idle paths must use idle_resnap()' +assert 'g16_repoll_us: u32 {\n default: 8,' in core_source, 'g16_repoll_us default expected to be 8' assert ( 'OwnedQueue::new_percpu_reclaim(c_str!("aurora_g16_events"), true)' in mod_source ), 'aurora_g16_events must use new_percpu_reclaim(..., true)' @@ -29,6 +35,9 @@ assert ( 'self.events_unbound.drain();' in sleep_source ), 'sleep.rs must drain events_unbound on suspend' +assert ( + 'self.cancel_resnap();' in sleep_source +), 'sleep.rs must still call unconditional cancel_resnap()' def item(declaration, text=source): @@ -51,6 +60,7 @@ def item(declaration, text=source): type Result = std::result::Result; const HOUSEKEEPING_NS: u64 = 1_000_000; +const ACTIVE_HOUSEKEEPING_NS: u64 = 5_000_000; const AUX_DRAIN_NS: u64 = 10_000_000; const EVENT_RETIRE_POLLS: u32 = 11; mod hw { @@ -445,12 +455,35 @@ def item(declaration, text=source): .unwrap(); assert_eq!(fw.retire_calls, 1); assert!(shared.evented.load(Ordering::Acquire)); + assert_eq!(shared.rearm_soon.get(), 1); + assert_eq!(shared.poll_now_calls.get(), 1); + + // TA-only non-terminal event must NOT restore evented, arm short repoll, or kick poll_now. + let shared_ta = Shared::new(); + shared_ta.evented.store(true, Ordering::Release); + let mut fw_ta = Firmware::new(); + fw_ta.engine.flights.push(Flight { + computes: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw_ta.engine.fs_target = 0x100; + fw_ta.drain_stage_delta = 1; + fw_ta.drain_fs_delta = 0; + shared_ta + .submit_locked(&mut fw_ta, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert!(!shared_ta.evented.load(Ordering::Acquire)); + assert_eq!(shared_ta.rearm_soon.get(), 0); + assert_eq!(shared_ta.poll_now_calls.get(), 0); } #[test] fn submit_locked_defers_housekeeping_and_arms_short_repoll_on_coalesced_event() { - // Housekeeping due (> 1 ms): submit_locked must NOT run synchronous publish(); it - // calls publish_checked() and kicks poll_now() so housekeeping runs off SUBMIT. + // Active bursts hold housekeeping at ACTIVE_HOUSEKEEPING_NS (5 ms): at 4 ms (< 5 ms), + // submit_locked skips poll_now(); at 5 ms, it calls publish_checked() and kicks poll_now() + // so housekeeping runs off SUBMIT. CLOCK.with(|c| c.set(5_000_000)); let shared = Shared::new(); let mut fw = Firmware::new(); @@ -476,6 +509,16 @@ def item(declaration, text=source): assert_eq!(fw.publish_full_calls, 0); assert_eq!(fw.publish_checked_calls, 1); assert_eq!(fw.retire_calls, 0); + assert_eq!(shared.poll_now_calls.get(), 0); + assert_eq!(shared.rearm_soon.get(), 0); + + // At 5 ms (>= ACTIVE_HOUSEKEEPING_NS), submit_locked defers housekeeping via poll_now(). + CLOCK.with(|c| c.set(6_000_000)); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 4 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_full_calls, 0); + assert_eq!(fw.publish_checked_calls, 2); assert_eq!(shared.poll_now_calls.get(), 1); assert_eq!(shared.rearm_soon.get(), 0); @@ -483,13 +526,45 @@ def item(declaration, text=source): shared.evented.store(true, Ordering::Release); fw.retire_on_call = true; shared - .submit_locked(&mut fw, Arc::new(Job { id: 4 }), &mut done) + .submit_locked(&mut fw, Arc::new(Job { id: 5 }), &mut done) .unwrap(); assert_eq!(fw.retire_calls, 1); assert_eq!(fw.engine.flights.len(), 1); assert_eq!(shared.rearm_soon.get(), 1); } +#[test] +fn poll_step_defers_active_housekeeping_until_five_ms_and_off_hot_lock() { + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 1_000_000; + fw.engine.flights.push(Flight { + computes: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw.engine.target = 0x100; + let mut retry_tail = false; + let mut deferred = false; + let mut done = vec![]; + + // At 4 ms (< 5 ms) while busy: housekeeping neither runs inline nor defers. + CLOCK.with(|c| c.set(5_000_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!deferred); + assert_eq!(fw.last_housekeeping_ns, 1_000_000); + + // At 5 ms (>= 5 ms) while busy: defers off the hot poll_step lock instead of running inline. + CLOCK.with(|c| c.set(6_000_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(deferred); + assert_eq!(fw.last_housekeeping_ns, 1_000_000); +} + #[test] fn run_housekeeping_throttles_auxiliary_ring_drain_while_flights_active() { CLOCK.with(|c| c.set(1_000_000)); @@ -1107,8 +1182,54 @@ def item(declaration, text=source): } __CANCEL_RESNAP__ + __IDLE_RESNAP__ __REARM_US__ __REARM__ + __NOTE_FLIGHT_US__ + } + + #[test] + fn idle_resnap_avoids_churn_for_short_armed_timer_while_cancelling_long_or_stale() { + CLOCK.store(100_000, Ordering::Release); + let shared = Shared::new(); + // Unarmed idle: no-op without dropping anything. + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Short armed timer (<= resnap_us = 100 us): preserved across brief d=1 idle gap. + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + CLOCK.store(120_000, Ordering::Release); + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + assert!(shared.resnap_handle.lock().is_some()); + + // Next submission arriving within window reuses the armed timer without restart. + shared.rearm(false); + assert_eq!(shared.starts.load(Ordering::Acquire), 1); + assert_eq!(shared.drops.load(Ordering::Acquire), 0); + + // Overdue or > resnap_us timer falls back to unconditional cancel_resnap(). + CLOCK.store(200_000, Ordering::Release); + shared.idle_resnap(); + assert_eq!(shared.drops.load(Ordering::Acquire), 1); + assert!(shared.resnap_handle.lock().is_none()); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); + } + + #[test] + fn note_flight_us_decays_rapidly_downward_for_burst_transitions() { + let shared = Shared::new(); + shared.note_flight_us(260); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 260); + // Three 20 us flights decay rapidly below 2 * resnap_us (200 -> 140 -> 80 -> 50). + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 140); + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 80); + shared.note_flight_us(20); + assert_eq!(shared.ewma_flight_us.load(Ordering::Relaxed), 50); + assert_eq!(shared.rearm_us(false), 25); } #[test] @@ -1310,11 +1431,13 @@ def item(declaration, text=source): '__TA_WAVE_READY__': 'fn ta_wave_ready(', '__OLDEST_STAMP_REACHED__': 'fn oldest_stamp_reached(', '__CANCEL_RESNAP__': 'pub(crate) fn cancel_resnap(', + '__IDLE_RESNAP__': 'pub(crate) fn idle_resnap(', '__REARM_US__': 'pub(crate) fn rearm_us(', '__REARM__': 'pub(crate) fn rearm(', '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): harness = harness.replace(token, item(decl).replace('super::hw::', 'hw::')) +harness = harness.replace('__NOTE_FLIGHT_US__', item('pub(crate) fn note_flight_us(', mod_source)) for token, decl in { '__EVENT_DRAIN__': 'pub(crate) fn drain(', '__EVENT_DRAIN_STATS__': 'pub(crate) fn drain_statistics(', @@ -1338,7 +1461,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 18, + 'tests': 21, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', From 4ec367549fb63835d0872689ea7293c8f3ffda32 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:52:40 -0500 Subject: [PATCH 0876/1514] drm/asahi: g16: coalesce timeline fence chains per queue for fw barriers Timeline semaphores on G16 attach each submitted JobFence into a dma_fence_chain across participating queues. Previously, two issues forced alternating cross-queue timeline ping-pongs permanently onto drm_sched after the first few hops: 1. asahi_g17_collect_fences() emitted every leaf in the chain without skipping signalled leaves or coalescing same-context leaves, hitting -ENOSPC once chain depth grew past the buffer capacity. 2. FwWaits::push_unique() deduplicated only identical FenceOrigin allocations instead of coalescing per logical queue, overflowing MAX_FW_WAITS (8) by hop 9 and cascading every subsequent hop onto drm_sched because the bounced producer stayed !is_enqueued(). Add asahi_g17_collect_fences_coalesced() (skipping already-signalled non-error leaves and keeping only the latest unsignalled leaf per dma_fence context while preserving every status < 0 error leaf), record cumulative accepted render/compute ordinals in FenceOrigin::last_ordinal so coalescing to a queue's newest fence retains earlier unretired work on both engines, coalesce FwWaits per logical queue, and check that a cross-queue render wait is still unretired before clearing fragment barriers. Add host unit tests covering 256-hop 2-queue timeline chain coalescing, error leaf preservation, and per-queue FwWaits ordinal merging. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 9 +- drivers/gpu/drm/asahi/g16/fence.rs | 70 +++- drivers/gpu/drm/asahi/g16/queue.rs | 11 +- drivers/gpu/drm/asahi/g17/sync_input.c | 62 +++- drivers/gpu/drm/asahi/g17/sync_input.h | 3 + drivers/gpu/drm/asahi/g17/sync_input.rs | 27 +- .../gpu/asahi-m4/test-fence-signalling.py | 331 +++++++++++++++++- 7 files changed, 478 insertions(+), 35 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 8e098a6e0eed07..773207879b5e90 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -3010,10 +3010,11 @@ impl Firmware { .find(|fl| fl.renders != 0) .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); let plan_flags = if !staged - && job - .fw_waits - .iter() - .any(|w| w.last_ordinal[super::command::RENDER].is_some()) + && job.fw_waits.iter().any(|w| { + w.last_ordinal[super::command::RENDER].is_some_and(|last| { + w.queue.completed[super::command::RENDER].load(Ordering::Acquire) < last + }) + }) { cmd.cmd.flags & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 1e90a148b3d0b0..75ca2b6768c81d 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -172,42 +172,90 @@ impl FenceOrigin { } } -/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 entries, bounded to -/// [`MAX_FW_WAITS`]). +/// One per-queue cross-queue firmware barrier target, coalescing multiple fences from the same +/// logical queue (e.g. from a timeline semaphore chain or repeated input syncs) to the highest +/// required render and compute ordinals on that queue. +pub(crate) struct FwWait { + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + origin: Arc, +} + +impl FwWait { + pub(crate) fn is_failed(&self) -> bool { + self.origin.is_failed() + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 queues, bounded to +/// [`MAX_FW_WAITS`] distinct logical queues). pub(crate) enum FwWaits { Empty, - One([Arc; 1]), - Heap(KVec>), + One([FwWait; 1]), + Heap(KVec), } impl FwWaits { fn push_unique(&mut self, origin: Arc) -> Result { - if self.iter().any(|existing| Arc::ptr_eq(existing, &origin)) { + let existing = match self { + Self::Empty => None, + Self::One(items) => items + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + Self::Heap(vec) => vec + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + }; + if let Some(wait) = existing { + let mut newer = false; + for engine in 0..2 { + if let Some(seq) = origin.last_ordinal[engine] { + match wait.last_ordinal[engine] { + Some(cur) if seq > cur => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + None => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + _ => {} + } + } + } + if newer { + wait.origin = origin; + } return Ok(()); } if self.len() >= MAX_FW_WAITS { return Err(E2BIG); } + let wait = FwWait { + queue: origin.queue.clone(), + last_ordinal: origin.last_ordinal, + origin, + }; match self { - Self::Empty => *self = Self::One([origin]), + Self::Empty => *self = Self::One([wait]), Self::One(_) => { let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; if let Self::One([first]) = core::mem::replace(self, Self::Empty) { let _ = vec.push_within_capacity(first); - let _ = vec.push_within_capacity(origin); + let _ = vec.push_within_capacity(wait); } *self = Self::Heap(vec); } - Self::Heap(vec) => vec.push(origin, GFP_KERNEL)?, + Self::Heap(vec) => vec.push(wait, GFP_KERNEL)?, } Ok(()) } } impl core::ops::Deref for FwWaits { - type Target = [Arc]; + type Target = [FwWait]; - fn deref(&self) -> &[Arc] { + fn deref(&self) -> &[FwWait] { match self { Self::Empty => &[], Self::One(items) => items, @@ -287,7 +335,7 @@ pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> O if status > 0 { continue; } - let leaves = crate::g17::sync_input::collect(input)?; + let leaves = crate::g17::sync_input::collect_coalesced(input)?; for leaf in leaves.iter() { if leaf.status < 0 { return None; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index bc4423839f133f..27130582a881bf 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -274,11 +274,14 @@ impl Queue { .ok_or(EIO)? .prepare(&self.vm, &submission.commands, hints)?; let gpu_id = Arc::as_ptr(&self.shared) as usize; + // Record cumulative queue ordinals across both engines so coalescing multiple + // same-queue fences in a timeline semaphore chain to the latest fence preserves + // any earlier unretired render or compute command on that queue. + let total_render = self.accepted[command::RENDER] + submission.counts[command::RENDER]; + let total_compute = self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]; let last_ordinal = [ - (submission.counts[command::RENDER] != 0) - .then_some(self.accepted[command::RENDER] + submission.counts[command::RENDER]), - (submission.counts[command::COMPUTE] != 0) - .then_some(self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]), + (total_render != 0).then_some(total_render), + (total_compute != 0).then_some(total_compute), ]; let origin = Arc::new( super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c87965..6c68414b49fd4d 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -8,19 +8,43 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, - size_t *count) + size_t *count, bool coalesce_contexts) { + int status = dma_fence_get_status(leaf); + size_t i; + + /* Already-signalled non-error leaves need no further wait or barrier. */ + if (status > 0) + return 0; + + for (i = 0; i < *count; ++i) { + if (out[i].fence == leaf) { + if (status < 0 && out[i].status >= 0) + out[i].status = status; + return 0; + } + if (coalesce_contexts && status == 0 && out[i].status == 0 && + out[i].fence->context == leaf->context) { + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } + if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } /* Called without the device mutex: status polling may run fence callbacks. */ -int asahi_g17_collect_fences(struct dma_fence *head, - struct asahi_g17_fence_leaf *out, size_t capacity) +static int collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity, + bool coalesce_contexts) { struct dma_fence *pending[128]; size_t count = 0, depth = 1; @@ -34,11 +58,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, if (asahi_g17_is_scope(node)) { struct dma_fence *children[2]; - unsigned int n = asahi_g17_scope_children(node, children), i; + unsigned int n, i; + int status = dma_fence_get_status(node); + + if (status > 0) { + dma_fence_put(node); + continue; + } + n = asahi_g17_scope_children(node, children); if (!n) { /* Preserve a failed scope as a failed leaf, never drop its error. */ - if (dma_fence_get_status(node) < 0) - error = collect_leaf(node, out, capacity, &count); + if (status < 0) + error = collect_leaf(node, out, capacity, &count, + coalesce_contexts); } else if (depth + n > ARRAY_SIZE(pending)) { for (i = 0; i < n; ++i) dma_fence_put(children[i]); @@ -60,7 +92,8 @@ int asahi_g17_collect_fences(struct dma_fence *head, } else if (dma_fence_is_container(leaf)) { error = -EOPNOTSUPP; } else { - error = collect_leaf(leaf, out, capacity, &count); + error = collect_leaf(leaf, out, capacity, &count, + coalesce_contexts); } if (error) break; @@ -79,6 +112,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, return count; } +int asahi_g17_collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity) +{ + return collect_fences(head, out, capacity, false); +} + +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity) +{ + return collect_fences(head, out, capacity, true); +} + void asahi_g17_put_fence(struct dma_fence *fence) { dma_fence_put(fence); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 44d3e338c19778..9fd39e223cf34d 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -13,6 +13,9 @@ struct asahi_g17_fence_leaf { int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity); void asahi_g17_put_fence(struct dma_fence *fence); struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t count); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 356fca680b23c2..4d7629a8ffe770 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -14,6 +14,8 @@ pub(crate) struct Leaf { unsafe extern "C" { fn asahi_g17_collect_fences(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; + fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, + out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); fn asahi_g17_merge_fences(fences: *const *mut bindings::dma_fence, count: usize) -> *mut bindings::dma_fence; @@ -42,27 +44,40 @@ impl Drop for Leaf { } } -/// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(crate) fn collect(input: &Fence) -> Option> { +fn collect_with( + input: &Fence, + collector: unsafe extern "C" fn(*mut bindings::dma_fence, *mut Leaf, usize) -> i32, +) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; // SAFETY: The input owns its fence. The C helper writes at most capacity // fully initialized records and releases every reference on failure. - let count = unsafe { - asahi_g17_collect_fences(input.raw(), leaves.as_mut_ptr(), capacity) - }; + let count = unsafe { collector(input.raw(), leaves.as_mut_ptr(), capacity) }; if count == ENOSPC.to_errno() && capacity < 128 { capacity = (capacity * 4).min(128); continue; } - if count < 0 { return None; } + if count < 0 { + return None; + } // SAFETY: The helper returned this many initialized, owned records. unsafe { leaves.set_len(count as usize) }; return Some(leaves); } } +/// Allocation, unsupported containers, or a large prefix retain normal waits. +pub(crate) fn collect(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences) +} + +/// Like [`collect`], coalescing unsignalled non-error leaves sharing a `dma_fence` context to +/// their latest sequence number so deep timeline chains stay bounded by distinct contexts. +pub(crate) fn collect_coalesced(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences_coalesced) +} + use super::fence::Submission; use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index c0dd3e2616dcc9..0843277bc93688 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -3,7 +3,9 @@ """Exercise production DMA-fence lockdep guard and Timeline off-pending signalling.""" from common import kernel_root, output_dir, rustc, sha import json +import os import pathlib +import shlex import subprocess import tempfile @@ -92,6 +94,10 @@ def extract_function(text, name): fence_source.index('/// Inline storage for the common 0-2 input fences'): fence_source.index('/// Reads a retained dependency') ] +fw_waits_src = fence_source[ + fence_source.index('/// Maximum distinct cross-queue firmware waits'): + fence_source.index('/// Fence operations of G16 job fences.') +] syncs_src = fence_source[ fence_source.index('/// The syncs of one SUBMIT.'): ] @@ -417,9 +423,92 @@ def extract_function(text, name): assert_eq!(log2.borrow().failed, vec![Fence(ENOMEM.0)]); } } + +mod fw_waits_test { + use super::{Error, Result, GFP_KERNEL}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + + const E2BIG: Error = Error(-7); + + pub(crate) struct QueueState(u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } + + FW_WAITS_SRC + + #[test] + fn fw_waits_coalesces_deep_two_queue_timeline_chain_and_merges_engines() { + let q0 = Arc::new(QueueState(0)); + let q1 = Arc::new(QueueState(1)); + let mut waits = FwWaits::Empty; + // 64 alternating timeline hops across 2 queues coalesce to 2 per-queue entries. + for hop in 1..=64u64 { + let (q, r, c) = if hop % 2 == 1 { + (q0.clone(), Some((hop + 1) / 2), Some(hop)) + } else { + (q1.clone(), None, Some(hop / 2)) + }; + let origin = Arc::new(FenceOrigin::new(1, 7, q, [r, c])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), 2); + let w0 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q0)).unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w0.last_ordinal, [Some(32), Some(63)]); + assert_eq!(w1.last_ordinal, [None, Some(32)]); + + // Merging an earlier render-only origin with a later compute-only origin on q1 keeps both. + waits + .push_unique(Arc::new(FenceOrigin::new(1, 7, q1.clone(), [Some(5), None]))) + .unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w1.last_ordinal, [Some(5), Some(32)]); + } + + #[test] + fn fw_waits_caps_distinct_queues_at_max_fw_waits() { + let mut waits = FwWaits::Empty; + for idx in 0..MAX_FW_WAITS { + let q = Arc::new(QueueState(idx as u32)); + let origin = Arc::new(FenceOrigin::new(1, 7, q, [None, Some(1)])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), MAX_FW_WAITS); + let extra = Arc::new(FenceOrigin::new( + 1, + 7, + Arc::new(QueueState(99)), + [None, Some(1)], + )); + assert_eq!(waits.push_unique(extra), Err(E2BIG)); + } +} '''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( 'TIMELINE_COMPLETE_FN', timeline_complete_fn ).replace('INPUT_FENCES_SRC', input_fences_src).replace( + 'FW_WAITS_SRC', fw_waits_src +).replace( 'SYNCS_SRC', syncs_src.replace('crate::g17::', 'g17::') ) @@ -439,9 +528,247 @@ def extract_function(text, name): if result.returncode: raise SystemExit(result.returncode) +# Exercise the actual production g17/sync_input.c collector against lightweight C dma_fence +# and dma_fence_chain shims to prove deep 2-queue timeline chains coalesce without -ENOSPC, +# skip signalled leaves, and preserve error leaves. +sync_input_c = root / 'drivers/gpu/drm/asahi/g17/sync_input.c' +sync_input_dir = sync_input_c.parent +c_harness = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +#define ASAHI_G17_SYNC_SCOPE_H 1 +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define GFP_KERNEL 0 + +struct dma_fence { + uint64_t context; + uint64_t seqno; + int status; + int refcount; + bool is_chain; + bool is_container; + struct dma_fence *chain_next; + struct dma_fence *chain_fence; +}; + +struct dma_fence_unwrap { + struct dma_fence *chain; + struct dma_fence *array; + unsigned int index; +}; + +static inline struct dma_fence *dma_fence_get(struct dma_fence *f) +{ + if (f) + ++f->refcount; + return f; +} + +static inline void dma_fence_put(struct dma_fence *f) +{ + if (f) { + assert(f->refcount > 0); + --f->refcount; + } +} + +static inline int dma_fence_get_status(struct dma_fence *f) +{ + return f ? f->status : 1; +} + +static inline bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{ + return f1->seqno > f2->seqno; +} + +static inline bool dma_fence_is_container(struct dma_fence *f) +{ + return f && (f->is_chain || f->is_container); +} + +static inline struct dma_fence *dma_fence_unwrap_first(struct dma_fence *head, + struct dma_fence_unwrap *cursor) +{ + cursor->chain = NULL; + cursor->array = NULL; + cursor->index = 0; + if (!head) + return NULL; + if (head->is_chain) { + cursor->chain = dma_fence_get(head); + return head->chain_fence; + } + return head; +} + +static inline struct dma_fence *dma_fence_unwrap_next(struct dma_fence_unwrap *cursor) +{ + struct dma_fence *next; + + if (!cursor->chain) + return NULL; + next = cursor->chain->chain_next; + dma_fence_put(cursor->chain); + if (!next) { + cursor->chain = NULL; + return NULL; + } + cursor->chain = dma_fence_get(next); + return next->chain_fence; +} + +#define dma_fence_unwrap_for_each(fence, cursor, head) \ + for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ + (fence) = dma_fence_unwrap_next((cursor))) + +static inline void *kmalloc_array(size_t n, size_t size, int flags) +{ + (void)flags; + return calloc(n, size); +} + +static inline void kfree(void *p) +{ + free(p); +} + +static inline struct dma_fence *__dma_fence_unwrap_merge(unsigned int n, + struct dma_fence **f, + struct dma_fence_unwrap *c) +{ + (void)n; + (void)f; + (void)c; + return NULL; +} + +static inline bool asahi_g17_is_scope(struct dma_fence *f) +{ + (void)f; + return false; +} + +static inline unsigned int asahi_g17_scope_children(struct dma_fence *f, + struct dma_fence *out[2]) +{ + (void)f; + (void)out; + return 0; +} + +#include "sync_input.h" +#include "sync_input.c" + +int main(void) +{ + enum { HOPS = 256 }; + struct dma_fence leaves[HOPS]; + struct dma_fence chains[HOPS]; + struct asahi_g17_fence_leaf out[4]; + int n, i; + + /* 256 alternating unsignalled hops across 2 contexts (10 and 20). */ + memset(leaves, 0, sizeof(leaves)); + memset(chains, 0, sizeof(chains)); + for (i = 0; i < HOPS; ++i) { + leaves[i].context = (i % 2 == 0) ? 10 : 20; + leaves[i].seqno = (uint64_t)(i / 2 + 1); + leaves[i].status = 0; + leaves[i].refcount = 1; + + chains[i].is_chain = true; + chains[i].refcount = 1; + chains[i].chain_fence = &leaves[i]; + chains[i].chain_next = (i > 0) ? &chains[i - 1] : NULL; + } + + /* Coalesced collector fits a 256-hop 2-queue timeline chain into capacity=4 with 2 leaves. */ + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 2); + assert((out[0].fence == &leaves[HOPS - 1] && out[1].fence == &leaves[HOPS - 2]) || + (out[1].fence == &leaves[HOPS - 1] && out[0].fence == &leaves[HOPS - 2])); + for (i = 0; i < n; ++i) { + assert(out[i].status == 0); + asahi_g17_put_fence(out[i].fence); + } + + /* Non-coalesced collector still sees distinct unsignalled leaves and hits -ENOSPC at cap=4. */ + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == -ENOSPC); + + /* Already-signalled leaves (status > 0) are skipped by both collectors. */ + for (i = 0; i < HOPS; ++i) + leaves[i].status = 1; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 0); + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == 0); + + /* Error leaf (status < 0) is preserved even when a later same-context leaf is unsignalled. */ + leaves[5].status = -5; + leaves[HOPS - 1].status = 0; + leaves[HOPS - 2].status = 0; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 3); + { + bool saw_err = false, saw_ctx10 = false, saw_ctx20 = false; + for (i = 0; i < n; ++i) { + if (out[i].fence == &leaves[5] && out[i].status == -5) + saw_err = true; + else if (out[i].fence == &leaves[HOPS - 2] && out[i].status == 0) + saw_ctx10 = true; + else if (out[i].fence == &leaves[HOPS - 1] && out[i].status == 0) + saw_ctx20 = true; + asahi_g17_put_fence(out[i].fence); + } + assert(saw_err && saw_ctx10 && saw_ctx20); + } + + /* Every refcount returns cleanly to 1 (no leaks or double puts). */ + for (i = 0; i < HOPS; ++i) { + assert(leaves[i].refcount == 1); + assert(chains[i].refcount == 1); + } + printf("sync_input C coalescing tests passed (256-hop chain -> 2 leaves, error preserved)\n"); + return 0; +} +''' + +with tempfile.TemporaryDirectory(prefix='m4-c-sync-input-') as directory: + directory = pathlib.Path(directory) + (directory / 'linux').mkdir() + for hdr in ('dma-fence.h', 'dma-fence-unwrap.h', 'slab.h', 'types.h'): + (directory / 'linux' / hdr).write_text('/* host shim */\n') + (directory / 'linux' / 'errno.h').write_text('#define ENOSPC 28\n#define EOPNOTSUPP 95\n') + (directory / 'sync_scope.h').write_text('/* host shim */\n') + c_unit = directory / 'test_sync_input.c' + c_unit.write_text(c_harness) + c_bin = directory / 'test_sync_input' + cc = shlex.split(os.environ.get('CC', 'cc')) + for command in [ + cc + ['-Wall', '-Wextra', '-Werror', '-I', str(directory), '-I', str(sync_input_dir), + str(c_unit), '-o', str(c_bin)], + [str(c_bin)], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 8, 'negative_compile_checks': 1, 'cpu_only': True, - 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants and g16 Timeline::complete() off-pending FIFO batch signalling.', + 'passed': True, 'tests': 11, 'negative_compile_checks': 1, 'cpu_only': True, + 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants, g16 Timeline::complete() off-pending FIFO batch signalling, FwWaits per-queue coalescing, and g17/sync_input.c chain coalescing.', 'source_sha256': sha(production), 'timeline_source_sha256': sha(fence_source_path), + 'sync_input_source_sha256': sha(sync_input_c), }, indent=2) + '\n') From b17e320b0109c15d4b428b53c263d3c95571cd7d Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 18:19:35 -0500 Subject: [PATCH 0877/1514] drm/asahi: g16: raise TA wave window and overlap pre-gfx compute Reduce render-wave serialization and pre-gfx compute dispatch latency: - Raise TA_WAVE_PASSES from 3 to 8 so multi-pass render bursts can keep up to 8 unfinished TA passes pipelined per wave without stalling lightweight shadow/postfx bursts. - Ring Channel::Compute ahead of Channel::Fs and Channel::Ta in flush_doorbells() so pre-gfx compute wakes immediately ahead of TA cross-engine barriers while preserving FS-before-TA doorbell order. - When TA wave pacing pauses ready same-queue renders, allow a later independent non-query-access Command::Compute on that same queue (whose command dependencies are already published) to overlap onto CDM without violating per-queue compute FIFO or barrier ordering. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 35 ++++- drivers/gpu/drm/asahi/g16/hw.rs | 4 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 16 +-- .../drivers/gpu/asahi-m4/test-publication.py | 127 ++++++++++++++---- 4 files changed, 139 insertions(+), 43 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 94c73d55727754..9c70d4b0e38570 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -981,17 +981,37 @@ impl Firmware { self.engine.stats.hold[0] += 1; break; } + let ta_wave_paused = self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES; let mut alt: Option = None; for (i, cand) in self.engine.pending.iter().enumerate() { if i == index || !self.can_queue_behind(cand) { continue; } // Preserve per-queue FIFO: never jump a later job of a queue ahead - // of an earlier pending job of the same queue. - if self.engine.pending[..i] - .iter() - .any(|earlier| Arc::ptr_eq(&earlier.queue, &cand.queue)) - { + // of an earlier pending job of the same queue, except when TA wave + // pacing pauses earlier ready renders and an independent non-query + // compute (such as pre-gfx culling) has all dependencies published + // (`can_queue_behind` already checked `check_command_dependencies`). + let same_queue_blocked = self.engine.pending[..i].iter().any(|earlier| { + if !Arc::ptr_eq(&earlier.queue, &cand.queue) { + return false; + } + let allow_pre_gfx = ta_wave_paused + && matches!( + command(cand, cand.progress.sent()), + Some(Command::Compute(c)) if !c.query_access + ) + && matches!( + command(earlier, earlier.progress.sent()), + Some(Command::Render(_)) + ) + && !self.needs_engine_drain(earlier) + && earlier + .check_command_dependencies(earlier.progress.sent()) + .is_ok(); + !allow_pre_gfx + }); + if same_queue_blocked { continue; } let better = match alt { @@ -1231,11 +1251,12 @@ impl Firmware { result } - /// Rings each submit channel touched during a publication batch once, preserving + /// Rings each submit channel touched during a publication batch once, waking Compute + /// first so pre-gfx compute starts immediately ahead of TA barriers while 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] { + for channel in [Channel::Compute, Channel::Fs, Channel::Ta] { if mask & (1u8 << (channel as u8)) != 0 { self.session.ring(channel)?; } diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 5311de8e0f6a2b..72dcaf4e4b3c0b 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -731,9 +731,9 @@ pub(crate) mod sizes { /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + `work`). pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 2; /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts pace - /// TA in `<= 3`-pass waves without throttling single-pass pipelining (where TA finishes + /// TA in `<= 8`-pass waves without throttling single-pass pipelining (where TA finishes /// well ahead of FS). - pub(crate) const TA_WAVE_PASSES: usize = 3; + pub(crate) const TA_WAVE_PASSES: usize = 8; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most. A slot is reused only after a later render diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index b7e6acb29bae64..418591eade9eb3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -65,7 +65,7 @@ def item(declaration, text=source): const EVENT_RETIRE_POLLS: u32 = 11; mod hw { pub mod sizes { - pub const TA_WAVE_PASSES: usize = 3; + pub const TA_WAVE_PASSES: usize = 8; } } @@ -848,21 +848,21 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, - renders: 3, + renders: 8, target: 0, - fs_target: 0x300, + fs_target: 0x800, }); - fw.engine.fs_target = 0x300; + fw.engine.fs_target = 0x800; fw.engine.pending.push(Arc::new(Job { id: 2 })); fw.engine.ta_wave_wait = true; - fw.ta_pending = 3; + fw.ta_pending = 8; fw.drain_stage_delta = 1; fw.drain_fs_delta = 0; let mut retry_tail = false; let mut deferred = false; let mut done = vec![]; - // TA still full (3 >= 3): no publish_checked wakeup and no retry_tail spin. + // TA still full (8 >= 8): no publish_checked wakeup and no retry_tail spin. assert!(fw .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) .unwrap()); @@ -870,9 +870,9 @@ def item(declaration, text=source): assert!(!retry_tail); assert!(!fw.engine.short_repoll); - // TA finishes one pass (ta_pending drops to 2 < 3) on a TA-only 0x70 IRQ while FS is still + // TA finishes one pass (ta_pending drops to 7 < 8) on a TA-only 0x70 IRQ while FS is still // running: immediately wakes publish_checked() without spinning retry_tail or short_repoll. - fw.ta_pending = 2; + fw.ta_pending = 7; assert!(fw .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) .unwrap()); 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 496ee218749313..a96fa6b8092900 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -152,7 +152,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=3; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=8; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -581,28 +581,101 @@ def item(declaration): assert_eq!(j1.queue.turn.load(Ordering::Relaxed),11); assert_eq!(f.engine.turn,11); } - #[test]fn ta_wave_pacing_flushes_doorbell_at_three_passes_and_arms_ta_wave_wait(){ + #[test]fn mixed_compute_and_render_batch_rings_compute_before_fs_and_ta(){ let vm1=mk_vm(1); - let r1=job_on_vm(1,vm1.clone(),true,0,Ok(())); - let r2=job_on_vm(2,vm1.clone(),true,0,Ok(())); - let r3=job_on_vm(3,vm1.clone(),true,0,Ok(())); - let r4=job_on_vm(4,vm1.clone(),true,0,Ok(())); - let c5=job_on_vm(5,vm1,false,0,Ok(())); let mut f=firmware( - vec![r1,r2,r3,r4,c5], - vec![(Ok(()),true),(Ok(()),true),(Ok(()),true),(Ok(()),true)], + vec![job_on_vm(1,vm1.clone(),true,0,Ok(())),job_on_vm(2,vm1,false,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::Compute,Channel::Fs,Channel::Ta]); + } + #[test]fn ta_wave_pacing_flushes_doorbell_at_eight_passes_and_arms_ta_wave_wait(){ + let vm1=mk_vm(1); + let mut jobs:Vec>=(1..=9).map(|id|job_on_vm(id,vm1.clone(),true,0,Ok(()))).collect(); + jobs.push(job_on_vm(10,vm1,false,0,Ok(()))); + let stages=vec![(Ok(()),true);9]; + let mut f=firmware(jobs,stages); + f.allow_behind=true; + let mut done=vec![]; assert_eq!(f.publish_checked(&mut done),Ok(())); - // Passes 1..3 fill TA_WAVE_PASSES (3) and ring FS+TA immediately; pass 4 pauses with - // ta_wave_wait=true while alt compute job 5 still publishes on Compute. - assert_eq!(f.attempted,[1,2,3,5]); + // Passes 1..8 fill TA_WAVE_PASSES (8) and ring FS+TA immediately; pass 9 pauses with + // ta_wave_wait=true while alt compute job 10 still publishes on Compute. + assert_eq!(f.attempted,[1,2,3,4,5,6,7,8,10]); assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); assert!(f.engine.ta_wave_wait); assert!(!f.engine.slot_wait); assert_eq!(f.engine.pending.len(),1); } + #[test]fn same_queue_independent_compute_bypasses_ta_wave_paused_render_only(){ + let vm1=mk_vm(1); + let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ + id,vm:vm1.clone(),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})}], + dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, + }); + // Seed 8 active TA passes so TA wave pacing is active. + let mut active_flights=Vec::new(); + for id in 1..=8 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + active_flights.push(fl); + } + // On q1: render 9 is TA-wave paused; independent !query_access compute 10 bypasses it. + let r9=mk(9,true,false,Ok(())); + let c10=mk(10,false,false,Ok(())); + let mut f=firmware(vec![r9,c10],vec![(Ok(()),true)]); + f.engine.flights=active_flights; + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert_eq!(f.attempted,[10]); + assert_eq!(f.engine.pending.len(),1); + assert!(f.engine.ta_wave_wait); + + // query_access compute on the same queue must NOT bypass TA-wave-paused render. + let mut f_q=firmware(vec![mk(11,true,false,Ok(())),mk(12,false,true,Ok(()))],vec![]); + for id in 1..=8 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_q.engine.flights.push(fl); + } + f_q.allow_behind=true; + assert_eq!(f_q.publish_checked(&mut done),Ok(())); + assert!(f_q.attempted.is_empty()); + + // Dependent compute (dependency Err(EAGAIN)) must NOT bypass TA-wave-paused render. + let mut f_dep=firmware(vec![mk(13,true,false,Ok(())),mk(14,false,false,Err(EAGAIN))],vec![]); + for id in 1..=8 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_dep.engine.flights.push(fl); + } + f_dep.allow_behind=true; + assert_eq!(f_dep.publish_checked(&mut done),Ok(())); + assert!(f_dep.attempted.is_empty()); + + // Later compute must NEVER jump an earlier pending compute on the same queue. + let mut f_cc=firmware( + vec![mk(15,true,false,Ok(())),mk(16,false,true,Ok(())),mk(17,false,false,Ok(()))], + vec![], + ); + for id in 1..=8 { + let mut fl=Flight::new(mk(id,true,false,Ok(()))); + fl.renders=1; + f_cc.engine.flights.push(fl); + } + f_cc.allow_behind=true; + f_cc.block_compute_behind=false; + // Job 16 is query_access (cannot bypass render 15); job 17 sits behind compute 16 so it must also wait. + assert_eq!(f_cc.publish_checked(&mut done),Ok(())); + assert!(f_cc.attempted.is_empty()); + } } #[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} @@ -1130,32 +1203,34 @@ def item(declaration): let r_live=mk(1); let next_r=mk(2); let mut r_ta=[0u32;16]; - r_ta[0]=0x100;r_ta[1]=0x200;r_ta[2]=0x300; + for i in 0..8 { + r_ta[i]=(i as u32 + 1)*0x100; + } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0x300,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:3,computes:0,renders:2,target:0,cstamp:[0;16], - r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x300, + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:8,computes:0,renders:7,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, 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,block_pipeline_vm:None}, }; - // Below TA_WAVE_PASSES (2 < 3): zero WC fw_stamp reads. - assert_eq!(p.ta_pending_passes(),2); + // Below TA_WAVE_PASSES (7 < 8): zero WC fw_stamp reads. + assert_eq!(p.ta_pending_passes(),7); assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); assert!(p.can_queue_behind(&next_r)); - // 3 unfinished TA passes: paces render queue_behind until TA advances. - p.engine.flights[0].renders=3; - assert_eq!(p.ta_pending_passes(),3); + // 8 unfinished TA passes: paces render queue_behind until TA advances. + p.engine.flights[0].renders=8; + assert_eq!(p.ta_pending_passes(),8); assert!(p.graph.render.fw_stamp[0].reads.get()>0); assert!(!p.can_queue_behind(&next_r)); - // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 2. + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 7. p.graph.render.fw_stamp[0].val.set(0x100); - assert_eq!(p.ta_pending_passes(),2); + assert_eq!(p.ta_pending_passes(),7); assert!(p.can_queue_behind(&next_r)); - // Even with 16 active FS passes, finished TA (obs=0x300) leaves single-pass pipelining unthrottled. - p.graph.render.fw_stamp[0].val.set(0x300); + // Even with 16 active FS passes, finished TA (obs=0x800) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x800); p.engine.flights[0].renders=16; assert_eq!(p.ta_pending_passes(),0); assert!(p.can_queue_behind(&next_r)); @@ -2110,7 +2185,7 @@ def item(declaration): if result.returncode: raise SystemExit(result.returncode) (output/'publication.json').write_text(json.dumps({ - 'passed': True, 'tests': 68, 'cpu_only': True, 'hardware_execution': False, + 'passed': True, 'tests': 70, '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') From 9cd259d4c29051ae2633a481c7ee3c946ab78b4c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 08:34:11 -0500 Subject: [PATCH 0878/1514] drm/asahi: g16: prefer warm VM-affine compute units when claiming When multiple processes interleave compute submissions on G16, pure round-robin compute-unit claiming rotates each VM onto another VM's recently retired unit, forcing a full WC scrub, 160-byte WC descriptor read-back, and 8 KiB full work write on every dispatch. Update Slots::claim_compute_for_pipe() to prefer a displaced warm unit already owned by the requesting VM (!scrub_full), then an unowned unit, before falling back to round-robin over the pipe's eligible range. This keeps concurrent multi-VM compute workloads on their own warm units while preserving base-unit pipe-0 isolation and quarantine fallback. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/slots.rs | 71 +++++++++++++------ .../drivers/gpu/asahi-m4/test-resources.py | 67 +++++++++++++++++ 2 files changed, 118 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 7a4cfeb10aeb63..9f27082581230e 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -1025,7 +1025,8 @@ impl Slots { if f.slot_count as usize >= f.slot.len() { return Ok(None); } - // Round robin over this VM's units eligible for `pipe`: pipe 0 spans `0..n`, while + // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, + // before falling back to round-robin over `start..n`: pipe 0 spans `0..n`, while // secondary pipes stay in `BASE_COMPUTE_UNITS..n` so base units `0..2` only ever hold // pipe-0 leases and a 2-unit VM can never hit `compute_exhausted_within(2)`. let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); @@ -1039,28 +1040,58 @@ impl Slots { } let span = n - start; let base_cursor = (self.cursor as usize).saturating_sub(start) % span; - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.lifetime.claim(k) { - 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); + let mut chosen = None; + if let Some(id) = vm_id { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if !self.compute.scrub_full[k] + && self.compute.owner[k] + .as_ref() + .is_some_and(|prev| prev.id == id) + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break; + } + } + if chosen.is_none() { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { + chosen = Some(k); + break; + } } - self.compute.last_full[k] = full; - f.slot[f.slot_count as usize] = k as u32; - f.slot_count += 1; - f.compute_pipe = pipe as u8; - self.cursor = ((k + 1) % n) as u32; - return Ok(Some(k)); } } - Ok(None) + if chosen.is_none() { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if self.compute.lifetime.claim(k) { + chosen = Some(k); + break; + } + } + } + let Some(k) = chosen else { + return Ok(None); + }; + 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); + } + self.compute.last_full[k] = full; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; + f.compute_pipe = pipe as u8; + self.cursor = ((k + 1) % n) as u32; + Ok(Some(k)) } #[allow(dead_code)] pub(crate) fn pick_pass( 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 be994dc4e53eb7..7687dfb409bab3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1755,6 +1755,73 @@ def module(text, name): assert!(p.reusable_for_within(1, &vm1, 2, 2048).is_some()); } + #[test]fn vm_affine_compute_claiming_keeps_four_interleaved_vms_warm(){ + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut units = KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + units.push(g16::slots::ComputeSlot::new(&mut o, k).unwrap(), 0).unwrap(); + } + let prep = g16::resources::ComputeArena { compute: units, render: None }; + let vms = [vm(1), vm(2), vm(3), vm(4)]; + // Round 0 warms one unit per VM (4 units out of 24); VM2's retirement displaces VM1's + // unit immediately so from round 1 onward every sequential interleaved claim is warm. + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + for _round in 0..4 { + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(!s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + // Pipelined depth-2 per VM across 4 concurrent VMs warms one additional unit per VM + // from the unowned pool and then reuses warm VM-owned units with zero cross-VM scrubs. + let mut live: Vec = Vec::new(); + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if idx < 3 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + live.push(c); + } + for _round in 0..4 { + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if _round > 0 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + let mut old = std::mem::replace(&mut live[idx], c); + s.retire(&mut old).unwrap(); + } + } + for mut c in live { + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + } + } ''' poll_source = (production/'poll.rs').read_text() From 71a3a31f203eb81f52983c7becc62319f66036ec Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 20:37:05 -0500 Subject: [PATCH 0879/1514] drm/asahi: g16: overlap barrier-free compute across two CDM pipes Add a second independent CDM workqueue pipe (pipe 0 on event 0x74 and pipe 1 on event 0x75) so barrier-free compute dispatches overlap across two hardware CDM pipes while preserving exact per-pipe and cross-pipe barriers, recovery isolation, and per-pipe UMA slot displacement: - Track per-pipe ownership in pools::lifetime::Lifetime (publish_on, per-pipe FIFO retirement, and same-pipe displacement) so pipe 1 can retire ahead of an in-flight pipe 0 command without EINVAL and without falsely displacing pipe 0's retired UMA owners. - Keep base compute units 0..BASE_COMPUTE_UNITS (0..2) on pipe 0 and restrict pipe 1 claims to BASE_COMPUTE_UNITS..n so a 2-unit base-only VM can never see both base units undisplaced across two pipes. - Balance barrier-free dispatches across both pipes in choose_compute_pipe and emit cross-pipe c2c barriers only when waiting across pipes. - Add host unit tests covering out-of-order dual-pipe retirement, same-pipe displacement isolation, and base-unit VM exhaustion safety. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode/compute.rs | 8 +- drivers/gpu/drm/asahi/g16/engine.rs | 465 +++++++++++++----- drivers/gpu/drm/asahi/g16/event.rs | 12 +- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 2 + drivers/gpu/drm/asahi/g16/graph.rs | 27 +- drivers/gpu/drm/asahi/g16/hw.rs | 16 +- drivers/gpu/drm/asahi/g16/job.rs | 53 +- drivers/gpu/drm/asahi/g16/params.rs | 2 +- drivers/gpu/drm/asahi/g16/poll.rs | 296 +++++++---- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 55 ++- drivers/gpu/drm/asahi/g16/queue.rs | 20 +- drivers/gpu/drm/asahi/g16/recovery.rs | 4 +- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 32 +- drivers/gpu/drm/asahi/g16/slots.rs | 90 +++- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 2 +- .../drivers/gpu/asahi-m4/check-compute.rs | 16 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 51 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 112 +++-- .../gpu/asahi-m4/test-progress-wrap.py | 50 +- .../drivers/gpu/asahi-m4/test-publication.py | 455 +++++++++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 83 +++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 213 +++++--- 22 files changed, 1533 insertions(+), 531 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index fe307dcfce52c8..179f39cb4c3bff 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -52,6 +52,8 @@ pub(crate) struct ComputeRefs { pub(crate) record_fw: u64, pub(crate) binding_generation: u8, pub(crate) uma_slot: u32, + /// Firmware completion event assigned to this compute pipe (e.g. 15 or 16). + pub(crate) event: u32, /// Native command descriptor identifier (work+0x820), independent of compute index. pub(crate) command_id: u64, /// Native u32 compute sequence/index (StartCompute+0x38). @@ -202,6 +204,8 @@ pub(crate) fn encode_compute_for( if r.binding_generation == 0 || r.uma_slot == 0 || r.uma_slot > 32 + || r.event == 0 + || r.event >= 128 || r.target_stamp & 0xff != 0 || r.submitted == 0 { @@ -328,7 +332,7 @@ pub(crate) fn encode_compute_for( put64(w, 0x800, r.user_stamp); put64(w, 0x808, r.fw_stamp); put32(w, 0x810, r.target_stamp); - put32(w, 0x814, compute::EVENT); + put32(w, 0x814, r.event); put32(w, 0x81c, 1); put32(w, 0x818, r.work_818); put64(w, 0x820, r.command_id); @@ -375,7 +379,7 @@ pub(crate) fn encode_compute_for( put64(q, 0x198, r.context_store_gva + 0x1e800); put64(q, 0x1a0, r.context_store_gva + 0x1f000); put64(q, 0x1a8, r.work + layout.target as u64); - put32(q, 0x1b8, compute::EVENT); + put32(q, 0x1b8, r.event); let requested = ts_va[0] != 0 || ts_va[1] != 0; timestamp(q, compute::TS_START, false, r, requested, layout.auxiliary); put32(q, 0x208, 1); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 9c70d4b0e38570..14696fb27aa717 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -171,14 +171,14 @@ struct RenderBarrierPlan { ta_prev_wait: bool, ta_fs_wait: Option, fs_render_wait: Option, - ta_compute_wait: Option, - fs_compute_wait: Option, + ta_compute_wait: [Option; sizes::COMPUTE_PIPES], + fs_compute_wait: [Option; sizes::COMPUTE_PIPES], } /// Computes TA/FS hardware ring barriers for a render command from its flags, prior render /// FS stamp, resolved render waits (`fs_wait_render`, `ta_wait_fs`), resolved `[ta, fs]` -/// compute wait stamps, and whether the immediately preceding in-flight render belongs to a -/// different VM (`cross_vm_prev`). +/// per-pipe compute wait stamps, and whether the immediately preceding in-flight render belongs +/// to a different VM (`cross_vm_prev`). /// /// Same-VM pipelined renders share one parameter-buffer / UMA slot, and cross-VM pipelined /// renders use distinct UMA slots (`RENDER_UMA_SLOT + slot`) on the shared TA/FS pipes: TA(N) @@ -198,7 +198,7 @@ fn plan_render_barriers( prev_fs: u32, fs_wait_render: Option, ta_wait_fs: Option, - compute_waits: [Option; 2], + compute_waits: [[Option; sizes::COMPUTE_PIPES]; 2], cross_vm_prev: bool, ) -> RenderBarrierPlan { let staged = @@ -243,11 +243,12 @@ fn plan_render_barriers( None }; let [ta_compute_wait, fs_wait] = compute_waits; - let fs_compute_wait = if fs_wait != ta_compute_wait { - fs_wait - } else { - None - }; + let mut fs_compute_wait = [None; sizes::COMPUTE_PIPES]; + for p in 0..sizes::COMPUTE_PIPES { + if fs_wait[p] != ta_compute_wait[p] { + fs_compute_wait[p] = fs_wait[p]; + } + } RenderBarrierPlan { early, ta_prev_wait, @@ -279,6 +280,8 @@ pub(crate) struct Flight { pub(crate) count: usize, pub(crate) computes: u32, pub(crate) renders: u32, + /// Compute pipe (`0..COMPUTE_PIPES`) this flight was published to. + pub(crate) compute_pipe: u8, /// Compute: final FW stamp, ring end (exclusive) and ring position before the prefix. pub(crate) target: u32, pub(crate) head: u32, @@ -338,6 +341,7 @@ impl Flight { count: 0, computes: 0, renders: 0, + compute_pipe: 0, target: 0, head: 0, c_start: 0, @@ -378,14 +382,16 @@ impl Flight { struct Prefix { computes: u32, renders: u32, + compute_pipe: usize, prev: Prev, /// This prefix (re)initializes the PB with InitBM. initbm: bool, c_head: u32, ta_head: u32, fs_head: u32, - /// Last compute ordinal / last draw ordinal. + /// Last total compute ordinal, per-pipe compute ordinal, and draw ordinal. n: u64, + pipe_n: u64, draw: u64, last_ct: u32, last_ta: u32, @@ -553,12 +559,13 @@ pub(crate) struct Engine { /// flight (`[start, end, 0, 0]` for compute; `[ta_start, ta_end, fs_start, fs_end]` for /// render), reused by accounting without re-reading WC cells. pub(crate) retired_ticks: [u64; 4], - /// Host compute ordinal and draw ordinal of the last publication. + /// Host compute ordinal, per-pipe compute ordinals, and draw ordinal of the last publication. pub(crate) ordinal: u64, + pub(crate) pipe_ordinal: [u64; sizes::COMPUTE_PIPES], pub(crate) draw: u64, /// Newest published receipts, the tail. - pub(crate) target: u32, - pub(crate) head: u32, + pub(crate) target: [u32; sizes::COMPUTE_PIPES], + pub(crate) head: [u32; sizes::COMPUTE_PIPES], pub(crate) ta_target: u32, pub(crate) fs_target: u32, pub(crate) ta_head: u32, @@ -566,8 +573,9 @@ pub(crate) struct Engine { /// Event counts at the tail's publication. pub(crate) events: u32, pub(crate) stage_seen: u32, - /// The compute queue / render queues were registered by a first record (`new_queue`). - pub(crate) queue_registered: bool, + /// The compute pipes / render queues were registered by a first record (`new_queue`). + pub(crate) queue_registered: [bool; sizes::COMPUTE_PIPES], + pub(crate) next_compute_pipe: u8, pub(crate) render_registered: bool, pub(crate) ta_registered: bool, /// A ready prefix waits only for a record's consumption: repoll sooner. @@ -580,9 +588,9 @@ pub(crate) struct Engine { pub(crate) ta_wave_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 compute and render flights. - pub(crate) progress_flight: [u64; 2], - pub(crate) progress: [Option; 3], + /// Progress tracking of the oldest compute pipe 0/1 and render flights. + pub(crate) progress_flight: [u64; 3], + pub(crate) progress: [Option; 4], /// Boxed with [`Self::prof`]: `Firmware` is built on the probe's stack. pub(crate) stats: KBox, /// Phase timers (debug_flags bit 49). @@ -605,24 +613,26 @@ impl Engine { shared: None, retired_ticks: [0; 4], ordinal: 0, + pipe_ordinal: [0; sizes::COMPUTE_PIPES], draw: 0, - target: 0, - head: 0, + target: [0; sizes::COMPUTE_PIPES], + head: [0; sizes::COMPUTE_PIPES], ta_target: 0, fs_target: 0, ta_head: 0, fs_head: 0, events: 0, stage_seen: 0, - queue_registered: false, + queue_registered: [false; sizes::COMPUTE_PIPES], + next_compute_pipe: 0, render_registered: false, ta_registered: false, chan_wait: false, slot_wait: false, ta_wave_wait: false, short_repoll: false, - progress_flight: [0; 2], - progress: [None; 3], + progress_flight: [0; 3], + progress: [None; 4], stats: KBox::new(Stats::default(), GFP_KERNEL)?, prof: KBox::new(Prof::default(), GFP_KERNEL)?, debugfs: None, @@ -778,11 +788,12 @@ impl Firmware { /// The single in-order Finalize frontier for each held M4 event. These cells are never /// reset after first publication, including across client VM switches and recovery. - pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 3]> { + pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 4]> { Ok([ self.graph.render.fw_stamp[0].r32(0)?, self.graph.render.fw_stamp[1].r32(0)?, - self.graph.compute.fw_stamp.r32(0)?, + self.graph.compute[0].fw_stamp.r32(0)?, + self.graph.compute[1].fw_stamp.r32(0)?, ]) } @@ -793,7 +804,7 @@ impl Firmware { flags: u32, event: u32, target: u32, - stage: [u32; 3], + stage: [u32; 4], ) -> Result { if flags & 1 != 0 && self.recovery.last_retired.contains(event, target) { // A notification may follow the full receipt. It names the retained old @@ -808,6 +819,12 @@ impl Firmware { .find(|f| match event { 15 => { f.computes != 0 + && f.compute_pipe == 0 + && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) + } + 16 => { + f.computes != 0 + && f.compute_pipe == 1 && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) } 0x70 => { @@ -858,7 +875,7 @@ impl Firmware { /// in the snapshot. Keep it until either its full receipt or its passed-abort proof. pub(crate) fn recovery_prepare_suspects( &mut self, - stage: [u32; 3], + stage: [u32; 4], _event: u32, fault_asid: Option, ) -> Result { @@ -868,9 +885,10 @@ impl Firmware { self.engine.ta_target, self.engine.fs_target, ); - // Every unfinished flight, including compute queued behind the oldest. + // Every unfinished flight, including compute queued behind the oldest on either pipe. for f in self.engine.flights.iter_mut() { - let unfinished = (f.computes != 0 && !reached(stage[2], f.target, target)) + let pipe = (f.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + let unfinished = (f.computes != 0 && !reached(stage[2 + pipe], f.target, target[pipe])) || (f.renders != 0 && (!reached(stage[0], f.ta_target, ta_target) || !reached(stage[1], f.fs_target, fs_target))); @@ -1579,6 +1597,118 @@ impl Firmware { self.wait_stamp_for(job, other, target_seq) } + /// Resolves the newest in-flight same-queue compute producer on each compute pipe with + /// ordinal `<= target_seq`. Returns `Ok([None; COMPUTE_PIPES])` when no barrier was + /// requested or the entire prefix through `target_seq` has already retired, and `Err(EAGAIN)` + /// if `target_seq` is neither in flight nor retired. + fn wait_compute_stamps_for( + &self, + job: &Arc, + target_seq: Option, + ) -> Result<[Option; sizes::COMPUTE_PIPES]> { + let Some(last) = target_seq else { + return Ok([None; sizes::COMPUTE_PIPES]); + }; + if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + return Ok([None; sizes::COMPUTE_PIPES]); + } + let mut waits = [None; sizes::COMPUTE_PIPES]; + let mut best_seq = [0u64; sizes::COMPUTE_PIPES]; + let mut found_last = false; + for flight in &self.engine.flights { + if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + continue; + } + let pipe = flight.compute_pipe as usize; + if pipe >= sizes::COMPUTE_PIPES { + return Err(EIO); + } + let mut member = 0usize; + for k in flight.first..flight.first + flight.count { + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == super::command::COMPUTE && fo.sequence <= last { + if fo.sequence == last { + found_last = true; + } + if fo.sequence >= best_seq[pipe] { + best_seq[pipe] = fo.sequence; + waits[pipe] = Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + }); + } + } + } + member += 1; + } + for j2 in flight.group.iter() { + for k in 0..j2.progress.count() { + if let Some(fo) = j2.command_order(k) { + if fo.engine == super::command::COMPUTE && fo.sequence <= last { + if fo.sequence == last { + found_last = true; + } + if fo.sequence >= best_seq[pipe] { + best_seq[pipe] = fo.sequence; + waits[pipe] = Some(WaitTarget { + stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, + initbm: flight.initbm, + }); + } + } + } + member += 1; + } + } + } + if !found_last && !job.queue.is_compute_retired(last) { + return Err(EAGAIN); + } + Ok(waits) + } + + /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: + /// - Base-only VMs (`units <= BASE_COMPUTE_UNITS`) or states where pipe 1 has no available + /// extension unit stay on pipe 0 so base units `0..2` never split across two pipes. + /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` + /// barrier). + /// - If barrier-free (`[None, None]`) or waiting on both pipes (`[Some, Some]`), pick the + /// pipe with fewer active compute commands, breaking ties by `next_compute_pipe`. + fn choose_compute_pipe( + &self, + waits: [Option; sizes::COMPUTE_PIPES], + units: usize, + ) -> usize { + if units <= super::resources::BASE_COMPUTE_UNITS + || !self.slots.compute_available_for_pipe(units, 1) + { + return 0; + } + match waits { + [Some(_), None] => 0, + [None, Some(_)] => 1, + _ => { + if !self.slots.compute_available_for_pipe(units, 0) { + return 1; + } + let mut active = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active[p] += fl.computes as usize; + } + } + if active[0] < active[1] { + 0 + } else if active[1] < active[0] { + 1 + } else { + (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES + } + } + } + } + /// 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 { @@ -1779,6 +1909,23 @@ impl Firmware { } else { &[Channel::Compute] }; + let (compute_pipe, c_waits) = if render { + (0usize, [None; sizes::COMPUTE_PIPES]) + } else { + let units = job.resources.compute_units()?; + let waits = self.wait_compute_stamps_for( + job, + job.command_order(index) + .and_then(|o| o.wait_through[super::command::COMPUTE]), + )?; + (self.choose_compute_pipe(waits, units), waits) + }; + let pipe_behind = !render + && self + .engine + .flights + .iter() + .any(|fl| fl.computes != 0 && fl.compute_pipe as usize == compute_pipe); for &channel in channels { let pipe = self.channels.channel(channel); let producer = self.channels.producer(channel); @@ -1807,10 +1954,20 @@ impl Firmware { self.graph.render.qstate[1].r32(qstate::WRITE)?, ) } else { - (self.graph.compute.qstate.r32(qstate::WRITE)?, 0, 0) + ( + self.graph.compute[compute_pipe].qstate.r32(qstate::WRITE)?, + 0, + 0, + ) }; let mut prefix = Prefix { + compute_pipe, n: self.engine.ordinal, + pipe_n: if render { + 0 + } else { + self.engine.pipe_ordinal[compute_pipe] + }, draw: self.engine.draw, c_head, ta_head, @@ -1823,34 +1980,31 @@ impl Firmware { let mut c_read = prefix.c_head; let mut ta_read = prefix.ta_head; let mut fs_read = prefix.fs_head; - if class_behind { - if render { - // Room for up to 4 TA entries (prev_barrier, ta_fs_barrier, compute_barrier, - // ta_work) and 4 FS entries (fs_dep, fs_compute_barrier, own_barrier, fs_work). - ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; - 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 - 5 - || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP - >= sizes::QUEUE_CAP - 5 - { - self.engine.slot_wait = true; - return Err(EAGAIN); - } - } else { - // Room for an optional cross-engine barrier plus compute work entry. - c_read = self.graph.compute.qstate.r32(qstate::READ)?; - if c_read >= 256 - || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 3 - { - self.engine.slot_wait = true; - return Err(EAGAIN); - } + if render && class_behind { + // Room for up to 5 TA entries (prev_barrier, ta_fs_barrier, 2x compute_barrier, + // ta_work) and 5 FS entries (fs_dep, 2x fs_compute_barrier, own_barrier, fs_work). + ta_read = self.graph.render.qstate[0].r32(qstate::READ)?; + 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 - 6 + || prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 6 + { + self.engine.slot_wait = true; + return Err(EAGAIN); + } + } else if !render && pipe_behind { + // Room for optional fs2c + cross-pipe c2c barriers plus compute work entry. + c_read = self.graph.compute[compute_pipe].qstate.r32(qstate::READ)?; + if c_read >= 256 + || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 4 + { + self.engine.slot_wait = true; + return Err(EAGAIN); } } f.first = index as usize; + f.compute_pipe = compute_pipe as u8; f.c_start = prefix.c_head; f.ta_start = prefix.ta_head; f.fs_start = prefix.fs_head; @@ -1858,18 +2012,41 @@ impl Firmware { let mut hz_stop: Option = None; match cmd { Command::Compute(c) => { - self.prefix_compute(job, &job.resources, index, c, &mut prefix, f, false)?; + self.prefix_compute( + job, + &job.resources, + index, + c, + c_waits, + &mut prefix, + f, + false, + )?; let mut last_seq = job.command_order(index).map(|o| o.sequence); let vm_units = job.resources.compute_units()?.min(sizes::COMPUTE_UNITS); - let free_c = self.slots.free_compute_in(vm_units) as usize; - let active_computes: usize = - self.engine.flights.iter().map(|fl| fl.computes as usize).sum(); + let free_c = self + .slots + .free_compute_in_for_pipe(vm_units, compute_pipe) as usize; + let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active_pipe[p] += fl.computes as usize; + } + } + let active_computes = active_pipe[0] + active_pipe[1]; + // Keep barrier-free work balanced across both compute pipes: fold extra commands + // into this pipe only when the alternate pipe already has deeper queued work, so + // independent submits distribute across pipes 0 and 1 in the same doorbell batch. + let pipe_fold_cap = + active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1); let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; - let ring_more = (sizes::QUEUE_CAP.saturating_sub(3)).saturating_sub(used) as usize; + let ring_more = (sizes::QUEUE_CAP.saturating_sub(4)).saturating_sub(used) as usize; let mut more_slots = free_c .min(params::compute_flights().saturating_sub(active_computes + 1)) .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) - .min(ring_more); + .min(ring_more) + .min(pipe_fold_cap); // Fold trailing barrier-free compute commands of the base job first. while more_slots > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { @@ -1883,7 +2060,16 @@ impl Firmware { let Some(Command::Compute(c2)) = command(job, end) else { break; }; - self.prefix_compute(job, &job.resources, end, c2, &mut prefix, f, false)?; + self.prefix_compute( + job, + &job.resources, + end, + c2, + [None; sizes::COMPUTE_PIPES], + &mut prefix, + f, + false, + )?; last_seq = Some(next_seq); end += 1; more_slots -= 1; @@ -1949,6 +2135,7 @@ impl Firmware { &job.resources, k, c2, + [None; sizes::COMPUTE_PIPES], &mut prefix, f, false, @@ -2029,7 +2216,7 @@ impl Firmware { }; let ta_used = prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP; let fs_used = prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP; - if ta_used >= sizes::QUEUE_CAP - 5 || fs_used >= sizes::QUEUE_CAP - 5 { + if ta_used >= sizes::QUEUE_CAP - 6 || fs_used >= sizes::QUEUE_CAP - 6 { break; } let geo2 = Geometry::new(&r2.cmd, 0); @@ -2044,19 +2231,15 @@ impl Firmware { & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; if self - .wait_stamp_for_with( + .wait_compute_stamps_for( job, - super::command::COMPUTE, o2.ta_wait_through[super::command::COMPUTE], - None, ) .is_err() || self - .wait_stamp_for_with( + .wait_compute_stamps_for( job, - super::command::COMPUTE, o2.wait_through[super::command::COMPUTE], - None, ) .is_err() || self @@ -2147,7 +2330,7 @@ impl Firmware { (prefix.ta_head.wrapping_sub(ta_read) % sizes::QUEUE_CAP) as usize; let fs_used = (prefix.fs_head.wrapping_sub(fs_read) % sizes::QUEUE_CAP) as usize; - let need_ring = n2_usize * 5; + let need_ring = n2_usize * (sizes::MAX_RENDER_RING_ENTRIES + 1); if ta_used + need_ring >= sizes::QUEUE_CAP as usize || fs_used + need_ring >= sizes::QUEUE_CAP as usize { @@ -2192,19 +2375,15 @@ impl Firmware { } }; if self - .wait_stamp_for_with( + .wait_compute_stamps_for( &j2, - super::command::COMPUTE, o2.ta_wait_through[super::command::COMPUTE], - None, ) .is_err() || self - .wait_stamp_for_with( + .wait_compute_stamps_for( &j2, - super::command::COMPUTE, o2.wait_through[super::command::COMPUTE], - None, ) .is_err() || !render_wait_ok(o2.wait_through[super::command::RENDER]) @@ -2307,7 +2486,9 @@ impl Firmware { .counter .w64(0, f.csubmitted[m])?; } - self.graph.compute.threshold.w32(0, prefix.n as u32)?; + self.graph.compute[compute_pipe] + .threshold + .w32(0, prefix.pipe_n as u32)?; } wmb(); if render { @@ -2319,7 +2500,7 @@ impl Firmware { self.graph.render.qstate[1].w32(qstate::WRITE, prefix.fs_head)?; } else { publish_producer( - &self.graph.compute.qstate, + &self.graph.compute[compute_pipe].qstate, prefix.c_head, &mut self.engine.stats.publications[0], )?; @@ -2330,10 +2511,10 @@ impl Firmware { for &channel in channels { let (qinfo, head, event, fresh) = match channel { Channel::Compute => ( - self.graph.compute.qinfo.va, + self.graph.compute[compute_pipe].qinfo.va, prefix.c_head, - 15, - !self.engine.queue_registered, + work::compute::EVENTS[compute_pipe] as u8, + !self.engine.queue_registered[compute_pipe], ), Channel::Ta => ( self.graph.render.qinfo[0].va, @@ -2385,9 +2566,11 @@ impl Firmware { self.engine.ta_registered = true; self.engine.render_registered = true; } else { - self.engine.target = f.target; - self.engine.head = f.head; - self.engine.queue_registered = true; + self.engine.pipe_ordinal[compute_pipe] = prefix.pipe_n; + self.engine.target[compute_pipe] = f.target; + self.engine.head[compute_pipe] = f.head; + self.engine.queue_registered[compute_pipe] = true; + self.engine.next_compute_pipe = (compute_pipe as u8) ^ 1; } self.engine.events = self.events.compute_events; self.engine.stage_seen = self.events.stage_events; @@ -2460,6 +2643,7 @@ impl Firmware { resources: &super::resources::Prepared, cmd_index: u32, cmd: &ComputeCommand, + c_waits: [Option; sizes::COMPUTE_PIPES], pf: &mut Prefix, f: &mut Flight, _later_render: bool, @@ -2468,16 +2652,19 @@ impl Firmware { if member >= sizes::COMPUTE_SLOTS { return Err(EAGAIN); } + let pipe = pf.compute_pipe; + let other = 1 - pipe; let n = super::recovery::logic::next_ordinal(pf.n).ok_or(EOVERFLOW)?; - let target = encode::stamp(n); + let pipe_n = super::recovery::logic::next_ordinal(pf.pipe_n).ok_or(EOVERFLOW)?; + let target = encode::stamp(pipe_n); let index = self .slots - .claim_compute_for(resources, &mut f.claims, Some(job.vm.id))? + .claim_compute_for_pipe(resources, &mut f.claims, Some(job.vm.id), pipe)? .ok_or(EAGAIN)?; let generation = job.vm.generation; self.slots.hold_compute_slot(index, &job.vm, resources)?; let s = resources.compute_unit(index)?; - let g = &self.graph.compute; + let g = &self.graph.compute[pipe]; let before = s.counter.r64(0)?; let submitted = before.checked_add(1).ok_or(EOVERFLOW)?; let refs = ComputeRefs { @@ -2504,6 +2691,7 @@ impl Firmware { // 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, + event: work::compute::EVENTS[pipe], // 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. @@ -2580,6 +2768,22 @@ impl Firmware { } else { None }; + let c2c_bar = if let Some(wait_c) = c_waits[other] { + let producer_initbm = wait_c.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); + let bar = encode::barrier( + self.graph.compute[other].fw_stamp.va, + wait_c.stamp, + work::compute::EVENTS[other], + target, + 0, + bar_type, + ); + s.barrier.write(work::barrier::SIZE, &bar)?; + true + } else { + false + }; f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); @@ -2594,11 +2798,19 @@ impl Firmware { } else { f.cwait[member] = 0; } + if c2c_bar { + g.ring.w64( + 8 * pf.c_head as usize, + s.barrier.va + work::barrier::SIZE as u64, + )?; + pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; + } g.ring.w64(8 * pf.c_head as usize, s.work.va)?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; f.cstamp[member] = target; pf.computes += 1; pf.n = n; + pf.pipe_n = pipe_n; pf.last_ct = target; pf.prev = Prev::Compute; Ok(()) @@ -2644,17 +2856,13 @@ impl Firmware { let staged = cmd.cmd.flags & kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES != 0; - let ta_wait_compute = self.wait_stamp_for_with( + let ta_wait_compute = self.wait_compute_stamps_for( job, - super::command::COMPUTE, order.and_then(|o| o.ta_wait_through[super::command::COMPUTE]), - None, )?; - let fs_wait_compute = self.wait_stamp_for_with( + let fs_wait_compute = self.wait_compute_stamps_for( job, - super::command::COMPUTE, order.and_then(|o| o.wait_through[super::command::COMPUTE]), - None, )?; let fs_wait_render = if has_prior_render { match order { @@ -2699,8 +2907,8 @@ impl Firmware { fs_wait_render.map(|w| w.stamp), ta_wait_fs.map(|w| w.stamp), [ - ta_wait_compute.map(|w| w.stamp), - fs_wait_compute.map(|w| w.stamp), + ta_wait_compute.map(|w| w.map(|t| t.stamp)), + fs_wait_compute.map(|w| w.map(|t| t.stamp)), ], cross_vm_prev, ); @@ -2836,8 +3044,8 @@ impl Firmware { // Cold `InitBM` transitions and recovery paths drain completely before publishing. let producer_initbm = pf.initbm || self.engine.flights.iter().any(|fl| fl.initbm) - || ta_wait_compute.is_some_and(|w| w.initbm) - || fs_wait_compute.is_some_and(|w| w.initbm) + || ta_wait_compute.iter().flatten().any(|w| w.initbm) + || fs_wait_compute.iter().flatten().any(|w| w.initbm) || fs_wait_render.is_some_and(|w| w.initbm) || ta_wait_fs.is_some_and(|w| w.initbm); let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer); @@ -2888,36 +3096,39 @@ impl Firmware { if plan.early { self.engine.stats.early += 1; } - if let Some(wait_c) = plan.ta_compute_wait { - let cbar = encode::barrier( - self.graph.compute.fw_stamp.va, - wait_c, - 15, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - p.compute_barrier.write(0, &cbar)?; - r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va)?; - pf.ta_head = (pf.ta_head + 1) % cap; - if render_bar == BarrierType::Stamp { - self.engine.stats.c2ta0 += 1; + for p_idx in 0..sizes::COMPUTE_PIPES { + let off = p_idx * work::barrier::SIZE; + if let Some(wait_c) = plan.ta_compute_wait[p_idx] { + let cbar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c, + work::compute::EVENTS[p_idx], + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.compute_barrier.write(off, &cbar)?; + r.ring[0].w64(8 * pf.ta_head as usize, p.compute_barrier.va + off as u64)?; + pf.ta_head = (pf.ta_head + 1) % cap; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } - } - if let Some(wait_c) = plan.fs_compute_wait { - let fcbar = encode::barrier( - self.graph.compute.fw_stamp.va, - wait_c, - 15, - target, - work::barrier::RENDER_WAIT_UUID, - render_bar, - ); - p.fs_compute_barrier.write(0, &fcbar)?; - r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va)?; - pf.fs_head = (pf.fs_head + 1) % cap; - if render_bar == BarrierType::Stamp { - self.engine.stats.c2ta0 += 1; + if let Some(wait_c) = plan.fs_compute_wait[p_idx] { + let fcbar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c, + work::compute::EVENTS[p_idx], + target, + work::barrier::RENDER_WAIT_UUID, + render_bar, + ); + p.fs_compute_barrier.write(off, &fcbar)?; + r.ring[1].w64(8 * pf.fs_head as usize, p.fs_compute_barrier.va + off as u64)?; + pf.fs_head = (pf.fs_head + 1) % cap; + if render_bar == BarrierType::Stamp { + self.engine.stats.c2ta0 += 1; + } } } // The paired fragment always requires the native explicit TA dependency. diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index 6716d3332a539e..d2f1463e7d21a0 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -3,7 +3,7 @@ //! M4 receive records. Events and statistics use complete 0x48-byte records. //! //! Type 1 carries 128 completion bits. The native runtime holds events 0x70 -//! (TA), 0x71 (fragment) and 15 (compute). Type 4 and statistics type 0x16 +//! (TA), 0x71 (fragment) and 15/16 (compute pipes 0/1). Type 4 and statistics type 0x16 //! announce the firmware's generation-based recovery; neither is a job receipt. use kernel::{bindings, device, prelude::*}; @@ -14,7 +14,7 @@ use super::hw::rings; use super::regs::{mb, rmb, wmb}; pub(crate) const RECORD_WORDS: usize = 18; -pub(crate) const STAGE_EVENTS: [u32; 3] = [0x70, 0x71, 15]; +pub(crate) const STAGE_EVENTS: [u32; 4] = [0x70, 0x71, 15, 16]; /// Retained only for the allocator's pending-growth container. M4 does not /// interpret a G15 type-7 record as an allocator request. pub(crate) const GROW_QUEUE: usize = 8; @@ -45,7 +45,7 @@ pub(crate) struct Events { /// First notification of the pending recovery, for its absolute deadline. pub(crate) recovery_started_ns: Option, pub(crate) channel_errors: u32, - pub(crate) event_ns: [u64; 3], + pub(crate) event_ns: [u64; 4], pub(crate) grow: KVec<[u32; 14]>, #[allow(dead_code)] pub(crate) grow_lost: u32, @@ -63,7 +63,7 @@ impl Events { last_statistics: None, recovery_started_ns: None, channel_errors: 0, - event_ns: [0; 3], + event_ns: [0; 4], grow: KVec::new(), grow_lost: 0, } @@ -125,7 +125,7 @@ impl Events { match kind { 1 => { // Type 1 carries 128 completion bits across words 1..=4; STAGE_EVENTS - // ([0x70, 0x71, 15]) only inspects word 1 (compute 15) and word 4 (TA/FS). + // ([0x70, 0x71, 15, 16]) inspects word 1 (compute 15/16) and word 4 (TA/FS). let (w1, w4) = match ring.ring.r32(base + 4).and_then(|w1| { Ok((w1, ring.ring.r32(base + 16)?)) }) { @@ -150,7 +150,7 @@ impl Events { self.stage_events = self.stage_events.wrapping_add(1); if stage == 1 { self.fs_events = self.fs_events.wrapping_add(1); - } else if stage == 2 { + } else if stage >= 2 { self.compute_events = self.compute_events.wrapping_add(1); } } diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index b6e9a734b4dad9..0bde4d35e88601 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -37,6 +37,8 @@ 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; +/// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. +pub(crate) const EVENTS: [u32; 2] = [EVENT, 16]; /// The binding generation. pub(crate) const GENERATION: usize = 0x88b; diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index de1a19b1a08177..4514454acbe15b 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -174,11 +174,10 @@ fn init_notifier(page: &FwObject, threshold: &FwObject) -> Result { } impl ComputeGraph { - fn new(o: &mut Objects) -> Result { + fn new(o: &mut Objects, sched_ctx: Arc) -> Result { let q = QueueObjects::new(o)?; Ok(Self { - // Host polls sched_ctx from WC during register_context(); keep uncached. - sched_ctx: alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?, + sched_ctx, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, @@ -190,8 +189,10 @@ impl ComputeGraph { fw_stamp: q.fw_stamp, }) } - fn init(&self, abi: FwAbi) -> Result { - self.sched_ctx.write(0, &graph::context_image())?; + fn init(&self, abi: FwAbi, init_ctx: bool) -> Result { + if init_ctx { + self.sched_ctx.write(0, &graph::context_image())?; + } init_notifier(&self.notifier, &self.threshold)?; self.notifier .w64(notifier_page::COMPUTE_RECORD, self.threshold.va)?; @@ -273,13 +274,19 @@ impl RenderGraph { pub(crate) struct Graphs { pub(crate) dev: ARef, - pub(crate) compute: ComputeGraph, + pub(crate) compute: [ComputeGraph; sizes::COMPUTE_PIPES], pub(crate) render: RenderGraph, } impl Graphs { pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { - let compute = ComputeGraph::new(o)?; - let render = RenderGraph::new(o, compute.sched_ctx.clone())?; + // Host polls sched_ctx from WC during register_context(); keep uncached and share one + // scheduling context across all compute pipes and the render graph. + let sched_ctx = alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?; + let compute = [ + ComputeGraph::new(o, sched_ctx.clone())?, + ComputeGraph::new(o, sched_ctx.clone())?, + ]; + let render = RenderGraph::new(o, sched_ctx)?; Ok(Self { dev: dev.as_ref().as_ref().into(), compute, @@ -294,7 +301,9 @@ impl Firmware { return Err(Error::from_errno(-(kernel::bindings::EPROTO as i32))); } } - self.graph.compute.init(self.init.abi)?; + for (pipe, compute) in self.graph.compute.iter().enumerate() { + compute.init(self.init.abi, pipe == 0)?; + } self.graph.render.init(self.init.abi)?; self.slots.init()?; self.init_render_pools(false)?; diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 72dcaf4e4b3c0b..31b28156527f6d 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -708,6 +708,8 @@ pub(crate) mod sizes { pub(crate) const POOL_SIZE: u64 = 0x200000; pub(crate) const FREELIST_SEED: u32 = 8192; pub(crate) const QUEUE_CAP: u32 = 256; + /// Independent firmware compute workqueue pipes sharing `Channel::Compute` and `sched_ctx`. + pub(crate) const COMPUTE_PIPES: usize = 2; /// Compute units claimable in one batched compute prefix (matches `COMPUTE_UNITS`). pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base physical PB/UMA allocator slots allocated per VM on first render. @@ -724,12 +726,14 @@ pub(crate) mod sizes { const _: () = assert!(super::client::render_descriptor(5) + 0x4000 <= super::client::render_base(0)); /// Worst-case firmware work-ring entries consumed per pipelined render pass on TA - /// (`prev_barrier`, `ta_fs_barrier`, `compute_barrier`, `ta_work`) and FS (`fs_dep`, - /// `fs_compute_barrier`, `own_barrier`, `fs_work`). `InitBM` runs only on an idle engine - /// (`initbm` + `ta_work` = 2 entries). - pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 4; - /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + `work`). - pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 2; + /// (`prev_barrier`, `ta_fs_barrier`, up to `COMPUTE_PIPES` `compute_barrier` entries, + /// `ta_work`) and FS (`fs_dep`, up to `COMPUTE_PIPES` `fs_compute_barrier` entries, + /// `own_barrier`, `fs_work`). `InitBM` runs only on an idle engine (`initbm` + `ta_work` = 2 + /// entries). + pub(crate) const MAX_RENDER_RING_ENTRIES: usize = 5; + /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + cross-pipe + /// `c2c` barrier + `work`). + pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 3; /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts pace /// TA in `<= 8`-pass waves without throttling single-pass pipelining (where TA finishes /// well ahead of FS). diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 3ab52248337680..6547895cceef8c 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -501,14 +501,51 @@ impl Job { 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)?; - self.queue.completed[order.engine] - .compare_exchange( - previous, - order.sequence, - Ordering::AcqRel, - Ordering::Acquire, - ) - .map_err(|_| EIO)?; + if order.engine != super::command::COMPUTE { + self.queue.completed[order.engine] + .compare_exchange( + previous, + order.sequence, + Ordering::AcqRel, + Ordering::Acquire, + ) + .map_err(|_| EIO)?; + return Ok(()); + } + // Concurrent 2-pipe compute commands on the same logical queue may retire out of + // sequence order. Record published out-of-order full receipts above `completed + 1` + // in `compute_ooo` and advance `completed[COMPUTE]` across contiguous retired runs. + let completed = self.queue.completed[super::command::COMPUTE].load(Ordering::Acquire); + if order.sequence <= completed { + return Err(EIO); + } + if order.sequence == completed + 1 { + let mut next = order.sequence; + let mut ooo = self.queue.compute_ooo.load(Ordering::Acquire); + while ooo & 1 != 0 { + next += 1; + ooo >>= 1; + } + // Re-anchor remaining OOO bits above `next + 1` (since `next` advanced by at least 1 + // and bit 0 of `ooo` is now `next + 1`, which is 0). + ooo >>= 1; + self.queue.compute_ooo.store(ooo, Ordering::Release); + self.queue.completed[super::command::COMPUTE] + .compare_exchange(completed, next, Ordering::AcqRel, Ordering::Acquire) + .map_err(|_| EIO)?; + return Ok(()); + } + let published = self.queue.published[super::command::COMPUTE].load(Ordering::Acquire); + let shift = order.sequence - completed - 2; + if order.sequence > published || shift >= 64 { + return Err(EIO); + } + let bit = 1u64 << shift; + let ooo = self.queue.compute_ooo.load(Ordering::Acquire); + if ooo & bit != 0 { + return Err(EIO); + } + self.queue.compute_ooo.store(ooo | bit, Ordering::Release); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 44e7a61cdaf304..ed93d1fd6469f3 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -51,7 +51,7 @@ pub(crate) fn compute_flights() -> usize { /// Render commands in flight at most: bounded by both retained pass slots /// (`RENDER_SLOTS - 1`, leaving one slot for displacement) and firmware TA/FS work-ring -/// capacity (`(QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES`, worst case 4 ring entries per pass). +/// capacity (`(QUEUE_CAP - 1) / MAX_RENDER_RING_ENTRIES`, worst case 5 ring entries per pass). /// Decoupled from `hw::sizes::FLIGHTS` because multi-pass render batches pack multiple passes /// into one `Flight`. pub(crate) fn render_flights() -> usize { diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index b651f331d350c6..857160a0b737f9 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -785,23 +785,25 @@ impl Firmware { self.engine.ta_wave_wait && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES } - /// Cheap single-stage stamp check for the oldest compute and oldest render flights' terminal - /// stages so `submit_locked()` can eagerly retire finished work without scanning all rings - /// when nothing has completed. + /// Cheap single-stage stamp check for the oldest compute pipe 0/1 and oldest render flights' + /// terminal stages so `submit_locked()` can eagerly retire finished work without scanning + /// all rings when nothing has completed. fn oldest_stamp_reached(&self) -> bool { if self.engine.flights.is_empty() { return false; } - let mut oldest_compute: Option<&Flight> = None; - let mut compute_behind = false; + let mut oldest_compute: [Option<&Flight>; super::hw::sizes::COMPUTE_PIPES] = + [None; super::hw::sizes::COMPUTE_PIPES]; + let mut compute_behind = [false; super::hw::sizes::COMPUTE_PIPES]; let mut oldest_render: Option<&Flight> = None; let mut render_behind = false; for f in self.engine.flights.iter() { if f.computes != 0 { - if oldest_compute.is_none() { - oldest_compute = Some(f); + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + if oldest_compute[p].is_none() { + oldest_compute[p] = Some(f); } else { - compute_behind = true; + compute_behind[p] = true; } } if f.renders != 0 { @@ -811,20 +813,22 @@ impl Firmware { render_behind = true; } } - if compute_behind && render_behind { + if compute_behind[0] && compute_behind[1] && render_behind { break; } } rmb(); - if let Some(f) = oldest_compute { - if let Ok(obs) = self.graph.compute.fw_stamp.r32(0) { - let reached = if compute_behind { - stamp_reached(obs, f.target, self.engine.target) - } else { - obs == f.target - }; - if reached { - return true; + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if let Some(f) = oldest_compute[p] { + if let Ok(obs) = self.graph.compute[p].fw_stamp.r32(0) { + let reached = if compute_behind[p] { + stamp_reached(obs, f.target, self.engine.target[p]) + } else { + obs == f.target + }; + if reached { + return true; + } } } } @@ -858,7 +862,7 @@ impl Firmware { return Ok(false); } let mut retired_any = false; - let (mut check_compute, mut check_render) = (true, true); + let (mut check_compute, mut check_render) = ([true; super::hw::sizes::COMPUTE_PIPES], true); let mut ret = self.retired_flight_classes(&mut check_compute, &mut check_render); while let Ok(Some((index, receipt))) = ret { let outcome = self.retire_outcome_at(index, receipt); @@ -909,17 +913,14 @@ impl Firmware { 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( + /// Exact queue-ring proof for one serialized publication on its workqueue pipe. + fn queue_ring_receipt( &self, - channel: Channel, state: &super::object::FwObject, info: &super::object::FwObject, head: u32, - record: u32, ) -> Result { - if head >= 256 || record >= 256 { + if head >= 256 { return Err(EINVAL); } // M4's qualified NC cursors are READ and WRITE. Offset zero is not an M4 @@ -941,17 +942,11 @@ impl Firmware { } // With ASC-cached QI, its three consumers and busy flag can remain stale until // terminal CIVAC. The working M4 protocol substitutes the NC READ cursor above. - let pipe = self.channels.channel(channel); - if pipe.read()? != record || pipe.completion()? != record || pipe.write()? != record { - return Ok(false); - } Ok(true) } - /// 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( + /// Passed queue-ring proof when later flights are queued behind `f` on the same pipe. + fn queue_ring_passed( &self, channel: Channel, state: &super::object::FwObject, @@ -959,10 +954,13 @@ impl Firmware { f: &Flight, ) -> Result { let cap = super::hw::sizes::QUEUE_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]), + let (start, head, tail) = match channel { + Channel::Compute => { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + (f.c_start, f.head, self.engine.head[p]) + } + Channel::Ta => (f.ta_start, f.ta_head, self.engine.ta_head), + Channel::Fs => (f.fs_start, f.fs_head, self.engine.fs_head), }; if head >= cap || start >= cap || tail >= cap { return Err(EINVAL); @@ -977,12 +975,58 @@ impl Firmware { } } } + Ok(true) + } + + /// Submit-channel proof for `record`: exact when no later record exists on `channel`, + /// otherwise passed within the current channel producer frontier. + fn channel_receipt(&self, channel: Channel, record: u32, passed: bool) -> Result { let slots = super::fw::channels::RING_SLOTS; - let first = (record + slots - 1) % slots; - let producer = self.channels.producer(channel); + if record >= slots { + return Err(EINVAL); + } let pipe = self.channels.channel(channel); - Ok(ring_passed(pipe.read()?, first, record, producer, slots) - && ring_passed(pipe.completion()?, first, record, producer, slots)) + if passed { + let first = (record + slots - 1) % slots; + let producer = self.channels.producer(channel); + Ok(ring_passed(pipe.read()?, first, record, producer, slots) + && ring_passed(pipe.completion()?, first, record, producer, slots)) + } else { + Ok(pipe.read()? == record && pipe.completion()? == record && pipe.write()? == record) + } + } + + /// 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( + &self, + channel: Channel, + state: &super::object::FwObject, + info: &super::object::FwObject, + head: u32, + record: u32, + ) -> Result { + Ok(self.queue_ring_receipt(state, info, head)? + && self.channel_receipt(channel, record, false)?) + } + + /// 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, + state: &super::object::FwObject, + info: &super::object::FwObject, + f: &Flight, + ) -> Result { + let record = match channel { + Channel::Compute => f.rec[2], + Channel::Ta => f.rec[0], + Channel::Fs => f.rec[1], + }; + Ok(self.queue_ring_passed(channel, state, info, f)? + && self.channel_receipt(channel, record, true)?) } /// A full receipt includes stage and notifier stamps, every physical consumer, @@ -1001,51 +1045,60 @@ impl Firmware { } } - /// Inspects the oldest compute flight and oldest render flight independently so either - /// class can retire as soon as its hardware receipt settles without waiting on the other. + /// Inspects the oldest compute flight per pipe and oldest render flight independently so any + /// pipe/class can retire as soon as its hardware receipt settles without waiting on another. pub(crate) fn retired_flight(&mut self) -> Result> { - let (mut check_compute, mut check_render) = (true, true); + let (mut check_compute, mut check_render) = ([true; super::hw::sizes::COMPUTE_PIPES], true); self.retired_flight_classes(&mut check_compute, &mut check_render) } - /// Like [`Self::retired_flight`], skipping classes that are inactive or already known + /// Like [`Self::retired_flight`], skipping pipes/classes that are inactive or already known /// pending in the current [`Self::retire_once`] pass and never polling a mixed flight twice. fn retired_flight_classes( &mut self, - check_compute: &mut bool, + check_compute: &mut [bool; super::hw::sizes::COMPUTE_PIPES], check_render: &mut bool, ) -> Result> { - let (mut compute_idx, mut render_idx) = (None, None); - if *check_compute || *check_render { + let mut compute_idx = [None; super::hw::sizes::COMPUTE_PIPES]; + let mut render_idx = None; + if check_compute[0] || check_compute[1] || *check_render { for (i, f) in self.engine.flights.iter().enumerate() { - if *check_compute && compute_idx.is_none() && f.computes != 0 { - compute_idx = Some(i); + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + if check_compute[p] && compute_idx[p].is_none() { + compute_idx[p] = Some(i); + } } if *check_render && render_idx.is_none() && f.renders != 0 { render_idx = Some(i); } - if (!*check_compute || compute_idx.is_some()) + if (!check_compute[0] || compute_idx[0].is_some()) + && (!check_compute[1] || compute_idx[1].is_some()) && (!*check_render || render_idx.is_some()) { break; } } } - if compute_idx.is_none() { - *check_compute = false; + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if compute_idx[p].is_none() { + check_compute[p] = false; + } } if render_idx.is_none() { *check_render = false; } - if let Some(index) = compute_idx { - let receipt = self.retired_at(index)?; - if receipt.complete() { - return Ok(Some((index, receipt))); - } - *check_compute = false; - if render_idx == Some(index) { - *check_render = false; - render_idx = None; + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if let Some(index) = compute_idx[p] { + let receipt = self.retired_at(index)?; + if receipt.complete() { + return Ok(Some((index, receipt))); + } + check_compute[p] = false; + if render_idx == Some(index) { + *check_render = false; + render_idx = None; + } } } if let Some(index) = render_idx { @@ -1069,33 +1122,45 @@ impl Firmware { rmb(); let mut full = true; let mut ticks = [0u64; 4]; - // Later flights of the same engine class queued behind this one: that class's queue, - // pipe and stamp cells already moved on, so its receipt is "passed", in order; the - // newest flight of a class keeps the exact receipt. + // Later flights of the same pipe/class queued behind this one: that pipe's queue and + // stamp cells already moved on, so its receipt is "passed", in order; the newest flight + // of a pipe keeps its exact queue receipt while Channel::Compute is checked independently + // against the shared submit-channel producer frontier. if f.computes != 0 { - let compute_behind = self + let pipe = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + let pipe_behind = self .engine .flights .iter() - .filter(|o| o.computes != 0) + .filter(|o| o.computes != 0 && o.compute_pipe == f.compute_pipe) .nth(1) .is_some(); - let g = &self.graph.compute; - if compute_behind { - 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)? + let chan_behind = self + .engine + .flights + .iter() + .filter(|o| o.computes != 0) + .nth(1) + .is_some() + || f.rec[2] != self.channels.producer(Channel::Compute); + let g = &self.graph.compute[pipe]; + if pipe_behind { + let tail = self.engine.target[pipe]; + if !stamp_reached(g.fw_stamp.r32(0)?, f.target, tail) + || !self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? + || !self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)? { return Ok(Retirement::Pending); } rmb(); let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; - full &= stamp_reached(stamp, f.target, e.target) + full &= stamp_reached(stamp, f.target, tail) && (stamp != f.target || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot); } else { if g.fw_stamp.r32(0)? != f.target - || !self.queue_receipt(Channel::Compute, &g.qstate, &g.qinfo, f.head, f.rec[2])? + || !self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? + || !self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)? { return Ok(Retirement::Pending); } @@ -1330,13 +1395,16 @@ impl Firmware { core::mem::forget(f); return; } - for &stamp in &f.cstamp[..(f.computes as usize).min(f.cstamp.len())] { - self.recovery.last_retired.push(0, stamp); + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + for &stamp in &f.cstamp[..(f.computes as usize).min(f.cstamp.len())] { + self.recovery.last_retired.push(p, stamp); + } } if f.renders != 0 { for m in 0..(f.renders as usize).min(f.r_ta_stamp.len()) { - self.recovery.last_retired.push(1, f.r_ta_stamp[m]); - self.recovery.last_retired.push(2, f.r_fs_stamp[m]); + self.recovery.last_retired.push(2, f.r_ta_stamp[m]); + self.recovery.last_retired.push(3, f.r_fs_stamp[m]); } let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { self.pools.retire_flight( @@ -1548,24 +1616,29 @@ impl Firmware { } } - /// Progress of the oldest compute and oldest render flights: a FW stamp of an engine on + /// Progress of the oldest compute pipe 0/1 and oldest render flights: a FW stamp of a pipe on /// which its oldest flight still has unreached work moved since the last poll. Renews the - /// deadline; the first call for a flight pair only records its position. + /// deadline; the first call for a flight only records its position. /// [`Self::check_hangs`] calls it while no firmware recovery notification is pending. pub(crate) fn progress(&mut self) { if self.engine.flights.is_empty() { return; } let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); - let (mut fc, mut fr) = (None, None); + let mut fc: [Option<&Flight>; super::hw::sizes::COMPUTE_PIPES] = + [None; super::hw::sizes::COMPUTE_PIPES]; + let mut fr = None; for f in e.flights.iter() { - if fc.is_none() && f.computes != 0 { - fc = Some(f); + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + if fc[p].is_none() { + fc[p] = Some(f); + } } if fr.is_none() && f.renders != 0 { fr = Some(f); } - if fc.is_some() && fr.is_some() { + if fc[0].is_some() && fc[1].is_some() && fr.is_some() { break; } } @@ -1573,22 +1646,26 @@ impl Firmware { // immediately after native wrap and must remain distinguishable from completion. let pending = |observed, own, tail| (!stamp_reached(observed, own, tail)).then_some(observed); - let (mut c, mut ta, mut fs) = (None, None, None); - let mut published = [0u64; 2]; - if let Some(fc) = fc { - c = pending(g.fw_stamp.r32(0).unwrap_or(0), fc.target, e.target); - published[0] = fc.published_ns; + let mut c = [None; super::hw::sizes::COMPUTE_PIPES]; + let (mut ta, mut fs) = (None, None); + let mut published = [0u64; 3]; + for p in 0..super::hw::sizes::COMPUTE_PIPES { + if let Some(f) = fc[p] { + c[p] = pending(g[p].fw_stamp.r32(0).unwrap_or(0), f.target, e.target[p]); + published[p] = f.published_ns; + } } if let Some(fr) = fr { ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), fr.ta_target, e.ta_target); fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); - published[1] = fr.published_ns; + published[2] = fr.published_ns; } - let compute_moved = - fc.is_some() && e.progress_flight[0] == published[0] && c != e.progress[0]; + let compute_moved = (0..super::hw::sizes::COMPUTE_PIPES).any(|p| { + fc[p].is_some() && e.progress_flight[p] == published[p] && c[p] != e.progress[p] + }); let render_moved = fr.is_some() - && e.progress_flight[1] == published[1] - && [ta, fs] != [e.progress[1], e.progress[2]]; + && e.progress_flight[2] == published[2] + && [ta, fs] != [e.progress[2], e.progress[3]]; if compute_moved { self.renew_compute_deadline(); } @@ -1596,7 +1673,7 @@ impl Firmware { self.renew_render_deadline(); } self.engine.progress_flight = published; - self.engine.progress = [c, ta, fs]; + self.engine.progress = [c[0], c[1], ta, fs]; } /// The device mutex still excludes slot reuse after owner-ledger retirement. Read the @@ -1775,12 +1852,12 @@ impl Firmware { if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); } - for b in 0..3 { + for b in 0..4 { let t = self.events.event_ns[b]; - let skip = if b == 2 { - f.computes == 0 - } else { - f.renders == 0 + let skip = match b { + 2 => f.computes == 0 || f.compute_pipe != 0, + 3 => f.computes == 0 || f.compute_pipe != 1, + _ => f.renders == 0, }; if skip { continue; @@ -1806,7 +1883,7 @@ impl Firmware { /// readiness and Flags words). #[allow(dead_code)] pub(crate) fn report(&self, what: &str) { - let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); + let (r, e) = (&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 @@ -1816,22 +1893,33 @@ impl Firmware { .flatten() .unwrap_or_default(); let f = e.oldest(); + let pipe = f + .map_or(0, |f| { + if f.computes != 0 { + f.compute_pipe as usize + } else { + 0 + } + }) + .min(super::hw::sizes::COMPUTE_PIPES - 1); + let g = &self.graph.compute[pipe]; let ms = f.map_or(0, |f| now_ns().wrapping_sub(f.published_ns) / 1_000_000); dev_info!( self.graph.dev.as_ref(), - "G16: {}: ctx={} prefixes={} n={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", + "G16: {}: ctx={} prefixes={} n={} pipe={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", what, f.map_or(0, |f| f.job.vm.slot), e.flights.len(), e.ordinal, - e.target, + pipe, + e.target[pipe], rd(&g.user_stamp, 0), rd(&g.fw_stamp, 0), rd(&g.qstate, qstate::DONE), rd(&g.qstate, qstate::READ), rd(&g.qstate, qstate::WRITE), - e.head, + e.head[pipe], ch.read(Channel::Compute).unwrap_or(0xdeadbeef), ch.write_cell(Channel::Compute).unwrap_or(0xdeadbeef), self.events.compute_events, diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 65aadde6637d2b..869e716b2b7e87 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -27,6 +27,7 @@ struct Unit { state: State, previous: State, generation: u8, + pipe: u8, publication: u64, } @@ -53,6 +54,7 @@ impl Lifetime { state: State::Fresh, previous: State::Fresh, generation: 0, + pipe: 0, publication: 0, }; Self { @@ -92,10 +94,13 @@ impl Lifetime { }; match u.state { State::Fresh => true, - // A later publication retired: it started only after this owner finished, and - // its load displaced this owner from the hardware slot. + // A later publication on the same hardware pipe retired: it started only after this + // owner finished on that pipe, and its load displaced this owner from the slot. State::Retired => self.units.iter().enumerate().any(|(b, other)| { - b != k && other.state == State::Retired && other.publication > u.publication + b != k + && other.state == State::Retired + && other.pipe == u.pipe + && other.publication > u.publication }), _ => false, } @@ -137,29 +142,42 @@ impl Lifetime { } } pub(crate) fn publish(&mut self, k: usize) -> bool { + self.publish_on(k, 0) + } + /// Publishes unit `k` onto hardware queue `pipe` (`0` for single-pipe engines, or the CDM + /// pipe index for dual-pipe compute). Each pipe enforces FIFO retirement and same-pipe + /// displacement independently while sharing a monotonic publication sequence. + pub(crate) fn publish_on(&mut self, k: usize, pipe: u8) -> bool { if k >= N || self.units[k].state != State::Preparing || self.sequence == u64::MAX { return false; } - // Without pipelining, publication is serialized against every owner of the slot. - if !self.pipelined && self.units.iter().any(|u| u.state == State::Published) { + // Without pipelining, publication is serialized against every owner on the same pipe. + if !self.pipelined + && self + .units + .iter() + .any(|u| u.state == State::Published && u.pipe == pipe) + { return false; } self.sequence += 1; + self.units[k].pipe = pipe; self.units[k].publication = self.sequence; self.units[k].state = State::Published; true } /// Called only after the caller has established complete, exact wire retirement. Owners - /// retire in publication order: `k` must be the oldest published owner. + /// retire in publication order per pipe: `k` must be the oldest published owner on its pipe. pub(crate) fn retire(&mut self, k: usize) -> bool { if k >= N || self.units[k].state != State::Published { return false; } let publication = self.units[k].publication; + let pipe = self.units[k].pipe; if self .units .iter() - .any(|u| u.state == State::Published && u.publication < publication) + .any(|u| u.state == State::Published && u.pipe == pipe && u.publication < publication) { return false; } @@ -303,4 +321,27 @@ mod tests { assert!(l.available(0)); assert!(!l.available(2)); } + #[test] + fn two_pipes_retire_out_of_order_and_displace_independently() { + let mut l = Lifetime::<4>::new(true); + // Publish unit 0 on pipe 0, then unit 2 on pipe 1. + assert!(l.claim(0) && l.publish_on(0, 0)); + assert!(l.claim(2) && l.publish_on(2, 1)); + // Pipe 1 finishes ahead of pipe 0: out-of-order retirement across pipes must succeed. + assert!(l.retire(2)); + // Pipe 1's second publication (unit 3) retires and displaces unit 2 on pipe 1. + assert!(l.claim(3) && l.publish_on(3, 1)); + assert!(l.retire(3)); + assert!(l.available(2)); + assert!(!l.available(3)); + // Pipe 0's unit 0 now retires: unit 3 (pipe 1, higher publication) must NOT displace it. + assert!(l.retire(0)); + assert!(!l.available(0)); + // Pipe 0's next publication (unit 1) retires and displaces unit 0 on pipe 0. + assert!(l.claim(1) && l.publish_on(1, 0)); + assert!(l.retire(1)); + assert!(l.available(0)); + assert!(!l.available(1)); + assert!(!l.available(3)); + } } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index f85ff71b7058a5..08cf2543c9c244 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -60,9 +60,13 @@ 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 + /// Out-of-order full compute receipts strictly above `completed[COMPUTE] + 1` (bit `k` + /// records ordinal `completed[COMPUTE] + 2 + k`), enabling concurrent 2-pipe completion. + pub(crate) compute_ooo: AtomicU64, + /// Published command frontier per engine. The firmware runs each queue pipe in /// publication order, each command to its Finalize, so a compute command may follow its - /// published (not yet retired) compute predecessors. + /// published (not yet retired) compute predecessors (on the same pipe or via a cross-pipe + /// barrier). 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. @@ -96,6 +100,17 @@ impl QueueState { } Ok(()) } + + /// Whether compute ordinal `seq` already has a full successful firmware receipt, either + /// at or below the contiguous `completed[COMPUTE]` frontier or recorded in `compute_ooo`. + pub(crate) fn is_compute_retired(&self, seq: u64) -> bool { + let completed = self.completed[command::COMPUTE].load(Ordering::Acquire); + if seq <= completed { + return true; + } + let shift = seq.wrapping_sub(completed).wrapping_sub(2); + shift < 64 && (self.compute_ooo.load(Ordering::Acquire) & (1u64 << shift)) != 0 + } } /// One per-file logical-queue credit, released after the queue scheduler drains. @@ -176,6 +191,7 @@ impl Queue { cancelled_at: [const { AtomicU64::new(0) }; 2], turn: AtomicU64::new(0), completed: [const { AtomicU64::new(0) }; 2], + compute_ooo: AtomicU64::new(0), 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 a72e4b9c7819f5..9f20506a0b0f95 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -57,7 +57,7 @@ pub(crate) struct Recovery { warning_deadline_ns: [u64; 2], pub(crate) long_commands: u64, pub(crate) publication_wait_deadline: Option, - /// Recently retired compute/TA/FS stamps, for late recovery snapshots. + /// Recently retired compute pipe 0/1 and TA/FS stamps, for late recovery snapshots. pub(crate) last_retired: logic::RetiredStamps, /// Queue engine order: render, compute. A quarantined/exhausted class stays offline. pub(crate) unavailable: [Option; 2], @@ -387,7 +387,7 @@ impl Firmware { /// 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 { + fn mark_recovery(&mut self, stage: [u32; 4], event: u32, asid: Option) -> Result { let data = self.init.firmware_data(); for i in 0..data.snapshot_entries { let offset = data.snapshot + i * 8; diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index a8eeb00b9591d0..f93b2cd35f4ffe 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -126,27 +126,27 @@ impl SnapshotEntry { /// Bounded per-stage history of recently retired firmware stamps. pub(crate) const RETIRED_STAMPS_CAP: usize = 64; -/// Bounded per-stage ring of recently retired compute/TA/FS firmware stamps so a late -/// recovery snapshot arriving after pipelined retirement resolves any recently retired -/// member, not only the single newest flight. +/// Bounded per-stage ring of recently retired compute pipe 0/1 and TA/FS firmware stamps +/// so a late recovery snapshot arriving after pipelined retirement resolves any recently +/// retired member, not only the single newest flight. #[derive(Clone, Debug)] pub(crate) struct RetiredStamps { - stamps: [[u32; RETIRED_STAMPS_CAP]; 3], - len: [u8; 3], - next: [u8; 3], + stamps: [[u32; RETIRED_STAMPS_CAP]; 4], + len: [u8; 4], + next: [u8; 4], } impl RetiredStamps { pub(crate) const fn new() -> Self { Self { - stamps: [[0; RETIRED_STAMPS_CAP]; 3], - len: [0; 3], - next: [0; 3], + stamps: [[0; RETIRED_STAMPS_CAP]; 4], + len: [0; 4], + next: [0; 4], } } pub(crate) fn push(&mut self, stage: usize, target: u32) { - if stage >= 3 { + if stage >= 4 { return; } let idx = self.next[stage] as usize; @@ -160,8 +160,9 @@ impl RetiredStamps { pub(crate) fn contains(&self, event: u32, target: u32) -> bool { let stage = match event { 15 => 0, - 0x70 => 1, - 0x71 => 2, + 16 => 1, + 0x70 => 2, + 0x71 => 3, _ => return false, }; let len = self.len[stage] as usize; @@ -214,9 +215,10 @@ mod tests { let mut retired = RetiredStamps::new(); assert!(!retired.contains(0x70, 0)); retired.push(0, 0x100); - retired.push(1, 0); - retired.push(2, 0x200); - for (event, target) in [(15, 0x100), (0x70, 0), (0x71, 0x200)] { + retired.push(1, 0x300); + retired.push(2, 0); + retired.push(3, 0x200); + for (event, target) in [(15, 0x100), (16, 0x300), (0x70, 0), (0x71, 0x200)] { assert!(retired.contains(event, target)); assert!(!retired.contains(event, target.wrapping_add(0x100))); } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index bb85a172bebc6d..7bcb1ca24913c4 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -68,7 +68,15 @@ impl ComputeSlot { )?, work: alloc_work(o, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?, seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, - barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. + barrier: alloc( + o, + barrier::SIZE * sizes::COMPUTE_PIPES, + cmd_fw(), + None, + 0, + false, + )?, pool: o.alloc(super::object::Request { size: 0x2000000, class: sh, @@ -263,8 +271,22 @@ impl PassSlot { prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, ta_fs_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - compute_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - fs_compute_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, + compute_barrier: alloc( + o, + barrier::SIZE * sizes::COMPUTE_PIPES, + cmd_fw(), + None, + 0, + false, + )?, + fs_compute_barrier: alloc( + o, + barrier::SIZE * sizes::COMPUTE_PIPES, + cmd_fw(), + None, + 0, + false, + )?, }) } @@ -371,6 +393,7 @@ impl PassSlot { pub(crate) struct Claims { pub(crate) slot: [u32; sizes::COMPUTE_SLOTS], pub(crate) slot_count: u32, + pub(crate) compute_pipe: u8, pub(crate) pass: [u32; sizes::RENDER_SLOTS], pub(crate) pass_count: u32, pub(crate) pass_mask: u64, @@ -388,6 +411,7 @@ impl Claims { Self { slot: [0; sizes::COMPUTE_SLOTS], slot_count: 0, + compute_pipe: 0, pass: [0; sizes::RENDER_SLOTS], pass_count: 0, pass_mask: 0, @@ -765,6 +789,18 @@ impl Slots { 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` compute units eligible for `pipe` can be claimed now. + /// Pipe 0 may claim `0..n`; secondary pipes stay in `BASE_COMPUTE_UNITS..n` so a 2-unit + /// base-only VM can never see both base units undisplaced across two pipes. + pub(crate) fn compute_available_for_pipe(&self, n: usize, pipe: usize) -> bool { + let limit = n.min(sizes::COMPUTE_UNITS); + let start = if pipe == 0 { + 0 + } else { + super::resources::BASE_COMPUTE_UNITS.min(limit) + }; + (start..limit).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 { @@ -883,7 +919,17 @@ impl Slots { } /// Available compute units within the first `n` units (a VM's prepared count). pub(crate) fn free_compute_in(&self, n: usize) -> u32 { - (0..n.min(sizes::COMPUTE_UNITS)) + self.free_compute_in_for_pipe(n, 0) + } + /// Available compute units within the first `n` units eligible for `pipe`. + pub(crate) fn free_compute_in_for_pipe(&self, n: usize, pipe: usize) -> u32 { + let limit = n.min(sizes::COMPUTE_UNITS); + let start = if pipe == 0 { + 0 + } else { + super::resources::BASE_COMPUTE_UNITS.min(limit) + }; + (start..limit) .filter(|&k| self.compute.lifetime.available(k)) .count() as u32 } @@ -931,20 +977,42 @@ impl Slots { self.compute.last_full.get(k).copied().unwrap_or(true) } + #[allow(dead_code)] pub(crate) fn claim_compute_for( &mut self, units: &super::resources::Prepared, f: &mut Claims, vm_id: Option, + ) -> Result> { + self.claim_compute_for_pipe(units, f, vm_id, 0) + } + + pub(crate) fn claim_compute_for_pipe( + &mut self, + units: &super::resources::Prepared, + f: &mut Claims, + vm_id: Option, + pipe: usize, ) -> Result> { if f.slot_count as usize >= f.slot.len() { return Ok(None); } - // 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. + // Round robin over this VM's units eligible for `pipe`: pipe 0 spans `0..n`, while + // secondary pipes stay in `BASE_COMPUTE_UNITS..n` so base units `0..2` only ever hold + // pipe-0 leases and a 2-unit VM can never hit `compute_exhausted_within(2)`. let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); - for i in 0..n { - let k = (self.cursor as usize + i) % n; + let start = if pipe == 0 { + 0 + } else { + super::resources::BASE_COMPUTE_UNITS + }; + if start >= n { + return Ok(None); + } + let span = n - start; + let base_cursor = (self.cursor as usize).saturating_sub(start) % span; + for i in 0..span { + let k = start + (base_cursor + i) % span; if self.compute.lifetime.claim(k) { let full = self.compute.scrub_full[k] || vm_id.is_none_or(|id| { @@ -959,6 +1027,7 @@ impl Slots { self.compute.last_full[k] = full; f.slot[f.slot_count as usize] = k as u32; f.slot_count += 1; + f.compute_pipe = pipe as u8; self.cursor = ((k + 1) % n) as u32; return Ok(Some(k)); } @@ -1394,7 +1463,7 @@ impl Slots { let mut c = self.compute.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) { + if !c.publish_on(k as usize, f.compute_pipe) { return Err(EBUSY); } } @@ -1473,6 +1542,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; @@ -1495,6 +1565,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; @@ -1521,6 +1592,7 @@ impl Slots { } self.pass_busy &= !f.pass_mask; f.slot_count = 0; + f.compute_pipe = 0; f.pass_count = 0; f.pass_mask = 0; f.ct_count = 0; 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 fb18eeabdaf83e..a9bdf0a390089d 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 @@ -249,7 +249,7 @@ fn compute_work(out: &std::path::Path) { 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, + compute_index: 8, work_818: 0, target_stamp: 0x900, submitted: 5, event: compute::EVENT, }; let c = uapi::drm_asahi_cmd_compute { cdm_ctrl_stream_base: g + 0x300000, cdm_ctrl_stream_end: g + 0x300200, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs index 330b1ac2bd1466..62fb9222460f81 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs @@ -32,7 +32,8 @@ fn refs(variant:u64)->encode::ComputeRefs { 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:if variant&1!=0{1<<40}else{0},record_fw:if variant&1!=0{f+0x700000}else{0}, - binding_generation:1,uma_slot:1,command_id:1,compute_index:0,work_818:0,target_stamp:0x100,submitted:1, + binding_generation:1,uma_slot:1,command_id:1,compute_index:0,work_818:0, + target_stamp:0x100,submitted:1,event:compute::EVENT, } } @@ -85,6 +86,18 @@ fn main(){ assert_eq!(&q[0x3c..0x40],&opaque.to_le_bytes()); assert_eq!(&w[0x810..0x814],&target.to_le_bytes()); } + // Second concurrent compute pipe uses event 16 at w+0x814 and q+0x1b8. + { + let r_p1 = encode::ComputeRefs { event: compute::EVENTS[1], ..refs(0) }; + let c = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: 0x1000300000, + cdm_ctrl_stream_end: 0x1000300200, + }; + let mut w=[0xa5;compute::WORK_SIZE];let mut q=[0x5a;compute::SEQ_SIZE]; + encode::encode_compute(&r_p1,&c,&[],&[0;2],1,1,1,&mut w,&mut q).unwrap(); + assert_eq!(&w[0x814..0x818],&compute::EVENTS[1].to_le_bytes()); + assert_eq!(&q[0x1b8..0x1bc],&compute::EVENTS[1].to_le_bytes()); + } let mut cases=0; let r=refs(0);let c=uapi::drm_asahi_cmd_compute {cdm_ctrl_stream_base:0x1000300000,cdm_ctrl_stream_end:0x1000300200}; let invalid:Vec<(encode::ComputeRefs,u32)>=vec![ @@ -93,6 +106,7 @@ fn main(){ (encode::ComputeRefs {uma_slot:0,..r},1),(encode::ComputeRefs {uma_slot:33,..r},1), (encode::ComputeRefs {target_stamp:0x101,..r},1), (encode::ComputeRefs {submitted:0,..r},1), + (encode::ComputeRefs {event:0,..r},1),(encode::ComputeRefs {event:128,..r},1), (encode::ComputeRefs {work:0xfffffc1ffffffff8,..r},1), (encode::ComputeRefs {work:0xfffffc2ffbfff000,..r},1), (encode::ComputeRefs {seq:0xfffffc2ffbffff00,..r},1), 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 d7058193d57395..6cbe422995dffb 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 @@ -32,7 +32,7 @@ def function_from(text, marker_text): def function(text, name): return function_from(text, 'fn ' + name + '(') -queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check']) +queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'is_compute_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']) push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) @@ -99,8 +99,8 @@ def function(text, name): self.signals.lock().unwrap().push((result,status)); } } -mod command { pub(crate) use super::Order; } -struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2] } +mod command { pub(crate) use super::{Order, COMPUTE}; } +struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2],compute_ooo:AtomicU64 } 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:AtomicU64,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } @@ -180,7 +180,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],published:[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],compute_ooo:AtomicU64::new(0)})) } 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)), @@ -342,7 +342,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],published:[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],compute_ooo:AtomicU64::new(0)}); 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(); @@ -356,7 +356,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],published:[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],compute_ooo:AtomicU64::new(0)}); 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(), @@ -544,7 +544,44 @@ def function(text, name): assert!(w3.upgrade().is_none(), "drm_sched job must not be retained by Scheduler after run"); assert!(w4.upgrade().is_none(), "queued job must not be retained by Scheduler after run"); } -'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::')).replace('PUSH_METHOD', push_method) +#[test] +fn compute_ooo_retirement_tracks_gaps_and_rejects_unpublished_or_duplicate() { + let queue=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(4)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + 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(), + Order::new([0,0],[0,2],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,3],[NONE;2],[0;2],1).unwrap(), + Order::new([0,0],[0,4],[NONE;2],[0;2],1).unwrap(), + ]; + let qjob=job_with_orders(1,Arc::new(Status::new()),vec![],orders,queue.clone()); + // Unpublished sequence 5 cannot retire OOO. + assert_eq!(qjob.command_retired(4),Err(EIO)); + // Sequences 2 and 4 retire OOO before 1 and 3. + qjob.command_retired(1).unwrap(); + qjob.command_retired(3).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),0); + assert!(!queue.is_compute_retired(1)); + assert!(queue.is_compute_retired(2)); + assert!(!queue.is_compute_retired(3)); + assert!(queue.is_compute_retired(4)); + // Duplicate OOO retirement is rejected. + assert_eq!(qjob.command_retired(1),Err(EIO)); + assert_eq!(qjob.command_retired(3),Err(EIO)); + // Retiring 1 advances contiguous frontier to 2 and re-anchors bit 0 to seq 4! + qjob.command_retired(0).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),2); + assert!(queue.is_compute_retired(1)); + assert!(queue.is_compute_retired(2)); + assert!(!queue.is_compute_retired(3)); + assert!(queue.is_compute_retired(4)); + assert_eq!(qjob.command_retired(3),Err(EIO)); + // Retiring 3 drains seq 4 as well, advancing contiguous frontier to 4 with clean bitmap. + qjob.command_retired(2).unwrap(); + assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),4); + assert_eq!(queue.compute_ooo.load(Ordering::Acquire),0); +} +'''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: directory=pathlib.Path(directory); test=directory/'test.rs'; test.write_text(harness) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 418591eade9eb3..f2d13a6a708049 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -66,6 +66,7 @@ def item(declaration, text=source): mod hw { pub mod sizes { pub const TA_WAVE_PASSES: usize = 8; + pub const COMPUTE_PIPES: usize = 2; } } @@ -125,7 +126,7 @@ def item(declaration, text=source): fw_stamp: [Cell32; 2], } struct Graph { - compute: ComputeGraph, + compute: [ComputeGraph; 2], render: RenderGraph, } @@ -143,6 +144,7 @@ def item(declaration, text=source): struct Flight { computes: u32, + compute_pipe: u8, renders: u32, target: u32, fs_target: u32, @@ -152,7 +154,7 @@ def item(declaration, text=source): shared: Option>, flights: Vec, pending: Vec>, - target: u32, + target: [u32; 2], fs_target: u32, chan_wait: bool, slot_wait: bool, @@ -301,9 +303,14 @@ def item(declaration, text=source): session: Session, objects: Objects, graph: Graph { - compute: ComputeGraph { - fw_stamp: Cell32::new(0), - }, + compute: [ + ComputeGraph { + fw_stamp: Cell32::new(0), + }, + ComputeGraph { + fw_stamp: Cell32::new(0), + }, + ], render: RenderGraph { fw_stamp: [Cell32::new(0), Cell32::new(0)], }, @@ -312,7 +319,7 @@ def item(declaration, text=source): shared: None, flights: vec![], pending: vec![], - target: 0, + target: [0; 2], fs_target: 0, chan_wait: false, slot_wait: false, @@ -416,12 +423,13 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x100, fs_target: 0, }); - fw.engine.target = 0x100; - fw.graph.compute.fw_stamp.set(0x100); + fw.engine.target[0] = 0x100; + fw.graph.compute[0].fw_stamp.set(0x100); fw.retire_on_call = true; let mut done = vec![]; @@ -443,6 +451,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x100, @@ -464,6 +473,7 @@ def item(declaration, text=source): let mut fw_ta = Firmware::new(); fw_ta.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x100, @@ -490,17 +500,19 @@ def item(declaration, text=source): fw.last_housekeeping_ns = 1_000_000; fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x100, fs_target: 0, }); fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x200, fs_target: 0, }); - fw.engine.target = 0x200; + fw.engine.target[0] = 0x200; let mut done = vec![]; shared @@ -539,11 +551,12 @@ def item(declaration, text=source): fw.last_housekeeping_ns = 1_000_000; fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x100, fs_target: 0, }); - fw.engine.target = 0x100; + fw.engine.target[0] = 0x100; let mut retry_tail = false; let mut deferred = false; let mut done = vec![]; @@ -572,6 +585,7 @@ def item(declaration, text=source): fw.last_aux_drain_ns = 1_000_000; fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x100, fs_target: 0, @@ -608,6 +622,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x100, @@ -634,6 +649,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x100, @@ -666,41 +682,69 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x200, }); fw.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x100, fs_target: 0, }); fw.engine.fs_target = 0x200; - fw.engine.target = 0x100; + fw.engine.target[0] = 0x100; // Render still running, compute reached its stamp. fw.graph.render.fw_stamp[1].set(0x100); - fw.graph.compute.fw_stamp.set(0x100); + fw.graph.compute[0].fw_stamp.set(0x100); assert!(fw.oldest_stamp_reached()); - assert_eq!(fw.graph.compute.fw_stamp.reads.get(), 1); + assert_eq!(fw.graph.compute[0].fw_stamp.reads.get(), 1); assert_eq!(fw.graph.render.fw_stamp[1].reads.get(), 0); assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); + + // Pipe 1 reaching its stamp behind a pending pipe 0 flight also wakes inline retirement. + let mut fw2 = Firmware::new(); + fw2.engine.flights.push(Flight { + computes: 1, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw2.engine.flights.push(Flight { + computes: 1, + compute_pipe: 1, + renders: 0, + target: 0x100, + fs_target: 0, + }); + fw2.engine.target = [0x200, 0x100]; + fw2.graph.compute[0].fw_stamp.set(0x100); + fw2.graph.compute[1].fw_stamp.set(0x100); + assert!(fw2.oldest_stamp_reached()); + assert_eq!(fw2.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fw2.graph.compute[1].fw_stamp.reads.get(), 1); + assert_eq!(fw2.graph.render.fw_stamp[1].reads.get(), 0); } #[test] fn oldest_stamp_reached_skips_inactive_class_wc_reads() { - // Compute-only workload never reads render fw_stamp. + // Compute-only workload never reads render fw_stamp or idle compute pipe 1. let mut fc = Firmware::new(); fc.engine.flights.push(Flight { computes: 1, + compute_pipe: 0, renders: 0, target: 0x200, fs_target: 0, }); - fc.engine.target = 0x200; - fc.graph.compute.fw_stamp.set(0x100); + fc.engine.target[0] = 0x200; + fc.graph.compute[0].fw_stamp.set(0x100); assert!(!fc.oldest_stamp_reached()); - assert_eq!(fc.graph.compute.fw_stamp.reads.get(), 1); + assert_eq!(fc.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fc.graph.compute[1].fw_stamp.reads.get(), 0); assert_eq!(fc.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fc.graph.render.fw_stamp[1].reads.get(), 0); @@ -708,6 +752,7 @@ def item(declaration, text=source): let mut fr = Firmware::new(); fr.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x200, @@ -715,7 +760,8 @@ def item(declaration, text=source): fr.engine.fs_target = 0x200; fr.graph.render.fw_stamp[1].set(0x100); assert!(!fr.oldest_stamp_reached()); - assert_eq!(fr.graph.compute.fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); } @@ -726,6 +772,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 1, target: 0, fs_target: 0x100, @@ -794,6 +841,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 11, target: 0, fs_target: 0x100, @@ -848,6 +896,7 @@ def item(declaration, text=source): let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, + compute_pipe: 0, renders: 8, target: 0, fs_target: 0x800, @@ -896,7 +945,7 @@ def item(declaration, text=source): const STATE_WRITE: usize = 0x40; const RING_SLOTS: u32 = 128; const RECORD_WORDS: usize = 18; - const STAGE_EVENTS: [u32; 3] = [0x70, 0x71, 15]; + const STAGE_EVENTS: [u32; 4] = [0x70, 0x71, 15, 16]; mod rings { pub const EVENT_RECORD: usize = 0x48; } @@ -984,7 +1033,7 @@ def item(declaration, text=source): ta_events: u32, fs_events: u32, compute_events: u32, - event_ns: [u64; 3], + event_ns: [u64; 4], errors: u32, channel_errors: u32, recovery_started_ns: Option, @@ -1018,7 +1067,8 @@ def item(declaration, text=source): #[test] fn event_drain_batches_state_read_and_minimizes_wc_reads() { let ring = Ring::new(); - // 3 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), Compute (15 -> word 1 bit 15). + // 4 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), + // Compute pipe 0 (15 -> word 1 bit 15), Compute pipe 1 (16 -> word 1 bit 16). let mut r0 = [0u32; RECORD_WORDS]; r0[0] = 1; r0[4] = 1 << 16; @@ -1028,22 +1078,28 @@ def item(declaration, text=source): let mut r2 = [0u32; RECORD_WORDS]; r2[0] = 1; r2[1] = 1 << 15; + let mut r3 = [0u32; RECORD_WORDS]; + r3[0] = 1; + r3[1] = 1 << 16; ring.put_record(0, &r0); ring.put_record(1, &r1); ring.put_record(2, &r2); - ring.set_indices(0, 3); + ring.put_record(3, &r3); + ring.set_indices(0, 4); let mut ev = Events::default(); ev.drain(&device::Device, &ring).unwrap(); assert_eq!(ev.event_ns[0], 12345); + assert_eq!(ev.event_ns[2], 12345); + assert_eq!(ev.event_ns[3], 12345); assert_eq!(ev.fs_events, 1); - assert_eq!(ev.compute_events, 1); - assert_eq!(ev.stage_events, 3); - assert_eq!(ring.read_idx(), 3); - // Exactly ONE STATE_READ write for all 3 records! + assert_eq!(ev.compute_events, 2); + assert_eq!(ev.stage_events, 4); + assert_eq!(ring.read_idx(), 4); + // Exactly ONE STATE_READ write for all 4 records! assert_eq!(ring.state.writes.get(), 1); - // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 9 reads (not 54)! - assert_eq!(ring.ring.reads.get(), 9); + // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 12 reads (not 72)! + assert_eq!(ring.ring.reads.get(), 12); } #[test] diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index a5906f690c6a95..0942af9db869a5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -9,7 +9,7 @@ def function(text,name): marker=text.index('fn '+name+'(');start=text.rfind('\n',0,marker)+1;at=text.index('{',marker);depth,end=1,at+1 while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1 return text[start:end] -option='progress: [Option; 3]' in engine +option='progress: [Option; 4]' in engine harness=r''' #![allow(dead_code)] use std::cell::Cell; @@ -18,6 +18,7 @@ def function(text,name): #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EIO:Error=Error(5);const ETIMEDOUT:Error=Error(110); type Result=core::result::Result; +mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=2;}} mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} mod params{ pub fn recovery()->bool{true} @@ -30,9 +31,9 @@ def function(text,name): macro_rules! dev_warn{($($tt:tt)*)=>{};} macro_rules! dev_err{($($tt:tt)*)=>{};} struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} -struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:Compute,render:Render} -struct Flight{computes:u32,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} -struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,progress_flight:[u64;2],progress:[__TYPE__;3]} +struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;2],render:Render} +struct Flight{computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} +struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,progress_flight:[u64;3],progress:[__TYPE__;4]} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} struct Recovery{deadline_ns:u64,compute_deadline_ns:u64,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,fail_stops:Vec} @@ -60,21 +61,21 @@ def function(text,name): type Completions=(); fn firmware(render:bool,target:u32,previous:u32)->Firmware{ set_now_ns(1_000_000_000); - let mut f=Firmware{graph:Graph{compute:Compute{fw_stamp:Object(Cell::new(previous))},render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target,ta_target:target,fs_target:target,progress_flight:[0;2],progress:[__ZERO__;3]}, + let mut f=Firmware{graph:Graph{compute:[Compute{fw_stamp:Object(Cell::new(previous))},Compute{fw_stamp:Object(Cell::new(previous))}],render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, recovery:Recovery{deadline_ns:u64::MAX,compute_deadline_ns:u64::MAX,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, render_renewed:0,compute_renewed:0,fail_stops:vec![]}; f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f } #[test]fn pending_native_zero_and_reached_are_distinct_progress_states(){ let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.compute_renewed,0);f.progress();assert_eq!(f.compute_renewed,0); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); + f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); assert_eq!(f.render_renewed,0); f.progress();assert_eq!(f.compute_renewed,1,"repeated completed stamp is not new progress"); } #[test]fn paired_ta_fs_zero_each_renews_once_without_lending_other_engine_progress(){ let mut f=firmware(true,0x100,0);f.progress(); - f.graph.compute.fw_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); + f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.render_renewed,1);assert_eq!(f.compute_renewed,0); f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.render_renewed,2);assert_eq!(f.compute_renewed,0); f.progress();assert_eq!(f.render_renewed,2); @@ -82,32 +83,45 @@ def function(text,name): #[test]fn before_at_and_after_zero_completions_have_the_same_progress_contract(){ for target in [0x7fffff00u32,0x80000000,0xffffff00,0,0x100]{ let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.compute_renewed,0); - f.graph.compute.fw_stamp.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); + f.graph.compute[0].fw_stamp.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); f.engine.flights[0].published_ns=2;f.progress();assert_eq!(f.compute_renewed,1,"new flight first sample is not forward progress"); } } #[test]fn concurrent_compute_and_render_renew_deadlines_independently(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); - f.engine.target=0x300; + f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); - f.graph.compute.fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); + f.graph.compute[0].fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); f.graph.render.fw_stamp[0].0.set(0x200);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(1,1)); } +#[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target=[0x200,0x200]; + f.progress();assert_eq!(f.compute_renewed,0); + // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. + f.graph.compute[1].fw_stamp.0.set(0x200); + f.progress();assert_eq!(f.compute_renewed,1); + f.progress();assert_eq!(f.compute_renewed,1); + // Pipe 0 advances independently -> renews compute deadline a second time. + f.graph.compute[0].fw_stamp.0.set(0x200); + f.progress();assert_eq!(f.compute_renewed,2); +} #[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); - f.engine.target=0x300; + f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),Ok(())); // Compute keeps advancing and retiring every 400 ms across 1.2 s while render stays stuck at 0x100. for step in 1u64..=3 { set_now_ns(1_000_000_000 + step * 400_000_000); let next_target = 0x300 + (step as u32) * 0x100; - f.graph.compute.fw_stamp.0.set(next_target - 0x100); + f.graph.compute[0].fw_stamp.0.set(next_target - 0x100); f.engine.flights[1].target = next_target; f.engine.flights[1].published_ns = 2 + step; - f.engine.target = next_target; + f.engine.target[0] = next_target; f.renew_compute_deadline(); let res = f.check_hangs(&mut done); if step < 3 { @@ -121,7 +135,7 @@ def function(text,name): } #[test]fn stuck_compute_times_out_while_render_keeps_advancing_and_retiring(){ let mut f=firmware(false,0x200,0x100); - f.engine.flights.push(Flight{computes:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); + f.engine.flights.push(Flight{computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); f.engine.ta_target=0x300;f.engine.fs_target=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),Ok(())); @@ -147,7 +161,7 @@ def function(text,name): } } } -'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') +'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress').replace('super::hw::','hw::')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') unit=out/'progress-wrap.rs';unit.write_text(harness);log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'progress-wrap')],[str(out/'progress-wrap'),'--nocapture']]: result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True);log+=result.stdout;print(result.stdout,end='');(out/'progress-wrap.log').write_text(log) 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 a96fa6b8092900..42e780e42f5f57 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -55,8 +55,8 @@ def item(declaration): assert 'p.prev_barrier.write(0, &prev)?;' in prefix_render_fn assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn assert 'p.fs_dep.write(0, &dep)?;' in prefix_render_fn -assert 'p.compute_barrier.write(0, &cbar)?;' in prefix_render_fn -assert 'p.fs_compute_barrier.write(0, &fcbar)?;' in prefix_render_fn +assert 'p.compute_barrier.write(off, &cbar)?;' in prefix_render_fn +assert 'p.fs_compute_barrier.write(off, &fcbar)?;' in prefix_render_fn c2ta_slice = prefix_render_fn[ prefix_render_fn.index('plan.ta_compute_wait'):prefix_render_fn.index('p.compute_barrier.write') ] @@ -66,6 +66,9 @@ def item(declaration): fs2c_slice = prefix_compute_fn[ prefix_compute_fn.index('wait_render'):prefix_compute_fn.index('s.barrier.write') ] +assert 'work::compute::EVENTS[pipe]' in prefix_compute_fn +assert 'work::compute::EVENTS[p_idx]' in c2ta_slice +assert 'work::compute::EVENTS[p_idx]' in c2fs_slice assert 'render_bar,' in c2ta_slice and 'BarrierType::Hold' not in c2ta_slice assert 'render_bar,' in c2fs_slice and 'BarrierType::Hold' not in c2fs_slice assert 'BarrierType::Stamp,' in prefix_render_fn[prefix_render_fn.index('let own = encode::barrier'):prefix_render_fn.index('p.own_barrier.write')] @@ -91,7 +94,19 @@ def item(declaration): #[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, completed:[AtomicU64;2] } +struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64 } +impl Queue { + fn new(turn:u64, priority:u32)->Arc{ + Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0)}) + } + fn is_compute_retired(&self, seq:u64)->bool{ + let c=self.completed[command::COMPUTE].load(Ordering::Acquire); + if seq<=c { return true; } + let off=seq-c-1; + if off==0 || off>64 { return false; } + (self.compute_ooo.load(Ordering::Acquire) & (1u64 << (off-1))) != 0 + } +} struct Progress { sent:AtomicU32,count:u32,pending:AtomicBool } impl Progress { fn sent(&self)->u32{self.sent.load(Ordering::Relaxed)} @@ -152,7 +167,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=8; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=8; pub const COMPUTE_PIPES:usize=2; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -256,7 +271,7 @@ def item(declaration): fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, - queue:Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}), + queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, 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}) } @@ -410,7 +425,7 @@ def item(declaration): let vm1=mk_vm(1); let mk_prio=|id:u32,render:bool,priority:u32|Arc::new(Job{ id,vm:vm1.clone(), - queue:Arc::new(Queue{turn:AtomicU64::new(0),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)]}), + queue:Queue::new(0,priority), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, @@ -526,8 +541,8 @@ def item(declaration): } #[test]fn alt_bypass_preserves_per_queue_fifo_order(){ let vm1=mk_vm(1); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); - let q2=Arc::new(Queue{turn:AtomicU64::new(1),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); + let q2=Queue::new(1,0); let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ id,vm:vm1.clone(),queue:q, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -612,7 +627,7 @@ def item(declaration): } #[test]fn same_queue_independent_compute_bypasses_ta_wave_paused_render_only(){ let vm1=mk_vm(1); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -698,15 +713,19 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} -struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,flights:Vec} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,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 compute_available_for_pipe(&self,n:usize,pipe:usize)->bool{ + self.compute_available && (pipe == 0 || n > resources::BASE_COMPUTE_UNITS) + } fn pass_available(&self,_n:usize)->bool{self.pass_available} } +mod resources { pub const BASE_COMPUTE_UNITS: usize = 2; } struct QueueBehindPools{exhausted:bool,can_pipeline:bool,block_pipeline_vm:Option} impl QueueBehindPools{ fn exhausted(&self)->bool{self.exhausted} @@ -716,6 +735,7 @@ def item(declaration): struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { use super::*; + use crate::hw::sizes; type Job = QueueBehindJob; type Flight = QueueBehindFlight; fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} @@ -751,11 +771,13 @@ def item(declaration): __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ + __WAIT_COMPUTE_STAMPS_FOR__ + __CHOOSE_COMPUTE_PIPE__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_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 q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,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})}], @@ -768,7 +790,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -798,8 +820,8 @@ def item(declaration): } #[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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); - let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,wait_cdm:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -814,7 +836,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -832,7 +854,7 @@ def item(declaration): }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -843,7 +865,7 @@ def item(declaration): #[test]fn render_queues_behind_same_vm_and_coexists_with_compute_while_blocking_initbm(){ 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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ 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})}], @@ -856,7 +878,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -887,8 +909,8 @@ def item(declaration): #[test]fn cross_vm_render_compute_overlap_matrix(){ 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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); - let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,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:false})}], @@ -900,13 +922,13 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -928,8 +950,8 @@ def item(declaration): } #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); - let q2=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); + let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -944,9 +966,9 @@ def item(declaration): let c_other_q=mk(5,q2.clone(),false,1,[None,None]); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -981,8 +1003,8 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1001,7 +1023,7 @@ def item(declaration): // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:0,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1014,8 +1036,8 @@ def item(declaration): let r_after_r=mk(3,true,2,[Some(1),None]); let host=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,target:0, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1042,8 +1064,8 @@ def item(declaration): } #[test]fn multi_queue_concurrent_compute_and_render_on_same_vm(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q_comp=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); - let q_rend=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q_comp=Queue::new(0,2); + let q_rend=Queue::new(0,2); let c_job=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q_comp.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1060,8 +1082,8 @@ def item(declaration): }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1072,7 +1094,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1080,7 +1102,7 @@ def item(declaration): } #[test]fn cross_engine_wait_and_compute_flight_cap_account_for_batched_horizon_members(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,2); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1098,8 +1120,8 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1114,7 +1136,7 @@ def item(declaration): } #[test]fn multi_pass_render_flight_wait_stamp_and_render_cap(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,2); let multi=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, @@ -1138,8 +1160,8 @@ def item(declaration): r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1154,7 +1176,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1176,7 +1198,7 @@ def item(declaration): let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1192,7 +1214,7 @@ def item(declaration): } #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); - let q1=Arc::new(Queue{turn:AtomicU64::new(0),priority:2,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,2); let mk=|id:u32|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1208,8 +1230,8 @@ def item(declaration): } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:8,computes:0,renders:7,target:0,cstamp:[0;16], + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:8,computes:0,renders:7,compute_pipe:0,target:0,cstamp:[0;16], r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1238,7 +1260,7 @@ def item(declaration): #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ 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,completed:[AtomicU64::new(0),AtomicU64::new(0)]}); + let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1253,8 +1275,8 @@ def item(declaration): let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,target:0,cstamp:[0;16], + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1308,17 +1330,18 @@ def item(declaration): #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + const NO_C: [[Option; 2]; 2] = [[None; 2]; 2]; // 1. Cold InitBM / empty render pipe (`class_behind = false`): zero render barriers, // compute->FS-only wait routes directly to fs_compute_barrier. assert_eq!( - plan_render_barriers(STAGED, false, true, 0, None, None, [None, Some(0x700)], false), + plan_render_barriers(STAGED, false, true, 0, None, None, [[None, None], [Some(0x700), None]], false), RenderBarrierPlan { early: false, ta_prev_wait: false, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: Some(0x700), + ta_compute_wait: [None, None], + fs_compute_wait: [Some(0x700), None], } ); // 2. Independent multi-pass render (`fs_wait_render = None`, e.g. compress.bw array / @@ -1327,14 +1350,14 @@ def item(declaration): // ZERO FS->FS barriers (only own_barrier on FS). for flags in [0u32, FRAG, STAGED] { assert_eq!( - plan_render_barriers(flags, true, true, 0x200, None, None, [None, None], false), + plan_render_barriers(flags, true, true, 0x200, None, None, NO_C, false), RenderBarrierPlan { early: true, ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); } @@ -1348,7 +1371,7 @@ def item(declaration): 0x200, Some(0x200), None, - [Some(0x700), Some(0x700)], + [[Some(0x700), None], [Some(0x700), None]], false, ), RenderBarrierPlan { @@ -1356,8 +1379,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: Some(0x700), - fs_compute_wait: None, + ta_compute_wait: [Some(0x700), None], + fs_compute_wait: [None, None], } ); // 4. Different compute targets on TA (0x600) vs FS (0x700) with no FS render dep: @@ -1370,7 +1393,7 @@ def item(declaration): 0x200, None, None, - [Some(0x600), Some(0x700)], + [[Some(0x600), None], [Some(0x700), None]], false, ), RenderBarrierPlan { @@ -1378,8 +1401,30 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: Some(0x600), - fs_compute_wait: Some(0x700), + ta_compute_wait: [Some(0x600), None], + fs_compute_wait: [Some(0x700), None], + } + ); + // 4b. Two-pipe compute waits deduplicate per pipe independently: pipe 0 shared by TA+FS + // (0x600) stays on TA only, while pipe 1 FS-only wait (0x700) routes to FS pipe 1. + assert_eq!( + plan_render_barriers( + STAGED, + true, + true, + 0x200, + None, + None, + [[Some(0x600), None], [Some(0x600), Some(0x700)]], + false, + ), + RenderBarrierPlan { + early: true, + ta_prev_wait: true, + ta_fs_wait: None, + fs_render_wait: None, + ta_compute_wait: [Some(0x600), None], + fs_compute_wait: [None, Some(0x700)], } ); // 5. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200) @@ -1392,7 +1437,7 @@ def item(declaration): 0x200, Some(0x200), Some(0x100), - [None, None], + NO_C, false, ), RenderBarrierPlan { @@ -1400,8 +1445,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: Some(0x200), - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 6. Staged render where TA and FS wait on the same older in-flight FS (0x100): @@ -1415,7 +1460,7 @@ def item(declaration): 0x200, Some(0x100), Some(0x100), - [None, None], + NO_C, false, ), RenderBarrierPlan { @@ -1423,8 +1468,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 7. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): @@ -1438,7 +1483,7 @@ def item(declaration): 0x200, Some(0x200), Some(0x200), - [None, None], + NO_C, false, ), RenderBarrierPlan { @@ -1446,8 +1491,8 @@ def item(declaration): ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 8. Dependent FRAGMENT_BARRIERS render (e.g. render.postfx): TA runs early with @@ -1460,7 +1505,7 @@ def item(declaration): 0x200, Some(0x200), None, - [Some(0x700), Some(0x700)], + [[Some(0x700), None], [Some(0x700), None]], false, ), RenderBarrierPlan { @@ -1468,47 +1513,47 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: Some(0x700), - fs_compute_wait: None, + ta_compute_wait: [Some(0x700), None], + fs_compute_wait: [None, None], } ); // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): // TA waits on 0x200 (FS->TA, dominating prev_ta); prev_barrier and fs_dep omitted. assert_eq!( - plan_render_barriers(0, true, true, 0x200, Some(0x200), None, [None, None], false), + plan_render_barriers(0, true, true, 0x200, Some(0x200), None, NO_C, false), RenderBarrierPlan { early: false, ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): // TA still needs prev_barrier on the shared PB in addition to ta_fs_wait(0x100). assert_eq!( - plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None], false), + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, NO_C, false), RenderBarrierPlan { early: false, ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when // fs_wait_render is None, dominating prev_ta and omitting fs_dep. assert_eq!( - plan_render_barriers(FRAG, true, false, 0x200, None, None, [None, None], false), + plan_render_barriers(FRAG, true, false, 0x200, None, None, NO_C, false), RenderBarrierPlan { early: false, ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 12. Cross-VM warm render behind another VM's render (`cross_vm_prev = true`, no @@ -1516,14 +1561,14 @@ def item(declaration): // for all flag styles (legacy/FRAG/STAGED) while FS ALWAYS waits on prev_fs (0x200). for flags in [0u32, FRAG, STAGED] { assert_eq!( - plan_render_barriers(flags, true, true, 0x200, None, None, [None, None], true), + plan_render_barriers(flags, true, true, 0x200, None, None, NO_C, true), RenderBarrierPlan { early: true, ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); } @@ -1531,30 +1576,136 @@ def item(declaration): // TA waits on own older FS (0x100) and prev_ta, while FS still waits on cross-VM // prev_fs (0x200) so two VMs' FS/PB teardowns never overlap. assert_eq!( - plan_render_barriers(0, true, true, 0x200, Some(0x100), None, [None, None], true), + plan_render_barriers(0, true, true, 0x200, Some(0x100), None, NO_C, true), RenderBarrierPlan { early: false, ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: Some(0x200), - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); // 14. Cross-VM with `early_tiling = false`: TA already waits on prev_fs, so fs_dep // is dominated and omitted. assert_eq!( - plan_render_barriers(STAGED, true, false, 0x200, None, None, [None, None], true), + plan_render_barriers(STAGED, true, false, 0x200, None, None, NO_C, true), RenderBarrierPlan { early: false, ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: None, - fs_compute_wait: None, + ta_compute_wait: [None, None], + fs_compute_wait: [None, None], } ); } + #[test]fn two_pipe_concurrent_compute_dispatch_and_fw_timestamp_safety(){ + 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=Queue::new(0,2); + let q2=Queue::new(0,2); + let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ + id,vm,queue, + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let c1=mk(1,vm1.clone(),q1.clone(),1); + let c2=mk(2,vm1.clone(),q1.clone(),2); + let c_vm2=mk(3,vm2.clone(),q2.clone(),1); + let mut host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. + assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + host.engine.flights.push(QueueBehindFlight{ + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. + assert_eq!(host.choose_compute_pipe([None, None], 2), 0); + assert!(host.can_queue_behind(&c2)); + // Add second concurrent flight on pipe 1: both pipes active, + // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. + host.engine.flights.push(QueueBehindFlight{ + job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + host.engine.next_compute_pipe=1; + assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + host.engine.next_compute_pipe=0; + assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + assert!(host.can_queue_behind(&c_vm2)); + // Same-VM compute still pipelines without draining. + assert!(host.can_queue_behind(&c2)); + } + #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Queue::new(0,2); + let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + }); + let c1=mk(1,1,None); + let c2=mk(2,2,None); + let c3=mk(3,3,Some(1)); + let c4=mk(4,4,Some(2)); + let mut host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ + QueueBehindFlight{ + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }, + QueueBehindFlight{ + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,target:0x200, + cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, + }; + // Barrier-free compute resolves [None, None]. + assert_eq!(host.wait_compute_stamps_for(&c3, None), Ok([None, None])); + // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). + let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); + assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); + assert_eq!(host.choose_compute_pipe(w1, 24), 0); + // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and + // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, + // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). + let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); + assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); + assert_eq!(host.choose_compute_pipe(w2, 24), 0); + // Unpublished seq 3 returns Err(EAGAIN). + assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); + // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, + // compute_ooo bit 0 marks seq 2 retired so wait_compute_stamps_for(Some(2)) succeeds + // and still waits on pipe 0's active seq 1 (0x100)! + host.engine.flights.remove(1); + q1.compute_ooo.store(1u64 << 0, Ordering::Release); + assert!(q1.is_compute_retired(2)); + let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); + assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); + assert_eq!(host.choose_compute_pipe(w2_ooo, 24), 0); + // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. + q1.completed[command::COMPUTE].store(2, Ordering::Release); + q1.compute_ooo.store(0, Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None, None])); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -1868,6 +2019,7 @@ def item(declaration): assert!(!unready.can_fold_render_horizon_job(2)); } + use crate::hw::sizes; mod recovery { pub(crate) mod logic { pub(crate) use crate::recovery::logic::{stamp_reached, RetiredStamps}; @@ -1905,6 +2057,7 @@ def item(declaration): claims: RecClaims, computes: u32, renders: u32, + compute_pipe: u8, target: u32, ta_target: u32, fs_target: u32, @@ -1917,7 +2070,7 @@ def item(declaration): gate_passed_ns: Option, unsettled_polls: u32, } - struct RecEngine { flights: Vec, target: u32, ta_target: u32, fs_target: u32 } + struct RecEngine { flights: Vec, target: [u32; 2], ta_target: u32, fs_target: u32 } struct RecState { last_retired: recovery::logic::RetiredStamps } struct RecFirmware { engine: RecEngine, recovery: RecState } impl RecFirmware { @@ -1937,6 +2090,7 @@ def item(declaration): claims: RecClaims { pass: [0; 16] }, computes: 3, renders: 0, + compute_pipe: 0, target: 0x300, ta_target: 0, fs_target: 0, @@ -1949,16 +2103,16 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], - target: 0x300, + target: [0x300, 0], ta_target: 0, fs_target: 0, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; - assert_eq!(fw.recovery_prepare(1, 15, 0x200, [0, 0, 0x100]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15, 0x200, [0, 0, 0x100, 0]), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(fw.engine.flights[0].recovery_suspect); - assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0x100]), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0x100, 0]), Err(ENOENT)); } #[test] fn recovery_prepare_matches_interior_render_stamps_and_cleans_only_unfinished_tpc() { @@ -1984,6 +2138,7 @@ def item(declaration): claims: RecClaims { pass }, computes: 0, renders: 3, + compute_pipe: 0, target: 0, ta_target: 0x300, fs_target: 0x300, @@ -1996,7 +2151,7 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], - target: 0, + target: [0, 0], ta_target: 0x300, fs_target: 0x300, }, @@ -2004,14 +2159,14 @@ def item(declaration): }; // Pass 0 TA finished (stage[0] == 0x100); interior TA target 0x200 matches and cleans // TPC only for unfinished passes 1 and 2. - assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, [0x100, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, [0x100, 0, 0, 0]), Ok(())); assert!(fw.engine.flights[0].doomed); assert_eq!(fw.engine.flights[0].job.resources.passes[0].tpc.cleared.get(), 0); assert_eq!(fw.engine.flights[0].job.resources.passes[1].tpc.cleared.get(), 0x2000); assert_eq!(fw.engine.flights[0].job.resources.passes[2].tpc.cleared.get(), 0x3000); // Interior FS target 0x200 also matches; unrelated target 0x400 returns ENOENT. - assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, [0x300, 0x100, 0]), Ok(())); - assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, [0x300, 0x100, 0]), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, [0x300, 0x100, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, [0x300, 0x100, 0, 0]), Err(ENOENT)); } #[test] fn cross_vm_recovery_prepare_isolates_blame_to_faulting_vm() { @@ -2028,6 +2183,7 @@ def item(declaration): claims: RecClaims { pass: [0; 16] }, computes: 0, renders: 1, + compute_pipe: 0, target: 0, ta_target: 0x100, fs_target: 0x100, @@ -2045,6 +2201,7 @@ def item(declaration): claims: RecClaims { pass: [0; 16] }, computes: 1, renders: 0, + compute_pipe: 0, target: 0x500, ta_target: 0, fs_target: 0, @@ -2058,15 +2215,15 @@ def item(declaration): unsettled_polls: 0, }, ], - target: 0x500, + target: [0x500, 0], ta_target: 0x100, fs_target: 0x100, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; // VM 1 (ASID 1) faults on FS 0x100 while VM 2 (ASID 2) has co-resident compute 0x500. - assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x100, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare_suspects([0x100, 0, 0], 0x71, Some(1)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x100, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare_suspects([0x100, 0, 0, 0], 0x71, Some(1)), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(fw.engine.flights[0].recovery_suspect); // VM 2's co-resident compute is suspect-only (checked via hardware ITS ticks), NEVER doomed! @@ -2084,6 +2241,7 @@ def item(declaration): claims: RecClaims { pass: [0; 16] }, computes: 0, renders: 1, + compute_pipe: 0, target: 0, ta_target: 0x200, fs_target: 0x200, @@ -2098,12 +2256,91 @@ def item(declaration): }; fw.engine.ta_target = 0x200; fw.engine.fs_target = 0x200; - assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x200, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare_suspects([0x200, 0, 0], 0x71, Some(1)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x200, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare_suspects([0x200, 0, 0, 0], 0x71, Some(1)), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(!fw.engine.flights[1].doomed); assert!(fw.engine.flights[1].recovery_suspect); } + #[test] + fn two_pipe_compute_recovery_isolates_faulting_pipe_and_event_targets() { + // Pipe 0 (VM 1, event 15) and Pipe 1 (VM 2, event 16) both hold identical per-pipe + // stamp 0x100. Faulting event 16 dooms ONLY pipe 1 (VM 2) while pipe 0 (VM 1) stays + // un-doomed suspect-only. + let mut cs = [0u32; 16]; + cs[0] = 0x100; + let mut last_retired = recovery::logic::RetiredStamps::new(); + last_retired.push(0, 0x300); + last_retired.push(1, 0x400); + let mut fw = RecFirmware { + engine: RecEngine { + flights: vec![ + RecFlight { + job: RecJob { vm: RecVm { slot: 1 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + compute_pipe: 0, + target: 0x100, + ta_target: 0, + fs_target: 0, + cstamp: cs, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + RecFlight { + job: RecJob { vm: RecVm { slot: 2 }, resources: Resources { passes: vec![] } }, + claims: RecClaims { pass: [0; 16] }, + computes: 1, + renders: 0, + compute_pipe: 1, + target: 0x100, + ta_target: 0, + fs_target: 0, + cstamp: cs, + r_ta_stamp: [0; 16], + r_fs_stamp: [0; 16], + doomed: false, + recovery_suspect: false, + recovery_started_ns: 0, + gate_passed_ns: None, + unsettled_polls: 0, + }, + ], + target: [0x100, 0x100], + ta_target: 0, + fs_target: 0, + }, + recovery: RecState { last_retired }, + }; + assert_eq!(fw.recovery_prepare(1, 16, 0x100, [0, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare_suspects([0, 0, 0, 0], 16, Some(2)), Ok(())); + assert!(!fw.engine.flights[0].doomed); + assert!(fw.engine.flights[0].recovery_suspect); + assert!(fw.engine.flights[1].doomed); + assert!(fw.engine.flights[1].recovery_suspect); + + // If pipe 0 already finished (stage[2] == 0x100) before recovery snapshot, pipe 0 is not + // even marked recovery_suspect while pipe 1 is. + fw.engine.flights[0].recovery_suspect = false; + fw.engine.flights[1].recovery_suspect = false; + fw.engine.flights[1].doomed = false; + assert_eq!(fw.recovery_prepare_suspects([0, 0, 0x100, 0], 16, Some(2)), Ok(())); + assert!(!fw.engine.flights[0].recovery_suspect); + assert!(fw.engine.flights[1].recovery_suspect); + assert!(fw.engine.flights[1].doomed); + + // last_retired_target distinguishes event 15 (slot 0) from event 16 (slot 1). + assert_eq!(fw.recovery_prepare(1, 15, 0x300, [0, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 16, 0x400, [0, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0, 0]), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 16, 0x300, [0, 0, 0, 0]), Err(ENOENT)); + } } ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) @@ -2167,12 +2404,14 @@ def item(declaration): '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', + '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', + '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', '__WAIT_TARGET__': 'struct WaitTarget {', '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' 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 9160894ea0eaa5..cfbb26d9e40999 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1234,7 +1234,7 @@ def module(text, name): assert_eq!(s.hold_compute_slot(g16::hw::sizes::COMPUTE_UNITS,&a,&prep),Err(EINVAL)); s.hold_compute_slot(k0,&a,&prep).unwrap(); s.verify_held(&cc).unwrap(); - s.publish(&cc).unwrap(); + s.publish(&mut cc).unwrap(); s.note_published(&cc); s.retire(&mut cc).unwrap(); @@ -1257,7 +1257,7 @@ def module(text, name): let mut dup=cr; dup.pass[1]=46; assert_eq!(s.verify_held(&dup),Err(EINVAL)); - s.publish(&cr).unwrap(); + s.publish(&mut cr).unwrap(); s.note_published(&cr); s.retire(&mut cr).unwrap(); @@ -1267,7 +1267,7 @@ def module(text, name): cr2.pass[0]=46;cr2.pass_count=1;cr2.pass_mask=1u64<<46;s.pass_busy|=1u64<<46; s.hold_render_pass(46,&b,&prep).unwrap(); s.verify_held(&cr2).unwrap(); - s.publish(&cr2).unwrap(); + s.publish(&mut cr2).unwrap(); s.note_published(&cr2); assert_eq!(s.stats.cross_vm_retargets[1],1); assert_eq!(s.stats.last_retarget[1].unit,46); @@ -1422,6 +1422,58 @@ def module(text, name): s.release(&mut c); } + #[test]fn two_pipe_compute_out_of_order_retire_and_base_unit_isolation(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut units=KVec::new(); + for k in 0..4u64 { + units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + } + let prep=g16::resources::ComputeArena{compute:units,render:None}; + let a=vm(1);let b=vm(2); + // Pipe 0 claims unit 0; pipe 1 stays out of base units 0..2 and claims unit 2. + let mut c0=Claims::new(); + let mut c1=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0,Some(a.id),0).unwrap(),Some(0)); + assert_eq!(c0.compute_pipe,0); + s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(2)); + assert_eq!(c1.compute_pipe,1); + s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap(); + // Pipe 1 finishes ahead of still-running pipe 0: retire must succeed (no EINVAL). + assert_eq!(s.retire(&mut c1),Ok(())); + // Second pipe-1 flight claims unit 3 and retires, displacing unit 2 on pipe 1. + let mut c1b=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(3)); + s.hold_vm(&c1b,&a).unwrap();s.publish(&mut c1b).unwrap(); + assert_eq!(s.retire(&mut c1b),Ok(())); + assert!(s.compute_available_for_pipe(4,1)); + // Now pipe 0's unit 0 retires: pipe 1's newer unit 3 must NOT mark unit 0 reusable, + // while base unit 1 remains fresh so a 2-unit base-only VM is never exhausted! + assert_eq!(s.retire(&mut c0),Ok(())); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // Pipe 0 claims base unit 1 (not undisplaced unit 0), publishes, and retires -> unit 0 displaced! + let mut c0b=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0b,Some(b.id),0).unwrap(),Some(1)); + s.hold_vm(&c0b,&b).unwrap();s.publish(&mut c0b).unwrap(); + assert_eq!(s.retire(&mut c0b),Ok(())); + assert!(!s.compute_exhausted_within(2)); + assert!(s.compute_available(2)); + // A 2-unit base-only VM can claim displaced base unit 0 on pipe 0, while pipe 1 + // reclaims displaced extension unit 2 on the 4-unit VM without touching base units 0..2. + let mut base_units=KVec::new(); + for k in 0..2u64 { + base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + } + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + let mut c0c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_base,&mut c0c,Some(b.id),0).unwrap(),Some(0)); + let mut c1c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(2)); + s.release(&mut c0c); + s.release(&mut c1c); + } + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); @@ -1527,7 +1579,7 @@ def module(text, name): let a=vm(1);let b=vm(2); let pub_retire=|s:&mut Slots,k:usize,vm:&sync::Arc|{ let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1u64< dirty=0x10000, last=0x2000. s.claim_pass_in(&prep,0,Some(a.id),0x10000).unwrap(); @@ -1592,10 +1644,27 @@ def module(text, name): assert_eq!(cmd_fw(), Class::Fw); assert_eq!(cmd_shared(), Class::Shared); let mut o = Objects::new(); - let c = ComputeGraph::new(&mut o).unwrap(); - let r = RenderGraph::new(&mut o, c.sched_ctx.clone()).unwrap(); - c.init(FwAbi).unwrap(); + let ctx = o.alloc(g16::object::Request { + size: 0x40, + class: Class::Fw, + placement: g16::object::Placement::Anywhere, + offset: 0, + client: None, + lower: None, + cpu: true, + }).unwrap(); + let c = ComputeGraph::new(&mut o, ctx.clone()).unwrap(); + let c1 = ComputeGraph::new(&mut o, ctx.clone()).unwrap(); + let r = RenderGraph::new(&mut o, ctx).unwrap(); + c.init(FwAbi, true).unwrap(); + c1.init(FwAbi, false).unwrap(); r.init(FwAbi).unwrap(); + assert_eq!(c.sched_ctx.va, c1.sched_ctx.va); + assert_ne!(c.qinfo.va, c1.qinfo.va); + assert_ne!(c.fw_stamp.va, c1.fw_stamp.va); + assert_eq!(c1.qinfo.class, Class::FwCached); + assert_eq!(c1.qstate.class, Class::Fw); + assert_eq!(c1.fw_stamp.class, Class::Shared); assert_eq!(c.qinfo.class, Class::FwCached); assert_eq!(c.qscratch.class, Class::FwCached); assert_eq!(c.job_list.class, Class::FwCached); 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 fd5c07ea64e104..827a3e885c8525 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 @@ -28,6 +28,7 @@ def function(text, name): #[path="__LOGIC__"]mod logic; use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } +mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 2; } } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} impl Object { @@ -40,15 +41,15 @@ def function(text, name): mod notifier_page {pub const COMPUTE_STAMP:usize=0;pub const COMPUTE_CONTEXT:usize=4;pub const TA_STAMP:usize=8;pub const FS_STAMP:usize=12;pub const FS_RECORD:usize=32;} mod notifier {pub const CONTEXT:usize=16;} mod compute {pub const DESCRIPTOR_COMPLETED:usize=0;pub const DESCRIPTOR_COUNTER:usize=8;} -struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} +#[derive(Default)]struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} struct RGraph{fw_stamp:[Object;2],qstate:[Object;2],qinfo:[Object;2],notifier:Object} -struct Graph{compute:CGraph,render:RGraph} +struct Graph{compute:[CGraph;2],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)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} -struct Claims{slot:[u32;16],slot_count:u32,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],pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} -struct Engine{flights:Vec,target:u32,ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} +struct Claims{slot:[u32;16],slot_count:u32,pass:[u32;4]} +struct Flight{computes:u32,renders:u32,compute_pipe:u8,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,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} +struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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} @@ -57,10 +58,15 @@ def function(text, name): struct Slots{scrub:Scrub} 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} -thread_local!{static CLOCK:Cell = const { Cell::new(100_000_000) };} -fn rmb(){}fn now_ns()->u64{CLOCK.with(|c| c.get())} +struct TopChannels{compute_producer:u32} +impl TopChannels{fn producer(&self,ch:Channel)->u32{match ch{Channel::Compute=>self.compute_producer,_=>1}}} +struct Firmware{graph:Graph,engine:Engine,slots:Slots,pools:Pools,channels:TopChannels,queue_passed:bool,last_chan_passed:Cell>} +thread_local! { static CLOCK: Cell = const { Cell::new(100_000_000) }; } +fn rmb(){}fn now_ns()->u64{CLOCK.with(|c|c.get())} impl Firmware{ + fn queue_ring_receipt(&self,_state:&Object,_info:&Object,_head:u32)->Result{Ok(self.queue_passed)} + fn queue_ring_passed(&self,_ch:Channel,_state:&Object,_info:&Object,_f:&Flight)->Result{Ok(self.queue_passed)} + fn channel_receipt(&self,_ch:Channel,_rec:u32,passed:bool)->Result{self.last_chan_passed.set(Some(passed));Ok(self.queue_passed)} 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. @@ -75,15 +81,15 @@ def function(text, name): fn firmware(render:bool,ordinal:u64)->Firmware{ let target=encode::stamp(ordinal); let mut f=Firmware{ - graph:Graph{compute:CGraph{fw_stamp:Object::default(),qstate:Object::default(),qinfo:Object::default(),notifier:Object::default()}, + graph:Graph{compute:[CGraph::default(),CGraph::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,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target,ta_target:target,fs_target:target,retired_ticks:[0;4]}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),compute_pipe:0,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;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:[target,0],ta_target:target,fs_target:target,retired_ticks:[0;4]}, 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,completed:2},queue_passed:true, + pools:Pools{full:true,completed:2},channels:TopChannels{compute_producer:1},queue_passed:true,last_chan_passed:Cell::new(None), }; - f.graph.compute.fw_stamp.set(0,u64::from(target)); - f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(target)); - f.graph.compute.notifier.set(notifier_page::COMPUTE_CONTEXT,2); + f.graph.compute[0].fw_stamp.set(0,u64::from(target)); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(target)); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); f.engine.flights[0].job.resources.compute[0].counter.set(0,ordinal); f.engine.flights[0].job.resources.compute[0].its.set(0,100);f.engine.flights[0].job.resources.compute[0].its.set(8,101); f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COMPLETED,ordinal); @@ -128,15 +134,15 @@ def function(text, name): 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); + f.engine.flights.push(later);f.engine.target[0]=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); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n+1))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n+1))); + f.graph.compute[0].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))); + f.graph.compute[0].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))); + f.graph.compute[0].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); @@ -190,10 +196,10 @@ def function(text, name): let mut f=firmware(true,10); let c=firmware(false,20).engine.flights.remove(0); f.engine.flights.push(c); - f.engine.target=encode::stamp(20); - f.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(20))); - f.graph.compute.notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(20))); - f.graph.compute.notifier.set(notifier_page::COMPUTE_CONTEXT,2); + f.engine.target[0]=encode::stamp(20); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(20))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(20))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); // Keep render FS stamp unreached so render at index 0 stays pending. f.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(9))); assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); @@ -211,7 +217,7 @@ def function(text, name): for stage in 0..2 { f2.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(40))); } f2.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(40))); f2.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(40))); - f2.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(29))); + f2.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); assert_eq!(f2.retired_flight(),Ok(Some((1,Retirement::Full)))); } #[test]fn multi_compute_horizon_requires_every_claimed_unit_receipt(){ @@ -251,8 +257,10 @@ def function(text, name): // Render-only retirement performs zero compute WC reads. let mut fr=firmware(true,5); assert_eq!(fr.retired_flight(),Ok(Some((0,Retirement::Full)))); - assert_eq!(fr.graph.compute.fw_stamp.reads.get(),0); - assert_eq!(fr.graph.compute.notifier.reads.get(),0); + assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute[0].notifier.reads.get(),0); + assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute[1].notifier.reads.get(),0); // In-progress render (TA done, FS still running) fails fast on FS stamp without reading TA or scene. let mut fp=firmware(true,7); fp.graph.render.fw_stamp[1].set(0,u64::from(encode::stamp(6))); @@ -268,9 +276,9 @@ def function(text, name): // Mixed flight pending is polled once, not twice. let mut fm=firmware(false,9); fm.engine.flights[0].renders=1; - fm.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(8))); + fm.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(8))); assert_eq!(fm.retired_flight(),Ok(None)); - assert_eq!(fm.graph.compute.fw_stamp.reads.get(),1); + assert_eq!(fm.graph.compute[0].fw_stamp.reads.get(),1); assert_eq!(fm.graph.render.fw_stamp[1].reads.get(),0); // Pending compute class is not re-polled while retiring a burst of render flights. let mut fmix=firmware(false,30); @@ -283,15 +291,15 @@ def function(text, name): for stage in 0..2 { fmix.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(41))); } fmix.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(41))); fmix.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(41))); - fmix.graph.compute.fw_stamp.set(0,u64::from(encode::stamp(29))); - let (mut check_c,mut check_r)=(true,true); + fmix.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + let (mut check_c,mut check_r)=([true;2],true); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); - assert!(!check_c && check_r); + assert!(!check_c[0] && !check_c[1] && check_r); fmix.engine.flights.remove(1); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); fmix.engine.flights.remove(1); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); - assert_eq!(fmix.graph.compute.fw_stamp.reads.get(),1); + assert_eq!(fmix.graph.compute[0].fw_stamp.reads.get(),1); } #[test]fn innocent_suspect_flight_does_not_false_abort_after_recovery_grace(){ let mut f=firmware(true,15); @@ -358,31 +366,14 @@ def function(text, name): c.engine.flights[0].job.resources.compute[0].its.set(8,299); assert_eq!(c.retired(),Ok(Retirement::Pending)); } -#[test]fn recovery_suspect_compact_compute_retires_full_with_hw_ticks(){ - // An innocent cross-VM compact compute (compute_ts_mask == 0) marked recovery_suspect - // during another VM's hang still proves stage execution via cold-path ITS ticks and - // retires Full without false Aborted or VM blame. - CLOCK.with(|c|c.set(100_000_000)); - let mut f=firmware(false,29); - f.engine.flights[0].compute_ts_mask=0; - f.engine.flights[0].recovery_suspect=true; - f.engine.flights[0].recovery_started_ns=90_000_000; - f.engine.flights[0].job.resources.compute[0].its.set(0,500); - f.engine.flights[0].job.resources.compute[0].its.set(8,525); - assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); - assert!(!f.engine.flights[0].doomed); - assert_eq!(f.engine.flights[0].job.resources.compute[0].its.reads.get(),2); - assert_eq!(f.engine.retired_ticks,[0;4]); -} #[test]fn cross_vm_render_hang_recovery_isolates_innocent_client_flight(){ - // VM A (slot 0, ASID 1) hangs/aborts on render n=30 while innocent VM B (slot 1, ASID 2, - // compact stage_ts_mask=0) has a co-resident render n=31 with real FS ticks and independent - // allocator slot completion. VM A aborts; VM B retires Full without blame or error. + // VM A (slot 0, ASID 1) hangs/aborts on render n=30 while innocent VM B (slot 1, ASID 2) + // has a co-resident render n=31 with real TA/FS ticks and independent allocator slot + // completion. VM A aborts; VM B retires Full without blame or error. CLOCK.with(|c|c.set(100_000_000)); let mut f=firmware(true,30); f.engine.flights[0].job.vm.slot=1; f.engine.flights[0].pb_slot=0; - f.engine.flights[0].stage_ts_mask=0; f.engine.flights[0].doomed=true; f.engine.flights[0].recovery_suspect=true; f.engine.flights[0].recovery_started_ns=90_000_000; @@ -392,12 +383,13 @@ def function(text, name): innocent.job.vm.slot=2; innocent.pb_slot=1; innocent.uma_submitted=2; - innocent.stage_ts_mask=0; innocent.doomed=false; innocent.recovery_suspect=true; innocent.recovery_started_ns=90_000_000; innocent.job.resources.pools=Pools{full:true,completed:2}; innocent.job.resources.passes[0].scene=Object::default(); + innocent.job.resources.passes[0].scene.set(0x600,300); + innocent.job.resources.passes[0].scene.set(0x608,320); innocent.job.resources.passes[0].scene.set(0x620,400); innocent.job.resources.passes[0].scene.set(0x628,430); f.engine.flights.push(innocent); @@ -411,19 +403,94 @@ def function(text, name): f.graph.render.notifier.set(notifier::CONTEXT,2); f.graph.render.notifier.set(notifier_page::FS_RECORD+notifier::CONTEXT,2); - // After 20 ms recovery grace, hanging VM A aborts on slot 0. - CLOCK.with(|c|c.set(110_000_000)); + // First unsettled poll records gate_passed_ns on hanging VM A; after ABORT_GRACE_NS, VM A aborts. + assert_eq!(f.retired_flight(),Ok(None)); + CLOCK.with(|c|c.set(100_000_000 + ABORT_GRACE_NS)); let (idx_a,ret_a)=f.retired_flight().unwrap().unwrap(); assert_eq!((idx_a,ret_a),(0,Retirement::Aborted)); assert!(ret_a.job_failed(f.engine.flights[0].doomed)); f.engine.flights.remove(0); - // Innocent VM B on slot 1 proves FS execution via cold-path FS ticks and retires Full. + // Innocent VM B on slot 1 proves TA/FS execution via hardware ticks and retires Full. let (idx_b,ret_b)=f.retired_flight().unwrap().unwrap(); assert_eq!((idx_b,ret_b),(0,Retirement::Full)); assert!(!f.engine.flights[0].doomed); assert!(!ret_b.job_failed(f.engine.flights[0].doomed)); } +#[test]fn two_compute_pipes_retire_out_of_order_independently(){ + // Pipe 0 flight at idx 0 (pending, rec=1) + Pipe 1 flight at idx 1 (complete, rec=2, + // shared Channel::Compute producer=2): pipe 1 retires Full ahead of pipe 0, and once + // pipe 0 settles afterwards it still uses passed channel_receipt because rec (1) != producer (2). + let mut f=firmware(false,10); + f.engine.flights[0].compute_pipe=0; + f.engine.flights[0].rec[2]=1; + let mut c1=firmware(false,11).engine.flights.remove(0); + c1.compute_pipe=1; + c1.rec[2]=2; + f.engine.flights.push(c1); + f.engine.target=[encode::stamp(10),encode::stamp(11)]; + f.channels.compute_producer=2; + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(9))); + f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(11))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(11))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_CONTEXT,2); + assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); + assert_eq!(f.last_chan_passed.get(),Some(true)); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + // Now finish pipe 0: rec[2]=1 != producer=2 still sets chan_behind=true. + f.last_chan_passed.set(None); + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(10))); + assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); + assert_eq!(f.last_chan_passed.get(),Some(true)); +} +#[test]fn two_pipe_cross_vm_compute_hang_recovery_isolates_innocent_pipe(){ + // Pipe 0 VM A (ASID 1) hangs/aborts while co-resident Pipe 1 VM B (ASID 2) proves CDM + // execution via hardware ITS ticks and retires Full immediately without blame or false abort. + CLOCK.with(|c|c.set(100_000_000)); + let mut f=firmware(false,40); + f.engine.flights[0].compute_pipe=0; + f.engine.flights[0].job.vm.slot=1; + f.engine.flights[0].rec[2]=1; + f.engine.flights[0].doomed=true; + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=90_000_000; + f.engine.flights[0].job.resources.compute[0].its=Object::default(); + + let mut innocent=firmware(false,41).engine.flights.remove(0); + innocent.compute_pipe=1; + innocent.job.vm.slot=2; + innocent.rec[2]=2; + innocent.doomed=false; + innocent.recovery_suspect=true; + innocent.recovery_started_ns=90_000_000; + innocent.job.resources.compute[0].its.set(0,500); + innocent.job.resources.compute[0].its.set(8,530); + f.engine.flights.push(innocent); + + f.engine.target=[encode::stamp(40),encode::stamp(41)]; + f.channels.compute_producer=2; + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(40))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(40))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,1); + f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(41))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(41))); + f.graph.compute[1].notifier.set(notifier_page::COMPUTE_CONTEXT,2); + + // Within grace: pipe 0 records gate_passed_ns while innocent pipe 1 retires Full immediately. + let (idx_b,ret_b)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_b,ret_b),(1,Retirement::Full)); + assert!(!f.engine.flights[1].doomed); + assert!(!ret_b.job_failed(f.engine.flights[1].doomed)); + f.engine.flights.remove(1); + assert_eq!(f.retired_flight(),Ok(None)); + + // Past ABORT_GRACE_NS from gate_passed_ns: hanging pipe 0 aborts cleanly. + CLOCK.with(|c|c.set(100_000_000 + ABORT_GRACE_NS)); + let (idx_a,ret_a)=f.retired_flight().unwrap().unwrap(); + assert_eq!((idx_a,ret_a),(0,Retirement::Aborted)); + assert!(ret_a.job_failed(f.engine.flights[0].doomed)); +} mod queue_proof { use super::{Channel, Object, Result, EINVAL}; @@ -469,12 +536,15 @@ def function(text, name): } fn producer(&self, ch: Channel) -> u32 { self.channel(ch).write } } - struct Engine { head: u32, ta_head: u32, fs_head: u32 } - struct Flight { c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3] } + struct Engine { head: [u32; 2], ta_head: u32, fs_head: u32 } + struct Flight { compute_pipe: u8, c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3] } struct Firmware { init: Init, channels: Channels, engine: Engine } mod inner { use super::*; impl Firmware { + __QUEUE_RING_RECEIPT__ + __QUEUE_RING_PASSED__ + __CHANNEL_RECEIPT__ __QUEUE_RECEIPT__ __QUEUE_PASSED__ } @@ -489,7 +559,7 @@ def function(text, name): ta: Pipe { read: 7, completion: 7, write: 7 }, fs: Pipe { read: 9, completion: 9, write: 9 }, }, - engine: Engine { head: 10, ta_head: 20, fs_head: 30 }, + engine: Engine { head: [10, 12], ta_head: 20, fs_head: 30 }, }; let mut state = Object::default(); let mut info = Object::default(); @@ -516,10 +586,24 @@ def function(text, name): assert_eq!(fw.queue_receipt(Channel::Compute, &state, &info, 256, 5), Err(EINVAL)); assert_eq!(info.reads.get(), 0); + // Split ring + channel receipts for 2-pipe OOO compute: pipe 1's own ring is exact + // (head=12) while shared Channel::Compute producer moved on to 6 (rec=5 -> passed=true). + fw.channels.compute = Pipe { read: 6, completion: 6, write: 6 }; + state.set(qstate::READ, 12); + state.set(qstate::WRITE, 12); + assert_eq!(fw.queue_ring_receipt(&state, &info, 12), Ok(true)); + assert_eq!(fw.channel_receipt(Channel::Compute, 5, false), Ok(false)); + assert_eq!(fw.channel_receipt(Channel::Compute, 5, true), Ok(true)); + let f_p1 = Flight { compute_pipe: 1, c_start: 10, head: 11, ta_start: 0, ta_head: 1, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; + assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(true)); + state.set(qstate::READ, 10); + assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(false)); + assert_eq!(info.reads.get(), 0); + // queue_passed with queued work behind flight (including wrap-around) never reads qinfo. fw.engine.ta_head = 2; fw.channels.ta = Pipe { read: 2, completion: 2, write: 3 }; - let f = Flight { c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; + let f = Flight { compute_pipe: 0, c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; state.set(qstate::READ, 1); assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(true)); assert_eq!(info.reads.get(), 0); @@ -536,8 +620,11 @@ def function(text, name): } '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: - harness=harness.replace(token,function((backend/path).read_text(),name)) +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: + body = function((backend/path).read_text(),name) + if token in ('__RETIRED_FLIGHT__', '__RETIRED_FLIGHT_CLASSES__', '__RETIRED_SNAPSHOT_AT__'): + body = body.replace('super::hw::', 'hw::') + harness=harness.replace(token, body) hw_text=(backend/'hw.rs').read_text() def mod_block(text, name): start=text.index('pub(crate) mod '+name+' {') From e30cdb92b4f596a5c183f35abb8d401e4ca84320 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 12:56:36 -0500 Subject: [PATCH 0880/1514] drm/asahi: g16: scale warm render PB/UMA slots to 16 and keep pass slots VM-affine Multi-process render workloads with d=4, 8, or 16 concurrent VMs thrashed the two shared base PB/UMA allocator slots, forcing full engine drains and InitBM epoch reinitializations on every cross-VM handoff as well as cross-VM full pass-slot scrubs. Expand the device-wide warm PB/UMA allocator pool to 16 slots (WARM_PB_SLOTS = 16, hardware UMA slots 33..48) plus 4 lazy quarantine spares (EXT_PB_SLOTS = 4, hardware UMA slots 49..52) while keeping every VM's client VA footprint unchanged at 2 base units (local indices 0..2, assigned rotating [home, alt] pairs) and up to 4 lazy recovery spares (local indices 2..6). Add mask-based Pools selection that prefers a VM's unused home slot so 16 concurrent VMs bind 16 disjoint warm slots regardless of arrival order and pipeline with zero InitBM after warmup. Add VM-affine render pass selection (Slots::pick_pass_in_for) and scale bursting VMs to Tier 1 pass headroom (18 slots) when active_render_vms >= 8 while keeping PB_HEAP_EXT_TIERS gated on single-VM pass demand so concurrent light renders do not expand to 256 MiB PB heaps. Also trim PbEpoch::prepare WC list seeding to the active heap_blocks prefix (plus any shrink tail on unpublished retries). Verified with asahi-m4 (25/25) and asahi-g15 (81/81) host selftests and checkpatch.pl (0 errors, 0 warnings). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 41 ++- drivers/gpu/drm/asahi/g16/hw.rs | 28 +- drivers/gpu/drm/asahi/g16/mod.rs | 13 +- drivers/gpu/drm/asahi/g16/poll.rs | 4 +- drivers/gpu/drm/asahi/g16/pools.rs | 196 +++++++++++- drivers/gpu/drm/asahi/g16/queue.rs | 4 +- drivers/gpu/drm/asahi/g16/resources.rs | 212 ++++++++++--- drivers/gpu/drm/asahi/g16/slots.rs | 70 ++++- .../drivers/gpu/asahi-m4/test-publication.py | 5 +- .../drivers/gpu/asahi-m4/test-resources.py | 290 +++++++++++++++--- 10 files changed, 717 insertions(+), 146 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 773207879b5e90..722b2fba551f88 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1127,8 +1127,8 @@ impl Firmware { && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) && (job .resources - .pb_slots() - .is_ok_and(|n| self.pools.exhausted_for_within(&job.vm, n)) + .pb_slot_mask() + .is_ok_and(|(mask, home)| self.pools.exhausted_for_mask(&job.vm, mask, home)) || job .resources .render_passes() @@ -1305,10 +1305,11 @@ impl Firmware { || (is_render && !job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools + .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) })) } @@ -1486,10 +1487,11 @@ impl Firmware { && super::recovery::logic::next_ordinal(e.draw).is_some() && job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools + .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) }) && job .resources @@ -1829,13 +1831,13 @@ impl Firmware { let mut a = job .resources .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; - let pb_slots = job.resources.pb_slots()?; + let (pb_mask, _) = job.resources.pb_slot_mask()?; let heap_blocks = job.resources.pb_heap_blocks()?; // Reuse this VM's retired epoch of the allocator slot when still bound and sized for the // VM's current PB heap (no reseed/InitBM); if the PB heap grew, rotate onto a fresh epoch. let (epoch, reused) = match self .pools - .reusable_for_within(alloc_slot, &job.vm, pb_slots, heap_blocks) + .reusable_for_mask(alloc_slot, &job.vm, pb_mask, heap_blocks) { Some(e) => { self.pools.stats.reused += 1; @@ -2271,7 +2273,10 @@ impl Firmware { }) { return Err(E2BIG); } - let Some(k) = self.slots.pick_pass_in(&job.resources, &geometry, 0) else { + let Some(k) = + self.slots + .pick_pass_in_for(&job.resources, &geometry, 0, Some(job.vm.id)) + else { self.engine.slot_wait = true; return Err(EAGAIN); }; @@ -2328,10 +2333,11 @@ impl Firmware { break; } let geo2 = Geometry::new(&r2.cmd, 0); - let Some(k2) = self.slots.pick_pass_in( + let Some(k2) = self.slots.pick_pass_in_for( &job.resources, &geo2, f.claims.pass_mask, + Some(job.vm.id), ) else { break; }; @@ -2457,10 +2463,11 @@ impl Firmware { break; }; let geo2 = Geometry::new(&r2.cmd, 0); - let Some(slot) = self.slots.pick_pass_in( + let Some(slot) = self.slots.pick_pass_in_for( &job.resources, &geo2, picked_mask, + Some(job.vm.id), ) else { precheck_ok = false; break; @@ -3039,11 +3046,11 @@ impl Firmware { .claim_pass_in(resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; self.slots.hold_render_pass(k, &job.vm, resources)?; let (refs, init_buffer) = if member == 0 { - let pb_slots = resources.pb_slots()?; + let (pb_mask, pb_home) = resources.pb_slot_mask()?; let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_within_blocks(&job.vm, behind, pb_slots, heap_blocks) + .pick_slot_in_mask_blocks(&job.vm, behind, pb_mask, pb_home, heap_blocks) .ok_or(EAGAIN)?; let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index a9c5cad5814db5..155c8f528abb23 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -607,9 +607,9 @@ pub(crate) mod client { pub(crate) const CWORK_STRIDE: u64 = 0x4000; // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a - // 64 MiB stride. Slots 0..4 live in 0x7010000000..0x7020000000; slots 4..PB_SLOTS - // live in 0x7008000000..0x7010000000, above base compute units 0..2 (ending at - // 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). + // 64 MiB stride. Per-VM local slots 0..4 live in 0x7010000000..0x7020000000; local slots + // 4..MAX_VM_PB_SLOTS live in 0x7008000000..0x7010000000, above base compute units 0..2 + // (ending at 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). pub(crate) const fn render_base(k: u64) -> u64 { if k < 4 { 0x7010000000 + k * 0x04000000 @@ -714,11 +714,23 @@ pub(crate) mod sizes { pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base physical PB/UMA allocator slots allocated per VM on first render. pub(crate) const BASE_PB_SLOTS: usize = 2; - /// Physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware UMA slot 33). - /// Base slots `0..BASE_PB_SLOTS` serve normal cross-VM switching; extra slots are allocated - /// lazily per VM only after a render hang permanently quarantines an allocator slot. - pub(crate) const PB_SLOTS: usize = 6; - const _: () = assert!(PB_SLOTS >= BASE_PB_SLOTS && PB_SLOTS <= 6); + /// Device-wide warm physical PB/UMA allocator slots (`parameter_id` `0..WARM_PB_SLOTS`, + /// hardware UMA slots `33..33 + WARM_PB_SLOTS`). Each VM maps two base units (`local_idx` + /// `0..BASE_PB_SLOTS`) bound to a rotating `[home, alt]` pair in this pool so up to + /// `WARM_PB_SLOTS` concurrent render VMs stay warm without extra per-VM memory. + pub(crate) const WARM_PB_SLOTS: usize = 16; + /// Lazily allocated recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`, mapped at + /// per-VM local VA indices `BASE_PB_SLOTS..MAX_VM_PB_SLOTS`) claimed only after a render + /// hang permanently quarantines an allocator slot. + pub(crate) const EXT_PB_SLOTS: usize = 4; + /// Maximum PB/UMA allocator slots mapped in one VM's client VA space (`render_base(0..6)`). + pub(crate) const MAX_VM_PB_SLOTS: usize = BASE_PB_SLOTS + EXT_PB_SLOTS; + /// Total device-wide physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware + /// UMA slots `RENDER_UMA_SLOT..RENDER_UMA_SLOT + PB_SLOTS`). + pub(crate) const PB_SLOTS: usize = WARM_PB_SLOTS + EXT_PB_SLOTS; + const _: () = assert!(WARM_PB_SLOTS >= BASE_PB_SLOTS); + const _: () = assert!(MAX_VM_PB_SLOTS >= BASE_PB_SLOTS && MAX_VM_PB_SLOTS <= 6); + const _: () = assert!(PB_SLOTS <= 32); const _: () = assert!(super::client::compute_context(1) + 0x40000 <= super::client::render_base(4)); const _: () = diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 30c26d3bc62a51..4a3c7a21966587 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -292,8 +292,12 @@ pub(crate) struct Shared { pub(crate) base_compute_quarantined: AtomicBool, /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. pub(crate) base_render_quarantined: AtomicBool, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) needed_pb_slots: AtomicU32, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: AtomicU32, + /// Round-robin cursor assigning each rendering VM a `[home, alt]` pair in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: AtomicU32, + /// Live open VMs that own a `RenderArena`, used to size multi-VM pass-slot headroom. + pub(crate) active_render_vms: Arc, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -629,6 +633,7 @@ impl Gpu { let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; let scrub_queue = slots::ScrubQueue::new_boxed()?; + let active_render_vms = Arc::new(AtomicU32::new(0), GFP_KERNEL)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -657,7 +662,9 @@ impl Gpu { recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), base_render_quarantined: AtomicBool::new(false), - needed_pb_slots: AtomicU32::new(hw::sizes::BASE_PB_SLOTS as u32), + quarantined_pb_mask: AtomicU32::new(0), + next_pb_slot: AtomicU32::new(0), + active_render_vms, sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 103423bee36260..3ae477db641047 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1350,8 +1350,8 @@ impl Firmware { .base_render_quarantined .store(self.slots.base_render_quarantined(), Ordering::Release); shared - .needed_pb_slots - .store(self.pools.needed_slots() as u32, Ordering::Release); + .quarantined_pb_mask + .store(self.pools.quarantined_mask(), Ordering::Release); } } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 54306b109d66ca..ed445f21829fd1 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -131,7 +131,23 @@ fn write_records( Ok(()) } impl Allocator { + /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. + #[allow(dead_code)] pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { + Self::new_at(o, k, k as u32, heap) + } + /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) + /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot + /// `RENDER_UMA_SLOT + hw_slot`). + pub(crate) fn new_at( + o: &mut Objects, + local_idx: u64, + hw_slot: u32, + heap: &Arc, + ) -> Result { + if local_idx >= sizes::MAX_VM_PB_SLOTS as u64 || (hw_slot as usize) >= sizes::PB_SLOTS { + return Err(EINVAL); + } 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 @@ -141,18 +157,30 @@ impl Allocator { o, 0x4000, Class::Shared, - nc(client::render_descriptor(k)), + nc(client::render_descriptor(local_idx)), false, )?; let pool = alloc( o, 0x2000000, Class::Shared, - nc(client::render_pool(k)), + nc(client::render_pool(local_idx)), false, )?; - 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 state = alloc( + o, + 0x20000, + Class::Shared, + nc(client::render_state(local_idx)), + true, + )?; + let list = alloc( + o, + 0x4000, + Class::Shared, + nc(client::render_list(local_idx)), + true, + )?; let submitted = alloc(o, 0x40, Class::Fw, None, true)?; let heap = heap.clone(); super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; @@ -160,7 +188,7 @@ impl Allocator { 0, &buffer::uma_manager_image( descriptor.va, - engine::RENDER_UMA_SLOT + k as u32, + engine::RENDER_UMA_SLOT + hw_slot, gva(&state)?, gva(&list)?, submitted.va, @@ -175,9 +203,13 @@ impl Allocator { submitted, heap, published: AtomicBool::new(false), - id: k as u32, + id: hw_slot, }) } + /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. + pub(crate) fn id(&self) -> u32 { + self.id + } pub(crate) fn refs(&self) -> Result { let prior = read64(&self.submitted, 0)?; if prior & 1 != 0 { @@ -271,6 +303,14 @@ pub(crate) fn alloc_pb_heap_chunk( impl PoolSet { pub(crate) fn new(o: &mut Objects) -> Result { + Self::new_with_slots(o, [0, 1]) + } + /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and + /// bound to device-wide physical PB/UMA slots `slots`. + pub(crate) fn new_with_slots( + o: &mut Objects, + slots: [usize; sizes::BASE_PB_SLOTS], + ) -> 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); @@ -282,8 +322,11 @@ impl PoolSet { false, )?; let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; - for k in 0..sizes::BASE_PB_SLOTS as u64 { - units.push(Allocator::new(o, k, &heap)?, GFP_KERNEL)?; + for (local, &hw_slot) in slots.iter().enumerate() { + units.push( + Allocator::new_at(o, local as u64, hw_slot as u32, &heap)?, + GFP_KERNEL, + )?; } Ok(Self { units, @@ -424,6 +467,16 @@ impl Pools { GFP_KERNEL, )?) } + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + mask |= 1u32 << k; + } + } + mask + } /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. #[allow(dead_code)] @@ -451,6 +504,10 @@ impl Pools { let n = limit.min(sizes::PB_SLOTS); (0..n).any(|k| self.slot_displaced(k)) } + /// Whether at least one displaced physical PB allocator slot exists in `slot_mask`. + fn has_displaced_slot_in_mask(&self, slot_mask: u32) -> bool { + (0..sizes::PB_SLOTS).any(|k| (slot_mask & (1u32 << k)) != 0 && self.slot_displaced(k)) + } /// 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 @@ -465,6 +522,26 @@ impl Pools { .then(|| owner.clone()) } /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot in `slot_mask` is available + /// to rotate onto safely. + pub(crate) fn reusable_for_mask( + &self, + k: usize, + vm: &Arc, + slot_mask: u32, + min_blocks: u32, + ) -> Option> { + if k >= sizes::PB_SLOTS || (slot_mask & (1u32 << k)) == 0 { + return None; + } + let owner = self.reusable(k, vm)?; + if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_in_mask(slot_mask) { + Some(owner) + } else { + None + } + } + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available /// to rotate onto safely. #[allow(dead_code)] @@ -482,6 +559,91 @@ impl Pools { None } } + /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm`, preferring `home` when + /// claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to `WARM_PB_SLOTS` concurrent VMs + /// bind disjoint warm slots regardless of arrival order. + pub(crate) fn pick_slot_in_mask_blocks( + &self, + vm: &Arc, + behind: bool, + slot_mask: u32, + home: usize, + min_blocks: u32, + ) -> Option { + let in_mask = |k: usize| k < sizes::PB_SLOTS && (slot_mask & (1u32 << k)) != 0; + if let Some(a) = self.active { + if in_mask(a) + && self + .reusable_for_mask(a, vm, slot_mask, min_blocks) + .is_some() + { + return Some(a); + } + } + if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { + in_mask(k) + && self + .reusable_for_mask(k, vm, slot_mask, min_blocks) + .is_some() + }) { + return Some(k); + } + if behind { + return None; + } + // Cold (drained): claim the VM's unused home slot first, then any unused warm slot, + // then a displaced warm slot (preferring home), and finally recovery spares. + if home < sizes::WARM_PB_SLOTS + && in_mask(home) + && self.slot_displaced(home) + && self.owners[home].is_none() + { + return Some(home); + } + if let Some(k) = (0..sizes::WARM_PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_none()) + { + return Some(k); + } + if home < sizes::WARM_PB_SLOTS && in_mask(home) && self.slot_displaced(home) { + return Some(home); + } + if let Some(k) = + (0..sizes::WARM_PB_SLOTS).find(|&k| in_mask(k) && self.slot_displaced(k)) + { + return Some(k); + } + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| { + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k)) + }) + } + /// Whether `vm` has a warm reusable PB slot in `slot_mask` covering `min_blocks` so it can + /// pipeline without InitBM. + pub(crate) fn can_pipeline_in_mask_blocks( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + min_blocks: u32, + ) -> bool { + self.pick_slot_in_mask_blocks(vm, true, slot_mask, home, min_blocks) + .is_some() + } + /// Whether no allocator slot in `slot_mask` can accept a render for `vm` once drained. + pub(crate) fn exhausted_for_mask( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_in_mask_blocks(vm, false, slot_mask, home, 0) + .is_none() + } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. /// @@ -492,6 +654,7 @@ impl Pools { /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot /// working set) or the lowest fresh slot is claimed. + #[allow(dead_code)] pub(crate) fn pick_slot_within_blocks( &self, vm: &Arc, @@ -518,6 +681,7 @@ impl Pools { .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. + #[allow(dead_code)] pub(crate) fn pick_slot_within( &self, vm: &Arc, @@ -739,6 +903,9 @@ pub(crate) struct PbEpochInner { pub(crate) initbm: Arc, assigned: AtomicU32, heap_blocks: AtomicU32, + /// High-water block count previously written into the zero-allocated `pages`/`blocks` lists, + /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). + seeded_blocks: AtomicU32, exposed: AtomicBool, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, @@ -764,6 +931,7 @@ impl PbEpoch { initbm: FwObject::view(&records, 0x400, 0x20)?, assigned: AtomicU32::new(u32::MAX), heap_blocks: AtomicU32::new(0), + seeded_blocks: AtomicU32::new(0), exposed: AtomicBool::new(false), _objects: o, _vm: vm.clone(), @@ -786,13 +954,18 @@ impl PbEpoch { { return Err(EINVAL); } - // Only the backed part of the heap is named; the rest of the lists stays zero. + // Only the backed part of the heap is named; the rest of the zero-allocated lists stays + // zero. On an unpublished retry with fewer blocks, clear the previously seeded tail. + let prev_blocks = self.seeded_blocks.load(Ordering::Acquire); + let write_blocks = heap_blocks.max(prev_blocks); + self.seeded_blocks.store(write_blocks, Ordering::Release); let pages = heap_blocks * buffer::PAGES_PER_BLOCK; - write_records(&self.pages, buffer::MAX_PAGES as usize, |i| { + let write_pages = write_blocks * buffer::PAGES_PER_BLOCK; + write_records(&self.pages, write_pages as usize, |i| { 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| { + write_records(&self.blocks, write_blocks as usize, |i| { let b = i as u32; u64::from(if b < heap_blocks { buffer::block_record(heap, b) } else { 0 }).to_le_bytes() })?; @@ -812,6 +985,7 @@ impl PbEpoch { heap_blocks, ), )?; + self.seeded_blocks.store(heap_blocks, Ordering::Release); self.assigned.store(k as u32, Ordering::Release); self.heap_blocks.store(heap_blocks, Ordering::Release); Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 27130582a881bf..f8e8462a063f13 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -265,7 +265,9 @@ impl Queue { let hints = super::resources::PrepareHints { expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), - pb_slots: self.shared.needed_pb_slots.load(Ordering::Acquire) as usize, + quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), + next_pb_slot: &self.shared.next_pb_slot, + active_render_vms: &self.shared.active_render_vms, }; let resources = self .vm diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 84871c04b1675d..aad844d07e73e6 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -106,7 +106,7 @@ const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; -const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; +const EXT_PB_SLOTS: usize = super::hw::sizes::EXT_PB_SLOTS; /// Demand-grown contiguous PB heap extensions within the 256 MiB /// [`super::hw::client::PB_HEAP_SIZE`] window so steady 60/120 Hz single-pass clients stay on /// the 64 MiB base heap while multi-pass and heavy 3D workloads expand to 128 MiB (Tier 0) and @@ -124,14 +124,18 @@ const _: () = assert!( const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; /// Device-wide hints read locklessly in `SUBMIT` to size per-VM extension backing. -#[derive(Copy, Clone, Default)] -pub(crate) struct PrepareHints { +#[derive(Copy, Clone)] +pub(crate) struct PrepareHints<'a> { /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. pub(crate) expand_compute_ext: bool, /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. pub(crate) expand_render_ext: bool, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) pb_slots: usize, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: u32, + /// Round-robin cursor assigning a VM's `[home, alt]` base PB/UMA slots in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: &'a AtomicU32, + /// Live open VMs owning a `RenderArena`, used for multi-VM pass-slot headroom. + pub(crate) active_render_vms: &'a Arc, } /// Updates the consecutive-compute burst counter and reports whether this submission @@ -209,6 +213,51 @@ fn target_render_slots( target.min(super::hw::sizes::RENDER_SLOTS) } +/// Like [`target_render_slots`], returning `(effective_target, single_vm_target)`. +/// +/// When `active_render_vms` reaches Tier 0's pass-slot ceiling (`EXT_RENDER_TIERS[0].1 == 8`) +/// and this VM is already bursting (`single_vm_target > BASE_RENDER_SLOTS`), `effective_target` +/// expands up to Tier 1 (`EXT_RENDER_TIERS[1].1 == 18`) so up to 16 concurrent render VMs each +/// keep a warm pass slot without cross-VM full-scrub thrashing. Steady 60/120 Hz single-pass +/// clients stay at `BASE_RENDER_SLOTS`, and `single_vm_target` keeps `PB_HEAP_EXT_TIERS` gated +/// on actual single-VM pass demand so multi-VM light renders do not expand to 256 MiB PB heaps. +fn target_render_slots_for( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_passes: u32, + base_quarantined: bool, + current_slots: usize, + single_vm_slots: usize, + active_render_vms: u32, +) -> (usize, usize) { + let single = target_render_slots( + last_render_ns, + render_burst, + now, + render_count, + active_passes, + base_quarantined, + single_vm_slots.max(BASE_RENDER_SLOTS), + ); + let mut target = current_slots.max(single); + if single > BASE_RENDER_SLOTS && (active_render_vms as usize) >= EXT_RENDER_TIERS[0].1 { + let multi_need = (active_render_vms as usize) + .saturating_add(1) + .min(EXT_RENDER_TIERS[1].1); + for &(start, end) in &EXT_RENDER_TIERS[..2] { + if target >= multi_need { + break; + } + if target < end && multi_need > start { + target = end; + } + } + } + (target.min(super::hw::sizes::RENDER_SLOTS), single) +} + pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { type Target = RenderInner; @@ -219,6 +268,8 @@ impl core::ops::Deref for RenderArena { pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, + /// Device-wide physical PB/UMA allocator slots `[home, alt]` bound to `pools.unit(0..2)`. + pub(crate) base_pb_slots: [usize; BASE_PB_SLOTS], pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], @@ -243,18 +294,20 @@ impl RenderArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + base_pb_slots: [usize; BASE_PB_SLOTS], ) -> Result> { let mut objects = factory.objects(vm); 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)?; + let pools = PoolSet::new_with_slots(&mut objects, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { passes, pools, + base_pb_slots, tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], @@ -345,8 +398,9 @@ impl RenderExtArena { } } -/// One lazily allocated recovery PB/UMA allocator slot (`BASE_PB_SLOTS..PB_SLOTS`), -/// sharing the VM's base PB heap so non-fault VMs pay zero extra allocator memory. +/// One lazily allocated recovery PB/UMA allocator slot (`WARM_PB_SLOTS..PB_SLOTS`), +/// mapped at per-VM local VA index `BASE_PB_SLOTS..MAX_VM_PB_SLOTS` and sharing the VM's base PB +/// heap so non-fault VMs pay zero extra allocator memory. pub(crate) struct PoolExtArena(crate::cleanup::Deferred); impl core::ops::Deref for PoolExtArena { type Target = PoolExtInner; @@ -366,11 +420,13 @@ impl PoolExtArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - slot: usize, + local_idx: usize, + hw_slot: usize, heap: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let allocator = super::pools::Allocator::new(&mut objects, slot as u64, heap)?; + let allocator = + super::pools::Allocator::new_at(&mut objects, local_idx as u64, hw_slot as u32, heap)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(PoolExtInner { @@ -490,8 +546,13 @@ struct Ready { render_ext: [Option>; EXT_RENDER_TIERS.len()], /// Demand-grown contiguous PB heap extension tiers (`PB_HEAP_EXT_TIERS`). pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], - /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. + /// Recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], + /// Single-VM render pass slot target (excluding multi-VM Tier 1 expansion), gating + /// `PB_HEAP_EXT_TIERS` so concurrent light-render VMs do not allocate 256 MiB PB heaps. + single_vm_render_slots: usize, + /// Device-wide count of open rendering VMs; decremented once on `Cache::close()` or drop. + render_vm_counter: Option>, /// Last compute submission and the back-to-back run it continues. last_compute_ns: u64, burst: u32, @@ -499,6 +560,13 @@ struct Ready { last_render_ns: u64, render_burst: u32, } +impl Drop for Ready { + fn drop(&mut self) { + if let Some(counter) = self.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } + } +} 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`. @@ -662,6 +730,9 @@ impl Cache { self.standby_available.notify_all(); let ready = { let mut ready = self.ready.lock(); + if let Some(counter) = ready.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } ( ready.compute.take(), ready.compute_ext.take(), @@ -678,7 +749,7 @@ impl Cache { self: &Arc, vm: &Arc, commands: &[Command], - hints: PrepareHints, + hints: PrepareHints<'_>, ) -> Result { let computes = commands .iter() @@ -733,34 +804,63 @@ impl Cache { } } if render && ready.render.is_none() { + let home = (hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize) + % super::hw::sizes::WARM_PB_SLOTS; + let alt = (home + 1) % super::hw::sizes::WARM_PB_SLOTS; ready.render = Some(RenderArena::new( &self.factory, &self.bind, &vm.vm, &self.live, + [home, alt], )?); + if ready.render_vm_counter.is_none() { + hints.active_render_vms.fetch_add(1, Ordering::AcqRel); + ready.render_vm_counter = Some(hints.active_render_vms.clone()); + } } if render { - let target_pb = hints.pb_slots.clamp(BASE_PB_SLOTS, super::hw::sizes::PB_SLOTS); - if target_pb > BASE_PB_SLOTS { - if let Some(base) = ready.render.as_ref() { + if let Some(base) = ready.render.as_ref() { + let quarantined = hints.quarantined_pb_mask; + let mut healthy = base + .base_pb_slots + .iter() + .filter(|&&slot| (quarantined & (1u32 << slot)) == 0) + .count(); + for (idx, ext) in ready.pb_ext.iter().enumerate() { + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ext.is_some() && (quarantined & (1u32 << hw_slot)) == 0 { + healthy += 1; + } + } + if healthy < BASE_PB_SLOTS { let heap = base.pools.heap().clone(); - for k in BASE_PB_SLOTS..target_pb { - let idx = k - BASE_PB_SLOTS; - if ready.pb_ext[idx].is_none() { - // Best effort: without recovery slots, keep prior PB slots. - ready.pb_ext[idx] = PoolExtArena::new( - &self.factory, - &self.bind, - &vm.vm, - &self.live, - k, - &heap, - ) - .ok(); - if ready.pb_ext[idx].is_none() { - break; - } + for idx in 0..EXT_PB_SLOTS { + if healthy >= BASE_PB_SLOTS { + break; + } + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ready.pb_ext[idx].is_some() + || (quarantined & (1u32 << hw_slot)) != 0 + { + continue; + } + let local_idx = BASE_PB_SLOTS + idx; + // Best effort: without recovery slots, keep prior PB slots. + ready.pb_ext[idx] = PoolExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + local_idx, + hw_slot, + &heap, + ) + .ok(); + if ready.pb_ext[idx].is_some() { + healthy += 1; + } else { + break; } } } @@ -778,7 +878,8 @@ impl Cache { let now = unsafe { kernel::bindings::ktime_get() } as u64; let state = &mut *ready; let active_passes = self.active_render_passes.load(Ordering::Acquire); - let target = target_render_slots( + let active_vms = hints.active_render_vms.load(Ordering::Acquire); + let (target, single_target) = target_render_slots_for( &mut state.last_render_ns, &mut state.render_burst, now, @@ -786,7 +887,10 @@ impl Cache { active_passes, hints.expand_render_ext, current_slots, + state.single_vm_render_slots, + active_vms, ); + state.single_vm_render_slots = state.single_vm_render_slots.max(single_target); for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { if start >= target { break; @@ -809,8 +913,11 @@ impl Cache { } if let Some(base) = ready.render.as_ref() { let base_blocks = base.pools.heap_blocks(); + let single_slots = ready.single_vm_render_slots; for (idx, &(start, end)) in PB_HEAP_EXT_TIERS.iter().enumerate() { - if ready.render_ext[idx].is_none() { + if single_slots < EXT_RENDER_TIERS[idx].1 + || ready.render_ext[idx].is_none() + { break; } if base_blocks >= end { @@ -1015,23 +1122,31 @@ impl Prepared { self.compute_ext.clone() } } - /// Contiguous PB/UMA allocator slots (`0..n`) this job can use. - pub(crate) fn pb_slots(&self) -> Result { - let _ = self.render()?; - let ext = self.pb_ext.iter().take_while(|slot| slot.is_some()).count(); - Ok(BASE_PB_SLOTS + ext) + /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. + pub(crate) fn pb_slot_mask(&self) -> Result<(u32, usize)> { + let base = self.render()?; + let mut mask = 0u32; + for &slot in &base.base_pb_slots { + mask |= 1u32 << slot; + } + for (idx, ext) in self.pb_ext.iter().enumerate() { + if ext.is_some() { + mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + } + } + Ok((mask, base.base_pb_slots[0])) } fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { let base = self.render()?; - if k < BASE_PB_SLOTS { - base.pools.unit(k).ok_or(EINVAL) - } else { - self.pb_ext - .get(k - BASE_PB_SLOTS) - .and_then(|slot| slot.as_deref()) - .map(|arena| &arena.allocator) - .ok_or(EINVAL) + if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { + return base.pools.unit(local).ok_or(EINVAL); } + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS).ok_or(EINVAL)?; + self.pb_ext + .get(idx) + .and_then(|slot| slot.as_deref()) + .map(|arena| &arena.allocator) + .ok_or(EINVAL) } pub(crate) fn prepare_pb_in_flight( &self, @@ -1071,11 +1186,12 @@ impl Prepared { pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { let base = self.render.as_ref()?; let heap_ext = core::array::from_fn(|idx| self.pb_heap_ext[idx].clone()); - if k < BASE_PB_SLOTS { + if base.base_pb_slots.contains(&k) { Some(PbOwnerArena::Base(base.clone(), heap_ext)) } else { + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS)?; self.pb_ext - .get(k - BASE_PB_SLOTS) + .get(idx) .and_then(|slot| slot.as_ref()) .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 9f27082581230e..900d25b725e0d9 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -1147,10 +1147,27 @@ impl Slots { resources: &super::resources::Prepared, geo: &Geometry, picked: u64, + ) -> Option { + self.pick_pass_in_for(resources, geo, picked, None) + } + /// Selects a render pass slot in `resources` with capacity for `geo`, preferring slots + /// already owned by `vm_id` (clean before dirty) and unowned slots before retargeting + /// another VM's warm pass slot. + pub(crate) fn pick_pass_in_for( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u64, + vm_id: Option, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); - let mut clean_partial = None; - let mut fallback = None; + let mut same_clean_partial = None; + let mut same_dirty = None; + let mut unowned_clean = None; + let mut unowned_dirty = None; + let mut other_full_clean = None; + let mut other_clean_partial = None; + let mut other_dirty = None; let mut saw_scrubbing = false; for i in 0..n { let k = (self.pass_cursor as usize + i) % n; @@ -1166,22 +1183,55 @@ impl Slots { saw_scrubbing = true; continue; } - if self.scrub.is_clean(k) { - if let Ok(d) = resources.render_pass_dirty(k) { + let clean = self.scrub.is_clean(k); + let full_clean = clean + && resources.render_pass_dirty(k).is_ok_and(|d| { let need = d.tilemap.load(Ordering::Acquire).min(geo.tilemap_bytes); - if need <= d.tilemap_clean.load(Ordering::Acquire) + need <= d.tilemap_clean.load(Ordering::Acquire) && d.heap.load(Ordering::Acquire) == 0 - { + }); + if let Some(id) = vm_id { + let same_vm = !self.render.scrub_full[k] + && self.render.owner[k].as_ref().is_some_and(|o| o.id == id); + if same_vm { + if full_clean { return Some(k); } + if clean { + same_clean_partial.get_or_insert(k); + } else { + same_dirty.get_or_insert(k); + } + } else if self.render.owner[k].is_none() { + if full_clean { + unowned_clean.get_or_insert(k); + } else { + unowned_dirty.get_or_insert(k); + } + } else if full_clean { + other_full_clean.get_or_insert(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - clean_partial.get_or_insert(k); - continue; + } else if full_clean { + return Some(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - fallback.get_or_insert(k); } } - if let Some(k) = clean_partial.or(fallback) { + if let Some(k) = same_clean_partial + .or(same_dirty) + .or(unowned_clean) + .or(unowned_dirty) + .or(other_full_clean) + .or(other_clean_partial) + .or(other_dirty) + { return Some(k); } if saw_scrubbing { 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 f15af074a62211..269925c85b0005 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -117,7 +117,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)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -162,9 +162,11 @@ def item(declaration): fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} + fn exhausted_for_mask(&self,vm:&Vm,_mask:u32,_home:usize)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -744,6 +746,7 @@ def item(declaration): fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { 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 7687dfb409bab3..860e6f89d8240c 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -97,10 +97,10 @@ def module(text, name): #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,Mmio} pub enum Placement{Anywhere} pub struct Request{pub size:usize,pub class:Class,pub placement:Placement,pub offset:usize,pub client:Option<(u64,u64)>,pub lower:Option,pub cpu:bool} - pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool} + pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool,pub write_bytes:std::sync::atomic::AtomicUsize} impl FwObject{ - pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)} - pub fn write(&self,o:usize,b:&[u8])->Result{let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} + pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)} + pub fn write(&self,o:usize,b:&[u8])->Result{self.write_bytes.fetch_add(b.len(),std::sync::atomic::Ordering::Relaxed);let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} pub fn fill(&self,o:usize,v:u8,n:usize)->Result{if self.fail_fill.swap(false,std::sync::atomic::Ordering::Relaxed){return Err(EIO);}self.fills.lock().unwrap().push((o,n));let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+n].fill(v);Ok(())} pub fn w32(&self,o:usize,v:u32)->Result{self.write(o,&v.to_le_bytes())} pub fn w64(&self,o:usize,v:u64)->Result{self.write(o,&v.to_le_bytes())} @@ -109,12 +109,13 @@ def module(text, name): } pub struct Factory; impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} + std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} pub struct Objects{pub objects:Vec>,next:u64} impl Objects{ pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)?;self.objects.push(x.clone());Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -605,9 +606,11 @@ def module(text, name): assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); let pools=PoolSet::new(&mut o).unwrap(); - for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { - let ext=g16::pools::Allocator::new(&mut o,k,pools.heap()).unwrap(); - assert_eq!(ext.refs().unwrap().parameter_id,k as u32); + for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { + let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; + let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; + let ext=g16::pools::Allocator::new_at(&mut o,local,hw_slot,pools.heap()).unwrap(); + assert_eq!(ext.refs().unwrap().parameter_id,hw_slot); } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { g16::slots::ComputeSlot::new(&mut o,k).unwrap(); @@ -702,10 +705,31 @@ def module(text, name): #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new_with_slots(&mut o,[7,8]).unwrap(); + assert_eq!(pools.unit(0).unwrap().id(),7); + assert_eq!(pools.unit(1).unwrap().id(),8); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + g16::hw::sizes::MAX_VM_PB_SLOTS as u64, + 0, + pools.heap() + ).err(), + Some(EINVAL) + ); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + 0, + g16::hw::sizes::PB_SLOTS as u32, + pools.heap() + ).err(), + Some(EINVAL) + ); let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { - let alloc=g16::pools::Allocator::new(&mut o,k as u64,pools.heap()).unwrap(); + let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; + let alloc=g16::pools::Allocator::new_at(&mut o,local,k as u32,pools.heap()).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); @@ -827,57 +851,61 @@ def module(text, name): e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); e }; + let warm=g16::hw::sizes::WARM_PB_SLOTS; + let ext=g16::hw::sizes::EXT_PB_SLOTS; + let total=g16::hw::sizes::PB_SLOTS; let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); - // Quarantine 4 slots (0..4): 2 healthy slots (4 and 5) remain for cross-VM switching. - for hang in 0..4usize { - let n=p.needed_slots(); - let slot=p.pick_slot_within(&vm1,false,n).unwrap(); - assert_eq!(slot,hang); + // A VM bound to [0, 1] with all 4 recovery spares (16..20) survives 4 hangs cleanly + // and keeps 2 healthy slots (18, 19) for cross-VM switching. + let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< global pool exhaustion. + // Cross-VM switching still works cleanly across surviving spares 18 and 19. + let s_a=warm+2;let s_b=warm+3; + assert_eq!(p.pick_slot_in_mask_blocks(&vm1,false,vm_mask,0,0),Some(s_a)); + let ea=mk_epoch(&vm1,s_a); + let b=p.bind(s_a,false);p.publish_flight(s_a);p.retire_flight(s_a,&ea,b,true).unwrap(); + assert_eq!(p.pick_slot_in_mask_blocks(&vm2,false,vm_mask,0,0),Some(s_b)); + let eb=mk_epoch(&vm2,s_b); + let b=p.bind(s_b,false);p.publish_flight(s_b);p.retire_flight(s_b,&eb,b,true).unwrap(); + assert_eq!(p.pick_slot_in_mask_blocks(&vm1,false,vm_mask,0,0),Some(s_a)); + // 5th hang quarantines s_a: only s_b survives (reuse-only for VM2; VM1/VM3 exhausted). + p.publish_flight(s_a); + p.quarantine_flight(s_a,None); + assert!(!p.exhausted_for_mask(&vm2,vm_mask,0)); + assert_eq!(p.pick_slot_in_mask_blocks(&vm2,false,vm_mask,0,0),Some(s_b)); + assert!(p.exhausted_for_mask(&vm1,vm_mask,0)); + assert!(p.exhausted_for_mask(&vm3,vm_mask,0)); p.invalidate(); - assert!(p.exhausted()); + assert!(p.exhausted_for_mask(&vm2,vm_mask,0)); - // Quarantine 5 fresh slots leaving slot 5 fresh: VM2 claims and reuses slot 5 while - // other VMs report per-VM exhaustion without tripping global exhaustion until recovery. + // Quarantine all but the last global slot leaving slot (PB_SLOTS - 1) fresh: + // VM2 claims and reuses it while other VMs report exhaustion until recovery. let mut q=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); - for _ in 0..5 { + for _ in 0..(total - 1) { let slot=q.pick_slot(&vm1,false).unwrap(); q.publish_flight(slot); q.quarantine_flight(slot,None); assert!(!q.exhausted()); } - assert_eq!(q.pick_slot(&vm2,false),Some(5)); - let qe5=mk_epoch(&vm2,5); - let qb=q.bind(5,false); - q.publish_flight(5); + let last=total-1; + assert_eq!(q.pick_slot(&vm2,false),Some(last)); + let qlast=mk_epoch(&vm2,last); + let qb=q.bind(last,false); + q.publish_flight(last); assert!(!q.exhausted_for(&vm3)); // in-flight: waits for drain first - q.retire_flight(5,&qe5,qb,true).unwrap(); + q.retire_flight(last,&qlast,qb,true).unwrap(); assert!(!q.exhausted()); assert!(!q.exhausted_for(&vm2)); - assert_eq!(q.pick_slot(&vm2,false),Some(5)); + assert_eq!(q.pick_slot(&vm2,false),Some(last)); assert!(q.exhausted_for(&vm1)); assert!(q.exhausted_for(&vm3)); // Recovery invalidates the last surviving slot's epoch -> global pool exhaustion. @@ -1822,6 +1850,177 @@ def module(text, name): assert_eq!(s.stats.cross_vm_retargets[0], 0); } + #[test]fn warm_pb_pool_keeps_sixteen_concurrent_vms_warm_and_handles_overflow(){ + let warm = g16::hw::sizes::WARM_PB_SLOTS; + assert_eq!(warm, 16); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mk_epoch = |owner: &sync::Arc, slot: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + owner, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.check_assignment(slot).unwrap(); + e.expose(); + e + }; + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let vms: Vec<_> = (0..20usize).map(|i| vm(100 + i as u64)).collect(); + let mask_for = |i: usize| -> (u32, usize) { + let home = i % warm; + let alt = (home + 1) % warm; + ((1u32 << home) | (1u32 << alt), home) + }; + // Prime 16 VMs arriving in scrambled (reverse) order: each claims its own home slot! + let mut epochs = Vec::new(); + for i in (0..warm).rev() { + let (mask, home) = mask_for(i); + let slot = p.pick_slot_in_mask_blocks(&vms[i], false, mask, home, 512).unwrap(); + assert_eq!(slot, home, "VM {i} must claim its home slot {home} despite reverse arrival"); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + epochs.push((i, e)); + } + // All 16 VMs now pipeline concurrently (behind=true) on 16 disjoint warm slots with 0 InitBM. + let mut binds = Vec::new(); + for &(i, ref _e) in &epochs { + let (mask, home) = mask_for(i); + assert!(p.can_pipeline_in_mask_blocks(&vms[i], mask, home, 512)); + let slot = p.pick_slot_in_mask_blocks(&vms[i], true, mask, home, 512).unwrap(); + assert_eq!(slot, home); + assert!(p.reusable_for_mask(slot, &vms[i], mask, 512).is_some()); + let b = p.bind(slot, true); + p.publish_flight(slot); + binds.push((i, slot, b)); + } + for (idx, (i, slot, b)) in binds.into_iter().enumerate() { + assert_eq!(p.slot_inflight(slot), 1); + p.retire_flight(slot, &epochs[idx].1, b, true).unwrap(); + assert_eq!(p.slot_inflight(slot), 0); + let _ = i; + } + // Overflow d=20: VMs 16..20 share warm slots [0..4] cleanly on drained displaced rotation. + for i in warm..20 { + let (mask, home) = mask_for(i); + assert!(!p.can_pipeline_in_mask_blocks(&vms[i], mask, home, 512)); + let slot = p.pick_slot_in_mask_blocks(&vms[i], false, mask, home, 512).unwrap(); + assert_ne!(mask & (1u32 << slot), 0); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + } + } + + #[test]fn vm_affine_render_pass_claiming_keeps_sixteen_vms_warm_and_scales_tier1(){ + use g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots_for}; + // Steady 60 Hz depth-1 VM stays at BASE_RENDER_SLOTS even when 16 render VMs are active. + let (mut last, mut burst) = (0u64, 0u32); + let (eff, single) = target_render_slots_for(&mut last, &mut burst, 10_000_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 16); + assert_eq!((eff, single), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + // Bursting VM with 4 active render VMs stays at Tier 0 (8 slots). + for step in 1..=3u64 { + let (e, s) = target_render_slots_for(&mut last, &mut burst, 10_000_000 + step * 500_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 4); + if step < 3 { + assert_eq!((e, s), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + } else { + assert_eq!((e, s), (EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1)); + } + } + // Once active_render_vms reaches 8 or 16, a bursting VM expands effective target to Tier 1 + // (18 slots) while keeping single_vm_target at Tier 0 (8) so PB_HEAP_EXT_TIERS[1] stays off. + let (eff8, single8) = target_render_slots_for(&mut last, &mut burst, 12_000_000, 1, 0, false, EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1, 8); + assert_eq!((eff8, single8), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + let (eff16, single16) = target_render_slots_for(&mut last, &mut burst, 12_500_000, 1, 0, false, eff8, single8, 16); + assert_eq!((eff16, single16), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + // Heavy single-VM multi-pass (8 passes) still advances single_vm_target to Tier 1. + let (eff_heavy, single_heavy) = target_render_slots_for(&mut last, &mut burst, 13_000_000, 8, 0, false, eff16, single16, 16); + assert_eq!((eff_heavy, single_heavy), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[1].1)); + + // 16 concurrent VMs across 18 pass slots stay on 16 disjoint warm pass slots with 0 cross-VM retargets. + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut passes = KVec::new(); + for k in 0..EXT_RENDER_TIERS[1].1 { + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let render = sync::Arc::new(render_arena(passes), 0).unwrap(); + let prep = g16::resources::ComputeArena { + compute: KVec::new(), + render: Some(render), + }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + let vms: Vec<_> = (0..16u64).map(|i| vm(200 + i)).collect(); + let mut vm_slots = [usize::MAX; 16]; + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + vm_slots[i] = k; + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + // Subsequent interleaved rounds across all 16 VMs hit their own warm pass slots every time! + for _round in 0..4 { + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + assert_eq!(k, vm_slots[i], "VM {i} must stay on its warm pass slot"); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(!s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + } + + #[test]fn pb_epoch_prepare_seeds_active_prefix_and_clears_shrink_tail(){ + use g16::fw::buffer; + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let v = vm(300); + g16::object::ALL_OBJECTS.with(|a| a.borrow_mut().clear()); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let (page_obj, block_obj) = g16::object::ALL_OBJECTS.with(|a| { + let objs = a.borrow(); + ( + objs.iter().find(|o| o.gva.is_some() && o.size == buffer::PAGE_LIST_SIZE).unwrap().clone(), + objs.iter().find(|o| o.gva.is_none() && o.size == buffer::BLOCK_LIST_SIZE).unwrap().clone(), + ) + }); + let heap = g16::hw::client::pb_heap(0); + // First prepare for 512 blocks writes ONLY 512*4*4 = 8192 page bytes and 512*8 = 4096 block bytes. + e.prepare(0, heap, 512).unwrap(); + assert_eq!(page_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 4 * 4); + assert_eq!(block_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 8); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + // Grow unpublished epoch to 1024 blocks, then shrink retry back to 512 blocks: + // tail [512..1024] must be zeroed cleanly. + e.prepare(1, heap, 1024).unwrap(); + assert_ne!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_ne!(block_obj.r32(512 * 8).unwrap(), 0); + e.prepare(2, heap, 512).unwrap(); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); + } } ''' poll_source = (production/'poll.rs').read_text() @@ -1875,6 +2074,7 @@ def module(text, name): ) + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots_for(') ) source = source.replace('__CMD_CLASSES__', '\n'.join(item(graph_source, decl) for decl in ('pub(crate) const fn graph_fw(', 'pub(crate) const fn qinfo_cached(', 'pub(crate) const fn cmd_fw(', 'pub(crate) const fn cmd_shared('))).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) graph_types = '\n'.join( @@ -1907,7 +2107,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 35, + 'result': 'pass', 'tests': 38, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From bd41d21140953602ac77ccb9225ef562e68074b5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 16:35:02 -0500 Subject: [PATCH 0881/1514] drm/asahi: g16: add RENDER_RAY_QUERY and BOUNDED_AS_BUILD support Implement cleanroom G16G (M4) hardware ray tracing support on top of the M4 production tree, advertising DRM_ASAHI_FEATURE_RENDER_RAY_QUERY and DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD: - Add pure RT validation, Gen1 SCS sizing, and intersection table helpers in g16/rt.rs (with TAIL_ENABLED = 0x2c), plus UAPI flags/reservations in asahi_drm.h and params.rs. - Extend command.rs stream parsing and SpanBatch VM admission for render ray-query stages, compute ray/SCS requests, and AS-build flags without reintroducing per-span VM locks. - Add demand-sized SCS UMA pools and freelist placement (0x80000 records in dedicated SCS windows) across slots.rs, pools.rs, resources.rs, hw.rs, and fw/buffer.rs, isolating SCS vs base arenas on reuse while retaining firmware PB/UMA leases across closed-VM reclaim. - Wire RT register encoding and J773g SCS bracketing (0x017e1 = 1 first, 0x017d9 = 1 last) in encode/{compute,render}.rs and engine.rs, pinning RT/SCS compute jobs to pipe 0, guarding horizon batching, and applying the 10 s long-job deadline allowance in recovery/logic.rs. Non-RT submits remain byte-identical. - Add test-ray-tracing.py and update asahi-m4 host selftests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 198 +++++- drivers/gpu/drm/asahi/g16/encode.rs | 12 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 162 ++++- drivers/gpu/drm/asahi/g16/encode/render.rs | 179 +++++- drivers/gpu/drm/asahi/g16/engine.rs | 149 ++++- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 24 +- drivers/gpu/drm/asahi/g16/fw/graph.rs | 11 + drivers/gpu/drm/asahi/g16/fw/work.rs | 16 +- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 10 +- drivers/gpu/drm/asahi/g16/hw.rs | 81 ++- drivers/gpu/drm/asahi/g16/job.rs | 10 + drivers/gpu/drm/asahi/g16/mod.rs | 3 +- drivers/gpu/drm/asahi/g16/object.rs | 2 +- drivers/gpu/drm/asahi/g16/params.rs | 6 +- drivers/gpu/drm/asahi/g16/pools.rs | 243 ++++++-- drivers/gpu/drm/asahi/g16/queue.rs | 32 +- drivers/gpu/drm/asahi/g16/recovery.rs | 33 +- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 61 ++ drivers/gpu/drm/asahi/g16/resources.rs | 157 ++++- drivers/gpu/drm/asahi/g16/rt.rs | 531 ++++++++++++++++ drivers/gpu/drm/asahi/g16/slots.rs | 151 ++++- include/uapi/drm/asahi_drm.h | 2 +- .../drivers/gpu/asahi-m4/check-compute.rs | 5 +- .../gpu/asahi-m4/test-command-stream.py | 31 +- .../gpu/asahi-m4/test-progress-wrap.py | 26 +- .../drivers/gpu/asahi-m4/test-publication.py | 84 +-- .../drivers/gpu/asahi-m4/test-ray-tracing.py | 587 ++++++++++++++++++ .../drivers/gpu/asahi-m4/test-resources.py | 249 ++++---- 28 files changed, 2646 insertions(+), 409 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g16/rt.rs create mode 100644 tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 3d6e66ff8bdfd0..c45d53bc86eabc 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -9,7 +9,10 @@ //! Render/compute attachments are retained with the immutable command; the whole //! VM job guard protects indirect and bindless accesses through retirement. //! Exact historical prefixes become immutable per-command dependencies. Ray-query state -//! remains disabled. +//! (RENDER_RAY_QUERY) and the AS-build flag (BOUNDED_AS_BUILD) are the M4 Pro's G17P command +//! set ([`super::rt`]): compute scratch layouts and intersection tables, render ray-query +//! stages, and compute flag bit 2 (alongside COMPUTE_NO_QUERY_ACCESS); every other compute +//! flag and reserved word stays MBZ. use core::mem::{offset_of, size_of}; use core::ops::Range; @@ -169,6 +172,10 @@ impl Order { pub(crate) struct RenderCommand { /// The payload, zero-extended to the full UAPI structure. pub(crate) cmd: uapi::drm_asahi_cmd_render, + /// The validated ray-query state of the vertex and fragment stages. + pub(crate) ray_query: [super::rt::RayQueryStage; 2], + /// The SCS-capable UMA pool of both stages' scratch. + pub(crate) scs: super::rt::ScsSeeds, /// Retained timestamp destinations, published after full command retirement. pub(crate) timestamp_outputs: crate::timestamp::Destinations, /// Explicit hardware attachments in effect for each render engine. @@ -179,6 +186,12 @@ pub(crate) struct RenderCommand { /// A validated compute command. pub(crate) struct ComputeCommand { pub(crate) cmd: uapi::drm_asahi_cmd_compute, + /// The validated scratch layout and intersection tables. + pub(crate) ray: super::rt::ComputeRay, + /// The SCS-capable UMA pool of the scratch. + pub(crate) scs: super::rt::ScsSeeds, + /// DRM_ASAHI_COMPUTE_AS_BUILD. + pub(crate) as_build: bool, /// The compute attachments in effect (validated writable). pub(crate) attachments: KVec, /// Retained timestamp destinations, published after full command retirement. @@ -187,12 +200,43 @@ pub(crate) struct ComputeCommand { pub(crate) query_access: bool, } +impl ComputeCommand { + /// Whether this compute command uses ray-tracing or SCS-scratch state. + pub(crate) fn is_rt(&self) -> bool { + self.as_build || self.ray.intersection.enabled() || self.scs.needed != 0 + } +} + /// A validated command. pub(crate) enum Command { Render(KBox), Compute(KBox), } +impl Command { + /// The command traces rays or builds acceleration structures and gets the long execution + /// allowance, as do the other commands of its submission (`Job::long`). + pub(crate) fn long(&self) -> bool { + match self { + Command::Render(r) => { + super::rt::select(false, r.ray_query.map(|stage| stage.traces()), false) + } + Command::Compute(c) => { + super::rt::select(c.ray.intersection.enabled(), [false; 2], c.as_build) + } + } + } + + /// The SCS-capable UMA pool the command runs on ([`super::rt::ScsSeeds::NONE`] without + /// shader-context scratch). + pub(crate) fn scs(&self) -> super::rt::ScsSeeds { + match self { + Command::Render(r) => r.scs, + Command::Compute(c) => c.scs, + } + } +} + /// Inline storage for the common 1-2 command submission, spilling to a heap `KVec` above 2. pub(crate) enum Commands { Empty, @@ -314,6 +358,10 @@ pub(crate) struct Context<'a> { pub(crate) vm: &'a mmu::Vm, /// The queue's USC window base. pub(crate) usc_base: u64, + /// Enabled GPU cores, which SCS memory is sized for. + pub(crate) active_cores: u32, + /// The queue's reserved render scratch pages per stage (`render_scs_layout`). + pub(crate) render_scs: [u16; 2], } /// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its @@ -450,6 +498,32 @@ fn render_payload( } } +/// Render payload bytes before the ray-query stages: they follow the historical prefixes. +const RAY_QUERY_START: usize = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); + +/// The ray-query stages of a render payload; a shorter payload reads both stages zeroed. +/// Bounded by [`RENDER_STAGE_PREFIXES_OFF`] so 480-byte `STAGE_PREFIXES` tails stay separate. +fn render_ray_query(bytes: &[u8]) -> Result<[super::rt::RayQueryStage; 2]> { + let rq_end = bytes.len().min(RENDER_STAGE_PREFIXES_OFF); + super::rt::RayQueryStage::parse_pair(bytes.get(RAY_QUERY_START..rq_end).unwrap_or(&[])) +} + +/// The scratch layout and intersection tables of a compute command. The M5 auxiliary +/// allocation and the reserved word stay MBZ. +fn compute_ray(cmd: &uapi::drm_asahi_cmd_compute) -> Result { + super::rt::ComputeRay::new( + cmd.scs_layout, + cmd.cdm_auxiliary_allocation, + cmd.reserved, + cmd.intersection_pool, + cmd.intersection_pool_bytes, + cmd.intersection_first, + cmd.intersection_count, + cmd.intersection_default_program, + cmd.intersection_default_control, + ) +} + /// Whether `[start, start + size)` is a nonempty range inside `range`. fn inside(start: u64, size: u64, range: &Range) -> bool { size != 0 && start >= range.start && start < range.end && size <= range.end - start @@ -505,20 +579,12 @@ fn validate_render_entry( ) -> Result<( uapi::drm_asahi_cmd_render, Option, + [super::rt::RayQueryStage; 2], )> { let (packet, prefixes) = render_payload(entry.payload)?; let cmd = &packet; - // Ray-query extensions belong to G17; reject every nonzero byte - // between the common historical-prefix fields and the stage-prefix tail. - let end = offset_of!(uapi::drm_asahi_cmd_render, prior_cdm) + size_of::(); - let rq_end = entry.payload.len().min(RENDER_STAGE_PREFIXES_OFF); - if entry - .payload - .get(end..rq_end) - .is_some_and(|tail| tail.iter().any(|&b| b != 0)) - { - return Err(EINVAL); - } + // The ray-query stages after the historical prefixes (RENDER_RAY_QUERY). + let ray_query = render_ray_query(entry.payload)?; if let Some(prefixes) = prefixes { if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) || (prefixes.ta_cdm_barrier != NONE @@ -556,8 +622,6 @@ fn validate_render_entry( { return Err(EINVAL); } - // `payload` rejects nonzero ray-query bytes beyond the prior - // extension. RENDER_RAY_QUERY is never advertised on G16. // Never discard unflagged high words, nor accept the flag without them. if cmd.flags & RSRC_SPEC_HI != 0 && entry.payload.len() < RSRC_SPEC_HI_MIN { return Err(EINVAL); @@ -570,17 +634,19 @@ fn validate_render_entry( { return Err(EINVAL); } - Ok((packet, prefixes)) + Ok((packet, prefixes, ray_query)) } fn validate_compute_entry( entry: &Entry<'_>, range: &Range, -) -> Result { +) -> Result<(uapi::drm_asahi_cmd_compute, super::rt::ComputeRay, bool)> { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; - if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 - || cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base + let Some(as_build) = super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS) else { + return Err(EINVAL); + }; + if cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base || !inside( cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end - cmd.cdm_ctrl_stream_base, @@ -589,24 +655,16 @@ fn validate_compute_entry( { return Err(EINVAL); } - // The G17P scratch layout and intersection tables: never on G16. if cmd .ts_end_copies .iter() .any(|ts| ts.handle != 0 || ts.offset != 0) - || packet.scs_layout != 0 - || packet.cdm_auxiliary_allocation != 0 - || packet.reserved != 0 - || packet.intersection_pool != 0 - || packet.intersection_pool_bytes != 0 - || packet.intersection_first != 0 - || packet.intersection_count != 0 - || packet.intersection_default_program != 0 - || packet.intersection_default_control != 0 { return Err(EINVAL); } - Ok(packet) + // The G17P scratch layout and intersection tables (RENDER_RAY_QUERY). + let ray = compute_ray(cmd)?; + Ok((packet, ray, as_build)) } /// Checks that `[start, end)` (rounded out to pages) lies inside the user address range and @@ -1231,6 +1289,68 @@ fn check_render( Ok(()) } +/// The hardware reads the intersection pool and the default intersection program: both must +/// be mapped readable, as on the M4 Pro. +fn check_intersection( + batch: &mut SpanBatch, + vm: &mmu::Vm, + tables: &super::rt::IntersectionTables, +) -> Result { + if !tables.enabled() { + return Ok(()); + } + let end = tables.pool.checked_add(tables.pool_bytes).ok_or(EINVAL)?; + batch.push(vm, tables.pool, end, true, false)?; + let code = tables.default_code(); + if code != 0 { + batch.push(vm, code, code.checked_add(64).ok_or(EINVAL)?, true, false)?; + } + Ok(()) +} + +/// Per-command render ray-query admission. A render's scratch must fit what its queue +/// reserved (`render_scs_layout`): the render's UMA pool was sized for that (EINVAL beyond it, +/// as on the M4 Pro). Returns the SCS-capable pool the render runs on, sized for the +/// reservation ([`super::rt::pool_seeds`]). +fn check_render_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + stages: &[super::rt::RayQueryStage; 2], +) -> Result { + for stage in stages { + check_intersection(batch, context.vm, &stage.intersection)?; + } + if !stages.iter().any(|stage| stage.scratch.enabled()) { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = stages.map(|stage| stage.scratch.pages()); + let needed = super::rt::required_seeds(context.active_cores, &pages)?; + let reserved = super::rt::required_seeds(context.active_cores, &context.render_scs)?; + if needed > reserved { + return Err(EINVAL); + } + let pool = super::rt::pool_seeds(context.active_cores, context.render_scs)?; + Ok(super::rt::ScsSeeds { needed, pool }) +} + +/// Per-command compute ray admission: the tables are mapped and the scratch fits an +/// SCS-capable UMA pool (E2BIG). Returns the SCS-capable pool the command runs on. +fn check_compute_ray( + batch: &mut SpanBatch, + context: &Context<'_>, + ray: &super::rt::ComputeRay, +) -> Result { + check_intersection(batch, context.vm, &ray.intersection)?; + if !ray.scratch.enabled() { + return Ok(super::rt::ScsSeeds::NONE); + } + let pages = ray.scratch.pages(); + Ok(super::rt::ScsSeeds { + needed: super::rt::required_seeds(context.active_cores, &[pages])?, + pool: super::rt::pool_seeds(context.active_cores, [pages, 0])?, + }) +} + /// Per-command compute admission. fn check_compute( batch: &mut SpanBatch, @@ -1240,7 +1360,7 @@ fn check_compute( ) -> Result<(u64, u64)> { let vm = context.vm; let (base, end) = (cmd.cdm_ctrl_stream_base, cmd.cdm_ctrl_stream_end); - if cmd.flags & !COMPUTE_NO_QUERY_ACCESS != 0 + if super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS).is_none() || cmd.sampler_count != 0 || cmd.sampler_heap != 0 || !helper_is_empty(&cmd.helper) @@ -1366,7 +1486,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { - let (packet, prefixes) = validate_render_entry(&entry, counts, early_tiling)?; + let (packet, prefixes, ray_query) = + validate_render_entry(&entry, counts, early_tiling)?; counts[RENDER] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1399,6 +1520,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result Result { - let packet = validate_compute_entry(&entry, &range)?; + let (packet, ray, as_build) = validate_compute_entry(&entry, &range)?; counts[COMPUTE] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1433,6 +1556,9 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result Result { let Prepared { - commands, + mut commands, orders, counts, } = self; @@ -1555,7 +1681,7 @@ impl Prepared { { let scratch = &mut proof.scratch; scratch.batch.clear(); - for command in commands.iter() { + for command in commands.iter_mut() { match command { Command::Render(render) => { check_render( @@ -1565,6 +1691,8 @@ impl Prepared { &render.vertex_attachments, &render.fragment_attachments, )?; + render.scs = + check_render_ray(&mut scratch.batch, context, &render.ray_query)?; if vdm_count >= scratch.vdm_vas.len() { return Err(EINVAL); } @@ -1578,6 +1706,8 @@ impl Prepared { &compute.cmd, &compute.attachments, )?; + compute.scs = + check_compute_ray(&mut scratch.batch, context, &compute.ray)?; if cdm_count >= scratch.cdm_ranges.len() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index 9fdc397dc3cfc7..5c91c50db28847 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -8,7 +8,7 @@ use kernel::{prelude::*, uapi}; -use super::fw::graph::manager; +use super::fw::graph::{manager, pools}; use super::fw::work::{self, barrier, compute, fs, initbm, scene, ta, REG_RECORD}; use super::hw; @@ -72,8 +72,9 @@ 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, encode_compute_for, init_compute_pool, preserve_compute_descriptor, - ComputeEncodeError, ComputeRefs, + encode_compute, encode_compute_for, encode_compute_rt, init_compute_pool, + preserve_compute_descriptor, ComputeEncodeError, ComputeRefs, ComputeRt, + COMPUTE_SCS_DRIVER_WORD, }; /// Tiling geometry and register words of a render (accelerator count 2). @@ -281,6 +282,7 @@ 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_fs_for, encode_ta, encode_ta_for, fill_scene, - initbm, render_attachments, scene, scene_prefix, scene_render, PassRefs, RenderRefs, + append_fs_timestamp_copies, encode_fs, encode_fs_for, encode_fs_rt, encode_ta, encode_ta_for, + encode_ta_rt, fill_scene, initbm, render_attachments, scene, scene_prefix, scene_render, + PassRefs, RenderRefs, StageRt, RENDER_SCS_ENABLE, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 179f39cb4c3bff..71191ebabfc357 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -3,7 +3,7 @@ //! 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}; +use super::{compute, manager, pools, 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) { @@ -65,6 +65,59 @@ pub(crate) struct ComputeRefs { pub(crate) submitted: u64, } +/// The first and last register records of a ray-query compute work item, as macOS 27.2 on the +/// J773g writes them: 0x017e1 = 1 first (only in ray-query items) and 0x017d9 = 1 last. macOS +/// also writes the trailing 0x017d9 in some compute work without ray queries; G16G's +/// non-ray-query work keeps the list it has always had. +const RAY_QUERY_FIRST: (u32, u64) = (0x017e1, 1); +const RAY_QUERY_LAST: (u32, u64) = (0x017d9, 1); +/// Write the SCS driver word 0x1a141 after 0x1a0e9 for a command with scratch, as g17's G17P +/// compute program does (zero on Gen1). Off: 25F84's program does not write it. Trace +/// question T1. +pub(crate) const COMPUTE_SCS_DRIVER_WORD: bool = false; + +/// The ray-tracing words of one compute work item, and the UMA pool it runs with. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRt { + /// 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1. + pub(crate) intersection: [u64; 6], + /// 0x101d1. + pub(crate) size: u64, + /// 0xd479. + pub(crate) tail: u64, + /// 0x1a0e9. + pub(crate) stack: u64, + /// 0x107a1. + pub(crate) window: u64, + /// 0x1a141, with [`COMPUTE_SCS_DRIVER_WORD`]. + pub(crate) driver: u64, + /// The command has scratch (the gated registers apply). + pub(crate) scs: bool, + /// Freelist entries of the unit's UMA pool, published in a fresh descriptor (SEEDS_A/B). + pub(crate) seeds: u32, + /// Records of the unit's freelist, published in a fresh descriptor (+0x1c). + pub(crate) records: u32, +} + +impl ComputeRt { + /// A command without ray state in a base UMA pool: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + driver: 0, + scs: false, + seeds: 8192, + records: manager::UNK_1C_VALUE, + }; +} + +/// Register records of a compute work item at most: the 24 of [`compute::SEL`], 0x10071, the +/// ray-query first and last records and the gated SCS driver word. +const MAX_REGS: usize = compute::SEL.len() + 4; + const FW_START: u64 = 0xfffffc2000000000; const FW_END: u64 = 0xfffffc2ffc000000; const VM_START: u64 = 0x4000; @@ -185,8 +238,38 @@ pub(crate) fn encode_compute( } /// [`encode_compute`] for the work layout of another firmware ABI. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_compute_for( + layout: &compute::Layout, + 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_rt( + layout, + r, + c, + att, + ts_va, + ctx, + n, + fault_mask, + &ComputeRt::DISABLED, + w, + q, + ) +} + +/// [`encode_compute_for`] with the command's ray-tracing words and its unit's UMA pool. With +/// [`ComputeRt::DISABLED`] the bytes are [`encode_compute_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_compute_rt( layout: &compute::Layout, r: &ComputeRefs, c: &uapi::drm_asahi_cmd_compute, @@ -195,9 +278,19 @@ pub(crate) fn encode_compute_for( ctx: u32, _n: u64, fault_mask: u32, + rt: &ComputeRt, w: &mut [u8; compute::WORK_SIZE], q: &mut [u8; compute::SEQ_SIZE], ) -> Result<(), ComputeEncodeError> { + // Whole 2-MiB pool rows within the freelist the manager reports, which is never smaller + // than a base unit's. + if rt.seeds == 0 + || rt.seeds % 512 != 0 + || rt.seeds > rt.records + || rt.records < manager::UNK_1C_VALUE + { + return Err(ComputeEncodeError::Storage); + } if ctx == 0 || ctx >= 64 { return Err(ComputeEncodeError::Context); } @@ -230,7 +323,12 @@ pub(crate) fn encode_compute_for( compute::CONTEXT_STORE_SIZE as u64, 0x4000, ) - || !gpu(r.pool_state_gva, compute::POOL_STATE_SIZE as u64, 0x4000) + // The freelist: one u64 seed address per record. + || !gpu( + r.pool_state_gva, + u64::from(rt.records) * core::mem::size_of::() as u64, + 0x4000, + ) || !gpu(r.page_list_gva, compute::PAGE_LIST_SIZE as u64, 0x4000) || (r.usc_base != 0 && !gpu(r.usc_base, 0x100000000, 0x100000000)) { @@ -272,6 +370,7 @@ pub(crate) fn encode_compute_for( } } let pre = r.preempt_gva; + let [i0, i1, i2, i3, i4, i5] = rt.intersection; let values = [ pre, base, @@ -282,16 +381,16 @@ pub(crate) fn encode_compute_for( 0x154024201, 0x10c08860, 0x1c, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, + i0, + i1, + i2, + i3, + i4, + i5, + rt.size, + rt.tail, + rt.stack, + rt.window, 0x13200400020, 0x200000001, 1, @@ -300,15 +399,32 @@ pub(crate) fn encode_compute_for( ]; w.fill(0); q.fill(0); - for (i, (&sel, &value)) in compute::SEL.iter().zip(values.iter()).enumerate() { - put32(w, compute::REGS + i * 12, sel); - put64(w, compute::REGS + i * 12 + 4, value); + let mut records = [(0u32, 0u64); MAX_REGS]; + let mut count = 0; + let mut push = |sel: u32, value: u64| { + records[count] = (sel, value); + count += 1; + }; + if rt.scs { + push(RAY_QUERY_FIRST.0, RAY_QUERY_FIRST.1); + } + for (&sel, &value) in compute::SEL.iter().zip(values.iter()) { + push(sel, value); + if sel == 0x1a0e9 && COMPUTE_SCS_DRIVER_WORD && rt.scs { + push(0x1a141, rt.driver); + } } - let count = if r.usc_base == 0 { 24 } else { 25 }; if r.usc_base != 0 { - put32(w, compute::REGS + 24 * 12, 0x10071); - put64(w, compute::REGS + 24 * 12 + 4, r.usc_base); + push(0x10071, r.usc_base); + } + if rt.scs { + push(RAY_QUERY_LAST.0, RAY_QUERY_LAST.1); + } + for (i, &(sel, value)) in records[..count].iter().enumerate() { + put32(w, compute::REGS + i * 12, sel); + put64(w, compute::REGS + i * 12 + 4, value); } + let count = count as u16; put32(w, 0, 3); put32(w, 0xc, ctx); put64( @@ -412,12 +528,12 @@ pub(crate) fn encode_compute_for( put32(w, d + manager::INDEX, r.uma_slot); put32(w, d + manager::ONE, 2); put64(w, d + manager::FREELIST, r.pool_state_gva); - put32(w, d + manager::UNK_1C, manager::UNK_1C_VALUE); - put32(w, d + manager::SEEDS_A, 8192); - put32(w, d + manager::SEEDS_B, 8192); + put32(w, d + manager::UNK_1C, rt.records); + put32(w, d + manager::SEEDS_A, rt.seeds); + put32(w, d + manager::SEEDS_B, rt.seeds); put64(w, d + manager::POOL_TABLE, r.page_list_gva); put32(w, d + 0x40, 4); - put32(w, d + 0x48, 128); + put32(w, d + manager::ROW_WORDS, pools::row_words(rt.seeds)); put64(w, compute::DESCRIPTOR_COUNTER, r.counter_fw); // Native M+0x5c distinguishes shared compute from per-workqueue-private pools. // Retain the existing value for these persistent units reused across queues; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 0d7f569c9a54ac..647ce051264530 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -69,6 +69,61 @@ pub(crate) struct PassRefs { pub(crate) ta_scratch: u64, } +/// Write the macOS 27.2 J773g SCS enable pair (`0x017e1 = 1` before `at`, `0x017d9 = 1` at the +/// end) in the register list of a render stage with scratch: `0x017e1 = 1` first in the TA list +/// (before `0x1748`) and after `0x1739` in the FS list, with `0x017d9 = 1` last in both, matching +/// `encode::compute` (`RAY_QUERY_FIRST`/`RAY_QUERY_LAST`) and the M5 render register lists. +pub(crate) const RENDER_SCS_ENABLE: bool = true; + +/// The ray-query words of one render stage (the M4 Pro's 25G83 render programs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct StageRt { + /// TA 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. + pub(crate) intersection: [u64; 6], + /// TA 0x101c9, FS 0x101c1. + pub(crate) size: u64, + /// TA 0xd471, FS 0xd469. + pub(crate) tail: u64, + /// TA 0x1a0f1, FS 0x1a0f9. + pub(crate) stack: u64, + /// TA 0x10799; FS 0x10791 with bit 9. + pub(crate) window: u64, + /// The stage has scratch (the gated register applies). + pub(crate) scs: bool, +} + +impl StageRt { + /// A stage without ray queries: the words G16G has always written. + pub(crate) const DISABLED: Self = Self { + intersection: [0; 6], + size: 0, + tail: 0, + stack: 8, + window: 0xff0000, + scs: false, + }; +} + +/// Register records, bracketed with `0x017e1 = 1` before record `at` and `0x017d9 = 1` at the +/// end when `RENDER_SCS_ENABLE && scs`; returns the record count. +fn stage_regs(dst: &mut [u8], sel: &[u32], val: &[u64], scs: bool, at: usize) -> u16 { + if !(RENDER_SCS_ENABLE && scs) { + regs(dst, sel, val); + return sel.len() as u16; + } + regs(dst, &sel[..at], &val[..at]); + put32(dst, REG_RECORD * at, 0x017e1); + put64(dst, REG_RECORD * at + 4, 1); + if let Some(rest) = dst.get_mut(REG_RECORD * (at + 1)..) { + regs(rest, &sel[at..], &val[at..]); + } + let last = REG_RECORD * (sel.len() + 1); + put32(dst, last, 0x017d9); + put64(dst, last + 4, 1); + sel.len() as u16 + 2 +} + fn scene_list_va(r: &RenderRefs, p: &PassRefs) -> u64 { if p.scene_list != 0 { p.scene_list @@ -158,8 +213,40 @@ pub(crate) fn encode_ta( /// Encode the 66-record single-cluster tiler work of `layout`'s ABI and its exact 0x300 /// sequence. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_ta_for( + layout: &ta::Layout, + 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_rt( + layout, + r, + p, + u, + ts_va, + ctx, + target, + geo, + cl, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_ta_for`] with the vertex stage's ray-query words. With [`StageRt::DISABLED`] the +/// bytes are [`encode_ta_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_ta_rt( layout: &ta::Layout, r: &RenderRefs, p: &PassRefs, @@ -169,6 +256,7 @@ pub(crate) fn encode_ta_for( target: u32, geo: &Geometry, _cl: Option<&ClusterLayout>, + rt: &StageRt, w: &mut [u8; ta::WORK_SIZE], q: &mut [u8; ta::SEQ_SIZE], ) { @@ -229,16 +317,16 @@ pub(crate) fn encode_ta_for( 0, 0x1c, 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, - 0xff0000, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, u64::from(r.parameter_id), compact(scene_list_va(r, p)), compact(scene_list_va(r, p)), @@ -251,7 +339,7 @@ pub(crate) fn encode_ta_for( // USC base is a shared queue property carried by the render refs. r.usc_base, ]; - regs(&mut w[ta::REGS..], &ta::SEL, &val); + let count = stage_regs(&mut w[ta::REGS..], &ta::SEL, &val, rt.scs, 0); put64(w, 4, r.counter[0]); put32(w, 0xc, ctx); put64(w, 0x10, r.notifier); @@ -260,8 +348,8 @@ pub(crate) fn encode_ta_for( put64(w, 0x28, p.scene); put64(w, 0x30, p.scene + 0x100); put64(w, 0x740, p.ta_work_gva + 0x40); - put16(w, 0x748, 66); - put16(w, 0x74a, 66 * 12); + put16(w, 0x748, count); + put16(w, 0x74a, count * 12); put64(w, 0x760, p.tpc_fw); put64(w, ta::TPC_BYTES, geo.tpc_bytes); put64(w, 0x770, p.ta_seq); @@ -340,8 +428,42 @@ pub(crate) fn encode_fs( } /// Encode the 82-record fragment work of `layout`'s ABI and base 0x380 sequence. -#[allow(clippy::too_many_arguments)] +#[allow(clippy::too_many_arguments, dead_code)] pub(crate) fn encode_fs_for( + layout: &fs::Layout, + 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_rt( + layout, + r, + p, + u, + ts_va, + ctx, + usc, + n, + target, + geo, + &StageRt::DISABLED, + w, + q, + ) +} + +/// [`encode_fs_for`] with the fragment stage's ray-query words. With [`StageRt::DISABLED`] +/// the bytes are [`encode_fs_for`]'s. +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_fs_rt( layout: &fs::Layout, r: &RenderRefs, p: &PassRefs, @@ -352,6 +474,7 @@ pub(crate) fn encode_fs_for( _n: u64, target: u32, geo: &Geometry, + rt: &StageRt, w: &mut [u8; fs::WORK_SIZE], q: &mut [u8], ) { @@ -375,7 +498,7 @@ pub(crate) fn encode_fs_for( u64::from(geo.isp_blocks), u64::from(geo.screen), 0, - 0xff0200, + rt.window | 1 << 9, p.heap_gva & !63, u.isp_scissor_base & !3, u.isp_dbias_base & !3, @@ -423,15 +546,15 @@ pub(crate) fn encode_fs_for( 0x1c, 0, geo.native_tiles, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 8, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, 0x6000400020, 0x200000001, u64::from(r.uuid), @@ -441,7 +564,7 @@ pub(crate) fn encode_fs_for( compact(scene_list_va(r, p)), usc, ]; - regs(&mut w[fs::REGS..], &fs::SEL, &val); + let count = stage_regs(&mut w[fs::REGS..], &fs::SEL, &val, rt.scs, 1); put32(w, 0, 1); put64(w, 4, r.counter[1]); put32(w, 0xc, ctx); @@ -459,8 +582,8 @@ pub(crate) fn encode_fs_for( put32(w, 0x68, geo.blocks); put32(w, 0x78, geo.tiles); put64(w, 0x780, p.fs_work_gva + 0x80); - put16(w, 0x788, 82); - put16(w, 0x78a, 82 * 12); + put16(w, 0x788, count); + put16(w, 0x78a, count * 12); put64(w, 0x7a0, u.isp_dbias_base); put64(w, 0x7b0, u.isp_scissor_base); put64(w, 0x7c0, u.isp_oclqry_base); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 7994d956ac782d..26009c05701a57 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -20,7 +20,7 @@ use kernel::{prelude::*, sync::Arc}; use super::channel::Channel; use super::command::{Command, ComputeCommand, RenderCommand}; -use super::encode::{self, ComputeRefs, Geometry, RenderRefs}; +use super::encode::{self, ComputeRefs, ComputeRt, Geometry, RenderRefs, StageRt}; use super::fw::channels::{SubmitRecord, RING_SLOTS}; use super::fw::graph::{notifier_page, qstate}; use super::fw::work::{self, BarrierType}; @@ -330,6 +330,8 @@ pub(crate) struct Flight { pub(crate) initbm: bool, /// Whether this flight publishes CPU-written command timestamps on retirement. pub(crate) has_timestamps: bool, + /// Whether this flight runs ray-tracing or SCS-scratch compute (pinned to compute pipe 0). + pub(crate) rt_compute: bool, } impl Flight { @@ -371,6 +373,7 @@ impl Flight { pb_binding: 0, initbm: false, has_timestamps: false, + rt_compute: false, } } } @@ -1125,14 +1128,17 @@ impl Firmware { // immediately instead of spinning on EAGAIN and stalling unrelated compute. if class_error.is_none() && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) - && (job + && (job.resources.pb_slot_mask().is_ok_and(|(mask, home)| { + self.pools.exhausted_for_mask_mode( + &job.vm, + mask, + home, + job.resources.render_scs(), + ) + }) || job .resources - .pb_slot_mask() - .is_ok_and(|(mask, home)| self.pools.exhausted_for_mask(&job.vm, mask, home)) - || job - .resources - .render_passes() - .is_ok_and(|n| self.slots.render_exhausted_within(n))) + .render_passes() + .is_ok_and(|n| self.slots.render_exhausted_within(n))) { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -1294,11 +1300,15 @@ impl Firmware { let cmd = command(job, job.progress.sent()); let is_render = matches!(cmd, Some(Command::Render(_))); let is_compute = matches!(cmd, Some(Command::Compute(_))); + let is_rt_compute = is_compute + && (job.resources.compute_scs() + || matches!(cmd, Some(Command::Compute(c)) if c.is_rt())); job.vm.status.get() != 0 || self.engine.flights.iter().any(|f| { f.doomed || f.recovery_suspect || f.initbm + || (is_rt_compute && f.computes != 0 && f.compute_pipe != 0) || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) @@ -1308,8 +1318,13 @@ impl Firmware { .pb_slot_mask() .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) .is_ok_and(|(mask, home, blocks)| { - self.pools - .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) })) } @@ -1462,8 +1477,13 @@ impl Firmware { .flights .iter() .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let rt_pipe1_busy = (job.resources.compute_scs() || c.is_rt()) + && e.flights + .iter() + .any(|f| f.computes != 0 && f.compute_pipe != 0); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); !cross_vm_render + && !rt_pipe1_busy && !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() @@ -1490,8 +1510,13 @@ impl Firmware { .pb_slot_mask() .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) .is_ok_and(|(mask, home, blocks)| { - self.pools - .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) }) && job .resources @@ -1781,8 +1806,15 @@ impl Firmware { &self, waits: [Option; sizes::COMPUTE_PIPES], units: usize, + rt_compute: bool, ) -> usize { - if units <= super::resources::BASE_COMPUTE_UNITS + if rt_compute + || self + .engine + .flights + .iter() + .any(|fl| fl.computes != 0 && fl.rt_compute) + || units <= super::resources::BASE_COMPUTE_UNITS || !self.slots.compute_available_for_pipe(units, 1) { return 0; @@ -1833,12 +1865,16 @@ impl Firmware { .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; let (pb_mask, _) = job.resources.pb_slot_mask()?; let heap_blocks = job.resources.pb_heap_blocks()?; - // Reuse this VM's retired epoch of the allocator slot when still bound and sized for the - // VM's current PB heap (no reseed/InitBM); if the PB heap grew, rotate onto a fresh epoch. - let (epoch, reused) = match self - .pools - .reusable_for_mask(alloc_slot, &job.vm, pb_mask, heap_blocks) - { + let render_scs = job.resources.render_scs(); + // Reuse this VM's retired epoch of the allocator slot when still bound, matching the + // SCS mode, and sized for the VM's current PB heap (no reseed/InitBM). + let (epoch, reused) = match self.pools.reusable_for_mask_mode( + alloc_slot, + &job.vm, + pb_mask, + heap_blocks, + render_scs, + ) { Some(e) => { self.pools.stats.reused += 1; a.init_buffer = false; @@ -1849,10 +1885,11 @@ impl Firmware { return Err(EAGAIN); } let e = job.resources.take_pb()?; - if let Err(err) = e.prepare( + if let Err(err) = e.prepare_with_scs( alloc_slot, job.resources.pb_heap_gva(alloc_slot)?, heap_blocks, + render_scs, ) { job.resources.return_pb(e); return Err(err); @@ -2023,12 +2060,14 @@ impl Firmware { (0usize, [None; sizes::COMPUTE_PIPES]) } else { let units = job.resources.compute_units()?; + let rt_compute = job.resources.compute_scs() + || matches!(cmd, Command::Compute(c) if c.is_rt()); let waits = self.wait_compute_stamps_for( job, job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, units), waits) + (self.choose_compute_pipe(waits, units, rt_compute), waits) }; let pipe_behind = !render && self @@ -2157,8 +2196,9 @@ impl Firmware { .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) .min(ring_more) .min(pipe_fold_cap); + let rt_head = job.resources.compute_scs() || c.is_rt(); // Fold trailing barrier-free compute commands of the base job first. - while more_slots > 0 && end < job.progress.count() { + while !rt_head && more_slots > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { break; }; @@ -2170,6 +2210,9 @@ impl Firmware { let Some(Command::Compute(c2)) = command(job, end) else { break; }; + if c2.is_rt() { + break; + } self.prefix_compute( job, &job.resources, @@ -2187,7 +2230,7 @@ impl Firmware { // Compute horizon: fold subsequent ready, barrier-free compute-only jobs of // the same queue and VM into the same CDM producer advance and doorbell. // Any non-qualifying job of this queue ends the scan so no later job overtakes it. - if end == job.progress.count() { + if !rt_head && !job.long() && end == job.progress.count() { hz_stop = Some(0); let mut idx = 0; while idx < self.engine.pending.len() { @@ -2208,6 +2251,11 @@ impl Firmware { if !Arc::ptr_eq(&j2.vm, &job.vm) || j2.progress.sent() != 0 || n2 == 0 + || j2.long() + || j2.resources.compute_scs() + || (0..n2).any(|k| { + matches!(command(&j2, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) || !j2.can_fold_horizon_job(first_seq) { hz_stop = Some(3); @@ -2420,6 +2468,8 @@ impl Firmware { break; }; if !Arc::ptr_eq(&j2.vm, &job.vm) + || j2.long() != job.long() + || j2.resources.render_scs() != job.resources.render_scs() || n2 == 0 || n2_usize > more_renders || !j2.can_fold_render_horizon_job(first_seq) @@ -2819,11 +2869,12 @@ impl Firmware { target_stamp: target, submitted, }; + let rt = compute_rt(&cmd.ray, s.seeds); let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; 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_for( + encode::encode_compute_rt( self.init.abi.compute(), &refs, &cmd.cmd, @@ -2832,6 +2883,7 @@ impl Firmware { job.vm.slot, n, 1, + &rt, w, image(&mut scratch.cq)?, ) @@ -2905,6 +2957,7 @@ impl Firmware { f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.rt_compute |= resources.compute_scs() || cmd.is_rt(); wmb(); if let Some((wait_fs, bar_type)) = fs2c_bar { g.ring.w64(8 * pf.c_head as usize, s.barrier.va)?; @@ -3051,7 +3104,14 @@ impl Firmware { let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_in_mask_blocks(&job.vm, behind, pb_mask, pb_home, heap_blocks) + .pick_slot_in_mask_blocks_mode( + &job.vm, + behind, + pb_mask, + pb_home, + heap_blocks, + resources.render_scs(), + ) .ok_or(EAGAIN)?; let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = @@ -3083,7 +3143,8 @@ impl Firmware { geometry.validate_capacity(p.tpc.size as u64, p.tilemap.size as u64)?; resources.set_pass_dirty(k, geometry.tpc_bytes, geometry.tilemap_bytes, heap_bytes)?; let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; - encode::encode_ta_for( + let [vertex_rt, fragment_rt] = cmd.ray_query.map(|stage| stage_rt(&stage)); + encode::encode_ta_rt( self.init.abi.ta(), &refs, &pass, @@ -3093,10 +3154,11 @@ impl Firmware { target, &geometry, None, + &vertex_rt, image(&mut scratch.ta)?, image(&mut scratch.tas)?, ); - encode::encode_fs_for( + encode::encode_fs_rt( self.init.abi.fs(), &refs, &pass, @@ -3107,6 +3169,7 @@ impl Firmware { draw, target, &geometry, + &fragment_rt, image(&mut scratch.fs)?, &mut scratch.fss[..], ); @@ -3311,3 +3374,35 @@ impl Firmware { self.power.utilization.busy(now); } } + +/// The compute register words of a validated command's ray state ([`super::rt`]) in a unit +/// whose UMA pool has `seeds` freelist entries, in a freelist of +/// [`super::rt::freelist_records`]. Without ray state in a base unit these are the words of +/// [`ComputeRt::DISABLED`]. +fn compute_rt(ray: &super::rt::ComputeRay, seeds: u32) -> ComputeRt { + ComputeRt { + intersection: ray.intersection.words(), + size: ray.scratch.size_word(), + tail: ray.scratch.compute_tail_word(), + stack: ray.scratch.stack_word(), + window: ray.scratch.window_word(), + driver: ray.scratch.driver_word(), + scs: ray.scratch.enabled(), + seeds, + records: super::rt::freelist_records(seeds), + } +} + +/// The TA or FS register words of a validated render stage's ray state. As the M4 Pro's +/// render programs, a stage's tail word is its scratch tail; its auxiliary intersection word +/// is validated but not written. +fn stage_rt(stage: &super::rt::RayQueryStage) -> StageRt { + StageRt { + intersection: stage.intersection.words(), + size: stage.scratch.size_word(), + tail: stage.scratch.tail_word(), + stack: stage.scratch.stack_word(), + window: stage.scratch.window_word(), + scs: stage.scratch.enabled(), + } +} diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 07317ee4663dc1..e0a7b43b677bf3 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -51,6 +51,8 @@ pub(crate) mod uma_manager { pub(crate) const SIZE: usize = 0xa0; pub(crate) const COMPLETED: usize = 0x54; pub(crate) const SEEDS: u32 = 8192; + /// Freelist records of a base pool (+0x1c), its 0x20000-byte freelist. + pub(crate) const RECORDS: u32 = 16384; } pub(crate) mod uma_pools { pub(crate) const POOLS: usize = 16; @@ -116,24 +118,32 @@ pub(crate) fn pb_manager_image( } /// One retained M4 UMA descriptor shared by TA and FS (slot 33..64). +/// A UMA manager whose freelist of `records` records (+0x1c) holds `seeds` entries (available +/// and total): [`uma_manager::SEEDS`] in [`uma_manager::RECORDS`] for a base pool. pub(crate) fn uma_manager_image( descriptor: u64, slot: u32, state_gpu: u64, list_gpu: u64, submitted_fw: u64, + seeds: u32, + records: u32, ) -> [u8; uma_manager::SIZE] { let mut m = [0; uma_manager::SIZE]; put64(&mut m, 0, descriptor); put32(&mut m, 8, slot); put32(&mut m, 0x10, 2); put64(&mut m, 0x14, state_gpu); - put32(&mut m, 0x1c, 16384); - put32(&mut m, 0x24, 8192); - put32(&mut m, 0x2c, 8192); + put32(&mut m, 0x1c, records); + put32(&mut m, 0x24, seeds); + put32(&mut m, 0x2c, seeds); put64(&mut m, 0x30, list_gpu); put32(&mut m, 0x40, 4); - put32(&mut m, 0x48, 128); + put32( + &mut m, + super::graph::manager::ROW_WORDS, + super::graph::pools::row_words(seeds), + ); put64(&mut m, 0x4c, submitted_fw); // +0x54 is the ASC completion count; +0x5c is the compute-exclusion flag. // Both start at zero for paired render engines and are never AP command serials. @@ -217,6 +227,12 @@ mod tests { 0x7012000000, 0x7012020000, 0xfffffc2000700000, + uma_manager::SEEDS, + uma_manager::RECORDS, + ); + assert_eq!( + (r32(&m, 0x1c), r32(&m, 0x24), r32(&m, 0x2c)), + (16384, 8192, 8192) ); assert_eq!(r64(&m, 0), 0xfffffc2000400000); assert_eq!(r32(&m, 8), 33); diff --git a/drivers/gpu/drm/asahi/g16/fw/graph.rs b/drivers/gpu/drm/asahi/g16/fw/graph.rs index e3c95e27567209..80279283a4dab6 100644 --- a/drivers/gpu/drm/asahi/g16/fw/graph.rs +++ b/drivers/gpu/drm/asahi/g16/fw/graph.rs @@ -138,6 +138,10 @@ pub(crate) mod manager { pub(crate) const COMPLETED: usize = 0x54; /// ASC compute-exclusion bookkeeping. AP initializes once; never a command serial. pub(crate) const COMPUTE_EXCLUSION: usize = 0x5c; + /// Eight per valid pool-table row ([`super::pools::row_words`]): macOS 27.2 on the J773g + /// writes 8 x rows on every pool (20, 24 and 108 rows seen) and counts a pool's growth + /// in the same unit. A 16-row base pool has 128. + pub(crate) const ROW_WORDS: usize = 0x48; } /// A private 32 MiB UMA pool: 8192 4 KiB freelist entries and sixteen 2 MiB rows. @@ -151,6 +155,13 @@ pub(crate) mod pools { pub(crate) const STATE_BYTES: usize = 0x20000; pub(crate) const TABLE_BYTES: usize = 0x4000; pub(crate) const SEEDS: usize = 8192; + /// [`super::manager::ROW_WORDS`] of a pool of `seeds` entries in whole rows: the u64 words + /// of its valid pool-table rows, eight per 0x40-byte row. + pub(crate) const fn row_words(seeds: u32) -> u32 { + let rows = seeds as u64 * SEED_BYTES / ROW_BYTES; + (rows * (TABLE_STRIDE / core::mem::size_of::()) as u64) as u32 + } + const _: () = assert!(row_words(SEEDS as u32) == 128); } /// The nonzero 25G83 queue header; the rest of the fresh 0x24c0 object remains zero. Keeping diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index 0341c5f6116daa..f50fc22164d4c0 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -66,9 +66,9 @@ pub(crate) mod compute; pub(crate) mod ta { pub(crate) const WORK_SIZE: usize = 0x940; /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) - /// spans of a TA work image. The intervening zero gap is cleared on full scrubs and skipped - /// on clean same-VM reuse. - pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x360; + /// spans of a TA work image (including two optional SCS register records). The intervening + /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x370; pub(crate) const TAIL_ACTIVE_START: usize = 0x740; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; @@ -112,7 +112,7 @@ pub(crate) mod ta { && l.auxiliary + 8 <= WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); - const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 66] = [ @@ -130,9 +130,9 @@ pub(crate) mod ta { pub(crate) mod fs { pub(crate) const WORK_SIZE: usize = 0xca0; /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) - /// spans of an FS work image. The intervening zero gap is cleared on full scrubs and skipped - /// on clean same-VM reuse. - pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x460; + /// spans of an FS work image (including two optional SCS register records). The intervening + /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x470; pub(crate) const TAIL_ACTIVE_START: usize = 0x780; pub(crate) const SEQ_SIZE: usize = 0x380; pub(crate) const SEQ_OBJECT: usize = 0x1000; @@ -179,7 +179,7 @@ pub(crate) mod fs { && l.flag < WORK_SIZE } const _: () = assert!(valid(&V25G83) && valid(&V26B123)); - const _: () = assert!(REGS + SEL.len() * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 82] = [ diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index 0bde4d35e88601..bb5ccf0ccc8460 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -3,10 +3,10 @@ //! 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; +/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 28 register +/// records (`0x20..0x170`, including USC base and RT/SCS records), 16-byte aligned. Bytes +/// between `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full write. +pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x170; /// 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). @@ -89,7 +89,7 @@ const fn valid(l: &Layout) -> bool { const _: () = assert!( valid(&V25G83) && valid(&V26B123) - && REGS + 25 * 12 <= HEAD_ACTIVE_SIZE + && REGS + (SEL.len() + 4) * 12 <= HEAD_ACTIVE_SIZE && HEAD_ACTIVE_SIZE <= BODY_ACTIVE_START && BODY_ACTIVE_START <= GENERATION && DESCRIPTOR + DESCRIPTOR_SIZE <= BODY_ACTIVE_END diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 155c8f528abb23..1e80e2303466c8 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -573,9 +573,9 @@ pub(crate) mod client { // Persistent compute units reused across application queues. Units 0 and 1 keep their // original 64 MiB placement below the render allocators; extension units (2..COMPUTE_UNITS) - // pack at a 40 MiB stride from 0x7080000000 up to the PB heap (0x70c0000000), clear of the - // dynamic PB page-list range 0x7040000000..0x7080000000 and leaving 7.25 MiB guard above - // each unit's 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. + // pack at a 40 MiB stride from 0x7080000000 up to the SCS compute records (0x70b8000000), + // clear of [`DYNAMIC`] and [`SCS_POOLS`] and leaving 7.25 MiB guard above each unit's + // 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. pub(crate) const EXT_COMPUTE_STRIDE: u64 = 0x02800000; pub(crate) const fn compute_base(k: u64) -> u64 { if k < 2 { @@ -606,6 +606,19 @@ pub(crate) mod client { pub(crate) const WORK_OFF: u64 = 0; pub(crate) const CWORK_STRIDE: u64 = 0x4000; + // SCS-capable compute units (ray-query scratch), one 64 MiB interval each after the last + // compute unit (0x70b7000000) and below the PB heap (0x70c0000000), holding the unit's + // list, preempt, auxiliary and context records at the base units' offsets from their + // state. Its UMA pool and freelist are in its SCS pool window ([`scs_compute_pool`]). + pub(crate) const fn scs_compute_records(k: u64) -> u64 { + 0x70b8000000 + k * 0x04000000 + } + /// Offsets of a compute unit's records from its state. + pub(crate) const COMPUTE_LIST_OFF: u64 = compute_list(0) - compute_state(0); + pub(crate) const COMPUTE_PREEMPT_OFF: u64 = compute_preempt(0) - compute_state(0); + pub(crate) const COMPUTE_AUX_OFF: u64 = compute_aux(0) - compute_state(0); + pub(crate) const COMPUTE_CONTEXT_OFF: u64 = compute_context(0) - compute_state(0); + // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a // 64 MiB stride. Per-VM local slots 0..4 live in 0x7010000000..0x7020000000; local slots // 4..MAX_VM_PB_SLOTS live in 0x7008000000..0x7010000000, above base compute units 0..2 @@ -632,6 +645,29 @@ pub(crate) mod client { pub(crate) const fn render_pb_pages(k: u64) -> u64 { render_base(k) + 0x2040000 } + // SCS-capable render allocators: the list and descriptor in their render unit's interval + // past its records, at the base allocator's offsets from its state. The UMA pool and + // freelist are in the allocator's SCS pool window ([`scs_render_pool`]). + pub(crate) const fn scs_render_records(k: u64) -> u64 { + render_base(k) + 0x2100000 + } + /// Kernel-placed client objects (PB page lists, `Objects::alloc_dynamic_client`). + pub(crate) const DYNAMIC: Range = 0x7040000000..0x7060000000; + /// SCS pool windows, after [`DYNAMIC`] and up to the CT window: each holds one + /// SCS-capable UMA pool and, right after it, its freelist (`rt::window_bytes`). Windows 0 + /// and 1 are the SCS compute units', 2 and 3 the SCS render allocators'. + pub(crate) const SCS_POOLS: u64 = 0x7060000000; + pub(crate) const SCS_POOL_WINDOW: u64 = 0x8000000; + pub(crate) const SCS_POOL_WINDOWS: u64 = 4; + pub(crate) const fn scs_compute_pool(k: u64) -> u64 { + SCS_POOLS + k * SCS_POOL_WINDOW + } + pub(crate) const fn scs_render_pool(k: u64) -> u64 { + SCS_POOLS + (2 + k) * SCS_POOL_WINDOW + } + /// Offsets of a render allocator's records from its state. + pub(crate) const RENDER_LIST_OFF: u64 = render_list(0) - render_state(0); + pub(crate) const RENDER_DESCRIPTOR_OFF: u64 = render_descriptor(0) - render_state(0); pub(crate) const PB_HEAP: u64 = 0x70c0000000; pub(crate) const PB_HEAP_SIZE: u64 = 0x10000000; pub(crate) const fn pb_heap(k: u64) -> u64 { @@ -811,6 +847,45 @@ pub(crate) mod sizes { super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT ); + /// SCS-capable compute units per VM, which share ledger indices (and UMA slots) with the + /// first base units. + pub(crate) const SCS_COMPUTE_UNITS: usize = 2; + /// Bytes of a base UMA pool (its seeds of 4 KiB). + pub(crate) const POOL_BYTES: u64 = 0x2000000; + const _: () = assert!( + super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::scs_compute_records(0) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64 - 1) + + super::client::COMPUTE_CONTEXT_OFF + + 0x40000 + <= super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + <= super::client::PB_HEAP + && super::client::WORK_PAGE + + (COMPUTE_UNITS + SCS_COMPUTE_UNITS) as u64 * super::client::CWORK_STRIDE + <= super::client::compute_base(0) + ); + const _: () = assert!( + super::client::render_pb_pages(0) + super::client::PB_PAGE_LIST_SIZE + <= super::client::scs_render_records(0) + && super::client::scs_render_records(0) + super::client::RENDER_DESCRIPTOR_OFF + 0x4000 + <= super::client::render_base(1) + && super::client::scs_render_records(BASE_PB_SLOTS as u64 - 1) + + super::client::RENDER_DESCRIPTOR_OFF + + 0x4000 + <= super::client::render_base(BASE_PB_SLOTS as u64) + ); + // One window per SCS compute unit and render allocator, between the dynamic range and the + // CT window. + const _: () = assert!( + super::client::DYNAMIC.end <= super::client::scs_compute_pool(0) + && super::client::scs_compute_pool(SCS_COMPUTE_UNITS as u64) + == super::client::scs_render_pool(0) + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) + == super::client::SCS_POOLS + + super::client::SCS_POOL_WINDOWS * super::client::SCS_POOL_WINDOW + && super::client::scs_render_pool(BASE_PB_SLOTS as u64) <= super::client::CT + && super::client::pass_base(RENDER_SLOTS as u64) <= super::client::DYNAMIC.start + ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; /// Jobs admitted to the engine per logical queue: enough to keep a queue's commands diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index c52f60a11e2b8b..a5dbc19b7d3e94 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -98,6 +98,8 @@ pub(crate) struct Job { pub(crate) vm: Arc, /// Validated commands, in submission order (at most 64). pub(crate) commands: Commands, + /// Any command traces rays or builds acceleration structures (`Command::long`). + long: bool, pub(crate) resources: super::resources::Prepared, /// Immutable dependency/order ledger, one entry for every accepted command. orders: Orders, @@ -151,6 +153,7 @@ impl Job { if commands.len() != orders.len() { return Err(EINVAL); } + let long = commands.iter().any(Command::long); let progress = super::engine::Progress::new(commands.len()); let guard = MappingGuard { guard, @@ -162,6 +165,7 @@ impl Job { queue, vm, commands, + long, orders, resources, fence, @@ -183,6 +187,12 @@ impl Job { ) } + /// The job gets the long execution allowance (ray traversal or acceleration-structure + /// builds, `recovery::logic::LONG_DEADLINE_MS`). + pub(crate) fn long(&self) -> bool { + self.long + } + /// Latches a hardware/publication failure before any later work can be published. /// Called under the device lock; it deliberately does not signal the fence. pub(crate) fn latch_failure(&self, error: Error) { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 9d12ae3e8df9a6..0c870a79c49c0f 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -69,6 +69,7 @@ mod queue; mod recovery; mod regs; mod resources; +mod rt; mod sleep; mod slots; mod timestamp; @@ -635,8 +636,8 @@ impl Gpu { let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; - let scrub_queue = slots::ScrubQueue::new_boxed()?; let active_render_vms = Arc::new(AtomicU32::new(0), GFP_KERNEL)?; + let scrub_queue = slots::ScrubQueue::new_boxed()?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 2ebe1a008fbbbe..4c94bfb15c44e9 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -444,7 +444,7 @@ impl Objects { lower: None, cpu: true, }, - Some(0x7040000000..0x7080000000), + Some(hw::client::DYNAMIC), ) } diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index ed93d1fd6469f3..434faf2ee2a046 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -6,8 +6,8 @@ //! SOFT_FAULTS suppressed by `soft_faults`, VDM_USC_INVALIDATE, and `INDEPENDENT_QUEUES` from //! `queue_limits`), G16 advertises per-command input readiness/errors, exact queue-local historical //! prefixes, fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent -//! logical queues, `FEW_PRIMITIVES`, and `COMPUTE_NO_QUERY_ACCESS`. Ray queries are not -//! advertised. +//! logical queues, `FEW_PRIMITIVES`, `COMPUTE_NO_QUERY_ACCESS`, render ray queries +//! (`RENDER_RAY_QUERY`) and bounded AS builds (`BOUNDED_AS_BUILD`). use kernel::{prelude::*, uapi}; @@ -100,6 +100,8 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = GPU_GENERATION; diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 8c801b79404611..c08da53d7fac24 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -15,7 +15,8 @@ pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; use super::hw::{client, engine, pte, sizes}; -use super::object::{Class, Factory, FwLease, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwLease, FwObject, Objects, Request}; +use super::slots::Placement; use super::Firmware; use crate::driver::AsahiDrmDevice; use core::{ @@ -83,6 +84,8 @@ pub(crate) struct PoolSet { heap: Arc, /// Blocks of the shared heap (the PB managers' lists cover the whole 256 MiB window). heap_blocks: u32, + /// Freelist entries of every allocator's UMA pool. + seeds: u32, } fn alloc( @@ -95,7 +98,7 @@ fn alloc( o.alloc(Request { size, class, - placement: Placement::Anywhere, + placement: super::object::Placement::Anywhere, offset: 0, client, lower: None, @@ -135,14 +138,14 @@ fn write_records( } impl Allocator { /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. - #[allow(dead_code)] pub(crate) fn new( o: &mut Objects, fw_factory: &Factory, k: u64, heap: &Arc, + placement: Placement, ) -> Result { - Self::new_at(o, fw_factory, k, k as u32, heap) + Self::new_at(o, fw_factory, k, k as u32, heap, placement) } /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot @@ -153,10 +156,30 @@ impl Allocator { local_idx: u64, hw_slot: u32, heap: &Arc, + placement: Placement, ) -> Result { + placement.check()?; if local_idx >= sizes::MAX_VM_PB_SLOTS as u64 || (hw_slot as usize) >= sizes::PB_SLOTS { return Err(EINVAL); } + let (pool_va, state_va, freelist_va) = match placement { + Placement::Base => ( + client::render_pool(local_idx), + client::render_state(local_idx), + client::render_state(local_idx), + ), + Placement::Scs { .. } => { + if local_idx >= sizes::BASE_PB_SLOTS as u64 { + return Err(EINVAL); + } + let pool = client::scs_render_pool(local_idx); + ( + pool, + client::scs_render_records(local_idx), + pool + placement.pool_bytes() as u64, + ) + } + }; let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table @@ -169,32 +192,26 @@ impl Allocator { o, 0x4000, Class::Shared, - nc(client::render_descriptor(local_idx)), - false, - )?; - let pool = alloc( - o, - 0x2000000, - Class::Shared, - nc(client::render_pool(local_idx)), + nc(state_va + client::RENDER_DESCRIPTOR_OFF), false, )?; + let pool = alloc(o, placement.pool_bytes(), Class::Shared, nc(pool_va), false)?; let state = alloc( o, - 0x20000, + placement.freelist_bytes(), Class::Shared, - nc(client::render_state(local_idx)), + nc(freelist_va), true, )?; let list = alloc( o, 0x4000, Class::Shared, - nc(client::render_list(local_idx)), + nc(state_va + client::RENDER_LIST_OFF), true, )?; let heap = heap.clone(); - super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; + super::slots::init_uma_pool(&state, &list, gva(&pool)?, placement.seeds())?; descriptor.write( 0, &buffer::uma_manager_image( @@ -203,6 +220,8 @@ impl Allocator { gva(&state)?, gva(&list)?, submitted.va, + placement.seeds(), + super::rt::freelist_records(placement.seeds()), ), )?; Ok(Self { @@ -341,7 +360,14 @@ impl PoolSet { let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; for (local, &hw_slot) in slots.iter().enumerate() { units.push( - Allocator::new_at(o, fw_factory, local as u64, hw_slot as u32, &heap)?, + Allocator::new_at( + o, + fw_factory, + local as u64, + hw_slot as u32, + &heap, + Placement::Base, + )?, GFP_KERNEL, )?; } @@ -349,8 +375,33 @@ impl PoolSet { units, heap, heap_blocks, + seeds: Placement::Base.seeds(), + }) + } + /// The SCS-capable allocators of this set's VM (ray-query scratch): one per base PB slot, + /// sharing this set's PB heap and hardware slot IDs, each with a pool of `seeds` entries + /// ([`super::rt::pool_seeds`]). PB epoch reuse keeps base and SCS bindings strictly disjoint. + pub(crate) fn scs(&self, o: &mut Objects, fw_factory: &Factory, seeds: u32) -> Result { + let heap = self.heap.clone(); + let placement = Placement::Scs { seeds }; + let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; + for (local, unit) in self.units.iter().enumerate() { + units.push( + Allocator::new_at(o, fw_factory, local as u64, unit.id(), &heap, placement)?, + GFP_KERNEL, + )?; + } + Ok(Self { + units, + heap, + heap_blocks: self.heap_blocks, + seeds, }) } + /// Freelist entries of the set's UMA pools. + pub(crate) fn seeds(&self) -> u32 { + self.seeds + } #[allow(dead_code)] pub(crate) fn unit(&self, k: usize) -> Option<&Allocator> { self.units.get(k) @@ -556,60 +607,87 @@ impl Pools { (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) .then(|| owner.clone()) } - /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// Like [`Self::reusable`], but also requires the retired epoch's SCS mode to match + /// `want_scs` so a base render and an SCS render never share an active UMA descriptor slot. + pub(crate) fn reusable_mode( + &self, + k: usize, + vm: &Arc, + want_scs: bool, + ) -> Option> { + self.reusable(k, vm) + .filter(|owner| owner.scs() == want_scs) + } + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot in `slot_mask` is available /// to rotate onto safely. - pub(crate) fn reusable_for_mask( + pub(crate) fn reusable_for_mask_mode( &self, k: usize, vm: &Arc, slot_mask: u32, min_blocks: u32, + want_scs: bool, ) -> Option> { if k >= sizes::PB_SLOTS || (slot_mask & (1u32 << k)) == 0 { return None; } - let owner = self.reusable(k, vm)?; + let owner = self.reusable_mode(k, vm, want_scs)?; if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_in_mask(slot_mask) { Some(owner) } else { None } } - /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// Like [`Self::reusable_mode`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available /// to rotate onto safely. #[allow(dead_code)] - pub(crate) fn reusable_for_within( + pub(crate) fn reusable_for_within_mode( &self, k: usize, vm: &Arc, limit: usize, min_blocks: u32, + want_scs: bool, ) -> Option> { - let owner = self.reusable(k, vm)?; + let owner = self.reusable_mode(k, vm, want_scs)?; if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_within(limit) { Some(owner) } else { None } } - /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm`, preferring `home` when - /// claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to `WARM_PB_SLOTS` concurrent VMs - /// bind disjoint warm slots regardless of arrival order. - pub(crate) fn pick_slot_in_mask_blocks( + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available + /// to rotate onto safely. + #[allow(dead_code)] + pub(crate) fn reusable_for_within( + &self, + k: usize, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> Option> { + self.reusable_for_within_mode(k, vm, limit, min_blocks, false) + } + /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm` and `want_scs`, + /// preferring `home` when claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to + /// `WARM_PB_SLOTS` concurrent VMs bind disjoint warm slots regardless of arrival order. + pub(crate) fn pick_slot_in_mask_blocks_mode( &self, vm: &Arc, behind: bool, slot_mask: u32, home: usize, min_blocks: u32, + want_scs: bool, ) -> Option { let in_mask = |k: usize| k < sizes::PB_SLOTS && (slot_mask & (1u32 << k)) != 0; if let Some(a) = self.active { if in_mask(a) && self - .reusable_for_mask(a, vm, slot_mask, min_blocks) + .reusable_for_mask_mode(a, vm, slot_mask, min_blocks, want_scs) .is_some() { return Some(a); @@ -618,7 +696,7 @@ impl Pools { if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { in_mask(k) && self - .reusable_for_mask(k, vm, slot_mask, min_blocks) + .reusable_for_mask_mode(k, vm, slot_mask, min_blocks, want_scs) .is_some() }) { return Some(k); @@ -655,56 +733,68 @@ impl Pools { .find(|&k| in_mask(k) && self.slot_displaced(k)) }) } - /// Whether `vm` has a warm reusable PB slot in `slot_mask` covering `min_blocks` so it can - /// pipeline without InitBM. - pub(crate) fn can_pipeline_in_mask_blocks( + /// Whether `vm` has a warm reusable PB slot in `slot_mask` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + pub(crate) fn can_pipeline_in_mask_blocks_mode( &self, vm: &Arc, slot_mask: u32, home: usize, min_blocks: u32, + want_scs: bool, ) -> bool { - self.pick_slot_in_mask_blocks(vm, true, slot_mask, home, min_blocks) + self.pick_slot_in_mask_blocks_mode(vm, true, slot_mask, home, min_blocks, want_scs) .is_some() } - /// Whether no allocator slot in `slot_mask` can accept a render for `vm` once drained. - pub(crate) fn exhausted_for_mask( + /// Whether no allocator slot in `slot_mask` can accept a render for `vm` and `want_scs` + /// once drained. + pub(crate) fn exhausted_for_mask_mode( &self, vm: &Arc, slot_mask: u32, home: usize, + want_scs: bool, ) -> bool { self.inflight.iter().all(|&c| c == 0) && self - .pick_slot_in_mask_blocks(vm, false, slot_mask, home, 0) + .pick_slot_in_mask_blocks_mode(vm, false, slot_mask, home, 0, want_scs) .is_none() } - /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused - /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm` and `want_scs`, + /// requiring any reused epoch to match `want_scs` and cover at least `min_blocks` when a + /// displaced slot is available for rotation. /// /// When `behind` is true (pipelining behind active flights), only a healthy warm reusable - /// slot already bound to `vm` (preferring `self.active`, then any other slot in `0..limit`) - /// is eligible; cold VMs or VMs whose PB heap expanded return `None` so the engine drains - /// once before rotating onto a fresh `InitBM` epoch. + /// slot already bound to `vm` with matching SCS mode (preferring `self.active`, then any + /// other slot in `0..limit`) is eligible; cold VMs, base<->SCS transitions, or VMs whose PB + /// heap expanded return `None` so the engine drains once before rotating onto a fresh + /// `InitBM` epoch. /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot /// working set) or the lowest fresh slot is claimed. #[allow(dead_code)] - pub(crate) fn pick_slot_within_blocks( + pub(crate) fn pick_slot_within_blocks_mode( &self, vm: &Arc, behind: bool, limit: usize, min_blocks: u32, + want_scs: bool, ) -> Option { let n = limit.min(sizes::PB_SLOTS); if let Some(a) = self.active { - if a < n && self.reusable_for_within(a, vm, n, min_blocks).is_some() { + if a < n + && self + .reusable_for_within_mode(a, vm, n, min_blocks, want_scs) + .is_some() + { return Some(a); } } - if let Some(k) = (0..n).find(|&k| self.reusable_for_within(k, vm, n, min_blocks).is_some()) - { + if let Some(k) = (0..n).find(|&k| { + self.reusable_for_within_mode(k, vm, n, min_blocks, want_scs) + .is_some() + }) { return Some(k); } if behind { @@ -715,6 +805,18 @@ impl Pools { .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused + /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. + #[allow(dead_code)] + pub(crate) fn pick_slot_within_blocks( + &self, + vm: &Arc, + behind: bool, + limit: usize, + min_blocks: u32, + ) -> Option { + self.pick_slot_within_blocks_mode(vm, behind, limit, min_blocks, false) + } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. #[allow(dead_code)] pub(crate) fn pick_slot_within( @@ -730,6 +832,19 @@ impl Pools { pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { self.pick_slot_within(vm, behind, sizes::PB_SLOTS) } + /// Whether `vm` has a warm reusable PB slot within `0..limit` matching `want_scs` and + /// covering `min_blocks` so it can pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within_blocks_mode( + &self, + vm: &Arc, + limit: usize, + min_blocks: u32, + want_scs: bool, + ) -> bool { + self.pick_slot_within_blocks_mode(vm, true, limit, min_blocks, want_scs) + .is_some() + } /// Whether `vm` has a warm reusable PB slot within `0..limit` covering `min_blocks` and can /// pipeline without InitBM. #[allow(dead_code)] @@ -739,8 +854,7 @@ impl Pools { limit: usize, min_blocks: u32, ) -> bool { - self.pick_slot_within_blocks(vm, true, limit, min_blocks) - .is_some() + self.can_pipeline_within_blocks_mode(vm, limit, min_blocks, false) } /// Whether `vm` has a warm reusable PB slot within `0..limit` and can pipeline without InitBM. #[allow(dead_code)] @@ -769,6 +883,20 @@ impl Pools { } !(0..sizes::PB_SLOTS).any(|k| self.slot_displaced(k)) } + /// Whether no allocator slot within `0..limit` can accept a render for `vm` and `want_scs` + /// once drained. + #[allow(dead_code)] + pub(crate) fn exhausted_for_within_mode( + &self, + vm: &Arc, + limit: usize, + want_scs: bool, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_within_blocks_mode(vm, false, limit, 0, want_scs) + .is_none() + } /// Whether no allocator slot within `0..limit` can accept a render for `vm` once drained. /// /// When a VM prepared fewer PB slots than needed after a render hang (or when only one @@ -776,7 +904,7 @@ impl Pools { /// instead of spinning on `EAGAIN` until the administrative publication deadline fails the GPU. #[allow(dead_code)] pub(crate) fn exhausted_for_within(&self, vm: &Arc, limit: usize) -> bool { - self.inflight.iter().all(|&c| c == 0) && self.pick_slot_within(vm, false, limit).is_none() + self.exhausted_for_within_mode(vm, limit, false) } /// Whether no allocator slot can accept a render for `vm` once the engine is drained. #[allow(dead_code)] @@ -992,6 +1120,7 @@ pub(crate) struct PbEpochInner { /// High-water block count previously written into the zero-allocated `pages`/`blocks` lists, /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). seeded_blocks: AtomicU32, + scs: AtomicBool, exposed: AtomicBool, /// VM-free firmware lease keeping `records` (`manager`, `ring`, `counter`, `misc`, `initbm`) /// mapped across closed-VM reclaim until a newer `InitBM` overwrites `pb_mgr_table[k]`. @@ -1023,6 +1152,7 @@ impl PbEpoch { assigned: AtomicU32::new(u32::MAX), heap_blocks: AtomicU32::new(0), seeded_blocks: AtomicU32::new(0), + scs: AtomicBool::new(false), exposed: AtomicBool::new(false), records_lease, _objects: o, @@ -1043,7 +1173,20 @@ 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. + #[allow(dead_code)] pub(crate) fn prepare(&self, k: usize, heap: u64, heap_blocks: u32) -> Result { + self.prepare_with_scs(k, heap, heap_blocks, false) + } + + /// Like [`Self::prepare`], recording whether this epoch is bound to the VM's SCS-capable + /// render allocators (`scs == true`) or its base allocators (`scs == false`). + pub(crate) fn prepare_with_scs( + &self, + k: usize, + heap: u64, + heap_blocks: u32, + scs: bool, + ) -> Result { if k >= sizes::PB_SLOTS || self.exposed.load(Ordering::Acquire) || heap_blocks == 0 @@ -1085,11 +1228,15 @@ impl PbEpoch { self.seeded_blocks.store(heap_blocks, Ordering::Release); self.assigned.store(k as u32, Ordering::Release); self.heap_blocks.store(heap_blocks, Ordering::Release); + self.scs.store(scs, Ordering::Release); Ok(()) } pub(crate) fn heap_blocks(&self) -> u32 { self.heap_blocks.load(Ordering::Acquire) } + pub(crate) fn scs(&self) -> bool { + self.scs.load(Ordering::Acquire) + } pub(crate) fn check_assignment(&self, k: usize) -> Result { if self.assigned.load(Ordering::Acquire) != k as u32 { return Err(EINVAL); diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index f8e8462a063f13..0b83aef27f1dc9 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -10,8 +10,12 @@ //! process (such as a compositor). It reserves no hardware graph or execution context. //! QUEUE_CREATE validates //! `usc_exec_base` (4 GiB aligned, the window inside the user range) and refuses a failed VM or -//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. Ray-query scratch layouts are -//! refused by the shared default `reserve_render_scs` (RENDER_RAY_QUERY is never advertised). +//! GPU (EIO); HIGH/REALTIME are refused by the shared `file.rs`. `render_scs_layout` (the +//! largest ray-query scratch layouts of the queue's render stages) is reserved at creation: +//! EINVAL for a malformed layout, E2BIG beyond the largest SCS-capable UMA pool; a render +//! whose scratch exceeds the reservation is refused (EINVAL), as on the M4 Pro. The +//! reservation also sizes the SCS-capable render pools its VM creates for it +//! ([`super::rt::pool_seeds`]). //! //! QUEUE_DESTROY (dropping the queue) drains: the scheduler entity is torn down first, which //! waits (killable) until every accepted job has been handed to the engine; the engine then runs @@ -156,6 +160,10 @@ pub(crate) struct Queue { vm: Arc, shared: Arc, timeline: Arc, + /// Enabled GPU cores, which SCS memory is sized for. + active_cores: u32, + /// Reserved render scratch pages per stage (`render_scs_layout`). + render_scs: [u16; 2], // Last field: all preceding fields (especially scheduler) drop before capacity returns. _credit: QueueCredit, } @@ -216,6 +224,8 @@ impl Queue { vm: vm_state, shared: gpu.shared.clone(), timeline, + active_cores: gpu.id.core_masks.iter().map(|mask| mask.count_ones()).sum(), + render_scs: [0; 2], _credit: credit, }) } @@ -246,6 +256,8 @@ impl Queue { &command::Context { vm: &self.vm.vm, usc_base: self.state.usc_base, + active_cores: self.active_cores, + render_scs: self.render_scs, }, &mut self.proof, )?; @@ -321,6 +333,22 @@ impl Queue { } impl crate::queue::Queue for Queue { + /// RENDER_RAY_QUERY: the largest scratch layouts of the queue's vertex and fragment stages. + /// A render's UMA pool serves both stages of one render at a time, so their extra pages add + /// up ([`super::rt::required_seeds`]). + fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { + if self.accepted != [0; 2] { + return Err(EBUSY); + } + let pages = [ + super::rt::ScratchRequest::new(layouts[0])?.pages(), + super::rt::ScratchRequest::new(layouts[1])?.pages(), + ]; + super::rt::required_seeds(self.active_cores, &pages)?; + self.render_scs = pages; + Ok(()) + } + fn submit( &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 8e9b9a61e3bab9..e6417355111425 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -51,8 +51,8 @@ pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Re } pub(crate) struct Recovery { - pub(crate) deadline_ns: u64, - pub(crate) compute_deadline_ns: u64, + /// Per-class host deadlines, ordinary and long-job ([`logic::Deadlines`]). + pub(crate) deadlines: logic::Deadlines, /// Per-class (render, compute) long-command warning deadlines; diagnostic only. warning_deadline_ns: [u64; 2], pub(crate) long_commands: u64, @@ -79,8 +79,7 @@ pub(crate) struct Recovery { impl Recovery { pub(crate) fn new() -> Self { Self { - deadline_ns: logic::EXPIRED, - compute_deadline_ns: logic::EXPIRED, + deadlines: logic::Deadlines::EXPIRED, warning_deadline_ns: [u64::MAX; 2], long_commands: 0, publication_wait_deadline: None, @@ -116,15 +115,18 @@ impl Firmware { pub(crate) fn renew_render_deadline(&mut self) { let now = now_ns(); - self.recovery.deadline_ns = logic::renew(now, params::deadline_ms(), 0).0; + let renewed = logic::Deadlines::renew(now, params::deadline_ms(), 0); + self.recovery.deadlines.any = renewed.any; + self.recovery.deadlines.long_any = renewed.long_any; self.recovery.warning_deadline_ns[super::command::RENDER] = now.saturating_add(5_000_000_000); } pub(crate) fn renew_compute_deadline(&mut self) { let now = now_ns(); - self.recovery.compute_deadline_ns = - logic::renew(now, 0, params::compute_deadline_ms()).1; + let renewed = logic::Deadlines::renew(now, 0, params::compute_deadline_ms()); + self.recovery.deadlines.compute = renewed.compute; + self.recovery.deadlines.long_compute = renewed.long_compute; self.recovery.warning_deadline_ns[super::command::COMPUTE] = now.saturating_add(5_000_000_000); } @@ -206,6 +208,16 @@ impl Firmware { .flights .iter() .any(|flight| flight.computes != 0); + let has_long_render = self + .engine + .flights + .iter() + .any(|flight| flight.renders != 0 && flight.job.long()); + let has_long_compute = self + .engine + .flights + .iter() + .any(|flight| flight.computes != 0 && flight.job.long()); if has_render && logic::expired( now, @@ -232,8 +244,11 @@ impl Firmware { "M4 GPU compute command has no completion-stamp progress for 5s; execution may still be active\n" ); } - if (has_render && logic::expired(now, self.recovery.deadline_ns)) - || (has_compute && logic::expired(now, self.recovery.compute_deadline_ns)) + // Ray traversal and AS builds: every flight of such a job (`Job::long`). + let render_deadline = self.recovery.deadlines.select(false, has_long_render); + let compute_deadline = self.recovery.deadlines.select(true, has_long_compute); + if (has_render && logic::expired(now, render_deadline)) + || (has_compute && logic::expired(now, compute_deadline)) { dev_err!( self.dev(), diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index f93b2cd35f4ffe..528760bb1654d3 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -182,6 +182,67 @@ pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> (u6 ) } +/// Ray traversal and acceleration-structure builds can run past one administrative deadline +/// (CTS stress). As on the M4 Pro (g17 `timeout::select`: two-second polls plus four extra +/// ones), a job with such a command gets at least ten seconds per flight. Still bounded: +/// this is an allowance, not evidence of GPU progress. +pub(crate) const LONG_DEADLINE_MS: u32 = 10_000; + +/// The administrative deadline of a long job, ms: at least [`LONG_DEADLINE_MS`], unless the +/// deadline is disabled (zero). +pub(crate) const fn long_deadline_ms(milliseconds: u32) -> u32 { + if milliseconds == 0 || milliseconds >= LONG_DEADLINE_MS { + milliseconds + } else { + LONG_DEADLINE_MS + } +} + +/// The four host deadlines renewed together: ordinary and compute-only, each plain and for a +/// long job. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct Deadlines { + pub(crate) any: u64, + pub(crate) compute: u64, + pub(crate) long_any: u64, + pub(crate) long_compute: u64, +} + +impl Deadlines { + pub(crate) const EXPIRED: Self = Self { + any: EXPIRED, + compute: EXPIRED, + long_any: EXPIRED, + long_compute: EXPIRED, + }; + + /// All four from `now`. + pub(crate) fn renew(now: u64, deadline_ms: u32, compute_deadline_ms: u32) -> Self { + let (any, compute) = renew(now, deadline_ms, compute_deadline_ms); + let (long_any, long_compute) = renew( + now, + long_deadline_ms(deadline_ms), + long_deadline_ms(compute_deadline_ms), + ); + Self { + any, + compute, + long_any, + long_compute, + } + } + + /// The deadline of the oldest flight: compute-only or not, of a long job or not. + pub(crate) const fn select(&self, compute_only: bool, long: bool) -> u64 { + match (compute_only, long) { + (true, false) => self.compute, + (false, false) => self.any, + (true, true) => self.long_compute, + (false, true) => self.long_any, + } + } +} + /// Zero explicitly opts long-running work out of the host's administrative watchdog. /// Completion stamps cannot distinguish a running shader from a firmware-silent hang. fn host_deadline(now: u64, milliseconds: u32) -> u64 { diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index c3b5d0acfed904..84d5623728910b 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassSlot}, + slots::{ComputeSlot, PassSlot, Placement}, vm::VmState, }; use crate::mmu; @@ -17,7 +17,7 @@ use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use kernel::{ new_condvar, new_mutex, new_spinlock_irq, prelude::*, - sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SpinLockIrq}, + sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SetOnce, SpinLockIrq}, }; /// Never-exposed PB epochs an open VM keeps on standby after bursts drain. @@ -55,17 +55,22 @@ const BURST_GAP_NS: u64 = 2_000_000; const BURST_COMMANDS: usize = 3; impl ComputeArena { - /// Allocates one self-contained compute unit `k` (its index fixes its client addresses and - /// hardware UMA slot). + /// Freelist entries of the unit's UMA pool. + pub(crate) fn seeds(&self) -> u32 { + self.unit.seeds + } + /// Allocates one self-contained compute unit `k` (its index and `placement` fix its client + /// addresses; the index fixes its hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, k: usize, + placement: Placement, ) -> Result> { let mut objects = factory.objects(vm); - let unit = ComputeSlot::new(&mut objects, factory, k as u64)?; + let unit = ComputeSlot::new_in(&mut objects, factory, k as u64, placement)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { @@ -88,18 +93,20 @@ pub(crate) struct ComputeUnitSet { units: KVec>, } impl ComputeUnitSet { - /// Units `range` (each index fixes its client addresses and hardware UMA slot). + /// Units `range` (each index and `placement` fix its client addresses; the index fixes its + /// hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, range: core::ops::Range, + placement: Placement, ) -> Result> { let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; for k in range { units.push( - ComputeArena::new(factory, bind, vm, live, k)?, + ComputeArena::new(factory, bind, vm, live, k, placement)?, GFP_KERNEL, )?; } @@ -108,6 +115,10 @@ impl ComputeUnitSet { fn len(&self) -> usize { self.units.len() } + /// Freelist entries of the set's UMA pools (all its units share a placement). + pub(crate) fn seeds(&self) -> u32 { + self.units.first().map_or(0, |arena| arena.seeds()) + } fn unit(&self, idx: usize) -> Option<&ComputeSlot> { self.units.get(idx).map(|arena| &arena.unit) } @@ -302,11 +313,20 @@ impl core::ops::Deref for RenderArena { &self.0 } } +/// The SCS-capable render allocators of a render arena and the mappings they own. +pub(crate) struct ScsPools { + pub(crate) pools: PoolSet, + _objects: Objects, +} + pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, /// Device-wide physical PB/UMA allocator slots `[home, alt]` bound to `pools.unit(0..2)`. pub(crate) base_pb_slots: [usize; BASE_PB_SLOTS], + /// [`PoolSet::scs`], with the VM's first render that has scratch. Held with the arena, so + /// a pass slot's owner lease keeps it too. Dropped before the arena's own mappings. + pub(crate) scs: SetOnce, pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], @@ -345,6 +365,7 @@ impl RenderArena { passes, pools, base_pb_slots, + scs: SetOnce::new(), tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], @@ -357,6 +378,30 @@ impl RenderArena { GFP_KERNEL, )?) } + /// Creates the SCS-capable render allocators with pools of `seeds.pool` entries unless + /// they exist. Existing ones must hold `seeds.needed`: once the hardware may hold them they + /// cannot grow (E2BIG). Called under the VM cache's construction mutex, before any job uses + /// them. + fn ensure_scs(&self, factory: &Factory, vm: &mmu::Vm, seeds: super::rt::ScsSeeds) -> Result { + if let Some(scs) = self.scs.as_ref() { + return if scs.pools.seeds() >= seeds.needed { + Ok(()) + } else { + Err(E2BIG) + }; + } + let mut objects = factory.objects(vm); + let pools = self.pools.scs(&mut objects, factory, seeds.pool)?; + objects.finish_private()?; + // The construction mutex excludes a second populate. + if !self.scs.populate(ScsPools { + pools, + _objects: objects, + }) { + return Err(EBUSY); + } + Ok(()) + } pub(crate) fn set_dirty(&self, k: usize, tpc: u64, tilemap: u64) -> Result { let pass = self.passes.get(k).ok_or(EINVAL)?; if tpc > pass.tpc.size as u64 || tilemap > pass.tilemap.size as u64 { @@ -468,6 +513,7 @@ impl PoolExtArena { local_idx as u64, hw_slot as u32, heap, + Placement::Base, )?; objects.finish_private()?; Ok(Arc::new( @@ -583,6 +629,8 @@ struct Ready { compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. compute_ext: Option>, + /// SCS-capable units, for jobs with compute scratch. + compute_scs: Option>, render: Option>, /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -778,6 +826,7 @@ impl Cache { ( ready.compute.take(), ready.compute_ext.take(), + ready.compute_scs.take(), ready.render.take(), core::mem::take(&mut ready.render_ext), core::mem::take(&mut ready.pb_heap_ext), @@ -804,6 +853,22 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; + // Scratch is sized on top of a pool's base pages: such a job runs on SCS-capable + // storage, for all its commands of that engine, whose pools hold the largest of them. + let scs = |engine: fn(&Command) -> bool| { + commands + .iter() + .filter(|&c| engine(c)) + .map(Command::scs) + .fold(super::rt::ScsSeeds::NONE, |a, b| super::rt::ScsSeeds { + needed: a.needed.max(b.needed), + pool: a.pool.max(b.pool).max(b.needed), + }) + }; + let compute_seeds = scs(|c| matches!(c, Command::Compute(_))); + let render_seeds = scs(|c| matches!(c, Command::Render(_))); + let compute_scs = compute_seeds.needed != 0; + let render_scs = render_seeds.needed != 0; let (compute, compute_ext, render_arena, render_ext, pb_heap_ext, pb_ext) = { // Never held by publication, completion, recovery, fence signalling or // standby waits, so Cache::close() and same-VM compute SUBMITs never block. @@ -811,16 +876,36 @@ impl Cache { if vm.status.get() != 0 || vm.vm.is_closed() || self.closed.load(Ordering::Acquire) { return Err(EIO); } - if compute && ready.compute.is_none() { + if compute && !compute_scs && ready.compute.is_none() { ready.compute = Some(ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, &self.live, 0..BASE_COMPUTE_UNITS, + Placement::Base, )?); } - if compute && ready.compute_ext.is_none() { + if compute_scs { + match ready.compute_scs.as_ref().map(|set| set.seeds()) { + None => { + ready.compute_scs = Some(ComputeUnitSet::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + 0..super::hw::sizes::SCS_COMPUTE_UNITS, + Placement::Scs { + seeds: compute_seeds.pool, + }, + )?); + } + // The units cannot grow once the hardware may hold them. + Some(seeds) if seeds < compute_seeds.needed => return Err(E2BIG), + Some(_) => {} + } + } + if compute && !compute_scs && ready.compute_ext.is_none() { let units = super::params::compute_units(); if units > BASE_COMPUTE_UNITS { // SAFETY: ktime_get has no preconditions. @@ -840,6 +925,7 @@ impl Cache { &vm.vm, &self.live, BASE_COMPUTE_UNITS..units, + Placement::Base, ) .ok(); } @@ -861,6 +947,13 @@ impl Cache { ready.render_vm_counter = Some(hints.active_render_vms.clone()); } } + if render_scs { + ready.render.as_ref().ok_or(EINVAL)?.ensure_scs( + &self.factory, + &vm.vm, + render_seeds, + )?; + } if render { if let Some(base) = ready.render.as_ref() { let quarantined = hints.quarantined_pb_mask; @@ -1000,8 +1093,16 @@ impl Cache { [const { None }; EXT_PB_SLOTS] }; ( - if compute { ready.compute.clone() } else { None }, - if compute { ready.compute_ext.clone() } else { None }, + match (compute, compute_scs) { + (true, true) => ready.compute_scs.clone(), + (true, false) => ready.compute.clone(), + (false, _) => None, + }, + if compute && !compute_scs { + ready.compute_ext.clone() + } else { + None + }, if render { ready.render.clone() } else { None }, render_ext, pb_heap_ext, @@ -1102,7 +1203,9 @@ impl Cache { Ok(Prepared { compute, compute_ext, + compute_scs, render: render_arena, + render_scs, render_ext, pb_heap_ext, pb_ext, @@ -1118,7 +1221,11 @@ pub(crate) struct Prepared { pub(crate) compute: Option>, /// The VM's extension compute units when the job was prepared. pub(crate) compute_ext: Option>, + /// The job's computes use the VM's SCS-capable compute arena (`0..SCS_COMPUTE_UNITS`). + compute_scs: bool, pub(crate) render: Option>, + /// The job's renders use the arena's SCS-capable allocators (`render.scs`). + render_scs: bool, /// The VM's demand-grown extension render pass tiers when the job was prepared. pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], /// The VM's demand-grown contiguous PB heap extension tiers when the job was prepared. @@ -1165,6 +1272,14 @@ impl Prepared { .and_then(|ext| ext.arena(k - base.len())) } } + /// Whether this job's computes use SCS-capable compute units. + pub(crate) fn compute_scs(&self) -> bool { + self.compute_scs + } + /// Whether this job's renders use SCS-capable render allocators. + pub(crate) fn render_scs(&self) -> bool { + self.render_scs + } /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. pub(crate) fn pb_slot_mask(&self) -> Result<(u32, usize)> { let base = self.render()?; @@ -1172,9 +1287,11 @@ impl Prepared { for &slot in &base.base_pb_slots { mask |= 1u32 << slot; } - for (idx, ext) in self.pb_ext.iter().enumerate() { - if ext.is_some() { - mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + if !self.render_scs { + for (idx, ext) in self.pb_ext.iter().enumerate() { + if ext.is_some() { + mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + } } } Ok((mask, base.base_pb_slots[0])) @@ -1182,7 +1299,17 @@ impl Prepared { fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { let base = self.render()?; if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { - return base.pools.unit(local).ok_or(EINVAL); + return if self.render_scs { + base.scs + .as_ref() + .and_then(|scs| scs.pools.unit(local)) + .ok_or(EINVAL) + } else { + base.pools.unit(local).ok_or(EINVAL) + }; + } + if self.render_scs { + return Err(EINVAL); } let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS).ok_or(EINVAL)?; self.pb_ext diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs new file mode 100644 index 00000000000000..4119afade7c232 --- /dev/null +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -0,0 +1,531 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Hardware ray tracing on G16G (RENDER_RAY_QUERY and BOUNDED_AS_BUILD). +//! +//! The command state is the shared G17P UAPI: a compute command's packed shader-context +//! scratch (SCS) layout and intersection tables, a render's per-stage ray-query state, and the +//! compute AS-build flag. The validation, the register words they become and the SCS memory +//! sizing are those of the M4 Pro (T6041, the same G16 GPU generation) on its 26B123 firmware +//! (`g17::fw::variant::V26B123`), except where macOS 27.2 on the J773g (G16G, 26B123) has +//! been traced: a ray-query compute item's 0x017e1/0x017d9 records and 0xd479 tail +//! ([`super::encode`]), and the SCS pools' freelists (+0x1c, [`SCS_FREELIST_RECORDS`]) and +//! row words (+0x48). This module is pure: no kernel objects, no allocation. +//! +//! What neither settles for G16G stays off behind a named gate or is open, as trace questions +//! of mesa#577: +//! +//! - 0x017d9 (SCS enable) in a render stage, [`super::encode`]'s `RENDER_SCS_ENABLE` (T5, +//! T6): the M4 Pro's 25G83 render programs write it in a stage with SCS. No G16G render with +//! ray queries has been traced. +//! - 0x1a141 (SCS driver word), `COMPUTE_SCS_DRIVER_WORD` (T1): macOS's ray-query compute +//! items on the J773g do not write it. +//! - An SCS-enable bit in the work or microsequence, as g17's kick header has (T6): none is +//! known, so nothing is written. +//! - A traversal exclusion between clients (T8): the A18 Pro needs one (`g17::traversal`), the +//! M4 Pro's variants do not set it; G16G adds none. +//! - How macOS sizes the SCS pool for a given request (T3): it grows its compute pool beyond +//! the M4 Pro's extras ([`pool_seeds`]); one request size does not give the rule. + +use kernel::prelude::*; + +/// Validated per-command shader-context scratch request (g17 `fw::compute::ScratchRequest`). +/// +/// The layout word is Apple's packed SCS layout: depth (bits 0:15), levels (16:23), cliques +/// (24:31), user (32:47) and driver (48:63). The region the hardware needs is derived with the +/// Gen1 section model: fixed prefixes totalling [`Self::FIXED_BYTES`], then per-thread stack, +/// per-thread driver and per-thread user bytes, rounded up with a two-page guard. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScratchRequest { + pages: u16, + window: u64, + stack: u64, + driver: u64, + tail: u64, +} + +impl ScratchRequest { + /// Native ScsLayoutGen1::getSectionEnd(4). + const FIXED_BYTES: u64 = 0x58000; + const THREADS_PER_CLIQUE: u64 = 32; + const BYTES_PER_STACK_ENTRY: u64 = 8; + const PAGE_SHIFT: u32 = 12; + const PAGE_SIZE: u64 = 1 << Self::PAGE_SHIFT; + const PAGES_PER_MIB: u64 = 1 << (20 - Self::PAGE_SHIFT); + /// Window word when enabled: bit 24 plus the clique count at 16:23. + const WINDOW_ENABLED: u64 = 1 << 24; + /// Disabled window word: the value G16G's work lists write today. + pub(crate) const WINDOW_DISABLED: u64 = 0xff_0000; + /// Disabled stack word: the value G16G's work lists write today. + pub(crate) const STACK_DISABLED: u64 = 8; + /// TA/FS tail reservation when enabled (0xd471, 0xd469), matching macOS 27.2's J773g + /// ray-query tail reservation (0x2c). + const TAIL_ENABLED: u64 = 0x2c; + /// Compute tail reservation when enabled (0xd479), as macOS 27.2 on the J773g writes it in + /// its ray-query compute work. + const COMPUTE_TAIL_ENABLED: u64 = 0x2c; + + /// No scratch. + pub(crate) const NONE: Self = Self { + pages: 0, + window: Self::WINDOW_DISABLED, + stack: Self::STACK_DISABLED, + driver: 0, + tail: 0, + }; + + /// Payload-free layouts request no scratch even if depth or cliques are set. + pub(crate) fn new(layout: u64) -> Result { + let depth = layout & u64::from(u16::MAX); + let cliques = (layout >> 24) & u64::from(u8::MAX); + let user = (layout >> 32) & u64::from(u16::MAX); + let driver = (layout >> 48) & u64::from(u16::MAX); + if user == 0 && driver == 0 { + return Ok(Self::NONE); + } + let threads = cliques + .checked_mul(Self::THREADS_PER_CLIQUE) + .ok_or(EINVAL)?; + let stack_bytes = threads + .checked_mul( + depth + .checked_mul(Self::BYTES_PER_STACK_ENTRY) + .ok_or(EINVAL)?, + ) + .ok_or(EINVAL)?; + let driver_bytes = threads.checked_mul(driver).ok_or(EINVAL)?; + let user_bytes = threads.checked_mul(user).ok_or(EINVAL)?; + let end = Self::FIXED_BYTES + .checked_add(stack_bytes) + .and_then(|bytes| bytes.checked_add(driver_bytes)) + .and_then(|bytes| bytes.checked_add(user_bytes)) + .and_then(|bytes| bytes.checked_add(2 * Self::PAGE_SIZE - 1)) + .ok_or(EINVAL)?; + let pages = end >> Self::PAGE_SHIFT; + Ok(Self { + pages: u16::try_from(pages).map_err(|_| EINVAL)?, + window: Self::WINDOW_ENABLED | (cliques << 16), + stack: depth & !7, + // The Gen1 register list publishes no level region: the word stays zero. + driver: 0, + tail: Self::TAIL_ENABLED, + }) + } + + pub(crate) fn enabled(self) -> bool { + self.pages != 0 + } + + /// Per-core 4-KiB pages of the request. + pub(crate) fn pages(self) -> u16 { + self.pages + } + + /// 0x101d1 (compute), 0x101c9 (TA), 0x101c1 (FS): the pages and their 1-MiB count. + pub(crate) fn size_word(self) -> u64 { + let pages = u64::from(self.pages); + pages | (pages.div_ceil(Self::PAGES_PER_MIB) << 16) + } + + /// 0x107a1 (compute), 0x10799 (TA); the FS 0x10791 also sets bit 9. + pub(crate) fn window_word(self) -> u64 { + self.window + } + + /// 0x1a0e9 (compute), 0x1a0f1 (TA), 0x1a0f9 (FS). + pub(crate) fn stack_word(self) -> u64 { + self.stack + } + + /// 0x1a141 (compute), written only with `COMPUTE_SCS_DRIVER_WORD`. + pub(crate) fn driver_word(self) -> u64 { + self.driver + } + + /// 0xd471 (TA), 0xd469 (FS). + pub(crate) fn tail_word(self) -> u64 { + self.tail + } + + /// 0xd479 (compute). + pub(crate) fn compute_tail_word(self) -> u64 { + if self.enabled() { + Self::COMPUTE_TAIL_ENABLED + } else { + 0 + } + } +} + +/// Validated intersection tables (g17 `fw::compute::IntersectionTables`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct IntersectionTables { + pub(crate) pool: u64, + pub(crate) pool_bytes: u64, + first: u32, + count: u32, + pub(crate) default_program: u64, + default_control: u64, +} + +impl IntersectionTables { + pub(crate) const NONE: Self = Self { + pool: 0, + pool_bytes: 0, + first: 0, + count: 0, + default_program: 0, + default_control: 0, + }; + + /// The HAL200 Gen1 table: a 16-KiB aligned pool of 16-KiB units below 2^48, a byte-sized + /// table length of 25 bits, 128-byte entries, and a default program whose 48-bit code + /// address is 64-byte aligned and whose control word has bit 40 set. + pub(crate) fn new( + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if pool == 0 { + if pool_bytes != 0 + || first != 0 + || count != 0 + || default_program != 0 + || default_control != 0 + { + return Err(EINVAL); + } + return Ok(Self::NONE); + } + let end = pool.checked_add(pool_bytes).ok_or(EINVAL)?; + let blocks_end = u64::from(first) + u64::from(count); + let code = default_program & 0x0000_ffff_ffff_ffff; + if pool & 0x3fff != 0 + || pool_bytes == 0 + || pool_bytes & 0x3fff != 0 + || end > (1u64 << 48) + || (pool_bytes >> 14) >= (1u64 << 25) + || count == 0 + || count >= (1 << 18) + || blocks_end * 128 > pool_bytes + || code & 63 != 0 + || default_control & !0x0000_7fff_0000_3fff != 0 + || (code == 0 && (default_program != 0 || default_control != 0)) + || (code != 0 && default_control & (1u64 << 40) == 0) + { + return Err(EINVAL); + } + Ok(Self { + pool, + pool_bytes, + first, + count, + default_program, + default_control, + }) + } + + /// A render stage's 48-byte table: the auxiliary word (zero or 8..=32, only with a pool), + /// four MBZ bytes, then the fields of [`Self::new`]. Bytes past 48 must be zero. The + /// auxiliary word is validated only: the M4 Pro's render programs write the scratch tail + /// where its compute program would write it. + pub(crate) fn parse(bytes: &[u8]) -> Result { + if bytes + .get(48..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut tail = [0u8; 48]; + let count = bytes.len().min(tail.len()); + tail[..count].copy_from_slice(&bytes[..count]); + let u32_at = + |at: usize| u32::from_le_bytes([tail[at], tail[at + 1], tail[at + 2], tail[at + 3]]); + let u64_at = |at: usize| u64::from(u32_at(at)) | u64::from(u32_at(at + 4)) << 32; + let auxiliary = u32_at(0); + if u32_at(4) != 0 || (auxiliary != 0 && !(8..=32).contains(&auxiliary)) { + return Err(EINVAL); + } + let tables = Self::new( + u64_at(8), + u64_at(16), + u32_at(24), + u32_at(28), + u64_at(32), + u64_at(40), + )?; + if auxiliary != 0 && !tables.enabled() { + return Err(EINVAL); + } + Ok(tables) + } + + pub(crate) fn enabled(self) -> bool { + self.pool != 0 + } + + /// The 48-bit address of the default program, or zero. + pub(crate) fn default_code(self) -> u64 { + self.default_program & 0x0000_ffff_ffff_ffff + } + + /// The six table words: compute 0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1; TA + /// 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1; FS 0x1a0a9, 0x1a0b1, 0x1a079, + /// 0x1a081, 0x1a0d9, 0x1a0e1. The M4 Pro's encoding (AGXMetalG17P endComputePass): the + /// first entry, the byte length, and two fixed pool words. Zero without tables, the value + /// G16G's work lists write today. + pub(crate) fn words(self) -> [u64; 6] { + if !self.enabled() { + return [0; 6]; + } + [ + self.pool + u64::from(self.first) * 128, + 0xc000_0000 | (u64::from(self.count) << 7), + 0x6f_0000_0000, + 0x3feff, + self.default_program, + self.default_control, + ] + } +} + +/// The ray state of a compute command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ComputeRay { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl ComputeRay { + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + /// As the M4 Pro (G17P command set): an auxiliary allocation is M5-only and must be zero, + /// as must the reserved word; tables and scratch are independent of each other. + #[allow(clippy::too_many_arguments)] + pub(crate) fn new( + scs_layout: u64, + auxiliary: u32, + reserved: u32, + pool: u64, + pool_bytes: u64, + first: u32, + count: u32, + default_program: u64, + default_control: u64, + ) -> Result { + if auxiliary != 0 || reserved != 0 { + return Err(EINVAL); + } + Ok(Self { + intersection: IntersectionTables::new( + pool, + pool_bytes, + first, + count, + default_program, + default_control, + )?, + scratch: ScratchRequest::new(scs_layout)?, + }) + } +} + +/// The ray state of one render stage (g17 `fw::render_rt::RayQueryStage`): index 0 the +/// vertex (tiling) stage, 1 the fragment stage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RayQueryStage { + pub(crate) intersection: IntersectionTables, + pub(crate) scratch: ScratchRequest, +} + +impl RayQueryStage { + /// Size of one `drm_asahi_render_ray_query_stage`. + pub(crate) const SIZE: usize = 56; + + #[allow(dead_code, reason = "The empty state of the host regressions.")] + pub(crate) const NONE: Self = Self { + intersection: IntersectionTables::NONE, + scratch: ScratchRequest::NONE, + }; + + fn parse(wire: &[u8; Self::SIZE]) -> Result { + let layout = u64::from_le_bytes([ + wire[0], wire[1], wire[2], wire[3], wire[4], wire[5], wire[6], wire[7], + ]); + let intersection = IntersectionTables::parse(&wire[8..])?; + let scratch = ScratchRequest::new(layout)?; + if scratch.enabled() != intersection.enabled() { + return Err(EINVAL); + } + Ok(Self { + intersection, + scratch, + }) + } + + /// Both stages from the render payload bytes after `prior_cdm`: shorter payloads are read + /// zero-filled, bytes past the two stages must be zero. + pub(crate) fn parse_pair(bytes: &[u8]) -> Result<[Self; 2]> { + if bytes + .get(2 * Self::SIZE..) + .is_some_and(|tail| tail.iter().any(|&b| b != 0)) + { + return Err(EINVAL); + } + let mut wire = [[0u8; Self::SIZE]; 2]; + for (index, stage) in wire.iter_mut().enumerate() { + let start = (index * Self::SIZE).min(bytes.len()); + let end = ((index + 1) * Self::SIZE).min(bytes.len()); + stage[..end - start].copy_from_slice(&bytes[start..end]); + } + Ok([Self::parse(&wire[0])?, Self::parse(&wire[1])?]) + } + + /// Whether the stage carries intersection tables. + pub(crate) fn traces(self) -> bool { + self.intersection.enabled() + } +} + +/// Only the explicit AS-build bit (bit 2) is accepted; reserved and unrelated compute flags +/// stay invalid on G16G, as on the M4 Pro (g17 `timeout::as_build`). +pub(crate) fn as_build(flags: u32) -> Option { + const AS_BUILD: u32 = 1 << 2; + if flags & !AS_BUILD != 0 { + None + } else { + Some(flags & AS_BUILD != 0) + } +} + +/// Whether a command needs the long execution allowance (g17 `timeout::select`): a compute +/// command with intersection tables, a render with tables in either stage, or an AS build. +pub(crate) fn select(compute_ray: bool, render_ray: [bool; 2], as_build: bool) -> bool { + compute_ray || render_ray.into_iter().any(|enabled| enabled) || as_build +} + +/// Freelist entries (4-KiB pages) of a UMA pool without SCS, the value G16G seeds today. +pub(crate) const BASE_SEEDS: u32 = 8192; +/// Records of a base UMA freelist: the capacity G16G's managers report at +0x1c for their +/// 0x20000-byte freelist (`UNK_1C_VALUE`). +pub(crate) const FREELIST_RECORDS: u32 = 16384; +/// Records of an SCS-capable pool's freelist: the +0x1c macOS 27.2 on the J773g writes on +/// every pool, over a 4-MiB freelist, whatever the pool's rows (20 to 108 seen). +pub(crate) const SCS_FREELIST_RECORDS: u32 = 0x80000; +/// Bytes of one freelist record, the 64-bit address of one 4-KiB seed. +pub(crate) const RECORD_BYTES: u64 = 8; +/// Bytes of one seed. +pub(crate) const SEED_BYTES: u64 = 0x1000; +/// Freelist entries of one 2-MiB pool-table row. +pub(crate) const SEEDS_PER_ROW: u32 = 512; +/// The most freelist entries of an SCS-capable UMA pool: the whole rows whose pool and +/// freelist fit one SCS pool window (62 rows, 124 MiB, and the 4-MiB freelist). The 256-row +/// pool table holds more. +pub(crate) const MAX_SCS_SEEDS: u32 = max_window_seeds(super::hw::client::SCS_POOL_WINDOW); +const _: () = assert!(BASE_SEEDS % SEEDS_PER_ROW == 0 && MAX_SCS_SEEDS % SEEDS_PER_ROW == 0); +const _: () = assert!(BASE_SEEDS < FREELIST_RECORDS && FREELIST_RECORDS < MAX_SCS_SEEDS); +const _: () = assert!(MAX_SCS_SEEDS < SCS_FREELIST_RECORDS); +const _: () = assert!(freelist_records(BASE_SEEDS) as u64 * RECORD_BYTES == 0x20000); + +/// The freelist records (+0x1c) of a UMA pool with `seeds` entries. +0x1c is the record count +/// of the freelist +0x14 points at. A base pool keeps the 16384 G16G has always written; an +/// SCS-capable pool (more than the base seeds) gets [`SCS_FREELIST_RECORDS`], as macOS 27.2 on +/// the J773g gives every pool. +pub(crate) const fn freelist_records(seeds: u32) -> u32 { + if seeds > BASE_SEEDS { + SCS_FREELIST_RECORDS + } else { + FREELIST_RECORDS + } +} + +/// Bytes of the freelist of a pool with `seeds` entries, in whole 16-KiB pages. +pub(crate) const fn freelist_bytes(seeds: u32) -> u64 { + (freelist_records(seeds) as u64 * RECORD_BYTES).next_multiple_of(0x4000) +} + +/// Bytes an SCS pool window needs for a pool of `seeds` entries and, after it, its freelist. +pub(crate) const fn window_bytes(seeds: u32) -> u64 { + seeds as u64 * SEED_BYTES + freelist_bytes(seeds) +} + +/// The most whole-row seeds whose pool and freelist fit `window` bytes. +const fn max_window_seeds(window: u64) -> u32 { + let mut seeds = (window / SEED_BYTES) as u32 / SEEDS_PER_ROW * SEEDS_PER_ROW; + while seeds != 0 && window_bytes(seeds) > window { + seeds -= SEEDS_PER_ROW; + } + seeds +} + +/// The 4-KiB pages one SCS request adds to a UMA pool for `active_cores` cores, as the M4 Pro +/// sizes its free list (g17 `fw::compute_pool::extra_bytes`): per core the request's pages, +/// their 1-MiB large-page inventory (pages / 256, rounded up) and eight tail pages. +pub(crate) fn extra_pages(active_cores: u32, scs_pages: u16) -> Result { + if active_cores == 0 { + return Err(EINVAL); + } + if scs_pages == 0 { + return Ok(0); + } + let small = u64::from(scs_pages); + small + .checked_add(small.div_ceil(256)) + .and_then(|pages| pages.checked_add(8)) + .and_then(|pages| pages.checked_mul(u64::from(active_cores))) + .ok_or(EOVERFLOW) +} + +/// Freelist entries a UMA pool needs to serve SCS requests of `pages` per stage at once (one +/// compute dispatch, or the two stages of one render): the base pool plus every stage's extra +/// pages, rounded up to whole pool-table rows. E2BIG beyond the largest SCS-capable pool +/// ([`MAX_SCS_SEEDS`]); without SCS it is [`BASE_SEEDS`]. +pub(crate) fn required_seeds(active_cores: u32, pages: &[u16]) -> Result { + let mut seeds = u64::from(BASE_SEEDS); + for &stage in pages { + seeds = seeds + .checked_add(extra_pages(active_cores, stage)?) + .ok_or(EOVERFLOW)?; + } + let row = u64::from(SEEDS_PER_ROW); + let seeds = seeds.checked_add(row - 1).ok_or(EOVERFLOW)? / row * row; + if seeds > u64::from(MAX_SCS_SEEDS) { + return Err(E2BIG); + } + u32::try_from(seeds).map_err(|_| E2BIG) +} + +/// The SCS-capable UMA pool a command runs on: one of at least `needed` freelist entries, or +/// if its VM has none yet, a new one of `pool` ([`pool_seeds`]). Both zero without scratch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ScsSeeds { + pub(crate) needed: u32, + pub(crate) pool: u32, +} + +impl ScsSeeds { + /// No scratch. + pub(crate) const NONE: Self = Self { needed: 0, pool: 0 }; +} + +/// Freelist entries of the SCS-capable pools created for requests of `pages` per stage (a +/// render's two stages, or a compute dispatch and zero). The pools serve every later job of the +/// VM and cannot grow once the hardware may hold them, so they hold two stages at the larger +/// one where a window holds that, otherwise the request itself; E2BIG if neither fits. +/// +/// - A render pool then takes a later queue that reserves the other stage too (Mesa replaces +/// its queue to add one). +/// - A compute pool gets two dispatches' extras. One is less than macOS provisions: for its +/// own ray-query kernel of 1703 pages per core, macOS 27.2 on the J773g grew the compute pool +/// to 108 rows, about 2.6 times the extras of [`extra_pages`]. +pub(crate) fn pool_seeds(active_cores: u32, pages: [u16; 2]) -> Result { + let largest = pages[0].max(pages[1]); + required_seeds(active_cores, &[largest, largest]) + .or_else(|_| required_seeds(active_cores, &pages)) +} diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index aa3d445a12bd83..8891434a0e52f7 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -32,36 +32,139 @@ pub(crate) struct ComputeSlot { pub(crate) counter: Arc, pub(crate) context_store: Arc, pub(crate) aux: Arc, + /// Freelist entries of the unit's UMA pool, seeded once ([`init_uma_pool`]). + pub(crate) seeds: u32, /// VM-free firmware lease keeping `work` (containing the compute UMA manager at `+0xe00`) /// and `counter` mapped in context-0 UAT until a later compute retirement overwrites /// firmware `uma_mgr_table[1 + k]`. uma_lease: Arc, } +/// Where a compute unit lives and how large its UMA pool is. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Placement { + /// The VM's base units: a 32 MiB pool at the unit's original client addresses. + Base, + /// SCS-capable units (ray-query scratch): a pool of `seeds` 4-KiB entries + /// ([`super::rt::required_seeds`]) and its freelist in the unit's SCS pool window, the + /// other records at their own client addresses, sharing ledger index and UMA slot `1 + k` + /// with base unit k. + Scs { seeds: u32 }, +} + +impl Placement { + fn pool(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_pool(k), + Placement::Scs { .. } => client::scs_compute_pool(k), + } + } + /// The base of the unit's list, preempt, auxiliary and context records. + fn state(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => client::scs_compute_records(k), + } + } + /// The unit's freelist: a base unit's at its state, an SCS unit's right after its pool. + fn freelist(self, k: u64) -> u64 { + match self { + Placement::Base => client::compute_state(k), + Placement::Scs { .. } => self.pool(k) + self.pool_bytes() as u64, + } + } + fn work(self, k: u64) -> u64 { + let index = match self { + Placement::Base => k, + Placement::Scs { .. } => sizes::COMPUTE_UNITS as u64 + k, + }; + client::WORK_PAGE + index * client::CWORK_STRIDE + } + /// Freelist entries of the unit's pool. + pub(crate) fn seeds(self) -> u32 { + match self { + Placement::Base => super::rt::BASE_SEEDS, + Placement::Scs { seeds } => seeds, + } + } + /// Bytes of the unit's pool: its seeds of 4 KiB. + pub(crate) fn pool_bytes(self) -> usize { + (u64::from(self.seeds()) * super::rt::SEED_BYTES) as usize + } + /// Bytes of the unit's freelist ([`super::rt::freelist_bytes`]). + pub(crate) fn freelist_bytes(self) -> usize { + super::rt::freelist_bytes(self.seeds()) as usize + } + /// An SCS unit's pool fits [`super::rt::MAX_SCS_SEEDS`] in whole rows, so it and its + /// freelist fit its window. + pub(crate) fn check(self) -> Result { + match self { + Placement::Base => Ok(()), + Placement::Scs { seeds } => { + if seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW != 0 + || seeds > super::rt::MAX_SCS_SEEDS + { + Err(E2BIG) + } else { + Ok(()) + } + } + } + } +} +const _: () = assert!( + sizes::POOL_BYTES == super::rt::BASE_SEEDS as u64 * super::rt::SEED_BYTES + && super::rt::window_bytes(super::rt::MAX_SCS_SEEDS) <= client::SCS_POOL_WINDOW +); + /// Initializes the private pool exactly once, before it is exposed. Never called on reuse. -pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64) -> Result { - if pool & 0x3fff != 0 { +/// `seeds` 4-KiB freelist entries and their 2-MiB pool-table rows; 8192 is the 32 MiB pool +/// every unit had before SCS. The freelist `state` holds every seed, the pool table `list` +/// every row. +pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: u32) -> Result { + let seeds = seeds as usize; + let rows = seeds / super::rt::SEEDS_PER_ROW as usize; + if pool & 0x3fff != 0 + || seeds == 0 + || seeds % super::rt::SEEDS_PER_ROW as usize != 0 + || seeds * super::rt::RECORD_BYTES as usize > state.size + || rows * super::fw::buffer::uma_pools::POOL_TABLE_STRIDE > list.size + { return Err(EINVAL); } let mut chunk = [0u8; 512]; - for first in (0..8192).step_by(64) { + for first in (0..seeds).step_by(64) { for j in 0..64 { chunk[j * 8..j * 8 + 8] .copy_from_slice(&(pool + ((first + j) as u64) * 0x1000).to_le_bytes()); } state.write(first * 8, &chunk)?; } - for i in 0..16 { + for i in 0..rows { list.w64(i * 64, (1u64 << 61) | (pool + i as u64 * 0x200000))?; } Ok(()) } impl ComputeSlot { + #[allow(dead_code)] pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { + Self::new_in(o, fw_factory, k, Placement::Base) + } + + /// Unit `k` at `placement`. + pub(crate) fn new_in( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + placement: Placement, + ) -> Result { + placement.check()?; let sh = Class::Shared; + let state = placement.state(k); let mut fw = fw_factory.fw_objects(); - let work = alloc_work(&mut fw, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?; + let work = alloc_work(&mut fw, 0x2000, placement.work(k), 0)?; let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; let uma_lease = FwLease::new(fw)?; let unit = Self { @@ -70,7 +173,7 @@ impl ComputeSlot { o, 0x4000, sh, - Client::nc(client::compute_preempt(k)), + Client::nc(state + client::COMPUTE_PREEMPT_OFF), 0, false, )?, @@ -86,42 +189,59 @@ impl ComputeSlot { false, )?, pool: o.alloc(super::object::Request { - size: 0x2000000, + size: placement.pool_bytes(), class: sh, placement: super::object::Placement::Anywhere, offset: 0, - client: Some((client::compute_pool(k), super::hw::pte::LEAF_NC)), + client: Some((placement.pool(k), super::hw::pte::LEAF_NC)), lower: None, cpu: false, })?, pool_state: alloc( o, - 0x20000, + placement.freelist_bytes(), + sh, + Client::nc(placement.freelist(k)), + 0, + false, + )?, + page_list: alloc( + o, + 0x4000, sh, - Client::nc(client::compute_state(k)), + Client::nc(state + client::COMPUTE_LIST_OFF), 0, false, )?, - page_list: alloc(o, 0x4000, sh, Client::nc(client::compute_list(k)), 0, false)?, counter, context_store: alloc( o, 0x40000, sh, - Client::nc(client::compute_context(k)), + Client::nc(state + client::COMPUTE_CONTEXT_OFF), 0, false, )?, - aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, + aux: alloc( + o, + 0x4000, + sh, + Client::nc(state + client::COMPUTE_AUX_OFF), + 0, + false, + )?, + seeds: placement.seeds(), uma_lease, }; init_uma_pool( &unit.pool_state, &unit.page_list, unit.pool.gva.ok_or(EINVAL)?, + unit.seeds, )?; Ok(unit) } + /// VM-free firmware lease keeping this unit's `work` and `counter` mapped in context-0 UAT. pub(crate) fn uma_lease(&self) -> Arc { self.uma_lease.clone() @@ -1171,7 +1291,12 @@ impl Slots { let Some(k) = chosen else { return Ok(None); }; + let arena_changed = self.compute.arena[k] + .as_ref() + .zip(units.compute_arena(k).as_ref()) + .is_some_and(|(a, b)| !Arc::ptr_eq(a, b)); let full = self.compute.scrub_full[k] + || arena_changed || vm_id.is_none_or(|id| { self.compute.owner[k] .as_ref() diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index db053aef622781..0ffd1dd5219873 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -329,7 +329,7 @@ enum drm_asahi_feature { DRM_ASAHI_FEATURE_COMPUTE_WIDE_VISIBILITY = (1UL) << 8, /* - * Bits 10 to 15 are reported only by the G17P runtime. + * Bits 10 to 16 are the HAL200/G16/G17P command-stream features. */ /** diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs index 62fb9222460f81..e0099ee4862e6c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs @@ -9,7 +9,10 @@ mod fw { } } #[allow(unused_imports)] -use fw::{graph::manager, work::compute}; +use fw::{ + graph::{manager, pools}, + work::compute, +}; mod uapi { #[derive(Default)] pub struct drm_asahi_cmd_compute {pub cdm_ctrl_stream_base:u64,pub cdm_ctrl_stream_end:u64} 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 3d1e261e301bc8..27093fdfdf1e7b 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 @@ -67,7 +67,7 @@ assert 'fn cover(' not in command assert 'enum Resolved' not in command hardware = (SOURCE.parent / 'hw.rs').read_text() -capacities = '\n'.join(re.findall(r'pub\(crate\) const (?:TPC_SIZE|TILEMAP_SIZE): u64 = .*?;', hardware)) +capacities = '\n'.join(re.findall(r'pub\(crate\) const (?:TPC_SIZE|TILEMAP_SIZE|SCS_POOL_WINDOW): u64 = .*?;', hardware)) names = ['drm_asahi_cmd_header', 'drm_asahi_attachment', 'drm_asahi_cmd_render', 'drm_asahi_cmd_compute', 'drm_asahi_bg_eot', 'drm_asahi_zls_buffer', 'drm_asahi_timestamp', 'drm_asahi_timestamps', 'drm_asahi_helper_program', @@ -103,7 +103,7 @@ // The parser logs why it refuses a command; check the format arguments, print nothing. macro_rules! pr_warn { ($($arg:tt)*) => {{ let _ = format_args!($($arg)*); }}; } pub mod bindings { pub const EOPNOTSUPP:i32=95; } -pub mod prelude { pub type Result = core::result::Result; pub const E2BIG:i32=-7; } +pub mod prelude { pub type Result = core::result::Result; pub const EINVAL:i32=-22; pub const E2BIG:i32=-7; pub const EOVERFLOW:i32=-75; } pub(crate) mod timestamp { pub(crate) struct Destinations; impl Destinations { pub(crate) const fn empty() -> Self { Self } } @@ -132,6 +132,7 @@ #[path="FW_WORK"] pub mod work; } #[path="FULL_ENCODER"] mod encode; +#[path="RT_MOD"] mod rt; READER IMPLS PRODUCTION_CONSTANTS @@ -237,7 +238,7 @@ } #[test] fn ray_query_and_unknown_extension_bytes_are_refused() { - let mut r=render(); r.ray_query[0].scs_layout=1; + let mut r=render(); r.ray_query[0].scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_RENDER,&data(&r),[NONE;2]),false).is_err()); let mut raw=data(&compute()); raw.extend([0u8;8]); assert!(check_stream(&entry(CMD_COMPUTE,&raw,[NONE;2]),false).is_ok()); @@ -386,7 +387,7 @@ both.legacy.flags |= FRAGMENT_BARRIERS; assert!(check_stream(&entry(CMD_RENDER, &data(&both), [NONE; 2]), true).is_err()); let mut rq = m5; - rq.legacy.ray_query[0].scs_layout = 1; + rq.legacy.ray_query[0].scs_layout = 0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_RENDER, &data(&rq), [NONE; 2]), true).is_err()); // Without STAGE_PREFIXES, nonzero trailing bytes past 448 are rejected; zero tail is accepted. @@ -444,7 +445,7 @@ assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); } let mut c=compute(); - c.scs_layout=1; + c.scs_layout=0xffff_0000_ff00_ffff; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); c.scs_layout=0; c.cdm_auxiliary_allocation=8; assert!(check_stream(&entry(CMD_COMPUTE,&data(&c),[NONE;2]),false).is_err()); @@ -696,6 +697,8 @@ pub(crate) struct Context<'a> { pub(crate) vm: &'a mmu::Vm, pub(crate) usc_base: u64, + pub(crate) active_cores: u32, + pub(crate) render_scs: [u16; 2], } use super::MAX_COMMANDS; RENDER_ADMISSION @@ -745,7 +748,7 @@ #[test] fn compressed_zls_1x_layered_and_2x_accepted() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; // 1x compressed D32F depth + stencil. let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -778,7 +781,7 @@ #[test] fn compressed_zls_invalid_ctrl_alignment_and_vm_spans_rejected() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let valid = || { let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -835,7 +838,7 @@ #[test] fn submit_wide_span_batch_dedups_and_flushes_once_across_passes() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let mut batch = SpanBatch::new(); for pass in 0..4u64 { let mut cmd = base_cmd(); @@ -875,7 +878,7 @@ #[test] fn few_primitives_flag_admitted_in_parse_and_render_check() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; let mut r = super::render(); r.flags = FEW_PRIMITIVES; assert!(super::check_stream( @@ -912,7 +915,7 @@ // First flush populates the proof for epoch 1. let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); assert_eq!(vm.batch_calls.get(), 1); @@ -958,7 +961,7 @@ vm.maps.remove(1); vm.epoch.set(Some(2)); let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40 }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Err(ENOENT)); @@ -975,9 +978,11 @@ replacements = {'FULL_UAPI': str(BINDINGS), 'READER': reader, 'CAPACITIES': capacities, 'FW_GRAPH': str(SOURCE.parent/'fw/graph.rs'), 'FW_WORK': str(SOURCE.parent/'fw/work.rs'), 'FULL_ENCODER': str(SOURCE.parent/'encode.rs'), + 'RT_MOD': str(SOURCE.parent/'rt.rs'), 'IMPLS': '\n'.join('unsafe impl AnyBitPattern for uapi::' + name + ' {}' for name in names), - 'PRODUCTION_CONSTANTS': constants, 'PARSE_TYPES': parse_types, - 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::'), + 'PRODUCTION_CONSTANTS': constants, + 'PARSE_TYPES': parse_types.replace('super::rt::', 'rt::'), + 'PRODUCTION_PARSER': parser.replace('super::encode::', 'encode::').replace('super::rt::', 'rt::'), 'INLINE_CONTAINERS': inline_containers.replace('crate::timestamp::', 'timestamp::'), 'RENDER_ADMISSION': render_admission.replace('super::vm::', 'vm::').replace('super::params::', 'params::'), 'G17_CONSTANTS': g17_constants, 'G17_PARSER': g17_parser} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index 0942af9db869a5..8cc61598bf6171 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -32,10 +32,12 @@ def function(text,name): macro_rules! dev_err{($($tt:tt)*)=>{};} struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;2],render:Render} -struct Flight{computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} +struct Job{long:bool} +impl Job{fn long(&self)->bool{self.long}} +struct Flight{job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,progress_flight:[u64;3],progress:[__TYPE__;4]} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} -struct Recovery{deadline_ns:u64,compute_deadline_ns:u64,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} +struct Recovery{deadlines:logic::Deadlines,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,fail_stops:Vec} impl Firmware{ fn dev(&self){} @@ -45,13 +47,17 @@ def function(text,name): fn fail_stop(&mut self,error:Error,_done:&mut ()){self.recovery.failed=Some(error);self.fail_stops.push(error);} fn renew_render_deadline(&mut self){ let now=now_ns(); - self.recovery.deadline_ns=logic::renew(now,params::deadline_ms(),0).0; + let renewed=logic::Deadlines::renew(now,params::deadline_ms(),0); + self.recovery.deadlines.any=renewed.any; + self.recovery.deadlines.long_any=renewed.long_any; self.recovery.warning_deadline_ns[command::RENDER]=now.saturating_add(5_000_000_000); self.render_renewed+=1; } fn renew_compute_deadline(&mut self){ let now=now_ns(); - self.recovery.compute_deadline_ns=logic::renew(now,0,params::compute_deadline_ms()).1; + let renewed=logic::Deadlines::renew(now,0,params::compute_deadline_ms()); + self.recovery.deadlines.compute=renewed.compute; + self.recovery.deadlines.long_compute=renewed.long_compute; self.recovery.warning_deadline_ns[command::COMPUTE]=now.saturating_add(5_000_000_000); self.compute_renewed+=1; } @@ -62,8 +68,8 @@ def function(text,name): fn firmware(render:bool,target:u32,previous:u32)->Firmware{ set_now_ns(1_000_000_000); let mut f=Firmware{graph:Graph{compute:[Compute{fw_stamp:Object(Cell::new(previous))},Compute{fw_stamp:Object(Cell::new(previous))}],render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flights:vec![Flight{computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, - recovery:Recovery{deadline_ns:u64::MAX,compute_deadline_ns:u64::MAX,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, + engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, + recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, render_renewed:0,compute_renewed:0,fail_stops:vec![]}; f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f } @@ -89,7 +95,7 @@ def function(text,name): } #[test]fn concurrent_compute_and_render_renew_deadlines_independently(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); f.engine.target[0]=0x300; f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); f.graph.compute[0].fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); @@ -97,7 +103,7 @@ def function(text,name): } #[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ let mut f=firmware(false,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); f.engine.target=[0x200,0x200]; f.progress();assert_eq!(f.compute_renewed,0); // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. @@ -110,7 +116,7 @@ def function(text,name): } #[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ let mut f=firmware(true,0x200,0x100); - f.engine.flights.push(Flight{computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); f.engine.target[0]=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),Ok(())); @@ -135,7 +141,7 @@ def function(text,name): } #[test]fn stuck_compute_times_out_while_render_keeps_advancing_and_retiring(){ let mut f=firmware(false,0x200,0x100); - f.engine.flights.push(Flight{computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); + f.engine.flights.push(Flight{job:Job{long:false},computes:0,compute_pipe:0,renders:1,target:0,ta_target:0x300,fs_target:0x300,published_ns:2}); f.engine.ta_target=0x300;f.engine.fs_target=0x300; let mut done=(); assert_eq!(f.check_hangs(&mut done),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 269925c85b0005..310c27495708a3 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -95,6 +95,7 @@ def item(declaration): __PUBLICATION_ERROR__ #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool } +impl ComputeCommand { fn is_rt(&self) -> bool { false } } #[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 } @@ -117,7 +118,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)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -128,8 +129,8 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,doomed:false,recovery_suspect:false,initbm:false}}} struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ @@ -162,11 +163,13 @@ def item(declaration): fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} - fn exhausted_for_mask(&self,vm:&Vm,_mask:u32,_home:usize)->bool{self.exhausted_for(vm)} + fn exhausted_for_within_mode(&self,vm:&Vm,limit:usize,_scs:bool)->bool{self.exhausted_for_within(vm,limit)} + fn exhausted_for_mask_mode(&self,vm:&Vm,_mask:u32,_home:usize,_scs:bool)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} - fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -727,7 +730,7 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -746,7 +749,8 @@ def item(declaration): fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} - fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks_mode(&self,vm:&Arc,limit:usize,min_blocks:u32,_scs:bool)->bool{self.can_pipeline_within_blocks(vm,limit,min_blocks)} + fn can_pipeline_in_mask_blocks_mode(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32,_scs:bool)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { @@ -806,7 +810,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -852,7 +856,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -870,7 +874,7 @@ def item(declaration): }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -894,7 +898,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -938,7 +942,7 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; @@ -983,8 +987,8 @@ def item(declaration): let p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1020,7 +1024,7 @@ def item(declaration): let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1053,7 +1057,7 @@ def item(declaration): let host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1099,7 +1103,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1110,7 +1114,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1137,7 +1141,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1177,7 +1181,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1192,7 +1196,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1214,7 +1218,7 @@ def item(declaration): let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1247,7 +1251,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:4,ta_target:0x400,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1292,7 +1296,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1638,27 +1642,29 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); host.engine.flights.push(QueueBehindFlight{ - job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. + assert_eq!(host.choose_compute_pipe([None, None], 24, true), 0); // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 2), 0); + assert_eq!(host.choose_compute_pipe([None, None], 2, false), 0); assert!(host.can_queue_behind(&c2)); // Add second concurrent flight on pipe 1: both pipes active, // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. host.engine.flights.push(QueueBehindFlight{ - job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,target:0x100, + job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], 24), 1); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], 24), 0); + assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1681,12 +1687,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,target:0x200, + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,target:0x200, cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1699,13 +1705,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, 24), 0); + assert_eq!(host.choose_compute_pipe(w1, 24, false), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, 24), 0); + assert_eq!(host.choose_compute_pipe(w2, 24, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1716,7 +1722,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, 24), 0); + assert_eq!(host.choose_compute_pipe(w2_ooo, 24, false), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1760,12 +1766,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1776,7 +1782,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,24),0); + assert_eq!(host.choose_compute_pipe(cw,24,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py new file mode 100644 index 00000000000000..3b5c3dca9299d7 --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -0,0 +1,587 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host-check the G16G ray-tracing command set (RENDER_RAY_QUERY, BOUNDED_AS_BUILD). + +Compiles the production g16/rt.rs, recovery/logic.rs and the TA/FS/compute encoders, plus the +command admission and engine conversion functions copied verbatim from command.rs and +engine.rs, against CPU-only stand-ins. No GPU, firmware or Mesa is involved. + +Failure modes this guards against (written before the code): + + 1. A non-RT command changes bytes: the engine's conversion of an empty ray state is not the + disabled word set, or the disabled set differs from the words G16G always wrote (the frozen + golden fixtures then cover the rest). + 2. RT words land in the wrong register record, the register counts change, a gated register + (0x1a141, render 0x017d9) is written while its gate is off, or a ray-query compute item is + not bracketed by 0x017e1 = 1 first and 0x017d9 = 1 last, or its tail is not 0x2c, as macOS + 27.2 writes them on the J773g. + 3. The fragment window word loses bit 9; a render stage's tail word takes the auxiliary + intersection word (the M4 Pro's render programs use the scratch tail). + 4. SCS sizing differs from the M4 Pro's formula ((pages + pages/256 + 8) x cores pages), is not + rounded to whole 2-MiB rows, overflows silently, or admits a pool whose pages and freelist do + not fit an SCS pool window (E2BIG); zero cores is accepted. + 5. A render whose scratch exceeds its queue's reservation is accepted, or one within it + refused; an unmapped intersection pool or default program is accepted. + 6. The long allowance misses a ray/AS-build job, applies to plain work, re-enables a disabled + (zero) deadline, or shortens a deadline already longer than 10 s. + 7. A compute flag other than AS_BUILD is accepted; scratch alone counts as ray traversal. + 8. The feature word loses a bit or gains another than RENDER_RAY_QUERY and BOUNDED_AS_BUILD. + 9. A UMA manager image or compute descriptor reports seeds that are not whole rows inside the + freelist, a freelist (+0x1c) that does not hold its pool or is smaller than a base one, an + SCS pool's freelist other than macOS's 0x80000 records, or row words (+0x48) other than 8 + per valid row. +10. Mesa's G16G ray-query commands (layout 0x0130000060010070 on 10 cores, compute and either or + both render stages, and their QUEUE_CREATE reservations) are refused, which Mesa reports as + VK_ERROR_DEVICE_LOST; the render pools a queue creates cannot take a queue that later + reserves the other stage too; or a compute pool is created for fewer than two dispatches + where a window holds two. +""" +from common import kernel_root, output_dir, rustc, flat_bindings +import hashlib +import json +import os +import pathlib +import re +import shlex +import subprocess +import tempfile + +ROOT = kernel_root() +OUT = output_dir() +BACKEND = ROOT / 'drivers/gpu/drm/asahi/g16' +FLAT = flat_bindings() + + +def function(text, name): + marker = text.index('fn ' + name + '(') + start = text.rfind('\n', 0, marker) + 1 + at = text.index('{', marker) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def block(text, declaration): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +command = (BACKEND / 'command.rs').read_text() +engine = (BACKEND / 'engine.rs').read_text() +admission = '\n'.join(function(command, name) for name in + ['check_intersection', 'check_render_ray', 'check_compute_ray']) +conversion = '\n'.join(function(engine, name) for name in ['compute_rt', 'stage_rt']) +# The client address map, which bounds SCS pools (SCS_POOL_WINDOW). +client = block((BACKEND / 'hw.rs').read_text(), 'pub(crate) mod client {') +long = block(command, 'impl Command {') +for text in ('admission', 'conversion', 'long'): + globals()[text] = globals()[text].replace('super::rt::', 'rt::') + +# The feature word: the bits params.rs adds, from the real header, plus the shared +# VM_STATUS and VM_STATUS_MIRROR of file.rs. +params = (BACKEND / 'params.rs').read_text() +statement = params[params.index('params.features |='):] +statement = statement[:statement.index(';')] +names = re.findall(r'drm_asahi_feature_(DRM_ASAHI_FEATURE_\w+)', statement) +with tempfile.TemporaryDirectory(prefix='m4-rt-features-') as name: + directory = pathlib.Path(name) + source = directory / 'features.c' + header = ROOT / 'include/uapi/drm/asahi_drm.h' + source.write_text('#include \n#include ' + json.dumps(str(header)) + '\nint main(void){printf("%#llx\\n",' + '(unsigned long long)(' + ' | '.join(names + ['DRM_ASAHI_FEATURE_VM_STATUS', + 'DRM_ASAHI_FEATURE_VM_STATUS_MIRROR']) + '));return 0;}\n') + binary = directory / 'features' + subprocess.run(shlex.split(os.environ.get('CC', 'cc')) + ['-std=gnu11', '-Wall', '-Werror', '-D__user=', + '-idirafter', str(header.parents[1]), str(source), '-o', str(binary)], check=True) + features = int(subprocess.run([str(binary)], check=True, capture_output=True, text=True).stdout, 16) +assert features == 0x4001fc02, hex(features) +assert sorted(names) == sorted(['DRM_ASAHI_FEATURE_PER_COMMAND_INPUT_SYNCS', 'DRM_ASAHI_FEATURE_EXACT_PRIOR_BARRIERS', + 'DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS', 'DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS', + 'DRM_ASAHI_FEATURE_FEW_PRIMITIVES', 'DRM_ASAHI_FEATURE_RENDER_RAY_QUERY', + 'DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD']), names +print(f'feature word {features:#x} (RENDER_RAY_QUERY | BOUNDED_AS_BUILD added to G16G features)') + +harness = r''' +#![allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_imports)] +extern crate self as kernel; +pub mod prelude { + pub type Result = core::result::Result; + pub const EINVAL: i32 = -22; pub const E2BIG: i32 = -7; pub const EOVERFLOW: i32 = -75; +} +use prelude::*; +const ENOENT: i32 = -2; +mod uapi { include!("@FLAT@"); } +mod hw { + pub mod engine { pub const COMPUTE_SEED: u32 = 0x100; } + pub mod sizes { pub const BASE_RENDER_SLOTS: usize = 2; } + @CLIENT@ +} +mod fw { + #[path = "@BACKEND@/fw/graph.rs"] pub mod graph; + #[path = "@BACKEND@/fw/work.rs"] pub mod work; +} +#[path = "@BACKEND@/encode.rs"] mod encode; +#[path = "@BACKEND@/rt.rs"] mod rt; +#[path = "@BACKEND@/recovery/logic.rs"] mod logic; +use encode::{ComputeRt, StageRt}; +use fw::work::{compute, fs, ta}; + +mod mmu { pub struct Vm { pub mapped: Vec<(u64, u64)> } } +/// Readable mappings only; the production span rules have their own tests. +fn cover(vm: &mmu::Vm, start: u64, end: u64, _read: bool, _write: bool) -> Result { + if vm.mapped.iter().any(|&(a, b)| a <= start && end <= b) { Ok(()) } else { Err(ENOENT) } +} +struct SpanBatch; +impl SpanBatch { + fn push(&mut self, vm: &mmu::Vm, start: u64, end: u64, read: bool, write: bool) -> Result { + cover(vm, start, end, read, write) + } +} +struct Context<'a> { vm: &'a mmu::Vm, usc_base: u64, active_cores: u32, render_scs: [u16; 2] } +@ADMISSION@ +@CONVERSION@ +type KBox = Box; +struct RenderCommand { ray_query: [rt::RayQueryStage; 2], scs: rt::ScsSeeds } +struct ComputeCommand { ray: rt::ComputeRay, scs: rt::ScsSeeds, as_build: bool } +enum Command { Render(KBox), Compute(KBox) } +@LONG@ + +// Mesa's three T1 layouts: depth 112, 96 cliques, driver 40, 88 and 304 bytes. +const LAYOUTS: [(u64, u16); 3] = [(0x0028000060000070, 791), (0x0058000060010070, 827), (0x0130000060010070, 989)]; +const POOL: u64 = 0x10000; +fn tables() -> rt::IntersectionTables { + rt::IntersectionTables::new(POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn ray(layout: u64) -> rt::ComputeRay { + rt::ComputeRay::new(layout, 0, 0, POOL, 0x4000, 1, 112, 0x10010020000, 0x16000000000).unwrap() +} +fn stage(layout: u64) -> rt::RayQueryStage { + rt::RayQueryStage { intersection: tables(), scratch: rt::ScratchRequest::new(layout).unwrap() } +} +fn records(w: &[u8], at: usize, count: usize) -> Vec<(u32, u64)> { + (0..count).map(|i| { + let r = &w[at + i * 12..at + i * 12 + 12]; + (u32::from_le_bytes(r[..4].try_into().unwrap()), u64::from_le_bytes(r[4..].try_into().unwrap())) + }).collect() +} +fn u16_at(w: &[u8], at: usize) -> usize { u16::from_le_bytes([w[at], w[at + 1]]) as usize } +fn u32_at(w: &[u8], at: usize) -> u32 { u32::from_le_bytes(w[at..at + 4].try_into().unwrap()) } + +#[test] +fn empty_ray_state_converts_to_the_words_g16g_always_wrote() { + assert_eq!(compute_rt(&rt::ComputeRay::NONE, 8192), ComputeRt::DISABLED); + assert_eq!(stage_rt(&rt::RayQueryStage::NONE), StageRt::DISABLED); + // Payload-free layouts and table-less commands are the same empty state. + let quiet = rt::ComputeRay::new(0x0000_0000_6000_0070, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + assert_eq!(compute_rt(&quiet, 8192), ComputeRt::DISABLED); + assert_eq!(StageRt::DISABLED.window | 1 << 9, 0xff0200); + assert!(!encode::compute_encoder_gate()); +} + +fn compute_refs() -> encode::ComputeRefs { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + 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 + 0x1008c0, 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: 1, + uma_slot: 1, event: compute::EVENT, command_id: 1, compute_index: 0, work_818: 0, target_stamp: 0x100, submitted: 1, + } +} + +fn encode_compute(layout: &compute::Layout, rt_words: &ComputeRt) -> core::result::Result<[u8; compute::WORK_SIZE], encode::ComputeEncodeError> { + let c = uapi::drm_asahi_cmd_compute { cdm_ctrl_stream_base: 0x1000300000, cdm_ctrl_stream_end: 0x1000300200, ..Default::default() }; + let mut w = [0xa5; compute::WORK_SIZE]; let mut q = [0xa5; compute::SEQ_SIZE]; + encode::encode_compute_rt(layout, &compute_refs(), &c, &[], &[0; 2], 1, 1, 1, rt_words, &mut w, &mut q)?; + Ok(w) +} + +#[test] +fn compute_rt_words_land_in_the_25f84_register_slots_only() { + for layout in [&compute::V25G83, &compute::V26B123] { + let plain = encode_compute(layout, &ComputeRt::DISABLED).unwrap(); + assert_eq!(u16_at(&plain, 0x728), 25); + let plain_regs = records(&plain, compute::REGS, 25); + let d = compute::DESCRIPTOR; + // A base unit's descriptor: 16384 records, 8192 seeds, 16 rows x 8. + assert_eq!((u32_at(&plain, d + 0x1c), u32_at(&plain, d + 0x24), u32_at(&plain, d + 0x2c), u32_at(&plain, d + 0x48)), + (16384, 8192, 8192, 128)); + for (layout_word, pages) in LAYOUTS { + let words = compute_rt(&ray(layout_word), 28672); + let w = encode_compute(layout, &words).unwrap(); + // macOS 27.2 on the J773g: 0x017e1 = 1 first, 0x017d9 = 1 last. + assert_eq!((u16_at(&w, 0x728), u16_at(&w, 0x72a)), (27, 27 * 12)); + let got = records(&w, compute::REGS, 27); + assert_eq!((got[0], got[26]), ((0x017e1, 1), (0x017d9, 1))); + assert!(got.iter().all(|&(sel, _)| sel != 0x1a141), "gated register"); + let expect = |sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let mib = u64::from(pages).div_ceil(256); + assert_eq!(expect(0x101d1), u64::from(pages) | mib << 16); + assert_eq!((expect(0xd479), expect(0x1a0e9), expect(0x107a1)), (0x2c, 112, 1 << 24 | 0x60 << 16)); + assert_eq!([expect(0x1a089), expect(0x1a091), expect(0x1a059), expect(0x1a061), expect(0x1a0b9), expect(0x1a0c1)], + [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]); + // An SCS pool's descriptor: the 0x80000-record freelist, 56 rows x 8. + assert_eq!((u32_at(&w, d + 0x1c), u32_at(&w, d + 0x24), u32_at(&w, d + 0x2c), u32_at(&w, d + 0x48)), + (0x80000, 28672, 28672, 448)); + // Between the two records the list is the plain one, only the ten RT words differ. + let rt_sels = [0x1a089, 0x1a091, 0x1a059, 0x1a061, 0x1a0b9, 0x1a0c1, 0x101d1, 0xd479, 0x1a0e9, 0x107a1]; + for (&(sel, value), &(plain_sel, plain_value)) in got[1..26].iter().zip(plain_regs.iter()) { + assert_eq!(sel, plain_sel); + assert!(value == plain_value || rt_sels.contains(&sel), "{sel:#x}"); + } + // Nothing else moves: the register list, its count and the pool's descriptor words. + let regs = compute::REGS..compute::REGS + 27 * 12; + let pool_words = [0x1c, 0x24, 0x2c, 0x48]; + for (i, (a, b)) in plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) + || pool_words.iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); + } + } + } + // Seeds are whole rows within the freelist, which is never smaller than a base one. + for seeds in [0, 8191, 8704 + 64, 16896] { + let words = ComputeRt { seeds, ..ComputeRt::DISABLED }; + assert!(encode_compute(layout, &words).is_err(), "seeds {seeds}"); + } + assert!(encode_compute(layout, &ComputeRt { seeds: 8704, ..ComputeRt::DISABLED }).is_ok()); + assert!(encode_compute(layout, &ComputeRt { seeds: 8192, records: 8192, ..ComputeRt::DISABLED }).is_err()); + // The pool's size moves only its seed counts and row words. + let small = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), 18432)).unwrap(); + let large = encode_compute(layout, &compute_rt(&ray(LAYOUTS[2].0), rt::MAX_SCS_SEEDS)).unwrap(); + assert_eq!((u32_at(&small, d + 0x1c), u32_at(&small, d + 0x2c), u32_at(&small, d + 0x48)), (0x80000, 18432, 288)); + assert_eq!((u32_at(&large, d + 0x1c), u32_at(&large, d + 0x2c), u32_at(&large, d + 0x48)), (0x80000, 31744, 496)); + for (i, (a, b)) in small.iter().zip(large.iter()).enumerate() { + if a != b { assert!([0x24, 0x2c, 0x48].iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); } + } + } +} + +fn render_refs() -> (encode::RenderRefs, encode::PassRefs, uapi::drm_asahi_cmd_render) { + let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 64; u.height_px = 64; u.layers = 1; u.samples = 1; u.utile_width_px = 32; u.utile_height_px = 32; + u.sample_size_B = 4; u.vdm_ctrl_stream_base = g + 0xa00000; u.isp_scissor_base = g + 0xb00000; + 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; 2], uma_aux: [f + 0x300100, f + 0x300200], + uma_gpu: g + 0x6000000, pb_mgr: f + 0x3000000, scene_list: g + 0x500000, parameter_id: 1, generation: 1, + activity: [f + 0x900004, f + 0xa00008], counter: [2, 1], uma_submitted: 2, uuid: 0x123400, 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() + }; + (r, p, u) +} + +#[test] +fn render_stage_words_land_in_the_ta_and_fs_register_slots_only() { + let (r, p, u) = render_refs(); + let geo = encode::Geometry::new(&u, p.heap_gva); + let ta_rt = |words: &StageRt, layout: &ta::Layout| { + let mut w = [0xa5; ta::WORK_SIZE]; let mut q = [0xa5; ta::SEQ_SIZE]; + encode::encode_ta_rt(layout, &r, &p, &u, &[0; 4], 1, 0x100, &geo, None, words, &mut w, &mut q); (w, q) + }; + let fs_rt = |words: &StageRt, layout: &fs::Layout| { + let mut w = [0xa5; fs::WORK_SIZE]; let mut q = [0xa5u8; fs::SEQ_SIZE]; + encode::encode_fs_rt(layout, &r, &p, &u, &[0; 4], 1, 1 << 40, 1, 0x100, &geo, words, &mut w, &mut q); (w, q) + }; + for (tl, fl) in [(&ta::V25G83, &fs::V25G83), (&ta::V26B123, &fs::V26B123)] { + let (ta_plain, taq_plain) = ta_rt(&StageRt::DISABLED, tl); + let (fs_plain, fsq_plain) = fs_rt(&StageRt::DISABLED, fl); + for (layout_word, pages) in LAYOUTS { + let mut s = stage(layout_word); + // The auxiliary word is validated, not written: the tail stays the scratch tail. + let mut wire = [0u8; 48]; + wire[0..4].copy_from_slice(&16u32.to_le_bytes()); + wire[8..16].copy_from_slice(&POOL.to_le_bytes()); wire[16..24].copy_from_slice(&0x4000u64.to_le_bytes()); + wire[24..28].copy_from_slice(&1u32.to_le_bytes()); wire[28..32].copy_from_slice(&112u32.to_le_bytes()); + wire[32..40].copy_from_slice(&0x10010020000u64.to_le_bytes()); wire[40..48].copy_from_slice(&0x16000000000u64.to_le_bytes()); + s.intersection = rt::IntersectionTables::parse(&wire).unwrap(); + let words = stage_rt(&s); + let size = u64::from(pages) | u64::from(pages).div_ceil(256) << 16; + let window = 1 << 24 | 0x60 << 16; + let ift = [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]; + let (w, q) = ta_rt(&words, tl); + assert_eq!(q, taq_plain); + assert_eq!((u16_at(&w, 0x748), u16_at(&w, 0x74a)), (68, 68 * 12)); + let ta_plain_regs = records(&ta_plain, ta::REGS, 66); + let got = records(&w, ta::REGS, 68); + assert_eq!((got[0], got[67]), ((0x017e1, 1), (0x017d9, 1))); + let value = |got: &Vec<(u32, u64)>, sel: u32| got.iter().find(|r| r.0 == sel).unwrap().1; + let ta_rt_sels = [0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799]; + assert_eq!([0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, 0x1a0d1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c9, 0xd471, 0x1a0f1, 0x10799].map(|s| value(&got, s)), [size, 0x2c, 112, window]); + for (&(sel, val), &(psel, pval)) in got[1..67].iter().zip(ta_plain_regs.iter()) { + assert_eq!(sel, psel); + assert!(val == pval || ta_rt_sels.contains(&sel), "TA {sel:#x}"); + } + for (i, (a, b)) in ta_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((ta::REGS..ta::REGS + 68 * 12).contains(&i) || (0x748..0x74c).contains(&i), "TA byte {i:#x}"); + } + } + let (w, q) = fs_rt(&words, fl); + assert_eq!(q, fsq_plain); + assert_eq!((u16_at(&w, 0x788), u16_at(&w, 0x78a)), (84, 84 * 12)); + let fs_plain_regs = records(&fs_plain, fs::REGS, 82); + let got = records(&w, fs::REGS, 84); + assert_eq!((got[0].0, got[1], got[83]), (0x1739, (0x017e1, 1), (0x017d9, 1))); + let fs_rt_sels = [0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x10791]; + assert_eq!([0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, 0x1a0d9, 0x1a0e1].map(|s| value(&got, s)), ift); + assert_eq!([0x101c1, 0xd469, 0x1a0f9, 0x10791].map(|s| value(&got, s)), [size, 0x2c, 112, window | 1 << 9]); + assert_eq!(got[0], fs_plain_regs[0]); + for (&(sel, val), &(psel, pval)) in got[2..83].iter().zip(fs_plain_regs[1..].iter()) { + assert_eq!(sel, psel); + assert!(val == pval || fs_rt_sels.contains(&sel), "FS {sel:#x}"); + } + for (i, (a, b)) in fs_plain.iter().zip(w.iter()).enumerate() { + if a != b { + assert!((fs::REGS..fs::REGS + 84 * 12).contains(&i) || (0x788..0x78c).contains(&i), "FS byte {i:#x}"); + } + } + } + } +} + +#[test] +fn scratch_requests_follow_the_gen1_section_model() { + for (layout, pages) in LAYOUTS { + let s = rt::ScratchRequest::new(layout).unwrap(); + assert_eq!(s.pages(), pages); + assert_eq!((s.tail_word(), s.stack_word(), s.window_word(), s.driver_word()), (0x2c, 112, 0x1600000, 0)); + // Both compute and render stages use macOS 27.2's J773g 0x2c tail reservation. + assert_eq!(s.compute_tail_word(), 0x2c); + } + assert_eq!(rt::ScratchRequest::NONE.compute_tail_word(), 0); + // Payload-free: no scratch even with depth and cliques. + assert_eq!(rt::ScratchRequest::new(0x0000_0000_ff00_ffff).unwrap(), rt::ScratchRequest::NONE); + // The smallest request is Apple's 89-page floor plus the guard page. + assert_eq!(rt::ScratchRequest::new(1 << 32).unwrap().pages(), 89); + // More than 2^16 pages, and a stack word that overflows, are refused. + assert_eq!(rt::ScratchRequest::new(0xffff_0000_ff00_ffff), Err(EINVAL)); + assert_eq!(rt::ScratchRequest::new(0x0000_ffff_ff00_0000), Err(EINVAL)); +} + +#[test] +fn scs_sizing_is_the_m4_pro_formula_in_whole_rows() { + // Per core: pages + ceil(pages / 256) + 8. + assert_eq!(rt::extra_pages(10, 791), Ok(10 * (791 + 4 + 8))); + assert_eq!(rt::extra_pages(10, 256), Ok(10 * (256 + 1 + 8))); + assert_eq!(rt::extra_pages(10, 257), Ok(10 * (257 + 2 + 8))); + assert_eq!(rt::extra_pages(10, 0), Ok(0)); + assert_eq!(rt::extra_pages(0, 791), Err(EINVAL)); + assert_eq!(rt::required_seeds(10, &[]), Ok(8192)); + assert_eq!(rt::required_seeds(10, &[0, 0]), Ok(8192)); + // Mesa's three T1 layouts on a 10-core M4: base 8192 + 10 x (pages + pages/256 + 8). + assert_eq!(rt::required_seeds(10, &[791]), Ok(16384)); + assert_eq!(rt::required_seeds(10, &[827]), Ok(16896)); + assert_eq!(rt::required_seeds(10, &[989]), Ok(18432)); + assert_eq!(rt::required_seeds(8, &[827]), Ok(15360)); + assert_eq!(rt::required_seeds(1, &[89]), Ok(8704)); + // Both stages of one render add up. + assert_eq!(rt::required_seeds(10, &[89, 89]), Ok(8192 + 2048)); + assert_eq!(rt::required_seeds(10, &[791, 89]), Ok(17408)); + assert_eq!(rt::required_seeds(10, &[989, 989]), Ok(28672)); + // Freelists: a base pool keeps 16384 records over 0x20000 bytes; an SCS pool gets the + // 0x80000 records over 4 MiB that macOS 27.2 writes on the J773g. + assert_eq!((rt::freelist_records(8192), rt::freelist_bytes(8192)), (16384, 0x20000)); + for seeds in [8704, 16384, 28672, rt::MAX_SCS_SEEDS] { + assert_eq!((rt::freelist_records(seeds), rt::freelist_bytes(seeds)), (0x80000, 0x400000)); + } + // The largest pool: 62 2-MiB rows, whose 124 MiB and 4-MiB freelist fill a 128 MiB window + // (63 rows and their freelist would not). + assert_eq!(rt::MAX_SCS_SEEDS, 62 * 512); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS) <= hw::client::SCS_POOL_WINDOW); + assert!(rt::window_bytes(rt::MAX_SCS_SEEDS + 512) > hw::client::SCS_POOL_WINDOW); + assert_eq!(rt::required_seeds(10, &[2337]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[2338]), Err(E2BIG)); + assert_eq!(rt::required_seeds(10, &[1164, 1164]), Ok(31744)); + assert_eq!(rt::required_seeds(10, &[1165, 1165]), Err(E2BIG)); + // Pools are created for two stages at the larger request, or the request if two do not fit. + assert_eq!(rt::pool_seeds(10, [791, 0]), Ok(24576)); + assert_eq!(rt::pool_seeds(10, [827, 0]), Ok(25088)); + assert_eq!(rt::pool_seeds(10, [0, 989]), rt::required_seeds(10, &[989, 989])); + assert_eq!(rt::pool_seeds(10, [2000, 0]), rt::required_seeds(10, &[2000])); + assert_eq!(rt::pool_seeds(10, [2338, 0]), Err(E2BIG)); + assert_eq!(rt::pool_seeds(10, [0, 0]), Ok(8192)); + // Extremes: refused, never wrapped (overflow checks are on). + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX, u16::MAX]), Err(E2BIG)); + assert_eq!(rt::required_seeds(u32::MAX, &[u16::MAX; 64]), Err(E2BIG)); + assert_eq!(rt::required_seeds(0, &[1]), Err(EINVAL)); + for cores in 1..=10 { for pages in [89u16, 200, 500, 791, 1000] { + if let Ok(seeds) = rt::required_seeds(cores, &[pages]) { + assert_eq!(seeds % rt::SEEDS_PER_ROW, 0); + assert!(u64::from(seeds) >= 8192 + rt::extra_pages(cores, pages).unwrap() && seeds <= rt::MAX_SCS_SEEDS); + } + }} +} + +#[test] +fn ray_and_as_build_admission() { + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [791, 0] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Admission returns the pool the command needs, and the one created for it: compute for two + // dispatches. + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[0].0)), Ok(scs(16384, 24576))); + assert_eq!(check_compute_ray(&mut b, &context, &ray(LAYOUTS[1].0)), Ok(scs(16896, 25088))); + // 4 KiB of driver bytes per thread: 3833 pages per core, more than a window holds. + let huge = 0x1000_0000_6000_0070; + assert_eq!(rt::ScratchRequest::new(huge).unwrap().pages(), 3833); + assert_eq!(check_compute_ray(&mut b, &context, &ray(huge)), Err(E2BIG)); + let unmapped = mmu::Vm { mapped: vec![(POOL, POOL + 0x3000), (0x10010020000, 0x10010020040)] }; + let narrow = Context { vm: &unmapped, ..context }; + assert_eq!(check_compute_ray(&mut b, &narrow, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let no_program = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &ray(LAYOUTS[0].0)), Err(ENOENT)); + let tables_only = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &Context { vm: &no_program, ..context }, &tables_only), Ok(rt::ScsSeeds::NONE)); + // Renders: within the queue's reservation, either stage; beyond it EINVAL. The pool created + // for them holds two stages of the reservation's larger one. + let none = rt::RayQueryStage::NONE; + let small = stage(1 << 32 | 0x6000_0000); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[0].0), none]), Ok(scs(16384, 24576))); + assert_eq!(check_render_ray(&mut b, &context, &[none, small]), Ok(scs(9216, 24576))); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, small]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [89, 89], ..context }, &[small, small]), Ok(scs(10240, 10240))); + assert_eq!(check_render_ray(&mut b, &context, &[stage(LAYOUTS[1].0), none]), Err(EINVAL)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [3833, 0], ..context }, &[stage(huge), none]), Err(E2BIG)); + assert_eq!(check_render_ray(&mut b, &Context { vm: &unmapped, ..context }, &[stage(LAYOUTS[0].0), none]), Err(ENOENT)); + assert_eq!(check_render_ray(&mut b, &Context { render_scs: [0, 0], ..context }, &[none, none]), Ok(rt::ScsSeeds::NONE)); + // Flags: AS_BUILD alone. + assert_eq!(rt::as_build(0), Some(false)); assert_eq!(rt::as_build(4), Some(true)); + for flag in [1, 2, 8, 1 << 16, 1 << 17, 1 << 20, 5, 6] { assert_eq!(rt::as_build(flag), None); } +} + +// The commands Mesa's G16G ray-query path (ASAHI_MESA_DEBUG=g16grt, mesa 3ff3d359) submits on a +// 10-core M4: hk_gen1_ray_query_scs_layout() is 0x0130000060010070 with the candidate profile, +// the intersection pool is one 16-KiB IFT (first 1, count 112), the default program +// 0x10010020000 with control 0x16000000000. dEQP-VK.ray_query.* compute, chit/ahit and +// dynamic-indexing cases submit the compute shape; .vert/.frag/.tesc cases reserve the render +// stage at QUEUE_CREATE (hk_queue_ensure_drm) and submit a render with it. Before SCS pools were +// sized from the request, every one of them was refused with E2BIG, which Mesa reports as +// VK_ERROR_DEVICE_LOST at vkQueueSubmit. +#[test] +fn mesa_g16grt_ray_query_commands_are_admitted() { + let mesa = LAYOUTS[2].0; + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000), (0x10010020000, 0x10010020040)] }; + let pages = rt::ScratchRequest::new(mesa).unwrap().pages(); + assert_eq!(pages, 989); + // QUEUE_CREATE render_scs_layout: the vertex stage, the fragment stage, or both. The VM's + // SCS render pools a queue creates hold both stages, so a queue Mesa replaces to add the + // other stage still fits them. + for reservation in [[pages, 0], [0, pages], [pages, pages]] { + assert!(rt::required_seeds(10, &reservation).is_ok(), "QUEUE_CREATE {reservation:?}"); + assert_eq!(rt::pool_seeds(10, reservation), Ok(28672), "{reservation:?}"); + } + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [pages, pages] }; + let scs = |needed, pool| rt::ScsSeeds { needed, pool }; + let mut b = SpanBatch; + // Compute: 18432 for one dispatch, a 56-row pool for two. + assert_eq!(check_compute_ray(&mut b, &context, &ray(mesa)), Ok(scs(18432, 28672))); + let none = rt::RayQueryStage::NONE; + for (stages, needed) in [([stage(mesa), none], 18432), ([none, stage(mesa)], 18432), ([stage(mesa), stage(mesa)], 28672)] { + assert_eq!(check_render_ray(&mut b, &context, &stages), Ok(scs(needed, 28672))); + // A queue that reserved one stage creates pools that take both. + let one = Context { render_scs: [pages, 0], ..context }; + assert_eq!(check_render_ray(&mut b, &one, &[stage(mesa), none]).map(|s| s.pool), Ok(28672)); + } + // Their pools fit an SCS window, freelist included. + assert_eq!(rt::freelist_records(28672), 0x80000); + assert!(rt::window_bytes(28672) <= hw::client::SCS_POOL_WINDOW); +} + +#[test] +fn long_allowance_follows_g17_select_per_job() { + let render = |stages: [rt::RayQueryStage; 2]| Command::Render(Box::new(RenderCommand { ray_query: stages, scs: rt::ScsSeeds::NONE })); + let compute = |ray: rt::ComputeRay, as_build: bool| Command::Compute(Box::new(ComputeCommand { ray, scs: rt::ScsSeeds::NONE, as_build })); + let none = rt::RayQueryStage::NONE; + assert!(render([stage(LAYOUTS[0].0), none]).long() && render([none, stage(LAYOUTS[0].0)]).long()); + assert!(!render([none, none]).long() && render([none, none]).scs() == rt::ScsSeeds::NONE); + assert!(compute(ray(LAYOUTS[0].0), false).long() && compute(rt::ComputeRay::NONE, true).long()); + assert!(!compute(rt::ComputeRay::NONE, false).long()); + // Scratch alone is not traversal (as on the M4 Pro), but it needs an SCS pool; tables + // alone do not. + let scratch = rt::ComputeRay::new(LAYOUTS[0].0, 0, 0, 0, 0, 0, 0, 0, 0).unwrap(); + let vm = mmu::Vm { mapped: vec![(POOL, POOL + 0x4000)] }; + let context = Context { vm: &vm, usc_base: 0, active_cores: 10, render_scs: [0, 0] }; + let admitted = rt::ScsSeeds { needed: 16384, pool: 24576 }; + let mut b = SpanBatch; + assert!(!compute(scratch, false).long() && check_compute_ray(&mut b, &context, &scratch) == Ok(admitted)); + let tables = rt::ComputeRay::new(0, 0, 0, POOL, 0x4000, 1, 112, 0, 0).unwrap(); + assert_eq!(check_compute_ray(&mut b, &context, &tables), Ok(rt::ScsSeeds::NONE)); + // A command's SCS pool is what admission recorded. + let command = Command::Compute(Box::new(ComputeCommand { ray: scratch, scs: admitted, as_build: false })); + assert_eq!((command.scs(), compute(rt::ComputeRay::NONE, false).scs()), (admitted, rt::ScsSeeds::NONE)); + // Deadlines: at least ten seconds for a long job, never re-enabling a disabled one. + assert_eq!(logic::long_deadline_ms(5000), 10_000); + assert_eq!(logic::long_deadline_ms(10_000), 10_000); + assert_eq!(logic::long_deadline_ms(30_000), 30_000); + assert_eq!(logic::long_deadline_ms(0), 0); + assert_eq!(logic::long_deadline_ms(1), 10_000); + let now = 1_000_000_000; + let d = logic::Deadlines::renew(now, 5000, 5000); + assert_eq!((d.select(false, false), d.select(true, false)), (now + 5_000_000_000, now + 5_000_000_000)); + assert_eq!((d.select(false, true), d.select(true, true)), (now + 10_000_000_000, now + 10_000_000_000)); + let d = logic::Deadlines::renew(now, 5000, 0); + assert_eq!((d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX)); + assert_eq!(d.select(false, true), now + 10_000_000_000); + let d = logic::Deadlines::renew(u64::MAX - 1, 20_000, 50); + assert_eq!((d.select(false, true), d.select(true, false), d.select(true, true)), (u64::MAX, u64::MAX, u64::MAX)); + let d = logic::Deadlines::renew(now, 50, 50); + assert_eq!((d.select(false, false), d.select(true, true)), (now + 100_000_000, now + 10_000_000_000)); + assert_eq!(logic::Deadlines::EXPIRED.select(true, true), logic::EXPIRED); +} +''' +encode_source = (BACKEND / 'encode.rs').read_text() +# The compute encoder's gates, visible to this harness only through a tiny accessor. +gates = '\npub(crate) fn compute_encoder_gate() -> bool { compute_encoder::COMPUTE_SCS_DRIVER_WORD }\n' \ + 'pub(crate) fn render_encoder_gate() -> bool { render_encoder::RENDER_SCS_ENABLE }\n' +with tempfile.TemporaryDirectory(prefix='m4-rust-rt-') as name: + directory = pathlib.Path(name) + staged = directory / 'g16' + staged.mkdir() + # Stage the encoder with the gate accessors appended; the other modules come from the tree. + (staged / 'encode').mkdir() + for part in ['compute.rs', 'render.rs']: + (staged / 'encode' / part).write_text((BACKEND / 'encode' / part).read_text()) + (staged / 'encode.rs').write_text(encode_source + gates) + source = harness + for key, value in {'@FLAT@': str(FLAT), '@ADMISSION@': admission, '@CONVERSION@': conversion, + '@LONG@': long, '@CLIENT@': client}.items(): + source = source.replace(key, value) + source = source.replace('#[path = "@BACKEND@/encode.rs"]', '#[path = "' + str(staged / 'encode.rs') + '"]') + source = source.replace('@BACKEND@', str(BACKEND)) + source += '\n#[test] fn render_gate_is_on() { assert!(encode::render_encoder_gate()); }\n' + test = directory / 'test.rs' + test.write_text(source) + (OUT / 'ray-tracing-host.rs').write_text(source) + binary = directory / 'test' + subprocess.run(rustc() + ['--edition=2021', '-C', 'overflow-checks=yes', '--test', str(test), '-o', str(binary)], check=True) + result = subprocess.run([str(binary), '--nocapture'], text=True, capture_output=True) + print(result.stdout + result.stderr, end='') + (OUT / 'ray-tracing-host.log').write_text(result.stdout + result.stderr) + result.check_returncode() + tests = int(re.search(r'test result: ok\. (\d+) passed;', result.stdout)[1]) +(OUT / 'ray-tracing-host.json').write_text(json.dumps({ + 'result': 'pass', 'tests': tests, 'feature_word': hex(features), + 'scope': 'Production rt.rs, recovery/logic.rs and TA/FS/compute encoders, with command.rs admission and ' + 'engine.rs conversion copied verbatim; VM spans mocked. No GPU, firmware or Mesa.', + 'source_sha256': {name: hashlib.sha256((BACKEND / name).read_bytes()).hexdigest() for name in + ['rt.rs', 'recovery/logic.rs', 'command.rs', 'engine.rs', 'params.rs', 'encode.rs', 'hw.rs', + 'encode/compute.rs', 'encode/render.rs']}, +}, indent=2) + '\n') 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 69138f4dd1135b..f80781e1b20ae8 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -232,6 +232,7 @@ def module(text, name): pub struct Events{pub grow:crate::KVec<[u32;18]>} pub struct Firmware{pub pools:pools::Pools,pub events:Events} pub mod budget{__BUDGET__} + #[path="__ROOT__/rt.rs"]pub mod rt; #[path="__ROOT__/slots.rs"]pub mod slots; #[path="__ROOT__/pools.rs"]pub mod pools; } @@ -653,7 +654,7 @@ def module(text, name): for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; - let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap()).unwrap(); + let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap(),g16::slots::Placement::Base).unwrap(); assert_eq!(ext.refs().unwrap().parameter_id,hw_slot); } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { @@ -753,13 +754,17 @@ def module(text, name): let pools=PoolSet::new_with_slots(&mut o,&f,[7,8]).unwrap(); assert_eq!(pools.unit(0).unwrap().id(),7); assert_eq!(pools.unit(1).unwrap().id(),8); + let scs=pools.scs(&mut o,&f,g16::hw::sizes::FREELIST_SEED + 512).unwrap(); + assert_eq!(scs.unit(0).unwrap().id(),7); + assert_eq!(scs.unit(1).unwrap().id(),8); assert_eq!( g16::pools::Allocator::new_at( &mut o, &f, g16::hw::sizes::MAX_VM_PB_SLOTS as u64, 0, - pools.heap() + pools.heap(), + g16::slots::Placement::Base ).err(), Some(EINVAL) ); @@ -769,14 +774,15 @@ def module(text, name): &f, 0, g16::hw::sizes::PB_SLOTS as u32, - pools.heap() + pools.heap(), + g16::slots::Placement::Base ).err(), Some(EINVAL) ); let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; - let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap()).unwrap(); + let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap(),g16::slots::Placement::Base).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); let desc=find_va(refs.uma_mgr[0]); @@ -906,33 +912,33 @@ def module(text, name): // and keeps 2 healthy slots (18, 19) for cross-VM switching. let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< 1, "quarantined leases stay retained"); } + + #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; + use g16::slots::ComputeSlot; + + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: compute_slots, render: None }; + + // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas + // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). + let mut vms = Vec::new(); + let mut vm_unit_arenas: Vec>> = Vec::new(); + for i in 0..8usize { + let v = vm(800 + i as u64); + let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); + for _ in 0..COMPUTE_UNITS { + per_unit.push( + sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + ); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); + vms.push(v); + vm_unit_arenas.push(per_unit); + } + + // Close all 8 VMs and reclaim displaced leases: + // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. + // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned + // (strong_count == 2); all 190 other units (including the other 23 units of each + // last-retired VM) drop immediately (strong_count == 1). + for v in &vms { + v.vm.close(); + } + assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); + assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); + let pinned_units: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); + for (i, units) in vm_unit_arenas.iter().enumerate() { + let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); + if i == 7 { + assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); + } else { + assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); + } + } + + // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. + let live = vm(900); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &live, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); + let pinned_after: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_after, 0); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); + } + } + #[test]fn closed_vm_reclaim_retains_firmware_pb_and_uma_leases_until_overwritten(){ use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; @@ -2459,90 +2558,6 @@ def module(text, name): let _ = WARM_PB_SLOTS; } - #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ - use g16::hw::sizes::COMPUTE_UNITS; - use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; - use g16::slots::ComputeSlot; - - let mut o = Objects::new(); - let mut s = Slots::new().unwrap(); - let mut compute_slots = KVec::new(); - for k in 0..COMPUTE_UNITS { - compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); - } - let prep = ComputeArena { compute: compute_slots, render: None }; - - // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas - // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). - let mut vms = Vec::new(); - let mut vm_unit_arenas: Vec>> = Vec::new(); - for i in 0..8usize { - let v = vm(800 + i as u64); - let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); - for _ in 0..COMPUTE_UNITS { - per_unit.push( - sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), - ); - } - COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); - for pipe in [0usize, 1usize] { - let mut c = Claims::new(); - let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); - s.hold_compute_slot(k, &v, &prep).unwrap(); - s.publish(&mut c).unwrap(); - s.retire(&mut c).unwrap(); - } - COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); - vms.push(v); - vm_unit_arenas.push(per_unit); - } - - // Close all 8 VMs and reclaim displaced leases: - // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. - // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned - // (strong_count == 2); all 190 other units (including the other 23 units of each - // last-retired VM) drop immediately (strong_count == 1). - for v in &vms { - v.vm.close(); - } - assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); - assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); - let pinned_units: usize = vm_unit_arenas - .iter() - .flat_map(|units| units.iter()) - .filter(|arena| sync::Arc::strong_count(arena) > 1) - .count(); - assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); - for (i, units) in vm_unit_arenas.iter().enumerate() { - let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); - if i == 7 { - assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); - } else { - assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); - assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); - } - } - - // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. - let live = vm(900); - for pipe in [0usize, 1usize] { - let mut c = Claims::new(); - let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); - s.hold_compute_slot(k, &live, &prep).unwrap(); - s.publish(&mut c).unwrap(); - s.retire(&mut c).unwrap(); - } - assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); - let pinned_after: usize = vm_unit_arenas - .iter() - .flat_map(|units| units.iter()) - .filter(|arena| sync::Arc::strong_count(arena) > 1) - .count(); - assert_eq!(pinned_after, 0); - for (i, v) in vms.iter().enumerate() { - assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); - } - } // A closed VM's PB slot 3 is displaced by slot 4 and reclaimed. pb_mgr_table[3] still names // its epoch's manager; gPM_SP(0) wrote that manager's page list (DYNAMIC, 0x704000cb40) @@ -2593,7 +2608,7 @@ def module(text, name): // A new VM's InitBM epoch rebinds slot 3. The old binding stays intact while that // render is in flight and goes only with its full retirement. let z = vm(48); - assert_eq!(p.pick_slot_in_mask_blocks(&z, false, 0b11000, 3, 512), Some(3)); + assert_eq!(p.pick_slot_in_mask_blocks_mode(&z, false, 0b11000, 3, 512, false), Some(3)); let ez = epoch(&z, 3); let bz = p.bind(3, false); p.hold_alloc(3, &z, None, None).unwrap(); @@ -2655,7 +2670,7 @@ def module(text, name): source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' -assert 'ComputeArena::new(factory, bind, vm, live, k)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' +assert 'ComputeArena::new(factory, bind, vm, live, k, placement)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') From 388229289c5f2904a04ca06939a23f0d12882ec0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 03:03:01 -0500 Subject: [PATCH 0882/1514] thermal: apple-pmp: hold brief -ENODATA glitches below passive trip Under sustained M4 GPU load, the die hotspot runs at 90-94 C while PMP SRAM channel validity words can transiently read != 1 during a refresh. Previously -ENODATA was only masked below 90 C (APPLE_PMP_GATED_HOLD_MC), so a single transient -ENODATA at >= 90 C triggered the hard sensor-fault backstop (S1 floor for ~1.8 s until 10 good reads and gradual release). Raise APPLE_PMP_GATED_HOLD_MC to 100 C (still 6 C below the 106 C passive trip and 8 C below the 108 C backstop), add a 100 ms transient refresh window (APPLE_PMP_TRANSIENT_HOLD_NS) for readings below 106 C, and share the check via apple_pmp_hold_nodata() between g16/glue.c and apple-pmp-thermal.c. Any -ENODATA at >= 106 C or lasting past its hold window continues to fail closed immediately. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/glue.c | 8 ++-- drivers/thermal/apple-pmp-thermal.c | 6 +-- include/linux/soc/apple/pmp-cooling.h | 19 +++++++- .../gpu/asahi-m4/test-thermal-policy.py | 43 +++++++++++++++++++ 4 files changed, 67 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 80bf1ff79a2b4f..699c7efae45d62 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -152,12 +152,12 @@ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool id if (!ret) { cooling->valid_ns = now; cooling->valid_mc = *temperature; - } else if (ret == -ENODATA && cooling->valid_ns && - (idle || now - cooling->valid_ns < APPLE_PMP_GATED_HOLD_NS) && - cooling->valid_mc < APPLE_PMP_GATED_HOLD_MC) { + } else if (ret == -ENODATA && + apple_pmp_hold_nodata(cooling->valid_ns, cooling->valid_mc, + now, idle)) { *temperature = cooling->valid_mc; /* Idle makes no heat: the 2 s with work in flight start with the work. */ - if (idle) + if (idle && cooling->valid_mc < APPLE_PMP_GATED_HOLD_MC) cooling->valid_ns = now; ret = 0; } diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index ceac085e3004d5..ba24ea700db1b5 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -374,9 +374,9 @@ static int apple_pmp_sample(void) if (!ret) { pmp_thermal.valid_ns = snapshot.finished_ns; pmp_thermal.valid_mc = value; - } else if (ret == -ENODATA && pmp_thermal.valid_ns && - snapshot.finished_ns - pmp_thermal.valid_ns < APPLE_PMP_GATED_HOLD_NS && - pmp_thermal.valid_mc < APPLE_PMP_GATED_HOLD_MC) { + } else if (ret == -ENODATA && + apple_pmp_hold_nodata(pmp_thermal.valid_ns, pmp_thermal.valid_mc, + snapshot.finished_ns, false)) { value = pmp_thermal.valid_mc; ret = 0; } diff --git a/include/linux/soc/apple/pmp-cooling.h b/include/linux/soc/apple/pmp-cooling.h index 6a53d9e87ef780..6f65811188fe55 100644 --- a/include/linux/soc/apple/pmp-cooling.h +++ b/include/linux/soc/apple/pmp-cooling.h @@ -23,15 +23,30 @@ /* * The firmware publishes a die sensor only while its cluster has power, so an idle * machine can have none valid for a moment (0.46 s the longest measured). Go on from the - * last reading for this long, if it was this cool. Longer or hotter is a failed sensor. + * last reading for this long, if it was this cool. Longer or hotter is a failed sensor, + * except for a single transient PMP SRAM refresh glitch below passive throttling. */ #define APPLE_PMP_GATED_HOLD_NS 2000000000ULL -#define APPLE_PMP_GATED_HOLD_MC 90000 +#define APPLE_PMP_GATED_HOLD_MC 100000 +#define APPLE_PMP_TRANSIENT_HOLD_NS 100000000ULL /* Below this hotspot, with no fault, recovery or cooling in force, nothing * acts until prediction starts at 105 C, so the slow cadence is enough. */ #define APPLE_PMP_FAST_POLL_MC 95000 +static inline bool apple_pmp_hold_nodata(unsigned long long valid_ns, + long valid_mc, + unsigned long long now, bool idle) +{ + if (!valid_ns || now < valid_ns) + return false; + if (valid_mc < APPLE_PMP_GATED_HOLD_MC && + (idle || now - valid_ns < APPLE_PMP_GATED_HOLD_NS)) + return true; + return valid_mc < APPLE_PMP_PASSIVE_MC && + now - valid_ns <= APPLE_PMP_TRANSIENT_HOLD_NS; +} + struct apple_pmp_cooling { unsigned long long last_ns, good_ns, anchor_ns, release_ns; unsigned long long dt_ns; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py index 4d7690a185e50b..9450a5d6a70019 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-thermal-policy.py @@ -255,3 +255,46 @@ def operation(op, now=0, mc=90000, error=0, gov=0, power=0, configured=9, cap=9, run(['cc','-std=gnu11','-Wall','-Wextra','-Werror','-fsanitize=undefined','-fno-sanitize-recover=all',str(lease_unit),'-o',str(OUT/'gpu-lease')]) run([str(OUT/'gpu-lease')]) print('GPU attach epochs reject stale worker publications and stale detach, begin restricted, expire budgets and never wrap') + +# Validate shared -ENODATA hold logic and its call sites in G16 glue and PMP thermal. +nodata_source = r''' +#include +#include +#include +int main(void) { + const unsigned long long t0 = 10000000000ULL; + /* Never hold without a prior valid timestamp or if time went backwards. */ + assert(!apple_pmp_hold_nodata(0, 50000, t0, true)); + assert(!apple_pmp_hold_nodata(0, 50000, t0, false)); + assert(!apple_pmp_hold_nodata(t0 + 1, 50000, t0, true)); + assert(!apple_pmp_hold_nodata(t0 + 1, 50000, t0, false)); + + /* Idle cool (<100 C) holds indefinitely; hot idle (>=100 C) uses transient window only. */ + assert(apple_pmp_hold_nodata(t0, 99999, t0 + 10000000000ULL, true)); + assert(apple_pmp_hold_nodata(t0, 100000, t0 + 100000000ULL, true)); + assert(!apple_pmp_hold_nodata(t0, 100000, t0 + 100000001ULL, true)); + + /* Active <100 C holds across the 2 s gated window, then fails closed. */ + assert(apple_pmp_hold_nodata(t0, 94000, t0 + APPLE_PMP_GATED_HOLD_NS - 1, false)); + assert(apple_pmp_hold_nodata(t0, 99999, t0 + APPLE_PMP_GATED_HOLD_NS - 1, false)); + assert(!apple_pmp_hold_nodata(t0, 99999, t0 + APPLE_PMP_GATED_HOLD_NS, false)); + + /* Active 100..105.999 C holds only a brief <=100 ms PMP SRAM refresh glitch. */ + assert(apple_pmp_hold_nodata(t0, 100000, t0 + APPLE_PMP_TRANSIENT_HOLD_NS, false)); + assert(apple_pmp_hold_nodata(t0, 105999, t0 + APPLE_PMP_TRANSIENT_HOLD_NS, false)); + assert(!apple_pmp_hold_nodata(t0, 100000, t0 + APPLE_PMP_TRANSIENT_HOLD_NS + 1, false)); + assert(!apple_pmp_hold_nodata(t0, 105999, t0 + APPLE_PMP_TRANSIENT_HOLD_NS + 1, false)); + + /* At or above passive throttling (106 C), -ENODATA always fails closed immediately. */ + assert(!apple_pmp_hold_nodata(t0, APPLE_PMP_PASSIVE_MC, t0, false)); + assert(!apple_pmp_hold_nodata(t0, APPLE_PMP_PASSIVE_MC, t0, true)); + assert(!apple_pmp_hold_nodata(t0, 110000, t0 + 1000000ULL, false)); + return 0; +} +''' +nodata_unit = OUT/'nodata-hold.c'; nodata_unit.write_text(nodata_source) +nodata_bin = build(ROOT, OUT, nodata_unit) +run([str(nodata_bin)]) +assert 'apple_pmp_hold_nodata(' in (G16/'glue.c').read_text() +assert 'apple_pmp_hold_nodata(' in (ROOT/'drivers/thermal/apple-pmp-thermal.c').read_text() +print('Shared -ENODATA hold masks brief PMP refresh glitches below passive trip and fails closed above') From 393cd79df2dd1319add833d5460b16f3a3c37746 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 16:27:28 -0500 Subject: [PATCH 0883/1514] drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records After a DRM client closes, Gpu::vm_closed() drops its registry and cache references, but device-wide slot tables (Pools::owners/owner_vms and owner_arenas across PB_SLOTS, Slots::render across 48 pass slots, and Slots::compute across 24 compute units) continued holding strong Arc and arena leases indefinitely until later traffic overwrote every slot. Under multi-process render and compute workloads, dead VMs stayed pinned after exit (multi-GiB Unevictable/Shmem and live TTBAT ASIDs), starving subsequent allocations with VK_ERROR_OUT_OF_DEVICE_MEMORY. At the same time, 26B123 RTKit firmware stores per-slot context-0 pointers in pb_mgr_table[0..15] and uma_mgr_table[1..48] that persist across subsequent work on other slots and are walked during GPU timeout recovery, so dropping the tiny firmware-owned metadata records before that exact hardware slot is overwritten would leave dangling firmware table pointers across timeout recovery. Reclaim displaced closed-VM leases cleanly without violating hardware displacement or firmware recovery contracts: - Add Lifetime::is_quarantined() so quarantined slots stay pinned forever without keeping reclaim armed. - Split the tiny firmware-owned metadata records (PbEpoch's pb_manager + counter, render Allocator's UMA descriptor + submitted, and ComputeSlot's kernel-lower work + counter) into VM-free FwLease objects allocated via Factory::fw_objects() without a Vm reference, and retain one FwLease per hardware slot in Pools and Slots until a later retired publication overwrites that exact hardware slot index. - Add Pools::reclaim_closed() and Slots::reclaim_closed() to drop owners, owner VMs, and owner arenas (Deferred-backed, safe under Shared::state) only for displaced, idle, non-pending, non-scrubbing, non-quarantined slots whose VM is closed via lock-free Vm::is_closed(). - Skip closed VMs in Slots::stage_displaced_pass_scrubs(), and arm ScrubState::waiter if a closed VM's displaced pass slot is mid-scrub. - Gate scanning behind Shared::closed_vm_reclaim (read-only Acquire load on the hot path), set in Gpu::vm_closed() and checked in idle/active poll_step(), submit_locked(), and run_housekeeping(). - Add host selftest coverage in test-resources.py and test-poll-retire.py. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 5 + drivers/gpu/drm/asahi/g16/object.rs | 50 +- drivers/gpu/drm/asahi/g16/poll.rs | 33 ++ drivers/gpu/drm/asahi/g16/pools.rs | 112 +++- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 6 + drivers/gpu/drm/asahi/g16/resources.rs | 23 +- drivers/gpu/drm/asahi/g16/slots.rs | 114 ++++- .../drivers/gpu/asahi-m4/test-poll-retire.py | 70 ++- .../drivers/gpu/asahi-m4/test-resources.py | 483 ++++++++++++++++-- 10 files changed, 834 insertions(+), 63 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 722b2fba551f88..7994d956ac782d 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2569,6 +2569,7 @@ impl Firmware { f.pb_slot as usize, &job.vm, job.resources.pb_owner_arena(f.pb_slot as usize), + job.resources.pb_uma_lease(f.pb_slot as usize), )?; } // Reserve lifetime ownership before any counter or producer becomes reachable. diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 4a3c7a21966587..9d12ae3e8df9a6 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -250,6 +250,9 @@ pub(crate) struct Shared { /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. pub(crate) publish_wake: AtomicBool, + /// Set on VM close (and re-armed while any non-quarantined slot still holds a closed VM) + /// so displaced closed-VM slot leases are reclaimed without scanning on the hot path. + pub(crate) closed_vm_reclaim: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, /// CPU whose cluster currently restricts `events_unbound` (`u32::MAX` before first pin). @@ -643,6 +646,7 @@ impl Gpu { crashed: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), unbound_cluster_cpu: AtomicU32::new(u32::MAX), unbound_pinning: AtomicBool::new(false), @@ -893,6 +897,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); + self.shared.closed_vm_reclaim.store(true, Ordering::Release); self.shared.wake_publish(); } diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 767df69e03f3e9..2ebe1a008fbbbe 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -296,11 +296,28 @@ pub(crate) struct Request { /// Private allocation coordinates. Only normal non-cacheable objects may be reclaimed. struct Private { - vm: mmu::Vm, + vm: Option, firmware: core::ops::Range, pending: Option>, } +/// VM-independent firmware-object lease whose backing and firmware/lower mappings stay alive +/// until a later command overwrites the same hardware table slot in firmware RAM. +/// +/// Dropping an `Arc` offloads unmap to `cleanup::Deferred`, so replacing a lease under +/// `Shared::state` never sleeps or blocks fence producers. +pub(crate) struct FwLease(crate::cleanup::Deferred); + +impl FwLease { + pub(crate) fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(objects)?), + GFP_KERNEL, + )?) + } +} + /// Immutable factory shared by ioctl-side private arena construction. #[derive(Clone)] pub(crate) struct Factory { @@ -317,7 +334,28 @@ impl Factory { uat: self.uat.clone(), window: self.window.clone(), private: Some(Private { - vm: vm.clone(), + vm: Some(vm.clone()), + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// Allocates firmware-only and context-0 lower-alias objects with no client VM binding. + pub(crate) fn fw_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, firmware: self.firmware.clone(), pending: None, }), @@ -473,7 +511,8 @@ impl Objects { None }; let client_gva = if let Some(range) = client_range { - let mapping = private.vm.map_in_range( + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = vm.map_in_range( &backing.gem, 0..bytes, hw::PAGE, @@ -485,6 +524,7 @@ impl Objects { self.mappings.push(mapping, GFP_KERNEL)?; Some(address) } else if let Some((gva, leaf)) = req.client { + let vm = private.vm.as_ref().ok_or(EINVAL)?; let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; if gva < hw::client::CLIENT_APERTURE.start || end > hw::client::CLIENT_APERTURE.end @@ -494,9 +534,7 @@ impl Objects { return Err(EINVAL); } self.mappings.push( - private - .vm - .map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, + vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, GFP_KERNEL, )?; Some(gva) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 3ae477db641047..e3252e36b2799b 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -272,6 +272,9 @@ impl Shared { }); } if pub_res.is_ok() { + if retired_any || !had_flights { + firmware.reclaim_closed_vm_slots(); + } pub_res = if recovery_pending { let r = firmware.publish(done); if r.is_ok() { @@ -579,6 +582,27 @@ pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { } impl Firmware { + /// Reclaims displaced slot leases belonging to closed VMs so dead processes do not keep + /// multi-hundred-MiB render/compute arenas and TTBAT ASIDs pinned while idle. + /// + /// Respects all hardware displacement contracts (active, in-flight, undisplaced, scrubbing, + /// and quarantined slots are preserved) and re-arms `Shared::closed_vm_reclaim` whenever a + /// non-quarantined slot still holds a closed VM awaiting retirement, displacement, or scrub. + pub(crate) fn reclaim_closed_vm_slots(&mut self) { + let Some(shared) = self.engine.shared.as_ref() else { + return; + }; + if !shared.closed_vm_reclaim.load(Ordering::Acquire) + || !shared.closed_vm_reclaim.swap(false, Ordering::AcqRel) + { + return; + } + let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); + if remaining { + shared.closed_vm_reclaim.store(true, Ordering::Release); + } + } + /// One non-sleeping poll step under the device lock. /// /// Retires finished flights and publishes ready work before periodic 1 ms housekeeping so @@ -622,7 +646,12 @@ impl Firmware { self.last_aux_drain_ns = now; ran_housekeeping = true; self.drain_rings()?; + self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { + let _ = self.slots.take_scrub_woke(); + if let Some(shared) = self.engine.shared.as_ref() { + shared.publish_wake.store(false, Ordering::Release); + } return Ok(false); } } @@ -645,6 +674,9 @@ impl Firmware { .shared .as_ref() .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + if retired_any || publish_woke || scrub_woke || housekeeping_due { + self.reclaim_closed_vm_slots(); + } // Skip redundant `publish_checked()` walks on busy polls where nothing could have // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), @@ -750,6 +782,7 @@ impl Firmware { self.last_aux_drain_ns = now; } self.last_housekeeping_ns = now; + self.reclaim_closed_vm_slots(); if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index ed445f21829fd1..78c93869d57dc5 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -15,7 +15,7 @@ pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; use super::hw::{client, engine, pte, sizes}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwLease, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; use core::{ @@ -57,6 +57,9 @@ pub(crate) struct Allocator { list: Arc, submitted: Arc, heap: Arc, + /// VM-free firmware lease retaining `descriptor` and `submitted` across closed-VM reclaim + /// until a later render overwrites this hardware UMA slot in firmware RAM. + uma_lease: Arc, published: AtomicBool, id: u32, } @@ -133,14 +136,20 @@ fn write_records( impl Allocator { /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. #[allow(dead_code)] - pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { - Self::new_at(o, k, k as u32, heap) + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + heap: &Arc, + ) -> Result { + Self::new_at(o, fw_factory, k, k as u32, heap) } /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot /// `RENDER_UMA_SLOT + hw_slot`). pub(crate) fn new_at( o: &mut Objects, + fw_factory: &Factory, local_idx: u64, hw_slot: u32, heap: &Arc, @@ -150,9 +159,12 @@ impl Allocator { } 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 - // must not share a writable GPU page with the engine auxiliary records. - let descriptor = alloc(o, uma_manager::SIZE, Class::Fw, None, true)?; + // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table + // stays mapped across closed-VM reclaim without pinning the VM's ASID or pools. + let mut fw = fw_factory.fw_objects(); + let descriptor = alloc(&mut fw, uma_manager::SIZE, Class::Fw, None, true)?; + let submitted = alloc(&mut fw, 0x40, Class::Fw, None, true)?; + let uma_lease = FwLease::new(fw)?; let auxiliary = alloc( o, 0x4000, @@ -181,7 +193,6 @@ impl Allocator { nc(client::render_list(local_idx)), true, )?; - let submitted = alloc(o, 0x40, Class::Fw, None, true)?; let heap = heap.clone(); super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; descriptor.write( @@ -202,10 +213,15 @@ impl Allocator { list, submitted, heap, + uma_lease, published: AtomicBool::new(false), id: hw_slot, }) } + /// Firmware-only lease retaining this allocator's UMA descriptor and submitted counter. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. pub(crate) fn id(&self) -> u32 { self.id @@ -302,13 +318,14 @@ pub(crate) fn alloc_pb_heap_chunk( } impl PoolSet { - pub(crate) fn new(o: &mut Objects) -> Result { - Self::new_with_slots(o, [0, 1]) + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory) -> Result { + Self::new_with_slots(o, fw_factory, [0, 1]) } /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and /// bound to device-wide physical PB/UMA slots `slots`. pub(crate) fn new_with_slots( o: &mut Objects, + fw_factory: &Factory, slots: [usize; sizes::BASE_PB_SLOTS], ) -> Result { // The firmware copes with a full PB without the host (its overflow counters move and @@ -324,7 +341,7 @@ impl PoolSet { let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; for (local, &hw_slot) in slots.iter().enumerate() { units.push( - Allocator::new_at(o, local as u64, hw_slot as u32, &heap)?, + Allocator::new_at(o, fw_factory, local as u64, hw_slot as u32, &heap)?, GFP_KERNEL, )?; } @@ -400,12 +417,21 @@ pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, owners: [Option>; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped + /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer + /// `InitBM` retires on that exact slot. + retained_pb: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_vms: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_arenas: [Option; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each render UMA slot's `descriptor` + `submitted` page + /// mapped for firmware's global `uma_mgr_table[RENDER_UMA_SLOT + k]` across closed-VM reclaim + /// until a newer render retires on that exact slot. + retained_uma: [Option>; sizes::PB_SLOTS], pending_vms: [Option>; sizes::PB_SLOTS], pending_arenas: [Option; sizes::PB_SLOTS], + pending_uma: [Option>; sizes::PB_SLOTS], /// 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; sizes::PB_SLOTS], @@ -429,10 +455,13 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], owner_vms: [const { None }; sizes::PB_SLOTS], owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], pending_vms: [const { None }; sizes::PB_SLOTS], pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], binds: [0; sizes::PB_SLOTS], keep: [false; sizes::PB_SLOTS], active: None, @@ -452,10 +481,13 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], owner_vms: [const { None }; sizes::PB_SLOTS], owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], pending_vms: [const { None }; sizes::PB_SLOTS], pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], binds: [0; sizes::PB_SLOTS], keep: [false; sizes::PB_SLOTS], active: None, @@ -748,7 +780,7 @@ impl Pools { pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { self.exhausted_for_within(vm, sizes::PB_SLOTS) } - /// Retains the candidate VM and owning render/recovery arena (holding the UMA descriptors) + /// Retains the candidate VM, owning render/recovery arena, and firmware UMA descriptor lease /// before publication visibility. #[allow(dead_code)] pub(crate) fn hold_alloc( @@ -756,12 +788,14 @@ impl Pools { k: usize, vm: &Arc, arena: Option, + uma_lease: Option>, ) -> Result { if k >= sizes::PB_SLOTS || self.quarantined[k] { return Err(EINVAL); } self.pending_vms[k] = Some(vm.clone()); self.pending_arenas[k] = arena; + self.pending_uma[k] = uma_lease; Ok(()) } /// Cancels unpublished candidate retention for allocator slot `k`. @@ -770,6 +804,7 @@ impl Pools { if k < sizes::PB_SLOTS { self.pending_vms[k] = None; self.pending_arenas[k] = None; + self.pending_uma[k] = None; } } /// Records a render reaching firmware visibility on allocator slot `k`. @@ -797,12 +832,16 @@ impl Pools { return Ok(()); } self.owners[k] = Some(epoch.clone()); + self.retained_pb[k] = Some(epoch.records_lease()); 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); } + if let Some(uma) = self.pending_uma[k].take() { + self.retained_uma[k] = Some(uma); + } self.last_clean_retired = Some(k); self.retire_epoch(k, binding, completed); Ok(()) @@ -865,9 +904,47 @@ impl Pools { *keep = false; } } + /// Releases displaced PB/UMA allocator leases owned by closed VMs while preserving active, + /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined + /// slot still holds a closed-VM lease awaiting retirement or displacement. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + continue; + } + let closed = self.owner_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()) + || self.owners[k] + .as_ref() + .is_some_and(|epoch| epoch._vm.vm.is_closed()) + || self.pending_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !closed { + continue; + } + if self.slot_displaced(k) + && self.pending_vms[k].is_none() + && self.pending_arenas[k].is_none() + && self.pending_uma[k].is_none() + { + self.owners[k] = None; + self.owner_vms[k] = None; + self.owner_arenas[k] = None; + self.keep[k] = false; + self.binds[k] = self.binds[k].wrapping_add(1); + } else { + remaining = true; + } + } + remaining + } #[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()); + *self.retained_pb.get_mut(k).ok_or(EINVAL)? = Some(epoch.records_lease()); Ok(()) } pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { @@ -907,6 +984,9 @@ pub(crate) struct PbEpochInner { /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). seeded_blocks: AtomicU32, exposed: AtomicBool, + /// VM-free firmware lease keeping `records` (`manager`, `ring`, `counter`, `misc`, `initbm`) + /// mapped across closed-VM reclaim until a newer `InitBM` overwrites `pb_mgr_table[k]`. + records_lease: Arc, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, _vm: Arc, @@ -919,8 +999,10 @@ impl PbEpoch { vm: &Arc, permit: super::budget::Permit, ) -> Result> { + let mut fw = factory.fw_objects(); + let records = alloc(&mut fw, 0x500, Class::Fw, None, true)?; + let records_lease = FwLease::new(fw)?; let mut o = factory.objects(&vm.vm); - let records = alloc(&mut o, 0x500, Class::Fw, None, true)?; let mut inner = PbEpochInner { manager: FwObject::view(&records, 0, 0xc0)?, pages: o.alloc_dynamic_client(buffer::PAGE_LIST_SIZE)?, @@ -933,6 +1015,7 @@ impl PbEpoch { heap_blocks: AtomicU32::new(0), seeded_blocks: AtomicU32::new(0), exposed: AtomicBool::new(false), + records_lease, _objects: o, _vm: vm.clone(), _permit: permit, @@ -944,6 +1027,11 @@ impl PbEpoch { )?) } + /// Firmware-only lease retaining this epoch's `pb_manager` + `counter` page. + pub(crate) fn records_lease(&self) -> Arc { + self.records_lease.clone() + } + /// 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, heap_blocks: u32) -> Result { diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 869e716b2b7e87..15e77396fcf7ac 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -122,6 +122,12 @@ impl Lifetime { pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) } + /// Whether owner `k` is permanently quarantined. + pub(crate) fn is_quarantined(&self, k: usize) -> bool { + self.units + .get(k) + .is_some_and(|u| u.state == State::Quarantined) + } pub(crate) fn claim(&mut self, k: usize) -> bool { if !self.available(k) { return false; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index aad844d07e73e6..271b3867da4242 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -64,7 +64,10 @@ impl ComputeArena { let mut objects = factory.objects(vm); 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)?; + compute.push( + ComputeSlot::new(&mut objects, factory, k as u64)?, + GFP_KERNEL, + )?; } objects.finish_private()?; Ok(Arc::new( @@ -301,7 +304,7 @@ impl RenderArena { for k in 0..BASE_RENDER_SLOTS { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; } - let pools = PoolSet::new_with_slots(&mut objects, base_pb_slots)?; + let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { @@ -425,8 +428,13 @@ impl PoolExtArena { heap: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let allocator = - super::pools::Allocator::new_at(&mut objects, local_idx as u64, hw_slot as u32, heap)?; + let allocator = super::pools::Allocator::new_at( + &mut objects, + factory, + local_idx as u64, + hw_slot as u32, + heap, + )?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(PoolExtInner { @@ -1196,6 +1204,13 @@ impl Prepared { .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } } + /// VM-free firmware lease keeping PB/UMA allocator slot `k`'s `descriptor` + `submitted` + /// pages mapped in context-0 UAT across closed-VM reclaim. + pub(crate) fn pb_uma_lease(&self, k: usize) -> Option> { + self.pb_allocator(k) + .ok() + .map(super::pools::Allocator::uma_lease) + } fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { for tier in self.render_ext.iter().take_while(|t| t.is_some()).flatten() { if let Some(idx) = k.checked_sub(tier.start) { diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 900d25b725e0d9..aa3d445a12bd83 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -15,7 +15,7 @@ use super::encode::{Geometry, PassRefs}; use super::fw::work::{barrier, fs, ta}; use super::graph::{alloc, alloc_work, cmd_fw, Client}; use super::hw::{client, sizes}; -use super::object::{Class, FwObject, Objects}; +use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. @@ -32,6 +32,10 @@ pub(crate) struct ComputeSlot { pub(crate) counter: Arc, pub(crate) context_store: Arc, pub(crate) aux: Arc, + /// VM-free firmware lease keeping `work` (containing the compute UMA manager at `+0xe00`) + /// and `counter` mapped in context-0 UAT until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + uma_lease: Arc, } /// Initializes the private pool exactly once, before it is exposed. Never called on reuse. @@ -54,8 +58,12 @@ pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64) -> Res } impl ComputeSlot { - pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { let sh = Class::Shared; + let mut fw = fw_factory.fw_objects(); + let work = alloc_work(&mut fw, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?; + let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; + let uma_lease = FwLease::new(fw)?; let unit = Self { its: alloc(o, 16, sh, None, 0, false)?, preempt: alloc( @@ -66,7 +74,7 @@ impl ComputeSlot { 0, false, )?, - work: alloc_work(o, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?, + work, seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. barrier: alloc( @@ -95,7 +103,7 @@ impl ComputeSlot { false, )?, page_list: alloc(o, 0x4000, sh, Client::nc(client::compute_list(k)), 0, false)?, - counter: alloc(o, 0x80, sh, None, 0, false)?, + counter, context_store: alloc( o, 0x40000, @@ -105,6 +113,7 @@ impl ComputeSlot { false, )?, aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, + uma_lease, }; init_uma_pool( &unit.pool_state, @@ -113,6 +122,10 @@ impl ComputeSlot { )?; Ok(unit) } + /// VM-free firmware lease keeping this unit's `work` and `counter` mapped in context-0 UAT. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } /// 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 @@ -461,6 +474,11 @@ 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], + /// VM-free firmware leases keeping each hardware slot's `work` + `counter` mapped in + /// context-0 UAT across closed-VM reclaim until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + retained_uma: [Option>; sizes::COMPUTE_UNITS], + pending_uma: [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. @@ -737,6 +755,8 @@ impl Slots { pending_owner: [const { None }; sizes::COMPUTE_UNITS], arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], + retained_uma: [const { None }; sizes::COMPUTE_UNITS], + pending_uma: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], last_full: [true; sizes::COMPUTE_UNITS], }), @@ -893,6 +913,9 @@ impl Slots { || self.render.scrub_full[k] || self.scrub.is_scrubbing(k) || self.scrub.is_clean(k) + || self.render.owner[k] + .as_ref() + .is_none_or(|vm| vm.vm.is_closed()) { continue; } @@ -932,6 +955,78 @@ impl Slots { } self.take_staged_scrubs() } + /// Releases displaced compute-unit and render-pass leases owned by closed VMs while + /// preserving active, in-flight, undisplaced, scrubbing, and quarantined slots. + /// + /// Returns `true` if any non-quarantined slot still holds a closed-VM lease awaiting + /// retirement, displacement, or an in-progress off-lock pass scrub. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::COMPUTE_UNITS { + if self.compute.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.compute.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.compute.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + if owner_closed + && self.compute.lifetime.available(k) + && self.compute.pending_owner[k].is_none() + && self.compute.pending_arena[k].is_none() + && self.compute.pending_uma[k].is_none() + { + self.compute.owner[k] = None; + self.compute.arena[k] = None; + self.compute.scrub_full[k] = true; + self.compute.last_full[k] = true; + } else { + remaining = true; + } + } + for k in 0..sizes::RENDER_SLOTS { + if self.render.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.render.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.render.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + let bit = 1u64 << k; + if owner_closed + && self.pass_busy & bit == 0 + && self.render.lifetime.available(k) + && self.render.pending_owner[k].is_none() + && self.render.pending_arena[k].is_none() + { + if self.scrub.is_scrubbing(k) { + self.scrub.waiter.store(true, Ordering::SeqCst); + } + if !self.scrub.is_scrubbing(k) { + self.render.owner[k] = None; + self.render.arena[k] = None; + self.render.scrub_full[k] = true; + self.render.last_full[k] = true; + self.scrub.clear_clean(k); + } else { + remaining = true; + } + } else { + remaining = true; + } + } + remaining + } /// Compute units published and not yet retired. pub(crate) fn compute_published(&self) -> u32 { self.compute.lifetime.published() @@ -1436,6 +1531,7 @@ impl Slots { .and_then(|old| Self::vm_retarget(k, old, vm)); self.compute.pending_owner[k] = Some(vm.clone()); self.compute.pending_arena[k] = resources.compute_arena(k); + self.compute.pending_uma[k] = resources.compute_unit(k).ok().map(ComputeSlot::uma_lease); Ok(()) } @@ -1557,6 +1653,12 @@ impl Slots { if let Some(cell) = self.compute.pending_arena.get_mut(k as usize) { *cell = resources.compute_arena(k as usize); } + if let Some(cell) = self.compute.pending_uma.get_mut(k as usize) { + *cell = resources + .compute_unit(k as usize) + .ok() + .map(ComputeSlot::uma_lease); + } } let mut mask = f.pass_mask & PASS_MASK; while mask != 0 { @@ -1635,6 +1737,9 @@ 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(); + if let Some(lease) = self.compute.pending_uma[k as usize].take() { + self.compute.retained_uma[k as usize] = Some(lease); + } if clean_scrub { self.compute.scrub_full[k as usize] = false; } @@ -1686,6 +1791,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.pending_uma[k as usize] = None; self.compute.scrub_full[k as usize] = true; } let mut mask = f.pass_mask & PASS_MASK; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 5a7a7b3e5ba362..03099634f7b6c2 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -213,6 +213,7 @@ def item(declaration, text=source): sleeping: AtomicBool, evented: AtomicBool, publish_wake: AtomicBool, + closed_vm_reclaim: AtomicBool, rearmed: Cell, idle_power_polls: Cell, rearm_soon: Cell, @@ -224,6 +225,7 @@ def item(declaration, text=source): sleeping: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), rearmed: Cell::new(0), idle_power_polls: Cell::new(0), rearm_soon: Cell::new(0), @@ -262,14 +264,32 @@ def item(declaration, text=source): } } +#[derive(Default)] +struct Pools { + reclaim_calls: u32, + reclaim_remaining: bool, +} +impl Pools { + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } +} + #[derive(Default)] struct Slots { scrub_woke: AtomicBool, + reclaim_calls: u32, + reclaim_remaining: bool, } impl Slots { fn take_scrub_woke(&self) -> bool { self.scrub_woke.swap(false, Ordering::AcqRel) } + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } } struct Firmware { @@ -280,6 +300,7 @@ def item(declaration, text=source): events: Events, recovery: Recovery, power: Power, + pools: Pools, slots: Slots, last_housekeeping_ns: u64, last_aux_drain_ns: u64, @@ -333,6 +354,7 @@ def item(declaration, text=source): events: Events::default(), recovery: Recovery::default(), power: Power::default(), + pools: Pools::default(), slots: Slots::default(), last_housekeeping_ns: 0, last_aux_drain_ns: 0, @@ -410,12 +432,57 @@ def item(declaration, text=source): self.ta_pending } + __RECLAIM_CLOSED_VM_SLOTS__ __POLL_STEP__ __OLDEST_TERMINAL_EVENTS__ __TA_WAVE_READY__ __OLDEST_STAMP_REACHED__ } +#[test] +fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { + CLOCK.with(|c| c.set(1_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.shared = Some(shared.clone()); + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared.publish_wake.store(true, Ordering::Release); + fw.pools.reclaim_remaining = true; + + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let busy = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert!(!busy); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (1, 1)); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!( + shared.closed_vm_reclaim.load(Ordering::Acquire), + "remaining undisplaced closed VM keeps reclaim armed" + ); + + // Once remaining clears, idle poll clears closed_vm_reclaim and later polls skip scans. + fw.pools.reclaim_remaining = false; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + + // Idle submit_locked also reclaims before publish_checked when armed. + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 9 }), &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); +} + #[test] fn submit_locked_retires_inline_on_reached_stamp_without_full_housekeeping() { CLOCK.with(|c| c.set(100_000)); @@ -1501,6 +1568,7 @@ def item(declaration, text=source): for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', + '__RECLAIM_CLOSED_VM_SLOTS__': 'pub(crate) fn reclaim_closed_vm_slots(', '__POLL_STEP__': 'pub(crate) fn poll_step(', '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', @@ -1537,7 +1605,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 21, + 'tests': 22, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', 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 860e6f89d8240c..efbe9e2b7a2f39 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -107,15 +107,26 @@ def module(text, name): pub fn r32(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u32::from_le_bytes(d[self.offset+o..self.offset+o+4].try_into().unwrap()))} pub fn snapshot(&self)->Vec{self.data.lock().unwrap().clone()} } + pub struct FwLease(pub crate::cleanup::Deferred); + impl FwLease { + pub fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Arc::new(Self(crate::cleanup::Deferred::new(objects)?), 0) + } + } pub struct Factory; - impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} + impl Factory{ + pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} + pub fn fw_objects(&self)->Objects{Objects::new()} + } + pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} - pub struct Objects{pub objects:Vec>,next:u64} + pub struct Objects{pub objects:Vec>} impl Objects{ - pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} + pub fn new()->Self{Self{objects:vec![]}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -140,8 +151,15 @@ def module(text, name): 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; - pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:()} + use crate::{mmu,sync::Arc}; + use core::sync::atomic::{AtomicBool,Ordering}; + pub struct MockVm(AtomicBool); + impl MockVm{ + pub fn new()->Self{Self(AtomicBool::new(false))} + pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} + pub fn close(&self){self.0.store(true,Ordering::Release);} + } + pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -171,10 +189,17 @@ def module(text, name): match self{Self::Base(a)=>Some((a.passes.get(k)?,PassDirty{tpc:a.tpc_dirty.get(k)?,tilemap:a.tilemap_dirty.get(k)?,tilemap_last:a.tilemap_last.get(k)?,tilemap_clean:a.tilemap_clean.get(k)?,heap:a.heap_dirty.get(k)?}))} } } + std::thread_local!{ + pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< + Option>, + >=const{std::cell::RefCell::new(None)}; + } 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 compute_arena(&self,_k:usize)->Option>{ + COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone()) + } pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} @@ -218,9 +243,13 @@ def module(text, name): heap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], } } + fn find_va(va:u64)->sync::Arc{ + g16::object::ALL_OBJECTS.with(|a|a.borrow().iter().find(|obj|obj.va==va).unwrap().clone()) + } 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();} + let f=g16::object::Factory; + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<=0x7000000000);assert!(base+a.mapped as u64<=0x7100000000);aliases.push((base,base+a.mapped as u64));}} aliases.push((0x1000000000,0x1000010000)); // Per-VM context store. @@ -315,11 +344,11 @@ def module(text, name): } } #[test]fn allocator_metadata_is_firmware_only_and_shared_state_keeps_real_backing(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let read64=|obj:&g16::object::FwObject,at:usize|->u64{obj.r32(at).unwrap()as u64|((obj.r32(at+4).unwrap()as u64)<<32)}; for k in 0..2 { let refs=pools.allocator_refs_for(k).unwrap(); - let descriptor=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let descriptor=find_va(refs.uma_mgr[0]); let auxiliary=o.objects.iter().find(|obj|obj.va+0x100==refs.uma_aux[0]).unwrap(); assert_eq!(descriptor.class,g16::object::Class::Fw); assert_eq!(descriptor.gva,None);assert_eq!(descriptor.client_leaf,None); @@ -342,8 +371,8 @@ def module(text, name): } assert_eq!(metadata,descriptor.snapshot()); // Freelist and pool-table pointers still select writable client mappings. - let state_va=read64(descriptor,g16::fw::graph::manager::FREELIST); - let list_va=read64(descriptor,g16::fw::graph::manager::POOL_TABLE); + let state_va=read64(&descriptor,g16::fw::graph::manager::FREELIST); + let list_va=read64(&descriptor,g16::fw::graph::manager::POOL_TABLE); for va in [list_va,state_va] { let shared=o.objects.iter().find(|obj|obj.gva==Some(va)).unwrap(); assert_eq!(shared.class,g16::object::Class::Shared); @@ -369,11 +398,11 @@ def module(text, name): s.publish(&mut c).unwrap();s.quarantine(&mut c);assert!(s.compute_exhausted()); } #[test]fn production_render_descriptors_preserve_firmware_bytes_and_exact_counter(){ - let mut o=Objects::new();let mut pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let mut pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let a=pools.prepare(0,1).unwrap();assert!(a.init_buffer);assert_eq!(a.uma_submitted,2); assert!(!pools.retired(0).unwrap());pools.publish_batch(0,2,1).unwrap(); assert!(pools.publish_batch(0,2,1).is_err());assert!(pools.prepare(0,2).is_err()); - let d=o.objects.iter().find(|o|o.va==a.uma_mgr[0]).unwrap(); + let d=find_va(a.uma_mgr[0]); d.w64(0x54,2).unwrap();d.w64(0x60,0x5a5aa5a5).unwrap(); let original=d.snapshot();assert!(pools.retired(0).unwrap()); let next=pools.prepare(0,2).unwrap();assert!(next.init_buffer);assert_eq!(next.uma_submitted,4); @@ -382,9 +411,15 @@ def module(text, name): #[test]fn cross_vm_evidence_counts_only_noted_publication(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); - let a=sync::Arc::new(g16::vm::VmState{id:100,slot:1,generation:1,vm:()},0).unwrap(); - let b=sync::Arc::new(g16::vm::VmState{id:101,slot:2,generation:1,vm:()},0).unwrap(); - let c=sync::Arc::new(g16::vm::VmState{id:102,slot:3,generation:9,vm:()},0).unwrap(); + let a=sync::Arc::new( + g16::vm::VmState{id:100,slot:1,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let b=sync::Arc::new( + g16::vm::VmState{id:101,slot:2,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let c=sync::Arc::new( + g16::vm::VmState{id:102,slot:3,generation:9,vm:g16::vm::MockVm::new()},0, + ).unwrap(); let mut claims=Claims::new(); for vm in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,vm).unwrap();s.publish(&mut claims).unwrap();s.note_published(&claims);s.retire(&mut claims).unwrap();} assert_eq!(s.stats.cross_vm_retargets,[0,0]); @@ -401,7 +436,11 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{sync::Arc::new(g16::vm::VmState{id,slot:id as u32,generation:1,vm:()},0).unwrap()} + fn vm(id:u64)->sync::Arc{ + sync::Arc::new( + g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap() + } #[test]fn previous_vm_lease_survives_replacement_publication_until_full_retirement(){ let mut o=Objects::new();let arena=arenas(&mut o);let mut s=Slots::new().unwrap(); let a=vm(1);let b=vm(2);let c=vm(3);let mut claims=Claims::new(); @@ -605,15 +644,15 @@ def module(text, name): assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; - let ext=g16::pools::Allocator::new_at(&mut o,local,hw_slot,pools.heap()).unwrap(); + let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap()).unwrap(); assert_eq!(ext.refs().unwrap().parameter_id,hw_slot); } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { - g16::slots::ComputeSlot::new(&mut o,k).unwrap(); + g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(); } let mut scene_lists=Vec::new(); let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); @@ -655,7 +694,7 @@ def module(text, name): } #[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 mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).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(); @@ -668,7 +707,7 @@ def module(text, name): let a1=pools.prepare_in_flight(0,1,false).unwrap(); assert_eq!(a1.uma_submitted,2); pools.publish_batch(0,2,1).unwrap();p.publish_flight(0); - let d0=o.objects.iter().find(|obj|obj.va==a1.uma_mgr[0]).unwrap(); + let d0=find_va(a1.uma_mgr[0]); 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). @@ -705,12 +744,14 @@ def module(text, name): #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ let mut o=Objects::new(); - let pools=PoolSet::new_with_slots(&mut o,[7,8]).unwrap(); + let f=g16::object::Factory; + let pools=PoolSet::new_with_slots(&mut o,&f,[7,8]).unwrap(); assert_eq!(pools.unit(0).unwrap().id(),7); assert_eq!(pools.unit(1).unwrap().id(),8); assert_eq!( g16::pools::Allocator::new_at( &mut o, + &f, g16::hw::sizes::MAX_VM_PB_SLOTS as u64, 0, pools.heap() @@ -720,6 +761,7 @@ def module(text, name): assert_eq!( g16::pools::Allocator::new_at( &mut o, + &f, 0, g16::hw::sizes::PB_SLOTS as u32, pools.heap() @@ -729,10 +771,10 @@ def module(text, name): let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; - let alloc=g16::pools::Allocator::new_at(&mut o,local,k as u32,pools.heap()).unwrap(); + let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap()).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); - let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let desc=find_va(refs.uma_mgr[0]); let slot_id=desc.r32(8).unwrap(); let expected=g16::hw::engine::RENDER_UMA_SLOT+k as u32; assert_eq!(slot_id,expected); @@ -1151,10 +1193,12 @@ def module(text, name): let mut o=Objects::new(); let mut units=KVec::new(); for k in 0..hw::sizes::COMPUTE_UNITS { - units.push(ComputeSlot::new(&mut o,k as u64).unwrap(),0).unwrap(); + units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64).unwrap(),0).unwrap(); } let prep=ComputeArena{compute:units,render:None}; - let a=Arc::new(vm::VmState{id:1,slot:1,generation:1,vm:()},0).unwrap(); + let a=Arc::new( + vm::VmState{id:1,slot:1,generation:1,vm:vm::MockVm::new()},0, + ).unwrap(); let mut s=Slots::new().unwrap(); assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),hw::sizes::COMPUTE_UNITS as u32); // Claim 4 units into one Claims for a compute horizon, publish, and retire in order. @@ -1237,7 +1281,7 @@ def module(text, name): s.release(&mut cancel2); // PoolSet::publish_batch advances submitted by 2 * renders and rejects invalid deltas. - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); assert_eq!(pools.publish_batch(0,0,0),Err(EINVAL)); assert_eq!(pools.publish_batch(0,4,3),Err(EINVAL)); assert_eq!(pools.publish_batch(0,6,3),Ok(())); @@ -1417,7 +1461,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut units=KVec::new(); for k in 0..4u64 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_full=g16::resources::ComputeArena{compute:units,render:None}; let a=vm(1);let b=vm(2); @@ -1444,7 +1488,7 @@ def module(text, name): // A base-only (2-unit) VM can now claim displaced base unit 0 again. let mut base_units=KVec::new(); for k in 0..2u64 { - base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); @@ -1455,7 +1499,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut units=KVec::new(); for k in 0..4u64 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep=g16::resources::ComputeArena{compute:units,render:None}; let a=vm(1);let b=vm(2); @@ -1492,7 +1536,7 @@ def module(text, name): // reclaims displaced extension unit 2 on the 4-unit VM without touching base units 0..2. let mut base_units=KVec::new(); for k in 0..2u64 { - base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; let mut c0c=Claims::new(); @@ -1788,7 +1832,7 @@ def module(text, name): let mut s = Slots::new().unwrap(); let mut units = KVec::new(); for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { - units.push(g16::slots::ComputeSlot::new(&mut o, k).unwrap(), 0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o, &g16::object::Factory, k).unwrap(), 0).unwrap(); } let prep = g16::resources::ComputeArena { compute: units, render: None }; let vms = [vm(1), vm(2), vm(3), vm(4)]; @@ -2021,6 +2065,370 @@ def module(text, name): assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); } + + #[test]fn closed_vms_reclaim_displaced_pb_render_and_compute_slots(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::{ComputeSlot, PassSlot}; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let mut passes = KVec::new(); + for k in 0..18 { + passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let shared_prep_compute = ComputeArena { compute: compute_slots, render: None }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + + let mut vms = Vec::new(); + let mut epochs = Vec::new(); + let mut pb_arenas = Vec::new(); + let mut pass_arenas = Vec::new(); + let mut comp_arenas = Vec::new(); + + // Bind and retire 16 VMs across warm PB slots, render passes, and compute units. + for i in 0..WARM_PB_SLOTS { + let v = vm(400 + i as u64); + let pb_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let mut r_passes = KVec::new(); + for k in 0..18 { + r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); + let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()) }; + let c_arena = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None }, 0, + ).unwrap(); + + // 1) PB slot i + let pb_slot = i; + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(pb_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(pb_slot, false); + p.hold_alloc(pb_slot, &v, Some(PbOwnerArena::Base(pb_arena.clone())), None).unwrap(); + p.publish_flight(pb_slot); + p.retire_flight(pb_slot, &e, b, true).unwrap(); + + // 2) Render pass slot i + let pk = s.pick_pass_in_for(&r_prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&r_prep, pk, Some(v.id), geo.tilemap_bytes).unwrap(); + let mut rc = Claims::new(); + rc.pass[0] = pk as u32; + rc.pass_count = 1; + rc.pass_mask = 1u64 << pk; + s.hold_render_pass(pk, &v, &r_prep).unwrap(); + s.publish(&mut rc).unwrap(); + s.retire(&mut rc).unwrap(); + + // 3) Compute unit i + let mut cc = Claims::new(); + let ck = s + .claim_compute_for(&shared_prep_compute, &mut cc, Some(v.id)) + .unwrap() + .unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena.clone())); + s.hold_compute_slot(ck, &v, &shared_prep_compute).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc).unwrap(); + s.retire(&mut cc).unwrap(); + + vms.push(v); + epochs.push(e); + pb_arenas.push(pb_arena); + pass_arenas.push(r_arena); + comp_arenas.push(c_arena); + } + + // Live VMs stay pinned and reusable across reclaim_closed(). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + for i in 0..WARM_PB_SLOTS { + assert!(sync::Arc::strong_count(&pb_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&pass_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&comp_arenas[i]) > 1); + assert!(p.reusable(i, &vms[i]).is_some()); + } + + // Close all VMs: displaced slots 0..15 reclaim immediately; last (15) stays undisplaced. + for v in &vms { + v.vm.close(); + } + assert!(p.reclaim_closed(), "undisplaced last PB slot remains"); + assert!(s.reclaim_closed(), "undisplaced last render/compute slot remain"); + // Displaced pass scrubs must skip closed VMs. + s.stage_displaced_pass_scrubs(); + assert!(!s.scrubbing_active()); + + let last = WARM_PB_SLOTS - 1; + for i in 0..last { + assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "PB epoch {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 2); + } + // Final undisplaced slot stays protected until displaced. + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 2); + + // Live VM runs 1 render + 1 compute, displacing slot 15 everywhere. + let live = vm(500); + let live_r_arena = sync::Arc::new(render_arena(passes), 0).unwrap(); + let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()) }; + let live_slot = p.pick_slot_in_mask_blocks(&live, false, 0b11, 0, 512).unwrap(); + assert_eq!(live_slot, 0); + let live_e = g16::pools::PbEpoch::new( + &factory, + &live, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + live_e.prepare(live_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + live_e.expose(); + let lb = p.bind(live_slot, false); + p.hold_alloc(live_slot, &live, Some(PbOwnerArena::Base(live_r_arena.clone())), None).unwrap(); + p.publish_flight(live_slot); + p.retire_flight(live_slot, &live_e, lb, true).unwrap(); + + let lpk = s.pick_pass_in_for(&live_r_prep, &geo, 0, Some(live.id)).unwrap(); + s.claim_pass_in(&live_r_prep, lpk, Some(live.id), geo.tilemap_bytes).unwrap(); + let mut lrc = Claims::new(); + lrc.pass[0] = lpk as u32; + lrc.pass_count = 1; + lrc.pass_mask = 1u64 << lpk; + s.hold_render_pass(lpk, &live, &live_r_prep).unwrap(); + s.publish(&mut lrc).unwrap(); + s.retire(&mut lrc).unwrap(); + + let mut lcc = Claims::new(); + let lck = s + .claim_compute_for(&shared_prep_compute, &mut lcc, Some(live.id)) + .unwrap() + .unwrap(); + s.hold_compute_slot(lck, &live, &shared_prep_compute).unwrap(); + s.publish(&mut lcc).unwrap(); + s.retire(&mut lcc).unwrap(); + + // Now slot 15 is displaced -> reclaim_closed() evicts it and returns false (0 remaining). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&epochs[last]), 1); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + drop(epochs); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); + } + + // Active off-lock scrub on a closed VM's displaced pass slot waits for scrub completion. + let mut s2 = Slots::new().unwrap(); + let mut sc_passes = KVec::new(); + for k in 0..2 { + sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); + let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()) }; + let va = vm(600); + let vb = vm(601); + for (k, owner) in [(0usize, &va), (1usize, &vb)] { + s2.claim_pass_in(&sc_prep, k, Some(owner.id), 0x2000).unwrap(); + sc_prep.set_pass_dirty(k, 0x1000, 0x2000, 0x200).unwrap(); + let mut c = Claims::new(); + c.pass[0] = k as u32; + c.pass_count = 1; + c.pass_mask = 1u64 << k; + s2.hold_render_pass(k, owner, &sc_prep).unwrap(); + s2.publish(&mut c).unwrap(); + s2.retire(&mut c).unwrap(); + } + // Stage off-lock scrub on displaced slot 0 while va is still open, then close va. + s2.stage_displaced_pass_scrubs(); + assert!(s2.scrubbing_active()); + let batch = s2.take_staged_scrubs(); + va.vm.close(); + assert!(s2.reclaim_closed(), "must not evict slot 0 mid-scrub"); + assert_eq!(sync::Arc::strong_count(&va), 2); + // Running the scrub wakes the reclaim waiter, then reclaim_closed() evicts slot 0. + assert!(drain_scrubs(batch)); + assert!(s2.take_scrub_woke()); + assert!(!s2.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&va), 1); + + // Quarantined closed-VM slots stay pinned forever AND do not keep reclaim_closed() armed. + let vq = vm(700); + let mut pq = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let eq = g16::pools::PbEpoch::new( + &factory, + &vq, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + pq.hold_alloc(0, &vq, Some(PbOwnerArena::Base(sc_arena.clone())), None).unwrap(); + pq.publish_flight(0); + pq.quarantine_flight(0, Some(eq.clone())); + let mut cq = Claims::new(); + let qk = s2.claim_compute_for(&shared_prep_compute, &mut cq, Some(vq.id)).unwrap().unwrap(); + s2.hold_compute_slot(qk, &vq, &shared_prep_compute).unwrap(); + s2.publish(&mut cq).unwrap(); + s2.quarantine(&mut cq); + vq.vm.close(); + assert!(!pq.reclaim_closed(), "quarantined PB slot must not spin reclaim"); + assert!(!s2.reclaim_closed(), "quarantined compute slot must not spin reclaim"); + assert!(sync::Arc::strong_count(&vq) > 1, "quarantined leases stay retained"); + } + #[test]fn closed_vm_reclaim_retains_firmware_pb_and_uma_leases_until_overwritten(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::ComputeSlot; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + // VM1 primes PB/UMA slot 0 and compute unit 0; VM2 displaces both via slot 1 / unit 1. + let vm1 = vm(1001); + let vm2 = vm(1002); + let vm3 = vm(1003); + + let pools1 = PoolSet::new_with_slots(&mut o, &factory, [0, 1]).unwrap(); + let uma1 = pools1.unit(0).unwrap().uma_lease(); + let r_arena1 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e1 = g16::pools::PbEpoch::new( + &factory, + &vm1, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease1 = e1.records_lease(); + e1.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e1.expose(); + let b1 = p.bind(0, false); + p.hold_alloc(0, &vm1, Some(PbOwnerArena::Base(r_arena1.clone())), Some(uma1.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e1, b1, true).unwrap(); + + let pools2 = PoolSet::new_with_slots(&mut o, &factory, [1, 2]).unwrap(); + let uma2 = pools2.unit(0).unwrap().uma_lease(); + let r_arena2 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e2 = g16::pools::PbEpoch::new( + &factory, + &vm2, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e2.prepare(1, g16::hw::client::pb_heap(0), 512).unwrap(); + e2.expose(); + let b2 = p.bind(1, false); + p.hold_alloc(1, &vm2, Some(PbOwnerArena::Base(r_arena2.clone())), Some(uma2.clone())).unwrap(); + p.publish_flight(1); + p.retire_flight(1, &e2, b2, true).unwrap(); + + // Compute unit 0 owned by VM1, displaced by VM2 on unit 1. + let mut units1 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units1.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); + } + let c_uma1 = units1[0].uma_lease(); + let prep1 = ComputeArena { compute: units1, render: None }; + let c_arena1 = sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(); + let mut cc1 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep1, &mut cc1, Some(vm1.id)).unwrap(), Some(0)); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena1.clone())); + s.hold_compute_slot(0, &vm1, &prep1).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc1).unwrap(); + s.retire(&mut cc1).unwrap(); + + let mut units2 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units2.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); + } + let prep2 = ComputeArena { compute: units2, render: None }; + let mut cc2 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep2, &mut cc2, Some(vm2.id)).unwrap(), Some(1)); + s.hold_compute_slot(1, &vm2, &prep2).unwrap(); + s.publish(&mut cc2).unwrap(); + s.retire(&mut cc2).unwrap(); + + let mut units3 = KVec::new(); + units3.push(ComputeSlot::new(&mut o, &factory, 0).unwrap(), 0).unwrap(); + let c_uma3 = units3[0].uma_lease(); + let prep3 = ComputeArena { compute: units3, render: None }; + + // Drop local arena/epoch/pool handles for VM1 and close VM1. + drop(e1); + drop(pools1); + drop(prep1); + vm1.vm.close(); + + // Reclaim evicts VM1's VmState, RenderArena, PbEpoch, and ComputeArena immediately, + // WHILE retaining its tiny VM-free firmware PB & UMA leases until overwritten! + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "VM1 VmState/TTBAT must release immediately"); + assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); + assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 2, "pb_mgr_table[0] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); + + // Cancelling an unpublished replacement on slot 0 / unit 0 must NOT release VM1's leases. + let pools3 = PoolSet::new_with_slots(&mut o, &factory, [0, 2]).unwrap(); + let uma3 = pools3.unit(0).unwrap().uma_lease(); + let r_arena3 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3.clone())), Some(uma3.clone())).unwrap(); + p.cancel_alloc(0); + assert_eq!(sync::Arc::strong_count(&uma1), 2); + assert_eq!(sync::Arc::strong_count(&uma3), 2); + + let mut cc3_cancel = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.release(&mut cc3_cancel); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2); + + // Once VM3 retires on exact hardware slot 0 / unit 0, firmware tables are overwritten and + // VM1's old FwLeases drop cleanly while VM3's leases become retained. + let e3 = g16::pools::PbEpoch::new( + &factory, + &vm3, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease3 = e3.records_lease(); + e3.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e3.expose(); + let b3 = p.bind(0, false); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3)), Some(uma3.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e3, b3, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); + assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); + + let mut cc3 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.publish(&mut cc3).unwrap(); + s.retire(&mut cc3).unwrap(); + assert_eq!(sync::Arc::strong_count(&c_uma1), 1, "overwritten compute uma_mgr_table[1] lease dropped"); + assert_eq!(sync::Arc::strong_count(&c_uma3), 3, "new compute UMA lease held by unit + retained_uma"); + let _ = WARM_PB_SLOTS; + } + } ''' poll_source = (production/'poll.rs').read_text() @@ -2031,6 +2439,9 @@ def module(text, name): assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' +assert 'closed_vm_reclaim' in mod_source +assert 'self.shared.closed_vm_reclaim.store(true, Ordering::Release);' in mod_source +assert 'reclaim_closed_vm_slots' in poll_source lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' @@ -2107,7 +2518,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 38, + 'result': 'pass', 'tests': 40, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From b2a65d203ce372d2b7f9478ba62e34b96ec7df2b Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 15:50:14 -0500 Subject: [PATCH 0884/1514] drm/asahi: g16: route SCS compute and base PB slots around quarantined slots After a firmware compute recovery permanently quarantines compute unit 0, brand-new VMs using the 2-unit SCS compute layout previously pinned themselves to hardware slots 0..2. Their first compute submission claimed and retired on unit 1 (the sole healthy slot in 0..2), leaving unit 1 as pipe 0's undisplaced latest retired lease so the second compute submission saw compute_exhausted_within(2) == true and immediately failed with ECANCELED, poisoning every subsequent fresh process. Track the live quarantined compute mask in Shared::quarantined_compute_mask and route ComputeUnitSet::new_scs onto two healthy hardware slots, preferring the pipe-0-reserved 0..PIPE1_COMPUTE_START range so pipe 1 cannot pin an undisplaced lease on SCS slots, then falling back across the remaining units. Apply the matching quarantined-slot skip when picking base warm PB slots for new render arenas. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 33 ++-- drivers/gpu/drm/asahi/g16/hw.rs | 12 +- drivers/gpu/drm/asahi/g16/mod.rs | 3 + drivers/gpu/drm/asahi/g16/poll.rs | 3 + drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 25 +++ drivers/gpu/drm/asahi/g16/queue.rs | 1 + drivers/gpu/drm/asahi/g16/resources.rs | 160 ++++++++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 116 +++++++++--- .../drivers/gpu/asahi-m4/test-publication.py | 34 ++-- .../drivers/gpu/asahi-m4/test-resources.py | 176 ++++++++++++++---- 10 files changed, 451 insertions(+), 112 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 26009c05701a57..64467a397408a9 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1114,8 +1114,8 @@ impl Firmware { && matches!(command(&job, job.progress.sent()), Some(Command::Compute(_))) && job .resources - .compute_units() - .is_ok_and(|n| self.slots.compute_exhausted_within(n)) + .compute_slot_mask() + .is_ok_and(|mask| self.slots.compute_exhausted_in_mask(mask)) { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -1351,8 +1351,8 @@ impl Firmware { && (compute_count >= params::compute_flights() || job .resources - .compute_units() - .is_ok_and(|units| !self.slots.compute_available(units))) + .compute_slot_mask() + .is_ok_and(|mask| !self.slots.compute_available_in_mask(mask))) } Some(Command::Render(_)) => { let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); @@ -1490,8 +1490,8 @@ impl Firmware { && super::recovery::logic::next_ordinal(e.ordinal).is_some() && job .resources - .compute_units() - .is_ok_and(|units| self.slots.compute_available(units)) + .compute_slot_mask() + .is_ok_and(|mask| self.slots.compute_available_in_mask(mask)) } Some(Command::Render(_)) => { let cross_vm_compute = e @@ -1796,8 +1796,9 @@ impl Firmware { } /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: - /// - Base-only VMs (`units <= BASE_COMPUTE_UNITS`) or states where pipe 1 has no available - /// extension unit stay on pipe 0 so base units `0..2` never split across two pipes. + /// - Base-only/SCS VMs (bits strictly in `0..PIPE1_COMPUTE_START`) or states where pipe 1 + /// has no available unit in `slot_mask` stay on pipe 0 so `0..PIPE1_COMPUTE_START` never + /// split across two pipes. /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` /// barrier). /// - If barrier-free (`[None, None]`) or waiting on both pipes (`[Some, Some]`), pick the @@ -1805,7 +1806,7 @@ impl Firmware { fn choose_compute_pipe( &self, waits: [Option; sizes::COMPUTE_PIPES], - units: usize, + slot_mask: u32, rt_compute: bool, ) -> usize { if rt_compute @@ -1814,8 +1815,7 @@ impl Firmware { .flights .iter() .any(|fl| fl.computes != 0 && fl.rt_compute) - || units <= super::resources::BASE_COMPUTE_UNITS - || !self.slots.compute_available_for_pipe(units, 1) + || !self.slots.compute_available_in_mask_for_pipe(slot_mask, 1) { return 0; } @@ -1823,7 +1823,7 @@ impl Firmware { [Some(_), None] => 0, [None, Some(_)] => 1, _ => { - if !self.slots.compute_available_for_pipe(units, 0) { + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { return 1; } let mut active = [0usize; sizes::COMPUTE_PIPES]; @@ -2059,7 +2059,7 @@ impl Firmware { let (compute_pipe, c_waits) = if render { (0usize, [None; sizes::COMPUTE_PIPES]) } else { - let units = job.resources.compute_units()?; + let slot_mask = job.resources.compute_slot_mask()?; let rt_compute = job.resources.compute_scs() || matches!(cmd, Command::Compute(c) if c.is_rt()); let waits = self.wait_compute_stamps_for( @@ -2067,7 +2067,7 @@ impl Firmware { job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, units, rt_compute), waits) + (self.choose_compute_pipe(waits, slot_mask, rt_compute), waits) }; let pipe_behind = !render && self @@ -2172,10 +2172,11 @@ impl Firmware { false, )?; let mut last_seq = job.command_order(index).map(|o| o.sequence); - let vm_units = job.resources.compute_units()?.min(sizes::COMPUTE_UNITS); + let slot_mask = job.resources.compute_slot_mask()?; let free_c = self .slots - .free_compute_in_for_pipe(vm_units, compute_pipe) as usize; + .free_compute_in_mask_for_pipe(slot_mask, compute_pipe) + as usize; let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; for fl in &self.engine.flights { if fl.computes != 0 { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 1e80e2303466c8..d556b290062e59 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -847,9 +847,17 @@ pub(crate) mod sizes { super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) <= super::engine::RENDER_UMA_SLOT ); - /// SCS-capable compute units per VM, which share ledger indices (and UMA slots) with the - /// first base units. + /// SCS-capable compute units per VM, bound dynamically to healthy compute ledger indices + /// (and UMA slots) preferring pipe-0-exclusive indices `0..PIPE1_COMPUTE_START`. pub(crate) const SCS_COMPUTE_UNITS: usize = 2; + /// First hardware compute ledger index usable by secondary compute pipes (`pipe >= 1`). + /// Keeping `0..PIPE1_COMPUTE_START` exclusive to pipe 0 guarantees that pipe 1 never holds + /// an undisplaced lease on those units, so 2-unit base-only and SCS compute VMs always have + /// at least one claimable unit across up to `PIPE1_COMPUTE_START - 2` permanent quarantines. + pub(crate) const PIPE1_COMPUTE_START: usize = 6; + const _: () = assert!( + PIPE1_COMPUTE_START >= SCS_COMPUTE_UNITS && PIPE1_COMPUTE_START + 2 <= COMPUTE_UNITS + ); /// Bytes of a base UMA pool (its seeds of 4 KiB). pub(crate) const POOL_BYTES: u64 = 0x2000000; const _: () = assert!( diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 0c870a79c49c0f..31e267b32760ef 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -294,6 +294,8 @@ pub(crate) struct Shared { pub(crate) recovering: AtomicBool, /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) has been quarantined. pub(crate) base_compute_quarantined: AtomicBool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: AtomicU32, /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. pub(crate) base_render_quarantined: AtomicBool, /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). @@ -666,6 +668,7 @@ impl Gpu { sleeping: AtomicBool::new(false), recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), + quarantined_compute_mask: AtomicU32::new(0), base_render_quarantined: AtomicBool::new(false), quarantined_pb_mask: AtomicU32::new(0), next_pb_slot: AtomicU32::new(0), diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e3252e36b2799b..2fca6c71513e64 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1379,6 +1379,9 @@ impl Firmware { shared .base_compute_quarantined .store(self.slots.base_compute_quarantined(), Ordering::Release); + shared + .quarantined_compute_mask + .store(self.slots.quarantined_compute_mask(), Ordering::Release); shared .base_render_quarantined .store(self.slots.base_render_quarantined(), Ordering::Release); diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 15e77396fcf7ac..d3cf6caf6084d3 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -118,6 +118,31 @@ impl Lifetime { .iter() .any(|u| matches!(u.state, State::Preparing | State::Published)) } + /// [`Self::exhausted`] restricted to owners selected by `mask` (bit `k` -> owner `k`). + pub(crate) fn exhausted_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < N && self.available(k) { + return false; + } + } + !self + .units + .iter() + .any(|u| matches!(u.state, State::Preparing | State::Published)) + } + /// Bitmask of permanently quarantined owners in `0..N.min(32)`. + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..N.min(32) { + if self.units[k].state == State::Quarantined { + mask |= 1u32 << k; + } + } + mask + } /// Whether any owner in `0..n` is permanently quarantined. pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 0b83aef27f1dc9..319232fd46334e 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -276,6 +276,7 @@ impl Queue { // No GPU completion lock is held; reclaim can wait for earlier hardware work. let hints = super::resources::PrepareHints { expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), + quarantined_compute_mask: self.shared.quarantined_compute_mask.load(Ordering::Acquire), expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), next_pb_slot: &self.shared.next_pb_slot, diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 84d5623728910b..a599515ffc0a90 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -91,6 +91,9 @@ impl ComputeArena { /// CDM pipe retains one undisplaced last-retired unit until displacement. pub(crate) struct ComputeUnitSet { units: KVec>, + /// Device-wide compute ledger indices bound to local SCS units `0..SCS_COMPUTE_UNITS`, or + /// `None` for contiguous base/extension sets whose local index equals the ledger index. + hw_slots: Option<[usize; super::hw::sizes::SCS_COMPUTE_UNITS]>, } impl ComputeUnitSet { /// Units `range` (each index and `placement` fix its client addresses; the index fixes its @@ -110,7 +113,38 @@ impl ComputeUnitSet { GFP_KERNEL, )?; } - Ok(Arc::new(Self { units }, GFP_KERNEL)?) + Ok(Arc::new( + Self { + units, + hw_slots: None, + }, + GFP_KERNEL, + )?) + } + /// SCS-capable compute units mapped at local VA indices `0..SCS_COMPUTE_UNITS` and bound to + /// device-wide healthy compute ledger indices `hw_slots`. + fn new_scs( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + hw_slots: [usize; super::hw::sizes::SCS_COMPUTE_UNITS], + seeds: u32, + ) -> Result> { + let mut units = KVec::with_capacity(super::hw::sizes::SCS_COMPUTE_UNITS, GFP_KERNEL)?; + for local in 0..super::hw::sizes::SCS_COMPUTE_UNITS { + units.push( + ComputeArena::new(factory, bind, vm, live, local, Placement::Scs { seeds })?, + GFP_KERNEL, + )?; + } + Ok(Arc::new( + Self { + units, + hw_slots: Some(hw_slots), + }, + GFP_KERNEL, + )?) } fn len(&self) -> usize { self.units.len() @@ -176,6 +210,8 @@ const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; pub(crate) struct PrepareHints<'a> { /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. pub(crate) expand_compute_ext: bool, + /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). + pub(crate) quarantined_compute_mask: u32, /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. pub(crate) expand_render_ext: bool, /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). @@ -186,6 +222,81 @@ pub(crate) struct PrepareHints<'a> { pub(crate) active_render_vms: &'a Arc, } +/// Selects `SCS_COMPUTE_UNITS` distinct hardware compute ledger indices for a VM's SCS compute +/// set, skipping permanently quarantined units in `quarantined_mask`. Scans from `0` up so +/// pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) are preferred before falling back to +/// `PIPE1_COMPUTE_START..max_units`. +fn pick_scs_compute_slots( + quarantined_mask: u32, + max_units: usize, +) -> [usize; super::hw::sizes::SCS_COMPUTE_UNITS] { + let limit = max_units + .min(super::hw::sizes::COMPUTE_UNITS) + .max(super::hw::sizes::SCS_COMPUTE_UNITS); + let mut out = [0usize; super::hw::sizes::SCS_COMPUTE_UNITS]; + let mut found = 0usize; + for k in 0..limit { + if (quarantined_mask & (1u32 << k)) == 0 { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + for k in 0..limit { + if !out[..found].contains(&k) { + out[found] = k; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + +/// Selects `[home, alt]` distinct physical PB/UMA allocator slots for a new `RenderArena`, +/// starting round-robin from `start % WARM_PB_SLOTS` and skipping permanently quarantined slots +/// in `quarantined_mask`. Scans `0..WARM_PB_SLOTS` first, then `WARM_PB_SLOTS..PB_SLOTS`, so +/// both base and `render_scs` VMs always start with two healthy PB slots after recovery. +fn pick_base_pb_slots(start: usize, quarantined_mask: u32) -> [usize; BASE_PB_SLOTS] { + let warm = super::hw::sizes::WARM_PB_SLOTS; + let total = super::hw::sizes::PB_SLOTS; + let mut out = [0usize; BASE_PB_SLOTS]; + let mut found = 0usize; + for i in 0..warm { + let slot = (start + i) % warm; + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for slot in warm..total { + if (quarantined_mask & (1u32 << slot)) == 0 { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + for i in 0..total { + let slot = (start + i) % total; + if !out[..found].contains(&slot) { + out[found] = slot; + found += 1; + if found == out.len() { + return out; + } + } + } + out +} + /// Updates the consecutive-compute burst counter and reports whether this submission /// qualifies to allocate extension compute units (`compute_ext`). /// @@ -889,15 +1000,17 @@ impl Cache { if compute_scs { match ready.compute_scs.as_ref().map(|set| set.seeds()) { None => { - ready.compute_scs = Some(ComputeUnitSet::new( + let hw_slots = pick_scs_compute_slots( + hints.quarantined_compute_mask, + super::params::compute_units(), + ); + ready.compute_scs = Some(ComputeUnitSet::new_scs( &self.factory, &self.bind, &vm.vm, &self.live, - 0..super::hw::sizes::SCS_COMPUTE_UNITS, - Placement::Scs { - seeds: compute_seeds.pool, - }, + hw_slots, + compute_seeds.pool, )?); } // The units cannot grow once the hardware may hold them. @@ -932,15 +1045,14 @@ impl Cache { } } if render && ready.render.is_none() { - let home = (hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize) - % super::hw::sizes::WARM_PB_SLOTS; - let alt = (home + 1) % super::hw::sizes::WARM_PB_SLOTS; + let start = hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize; + let base_pb_slots = pick_base_pb_slots(start, hints.quarantined_pb_mask); ready.render = Some(RenderArena::new( &self.factory, &self.bind, &vm.vm, &self.live, - [home, alt], + base_pb_slots, )?); if ready.render_vm_counter.is_none() { hints.active_render_vms.fetch_add(1, Ordering::AcqRel); @@ -1258,12 +1370,34 @@ impl Prepared { self.compute.as_deref().ok_or(EINVAL) } /// Compute units this job can use. + #[allow(dead_code)] pub(crate) fn compute_units(&self) -> Result { Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) } + /// Hardware compute ledger bitmask (bit `k` -> unit `k`) this job can use. + pub(crate) fn compute_slot_mask(&self) -> Result { + let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let mut mask = 0u32; + for slot in slots { + mask |= 1u32 << slot; + } + return Ok(mask); + } + let total = self.compute_units()?.min(super::hw::sizes::COMPUTE_UNITS); + Ok(if total >= 32 { + u32::MAX + } else { + (1u32 << total) - 1 + }) + } /// The per-unit arena holding compute unit `k`. pub(crate) fn compute_arena(&self, k: usize) -> Option> { let base = self.compute.as_ref()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k)?; + return base.arena(local); + } if k < base.len() { base.arena(k) } else { @@ -1454,9 +1588,13 @@ impl Prepared { .map(|(tier, _)| PassOwnerArena::Ext(tier.clone())) } } - /// Compute unit `k`: the VM's base units, then its extension units. + /// Compute unit `k`: the VM's base/SCS units, then its extension units. pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { let base = self.compute()?; + if let Some(slots) = base.hw_slots { + let local = slots.iter().position(|&slot| slot == k).ok_or(EINVAL)?; + return base.unit(local).ok_or(EINVAL); + } match base.unit(k) { Some(unit) => Ok(unit), None => self diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 8891434a0e52f7..22a83b59b690f6 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -923,9 +923,18 @@ impl Slots { .exhausted_within(super::params::compute_units()) } /// Whether none of the first `n` compute units (a VM's own) can ever be claimed again. + #[allow(dead_code)] pub(crate) fn compute_exhausted_within(&self, n: usize) -> bool { self.compute.lifetime.exhausted_within(n) } + /// Whether none of the compute units in `mask` (bit `k` -> unit `k`) can ever be claimed. + pub(crate) fn compute_exhausted_in_mask(&self, mask: u32) -> bool { + self.compute.lifetime.exhausted_in_mask(mask) + } + /// Bitmask of permanently quarantined compute units (`0..COMPUTE_UNITS`). + pub(crate) fn quarantined_compute_mask(&self) -> u32 { + self.compute.lifetime.quarantined_mask() + } pub(crate) fn render_exhausted(&self) -> bool { self.render.lifetime.exhausted() } @@ -949,20 +958,44 @@ impl Slots { [self.compute.lifetime.counts(), self.render.lifetime.counts()] } /// Whether one of the first `n` compute units can be claimed now. + #[allow(dead_code)] pub(crate) fn compute_available(&self, n: usize) -> bool { (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) } + /// Whether any compute unit in `mask` can be claimed now. + pub(crate) fn compute_available_in_mask(&self, mask: u32) -> bool { + let mut rem = mask; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + return true; + } + } + false + } + /// Whether any compute unit in `mask` eligible for `pipe` can be claimed now. + /// Pipe 0 may claim any bit in `mask`; secondary pipes stay in + /// `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` only ever hold pipe-0 + /// leases. + pub(crate) fn compute_available_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> bool { + let allowed = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + self.compute_available_in_mask(allowed) + } /// Whether one of the first `n` compute units eligible for `pipe` can be claimed now. - /// Pipe 0 may claim `0..n`; secondary pipes stay in `BASE_COMPUTE_UNITS..n` so a 2-unit - /// base-only VM can never see both base units undisplaced across two pipes. + #[allow(dead_code)] pub(crate) fn compute_available_for_pipe(&self, n: usize, pipe: usize) -> bool { let limit = n.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + let mask = if limit >= 32 { + u32::MAX } else { - super::resources::BASE_COMPUTE_UNITS.min(limit) + (1u32 << limit) - 1 }; - (start..limit).any(|k| self.compute.lifetime.available(k)) + self.compute_available_in_mask_for_pipe(mask, pipe) } /// Whether one of the first `n` render pass slots can be claimed now. #[allow(dead_code)] @@ -1161,20 +1194,37 @@ impl Slots { self.free_compute_in(super::params::compute_units()) } /// Available compute units within the first `n` units (a VM's prepared count). + #[allow(dead_code)] pub(crate) fn free_compute_in(&self, n: usize) -> u32 { self.free_compute_in_for_pipe(n, 0) } + /// Available compute units in `mask` eligible for `pipe`. + pub(crate) fn free_compute_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> u32 { + let mut rem = if pipe == 0 { + mask + } else { + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + let mut count = 0u32; + while rem != 0 { + let k = rem.trailing_zeros() as usize; + rem &= rem - 1; + if k < sizes::COMPUTE_UNITS && self.compute.lifetime.available(k) { + count += 1; + } + } + count + } /// Available compute units within the first `n` units eligible for `pipe`. + #[allow(dead_code)] pub(crate) fn free_compute_in_for_pipe(&self, n: usize, pipe: usize) -> u32 { let limit = n.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + let mask = if limit >= 32 { + u32::MAX } else { - super::resources::BASE_COMPUTE_UNITS.min(limit) + (1u32 << limit) - 1 }; - (start..limit) - .filter(|&k| self.compute.lifetime.available(k)) - .count() as u32 + self.free_compute_in_mask_for_pipe(mask, pipe) } /// Forces a full scrub on the next claim of every slot (after firmware recovery). #[allow(dead_code)] @@ -1241,25 +1291,26 @@ impl Slots { return Ok(None); } // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, - // before falling back to round-robin over `start..n`: pipe 0 spans `0..n`, while - // secondary pipes stay in `BASE_COMPUTE_UNITS..n` so base units `0..2` only ever hold - // pipe-0 leases and a 2-unit VM can never hit `compute_exhausted_within(2)`. - let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); - let start = if pipe == 0 { - 0 + // before falling back to round-robin over `allowed`: pipe 0 spans `mask`, while + // secondary pipes stay in `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` + // only ever hold pipe-0 leases and 2-unit base/SCS VMs never split across two pipes. + let mask = units.compute_slot_mask()?; + let allowed = if pipe == 0 { + mask } else { - super::resources::BASE_COMPUTE_UNITS + mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) }; - if start >= n { + if allowed == 0 { return Ok(None); } - let span = n - start; - let base_cursor = (self.cursor as usize).saturating_sub(start) % span; + let n = sizes::COMPUTE_UNITS; + let base_cursor = (self.cursor as usize) % n; let mut chosen = None; if let Some(id) = vm_id { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if !self.compute.scrub_full[k] + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 + && !self.compute.scrub_full[k] && self.compute.owner[k] .as_ref() .is_some_and(|prev| prev.id == id) @@ -1270,9 +1321,12 @@ impl Slots { } } if chosen.is_none() { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 + && self.compute.owner[k].is_none() + && self.compute.lifetime.claim(k) + { chosen = Some(k); break; } @@ -1280,9 +1334,9 @@ impl Slots { } } if chosen.is_none() { - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.lifetime.claim(k) { + for i in 0..n { + let k = (base_cursor + i) % n; + if (allowed & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { chosen = Some(k); break; } 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 310c27495708a3..8c32b1ff744a3c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -118,7 +118,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)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn compute_slot_mask(&self)->Result{Ok(0b11)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -153,7 +153,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 compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u32)->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;} @@ -177,7 +177,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const PIPE1_COMPUTE_START:usize=6; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -737,8 +737,13 @@ def item(declaration): 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 compute_available_in_mask(&self,_mask:u32)->bool{self.compute_available} + fn compute_available_in_mask_for_pipe(&self,mask:u32,pipe:usize)->bool{ + let allowed = if pipe == 0 { mask } else { mask & !((1u32 << hw::sizes::PIPE1_COMPUTE_START) - 1) }; + self.compute_available && allowed != 0 + } fn compute_available_for_pipe(&self,n:usize,pipe:usize)->bool{ - self.compute_available && (pipe == 0 || n > resources::BASE_COMPUTE_UNITS) + self.compute_available && (pipe == 0 || n > hw::sizes::PIPE1_COMPUTE_START) } fn pass_available(&self,_n:usize)->bool{self.pass_available} } @@ -1642,17 +1647,18 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); host.engine.flights.push(QueueBehindFlight{ job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 24, true), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, true), 0); // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 2, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], 0b11, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], 0b110, false), 0); assert!(host.can_queue_behind(&c2)); // Add second concurrent flight on pipe 1: both pipes active, // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. @@ -1662,9 +1668,9 @@ def item(declaration): has_timestamps:false,doomed:false,recovery_suspect:false, }); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 1); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], 24, false), 0); + assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1705,13 +1711,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w1, (1u32 << 24) - 1, false), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w2, (1u32 << 24) - 1, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1722,7 +1728,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, 24, false), 0); + assert_eq!(host.choose_compute_pipe(w2_ooo, (1u32 << 24) - 1, false), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1782,7 +1788,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,24,false),0); + assert_eq!(host.choose_compute_pipe(cw,(1u32<<24)-1,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; 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 f80781e1b20ae8..ee0fc783e7036a 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -176,7 +176,7 @@ def module(text, name): pub mod resources { use core::sync::atomic::{AtomicU64,Ordering};use crate::*; pub struct PassDirty<'a>{pub tpc:&'a AtomicU64,pub tilemap:&'a AtomicU64,pub tilemap_last:&'a AtomicU64,pub tilemap_clean:&'a AtomicU64,pub heap:&'a AtomicU64} - pub struct ComputeArena{pub compute:KVec,pub render:Option>} + pub struct ComputeArena{pub compute:KVec,pub render:Option>,pub hw_slots:Option<[usize;super::hw::sizes::SCS_COMPUTE_UNITS]>} // A job's compute units; here one arena. pub type Prepared=ComputeArena; #[derive(Clone)] @@ -199,10 +199,28 @@ def module(text, name): } 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_slot_mask(&self)->Result{ + if let Some(slots)=self.hw_slots { + let mut mask=0u32; + for slot in slots { mask |= 1u32 << slot; } + return Ok(mask); + } + let n=self.compute.len().min(super::hw::sizes::COMPUTE_UNITS); + Ok(if n>=32 { u32::MAX } else { (1u32 << n) - 1 }) + } + pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{ + if let Some(slots)=self.hw_slots { + let local=slots.iter().position(|&s|s==k).ok_or(EINVAL)?; + return self.compute.get(local).ok_or(EINVAL); + } + self.compute.get(k).ok_or(EINVAL) + } pub fn compute_arena(&self,k:usize)->Option>{ + let idx=if let Some(slots)=self.hw_slots { + slots.iter().position(|&s|s==k)? + } else { k }; COMPUTE_OWNER_ARENAS - .with(|a|a.borrow().as_ref().and_then(|v|v.get(k).cloned())) + .with(|a|a.borrow().as_ref().and_then(|v|v.get(idx).cloned())) .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) } pub fn render_arena(&self)->Option>{self.render.clone()} @@ -216,6 +234,7 @@ def module(text, name): impl RenderArena{ __SET_DIRTY__ } pub(crate) const BASE_COMPUTE_UNITS: usize = 2; pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; + const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; __RENDER_BURST__ } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} @@ -256,7 +275,7 @@ def module(text, name): let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} - Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:render_arena(passes)} + Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<bool{let mut q=g16::slots::ScrubQueue::new();q.push_batch(batch);let mut wake=false;while let Some(mut item)=q.pop(){wake|=item.run_one();}wake} @@ -1062,7 +1081,7 @@ def module(text, name): #[test]fn offlock_scrub_cleans_displaced_slot_and_skips_sync_scrub_on_same_vm_claim(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x2000,tilemap_bytes:0x4000}; // Publish and retire slot 0: not displaced yet, so nothing is staged. @@ -1113,7 +1132,7 @@ def module(text, name): #[test]fn offlock_scrub_falls_back_on_error_drop_recovery_and_cross_vm(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1);let b=vm(2); // Prime and displace slot 0. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; @@ -1164,7 +1183,7 @@ def module(text, name): #[test]fn post_publish_scrub_staging_does_not_block_immediate_slot_reuse(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; // Prime slot 0, then displace it by retiring slot 1; record retirement without staging yet. @@ -1206,7 +1225,7 @@ def module(text, name): for k in 0..hw::sizes::COMPUTE_UNITS { units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64).unwrap(),0).unwrap(); } - let prep=ComputeArena{compute:units,render:None}; + let prep=ComputeArena{compute:units,render:None,hw_slots:None}; let a=Arc::new( vm::VmState{id:1,slot:1,generation:1,vm:vm::MockVm::new()},0, ).unwrap(); @@ -1246,7 +1265,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; let a=vm(1); // Wrapped submission order [46, 47, 0]: retiring in order leaves slot 0 as last_retired // while high slots 46 and 47 (bits above 31) are displaced and reusable immediately. @@ -1308,7 +1327,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render)}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; let a=vm(1);let b=vm(2); // Per-unit compute hold_compute_slot + verify_held + note_published. @@ -1474,7 +1493,7 @@ def module(text, name): for k in 0..4u64 { units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_full=g16::resources::ComputeArena{compute:units,render:None}; + let prep_full=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; let a=vm(1);let b=vm(2); // Retire base unit 0, then hang and quarantine base unit 1 (or vice versa): // unit 0 is now retired-undisplaced and unit 1 is quarantined -> base [0..2] exhausted. @@ -1501,37 +1520,38 @@ def module(text, name): for k in 0..2u64 { base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); s.release(&mut c); } #[test]fn two_pipe_compute_out_of_order_retire_and_base_unit_isolation(){ let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; let mut units=KVec::new(); - for k in 0..4u64 { + for k in 0..(p1_start + 2) as u64 { units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep=g16::resources::ComputeArena{compute:units,render:None}; + let prep=g16::resources::ComputeArena{compute:units,render:None,hw_slots:None}; let a=vm(1);let b=vm(2); - // Pipe 0 claims unit 0; pipe 1 stays out of base units 0..2 and claims unit 2. + // Pipe 0 claims unit 0; pipe 1 stays out of 0..PIPE1_COMPUTE_START and claims PIPE1_COMPUTE_START. let mut c0=Claims::new(); let mut c1=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep,&mut c0,Some(a.id),0).unwrap(),Some(0)); assert_eq!(c0.compute_pipe,0); s.hold_vm(&c0,&a).unwrap();s.publish(&mut c0).unwrap(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(2)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1,Some(a.id),1).unwrap(),Some(p1_start)); assert_eq!(c1.compute_pipe,1); s.hold_vm(&c1,&a).unwrap();s.publish(&mut c1).unwrap(); // Pipe 1 finishes ahead of still-running pipe 0: retire must succeed (no EINVAL). assert_eq!(s.retire(&mut c1),Ok(())); - // Second pipe-1 flight claims unit 3 and retires, displacing unit 2 on pipe 1. + // Second pipe-1 flight claims PIPE1_COMPUTE_START + 1 and retires, displacing PIPE1_COMPUTE_START. let mut c1b=Claims::new(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(3)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1b,Some(a.id),1).unwrap(),Some(p1_start + 1)); s.hold_vm(&c1b,&a).unwrap();s.publish(&mut c1b).unwrap(); assert_eq!(s.retire(&mut c1b),Ok(())); - assert!(s.compute_available_for_pipe(4,1)); - // Now pipe 0's unit 0 retires: pipe 1's newer unit 3 must NOT mark unit 0 reusable, + assert!(s.compute_available_for_pipe(p1_start + 2,1)); + // Now pipe 0's unit 0 retires: pipe 1's newer retirement must NOT mark unit 0 reusable, // while base unit 1 remains fresh so a 2-unit base-only VM is never exhausted! assert_eq!(s.retire(&mut c0),Ok(())); assert!(!s.compute_exhausted_within(2)); @@ -1544,20 +1564,89 @@ def module(text, name): assert!(!s.compute_exhausted_within(2)); assert!(s.compute_available(2)); // A 2-unit base-only VM can claim displaced base unit 0 on pipe 0, while pipe 1 - // reclaims displaced extension unit 2 on the 4-unit VM without touching base units 0..2. + // reclaims displaced extension unit PIPE1_COMPUTE_START without touching 0..PIPE1_COMPUTE_START. let mut base_units=KVec::new(); for k in 0..2u64 { base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } - let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; + let prep_base=g16::resources::ComputeArena{compute:base_units,render:None,hw_slots:None}; let mut c0c=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep_base,&mut c0c,Some(b.id),0).unwrap(),Some(0)); let mut c1c=Claims::new(); - assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(2)); + assert_eq!(s.claim_compute_for_pipe(&prep,&mut c1c,Some(b.id),1).unwrap(),Some(p1_start)); s.release(&mut c0c); s.release(&mut c1c); } + #[test]fn scs_compute_and_base_pb_route_around_quarantined_slots(){ + use crate::g16::resources::{pick_base_pb_slots, pick_scs_compute_slots}; + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let p1_start = g16::hw::sizes::PIPE1_COMPUTE_START; + let mut full_units=KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + full_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); + } + let prep_full=g16::resources::ComputeArena{compute:full_units,render:None,hw_slots:None}; + let bad=vm(1);let fresh=vm(2);let other=vm(3); + // Exact dcp102b sequence: a prior process hangs and permanently quarantines compute unit 0. + let mut c=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c,Some(bad.id),0).unwrap(),Some(0)); + s.hold_vm(&c,&bad).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); + assert_eq!(s.quarantined_compute_mask(), 1u32 << 0); + // Pipe 1 runs concurrent non-SCS compute on PIPE1_COMPUTE_START..COMPUTE_UNITS. + let mut c_p1=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c_p1,Some(other.id),1).unwrap(),Some(p1_start)); + s.hold_vm(&c_p1,&other).unwrap();s.publish(&mut c_p1).unwrap();s.retire(&mut c_p1).unwrap(); + // Brand-new SCS compute VM skips quarantined unit 0 and binds [1, 2] (mask 0b110), both < PIPE1_COMPUTE_START. + let scs_slots = pick_scs_compute_slots(s.quarantined_compute_mask(), g16::hw::sizes::COMPUTE_UNITS); + assert_eq!(scs_slots, [1, 2]); + let mut scs_units=KVec::new(); + for local in 0..g16::hw::sizes::SCS_COMPUTE_UNITS as u64 { + scs_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,local).unwrap(),0).unwrap(); + } + let prep_scs=g16::resources::ComputeArena{compute:scs_units,render:None,hw_slots:Some(scs_slots)}; + let scs_mask = prep_scs.compute_slot_mask().unwrap(); + assert_eq!(scs_mask, (1u32 << 1) | (1u32 << 2)); + // Execute two back-to-back SCS compute commands (e.g. rt.scene p_rt + p_comp) repeatedly: + // must never hit compute_exhausted_in_mask and must ping-pong cleanly across [1, 2]. + for expected in [1usize, 2, 1, 2] { + assert!(!s.compute_exhausted_in_mask(scs_mask)); + assert!(s.compute_available_in_mask(scs_mask)); + let mut cs=Claims::new(); + assert_eq!(s.claim_compute_for_pipe(&prep_scs,&mut cs,Some(fresh.id),0).unwrap(),Some(expected)); + s.hold_vm(&cs,&fresh).unwrap();s.publish(&mut cs).unwrap();s.retire(&mut cs).unwrap(); + } + // Up to 4 quarantines in 0..PIPE1_COMPUTE_START stay inside pipe-0-exclusive 0..6; beyond that falls back cleanly. + assert_eq!(pick_scs_compute_slots(0b001111, g16::hw::sizes::COMPUTE_UNITS), [4, 5]); + assert_eq!(pick_scs_compute_slots(0b111111, g16::hw::sizes::COMPUTE_UNITS), [6, 7]); + // Twin fix: pick_base_pb_slots skips quarantined warm PB slots and falls back to EXT_PB_SLOTS. + assert_eq!(pick_base_pb_slots(0, 0), [0, 1]); + assert_eq!(pick_base_pb_slots(3, 1u32 << 3), [4, 5]); + assert_eq!(pick_base_pb_slots(3, (1u32 << 3) | (1u32 << 4)), [5, 6]); + let all_warm_but_one = ((1u32 << g16::hw::sizes::WARM_PB_SLOTS) - 1) & !(1u32 << 7); + assert_eq!(pick_base_pb_slots(0, all_warm_but_one), [7, g16::hw::sizes::WARM_PB_SLOTS]); + // Confirm Pools::exhausted_for_mask_mode stays false for render_scs with picked healthy slots. + let mut pools = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let bad_vm = vm(10); + let good_vm = vm(11); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let ep = g16::pools::PbEpoch::new( + &factory, + &bad_vm, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ) + .unwrap(); + ep.prepare(3, 0x70c0000000, 2048).unwrap(); + ep.expose(); + pools.publish_flight(3); + pools.quarantine_flight(3, Some(ep)); + let picked = pick_base_pb_slots(3, pools.quarantined_mask()); + assert_eq!(picked, [4, 5]); + let pb_mask = (1u32 << picked[0]) | (1u32 << picked[1]); + assert!(!pools.exhausted_for_mask_mode(&good_vm, pb_mask, picked[0], true)); + } + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); @@ -1566,7 +1655,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render)}; + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render),hw_slots:None}; let a=vm(1);let b=vm(2); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x1000}; // Retire base pass slot 0, then hang and quarantine base pass slot 1 -> base [0..2] exhausted. @@ -1598,7 +1687,7 @@ def module(text, name): use crate::g16::slots::ScrubQueue; let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); - let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render.clone()),hw_slots:None}; let a=vm(1); let geo=g16::encode::Geometry{tpc_bytes:0x1000,tilemap_bytes:0x2000}; // Prime and displace slot 0. @@ -1659,7 +1748,7 @@ def module(text, name): passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); - let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone())}; + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; let a=vm(1);let b=vm(2); let pub_retire=|s:&mut Slots,k:usize,vm:&sync::Arc|{ let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1u64< = (0..16u64).map(|i| vm(200 + i)).collect(); @@ -2096,7 +2186,7 @@ def module(text, name): for k in 0..18 { passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } - let shared_prep_compute = ComputeArena { compute: compute_slots, render: None }; + let shared_prep_compute = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; let mut vms = Vec::new(); @@ -2114,9 +2204,9 @@ def module(text, name): r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); - let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()) }; + let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()), hw_slots: None }; let c_arena = sync::Arc::new( - ComputeArena { compute: KVec::new(), render: None }, 0, + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, 0, ).unwrap(); // 1) PB warm slot i @@ -2205,7 +2295,7 @@ def module(text, name): // Live VM 17 runs 1 render + 1 compute, displacing slot 15 everywhere. let live = vm(500); let live_r_arena = sync::Arc::new(render_arena(passes), 0).unwrap(); - let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()) }; + let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()), hw_slots: None }; let live_slot = p .pick_slot_in_mask_blocks_mode(&live, false, 0b11, 0, 512, false) .unwrap(); @@ -2281,7 +2371,7 @@ def module(text, name): sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); } let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); - let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()) }; + let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()), hw_slots: None }; let va = vm(600); let vb = vm(601); for (k, owner) in [(0usize, &va), (1usize, &vb)] { @@ -2341,7 +2431,7 @@ def module(text, name): for k in 0..COMPUTE_UNITS { compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); } - let prep = ComputeArena { compute: compute_slots, render: None }; + let prep = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). @@ -2352,7 +2442,11 @@ def module(text, name): let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); for _ in 0..COMPUTE_UNITS { per_unit.push( - sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(), ); } COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); @@ -2468,8 +2562,12 @@ def module(text, name): units1.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); } let c_uma1 = units1[0].uma_lease(); - let prep1 = ComputeArena { compute: units1, render: None }; - let c_arena1 = sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(); + let prep1 = ComputeArena { compute: units1, render: None, hw_slots: None }; + let c_arena1 = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None, hw_slots: None }, + 0, + ) + .unwrap(); let mut cc1 = Claims::new(); assert_eq!(s.claim_compute_for(&prep1, &mut cc1, Some(vm1.id)).unwrap(), Some(0)); COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena1.clone())); @@ -2482,7 +2580,7 @@ def module(text, name): for k in 0..COMPUTE_UNITS { units2.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); } - let prep2 = ComputeArena { compute: units2, render: None }; + let prep2 = ComputeArena { compute: units2, render: None, hw_slots: None }; let mut cc2 = Claims::new(); assert_eq!(s.claim_compute_for(&prep2, &mut cc2, Some(vm2.id)).unwrap(), Some(1)); s.hold_compute_slot(1, &vm2, &prep2).unwrap(); @@ -2492,7 +2590,7 @@ def module(text, name): let mut units3 = KVec::new(); units3.push(ComputeSlot::new(&mut o, &factory, 0).unwrap(), 0).unwrap(); let c_uma3 = units3[0].uma_lease(); - let prep3 = ComputeArena { compute: units3, render: None }; + let prep3 = ComputeArena { compute: units3, render: None, hw_slots: None }; // Drop local arena/epoch/pool handles for VM1 and close VM1. drop(e1); @@ -2682,6 +2780,8 @@ def module(text, name): line for line in resources_source.splitlines() if line.startswith(('const BURST_SUBMITS:', 'const BURST_GAP_NS:', 'const BURST_COMMANDS:', 'const RENDER_BURST_COMMANDS:')) ) + + '\npub(crate) ' + item(resources_source, 'fn pick_scs_compute_slots(') + + '\npub(crate) ' + item(resources_source, 'fn pick_base_pb_slots(') + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots_for(') From eba58542113b3cd3a16ee8f9a4bc1c813f1e11dc Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 01:19:33 -0500 Subject: [PATCH 0885/1514] drm/asahi: g16: cap TA wave depth at 4 passes and fix ta_wave_wait wakeups Keep the TA wave cap at 4 passes (TA_WAVE_PASSES = 4) with hysteresis refill at 2 (TA_WAVE_REFILL = 2), and keep non_terminal_only clear while ta_wave_wait is active so TA-only (0x70) interrupts wake and refill stalled TA waves without spinning once ta_wave_wait clears. Always advance render.threshold[0] alongside render.threshold[8] to prefix.draw as u32 in publish_prefix_body(): firmware only updates notifier_page::TA_STAMP and notifier::CONTEXT when notifier.cur_count == *render.threshold[0], so holding threshold[0] at an earlier unfinished TA flight drops TA_STAMP on fast tail flights whose TA finishes before host rearm, causing a permanent Retirement::Pending -> 5 s ETIMEDOUT fail-stop (seen on render.shadow(d32f, depth_only, 2048) d=2). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 6 +- drivers/gpu/drm/asahi/g16/hw.rs | 11 ++-- drivers/gpu/drm/asahi/g16/poll.rs | 16 ++++-- .../drivers/gpu/asahi-m4/test-poll-retire.py | 44 +++++++++++---- .../drivers/gpu/asahi-m4/test-publication.py | 56 ++++++++++--------- 5 files changed, 83 insertions(+), 50 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 14696fb27aa717..4552f85bce08f7 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -286,7 +286,7 @@ pub(crate) struct Flight { pub(crate) target: u32, pub(crate) head: u32, pub(crate) c_start: u32, - /// Render: final TA/FS stamps, ring ends and ring positions before the prefix. + /// Render: final TA/FS stamps, ring ends and ring positions. pub(crate) ta_target: u32, pub(crate) fs_target: u32, pub(crate) ta_head: u32, @@ -2475,7 +2475,9 @@ impl Firmware { .publish_pb_batch(a, f.uma_submitted, f.renders)?; self.pools.publish_flight(a); // Notifier service dereferences u32 counters; the host ordering ledger - // remains u64. Eight-byte spacing is retained allocation padding. + // remains u64. Eight-byte spacing is retained allocation padding. Always + // advance both TA and FS thresholds to the newest published draw ordinal + // so firmware never skips updating `TA_STAMP` on fast tail flights. self.graph.render.threshold.w32(0, prefix.draw as u32)?; self.graph.render.threshold.w32(8, prefix.draw as u32)?; } else { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 31b28156527f6d..a9c5cad5814db5 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -734,10 +734,13 @@ pub(crate) mod sizes { /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + cross-pipe /// `c2c` barrier + `work`). pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 3; - /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts pace - /// TA in `<= 8`-pass waves without throttling single-pass pipelining (where TA finishes - /// well ahead of FS). - pub(crate) const TA_WAVE_PASSES: usize = 8; + /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts stay + /// inside M4 firmware's `<= 4`-pass TA/scene pipeline without throttling single-pass + /// pipelining (where TA finishes well ahead of FS). + pub(crate) const TA_WAVE_PASSES: usize = 4; + /// Unfinished TA pass count at or below which a TA-wave-paused render queue wakes to + /// launch the next wave, avoiding 1-pass stub drips. + pub(crate) const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most. A slot is reused only after a later render diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 857160a0b737f9..61567df95f16b4 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -681,14 +681,16 @@ impl Firmware { } published?; // A TA-only (0x70) EP 0x20 interrupt while FS is still running does not signal flight - // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it. + // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it, + // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`). let non_terminal_only = !retired_any && term_before.is_some() && self.events.stage_events != stage_before && self.oldest_terminal_events() == term_before && !self.oldest_stamp_reached() && !self.recovery.receipt_fault - && !recovery_pending; + && !recovery_pending + && !self.engine.ta_wave_wait; // 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 tail waits per interrupt. @@ -714,12 +716,13 @@ impl Firmware { } // If a terminal EP 0x20 event arrived with flights outstanding and nothing retired within // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring - // headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. + // or TA-wave headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. self.engine.short_repoll = !self.engine.flights.is_empty() && !self.engine.frozen && !non_terminal_only && ((evented && had_flights && !retired_any) - || (!self.engine.pending.is_empty() && self.engine.slot_wait)); + || (!self.engine.pending.is_empty() + && (self.engine.slot_wait || self.engine.ta_wave_wait))); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() @@ -780,9 +783,10 @@ impl Firmware { Some((compute, render)) } - /// Whether a render job paused by `TA_WAVE_PASSES` pacing can publish its next wave now. + /// Whether a render job paused by `TA_WAVE_PASSES` pacing has enough TA headroom to publish + /// the next wave without dribbling 1-pass stub flights. fn ta_wave_ready(&self) -> bool { - self.engine.ta_wave_wait && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES + self.engine.ta_wave_wait && self.ta_pending_passes() <= super::hw::sizes::TA_WAVE_REFILL } /// Cheap single-stage stamp check for the oldest compute pipe 0/1 and oldest render flights' diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index f2d13a6a708049..5a7a7b3e5ba362 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -65,7 +65,8 @@ def item(declaration, text=source): const EVENT_RETIRE_POLLS: u32 = 11; mod hw { pub mod sizes { - pub const TA_WAVE_PASSES: usize = 8; + pub const TA_WAVE_PASSES: usize = 4; + pub const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; pub const COMPUTE_PIPES: usize = 2; } } @@ -891,41 +892,60 @@ def item(declaration, text=source): } #[test] -fn ta_only_irq_wakes_ta_wave_wait_without_spinning_retry_tail() { +fn ta_only_irq_wakes_ta_wave_wait_with_hysteresis_and_short_repoll() { CLOCK.with(|c| c.set(100_000)); let mut fw = Firmware::new(); fw.engine.flights.push(Flight { computes: 0, compute_pipe: 0, - renders: 8, + renders: 4, target: 0, - fs_target: 0x800, + fs_target: 0x400, }); - fw.engine.fs_target = 0x800; + fw.engine.fs_target = 0x400; fw.engine.pending.push(Arc::new(Job { id: 2 })); fw.engine.ta_wave_wait = true; - fw.ta_pending = 8; + fw.ta_pending = 4; fw.drain_stage_delta = 1; fw.drain_fs_delta = 0; let mut retry_tail = false; let mut deferred = false; let mut done = vec![]; - // TA still full (8 >= 8): no publish_checked wakeup and no retry_tail spin. + // TA still full (4 > TA_WAVE_REFILL=2): no publish_checked wakeup yet, but ta_wave_wait + // keeps non_terminal_only false so a 0x70 IRQ retries tail. assert!(fw .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) .unwrap()); assert_eq!(fw.publish_checked_calls, 0); + assert!(retry_tail); + + // TA drops to 3 (> TA_WAVE_REFILL=2): hysteresis avoids 1-pass stub drip, while + // tail == 0 arms short_repoll because ta_wave_wait is active. + fw.ta_pending = 3; + retry_tail = false; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); assert!(!retry_tail); - assert!(!fw.engine.short_repoll); + assert!(fw.engine.short_repoll); - // TA finishes one pass (ta_pending drops to 7 < 8) on a TA-only 0x70 IRQ while FS is still - // running: immediately wakes publish_checked() without spinning retry_tail or short_repoll. - fw.ta_pending = 7; + // TA drains to 2 (<= TA_WAVE_REFILL): immediately wakes publish_checked() to launch the + // next wave cleanly. + fw.ta_pending = 2; assert!(fw - .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) .unwrap()); assert_eq!(fw.publish_checked_calls, 1); + assert!(fw.engine.short_repoll); + + // Once ta_wave_wait clears, a TA-only 0x70 IRQ stays non_terminal_only (no spin/short_repoll). + fw.engine.ta_wave_wait = false; + retry_tail = false; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); assert!(!retry_tail); assert!(!fw.engine.short_repoll); } 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 42e780e42f5f57..2e6c4d7f5182dd 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -76,6 +76,10 @@ def item(declaration): assert 'bar_type,' in fs2c_slice and 'BarrierType::Hold' not in fs2c_slice assert 'let waits_for_timestamps = c.query_access' in can_queue_behind_fn assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src +publish_prefix_body_fn = item('fn publish_prefix_body(') +assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn +assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn +assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source harness = r''' @@ -167,7 +171,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=8; pub const COMPUTE_PIPES:usize=2; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -608,18 +612,18 @@ def item(declaration): assert_eq!(f.attempted,[1,2]); assert_eq!(f.session.rings,[Channel::Compute,Channel::Fs,Channel::Ta]); } - #[test]fn ta_wave_pacing_flushes_doorbell_at_eight_passes_and_arms_ta_wave_wait(){ + #[test]fn ta_wave_pacing_flushes_doorbell_at_four_passes_and_arms_ta_wave_wait(){ let vm1=mk_vm(1); - let mut jobs:Vec>=(1..=9).map(|id|job_on_vm(id,vm1.clone(),true,0,Ok(()))).collect(); - jobs.push(job_on_vm(10,vm1,false,0,Ok(()))); - let stages=vec![(Ok(()),true);9]; + let mut jobs:Vec>=(1..=5).map(|id|job_on_vm(id,vm1.clone(),true,0,Ok(()))).collect(); + jobs.push(job_on_vm(6,vm1,false,0,Ok(()))); + let stages=vec![(Ok(()),true);5]; let mut f=firmware(jobs,stages); f.allow_behind=true; let mut done=vec![]; assert_eq!(f.publish_checked(&mut done),Ok(())); - // Passes 1..8 fill TA_WAVE_PASSES (8) and ring FS+TA immediately; pass 9 pauses with - // ta_wave_wait=true while alt compute job 10 still publishes on Compute. - assert_eq!(f.attempted,[1,2,3,4,5,6,7,8,10]); + // Passes 1..4 fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses with + // ta_wave_wait=true while alt compute job 6 still publishes on Compute. + assert_eq!(f.attempted,[1,2,3,4,6]); assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); assert!(f.engine.ta_wave_wait); assert!(!f.engine.slot_wait); @@ -634,9 +638,9 @@ def item(declaration): commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, }); - // Seed 8 active TA passes so TA wave pacing is active. + // Seed 4 active TA passes so TA wave pacing is active. let mut active_flights=Vec::new(); - for id in 1..=8 { + for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; active_flights.push(fl); @@ -655,7 +659,7 @@ def item(declaration): // query_access compute on the same queue must NOT bypass TA-wave-paused render. let mut f_q=firmware(vec![mk(11,true,false,Ok(())),mk(12,false,true,Ok(()))],vec![]); - for id in 1..=8 { + for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; f_q.engine.flights.push(fl); @@ -666,7 +670,7 @@ def item(declaration): // Dependent compute (dependency Err(EAGAIN)) must NOT bypass TA-wave-paused render. let mut f_dep=firmware(vec![mk(13,true,false,Ok(())),mk(14,false,false,Err(EAGAIN))],vec![]); - for id in 1..=8 { + for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; f_dep.engine.flights.push(fl); @@ -680,7 +684,7 @@ def item(declaration): vec![mk(15,true,false,Ok(())),mk(16,false,true,Ok(())),mk(17,false,false,Ok(()))], vec![], ); - for id in 1..=8 { + for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; f_cc.engine.flights.push(fl); @@ -1225,34 +1229,34 @@ def item(declaration): let r_live=mk(1); let next_r=mk(2); let mut r_ta=[0u32;16]; - for i in 0..8 { + for i in 0..4 { r_ta[i]=(i as u32 + 1)*0x100; } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:8,computes:0,renders:7,compute_pipe:0,target:0,cstamp:[0;16], - r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, + engine:QueueBehindEngine{ordinal:0,draw:4,ta_target:0x400,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x400, 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,block_pipeline_vm:None}, }; - // Below TA_WAVE_PASSES (7 < 8): zero WC fw_stamp reads. - assert_eq!(p.ta_pending_passes(),7); + // Below TA_WAVE_PASSES (3 < 4): zero WC fw_stamp reads. + assert_eq!(p.ta_pending_passes(),3); assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); assert!(p.can_queue_behind(&next_r)); - // 8 unfinished TA passes: paces render queue_behind until TA advances. - p.engine.flights[0].renders=8; - assert_eq!(p.ta_pending_passes(),8); + // 4 unfinished TA passes: paces render queue_behind until TA advances. + p.engine.flights[0].renders=4; + assert_eq!(p.ta_pending_passes(),4); assert!(p.graph.render.fw_stamp[0].reads.get()>0); assert!(!p.can_queue_behind(&next_r)); - // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 7. + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 3. p.graph.render.fw_stamp[0].val.set(0x100); - assert_eq!(p.ta_pending_passes(),7); + assert_eq!(p.ta_pending_passes(),3); assert!(p.can_queue_behind(&next_r)); - // Even with 16 active FS passes, finished TA (obs=0x800) leaves single-pass pipelining unthrottled. - p.graph.render.fw_stamp[0].val.set(0x800); + // Even with 16 active FS passes, finished TA (obs=0x400) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x400); p.engine.flights[0].renders=16; assert_eq!(p.ta_pending_passes(),0); assert!(p.can_queue_behind(&next_r)); From 6bd4317e47e0d9b71b05bd13860b5cc88ce00bdd Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 12:59:21 -0500 Subject: [PATCH 0886/1514] drm/asahi/g16: split compute arenas per unit to bound closed-VM pins With two independent CDM pipes (COMPUTE_PIPES = 2), multi-process compute leaves one undisplaced last-retired compute unit on pipe 0 and one on pipe 1 (22 of 24 units reusable). Because firmware may still reference each pipe's last-retired unit until a later retired publication on that same pipe displaces it, those two owner leases must remain pinned. Previously, Ready::compute_ext backed all 22 extension compute units (2..24) inside a single monolithic Arc (~713 MiB). Holding a lease on one undisplaced extension unit pinned all 22 units of its closed VM; across two CDM pipes that retained ~1.40 GiB (+1,464 MiB Unevictable) instead of 2 x ~32.4 MiB (~65 MiB). Split compute unit backing so each ComputeArena owns a single self-contained ComputeSlot and introduce ComputeUnitSet (a KVec of per-unit Arc) for Ready::{compute, compute_ext} and Prepared::{compute, compute_ext}: - Prepared::compute_arena(k) returns only unit k's Arc, keeping zero-alloc Cache::prepare() cloning intact. - When a VM closes, Cache::close() and Slots::reclaim_closed() drop every unused or displaced unit immediately while each pipe's undisplaced (or quarantined) slot pins only its own ~32.4 MiB unit (~22x reduction). - Add dual-pipe per-unit closed-VM reclamation coverage in test-resources.py. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/resources.rs | 89 ++++++++++++----- .../drivers/gpu/asahi-m4/test-resources.py | 99 ++++++++++++++++++- 2 files changed, 158 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 271b3867da4242..c3b5d0acfed904 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -27,6 +27,8 @@ use kernel::{ /// avoids allocating and mapping fresh epochs whenever submission depth rises. const SPARE_EPOCHS: usize = 32; +/// Backing for one physical compute unit (`k`) of a VM, deferred-dropped independently so an +/// undisplaced last-retired owner lease on one CDM pipe never pins the VM's other compute units. pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { type Target = ComputeInner; @@ -35,7 +37,7 @@ impl core::ops::Deref for ComputeArena { } } pub(crate) struct ComputeInner { - pub(crate) compute: KVec, + pub(crate) unit: ComputeSlot, _objects: Objects, // Mappings must disappear while their root still owns its ASID. _bind: mmu::VmBind, @@ -53,26 +55,21 @@ 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). + /// Allocates one self-contained compute unit `k` (its index fixes its client addresses and + /// hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - units: core::ops::Range, + k: usize, ) -> Result> { let mut objects = factory.objects(vm); - let mut compute = KVec::with_capacity(units.len(), GFP_KERNEL)?; - for k in units { - compute.push( - ComputeSlot::new(&mut objects, factory, k as u64)?, - GFP_KERNEL, - )?; - } + let unit = ComputeSlot::new(&mut objects, factory, k as u64)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { - compute, + unit, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -82,6 +79,43 @@ impl ComputeArena { } } +/// Contiguous range of independently reference-counted [`ComputeArena`] units owned by a VM. +/// +/// Each unit `k` owns its own `Arc` so `Cache::close()` and +/// `Slots::reclaim_closed()` release all unused or displaced units immediately even while a +/// CDM pipe retains one undisplaced last-retired unit until displacement. +pub(crate) struct ComputeUnitSet { + units: KVec>, +} +impl ComputeUnitSet { + /// Units `range` (each index fixes its client addresses and hardware UMA slot). + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + range: core::ops::Range, + ) -> Result> { + let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; + for k in range { + units.push( + ComputeArena::new(factory, bind, vm, live, k)?, + GFP_KERNEL, + )?; + } + Ok(Arc::new(Self { units }, GFP_KERNEL)?) + } + fn len(&self) -> usize { + self.units.len() + } + fn unit(&self, idx: usize) -> Option<&ComputeSlot> { + self.units.get(idx).map(|arena| &arena.unit) + } + fn arena(&self, idx: usize) -> Option> { + self.units.get(idx).cloned() + } +} + /// Render pass slots every VM gets with its first render command; extension slots /// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are grown lazily in bounded tiers once the VM /// pipelines renders or submits multi-pass/burst frames. @@ -546,9 +580,9 @@ impl PassOwnerArena { #[derive(Default)] struct Ready { - compute: Option>, + compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. - compute_ext: Option>, + compute_ext: Option>, render: Option>, /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -778,7 +812,7 @@ impl Cache { return Err(EIO); } if compute && ready.compute.is_none() { - ready.compute = Some(ComputeArena::new( + ready.compute = Some(ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, @@ -800,7 +834,7 @@ impl Cache { hints.expand_compute_ext, ) { // Best effort: without them the VM keeps the base compute units. - state.compute_ext = ComputeArena::new( + state.compute_ext = ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, @@ -1081,9 +1115,9 @@ impl Cache { /// Immutable references carried by an accepted job. No fallible lazy work in the engine. pub(crate) struct Prepared { - pub(crate) compute: Option>, + pub(crate) compute: Option>, /// The VM's extension compute units when the job was prepared. - pub(crate) compute_ext: Option>, + pub(crate) compute_ext: Option>, pub(crate) render: Option>, /// The VM's demand-grown extension render pass tiers when the job was prepared. pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -1113,21 +1147,22 @@ impl Drop for Prepared { } } impl Prepared { - pub(crate) fn compute(&self) -> Result<&ComputeArena> { + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { 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())) + Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) } - /// The arena holding compute unit `k`. + /// The per-unit 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()) + if k < base.len() { + base.arena(k) } else { - self.compute_ext.clone() + self.compute_ext + .as_ref() + .and_then(|ext| ext.arena(k - base.len())) } } /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. @@ -1294,13 +1329,13 @@ impl Prepared { } /// 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) { + let base = self.compute()?; + match base.unit(k) { Some(unit) => Ok(unit), None => self .compute_ext .as_deref() - .and_then(|e| e.compute.get(k - base.len())) + .and_then(|e| e.unit(k - base.len())) .ok_or(EINVAL), } } 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 efbe9e2b7a2f39..458a57a99a8dc9 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -193,12 +193,17 @@ def module(text, name): pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< Option>, >=const{std::cell::RefCell::new(None)}; + pub static COMPUTE_OWNER_ARENAS:std::cell::RefCell< + Option>>, + >=const{std::cell::RefCell::new(None)}; } 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>{ - COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone()) + pub fn compute_arena(&self,k:usize)->Option>{ + COMPUTE_OWNER_ARENAS + .with(|a|a.borrow().as_ref().and_then(|v|v.get(k).cloned())) + .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) } pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} @@ -2429,6 +2434,90 @@ def module(text, name): let _ = WARM_PB_SLOTS; } + #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; + use g16::slots::ComputeSlot; + + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: compute_slots, render: None }; + + // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas + // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). + let mut vms = Vec::new(); + let mut vm_unit_arenas: Vec>> = Vec::new(); + for i in 0..8usize { + let v = vm(800 + i as u64); + let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); + for _ in 0..COMPUTE_UNITS { + per_unit.push( + sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + ); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); + vms.push(v); + vm_unit_arenas.push(per_unit); + } + + // Close all 8 VMs and reclaim displaced leases: + // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. + // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned + // (strong_count == 2); all 190 other units (including the other 23 units of each + // last-retired VM) drop immediately (strong_count == 1). + for v in &vms { + v.vm.close(); + } + assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); + assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); + let pinned_units: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); + for (i, units) in vm_unit_arenas.iter().enumerate() { + let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); + if i == 7 { + assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); + } else { + assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); + } + } + + // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. + let live = vm(900); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &live, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); + let pinned_after: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_after, 0); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); + } + } } ''' poll_source = (production/'poll.rs').read_text() @@ -2474,6 +2563,10 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' +assert 'ComputeArena::new(factory, bind, vm, live, k)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' +assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' +assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -2518,7 +2611,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 40, + 'result': 'pass', 'tests': 41, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 2cd448a3c82834fd9cdf8a61bf76a20228011459 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 17:17:23 -0500 Subject: [PATCH 0887/1514] drm/asahi: g16: say which side stalled when M4 recovery times out When a firmware recovery does not finish within its 1000 ms budget, recover() only logs "M4 GPU recovery exceeded 1000 ms" and fail-stops. On a live M4 recovery timeout after a type-4 event and its statistics record, the log could not tell whether the firmware never halted in phase 1 or the host acknowledged phase 1 and phase 3 never came. It also could not tell whether tiling or fragment work was left behind; the stats showed seven render owners still published. Keep the last phase the host read and name the stall from it and from whether the host had answered (recovery::logic::Stall). Also print the observed TA and FS stamps next to the newest published ones, and the number of flights retained. The message keeps its prefix, so existing log matching still works. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/recovery.rs | 16 ++++++- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 48 +++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 8e9b9a61e3bab9..6ed3120b70b576 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -425,16 +425,30 @@ impl Firmware { let deadline = start.saturating_add(logic::RECOVERY_BUDGET_NS); let mut answered = false; let mut generation = 0; + let mut last_phase = 0; loop { if let Some(error) = self.transport_error() { return Err(error); } let now = now_ns(); if logic::expired(now, deadline) { - dev_err!(self.dev(), "M4 GPU recovery exceeded 1000 ms\n"); + // Which side stalled, and whether tiling or fragment work was left behind. + let stage = self.recovery_snapshot().unwrap_or_default(); + dev_err!( + self.dev(), + "M4 GPU recovery exceeded 1000 ms: {} (phase {}, TA {:#x}/{:#x}, FS {:#x}/{:#x}, {} flights)\n", + logic::Stall::of(last_phase, answered).describe(), + last_phase, + stage[0], + self.engine.ta_target, + stage[1], + self.engine.fs_target, + self.engine.flights.len() + ); return Err(ETIMEDOUT); } let phase = self.firmware_r32(self.init.firmware_data().phase)?; + last_phase = phase; let current_generation = if phase == 1 || phase == 3 { self.firmware_generation()? } else { diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index f93b2cd35f4ffe..a0b9641e51c194 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -102,6 +102,36 @@ pub(crate) fn action(phase: u32, answered: bool, generation_matches: bool) -> Re } } +/// Where a recovery that ran past [`RECOVERY_BUDGET_NS`] stopped, from the last phase the host +/// read and whether the host had acknowledged phase 1 ([`action`]'s inputs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stall { + /// The firmware announced a recovery but never published phase 1. + NotHalted, + /// The firmware published phase 1 and the host had not acknowledged it. + NotAcknowledged, + /// The host acknowledged phase 1 and the firmware never published phase 3. + NotResumed, +} + +impl Stall { + pub(crate) const fn of(phase: u32, answered: bool) -> Self { + match (phase, answered) { + (_, true) => Self::NotResumed, + (1, false) => Self::NotAcknowledged, + _ => Self::NotHalted, + } + } + + pub(crate) const fn describe(self) -> &'static str { + match self { + Self::NotHalted => "firmware never halted in phase 1", + Self::NotAcknowledged => "phase 1 not acknowledged", + Self::NotResumed => "firmware never published phase 3", + } + } +} + /// One valid-prefix entry of the firmware's snapshot. Invalid entries terminate it. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct SnapshotEntry { @@ -249,6 +279,24 @@ mod tests { assert_eq!(action(3, true, false), RecoveryAction::ProtocolError); } + #[test] + fn budget_overrun_names_the_phase_that_never_arrived() { + // dcp103b: a type-4 event and its statistics arrived, then 1000 ms passed. Which side + // stalled follows from the last phase read and whether the host had answered. + assert_eq!(Stall::of(0, false), Stall::NotHalted); + assert_eq!(Stall::of(1, false), Stall::NotAcknowledged); + assert_eq!(Stall::of(2, true), Stall::NotResumed); + for phase in [3, 4, u32::MAX] { + assert_eq!(Stall::of(phase, false), Stall::NotHalted); + } + let all = [Stall::NotHalted, Stall::NotAcknowledged, Stall::NotResumed]; + for (i, a) in all.iter().enumerate() { + for b in &all[i + 1..] { + assert_ne!(a.describe(), b.describe()); + } + } + } + #[test] fn affected_job_failure_does_not_erase_a_full_owner_receipt() { assert!(!Retirement::Pending.complete()); From 1bbf487c22ad6afc353730d894874818ab5c6cf1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:11 -0500 Subject: [PATCH 0888/1514] selftests: asahi-m4: verify render-only PB slot routing stability Commit 7a8472835197 ("drm/asahi: g16: route SCS compute and base PB slots around quarantined slots") replaced the [home, home + 1] warm PB pair of a new render arena with a quarantine-aware picker. Verify that with nothing quarantined the picker returns the contiguous [home, home + 1] pair for every start, and that sixteen render-only VMs use every warm slot once as home and once as alternate regardless of earlier round-robin cursor motion. Signed-off-by: Diljit Singh --- .../drivers/gpu/asahi-m4/test-resources.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) 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 ee0fc783e7036a..9e5331c254c9f3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1647,6 +1647,32 @@ def module(text, name): assert!(!pools.exhausted_for_mask_mode(&good_vm, pb_mask, picked[0], true)); } + #[test]fn render_only_pb_routing_without_quarantine_matches_v29_for_any_boot_history(){ + use crate::g16::resources::pick_base_pb_slots; + let warm = g16::hw::sizes::WARM_PB_SLOTS; + // v29 (4310e041) gave a new render arena [start % WARM_PB_SLOTS, home + 1]. With nothing + // quarantined the quarantine-aware picker must be that exact pair for every start. + for start in 0..(4 * warm) { + assert_eq!(pick_base_pb_slots(start, 0), [start % warm, (start + 1) % warm]); + } + // render.light [procs] d=16 (dcp103a, dcp103b) makes WARM_PB_SLOTS render-only VMs. Earlier + // work in the same boot only moves `next_pb_slot`: whatever the start, every warm slot is + // the home of exactly one of them and the alternate of exactly one other. + for start in [0usize, 1, 7, 15, 16, 39, 1000] { + let mut home = [0u32; 32]; + let mut alt = [0u32; 32]; + for vm in 0..warm { + let [h, a] = pick_base_pb_slots(start + vm, 0); + assert_ne!(h, a); + home[h] += 1; + alt[a] += 1; + } + assert!(home[..warm].iter().all(|&n| n == 1), "start {start}: {home:?}"); + assert!(alt[..warm].iter().all(|&n| n == 1), "start {start}: {alt:?}"); + assert!(home[warm..].iter().chain(&alt[warm..]).all(|&n| n == 0)); + } + } + #[test]fn base_render_quarantine_expands_fresh_vm_and_recovers_displacement(){ use crate::g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots}; let mut o=Objects::new();let mut s=Slots::new().unwrap(); From 4c5beb4c0fff1551876e78fdc12cf8711f497b95 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 03:17:07 -0500 Subject: [PATCH 0889/1514] drm/asahi: g16: avoid TVB partial-render spills on heavy scenes The G16 parameter-buffer (PB) heap window reserves 256 MiB of GPU VA per VM (PB_HEAP_SIZE), while PoolSet maps only a 64 MiB (512-block) base backing arena so steady 60/120 Hz single-pass desktop VMs keep a small resident footprint. Heavy multi-pass 3D scenes can exhaust 64 MiB of TVB parameter blocks mid-frame and trigger firmware partial-render spills. Demand-grow up to two contiguous PB heap extension chunks inside each VM's 256 MiB PB_HEAP window paired with the existing render extension tiers: - Tier 0: +64 MiB at PB_HEAP + 64 MiB (128 MiB / 1024 blocks total) - Tier 1: +128 MiB at PB_HEAP + 128 MiB (256 MiB / 2048 blocks total) Allocation is best-effort and strictly contiguous, kept mapped until VM teardown (with live_vm_token protection) so no unmap races with in-flight firmware parameter-buffer accesses. Record the initialized heap block count on each PbEpoch and gate pipelined reuse in Pools so a VM whose PB heap expanded drains once and rotates onto a displaced PB slot for a fresh InitBM covering the expanded block count, safely falling back to its warm epoch if no displaced PB slot remains under quarantine. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 25 +++- drivers/gpu/drm/asahi/g16/pools.rs | 98 ++++++++++++-- drivers/gpu/drm/asahi/g16/resources.rs | 127 ++++++++++++++++-- .../drivers/gpu/asahi-m4/test-publication.py | 4 +- .../drivers/gpu/asahi-m4/test-resources.py | 63 +++++++++ 5 files changed, 292 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 4552f85bce08f7..6d7286fdd66104 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1300,7 +1300,10 @@ impl Firmware { && !job .resources .pb_slots() - .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n))) + .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(n, blocks)| { + self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + })) } /// Whether `job` is ready to run without an engine drain but currently blocked solely on @@ -1460,7 +1463,10 @@ impl Firmware { && job .resources .pb_slots() - .is_ok_and(|n| self.pools.can_pipeline_within(&job.vm, n)) + .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(n, blocks)| { + self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + }) && job .resources .render_passes() @@ -1728,8 +1734,14 @@ impl Firmware { let mut a = job .resources .prepare_pb_in_flight(alloc_slot, draw, render_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) { + let pb_slots = job.resources.pb_slots()?; + let heap_blocks = job.resources.pb_heap_blocks()?; + // Reuse this VM's retired epoch of the allocator slot when still bound and sized for the + // VM's current PB heap (no reseed/InitBM); if the PB heap grew, rotate onto a fresh epoch. + let (epoch, reused) = match self + .pools + .reusable_for_within(alloc_slot, &job.vm, pb_slots, heap_blocks) + { Some(e) => { self.pools.stats.reused += 1; a.init_buffer = false; @@ -1743,7 +1755,7 @@ impl Firmware { if let Err(err) = e.prepare( alloc_slot, job.resources.pb_heap_gva(alloc_slot)?, - job.resources.pb_heap_blocks()?, + heap_blocks, ) { job.resources.return_pb(e); return Err(err); @@ -2920,9 +2932,10 @@ impl Firmware { self.slots.hold_render_pass(k, &job.vm, resources)?; let (refs, init_buffer) = if member == 0 { let pb_slots = resources.pb_slots()?; + let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_within(&job.vm, behind, pb_slots) + .pick_slot_within_blocks(&job.vm, behind, pb_slots, heap_blocks) .ok_or(EAGAIN)?; let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c570665604e671..c1860860642925 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -243,6 +243,32 @@ impl Allocator { gva(&self.heap) } } +/// Maps one contiguous PB heap extension chunk (`start_block..start_block + blocks`) inside the +/// VM's 256 MiB [`client::PB_HEAP_SIZE`] window so demand-grown heaps extend seamlessly after the +/// base [`PoolSet`] allocation without unmapping any in-flight base range. +#[allow(dead_code)] +pub(crate) fn alloc_pb_heap_chunk( + o: &mut Objects, + start_block: u32, + blocks: u32, +) -> Result> { + if blocks == 0 + || start_block + .checked_add(blocks) + .is_none_or(|end| end > buffer::MAX_BLOCKS) + { + return Err(EINVAL); + } + let gva = client::pb_heap(0) + u64::from(start_block) * buffer::BLOCK_BYTES; + alloc( + o, + blocks as usize * buffer::BLOCK_BYTES as usize, + Class::Shared, + Some((gva, pte::LEAF_NC)), + false, + ) +} + 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 @@ -394,6 +420,11 @@ impl Pools { && self.active != Some(k) && (self.owners[k].is_none() || self.last_clean_retired.is_some_and(|r| r != k)) } + /// Whether at least one displaced physical PB allocator slot exists in `0..limit`. + fn has_displaced_slot_within(&self, limit: usize) -> bool { + let n = limit.min(sizes::PB_SLOTS); + (0..n).any(|k| self.slot_displaced(k)) + } /// 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 @@ -407,27 +438,49 @@ impl Pools { (Arc::ptr_eq(&owner._vm, vm) && owner.exposed.load(Ordering::Acquire)) .then(|| owner.clone()) } - /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available + /// to rotate onto safely. + #[allow(dead_code)] + pub(crate) fn reusable_for_within( + &self, + k: usize, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> Option> { + let owner = self.reusable(k, vm)?; + if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_within(limit) { + Some(owner) + } else { + None + } + } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused + /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. /// /// When `behind` is true (pipelining behind active flights), only a healthy warm reusable /// slot already bound to `vm` (preferring `self.active`, then any other slot in `0..limit`) - /// is eligible; cold VMs requiring `InitBM` return `None` so the engine drains first. - /// When `behind` is false (engine drained), a warm reusable slot for `vm` is preferred; - /// otherwise an already-used displaced slot is chosen first (preserving the 2-slot working - /// set) or the lowest fresh slot is claimed. - pub(crate) fn pick_slot_within( + /// is eligible; cold VMs or VMs whose PB heap expanded return `None` so the engine drains + /// once before rotating onto a fresh `InitBM` epoch. + /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is + /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot + /// working set) or the lowest fresh slot is claimed. + pub(crate) fn pick_slot_within_blocks( &self, vm: &Arc, behind: bool, limit: usize, + min_blocks: u32, ) -> Option { let n = limit.min(sizes::PB_SLOTS); if let Some(a) = self.active { - if a < n && self.reusable(a, vm).is_some() { + if a < n && self.reusable_for_within(a, vm, n, min_blocks).is_some() { return Some(a); } } - if let Some(k) = (0..n).find(|&k| self.reusable(k, vm).is_some()) { + if let Some(k) = (0..n).find(|&k| self.reusable_for_within(k, vm, n, min_blocks).is_some()) + { return Some(k); } if behind { @@ -438,15 +491,36 @@ impl Pools { .find(|&k| self.slot_displaced(k) && self.owners[k].is_some()) .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) } + /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. + pub(crate) fn pick_slot_within( + &self, + vm: &Arc, + behind: bool, + limit: usize, + ) -> Option { + self.pick_slot_within_blocks(vm, behind, limit, 0) + } /// Selects a physical PB/UMA allocator slot across all `0..PB_SLOTS` for `vm`. #[allow(dead_code)] pub(crate) fn pick_slot(&self, vm: &Arc, behind: bool) -> Option { self.pick_slot_within(vm, behind, sizes::PB_SLOTS) } + /// Whether `vm` has a warm reusable PB slot within `0..limit` covering `min_blocks` and can + /// pipeline without InitBM. + #[allow(dead_code)] + pub(crate) fn can_pipeline_within_blocks( + &self, + vm: &Arc, + limit: usize, + min_blocks: u32, + ) -> bool { + self.pick_slot_within_blocks(vm, true, limit, min_blocks) + .is_some() + } /// Whether `vm` has a warm reusable PB slot within `0..limit` and can pipeline without InitBM. #[allow(dead_code)] pub(crate) fn can_pipeline_within(&self, vm: &Arc, limit: usize) -> bool { - self.pick_slot_within(vm, true, limit).is_some() + self.can_pipeline_within_blocks(vm, limit, 0) } /// Whether `vm` has a warm reusable PB slot and can pipeline without InitBM. #[allow(dead_code)] @@ -638,6 +712,7 @@ pub(crate) struct PbEpochInner { pub(crate) misc: Arc, pub(crate) initbm: Arc, assigned: AtomicU32, + heap_blocks: AtomicU32, exposed: AtomicBool, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, @@ -662,6 +737,7 @@ impl PbEpoch { misc: FwObject::view(&records, 0x300, 0x40)?, initbm: FwObject::view(&records, 0x400, 0x20)?, assigned: AtomicU32::new(u32::MAX), + heap_blocks: AtomicU32::new(0), exposed: AtomicBool::new(false), _objects: o, _vm: vm.clone(), @@ -711,8 +787,12 @@ impl PbEpoch { ), )?; self.assigned.store(k as u32, Ordering::Release); + self.heap_blocks.store(heap_blocks, Ordering::Release); Ok(()) } + pub(crate) fn heap_blocks(&self) -> u32 { + self.heap_blocks.load(Ordering::Acquire) + } pub(crate) fn check_assignment(&self, k: usize) -> Result { if self.assigned.load(Ordering::Acquire) != k as u32 { return Err(EINVAL); diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 4ce13702bc4de3..84871c04b1675d 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -107,6 +107,18 @@ const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; +/// Demand-grown contiguous PB heap extensions within the 256 MiB +/// [`super::hw::client::PB_HEAP_SIZE`] window so steady 60/120 Hz single-pass clients stay on +/// the 64 MiB base heap while multi-pass and heavy 3D workloads expand to 128 MiB (Tier 0) and +/// 256 MiB (Tier 1) without TVB partial-render spills. +pub(crate) const PB_HEAP_EXT_TIERS: [(u32, u32); 2] = + [(512, 1024), (1024, super::fw::buffer::MAX_BLOCKS)]; +const _: () = assert!(PB_HEAP_EXT_TIERS[0].1 == PB_HEAP_EXT_TIERS[1].0); +const _: () = assert!(PB_HEAP_EXT_TIERS[1].1 == super::fw::buffer::MAX_BLOCKS); +const _: () = assert!( + (PB_HEAP_EXT_TIERS[1].1 as u64) * super::fw::buffer::BLOCK_BYTES + <= super::hw::client::PB_HEAP_SIZE +); /// Single-submission render command count that expands Tier 0 extension slots immediately: /// `BASE_RENDER_SLOTS` holds only one active render once displacement occupies a slot. const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; @@ -372,13 +384,62 @@ impl PoolExtArena { } } -/// Keeps the arena owning a retained PB/UMA allocator slot alive through displacement. -/// The wrapped `Arc`s are held solely for their `Drop` lifetime and never read back. +/// One demand-grown contiguous PB heap chunk extending the VM's base [`PoolSet`] heap within the +/// 256 MiB `PB_HEAP_SIZE` GPU VA window without unmapping any in-flight lower range. +pub(crate) struct PbHeapExtArena(crate::cleanup::Deferred); +impl core::ops::Deref for PbHeapExtArena { + type Target = PbHeapExtInner; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +pub(crate) struct PbHeapExtInner { + pub(crate) blocks: u32, + _heap: Arc, + _objects: Objects, + _bind: mmu::VmBind, + _live: Arc, +} +impl PbHeapExtArena { + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + start_block: u32, + blocks: u32, + ) -> Result> { + let mut objects = factory.objects(vm); + let heap = super::pools::alloc_pb_heap_chunk(&mut objects, start_block, blocks)?; + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(PbHeapExtInner { + blocks, + _heap: heap, + _objects: objects, + _bind: bind.clone(), + _live: live.clone(), + })?), + GFP_KERNEL, + )?) + } +} + +/// Keeps the arenas owning a retained PB/UMA allocator slot and its backed PB heap tiers alive +/// through displacement. The wrapped `Arc`s are held solely for their `Drop` lifetime and never +/// read back. #[derive(Clone)] #[allow(dead_code)] pub(crate) enum PbOwnerArena { - Base(Arc), - Ext(Arc, Arc), + Base( + Arc, + [Option>; PB_HEAP_EXT_TIERS.len()], + ), + Ext( + Arc, + Arc, + [Option>; PB_HEAP_EXT_TIERS.len()], + ), } /// Keeps the arena owning a retained pass slot alive through displacement. @@ -427,6 +488,8 @@ struct Ready { render: Option>, /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). render_ext: [Option>; EXT_RENDER_TIERS.len()], + /// Demand-grown contiguous PB heap extension tiers (`PB_HEAP_EXT_TIERS`). + pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], /// Last compute submission and the back-to-back run it continues. @@ -604,6 +667,7 @@ impl Cache { ready.compute_ext.take(), ready.render.take(), core::mem::take(&mut ready.render_ext), + core::mem::take(&mut ready.pb_heap_ext), core::mem::take(&mut ready.pb_ext), ) }; @@ -627,7 +691,7 @@ impl Cache { .count() .try_into()?; let render = render_count != 0; - let (compute, compute_ext, render_arena, render_ext, pb_ext) = { + let (compute, compute_ext, render_arena, render_ext, pb_heap_ext, pb_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(); @@ -743,12 +807,44 @@ impl Cache { } } } + if let Some(base) = ready.render.as_ref() { + let base_blocks = base.pools.heap_blocks(); + for (idx, &(start, end)) in PB_HEAP_EXT_TIERS.iter().enumerate() { + if ready.render_ext[idx].is_none() { + break; + } + if base_blocks >= end { + continue; + } + if ready.pb_heap_ext[idx].is_none() { + let chunk_start = start.max(base_blocks); + // Best effort: stop on failure so the backed PB VA stays contiguous. + ready.pb_heap_ext[idx] = PbHeapExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + chunk_start, + end - chunk_start, + ) + .ok(); + if ready.pb_heap_ext[idx].is_none() { + break; + } + } + } + } } let render_ext = if render { core::array::from_fn(|idx| ready.render_ext[idx].clone()) } else { [const { None }; EXT_RENDER_TIERS.len()] }; + let pb_heap_ext = if render { + core::array::from_fn(|idx| ready.pb_heap_ext[idx].clone()) + } else { + [const { None }; PB_HEAP_EXT_TIERS.len()] + }; let pb_ext = if render { core::array::from_fn(|idx| ready.pb_ext[idx].clone()) } else { @@ -759,6 +855,7 @@ impl Cache { if compute { ready.compute_ext.clone() } else { None }, if render { ready.render.clone() } else { None }, render_ext, + pb_heap_ext, pb_ext, ) }; @@ -858,6 +955,7 @@ impl Cache { compute_ext, render: render_arena, render_ext, + pb_heap_ext, pb_ext, total_renders: render_count, unpublished_renders: AtomicU32::new(render_count), @@ -874,6 +972,8 @@ pub(crate) struct Prepared { pub(crate) render: Option>, /// The VM's demand-grown extension render pass tiers when the job was prepared. pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], + /// The VM's demand-grown contiguous PB heap extension tiers when the job was prepared. + pub(crate) pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], /// Total render commands accounted against `Cache::active_render_passes`. @@ -957,18 +1057,27 @@ impl Prepared { self.pb_allocator(k)?.heap_gva() } pub(crate) fn pb_heap_blocks(&self) -> Result { - Ok(self.render()?.pools.heap_blocks()) + let base = self.render()?.pools.heap_blocks(); + let ext: u32 = self + .pb_heap_ext + .iter() + .take_while(|tier| tier.is_some()) + .flatten() + .map(|tier| tier.blocks) + .sum(); + Ok(base.saturating_add(ext).min(super::fw::buffer::MAX_BLOCKS)) } - /// The arena owning PB/UMA allocator slot `k`. + /// The arenas owning PB/UMA allocator slot `k` and its backed PB heap tiers. pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { let base = self.render.as_ref()?; + let heap_ext = core::array::from_fn(|idx| self.pb_heap_ext[idx].clone()); if k < BASE_PB_SLOTS { - Some(PbOwnerArena::Base(base.clone())) + Some(PbOwnerArena::Base(base.clone(), heap_ext)) } else { self.pb_ext .get(k - BASE_PB_SLOTS) .and_then(|slot| slot.as_ref()) - .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone())) + .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } } fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { 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 2e6c4d7f5182dd..e01576c044d1ad 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -117,7 +117,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)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -164,6 +164,7 @@ def item(declaration): fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -735,6 +736,7 @@ def item(declaration): fn exhausted(&self)->bool{self.exhausted} fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} + fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { 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 cfbb26d9e40999..5f3741b9824d65 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1691,6 +1691,69 @@ def module(text, name): assert_eq!(r.registration_barrier.class, Class::Fw); } + #[test]fn pb_heap_growth_rotates_to_expanded_epoch_and_falls_back_under_quarantine(){ + use g16::fw::buffer; + use g16::hw::client; + use g16::pools::{PbEpoch, Pools, alloc_pb_heap_chunk}; + + // Demand-grown PB heap chunks map contiguously right after the 64 MiB base heap + // inside PB_HEAP_SIZE (256 MiB) and reject out-of-range or zero-sized chunks. + let mut o = Objects::new(); + let tier0 = alloc_pb_heap_chunk(&mut o, 512, 512).unwrap(); + let tier1 = alloc_pb_heap_chunk(&mut o, 1024, 1024).unwrap(); + assert_eq!(tier0.gva, Some(client::pb_heap(0) + 512 * buffer::BLOCK_BYTES)); + assert_eq!(tier0.size, 512 * buffer::BLOCK_BYTES as usize); + assert_eq!(tier1.gva, Some(client::pb_heap(0) + 1024 * buffer::BLOCK_BYTES)); + assert_eq!(tier1.size, 1024 * buffer::BLOCK_BYTES as usize); + assert!(alloc_pb_heap_chunk(&mut o, 512, 0).is_err()); + assert!(alloc_pb_heap_chunk(&mut o, 1024, 1025).is_err()); + + // Start VM1 with a 512-block (64 MiB) warm epoch on slot 0. + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let vm1 = vm(1); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let e512 = PbEpoch::new(&factory, &vm1, g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap()).unwrap(); + e512.prepare(0, client::pb_heap(0), 512).unwrap(); + assert_eq!(e512.heap_blocks(), 512); + e512.expose(); + let b0 = p.bind(0, false); + p.publish_flight(0); + p.retire_flight(0, &e512, b0, true).unwrap(); + + // At 512 blocks VM1 pipelines cleanly on slot 0. + assert!(p.can_pipeline_within_blocks(&vm1, 2, 512)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 512), Some(0)); + + // Once VM1 expands its PB heap to 1024 blocks (128 MiB), slot 0's 512-block epoch + // refuses pipelining so the engine drains once and rotates onto displaced slot 1. + assert!(!p.can_pipeline_within_blocks(&vm1, 2, 1024)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 1024), None); + assert_eq!(p.pick_slot_within_blocks(&vm1, false, 2, 1024), Some(1)); + assert!(p.reusable_for_within(0, &vm1, 2, 1024).is_none()); + + let e1024 = PbEpoch::new(&factory, &vm1, g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap()).unwrap(); + e1024.prepare(1, client::pb_heap(0), 1024).unwrap(); + assert_eq!(e1024.heap_blocks(), 1024); + e1024.expose(); + let b1 = p.bind(1, false); + p.publish_flight(1); + p.retire_flight(1, &e1024, b1, true).unwrap(); + + // Slot 1 now pipelines at 1024 blocks; expanding to 2048 rotates cleanly back to displaced slot 0. + assert!(p.can_pipeline_within_blocks(&vm1, 2, 1024)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 1024), Some(1)); + assert!(!p.can_pipeline_within_blocks(&vm1, 2, 2048)); + assert_eq!(p.pick_slot_within_blocks(&vm1, false, 2, 2048), Some(0)); + + // Quarantine edge case: if slot 0 is quarantined so no displaced slot remains in 0..2, + // VM1 safely falls back to reusing its warm 1024-block slot 1 instead of deadlocking. + p.quarantine_flight(0, None); + assert!(p.can_pipeline_within_blocks(&vm1, 2, 2048)); + assert_eq!(p.pick_slot_within_blocks(&vm1, true, 2, 2048), Some(1)); + assert!(p.reusable_for_within(1, &vm1, 2, 2048).is_some()); + } + } ''' poll_source = (production/'poll.rs').read_text() From 047b934ce47ad72d4c9954c0cf07eec7ee20fef8 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:27:05 -0500 Subject: [PATCH 0890/1514] drm/asahi: g16: keep closed VMs' PB epochs until their slot is replaced Commit c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records") lets Pools::reclaim_closed() drop the owner epoch of a closed VM's PB slot as soon as a render retires on any other slot while keeping the manager record mapped. That epoch maps the page list of its manager in the VM's DYNAMIC client window and its block list, and it holds the VM's TTBAT slot. Because the firmware keeps pb_mgr_table[k] naming the manager across work on other slots, dropping the epoch releases the page and block lists and the VM's ASID while the firmware can still reference that manager. A light render workload run repeatedly with sixteen concurrent client processes faulted with no compute or ray-query work active: fault bank 1: status 0x8b81ddc021 va 0x704000cb40 (write unmapped level 0 unit 0xe0 ctx 46) attribution: busy=0 ctx=46 flight_matches=1 live_vm=Some(110) event=0xffffffff flights=1 Unit 0xe0 is gPM_SP(0), the parameter manager. Only PB page lists are placed in the DYNAMIC window: 0x704000cb40 is entry 720 of a VM's second page list. No TA, FS or compute slot was running for ctx 46, so the firmware attributed the fault to no stage. The parameter manager wrote a PB page list that ctx 46 did not map. Reclaim releases exactly such a list, together with the VM context, while pb_mgr_table[k] still names its manager. Keep the owner epoch until a newer epoch retires on the same slot, as before reclaim existed; retire_flight() already replaces it then. Reclaim still releases the closed VM's render arena, PB heap and the slot's VM references. A closed VM then keeps only its two 32 KiB lists, its records and its context until its slot is reused, and each PB slot pins at most one such VM. A slot holding nothing but that epoch no longer keeps reclaim armed. Add a host regression test for this sequence and update the two reclaim tests, which expected the epoch and the VM's TTBAT slot to be released at reclaim. Fixes: c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/pools.rs | 25 +++-- .../drivers/gpu/asahi-m4/test-resources.py | 103 +++++++++++++++++- 2 files changed, 114 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 78c93869d57dc5..8c801b79404611 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -416,6 +416,9 @@ impl PoolSet { pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, + /// The epoch whose manager `pb_mgr_table[k]` names, kept until a newer epoch retires on + /// slot `k`, also after its VM closed: it maps the manager's page and block lists and keeps + /// the VM's TTBAT slot bound, the context through which those lists are written. owners: [Option>; sizes::PB_SLOTS], /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer @@ -904,15 +907,26 @@ impl Pools { *keep = false; } } - /// Releases displaced PB/UMA allocator leases owned by closed VMs while preserving active, + /// Releases the displaced render arenas and PB heaps of closed VMs while preserving active, /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined - /// slot still holds a closed-VM lease awaiting retirement or displacement. + /// slot still holds such a closed-VM lease awaiting retirement or displacement. + /// + /// The owner epoch itself stays until a newer epoch retires on its slot + /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter + /// manager can still write that manager's page list through the context of the epoch's VM. pub(crate) fn reclaim_closed(&mut self) -> bool { let mut remaining = false; for k in 0..sizes::PB_SLOTS { if self.quarantined[k] { continue; } + let pending = self.pending_vms[k].is_some() + || self.pending_arenas[k].is_some() + || self.pending_uma[k].is_some(); + // Only the owner epoch is left; the next epoch to retire on the slot releases it. + if !pending && self.owner_vms[k].is_none() && self.owner_arenas[k].is_none() { + continue; + } let closed = self.owner_vms[k] .as_ref() .is_some_and(|vm| vm.vm.is_closed()) @@ -925,12 +939,7 @@ impl Pools { if !closed { continue; } - if self.slot_displaced(k) - && self.pending_vms[k].is_none() - && self.pending_arenas[k].is_none() - && self.pending_uma[k].is_none() - { - self.owners[k] = None; + if self.slot_displaced(k) && !pending { self.owner_vms[k] = None; self.owner_arenas[k] = None; self.keep[k] = false; 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 458a57a99a8dc9..69138f4dd1135b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -2180,7 +2180,8 @@ def module(text, name): let last = WARM_PB_SLOTS - 1; for i in 0..last { assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); - assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "PB epoch {i} reclaimed"); + // pb_mgr_table[i] still names this epoch's manager: it stays until replaced. + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); assert_eq!(sync::Arc::strong_count(&vms[i]), 2); @@ -2231,9 +2232,30 @@ def module(text, name): assert!(!p.reclaim_closed()); assert!(!s.reclaim_closed()); assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); - assert_eq!(sync::Arc::strong_count(&epochs[last]), 1); assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + // VM 17's epoch replaced slot 0's; the other slots keep their closed owners' epochs. + assert_eq!(sync::Arc::strong_count(&epochs[0]), 1, "replaced PB epoch 0 released"); + for i in 1..WARM_PB_SLOTS { + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + } + // Each epoch is released once a newer epoch retires on its own slot. + for i in 1..WARM_PB_SLOTS { + let next = vm(520 + i as u64); + let e = g16::pools::PbEpoch::new( + &factory, + &next, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(i, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(i, false); + p.hold_alloc(i, &next, None, None).unwrap(); + p.publish_flight(i); + p.retire_flight(i, &e, b, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "replaced PB epoch {i} released"); + } + assert!(!p.reclaim_closed()); drop(epochs); for (i, v) in vms.iter().enumerate() { assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); @@ -2379,14 +2401,15 @@ def module(text, name): drop(prep1); vm1.vm.close(); - // Reclaim evicts VM1's VmState, RenderArena, PbEpoch, and ComputeArena immediately, - // WHILE retaining its tiny VM-free firmware PB & UMA leases until overwritten! + // Reclaim evicts VM1's RenderArena and ComputeArena immediately and retains its + // firmware PB & UMA leases until overwritten. PB slot 0's epoch keeps VM1's VmState + // (TTBAT slot) and page list until a newer epoch retires on slot 0. assert!(!p.reclaim_closed()); assert!(!s.reclaim_closed()); - assert_eq!(sync::Arc::strong_count(&vm1), 1, "VM1 VmState/TTBAT must release immediately"); + assert_eq!(sync::Arc::strong_count(&vm1), 2, "VM1 TTBAT slot stays with its PB epoch"); assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); - assert_eq!(sync::Arc::strong_count(&pb_lease1), 2, "pb_mgr_table[0] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 3, "pb_mgr_table[0] lease held by epoch + retained_pb"); assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); @@ -2398,6 +2421,7 @@ def module(text, name): p.cancel_alloc(0); assert_eq!(sync::Arc::strong_count(&uma1), 2); assert_eq!(sync::Arc::strong_count(&uma3), 2); + assert_eq!(sync::Arc::strong_count(&vm1), 2); let mut cc3_cancel = Claims::new(); assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); @@ -2420,6 +2444,7 @@ def module(text, name): p.publish_flight(0); p.retire_flight(0, &e3, b3, true).unwrap(); assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "replaced PB epoch releases VM1's TTBAT slot"); assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); @@ -2518,6 +2543,72 @@ def module(text, name): assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); } } + + // A closed VM's PB slot 3 is displaced by slot 4 and reclaimed. pb_mgr_table[3] still names + // its epoch's manager; gPM_SP(0) wrote that manager's page list (DYNAMIC, 0x704000cb40) + // through ctx 46 after the epoch was gone: "write unmapped level 0 unit 0xe0 ctx 46". + #[test]fn closed_vm_pb_epoch_keeps_page_list_and_context_until_slot_replacement_retires(){ + use g16::resources::PbOwnerArena; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + + // VM X (ctx 46) runs and retires on PB slot 3; VM Y then retires on slot 4. + let x = vm(46); + let x_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let ex = epoch(&x, 3); + let x_records = ex.records_lease(); + let bx = p.bind(3, false); + p.hold_alloc(3, &x, Some(PbOwnerArena::Base(x_arena.clone())), None).unwrap(); + p.publish_flight(3); + p.retire_flight(3, &ex, bx, true).unwrap(); + let y = vm(47); + let ey = epoch(&y, 4); + let by = p.bind(4, false); + p.hold_alloc(4, &y, None, None).unwrap(); + p.publish_flight(4); + p.retire_flight(4, &ey, by, true).unwrap(); + + // X closes. Its arena and PB heap go, but not the epoch firmware still names. + x.vm.close(); + assert!(!p.reclaim_closed(), "a retained owner epoch alone must not keep reclaim armed"); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&x_arena), 1, "closed VM's render arena reclaimed"); + assert_eq!(sync::Arc::strong_count(&ex), 2, "slot 3 epoch (page list) reclaimed early"); + assert_eq!(sync::Arc::strong_count(&x), 2, "ctx 46 released while its lists are named"); + assert!(sync::Arc::strong_count(&x_records) >= 2); + assert!(p.reusable(3, &x).is_none()); + + // A new VM's InitBM epoch rebinds slot 3. The old binding stays intact while that + // render is in flight and goes only with its full retirement. + let z = vm(48); + assert_eq!(p.pick_slot_in_mask_blocks(&z, false, 0b11000, 3, 512), Some(3)); + let ez = epoch(&z, 3); + let bz = p.bind(3, false); + p.hold_alloc(3, &z, None, None).unwrap(); + p.publish_flight(3); + assert!(p.reclaim_closed(), "rebinding render still in flight"); + assert_eq!(sync::Arc::strong_count(&ex), 2); + assert_eq!(sync::Arc::strong_count(&x), 2); + p.retire_flight(3, &ez, bz, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ex), 1, "replaced epoch released"); + drop(ex); + assert_eq!(sync::Arc::strong_count(&x), 1, "closed VM released after replacement"); + assert_eq!(sync::Arc::strong_count(&x_records), 1); + assert!(!p.reclaim_closed()); + } + } ''' poll_source = (production/'poll.rs').read_text() From a1450a23e65d0c68a6b5c9a18d3c5fd265d2b63f Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 17:59:09 -0500 Subject: [PATCH 0891/1514] drm/asahi: g16: log fault_scan() records and firmware log entries during recovery When firmware announces a recovery with no attributed stage ([4, gen, 0, ffffffff]), recover() already runs fault_scan() while the firmware is halted in phase 1, but discards the fault status, VA, bank and unit without calling the existing log_fault() decoder, and silently drains the nine firmware log rings without printing their payload lines. Extend Regs::fault_scan() to snapshot all eight fault banks (restoring the saved selector), decode every non-zero bank through log_fault() with busy/ASID flight and live-VM attribution, and explicitly log when all eight banks read zero. Keep LOG_DATA attached to Channels and, whenever recovery is pending or running, print up to the last 32 drained firmware log payload entries before advancing the consumer (leaving the normal non-recovery drain path untouched). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/boot.rs | 6 +- drivers/gpu/drm/asahi/g16/channel.rs | 136 +++++++++++++++++++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 3 + drivers/gpu/drm/asahi/g16/initdata.rs | 1 + drivers/gpu/drm/asahi/g16/poll.rs | 3 +- drivers/gpu/drm/asahi/g16/recovery.rs | 71 +++++++++++++- drivers/gpu/drm/asahi/g16/regs.rs | 60 ++++++++---- drivers/gpu/drm/asahi/g16/vm.rs | 9 ++ 8 files changed, 249 insertions(+), 40 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 353c576b247d18..73b3445ffe2b94 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -533,9 +533,9 @@ impl Session { 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> { + /// All eight engine fault banks, 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) } diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index 17b5aef14c6178..9e958a99a5ae97 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -55,6 +55,9 @@ impl Ring { } } +/// Maximum firmware log entries printed per recovery before suppressing excess entries. +pub(crate) const RECOVERY_FWLOG_CAP: usize = 32; + /// The channels and rings. pub(crate) struct Channels { /// The 12 submit channels (TA, FS and compute are used). @@ -63,6 +66,8 @@ pub(crate) struct Channels { pub(crate) event: Ring, /// The nine log sub-rings share one state object (9 x 0x30) and one ring object. pub(crate) log: Ring, + /// Backing payload buffer (`LOG_DATA`, 9 x 256 x 0xd8) indexed by firmware log records. + log_data: Arc, pub(crate) trace: Ring, pub(crate) stats: Ring, /// Allocated for the firmware; the host never uses it. @@ -93,6 +98,7 @@ impl Channels { devctl: Ring, event: Ring, log: Ring, + log_data: Arc, trace: Ring, stats: Ring, fwctl: Ring, @@ -112,6 +118,7 @@ impl Channels { devctl, event, log, + log_data, trace, stats, _fwctl: fwctl, @@ -222,17 +229,92 @@ impl Channels { ); } - /// 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)?; - let consumer = ring.state.r32(offset + STATE_READ)?; - if producer >= capacity || consumer >= capacity { + /// Drains one firmware log sub-ring. Outside recovery (`budget` is `None`), advances the + /// consumer directly without touching the payload pages. During recovery (`Some(remaining)`), + /// prints up to the last `*remaining` entries and counts any older/excess entries suppressed. + #[inline(never)] + fn drain_log_ring( + &self, + dev: &kernel::device::Device, + thread: usize, + budget: Option<&mut usize>, + suppressed: &mut usize, + ) -> Result { + let offset = thread * 0x30; + let producer = self.log.state.r32(offset + STATE_WRITE)?; + let mut consumer = self.log.state.r32(offset + STATE_READ)?; + if producer >= RING_SLOTS || consumer >= RING_SLOTS { return Err(super::boot::eproto()); } - if consumer != producer { - ring.state.w32(offset + STATE_READ, producer)?; - wmb(); + if consumer == producer { + return Ok(()); } + if let Some(remaining) = budget { + rmb(); + let pending = producer.wrapping_sub(consumer) % RING_SLOTS; + if (pending as usize) > *remaining { + let skip = pending as usize - *remaining; + *suppressed = suppressed.saturating_add(skip); + consumer = (consumer + skip as u32) % RING_SLOTS; + } + while consumer != producer { + let entry_off = + (thread * RING_SLOTS as usize + consumer as usize) * rings::EVENT_RECORD; + let kind = self.log.ring.r32(entry_off)?; + let slot = self.log.ring.r32(entry_off + 8)?; + let payload_idx = thread * RING_SLOTS as usize + (slot & 255) as usize; + let payload_off = payload_idx * rings::LOG_PAYLOAD_SIZE; + let ptype = self.log_data.r32(payload_off)?; + let seq = self.log_data.r32(payload_off + 4)?; + let mut text = [0u8; rings::LOG_PAYLOAD_TEXT_SIZE]; + self.log_data + .read(payload_off + rings::LOG_PAYLOAD_TEXT_OFFSET, &mut text)?; + let len = text.iter().position(|&b| b == 0).unwrap_or(text.len()); + let line = core::str::from_utf8(&text[..len]) + .ok() + .map(|s| s.trim_end_matches(['\r', '\n'])); + match line { + Some(msg) if !msg.is_empty() && kind == 2 && ptype == 3 => { + dev_warn!( + dev, + "G16: fwlog[{}] seq={} slot={}: {}\n", + thread, + seq, + slot, + msg + ); + } + Some(msg) if !msg.is_empty() => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={}: {}\n", + thread, + kind, + ptype, + seq, + slot, + msg + ); + } + _ => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={} (non-text len={})\n", + thread, + kind, + ptype, + seq, + slot, + len + ); + } + } + *remaining = remaining.saturating_sub(1); + consumer = (consumer + 1) % RING_SLOTS; + } + } + self.log.state.w32(offset + STATE_READ, producer)?; + wmb(); Ok(()) } @@ -252,21 +334,39 @@ impl Channels { result } - /// Drains the nine log sub-rings and the ktrace receive ring. - pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + /// Drains the nine log sub-rings and the ktrace receive ring. When `fwlog_budget` is `Some`, + /// prints drained firmware log records up to the remaining budget. + pub(crate) fn drain_auxiliary_rings_with_log( + &self, + dev: &kernel::device::Device, + mut fwlog_budget: Option<&mut usize>, + ) -> Result { let mut result = Ok(()); + let mut suppressed = 0usize; let mut keep = |r: Result| { if result.is_ok() { result = r; } }; for i in 0..rings::LOG_RINGS { - keep(Self::drain_one(&self.log, i * 0x30, 256)); + keep(self.drain_log_ring(dev, i, fwlog_budget.as_deref_mut(), &mut suppressed)); + } + if suppressed != 0 { + dev_warn!( + dev, + "G16: fwlog: suppressed {} additional entries during recovery\n", + suppressed + ); } keep(self.drain_trace(dev)); result } + /// Drains the nine log sub-rings and the ktrace receive ring silently. + pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + self.drain_auxiliary_rings_with_log(dev, None) + } + /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace /// and stats, 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 @@ -410,7 +510,12 @@ impl Firmware { /// Drains the receive rings and decodes events. Called on full housekeeping and idle passes. pub(crate) fn drain_rings(&mut self) -> Result { let dev = self.session.dev.clone(); - self.channels.drain_rings(&dev, &mut self.events) + let mut result = self.channels.drain_events_and_stats(&dev, &mut self.events); + let aux = self.drain_auxiliary_rings(); + if result.is_ok() { + result = aux; + } + result } /// Drains only the event and statistics rings on the hot retirement path. @@ -419,9 +524,12 @@ impl Firmware { self.channels.drain_events_and_stats(&dev, &mut self.events) } - /// Drains the auxiliary log and trace rings on periodic housekeeping passes. + /// Drains the auxiliary log and trace rings on periodic housekeeping passes. Prints firmware + /// log records (bounded per recovery) whenever a firmware recovery is pending or running. pub(crate) fn drain_auxiliary_rings(&mut self) -> Result { let dev = self.session.dev.clone(); - self.channels.drain_auxiliary_rings(&dev) + let log_fwlog = self.recovery.receipt_fault || self.recovery_pending().unwrap_or(false); + let budget = log_fwlog.then_some(&mut self.recovery.fwlog_remaining); + self.channels.drain_auxiliary_rings_with_log(&dev, budget) } } diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 155c8f528abb23..55fcb9f05c950b 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -542,6 +542,9 @@ pub(crate) mod rings { pub(crate) const LOG_RINGS: usize = 9; pub(crate) const LOG_STATE_SIZE: usize = 0x1b0; pub(crate) const LOG_RING_SIZE: usize = 0x28800; + pub(crate) const LOG_PAYLOAD_SIZE: usize = 0xd8; + pub(crate) const LOG_PAYLOAD_TEXT_OFFSET: usize = 0x10; + pub(crate) const LOG_PAYLOAD_TEXT_SIZE: usize = 0xc8; pub(crate) const TRACE_RING_SIZE: usize = 0x9000; pub(crate) const STATS_RING_SIZE: usize = 0x4800; pub(crate) const FWCTL_RING_SIZE: usize = 0x4000; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index e4898529be5c7d..6d8f3bb7836e7e 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -150,6 +150,7 @@ pub(crate) fn build( pair(&graph, id::DEVCTRL_STATE, id::DEVCTRL_RING), pair(&graph, id::EVENT_STATE, id::EVENT_DATA), pair(&graph, id::LOG_STATE, id::LOG_ENTRIES), + graph[id::LOG_DATA].clone(), pair(&graph, id::KTRACE_STATE, id::KTRACE_DATA), pair(&graph, id::STATISTICS_STATE, id::STATISTICS_DATA), // FWCTL state and ring share one allocation (ring starts at+0x40). diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e3252e36b2799b..0685f2688827db 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1347,7 +1347,6 @@ impl Firmware { } /// Logs the fault bank of `state` when it holds a fault. - #[allow(dead_code)] pub(crate) fn log_fault(&self, state: &EngineState) { let (bank, f, va) = (state.bank, state.status, state.address); if f != 0 { @@ -1357,7 +1356,7 @@ impl Firmware { } else { "unmapped" }; - dev_info!( + dev_warn!( self.graph.dev.as_ref(), "G16: fault bank {}: status {:#x} va {:#x} ({} {} level {} unit {:#x} ctx {})\n", bank, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 6ed3120b70b576..ce51e5249f5182 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -74,6 +74,7 @@ pub(crate) struct Recovery { window_ns: u64, window_count: u32, running: bool, + pub(crate) fwlog_remaining: usize, } impl Recovery { @@ -97,6 +98,7 @@ impl Recovery { window_ns: 0, window_count: 0, running: false, + fwlog_remaining: super::channel::RECOVERY_FWLOG_CAP, } } @@ -402,6 +404,59 @@ impl Firmware { self.recovery_prepare_suspects(stage, event, asid) } + /// Decodes and logs every non-zero fault bank captured while firmware is halted in phase 1, + /// together with whether the faulting context matches any in-flight flight or open VM. + #[inline(never)] + fn log_recovery_faults(&self, scan: Option<&super::regs::FaultScan>, event: u32) { + let Some(scan) = scan else { + dev_warn!( + self.dev(), + "G16: fault_scan: GPU powered down (event={:#x}, flights={})\n", + event, + self.engine.flights.len() + ); + return; + }; + let mut nonzero = 0usize; + for entry in &scan.banks { + if entry.status == 0 { + continue; + } + nonzero += 1; + self.log_fault(entry); + let ctx = ((entry.status >> 17) & 0x3f) as u32; + let flight_matches = self + .engine + .flights + .iter() + .filter(|f| f.job.vm.slot == ctx) + .count(); + let live_vm = self.vms.find_by_slot(ctx); + dev_warn!( + self.dev(), + "G16: fault bank {} attribution: busy={} saved_bank={} ctx={} flight_matches={} live_vm={:?} event={:#x} flights={}\n", + entry.bank, + scan.busy, + scan.saved_bank, + ctx, + flight_matches, + live_vm, + event, + self.engine.flights.len() + ); + } + if nonzero == 0 { + dev_warn!( + self.dev(), + "G16: fault_scan: all 8 banks zero (busy={}, saved_bank={}, event={:#x}, flights={})\n", + scan.busy, + scan.saved_bank, + event, + self.engine.flights.len() + ); + } + } + fn recover(&mut self) -> Result { struct RecoveringGuard(Option>); impl Drop for RecoveringGuard { @@ -432,6 +487,7 @@ impl Firmware { } let now = now_ns(); if logic::expired(now, deadline) { + let _ = self.drain_auxiliary_rings(); // Which side stalled, and whether tiling or fragment work was left behind. let stage = self.recovery_snapshot().unwrap_or_default(); dev_err!( @@ -493,10 +549,13 @@ impl Firmware { 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) + let scan = self.session.fault_scan()?; + self.log_recovery_faults(scan.as_ref(), event); + let _ = self.drain_auxiliary_rings(); + let asid = scan + .as_ref() + .and_then(super::regs::FaultScan::first_latched) + .map(|fault| ((fault.status >> 17) & 0x3f) as u32) .filter(|asid| *asid >= 1); self.mark_recovery(stage, event, asid)?; // Snapshot reads and all TPC repairs precede acknowledgement. @@ -506,6 +565,7 @@ impl Firmware { answered = true; } RecoveryAction::Resume => { + let _ = self.drain_auxiliary_rings(); barrier(); self.firmware_w32(self.init.firmware_data().phase, 0)?; barrier(); @@ -514,6 +574,7 @@ impl Firmware { self.recovery.statistics_seen = self.events.recovery_statistics; self.events.recovery_started_ns = None; self.recovery.running = false; + self.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; self.engine.frozen = false; self.renew_deadlines(); dev_warn!( @@ -539,10 +600,12 @@ impl Firmware { self.engine.flights.is_empty(), now.saturating_sub(start), ) { + let _ = self.drain_auxiliary_rings(); 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.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; self.engine.frozen = false; dev_warn!( self.dev(), diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index 74b8fd7a434178..225a0ed5d32d42 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -153,7 +153,7 @@ pub(crate) struct Identity { } /// Fault-bank selector values (`+0xd800`) that name a fault bank. -const FAULT_BANKS: u64 = 8; +pub(crate) const FAULT_BANKS: usize = 8; /// Engine receipts: busy bit and one fault bank. #[derive(Copy, Clone, Default)] @@ -177,6 +177,24 @@ impl EngineState { } } +/// Full eight-bank fault-register snapshot taken while firmware is halted for recovery. +#[derive(Copy, Clone, Default)] +pub(crate) struct FaultScan { + /// Bit 0 of `+0xc020 | +0xc120`. + pub(crate) busy: u64, + /// Selector (`+0xd800`) observed before scanning banks 0..7 and restored afterwards. + pub(crate) saved_bank: u64, + /// Raw status (`+0xd8c0`) and address (`+0xd8c8 << 6`) of each fault bank 0..7. + pub(crate) banks: [EngineState; FAULT_BANKS], +} + +impl FaultScan { + /// First bank whose latched fault bit (bit 0) is set. + pub(crate) fn first_latched(&self) -> Option<&EngineState> { + self.banks.iter().find(|entry| entry.status & 1 != 0) + } +} + /// G16 register access. pub(crate) struct Regs { /// The shared SGX mapping. @@ -313,29 +331,37 @@ impl Regs { }) } - /// 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 { + /// Engine receipts for a firmware halted for recovery and waiting on the host: reads all + /// eight fault banks (selectors 0 to 7 in order), capturing status and address for every + /// non-zero bank, and restores the saved selector. + #[inline(never)] + 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 busy = (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1; + let mut scan = FaultScan { + busy, + saved_bank: saved, + banks: [EngineState::default(); FAULT_BANKS], }; - for bank in 0..FAULT_BANKS { + for (idx, entry) in scan.banks.iter_mut().enumerate() { + let bank = idx as u64; 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; - } + let address = if status != 0 { + r.try_read64(0x18c8)? << 6 + } else { + 0 + }; + *entry = EngineState { + busy, + bank, + status, + address, + }; } r.try_write64(saved, 0x1800)?; - Ok(state) + Ok(scan) } } diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 0367a4421554c0..7db8f5d799e128 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -341,6 +341,15 @@ impl Registry { .ok_or(ENOENT) } + /// The VM id of a live VM currently bound to TTBAT `slot`, if any. + pub(crate) fn find_by_slot(&self, slot: u32) -> Option { + self.vms + .lock() + .iter() + .find(|state| state.slot == slot) + .map(|state| state.id) + } + /// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under /// the device lock. pub(crate) fn fail_all(&self, error: Error) { From 37d7d7e938689dcc822d436da8edd506b7479519 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:11 -0500 Subject: [PATCH 0892/1514] drm/asahi: g16: mark SCS stages in StartCompute, StartTA and StartFS The 26B123 G16G firmware learns which slots run shader-context scratch (SCS) work from a u32 in each start command: StartCompute +0x40, StartTA +0x60 and StartFS +0x78. It ORs the slot into a per-engine SCS mask, appends 0x017d9 = 1 to that kick's register list for masked slots, and when its scheduler goes idle it tears the SCS state down (0x017e0 = 0, the compute and TA windows 0x107a0/0x10798 = 0xff0000, 0x100e8/0x100f0/0x10408/0x10410 = 0x100) unless a masked slot is still busy. The G16 encoders always left the three words zero, so the teardown ran at the first idle after every ray-query kick, while the dispatch was still executing. Compute and ray-generation ray queries then lost traversal mid-dispatch and returned misses without a fault, and fragment and tiling ray queries stalled their stage until the firmware recovered it (events 0x71 and 0x70). macOS 27.2 on Apple M4 sets StartCompute +0x40 on every compute item whose register list opens with 0x017e1 and leaves it clear on all others. This is the M4 counterpart of the G17P kick header's SCS bit (bit 61), which g17 sets for compute and per render stage. Set each word exactly when the stage's register list enables SCS. Non-ray-tracing work is byte-identical. The host check now also requires the flag on ray-query compute, TA and FS sequences and nothing else to change there. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode/compute.rs | 1 + drivers/gpu/drm/asahi/g16/encode/render.rs | 2 ++ drivers/gpu/drm/asahi/g16/fw/work.rs | 6 +++++ drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 5 ++++ drivers/gpu/drm/asahi/g16/rt.rs | 7 ++++-- .../drivers/gpu/asahi-m4/test-ray-tracing.py | 25 +++++++++++++++---- 6 files changed, 39 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 71191ebabfc357..78c972ac4c9df8 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -476,6 +476,7 @@ pub(crate) fn encode_compute_rt( put32(q, 0x30, u32::from(fault_mask != 0)); put32(q, 0x38, r.compute_index); put32(q, 0x3c, r.work_818); + put32(q, compute::START_SCS, u32::from(rt.scs)); put64(q, 0x44, r.work + 0x76c); put32(q, 0x50, 1); for (i, a) in att.iter().enumerate() { diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index 647ce051264530..ebf2e03a682697 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -378,6 +378,7 @@ pub(crate) fn encode_ta_rt( put64(q, 0x64, work + 0x784); put64(q, 0x6c, work + 0x8a8); put32(q, 0x7c, r.uuid); + put32(q, ta::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); // TA attachments are filled by render_attachments before publication. inline_uma(q, 0x190, r, 0); timestamps( @@ -657,6 +658,7 @@ pub(crate) fn encode_fs_rt( put64(q, 0x7c, work + 0xa58); put64(q, 0x84, work + 0xbf0); put32(q, 0xa0, r.uuid); + put32(q, fs::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); inline_uma(q, 0x1b0, r, 1); timestamps( q, diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index f50fc22164d4c0..5b1220b301e3fb 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -80,6 +80,9 @@ pub(crate) mod ta { pub(crate) const TS_END: usize = 0x21c; pub(crate) const FINALIZE: usize = 0x268; pub(crate) const END: usize = 0x2fc; + /// u32 of the StartTA command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x60; /// The binding generation. pub(crate) const GENERATION: usize = 0x917; @@ -142,6 +145,9 @@ pub(crate) mod fs { pub(crate) const TS_END: usize = 0x23c; pub(crate) const FINALIZE: usize = 0x288; pub(crate) const END: usize = 0x344; + /// u32 of the StartFS command: nonzero when the stage's register list enables SCS + /// (`compute::START_SCS`). + pub(crate) const START_SCS: usize = 0x78; /// The binding generation. pub(crate) const GENERATION: usize = 0xc5f; diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index bb5ccf0ccc8460..85daf5876aec3b 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -36,6 +36,11 @@ pub(crate) const CONTEXT_STORE_SIZE: usize = 0x40000; pub(crate) const POOL_SIZE: usize = 0x2000000; pub(crate) const POOL_STATE_SIZE: usize = 0x20000; pub(crate) const PAGE_LIST_SIZE: usize = 0x4000; +/// u32 of the StartCompute command: nonzero when the work's register list enables shader-context +/// scratch (SCS). The firmware then records the work's slot as an SCS user, appends +/// `0x017d9 = 1` to the kick's register list, and keeps the SCS state (`0x017e0`, the compute +/// and TA windows) through its idle teardown while the slot is busy. +pub(crate) const START_SCS: usize = 0x40; pub(crate) const EVENT: u32 = 15; /// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. pub(crate) const EVENTS: [u32; 2] = [EVENT, 16]; diff --git a/drivers/gpu/drm/asahi/g16/rt.rs b/drivers/gpu/drm/asahi/g16/rt.rs index 4119afade7c232..5b42e6f2d1dcf4 100644 --- a/drivers/gpu/drm/asahi/g16/rt.rs +++ b/drivers/gpu/drm/asahi/g16/rt.rs @@ -19,8 +19,11 @@ //! ray queries has been traced. //! - 0x1a141 (SCS driver word), `COMPUTE_SCS_DRIVER_WORD` (T1): macOS's ray-query compute //! items on the J773g do not write it. -//! - An SCS-enable bit in the work or microsequence, as g17's kick header has (T6): none is -//! known, so nothing is written. +//! - The SCS-enable bit (T6, g17's kick header bit 61) is a u32 of each start command: +//! StartCompute +0x40, StartTA +0x60, StartFS +0x78 (`fw::work`'s `START_SCS`). macOS 27.2 on +//! the J773g sets it on every compute item whose list opens with 0x017e1 and on no other. A +//! slot without it is not protected from the firmware's idle SCS teardown (0x017e0 = 0, +//! compute and TA windows 0xff0000), which runs while its dispatch is still executing. //! - A traversal exclusion between clients (T8): the A18 Pro needs one (`g17::traversal`), the //! M4 Pro's variants do not set it; G16G adds none. //! - How macOS sizes the SCS pool for a given request (T3): it grows its compute pool beyond diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py index 3b5c3dca9299d7..bfc62d7c4c9ef5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -14,7 +14,9 @@ 2. RT words land in the wrong register record, the register counts change, a gated register (0x1a141, render 0x017d9) is written while its gate is off, or a ray-query compute item is not bracketed by 0x017e1 = 1 first and 0x017d9 = 1 last, or its tail is not 0x2c, as macOS - 27.2 writes them on the J773g. + 27.2 writes them on the J773g; or a start command's SCS flag (StartCompute +0x40, StartTA + +0x60, StartFS +0x78) differs from whether the item's register list enables SCS, which + leaves a running ray-query dispatch exposed to the firmware's idle SCS teardown. 3. The fragment window word loses bit 9; a render stage's tail word takes the auxiliary intersection word (the M4 Pro's render programs use the scratch tail). 4. SCS sizing differs from the M4 Pro's formula ((pages + pages/256 + 8) x cores pages), is not @@ -237,12 +239,17 @@ def block(text, declaration): assert_eq!(sel, plain_sel); assert!(value == plain_value || rt_sels.contains(&sel), "{sel:#x}"); } - // Nothing else moves: the register list, its count and the pool's descriptor words. + // The embedded StartCompute marks the slot as an SCS user, as macOS 27.2 does on + // every J773g compute item that opens with 0x017e1 (and on no other). + let flag = compute::SEQ_EMBEDDED + compute::START_SCS; + assert_eq!((u32_at(&plain, flag), u32_at(&w, flag)), (0, 1)); + // Nothing else moves: the register list, its count, the pool's descriptor words and + // the start command's SCS flag. let regs = compute::REGS..compute::REGS + 27 * 12; let pool_words = [0x1c, 0x24, 0x2c, 0x48]; for (i, (a, b)) in plain.iter().zip(w.iter()).enumerate() { if a != b { - assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) + assert!(regs.contains(&i) || (0x728..0x72c).contains(&i) || (flag..flag + 4).contains(&i) || pool_words.iter().any(|&o| (d + o..d + o + 4).contains(&i)), "byte {i:#x}"); } } @@ -315,7 +322,11 @@ def block(text, declaration): let window = 1 << 24 | 0x60 << 16; let ift = [POOL + 128, 0xc0003800, 0x6f00000000, 0x3feff, 0x10010020000, 0x16000000000]; let (w, q) = ta_rt(&words, tl); - assert_eq!(q, taq_plain); + // StartTA marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&taq_plain, ta::START_SCS), u32_at(&q, ta::START_SCS)), (0, 1)); + for (i, (a, b)) in taq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (ta::START_SCS..ta::START_SCS + 4).contains(&i), "TA seq byte {i:#x}"); + } assert_eq!((u16_at(&w, 0x748), u16_at(&w, 0x74a)), (68, 68 * 12)); let ta_plain_regs = records(&ta_plain, ta::REGS, 66); let got = records(&w, ta::REGS, 68); @@ -334,7 +345,11 @@ def block(text, declaration): } } let (w, q) = fs_rt(&words, fl); - assert_eq!(q, fsq_plain); + // StartFS marks the slot as an SCS user; nothing else in the sequence moves. + assert_eq!((u32_at(&fsq_plain, fs::START_SCS), u32_at(&q, fs::START_SCS)), (0, 1)); + for (i, (a, b)) in fsq_plain.iter().zip(q.iter()).enumerate() { + assert!(a == b || (fs::START_SCS..fs::START_SCS + 4).contains(&i), "FS seq byte {i:#x}"); + } assert_eq!((u16_at(&w, 0x788), u16_at(&w, 0x78a)), (84, 84 * 12)); let fs_plain_regs = records(&fs_plain, fs::REGS, 82); let got = records(&w, fs::REGS, 84); From 2412db2bdf80eb964dbf2f843de5bf34ee7094bb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:13 -0500 Subject: [PATCH 0893/1514] drm/asahi: g16: share device-lifetime firmware-cached render records A render pass slot index is device-global and claimed by one flight at a time, so render microsequences and barrier records need not be allocated per VM. Mapping them with firmware-cached leaf 0x443 inside a per-VM render arena is unsafe on client teardown because KernelMapping::drop() fail-stops an ASC-cached M4 mapping that has no qualified teardown. Allocate render microsequences and barrier records once per pass slot index, on first use, from a device-lifetime allocator that is never dropped (resources::RenderCmds, reached through Factory), and let every VM's PassSlot of that index share them. Each microsequence keeps its own page and the barrier records share one page, matching compute unit barriers: 48 KiB per index (at most 2.25 MiB per boot) instead of 128 KiB per pass slot of every VM. Class::FwCoherent (firmware leaf 0x443 behind a cacheable host mapping, matching macOS 26B123 per-queue command objects) is accepted only by this device-lifetime allocator and never with a client or lower alias. Per-VM arenas and the session allocator reject it, so closing a client can never drop a firmware-cached mapping. Extend the host resource tests to verify that two VMs' pass slot k share one set, no VM arena owns a firmware-cached object, dropping a VM retains the set, and other allocators reject Class::FwCoherent. Pass slot backing drops from 608 to 480 KiB of metadata per VM. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 7 +- drivers/gpu/drm/asahi/g16/object.rs | 75 ++++++++++- drivers/gpu/drm/asahi/g16/resources.rs | 83 ++++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 85 ++++++++---- .../drivers/gpu/asahi-m4/test-resources.py | 122 ++++++++++++++---- 5 files changed, 300 insertions(+), 72 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 31e267b32760ef..2dedd2d48c3b69 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -754,10 +754,11 @@ impl Firmware { let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; + let render_cmds = resources::RenderCmds::new()?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, slots, pools, vms, engine, slot)) + Ok((graph, slots, pools, vms, engine, render_cmds, slot)) })(); - let (graph, slots, pools, vms, engine, slot) = match backend { + let (graph, slots, pools, vms, engine, render_cmds, slot) = match backend { Ok(backend) => backend, Err(error) => { dev_err!( @@ -777,7 +778,7 @@ impl Firmware { events, .. } = KBox::into_inner(booted); - let private_factory = objects.private_factory(); + let private_factory = objects.private_factory(render_cmds); let mut firmware = slot .write_init(init!(Firmware { session, diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 4c94bfb15c44e9..e5329887c1e9c3 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,6 +46,13 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, + /// Firmware-only, ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS + /// 26B123 gives its per-queue command objects and the G13-G15 private-allocator contract + /// (`PROT_FW_PRIV_RW` behind `gem::new_kernel_object`). Only for records the host writes + /// before publication and the firmware only reads, with no client or lower alias, and only + /// from device-lifetime allocators ([`Factory::persistent_objects`]): an ASC-cached M4 + /// mapping has no qualified teardown, so its owner is never dropped. + FwCoherent, /// Firmware device mapping. #[allow(dead_code)] Mmio, @@ -59,6 +66,7 @@ impl Class { Class::FwCached => pte::FW_CACHED, Class::Shared => pte::SHARED, Class::SharedCached => pte::SHARED_CACHED, + Class::FwCoherent => pte::FW_CACHED, Class::Mmio => pte::MMIO, } } @@ -325,6 +333,7 @@ pub(crate) struct Factory { uat: Arc, window: Arc>, firmware: core::ops::Range, + render_cmds: Arc, } impl Factory { @@ -339,6 +348,7 @@ impl Factory { pending: None, }), sealed: false, + persistent: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -360,6 +370,7 @@ impl Factory { pending: None, }), sealed: false, + persistent: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -368,6 +379,36 @@ impl Factory { pages: 0, } } + + /// Allocates the only objects that may hold [`Class::FwCoherent`] records: firmware-only, + /// with no client VM binding. The caller owns them for the device lifetime and never drops + /// them ([`super::resources::RenderCmds`]). + pub(crate) fn persistent_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + persistent: true, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// The device-lifetime render microsequences and barrier records of pass slot `k`, shared by + /// every VM's [`super::slots::PassSlot`] `k`. + pub(crate) fn pass_cmds(&self, k: usize) -> Result { + self.render_cmds.get(self, k) + } } /// The firmware object allocator and the set of retained objects. @@ -378,6 +419,8 @@ pub(crate) struct Objects { pub(crate) window: Arc>, private: Option, sealed: bool, + /// A device-lifetime allocator that may map [`Class::FwCoherent`] records. + persistent: bool, /// Next free VA of the firmware allocator window. fw_next: u64, /// Every object owned by this session or private arena. @@ -406,6 +449,7 @@ impl Objects { window: Arc::pin_init(new_mutex!(window, "g16::Objects::window"), GFP_KERNEL)?, private: None, sealed: false, + persistent: false, fw_next: hw::va::FW_ALLOC.start, retained: KVec::new(), clients: KVec::new(), @@ -416,19 +460,24 @@ impl Objects { } /// Freeze the session allocation boundary before making any private arenas. - pub(crate) fn private_factory(&mut self) -> Factory { + pub(crate) fn private_factory( + &mut self, + render_cmds: Arc, + ) -> Factory { self.sealed = true; Factory { dev: self.dev.clone(), uat: self.uat.clone(), window: self.window.clone(), firmware: self.fw_next..hw::va::FW_ALLOC.end, + render_cmds, } } /// Maps private backing into one client and unique kernel/firmware apertures. Mapping /// owners retain the GEM independently, including every partial construction failure. - /// All reclaimable objects are NC from creation; there is no ASC cache transition. + /// All reclaimable objects are NC from creation; there is no ASC cache transition. Only a + /// device-lifetime allocator maps [`Class::FwCoherent`] records, never reclaimed. fn alloc_private(&mut self, req: Request) -> Result> { self.alloc_private_in(req, None) } @@ -454,7 +503,12 @@ impl Objects { client_range: Option>, ) -> Result> { if !matches!(req.placement, Placement::Anywhere) - || !matches!(req.class, Class::Fw | Class::Shared) + || !matches!(req.class, Class::Fw | Class::Shared | Class::FwCoherent) + || (req.class == Class::FwCoherent + && (!self.persistent + || req.client.is_some() + || req.lower.is_some() + || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { @@ -469,14 +523,21 @@ impl Objects { & !(hw::PAGE as usize - 1); self.retained.reserve(1, GFP_KERNEL)?; self.mappings.reserve(3, GFP_KERNEL)?; - let mut backing = gem::new_kernel_object_wc(&self.dev, bytes)?; + // A firmware-cached record needs a cacheable host view of the same pages (the host and + // firmware caches are coherent, as for G13-G15 private objects); every other private + // class keeps its write-combined view. + let mut backing = if req.class == Class::FwCoherent { + gem::new_kernel_object(&self.dev, bytes)? + } else { + gem::new_kernel_object_wc(&self.dev, bytes)? + }; let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; - // SAFETY: Fresh private WC mapping spans bytes and has not been exposed. + // SAFETY: Fresh private mapping spans bytes and has not been exposed. unsafe { core::ptr::write_bytes(pointer.as_ptr(), 0, bytes) }; Some(pointer) } else { @@ -619,6 +680,10 @@ impl Objects { } return self.alloc_private(req); } + // Session objects are write-combined: they never give the firmware a cached record. + if req.class == Class::FwCoherent { + return Err(EINVAL); + } if self.sealed { return Err(EBUSY); } diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index a599515ffc0a90..761b6bac29c192 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassSlot, Placement}, + slots::{ComputeSlot, PassCmds, PassSlot, Placement}, vm::VmState, }; use crate::mmu; @@ -20,6 +20,60 @@ use kernel::{ sync::{Arc, CondVar, CondVarTimeoutResult, Mutex, SetOnce, SpinLockIrq}, }; +/// One pass slot index's device-lifetime render command records and the allocator that maps +/// them. The allocator is never dropped: an ASC-cached M4 mapping has no qualified teardown +/// (`mmu::KernelMapping::drop` refuses it), so even a failed construction keeps its mappings. +struct PersistentPassCmds { + objects: core::mem::ManuallyDrop, + cmds: Option, +} + +/// The firmware-cached render microsequences and barrier records of every pass slot index +/// (`0..RENDER_SLOTS`), created on first use and kept until reboot. A pass slot index is +/// device-global and claimed by one flight at a time, so every VM's [`PassSlot`] of an index +/// shares its records, and closing a VM drops no firmware-cached mapping. +#[pin_data] +pub(crate) struct RenderCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::RENDER_SLOTS]>, +} + +impl RenderCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::RENDER_SLOTS], + "g16::render_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of pass slot index `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { + return Ok(cmds.clone()); + } + let mut set = KBox::new( + PersistentPassCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + cmds: None, + }, + GFP_KERNEL, + )?; + // From here on a failure leaks the allocator with whatever it mapped. + let cmds = PassCmds::new(&mut set.objects)?; + set.objects.finish_private()?; + set.cmds = Some(cmds.clone()); + *entry = Some(set); + Ok(cmds) + } +} + /// 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 @@ -167,14 +221,15 @@ impl ComputeUnitSet { pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; /// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). /// -/// Each extension `PassSlot` backs 3.59 MiB (2 MiB TPC + 1 MiB tilemap + 608 KiB metadata, -/// scratch, and barriers). Growing in four bounded chunks keeps compositor and shallow desktop -/// VMs on Tier 0 (~21.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, -/// and keeps every tier's client-object batch well below `MAX_CLIENT` (512): -/// - Tier 0 (`2..8`, 6 slots, +21.56 MiB / 21.56 MiB cum): compositors, 2-6 pass frames. -/// - Tier 1 (`8..18`, 10 slots, +35.94 MiB / 57.50 MiB cum): moderate multi-pass bursts. -/// - Tier 2 (`18..32`, 14 slots, +50.31 MiB / 107.81 MiB cum): 20-31 pass pipelined frames. -/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +57.50 MiB / 165.31 MiB cum at 48 slots): deep +/// Each extension `PassSlot` backs 3.47 MiB (2 MiB TPC + 1 MiB tilemap + 480 KiB metadata and +/// scratch; its microsequences and barriers are the device-lifetime [`RenderCmds`] of its index). +/// Growing in four bounded chunks keeps compositor and shallow desktop VMs on Tier 0 +/// (~20.8 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and keeps +/// every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +20.81 MiB / 20.81 MiB cum): compositors, 2-6 pass frames. +/// - Tier 1 (`8..18`, 10 slots, +34.69 MiB / 55.50 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..32`, 14 slots, +48.56 MiB / 104.06 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.50 MiB / 159.56 MiB cum at 48 slots): deep /// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ (BASE_RENDER_SLOTS, 8), @@ -324,8 +379,8 @@ fn should_expand_compute_ext( /// /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives /// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay -/// on the two base pass slots (~49.2 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, -/// +21.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// on the two base pass slots (~48.9 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, +/// +20.8 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, /// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a /// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission /// and one displacement slot exceed the currently backed capacity. @@ -467,7 +522,8 @@ impl RenderArena { let mut objects = factory.objects(vm); 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 cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; } let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; @@ -565,7 +621,8 @@ impl RenderExtArena { let mut tilemap_clean = KVec::with_capacity(count, GFP_KERNEL)?; let mut heap_dirty = KVec::with_capacity(count, GFP_KERNEL)?; for k in slots.clone() { - passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; + let cmds = factory.pass_cmds(k)?; + passes.push(PassSlot::new(&mut objects, k as u64, 1, &cmds)?, GFP_KERNEL)?; tpc_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; tilemap_dirty.push(AtomicU64::new(0), GFP_KERNEL)?; tilemap_last.push(AtomicU64::new(0), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 22a83b59b690f6..711bcdae9a0256 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -264,6 +264,56 @@ impl ComputeSlot { } } +/// The render microsequences and barrier records of one pass slot index, shared by every VM's +/// [`PassSlot`] of that index: the index is device-global and claimed by one flight at a time. +/// They are written by the host before publication and only read by the firmware, so they take +/// the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command +/// objects. Each microsequence keeps its own page; the barrier records share one page, as the +/// compute unit's barriers do. +#[derive(Clone)] +pub(crate) struct PassCmds { + pub(crate) ta_seq: Arc, + pub(crate) fs_seq: Arc, + pub(crate) own_barrier: Arc, + pub(crate) prev_barrier: Arc, + pub(crate) ta_fs_barrier: Arc, + pub(crate) fs_dep: Arc, + pub(crate) compute_barrier: Arc, + pub(crate) fs_compute_barrier: Arc, +} + +impl PassCmds { + /// Barrier records in the shared page: own, prev, TA->FS, FS dependency (one record each), + /// then the per-pipe compute and FS-compute barriers. + const OWN: usize = 0; + const PREV: usize = barrier::SIZE; + const TA_FS: usize = 2 * barrier::SIZE; + const FS_DEP: usize = 3 * barrier::SIZE; + const COMPUTE: usize = 4 * barrier::SIZE; + const FS_COMPUTE: usize = Self::COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + const BARRIERS: usize = Self::FS_COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; + + /// Allocates one pass slot index's set from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + pub(crate) fn new(o: &mut Objects) -> Result { + let coherent = Class::FwCoherent; + let barriers = alloc(o, Self::BARRIERS, coherent, None, 0, false)?; + let record = |offset, size| FwObject::view(&barriers, offset, size); + Ok(Self { + ta_seq: alloc(o, ta::SEQ_OBJECT, coherent, None, 0, false)?, + fs_seq: alloc(o, fs::SEQ_OBJECT, coherent, None, 0, false)?, + own_barrier: record(Self::OWN, barrier::SIZE)?, + prev_barrier: record(Self::PREV, barrier::SIZE)?, + ta_fs_barrier: record(Self::TA_FS, barrier::SIZE)?, + fs_dep: record(Self::FS_DEP, barrier::SIZE)?, + compute_barrier: record(Self::COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + fs_compute_barrier: record(Self::FS_COMPUTE, barrier::SIZE * sizes::COMPUTE_PIPES)?, + }) + } +} + +const _: () = assert!(PassCmds::BARRIERS <= super::hw::PAGE as usize); + /// One render pass slot. pub(crate) struct PassSlot { pub(crate) aux: Arc, @@ -292,8 +342,9 @@ pub(crate) struct PassSlot { } impl PassSlot { - /// Allocates pass slot `i`'s objects, with their client leaf classes. - pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32) -> Result { + /// Allocates pass slot `i`'s objects, with their client leaf classes, around the + /// device-lifetime microsequences and barrier records `cmds` of index `i`. + pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32, cmds: &PassCmds) -> Result { let sh = Class::Shared; let off = client::pass_off(i); let tpc = if i >= sizes::BASE_RENDER_SLOTS as u64 { @@ -393,33 +444,19 @@ impl PassSlot { fs_scratch, fs_work, ta_work, - ta_seq: alloc(o, ta::SEQ_OBJECT, cmd_fw(), None, 0, false)?, - fs_seq: alloc(o, fs::SEQ_OBJECT, cmd_fw(), None, 0, false)?, + ta_seq: cmds.ta_seq.clone(), + fs_seq: cmds.fs_seq.clone(), ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, scene: alloc(o, super::fw::work::scene::SIZE, sh, None, 0, false)?, // Internal TA start/end, FS start/end; legacy user cells likewise. its: alloc(o, 32, sh, None, 0, false)?, _uts: alloc(o, 32, Class::Fw, None, 0, false)?, - own_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - prev_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - ta_fs_barrier: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - fs_dep: alloc(o, barrier::SIZE, cmd_fw(), None, 0, false)?, - compute_barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, - fs_compute_barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, + own_barrier: cmds.own_barrier.clone(), + prev_barrier: cmds.prev_barrier.clone(), + ta_fs_barrier: cmds.ta_fs_barrier.clone(), + fs_dep: cmds.fs_dep.clone(), + compute_barrier: cmds.compute_barrier.clone(), + fs_compute_barrier: cmds.fs_compute_barrier.clone(), }) } 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 9e5331c254c9f3..64f7305725f5b0 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -94,7 +94,7 @@ def module(text, name): } pub mod object { use crate::*;use crate::sync::Arc; - #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,Mmio} + #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,FwCoherent,Mmio} pub enum Placement{Anywhere} pub struct Request{pub size:usize,pub class:Class,pub placement:Placement,pub offset:usize,pub client:Option<(u64,u64)>,pub lower:Option,pub cpu:bool} pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool,pub write_bytes:std::sync::atomic::AtomicUsize} @@ -118,15 +118,28 @@ def module(text, name): impl Factory{ pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} pub fn fw_objects(&self)->Objects{Objects::new()} + pub fn persistent_objects(&self)->Objects{Objects::persistent()} } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} - pub struct Objects{pub objects:Vec>} + pub struct Objects{pub objects:Vec>,pub persistent:bool} + // Device-lifetime render records of each pass slot index, per test thread (the + // production table is resources::RenderCmds): one never-dropped allocator owns them. + std::thread_local!{ + pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; + pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + } + pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ + if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ - pub fn new()->Self{Self{objects:vec![]}} + pub fn new()->Self{Self{objects:vec![],persistent:false}} + pub fn persistent()->Self{Self{objects:vec![],persistent:true}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()||r.lower.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -274,7 +287,7 @@ def module(text, name): fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<,lower:Option|Request{size:0x40,class,placement:Placement::Anywhere,offset:0,client,lower,cpu:true}; + // A per-VM arena cannot map a firmware-cached record (its teardown would unmap it), and + // a device-lifetime allocator cannot give one a client or lower alias. + let mut vm=Objects::new(); + assert!(matches!(vm.alloc(req(Class::FwCoherent,None,None)),Err(EINVAL))); + let mut dev=Objects::persistent(); + assert!(matches!(dev.alloc(req(Class::FwCoherent,Some((0x7040000000,g16::hw::pte::LEAF_NC)),None)),Err(EINVAL))); + assert!(matches!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))),Err(EINVAL))); + // Two VMs' pass slot 3 share index 3's records; neither VM arena owns any of them. + let (mut a,mut b)=(Objects::new(),Objects::new()); + let pa=g16::slots::PassSlot::new(&mut a,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let pb=g16::slots::PassSlot::new(&mut b,3,1,&crate::g16::object::test_cmds(3)).unwrap(); + let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone()]; + let (ra,rb)=(records(&pa),records(&pb)); + for (x,y) in ra.iter().zip(rb.iter()){ + assert!(crate::sync::Arc::ptr_eq(x,y)); + assert_eq!(x.class,Class::FwCoherent); + assert_eq!((x.gva,x.lower_gva,x.client_leaf),(None,None,None)); + } + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|o.class!=Class::FwCoherent)); + assert!(a.objects.iter().chain(b.objects.iter()).all(|o|ra.iter().all(|r|!crate::sync::Arc::ptr_eq(o,r)))); + let pc=g16::slots::PassSlot::new(&mut b,4,1,&crate::g16::object::test_cmds(4)).unwrap(); + assert!(!crate::sync::Arc::ptr_eq(&pc.ta_seq,&pa.ta_seq)&&!crate::sync::Arc::ptr_eq(&pc.own_barrier,&pa.own_barrier)); + // Microsequences keep whole pages; the barrier records are disjoint 0x40-aligned + // records of one page; the encoders name the shared records. + assert_eq!((pa.ta_seq.va&0x3fff,pa.fs_seq.va&0x3fff),(0,0)); + let page=ra[2].va&!0x3fff; + let mut spans:Vec<(u64,u64)>=ra[2..].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); + spans.sort(); + assert!(spans.windows(2).all(|w|w[0].1<=w[1].0)); + assert!(ra[2..].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pb.refs().ta_seq,pb.refs().fs_seq)); + assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pa.ta_seq.va,pa.fs_seq.va)); + // Closing VM a drops its arena and pass slot: the device table still owns and hands + // out the same records, mapped by its never-dropped allocator. + drop(pa);drop(a); + let again=crate::g16::object::test_cmds(3); + assert!(crate::sync::Arc::ptr_eq(&again.ta_seq,&rb[0])&&crate::sync::Arc::ptr_eq(&again.fs_dep,&rb[5])); + crate::g16::object::PERSISTENT.with(|p|{ + let p=p.borrow();let owned=&p.as_ref().unwrap().objects; + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[0]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[1]))); + assert!(owned.iter().all(|o|o.class==Class::FwCoherent)); + }); + drop(pb);drop(pc);drop(b); + } #[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); let work=arena.compute.compute.iter().map(|s|&s.work) @@ -682,7 +743,7 @@ def module(text, name): let mut scene_lists=Vec::new(); let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); for k in 0..g16::hw::sizes::RENDER_SLOTS as u64 { - let pass=g16::slots::PassSlot::new(&mut o,k,1).unwrap(); + let pass=g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(); let va=pass.refs().scene_list; assert_ne!(va,0); assert!(!scene_lists.contains(&va),"each pass slot must own a distinct scene_list"); @@ -692,7 +753,7 @@ def module(text, name): for &(start, end) in &g16::resources::EXT_RENDER_TIERS { let mut ot = Objects::new(); for k in start..end { - g16::slots::PassSlot::new(&mut ot, k as u64, 1).unwrap(); + g16::slots::PassSlot::new(&mut ot, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(); } let tier_maps = count_client(&ot); assert!( @@ -1023,7 +1084,7 @@ def module(text, name): 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 { - let pass=g16::slots::PassSlot::new(&mut o,k,1).unwrap(); + let pass=g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(); if k < g16::hw::sizes::BASE_RENDER_SLOTS as u64 { assert_eq!(pass.tpc.size as u64, g16::hw::client::TPC_SIZE); assert_eq!(pass.tilemap.size as u64, g16::hw::client::TILEMAP_SIZE); @@ -1129,6 +1190,7 @@ def module(text, name): assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); } + #[test]fn offlock_scrub_falls_back_on_error_drop_recovery_and_cross_vm(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); let render=sync::Arc::new(arena.render,0).unwrap(); @@ -1262,7 +1324,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); 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(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; @@ -1324,7 +1386,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); 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(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:arena.compute.compute,render:Some(render),hw_slots:None}; @@ -1470,20 +1532,26 @@ def module(text, name): // Verify exact per-slot mapped backing bytes for Base vs Ext slots. let mut o_base = Objects::new(); - g16::slots::PassSlot::new(&mut o_base, 0, 1).unwrap(); + g16::slots::PassSlot::new(&mut o_base, 0, 1, &crate::g16::object::test_cmds((0) as u64)).unwrap(); let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 608) * 1024); + // Microsequences and barrier records are the device-lifetime records of the index. + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 480) * 1024); let mut o_ext = Objects::new(); - g16::slots::PassSlot::new(&mut o_ext, 2, 1).unwrap(); + g16::slots::PassSlot::new(&mut o_ext, 2, 1, &crate::g16::object::test_cmds((2) as u64)).unwrap(); let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 608) * 1024); + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 480) * 1024); + // Each index's device-lifetime records: two microsequence pages and one barrier page. + let indices = crate::g16::object::PASS_CMDS.with(|p| p.borrow().len()); + let device_bytes: usize = crate::g16::object::PERSISTENT + .with(|p| p.borrow().as_ref().unwrap().objects.iter().map(|obj| obj.mapped).sum()); + assert_eq!((indices, device_bytes), (2, 2 * 3 * 16 * 1024)); // Cumulative extension backing across the 4 demand-grown tiers: - // Tier 0 (6 ext): 21.5625 MiB, Tier 1 (16 ext): 57.50 MiB, - // Tier 2 (30 ext): 107.8125 MiB, Tier 3 (46 ext): 165.3125 MiB. - assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 22_080 * 1024); - assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 58_880 * 1024); - assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 110_400 * 1024); - assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 169_280 * 1024); + // Tier 0 (6 ext): 20.8125 MiB, Tier 1 (16 ext): 55.50 MiB, + // Tier 2 (30 ext): 104.0625 MiB, Tier 3 (46 ext): 159.5625 MiB. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_312 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_832 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 106_560 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 163_392 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -1678,7 +1746,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..4u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render),hw_slots:None}; @@ -1771,7 +1839,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut passes=KVec::new(); for k in 0..3u64 { - passes.push(g16::slots::PassSlot::new(&mut o,k,1).unwrap(),0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap(); } let render=sync::Arc::new(render_arena(passes),0).unwrap(); let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; @@ -2116,7 +2184,7 @@ def module(text, name): let mut s = Slots::new().unwrap(); let mut passes = KVec::new(); for k in 0..EXT_RENDER_TIERS[1].1 { - passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let render = sync::Arc::new(render_arena(passes), 0).unwrap(); let prep = g16::resources::ComputeArena { @@ -2210,7 +2278,7 @@ def module(text, name): } let mut passes = KVec::new(); for k in 0..18 { - passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let shared_prep_compute = ComputeArena { compute: compute_slots, render: None, hw_slots: None }; let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; @@ -2227,7 +2295,7 @@ def module(text, name): let pb_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); let mut r_passes = KVec::new(); for k in 0..18 { - r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + r_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()), hw_slots: None }; @@ -2394,7 +2462,7 @@ def module(text, name): let mut s2 = Slots::new().unwrap(); let mut sc_passes = KVec::new(); for k in 0..2 { - sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + sc_passes.push(PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); } let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()), hw_slots: None }; @@ -2828,7 +2896,7 @@ def module(text, name): ).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') source = source.replace('__GRAPH_TYPES__', graph_types) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) -source = source.replace('__HW__','\n'.join(module(hw,n) for n in ('client','sizes','engine','tuning','pte'))).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) +source = source.replace('__HW__','\n'.join([module(hw,n) for n in ('client','sizes','engine','tuning','pte')] + [l for l in hw.splitlines() if l.startswith('pub(crate) const PAGE: u64')])).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) (out/'check-resources.rs').write_text(source) log = '' for command in [ From e6d8e0ae150098e05a149131f1c7227c5aacbbc0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:31:14 -0500 Subject: [PATCH 0894/1514] drm/asahi: g16: share device-lifetime firmware-cached render work images Move the TA and FS work images, the larger part of what the firmware reads per render, into the per-index device-lifetime RenderCmds records. macOS 26B123 maps its per-queue command objects, work items included, with the firmware-cached leaf 0x443 and maps the same pages into GPU context 0 with the uncached leaf 0xc8b. The work images keep that uncached kernel GPU task lower alias. Because the host writes to the work images through a cacheable mapping while the GPU reads their register lists through the uncached alias, FwObject cleans each store to such an object to the point of coherency (dc cvac, then dsb sy). Only a firmware-cached object with a lower alias performs this clean; the microsequences and barriers, which only the firmware reads, are unchanged. Each pass slot index now holds five device-lifetime pages (80 KiB, at most 3.75 MiB per boot) and every VM pass slot sheds two more pages (448 KiB of metadata). Compute command objects are unchanged because the host reads firmware-written descriptor counters from the compute work image. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/object.rs | 44 +++++++++---- drivers/gpu/drm/asahi/g16/resources.rs | 31 +++++----- drivers/gpu/drm/asahi/g16/slots.rs | 62 ++++++++++++------- .../drivers/gpu/asahi-m4/test-resources.py | 56 +++++++++++------ 4 files changed, 125 insertions(+), 68 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index e5329887c1e9c3..c4c42d1dd1290f 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -46,12 +46,14 @@ pub(crate) enum Class { Shared, /// Firmware and GPU, ASC-cached. SharedCached, - /// Firmware-only, ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS - /// 26B123 gives its per-queue command objects and the G13-G15 private-allocator contract - /// (`PROT_FW_PRIV_RW` behind `gem::new_kernel_object`). Only for records the host writes - /// before publication and the firmware only reads, with no client or lower alias, and only + /// ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS 26B123 gives its + /// per-queue command objects and the G13-G15 private-allocator contract (`PROT_FW_PRIV_RW` + /// behind `gem::new_kernel_object`). Only for command records the host writes before + /// publication and never reads back what the firmware writes, with no client alias, and only /// from device-lifetime allocators ([`Factory::persistent_objects`]): an ASC-cached M4 - /// mapping has no qualified teardown, so its owner is never dropped. + /// mapping has no qualified teardown, so its owner is never dropped. A kernel GPU task lower + /// alias stays uncached, as macOS maps its work items for the GPU; host stores to such an + /// object are cleaned to the point of coherency for it ([`FwObject::write`]). FwCoherent, /// Firmware device mapping. #[allow(dead_code)] @@ -108,6 +110,9 @@ pub(crate) struct FwObject { // Subrecords retain the owning WC vmap as well as their GEM. _parent: Option>, limit: Option, + /// Host stores go through a cacheable view the GPU reads through its uncached lower alias: + /// each store is cleaned to the point of coherency. + clean: bool, } // SAFETY: The object only refers to kernel memory shared with the firmware; every host access @@ -156,17 +161,27 @@ impl FwObject { backing: gem::ObjectRef::new(object.gem()), _parent: Some(object.clone()), limit: Some(size), + clean: object.clean, }, GFP_KERNEL, )?) } + /// Makes host stores to `len` bytes at `p` visible to an uncached GPU alias. + fn stored(&self, p: *const u8, len: usize) { + if self.clean { + crate::pgtable::clean_poc(p, len); + crate::pgtable::poc_barrier(); + } + } + /// Copies bytes into the object before it is published, or into host-owned words. pub(crate) fn write(&self, offset: usize, bytes: &[u8]) -> Result { let p = self.ptr(offset, bytes.len())?; // SAFETY: `p` is valid for `bytes.len()` bytes of the object's mapping, which no Rust // reference aliases. unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()) }; + self.stored(p, bytes.len()); Ok(()) } @@ -175,6 +190,7 @@ impl FwObject { let p = self.ptr(offset, len)?; // SAFETY: As for `write`. unsafe { core::ptr::write_bytes(p, value, len) }; + self.stored(p, len); Ok(()) } @@ -184,6 +200,7 @@ impl FwObject { if p as usize % 4 == 0 { // SAFETY: `p` is valid and aligned for a u32. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 4); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -196,6 +213,7 @@ impl FwObject { if p as usize % 8 == 0 { // SAFETY: `p` is valid and aligned for a u64. unsafe { p.cast::().write_volatile(value.to_le()) }; + self.stored(p, 8); Ok(()) } else { self.write(offset, &value.to_le_bytes()) @@ -404,8 +422,8 @@ impl Factory { } } - /// The device-lifetime render microsequences and barrier records of pass slot `k`, shared by - /// every VM's [`super::slots::PassSlot`] `k`. + /// The device-lifetime render command records of pass slot `k`, shared by every VM's + /// [`super::slots::PassSlot`] `k`. pub(crate) fn pass_cmds(&self, k: usize) -> Result { self.render_cmds.get(self, k) } @@ -505,10 +523,7 @@ impl Objects { if !matches!(req.placement, Placement::Anywhere) || !matches!(req.class, Class::Fw | Class::Shared | Class::FwCoherent) || (req.class == Class::FwCoherent - && (!self.persistent - || req.client.is_some() - || req.lower.is_some() - || client_range.is_some())) + && (!self.persistent || req.client.is_some() || client_range.is_some())) || req.size == 0 || req.offset >= hw::PAGE as usize { @@ -534,11 +549,16 @@ impl Objects { let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; + let clean = req.class == Class::FwCoherent && req.lower.is_some(); let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; // SAFETY: Fresh private mapping spans bytes and has not been exposed. unsafe { core::ptr::write_bytes(pointer.as_ptr(), 0, bytes) }; + if clean { + crate::pgtable::clean_poc(pointer.as_ptr(), bytes); + crate::pgtable::poc_barrier(); + } Some(pointer) } else { None @@ -622,6 +642,7 @@ impl Objects { backing, _parent: None, limit: None, + clean, }, GFP_KERNEL, )?; @@ -777,6 +798,7 @@ impl Objects { backing, _parent: None, limit: None, + clean: false, }) .into(); self.retained.push(object.clone(), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 761b6bac29c192..25b0d609a3d2a1 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -28,10 +28,11 @@ struct PersistentPassCmds { cmds: Option, } -/// The firmware-cached render microsequences and barrier records of every pass slot index -/// (`0..RENDER_SLOTS`), created on first use and kept until reboot. A pass slot index is -/// device-global and claimed by one flight at a time, so every VM's [`PassSlot`] of an index -/// shares its records, and closing a VM drops no firmware-cached mapping. +/// The firmware-cached render command records (work images, microsequences and barrier records) +/// of every pass slot index (`0..RENDER_SLOTS`), created on first use and kept until reboot. A +/// pass slot index is device-global and claimed by one flight at a time, so every VM's +/// [`PassSlot`] of an index shares its records, and closing a VM drops no firmware-cached +/// mapping. #[pin_data] pub(crate) struct RenderCmds { #[pin] @@ -66,7 +67,7 @@ impl RenderCmds { GFP_KERNEL, )?; // From here on a failure leaks the allocator with whatever it mapped. - let cmds = PassCmds::new(&mut set.objects)?; + let cmds = PassCmds::new(&mut set.objects, k as u64)?; set.objects.finish_private()?; set.cmds = Some(cmds.clone()); *entry = Some(set); @@ -221,15 +222,15 @@ impl ComputeUnitSet { pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; /// Demand-grown extension render pass slot tiers (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`). /// -/// Each extension `PassSlot` backs 3.47 MiB (2 MiB TPC + 1 MiB tilemap + 480 KiB metadata and -/// scratch; its microsequences and barriers are the device-lifetime [`RenderCmds`] of its index). -/// Growing in four bounded chunks keeps compositor and shallow desktop VMs on Tier 0 -/// (~20.8 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and keeps -/// every tier's client-object batch well below `MAX_CLIENT` (512): -/// - Tier 0 (`2..8`, 6 slots, +20.81 MiB / 20.81 MiB cum): compositors, 2-6 pass frames. -/// - Tier 1 (`8..18`, 10 slots, +34.69 MiB / 55.50 MiB cum): moderate multi-pass bursts. -/// - Tier 2 (`18..32`, 14 slots, +48.56 MiB / 104.06 MiB cum): 20-31 pass pipelined frames. -/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.50 MiB / 159.56 MiB cum at 48 slots): deep +/// Each extension `PassSlot` backs 3.44 MiB (2 MiB TPC + 1 MiB tilemap + 448 KiB metadata and +/// scratch; its work images, microsequences and barriers are the device-lifetime [`RenderCmds`] +/// of its index). Growing in four bounded chunks keeps compositor and shallow desktop VMs on +/// Tier 0 (~20.6 MiB), keeps 20-31 pass workloads on Tier 2 without paying for 48 slots, and +/// keeps every tier's client-object batch well below `MAX_CLIENT` (512): +/// - Tier 0 (`2..8`, 6 slots, +20.63 MiB / 20.63 MiB cum): compositors, 2-6 pass frames. +/// - Tier 1 (`8..18`, 10 slots, +34.38 MiB / 55.00 MiB cum): moderate multi-pass bursts. +/// - Tier 2 (`18..32`, 14 slots, +48.13 MiB / 103.13 MiB cum): 20-31 pass pipelined frames. +/// - Tier 3 (`32..RENDER_SLOTS`, 16 slots, +55.00 MiB / 158.13 MiB cum at 48 slots): deep /// multi-pass bursts (160 client mappings <= `MAX_CLIENT`). pub(crate) const EXT_RENDER_TIERS: [(usize, usize); 4] = [ (BASE_RENDER_SLOTS, 8), @@ -380,7 +381,7 @@ fn should_expand_compute_ext( /// Steady 60/120 Hz single-pass depth-1 clients finish each frame before the next arrives /// (`active_passes == 0`, `render_count == 1`, inter-frame gap >= `BURST_GAP_NS`) and stay /// on the two base pass slots (~48.9 MiB). Extension tiers grow on demand: Tier 0 (`2..8`, -/// +20.8 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, +/// +20.6 MiB) allocates when a base pass slot is quarantined, a VM overlaps an in-flight render, /// submits a multi-pass command stream (`render_count >= BASE_RENDER_SLOTS`), or sustains a /// sub-2 ms back-to-back burst; higher tiers allocate only when live passes plus this submission /// and one displacement slot exceed the currently backed capacity. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 711bcdae9a0256..f6952828e1ecaf 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -264,14 +264,18 @@ impl ComputeSlot { } } -/// The render microsequences and barrier records of one pass slot index, shared by every VM's -/// [`PassSlot`] of that index: the index is device-global and claimed by one flight at a time. -/// They are written by the host before publication and only read by the firmware, so they take -/// the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command -/// objects. Each microsequence keeps its own page; the barrier records share one page, as the -/// compute unit's barriers do. +/// The render command records of one pass slot index (TA and FS work images, microsequences and +/// barrier records), shared by every VM's [`PassSlot`] of that index: the index is device-global +/// and claimed by one flight at a time. The host writes them before publication and never reads +/// back what the firmware writes, so they take the firmware-cached [`Class::FwCoherent`] view +/// macOS 26B123 gives its per-queue command objects. The work images keep their uncached kernel +/// GPU task lower alias, as macOS maps its work items for the GPU. Each work image and +/// microsequence keeps its own page; the barrier records share one page, as the compute unit's +/// barriers do. #[derive(Clone)] pub(crate) struct PassCmds { + pub(crate) ta_work: Arc, + pub(crate) fs_work: Arc, pub(crate) ta_seq: Arc, pub(crate) fs_seq: Arc, pub(crate) own_barrier: Arc, @@ -293,13 +297,37 @@ impl PassCmds { const FS_COMPUTE: usize = Self::COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; const BARRIERS: usize = Self::FS_COMPUTE + barrier::SIZE * sizes::COMPUTE_PIPES; - /// Allocates one pass slot index's set from a device-lifetime allocator + /// Allocates pass slot index `i`'s set from a device-lifetime allocator /// ([`Factory::persistent_objects`]), which the caller never drops. - pub(crate) fn new(o: &mut Objects) -> Result { + pub(crate) fn new(o: &mut Objects, i: u64) -> Result { let coherent = Class::FwCoherent; + let off = client::pass_off(i); + let mut work = |size, page, offset| { + o.alloc(super::object::Request { + size, + class: coherent, + placement: super::object::Placement::Anywhere, + offset, + client: None, + lower: Some(page), + cpu: true, + }) + }; + let fs_work = work( + fs::WORK_SIZE, + client::FS_WORK_PAGE + off, + client::FS_WORK_OFF as usize, + )?; + let ta_work = work( + ta::WORK_SIZE, + client::TA_WORK_PAGE + off, + client::TA_WORK_OFF as usize, + )?; let barriers = alloc(o, Self::BARRIERS, coherent, None, 0, false)?; let record = |offset, size| FwObject::view(&barriers, offset, size); Ok(Self { + ta_work, + fs_work, ta_seq: alloc(o, ta::SEQ_OBJECT, coherent, None, 0, false)?, fs_seq: alloc(o, fs::SEQ_OBJECT, coherent, None, 0, false)?, own_barrier: record(Self::OWN, barrier::SIZE)?, @@ -343,7 +371,7 @@ pub(crate) struct PassSlot { impl PassSlot { /// Allocates pass slot `i`'s objects, with their client leaf classes, around the - /// device-lifetime microsequences and barrier records `cmds` of index `i`. + /// device-lifetime command records `cmds` of index `i`. pub(crate) fn new(o: &mut Objects, i: u64, pre_records: u32, cmds: &PassCmds) -> Result { let sh = Class::Shared; let off = client::pass_off(i); @@ -421,18 +449,6 @@ impl PassSlot { 0, false, )?; - let fs_work = alloc_work( - o, - fs::WORK_SIZE, - client::FS_WORK_PAGE + off, - client::FS_WORK_OFF as usize, - )?; - let ta_work = alloc_work( - o, - ta::WORK_SIZE, - client::TA_WORK_PAGE + off, - client::TA_WORK_OFF as usize, - )?; Ok(Self { aux, pre, @@ -442,8 +458,8 @@ impl PassSlot { scene_user, scene_list, fs_scratch, - fs_work, - ta_work, + fs_work: cmds.fs_work.clone(), + ta_work: cmds.ta_work.clone(), ta_seq: cmds.ta_seq.clone(), fs_seq: cmds.fs_seq.clone(), ta_scratch: alloc(o, 0x10000, sh, None, 0, false)?, 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 64f7305725f5b0..2df865d4f856aa 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -131,7 +131,7 @@ def module(text, name): } pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} - let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c } impl Objects{ @@ -139,7 +139,7 @@ def module(text, name): pub fn persistent()->Self{Self{objects:vec![],persistent:true}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()||r.lower.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -354,18 +354,23 @@ def module(text, name): assert!(matches!(vm.alloc(req(Class::FwCoherent,None,None)),Err(EINVAL))); let mut dev=Objects::persistent(); assert!(matches!(dev.alloc(req(Class::FwCoherent,Some((0x7040000000,g16::hw::pte::LEAF_NC)),None)),Err(EINVAL))); - assert!(matches!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))),Err(EINVAL))); + assert!(dev.alloc(req(Class::FwCoherent,None,Some(0x70f1000000))).is_ok()); // Two VMs' pass slot 3 share index 3's records; neither VM arena owns any of them. let (mut a,mut b)=(Objects::new(),Objects::new()); let pa=g16::slots::PassSlot::new(&mut a,3,1,&crate::g16::object::test_cmds(3)).unwrap(); let pb=g16::slots::PassSlot::new(&mut b,3,1,&crate::g16::object::test_cmds(3)).unwrap(); - let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone()]; + let records=|p:&g16::slots::PassSlot|[p.ta_seq.clone(),p.fs_seq.clone(),p.own_barrier.clone(),p.prev_barrier.clone(),p.ta_fs_barrier.clone(),p.fs_dep.clone(),p.compute_barrier.clone(),p.fs_compute_barrier.clone(),p.ta_work.clone(),p.fs_work.clone()]; let (ra,rb)=(records(&pa),records(&pb)); - for (x,y) in ra.iter().zip(rb.iter()){ + for (i,(x,y)) in ra.iter().zip(rb.iter()).enumerate(){ assert!(crate::sync::Arc::ptr_eq(x,y)); assert_eq!(x.class,Class::FwCoherent); - assert_eq!((x.gva,x.lower_gva,x.client_leaf),(None,None,None)); + assert_eq!((x.gva,x.client_leaf),(None,None)); + // Only the work images have the (uncached) kernel GPU task lower alias. + assert_eq!(x.lower_gva.is_some(),i>=8); } + assert!(ra[8..].iter().all(|o|o.lower_leaf==Some(g16::hw::pte::LOWER))); + assert_eq!((pa.refs().ta_work_gva,pa.refs().fs_work_gva),(pb.refs().ta_work_gva,pb.refs().fs_work_gva)); + assert_eq!((pa.refs().ta_work,pa.refs().ta_work_gva),(ra[8].va,ra[8].lower_gva.unwrap())); assert!(a.objects.iter().chain(b.objects.iter()).all(|o|o.class!=Class::FwCoherent)); assert!(a.objects.iter().chain(b.objects.iter()).all(|o|ra.iter().all(|r|!crate::sync::Arc::ptr_eq(o,r)))); let pc=g16::slots::PassSlot::new(&mut b,4,1,&crate::g16::object::test_cmds(4)).unwrap(); @@ -374,10 +379,10 @@ def module(text, name): // records of one page; the encoders name the shared records. assert_eq!((pa.ta_seq.va&0x3fff,pa.fs_seq.va&0x3fff),(0,0)); let page=ra[2].va&!0x3fff; - let mut spans:Vec<(u64,u64)>=ra[2..].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); + let mut spans:Vec<(u64,u64)>=ra[2..8].iter().map(|o|(o.va,o.va+o.size as u64)).collect(); spans.sort(); assert!(spans.windows(2).all(|w|w[0].1<=w[1].0)); - assert!(ra[2..].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); + assert!(ra[2..8].iter().all(|o|o.va&!0x3fff==page&&o.va%0x40==0&&o.va+o.size as u64<=page+0x4000)); assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pb.refs().ta_seq,pb.refs().fs_seq)); assert_eq!((pa.refs().ta_seq,pa.refs().fs_seq),(pa.ta_seq.va,pa.fs_seq.va)); // Closing VM a drops its arena and pass slot: the device table still owns and hands @@ -389,12 +394,16 @@ def module(text, name): let p=p.borrow();let owned=&p.as_ref().unwrap().objects; assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[0]))); assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[1]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[8]))); + assert!(owned.iter().any(|o|crate::sync::Arc::ptr_eq(o,&rb[9]))); assert!(owned.iter().all(|o|o.class==Class::FwCoherent)); }); drop(pb);drop(pc);drop(b); } #[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); + assert!(arena.compute.compute.iter().all(|s|s.work.class==g16::object::Class::Shared)); + assert!(arena.render.passes.iter().all(|s|s.ta_work.class==g16::object::Class::FwCoherent&&s.fs_work.class==g16::object::Class::FwCoherent)); let work=arena.compute.compute.iter().map(|s|&s.work) .chain(arena.render.passes.iter().flat_map(|s|[&s.ta_work,&s.fs_work])); for object in work { @@ -402,7 +411,7 @@ def module(text, name): assert_eq!(object.client_leaf,None); assert!(object.lower_gva.is_some()); assert_eq!(object.lower_leaf,Some(0x00c0000000000c8b)); - assert_eq!(object.class,g16::object::Class::Shared); + assert!(object.class==g16::object::Class::Shared||object.class==g16::object::Class::FwCoherent); assert!(object.va>=0xfffffc2000000000); let lower=object.lower_gva.unwrap(); for client in &o.objects { @@ -1535,23 +1544,24 @@ def module(text, name): g16::slots::PassSlot::new(&mut o_base, 0, 1, &crate::g16::object::test_cmds((0) as u64)).unwrap(); let base_slot_bytes: usize = o_base.objects.iter().map(|obj| obj.mapped).sum(); // Microsequences and barrier records are the device-lifetime records of the index. - assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 480) * 1024); + assert_eq!(base_slot_bytes, (16 * 1024 + 8 * 1024 + 448) * 1024); let mut o_ext = Objects::new(); g16::slots::PassSlot::new(&mut o_ext, 2, 1, &crate::g16::object::test_cmds((2) as u64)).unwrap(); let ext_slot_bytes: usize = o_ext.objects.iter().map(|obj| obj.mapped).sum(); - assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 480) * 1024); - // Each index's device-lifetime records: two microsequence pages and one barrier page. + assert_eq!(ext_slot_bytes, (2 * 1024 + 1024 + 448) * 1024); + // Each index's device-lifetime records: two work image pages, two microsequence pages + // and one barrier page. let indices = crate::g16::object::PASS_CMDS.with(|p| p.borrow().len()); let device_bytes: usize = crate::g16::object::PERSISTENT .with(|p| p.borrow().as_ref().unwrap().objects.iter().map(|obj| obj.mapped).sum()); - assert_eq!((indices, device_bytes), (2, 2 * 3 * 16 * 1024)); + assert_eq!((indices, device_bytes), (2, 2 * 5 * 16 * 1024)); // Cumulative extension backing across the 4 demand-grown tiers: - // Tier 0 (6 ext): 20.8125 MiB, Tier 1 (16 ext): 55.50 MiB, - // Tier 2 (30 ext): 104.0625 MiB, Tier 3 (46 ext): 159.5625 MiB. - assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_312 * 1024); - assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_832 * 1024); - assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 106_560 * 1024); - assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 163_392 * 1024); + // Tier 0 (6 ext): 20.625 MiB, Tier 1 (16 ext): 55.00 MiB, + // Tier 2 (30 ext): 103.125 MiB, Tier 3 (46 ext): 158.125 MiB. + assert_eq!((tier0_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 21_120 * 1024); + assert_eq!((tier1_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 56_320 * 1024); + assert_eq!((tier2_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 105_600 * 1024); + assert_eq!((full_end - BASE_RENDER_SLOTS) * ext_slot_bytes, 161_920 * 1024); } #[test]fn base_compute_quarantine_expands_fresh_vm_and_recovers_displacement(){ @@ -2861,6 +2871,14 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +object_source = (production/'object.rs').read_text() +# A firmware-cached object with an uncached GPU lower alias is cleaned to the point of +# coherency after every host store; only that combination sets the flag. +stored_fn = item(object_source, 'fn stored(&self') +assert 'crate::pgtable::clean_poc(' in stored_fn and 'crate::pgtable::poc_barrier()' in stored_fn, 'FwObject::stored must clean and complete' +for store in ('pub(crate) fn write(', 'pub(crate) fn fill(', 'pub(crate) fn w32(', 'pub(crate) fn w64('): + assert 'self.stored(' in item(object_source, store), store + ' must clean firmware-cached GPU-aliased stores' +assert object_source.count('let clean = req.class == Class::FwCoherent && req.lower.is_some();') == 1, 'only FwCoherent work with a lower alias cleans its stores' assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' assert 'ComputeArena::new(factory, bind, vm, live, k, placement)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' From d1e55b93c9a0a4c4f6916d9343b6e1d12173dd01 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 01:00:00 -0500 Subject: [PATCH 0895/1514] drm/asahi: g16: run SCS compute only beside SCS compute of its VM Ray-query compute on G16G runs with shader-context scratch (SCS). Each compute work item sets the compute engine's SCS state in its register list: a ray-query item enables the SCS window, and every other item writes it disabled. The engine pins ray-query compute to pipe 0 and holds it while compute runs on pipe 1. It still lets another VM's compute, or the same VM's non-SCS compute, queue behind a ray-query item on pipe 0, and lets a ray-query item queue behind such compute. Such an overlapped ray-query dispatch is reported complete before its results reach memory. With a ray-query process and a long-ALU process sharing the GPU, 33,091 to 35,419 of 131,072 rays still held the buffer's fill pattern when the fence signalled, with every Mesa build tried. Once the ray-query process exited, the rest of its stores were written back from the shader cores' L1 cache into its closed VM: fault bank 4: status 0x283a03a1 va 0x5bf27c5180 (write unmapped level 3 unit 0x1 ctx 29) attribution: busy=1 ctx=29 flight_matches=0 live_vm=None flights=9 When those writes filled all eight fault banks, the firmware did not finish the recovery and the GPU stopped. Let SCS compute (ray queries, and every compute command of a job with SCS scratch) share the compute engine only with SCS compute of its own VM. Other compute neither queues behind it nor runs while it is published; each waits for the other to retire. One ray-query queue still pipelines its own commands, and renders are not affected. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 25 ++++- .../drivers/gpu/asahi-m4/test-publication.py | 105 ++++++++++++++---- 2 files changed, 100 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 64467a397408a9..b67b6ba5b817d5 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -163,6 +163,18 @@ const fn cross_engine_barrier_type(producer_initbm: bool, consumer_initbm: bool) BarrierType::from_stamp_only(!producer_initbm && !consumer_initbm) } +/// Whether a compute command of `vm` that runs shader-context scratch (SCS) work (`scs`), or +/// does not, must wait for compute flight `f` to retire before it is published. +/// +/// SCS compute (ray queries, and every compute command of a job with SCS scratch) shares the +/// compute engine only with SCS compute of its own VM. Each compute work item sets the +/// engine's SCS state in its register list, enabled for SCS work and disabled otherwise. An +/// SCS item that other compute overlaps is reported complete while its stores are still in +/// flight, and they land after its fence has signalled, also after its VM is gone. +fn scs_compute_conflict(f: &Flight, vm: &Arc, scs: bool) -> bool { + f.computes != 0 && (f.rt_compute != scs || (scs && !Arc::ptr_eq(&f.job.vm, vm))) +} + /// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or /// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -1308,7 +1320,7 @@ impl Firmware { f.doomed || f.recovery_suspect || f.initbm - || (is_rt_compute && f.computes != 0 && f.compute_pipe != 0) + || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) @@ -1477,13 +1489,14 @@ impl Firmware { .flights .iter() .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); - let rt_pipe1_busy = (job.resources.compute_scs() || c.is_rt()) - && e.flights - .iter() - .any(|f| f.computes != 0 && f.compute_pipe != 0); + let scs = job.resources.compute_scs() || c.is_rt(); + let scs_conflict = e + .flights + .iter() + .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); !cross_vm_render - && !rt_pipe1_busy + && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() && !self.slots.compute_exhausted() 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 8c32b1ff744a3c..5cefe344b30903 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -94,8 +94,8 @@ def item(declaration): 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 } -impl ComputeCommand { fn is_rt(&self) -> bool { false } } +#[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } +impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } #[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 } @@ -129,8 +129,9 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false}}} +__SCS_COMPUTE_CONFLICT__ struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} impl Engine { __PICK__ @@ -283,7 +284,7 @@ def item(declaration): Arc::new(Job{id,vm, queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - 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}) + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ job_on_vm(id,mk_vm(id),render,sent,dependency) @@ -437,7 +438,7 @@ def item(declaration): id,vm:vm1.clone(), queue:Queue::new(0,priority), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // Head render (prio 2) is blocked behind active render flight; alt-class fallback @@ -556,7 +557,7 @@ def item(declaration): let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ id,vm:vm1.clone(),queue:q, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; @@ -641,7 +642,7 @@ def item(declaration): let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ id,vm:vm1.clone(),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})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, }); // Seed 4 active TA passes so TA wave pacing is active. @@ -788,6 +789,7 @@ def item(declaration): #[derive(Copy, Clone, Debug, PartialEq, Eq)] __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ + __SCS_COMPUTE_CONFLICT__ impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ __BLOCKED_ON_SLOT_HEADROOM__ @@ -805,7 +807,7 @@ def item(declaration): let q1=Queue::new(0,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})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -843,6 +845,60 @@ def item(declaration): p.slots.compute_available=false; assert!(!p.can_queue_behind(&j2)); } + #[test]fn scs_compute_shares_the_compute_engine_only_with_scs_compute_of_its_vm(){ + // gpubench compute.long: a ray-query lane (vm1) beside a long-ALU lane (vm2). The + // ray-query dispatch was reported complete with its results unwritten whenever the + // other lane's compute ran with it, and its stores then faulted in its closed VM. + 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=Queue::new(0,0); + let q2=Queue::new(0,0); + let mk=|id:u32,vm:Arc,queue:Arc,rt:bool|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt})], + order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let rq=mk(1,vm1.clone(),q1.clone(),true); + let rq_next=mk(2,vm1.clone(),q1.clone(),true); + let rq_post=mk(3,vm1.clone(),q1.clone(),false); + let alu=mk(4,vm2.clone(),q2.clone(),false); + let rq_vm2=mk(5,vm2.clone(),q2.clone(),true); + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![flight(rq.clone(),true,0)]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Behind an SCS flight only SCS compute of its own VM queues, so one ray-query + // queue keeps pipelining. + assert!(p.can_queue_behind(&rq_next)); + assert!(!p.needs_engine_drain(&rq_next)); + for j in [&alu,&rq_post,&rq_vm2] { + assert!(!p.can_queue_behind(j)); + assert!(p.needs_engine_drain(j)); + } + // SCS compute does not start beside non-SCS compute on either pipe. + for pipe in [0u8,1] { + p.engine.flights=vec![flight(alu.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + } + // A render flight of its own VM does not hold it; once SCS compute is gone, the rest + // overlaps as before. + let mut render=flight(mk(6,vm1.clone(),q1.clone(),false),false,0); + render.computes=0; + render.renders=1; + p.engine.flights=vec![render]; + assert!(!p.needs_engine_drain(&rq)); + assert!(p.can_queue_behind(&rq)); + p.engine.flights=vec![flight(rq_post.clone(),false,0)]; + assert!(p.can_queue_behind(&alu)); + assert!(!p.needs_engine_drain(&alu)); + } #[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=Queue::new(0,0); @@ -850,7 +906,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,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})], + commands:vec![Command::Compute(ComputeCommand{query_access,rt:false})], order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -893,7 +949,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ 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})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -938,7 +994,7 @@ def item(declaration): let q2=Queue::new(0,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:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -980,7 +1036,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1012,7 +1068,7 @@ def item(declaration): let multi_c=Arc::new(QueueBehindJob{ id:6,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false});3], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false});3], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![ Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, @@ -1052,7 +1108,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1094,7 +1150,7 @@ def item(declaration): let c_job=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q_comp.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1131,7 +1187,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1289,7 +1345,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ 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})}], + commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); @@ -1633,7 +1689,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ id,vm,queue, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1681,7 +1737,7 @@ def item(declaration): let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1741,7 +1797,7 @@ def item(declaration): let c1=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1755,7 +1811,7 @@ def item(declaration): let c2_wait_q1=Arc::new(QueueBehindJob{ id:3,vm:vm1.clone(),queue:q2.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:false})], + commands:vec![Command::Compute(ComputeCommand{query_access:false,rt:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[Some(1),Some(1)]}], @@ -1763,7 +1819,7 @@ def item(declaration): let c2_query_wait_q1=Arc::new(QueueBehindJob{ id:4,vm:vm1.clone(),queue:q2.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Compute(ComputeCommand{query_access:true})], + commands:vec![Command::Compute(ComputeCommand{query_access:true,rt:false})], order:Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources, fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[None,Some(1)]}], @@ -2514,12 +2570,13 @@ def item(declaration): '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', + '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', '__WAIT_TARGET__': 'struct WaitTarget {', '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::fence::", "crate::fence::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::vm::VmState", "crate::Vm").replace("super::fence::", "crate::fence::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' From be351654938d17c85c569eeaa65e125f4e6bd425 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 18:24:01 +1100 Subject: [PATCH 0896/1514] drm/apple: serialize HDMI resume unplug with route assignment The resume path checks the fixed HDMI connector before releasing the link, then acquires the fabric mutex to update connector presence. A competing Type-C route selection can claim the DPTX port in that gap. Hold the fabric mutex across the ownership check, port release and presence update. Keep the established fabric-to-HPD lock order. The extracted fixture verifies that resume holds the fabric guard while releasing the link. Both arm64 DCP objects build and all six fixture mutations are rejected. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-fabric.c | 29 ++++++++++++- drivers/gpu/drm/apple/dcp.c | 13 +----- drivers/gpu/drm/apple/dcp.h | 2 + tools/asahi/dcp-hdmi-sleep-unplug-tests.py | 50 ++++++++++++++++------ tools/asahi/run-host-tests.py | 2 +- 5 files changed, 68 insertions(+), 28 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index b81598df13062e..eda8620c020ebc 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -1213,12 +1213,12 @@ static void dcp_hdmi_capacity_available(void *ctx) * never tracked: when the hold expires, the desktop has let the HDMI CRTC go * and the hybrid is free for a Type-C display again. */ -void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) +static void dcp_fabric_hdmi_unplugged_locked(struct apple_dcp *dcp) { unsigned long flags; u64 generation; - guard(mutex)(&dcp_typec_fabric_lock); + lockdep_assert_held(&dcp_typec_fabric_lock); generation = dcp_hdmi_edge(dcp); if (!generation) return; @@ -1230,6 +1230,31 @@ void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) dcp_fabric_hybrid_kick(dcp, 0); } +void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp_typec_fabric_lock); + dcp_fabric_hdmi_unplugged_locked(dcp); +} + +/* + * Release a fixed HDMI link unplugged while its HPD IRQ was masked. Hold + * the fabric lock from the ownership check through the presence update so + * a Type-C route cannot take the same DPTX port during the release. + */ +void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp_typec_fabric_lock); + + if (dcp->active_typec_route || !dcp->connector || + !READ_ONCE(dcp->connector->connected) || + gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0) + return; + + dev_info(dcp->dev, "HDMI display unplugged during sleep\n"); + dcp_hdmi_disconnect(dcp); + dcp_fabric_hdmi_unplugged_locked(dcp); +} + static void dcp_hdmi_settle_work(struct work_struct *work) { struct apple_dcp *dcp = container_of(to_delayed_work(work), diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 7fdb7b58a96f5f..f0b4d13341a78c 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -10258,21 +10258,10 @@ static int dcp_platform_suspend(struct device *dev) return 0; } -/* - * The suspend kept an attached HDMI display's link (dcp_platform_suspend()). - * One unplugged during the sleep made no edge the masked HPD IRQ saw, and - * nothing else reports it: release it now, as an unplug while awake is. - */ -static void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp) +void dcp_hdmi_disconnect(struct apple_dcp *dcp) { - if (READ_ONCE(dcp->active_typec_route) || !dcp->connector || - !READ_ONCE(dcp->connector->connected) || - gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0) - return; - dev_info(dcp->dev, "HDMI display unplugged during sleep\n"); disconnected_hpd_event(dcp->connector); dcp_dptx_disconnect(dcp, 0); - dcp_fabric_hdmi_unplugged(dcp); } static int dcp_platform_resume(struct device *dev) diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 41243ff65d8b0e..19cbea3122184c 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -184,6 +184,8 @@ bool apple_t8122_25g83_board(void); void dcp_typec_hybrid_first_dt(void); void dcp_fabric_hdmi_unplugged(struct apple_dcp *dcp); +void dcp_hdmi_unplugged_in_sleep(struct apple_dcp *dcp); +void dcp_hdmi_disconnect(struct apple_dcp *dcp); void dcp_fabric_hybrid_kick(struct apple_dcp *dcp, unsigned int delay_ms); void dcp_hdmi_yield_link(struct apple_dcp *dcp); void dcp_link_recovery_schedule(struct apple_dcp *dcp); diff --git a/tools/asahi/dcp-hdmi-sleep-unplug-tests.py b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py index df588dcdc16e21..b1ef7a00daa235 100755 --- a/tools/asahi/dcp-hdmi-sleep-unplug-tests.py +++ b/tools/asahi/dcp-hdmi-sleep-unplug-tests.py @@ -9,10 +9,10 @@ the IRQ comes back. A T6030 native output still releases the link at suspend, because its resume sets the PHY and crossbar up again. -The fixture compiles the HDMI block of dcp_platform_suspend() and -dcp_hdmi_unplugged_in_sleep() from drivers/gpu/drm/apple/dcp.c against mocks -and checks which displays are released. --mutation names a change to the -production code that the matrix must kill. +The fixture compiles the HDMI block of dcp_platform_suspend() and the +fabric's dcp_hdmi_unplugged_in_sleep() against mocks. It checks which +outputs are released and that the fabric lock covers the resume release. +--mutation names a change to the production code that the matrix must kill. """ import argparse import re @@ -23,6 +23,7 @@ ROOT = Path(__file__).resolve().parents[2] DCP = 'drivers/gpu/drm/apple/dcp.c' +FABRIC = 'drivers/gpu/drm/apple/dcp-fabric.c' RESUME_CALL = '\tif (dcp->hdmi_hpd_irq)\n\t\tdcp_hdmi_unplugged_in_sleep(dcp);\n' MUTATIONS = { @@ -33,11 +34,11 @@ 'gpio-error': ('gpiod_get_value_cansleep(dcp->hdmi_hpd) != 0)\n\t\treturn;', 'gpiod_get_value_cansleep(dcp->hdmi_hpd) > 0)\n\t\treturn;'), # Release the HDMI connector while a Type-C display owns the pipeline. - 'ignore-borrowed': ('if (READ_ONCE(dcp->active_typec_route) || !dcp->connector ||', + 'ignore-borrowed': ('if (dcp->active_typec_route || !dcp->connector ||', 'if (!dcp->connector ||'), # Leave the hybrid fabric thinking HDMI is still there. - 'no-fabric': ('\tdcp_dptx_disconnect(dcp, 0);\n\tdcp_fabric_hdmi_unplugged(dcp);\n}', - '\tdcp_dptx_disconnect(dcp, 0);\n}'), + 'no-fabric': ('\tdcp_fabric_hdmi_unplugged_locked(dcp);\n', ''), + 'no-fabric-lock': ('\tguard(mutex)(&dcp_typec_fabric_lock);\n', ''), # Never look for an unplug after the sleep. 'no-resume-check': (RESUME_CALL, ''), } @@ -53,7 +54,7 @@ def block(text, start): raise AssertionError('unbalanced production block') def function(text, name): - match = re.search(r'\n(static [^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) + match = re.search(r'\n((?:static )?[^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) assert match, name return block(text, match.start(1)) @@ -79,7 +80,26 @@ def function(text, name): static void disable_irq(int irq) { irq_off++; } static void disconnected_hpd_event(struct apple_connector *c) { c->connected = false; hpd_events++; } static int dcp_dptx_disconnect(struct apple_dcp *d, int port) { disconnects++; return 0; } -static void dcp_fabric_hdmi_unplugged(struct apple_dcp *d) { fabric_unplugs++; } +static int dcp_typec_fabric_lock; +static int *hold_lock(int *lock) +{ + assert(!*lock); + *lock = 1; + return lock; +} +static void release_lock(int **lock) { **lock = 0; } +#define guard(kind) int *held_##kind __attribute__((cleanup(release_lock))) = hold_lock +static void dcp_hdmi_disconnect(struct apple_dcp *dcp) +{ + assert(dcp_typec_fabric_lock); + disconnected_hpd_event(dcp->connector); + dcp_dptx_disconnect(dcp, 0); +} +static void dcp_fabric_hdmi_unplugged_locked(struct apple_dcp *d) +{ + assert(dcp_typec_fabric_lock); + fabric_unplugs++; +} static void reset(void) { hpd_events = disconnects = fabric_unplugs = irq_off = 0; } ''' @@ -158,10 +178,15 @@ def main(): args = parser.parse_args() source = (ROOT / DCP).read_text() + unplug = function((ROOT / FABRIC).read_text(), 'dcp_hdmi_unplugged_in_sleep') if args.mutation: old, new = MUTATIONS[args.mutation] - assert source.count(old) == 1, args.mutation - source = source.replace(old, new) + if old in unplug: + assert unplug.count(old) == 1, args.mutation + unplug = unplug.replace(old, new) + else: + assert source.count(old) == 1, args.mutation + source = source.replace(old, new) resume = function(source, 'dcp_platform_resume') # The release runs while the HPD IRQ is still masked: an edge from then @@ -173,8 +198,7 @@ def main(): suspend = function(source, 'dcp_platform_suspend') hdmi = block(suspend, suspend.index('\tif (dcp->hdmi_hpd_irq) {\n\t\tdisable_irq')) - code = HARNESS + function(source, 'dcp_hdmi_unplugged_in_sleep') + \ - CHECKS.replace('SUSPEND', hdmi) + code = HARNESS + unplug + CHECKS.replace('SUSPEND', hdmi) with tempfile.TemporaryDirectory() as directory: path = Path(directory) / 'check.c' diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 9605e7101c81f7..874ddbc5e1d1a7 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -193,7 +193,7 @@ def mutations(flag, names, base, expect=KILL): # An HDMI display kept through a sleep but unplugged during it is released on resume. 'dcp-hdmi-sleep-unplug-tests.py': [([], PASS)] + mutations('--mutation', ('keep-native', 'gpio-error', 'ignore-borrowed', 'no-fabric', - 'no-resume-check'), []), + 'no-fabric-lock', 'no-resume-check'), []), # A fixed (non-Type-C) output takes its DP AV service again after a sleep. 'dpavserv-admission-tests.py': [([], PASS)] + mutations('--mutation', ('old-cable-wait', 'ignore-generation', 'ignore-cable', From cf3d0b9b973e7e6c76b0dcd34ac4a61733a13711 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 18:32:25 +1100 Subject: [PATCH 0897/1514] drm/apple: audio: open as unplugged while the sink info is unreadable PipeWire and PulseAudio probe a PCM once when its card appears and drop the output for good if the open fails, which is why an unplugged sink already opens with a fixed hardware description. A plugged sink's open reads its elements and product attributes from the DCP audio service. On the Mac mini M2 (27.2 firmware) the HDMI DCP's firmware announces that service again while the display link is set up again at boot, and stops and restarts it meanwhile; a read in that window fails. The open failed with it, PipeWire's first probe of that card fell in the window, and the HDMI output never got its HiFi profile, although the ELD and jack came up a few seconds later. A restart of PipeWire after that showed the profile and an available HDMI port on both cards. Open as for an unplugged sink when the sink info cannot be read. The stream then runs as an unplugged one does, until the next open. tools/asahi/dcpaud-open-fallback-tests.py runs the real dcp_pcm_open() over plugged, unplugged, restarting and refused sinks and a DMA failure, and kills two mutations. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 18 ++- tools/asahi/dcpaud-open-fallback-tests.py | 170 ++++++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 3 files changed, 188 insertions(+), 2 deletions(-) create mode 100755 tools/asahi/dcpaud-open-fallback-tests.py diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 565016dcd7a893..ed061e94a0a4b3 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -429,8 +429,22 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) } ret = dcpaud_read_remote_info(dcpaud); - if (ret < 0) - return ret; + if (ret < 0) { + /* + * The service is between a stop and its next start: the firmware + * announces it again while the display link is set up again (a + * modeset), and it refuses the element read meanwhile. Open as for + * an unplugged sink rather than fail, which would drop the output + * for good (see dcp_pcm_hw_unplugged). + */ + dev_dbg(dcpaud->dev, "sink info not readable (%d), opening as unplugged\n", + ret); + mutex_lock(&dcpaud->data_lock); + dcpaud->open_unplugged = true; + mutex_unlock(&dcpaud->data_lock); + hw = dcp_pcm_hw_unplugged; + goto refine; + } snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT, dcpaud_rule_format, dcpaud, diff --git a/tools/asahi/dcpaud-open-fallback-tests.py b/tools/asahi/dcpaud-open-fallback-tests.py new file mode 100755 index 00000000000000..fde9be97e127ea --- /dev/null +++ b/tools/asahi/dcpaud-open-fallback-tests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the real dcp_pcm_open() over plugged, unplugged and unreadable sinks. + +PipeWire and PulseAudio probe a PCM once when its card appears and drop the +output for good if the open fails. dcp_pcm_open() opens an unplugged sink +with a fixed hardware description for that reason. A sink whose DCP audio +service is between a stop and its next start (the firmware announces it again +while the display link is set up again) cannot have its elements read; the +open then takes the same unplugged path instead of failing. + +The fixture compiles dcp_pcm_open() from drivers/gpu/drm/apple/audio.c against +mocks of the ALSA and DMA calls. --mutation names a change to the production +function that the matrix must kill. +""" +import argparse +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +AUDIO = 'drivers/gpu/drm/apple/audio.c' + +MUTATIONS = { + # Fail the open when the sink info cannot be read (the old behaviour). + 'fail-open': ('\tif (ret < 0) {\n\t\t/*\n\t\t * The service is between', + '\tif (ret < 0) {\n\t\treturn ret;\n\t\t/*\n\t\t * The service is between'), + # Open with the unplugged description but treat the stream as plugged. + 'no-flag': ('\t\tdcpaud->open_unplugged = true;\n', ''), +} + +def block(text, start): + opening = text.index('{', start) + depth = 0 + for end in range(opening, len(text)): + depth += text[end] == '{' + depth -= text[end] == '}' + if not depth: + return text[start:end + 1] + raise AssertionError('unbalanced production block') + +def function(text, name): + match = re.search(r'\n(static [^\n;]*\b' + name + r'\([^;{}]*\)\n)\{', text) + assert match, name + return block(text, match.start(1)) + +HARNESS = r''' +#include +#include +#include +#include +#include +#define dev_dbg(...) ((void)0) +#define SNDRV_PCM_INFO_MMAP 1u +#define SNDRV_PCM_INFO_MMAP_VALID 2u +#define SNDRV_PCM_INFO_INTERLEAVED 4u +#define SNDRV_PCM_INFO_RESUME 8u +#define SNDRV_PCM_HW_PARAM_FORMAT 0 +#define SNDRV_PCM_HW_PARAM_CHANNELS 1 +#define SNDRV_PCM_HW_PARAM_RATE 2 +#define SND_DMAENGINE_PCM_DAI_FLAG_PACK 1 +#define DCPAUD_PERIODS_MAX 64 +#define UNPLUGGED_FORMATS 0x700u +#define PLUGGED_FORMATS 0x7u +struct device { int unused; }; +struct mutex { int held; }; +static void mutex_lock(struct mutex *m) { m->held++; } +static void mutex_unlock(struct mutex *m) { m->held--; } +struct snd_pcm_hardware { unsigned int info; unsigned long long formats; unsigned int channels_min, channels_max; + unsigned int periods_min, periods_max; size_t period_bytes_min, period_bytes_max, buffer_bytes_max, fifo_size; }; +struct snd_pcm_runtime { struct snd_pcm_hardware hw; }; +struct snd_pcm { void *private_data; }; +struct snd_pcm_substream { struct snd_pcm *pcm; struct snd_pcm_runtime *runtime; }; +struct snd_dmaengine_dai_dma_data { unsigned int flags; }; +struct dma_chan { int unused; }; +struct dcp_audio { struct device *dev; struct mutex data_lock; bool connected, open_unplugged; + unsigned long open_cookie, connection_cookie; struct dma_chan *chan; }; +static const struct snd_pcm_hardware dcp_pcm_hw = { .formats = PLUGGED_FORMATS }; +static const struct snd_pcm_hardware dcp_pcm_hw_unplugged = { .formats = UNPLUGGED_FORMATS }; +static int init_error, info_error, rules, dma_opens; +static int dcpaud_init_dma(struct dcp_audio *d) { return init_error; } +static int dcpaud_read_remote_info(struct dcp_audio *d) { return info_error; } +static int dcpaud_rule_format(void *p, void *r) { return 0; } +static int dcpaud_rule_channels(void *p, void *r) { return 0; } +static int dcpaud_rule_rate(void *p, void *r) { return 0; } +static int snd_pcm_hw_rule_add(struct snd_pcm_runtime *r, unsigned int c, int v, void *f, void *p, ...) +{ rules++; return 0; } +static int snd_dmaengine_pcm_refine_runtime_hwparams(struct snd_pcm_substream *s, + struct snd_dmaengine_dai_dma_data *d, struct snd_pcm_hardware *h, struct dma_chan *c) { return 0; } +static int snd_dmaengine_pcm_open(struct snd_pcm_substream *s, struct dma_chan *c) { dma_opens++; return 0; } +''' + +CHECKS = r''' +static int failures; +#define CHECK(c) do { if (!(c)) { printf("FAIL line %d (%s: %s)\n", __LINE__, name, #c); failures++; } } while (0) + +static int run(const char *name, bool connected, int ierr, int info, struct dcp_audio *d, + struct snd_pcm_runtime *rt) +{ + static struct snd_pcm pcm; + struct snd_pcm_substream s = { .pcm = &pcm, .runtime = rt }; + + (void)name; + *d = (struct dcp_audio){ .connected = connected, .connection_cookie = 7 }; + *rt = (struct snd_pcm_runtime){ 0 }; + pcm.private_data = d; + init_error = ierr; info_error = info; rules = dma_opens = 0; + return dcp_pcm_open(&s); +} + +int main(void) +{ + struct dcp_audio d; + struct snd_pcm_runtime rt; + const char *name; + + name = "plugged"; + CHECK(run(name, true, 0, 0, &d, &rt) == 0); + CHECK(!d.open_unplugged && rules == 3 && dma_opens == 1); + CHECK(rt.hw.formats == PLUGGED_FORMATS && d.open_cookie == 7 && !d.data_lock.held); + + name = "unplugged"; + CHECK(run(name, false, 0, 0, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && dma_opens == 1 && rt.hw.formats == UNPLUGGED_FORMATS); + + name = "service-restarting"; + CHECK(run(name, true, 0, -ENODEV, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && dma_opens == 1); + CHECK(rt.hw.formats == UNPLUGGED_FORMATS && !d.data_lock.held); + + name = "firmware-refused"; + CHECK(run(name, true, 0, -EIO, &d, &rt) == 0); + CHECK(d.open_unplugged && dma_opens == 1); + + name = "no-dma"; + CHECK(run(name, true, -EPROBE_DEFER_, 0, &d, &rt) == -EPROBE_DEFER_); + CHECK(!dma_opens && !d.data_lock.held); + + if (failures) + return 1; + puts("PASS dcp_pcm_open: plugged, unplugged, service restarting and refused element read " + "open (the last two as unplugged), DMA failure still fails"); + return 0; +} +''' + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + + source = (ROOT / AUDIO).read_text() + if args.mutation: + old, new = MUTATIONS[args.mutation] + assert source.count(old) == 1, args.mutation + source = source.replace(old, new) + + code = HARNESS + '#define EPROBE_DEFER_ 517\n' + function(source, 'dcp_pcm_open') + CHECKS + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'check.c' + path.write_text(code) + subprocess.run(['clang', '-std=gnu11', '-Wall', '-Werror', '-Wno-unused-function', + '-Wno-unreachable-code', '-fsanitize=address,undefined', str(path), + '-o', str(path.with_suffix(''))], check=True) + sys.exit(subprocess.run([str(path.with_suffix(''))]).returncode) + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 26b49869112881..28f0143c5b6de0 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -178,6 +178,8 @@ def mutations(flag, names, base, expect=KILL): 'missing-control-firmware', 'missing-control-descriptor', 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), + # A DP audio PCM whose sink info cannot be read yet opens as unplugged. + 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('fail-open', 'no-flag'), []), 'dcp-bw-scratch-window-tests.py': [([], PASS)] + mutations('--mutation', ('old-check', 'start-only'), []), 'clpc-gpu-demand-tests.py': [([], PASS)], 'clpc-high-power-cleanup-tests.py': [(out(), PASS), From 415de702f44c851ed07ac789c535eccb93e16829 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 18:33:03 +1100 Subject: [PATCH 0898/1514] arm64: configs: asahi: enable the G14 firmware-27.2 GPU backend DRM_ASAHI_G14_V27_2 landed with the G14 27.2 series (#2610) but the shared distro fragment never requested it, so hardware-defaults-tests fails and distro kernels would silently drop M2 GPU support on 27.2 firmware. Request it next to DRM_ASAHI_G15, which it depends on. Signed-off-by: Ryan Murray --- arch/arm64/configs/asahi.config | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/configs/asahi.config b/arch/arm64/configs/asahi.config index f4e60efde4d426..77e982357db78e 100644 --- a/arch/arm64/configs/asahi.config +++ b/arch/arm64/configs/asahi.config @@ -81,6 +81,7 @@ CONFIG_VIDEO_APPLE_SCALER=m CONFIG_DRM=y CONFIG_DRM_ASAHI=m CONFIG_DRM_ASAHI_G15=y +CONFIG_DRM_ASAHI_G14_V27_2=y CONFIG_DRM_ASAHI_G16=y CONFIG_DRM_ASAHI_G18=y CONFIG_DRM_ASAHI_M5=y From 82a27e5e91eb2eb794f244366b6a1ebd42c9b21c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 19:01:22 +1100 Subject: [PATCH 0899/1514] drm/apple: audio: read a replaced service's successor at PCM open The previous change opened a PCM as unplugged on any failure to read the sink info. That masked persistent errors as a silent stream, and it left the open's cookie live, so dcp_pcm_hw_free() and the native start took the sink as connected for a stream that never prepared a link. What fails at boot on the Mac mini M2 is a call to an audio service instance the firmware is replacing: it refuses it as offline and publishes the successor within a second, as dcp_audiosrv_open() already handles for the open itself. Do the same for the sink info: when the read fails and a successor is published within AV_AUDIOSRV_REPLACE_MS, take the sink as the successor reports it and read again from it. Only a service that is gone (-ENODEV) still opens as unplugged, and with a cookie no connection has, so no stream op of that open takes the sink as connected. Any other failure fails the open as before. The host test runs the real dcp_pcm_open() and dcpaud_connection_up() over nine cases and kills four mutations. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 44 +++++++-- drivers/gpu/drm/apple/audio.h | 3 + drivers/gpu/drm/apple/av.c | 31 ++++++ tools/asahi/dcpaud-open-fallback-tests.py | 115 +++++++++++++++------- tools/asahi/run-host-tests.py | 4 +- 5 files changed, 153 insertions(+), 44 deletions(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index f6ac38fe628b91..7e351ada8d3cbd 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -410,6 +410,9 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) .flags = SND_DMAENGINE_PCM_DAI_FLAG_PACK, }; struct snd_pcm_hardware hw; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + u64 gen; +#endif int ret; mutex_lock(&dcpaud->data_lock); @@ -428,23 +431,48 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) goto refine; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + gen = dcp_audiosrv_instance(dcpaud->dcp_dev); +#endif ret = dcpaud_read_remote_info(dcpaud); - if (ret < 0) { +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* + * The firmware announces the audio service again while the display + * link is set up again (a modeset, at boot), and refuses calls to the + * instance it is replacing meanwhile. Userspace probes the PCM once + * and drops an output whose open fails, so read from the successor. + * The sink is taken as the successor reports it. + */ + if (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) { + dev_dbg(dcpaud->dev, "sink info read failed on a replaced instance (%d), retrying\n", + ret); + mutex_lock(&dcpaud->data_lock); + dcpaud->open_unplugged = !dcpaud->connected; + dcpaud->open_cookie = dcpaud->connection_cookie; + mutex_unlock(&dcpaud->data_lock); + if (dcpaud->open_unplugged) { + hw = dcp_pcm_hw_unplugged; + goto refine; + } + ret = dcpaud_read_remote_info(dcpaud); + } +#endif + if (ret == -ENODEV) { /* - * The service is between a stop and its next start: the firmware - * announces it again while the display link is set up again (a - * modeset), and it refuses the element read meanwhile. Open as for - * an unplugged sink rather than fail, which would drop the output - * for good (see dcp_pcm_hw_unplugged). + * No instance answers: the service went and its unplug is on the + * way. Open as unplugged, as before the plug, and with a cookie + * no connection has, so that no stream op of this open takes the + * sink as connected. */ - dev_dbg(dcpaud->dev, "sink info not readable (%d), opening as unplugged\n", - ret); mutex_lock(&dcpaud->data_lock); dcpaud->open_unplugged = true; + dcpaud->open_cookie = dcpaud->connection_cookie - 1; mutex_unlock(&dcpaud->data_lock); hw = dcp_pcm_hw_unplugged; goto refine; } + if (ret < 0) + return ret; snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT, dcpaud_rule_format, dcpaud, diff --git a/drivers/gpu/drm/apple/audio.h b/drivers/gpu/drm/apple/audio.h index 0ba2ba225af5e5..baf83a50eea61a 100644 --- a/drivers/gpu/drm/apple/audio.h +++ b/drivers/gpu/drm/apple/audio.h @@ -47,6 +47,9 @@ struct dcp_audio_link_format { bool dcp_audiosrv_link_by_format(struct device *dev); bool dcp_audiosrv_native_link(struct device *dev); +/* The published audio service instance; whether it was replaced since @gen */ +u64 dcp_audiosrv_instance(struct device *dev); +bool dcp_audiosrv_replaced(struct device *dev, u64 gen); int dcp_audiosrv_open(struct device *dev); void dcp_audiosrv_close(struct device *dev); int dcp_audiosrv_link(struct device *dev, enum dcp_audio_link op, diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index efca053134e1ac..32221c1696f892 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -342,6 +342,37 @@ static int av_audiosrv_call(struct apple_epic_service *srv, u32 command, const v /* How long an Open refused by an instance being replaced waits for the next one */ #define AV_AUDIOSRV_REPLACE_MS 1000 +/* The audio service instance now published, as dcp_audiosrv_replaced() takes it. */ +u64 dcp_audiosrv_instance(struct device *dev) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct audiosrv_data *asrv = dcp->audiosrv; + + if (!asrv) + return 0; + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->gen; +} + +/* + * Whether instance @gen has a published successor, waiting for one as + * dcp_audiosrv_open() does: the firmware refuses calls to an instance it is + * replacing, and publishes the successor within some hundred milliseconds. + */ +bool dcp_audiosrv_replaced(struct device *dev, u64 gen) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct audiosrv_data *asrv = dcp->audiosrv; + + if (!asrv) + return false; + wait_event_timeout(asrv->gen_wq, + READ_ONCE(asrv->srv) && READ_ONCE(asrv->gen) != gen, + msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)); + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->srv && asrv->gen != gen; +} + /* * The 14.7 external role: the service is open while a PCM is (see * av_service_connect()). The instance the PCM opened is kept under open_lock, diff --git a/tools/asahi/dcpaud-open-fallback-tests.py b/tools/asahi/dcpaud-open-fallback-tests.py index fde9be97e127ea..284a83c354653a 100755 --- a/tools/asahi/dcpaud-open-fallback-tests.py +++ b/tools/asahi/dcpaud-open-fallback-tests.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only -"""Run the real dcp_pcm_open() over plugged, unplugged and unreadable sinks. +"""Run the real dcp_pcm_open() over plugged, unplugged, replaced and gone sinks. PipeWire and PulseAudio probe a PCM once when its card appears and drop the output for good if the open fails. dcp_pcm_open() opens an unplugged sink -with a fixed hardware description for that reason. A sink whose DCP audio -service is between a stop and its next start (the firmware announces it again -while the display link is set up again) cannot have its elements read; the -open then takes the same unplugged path instead of failing. +with a fixed hardware description for that reason. The firmware refuses +calls to an audio service instance it is replacing (it announces the service +again while the display link is set up again): the open then reads from the +successor. A service that is gone opens as unplugged with a cookie no +connection has, so no later stream op (hw_free, native start) takes the sink as +connected. Any other failure still fails the open. The fixture compiles dcp_pcm_open() from drivers/gpu/drm/apple/audio.c against mocks of the ALSA and DMA calls. --mutation names a change to the production @@ -24,11 +26,17 @@ AUDIO = 'drivers/gpu/drm/apple/audio.c' MUTATIONS = { - # Fail the open when the sink info cannot be read (the old behaviour). - 'fail-open': ('\tif (ret < 0) {\n\t\t/*\n\t\t * The service is between', - '\tif (ret < 0) {\n\t\treturn ret;\n\t\t/*\n\t\t * The service is between'), - # Open with the unplugged description but treat the stream as plugged. - 'no-flag': ('\t\tdcpaud->open_unplugged = true;\n', ''), + # Fail the open when the instance is being replaced. + 'no-retry': ('\tif (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', + '\tif (0 && gen) {'), + # Fail the open when the service is gone. + 'gone-fails': ('\tif (ret == -ENODEV) {\n\t\t/*\n\t\t * No instance answers', + '\tif (0) {\n\t\t/*\n\t\t * No instance answers'), + # Keep the live cookie on a gone service: later ops take it as connected. + 'keep-cookie': ('\t\tdcpaud->open_cookie = dcpaud->connection_cookie - 1;\n', ''), + # Turn every failure into an unplugged open. + 'mask-all': ('\tif (ret == -ENODEV) {\n\t\t/*\n\t\t * No instance answers', + '\tif (ret < 0) {\n\t\t/*\n\t\t * No instance answers'), } def block(text, start): @@ -53,6 +61,8 @@ def function(text, name): #include #include #define dev_dbg(...) ((void)0) +#define IS_ENABLED(x) 1 +typedef unsigned long long u64; #define SNDRV_PCM_INFO_MMAP 1u #define SNDRV_PCM_INFO_MMAP_VALID 2u #define SNDRV_PCM_INFO_INTERLEAVED 4u @@ -75,13 +85,27 @@ def function(text, name): struct snd_pcm_substream { struct snd_pcm *pcm; struct snd_pcm_runtime *runtime; }; struct snd_dmaengine_dai_dma_data { unsigned int flags; }; struct dma_chan { int unused; }; -struct dcp_audio { struct device *dev; struct mutex data_lock; bool connected, open_unplugged; - unsigned long open_cookie, connection_cookie; struct dma_chan *chan; }; +struct dcp_audio { struct device *dev, *dcp_dev; struct mutex data_lock; bool connected, open_unplugged; + unsigned int open_cookie, connection_cookie; struct dma_chan *chan; }; static const struct snd_pcm_hardware dcp_pcm_hw = { .formats = PLUGGED_FORMATS }; static const struct snd_pcm_hardware dcp_pcm_hw_unplugged = { .formats = UNPLUGGED_FORMATS }; -static int init_error, info_error, rules, dma_opens; +static int init_error, info_errors[2], reads, rules, dma_opens; +static bool replaced, successor_connected; +static struct dcp_audio *cur; static int dcpaud_init_dma(struct dcp_audio *d) { return init_error; } -static int dcpaud_read_remote_info(struct dcp_audio *d) { return info_error; } +static int dcpaud_read_remote_info(struct dcp_audio *d) { return info_errors[reads++ ? 1 : 0]; } +static u64 dcp_audiosrv_instance(struct device *d) { return 4; } +static bool dcp_audiosrv_replaced(struct device *d, u64 gen) +{ + if (gen != 4) + return false; + if (replaced) { + /* the teardown reported the unplug, the successor its sink (or not yet) */ + cur->connected = successor_connected; + cur->connection_cookie += successor_connected ? 1 : 0; + } + return replaced; +} static int dcpaud_rule_format(void *p, void *r) { return 0; } static int dcpaud_rule_channels(void *p, void *r) { return 0; } static int dcpaud_rule_rate(void *p, void *r) { return 0; } @@ -96,17 +120,19 @@ def function(text, name): static int failures; #define CHECK(c) do { if (!(c)) { printf("FAIL line %d (%s: %s)\n", __LINE__, name, #c); failures++; } } while (0) -static int run(const char *name, bool connected, int ierr, int info, struct dcp_audio *d, - struct snd_pcm_runtime *rt) +static int run(bool connected, int ierr, int e0, int e1, bool repl, bool succ, + struct dcp_audio *d, struct snd_pcm_runtime *rt) { static struct snd_pcm pcm; struct snd_pcm_substream s = { .pcm = &pcm, .runtime = rt }; - (void)name; *d = (struct dcp_audio){ .connected = connected, .connection_cookie = 7 }; *rt = (struct snd_pcm_runtime){ 0 }; pcm.private_data = d; - init_error = ierr; info_error = info; rules = dma_opens = 0; + cur = d; + init_error = ierr; info_errors[0] = e0; info_errors[1] = e1; + replaced = repl; successor_connected = succ; + reads = rules = dma_opens = 0; return dcp_pcm_open(&s); } @@ -117,31 +143,51 @@ def function(text, name): const char *name; name = "plugged"; - CHECK(run(name, true, 0, 0, &d, &rt) == 0); - CHECK(!d.open_unplugged && rules == 3 && dma_opens == 1); - CHECK(rt.hw.formats == PLUGGED_FORMATS && d.open_cookie == 7 && !d.data_lock.held); + CHECK(run(true, 0, 0, 0, false, false, &d, &rt) == 0); + CHECK(!d.open_unplugged && rules == 3 && dma_opens == 1 && reads == 1); + CHECK(rt.hw.formats == PLUGGED_FORMATS && dcpaud_connection_up(&d) && !d.data_lock.held); name = "unplugged"; - CHECK(run(name, false, 0, 0, &d, &rt) == 0); - CHECK(d.open_unplugged && !rules && dma_opens == 1 && rt.hw.formats == UNPLUGGED_FORMATS); + CHECK(run(false, 0, 0, 0, false, false, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && !reads && rt.hw.formats == UNPLUGGED_FORMATS); + CHECK(!dcpaud_connection_up(&d)); + + name = "replaced, successor plugged"; + CHECK(run(true, 0, -EINVAL, 0, true, true, &d, &rt) == 0); + CHECK(!d.open_unplugged && reads == 2 && rules == 3 && dma_opens == 1); + CHECK(rt.hw.formats == PLUGGED_FORMATS && dcpaud_connection_up(&d) && d.open_cookie == 8); - name = "service-restarting"; - CHECK(run(name, true, 0, -ENODEV, &d, &rt) == 0); - CHECK(d.open_unplugged && !rules && dma_opens == 1); - CHECK(rt.hw.formats == UNPLUGGED_FORMATS && !d.data_lock.held); + name = "replaced, successor not yet plugged"; + CHECK(run(true, 0, -EINVAL, 0, true, false, &d, &rt) == 0); + CHECK(d.open_unplugged && reads == 1 && !rules && !dcpaud_connection_up(&d)); - name = "firmware-refused"; - CHECK(run(name, true, 0, -EIO, &d, &rt) == 0); - CHECK(d.open_unplugged && dma_opens == 1); + name = "replaced, successor refuses too"; + CHECK(run(true, 0, -EINVAL, -EINVAL, true, true, &d, &rt) == -EINVAL); + CHECK(!dma_opens); + + name = "stable service refuses"; + CHECK(run(true, 0, -EINVAL, 0, false, false, &d, &rt) == -EINVAL); + CHECK(!dma_opens && reads == 1); + + name = "persistent error"; + CHECK(run(true, 0, -ENOMEM, 0, false, false, &d, &rt) == -ENOMEM); + CHECK(!dma_opens); + + name = "service gone"; + CHECK(run(true, 0, -ENODEV, 0, false, false, &d, &rt) == 0); + CHECK(d.open_unplugged && !rules && dma_opens == 1 && rt.hw.formats == UNPLUGGED_FORMATS); + /* hw_free and native start test only this: the sink is not this open's */ + CHECK(!dcpaud_connection_up(&d) && !d.data_lock.held); name = "no-dma"; - CHECK(run(name, true, -EPROBE_DEFER_, 0, &d, &rt) == -EPROBE_DEFER_); + CHECK(run(true, -EPROBE_DEFER_, 0, 0, false, false, &d, &rt) == -EPROBE_DEFER_); CHECK(!dma_opens && !d.data_lock.held); if (failures) return 1; - puts("PASS dcp_pcm_open: plugged, unplugged, service restarting and refused element read " - "open (the last two as unplugged), DMA failure still fails"); + puts("PASS dcp_pcm_open: plugged, unplugged, replaced instance (successor plugged, not yet, " + "refusing), stable refusal and persistent error fail, gone service opens unplugged " + "and never connected, DMA failure fails"); return 0; } ''' @@ -157,7 +203,8 @@ def main(): assert source.count(old) == 1, args.mutation source = source.replace(old, new) - code = HARNESS + '#define EPROBE_DEFER_ 517\n' + function(source, 'dcp_pcm_open') + CHECKS + code = (HARNESS + '#define EPROBE_DEFER_ 517\n' + function(source, 'dcpaud_connection_up') + + function(source, 'dcp_pcm_open') + CHECKS) with tempfile.TemporaryDirectory() as directory: path = Path(directory) / 'check.c' path.write_text(code) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index dceda03a4a5207..1086d92fe81012 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -181,8 +181,8 @@ def mutations(flag, names, base, expect=KILL): 'missing-control-firmware', 'missing-control-descriptor', 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), - # A DP audio PCM whose sink info cannot be read yet opens as unplugged. - 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('fail-open', 'no-flag'), []), + # A DP audio PCM open reads a replaced service's successor; a gone service opens unplugged. + 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('no-retry', 'gone-fails', 'keep-cookie', 'mask-all'), []), # a7638d51880c, the parent of the fix, ran pm_runtime_force_suspend in the late # slot, so the dp-audio domain dropped under a running DCP. 'dcpaud-sleep-hold-tests.py': [(out(), PASS)] From 39aa860161d316109cb87ffd35a28accd07a9a83 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 19:59:35 +1100 Subject: [PATCH 0900/1514] dmaengine: apple-sio: Send a low-window SIO the tables for its protocol The M2's SIO firmware reports protocol 9 on system firmware 13.5 and protocol 10 on 27.2, with the same ADT, and the two take different boot tables: protocol 10 takes T6030's six 36-byte DMA shim records and nine device types. Given the earlier five 32-byte records, the 27.2 firmware crashes at its first channel configuration ("Fifo allocation overflow 2048:0"), so DisplayPort/HDMI audio on the Mac mini M2 never started. Only the driver sees the protocol, in STARTED. The boot loader now passes the protocol-10 tables as a second list, apple,sio-firmware-params-v10; send that list when the firmware reports protocol 10, after checking it as T6030's tables are checked (each table once, at its exact size, inside a mapped window). Protocol 9 and nodes without the second list keep apple,sio-firmware-params. A protocol-10 firmware left with the earlier shim records (an older boot loader, or a second list that fails the check) would crash at the first channel configuration: keep its firmware running, so sleep still stops it, but refuse channel configuration with -ENODEV and say so. Signed-off-by: Ryan Murray --- drivers/dma/apple-sio-t6030-test.dtso | 33 ++++++++++++++++ drivers/dma/apple-sio-test.c | 50 +++++++++++++++++++++++- drivers/dma/apple-sio.c | 55 ++++++++++++++++++++++++--- 3 files changed, 131 insertions(+), 7 deletions(-) diff --git a/drivers/dma/apple-sio-t6030-test.dtso b/drivers/dma/apple-sio-t6030-test.dtso index df42f31a2a8d13..5f9cf0cfedbe27 100644 --- a/drivers/dma/apple-sio-t6030-test.dtso +++ b/drivers/dma/apple-sio-t6030-test.dtso @@ -41,6 +41,39 @@ 0x1c 0x5a 0x1d 0x40>; }; + /* + * A low-window SIO (M2) as a loader leaves it for either firmware: the earlier tables, + * and T6030's shim records and device types in a second list, for protocol 10. + */ + low_w: low-w { iommu-addresses = <&low 0x0 0x30000 0x0 0x2d000>; }; + + low: sio-low-window-test-both { + compatible = "apple,t8112-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&low_w>; + apple,sio-firmware-params = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + apple,sio-firmware-params-v10 = <0x1e 0x30 0x1f 0x300 0xb 0x31 0xc 0x1b80 + 0xf 0x34 0x10 0x1e000 0x30d 0x54 0x30e 0x4000 + 0x1a 0x58 0x1b 0x40 0x22 0x5b 0x23 0xd8 + 0x1c 0x5c 0x1d 0x48>; + }; + + /* The second list with the earlier shim records: not protocol 10's */ + lowbad_w: lowbad-w { iommu-addresses = <&lowbad 0x0 0x30000 0x0 0x2d000>; }; + + lowbad: sio-low-window-test-bad-v10 { + compatible = "apple,t8112-sio", "apple,sio"; + dma-channels = <8>; + memory-region = <&lowbad_w>; + apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xa0 + 0x1c 0x5a 0x1d 0x40>; + apple,sio-firmware-params-v10 = <0x1a 0x58 0x1b 0x40 0x22 0x5b 0x23 0xa0 + 0x1c 0x5c 0x1d 0x48>; + }; + sio-t6030-test-unmapped { apple,sio-firmware-params = <0x1a 0x58 0x1b 0x40 0x22 0x59 0x23 0xd8 0x1c 0x5a 0x1d 0x48>; diff --git a/drivers/dma/apple-sio-test.c b/drivers/dma/apple-sio-test.c index 1088b967686386..f093d01c341322 100644 --- a/drivers/dma/apple-sio-test.c +++ b/drivers/dma/apple-sio-test.c @@ -273,7 +273,7 @@ static void sio_t6030_device_tree_test(struct kunit *test) int ret; KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", nodes[i][0]); - ret = sio_t6030_check_node(np); + ret = sio_t6030_check_node(np, "apple,sio-firmware-params"); if (!strcmp(nodes[i][1], "admitted")) KUNIT_EXPECT_EQ_MSG(test, ret, 0, "%s", nodes[i][0]); else @@ -309,6 +309,53 @@ static void sio_t6030_probe_test(struct kunit *test) } } +/* + * A low-window SIO's parameter list follows the protocol its firmware reports: the earlier + * tables for protocol 9, the second list for protocol 10; a protocol-10 firmware without a valid + * second list gets no DMA (the earlier shim records crash it at the first channel configuration). + */ +static void sio_low_window_params_test(struct kunit *test) +{ + static const struct { + const char *path; + u32 protocol; + const char *prop; + bool mismatch; + } cases[] = { + { "/sio-t6030-test/sio-low-window-test-both", 9, "apple,sio-firmware-params", false }, + { "/sio-t6030-test/sio-low-window-test-both", 10, "apple,sio-firmware-params-v10", + false }, + { "/sio-t6030-test/sio-low-window-test-bad-v10", 10, "apple,sio-firmware-params", + true }, + { "/sio-t6030-test/sio-low-window-test-bad-v10", 9, "apple,sio-firmware-params", + false }, + /* An older loader: the earlier tables only */ + { "/sio-t6030-test/sio-t6030-test-earlier", 10, "apple,sio-firmware-params", true }, + { "/sio-t6030-test/sio-t6030-test-earlier", 9, "apple,sio-firmware-params", false }, + /* T6030: its protocol-10 tables are the first list */ + { "/sio-t6030-test/sio-t6030-test-v10", 10, "apple,sio-firmware-params", false }, + }; + struct device *dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_EQ(test, 0, of_overlay_apply_kunit(test, apple_sio_t6030_test)); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + struct device_node *np __free(device_node) = of_find_node_by_path(cases[i].path); + struct sio_data *sio = kunit_kzalloc(test, sizeof(*sio), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", cases[i].path); + KUNIT_ASSERT_NOT_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, sio); + dev->of_node = np; + sio->dev = dev; + sio->protocol = cases[i].protocol; + KUNIT_EXPECT_STREQ_MSG(test, sio_dt_params_name(sio), cases[i].prop, "%s v%u", + cases[i].path, cases[i].protocol); + KUNIT_EXPECT_EQ_MSG(test, sio->tables_mismatch, cases[i].mismatch, "%s v%u", + cases[i].path, cases[i].protocol); + } +} + static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_protocol10_test), KUNIT_CASE(sio_t6030_earlier_loader_test), @@ -318,6 +365,7 @@ static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_spans_test), KUNIT_CASE(sio_t6030_device_tree_test), KUNIT_CASE(sio_t6030_probe_test), + KUNIT_CASE(sio_low_window_params_test), {} }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index cb75beb54ae994..299abb98d8df50 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -189,6 +189,8 @@ struct sio_data { /* The firmware is stopped for a system sleep. */ bool asleep; bool firmware_only; + /* Protocol 10 firmware given the earlier boot tables: no DMA, which would crash it */ + bool tables_mismatch; bool commit_registered; bool commit_used; u32 protocol; @@ -370,16 +372,16 @@ static int sio_t6030_windows(struct device_node *np, struct sio_t6030_window *wi return err == -ENOENT ? n : err; } -/* 0 when the node's boot tables are protocol-10 tables inside its mapped windows */ -static int sio_t6030_check_node(struct device_node *np) +/* 0 when the node's boot tables in propname are protocol-10 tables inside its mapped windows */ +static int sio_t6030_check_node(struct device_node *np, const char *propname) { struct sio_t6030_window windows[SIO_T6030_WINDOWS_MAX]; u32 params[2 * SIO_T6030_PARAMS_MAX]; int nparams, nwindows; - nparams = of_property_count_u32_elems(np, "apple,sio-firmware-params"); + nparams = of_property_count_u32_elems(np, propname); if (nparams <= 0 || nparams > ARRAY_SIZE(params) || - of_property_read_u32_array(np, "apple,sio-firmware-params", params, nparams)) + of_property_read_u32_array(np, propname, params, nparams)) return -EINVAL; nwindows = sio_t6030_windows(np, windows, ARRAY_SIZE(windows)); if (nwindows < 0) @@ -389,7 +391,7 @@ static int sio_t6030_check_node(struct device_node *np) static int sio_t6030_check_boot_tables(struct device *dev) { - if (sio_t6030_check_node(dev->of_node)) { + if (sio_t6030_check_node(dev->of_node, "apple,sio-firmware-params")) { dev_err(dev, "boot tables are not for SIO protocol 10; leaving the SIO stopped\n"); return -ENODEV; } @@ -1678,6 +1680,9 @@ static int sio_device_config(struct dma_chan *chan, struct sio_shmem_chan_config cfg; int ret; + if (sio->tables_mismatch) + return -ENODEV; + if (config->peripheral_config) { if (config->peripheral_size != sizeof(struct apple_sio_idle)) return -EINVAL; @@ -1926,15 +1931,53 @@ static int sio_alloc_shmem(struct sio_data *sio) return err; } +/* + * A low-window SIO (M1, M2) takes the earlier boot tables when its firmware reports protocol 9 + * and T6030's when it reports protocol 10 (the M2's 27.2 firmware, with an ADT the same as its + * 13.5 one's), so the boot loader passes T6030's tables as a second list, used for protocol 10. + * A protocol-10 firmware given only the earlier tables (an older boot loader) crashes at its + * first channel configuration; keep the firmware running for sleep, but offer it no DMA. + */ +static const char *sio_dt_params_name(struct sio_data *sio) +{ + struct device_node *np = sio->dev->of_node; + + if (sio->protocol != 10) + return "apple,sio-firmware-params"; + if (!of_property_present(np, "apple,sio-firmware-params-v10")) { + u32 key, size; + int i, n = of_property_count_u32_elems(np, "apple,sio-firmware-params"); + + /* The earlier layout's five 32-byte shim records are never protocol 10's */ + for (i = 0; i + 1 < n; i += 2) + if (!of_property_read_u32_index(np, "apple,sio-firmware-params", i, &key) && + key == 0x23 && + !of_property_read_u32_index(np, "apple,sio-firmware-params", i + 1, + &size) && + size == 5 * 32) + sio->tables_mismatch = true; + return "apple,sio-firmware-params"; + } + if (sio_t6030_check_node(np, "apple,sio-firmware-params-v10")) { + sio->tables_mismatch = true; + return "apple,sio-firmware-params"; + } + return "apple,sio-firmware-params-v10"; +} + static int sio_send_dt_params(struct sio_data *sio) { struct device_node *np = sio->dev->of_node; - const char *propname = "apple,sio-firmware-params"; + const char *propname; int nparams, err, i; if (sio->hw->send_dt_params) return sio->hw->send_dt_params(sio); + propname = sio_dt_params_name(sio); + if (sio->tables_mismatch) + dev_err(sio->dev, "boot tables are not for SIO protocol 10; no DMA\n"); + nparams = of_property_count_u32_elems(np, propname); if (nparams < 0) { err = nparams; From 6cf0ccf5aab2f2bd96970d59f51cf593d2d8a152 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 23:56:10 +0100 Subject: [PATCH 0901/1514] drm/apple: take the T8152 USB-C display state from the Type-C ports The T8152 DCPs found a USB-C display by reading the rear ports' PD controllers over SPMI every 250 ms (t8152_pd.c): plug and orientation from STATUS (0x1a), DisplayPort connection, pin assignment and HPD from DATA_STATUS (0x5f), through the controllers' register window (select at 0x00, length at 0x1f, data from 0x20). With tipd bound to the same controllers, tipd failed to read its events while the display path polled. The controllers belong to tipd now. Take the state from the Type-C class instead: one Type-C mode switch per rear port, the port's usb-c node in the shared ports node, with an endpoint at the display port of the port's connector. tipd sets the port's mode on it. The switch records whether the port is in DisplayPort alt mode with HPD high, the lanes of the pin assignment (two for B, D and F, which share the cable with USB 3) and the plug orientation of the Type-C port, once, next to the port claims of t8152_atc.c, and tells every DCP that drives USB-C to look at the ports. The port claim and the PHY, crossbar and DPTX handling of t8152_atc.c and iboot_drm.c stay as they were. One switch per port, not one per DCP: a connector's port driver takes three mode switches at most (TYPEC_MUX_MAX_DEVS; fwnode_connection_find_matches() stops at the third endpoint and returns success). A switch per DCP would fill all three on every J873g rear connector, and the port's ATC PHY, which needs one for USB4, would never be called. A HPD pulse is not a new sink. Without a video stream, an EV2780 drops HPD for about 160 ms every 4.7 s; the PD controller reports it after the fact, and tipd passes it on as HPD low and then high. Connecting the sink anew on each pulse kept its link from coming up (link faults, one lane, then a standby link trained at RBR whose mode list lacked the enabled mode, so the next DPMS on failed atomic check). The 250 ms poll never saw these pulses. A switch event is looked at 100 ms later, which takes such a low and high together, and only a changed plug (orientation, lanes) or a sink that leaves DP alt mode with its partner is a new connection. dcp-fabric.c's route layer itself does not fit these DCPs: it switches a DP PHY and the display crossbar through their drivers and connects the sink through the DCP's IOMFB DPTX service, while the iBoot interface DCPs program the ATC PHY and the crossbar themselves and connect through their own DPTX port service. Their switches only record the state, in t8152_typec.c. The 250 ms work now only re-arms while a DCP can take the shared HDMI port, whose HPD line has no interrupt. The PD controller reset that made a sink which stopped answering AUX enter DP alt mode again (a cold reset, "Gaid", then system power state S0, "SSPS") is gone: the controller is tipd's, and tipd puts it into S0 whenever it sets the controller up. What remains is the DisplayPort side, at most once a minute: release the link and connect the port's sink again. HPD changes now reach the display path as they happen. The first DCP that probes registers the switches, ahead of everything else in its probe, and they stay until the driver is unloaded: tipd keeps the switch it found, and must not wait for a DCP that cannot start. Their parent is a faux device of their own ("t8152-typec"), not that DCP, so unbinding a DCP leaves no switch under an unbound device. A switch that cannot be registered is disabled in the live tree, so that tipd goes on without it; the driver keeps that changeset and reverts it at unload. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/Kconfig | 5 +- drivers/gpu/drm/apple/Makefile | 2 +- drivers/gpu/drm/apple/dcp.c | 6 +- drivers/gpu/drm/apple/iboot_drm.c | 77 +++++--- drivers/gpu/drm/apple/iomfb_iboot.c | 11 +- drivers/gpu/drm/apple/iomfb_iboot.h | 13 +- drivers/gpu/drm/apple/t8152_atc.c | 15 +- drivers/gpu/drm/apple/t8152_display.h | 31 +-- drivers/gpu/drm/apple/t8152_pd.c | 211 -------------------- drivers/gpu/drm/apple/t8152_typec.c | 264 ++++++++++++++++++++++++++ 10 files changed, 359 insertions(+), 276 deletions(-) delete mode 100644 drivers/gpu/drm/apple/t8152_pd.c create mode 100644 drivers/gpu/drm/apple/t8152_typec.c diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 876ebbd58605e1..aae90f8de5825c 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -78,7 +78,7 @@ config DRM_APPLE_DCP_T8132 config DRM_APPLE_DCP_T8152 bool "Mac mini M6 (J873g) displays" depends on DRM_APPLE - depends on SPMI=y || SPMI=DRM_APPLE + depends on TYPEC depends on MFD_MACSMC=y || MFD_MACSMC=DRM_APPLE select APERTURE_HELPERS help @@ -86,7 +86,8 @@ config DRM_APPLE_DCP_T8152 coprocessors of the T8152 Mac mini (J873g) through their firmware's iBoot interface: the HDMI port, whose DisplayPort-to-HDMI converter is powered through the SMC, and displays on the rear USB-C ports, - whose PD controllers are polled over SPMI. + whose DisplayPort alt mode the USB Type-C port driver of their PD + controllers reports (TYPEC_SN201202X). The boot loader hands each coprocessor over, running or quiesced, with the AFK endpoints it left running. The adopted sessions cannot diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index e6752d0f285166..c040f80df8e80e 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -19,7 +19,7 @@ appledrm-y += iomfb_v26_6_desktop.o appledrm-y += iomfb_v14_7.o iomfb_v14_7_link.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8132) += iomfb_m4.o t8132_ext_drm.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_atc.o t8152_aux.o t8152_dptx.o -appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_pd.o +appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_typec.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += iomfb_iboot.o iboot_drm.o appledrm-y += iomfb_h17p.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_h17p_test.o parser_test.o diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 396b62c988ecbb..b0b1255045fd52 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7938,8 +7938,11 @@ static int dcp_platform_probe(struct platform_device *pdev) void *group; int ret; - if (hw->firmware_compat == DCP_FIRMWARE_IBOOT) + if (hw->firmware_compat == DCP_FIRMWARE_IBOOT) { + /* The port controllers wait for the USB-C display switches. */ + t8152_typec_register(dev); return dcp_platform_probe_iboot(pdev); + } /* t6041_dcpext=0: stay off the external processors' hardware. */ if (of_device_is_compatible(dev->of_node, "apple,t6041-dcpext") && @@ -10249,6 +10252,7 @@ int __init dcp_register(void) void dcp_unregister(void) { platform_driver_unregister(&apple_platform_driver); + t8152_typec_unregister(); } #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) diff --git a/drivers/gpu/drm/apple/iboot_drm.c b/drivers/gpu/drm/apple/iboot_drm.c index c0b3bd2311962d..46b9fae4992545 100644 --- a/drivers/gpu/drm/apple/iboot_drm.c +++ b/drivers/gpu/drm/apple/iboot_drm.c @@ -369,10 +369,10 @@ iboot_connector_detect(struct drm_connector *connector, bool force) dev_info(dcp->dev, "sink %s\n", hpd ? "plugged" : "unplugged"); disp->hpd = hpd; /* - * USB-C: the DPTX port's HPD follows the PD controller, and a - * new plug may come the other way round. + * USB-C: the DPTX port's HPD follows the port's Type-C state, + * and a new plug may come the other way round. */ - if (disp->pd) { + if (disp->usbc) { if (!hpd || ib->powered) { iboot_cancel_swap_locked(ib); if (t8152_dptx_disconnect(disp, 0)) @@ -408,11 +408,11 @@ iboot_connector_detect(struct drm_connector *connector, bool force) dev_err(dcp->dev, "no modes from the new sink\n"); ib->nr_tmodes = 0; ib->nr_cmodes = 0; - /* A sleeping EIZO may need a fresh DP alt mode entry. */ - if (disp->pd && !disp->on_hdmi && - time_after(jiffies, ib->pd_reset_time + 60 * HZ)) { - ib->pd_reset_time = jiffies; - schedule_work(&ib->pd_reset_work); + /* A sleeping EIZO may need its link started anew. */ + if (disp->usbc && !disp->on_hdmi && + time_after(jiffies, ib->relink_time + 60 * HZ)) { + ib->relink_time = jiffies; + schedule_work(&ib->relink_work); } } /* @@ -724,16 +724,17 @@ static int iboot_set_mode_locked(struct dcp_iboot *ib, dev_err(ib->dcp->dev, "set_mode failed: %d\n", ret); /* * USB-C: a sink that no longer answers AUX (seen after the - * monitor's deep sleep) comes back with a fresh DP alt mode - * entry; the plug that follows sets the mode again. At most - * once a minute, so a dead sink does not loop. + * monitor's deep sleep) is connected anew: its link is + * released, and the plug that follows starts the PHY cold + * and sets the mode again. At most once a minute, so a dead + * sink does not loop. */ - if (ib->disp.pd && !ib->disp.on_hdmi && - time_after(jiffies, ib->pd_reset_time + 60 * HZ)) { + if (ib->disp.usbc && !ib->disp.on_hdmi && + time_after(jiffies, ib->relink_time + 60 * HZ)) { ib->cur_mode = *t; ib->mode_failed = true; - ib->pd_reset_time = jiffies; - schedule_work(&ib->pd_reset_work); + ib->relink_time = jiffies; + schedule_work(&ib->relink_work); } return ret; } @@ -944,14 +945,18 @@ static const struct drm_mode_config_funcs iboot_mode_config_funcs = { .atomic_commit = drm_atomic_helper_commit, }; -static void iboot_pd_reset_work(struct work_struct *work) +/* + * Release the link of a USB-C sink that does not answer, and have the port's + * sink plugged again: the port's Type-C state still shows it, so the next + * look at the ports connects it as a new one. + */ +static void iboot_relink_work(struct work_struct *work) { - struct dcp_iboot *ib = container_of(work, struct dcp_iboot, pd_reset_work); + struct dcp_iboot *ib = container_of(work, struct dcp_iboot, relink_work); struct t8152_display *disp = &ib->disp; int ret; - dev_info(ib->dcp->dev, "USB-C sink does not answer, entering DP alt mode again\n"); - /* The reset may finish between polls. Release the old link explicitly. */ + dev_info(ib->dcp->dev, "USB-C sink does not answer, connecting it again\n"); mutex_lock(&ib->lock); iboot_cancel_swap_locked(ib); ret = t8152_dptx_disconnect(disp, 0); @@ -968,13 +973,9 @@ static void iboot_pd_reset_work(struct work_struct *work) return; } disp->hpd = 0; - ret = t8152_pd_reconnect(disp); mutex_unlock(&ib->lock); - if (ret) { - dev_err(ib->dcp->dev, "DP alt mode entry failed: %d\n", ret); - return; - } drm_kms_helper_hotplug_event(&ib->drm); + dcp_iboot_hpd_event(ib); } static void iboot_hpd_work(struct work_struct *work) @@ -985,11 +986,27 @@ static void iboot_hpd_work(struct work_struct *work) if (!READ_ONCE(ib->ready)) return; drm_helper_hpd_irq_event(&ib->drm); - if (READ_ONCE(ib->ready)) + /* + * USB-C changes come from the ports' display switches. The HDMI port's + * HPD line has no interrupt: poll it while this DCP can take the port. + */ + if (READ_ONCE(ib->ready) && ib->disp.hdmi_port) queue_delayed_work(system_freezable_wq, &ib->hpd_work, msecs_to_jiffies(250)); } +/* + * A USB-C port's Type-C state changed: look at the ports shortly. A HPD pulse + * the port driver learns of after the fact comes as HPD low and high at once; + * the delay takes both together. + */ +void dcp_iboot_hpd_event(struct dcp_iboot *ib) +{ + if (READ_ONCE(ib->ready)) + mod_delayed_work(system_freezable_wq, &ib->hpd_work, + msecs_to_jiffies(100)); +} + void dcp_iboot_kms_stop(struct dcp_iboot *ib) { if (!ib->kms_work_ready) @@ -998,7 +1015,7 @@ void dcp_iboot_kms_stop(struct dcp_iboot *ib) cancel_delayed_work_sync(&ib->hpd_work); hrtimer_cancel(&ib->swap_timer); cancel_work_sync(&ib->swap_work); - cancel_work_sync(&ib->pd_reset_work); + cancel_work_sync(&ib->relink_work); } static void iboot_swap_stop(void *data) @@ -1014,7 +1031,7 @@ int dcp_iboot_kms_init(struct dcp_iboot *ib) ib->pending = -1; INIT_WORK(&ib->swap_work, iboot_swap_work); - INIT_WORK(&ib->pd_reset_work, iboot_pd_reset_work); + INIT_WORK(&ib->relink_work, iboot_relink_work); INIT_DELAYED_WORK(&ib->hpd_work, iboot_hpd_work); hrtimer_setup(&ib->swap_timer, iboot_swap_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); @@ -1031,7 +1048,7 @@ int dcp_iboot_kms_init(struct dcp_iboot *ib) ret = drmm_mode_config_init(drm); if (ret) return ret; - ib->pd_reset_time = jiffies - 61 * HZ; + ib->relink_time = jiffies - 61 * HZ; drm->mode_config.min_width = 320; drm->mode_config.min_height = 240; @@ -1067,10 +1084,10 @@ int dcp_iboot_kms_init(struct dcp_iboot *ib) if (ret) return ret; drm_connector_helper_add(&ib->connector, &iboot_connector_helper); - if (ib->disp.hpd_gpio || ib->disp.pd) + if (ib->disp.hpd_gpio || ib->disp.usbc) ib->connector.polled = DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT; - if (ib->disp.pd) + if (ib->disp.usbc) ib->connector.polled = DRM_CONNECTOR_POLL_HPD; ret = drm_connector_attach_encoder(&ib->connector, &ib->encoder); if (ret) diff --git a/drivers/gpu/drm/apple/iomfb_iboot.c b/drivers/gpu/drm/apple/iomfb_iboot.c index 757b122dc8e42e..df308b133a39ad 100644 --- a/drivers/gpu/drm/apple/iomfb_iboot.c +++ b/drivers/gpu/drm/apple/iomfb_iboot.c @@ -625,7 +625,7 @@ static int dcp_iboot_start(struct dcp_iboot *ib) &t8152_dptx_port_ops, 2); if (ret) return dev_err_probe(dev, ret, "no DPTX port service\n"); - if (disp->pd) { + if (disp->usbc) { ret = t8152_dptx_disconnect(disp, 0); if (ret) return dev_err_probe(dev, ret, "cannot release inherited DP link\n"); @@ -635,7 +635,7 @@ static int dcp_iboot_start(struct dcp_iboot *ib) * USB-C negotiation can outlive probe or fail while a monitor sleeps. * Register the connector first; the hotplug path owns all USB-C links. */ - if (disp->pd) + if (disp->usbc) sink = false; if (sink) { ret = t8152_dptx_connect(disp, 0); @@ -698,9 +698,9 @@ static int dcp_iboot_start(struct dcp_iboot *ib) if (ret) return ret; WRITE_ONCE(ib->ready, true); - if (disp->hpd_gpio || disp->pd) + if (disp->hpd_gpio || disp->usbc) drmm_kms_helper_poll_init(&ib->drm); - if (disp->pd) + if (disp->usbc) queue_delayed_work(system_freezable_wq, &ib->hpd_work, msecs_to_jiffies(250)); drm_client_setup(&ib->drm, NULL); @@ -801,6 +801,9 @@ int dcp_iboot_probe(struct apple_dcp *dcp) dev_warn(dev, "live session not recorded; its DMA stays allocated\n"); WRITE_ONCE(dcp->retain_dma, true); } + /* The device stays bound from here on: follow the USB-C ports. */ + if (t8152_typec_init(disp)) + dev_err(dev, "USB-C ports not followed, no USB-C display\n"); if (ret) dev_err(dev, "cannot adopt the DCP: %d\n", ret); else diff --git a/drivers/gpu/drm/apple/iomfb_iboot.h b/drivers/gpu/drm/apple/iomfb_iboot.h index 9c2268604b0175..bddeeedc198d52 100644 --- a/drivers/gpu/drm/apple/iomfb_iboot.h +++ b/drivers/gpu/drm/apple/iomfb_iboot.h @@ -94,9 +94,9 @@ struct dcp_iboot { bool mode_set; /* SET_MODE of cur_mode failed; the next plug sets it again */ bool mode_failed; - /* USB-C: re-enter DP alt mode when the sink stopped answering */ - struct work_struct pd_reset_work; - unsigned long pd_reset_time; + /* USB-C: connect the sink anew when it stopped answering */ + struct work_struct relink_work; + unsigned long relink_time; /* * The DPAV video interface started: SET_MODE again, or the * firmware's idle power off timer takes the link down 30 s later. @@ -116,6 +116,10 @@ static inline struct dcp_iboot *to_dcp_iboot(struct drm_device *drm) } #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8152) +/* t8152_typec.c */ +void t8152_typec_register(struct device *dev); +void t8152_typec_unregister(void); + /* iomfb_iboot.c */ int dcp_iboot_probe(struct apple_dcp *dcp); void dcp_iboot_remove(struct apple_dcp *dcp); @@ -131,7 +135,10 @@ int dcp_iboot_set_boot_mode(struct dcp_iboot *ib); void dcp_iboot_update_edid(struct dcp_iboot *ib); void dcp_iboot_reset_mode(struct dcp_iboot *ib); void dcp_iboot_av_started(struct dcp_iboot *ib); +void dcp_iboot_hpd_event(struct dcp_iboot *ib); #else +static inline void t8152_typec_register(struct device *dev) { } +static inline void t8152_typec_unregister(void) { } static inline int dcp_iboot_probe(struct apple_dcp *dcp) { return -ENODEV; } static inline void dcp_iboot_remove(struct apple_dcp *dcp) { } #endif diff --git a/drivers/gpu/drm/apple/t8152_atc.c b/drivers/gpu/drm/apple/t8152_atc.c index ce4b6a84602de1..b2d018d4e636ec 100644 --- a/drivers/gpu/drm/apple/t8152_atc.c +++ b/drivers/gpu/drm/apple/t8152_atc.c @@ -13,7 +13,7 @@ * set up the lanes again), drive settings, the DCP -> ATCn/DFP0 crossbar * route, and with the display off or unplugged a full power down and a cold * start. A DCP drives one USB-C port at a time: the one it claims from the - * shared ports while polling their PD controllers. + * shared ports once their Type-C state shows a sink (t8152_typec.c). */ #include @@ -53,7 +53,6 @@ struct t8152_atc_port { unsigned int index; /* ATC instance */ /* display crossbar DFP endpoint of this ATC */ u32 dfp; - struct spmi_device *pd; /* AP DisplayPort AUX controller aux0 (shared), for the EDID */ struct t8152_aux *aux; /* PMGR power states of the four ATC dependencies */ @@ -692,7 +691,9 @@ static int atc_detect(struct t8152_display *disp, bool *flipped) atc->next = atc->cur; /* Keep a monitor on its controller, including while userspace blanks it. */ if (atc_owner[atc->cur->index] == disp->dev) { - ret = t8152_pd_sink(atc->cur->pd, flipped, &atc->cur->next_lanes); + ret = t8152_typec_sink(disp, atc->cur->index, flipped, + &atc->cur->next_lanes); + /* The plug changed: a new sink */ if (ret > 0 && (atc->cur->swap != *flipped || atc->cur->lanes != atc->cur->next_lanes)) disp->hpd = 0; @@ -706,7 +707,7 @@ static int atc_detect(struct t8152_display *disp, bool *flipped) struct t8152_atc_port *port = &atc->port[i]; if (atc_owner[port->index] || - t8152_pd_sink(port->pd, flipped, &port->next_lanes) <= 0) + t8152_typec_sink(disp, port->index, flipped, &port->next_lanes) <= 0) continue; atc_owner[port->index] = disp->dev; atc->next = port; @@ -739,7 +740,6 @@ static void atc_select(struct t8152_display *disp) dev_info(disp->dev, "USB-C display on ATC%u now, was ATC%u\n", port->index, atc->cur->index); atc->cur = port; - disp->pd = port->pd; disp->dcp_output = port->dfp; } @@ -796,9 +796,6 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, port->psd = atc_map(disp, np, "atc-psd"); if (!port->base || !port->ps || !port->psd) return -ENOMEM; - port->pd = t8152_pd_get(np); - if (IS_ERR_OR_NULL(port->pd)) - return port->pd ? PTR_ERR(port->pd) : -ENODEV; /* The node without ports is ATC3's (J873g back-right). */ port->dfp = 3; of_property_read_u32(np, "apple,dfp-endpoint", &port->dfp); @@ -916,7 +913,7 @@ int t8152_atc_init(struct t8152_display *disp) atc->next = atc->cur; disp->phy = &atc_ops; disp->phy_priv = atc; - disp->pd = atc->cur->pd; + disp->usbc = true; disp->dcp_output = atc->cur->dfp; dev_info(disp->dev, "USB-C display on ATC%u (%u ports)\n", atc->cur->index, atc->nports); diff --git a/drivers/gpu/drm/apple/t8152_display.h b/drivers/gpu/drm/apple/t8152_display.h index b26baf6b04924f..f4aa562fb38109 100644 --- a/drivers/gpu/drm/apple/t8152_display.h +++ b/drivers/gpu/drm/apple/t8152_display.h @@ -4,15 +4,15 @@ * that no subsystem driver covers yet: the ATC PHYs' DisplayPort lanes and * their display crossbar route (t8152_atc.c), the HDMI port's dedicated * DisplayPort PHY and PS190 converter (t8152_hdmi.c), the AP's DisplayPort - * AUX controllers that read the sink's EDID (t8152_aux.c), the rear USB-C - * ports' ACE3 PD controllers (t8152_pd.c), and the DPTX port service the - * DCP firmware calls into for the PHY (t8152_dptx.c). + * AUX controllers that read the sink's EDID (t8152_aux.c), and the DPTX port + * service the DCP firmware calls into for the PHY (t8152_dptx.c). The rear + * USB-C ports' DisplayPort alt mode state comes from their Type-C port + * driver, through the ports' shared display switches (t8152_typec.c). * - * Interim: the ATC DisplayPort mode moves to drivers/phy/apple/atc.c, the - * ACE3 controllers to tipd, and the choice of port with DP alt mode to the - * Type-C route layer of dcp-fabric.c, each in its own change. Until then - * these files program the registers themselves, for the iBoot interface - * DCPs of iomfb_iboot.c alone. + * Interim: the ATC DisplayPort mode moves to drivers/phy/apple/atc.c and the + * choice of port with DP alt mode to the Type-C route layer of dcp-fabric.c, + * each in its own change. Until then these files program the registers + * themselves, for the iBoot interface DCPs of iomfb_iboot.c alone. */ #ifndef __APPLE_T8152_DISPLAY_H__ #define __APPLE_T8152_DISPLAY_H__ @@ -24,9 +24,9 @@ struct apple_epic_service_ops; struct device; struct device_node; struct gpio_desc; -struct spmi_device; struct t8152_display; struct t8152_hdmi; +struct t8152_typec; /* SET_DRIVE_SETTINGS and GET_DRIVE_SETTINGS records, one per lane */ struct t8152_drive_settings { @@ -90,8 +90,9 @@ struct t8152_display { /* optional sink HPD line (HDMI), polled; the last level seen */ struct gpio_desc *hpd_gpio; int hpd; - /* USB-C: the PD controller of the port in use */ - struct spmi_device *pd; + /* USB-C: plug and HPD come from the ports' display switches */ + bool usbc; + struct t8152_typec *typec; /* HDMI PHY: DCPEXT0's, or the main DCP's on an HDMI-only boot */ bool hdmi; /* @@ -126,10 +127,10 @@ int t8152_aux_init(struct t8152_display *disp, struct t8152_aux *aux); int t8152_aux_read_edid(struct t8152_display *disp, struct t8152_aux *aux, u8 *buf, size_t size); -/* t8152_pd.c */ -struct spmi_device *t8152_pd_get(struct device_node *np); -int t8152_pd_sink(struct spmi_device *pd, bool *flipped, u32 *lanes); -int t8152_pd_reconnect(struct t8152_display *disp); +/* t8152_typec.c, see also iomfb_iboot.h */ +int t8152_typec_init(struct t8152_display *disp); +int t8152_typec_sink(struct t8152_display *disp, u32 index, bool *flipped, + u32 *lanes); /* t8152_dptx.c */ extern const struct apple_epic_service_ops t8152_dptx_port_ops; diff --git a/drivers/gpu/drm/apple/t8152_pd.c b/drivers/gpu/drm/apple/t8152_pd.c deleted file mode 100644 index 8c514d17d69d2c..00000000000000 --- a/drivers/gpu/drm/apple/t8152_pd.c +++ /dev/null @@ -1,211 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* - * USB-C plug state from the rear ports' ACE3 PD controllers over SPMI, for - * the USB-C displays' hotplug: the DP alt mode connection, its pin - * assignment and the plug orientation. Logical registers are read through a - * window: select with a register-zero write, wait for the busy bit to - * clear, read the size at 0x1f and the data from 0x20. - * - * Interim, until tipd owns these controllers and reports DP alt mode to the - * Type-C route layer of dcp-fabric.c: tipd and this share the SPMI devices, - * serialized by the device lock. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "t8152_display.h" - -#define ACE3_SELECT 0x00 -#define ACE3_SELECT_BUSY BIT(7) -#define ACE3_SIZE 0x1f -#define ACE3_DATA 0x20 -#define ACE3_BURST 16 - -#define ACE3_REG_CMD1 0x08 -#define ACE3_REG_DATA1 0x09 -#define ACE3_REG_STATUS 0x1a -#define ACE3_REG_POWER_STATE 0x20 -#define ACE3_REG_DATA_STATUS 0x5f - -#define STATUS_PLUG_PRESENT BIT(0) -#define STATUS_UPSIDE_DOWN BIT(4) -#define DATA_DP_CONNECTION BIT(8) -#define DATA_HPD_LEVEL BIT(15) /* CD321x, as tipd */ - -static int ace3_read(struct spmi_device *sdev, u8 reg, u8 *buf, size_t len) -{ - u8 sel, size; - int ret, err = 0; - - ret = spmi_register_zero_write(sdev, reg); - if (ret) - return ret; - ret = read_poll_timeout(spmi_ext_register_read, err, - err || !(sel & ACE3_SELECT_BUSY), 50, 20000, - false, sdev, ACE3_SELECT, &sel, 1); - if (ret || err) - return ret ?: err; - ret = spmi_ext_register_read(sdev, ACE3_SIZE, &size, 1); - if (ret) - return ret; - if (size < len) - return -EIO; - for (size_t done = 0; done < len; done += ACE3_BURST) { - ret = spmi_ext_register_read(sdev, ACE3_DATA + done, buf + done, - min_t(size_t, len - done, ACE3_BURST)); - if (ret) - return ret; - } - return 0; -} - -static int ace3_select(struct spmi_device *sdev, u8 reg) -{ - u8 sel; - int ret, err = 0; - - ret = spmi_register_zero_write(sdev, reg); - if (ret) - return ret; - ret = read_poll_timeout(spmi_ext_register_read, err, - err || !(sel & ACE3_SELECT_BUSY), 50, 20000, - false, sdev, ACE3_SELECT, &sel, 1); - return ret ?: err; -} - -static int ace3_write(struct spmi_device *sdev, u8 reg, const u8 *buf, - size_t len) -{ - int ret = ace3_select(sdev, reg); - - return ret ?: spmi_ext_register_write(sdev, ACE3_DATA, (u8 *)buf, len); -} - -/* A 4CC command with an optional data byte; 0 once the controller took it. */ -static int ace3_cmd(struct spmi_device *sdev, const char *cmd, int data) -{ - u8 val[4]; - int ret; - - ret = spmi_command_wakeup(sdev); - if (ret) - return ret; - if (data >= 0) { - u8 d = data; - - ret = ace3_write(sdev, ACE3_REG_DATA1, &d, 1); - if (ret) - return ret; - } - ret = ace3_write(sdev, ACE3_REG_CMD1, cmd, 4); - if (ret) - return ret; - for (int i = 0; i < 1000; i++) { - ret = ace3_read(sdev, ACE3_REG_CMD1, val, sizeof(val)); - if (ret) - return ret; - if (!memcmp(val, "!CMD", 4)) - return -EIO; - if (!memcmp(val, "\0\0\0\0", 4)) - return 0; - usleep_range(1000, 2000); - } - return -ETIMEDOUT; -} - -/* - * Leave and enter DP alt mode again, as unplugging and plugging the cable - * does: reset the controller (Gaid), then power the port up again once it - * takes commands (SSPS 0). A sink that stopped answering AUX after a - * monitor's deep sleep comes back this way. - */ -int t8152_pd_reconnect(struct t8152_display *disp) -{ - struct spmi_device *pd = disp->pd; - int ret; - - device_lock(&pd->dev); - /* Gaid resets the controller before it can report completion. */ - ret = spmi_command_wakeup(pd); - if (!ret) - ret = ace3_write(pd, ACE3_REG_CMD1, "Gaid", 4); - if (ret) - goto out; - /* - * The controller restarts: on the J873g ports its mode register read - * "BOOT" about 22 ms after Gaid, it acknowledged no SPMI command from - * about 215 ms on, and it read "APP " and took SSPS again after about - * 290 ms. Polling it through that gap only gets NACKs, which the SPMI - * controller logs as errors, and nothing signals the restart's end. - * So SSPS is first sent 500 ms after Gaid, and every 500 ms after that - * for a controller that takes longer. - */ - for (int i = 0; i < 60; i++) { - msleep(500); - ret = ace3_cmd(pd, "SSPS", 0); - if (!ret) - break; - } -out: - device_unlock(&pd->dev); - return ret; -} - -/* 1 with a DisplayPort sink in DP alt mode and HPD high, 0 without. */ -int t8152_pd_sink(struct spmi_device *pd, bool *flipped, u32 *lanes) -{ - u8 status[4], data[4], power; - int ret; - - /* Serialize the logical register window with the USB4 port monitor. */ - device_lock(&pd->dev); - /* Without a plug the controller sleeps and ignores selects. */ - ret = spmi_command_wakeup(pd); - if (ret) - goto out; - ret = ace3_read(pd, ACE3_REG_POWER_STATE, &power, sizeof(power)); - if (ret) - goto out; - /* Register access alone does not enable the alt-mode policy engine. */ - if (power) { - ret = ace3_cmd(pd, "SSPS", 0); - if (ret) - goto out; - } - ret = ace3_read(pd, ACE3_REG_STATUS, status, sizeof(status)); - if (!ret) - ret = ace3_read(pd, ACE3_REG_DATA_STATUS, data, sizeof(data)); - if (ret) - goto out; - *flipped = status[0] & STATUS_UPSIDE_DOWN; - /* Pin D/F shares the cable with USB3; C/E uses all four DP lanes. */ - *lanes = get_unaligned_le32(data) & BIT(5) ? 2 : 4; - /* The sink answers AUX once it raised HPD, not at alt mode entry. */ - ret = (status[0] & STATUS_PLUG_PRESENT) && - (get_unaligned_le32(data) & DATA_DP_CONNECTION) && - (get_unaligned_le32(data) & DATA_HPD_LEVEL); -out: - device_unlock(&pd->dev); - return ret; -} - -/* The PD controller @np's apple,usb-pd points at, NULL without one. */ -struct spmi_device *t8152_pd_get(struct device_node *np) -{ - struct device_node *pd_np = of_parse_phandle(np, "apple,usb-pd", 0); - struct spmi_device *pd; - - if (!pd_np) - return NULL; - /* Holds a reference for the lifetime of the (retained) device. */ - pd = spmi_find_device_by_of_node(pd_np); - of_node_put(pd_np); - return pd ?: ERR_PTR(-EPROBE_DEFER); -} diff --git a/drivers/gpu/drm/apple/t8152_typec.c b/drivers/gpu/drm/apple/t8152_typec.c new file mode 100644 index 00000000000000..afae7b2546d607 --- /dev/null +++ b/drivers/gpu/drm/apple/t8152_typec.c @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The rear USB-C ports' DisplayPort alt mode, from the USB Type-C port + * driver that owns their PD controllers. Each port has one Type-C mode + * switch for the display path, shared by all DCPs: the port's usb-c node in + * the shared ports node (apple,usb-c-ports), whose endpoint is at the display + * port of the port's connector. The Type-C class looks at three mode switches + * of a connector at most, and the port's PHY needs one as well, so there is + * no room for one per DCP. + * + * The first DCP that probes registers the switches, and they stay until the + * driver is unloaded: the port driver keeps using a switch it found, and + * must not wait for a DCP that cannot start. A switch records what the + * display path reads (DisplayPort alt mode with HPD high, the lanes of the + * pin assignment, the plug orientation) and has every DCP that drives USB-C + * look at its ports; t8152_atc.c claims a port for one of them. + * + * The switches are dcp-fabric.c's in the device tree only. Its route layer + * switches a DP PHY and the display crossbar through their own drivers and + * connects the sink through the DCP's IOMFB DPTX service; these DCPs program + * the ATC PHY and the crossbar themselves and connect through the iBoot + * interface's DPTX port service, so their switches record the state alone. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iomfb_iboot.h" +#include "t8152_display.h" + +/* The ATC instances, as the display crossbar's DFP endpoints number them */ +#define T8152_TYPEC_PORTS 4 + +struct t8152_typec_port { + struct typec_mux_dev *mux; + /* below under t8152_typec_lock */ + bool sink; + bool flipped; + u32 lanes; +}; + +/* A DCP that drives USB-C, told about the ports' changes */ +struct t8152_typec { + struct list_head node; + struct t8152_display *disp; +}; + +/* Registers the switches, once */ +static DEFINE_MUTEX(t8152_typec_register_lock); +/* Below under t8152_typec_register_lock: the switches' parent, which no DCP binding owns */ +static struct faux_device *t8152_typec_owner; +/* The status changesets of ports whose switch could not be registered */ +struct t8152_typec_disabled { + struct list_head node; + struct of_changeset cs; +}; + +static LIST_HEAD(t8152_typec_disabled_ports); +/* The ports' state, written by the port driver, and the DCPs that read it */ +static DEFINE_SPINLOCK(t8152_typec_lock); +static struct t8152_typec_port t8152_typec_ports[T8152_TYPEC_PORTS]; +static LIST_HEAD(t8152_typec_displays); + +static int t8152_typec_set(struct typec_mux_dev *mux, struct typec_mux_state *state) +{ + struct t8152_typec_port *port = typec_mux_get_drvdata(mux); + struct typec_displayport_data *dp = NULL; + struct t8152_typec *typec; + bool flipped = false; + u32 lanes = 4; + + if (state->alt && state->alt->svid == USB_TYPEC_DP_SID && + state->mode >= TYPEC_DP_STATE_A && state->mode <= TYPEC_DP_STATE_F) { + dp = state->data; + flipped = typec_altmode_get_orientation(state->alt) == + TYPEC_ORIENTATION_REVERSE; + /* B, D and F share the cable with USB 3: two DisplayPort lanes */ + if (state->mode == TYPEC_DP_STATE_B || state->mode == TYPEC_DP_STATE_D || + state->mode == TYPEC_DP_STATE_F) + lanes = 2; + } + + guard(spinlock)(&t8152_typec_lock); + /* The sink answers AUX once it raised HPD, not at alt mode entry. */ + port->sink = dp && (dp->status & DP_STATUS_HPD_STATE); + port->flipped = flipped; + port->lanes = lanes; + list_for_each_entry(typec, &t8152_typec_displays, node) + dcp_iboot_hpd_event(container_of(typec->disp, struct dcp_iboot, disp)); + return 0; +} + +/* + * 1 with a DisplayPort sink on the port of ATC @index (DP alt mode, HPD + * high), 0 without. + * + * A HPD pulse that ends before the DCP looks is not a new sink: an EV2780 + * without a video stream drops HPD for about 160 ms every few seconds, and + * connecting it anew each time kept its link from coming up. A sink that is + * really unplugged leaves DP alt mode with its partner. + */ +int t8152_typec_sink(struct t8152_display *disp, u32 index, bool *flipped, + u32 *lanes) +{ + struct t8152_typec_port *port; + + if (!disp->typec || index >= T8152_TYPEC_PORTS) + return 0; + port = &t8152_typec_ports[index]; + guard(spinlock)(&t8152_typec_lock); + if (!port->mux || !port->sink) + return 0; + *flipped = port->flipped; + *lanes = port->lanes; + return 1; +} + +static int t8152_typec_port_register(struct device *dev, struct device_node *np) +{ + struct typec_mux_desc desc = {}; + struct t8152_typec_port *port; + struct typec_mux_dev *mux; + u32 index; + int ret; + + ret = of_property_read_u32(np, "apple,dfp-endpoint", &index); + if (ret || index >= T8152_TYPEC_PORTS) + return dev_err_probe(dev, ret ?: -EINVAL, "%pOF: invalid port\n", np); + port = &t8152_typec_ports[index]; + if (port->mux) + return 0; + desc.fwnode = of_fwnode_handle(np); + desc.set = t8152_typec_set; + desc.drvdata = port; + desc.name = kasprintf(GFP_KERNEL, "dcp-usb-c%u", index); + if (!desc.name) + return -ENOMEM; + port->lanes = 4; + /* Under the shared owner, not @dev: the switch outlives any DCP's binding. */ + mux = typec_mux_register(&t8152_typec_owner->dev, &desc); + kfree(desc.name); + if (IS_ERR(mux)) + return dev_err_probe(dev, PTR_ERR(mux), "%pOF: switch not registered\n", np); + scoped_guard(spinlock, &t8152_typec_lock) + port->mux = mux; + return 0; +} + +/* + * A switch that cannot be registered: the port driver goes on without it. + * The changeset stays applied until the driver unloads, which reverts it. + */ +static void t8152_typec_port_disable(struct device *dev, struct device_node *np) +{ + struct t8152_typec_disabled *d = kzalloc(sizeof(*d), GFP_KERNEL); + + if (!d) + return; + of_changeset_init(&d->cs); + if (!of_changeset_update_prop_string(&d->cs, np, "status", "disabled") && + !of_changeset_apply(&d->cs)) { + list_add(&d->node, &t8152_typec_disabled_ports); + return; + } + dev_err(dev, "%pOF: could not disable the display switch\n", np); + of_changeset_destroy(&d->cs); + kfree(d); +} + +/* + * Register the display switches of the USB-C ports the DCP @dev can drive, + * unless another DCP did. Called first in the DCP's probe, so that the port + * driver, which waits for them, never waits for a DCP that cannot start. + */ +void t8152_typec_register(struct device *dev) +{ + struct device_node *ports __free(device_node) = + of_parse_phandle(dev->of_node, "apple,usb-c-ports", 0); + struct device_node *np = ports ?: dev->of_node; + + guard(mutex)(&t8152_typec_register_lock); + if (!t8152_typec_owner) { + t8152_typec_owner = faux_device_create("t8152-typec", NULL, NULL); + if (!t8152_typec_owner) { + dev_err(dev, "no owner for the USB-C display switches\n"); + return; + } + } + for_each_available_child_of_node_scoped(np, child) { + if (of_property_present(child, "mode-switch") && + t8152_typec_port_register(dev, child)) + t8152_typec_port_disable(dev, child); + } +} + +/* At driver unload, once no DCP is bound */ +void t8152_typec_unregister(void) +{ + guard(mutex)(&t8152_typec_register_lock); + for (unsigned int i = 0; i < T8152_TYPEC_PORTS; i++) { + struct typec_mux_dev *mux = t8152_typec_ports[i].mux; + + if (!mux) + continue; + scoped_guard(spinlock, &t8152_typec_lock) + t8152_typec_ports[i].mux = NULL; + typec_mux_unregister(mux); + } + while (!list_empty(&t8152_typec_disabled_ports)) { + struct t8152_typec_disabled *d = + list_first_entry(&t8152_typec_disabled_ports, typeof(*d), node); + + list_del(&d->node); + /* A changeset that cannot be reverted is still part of the tree: keep it */ + if (of_changeset_revert(&d->cs)) + continue; + of_changeset_destroy(&d->cs); + kfree(d); + } + if (t8152_typec_owner) { + faux_device_destroy(t8152_typec_owner); + t8152_typec_owner = NULL; + } +} + +static void t8152_typec_leave(void *data) +{ + struct t8152_typec *typec = data; + + scoped_guard(spinlock, &t8152_typec_lock) + list_del(&typec->node); +} + +/* + * Have the DCP see the USB-C ports' display state from now on: call this + * once the DCP stays bound. Without it, the DCP sees no USB-C sink. + */ +int t8152_typec_init(struct t8152_display *disp) +{ + struct t8152_typec *typec; + int ret; + + typec = devm_kzalloc(disp->dev, sizeof(*typec), GFP_KERNEL); + if (!typec) + return -ENOMEM; + typec->disp = disp; + scoped_guard(spinlock, &t8152_typec_lock) + list_add_tail(&typec->node, &t8152_typec_displays); + ret = devm_add_action_or_reset(disp->dev, t8152_typec_leave, typec); + if (ret) + return ret; + disp->typec = typec; + return 0; +} From f9ad98d1d5d604ef3c4535e9fa397c08c130c9d1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 23:57:58 +0100 Subject: [PATCH 0902/1514] arm64: dts: apple: t8152-j873g: hand the rear USB-C PD controllers to tipd The PD controllers of the three rear USB-C ports were described for the display path alone, which read them over SPMI itself. Describe them for tipd, which owns them from now on, and the display path takes their DisplayPort alt mode state from the Type-C class: - the controllers as apple,t8152-sn201202x, with the T8132 fallback: tipd's SPMI transport then polls the register selection and reads the payload length from register 0x1f, as these controllers need; - the SPMI controller (AIC 682) as the interrupt controller of their event, sleep and wake sources: 11/17/19 (back-middle), 37/43/45 (back-left) and 63/69/71 (back-right), rising edge, as in the ADT. In a test with the compatibles and interrupts alone, tipd bound all three, took its events by interrupt, and both display partners showed DisplayPort alt mode active; - a usb-c-connector per controller, whose display port (port@3) leads to the port's usb-c node in the main DCP's shared ports node, the port's one display switch for all three DCPs. The USB port (port@0) stays unlinked: the USB data path is not changed here. The DCP's usb-c nodes lose apple,usb-pd, which nothing reads any more. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 134 +++++++++++++++++- 1 file changed, 128 insertions(+), 6 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi index 8263f1c68634be..2cc188ea99d91d 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -100,29 +100,124 @@ /* * ADT /arm-io/nub-spmi-a0 (gen 4): the USB-C PD controllers of * the three rear ports, each of which can carry the USB-C display. + * Their event, sleep and wake sources are interrupts of this + * controller (the ADT's), its own line is AIC 682. A connector's + * display port leads to the port's display switch, which all + * DCPs share. */ nub_spmi_a0: spmi@308908000 { compatible = "apple,t8152-spmi", "apple,t8142-spmi"; reg = <0x3 0x08908000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + interrupt-controller; + #interrupt-cells = <2>; #address-cells = <2>; #size-cells = <0>; /* back-middle */ hpm0: usb-pd@c { - compatible = "apple,sn201202x"; + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; reg = <0xc SPMI_USID>; + interrupts = <11 IRQ_TYPE_EDGE_RISING>, + <17 IRQ_TYPE_EDGE_RISING>, + <19 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec0: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-middle"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec0_display: endpoint { + remote-endpoint = <&display_typec0>; + }; + }; + }; + }; }; /* back-left */ hpm1: usb-pd@a { - compatible = "apple,sn201202x"; + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; reg = <0xa SPMI_USID>; + interrupts = <37 IRQ_TYPE_EDGE_RISING>, + <43 IRQ_TYPE_EDGE_RISING>, + <45 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec1: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-left"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec1_display: endpoint { + remote-endpoint = <&display_typec1>; + }; + }; + }; + }; }; /* back-right */ hpm3: usb-pd@8 { - compatible = "apple,sn201202x"; + compatible = "apple,t8152-sn201202x", "apple,t8132-sn201202x", + "apple,sn201202x"; reg = <0x8 SPMI_USID>; + interrupts = <63 IRQ_TYPE_EDGE_RISING>, + <69 IRQ_TYPE_EDGE_RISING>, + <71 IRQ_TYPE_EDGE_RISING>; + interrupt-names = "irq", "sleep", "wake"; + + typec3: connector { + compatible = "usb-c-connector"; + label = "USB-C Back-right"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + /* USB: not linked to its controller yet */ + port@0 { + reg = <0>; + }; + + /* DisplayPort: the DCPs' display switch */ + port@3 { + reg = <3>; + + typec3_display: endpoint { + remote-endpoint = <&display_typec3>; + }; + }; + }; + }; }; }; @@ -182,6 +277,7 @@ * USB-C back-middle: ADT atc-phy0. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common * domain. Tunables before and after the lane crossbar setup. + * The node is also the port's display switch for all DCPs. */ usb-c@403000000 { reg = <0x4 0x03000000 0x0 0x84000>, @@ -189,7 +285,8 @@ <0x3 0x03a13700 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <0>; - apple,usb-pd = <&hpm0>; + /* The DCPs' display switch of the port */ + mode-switch; apple,tunable-pre = /* ACIOPHY_CMN_DFLT */ <0x00800 0x00fc0000 0x00fc0000>, @@ -279,12 +376,19 @@ <0x00ebc 0x0000007f 0x0000005a>, /* ASDC_AUX_SHM_DFLT */ <0x02308 0x000000fc 0x00000084>; + + port { + display_typec0: endpoint { + remote-endpoint = <&typec0_display>; + }; + }; }; /* * USB-C back-left: ADT atc-phy1. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common * domain. Tunables before and after the lane crossbar setup. + * The node is also the port's display switch for all DCPs. */ usb-c@40b000000 { reg = <0x4 0x0b000000 0x0 0x84000>, @@ -292,7 +396,8 @@ <0x3 0x03a13800 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <1>; - apple,usb-pd = <&hpm1>; + /* The DCPs' display switch of the port */ + mode-switch; apple,tunable-pre = /* ACIOPHY_CMN_DFLT */ <0x00800 0x00fc0000 0x00fc0000>, @@ -382,12 +487,19 @@ <0x00ebc 0x0000007f 0x0000005a>, /* ASDC_AUX_SHM_DFLT */ <0x02308 0x000000fc 0x00000084>; + + port { + display_typec1: endpoint { + remote-endpoint = <&typec1_display>; + }; + }; }; /* * USB-C back-right: ADT atc-phy3. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common * domain. Tunables before and after the lane crossbar setup. + * The node is also the port's display switch for all DCPs. */ usb-c@413000000 { reg = <0x4 0x13000000 0x0 0x84000>, @@ -395,7 +507,8 @@ <0x3 0x03a13a00 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <3>; - apple,usb-pd = <&hpm3>; + /* The DCPs' display switch of the port */ + mode-switch; apple,tunable-pre = /* ACIOPHY_CMN_DFLT */ <0x00800 0x00fc0000 0x00fc0000>, @@ -485,7 +598,14 @@ <0x00ebc 0x0000007f 0x0000005a>, /* ASDC_AUX_SHM_DFLT */ <0x02308 0x000000fc 0x00000084>; + + port { + display_typec3: endpoint { + remote-endpoint = <&typec3_display>; + }; + }; }; + }; /* @@ -563,6 +683,7 @@ iommus = <&dispext0_dart 0>; dma-coherent; }; + }; dcpext1_mbox: mailbox@316020700 { @@ -591,6 +712,7 @@ iommus = <&dispext1_dart 0>; dma-coherent; }; + }; }; From 416ba83b2e7387e0455dc84d0e0123e0ccae82de Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 01:32:46 -0800 Subject: [PATCH 0903/1514] dt-bindings: watchdog: apple,wdt: add optional simple-reconfig register Apple Silicon SoCs with a simple-reconfig watchdog (such as T6050 / M5 Ultra) route WD2's bark interrupt to a cold SoC reset via a separate AON routing register, rather than resetting through WD1's RESET_EN bit. Document an optional second reg entry ("reconfig") in apple,wdt.yaml and require reg-names when both "wdt" and "reconfig" regions are present, keeping existing single-reg nodes valid without reg-names. Signed-off-by: Jeff Queisser --- .../bindings/watchdog/apple,wdt.yaml | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml index 9a6634e146d757..f65a37d504791a 100644 --- a/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml +++ b/Documentation/devicetree/bindings/watchdog/apple,wdt.yaml @@ -11,6 +11,15 @@ maintainers: allOf: - $ref: watchdog.yaml# + - if: + properties: + reg: + minItems: 2 + required: + - reg + then: + required: + - reg-names properties: compatible: @@ -42,7 +51,16 @@ properties: - const: apple,wdt reg: - maxItems: 1 + minItems: 1 + items: + - description: Watchdog timer registers + - description: Simple-reconfig routing register + + reg-names: + minItems: 1 + items: + - const: wdt + - const: reconfig clocks: maxItems: 1 @@ -69,5 +87,17 @@ examples: clocks = <&clk>; interrupts = ; }; + - | + #include + #include + + watchdog@8836c000 { + compatible = "apple,t6050-wdt", "apple,t8103-wdt"; + reg = <0x8836c000 0x4000>, + <0x8833002c 0x4>; + reg-names = "wdt", "reconfig"; + clocks = <&clk>; + interrupts = ; + }; ... From 9927b97fc39038785e6bb33c86510ffd90c3ddb6 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 01:32:52 -0800 Subject: [PATCH 0904/1514] soc: apple: sleep: hand off WD2 to apple_wdt and preserve T6050 reconfig across wake drivers/soc/apple/sleep.c uses WD2 as its suspend/resume safety net between apple_sleep_begin() and apple_sleep_end(). Once apple_wdt also drives WD2 on SoCs with a simple-reconfig routing register, the two drivers must coordinate ownership so apple_wdt_suspend() does not disarm sleep's 120 s safety net and apple_sleep_end() restores an active apple_wdt timer after clearing sleep's WD2 timer. Add a lock-protected WD2 handoff API in include/linux/soc/apple/sleep.h (with inline no-op stubs when CONFIG_APPLE_SOC_SLEEP=n): - apple_sleep_wdt_register(dev, wdt, restore, data) matches @wdt's resource start against available apple_sleep DT nodes' "wdt" regions regardless of probe order; watchdogs without a matching sleep node (such as J775D or a secondary die) return 0 without taking the slot, while a second device claiming the same block returns -EBUSY. - apple_sleep_wdt_active(dev) reports whether sleep currently owns WD2 for @dev so only that watchdog yields during [begin .. end]. - apple_sleep_end() clears WD2_CTL, invokes @restore while holding the handoff lock, and clears ownership. On T6050, apple,seq-commit-wdt writes 0x20 (sleep-commit routing) to wdt-aux + AON_WDT_SLEEP (0x2c) during commit without restoring it on wake. Bracket t6050_seq(T6050_SEQ_WDT) using struct apple_sleep's existing aon_wdt_saved/aon_wdt_marked fields (matching T8142): save wdt-aux + AON_WDT_SLEEP before commit, and in t6050_sleep_wake_regs() stop WD2, W1C-clear IRQ_STATUS with a readl() barrier, restore the saved routing word with a readl() barrier, and re-arm the 120 s wake net. Leave T8142's aon_wdt_sleep OR path unchanged (T8142 has no "reconfig" DT node in this series) and leave shared apple_sleep_set_wd2() unchanged (empirical J775D register checks confirm a stopped WD2 does not latch IRQ_STATUS past bark). Add isolated KUnit coverage for block matching, slot ownership, and .end ordering in sleep-test.c. Signed-off-by: Jeff Queisser --- drivers/soc/apple/sleep-t6050.h | 35 ++++++-- drivers/soc/apple/sleep-test.c | 131 ++++++++++++++++++++++++++++++ drivers/soc/apple/sleep.c | 138 ++++++++++++++++++++++++++++++-- include/linux/soc/apple/sleep.h | 28 +++++++ 4 files changed, 321 insertions(+), 11 deletions(-) diff --git a/drivers/soc/apple/sleep-t6050.h b/drivers/soc/apple/sleep-t6050.h index a4bf3fabcf375c..e57a42caa4e14a 100644 --- a/drivers/soc/apple/sleep-t6050.h +++ b/drivers/soc/apple/sleep-t6050.h @@ -3123,6 +3123,33 @@ static void t6050_clusters_down_first_report(struct apple_sleep *s) r->early_seq[1], r->early_us[1], r->early_ret[2]); } +static void t6050_sleep_commit_wdt(struct apple_sleep *s) +{ + struct apple_sleep_region_state *r = s->region; + + if (r && r->seq[T6050_SEQ_WDT].n) { + s->aon_wdt_saved = readl(s->wdt_aux + AON_WDT_SLEEP); + s->aon_wdt_marked = true; + } + t6050_seq(s, T6050_SEQ_WDT); + writel(0, s->wdt + WDT_WD0_CTL); + apple_sleep_set_wd2(s, T6050_WDT_COMMIT_SECS); + writel(0, s->wdt_aux + AON_AP_DEADLINE); +} + +static void t6050_sleep_wake_wdt(struct apple_sleep *s) +{ + writel(0, s->wdt + WDT_WD2_CTL); + writel(WDT_WD2_CTL_IRQ_STATUS, s->wdt + WDT_WD2_CTL); + (void)readl(s->wdt + WDT_WD2_CTL); + if (s->aon_wdt_marked) { + writel(s->aon_wdt_saved, s->wdt_aux + AON_WDT_SLEEP); + (void)readl(s->wdt_aux + AON_WDT_SLEEP); + s->aon_wdt_marked = false; + } + apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); +} + /* * The commit window, each step at the DT schedule's time before the sleep timer: the MCC * requests released, the storage link's PHY parked and its words down, the watchdogs, the @@ -3175,10 +3202,7 @@ static void t6050_sleep_commit_regs(struct apple_sleep *s) } } t6050_step(s, T6050_STEP_WDT); - t6050_seq(s, T6050_SEQ_WDT); - writel(0, s->wdt + WDT_WD0_CTL); - apple_sleep_set_wd2(s, T6050_WDT_COMMIT_SECS); - writel(0, s->wdt_aux + 8); + t6050_sleep_commit_wdt(s); /* The memory floor's voter to 0, not read */ t6050_step(s, T6050_STEP_FLOOR); s->region->floor_changed |= BIT(1); @@ -3796,8 +3820,7 @@ static void t6050_sleep_wake_regs(struct apple_sleep *s) r->gfx_aic[2] = readl(r->aic_gfx + 0x14); } /* The complexes' requests back, in macOS's early wake order */ - writel(0, s->wdt + WDT_WD2_CTL); - apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); + t6050_sleep_wake_wdt(s); for (i = 0; i < 3; i++) writel(r->cluster_saved[i], s->cluster + 4 * i); writel(PWRGATE_ON, s->pwrgate); diff --git a/drivers/soc/apple/sleep-test.c b/drivers/soc/apple/sleep-test.c index fff01f6447e5ad..56df6219d56776 100644 --- a/drivers/soc/apple/sleep-test.c +++ b/drivers/soc/apple/sleep-test.c @@ -364,6 +364,136 @@ static void apple_sleep_test_region_rejects_bad_inventory(struct kunit *test) KUNIT_EXPECT_EQ(test, sleep_region_validate(&p), -EINVAL); } +struct apple_sleep_test_wdt_saved { + struct device *dev; + void (*restore)(void *data); + void *data; + bool owned; +}; + +struct apple_sleep_test_wdt_ctx { + u32 *wdt_regs; + int calls; + u32 ctl_at_restore; + bool owned_at_restore; +}; + +struct apple_sleep_test_wdt_state { + struct device dev1; + struct device dev2; + u32 fake_wdt[16]; + struct apple_sleep_test_wdt_saved saved; +}; + +static void apple_sleep_test_wdt_restore_global(void *data) +{ + struct apple_sleep_test_wdt_saved *saved = data; + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wdt_dev = saved->dev; + apple_sleep_wdt_restore = saved->restore; + apple_sleep_wdt_data = saved->data; + apple_sleep_wd2_owned = saved->owned; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} + +static void apple_sleep_test_wdt_restore_cb(void *data) +{ + struct apple_sleep_test_wdt_ctx *ctx = data; + + ctx->calls++; + ctx->ctl_at_restore = ctx->wdt_regs[WDT_WD2_CTL / 4]; + ctx->owned_at_restore = apple_sleep_wd2_owned; +} + +static void apple_sleep_test_wdt_handoff(struct kunit *test) +{ + struct resource t6050_sleep_wdt = DEFINE_RES_MEM(0x28836c000ULL, 0x4000); + struct resource t6050_dev_wdt = DEFINE_RES_MEM(0x28836c000ULL, 0x4000); + struct resource t8142_sleep_wdt = DEFINE_RES_MEM(0x23d2b0000ULL, 0x30); + struct resource t8142_dev_wdt = DEFINE_RES_MEM(0x23d2b0000ULL, 0x4000); + struct resource die1_wdt = DEFINE_RES_MEM(0x228836c000ULL, 0x4000); + struct apple_sleep_test_wdt_state *st; + struct apple_sleep_test_wdt_ctx ctx; + unsigned long flags; + + st = kunit_kzalloc(test, sizeof(*st), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, st); + + /* Isolate global handoff state so a probed apple_wdt on J714S/J716C is untouched. */ + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + st->saved.dev = apple_sleep_wdt_dev; + st->saved.restore = apple_sleep_wdt_restore; + st->saved.data = apple_sleep_wdt_data; + st->saved.owned = apple_sleep_wd2_owned; + apple_sleep_wdt_dev = NULL; + apple_sleep_wdt_restore = NULL; + apple_sleep_wdt_data = NULL; + apple_sleep_wd2_owned = false; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + KUNIT_ASSERT_EQ(test, + kunit_add_action_or_reset(test, apple_sleep_test_wdt_restore_global, + &st->saved), 0); + + ctx = (struct apple_sleep_test_wdt_ctx){ .wdt_regs = st->fake_wdt }; + + /* Block matching compares resource start across differing map sizes. */ + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, &t6050_dev_wdt)); + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_same_block(&t8142_sleep_wdt, &t8142_dev_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, &die1_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(NULL, &t6050_dev_wdt)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_same_block(&t6050_sleep_wdt, NULL)); + + /* Invalid arguments and unmatched watchdogs. */ + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(NULL, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev1, true, NULL, &ctx), + -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, false, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev2)); + + /* Matching watchdog claims the single slot; a second claiming it gets -EBUSY. */ + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev1, true, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EBUSY); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, false, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev1)); + + /* Ownership applies only to the registered watchdog; .end orders CTL=0, restore, clear. */ + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wd2_owned = true; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + KUNIT_EXPECT_TRUE(test, apple_sleep_wdt_active(&st->dev1)); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev2)); + + st->fake_wdt[WDT_WD2_CTL / 4] = 1; + apple_sleep_wdt_end((void __iomem __force *)st->fake_wdt); + KUNIT_EXPECT_EQ(test, ctx.calls, 1); + KUNIT_EXPECT_EQ(test, ctx.ctl_at_restore, 0u); + KUNIT_EXPECT_TRUE(test, ctx.owned_at_restore); + KUNIT_EXPECT_FALSE(test, apple_sleep_wdt_active(&st->dev1)); + + /* Unregistering a non-holder leaves the slot intact; unregistering the holder frees it. */ + apple_sleep_wdt_unregister(&st->dev2); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), -EBUSY); + apple_sleep_wdt_unregister(&st->dev1); + KUNIT_EXPECT_EQ(test, apple_sleep_wdt_register_matched(&st->dev2, true, + apple_sleep_test_wdt_restore_cb, + &ctx), 0); + apple_sleep_wdt_unregister(&st->dev2); +} + static struct kunit_case apple_sleep_test_cases[] = { KUNIT_CASE(apple_sleep_test_layout), KUNIT_CASE(apple_sleep_test_t6050), @@ -377,6 +507,7 @@ static struct kunit_case apple_sleep_test_cases[] = { KUNIT_CASE(apple_sleep_test_words), KUNIT_CASE(apple_sleep_test_books), KUNIT_CASE(apple_sleep_test_wake_names), + KUNIT_CASE(apple_sleep_test_wdt_handoff), {} }; diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9cee856626f918..bfad9de85080b8 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -140,6 +140,7 @@ struct aura_s2r_mailbox { #define WDT_WD2_COUNT 0x20 #define WDT_WD2_ALARM 0x28 #define WDT_WD2_CTL 0x2c +#define WDT_WD2_CTL_IRQ_STATUS BIT(1) #define WDT_TICKS_PER_S 24000000 /* The sleep's own safety net: ADT /arm-io/wdt simple-reconfig-wdog-icc-time. */ #define WDT_SLEEP_SECS 5 @@ -148,9 +149,10 @@ struct aura_s2r_mailbox { #define AON_AP_DEADLINE 0x08 /* - * T8142: a word of the watchdog's second page (/arm-io/wdt + 0x802c). macOS's entry - * read-modify-writes it from 0 to 0x20 right before WD0's control and WD2 (26B131 trace, - * 11.1 ms before the S2R timer); XNU writes 0x10 there during boot. Meaning unknown. + * Simple-reconfig WD2 routing word (bits 5:4: 01 = run-time cold reset, 10 = sleep-commit + * routing). Lives at wdt-aux + 0x2c on T6050 and aon-misc + 0x2c (/arm-io/wdt + 0x802c) on + * T8142; sleep saves it before commit (T6050 DT sequence writes 0x20, T8142 ORs 0x20) and + * restores the saved value on wake. */ #define AON_WDT_SLEEP 0x2c @@ -1860,6 +1862,125 @@ void apple_sleep_smc_unregister(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_smc_unregister); +static const struct of_device_id apple_sleep_of_match[]; + +static DEFINE_SPINLOCK(apple_sleep_wdt_lock); +static struct device *apple_sleep_wdt_dev; +static void (*apple_sleep_wdt_restore)(void *data); +static void *apple_sleep_wdt_data; +static bool apple_sleep_wd2_owned; + +static bool apple_sleep_wdt_same_block(const struct resource *sleep_wdt, + const struct resource *wdt) +{ + if (!sleep_wdt || !wdt) + return false; + return sleep_wdt->start == wdt->start; +} + +static bool apple_sleep_dt_owns_wdt(const struct resource *wdt) +{ + struct device_node *np = NULL; + bool found = false; + + if (!wdt) + return false; + + for_each_matching_node(np, apple_sleep_of_match) { + struct resource res; + int idx; + + if (!of_device_is_available(np)) + continue; + idx = of_property_match_string(np, "reg-names", "wdt"); + if (idx < 0 || of_address_to_resource(np, idx, &res)) + continue; + if (apple_sleep_wdt_same_block(&res, wdt)) { + found = true; + of_node_put(np); + break; + } + } + + return found; +} + +static int apple_sleep_wdt_register_matched(struct device *dev, bool matched, + void (*restore)(void *data), void *data) +{ + unsigned long flags; + + if (!dev || !restore) + return -EINVAL; + if (!matched) + return 0; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + if (apple_sleep_wdt_dev && apple_sleep_wdt_dev != dev) { + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + return -EBUSY; + } + apple_sleep_wdt_dev = dev; + apple_sleep_wdt_restore = restore; + apple_sleep_wdt_data = data; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + + return 0; +} + +int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data) +{ + if (!dev || !wdt || !restore) + return -EINVAL; + + return apple_sleep_wdt_register_matched(dev, apple_sleep_dt_owns_wdt(wdt), + restore, data); +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_register); + +void apple_sleep_wdt_unregister(struct device *dev) +{ + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + if (apple_sleep_wdt_dev == dev) { + apple_sleep_wdt_dev = NULL; + apple_sleep_wdt_restore = NULL; + apple_sleep_wdt_data = NULL; + } + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_unregister); + +bool apple_sleep_wdt_active(struct device *dev) +{ + unsigned long flags; + bool active; + + if (!dev) + return false; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + active = apple_sleep_wd2_owned && apple_sleep_wdt_dev == dev; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + + return active; +} +EXPORT_SYMBOL_GPL(apple_sleep_wdt_active); + +static void apple_sleep_wdt_end(void __iomem *wdt) +{ + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + writel(0, wdt + WDT_WD2_CTL); + if (apple_sleep_wdt_restore) + apple_sleep_wdt_restore(apple_sleep_wdt_data); + apple_sleep_wd2_owned = false; + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); +} + void apple_sleep_display_quiesced(struct device *dev, bool quiesced) { struct apple_sleep *s = apple_sleep; @@ -6462,7 +6583,14 @@ static int apple_sleep_begin(suspend_state_t state) apple_sleep->smc_woke_alone = false; sleep_pins_save(apple_sleep); } - apple_sleep_set_wd2(apple_sleep, WDT_SUSPEND_SECS); + { + unsigned long flags; + + spin_lock_irqsave(&apple_sleep_wdt_lock, flags); + apple_sleep_wd2_owned = true; + apple_sleep_set_wd2(apple_sleep, WDT_SUSPEND_SECS); + spin_unlock_irqrestore(&apple_sleep_wdt_lock, flags); + } pm_set_suspend_via_firmware(); sleep_ans_late_open(); @@ -6480,7 +6608,7 @@ static void apple_sleep_end(void) if (pm_suspend_via_firmware() && apple_sleep->soc->ops->pmu_wake) apple_sleep->soc->ops->pmu_wake(apple_sleep); if (pm_suspend_via_firmware()) - writel(0, apple_sleep->wdt + WDT_WD2_CTL); + apple_sleep_wdt_end(apple_sleep->wdt); } /* diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index db4337d663b818..5ae87fdff0f9d9 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -13,6 +13,7 @@ struct device; struct device_node; +struct resource; /* The SMC's sleep messages: the pmVC value and the spacings between them, used as floors */ struct apple_sleep_smc_policy { @@ -256,6 +257,18 @@ void apple_sleep_restore_pins(void); * sleep engine's PMGR reset of its own domains, its DARTs kept. The caller starts it after. */ int apple_sleep_engine_reset(struct device *dev); + +/* + * Watchdog handoff over a firmware-driven suspend. Between .begin and .end the + * sleep driver owns WD2 as its suspend/resume safety net; at .end it clears WD2 + * and invokes @restore so a watchdog driver sharing that WD2 block can re-arm + * its active timer. Registration matches @wdt against any available sleep node's + * "wdt" region; watchdogs without a matching sleep node return 0 without registering. + */ +int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data); +void apple_sleep_wdt_unregister(struct device *dev); +bool apple_sleep_wdt_active(struct device *dev); #else static inline const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void) { return NULL; } static inline bool apple_sleep_smc_defer_notice(void) { return false; } @@ -463,6 +476,21 @@ static inline int apple_sleep_engine_reset(struct device *dev) { return -EOPNOTSUPP; } + +static inline int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *data), void *data) +{ + return 0; +} + +static inline void apple_sleep_wdt_unregister(struct device *dev) +{ +} + +static inline bool apple_sleep_wdt_active(struct device *dev) +{ + return false; +} #endif #endif From 3ac087a572e9d4ceaed8cd3ab269cf452a1de1c3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:42:29 +1100 Subject: [PATCH 0905/1514] dt-bindings: soc: apple: add standalone CLPC binding Add a Device Tree binding for standalone Apple SoC CLPC nodes on chips that do not have a PMC voter block (such as T8112). These nodes expose platform profiles (low-power, balanced, performance) through the shared apple-clpc driver, optionally referencing the SMC for package power readings or High Power mode. Signed-off-by: Ryan Murray --- .../bindings/soc/apple/apple,clpc.yaml | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml diff --git a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml new file mode 100644 index 00000000000000..064f8e7beac5b9 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,clpc.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple SoC host performance controller (standalone) + +maintainers: + - Ryan Murray + +description: + Platform-profile provider for Apple SoCs whose host performance controller + (CLPC) does not sit under a PMC voter block (apple,pmc.yaml). Exposes + low-power, balanced and performance platform profiles and enforces CPU + frequency ceilings (and optional SMC package power targets or High Power + mode) through the shared apple-clpc driver. + +properties: + compatible: + oneOf: + - items: + - enum: + - apple,t8112-clpc + - const: apple,clpc + - const: apple,clpc + + apple,smc: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The SMC, whose package power reading (PHPC) the low-power platform + profile can monitor or target, and which the performance profile tells + about High Power mode on Macs that have it. + + apple,high-power-mode: + type: boolean + description: + The machine has High Power mode, the fan and power headroom macOS + offers on some MacBook Pros. The performance platform profile then + tells the SMC (apple,smc) that it is on. + + apple,low-power-frequency-max-mhz: + description: + The machine's CPU frequency ceiling in macOS's Low Power mode, in + MHz, as the ADT's cpu-low-power-frequency-max has it. The low-power + platform profile holds the CPU clusters to it, up to the next + frequency of their tables. When absent, the driver derives a ceiling + from the fastest CPU cluster's operating points. + + apple,low-power-mw: + $ref: /schemas/types.yaml#/definitions/uint32 + description: + Optional package power target in milliwatts (measured from SMC PHPC) + for the low-power platform profile. + +required: + - compatible + +additionalProperties: false + +examples: + - | + performance-controller { + compatible = "apple,t8112-clpc", "apple,clpc"; + apple,smc = <&smc>; + }; From 22a4d124edb228b73b061f5a1e75d1835a59de62 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:42:29 +1100 Subject: [PATCH 0906/1514] soc: apple: clpc: support standalone platform-profile nodes without PMC Apple T8112 (M2) has no PMC voter block, so apple-clpc currently refuses to probe and leaves /sys/class/platform-profile empty. On Fedora/GNOME systems using power-profiles-daemon this forces fallback to the two-mode placeholder driver (no performance profile, no CPU limits). Extend the existing apple-clpc driver as one shared implementation: - Allow probing without a PMC parent when a platform profile is available, skipping PMC voter registration/floor updates and avoiding periodic polling when idle outside low-power mode. - Add a generic "apple,clpc" match entry that derives a low-power CPU ceiling from the fastest cluster's operating points (64%, rounded down to a valid OPP, leaving slower clusters uncapped) whenever neither the DT (apple,low-power-frequency-max-mhz) nor a SoC table sets an explicit ceiling. Explicit DT/table ceilings keep the existing round-up rule. - Apply profile ceilings synchronously in apple_clpc_profile_set() and wake on CPUFREQ_CREATE_POLICY so userspace observes changes immediately. - Support optional DT apple,low-power-mw and make APPLE_PMC optional in Kconfig. - Add KUnit coverage for explicit round-up, generic T8112 OPP derivation, and platform-profile ops transitions. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 6 +- drivers/soc/apple/clpc.c | 738 +++++++++++++++++++++++++++----------- 2 files changed, 523 insertions(+), 221 deletions(-) diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 8dc9384bdc5d11..f5ac320f2fbe64 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -345,7 +345,7 @@ config APPLE_REGVIEW config APPLE_CLPC tristate "Apple host performance controller floors" depends on ARCH_APPLE || COMPILE_TEST - depends on APPLE_PMC && CPU_FREQ + depends on (APPLE_PMC || !APPLE_PMC) && CPU_FREQ depends on MFD_MACSMC || !MFD_MACSMC select ACPI_PLATFORM_PROFILE if ACPI default ARCH_APPLE @@ -353,9 +353,9 @@ config APPLE_CLPC Raises the DRAM controller and SoC fabric performance floors of the host's PMC voter agent while CPU clusters are busy, and releases them at idle. On SoCs with power modes it also offers them as - platform profiles. + platform profiles (with or without a PMC parent). - Say 'y' or 'm' here if you have an Apple SoC with a PMC. + Say 'y' or 'm' here if you have an Apple SoC. config APPLE_DISPLAY_GATE bool "Apple internal display enable gate" diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 3e786e7cf1c39d..c1a7d51cfdfce1 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -68,6 +68,13 @@ enum apple_clpc_rail { #define APPLE_CLPC_GPU_BACKOFF_MS 100 /* Package power readings in the low-power profile: every 100 ms */ #define APPLE_CLPC_POWER_MS 100 +/* + * Policy fraction of the fastest CPU cluster's maximum frequency used as the + * low-power platform-profile ceiling when neither the DT nor the SoC table + * supplies an explicit frequency (matches macOS Low Power Mode's ~64% P-core + * ceiling). + */ +#define APPLE_CLPC_LOW_POWER_PCT 64 /* Why the last vote was cast, for debugfs */ #define APPLE_CLPC_REASON_CPU BIT(0) @@ -122,7 +129,10 @@ enum apple_clpc_rail { * from a deferrable timer * @low_power_khz: CPU frequency ceiling of the low-power platform profile, * taken up to the next table frequency, for a node without - * apple,low-power-frequency-max-mhz; 0 for no platform profile + * apple,low-power-frequency-max-mhz; 0 for none + * @auto_low_power: derive the low-power ceiling from the fastest CPU + * cluster's operating points (APPLE_CLPC_LOW_POWER_PCT) when neither DT + * nor @low_power_khz sets one * @low_power_mw: package power (the SMC's PHPC key) the low-power profile * holds the CPU clusters to; 0 for none * @high_power_machine: the machine compatible that had High Power mode from @@ -149,6 +159,7 @@ struct apple_clpc_hw { unsigned int ane_cluster_khz; const char *ane_cluster_machine; bool idle_on_time; + bool auto_low_power; unsigned int low_power_khz; unsigned int low_power_mw; const char *high_power_machine; @@ -258,10 +269,13 @@ struct apple_clpc { unsigned long gpu_streaming_samples; unsigned long gpu_dense_samples; /* The platform profile and, for its power target, the SMC */ + bool has_pmc; enum platform_profile_option profile; bool low_power; /* the DT ceiling, else hw->low_power_khz, else 0 */ unsigned int low_power_khz; + bool auto_low_power; + unsigned int low_power_mw; struct device_node *smc_np; struct apple_smc *smc; /* The performance profile is sent to the SMC as High Power mode */ @@ -594,7 +608,8 @@ static void apple_clpc_find_clusters(struct apple_clpc *clpc) cl = &clpc->clusters[i]; cpumask_set_cpu(cpu, cl->cpus); cpumask_set_cpu(cpu, clpc->covered); - clpc->idle[cpu] = get_cpu_idle_time(cpu, &clpc->wall[cpu], 0); + if (clpc->idle && clpc->wall) + clpc->idle[cpu] = get_cpu_idle_time(cpu, &clpc->wall[cpu], 0); } cpufreq_cpu_put(policy); } @@ -678,11 +693,30 @@ static u32 apple_clpc_floor(struct apple_clpc *clpc, const unsigned int *state) return floor; } +static inline bool apple_clpc_has_profile_ceiling(const struct apple_clpc *clpc) +{ + return clpc->low_power_khz || clpc->auto_low_power; +} + static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) { if (READ_ONCE(clpc->stopped)) return; + if (!clpc->has_pmc) { + unsigned long delay; + + cancel_delayed_work(&clpc->idle_work); + if (apple_clpc_has_profile_ceiling(clpc) && READ_ONCE(clpc->low_power)) + delay = msecs_to_jiffies(APPLE_CLPC_POWER_MS); + else if (!cpumask_equal(clpc->covered, cpu_possible_mask)) + delay = HZ; + else + return; + mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, delay); + return; + } + /* * A held vote has to be sampled on time so that it drops once demand * stops; with no vote held, sampling can wait for a CPU that wakes up @@ -881,6 +915,8 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, struct cpufreq_frequency_table *pos; unsigned int best = khz; + if (!policy->freq_table) + return khz; cpufreq_for_each_valid_entry(pos, policy->freq_table) { if (up ? pos->frequency > khz && (best == khz || pos->frequency < best) : pos->frequency < khz && (best == khz || pos->frequency > best)) @@ -889,6 +925,41 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, return best; } +/* + * The low-power platform-profile frequency ceiling for @policy: + * - when @low_power_khz is given (ADT/DT or SoC table), the first table + * frequency at or above @low_power_khz (matching macOS Low Power Mode's + * round-up on M4/M5), or policy max if the cluster is slower; + * - otherwise, when @auto_low_power is set, APPLE_CLPC_LOW_POWER_PCT of + * @max_cluster_khz rounded down to a table frequency on the fastest + * cluster(s), leaving slower clusters uncapped. + */ +static unsigned int apple_clpc_low_power_top_khz(struct cpufreq_policy *policy, + unsigned int low_power_khz, + bool auto_low_power, + unsigned int max_cluster_khz) +{ + unsigned int top; + + if (low_power_khz) { + top = apple_clpc_step_khz(policy, low_power_khz - 1, true); + if (top < low_power_khz) + top = policy->cpuinfo.max_freq; + return top; + } + if (auto_low_power && max_cluster_khz && + policy->cpuinfo.max_freq >= max_cluster_khz) { + unsigned int target = div_u64((u64)max_cluster_khz * + APPLE_CLPC_LOW_POWER_PCT, 100); + + top = apple_clpc_step_khz(policy, target + 1, false); + if (top > target) + top = policy->cpuinfo.min_freq ?: policy->cpuinfo.max_freq; + return top; + } + return policy->cpuinfo.max_freq; +} + /* * The SMC of the apple,smc phandle, once its driver is bound; NULL before. * Callers test IS_ENABLED(CONFIG_MFD_MACSMC) first, so a kernel without the @@ -946,52 +1017,60 @@ static bool apple_clpc_steps_first(unsigned int a_khz, unsigned int a_max, /* * The platform profile's ceilings. In the low-power profile every cluster - * stays at or below the first frequency at or above clpc->low_power_khz. Each - * new package power reading above hw->low_power_mw takes one table step off - * one cluster, and each one below 90% of it puts one back, in the order of + * stays at or below apple_clpc_low_power_top_khz(). When @low_power_mw is set, + * each new package power reading above it takes one table step off one + * cluster, and each one below 90% of it puts one back, in the order of * apple_clpc_steps_first(). Elsewhere there is no ceiling. */ static void apple_clpc_profile_limit(struct apple_clpc *clpc) { bool low = READ_ONCE(clpc->low_power); struct cpufreq_policy *policy[APPLE_CLPC_MAX_CLUSTERS] = {}; - unsigned int i, khz, pick_khz = 0; + unsigned int i, khz, pick_khz = 0, max_cluster_khz = 0; int mw, step = 0, pick = -1; - if (!clpc->low_power_khz || time_before(jiffies, clpc->power_next)) + if (!apple_clpc_has_profile_ceiling(clpc) || + time_before(jiffies, clpc->power_next)) return; clpc->power_next = jiffies + msecs_to_jiffies(APPLE_CLPC_POWER_MS); - if (low && clpc->hw->low_power_mw) { + if (low && clpc->smc_np) { mw = apple_clpc_read_power(clpc); clpc->power_reads++; /* The SMC updates the reading less often: act on a new one only. */ if (mw >= 0 && mw != clpc->power_mw) { clpc->power_updates++; - if (mw > (int)clpc->hw->low_power_mw) - step = -1; - else if (mw < (int)clpc->hw->low_power_mw * 9 / 10) - step = 1; + if (clpc->low_power_mw) { + if (mw > (int)clpc->low_power_mw) + step = -1; + else if (mw < (int)clpc->low_power_mw * 9 / 10) + step = 1; + } } clpc->power_mw = mw; } + for (i = 0; i < clpc->nr_clusters; i++) { + policy[i] = cpufreq_cpu_get(clpc->clusters[i].policy_cpu); + if (policy[i]) + max_cluster_khz = max(max_cluster_khz, + policy[i]->cpuinfo.max_freq); + } for (i = 0; i < clpc->nr_clusters; i++) { struct apple_clpc_cluster *cl = &clpc->clusters[i]; - policy[i] = cpufreq_cpu_get(cl->policy_cpu); if (!policy[i]) continue; if (!freq_qos_request_active(&cl->max_qos) && freq_qos_add_request(&policy[i]->constraints, &cl->max_qos, FREQ_QOS_MAX, FREQ_QOS_MAX_DEFAULT_VALUE) < 0) clpc->update_errors++; - /* The top: the first table frequency at or above clpc->low_power_khz */ - cl->top_khz = apple_clpc_step_khz(policy[i], - clpc->low_power_khz - 1, true); - if (cl->top_khz < clpc->low_power_khz) - cl->top_khz = policy[i]->cpuinfo.max_freq; + cl->top_khz = apple_clpc_low_power_top_khz(policy[i], + clpc->low_power_khz, + clpc->auto_low_power, + max_cluster_khz); if (!low) cl->max_khz = 0; - else if (!cl->max_khz) + else if (!cl->max_khz || !clpc->low_power_mw || + cl->max_khz > cl->top_khz) cl->max_khz = cl->top_khz; if (!step) continue; @@ -1023,71 +1102,73 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) static void apple_clpc_sample(struct apple_clpc *clpc) { unsigned int demand[APPLE_CLPC_RAILS] = {}; - unsigned int state[APPLE_CLPC_RAILS]; + unsigned int state[APPLE_CLPC_RAILS] = {}; unsigned long now = jiffies; unsigned int i, rail; - u32 reason = 0, floor; + u32 reason = 0, floor = 0; clpc->samples++; if (!cpumask_equal(clpc->covered, cpu_possible_mask) && - time_after_eq(now, clpc->next_scan)) { + (!clpc->has_pmc || time_after_eq(now, clpc->next_scan))) { apple_clpc_find_clusters(clpc); clpc->next_scan = now + HZ; } - for (i = 0; i < clpc->nr_clusters; i++) { - struct apple_clpc_cluster *cl = &clpc->clusters[i]; + if (clpc->has_pmc) { + for (i = 0; i < clpc->nr_clusters; i++) { + struct apple_clpc_cluster *cl = &clpc->clusters[i]; - apple_clpc_sample_cluster(clpc, cl); + apple_clpc_sample_cluster(clpc, cl); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + demand[rail] = max(demand[rail], cl->request[rail]); + } for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], cl->request[rail]); - } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (demand[rail]) - reason |= APPLE_CLPC_REASON_CPU; - if (apple_clpc_gpu_input_demand(clpc->hw, clpc->gpu, demand)) - reason |= APPLE_CLPC_REASON_HOST_GPU; - if (apple_clpc_ane_input_demand(clpc, demand)) - reason |= APPLE_CLPC_REASON_ANE; - apple_clpc_ane_cluster(clpc, reason & APPLE_CLPC_REASON_ANE, now); - if (clpc->gpu_pmgr) { - /* Both run every sample: each tracks state across samples. */ - bool late = time_after(now, clpc->gpu_sampled + - msecs_to_jiffies(2 * APPLE_CLPC_SAMPLE_MS)); - bool dense = apple_clpc_gpu_dense(clpc, late); - bool streaming = apple_clpc_gpu_streaming(clpc, now); - - if (streaming || dense) { - bool released = apple_clpc_gpu_limited(clpc, now); - - apple_clpc_gpu_floor_count(clpc, released); - if (!released) { - reason |= streaming ? APPLE_CLPC_REASON_STREAMING_GPU : - APPLE_CLPC_REASON_DENSE_GPU; - if (streaming) - clpc->gpu_streaming_samples++; - else - clpc->gpu_dense_samples++; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - demand[rail] = max(demand[rail], - clpc->hw->gpu[rail]); + if (demand[rail]) + reason |= APPLE_CLPC_REASON_CPU; + if (apple_clpc_gpu_input_demand(clpc->hw, clpc->gpu, demand)) + reason |= APPLE_CLPC_REASON_HOST_GPU; + if (apple_clpc_ane_input_demand(clpc, demand)) + reason |= APPLE_CLPC_REASON_ANE; + apple_clpc_ane_cluster(clpc, reason & APPLE_CLPC_REASON_ANE, now); + if (clpc->gpu_pmgr) { + /* Both run every sample: each tracks state across samples. */ + bool late = time_after(now, clpc->gpu_sampled + + msecs_to_jiffies(2 * APPLE_CLPC_SAMPLE_MS)); + bool dense = apple_clpc_gpu_dense(clpc, late); + bool streaming = apple_clpc_gpu_streaming(clpc, now); + + if (streaming || dense) { + bool released = apple_clpc_gpu_limited(clpc, now); + + apple_clpc_gpu_floor_count(clpc, released); + if (!released) { + reason |= streaming ? APPLE_CLPC_REASON_STREAMING_GPU : + APPLE_CLPC_REASON_DENSE_GPU; + if (streaming) + clpc->gpu_streaming_samples++; + else + clpc->gpu_dense_samples++; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + demand[rail] = max(demand[rail], + clpc->hw->gpu[rail]); + } } } - } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - state[rail] = apple_clpc_vote(&clpc->vote[rail], demand[rail], - now); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + state[rail] = apple_clpc_vote(&clpc->vote[rail], demand[rail], + now); - floor = apple_clpc_floor(clpc, state); - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (state[rail] > demand[rail]) - reason |= APPLE_CLPC_REASON_HOLD; - clpc->last_floor = floor; - clpc->last_reason = reason; - clpc->last_vote_ns = ktime_get_mono_fast_ns(); - if (apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, floor)) - clpc->update_errors++; + floor = apple_clpc_floor(clpc, state); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + if (state[rail] > demand[rail]) + reason |= APPLE_CLPC_REASON_HOLD; + clpc->last_floor = floor; + clpc->last_reason = reason; + clpc->last_vote_ns = ktime_get_mono_fast_ns(); + if (apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, floor)) + clpc->update_errors++; + } apple_clpc_profile_limit(clpc); @@ -1097,9 +1178,10 @@ static void apple_clpc_sample(struct apple_clpc *clpc) * ceiling (High Power only) has nothing to do there, so it stays * deferrable. */ - apple_clpc_queue(clpc, !apple_clpc_floor(clpc, state) && !clpc->gpu_on && + apple_clpc_queue(clpc, !floor && !clpc->gpu_on && !clpc->ane_qos_khz && - !(clpc->low_power_khz && READ_ONCE(clpc->low_power))); + !(apple_clpc_has_profile_ceiling(clpc) && + READ_ONCE(clpc->low_power))); } static void apple_clpc_run(struct apple_clpc *clpc) @@ -1125,20 +1207,22 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) struct apple_clpc *clpc = s->private; unsigned int i, rail; - seq_printf(s, "agent: %u floor: %#010x (saved %#010x)\n", clpc->agent, - apple_pmc_floor_read(clpc->pmc, clpc->agent), - clpc->saved_floor); - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - seq_printf(s, "%s: rail %u state %u enabled %u map %u,%u,%u,%u\n", - rail == APPLE_CLPC_DCS ? "dcs" : "soc", - clpc->hw->rail[rail], clpc->vote[rail].state, - apple_pmc_voter_enabled(clpc->pmc, clpc->agent, - clpc->hw->rail[rail]), - clpc->hw->map[rail][0], clpc->hw->map[rail][1], - clpc->hw->map[rail][2], clpc->hw->map[rail][3]); - seq_printf(s, "last_vote: %#x reason_bits %#x sampled_ns %llu (cpu=1 host_gpu=2 streaming_gpu=4 dense_gpu=8 hold=16 ane=32)\n", - READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), - READ_ONCE(clpc->last_vote_ns)); + if (clpc->has_pmc) { + seq_printf(s, "agent: %u floor: %#010x (saved %#010x)\n", clpc->agent, + apple_pmc_floor_read(clpc->pmc, clpc->agent), + clpc->saved_floor); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + seq_printf(s, "%s: rail %u state %u enabled %u map %u,%u,%u,%u\n", + rail == APPLE_CLPC_DCS ? "dcs" : "soc", + clpc->hw->rail[rail], clpc->vote[rail].state, + apple_pmc_voter_enabled(clpc->pmc, clpc->agent, + clpc->hw->rail[rail]), + clpc->hw->map[rail][0], clpc->hw->map[rail][1], + clpc->hw->map[rail][2], clpc->hw->map[rail][3]); + seq_printf(s, "last_vote: %#x reason_bits %#x sampled_ns %llu (cpu=1 host_gpu=2 streaming_gpu=4 dense_gpu=8 hold=16 ane=32)\n", + READ_ONCE(clpc->last_floor), READ_ONCE(clpc->last_reason), + READ_ONCE(clpc->last_vote_ns)); + } if (clpc->gpu) { struct apple_clpc_gpu *gpu = clpc->gpu; unsigned int busy, level; @@ -1178,7 +1262,7 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) } seq_printf(s, "samples: %lu update errors: %lu\n", clpc->samples, clpc->update_errors); - if (clpc->low_power_khz) { + if (apple_clpc_has_profile_ceiling(clpc)) { seq_printf(s, "profile: %s power %d mW (%lu new of %lu readings) ceilings (kHz):", clpc->profile == PLATFORM_PROFILE_LOW_POWER ? "low-power" : clpc->profile == PLATFORM_PROFILE_PERFORMANCE ? "performance" : @@ -1205,12 +1289,14 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) clpc->gpu_streaming_samples, clpc->gpu_dense_samples); seq_printf(s, "gpu read errors: %lu\n", clpc->gpu_read_errors); } - for (i = 0; i < clpc->nr_clusters; i++) - seq_printf(s, "cluster cpu%u: busy %u%% level %u%% -> dcs %u soc %u\n", - clpc->clusters[i].policy_cpu, clpc->clusters[i].busy, - clpc->clusters[i].level, - clpc->clusters[i].request[APPLE_CLPC_DCS], - clpc->clusters[i].request[APPLE_CLPC_SOC]); + if (clpc->has_pmc) { + for (i = 0; i < clpc->nr_clusters; i++) + seq_printf(s, "cluster cpu%u: busy %u%% level %u%% -> dcs %u soc %u\n", + clpc->clusters[i].policy_cpu, clpc->clusters[i].busy, + clpc->clusters[i].level, + clpc->clusters[i].request[APPLE_CLPC_DCS], + clpc->clusters[i].request[APPLE_CLPC_SOC]); + } return 0; } @@ -1297,8 +1383,9 @@ static void apple_clpc_halt(struct apple_clpc *clpc) cancel_delayed_work_sync(&clpc->work); cancel_delayed_work_sync(&clpc->idle_work); } - apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, - clpc->saved_floor); + if (clpc->has_pmc) + apple_pmc_floor_update(clpc->pmc, clpc->agent, clpc->mask, + clpc->saved_floor); for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) clpc->vote[rail].state = 0; if (clpc->ane_qos_khz && @@ -1339,7 +1426,6 @@ static void apple_clpc_stop(void *data) for (i = 0; i < clpc->nr_clusters; i++) if (freq_qos_request_active(&clpc->clusters[i].max_qos)) freq_qos_remove_request(&clpc->clusters[i].max_qos); - of_node_put(clpc->smc_np); apple_clpc_free_clusters(clpc); } @@ -1355,13 +1441,20 @@ static int apple_clpc_policy_notify(struct notifier_block *nb, unsigned long eve struct cpufreq_policy *policy = data; unsigned int i; + if (event == CPUFREQ_CREATE_POLICY) { + if (!READ_ONCE(clpc->stopped)) + mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, 0); + return NOTIFY_OK; + } if (event != CPUFREQ_REMOVE_POLICY) return NOTIFY_DONE; guard(mutex)(&clpc->sample_lock); for (i = 0; i < clpc->nr_clusters; i++) - if (cpumask_test_cpu(clpc->clusters[i].policy_cpu, policy->related_cpus) && - freq_qos_request_active(&clpc->clusters[i].max_qos)) - freq_qos_remove_request(&clpc->clusters[i].max_qos); + if (cpumask_test_cpu(clpc->clusters[i].policy_cpu, policy->related_cpus)) { + if (freq_qos_request_active(&clpc->clusters[i].max_qos)) + freq_qos_remove_request(&clpc->clusters[i].max_qos); + clpc->clusters[i].max_khz = 0; + } if (clpc->ane_cpu < 0 || !cpumask_test_cpu(clpc->ane_cpu, policy->related_cpus)) return NOTIFY_OK; if (freq_qos_request_active(&clpc->ane_qos)) @@ -1463,8 +1556,13 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti } WRITE_ONCE(clpc->profile, profile); WRITE_ONCE(clpc->low_power, profile == PLATFORM_PROFILE_LOW_POWER); - /* The next sample applies it. */ + /* Apply profile ceilings right away so userspace sees the change immediately. */ clpc->power_next = jiffies; + if (!READ_ONCE(clpc->stopped) && apple_clpc_has_profile_ceiling(clpc)) { + if (!cpumask_equal(clpc->covered, cpu_possible_mask)) + apple_clpc_find_clusters(clpc); + apple_clpc_profile_limit(clpc); + } mutex_unlock(&clpc->sample_lock); if (!READ_ONCE(clpc->stopped)) mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, 0); @@ -1586,14 +1684,21 @@ static const struct apple_clpc_hw *apple_clpc_dt_hw(struct device *dev, return hw; } +static void apple_clpc_put_smc_np(void *data) +{ + struct apple_clpc *clpc = data; + + of_node_put(clpc->smc_np); +} + static int apple_clpc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *gpu = NULL; struct apple_clpc *clpc; unsigned int rail, i; - bool high_power; - u32 mhz; + bool high_power, has_profile; + u32 mhz, mw; int ret; clpc = devm_kzalloc(dev, sizeof(*clpc), GFP_KERNEL); @@ -1605,82 +1710,148 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->hw = apple_clpc_dt_hw(dev, of_device_get_match_data(dev)); if (IS_ERR(clpc->hw)) return PTR_ERR(clpc->hw); - /* T6040 firmware keeps GFX powered for its whole lifetime. A separate - * host publication/idle input, not that supplier state, drives demand; - * the T8132 and M5 (T8142) GPU drivers report through the same input. - * On T8140 the same input counts submissions for dense light work. - */ - if (clpc->hw->gpu_input || clpc->hw->gpu_dense) { - clpc->gpu = kzalloc_obj(*clpc->gpu); - if (!clpc->gpu) - return -ENOMEM; - kref_init(&clpc->gpu->ref); - spin_lock_init(&clpc->gpu->lock); - ret = devm_add_action_or_reset(dev, apple_clpc_gpu_owner_put, clpc->gpu); - if (ret) - return ret; - } - if (clpc->hw->ane[APPLE_CLPC_DCS] || clpc->hw->ane[APPLE_CLPC_SOC]) { - clpc->ane = kzalloc_obj(*clpc->ane); - if (!clpc->ane) - return -ENOMEM; - kref_init(&clpc->ane->ref); - spin_lock_init(&clpc->ane->lock); - ret = devm_add_action_or_reset(dev, apple_clpc_ane_owner_put, clpc->ane); - if (ret) - return ret; - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - clpc->ane_states[rail] = clpc->hw->ane[rail]; - } + + clpc->has_pmc = clpc->pmc && apple_pmc_rail_count(clpc->pmc) > 0; clpc->ane_cpu = -ENODEV; clpc->ane_until = jiffies; - if (clpc->ane && clpc->hw->ane_cluster_khz && - of_machine_is_compatible(clpc->hw->ane_cluster_machine)) { - clpc->ane_cpu = apple_clpc_cluster_cpu(clpc->hw->ane_cluster); - if (clpc->ane_cpu >= 0) { - clpc->policy_nb.notifier_call = apple_clpc_policy_notify; - if (!cpufreq_register_notifier(&clpc->policy_nb, - CPUFREQ_POLICY_NOTIFIER)) { - clpc->policy_nb_added = true; - clpc->ane_cluster_khz = clpc->hw->ane_cluster_khz; + + /* + * The boot loader copies the ADT's Low Power mode CPU ceiling + * (pmgr/clpc cpu-low-power-frequency-max) into the node. Without it, + * a SoC's own value applies where it has one, or the generic + * operating-point ceiling when auto_low_power is enabled. + */ + if (!of_property_read_u32(dev->of_node, "apple,low-power-frequency-max-mhz", &mhz)) + clpc->low_power_khz = mhz * 1000; + else + clpc->low_power_khz = clpc->hw->low_power_khz; + if (!clpc->low_power_khz && clpc->hw->auto_low_power) + clpc->auto_low_power = true; + if (!of_property_read_u32(dev->of_node, "apple,low-power-mw", &mw)) + clpc->low_power_mw = mw; + else + clpc->low_power_mw = clpc->hw->low_power_mw; + /* + * The board DT says whether the machine has High Power mode: then the + * performance profile tells the SMC that it is on (the zETM record). + * A machine with High Power mode and no low-power ceiling still gets + * the platform profile, named "apple-smc" so that userspace keeps its + * own low-power CPU budget. + */ + high_power = of_property_read_bool(dev->of_node, "apple,high-power-mode"); + /* + * A DTB from before the property (the ESP copy can lag the kernel) + * keeps High Power mode where this table already gave it. + */ + if (!high_power && clpc->hw->high_power_machine) + high_power = of_machine_is_compatible(clpc->hw->high_power_machine); + if ((apple_clpc_has_profile_ceiling(clpc) || high_power) && + IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + /* + * The SMC is optional: without it (no apple,smc phandle, or a + * kernel without the SMC driver) the low-power profile has only + * its ceiling and there is no High Power mode. + */ + if (IS_ENABLED(CONFIG_MFD_MACSMC)) { + clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); + if (clpc->smc_np) { + ret = devm_add_action_or_reset(dev, apple_clpc_put_smc_np, clpc); + if (ret) + return ret; } } - if (!clpc->ane_cluster_khz) - dev_dbg(dev, "no ANE cluster floor (cpu-map cluster%u)\n", - clpc->hw->ane_cluster); + clpc->high_power = clpc->smc_np && high_power; } - /* The property is optional: without it, CPU demand alone sets the floors. */ - if (clpc->hw->gpu_demand) - gpu = of_parse_phandle(dev->of_node, "apple,gpu-power-state", 0); - if (gpu) { - ret = of_property_read_u32(gpu, "reg", &clpc->gpu_offset); - clpc->gpu_pmgr = syscon_node_to_regmap(gpu->parent); - of_node_put(gpu); + /* High Power mode alone needs the SMC; without it there is no profile. */ + has_profile = (apple_clpc_has_profile_ceiling(clpc) || clpc->high_power) && + IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE); + if (!clpc->has_pmc && !has_profile) + return dev_err_probe(dev, -ENODEV, + "parent is not a PMC and no platform profile is available\n"); + + if (clpc->has_pmc) { + /* T6040 firmware keeps GFX powered for its whole lifetime. A separate + * host publication/idle input, not that supplier state, drives demand; + * the T8132 and M5 (T8142) GPU drivers report through the same input. + * On T8140 the same input counts submissions for dense light work. + */ + if (clpc->hw->gpu_input || clpc->hw->gpu_dense) { + clpc->gpu = kzalloc_obj(*clpc->gpu); + if (!clpc->gpu) + return -ENOMEM; + kref_init(&clpc->gpu->ref); + spin_lock_init(&clpc->gpu->lock); + ret = devm_add_action_or_reset(dev, apple_clpc_gpu_owner_put, clpc->gpu); + if (ret) + return ret; + } + if (clpc->hw->ane[APPLE_CLPC_DCS] || clpc->hw->ane[APPLE_CLPC_SOC]) { + clpc->ane = kzalloc_obj(*clpc->ane); + if (!clpc->ane) + return -ENOMEM; + kref_init(&clpc->ane->ref); + spin_lock_init(&clpc->ane->lock); + ret = devm_add_action_or_reset(dev, apple_clpc_ane_owner_put, clpc->ane); + if (ret) + return ret; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + clpc->ane_states[rail] = clpc->hw->ane[rail]; + } + if (clpc->ane && clpc->hw->ane_cluster_khz && + of_machine_is_compatible(clpc->hw->ane_cluster_machine)) { + clpc->ane_cpu = apple_clpc_cluster_cpu(clpc->hw->ane_cluster); + if (clpc->ane_cpu >= 0) { + clpc->policy_nb.notifier_call = apple_clpc_policy_notify; + if (!cpufreq_register_notifier(&clpc->policy_nb, + CPUFREQ_POLICY_NOTIFIER)) { + clpc->policy_nb_added = true; + clpc->ane_cluster_khz = clpc->hw->ane_cluster_khz; + } + } + if (!clpc->ane_cluster_khz) + dev_dbg(dev, "no ANE cluster floor (cpu-map cluster%u)\n", + clpc->hw->ane_cluster); + } + /* The property is optional: without it, CPU demand alone sets the floors. */ + if (clpc->hw->gpu_demand) + gpu = of_parse_phandle(dev->of_node, "apple,gpu-power-state", 0); + if (gpu) { + ret = of_property_read_u32(gpu, "reg", &clpc->gpu_offset); + clpc->gpu_pmgr = syscon_node_to_regmap(gpu->parent); + of_node_put(gpu); + if (ret) + return dev_err_probe(dev, ret, "graphics power state has no reg\n"); + if (IS_ERR(clpc->gpu_pmgr)) + return dev_err_probe(dev, PTR_ERR(clpc->gpu_pmgr), + "no regmap for the graphics power state\n"); + } + + ret = of_property_read_u32(dev->of_node, "reg", &clpc->agent); if (ret) - return dev_err_probe(dev, ret, "graphics power state has no reg\n"); - if (IS_ERR(clpc->gpu_pmgr)) - return dev_err_probe(dev, PTR_ERR(clpc->gpu_pmgr), - "no regmap for the graphics power state\n"); - } - if (!apple_pmc_rail_count(clpc->pmc)) - return dev_err_probe(dev, -ENODEV, "parent is not a PMC\n"); + return dev_err_probe(dev, ret, "missing voter agent\n"); - ret = of_property_read_u32(dev->of_node, "reg", &clpc->agent); - if (ret) - return dev_err_probe(dev, ret, "missing voter agent\n"); + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { + if (clpc->hw->rail[rail] >= apple_pmc_rail_count(clpc->pmc)) + return -EINVAL; + clpc->mask |= APPLE_PMC_RAIL_MASK(clpc->hw->rail[rail]); + } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) { - if (clpc->hw->rail[rail] >= apple_pmc_rail_count(clpc->pmc)) - return -EINVAL; - clpc->mask |= APPLE_PMC_RAIL_MASK(clpc->hw->rail[rail]); - } + clpc->idle = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->idle), + GFP_KERNEL); + clpc->wall = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->wall), + GFP_KERNEL); + if (!clpc->idle || !clpc->wall) + return -ENOMEM; - clpc->idle = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->idle), - GFP_KERNEL); - clpc->wall = devm_kcalloc(dev, nr_cpu_ids, sizeof(*clpc->wall), - GFP_KERNEL); - if (!clpc->idle || !clpc->wall) - return -ENOMEM; + for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) + if (!apple_pmc_voter_enabled(clpc->pmc, clpc->agent, + clpc->hw->rail[rail])) + dev_warn(dev, "voter agent %u is not enabled on rail %u\n", + clpc->agent, clpc->hw->rail[rail]); + + clpc->saved_floor = apple_pmc_floor_read(clpc->pmc, clpc->agent) & + clpc->mask; + } for (i = 0; i < APPLE_CLPC_MAX_CLUSTERS; i++) { if (!zalloc_cpumask_var(&clpc->clusters[i].cpus, GFP_KERNEL)) { @@ -1693,14 +1864,6 @@ static int apple_clpc_probe(struct platform_device *pdev) return -ENOMEM; } - for (rail = 0; rail < APPLE_CLPC_RAILS; rail++) - if (!apple_pmc_voter_enabled(clpc->pmc, clpc->agent, - clpc->hw->rail[rail])) - dev_warn(dev, "voter agent %u is not enabled on rail %u\n", - clpc->agent, clpc->hw->rail[rail]); - - clpc->saved_floor = apple_pmc_floor_read(clpc->pmc, clpc->agent) & - clpc->mask; apple_clpc_find_clusters(clpc); clpc->next_scan = jiffies + HZ; mutex_init(&clpc->sample_lock); @@ -1733,45 +1896,10 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->profile = PLATFORM_PROFILE_BALANCED; clpc->power_next = jiffies; - /* - * The boot loader copies the ADT's Low Power mode CPU ceiling - * (pmgr/clpc cpu-low-power-frequency-max) into the node. Without it, - * a SoC's own value applies where it has one. - */ - if (!of_property_read_u32(dev->of_node, "apple,low-power-frequency-max-mhz", &mhz)) - clpc->low_power_khz = mhz * 1000; - else - clpc->low_power_khz = clpc->hw->low_power_khz; - /* - * The board DT says whether the machine has High Power mode: then the - * performance profile tells the SMC that it is on (the zETM record). - * A machine with High Power mode and no low-power ceiling still gets - * the platform profile, named "apple-smc" so that userspace keeps its - * own low-power CPU budget. - */ - high_power = of_property_read_bool(dev->of_node, "apple,high-power-mode"); - /* - * A DTB from before the property (the ESP copy can lag the kernel) - * keeps High Power mode where this table already gave it. - */ - if (!high_power && clpc->hw->high_power_machine) - high_power = of_machine_is_compatible(clpc->hw->high_power_machine); - if ((clpc->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { - /* - * The SMC is optional: without it (no apple,smc phandle, or a - * kernel without the SMC driver) the low-power profile has only - * its ceiling and there is no High Power mode. - */ - if (IS_ENABLED(CONFIG_MFD_MACSMC)) - clpc->smc_np = of_parse_phandle(dev->of_node, "apple,smc", 0); - clpc->high_power = clpc->smc_np && high_power; - } - /* High Power mode alone needs the SMC; without it there is no profile. */ - if ((clpc->low_power_khz || clpc->high_power) && - IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { + if (has_profile) { struct device *ppdev; - if (clpc->low_power_khz && !clpc->policy_nb_added) { + if (apple_clpc_has_profile_ceiling(clpc) && !clpc->policy_nb_added) { clpc->policy_nb.notifier_call = apple_clpc_policy_notify; clpc->policy_nb_added = !cpufreq_register_notifier(&clpc->policy_nb, CPUFREQ_POLICY_NOTIFIER); @@ -1780,10 +1908,15 @@ static int apple_clpc_probe(struct platform_device *pdev) * "apple-clpc" budgets the low-power profile itself; "apple-smc" * only carries High Power mode, and userspace keeps the CPU budget. */ - ppdev = devm_platform_profile_register(dev, clpc->low_power_khz ? "apple-clpc" : - "apple-smc", clpc, &apple_clpc_profile_ops); - if (IS_ERR(ppdev)) + ppdev = devm_platform_profile_register(dev, + apple_clpc_has_profile_ceiling(clpc) ? + "apple-clpc" : "apple-smc", + clpc, &apple_clpc_profile_ops); + if (IS_ERR(ppdev)) { + if (!clpc->has_pmc) + return PTR_ERR(ppdev); dev_warn(dev, "no platform profile: %pe\n", ppdev); + } } mutex_lock(&apple_clpc_clients_lock); @@ -1809,8 +1942,10 @@ static int apple_clpc_resume(struct device *dev) struct apple_clpc *clpc = dev_get_drvdata(dev); unsigned int cpu; - for_each_possible_cpu(cpu) - clpc->wall[cpu] = 0; + if (clpc->wall) + for_each_possible_cpu(cpu) + clpc->wall[cpu] = 0; + clpc->power_next = jiffies; WRITE_ONCE(clpc->stopped, false); apple_clpc_queue(clpc, true); return 0; @@ -2005,6 +2140,16 @@ static const struct apple_clpc_hw apple_clpc_hw_t8142 = { .ane_cluster_machine = "apple,t8142", }; +/* + * Standalone CLPC node without a PMC voter parent (for example T8112): no + * memory/fabric floor votes, and when the DT carries no explicit + * apple,low-power-frequency-max-mhz the low-power platform profile derives its + * ceiling from the fastest CPU cluster's operating points. + */ +static const struct apple_clpc_hw apple_clpc_hw_generic = { + .auto_low_power = true, +}; + #if IS_BUILTIN(CONFIG_KUNIT) && !defined(MODULE) #include #include @@ -2364,6 +2509,159 @@ static void apple_clpc_ane_wake_removal_test(struct kunit *test) apple_clpc_ane_put(ane); } +static void apple_clpc_low_power_roundup_test(struct kunit *test) +{ + /* M4 Pro P-cluster OPPs around the 2808 MHz ADT ceiling (J616s). */ + struct cpufreq_frequency_table p_table[] = { + { .frequency = 2592000 }, + { .frequency = 2868000 }, + { .frequency = 3132000 }, + { .frequency = 4512000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table e_table[] = { + { .frequency = 1020000 }, + { .frequency = 2592000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_policy p_pol = { + .freq_table = p_table, + .cpuinfo = { .min_freq = 2592000, .max_freq = 4512000 }, + }; + struct cpufreq_policy e_pol = { + .freq_table = e_table, + .cpuinfo = { .min_freq = 1020000, .max_freq = 2592000 }, + }; + + /* Explicit ceiling rounds UP to the first OPP >= 2808 MHz (2868 MHz). */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&p_pol, 2808000, false, 4512000), + 2868000u); + /* Slower cluster below 2808 MHz stays at its max (2592 MHz). */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&e_pol, 2808000, false, 4512000), + 2592000u); + /* Explicit DT ceiling also overrides auto_low_power. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&p_pol, 2808000, true, 4512000), + 2868000u); +} + +static void apple_clpc_low_power_auto_test(struct kunit *test) +{ + /* T8112 (J473/J413) live E and P cluster operating points. */ + struct cpufreq_frequency_table e_table[] = { + { .frequency = 600000 }, + { .frequency = 912000 }, + { .frequency = 1284000 }, + { .frequency = 1752000 }, + { .frequency = 2004000 }, + { .frequency = 2256000 }, + { .frequency = 2424000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table p_table[] = { + { .frequency = 660000 }, + { .frequency = 924000 }, + { .frequency = 1188000 }, + { .frequency = 1452000 }, + { .frequency = 1704000 }, + { .frequency = 1968000 }, + { .frequency = 2208000 }, + { .frequency = 2400000 }, + { .frequency = 2568000 }, + { .frequency = 2724000 }, + { .frequency = 2868000 }, + { .frequency = 2988000 }, + { .frequency = 3096000 }, + { .frequency = 3204000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_frequency_table single_table[] = { + { .frequency = 3000000 }, + { .frequency = CPUFREQ_TABLE_END }, + }; + struct cpufreq_policy e_pol = { + .freq_table = e_table, + .cpuinfo = { .min_freq = 600000, .max_freq = 2424000 }, + }; + struct cpufreq_policy p_pol = { + .freq_table = p_table, + .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, + }; + struct cpufreq_policy single_pol = { + .freq_table = single_table, + .cpuinfo = { .min_freq = 3000000, .max_freq = 3000000 }, + }; + struct cpufreq_policy no_table_pol = { + .freq_table = NULL, + .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, + }; + + /* 64% of 3204 MHz = 2050.56 MHz -> highest OPP <= target is 1968 MHz. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&p_pol, 0, true, 3204000), + 1968000u); + /* Slower E-cluster (2424 < 3204 MHz) stays uncapped. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&e_pol, 0, true, 3204000), + 2424000u); + /* Without auto_low_power or low_power_khz, no cap applies. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&p_pol, 0, false, 3204000), + 3204000u); + /* All OPPs above 64% target: fall back safely to policy min_freq. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&single_pol, 0, true, 3000000), + 3000000u); + /* NULL freq_table must not dereference NULL; falls back to min_freq. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&no_table_pol, 0, true, 3204000), + 660000u); +} + +static void apple_clpc_profile_ops_test(struct kunit *test) +{ + struct apple_clpc *clpc = kunit_kzalloc(test, sizeof(*clpc), GFP_KERNEL); + struct device dev = {}; + unsigned long choices = 0; + enum platform_profile_option prof = PLATFORM_PROFILE_BALANCED; + + KUNIT_ASSERT_NOT_NULL(test, clpc); + mutex_init(&clpc->sample_lock); + clpc->hw = &apple_clpc_hw_generic; + clpc->auto_low_power = true; + clpc->has_pmc = false; + clpc->stopped = true; + clpc->profile = PLATFORM_PROFILE_BALANCED; + dev_set_drvdata(&dev, clpc); + + KUNIT_EXPECT_TRUE(test, apple_clpc_hw_generic.auto_low_power); + KUNIT_EXPECT_FALSE(test, apple_clpc_hw_t6040.auto_low_power); + KUNIT_EXPECT_FALSE(test, apple_clpc_hw_t8132.auto_low_power); + KUNIT_EXPECT_TRUE(test, apple_clpc_has_profile_ceiling(clpc)); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_probe(clpc, &choices), 0); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_LOW_POWER, &choices)); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_BALANCED, &choices)); + KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_PERFORMANCE, &choices)); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_LOW_POWER), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_LOW_POWER); + KUNIT_EXPECT_TRUE(test, clpc->low_power); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_PERFORMANCE), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_PERFORMANCE); + KUNIT_EXPECT_FALSE(test, clpc->low_power); + + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_BALANCED), 0); + KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); + KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_BALANCED); + KUNIT_EXPECT_FALSE(test, clpc->low_power); +} + static struct kunit_case apple_clpc_cases[] = { KUNIT_CASE(apple_clpc_ane_demand_hold_test), KUNIT_CASE(apple_clpc_ane_states_test), @@ -2376,6 +2674,9 @@ static struct kunit_case apple_clpc_cases[] = { KUNIT_CASE(apple_clpc_gpu_cold_wake_test), KUNIT_CASE(apple_clpc_gpu_request_lifetime_test), KUNIT_CASE(apple_clpc_gpu_provider_removal_test), + KUNIT_CASE(apple_clpc_low_power_roundup_test), + KUNIT_CASE(apple_clpc_low_power_auto_test), + KUNIT_CASE(apple_clpc_profile_ops_test), {} }; static struct kunit_suite apple_clpc_suite = { @@ -2463,6 +2764,7 @@ static const struct of_device_id apple_clpc_of_match[] = { { .compatible = "apple,t8152-clpc", .data = &apple_clpc_hw_t8152 }, { .compatible = "apple,t6041-max-clpc", .data = &apple_clpc_hw_t6041 }, { .compatible = "apple,t6041-clpc", .data = &apple_clpc_hw_t6040 }, + { .compatible = "apple,clpc", .data = &apple_clpc_hw_generic }, {} }; MODULE_DEVICE_TABLE(of, apple_clpc_of_match); From 29820d4a22ba90ed3548064b95f8a6259e71ab7f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:42:30 +1100 Subject: [PATCH 0907/1514] arm64: dts: apple: t8112: add standalone CLPC node for platform profiles Add a root-level performance-controller node ("apple,t8112-clpc", "apple,clpc") referencing &smc in t8112.dtsi so all T8112 boards (J473, J413, J415, J493) expose the shared apple-clpc platform-profile provider with real low-power, balanced, and performance profiles. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112.dtsi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index 1244444d470d57..fd13d3c654e935 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -27,6 +27,11 @@ #endif }; + clpc: performance-controller { + compatible = "apple,t8112-clpc", "apple,clpc"; + apple,smc = <&smc>; + }; + cpus { #address-cells = <2>; #size-cells = <0>; From 0897a4c2b35e788e610157500672252e6cdbba70 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 01:53:04 -0800 Subject: [PATCH 0908/1514] watchdog: apple: use WD2 simple-reconfig so expiry and reboot reset the SoC On Apple Silicon SoCs whose watchdog DT node provides the optional "reconfig" routing register (such as T6050 / M5 Ultra), legacy WD1 RESET_EN stalls the SoC instead of performing a cold reset. Routing WD2's bark interrupt via bits 5:4 = 01 of the "reconfig" register (with WD2_BITE = U32_MAX and WD2_CTRL = IRQ_EN) triggers a clean cold reset on both watchdog expiry and apple_wdt_restart(). When "reconfig" (>= 4 bytes, mapped non-exclusively via devm_ioremap) is present: - Register the apple_sleep WD2 handoff (matching the watchdog's reg[0] resource) before touching any watchdog registers so a registration error writes zero registers and devm unregisters the watchdog before the sleep handoff. - Unify all four WD2 arming paths (start(), restart(), pre-probe takeover, and apple_wdt_sleep_restore()) into apple_wdt_wd2_arm(): CTRL=0, BITE=U32_MAX, CUR=0, BARK=ticks, W1C clear IRQ_STATUS, a readl(WD2_CTRL) ordering barrier ahead of the separate reconfig mapping, apple_wdt_enable_reconfig() (with readback), and CTRL=IRQ_EN. - Unify pre-probe takeover: always clear WD1_CTRL, and when either a legacy boot-loader WD1 (RESET_EN) or WD2 (IRQ_EN or RESET_EN) was armed before probe (outside kdump), set WDOG_HW_RUNNING before calling apple_wdt_wd2_arm() so a watchdog already armed at probe stays armed and resets cleanly instead of stalling or being dropped. - Derive the 40 ms reboot bark delay from clk_rate and yield WD2 to apple_sleep when apple_sleep_wdt_active(dev) is true. Single-reg DT nodes keep existing WD1 behavior unchanged aside from guarding apple_wdt_get_timeleft() against cur_time >= reset_time underflow on both WD1 and WD2. Add tools/asahi/apple-wdt-tests.py (registered in run-host-tests.py) compiling the real driver body and T6050 commit/wake WDT helpers under ASan/UBSan with --old-ref 70a00e583b032 and eight negative mutations. Signed-off-by: Jeff Queisser --- drivers/watchdog/apple_wdt.c | 214 ++++++- tools/asahi/apple-wdt-tests.py | 1017 ++++++++++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 7 + 3 files changed, 1211 insertions(+), 27 deletions(-) create mode 100755 tools/asahi/apple-wdt-tests.py diff --git a/drivers/watchdog/apple_wdt.c b/drivers/watchdog/apple_wdt.c index 3c867a3ce636e5..1300a00d5cd654 100644 --- a/drivers/watchdog/apple_wdt.c +++ b/drivers/watchdog/apple_wdt.c @@ -12,28 +12,32 @@ #include #include #include +#include #include #include #include +#include #include /* * Apple Watchdog MMIO registers * - * This HW block has three separate watchdogs. WD0 resets the machine - * to recovery mode and is not very useful for us. WD1 and WD2 trigger a normal - * machine reset. WD0 additionally supports a configurable interrupt. - * This information can be used to implement pretimeout support at a later time. + * This HW block has three separate watchdogs. WD0 resets the machine to + * recovery mode and is not used by Linux. On legacy wdt-version 2 platforms + * WD1 triggers a normal machine reset via APPLE_WDT_CTRL_RESET_EN when + * CUR_TIME >= BITE_TIME. + * + * On platforms that provide the optional "reconfig" routing register + * (simple-reconfig-wdog-support), WD1/WD2 hardware RESET_EN does not reset + * reliably; instead, setting bits 5:4 = 01 in the reconfig register routes + * WD2's bark interrupt (CUR_TIME >= BARK_TIME with APPLE_WDT_CTRL_IRQ_EN + * set and BITE_TIME = U32_MAX) to a clean cold reset. * * APPLE_WDT_WDx_CUR_TIME is a simple counter incremented for each tick of the * reference clock. It can also be overwritten to any value. - * Whenever APPLE_WDT_CTRL_RESET_EN is set in APPLE_WDT_WDx_CTRL and - * APPLE_WDT_WDx_CUR_TIME >= APPLE_WDT_WDx_BITE_TIME the entire machine is - * reset. - * Whenever APPLE_WDT_CTRL_IRQ_EN is set and APPLE_WDTx_WD1_CUR_TIME >= - * APPLE_WDTx_WD1_BARK_TIME an interrupt is triggered and - * APPLE_WDT_CTRL_IRQ_STATUS is set. The interrupt can be cleared by writing - * 1 to APPLE_WDT_CTRL_IRQ_STATUS. + * Whenever APPLE_WDT_CTRL_IRQ_EN is set and CUR_TIME >= BARK_TIME an interrupt + * is triggered and APPLE_WDT_CTRL_IRQ_STATUS is set. The interrupt can be + * cleared by writing 1 to APPLE_WDT_CTRL_IRQ_STATUS. */ #define APPLE_WDT_WD0_CUR_TIME 0x00 #define APPLE_WDT_WD0_BITE_TIME 0x04 @@ -46,17 +50,26 @@ #define APPLE_WDT_WD2_CUR_TIME 0x20 #define APPLE_WDT_WD2_BITE_TIME 0x24 +#define APPLE_WDT_WD2_BARK_TIME 0x28 #define APPLE_WDT_WD2_CTRL 0x2c #define APPLE_WDT_CTRL_IRQ_EN BIT(0) #define APPLE_WDT_CTRL_IRQ_STATUS BIT(1) #define APPLE_WDT_CTRL_RESET_EN BIT(2) +/* Optional "reconfig" register: bits 5:4 = 01 routes WD2 bark to cold reset */ +#define APPLE_WDT_RECONFIG_MASK GENMASK(5, 4) +#define APPLE_WDT_RECONFIG_WD2 BIT(4) + +/* ~40 ms bark delay before simple-reconfig cold reset */ +#define APPLE_WDT_REBOOT_DELAY_MS 40 + #define APPLE_WDT_TIMEOUT_DEFAULT 30 struct apple_wdt { struct watchdog_device wdd; void __iomem *regs; + void __iomem *reconfig; unsigned long clk_rate; }; @@ -65,10 +78,52 @@ static struct apple_wdt *to_apple_wdt(struct watchdog_device *wdd) return container_of(wdd, struct apple_wdt, wdd); } +static u32 apple_wdt_timeout_ticks(struct apple_wdt *wdt, unsigned int s) +{ + u32 actual = min(s, wdt->wdd.max_hw_heartbeat_ms / 1000); + + return wdt->clk_rate * actual; +} + +static void apple_wdt_enable_reconfig(struct apple_wdt *wdt) +{ + u32 val = readl_relaxed(wdt->reconfig); + + writel_relaxed((val & ~APPLE_WDT_RECONFIG_MASK) | APPLE_WDT_RECONFIG_WD2, + wdt->reconfig); + (void)readl(wdt->reconfig); +} + +static void apple_wdt_wd2_arm(struct apple_wdt *wdt, u32 bark_ticks) +{ + /* + * Disarm WD2, program safe BITE/CUR/BARK, and clear any latched + * IRQ_STATUS before routing WD2 bark to cold reset and enabling IRQ_EN. + * Read back WD2_CTRL to order the watchdog-block writes before touching + * the separate AON reconfig mapping; apple_wdt_enable_reconfig() reads + * back reconfig before the final IRQ_EN write. + */ + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL); + writel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME); + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); + writel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); + writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, + wdt->regs + APPLE_WDT_WD2_CTRL); + (void)readl(wdt->regs + APPLE_WDT_WD2_CTRL); + apple_wdt_enable_reconfig(wdt); + writel_relaxed(APPLE_WDT_CTRL_IRQ_EN, wdt->regs + APPLE_WDT_WD2_CTRL); +} + static int apple_wdt_start(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + if (wdt->reconfig) { + apple_wdt_wd2_arm(wdt, + apple_wdt_timeout_ticks(wdt, wdd->timeout)); + return 0; + } + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); writel_relaxed(APPLE_WDT_CTRL_RESET_EN, wdt->regs + APPLE_WDT_WD1_CTRL); @@ -78,8 +133,9 @@ static int apple_wdt_start(struct watchdog_device *wdd) static int apple_wdt_stop(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + u32 ctrl_off = wdt->reconfig ? APPLE_WDT_WD2_CTRL : APPLE_WDT_WD1_CTRL; - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + writel_relaxed(0, wdt->regs + ctrl_off); return 0; } @@ -87,8 +143,13 @@ static int apple_wdt_stop(struct watchdog_device *wdd) static int apple_wdt_ping(struct watchdog_device *wdd) { struct apple_wdt *wdt = to_apple_wdt(wdd); + u32 cur_off; - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent)) + return 0; + + cur_off = wdt->reconfig ? APPLE_WDT_WD2_CUR_TIME : APPLE_WDT_WD1_CUR_TIME; + writel_relaxed(0, wdt->regs + cur_off); return 0; } @@ -96,12 +157,15 @@ static int apple_wdt_ping(struct watchdog_device *wdd) static int apple_wdt_set_timeout(struct watchdog_device *wdd, unsigned int s) { struct apple_wdt *wdt = to_apple_wdt(wdd); - u32 actual; - - writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); - - actual = min(s, wdd->max_hw_heartbeat_ms / 1000); - writel_relaxed(wdt->clk_rate * actual, wdt->regs + APPLE_WDT_WD1_BITE_TIME); + u32 ticks = apple_wdt_timeout_ticks(wdt, s); + + if (wdt->reconfig) { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME); + writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME); + } else { + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); + writel_relaxed(ticks, wdt->regs + APPLE_WDT_WD1_BITE_TIME); + } wdd->timeout = s; @@ -113,8 +177,16 @@ static unsigned int apple_wdt_get_timeleft(struct watchdog_device *wdd) struct apple_wdt *wdt = to_apple_wdt(wdd); u32 cur_time, reset_time; - cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CUR_TIME); - reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_BITE_TIME); + if (wdt->reconfig) { + cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CUR_TIME); + reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD2_BARK_TIME); + } else { + cur_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CUR_TIME); + reset_time = readl_relaxed(wdt->regs + APPLE_WDT_WD1_BITE_TIME); + } + + if (cur_time >= reset_time) + return 0; return (reset_time - cur_time) / wdt->clk_rate; } @@ -124,6 +196,22 @@ static int apple_wdt_restart(struct watchdog_device *wdd, unsigned long mode, { struct apple_wdt *wdt = to_apple_wdt(wdd); + if (wdt->reconfig) { + u32 ticks = max_t(u32, 1, + div_u64((u64)wdt->clk_rate * APPLE_WDT_REBOOT_DELAY_MS, + MSEC_PER_SEC)); + + apple_wdt_wd2_arm(wdt, ticks); + + /* + * Flush writes and wait for the bark delay (~40 ms) plus SoC + * reset latency (~125 ms) before returning from restart. + */ + (void)readl(wdt->regs + APPLE_WDT_WD2_CUR_TIME); + mdelay(200); + return 0; + } + writel_relaxed(APPLE_WDT_CTRL_RESET_EN, wdt->regs + APPLE_WDT_WD1_CTRL); writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_BITE_TIME); writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CUR_TIME); @@ -155,21 +243,46 @@ static const struct watchdog_info apple_wdt_info = { .options = WDIOF_MAGICCLOSE | WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT, }; +static void apple_wdt_sleep_restore(void *data) +{ + struct apple_wdt *wdt = data; + + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) + apple_wdt_start(&wdt->wdd); +} + +static void apple_wdt_sleep_unregister(void *data) +{ + apple_sleep_wdt_unregister(data); +} + static int apple_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; + struct resource *wdt_res, *reconfig_res; struct apple_wdt *wdt; struct clk *clk; u32 wdt_ctrl; + int ret; wdt = devm_kzalloc(dev, sizeof(*wdt), GFP_KERNEL); if (!wdt) return -ENOMEM; - wdt->regs = devm_platform_ioremap_resource(pdev, 0); + wdt->regs = devm_platform_get_and_ioremap_resource(pdev, 0, &wdt_res); if (IS_ERR(wdt->regs)) return PTR_ERR(wdt->regs); + reconfig_res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "reconfig"); + if (reconfig_res) { + if (resource_size(reconfig_res) < sizeof(u32)) + return -EINVAL; + wdt->reconfig = devm_ioremap(dev, reconfig_res->start, + resource_size(reconfig_res)); + if (!wdt->reconfig) + return -ENOMEM; + } + clk = devm_clk_get_enabled(dev, NULL); if (IS_ERR(clk)) return PTR_ERR(clk); @@ -185,13 +298,54 @@ static int apple_wdt_probe(struct platform_device *pdev) wdt->wdd.max_hw_heartbeat_ms = U32_MAX / wdt->clk_rate * 1000; wdt->wdd.timeout = APPLE_WDT_TIMEOUT_DEFAULT; - wdt_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); - if ((wdt_ctrl & APPLE_WDT_CTRL_RESET_EN) && !is_kdump_kernel()) - set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); - watchdog_set_nowayout(&wdt->wdd, WATCHDOG_NOWAYOUT); watchdog_init_timeout(&wdt->wdd, 0, dev); - apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + + if (wdt->reconfig) { + u32 wd1_ctrl, wd2_ctrl; + bool armed; + + /* + * Register the sleep handoff before touching watchdog registers + * so a registration failure cannot leave WD2 armed, and so devm + * unwinds watchdog_unregister_device() before unregistering here. + */ + ret = apple_sleep_wdt_register(dev, wdt_res, + apple_wdt_sleep_restore, wdt); + if (ret) + return ret; + ret = devm_add_action_or_reset(dev, apple_wdt_sleep_unregister, dev); + if (ret) + return ret; + + wd1_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + wd2_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD2_CTRL); + armed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) || + (wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN)); + + if (wd1_ctrl) + writel_relaxed(0, wdt->regs + APPLE_WDT_WD1_CTRL); + + if (armed && !is_kdump_kernel()) { + if (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over legacy WD1 watchdog as WD2 simple-reconfig\n"); + if (wd2_ctrl & APPLE_WDT_CTRL_RESET_EN) + dev_info(dev, "taking over WD2 RESET_EN watchdog as WD2 simple-reconfig\n"); + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_wd2_arm(wdt, + apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout)); + } else { + if (wd2_ctrl) + writel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS, + wdt->regs + APPLE_WDT_WD2_CTRL); + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } + } else { + wdt_ctrl = readl_relaxed(wdt->regs + APPLE_WDT_WD1_CTRL); + if ((wdt_ctrl & APPLE_WDT_CTRL_RESET_EN) && !is_kdump_kernel()) + set_bit(WDOG_HW_RUNNING, &wdt->wdd.status); + apple_wdt_set_timeout(&wdt->wdd, wdt->wdd.timeout); + } /* * A crash kernel only saves the dump and restarts. If it stalls, the @@ -215,6 +369,9 @@ static int apple_wdt_resume(struct device *dev) { struct apple_wdt *wdt = dev_get_drvdata(dev); + if (wdt->reconfig && apple_sleep_wdt_active(dev)) + return 0; + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_start(&wdt->wdd); @@ -225,6 +382,9 @@ static int apple_wdt_suspend(struct device *dev) { struct apple_wdt *wdt = dev_get_drvdata(dev); + if (wdt->reconfig && apple_sleep_wdt_active(dev)) + return 0; + if (watchdog_active(&wdt->wdd) || watchdog_hw_running(&wdt->wdd)) apple_wdt_stop(&wdt->wdd); diff --git a/tools/asahi/apple-wdt-tests.py b/tools/asahi/apple-wdt-tests.py new file mode 100755 index 00000000000000..f6f8cf01dd2d62 --- /dev/null +++ b/tools/asahi/apple-wdt-tests.py @@ -0,0 +1,1017 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Check Apple SoC Watchdog probe, ops, PM, sleep handoff and T6050 wake WDT helpers. + +The full production driver body from drivers/watchdog/apple_wdt.c (ops, probe, +suspend, resume, and sleep restore) and the T6050 commit/wake WDT helpers from +drivers/soc/apple/sleep-t6050.h are compiled unchanged under ASan and UBSan +against an in-memory MMIO register model with write-order and barrier tracking. + +- Without a "reconfig" MMIO resource (legacy wdt-version 2): probe adopts + WD1_CTRL RESET_EN, start/stop/ping/set_timeout/get_timeleft/suspend/resume/ + restart drive WD1 unchanged and leave WD2 untouched. +- With a "reconfig" MMIO resource (simple-reconfig-wdog-support): + - Probe rejects undersized (< 4 B) reconfig resources with -EINVAL. + - Probe registers the sleep handoff before touching watchdog registers so a + registration failure (-EBUSY) writes zero registers, and devm unregisters + the watchdog before unregistering the sleep handoff. + - Probe clears any pre-armed WD1_CTRL and unifies pre-probe takeover: any + armed WD1 (RESET_EN) or WD2 (IRQ_EN or RESET_EN) sets WDOG_HW_RUNNING + before the first WD2 write and re-arms WD2 safely through apple_wdt_wd2_arm(). + - start/stop/ping/set_timeout/get_timeleft/restart drive WD2 bark-IRQ with + clock-derived reboot delay, write-order and readl() barrier checks, and + underflow guard. + - resume without apple_sleep reprograms reconfig, WD2_BITE and WD2_BARK even + if register state was lost across suspend. + - suspend/ping/resume during firmware-driven apple_sleep leave sleep's WD2 + safety net intact only for the device owning the sleep slot; non-matching + devices keep operating normally. + - kdump probe skips takeover (both WD1 and WD2) and arms WD2 at max_hw_heartbeat_ms. + - T6050 sleep commit/wake WDT helpers save wdt-aux + AON_WDT_SLEEP before + t6050_seq(T6050_SEQ_WDT) and restore it on wake after CTL=0, W1C IRQ_STATUS + clear, and a readl() barrier, followed by a readl() barrier before re-arming. + +--old-ref REV compiles and runs apple_wdt.c from REV and expects failure. +--mutation NAME mutates the driver/helper source and expects failure. +""" +import argparse +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +DRIVER = 'drivers/watchdog/apple_wdt.c' +SLEEP_T6050 = 'drivers/soc/apple/sleep-t6050.h' + + +def show(ref, path): + if not ref: + return (ROOT / path).read_text() + return subprocess.run(['git', '-C', str(ROOT), 'show', f'{ref}:{path}'], check=True, + capture_output=True, text=True).stdout + + +def extract_body(source): + start = source.index('#define APPLE_WDT_WD0_CUR_TIME') + end = source.index('static DEFINE_SIMPLE_DEV_PM_OPS') + return source[start:end] + + +def extract_t6050_wdt_helpers(source): + start = source.index('static void t6050_sleep_commit_wdt(') + end = source.index('/*\n * The commit window,') + return source[start:end] + + +def apply_mutation(body, t6050_helpers, mutation): + if not mutation: + return body, t6050_helpers + if mutation == 'ignore-sleep-handoff': + needle = 'if (wdt->reconfig && apple_sleep_wdt_active(wdd->parent))\n\t\treturn 0;' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, 'if (0)\n\t\treturn 0;'), t6050_helpers + if mutation == 'no-bark-in-start': + needle = '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, '\t/* omitted BARK write */'), t6050_helpers + if mutation == 'no-status-clear': + needle = '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n\t\t wdt->regs + APPLE_WDT_WD2_CTRL);' + if needle not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body.replace(needle, '\t/* omitted IRQ_STATUS clear */'), t6050_helpers + if mutation == 'reconfig-before-bark': + old = ('\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' + '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' + '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n' + '\t\t wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\tapple_wdt_enable_reconfig(wdt);') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = ('\tapple_wdt_enable_reconfig(wdt);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\twritel_relaxed(U32_MAX, wdt->regs + APPLE_WDT_WD2_BITE_TIME);\n' + '\twritel_relaxed(0, wdt->regs + APPLE_WDT_WD2_CUR_TIME);\n' + '\twritel_relaxed(bark_ticks, wdt->regs + APPLE_WDT_WD2_BARK_TIME);\n' + '\twritel_relaxed(APPLE_WDT_CTRL_IRQ_STATUS,\n' + '\t\t wdt->regs + APPLE_WDT_WD2_CTRL);\n' + '\t(void)readl(wdt->regs + APPLE_WDT_WD2_CTRL);') + return body.replace(old, new), t6050_helpers + if mutation == 'register-after-arm': + reg_block = ('\t\tret = apple_sleep_wdt_register(dev, wdt_res,\n' + '\t\t\t\t\t apple_wdt_sleep_restore, wdt);\n' + '\t\tif (ret)\n' + '\t\t\treturn ret;\n' + '\t\tret = devm_add_action_or_reset(dev, apple_wdt_sleep_unregister, dev);\n' + '\t\tif (ret)\n' + '\t\t\treturn ret;\n') + tail = '\treturn devm_watchdog_register_device(dev, &wdt->wdd);' + if reg_block not in body or tail not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + mut = body.replace(reg_block, '') + mut = mut.replace(tail, + '\tret = devm_watchdog_register_device(dev, &wdt->wdd);\n' + '\tif (ret)\n\t\treturn ret;\n' + '\tif (wdt->reconfig) {\n' + reg_block + '\t}\n\treturn 0;') + return mut, t6050_helpers + if mutation == 'hwrunning-after-arm': + old = ('\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);\n' + '\t\t\tapple_wdt_wd2_arm(wdt,\n' + '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = ('\t\t\tapple_wdt_wd2_arm(wdt,\n' + '\t\t\t\t\t apple_wdt_timeout_ticks(wdt, wdt->wdd.timeout));\n' + '\t\t\tset_bit(WDOG_HW_RUNNING, &wdt->wdd.status);') + return body.replace(old, new), t6050_helpers + if mutation == 'no-wd1-adopt': + old = ('\t\tarmed = (wd1_ctrl & APPLE_WDT_CTRL_RESET_EN) ||\n' + '\t\t\t(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));') + if old not in body: + raise SystemExit(f'mutation {mutation}: target pattern not found') + new = '\t\tarmed = !!(wd2_ctrl & (APPLE_WDT_CTRL_IRQ_EN | APPLE_WDT_CTRL_RESET_EN));' + return body.replace(old, new), t6050_helpers + if mutation == 'no-t6050-wake-restore': + old = ('\tif (s->aon_wdt_marked) {\n' + '\t\twritel(s->aon_wdt_saved, s->wdt_aux + AON_WDT_SLEEP);\n' + '\t\t(void)readl(s->wdt_aux + AON_WDT_SLEEP);\n' + '\t\ts->aon_wdt_marked = false;\n' + '\t}') + if old not in t6050_helpers: + raise SystemExit(f'mutation {mutation}: target pattern not found') + return body, t6050_helpers.replace(old, '\t/* omitted wake restore */') + raise SystemExit(f'unknown mutation: {mutation}') + + +PREFIX = r''' +#include +#include +#include +#include +#include +#include +#include +#include + +typedef uint32_t u32; +typedef uint64_t u64; +typedef uintptr_t resource_size_t; + +#define BIT(x) (1u << (x)) +#define GENMASK(h, l) (((~0u) << (l)) & (~0u >> (31 - (h)))) +#define U32_MAX 0xffffffffu +#define MSEC_PER_SEC 1000u +#define __iomem +#define GFP_KERNEL 0 +#define THIS_MODULE NULL +#define IORESOURCE_MEM 0x00000200u +#define WATCHDOG_NOWAYOUT 0 +#define WDIOF_MAGICCLOSE 0x0100u +#define WDIOF_KEEPALIVEPING 0x8000u +#define WDIOF_SETTIMEOUT 0x0080u + +#define WDOG_ACTIVE 0 +#define WDOG_HW_RUNNING 1 + +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define max_t(type, a, b) ((type)(a) > (type)(b) ? (type)(a) : (type)(b)) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - offsetof(type, member))) + +static inline u64 div_u64(u64 dividend, u32 divisor) +{ + return dividend / divisor; +} + +static inline void set_bit(unsigned int nr, volatile unsigned long *addr) +{ + *addr |= (1UL << nr); +} + +static inline bool test_bit(unsigned int nr, const volatile unsigned long *addr) +{ + return (*addr & (1UL << nr)) != 0; +} + +static inline bool IS_ERR(const void *ptr) +{ + return (uintptr_t)ptr >= (uintptr_t)-4095L; +} + +static inline long PTR_ERR(const void *ptr) +{ + return (long)(intptr_t)ptr; +} + +struct device { + void *drvdata; +}; + +struct platform_device { + struct device dev; +}; + +struct resource { + resource_size_t start; + resource_size_t end; +}; + +static inline resource_size_t resource_size(const struct resource *res) +{ + return res->end - res->start + 1; +} + +struct clk { + unsigned long rate; +}; + +struct watchdog_device; + +struct watchdog_ops { + void *owner; + int (*start)(struct watchdog_device *); + int (*stop)(struct watchdog_device *); + int (*ping)(struct watchdog_device *); + int (*set_timeout)(struct watchdog_device *, unsigned int); + unsigned int (*get_timeleft)(struct watchdog_device *); + int (*restart)(struct watchdog_device *, unsigned long, void *); +}; + +struct watchdog_info { + const char *identity; + unsigned int options; +}; + +struct watchdog_device { + struct device *parent; + const struct watchdog_ops *ops; + const struct watchdog_info *info; + unsigned int timeout; + unsigned int max_hw_heartbeat_ms; + unsigned long status; +}; + +static inline bool watchdog_active(struct watchdog_device *wdd) +{ + return test_bit(WDOG_ACTIVE, &wdd->status); +} + +static inline bool watchdog_hw_running(struct watchdog_device *wdd) +{ + return test_bit(WDOG_HW_RUNNING, &wdd->status); +} + +/* Mock hardware + write log */ +#define MMIO_WORDS 16 +static u32 mmio_regs[MMIO_WORDS]; +static u32 wdt_aux_regs[MMIO_WORDS]; +#define reconfig_reg (wdt_aux_regs[0x2c / 4]) + +struct mmio_event { + bool is_reconfig; + u32 off; + u32 val; +}; + +static struct mmio_event write_log[256]; +static unsigned int write_log_len; + +static unsigned int mdelay_total_ms; +static bool mock_has_reconfig; +static resource_size_t mock_reconfig_size = 4; +static struct resource mock_wdt_res; +static struct resource mock_reconfig_res; +static struct clk mock_clk = { .rate = 24000000UL }; +static bool mock_kdump; +static unsigned int mock_warns; +static unsigned int mock_infos; +static unsigned int mock_dt_timeout; +static bool wdt_ctrl_read_since_write; +static bool reconfig_read_since_write; +static struct watchdog_device *registered_wdd; +static struct watchdog_device *current_probe_wdd; +static bool expect_hw_running_before_wd2_write; +static bool mock_sleep_active; +static int mock_sleep_reg_ret; +static struct device *mock_sleep_owner; +static const struct resource *mock_sleep_reg_res; +static void (*mock_sleep_restore)(void *); +static void *mock_sleep_data; +static void *mock_devm_alloc; + +/* Devm LIFO stack to verify teardown order (watchdog unregister before sleep unregister) */ +enum devm_kind { DEVM_ACTION = 1, DEVM_WDT = 2 }; +struct devm_entry { + enum devm_kind kind; + void (*action)(void *); + void *data; +}; +static struct devm_entry devm_stack[16]; +static unsigned int devm_stack_len; +static enum devm_kind teardown_order[16]; +static unsigned int teardown_order_len; + +static void record_write(const volatile void *addr, u32 val) +{ + assert(write_log_len < 256); + if (addr == (const volatile void *)&reconfig_reg) { + if ((val & GENMASK(5, 4)) == BIT(4)) { + /* + * Routing WD2 bark to cold reset must never occur while + * IRQ_EN is set, IRQ_STATUS is latched, BITE is short, + * CUR >= BARK, or without a readl() barrier on the + * separate watchdog register block first. + */ + assert((mmio_regs[0x2c / 4] & (BIT(0) | BIT(1))) == 0); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x20 / 4] < mmio_regs[0x28 / 4]); + assert(wdt_ctrl_read_since_write); + } + reconfig_read_since_write = false; + write_log[write_log_len++] = (struct mmio_event){ true, 0x2c, val }; + } else if (addr >= (const volatile void *)wdt_aux_regs && + addr < (const volatile void *)(wdt_aux_regs + MMIO_WORDS)) { + uintptr_t base = (uintptr_t)wdt_aux_regs; + uintptr_t p = (uintptr_t)addr; + write_log[write_log_len++] = (struct mmio_event){ true, (u32)(p - base), val }; + } else { + uintptr_t base = (uintptr_t)mmio_regs; + uintptr_t p = (uintptr_t)addr; + u32 off = (u32)(p - base); + assert(p >= base && p < base + sizeof(mmio_regs)); + if (expect_hw_running_before_wd2_write && off >= 0x20 && off <= 0x2c) + assert(current_probe_wdd && watchdog_hw_running(current_probe_wdd)); + /* Enabling WD2 IRQ_EN under simple-reconfig requires a readl(reconfig) first */ + if (off == 0x2c && (val & BIT(0)) && (reconfig_reg & GENMASK(5, 4)) == BIT(4)) + assert(reconfig_read_since_write); + wdt_ctrl_read_since_write = false; + write_log[write_log_len++] = (struct mmio_event){ false, off, val }; + } +} + +static u32 readl_relaxed(const volatile void *addr) +{ + return *(const volatile u32 *)addr; +} + +static u32 readl(const volatile void *addr) +{ + if (addr == (const volatile void *)&mmio_regs[0x2c / 4]) + wdt_ctrl_read_since_write = true; + if (addr == (const volatile void *)&reconfig_reg) + reconfig_read_since_write = true; + return *(const volatile u32 *)addr; +} + +static void writel_relaxed(u32 val, volatile void *addr) +{ + if (addr == (volatile void *)&mmio_regs[0x2c / 4]) { + /* Model W1C semantics on APPLE_WDT_CTRL_IRQ_STATUS (BIT(1)) */ + u32 latched = mmio_regs[0x2c / 4] & BIT(1); + if (val & BIT(1)) + latched = 0; + mmio_regs[0x2c / 4] = (val & ~BIT(1)) | latched; + } else { + *(volatile u32 *)addr = val; + } + record_write(addr, val); +} + +static void writel(u32 val, volatile void *addr) +{ + writel_relaxed(val, addr); +} + +static void mdelay(unsigned int ms) +{ + mdelay_total_ms += ms; +} + +static void *devm_kzalloc(struct device *dev, size_t size, int gfp) +{ + assert(!mock_devm_alloc); + mock_devm_alloc = calloc(1, size); + return mock_devm_alloc; +} + +static void __iomem *devm_platform_ioremap_resource(struct platform_device *pdev, + unsigned int index) +{ + assert(index == 0); + return (void __iomem *)mmio_regs; +} + +static void __iomem *devm_platform_get_and_ioremap_resource(struct platform_device *pdev, + unsigned int index, + struct resource **res) +{ + assert(index == 0); + mock_wdt_res.start = 0x28836c000ULL; + mock_wdt_res.end = 0x28836c000ULL + 0x4000 - 1; + if (res) + *res = &mock_wdt_res; + return (void __iomem *)mmio_regs; +} + +static struct resource *platform_get_resource_byname(struct platform_device *pdev, + unsigned int type, const char *name) +{ + assert(type == IORESOURCE_MEM); + if (mock_has_reconfig && strcmp(name, "reconfig") == 0) { + mock_reconfig_res.start = (resource_size_t)(uintptr_t)&reconfig_reg; + mock_reconfig_res.end = mock_reconfig_res.start + mock_reconfig_size - 1; + return &mock_reconfig_res; + } + return NULL; +} + +static void __iomem *devm_ioremap(struct device *dev, resource_size_t offset, + resource_size_t size) +{ + return (void __iomem *)(uintptr_t)offset; +} + +static struct clk *devm_clk_get_enabled(struct device *dev, const char *id) +{ + return &mock_clk; +} + +static unsigned long clk_get_rate(struct clk *clk) +{ + return clk->rate; +} + +static void platform_set_drvdata(struct platform_device *pdev, void *data) +{ + pdev->dev.drvdata = data; +} + +static void *dev_get_drvdata(struct device *dev) +{ + return dev->drvdata; +} + +static bool is_kdump_kernel(void) +{ + return mock_kdump; +} + +static void watchdog_set_nowayout(struct watchdog_device *wdd, bool nowayout) {} +static int watchdog_init_timeout(struct watchdog_device *wdd, unsigned int t, struct device *dev) +{ + current_probe_wdd = wdd; + if (mock_dt_timeout) + wdd->timeout = mock_dt_timeout; + return 0; +} +static void watchdog_stop_on_unregister(struct watchdog_device *wdd) {} +static void watchdog_set_restart_priority(struct watchdog_device *wdd, int prio) {} + +static int devm_watchdog_register_device(struct device *dev, struct watchdog_device *wdd) +{ + registered_wdd = wdd; + assert(devm_stack_len < 16); + devm_stack[devm_stack_len++] = (struct devm_entry){ DEVM_WDT, NULL, wdd }; + return 0; +} + +static int devm_add_action_or_reset(struct device *dev, void (*action)(void *), void *data) +{ + assert(devm_stack_len < 16); + devm_stack[devm_stack_len++] = (struct devm_entry){ DEVM_ACTION, action, data }; + return 0; +} + +static int apple_sleep_wdt_register(struct device *dev, const struct resource *wdt, + void (*restore)(void *), void *data) +{ + if (mock_sleep_reg_ret) + return mock_sleep_reg_ret; + mock_sleep_owner = dev; + mock_sleep_reg_res = wdt; + mock_sleep_restore = restore; + mock_sleep_data = data; + return 0; +} + +static void apple_sleep_wdt_unregister(struct device *dev) +{ + if (mock_sleep_owner == dev) { + mock_sleep_owner = NULL; + mock_sleep_reg_res = NULL; + mock_sleep_restore = NULL; + mock_sleep_data = NULL; + } +} + +static bool apple_sleep_wdt_active(struct device *dev) +{ + return mock_sleep_active && mock_sleep_owner == dev; +} + +#define dev_warn(dev, fmt, ...) do { mock_warns++; } while (0) +#define dev_info(dev, fmt, ...) do { mock_infos++; } while (0) +''' + +T6050_PRELUDE = r''' +/* Minimal harness for T6050 sleep commit/wake WDT helpers extracted from sleep-t6050.h */ +#define WDT_WD0_CTL 0x0c +#define WDT_WD2_COUNT 0x20 +#define WDT_WD2_ALARM 0x28 +#define WDT_WD2_CTL 0x2c +#define WDT_WD2_CTL_IRQ_STATUS BIT(1) +#define WDT_TICKS_PER_S 24000000u +#define WDT_SUSPEND_SECS 120u +#define T6050_WDT_COMMIT_SECS 13u +#define AON_AP_DEADLINE 0x08 +#define AON_WDT_SLEEP 0x2c +#define T6050_SEQ_WDT 2 +#define T6050_SEQS 6 + +struct t6050_ops { + const u32 *op; + unsigned int n; +}; + +struct apple_sleep_region_state { + struct t6050_ops seq[T6050_SEQS]; +}; + +struct apple_sleep { + void __iomem *wdt; + void __iomem *wdt_aux; + struct apple_sleep_region_state *region; + u32 aon_wdt_saved; + bool aon_wdt_marked; +}; + +static bool mock_t6050_seq_saw_saved; +static u32 mock_t6050_seq_saved_val; +static bool mock_t6050_wake_armed_after_readback; + +static void t6050_seq(struct apple_sleep *s, int which) +{ + assert(which == T6050_SEQ_WDT); + if (s->region && s->region->seq[T6050_SEQ_WDT].n) { + mock_t6050_seq_saw_saved = s->aon_wdt_marked; + mock_t6050_seq_saved_val = s->aon_wdt_saved; + writel(0x20u, s->wdt_aux + AON_WDT_SLEEP); + } +} + +static void apple_sleep_set_wd2(struct apple_sleep *s, unsigned int secs) +{ + if (secs == WDT_SUSPEND_SECS) { + /* Before re-arming during wake, status must be clear and reconfig read back */ + assert((mmio_regs[0x2c / 4] & BIT(1)) == 0); + mock_t6050_wake_armed_after_readback = reconfig_read_since_write; + } + writel(0, s->wdt + WDT_WD2_CTL); + writel(0, s->wdt + WDT_WD2_COUNT); + writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD2_ALARM); + writel(1, s->wdt + WDT_WD2_CTL); +} +''' + +MAIN = r''' +static void reset_hw(bool has_reconfig, unsigned long clk_rate, bool kdump) +{ + memset(mmio_regs, 0, sizeof(mmio_regs)); + memset(wdt_aux_regs, 0, sizeof(wdt_aux_regs)); + write_log_len = 0; + mdelay_total_ms = 0; + mock_has_reconfig = has_reconfig; + mock_reconfig_size = 4; + mock_clk.rate = clk_rate; + mock_kdump = kdump; + mock_warns = 0; + mock_infos = 0; + mock_dt_timeout = 0; + wdt_ctrl_read_since_write = false; + reconfig_read_since_write = false; + registered_wdd = NULL; + current_probe_wdd = NULL; + expect_hw_running_before_wd2_write = false; + mock_sleep_active = false; + mock_sleep_reg_ret = 0; + mock_sleep_owner = NULL; + mock_sleep_reg_res = NULL; + mock_sleep_restore = NULL; + mock_sleep_data = NULL; + devm_stack_len = 0; + teardown_order_len = 0; +} + +static int find_write(bool is_reconfig, u32 off, u32 val, int from) +{ + for (int i = from; i < (int)write_log_len; i++) { + if (write_log[i].is_reconfig == is_reconfig && + write_log[i].off == off && + write_log[i].val == val) + return i; + } + return -1; +} + +static void teardown_pdev(struct platform_device *pdev) +{ + teardown_order_len = 0; + while (devm_stack_len > 0) { + struct devm_entry e = devm_stack[--devm_stack_len]; + teardown_order[teardown_order_len++] = e.kind; + if (e.kind == DEVM_ACTION && e.action) + e.action(e.data); + } + free(mock_devm_alloc); + mock_devm_alloc = NULL; + pdev->dev.drvdata = NULL; +} + +int main(void) +{ + struct platform_device pdev = {}; + struct device other_dev = {}; + struct watchdog_device *wdd; + + /* 1. Legacy WD1 path (no reconfig): unchanged behaviour, WD2 untouched */ + reset_hw(false, 24000000UL, false); + mmio_regs[0x1c / 4] = BIT(2); /* WD1_CTRL = RESET_EN armed by bootloader */ + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(wdd != NULL); + assert(watchdog_hw_running(wdd)); + assert(mmio_regs[0x14 / 4] == 30u * 24000000u); + assert(mmio_regs[0x2c / 4] == 0); + + assert(wdd->ops->start(wdd) == 0); + assert(mmio_regs[0x1c / 4] == BIT(2)); + assert(mmio_regs[0x2c / 4] == 0); + + mmio_regs[0x10 / 4] = 10u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 20u); + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x10 / 4] == 0); + + /* Underflow guard when counter reaches or passes bite (catches old driver) */ + mmio_regs[0x10 / 4] = 35u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 0); + + assert(wdd->ops->stop(wdd) == 0); + assert(mmio_regs[0x1c / 4] == 0); + + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(mmio_regs[0x1c / 4] == BIT(2)); + assert(mmio_regs[0x14 / 4] == 0); + assert(mmio_regs[0x2c / 4] == 0); + assert(mdelay_total_ms == 150); + teardown_pdev(&pdev); + + /* 2. Simple-reconfig WD2: undersized reconfig resource rejected with 0 writes */ + reset_hw(true, 24000000UL, false); + mock_reconfig_size = 2; + assert(apple_wdt_probe(&pdev) == -EINVAL); + assert(write_log_len == 0); + teardown_pdev(&pdev); + + /* 2b. Failed sleep handoff registration returns -EBUSY with 0 register writes */ + reset_hw(true, 24000000UL, false); + mock_sleep_reg_ret = -EBUSY; + mmio_regs[0x1c / 4] = BIT(2); + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_probe(&pdev) == -EBUSY); + assert(write_log_len == 0); + assert(registered_wdd == NULL); + teardown_pdev(&pdev); + + /* 3. Simple-reconfig WD2: probe clears armed WD1 and safely takes over hazardous WD2 */ + reset_hw(true, 24000000UL, false); + mock_dt_timeout = 20; /* verify watchdog_init_timeout() runs before takeover */ + expect_hw_running_before_wd2_write = true; + reconfig_reg = 0x000000a5u; /* unrelated bits must be preserved */ + mmio_regs[0x1c / 4] = BIT(2); /* legacy WD1 armed before probe */ + mmio_regs[0x20 / 4] = 500u; /* hazardous: CUR >= BARK */ + mmio_regs[0x24 / 4] = 1000u; /* stale short WD2_BITE */ + mmio_regs[0x28 / 4] = 100u; /* stale short WD2_BARK */ + mmio_regs[0x2c / 4] = BIT(0) | BIT(1) | BIT(2); /* IRQ_EN + latched IRQ_STATUS + RESET_EN */ + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_sleep_reg_res == &mock_wdt_res); + assert(mock_infos == 2); /* both legacy WD1 and WD2 RESET_EN takeover logged */ + assert(mmio_regs[0x1c / 4] == 0); /* WD1 cleared */ + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == 0x00000095u); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == 20u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + + /* Verify unified arming write order: CTRL=0, BITE=U32_MAX, CUR=0, BARK, CTRL=IRQ_STATUS, reconfig, CTRL=IRQ_EN */ + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 20u * 24000000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, 0x00000095u, i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + + /* 4. WD2 start / ping / set_timeout / get_timeleft / underflow / stop */ + write_log_len = 0; + assert(wdd->ops->set_timeout(wdd, 15) == 0); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + { + int i_cur = find_write(false, 0x20, 0, 0); + int i_bark = find_write(false, 0x28, 15u * 24000000u, 0); + assert(i_cur >= 0 && i_bark > i_cur); + } + + mmio_regs[0x20 / 4] = 5u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 10u); + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 0); + mmio_regs[0x20 / 4] = 20u * 24000000u; + assert(wdd->ops->get_timeleft(wdd) == 0); + + /* 5. Suspend/resume WITHOUT apple_sleep: resume reprograms lost BARK and reconfig */ + set_bit(WDOG_ACTIVE, &wdd->status); + assert(apple_wdt_suspend(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == 0); + /* Simulate power loss clearing BARK, BITE and reconfig across suspend */ + mmio_regs[0x24 / 4] = 0; + mmio_regs[0x28 / 4] = 0; + reconfig_reg = 0; + write_log_len = 0; + assert(apple_wdt_resume(&pdev.dev) == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 15u * 24000000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + + /* 6. Suspend/resume WITH apple_sleep active: sleep owns WD2 from .begin to .end */ + assert(mock_sleep_restore != NULL); + mock_sleep_active = true; + /* apple_sleep_begin() armed WD2 for 120 s */ + mmio_regs[0x20 / 4] = 1000u; + mmio_regs[0x28 / 4] = 120u * 24000000u; + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_suspend(&pdev.dev) == 0); + /* Must NOT stop sleep's 120 s safety net */ + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == 120u * 24000000u); + /* Keepalive ping during sleep must NOT zero sleep's counter */ + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 1000u); + /* Sleep commit switched reconfig to 0x20 and wake armed 120 s */ + reconfig_reg = 0x20u; + assert(apple_wdt_resume(&pdev.dev) == 0); + /* Must NOT clobber sleep's resume safety net before .end */ + assert(reconfig_reg == 0x20u); + assert(mmio_regs[0x28 / 4] == 120u * 24000000u); + /* apple_sleep_end() clears WD2_CTL and invokes restore callback */ + mmio_regs[0x2c / 4] = 0; + mock_sleep_restore(mock_sleep_data); + mock_sleep_active = false; + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 15u * 24000000u); + assert(mmio_regs[0x20 / 4] == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + + /* 6b. Per-device active(): a non-owner device still pings/suspends during sleep */ + mock_sleep_active = true; + mock_sleep_owner = &other_dev; + mmio_regs[0x20 / 4] = 1000u; + assert(wdd->ops->ping(wdd) == 0); + assert(mmio_regs[0x20 / 4] == 0); + assert(apple_wdt_suspend(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == 0); + assert(apple_wdt_resume(&pdev.dev) == 0); + assert(mmio_regs[0x2c / 4] == BIT(0)); + mock_sleep_owner = &pdev.dev; + mock_sleep_active = false; + + /* When watchdog is stopped, sleep .end restore must leave WD2 off */ + wdd->status = 0; + assert(wdd->ops->stop(wdd) == 0); + mock_sleep_active = true; + mmio_regs[0x2c / 4] = 0; + mock_sleep_restore(mock_sleep_data); + mock_sleep_active = false; + assert(mmio_regs[0x2c / 4] == 0); + + /* 7. Restart uses clock-derived bark delay (40 ms) and WD2, never WD1 */ + reconfig_reg = 0; + mdelay_total_ms = 0; + write_log_len = 0; + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 24000000u * 40u / 1000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x1c / 4] == 0); + assert(mdelay_total_ms >= 200); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_bite = find_write(false, 0x24, U32_MAX, i_stop); + int i_cur = find_write(false, 0x20, 0, i_bite); + int i_bark = find_write(false, 0x28, 24000000u * 40u / 1000u, i_cur); + int i_clr = find_write(false, 0x2c, BIT(1), i_bark); + int i_reconfig = find_write(true, 0x2c, BIT(4), i_clr); + int i_en = find_write(false, 0x2c, BIT(0), i_reconfig); + assert(i_stop >= 0 && i_bite > i_stop && i_cur > i_bite && i_bark > i_cur); + assert(i_clr > i_bark && i_reconfig > i_clr && i_en > i_reconfig); + } + teardown_pdev(&pdev); + /* Verify devm unwinds watchdog before sleep handoff */ + assert(teardown_order_len == 2); + assert(teardown_order[0] == DEVM_WDT); + assert(teardown_order[1] == DEVM_ACTION); + assert(mock_sleep_restore == NULL); + + /* 7b. Pre-probe legacy WD1 alone is adopted as WD2 simple-reconfig with HW_RUNNING */ + reset_hw(true, 24000000UL, false); + expect_hw_running_before_wd2_write = true; + mmio_regs[0x1c / 4] = BIT(2); /* published Aura trial-boot WD1 */ + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_infos == 1); + assert(mmio_regs[0x1c / 4] == 0); + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == 30u * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + + /* 7c. Pre-probe WD2 RESET_EN alone is adopted as WD2 simple-reconfig with HW_RUNNING */ + reset_hw(true, 24000000UL, false); + expect_hw_running_before_wd2_write = true; + mmio_regs[0x2c / 4] = BIT(2); + assert(apple_wdt_probe(&pdev) == 0); + expect_hw_running_before_wd2_write = false; + wdd = registered_wdd; + assert(mock_infos == 1); + assert(watchdog_hw_running(wdd)); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + + /* 7d. Idle pre-probe with only stale latched IRQ_STATUS clears status and stays stopped */ + reset_hw(true, 24000000UL, false); + mmio_regs[0x2c / 4] = BIT(1); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(!watchdog_hw_running(wdd)); + assert(mmio_regs[0x2c / 4] == 0); + assert(reconfig_reg == 0); + teardown_pdev(&pdev); + + /* 8. Restart bark delay scales with clk_rate (non-24 MHz) */ + reset_hw(true, 12000000UL, false); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(wdd->ops->restart(wdd, 0, NULL) == 0); + assert(mmio_regs[0x28 / 4] == 12000000u * 40u / 1000u); + teardown_pdev(&pdev); + + /* 9. Crash kernel skips takeover (WD1 and WD2) and arms WD2 at max_hw_heartbeat_ms */ + reset_hw(true, 24000000UL, true); + mmio_regs[0x1c / 4] = BIT(2); + mmio_regs[0x2c / 4] = BIT(0); + assert(apple_wdt_probe(&pdev) == 0); + wdd = registered_wdd; + assert(!watchdog_hw_running(wdd)); + assert(mmio_regs[0x1c / 4] == 0); + assert(reconfig_reg == BIT(4)); + assert(mmio_regs[0x24 / 4] == U32_MAX); + assert(mmio_regs[0x28 / 4] == (U32_MAX / 24000000u) * 24000000u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + teardown_pdev(&pdev); + +#ifndef SKIP_T6050_SLEEP_HELPERS + /* 10. T6050 sleep commit/wake WDT helpers save and restore wdt-aux + AON_WDT_SLEEP */ + { + struct apple_sleep_region_state reg = { .seq = { [T6050_SEQ_WDT] = { .n = 1 } } }; + struct apple_sleep s = { + .wdt = (void __iomem *)mmio_regs, + .wdt_aux = (void __iomem *)wdt_aux_regs, + .region = ®, + }; + + reset_hw(true, 24000000UL, false); + reconfig_reg = 0x00000095u; /* 0x10 routing + unrelated bits */ + reconfig_read_since_write = true; /* already settled before commit */ + mmio_regs[0x24 / 4] = U32_MAX; + mmio_regs[0x28 / 4] = 30u * 24000000u; + mmio_regs[0x2c / 4] = BIT(0); + mock_t6050_seq_saw_saved = false; + mock_t6050_seq_saved_val = 0; + + t6050_sleep_commit_wdt(&s); + assert(mock_t6050_seq_saw_saved); + assert(mock_t6050_seq_saved_val == 0x00000095u); + assert(s.aon_wdt_marked); + assert(reconfig_reg == 0x20u); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == T6050_WDT_COMMIT_SECS * WDT_TICKS_PER_S); + + /* Wake: simulate latched IRQ_STATUS and verify CTL=0 -> clear -> readl -> restore -> readl -> set_wd2 */ + mmio_regs[0x2c / 4] = BIT(0) | BIT(1); + write_log_len = 0; + mock_t6050_wake_armed_after_readback = false; + t6050_sleep_wake_wdt(&s); + assert(!s.aon_wdt_marked); + assert(reconfig_reg == 0x00000095u); + assert(mock_t6050_wake_armed_after_readback); + assert(mmio_regs[0x2c / 4] == BIT(0)); + assert(mmio_regs[0x28 / 4] == WDT_SUSPEND_SECS * WDT_TICKS_PER_S); + { + int i_stop = find_write(false, 0x2c, 0, 0); + int i_clr = find_write(false, 0x2c, BIT(1), i_stop); + int i_rest = find_write(true, 0x2c, 0x00000095u, i_clr); + int i_arm = find_write(false, 0x2c, BIT(0), i_rest); + assert(i_stop >= 0 && i_clr > i_stop && i_rest > i_clr && i_arm > i_rest); + } + + /* When seq[T6050_SEQ_WDT] is empty, aon_wdt_marked stays false and wake leaves reconfig alone */ + reg.seq[T6050_SEQ_WDT].n = 0; + reconfig_reg = 0x10u; + reconfig_read_since_write = true; + write_log_len = 0; + t6050_sleep_commit_wdt(&s); + assert(!s.aon_wdt_marked); + write_log_len = 0; + t6050_sleep_wake_wdt(&s); + assert(find_write(true, 0x2c, 0x10u, 0) < 0); + assert(reconfig_reg == 0x10u); + } +#endif + + puts("PASS apple_wdt legacy WD1, simple-reconfig WD2, sleep handoff, and T6050 wake"); + return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, help='keep build and result files here') + parser.add_argument('--cc', default='cc') + parser.add_argument('--old-ref', help='compile and run apple_wdt.c from this revision') + parser.add_argument('--mutation', help='apply a named mutation and expect failure') + args = parser.parse_args() + + source = show(args.old_ref, DRIVER) + body = extract_body(source) + if args.old_ref: + t6050_part = '#define SKIP_T6050_SLEEP_HELPERS 1\n' + else: + t6050_src = show(None, SLEEP_T6050) + t6050_helpers = extract_t6050_wdt_helpers(t6050_src) + body, t6050_helpers = apply_mutation(body, t6050_helpers, args.mutation) + t6050_part = T6050_PRELUDE + t6050_helpers + + code = PREFIX + body + t6050_part + MAIN + + def run(out): + out.mkdir(parents=True, exist_ok=True) + cfile, exe = out / 'apple-wdt.c', out / 'apple-wdt' + cfile.write_text(code) + subprocess.run([args.cc, '-std=gnu11', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-unused-parameter', '-Wno-unused-function', + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', + str(cfile), '-o', str(exe)], check=True) + res = subprocess.run([str(exe)], capture_output=True, text=True) + print(res.stdout + res.stderr, end='') + return res.returncode + + if args.out: + return run(args.out) + with tempfile.TemporaryDirectory(prefix='apple-wdt-') as out: + return run(Path(out)) + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 26b49869112881..90460b60ee5ce4 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -113,6 +113,13 @@ def mutations(flag, names, base, expect=KILL): 'binding-lifetime-tests.py': [(out(), PASS)] + mutations('--mutation', ('no-close', 'no-join'), out()), 'apple-pwm-pm-tests.py': [([], PASS), (['--negative-control'], PASS)], + # 70a00e583b032 underflows get_timeleft() on cur > bite and ignores the reconfig reg. + 'apple-wdt-tests.py': [(out(), PASS), + (out() + ['--old-ref', '70a00e583b032'], KILL)] + + mutations('--mutation', ('ignore-sleep-handoff', 'no-bark-in-start', 'no-status-clear', + 'reconfig-before-bark', 'register-after-arm', + 'hwrunning-after-arm', 'no-wd1-adopt', + 'no-t6050-wake-restore'), out()), 'apple-m4-pmu-tests.py': [([], PASS)] + mutations('--mutation', ('m1-layout', 'cycles-anywhere', 'expose-8-9', 'flags-in-event'), []), 'apple-dart-dapf-tests.py': [(out(), PASS)] From 67f0883910025e639cebe9abf66c243771466926 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 01:53:08 -0800 Subject: [PATCH 0909/1514] arm64: dts: apple: t6050: add watchdog simple-reconfig register Add the optional "reconfig" register (<0x2 0x8833002c 0x0 0x4>) and reg-names ("wdt", "reconfig") to watchdog@28836c000 in t6050-die0.dtsi so apple_wdt selects WD2 bark-IRQ simple-reconfig mode on T6050 boards for clean cold resets on watchdog expiry and reboot. Signed-off-by: Jeff Queisser --- arch/arm64/boot/dts/apple/t6050-die0.dtsi | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t6050-die0.dtsi b/arch/arm64/boot/dts/apple/t6050-die0.dtsi index 1d6887ef8bde1e..6643e2d66215ed 100644 --- a/arch/arm64/boot/dts/apple/t6050-die0.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-die0.dtsi @@ -39,7 +39,9 @@ wdt: watchdog@28836c000 { compatible = "apple,t6050-wdt", "apple,t8103-wdt"; - reg = <0x2 0x8836c000 0x0 0x4000>; + reg = <0x2 0x8836c000 0x0 0x4000>, + <0x2 0x8833002c 0x0 0x4>; + reg-names = "wdt", "reconfig"; clocks = <&clkref>; interrupts = ; }; From 23fd5c0337d571b1f438045d02bccbc7c3f32e7c Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Sun, 15 Nov 2026 09:23:00 -0300 Subject: [PATCH 0910/1514] drm/asahi: hw: t6041: keep the 25G83 limiter start on 40 cores The 40-core 25G83 configuration overlays the power configuration words measured on a running 25F84. The first three, +0x0 = 1, +0x44 = 0xc and +0x9c = 338.0, are state the firmware's performance limiter writes while it runs. Started with them, the 25G83 firmware lowers the limit at +0x48 on cold GPU power-ups and never raises it: on a J575C it reached 162 of 1000 after 6,000 short Vulkan clients, and the GPU ran at 46 % of its speed until a reboot. Leave those three at the 25G83 starting values, as the M4 Pro and the J616C run. The limit then stays at 1000. Closes #1949 Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- drivers/gpu/drm/asahi/hw/t6041.rs | 19 ++++++++++++++++++- tools/asahi/g17-t6041-initdata-tests.py | 13 +++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index 2843d74a7be238..f2b4a464089da2 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -410,16 +410,33 @@ const CHIP: v25g83::Chip = v25g83::Chip { cs_perf_table: false, }; -/// [`CHIP`] for 25G83: its hardware data has 0 at `+0x2610`. +/// [`CHIP`] for 25G83: its hardware data has 0 at `+0x2610`, and its power configuration keeps +/// the 25G83 starting values of the performance limiter ([`POWER_CONFIG_WORDS_25G83`]). /// /// 25F84 runs with 1 there. On 25G83 the 40-core J614C then accepts work and marks it done, /// but the GPU never runs it: no completion, no fault, every job times out. With 0, which is /// also what the J616C's 25G83 contents have, compute and render work run. const CHIP_25G83: v25g83::Chip = v25g83::Chip { hw_data_words: HW_DATA_WORDS_25G83, + power_config_words: POWER_CONFIG_WORDS_25G83, ..CHIP }; +/// [`POWER_CONFIG_WORDS`] without its first three words, `+0x0 = 1`, `+0x44 = 0xc` and +/// `+0x9c = 338.0`. +/// +/// They are state the firmware writes into its performance limiter while it runs (it sets +/// `+0x44` to 0xc itself, and `+0x9c` reaches 338.0 once the limit is at its floor), measured +/// from a running 25F84. Started with them, the 25G83 firmware lowers the limit at `+0x48` +/// (1000 at boot) on cold GPU power-ups and never raises it again: on the 40-core J575C it +/// reached 162 after 6,000 short Vulkan clients and the GPU ran at 46 % of its speed until a +/// reboot. With the 25G83 starting values (`+0x44 = 1`, as the M4 Pro and the J616C run), +/// the limit stays at 1000. +const POWER_CONFIG_WORDS_25G83: &[(usize, u32, usize)] = match POWER_CONFIG_WORDS { + [(0x0, 0x1, 1), (0x44, 0xc, 1), (0x9c, 0x43a9_0000, 1), rest @ ..] => rest, + _ => panic!("the first T6041 power configuration words must be +0x0, +0x44 and +0x9c"), +}; + /// [`HW_DATA_WORDS`] without its last word, `+0x2610 = 1`. const HW_DATA_WORDS_25G83: &[(usize, u32, usize)] = match HW_DATA_WORDS.split_last() { Some((&(0x2610, 1, 1), rest)) => rest, diff --git a/tools/asahi/g17-t6041-initdata-tests.py b/tools/asahi/g17-t6041-initdata-tests.py index f2459ce46bb7f2..f532332f7c6cfb 100644 --- a/tools/asahi/g17-t6041-initdata-tests.py +++ b/tools/asahi/g17-t6041-initdata-tests.py @@ -112,7 +112,8 @@ def item(source, start): "const CHIP_25G83: ", "const HW_DATA_WORDS: ", "const HW_DATA_WORDS_25G83: ", - "const POWER_CONFIG_WORDS", + "const POWER_CONFIG_WORDS: ", + "const POWER_CONFIG_WORDS_25G83: ", ] J616C_ITEMS = [ @@ -226,7 +227,15 @@ def aux(name, rows): let (hw_g83, power_g83, region_g83) = build(t6041::CHIP_ID, &t6041::REGISTER_WINDOWS_25G83, &[], &t6041::PERF, &T6041_OPPS, &T6041_AUX, &t6041::CHIP_25G83, &t6041::REGION_C, 40); println!("T6041 25G83 initialization objects built"); - assert_eq!(power_g83, power, "the register map changes only the hardware data"); + // The power configuration keeps the 25G83 starting values of the performance limiter. + let word = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + let changed = (0..power.len() / 4).map(|i| 4 * i) + .filter(|&at| word(&power, at) != word(&power_g83, at)).collect::>(); + assert_eq!(changed, [0x0, 0x44, 0x9c], "25G83 power configuration: only the limiter start"); + assert_eq!([word(&power, 0x0), word(&power, 0x44), word(&power, 0x9c)], [1, 0xc, 0x43a9_0000], + "25F84 limiter state"); + assert_eq!([word(&power_g83, 0x0), word(&power_g83, 0x44), word(&power_g83, 0x9c)], [0, 1, 0], + "25G83 limiter start"); assert_eq!(region_g83, region, "the register map changes only the hardware data"); let map = 0x640..0x640 + REGISTER_MAP_SLOTS * core::mem::size_of::(); let outside = |a: &[u8], b: &[u8]| a.iter().zip(b).enumerate() From 7023eff4a6993428412c926d0594f5f185d02acb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:25:40 +1100 Subject: [PATCH 0911/1514] drm/apple: send HDR10 static metadata across all DCPAV transports Extend HDR10 static metadata (DCPAV selector 0x15 SetHDRStaticMetadata and selector 0x14 StopInfoFrame) from desktop 26.6 compact EPIC alone to all IOMFB-template external outputs, including legacy EPIC (12.3/13.5/ 14.7) and AFKv2 (firmware 27.x MCDP29xx/MCDP2900 converters and H17P external outputs): - Move the pinned AV service and per-link metadata cache from dcp_desktop_state into apple_dcp and bind dcpav-service-epic for both legacy and AFKv2 external AV classes (DCPDPService, DCPDP13Service, AppleDCPDP2HDMI, AppleDCPMCDP29XX, AppleDCPMCDP2900). - Dispatch 0x15/0x14 via afk_send_command_len() on wire_v2 endpoints and afk_send_command_with_reply_len() on legacy/compact endpoints. - Track a link generation counter so stale or failed transport replies never latch sent_valid or suppress subsequent retries, and forget link metadata on every power-off path. - Validate Type 1 HDR_OUTPUT_METADATA blobs in atomic check and align DSC PQ ranking with DCP-managed compression. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 6 + drivers/gpu/drm/apple/dcp-hdr-metadata.h | 9 +- drivers/gpu/drm/apple/dcp-internal.h | 23 ++- drivers/gpu/drm/apple/dcp.c | 40 +--- .../gpu/drm/apple/epic/dpavservep-v14-test.c | 1 + drivers/gpu/drm/apple/epic/dpavservep.c | 16 ++ drivers/gpu/drm/apple/iomfb.c | 176 +++++++++++------- drivers/gpu/drm/apple/iomfb_h17p.c | 2 +- drivers/gpu/drm/apple/iomfb_internal.h | 2 + drivers/gpu/drm/apple/iomfb_template.c | 7 + drivers/gpu/drm/apple/iomfb_v12_3.c | 2 +- drivers/gpu/drm/apple/iomfb_v13_3.c | 2 +- drivers/gpu/drm/apple/iomfb_v14_7_tpl.c | 2 +- drivers/gpu/drm/apple/iomfb_v26_6_desktop.c | 2 +- drivers/gpu/drm/apple/iomfb_v27.c | 2 +- drivers/gpu/drm/apple/parser.c | 17 +- drivers/gpu/drm/apple/parser.h | 3 +- .../drivers/gpu/apple-dcp/display.py | 160 +++++++++++++++- .../selftests/drivers/gpu/apple-dcp/edid.py | 52 +++++- .../selftests/drivers/gpu/apple-dcp/rate.py | 24 ++- 20 files changed, 402 insertions(+), 146 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index f4cc3f9ec8c75a..fc0c32bb540860 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -53,6 +53,7 @@ #include "apple_boot_display.h" #include "apple_resume.h" +#include "dcp-hdr-metadata.h" #include "dcp.h" #include "plane.h" #include "iomfb_m4.h" @@ -959,8 +960,13 @@ static int apple_connector_atomic_check(struct drm_connector *conn, { struct drm_connector_state *old = drm_atomic_get_old_connector_state(state, conn); struct drm_connector_state *new = drm_atomic_get_new_connector_state(state, conn); + const struct drm_property_blob *blob = new->hdr_output_metadata; struct drm_crtc_state *crtc_state; + if (blob && (blob->length != sizeof(struct hdr_output_metadata) || + !dcp_hdr_is_type1(blob->data))) + return -EINVAL; + if (!new->crtc || (old->colorspace == new->colorspace && drm_connector_atomic_hdr_metadata_equal(old, new))) return 0; diff --git a/drivers/gpu/drm/apple/dcp-hdr-metadata.h b/drivers/gpu/drm/apple/dcp-hdr-metadata.h index 15937ac47fe9a4..a3815e954065a8 100644 --- a/drivers/gpu/drm/apple/dcp-hdr-metadata.h +++ b/drivers/gpu/drm/apple/dcp-hdr-metadata.h @@ -1,6 +1,6 @@ /* SPDX-License-Identifier: GPL-2.0-only OR MIT */ /* - * HDR10 static metadata for the DCPAV service of desktop 26.x DCPs. + * HDR10 static metadata for the DCPAV service. * * The display's Dynamic Range and Mastering InfoFrame is link state the * firmware builds itself: the host sends DCPAV selector 0x15 @@ -62,6 +62,11 @@ #define DCP_HDR_STOP_STATUS 0x70 #define DCP_HDR_INFOFRAME_DRM 0x87 +static inline bool dcp_hdr_is_type1(const struct hdr_output_metadata *hdr) +{ + return !hdr->metadata_type && !hdr->hdmi_metadata_type1.metadata_type; +} + /* The 24-byte Type 1 body of @hdr; -EINVAL unless it is a Type 1 block. */ static inline int dcp_hdr_data(u8 data[DCP_HDR_DATA_SIZE], const struct hdr_output_metadata *hdr) @@ -69,7 +74,7 @@ static inline int dcp_hdr_data(u8 data[DCP_HDR_DATA_SIZE], const struct hdr_metadata_infoframe *t1 = &hdr->hdmi_metadata_type1; unsigned int i; - if (hdr->metadata_type || t1->metadata_type) + if (!dcp_hdr_is_type1(hdr)) return -EINVAL; for (i = 0; i < 3; i++) { put_unaligned_le16(t1->display_primaries[i].x, data + i * 4); diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index bd48c637903716..27886edb5119c3 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -411,18 +411,6 @@ struct dcp_desktop_state { u32 vrr_min_on, vrr_min_off, vrr_min_sent; /* The frame's colour matrix, sent after an adaptive sync update. */ struct iomfb_set_matrix_req matrix; - /* - * HDR10 static metadata (external processors): the pinned - * dcpav-service-epic service, the Type 1 body last sent on this link - * (taken or refused), if any, and whether the firmware took one, so - * that the link carries a Dynamic Range and Mastering InfoFrame. - * hdr_lock protects all of them. - */ - spinlock_t hdr_lock; - struct apple_epic_service *av_service; - u8 hdr_sent[24]; - bool hdr_sent_valid; - bool hdr_infoframe; u32 present_id; bool present_pending; /* @@ -825,6 +813,17 @@ struct apple_dcp { bool typec_hpd_held; bool use_timestamps; bool vrr_enabled; + struct { + /* Pins the AV service and tracks HDR10 metadata for its link. */ + spinlock_t lock; + struct apple_epic_service *service; + u64 generation; + u8 sent[24]; + bool sent_valid; + bool infoframe; + } hdr; + /* The selected IOMFB backend programs catalogue colour IDs and PQ surfaces. */ + bool iomfb_template_pq; /* * The mode set asks for a PQ signal; output_pq: the one set carries it; * output_edr: a panel shows the PQ content as EDR, edr_sent: swaps diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index f0b4d13341a78c..70e39123e62462 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -4402,37 +4402,7 @@ static const struct apple_epic_service_ops dcp_compact_aux_ops[] = { static void dcp_av_service_init(struct apple_epic_service *service, const char *name, const char *class, s64 unit) { - struct dcp_desktop_state *d = service->ep->dcp->desktop; - struct apple_epic_service *old; - - service = afk_service_get(service); - if (!service) - return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - old = d->av_service; - d->av_service = service; - d->hdr_sent_valid = false; - d->hdr_infoframe = false; - } - if (old) - afk_service_put(old); -} - -static void dcp_av_service_teardown(struct apple_epic_service *service) -{ - struct dcp_desktop_state *d = service->ep->dcp->desktop; - bool owned; - - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - owned = d->av_service == service; - if (owned) { - d->av_service = NULL; - d->hdr_sent_valid = false; - d->hdr_infoframe = false; - } - } - if (owned) - afk_service_put(service); + dcp_hdr_service_bind(service); } static const struct apple_epic_service_ops dcp_ext_av_service_ops[] = { @@ -4440,7 +4410,7 @@ static const struct apple_epic_service_ops dcp_ext_av_service_ops[] = { .name = "dcpav-service-epic", .reusable = true, .init = dcp_av_service_init, - .teardown = dcp_av_service_teardown, + .teardown = dcp_hdr_service_unbind, }, { .name = "*", @@ -5089,8 +5059,6 @@ static void _dcp_poweroff(struct apple_dcp *dcp) iomfb_poweroff_v26_6_desktop(dcp); if (dcp->edr_hm) dcp->edr_restart = true; - /* The link set up again starts without HDR10 metadata. */ - dcp_hdr_metadata_forget(dcp); break; case DCP_FIRMWARE_V_26_6: iomfb_v26_6_poweroff(dcp); @@ -5112,6 +5080,8 @@ static void _dcp_poweroff(struct apple_dcp *dcp) WARN_ONCE(true, "Unexpected firmware version: %u\n", dcp->fw_compat); break; } + /* The link set up again starts without HDR10 metadata. */ + dcp_hdr_metadata_forget(dcp); } static void dcp_resume_enable_irq(void *ctx) @@ -7516,7 +7486,6 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->desktop = devm_kzalloc(dev, sizeof(*dcp->desktop), GFP_KERNEL); if (!dcp->desktop) return -ENOMEM; - spin_lock_init(&dcp->desktop->hdr_lock); /* * The opaque client identity of the IOMFB calls. The firmware's * own client passes a kernel pointer there; pass a random value @@ -7560,6 +7529,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp_fabric_init(dcp); spin_lock_init(&dcp->mode_state.lock); spin_lock_init(&dcp->metadata.lock); + spin_lock_init(&dcp->hdr.lock); mutex_init(&dcp->dcpavserv.lock); INIT_WORK(&dcp->dcpavserv.close_wq, dcpavserv_close_work); ret = dcpavserv_edid_retry_init(dcp); diff --git a/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c index 1912f87454e5d6..c1e06f94af4b1a 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c +++ b/drivers/gpu/drm/apple/epic/dpavservep-v14-test.c @@ -152,6 +152,7 @@ static struct av14_test *av14_setup(struct kunit *test, bool native) t->dcp->external_native = native; mutex_init(&t->dcp->hpd_mutex); mutex_init(&t->dcp->dcpavserv.lock); + spin_lock_init(&t->dcp->hdr.lock); INIT_WORK(&t->dcp->dcpavserv.close_wq, dcpavserv_close_work); /* Queued work runs here, in test context: av14_run_close_work() */ disable_work(&t->dcp->dcpavserv.close_wq); diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index b3460c45c1f564..96bbac2cf72783 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -19,6 +19,7 @@ #include "../dcp-internal.h" #include "../dcp-fabric.h" #include "../connector.h" +#include "../iomfb_internal.h" #include "../trace.h" static void dcpavserv_notify_edid(struct apple_epic_service *service) @@ -35,6 +36,16 @@ static void dcpavserv_notify_edid(struct apple_epic_service *service) schedule_work(&connector->hotplug_wq); } +static bool dcpavserv_hdr_class(const char *class) +{ + return class && + (!strcmp(class, "DCPDP13Service") || + !strcmp(class, "DCPDPService") || + !strcmp(class, "AppleDCPDP2HDMI") || + !strcmp(class, "AppleDCPMCDP29XX") || + !strcmp(class, "AppleDCPMCDP2900")); +} + static bool dcpavserv_identity(struct apple_epic_service *service, const char *name, const char *class, s64 unit) { @@ -148,6 +159,9 @@ static void dcpavserv_init(struct apple_epic_service *service, const char *name, dcp->dcpavserv.opened = NULL; dcp->dcpavserv.opened_epoch = 0; service->cookie = &dcp->dcpavserv; + if (!dcp->desktop && !dcp_is_ext26(dcp) && + dcpavserv_hdr_class(class)) + dcp_hdr_service_bind(service); complete(&dcp->dcpavserv.enable_completion); published = true; } @@ -193,6 +207,7 @@ static void dcpavserv_teardown(struct apple_epic_service *service) mutex_lock(&dcp->dcpavserv.lock); if (dcp->dcpavserv.service == service) { + dcp_hdr_service_unbind(service); dcp->dcpavserv.enabled = false; dcp->dcpavserv.service = NULL; dcp->dcpavserv.epoch++; @@ -222,6 +237,7 @@ void dpavservep_detach(struct apple_dcp *dcp) dcp->dcpavserv.opened_epoch = 0; reinit_completion(&dcp->dcpavserv.enable_completion); if (service) { + dcp_hdr_service_unbind(service); afk_service_retire(service); dcpavserv_invalidate_edid(dcp); } diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 1de9af271a4020..805c715f13f31f 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -2463,7 +2463,13 @@ int dcp_modes_replace(struct apple_dcp *dcp, struct dcp_parse_ctx *ctx, ctx->metadata_timing = dcp_firmware_metadata_enabled(dcp); ctx->sdr_default_rgb = dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp); - ctx->pq_dsc = dcp->fw_compat == DCP_FIRMWARE_V_27_0; + /* + * The template sends a timing and colour ID to DCP. It can + * select an entry the timing lists as needing DSC, just as + * for SDR. The parser still rejects unsafe PQ entries. + */ + ctx->pq_dsc = READ_ONCE(dcp->iomfb_template_pq) && + !dcp_has_panel(dcp); } ctx->zero_vrr_range_fallback = dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; ctx->internal_present_deadline = dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP; @@ -3185,18 +3191,14 @@ int dcp_takeover_trial(struct platform_device *pdev, const char **reason) } /* - * PQ output goes through the IOMFB template's mode set, which picks the - * timing's PQ element (see dcp_display_mode.pq): the desktop 26.x firmware, - * the external H17P processor and the firmware 27 external processors. The - * other processors, and the firmware 27 panel, keep SDR. + * The template chooses a PQ colour ID and tags the surfaces. The caller + * checks for that ID in the current timing catalogue. Panels keep their + * existing SDR/EDR path, with the desktop template retaining PQ support. */ static bool dcp_hdr_output_supported(struct apple_dcp *dcp) { - if (iomfb_is_m4(dcp)) - return false; - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp)); + return READ_ONCE(dcp->iomfb_template_pq) && + (!dcp_has_panel(dcp) || dcp->desktop); } /* @@ -3259,20 +3261,66 @@ static bool dcp_crtc_bt2020(struct apple_dcp *dcp, struct drm_crtc *crtc, return conn_state && conn_state->colorspace == DRM_MODE_COLORIMETRY_BT2020_RGB; } -/* - * HDR10 static metadata is link state on the external processors: a link - * set up again (mode set, power off) starts without it. - */ -void dcp_hdr_metadata_forget(struct apple_dcp *dcp) +static void dcp_hdr_reset_locked(struct apple_dcp *dcp) { - struct dcp_desktop_state *d = dcp->desktop; + lockdep_assert_held(&dcp->hdr.lock); + dcp->hdr.generation++; + dcp->hdr.sent_valid = false; + dcp->hdr.infoframe = false; +} - if (!d) +void dcp_hdr_service_bind(struct apple_epic_service *service) +{ + struct apple_dcp *dcp = service->ep->dcp; + struct apple_epic_service *old; + + service = afk_service_get(service); + if (!service) return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - d->hdr_sent_valid = false; - d->hdr_infoframe = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + old = dcp->hdr.service; + WRITE_ONCE(dcp->hdr.service, service); + dcp_hdr_reset_locked(dcp); } + if (old) + afk_service_put(old); +} + +void dcp_hdr_service_unbind(struct apple_epic_service *service) +{ + struct apple_dcp *dcp = service->ep->dcp; + bool owned; + + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + owned = dcp->hdr.service == service; + if (owned) { + WRITE_ONCE(dcp->hdr.service, NULL); + dcp_hdr_reset_locked(dcp); + } + } + if (owned) + afk_service_put(service); +} + +/* A link set up again starts without the previous HDR10 metadata. */ +void dcp_hdr_metadata_forget(struct apple_dcp *dcp) +{ + guard(spinlock_irqsave)(&dcp->hdr.lock); + dcp_hdr_reset_locked(dcp); +} + +static int dcp_hdr_send(struct apple_epic_service *service, + const void *msg, size_t msg_len, + void *reply, size_t reply_len, + u32 *retcode, size_t *received) +{ + if (service->ep->wire_v2) + return afk_send_command_len(service, EPIC_SUBTYPE_STD_SERVICE, + msg, msg_len, reply, reply_len, + retcode, received); + return afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, + msg, msg_len, reply, reply_len, + retcode, received); } /* @@ -3283,33 +3331,34 @@ void dcp_hdr_metadata_forget(struct apple_dcp *dcp) */ static void dcp_hdr_infoframe_stop(struct apple_dcp *dcp) { - struct dcp_desktop_state *d = dcp->desktop; struct apple_epic_service *service = NULL; u8 msg[DCP_HDR_STOP_SIZE], reply[DCP_HDR_STOP_SIZE] = {}; size_t received = 0; + u64 generation; u32 retcode = 0; int ret; - if (!d || READ_ONCE(dcp->crashed)) + if (READ_ONCE(dcp->crashed)) return; - scoped_guard(spinlock_irqsave, &d->hdr_lock) - if (d->hdr_infoframe) - service = afk_service_get(d->av_service); + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + generation = dcp->hdr.generation; + if (dcp->hdr.infoframe) + service = afk_service_get(dcp->hdr.service); + } if (!service) return; dcp_hdr_stop_message(msg); - ret = afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, - msg, sizeof(msg), reply, sizeof(reply), - &retcode, &received); + ret = dcp_hdr_send(service, msg, sizeof(msg), reply, sizeof(reply), + &retcode, &received); ret = dcp_hdr_stop_reply(ret, retcode, reply, received); if (ret) dev_warn(dcp->dev, "HDR InfoFrame not stopped: %d\n", ret); else dev_dbg(dcp->dev, "HDR InfoFrame stopped\n"); - scoped_guard(spinlock_irqsave, &d->hdr_lock) - if (d->av_service == service) - d->hdr_infoframe = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) + if (dcp->hdr.service == service && dcp->hdr.generation == generation) + dcp->hdr.infoframe = false; afk_service_put(service); } @@ -3318,8 +3367,8 @@ bool dcp_hdr_metadata_live(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && - !dcp_has_panel(dcp); + return READ_ONCE(dcp->iomfb_template_pq) && !dcp_has_panel(dcp) && + (dcp->desktop || READ_ONCE(dcp->hdr.service)); } /* @@ -3360,27 +3409,20 @@ static void dcp_edr_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) { - struct dcp_desktop_state *d = dcp->desktop; - const struct drm_connector_state *conn_state = NULL; - struct drm_connector_state *state; - struct drm_connector *connector; + const struct drm_connector_state *conn_state; struct apple_epic_service *service; u8 data[DCP_HDR_DATA_SIZE], msg[DCP_HDR_MSG_SIZE]; u8 reply[DCP_HDR_MSG_SIZE] = {}; size_t received = 0; + u64 generation; u32 retcode = 0; bool same; - int i, ret; + int transport, ret; - if (!d || !dcp->output_pq || READ_ONCE(dcp->crashed) || + if (!dcp->output_pq || READ_ONCE(dcp->crashed) || !dcp_hdr_metadata_live(to_apple_crtc(crtc)->dcp)) return; - for_each_new_connector_in_state(commit, connector, state, i) - if (state->crtc == crtc) - conn_state = state; - if (!conn_state && dcp->connector && dcp->connector->base.state && - dcp->connector->base.state->crtc == crtc) - conn_state = dcp->connector->base.state; + conn_state = dcp_crtc_connector_state(dcp, crtc, commit); if (!conn_state || !conn_state->hdr_output_metadata || conn_state->hdr_output_metadata->length != sizeof(struct hdr_output_metadata)) return; @@ -3390,35 +3432,32 @@ static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, return; /* Most frames change nothing: compare before pinning the service. */ - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - same = d->hdr_sent_valid && !memcmp(d->hdr_sent, data, sizeof(data)); - service = same ? NULL : afk_service_get(d->av_service); + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + generation = dcp->hdr.generation; + same = dcp->hdr.sent_valid && !memcmp(dcp->hdr.sent, data, sizeof(data)); + service = same ? NULL : afk_service_get(dcp->hdr.service); } if (!service) return; dcp_hdr_message(msg, data); - ret = afk_send_command_with_reply_len(service, EPIC_SUBTYPE_STD_SERVICE, - msg, sizeof(msg), reply, sizeof(reply), - &retcode, &received); - ret = dcp_hdr_reply(ret, retcode, reply, received); - /* - * A block the firmware refused is not sent again on every frame (the - * command is synchronous): only a new block, a new mode set or a new - * service instance retries. - */ + transport = dcp_hdr_send(service, msg, sizeof(msg), reply, sizeof(reply), + &retcode, &received); + ret = dcp_hdr_reply(transport, retcode, reply, received); if (ret) dev_warn_ratelimited(dcp->dev, "HDR static metadata not taken: %d\n", ret); else dev_dbg(dcp->dev, "HDR static metadata: MaxCLL %u MaxFALL %u mastering %u/%u\n", get_unaligned_le16(data + 20), get_unaligned_le16(data + 22), get_unaligned_le16(data + 16), get_unaligned_le16(data + 18)); - scoped_guard(spinlock_irqsave, &d->hdr_lock) { - if (d->av_service == service) { - memcpy(d->hdr_sent, data, sizeof(data)); - d->hdr_sent_valid = true; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + if (dcp->hdr.service == service && dcp->hdr.generation == generation) { + /* Without a valid reply, the previous block may no longer be active. */ + dcp->hdr.sent_valid = !transport && ret != -EPROTO; + if (dcp->hdr.sent_valid) + memcpy(dcp->hdr.sent, data, sizeof(data)); if (!ret) - d->hdr_infoframe = true; + dcp->hdr.infoframe = true; } } afk_service_put(service); @@ -4320,6 +4359,7 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) { struct platform_device *pdev = to_apple_crtc(crtc)->dcp; struct apple_dcp *dcp = platform_get_drvdata(pdev); + bool route_ready; if (iomfb_is_m4(dcp)) { struct drm_plane_state *plane = drm_atomic_get_new_plane_state(commit, @@ -4372,13 +4412,13 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) return; } - if ((dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - dcp->fw_compat == DCP_FIRMWARE_V_27_0) && - READ_ONCE(dcp->mode_state.valid) && dcp->connector && - READ_ONCE(dcp->connector->connected)) { + route_ready = dcp_crtc_route_ready(crtc, commit, true); + if (READ_ONCE(dcp->mode_state.valid) && dcp->connector && + READ_ONCE(dcp->connector->connected) && + !(to_apple_atomic_state(commit)->failed_routes & drm_crtc_mask(crtc))) { /* A panel's EDR switches without a mode set (dcp_edr_live()). */ dcp_edr_sync(dcp, crtc, commit); - if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) + if (route_ready) dcp_hdr_metadata_sync(dcp, crtc, commit); } @@ -4397,7 +4437,7 @@ void dcp_flush(struct drm_crtc *crtc, struct drm_atomic_commit *commit) * firmware has reported the display back. */ if ((to_apple_atomic_state(commit)->failed_routes & drm_crtc_mask(crtc)) || - !dcp_crtc_route_ready(crtc, commit, true) || + !route_ready || !READ_ONCE(dcp->mode_state.valid) || !dcp->connector || !dcp->connector->connected) { schedule_work(&dcp->vblank_wq); return; diff --git a/drivers/gpu/drm/apple/iomfb_h17p.c b/drivers/gpu/drm/apple/iomfb_h17p.c index 18e7b936970381..8476c1ddeba9cb 100644 --- a/drivers/gpu/drm/apple/iomfb_h17p.c +++ b/drivers/gpu/drm/apple/iomfb_h17p.c @@ -1303,7 +1303,7 @@ void iomfb_start_h17p(struct apple_dcp *dcp) } WRITE_ONCE(dcp->pipe_enabled_h17p, false); dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) diff --git a/drivers/gpu/drm/apple/iomfb_internal.h b/drivers/gpu/drm/apple/iomfb_internal.h index 1e905637c3786d..ba804e3618cf8e 100644 --- a/drivers/gpu/drm/apple/iomfb_internal.h +++ b/drivers/gpu/drm/apple/iomfb_internal.h @@ -124,6 +124,8 @@ u8 dcp_crtc_eotf(struct apple_dcp *dcp, struct drm_crtc *crtc, int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit); void dcp_hdr_metadata_forget(struct apple_dcp *dcp); +void dcp_hdr_service_bind(struct apple_epic_service *service); +void dcp_hdr_service_unbind(struct apple_epic_service *service); int iomfb_ext26_blank(struct apple_dcp *dcp); bool iomfb_ext26_backing_fresh(struct apple_dcp *dcp, struct drm_framebuffer *fb); int iomfb_ext26_retain_epoch(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 0e9064dcb289b9..b783cb0d1a9b40 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4919,6 +4919,13 @@ static void dcp_started(struct apple_dcp *dcp, void *data, void *cookie) iomfb_get_color_remap_mode(dcp, false, &color_remap, init_1, cookie); } +/* These sessions program the catalogue's colour ID and tag PQ surfaces. */ +static void iomfb_template_start(struct apple_dcp *dcp) +{ + WRITE_ONCE(dcp->iomfb_template_pq, true); + dcp_start_signal(dcp, false, dcp_started, NULL); +} + void DCP_FW_NAME(iomfb_shutdown)(struct apple_dcp *dcp) { #if DCP_FW_DESKTOP_26(DCP_FW_VER) diff --git a/drivers/gpu/drm/apple/iomfb_v12_3.c b/drivers/gpu/drm/apple/iomfb_v12_3.c index fba8add2e1aad0..c6726efea47865 100644 --- a/drivers/gpu/drm/apple/iomfb_v12_3.c +++ b/drivers/gpu/drm/apple/iomfb_v12_3.c @@ -111,7 +111,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v13_3.c b/drivers/gpu/drm/apple/iomfb_v13_3.c index 1807791e92afb8..3521abccf038e6 100644 --- a/drivers/gpu/drm/apple/iomfb_v13_3.c +++ b/drivers/gpu/drm/apple/iomfb_v13_3.c @@ -116,7 +116,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c index 0679ee5a13a7c3..88e7909ec826d0 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_tpl.c @@ -124,7 +124,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c index 8778ccf269bb2c..c718639d52d20f 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c @@ -353,7 +353,7 @@ void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/iomfb_v27.c b/drivers/gpu/drm/apple/iomfb_v27.c index a7d7d6b93f341d..c2a6d2413a45dc 100644 --- a/drivers/gpu/drm/apple/iomfb_v27.c +++ b/drivers/gpu/drm/apple/iomfb_v27.c @@ -817,7 +817,7 @@ bool iomfb_v27_callback_size_valid(unsigned int tag, u32 input, u32 output) void iomfb_start_v27(struct apple_dcp *dcp) { dcp->cb_handlers = cb_handlers; - dcp_start_signal(dcp, false, dcp_started, NULL); + iomfb_template_start(dcp); } #undef DCP_FW_VER diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index de2cbc5a605aa7..e4bca4075828a6 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -595,25 +595,22 @@ static unsigned int pq_mode_rank(const struct color_mode *cmode) return rank + (cmode->depth == 10); } -/* A PQ element that needs DSC ranks below every one that does not. */ -#define PQ_RANK_NO_DSC 4 - /* - * @dsc: firmware 27, whose processor compresses an element the timing lists - * as needing DSC itself, as for SDR: such a PQ element is usable too. + * @dsc: the modeset delegates compression of DSC-required elements to DCP. */ static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, struct color_mode *cmode, const struct timing_color_restrictions *limits, bool dsc) { unsigned int rank = pq_mode_rank(cmode); + bool needs_dsc = timing_color_contains(&limits->dsc_required, cmode->id); - if (!rank || timing_color_contains(&limits->unsafe, cmode->id)) - return; - if (!timing_color_contains(&limits->dsc_required, cmode->id)) - rank += PQ_RANK_NO_DSC; - else if (!dsc) + if (!rank || (needs_dsc && !dsc) || + timing_color_contains(&limits->unsafe, cmode->id)) return; + + /* Break equal format and depth ranks in favour of no compression. */ + rank = 2 * rank + !needs_dsc; if (rank < *best_rank) return; if (rank > *best_rank) diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 607aa029adca73..2f92a7a9eb4d95 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -42,8 +42,7 @@ struct dcp_parse_ctx { */ bool sdr_default_rgb; /* - * A firmware 27 processor: it compresses a PQ element the timing lists - * as needing DSC itself, so such an element is usable for PQ. + * The modeset delegates compression of DSC-required elements to DCP. */ bool pq_dsc; /* diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index dc3a99fcaf6cae..5078e40f148fe3 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -598,8 +598,10 @@ def brightness_commit(root): def hdr_metadata(root): - """HDR10 static metadata message for DCPAV selector 0x15, byte for byte.""" - header = (root / 'drivers/gpu/drm/apple/dcp-hdr-metadata.h').read_text() + """HDR10 metadata wire encoding and caching over the AV service (legacy and AFKv2).""" + apple = root / 'drivers/gpu/drm/apple' + header = (apple / 'dcp-hdr-metadata.h').read_text() + iomfb = (apple / 'iomfb.c').read_text() header = '\n'.join(line for line in header.splitlines() if not line.startswith('#include')) header = header.replace('static inline ', 'static inline __attribute__((unused)) ') @@ -655,6 +657,159 @@ def pad(raw): union { struct hdr_metadata_infoframe hdmi_metadata_type1; }; }; """ + header + r""" +typedef uint64_t u64; +#define HDMI_EOTF_SMPTE_ST2084 2 +#define EPIC_SUBTYPE_STD_SERVICE 0xc0 +#define READ_ONCE(x) (x) +#define scoped_guard(kind, lock) for (bool held = true; held; held = false) +#define lockdep_assert_held(lock) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) +#define dev_warn(...) ((void)0) +#define dev_dbg(...) ((void)0) +struct apple_dcp_afkep { bool wire_v2; }; +struct apple_epic_service { struct apple_dcp_afkep *ep; unsigned int refs; }; +struct drm_crtc { int dcp; }; +struct drm_atomic_commit { int unused; }; +struct drm_connector_state { + struct { size_t length; const void *data; } *hdr_output_metadata; +}; +struct apple_dcp { + bool output_pq, crashed; + struct { + struct apple_epic_service *service; + u64 generation; + u8 sent[DCP_HDR_DATA_SIZE]; + bool sent_valid, infoframe; + } hdr; +}; +#define to_apple_crtc(crtc) (crtc) +#define dcp_hdr_metadata_live(pdev) true +static const struct drm_connector_state *test_connector; +static int transport_result; +static u32 dcp_status; +static size_t reply_length; +static unsigned int sends, v2_sends, legacy_sends, stop_sends; +static bool reset_during_send; +static struct apple_dcp test_dcp; +static const struct drm_connector_state *dcp_crtc_connector_state( + struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) +{ + (void)dcp; (void)crtc; (void)commit; + return test_connector; +} +static struct apple_epic_service *afk_service_get(struct apple_epic_service *service) +{ + if (service) + service->refs++; + return service; +} +static void afk_service_put(struct apple_epic_service *service) +{ + assert(service->refs == 1); + service->refs--; +} +""" + block(iomfb, 'static void dcp_hdr_reset_locked(') + r""" +static int mock_hdr_command(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + u32 selector = get_unaligned_le32((const u8 *)msg + 0x04); + + assert(service->refs == 1 && type == EPIC_SUBTYPE_STD_SERVICE); + if (selector == DCP_HDR_SELECTOR_SET_STATIC) { + assert(msg_len == DCP_HDR_MSG_SIZE && capacity == DCP_HDR_MSG_SIZE); + sends++; + } else { + assert(selector == DCP_HDR_SELECTOR_STOP_INFOFRAME); + assert(msg_len == DCP_HDR_STOP_SIZE && capacity == DCP_HDR_STOP_SIZE); + stop_sends++; + } + if (reset_during_send) + dcp_hdr_reset_locked(&test_dcp); + if (transport_result) + return transport_result; + *retcode = 0; + *received = reply_length; + if (selector == DCP_HDR_SELECTOR_SET_STATIC) + put_unaligned_le32(dcp_status, (u8 *)reply + DCP_HDR_MSG_STATUS); + else + put_unaligned_le32(dcp_status, (u8 *)reply + DCP_HDR_STOP_STATUS); + return 0; +} +static int afk_send_command_len(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + assert(service->ep->wire_v2); + v2_sends++; + return mock_hdr_command(service, type, msg, msg_len, reply, capacity, retcode, received); +} +static int afk_send_command_with_reply_len(struct apple_epic_service *service, u8 type, + const void *msg, size_t msg_len, void *reply, size_t capacity, u32 *retcode, size_t *received) +{ + assert(!service->ep->wire_v2); + legacy_sends++; + return mock_hdr_command(service, type, msg, msg_len, reply, capacity, retcode, received); +} +""" + block(iomfb, 'static int dcp_hdr_send(') + block(iomfb, 'static void dcp_hdr_infoframe_stop(') + block(iomfb, 'static void dcp_hdr_metadata_sync(') + r""" +static void test_metadata_cache(struct hdr_output_metadata hdr) +{ + struct apple_dcp_afkep ep = { .wire_v2 = false }; + struct apple_epic_service service = { .ep = &ep }; + struct drm_crtc crtc = {}; + struct drm_atomic_commit commit = {}; + struct drm_connector_state conn; + __typeof__(*conn.hdr_output_metadata) blob = { sizeof(hdr), &hdr }; + + conn.hdr_output_metadata = &blob; + test_connector = &conn; + test_dcp.output_pq = true; + test_dcp.hdr.service = &service; + reply_length = DCP_HDR_MSG_SIZE; + transport_result = -EIO; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 1 && legacy_sends == 1 && !v2_sends && !test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + transport_result = 0; + reply_length = DCP_HDR_MSG_STATUS; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 2 && !test_dcp.hdr.sent_valid); + + reply_length = DCP_HDR_MSG_SIZE; + reset_during_send = true; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 3 && !test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + reset_during_send = false; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 4 && test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + + dcp_hdr_reset_locked(&test_dcp); + dcp_status = 1; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 5 && test_dcp.hdr.sent_valid && !test_dcp.hdr.infoframe); + hdr.hdmi_metadata_type1.max_cll--; + dcp_status = 0; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 6 && test_dcp.hdr.infoframe && !service.refs); + hdr.hdmi_metadata_type1.max_cll++; + transport_result = -ETIMEDOUT; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 7 && !test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + hdr.hdmi_metadata_type1.max_cll--; + transport_result = 0; + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 8 && test_dcp.hdr.sent_valid && !service.refs); + + /* AFKv2 transport (fw 27 / H17P) uses afk_send_command_len for 0x15 and 0x14. */ + ep.wire_v2 = true; + dcp_hdr_reset_locked(&test_dcp); + dcp_hdr_metadata_sync(&test_dcp, &crtc, &commit); + assert(sends == 9 && v2_sends == 1 && test_dcp.hdr.sent_valid && test_dcp.hdr.infoframe); + reply_length = DCP_HDR_STOP_SIZE; + dcp_hdr_infoframe_stop(&test_dcp); + assert(stop_sends == 1 && v2_sends == 2 && !test_dcp.hdr.infoframe && !service.refs); + puts("PASS: retry transport and short replies, discard stale replies, deduplicate completed commands, AFKv2 0x15/0x14"); +} + static const u8 expected[] = {""" + expected + r"""}; static const u8 expected_stop[] = {""" + expected_stop + r"""}; int main(void) @@ -675,6 +830,7 @@ def pad(raw): fprintf(stderr, "byte %#zx: %#x, expected %#x\n", i, msg[i], expected[i]); return 1; } + test_metadata_cache(hdr); /* Only static metadata Type 1 is sent. */ hdr.metadata_type = 1; assert(dcp_hdr_data(data, &hdr) == -EINVAL); diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 476c35ff89f7da..e49b0bb4b0d823 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -100,6 +100,7 @@ def function(file,signature): struct apple_connector { void *dcp;bool connected,edid_invalidation_pending;struct { int registration_state; } base;unsigned int hotplug_wq; }; struct apple_dcp { void *dev;int fw_compat;struct apple_dcp_afkep *dcpavservep;struct apple_connector *connector; + void *desktop; bool external_physically_absent,hpd_mutex,quiescing,typec_cable_connected;u64 typec_generation;unsigned int nr_modes; struct { int iomfb_method_profile,firmware_compat; bool fw_14_7_endpoints,afk_announced_names; unsigned int num_dptx_ports; } hw; bool ext_dead,external_native; struct { bool lock,enabled;u64 epoch;int enable_completion;struct apple_epic_service *service,*opened; @@ -112,6 +113,9 @@ def function(file,signature): '''+internal_inline(root,'dcp_fw_is_14_7')+internal_inline(root,'dcp_is_v14_7_external')+internal_inline(root,'dcp_is_v27_external')+r'''struct epic_cmd { u32 retcode;u64 rxbuf,txbuf;u32 rxlen,txlen; }; static unsigned int dma_frees,opens; +static void dcp_hdr_service_bind(struct apple_epic_service *s) { (void)s; } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) { (void)s; } + static int open_error,open_action; void dpavservep_detach(struct apple_dcp *dcp); static void afk_recv_handle_teardown(struct apple_dcp_afkep *ep, u32 channel); @@ -172,7 +176,7 @@ def function(file,signature): function('afk.h','static inline bool afk_service_matches('),function('afk.h','static inline bool afk_service_reclaimable('), function('afk.h','static inline bool\nafk_service_reinit('),function('afk.h','static inline void afk_service_discard('), function('afk.h','static inline void afk_service_publish('), - function('epic/dpavservep.c','static void dcpavserv_notify_edid('),function('epic/dpavservep.c','static bool dcpavserv_identity('), + function('epic/dpavservep.c','static void dcpavserv_notify_edid('),function('epic/dpavservep.c','static bool dcpavserv_hdr_class('),function('epic/dpavservep.c','static bool dcpavserv_identity('), '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n'+function('epic/dpavservep.c','static bool dcpavserv_admission_current('),function('epic/dpavservep.c','static int dcpavserv_prepare('), function('epic/dpavservep.c','static int dcpavserv_revalidate('),function('epic/dpavservep.c','static void dcpavserv_init('),function('epic/dpavservep.c','static void dcpavserv_invalidate_edid('), function('epic/dpavservep.c','static void dcpavserv_teardown('),function('epic/dpavservep.c','void dpavservep_detach('), @@ -663,10 +667,15 @@ def function(file, signature): '''+internal_inline(root,'dcp_is_v14_7_external')+r'''static unsigned int reads, allocations, legacy_reads, receives; static unsigned int event; static struct apple_dcp_afkep *received_ep; +static struct apple_epic_service *hdr_bound; static struct apple_epic_service *afk_service_get(struct apple_epic_service *s) { if(!s || !s->enabled || s->torndown) return NULL; s->users++; return s; } static void afk_service_put(struct apple_epic_service *s) { assert(s->users); s->users--; } +static void dcp_hdr_service_bind(struct apple_epic_service *s) +{ assert(!hdr_bound); hdr_bound=afk_service_get(s); } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) +{ if(hdr_bound==s) { hdr_bound=NULL; afk_service_put(s); } } static void afk_service_retire(struct apple_epic_service *s) { s->enabled=false;s->torndown=true; } static void drm_edid_free(const struct drm_edid *e) { if(e) { assert(allocations); allocations--; free((void *)e); } } @@ -674,7 +683,7 @@ def function(file, signature): static const struct drm_edid *dcpavserv_read_edid_inline(struct apple_epic_service *s) { struct apple_dcp *d=s->ep->dcp; - assert(!d->hpd_mutex && !d->dcpavserv.lock && s->users==2); + assert(!d->hpd_mutex && !d->dcpavserv.lock && s->users==(hdr_bound==s ? 3U : 2U)); reads++; if(event==1 || event==2) { d->typec_generation++; d->typec_cable_connected=(event==2); } if(event==3) { s->enabled=false; dcpavserv_teardown(s); } @@ -697,6 +706,7 @@ def function(file, signature): function('epic/dpavservep.c', 'static void dcpavserv_teardown('), function('dcp.c', 'static struct apple_dcp_afkep *dcp_afkep('), function('dcp.c', 'static void dcp_recv_msg('), + function('epic/dpavservep.c', 'static bool dcpavserv_hdr_class('), function('epic/dpavservep.c', 'static bool dcpavserv_identity('), '/* These scenarios model a Type-C output (dcp-fabric.c decides it in the driver). */\nstatic bool dcp_is_typec_output(struct apple_dcp *d) { (void)d; return true; }\n' + function('epic/dpavservep.c', 'static bool dcpavserv_admission_current('), function('epic/dpavservep.c', 'static int dcpavserv_prepare('), @@ -753,16 +763,26 @@ def function(file, signature): assert(connector.edid_invalidation_pending && connector.hotplug_wq && d.dcpavserv.epoch==2); /* Same slot and physical generation: CLOSE/re-OPEN gets a fresh ticket. */ s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); - assert(d.dcpavserv.service==&s && s.users==1 && d.dcpavserv.epoch==3); + assert(d.dcpavserv.service==&s && hdr_bound==&s && s.users==2 && d.dcpavserv.epoch==3); mutex_lock(&d.dcpavserv.lock); assert(!dcpavserv_edid_service_current(&d,1) && dcpavserv_edid_service_current(&d,3)); mutex_unlock(&d.dcpavserv.lock); event=0; e=dcpavserv_copy_edid(&d,3,&epoch); assert(!IS_ERR(e) && epoch==3); /* Simulate retirement in the final validation-to-publication gap. */ - s.enabled=false; dcpavserv_teardown(&s); s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); + s.enabled=false; dcpavserv_teardown(&s); assert(!hdr_bound && !s.users); s.enabled=true; assert(!dcpavserv_prepare(&s,name,class,1)); dcpavserv_init(&s,name,class,1); mutex_lock(&d.dcpavserv.lock); assert(!dcpavserv_edid_service_current(&d,epoch)); mutex_unlock(&d.dcpavserv.lock); - drm_edid_free(e); assert(d.typec_generation==3 && d.dcpavserv.epoch==5 && s.users==1); - s.enabled=false; dcpavserv_teardown(&s); + drm_edid_free(e); assert(d.typec_generation==3 && d.dcpavserv.epoch==5 && hdr_bound==&s && s.users==2); + s.enabled=false; dcpavserv_teardown(&s); assert(!hdr_bound && !s.users); + /* Firmware 27 MCDP29xx / MCDP2900 AV services bind HDR metadata on EP 0x28 too. */ + av.endpoint=0x28; d.hw.iomfb_method_profile=0; s.enabled=true; + const char *v27_classes[] = {"AppleDCPMCDP29XX", "AppleDCPMCDP2900"}; + for (size_t i = 0; i < sizeof(v27_classes) / sizeof(v27_classes[0]); i++) { + assert(!dcpavserv_prepare(&s, name, v27_classes[i], 0)); + dcpavserv_init(&s, name, v27_classes[i], 0); + assert(hdr_bound == &s && s.users == 2); + dcpavserv_teardown(&s); + assert(!hdr_bound && !s.users); + } av.wire_v2=false; av.endpoint=0x28; d.hw.iomfb_method_profile=0; d.dcpavserv.enabled=false; assert(!dcpavserv_prepare(&s,name,NULL,0)); assert(dcpavserv_prepare(&s,name,class,1)==-ENODEV); @@ -772,8 +792,26 @@ def function(file, signature): assert(!IS_ERR(e) && legacy_reads==1 && s.users==1); drm_edid_free(e); d.hw.iomfb_method_profile=0;av.wire_v2=false;d.external_physically_absent=true; mutex_lock(&d.hpd_mutex);assert(dcpavserv_edid_current(&d,0));mutex_unlock(&d.hpd_mutex); + dcpavserv_teardown(&s); + + /* The legacy AV service owns HDR metadata on both DP and HDMI. */ + const char *legacy_classes[] = {"DCPDPService", "DCPDP13Service", "AppleDCPDP2HDMI"}; + for (size_t i = 0; i < sizeof(legacy_classes) / sizeof(legacy_classes[0]); i++) { + assert(!dcpavserv_prepare(&s, name, legacy_classes[i], 0)); + dcpavserv_init(&s, name, legacy_classes[i], 0); + assert(hdr_bound == &s && s.users == 2); + dcpavserv_teardown(&s); + assert(!hdr_bound && !s.users); + } + /* The desktop command binds through its own service lifecycle. */ + struct dcp_desktop_state desktop = {}; + d.desktop = &desktop; + assert(!dcpavserv_prepare(&s, name, class, 0)); + dcpavserv_init(&s, name, class, 0); + assert(d.dcpavserv.service == &s && !hdr_bound); + dcpavserv_teardown(&s); assert(!allocations && !d.hpd_mutex && !d.dcpavserv.lock); - puts("PASS: production old/new lookup and receive, exact service admission before OPEN, delayed disconnect/replug, service detach pins, legacy transport"); + puts("PASS: production old/new lookup and receive, exact service admission before OPEN, delayed disconnect/replug, service detach pins, legacy and AFKv2 HDR binding"); } ''' return prefix + '\n'.join(parts) + suffix diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 7a0ee164cf8595..dffa976dfea2fb 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -106,6 +106,14 @@ def color(i, score, depth, eotf, colorimetry, encoding=0, dynamic=0): ycc_raw = bytearray(struct.pack('enabled) return NULL; s->users++; return s; } static void afk_service_put(struct apple_epic_service *s) { assert(s->users); s->users--; } +static void dcp_hdr_service_bind(struct apple_epic_service *s) { (void)s; } +static void dcp_hdr_service_unbind(struct apple_epic_service *s) { (void)s; } static void afk_service_retire(struct apple_epic_service *s) { assert(!*hpd_lock); s->enabled=false; s->torndown=true; } /* These H17P scenarios never queue the native 14.7 Close worker. */ static bool cancel_work_sync(struct work_struct *w) { assert(!w->scheduled); return false; } @@ -914,7 +933,8 @@ def publication(root): static int __attribute__((unused)) dcp_direct_crossbar_link(struct apple_dcp *d,bool up) { (void)d;(void)up;return 0; } ''' transport = '\n'.join(block(av,marker) for marker in [ - 'static void dcpavserv_notify_edid(', 'static bool dcpavserv_identity(', + 'static void dcpavserv_notify_edid(', 'static bool dcpavserv_hdr_class(', + 'static bool dcpavserv_identity(', 'static bool dcpavserv_admission_current(', 'static int dcpavserv_prepare(', 'static void dcpavserv_init(', 'static void dcpavserv_invalidate_edid(', 'static void dcpavserv_teardown(', 'void dpavservep_detach(', From f4743df244e33e3354b35ae337264e4337dd662e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:32:18 +1100 Subject: [PATCH 0912/1514] drm/apple: expose full colour mode catalog and DRM colour properties Retain the per-timing ColorModes catalogue reported by DCP firmware and expose the standard Linux DRM output colour properties on external connectors so compositors and userspace can select every colour mode supported by the display: - Store up to 64 compact 8-byte real colour elements per timing in dcp_display_mode (sorted by descending firmware score with unsafe and DSC flags) and extend pq_mode_rank() with YCbCr 4:2:2/4:2:0 fallbacks ranked below RGB and YCbCr 4:4:4. - Add dcp_select_color_mode() in dcp-color.h mapping EOTF (SDR, HDR gamma, ST 2084 PQ, BT.2100 HLG), Colorspace, color format (AUTO, RGB, YCbCr 4:4:4, YCbCr 4:2:2 incl. DP/HDMI tunnel encodings, YCbCr 4:2:0), Broadcast RGB (Automatic, Full, Limited), and max bpc (8..12) onto the timing's colour catalogue, preserving default AUTO behaviour and rejecting unsupported combinations with -EINVAL in atomic check. - Attach full HDMI/DP Colorspace bitmasks, Broadcast RGB, color format, and max bpc (8..12) on external connectors with a matching connector reset hook, atomic_check mode_changed triggers, and postclose reset. - Tag HLG and wide-gamut SDR (BT.2020, DCI-P3) RGB scanout surfaces in iomfb_flush() and expose live active colour mode and HDR InfoFrame state in connector debugfs (color_state). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 105 +++++- drivers/gpu/drm/apple/connector.c | 142 ++++++++ drivers/gpu/drm/apple/dcp-color.h | 326 ++++++++++++++++++ drivers/gpu/drm/apple/dcp-internal.h | 9 +- drivers/gpu/drm/apple/dcp.c | 4 + drivers/gpu/drm/apple/iomfb.c | 60 +++- drivers/gpu/drm/apple/iomfb_template.c | 109 ++++-- drivers/gpu/drm/apple/parser-test.c | 5 +- drivers/gpu/drm/apple/parser.c | 60 +++- drivers/gpu/drm/apple/parser.h | 20 ++ .../drivers/gpu/apple-dcp/display.py | 172 ++++++++- .../selftests/drivers/gpu/apple-dcp/run.py | 1 + 12 files changed, 941 insertions(+), 72 deletions(-) create mode 100644 drivers/gpu/drm/apple/dcp-color.h diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index fc0c32bb540860..7295923e517987 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -284,9 +284,13 @@ static void apple_drm_reset_hdr(struct drm_device *dev) drm_connector_list_iter_begin(dev, &iter); drm_for_each_connector_iter(conn, &iter) { struct drm_connector_state *cs = conn->state; + u8 default_bpc = conn->max_bpc_property ? 12 : 0; if (!cs->crtc || (!cs->hdr_output_metadata && - cs->colorspace == DRM_MODE_COLORIMETRY_DEFAULT)) + cs->colorspace == DRM_MODE_COLORIMETRY_DEFAULT && + cs->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + cs->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!default_bpc || cs->max_requested_bpc == default_bpc))) continue; cs = drm_atomic_get_connector_state(state, conn); if (IS_ERR(cs)) { @@ -296,6 +300,10 @@ static void apple_drm_reset_hdr(struct drm_device *dev) drm_property_blob_put(cs->hdr_output_metadata); cs->hdr_output_metadata = NULL; cs->colorspace = DRM_MODE_COLORIMETRY_DEFAULT; + cs->color_format = DRM_CONNECTOR_COLOR_FORMAT_AUTO; + cs->hdmi.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_AUTO; + if (default_bpc) + cs->max_requested_bpc = default_bpc; changed = true; } drm_connector_list_iter_end(&iter); @@ -894,10 +902,19 @@ static void apple_connector_early_unregister(struct drm_connector *connector) apple_connector_backlight_early_unregister(to_apple_connector(connector)); } +static void apple_connector_reset(struct drm_connector *connector) +{ + drm_atomic_helper_connector_reset(connector); + if (connector->state && connector->max_bpc_property) { + connector->state->max_requested_bpc = 12; + connector->state->max_bpc = 12; + } +} + static const struct drm_connector_funcs apple_connector_funcs = { .fill_modes = drm_helper_probe_single_connector_modes, .destroy = appledrm_connector_cleanup, - .reset = drm_atomic_helper_connector_reset, + .reset = apple_connector_reset, .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, .detect = apple_connector_detect, @@ -967,19 +984,29 @@ static int apple_connector_atomic_check(struct drm_connector *conn, !dcp_hdr_is_type1(blob->data))) return -EINVAL; - if (!new->crtc || (old->colorspace == new->colorspace && - drm_connector_atomic_hdr_metadata_equal(old, new))) + if (!new->crtc) + return 0; + if (old->colorspace == new->colorspace && + old->color_format == new->color_format && + old->hdmi.broadcast_rgb == new->hdmi.broadcast_rgb && + old->max_requested_bpc == new->max_requested_bpc && + drm_connector_atomic_hdr_metadata_equal(old, new)) return 0; crtc_state = drm_atomic_get_crtc_state(state, new->crtc); if (IS_ERR(crtc_state)) return PTR_ERR(crtc_state); /* - * The output colour element follows the EOTF and colorspace, so a - * change of either is a mode set. Where the firmware takes HDR10 - * static metadata on a live link, a new block alone is sent with this - * commit's flush (dcp_hdr_metadata_sync()) and the colour mode stays. + * The output colour element follows EOTF, colorspace, format, range + * and bit depth, so changing any of them requires a mode set. Where + * the firmware takes HDR10 static metadata on a live link, updating + * the metadata payload alone is sent with this commit's flush + * (dcp_hdr_metadata_sync()) and the colour mode stays. */ - if (old->colorspace == new->colorspace && old->crtc == new->crtc && + if (old->colorspace == new->colorspace && + old->color_format == new->color_format && + old->hdmi.broadcast_rgb == new->hdmi.broadcast_rgb && + old->max_requested_bpc == new->max_requested_bpc && + old->crtc == new->crtc && apple_connector_eotf(old) == apple_connector_eotf(new) && to_apple_connector(conn)->dcp && dcp_hdr_metadata_live(to_apple_connector(conn)->dcp)) @@ -1029,28 +1056,63 @@ static int apple_connector_attach_pq_reference(struct drm_connector *connector) } /* - * External displays can take a PQ BT.2020 signal where the firmware - * offers one, and a desktop 26.x panel PQ content it shows as EDR; - * dcp_crtc_atomic_check() refuses it elsewhere. + * External displays expose the colour properties backed by DCP's per-timing + * ColorModes catalogue (Colorspace, HDR_OUTPUT_METADATA, Broadcast RGB, + * color format, max bpc); dcp_crtc_atomic_check() validates each request + * against the active timing's catalogue. Internal panels with EDR expose + * Colorspace (BT2020_RGB), HDR_OUTPUT_METADATA and PQ_REFERENCE_LUMINANCE. */ static int apple_connector_attach_hdr(struct drm_connector *connector, bool panel_edr) { - const u32 colorspaces = BIT(DRM_MODE_COLORIMETRY_BT2020_RGB); + static const u32 panel_colorspaces = BIT(DRM_MODE_COLORIMETRY_BT2020_RGB); + static const u32 hdmi_colorspaces = + BIT(DRM_MODE_COLORIMETRY_SMPTE_170M_YCC) | + BIT(DRM_MODE_COLORIMETRY_BT709_YCC) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_601) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_709) | + BIT(DRM_MODE_COLORIMETRY_SYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPRGB) | + BIT(DRM_MODE_COLORIMETRY_BT2020_CYCC) | + BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) | + BIT(DRM_MODE_COLORIMETRY_BT2020_YCC) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER); + static const u32 dp_colorspaces = + BIT(DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED) | + BIT(DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT) | + BIT(DRM_MODE_COLORIMETRY_OPRGB) | + BIT(DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65) | + BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) | + BIT(DRM_MODE_COLORIMETRY_BT601_YCC) | + BIT(DRM_MODE_COLORIMETRY_BT709_YCC) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_601) | + BIT(DRM_MODE_COLORIMETRY_XVYCC_709) | + BIT(DRM_MODE_COLORIMETRY_SYCC_601) | + BIT(DRM_MODE_COLORIMETRY_OPYCC_601) | + BIT(DRM_MODE_COLORIMETRY_BT2020_CYCC) | + BIT(DRM_MODE_COLORIMETRY_BT2020_YCC); + static const unsigned long ext_color_formats = + BIT(DRM_OUTPUT_COLOR_FORMAT_RGB444) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422) | + BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR420); int ret; switch (connector->connector_type) { case DRM_MODE_CONNECTOR_eDP: if (!panel_edr) return 0; - fallthrough; + ret = drm_mode_create_dp_colorspace_property(connector, panel_colorspaces); + break; /* A desktop 26.x Type-C route is a pipeline output carrying DisplayPort. */ case DRM_MODE_CONNECTOR_USB: case DRM_MODE_CONNECTOR_DisplayPort: - ret = drm_mode_create_dp_colorspace_property(connector, colorspaces); + ret = drm_mode_create_dp_colorspace_property(connector, dp_colorspaces); break; case DRM_MODE_CONNECTOR_HDMIA: - ret = drm_mode_create_hdmi_colorspace_property(connector, colorspaces); + ret = drm_mode_create_hdmi_colorspace_property(connector, hdmi_colorspaces); break; default: return 0; @@ -1063,7 +1125,16 @@ static int apple_connector_attach_hdr(struct drm_connector *connector, drm_connector_attach_hdr_output_metadata_property(connector); if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) return apple_connector_attach_pq_reference(connector); - return 0; + ret = drm_connector_attach_broadcast_rgb_property(connector); + if (ret) + return ret; + ret = drm_connector_attach_color_format_property(connector, ext_color_formats); + if (ret) + return ret; + /* drm_connector_attach_max_bpc_property() populates connector->state. */ + if (!connector->state) + apple_connector_reset(connector); + return drm_connector_attach_max_bpc_property(connector, 8, 12); } static const struct drm_crtc_helper_funcs apple_crtc_helper_funcs = { diff --git a/drivers/gpu/drm/apple/connector.c b/drivers/gpu/drm/apple/connector.c index fb08369e2877d7..3a870bb3491ec6 100644 --- a/drivers/gpu/drm/apple/connector.c +++ b/drivers/gpu/drm/apple/connector.c @@ -11,6 +11,7 @@ #include #include #include +#include #include @@ -113,6 +114,145 @@ CONNECTOR_DEBUGFS_ENTRY(timing, DCP_CHUNK_TIMING_ELELMENTS); CONNECTOR_DEBUGFS_ENTRY(display_attribs, DCP_CHUNK_DISPLAY_ATTRIBUTES); CONNECTOR_DEBUGFS_ENTRY(transport, DCP_CHUNK_TRANSPORT); +static const char *dcp_color_format_name(u8 format) +{ + switch (format) { + case DCP_COLOR_FORMAT_RGB: + return "RGB"; + case DCP_COLOR_FORMAT_YCBCR420: + return "YCbCr420"; + case DCP_COLOR_FORMAT_YCBCR444: + return "YCbCr444"; + case DCP_COLOR_FORMAT_YCBCR422: + return "YCbCr422"; + case DCP_COLOR_FORMAT_YCBCR422_DP: + return "YCbCr422_DP"; + case DCP_COLOR_FORMAT_YCBCR422_HDMI: + return "YCbCr422_HDMI"; + default: + return "other"; + } +} + +static const char *dcp_color_eotf_name(u8 eotf) +{ + switch (eotf) { + case DCP_EOTF_SDR_GAMMA: + return "SDR"; + case DCP_EOTF_HDR_GAMMA: + return "HDR_gamma"; + case DCP_EOTF_ST_2084: + return "PQ"; + case DCP_EOTF_BT_2100: + return "HLG"; + default: + return "other"; + } +} + +static const char *dcp_colorimetry_name(u8 colorimetry) +{ + switch (colorimetry) { + case DCP_COLORIMETRY_BT601: + return "BT601"; + case DCP_COLORIMETRY_BT709: + return "BT709"; + case DCP_COLORIMETRY_XVYCC_601: + return "xvYCC601"; + case DCP_COLORIMETRY_XVYCC_709: + return "xvYCC709"; + case DCP_COLORIMETRY_SYCC_601: + return "sYCC601"; + case DCP_COLORIMETRY_ADOBE_YCC_601: + return "AdobeYCC601"; + case DCP_COLORIMETRY_BT2020_CYCC: + return "BT2020_CYCC"; + case DCP_COLORIMETRY_BT2020_YCC: + return "BT2020_YCC"; + case DCP_COLORIMETRY_BT2020_RGB: + return "BT2020_RGB"; + case DCP_COLORIMETRY_SRGB: + return "sRGB"; + case DCP_COLORIMETRY_SCRGB: + return "scRGB"; + case DCP_COLORIMETRY_SCRGB_FIXED: + return "scRGB_fixed"; + case DCP_COLORIMETRY_ADOBE_RGB: + return "AdobeRGB"; + case DCP_COLORIMETRY_DCI_P3_RGB_D65: + return "DCI_P3_D65"; + case DCP_COLORIMETRY_DCI_P3_RGB_THEATER: + return "DCI_P3_Theater"; + case DCP_COLORIMETRY_RGB: + return "Default_RGB"; + default: + return "other"; + } +} + +static int color_state_show(struct seq_file *m, void *data) +{ + struct apple_connector *apple_con = m->private; + struct platform_device *pdev = READ_ONCE(apple_con->dcp); + struct apple_dcp *dcp; + struct dcp_color_mode cm; + u8 sent[24] = {}; + bool hdr_service, hdr_infoframe, hdr_sent_valid; + u32 timing_id, color_id; + + if (!pdev) { + seq_puts(m, "pipeline: none\n"); + return 0; + } + dcp = platform_get_drvdata(pdev); + if (!dcp) { + seq_puts(m, "pipeline: unbound\n"); + return 0; + } + + timing_id = dcp->mode.timing_mode_id; + color_id = dcp->mode.color_mode_id; + cm = dcp->active_color; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + hdr_service = !!dcp->hdr.service; + hdr_infoframe = dcp->hdr.infoframe; + hdr_sent_valid = dcp->hdr.sent_valid; + if (hdr_sent_valid) + memcpy(sent, dcp->hdr.sent, sizeof(sent)); + } + + seq_printf(m, "timing_id: %u\n", timing_id); + seq_printf(m, "color_id: %u\n", color_id); + if (cm.score >= 0) { + seq_printf(m, "depth: %u\n", cm.depth); + seq_printf(m, "format: %s (%u)\n", dcp_color_format_name(cm.format), cm.format); + seq_printf(m, "colorimetry: %s (%u)\n", + dcp_colorimetry_name(cm.colorimetry), cm.colorimetry); + seq_printf(m, "eotf: %s (%u)\n", dcp_color_eotf_name(cm.eotf), cm.eotf); + seq_printf(m, "range: %s (%u)\n", + cm.range == DCP_COLOR_YCBCR_RANGE_FULL ? "Full" : "Limited", + cm.range); + } else { + seq_puts(m, "depth: none\n"); + } + seq_printf(m, "vrr_enabled: %u\n", dcp->vrr_enabled); + seq_printf(m, "output_pq: %u\n", dcp->output_pq); + seq_printf(m, "output_hdr: %u\n", dcp->output_hdr); + seq_printf(m, "output_edr: %u\n", dcp->output_edr); + seq_printf(m, "hdr_service: %u\n", hdr_service); + seq_printf(m, "hdr_infoframe: %u\n", hdr_infoframe); + seq_printf(m, "hdr_sent_valid: %u\n", hdr_sent_valid); + if (hdr_sent_valid) { + seq_printf(m, "hdr_mastering_max: %u\n", get_unaligned_le16(sent + 16)); + seq_printf(m, "hdr_mastering_min: %u\n", get_unaligned_le16(sent + 18)); + seq_printf(m, "hdr_max_cll: %u\n", get_unaligned_le16(sent + 20)); + seq_printf(m, "hdr_max_fall: %u\n", get_unaligned_le16(sent + 22)); + } + return 0; +} + +DEFINE_SHOW_ATTRIBUTE(color_state); + static void dcp_afk_debugfs_root(struct platform_device *pdev, int ep, struct dentry *root) { #if IS_ENABLED(CONFIG_DRM_APPLE_DEBUG) @@ -156,6 +296,8 @@ void apple_connector_debugfs_init(struct drm_connector *connector, struct dentry &chunk_display_attribs_fops); debugfs_create_file("Transport", 0444, root, apple_con, &chunk_transport_fops); + debugfs_create_file("color_state", 0444, root, apple_con, + &color_state_fops); switch (connector->connector_type) { case DRM_MODE_CONNECTOR_DisplayPort: diff --git a/drivers/gpu/drm/apple/dcp-color.h b/drivers/gpu/drm/apple/dcp-color.h new file mode 100644 index 00000000000000..d81779a03bc04b --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-color.h @@ -0,0 +1,326 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Output colour mode selection for Apple DCP external displays. + * + * Maps standard DRM connector properties (HDR_OUTPUT_METADATA EOTF, + * Colorspace, color format, Broadcast RGB, max bpc) onto the per-timing + * ColorModes catalogue reported by DCP firmware. + */ +#ifndef __APPLE_DCP_COLOR_H__ +#define __APPLE_DCP_COLOR_H__ + +#include +#include +#include +#include + +#include "parser.h" + +struct dcp_color_request { + u8 eotf; /* enum hdmi_eotf */ + u8 colorspace; /* enum drm_colorspace */ + u8 color_format; /* enum drm_connector_color_format */ + u8 broadcast_rgb; /* enum drm_hdmi_broadcast_rgb */ + u8 max_bpc; /* 0 (uncapped) or 8..12 */ + bool allow_hdr; + bool allow_dsc; + bool allow_unsafe_sdr; + bool default_rgb; +}; + +static inline bool dcp_color_request_is_default(const struct dcp_color_request *req) +{ + return req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + req->broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!req->max_bpc || req->max_bpc >= 12); +} + +static inline bool dcp_color_format_is_ycbcr422(u8 format) +{ + return format == DCP_COLOR_FORMAT_YCBCR422 || + format == DCP_COLOR_FORMAT_YCBCR422_DP || + format == DCP_COLOR_FORMAT_YCBCR422_HDMI; +} + +static inline bool dcp_color_format_matches(u8 fmt, u8 req_fmt) +{ + switch (req_fmt) { + case DRM_CONNECTOR_COLOR_FORMAT_AUTO: + return fmt == DCP_COLOR_FORMAT_RGB || + fmt == DCP_COLOR_FORMAT_YCBCR444 || + dcp_color_format_is_ycbcr422(fmt) || + fmt == DCP_COLOR_FORMAT_YCBCR420; + case DRM_CONNECTOR_COLOR_FORMAT_RGB444: + return fmt == DCP_COLOR_FORMAT_RGB; + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR444: + return fmt == DCP_COLOR_FORMAT_YCBCR444; + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR422: + return dcp_color_format_is_ycbcr422(fmt); + case DRM_CONNECTOR_COLOR_FORMAT_YCBCR420: + return fmt == DCP_COLOR_FORMAT_YCBCR420; + default: + return false; + } +} + +static inline bool dcp_color_eotf_matches(u8 eotf, const struct dcp_color_request *req) +{ + switch (req->eotf) { + case HDMI_EOTF_TRADITIONAL_GAMMA_SDR: + return eotf == DCP_EOTF_SDR_GAMMA; + case HDMI_EOTF_TRADITIONAL_GAMMA_HDR: + return req->allow_hdr && eotf == DCP_EOTF_HDR_GAMMA; + case HDMI_EOTF_SMPTE_ST2084: + return req->allow_hdr && eotf == DCP_EOTF_ST_2084; + case HDMI_EOTF_BT_2100_HLG: + return req->allow_hdr && eotf == DCP_EOTF_BT_2100; + default: + return false; + } +} + +static inline bool dcp_color_range_matches(u8 range, u8 broadcast_rgb) +{ + switch (broadcast_rgb) { + case DRM_HDMI_BROADCAST_RGB_AUTO: + return true; + case DRM_HDMI_BROADCAST_RGB_FULL: + return range == DCP_COLOR_YCBCR_RANGE_FULL; + case DRM_HDMI_BROADCAST_RGB_LIMITED: + return range == DCP_COLOR_YCBCR_RANGE_LIMITED; + default: + return false; + } +} + +static inline bool dcp_color_space_matches(u8 colorimetry, + const struct dcp_color_request *req) +{ + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + + switch (req->colorspace) { + case DRM_MODE_COLORIMETRY_DEFAULT: + if (hdr) + return colorimetry == DCP_COLORIMETRY_BT2020_RGB || + colorimetry == DCP_COLORIMETRY_BT2020_YCC || + colorimetry == DCP_COLORIMETRY_BT2020_CYCC; + return true; + case DRM_MODE_COLORIMETRY_BT2020_RGB: + if (colorimetry == DCP_COLORIMETRY_BT2020_RGB) + return true; + /* + * Compositors (e.g. Mutter) request BT2020_RGB with AUTO format + * for HDR even on timings where only YCbCr BT.2020 is safe. + */ + return hdr && + req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + colorimetry == DCP_COLORIMETRY_BT2020_YCC; + case DRM_MODE_COLORIMETRY_BT2020_YCC: + return colorimetry == DCP_COLORIMETRY_BT2020_YCC; + case DRM_MODE_COLORIMETRY_BT2020_CYCC: + return colorimetry == DCP_COLORIMETRY_BT2020_CYCC; + case DRM_MODE_COLORIMETRY_BT709_YCC: + return colorimetry == DCP_COLORIMETRY_BT709; + case DRM_MODE_COLORIMETRY_SMPTE_170M_YCC: + case DRM_MODE_COLORIMETRY_BT601_YCC: + return colorimetry == DCP_COLORIMETRY_BT601; + case DRM_MODE_COLORIMETRY_XVYCC_601: + return colorimetry == DCP_COLORIMETRY_XVYCC_601; + case DRM_MODE_COLORIMETRY_XVYCC_709: + return colorimetry == DCP_COLORIMETRY_XVYCC_709; + case DRM_MODE_COLORIMETRY_SYCC_601: + return colorimetry == DCP_COLORIMETRY_SYCC_601; + case DRM_MODE_COLORIMETRY_OPYCC_601: + return colorimetry == DCP_COLORIMETRY_ADOBE_YCC_601; + case DRM_MODE_COLORIMETRY_OPRGB: + return colorimetry == DCP_COLORIMETRY_ADOBE_RGB; + case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65: + return colorimetry == DCP_COLORIMETRY_DCI_P3_RGB_D65; + case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER: + return colorimetry == DCP_COLORIMETRY_DCI_P3_RGB_THEATER; + case DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED: + return colorimetry == DCP_COLORIMETRY_SCRGB_FIXED; + case DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT: + return colorimetry == DCP_COLORIMETRY_SCRGB; + default: + return false; + } +} + +static inline u32 dcp_color_entry_rank(const struct dcp_color_entry *e, + const struct dcp_color_request *req) +{ + u32 fmt_rank, space_rank, depth_rank, range_rank, dsc_rank; + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + + switch (e->format) { + case DCP_COLOR_FORMAT_RGB: + fmt_rank = 6; + break; + case DCP_COLOR_FORMAT_YCBCR444: + fmt_rank = 5; + break; + case DCP_COLOR_FORMAT_YCBCR422: + fmt_rank = 4; + break; + case DCP_COLOR_FORMAT_YCBCR422_DP: + fmt_rank = 3; + break; + case DCP_COLOR_FORMAT_YCBCR422_HDMI: + fmt_rank = 2; + break; + case DCP_COLOR_FORMAT_YCBCR420: + fmt_rank = 1; + break; + default: + fmt_rank = 0; + break; + } + + if (hdr) { + if (e->colorimetry == DCP_COLORIMETRY_BT2020_RGB) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_BT2020_YCC) + space_rank = 2; + else + space_rank = 1; + } else if (req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT) { + if (e->format == DCP_COLOR_FORMAT_RGB) { + if (req->default_rgb && e->colorimetry == DCP_COLORIMETRY_RGB) + space_rank = 4; + else if (e->colorimetry == DCP_COLORIMETRY_SRGB || + e->colorimetry == DCP_COLORIMETRY_BT709) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_RGB) + space_rank = 2; + else + space_rank = 1; + } else { + if (e->colorimetry == DCP_COLORIMETRY_BT709) + space_rank = 3; + else if (e->colorimetry == DCP_COLORIMETRY_BT601) + space_rank = 2; + else + space_rank = 1; + } + } else { + space_rank = 1; + } + + if (req->eotf == HDMI_EOTF_SMPTE_ST2084 && + req->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO) { + /* Match pq_mode_rank(): 10 bpc fits HDR framebuffers directly. */ + depth_rank = e->depth == 10 ? 3 : (e->depth == 12 ? 2 : 1); + } else { + depth_rank = e->depth; + } + + if (e->format == DCP_COLOR_FORMAT_RGB) + range_rank = e->range == DCP_COLOR_YCBCR_RANGE_FULL ? 2 : 1; + else + range_rank = e->range == DCP_COLOR_YCBCR_RANGE_LIMITED ? 2 : 1; + + dsc_rank = (e->flags & DCP_COLOR_FLAG_DSC) ? 0 : 1; + + return (fmt_rank << 16) | (space_rank << 12) | (depth_rank << 6) | + (range_rank << 2) | dsc_rank; +} + +static inline void dcp_color_mode_from_entry(struct dcp_color_mode *out, + const struct dcp_color_entry *e) +{ + out->score = 0; + out->id = e->id; + out->eotf = e->eotf; + out->format = e->format; + out->colorimetry = e->colorimetry; + out->range = e->range; + out->depth = e->depth; +} + +static inline int dcp_default_sdr_color(const struct dcp_display_mode *mode, + struct dcp_color_mode *out) +{ + const struct dcp_color_mode *cmode = NULL; + + if (mode->color_mode_id == mode->sdr_rgb.id && mode->sdr_rgb.score >= 0) + cmode = &mode->sdr_rgb; + else if (mode->color_mode_id == mode->sdr_444.id && mode->sdr_444.score >= 0) + cmode = &mode->sdr_444; + else if (mode->color_mode_id == mode->sdr.id && mode->sdr.score >= 0) + cmode = &mode->sdr; + else if (mode->color_mode_id == mode->best.id && mode->best.score >= 0) + cmode = &mode->best; + + if (cmode) { + *out = *cmode; + return 0; + } + return -EINVAL; +} + +static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, + const struct dcp_color_request *req, + struct dcp_color_mode *out) +{ + u8 max_bpc = req->max_bpc ? req->max_bpc : 12; + bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + unsigned int pass, max_pass, i; + const struct dcp_color_entry *best = NULL; + u32 best_rank = 0; + + if (dcp_color_request_is_default(req)) { + if (req->eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT) + return dcp_default_sdr_color(mode, out); + if (req->eotf == HDMI_EOTF_SMPTE_ST2084 && + (req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT || + req->colorspace == DRM_MODE_COLORIMETRY_BT2020_RGB)) { + if (!req->allow_hdr || mode->pq.score < 0) + return -EINVAL; + *out = mode->pq; + return 0; + } + } + + if (hdr && !req->allow_hdr) + return -EINVAL; + + max_pass = (!hdr && req->allow_unsafe_sdr) ? 2 : 1; + for (pass = 0; pass < max_pass && !best; pass++) { + bool allow_unsafe = pass > 0; + + for (i = 0; i < mode->nr_colors; i++) { + const struct dcp_color_entry *e = &mode->colors[i]; + u32 rank; + + if ((e->flags & DCP_COLOR_FLAG_UNSAFE) && !allow_unsafe) + continue; + if ((e->flags & DCP_COLOR_FLAG_DSC) && hdr && !req->allow_dsc) + continue; + if (e->depth > max_bpc) + continue; + if (!dcp_color_eotf_matches(e->eotf, req)) + continue; + if (!dcp_color_format_matches(e->format, req->color_format)) + continue; + if (!dcp_color_range_matches(e->range, req->broadcast_rgb)) + continue; + if (!dcp_color_space_matches(e->colorimetry, req)) + continue; + rank = dcp_color_entry_rank(e, req); + /* Entries are sorted by descending firmware score: keep first on ties. */ + if (!best || rank > best_rank) { + best = e; + best_rank = rank; + } + } + } + + if (!best) + return -EINVAL; + dcp_color_mode_from_entry(out, best); + return 0; +} + +#endif /* __APPLE_DCP_COLOR_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 27886edb5119c3..116d0119d12665 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -28,6 +28,7 @@ #include "dptxep.h" #include "dcp_backlight.h" #include "dcp-announce.h" +#include "dcp-color.h" #include "dcp-display-metadata.h" #include "dcp-metadata-epoch.h" #include "dcp-180hz.h" @@ -826,11 +827,15 @@ struct apple_dcp { bool iomfb_template_pq; /* * The mode set asks for a PQ signal; output_pq: the one set carries it; - * output_edr: a panel shows the PQ content as EDR, edr_sent: swaps - * still carry EDR state the firmware must be told to drop. + * output_hdr: any non-SDR EOTF (PQ/HLG/HDR-gamma); output_edr: a panel + * shows the PQ content as EDR, edr_sent: swaps still carry EDR state + * the firmware must be told to drop. */ + struct dcp_color_request color_req; + struct dcp_color_mode active_color; bool pq_requested; bool output_pq; + bool output_hdr; bool output_edr; bool edr_sent; /* diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 70e39123e62462..a63bcef017959c 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5081,6 +5081,9 @@ static void _dcp_poweroff(struct apple_dcp *dcp) break; } /* The link set up again starts without HDR10 metadata. */ + dcp->active_color.score = -1; + dcp->output_pq = false; + dcp->output_hdr = false; dcp_hdr_metadata_forget(dcp); } @@ -7530,6 +7533,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) spin_lock_init(&dcp->mode_state.lock); spin_lock_init(&dcp->metadata.lock); spin_lock_init(&dcp->hdr.lock); + dcp->active_color.score = -1; mutex_init(&dcp->dcpavserv.lock); INIT_WORK(&dcp->dcpavserv.close_wq, dcpavserv_close_work); ret = dcpavserv_edid_retry_init(dcp); diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 805c715f13f31f..66d142ee2c2c6c 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3419,7 +3419,7 @@ static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, bool same; int transport, ret; - if (!dcp->output_pq || READ_ONCE(dcp->crashed) || + if (!dcp->output_hdr || READ_ONCE(dcp->crashed) || !dcp_hdr_metadata_live(to_apple_crtc(crtc)->dcp)) return; conn_state = dcp_crtc_connector_state(dcp, crtc, commit); @@ -3427,7 +3427,7 @@ static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, conn_state->hdr_output_metadata->length != sizeof(struct hdr_output_metadata)) return; if (((const struct hdr_output_metadata *)conn_state->hdr_output_metadata->data) - ->hdmi_metadata_type1.eotf != HDMI_EOTF_SMPTE_ST2084 || + ->hdmi_metadata_type1.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || dcp_hdr_data(data, conn_state->hdr_output_metadata->data)) return; @@ -3463,29 +3463,57 @@ static void dcp_hdr_metadata_sync(struct apple_dcp *dcp, struct drm_crtc *crtc, afk_service_put(service); } -/* Only an SDR or a PQ signal, and PQ only where the timing has an element. */ +static void dcp_crtc_color_request(struct apple_dcp *dcp, struct drm_crtc *crtc, + struct drm_atomic_commit *commit, + struct dcp_color_request *req) +{ + const struct drm_connector_state *conn_state = + dcp_crtc_connector_state(dcp, crtc, commit); + + *req = (struct dcp_color_request) { + .eotf = dcp_crtc_eotf(dcp, crtc, commit), + .colorspace = conn_state ? conn_state->colorspace : + DRM_MODE_COLORIMETRY_DEFAULT, + .color_format = conn_state ? conn_state->color_format : + DRM_CONNECTOR_COLOR_FORMAT_AUTO, + .broadcast_rgb = conn_state ? conn_state->hdmi.broadcast_rgb : + DRM_HDMI_BROADCAST_RGB_AUTO, + .max_bpc = conn_state ? conn_state->max_requested_bpc : 0, + .allow_hdr = dcp_hdr_output_supported(dcp), + .allow_dsc = READ_ONCE(dcp->iomfb_template_pq) && !dcp_has_panel(dcp), + .allow_unsafe_sdr = dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL, + .default_rgb = dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + !dcp_has_panel(dcp), + }; +} + +/* Validate requested EOTF, colorspace, format, range and bpc against the timing. */ int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *commit) { struct drm_crtc_state *crtc_state = drm_atomic_get_new_crtc_state(commit, crtc); + struct dcp_color_request req; + struct dcp_color_mode selected; struct dcp_display_mode mode; if (!crtc_state || !crtc_state->enable || !drm_atomic_crtc_needs_modeset(crtc_state)) return 0; - switch (dcp_crtc_eotf(dcp, crtc, commit)) { - case HDMI_EOTF_TRADITIONAL_GAMMA_SDR: - return 0; - case HDMI_EOTF_SMPTE_ST2084: - if (dcp_panel_edr_supported(dcp)) - return 0; - if (dcp_hdr_output_supported(dcp) && - lookup_mode(dcp, &crtc_state->mode, &mode) && mode.pq.score >= 0) + dcp_crtc_color_request(dcp, crtc, commit, &req); + if (dcp_panel_edr_supported(dcp)) { + if (req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || + req.eotf == HDMI_EOTF_SMPTE_ST2084) return 0; - fallthrough; - default: return -EINVAL; } + if (dcp_color_request_is_default(&req) && + req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT) + return 0; + if (!lookup_mode(dcp, &crtc_state->mode, &mode)) + return -EINVAL; + return dcp_select_color_mode(&mode, &req, &selected); } /* The user may own drm_display_mode, so we need to search for our copy */ @@ -3638,11 +3666,13 @@ int dcp_crtc_atomic_modeset(struct drm_crtc *crtc, if (crtc_state->mode.hdisplay == 0 && crtc_state->mode.vdisplay == 0) return 0; - dcp->pq_requested = dcp_crtc_eotf(dcp, crtc, commit) == HDMI_EOTF_SMPTE_ST2084; + dcp_crtc_color_request(dcp, crtc, commit, &dcp->color_req); + dcp->pq_requested = dcp->color_req.eotf == HDMI_EOTF_SMPTE_ST2084; dcp->output_edr = dcp->pq_requested && dcp_panel_edr_supported(dcp) && dcp_crtc_bt2020(dcp, crtc, commit); dcp->pq_requested &= dcp_hdr_output_supported(dcp); - if (!dcp->pq_requested) + if (dcp->color_req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR || + !dcp_hdr_output_supported(dcp)) dcp_hdr_infoframe_stop(dcp); dcp_hdr_metadata_forget(dcp); dcp_mode_begin(&dcp->mode_state); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index b783cb0d1a9b40..fd7e98e4b5255e 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -3917,6 +3917,7 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, struct dcp_display_mode selected, *mode = &selected; struct dcp_modeset_cookie *modeset; struct dcp_wait_cookie *cookie; + struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; int ret; @@ -3932,24 +3933,26 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, return -EIO; } - /* An HDR commit scans out through the timing's PQ element. */ - if (dcp->pq_requested && mode->pq.score >= 0) + if (!dcp_select_color_mode(mode, &dcp->color_req, &selected_color)) { + mode->color_mode_id = selected_color.id; + cmode = &selected_color; + } else if (dcp->pq_requested && mode->pq.score >= 0) { mode->color_mode_id = mode->pq.id; - - dev_dbg(dcp->dev, - "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", - mode->color_mode_id, mode->timing_mode_id, - DRM_MODE_ARG(&crtc_state->mode)); - if (mode->color_mode_id == mode->pq.id && mode->pq.score >= 0) cmode = &mode->pq; - else if (mode->color_mode_id == mode->sdr_rgb.id) + } else if (mode->color_mode_id == mode->sdr_rgb.id) { cmode = &mode->sdr_rgb; - else if (mode->color_mode_id == mode->sdr_444.id) + } else if (mode->color_mode_id == mode->sdr_444.id) { cmode = &mode->sdr_444; - else if (mode->color_mode_id == mode->sdr.id) + } else if (mode->color_mode_id == mode->sdr.id) { cmode = &mode->sdr; - else if (mode->color_mode_id == mode->best.id) + } else if (mode->color_mode_id == mode->best.id) { cmode = &mode->best; + } + + dev_dbg(dcp->dev, + "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", + mode->color_mode_id, mode->timing_mode_id, + DRM_MODE_ARG(&crtc_state->mode)); if (cmode) dev_dbg(dcp->dev, "color mode depth:%hhu format:%u colorimetry:%u eotf:%u range:%u vrr:%u\n", @@ -3960,7 +3963,12 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, .color_mode_id = mode->color_mode_id, .timing_mode_id = mode->timing_mode_id }; - dcp->output_pq = dcp->pq_requested && mode->pq.score >= 0; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; /* VRR modes need swap timestamps, see iomfb_flush(); so do fixed internal timings. */ dcp->use_timestamps = mode->needs_timestamps; @@ -4178,6 +4186,7 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, { struct dcp_display_mode selected, *mode = &selected; struct dcp_wait_cookie *cookie; + struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; bool paired = false; bool keep_mode = false; @@ -4219,9 +4228,21 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, return -EIO; } - /* An HDR commit scans out through the timing's PQ element. */ - if (dcp->pq_requested && mode->pq.score >= 0) + if (!dcp_select_color_mode(mode, &dcp->color_req, &selected_color)) { + mode->color_mode_id = selected_color.id; + cmode = &selected_color; + } else if (dcp->pq_requested && mode->pq.score >= 0) { mode->color_mode_id = mode->pq.id; + cmode = &mode->pq; + } else if (mode->color_mode_id == mode->sdr_rgb.id) { + cmode = &mode->sdr_rgb; + } else if (mode->color_mode_id == mode->sdr_444.id) { + cmode = &mode->sdr_444; + } else if (mode->color_mode_id == mode->sdr.id) { + cmode = &mode->sdr; + } else if (mode->color_mode_id == mode->best.id) { + cmode = &mode->best; + } /* The connection's audio link runs through the mode set. */ av_audio_before_modeset(dcp); @@ -4230,16 +4251,6 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, "set_digital_out_mode(color:%d timing:%d) " DRM_MODE_FMT "\n", mode->color_mode_id, mode->timing_mode_id, DRM_MODE_ARG(&crtc_state->mode)); - if (mode->color_mode_id == mode->pq.id && mode->pq.score >= 0) - cmode = &mode->pq; - else if (mode->color_mode_id == mode->sdr_rgb.id) - cmode = &mode->sdr_rgb; - else if (mode->color_mode_id == mode->sdr_444.id) - cmode = &mode->sdr_444; - else if (mode->color_mode_id == mode->sdr.id) - cmode = &mode->sdr; - else if (mode->color_mode_id == mode->best.id) - cmode = &mode->best; if (dcp_is_ext26(dcp)) { if (mode->sdr_rgb.score < 0 || mode->sdr_rgb.depth != 8 || mode->sdr_rgb.format != DCP_COLOR_FORMAT_RGB || crtc_state->vrr_enabled) @@ -4269,7 +4280,12 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, .color_mode_id = mode->color_mode_id, .timing_mode_id = mode->timing_mode_id }; - dcp->output_pq = dcp->pq_requested && mode->pq.score >= 0; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; /* Built-in ProMotion panels require timestamps even in fixed-120 mode. */ dcp->use_timestamps = mode->needs_timestamps && dcp->main_display; @@ -4398,7 +4414,7 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, /* A firmware 27 pair took them on both engines (dcp_peer_finish_v27()). */ if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL || (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp) && !paired)) - dcp_external_hdr_hints(dcp, dcp->output_pq); + dcp_external_hdr_hints(dcp, dcp->output_hdr); dcp_link_report(dcp, &crtc_state->mode); return 0; @@ -4531,14 +4547,39 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru req->surf[l].base.colorspace = DCP_COLORSPACE_P3_D65; /* - * On a PQ output the compositor has already encoded RGB - * surfaces for the sink: BT.2020 primaries, PQ code values. - * An EDR panel takes the same and maps them into its headroom. + * On an HDR output the compositor has already encoded RGB + * surfaces for the sink: BT.2020 primaries, PQ or HLG code + * values. An EDR panel takes PQ and maps it into its headroom. + * Wide-gamut SDR outputs tag RGB surfaces with their target + * primaries so DCP passes them through without sRGB gamut + * remapping. */ - if ((dcp->output_pq || dcp->output_edr) && - !new_state->fb->format->is_yuv) { - req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; - req->surf[l].base.xfer_func = DCP_XFER_FUNC_PQ; + if (!new_state->fb->format->is_yuv) { + if (dcp->output_pq || dcp->output_edr) { + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + req->surf[l].base.xfer_func = DCP_XFER_FUNC_PQ; + } else if (dcp->output_hdr && + dcp->active_color.eotf == DCP_EOTF_BT_2100) { + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + req->surf[l].base.xfer_func = DCP_XFER_FUNC_HLG; + } else if (!dcp_has_panel(dcp) && + dcp->active_color.score >= 0) { + switch (dcp->active_color.colorimetry) { + case DCP_COLORIMETRY_BT2020_RGB: + case DCP_COLORIMETRY_BT2020_YCC: + case DCP_COLORIMETRY_BT2020_CYCC: + req->surf[l].base.colorspace = DCP_COLORSPACE_BT2020; + break; + case DCP_COLORIMETRY_DCI_P3_RGB_D65: + req->surf[l].base.colorspace = DCP_COLORSPACE_P3_D65; + break; + case DCP_COLORIMETRY_DCI_P3_RGB_THEATER: + req->surf[l].base.colorspace = DCP_COLORSPACE_DCI_P3; + break; + default: + break; + } + } } #if DCP_FW_H17(DCP_FW_VER) diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index 2c277e32b33cde..245818de86732f 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -1428,8 +1428,9 @@ static void parser_panel_identity(struct kunit *test) struct dcp_parse_ctx ctx; const struct drm_edid *edid; const struct edid *raw; - struct dcp_display_mode modes[2] = {}; + struct dcp_display_mode *modes = kunit_kcalloc(test, 2, sizeof(*modes), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, modes); modes[0].mode = (struct drm_display_mode) { .clock = 540005, .hdisplay = 3456, .hsync_start = 3500, .hsync_end = 3550, .htotal = 4000, .vdisplay = 2160, @@ -1457,7 +1458,7 @@ static void parser_panel_identity(struct kunit *test) KUNIT_ASSERT_EQ(test, parse(blob->data, blob->size, &ctx), 0); KUNIT_ASSERT_EQ(test, parse_panel_metadata(&ctx, &metadata), 0); KUNIT_EXPECT_STREQ(test, metadata.name, "Synthetic Int"); - edid = dcp_panel_edid(&metadata, NULL, modes, ARRAY_SIZE(modes), 345, 223); + edid = dcp_panel_edid(&metadata, NULL, modes, 2, 345, 223); KUNIT_ASSERT_FALSE(test, IS_ERR(edid)); KUNIT_EXPECT_TRUE(test, drm_edid_valid(edid)); raw = drm_edid_raw(edid); diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index e4bca4075828a6..4ceeddbcc116af 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -586,15 +586,70 @@ static unsigned int pq_mode_rank(const struct color_mode *cmode) if (cmode->pixel_encoding == DCP_COLOR_FORMAT_RGB && cmode->colorimetry == DCP_COLORIMETRY_BT2020_RGB && cmode->dynamic_range == DCP_COLOR_YCBCR_RANGE_FULL) - rank = 3; + rank = 7; else if (cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR444 && cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) + rank = 5; + else if ((cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422 || + cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422_DP || + cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422_HDMI) && + cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) + rank = 3; + else if (cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR420 && + cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 1; else return 0; return rank + (cmode->depth == 10); } +static void record_color_entry(struct dcp_display_mode *out, + s64 scores[DCP_MAX_COLOR_ENTRIES], + const struct color_mode *cmode, + const struct timing_color_restrictions *limits, + bool limits_known) +{ + struct dcp_color_entry entry = {}; + unsigned int pos, end; + + if (cmode->colorimetry < 0 || cmode->colorimetry >= DCP_COLORIMETRY_COUNT || + cmode->depth < 8 || cmode->depth > 12 || + cmode->dynamic_range < 0 || cmode->dynamic_range >= DCP_COLOR_YCBCR_RANGE_COUNT || + cmode->eotf < 0 || cmode->eotf >= DCP_EOTF_COUNT || + cmode->pixel_encoding < 0 || cmode->pixel_encoding >= DCP_COLOR_FORMAT_COUNT) + return; + + entry.id = cmode->id; + entry.eotf = cmode->eotf; + entry.format = cmode->pixel_encoding; + entry.range = cmode->dynamic_range; + entry.colorimetry = cmode->colorimetry; + entry.depth = cmode->depth; + if (limits_known) { + if (timing_color_contains(&limits->unsafe, cmode->id)) + entry.flags |= DCP_COLOR_FLAG_UNSAFE; + if (timing_color_contains(&limits->dsc_required, cmode->id)) + entry.flags |= DCP_COLOR_FLAG_DSC; + } + + pos = out->nr_colors; + while (pos > 0 && scores[pos - 1] < cmode->score) + pos--; + if (pos >= DCP_MAX_COLOR_ENTRIES) + return; + end = out->nr_colors < DCP_MAX_COLOR_ENTRIES ? out->nr_colors : DCP_MAX_COLOR_ENTRIES - 1; + if (end > pos) { + memmove(&out->colors[pos + 1], &out->colors[pos], + (end - pos) * sizeof(out->colors[0])); + memmove(&scores[pos + 1], &scores[pos], + (end - pos) * sizeof(scores[0])); + } + out->colors[pos] = entry; + scores[pos] = cmode->score; + if (out->nr_colors < DCP_MAX_COLOR_ENTRIES) + out->nr_colors++; +} + /* * @dsc: the modeset delegates compression of DSC-required elements to DCP. */ @@ -627,6 +682,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, { struct iterator outer_it; struct dcp_color_mode bootstrap = { .score = -1 }; + s64 color_scores[DCP_MAX_COLOR_ENTRIES]; unsigned int best_sdr_rank = 0, best_unsafe_rank = 0, best_pq_rank = 0; unsigned int best_rgb_rank = 0; int ret = 0; @@ -635,6 +691,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, out->sdr.score = -1; out->best.score = -1; out->pq.score = -1; + out->nr_colors = 0; out->sdr_usable = false; out->sdr_unsafe = false; out->has_bootstrap = false; @@ -719,6 +776,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, cmode.depth, cmode.colorimetry, cmode.eotf, cmode.dynamic_range, cmode.pixel_encoding); + record_color_entry(out, color_scores, &cmode, limits, limits_known); if (limits_known) collect_pq_mode(&out->pq, &best_pq_rank, &cmode, limits, diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 2f92a7a9eb4d95..7e276e0390c6d4 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -135,6 +135,23 @@ struct dcp_color_mode { u8 depth; }; +#define DCP_COLOR_FLAG_UNSAFE (1U << 0) +#define DCP_COLOR_FLAG_DSC (1U << 1) +#define DCP_MAX_COLOR_ENTRIES 64 + +/* Compact colour element retained per timing, sorted by descending score. */ +struct dcp_color_entry { + u32 id; + u8 eotf : 3; + u8 format : 4; + u8 range : 1; + u8 colorimetry : 5; + u8 flags : 2; + u8 reserved : 1; + u8 depth; + u8 pad; +}; + /* * Represents a single display mode. These mode objects are populated at * runtime based on the TimingElements dictionary sent by the DCP. @@ -184,6 +201,9 @@ struct dcp_display_mode { /* Immutable receipt provenance; never retag a cached exception. */ struct dcp_metadata_ticket unsafe_rgb8_ticket; u64 unsafe_rgb8_service_epoch; + /* Real colour elements reported for this timing, descending by score. */ + struct dcp_color_entry colors[DCP_MAX_COLOR_ENTRIES]; + u8 nr_colors; }; struct dimension { diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index 5078e40f148fe3..b17dfb80d8177e 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -658,6 +658,7 @@ def pad(raw): }; """ + header + r""" typedef uint64_t u64; +#define HDMI_EOTF_TRADITIONAL_GAMMA_SDR 0 #define HDMI_EOTF_SMPTE_ST2084 2 #define EPIC_SUBTYPE_STD_SERVICE 0xc0 #define READ_ONCE(x) (x) @@ -674,7 +675,7 @@ def pad(raw): struct { size_t length; const void *data; } *hdr_output_metadata; }; struct apple_dcp { - bool output_pq, crashed; + bool output_pq, output_hdr, crashed; struct { struct apple_epic_service *service; u64 generation; @@ -762,6 +763,7 @@ def pad(raw): conn.hdr_output_metadata = &blob; test_connector = &conn; test_dcp.output_pq = true; + test_dcp.output_hdr = true; test_dcp.hdr.service = &service; reply_length = DCP_HDR_MSG_SIZE; transport_result = -EIO; @@ -865,3 +867,171 @@ def pad(raw): return 0; } """ + + +def color_selection(root): + """Full colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, range, gamut, PQ/HLG.""" + apple = root / 'drivers/gpu/drm/apple' + parser_h = (apple / 'parser.h').read_text() + color_h = (apple / 'dcp-color.h').read_text() + # Extract enum + struct definitions from parser.h + p_start = parser_h.index('enum dcp_color_eotf {') + p_end = parser_h.index('struct dimension {') + parser_defs = parser_h[p_start:p_end] + color_defs = '\n'.join(line for line in color_h.splitlines() + if not line.startswith('#include')) + color_defs = color_defs.replace('static inline ', 'static inline __attribute__((unused)) ') + return r""" +#include +#include +#include +#include +#include +#include +#include +typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; +typedef uint64_t u64; typedef int64_t s64; +struct drm_display_mode { int unused; }; +struct dcp_metadata_ticket { int unused; }; +enum hdmi_eotf { + HDMI_EOTF_TRADITIONAL_GAMMA_SDR = 0, + HDMI_EOTF_TRADITIONAL_GAMMA_HDR = 1, + HDMI_EOTF_SMPTE_ST2084 = 2, + HDMI_EOTF_BT_2100_HLG = 3, +}; +enum drm_colorspace { + DRM_MODE_COLORIMETRY_DEFAULT = 0, + DRM_MODE_COLORIMETRY_SMPTE_170M_YCC = 1, + DRM_MODE_COLORIMETRY_BT709_YCC = 2, + DRM_MODE_COLORIMETRY_XVYCC_601 = 3, + DRM_MODE_COLORIMETRY_XVYCC_709 = 4, + DRM_MODE_COLORIMETRY_SYCC_601 = 5, + DRM_MODE_COLORIMETRY_OPYCC_601 = 6, + DRM_MODE_COLORIMETRY_OPRGB = 7, + DRM_MODE_COLORIMETRY_BT2020_CYCC = 8, + DRM_MODE_COLORIMETRY_BT2020_RGB = 9, + DRM_MODE_COLORIMETRY_BT2020_YCC = 10, + DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65 = 11, + DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER = 12, + DRM_MODE_COLORIMETRY_RGB_WIDE_FIXED = 13, + DRM_MODE_COLORIMETRY_RGB_WIDE_FLOAT = 14, + DRM_MODE_COLORIMETRY_BT601_YCC = 15, +}; +enum drm_connector_color_format { + DRM_CONNECTOR_COLOR_FORMAT_AUTO = 0, + DRM_CONNECTOR_COLOR_FORMAT_RGB444 = 1, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR444 = 2, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR422 = 3, + DRM_CONNECTOR_COLOR_FORMAT_YCBCR420 = 4, +}; +enum drm_hdmi_broadcast_rgb { + DRM_HDMI_BROADCAST_RGB_AUTO = 0, + DRM_HDMI_BROADCAST_RGB_FULL = 1, + DRM_HDMI_BROADCAST_RGB_LIMITED = 2, +}; +""" + parser_defs + color_defs + r""" +static void add_entry(struct dcp_display_mode *m, u32 id, u8 eotf, u8 fmt, + u8 space, u8 range, u8 depth, u8 flags) +{ + assert(m->nr_colors < DCP_MAX_COLOR_ENTRIES); + m->colors[m->nr_colors++] = (struct dcp_color_entry) { + .id = id, .eotf = eotf, .format = fmt, .colorimetry = space, + .range = range, .depth = depth, .flags = flags, + }; +} + +int main(void) +{ + struct dcp_display_mode acer = { .sdr_rgb = { .score = 100, .id = 81, .eotf = DCP_EOTF_SDR_GAMMA, + .format = DCP_COLOR_FORMAT_RGB, .colorimetry = DCP_COLORIMETRY_SRGB, + .range = DCP_COLOR_YCBCR_RANGE_FULL, .depth = 8 }, + .pq = { .score = 200, .id = 113, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_RGB, .colorimetry = DCP_COLORIMETRY_BT2020_RGB, + .range = DCP_COLOR_YCBCR_RANGE_FULL, .depth = 10 }, + .color_mode_id = 81 }; + struct dcp_color_request req; + struct dcp_color_mode out; + + /* Populate Acer 1080p60-shaped catalog */ + add_entry(&acer, 81, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, 0); + add_entry(&acer, 82, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 91, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 95, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 83, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 84, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT601, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 93, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 107, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 109, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 114, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 115, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 117, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 12, 0); + add_entry(&acer, 121, DCP_EOTF_BT_2100, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 122, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR420, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + + /* Default SDR fast path */ + req = (struct dcp_color_request){ .allow_hdr = true, .allow_dsc = true, .max_bpc = 12 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 81); + + /* Default PQ fast path (Mutter sets BT2020_RGB + PQ) */ + req.eotf = HDMI_EOTF_SMPTE_ST2084; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 113 && out.depth == 10); + + /* Explicit 12 bpc PQ RGB vs 10 bpc PQ RGB vs Limited range */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 117 && out.depth == 12); + req.max_bpc = 10; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 113 && out.depth == 10); + req.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 114 && out.range == DCP_COLOR_YCBCR_RANGE_LIMITED); + + /* Explicit YCbCr 4:4:4 / 4:2:2 PQ (including 10b vs 12b DP tunnel) */ + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, .max_bpc = 12, .allow_hdr = true }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 107); + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.max_bpc = 10; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 115 && out.depth == 10); + req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 115); /* plain 422 outranks 422_DP */ + + /* HLG support */ + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_BT_2100_HLG, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .max_bpc = 12, .allow_hdr = true }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 121); + + /* SDR: RGB 8b Limited, RGB 10b wide-gamut BT.2020, YCbCr 4:2:2 BT.709/BT.601, YCbCr 4:2:0 */ + req = (struct dcp_color_request){ .broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED, .max_bpc = 8 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 82); + req = (struct dcp_color_request){ .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, .max_bpc = 10 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 95); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, + .colorspace = DRM_MODE_COLORIMETRY_BT709_YCC, .max_bpc = 10 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 93); + req.colorspace = DRM_MODE_COLORIMETRY_SMPTE_170M_YCC; req.max_bpc = 8; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 84); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR420, .max_bpc = 8 }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 122); + + /* MSI 1440p60-shaped timing: PQ RGB unsafe, PQ 444/422 safe -> Mutter AUTO BT2020_RGB succeeds via 444 */ + struct dcp_display_mode msi = { .sdr_rgb = acer.sdr_rgb, + .pq = { .score = 10, .id = 104, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_YCBCR444, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, + .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 }, + .color_mode_id = 81 }; + add_entry(&msi, 104, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 106, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE); + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, + .max_bpc = 12, .allow_hdr = true }; + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 104); + /* Explicit PQ RGB on MSI 1440p60 MUST be rejected (only unsafe RGB exists) */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; + assert(dcp_select_color_mode(&msi, &req, &out) == -EINVAL); + /* Explicit PQ 4:2:2 on MSI 1440p60 picks DP tunnel entry 106 */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 106); + + puts("PASS: colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, Full/Limited, wide gamut, PQ/HLG, and -EINVAL rejection"); + return 0; +} +""" diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 87140d980dc955..2128a160cc4cf8 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -61,6 +61,7 @@ def main(): ('audio', 'cec-only-av-endpoint', audio.cec_only_endpoint, ((),), ()), ('display', 'desktop-gamma', desktop.gamma, ((),), ()), ('display', 'hdr-static-metadata', display.hdr_metadata, ((),), ()), + ('display', 'color-mode-selection', display.color_selection, ((),), ()), ('display', 'ctm-encoding', colorimetry.ctm, ((),), ()), ('lifecycle', 'desktop-modeset-unmap', desktop.modeset_unmap, ((),), ()), ('lifecycle', 'desktop-unknown-modeset-recovery', desktop.modeset_unknown, ((),), ()), From de0a438a022b4bfad6aac022308b1332cf748c26 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 20:34:02 +1100 Subject: [PATCH 0913/1514] drm/apple: clear adaptive sync on fixed modes and modeset legacy VRR toggles Fix two VRR gaps on non-live-VRR IOMFB-template DCPs: - In iomfb_modeset(), clear Adaptive Sync (minRR = 0) when switching from a VRR timing (dcp->vrr_enabled) to a fixed timing (!mode->vrr), matching dcp_desktop_modeset(). - In dcp_crtc_atomic_check(), mark mode_changed when VRR_ENABLED changes on 12.3/13.5/14.7_tpl pipelines that apply Adaptive Sync inside iomfb_modeset(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 5 ++++- drivers/gpu/drm/apple/iomfb_template.c | 9 +++++---- .../drivers/gpu/apple-dcp/lifecycle.py | 18 ++++++++++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index a63bcef017959c..38e770070c1f3c 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2228,7 +2228,10 @@ int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commi * macOS switches between a timing's fixed and variable modes with a * full mode set. */ - if ((dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || + if ((dcp->fw_compat == DCP_FIRMWARE_V_12_3 || + dcp->fw_compat == DCP_FIRMWARE_V_13_5 || + dcp->fw_compat == DCP_FIRMWARE_V_14_7_TEMPLATE || + dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp->main_display && !dcp_has_panel(dcp))) && crtc_state->enable && !dcp_vrr_live(dcp)) { diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index fd7e98e4b5255e..4108e1a2615189 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4340,11 +4340,12 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, complete_set_digital_out_mode(dcp, NULL, cookie); } else #endif - if (mode->vrr && - dcp->hw.iomfb_method_profile != - DCP_IOMFB_METHODS_H17P_EXTERNAL) + if ((mode->vrr || dcp->vrr_enabled) && + dcp->hw.iomfb_method_profile != + DCP_IOMFB_METHODS_H17P_EXTERNAL) dcp_set_adaptive_sync(dcp, - crtc_state->vrr_enabled ? mode->min_vrr : 0, + mode->vrr && crtc_state->vrr_enabled ? + mode->min_vrr : 0, cookie); else dcp_set_digital_out_mode(dcp, false, &dcp->mode, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index bd749368aa8209..c6f45f9a6582c9 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -2018,6 +2018,24 @@ def vrr(root): dcp.panel = false; dcp.peer_check = 0; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; + /* Legacy 12.3/13.5/14.7_tpl DCPs program VRR inside iomfb_modeset(). */ + const enum dcp_firmware_version tpl_fws[] = { + DCP_FIRMWARE_V_12_3, DCP_FIRMWARE_V_13_5, DCP_FIRMWARE_V_14_7_TEMPLATE + }; + for (unsigned int i = 0; i < 3; i++) { + dcp.fw_compat = tpl_fws[i]; + state.crtc.enable = true; + state.crtc.vrr_enabled = true; + state.crtc.mode_changed = false; + state.no_old_crtc = false; + state.old_crtc.vrr_enabled = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && state.crtc.mode_changed); + state.crtc.mode_changed = false; + state.old_crtc.vrr_enabled = true; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && !state.crtc.mode_changed); + cases += 2; + } + dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ return prefix + check + suffix.replace('DESKTOP_VRR', desktop, 1).replace('FW27_VRR', fw27, 1) From 9d8d2015093c21b428e097c073738cdd17c91d6c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:00:34 +1100 Subject: [PATCH 0914/1514] drm/apple: allow non-DSC PQ fallback on unsafe-only HDMI 2.0 timings External timings above HDMI 1.4's 340 MHz clock behind DP-to-HDMI 2.0 protocol converters (such as 1920x1080@180 and 2560x1440@144 on MCDP29xx/2900) have every non-virtual color element listed in UnsafeColorElementIDs. SDR already drives those timings through their unsafe elements, whereas collect_pq_mode() and dcp_select_color_mode() rejected unsafe PQ elements unconditionally, leaving HDR unavailable at the monitor's default max refresh rate. Allow falling back to the best non-DSC unsafe PQ element only on timings that have no safe SDR elements at all (!sdr_usable && sdr_unsafe) outside the external_sdr path. Timings with any safe SDR element continue to enforce UnsafeColorElementIDs strictly for PQ. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-color.h | 3 +- drivers/gpu/drm/apple/parser.c | 28 +++++++++++++++---- .../drivers/gpu/apple-dcp/display.py | 18 ++++++++++++ .../selftests/drivers/gpu/apple-dcp/rate.py | 17 +++++++++++ 4 files changed, 60 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-color.h b/drivers/gpu/drm/apple/dcp-color.h index d81779a03bc04b..f83b3bd60b59b0 100644 --- a/drivers/gpu/drm/apple/dcp-color.h +++ b/drivers/gpu/drm/apple/dcp-color.h @@ -286,7 +286,8 @@ static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, if (hdr && !req->allow_hdr) return -EINVAL; - max_pass = (!hdr && req->allow_unsafe_sdr) ? 2 : 1; + max_pass = (req->allow_unsafe_sdr && + (!hdr || (!mode->sdr_usable && mode->sdr_unsafe))) ? 2 : 1; for (pass = 0; pass < max_pass && !best; pass++) { bool allow_unsafe = pass > 0; diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 4ceeddbcc116af..7d0b2a1fcb7536 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -655,13 +655,14 @@ static void record_color_entry(struct dcp_display_mode *out, */ static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, struct color_mode *cmode, - const struct timing_color_restrictions *limits, bool dsc) + const struct timing_color_restrictions *limits, + bool dsc, bool allow_unsafe) { unsigned int rank = pq_mode_rank(cmode); bool needs_dsc = timing_color_contains(&limits->dsc_required, cmode->id); if (!rank || (needs_dsc && !dsc) || - timing_color_contains(&limits->unsafe, cmode->id)) + (!allow_unsafe && timing_color_contains(&limits->unsafe, cmode->id))) return; /* Break equal format and depth ranks in favour of no compression. */ @@ -682,9 +683,10 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, { struct iterator outer_it; struct dcp_color_mode bootstrap = { .score = -1 }; + struct dcp_color_mode unsafe_pq = { .score = -1 }; s64 color_scores[DCP_MAX_COLOR_ENTRIES]; unsigned int best_sdr_rank = 0, best_unsafe_rank = 0, best_pq_rank = 0; - unsigned int best_rgb_rank = 0; + unsigned int best_unsafe_pq_rank = 0, best_rgb_rank = 0; int ret = 0; out->sdr_444.score = -1; out->sdr_rgb.score = -1; @@ -778,9 +780,14 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, cmode.pixel_encoding); record_color_entry(out, color_scores, &cmode, limits, limits_known); - if (limits_known) + if (limits_known) { collect_pq_mode(&out->pq, &best_pq_rank, &cmode, limits, - handle->pq_dsc); + handle->pq_dsc, false); + if (!external_sdr) + collect_pq_mode(&unsafe_pq, &best_unsafe_pq_rank, + &cmode, limits, handle->pq_dsc, + true); + } if (cmode.eotf == DCP_EOTF_SDR_GAMMA && (!limits_known || (!timing_color_contains(&limits->unsafe, cmode.id) && @@ -845,6 +852,17 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, fill_color_mode(&out->best, &cmode); } + /* + * Timings above HDMI 1.4's 340 MHz clock behind DP-to-HDMI 2.0 bridges + * list every element in UnsafeColorElementIDs even though SDR already + * drives them through those unsafe elements. Fall back to the best + * non-DSC unsafe PQ element only on such unsafe-only timings, keeping + * UnsafeColorElementIDs strict whenever any safe SDR element exists. + */ + if (!external_sdr && out->pq.score < 0 && !out->sdr_usable && + out->sdr_unsafe && unsafe_pq.score >= 0) + out->pq = unsafe_pq; + return 0; } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index b17dfb80d8177e..dbd6ca31425bcd 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -1031,6 +1031,24 @@ def color_selection(root): req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 106); + /* Unsafe-only >340 MHz HDMI 2.0 timing (e.g. 1080p180 / 1440p144): SDR already uses unsafe + * elements (sdr_usable=false, sdr_unsafe=true), so non-DSC unsafe PQ is permitted, whereas + * safe timings (sdr_usable=true) strictly reject unsafe PQ. */ + struct dcp_display_mode msi144 = { .sdr_rgb = acer.sdr_rgb, .color_mode_id = 80, + .sdr_usable = false, .sdr_unsafe = true, + .pq = { .score = 10, .id = 105, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, + .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 } }; + add_entry(&msi144, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); + add_entry(&msi144, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, DCP_COLOR_FLAG_UNSAFE); + req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, + .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, .max_bpc = 12, + .allow_hdr = true, .allow_unsafe_sdr = true }; + assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 105); + /* Same unsafe entry on a timing with sdr_usable=true MUST be rejected */ + msi144.sdr_usable = true; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + puts("PASS: colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, Full/Limited, wide gamut, PQ/HLG, and -EINVAL rejection"); return 0; } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index dffa976dfea2fb..524b5242577386 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -114,6 +114,16 @@ def color(i, score, depth, eotf, colorimetry, encoding=0, dynamic=0): dsc_raw = bytearray(struct.pack('340 MHz timing (e.g. 1080p180 / 1440p144): every + # element is in UnsafeColorElementIDs, so SDR already uses an unsafe element + # and PQ falls back to the best non-DSC unsafe PQ element. + unsafe_only_fixture = [dict(timing_fixture[0], ColorModes=[ + color(80, 1, 8, 0, 10), color(105, 5, 12, 2, 7, encoding=2), + color(113, 9, 10, 2, 9)], + UnsafeColorElementIDs=[80, 105, 113], DSCRequiredColorElementIDs=[113])] + unsafe_only_raw = bytearray(struct.pack('340 MHz timing falls back to non-DSC unsafe PQ (105), + * still skipping DSC-required unsafe PQ (113) when pq_dsc is false. */ + assert(!parse(unsafe_only_blob, sizeof(unsafe_only_blob), &c)); + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && !m[0].sdr_usable && m[0].sdr_unsafe); + assert(m[0].pq.id == 105 && m[0].pq.depth == 12); + free(m); /* The default modes; the timing ID that carries DRM_MODE_TYPE_PREFERRED. */ static const struct { const unsigned char *blob; size_t size; bool internal; u32 id; } d[] = { { default_acer, sizeof(default_acer), false, 2 }, From 62420ea802f9b4b7f4caee12d1accc6bad6097c5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:14:57 +1100 Subject: [PATCH 0915/1514] drm/asahi: set the G14 27.2 firmware progress checks and compute watchdog The G14 firmware 27.2 runtime armed the firmware's progress recovery (HwDataB +0xfc4) but left the Globals words that configure it at zero: the 3D/TA/compute progress-check intervals (+0x998/+0x99c/+0x9a0), the compute context-switch and kill timeouts (+0x9c8/+0x9cc), the relaxed compute kill timeout (+0x24), command submission enabled (+0x78) and +0xe28. The firmware then timed out ordinary work within a second or two. The J473 (M2 mini) lost piglit arb_shader_image_load_store-shader-mem-barrier to a TA timeout in its first subtest, and Geekbench 6 Vulkan to a compute timeout in Background Blur. Both complete on the J413, the same G14G on firmware 13.5, whose runtime sets these words. The 27.2 Globals object has the same 0xe48-byte layout on M3 and M4. Their 27.2 runtimes write these words with these values (m3_power_26, g16/fw/initdata). Write them the same way. The exception is the TA interval: it uses the 100 polls the M3 runtime uses for long vertex loops (m3_config), not 10. The values live in g14_v27_2_abi.rs with a test that they fit the object and leave the power words alone. The idle power-off delays (+0x9b8..+0x9c0) are not touched. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 38 ++++++++++++++++++++++++++ drivers/gpu/drm/asahi/gpu/v27_2.rs | 6 +++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 535313f91126cf..4e7fd8de186e58 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -71,6 +71,28 @@ impl GrowRequest { } } +/// Globals words of the firmware's per-pipe progress checks and compute watchdog, which the +/// shared 0xe48-byte 27.2 Globals hold at the same offsets as the M3 and M4 27.2 runtimes write +/// them (`m3_power_26`, `g16/fw/initdata`), with the 13.5 names: 0x24 relaxed compute kill +/// timeout (ms), 0x78 command submission enabled, 0x998/0x99c/0x9a0 progress-check intervals +/// of 3D/TA/compute (firmware polls), 0x9c8 compute context-switch timeout (ms), 0x9cc compute +/// kill timeout (ms), 0xe28. Left zero, the firmware's progress recovery (armed in HwDataB) +/// times out TA and compute work that runs past a poll within a second or two. The TA interval +/// is the 100 polls the M3 runtime uses for long vertex loops (`m3_config`), not 10. +pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 8] = [ + (0x24, 3000), + (0x78, 1), + (0x998, 40), + (0x99c, 100), + (0x9a0, 250), + (0x9c8, 40), + (0x9cc, 50), + (0xe28, 3), +]; + +/// Size of the 27.2 Globals object. +pub(crate) const GLOBALS_BYTES: usize = 0xe48; + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -148,4 +170,20 @@ mod tests { ] ); } + + #[test] + fn progress_words_fit_the_globals_and_leave_power_words_alone() { + let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; + for (i, &(at, value)) in GLOBALS_PROGRESS.iter().enumerate() { + assert_eq!(at % 4, 0); + assert!(at + 4 <= GLOBALS_BYTES); + assert_ne!(value, 0); + assert!(power.iter().all(|&p| p + 4 <= at || at + 4 <= p)); + assert!(GLOBALS_PROGRESS[i + 1..].iter().all(|&(other, _)| other != at)); + } + // Every progress interval is set: a zero interval is what stopped work in a poll. + for at in [0x998, 0x99c, 0x9a0] { + assert!(GLOBALS_PROGRESS.iter().any(|&(o, v)| o == at && v != 0)); + } + } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index c3b3dd9b99520a..32d11d7ae6e746 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -1061,7 +1061,7 @@ impl RootV27_2 { let page = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; fw::types::GpuArray::empty(page, mmu::UAT_PGSZ)? }; - let mut globals = alloc.shared_ro.array_empty::(0xe48)?; + let mut globals = alloc.shared_ro.array_empty::(g14_v27_2_abi::GLOBALS_BYTES)?; { let data = globals.as_mut_slice(); for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { @@ -1072,6 +1072,10 @@ impl RootV27_2 { put32(data, at, value); } put32(data, 0x6e, 1); + // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. + for (at, value) in g14_v27_2_abi::GLOBALS_PROGRESS { + put32(data, at, value); + } crate::pgtable::clean_poc(data.as_ptr(), data.len()); } let mut control = alloc.shared.array_empty::(0xe850)?; From 9bf590bddd779a15c29a8334ec49473264f4a1c4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:24:02 +1100 Subject: [PATCH 0916/1514] dt-bindings: dma: apple,sio: describe alternate protocol-10 tables Document the optional list for a low-window SIO that can use either table layout before firmware reports its protocol. Signed-off-by: Ryan Murray --- Documentation/devicetree/bindings/dma/apple,sio.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/devicetree/bindings/dma/apple,sio.yaml b/Documentation/devicetree/bindings/dma/apple,sio.yaml index 62c517ccff0220..1de8f0851422ef 100644 --- a/Documentation/devicetree/bindings/dma/apple,sio.yaml +++ b/Documentation/devicetree/bindings/dma/apple,sio.yaml @@ -230,6 +230,14 @@ properties: is done upfront in the loader which can be better suited for keeping up with Apple's firmware changes. + apple,sio-firmware-params-v10: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Optional alternative boot parameters for the low-window SIO protocol + 10 layout, using the same key/value format as apple,sio-firmware-params. + The bootloader can supply both lists when the firmware protocol is + only known after the coprocessor starts. + apple,channel-threshold: $ref: /schemas/types.yaml#/definitions/uint32 description: From 19218c164c55fcf396cda24f605635da54a43f1c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:24:02 +1100 Subject: [PATCH 0917/1514] dmaengine: apple-sio: reject unvalidated protocol-10 tables Validate both candidate lists before choosing one. Keep the attach path for sleep when both lists are rejected and refuse cyclic DMA preparation as well as channel configuration. Cover the selection and refusal paths in KUnit. Signed-off-by: Ryan Murray --- drivers/dma/apple-sio-test.c | 29 ++++++++++++++++++++++++----- drivers/dma/apple-sio.c | 31 +++++++++++-------------------- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/drivers/dma/apple-sio-test.c b/drivers/dma/apple-sio-test.c index f093d01c341322..8c77aaa978160d 100644 --- a/drivers/dma/apple-sio-test.c +++ b/drivers/dma/apple-sio-test.c @@ -325,12 +325,11 @@ static void sio_low_window_params_test(struct kunit *test) { "/sio-t6030-test/sio-low-window-test-both", 9, "apple,sio-firmware-params", false }, { "/sio-t6030-test/sio-low-window-test-both", 10, "apple,sio-firmware-params-v10", false }, - { "/sio-t6030-test/sio-low-window-test-bad-v10", 10, "apple,sio-firmware-params", - true }, + { "/sio-t6030-test/sio-low-window-test-bad-v10", 10, NULL, true }, { "/sio-t6030-test/sio-low-window-test-bad-v10", 9, "apple,sio-firmware-params", false }, /* An older loader: the earlier tables only */ - { "/sio-t6030-test/sio-t6030-test-earlier", 10, "apple,sio-firmware-params", true }, + { "/sio-t6030-test/sio-t6030-test-earlier", 10, NULL, true }, { "/sio-t6030-test/sio-t6030-test-earlier", 9, "apple,sio-firmware-params", false }, /* T6030: its protocol-10 tables are the first list */ { "/sio-t6030-test/sio-t6030-test-v10", 10, "apple,sio-firmware-params", false }, @@ -342,6 +341,7 @@ static void sio_low_window_params_test(struct kunit *test) for (i = 0; i < ARRAY_SIZE(cases); i++) { struct device_node *np __free(device_node) = of_find_node_by_path(cases[i].path); struct sio_data *sio = kunit_kzalloc(test, sizeof(*sio), GFP_KERNEL); + const char *propname; KUNIT_ASSERT_NOT_NULL_MSG(test, np, "%s", cases[i].path); KUNIT_ASSERT_NOT_NULL(test, dev); @@ -349,13 +349,31 @@ static void sio_low_window_params_test(struct kunit *test) dev->of_node = np; sio->dev = dev; sio->protocol = cases[i].protocol; - KUNIT_EXPECT_STREQ_MSG(test, sio_dt_params_name(sio), cases[i].prop, "%s v%u", - cases[i].path, cases[i].protocol); + propname = sio_dt_params_name(sio); + if (cases[i].prop) + KUNIT_EXPECT_STREQ_MSG(test, propname, cases[i].prop, "%s v%u", + cases[i].path, cases[i].protocol); + else + KUNIT_EXPECT_NULL(test, propname); KUNIT_EXPECT_EQ_MSG(test, sio->tables_mismatch, cases[i].mismatch, "%s v%u", cases[i].path, cases[i].protocol); } } +static void sio_protocol10_cyclic_without_tables_test(struct kunit *test) +{ + struct sio_data *sio = kunit_kzalloc(test, sizeof(*sio), GFP_KERNEL); + struct sio_chan *chan = kunit_kzalloc(test, sizeof(*chan), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, sio); + KUNIT_ASSERT_NOT_NULL(test, chan); + sio->tables_mismatch = true; + chan->host = sio; + + KUNIT_EXPECT_NULL(test, sio_prep_dma_cyclic(&chan->vc.chan, 0, 4096, 1024, + sio_chan_direction(chan->no), 0)); +} + static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_protocol10_test), KUNIT_CASE(sio_t6030_earlier_loader_test), @@ -366,6 +384,7 @@ static struct kunit_case sio_t6030_test_cases[] = { KUNIT_CASE(sio_t6030_device_tree_test), KUNIT_CASE(sio_t6030_probe_test), KUNIT_CASE(sio_low_window_params_test), + KUNIT_CASE(sio_protocol10_cyclic_without_tables_test), {} }; diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 299abb98d8df50..8fa59e76235e5e 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -871,7 +871,8 @@ static struct dma_async_tx_descriptor *sio_prep_dma_cyclic( struct sio_chan *siochan = to_sio_chan(chan); struct sio_tx *siotx; - if (direction != sio_chan_direction(siochan->no)) + if (siochan->host->tables_mismatch || + direction != sio_chan_direction(siochan->no)) return NULL; siotx = sio_alloc_tx(siochan, buf_addr, buf_len, period_len, GFP_NOWAIT); @@ -1944,25 +1945,13 @@ static const char *sio_dt_params_name(struct sio_data *sio) if (sio->protocol != 10) return "apple,sio-firmware-params"; - if (!of_property_present(np, "apple,sio-firmware-params-v10")) { - u32 key, size; - int i, n = of_property_count_u32_elems(np, "apple,sio-firmware-params"); - - /* The earlier layout's five 32-byte shim records are never protocol 10's */ - for (i = 0; i + 1 < n; i += 2) - if (!of_property_read_u32_index(np, "apple,sio-firmware-params", i, &key) && - key == 0x23 && - !of_property_read_u32_index(np, "apple,sio-firmware-params", i + 1, - &size) && - size == 5 * 32) - sio->tables_mismatch = true; + if (!sio_t6030_check_node(np, "apple,sio-firmware-params-v10")) + return "apple,sio-firmware-params-v10"; + if (!sio_t6030_check_node(np, "apple,sio-firmware-params")) return "apple,sio-firmware-params"; - } - if (sio_t6030_check_node(np, "apple,sio-firmware-params-v10")) { - sio->tables_mismatch = true; - return "apple,sio-firmware-params"; - } - return "apple,sio-firmware-params-v10"; + + sio->tables_mismatch = true; + return NULL; } static int sio_send_dt_params(struct sio_data *sio) @@ -1975,8 +1964,10 @@ static int sio_send_dt_params(struct sio_data *sio) return sio->hw->send_dt_params(sio); propname = sio_dt_params_name(sio); - if (sio->tables_mismatch) + if (!propname) { dev_err(sio->dev, "boot tables are not for SIO protocol 10; no DMA\n"); + return 0; + } nparams = of_property_count_u32_elems(np, propname); if (nparams < 0) { From 8c7d58b1ca475c1db6d1dfb73c3ec9f02c01e121 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:38:30 +1100 Subject: [PATCH 0918/1514] drm/apple: enforce non-DSC unsafe PQ, gate non-template colour checks, and sync color_state Address review findings across the colour-mode and HDR path: - Never admit DSC-required unsafe PQ elements on unsafe-only timings even when pq_dsc / allow_dsc is true (pass false for dsc when collecting unsafe_pq in parse_color_modes() and skip DCP_COLOR_FLAG_DSC in the unsafe HDR pass of dcp_select_color_mode()); add selftest coverage in rate.py and display.py for pq_dsc=true / allow_dsc=true. - Reject non-default colour property requests with -EINVAL in dcp_crtc_check_hdr() on non-template IOMFB backends (!iomfb_template_pq) and RGB8-only ext26 pipelines instead of silently accepting them. - Preserve explicit DCI_P3_RGB_D65 wide-gamut SDR tagging on H17P external pipes in iomfb_flush() and pass dcp->output_hdr to paired v27 parameter 6 in dcp_peer_finish_v27(). - Check connector->state allocation after apple_connector_reset() before attaching max bpc, and snapshot mode/active_color/output flags under dcp->hdr.lock between iomfb_modeset() and color_state_show(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 2 ++ drivers/gpu/drm/apple/connector.c | 20 +++++++++----- drivers/gpu/drm/apple/dcp-color.h | 3 ++- .../gpu/drm/apple/dcp-peer-runtime-v27.inc | 2 +- drivers/gpu/drm/apple/iomfb.c | 2 ++ drivers/gpu/drm/apple/iomfb_template.c | 26 +++++++++++-------- drivers/gpu/drm/apple/parser.c | 3 +-- .../drivers/gpu/apple-dcp/display.py | 9 ++++++- .../selftests/drivers/gpu/apple-dcp/rate.py | 15 ++++++----- 9 files changed, 53 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 7295923e517987..a02062fb7a27ea 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1134,6 +1134,8 @@ static int apple_connector_attach_hdr(struct drm_connector *connector, /* drm_connector_attach_max_bpc_property() populates connector->state. */ if (!connector->state) apple_connector_reset(connector); + if (!connector->state) + return -ENOMEM; return drm_connector_attach_max_bpc_property(connector, 8, 12); } diff --git a/drivers/gpu/drm/apple/connector.c b/drivers/gpu/drm/apple/connector.c index 3a870bb3491ec6..e3c8c876a215ae 100644 --- a/drivers/gpu/drm/apple/connector.c +++ b/drivers/gpu/drm/apple/connector.c @@ -200,6 +200,8 @@ static int color_state_show(struct seq_file *m, void *data) bool hdr_service, hdr_infoframe, hdr_sent_valid; u32 timing_id, color_id; + bool vrr_enabled, output_pq, output_hdr, output_edr; + if (!pdev) { seq_puts(m, "pipeline: none\n"); return 0; @@ -210,10 +212,14 @@ static int color_state_show(struct seq_file *m, void *data) return 0; } - timing_id = dcp->mode.timing_mode_id; - color_id = dcp->mode.color_mode_id; - cm = dcp->active_color; scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + timing_id = dcp->mode.timing_mode_id; + color_id = dcp->mode.color_mode_id; + cm = dcp->active_color; + vrr_enabled = dcp->vrr_enabled; + output_pq = dcp->output_pq; + output_hdr = dcp->output_hdr; + output_edr = dcp->output_edr; hdr_service = !!dcp->hdr.service; hdr_infoframe = dcp->hdr.infoframe; hdr_sent_valid = dcp->hdr.sent_valid; @@ -235,10 +241,10 @@ static int color_state_show(struct seq_file *m, void *data) } else { seq_puts(m, "depth: none\n"); } - seq_printf(m, "vrr_enabled: %u\n", dcp->vrr_enabled); - seq_printf(m, "output_pq: %u\n", dcp->output_pq); - seq_printf(m, "output_hdr: %u\n", dcp->output_hdr); - seq_printf(m, "output_edr: %u\n", dcp->output_edr); + seq_printf(m, "vrr_enabled: %u\n", vrr_enabled); + seq_printf(m, "output_pq: %u\n", output_pq); + seq_printf(m, "output_hdr: %u\n", output_hdr); + seq_printf(m, "output_edr: %u\n", output_edr); seq_printf(m, "hdr_service: %u\n", hdr_service); seq_printf(m, "hdr_infoframe: %u\n", hdr_infoframe); seq_printf(m, "hdr_sent_valid: %u\n", hdr_sent_valid); diff --git a/drivers/gpu/drm/apple/dcp-color.h b/drivers/gpu/drm/apple/dcp-color.h index f83b3bd60b59b0..a4b8a34f02e461 100644 --- a/drivers/gpu/drm/apple/dcp-color.h +++ b/drivers/gpu/drm/apple/dcp-color.h @@ -297,7 +297,8 @@ static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, if ((e->flags & DCP_COLOR_FLAG_UNSAFE) && !allow_unsafe) continue; - if ((e->flags & DCP_COLOR_FLAG_DSC) && hdr && !req->allow_dsc) + if ((e->flags & DCP_COLOR_FLAG_DSC) && hdr && + (!req->allow_dsc || allow_unsafe)) continue; if (e->depth > max_bpc) continue; diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index cd8340105b37bf..b8add62381a205 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -69,7 +69,7 @@ static void dcp_peer_finish_v27(struct apple_dcp *dcp, struct apple_dcp *peer) if (!dcp_peer_both_v27(dcp, peer, "A449", config, sizeof(config), NULL, 0x7c, false) && !dcp_peer_param_v27(dcp, peer, 3, 1, 0x10000) && !dcp_peer_both_v27(dcp, peer, "A453", &zero, sizeof(zero), tile, sizeof(tile), false) && - !dcp_peer_param_v27(dcp, peer, 6, 1, dcp->output_pq ? 0x20000 : 0x10000)) + !dcp_peer_param_v27(dcp, peer, 6, 1, dcp->output_hdr ? 0x20000 : 0x10000)) dev_info(dcp->dev, "paired engines report %ux%u each\n", le32_to_cpu(tile[0]), le32_to_cpu(tile[1])); } diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 66d142ee2c2c6c..12067db7adbf49 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3511,6 +3511,8 @@ int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT) return 0; + if (!READ_ONCE(dcp->iomfb_template_pq) || dcp_is_ext26(dcp)) + return -EINVAL; if (!lookup_mode(dcp, &crtc_state->mode, &mode)) return -EINVAL; return dcp_select_color_mode(&mode, &req, &selected); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 4108e1a2615189..af7c622e0e99a9 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4276,16 +4276,18 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, dcp->mode.color_mode_id == mode->color_mode_id && dcp->mode.timing_mode_id == mode->timing_mode_id; #endif - dcp->mode = (struct dcp_set_digital_out_mode_req){ - .color_mode_id = mode->color_mode_id, - .timing_mode_id = mode->timing_mode_id - }; - if (cmode) - dcp->active_color = *cmode; - else - dcp->active_color.score = -1; - dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; - dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req){ + .color_mode_id = mode->color_mode_id, + .timing_mode_id = mode->timing_mode_id + }; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + } /* Built-in ProMotion panels require timestamps even in fixed-120 mode. */ dcp->use_timestamps = mode->needs_timestamps && dcp->main_display; @@ -4592,7 +4594,9 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17P_EXTERNAL && !new_state->fb->format->is_yuv && - req->surf[l].base.colorspace == DCP_COLORSPACE_P3_D65) + req->surf[l].base.colorspace == DCP_COLORSPACE_P3_D65 && + (dcp->active_color.score < 0 || + dcp->active_color.colorimetry != DCP_COLORIMETRY_DCI_P3_RGB_D65)) req->surf[l].base.colorspace = DCP_COLORSPACE_UNSPECIFIED; #endif } diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 7d0b2a1fcb7536..5f762e53c2bb44 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -785,8 +785,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, handle->pq_dsc, false); if (!external_sdr) collect_pq_mode(&unsafe_pq, &best_unsafe_pq_rank, - &cmode, limits, handle->pq_dsc, - true); + &cmode, limits, false, true); } if (cmode.eotf == DCP_EOTF_SDR_GAMMA && (!limits_known || diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index dbd6ca31425bcd..b7427feb4bc267 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -1040,13 +1040,20 @@ def color_selection(root): .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 } }; add_entry(&msi144, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); + add_entry(&msi144, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE | DCP_COLOR_FLAG_DSC); add_entry(&msi144, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, DCP_COLOR_FLAG_UNSAFE); req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, .max_bpc = 12, - .allow_hdr = true, .allow_unsafe_sdr = true }; + .allow_hdr = true, .allow_dsc = true, .allow_unsafe_sdr = true }; assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 105); + /* DSC-required unsafe PQ (113) MUST be rejected even with allow_dsc=true */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; + req.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); /* Same unsafe entry on a timing with sdr_usable=true MUST be rejected */ msi144.sdr_usable = true; + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; + req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); puts("PASS: colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, Full/Limited, wide gamut, PQ/HLG, and -EINVAL rejection"); diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 524b5242577386..d9f53d58b299a6 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -357,12 +357,15 @@ def timing(i, w, h, hz, pref, score, unsafe=False): free(m); } /* Unsafe-only >340 MHz timing falls back to non-DSC unsafe PQ (105), - * still skipping DSC-required unsafe PQ (113) when pq_dsc is false. */ - assert(!parse(unsafe_only_blob, sizeof(unsafe_only_blob), &c)); - m = enumerate_modes(&c, &n, 600, 330, 0, false, false); - assert(!IS_ERR(m) && n == 1 && !m[0].sdr_usable && m[0].sdr_unsafe); - assert(m[0].pq.id == 105 && m[0].pq.depth == 12); - free(m); + * still skipping DSC-required unsafe PQ (113) even when pq_dsc is true. */ + for (unsigned int dsc = 0; dsc < 2; dsc++) { + assert(!parse(unsafe_only_blob, sizeof(unsafe_only_blob), &c)); + c.pq_dsc = dsc; + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && !m[0].sdr_usable && m[0].sdr_unsafe); + assert(m[0].pq.id == 105 && m[0].pq.depth == 12); + free(m); + } /* The default modes; the timing ID that carries DRM_MODE_TYPE_PREFERRED. */ static const struct { const unsigned char *blob; size_t size; bool internal; u32 id; } d[] = { { default_acer, sizeof(default_acer), false, 2 }, From 975ba41ba8920e37ea41547e7fee5c2e79174efa Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:45:38 +1100 Subject: [PATCH 0919/1514] drm/asahi: preserve terminal VmStatus on M3 packet cancellation and device loss Address review findings on packet completion state handling: - Replace the single finish_claimed AtomicBool with a three-state AtomicU8 (PENDING, PACKET_FAILED, TERMINAL) so a terminal GPU fault on a published prefix still records on VmStatus even after an earlier fail_packet() cancellation or partial-publish rejection, without re-signaling the fence. - Record device-loss errors (EIO, ETIMEDOUT, ENODEV) via VmStatus::record_if_device_loss() inside fail_packet(), matching G15/G16/G17 so Job::run() and Inner::fail_front() do not drop terminal runtime loss while keeping transient rejections (EBUSY, ENOMEM, E2BIG, ECANCELED) out of VmStatus. - Extend m3-packet-completion-tests with coverage for cancel-before-fault and device-loss errors in fail_packet(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_submit.rs | 57 +++++++++++++++++++---- tools/asahi/m3-packet-completion-tests.py | 41 ++++++++++++++-- 2 files changed, 85 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 3878be27cad5fd..a16a199c55b6f7 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -5,7 +5,7 @@ use crate::{file,m3::agx_uapi,mmu,queue}; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] use crate::m3::m3_drm::Shared; use crate::alloc::Allocator as _; -use core::sync::atomic::{AtomicBool, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU8, Ordering}; #[derive(Default)] pub(crate) struct Completion; #[vtable] @@ -47,7 +47,7 @@ pub(crate) struct Packet { pub(crate) wide_visibility:KVec, pub(crate) render_attachments:KVec<[crate::m3::agx_attachments::Attachments;2]>, completion:UserFence, - finish_claimed: AtomicBool, + finish_state: AtomicU8, /// Set before a batch with any of this packet's commands can change firmware-visible state, /// and never cleared. published: AtomicBool, @@ -119,24 +119,63 @@ impl Packet { self.complete(result, true); } /// Fail the fence without making a packet rejection or cancellation a VM error. + /// Terminal device-loss errors still record on `VmStatus`. /// A published prefix still owns its mappings until the runtime retires it. pub(crate) fn fail_packet(&self,error:Error) { self.complete(Err(error), false); } fn complete(&self,result:Result,fail_vm:bool) { + const PENDING: u8 = 0; + const PACKET_FAILED: u8 = 1; + const TERMINAL: u8 = 2; // Retirement, cancellation and a queued scheduler timeout can race. - // Claim error/signal ownership once; this flag is NOT proof that the - // fence is signaled or that hardware DMA has stopped. - if self.finish_claimed.swap(true, Ordering::Relaxed) { return; } + // Claim fence error/signal ownership once while still allowing a later + // terminal GPU fault (`fail_vm == true`) on a published prefix to record + // on `VmStatus` after an earlier `fail_packet()`. + let record_vm = |e: Error| { + if let Some(status) = self.vm.status() { + if fail_vm { + status.record(e); + } else { + status.record_if_device_loss(e); + } + } + }; + match result { + Ok(()) => { + if self + .finish_state + .compare_exchange(PENDING, TERMINAL, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return; + } + } + Err(e) if fail_vm => match self.finish_state.swap(TERMINAL, Ordering::AcqRel) { + PENDING => {} + PACKET_FAILED => { + record_vm(e); + return; + } + _ => return, + }, + Err(_) => { + if self + .finish_state + .compare_exchange(PENDING, PACKET_FAILED, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return; + } + } + } if let Err(e)=result { // A guard still held here belongs to work the firmware may still run: block // mapping changes before the error fence is visible (as G15 does), so userspace // can't unmap memory under it. It stays with the packet until the runtime drops // the packet, after the firmware has provably stopped. if let Some(guard)=self.vm_job.lock().as_ref() {guard.quarantine();} - if fail_vm { - if let Some(status) = self.vm.status() { status.record(e); } - } + record_vm(e); self.completion.set_error(e); } // A scheduler job/fence and the runtime's last packet can outlive @@ -357,7 +396,7 @@ impl queue::Queue for Queue { #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] render_queue: self.render_queue.clone(),vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), - finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), + finish_state:AtomicU8::new(0),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; let mut job=self.entity.new_job(1,Job{shared:self.shared.clone(),packet})?; for sync in syncs.drain(0..in_sync_count) {if let Some(f)=sync.fence {job.add_dependency(f)?;}} diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py index 34c45cf1cb2d4b..b0f771723e4043 100644 --- a/tools/asahi/m3-packet-completion-tests.py +++ b/tools/asahi/m3-packet-completion-tests.py @@ -19,8 +19,8 @@ def method(source, signature): MOCKS = r""" use std::cell::Cell; -use std::sync::{Mutex, atomic::{AtomicBool, Ordering}}; -#[derive(Clone, Copy)] +use std::sync::{Mutex, atomic::{AtomicU8, Ordering}}; +#[derive(Clone, Copy, PartialEq, Eq)] struct Error(i32); impl Error { fn to_errno(self) -> i32 { self.0 } @@ -28,6 +28,8 @@ def method(source, signature): type Result = std::result::Result<(), Error>; const EIO: Error = Error(-5); const EBUSY: Error = Error(-16); +const ENODEV: Error = Error(-19); +const ETIMEDOUT: Error = Error(-110); const ECANCELED: Error = Error(-125); #[derive(Default)] @@ -42,6 +44,11 @@ def method(source, signature): self.error.set(error.0); } } + fn record_if_device_loss(&self, error: Error) { + if error == EIO || error == ETIMEDOUT || error == ENODEV { + self.record(error); + } + } fn submit(&self) -> Result { match self.error.get() { 0 => Ok(()), @@ -66,7 +73,7 @@ def method(source, signature): struct Packet<'a> { vm: &'a Vm, vm_job: JobGuard, - finish_claimed: AtomicBool, + finish_state: AtomicU8, completion: Fence, commands: [(); 1], } @@ -89,7 +96,7 @@ def method(source, signature): Self { vm, vm_job: JobGuard(Mutex::new(guard.then(Guard::default))), - finish_claimed: AtomicBool::new(false), + finish_state: AtomicU8::new(0), completion: Fence::default(), commands: [()], } @@ -144,6 +151,32 @@ def method(source, signature): assert_eq!(faulty.completion.signals.get(), 1); assert_eq!(faulty.completion.error.get(), -5); } + +#[test] +fn cancel_before_terminal_fault_records_vm_error_without_resignaling() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); + packet.finish(Err(EIO)); + assert_eq!(vm.error.get(), -5); + assert_eq!(packet.completion.signals.get(), 1); + assert_eq!(packet.completion.error.get(), -125); +} + +#[test] +fn fail_packet_records_device_loss_errors() { + for err in [EIO, ETIMEDOUT, ENODEV] { + let vm = Vm::default(); + let packet = Packet::new(&vm, false); + packet.fail_packet(err); + assert_eq!(vm.error.get(), err.0); + assert_eq!(packet.completion.error.get(), err.0); + assert_eq!(packet.completion.signals.get(), 1); + } +} """ From fe951ba7891c4d46b3c15f0359033ba3847b8a5c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:47:04 +1100 Subject: [PATCH 0920/1514] dmaengine: apple-sio: keep rejected tables on firmware-only path When protocol 10 has no usable table list, probe has a running coprocessor and no usable DMA service. Reuse firmware-only probe completion before shared-memory setup and DMA registration so the sleep callbacks remain attached. Signed-off-by: Ryan Murray --- drivers/dma/apple-sio.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index 8fa59e76235e5e..fc1a02f3d12efc 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -2150,6 +2150,10 @@ static int sio_probe(struct platform_device *pdev) err = sio_send_dt_params(sio); if (err < 0) return dev_err_probe(&pdev->dev, err, "failed to send boot-up parameters\n"); + if (sio->tables_mismatch) { + sio->firmware_only = true; + goto rpm_put; + } err = sio_alloc_shmem(sio); if (err < 0) From e107fb193e0ac318ea9fb1b09f232b8d7e98e8a0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:52:16 +1100 Subject: [PATCH 0921/1514] arm64: configs: add aurora_defconfig, the fleet kernel configuration Fleet kernels have been configured from a Fedora asahi base config kept outside the tree, with asahi.config and one lab line merged on top. That cannot be reproduced from the tree alone. aurora_defconfig is the savedefconfig output of that configuration at this commit. `make aurora_defconfig asahi.config` produces a .config identical to the fleet recipe here and to the 7.3.0-aurora-fleet87 kit config (same toolchain: clang 22.1.6, rustc 1.97.1, pahole 1.31). Regenerate it with savedefconfig when the fleet configuration changes; the release workflow warns when asahi.config has moved past it. Signed-off-by: Ryan Murray --- arch/arm64/configs/aurora_defconfig | 5568 +++++++++++++++++++++++++++ 1 file changed, 5568 insertions(+) create mode 100644 arch/arm64/configs/aurora_defconfig diff --git a/arch/arm64/configs/aurora_defconfig b/arch/arm64/configs/aurora_defconfig new file mode 100644 index 00000000000000..cd57de3bb1a375 --- /dev/null +++ b/arch/arm64/configs/aurora_defconfig @@ -0,0 +1,5568 @@ +CONFIG_UAPI_HEADER_TEST=y +# CONFIG_LOCALVERSION_AUTO is not set +CONFIG_BUILD_SALT="7.0.13-400.asahi.fc44.aarch64" +CONFIG_KERNEL_ZSTD=y +CONFIG_SYSVIPC=y +CONFIG_POSIX_MQUEUE=y +CONFIG_WATCH_QUEUE=y +CONFIG_AUDIT=y +CONFIG_NO_HZ_FULL=y +CONFIG_NO_HZ=y +CONFIG_HIGH_RES_TIMERS=y +CONFIG_POSIX_AUX_CLOCKS=y +CONFIG_BPF_JIT=y +CONFIG_BPF_JIT_ALWAYS_ON=y +CONFIG_BPF_PRELOAD=y +CONFIG_BPF_LSM=y +CONFIG_PREEMPT_DYNAMIC=y +CONFIG_SCHED_CORE=y +CONFIG_SCHED_CLASS_EXT=y +CONFIG_IRQ_TIME_ACCOUNTING=y +CONFIG_BSD_PROCESS_ACCT=y +CONFIG_BSD_PROCESS_ACCT_V3=y +CONFIG_TASKSTATS=y +CONFIG_TASK_DELAY_ACCT=y +CONFIG_TASK_XACCT=y +CONFIG_TASK_IO_ACCOUNTING=y +CONFIG_PSI=y +CONFIG_IKHEADERS=m +CONFIG_LOG_BUF_SHIFT=18 +CONFIG_PRINTK_INDEX=y +CONFIG_UCLAMP_TASK=y +CONFIG_NUMA_BALANCING=y +CONFIG_MEMCG=y +CONFIG_MEMCG_V1=y +CONFIG_BLK_CGROUP=y +CONFIG_CFS_BANDWIDTH=y +CONFIG_UCLAMP_TASK_GROUP=y +CONFIG_CGROUP_PIDS=y +CONFIG_CGROUP_RDMA=y +CONFIG_CGROUP_DMEM=y +CONFIG_CGROUP_FREEZER=y +CONFIG_CPUSETS=y +CONFIG_CGROUP_DEVICE=y +CONFIG_CGROUP_CPUACCT=y +CONFIG_CGROUP_PERF=y +CONFIG_CGROUP_BPF=y +CONFIG_CGROUP_MISC=y +CONFIG_NAMESPACES=y +CONFIG_USER_NS=y +CONFIG_CHECKPOINT_RESTORE=y +CONFIG_SCHED_AUTOGROUP=y +# CONFIG_INITRAMFS_PRESERVE_MTIME is not set +CONFIG_SYSFS_SYSCALL=y +CONFIG_EXPERT=y +CONFIG_SGETMASK_SYSCALL=y +CONFIG_PROFILING=y +CONFIG_RUST=y +CONFIG_KEXEC=y +CONFIG_KEXEC_SIG=y +CONFIG_CRASH_DM_CRYPT=y +CONFIG_KEXEC_HANDOVER=y +CONFIG_LIVEUPDATE=y +CONFIG_ARCH_SUNXI=y +CONFIG_ARCH_APPLE=y +CONFIG_ARCH_BCM=y +CONFIG_ARCH_BCM2835=y +CONFIG_ARCH_BST=y +CONFIG_ARCH_CIX=y +CONFIG_ARCH_K3=y +CONFIG_ARCH_HISI=y +CONFIG_ARCH_MESON=y +CONFIG_ARCH_MVEBU=y +CONFIG_ARCH_NXP=y +CONFIG_ARCH_LAYERSCAPE=y +CONFIG_ARCH_MXC=y +CONFIG_ARCH_S32=y +CONFIG_ARCH_QCOM=y +CONFIG_ARCH_RENESAS=y +CONFIG_ARCH_ROCKCHIP=y +CONFIG_ARCH_SEATTLE=y +CONFIG_ARCH_SYNQUACER=y +CONFIG_ARCH_TEGRA=y +CONFIG_ARCH_THUNDER=y +CONFIG_ARCH_THUNDER2=y +CONFIG_ARCH_VEXPRESS=y +CONFIG_ARCH_XGENE=y +CONFIG_ARCH_ZYNQMP=y +CONFIG_ARM64_ERRATUM_834220=y +CONFIG_ARM64_ERRATUM_2441007=y +CONFIG_ARM64_ERRATUM_1286807=y +CONFIG_ARM64_ERRATUM_1542419=y +CONFIG_ARM64_ERRATUM_2441009=y +# CONFIG_QCOM_FALKOR_ERRATUM_1003 is not set +CONFIG_ARM64_16K_PAGES=y +CONFIG_ARM64_VA_BITS_48=y +CONFIG_NR_CPUS=4096 +CONFIG_NUMA=y +CONFIG_NODES_SHIFT=9 +CONFIG_HZ_1000=y +CONFIG_PARAVIRT_TIME_ACCOUNTING=y +CONFIG_ARM64_SW_TTBR0_PAN=y +CONFIG_COMPAT=y +CONFIG_ARMV8_DEPRECATED=y +CONFIG_SWP_EMULATION=y +CONFIG_CP15_BARRIER_EMULATION=y +CONFIG_SETEND_EMULATION=y +CONFIG_ARM64_PMEM=y +CONFIG_ARM64_PSEUDO_NMI=y +CONFIG_ARM64_MEMORY_MODEL_CONTROL=y +CONFIG_RANDOMIZE_BASE=y +CONFIG_ARM64_CTXR_EXECMEM=y +CONFIG_ARM64_ACPI_PARKING_PROTOCOL=y +CONFIG_COMPRESSED_INSTALL=y +CONFIG_HIBERNATION=y +CONFIG_PM_QOS_CPU_SYSTEM_WAKEUP=y +CONFIG_PM_DEBUG=y +CONFIG_PM_TEST_SUSPEND=y +CONFIG_ENERGY_MODEL=y +CONFIG_ARM_PSCI_CPUIDLE=y +CONFIG_CPU_FREQ=y +CONFIG_CPU_FREQ_STAT=y +CONFIG_CPU_FREQ_GOV_POWERSAVE=y +CONFIG_CPU_FREQ_GOV_USERSPACE=y +CONFIG_CPU_FREQ_GOV_ONDEMAND=y +CONFIG_CPU_FREQ_GOV_CONSERVATIVE=y +CONFIG_CPUFREQ_DT=m +CONFIG_CPUFREQ_VIRT=m +CONFIG_ARM_ALLWINNER_SUN50I_CPUFREQ_NVMEM=m +CONFIG_ARM_APPLE_SOC_CPUFREQ=m +CONFIG_ARM_ARMADA_37XX_CPUFREQ=m +CONFIG_ARM_ARMADA_8K_CPUFREQ=m +CONFIG_ARM_SCPI_CPUFREQ=m +CONFIG_ARM_IMX_CPUFREQ_DT=m +CONFIG_ARM_QCOM_CPUFREQ_NVMEM=m +CONFIG_ARM_QCOM_CPUFREQ_HW=m +CONFIG_ARM_RASPBERRYPI_CPUFREQ=m +CONFIG_ARM_SCMI_CPUFREQ=m +# CONFIG_ARM_TEGRA20_CPUFREQ is not set +CONFIG_ARM_TEGRA186_CPUFREQ=m +CONFIG_ARM_TEGRA194_CPUFREQ=m +CONFIG_QORIQ_CPUFREQ=m +CONFIG_ACPI_CPPC_CPUFREQ=m +# CONFIG_ACPI_CPPC_CPUFREQ_FIE is not set +CONFIG_ACPI=y +CONFIG_ACPI_FPDT=y +CONFIG_ACPI_EC=y +CONFIG_ACPI_TAD=m +CONFIG_ACPI_DOCK=y +CONFIG_ACPI_IPMI=m +CONFIG_ACPI_PCI_SLOT=y +CONFIG_ACPI_HOTPLUG_MEMORY=y +CONFIG_ACPI_BGRT=y +CONFIG_ACPI_NFIT=m +CONFIG_ACPI_APEI=y +CONFIG_ACPI_APEI_GHES=y +CONFIG_ACPI_APEI_PCIEAER=y +CONFIG_ACPI_APEI_MEMORY_FAILURE=y +CONFIG_ACPI_APEI_EINJ=m +CONFIG_ACPI_PFRUT=m +CONFIG_ACPI_AGDI=y +CONFIG_ACPI_FFH=y +CONFIG_VIRTUALIZATION=y +CONFIG_KVM=y +CONFIG_LIVEPATCH=y +# CONFIG_SCHED_CLUSTER is not set +CONFIG_ARCH_MMAP_RND_BITS=18 +CONFIG_ARCH_MMAP_RND_COMPAT_BITS=11 +CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT=y +# CONFIG_RELR is not set +CONFIG_MODULES=y +CONFIG_MODULE_UNLOAD=y +CONFIG_MODULE_UNLOAD_TAINT_TRACKING=y +CONFIG_MODULE_COMPRESS=y +CONFIG_MODULE_COMPRESS_XZ=y +# CONFIG_MODULE_COMPRESS_ALL is not set +CONFIG_MODULE_DECOMPRESS=y +CONFIG_MODPROBE_PATH="/usr/sbin/modprobe" +CONFIG_BLK_DEV_ZONED=y +CONFIG_BLK_DEV_THROTTLING=y +CONFIG_BLK_WBT=y +CONFIG_BLK_CGROUP_IOLATENCY=y +CONFIG_BLK_CGROUP_FC_APPID=y +CONFIG_BLK_CGROUP_IOCOST=y +CONFIG_BLK_CGROUP_IOPRIO=y +CONFIG_BLK_SED_OPAL=y +CONFIG_PARTITION_ADVANCED=y +CONFIG_AIX_PARTITION=y +CONFIG_OSF_PARTITION=y +CONFIG_MAC_PARTITION=y +CONFIG_BSD_DISKLABEL=y +CONFIG_MINIX_SUBPARTITION=y +CONFIG_SOLARIS_X86_PARTITION=y +CONFIG_UNIXWARE_DISKLABEL=y +CONFIG_LDM_PARTITION=y +CONFIG_SGI_PARTITION=y +CONFIG_SUN_PARTITION=y +CONFIG_OF_PARTITION=y +CONFIG_IOSCHED_BFQ=y +CONFIG_BINFMT_MISC=m +CONFIG_ZSWAP=y +CONFIG_ZSWAP_SHRINKER_DEFAULT_ON=y +# CONFIG_SLAB_MERGE_DEFAULT is not set +CONFIG_SLAB_FREELIST_RANDOM=y +CONFIG_SLAB_FREELIST_HARDENED=y +CONFIG_KMALLOC_PARTITION_CACHES=y +# CONFIG_COMPAT_BRK is not set +CONFIG_MEMORY_HOTPLUG=y +CONFIG_MHP_DEFAULT_ONLINE_TYPE_ONLINE_AUTO=y +CONFIG_MEMORY_HOTREMOVE=y +CONFIG_KSM=y +CONFIG_DEFAULT_MMAP_MIN_ADDR=65536 +CONFIG_MEMORY_FAILURE=y +CONFIG_HWPOISON_INJECT=m +CONFIG_TRANSPARENT_HUGEPAGE=y +CONFIG_TRANSPARENT_HUGEPAGE_MADVISE=y +CONFIG_CMA_SYSFS=y +CONFIG_CMA_AREAS=7 +CONFIG_PAGE_BLOCK_MAX_ORDER=7 +CONFIG_IDLE_PAGE_TRACKING=y +CONFIG_ZONE_DEVICE=y +CONFIG_DEVICE_PRIVATE=y +CONFIG_USERFAULTFD=y +CONFIG_LRU_GEN=y +CONFIG_LRU_GEN_ENABLED=y +CONFIG_DAMON=y +CONFIG_DAMON_RECLAIM=y +CONFIG_DAMON_STAT=y +# CONFIG_DAMON_STAT_ENABLED_DEFAULT is not set +CONFIG_NET=y +CONFIG_PACKET=y +CONFIG_PACKET_DIAG=y +CONFIG_INET_PSP=y +CONFIG_UNIX_DIAG=y +CONFIG_TLS_DEVICE=y +CONFIG_XFRM_USER=y +CONFIG_XFRM_INTERFACE=m +CONFIG_XFRM_SUB_POLICY=y +CONFIG_XFRM_STATISTICS=y +CONFIG_NET_KEY=m +CONFIG_NET_KEY_MIGRATE=y +CONFIG_XFRM_IPTFS=m +CONFIG_SMC=m +CONFIG_SMC_DIAG=m +CONFIG_DIBS=m +CONFIG_DIBS_LO=y +CONFIG_XDP_SOCKETS=y +CONFIG_XDP_SOCKETS_DIAG=m +CONFIG_IP_MULTICAST=y +CONFIG_IP_ADVANCED_ROUTER=y +CONFIG_IP_FIB_TRIE_STATS=y +CONFIG_IP_MULTIPLE_TABLES=y +CONFIG_IP_ROUTE_MULTIPATH=y +CONFIG_IP_ROUTE_VERBOSE=y +CONFIG_NET_IPIP=m +CONFIG_NET_IPGRE_DEMUX=m +CONFIG_NET_IPGRE=m +CONFIG_NET_IPGRE_BROADCAST=y +CONFIG_IP_MROUTE=y +CONFIG_IP_MROUTE_MULTIPLE_TABLES=y +CONFIG_IP_PIMSM_V1=y +CONFIG_IP_PIMSM_V2=y +CONFIG_NET_IPVTI=m +CONFIG_NET_FOU_IP_TUNNELS=y +CONFIG_INET_AH=m +CONFIG_INET_ESP=m +CONFIG_INET_ESP_OFFLOAD=m +CONFIG_INET_ESPINTCP=y +CONFIG_INET_IPCOMP=m +CONFIG_INET_UDP_DIAG=y +CONFIG_INET_RAW_DIAG=y +CONFIG_INET_DIAG_DESTROY=y +CONFIG_TCP_CONG_ADVANCED=y +CONFIG_TCP_CONG_HSTCP=m +CONFIG_TCP_CONG_HYBLA=m +CONFIG_TCP_CONG_NV=m +CONFIG_TCP_CONG_SCALABLE=m +CONFIG_TCP_CONG_LP=m +CONFIG_TCP_CONG_VENO=m +CONFIG_TCP_CONG_YEAH=m +CONFIG_TCP_CONG_ILLINOIS=m +CONFIG_TCP_CONG_DCTCP=m +CONFIG_TCP_CONG_CDG=m +CONFIG_TCP_CONG_BBR=m +CONFIG_TCP_AO=y +CONFIG_TCP_MD5SIG=y +CONFIG_IPV6_ROUTER_PREF=y +CONFIG_IPV6_ROUTE_INFO=y +CONFIG_IPV6_OPTIMISTIC_DAD=y +CONFIG_INET6_AH=m +CONFIG_INET6_ESP=m +CONFIG_INET6_ESP_OFFLOAD=m +CONFIG_INET6_ESPINTCP=y +CONFIG_INET6_IPCOMP=m +CONFIG_IPV6_MIP6=y +CONFIG_IPV6_ILA=m +CONFIG_IPV6_VTI=m +CONFIG_IPV6_SIT_6RD=y +CONFIG_IPV6_GRE=m +CONFIG_IPV6_SUBTREES=y +CONFIG_IPV6_MROUTE=y +CONFIG_IPV6_MROUTE_MULTIPLE_TABLES=y +CONFIG_IPV6_PIMSM_V2=y +CONFIG_IPV6_SEG6_LWTUNNEL=y +CONFIG_IPV6_SEG6_HMAC=y +CONFIG_IPV6_RPL_LWTUNNEL=y +CONFIG_IPV6_IOAM6_LWTUNNEL=y +CONFIG_NETLABEL=y +CONFIG_MPTCP=y +CONFIG_NETWORK_PHY_TIMESTAMPING=y +CONFIG_NETFILTER=y +CONFIG_BRIDGE_NETFILTER=m +CONFIG_NETFILTER_NETLINK_HOOK=m +CONFIG_NF_CONNTRACK=m +CONFIG_NF_CONNTRACK_SECMARK=y +CONFIG_NF_CONNTRACK_ZONES=y +CONFIG_NF_CONNTRACK_PROCFS=y +CONFIG_NF_CONNTRACK_EVENTS=y +CONFIG_NF_CONNTRACK_TIMEOUT=y +CONFIG_NF_CONNTRACK_TIMESTAMP=y +CONFIG_NF_CONNTRACK_AMANDA=m +CONFIG_NF_CONNTRACK_FTP=m +CONFIG_NF_CONNTRACK_H323=m +CONFIG_NF_CONNTRACK_IRC=m +CONFIG_NF_CONNTRACK_NETBIOS_NS=m +CONFIG_NF_CONNTRACK_SNMP=m +CONFIG_NF_CONNTRACK_PPTP=m +CONFIG_NF_CONNTRACK_SANE=m +CONFIG_NF_CONNTRACK_SIP=m +CONFIG_NF_CONNTRACK_TFTP=m +CONFIG_NF_CT_NETLINK=m +CONFIG_NF_CT_NETLINK_TIMEOUT=m +CONFIG_NF_CT_NETLINK_HELPER=m +CONFIG_NETFILTER_NETLINK_GLUE_CT=y +CONFIG_NF_TABLES=m +CONFIG_NF_TABLES_INET=y +CONFIG_NF_TABLES_NETDEV=y +CONFIG_NFT_NUMGEN=m +CONFIG_NFT_CT=m +CONFIG_NFT_FLOW_OFFLOAD=m +CONFIG_NFT_CONNLIMIT=m +CONFIG_NFT_LOG=m +CONFIG_NFT_LIMIT=m +CONFIG_NFT_MASQ=m +CONFIG_NFT_REDIR=m +CONFIG_NFT_NAT=m +CONFIG_NFT_TUNNEL=m +CONFIG_NFT_QUEUE=m +CONFIG_NFT_QUOTA=m +CONFIG_NFT_REJECT=m +CONFIG_NFT_COMPAT=m +CONFIG_NFT_HASH=m +CONFIG_NFT_FIB_INET=m +CONFIG_NFT_XFRM=m +CONFIG_NFT_SOCKET=m +CONFIG_NFT_OSF=m +CONFIG_NFT_TPROXY=m +CONFIG_NFT_SYNPROXY=m +CONFIG_NFT_DUP_NETDEV=m +CONFIG_NFT_FWD_NETDEV=m +CONFIG_NFT_FIB_NETDEV=m +CONFIG_NFT_REJECT_NETDEV=m +CONFIG_NF_FLOW_TABLE_INET=m +CONFIG_NF_FLOW_TABLE=m +CONFIG_NF_FLOW_TABLE_PROCFS=y +CONFIG_NETFILTER_XTABLES=y +CONFIG_NETFILTER_XTABLES_LEGACY=y +CONFIG_NETFILTER_XT_SET=m +CONFIG_NETFILTER_XT_TARGET_AUDIT=m +CONFIG_NETFILTER_XT_TARGET_CHECKSUM=m +CONFIG_NETFILTER_XT_TARGET_CLASSIFY=m +CONFIG_NETFILTER_XT_TARGET_CONNMARK=m +CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=m +CONFIG_NETFILTER_XT_TARGET_DSCP=m +CONFIG_NETFILTER_XT_TARGET_HMARK=m +CONFIG_NETFILTER_XT_TARGET_IDLETIMER=m +CONFIG_NETFILTER_XT_TARGET_LED=m +CONFIG_NETFILTER_XT_TARGET_LOG=m +CONFIG_NETFILTER_XT_TARGET_MARK=m +CONFIG_NETFILTER_XT_TARGET_NFLOG=m +CONFIG_NETFILTER_XT_TARGET_NFQUEUE=m +CONFIG_NETFILTER_XT_TARGET_NOTRACK=m +CONFIG_NETFILTER_XT_TARGET_TEE=m +CONFIG_NETFILTER_XT_TARGET_TPROXY=m +CONFIG_NETFILTER_XT_TARGET_TRACE=m +CONFIG_NETFILTER_XT_TARGET_SECMARK=m +CONFIG_NETFILTER_XT_TARGET_TCPMSS=m +CONFIG_NETFILTER_XT_TARGET_TCPOPTSTRIP=m +CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=m +CONFIG_NETFILTER_XT_MATCH_BPF=m +CONFIG_NETFILTER_XT_MATCH_CGROUP=m +CONFIG_NETFILTER_XT_MATCH_CLUSTER=m +CONFIG_NETFILTER_XT_MATCH_COMMENT=m +CONFIG_NETFILTER_XT_MATCH_CONNBYTES=m +CONFIG_NETFILTER_XT_MATCH_CONNLABEL=m +CONFIG_NETFILTER_XT_MATCH_CONNLIMIT=m +CONFIG_NETFILTER_XT_MATCH_CONNMARK=m +CONFIG_NETFILTER_XT_MATCH_CONNTRACK=m +CONFIG_NETFILTER_XT_MATCH_CPU=m +CONFIG_NETFILTER_XT_MATCH_DCCP=m +CONFIG_NETFILTER_XT_MATCH_DEVGROUP=m +CONFIG_NETFILTER_XT_MATCH_DSCP=m +CONFIG_NETFILTER_XT_MATCH_ESP=m +CONFIG_NETFILTER_XT_MATCH_HASHLIMIT=m +CONFIG_NETFILTER_XT_MATCH_HELPER=m +CONFIG_NETFILTER_XT_MATCH_IPCOMP=m +CONFIG_NETFILTER_XT_MATCH_IPRANGE=m +CONFIG_NETFILTER_XT_MATCH_IPVS=m +CONFIG_NETFILTER_XT_MATCH_LENGTH=m +CONFIG_NETFILTER_XT_MATCH_LIMIT=m +CONFIG_NETFILTER_XT_MATCH_MAC=m +CONFIG_NETFILTER_XT_MATCH_MARK=m +CONFIG_NETFILTER_XT_MATCH_MULTIPORT=m +CONFIG_NETFILTER_XT_MATCH_NFACCT=m +CONFIG_NETFILTER_XT_MATCH_OSF=m +CONFIG_NETFILTER_XT_MATCH_OWNER=m +CONFIG_NETFILTER_XT_MATCH_POLICY=m +CONFIG_NETFILTER_XT_MATCH_PHYSDEV=m +CONFIG_NETFILTER_XT_MATCH_PKTTYPE=m +CONFIG_NETFILTER_XT_MATCH_QUOTA=m +CONFIG_NETFILTER_XT_MATCH_RATEEST=m +CONFIG_NETFILTER_XT_MATCH_REALM=m +CONFIG_NETFILTER_XT_MATCH_RECENT=m +CONFIG_NETFILTER_XT_MATCH_SOCKET=m +CONFIG_NETFILTER_XT_MATCH_STATE=m +CONFIG_NETFILTER_XT_MATCH_STATISTIC=m +CONFIG_NETFILTER_XT_MATCH_STRING=m +CONFIG_NETFILTER_XT_MATCH_TCPMSS=m +CONFIG_NETFILTER_XT_MATCH_TIME=m +CONFIG_NETFILTER_XT_MATCH_U32=m +CONFIG_IP_SET=m +CONFIG_IP_SET_BITMAP_IP=m +CONFIG_IP_SET_BITMAP_IPMAC=m +CONFIG_IP_SET_BITMAP_PORT=m +CONFIG_IP_SET_HASH_IP=m +CONFIG_IP_SET_HASH_IPMARK=m +CONFIG_IP_SET_HASH_IPPORT=m +CONFIG_IP_SET_HASH_IPPORTIP=m +CONFIG_IP_SET_HASH_IPPORTNET=m +CONFIG_IP_SET_HASH_IPMAC=m +CONFIG_IP_SET_HASH_MAC=m +CONFIG_IP_SET_HASH_NETPORTNET=m +CONFIG_IP_SET_HASH_NET=m +CONFIG_IP_SET_HASH_NETNET=m +CONFIG_IP_SET_HASH_NETPORT=m +CONFIG_IP_SET_HASH_NETIFACE=m +CONFIG_IP_SET_LIST_SET=m +CONFIG_IP_VS=m +CONFIG_IP_VS_IPV6=y +CONFIG_IP_VS_PROTO_TCP=y +CONFIG_IP_VS_PROTO_UDP=y +CONFIG_IP_VS_PROTO_ESP=y +CONFIG_IP_VS_PROTO_AH=y +CONFIG_IP_VS_PROTO_SCTP=y +CONFIG_IP_VS_RR=m +CONFIG_IP_VS_WRR=m +CONFIG_IP_VS_LC=m +CONFIG_IP_VS_WLC=m +CONFIG_IP_VS_FO=m +CONFIG_IP_VS_OVF=m +CONFIG_IP_VS_LBLC=m +CONFIG_IP_VS_LBLCR=m +CONFIG_IP_VS_DH=m +CONFIG_IP_VS_SH=m +CONFIG_IP_VS_MH=m +CONFIG_IP_VS_SED=m +CONFIG_IP_VS_NQ=m +CONFIG_IP_VS_TWOS=m +CONFIG_IP_VS_FTP=m +CONFIG_IP_VS_PE_SIP=m +CONFIG_NFT_DUP_IPV4=m +CONFIG_NFT_FIB_IPV4=m +CONFIG_NF_TABLES_ARP=y +CONFIG_NF_LOG_ARP=m +CONFIG_NF_LOG_IPV4=m +CONFIG_IP_NF_IPTABLES=m +CONFIG_IP_NF_MATCH_AH=m +CONFIG_IP_NF_MATCH_ECN=m +CONFIG_IP_NF_MATCH_RPFILTER=m +CONFIG_IP_NF_MATCH_TTL=m +CONFIG_IP_NF_TARGET_REJECT=m +CONFIG_IP_NF_TARGET_SYNPROXY=m +CONFIG_IP_NF_NAT=m +CONFIG_IP_NF_TARGET_MASQUERADE=m +CONFIG_IP_NF_TARGET_NETMAP=m +CONFIG_IP_NF_TARGET_REDIRECT=m +CONFIG_IP_NF_TARGET_ECN=m +CONFIG_IP_NF_TARGET_TTL=m +CONFIG_IP_NF_RAW=m +CONFIG_IP_NF_SECURITY=m +CONFIG_IP_NF_ARPFILTER=m +CONFIG_IP_NF_ARP_MANGLE=m +CONFIG_NFT_DUP_IPV6=m +CONFIG_NFT_FIB_IPV6=m +CONFIG_IP6_NF_IPTABLES=m +CONFIG_IP6_NF_MATCH_AH=m +CONFIG_IP6_NF_MATCH_EUI64=m +CONFIG_IP6_NF_MATCH_FRAG=m +CONFIG_IP6_NF_MATCH_OPTS=m +CONFIG_IP6_NF_MATCH_HL=m +CONFIG_IP6_NF_MATCH_IPV6HEADER=m +CONFIG_IP6_NF_MATCH_MH=m +CONFIG_IP6_NF_MATCH_RPFILTER=m +CONFIG_IP6_NF_MATCH_RT=m +CONFIG_IP6_NF_MATCH_SRH=m +CONFIG_IP6_NF_TARGET_HL=m +CONFIG_IP6_NF_TARGET_REJECT=m +CONFIG_IP6_NF_TARGET_SYNPROXY=m +CONFIG_IP6_NF_RAW=m +CONFIG_IP6_NF_SECURITY=m +CONFIG_IP6_NF_NAT=m +CONFIG_IP6_NF_TARGET_MASQUERADE=m +CONFIG_IP6_NF_TARGET_NPT=m +CONFIG_NF_TABLES_BRIDGE=m +CONFIG_NFT_BRIDGE_META=m +CONFIG_NFT_BRIDGE_REJECT=m +CONFIG_NF_CONNTRACK_BRIDGE=m +CONFIG_BRIDGE_NF_EBTABLES_LEGACY=m +CONFIG_BRIDGE_NF_EBTABLES=m +CONFIG_BRIDGE_EBT_BROUTE=m +CONFIG_BRIDGE_EBT_T_FILTER=m +CONFIG_BRIDGE_EBT_T_NAT=m +CONFIG_BRIDGE_EBT_802_3=m +CONFIG_BRIDGE_EBT_AMONG=m +CONFIG_BRIDGE_EBT_ARP=m +CONFIG_BRIDGE_EBT_IP=m +CONFIG_BRIDGE_EBT_IP6=m +CONFIG_BRIDGE_EBT_LIMIT=m +CONFIG_BRIDGE_EBT_MARK=m +CONFIG_BRIDGE_EBT_PKTTYPE=m +CONFIG_BRIDGE_EBT_STP=m +CONFIG_BRIDGE_EBT_VLAN=m +CONFIG_BRIDGE_EBT_ARPREPLY=m +CONFIG_BRIDGE_EBT_DNAT=m +CONFIG_BRIDGE_EBT_MARK_T=m +CONFIG_BRIDGE_EBT_REDIRECT=m +CONFIG_BRIDGE_EBT_SNAT=m +CONFIG_BRIDGE_EBT_LOG=m +CONFIG_BRIDGE_EBT_NFLOG=m +CONFIG_IP_SCTP=m +CONFIG_TIPC=m +CONFIG_ATM=m +CONFIG_ATM_BR2684=m +CONFIG_L2TP=m +CONFIG_L2TP_DEBUGFS=m +CONFIG_L2TP_V3=y +CONFIG_L2TP_IP=m +CONFIG_L2TP_ETH=m +CONFIG_BRIDGE=m +CONFIG_BRIDGE_VLAN_FILTERING=y +CONFIG_BRIDGE_MRP=y +CONFIG_BRIDGE_CFM=y +CONFIG_NET_DSA=m +CONFIG_NET_DSA_TAG_GSWIP=m +CONFIG_NET_DSA_TAG_KSZ=m +CONFIG_NET_DSA_TAG_OCELOT=m +CONFIG_NET_DSA_TAG_OCELOT_8021Q=m +CONFIG_NET_DSA_TAG_RTL4_A=m +CONFIG_NET_DSA_TAG_RTL8_4=m +CONFIG_NET_DSA_TAG_SJA1105=m +CONFIG_NET_DSA_TAG_TRAILER=m +CONFIG_VLAN_8021Q=m +CONFIG_VLAN_8021Q_GVRP=y +CONFIG_VLAN_8021Q_MVRP=y +CONFIG_6LOWPAN=m +CONFIG_6LOWPAN_DEBUGFS=y +CONFIG_6LOWPAN_GHC_EXT_HDR_HOP=m +CONFIG_6LOWPAN_GHC_UDP=m +CONFIG_6LOWPAN_GHC_ICMPV6=m +CONFIG_6LOWPAN_GHC_EXT_HDR_DEST=m +CONFIG_6LOWPAN_GHC_EXT_HDR_FRAG=m +CONFIG_6LOWPAN_GHC_EXT_HDR_ROUTE=m +CONFIG_IEEE802154=m +CONFIG_IEEE802154_6LOWPAN=m +CONFIG_MAC802154=m +CONFIG_NET_SCHED=y +CONFIG_NET_SCH_HTB=m +CONFIG_NET_SCH_HFSC=m +CONFIG_NET_SCH_PRIO=m +CONFIG_NET_SCH_MULTIQ=m +CONFIG_NET_SCH_RED=m +CONFIG_NET_SCH_SFB=m +CONFIG_NET_SCH_SFQ=m +CONFIG_NET_SCH_TEQL=m +CONFIG_NET_SCH_TBF=m +CONFIG_NET_SCH_CBS=m +CONFIG_NET_SCH_ETF=m +CONFIG_NET_SCH_TAPRIO=m +CONFIG_NET_SCH_GRED=m +CONFIG_NET_SCH_NETEM=m +CONFIG_NET_SCH_DRR=m +CONFIG_NET_SCH_MQPRIO=m +CONFIG_NET_SCH_CHOKE=m +CONFIG_NET_SCH_QFQ=m +CONFIG_NET_SCH_CODEL=m +CONFIG_NET_SCH_FQ_CODEL=y +CONFIG_NET_SCH_CAKE=m +CONFIG_NET_SCH_FQ=m +CONFIG_NET_SCH_HHF=m +CONFIG_NET_SCH_PIE=m +CONFIG_NET_SCH_FQ_PIE=m +CONFIG_NET_SCH_INGRESS=m +CONFIG_NET_SCH_PLUG=m +CONFIG_NET_SCH_ETS=m +CONFIG_NET_SCH_BPF=y +CONFIG_NET_SCH_DUALPI2=m +CONFIG_NET_CLS_BASIC=m +CONFIG_NET_CLS_ROUTE4=m +CONFIG_NET_CLS_FW=m +CONFIG_NET_CLS_U32=m +CONFIG_CLS_U32_PERF=y +CONFIG_CLS_U32_MARK=y +CONFIG_NET_CLS_FLOW=m +CONFIG_NET_CLS_CGROUP=y +CONFIG_NET_CLS_BPF=m +CONFIG_NET_CLS_FLOWER=m +CONFIG_NET_CLS_MATCHALL=m +CONFIG_NET_EMATCH=y +CONFIG_NET_EMATCH_CMP=m +CONFIG_NET_EMATCH_NBYTE=m +CONFIG_NET_EMATCH_U32=m +CONFIG_NET_EMATCH_META=m +CONFIG_NET_EMATCH_TEXT=m +CONFIG_NET_EMATCH_CANID=m +CONFIG_NET_EMATCH_IPSET=m +CONFIG_NET_EMATCH_IPT=m +CONFIG_NET_CLS_ACT=y +CONFIG_NET_ACT_POLICE=m +CONFIG_NET_ACT_GACT=m +CONFIG_GACT_PROB=y +CONFIG_NET_ACT_MIRRED=m +CONFIG_NET_ACT_SAMPLE=m +CONFIG_NET_ACT_NAT=m +CONFIG_NET_ACT_PEDIT=m +CONFIG_NET_ACT_SIMP=m +CONFIG_NET_ACT_SKBEDIT=m +CONFIG_NET_ACT_CSUM=m +CONFIG_NET_ACT_MPLS=m +CONFIG_NET_ACT_VLAN=m +CONFIG_NET_ACT_BPF=m +CONFIG_NET_ACT_CONNMARK=m +CONFIG_NET_ACT_CTINFO=m +CONFIG_NET_ACT_SKBMOD=m +CONFIG_NET_ACT_IFE=m +CONFIG_NET_ACT_TUNNEL_KEY=m +CONFIG_NET_ACT_CT=m +CONFIG_NET_ACT_GATE=m +CONFIG_NET_IFE_SKBMARK=m +CONFIG_NET_IFE_SKBPRIO=m +CONFIG_NET_IFE_SKBTCINDEX=m +CONFIG_NET_TC_SKB_EXT=y +CONFIG_DCB=y +CONFIG_BATMAN_ADV=m +CONFIG_BATMAN_ADV_TRACING=y +CONFIG_OPENVSWITCH=m +CONFIG_VSOCKETS=m +CONFIG_VMWARE_VMCI_VSOCKETS=m +CONFIG_VIRTIO_VSOCKETS=m +CONFIG_HYPERV_VSOCKETS=m +CONFIG_NETLINK_DIAG=y +CONFIG_MPLS_ROUTING=m +CONFIG_MPLS_IPTUNNEL=m +CONFIG_HSR=m +CONFIG_QRTR_SMD=m +CONFIG_NET_NCSI=y +CONFIG_NCSI_OEM_CMD_GET_MAC=y +CONFIG_NCSI_OEM_CMD_KEEP_PHY=y +CONFIG_CGROUP_NET_PRIO=y +CONFIG_BPF_STREAM_PARSER=y +CONFIG_NET_PKTGEN=m +CONFIG_NET_DROP_MONITOR=y +CONFIG_CAN=y +CONFIG_CAN_RAW=m +CONFIG_CAN_BCM=m +CONFIG_CAN_GW=m +CONFIG_CAN_J1939=m +CONFIG_CAN_ISOTP=m +CONFIG_BT=m +CONFIG_BT_RFCOMM=m +CONFIG_BT_RFCOMM_TTY=y +CONFIG_BT_BNEP=m +CONFIG_BT_BNEP_MC_FILTER=y +CONFIG_BT_BNEP_PROTO_FILTER=y +CONFIG_BT_HIDP=m +CONFIG_BT_6LOWPAN=m +CONFIG_BT_LEDS=y +CONFIG_BT_MSFTEXT=y +CONFIG_BT_AOSPEXT=y +CONFIG_BT_BRCMEXT=y +# CONFIG_BT_DEBUGFS is not set +CONFIG_BT_MTK7932_PCIE=m +CONFIG_BT_HCIBTUSB=m +CONFIG_BT_HCIBTUSB_AUTOSUSPEND=y +CONFIG_BT_HCIBTUSB_MTK=y +CONFIG_BT_HCIBTSDIO=m +CONFIG_BT_HCIUART=m +CONFIG_BT_HCIUART_NOKIA=m +CONFIG_BT_HCIUART_BCSP=y +CONFIG_BT_HCIUART_ATH3K=y +CONFIG_BT_HCIUART_LL=y +CONFIG_BT_HCIUART_INTEL=y +CONFIG_BT_HCIUART_BCM=y +CONFIG_BT_HCIUART_RTL=y +CONFIG_BT_HCIUART_QCA=y +CONFIG_BT_HCIUART_AG6XX=y +CONFIG_BT_HCIUART_MRVL=y +CONFIG_BT_HCIBCM203X=m +CONFIG_BT_HCIBCM4377=m +CONFIG_BT_HCIBPA10X=m +CONFIG_BT_HCIBFUSB=m +CONFIG_BT_HCIVHCI=m +CONFIG_BT_MRVL=m +CONFIG_BT_MRVL_SDIO=m +CONFIG_BT_ATH3K=m +CONFIG_BT_MTKSDIO=m +CONFIG_BT_MTKUART=m +CONFIG_BT_QCOMSMD=m +CONFIG_BT_VIRTIO=m +CONFIG_BT_NXPUART=m +CONFIG_BT_INTEL_PCIE=m +CONFIG_BT_CENTAURI=m +CONFIG_BT_HCICENTAURI=m +CONFIG_AF_RXRPC_IPV6=y +CONFIG_AF_RXRPC_DEBUG=y +CONFIG_RXKAD=y +CONFIG_RXGK=y +CONFIG_AF_KCM=m +CONFIG_MCTP=y +CONFIG_CFG80211=m +CONFIG_CFG80211_DEBUGFS=y +CONFIG_MAC80211=m +CONFIG_MAC80211_MESH=y +CONFIG_MAC80211_DEBUGFS=y +CONFIG_RFKILL=m +CONFIG_RFKILL_INPUT=y +CONFIG_RFKILL_GPIO=m +CONFIG_NET_9P=m +CONFIG_NET_9P_VIRTIO=m +CONFIG_NET_9P_USBG=m +CONFIG_NET_9P_RDMA=m +CONFIG_NFC=m +CONFIG_NFC_DIGITAL=m +CONFIG_NFC_NCI=m +CONFIG_NFC_NCI_SPI=m +CONFIG_NFC_HCI=m +CONFIG_NFC_SHDLC=y +CONFIG_NFC_TRF7970A=m +CONFIG_NFC_SIM=m +CONFIG_NFC_PORT100=m +CONFIG_NFC_APPLE_STOCKHOLM=m +CONFIG_NFC_PN544_I2C=m +CONFIG_NFC_PN533_USB=m +CONFIG_NFC_PN533_I2C=m +CONFIG_NFC_PN532_UART=m +CONFIG_NFC_MICROREAD_I2C=m +CONFIG_NFC_MRVL_USB=m +CONFIG_NFC_ST21NFCA_I2C=m +CONFIG_NFC_NXP_NCI=m +CONFIG_NFC_NXP_NCI_I2C=m +CONFIG_PCI=y +CONFIG_PCIEAER=y +CONFIG_PCIEAER_INJECT=m +CONFIG_PCIE_ECRC=y +CONFIG_PCIE_DPC=y +CONFIG_PCIE_PTM=y +CONFIG_PCIE_EDR=y +CONFIG_PCI_STUB=y +CONFIG_PCI_PF_STUB=m +CONFIG_PCI_NPEM=y +CONFIG_PCI_PRI=y +CONFIG_PCI_PASID=y +CONFIG_PCIE_TPH=y +CONFIG_PCI_P2PDMA=y +CONFIG_PCI_HYPERV=m +CONFIG_PCI_DYNAMIC_OF_NODES=y +CONFIG_HOTPLUG_PCI_ACPI=y +CONFIG_HOTPLUG_PCI_ACPI_AMPERE_ALTRA=m +CONFIG_HOTPLUG_PCI_ACPI_IBM=m +CONFIG_HOTPLUG_PCI_OCTEONEP=y +CONFIG_PCI_AARDVARK=y +CONFIG_PCIE_APPLE_T8140_BOOTSTRAP=y +CONFIG_PCIE_APPLE=y +CONFIG_PCIE_APPLE_MSI=y +CONFIG_PCIE_BRCMSTB=y +CONFIG_PCI_HOST_THUNDER_PEM=y +CONFIG_PCI_HOST_THUNDER_ECAM=y +CONFIG_PCI_HOST_GENERIC=y +CONFIG_PCI_HYPERV_INTERFACE=y +CONFIG_PCI_TEGRA=y +CONFIG_PCIE_RENESAS_RZG3S_HOST=y +CONFIG_PCIE_ROCKCHIP_HOST=y +CONFIG_PCI_XGENE=y +CONFIG_PCIE_XILINX=y +CONFIG_PCIE_XILINX_DMA_PL=y +CONFIG_PCIE_XILINX_NWL=y +CONFIG_PCIE_XILINX_CPM=y +CONFIG_PCIE_CADENCE_PLAT_HOST=y +CONFIG_PCI_SKY1_HOST=y +CONFIG_PCI_J721E_HOST=y +CONFIG_PCI_MESON=y +CONFIG_PCI_IMX6_HOST=y +CONFIG_PCI_LAYERSCAPE=y +CONFIG_PCI_HISI=y +CONFIG_PCIE_KIRIN=y +CONFIG_PCIE_HISI_STB=y +CONFIG_PCIE_ARMADA_8K=y +CONFIG_PCIE_TEGRA194_HOST=y +CONFIG_PCIE_NXP_S32G=y +CONFIG_PCIE_DW_PLAT_HOST=y +CONFIG_PCIE_QCOM=y +CONFIG_PCIE_ROCKCHIP_DW_HOST=y +CONFIG_PCI_KEYSTONE_HOST=y +CONFIG_PCIE_LAYERSCAPE_GEN4=y +CONFIG_PCIE_MOBIVEIL_PLAT=y +CONFIG_PCIE_MICROCHIP_HOST=y +CONFIG_PCI_SW_SWITCHTEC=m +CONFIG_CXL_BUS=m +CONFIG_CXL_FEATURES=y +CONFIG_RAPIDIO=m +CONFIG_RAPIDIO_TSI721=m +CONFIG_RAPIDIO_DMA_ENGINE=y +CONFIG_RAPIDIO_ENUM_BASIC=m +CONFIG_RAPIDIO_CHMAN=m +CONFIG_RAPIDIO_MPORT_CDEV=m +CONFIG_RAPIDIO_CPS_XX=m +CONFIG_RAPIDIO_CPS_GEN2=m +CONFIG_RAPIDIO_RXS_GEN3=m +CONFIG_DEVTMPFS=y +CONFIG_DEVTMPFS_MOUNT=y +CONFIG_DEVTMPFS_SAFE=y +CONFIG_FW_LOADER_COMPRESS=y +CONFIG_FW_LOADER_COMPRESS_ZSTD=y +# CONFIG_DM_KUNIT_TEST is not set +CONFIG_MOXTET=m +CONFIG_HISILICON_LPC=y +CONFIG_IMX_AIPSTZ=m +# CONFIG_QCOM_EBI2 is not set +CONFIG_QCOM_SSC_BLOCK_BUS=y +CONFIG_SUNXI_RSB=m +CONFIG_TEGRA_ACONNECT=m +CONFIG_TEGRA_GMI=m +CONFIG_FSL_MC_UAPI_SUPPORT=y +CONFIG_MHI_BUS_PCI_GENERIC=m +CONFIG_CONNECTOR=y +CONFIG_ARM_SCMI_PROTOCOL=y +CONFIG_ARM_SCMI_TRANSPORT_VIRTIO=y +CONFIG_ARM_SCMI_POWER_CONTROL=y +CONFIG_ARM_SCPI_PROTOCOL=m +CONFIG_FIRMWARE_MEMMAP=y +CONFIG_DMI_SYSFS=y +CONFIG_ISCSI_IBFT=m +CONFIG_FW_CFG_SYSFS=m +CONFIG_SYSFB_SIMPLEFB=y +CONFIG_TURRIS_MOX_RWTM=m +CONFIG_ARM_FFA_TRANSPORT=y +CONFIG_EFI_VARS_PSTORE_DEFAULT_DISABLE=y +CONFIG_EFI_ZBOOT=y +CONFIG_EFI_TEST=m +CONFIG_OVMF_DEBUG_LOG=y +CONFIG_TEE_STMM_EFI=m +CONFIG_IMX_DSP=m +CONFIG_IMX_SCU=y +CONFIG_IMX_SCMI_MISC_DRV=m +CONFIG_QCOM_QSEECOM=y +CONFIG_QCOM_QSEECOM_UEFISECAPP=y +CONFIG_TEGRA_BPMP=y +CONFIG_FWCTL_MLX5=m +CONFIG_FWCTL_PDS=m +CONFIG_GNSS=m +CONFIG_GNSS_MTK_SERIAL=m +CONFIG_GNSS_SIRF_SERIAL=m +CONFIG_GNSS_UBX_SERIAL=m +CONFIG_GNSS_USB=m +CONFIG_MTD=y +CONFIG_MTD_OF_PARTS=m +CONFIG_MTD_BLOCK=m +CONFIG_MTD_CFI=m +CONFIG_MTD_CFI_INTELEXT=m +CONFIG_MTD_CFI_AMDSTD=m +CONFIG_MTD_CFI_STAA=m +CONFIG_MTD_PHYSMAP=m +CONFIG_MTD_PHYSMAP_OF=y +CONFIG_MTD_DATAFLASH=m +CONFIG_MTD_DATAFLASH_WRITE_VERIFY=y +CONFIG_MTD_DATAFLASH_OTP=y +CONFIG_MTD_MCHP48L640=m +CONFIG_MTD_SST25L=m +CONFIG_MTD_PHRAM=m +CONFIG_MTD_MTDRAM=m +CONFIG_MTD_BLOCK2MTD=m +CONFIG_MTD_RAW_NAND=m +CONFIG_MTD_NAND_MARVELL=m +CONFIG_MTD_NAND_TEGRA=m +CONFIG_MTD_NAND_CADENCE=m +CONFIG_MTD_NAND_NANDSIM=m +CONFIG_MTD_SPI_NAND=m +CONFIG_MTD_NAND_ECC_MXIC=y +CONFIG_MTD_SPI_NOR=m +CONFIG_SPI_HISI_SFC=m +CONFIG_MTD_UBI=m +CONFIG_MTD_UBI_NVMEM=m +# CONFIG_PNP_DEBUG_MESSAGES is not set +CONFIG_BLK_DEV_NULL_BLK=m +CONFIG_BLK_DEV_RUST_NULL=m +CONFIG_ZRAM=m +CONFIG_ZRAM_BACKEND_LZ4=y +CONFIG_ZRAM_BACKEND_LZ4HC=y +CONFIG_ZRAM_BACKEND_ZSTD=y +CONFIG_ZRAM_BACKEND_DEFLATE=y +CONFIG_ZRAM_BACKEND_842=y +CONFIG_ZRAM_BACKEND_LZO=y +CONFIG_ZRAM_WRITEBACK=y +CONFIG_ZRAM_MULTI_COMP=y +CONFIG_BLK_DEV_LOOP=m +CONFIG_BLK_DEV_LOOP_MIN_COUNT=0 +CONFIG_BLK_DEV_DRBD=m +CONFIG_BLK_DEV_NBD=m +CONFIG_BLK_DEV_RAM=m +CONFIG_BLK_DEV_RAM_SIZE=16384 +CONFIG_ATA_OVER_ETH=m +CONFIG_VIRTIO_BLK=y +CONFIG_BLK_DEV_RBD=m +CONFIG_BLK_DEV_UBLK=m +CONFIG_BLK_DEV_RNBD_CLIENT=m +CONFIG_BLK_DEV_RNBD_SERVER=m +CONFIG_BLK_DEV_ZONED_LOOP=m +CONFIG_BLK_DEV_NVME=m +CONFIG_NVME_MULTIPATH=y +CONFIG_NVME_HWMON=y +CONFIG_NVME_RDMA=m +CONFIG_NVME_FC=m +CONFIG_NVME_TCP=m +CONFIG_NVME_TCP_TLS=y +CONFIG_NVME_HOST_AUTH=y +CONFIG_NVME_APPLE=m +CONFIG_NVME_TARGET=m +CONFIG_NVME_TARGET_PASSTHRU=y +CONFIG_NVME_TARGET_LOOP=m +CONFIG_NVME_TARGET_RDMA=m +CONFIG_NVME_TARGET_FC=m +CONFIG_NVME_TARGET_FCLOOP=m +CONFIG_NVME_TARGET_TCP=m +CONFIG_NVME_TARGET_TCP_TLS=y +CONFIG_NVME_TARGET_AUTH=y +CONFIG_RPMB=m +CONFIG_TI_FPC202=m +CONFIG_ENCLOSURE_SERVICES=m +CONFIG_SMPRO_ERRMON=m +CONFIG_SMPRO_MISC=m +CONFIG_HI6421V600_IRQ=m +CONFIG_QCOM_COINCELL=m +CONFIG_QCOM_FASTRPC=m +CONFIG_APDS9802ALS=m +CONFIG_ISL29003=m +CONFIG_ISL29020=m +CONFIG_SENSORS_TSL2550=m +CONFIG_SENSORS_BH1770=m +CONFIG_DW_XDATA_PCIE=m +CONFIG_XILINX_SDFEC=m +CONFIG_OPEN_DICE=m +CONFIG_NTSYNC=m +CONFIG_VCPU_STALL_DETECTOR=m +CONFIG_NSM=m +CONFIG_EEPROM_MAX6875=m +CONFIG_EEPROM_IDT_89HPESX=m +CONFIG_SENSORS_LIS3_I2C=m +CONFIG_VMWARE_VMCI=m +CONFIG_BCM_VK=m +CONFIG_BCM_VK_TTY=y +CONFIG_MISC_ALCOR_PCI=m +CONFIG_MISC_RTSX_PCI=m +CONFIG_MISC_RTSX_USB=m +CONFIG_UACCE=m +CONFIG_PVPANIC=y +CONFIG_PVPANIC_PCI=m +CONFIG_GP_PCI1XXXX=m +CONFIG_MISC_RP1=m +CONFIG_BLK_DEV_SD=y +CONFIG_CHR_DEV_ST=m +CONFIG_BLK_DEV_SR=y +CONFIG_CHR_DEV_SG=y +CONFIG_CHR_DEV_SCH=m +CONFIG_SCSI_ENCLOSURE=m +CONFIG_SCSI_CONSTANTS=y +CONFIG_SCSI_LOGGING=y +CONFIG_SCSI_SCAN_ASYNC=y +CONFIG_SCSI_FC_ATTRS=m +CONFIG_SCSI_SAS_ATA=y +CONFIG_ISCSI_TCP=m +CONFIG_SCSI_CXGB3_ISCSI=m +CONFIG_SCSI_CXGB4_ISCSI=m +CONFIG_SCSI_BNX2_ISCSI=m +CONFIG_SCSI_BNX2X_FCOE=m +CONFIG_BE2ISCSI=m +CONFIG_SCSI_HPSA=m +CONFIG_SCSI_MVSAS=m +# CONFIG_SCSI_MVSAS_DEBUG is not set +CONFIG_SCSI_MVSAS_TASKLET=y +CONFIG_SCSI_MVUMI=m +CONFIG_SCSI_ARCMSR=m +CONFIG_SCSI_ESAS2R=m +CONFIG_MEGARAID_NEWGEN=y +CONFIG_MEGARAID_MM=m +CONFIG_MEGARAID_MAILBOX=m +CONFIG_MEGARAID_LEGACY=m +CONFIG_MEGARAID_SAS=m +CONFIG_SCSI_MPT3SAS=m +CONFIG_SCSI_MPI3MR=m +CONFIG_SCSI_SMARTPQI=m +CONFIG_SCSI_HPTIOP=m +CONFIG_SCSI_MYRB=m +CONFIG_SCSI_MYRS=m +CONFIG_LIBFC=m +CONFIG_LIBFCOE=m +CONFIG_FCOE=m +CONFIG_SCSI_SNIC=m +CONFIG_SCSI_DMX3191D=m +CONFIG_SCSI_FDOMAIN_PCI=m +CONFIG_SCSI_INITIO=m +CONFIG_SCSI_INIA100=m +CONFIG_SCSI_STEX=m +CONFIG_SCSI_SYM53C8XX_2=m +CONFIG_SCSI_IPR=m +CONFIG_SCSI_QLOGIC_1280=m +CONFIG_SCSI_QLA_FC=m +CONFIG_TCM_QLA2XXX=m +CONFIG_SCSI_QLA_ISCSI=m +CONFIG_QEDI=m +CONFIG_QEDF=m +CONFIG_SCSI_LPFC=m +CONFIG_SCSI_EFCT=m +CONFIG_SCSI_DC395x=m +CONFIG_SCSI_AM53C974=m +CONFIG_SCSI_WD719X=m +CONFIG_SCSI_DEBUG=m +CONFIG_SCSI_PMCRAID=m +CONFIG_SCSI_VIRTIO=m +CONFIG_SCSI_CHELSIO_FCOE=m +CONFIG_SCSI_DH=y +CONFIG_SCSI_DH_RDAC=m +CONFIG_SCSI_DH_HP_SW=m +CONFIG_SCSI_DH_EMC=m +CONFIG_SCSI_DH_ALUA=m +CONFIG_ATA=y +CONFIG_SATA_AHCI=y +CONFIG_SATA_AHCI_PLATFORM=m +CONFIG_AHCI_DWC=m +CONFIG_AHCI_IMX=m +CONFIG_AHCI_CEVA=m +CONFIG_AHCI_MVEBU=m +CONFIG_AHCI_SUNXI=m +CONFIG_AHCI_TEGRA=m +CONFIG_AHCI_XGENE=m +CONFIG_AHCI_QORIQ=m +CONFIG_SATA_AHCI_SEATTLE=m +CONFIG_SATA_ACARD_AHCI=m +CONFIG_SATA_SIL24=m +CONFIG_PDC_ADMA=m +CONFIG_ATA_PIIX=y +CONFIG_SATA_MV=m +CONFIG_PATA_MARVELL=m +CONFIG_PATA_ACPI=m +CONFIG_ATA_GENERIC=m +CONFIG_MD=y +CONFIG_BLK_DEV_MD=y +CONFIG_MD_LINEAR=m +CONFIG_BCACHE=m +CONFIG_BLK_DEV_DM=y +CONFIG_DM_DEBUG=y +CONFIG_DM_UNSTRIPED=m +CONFIG_DM_CRYPT=m +CONFIG_DM_SNAPSHOT=y +CONFIG_DM_THIN_PROVISIONING=m +CONFIG_DM_CACHE=m +CONFIG_DM_WRITECACHE=m +CONFIG_DM_EBS=m +CONFIG_DM_ERA=m +CONFIG_DM_CLONE=m +CONFIG_DM_MIRROR=y +CONFIG_DM_LOG_USERSPACE=m +CONFIG_DM_RAID=m +CONFIG_DM_ZERO=y +CONFIG_DM_MULTIPATH=m +CONFIG_DM_MULTIPATH_QL=m +CONFIG_DM_MULTIPATH_ST=m +CONFIG_DM_MULTIPATH_HST=m +CONFIG_DM_MULTIPATH_IOA=m +CONFIG_DM_DELAY=m +CONFIG_DM_DUST=m +CONFIG_DM_INIT=y +CONFIG_DM_UEVENT=y +CONFIG_DM_FLAKEY=m +CONFIG_DM_VERITY=m +CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y +CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG_SECONDARY_KEYRING=y +CONFIG_DM_VERITY_FEC=y +CONFIG_DM_SWITCH=m +CONFIG_DM_LOG_WRITES=m +CONFIG_DM_INTEGRITY=m +CONFIG_DM_ZONED=m +CONFIG_DM_VDO=m +CONFIG_TARGET_CORE=m +CONFIG_TCM_IBLOCK=m +CONFIG_TCM_FILEIO=m +CONFIG_TCM_PSCSI=m +CONFIG_TCM_USER2=m +CONFIG_LOOPBACK_TARGET=m +CONFIG_TCM_FC=m +CONFIG_ISCSI_TARGET=m +CONFIG_ISCSI_TARGET_CXGB4=m +CONFIG_REMOTE_TARGET=m +CONFIG_BONDING=m +CONFIG_DUMMY=m +CONFIG_WIREGUARD=m +CONFIG_OVPN=m +CONFIG_EQUALIZER=m +CONFIG_NET_FC=y +CONFIG_IFB=m +CONFIG_NET_TEAM=m +CONFIG_NET_TEAM_MODE_BROADCAST=m +CONFIG_NET_TEAM_MODE_ROUNDROBIN=m +CONFIG_NET_TEAM_MODE_RANDOM=m +CONFIG_NET_TEAM_MODE_ACTIVEBACKUP=m +CONFIG_NET_TEAM_MODE_LOADBALANCE=m +CONFIG_MACVLAN=m +CONFIG_MACVTAP=m +CONFIG_IPVLAN=m +CONFIG_IPVTAP=m +CONFIG_VXLAN=m +CONFIG_GENEVE=m +CONFIG_BAREUDP=m +CONFIG_GTP=m +CONFIG_PFCP=m +CONFIG_AMT=m +CONFIG_MACSEC=m +CONFIG_NETCONSOLE=m +CONFIG_NETCONSOLE_DYNAMIC=y +CONFIG_RIONET=m +CONFIG_TUN=m +CONFIG_VETH=m +CONFIG_VIRTIO_NET=m +CONFIG_NLMON=m +CONFIG_NETKIT=y +CONFIG_NET_VRF=m +CONFIG_VSOCKMON=m +CONFIG_MHI_NET=m +# CONFIG_ATM_DRIVERS is not set +CONFIG_B53_SPI_DRIVER=m +CONFIG_B53_MDIO_DRIVER=m +CONFIG_B53_MMAP_DRIVER=m +CONFIG_B53_SRAB_DRIVER=m +CONFIG_B53_SERDES=m +CONFIG_NET_DSA_BCM_SF2=m +CONFIG_NET_DSA_LOOP=m +CONFIG_NET_DSA_HIRSCHMANN_HELLCREEK=m +CONFIG_NET_DSA_MT7530=m +CONFIG_NET_DSA_MV88E6XXX=m +CONFIG_NET_DSA_MV88E6XXX_PTP=y +CONFIG_NET_DSA_MXL862=m +CONFIG_NET_DSA_QCA8K=m +CONFIG_NET_DSA_QCA8K_LEDS_SUPPORT=y +CONFIG_NET_DSA_XRS700X_I2C=m +CONFIG_NET_DSA_XRS700X_MDIO=m +CONFIG_NET_DSA_REALTEK=m +CONFIG_NET_DSA_SMSC_LAN9303_I2C=m +CONFIG_NET_DSA_SMSC_LAN9303_MDIO=m +# CONFIG_NET_VENDOR_3COM is not set +# CONFIG_NET_VENDOR_ADAPTEC is not set +CONFIG_ET131X=m +# CONFIG_NET_VENDOR_ALACRITECH is not set +CONFIG_ALTERA_TSE=m +CONFIG_ENA_ETHERNET=m +CONFIG_AMD8111_ETH=m +CONFIG_PCNET32=m +CONFIG_AMD_XGBE=m +CONFIG_AMD_XGBE_DCB=y +CONFIG_PDS_CORE=m +CONFIG_NET_XGENE=m +CONFIG_NET_XGENE_V2=m +CONFIG_AQTION=m +CONFIG_EMAC_ROCKCHIP=m +CONFIG_SPI_AX88796C=m +CONFIG_SPI_AX88796C_COMPRESSION=y +CONFIG_ATL2=m +CONFIG_ATL1=m +CONFIG_ATL1E=m +CONFIG_ATL1C=m +CONFIG_ALX=m +CONFIG_B44=m +CONFIG_BCMGENET=m +CONFIG_TIGON3=m +CONFIG_BNX2X=m +CONFIG_BNXT=m +CONFIG_BNXT_DCB=y +CONFIG_BNGE=m +CONFIG_MACB=m +CONFIG_MACB_PCI=m +CONFIG_THUNDER_NIC_PF=m +CONFIG_THUNDER_NIC_VF=m +CONFIG_CHELSIO_T1=m +CONFIG_CHELSIO_T1_1G=y +CONFIG_CHELSIO_T4_DCB=y +CONFIG_CHELSIO_T4VF=m +CONFIG_CHELSIO_IPSEC_INLINE=m +CONFIG_CHELSIO_TLS_DEVICE=m +# CONFIG_NET_VENDOR_CISCO is not set +# CONFIG_NET_VENDOR_CORTINA is not set +CONFIG_DM9051=m +# CONFIG_NET_VENDOR_DEC is not set +CONFIG_DL2K=m +CONFIG_SUNDANCE=m +# CONFIG_BE2NET_HWMON is not set +CONFIG_TSNEP=m +# CONFIG_NET_VENDOR_EZCHIP is not set +CONFIG_FEC=m +CONFIG_FSL_FMAN=m +CONFIG_GIANFAR=m +CONFIG_FSL_DPAA_ETH=m +CONFIG_FSL_DPAA2_ETH=m +CONFIG_FSL_DPAA2_ETH_DCB=y +CONFIG_FSL_DPAA2_SWITCH=m +CONFIG_FSL_ENETC=m +CONFIG_NXP_ENETC4=m +CONFIG_FSL_ENETC_VF=m +CONFIG_FSL_ENETC_QOS=y +CONFIG_FUN_ETH=m +CONFIG_GVE=m +CONFIG_HNS_DSAF=m +CONFIG_HNS_ENET=m +CONFIG_HNS3=m +CONFIG_HNS3_DCB=y +CONFIG_HNS3_HCLGEVF=m +CONFIG_HIBMCGE=m +# CONFIG_NET_VENDOR_HUAWEI is not set +# CONFIG_NET_VENDOR_I825XX is not set +CONFIG_E100=m +CONFIG_E1000=m +CONFIG_E1000E=m +CONFIG_IGB=m +CONFIG_IGBVF=m +CONFIG_IXGBE=m +CONFIG_IXGBE_DCB=y +CONFIG_IXGBEVF=m +CONFIG_I40E=m +CONFIG_I40EVF=m +CONFIG_ICE=m +CONFIG_FM10K=m +CONFIG_IGC=m +CONFIG_IDPF=m +CONFIG_IDPF_SINGLEQ=y +CONFIG_JME=m +CONFIG_ADIN1110=m +CONFIG_LITEX_LITEETH=m +CONFIG_MVNETA=m +CONFIG_MVPP2=m +CONFIG_MVPP2_PTP=y +CONFIG_SKGE=m +CONFIG_SKGE_GENESIS=y +CONFIG_SKY2=m +CONFIG_OCTEONTX2_AF=m +CONFIG_OCTEONTX2_PF=m +CONFIG_OCTEONTX2_VF=m +CONFIG_OCTEON_EP=m +CONFIG_OCTEON_EP_VF=m +CONFIG_PRESTERA=m +CONFIG_MLX4_EN=m +CONFIG_MLX5_CORE=m +CONFIG_MLX5_FPGA=y +CONFIG_MLX5_CORE_EN=y +CONFIG_MLX5_CORE_IPOIB=y +CONFIG_MLX5_MACSEC=y +CONFIG_MLX5_EN_IPSEC=y +CONFIG_MLX5_EN_TLS=y +CONFIG_MLX5_SF=y +CONFIG_MLX5_DPLL=m +CONFIG_MLXSW_CORE=m +CONFIG_MLXBF_GIGE=m +CONFIG_KSZ884X_PCI=m +CONFIG_LAN743X=m +CONFIG_LAN966X_SWITCH=m +# CONFIG_NET_VENDOR_MICROSEMI is not set +CONFIG_MICROSOFT_MANA=m +# CONFIG_NET_VENDOR_MUCSE is not set +CONFIG_MYRI10GE=m +CONFIG_FEALNX=m +# CONFIG_NET_VENDOR_NI is not set +CONFIG_NATSEMI=m +CONFIG_NS83820=m +CONFIG_NFP=m +# CONFIG_NFP_APP_ABM_NIC is not set +CONFIG_NE2K_PCI=m +CONFIG_FORCEDETH=m +CONFIG_ETHOC=m +CONFIG_IONIC=m +CONFIG_QLA3XXX=m +CONFIG_QLCNIC=m +CONFIG_NETXEN_NIC=m +CONFIG_QED=m +CONFIG_QEDE=m +# CONFIG_NET_VENDOR_BROCADE is not set +# CONFIG_NET_VENDOR_QUALCOMM is not set +CONFIG_R6040=m +CONFIG_8139CP=m +CONFIG_8139TOO=m +# CONFIG_8139TOO_PIO is not set +CONFIG_8139TOO_8129=y +CONFIG_R8169=m +CONFIG_R8169_LEDS=y +CONFIG_RAVB=m +CONFIG_RTSN=m +CONFIG_ROCKER=m +# CONFIG_NET_VENDOR_SAMSUNG is not set +# CONFIG_NET_VENDOR_SEEQ is not set +CONFIG_SC92031=m +CONFIG_SIS900=m +CONFIG_SIS190=m +# CONFIG_NET_VENDOR_SOLARFLARE is not set +CONFIG_SMC91X=m +CONFIG_EPIC100=m +CONFIG_SMSC911X=m +CONFIG_SMSC9420=m +CONFIG_SNI_NETSEC=m +CONFIG_STMMAC_ETH=m +CONFIG_DWMAC_DWC_QOS_ETH=m +CONFIG_DWMAC_TEGRA=m +CONFIG_DWMAC_MOTORCOMM=m +# CONFIG_NET_VENDOR_SUN is not set +# CONFIG_NET_VENDOR_SYNOPSYS is not set +CONFIG_TEHUTI=m +CONFIG_TEHUTI_TN40=m +CONFIG_TI_K3_AM65_CPSW_NUSS=m +CONFIG_TI_K3_AM65_CPSW_SWITCHDEV=y +CONFIG_TI_K3_AM65_CPTS=m +CONFIG_TI_AM65_CPSW_QOS=y +CONFIG_TI_ICSSG_PRUETH=m +CONFIG_TI_ICSSG_PRUETH_SR1=m +CONFIG_TI_PRUETH=m +CONFIG_MSE102X=m +CONFIG_VIA_RHINE=m +CONFIG_VIA_RHINE_MMIO=y +CONFIG_VIA_VELOCITY=m +CONFIG_NGBE=m +CONFIG_TXGBE=m +CONFIG_TXGBEVF=m +CONFIG_NGBEVF=m +# CONFIG_NET_VENDOR_WIZNET is not set +CONFIG_XILINX_EMACLITE=m +CONFIG_XILINX_LL_TEMAC=m +CONFIG_QCOM_IPA=m +CONFIG_PHYLIB=y +CONFIG_LED_TRIGGER_PHY=y +CONFIG_RUST_PHYLIB_ABSTRACTIONS=y +CONFIG_AS21XXX_PHY=m +CONFIG_AIR_EN8811H_PHY=m +CONFIG_AMD_PHY=m +CONFIG_MESON_GXL_PHY=m +CONFIG_ADIN_PHY=m +CONFIG_AQUANTIA_PHY=m +CONFIG_AX88796B_RUST_PHY=y +CONFIG_BCM54140_PHY=m +CONFIG_BCM87XX_PHY=m +CONFIG_CICADA_PHY=m +CONFIG_CORTINA_PHY=m +CONFIG_DAVICOM_PHY=m +CONFIG_ICPLUS_PHY=m +CONFIG_LXT_PHY=m +CONFIG_INTEL_XWAY_PHY=m +CONFIG_LSI_ET1011C_PHY=m +CONFIG_MARVELL_PHY=m +CONFIG_MARVELL_88Q2XXX_PHY=m +CONFIG_MARVELL_88X2222_PHY=m +CONFIG_MAXLINEAR_GPHY=m +CONFIG_MAXLINEAR_86110_PHY=m +CONFIG_MICREL_PHY=m +CONFIG_MICROCHIP_T1S_PHY=m +CONFIG_MICROSEMI_PHY=m +CONFIG_NATIONAL_PHY=m +CONFIG_NXP_CBTX_PHY=m +CONFIG_NXP_C45_TJA11XX_PHY=m +CONFIG_NCN26000_PHY=m +CONFIG_AT803X_PHY=m +CONFIG_QCA83XX_PHY=m +CONFIG_QCA808X_PHY=m +CONFIG_QCA807X_PHY=m +CONFIG_QSEMI_PHY=m +CONFIG_REALTEK_PHY_HWMON=y +CONFIG_ROCKCHIP_PHY=m +CONFIG_STE10XP=m +CONFIG_TERANETICS_PHY=m +CONFIG_DP83822_PHY=m +CONFIG_DP83848_PHY=m +CONFIG_DP83867_PHY=m +CONFIG_DP83869_PHY=m +CONFIG_DP83TD510_PHY=m +CONFIG_DP83TG720_PHY=m +CONFIG_VITESSE_PHY=m +CONFIG_XILINX_GMII2RGMII=m +CONFIG_CAN_VCAN=m +CONFIG_CAN_VXCAN=m +CONFIG_CAN_CAN327=m +CONFIG_CAN_FLEXCAN=m +CONFIG_CAN_SLCAN=m +CONFIG_CAN_XILINXCAN=m +CONFIG_CAN_CTUCANFD_PCI=m +CONFIG_CAN_CTUCANFD_PLATFORM=m +CONFIG_CAN_IFI_CANFD=m +CONFIG_CAN_M_CAN=m +CONFIG_CAN_M_CAN_PCI=m +CONFIG_CAN_M_CAN_PLATFORM=m +CONFIG_CAN_PEAK_PCIEFD=m +CONFIG_CAN_RCAR_CANFD=m +CONFIG_CAN_ROCKCHIP_CANFD=m +CONFIG_CAN_HI311X=m +CONFIG_CAN_MCP251X=m +CONFIG_CAN_MCP251XFD=m +CONFIG_CAN_8DEV_USB=m +CONFIG_CAN_EMS_USB=m +CONFIG_CAN_ESD_USB=m +CONFIG_CAN_F81604=m +CONFIG_CAN_GS_USB=m +CONFIG_CAN_KVASER_USB=m +CONFIG_CAN_MCBA_USB=m +CONFIG_CAN_PEAK_USB=m +CONFIG_MCTP_SERIAL=m +CONFIG_MCTP_TRANSPORT_I3C=m +CONFIG_MCTP_TRANSPORT_USB=m +CONFIG_MDIO_GPIO=m +CONFIG_MDIO_HISI_FEMAC=m +CONFIG_MDIO_MVUSB=m +CONFIG_MDIO_OCTEON=m +CONFIG_MDIO_IPQ8064=m +CONFIG_MDIO_BUS_MUX_GPIO=m +CONFIG_MDIO_BUS_MUX_MULTIPLEXER=m +CONFIG_MDIO_BUS_MUX_MMIOREG=m +CONFIG_PPP=m +CONFIG_PPP_BSDCOMP=m +CONFIG_PPP_DEFLATE=m +CONFIG_PPP_FILTER=y +CONFIG_PPP_MPPE=m +CONFIG_PPP_MULTILINK=y +CONFIG_PPPOATM=m +CONFIG_PPPOE=m +CONFIG_PPTP=m +CONFIG_PPPOL2TP=m +CONFIG_PPP_ASYNC=m +CONFIG_PPP_SYNC_TTY=m +CONFIG_SLIP=m +CONFIG_SLIP_COMPRESSED=y +CONFIG_SLIP_SMART=y +CONFIG_USB_CATC=m +CONFIG_USB_KAWETH=m +CONFIG_USB_PEGASUS=m +CONFIG_USB_RTL8150=m +CONFIG_USB_RTL8152=m +CONFIG_USB_LAN78XX=m +CONFIG_USB_USBNET=m +CONFIG_USB_NET_CDC_EEM=m +CONFIG_USB_NET_HUAWEI_CDC_NCM=m +CONFIG_USB_NET_CDC_MBIM=m +CONFIG_USB_NET_DM9601=m +CONFIG_USB_NET_SR9700=m +CONFIG_USB_NET_SMSC75XX=m +CONFIG_USB_NET_SMSC95XX=m +CONFIG_USB_NET_GL620A=m +CONFIG_USB_NET_PLUSB=m +CONFIG_USB_NET_MCS7830=m +CONFIG_USB_NET_RNDIS_HOST=m +CONFIG_USB_ALI_M5632=y +CONFIG_USB_AN2720=y +CONFIG_USB_EPSON2888=y +CONFIG_USB_KC2190=y +CONFIG_USB_NET_CX82310_ETH=m +CONFIG_USB_NET_KALMIA=m +CONFIG_USB_NET_QMI_WWAN=m +CONFIG_USB_HSO=m +CONFIG_USB_NET_INT51X1=m +CONFIG_USB_IPHETH=m +CONFIG_USB_SIERRA_NET=m +CONFIG_USB_VL600=m +CONFIG_USB_NET_CH9200=m +CONFIG_USB_NET_AQC111=m +# CONFIG_WLAN_VENDOR_ADMTEK is not set +CONFIG_APPLE_CENTAURI=m +CONFIG_APPLE_CENTAURI_T6050=m +CONFIG_ATH5K=m +CONFIG_ATH5K_DEBUG=y +CONFIG_ATH9K=m +CONFIG_ATH9K_AHB=y +CONFIG_ATH9K_DEBUGFS=y +CONFIG_ATH9K_PCI_NO_EEPROM=m +CONFIG_ATH9K_HTC=m +CONFIG_CARL9170=m +CONFIG_ATH6KL=m +CONFIG_ATH6KL_SDIO=m +CONFIG_ATH6KL_USB=m +CONFIG_ATH6KL_DEBUG=y +CONFIG_AR5523=m +CONFIG_WIL6210=m +CONFIG_ATH10K=m +CONFIG_ATH10K_PCI=m +CONFIG_ATH10K_AHB=y +CONFIG_ATH10K_SDIO=m +CONFIG_ATH10K_USB=m +CONFIG_ATH10K_SNOC=m +CONFIG_ATH10K_DEBUGFS=y +CONFIG_WCN36XX=m +CONFIG_ATH11K=m +CONFIG_ATH11K_AHB=m +CONFIG_ATH11K_PCI=m +CONFIG_ATH12K=m +CONFIG_ATH12K_AHB=y +# CONFIG_WLAN_VENDOR_ATMEL is not set +CONFIG_B43=m +CONFIG_B43_SDIO=y +CONFIG_B43LEGACY=m +# CONFIG_B43LEGACY_DEBUG is not set +CONFIG_BRCMSMAC=m +CONFIG_BRCMFMAC=m +CONFIG_BRCMFMAC_USB=y +CONFIG_BRCMFMAC_PCIE=y +CONFIG_IWL4965=m +CONFIG_IWL3945=m +CONFIG_IWLEGACY_DEBUG=y +CONFIG_IWLEGACY_DEBUGFS=y +CONFIG_IWLWIFI=m +CONFIG_IWLDVM=m +CONFIG_IWLMVM=m +CONFIG_IWLMLD=m +CONFIG_IWLWIFI_DEBUG=y +CONFIG_IWLWIFI_DEBUGFS=y +# CONFIG_IWLWIFI_DEVICE_TRACING is not set +# CONFIG_WLAN_VENDOR_INTERSIL is not set +CONFIG_LIBERTAS_THINFIRM=m +CONFIG_LIBERTAS_THINFIRM_USB=m +CONFIG_MWIFIEX=m +CONFIG_MWIFIEX_SDIO=m +CONFIG_MWIFIEX_PCIE=m +CONFIG_MWIFIEX_USB=m +CONFIG_MWL8K=m +CONFIG_MT7601U=m +CONFIG_MT76x0U=m +CONFIG_MT76x0E=m +CONFIG_MT76x2E=m +CONFIG_MT76x2U=m +CONFIG_MT7603E=m +CONFIG_MT7615E=m +CONFIG_MT7663U=m +CONFIG_MT7663S=m +CONFIG_MT7915E=m +CONFIG_MT7921E=m +CONFIG_MT7921S=m +CONFIG_MT7921U=m +CONFIG_MT7996E=m +CONFIG_MT7925E=m +CONFIG_MT7925U=m +CONFIG_MT7932_FULLMAC=m +# CONFIG_WLAN_VENDOR_PURELIFI is not set +CONFIG_RT2X00=m +CONFIG_RT2400PCI=m +CONFIG_RT2500PCI=m +CONFIG_RT61PCI=m +CONFIG_RT2800PCI=m +CONFIG_RT2500USB=m +CONFIG_RT73USB=m +CONFIG_RT2800USB=m +CONFIG_RT2800USB_RT3573=y +CONFIG_RT2800USB_RT53XX=y +CONFIG_RT2800USB_RT55XX=y +CONFIG_RT2800USB_UNKNOWN=y +CONFIG_RT2X00_LIB_DEBUGFS=y +CONFIG_RTL8180=m +CONFIG_RTL8187=m +CONFIG_RTL8192CE=m +CONFIG_RTL8192SE=m +CONFIG_RTL8192DE=m +CONFIG_RTL8723AE=m +CONFIG_RTL8723BE=m +CONFIG_RTL8188EE=m +CONFIG_RTL8192EE=m +CONFIG_RTL8821AE=m +CONFIG_RTL8192DU=m +# CONFIG_RTLWIFI_DEBUG is not set +CONFIG_RTL8XXXU=m +CONFIG_RTL8XXXU_UNTESTED=y +CONFIG_RTW88=m +CONFIG_RTW88_8822BE=m +CONFIG_RTW88_8822BS=m +CONFIG_RTW88_8822BU=m +CONFIG_RTW88_8822CE=m +CONFIG_RTW88_8822CS=m +CONFIG_RTW88_8822CU=m +CONFIG_RTW88_8723DE=m +CONFIG_RTW88_8723DS=m +CONFIG_RTW88_8723CS=m +CONFIG_RTW88_8723DU=m +CONFIG_RTW88_8821CE=m +CONFIG_RTW88_8821CS=m +CONFIG_RTW88_8821CU=m +CONFIG_RTW88_8821AU=m +CONFIG_RTW88_8812AU=m +CONFIG_RTW88_8814AE=m +CONFIG_RTW88_8814AU=m +CONFIG_RTW89=m +CONFIG_RTW89_8851BE=m +CONFIG_RTW89_8851BU=m +CONFIG_RTW89_8852AE=m +CONFIG_RTW89_8852AU=m +CONFIG_RTW89_8852BE=m +CONFIG_RTW89_8852BU=m +CONFIG_RTW89_8852BTE=m +CONFIG_RTW89_8852CE=m +CONFIG_RTW89_8852CU=m +CONFIG_RTW89_8922AE=m +CONFIG_RSI_91X=m +# CONFIG_WLAN_VENDOR_SILABS is not set +CONFIG_CW1200=m +CONFIG_CW1200_WLAN_SDIO=m +CONFIG_CW1200_WLAN_SPI=m +CONFIG_WL1251=m +CONFIG_WL1251_SPI=m +CONFIG_WL1251_SDIO=m +CONFIG_WL12XX=m +CONFIG_WL18XX=m +CONFIG_WLCORE_SPI=m +CONFIG_WLCORE_SDIO=m +CONFIG_ZD1211RW=m +CONFIG_QTNFMAC_PCIE=m +CONFIG_MAC80211_HWSIM=m +CONFIG_VIRT_WIFI=m +CONFIG_IEEE802154_FAKELB=m +CONFIG_IEEE802154_AT86RF230=m +CONFIG_IEEE802154_MRF24J40=m +CONFIG_IEEE802154_CC2520=m +CONFIG_IEEE802154_ATUSB=m +CONFIG_IEEE802154_ADF7242=m +CONFIG_IEEE802154_CA8210=m +CONFIG_IEEE802154_MCR20A=m +CONFIG_WWAN=m +CONFIG_WWAN_HWSIM=m +CONFIG_MHI_WWAN_CTRL=m +CONFIG_MHI_WWAN_MBIM=m +CONFIG_QCOM_BAM_DMUX=m +CONFIG_RPMSG_WWAN_CTRL=m +CONFIG_IOSM=m +CONFIG_MTK_T7XX=m +CONFIG_VMXNET3=m +CONFIG_USB4_NET=m +CONFIG_HYPERV_NET=m +CONFIG_NETDEVSIM=m +CONFIG_INPUT_MOUSEDEV=y +CONFIG_INPUT_JOYDEV=m +CONFIG_INPUT_EVDEV=y +CONFIG_KEYBOARD_ADC=m +CONFIG_KEYBOARD_ADP5585=m +CONFIG_KEYBOARD_QT1050=m +CONFIG_KEYBOARD_QT1070=m +CONFIG_KEYBOARD_GPIO=m +CONFIG_KEYBOARD_GPIO_POLLED=m +CONFIG_KEYBOARD_SNVS_PWRKEY=m +CONFIG_KEYBOARD_IMX_SC_KEY=m +CONFIG_KEYBOARD_TEGRA=m +CONFIG_KEYBOARD_PINEPHONE=m +CONFIG_KEYBOARD_STMPE=m +CONFIG_KEYBOARD_TM2_TOUCHKEY=m +CONFIG_KEYBOARD_CROS_EC=m +CONFIG_KEYBOARD_CYPRESS_SF=m +# CONFIG_MOUSE_PS2 is not set +CONFIG_MOUSE_APPLETOUCH=m +CONFIG_MOUSE_BCM5974=m +CONFIG_MOUSE_CYAPA=m +CONFIG_MOUSE_ELAN_I2C=m +CONFIG_MOUSE_ELAN_I2C_SMBUS=y +CONFIG_MOUSE_VSXXXAA=m +CONFIG_MOUSE_SYNAPTICS_I2C=m +CONFIG_MOUSE_SYNAPTICS_USB=m +CONFIG_INPUT_JOYSTICK=y +CONFIG_JOYSTICK_ANALOG=m +CONFIG_JOYSTICK_A3D=m +CONFIG_JOYSTICK_ADC=m +CONFIG_JOYSTICK_ADI=m +CONFIG_JOYSTICK_COBRA=m +CONFIG_JOYSTICK_GF2K=m +CONFIG_JOYSTICK_GRIP=m +CONFIG_JOYSTICK_GRIP_MP=m +CONFIG_JOYSTICK_GUILLEMOT=m +CONFIG_JOYSTICK_INTERACT=m +CONFIG_JOYSTICK_SIDEWINDER=m +CONFIG_JOYSTICK_TMDC=m +CONFIG_JOYSTICK_IFORCE=m +CONFIG_JOYSTICK_IFORCE_USB=m +CONFIG_JOYSTICK_IFORCE_232=m +CONFIG_JOYSTICK_JOYDUMP=m +CONFIG_JOYSTICK_XPAD=m +CONFIG_JOYSTICK_XPAD_FF=y +CONFIG_JOYSTICK_XPAD_LEDS=y +CONFIG_JOYSTICK_PSXPAD_SPI=m +CONFIG_JOYSTICK_PSXPAD_SPI_FF=y +CONFIG_JOYSTICK_PXRC=m +CONFIG_JOYSTICK_QWIIC=m +CONFIG_JOYSTICK_SENSEHAT=m +CONFIG_INPUT_TABLET=y +CONFIG_TABLET_USB_ACECAD=m +CONFIG_TABLET_USB_AIPTEK=m +CONFIG_TABLET_USB_HANWANG=m +CONFIG_TABLET_USB_KBTAB=m +CONFIG_TABLET_USB_PEGASUS=m +CONFIG_TABLET_SERIAL_WACOM4=m +CONFIG_INPUT_TOUCHSCREEN=y +CONFIG_TOUCHSCREEN_ADS7846=m +CONFIG_TOUCHSCREEN_ADC=m +CONFIG_TOUCHSCREEN_APPLE_Z2=m +CONFIG_TOUCHSCREEN_ATMEL_MXT=m +CONFIG_TOUCHSCREEN_AUO_PIXCIR=m +CONFIG_TOUCHSCREEN_CY8CTMA140=m +CONFIG_TOUCHSCREEN_CYTTSP5=m +CONFIG_TOUCHSCREEN_EETI=m +CONFIG_TOUCHSCREEN_EGALAX=m +CONFIG_TOUCHSCREEN_EXC3000=m +CONFIG_TOUCHSCREEN_GOODIX=m +CONFIG_TOUCHSCREEN_HIMAX_HX852X=m +CONFIG_TOUCHSCREEN_HYCON_HY46XX=m +CONFIG_TOUCHSCREEN_HYNITRON_CSTXXX=m +CONFIG_TOUCHSCREEN_HYNITRON_CST816X=m +CONFIG_TOUCHSCREEN_ILI210X=m +CONFIG_TOUCHSCREEN_ILITEK=m +CONFIG_TOUCHSCREEN_ELAN=m +CONFIG_TOUCHSCREEN_WACOM_I2C=m +CONFIG_TOUCHSCREEN_MMS114=m +CONFIG_TOUCHSCREEN_MSG2638=m +CONFIG_TOUCHSCREEN_NOVATEK_NVT_TS=m +CONFIG_TOUCHSCREEN_IMAGIS=m +CONFIG_TOUCHSCREEN_EDT_FT5X06=m +CONFIG_TOUCHSCREEN_RASPBERRYPI_FW=m +CONFIG_TOUCHSCREEN_TI_AM335X_TSC=m +CONFIG_TOUCHSCREEN_PIXCIR=m +CONFIG_TOUCHSCREEN_USB_COMPOSITE=m +CONFIG_TOUCHSCREEN_TSC2007=m +CONFIG_TOUCHSCREEN_TSC2007_IIO=y +CONFIG_TOUCHSCREEN_RM_TS=m +CONFIG_TOUCHSCREEN_SILEAD=m +CONFIG_TOUCHSCREEN_SIS_I2C=m +CONFIG_TOUCHSCREEN_ST1232=m +CONFIG_TOUCHSCREEN_STMPE=m +CONFIG_TOUCHSCREEN_ZET6223=m +CONFIG_TOUCHSCREEN_ZFORCE=m +CONFIG_TOUCHSCREEN_COLIBRI_VF50=m +CONFIG_TOUCHSCREEN_IQS5XX=m +CONFIG_TOUCHSCREEN_IQS7211=m +CONFIG_TOUCHSCREEN_ZINITIX=m +CONFIG_TOUCHSCREEN_HIMAX_HX83112B=m +CONFIG_INPUT_MISC=y +CONFIG_INPUT_BBNSM_PWRKEY=m +CONFIG_INPUT_CS40L50_VIBRA=m +CONFIG_INPUT_E3X0_BUTTON=m +CONFIG_INPUT_PM8941_PWRKEY=m +CONFIG_INPUT_PM8XXX_VIBRATOR=m +CONFIG_INPUT_MAX77650_ONKEY=m +CONFIG_INPUT_MAX77693_HAPTIC=m +CONFIG_INPUT_GPIO_BEEPER=m +CONFIG_INPUT_GPIO_VIBRA=m +CONFIG_INPUT_KXTJ9=m +CONFIG_INPUT_TPS65219_PWRBUTTON=m +CONFIG_INPUT_TPS6594_PWRBUTTON=m +CONFIG_INPUT_AXP20X_PEK=m +CONFIG_INPUT_UINPUT=m +CONFIG_INPUT_PWM_BEEPER=m +CONFIG_INPUT_RK805_PWRKEY=m +CONFIG_INPUT_IQS269A=m +CONFIG_INPUT_IQS626A=m +CONFIG_INPUT_IQS7222=m +CONFIG_INPUT_CMA3000=m +CONFIG_INPUT_CMA3000_I2C=m +CONFIG_INPUT_HISI_POWERKEY=y +CONFIG_INPUT_QNAP_MCU=m +CONFIG_INPUT_RT5120_PWRKEY=m +CONFIG_INPUT_MACSMC_INPUT=m +CONFIG_RMI4_I2C=m +CONFIG_RMI4_SPI=m +CONFIG_RMI4_SMB=m +CONFIG_RMI4_F1A=y +CONFIG_RMI4_F21=y +CONFIG_RMI4_F34=y +CONFIG_RMI4_F55=y +CONFIG_SERIO_SERPORT=m +CONFIG_SERIO_AMBAKMI=m +CONFIG_SERIO_RAW=m +CONFIG_SERIO_ALTERA_PS2=m +CONFIG_SERIO_ARC_PS2=m +CONFIG_GAMEPORT_EMU10K1=m +CONFIG_GAMEPORT_FM801=m +# CONFIG_LEGACY_PTYS is not set +# CONFIG_LEGACY_TIOCSTI is not set +CONFIG_SERIAL_8250=y +# CONFIG_SERIAL_8250_16550A_VARIANTS is not set +CONFIG_SERIAL_8250_CONSOLE=y +CONFIG_SERIAL_8250_EXAR=m +CONFIG_SERIAL_8250_NR_UARTS=32 +CONFIG_SERIAL_8250_RUNTIME_UARTS=32 +CONFIG_SERIAL_8250_EXTENDED=y +CONFIG_SERIAL_8250_SHARE_IRQ=y +CONFIG_SERIAL_8250_RSA=y +CONFIG_SERIAL_8250_MANY_PORTS=y +CONFIG_SERIAL_8250_PCI1XXXX=y +CONFIG_SERIAL_8250_BCM2835AUX=y +CONFIG_SERIAL_8250_DFL=m +CONFIG_SERIAL_8250_DW=y +CONFIG_SERIAL_8250_EM=y +CONFIG_SERIAL_8250_RT288X=y +CONFIG_SERIAL_8250_OMAP=y +CONFIG_SERIAL_OF_PLATFORM=y +CONFIG_SERIAL_AMBA_PL011=y +CONFIG_SERIAL_AMBA_PL011_CONSOLE=y +CONFIG_SERIAL_EARLYCON_SEMIHOST=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL_EARLYCON=y +CONFIG_SERIAL_APPLE_DOCKCHANNEL=y +CONFIG_SERIAL_MESON=y +CONFIG_SERIAL_MESON_CONSOLE=y +CONFIG_SERIAL_SAMSUNG=y +CONFIG_SERIAL_SAMSUNG_CONSOLE=y +CONFIG_SERIAL_TEGRA=y +CONFIG_SERIAL_TEGRA_TCU=y +CONFIG_SERIAL_TEGRA_UTC=y +CONFIG_SERIAL_IMX=y +CONFIG_SERIAL_IMX_CONSOLE=y +# CONFIG_SERIAL_IMX_EARLYCON is not set +CONFIG_SERIAL_SH_SCI=y +CONFIG_SERIAL_RSCI=y +CONFIG_SERIAL_JSM=m +CONFIG_SERIAL_MSM=y +CONFIG_SERIAL_MSM_CONSOLE=y +CONFIG_SERIAL_QCOM_GENI=y +CONFIG_SERIAL_QCOM_GENI_CONSOLE=y +CONFIG_SERIAL_SC16IS7XX=m +CONFIG_SERIAL_XILINX_PS_UART=y +CONFIG_SERIAL_XILINX_PS_UART_CONSOLE=y +CONFIG_SERIAL_ARC=m +CONFIG_SERIAL_FSL_LPUART=y +CONFIG_SERIAL_FSL_LPUART_CONSOLE=y +CONFIG_SERIAL_FSL_LINFLEXUART=y +CONFIG_SERIAL_FSL_LINFLEXUART_CONSOLE=y +CONFIG_SERIAL_MVEBU_UART=y +CONFIG_NOZOMI=m +CONFIG_NULL_TTY=m +CONFIG_RPMSG_TTY=m +CONFIG_SERIAL_DEV_BUS=y +CONFIG_VIRTIO_CONSOLE=y +CONFIG_IPMI_HANDLER=m +CONFIG_IPMI_DEVICE_INTERFACE=m +CONFIG_IPMI_SSIF=m +CONFIG_IPMI_IPMB=m +CONFIG_IPMI_WATCHDOG=m +CONFIG_IPMI_POWEROFF=m +CONFIG_SSIF_IPMI_BMC=m +CONFIG_IPMB_DEVICE_INTERFACE=m +CONFIG_HW_RANDOM=y +CONFIG_HW_RANDOM_TIMERIOMEM=m +CONFIG_HW_RANDOM_BCM2835=m +CONFIG_HW_RANDOM_IPROC_RNG200=m +CONFIG_HW_RANDOM_OMAP=m +CONFIG_HW_RANDOM_VIRTIO=y +CONFIG_HW_RANDOM_HISI=m +CONFIG_HW_RANDOM_XGENE=m +CONFIG_HW_RANDOM_MESON=m +CONFIG_HW_RANDOM_CAVIUM=m +CONFIG_HW_RANDOM_XIPHERA=m +CONFIG_HW_RANDOM_CN10K=m +CONFIG_HW_RANDOM_ROCKCHIP=m +CONFIG_TCG_TPM2_HMAC=y +CONFIG_TCG_TIS=y +CONFIG_TCG_TIS_SPI=m +CONFIG_TCG_TIS_SPI_CR50=y +CONFIG_TCG_TIS_I2C=m +CONFIG_TCG_TIS_SYNQUACER=m +CONFIG_TCG_TIS_I2C_CR50=m +CONFIG_TCG_TIS_I2C_ATMEL=m +CONFIG_TCG_TIS_I2C_INFINEON=m +CONFIG_TCG_TIS_I2C_NUVOTON=m +CONFIG_TCG_VTPM_PROXY=m +CONFIG_TCG_FTPM_TEE=m +CONFIG_XILLYBUS=m +CONFIG_XILLYBUS_PCIE=m +CONFIG_XILLYBUS_OF=m +CONFIG_XILLYUSB=m +CONFIG_I2C_CHARDEV=m +CONFIG_I2C_ARB_GPIO_CHALLENGE=m +CONFIG_I2C_MUX_GPIO=m +CONFIG_I2C_MUX_GPMUX=m +CONFIG_I2C_MUX_LTC4306=m +CONFIG_I2C_MUX_PCA9541=m +CONFIG_I2C_MUX_PCA954x=m +CONFIG_I2C_MUX_PINCTRL=m +CONFIG_I2C_MUX_REG=m +CONFIG_I2C_MUX_MLXCPLD=m +CONFIG_I2C_MUX_MULE=m +CONFIG_I2C_AMD_MP2=m +CONFIG_I2C_NFORCE2=m +CONFIG_I2C_NVIDIA_GPU=m +CONFIG_I2C_ZHAOXIN=m +CONFIG_I2C_SCMI=m +CONFIG_I2C_BCM2835=m +CONFIG_I2C_BRCMSTB=m +CONFIG_I2C_CADENCE=m +CONFIG_I2C_DESIGNWARE_CORE=y +CONFIG_I2C_DESIGNWARE_PCI=m +CONFIG_I2C_GPIO=m +CONFIG_I2C_IMX=m +CONFIG_I2C_IMX_LPI2C=m +CONFIG_I2C_MLXBF=m +CONFIG_I2C_MESON=m +CONFIG_I2C_MV64XXX=m +CONFIG_I2C_OMAP=m +CONFIG_I2C_APPLE=m +CONFIG_I2C_DP855=m +CONFIG_I2C_PCA_PLATFORM=m +CONFIG_I2C_PXA=m +CONFIG_I2C_QCOM_CCI=m +CONFIG_I2C_QCOM_GENI=y +CONFIG_I2C_QUP=m +CONFIG_I2C_RIIC=m +CONFIG_I2C_RK3X=y +CONFIG_I2C_SIMTEC=m +CONFIG_I2C_SYNQUACER=m +CONFIG_I2C_TEGRA=m +CONFIG_I2C_TEGRA_BPMP=m +CONFIG_I2C_VERSATILE=m +CONFIG_I2C_THUNDERX=m +CONFIG_I2C_XILINX=m +CONFIG_I2C_XLP9XX=m +CONFIG_I2C_DIOLAN_U2C=m +CONFIG_I2C_DLN2=m +CONFIG_I2C_CP2615=m +CONFIG_I2C_PCI1XXXX=m +CONFIG_I2C_TINY_USB=m +CONFIG_I2C_MLXCPLD=m +CONFIG_I2C_CROS_EC_TUNNEL=m +CONFIG_I2C_XGENE_SLIMPRO=m +CONFIG_I2C_VIRTIO=m +CONFIG_I2C_STUB=m +CONFIG_I2C_SLAVE_EEPROM=m +CONFIG_I3C=m +CONFIG_ADI_I3C_MASTER=m +CONFIG_CDNS_I3C_MASTER=m +CONFIG_DW_I3C_MASTER=m +CONFIG_SVC_I3C_MASTER=m +CONFIG_MIPI_I3C_HCI=m +CONFIG_MIPI_I3C_HCI_PCI=m +CONFIG_RENESAS_I3C=m +CONFIG_SPI=y +CONFIG_SPI_ALTERA_DFL=m +CONFIG_SPI_AMLOGIC_SPIFC_A1=m +CONFIG_SPI_AMLOGIC_SPIFC_A4=m +CONFIG_SPI_AMLOGIC_SPISG=m +CONFIG_SPI_APPLE=m +CONFIG_SPI_APPLE_QSPI=m +CONFIG_SPI_ARMADA_3700=m +CONFIG_SPI_BCM2835=m +CONFIG_SPI_BCM2835AUX=m +CONFIG_SPI_CADENCE=m +CONFIG_SPI_CADENCE_QUADSPI=m +CONFIG_SPI_CADENCE_XSPI=m +CONFIG_SPI_CH341=m +CONFIG_SPI_DESIGNWARE=m +CONFIG_SPI_DW_DMA=y +CONFIG_SPI_DW_PCI=m +CONFIG_SPI_DW_MMIO=m +CONFIG_SPI_DLN2=m +CONFIG_SPI_FSL_LPSPI=m +CONFIG_SPI_FSL_QUADSPI=m +CONFIG_SPI_NXP_FLEXSPI=m +CONFIG_SPI_NXP_XSPI=m +CONFIG_SPI_GPIO=m +CONFIG_SPI_IMX=m +CONFIG_SPI_FSL_DSPI=m +CONFIG_SPI_MESON_SPICC=m +CONFIG_SPI_MESON_SPIFC=m +CONFIG_SPI_MICROCHIP_CORE_QSPI=m +CONFIG_SPI_OMAP24XX=m +CONFIG_SPI_ORION=m +CONFIG_SPI_PCI1XXXX=m +CONFIG_SPI_PL022=m +CONFIG_SPI_ROCKCHIP=m +CONFIG_SPI_ROCKCHIP_SFC=m +CONFIG_SPI_RSPI=m +CONFIG_SPI_RZV2H_RSPI=m +CONFIG_SPI_QCOM_QSPI=m +CONFIG_SPI_QPIC_SNAND=m +CONFIG_SPI_QUP=m +CONFIG_SPI_QCOM_GENI=m +CONFIG_SPI_SN_F_OSPI=m +CONFIG_SPI_SUN6I=m +CONFIG_SPI_SYNQUACER=m +CONFIG_SPI_TEGRA210_QUAD=y +CONFIG_SPI_TEGRA114=m +CONFIG_SPI_THUNDERX=m +CONFIG_SPI_VIRTIO=m +CONFIG_SPI_XILINX=m +CONFIG_SPI_XLP=m +CONFIG_SPI_ZYNQMP_GQSPI=m +CONFIG_SPI_AMD=y +CONFIG_SPI_MUX=m +CONFIG_SPI_SPIDEV=m +CONFIG_SPMI=y +CONFIG_SPMI_APPLE=y +CONFIG_SPMI_HISI3670=m +CONFIG_PPS_CLIENT_LDISC=m +CONFIG_PPS_CLIENT_GPIO=m +CONFIG_PPS_GENERATOR=m +CONFIG_DP83640_PHY=m +CONFIG_PTP_1588_CLOCK_KVM=m +CONFIG_PTP_1588_CLOCK_IDT82P33=m +CONFIG_PTP_1588_CLOCK_IDTCM=m +CONFIG_PTP_1588_CLOCK_FC3W=m +CONFIG_PTP_1588_CLOCK_MOCK=m +CONFIG_PTP_DFL_TOD=m +CONFIG_PTP_NETC_V4_TIMER=m +CONFIG_ZL3073X_I2C=m +CONFIG_ZL3073X_SPI=m +CONFIG_PINCTRL_AMD=y +CONFIG_PINCTRL_AMDISP=m +CONFIG_PINCTRL_APPLE_GPIO=m +CONFIG_PINCTRL_AS3722=y +CONFIG_PINCTRL_AXP209=m +CONFIG_PINCTRL_CY8C95X0=m +CONFIG_PINCTRL_MAX77620=y +CONFIG_PINCTRL_RK805=m +CONFIG_PINCTRL_SCMI=y +CONFIG_PINCTRL_SINGLE=y +CONFIG_PINCTRL_MLXBF3=m +CONFIG_PINCTRL_BRCMSTB=y +CONFIG_PINCTRL_BCM2712=y +CONFIG_PINCTRL_CS42L43=m +CONFIG_PINCTRL_SKY1=y +CONFIG_PINCTRL_IMX_SCMI=y +CONFIG_PINCTRL_IMX91=y +CONFIG_PINCTRL_IMX93=y +CONFIG_PINCTRL_S32G2=y +# CONFIG_PINCTRL_IPQ5018 is not set +# CONFIG_PINCTRL_IPQ5332 is not set +# CONFIG_PINCTRL_IPQ5424 is not set +# CONFIG_PINCTRL_IPQ8074 is not set +# CONFIG_PINCTRL_IPQ6018 is not set +# CONFIG_PINCTRL_IPQ9574 is not set +# CONFIG_PINCTRL_KAANAPALI is not set +# CONFIG_PINCTRL_MSM8953 is not set +# CONFIG_PINCTRL_MSM8976 is not set +# CONFIG_PINCTRL_MSM8994 is not set +CONFIG_PINCTRL_MSM8996=m +CONFIG_PINCTRL_MSM8998=m +CONFIG_PINCTRL_QCM2290=m +# CONFIG_PINCTRL_QCS404 is not set +# CONFIG_PINCTRL_QCS615 is not set +CONFIG_PINCTRL_QDF2XXX=m +# CONFIG_PINCTRL_QDU1000 is not set +# CONFIG_PINCTRL_SDM660 is not set +# CONFIG_PINCTRL_SDM670 is not set +CONFIG_PINCTRL_SDM845=m +# CONFIG_PINCTRL_SDX75 is not set +# CONFIG_PINCTRL_SM4450 is not set +CONFIG_PINCTRL_SM6115=m +# CONFIG_PINCTRL_SM6125 is not set +# CONFIG_PINCTRL_SM6350 is not set +# CONFIG_PINCTRL_SM6375 is not set +# CONFIG_PINCTRL_SM7150 is not set +CONFIG_PINCTRL_MILOS=m +# CONFIG_PINCTRL_SM8150 is not set +# CONFIG_PINCTRL_SM8250 is not set +# CONFIG_PINCTRL_SM8350 is not set +CONFIG_PINCTRL_SM8450=m +# CONFIG_PINCTRL_SM8550 is not set +# CONFIG_PINCTRL_SM8650 is not set +# CONFIG_PINCTRL_SM8750 is not set +CONFIG_PINCTRL_QCOM_SPMI_PMIC=y +CONFIG_PINCTRL_LPASS_LPI=m +CONFIG_PINCTRL_SC7280_LPASS_LPI=m +CONFIG_PINCTRL_SM4250_LPASS_LPI=m +CONFIG_PINCTRL_SM6115_LPASS_LPI=m +CONFIG_PINCTRL_SM8250_LPASS_LPI=m +CONFIG_PINCTRL_SM8450_LPASS_LPI=m +CONFIG_PINCTRL_SC8280XP_LPASS_LPI=m +CONFIG_PINCTRL_SM8550_LPASS_LPI=m +CONFIG_PINCTRL_SUN8I_H3=y +CONFIG_PINCTRL_SUN20I_D1=y +CONFIG_GPIO_CDEV_V1=y +CONFIG_GPIO_RASPBERRYPI_EXP=m +CONFIG_GPIO_BRCMSTB=m +CONFIG_GPIO_CADENCE=m +CONFIG_GPIO_DAVINCI=m +CONFIG_GPIO_DWAPB=m +CONFIG_GPIO_EXAR=m +CONFIG_GPIO_MB86S7X=m +CONFIG_GPIO_MPC8XXX=y +CONFIG_GPIO_MXC=m +CONFIG_GPIO_PL061=y +CONFIG_GPIO_RCAR=m +CONFIG_GPIO_SYSCON=m +CONFIG_GPIO_THUNDERX=m +CONFIG_GPIO_VF610=y +CONFIG_GPIO_WCD934X=m +CONFIG_GPIO_XGENE=y +CONFIG_GPIO_XGENE_SB=m +CONFIG_GPIO_XILINX=m +CONFIG_GPIO_XLP=m +CONFIG_GPIO_ZYNQ=m +CONFIG_GPIO_FXL6408=m +CONFIG_GPIO_DS4520=m +CONFIG_GPIO_MAX732X=m +CONFIG_GPIO_PCA953X=y +CONFIG_GPIO_PCA953X_IRQ=y +CONFIG_GPIO_PCA9570=m +CONFIG_GPIO_PCF857X=m +CONFIG_GPIO_TPIC2810=m +CONFIG_GPIO_ADP5585=m +CONFIG_GPIO_BD9571MWV=m +CONFIG_GPIO_CROS_EC=m +CONFIG_GPIO_DLN2=m +CONFIG_GPIO_MACSMC=m +CONFIG_GPIO_MAX77620=y +CONFIG_GPIO_MAX77650=m +CONFIG_GPIO_QIXIS_FPGA=m +CONFIG_GPIO_STMPE=y +CONFIG_GPIO_TPS65086=m +CONFIG_GPIO_WM8994=m +CONFIG_GPIO_MLXBF=m +CONFIG_GPIO_MLXBF2=m +CONFIG_GPIO_MLXBF3=m +CONFIG_GPIO_PCI_IDIO_16=m +CONFIG_GPIO_MOXTET=m +CONFIG_GPIO_MPSSE=m +CONFIG_GPIO_AGGREGATOR=m +CONFIG_GPIO_LINE_MUX=m +CONFIG_GPIO_VIRTIO=m +CONFIG_GPIO_SIM=m +CONFIG_GPIO_VIRTUSER=m +CONFIG_W1=m +CONFIG_W1_MASTER_DS2490=m +CONFIG_W1_MASTER_DS2482=m +CONFIG_W1_MASTER_GPIO=m +CONFIG_W1_MASTER_UART=m +CONFIG_W1_SLAVE_THERM=m +CONFIG_W1_SLAVE_SMEM=m +CONFIG_W1_SLAVE_DS2405=m +CONFIG_W1_SLAVE_DS2408=m +# CONFIG_W1_SLAVE_DS2408_READBACK is not set +CONFIG_W1_SLAVE_DS2413=m +CONFIG_W1_SLAVE_DS2406=m +CONFIG_W1_SLAVE_DS2423=m +CONFIG_W1_SLAVE_DS2805=m +CONFIG_W1_SLAVE_DS2430=m +CONFIG_W1_SLAVE_DS2431=m +CONFIG_W1_SLAVE_DS2433=m +CONFIG_W1_SLAVE_DS2433_CRC=y +CONFIG_W1_SLAVE_DS2438=m +CONFIG_W1_SLAVE_DS2780=m +CONFIG_W1_SLAVE_DS2781=m +CONFIG_W1_SLAVE_DS28E04=m +CONFIG_POWER_RESET_AS3722=y +CONFIG_POWER_RESET_GPIO=y +CONFIG_POWER_RESET_GPIO_RESTART=y +CONFIG_POWER_RESET_HISI=y +CONFIG_POWER_RESET_MACSMC=m +CONFIG_POWER_RESET_MSM=y +CONFIG_POWER_RESET_QCOM_PON=m +CONFIG_POWER_RESET_ODROID_GO_ULTRA_POWEROFF=y +CONFIG_POWER_RESET_REGULATOR=y +CONFIG_POWER_RESET_RESTART=y +CONFIG_POWER_RESET_TORADEX_EC=m +CONFIG_POWER_RESET_TPS65086=y +CONFIG_POWER_RESET_VEXPRESS=y +CONFIG_POWER_RESET_XGENE=y +CONFIG_POWER_RESET_SYSCON=y +CONFIG_POWER_RESET_SYSCON_POWEROFF=y +CONFIG_SYSCON_REBOOT_MODE=y +CONFIG_NVMEM_REBOOT_MODE=m +CONFIG_POWER_MLXBF=m +CONFIG_POWER_SEQUENCING_PCIE_M2=m +CONFIG_IP5XXX_POWER=m +CONFIG_BATTERY_CW2015=m +CONFIG_BATTERY_LENOVO_YOGA_C630=m +CONFIG_BATTERY_QCOM_BATTMGR=m +CONFIG_BATTERY_SAMSUNG_SDI=y +CONFIG_BATTERY_SBS=m +CONFIG_BATTERY_BQ27XXX=m +# CONFIG_BATTERY_BQ27XXX_HDQ is not set +CONFIG_CHARGER_AXP20X=m +CONFIG_BATTERY_AXP20X=m +CONFIG_AXP20X_POWER=m +CONFIG_BATTERY_MAX17040=m +CONFIG_BATTERY_MAX17042=m +CONFIG_BATTERY_MAX1720X=m +CONFIG_CHARGER_GPIO=m +CONFIG_CHARGER_LT3651=m +CONFIG_CHARGER_LTC4162L=m +CONFIG_CHARGER_MAX77650=m +CONFIG_CHARGER_MAX77705=m +CONFIG_CHARGER_MAX77976=m +CONFIG_CHARGER_MAX8971=m +CONFIG_CHARGER_QCOM_SMBB=m +CONFIG_CHARGER_BQ24735=m +CONFIG_CHARGER_BQ2515X=m +CONFIG_CHARGER_BQ25980=m +CONFIG_CHARGER_BQ256XX=m +CONFIG_CHARGER_RK817=m +CONFIG_CHARGER_SMB347=m +CONFIG_BATTERY_GAUGE_LTC2941=m +CONFIG_BATTERY_RT5033=m +CONFIG_CHARGER_RT5033=m +CONFIG_CHARGER_RT9467=m +CONFIG_CHARGER_RT9471=m +CONFIG_CHARGER_RT9756=m +CONFIG_CHARGER_CROS_USBPD=m +CONFIG_FUEL_GAUGE_STC3117=m +CONFIG_CHARGER_UCS1002=m +CONFIG_CHARGER_BD99954=m +CONFIG_BATTERY_SURFACE=m +CONFIG_CHARGER_SURFACE=m +CONFIG_BATTERY_UG3105=m +CONFIG_CHARGER_QCOM_SMB2=m +CONFIG_FUEL_GAUGE_MM8013=m +CONFIG_MACSMC_POWER=m +CONFIG_SENSORS_SMPRO=m +CONFIG_SENSORS_AD7314=m +CONFIG_SENSORS_AD7414=m +CONFIG_SENSORS_AD7418=m +CONFIG_SENSORS_ADM1025=m +CONFIG_SENSORS_ADM1026=m +CONFIG_SENSORS_ADM1029=m +CONFIG_SENSORS_ADM1031=m +CONFIG_SENSORS_ADM9240=m +CONFIG_SENSORS_ADT7310=m +CONFIG_SENSORS_ADT7410=m +CONFIG_SENSORS_ADT7411=m +CONFIG_SENSORS_ADT7462=m +CONFIG_SENSORS_ADT7470=m +CONFIG_SENSORS_ADT7475=m +CONFIG_SENSORS_AQUACOMPUTER_D5NEXT=m +CONFIG_SENSORS_ASC7621=m +CONFIG_SENSORS_ASUS_ROG_RYUJIN=m +CONFIG_SENSORS_AXI_FAN_CONTROL=m +CONFIG_SENSORS_APPLE_AON_PTD=m +CONFIG_SENSORS_APPLE_PMP_J613=m +CONFIG_SENSORS_ARM_SCMI=m +CONFIG_SENSORS_ARM_SCPI=m +CONFIG_SENSORS_ATXP1=m +CONFIG_SENSORS_CHIPCAP2=m +CONFIG_SENSORS_CORSAIR_CPRO=m +CONFIG_SENSORS_CORSAIR_PSU=m +CONFIG_SENSORS_DRIVETEMP=m +CONFIG_SENSORS_DS620=m +CONFIG_SENSORS_DS1621=m +CONFIG_SENSORS_F71805F=m +CONFIG_SENSORS_F71882FG=m +CONFIG_SENSORS_F75375S=m +CONFIG_SENSORS_MC33XS2410=m +CONFIG_SENSORS_FTSTEUTATES=m +CONFIG_SENSORS_GIGABYTE_WATERFORCE=m +CONFIG_SENSORS_GL518SM=m +CONFIG_SENSORS_GL520SM=m +CONFIG_SENSORS_G760A=m +CONFIG_SENSORS_G762=m +CONFIG_SENSORS_GPIO_FAN=m +CONFIG_SENSORS_HS3001=m +CONFIG_SENSORS_HTU31=m +CONFIG_SENSORS_IBMAEM=m +CONFIG_SENSORS_IBMPEX=m +CONFIG_SENSORS_IIO_HWMON=m +CONFIG_SENSORS_ISL28022=m +CONFIG_SENSORS_IT87=m +CONFIG_SENSORS_JC42=m +CONFIG_SENSORS_POWERZ=m +CONFIG_SENSORS_POWR1220=m +CONFIG_SENSORS_LINEAGE=m +CONFIG_SENSORS_LTC2945=m +CONFIG_SENSORS_LTC2947_I2C=m +CONFIG_SENSORS_LTC2947_SPI=m +CONFIG_SENSORS_LTC2990=m +CONFIG_SENSORS_LTC2991=m +CONFIG_SENSORS_LTC4151=m +CONFIG_SENSORS_LTC4215=m +CONFIG_SENSORS_LTC4222=m +CONFIG_SENSORS_LTC4245=m +CONFIG_SENSORS_LTC4260=m +CONFIG_SENSORS_LTC4261=m +CONFIG_SENSORS_MACSMC_HWMON=m +CONFIG_SENSORS_MAX1111=m +CONFIG_SENSORS_MAX16065=m +CONFIG_SENSORS_MAX1619=m +CONFIG_SENSORS_MAX1668=m +CONFIG_SENSORS_MAX197=m +CONFIG_SENSORS_MAX31722=m +CONFIG_SENSORS_MAX31760=m +CONFIG_MAX31827=m +CONFIG_SENSORS_MAX6620=m +CONFIG_SENSORS_MAX6639=m +CONFIG_SENSORS_MAX6650=m +CONFIG_SENSORS_MAX6697=m +CONFIG_SENSORS_MAX31790=m +CONFIG_SENSORS_MAX77705=m +CONFIG_SENSORS_MC34VR500=m +CONFIG_SENSORS_MCP3021=m +CONFIG_SENSORS_MLXREG_FAN=m +CONFIG_SENSORS_TC654=m +CONFIG_SENSORS_MR75203=m +CONFIG_SENSORS_ADCXX=m +CONFIG_SENSORS_LM63=m +CONFIG_SENSORS_LM70=m +CONFIG_SENSORS_LM73=m +CONFIG_SENSORS_LM75=m +CONFIG_SENSORS_LM77=m +CONFIG_SENSORS_LM78=m +CONFIG_SENSORS_LM80=m +CONFIG_SENSORS_LM83=m +CONFIG_SENSORS_LM85=m +CONFIG_SENSORS_LM87=m +CONFIG_SENSORS_LM90=m +CONFIG_SENSORS_LM92=m +CONFIG_SENSORS_LM93=m +CONFIG_SENSORS_LM95234=m +CONFIG_SENSORS_LM95241=m +CONFIG_SENSORS_LM95245=m +CONFIG_SENSORS_PC87360=m +CONFIG_SENSORS_PC87427=m +CONFIG_SENSORS_NTC_THERMISTOR=m +CONFIG_SENSORS_NCT6683=m +CONFIG_SENSORS_NCT6775=m +CONFIG_SENSORS_NCT6775_I2C=m +CONFIG_SENSORS_NCT7363=m +CONFIG_SENSORS_NCT7802=m +CONFIG_SENSORS_NCT7904=m +CONFIG_SENSORS_NPCM7XX=m +CONFIG_SENSORS_NZXT_KRAKEN2=m +CONFIG_SENSORS_NZXT_KRAKEN3=m +CONFIG_SENSORS_NZXT_SMART2=m +CONFIG_SENSORS_PCF8591=m +CONFIG_PMBUS=m +CONFIG_SENSORS_ADM1266=m +CONFIG_SENSORS_ADM1275=m +CONFIG_SENSORS_ADP1050=m +CONFIG_SENSORS_BEL_PFE=m +CONFIG_SENSORS_BPA_RS600=m +CONFIG_SENSORS_CRPS=m +CONFIG_SENSORS_DELTA_AHE50DC_FAN=m +CONFIG_SENSORS_FSP_3Y=m +CONFIG_SENSORS_HAC300S=m +CONFIG_SENSORS_DPS920AB=m +CONFIG_SENSORS_INA233=m +CONFIG_SENSORS_LM25066=m +CONFIG_SENSORS_LM25066_REGULATOR=y +CONFIG_SENSORS_LT3074=m +CONFIG_SENSORS_LT3074_REGULATOR=m +CONFIG_SENSORS_LT7182S=m +CONFIG_SENSORS_LTC2978=m +CONFIG_SENSORS_LTC3815=m +CONFIG_SENSORS_MAX16064=m +CONFIG_SENSORS_MAX17616=m +CONFIG_SENSORS_MAX20751=m +CONFIG_SENSORS_MAX34440=m +CONFIG_SENSORS_MAX8688=m +CONFIG_SENSORS_MP2869=m +CONFIG_SENSORS_MP2888=m +CONFIG_SENSORS_MP2891=m +CONFIG_SENSORS_MP2925=m +CONFIG_SENSORS_MP29502=m +CONFIG_SENSORS_MP2975=m +CONFIG_SENSORS_MP2993=m +CONFIG_SENSORS_MP2975_REGULATOR=y +CONFIG_SENSORS_MP5023=m +CONFIG_SENSORS_MP5920=m +CONFIG_SENSORS_MP5926=m +CONFIG_SENSORS_MP9941=m +CONFIG_SENSORS_MP9945=m +CONFIG_SENSORS_MPQ7932_REGULATOR=y +CONFIG_SENSORS_MPQ7932=m +CONFIG_SENSORS_MPQ8785=m +CONFIG_SENSORS_PIM4328=m +CONFIG_SENSORS_PLI1209BC=m +CONFIG_SENSORS_PLI1209BC_REGULATOR=y +CONFIG_SENSORS_PM6764TR=m +CONFIG_SENSORS_Q54SJ108A2=m +CONFIG_SENSORS_STEF48H28=m +CONFIG_SENSORS_TDA38640=m +CONFIG_SENSORS_TDA38640_REGULATOR=y +CONFIG_SENSORS_TPS25990=m +CONFIG_SENSORS_TPS40422=m +CONFIG_SENSORS_TPS53679=m +CONFIG_SENSORS_TPS546D24=m +CONFIG_SENSORS_UCD9000=m +CONFIG_SENSORS_UCD9200=m +CONFIG_SENSORS_XDP710=m +CONFIG_SENSORS_XDPE152=m +CONFIG_SENSORS_ZL6100=m +CONFIG_SENSORS_PT5161L=m +CONFIG_SENSORS_PWM_FAN=m +CONFIG_SENSORS_QNAP_MCU_HWMON=m +CONFIG_SENSORS_RASPBERRYPI_HWMON=m +CONFIG_SENSORS_SHT15=m +CONFIG_SENSORS_SHT21=m +CONFIG_SENSORS_SHT3x=m +CONFIG_SENSORS_SHTC1=m +CONFIG_SENSORS_SIS5595=m +CONFIG_SENSORS_SY7636A=m +CONFIG_SENSORS_DME1737=m +CONFIG_SENSORS_EMC1403=m +CONFIG_SENSORS_EMC2305=m +CONFIG_SENSORS_EMC6W201=m +CONFIG_SENSORS_SMSC47M1=m +CONFIG_SENSORS_SMSC47M192=m +CONFIG_SENSORS_SMSC47B397=m +CONFIG_SENSORS_SCH5627=m +CONFIG_SENSORS_SCH5636=m +CONFIG_SENSORS_SURFACE_FAN=m +CONFIG_SENSORS_SURFACE_TEMP=m +CONFIG_SENSORS_ADC128D818=m +CONFIG_SENSORS_ADS7828=m +CONFIG_SENSORS_ADS7871=m +CONFIG_SENSORS_AMC6821=m +CONFIG_SENSORS_INA209=m +CONFIG_SENSORS_INA2XX=m +CONFIG_SENSORS_INA238=m +CONFIG_SENSORS_INA3221=m +CONFIG_SENSORS_SPD5118=m +CONFIG_SENSORS_TC74=m +CONFIG_SENSORS_THMC50=m +CONFIG_SENSORS_TMP102=m +CONFIG_SENSORS_TMP103=m +CONFIG_SENSORS_TMP108=m +CONFIG_SENSORS_TMP401=m +CONFIG_SENSORS_TMP421=m +CONFIG_SENSORS_TMP464=m +CONFIG_SENSORS_TMP513=m +CONFIG_SENSORS_TSC1641=m +CONFIG_SENSORS_VEXPRESS=m +CONFIG_SENSORS_VIA686A=m +CONFIG_SENSORS_VT1211=m +CONFIG_SENSORS_VT8231=m +CONFIG_SENSORS_W83773G=m +CONFIG_SENSORS_W83781D=m +CONFIG_SENSORS_W83791D=m +CONFIG_SENSORS_W83792D=m +CONFIG_SENSORS_W83793=m +CONFIG_SENSORS_W83795=m +CONFIG_SENSORS_W83L785TS=m +CONFIG_SENSORS_W83L786NG=m +CONFIG_SENSORS_W83627HF=m +CONFIG_SENSORS_W83627EHF=m +CONFIG_SENSORS_XGENE=m +CONFIG_SENSORS_INTEL_M10_BMC_HWMON=m +CONFIG_SENSORS_ACPI_POWER=m +CONFIG_THERMAL_NETLINK=y +CONFIG_THERMAL_STATISTICS=y +CONFIG_THERMAL_DEFAULT_GOV_POWER_ALLOCATOR=y +CONFIG_THERMAL_GOV_FAIR_SHARE=y +CONFIG_THERMAL_GOV_USER_SPACE=y +CONFIG_THERMAL_GOV_POWER_ALLOCATOR=y +CONFIG_DEVFREQ_THERMAL=y +CONFIG_PCIE_THERMAL=y +CONFIG_THERMAL_MMIO=m +CONFIG_HISI_THERMAL=m +CONFIG_IMX_SC_THERMAL=m +CONFIG_IMX8MM_THERMAL=m +CONFIG_IMX91_THERMAL=m +CONFIG_K3_THERMAL=m +CONFIG_MAX77620_THERMAL=m +CONFIG_QORIQ_THERMAL=m +CONFIG_SUN8I_THERMAL=m +CONFIG_ROCKCHIP_THERMAL=m +CONFIG_ARMADA_THERMAL=m +CONFIG_BCM2711_THERMAL=m +CONFIG_BCM2835_THERMAL=m +CONFIG_RZG2L_THERMAL=m +CONFIG_RZG3E_THERMAL=m +CONFIG_RZG3S_THERMAL=m +CONFIG_TEGRA_SOCTHERM=m +CONFIG_TEGRA_BPMP_THERMAL=m +CONFIG_QCOM_TSENS=m +CONFIG_QCOM_SPMI_ADC_TM5=m +CONFIG_QCOM_SPMI_TEMP_ALARM=m +CONFIG_QCOM_LMH=m +CONFIG_KHADAS_MCU_FAN_THERMAL=m +CONFIG_APPLE_PMP_THERMAL=m +CONFIG_WATCHDOG=y +CONFIG_WATCHDOG_SYSFS=y +CONFIG_WATCHDOG_HRTIMER_PRETIMEOUT=y +CONFIG_SOFT_WATCHDOG=m +CONFIG_BD96801_WATCHDOG=m +CONFIG_CROS_EC_WATCHDOG=m +CONFIG_GPIO_WATCHDOG=m +CONFIG_WDAT_WDT=m +CONFIG_XILINX_WATCHDOG=m +CONFIG_XILINX_WINDOW_WATCHDOG=m +CONFIG_MLX_WDT=m +CONFIG_ARM_SP805_WATCHDOG=m +CONFIG_ARM_SBSA_WATCHDOG=m +CONFIG_ARMADA_37XX_WATCHDOG=m +CONFIG_CADENCE_WATCHDOG=m +CONFIG_DW_WATCHDOG=m +CONFIG_K3_RTI_WATCHDOG=m +CONFIG_SUNXI_WATCHDOG=m +CONFIG_MAX77620_WATCHDOG=m +CONFIG_IMX2_WDT=m +CONFIG_IMX_SC_WDT=m +CONFIG_IMX7ULP_WDT=m +CONFIG_S32G_WDT=m +CONFIG_TEGRA_WATCHDOG=m +CONFIG_QCOM_WDT=m +CONFIG_MESON_GXBB_WATCHDOG=m +CONFIG_MESON_WATCHDOG=m +CONFIG_ARM_SMC_WATCHDOG=m +CONFIG_RENESAS_WWDT=m +CONFIG_RENESAS_RZG2LWDT=m +CONFIG_RENESAS_RZV2HWDT=m +CONFIG_PM8916_WATCHDOG=m +CONFIG_APPLE_WATCHDOG=y +CONFIG_ALIM7101_WDT=m +CONFIG_I6300ESB_WDT=m +CONFIG_HP_WATCHDOG=m +CONFIG_NIC7018_WDT=m +CONFIG_BCM2835_WDT=m +CONFIG_PCIPCWATCHDOG=m +CONFIG_WDTPCI=m +CONFIG_USBPCWATCHDOG=m +CONFIG_SSB_DRIVER_GPIO=y +CONFIG_BCMA_DRIVER_GMAC_CMN=y +CONFIG_BCMA_DRIVER_GPIO=y +CONFIG_MFD_ADP5585=m +CONFIG_MFD_SMPRO=m +CONFIG_MFD_AS3722=y +CONFIG_MFD_BD9571MWV=m +CONFIG_MFD_AC100=m +CONFIG_MFD_AXP20X_I2C=y +CONFIG_MFD_AXP20X_RSB=m +CONFIG_MFD_CS40L50_I2C=m +CONFIG_MFD_CS40L50_SPI=m +CONFIG_MFD_CS42L43_I2C=m +CONFIG_MFD_CS42L43_SDW=m +CONFIG_MFD_MACSMC=y +CONFIG_MFD_DLN2=m +CONFIG_MFD_HI6421_PMIC=m +CONFIG_MFD_HI6421_SPMI=m +CONFIG_MFD_HI655X_PMIC=m +CONFIG_MFD_MAX5970=m +CONFIG_MFD_MAX77620=y +CONFIG_MFD_MAX77650=m +CONFIG_MFD_MAX77686=y +CONFIG_MFD_MAX77705=m +CONFIG_MFD_MAX77714=m +CONFIG_MFD_MAX77759=m +CONFIG_MFD_SPMI_PMIC=y +CONFIG_MFD_SY7636A=m +CONFIG_MFD_RT4831=m +CONFIG_MFD_RT5033=m +CONFIG_MFD_RT5120=m +CONFIG_MFD_RK8XX_I2C=m +CONFIG_MFD_RK8XX_SPI=m +CONFIG_MFD_SM501=m +CONFIG_MFD_SM501_GPIO=y +CONFIG_MFD_STMPE=y +CONFIG_STMPE_SPI=y +CONFIG_MFD_TI_AM335X_TSCADC=m +CONFIG_MFD_TPS65086=m +CONFIG_MFD_TPS65219=m +CONFIG_MFD_TPS6594_I2C=m +CONFIG_MFD_VX855=m +CONFIG_MFD_ROHM_BD718XX=y +CONFIG_MFD_ROHM_BD96801=m +CONFIG_MFD_WCD934X=m +CONFIG_MFD_KHADAS_MCU=m +CONFIG_MFD_QCOM_PM8008=m +CONFIG_MFD_INTEL_M10_BMC_SPI=m +CONFIG_MFD_INTEL_M10_BMC_PMCI=m +CONFIG_MFD_QNAP_MCU=m +CONFIG_MFD_RSMU_I2C=m +CONFIG_MFD_RSMU_SPI=m +CONFIG_REGULATOR_FIXED_VOLTAGE=y +CONFIG_REGULATOR_VIRTUAL_CONSUMER=m +CONFIG_REGULATOR_USERSPACE_CONSUMER=m +CONFIG_REGULATOR_ACT8865=m +CONFIG_REGULATOR_ADP5055=m +CONFIG_REGULATOR_ANATOP=m +CONFIG_REGULATOR_ARM_SCMI=y +CONFIG_REGULATOR_AS3722=m +CONFIG_REGULATOR_AW37503=m +CONFIG_REGULATOR_AXP20X=m +CONFIG_REGULATOR_BD718XX=m +CONFIG_REGULATOR_BD9571MWV=m +CONFIG_REGULATOR_BD96801=m +CONFIG_REGULATOR_CROS_EC=m +CONFIG_REGULATOR_FAN53555=y +CONFIG_REGULATOR_GPIO=y +CONFIG_REGULATOR_HI6421=m +CONFIG_REGULATOR_HI6421V530=m +CONFIG_REGULATOR_HI655X=m +CONFIG_REGULATOR_HI6421V600=m +CONFIG_REGULATOR_MAX5970=m +CONFIG_REGULATOR_MAX77503=m +CONFIG_REGULATOR_MAX77620=y +CONFIG_REGULATOR_MAX77650=m +CONFIG_REGULATOR_MAX77675=m +CONFIG_REGULATOR_MAX77857=m +CONFIG_REGULATOR_MAX8893=m +CONFIG_REGULATOR_MAX8973=m +CONFIG_REGULATOR_MAX20411=m +CONFIG_REGULATOR_MAX77686=m +CONFIG_REGULATOR_MAX77802=m +CONFIG_REGULATOR_MP5416=m +CONFIG_REGULATOR_MP8859=m +CONFIG_REGULATOR_MP886X=m +CONFIG_REGULATOR_MT6316=m +CONFIG_REGULATOR_MT6363=m +CONFIG_REGULATOR_PCA9450=m +CONFIG_REGULATOR_PF9453=m +CONFIG_REGULATOR_PF0900=m +CONFIG_REGULATOR_PF530X=m +CONFIG_REGULATOR_PF8X00=m +CONFIG_REGULATOR_PFUZE100=m +CONFIG_REGULATOR_PWM=y +CONFIG_REGULATOR_QCOM_PM8008=m +CONFIG_REGULATOR_QCOM_REFGEN=m +CONFIG_REGULATOR_QCOM_RPMH=y +CONFIG_REGULATOR_QCOM_SMD_RPM=m +CONFIG_REGULATOR_QCOM_SPMI=m +CONFIG_REGULATOR_QCOM_USB_VBUS=m +CONFIG_REGULATOR_RAA215300=m +CONFIG_REGULATOR_RASPBERRYPI_TOUCHSCREEN_ATTINY=m +CONFIG_REGULATOR_RASPBERRYPI_TOUCHSCREEN_V2=m +CONFIG_REGULATOR_RK808=m +CONFIG_REGULATOR_RT4801=m +CONFIG_REGULATOR_RT4803=m +CONFIG_REGULATOR_RT4831=m +CONFIG_REGULATOR_RT5033=m +CONFIG_REGULATOR_RT5120=m +CONFIG_REGULATOR_RT5190A=m +CONFIG_REGULATOR_RT5739=m +CONFIG_REGULATOR_RT5759=m +CONFIG_REGULATOR_RT6160=m +CONFIG_REGULATOR_RT6190=m +CONFIG_REGULATOR_RT6245=m +CONFIG_REGULATOR_RT8092=m +CONFIG_REGULATOR_RTQ2134=m +CONFIG_REGULATOR_RTMV20=m +CONFIG_REGULATOR_RTQ6752=m +CONFIG_REGULATOR_RTQ2208=m +# CONFIG_REGULATOR_SUN20I is not set +CONFIG_REGULATOR_SY7636A=m +CONFIG_REGULATOR_SY8106A=m +CONFIG_REGULATOR_SY8827N=m +CONFIG_REGULATOR_TPS62360=m +CONFIG_REGULATOR_TPS6286X=m +CONFIG_REGULATOR_TPS65086=m +CONFIG_REGULATOR_TPS65132=m +CONFIG_REGULATOR_TPS65185=m +CONFIG_REGULATOR_TPS65219=m +CONFIG_REGULATOR_VCTRL=m +CONFIG_REGULATOR_VEXPRESS=m +CONFIG_REGULATOR_WM8994=m +CONFIG_REGULATOR_QCOM_LABIBB=m +CONFIG_RC_CORE=y +CONFIG_BPF_LIRC_MODE2=y +CONFIG_LIRC=y +CONFIG_RC_MAP=m +CONFIG_RC_DECODERS=y +CONFIG_IR_IMON_DECODER=m +CONFIG_IR_JVC_DECODER=m +CONFIG_IR_MCE_KBD_DECODER=m +CONFIG_IR_NEC_DECODER=m +CONFIG_IR_RC5_DECODER=m +CONFIG_IR_RC6_DECODER=m +CONFIG_IR_RCMM_DECODER=m +CONFIG_IR_SANYO_DECODER=m +CONFIG_IR_SHARP_DECODER=m +CONFIG_IR_SONY_DECODER=m +CONFIG_IR_XMP_DECODER=m +CONFIG_RC_DEVICES=y +CONFIG_IR_ENE=m +CONFIG_IR_FINTEK=m +CONFIG_IR_GPIO_CIR=m +CONFIG_IR_GPIO_TX=m +CONFIG_IR_HIX5HD2=m +CONFIG_IR_IGORPLUGUSB=m +CONFIG_IR_IGUANA=m +CONFIG_IR_IMON=m +CONFIG_IR_IMON_RAW=m +CONFIG_IR_ITE_CIR=m +CONFIG_IR_MCEUSB=m +CONFIG_IR_MESON=m +CONFIG_IR_NUVOTON=m +CONFIG_IR_PWM_TX=m +CONFIG_IR_REDRAT3=m +CONFIG_IR_SERIAL=m +CONFIG_IR_SERIAL_TRANSMITTER=y +CONFIG_IR_SPI=m +CONFIG_IR_STREAMZAP=m +CONFIG_IR_SUNXI=m +CONFIG_IR_TOY=m +CONFIG_IR_TTUSBIR=m +CONFIG_RC_ATI_REMOTE=m +CONFIG_RC_LOOPBACK=m +CONFIG_RC_XBOX_DVD=m +CONFIG_MEDIA_CEC_RC=y +CONFIG_MEDIA_CEC_SUPPORT=y +CONFIG_CEC_CH7322=m +CONFIG_CEC_CROS_EC=m +CONFIG_CEC_MESON_AO=m +CONFIG_CEC_MESON_G12A_AO=m +CONFIG_CEC_GPIO=m +CONFIG_CEC_TEGRA=m +CONFIG_USB_PULSE8_CEC=m +CONFIG_USB_RAINSHADOW_CEC=m +CONFIG_MEDIA_SUPPORT=m +CONFIG_MEDIA_SUPPORT_FILTER=y +CONFIG_MEDIA_CAMERA_SUPPORT=y +CONFIG_MEDIA_ANALOG_TV_SUPPORT=y +CONFIG_MEDIA_DIGITAL_TV_SUPPORT=y +CONFIG_MEDIA_RADIO_SUPPORT=y +CONFIG_MEDIA_PLATFORM_SUPPORT=y +CONFIG_MEDIA_TEST_SUPPORT=y +CONFIG_MEDIA_USB_SUPPORT=y +CONFIG_USB_GSPCA=m +CONFIG_USB_GSPCA_BENQ=m +CONFIG_USB_GSPCA_CONEX=m +CONFIG_USB_GSPCA_CPIA1=m +CONFIG_USB_GSPCA_DTCS033=m +CONFIG_USB_GSPCA_ETOMS=m +CONFIG_USB_GSPCA_FINEPIX=m +CONFIG_USB_GSPCA_JEILINJ=m +CONFIG_USB_GSPCA_JL2005BCD=m +CONFIG_USB_GSPCA_KINECT=m +CONFIG_USB_GSPCA_KONICA=m +CONFIG_USB_GSPCA_MARS=m +CONFIG_USB_GSPCA_MR97310A=m +CONFIG_USB_GSPCA_NW80X=m +CONFIG_USB_GSPCA_OV519=m +CONFIG_USB_GSPCA_OV534=m +CONFIG_USB_GSPCA_OV534_9=m +CONFIG_USB_GSPCA_PAC207=m +CONFIG_USB_GSPCA_PAC7302=m +CONFIG_USB_GSPCA_PAC7311=m +CONFIG_USB_GSPCA_SE401=m +CONFIG_USB_GSPCA_SN9C2028=m +CONFIG_USB_GSPCA_SN9C20X=m +CONFIG_USB_GSPCA_SONIXB=m +CONFIG_USB_GSPCA_SONIXJ=m +CONFIG_USB_GSPCA_SPCA1528=m +CONFIG_USB_GSPCA_SPCA500=m +CONFIG_USB_GSPCA_SPCA501=m +CONFIG_USB_GSPCA_SPCA505=m +CONFIG_USB_GSPCA_SPCA506=m +CONFIG_USB_GSPCA_SPCA508=m +CONFIG_USB_GSPCA_SPCA561=m +CONFIG_USB_GSPCA_SQ905=m +CONFIG_USB_GSPCA_SQ905C=m +CONFIG_USB_GSPCA_SQ930X=m +CONFIG_USB_GSPCA_STK014=m +CONFIG_USB_GSPCA_STK1135=m +CONFIG_USB_GSPCA_STV0680=m +CONFIG_USB_GSPCA_SUNPLUS=m +CONFIG_USB_GSPCA_T613=m +CONFIG_USB_GSPCA_TOPRO=m +CONFIG_USB_GSPCA_TOUPTEK=m +CONFIG_USB_GSPCA_TV8532=m +CONFIG_USB_GSPCA_VC032X=m +CONFIG_USB_GSPCA_VICAM=m +CONFIG_USB_GSPCA_XIRLINK_CIT=m +CONFIG_USB_GSPCA_ZC3XX=m +CONFIG_USB_GL860=m +CONFIG_USB_M5602=m +CONFIG_USB_STV06XX=m +CONFIG_USB_PWC=m +CONFIG_USB_S2255=m +CONFIG_VIDEO_USBTV=m +CONFIG_USB_VIDEO_CLASS=m +CONFIG_VIDEO_GO7007=m +CONFIG_VIDEO_GO7007_USB=m +CONFIG_VIDEO_GO7007_USB_S2250_BOARD=m +CONFIG_VIDEO_HDPVR=m +CONFIG_VIDEO_PVRUSB2=m +CONFIG_VIDEO_STK1160=m +CONFIG_VIDEO_AU0828=m +CONFIG_VIDEO_CX231XX=m +CONFIG_VIDEO_CX231XX_ALSA=m +CONFIG_VIDEO_CX231XX_DVB=m +CONFIG_DVB_AS102=m +CONFIG_DVB_USB_V2=m +CONFIG_DVB_USB_AF9015=m +CONFIG_DVB_USB_AF9035=m +CONFIG_DVB_USB_ANYSEE=m +CONFIG_DVB_USB_AU6610=m +CONFIG_DVB_USB_AZ6007=m +CONFIG_DVB_USB_CE6230=m +CONFIG_DVB_USB_DVBSKY=m +CONFIG_DVB_USB_EC168=m +CONFIG_DVB_USB_GL861=m +CONFIG_DVB_USB_LME2510=m +CONFIG_DVB_USB_MXL111SF=m +CONFIG_DVB_USB_RTL28XXU=m +CONFIG_DVB_USB_ZD1301=m +CONFIG_DVB_USB=m +CONFIG_DVB_USB_A800=m +CONFIG_DVB_USB_AF9005=m +CONFIG_DVB_USB_AF9005_REMOTE=m +CONFIG_DVB_USB_AZ6027=m +CONFIG_DVB_USB_CINERGY_T2=m +CONFIG_DVB_USB_CXUSB=m +CONFIG_DVB_USB_CXUSB_ANALOG=y +CONFIG_DVB_USB_DIB0700=m +CONFIG_DVB_USB_DIBUSB_MB=m +CONFIG_DVB_USB_DIBUSB_MC=m +CONFIG_DVB_USB_DIGITV=m +CONFIG_DVB_USB_DTT200U=m +CONFIG_DVB_USB_DTV5100=m +CONFIG_DVB_USB_DW2102=m +CONFIG_DVB_USB_GP8PSK=m +CONFIG_DVB_USB_M920X=m +CONFIG_DVB_USB_NOVA_T_USB2=m +CONFIG_DVB_USB_OPERA1=m +CONFIG_DVB_USB_PCTV452E=m +CONFIG_DVB_USB_TECHNISAT_USB2=m +CONFIG_DVB_USB_TTUSB2=m +CONFIG_DVB_USB_UMT_010=m +CONFIG_DVB_USB_VP702X=m +CONFIG_DVB_USB_VP7045=m +CONFIG_SMS_USB_DRV=m +CONFIG_DVB_TTUSB_BUDGET=m +CONFIG_DVB_TTUSB_DEC=m +CONFIG_VIDEO_EM28XX=m +CONFIG_VIDEO_EM28XX_V4L2=m +CONFIG_VIDEO_EM28XX_ALSA=m +CONFIG_VIDEO_EM28XX_DVB=m +CONFIG_MEDIA_PCI_SUPPORT=y +CONFIG_VIDEO_SOLO6X10=m +CONFIG_VIDEO_TW686X=m +CONFIG_VIDEO_IVTV=m +CONFIG_VIDEO_FB_IVTV=m +CONFIG_VIDEO_HEXIUM_GEMINI=m +CONFIG_VIDEO_HEXIUM_ORION=m +CONFIG_VIDEO_MXB=m +CONFIG_VIDEO_BT848=m +CONFIG_DVB_BT8XX=m +CONFIG_VIDEO_CX18=m +CONFIG_VIDEO_CX18_ALSA=m +CONFIG_VIDEO_CX23885=m +CONFIG_MEDIA_ALTERA_CI=m +CONFIG_VIDEO_CX88=m +CONFIG_VIDEO_CX88_ALSA=m +CONFIG_VIDEO_CX88_BLACKBIRD=m +CONFIG_VIDEO_CX88_DVB=m +CONFIG_VIDEO_SAA7134=m +CONFIG_VIDEO_SAA7134_ALSA=m +CONFIG_VIDEO_SAA7134_DVB=m +CONFIG_VIDEO_SAA7134_GO7007=m +CONFIG_VIDEO_SAA7164=m +CONFIG_DVB_B2C2_FLEXCOP_PCI=m +CONFIG_DVB_DDBRIDGE=m +CONFIG_DVB_DM1105=m +CONFIG_MANTIS_CORE=m +CONFIG_DVB_MANTIS=m +CONFIG_DVB_HOPPER=m +CONFIG_DVB_NETUP_UNIDVB=m +CONFIG_DVB_NGENE=m +CONFIG_DVB_PLUTO2=m +CONFIG_DVB_PT1=m +CONFIG_DVB_PT3=m +CONFIG_DVB_SMIPCIE=m +CONFIG_DVB_BUDGET_CORE=m +CONFIG_DVB_BUDGET=m +CONFIG_DVB_BUDGET_CI=m +CONFIG_DVB_BUDGET_AV=m +CONFIG_IPU_BRIDGE=m +CONFIG_RADIO_MAXIRADIO=m +CONFIG_RADIO_SAA7706H=m +CONFIG_RADIO_SHARK=m +CONFIG_RADIO_SHARK2=m +CONFIG_RADIO_SI4713=m +CONFIG_RADIO_TEA5764=m +CONFIG_USB_DSBR=m +CONFIG_USB_KEENE=m +CONFIG_USB_MA901=m +CONFIG_USB_MR800=m +CONFIG_RADIO_SI470X=m +CONFIG_USB_SI470X=m +CONFIG_I2C_SI470X=m +CONFIG_V4L_PLATFORM_DRIVERS=y +CONFIG_V4L_MEM2MEM_DRIVERS=y +CONFIG_VIDEO_MUX=m +CONFIG_VIDEO_ALLEGRO_DVT=m +CONFIG_VIDEO_C3_ISP=m +CONFIG_VIDEO_C3_MIPI_ADAPTER=m +CONFIG_VIDEO_C3_MIPI_CSI2=m +CONFIG_VIDEO_MESON_GE2D=m +CONFIG_VIDEO_AMPHION_VPU=m +CONFIG_VIDEO_APPLE_ISP=m +CONFIG_VIDEO_APPLE_AVD=m +CONFIG_VIDEO_APPLE_AVE=m +CONFIG_VIDEO_APPLE_JPEG=m +CONFIG_VIDEO_APPLE_PRORES=m +CONFIG_VIDEO_APPLE_SCALER=m +CONFIG_VIDEO_MALI_C55=m +CONFIG_VIDEO_BCM2835_UNICAM=m +CONFIG_VIDEO_CADENCE_CSI2RX=m +CONFIG_VIDEO_CADENCE_CSI2TX=m +CONFIG_VIDEO_CODA=m +CONFIG_VIDEO_WAVE_VPU=m +CONFIG_VIDEO_E5010_JPEG_ENC=m +CONFIG_VIDEO_TEGRA_VDE=m +CONFIG_VIDEO_IMX7_CSI=m +CONFIG_VIDEO_IMX8MQ_MIPI_CSI2=m +CONFIG_VIDEO_IMX_MIPI_CSIS=m +CONFIG_VIDEO_IMX8_ISI=m +CONFIG_VIDEO_IMX8_ISI_M2M=y +CONFIG_VIDEO_IMX_PXP=m +CONFIG_VIDEO_DW100=m +CONFIG_VIDEO_IMX8_JPEG=m +CONFIG_VIDEO_QCOM_CAMSS=m +CONFIG_VIDEO_QCOM_IRIS=m +CONFIG_VIDEO_QCOM_VENUS=m +CONFIG_VIDEO_RASPBERRYPI_PISP_BE=m +CONFIG_VIDEO_RP1_CFE=m +CONFIG_VIDEO_RZG2L_CSI2=m +CONFIG_VIDEO_RZG2L_CRU=m +CONFIG_VIDEO_RZV2H_IVC=m +CONFIG_VIDEO_RENESAS_FCP=m +CONFIG_VIDEO_RENESAS_FDP1=m +CONFIG_VIDEO_RENESAS_VSP1=m +CONFIG_VIDEO_ROCKCHIP_RGA=m +CONFIG_VIDEO_ROCKCHIP_CIF=m +CONFIG_VIDEO_ROCKCHIP_ISP1=m +CONFIG_VIDEO_ROCKCHIP_VDEC=m +CONFIG_VIDEO_SUN4I_CSI=m +CONFIG_VIDEO_SUN6I_CSI=m +CONFIG_VIDEO_SUN8I_DEINTERLACE=m +CONFIG_VIDEO_SUN8I_ROTATE=m +CONFIG_VIDEO_SYNOPSYS_HDMIRX=m +CONFIG_VIDEO_SYNOPSYS_HDMIRX_LOAD_DEFAULT_EDID=y +CONFIG_VIDEO_DW_MIPI_CSI2RX=m +CONFIG_VIDEO_TI_CAL=m +CONFIG_VIDEO_TI_CAL_MC=y +CONFIG_VIDEO_TI_J721E_CSI2RX=m +CONFIG_VIDEO_HANTRO=m +CONFIG_VIDEO_HANTRO_HEVC_RFC=y +CONFIG_SMS_SDIO_DRV=m +CONFIG_V4L_TEST_DRIVERS=y +CONFIG_VIDEO_VIM2M=m +CONFIG_VIDEO_VICODEC=m +CONFIG_VIDEO_VIMC=m +CONFIG_VIDEO_VIVID=m +CONFIG_VIDEO_VIVID_CEC=y +CONFIG_VIDEO_VISL=m +CONFIG_VIDEO_AR0521=m +CONFIG_VIDEO_GC0308=m +CONFIG_VIDEO_GC0310=m +CONFIG_VIDEO_GC2145=m +CONFIG_VIDEO_HI556=m +CONFIG_VIDEO_HI846=m +CONFIG_VIDEO_HI847=m +CONFIG_VIDEO_IMX111=m +CONFIG_VIDEO_IMX208=m +CONFIG_VIDEO_IMX214=m +CONFIG_VIDEO_IMX219=m +CONFIG_VIDEO_IMX258=m +CONFIG_VIDEO_IMX274=m +CONFIG_VIDEO_IMX283=m +CONFIG_VIDEO_IMX290=m +CONFIG_VIDEO_IMX296=m +CONFIG_VIDEO_IMX319=m +CONFIG_VIDEO_IMX334=m +CONFIG_VIDEO_IMX335=m +CONFIG_VIDEO_IMX355=m +CONFIG_VIDEO_IMX412=m +CONFIG_VIDEO_IMX415=m +CONFIG_VIDEO_MT9M001=m +CONFIG_VIDEO_MT9M114=m +CONFIG_VIDEO_MT9P031=m +CONFIG_VIDEO_MT9T112=m +CONFIG_VIDEO_MT9V032=m +CONFIG_VIDEO_MT9V111=m +CONFIG_VIDEO_OG01A1B=m +CONFIG_VIDEO_OG0VE1B=m +CONFIG_VIDEO_OS05B10=m +CONFIG_VIDEO_OV01A10=m +CONFIG_VIDEO_OV02A10=m +CONFIG_VIDEO_OV02E10=m +CONFIG_VIDEO_OV02C10=m +CONFIG_VIDEO_OV08D10=m +CONFIG_VIDEO_OV08X40=m +CONFIG_VIDEO_OV13858=m +CONFIG_VIDEO_OV13B10=m +CONFIG_VIDEO_OV2659=m +CONFIG_VIDEO_OV2680=m +CONFIG_VIDEO_OV2685=m +CONFIG_VIDEO_OV2735=m +CONFIG_VIDEO_OV2740=m +CONFIG_VIDEO_OV4689=m +CONFIG_VIDEO_OV5640=m +CONFIG_VIDEO_OV5645=m +CONFIG_VIDEO_OV5647=m +CONFIG_VIDEO_OV5648=m +CONFIG_VIDEO_OV5670=m +CONFIG_VIDEO_OV5675=m +CONFIG_VIDEO_OV5693=m +CONFIG_VIDEO_OV5695=m +CONFIG_VIDEO_OV6211=m +CONFIG_VIDEO_OV64A40=m +CONFIG_VIDEO_OV7251=m +CONFIG_VIDEO_OV772X=m +CONFIG_VIDEO_OV7740=m +CONFIG_VIDEO_OV8856=m +CONFIG_VIDEO_OV8858=m +CONFIG_VIDEO_OV8865=m +CONFIG_VIDEO_OV9282=m +CONFIG_VIDEO_OV9640=m +CONFIG_VIDEO_OV9650=m +CONFIG_VIDEO_OV9734=m +CONFIG_VIDEO_RDACM20=m +CONFIG_VIDEO_RJ54N1=m +CONFIG_VIDEO_S5C73M3=m +CONFIG_VIDEO_S5K3M5=m +CONFIG_VIDEO_S5K5BAF=m +CONFIG_VIDEO_S5K6A3=m +CONFIG_VIDEO_S5KJN1=m +CONFIG_VIDEO_VD55G1=m +CONFIG_VIDEO_VD56G3=m +CONFIG_VIDEO_CCS=m +CONFIG_VIDEO_ET8EK8=m +CONFIG_VIDEO_AD5820=m +CONFIG_VIDEO_AK7375=m +CONFIG_VIDEO_DW9714=m +CONFIG_VIDEO_DW9719=m +CONFIG_VIDEO_DW9768=m +CONFIG_VIDEO_DW9807_VCM=m +CONFIG_VIDEO_ADP1653=m +CONFIG_VIDEO_LM3560=m +CONFIG_VIDEO_LM3646=m +CONFIG_VIDEO_TDA1997X=m +CONFIG_VIDEO_TLV320AIC23B=m +CONFIG_VIDEO_ADV7180=m +CONFIG_VIDEO_ADV7183=m +CONFIG_VIDEO_ADV748X=m +CONFIG_VIDEO_ADV7604=m +CONFIG_VIDEO_ADV7842=m +CONFIG_VIDEO_BT819=m +CONFIG_VIDEO_BT856=m +CONFIG_VIDEO_BT866=m +CONFIG_VIDEO_ISL7998X=m +CONFIG_VIDEO_LT6911UXE=m +CONFIG_VIDEO_KS0127=m +CONFIG_VIDEO_MAX9286=m +CONFIG_VIDEO_ML86V7667=m +CONFIG_VIDEO_SAA7110=m +CONFIG_VIDEO_TC358743=m +CONFIG_VIDEO_TC358743_CEC=y +CONFIG_VIDEO_TC358746=m +CONFIG_VIDEO_TVP514X=m +CONFIG_VIDEO_TVP7002=m +CONFIG_VIDEO_TW9910=m +CONFIG_VIDEO_VPX3220=m +CONFIG_VIDEO_ADV7170=m +CONFIG_VIDEO_ADV7175=m +CONFIG_VIDEO_ADV7343=m +CONFIG_VIDEO_ADV7393=m +CONFIG_VIDEO_AK881X=m +CONFIG_VIDEO_SAA7185=m +CONFIG_VIDEO_THS8200=m +CONFIG_VIDEO_I2C=m +CONFIG_VIDEO_ST_MIPID02=m +CONFIG_VIDEO_THS7303=m +CONFIG_VIDEO_DS90UB913=m +CONFIG_VIDEO_DS90UB953=m +CONFIG_VIDEO_DS90UB960=m +CONFIG_VIDEO_MAX96714=m +CONFIG_VIDEO_MAX96717=m +CONFIG_CXD2880_SPI_DRV=m +CONFIG_VIDEO_GS1662=m +CONFIG_AUXDISPLAY=y +CONFIG_HD44780=m +CONFIG_HT16K33=m +CONFIG_DRM=y +CONFIG_DRM_WERROR=y +CONFIG_DRM_PANIC=y +CONFIG_DRM_PANIC_SCREEN_QR_CODE=y +CONFIG_DRM_LOAD_EDID_FIRMWARE=y +CONFIG_DRM_DISPLAY_DP_AUX_CEC=y +CONFIG_DRM_DISPLAY_DP_AUX_CHARDEV=y +CONFIG_DRM_ADP=m +CONFIG_DRM_AMDGPU=m +CONFIG_DRM_AMDGPU_SI=y +CONFIG_DRM_AMDGPU_CIK=y +CONFIG_DRM_AMD_ISP=y +CONFIG_DRM_AMD_ACP=y +CONFIG_DRM_AMD_DC_SI=y +CONFIG_DRM_AMD_SECURE_DISPLAY=y +CONFIG_HSA_AMD=y +CONFIG_DRM_APPLE=m +CONFIG_DRM_APPLE_DCP_T8132=y +CONFIG_DRM_APPLE_DCP_T8152=y +CONFIG_DRM_HDLCD=m +CONFIG_DRM_MALI_DISPLAY=m +CONFIG_DRM_KOMEDA=m +CONFIG_DRM_ASAHI=m +CONFIG_DRM_ASAHI_G18=y +CONFIG_DRM_ASAHI_M5=y +CONFIG_DRM_ASAHI_M3_T8122=y +CONFIG_DRM_AST=m +CONFIG_DRM_CHIPONE_ICN6211=m +CONFIG_DRM_CHRONTEL_CH7033=m +CONFIG_DRM_CROS_EC_ANX7688=m +CONFIG_DRM_FSL_LDB=m +CONFIG_DRM_I2C_NXP_TDA998X=m +CONFIG_DRM_ITE_IT6263=m +CONFIG_DRM_ITE_IT6505=m +CONFIG_DRM_LONTIUM_LT8912B=m +CONFIG_DRM_LONTIUM_LT9611=m +CONFIG_DRM_LONTIUM_LT9611UXC=m +CONFIG_DRM_ITE_IT66121=m +CONFIG_DRM_NWL_MIPI_DSI=m +CONFIG_DRM_NXP_PTN3460=m +CONFIG_DRM_PARADE_PS8622=m +CONFIG_DRM_PARADE_PS8640=m +CONFIG_DRM_SAMSUNG_DSIM=m +CONFIG_DRM_SII902X=m +CONFIG_DRM_SII9234=m +CONFIG_DRM_SIMPLE_BRIDGE=m +CONFIG_DRM_SOLOMON_SSD2825=m +CONFIG_DRM_TOSHIBA_TC358762=m +CONFIG_DRM_TOSHIBA_TC358764=m +CONFIG_DRM_TOSHIBA_TC358767=m +CONFIG_DRM_TOSHIBA_TC358768=m +CONFIG_DRM_TOSHIBA_TC358775=m +CONFIG_DRM_TI_DLPC3433=m +CONFIG_DRM_TI_TFP410=m +CONFIG_DRM_TI_SN65DSI83=m +CONFIG_DRM_TI_SN65DSI86=m +CONFIG_DRM_TI_TPD12S015=m +CONFIG_DRM_WAVESHARE_BRIDGE=m +CONFIG_DRM_ANALOGIX_ANX6345=m +CONFIG_DRM_ANALOGIX_ANX78XX=m +CONFIG_DRM_ANALOGIX_ANX7625=m +CONFIG_DRM_I2C_ADV7511=m +CONFIG_DRM_I2C_ADV7511_AUDIO=y +CONFIG_DRM_CDNS_DSI=m +CONFIG_DRM_CDNS_MHDP8546=m +CONFIG_DRM_IMX8MP_DW_HDMI_BRIDGE=m +CONFIG_DRM_IMX8QM_LDB=m +CONFIG_DRM_IMX8QXP_LDB=m +CONFIG_DRM_IMX8QXP_PIXEL_COMBINER=m +CONFIG_DRM_IMX8QXP_PIXEL_LINK=m +CONFIG_DRM_IMX8QXP_PIXEL_LINK_TO_DPI=m +CONFIG_DRM_IMX93_MIPI_DSI=m +CONFIG_DRM_DW_HDMI_AHB_AUDIO=m +CONFIG_DRM_DW_HDMI_GP_AUDIO=m +CONFIG_DRM_DW_HDMI_CEC=m +CONFIG_DRM_DW_HDMI_QP_CEC=y +CONFIG_DRM_ETNAVIV=m +CONFIG_DRM_GUD=m +CONFIG_DRM_HISI_KIRIN=m +CONFIG_DRM_HYPERV=m +CONFIG_DRM_POWERVR=m +CONFIG_DRM_IMX8_DC=m +CONFIG_DRM_IMX_DCSS=m +CONFIG_DRM_IMX_LCDC=m +CONFIG_DRM_LIMA=m +CONFIG_DRM_MESON=m +CONFIG_DRM_MGAG200=m +CONFIG_DRM_MSM=m +# CONFIG_DRM_MSM_MDP4 is not set +# CONFIG_DRM_MSM_DSI_28NM_8960_PHY is not set +CONFIG_DRM_IMX_LCDIF=m +CONFIG_DRM_NOUVEAU=m +CONFIG_DRM_PANEL_ARM_VERSATILE=m +CONFIG_DRM_PANEL_BOE_BF060Y8M_AJ0=m +CONFIG_DRM_PANEL_BOE_TD4320=m +CONFIG_DRM_PANEL_BOE_TH101MB31UIG002_28A=m +CONFIG_DRM_PANEL_BOE_TV101WUM_NL6=m +CONFIG_DRM_PANEL_BOE_TV101WUM_LL2=m +CONFIG_DRM_PANEL_ELIDA_KD35T133=m +CONFIG_DRM_PANEL_FEIXIN_K101_IM2BA02=m +CONFIG_DRM_PANEL_FEIYANG_FY07024DI26A30D=m +CONFIG_DRM_PANEL_DSI_CM=m +CONFIG_DRM_PANEL_HIMAX_HX8279=m +CONFIG_DRM_PANEL_HIMAX_HX83102=m +CONFIG_DRM_PANEL_HIMAX_HX83112B=m +CONFIG_DRM_PANEL_HIMAX_HX8394=m +CONFIG_DRM_PANEL_HYDIS_HV101HD1=m +CONFIG_DRM_PANEL_ILITEK_IL9322=m +CONFIG_DRM_PANEL_ILITEK_ILI9341=m +CONFIG_DRM_PANEL_ILITEK_ILI9881C=m +CONFIG_DRM_PANEL_ILITEK_ILI9882T=m +CONFIG_DRM_PANEL_INNOLUX_EJ030NA=m +CONFIG_DRM_PANEL_JADARD_JD9365DA_H3=m +CONFIG_DRM_PANEL_JDI_LPM102A188A=m +CONFIG_DRM_PANEL_JDI_R63452=m +CONFIG_DRM_PANEL_KHADAS_TS050=m +CONFIG_DRM_PANEL_KINGDISPLAY_KD097D04=m +CONFIG_DRM_PANEL_LINCOLNTECH_LCD197=m +CONFIG_DRM_PANEL_LG_LD070WX3=m +CONFIG_DRM_PANEL_LG_LG4573=m +CONFIG_DRM_PANEL_MAGNACHIP_D53E6EA8966=m +CONFIG_DRM_PANEL_MANTIX_MLAF057WE51=m +CONFIG_DRM_PANEL_NEWVISION_NV3051D=m +CONFIG_DRM_PANEL_NOVATEK_NT35510=m +CONFIG_DRM_PANEL_NOVATEK_NT35560=m +CONFIG_DRM_PANEL_NOVATEK_NT35950=m +CONFIG_DRM_PANEL_NOVATEK_NT37801=m +CONFIG_DRM_PANEL_OLIMEX_LCD_OLINUXINO=m +CONFIG_DRM_PANEL_ORISETECH_OTM8009A=m +CONFIG_DRM_PANEL_PANASONIC_VVX10F034N00=m +CONFIG_DRM_PANEL_RASPBERRYPI_TOUCHSCREEN=m +CONFIG_DRM_PANEL_RAYDIUM_RM67200=m +CONFIG_DRM_PANEL_RAYDIUM_RM68200=m +CONFIG_DRM_PANEL_RAYDIUM_RM692E5=m +CONFIG_DRM_PANEL_RAYDIUM_RM69380=m +CONFIG_DRM_PANEL_RENESAS_R61307=m +CONFIG_DRM_PANEL_RENESAS_R69328=m +CONFIG_DRM_PANEL_RONBO_RB070D30=m +CONFIG_DRM_PANEL_SAMSUNG_AMS581VF01=m +CONFIG_DRM_PANEL_SAMSUNG_AMS639RQ08=m +CONFIG_DRM_PANEL_SAMSUNG_S6E88A0_AMS427AP24=m +CONFIG_DRM_PANEL_SAMSUNG_S6E88A0_AMS452EF01=m +CONFIG_DRM_PANEL_SAMSUNG_ATNA33XC20=m +CONFIG_DRM_PANEL_SAMSUNG_DB7430=m +CONFIG_DRM_PANEL_SAMSUNG_LD9040=m +CONFIG_DRM_PANEL_SAMSUNG_LTL106HL02=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3FC2X01=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3HA2=m +CONFIG_DRM_PANEL_SAMSUNG_S6E3HA8=m +CONFIG_DRM_PANEL_SAMSUNG_S6E63J0X03=m +CONFIG_DRM_PANEL_SAMSUNG_S6E8AA0=m +CONFIG_DRM_PANEL_SAMSUNG_S6E8AA5X01_AMS561RA01=m +CONFIG_DRM_PANEL_SAMSUNG_SOFEF00=m +CONFIG_DRM_PANEL_SEIKO_43WVF1G=m +CONFIG_DRM_PANEL_SHARP_LQ079L1SX01=m +CONFIG_DRM_PANEL_SHARP_LQ101R1SX01=m +CONFIG_DRM_PANEL_SHARP_LS043T1LE01=m +CONFIG_DRM_PANEL_SITRONIX_ST7701=m +CONFIG_DRM_PANEL_SITRONIX_ST7703=m +CONFIG_DRM_PANEL_SITRONIX_ST7789V=m +CONFIG_DRM_PANEL_SONY_TULIP_TRULY_NT35521=m +CONFIG_DRM_PANEL_STARTEK_KD070FHFID015=m +CONFIG_DRM_PANEL_EDP=m +CONFIG_DRM_PANEL_SIMPLE=m +CONFIG_DRM_PANEL_SUMMIT=m +CONFIG_DRM_PANEL_SYNAPTICS_TDDI=m +CONFIG_DRM_PANEL_TPO_TPG110=m +CONFIG_DRM_PANEL_TRULY_NT35597_WQXGA=m +CONFIG_DRM_PANEL_VISIONOX_G2647FB105=m +CONFIG_DRM_PANEL_VISIONOX_R66451=m +CONFIG_DRM_PANEL_VISIONOX_RM69299=m +CONFIG_DRM_PANEL_VISIONOX_RM692E5=m +CONFIG_DRM_PANEL_VISIONOX_VTDR6130=m +CONFIG_DRM_PANEL_WIDECHIPS_WS2401=m +CONFIG_DRM_PANFROST=m +CONFIG_DRM_PANTHOR=m +CONFIG_DRM_PL111=m +CONFIG_DRM_QXL=m +CONFIG_DRM_RADEON=m +CONFIG_DRM_RADEON_USERPTR=y +CONFIG_DRM_RZG2L_DU=m +CONFIG_DRM_ROCKCHIP=m +CONFIG_ROCKCHIP_VOP2=y +CONFIG_ROCKCHIP_ANALOGIX_DP=y +CONFIG_ROCKCHIP_CDN_DP=y +CONFIG_ROCKCHIP_DW_DP=y +CONFIG_ROCKCHIP_DW_HDMI=y +CONFIG_ROCKCHIP_DW_HDMI_QP=y +CONFIG_ROCKCHIP_DW_MIPI_DSI=y +CONFIG_ROCKCHIP_DW_MIPI_DSI2=y +CONFIG_ROCKCHIP_INNO_HDMI=y +CONFIG_ROCKCHIP_LVDS=y +CONFIG_ROCKCHIP_RGB=y +CONFIG_ROCKCHIP_RK3066_HDMI=y +CONFIG_DRM_ST7571=m +CONFIG_DRM_ST7571_I2C=m +CONFIG_DRM_ST7571_SPI=m +CONFIG_DRM_ST7586=m +CONFIG_DRM_ST7735R=m +CONFIG_DRM_ST7920=m +CONFIG_DRM_SSD130X=m +CONFIG_DRM_SSD130X_I2C=m +CONFIG_DRM_SSD130X_SPI=m +CONFIG_DRM_SUN4I=m +CONFIG_DRM_SIMPLEDRM=y +CONFIG_DRM_TEGRA=m +CONFIG_DRM_TEGRA_STAGING=y +CONFIG_DRM_TIDSS=m +CONFIG_DRM_BOCHS=m +CONFIG_DRM_CIRRUS_QEMU=m +CONFIG_DRM_GM12U320=m +CONFIG_DRM_PANEL_MIPI_DBI=m +CONFIG_DRM_PIXPAPER=m +CONFIG_TINYDRM_HX8357D=m +CONFIG_TINYDRM_ILI9163=m +CONFIG_TINYDRM_ILI9225=m +CONFIG_TINYDRM_ILI9341=m +CONFIG_TINYDRM_ILI9486=m +CONFIG_TINYDRM_MI0283QT=m +CONFIG_TINYDRM_REPAPER=m +CONFIG_TINYDRM_SHARP_MEMORY=m +CONFIG_DRM_UDL=m +CONFIG_DRM_V3D=m +CONFIG_DRM_VC4=m +CONFIG_DRM_VC4_HDMI_CEC=y +# CONFIG_DRM_VC4_KUNIT_TEST is not set +CONFIG_DRM_VGEM=m +CONFIG_DRM_VIRTIO_GPU=m +CONFIG_DRM_VKMS=m +CONFIG_DRM_VMWGFX=m +CONFIG_DRM_ZYNQMP_DPSUB=m +CONFIG_DRM_ZYNQMP_DPSUB_AUDIO=y +CONFIG_FB=y +CONFIG_FB_EFI=y +# CONFIG_FB_DEVICE is not set +CONFIG_FB_TILEBLITTING=y +CONFIG_LCD_CLASS_DEVICE=m +CONFIG_LCD_PLATFORM=m +CONFIG_BACKLIGHT_CLASS_DEVICE=y +CONFIG_BACKLIGHT_AW99706=m +CONFIG_BACKLIGHT_KTD253=m +CONFIG_BACKLIGHT_KTZ8866=m +CONFIG_BACKLIGHT_PWM=m +CONFIG_BACKLIGHT_APPLE_DWI=m +CONFIG_BACKLIGHT_QCOM_WLED=m +CONFIG_BACKLIGHT_RT4831=m +CONFIG_BACKLIGHT_LM3509=m +CONFIG_BACKLIGHT_LM3630A=m +CONFIG_BACKLIGHT_LP855X=m +CONFIG_BACKLIGHT_MP3309C=m +CONFIG_BACKLIGHT_GPIO=m +CONFIG_BACKLIGHT_ARCXCNN=m +CONFIG_BACKLIGHT_LED=m +CONFIG_FRAMEBUFFER_CONSOLE_ROTATION=y +CONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER=y +CONFIG_LOGO=y +CONFIG_LOGO_LINUX_CLUT224_FILE="drivers/video/logo/logo_linux_clut224.ppm" +CONFIG_DRM_ACCEL=y +CONFIG_DRM_ACCEL_ANE=m +CONFIG_DRM_ACCEL_ARM_ETHOSU=m +CONFIG_DRM_ACCEL_QAIC=m +CONFIG_DRM_ACCEL_ROCKET=m +CONFIG_SOUND=m +CONFIG_SND=m +CONFIG_SND_HRTIMER=m +CONFIG_SND_UTIMER=y +CONFIG_SND_SEQUENCER=m +CONFIG_SND_SEQ_DUMMY=m +CONFIG_SND_DUMMY=m +CONFIG_SND_ALOOP=m +CONFIG_SND_PCMTEST=m +CONFIG_SND_VIRMIDI=m +CONFIG_SND_MTPAV=m +CONFIG_SND_SERIAL_U16550=m +CONFIG_SND_SERIAL_GENERIC=m +CONFIG_SND_MPU401=m +CONFIG_SND_AC97_POWER_SAVE=y +CONFIG_SND_ALS300=m +CONFIG_SND_AU8810=m +CONFIG_SND_AU8820=m +CONFIG_SND_AU8830=m +CONFIG_SND_AZT3328=m +CONFIG_SND_BT87X=m +CONFIG_SND_CA0106=m +CONFIG_SND_CMIPCI=m +CONFIG_SND_OXYGEN=m +CONFIG_SND_CS4281=m +CONFIG_SND_CS46XX=m +CONFIG_SND_CTXFI=m +CONFIG_SND_DARLA20=m +CONFIG_SND_GINA20=m +CONFIG_SND_LAYLA20=m +CONFIG_SND_DARLA24=m +CONFIG_SND_GINA24=m +CONFIG_SND_LAYLA24=m +CONFIG_SND_MONA=m +CONFIG_SND_MIA=m +CONFIG_SND_ECHO3G=m +CONFIG_SND_INDIGO=m +CONFIG_SND_INDIGOIO=m +CONFIG_SND_INDIGODJ=m +CONFIG_SND_INDIGOIOX=m +CONFIG_SND_INDIGODJX=m +CONFIG_SND_EMU10K1=m +CONFIG_SND_EMU10K1X=m +CONFIG_SND_ENS1370=m +CONFIG_SND_ENS1371=m +CONFIG_SND_ES1938=m +CONFIG_SND_ES1968=m +CONFIG_SND_ES1968_INPUT=y +CONFIG_SND_ES1968_RADIO=y +CONFIG_SND_FM801=m +CONFIG_SND_FM801_TEA575X_BOOL=y +CONFIG_SND_HDSP=m +CONFIG_SND_HDSPM=m +CONFIG_SND_ICE1712=m +CONFIG_SND_ICE1724=m +CONFIG_SND_KORG1212=m +CONFIG_SND_LOLA=m +CONFIG_SND_LX6464ES=m +CONFIG_SND_MAESTRO3=m +CONFIG_SND_MAESTRO3_INPUT=y +CONFIG_SND_MIXART=m +CONFIG_SND_NM256=m +CONFIG_SND_PCXHR=m +CONFIG_SND_RIPTIDE=m +CONFIG_SND_RME32=m +CONFIG_SND_RME96=m +CONFIG_SND_RME9652=m +CONFIG_SND_SONICVIBES=m +CONFIG_SND_TRIDENT=m +CONFIG_SND_VIRTUOSO=m +CONFIG_SND_VX222=m +CONFIG_SND_YMFPCI=m +CONFIG_SND_HDA_HWDEP=y +CONFIG_SND_HDA_INPUT_BEEP=y +CONFIG_SND_HDA_INPUT_BEEP_MODE=0 +CONFIG_SND_HDA_PATCH_LOADER=y +CONFIG_SND_HDA_POWER_SAVE_DEFAULT=1 +CONFIG_SND_HDA_PREALLOC_SIZE=2048 +CONFIG_SND_HDA_INTEL=m +CONFIG_SND_HDA_TEGRA=m +CONFIG_SND_HDA_CIX_IPBLOQ=m +CONFIG_SND_HDA_ACPI=m +CONFIG_SND_HDA_CODEC_ANALOG=m +CONFIG_SND_HDA_CODEC_SIGMATEL=m +CONFIG_SND_HDA_CODEC_VIA=m +CONFIG_SND_HDA_CODEC_CONEXANT=m +CONFIG_SND_HDA_CODEC_SENARYTECH=m +CONFIG_SND_HDA_CODEC_CA0110=m +CONFIG_SND_HDA_CODEC_CA0132=m +CONFIG_SND_HDA_CODEC_CMEDIA=m +CONFIG_SND_HDA_CODEC_CM9825=m +CONFIG_SND_HDA_CODEC_SI3054=m +CONFIG_SND_HDA_CODEC_REALTEK=m +CONFIG_SND_HDA_CODEC_CIRRUS=m +CONFIG_SND_HDA_CODEC_CS8409=m +CONFIG_SND_HDA_CODEC_HDMI=m +CONFIG_SND_HDA_INTEL_HDMI_SILENT_STREAM=y +CONFIG_SND_HDA_SCODEC_CS35L41_I2C=m +CONFIG_SND_HDA_SCODEC_CS35L41_SPI=m +CONFIG_SND_HDA_SCODEC_TAS2781_I2C=m +CONFIG_SND_HDA_SCODEC_TAS2781_SPI=m +# CONFIG_SND_SPI is not set +CONFIG_SND_USB_AUDIO=m +CONFIG_SND_USB_AUDIO_MIDI_V2=y +CONFIG_SND_USB_UA101=m +CONFIG_SND_USB_CAIAQ=m +CONFIG_SND_USB_CAIAQ_INPUT=y +CONFIG_SND_USB_6FIRE=m +CONFIG_SND_USB_HIFACE=m +CONFIG_SND_BCD2000=m +CONFIG_SND_USB_AUDIO_QMI=m +CONFIG_SND_USB_POD=m +CONFIG_SND_USB_PODHD=m +CONFIG_SND_USB_TONEPORT=m +CONFIG_SND_USB_VARIAX=m +CONFIG_SND_SOC=m +CONFIG_SND_SOC_USB=m +CONFIG_SND_SOC_ADI_AXI_I2S=m +CONFIG_SND_SOC_ADI_AXI_SPDIF=m +CONFIG_SND_SOC_APPLE_AOP_AUDIO=m +CONFIG_SND_SOC_APPLE_T8152_AOP_AUDIO=m +CONFIG_SND_SOC_APPLE_MACAUDIO=m +CONFIG_SND_SOC_MIKROE_PROTO=m +CONFIG_SND_BCM2835_SOC_I2S=m +CONFIG_SND_DESIGNWARE_I2S=m +CONFIG_SND_DESIGNWARE_PCM=y +CONFIG_SND_SOC_FSL_ASRC=m +CONFIG_SND_SOC_FSL_MQS=m +CONFIG_SND_SOC_FSL_MICFIL=m +CONFIG_SND_SOC_FSL_EASRC=m +CONFIG_SND_SOC_FSL_XCVR=m +CONFIG_SND_SOC_FSL_RPMSG=m +CONFIG_SND_IMX_SOC=m +CONFIG_SND_SOC_IMX_ES8328=m +CONFIG_SND_SOC_IMX_SGTL5000=m +CONFIG_SND_SOC_FSL_ASOC_CARD=m +CONFIG_SND_SOC_IMX_AUDMIX=m +CONFIG_SND_SOC_IMX_HDMI=m +CONFIG_SND_SOC_IMX_CARD=m +CONFIG_SND_SOC_CHV3_I2S=m +CONFIG_SND_I2S_HI6210_I2S=m +CONFIG_SND_MESON_AXG_SOUND_CARD=m +CONFIG_SND_MESON_GX_SOUND_CARD=m +CONFIG_SND_SOC_QCOM=m +CONFIG_SND_SOC_APQ8016_SBC=m +CONFIG_SND_SOC_QDSP6_USB=m +CONFIG_SND_SOC_MSM8996=m +CONFIG_SND_SOC_SDM845=m +CONFIG_SND_SOC_SC8280XP=m +CONFIG_SND_SOC_SC7180=m +CONFIG_SND_SOC_SC7280=m +CONFIG_SND_SOC_X1E80100=m +CONFIG_SND_SOC_MSIOF=m +CONFIG_SND_SOC_RZ=m +CONFIG_SND_SOC_ROCKCHIP_I2S_TDM=m +CONFIG_SND_SOC_ROCKCHIP_PDM=m +CONFIG_SND_SOC_ROCKCHIP_SAI=m +CONFIG_SND_SOC_ROCKCHIP_SPDIF=m +CONFIG_SND_SOC_ROCKCHIP_MAX98090=m +CONFIG_SND_SOC_ROCKCHIP_RT5645=m +CONFIG_SND_SOC_RK3288_HDMI_ANALOG=m +CONFIG_SND_SOC_RK3399_GRU_SOUND=m +CONFIG_SND_SUN4I_CODEC=m +CONFIG_SND_SUN8I_CODEC=m +CONFIG_SND_SUN8I_CODEC_ANALOG=m +CONFIG_SND_SUN50I_CODEC_ANALOG=m +CONFIG_SND_SUN4I_I2S=m +CONFIG_SND_SUN4I_SPDIF=m +CONFIG_SND_SUN50I_DMIC=m +CONFIG_SND_SOC_TEGRA=m +CONFIG_SND_SOC_TEGRA20_AC97=m +CONFIG_SND_SOC_TEGRA20_I2S=m +CONFIG_SND_SOC_TEGRA20_SPDIF=m +CONFIG_SND_SOC_TEGRA30_I2S=m +CONFIG_SND_SOC_TEGRA210_AHUB=m +CONFIG_SND_SOC_TEGRA210_DMIC=m +CONFIG_SND_SOC_TEGRA210_I2S=m +CONFIG_SND_SOC_TEGRA210_OPE=m +CONFIG_SND_SOC_TEGRA186_ASRC=m +CONFIG_SND_SOC_TEGRA186_DSPK=m +CONFIG_SND_SOC_TEGRA210_ADMAIF=m +CONFIG_SND_SOC_TEGRA210_MVC=m +CONFIG_SND_SOC_TEGRA210_SFC=m +CONFIG_SND_SOC_TEGRA210_AMX=m +CONFIG_SND_SOC_TEGRA210_ADX=m +CONFIG_SND_SOC_TEGRA210_MIXER=m +CONFIG_SND_SOC_TEGRA_AUDIO_GRAPH_CARD=m +CONFIG_SND_SOC_TEGRA_RT5631=m +CONFIG_SND_SOC_TEGRA_RT5640=m +CONFIG_SND_SOC_TEGRA_MAX98090=m +CONFIG_SND_SOC_TEGRA_MAX98088=m +CONFIG_SND_SOC_TEGRA_RT5677=m +CONFIG_SND_SOC_TEGRA_SGTL5000=m +CONFIG_SND_SOC_J721E_EVM=m +CONFIG_SND_SOC_XILINX_I2S=m +CONFIG_SND_SOC_XILINX_AUDIO_FORMATTER=m +CONFIG_SND_SOC_XILINX_SPDIF=m +CONFIG_SND_SOC_SOF_TOPLEVEL=y +CONFIG_SND_SOC_SOF_PCI=m +CONFIG_SND_SOC_SOF_ACPI=m +CONFIG_SND_SOC_SOF_OF=m +CONFIG_SND_SOC_SOF_IMX_TOPLEVEL=y +CONFIG_SND_SOC_SOF_IMX8=m +CONFIG_SND_SOC_SOF_IMX9=m +CONFIG_SND_SOC_SOF_MTK_TOPLEVEL=y +CONFIG_SND_SOC_AC97_CODEC=m +CONFIG_SND_SOC_ADAU1372_I2C=m +CONFIG_SND_SOC_ADAU1372_SPI=m +CONFIG_SND_SOC_ADAU1373=m +CONFIG_SND_SOC_ADAU1761_I2C=m +CONFIG_SND_SOC_ADAU1761_SPI=m +CONFIG_SND_SOC_ADAU7118_HW=m +CONFIG_SND_SOC_ADAU7118_I2C=m +CONFIG_SND_SOC_AK4619=m +CONFIG_SND_SOC_AUDIO_IIO_AUX=m +CONFIG_SND_SOC_AW8738=m +CONFIG_SND_SOC_AW88395=m +CONFIG_SND_SOC_AW88166=m +CONFIG_SND_SOC_AW88261=m +CONFIG_SND_SOC_AW88081=m +CONFIG_SND_SOC_AW87390=m +CONFIG_SND_SOC_AW88399=m +CONFIG_SND_SOC_BD28623=m +CONFIG_SND_SOC_BT_SCO=m +CONFIG_SND_SOC_CHV3_CODEC=m +CONFIG_SND_SOC_CS35L56_SDW=m +CONFIG_SND_SOC_CS40L50=m +CONFIG_SND_SOC_CS42L42=m +CONFIG_SND_SOC_CS42L42_SDW=m +CONFIG_SND_SOC_CS42L43=m +CONFIG_SND_SOC_CS42L43_SDW=m +CONFIG_SND_SOC_CS4234=m +CONFIG_SND_SOC_CS4265=m +CONFIG_SND_SOC_CS4271_I2C=m +CONFIG_SND_SOC_CS42XX8_I2C=m +CONFIG_SND_SOC_CS43130=m +CONFIG_SND_SOC_CS48L32=m +CONFIG_SND_SOC_CS530X_I2C=m +CONFIG_SND_SOC_CX2072X=m +CONFIG_SND_SOC_DA7213=m +CONFIG_SND_SOC_ES7134=m +CONFIG_SND_SOC_ES8311=m +CONFIG_SND_SOC_ES8316=m +CONFIG_SND_SOC_ES8323=m +CONFIG_SND_SOC_ES8326=m +CONFIG_SND_SOC_ES8375=m +CONFIG_SND_SOC_ES8389=m +CONFIG_SND_SOC_HDA=m +CONFIG_SND_SOC_ICS43432=m +CONFIG_SND_SOC_IDT821034=m +CONFIG_SND_SOC_MAX9867=m +CONFIG_SND_SOC_MAX98520=m +CONFIG_SND_SOC_MAX98363=m +CONFIG_SND_SOC_MAX98373_I2C=m +CONFIG_SND_SOC_MAX98373_SDW=m +CONFIG_SND_SOC_MAX98390=m +CONFIG_SND_SOC_MAX98396=m +CONFIG_SND_SOC_MSM8916_WCD_ANALOG=m +CONFIG_SND_SOC_MSM8916_WCD_DIGITAL=m +CONFIG_SND_SOC_PCM1754=m +CONFIG_SND_SOC_PCM1789_I2C=m +CONFIG_SND_SOC_PCM186X_I2C=m +CONFIG_SND_SOC_PCM186X_SPI=m +CONFIG_SND_SOC_PCM3060_I2C=m +CONFIG_SND_SOC_PCM3060_SPI=m +CONFIG_SND_SOC_PCM5102A=m +CONFIG_SND_SOC_PCM512x_I2C=m +CONFIG_SND_SOC_PCM512x_SPI=m +CONFIG_SND_SOC_PCM6240=m +CONFIG_SND_SOC_PM4125_SDW=m +CONFIG_SND_SOC_RK3308=m +CONFIG_SND_SOC_RK3328=m +CONFIG_SND_SOC_RK817=m +CONFIG_SND_SOC_RT1017_SDCA_SDW=m +CONFIG_SND_SOC_RT1318_SDW=m +CONFIG_SND_SOC_RT1320_SDW=m +CONFIG_SND_SOC_RT5575=m +CONFIG_SND_SOC_RT5575_SPI=y +CONFIG_SND_SOC_RT5616=m +CONFIG_SND_SOC_RT5659=m +CONFIG_SND_SOC_RT5682_SDW=m +CONFIG_SND_SOC_RT700_SDW=m +CONFIG_SND_SOC_RT711_SDW=m +CONFIG_SND_SOC_RT711_SDCA_SDW=m +CONFIG_SND_SOC_RT712_SDCA_DMIC_SDW=m +CONFIG_SND_SOC_RT722_SDCA_SDW=m +CONFIG_SND_SOC_RT715_SDW=m +CONFIG_SND_SOC_RT715_SDCA_SDW=m +CONFIG_SND_SOC_RT9123=m +CONFIG_SND_SOC_RT9123P=m +CONFIG_SND_SOC_RTQ9124=m +CONFIG_SND_SOC_RTQ9128=m +CONFIG_SND_SOC_SIMPLE_AMPLIFIER=m +CONFIG_SND_SOC_SIMPLE_MUX=m +CONFIG_SND_SOC_SMA1303=m +CONFIG_SND_SOC_SMA1307=m +CONFIG_SND_SOC_SSM3515=m +CONFIG_SND_SOC_TAS2562=m +CONFIG_SND_SOC_TAS2780=m +CONFIG_SND_SOC_TAS2781_I2C=m +CONFIG_SND_SOC_TAS5805M=m +CONFIG_SND_SOC_TAS6424=m +CONFIG_SND_SOC_TDA7419=m +CONFIG_SND_SOC_TFA989X=m +CONFIG_SND_SOC_TLV320ADC3XXX=m +CONFIG_SND_SOC_TLV320AIC23_I2C=m +CONFIG_SND_SOC_TLV320AIC23_SPI=m +CONFIG_SND_SOC_TLV320AIC32X4_I2C=m +CONFIG_SND_SOC_TLV320AIC32X4_SPI=m +CONFIG_SND_SOC_TLV320AIC3X_I2C=m +CONFIG_SND_SOC_TLV320AIC3X_SPI=m +CONFIG_SND_SOC_TLV320ADCX140=m +CONFIG_SND_SOC_TSCS42XX=m +CONFIG_SND_SOC_UDA1342=m +CONFIG_SND_SOC_WCD9335=m +CONFIG_SND_SOC_WCD934X=m +CONFIG_SND_SOC_WCD937X_SDW=m +CONFIG_SND_SOC_WCD939X_SDW=m +CONFIG_SND_SOC_WM8524=m +CONFIG_SND_SOC_WM8731_I2C=m +CONFIG_SND_SOC_WM8731_SPI=m +CONFIG_SND_SOC_WM8741=m +CONFIG_SND_SOC_WM8753=m +CONFIG_SND_SOC_WM8804_I2C=m +CONFIG_SND_SOC_WM8804_SPI=m +CONFIG_SND_SOC_WM8903=m +CONFIG_SND_SOC_WM8940=m +CONFIG_SND_SOC_WM8960=m +CONFIG_SND_SOC_WM8961=m +CONFIG_SND_SOC_WM8962=m +CONFIG_SND_SOC_WSA883X=m +CONFIG_SND_SOC_WSA884X=m +CONFIG_SND_SOC_ZL38060=m +CONFIG_SND_SOC_MAX9759=m +CONFIG_SND_SOC_MT6357=m +CONFIG_SND_SOC_NAU8824=m +CONFIG_SND_SOC_NTP8918=m +CONFIG_SND_SOC_NTP8835=m +CONFIG_SND_SOC_TPA6130A2=m +CONFIG_SND_SOC_LPASS_WSA_MACRO=m +CONFIG_SND_SOC_LPASS_VA_MACRO=m +CONFIG_SND_AUDIO_GRAPH_CARD2=m +CONFIG_SND_AUDIO_GRAPH_CARD2_CUSTOM_SAMPLE=m +CONFIG_SND_VIRTIO=m +CONFIG_HID_BATTERY_STRENGTH=y +CONFIG_HIDRAW=y +CONFIG_UHID=m +CONFIG_HID_HAPTIC=y +CONFIG_HID_A4TECH=m +CONFIG_HID_ACCUTOUCH=m +CONFIG_HID_ACRUX=m +CONFIG_HID_ACRUX_FF=y +CONFIG_HID_APPLE=m +CONFIG_HID_APPLE_MTP_HAPTIC=m +CONFIG_HID_APPLEIR=m +CONFIG_HID_AUREAL=m +CONFIG_HID_BELKIN=m +CONFIG_HID_BETOP_FF=m +CONFIG_HID_BIGBEN_FF=m +CONFIG_HID_CHERRY=m +CONFIG_HID_CHICONY=m +CONFIG_HID_CORSAIR=m +CONFIG_HID_COUGAR=m +CONFIG_HID_MACALLY=m +CONFIG_HID_PRODIKEYS=m +CONFIG_HID_CMEDIA=m +CONFIG_HID_CP2112=m +CONFIG_HID_CREATIVE_SB0540=m +CONFIG_HID_CYPRESS=m +CONFIG_HID_DRAGONRISE=m +CONFIG_DRAGONRISE_FF=y +CONFIG_HID_EMS_FF=m +CONFIG_HID_ELAN=m +CONFIG_HID_ELECOM=m +CONFIG_HID_ELO=m +CONFIG_HID_EVISION=m +CONFIG_HID_EZKEY=m +CONFIG_HID_FT260=m +CONFIG_HID_GEMBIRD=m +CONFIG_HID_GFRM=m +CONFIG_HID_GLORIOUS=m +CONFIG_HID_HOLTEK=m +CONFIG_HOLTEK_FF=y +CONFIG_HID_GOODIX_SPI=m +CONFIG_HID_GOOGLE_STADIA_FF=m +CONFIG_HID_VIVALDI=m +CONFIG_HID_GT683R=m +CONFIG_HID_KEYTOUCH=m +CONFIG_HID_KYE=m +CONFIG_HID_KYSONA=m +CONFIG_HID_UCLOGIC=m +CONFIG_HID_WALTOP=m +CONFIG_HID_VIEWSONIC=m +CONFIG_HID_XIAOMI=m +CONFIG_HID_GYRATION=m +CONFIG_HID_ICADE=m +CONFIG_HID_ITE=m +CONFIG_HID_JABRA=m +CONFIG_HID_TWINHAN=m +CONFIG_HID_KENSINGTON=m +CONFIG_HID_LCPOWER=m +CONFIG_HID_LENOVO=m +CONFIG_HID_LETSKETCH=m +CONFIG_HID_LOGITECH=m +CONFIG_HID_LOGITECH_DJ=m +CONFIG_LOGITECH_FF=y +CONFIG_LOGIRUMBLEPAD2_FF=y +CONFIG_LOGIG940_FF=y +CONFIG_HID_MAGICMOUSE=m +CONFIG_HID_MALTRON=m +CONFIG_HID_MAYFLASH=m +CONFIG_HID_MEGAWORLD_FF=m +CONFIG_HID_MICROSOFT=m +CONFIG_HID_MONTEREY=m +CONFIG_HID_MULTITOUCH=m +CONFIG_HID_NINTENDO=m +CONFIG_NINTENDO_FF=y +CONFIG_HID_NTI=m +CONFIG_HID_NTRIG=y +CONFIG_HID_NVIDIA_SHIELD=m +CONFIG_NVIDIA_SHIELD_FF=y +CONFIG_HID_ORTEK=m +CONFIG_HID_PANTHERLORD=m +CONFIG_PANTHERLORD_FF=y +CONFIG_HID_PENMOUNT=m +CONFIG_HID_PETALYNX=m +CONFIG_HID_PICOLCD=m +CONFIG_HID_PICOLCD_FB=y +CONFIG_HID_PICOLCD_BACKLIGHT=y +CONFIG_HID_PICOLCD_LCD=y +CONFIG_HID_PICOLCD_LEDS=y +CONFIG_HID_PLANTRONICS=m +CONFIG_HID_PLAYSTATION=m +CONFIG_PLAYSTATION_FF=y +CONFIG_HID_PXRC=m +CONFIG_HID_RAPOO=m +CONFIG_HID_RAZER=m +CONFIG_HID_PRIMAX=m +CONFIG_HID_RETRODE=m +CONFIG_HID_ROCCAT=m +CONFIG_HID_SAITEK=m +CONFIG_HID_SAMSUNG=m +CONFIG_HID_SEMITEK=m +CONFIG_HID_SIGMAMICRO=m +CONFIG_HID_SONY=m +CONFIG_SONY_FF=y +CONFIG_HID_SPEEDLINK=m +CONFIG_HID_STEAM=m +CONFIG_STEAM_FF=y +CONFIG_HID_STEELSERIES=m +CONFIG_HID_SUNPLUS=m +CONFIG_HID_RMI=m +CONFIG_HID_GREENASIA=m +CONFIG_GREENASIA_FF=y +CONFIG_HID_HYPERV_MOUSE=m +CONFIG_HID_SMARTJOYPLUS=m +CONFIG_SMARTJOYPLUS_FF=y +CONFIG_HID_TIVO=m +CONFIG_HID_TOPSEED=m +CONFIG_HID_TOPRE=m +CONFIG_HID_THINGM=m +CONFIG_HID_THRUSTMASTER=m +CONFIG_THRUSTMASTER_FF=y +CONFIG_HID_UDRAW_PS3=m +CONFIG_HID_U2FZERO=m +CONFIG_HID_UNIVERSAL_PIDFF=m +CONFIG_HID_WACOM=m +CONFIG_HID_WIIMOTE=m +CONFIG_HID_WINWING=m +CONFIG_HID_XINMO=m +CONFIG_HID_ZEROPLUS=m +CONFIG_ZEROPLUS_FF=y +CONFIG_HID_ZYDACRON=m +CONFIG_HID_SENSOR_HUB=m +CONFIG_HID_ALPS=m +CONFIG_HID_MCP2221=m +CONFIG_HID_BPF=y +CONFIG_I2C_HID_ACPI=m +CONFIG_I2C_HID_OF=y +CONFIG_I2C_HID_OF_ELAN=m +CONFIG_I2C_HID_OF_GOODIX=m +CONFIG_SURFACE_HID=m +CONFIG_SURFACE_KBD=m +CONFIG_HID_PID=y +CONFIG_USB_HIDDEV=y +CONFIG_SPI_HID_APPLE_OF=m +CONFIG_HID_DOCKCHANNEL=m +CONFIG_USB_LED_TRIG=y +CONFIG_USB=y +CONFIG_USB_PCI_AMD=y +CONFIG_USB_ANNOUNCE_NEW_DEVICES=y +CONFIG_USB_OTG=y +CONFIG_USB_OTG_FSM=m +CONFIG_USB_LEDS_TRIGGER_USBPORT=m +CONFIG_USB_MON=y +CONFIG_USB_XHCI_HCD=y +CONFIG_USB_XHCI_DBGCAP=y +CONFIG_USB_XHCI_PCI_RENESAS=y +CONFIG_USB_XHCI_MVEBU=m +CONFIG_USB_XHCI_RZV2M=y +CONFIG_USB_XHCI_SIDEBAND=y +CONFIG_USB_XHCI_TEGRA=m +CONFIG_USB_EHCI_HCD=y +CONFIG_USB_EHCI_FSL=m +CONFIG_USB_EHCI_HCD_ORION=m +CONFIG_USB_EHCI_TEGRA=m +CONFIG_USB_EHCI_HCD_PLATFORM=m +CONFIG_USB_OHCI_HCD=m +CONFIG_USB_OHCI_HCD_PLATFORM=m +CONFIG_USB_UHCI_HCD=m +CONFIG_USB_SL811_HCD=m +CONFIG_USB_SL811_HCD_ISO=y +CONFIG_USB_PRINTER=m +CONFIG_USB_TMC=m +CONFIG_USB_STORAGE=m +CONFIG_USB_STORAGE_REALTEK=m +CONFIG_USB_STORAGE_DATAFAB=m +CONFIG_USB_STORAGE_FREECOM=m +CONFIG_USB_STORAGE_ISD200=m +CONFIG_USB_STORAGE_USBAT=m +CONFIG_USB_STORAGE_SDDR09=m +CONFIG_USB_STORAGE_SDDR55=m +CONFIG_USB_STORAGE_JUMPSHOT=m +CONFIG_USB_STORAGE_ALAUDA=m +CONFIG_USB_STORAGE_ONETOUCH=m +CONFIG_USB_STORAGE_KARMA=m +CONFIG_USB_STORAGE_CYPRESS_ATACB=m +CONFIG_USB_STORAGE_ENE_UB6250=m +CONFIG_USB_UAS=m +CONFIG_USB_MDC800=m +CONFIG_USB_MICROTEK=m +CONFIG_USBIP_CORE=m +CONFIG_USBIP_VHCI_HCD=m +CONFIG_USBIP_HOST=m +CONFIG_USBIP_VUDC=m +CONFIG_USB_CDNS_SUPPORT=m +CONFIG_USB_CDNS3=m +CONFIG_USB_CDNS3_HOST=y +CONFIG_USB_CDNS3_GADGET=y +CONFIG_USB_MUSB_HDRC=m +CONFIG_USB_MUSB_SUNXI=m +CONFIG_USB_DWC3=m +CONFIG_USB_DWC3_ULPI=y +CONFIG_USB_DWC2=m +CONFIG_USB_DWC2_PCI=m +CONFIG_USB_CHIPIDEA_UDC=y +CONFIG_USB_ISP1760=m +CONFIG_USB_SERIAL=y +CONFIG_USB_SERIAL_CONSOLE=y +CONFIG_USB_SERIAL_GENERIC=y +CONFIG_USB_SERIAL_SIMPLE=m +CONFIG_USB_SERIAL_AIRCABLE=m +CONFIG_USB_SERIAL_ARK3116=m +CONFIG_USB_SERIAL_BELKIN=m +CONFIG_USB_SERIAL_CH341=m +CONFIG_USB_SERIAL_WHITEHEAT=m +CONFIG_USB_SERIAL_DIGI_ACCELEPORT=m +CONFIG_USB_SERIAL_CP210X=m +CONFIG_USB_SERIAL_CYPRESS_M8=m +CONFIG_USB_SERIAL_EMPEG=m +CONFIG_USB_SERIAL_FTDI_SIO=m +CONFIG_USB_SERIAL_VISOR=m +CONFIG_USB_SERIAL_IPAQ=m +CONFIG_USB_SERIAL_IR=m +CONFIG_USB_SERIAL_EDGEPORT=m +CONFIG_USB_SERIAL_EDGEPORT_TI=m +CONFIG_USB_SERIAL_F81232=m +CONFIG_USB_SERIAL_F8153X=m +CONFIG_USB_SERIAL_GARMIN=m +CONFIG_USB_SERIAL_IPW=m +CONFIG_USB_SERIAL_IUU=m +CONFIG_USB_SERIAL_KEYSPAN_PDA=m +CONFIG_USB_SERIAL_KEYSPAN=m +CONFIG_USB_SERIAL_KLSI=m +CONFIG_USB_SERIAL_KOBIL_SCT=m +CONFIG_USB_SERIAL_MCT_U232=m +CONFIG_USB_SERIAL_MOS7720=m +CONFIG_USB_SERIAL_MOS7840=m +CONFIG_USB_SERIAL_NAVMAN=m +CONFIG_USB_SERIAL_PL2303=m +CONFIG_USB_SERIAL_OTI6858=m +CONFIG_USB_SERIAL_QCAUX=m +CONFIG_USB_SERIAL_QUALCOMM=m +CONFIG_USB_SERIAL_SPCP8X5=m +CONFIG_USB_SERIAL_SAFE=m +CONFIG_USB_SERIAL_SAFE_PADDED=y +CONFIG_USB_SERIAL_SIERRAWIRELESS=m +CONFIG_USB_SERIAL_SYMBOL=m +CONFIG_USB_SERIAL_TI=m +CONFIG_USB_SERIAL_CYBERJACK=m +CONFIG_USB_SERIAL_OPTION=m +CONFIG_USB_SERIAL_OMNINET=m +CONFIG_USB_SERIAL_OPTICON=m +CONFIG_USB_SERIAL_XSENS_MT=m +CONFIG_USB_SERIAL_SSU100=m +CONFIG_USB_SERIAL_QT2=m +CONFIG_USB_SERIAL_UPD78F0730=m +CONFIG_USB_SERIAL_XR=m +CONFIG_USB_SERIAL_DEBUG=m +CONFIG_USB_VL122_HUB=m +CONFIG_USB_EMI62=m +CONFIG_USB_EMI26=m +CONFIG_USB_ADUTUX=m +CONFIG_USB_SEVSEG=m +CONFIG_USB_LEGOTOWER=m +CONFIG_USB_LCD=m +CONFIG_USB_IDMOUSE=m +CONFIG_USB_APPLEDISPLAY=m +CONFIG_USB_QCOM_EUD=m +CONFIG_APPLE_MFI_FASTCHARGE=m +CONFIG_USB_SISUSBVGA=m +CONFIG_USB_LD=m +CONFIG_USB_TRANCEVIBRATOR=m +CONFIG_USB_IOWARRIOR=m +CONFIG_USB_ISIGHTFW=m +CONFIG_USB_YUREX=m +CONFIG_USB_HUB_USB251XB=m +CONFIG_USB_HSIC_USB3503=m +CONFIG_USB_HSIC_USB4604=m +CONFIG_USB_CHAOSKEY=m +CONFIG_USB_ONBOARD_DEV=m +CONFIG_USB_ONBOARD_DEV_USB5744=y +CONFIG_USB_ATM=m +CONFIG_USB_CXACRU=m +CONFIG_USB_UEAGLEATM=m +CONFIG_USB_XUSBATM=m +CONFIG_USB_GPIO_VBUS=m +CONFIG_USB_GADGET_VBUS_DRAW=100 +CONFIG_U_SERIAL_CONSOLE=y +CONFIG_USB_RZV2M_USB3DRD=m +CONFIG_USB_SNP_UDC_PLAT=m +CONFIG_USB_MAX3420_UDC=m +CONFIG_USB_TEGRA_XUDC=m +CONFIG_USB_CDNS2_UDC=m +CONFIG_USB_CONFIGFS=m +CONFIG_USB_CONFIGFS_SERIAL=y +CONFIG_USB_CONFIGFS_ACM=y +CONFIG_USB_CONFIGFS_NCM=y +CONFIG_USB_CONFIGFS_ECM=y +CONFIG_USB_CONFIGFS_ECM_SUBSET=y +CONFIG_USB_CONFIGFS_EEM=y +CONFIG_USB_CONFIGFS_MASS_STORAGE=y +CONFIG_USB_CONFIGFS_F_FS=y +CONFIG_USB_CONFIGFS_F_MIDI2=y +CONFIG_USB_CONFIGFS_F_HID=y +CONFIG_USB_CONFIGFS_F_TCM=y +CONFIG_TYPEC=m +CONFIG_TYPEC_TCPM=m +CONFIG_TYPEC_TCPCI=m +CONFIG_TYPEC_TCPCI_MAXIM=m +CONFIG_TYPEC_FUSB302=m +CONFIG_TYPEC_QCOM_PMIC=m +CONFIG_TYPEC_UCSI=m +CONFIG_UCSI_CCG=m +CONFIG_UCSI_ACPI=m +CONFIG_UCSI_STM32G0=m +CONFIG_UCSI_PMIC_GLINK=m +CONFIG_UCSI_LENOVO_YOGA_C630=m +CONFIG_TYPEC_TPS6598X=m +CONFIG_TYPEC_SN201202X=m +CONFIG_TYPEC_TPS6598X_DEBUG_COMMANDS=y +CONFIG_TYPEC_ANX7411=m +CONFIG_TYPEC_RT1719=m +CONFIG_TYPEC_HD3SS3220=m +CONFIG_TYPEC_STUSB160X=m +CONFIG_TYPEC_WUSB3801=m +CONFIG_TYPEC_MUX_FSA4480=m +CONFIG_TYPEC_MUX_GPIO_SBU=m +CONFIG_TYPEC_MUX_PI3USB30532=m +CONFIG_TYPEC_MUX_IT5205=m +CONFIG_TYPEC_MUX_NB7VPQ904M=m +CONFIG_TYPEC_MUX_PS883X=m +CONFIG_TYPEC_MUX_PTN36502=m +CONFIG_TYPEC_MUX_TUSB1046=m +CONFIG_TYPEC_DP_ALTMODE=m +CONFIG_TYPEC_NVIDIA_ALTMODE=m +CONFIG_TYPEC_TBT_ALTMODE=m +CONFIG_USB_ROLE_SWITCH=y +CONFIG_MMC=m +CONFIG_PWRSEQ_SD8787=m +CONFIG_SDIO_UART=m +CONFIG_MMC_ARMMMCI=m +# CONFIG_MMC_STM32_SDMMC is not set +CONFIG_MMC_SDHCI=m +CONFIG_MMC_SDHCI_PCI=m +CONFIG_MMC_SDHCI_ACPI=m +CONFIG_MMC_SDHCI_PLTFM=m +CONFIG_MMC_SDHCI_OF_ARASAN=m +CONFIG_MMC_SDHCI_OF_ESDHC=m +CONFIG_MMC_SDHCI_OF_DWCMSHC=m +CONFIG_MMC_SDHCI_CADENCE=m +CONFIG_MMC_SDHCI_ESDHC_IMX=m +CONFIG_MMC_SDHCI_TEGRA=m +CONFIG_MMC_SDHCI_PXAV3=m +CONFIG_MMC_SDHCI_F_SDH30=m +CONFIG_MMC_SDHCI_IPROC=m +CONFIG_MMC_MESON_GX=m +CONFIG_MMC_MESON_MX_SDIO=m +CONFIG_MMC_ALCOR=m +CONFIG_MMC_SDHCI_MSM=m +CONFIG_MMC_TIFM_SD=m +CONFIG_MMC_SPI=m +CONFIG_MMC_SDHI=m +CONFIG_MMC_CB710=m +CONFIG_MMC_VIA_SDMMC=m +CONFIG_MMC_CAVIUM_THUNDERX=m +CONFIG_MMC_DW=m +CONFIG_MMC_DW_BLUEFIELD=m +CONFIG_MMC_DW_EXYNOS=m +CONFIG_MMC_DW_HI3798CV200=m +CONFIG_MMC_DW_HI3798MV200=m +CONFIG_MMC_DW_K3=m +CONFIG_MMC_DW_PCI=m +CONFIG_MMC_DW_ROCKCHIP=m +CONFIG_MMC_VUB300=m +CONFIG_MMC_USHC=m +CONFIG_MMC_REALTEK_PCI=m +CONFIG_MMC_REALTEK_USB=m +CONFIG_MMC_SUNXI=m +CONFIG_MMC_HSQ=m +CONFIG_MMC_BCM2835=m +CONFIG_MMC_SDHCI_BRCMSTB=m +CONFIG_MMC_SDHCI_XENON=m +CONFIG_MMC_SDHCI_AM654=m +CONFIG_SCSI_UFSHCD=m +CONFIG_SCSI_UFS_BSG=y +CONFIG_SCSI_UFS_CRYPTO=y +CONFIG_SCSI_UFS_HWMON=y +CONFIG_SCSI_UFSHCD_PCI=m +CONFIG_SCSI_UFSHCD_PLATFORM=m +CONFIG_SCSI_UFS_CDNS_PLATFORM=m +CONFIG_SCSI_UFS_QCOM=m +CONFIG_SCSI_UFS_HISI=m +CONFIG_SCSI_UFS_TI_J721E=m +CONFIG_SCSI_UFS_ROCKCHIP=m +CONFIG_SCSI_UFS_AMD_VERSAL2=m +CONFIG_MEMSTICK=m +CONFIG_MSPRO_BLOCK=m +CONFIG_MEMSTICK_TIFM_MS=m +CONFIG_MEMSTICK_JMICRON_38X=m +CONFIG_MEMSTICK_R592=m +CONFIG_MEMSTICK_REALTEK_USB=m +CONFIG_LEDS_CLASS=y +CONFIG_LEDS_CLASS_FLASH=m +CONFIG_LEDS_BRIGHTNESS_HW_CHANGED=y +CONFIG_LEDS_AN30259A=m +CONFIG_LEDS_OSRAM_AMS_AS3668=m +CONFIG_LEDS_AW200XX=m +CONFIG_LEDS_CR0014114=m +CONFIG_LEDS_LM3530=m +CONFIG_LEDS_LM3532=m +CONFIG_LEDS_LM3692X=m +CONFIG_LEDS_PCA9532=m +CONFIG_LEDS_PCA9532_GPIO=y +CONFIG_LEDS_GPIO=m +CONFIG_LEDS_LP3944=m +CONFIG_LEDS_LP3952=m +CONFIG_LEDS_LP50XX=m +CONFIG_LEDS_LP8864=m +CONFIG_LEDS_PCA963X=m +CONFIG_LEDS_PCA995X=m +CONFIG_LEDS_QNAP_MCU=m +CONFIG_LEDS_PWM=m +CONFIG_LEDS_REGULATOR=m +CONFIG_LEDS_LT3593=m +CONFIG_LEDS_MAX5970=m +CONFIG_LEDS_TLC591XX=m +CONFIG_LEDS_MAX77650=m +CONFIG_LEDS_MAX77705=m +CONFIG_LEDS_IS31FL32XX=m +CONFIG_LEDS_BLINKM=m +CONFIG_LEDS_BLINKM_MULTICOLOR=y +CONFIG_LEDS_SYSCON=y +CONFIG_LEDS_MLXREG=m +CONFIG_LEDS_USER=m +CONFIG_LEDS_ST1202=m +CONFIG_LEDS_AS3645A=m +CONFIG_LEDS_LM3601X=m +CONFIG_LEDS_QCOM_FLASH=m +CONFIG_LEDS_SGM3140=m +CONFIG_LEDS_SY7802=m +CONFIG_LEDS_TPS6131X=m +CONFIG_LEDS_GROUP_MULTICOLOR=m +CONFIG_LEDS_KTD202X=m +CONFIG_LEDS_LP5812=m +CONFIG_LEDS_NCP5623=m +CONFIG_LEDS_PWM_MULTICOLOR=m +CONFIG_LEDS_QCOM_LPG=m +CONFIG_LEDS_TRIGGER_ONESHOT=m +CONFIG_LEDS_TRIGGER_DISK=y +CONFIG_LEDS_TRIGGER_MTD=y +CONFIG_LEDS_TRIGGER_HEARTBEAT=m +CONFIG_LEDS_TRIGGER_BACKLIGHT=m +CONFIG_LEDS_TRIGGER_CPU=y +CONFIG_LEDS_TRIGGER_ACTIVITY=m +CONFIG_LEDS_TRIGGER_GPIO=m +CONFIG_LEDS_TRIGGER_DEFAULT_ON=m +CONFIG_LEDS_TRIGGER_TRANSIENT=m +CONFIG_LEDS_TRIGGER_CAMERA=m +CONFIG_LEDS_TRIGGER_PANIC=y +CONFIG_LEDS_TRIGGER_NETDEV=m +CONFIG_LEDS_TRIGGER_TTY=m +CONFIG_LEDS_TRIGGER_INPUT_EVENTS=m +CONFIG_ACCESSIBILITY=y +CONFIG_A11Y_BRAILLE_CONSOLE=y +CONFIG_SPEAKUP=m +CONFIG_SPEAKUP_SYNTH_ACNTSA=m +CONFIG_SPEAKUP_SYNTH_APOLLO=m +CONFIG_SPEAKUP_SYNTH_AUDPTR=m +CONFIG_SPEAKUP_SYNTH_BNS=m +CONFIG_SPEAKUP_SYNTH_DECTLK=m +CONFIG_SPEAKUP_SYNTH_LTLK=m +CONFIG_SPEAKUP_SYNTH_SOFT=m +CONFIG_SPEAKUP_SYNTH_SPKOUT=m +CONFIG_SPEAKUP_SYNTH_TXPRT=m +CONFIG_INFINIBAND=m +CONFIG_INFINIBAND_USER_MAD=m +CONFIG_INFINIBAND_USER_ACCESS=m +CONFIG_INFINIBAND_BNG_RE=m +CONFIG_INFINIBAND_CXGB4=m +CONFIG_INFINIBAND_EFA=m +CONFIG_INFINIBAND_ERDMA=m +CONFIG_INFINIBAND_IONIC=m +CONFIG_INFINIBAND_IRDMA=m +CONFIG_MANA_INFINIBAND=m +CONFIG_MLX4_INFINIBAND=m +CONFIG_MLX5_INFINIBAND=m +CONFIG_INFINIBAND_MTHCA=m +CONFIG_INFINIBAND_OCRDMA=m +CONFIG_INFINIBAND_QEDR=m +CONFIG_RDMA_RXE=m +CONFIG_RDMA_SIW=m +CONFIG_INFINIBAND_IPOIB=m +CONFIG_INFINIBAND_IPOIB_CM=y +CONFIG_INFINIBAND_IPOIB_DEBUG_DATA=y +CONFIG_INFINIBAND_SRP=m +CONFIG_INFINIBAND_SRPT=m +CONFIG_INFINIBAND_ISER=m +CONFIG_INFINIBAND_ISERT=m +CONFIG_INFINIBAND_RTRS_CLIENT=m +CONFIG_INFINIBAND_RTRS_SERVER=m +CONFIG_EDAC=y +CONFIG_EDAC_GHES=y +CONFIG_EDAC_SCRUB=y +CONFIG_EDAC_ECS=y +CONFIG_EDAC_MEM_REPAIR=y +CONFIG_EDAC_LAYERSCAPE=m +CONFIG_EDAC_THUNDERX=m +CONFIG_EDAC_SYNOPSYS=m +CONFIG_EDAC_XGENE=m +CONFIG_EDAC_QCOM=m +CONFIG_EDAC_BLUEFIELD=m +CONFIG_EDAC_DMC520=m +CONFIG_EDAC_ZYNQMP=m +CONFIG_EDAC_VERSAL=m +CONFIG_EDAC_CORTEX_A72=m +CONFIG_EDAC_APPLE_SOC=m +CONFIG_EDAC_VERSALNET=m +CONFIG_RTC_CLASS=y +CONFIG_RTC_DRV_ABEOZ9=m +CONFIG_RTC_DRV_ABX80X=m +CONFIG_RTC_DRV_AC100=m +CONFIG_RTC_DRV_AS3722=m +CONFIG_RTC_DRV_DS1307=m +CONFIG_RTC_DRV_DS1374=m +CONFIG_RTC_DRV_DS1374_WDT=y +CONFIG_RTC_DRV_DS1672=m +CONFIG_RTC_DRV_HYM8563=m +CONFIG_RTC_DRV_MAX6900=m +CONFIG_RTC_DRV_MAX31335=m +CONFIG_RTC_DRV_MAX77686=m +CONFIG_RTC_DRV_NVIDIA_VRS10=m +CONFIG_RTC_DRV_NCT3018Y=m +CONFIG_RTC_DRV_RK808=m +CONFIG_RTC_DRV_RS5C372=m +CONFIG_RTC_DRV_ISL1208=m +CONFIG_RTC_DRV_ISL12022=m +CONFIG_RTC_DRV_ISL12026=m +CONFIG_RTC_DRV_X1205=m +CONFIG_RTC_DRV_PCF8523=m +CONFIG_RTC_DRV_PCF85363=m +CONFIG_RTC_DRV_PCF8563=m +CONFIG_RTC_DRV_PCF8583=m +CONFIG_RTC_DRV_M41T80=m +CONFIG_RTC_DRV_M41T80_WDT=y +CONFIG_RTC_DRV_BQ32K=m +CONFIG_RTC_DRV_S35390A=m +CONFIG_RTC_DRV_FM3130=m +CONFIG_RTC_DRV_RX8010=m +CONFIG_RTC_DRV_RX8581=m +CONFIG_RTC_DRV_RX8025=m +CONFIG_RTC_DRV_EM3027=m +CONFIG_RTC_DRV_RV3028=m +CONFIG_RTC_DRV_RV3032=m +CONFIG_RTC_DRV_RV8803=m +CONFIG_RTC_DRV_SD3078=m +CONFIG_RTC_DRV_M41T93=m +CONFIG_RTC_DRV_M41T94=m +CONFIG_RTC_DRV_DS1305=m +CONFIG_RTC_DRV_DS1343=m +CONFIG_RTC_DRV_DS1347=m +CONFIG_RTC_DRV_DS1390=m +CONFIG_RTC_DRV_MAX6916=m +CONFIG_RTC_DRV_R9701=m +CONFIG_RTC_DRV_RX4581=m +CONFIG_RTC_DRV_RS5C348=m +CONFIG_RTC_DRV_MAX6902=m +CONFIG_RTC_DRV_PCF2123=m +CONFIG_RTC_DRV_MCP795=m +CONFIG_RTC_DRV_DS3232=m +# CONFIG_RTC_DRV_DS3232_HWMON is not set +CONFIG_RTC_DRV_PCF2127=m +CONFIG_RTC_DRV_PCF85063=m +CONFIG_RTC_DRV_RV3029C2=m +CONFIG_RTC_DRV_DS1286=m +CONFIG_RTC_DRV_DS1511=m +CONFIG_RTC_DRV_DS1553=m +CONFIG_RTC_DRV_DS1685_FAMILY=m +CONFIG_RTC_DRV_DS1742=m +CONFIG_RTC_DRV_DS2404=m +CONFIG_RTC_DRV_EFI=y +CONFIG_RTC_DRV_STK17TA8=m +CONFIG_RTC_DRV_M48T35=m +CONFIG_RTC_DRV_M48T59=m +CONFIG_RTC_DRV_MSM6242=m +CONFIG_RTC_DRV_RP5C01=m +CONFIG_RTC_DRV_OPTEE=m +CONFIG_RTC_DRV_ZYNQMP=m +CONFIG_RTC_DRV_CROS_EC=m +CONFIG_RTC_DRV_FSL_FTM_ALARM=m +CONFIG_RTC_DRV_PL031=y +CONFIG_RTC_DRV_SUN6I=y +CONFIG_RTC_DRV_MV=m +CONFIG_RTC_DRV_ARMADA38X=m +CONFIG_RTC_DRV_CADENCE=m +CONFIG_RTC_DRV_PM8XXX=m +CONFIG_RTC_DRV_TEGRA=m +CONFIG_RTC_DRV_SNVS=m +CONFIG_RTC_DRV_BBNSM=m +CONFIG_RTC_DRV_IMX_BBM_SCMI=m +CONFIG_RTC_DRV_IMX_SC=m +CONFIG_RTC_DRV_XGENE=m +CONFIG_RTC_DRV_R7301=m +CONFIG_RTC_DRV_TI_K3=m +CONFIG_RTC_DRV_APPLE_PMU=y +CONFIG_RTC_DRV_MACSMC=y +CONFIG_RTC_DRV_S32G=m +CONFIG_DMADEVICES=y +CONFIG_ALTERA_MSGDMA=m +CONFIG_APPLE_SIO=m +CONFIG_ARM_DMA350=m +CONFIG_AXI_DMAC=m +CONFIG_BCM_SBA_RAID=m +CONFIG_DMA_BCM2835=m +CONFIG_DMA_SUN6I=m +CONFIG_DW_AXI_DMAC=m +CONFIG_FSL_EDMA=m +CONFIG_FSL_QDMA=m +CONFIG_HISI_DMA=m +CONFIG_IMX_SDMA=m +CONFIG_K3_DMA=m +CONFIG_MV_XOR=y +CONFIG_MV_XOR_V2=y +CONFIG_MXS_DMA=y +CONFIG_PL330_DMA=m +CONFIG_TEGRA186_GPC_DMA=m +CONFIG_TEGRA20_APB_DMA=y +CONFIG_TEGRA210_ADMA=m +CONFIG_XILINX_DMA=m +CONFIG_XILINX_XDMA=m +CONFIG_XILINX_ZYNQMP_DMA=m +CONFIG_XILINX_ZYNQMP_DPDMA=m +CONFIG_AMD_QDMA=m +CONFIG_QCOM_BAM_DMA=y +CONFIG_QCOM_GPI_DMA=m +CONFIG_QCOM_HIDMA_MGMT=m +CONFIG_QCOM_HIDMA=m +CONFIG_DW_DMAC=m +CONFIG_DW_DMAC_PCI=m +CONFIG_DW_EDMA=m +CONFIG_DW_EDMA_PCIE=m +CONFIG_RZ_DMAC=y +CONFIG_TI_K3_UDMA=m +CONFIG_TI_K3_UDMA_GLUE_LAYER=m +CONFIG_FSL_DPAA2_QDMA=m +CONFIG_ASYNC_TX_DMA=y +CONFIG_UDMABUF=y +CONFIG_DMABUF_HEAPS=y +CONFIG_DMABUF_HEAPS_SYSTEM=y +CONFIG_DMABUF_HEAPS_CMA=y +CONFIG_UIO_PCI_GENERIC=m +CONFIG_UIO_HV_GENERIC=m +CONFIG_UIO_DFL=m +CONFIG_VFIO=m +CONFIG_VFIO_DEVICE_CDEV=y +CONFIG_VFIO_NOIOMMU=y +CONFIG_VFIO_PCI=m +CONFIG_MLX5_VFIO_PCI=m +CONFIG_PDS_VFIO_PCI=m +CONFIG_VIRTIO_VFIO_PCI=m +CONFIG_NVGRACE_GPU_VFIO_PCI=m +CONFIG_QAT_VFIO_PCI=m +CONFIG_VFIO_PLATFORM=m +CONFIG_VFIO_AMBA=m +CONFIG_VFIO_PLATFORM_AMDXGBE_RESET=m +CONFIG_VFIO_FSL_MC=m +CONFIG_VFIO_CDX=m +CONFIG_VIRT_DRIVERS=y +CONFIG_VBOXGUEST=m +CONFIG_NITRO_ENCLAVES=m +CONFIG_EFI_SECRET=m +CONFIG_ARM_CCA_GUEST=m +CONFIG_VIRTIO_PCI=y +CONFIG_VIRTIO_VDPA=m +CONFIG_VIRTIO_BALLOON=m +CONFIG_VIRTIO_MEM=m +CONFIG_VIRTIO_INPUT=m +CONFIG_VIRTIO_MMIO=m +CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y +CONFIG_VIRTIO_RTC=m +CONFIG_VDPA=m +CONFIG_VDPA_SIM=m +CONFIG_VDPA_SIM_NET=m +CONFIG_VDPA_SIM_BLOCK=m +CONFIG_VDPA_USER=m +CONFIG_IFCVF=m +CONFIG_MLX5_VDPA_NET=m +CONFIG_VP_VDPA=m +CONFIG_SNET_VDPA=m +CONFIG_PDS_VDPA=m +CONFIG_OCTEONEP_VDPA=m +CONFIG_VHOST_NET=m +CONFIG_VHOST_SCSI=m +CONFIG_VHOST_VSOCK=m +CONFIG_VHOST_VDPA=m +CONFIG_HYPERV=y +CONFIG_HYPERV_UTILS=m +CONFIG_HYPERV_BALLOON=m +CONFIG_HYPERV_VMBUS=m +CONFIG_GPIB=m +CONFIG_GPIB_AGILENT_82350B=m +CONFIG_GPIB_AGILENT_82357A=m +CONFIG_GPIB_CEC_PCI=m +CONFIG_GPIB_NI_PCI_ISA=m +CONFIG_GPIB_CB7210=m +CONFIG_GPIB_NI_USB=m +CONFIG_GPIB_FLUKE=m +CONFIG_GPIB_FMH=m +CONFIG_GPIB_GPIO=m +CONFIG_GPIB_INES=m +CONFIG_GPIB_LPVO=m +CONFIG_STAGING=y +CONFIG_RTL8723BS=m +CONFIG_STAGING_MEDIA=y +CONFIG_VIDEO_MAX96712=m +CONFIG_VIDEO_MESON_VDEC=m +CONFIG_VIDEO_SUNXI=y +CONFIG_VIDEO_SUNXI_CEDRUS=m +CONFIG_VIDEO_SUN6I_ISP=m +CONFIG_VIDEO_TEGRA=m +CONFIG_SND_BCM2835=m +CONFIG_CHROME_PLATFORMS=y +CONFIG_CHROMEOS_ACPI=m +CONFIG_CHROMEOS_TBMC=y +CONFIG_CROS_EC=m +CONFIG_CROS_EC_I2C=m +CONFIG_CROS_EC_RPMSG=m +CONFIG_CROS_EC_SPI=m +CONFIG_CROS_EC_UART=m +CONFIG_CROS_KBD_LED_BACKLIGHT=m +# CONFIG_CROS_EC_LIGHTBAR is not set +# CONFIG_CROS_EC_DEBUGFS is not set +CONFIG_CROS_HPS_I2C=m +CONFIG_CHROMEOS_PRIVACY_SCREEN=m +CONFIG_MELLANOX_PLATFORM=y +CONFIG_MLX_PLATFORM=m +CONFIG_MLXREG_DPU=m +CONFIG_MLXREG_HOTPLUG=m +CONFIG_MLXREG_IO=m +CONFIG_MLXREG_LC=m +CONFIG_MLXBF_TMFIFO=m +CONFIG_MLXBF_BOOTCTL=m +CONFIG_MLXBF_PMC=m +CONFIG_SURFACE_ACPI_NOTIFY=m +CONFIG_SURFACE_AGGREGATOR_CDEV=m +CONFIG_SURFACE_AGGREGATOR_HUB=m +CONFIG_SURFACE_AGGREGATOR_REGISTRY=m +CONFIG_SURFACE_AGGREGATOR_TABLET_SWITCH=m +CONFIG_SURFACE_DTX=m +CONFIG_SURFACE_GPE=m +CONFIG_SURFACE_HOTPLUG=m +CONFIG_SURFACE_PLATFORM_PROFILE=m +CONFIG_SURFACE_PRO3_BUTTON=m +CONFIG_SURFACE_AGGREGATOR=m +CONFIG_EC_ACER_ASPIRE1=m +CONFIG_EC_LENOVO_YOGA_C630=m +CONFIG_EC_LENOVO_THINKPAD_T14S=m +CONFIG_BCM_VIDEOCORE=m +CONFIG_BCM2835_VCHIQ_MMAL=m +CONFIG_CLK_ICST=y +CONFIG_CLK_SP810=y +CONFIG_COMMON_CLK_MAX77686=y +CONFIG_COMMON_CLK_RK808=m +CONFIG_COMMON_CLK_SCPI=m +CONFIG_COMMON_CLK_SI5341=m +CONFIG_COMMON_CLK_SI544=m +CONFIG_COMMON_CLK_AXI_CLKGEN=m +CONFIG_COMMON_CLK_PWM=m +CONFIG_COMMON_CLK_RS9_PCIE=m +CONFIG_COMMON_CLK_SI521XX=y +CONFIG_COMMON_CLK_VC3=m +CONFIG_COMMON_CLK_VC7=m +CONFIG_COMMON_CLK_BD718XX=m +CONFIG_CLK_BCM2711_DVP=m +CONFIG_CLK_RASPBERRYPI=y +# CONFIG_COMMON_CLK_HI3516CV300 is not set +CONFIG_COMMON_CLK_HI3519=m +# CONFIG_COMMON_CLK_HI3798CV200 is not set +CONFIG_CLK_IMX8MM=y +CONFIG_CLK_IMX8MN=y +CONFIG_CLK_IMX8MP=y +CONFIG_CLK_IMX8MQ=y +CONFIG_CLK_IMX8QXP=y +CONFIG_CLK_IMX8ULP=y +CONFIG_CLK_IMX93=y +CONFIG_CLK_IMX95_BLK_CTL=m +CONFIG_TI_SCI_CLK=y +CONFIG_TI_SYSCON_CLK=m +CONFIG_COMMON_CLK_AXG_AUDIO=y +CONFIG_COMMON_CLK_T7_PERIPHERALS=m +CONFIG_COMMON_CLK_QCOM=y +CONFIG_CLK_GLYMUR_TCSRCC=y +# CONFIG_CLK_KAANAPALI_CAMCC is not set +# CONFIG_CLK_KAANAPALI_DISPCC is not set +# CONFIG_CLK_KAANAPALI_GCC is not set +# CONFIG_CLK_KAANAPALI_GPUCC is not set +# CONFIG_CLK_KAANAPALI_TCSRCC is not set +# CONFIG_CLK_KAANAPALI_VIDEOCC is not set +CONFIG_QCOM_A53PLL=m +# CONFIG_QCOM_CLK_APCC_MSM8996 is not set +# CONFIG_IPQ_APSS_6018 is not set +CONFIG_IPQ_GCC_5018=m +# CONFIG_IPQ_GCC_5332 is not set +# CONFIG_IPQ_GCC_5424 is not set +# CONFIG_IPQ_GCC_6018 is not set +# CONFIG_IPQ_GCC_8074 is not set +# CONFIG_IPQ_GCC_9574 is not set +CONFIG_IPQ_NSSCC_QCA8K=m +CONFIG_MSM_GCC_8939=m +# CONFIG_MSM_GCC_8953 is not set +# CONFIG_MSM_GCC_8976 is not set +# CONFIG_MSM_MMCC_8994 is not set +# CONFIG_MSM_GCC_8994 is not set +# CONFIG_MSM_MMCC_8998 is not set +CONFIG_QCM_GCC_2290=m +# CONFIG_QCM_DISPCC_2290 is not set +CONFIG_QCS_GCC_404=m +CONFIG_SC_LPASS_CORECC_7180=m +CONFIG_SDM_GCC_660=m +# CONFIG_SDM_MMCC_660 is not set +# CONFIG_SDM_GPUCC_660 is not set +# CONFIG_QDU_GCC_1000 is not set +# CONFIG_QDU_ECPRICC_1000 is not set +CONFIG_SDM_GCC_845=m +# CONFIG_SDX_GCC_75 is not set +# CONFIG_SM_CAMCC_4450 is not set +# CONFIG_SM_CAMCC_6350 is not set +# CONFIG_SM_CAMCC_8150 is not set +# CONFIG_SM_CAMCC_8450 is not set +# CONFIG_SM_CAMCC_8550 is not set +# CONFIG_SM_CAMCC_8750 is not set +# CONFIG_SM_DISPCC_8550 is not set +# CONFIG_SM_GCC_4450 is not set +CONFIG_SM_GCC_6115=m +# CONFIG_SM_GCC_6125 is not set +# CONFIG_SM_GCC_6350 is not set +# CONFIG_SM_GCC_6375 is not set +CONFIG_SM_GCC_7150=m +CONFIG_SM_GCC_8250=m +CONFIG_SM_GCC_8350=m +CONFIG_SM_GCC_8450=m +CONFIG_SM_GCC_8550=m +CONFIG_SM_GCC_8650=m +CONFIG_SM_GCC_8750=m +# CONFIG_SM_GPUCC_4450 is not set +# CONFIG_SM_GPUCC_6125 is not set +# CONFIG_SM_GPUCC_6375 is not set +# CONFIG_SM_GPUCC_6350 is not set +# CONFIG_SM_GPUCC_8150 is not set +# CONFIG_SM_GPUCC_8250 is not set +# CONFIG_SM_GPUCC_8350 is not set +# CONFIG_SM_GPUCC_8450 is not set +# CONFIG_SM_GPUCC_8550 is not set +# CONFIG_SM_LPASSCC_6115 is not set +# CONFIG_SM_TCSRCC_8550 is not set +CONFIG_SM_TCSRCC_8650=m +# CONFIG_SM_TCSRCC_8750 is not set +# CONFIG_SM_VIDEOCC_6350 is not set +# CONFIG_SM_VIDEOCC_8150 is not set +# CONFIG_SM_VIDEOCC_8550 is not set +# CONFIG_SM_VIDEOCC_8750 is not set +CONFIG_SPMI_PMIC_CLKDIV=m +CONFIG_QCOM_HFPLL=m +CONFIG_KPSS_XCC=m +# CONFIG_SM_VIDEOCC_8450 is not set +# CONFIG_CLK_RV1126B is not set +CONFIG_SUN55I_A523_CCU=m +CONFIG_SUN55I_A523_R_CCU=m +CONFIG_XILINX_VCU=m +CONFIG_COMMON_CLK_XLNX_CLKWZRD=m +CONFIG_HWSPINLOCK=y +CONFIG_HWSPINLOCK_OMAP=m +CONFIG_HWSPINLOCK_QCOM=m +CONFIG_HWSPINLOCK_SUN6I=m +CONFIG_TEGRA186_TIMER=y +CONFIG_RENESAS_OSTM=y +CONFIG_NXP_STM_TIMER=y +CONFIG_ARM_MHU=m +CONFIG_ARM_MHU_V2=m +CONFIG_ARM_MHU_V3=m +CONFIG_IMX_MBOX=m +CONFIG_PLATFORM_MHU=m +CONFIG_OMAP2PLUS_MBOX=m +CONFIG_ROCKCHIP_MBOX=y +CONFIG_BCM2835_MBOX=y +CONFIG_QCOM_APCS_IPC=m +CONFIG_TEGRA_HSP_MBOX=y +CONFIG_XGENE_SLIMPRO_MBOX=m +CONFIG_QCOM_CPUCP_MBOX=m +CONFIG_QCOM_IPCC=m +CONFIG_CIX_MBOX=m +CONFIG_IOMMU_DEFAULT_DMA_LAZY=y +CONFIG_ARM_SMMU=y +CONFIG_ARM_SMMU_V3=y +CONFIG_ARM_SMMU_V3_SVA=y +CONFIG_ARM_SMMU_V3_IOMMUFD=y +CONFIG_TEGRA241_CMDQV=y +CONFIG_QCOM_IOMMU=y +CONFIG_IOMMUFD=m +CONFIG_ROCKCHIP_IOMMU=y +CONFIG_SUN50I_IOMMU=y +CONFIG_TEGRA_IOMMU_SMMU=y +CONFIG_APPLE_DART=y +CONFIG_APPLE_DART_J713_DCP=y +CONFIG_VIRTIO_IOMMU=y +CONFIG_IMX_REMOTEPROC=m +CONFIG_IMX_DSP_REMOTEPROC=m +CONFIG_QCOM_Q6V5_ADSP=m +CONFIG_QCOM_Q6V5_MSS=m +CONFIG_QCOM_Q6V5_PAS=m +CONFIG_QCOM_Q6V5_WCSS=m +CONFIG_QCOM_SYSMON=m +CONFIG_QCOM_WCNSS_PIL=m +CONFIG_TI_K3_DSP_REMOTEPROC=m +CONFIG_TI_K3_M4_REMOTEPROC=m +CONFIG_TI_K3_R5_REMOTEPROC=m +CONFIG_XLNX_R5_REMOTEPROC=m +CONFIG_RPMSG_CHAR=m +CONFIG_RPMSG_CTRL=m +CONFIG_RPMSG_QCOM_GLINK_RPM=m +CONFIG_RPMSG_QCOM_GLINK_SMEM=m +CONFIG_RPMSG_QCOM_SMD=m +CONFIG_SOUNDWIRE=m +CONFIG_SOUNDWIRE_QCOM=m +# CONFIG_MESON_CLK_MEASURE is not set +CONFIG_APPLE_DBGVIEW=m +CONFIG_APPLE_DOCKCHANNEL=m +CONFIG_APPLE_PMGR_MISC=y +CONFIG_APPLE_SOC_SLEEP=y +CONFIG_APPLE_RTKIT_HELPER=m +CONFIG_APPLE_SART=m +CONFIG_APPLE_PMP=m +CONFIG_APPLE_REGVIEW=m +CONFIG_FSL_DPAA=y +CONFIG_FSL_MC_DPIO=m +CONFIG_DPAA2_CONSOLE=m +CONFIG_FSL_RCPM=y +CONFIG_A64FX_DIAG=y +CONFIG_SOC_IMX9=m +CONFIG_WPCM450_SOC=m +CONFIG_QCOM_AOSS_QMP=m +CONFIG_QCOM_PMIC_PDCHARGER_ULOG=m +CONFIG_QCOM_RAMP_CTRL=m +CONFIG_QCOM_RPM_MASTER_STATS=m +CONFIG_QCOM_SMEM=m +CONFIG_QCOM_SPM=y +# CONFIG_ARCH_R8A774B1 is not set +# CONFIG_ARCH_R8A774C0 is not set +# CONFIG_ARCH_R8A774E1 is not set +# CONFIG_ARCH_R8A77951 is not set +# CONFIG_ARCH_R8A77960 is not set +# CONFIG_ARCH_R8A77961 is not set +# CONFIG_ARCH_R8A77965 is not set +# CONFIG_ARCH_R8A77970 is not set +# CONFIG_ARCH_R8A77980 is not set +# CONFIG_ARCH_R8A77990 is not set +# CONFIG_ARCH_R8A77995 is not set +# CONFIG_ARCH_R8A779A0 is not set +# CONFIG_ARCH_R8A779F0 is not set +# CONFIG_ARCH_R8A779G0 is not set +# CONFIG_ARCH_R8A779H0 is not set +# CONFIG_ARCH_R9A09G047 is not set +CONFIG_ROCKCHIP_IODOMAIN=m +CONFIG_ROCKCHIP_DTPM=m +CONFIG_SOC_TEGRA_CBB=m +CONFIG_TI_PRUSS=m +CONFIG_RASPBERRYPI_POWER=y +CONFIG_IMX_SCU_PD=y +CONFIG_QCOM_CPR=m +CONFIG_QCOM_RPMHPD=y +CONFIG_QCOM_RPMPD=m +# CONFIG_SUN20I_PPU is not set +CONFIG_SUN50I_H6_PRCM_PPU=m +CONFIG_SUN55I_PCK600=m +CONFIG_TI_SCI_PM_DOMAINS=y +CONFIG_DEVFREQ_GOV_POWERSAVE=m +CONFIG_DEVFREQ_GOV_PASSIVE=m +CONFIG_ARM_HISI_UNCORE_DEVFREQ=m +CONFIG_ARM_IMX_BUS_DEVFREQ=m +CONFIG_ARM_IMX8M_DDRC_DEVFREQ=m +CONFIG_ARM_TEGRA_DEVFREQ=m +CONFIG_ARM_RK3399_DMC_DEVFREQ=m +CONFIG_ARM_SUN8I_A33_MBUS_DEVFREQ=m +CONFIG_EXTCON_ADC_JACK=m +CONFIG_EXTCON_GPIO=m +CONFIG_EXTCON_LC824206XA=m +CONFIG_EXTCON_PTN5150=m +CONFIG_EXTCON_SM5502=m +CONFIG_EXTCON_USB_GPIO=m +CONFIG_EXTCON_USBC_CROS_EC=m +CONFIG_EXTCON_USBC_TUSB320=m +CONFIG_MEMORY=y +CONFIG_ARM_PL172_MPMC=m +CONFIG_OMAP_GPMC=y +CONFIG_FPGA_DFL_EMIF=m +CONFIG_TEGRA210_EMC=m +CONFIG_IIO_BUFFER_HW_CONSUMER=m +CONFIG_IIO_SW_DEVICE=m +CONFIG_IIO_SW_TRIGGER=m +CONFIG_IIO_TRIGGERED_EVENT=m +CONFIG_ADXL313_I2C=m +CONFIG_ADXL313_SPI=m +CONFIG_ADXL355_I2C=m +CONFIG_ADXL355_SPI=m +CONFIG_ADXL367_SPI=m +CONFIG_ADXL367_I2C=m +CONFIG_ADXL372_SPI=m +CONFIG_ADXL372_I2C=m +CONFIG_ADXL380_SPI=m +CONFIG_ADXL380_I2C=m +CONFIG_BMA180=m +CONFIG_BMC150_ACCEL=m +CONFIG_DA280=m +CONFIG_DA311=m +CONFIG_DMARD10=m +CONFIG_HID_SENSOR_ACCEL_3D=m +CONFIG_IIO_CROS_EC_ACCEL_LEGACY=m +CONFIG_IIO_ST_ACCEL_3AXIS=m +CONFIG_IIO_KX022A_SPI=m +CONFIG_IIO_KX022A_I2C=m +CONFIG_KXSD9=m +CONFIG_KXCJK1013=m +CONFIG_MMA7660=m +CONFIG_MMA8452=m +CONFIG_MSA311=m +CONFIG_MXC4005=m +CONFIG_MXC6255=m +CONFIG_SCA3300=m +CONFIG_AD4000=m +CONFIG_AD4030=m +CONFIG_AD4062=m +CONFIG_AD4080=m +CONFIG_AD4130=m +CONFIG_AD4134=m +CONFIG_AD4170_4=m +CONFIG_AD4695=m +CONFIG_AD4851=m +CONFIG_AD7091R8=m +CONFIG_AD7124=m +CONFIG_AD7191=m +CONFIG_AD7292=m +CONFIG_AD7380=m +CONFIG_AD7405=m +CONFIG_AD7625=m +CONFIG_AD7766=m +CONFIG_AD7779=m +CONFIG_AD7949=m +CONFIG_AD9467=m +CONFIG_ADE9000=m +CONFIG_AXP20X_ADC=m +CONFIG_AXP288_ADC=m +CONFIG_DLN2_ADC=m +CONFIG_ENVELOPE_DETECTOR=m +CONFIG_INA2XX_ADC=m +CONFIG_IMX7D_ADC=m +CONFIG_IMX8QXP_ADC=m +CONFIG_IMX93_ADC=m +CONFIG_MAX11205=m +CONFIG_MAX11410=m +CONFIG_MAX1241=m +CONFIG_MAX1363=m +CONFIG_MAX14001=m +CONFIG_MAX34408=m +CONFIG_MCP320X=m +CONFIG_MCP3422=m +CONFIG_MCP3911=m +CONFIG_NXP_SAR_ADC=m +CONFIG_PAC1921=m +CONFIG_PAC1934=m +CONFIG_QCOM_SPMI_RRADC=m +CONFIG_QCOM_SPMI_IADC=m +CONFIG_QCOM_SPMI_VADC=m +CONFIG_QCOM_SPMI_ADC5=m +CONFIG_ROHM_BD79124=m +CONFIG_ROCKCHIP_SARADC=m +CONFIG_RICHTEK_RTQ6056=m +CONFIG_RZG2L_ADC=m +CONFIG_RZT2H_ADC=m +CONFIG_SD_ADC_MODULATOR=m +CONFIG_STMPE_ADC=m +CONFIG_SUN20I_GPADC=m +CONFIG_TI_ADC128S052=m +CONFIG_TI_ADS1015=m +CONFIG_TI_ADS1018=m +CONFIG_TI_ADS1100=m +CONFIG_TI_ADS131E08=m +CONFIG_TI_ADS131M02=m +CONFIG_TI_ADS7138=m +CONFIG_TI_ADS7924=m +CONFIG_TI_ADS8344=m +CONFIG_TI_AM335X_ADC=m +CONFIG_TI_LMP92064=m +CONFIG_TI_TSC2046=m +CONFIG_XILINX_XADC=m +CONFIG_XILINX_AMS=m +CONFIG_AD74115=m +CONFIG_AD74413R=m +CONFIG_IIO_RESCALE=m +CONFIG_ADL8113=m +CONFIG_HMC425=m +CONFIG_BME680=m +CONFIG_PMS7003=m +CONFIG_SCD30_CORE=m +CONFIG_SCD30_I2C=m +CONFIG_SCD30_SERIAL=m +CONFIG_IIO_AOP_SENSOR_LAS=m +CONFIG_IIO_AOP_SENSOR_ALS=m +CONFIG_IIO_AOP_SENSOR_MOTION=m +CONFIG_IIO_AOP_SENSOR_DEVMOTION=m +CONFIG_IIO_AOP_SENSOR_TEMP=m +CONFIG_IIO_CROS_EC_SENSORS_CORE=m +CONFIG_IIO_CROS_EC_SENSORS=m +CONFIG_IIO_CROS_EC_SENSORS_LID_ANGLE=m +CONFIG_IIO_CROS_EC_ACTIVITY=m +CONFIG_IIO_SCMI=m +CONFIG_AD3530R=m +CONFIG_AD3552R_HS=m +CONFIG_AD3552R=m +CONFIG_LTC2688=m +CONFIG_AD5766=m +CONFIG_AD5770R=m +CONFIG_AD7293=m +CONFIG_AD8460=m +CONFIG_BD79703=m +CONFIG_DPOT_DAC=m +CONFIG_LTC1660=m +CONFIG_LTC2664=m +CONFIG_MAX22007=m +CONFIG_MAX5522=m +CONFIG_MCP4728=m +CONFIG_MCP47FEB02=m +CONFIG_MCP4821=m +CONFIG_TI_DAC7311=m +CONFIG_ADF4377=m +CONFIG_ADXRS290=m +CONFIG_FXAS21002C=m +CONFIG_HID_SENSOR_GYRO_3D=m +CONFIG_MPU3050_I2C=m +CONFIG_IIO_ST_GYRO_3AXIS=m +CONFIG_MAX30100=m +CONFIG_DHT11=m +CONFIG_HDC100X=m +CONFIG_HDC2010=m +CONFIG_HID_SENSOR_HUMIDITY=m +CONFIG_HTS221=m +CONFIG_HTU21=m +CONFIG_SI7020=m +CONFIG_ADIS16475=m +CONFIG_ADIS16550=m +CONFIG_BMI160_I2C=m +CONFIG_BMI160_SPI=m +CONFIG_BMI270_I2C=m +CONFIG_BMI270_SPI=m +CONFIG_BOSCH_BNO055_SERIAL=m +CONFIG_BOSCH_BNO055_I2C=m +CONFIG_FXOS8700_I2C=m +CONFIG_FXOS8700_SPI=m +CONFIG_INV_ICM42600_I2C=m +CONFIG_INV_ICM42600_SPI=m +CONFIG_INV_ICM45600_I2C=m +CONFIG_INV_ICM45600_SPI=m +CONFIG_INV_ICM45600_I3C=m +CONFIG_INV_MPU6050_I2C=m +CONFIG_SMI330_I2C=m +CONFIG_SMI330_SPI=m +CONFIG_IIO_ST_LSM6DSX=m +CONFIG_ACPI_ALS=m +CONFIG_ADUX1020=m +CONFIG_AL3000A=m +CONFIG_AL3010=m +CONFIG_APDS9160=m +CONFIG_APDS9306=m +CONFIG_APDS9960=m +CONFIG_BH1745=m +CONFIG_BH1750=m +CONFIG_CM32181=m +CONFIG_CM3605=m +CONFIG_IIO_CROS_EC_LIGHT_PROX=m +CONFIG_GP2AP002=m +CONFIG_SENSORS_ISL29018=m +CONFIG_SENSORS_ISL29028=m +CONFIG_HID_SENSOR_ALS=m +CONFIG_ROHM_BU27034=m +CONFIG_RPR0521=m +CONFIG_LTR501=m +CONFIG_LTRF216A=m +CONFIG_LV0104CS=m +CONFIG_MAX44009=m +CONFIG_OPT3001=m +CONFIG_OPT4001=m +CONFIG_OPT4060=m +CONFIG_PA12203001=m +CONFIG_STK3310=m +CONFIG_ST_UVIS25=m +CONFIG_TCS3472=m +CONFIG_TSL2772=m +CONFIG_TSL4531=m +CONFIG_VCNL4000=m +CONFIG_VCNL4035=m +CONFIG_VEML3235=m +CONFIG_VEML6030=m +CONFIG_VEML6070=m +CONFIG_VL6180=m +CONFIG_ZOPT2201=m +CONFIG_AF8133J=m +CONFIG_AK8975=m +CONFIG_BMC150_MAGN_I2C=m +CONFIG_BMC150_MAGN_SPI=m +CONFIG_MAG3110=m +CONFIG_HID_SENSOR_MAGNETOMETER_3D=m +CONFIG_MMC5633=m +CONFIG_IIO_ST_MAGN_3AXIS=m +CONFIG_SENSORS_RM3100_I2C=m +CONFIG_SENSORS_RM3100_SPI=m +CONFIG_IIO_MUX=m +CONFIG_HID_SENSOR_INCLINOMETER_3D=m +CONFIG_HID_SENSOR_DEVICE_ROTATION=m +CONFIG_IIO_TIGHTLOOP_TRIGGER=m +CONFIG_IIO_SYSFS_TRIGGER=m +CONFIG_HID_SENSOR_CUSTOM_INTEL_HINGE=m +CONFIG_AD5110=m +CONFIG_AD5272=m +CONFIG_MCP4018=m +CONFIG_MCP41010=m +CONFIG_X9250=m +CONFIG_LMP91000=m +CONFIG_ABP060MG=m +CONFIG_ABP2030PA_I2C=m +CONFIG_ABP2030PA_SPI=m +CONFIG_BMP280=m +CONFIG_IIO_CROS_EC_BARO=m +CONFIG_ICP10100=m +CONFIG_MPL115_I2C=m +CONFIG_MPRLS0025PA_I2C=m +CONFIG_MPRLS0025PA_SPI=m +CONFIG_IIO_ST_PRESS=m +CONFIG_CROS_EC_MKBP_PROXIMITY=m +CONFIG_D3323AA=m +CONFIG_MB1232=m +CONFIG_SX9310=m +CONFIG_SX9324=m +CONFIG_SX9360=m +CONFIG_VCNL3020=m +CONFIG_VL53L0X_I2C=m +CONFIG_LTC2983=m +CONFIG_MAXIM_THERMOCOUPLE=m +CONFIG_HID_SENSOR_TEMP=m +CONFIG_MLX90614=m +CONFIG_MLX90632=m +CONFIG_TMP006=m +CONFIG_TMP117=m +CONFIG_MAX30208=m +CONFIG_MAX31856=m +CONFIG_MAX31865=m +CONFIG_MCP9600=m +CONFIG_PWM=y +CONFIG_PWM_PROVIDE_GPIO=y +CONFIG_PWM_ADP5585=m +CONFIG_PWM_APPLE=m +CONFIG_PWM_ARGON_FAN_HAT=m +CONFIG_PWM_AXI_PWMGEN=m +CONFIG_PWM_BCM2835=m +CONFIG_PWM_CLK=m +CONFIG_PWM_CROS_EC=m +CONFIG_PWM_DWC=m +CONFIG_PWM_GPIO=m +CONFIG_PWM_HIBVT=m +CONFIG_PWM_IMX27=m +CONFIG_PWM_IMX_TPM=m +CONFIG_PWM_MC33XS2410=m +CONFIG_PWM_MESON=m +CONFIG_PWM_OMAP_DMTIMER=m +CONFIG_PWM_PCA9685=m +CONFIG_PWM_RASPBERRYPI_POE=m +CONFIG_PWM_RENESAS_RZG2L_GPT=m +CONFIG_PWM_ROCKCHIP=m +CONFIG_PWM_STMPE=y +CONFIG_PWM_SUN4I=m +CONFIG_PWM_TEGRA=y +CONFIG_PWM_TIECAP=m +CONFIG_PWM_TIEHRPWM=m +CONFIG_PWM_XILINX=m +CONFIG_AL_FIC=y +CONFIG_BCM2712_MIP=y +CONFIG_XILINX_INTC=y +CONFIG_QCOM_PDC=y +CONFIG_QCOM_MPM=m +CONFIG_TI_SCI_INTR_IRQCHIP=y +CONFIG_TI_SCI_INTA_IRQCHIP=m +CONFIG_RESET_GPIO=m +CONFIG_RESET_IMX_SCU=m +CONFIG_RESET_IMX7=y +CONFIG_RESET_IMX8MP_AUDIOMIX=m +CONFIG_RESET_QCOM_AOSS=y +CONFIG_RESET_QCOM_PDC=m +CONFIG_RESET_RZG2L_USBPHY_CTRL=m +CONFIG_RESET_RZV2H_USB2PHY=m +CONFIG_RESET_TI_SCI=m +CONFIG_RESET_TI_SYSCON=m +CONFIG_RESET_TI_TPS380X=m +CONFIG_RESET_MESON=m +CONFIG_COMMON_RESET_HI3660=m +CONFIG_COMMON_RESET_HI6220=m +CONFIG_PHY_CAN_TRANSCEIVER=m +CONFIG_PHY_NXP_PTN3222=m +CONFIG_PHY_SNPS_EUSB2=m +CONFIG_PHY_TI_CD2E22=m +CONFIG_PHY_XGENE=y +CONFIG_PHY_SUN4I_USB=m +CONFIG_PHY_SUN50I_USB3=m +CONFIG_PHY_MESON8B_USB2=m +CONFIG_PHY_MESON_GXL_USB2=m +CONFIG_PHY_MESON_G12A_USB3_PCIE=m +CONFIG_PHY_MESON_AXG_PCIE=m +CONFIG_PHY_MESON_AXG_MIPI_DPHY=m +CONFIG_PHY_APPLE_ATC=m +CONFIG_PHY_APPLE_T6040_USB2=m +CONFIG_PHY_APPLE_DPTX=m +CONFIG_PHY_APPLE_T6050_DP=m +CONFIG_PHY_CADENCE_TORRENT=m +CONFIG_PHY_CADENCE_DPHY=m +CONFIG_PHY_CADENCE_DPHY_RX=m +CONFIG_PHY_CADENCE_SIERRA=m +CONFIG_PHY_CADENCE_SALVO=m +CONFIG_PHY_MIXEL_LVDS_PHY=m +CONFIG_PHY_MIXEL_MIPI_DPHY=m +CONFIG_PHY_FSL_IMX8M_PCIE=y +CONFIG_PHY_FSL_IMX8QM_HSIO=m +CONFIG_PHY_FSL_LYNX_28G=m +CONFIG_PHY_HI6220_USB=m +CONFIG_PHY_HI3660_USB=m +CONFIG_PHY_HI3670_USB=m +CONFIG_PHY_HISTB_COMBPHY=m +CONFIG_PHY_HISI_INNO_USB2=m +CONFIG_PHY_MVEBU_A3700_COMPHY=m +CONFIG_PHY_MVEBU_A3700_UTMI=m +CONFIG_PHY_MVEBU_A38X_COMPHY=m +CONFIG_PHY_MVEBU_CP110_COMPHY=m +CONFIG_PHY_MVEBU_CP110_UTMI=m +CONFIG_PHY_QCOM_EDP=m +CONFIG_PHY_QCOM_PCIE2=m +CONFIG_PHY_QCOM_QMP=m +CONFIG_PHY_QCOM_QMP_USB_LEGACY=m +CONFIG_PHY_QCOM_QUSB2=m +CONFIG_PHY_QCOM_EUSB2_REPEATER=m +CONFIG_PHY_QCOM_UNIPHY_PCIE_28LP=y +CONFIG_PHY_QCOM_M31_EUSB=m +CONFIG_PHY_QCOM_USB_HS=m +CONFIG_PHY_QCOM_USB_SNPS_FEMTO_V2=m +CONFIG_PHY_QCOM_USB_HSIC=m +CONFIG_PHY_QCOM_USB_HS_28NM=m +CONFIG_PHY_QCOM_USB_SS=m +CONFIG_PHY_QCOM_SGMII_ETH=m +CONFIG_PHY_RCAR_GEN3_USB2=m +CONFIG_PHY_RZ_G3E_USB3=m +CONFIG_PHY_ROCKCHIP_DP=m +CONFIG_PHY_ROCKCHIP_DPHY_RX0=m +CONFIG_PHY_ROCKCHIP_EMMC=m +CONFIG_PHY_ROCKCHIP_INNO_HDMI=m +CONFIG_PHY_ROCKCHIP_INNO_USB2=m +CONFIG_PHY_ROCKCHIP_INNO_CSIDPHY=m +CONFIG_PHY_ROCKCHIP_INNO_DSIDPHY=m +CONFIG_PHY_ROCKCHIP_NANENG_COMBO_PHY=m +CONFIG_PHY_ROCKCHIP_PCIE=y +CONFIG_PHY_ROCKCHIP_SAMSUNG_DCPHY=m +CONFIG_PHY_ROCKCHIP_SAMSUNG_HDPTX=m +CONFIG_PHY_ROCKCHIP_SNPS_PCIE3=m +CONFIG_PHY_ROCKCHIP_TYPEC=m +CONFIG_PHY_ROCKCHIP_USB=m +CONFIG_PHY_ROCKCHIP_USBDP=m +CONFIG_PHY_TEGRA_XUSB=m +CONFIG_OMAP_USB2=m +CONFIG_PHY_AM654_SERDES=m +CONFIG_PHY_J721E_WIZ=m +CONFIG_PHY_XILINX_ZYNQMP=m +CONFIG_POWERCAP=y +CONFIG_ARM_SCMI_POWERCAP=m +CONFIG_DTPM=y +CONFIG_DTPM_CPU=y +CONFIG_DTPM_DEVFREQ=y +CONFIG_ARM_CCI_PMU=m +CONFIG_ARM_CCN=y +CONFIG_ARM_CMN=m +CONFIG_ARM_NI=m +CONFIG_ARM_SMMU_V3_PMU=m +CONFIG_ARM_DSU_PMU=m +CONFIG_FSL_IMX8_DDR_PMU=m +CONFIG_FUJITSU_UNCORE_PMU=m +CONFIG_QCOM_L2_PMU=y +CONFIG_QCOM_L3_PMU=y +CONFIG_XGENE_PMU=y +CONFIG_ARM_SPE_PMU=m +CONFIG_ARM_DMC620_PMU=m +CONFIG_MARVELL_CN10K_TAD_PMU=m +CONFIG_APPLE_M1_CPU_PMU=y +CONFIG_ALIBABA_UNCORE_DRW_PMU=m +CONFIG_HISI_PMU=y +CONFIG_MARVELL_CN10K_DDR_PMU=m +CONFIG_DWC_PCIE_PMU=m +CONFIG_ARM_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_NVIDIA_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_AMPERE_CORESIGHT_PMU_ARCH_SYSTEM_PMU=m +CONFIG_MESON_DDR_PMU=m +CONFIG_CXL_PMU=m +CONFIG_MARVELL_PEM_PMU=m +CONFIG_USB4=m +CONFIG_USB4_APPLE_SOC=m +CONFIG_ANDROID_BINDER_IPC=y +CONFIG_ANDROID_BINDERFS=y +CONFIG_LIBNVDIMM=y +# CONFIG_BTT is not set +CONFIG_RAMDAX=m +CONFIG_DEV_DAX=y +CONFIG_DEV_DAX_KMEM=m +CONFIG_NVMEM_LAYOUT_SL28_VPD=m +CONFIG_NVMEM_LAYOUT_ONIE_TLV=m +CONFIG_EEPROM_AT24=m +CONFIG_EEPROM_AT25=m +CONFIG_EEPROM_93XX46=m +CONFIG_EEPROM_EE1004=m +CONFIG_EEPROM_M24LR=m +CONFIG_NVMEM_APPLE_EFUSES=m +CONFIG_NVMEM_APPLE_SPMI=y +CONFIG_NVMEM_IMX_OCOTP=m +CONFIG_NVMEM_IMX_OCOTP_ELE=m +CONFIG_NVMEM_IMX_OCOTP_SCU=m +CONFIG_NVMEM_LAYERSCAPE_SFP=m +CONFIG_NVMEM_MESON_MX_EFUSE=m +CONFIG_NVMEM_S32G_OCOTP=m +CONFIG_NVMEM_QCOM_QFPROM=m +CONFIG_NVMEM_QCOM_SEC_QFPROM=m +CONFIG_NVMEM_QNAP_MCU_EEPROM=m +CONFIG_NVMEM_RCAR_EFUSE=m +CONFIG_NVMEM_RMEM=m +CONFIG_NVMEM_ROCKCHIP_EFUSE=m +CONFIG_NVMEM_ROCKCHIP_OTP=m +CONFIG_NVMEM_SPMI_SDAM=m +CONFIG_NVMEM_SUNXI_SID=m +CONFIG_NVMEM_U_BOOT_ENV=m +CONFIG_NVMEM_ZYNQMP=m +# CONFIG_STM_PROTO_BASIC is not set +# CONFIG_STM_PROTO_SYS_T is not set +CONFIG_FPGA=m +CONFIG_ALTERA_PR_IP_CORE=m +CONFIG_ALTERA_PR_IP_CORE_PLAT=m +CONFIG_FPGA_MGR_ALTERA_PS_SPI=m +CONFIG_FPGA_MGR_ALTERA_CVP=m +CONFIG_FPGA_MGR_XILINX_SELECTMAP=m +CONFIG_FPGA_MGR_XILINX_SPI=m +CONFIG_FPGA_MGR_ICE40_SPI=m +CONFIG_FPGA_MGR_MACHXO2_SPI=m +CONFIG_XILINX_PR_DECOUPLER=m +CONFIG_OF_FPGA_REGION=m +CONFIG_FPGA_DFL=m +CONFIG_FPGA_DFL_FME=m +CONFIG_FPGA_DFL_FME_MGR=m +CONFIG_FPGA_DFL_FME_BRIDGE=m +CONFIG_FPGA_DFL_FME_REGION=m +CONFIG_FPGA_DFL_AFU=m +CONFIG_FPGA_DFL_NIOS_INTEL_PAC_N3000=m +CONFIG_FPGA_DFL_PCI=m +CONFIG_FPGA_MGR_ZYNQMP_FPGA=m +CONFIG_FPGA_M10_BMC_SEC_UPDATE=m +CONFIG_FPGA_MGR_LATTICE_SYSCONFIG_SPI=m +CONFIG_TEE=m +CONFIG_OPTEE=m +CONFIG_ARM_TSTEE=m +CONFIG_QCOMTEE=m +CONFIG_MUX_ADG792A=m +CONFIG_MUX_APPLE_DPXBAR=m +CONFIG_MUX_GPIO=m +CONFIG_SLIM_QCOM_NGD_CTRL=m +CONFIG_INTERCONNECT_IMX=m +CONFIG_INTERCONNECT_IMX8MM=m +CONFIG_INTERCONNECT_IMX8MN=m +CONFIG_INTERCONNECT_IMX8MQ=m +CONFIG_INTERCONNECT_IMX8MP=m +CONFIG_INTERCONNECT_QCOM=y +CONFIG_INTERCONNECT_QCOM_GLYMUR=y +CONFIG_INTERCONNECT_QCOM_MSM8916=m +CONFIG_INTERCONNECT_QCOM_MSM8953=m +CONFIG_INTERCONNECT_QCOM_MSM8996=m +CONFIG_INTERCONNECT_QCOM_OSM_L3=m +CONFIG_INTERCONNECT_QCOM_QCM2290=m +CONFIG_INTERCONNECT_QCOM_QCS8300=y +CONFIG_INTERCONNECT_QCOM_SA8775P=y +CONFIG_INTERCONNECT_QCOM_SC7180=y +CONFIG_INTERCONNECT_QCOM_SC7280=y +CONFIG_INTERCONNECT_QCOM_SC8180X=y +CONFIG_INTERCONNECT_QCOM_SC8280XP=y +CONFIG_INTERCONNECT_QCOM_SDM845=m +CONFIG_INTERCONNECT_QCOM_SDX75=m +CONFIG_INTERCONNECT_QCOM_SM6115=m +CONFIG_INTERCONNECT_QCOM_MILOS=m +CONFIG_INTERCONNECT_QCOM_SM8150=m +CONFIG_INTERCONNECT_QCOM_SM8250=m +CONFIG_INTERCONNECT_QCOM_SM8450=m +CONFIG_INTERCONNECT_QCOM_X1E80100=y +CONFIG_COUNTER=m +CONFIG_INTERRUPT_CNT=m +CONFIG_TI_ECAP_CAPTURE=m +CONFIG_TI_EQEP=m +CONFIG_HTE=y +CONFIG_HTE_TEGRA194=m +CONFIG_CDX_BUS=y +CONFIG_CDX_CONTROLLER=m +CONFIG_VALIDATE_FS_PARSER=y +CONFIG_EXT4_FS=y +CONFIG_EXT4_FS_POSIX_ACL=y +CONFIG_EXT4_FS_SECURITY=y +CONFIG_JFS_FS=m +CONFIG_JFS_POSIX_ACL=y +CONFIG_JFS_SECURITY=y +CONFIG_XFS_FS=m +CONFIG_XFS_SUPPORT_V4=y +CONFIG_XFS_SUPPORT_ASCII_CI=y +CONFIG_XFS_QUOTA=y +CONFIG_XFS_POSIX_ACL=y +CONFIG_GFS2_FS=m +CONFIG_GFS2_FS_LOCKING_DLM=y +CONFIG_BTRFS_FS=y +CONFIG_BTRFS_FS_POSIX_ACL=y +CONFIG_NILFS2_FS=m +CONFIG_F2FS_FS=m +CONFIG_F2FS_FS_SECURITY=y +CONFIG_F2FS_FS_COMPRESSION=y +CONFIG_F2FS_UNFAIR_RWSEM=y +CONFIG_ZONEFS_FS=m +CONFIG_FS_DAX=y +CONFIG_FS_ENCRYPTION=y +CONFIG_FS_VERITY=y +CONFIG_FANOTIFY=y +CONFIG_FANOTIFY_ACCESS_PERMISSIONS=y +CONFIG_QUOTA_NETLINK_INTERFACE=y +CONFIG_QFMT_V2=y +CONFIG_AUTOFS_FS=y +CONFIG_FUSE_FS=m +CONFIG_CUSE=m +CONFIG_VIRTIO_FS=m +CONFIG_OVERLAY_FS=m +CONFIG_FSCACHE_STATS=y +CONFIG_CACHEFILES=m +CONFIG_ISO9660_FS=m +CONFIG_JOLIET=y +CONFIG_ZISOFS=y +CONFIG_UDF_FS=m +CONFIG_MSDOS_FS=m +CONFIG_VFAT_FS=m +CONFIG_FAT_DEFAULT_IOCHARSET="ascii" +CONFIG_EXFAT_FS=m +CONFIG_NTFS3_FS=m +CONFIG_NTFS3_LZX_XPRESS=y +CONFIG_NTFS3_FS_POSIX_ACL=y +CONFIG_PROC_KCORE=y +CONFIG_PROC_VMCORE_DEVICE_DUMP=y +CONFIG_TMPFS_POSIX_ACL=y +CONFIG_TMPFS_INODE64=y +CONFIG_TMPFS_QUOTA=y +CONFIG_HUGETLBFS=y +CONFIG_EFIVAR_FS=y +CONFIG_ORANGEFS_FS=m +CONFIG_ECRYPT_FS=m +CONFIG_HFS_FS=m +CONFIG_HFSPLUS_FS=m +CONFIG_JFFS2_FS=m +CONFIG_JFFS2_SUMMARY=y +CONFIG_JFFS2_FS_XATTR=y +CONFIG_UBIFS_FS=m +CONFIG_UBIFS_ATIME_SUPPORT=y +CONFIG_UBIFS_FS_AUTHENTICATION=y +CONFIG_SQUASHFS=m +CONFIG_SQUASHFS_FILE_DIRECT=y +CONFIG_SQUASHFS_COMPILE_DECOMP_MULTI_PERCPU=y +CONFIG_SQUASHFS_XATTR=y +CONFIG_SQUASHFS_LZ4=y +CONFIG_SQUASHFS_LZO=y +CONFIG_SQUASHFS_XZ=y +CONFIG_SQUASHFS_ZSTD=y +CONFIG_MINIX_FS=m +CONFIG_ROMFS_FS=m +CONFIG_PSTORE_RAM=m +CONFIG_UFS_FS=m +CONFIG_EROFS_FS=m +CONFIG_EROFS_FS_ZIP_DEFLATE=y +CONFIG_EROFS_FS_ZIP_ZSTD=y +CONFIG_EROFS_FS_ZIP_ACCEL=y +CONFIG_VBOXSF_FS=m +CONFIG_NFS_FS=m +CONFIG_NFS_V3_ACL=y +CONFIG_NFS_V4=m +CONFIG_NFS_SWAP=y +CONFIG_NFS_V4_2=y +CONFIG_NFS_FSCACHE=y +# CONFIG_NFS_V4_2_READ_PLUS is not set +CONFIG_NFSD=m +CONFIG_NFSD_V3_ACL=y +CONFIG_NFSD_V4=y +CONFIG_NFSD_BLOCKLAYOUT=y +CONFIG_NFSD_SCSILAYOUT=y +CONFIG_NFSD_FLEXFILELAYOUT=y +CONFIG_NFSD_V4_2_INTER_SSC=y +CONFIG_NFSD_V4_SECURITY_LABEL=y +CONFIG_NFSD_V4_POSIX_ACLS=y +CONFIG_NFS_LOCALIO=y +CONFIG_SUNRPC_DEBUG=y +CONFIG_CEPH_FS=m +CONFIG_CEPH_FSCACHE=y +CONFIG_CEPH_FS_POSIX_ACL=y +CONFIG_CEPH_FS_SECURITY_LABEL=y +CONFIG_CIFS=m +# CONFIG_CIFS_STATS2 is not set +CONFIG_CIFS_UPCALL=y +CONFIG_CIFS_XATTR=y +CONFIG_CIFS_POSIX=y +CONFIG_CIFS_DFS_UPCALL=y +CONFIG_CIFS_SWN_UPCALL=y +CONFIG_CIFS_FSCACHE=y +# CONFIG_SMB_KUNIT_TESTS is not set +CONFIG_AFS_FS=m +CONFIG_AFS_DEBUG=y +CONFIG_AFS_FSCACHE=y +CONFIG_9P_FS=m +CONFIG_9P_FSCACHE=y +CONFIG_9P_FS_POSIX_ACL=y +CONFIG_9P_FS_SECURITY=y +CONFIG_NLS_DEFAULT="utf8" +CONFIG_NLS_CODEPAGE_437=y +CONFIG_NLS_CODEPAGE_737=m +CONFIG_NLS_CODEPAGE_775=m +CONFIG_NLS_CODEPAGE_850=m +CONFIG_NLS_CODEPAGE_852=m +CONFIG_NLS_CODEPAGE_855=m +CONFIG_NLS_CODEPAGE_857=m +CONFIG_NLS_CODEPAGE_860=m +CONFIG_NLS_CODEPAGE_861=m +CONFIG_NLS_CODEPAGE_862=m +CONFIG_NLS_CODEPAGE_863=m +CONFIG_NLS_CODEPAGE_864=m +CONFIG_NLS_CODEPAGE_865=m +CONFIG_NLS_CODEPAGE_866=m +CONFIG_NLS_CODEPAGE_869=m +CONFIG_NLS_CODEPAGE_936=m +CONFIG_NLS_CODEPAGE_950=m +CONFIG_NLS_CODEPAGE_932=m +CONFIG_NLS_CODEPAGE_949=m +CONFIG_NLS_CODEPAGE_874=m +CONFIG_NLS_ISO8859_8=m +CONFIG_NLS_CODEPAGE_1250=m +CONFIG_NLS_CODEPAGE_1251=m +CONFIG_NLS_ASCII=y +CONFIG_NLS_ISO8859_1=m +CONFIG_NLS_ISO8859_2=m +CONFIG_NLS_ISO8859_3=m +CONFIG_NLS_ISO8859_4=m +CONFIG_NLS_ISO8859_5=m +CONFIG_NLS_ISO8859_6=m +CONFIG_NLS_ISO8859_7=m +CONFIG_NLS_ISO8859_9=m +CONFIG_NLS_ISO8859_13=m +CONFIG_NLS_ISO8859_14=m +CONFIG_NLS_ISO8859_15=m +CONFIG_NLS_KOI8_R=m +CONFIG_NLS_KOI8_U=m +CONFIG_NLS_MAC_ROMAN=m +CONFIG_NLS_MAC_CELTIC=m +CONFIG_NLS_MAC_CENTEURO=m +CONFIG_NLS_MAC_CROATIAN=m +CONFIG_NLS_MAC_CYRILLIC=m +CONFIG_NLS_MAC_GAELIC=m +CONFIG_NLS_MAC_GREEK=m +CONFIG_NLS_MAC_ICELAND=m +CONFIG_NLS_MAC_INUIT=m +CONFIG_NLS_MAC_ROMANIAN=m +CONFIG_NLS_MAC_TURKISH=m +CONFIG_DLM=m +CONFIG_DLM_DEBUG=y +CONFIG_UNICODE=y +CONFIG_KEYS_REQUEST_CACHE=y +CONFIG_PERSISTENT_KEYRINGS=y +CONFIG_BIG_KEYS=y +CONFIG_TRUSTED_KEYS=y +# CONFIG_TRUSTED_KEYS_TPM is not set +CONFIG_KEY_DH_OPERATIONS=y +CONFIG_KEY_NOTIFICATIONS=y +CONFIG_SECURITY_DMESG_RESTRICT=y +CONFIG_PROC_MEM_ALWAYS_FORCE=y +CONFIG_SECURITY=y +CONFIG_SECURITY_INFINIBAND=y +CONFIG_SECURITY_NETWORK_XFRM=y +CONFIG_LSM_MMAP_MIN_ADDR=65535 +CONFIG_SECURITY_SELINUX=y +CONFIG_SECURITY_SELINUX_BOOTPARAM=y +CONFIG_SECURITY_TOMOYO=y +CONFIG_SECURITY_TOMOYO_ACTIVATION_TRIGGER="/usr/lib/systemd/systemd" +CONFIG_SECURITY_YAMA=y +CONFIG_SECURITY_LOCKDOWN_LSM=y +CONFIG_SECURITY_LOCKDOWN_LSM_EARLY=y +CONFIG_SECURITY_LANDLOCK=y +CONFIG_SECURITY_IPE=y +CONFIG_INTEGRITY_SIGNATURE=y +CONFIG_INTEGRITY_ASYMMETRIC_KEYS=y +CONFIG_INTEGRITY_PLATFORM_KEYRING=y +CONFIG_INTEGRITY_MACHINE_KEYRING=y +CONFIG_INTEGRITY_CA_MACHINE_KEYRING=y +CONFIG_INTEGRITY_CA_MACHINE_KEYRING_MAX=y +CONFIG_IMA=y +CONFIG_IMA_KEXEC=y +CONFIG_IMA_DEFAULT_HASH_SHA256=y +CONFIG_IMA_WRITE_POLICY=y +CONFIG_IMA_APPRAISE=y +CONFIG_IMA_ARCH_POLICY=y +CONFIG_IMA_APPRAISE_MODSIG=y +CONFIG_IMA_KEYRINGS_PERMIT_SIGNED_BY_BUILTIN_OR_SECONDARY=y +CONFIG_EVM=y +CONFIG_LSM="lockdown,yama,integrity,selinux,bpf,landlock,ipe" +CONFIG_INIT_ON_ALLOC_DEFAULT_ON=y +CONFIG_FORTIFY_SOURCE=y +CONFIG_HARDENED_USERCOPY=y +CONFIG_BUG_ON_DATA_CORRUPTION=y +CONFIG_CRYPTO_FIPS=y +CONFIG_CRYPTO_USER=m +CONFIG_CRYPTO_SELFTESTS=y +CONFIG_CRYPTO_NULL=y +CONFIG_CRYPTO_PCRYPT=m +CONFIG_CRYPTO_CRYPTD=y +CONFIG_CRYPTO_AUTHENC=y +CONFIG_CRYPTO_BENCHMARK=m +CONFIG_CRYPTO_ECDSA=y +CONFIG_CRYPTO_ECRDSA=m +CONFIG_CRYPTO_BLOWFISH=m +CONFIG_CRYPTO_CAST5=m +CONFIG_CRYPTO_CAST6=m +CONFIG_CRYPTO_SERPENT=m +CONFIG_CRYPTO_TWOFISH=m +CONFIG_CRYPTO_ADIANTUM=m +CONFIG_CRYPTO_HCTR2=m +CONFIG_CRYPTO_LRW=m +CONFIG_CRYPTO_AEGIS128=m +CONFIG_CRYPTO_CCM=y +CONFIG_CRYPTO_GCM=y +CONFIG_CRYPTO_SEQIV=y +CONFIG_CRYPTO_BLAKE2B=y +CONFIG_CRYPTO_CMAC=y +CONFIG_CRYPTO_MD4=m +CONFIG_CRYPTO_MD5=y +CONFIG_CRYPTO_RMD160=m +CONFIG_CRYPTO_SHA3=y +CONFIG_CRYPTO_WP512=m +CONFIG_CRYPTO_XCBC=m +CONFIG_CRYPTO_XXHASH=y +CONFIG_CRYPTO_CRC32C=y +CONFIG_CRYPTO_CRC32=m +CONFIG_CRYPTO_DEFLATE=y +CONFIG_CRYPTO_842=y +CONFIG_CRYPTO_LZ4HC=m +CONFIG_CRYPTO_DRBG=y +CONFIG_CRYPTO_JITTERENTROPY_OSR=1 +CONFIG_CRYPTO_USER_API_HASH=y +CONFIG_CRYPTO_USER_API_SKCIPHER=y +CONFIG_CRYPTO_USER_API_RNG=y +CONFIG_CRYPTO_USER_API_AEAD=y +# CONFIG_CRYPTO_USER_API_ENABLE_OBSOLETE is not set +CONFIG_CRYPTO_GHASH_ARM64_CE=m +CONFIG_CRYPTO_AES_ARM64_NEON_BLK=y +CONFIG_CRYPTO_AES_ARM64_BS=m +CONFIG_CRYPTO_AES_ARM64_CE_CCM=y +CONFIG_CRYPTO_DEV_SUN4I_SS=m +CONFIG_CRYPTO_DEV_SUN8I_CE=m +CONFIG_CRYPTO_DEV_SUN8I_CE_HASH=y +CONFIG_CRYPTO_DEV_SUN8I_CE_TRNG=y +CONFIG_CRYPTO_DEV_SUN8I_SS=m +CONFIG_CRYPTO_DEV_SUN8I_SS_HASH=y +CONFIG_CRYPTO_DEV_FSL_CAAM=m +CONFIG_CRYPTO_DEV_FSL_CAAM_RINGSIZE=3 +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC=y +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC_COUNT_THLD=8 +CONFIG_CRYPTO_DEV_FSL_CAAM_INTC_TIME_THLD=8192 +CONFIG_CRYPTO_DEV_FSL_DPAA2_CAAM=m +CONFIG_CRYPTO_DEV_ATMEL_ECC=m +CONFIG_CRYPTO_DEV_ATMEL_SHA204A=m +CONFIG_CRYPTO_DEV_CCP=y +CONFIG_CAVIUM_CPT=m +CONFIG_CRYPTO_DEV_NITROX_CNN55XX=m +CONFIG_CRYPTO_DEV_MARVELL_CESA=m +CONFIG_CRYPTO_DEV_OCTEONTX_CPT=m +CONFIG_CRYPTO_DEV_OCTEONTX2_CPT=m +CONFIG_CRYPTO_DEV_QAT_DH895xCC=m +CONFIG_CRYPTO_DEV_QAT_C3XXX=m +CONFIG_CRYPTO_DEV_QAT_C62X=m +CONFIG_CRYPTO_DEV_QAT_4XXX=m +CONFIG_CRYPTO_DEV_QAT_420XX=m +CONFIG_CRYPTO_DEV_QAT_DH895xCCVF=m +CONFIG_CRYPTO_DEV_QAT_C3XXXVF=m +CONFIG_CRYPTO_DEV_QAT_C62XVF=m +CONFIG_CRYPTO_DEV_ROCKCHIP=m +CONFIG_CRYPTO_DEV_TEGRA=m +CONFIG_CRYPTO_DEV_ZYNQMP_AES=m +CONFIG_CRYPTO_DEV_ZYNQMP_SHA3=m +CONFIG_CRYPTO_DEV_CHELSIO=m +CONFIG_CRYPTO_DEV_VIRTIO=m +CONFIG_CRYPTO_DEV_SAFEXCEL=m +CONFIG_CRYPTO_DEV_HISI_HPRE=m +CONFIG_CRYPTO_DEV_AMLOGIC_GXL=y +CONFIG_CRYPTO_DEV_APPLE_SIO_AES=m +CONFIG_CRYPTO_DEV_SA2UL=m +CONFIG_CRYPTO_DEV_TI_DTHEV2=m +CONFIG_PKCS8_PRIVATE_KEY_PARSER=m +CONFIG_SIGNED_PE_FILE_VERIFICATION=y +CONFIG_SYSTEM_EXTRA_CERTIFICATE=y +CONFIG_SECONDARY_TRUSTED_KEYRING=y +CONFIG_SYSTEM_BLACKLIST_KEYRING=y +CONFIG_SYSTEM_BLACKLIST_AUTH_UPDATE=y +# CONFIG_RAID6_PQ_BENCHMARK is not set +CONFIG_DMA_NUMA_CMA=y +CONFIG_CMA_SIZE_MBYTES=64 +CONFIG_PRINTK_TIME=y +CONFIG_CONSOLE_LOGLEVEL_QUIET=3 +CONFIG_BOOT_PRINTK_DELAY=y +CONFIG_DYNAMIC_DEBUG=y +# CONFIG_DEBUG_MISC is not set +CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y +CONFIG_DEBUG_INFO_BTF=y +CONFIG_STRIP_ASM_SYMS=y +CONFIG_HEADERS_INSTALL=y +CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x0 +CONFIG_KGDB=y +CONFIG_KGDB_TESTS=y +CONFIG_UBSAN=y +CONFIG_UBSAN_SHIFT=y +# CONFIG_UBSAN_BOOL is not set +# CONFIG_UBSAN_ENUM is not set +CONFIG_UBSAN_KVM_EL2=y +CONFIG_PAGE_OWNER=y +CONFIG_PAGE_POISONING=y +CONFIG_DEBUG_WX=y +CONFIG_SCHED_STACK_END_CHECK=y +CONFIG_DEBUG_MEMORY_INIT=y +CONFIG_KFENCE=y +CONFIG_DEBUG_SHIRQ=y +CONFIG_SOFTLOCKUP_DETECTOR_INTR_STORM=y +CONFIG_HARDLOCKUP_DETECTOR=y +CONFIG_TEST_LOCKUP=m +CONFIG_LOCK_TORTURE_TEST=m +CONFIG_DEBUG_LIST=y +CONFIG_RCU_TORTURE_TEST=m +CONFIG_RCU_CPU_STALL_TIMEOUT=60 +CONFIG_LATENCYTOP=y +CONFIG_BOOTTIME_TRACING=y +CONFIG_FUNCTION_GRAPH_RETVAL=y +CONFIG_FPROBE=y +CONFIG_FUNCTION_PROFILER=y +CONFIG_STACK_TRACER=y +CONFIG_SCHED_TRACER=y +CONFIG_HWLAT_TRACER=y +CONFIG_TIMERLAT_TRACER=y +CONFIG_FTRACE_SYSCALLS=y +CONFIG_BLK_DEV_IO_TRACE=y +CONFIG_HIST_TRIGGERS=y +CONFIG_RING_BUFFER_BENCHMARK=m +CONFIG_TRACE_EVAL_MAP_FILE=y +CONFIG_RV=y +CONFIG_RV_PER_TASK_MONITORS=3 +CONFIG_RV_MON_WWNR=y +CONFIG_RV_MON_SCHED=y +CONFIG_IO_STRICT_DEVMEM=y +CONFIG_CORESIGHT=m +CONFIG_CORESIGHT_LINK_AND_SINK_TMC=m +CONFIG_CORESIGHT_CATU=m +CONFIG_CORESIGHT_SINK_TPIU=m +CONFIG_CORESIGHT_SINK_ETBV10=m +CONFIG_CORESIGHT_SOURCE_ETM4X=m +CONFIG_CORESIGHT_STM=m +CONFIG_CORESIGHT_CTCU=m +CONFIG_CORESIGHT_CPU_DEBUG=m +CONFIG_CORESIGHT_CTI=m +CONFIG_CORESIGHT_TRBE=m +CONFIG_ULTRASOC_SMB=m +CONFIG_CORESIGHT_TPDM=m +CONFIG_CORESIGHT_TNOC=m +CONFIG_KUNIT=m +# CONFIG_KUNIT_FAULT_TEST is not set +CONFIG_KUNIT_ALL_TESTS=m +# CONFIG_KUNIT_DEFAULT_ENABLED is not set +# CONFIG_TEST_LIST_SORT is not set +CONFIG_ATOMIC64_SELFTEST=y +CONFIG_ASYNC_RAID6_TEST=m +CONFIG_TEST_KSTRTOX=y +CONFIG_TEST_VMALLOC=m +CONFIG_TEST_BPF=m +CONFIG_LINEAR_RANGES_TEST=m +CONFIG_TEST_KMOD=m +CONFIG_TEST_HMM=m +CONFIG_MEMTEST=y From 351360b54739260f39b11acf0845185e458eabeb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:53:43 +1100 Subject: [PATCH 0922/1514] docs: describe the main branch and the three release channels RELEASES.md describes the stable (v*), nightly and edge channels, what a release contains, how a stable tag is cut on a fixed cadence from a nightly commit, and how upstream version upgrades go through one rebase/v branch. README points at the channels and at aurora_defconfig. CONTRIBUTING.md gains the branch rules: pull requests into main from feat/ or fix/ branches, wip/ and archive/ for parked and historical work, no direct or force pushes to main, and merged branches deleted on merge. Signed-off-by: Ryan Murray --- CONTRIBUTING.md | 29 ++++++++++++++++ README | 13 +++++++ RELEASES.md | 90 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 RELEASES.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f20ec244cf27c7..aac803eeae2381 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -79,3 +79,32 @@ or sensitive, say so rather than substituting data from another Mac. For kernel patches, also follow the existing [kernel submission guidance](Documentation/process/submitting-patches.rst). + +## Contributing code + +`main` is the only branch work lands in. Open every pull request against +`main` from a short-lived branch: + +- `feat/` for new work, `fix/` for fixes. +- `wip/` for work you park without a pull request. It is not merged + from directly; open a `feat/` or `fix/` pull request when it is ready. +- `archive/` holds old branches kept for their history. Do not push to them. +- `feat/-` can also be a topic branch for a large feature that + takes several pull requests: the parts are reviewed as pull requests into + the topic branch, the whole is regression-tested there and lands on `main` + as one pull request, and the topic branch is then deleted. +- `rebase/v` is the single branch for an upstream version upgrade, + and `hotfix/v` a short-lived branch for a stable hotfix (see + [RELEASES.md](RELEASES.md)). + +There are no long-lived release or per-platform branches. + +`main` takes changes only through pull requests: no direct pushes, no force +pushes and no deletion. Merged branches are deleted automatically, so start +new work from a fresh branch off `main` instead of reusing a merged one. Do +not stack long chains of pull requests on each other; if you must, retarget +the stacked ones to `main` before their base is merged. + +Releases are cut from `main` on a fixed cadence and never wait for unfinished +work. How the edge, nightly and stable channels are built is in +[RELEASES.md](RELEASES.md). diff --git a/README b/README index 010c587224224b..23a68bc6cff018 100644 --- a/README +++ b/README @@ -1,3 +1,16 @@ +Aurora Silicon +============== + +This tree is the Aurora Silicon kernel for Apple silicon Macs. Work lands on +the `main` branch through pull requests (see CONTRIBUTING.md). Built kernels +are published as GitHub Releases in three channels, described in RELEASES.md: + +* stable: a `v*` release (https://github.com/aurora-silicon/linux/releases/latest) +* nightly: the `aurora-nightly` prerelease, rebuilt daily when main moved +* edge: the `aurora-edge` prerelease, rebuilt on every push to main + +Build the same configuration locally with `make aurora_defconfig asahi.config`. + Linux kernel ============ diff --git a/RELEASES.md b/RELEASES.md new file mode 100644 index 00000000000000..4e83269f304985 --- /dev/null +++ b/RELEASES.md @@ -0,0 +1,90 @@ +# Aurora kernel releases + +This repository has one long-lived branch, `main`. Every change lands there +through a pull request, and every release is built from a commit on `main` by +[`kernel-release.yml`](.github/workflows/kernel-release.yml). + +## Channels + +| Channel | Where | Built when | Changes? | +| --- | --- | --- | --- | +| stable | the GitHub Release for a `v*` tag, e.g. [`releases/latest`](https://github.com/aurora-silicon/linux/releases/latest) | a `v*` tag is pushed on a `main` commit | never: a stable release is not rebuilt or edited | +| nightly | prerelease tag [`aurora-nightly`](https://github.com/aurora-silicon/linux/releases/tag/aurora-nightly) | once a day, if `main` moved since the last nightly | tag and assets replaced each night | +| edge | prerelease tag [`aurora-edge`](https://github.com/aurora-silicon/linux/releases/tag/aurora-edge) | every push to `main` (a newer push cancels the running build) | tag and assets replaced on every push | + +Each release body names the exact `main` commit it was built from. `edge` is +for testing what just merged; `nightly` is the candidate pool for the next +stable tag; `stable` is what distributions ship by default. + +## What a release contains + +For kernel release `` (also in the `kernel.release` asset): + +- `Image-.gz`: the arm64 kernel image +- `modules-.tar.zst`: the `lib/modules/` tree, modules signed +- `dtbs-.tar.zst`: all device trees built by the configuration +- `config-`, `System.map-` +- `module-signing-cert-.der`: the certificate the modules are signed with +- `linux-aurora*-bin-*.pkg.tar.zst`: Arch Linux packages from `make pacman-pkg` +- `source.commit`, `SHA256SUMS` + +The configuration is the fleet configuration: `make aurora_defconfig asahi.config` +(`arch/arm64/configs/aurora_defconfig` plus `asahi.config`), built with the +toolchain versions pinned in the workflow. + +Each build signs its modules with a key generated for that build and deletes +the private key afterwards. Our lab fleet kits are signed separately and are +not published here. + +## Cutting a stable release + +Stable releases are time-boxed. On the release cadence: + +1. Take the commit the current `aurora-nightly` was built from (it is in the + release body), once it has passed the lab regression gate: every lab Mac + (M1 Pro, M2 Air, M2 mini, M3 Air, M4 Air, M4 Pro, Neo) boots it with no new + failures compared with the previous stable release. The gate looks for + regressions only; missing features do not block a tag. +2. Tag it and push the tag: + + ```sh + git tag -a v0.2.0 -m 'Aurora v0.2.0' + git push origin v0.2.0 + ``` + +3. The workflow builds it and publishes the release with generated notes. + +Never hold a tag for unfinished work. Work that is not ready stays in its pull +request and goes out in the next release. The workflow refuses a tag that is +not on `main` and never overwrites a stable release that already exists. + +## Hotfixes + +Only a boot failure, data loss, a security problem or a risk of hardware damage +in a stable release justifies a hotfix. Everything else is fixed forward on +`main` and ships in the next release. + +1. Branch `hotfix/v` from the stable tag, fix it there and tag + `v` on that branch. The tag builds and publishes like any stable + release. +2. Forward-port the same commits to `main` through a pull request; each + forward-ported commit carries a `Forward-port: ` trailer naming the + hotfix commit. +3. Delete the hotfix branch once the forward-port is merged. + +Hotfix tags are the one case where a stable tag is not on `main`; the +workflow accepts them only from a `hotfix/` branch. + +## Upstream stable updates + +Upstream stable point releases for the current base (for example 7.3.y) are +merged into `main` weekly through a pull request, and at once when they carry +security fixes. + +## Kernel version upgrades + +Moving to a new upstream version (for example 7.4) happens on one branch, +`rebase/v7.4`, opened as a pull request into `main`. It is built and +fleet-tested like any other change and merged when it passes. `main` is never +rebased in place, and nobody stacks other work on the rebase branch; only fixes +needed for the rebase itself go there. From 42c2393835d177689615e02f4fc51615e4703d4d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:52:32 +1100 Subject: [PATCH 0923/1514] ci: build kernel releases for the edge, nightly and stable channels kernel-release.yml builds the fleet configuration on ubuntu-24.04-arm with the fleet toolchain versions pinned (LLVM 22.1.6, Rust 1.97.1, bindgen 0.73.2, pahole 1.31) and publishes: - aurora-edge: prerelease, moved to every push to main; a newer push cancels a running edge build. - aurora-nightly: prerelease, daily, only when main moved since the commit the aurora-nightly tag points at. - v*: a stable release per tag on a main commit, with generated notes. An existing stable release is never rebuilt or overwritten. Assets: Image.gz, the modules tree, DTBs, config, System.map, the module signing certificate, Arch packages from make pacman-pkg and SHA256SUMS. Modules are signed with a key generated for the run and deleted afterwards; the build fails if a tarball carries it. workflow_dispatch builds without publishing by default; pull requests that change the release machinery get the same build-only run. Signed-off-by: Ryan Murray --- .github/scripts/kernel-release-build.sh | 124 +++++++++++ .github/workflows/kernel-release.yml | 278 ++++++++++++++++++++++++ 2 files changed, 402 insertions(+) create mode 100755 .github/scripts/kernel-release-build.sh create mode 100644 .github/workflows/kernel-release.yml diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh new file mode 100755 index 00000000000000..3c30d800daa801 --- /dev/null +++ b/.github/scripts/kernel-release-build.sh @@ -0,0 +1,124 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Build the Aurora kernel release artifacts from this tree. +# +# Usage: kernel-release-build.sh +# +# The configuration is the fleet configuration: arch/arm64/configs/aurora_defconfig +# (savedefconfig output of the fleet .config) with arch/arm64/configs/asahi.config +# merged on top, so options added to asahi.config reach the release before +# aurora_defconfig is regenerated. Requires ARCH=arm64 LLVM=1 toolchain in PATH +# (clang/lld, rustc + rust-src, bindgen, pahole). +# +# Modules are signed with the key the build generates (certs/signing_key.pem). +# The private key is deleted at the end and never packaged. + +set -euo pipefail + +O=$(realpath -m "$1") +D=$(realpath -m "$2") +LV=$3 +PKGBASE=$4 +S=$(git rev-parse --show-toplevel) +JOBS=${JOBS:-$(nproc)} + +export ARCH=arm64 LLVM=1 +export KBUILD_BUILD_USER=${KBUILD_BUILD_USER:-aurora} KBUILD_BUILD_HOST=${KBUILD_BUILD_HOST:-github} +export KBUILD_BUILD_TIMESTAMP=${KBUILD_BUILD_TIMESTAMP:-$(git -C "$S" log -1 --format=%cD HEAD)} + +mk() { make -C "$S" O="$O" LOCALVERSION="$LV" -j"$JOBS" "$@"; } + +mkdir -p "$O" "$D" +rm -f "$O/.config" + +echo "::group::toolchain" +clang --version | head -1 +ld.lld --version | head -1 +rustc --version +bindgen --version +pahole --version +echo "::endgroup::" + +echo "::group::config" +mk aurora_defconfig asahi.config +mk savedefconfig +if cmp -s "$O/defconfig" "$S/arch/arm64/configs/aurora_defconfig"; then + echo "config: identical to aurora_defconfig" +else + echo "::warning::generated config differs from aurora_defconfig (asahi.config or Kconfig changed); regenerate it with savedefconfig" + diff -u "$S/arch/arm64/configs/aurora_defconfig" "$O/defconfig" || true +fi +python3 - "$S/arch/arm64/configs/asahi.config" "$O/.config" <<'PY' +import re, sys +def load(p): + d = {} + for l in open(p): + l = l.strip() + m = re.match(r'^(CONFIG_\w+)=(.*)$', l) + if m: + d[m.group(1)] = m.group(2) + continue + m = re.match(r'^# (CONFIG_\w+) is not set$', l) + if m: + d[m.group(1)] = 'n' + return d +want, have = load(sys.argv[1]), load(sys.argv[2]) +bad = [(k, v, have.get(k, 'n')) for k, v in want.items() if have.get(k, 'n') != v] +print(f"asahi.config requests {len(want)}; mismatches {len(bad)}") +for k, v, h in bad: + print(f"MISMATCH {k}: want {v} got {h}") +sys.exit(1 if bad else 0) +PY +grep -qx 'CONFIG_MODULE_SIG_KEY="certs/signing_key.pem"' "$O/.config" +echo "::endgroup::" + +echo "::group::build" +mk Image.gz modules dtbs +echo "::endgroup::" + +KREL=$(cat "$O/include/config/kernel.release") +M=$O/modroot +rm -rf "$M" +mk INSTALL_MOD_PATH="$M" INSTALL_MOD_STRIP=1 modules_install +rm -f "$M/lib/modules/$KREL/build" "$M/lib/modules/$KREL/source" + +TAR=(tar --sort=name --mtime="$KBUILD_BUILD_TIMESTAMP" --owner=0 --group=0 --numeric-owner) +cp "$O/arch/arm64/boot/Image.gz" "$D/Image-$KREL.gz" +cp "$O/.config" "$D/config-$KREL" +cp "$O/System.map" "$D/System.map-$KREL" +"${TAR[@]}" --zstd -C "$M" -cf "$D/modules-$KREL.tar.zst" "lib/modules/$KREL" +"${TAR[@]}" --zstd -C "$O/arch/arm64/boot/dts" -cf "$D/dtbs-$KREL.tar.zst" \ + $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | sort) +cp "$O/certs/signing_key.x509" "$D/module-signing-cert-$KREL.der" +git -C "$S" rev-parse HEAD > "$D/source.commit" +echo "$KREL" > "$D/kernel.release" +echo "modules: $(find "$M/lib/modules/$KREL" -name '*.ko*' | wc -l)" +echo "dtbs: $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | wc -l)" + +echo "::group::pacman-pkg" +if command -v makepkg >/dev/null; then + rm -f "$O"/*.pkg.tar.* + if mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ + MAKEPKGOPTS="--nodeps --noconfirm" pacman-pkg; then + cp "$O"/*.pkg.tar.zst "$D/" + else + echo "::warning::make pacman-pkg failed; release ships without the Arch package" + fi +else + echo "::warning::makepkg not installed; skipping the Arch package" +fi +echo "::endgroup::" + +# The private signing key stays on the builder for this run only. +rm -f "$O/certs/signing_key.pem" +for f in "$D"/*.tar.* ; do + if tar -tf "$f" | grep -q 'signing_key\.pem$'; then + echo "::error::$f contains the private signing key" + exit 1 + fi +done + +(cd "$D" && sha256sum $(ls | grep -v -x SHA256SUMS) > SHA256SUMS) +cat "$D/SHA256SUMS" +echo "BUILD-OK $KREL" diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml new file mode 100644 index 00000000000000..3442ecb87cd5ff --- /dev/null +++ b/.github/workflows/kernel-release.yml @@ -0,0 +1,278 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel release channels (see RELEASES.md): +# aurora-edge prerelease, rebuilt on every push to main +# aurora-nightly prerelease, daily from main when main moved since the last nightly +# v* immutable stable release, built from a tag on main +# +# workflow_dispatch builds without publishing (publish: none) or publishes +# one rolling channel by hand (publish: edge | nightly). Pull requests that +# change the release machinery itself get a build without publishing. +# +# The configuration is the fleet configuration (aurora_defconfig + asahi.config) +# built with the fleet toolchain versions pinned below. Modules are signed with +# a key generated for each run and thrown away afterwards; lab fleet kits are +# signed separately and are not produced here. + +name: kernel-release + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + branches: [main] + paths: + - '.github/workflows/kernel-release.yml' + - '.github/scripts/kernel-release-build.sh' + - 'arch/arm64/configs/aurora_defconfig' + schedule: + - cron: '30 15 * * *' + workflow_dispatch: + inputs: + publish: + description: 'Channel to publish (none = build only)' + type: choice + options: [none, edge, nightly] + default: none + +permissions: + contents: read + +concurrency: + group: >- + kernel-release-${{ + github.event_name == 'schedule' && 'nightly' || + github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || + startsWith(github.ref, 'refs/tags/v') && github.ref_name || + github.event_name == 'workflow_dispatch' && inputs.publish != 'none' && inputs.publish || + github.event_name == 'workflow_dispatch' && format('dispatch-{0}', github.ref_name) || + 'edge' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} + +env: + LLVM_VERSION: '22.1.6' + RUST_VERSION: '1.97.1' + BINDGEN_VERSION: '0.73.2' + PAHOLE_VERSION: 'v1.31' + +jobs: + plan: + runs-on: ubuntu-24.04-arm + outputs: + channel: ${{ steps.plan.outputs.channel }} + sha: ${{ steps.plan.outputs.sha }} + build: ${{ steps.plan.outputs.build }} + localversion: ${{ steps.plan.outputs.localversion }} + pkgbase: ${{ steps.plan.outputs.pkgbase }} + steps: + - id: plan + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + EVENT: ${{ github.event_name }} + REF: ${{ github.ref }} + REF_NAME: ${{ github.ref_name }} + SHA: ${{ github.event.pull_request.head.sha || github.sha }} + PUBLISH: ${{ inputs.publish }} + run: | + set -euo pipefail + build=true + case "$EVENT:$REF" in + push:refs/heads/main) channel=edge ;; + push:refs/tags/v*) channel=stable ;; + schedule:*) channel=nightly ;; + pull_request:*) channel=none ;; + workflow_dispatch:*) + channel=$PUBLISH + if [ "$channel" != none ] && [ "$REF" != refs/heads/main ]; then + echo "::error::publishing $channel needs a dispatch on main"; exit 1 + fi ;; + *) echo "::error::unexpected trigger $EVENT $REF"; exit 1 ;; + esac + if [ "$channel" = nightly ]; then + sha=$(gh api "repos/$REPO/commits/main" -q .sha) + last=$(gh api "repos/$REPO/commits/aurora-nightly" -q .sha 2>/dev/null || true) + if [ "$EVENT" = schedule ] && [ "$last" = "$sha" ]; then + echo "main is still at the last nightly ($sha); nothing to build" + build=false + fi + else + sha=$SHA + fi + if [ "$channel" = stable ]; then + # A stable tag must be on main, or on a hotfix/ branch (RELEASES.md). + on= + for b in main $(gh api --paginate "repos/$REPO/branches" -q '.[].name | select(startswith("hotfix/"))'); do + status=$(gh api "repos/$REPO/compare/$(jq -rn --arg b "$b" '$b|@uri')...$sha" -q .status) + case "$status" in behind|identical) on=$b; break ;; esac + done + if [ -z "$on" ]; then + echo "::error::$REF_NAME ($sha) is not on main or a hotfix/ branch"; exit 1 + fi + echo "$REF_NAME is on $on" + fi + case "$channel" in + stable) lv="-aurora-${REF_NAME#v}"; pkg=linux-aurora-bin ;; + edge|nightly) lv="-aurora-$channel"; pkg="linux-aurora-$channel-bin" ;; + *) lv=-aurora-ci; pkg=linux-aurora-ci-bin ;; + esac + { + echo "channel=$channel"; echo "sha=$sha"; echo "build=$build" + echo "localversion=$lv"; echo "pkgbase=$pkg" + } | tee -a "$GITHUB_OUTPUT" + + build: + needs: plan + if: needs.plan.outputs.build == 'true' + runs-on: ubuntu-24.04-arm + timeout-minutes: 345 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Free disk space + run: | + sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \ + /usr/local/share/boost /opt/hostedtoolcache/CodeQL || true + df -h / "$GITHUB_WORKSPACE" + + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + bc bison flex libelf-dev libssl-dev libdw-dev zlib1g-dev cmake \ + cpio kmod rsync zstd xz-utils python3 \ + fakeroot libarchive-tools + + - name: Install makepkg (for make pacman-pkg) + continue-on-error: true + run: sudo apt-get install -y --no-install-recommends makepkg + + - name: Install Rust + run: | + if ! command -v rustup >/dev/null; then + curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + export PATH="$HOME/.cargo/bin:$PATH" + fi + rustup toolchain install "$RUST_VERSION" --profile minimal -c rust-src + rustup default "$RUST_VERSION" + rustc --version + + - name: Restore toolchain cache + id: tc-cache + uses: actions/cache@v4 + with: + path: ~/tc + key: tc-${{ runner.arch }}-llvm${{ env.LLVM_VERSION }}-bindgen${{ env.BINDGEN_VERSION }}-pahole${{ env.PAHOLE_VERSION }}-1 + + - name: Install LLVM, bindgen and pahole + if: steps.tc-cache.outputs.cache-hit != 'true' + run: | + set -euo pipefail + mkdir -p ~/tc + curl -fsSL -o /tmp/llvm.tar.xz \ + "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_VERSION/LLVM-$LLVM_VERSION-Linux-ARM64.tar.xz" + mkdir -p ~/tc/llvm + tar -xJf /tmp/llvm.tar.xz -C ~/tc/llvm --strip-components=1 + rm /tmp/llvm.tar.xz + git clone -q --depth 1 -b "$PAHOLE_VERSION" --recurse-submodules --shallow-submodules \ + https://git.kernel.org/pub/scm/devel/pahole/pahole.git /tmp/pahole + cmake -S /tmp/pahole -B /tmp/pahole/build -DCMAKE_INSTALL_PREFIX="$HOME/tc/pahole" \ + -D__LIB=lib -DCMAKE_BUILD_TYPE=Release + make -C /tmp/pahole/build -j"$(nproc)" install + LIBCLANG_PATH=~/tc/llvm/lib cargo install --locked --root ~/tc/bindgen \ + bindgen-cli --version "$BINDGEN_VERSION" + + - name: Build + env: + LOCALVERSION: ${{ needs.plan.outputs.localversion }} + PKGBASE: ${{ needs.plan.outputs.pkgbase }} + run: | + set -euo pipefail + export PATH="$HOME/tc/llvm/bin:$HOME/tc/pahole/bin:$HOME/tc/bindgen/bin:$PATH" + export LD_LIBRARY_PATH="$HOME/tc/pahole/lib:$HOME/tc/llvm/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" + export LIBCLANG_PATH="$HOME/tc/llvm/lib" + .github/scripts/kernel-release-build.sh "$RUNNER_TEMP/out" "$RUNNER_TEMP/dist" "$LOCALVERSION" "$PKGBASE" + df -h / + + - uses: actions/upload-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: ${{ runner.temp }}/dist/ + retention-days: 7 + compression-level: 0 + + publish: + needs: [plan, build] + if: needs.plan.outputs.channel != 'none' && needs.plan.outputs.build == 'true' + runs-on: ubuntu-24.04-arm + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + CHANNEL: ${{ needs.plan.outputs.channel }} + SHA: ${{ needs.plan.outputs.sha }} + TAG_NAME: ${{ github.ref_name }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + steps: + - uses: actions/download-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: dist + + - name: Write release notes + run: | + set -euo pipefail + krel=$(cat dist/kernel.release) + cat > notes.md </dev/null 2>&1; then + # Move the channel tag to the new commit. main only moves forward, + # so this is a fast-forward of the tag; a rewritten main fails here. + gh api -X PATCH "repos/$GH_REPO/git/refs/tags/$tag" -f sha="$SHA" -F force=false >/dev/null + gh release edit "$tag" --prerelease --title "$title" --notes-file notes.md + gh release upload "$tag" dist/* --clobber + keep=$(cd dist && ls) + gh release view "$tag" --json assets -q '.assets[].name' | while read -r a; do + grep -qxF "$a" <<<"$keep" || gh release delete-asset "$tag" "$a" -y + done + else + gh release create "$tag" dist/* --target "$SHA" --prerelease --latest=false \ + --title "$title" --notes-file notes.md + fi + gh release view "$tag" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' + + - name: Publish stable release + if: needs.plan.outputs.channel == 'stable' + run: | + set -euo pipefail + if gh release view "$TAG_NAME" >/dev/null 2>&1; then + echo "::error::release $TAG_NAME already exists; stable releases are never rebuilt" + exit 1 + fi + gh release create "$TAG_NAME" dist/* --verify-tag --latest \ + --title "Aurora kernel $TAG_NAME" --notes-file notes.md --generate-notes + gh release view "$TAG_NAME" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' From 6ef20f362a51d36f9533de4e1c6504c426537ac0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:52:32 +1100 Subject: [PATCH 0924/1514] ci: run the checks on main main replaces integration/aurora as the branch work lands in, and aurora-wip is retired. Point the push and pull_request filters at main. Signed-off-by: Ryan Murray --- .github/workflows/apple-drm-kunit.yml | 2 +- .github/workflows/dt-checks.yml | 4 ++-- .github/workflows/host-tests.yml | 4 ++-- .github/workflows/mt7932-kunit.yml | 2 +- .github/workflows/pmgr-pwrstate-kunit.yml | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/apple-drm-kunit.yml b/.github/workflows/apple-drm-kunit.yml index e973618725edbd..ef74ebce5dc830 100644 --- a/.github/workflows/apple-drm-kunit.yml +++ b/.github/workflows/apple-drm-kunit.yml @@ -7,7 +7,7 @@ name: Apple DRM KUnit on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'drivers/gpu/drm/apple/**' - '.github/workflows/apple-drm-kunit.yml' diff --git a/.github/workflows/dt-checks.yml b/.github/workflows/dt-checks.yml index e823805e31ea23..056add04447b11 100644 --- a/.github/workflows/dt-checks.yml +++ b/.github/workflows/dt-checks.yml @@ -7,7 +7,7 @@ name: Device tree checks on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'arch/arm64/boot/dts/apple/**' - 'Documentation/devicetree/bindings/**' @@ -15,7 +15,7 @@ on: - 'scripts/dtc/**' - '.github/workflows/dt-checks.yml' push: - branches: [integration/aurora] + branches: [main] paths: - 'arch/arm64/boot/dts/apple/**' - 'Documentation/devicetree/bindings/**' diff --git a/.github/workflows/host-tests.yml b/.github/workflows/host-tests.yml index b67a68f3dfce3c..bba2855c0e9fb0 100644 --- a/.github/workflows/host-tests.yml +++ b/.github/workflows/host-tests.yml @@ -8,9 +8,9 @@ name: Host tests on: push: - branches: [integration/aurora, aurora-wip] + branches: [main] pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] workflow_dispatch: permissions: diff --git a/.github/workflows/mt7932-kunit.yml b/.github/workflows/mt7932-kunit.yml index 368ef703704f77..7706d39850b90b 100644 --- a/.github/workflows/mt7932-kunit.yml +++ b/.github/workflows/mt7932-kunit.yml @@ -6,7 +6,7 @@ name: MT7932 KUnit on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'drivers/net/wireless/mediatek/mt7932/**' - 'drivers/pci/controller/pcie-apple*' diff --git a/.github/workflows/pmgr-pwrstate-kunit.yml b/.github/workflows/pmgr-pwrstate-kunit.yml index 5abc669e06de35..b6fb9d396cf68d 100644 --- a/.github/workflows/pmgr-pwrstate-kunit.yml +++ b/.github/workflows/pmgr-pwrstate-kunit.yml @@ -6,7 +6,7 @@ name: PMGR power state KUnit on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main] paths: - 'drivers/pmdomain/apple/**' - 'include/linux/soc/apple/**' From 2a7855a2f190fda8b5b10fb3d949206e43aa54eb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:04:11 +1100 Subject: [PATCH 0925/1514] .github: add CODEOWNERS for release and policy files Require a review from an Owner for changes to .github/ (workflows, templates, this file), the fleet defconfig, RELEASES.md and CONTRIBUTING.md. Everything else follows the normal merge policy. Signed-off-by: Ryan Murray --- .github/CODEOWNERS | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 00000000000000..b22b22407c1d50 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,12 @@ +# Code owners for aurora-silicon/linux. +# +# Only files whose change affects every user or the release process are +# listed. Changes to them need a review from an Owner; everything else +# follows the normal merge policy: +# https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md +# Roles: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/governance-and-roles.md + +/.github/ @RyanTheTide @DjDeveloperr +/arch/arm64/configs/aurora_defconfig @RyanTheTide @DjDeveloperr +/RELEASES.md @RyanTheTide @DjDeveloperr +/CONTRIBUTING.md @RyanTheTide @DjDeveloperr From 631ad6162e3ceb4690f687250e67a32eab728c54 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:12:41 +1100 Subject: [PATCH 0926/1514] drm/asahi: advance M3 packet finish_state to TERMINAL on clean retirement When a packet with a published prefix previously hit fail_packet() (transitioning PENDING -> PACKET_FAILED) and then retires cleanly via retired() -> complete(Ok(()), true), advance finish_state to TERMINAL via swap(TERMINAL) without re-signaling the fence so a racing post-retirement scheduler timeout cannot poison VmStatus. Extend m3-packet-completion-tests to assert that finish(Err(EIO)) after cancel + retired() leaves VmStatus clear and signals once. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_submit.rs | 6 +----- tools/asahi/m3-packet-completion-tests.py | 4 ++++ 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index a16a199c55b6f7..69316c8f83e82c 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -143,11 +143,7 @@ impl Packet { }; match result { Ok(()) => { - if self - .finish_state - .compare_exchange(PENDING, TERMINAL, Ordering::AcqRel, Ordering::Acquire) - .is_err() - { + if self.finish_state.swap(TERMINAL, Ordering::AcqRel) != PENDING { return; } } diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py index b0f771723e4043..389a9f40055114 100644 --- a/tools/asahi/m3-packet-completion-tests.py +++ b/tools/asahi/m3-packet-completion-tests.py @@ -140,6 +140,10 @@ def method(source, signature): assert!(packet.vm_job.lock().is_none()); assert_eq!(packet.completion.signals.get(), 1); assert_eq!(packet.completion.error.get(), -125); + // Clean retirement closes the state to TERMINAL: a racing post-retirement fault must not poison VmStatus. + packet.finish(Err(EIO)); + assert_eq!(vm.error.get(), 0); + assert_eq!(packet.completion.signals.get(), 1); } #[test] From 940d1f1ef2bab8544f08767d2c8434a4fe26f383 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:14:17 +1100 Subject: [PATCH 0927/1514] drm/apple: fix YCbCr 4:2:2/4:4:4 PixelEncoding values and parse DownstreamFormat 4:2:0 Fix the swapped DCP PixelEncoding enum values in parser.h, expose converter DownstreamFormat YCbCr 4:2:0 modes, and complete hdr.lock coverage for color_state snapshots: - Apple DCP firmware assigns PixelEncoding=2 to 24-bpp YCbCr 4:2:2 (Score +20000, 12-bpc safe at 297 MHz / 241.5 MHz and admitted at 583.6 MHz HDMI 2.0 1440p144) and PixelEncoding=3 to 24/30/36-bpp YCbCr 4:4:4 (Score +30000, 8/10/12-bpc, 10/12-bpc unsafe at 297 MHz and excluded at 583.6 MHz). Fix DCP_COLOR_FORMAT_YCBCR422=2 and DCP_COLOR_FORMAT_YCBCR444=3 so explicit color format selection and YCbCr PQ/SDR ranking match the wire format. - Parse the optional DownstreamFormat dictionary on non-virtual ColorModes entries: when a DP-to-HDMI bridge downsamples to PixelEncoding=1 (YCbCr 4:2:0) on the downstream link (e.g. 4K60 over MCDP2900), record the entry as DCP_COLOR_FORMAT_YCBCR420 so explicit YCbCr 4:2:0 requests select it without aliasing YCbCr 4:4:4 or 4:2:2. - Synchronize the desktop 26.6 iomfb_modeset() and _dcp_poweroff() active_color/output_pq/output_hdr updates under dcp->hdr.lock to match color_state_show(). - Update apple-dcp host selftests in rate.py and display.py for the true PixelEncoding values and add a DownstreamFormat 4:2:0 fixture test. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 8 ++- drivers/gpu/drm/apple/iomfb_template.c | 22 +++---- drivers/gpu/drm/apple/parser.c | 39 +++++++++++++ drivers/gpu/drm/apple/parser.h | 4 +- .../drivers/gpu/apple-dcp/display.py | 57 ++++++++++--------- .../selftests/drivers/gpu/apple-dcp/rate.py | 53 +++++++++++++++-- 6 files changed, 134 insertions(+), 49 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 38e770070c1f3c..be584395d3f96a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5084,9 +5084,11 @@ static void _dcp_poweroff(struct apple_dcp *dcp) break; } /* The link set up again starts without HDR10 metadata. */ - dcp->active_color.score = -1; - dcp->output_pq = false; - dcp->output_hdr = false; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->active_color.score = -1; + dcp->output_pq = false; + dcp->output_hdr = false; + } dcp_hdr_metadata_forget(dcp); } diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index af7c622e0e99a9..4f052891b7674d 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -3959,16 +3959,18 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, cmode->depth, cmode->format, cmode->colorimetry, cmode->eotf, cmode->range, mode->vrr); - dcp->mode = (struct dcp_set_digital_out_mode_req) { - .color_mode_id = mode->color_mode_id, - .timing_mode_id = mode->timing_mode_id - }; - if (cmode) - dcp->active_color = *cmode; - else - dcp->active_color.score = -1; - dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; - dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req) { + .color_mode_id = mode->color_mode_id, + .timing_mode_id = mode->timing_mode_id + }; + if (cmode) + dcp->active_color = *cmode; + else + dcp->active_color.score = -1; + dcp->output_pq = cmode && cmode->eotf == DCP_EOTF_ST_2084; + dcp->output_hdr = cmode && cmode->eotf != DCP_EOTF_SDR_GAMMA; + } /* VRR modes need swap timestamps, see iomfb_flush(); so do fixed internal timings. */ dcp->use_timestamps = mode->needs_timestamps; diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 5f762e53c2bb44..39e4b2e87982c5 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -675,6 +675,34 @@ static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, *best_rank = rank; } +static int parse_downstream_pixel_encoding(struct dcp_parse_ctx *handle, + s64 *encoding) +{ + struct iterator it; + int ret; + + *encoding = -1; + ret = iterator_begin(handle, &it, true); + if (ret) + return ret; + + for (; it.idx < it.len; ++it.idx) { + char *key = parse_string(it.handle); + + if (IS_ERR(key)) + return PTR_ERR(key); + if (!strcmp(key, "PixelEncoding")) + ret = parse_int(it.handle, encoding); + else + ret = skip(it.handle); + kfree(key); + if (ret) + return ret; + } + + return 0; +} + static int parse_color_modes(struct dcp_parse_ctx *handle, struct dcp_display_mode *out, bool external_sdr, const struct timing_color_restrictions *limits, @@ -707,6 +735,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, static const char * const fields[] = { "Colorimetry", "Depth", "DynamicRange", "EOTF", "ID", "PixelEncoding", "Score", "IsVirtual" }; unsigned int seen = 0; bool is_virtual = true; + s64 downstream_encoding = -1; struct color_mode cmode = { .colorimetry = -1, .depth = -1, @@ -738,6 +767,9 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, ret = parse_int(it.handle, &cmode.colorimetry); else if (!strcmp(key, "Depth")) ret = parse_int(it.handle, &cmode.depth); + else if (!strcmp(key, "DownstreamFormat")) + ret = parse_downstream_pixel_encoding(it.handle, + &downstream_encoding); else if (!strcmp(key, "DynamicRange")) ret = parse_int(it.handle, &cmode.dynamic_range); else if (!strcmp(key, "EOTF")) @@ -774,6 +806,13 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, cmode.id > U32_MAX) continue; + /* + * DP-to-HDMI bridges downsample 4K60 YCbCr 4:4:4/4:2:2 to + * YCbCr 4:2:0 on the downstream link; expose the wire format. + */ + if (downstream_encoding == DCP_COLOR_FORMAT_YCBCR420) + cmode.pixel_encoding = DCP_COLOR_FORMAT_YCBCR420; + trace_iomfb_color_mode(handle->dcp, cmode.id, cmode.score, cmode.depth, cmode.colorimetry, cmode.eotf, cmode.dynamic_range, diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 7e276e0390c6d4..73491f2f6d89ef 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -82,8 +82,8 @@ enum dcp_color_eotf { enum dcp_color_format { DCP_COLOR_FORMAT_RGB = 0, // "RGB" DCP_COLOR_FORMAT_YCBCR420 = 1, // "YUV 4:2:0" - DCP_COLOR_FORMAT_YCBCR422 = 3, // "YUV 4:2:2" - DCP_COLOR_FORMAT_YCBCR444 = 2, // "YUV 4:4:4" + DCP_COLOR_FORMAT_YCBCR422 = 2, // "YUV 4:2:2" + DCP_COLOR_FORMAT_YCBCR444 = 3, // "YUV 4:4:4" DCP_COLOR_FORMAT_DV_NATIVE = 4, // "DolbyVision (native)" DCP_COLOR_FORMAT_DV_HDMI = 5, // "DolbyVision (HDMI)" DCP_COLOR_FORMAT_YCBCR422_DP = 6, // "YCbCr 4:2:2 (DP tunnel)" diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index b7427feb4bc267..7489f9cc66817b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -952,20 +952,21 @@ def color_selection(root): struct dcp_color_request req; struct dcp_color_mode out; - /* Populate Acer 1080p60-shaped catalog */ + /* Populate Acer 1080p60-shaped catalog (enc 3 = YCbCr444, enc 2 = YCbCr422) */ add_entry(&acer, 81, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, 0); add_entry(&acer, 82, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); - add_entry(&acer, 91, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); - add_entry(&acer, 95, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); - add_entry(&acer, 83, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); - add_entry(&acer, 84, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT601, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); - add_entry(&acer, 93, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); - add_entry(&acer, 107, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); - add_entry(&acer, 109, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 86, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 85, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); + add_entry(&acer, 84, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 83, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT601, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); + add_entry(&acer, 90, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 108, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&acer, 110, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); add_entry(&acer, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, 0); add_entry(&acer, 114, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); - add_entry(&acer, 115, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); + add_entry(&acer, 116, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); add_entry(&acer, 117, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 12, 0); + add_entry(&acer, 120, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); add_entry(&acer, 121, DCP_EOTF_BT_2100, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 10, 0); add_entry(&acer, 122, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR420, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, 0); @@ -985,51 +986,51 @@ def color_selection(root): req.broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED; assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 114 && out.range == DCP_COLOR_YCBCR_RANGE_LIMITED); - /* Explicit YCbCr 4:4:4 / 4:2:2 PQ (including 10b vs 12b DP tunnel) */ + /* Explicit YCbCr 4:4:4 (10b/12b) and 4:2:2 (plain outranks DP tunnel) PQ */ req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, - .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, .max_bpc = 12, .allow_hdr = true }; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 107); - req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.max_bpc = 10; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 115 && out.depth == 10); + .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, .max_bpc = 10, .allow_hdr = true }; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 116 && out.depth == 10); req.max_bpc = 12; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 115); /* plain 422 outranks 422_DP */ + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 120 && out.depth == 12); + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.max_bpc = 12; + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 108); /* plain 422 outranks 422_DP (110) */ /* HLG support */ req = (struct dcp_color_request){ .eotf = HDMI_EOTF_BT_2100_HLG, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, .max_bpc = 12, .allow_hdr = true }; assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 121); - /* SDR: RGB 8b Limited, RGB 10b wide-gamut BT.2020, YCbCr 4:2:2 BT.709/BT.601, YCbCr 4:2:0 */ + /* SDR: RGB 8b Limited, RGB 10b wide-gamut BT.2020, YCbCr 4:4:4 BT.709/BT.601, YCbCr 4:2:0 */ req = (struct dcp_color_request){ .broadcast_rgb = DRM_HDMI_BROADCAST_RGB_LIMITED, .max_bpc = 8 }; assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 82); req = (struct dcp_color_request){ .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, .max_bpc = 10 }; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 95); - req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 85); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR444, .colorspace = DRM_MODE_COLORIMETRY_BT709_YCC, .max_bpc = 10 }; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 93); + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 90); req.colorspace = DRM_MODE_COLORIMETRY_SMPTE_170M_YCC; req.max_bpc = 8; - assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 84); + assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 83); req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR420, .max_bpc = 8 }; assert(!dcp_select_color_mode(&acer, &req, &out) && out.id == 122); - /* MSI 1440p60-shaped timing: PQ RGB unsafe, PQ 444/422 safe -> Mutter AUTO BT2020_RGB succeeds via 444 */ + /* MSI 1440p60-shaped timing: PQ RGB/444 unsafe, PQ 422 safe -> Mutter AUTO BT2020_RGB succeeds via 422 (105) */ struct dcp_display_mode msi = { .sdr_rgb = acer.sdr_rgb, - .pq = { .score = 10, .id = 104, .eotf = DCP_EOTF_ST_2084, - .format = DCP_COLOR_FORMAT_YCBCR444, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, + .pq = { .score = 10, .id = 105, .eotf = DCP_EOTF_ST_2084, + .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 }, .color_mode_id = 81 }; - add_entry(&msi, 104, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); - add_entry(&msi, 106, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); + add_entry(&msi, 107, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422_DP, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, 0); add_entry(&msi, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE); req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB, .max_bpc = 12, .allow_hdr = true }; - assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 104); + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 105); /* Explicit PQ RGB on MSI 1440p60 MUST be rejected (only unsafe RGB exists) */ req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; assert(dcp_select_color_mode(&msi, &req, &out) == -EINVAL); - /* Explicit PQ 4:2:2 on MSI 1440p60 picks DP tunnel entry 106 */ + /* Explicit PQ 4:2:2 on MSI 1440p60 picks plain 4:2:2 (105) over DP tunnel (107) */ req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; - assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 106); + assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 105); /* Unsafe-only >340 MHz HDMI 2.0 timing (e.g. 1080p180 / 1440p144): SDR already uses unsafe * elements (sdr_usable=false, sdr_unsafe=true), so non-DSC unsafe PQ is permitted, whereas diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index d9f53d58b299a6..1243fee58f3e37 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -98,18 +98,18 @@ def color(i, score, depth, eotf, colorimetry, encoding=0, dynamic=0): pq_raw = bytearray(struct.pack(' Date: Tue, 24 Nov 2026 01:27:30 -0500 Subject: [PATCH 0928/1514] drm/asahi: g16: share device-lifetime firmware-cached compute records and work rings Match the render pass-slot command-record layout on Apple G16 by moving per-unit compute microsequences and barrier records, together with the four compute/render firmware work rings, into device-lifetime Class::FwCoherent mappings owned outside per-VM arenas. Each hardware compute unit index (0..COMPUTE_UNITS) is device-global and claimed by one flight at a time. Previously every VM's ComputeSlot allocated its own uncached seq and barrier pages, while prefix_compute hardcoded ComputeRefs::seq to the embedded sequence inside the uncached compute work image (work + 0x900) and wrote 1248 bytes of write-combined body per clean same-VM submit. The work image already names its microsequence by address (+0x760) and size (+0x768), and encode_compute_rt already emits every microsequence self-reference relative to ComputeRefs::seq. Share device-lifetime UnitCmds (seq and barrier) per hardware compute slot via resources::ComputeCmds (indexed by hw_slot so SCS sets map to the exact hardware ledger slot they claim), point ComputeRefs::seq to s.seq.va, write the 768-byte microsequence into cacheable s.seq, and shrink clean same-VM WC work writes to work[0x720..0x900]. Likewise allocate the two compute and two render work rings (host-written VA arrays, never host-read) from a ManuallyDrop device-lifetime Factory::persistent_objects_probe allocator after sealing session allocations; because Graphs::finish() runs during platform probe() before drm_dev_register(), the probe-only allocator prepares its backing against the bound platform device while non-probe private allocations keep requiring registration_guard(). Keep ComputeSlot::work in Class::Shared so host retirement reads of DESCRIPTOR_COMPLETED and 26B123 work_ticks stay strictly coherent without relying on ASC-to-AP cache clean ordering. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 18 +- drivers/gpu/drm/asahi/g16/graph.rs | 148 +++++++++++++-- drivers/gpu/drm/asahi/g16/mod.rs | 12 +- drivers/gpu/drm/asahi/g16/object.rs | 38 +++- drivers/gpu/drm/asahi/g16/resources.rs | 81 ++++++++- drivers/gpu/drm/asahi/g16/slots.rs | 67 +++++-- .../drivers/gpu/asahi-m4/test-resources.py | 170 +++++++++++++++--- 7 files changed, 449 insertions(+), 85 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index b67b6ba5b817d5..179b912db6809e 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2856,8 +2856,8 @@ 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 qualified layout. - seq: s.work.va + 0x900, + // Separate device-lifetime firmware-cached microsequence record for this unit index. + seq: s.seq.va, preempt_gva: s.preempt.gva.ok_or(EINVAL)?, its: s.its.va, stats_fw: self.init.compute_activity.va, @@ -2886,6 +2886,7 @@ impl Firmware { let rt = compute_rt(&cmd.ray, s.seeds); let scratch = self.engine.scratch.as_deref_mut().ok_or(ENOMEM)?; let w = image(&mut scratch.cw)?; + let q = image(&mut scratch.cq)?; // User results are published coherently after the complete retirement receipt. // The firmware's internal timestamp pair remains enabled. encode::encode_compute_rt( @@ -2899,9 +2900,10 @@ impl Firmware { 1, &rt, w, - image(&mut scratch.cq)?, + q, ) .map_err(|_| EINVAL)?; + s.seq.write(0, q)?; let full_work = self.slots.compute_needs_full_work(index) || before == 0; if full_work { if before != 0 { @@ -2921,14 +2923,14 @@ impl Firmware { s.work.write(0, w)?; } else { // Clean same-VM reuse: DESCRIPTOR (0xe00..0xea0) was already authenticated on - // retirement for this exact unit and VM, and static NOTIFIER (0xc00..0xd18) and - // tail (0xee0..0xf08) remain intact in place. Skip the 160-byte WC read-back and - // write only the active head and encoded body through the microsequence end. - let body_end = work::compute::SEQ_EMBEDDED + work::compute::SEQ_SIZE; + // retirement for this exact unit and VM, static NOTIFIER (0xc00..0xd18) and tail + // (0xee0..0xf08) remain intact in place, and the live microsequence lives in + // firmware-cached `s.seq`. Skip the 160-byte WC read-back and embedded sequence copy, + // writing only the active head and body before `SEQ_EMBEDDED`. s.work.write(0, &w[..work::compute::HEAD_ACTIVE_SIZE])?; s.work.write( work::compute::BODY_ACTIVE_START, - &w[work::compute::BODY_ACTIVE_START..body_end], + &w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED], )?; } let wait_render = self.cross_engine_wait(job, cmd_index, super::command::RENDER)?; diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index f23f4936ab3aa1..f5c3e8debcab16 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -14,7 +14,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, FwAbi}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; @@ -126,23 +126,55 @@ pub(crate) struct ComputeGraph { pub(crate) fw_stamp: Arc, } -struct QueueObjects { +struct QueueSession { qinfo: Arc, qstate: Arc, - ring: Arc, user_stamp: Arc, fw_stamp: Arc, } -impl QueueObjects { +impl QueueSession { fn new(o: &mut Objects) -> Result { Ok(Self { qinfo: alloc(o, qinfo::SIZE, graph_fw(), None, 0, false)?, qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, - ring: alloc(o, sizes::QUEUE_CAP as usize * 8, cmd_fw(), None, 0, false)?, user_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, fw_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, }) } + /// Completes the queue with its firmware-cached work ring from a device-lifetime + /// [`Factory::persistent_objects`] allocator. The host only writes 64-bit work/barrier VAs + /// into the ring before advancing the uncached `qstate::WRITE` producer and never reads + /// back firmware writes, matching macOS 26B123's `0x443` command-ring mapping. + fn finish(self, rings: &mut Objects) -> Result { + Ok(QueueObjects { + qinfo: self.qinfo, + qstate: self.qstate, + ring: alloc( + rings, + sizes::QUEUE_CAP as usize * 8, + Class::FwCoherent, + None, + 0, + false, + )?, + user_stamp: self.user_stamp, + fw_stamp: self.fw_stamp, + }) + } +} + +struct QueueObjects { + qinfo: Arc, + qstate: Arc, + ring: Arc, + user_stamp: Arc, + fw_stamp: Arc, +} +impl QueueObjects { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects) -> Result { + QueueSession::new(o)?.finish(rings) + } } fn init_queue( @@ -173,14 +205,30 @@ fn init_notifier(page: &FwObject, threshold: &FwObject) -> Result { Ok(()) } -impl ComputeGraph { +struct ComputeGraphSession { + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: Arc, + q: QueueSession, +} +impl ComputeGraphSession { fn new(o: &mut Objects, sched_ctx: Arc) -> Result { - let q = QueueObjects::new(o)?; Ok(Self { sched_ctx, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, + q: QueueSession::new(o)?, + }) + } + fn finish(self, rings: &mut Objects) -> Result { + let q = self.q.finish(rings)?; + Ok(ComputeGraph { + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, qscratch: q.qinfo.clone(), qinfo: q.qinfo, qstate: q.qstate, @@ -189,6 +237,13 @@ impl ComputeGraph { fw_stamp: q.fw_stamp, }) } +} + +impl ComputeGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, sched_ctx: Arc) -> Result { + ComputeGraphSession::new(o, sched_ctx)?.finish(rings) + } fn init(&self, abi: FwAbi, init_ctx: bool) -> Result { if init_ctx { self.sched_ctx.write(0, &graph::context_image())?; @@ -226,16 +281,21 @@ pub(crate) struct RenderGraph { pub(crate) legacy_empty: Arc, pub(crate) registration_barrier: Arc, } -impl RenderGraph { +struct RenderGraphSession { + ta: QueueSession, + fs: QueueSession, + sched_ctx: Arc, + notifier: Arc, + threshold: Arc, + job_list: [Arc; 2], + legacy_empty: Arc, + registration_barrier: Arc, +} +impl RenderGraphSession { fn new(o: &mut Objects, context: Arc) -> Result { - let [ta, fs] = [QueueObjects::new(o)?, QueueObjects::new(o)?]; Ok(Self { - qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], - qinfo: [ta.qinfo, fs.qinfo], - qstate: [ta.qstate, fs.qstate], - ring: [ta.ring, fs.ring], - user_stamp: [ta.user_stamp, fs.user_stamp], - fw_stamp: [ta.fw_stamp, fs.fw_stamp], + ta: QueueSession::new(o)?, + fs: QueueSession::new(o)?, sched_ctx: context, notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, @@ -254,6 +314,30 @@ impl RenderGraph { )?, }) } + fn finish(self, rings: &mut Objects) -> Result { + let [ta, fs] = [self.ta.finish(rings)?, self.fs.finish(rings)?]; + Ok(RenderGraph { + qscratch: [ta.qinfo.clone(), fs.qinfo.clone()], + qinfo: [ta.qinfo, fs.qinfo], + qstate: [ta.qstate, fs.qstate], + ring: [ta.ring, fs.ring], + user_stamp: [ta.user_stamp, fs.user_stamp], + fw_stamp: [ta.fw_stamp, fs.fw_stamp], + sched_ctx: self.sched_ctx, + notifier: self.notifier, + threshold: self.threshold, + job_list: self.job_list, + legacy_empty: self.legacy_empty, + registration_barrier: self.registration_barrier, + }) + } +} + +impl RenderGraph { + #[allow(dead_code)] + fn new(o: &mut Objects, rings: &mut Objects, context: Arc) -> Result { + RenderGraphSession::new(o, context)?.finish(rings) + } fn init(&self, abi: FwAbi) -> Result { init_notifier(&self.notifier, &self.threshold)?; for e in 0..2 { @@ -272,26 +356,52 @@ impl RenderGraph { } } +/// Session-side queue graph allocations before sealing the session allocator and attaching +/// the firmware-cached work rings from a probe-time device-lifetime +/// [`Factory::persistent_objects_probe`] pool. +pub(crate) struct GraphSession { + compute: [ComputeGraphSession; sizes::COMPUTE_PIPES], + render: RenderGraphSession, +} + pub(crate) struct Graphs { pub(crate) dev: ARef, pub(crate) compute: [ComputeGraph; sizes::COMPUTE_PIPES], pub(crate) render: RenderGraph, + /// Owns the firmware-cached work rings for the device lifetime (never dropped). + _ring_objects: core::mem::ManuallyDrop, } impl Graphs { #[inline(never)] - pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { + pub(crate) fn prepare(o: &mut Objects) -> Result { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. let sched_ctx = alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?; let compute = [ - ComputeGraph::new(o, sched_ctx.clone())?, - ComputeGraph::new(o, sched_ctx.clone())?, + ComputeGraphSession::new(o, sched_ctx.clone())?, + ComputeGraphSession::new(o, sched_ctx.clone())?, ]; - let render = RenderGraph::new(o, sched_ctx)?; + let render = RenderGraphSession::new(o, sched_ctx)?; + Ok(GraphSession { compute, render }) + } + + #[inline(never)] + pub(crate) fn finish( + dev: &AsahiDrmDevice, + session: GraphSession, + factory: &Factory, + ) -> Result { + // Never dropped even on partial failure: ASC-cached mappings have no qualified teardown. + let mut ring_objects = core::mem::ManuallyDrop::new(factory.persistent_objects_probe()); + let [c0, c1] = session.compute; + let compute = [c0.finish(&mut ring_objects)?, c1.finish(&mut ring_objects)?]; + let render = session.render.finish(&mut ring_objects)?; + ring_objects.finish_private()?; Ok(Self { dev: dev.as_ref().as_ref().into(), compute, render, + _ring_objects: ring_objects, }) } } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2dedd2d48c3b69..7c7851ee6068a9 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -749,16 +749,19 @@ impl Firmware { ); power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut booted.objects)?; + let graph_session = graph::Graphs::prepare(&mut booted.objects)?; let slots = slots::Slots::new()?; let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; let render_cmds = resources::RenderCmds::new()?; + let compute_cmds = resources::ComputeCmds::new()?; + let private_factory = booted.objects.private_factory(render_cmds, compute_cmds); + let graph = graph::Graphs::finish(dev, graph_session, &private_factory)?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, slots, pools, vms, engine, render_cmds, slot)) + Ok((graph, private_factory, slots, pools, vms, engine, slot)) })(); - let (graph, slots, pools, vms, engine, render_cmds, slot) = match backend { + let (graph, private_factory, slots, pools, vms, engine, slot) = match backend { Ok(backend) => backend, Err(error) => { dev_err!( @@ -773,12 +776,11 @@ impl Firmware { let boot::Booted { session, init, - mut objects, + objects, channels, events, .. } = KBox::into_inner(booted); - let private_factory = objects.private_factory(render_cmds); let mut firmware = slot .write_init(init!(Firmware { session, diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index c4c42d1dd1290f..490543a28d4033 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -352,6 +352,7 @@ pub(crate) struct Factory { window: Arc>, firmware: core::ops::Range, render_cmds: Arc, + compute_cmds: Arc, } impl Factory { @@ -367,6 +368,7 @@ impl Factory { }), sealed: false, persistent: false, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -389,6 +391,7 @@ impl Factory { }), sealed: false, persistent: false, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -413,6 +416,7 @@ impl Factory { }), sealed: false, persistent: true, + probe: false, fw_next: self.firmware.start, retained: KVec::new(), clients: KVec::new(), @@ -422,11 +426,26 @@ impl Factory { } } + /// Probe-time variant of [`Self::persistent_objects`], called only from + /// [`super::graph::Graphs::finish`] during platform `probe()` before `drm_dev_register()` + /// makes `registration_guard()` available. + pub(crate) fn persistent_objects_probe(&self) -> Objects { + let mut objects = self.persistent_objects(); + objects.probe = true; + objects + } + /// The device-lifetime render command records of pass slot `k`, shared by every VM's /// [`super::slots::PassSlot`] `k`. pub(crate) fn pass_cmds(&self, k: usize) -> Result { self.render_cmds.get(self, k) } + + /// The device-lifetime compute command records of hardware compute unit `k`, shared by every + /// VM's [`super::slots::ComputeSlot`] bound to hardware unit `k`. + pub(crate) fn compute_cmds(&self, k: usize) -> Result { + self.compute_cmds.get(self, k) + } } /// The firmware object allocator and the set of retained objects. @@ -439,6 +458,8 @@ pub(crate) struct Objects { sealed: bool, /// A device-lifetime allocator that may map [`Class::FwCoherent`] records. persistent: bool, + /// Runs during platform `probe()` before `drm_dev_register()` provides `registration_guard()`. + probe: bool, /// Next free VA of the firmware allocator window. fw_next: u64, /// Every object owned by this session or private arena. @@ -468,6 +489,7 @@ impl Objects { private: None, sealed: false, persistent: false, + probe: false, fw_next: hw::va::FW_ALLOC.start, retained: KVec::new(), clients: KVec::new(), @@ -481,6 +503,7 @@ impl Objects { pub(crate) fn private_factory( &mut self, render_cmds: Arc, + compute_cmds: Arc, ) -> Factory { self.sealed = true; Factory { @@ -489,6 +512,7 @@ impl Objects { window: self.window.clone(), firmware: self.fw_next..hw::va::FW_ALLOC.end, render_cmds, + compute_cmds, } } @@ -546,9 +570,17 @@ impl Objects { } else { gem::new_kernel_object_wc(&self.dev, bytes)? }; - let registered = self.dev.registration_guard().ok_or(ENODEV)?; - let parent: &kernel::platform::Device = registered.as_ref(); - gem::prepare_new_object(&backing.gem, parent.as_ref())?; + if self.probe { + // SAFETY: `Factory::persistent_objects_probe()` is called only from + // `Graphs::finish()` during platform `probe()`, while the platform device is + // bound and before `drm_dev_register()` makes `registration_guard()` available. + let bound = unsafe { self.dev.as_ref().as_ref().as_bound() }; + gem::prepare_new_object(&backing.gem, bound)?; + } else { + let registered = self.dev.registration_guard().ok_or(ENODEV)?; + let parent: &kernel::platform::Device = registered.as_ref(); + gem::prepare_new_object(&backing.gem, parent.as_ref())?; + } let clean = req.class == Class::FwCoherent && req.lower.is_some(); let cpu = if req.cpu { let vmap = backing.vmap()?; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 25b0d609a3d2a1..0961b97b389035 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -9,7 +9,7 @@ use super::{ command::Command, object::{Factory, Objects}, pools::{PbEpoch, PoolSet}, - slots::{ComputeSlot, PassCmds, PassSlot, Placement}, + slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, }; use crate::mmu; @@ -75,6 +75,60 @@ impl RenderCmds { } } +/// One hardware compute unit's device-lifetime command records and the allocator that maps +/// them. The allocator is never dropped for the same reason as [`PersistentPassCmds`]. +struct PersistentUnitCmds { + objects: core::mem::ManuallyDrop, + cmds: Option, +} + +/// The firmware-cached compute command records (microsequence and barrier records) of every +/// hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until reboot. A +/// hardware compute unit is device-global and claimed by one flight at a time, so every VM's +/// [`ComputeSlot`] bound to hardware unit `k` shares its records, and closing a VM drops no +/// firmware-cached mapping. +#[pin_data] +pub(crate) struct ComputeCmds { + #[pin] + sets: Mutex<[Option>; super::hw::sizes::COMPUTE_UNITS]>, +} + +impl ComputeCmds { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + sets <- new_mutex!( + [const { None }; super::hw::sizes::COMPUTE_UNITS], + "g16::compute_cmds" + ), + }), + GFP_KERNEL, + ) + } + + /// The records of hardware compute unit `k`, allocated from `factory` on first use. + pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { + let mut sets = self.sets.lock(); + let entry = sets.get_mut(k).ok_or(EINVAL)?; + if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { + return Ok(cmds.clone()); + } + let mut set = KBox::new( + PersistentUnitCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + cmds: None, + }, + GFP_KERNEL, + )?; + // From here on a failure leaks the allocator with whatever it mapped. + let cmds = UnitCmds::new(&mut set.objects)?; + set.objects.finish_private()?; + set.cmds = Some(cmds.clone()); + *entry = Some(set); + Ok(cmds) + } +} + /// 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 @@ -114,18 +168,21 @@ impl ComputeArena { pub(crate) fn seeds(&self) -> u32 { self.unit.seeds } - /// Allocates one self-contained compute unit `k` (its index and `placement` fix its client - /// addresses; the index fixes its hardware UMA slot). + /// Allocates one self-contained compute unit at local VA index `local` bound to device-wide + /// hardware ledger slot `hw_slot` (`local` and `placement` fix its client addresses; `hw_slot` + /// selects its shared device-lifetime command records). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - k: usize, + local: usize, + hw_slot: usize, placement: Placement, ) -> Result> { + let cmds = factory.compute_cmds(hw_slot)?; let mut objects = factory.objects(vm); - let unit = ComputeSlot::new_in(&mut objects, factory, k as u64, placement)?; + let unit = ComputeSlot::new_in(&mut objects, factory, local as u64, placement, &cmds)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { @@ -164,7 +221,7 @@ impl ComputeUnitSet { let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; for k in range { units.push( - ComputeArena::new(factory, bind, vm, live, k, placement)?, + ComputeArena::new(factory, bind, vm, live, k, k, placement)?, GFP_KERNEL, )?; } @@ -187,9 +244,17 @@ impl ComputeUnitSet { seeds: u32, ) -> Result> { let mut units = KVec::with_capacity(super::hw::sizes::SCS_COMPUTE_UNITS, GFP_KERNEL)?; - for local in 0..super::hw::sizes::SCS_COMPUTE_UNITS { + for (local, &hw_slot) in hw_slots.iter().enumerate() { units.push( - ComputeArena::new(factory, bind, vm, live, local, Placement::Scs { seeds })?, + ComputeArena::new( + factory, + bind, + vm, + live, + local, + hw_slot, + Placement::Scs { seeds }, + )?, GFP_KERNEL, )?; } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index f6952828e1ecaf..697598889f1f72 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -12,12 +12,44 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; -use super::fw::work::{barrier, fs, ta}; -use super::graph::{alloc, alloc_work, cmd_fw, Client}; +use super::fw::work::{barrier, compute, fs, ta}; +use super::graph::{alloc, alloc_work, Client}; use super::hw::{client, sizes}; use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; +/// The compute command records of one hardware compute unit index (microsequence and barrier +/// records), shared by every VM's [`ComputeSlot`] bound to that hardware unit: the unit index +/// is device-global and claimed by one flight at a time. The host writes them before +/// publication and never reads back what the firmware writes, so they take the firmware-cached +/// [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command objects, with no client +/// or lower alias. +#[derive(Clone)] +pub(crate) struct UnitCmds { + pub(crate) seq: Arc, + pub(crate) barrier: Arc, +} + +impl UnitCmds { + /// Allocates one compute unit index's command records from a device-lifetime allocator + /// ([`Factory::persistent_objects`]), which the caller never drops. + pub(crate) fn new(o: &mut Objects) -> Result { + let coherent = Class::FwCoherent; + Ok(Self { + seq: alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?, + // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. + barrier: alloc( + o, + barrier::SIZE * sizes::COMPUTE_PIPES, + coherent, + None, + 0, + false, + )?, + }) + } +} + /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. pub(crate) struct ComputeSlot { pub(crate) its: Arc, @@ -149,16 +181,23 @@ pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: impl ComputeSlot { #[allow(dead_code)] - pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { - Self::new_in(o, fw_factory, k, Placement::Base) + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + cmds: &UnitCmds, + ) -> Result { + Self::new_in(o, fw_factory, k, Placement::Base, cmds) } - /// Unit `k` at `placement`. + /// Unit `k` at `placement`, around the device-lifetime command records `cmds` of its + /// hardware ledger slot. pub(crate) fn new_in( o: &mut Objects, fw_factory: &Factory, k: u64, placement: Placement, + cmds: &UnitCmds, ) -> Result { placement.check()?; let sh = Class::Shared; @@ -178,16 +217,8 @@ impl ComputeSlot { false, )?, work, - seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, - // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. - barrier: alloc( - o, - barrier::SIZE * sizes::COMPUTE_PIPES, - cmd_fw(), - None, - 0, - false, - )?, + seq: cmds.seq.clone(), + barrier: cmds.barrier.clone(), pool: o.alloc(super::object::Request { size: placement.pool_bytes(), class: sh, @@ -249,9 +280,9 @@ impl ComputeSlot { /// 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. + /// checks cannot observe stale ticks; `work` and `seq` are overwritten 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 { 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 2df865d4f856aa..dd7931881e3f49 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -119,21 +119,29 @@ def module(text, name): pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} pub fn fw_objects(&self)->Objects{Objects::new()} pub fn persistent_objects(&self)->Objects{Objects::persistent()} + pub fn persistent_objects_probe(&self)->Objects{Objects::persistent()} } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} pub struct Objects{pub objects:Vec>,pub persistent:bool} - // Device-lifetime render records of each pass slot index, per test thread (the - // production table is resources::RenderCmds): one never-dropped allocator owns them. + // Device-lifetime render and compute command records, per test thread (the production + // tables are resources::RenderCmds and resources::ComputeCmds): one never-dropped + // allocator owns them. std::thread_local!{ pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + pub static UNIT_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; } pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::PassCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); PASS_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c } + pub fn test_unit_cmds(k:u64)->crate::g16::slots::UnitCmds{ + if let Some(c)=UNIT_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::UnitCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + UNIT_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c + } impl Objects{ pub fn new()->Self{Self{objects:vec![],persistent:false}} pub fn persistent()->Self{Self{objects:vec![],persistent:true}} @@ -287,7 +295,7 @@ def module(text, name): fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); let f=g16::object::Factory; - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k,&crate::g16::object::test_unit_cmds(k)).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o, k, 1, &crate::g16::object::test_cmds((k) as u64)).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None,hw_slots:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' +engine_source = (production/'engine.rs').read_text() +prefix_compute_fn = item(engine_source, 'fn prefix_compute(') +assert 'seq: s.seq.va,' in prefix_compute_fn, 'prefix_compute must point ComputeRefs::seq at firmware-cached s.seq' +assert 's.seq.write(0, q)?;' in prefix_compute_fn, 'prefix_compute must write encoded sequence into s.seq' +assert '&w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED]' in prefix_compute_fn, 'clean compute reuse must skip embedded sequence copy into WC work' +graphs_finish_fn = item(graph_source, 'pub(crate) fn finish(') +assert 'core::mem::ManuallyDrop::new(factory.persistent_objects_probe())' in graphs_finish_fn, 'Graphs::finish must keep probe-time FwCoherent ring allocator in ManuallyDrop' +assert 'ring_objects.finish_private()?;' in graphs_finish_fn, 'Graphs::finish must publish persistent ring mappings' +alloc_private_in_fn = item(object_source, 'fn alloc_private_in(') +assert 'pub(crate) fn persistent_objects_probe(&self) -> Objects' in object_source, 'Factory must expose persistent_objects_probe for probe-time work rings' +assert 'if self.probe {' in alloc_private_in_fn and 'self.dev.registration_guard().ok_or(ENODEV)?' in alloc_private_in_fn, 'alloc_private_in must gate as_bound() on self.probe and keep registration_guard() otherwise' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -2903,12 +3019,18 @@ def module(text, name): item(graph_source, decl) for decl in ( 'pub(crate) struct ComputeGraph {', + 'struct QueueSession {', + 'impl QueueSession {', 'struct QueueObjects {', 'impl QueueObjects {', 'fn init_queue(', 'fn init_notifier(', + 'struct ComputeGraphSession {', + 'impl ComputeGraphSession {', 'impl ComputeGraph {', 'pub(crate) struct RenderGraph {', + 'struct RenderGraphSession {', + 'impl RenderGraphSession {', 'impl RenderGraph {', ) ).replace('fn new(', 'pub(crate) fn new(').replace('fn init(', 'pub(crate) fn init(') From 3e0e4f6d4f2883001192c04b681e408c7563ff00 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 01:31:20 -0500 Subject: [PATCH 0929/1514] drm/asahi: g16: avoid unaligned byte WC reads on compute retirement Compute retirement checks DESCRIPTOR_COMPLETED (0xe54) and DESCRIPTOR_COUNTER (0xe4c) via FwObject::r64(). Both packed fields are 4-byte aligned (offset % 8 == 4), which previously bypassed the 8-byte fast path and fell through to FwObject::read()'s byte loop, issuing 16 single-byte write-combined loads and 4 read barriers per call (32 byte loads and 8 barriers per retired compute command). Add a 4-byte-aligned fast path in FwObject::r64() that reads matched aligned 32-bit word pairs separated by rmb(), preserving the exact tear-free double-snapshot and EAGAIN retry semantics while cutting each 4-byte-aligned receipt check to 4 aligned 32-bit loads. In Firmware::compute_ticks_with(), also read ABI-defined work_ticks before falling back to unit.its. On 26B123, firmware leaves unit.its zeroed and records compute GPU ticks in work_ticks, so probing work_ticks first avoids two always-zero WC r64 reads and two read barriers per compute command while preserving the ITS fallback and 25G83 behavior. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/object.rs | 24 +++ drivers/gpu/drm/asahi/g16/poll.rs | 42 ++-- .../drivers/gpu/asahi-m4/test-timestamps.py | 198 ++++++++++++++++-- 3 files changed, 231 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 490543a28d4033..080d21522921b6 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -272,6 +272,30 @@ impl FwObject { // SAFETY: ptr() bounds this naturally aligned 64-bit volatile receipt. return Ok(u64::from_le(unsafe { (p as *const u64).read_volatile() })); } + if p as usize % 4 == 0 { + // Packed 64-bit firmware fields such as compute::DESCRIPTOR_COUNTER (0xe4c) and + // DESCRIPTOR_COMPLETED (0xe54) are 4-byte aligned. Read aligned 32-bit word pairs + // rather than falling through to 16 single-byte WC loads in self.read(). + let pair = |words: *const u32| -> (u32, u32) { + rmb(); + // SAFETY: ptr() bounds 8 bytes and `words` is 4-byte aligned. + let lo = u32::from_le(unsafe { words.read_volatile() }); + // SAFETY: `words.add(1)` stays within the 8-byte range and is 4-byte aligned. + let hi = u32::from_le(unsafe { words.add(1).read_volatile() }); + (lo, hi) + }; + let words = p.cast::(); + let mut first = pair(words); + for _ in 0..3 { + let next = pair(words); + if first == next { + rmb(); + return Ok(u64::from(next.0) | (u64::from(next.1) << 32)); + } + first = next; + } + return Err(EAGAIN); + } let mut first = [0u8; 8]; let mut next = [0u8; 8]; self.read(offset, &mut first)?; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 2fca6c71513e64..78b4415f27e42d 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -917,8 +917,9 @@ impl Firmware { } /// 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. + /// ABIs with `work_ticks` leave ITS 0/0 and write them into the work object. Check + /// `work_ticks` first when the ABI defines them so 26B123 skips two always-zero WC reads + /// per command, falling back to ITS if `work_ticks` holds no interval. fn compute_ticks(&self, unit: &super::slots::ComputeSlot) -> Result<(u64, u64)> { Self::compute_ticks_with(self.init.abi.compute().work_ticks, unit) } @@ -927,27 +928,26 @@ impl Firmware { work_ticks: Option<(usize, usize)>, 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)) = 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)); + if let Some((start_off, end_off)) = work_ticks { + 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) + }; + let (start, end) = (at(start_off)?, at(end_off)?); + if start != 0 && end >= start { + return Ok((start, end)); } - Err(EIO) - }; - Ok((at(start_off)?, at(end_off)?)) + } + Ok((unit.its.r64(0)?, unit.its.r64(8)?)) } /// Exact queue-ring proof for one serialized publication on its workqueue pipe. 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 f0e9c9ffb0d4ca..06b87ba9ef64bb 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -22,6 +22,7 @@ def function(source, marker): mmu = (backend / 'mmu.rs').read_text() shared = (backend / 'timestamp.rs').read_text() poll = (backend / 'g16/poll.rs').read_text() +obj = (backend / 'g16/object.rs').read_text() cache_policy = function((backend / 'gem.rs').read_text(), 'pub(crate) fn is_writeback(') store = function(mmu, 'pub(crate) fn write(&self, value: u64)') vmap_store = function(mmu, 'pub(crate) fn write(&self, offset: usize, value: u64)') @@ -31,6 +32,8 @@ def function(source, marker): retire = function(poll, 'fn publish_timestamps(&self, flight: &Flight, claims: &super::slots::Claims)') compute_ticks = function(poll, 'fn compute_ticks(&self, unit: &super::slots::ComputeSlot)') compute_ticks_with = function(poll, 'fn compute_ticks_with(') +fw_r64 = function(obj, 'pub(crate) fn r64(&self, offset: usize)') +fw_read = function(obj, 'pub(crate) fn read(&self, offset: usize, out: &mut [u8])') source = r''' #![allow(dead_code)] use core::sync::atomic::{AtomicU8, AtomicU64, Ordering, fence as barrier}; @@ -161,12 +164,40 @@ def function(source, marker): pub struct Render{pub timestamp_outputs:Destinations} pub enum Command{Compute(Compute),Render(Render)} } - pub struct Cells(pub [u64;4]);impl Cells{ - pub fn r64(&self,offset:usize)->Result{ - match offset{0=>Ok(self.0[0]),8=>Ok(self.0[1]),0x600=>Ok(self.0[0]),0x608=>Ok(self.0[1]),0x620=>Ok(self.0[2]),0x628=>Ok(self.0[3]),_=>Err(EINVAL)} + pub struct Cells { + pub vals: [u64; 4], + pub r64_calls: std::cell::Cell, + pub r32_calls: std::cell::Cell, + } + impl Cells { + pub fn new(vals: [u64; 4]) -> Self { + Self { + vals, + r64_calls: std::cell::Cell::new(0), + r32_calls: std::cell::Cell::new(0), + } + } + pub fn r64(&self, offset: usize) -> Result { + self.r64_calls.set(self.r64_calls.get() + 1); + match offset { + 0 => Ok(self.vals[0]), + 8 => Ok(self.vals[1]), + 0x600 => Ok(self.vals[0]), + 0x608 => Ok(self.vals[1]), + 0x620 => Ok(self.vals[2]), + 0x628 => Ok(self.vals[3]), + _ => Err(EINVAL), + } } - pub fn r32(&self,offset:usize)->Result{ - let v=match offset{0x100=>self.0[0],0x104=>self.0[0]>>32,0x108=>self.0[1],0x10c=>self.0[1]>>32,_=>return Err(EINVAL)}; + pub fn r32(&self, offset: usize) -> Result { + self.r32_calls.set(self.r32_calls.get() + 1); + let v = match offset { + 0x100 => self.vals[0], + 0x104 => self.vals[0] >> 32, + 0x108 => self.vals[1], + 0x10c => self.vals[1] >> 32, + _ => return Err(EINVAL), + }; Ok(v as u32) } } @@ -195,11 +226,11 @@ def function(source, marker): fn firmware()->Firmware{Firmware{slots:Slots{scrub:Scrub{compute:vec![],passes:vec![]}},init:Init{abi:Abi{compute:ComputeAbi{work_ticks:None}}}}} fn resources()->Resources{Resources{ compute:vec![ - Compute{its:Cells([10,20,0,0]),work:Cells([0,0,0,0])}, - Compute{its:Cells([30,40,0,0]),work:Cells([0,0,0,0])}, - Compute{its:Cells([50,60,0,0]),work:Cells([0,0,0,0])}, + Compute{its:Cells::new([10,20,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([30,40,0,0]),work:Cells::new([0,0,0,0])}, + Compute{its:Cells::new([50,60,0,0]),work:Cells::new([0,0,0,0])}, ], - passes:vec![Pass{scene:Cells([100,200,300,400])},Pass{scene:Cells([500,600,700,800])},Pass{scene:Cells([900,1000,1100,1200])}] + passes:vec![Pass{scene:Cells::new([100,200,300,400])},Pass{scene:Cells::new([500,600,700,800])},Pass{scene:Cells::new([900,1000,1100,1200])}] }} #[test]fn retirement_uses_claimed_hardware_cells_and_endpoint_order(){ let compute=backing();let render=backing(); @@ -276,8 +307,8 @@ def function(source, marker): fw.init.abi.compute.work_ticks=Some((0x100,0x108)); let res=Resources{ compute:vec![ - Compute{its:Cells([0,0,0,0]),work:Cells([0x1_0000_0070,0x1_0000_0090,0,0])}, - Compute{its:Cells([0,0,0,0]),work:Cells([0x2_0000_0010,0x2_0000_0040,0,0])}, + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x1_0000_0070,0x1_0000_0090,0,0])}, + Compute{its:Cells::new([0,0,0,0]),work:Cells::new([0x2_0000_0010,0x2_0000_0040,0,0])}, ], passes:vec![], }; @@ -291,8 +322,151 @@ def function(source, marker): fw.publish_timestamps(&flight,&claims).unwrap(); assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); + // 26B123 work_ticks-first path must skip redundant ITS WC reads when work ticks are valid. + assert_eq!(flight.job.resources.compute[0].its.r64_calls.get(), 0); + assert_eq!(flight.job.resources.compute[1].its.r64_calls.get(), 0); + // When work_ticks holds no interval (0/0), fall back to ITS cleanly. + let fallback_unit = Compute { + its: Cells::new([0x300, 0x400, 0, 0]), + work: Cells::new([0, 0, 0, 0]), + }; + assert_eq!(fw.compute_ticks(&fallback_unit), Ok((0x300, 0x400))); + assert_eq!(fallback_unit.its.r64_calls.get(), 2); + // 25G83 (work_ticks = None) reads ITS directly with zero work reads. + let fw25 = firmware(); + let unit25 = Compute { + its: Cells::new([0x500, 0x600, 0, 0]), + work: Cells::new([0x700, 0x800, 0, 0]), + }; + assert_eq!(fw25.compute_ticks(&unit25), Ok((0x500, 0x600))); + assert_eq!(unit25.its.r64_calls.get(), 2); + assert_eq!(unit25.work.r32_calls.get(), 0); +} +mod r64_scope { + use super::{Result, EINVAL}; + use std::cell::Cell; + use std::sync::atomic::{AtomicU32, Ordering}; + const EAGAIN: i32 = -11; + thread_local! { + static RMB_COUNT: Cell = const { Cell::new(0) }; + static MUTATE_HOOK: Cell> = const { Cell::new(None) }; + } + fn rmb() { + RMB_COUNT.with(|c| c.set(c.get() + 1)); + std::sync::atomic::fence(Ordering::SeqCst); + if let Some(hook) = MUTATE_HOOK.with(|h| h.get()) { + hook(); + } + } + #[repr(C, align(8))] + struct Buf([u8; 32]); + struct FwObject { + ptr: *mut u8, + len: usize, + read_calls: Cell, + } + impl FwObject { + fn ptr(&self, offset: usize, len: usize) -> Result<*mut u8> { + if offset.checked_add(len).is_none_or(|e| e > self.len) { + return Err(EINVAL); + } + Ok(unsafe { self.ptr.add(offset) }) + } + fn read_impl(&self, offset: usize, out: &mut [u8]) -> Result { + self.read_calls.set(self.read_calls.get() + 1); + self.read_prod(offset, out) + } + __FW_READ__ + __FW_R64__ + } + #[test] + fn r64_4byte_aligned_uses_word_pairs_handles_carry_and_rejects_churn() { + let mut buf = Buf([0u8; 32]); + let val_a: u64 = 0x1122_3344_5566_7788; + let val_b: u64 = 0x0123_4567_89ab_cdef; + let val_c: u64 = 0xfedc_ba98_7654_3210; + buf.0[0..8].copy_from_slice(&val_a.to_le_bytes()); + buf.0[4 + 8..4 + 16].copy_from_slice(&val_b.to_le_bytes()); + buf.0[21..29].copy_from_slice(&val_c.to_le_bytes()); + let obj = FwObject { + ptr: buf.0.as_mut_ptr(), + len: buf.0.len(), + read_calls: Cell::new(0), + }; + // 8-byte aligned: single volatile u64 + 1 rmb, never calls byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(0), Ok(val_a)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 1); + // 4-byte aligned (matching compute::DESCRIPTOR_COUNTER 0xe4c / COMPLETED 0xe54): + // uses 32-bit word pairs (3 rmbs), never falls back to byte read(). + RMB_COUNT.with(|c| c.set(0)); + assert_eq!(obj.r64(12), Ok(val_b)); + assert_eq!(obj.read_calls.get(), 0); + assert_eq!(RMB_COUNT.with(|c| c.get()), 3); + // Unaligned (offset % 4 != 0): still uses read() double-snapshot fallback. + assert_eq!(obj.r64(21), Ok(val_c)); + assert_eq!(obj.read_calls.get(), 2); + // Actively mutating 4-byte-aligned receipt returns EAGAIN instead of a torn word. + static TARGET: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static TICK: AtomicU32 = AtomicU32::new(0); + fn bump() { + let p = TARGET.load(Ordering::Relaxed); + if !p.is_null() { + let n = TICK.fetch_add(1, Ordering::Relaxed); + unsafe { p.write_volatile(n) }; + } + } + TARGET.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(bump))); + assert_eq!(obj.r64(12), Err(EAGAIN)); + MUTATE_HOOK.with(|h| h.set(None)); + TARGET.store(core::ptr::null_mut(), Ordering::Relaxed); + // Torn carry-wrap snapshot recovery: snapshot 1 sees LOW_WRAP, snapshot 2 sees torn + // (0xffff_ffff, 1), snapshots 3 & 4 see settled HIGH_WRAP -> returns HIGH_WRAP. + const LOW_WRAP: u64 = 0x0000_0000_ffff_ffff; + const HIGH_WRAP: u64 = 0x0000_0001_0000_0000; + static WRAP_PTR: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); + static WRAP_STEP: AtomicU32 = AtomicU32::new(0); + fn step_wrap() { + let p = WRAP_PTR.load(Ordering::Relaxed); + if p.is_null() { + return; + } + match WRAP_STEP.fetch_add(1, Ordering::Relaxed) { + 0 => { + unsafe { + p.write_volatile(LOW_WRAP as u32); + p.add(1).write_volatile((LOW_WRAP >> 32) as u32); + } + } + 1 => { + // Torn intermediate across the 32-bit carry boundary. + unsafe { + p.write_volatile(0xffff_ffff); + p.add(1).write_volatile(1); + } + } + _ => { + unsafe { + p.write_volatile(HIGH_WRAP as u32); + p.add(1).write_volatile((HIGH_WRAP >> 32) as u32); + } + } + } + } + WRAP_STEP.store(0, Ordering::Relaxed); + WRAP_PTR.store(unsafe { buf.0.as_mut_ptr().add(12).cast::() }, Ordering::Relaxed); + MUTATE_HOOK.with(|h| h.set(Some(step_wrap))); + assert_eq!(obj.r64(12), Ok(HIGH_WRAP)); + MUTATE_HOOK.with(|h| h.set(None)); + WRAP_PTR.store(core::ptr::null_mut(), Ordering::Relaxed); + assert_eq!(obj.read_calls.get(), 2); + } } -'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')) +'''.replace('__CHECKED_OFFSET__', checked_offset).replace('__STORE__', store).replace('__VMAP_STORE__', vmap_store.replace('.timestamp_lock.lock()', '.timestamp_lock.lock().unwrap()')).replace('__CACHE_POLICY__', cache_policy).replace('__WRITE__', write).replace('__PUBLISH__', publish).replace('__COMPUTE_TICKS__', compute_ticks.replace('fn compute_ticks', 'pub(crate) fn compute_ticks')).replace('__COMPUTE_TICKS_WITH__', compute_ticks_with).replace('__RETIRE__', retire.replace('fn publish_timestamps', 'pub(crate) fn publish_timestamps')).replace('__FW_READ__', fw_read.replace('pub(crate) fn read(', 'fn read_prod(')).replace('__FW_R64__', fw_r64.replace('self.read(', 'self.read_impl(')) path = out / 'timestamps-host.rs' path.write_text(source) subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'timestamps-host')], check=True) From 4456a8b61ad8d738a7250bc19f2b4ac64a97f6a7 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:13:33 -0600 Subject: [PATCH 0930/1514] drm/asahi: g18: raise max_commands_per_submission to 64 G18 already admits and executes up to UAPI_MAX_HARDWARE_COMMANDS (64) commands per submission sequentially under submit_lock, yet G18DrmGpu:: get_params() hardcodes max_commands_per_submission = 1. Report file::MAX_COMMANDS_PER_SUBMISSION (64) so userspace batches multiple commands into a single SUBMIT ioctl. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- drivers/gpu/drm/asahi/g18/drm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index 14a726b24fc4cc..7fd3eb35c92996 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -197,7 +197,7 @@ impl gpu::Gpu for G18DrmGpu { params.max_frequency_khz = 0; params.usc_generation = G18_USC_GENERATION; params.gpu_hal_generation = G18_UAPI_HAL_GENERATION; - params.max_commands_per_submission = 1; + params.max_commands_per_submission = file::MAX_COMMANDS_PER_SUBMISSION; if self.config.admit_graphics_scratch { params.features |= uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_G18_GRAPHICS_SCRATCH as u64; } From cfe10888f5bcb238823280bfd840e2c49c361044 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 02:41:43 -0500 Subject: [PATCH 0931/1514] drm/asahi: g16: advertise soft faults With DRM_ASAHI_FEATURE_SOFT_FAULTS, Mesa marks every load as safe to speculate, so it can peephole-select and hoist loads out of control flow, and it drops the bounds checks of robust vertex fetches. G16 has never advertised the bit: its soft_faults() returned false since the backend landed. The G17 backend advertises it after measuring that its firmware's own fault mode returns zero for unmapped loads and drops unmapped stores. G16 programs no fault mode, and no word of the macOS 26B123 InitData or queue records captured on the J773g reads as one; its kext writes no GPU register outside the ring write cells. So the default fault behaviour of the 26B123 G16G firmware decides. On the J773g (26B123) with the bit advertised, 18,676 dEQP-VK robustness cases (every case outside robustness2, and 2,500 of the 82,600 robustness2 cases sampled across its groups) give the same results with Mesa's soft-fault use on and off (ASAHI_MESA_DEBUG=nosoft): 8,762 pass, 9,914 not supported, none fail, with no GPU fault or recovery. The full Vulkan and OpenGL benchmark suites and a deep sleep ran without a GPU fault. Loads, stores and atomics to unmapped leaf, level-2 and root translations have not been measured on their own. A shader store to an unmapped leaf of a closed VM's context has faulted and recovered the GPU on this backend, so the store half of the uAPI's promise is not shown yet. Keep fault_control (default 0xb) as the opt-out. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 4 +- drivers/gpu/drm/asahi/g16/params.rs | 11 ++- .../drivers/gpu/asahi-m4/test-uapi.py | 93 ++++++++++++++++++- 3 files changed, 100 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 7c7851ee6068a9..18ebaf1abebb55 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -883,8 +883,10 @@ impl gpu::Gpu for Gpu { true } + /// G16 programs no fault mode into the firmware: an unmapped shader access behaves as the + /// firmware's default fault mode makes it. `fault_control` (default 0xb) stays the opt-out. fn soft_faults(&self) -> bool { - false + true } fn prepare_new_objects(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 434faf2ee2a046..0f9caf69342841 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -3,11 +3,12 @@ //! 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`, VDM_USC_INVALIDATE, and `INDEPENDENT_QUEUES` from -//! `queue_limits`), G16 advertises per-command input readiness/errors, exact queue-local historical -//! prefixes, fragment-only and staged render barriers (`RENDER_STAGE_PREFIXES_V2`), independent -//! logical queues, `FEW_PRIMITIVES`, `COMPUTE_NO_QUERY_ACCESS`, render ray queries -//! (`RENDER_RAY_QUERY`) and bounded AS builds (`BOUNDED_AS_BUILD`). +//! SOFT_FAULTS from `soft_faults` and `fault_control`, VDM_USC_INVALIDATE, and +//! `INDEPENDENT_QUEUES` from `queue_limits`), G16 advertises per-command input readiness/errors, +//! exact queue-local historical prefixes, fragment-only and staged render barriers +//! (`RENDER_STAGE_PREFIXES_V2`), independent logical queues, `FEW_PRIMITIVES`, +//! `COMPUTE_NO_QUERY_ACCESS`, render ray queries (`RENDER_RAY_QUERY`) and bounded AS builds +//! (`BOUNDED_AS_BUILD`). use kernel::{prelude::*, uapi}; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py index a6c936f3c0b4aa..0aa956ee2d8cde 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py @@ -5,8 +5,95 @@ import json import os from pathlib import Path +import re +import subprocess from abi import c_layout, differences, rust_layout -from common import FIXTURES, kernel_root, output_dir, verify_fixtures +from common import FIXTURES, kernel_root, output_dir, rustc, verify_fixtures + + +def item(text, declaration): + start = text.index(declaration) + at = text.index('{', start) + depth, end = 1, at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +SOFT_FAULTS_HARNESS = r''' +#![allow(dead_code, non_upper_case_globals)] +mod uapi { __UAPI__ } +mod module_parameters { + pub struct Param(pub std::cell::Cell); + impl Param { pub fn value(&self) -> u32 { self.0.get() } } + std::thread_local! { + pub static FAULT_CONTROL: Param = const { Param(std::cell::Cell::new(0xb)) }; + } + pub struct FaultControl; + impl FaultControl { pub fn value(&self) -> u32 { FAULT_CONTROL.with(|p| p.value()) } } + pub static fault_control: FaultControl = FaultControl; +} +pub struct QueueLimits; +trait Backend { + fn supports_vm_status(&self) -> bool { false } + fn queue_limits(&self) -> Option { None } + __SHARED__ +} +struct G16; +impl Backend for G16 { + fn supports_vm_status(&self) -> bool { true } + fn queue_limits(&self) -> Option { Some(QueueLimits) } + __OVERRIDE__ +} +const SOFT: u64 = uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SOFT_FAULTS as u64; +#[test] +fn g16_advertises_soft_faults_until_fault_control_opts_out() { + let set = |v| module_parameters::FAULT_CONTROL.with(|p| p.0.set(v)); + set(0xb); + assert_eq!(G16.feature_flags() & SOFT, SOFT); + for other in [0, 1, 0xa, 0xf] { + set(other); + assert_eq!(G16.feature_flags() & SOFT, 0, "fault_control {other:#x}"); + } + set(0xb); + // The other shared bits are unchanged by the opt-out. + let rest = G16.feature_flags() & !SOFT; + set(0); + assert_eq!(G16.feature_flags(), rest); +} +''' + + +def soft_faults(kernel, header, out): + """The production G16 SOFT_FAULTS advertisement: the shared defaults with G16's override.""" + gpu = (kernel / 'drivers/gpu/drm/asahi/gpu.rs').read_text() + g16 = (kernel / 'drivers/gpu/drm/asahi/g16/mod.rs').read_text() + # G16 keeps the shared fault_control opt-out: it overrides soft_faults() only. + assert g16.count('fn soft_faults(&self) -> bool {') == 1 + assert 'fn supports_soft_faults(' not in g16 + text = header.read_text() + + def feature(name): + shift = re.search(r'\b' + name + r'\s*=\s*\(1UL\)\s*<<\s*(\d+)', text).group(1) + return f'pub const drm_asahi_feature_{name}: u32 = 1 << {shift};' + + names = ('SOFT_FAULTS', 'VM_STATUS', 'VM_STATUS_MIRROR', 'INDEPENDENT_QUEUES') + uapi = '\n'.join(feature('DRM_ASAHI_FEATURE_' + n) for n in names) + shared = '\n'.join(item(gpu, decl) for decl in ('fn supports_soft_faults(&self) -> bool {', + 'fn feature_flags(&self) -> u64 {', + 'fn soft_faults(&self) -> bool {')) + source = (SOFT_FAULTS_HARNESS.replace('__UAPI__', uapi).replace('__SHARED__', shared) + .replace('__OVERRIDE__', item(g16, 'fn soft_faults(&self) -> bool {'))) + (out / 'soft-faults.rs').write_text(source) + for command in [rustc() + ['--edition=2021', '--test', str(out / 'soft-faults.rs'), '-o', + str(out / 'soft-faults')], + [str(out / 'soft-faults')]]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) + print(result.stdout, end='') + if result.returncode: + raise SystemExit(result.returncode) def main(): @@ -23,6 +110,7 @@ def main(): kernel = c_layout(header, bindings, out, 'kernel-layout') rust = rust_layout(bindings, out) errors = differences(kernel, rust) + soft_faults(args.kernel.resolve(), header, out) mesa = None if args.mesa: mesa = args.mesa.resolve() / 'include/drm-uapi/asahi_drm.h' @@ -31,7 +119,8 @@ def main(): 'kernel': str(header), 'bindings': str(bindings), 'comparisons': len(kernel), 'mesa': str(mesa) if mesa else None, 'mesa_comparison': 'performed' if mesa else 'not requested; set ASAHI_M4_MESA or --mesa', - 'errors': errors} + 'errors': errors, + 'soft_faults': 'G16 SOFT_FAULTS advertisement checked against fault_control'} if args.json: args.json.write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2)) From fdfd4a3bf7c535ef3ced7dcc2c1f9a7bc864348e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:29:26 +1100 Subject: [PATCH 0932/1514] drm/asahi: clarify direct-rejection scope and tighten test extraction Rename the direct-rejection test in m3-packet-completion-tests.py so it describes what it exercises (direct fail_packet(EBUSY) rejection) rather than claiming queued bystanders survive fail_pending() on a device fault; today fail_pending() still VM-fails queued packets on device fault until per-client recovery lands. Also anchor method extraction to 'fn {name}(&self' so future helper methods with matching suffixes cannot shadow the intended Packet method. Signed-off-by: Ryan Murray --- tools/asahi/m3-packet-completion-tests.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py index 389a9f40055114..45b786ed2e8c95 100644 --- a/tools/asahi/m3-packet-completion-tests.py +++ b/tools/asahi/m3-packet-completion-tests.py @@ -108,20 +108,20 @@ def method(source, signature): } #[test] -fn rejected_bystander_remains_admissible_after_another_vm_faults() { +fn direct_packet_rejection_leaves_vm_admissible() { let guilty = Vm::default(); - let bystander = Vm::default(); + let other = Vm::default(); let faulty = Packet::new(&guilty, true); - let rejected = Packet::new(&bystander, false); + let rejected = Packet::new(&other, false); faulty.finish(Err(EIO)); rejected.fail_packet(EBUSY); assert_eq!(guilty.error.get(), -5); assert!(faulty.vm_job.lock().as_ref().unwrap().0.get()); assert_eq!(rejected.completion.error.get(), -16); - assert_eq!(bystander.error.get(), 0); - assert!(bystander.submit().is_ok()); + assert_eq!(other.error.get(), 0); + assert!(other.submit().is_ok()); - let later = Packet::new(&bystander, true); + let later = Packet::new(&other, true); later.retired(); assert_eq!(later.completion.error.get(), 0); assert_eq!(later.completion.signals.get(), 1); @@ -198,7 +198,7 @@ def main(): "self.complete(Err(error), false);", "self.complete(Err(error), true);" ) methods = ("release_guard", "retired", "finish", "fail_packet", "complete") - extracted = [method(source, f"fn {name}(") for name in methods] + extracted = [method(source, f"fn {name}(&self") for name in methods] args.out.mkdir(parents=True, exist_ok=True) program = args.out / "packet-completion.rs" program.write_text(MOCKS + "\n".join(extracted) + TESTS) From fd49ba25a8b05f30dcde9f85c44755860ed9bdec Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 06:32:06 -0500 Subject: [PATCH 0933/1514] selftests: drm/asahi-m4: publish render claims mutably in test-resources Slots::publish() takes its claims as &mut Claims. Five render-slot cases still passed &Claims, so check-resources.rs no longer compiled and the asahi-m4 suite failed at test-resources.py. Signed-off-by: Diljit Singh --- .../selftests/drivers/gpu/asahi-m4/test-resources.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 e76430e00c6ebe..c4df745aa4c0cb 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -850,7 +850,7 @@ def module(text, name): c31.pass[0]=31;c31.pass_count=1;c31.pass_mask=1u32<<31; s.claim_pass_for(&arena,31,Some(a.id)).unwrap(); s.hold_vm(&c31,&a).unwrap(); - s.publish(&c31).unwrap(); + s.publish(&mut c31).unwrap(); // Clean same-VM reuse of displaced slot 0 does not need full work write. s.claim_pass_for(&arena,0,Some(a.id)).unwrap(); assert!(!s.render_needs_full_work(0)); @@ -1278,13 +1278,13 @@ def module(text, name): // Prime and displace slot 0. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; s.claim_pass_in(&prep,0,Some(a.id),0x2000).unwrap(); - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap(); render.set_dirty(0,0x1000,0x2000).unwrap(); render.passes[0].tilemap.fill(0,0x66,0x2000).unwrap(); s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap(); s.retire(&mut c1).unwrap(); // Hand staged scrub off via ScrubQueue; waiter is woken on completion and woke flag is set. @@ -1311,10 +1311,10 @@ def module(text, name): // the async scrub runs: it must clear scrubbing without marking clean, so next claim // performs a full scrub. let mut c0=Claims::new();c0.pass[0]=0;c0.pass_mask=1; - s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&c0).unwrap();s.retire(&mut c0).unwrap(); + s.hold_vm(&c0,&a).unwrap();s.hold_arenas(&c0,&prep);s.publish(&mut c0).unwrap();s.retire(&mut c0).unwrap(); let mut c1=Claims::new();c1.pass[0]=1;c1.pass_mask=2; s.claim_pass_in(&prep,1,Some(a.id),0x1000).unwrap(); - s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&c1).unwrap();s.retire(&mut c1).unwrap(); + s.hold_vm(&c1,&a).unwrap();s.hold_arenas(&c1,&prep);s.publish(&mut c1).unwrap();s.retire(&mut c1).unwrap(); s.stage_displaced_pass_scrubs(); assert!(q.push_batch(s.take_staged_scrubs())); assert!(s.scrubbing_active()); From 63cc4418004be59af442f51091e2c460bb1f6cae Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 11:36:34 +0000 Subject: [PATCH 0934/1514] agents: point AGENTS.md and CLAUDE.md at the Aurora Silicon rulebook Every agent that opens this repository loads the same rules, whoever runs it: the rulebook in aurora-silicon/agent-guidelines. This file keeps only the repo specifics. Route reviews to the teams that review and merge here with .github/CODEOWNERS; any one approval from a listed owner counts. Changes under .github/ need an Owner's review. No runtime change. [skip ci] Signed-off-by: Ryan Murray --- .github/CODEOWNERS | 9 ++++++--- AGENTS.md | 8 ++++++++ CLAUDE.md | 3 +++ 3 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b22b22407c1d50..0c1a7f2018c1e0 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,8 +1,11 @@ +# Reviews go to the teams that review and merge here; any one approval from a listed +# owner satisfies code-owner review (https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/access-tiers.md). +* @aurora-silicon/core @aurora-silicon/omarchy-m + # Code owners for aurora-silicon/linux. # -# Only files whose change affects every user or the release process are -# listed. Changes to them need a review from an Owner; everything else -# follows the normal merge policy: +# The files below affect every user or the release process: they need an +# Owner's review. Everything else follows the normal merge policy: # https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md # Roles: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/governance-and-roles.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000000..5fea8735806a6b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Agent and contributor rules: linux + +**Rulebook:** follow the Aurora Silicon rulebook, https://github.com/aurora-silicon/agent-guidelines/blob/main/AGENTS.md. It applies to every agent and contributor, whoever runs them. This file adds the repo specifics. + +## Repo notes + +- Default branch: `main`. Open pull requests against it from `feat/`, `fix/` or `wip/` branches. +- Reviews and merges: Core and Omarchy Mac maintainers (https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/access-tiers.md). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000000000..2745da24849f4c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +Follow https://github.com/aurora-silicon/agent-guidelines/blob/main/AGENTS.md; repo specifics below. + +@AGENTS.md From 80079aa69dfb38c578c76ee489a75435389deacd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 21:38:34 +1100 Subject: [PATCH 0935/1514] drm/asahi: add M3 Extended per-client GPU fault recovery sharing g16 logic Implement per-client GPU fault recovery for the M3 Extended (26.x / 27.2) runtime so a single client's MMU fault or shader hang isolates only the guilty VM instead of failing the device until reboot. - Share the 27.2 recovery protocol state machine, snapshot decoder, and storm admission window directly from drivers/gpu/drm/asahi/g16/recovery/logic.rs via drivers/gpu/drm/asahi/m3/m3_recovery.rs (zero duplication, no edits to g16/, file.rs, or mmu.rs). - Derive extended control-region recovery offsets from the m3_init_26 layout shift (0 on 26.6.2, 0x1e0 on 27.2) with bounds validation. - Enforce a cumulative per-boot QuarantineBudget (31 aborted flights, fail-closed) so repeated fault storms cannot retain quarantined VM bindings without bound. - Read and decode the extended MMU fault bank safely on failure to distinguish MMU faults (EIO) from hangs/timeouts (ETIMEDOUT) and log the faulting address translation. - Clear active pass TPC storage before phase 2 when the snapshot names a stopped tiler (flags & 9 == 9), drain stopped work rings cleanly (including firmware-discarded paired fragment commands on TA faults where TA drains, FS READ == head, and engines are idle), re-sync host/fw stamps, and handle pool+0x54 catch-up on subsequent draws. - Quarantine aborted VM bindings and fail only the stopped batch's packets so healthy clients (such as gnome-shell) and fresh clients continue unaffected. - Add host unit tests in tools/asahi/m3-recovery-tests.py (including a --mutate negative control) registered in tools/asahi/run-host-tests.py. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_compute.rs | 60 ++++- drivers/gpu/drm/asahi/m3/m3_config.rs | 95 +++++++- drivers/gpu/drm/asahi/m3/m3_device.rs | 52 ++++- drivers/gpu/drm/asahi/m3/m3_init_26.rs | 5 + drivers/gpu/drm/asahi/m3/m3_recovery.rs | 202 ++++++++++++++++ drivers/gpu/drm/asahi/m3/m3_render.rs | 110 ++++++++- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 295 +++++++++++++++++++++++- drivers/gpu/drm/asahi/m3/mod.rs | 1 + tools/asahi/m3-recovery-tests.py | 42 ++++ tools/asahi/m3-runtime-tests.rs | 3 + tools/asahi/run-host-tests.py | 1 + 11 files changed, 844 insertions(+), 22 deletions(-) create mode 100644 drivers/gpu/drm/asahi/m3/m3_recovery.rs create mode 100755 tools/asahi/m3-recovery-tests.py diff --git a/drivers/gpu/drm/asahi/m3/m3_compute.rs b/drivers/gpu/drm/asahi/m3/m3_compute.rs index d49a311c506c2b..b091459349a87d 100644 --- a/drivers/gpu/drm/asahi/m3/m3_compute.rs +++ b/drivers/gpu/drm/asahi/m3/m3_compute.rs @@ -34,6 +34,12 @@ pub(crate) struct Compute { last_progress_ns: i64, head: u16, cached_views: KVec, + /// Quarantined client views retained after firmware-aborted computes so their + /// ASIDs and driver mappings are never evicted or recycled. + quarantined_views: KVec, + quarantine_active_vm: bool, + /// Cumulative computes aborted by recovery that did not advance pool+0x54. + pool_delta: u64, slot: usize, batch_count: usize, checkpoint: (u64,u16,usize), @@ -119,7 +125,7 @@ impl Compute { // the invalidation. crate::mem::sync();crate::mem::tlbi_all();crate::mem::sync(); unsafe {core::arch::asm!("isb",options(nostack,preserves_flags))}; - Ok(Self {_client_command:client_command.ok_or(EINVAL)?,objects,command_bytes,sequence_bytes,_binding:binding,stats,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),sequence:1,head:1,cached_views:KVec::new(),slot:0,batch_count:1,checkpoint:(0,0,0),barriers:None,registers,profile,_lower_tlbi:lower_tlbi}) + Ok(Self {_client_command:client_command.ok_or(EINVAL)?,objects,command_bytes,sequence_bytes,_binding:binding,stats,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),sequence:1,head:1,cached_views:KVec::new(),quarantined_views:KVec::new(),quarantine_active_vm:false,pool_delta:0,slot:0,batch_count:1,checkpoint:(0,0,0),barriers:None,registers,profile,_lower_tlbi:lower_tlbi}) } fn encode_command(objects: &mut [Buffer], bytes: &mut [u8], context: u32, control: crate::m3::agx_compute::Control, sequence: u64, stamp_value: u32, slot: usize, @@ -224,9 +230,13 @@ impl Compute { // Complete allocations before moving the active views. Eviction // drops only an idle cached view; no arena storage is duplicated. let old_views = KVec::with_capacity(next.views.len(), GFP_KERNEL)?; - self.cached_views.reserve(1, GFP_KERNEL)?; - if self.cached_views.len() == 3 { - drop(self.cached_views.remove(0).map_err(|_| EIO)?); + if self.quarantine_active_vm { + self.quarantined_views.reserve(1, GFP_KERNEL)?; + } else { + self.cached_views.reserve(1, GFP_KERNEL)?; + if self.cached_views.len() == 3 { + drop(self.cached_views.remove(0).map_err(|_| EIO)?); + } } let mut old = CachedViews { binding: core::mem::replace(&mut self._binding, next.binding), @@ -236,7 +246,12 @@ impl Compute { for (i, view) in next.views { old.views.push((i, self.objects[i].swap_gpu_view(view)?), GFP_KERNEL)?; } - self.cached_views.push(old, GFP_KERNEL)?; + if self.quarantine_active_vm { + self.quarantine_active_vm = false; + self.quarantined_views.push(old, GFP_KERNEL)?; + } else { + self.cached_views.push(old, GFP_KERNEL)?; + } } self.checkpoint=(self.sequence,self.head,self.batch_count); self.batch_count=0; @@ -434,10 +449,43 @@ impl Compute { && self.objects[storage::QUEUE_STATE].read_u32(queue::READ)? == u32::from(self.head); if !stamped { return Ok(false); } if self.profile == super::m3_profile::Profile::Extended { - return Ok(self.objects[storage::POOL].read_u64(0x54)? == self.sequence); + let actual = self.objects[storage::POOL].read_u64(0x54)?; + let expected = self.sequence.saturating_sub(self.pool_delta); + if actual < expected { + return Ok(false); + } + if actual > expected && actual <= self.sequence { + self.pool_delta = self.sequence - actual; + } } Ok(true) } + /// Whether the firmware has drained the compute work ring to its current write head. + pub(crate) fn queues_drained(&mut self) -> Result { + Ok(self.objects[storage::QUEUE_STATE].read_u32(queue::DONE)? == u32::from(self.head) + && self.objects[storage::QUEUE_STATE].read_u32(queue::READ)? == u32::from(self.head)) + } + /// Re-synchronize compute stamps and pool expectations after firmware recovery + /// drained the stopped batch, and mark the faulting VM's binding for quarantine. + pub(crate) fn finish_recovery(&mut self, dev: &driver::AsahiDrmDevice) -> Result { + self.quarantine_active_vm = true; + let expected = self.stamp(); + let host = self.objects[storage::STAMP].read_u32(0)?; + let fw = self.objects[storage::FW_STAMP].read_u32(0)?; + let pool54 = self.objects[storage::POOL].read_u64(0x54)?; + dev_info!( + dev.as_ref(), + "M3 recovery compute post-drain: seq={} stamps={:#x}/{:#x} (want {:#x}) pool54={}\n", + self.sequence, host, fw, expected, pool54 + ); + if host != expected { self.objects[storage::STAMP].u32(0, expected)?; } + if fw != expected { self.objects[storage::FW_STAMP].u32(0, expected)?; } + if self.profile == super::m3_profile::Profile::Extended { + self.pool_delta = self.sequence.saturating_sub(pool54); + } + agx_memory::publish(); + Ok(()) + } pub(crate) fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result { for off in (0..512).step_by(128) { let mut raw=[0u8;128]; self.objects[storage::COMMAND].read(off,&mut raw)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index b6646e223c4f19..860ac6ccd83a8e 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -54,6 +54,9 @@ pub(crate) struct Config { io_descriptors: Option>, _iomaps: KVec, pub(crate) completed_events: u64, + pending_recovery_event: Option<(u32, u32)>, + pending_recovery_stats: bool, + last_recovery_gen: Option, pstates: crate::m3::m3_adt_config::PstateWatch, thermal: crate::m3::m3_thermal::Governor, request_top: u32, @@ -74,6 +77,7 @@ impl Config { let thermal = crate::m3::m3_thermal::Governor::new(dev.as_ref().as_ref(), &contents.pstates)?; return Ok(Self { objects: owners.objects, _iomaps: owners.iomaps, profile: firmware.profile(), control_generation: 0, completed_events: 0, + pending_recovery_event: None, pending_recovery_stats: false, last_recovery_gen: None, io_descriptors: Some(owners.descriptors), pstates: crate::m3::m3_adt_config::PstateWatch::new(contents.pstates), thermal, request_top: 8, request_value: 0, request_checked: false, request_check_at: None, @@ -156,6 +160,7 @@ impl Config { let thermal = crate::m3::m3_thermal::Governor::new(dev.as_ref().as_ref(), &contents.pstates)?; Ok(Self { objects, profile: firmware.profile(), control_generation: 0, io_descriptors: None, _iomaps: iomaps, completed_events: 0, + pending_recovery_event: None, pending_recovery_stats: false, last_recovery_gen: None, pstates: crate::m3::m3_adt_config::PstateWatch::new(contents.pstates), thermal, request_top:contents.table.0,request_value:0,request_checked:false, request_check_at:None,request_writes:0,request_observed:0 }) @@ -535,14 +540,21 @@ impl Config { core::str::from_utf8(&text[..len]).unwrap_or("")); } } else if channel == storage::EVENT { - if kind != 1 { + if kind == 1 { + let flags = u32::from_le_bytes(record[4..8].try_into().map_err(|_| EIO)?); + self.completed_events = self.completed_events.saturating_add((flags & 7).count_ones().into()); + } else if kind == 0 || kind == 4 { + let word3 = u32::from_le_bytes(record[12..16].try_into().map_err(|_| EIO)?); + dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); + self.pending_recovery_event.get_or_insert((kind, word3)); + } else { dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); return Err(EIO); } - let flags = u32::from_le_bytes(record[4..8].try_into().map_err(|_| EIO)?); - self.completed_events = self.completed_events.saturating_add((flags & 7).count_ones().into()); - } else if (channel == storage::TRACE && kind != 5) - || (channel == storage::STATS && kind == 0x16) { + } else if channel == storage::STATS && kind == 0x16 { + dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); + self.pending_recovery_stats = true; + } else if channel == storage::TRACE && kind != 5 { dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); return Err(EIO); } @@ -555,6 +567,79 @@ impl Config { Ok(()) } + pub(crate) fn recovery_offsets(&self) -> Option { + if self.profile != super::m3_profile::Profile::Extended { + return None; + } + let offsets = super::m3_recovery::RecoveryOffsets::extended( + super::m3_init_26::control_shift(), + ); + offsets + .valid_for(self.objects[CONTROL_REGION].size()) + .then_some(offsets) + } + + pub(crate) fn recovery_phase(&mut self) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + self.objects[CONTROL_REGION].read_u32(offsets.phase) + } + + pub(crate) fn recovery_generation(&mut self) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + let lo = self.objects[CONTROL_REGION].read_u32(offsets.generation)?; + let hi = self.objects[CONTROL_REGION].read_u32(offsets.generation + 4)?; + Ok(u64::from(lo) | (u64::from(hi) << 32)) + } + + pub(crate) fn write_recovery_phase(&mut self, phase: u32) -> Result { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + agx_memory::publish(); + self.objects[CONTROL_REGION].u32(offsets.phase, phase)?; + agx_memory::publish(); + Ok(()) + } + + pub(crate) fn read_recovery_snapshot(&mut self, index: usize) -> Result<(u32, u32)> { + let offsets = self.recovery_offsets().ok_or(EOPNOTSUPP)?; + if index >= offsets.snapshot_entries { + return Err(ERANGE); + } + let at = offsets.snapshot + index * 8; + let flags = self.objects[CONTROL_REGION].read_u32(at)?; + let target = self.objects[CONTROL_REGION].read_u32(at + 4)?; + Ok((flags, target)) + } + + pub(crate) fn note_recovered(&mut self, generation: u64) { + self.last_recovery_gen = Some(generation); + self.pending_recovery_event = None; + self.pending_recovery_stats = false; + } + + /// Returns a recovery trigger error if the firmware reported a fault/timeout + /// or entered recovery phase != 0, ignoring trailing `STATS 0x16` from the + /// already-completed recovery generation. + pub(crate) fn take_recovery_trigger(&mut self) -> Result> { + if self.recovery_offsets().is_none() { + return Ok(None); + } + let phase = self.recovery_phase()?; + if let Some((kind, _word3)) = self.pending_recovery_event.take() { + self.pending_recovery_stats = false; + return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + } + if core::mem::take(&mut self.pending_recovery_stats) { + let gen = self.recovery_generation()?; + if !super::m3_recovery::is_trailing_stats(phase, gen, self.last_recovery_gen) { + return Ok(Some(EIO)); + } + } + if phase != 0 { + return Ok(Some(EIO)); + } + Ok(None) + } + } /// All extended initialization owners, retained as one construction transaction. diff --git a/drivers/gpu/drm/asahi/m3/m3_device.rs b/drivers/gpu/drm/asahi/m3/m3_device.rs index 9897690d923dcc..9c7159f6d83d2a 100644 --- a/drivers/gpu/drm/asahi/m3/m3_device.rs +++ b/drivers/gpu/drm/asahi/m3/m3_device.rs @@ -173,12 +173,60 @@ impl Device { self.sgx.try_access().ok_or(ENODEV)?.as_view().try_read32(0xe01000) } + /// Read-only MMU fault bank & engine busy snapshot for Extended (26.x/27.2) + /// profiles. Returns `Ok(true)` if any cluster fault bank has its valid bit set. + /// Does not acknowledge or clear hardware fault banks. + pub(crate) fn log_extended_fault_banks(&self, vm: &crate::mmu::Vm) -> Result { + let sgx_guard = self.sgx.try_access().ok_or(ENODEV)?; + let sgx = sgx_guard.as_view(); + let pstate = sgx.try_read32(0xe01000)? & 0xf; + if pstate == 0 { + dev_info!( + self.dev.as_ref(), + "M3 {}: GPU is powered down; skipping fault-bank snapshot\n", + self.soc.gpu_name + ); + return Ok(false); + } + let c020 = sgx.try_read64(0xc020)?; + let c120 = sgx.try_read64(0xc120)?; + let selector = sgx.try_read64(0xd800)?; + let mut any_fault = false; + for bank in 0..u64::from(self.soc.clusters) { + sgx.try_write64(bank, 0xd800)?; + let address = sgx.try_read64(0xd8c8)?; + let fault = sgx.try_read64(0xd8c0)?; + dev_info!( + self.dev.as_ref(), + "M3 {}: pstate={} busy={:#x}/{:#x} bank {} fault={:#x} address={:#x}\n", + self.soc.gpu_name, + pstate, + c020, + c120, + bank, + fault, + address << 6 + ); + if fault & 1 != 0 { + any_fault = true; + dev_info!( + self.dev.as_ref(), + "M3 fault mapping bank={} address={:#x} translation={:?}\n", + bank, + address << 6, + vm.translate_iova(address << 6) + ); + } + } + sgx.try_write64(selector, 0xd800)?; + Ok(any_fault) + } + /// Read-only snapshot. Do not select or acknowledge fault banks here; /// the firmware owns those registers until recovery is ported. pub(crate) fn log_engine_state(&self, vm: &crate::mmu::Vm) -> Result { if self.firmware.profile() == super::m3_profile::Profile::Extended { - // Adaptive clock gating can leave individual engine banks inaccessible - // even while the GPU performance-state register says powered up. + let _ = self.log_extended_fault_banks(vm)?; return Ok(()); } let sgx_guard = self.sgx.try_access().ok_or(ENODEV)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_init_26.rs b/drivers/gpu/drm/asahi/m3/m3_init_26.rs index 750f6065103bc4..86305bfb182cbf 100644 --- a/drivers/gpu/drm/asahi/m3/m3_init_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_init_26.rs @@ -19,6 +19,11 @@ pub(crate) const LOG_THREADS: usize = 9; pub(crate) const RX_BYTES: usize = 0x48; pub(crate) const LOG_PAYLOAD_BYTES: usize = 0xd8; +/// Control-region offset shift for recovery/flush fields on this extended layout. +pub(crate) const fn control_shift() -> usize { + 0 +} + /// The shared cache-flush ring has separate index and entry addresses on the wire. pub(crate) fn write_flush_ring( bytes: &mut [u8], offset: usize, state: u64, entries: u64, diff --git a/drivers/gpu/drm/asahi/m3/m3_recovery.rs b/drivers/gpu/drm/asahi/m3/m3_recovery.rs new file mode 100644 index 00000000000000..7d00de4253f3a1 --- /dev/null +++ b/drivers/gpu/drm/asahi/m3/m3_recovery.rs @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! M3 Extended (26.x / 27.2) per-client GPU fault recovery. +//! +//! Shares the 27.2 recovery phase state machine, snapshot decoder, and storm +//! admission window directly from `g16/recovery/logic.rs` (the same protocol +//! G16 and G14 27.2 answer) so no phase logic is duplicated across backends. + +#[path = "../g16/recovery/logic.rs"] +#[allow(dead_code)] +pub(crate) mod logic; + +pub(crate) use logic::{RecoveryAction, SnapshotEntry}; + +/// Maximum quarantined aborted flights per boot (half of the 63 user UAT +/// contexts). Exceeding this cap fails closed into device fail-stop rather +/// than leaking bindings/packets without bound across storm windows. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Additional recovery rounds answered while stopped work drains from queues. +pub(crate) const FURTHER_RECOVERIES: u32 = 4; + +/// Maximum time to wait for stopped work to drain from work rings after phase 0. +pub(crate) const RECOVERY_DRAIN_MS: i64 = 1000; + +/// Overall wall-clock budget for starting recovery rounds under the runtime lock. +pub(crate) const RECOVERY_BUDGET_MS: i64 = 5000; + +/// Recovery control-object offsets derived from the `m3_init_26` layout shift +/// rather than hardcoded size checks. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct RecoveryOffsets { + pub(crate) snapshot: usize, + pub(crate) snapshot_entries: usize, + pub(crate) generation: usize, + pub(crate) phase: usize, +} + +impl RecoveryOffsets { + /// Extended control region offsets shifted by the profile's `m3_init_26` + /// control-table delta (`0` on 26.6.2 / `0xeaf0`, `0x1e0` on 27.2 / `0xedd0`). + pub(crate) const fn extended(shift: usize) -> Self { + Self { + snapshot: logic::SNAPSHOT + shift, + snapshot_entries: logic::SNAPSHOT_ENTRIES, + generation: logic::GENERATION + shift, + phase: logic::PHASE + shift, + } + } + + /// Verify every recovery word and snapshot entry fits inside `control_bytes`. + pub(crate) const fn valid_for(self, control_bytes: usize) -> bool { + let Some(snap_bytes) = self.snapshot_entries.checked_mul(8) else { + return false; + }; + let Some(snap_end) = self.snapshot.checked_add(snap_bytes) else { + return false; + }; + let Some(gen_end) = self.generation.checked_add(8) else { + return false; + }; + let Some(phase_end) = self.phase.checked_add(4) else { + return false; + }; + snap_end <= self.generation + && gen_end <= self.phase + && phase_end <= control_bytes + } +} + +/// A snapshot entry for a stopped tiler (valid + tiler bits): TPC storage must +/// be cleared before answering phase 2, matching G16 and G14 27.2. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// Trailing `STATS 0x16` notifications can arrive after the host already wrote +/// phase 0 for that recovery generation; do not treat them as a new fault. +pub(crate) const fn is_trailing_stats( + phase: u32, + current_gen: u64, + last_recovered_gen: Option, +) -> bool { + if phase != 0 { + return false; + } + match last_recovered_gen { + Some(prev) => prev == current_gen, + None => false, + } +} + +/// Cumulative per-boot bound on quarantined flights across recovery windows. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct QuarantineBudget { + count: usize, + limit: usize, +} + +impl QuarantineBudget { + pub(crate) const fn new(limit: usize) -> Self { + Self { count: 0, limit } + } + + pub(crate) const fn count(&self) -> usize { + self.count + } + + pub(crate) const fn can_admit(&self, flights: usize) -> bool { + match self.count.checked_add(flights) { + Some(total) => total <= self.limit, + None => false, + } + } + + pub(crate) fn charge(&mut self, flights: usize) -> bool { + if !self.can_admit(flights) { + return false; + } + self.count += flights; + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extended_offsets_match_shared_g16_and_272_layouts() { + let base = RecoveryOffsets::extended(0); + assert_eq!(base.snapshot, 0x40b8); + assert_eq!(base.generation, 0x4fa0); + assert_eq!(base.phase, 0x4fb0); + assert!(base.valid_for(0xeaf0)); + assert!(!base.valid_for(0x4fb0)); + + let v272 = RecoveryOffsets::extended(0x1e0); + assert_eq!(v272.snapshot, 0x4298); + assert_eq!(v272.generation, 0x5180); + assert_eq!(v272.phase, 0x5190); + assert!(v272.valid_for(0xedd0)); + assert!(!v272.valid_for(0x5190)); + } + + #[test] + fn stopped_tiler_matches_observed_g15g_and_g14_flags() { + assert!(stopped_tiler(0xd)); + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(!stopped_tiler(0x0)); + } + + #[test] + fn quarantine_budget_bounds_cumulative_retention() { + let mut budget = QuarantineBudget::new(QUARANTINE_LIMIT); + assert!(budget.can_admit(1)); + for i in 0..QUARANTINE_LIMIT { + assert_eq!(budget.count(), i); + assert!(budget.charge(1)); + } + assert_eq!(budget.count(), QUARANTINE_LIMIT); + assert!(!budget.can_admit(1)); + assert!(!budget.charge(1)); + assert_eq!(budget.count(), QUARANTINE_LIMIT); + } + + #[test] + fn trailing_stats_ignored_only_for_same_generation_at_phase_zero() { + assert!(!is_trailing_stats(0, 1, None)); + assert!(is_trailing_stats(0, 1, Some(1))); + assert!(!is_trailing_stats(0, 2, Some(1))); + assert!(!is_trailing_stats(1, 1, Some(1))); + assert!(!is_trailing_stats(1, 2, Some(1))); + } + + #[test] + fn shared_g16_phase_table_and_storm_window_work() { + assert_eq!(logic::action(0, false, true), RecoveryAction::Wait); + assert_eq!( + logic::action(1, false, true), + RecoveryAction::MarkAndAcknowledge + ); + assert_eq!(logic::action(2, true, true), RecoveryAction::Wait); + assert_eq!(logic::action(3, true, true), RecoveryAction::Resume); + assert_eq!(logic::action(3, true, false), RecoveryAction::ProtocolError); + assert_eq!( + SnapshotEntry::decode(0xd, 0x7a00_0200), + Some(SnapshotEntry { + flags: 0xd, + event: 0, + target: 0x7a00_0200, + }) + ); + let (mut win, mut count) = (0, 0); + for _ in 0..logic::WINDOW_LIMIT { + assert!(logic::admit(10, &mut win, &mut count)); + } + assert!(!logic::admit(11, &mut win, &mut count)); + } +} diff --git a/drivers/gpu/drm/asahi/m3/m3_render.rs b/drivers/gpu/drm/asahi/m3/m3_render.rs index a3ada4a349dfa4..c06b5335d823b7 100644 --- a/drivers/gpu/drm/asahi/m3/m3_render.rs +++ b/drivers/gpu/drm/asahi/m3/m3_render.rs @@ -30,6 +30,17 @@ pub(crate) struct Render { last_progress_ns:i64, stamp_epoch:timeline::StampEpoch, draw:u64, heads:[u16;2], cached_views:KVec, + /// Quarantined client views and replaced arena backing retained after + /// firmware-aborted draws so their ASIDs and driver mappings are never + /// evicted or recycled while quiescence is unproven. + quarantined_views:KVec, + quarantined_buffers:KVec, + quarantine_active_vm:bool, + /// Draw number whose batch was aborted by firmware recovery so `complete()` + /// does not reject the next draw with `EBUSY` on a firmware-discarded FS `DONE`. + recovery_aborted_draw:Option, + /// Cumulative draws aborted by recovery that did not advance pool+0x54. + pool_delta:[u64;2], slot:usize, batch_count:usize, early_count:u32, /// Measurement packets in the pass most recently appended to its queues. stage_timestamps:[bool;2], @@ -99,7 +110,7 @@ impl Render { tiler_bytes.resize(if profile==super::m3_profile::Profile::Extended {tiler::EXTENDED_SIZE} else {tiler::SIZE},0u8,GFP_KERNEL)?; let mut fragment_bytes=KVec::new(); fragment_bytes.resize(if profile==super::m3_profile::Profile::Extended {fragment::EXTENDED_SIZE} else {fragment::SIZE},0u8,GFP_KERNEL)?; - let mut job=Self{passes,init_bm,stats,profile,sequence_bytes,tiler_bytes,fragment_bytes,objects,_aliases:aliases,_binding:binding,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),draw:0,heads:[0;2],cached_views:KVec::new(),slot:0,batch_count:0,early_count:0,stage_timestamps:[true;2],base:0,checkpoint:(0,[0;2],0,0,0,0),clusters,registers,_lower_tlbi:lower_tlbi}; + let mut job=Self{passes,init_bm,stats,profile,sequence_bytes,tiler_bytes,fragment_bytes,objects,_aliases:aliases,_binding:binding,last_progress_ns:0,stamp_epoch:timeline::StampEpoch::default(),draw:0,heads:[0;2],cached_views:KVec::new(),quarantined_views:KVec::new(),quarantined_buffers:KVec::new(),quarantine_active_vm:false,recovery_aborted_draw:None,pool_delta:[0;2],slot:0,batch_count:0,early_count:0,stage_timestamps:[true;2],base:0,checkpoint:(0,[0;2],0,0,0,0),clusters,registers,_lower_tlbi:lower_tlbi}; // Lists and the matching manager are built before InitBM publication. job.initialize_parameter_buffer()?; for (index,pool) in UMA_POOLS.iter().enumerate() { @@ -557,8 +568,12 @@ impl Render { }; // Finish fallible allocations before replacing the current owner. let old_views=KVec::with_capacity(next.views.len(),GFP_KERNEL)?; - self.cached_views.reserve(1,GFP_KERNEL)?; - if self.cached_views.len()==3 {drop(self.cached_views.remove(0).map_err(|_|EIO)?);} + if self.quarantine_active_vm { + self.quarantined_views.reserve(1,GFP_KERNEL)?; + } else { + self.cached_views.reserve(1,GFP_KERNEL)?; + if self.cached_views.len()==3 {drop(self.cached_views.remove(0).map_err(|_|EIO)?);} + } let mut old=CachedViews { binding:core::mem::replace(&mut self._binding,next.binding), aliases:core::mem::replace(&mut self._aliases,next.aliases), @@ -567,7 +582,12 @@ impl Render { for (i,view) in next.views { old.views.push((i,self.view_owner(i).swap_gpu_view(view)?),GFP_KERNEL)?; } - self.cached_views.push(old,GFP_KERNEL)?; + if self.quarantine_active_vm { + self.quarantine_active_vm=false; + self.quarantined_views.push(old,GFP_KERNEL)?; + } else { + self.cached_views.push(old,GFP_KERNEL)?; + } } // Growth is legal only after exact retirement, and before append. // Cached VM mappings must be dropped before freeing the old backing. @@ -580,11 +600,14 @@ impl Render { for (field,base,bytes) in [(P::Tpc,s::TPC_LABEL,g.tpc_bytes),(P::Tilemap,s::TILEMAP_LABEL,g.tilemap_bytes)] { let size=usize::try_from(bytes).map_err(|_|EOVERFLOW)?; if size>self.passes[slot].get(field).size() { + let keep_old = !self.quarantined_views.is_empty() || self.quarantine_active_vm; + if keep_old { self.quarantined_buffers.reserve(1,GFP_KERNEL)?; } let buffer=Buffer::tiler(dev,uat.kernel_vm(),vm,size)?; self.cached_views.clear(); dev_info!(dev.as_ref(),"M3 render arena growth: slot={} object={} {} -> {} bytes GPU={:#x}\n", slot,base,self.passes[slot].get(field).size(),size,buffer.gpu_va()?); - *self.passes[slot].get_mut(field)=buffer; + let prev = core::mem::replace(self.passes[slot].get_mut(field), buffer); + if keep_old { let _ = self.quarantined_buffers.push(prev, GFP_KERNEL); } } } } @@ -768,19 +791,90 @@ impl Render { Ok(done) } pub(crate) fn complete(&mut self)->Result { + let recovered = self.recovery_aborted_draw == Some(self.draw); for (stamp,fw,pointers,value,head) in [(s::TA_STAMP,s::TA_FW_STAMP,s::TA_POINTERS,self.stamp_epoch.value(s::STAMP_TA - 256,self.draw),self.heads[0]), (s::FRAGMENT_STAMP,s::FRAGMENT_FW_STAMP,s::FRAGMENT_POINTERS,self.stamp_epoch.value(s::STAMP_FRAGMENT - 256,self.draw),self.heads[1])] { if self.objects[stamp].read_u32(0)?!=value || self.objects[fw].read_u32(0)?!=value - || self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head) + || (!recovered && self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head)) || self.objects[pointers].read_u32(queue::READ)?!=u32::from(head) {return Ok(false);} } if self.profile==super::m3_profile::Profile::Extended && self.draw!=0 { - for pool in UMA_POOLS { - if self.objects[pool.manager].read_u64(0x54)?!=self.draw {return Ok(false);} + for (idx, pool) in UMA_POOLS.iter().enumerate() { + let actual = self.objects[pool.manager].read_u64(0x54)?; + let expected = self.draw.saturating_sub(self.pool_delta[idx]); + if actual < expected {return Ok(false);} + if actual > expected && actual <= self.draw { + self.pool_delta[idx] = self.draw - actual; + } + } + } + Ok(true) + } + /// Clear TPC storage for all pass slots of an active batch before answering + /// recovery phase 2 when the firmware snapshot names a stopped tiler. + pub(crate) fn clear_active_tpc(&mut self, base: usize, count: usize) -> Result { + for index in 0..count { + let slot = Self::at(base, index); + self.passes[slot].get_mut(P::Tpc).fill(0)?; + } + crate::m3::agx_memory::publish(); + Ok(()) + } + /// Whether the firmware has drained both render work rings to their current write heads. + pub(crate) fn queues_drained(&mut self) -> Result { + for (pointers, head) in [(s::TA_POINTERS, self.heads[0]), (s::FRAGMENT_POINTERS, self.heads[1])] { + if self.objects[pointers].read_u32(queue::DONE)? != u32::from(head) + || self.objects[pointers].read_u32(queue::READ)? != u32::from(head) + { + return Ok(false); } } Ok(true) } + /// Whether TA fully drained while fragment has READ == head but DONE < head. + /// + /// On a TA fault, 27.2 firmware aborts the paired fragment command without + /// advancing `FRAGMENT_POINTERS.DONE` (while advancing `READ == head` and + /// idling the engines); the next draw catches `DONE` back up to `head`. + pub(crate) fn fragment_read_only_pending(&mut self) -> Result { + let ta_done = self.objects[s::TA_POINTERS].read_u32(queue::DONE)?; + let ta_read = self.objects[s::TA_POINTERS].read_u32(queue::READ)?; + let fs_done = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::DONE)?; + let fs_read = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::READ)?; + Ok(ta_done == u32::from(self.heads[0]) + && ta_read == u32::from(self.heads[0]) + && fs_read == u32::from(self.heads[1]) + && fs_done != u32::from(self.heads[1])) + } + /// Re-synchronize render stamps and pool expectations after firmware recovery + /// drained the stopped batch, and mark the faulting VM's binding for quarantine. + pub(crate) fn finish_recovery(&mut self, dev: &driver::AsahiDrmDevice) -> Result { + self.quarantine_active_vm = true; + self.recovery_aborted_draw = Some(self.draw); + let ta_expected = self.stamp_epoch.value(s::STAMP_TA - 256, self.draw); + let fs_expected = self.stamp_epoch.value(s::STAMP_FRAGMENT - 256, self.draw); + let ta_host = self.objects[s::TA_STAMP].read_u32(0)?; + let ta_fw = self.objects[s::TA_FW_STAMP].read_u32(0)?; + let fs_host = self.objects[s::FRAGMENT_STAMP].read_u32(0)?; + let fs_fw = self.objects[s::FRAGMENT_FW_STAMP].read_u32(0)?; + let pool0 = self.objects[UMA_POOLS[0].manager].read_u64(0x54)?; + let pool1 = self.objects[UMA_POOLS[1].manager].read_u64(0x54)?; + dev_info!( + dev.as_ref(), + "M3 recovery render post-drain: draw={} ta={:#x}/{:#x} (want {:#x}) fs={:#x}/{:#x} (want {:#x}) pool54={}/{}\n", + self.draw, ta_host, ta_fw, ta_expected, fs_host, fs_fw, fs_expected, pool0, pool1 + ); + if ta_host != ta_expected { self.objects[s::TA_STAMP].u32(0, ta_expected)?; } + if ta_fw != ta_expected { self.objects[s::TA_FW_STAMP].u32(0, ta_expected)?; } + if fs_host != fs_expected { self.objects[s::FRAGMENT_STAMP].u32(0, fs_expected)?; } + if fs_fw != fs_expected { self.objects[s::FRAGMENT_FW_STAMP].u32(0, fs_expected)?; } + if self.profile == super::m3_profile::Profile::Extended { + self.pool_delta[0] = self.draw.saturating_sub(pool0); + self.pool_delta[1] = self.draw.saturating_sub(pool1); + } + crate::m3::agx_memory::publish(); + Ok(()) + } pub(crate) fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result { // Retain allocator state as well as payloads: an exhausted parameter // pool can stall TA without producing an MMU fault. diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index f958364f3bc3b6..2800f824779705 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -40,9 +40,26 @@ struct GeometryTiming { } impl NativeJob { fn complete(&mut self)->Result {match self {Self::Compute(j)=>j.complete(),Self::Render(j)=>j.complete()}} + fn queues_drained(&mut self)->Result {match self {Self::Compute(j)=>j.queues_drained(),Self::Render(j)=>j.queues_drained()}} + fn finish_recovery(&mut self,dev:&driver::AsahiDrmDevice)->Result {match self {Self::Compute(j)=>j.finish_recovery(dev),Self::Render(j)=>j.finish_recovery(dev)}} fn log(&mut self,dev:&driver::AsahiDrmDevice)->Result {match self {Self::Compute(j)=>j.log(dev),Self::Render(j)=>j.log(dev)}} fn batch_gpu_span(&mut self)->Result<[u64;2]> {match self {Self::Compute(j)=>j.batch_gpu_span(),Self::Render(j)=>j.batch_gpu_span()}} } + +fn vm_failed(packet: &crate::m3::m3_submit::Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +fn latch_guilty(packet: &crate::m3::m3_submit::Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + +fn now_ns() -> u64 { + ::ktime_get() as u64 +} struct Inner { transport: rtkit::RtKit, state: Arc, @@ -52,6 +69,13 @@ struct Inner { pending: KVec<(Arc,usize)>, /// Published batches, oldest first. More than one only with asahi.m3_pipeline_depth > 1. active: KVec, + /// Packets from firmware-aborted batches retained until teardown so their + /// quarantined VM job guards remain pinned; bounded by `quarantine_budget`. + quarantined_packets: KVec>, + quarantine_budget: crate::m3::m3_recovery::QuarantineBudget, + recovery_window_ns: u64, + recovery_window_count: u32, + recoveries: u64, gpu_pending: bool, active_power_last: Option>, active_power_samples: u32, @@ -191,6 +215,250 @@ impl Inner { for batch in self.active.drain_all() {Self::finish_all(&batch.entries,Err(error));} self.fail_pending(error); } + /// Answer the Extended (26.x / 27.2) firmware recovery phase handshake using + /// the shared `g16/recovery/logic.rs` state machine so only the guilty VM + /// loses its device while innocent bystanders and fresh clients continue. + fn recover_extended(&mut self, trigger: Error) -> Result { + use crate::m3::m3_recovery::{self as rec, logic, RecoveryAction, SnapshotEntry}; + let offsets = self.config.recovery_offsets().ok_or(EOPNOTSUPP)?; + if self.active.is_empty() || self.state.health.crashed() { + return Err(EIO); + } + let flights = self.active.len(); + if !self.quarantine_budget.can_admit(flights) { + dev_err!( + self.drm.as_ref(), + "M3 GPU quarantine limit reached ({}/{}); fail-stop\n", + self.quarantine_budget.count(), + rec::QUARANTINE_LIMIT + ); + return Err(EIO); + } + let start_ns = now_ns(); + if !logic::admit( + start_ns, + &mut self.recovery_window_ns, + &mut self.recovery_window_count, + ) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery storm; fail-stop\n"); + return Err(EIO); + } + self.log_owners(trigger); + let vm = self.active[0].entries[0].0.vm.clone(); + let mmu_fault = self.device.log_extended_fault_banks(&vm).unwrap_or(false); + let blame_err = if mmu_fault { EIO } else { trigger }; + let overall = Instant::::now(); + let mut rounds = 0u32; + let mut prev_gen: Option = None; + let mut blamed = false; + loop { + if overall.elapsed() > Delta::from_millis(rec::RECOVERY_BUDGET_MS) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery exceeded overall budget\n"); + return Err(ETIMEDOUT); + } + let wait_p1 = Instant::::now(); + loop { + if self.state.health.crashed() { + return Err(EIO); + } + let phase = self.config.recovery_phase()?; + match logic::action(phase, false, true) { + RecoveryAction::MarkAndAcknowledge => break, + RecoveryAction::Wait => { + if wait_p1.elapsed() > Delta::from_nanos(logic::EVENT_WAIT_NS as i64) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 1 did not arrive\n"); + return Err(ETIMEDOUT); + } + let _ = self.config.drain(&self.drm); + fsleep(Delta::from_millis(1)); + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery unexpected phase {}\n", phase); + return Err(EPROTO); + } + } + } + let generation = self.config.recovery_generation()?; + if prev_gen == Some(generation) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery repeated generation {}\n", generation); + return Err(EPROTO); + } + prev_gen = Some(generation); + let mut entries = 0usize; + let mut clear_tpc = false; + for idx in 0..offsets.snapshot_entries { + let (flags, target) = self.config.read_recovery_snapshot(idx)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { + break; + }; + if rec::stopped_tiler(entry.flags) { + clear_tpc = true; + } + if entries < 4 { + dev_info!( + self.drm.as_ref(), + "M3 recovery gen={} snapshot[{}]: flags={:#x} event={:#x} target={:#x}\n", + generation, + entries, + entry.flags, + entry.event, + entry.target + ); + } + entries += 1; + } + if clear_tpc { + for batch in self.active.iter() { + if let NativeJob::Render(j) = &mut self.jobs[batch.index] { + j.clear_active_tpc(batch.base, batch.entries.len())?; + } + } + } + if !blamed { + for (packet, _) in self.active.iter().flat_map(|b| b.entries.iter()) { + latch_guilty(packet, blame_err); + } + blamed = true; + } + let ack_start = Instant::::now(); + self.config.write_recovery_phase(2)?; + let mut kicked = false; + loop { + if self.state.health.crashed() { + return Err(EIO); + } + let phase = self.config.recovery_phase()?; + let cur_gen = if phase == 3 { + self.config.recovery_generation()? + } else { + generation + }; + match logic::action(phase, true, cur_gen == generation) { + RecoveryAction::Resume => break, + RecoveryAction::Wait => { + let elapsed = ack_start.elapsed(); + if !kicked && elapsed > Delta::from_nanos((logic::RECOVERY_BUDGET_NS / 2) as i64) { + kicked = true; + dev_warn!(self.drm.as_ref(), "M3 GPU recovery: no phase 3 in 500 ms; ringing control doorbell\n"); + let _ = Pin::new(&mut self.transport).send_message(0x21, 0x0084_0000_0000_0011); + } + if elapsed > Delta::from_nanos(logic::RECOVERY_BUDGET_NS as i64) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 3 timed out (gen {})\n", generation); + return Err(ETIMEDOUT); + } + let _ = self.config.drain(&self.drm); + fsleep(Delta::from_millis(1)); + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery protocol error (phase={} gen={}/{})\n", phase, cur_gen, generation); + return Err(EPROTO); + } + } + } + self.config.write_recovery_phase(0)?; + self.config.note_recovered(generation); + dev_err!( + self.drm.as_ref(), + "M3 GPU recovery {} answered in {} ms ({} snapshot entries, clear_tpc={})\n", + generation, + ack_start.elapsed().as_millis(), + entries, + clear_tpc + ); + let drain_start = Instant::::now(); + let mut another_round = false; + loop { + let _ = self.config.drain(&self.drm); + let pipes_idle = self.config.pipes_idle()?; + let mut all_drained = pipes_idle; + if all_drained { + let engines_idle = (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 + || self.device.check_idle_parts(true, false).is_ok(); + for batch in self.active.iter() { + let batch_drained = match &mut self.jobs[batch.index] { + NativeJob::Render(j) => { + j.queues_drained()? + || (engines_idle && j.fragment_read_only_pending()?) + } + job => job.queues_drained()?, + }; + if !batch_drained { + all_drained = false; + break; + } + if let Some(mixed) = &batch.mixed { + if !self.jobs[mixed.compute_index].queues_drained()? { + all_drained = false; + break; + } + } + } + } + if all_drained { + break; + } + if self.state.health.crashed() { + return Err(EIO); + } + let phase = self.config.recovery_phase()?; + match logic::action(phase, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => { + another_round = true; + break; + } + _ => { + dev_err!(self.drm.as_ref(), "M3 GPU recovery invalid phase {} during drain\n", phase); + return Err(EPROTO); + } + } + if drain_start.elapsed() > Delta::from_millis(rec::RECOVERY_DRAIN_MS) { + dev_err!(self.drm.as_ref(), "M3 GPU recovery stopped work did not drain\n"); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + if !another_round { + break; + } + rounds += 1; + if rounds > rec::FURTHER_RECOVERIES { + dev_err!(self.drm.as_ref(), "M3 GPU recovery exceeded further rounds ({})\n", rounds); + return Err(EIO); + } + } + // Re-sync stamps/pool counters and mark faulting VM views for quarantine. + for batch in self.active.iter() { + self.jobs[batch.index].finish_recovery(&self.drm)?; + if let Some(mixed) = &batch.mixed { + self.jobs[mixed.compute_index].finish_recovery(&self.drm)?; + } + } + // Fail and quarantine all packets from the stopped batch(es). + self.quarantine_budget.charge(flights); + for batch in self.active.drain_all() { + for (packet, _) in batch.entries { + packet.finish(Err(blame_err)); + if !self.quarantined_packets.iter().any(|q| Arc::ptr_eq(q, &packet)) { + if self.quarantined_packets.push(packet.clone(), GFP_KERNEL).is_err() { + core::mem::forget(packet); + } + } + } + } + self.packets.clear(); + self.gpu_pending = false; + self.state.health.set_gpu_pending(false); + self.recoveries = self.recoveries.saturating_add(1); + dev_err!( + self.drm.as_ref(), + "M3 GPU recovered ({} so far, gen {}, blame {:?}); guilty VM isolated\n", + self.recoveries, + prev_gen.unwrap_or(0), + blame_err + ); + Ok(()) + } /// Name the processes whose published commands were in flight when the GPU failed. Batches /// in flight share one VM, so this is normally one process; a VM shared between processes /// names each submitter once (the first four). @@ -321,6 +589,12 @@ impl Inner { fn publish_next(&mut self)->bool { let mut progress=false; while !self.pending.is_empty() && self.state.healthy() { + while let Some((packet,_))=self.pending.first() { + if !vm_failed(packet) {break;} + self.fail_front(EIO); + progress=true; + } + if self.pending.is_empty() {break;} match self.reseed_stamp_epochs() { Ok(true)=>{}, Ok(false)=>break, @@ -717,6 +991,12 @@ impl Inner { if !self.state.healthy() || self.config.drain(&self.drm).is_err() { self.fail_active(EIO);return Err(EIO); } + if let Some(trigger) = self.config.take_recovery_trigger().unwrap_or(Some(EIO)) { + if let Err(e) = self.recover_extended(trigger) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } // With later batches in flight, the oldest retires once its own last draw's stamps // have arrived; the last one is also checked for exact queue, event and engine idle. if self.active.len()>1 { @@ -853,6 +1133,12 @@ impl Inner { } if expired { dev_err!(self.drm.as_ref(),"M3 completion events={} previous={}\n",completed,previous); + if self.config.recovery_phase() == Ok(1) { + if let Err(e) = self.recover_extended(ETIMEDOUT) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } self.fail_active(ETIMEDOUT);return Err(ETIMEDOUT); } Ok(false) @@ -1119,7 +1405,10 @@ impl Runtime { } }; Ok(Self { inner: ManuallyDrop::new(owner.write(Inner { transport, state, config, uat, window, drm, device, - jobs:KVec::new(),packets:KVec::new(),pending:KVec::new(),active:KVec::new(),gpu_pending:false,active_power_last:None,active_power_samples:0,fault_captured:false,timing:[[0;7];2],render_batches:[0;crate::m3::m3_pass_layout::SLOTS], + jobs:KVec::new(),packets:KVec::new(),pending:KVec::new(),active:KVec::new(), + quarantined_packets:KVec::new(),quarantine_budget:crate::m3::m3_recovery::QuarantineBudget::new(crate::m3::m3_recovery::QUARANTINE_LIMIT), + recovery_window_ns:0,recovery_window_count:0,recoveries:0, + gpu_pending:false,active_power_last:None,active_power_samples:0,fault_captured:false,timing:[[0;7];2],render_batches:[0;crate::m3::m3_pass_layout::SLOTS], geometry:[GeometryTiming::default();32],geometry_overflow:0,coalesced_packets:0,coalesced_render_stamps:0,mixed_batches:0,pass_cost:policy::PassCosts::default(),render_initialized:false,t8122_verdict:false, boot_step:crate::m3::t8122_start::BootStep::Publish })) }) } @@ -1160,6 +1449,7 @@ impl Runtime { let mut guard=shared.lock(); let inner=&mut *Option::as_mut(&mut *guard).ok_or(ENODEV)?.inner; if !inner.state.healthy() {return Err(EIO);} + if vm_failed(&packet) {return Err(EIO);} if packet.commands.is_empty() || packet.commands.len()>256 { pr_err!("M3 submit limit: commands={} maximum=256\n",packet.commands.len()); return Err(E2BIG); @@ -1214,6 +1504,9 @@ impl Runtime { if let Err(error)=inner.config.drain(&inner.drm) { inner.capture_fault(error);inner.fail_pending(EIO);return Service::Idle; } + if let Some(error) = inner.config.take_recovery_trigger().unwrap_or(Some(EIO)) { + inner.capture_fault(error);inner.fail_pending(EIO);return Service::Idle; + } return if inner.publish_next() {Service::Progress} else {Service::Idle}; } let messages=inner.state.event_messages.load(Ordering::Acquire); diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index 74ed39974f7590..d3113a18239b5c 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -204,6 +204,7 @@ mod t8122_hwdata; pub(crate) mod m3_init_26; mod m3_profile; +mod m3_recovery; pub(crate) mod m3_mmio_26; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] diff --git a/tools/asahi/m3-recovery-tests.py b/tools/asahi/m3-recovery-tests.py new file mode 100755 index 00000000000000..b31929f9e64bc0 --- /dev/null +++ b/tools/asahi/m3-recovery-tests.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host tests for M3 Extended shared per-client GPU fault recovery logic.""" +import argparse +from pathlib import Path +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--static", action="store_true", help="link without guest libraries") + parser.add_argument("--mutate", action="store_true") + args = parser.parse_args() + repo = Path(__file__).resolve().parents[2] + src = repo / "drivers/gpu/drm/asahi/m3/m3_recovery.rs" + args.out.mkdir(parents=True, exist_ok=True) + entry = src + if args.mutate: + # Negative control: drop the cumulative quarantine budget limit. + text = src.read_text() + target = "Some(total) => total <= self.limit," + if target not in text: + raise RuntimeError("mutation target missing in m3_recovery.rs") + g16_logic = (repo / "drivers/gpu/drm/asahi/g16/recovery/logic.rs").resolve() + mutated = text.replace( + '#[path = "../g16/recovery/logic.rs"]', + f'#[path = "{g16_logic}"]', + ).replace(target, "Some(_) => true,") + entry = args.out / "m3_recovery_mut.rs" + entry.write_text(mutated) + binary = args.out.resolve() / "tests" + flags = ["-C", "target-feature=+crt-static"] if args.static else [] + subprocess.run( + ["rustc", "--test", "--edition=2021", *flags, str(entry), "-o", str(binary)], + check=True, + ) + return subprocess.run([str(binary)], check=False).returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/asahi/m3-runtime-tests.rs b/tools/asahi/m3-runtime-tests.rs index 0d6d4e5841194f..5437c254e31d14 100644 --- a/tools/asahi/m3-runtime-tests.rs +++ b/tools/asahi/m3-runtime-tests.rs @@ -109,3 +109,6 @@ fn extended_parameter_aliases_are_gpu_only_and_legacy_is_unchanged() { #[path = "../../drivers/gpu/drm/asahi/m3/m3_completion_policy.rs"] mod m3_completion_policy; + +#[path = "../../drivers/gpu/drm/asahi/m3/m3_recovery.rs"] +mod m3_recovery; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 33b9ba9e8f0085..1244ff626dfacb 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -89,6 +89,7 @@ def mutations(flag, names, base, expect=KILL): 'm3-packet-completion-tests.py': [(out(), PASS), (out() + ['--mutate'], KILL)], + 'm3-recovery-tests.py': [(out(), PASS), (out() + ['--mutate'], KILL)], 'm3-stamp-admission-tests.py': [(out(), PASS), (out() + ['--mutation', 'live-reseed'], KILL)], 'hardware-defaults-tests.py': [([], PASS)], From d4acd94ddbf149dc18cd1ca60793cbe5723ee2a4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:52:08 +1100 Subject: [PATCH 0936/1514] drm/apple: harden colour selection, downstream 4:2:0 flag, VRR check, and stack usage Address review feedback across the colour-mode and VRR paths: - Gate pass 2 (unsafe fallback) in dcp_select_color_mode() on !mode->sdr_usable && mode->sdr_unsafe for SDR as well as HDR, so explicit SDR property requests on safe timings never fall through to UnsafeColorElementIDs. - Preserve cmode.pixel_encoding as the upstream encoding when parsing DownstreamFormat YCbCr 4:2:0 entries, carrying the downstream wire format in DCP_COLOR_FLAG_DOWNSTREAM_420 so tracepoints, sdr_rgb, and ext26 modesets remain unaffected while colour matching and color_state report wire YCbCr 4:2:0. - Bound unsafe-only PQ fallback to the wire bpp ceiling of the timing's non-DSC unsafe SDR elements (sdr_unsafe_max_bpp) as an extra link budget guard alongside firmware pre-filtering. - Attach Broadcast RGB, color format, and max bpc only on external connectors backed by iomfb_template, and allow default SDR commits with max_bpc >= 8 on fixed 8-bit pipes. - Replace the firmware-version list in dcp_crtc_atomic_check() with a capability check on iomfb_template_pq && !dcp_vrr_live(dcp) (keeping the firmware 27 panel guard), and share dcp_sdr_default_rgb(). - Eliminate struct dcp_display_mode and color_scores stack allocations across parser.c, iomfb.c, iomfb_template.c, iomfb_v14_7.c, and iomfb_v26_6.c, and add static_assert bounds for dcp_color_entry bitfields. - Extend apple-dcp host selftests to cover all of the above. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/apple_drv.c | 32 +++- drivers/gpu/drm/apple/dcp-color.h | 41 ++++- drivers/gpu/drm/apple/dcp.c | 25 +-- drivers/gpu/drm/apple/dcp.h | 1 + drivers/gpu/drm/apple/iomfb.c | 80 ++++++--- drivers/gpu/drm/apple/iomfb_template.c | 10 +- drivers/gpu/drm/apple/iomfb_v14_7.c | 31 ++-- drivers/gpu/drm/apple/iomfb_v26_6.c | 10 +- drivers/gpu/drm/apple/parser.c | 166 +++++++++++++----- drivers/gpu/drm/apple/parser.h | 12 +- .../drivers/gpu/apple-dcp/display.py | 28 ++- .../drivers/gpu/apple-dcp/lifecycle.py | 9 +- .../selftests/drivers/gpu/apple-dcp/rate.py | 61 +++++-- 13 files changed, 361 insertions(+), 145 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index a02062fb7a27ea..ebbc02ac07010c 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -1063,7 +1063,7 @@ static int apple_connector_attach_pq_reference(struct drm_connector *connector) * Colorspace (BT2020_RGB), HDR_OUTPUT_METADATA and PQ_REFERENCE_LUMINANCE. */ static int apple_connector_attach_hdr(struct drm_connector *connector, - bool panel_edr) + bool panel_edr, bool ext_color_props) { static const u32 panel_colorspaces = BIT(DRM_MODE_COLORIMETRY_BT2020_RGB); static const u32 hdmi_colorspaces = @@ -1125,6 +1125,8 @@ static int apple_connector_attach_hdr(struct drm_connector *connector, drm_connector_attach_hdr_output_metadata_property(connector); if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) return apple_connector_attach_pq_reference(connector); + if (!ext_color_props) + return 0; ret = drm_connector_attach_broadcast_rgb_property(connector); if (ret) return ret; @@ -1179,7 +1181,8 @@ static int apple_connector_create(struct drm_device *drm, if (ret) goto err_cleanup; ret = apple_connector_attach_hdr(&connector->base, - dcp_fw_compat_panel_edr(dcp)); + dcp_fw_compat_panel_edr(dcp), + dcp_ext_color_props_supported(dcp)); if (ret) goto err_cleanup; @@ -1410,6 +1413,24 @@ VISIBLE_IF_KUNIT bool apple_typec_port_rgb8_only(struct platform_device **dcp, return false; } +static bool apple_typec_port_color_props(struct platform_device **dcp, + int num_dcp, + struct platform_device *pipeline, + unsigned int port_idx) +{ + int i; + + for (i = 0; i < num_dcp; i++) { + if (pipeline && dcp[i] != pipeline) + continue; + if (!dcp_typec_port_has_candidate(port_idx, dcp[i])) + continue; + if (dcp_ext_color_props_supported(dcp[i])) + return true; + } + return false; +} + /* * Create a connector per physical Type-C port and attach it to every * pipeline that can drive it. The M2 Pro/Max laptops append a second @@ -1512,7 +1533,12 @@ static int apple_probe_typec_ports(struct drm_device *drm, * intact; its capabilities are not the pipeline's. */ if (!apple_typec_port_rgb8_only(dcp, num_dcp, pipeline, port_idx)) { - ret = apple_connector_attach_hdr(&connector->base, false); + bool color_props = apple_typec_port_color_props(dcp, num_dcp, + pipeline, + port_idx); + + ret = apple_connector_attach_hdr(&connector->base, false, + color_props); if (ret) return ret; } diff --git a/drivers/gpu/drm/apple/dcp-color.h b/drivers/gpu/drm/apple/dcp-color.h index a4b8a34f02e461..e9a683dcde9bc4 100644 --- a/drivers/gpu/drm/apple/dcp-color.h +++ b/drivers/gpu/drm/apple/dcp-color.h @@ -42,6 +42,22 @@ static inline bool dcp_color_format_is_ycbcr422(u8 format) format == DCP_COLOR_FORMAT_YCBCR422_HDMI; } +static inline u8 dcp_color_entry_format(const struct dcp_color_entry *e) +{ + if (e->flags & DCP_COLOR_FLAG_DOWNSTREAM_420) + return DCP_COLOR_FORMAT_YCBCR420; + return e->format; +} + +static inline u8 dcp_color_wire_bpp(u8 format, u8 depth) +{ + if (format == DCP_COLOR_FORMAT_YCBCR420) + return (depth * 3) / 2; + if (dcp_color_format_is_ycbcr422(format)) + return depth * 2; + return depth * 3; +} + static inline bool dcp_color_format_matches(u8 fmt, u8 req_fmt) { switch (req_fmt) { @@ -152,8 +168,9 @@ static inline u32 dcp_color_entry_rank(const struct dcp_color_entry *e, { u32 fmt_rank, space_rank, depth_rank, range_rank, dsc_rank; bool hdr = req->eotf != HDMI_EOTF_TRADITIONAL_GAMMA_SDR; + u8 fmt = dcp_color_entry_format(e); - switch (e->format) { + switch (fmt) { case DCP_COLOR_FORMAT_RGB: fmt_rank = 6; break; @@ -185,7 +202,7 @@ static inline u32 dcp_color_entry_rank(const struct dcp_color_entry *e, else space_rank = 1; } else if (req->colorspace == DRM_MODE_COLORIMETRY_DEFAULT) { - if (e->format == DCP_COLOR_FORMAT_RGB) { + if (fmt == DCP_COLOR_FORMAT_RGB) { if (req->default_rgb && e->colorimetry == DCP_COLORIMETRY_RGB) space_rank = 4; else if (e->colorimetry == DCP_COLORIMETRY_SRGB || @@ -215,7 +232,7 @@ static inline u32 dcp_color_entry_rank(const struct dcp_color_entry *e, depth_rank = e->depth; } - if (e->format == DCP_COLOR_FORMAT_RGB) + if (fmt == DCP_COLOR_FORMAT_RGB) range_rank = e->range == DCP_COLOR_YCBCR_RANGE_FULL ? 2 : 1; else range_rank = e->range == DCP_COLOR_YCBCR_RANGE_LIMITED ? 2 : 1; @@ -232,7 +249,7 @@ static inline void dcp_color_mode_from_entry(struct dcp_color_mode *out, out->score = 0; out->id = e->id; out->eotf = e->eotf; - out->format = e->format; + out->format = dcp_color_entry_format(e); out->colorimetry = e->colorimetry; out->range = e->range; out->depth = e->depth; @@ -242,6 +259,7 @@ static inline int dcp_default_sdr_color(const struct dcp_display_mode *mode, struct dcp_color_mode *out) { const struct dcp_color_mode *cmode = NULL; + unsigned int i; if (mode->color_mode_id == mode->sdr_rgb.id && mode->sdr_rgb.score >= 0) cmode = &mode->sdr_rgb; @@ -254,6 +272,12 @@ static inline int dcp_default_sdr_color(const struct dcp_display_mode *mode, if (cmode) { *out = *cmode; + for (i = 0; i < mode->nr_colors; i++) { + if (mode->colors[i].id == out->id) { + out->format = dcp_color_entry_format(&mode->colors[i]); + break; + } + } return 0; } return -EINVAL; @@ -286,13 +310,13 @@ static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, if (hdr && !req->allow_hdr) return -EINVAL; - max_pass = (req->allow_unsafe_sdr && - (!hdr || (!mode->sdr_usable && mode->sdr_unsafe))) ? 2 : 1; + max_pass = (req->allow_unsafe_sdr && !mode->sdr_usable && mode->sdr_unsafe) ? 2 : 1; for (pass = 0; pass < max_pass && !best; pass++) { bool allow_unsafe = pass > 0; for (i = 0; i < mode->nr_colors; i++) { const struct dcp_color_entry *e = &mode->colors[i]; + u8 fmt = dcp_color_entry_format(e); u32 rank; if ((e->flags & DCP_COLOR_FLAG_UNSAFE) && !allow_unsafe) @@ -300,11 +324,14 @@ static inline int dcp_select_color_mode(const struct dcp_display_mode *mode, if ((e->flags & DCP_COLOR_FLAG_DSC) && hdr && (!req->allow_dsc || allow_unsafe)) continue; + if (allow_unsafe && hdr && mode->sdr_unsafe_max_bpp && + dcp_color_wire_bpp(fmt, e->depth) > mode->sdr_unsafe_max_bpp) + continue; if (e->depth > max_bpc) continue; if (!dcp_color_eotf_matches(e->eotf, req)) continue; - if (!dcp_color_format_matches(e->format, req->color_format)) + if (!dcp_color_format_matches(fmt, req->color_format)) continue; if (!dcp_color_range_matches(e->range, req->broadcast_rgb)) continue; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index be584395d3f96a..bc037fb6e2973e 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2222,18 +2222,13 @@ int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commi /* * On desktop 26.6 firmware the panel takes VRR_ENABLED with the next - * frame, without a mode set (see dcp_vrr_update()). The external - * processors ignore a new minimum rate on a live mode, so they still - * change adaptive sync with a mode set, as firmware 27's externals do: - * macOS switches between a timing's fixed and variable modes with a - * full mode set. + * frame, without a mode set (see dcp_vrr_update()). Other template + * pipes change adaptive sync inside iomfb_modeset() via a full mode + * set, except firmware 27 panels which do not re-modeset on VRR. */ - if ((dcp->fw_compat == DCP_FIRMWARE_V_12_3 || - dcp->fw_compat == DCP_FIRMWARE_V_13_5 || - dcp->fw_compat == DCP_FIRMWARE_V_14_7_TEMPLATE || - dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP || - (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp->main_display && - !dcp_has_panel(dcp))) && + if (READ_ONCE(dcp->iomfb_template_pq) && + !(dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + (dcp->main_display || dcp_has_panel(dcp))) && crtc_state->enable && !dcp_vrr_live(dcp)) { struct drm_crtc_state *old = drm_atomic_get_old_crtc_state(commit, crtc); @@ -4332,6 +4327,14 @@ bool dcp_fw_compat_panel_edr(struct platform_device *pdev) dcp->fw_compat == DCP_FIRMWARE_V_27_0; } +/* External connectors driven by iomfb_template support full colour selection. */ +bool dcp_ext_color_props_supported(struct platform_device *pdev) +{ + struct apple_dcp *dcp = platform_get_drvdata(pdev); + + return !dcp_is_ext26(dcp) && !dcp_fw_compat_is_14_7(pdev); +} + bool dcp_fw_compat_is_14_7(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 19cbea3122184c..4186aa99c0b7cf 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -92,6 +92,7 @@ bool dcp_fw_compat_is_12_x(struct platform_device *pdev); bool dcp_fw_compat_is_14_7(struct platform_device *pdev); bool dcp_fw_compat_is_desktop(struct platform_device *pdev); bool dcp_fw_compat_panel_edr(struct platform_device *pdev); +bool dcp_ext_color_props_supported(struct platform_device *pdev); unsigned int dcp_gamma_lut_size(struct platform_device *pdev); /* T6041 external display processors may join the DRM device. */ bool dcp_t6041_ext_enabled(void); diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 12067db7adbf49..3febcae75f8d8d 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -2429,6 +2429,14 @@ u64 dcp_modes_transfer_begin(struct apple_dcp *dcp) * catalog, except on H17P external, which publishes an empty one. A * transfer started before the current attachment is never published. */ +static bool dcp_sdr_default_rgb(struct apple_dcp *dcp) +{ + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && !dcp_has_panel(dcp); +} + +static const struct dcp_display_mode * +dcp_find_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode); + int dcp_modes_replace(struct apple_dcp *dcp, struct dcp_parse_ctx *ctx, u64 generation) { @@ -2461,8 +2469,7 @@ int dcp_modes_replace(struct apple_dcp *dcp, struct dcp_parse_ctx *ctx, if (ret) return ret; ctx->metadata_timing = dcp_firmware_metadata_enabled(dcp); - ctx->sdr_default_rgb = dcp->fw_compat == DCP_FIRMWARE_V_27_0 && - !dcp_has_panel(dcp); + ctx->sdr_default_rgb = dcp_sdr_default_rgb(dcp); /* * The template sends a timing and colour ID to DCP. It can * select an entry the timing lists as needing DSC, just as @@ -3009,15 +3016,15 @@ static int dcp_desktop_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { struct dcp_desktop_state *d = dcp->desktop; - struct dcp_display_mode matched; + const struct dcp_display_mode *matched; if (d->trial_modeset_ok) { d->trial_modeset_ok = false; /* The trial installed a VRR timing variable too (see the mode set). */ if (d->mode_live && - lookup_mode(dcp, &crtc_state->mode, &matched) && - matched.timing_mode_id == d->trial_timing_mode_id && - matched.color_mode_id == d->trial_color_mode_id) { + (matched = dcp_find_mode(dcp, &crtc_state->mode)) && + matched->timing_mode_id == d->trial_timing_mode_id && + matched->color_mode_id == d->trial_color_mode_id) { dev_dbg(dcp->dev, "keeping the takeover mode " DRM_MODE_FMT "\n", DRM_MODE_ARG(&crtc_state->mode)); return 0; @@ -3042,20 +3049,20 @@ MODULE_PARM_DESC(takeover_adopt, static int dcp_takeover_adopt(struct apple_dcp *dcp, const struct drm_display_mode *m) { struct dcp_desktop_state *d = dcp->desktop; - struct dcp_display_mode sel; + const struct dcp_display_mode *sel = dcp_find_mode(dcp, m); - if (!lookup_mode(dcp, m, &sel)) + if (!sel) return -ENOENT; dcp->mode = (struct dcp_set_digital_out_mode_req) { - .color_mode_id = sel.color_mode_id, - .timing_mode_id = sel.timing_mode_id, + .color_mode_id = sel->color_mode_id, + .timing_mode_id = sel->timing_mode_id, }; - dcp->use_timestamps = sel.needs_timestamps; + dcp->use_timestamps = sel->needs_timestamps; dcp->vrr_enabled = false; d->mode_live = true; d->takeover_adopted = true; dev_info(dcp->dev, "takeover: adopting the live mode (color:%u timing:%u) " DRM_MODE_FMT "\n", - sel.color_mode_id, sel.timing_mode_id, DRM_MODE_ARG(m)); + sel->color_mode_id, sel->timing_mode_id, DRM_MODE_ARG(m)); return 0; } @@ -3483,8 +3490,7 @@ static void dcp_crtc_color_request(struct apple_dcp *dcp, struct drm_crtc *crtc, .allow_dsc = READ_ONCE(dcp->iomfb_template_pq) && !dcp_has_panel(dcp), .allow_unsafe_sdr = dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17P_EXTERNAL, - .default_rgb = dcp->fw_compat == DCP_FIRMWARE_V_27_0 && - !dcp_has_panel(dcp), + .default_rgb = dcp_sdr_default_rgb(dcp), }; } @@ -3495,7 +3501,7 @@ int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_crtc_state *crtc_state = drm_atomic_get_new_crtc_state(commit, crtc); struct dcp_color_request req; struct dcp_color_mode selected; - struct dcp_display_mode mode; + const struct dcp_display_mode *mode; if (!crtc_state || !crtc_state->enable || !drm_atomic_crtc_needs_modeset(crtc_state)) @@ -3511,16 +3517,24 @@ int dcp_crtc_check_hdr(struct apple_dcp *dcp, struct drm_crtc *crtc, req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT) return 0; - if (!READ_ONCE(dcp->iomfb_template_pq) || dcp_is_ext26(dcp)) + if (!READ_ONCE(dcp->iomfb_template_pq) || dcp_is_ext26(dcp)) { + /* Fixed 8-bit SDR pipes satisfy any default SDR request with max_bpc >= 8. */ + if (req.eotf == HDMI_EOTF_TRADITIONAL_GAMMA_SDR && + req.colorspace == DRM_MODE_COLORIMETRY_DEFAULT && + req.color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO && + req.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_AUTO && + (!req.max_bpc || req.max_bpc >= 8)) + return 0; return -EINVAL; - if (!lookup_mode(dcp, &crtc_state->mode, &mode)) + } + mode = dcp_find_mode(dcp, &crtc_state->mode); + if (!mode) return -EINVAL; - return dcp_select_color_mode(&mode, &req, &selected); + return dcp_select_color_mode(mode, &req, &selected); } -/* The user may own drm_display_mode, so we need to search for our copy */ -bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, - struct dcp_display_mode *out) +static const struct dcp_display_mode * +dcp_find_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode) { struct dcp_display_mode *modes; unsigned int count, i; @@ -3533,7 +3547,7 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, DRM_MODE_MATCH_TIMINGS | DRM_MODE_MATCH_CLOCK)) { if (!modes[i].automatic_rgb8_quirk) - goto found; + return &modes[i]; mutex_lock(&dcp->hpd_mutex); mutex_lock(&dcp->dcpavserv.lock); spin_lock_irqsave(&dcp->metadata.lock, flags); @@ -3542,16 +3556,24 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, mutex_unlock(&dcp->dcpavserv.lock); mutex_unlock(&dcp->hpd_mutex); if (eligible) - goto found; + return &modes[i]; } } - return false; + return NULL; +} + +/* The user may own drm_display_mode, so we need to search for our copy */ +bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, + struct dcp_display_mode *out) +{ + const struct dcp_display_mode *found = dcp_find_mode(dcp, mode); -found: + if (!found) + return false; /* Callers keep a copy, never a pointer into the catalog. */ if (out) - *out = modes[i]; + *out = *found; return true; } @@ -3565,15 +3587,15 @@ bool lookup_mode(struct apple_dcp *dcp, const struct drm_display_mode *mode, static bool dcp_mode_settable(struct apple_dcp *dcp, const struct drm_display_mode *mode) { - struct dcp_display_mode dcp_mode; + const struct dcp_display_mode *dcp_mode = dcp_find_mode(dcp, mode); - if (!lookup_mode(dcp, mode, &dcp_mode)) + if (!dcp_mode) return false; if (dcp->fw_compat == DCP_FIRMWARE_H17P && !dcp_is_ext26(dcp) && dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17P_EXTERNAL) - return dcp_mode.mode.type & DRM_MODE_TYPE_PREFERRED; + return dcp_mode->mode.type & DRM_MODE_TYPE_PREFERRED; /* * The T6050 internal DCP (M5 Max) crashes on 3024x1986@60 and the diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 4f052891b7674d..78f3a29b9b405b 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -3914,13 +3914,16 @@ static void dcp_modeset_select(struct apple_dcp *dcp, void *out, void *cookie) int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { - struct dcp_display_mode selected, *mode = &selected; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); struct dcp_modeset_cookie *modeset; struct dcp_wait_cookie *cookie; struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; int ret; + if (!mode) + return -ENOMEM; + if (dcp->crashed) return -ENODEV; /* A timed-out command still owns its channel until firmware replies. */ @@ -4186,7 +4189,7 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, #endif ) { - struct dcp_display_mode selected, *mode = &selected; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); struct dcp_wait_cookie *cookie; struct dcp_color_mode selected_color = { .score = -1 }; struct dcp_color_mode *cmode = NULL; @@ -4194,6 +4197,9 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, bool keep_mode = false; int ret; + if (!mode) + return -ENOMEM; + #if DCP_FW_H17(DCP_FW_VER) && DCP_FW_VER < DCP_FW_VERSION(27, 0, 0) if (dcp_is_ext26(dcp)) { u32 pitch = primary && primary->fb ? primary->fb->pitches[0] : dcp->ext26_stride; diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index a99bfed67183fd..c6d3c66a0be27a 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -3200,13 +3200,13 @@ bool iomfb_v14_7_external_showing(struct apple_dcp *dcp, const struct drm_display_mode *drm_mode) { struct apple_dcp_v14 *v14 = dcp->v14; - struct dcp_display_mode mode = {}; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); bool live; - if (!dcp->external_native || !v14 || !lookup_mode(dcp, drm_mode, &mode)) + if (!mode || !dcp->external_native || !v14 || !lookup_mode(dcp, drm_mode, mode)) return false; mutex_lock(&v14->lock); - live = dcp_v14_external_described(v14) && dcp_v14_external_mode_live(v14, &mode); + live = dcp_v14_external_described(v14) && dcp_v14_external_mode_live(v14, mode); mutex_unlock(&v14->lock); return live; } @@ -3235,10 +3235,12 @@ static void dcp_v14_audio_on(struct apple_dcp *dcp) static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { struct apple_dcp_v14 *v14 = dcp->v14; - struct dcp_display_mode mode = {}; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); bool audio_off = false; int ret = 0; + if (!mode) + return -ENOMEM; if (!v14 || READ_ONCE(v14->failed) || !v14->opened) return -EIO; /* @@ -3254,7 +3256,7 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state if (ret) goto out; /* Only after the wait: a new description replaces the catalog. */ - if (!lookup_mode(dcp, &crtc_state->mode, &mode)) { + if (!lookup_mode(dcp, &crtc_state->mode, mode)) { mutex_unlock(&v14->lock); ret = -EINVAL; goto out; @@ -3264,10 +3266,11 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state * it again only restarts its timings under the display. A retry or a * replayed CRTC lands here when the display came back as it was. */ - if (dcp_v14_external_mode_live(v14, &mode)) { + if (dcp_v14_external_mode_live(v14, mode)) { mutex_unlock(&v14->lock); dev_info(dcp->dev, "display mode " DRM_MODE_FMT " (timing %u, color %u) already active and showing\n", - DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id); + DRM_MODE_ARG(&crtc_state->mode), + mode->timing_mode_id, mode->color_mode_id); atomic_set(&dcp->external_retries, 0); dcp_mode_set_valid(&dcp->mode_state, true); if (dcp->avep) @@ -3279,7 +3282,7 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state if (READ_ONCE(v14->failed)) ret = -EIO; if (!ret) - ret = dcp_v14_set_mode(v14, mode.color_mode_id, mode.timing_mode_id); + ret = dcp_v14_set_mode(v14, mode->color_mode_id, mode->timing_mode_id); if (!ret) ret = dcp_v14_set_power(v14, true); /* @@ -3292,19 +3295,19 @@ static int dcp_v14_external_modeset(struct apple_dcp *dcp, struct drm_crtc_state * before the first swap. */ if (!ret) - ret = dcp_v14_set_mode(v14, mode.color_mode_id, mode.timing_mode_id); + ret = dcp_v14_set_mode(v14, mode->color_mode_id, mode->timing_mode_id); if (!ret) { - v14->panel_width = mode.mode.hdisplay; - v14->panel_height = mode.mode.vdisplay; - v14->mode_timing = mode.timing_mode_id; - v14->mode_color = mode.color_mode_id; + v14->panel_width = mode->mode.hdisplay; + v14->panel_height = mode->mode.vdisplay; + v14->mode_timing = mode->timing_mode_id; + v14->mode_color = mode->color_mode_id; v14->mode_swaps = 0; v14->mode_live = true; } mutex_unlock(&v14->lock); out: dev_info(dcp->dev, "display mode " DRM_MODE_FMT " (timing %u, color %u): %d\n", - DRM_MODE_ARG(&crtc_state->mode), mode.timing_mode_id, mode.color_mode_id, ret); + DRM_MODE_ARG(&crtc_state->mode), mode->timing_mode_id, mode->color_mode_id, ret); if (ret) { /* * A mode that is gone, or a description that never settled: diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.c b/drivers/gpu/drm/apple/iomfb_v26_6.c index 1f456dc17776a6..95128654acf305 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6.c @@ -1740,9 +1740,11 @@ int iomfb_v26_6_atomic_check(struct apple_dcp *dcp, struct drm_crtc *crtc, int iomfb_v26_6_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state) { - struct dcp_display_mode mode; + struct dcp_display_mode *mode __free(kfree) = kzalloc_obj(*mode); - if (!lookup_mode(dcp, &crtc_state->mode, &mode)) + if (!mode) + return -ENOMEM; + if (!lookup_mode(dcp, &crtc_state->mode, mode)) return -EINVAL; /* * The firmware keeps the timing it booted with, which every mode @@ -1751,8 +1753,8 @@ int iomfb_v26_6_modeset(struct apple_dcp *dcp, struct drm_crtc_state *crtc_state * (locked 60 Hz). */ if (dcp->v26) { - WRITE_ONCE(dcp->v26->timed, mode.vrr); - WRITE_ONCE(dcp->v26->refresh, drm_mode_vrefresh(&mode.mode)); + WRITE_ONCE(dcp->v26->timed, mode->vrr); + WRITE_ONCE(dcp->v26->refresh, drm_mode_vrefresh(&mode->mode)); } dcp_mode_set_valid(&dcp->mode_state, true); return 0; diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 39e4b2e87982c5..f7ce155f8df85a 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -571,31 +571,45 @@ static int parse_timing_color_restrictions(struct dcp_parse_ctx *handle, return 0; } +static u8 color_wire_bpp(enum dcp_color_format fmt, u8 depth) +{ + if (fmt == DCP_COLOR_FORMAT_YCBCR420) + return (depth * 3) / 2; + if (fmt == DCP_COLOR_FORMAT_YCBCR422 || + fmt == DCP_COLOR_FORMAT_YCBCR422_DP || + fmt == DCP_COLOR_FORMAT_YCBCR422_HDMI) + return depth * 2; + return depth * 3; +} + /* * An HDR output scans out through a PQ BT.2020 element. Prefer RGB, which * needs no conversion, then 10 bits per component, which is what an HDR * framebuffer carries; a timing without link bandwidth for PQ RGB may still * offer YCbCr 4:4:4, which the processor converts the RGB surfaces to. */ -static unsigned int pq_mode_rank(const struct color_mode *cmode) +static unsigned int pq_mode_rank(const struct color_mode *cmode, + bool downstream_420) { + enum dcp_color_format fmt = downstream_420 ? + DCP_COLOR_FORMAT_YCBCR420 : cmode->pixel_encoding; unsigned int rank; if (cmode->eotf != DCP_EOTF_ST_2084) return 0; - if (cmode->pixel_encoding == DCP_COLOR_FORMAT_RGB && + if (fmt == DCP_COLOR_FORMAT_RGB && cmode->colorimetry == DCP_COLORIMETRY_BT2020_RGB && cmode->dynamic_range == DCP_COLOR_YCBCR_RANGE_FULL) rank = 7; - else if (cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR444 && + else if (fmt == DCP_COLOR_FORMAT_YCBCR444 && cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 5; - else if ((cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422 || - cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422_DP || - cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR422_HDMI) && + else if ((fmt == DCP_COLOR_FORMAT_YCBCR422 || + fmt == DCP_COLOR_FORMAT_YCBCR422_DP || + fmt == DCP_COLOR_FORMAT_YCBCR422_HDMI) && cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 3; - else if (cmode->pixel_encoding == DCP_COLOR_FORMAT_YCBCR420 && + else if (fmt == DCP_COLOR_FORMAT_YCBCR420 && cmode->colorimetry == DCP_COLORIMETRY_BT2020_YCC) rank = 1; else @@ -604,14 +618,19 @@ static unsigned int pq_mode_rank(const struct color_mode *cmode) } static void record_color_entry(struct dcp_display_mode *out, - s64 scores[DCP_MAX_COLOR_ENTRIES], + s64 *scores, const struct color_mode *cmode, const struct timing_color_restrictions *limits, - bool limits_known) + bool limits_known, bool downstream_420) { struct dcp_color_entry entry = {}; unsigned int pos, end; + static_assert(DCP_EOTF_COUNT <= 8); + static_assert(DCP_COLOR_FORMAT_COUNT <= 16); + static_assert(DCP_COLOR_YCBCR_RANGE_COUNT <= 2); + static_assert(DCP_COLORIMETRY_COUNT <= 32); + if (cmode->colorimetry < 0 || cmode->colorimetry >= DCP_COLORIMETRY_COUNT || cmode->depth < 8 || cmode->depth > 12 || cmode->dynamic_range < 0 || cmode->dynamic_range >= DCP_COLOR_YCBCR_RANGE_COUNT || @@ -625,6 +644,8 @@ static void record_color_entry(struct dcp_display_mode *out, entry.range = cmode->dynamic_range; entry.colorimetry = cmode->colorimetry; entry.depth = cmode->depth; + if (downstream_420) + entry.flags |= DCP_COLOR_FLAG_DOWNSTREAM_420; if (limits_known) { if (timing_color_contains(&limits->unsafe, cmode->id)) entry.flags |= DCP_COLOR_FLAG_UNSAFE; @@ -656,13 +677,13 @@ static void record_color_entry(struct dcp_display_mode *out, static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, struct color_mode *cmode, const struct timing_color_restrictions *limits, - bool dsc, bool allow_unsafe) + bool dsc, bool downstream_420) { - unsigned int rank = pq_mode_rank(cmode); + unsigned int rank = pq_mode_rank(cmode, downstream_420); bool needs_dsc = timing_color_contains(&limits->dsc_required, cmode->id); if (!rank || (needs_dsc && !dsc) || - (!allow_unsafe && timing_color_contains(&limits->unsafe, cmode->id))) + timing_color_contains(&limits->unsafe, cmode->id)) return; /* Break equal format and depth ranks in favour of no compression. */ @@ -671,7 +692,8 @@ static void collect_pq_mode(struct dcp_color_mode *pq, unsigned int *best_rank, return; if (rank > *best_rank) pq->score = -1; - fill_color_mode(pq, cmode); + if (!fill_color_mode(pq, cmode) && downstream_420 && pq->id == cmode->id) + pq->format = DCP_COLOR_FORMAT_YCBCR420; *best_rank = rank; } @@ -711,17 +733,18 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, { struct iterator outer_it; struct dcp_color_mode bootstrap = { .score = -1 }; - struct dcp_color_mode unsafe_pq = { .score = -1 }; - s64 color_scores[DCP_MAX_COLOR_ENTRIES]; + s64 *color_scores; unsigned int best_sdr_rank = 0, best_unsafe_rank = 0, best_pq_rank = 0; unsigned int best_unsafe_pq_rank = 0, best_rgb_rank = 0; int ret = 0; + out->sdr_444.score = -1; out->sdr_rgb.score = -1; out->sdr.score = -1; out->best.score = -1; out->pq.score = -1; out->nr_colors = 0; + out->sdr_unsafe_max_bpp = 0; out->sdr_usable = false; out->sdr_unsafe = false; out->has_bootstrap = false; @@ -730,11 +753,16 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, if (ret) return ret; + color_scores = kcalloc(DCP_MAX_COLOR_ENTRIES, sizeof(*color_scores), + GFP_KERNEL); + if (!color_scores) + return -ENOMEM; + for (; outer_it.idx < outer_it.len; ++outer_it.idx) { struct iterator it; static const char * const fields[] = { "Colorimetry", "Depth", "DynamicRange", "EOTF", "ID", "PixelEncoding", "Score", "IsVirtual" }; unsigned int seen = 0; - bool is_virtual = true; + bool is_virtual = true, downstream_420; s64 downstream_encoding = -1; struct color_mode cmode = { .colorimetry = -1, @@ -748,7 +776,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, ret = iterator_begin(handle, &it, true); if (ret) - return ret; + goto out_free; for (; it.idx < it.len; ++it.idx) { char *key = parse_string(it.handle); @@ -789,7 +817,7 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, kfree(key); if (ret) - return ret; + goto out_free; } /* @@ -808,32 +836,41 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, /* * DP-to-HDMI bridges downsample 4K60 YCbCr 4:4:4/4:2:2 to - * YCbCr 4:2:0 on the downstream link; expose the wire format. + * YCbCr 4:2:0 on the downstream link. Preserve cmode.pixel_encoding + * as the upstream encoding and flag the downstream wire format. */ - if (downstream_encoding == DCP_COLOR_FORMAT_YCBCR420) - cmode.pixel_encoding = DCP_COLOR_FORMAT_YCBCR420; + downstream_420 = downstream_encoding == DCP_COLOR_FORMAT_YCBCR420; trace_iomfb_color_mode(handle->dcp, cmode.id, cmode.score, cmode.depth, cmode.colorimetry, cmode.eotf, cmode.dynamic_range, cmode.pixel_encoding); - record_color_entry(out, color_scores, &cmode, limits, limits_known); + record_color_entry(out, color_scores, &cmode, limits, + limits_known, downstream_420); - if (limits_known) { + if (limits_known) collect_pq_mode(&out->pq, &best_pq_rank, &cmode, limits, - handle->pq_dsc, false); - if (!external_sdr) - collect_pq_mode(&unsafe_pq, &best_unsafe_pq_rank, - &cmode, limits, false, true); - } + handle->pq_dsc, downstream_420); if (cmode.eotf == DCP_EOTF_SDR_GAMMA && (!limits_known || (!timing_color_contains(&limits->unsafe, cmode.id) && - !timing_color_contains(&limits->dsc_required, cmode.id)))) + !timing_color_contains(&limits->dsc_required, cmode.id)))) { out->sdr_usable = true; - else if (!external_sdr && cmode.eotf == DCP_EOTF_SDR_GAMMA && - !timing_color_contains(&limits->dsc_required, cmode.id)) + } else if (!external_sdr && cmode.eotf == DCP_EOTF_SDR_GAMMA && + !timing_color_contains(&limits->dsc_required, cmode.id)) { out->sdr_unsafe = true; + if (cmode.depth >= 8 && cmode.depth <= 12 && + cmode.pixel_encoding >= 0 && + cmode.pixel_encoding < DCP_COLOR_FORMAT_COUNT) { + enum dcp_color_format wire_fmt = downstream_420 ? + DCP_COLOR_FORMAT_YCBCR420 : + cmode.pixel_encoding; + u8 bpp = color_wire_bpp(wire_fmt, cmode.depth); + + if (bpp > out->sdr_unsafe_max_bpp) + out->sdr_unsafe_max_bpp = bpp; + } + } if (external_sdr) { unsigned int rank; @@ -893,15 +930,55 @@ static int parse_color_modes(struct dcp_parse_ctx *handle, /* * Timings above HDMI 1.4's 340 MHz clock behind DP-to-HDMI 2.0 bridges * list every element in UnsafeColorElementIDs even though SDR already - * drives them through those unsafe elements. Fall back to the best - * non-DSC unsafe PQ element only on such unsafe-only timings, keeping - * UnsafeColorElementIDs strict whenever any safe SDR element exists. + * drives them through those unsafe elements. DCP firmware omits + * over-budget non-DSC modes from ColorModes (e.g. 12-bit RGB on + * 1080p180 and 10/12-bit RGB on 1440p144); as an additional link-budget + * guard, bound the fallback to the wire bpp of the timing's non-DSC + * unsafe SDR elements, and keep UnsafeColorElementIDs strict whenever + * any safe SDR element exists. */ - if (!external_sdr && out->pq.score < 0 && !out->sdr_usable && - out->sdr_unsafe && unsafe_pq.score >= 0) - out->pq = unsafe_pq; + if (!external_sdr && limits_known && out->pq.score < 0 && + !out->sdr_usable && out->sdr_unsafe) { + unsigned int i; - return 0; + for (i = 0; i < out->nr_colors; i++) { + const struct dcp_color_entry *e = &out->colors[i]; + bool ds420 = !!(e->flags & DCP_COLOR_FLAG_DOWNSTREAM_420); + enum dcp_color_format wire_fmt = ds420 ? + DCP_COLOR_FORMAT_YCBCR420 : e->format; + struct color_mode c = { + .id = e->id, + .depth = e->depth, + .dynamic_range = e->range, + .eotf = e->eotf, + .pixel_encoding = e->format, + .colorimetry = e->colorimetry, + .score = color_scores[i], + }; + unsigned int rank; + + if (e->flags & DCP_COLOR_FLAG_DSC) + continue; + if (out->sdr_unsafe_max_bpp && + color_wire_bpp(wire_fmt, e->depth) > out->sdr_unsafe_max_bpp) + continue; + rank = pq_mode_rank(&c, ds420); + if (!rank) + continue; + rank = 2 * rank + 1; + if (rank < best_unsafe_pq_rank) + continue; + if (rank > best_unsafe_pq_rank) + out->pq.score = -1; + if (!fill_color_mode(&out->pq, &c) && ds420 && out->pq.id == e->id) + out->pq.format = DCP_COLOR_FORMAT_YCBCR420; + best_unsafe_pq_rank = rank; + } + } + +out_free: + kfree(color_scores); + return ret; } /* @@ -980,13 +1057,12 @@ static int parse_mode(struct dcp_parse_ctx *handle, bool limits_known; struct drm_display_mode *mode = &out->mode; - *out = (struct dcp_display_mode) { - .sdr_rgb.score = -1, - .sdr_444.score = -1, - .sdr.score = -1, - .best.score = -1, - .pq.score = -1, - }; + memset(out, 0, sizeof(*out)); + out->sdr_rgb.score = -1; + out->sdr_444.score = -1; + out->sdr.score = -1; + out->best.score = -1; + out->pq.score = -1; *score = -1; handle->ambiguous_180hz = false; diff --git a/drivers/gpu/drm/apple/parser.h b/drivers/gpu/drm/apple/parser.h index 73491f2f6d89ef..d7edfa8721ca59 100644 --- a/drivers/gpu/drm/apple/parser.h +++ b/drivers/gpu/drm/apple/parser.h @@ -135,9 +135,10 @@ struct dcp_color_mode { u8 depth; }; -#define DCP_COLOR_FLAG_UNSAFE (1U << 0) -#define DCP_COLOR_FLAG_DSC (1U << 1) -#define DCP_MAX_COLOR_ENTRIES 64 +#define DCP_COLOR_FLAG_UNSAFE (1U << 0) +#define DCP_COLOR_FLAG_DSC (1U << 1) +#define DCP_COLOR_FLAG_DOWNSTREAM_420 (1U << 2) +#define DCP_MAX_COLOR_ENTRIES 64 /* Compact colour element retained per timing, sorted by descending score. */ struct dcp_color_entry { @@ -146,8 +147,7 @@ struct dcp_color_entry { u8 format : 4; u8 range : 1; u8 colorimetry : 5; - u8 flags : 2; - u8 reserved : 1; + u8 flags : 3; u8 depth; u8 pad; }; @@ -204,6 +204,8 @@ struct dcp_display_mode { /* Real colour elements reported for this timing, descending by score. */ struct dcp_color_entry colors[DCP_MAX_COLOR_ENTRIES]; u8 nr_colors; + /* Max wire bits/pixel among non-DSC unsafe SDR elements (0 if none). */ + u8 sdr_unsafe_max_bpp; }; struct dimension { diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index 7489f9cc66817b..66604bfdb7b3f7 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -1033,29 +1033,47 @@ def color_selection(root): assert(!dcp_select_color_mode(&msi, &req, &out) && out.id == 105); /* Unsafe-only >340 MHz HDMI 2.0 timing (e.g. 1080p180 / 1440p144): SDR already uses unsafe - * elements (sdr_usable=false, sdr_unsafe=true), so non-DSC unsafe PQ is permitted, whereas - * safe timings (sdr_usable=true) strictly reject unsafe PQ. */ + * elements (sdr_usable=false, sdr_unsafe=true), so non-DSC unsafe PQ within sdr_unsafe_max_bpp + * is permitted, whereas safe timings (sdr_usable=true) strictly reject unsafe SDR and PQ. */ struct dcp_display_mode msi144 = { .sdr_rgb = acer.sdr_rgb, .color_mode_id = 80, - .sdr_usable = false, .sdr_unsafe = true, + .sdr_usable = false, .sdr_unsafe = true, .sdr_unsafe_max_bpp = 24, .pq = { .score = 10, .id = 105, .eotf = DCP_EOTF_ST_2084, .format = DCP_COLOR_FORMAT_YCBCR422, .colorimetry = DCP_COLORIMETRY_BT2020_YCC, .range = DCP_COLOR_YCBCR_RANGE_LIMITED, .depth = 12 } }; add_entry(&msi144, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); add_entry(&msi144, 113, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE | DCP_COLOR_FLAG_DSC); + add_entry(&msi144, 114, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_BT2020_RGB, DCP_COLOR_YCBCR_RANGE_FULL, 10, DCP_COLOR_FLAG_UNSAFE); add_entry(&msi144, 105, DCP_EOTF_ST_2084, DCP_COLOR_FORMAT_YCBCR422, DCP_COLORIMETRY_BT2020_YCC, DCP_COLOR_YCBCR_RANGE_LIMITED, 12, DCP_COLOR_FLAG_UNSAFE); req = (struct dcp_color_request){ .eotf = HDMI_EOTF_SMPTE_ST2084, .colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC, .color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422, .max_bpc = 12, .allow_hdr = true, .allow_dsc = true, .allow_unsafe_sdr = true }; assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 105); - /* DSC-required unsafe PQ (113) MUST be rejected even with allow_dsc=true */ + /* Non-DSC 30-bpp RGB PQ (114) exceeds 24-bpp unsafe SDR ceiling -> rejected; 30-bpp SDR admits it */ req.color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_RGB; assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); - /* Same unsafe entry on a timing with sdr_usable=true MUST be rejected */ + msi144.sdr_unsafe_max_bpp = 30; + assert(!dcp_select_color_mode(&msi144, &req, &out) && out.id == 114); + msi144.sdr_unsafe_max_bpp = 24; + /* DSC-required unsafe PQ (113) MUST be rejected even with allow_dsc=true and 30-bpp SDR */ + msi144.colors[2].flags |= DCP_COLOR_FLAG_DSC; + msi144.sdr_unsafe_max_bpp = 30; + assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + /* Same unsafe entry on a timing with sdr_usable=true MUST be rejected (for both HDR and SDR) */ msi144.sdr_usable = true; req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR422; req.colorspace = DRM_MODE_COLORIMETRY_BT2020_YCC; assert(dcp_select_color_mode(&msi144, &req, &out) == -EINVAL); + /* Explicit SDR request on a safe timing (e.g. 4K60 where only 4:2:0 is safe) MUST NOT fall through to unsafe SDR */ + struct dcp_display_mode k4 = { .color_mode_id = 119, .sdr_usable = true, .sdr_unsafe = true }; + add_entry(&k4, 80, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_RGB, DCP_COLORIMETRY_SRGB, DCP_COLOR_YCBCR_RANGE_FULL, 8, DCP_COLOR_FLAG_UNSAFE); + add_entry(&k4, 119, DCP_EOTF_SDR_GAMMA, DCP_COLOR_FORMAT_YCBCR444, DCP_COLORIMETRY_BT709, DCP_COLOR_YCBCR_RANGE_LIMITED, 8, DCP_COLOR_FLAG_DOWNSTREAM_420); + req = (struct dcp_color_request){ .color_format = DRM_CONNECTOR_COLOR_FORMAT_RGB444, .max_bpc = 8, .allow_unsafe_sdr = true }; + assert(dcp_select_color_mode(&k4, &req, &out) == -EINVAL); + /* DownstreamFormat 4:2:0 matches YCBCR420 and reports wire YCbCr 4:2:0 while preserving upstream format */ + req.color_format = DRM_CONNECTOR_COLOR_FORMAT_YCBCR420; + assert(!dcp_select_color_mode(&k4, &req, &out) && out.id == 119 && out.format == DCP_COLOR_FORMAT_YCBCR420); + assert(k4.colors[1].format == DCP_COLOR_FORMAT_YCBCR444); puts("PASS: colour mode selection across RGB/YCbCr 444/422/420, 8/10/12 bpc, Full/Limited, wide gamut, PQ/HLG, and -EINVAL rejection"); return 0; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index c6f45f9a6582c9..d06fe608118556 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1844,7 +1844,7 @@ def vrr(root): DCP_FIRMWARE_V_14_7, DCP_FIRMWARE_V_14_7_TEMPLATE, DCP_FIRMWARE_V_26_6, DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0 }; struct apple_dcp { - bool crashed, external, external_native, quiescing, main_display, panel; + bool crashed, external, external_native, quiescing, main_display, panel, iomfb_template_pq; int peer_check; /* what the firmware 27 paired-timing check answers */ unsigned int nr_typec_routes; enum dcp_firmware_version fw_compat; @@ -1954,6 +1954,7 @@ def vrr(root): # VRR_ENABLED change must never become a mode set. The external # processors ignore a live minimum rate and still apply it with a mode set. desktop = r""" dcp.fw_compat = DCP_FIRMWARE_V_26_6_DESKTOP; + dcp.iomfb_template_pq = true; dcp.hw.iomfb_method_profile = 0; dcp.mode_state.valid = true; dcp.connector = &connector; @@ -1979,12 +1980,14 @@ def vrr(root): cases++; } dcp.main_display = false; + dcp.iomfb_template_pq = false; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ # Firmware 27: its externals change adaptive sync with a full mode set, as # macOS switches between a timing's fixed and variable modes; the panel # does not. A paired timing the pair cannot take fails the check. fw27 = r""" dcp.fw_compat = DCP_FIRMWARE_V_27_0; + dcp.iomfb_template_pq = true; dcp.hw.iomfb_method_profile = 0; dcp.mode_state.valid = true; dcp.connector = &connector; @@ -2018,10 +2021,11 @@ def vrr(root): dcp.panel = false; dcp.peer_check = 0; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; - /* Legacy 12.3/13.5/14.7_tpl DCPs program VRR inside iomfb_modeset(). */ + /* Template-driven 12.3/13.5/14.7_tpl DCPs program VRR inside iomfb_modeset(). */ const enum dcp_firmware_version tpl_fws[] = { DCP_FIRMWARE_V_12_3, DCP_FIRMWARE_V_13_5, DCP_FIRMWARE_V_14_7_TEMPLATE }; + dcp.iomfb_template_pq = true; for (unsigned int i = 0; i < 3; i++) { dcp.fw_compat = tpl_fws[i]; state.crtc.enable = true; @@ -2035,6 +2039,7 @@ def vrr(root): assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && !state.crtc.mode_changed); cases += 2; } + dcp.iomfb_template_pq = false; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ return prefix + check + suffix.replace('DESKTOP_VRR', desktop, 1).replace('FW27_VRR', fw27, 1) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index 1243fee58f3e37..d8087416a52eb6 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -114,19 +114,29 @@ def color(i, score, depth, eotf, colorimetry, encoding=0, dynamic=0): dsc_raw = bytearray(struct.pack('340 MHz timing (e.g. 1080p180 / 1440p144): every - # element is in UnsafeColorElementIDs, so SDR already uses an unsafe element - # and PQ falls back to the best non-DSC unsafe PQ element. + # An unsafe-only HDMI 2.0 >340 MHz timing (e.g. 1440p144): 8-bit SDR (24 bpp) + # caps non-DSC unsafe PQ to <=24 bpp (12-bit 4:2:2 id 105), rejecting both + # DSC-required PQ (113) and over-budget non-DSC 10-bit RGB PQ (114, 30 bpp). unsafe_only_fixture = [dict(timing_fixture[0], ColorModes=[ - color(80, 1, 8, 0, 10), color(105, 5, 12, 2, 7, encoding=2), - color(113, 9, 10, 2, 9)], - UnsafeColorElementIDs=[80, 105, 113], DSCRequiredColorElementIDs=[113])] + color(114, 20, 10, 2, 9), color(105, 5, 12, 2, 7, encoding=2), + color(113, 9, 10, 2, 9), color(80, 1, 8, 0, 10)], + UnsafeColorElementIDs=[80, 105, 113, 114], DSCRequiredColorElementIDs=[113])] unsafe_only_raw = bytearray(struct.pack('340 MHz timing falls back to non-DSC unsafe PQ (105), - * still skipping DSC-required unsafe PQ (113) even when pq_dsc is true. */ + /* Unsafe-only >340 MHz timing falls back to non-DSC unsafe PQ within + * sdr_unsafe_max_bpp: 24-bpp SDR picks 12-bit 4:2:2 (105) over 30-bpp + * non-DSC RGB (114) and DSC-required RGB (113); 30-bpp SDR picks 114. */ for (unsigned int dsc = 0; dsc < 2; dsc++) { assert(!parse(unsafe_only_blob, sizeof(unsafe_only_blob), &c)); c.pq_dsc = dsc; m = enumerate_modes(&c, &n, 600, 330, 0, false, false); assert(!IS_ERR(m) && n == 1 && !m[0].sdr_usable && m[0].sdr_unsafe); + assert(m[0].sdr_unsafe_max_bpp == 24); assert(m[0].pq.id == 105 && m[0].pq.depth == 12 && m[0].pq.format == DCP_COLOR_FORMAT_YCBCR422); free(m); } - /* DP-to-HDMI bridge 4K60 DownstreamFormat exposes true wire YCbCr 4:2:0 - * (CE 119 SDR, CE 162 PQ) without aliasing 4:4:4 (83) or 4:2:2 (105). */ + assert(!parse(unsafe_30bpp_blob, sizeof(unsafe_30bpp_blob), &c)); + m = enumerate_modes(&c, &n, 600, 330, 0, false, false); + assert(!IS_ERR(m) && n == 1 && m[0].sdr_unsafe_max_bpp == 30); + assert(m[0].pq.id == 114 && m[0].pq.depth == 10 && + m[0].pq.format == DCP_COLOR_FORMAT_RGB); + free(m); + /* DP-to-HDMI bridge 4K60 DownstreamFormat flags true wire YCbCr 4:2:0 + * (CE 119 SDR, CE 162 PQ) while keeping upstream format intact (CE 80 + * stays in sdr_rgb, CE 83 stays 4:4:4, CE 105 stays 4:2:2). */ assert(!parse(ds420_blob, sizeof(ds420_blob), &c)); m = enumerate_modes(&c, &n, 600, 330, 0, false, false); - assert(!IS_ERR(m) && n == 1 && m[0].sdr_usable && m[0].sdr_444.id == 83); + assert(!IS_ERR(m) && n == 1 && m[0].sdr_usable && + m[0].sdr_rgb.id == 80 && m[0].sdr_rgb.format == DCP_COLOR_FORMAT_RGB && + m[0].sdr_444.id == 83); { unsigned int found_420_sdr = 0, found_420_pq = 0, found_444 = 0, found_422 = 0; for (unsigned int j = 0; j < m[0].nr_colors; j++) { if (m[0].colors[j].id == 119) { - assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR420 && + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR444 && + (m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420) && !(m[0].colors[j].flags & DCP_COLOR_FLAG_UNSAFE)); found_420_sdr++; } else if (m[0].colors[j].id == 162) { - assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR420 && + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR422 && + (m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420) && (m[0].colors[j].flags & DCP_COLOR_FLAG_UNSAFE)); found_420_pq++; } else if (m[0].colors[j].id == 83) { - assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR444); + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR444 && + !(m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420)); found_444++; } else if (m[0].colors[j].id == 105) { - assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR422); + assert(m[0].colors[j].format == DCP_COLOR_FORMAT_YCBCR422 && + !(m[0].colors[j].flags & DCP_COLOR_FLAG_DOWNSTREAM_420)); found_422++; } } @@ -1026,7 +1051,7 @@ def publication(root): + mode_helpers) # The desktop 26.6 VRR filter is gone once that firmware takes adaptive sync. vrr_filter = block(iomfb,'static bool dcp_mode_vrr_supported(')+'\n' if 'static bool dcp_mode_vrr_supported(' in iomfb else '' - publication = block(iomfb,'static void dcp_clear_connector_edid(')+'\n'+block(iomfb,'static void dcp_consume_edid_invalidation(')+mode_helpers+vrr_filter+block(iomfb,'int dcp_get_modes(')+block(iomfb,'bool lookup_mode(') + publication = block(iomfb,'static void dcp_clear_connector_edid(')+'\n'+block(iomfb,'static void dcp_consume_edid_invalidation(')+mode_helpers+vrr_filter+block(iomfb,'int dcp_get_modes(')+block(iomfb,'static const struct dcp_display_mode *\ndcp_find_mode(')+block(iomfb,'bool lookup_mode(') if 'dcp_edid_sdr(' in publication: # Keep extracting the real publication path, including its SDR helper. # Model only kernel allocation/DRM ownership at the host boundary. From 1e10b5670f51816c5a43f4499f071d57ad24d659 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Bal=C3=A1zsy?= Date: Mon, 16 Nov 2026 10:06:19 +0100 Subject: [PATCH 0937/1514] phy: apple: t6040: DP tunnel pixel clock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In CIO mode the T6040 ATC PHY's AUSPLL feeds the pixel clocks of the router's DP IN adapters: one fixed AUSPLL frequency, a divider select per link rate in TX_DP_CTRL0 (RBR 4, HBR 3, HBR2 1, HBR3 0), the clock switch gate in the cfg bank, and the stop. DP IN 0 uses PCLK1 and switch 1; DP IN 1 uses PCLK2 and switch 2 and needs PCLK1 running as well. appledrm drives it through phy_configure() on the PHY's DP phy, with three new DP options: set_tunnel_rate, tunnel_dpin and tunnel_rate (the DP link rate code, 0 to stop). Which path a tunnel takes follows the PHY behind the route, not the machine: an "apple,t6040-atcphy" PHY clocks the tunnel itself (on T6040 and T6041 alike) and needs no apple_atc_dp_tunnel_open(). The PHY stops the tunnel clocks when it leaves CIO. [petr: taken from fbalazsy/linux j616s/split-display (the tunnel clock, 432f1ec86 "give the DP tunnel pixel clock a symbol of its own" and 346a417f7 "give DP IN 1 of a tunnel its PCLK1 prerequisite") onto integration/aurora. Tested on the J614s with a Studio Display (2022) on Thunderbolt up to 5120x2880@60, aurora-silicon/linux#1589.] [petr: per review, the clock goes through phy_configure() instead of an exported apple_t6040_dp_tunnel_rate(), and dcp-fabric selects it by the PHY's compatible instead of of_machine_is_compatible("apple,t6040"/"t6041").] [petr: per review, the AUSPLL start waits for ACK at either level and for the lock, as the stop does; retuning DP IN 0 keeps PCLK1 on under a running DP IN 1; a DP IN 1 whose switch 1 times out also releases it.] Signed-off-by: FrantiÅ¡ek Balázsy Signed-off-by: Petr Å kuta <20834920+petrskuta@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp-fabric.c | 50 ++++- drivers/phy/apple/t6040-usb2.c | 306 +++++++++++++++++++++++++++++ include/linux/phy/phy-dp.h | 28 +++ 3 files changed, 379 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index eda8620c020ebc..b4be5bc2da3919 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -458,6 +458,31 @@ bool dcp_is_typec_only(struct platform_device *pdev) return !dcp->fixed_phy; } +/* + * Whether @phy's own PLL clocks the DP IN adapters of its USB4 router, so that + * the tunnel's pixel clock is set through phy_configure(), a property of the + * PHY: the T6040 ATC PHY (M4 Pro/Max, also on T6041) feeds DP IN 0 and 1 from + * its AUSPLL. Such a PHY also needs no apple_atc_dp_tunnel_open(). + */ +static bool dcp_phy_clocks_tunnel(struct phy *phy) +{ + return phy && of_device_is_compatible(phy->dev.of_node, "apple,t6040-atcphy"); +} + +/* Start the tunnel pixel clock of DP IN @dpin at link rate code @rate, or stop it (0). */ +static int dcp_phy_tunnel_rate(struct phy *phy, unsigned int dpin, u8 rate) +{ + union phy_configure_opts opts = { + .dp = { + .set_tunnel_rate = 1, + .tunnel_dpin = dpin, + .tunnel_rate = rate, + }, + }; + + return phy_configure(phy, &opts); +} + static int dcp_route_clock_rate(struct apple_dcp_typec_route *route, struct phy *phy, unsigned int dpin, u8 rate) { @@ -481,6 +506,14 @@ static int dcp_route_clock_rate(struct apple_dcp_typec_route *route, return ret; } + /* A PHY whose own PLL feeds the DP IN pixel clocks takes the rate itself. */ + if (dcp_phy_clocks_tunnel(phy)) { + ret = dcp_phy_tunnel_rate(phy, dpin, rate); + if (!ret) + route->tunnel_rate = rate; + return ret; + } + /* A T8132 dcpext names its source (2 or 4), as T6030 does. */ if (of_machine_is_compatible("apple,t6030") || t8132) { typeof(apple_atc_dp_tunnel_rate_source) *fn; @@ -2333,6 +2366,9 @@ static void dcp_tunnel_prepare(struct apple_dcp_typec_route *route, if (ret && ret != -EOPNOTSUPP) dev_warn(dcp->dev, "DP tunnel crossbar preselect failed: %d\n", ret); + /* The clock call starts everything on a PHY that clocks the tunnel. */ + if (dcp_phy_clocks_tunnel(dcp->phy)) + return; open = symbol_get(apple_atc_dp_tunnel_open); if (!open) return; @@ -3155,12 +3191,16 @@ static int dcp_tb_split_teardown_locked(struct apple_dcp_typec_port *port, /* Retire the callback before dropping its clock reference. */ dcp->split.active = false; if (dcp->phy) { - typeof(apple_atc_dp_tunnel_rate) *stop = - symbol_get(apple_atc_dp_tunnel_rate); + if (dcp_phy_clocks_tunnel(dcp->phy)) { + dcp_phy_tunnel_rate(dcp->phy, 1, 0); + } else { + typeof(apple_atc_dp_tunnel_rate) *stop = + symbol_get(apple_atc_dp_tunnel_rate); - if (stop) { - stop(dcp->phy, 1, 0); - symbol_put(apple_atc_dp_tunnel_rate); + if (stop) { + stop(dcp->phy, 1, 0); + symbol_put(apple_atc_dp_tunnel_rate); + } } } if (dcp->split.xbar) { diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 4e995d029785cc..0a501ac9fe27e5 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -294,6 +294,9 @@ struct t6040_usb2_phy { bool usb3_lent; /* DP mode took the lanes of this Type-C port */ bool pipe_switched; /* the controller's PIPE runs on this PHY */ bool cio_up; /* the lanes run USB4/Thunderbolt */ + u8 tun_rate[2]; /* DP tunnel link rate per DP IN adapter, 0 = off */ + bool tun_pre; /* switch 1 is held for DP IN 1 alone */ + bool tun_pll; /* AUSPLL programmed for DP tunnels */ /* DisplayPort; dp_ok is false when the DT lacks a DP route */ struct phy *dp; @@ -1770,11 +1773,14 @@ static int t6040_cio_up_locked(struct t6040_usb2_phy *tphy) return ret; } +static void t6040_tun_stop_all_locked(struct t6040_usb2_phy *tphy); + static void t6040_cio_down_locked(struct t6040_usb2_phy *tphy) { lockdep_assert_held(&tphy->lock); if (!tphy->cio_up) return; + t6040_tun_stop_all_locked(tphy); t6040_phy_tx_cmn_down(tphy); t6040_cio_rx_down(tphy); fsleep(200); @@ -1880,6 +1886,8 @@ static int t6040_dp_validate(struct phy *phy, enum phy_mode mode, int submode, return 0; } +static int t6040_tun_rate_locked(struct t6040_usb2_phy *tphy, unsigned int dpin, u8 rate); + static int t6040_dp_configure(struct phy *phy, union phy_configure_opts *opts_) { struct t6040_usb2_phy *tphy = phy_get_drvdata(phy); @@ -1888,6 +1896,13 @@ static int t6040_dp_configure(struct phy *phy, union phy_configure_opts *opts_) int ret; guard(mutex)(&tphy->lock); + /* A DP tunnel's pixel clock, PHY in CIO: see "DP tunnels" below. */ + if (opts->set_tunnel_rate) { + if (opts->set_rate || opts->set_lanes || opts->set_voltages || + opts->tunnel_dpin > 1) + return -EINVAL; + return t6040_tun_rate_locked(tphy, opts->tunnel_dpin, opts->tunnel_rate); + } if (!tphy->dp_up) return -EINVAL; if ((opts->set_lanes || opts->set_voltages) && @@ -1950,6 +1965,297 @@ static const struct phy_ops t6040_dp_phy_ops = { .set_mode = t6040_dp_set_mode, }; +/* ---- DP tunnels: the pixel clocks of the router's DP IN adapters (PHY in CIO) ---- + * + * The DP 1.4 tunnel's init, update and shutdown and the DP clock + * configuration: one fixed AUSPLL frequency feeds the DPTX pixel clocks, + * whose select field divides it per link rate. DP IN adapter 0 is taken to + * use PCLK1 and clock switch 1, adapter 1 PCLK2 and switch 2 (the PHY does + * not choose: the index is the display controller's). Driven only by + * appledrm, through phy_configure() with the DP options' set_tunnel_rate + * (t6040_dp_configure()), and only while the PHY is in CIO. + */ +#define T6040_CORE_RCAL1 0x804 /* AUS40CMN_DIG RCAL1 */ +#define T6040_CORE_RCAL1_DONE BIT(0) +#define T6040_CORE_AUSPLL_CMD 0x3000 /* AUSPLL_TOP_APB_CMD_CMDOVERRIDE */ +#define T6040_CORE_AUSPLL_CMD_REQ BIT(0) +#define T6040_CORE_AUSPLL_CMD_ACK BIT(1) +#define T6040_CORE_AUSPLL_FREQDESC_A 0x3080 +#define T6040_CORE_AUSPLL_FREQDESC_B 0x3084 +#define T6040_CORE_AUSPLL_FREQDESC_C 0x3088 +#define T6040_CORE_AUSPLL_CLKOUT_MASTER 0x3200 +#define T6040_CORE_AUSPLL_CLKOUT_DIV 0x3208 +#define T6040_CORE_AUSPLL_BGR 0x3218 +#define T6040_CORE_AUSPLL_FREQINIT_1 0x3234 +#define T6040_CORE_TX_DP_CTRL0 0x7000 +#define T6040_CORE_TX_DP_CTRL0_ENABLES GENMASK(18, 16) +#define T6040_CORE_DP_PCLK_STATUS 0x7034 +#define T6040_CORE_DP_PCLK_STATUS_LOCK BIT(3) /* AUSPLL_LOCK */ + +static const struct t6040_tun_pclk { + u8 sel_shift; /* TX_DP_CTRL0 select field */ + u32 en; /* TX_DP_CTRL0 enable */ + u32 sw_mask, sw_gate, sw_on; /* clock switch: cleared, set, status when on */ + u32 req[2], req_stat[2], sw_off; /* PMGR requests, their status, cleared at off */ +} t6040_tun_pclk[2] = { + { 4, BIT(16), 0x473, 0x10, BIT(0), { 0x20, 0x40 }, { BIT(1), BIT(2) }, 0x403 }, + { 8, BIT(17), 0xb8c, 0x80, BIT(3), { 0x100, 0x200 }, { BIT(4), BIT(5) }, 0x80c }, +}; + +/* The pixel clock select: RBR, HBR, HBR2, HBR3; UHBR is not tunnelled on this path. */ +static int t6040_tun_select(u8 rate) +{ + switch (rate) { + case 0x06: + return 4; + case 0x0a: + return 3; + case 0x14: + return 1; + case 0x1e: + return 0; + default: + return -EINVAL; + } +} + +/* DP IN 1 runs on PCLK2 and needs PCLK1 as well: without it its video stops. */ +static u32 t6040_tun_enables(struct t6040_usb2_phy *tphy) +{ + return ((tphy->tun_rate[0] || tphy->tun_rate[1]) ? t6040_tun_pclk[0].en : 0) | + (tphy->tun_rate[1] ? t6040_tun_pclk[1].en : 0); +} + +/* AUSPLL_TOP command override: request @req with the toggle protocol, then wait for @ack. */ +static int t6040_tun_pll_cmd(struct t6040_usb2_phy *tphy, u32 val, bool ack_set) +{ + void __iomem *cmd = t6040_core(tphy) + T6040_CORE_AUSPLL_CMD; + u32 v; + + writel((readl(cmd) & 0xe0000006) | val, cmd); + return readl_poll_timeout(cmd, v, !!(v & T6040_CORE_AUSPLL_CMD_ACK) == ack_set, + 10, 500 * USEC_PER_MSEC); +} + +/* The DP 1.4 tunnel shutdown: pixel clocks off, AUSPLL released. */ +static void t6040_tun_pll_stop(struct t6040_usb2_phy *tphy) +{ + void __iomem *core = t6040_core(tphy); + bool ack = readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_ACK; + u32 v; + + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, T6040_CORE_TX_DP_CTRL0_ENABLES); + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, 0xc); + if (t6040_tun_pll_cmd(tphy, (ack ? 0 : T6040_CORE_AUSPLL_CMD_REQ) | 0x10000000, !ack) || + t6040_tun_pll_cmd(tphy, (ack ? T6040_CORE_AUSPLL_CMD_REQ : 0) | 0x10000018, ack) || + readl_poll_timeout(core + T6040_CORE_DP_PCLK_STATUS, v, + !(v & T6040_CORE_DP_PCLK_STATUS_LOCK), 10, 500 * USEC_PER_MSEC)) + dev_warn(tphy->dev, "DP tunnel: AUSPLL release timed out (cmd %#x, pclk status %#x)\n", + readl(core + T6040_CORE_AUSPLL_CMD), + readl(core + T6040_CORE_DP_PCLK_STATUS)); + t6040_usb2_clear32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x8); + tphy->tun_pll = false; +} + +/* The common block's init, then the fixed AUSPLL program of the DP 1.4 tunnel init. */ +static int t6040_tun_pll_start(struct t6040_usb2_phy *tphy) +{ + void __iomem *core = t6040_core(tphy); + bool ack; + u32 v; + + if ((readl(core + T6040_CORE_AUSPLL_CLKOUT_MASTER) & 0x808) || + (readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_REQ)) { + dev_warn(tphy->dev, "DP tunnel: AUSPLL already in use (master %#x, cmd %#x)\n", + readl(core + T6040_CORE_AUSPLL_CLKOUT_MASTER), + readl(core + T6040_CORE_AUSPLL_CMD)); + return -EBUSY; + } + t6040_usb2_clear32(core + T6040_CORE_TX_DP_CTRL0, T6040_CORE_TX_DP_CTRL0_ENABLES); + + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x4); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x8); + udelay(1); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x1); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x2); + udelay(1); + t6040_usb2_clear32(core + T6040_CORE_CMN_OVRD, T6040_CORE_CMN_OVRD_CLAMP); + t6040_usb2_set32(core + T6040_CORE_CMN_OVRD, 0x20); + udelay(1); + t6040_usb2_set32(core + T6040_CORE_CMN_BIAS, T6040_CORE_CMN_BIAS_BGBIAS_EN_OV); + udelay(15); + if (readl_poll_timeout(core + T6040_CORE_RCAL1, v, v & T6040_CORE_RCAL1_DONE, 1, 100)) + dev_dbg(tphy->dev, "DP tunnel: RCAL not done (%#x)\n", v); + + t6040_usb2_clear32(core + T6040_CORE_AUSPLL_FREQINIT_1, 0x3); + writel(0x1e0e021c, core + T6040_CORE_AUSPLL_FREQDESC_A); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_FREQDESC_B, 0x0fffffff, 0); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_FREQDESC_C, 0x007fffff, 0x644a00); + t6040_usb2_mask32(core + T6040_CORE_AUSPLL_CLKOUT_DIV, 0x001f0000, 0x10000); + t6040_usb2_set32(core + T6040_CORE_AUSPLL_BGR, 0x1); + t6040_usb2_set32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x808); + tphy->tun_pll = true; + + /* + * Toggle protocol, as in the stop: the request flips REQ and waits for + * ACK to follow, whichever level a PHY reset left it at. The pixel + * clock must lock either way. + */ + ack = readl(core + T6040_CORE_AUSPLL_CMD) & T6040_CORE_AUSPLL_CMD_ACK; + if (t6040_tun_pll_cmd(tphy, (ack ? 0 : T6040_CORE_AUSPLL_CMD_REQ) | 0x10000000, !ack) || + readl_poll_timeout(core + T6040_CORE_DP_PCLK_STATUS, v, + v & T6040_CORE_DP_PCLK_STATUS_LOCK, + 10, 500 * USEC_PER_MSEC) || + t6040_tun_pll_cmd(tphy, (ack ? T6040_CORE_AUSPLL_CMD_REQ : 0) | 0x10010000, ack)) { + dev_err(tphy->dev, "DP tunnel: AUSPLL did not lock (cmd %#x, pclk status %#x)\n", + readl(core + T6040_CORE_AUSPLL_CMD), + readl(core + T6040_CORE_DP_PCLK_STATUS)); + t6040_tun_pll_stop(tphy); + return -ETIMEDOUT; + } + t6040_usb2_set32(core + T6040_CORE_TX_DP_CTRL0, 0xc); + return 0; +} + +static void t6040_tun_select_field(u32 *v, const struct t6040_tun_pclk *p, int sel, bool en) +{ + if (!!(*v & p->en) != en || ((*v >> p->sel_shift) & 0xf) != sel) + *v = (*v & ~(p->en | (0xf << p->sel_shift))) | (sel << p->sel_shift); +} + +/* The DP 1.4 tunnel update for one pclk: select with its enable off, then the enables. */ +static void t6040_tun_select_write(struct t6040_usb2_phy *tphy, unsigned int dpin, int sel) +{ + void __iomem *ctrl0 = t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0; + u32 v = readl(ctrl0); + + t6040_tun_select_field(&v, &t6040_tun_pclk[dpin], sel, !!tphy->tun_rate[dpin]); + /* PCLK1 is DP IN 1's prerequisite at its own rate, unless DP IN 0 runs on it. */ + if (dpin == 1 && !tphy->tun_rate[0]) + t6040_tun_select_field(&v, &t6040_tun_pclk[0], sel, true); + /* Retuning DP IN 0 must not gate PCLK1 under a running DP IN 1. */ + if (dpin == 0 && tphy->tun_rate[1]) + v |= t6040_tun_pclk[0].en; + writel(v, ctrl0); + writel((v & ~T6040_CORE_TX_DP_CTRL0_ENABLES) | t6040_tun_enables(tphy), ctrl0); +} + +/* The DP clock configuration for one DP 1.x switch: pixel-clock gate on, or off. */ +static int t6040_tun_switch(struct t6040_usb2_phy *tphy, unsigned int dpin, bool on) +{ + const struct t6040_tun_pclk *p = &t6040_tun_pclk[dpin]; + void __iomem *cfg = t6040_cfg(tphy); + unsigned int i; + u32 s; + + if (on) { + t6040_usb2_mask32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_mask, p->sw_gate); + return readl_poll_timeout(cfg + T6040_CFG_DP_CLKSWITCH_STAT, s, s & p->sw_on, + 10, 5 * USEC_PER_MSEC); + } + t6040_usb2_set32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_gate); + for (i = 0; i < 2; i++) { + if (!(readl(cfg + T6040_CFG_DP_CLKSWITCH_CTRL) & p->req[i])) + continue; + t6040_usb2_clear32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->req[i]); + if (readl_poll_timeout(cfg + T6040_CFG_DP_CLKSWITCH_STAT, s, !(s & p->req_stat[i]), + 10, 5 * USEC_PER_MSEC)) + dev_dbg(tphy->dev, "DP tunnel %u: request %#x not released (%#x)\n", + dpin, p->req[i], s); + } + t6040_usb2_clear32(cfg + T6040_CFG_DP_CLKSWITCH_CTRL, p->sw_off); + return 0; +} + +/* All tunnel clocks down, which the PHY's shutdown of mode 2 starts with. */ +static void t6040_tun_stop_all_locked(struct t6040_usb2_phy *tphy) +{ + unsigned int dpin; + + lockdep_assert_held(&tphy->lock); + if (!tphy->tun_pll) + return; + for (dpin = 0; dpin < 2; dpin++) { + if (!tphy->tun_rate[dpin]) + continue; + tphy->tun_rate[dpin] = 0; + t6040_tun_switch(tphy, dpin, false); + } + if (tphy->tun_pre) { + tphy->tun_pre = false; + t6040_tun_switch(tphy, 0, false); + } + t6040_tun_pll_stop(tphy); + dev_info(tphy->dev, "DP tunnel clocks off\n"); +} + +static int t6040_tun_rate_locked(struct t6040_usb2_phy *tphy, unsigned int dpin, u8 rate) +{ + int sel, ret; + u8 old = tphy->tun_rate[dpin]; + + lockdep_assert_held(&tphy->lock); + if (!rate) { + if (!old) + return 0; + tphy->tun_rate[dpin] = 0; + if (dpin == 0 && tphy->tun_rate[1]) { + /* DP IN 1 keeps PCLK1 and its switch, now at its own rate. */ + tphy->tun_pre = true; + t6040_tun_select_write(tphy, 1, t6040_tun_select(tphy->tun_rate[1])); + } else { + t6040_tun_switch(tphy, dpin, false); + if (dpin == 1 && tphy->tun_pre) { + tphy->tun_pre = false; + t6040_tun_switch(tphy, 0, false); + } + } + t6040_usb2_mask32(t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0, + T6040_CORE_TX_DP_CTRL0_ENABLES, t6040_tun_enables(tphy)); + if (!tphy->tun_rate[!dpin]) + t6040_tun_pll_stop(tphy); + dev_dbg(tphy->dev, "DP tunnel %u off\n", dpin); + return 0; + } + sel = t6040_tun_select(rate); + if (sel < 0) + return sel; + if (!tphy->cio_up) + return -EBUSY; + if (old == rate) + return 0; + if (!tphy->tun_pll) { + ret = t6040_tun_pll_start(tphy); + if (ret) + return ret; + } + tphy->tun_rate[dpin] = rate; + t6040_tun_select_write(tphy, dpin, sel); + /* DP IN 1 alone: switch 1 passes PCLK1, its prerequisite. */ + if (dpin == 1 && !tphy->tun_rate[0] && !tphy->tun_pre) { + /* Owned before it is gated on, so a timeout below also releases it. */ + tphy->tun_pre = true; + ret = t6040_tun_switch(tphy, 0, true); + if (ret) + goto switch_failed; + } else if (dpin == 0) { + tphy->tun_pre = false; /* DP IN 0 owns switch 1 again */ + } + ret = t6040_tun_switch(tphy, dpin, true); +switch_failed: + if (ret) { + dev_err(tphy->dev, "DP tunnel %u: clock switch timed out (ctrl %#x status %#x)\n", + dpin, readl(t6040_cfg(tphy) + T6040_CFG_DP_CLKSWITCH_CTRL), + readl(t6040_cfg(tphy) + T6040_CFG_DP_CLKSWITCH_STAT)); + t6040_tun_rate_locked(tphy, dpin, 0); + return ret; + } + dev_info(tphy->dev, "DP tunnel %u: rate %#x, select %d (ctrl0 %#x, pclk status %#x)\n", + dpin, rate, sel, readl(t6040_core(tphy) + T6040_CORE_TX_DP_CTRL0), + readl(t6040_core(tphy) + T6040_CORE_DP_PCLK_STATUS)); + return 0; +} + /* ---- Type-C mode switch: the Type-C controller asks for DP on a USB-C port ---- */ static int t6040_dp_mux_set(struct typec_mux_dev *mux, struct typec_mux_state *state) diff --git a/include/linux/phy/phy-dp.h b/include/linux/phy/phy-dp.h index 9cce5766bc0b89..bdedc2c3517a7d 100644 --- a/include/linux/phy/phy-dp.h +++ b/include/linux/phy/phy-dp.h @@ -93,6 +93,34 @@ struct phy_configure_opts_dp { * */ u8 set_voltages : 1; + + /** + * @set_tunnel_rate: + * + * Flag indicating, whether or not to start or stop the pixel clock + * of a DisplayPort tunnel, for a PHY in USB4 mode whose own PLL + * clocks the DP IN adapters of its USB4 router. Used alone: the + * other set_* flags must be clear. + * + */ + u8 set_tunnel_rate : 1; + + /** + * @tunnel_dpin: + * + * DP IN adapter of the router whose pixel clock @set_tunnel_rate + * starts or stops, as the display controller numbers them. + */ + unsigned int tunnel_dpin; + + /** + * @tunnel_rate: + * + * DP link rate code (DPCD LINK_BW_SET: 0x06 RBR, 0x0a HBR, 0x14 HBR2, + * 0x1e HBR3) of the stream tunnelled through @tunnel_dpin, or 0 to + * stop its pixel clock. + */ + u8 tunnel_rate; }; #endif /* __PHY_DP_H_ */ From 99cc22fb1272a10e47d554d57e8194682e8d9db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Bal=C3=A1zsy?= Date: Mon, 16 Nov 2026 10:06:28 +0100 Subject: [PATCH 0938/1514] mux: apple-display-crossbar: enable the T604X ATC for a DP IN tunnel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On T6040/T6041 the crossbar's 0x34 is a per-clock UHBR select (bit n set when the link rate is UHBR) and the ATC enable of a DP IN output is at 0x38. The T6030 link wrote the ATC enable to 0x34, which set the UHBR select of an HBR2 stream and left the ATC disabled: the tunnel trained but no pixel data reached the DP IN. DP IN tunnels carry DP 1.x rates only, so clear the UHBR select and set the enable at 0x38; the DP alt mode output keeps the T6030 write. Resume checks the same register. [petr: split out of fbalazsy/linux 5e6657513 "drm/apple: T6041 display coprocessors across hibernation and S2R" (with its comment from ed490dd5f). On the J614s this took the Studio Display's video path from ~480 to ~976,000 packets/s at 1080p60, aurora-silicon/linux#1589.] Signed-off-by: František Balázsy Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- drivers/mux/apple-display-crossbar.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/drivers/mux/apple-display-crossbar.c b/drivers/mux/apple-display-crossbar.c index f45d296eebef4c..12e1f8a1cf7891 100644 --- a/drivers/mux/apple-display-crossbar.c +++ b/drivers/mux/apple-display-crossbar.c @@ -106,6 +106,8 @@ struct apple_dpxbar_hw { bool t6030_flow; /* no UNK_TUNABLE write at probe */ bool no_tunable; + /* DP IN tunnels enable the ATC at 0x38; 0x34 selects UHBR (T604X) */ + bool t604x_dpin_atc; /* power domain held only while an output is selected */ bool runtime_pm; /* T8142 layout: a connection status still busy after its poll is only logged */ @@ -236,6 +238,14 @@ static void t602x_dump(struct apple_dpxbar *xbar, const char *tag) #define T602X_DISPEXT_ENABLE 0x02c #define T602X_MUX_SELECT 0x030 #define T602X_ATC_ENABLE 0x034 +/* + * T604X, when a connection comes up: 0x34 holds a per-clock UHBR select + * (bit n set when the link rate is UHBR, cleared when it is not) and the ATC + * is enabled at 0x38 (its bit ORed in); neither is cleared at teardown. Used + * for DP IN tunnels only: the DP alt mode output keeps the T6030 write. + */ +#define T604X_ATC_UHBR_SELECT 0x034 +#define T604X_ATC_ENABLE 0x038 /* * Field of a T6030 output in the gate, select and enable registers. DP IN 0, @@ -285,7 +295,13 @@ static void apple_dpxbar_t6030_link(struct apple_dpxbar *xbar, dpxbar_set32(xbar, T602X_FIFO_WR_DPTX_CLK_EN, u); dpxbar_set32(xbar, rd, u); dpxbar_set32(xbar, out, d); - dpxbar_set32(xbar, T602X_ATC_ENABLE, d); + if (xbar->hw->t604x_dpin_atc && index != MUX_DPPHY) { + /* DP IN tunnels carry DP 1.x rates only: no UHBR select. */ + dpxbar_clear32(xbar, T604X_ATC_UHBR_SELECT, d); + dpxbar_set32(xbar, T604X_ATC_ENABLE, d); + } else { + dpxbar_set32(xbar, T602X_ATC_ENABLE, d); + } dpxbar_set32(xbar, T602X_DISPEXT_ENABLE, u); } else { dpxbar_clear32(xbar, T602X_DISPEXT_ENABLE, u); @@ -1380,6 +1396,9 @@ static int apple_dpxbar_resume(struct device *dev) u32 shift = apple_dpxbar_t6030_shift(i); u32 mask = (0xfU << shift) | (0xfU << (shift + 12)); u32 route = (state << shift) | (state << (shift + 12)); + /* Where apple_dpxbar_t6030_link() set the ATC enable of this output. */ + u32 atc_enable_reg = xbar->hw->t604x_dpin_atc && i != MUX_DPPHY ? + T604X_ATC_ENABLE : T602X_ATC_ENABLE; if (state < 0) continue; @@ -1388,7 +1407,7 @@ static int apple_dpxbar_resume(struct device *dev) restored |= BIT(i); } if (xbar->tunnel_link_up[i] && - (!(readl(xbar->regs + T602X_ATC_ENABLE) & BIT(shift)) || + (!(readl(xbar->regs + atc_enable_reg) & BIT(shift)) || !(readl(xbar->regs + T602X_DISPEXT_ENABLE) & BIT(state)))) { xbar->tunnel_link_up[i] = false; restored |= BIT(i); @@ -1445,6 +1464,7 @@ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6041 = { .ops = &apple_dpxbar_t602x_ops, .t6030_flow = true, .no_tunable = true, + .t604x_dpin_atc = true, }; /* From bebf4c342228acd6508378856f9f1df9267a18e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20=C5=A0kuta?= <20834920+petrskuta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:06:41 +0100 Subject: [PATCH 0939/1514] thunderbolt: apple: drive displays behind T6040/T6041 DP tunnels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Give the T6040 ACIO the M4 (T8132) DP IN policy and qualify T6040 and T6041 for DP tunnels. Their DP IN adapters take the t8103 handshake and the M3 flow, as on T8132; the pixel clock is the ATC PHY's AUSPLL, set through phy_configure(). Tested on the J614s (M4 Pro) with a Studio Display (2022) on the left Thunderbolt port: 1920x1080, 2560x1440 and 5120x2880 at 60 Hz, extended desktop, aurora-silicon/linux#1589. Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- drivers/thunderbolt/apple.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index e21cf99212ebae..4ec9fe4f824a55 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -245,7 +245,8 @@ static const struct apple_cio_hw apple_cio_t6040_hw = { .lstx_after_boot = true, .strict_fw_ready = true, .no_host_clx = true, - .dp = &apple_dpin_disabled, + /* The T8132 (M4) DP IN flow; the PHY's AUSPLL is the pixel clock. */ + .dp = &apple_dpin_m4, }; #define APPLE_CIO_NHI_HOP_COUNT 0x0 @@ -630,6 +631,9 @@ static const struct of_device_id apple_dpin_qualified_soc[] = { { .compatible = "apple,t6021" }, { .compatible = "apple,t6030" }, { .compatible = "apple,t8132" }, + /* T6040/T6041 (M4 Pro/Max): M4 DP IN flow, PHY tunnel pixel clock */ + { .compatible = "apple,t6040" }, + { .compatible = "apple,t6041" }, /* T6050: t8103 DP IN handshake, M3 flow, four DP IN adapters */ { .compatible = "apple,t6050" }, {}, From 3a4ef816e81f1e3d99dba1323fe1878a1872dc37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20=C5=A0kuta?= <20834920+petrskuta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:06:48 +0100 Subject: [PATCH 0940/1514] drm/apple: enable a T6041 tunnel's crossbar at its first link up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit dcp_tunnel_crossbar_up() routes the mux at the first DidChangeLinkConfiguration and enables the connection only for dcp_t602x_tunnel_route(), which never matches the T6041 crossbar on 26.6. Its clocks then stay off until a retrain runs the up path again. 1080p and 1440p got video only because the firmware retrained after the mode set; 5120x2880 keeps the trained link ("Forcing link status to true for synched-pipe config") and stayed dark with the crossbar's FIFO and pixel clocks off. Also enable the connection at the first link up for the T6041 crossbar. Tested on the J614s with a Studio Display (2022): 5120x2880@60, aurora-silicon/linux#1589. Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp-fabric.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index b4be5bc2da3919..148dd101094d02 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -2554,8 +2554,16 @@ int dcp_tunnel_crossbar_up(struct apple_dcp *dcp, u32 unit) ret = mux_control_try_select(route->active_xbar, route->mux_index); if (!ret) route->xbar_up = true; - /* T602X DP IN selection reserves and routes the mux only. */ - if (!ret && dcp_t602x_tunnel_route(route)) { + /* + * T602X DP IN selection reserves and routes the mux only, so the + * first link up also enables the connection. The T6041 crossbar + * (M4 Pro/Max) takes the same T6030 flow on every firmware: without + * this its clocks stay off until a retrain, and a mode set that + * keeps the trained link (5K on 26.6) never gets any video. + */ + if (!ret && (dcp_t602x_tunnel_route(route) || + of_device_is_compatible(route->active_xbar->chip->dev.parent->of_node, + "apple,t6041-display-crossbar"))) { ret = dcp_tunnel_xbar_configure(route); if (!ret) ret = dcp_dpxbar_link(route->active_xbar, true); From 0ebd96f1be0db7a0981c980e94cdaf49cd42de46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20=C5=A0kuta?= <20834920+petrskuta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:33:12 +0100 Subject: [PATCH 0941/1514] phy: apple: t6040: release both AUSPLL clock outputs when a tunnel stops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tunnel's AUSPLL start sets CLKOUT_MASTER 0x808 and refuses to start while either bit is set ('already in use'), but the stop cleared only 0x8. After the first stop, e.g. a DPMS off of a Studio Display, the tunnel clock could not start again: DP tunnel: AUSPLL already in use (master 0x81d54, cmd 0x10000018) DP tunnel pixel clock (rate 0x14) failed: -16 and the display stayed dark after DPMS on. Clear both outputs. Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- drivers/phy/apple/t6040-usb2.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 0a501ac9fe27e5..5a0546da5b78f6 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -2053,7 +2053,8 @@ static void t6040_tun_pll_stop(struct t6040_usb2_phy *tphy) dev_warn(tphy->dev, "DP tunnel: AUSPLL release timed out (cmd %#x, pclk status %#x)\n", readl(core + T6040_CORE_AUSPLL_CMD), readl(core + T6040_CORE_DP_PCLK_STATUS)); - t6040_usb2_clear32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x8); + /* Both outputs the start set: a stale 0x800 reads as "in use" next time. */ + t6040_usb2_clear32(core + T6040_CORE_AUSPLL_CLKOUT_MASTER, 0x808); tphy->tun_pll = false; } From b1b0204a3bae28f337526e73ca5483e2f6cfdd01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Bal=C3=A1zsy?= Date: Fri, 13 Nov 2026 15:48:18 +0100 Subject: [PATCH 0942/1514] tools: asahi: model the T6040 tunnel clock in the T6030 clock host test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The host test extracts dcp_route_clock_rate() from the display fabric and builds it on its own. The fabric now sets the tunnel clock through phy_configure() when the route's PHY is a T6040 ATC PHY, so the test needs those helpers and a model of the PHY operation. Extract dcp_phy_clocks_tunnel() and dcp_phy_tunnel_rate() with the other fabric functions, give the model PHY an OF node and stub phy_configure() with the DP tunnel options. Add a case that runs a T6040 ATC PHY on the T6040, T6041 and T6030 machines through DP IN 0 and 1: the rate reaches the PHY with set_tunnel_rate alone and the right adapter, neither the ATC nor the T6050 provider is called, and a clock that fails to start leaves the route's rate alone. [petr: reworked for phy_configure() and the PHY compatible.] Signed-off-by: František Balázsy Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- tools/asahi/t6030-clock-tests.py | 4 +- tools/asahi/t6030-clock/fixture.c | 67 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/tools/asahi/t6030-clock-tests.py b/tools/asahi/t6030-clock-tests.py index 1c26aee6b87182..9c8a326c582e2c 100644 --- a/tools/asahi/t6030-clock-tests.py +++ b/tools/asahi/t6030-clock-tests.py @@ -21,14 +21,14 @@ 'atc_t8122_tunnel_stop', 'atc_t8122_tunnel_pclk', 'atc_t8122_tunnel_start', 'apple_atc_dp_tunnel_rate_source'], 'drivers/gpu/drm/apple/dcp-fabric.c': [ - 'dcp_route_clock_rate', 'dcp_tunnel_set_rate'], + 'dcp_phy_clocks_tunnel', 'dcp_phy_tunnel_rate', 'dcp_route_clock_rate', 'dcp_tunnel_set_rate'], } CASES = ['dual-start', 'reverse-start', 'stop-second', 'same-rate', 'stale-owner', 'same-source', 'retune-one', 'busy-mode', 'busy-pll', 'invalid-source', 'invalid-rate', 'wrong-generation', 'failed-cleanup', 'failed-final-stop', 'stale-ack', 'unflagged-ack'] CASES += ['fail-start-' + str(i) for i in range(4)] -CASES += ['t6050-dpin-clocks'] +CASES += ['t6050-dpin-clocks', 't6040-tunnel-clock'] def function(source, name): match = re.search(r'^(?:static\s+)?(?:inline\s+)?(?:unsigned\s+)?(?:int|void|bool)\s+' + name + diff --git a/tools/asahi/t6030-clock/fixture.c b/tools/asahi/t6030-clock/fixture.c index 3efdc838fe8d18..832c412187e794 100644 --- a/tools/asahi/t6030-clock/fixture.c +++ b/tools/asahi/t6030-clock/fixture.c @@ -46,9 +46,28 @@ struct apple_atcphy { bool prepared, changed, restored; } cio_sleep; }; +struct device_node { + const char *compatible; +}; struct phy { const void *ops; struct apple_atcphy *data; + struct { + struct device_node *of_node; + } dev; +}; +static bool of_device_is_compatible(const struct device_node *np, const char *s) +{ + return np && !strcmp(np->compatible, s); +} +/* include/linux/phy/phy-dp.h: the DP tunnel options only. */ +struct phy_configure_opts_dp { + u8 set_rate : 1, set_lanes : 1, set_voltages : 1, set_tunnel_rate : 1; + unsigned int tunnel_dpin; + u8 tunnel_rate; +}; +union phy_configure_opts { + struct phy_configure_opts_dp dp; }; struct apple_dcp; struct apple_dcp_typec_route { @@ -138,6 +157,23 @@ static int apple_t6050_dp_tunnel_clock(struct phy *p, unsigned clock, u8 rate) t6050_rate = rate; return t6050_error; } +/* + * T6040 ATC PHY (t6040-usb2.c): one pixel clock per DP IN adapter (0 or 1), + * set through phy_configure() with set_tunnel_rate alone, recorded. + */ +static unsigned t6040_calls, t6040_dpin; +static u8 t6040_rate; +static int t6040_error; +static int phy_configure(struct phy *p, union phy_configure_opts *opts) +{ + assert(of_device_is_compatible(p->dev.of_node, "apple,t6040-atcphy")); + assert(opts->dp.set_tunnel_rate && !opts->dp.set_rate && + !opts->dp.set_lanes && !opts->dp.set_voltages); + t6040_calls++; + t6040_dpin = opts->dp.tunnel_dpin; + t6040_rate = opts->dp.tunnel_rate; + return t6040_error; +} /* * Production: of_device_is_compatible(dcp->dev->of_node, "apple,t8132-dcpext"). * These are T6030 DCPs: the T8132 dcpext paths must never be taken. @@ -275,6 +311,37 @@ int main(int argc, char **argv) printf("PASS %s: DP IN n on tunnel clock n + 1, rate kept only when set\n", name); return 0; } + if (!strcmp(name, "t6040-tunnel-clock")) { + /* + * The PHY's compatible picks the path, not the machine: a T6040 + * ATC PHY takes the rate through phy_configure() on T6040 and + * T6041 alike, and neither the ATC nor the T6050 provider is + * called. A T6030 machine with that PHY takes the same path. + */ + const char *const machines[] = { "apple,t6040", "apple,t6041", "apple,t6030" }; + struct device_node t6040_atcphy = { .compatible = "apple,t6040-atcphy" }; + u8 route_rate; + phy.dev.of_node = &t6040_atcphy; + for (unsigned m = 0; m < 3; m++) { + machine = machines[m]; + t6040_calls = 0; + t6040_error = 0; + for (unsigned dpin = 0; dpin < 2; dpin++) { + assert(!t6050_clock_call(&phy, dpin, 0x1e, &route_rate)); + assert(t6040_dpin == dpin && t6040_rate == 0x1e && route_rate == 0x1e); + assert(!t6050_clock_call(&phy, dpin, 0, &route_rate)); + assert(t6040_dpin == dpin && !t6040_rate && !route_rate); + } + assert(t6040_calls == 4); + /* A clock that failed to start leaves the route's rate alone. */ + t6040_error = -ETIMEDOUT; + assert(t6050_clock_call(&phy, 1, 0x14, &route_rate) == -ETIMEDOUT && + route_rate == 0x55); + } + assert(!t6050_calls && !writes && !polls && !crossbar_stops); + printf("PASS %s: T6040 ATC PHY tunnel clock through phy_configure\n", name); + return 0; + } if (!strcmp(name, "wrong-generation")) { hw.gen = ATCPHY_GENERATION_T8103; assert(clock_call(&phy, 0, 0, 0x14) == -EOPNOTSUPP && !writes); From 3b624534ee4c03cc727e9a132136ff9b01154fa1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 22:49:59 +1100 Subject: [PATCH 0943/1514] github: route reviews by area, add the readiness bot and the PR text check CODEOWNERS now requests a review from Core and Omarchy Mac on every path, so the one approval the main ruleset counts can come from either team. '# area:' sections group the paths: Omarchy Mac first for the M1 to M3 device trees and shared SoC drivers (area platform), Dj added for the GPU driver, and the existing Owner-only release files kept last so they still win. The readiness bot turns the same sections into area: labels. pr-readiness.yml calls the organisation's reusable workflow, which keeps one merge-readiness comment and the readiness labels on every open PR (aurora-silicon/.github docs/pr-readiness.md). pr-text.yml calls the organisation's PR text check: the Tested and Risk lines are present and no AI attribution appears in the PR text or the author's commits. The repository's own issue forms are removed so the organisation's bug, regression and bring-up forms apply here as everywhere else; the old ones pointed at the retired omacom/linux-aurora repository. Signed-off-by: Ryan Murray --- .github/CODEOWNERS | 96 +++++++++++++++++-- .github/ISSUE_TEMPLATE/aurora_bug.yml | 66 ------------- .github/ISSUE_TEMPLATE/aurora_test_report.yml | 57 ----------- .github/ISSUE_TEMPLATE/config.yml | 8 -- .github/workflows/pr-readiness.yml | 47 +++++++++ .github/workflows/pr-text.yml | 20 ++++ 6 files changed, 153 insertions(+), 141 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/aurora_bug.yml delete mode 100644 .github/ISSUE_TEMPLATE/aurora_test_report.yml delete mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/workflows/pr-readiness.yml create mode 100644 .github/workflows/pr-text.yml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b22b22407c1d50..3d4e3f46ca952e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,12 +1,88 @@ # Code owners for aurora-silicon/linux. # -# Only files whose change affects every user or the release process are -# listed. Changes to them need a review from an Owner; everything else -# follows the normal merge policy: -# https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md -# Roles: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/governance-and-roles.md - -/.github/ @RyanTheTide @DjDeveloperr -/arch/arm64/configs/aurora_defconfig @RyanTheTide @DjDeveloperr -/RELEASES.md @RyanTheTide @DjDeveloperr -/CONTRIBUTING.md @RyanTheTide @DjDeveloperr +# Every PR is reviewed by Core or Omarchy Mac; an approval from either team +# counts everywhere. The '# area:' sections only route: they add the area's +# specialists to the review request and give the readiness bot its area: +# labels. Omarchy Mac is listed first where it reviews first (M1 to M3 +# platform). Later lines win, as in every CODEOWNERS file, so keep the team +# pair on every area line. +# Routing and labels: https://github.com/aurora-silicon/agent-guidelines/blob/main/docs/MAINTAINER-HANDBOOK.md +# Merge rules: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md + +* @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: platform +/arch/arm64/boot/dts/apple/t8103* @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t600* @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8112* @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t602* @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8122* @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t603* @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/soc/apple/ @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/iommu/apple-dart.c @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/nvme/host/apple.c @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/spmi/ @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/watchdog/apple_wdt.c @aurora-silicon/omarchy-m @aurora-silicon/core +/drivers/gpio/gpio-macsmc.c @aurora-silicon/omarchy-m @aurora-silicon/core + +# area: bringup +/arch/arm64/boot/dts/apple/t8132* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t604* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t8140* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t8142* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t8152* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t6050* @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: gpu +/drivers/gpu/drm/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr +/include/uapi/drm/asahi_drm.h @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr +/tools/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr + +# area: display +/drivers/gpu/drm/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/gpu/drm/tiny/appletbdrm.c @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: audio +/sound/soc/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m +/sound/soc/codecs/tas2764* @aurora-silicon/core @aurora-silicon/omarchy-m +/sound/soc/codecs/tas2770* @aurora-silicon/core @aurora-silicon/omarchy-m +/sound/soc/codecs/cs42l83* @aurora-silicon/core @aurora-silicon/omarchy-m +/sound/soc/codecs/cs42l84* @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: power +/drivers/pmdomain/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/cpufreq/apple-soc-cpufreq.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/mfd/macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/power/supply/macsmc-power* @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/rtc/rtc-macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/hwmon/macsmc-hwmon.c @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: usb +/drivers/usb/typec/tipd/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/phy/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/thunderbolt/apple* @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: media +/drivers/media/platform/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/accel/ane/ @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: wireless +/drivers/net/wireless/broadcom/brcm80211/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/bluetooth/hci_bcm4377.c @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: input +/drivers/input/touchscreen/apple_z2.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/input/misc/macsmc-input.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/hid/hid-apple.c @aurora-silicon/core @aurora-silicon/omarchy-m + +# area: rust +/rust/ @aurora-silicon/core @aurora-silicon/omarchy-m + +# Files whose change affects every user or the release process: an Owner +# reviews them. Keep these last so they win. +# area: release +/.github/ @RyanTheTide @DjDeveloperr +/arch/arm64/configs/aurora_defconfig @RyanTheTide @DjDeveloperr +/RELEASES.md @RyanTheTide @DjDeveloperr +/CONTRIBUTING.md @RyanTheTide @DjDeveloperr +# end-area diff --git a/.github/ISSUE_TEMPLATE/aurora_bug.yml b/.github/ISSUE_TEMPLATE/aurora_bug.yml deleted file mode 100644 index 245aa165168064..00000000000000 --- a/.github/ISSUE_TEMPLATE/aurora_bug.yml +++ /dev/null @@ -1,66 +0,0 @@ -name: Aurora Linux bug -description: Report one reproducible problem with machine, build, and error details. -labels: [bug] -body: - - type: markdown - attributes: - value: | - Search existing issues first. Add evidence for a known bug there and link related issues or code examples. For broad testing, use the test-report form and keep one report per Mac. - See [reporting guidance](https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md) and the [roadmap #56](https://github.com/omacom/linux-aurora/issues/56). - Never attach serials, addresses, keys, fingerprints, calibration bytes, raw device trees, per-unit firmware images, or core dumps. Review logs for private data. - - type: textarea - id: environment - attributes: - label: Mac and installed build - description: Exact installed release tag, running kernel, bootloader/package versions, distribution, and any local changes. If boot fails, give what is available. - placeholder: | - Model / board / SoC: MacBook Pro M3 Pro / apple,j516s / apple,t6031 - Installed Aurora tag: - uname -r: - Bootloader and relevant package versions: - Distribution / local patches: - validations: - required: true - - type: textarea - id: firmware - attributes: - label: Both firmware versions and provisioning - description: Read both fields from /proc/device-tree/chosen/. Say unavailable if not accessible. For calibration problems, state provisioning status and whether data came from this Mac; do not upload it. - placeholder: | - asahi,os-fw-version: - asahi,system-fw-version: - Own-Mac provisioning status (if relevant): - validations: - required: true - - type: textarea - id: reproduction - attributes: - label: Reproduction, expected result, and actual result - description: Include the shortest steps, frequency, and last known-good / first bad build if known. For display failures, give dock/display, port, connection type, and mode. - validations: - required: true - - type: textarea - id: session - attributes: - label: Graphics or session details (if relevant) - description: Mesa version and active renderer, GPU profile/opt-in, compositor and lock-screen versions, and relevant app version. For resume, was it locked before authentication, and did the session/compositor restart? For a crash, give executable, signal, and timestamp. - - type: textarea - id: logs - attributes: - label: Relevant error lines - description: Quote literal errors with nearby context. Trim and redact logs; avoid whole journals, dmesg dumps, or core dumps. State if logs could not be collected. - render: text - validations: - required: true - - type: textarea - id: related - attributes: - label: Related issues, pull requests, or code examples - description: Link references and explain which behavior matches. Include any workaround already tried. - - type: textarea - id: untested - attributes: - label: What was not tested - description: For example, no dock available, only one port tested, or no suspend test. A build or module probe alone is not a runtime pass. - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/aurora_test_report.yml b/.github/ISSUE_TEMPLATE/aurora_test_report.yml deleted file mode 100644 index 8abd593f2bf2ad..00000000000000 --- a/.github/ISSUE_TEMPLATE/aurora_test_report.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Aurora Linux per-Mac test report -description: Record results for one Mac; append later tests to the same issue. -title: "[board] (Mac model): test results" -labels: [test-report] -body: - - type: markdown - attributes: - value: | - Keep one broad test-report issue per Mac and append later results as comments. Add detailed evidence for known bugs to their existing issues and link them here. - See [reporting guidance](https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md) and the [roadmap #56](https://github.com/omacom/linux-aurora/issues/56). - Never attach serials, addresses, keys, fingerprints, calibration bytes, raw device trees, per-unit firmware images, or core dumps. Review logs for private data. - - type: textarea - id: environment - attributes: - label: Mac and installed build - description: Model, board/SoC from /proc/device-tree/compatible, exact installed Aurora tag, uname -r, bootloader/package versions, distribution, and local changes. Say unavailable where necessary. - validations: - required: true - - type: textarea - id: firmware - attributes: - label: Both firmware versions and provisioning - description: Read both fields from /proc/device-tree/chosen/. Report own-Mac provisioning status if relevant, never calibration contents. - placeholder: | - asahi,os-fw-version: - asahi,system-fw-version: - Own-Mac provisioning status (if relevant): - validations: - required: true - - type: textarea - id: results - attributes: - label: Actions and results - description: List pass/fail/not tested per action. Distinguish Touch ID enrolment/verification/after reboot, display coldplug/hotplug and connection/port/mode, and actual Bluetooth/audio operation. A loaded driver or successful compile is not a pass. - placeholder: | - Feature / action | pass, fail, or not tested | details - For failures: steps, frequency, last known-good / first bad build, related bug link. - validations: - required: true - - type: textarea - id: session - attributes: - label: Graphics and session details - description: Mesa version and active renderer, GPU profile/opt-in, compositor/lock-screen versions, and relevant apps. If suspend was tested, was the session locked before authentication, and did it resume or restart? Give executable, signal, and timestamp for crashes. Say not tested or unavailable where appropriate. - - type: textarea - id: logs - attributes: - label: Relevant logs and related reports - description: Literal error lines with nearby context, or no errors observed. Trim and redact logs; avoid whole journals or dmesg dumps. Link canonical bugs, code examples, and earlier results. - render: text - - type: textarea - id: untested - attributes: - label: Untested features and limitations - description: Be explicit about unavailable peripherals, untested ports, firmware combinations, or suspend/crash checks. - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 03486756a029cf..00000000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,8 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: Reporting guide and existing per-Mac reports - url: https://github.com/omacom/linux-aurora/blob/integration/aurora/CONTRIBUTING.md - about: Check how to report results and append to an existing report for your Mac. - - name: Aurora Linux bug-fix roadmap - url: https://github.com/omacom/linux-aurora/issues/56 - about: Find priorities and canonical issue links before opening a duplicate. diff --git a/.github/workflows/pr-readiness.yml b/.github/workflows/pr-readiness.yml new file mode 100644 index 00000000000000..ab56cb82792d66 --- /dev/null +++ b/.github/workflows/pr-readiness.yml @@ -0,0 +1,47 @@ +name: pr-readiness + +# Merge-readiness comment and labels on every open pull request. +# The logic lives in aurora-silicon/.github; this file only says when to run. +# Rules: https://github.com/aurora-silicon/agent-guidelines/blob/main/docs/MAINTAINER-HANDBOOK.md + +on: + pull_request_target: + types: [opened, reopened, synchronize, edited, ready_for_review, labeled, unlabeled] + pull_request_review: + types: [submitted, dismissed] + issue_comment: + types: [created, edited] + schedule: + - cron: "7,37 * * * *" + workflow_dispatch: + inputs: + pr: + description: Pull request number (empty = every open pull request) + required: false + +permissions: + contents: read + pull-requests: write + issues: write + checks: read + statuses: read + +concurrency: + # Comments get their own group without cancelling, so a stream of + # comments (or a bot's) never cancels a push or review run. + group: pr-readiness-${{ github.event_name == 'issue_comment' && format('comment-{0}', github.event.comment.id) || github.event.pull_request.number || inputs.pr || 'sweep' }} + cancel-in-progress: ${{ github.event.pull_request.number != null }} + +jobs: + readiness: + # Reviews on pull requests from forks get a read-only token, and the + # bot's own comments do not matter; the sweep picks those up. + if: >- + github.repository_owner == 'aurora-silicon' && + (github.event_name != 'pull_request_review' || + github.event.pull_request.head.repo.full_name == github.repository) && + (github.event_name != 'issue_comment' || + (github.event.issue.pull_request && github.event.comment.user.type != 'Bot')) + uses: aurora-silicon/.github/.github/workflows/pr-readiness.yml@main + with: + pr: ${{ format('{0}', github.event.pull_request.number || github.event.issue.number || inputs.pr || '') }} diff --git a/.github/workflows/pr-text.yml b/.github/workflows/pr-text.yml new file mode 100644 index 00000000000000..83c942d878045e --- /dev/null +++ b/.github/workflows/pr-text.yml @@ -0,0 +1,20 @@ +name: pr-text + +# 'Tested:' and 'Risk:' lines present, no AI attribution in the PR text. +# Guide: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/pr-structure.md + +on: + pull_request: + types: [opened, edited, synchronize, reopened, ready_for_review, converted_to_draft] + +permissions: + contents: read + pull-requests: read + +concurrency: + group: pr-text-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + pr-text: + uses: aurora-silicon/.github/.github/workflows/pr-text.yml@main From 30cebe9aeb973b37f71b5b33deae5e370ff4bbc8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 23:11:28 +1100 Subject: [PATCH 0944/1514] drm/asahi: harden M3 Extended recovery quarantine, trailing events, layout bounds, and MMIO ordering Address all review findings on M3 Extended per-client GPU fault recovery: - Pin quarantined VmJobGuards against subsequent Packet::release_guard() calls once a terminal fault (fail_vm == true) quarantines a packet, and reserve quarantined_packets capacity before draining active batches, preventing Inner::fail_front() or Runtime::withdraw() from unmapping a quarantined VM's pages. - Propagate config.drain() errors in recover_extended(), clear and filter trailing EVENT 0/4 notifications belonging to the already-answered recovery generation (phase == 0 && gen == last_recovery_gen), and fail boot_extended() / retire_extended_control() immediately if take_recovery_trigger() reports a firmware fault. - Bind RecoveryOffsets::valid_for() to the exact expected CONTROL_REGION byte size alongside the layout shift so shifted layouts fail closed, and apply control_shift() in Config::log_recovery_state(). - Defer log_extended_fault_banks() until firmware reaches recovery phase 1 (engines stopped), always restore SGX+0xd800 on error paths, and honor the SoC retire_mmio busy mask so post-phase-0 drain and fault-bank logging never touch clock-gated 0xc020/0xc120 registers on single-cluster G15G. - Tighten pool+0x54 upper bounds in render/compute completion, narrow lagging-DONE allowance to the fragment stage, use mixed.renders for TPC clear, handle phase-1 recovery on pipelined active expiry, clear standalone m3_recovery test warnings, and add packet-guard pin tests. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_compute.rs | 4 +- drivers/gpu/drm/asahi/m3/m3_config.rs | 17 ++++-- drivers/gpu/drm/asahi/m3/m3_device.rs | 64 +++++++++++++---------- drivers/gpu/drm/asahi/m3/m3_init_26.rs | 13 +++-- drivers/gpu/drm/asahi/m3/m3_recovery.rs | 23 ++++++-- drivers/gpu/drm/asahi/m3/m3_render.rs | 11 ++-- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 46 ++++++++++++---- drivers/gpu/drm/asahi/m3/m3_submit.rs | 35 +++++++++++-- tools/asahi/m3-packet-completion-tests.py | 27 +++++++++- 9 files changed, 178 insertions(+), 62 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_compute.rs b/drivers/gpu/drm/asahi/m3/m3_compute.rs index b091459349a87d..10dd602d0d500e 100644 --- a/drivers/gpu/drm/asahi/m3/m3_compute.rs +++ b/drivers/gpu/drm/asahi/m3/m3_compute.rs @@ -451,10 +451,10 @@ impl Compute { if self.profile == super::m3_profile::Profile::Extended { let actual = self.objects[storage::POOL].read_u64(0x54)?; let expected = self.sequence.saturating_sub(self.pool_delta); - if actual < expected { + if actual < expected || actual > self.sequence { return Ok(false); } - if actual > expected && actual <= self.sequence { + if actual > expected { self.pool_delta = self.sequence - actual; } } diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index 860ac6ccd83a8e..0d1d668d91ddd5 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -375,8 +375,13 @@ impl Config { /// Nothing is acknowledged, cleared or resumed here. pub(crate) fn log_recovery_state(&mut self, dev: &driver::AsahiDrmDevice, events: u64) -> Result { if self.profile == super::m3_profile::Profile::Extended { + let control_start = 0x4ebc + super::m3_init_26::control_shift(); + let control_size = self.objects[CONTROL_REGION].size(); for (owner, start, length) in [(super::m3_init_26::RECOVERY_ACTIVITY, 0, 0x60), - (CONTROL_REGION, 0x4ebc, 0x100)] { + (CONTROL_REGION, control_start, 0x100)] { + if owner == CONTROL_REGION && start.saturating_add(length) > control_size { + continue; + } for offset in (start..start + length).step_by(32) { let mut bytes = [0; 32]; self.objects[owner].read(offset, &mut bytes)?; @@ -573,6 +578,7 @@ impl Config { } let offsets = super::m3_recovery::RecoveryOffsets::extended( super::m3_init_26::control_shift(), + super::m3_init_26::control_region_bytes(), ); offsets .valid_for(self.objects[CONTROL_REGION].size()) @@ -617,8 +623,8 @@ impl Config { } /// Returns a recovery trigger error if the firmware reported a fault/timeout - /// or entered recovery phase != 0, ignoring trailing `STATS 0x16` from the - /// already-completed recovery generation. + /// or entered recovery phase != 0, ignoring trailing `EVENT 0`/`4` or + /// `STATS 0x16` notifications from the already-completed recovery generation. pub(crate) fn take_recovery_trigger(&mut self) -> Result> { if self.recovery_offsets().is_none() { return Ok(None); @@ -626,7 +632,10 @@ impl Config { let phase = self.recovery_phase()?; if let Some((kind, _word3)) = self.pending_recovery_event.take() { self.pending_recovery_stats = false; - return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + let gen = self.recovery_generation()?; + if !super::m3_recovery::is_trailing_stats(phase, gen, self.last_recovery_gen) { + return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + } } if core::mem::take(&mut self.pending_recovery_stats) { let gen = self.recovery_generation()?; diff --git a/drivers/gpu/drm/asahi/m3/m3_device.rs b/drivers/gpu/drm/asahi/m3/m3_device.rs index 9c7159f6d83d2a..ec0eec77aaa4ab 100644 --- a/drivers/gpu/drm/asahi/m3/m3_device.rs +++ b/drivers/gpu/drm/asahi/m3/m3_device.rs @@ -175,7 +175,8 @@ impl Device { /// Read-only MMU fault bank & engine busy snapshot for Extended (26.x/27.2) /// profiles. Returns `Ok(true)` if any cluster fault bank has its valid bit set. - /// Does not acknowledge or clear hardware fault banks. + /// Does not acknowledge or clear hardware fault banks, and always restores + /// the bank selector register (`0xd800`) on exit. pub(crate) fn log_extended_fault_banks(&self, vm: &crate::mmu::Vm) -> Result { let sgx_guard = self.sgx.try_access().ok_or(ENODEV)?; let sgx = sgx_guard.as_view(); @@ -188,38 +189,47 @@ impl Device { ); return Ok(false); } - let c020 = sgx.try_read64(0xc020)?; - let c120 = sgx.try_read64(0xc120)?; + let check_busy = crate::m3::m3_params::retire_mmio(self.soc) + & crate::m3::m3_params::RETIRE_MMIO_BUSY + != 0; + let (c020, c120) = if check_busy { + (sgx.try_read64(0xc020)?, sgx.try_read64(0xc120)?) + } else { + (0, 0) + }; let selector = sgx.try_read64(0xd800)?; - let mut any_fault = false; - for bank in 0..u64::from(self.soc.clusters) { - sgx.try_write64(bank, 0xd800)?; - let address = sgx.try_read64(0xd8c8)?; - let fault = sgx.try_read64(0xd8c0)?; - dev_info!( - self.dev.as_ref(), - "M3 {}: pstate={} busy={:#x}/{:#x} bank {} fault={:#x} address={:#x}\n", - self.soc.gpu_name, - pstate, - c020, - c120, - bank, - fault, - address << 6 - ); - if fault & 1 != 0 { - any_fault = true; + let result = (|| -> Result { + let mut any_fault = false; + for bank in 0..u64::from(self.soc.clusters) { + sgx.try_write64(bank, 0xd800)?; + let address = sgx.try_read64(0xd8c8)?; + let fault = sgx.try_read64(0xd8c0)?; dev_info!( self.dev.as_ref(), - "M3 fault mapping bank={} address={:#x} translation={:?}\n", + "M3 {}: pstate={} busy={:#x}/{:#x} bank {} fault={:#x} address={:#x}\n", + self.soc.gpu_name, + pstate, + c020, + c120, bank, - address << 6, - vm.translate_iova(address << 6) + fault, + address << 6 ); + if fault & 1 != 0 { + any_fault = true; + dev_info!( + self.dev.as_ref(), + "M3 fault mapping bank={} address={:#x} translation={:?}\n", + bank, + address << 6, + vm.translate_iova(address << 6) + ); + } } - } - sgx.try_write64(selector, 0xd800)?; - Ok(any_fault) + Ok(any_fault) + })(); + let _ = sgx.try_write64(selector, 0xd800); + result } /// Read-only snapshot. Do not select or acknowledge fault banks here; diff --git a/drivers/gpu/drm/asahi/m3/m3_init_26.rs b/drivers/gpu/drm/asahi/m3/m3_init_26.rs index 86305bfb182cbf..a4ce845e4a6a4f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_init_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_init_26.rs @@ -19,9 +19,16 @@ pub(crate) const LOG_THREADS: usize = 9; pub(crate) const RX_BYTES: usize = 0x48; pub(crate) const LOG_PAYLOAD_BYTES: usize = 0xd8; -/// Control-region offset shift for recovery/flush fields on this extended layout. +/// Control-region byte size and offset shift for recovery/flush fields on this extended layout. +pub(crate) const CONTROL_REGION_BYTES: usize = 0xeaf0; +pub(crate) const CONTROL_SHIFT: usize = 0; + pub(crate) const fn control_shift() -> usize { - 0 + CONTROL_SHIFT +} + +pub(crate) const fn control_region_bytes() -> usize { + CONTROL_REGION_BYTES } /// The shared cache-flush ring has separate index and entry addresses on the wire. @@ -61,7 +68,7 @@ pub(crate) fn allocation(index: usize) -> Result { 44 => 0xe10, 45 => 0xe48, 46 => 0x670, - 47 => 0xeaf0, + 47 => CONTROL_REGION_BYTES, 48 => 0x20, DYNAMIC_STATE | RETENTION_STATE | GLOBAL_POOL | GLOBAL_PARAMETERS => 0x4000, PERFORMANCE_CONTROL => 0x6578, diff --git a/drivers/gpu/drm/asahi/m3/m3_recovery.rs b/drivers/gpu/drm/asahi/m3/m3_recovery.rs index 7d00de4253f3a1..a2fa6d1daa6369 100644 --- a/drivers/gpu/drm/asahi/m3/m3_recovery.rs +++ b/drivers/gpu/drm/asahi/m3/m3_recovery.rs @@ -27,29 +27,35 @@ pub(crate) const RECOVERY_DRAIN_MS: i64 = 1000; pub(crate) const RECOVERY_BUDGET_MS: i64 = 5000; /// Recovery control-object offsets derived from the `m3_init_26` layout shift -/// rather than hardcoded size checks. +/// and validated against the exact expected `CONTROL_REGION` byte size. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct RecoveryOffsets { pub(crate) snapshot: usize, pub(crate) snapshot_entries: usize, pub(crate) generation: usize, pub(crate) phase: usize, + pub(crate) control_bytes: usize, } impl RecoveryOffsets { /// Extended control region offsets shifted by the profile's `m3_init_26` /// control-table delta (`0` on 26.6.2 / `0xeaf0`, `0x1e0` on 27.2 / `0xedd0`). - pub(crate) const fn extended(shift: usize) -> Self { + pub(crate) const fn extended(shift: usize, control_bytes: usize) -> Self { Self { snapshot: logic::SNAPSHOT + shift, snapshot_entries: logic::SNAPSHOT_ENTRIES, generation: logic::GENERATION + shift, phase: logic::PHASE + shift, + control_bytes, } } - /// Verify every recovery word and snapshot entry fits inside `control_bytes`. + /// Verify `control_bytes` matches the expected layout size and every recovery + /// word and snapshot entry fits inside it (failing closed on mismatched layouts). pub(crate) const fn valid_for(self, control_bytes: usize) -> bool { + if control_bytes != self.control_bytes { + return false; + } let Some(snap_bytes) = self.snapshot_entries.checked_mul(8) else { return false; }; @@ -128,18 +134,25 @@ mod tests { #[test] fn extended_offsets_match_shared_g16_and_272_layouts() { - let base = RecoveryOffsets::extended(0); + assert!(FURTHER_RECOVERIES > 0); + assert!(RECOVERY_DRAIN_MS > 0); + assert!(RECOVERY_BUDGET_MS >= RECOVERY_DRAIN_MS); + + let base = RecoveryOffsets::extended(0, 0xeaf0); assert_eq!(base.snapshot, 0x40b8); assert_eq!(base.generation, 0x4fa0); assert_eq!(base.phase, 0x4fb0); assert!(base.valid_for(0xeaf0)); assert!(!base.valid_for(0x4fb0)); + // Must fail closed if CONTROL_REGION grows to 27.2 without updating the shift. + assert!(!base.valid_for(0xedd0)); - let v272 = RecoveryOffsets::extended(0x1e0); + let v272 = RecoveryOffsets::extended(0x1e0, 0xedd0); assert_eq!(v272.snapshot, 0x4298); assert_eq!(v272.generation, 0x5180); assert_eq!(v272.phase, 0x5190); assert!(v272.valid_for(0xedd0)); + assert!(!v272.valid_for(0xeaf0)); assert!(!v272.valid_for(0x5190)); } diff --git a/drivers/gpu/drm/asahi/m3/m3_render.rs b/drivers/gpu/drm/asahi/m3/m3_render.rs index c06b5335d823b7..5ce53ec48c4303 100644 --- a/drivers/gpu/drm/asahi/m3/m3_render.rs +++ b/drivers/gpu/drm/asahi/m3/m3_render.rs @@ -792,18 +792,19 @@ impl Render { } pub(crate) fn complete(&mut self)->Result { let recovered = self.recovery_aborted_draw == Some(self.draw); - for (stamp,fw,pointers,value,head) in [(s::TA_STAMP,s::TA_FW_STAMP,s::TA_POINTERS,self.stamp_epoch.value(s::STAMP_TA - 256,self.draw),self.heads[0]), - (s::FRAGMENT_STAMP,s::FRAGMENT_FW_STAMP,s::FRAGMENT_POINTERS,self.stamp_epoch.value(s::STAMP_FRAGMENT - 256,self.draw),self.heads[1])] { + for (stage,stamp,fw,pointers,value,head) in [(0usize,s::TA_STAMP,s::TA_FW_STAMP,s::TA_POINTERS,self.stamp_epoch.value(s::STAMP_TA - 256,self.draw),self.heads[0]), + (1usize,s::FRAGMENT_STAMP,s::FRAGMENT_FW_STAMP,s::FRAGMENT_POINTERS,self.stamp_epoch.value(s::STAMP_FRAGMENT - 256,self.draw),self.heads[1])] { + let allow_lagging_done = recovered && stage == 1; if self.objects[stamp].read_u32(0)?!=value || self.objects[fw].read_u32(0)?!=value - || (!recovered && self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head)) + || (!allow_lagging_done && self.objects[pointers].read_u32(queue::DONE)?!=u32::from(head)) || self.objects[pointers].read_u32(queue::READ)?!=u32::from(head) {return Ok(false);} } if self.profile==super::m3_profile::Profile::Extended && self.draw!=0 { for (idx, pool) in UMA_POOLS.iter().enumerate() { let actual = self.objects[pool.manager].read_u64(0x54)?; let expected = self.draw.saturating_sub(self.pool_delta[idx]); - if actual < expected {return Ok(false);} - if actual > expected && actual <= self.draw { + if actual < expected || actual > self.draw {return Ok(false);} + if actual > expected { self.pool_delta[idx] = self.draw - actual; } } diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 2800f824779705..437d779436ea7b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -245,8 +245,7 @@ impl Inner { } self.log_owners(trigger); let vm = self.active[0].entries[0].0.vm.clone(); - let mmu_fault = self.device.log_extended_fault_banks(&vm).unwrap_or(false); - let blame_err = if mmu_fault { EIO } else { trigger }; + let mut blame_err = trigger; let overall = Instant::::now(); let mut rounds = 0u32; let mut prev_gen: Option = None; @@ -269,7 +268,7 @@ impl Inner { dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 1 did not arrive\n"); return Err(ETIMEDOUT); } - let _ = self.config.drain(&self.drm); + self.config.drain(&self.drm)?; fsleep(Delta::from_millis(1)); } _ => { @@ -284,6 +283,14 @@ impl Inner { return Err(EPROTO); } prev_gen = Some(generation); + // Read MMU fault banks only once firmware has reached phase 1 (engines stopped + // and firmware waiting for host phase 2) so SGX+0xd800 cannot race with firmware. + if !blamed { + let mmu_fault = self.device.log_extended_fault_banks(&vm).unwrap_or(false); + if mmu_fault { + blame_err = EIO; + } + } let mut entries = 0usize; let mut clear_tpc = false; for idx in 0..offsets.snapshot_entries { @@ -310,7 +317,8 @@ impl Inner { if clear_tpc { for batch in self.active.iter() { if let NativeJob::Render(j) = &mut self.jobs[batch.index] { - j.clear_active_tpc(batch.base, batch.entries.len())?; + let renders = batch.mixed.as_ref().map_or(batch.entries.len(), |m| m.renders); + j.clear_active_tpc(batch.base, renders)?; } } } @@ -346,7 +354,7 @@ impl Inner { dev_err!(self.drm.as_ref(), "M3 GPU recovery phase 3 timed out (gen {})\n", generation); return Err(ETIMEDOUT); } - let _ = self.config.drain(&self.drm); + self.config.drain(&self.drm)?; fsleep(Delta::from_millis(1)); } _ => { @@ -365,15 +373,23 @@ impl Inner { entries, clear_tpc ); + let check_busy = crate::m3::m3_params::retire_mmio(self.device.soc()) + & crate::m3::m3_params::RETIRE_MMIO_BUSY + != 0; let drain_start = Instant::::now(); let mut another_round = false; loop { - let _ = self.config.drain(&self.drm); + self.config.drain(&self.drm)?; let pipes_idle = self.config.pipes_idle()?; + let phase = self.config.recovery_phase()?; let mut all_drained = pipes_idle; if all_drained { - let engines_idle = (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 - || self.device.check_idle_parts(true, false).is_ok(); + // Honor the SoC's retire_mmio mask: do not probe core-clock-gated busy + // registers (0xc020/0xc120) when RETIRE_MMIO_BUSY is omitted (e.g. G15G). + let engines_idle = phase == 0 + && (!check_busy + || (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 + || self.device.check_idle_parts(true, false).is_ok()); for batch in self.active.iter() { let batch_drained = match &mut self.jobs[batch.index] { NativeJob::Render(j) => { @@ -395,12 +411,12 @@ impl Inner { } } if all_drained { + self.config.note_recovered(generation); break; } if self.state.health.crashed() { return Err(EIO); } - let phase = self.config.recovery_phase()?; match logic::action(phase, false, true) { RecoveryAction::Wait => {} RecoveryAction::MarkAndAcknowledge => { @@ -434,7 +450,9 @@ impl Inner { self.jobs[mixed.compute_index].finish_recovery(&self.drm)?; } } - // Fail and quarantine all packets from the stopped batch(es). + // Reserve capacity before draining active batches; fail and pin every stopped packet. + let active_packets: usize = self.active.iter().map(|b| b.entries.len()).sum(); + let _ = self.quarantined_packets.reserve(active_packets, GFP_KERNEL); self.quarantine_budget.charge(flights); for batch in self.active.drain_all() { for (packet, _) in batch.entries { @@ -1015,6 +1033,12 @@ impl Inner { let (expired,previous)=self.active.first().map(|b|(b.start.elapsed()>=Delta::from_secs(2),b.previous_events)).ok_or(EIO)?; if expired { dev_err!(self.drm.as_ref(),"M3 pipelined completion events={} previous={}\n",self.config.completed_events,previous); + if self.config.recovery_phase() == Ok(1) { + if let Err(e) = self.recover_extended(ETIMEDOUT) { + self.fail_active(e);return Err(e); + } + return Ok(true); + } self.fail_active(ETIMEDOUT);return Err(ETIMEDOUT); } return Ok(false); @@ -1586,6 +1610,7 @@ impl Runtime { while !self.inner.config.ready()? { let inner: &mut Inner = &mut *self.inner; inner.config.drain(&inner.drm)?; + if let Some(error) = inner.config.take_recovery_trigger()? { return Err(error); } if !inner.state.healthy() { return Err(EIO); } if deadline.elapsed() >= Delta::from_secs(2) { return Err(ETIMEDOUT); } fsleep(Delta::from_millis(1)); @@ -1618,6 +1643,7 @@ impl Runtime { loop { let inner: &mut Inner = &mut *self.inner; inner.config.drain(&inner.drm)?; + if let Some(error) = inner.config.take_recovery_trigger()? { return Err(error); } if !inner.state.healthy() { return Err(EIO); } if inner.config.control_done(expected)? { return Ok(()); } if deadline.elapsed() >= Delta::from_secs(2) { return Err(ETIMEDOUT); } diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 69316c8f83e82c..5ba1f368798765 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -48,6 +48,10 @@ pub(crate) struct Packet { pub(crate) render_attachments:KVec<[crate::m3::agx_attachments::Attachments;2]>, completion:UserFence, finish_state: AtomicU8, + /// Set once a terminal fault (`fail_vm == true`) quarantines `vm_job`; + /// thereafter `release_guard()` is a no-op so neither `fail_front()` nor + /// `withdraw()` can unmap a quarantined VM's pages. + guard_pinned: AtomicBool, /// Set before a batch with any of this packet's commands can change firmware-visible state, /// and never cleared. published: AtomicBool, @@ -109,7 +113,14 @@ impl Packet { self.timestamps[index][stage*2+i].as_ref().map_or(0,Destination::firmware_address))) } /// Called only after all published commands retired or before any publication. - pub(crate) fn release_guard(&self) {drop(self.vm_job.lock().take());} + /// Never drops a guard that was pinned by a terminal fault quarantine. + pub(crate) fn release_guard(&self) { + let mut guard_slot = self.vm_job.lock(); + if self.guard_pinned.load(Ordering::Acquire) { + return; + } + drop(guard_slot.take()); + } /// Called before the first firmware-visible change of a batch that includes this packet. pub(crate) fn mark_published(&self) {self.published.store(true,Ordering::Relaxed);} /// Whether the firmware may have seen any of this packet's commands. @@ -150,6 +161,12 @@ impl Packet { Err(e) if fail_vm => match self.finish_state.swap(TERMINAL, Ordering::AcqRel) { PENDING => {} PACKET_FAILED => { + let guard_slot = self.vm_job.lock(); + if let Some(guard) = guard_slot.as_ref() { + self.guard_pinned.store(true, Ordering::Release); + guard.quarantine(); + } + drop(guard_slot); record_vm(e); return; } @@ -168,9 +185,17 @@ impl Packet { if let Err(e)=result { // A guard still held here belongs to work the firmware may still run: block // mapping changes before the error fence is visible (as G15 does), so userspace - // can't unmap memory under it. It stays with the packet until the runtime drops - // the packet, after the firmware has provably stopped. - if let Some(guard)=self.vm_job.lock().as_ref() {guard.quarantine();} + // can't unmap memory under it. Terminal faults (`fail_vm`) also pin the guard + // against later `release_guard()` calls so it stays with the packet until the + // runtime drops it after the firmware has provably stopped. + let guard_slot = self.vm_job.lock(); + if let Some(guard) = guard_slot.as_ref() { + if fail_vm { + self.guard_pinned.store(true, Ordering::Release); + } + guard.quarantine(); + } + drop(guard_slot); record_vm(e); self.completion.set_error(e); } @@ -392,7 +417,7 @@ impl queue::Queue for Queue { #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] render_queue: self.render_queue.clone(),vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), - finish_state:AtomicU8::new(0),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), + finish_state:AtomicU8::new(0),guard_pinned:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; let mut job=self.entity.new_job(1,Job{shared:self.shared.clone(),packet})?; for sync in syncs.drain(0..in_sync_count) {if let Some(f)=sync.fence {job.add_dependency(f)?;}} diff --git a/tools/asahi/m3-packet-completion-tests.py b/tools/asahi/m3-packet-completion-tests.py index 45b786ed2e8c95..1b58bba7f1d7d6 100644 --- a/tools/asahi/m3-packet-completion-tests.py +++ b/tools/asahi/m3-packet-completion-tests.py @@ -19,7 +19,7 @@ def method(source, signature): MOCKS = r""" use std::cell::Cell; -use std::sync::{Mutex, atomic::{AtomicU8, Ordering}}; +use std::sync::{Mutex, atomic::{AtomicBool, AtomicU8, Ordering}}; #[derive(Clone, Copy, PartialEq, Eq)] struct Error(i32); impl Error { @@ -74,6 +74,7 @@ def method(source, signature): vm: &'a Vm, vm_job: JobGuard, finish_state: AtomicU8, + guard_pinned: AtomicBool, completion: Fence, commands: [(); 1], } @@ -97,6 +98,7 @@ def method(source, signature): vm, vm_job: JobGuard(Mutex::new(guard.then(Guard::default))), finish_state: AtomicU8::new(0), + guard_pinned: AtomicBool::new(false), completion: Fence::default(), commands: [()], } @@ -181,6 +183,29 @@ def method(source, signature): assert_eq!(packet.completion.signals.get(), 1); } } + +#[test] +fn terminal_fault_pins_guard_against_release_guard() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.finish(Err(EIO)); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); + // Subsequent fail_front() / withdraw() calls must not release a quarantined guard. + packet.release_guard(); + assert!(packet.vm_job.lock().is_some()); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); +} + +#[test] +fn cancel_then_terminal_fault_pins_guard_against_release_guard() { + let vm = Vm::default(); + let packet = Packet::new(&vm, true); + packet.fail_packet(ECANCELED); + packet.finish(Err(EIO)); + packet.release_guard(); + assert!(packet.vm_job.lock().is_some()); + assert!(packet.vm_job.lock().as_ref().unwrap().0.get()); +} """ From 7b0416bd0edb7e0bf2018ef84e2797cd22b2e513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20=C5=A0kuta?= <20834920+petrskuta@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:18:15 +0100 Subject: [PATCH 0945/1514] drm/apple: dptx: no PHY lane check for a DP tunnel on any SoC MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SET_ACTIVE_LANE_COUNT compares the requested lane count with the PHY's. A DP tunnel has no PHY lanes: its lane count is the tunnel's, and the PHY's holds the previous active one. The check already skipped tunnels on a T8132 dcpext; on other SoCs every tunnel link up logged set_active_lane_count: unexpected lane count:4 phy: 0 at error level, as on the J614s (T6040) with a Studio Display at every hotplug and resume. Skip the check for any tunnel output (dcp_is_usb4_output()), which is a property of the route rather than of the SoC. Only the message changes: the lane count was accepted either way. Signed-off-by: Petr Škuta <20834920+petrskuta@users.noreply.github.com> --- drivers/gpu/drm/apple/dptxep.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index c6b773573ad499..01d5f67c18b2b2 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -482,11 +482,11 @@ static int dptxport_call_set_active_lane_count(struct apple_epic_service *servic ret = dptx_j700_validate_lanes(dptx, lane_count); if (ret) return ret; - } else if (dptx->lane_count < lane_count && - !(dcp_is_t8132_ext(dcp) && dcp_is_usb4_output(dcp))) { + } else if (dptx->lane_count < lane_count && !dcp_is_usb4_output(dcp)) { /* - * A T8132 tunnel has no PHY lanes to check: its lane count - * is the tunnel's, and lane_count holds the previous active one. + * A DP tunnel has no PHY lanes to check, on any SoC: its lane + * count is the tunnel's, and lane_count holds the previous + * active one. */ dev_err(dcp->dev, "set_active_lane_count: unexpected lane " "count:%llu phy: %d\n", lane_count, dptx->lane_count); From c74e0da2d95bb0cbd051ab34588d7afce56ddd54 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 23:28:03 +1100 Subject: [PATCH 0946/1514] drm/asahi: gate M3 discarded-FS drain on tiler-only stop and fail closed without recovery offsets Address both remaining review items on M3 Extended per-client recovery: - Gate the discarded-fragment drain fallback (fragment_read_only_pending) on a snapshot-proven tiler-only stop (stopped_tiler seen, no non-tiler or fragment entry) where TA was still pending before phase 0, so a pure-fragment or TA+FS stop never short-circuits post-phase-0 drain. Also set recovery_aborted_draw in finish_recovery() only when fragment_read_only_pending() actually holds. - Fail closed (return Err(EIO) in drain_extended(), and report any pending event/stats trigger before returning Ok(None) in take_recovery_trigger()) whenever recovery_offsets() is None on a mismatched CONTROL_REGION layout. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_config.rs | 13 +++++++++++++ drivers/gpu/drm/asahi/m3/m3_recovery.rs | 14 ++++++++++++++ drivers/gpu/drm/asahi/m3/m3_render.rs | 10 +++++++++- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 21 ++++++++++++++++++++- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index 0d1d668d91ddd5..cda051e17b203f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -551,6 +551,9 @@ impl Config { } else if kind == 0 || kind == 4 { let word3 = u32::from_le_bytes(record[12..16].try_into().map_err(|_| EIO)?); dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); + if self.recovery_offsets().is_none() { + return Err(EIO); + } self.pending_recovery_event.get_or_insert((kind, word3)); } else { dev_err!(dev.as_ref(), "M3 firmware event {}: {:02x?}\n", kind, record); @@ -558,6 +561,9 @@ impl Config { } } else if channel == storage::STATS && kind == 0x16 { dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); + if self.recovery_offsets().is_none() { + return Err(EIO); + } self.pending_recovery_stats = true; } else if channel == storage::TRACE && kind != 5 { dev_err!(dev.as_ref(), "M3 firmware channel {} record {}: {:02x?}\n", channel, kind, record); @@ -627,6 +633,13 @@ impl Config { /// `STATS 0x16` notifications from the already-completed recovery generation. pub(crate) fn take_recovery_trigger(&mut self) -> Result> { if self.recovery_offsets().is_none() { + if let Some((kind, _word3)) = self.pending_recovery_event.take() { + self.pending_recovery_stats = false; + return Ok(Some(if kind == 4 { ETIMEDOUT } else { EIO })); + } + if core::mem::take(&mut self.pending_recovery_stats) { + return Ok(Some(EIO)); + } return Ok(None); } let phase = self.recovery_phase()?; diff --git a/drivers/gpu/drm/asahi/m3/m3_recovery.rs b/drivers/gpu/drm/asahi/m3/m3_recovery.rs index a2fa6d1daa6369..64eb09a6453eba 100644 --- a/drivers/gpu/drm/asahi/m3/m3_recovery.rs +++ b/drivers/gpu/drm/asahi/m3/m3_recovery.rs @@ -80,6 +80,13 @@ pub(crate) const fn stopped_tiler(flags: u32) -> bool { flags & 9 == 9 } +/// Whether the recovery snapshot proves a tiler-only stop (at least one stopped +/// tiler entry and no non-tiler/fragment entry). Only in this case does 27.2 +/// firmware discard the paired fragment command without advancing `FS.DONE`. +pub(crate) const fn tiler_only_stop(stopped_tiler_seen: bool, non_tiler_seen: bool) -> bool { + stopped_tiler_seen && !non_tiler_seen +} + /// Trailing `STATS 0x16` notifications can arrive after the host already wrote /// phase 0 for that recovery generation; do not treat them as a new fault. pub(crate) const fn is_trailing_stats( @@ -160,9 +167,16 @@ mod tests { fn stopped_tiler_matches_observed_g15g_and_g14_flags() { assert!(stopped_tiler(0xd)); assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x15)); + assert!(!stopped_tiler(0x27)); assert!(!stopped_tiler(0x7)); assert!(!stopped_tiler(0x8)); assert!(!stopped_tiler(0x0)); + + assert!(tiler_only_stop(true, false)); + assert!(!tiler_only_stop(true, true)); + assert!(!tiler_only_stop(false, true)); + assert!(!tiler_only_stop(false, false)); } #[test] diff --git a/drivers/gpu/drm/asahi/m3/m3_render.rs b/drivers/gpu/drm/asahi/m3/m3_render.rs index 5ce53ec48c4303..335dd95f640bea 100644 --- a/drivers/gpu/drm/asahi/m3/m3_render.rs +++ b/drivers/gpu/drm/asahi/m3/m3_render.rs @@ -832,6 +832,10 @@ impl Render { } Ok(true) } + /// Whether the tiler queue has not yet retired its current head. + pub(crate) fn ta_done_pending(&mut self) -> Result { + Ok(self.objects[s::TA_POINTERS].read_u32(queue::DONE)? != u32::from(self.heads[0])) + } /// Whether TA fully drained while fragment has READ == head but DONE < head. /// /// On a TA fault, 27.2 firmware aborts the paired fragment command without @@ -851,7 +855,11 @@ impl Render { /// drained the stopped batch, and mark the faulting VM's binding for quarantine. pub(crate) fn finish_recovery(&mut self, dev: &driver::AsahiDrmDevice) -> Result { self.quarantine_active_vm = true; - self.recovery_aborted_draw = Some(self.draw); + self.recovery_aborted_draw = if self.fragment_read_only_pending()? { + Some(self.draw) + } else { + None + }; let ta_expected = self.stamp_epoch.value(s::STAMP_TA - 256, self.draw); let fs_expected = self.stamp_epoch.value(s::STAMP_FRAGMENT - 256, self.draw); let ta_host = self.objects[s::TA_STAMP].read_u32(0)?; diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 437d779436ea7b..4885e98486bf0a 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -293,6 +293,7 @@ impl Inner { } let mut entries = 0usize; let mut clear_tpc = false; + let mut non_tiler_stop = false; for idx in 0..offsets.snapshot_entries { let (flags, target) = self.config.read_recovery_snapshot(idx)?; let Some(entry) = SnapshotEntry::decode(flags, target) else { @@ -300,6 +301,8 @@ impl Inner { }; if rec::stopped_tiler(entry.flags) { clear_tpc = true; + } else { + non_tiler_stop = true; } if entries < 4 { dev_info!( @@ -314,6 +317,7 @@ impl Inner { } entries += 1; } + let tiler_only = rec::tiler_only_stop(clear_tpc, non_tiler_stop); if clear_tpc { for batch in self.active.iter() { if let NativeJob::Render(j) = &mut self.jobs[batch.index] { @@ -363,6 +367,17 @@ impl Inner { } } } + // Snapshot whether TA was still pending before phase 0 so the discarded-FS + // fallback only applies when TA actually drains after phase 0 on a + // snapshot-proven tiler-only stop (never on a pure-fragment or TA+FS stop). + let mut ta_pending_before_p0 = false; + for batch in self.active.iter() { + if let NativeJob::Render(j) = &mut self.jobs[batch.index] { + if j.ta_done_pending()? { + ta_pending_before_p0 = true; + } + } + } self.config.write_recovery_phase(0)?; self.config.note_recovered(generation); dev_err!( @@ -376,6 +391,7 @@ impl Inner { let check_busy = crate::m3::m3_params::retire_mmio(self.device.soc()) & crate::m3::m3_params::RETIRE_MMIO_BUSY != 0; + let allow_discarded_fs = tiler_only && ta_pending_before_p0; let drain_start = Instant::::now(); let mut another_round = false; loop { @@ -386,7 +402,10 @@ impl Inner { if all_drained { // Honor the SoC's retire_mmio mask: do not probe core-clock-gated busy // registers (0xc020/0xc120) when RETIRE_MMIO_BUSY is omitted (e.g. G15G). - let engines_idle = phase == 0 + // Only allow the discarded-FS fallback when the snapshot proved a + // tiler-only stop and TA actually drained after phase 0. + let engines_idle = allow_discarded_fs + && phase == 0 && (!check_busy || (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 || self.device.check_idle_parts(true, false).is_ok()); From 90292a2e51c29097af5dd2320b0d0c76d36bca6e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 23:15:25 +1100 Subject: [PATCH 0947/1514] ci: boot release kernels under QEMU and load every module Before a release is published, boot the built kernel on the QEMU virt machine and modprobe every module in modules.order, with a watchdog per module. Loading the KUnit modules runs their suites (kunit.enable=1 on the smoke command line only). A module whose init returns -ENODEV/-ENXIO found no hardware and counts as loaded. Any other load failure, hang, kernel warning, oops or panic, and any failing KUnit suite, fails the run unless kernel-smoke-expected.txt lists it with a reason. Warnings are pinned to the module being loaded through a marker written to /dev/kmsg. The Apple drivers find no hardware under QEMU; they are covered by the lab regression gate on real Macs. Signed-off-by: Ryan Murray --- .github/scripts/kernel-smoke-expected.txt | 33 ++++ .github/scripts/kernel-smoke-qemu.sh | 175 ++++++++++++++++++++++ .github/workflows/kernel-release.yml | 44 +++++- 3 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 .github/scripts/kernel-smoke-expected.txt create mode 100755 .github/scripts/kernel-smoke-qemu.sh diff --git a/.github/scripts/kernel-smoke-expected.txt b/.github/scripts/kernel-smoke-expected.txt new file mode 100644 index 00000000000000..19a164a8c79ac3 --- /dev/null +++ b/.github/scripts/kernel-smoke-expected.txt @@ -0,0 +1,33 @@ +# Modules the QEMU smoke run does not load, or that are known not to load +# under QEMU, and KUnit suites known to fail there. One per line: +# skip never loaded +# fail loading may fail or hang without failing the run +# warn a kernel warning while loading it does not fail the run +# kunit the suite may fail without failing the run +# Names may be shell globs. Every entry needs a reason. Remove an entry once it +# passes. +skip rcutorture runs torture kthreads until unloaded +skip locktorture runs torture kthreads until unloaded +skip scftorture runs torture kthreads until unloaded +skip rcuscale runs a benchmark until unloaded +skip refscale runs a benchmark until unloaded +skip torture only a library for the torture tests above +skip test_lockup provokes soft/hard lockups on purpose +skip test_vmalloc vmalloc stress test, runs for minutes under emulation +skip speakup_* speech synthesizer drivers; the serial ones wait for a synthesizer on a serial port +fail tcrypt returns -EAGAIN by design after running its tests +fail xusbatm needs vendor/product module parameters +fail ptp_kvm needs the KVM PTP hypervisor service +fail alim7101_wdt probes for an ALi M7101 chipset (-EBUSY without it) +fail dtpm Rockchip SoC power hierarchy, refuses on other machines +fail snd-soc-uda1342 its I2C driver name "uda1342" is already taken by the media uda1342 driver +fail nhc_ghc_* 6LoWPAN GHC compression claims the NHC IDs of the plain nhc_* modules loaded before it +warn serial_ir PC serial-port IR receiver requests a fixed legacy IRQ the virt machine does not have +warn snd-mtpav PC parallel-port MIDI driver requests a fixed legacy IRQ the virt machine does not have +fail ubifs init cannot get the zstd compressor (-ENOENT) in this initramfs; not yet triaged +kunit arm-smmu-v3-kunit-test arm_smmu_v3_invs_test trips UBSAN array-index-out-of-bounds in arm-smmu-v3.c; not yet triaged +kunit amdv1_iommu_test test_map_simple secondary page-table accounting mismatch; not yet triaged +kunit amdgpu_dm_hdcp dm_test_event_cpirq_schedules_property_validate fails; not yet triaged +kunit amdgpu_dm_irq dm_test_dcn10_register_irq_handlers_one_crtc fails; not yet triaged +kunit amdgpu_dm_crtc dm_test_crtc_enable_vblank_ips_restore{,_replay} fault (unexpected DAIF); not yet triaged +kunit binder_alloc binder_alloc_exhaustive_test reports failures; not yet triaged diff --git a/.github/scripts/kernel-smoke-qemu.sh b/.github/scripts/kernel-smoke-qemu.sh new file mode 100755 index 00000000000000..ca19daf19d94b1 --- /dev/null +++ b/.github/scripts/kernel-smoke-qemu.sh @@ -0,0 +1,175 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Boot a release kernel under QEMU (virt machine) and load every module it ships. +# +# Usage: kernel-smoke-qemu.sh +# +# Loading a KUnit module runs its suites, so this also runs every KUnit suite the +# configuration builds as a module. The Apple drivers find no hardware under +# QEMU and only register themselves; real hardware is covered by the lab gate. +# +# .github/scripts/kernel-smoke-expected.txt lists modules that are not loaded +# (skip) or are known not to load or to fail under QEMU (fail), and KUnit suites +# known to fail (kunit), each with a reason. A module whose init returns -ENODEV +# or -ENXIO (no such device: it probed for hardware QEMU does not have) counts as +# loaded correctly. Anything else that fails to load, hangs, oopses, warns or +# panics fails the run. + +set -euo pipefail + +IMG=$(realpath "$1") +MODS=$(realpath "$2") +BUSYBOX=$(realpath "$3") +OUT=$(realpath -m "$4") +HERE=$(dirname "$(realpath "$0")") +EXPECTED=$HERE/kernel-smoke-expected.txt +QEMU_TIMEOUT=${QEMU_TIMEOUT:-9000} +MOD_TIMEOUT=${MOD_TIMEOUT:-120} + +mkdir -p "$OUT" +R=$(mktemp -d "$OUT/initramfs.XXXXXX") +trap 'rm -rf "$R"' EXIT + +# sbin too: request_module() runs /sbin/modprobe. +mkdir -p "$R"/{bin,sbin,usr/bin,usr/sbin,dev,proc,sys,tmp,etc} +install -m 0755 "$BUSYBOX" "$R/bin/busybox" +tar --zstd -xf "$MODS" -C "$R" +KREL=$(ls "$R/lib/modules") +# skip entries may be shell globs (speakup_*); expand them against modules.order. +mapfile -t SKIPPAT < <(awk '$1 == "skip" { print $2 }' "$EXPECTED") +while read -r path; do + m=${path##*/}; m=${m%%.ko*} + for pat in "${SKIPPAT[@]}"; do + # shellcheck disable=SC2053 + if [[ $m == $pat ]]; then echo "$m"; break; fi + done +done < "$R/lib/modules/$KREL/modules.order" > "$R/etc/smoke-skip" +echo "skipping $(wc -l < "$R/etc/smoke-skip") modules" + +cat > "$R/init" < /dev/kmsg + modprobe "\$m" > /tmp/out 2>&1 & + pid=\$!; t=0 + while kill -0 \$pid 2>/dev/null && [ \$t -lt $MOD_TIMEOUT ]; do sleep 1; t=\$((t + 1)); done + if kill -0 \$pid 2>/dev/null; then echo "SMOKE-HANG \$m"; continue; fi + if wait \$pid; then echo "SMOKE-OK \$m" + elif grep -q "No such device" /tmp/out; then echo "SMOKE-NODEV \$m" + else echo "SMOKE-FAIL \$m \$(head -c 300 /tmp/out | tr '\n' ' ')"; fi +done < /lib/modules/\$(uname -r)/modules.order +echo SMOKE-DMESG-BEGIN +dmesg +echo SMOKE-DMESG-END +echo SMOKE-END +poweroff -f +EOF +chmod 0755 "$R/init" + +(cd "$R" && find . | LC_ALL=C sort | cpio -o -H newc --quiet | zstd -T0 -q -3 > "$OUT/initramfs.cpio.zst") +rm -rf "$R"; trap - EXIT + +ACCEL=tcg +if [ -w /dev/kvm ] && [ "$(uname -m)" = aarch64 ]; then ACCEL=kvm; fi +CPU=max; [ $ACCEL = kvm ] && CPU=host +echo "qemu: accel=$ACCEL kernel=$KREL" +set +e +timeout "$QEMU_TIMEOUT" qemu-system-aarch64 -M virt -accel $ACCEL -cpu $CPU -smp 4 -m 6G \ + -nographic -no-reboot -kernel "$IMG" -initrd "$OUT/initramfs.cpio.zst" \ + -append "console=ttyAMA0 rdinit=/init panic=-1 loglevel=1 log_buf_len=128M kunit.enable=1" \ + > "$OUT/console.log" 2>&1 +QRC=$? +set -e +echo "qemu exit $QRC" + +python3 - "$OUT/console.log" "$EXPECTED" "$OUT" <<'PY' +import fnmatch, re, sys, json +log, expected, out = sys.argv[1:] +text = open(log, errors='replace').read().replace('\r', '') +exp = {'skip': {}, 'fail': {}, 'warn': {}, 'kunit': {}} +for line in open(expected): + line = line.strip() + if not line or line.startswith('#'): + continue + kind, name, *why = line.split(None, 2) + exp[kind][name] = why[0] if why else '' +def expected(kind, name): + return any(fnmatch.fnmatchcase(name, pat) for pat in exp[kind]) +res = {} +for m in re.finditer(r'^SMOKE-(OK|NODEV|FAIL|HANG|SKIP) (\S+)(.*)$', text, re.M): + res[m.group(2)] = (m.group(1), m.group(3).strip()) +begin = re.search(r'^SMOKE-BEGIN (\S+) (\d+) modules', text, re.M) +ended = re.search(r'^SMOKE-END$', text, re.M) is not None +d = re.search(r'^SMOKE-DMESG-BEGIN$(.*)^SMOKE-DMESG-END$', text, re.M | re.S) +dmesg = d.group(1) if d else text +open(f'{out}/dmesg.txt', 'w').write(dmesg) +strip = lambda l: re.sub(r'^\[\s*[\d.]+\]\s?', '', l) +lines = [strip(l) for l in dmesg.splitlines()] +kunit = {} +for l in lines: + m = re.match(r'^(not ok|ok) \d+ (\S+)(.*)$', l) + if m: + kunit[m.group(2)] = 'SKIP' if '# SKIP' in m.group(3) else ('PASS' if m.group(1) == 'ok' else 'FAIL') +# Kernel warnings, oopses and stalls, attributed to the module being loaded +# (the init writes "smoke-load " to /dev/kmsg before each modprobe). +EVENT = re.compile(r'^(WARNING:|Oops|BUG:|Kernel panic|Unable to handle kernel|INFO: task .* blocked for more than|watchdog: BUG: soft lockup|rcu: INFO: .*detected stall)') +# KUnit modules provoke warnings and KFENCE reports on purpose; for them the +# suite results below are the verdict. +cur, events, kunit_mods = None, [], set() +for l in lines: + m = re.match(r'^smoke-load (\S+)$', l) + if m: + cur = m.group(1) + continue + if l.startswith('KTAP version') and cur: + kunit_mods.add(cur) + if EVENT.search(l): + events.append((cur, l)) +bad_kernel, tolerated, kunit_warn = [], [], 0 +for mod, l in events: + if mod in kunit_mods: + kunit_warn += 1 + elif mod and expected('warn', mod): + tolerated.append(f'{mod}: {l}') + else: + bad_kernel.append(f'{mod}: {l}') +problems = [] +if not begin: + problems.append('kernel did not reach the smoke init') +if not ended: + problems.append('run did not finish (panic, hang or timeout)') +counts = {} +for name, (st, msg) in res.items(): + counts[st] = counts.get(st, 0) + 1 + if st in ('FAIL', 'HANG') and not expected('fail', name): + problems.append(f'module {name}: {st} {msg}') +stale = [n for n in exp['fail'] if res.get(n, ('', ''))[0] == 'OK'] +kfail = [s for s, r in kunit.items() if r == 'FAIL' and not expected('kunit', s)] +problems += [f'KUnit suite {s}: FAIL' for s in kfail] +if bad_kernel: + problems += [f'kernel: {l}' for l in bad_kernel[:40]] +kc = {} +for r in kunit.values(): + kc[r] = kc.get(r, 0) + 1 +summary = {'kernel': begin.group(1) if begin else None, 'modules': int(begin.group(2)) if begin else 0, + 'finished': ended, 'loads': counts, 'kunit_suites': kc, + 'kunit_modules': len(kunit_mods), 'kunit_module_warnings': kunit_warn, + 'stale_expected_failures': stale, 'tolerated_warnings': tolerated, + 'kernel_warnings': bad_kernel[:50], 'problems': problems} +json.dump(summary, open(f'{out}/smoke-summary.json', 'w'), indent=1) +with open(f'{out}/smoke-results.tsv', 'w') as f: + for name, (st, msg) in sorted(res.items()): + f.write(f'{name}\t{st}\t{msg}\n') + for s, r in sorted(kunit.items()): + f.write(f'kunit:{s}\t{r}\t\n') +print(json.dumps({k: v for k, v in summary.items() if k != 'kernel_warnings'}, indent=1)[:6000]) +sys.exit(1 if problems else 0) +PY diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 3442ecb87cd5ff..9c4ea2a31718f0 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -9,6 +9,9 @@ # one rolling channel by hand (publish: edge | nightly). Pull requests that # change the release machinery itself get a build without publishing. # +# Every build boots under QEMU and loads every module it ships (which also runs +# the KUnit suites built as modules) before anything is published. +# # The configuration is the fleet configuration (aurora_defconfig + asahi.config) # built with the fleet toolchain versions pinned below. Modules are signed with # a key generated for each run and thrown away afterwards; lab fleet kits are @@ -207,8 +210,47 @@ jobs: retention-days: 7 compression-level: 0 - publish: + smoke: needs: [plan, build] + runs-on: ubuntu-24.04-arm + timeout-minutes: 180 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.plan.outputs.sha }} + fetch-depth: 1 + persist-credentials: false + sparse-checkout: .github + + - uses: actions/download-artifact@v4 + with: + name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: dist + + - name: Install QEMU + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends qemu-system-arm busybox-static zstd cpio + + - name: Boot under QEMU and load every module + run: | + krel=$(cat dist/kernel.release) + gzip -dc "dist/Image-$krel.gz" > Image + .github/scripts/kernel-smoke-qemu.sh Image "dist/modules-$krel.tar.zst" /bin/busybox smoke + + - if: always() + uses: actions/upload-artifact@v4 + with: + name: smoke-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} + path: | + smoke/console.log + smoke/dmesg.txt + smoke/smoke-summary.json + smoke/smoke-results.tsv + retention-days: 14 + + publish: + needs: [plan, build, smoke] if: needs.plan.outputs.channel != 'none' && needs.plan.outputs.build == 'true' runs-on: ubuntu-24.04-arm permissions: From 3a04bc2ff31bf8a884e0183f341be46a5874165b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 23:37:56 +1100 Subject: [PATCH 0948/1514] docs: link the organisation branching rules from RELEASES.md and CONTRIBUTING.md Point at agent-guidelines' branching-and-releases policy for the rules, and state that only Owners create v* tags and how versions are numbered. Signed-off-by: Ryan Murray --- CONTRIBUTING.md | 3 ++- RELEASES.md | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aac803eeae2381..2c061be4b95f5f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,7 +97,8 @@ For kernel patches, also follow the existing and `hotfix/v` a short-lived branch for a stable hotfix (see [RELEASES.md](RELEASES.md)). -There are no long-lived release or per-platform branches. +There are no long-lived release or per-platform branches. The full rules are in +[branching-and-releases](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md). `main` takes changes only through pull requests: no direct pushes, no force pushes and no deletion. Merged branches are deleted automatically, so start diff --git a/RELEASES.md b/RELEASES.md index 4e83269f304985..6e060aca2dcedb 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -4,6 +4,10 @@ This repository has one long-lived branch, `main`. Every change lands there through a pull request, and every release is built from a commit on `main` by [`kernel-release.yml`](.github/workflows/kernel-release.yml). +The organisation-wide rules (branch names, who may tag, the merge gate) are in +[branching-and-releases](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md); +this file adds the kernel build details. + ## Channels | Channel | Where | Built when | Changes? | @@ -45,7 +49,8 @@ Stable releases are time-boxed. On the release cadence: (M1 Pro, M2 Air, M2 mini, M3 Air, M4 Air, M4 Pro, Neo) boots it with no new failures compared with the previous stable release. The gate looks for regressions only; missing features do not block a tag. -2. Tag it and push the tag: +2. An Owner tags it and pushes the tag (only Owners create `v*` tags, and + nobody moves or deletes one): ```sh git tag -a v0.2.0 -m 'Aurora v0.2.0' @@ -54,6 +59,9 @@ Stable releases are time-boxed. On the release cadence: 3. The workflow builds it and publishes the release with generated notes. +Versions are `X.Y.Z`: Y goes up for a regular release, Z for a hotfix, and a +new upstream base is at least a minor bump. + Never hold a tag for unfinished work. Work that is not ready stays in its pull request and goes out in the next release. The workflow refuses a tag that is not on `main` and never overwrites a stable release that already exists. From 208894259f593416d91546c9c8f8325614aefef1 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Mon, 23 Nov 2026 17:46:23 -0700 Subject: [PATCH 0949/1514] iommu/apple-dart: hold a sleep lease with a semaphore, not a mutex v27_lifecycle is taken by apple_dart_v27_claim() and stays held for as long as the sleep lease lasts. The claim runs in the suspend's async work and the lease is finished by the resume, from another task. A mutex has to be released by the task that took it. With lock checking on, the first T6050 deep sleep reports both ends: BUG: workqueue leaked atomic, lock or RCU: kworker/u73:1[211] locks held by kworker/u73:1/211: #0: (&dart->v27_lifecycle), at: apple_dart_v27_claim+0xf4/0xb80 WARNING: bad unlock balance detected! mutex_unlock apple_dart_v27_finish dcp_v27_late_disarm and lockdep turns itself off for the rest of the boot. A lock that changes hands is a semaphore. Make it one; no change to who waits for what. Signed-off-by: Jens Axboe --- drivers/iommu/apple-dart-v27-late.inc | 8 ++++---- drivers/iommu/apple-dart.c | 21 ++++++++++++++------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/drivers/iommu/apple-dart-v27-late.inc b/drivers/iommu/apple-dart-v27-late.inc index 74e663b1e40641..965eaf0f17edc5 100644 --- a/drivers/iommu/apple-dart-v27-late.inc +++ b/drivers/iommu/apple-dart-v27-late.inc @@ -137,12 +137,12 @@ int apple_dart_v27_claim(struct device *dev, struct device *owner, return -EBUSY; } if (dev->driver != &apple_dart_driver.driver || !(d = dev_get_drvdata(dev)) || - !d->v27_provider || !mutex_trylock(&d->v27_lifecycle)) { + !d->v27_provider || down_trylock(&d->v27_lifecycle)) { device_unlock(dev); return -ENODEV; } if (!try_module_get(THIS_MODULE)) { - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); device_unlock(dev); return -ENODEV; } @@ -340,7 +340,7 @@ free: unlock: module_put(THIS_MODULE); put_device(dev); - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); return ret; } EXPORT_SYMBOL_GPL(apple_dart_v27_claim); @@ -459,7 +459,7 @@ int apple_dart_v27_finish(struct apple_dart_v27_lease *l, bool stopped) WRITE_ONCE(d->m5_sleep_owner, NULL); WRITE_ONCE(d->v27_restoring, false); pm_runtime_put_noidle(d->dev); - mutex_unlock(&d->v27_lifecycle); + up(&d->v27_lifecycle); module_put(l->module); put_device(provider); kfree(l); diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bf7a4fc0807faa..5301e8ecb192b2 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -49,6 +49,7 @@ #include #include #include +#include #include #include #include @@ -385,7 +386,11 @@ struct apple_dart { u32 m5_disp_streams; /* the display pipe's streams before its domain went off */ bool m5_released, m5_changed, m5_display, m5_failed; /* Optional cached evidence; never a sleep-ownership grant. */ - struct mutex v27_lifecycle; + /* + * Held for as long as a sleep lease lasts: taken by the suspend that claims the lease and + * released by the resume that finishes it, in another task. So a semaphore, not a mutex. + */ + struct semaphore v27_lifecycle; struct list_head v27_clients; atomic_t v27_ops; bool v27_provider, v27_lost, v27_noirq_skip, v27_restoring; @@ -5795,7 +5800,7 @@ static int apple_dart_probe(struct platform_device *pdev) } } spin_lock_init(&dart->lock); - mutex_init(&dart->v27_lifecycle); + sema_init(&dart->v27_lifecycle, 1); INIT_LIST_HEAD(&dart->v27_clients); atomic_set(&dart->v27_ops, 0); dart->v27_provider = res && apple_dart_v27_provider(dev, res->start); @@ -6535,10 +6540,12 @@ int apple_dart_restore_tunnel_state(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_restore_tunnel_state); +DEFINE_GUARD(apple_dart_v27_lifecycle, struct semaphore *, down(_T), up(_T)) + static void apple_dart_remove(struct platform_device *pdev) { struct apple_dart *dart = platform_get_drvdata(pdev); - guard(mutex)(&dart->v27_lifecycle); + guard(apple_dart_v27_lifecycle)(&dart->v27_lifecycle); if (dart->cold_ane) { dev_warn(&pdev->dev, "cold ANE DART retained until reset\n"); @@ -6593,11 +6600,11 @@ static void apple_dart_shutdown(struct platform_device *pdev) struct apple_dart *dart = platform_get_drvdata(pdev); /* - * A sleep lease that lost its retained state keeps this mutex for good, so that nothing + * A sleep lease that lost its retained state keeps this semaphore for good, so that nothing * reuses the DART before the platform reset. The reset is what follows here: waiting for - * the mutex would hang the shutdown. + * it would hang the shutdown. */ - if (!mutex_trylock(&dart->v27_lifecycle)) { + if (down_trylock(&dart->v27_lifecycle)) { dev_info(&pdev->dev, "shutdown: left as its sleep lease pinned it\n"); return; } @@ -6609,7 +6616,7 @@ static void apple_dart_shutdown(struct platform_device *pdev) */ if (apple_dart_has_borrowed(dart)) apple_dart_fail_borrowed(dart, "shutdown"); - mutex_unlock(&dart->v27_lifecycle); + up(&dart->v27_lifecycle); } static const struct apple_dart_hw apple_dart_hw_t8103 = { From 7d64087e37aa9f17d7e2c1504ff6efb8a6300f28 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Mon, 23 Nov 2026 17:46:24 -0700 Subject: [PATCH 0950/1514] soc: apple: sleep: keep RCU watching while the T6050 entry prepares On a SoC with early_context the whole entry runs as cpu_suspend()'s finisher. cpu_suspend() calls the finisher after ct_cpuidle_enter(), with RCU not watching, which fits a finisher that only powers the core down. This one first checks the RTC alarm over SPMI under the controller's lock, stops the coprocessors, looks at work items and logs. With lock checking on, the first T6050 deep sleep reports each of them: RCU not watching for tracepoint WARNING: include/trace/events/lock.h:47 at lock_acquire _mutex_trylock_nest_lock apple_spmi_fifo_trylock t6050_sleep_pmu_xfer t6050_sleep_check_alarm apple_sleep_enter_saved cpu_suspend WARNING: suspicious RCU usage work_busy apple_nvme_m5_last_check apple_sleep_enter_saved Leave the idle state for the preparation and enter it again before the commit, which is the part that never returns. Signed-off-by: Jens Axboe --- drivers/soc/apple/sleep.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9cee856626f918..375988d9697d3f 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -6027,14 +6028,21 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) static int apple_sleep_enter_saved(unsigned long unused) { struct apple_sleep *s = apple_sleep; - int ret = s->soc->ops->cpu_prepare(s->mbox->boot_mpidr); + int ret; + /* + * cpu_suspend() calls its finisher with RCU not watching. Up to the commit this one + * takes locks, logs and looks at work items: RCU watches until then. + */ + ct_cpuidle_exit(); + ret = s->soc->ops->cpu_prepare(s->mbox->boot_mpidr); + if (!ret) + ret = apple_sleep_enter_prepare(s); + if (!ret) + pm_set_resume_via_firmware(); + ct_cpuidle_enter(); if (ret) return ret; - ret = apple_sleep_enter_prepare(s); - if (ret) - return ret; - pm_set_resume_via_firmware(); /* cpu_suspend has already saved boot context. Commit never returns. */ return apple_sleep_commit(0); } From cbc00abf1689afadd3eb6f3d3e0493e20b9fe750 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 11:55:46 -0700 Subject: [PATCH 0951/1514] wifi: apple: centauri: attach the Beta function outside the rescan lock and boot_lock centauri_t6050_start_ipc() holds the PCI rescan lock while it attaches the Bluetooth function's driver, whose probe registers a PM notifier. A suspend that starts while the N1 is still coming up after a wake then never finishes: - the suspend runs the PM notifiers; the PCIe host's flushes its unpark work, - that work waits for the rescan lock in its cold rescan, - the boot worker holds the lock and waits, in hci_register_dev(), to write the notifier chain the suspend is reading. Nothing has armed the sleep's watchdog yet, so the machine stays up with the suspend stuck. On a K116s, two RTC deep sleeps back to back do it every time; a lid closed again a few seconds after a wake does too. Take a reference under the lock and attach after dropping it. The boot worker's boot_lock has the same problem one step removed. The attach ran under it, the PCIe host's PM notifier takes the rescan lock, and the rewake worker takes boot_lock in centauri_t6050_quiesce() with the rescan lock held. Lockdep reports it at the first deep sleep: &c->boot_lock --> (pm_chain_head).rwsem --> pci_rescan_remove_lock So the boot worker attaches after it has dropped boot_lock as well. Fixes: 0a2d99d4ae30 ("PCI: apple: T6050: look for a parked port's functions from a work") Signed-off-by: Jens Axboe --- .../apple/centauri/t6050/centauri_ipc.c | 29 ++++++++++++++----- .../apple/centauri/t6050/centauri_pci.c | 5 +++- .../apple/centauri/t6050/centauri_t6050.h | 3 +- 3 files changed, 28 insertions(+), 9 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c index a5f49860afdd2f..b4b1cc5941601d 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_ipc.c @@ -378,7 +378,8 @@ static int enumerate_functions(struct centauri_t6050 *c) return 0; } -static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) +static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c, + struct pci_dev **beta) { struct centauri_t6050_ipc *ipc; u32 stage; @@ -450,9 +451,7 @@ static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) /* Publish usable shared firmware before the Beta consumer probes. */ smp_store_release(&c->ready, true); - ret = device_attach(&ipc->function[2]->dev); - if (ret < 0) - dev_warn(&c->pdev->dev, "Beta driver attachment failed: %d\n", ret); + *beta = pci_dev_get(ipc->function[2]); return 0; failed: dev_err(&c->pdev->dev, "IPC bootstrap failed: %d (Control stage=%#x)\n", @@ -468,15 +467,31 @@ static int centauri_t6050_start_ipc_locked(struct centauri_t6050 *c) return ret; } -int centauri_t6050_start_ipc(struct centauri_t6050 *c) +/* On success *beta may hold a reference to the Beta function, for centauri_t6050_attach_beta(). */ +int centauri_t6050_start_ipc(struct centauri_t6050 *c, struct pci_dev **beta) { int ret; if (!pci_trylock_rescan_remove()) return -EAGAIN; - ret = READ_ONCE(c->removing) ? -ECANCELED : centauri_t6050_start_ipc_locked(c); + ret = READ_ONCE(c->removing) ? -ECANCELED : + centauri_t6050_start_ipc_locked(c, beta); pci_unlock_rescan_remove(); - return ret; + return *beta ? 0 : ret; +} + +/* + * Under neither the rescan lock nor boot_lock: the Beta driver's probe + * registers a PM notifier, a suspend's notifiers wait for a rescan, and a + * rescan's holder (the rewake) takes boot_lock. + */ +void centauri_t6050_attach_beta(struct centauri_t6050 *c, struct pci_dev *beta) +{ + int ret = device_attach(&beta->dev); + + if (ret < 0) + dev_warn(&c->pdev->dev, "Beta driver attachment failed: %d\n", ret); + pci_dev_put(beta); } void centauri_t6050_free_ipc(struct centauri_t6050 *c) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c index 6cda4019d8f0dc..8513557a566dd8 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_pci.c @@ -455,6 +455,7 @@ static int centauri_t6050_cycle(struct centauri_t6050 *c) static void centauri_t6050_boot_worker(struct work_struct *work) { struct centauri_t6050 *c = container_of(to_delayed_work(work), struct centauri_t6050, boot_work); + struct pci_dev *beta = NULL; bool retry = false; int ret; @@ -473,7 +474,7 @@ static void centauri_t6050_boot_worker(struct work_struct *work) c->boot_phase = CEN_BOOT_IPC; break; case CEN_BOOT_IPC: - ret = centauri_t6050_start_ipc(c); + ret = centauri_t6050_start_ipc(c, &beta); if (!ret) c->boot_phase = CEN_BOOT_READY; break; @@ -496,6 +497,8 @@ static void centauri_t6050_boot_worker(struct work_struct *work) if (READ_ONCE(c->removing)) c->boot_phase = CEN_BOOT_STOPPED; mutex_unlock(&c->boot_lock); + if (beta) + centauri_t6050_attach_beta(c, beta); if (retry && !READ_ONCE(c->removing)) queue_delayed_work(system_long_wq, &c->boot_work, msecs_to_jiffies(20)); } diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h index 17a92ca333985c..39311db97221bb 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_t6050.h @@ -72,7 +72,8 @@ int centauri_t6050_request_irqs(struct centauri_t6050_irqs *irqs, struct pci_dev unsigned int count, irq_handler_t handler, void *data); void centauri_t6050_free_irqs(struct centauri_t6050_irqs *irqs); -int centauri_t6050_start_ipc(struct centauri_t6050 *c); +int centauri_t6050_start_ipc(struct centauri_t6050 *c, struct pci_dev **beta); +void centauri_t6050_attach_beta(struct centauri_t6050 *c, struct pci_dev *beta); void centauri_t6050_free_ipc(struct centauri_t6050 *c); void centauri_t6050_release_ipc(struct centauri_t6050_ipc *ipc); bool centauri_t6050_ipc_fenced(struct centauri_t6050_ipc *ipc); From 91f0296b98d6574acf38c75b6bf63db98a4b04c0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 24 Nov 2026 23:59:07 +1100 Subject: [PATCH 0952/1514] drm/asahi: m3: validate aborted stamps for discarded-FS drain check On a live J615 (T8122, G15G 27.2) tiler-only MMU fault, firmware already advances TA.DONE == TA.READ during phase 2 -> phase 3 before host phase 0, so checking ta_done_pending() right before phase 0 always read false and timed out waiting for the discarded paired fragment's FS.DONE. Remove the racy ta_done_pending() pre-phase-0 check and tighten fragment_read_only_pending() directly to require both TA_STAMP != expected (TA genuinely aborted) and FRAGMENT_FW_STAMP != expected (paired FS was discarded rather than executed), gated by tiler_only_stop() from the phase-1 snapshot and phase == 0. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_render.rs | 24 +++++++++++++++--------- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 19 ++++--------------- 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_render.rs b/drivers/gpu/drm/asahi/m3/m3_render.rs index 335dd95f640bea..f83a9cca36c6a2 100644 --- a/drivers/gpu/drm/asahi/m3/m3_render.rs +++ b/drivers/gpu/drm/asahi/m3/m3_render.rs @@ -832,24 +832,30 @@ impl Render { } Ok(true) } - /// Whether the tiler queue has not yet retired its current head. - pub(crate) fn ta_done_pending(&mut self) -> Result { - Ok(self.objects[s::TA_POINTERS].read_u32(queue::DONE)? != u32::from(self.heads[0])) - } - /// Whether TA fully drained while fragment has READ == head but DONE < head. + /// Whether TA aborted and retired its ring while fragment has `READ == head` + /// with `DONE != head` and neither the TA host stamp nor the fragment FW + /// stamp reached the expected draw value. /// - /// On a TA fault, 27.2 firmware aborts the paired fragment command without - /// advancing `FRAGMENT_POINTERS.DONE` (while advancing `READ == head` and - /// idling the engines); the next draw catches `DONE` back up to `head`. + /// On a tiler-only fault, 27.2 firmware advances `TA.DONE` (already before + /// phase 3) while leaving `TA_STAMP` behind and discarding the paired + /// fragment command without advancing `FRAGMENT_POINTERS.DONE` or + /// `FRAGMENT_FW_STAMP` (`READ` still reaches `head`); the next draw catches + /// `DONE` back up to `head`. pub(crate) fn fragment_read_only_pending(&mut self) -> Result { + let ta_expected = self.stamp_epoch.value(s::STAMP_TA - 256, self.draw); + let fs_expected = self.stamp_epoch.value(s::STAMP_FRAGMENT - 256, self.draw); + let ta_host = self.objects[s::TA_STAMP].read_u32(0)?; + let fs_fw = self.objects[s::FRAGMENT_FW_STAMP].read_u32(0)?; let ta_done = self.objects[s::TA_POINTERS].read_u32(queue::DONE)?; let ta_read = self.objects[s::TA_POINTERS].read_u32(queue::READ)?; let fs_done = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::DONE)?; let fs_read = self.objects[s::FRAGMENT_POINTERS].read_u32(queue::READ)?; Ok(ta_done == u32::from(self.heads[0]) && ta_read == u32::from(self.heads[0]) + && ta_host != ta_expected && fs_read == u32::from(self.heads[1]) - && fs_done != u32::from(self.heads[1])) + && fs_done != u32::from(self.heads[1]) + && fs_fw != fs_expected) } /// Re-synchronize render stamps and pool expectations after firmware recovery /// drained the stopped batch, and mark the faulting VM's binding for quarantine. diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 4885e98486bf0a..c5295f561b39ae 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -367,17 +367,6 @@ impl Inner { } } } - // Snapshot whether TA was still pending before phase 0 so the discarded-FS - // fallback only applies when TA actually drains after phase 0 on a - // snapshot-proven tiler-only stop (never on a pure-fragment or TA+FS stop). - let mut ta_pending_before_p0 = false; - for batch in self.active.iter() { - if let NativeJob::Render(j) = &mut self.jobs[batch.index] { - if j.ta_done_pending()? { - ta_pending_before_p0 = true; - } - } - } self.config.write_recovery_phase(0)?; self.config.note_recovered(generation); dev_err!( @@ -391,7 +380,6 @@ impl Inner { let check_busy = crate::m3::m3_params::retire_mmio(self.device.soc()) & crate::m3::m3_params::RETIRE_MMIO_BUSY != 0; - let allow_discarded_fs = tiler_only && ta_pending_before_p0; let drain_start = Instant::::now(); let mut another_round = false; loop { @@ -402,9 +390,10 @@ impl Inner { if all_drained { // Honor the SoC's retire_mmio mask: do not probe core-clock-gated busy // registers (0xc020/0xc120) when RETIRE_MMIO_BUSY is omitted (e.g. G15G). - // Only allow the discarded-FS fallback when the snapshot proved a - // tiler-only stop and TA actually drained after phase 0. - let engines_idle = allow_discarded_fs + // Only allow the discarded-FS fallback on a snapshot-proven tiler-only stop + // once recovery is back in phase 0 (and fragment_read_only_pending verifies + // that TA aborted without advancing TA_STAMP and FS_FW_STAMP never advanced). + let engines_idle = tiler_only && phase == 0 && (!check_busy || (self.device.pstate_register().unwrap_or(1) & 0xf) == 0 From dcaea251634592936f3c3e312b8804ded52d7d43 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:01:12 +1100 Subject: [PATCH 0953/1514] ci: move the kernel channel tags with the release deploy key The aurora-* tags are protected by a ruleset whose only non-admin bypass is the release deploy key, and GITHUB_TOKEN cannot be given a bypass on a repository ruleset. Move aurora-edge and aurora-nightly over SSH with that key (secret RELEASE_DEPLOY_KEY): only forward (the new commit must contain the tagged one) and with a lease on the old value. Without the secret the job stops with a one-line message saying what to add. Signed-off-by: Ryan Murray --- .github/workflows/kernel-release.yml | 46 +++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 9c4ea2a31718f0..dce180480fef76 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -12,6 +12,10 @@ # Every build boots under QEMU and loads every module it ships (which also runs # the KUnit suites built as modules) before anything is published. # +# The aurora-* channel tags are protected by a ruleset; the publish job moves +# them over SSH with the release deploy key (secret RELEASE_DEPLOY_KEY), only +# forward and with a lease. Stable releases attach to the v* tag an Owner pushed. +# # The configuration is the fleet configuration (aurora_defconfig + asahi.config) # built with the fleet toolchain versions pinned below. Modules are signed with # a key generated for each run and thrown away afterwards; lab fleet kits are @@ -285,6 +289,43 @@ jobs: EOF cat notes.md + - name: Move the channel tag + if: needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly' + env: + DEPLOY_KEY: ${{ secrets.RELEASE_DEPLOY_KEY }} + run: | + set -euo pipefail + tag="aurora-$CHANNEL" + # Rolling channel tags only move forward: the new commit must contain + # the one the tag points at now (a rewritten main stops here). + old=$(gh api "repos/$GH_REPO/git/ref/tags/$tag" -q .object.sha 2>/dev/null || true) + if [ -n "$old" ]; then + status=$(gh api "repos/$GH_REPO/compare/$old...$SHA" -q .status) + case "$status" in + ahead|identical) ;; + *) echo "::error::$tag is at $old, which $SHA does not contain ($status)"; exit 1 ;; + esac + fi + [ "$old" = "$SHA" ] && { echo "$tag already at $SHA"; exit 0; } + # The aurora-* tags are protected by a ruleset that only the release + # deploy key may bypass; GITHUB_TOKEN cannot move them. + if [ -z "$DEPLOY_KEY" ]; then + echo "::error::$tag is protected; add the release deploy key's private half as the RELEASE_DEPLOY_KEY secret (public half: a write deploy key)" + exit 1 + fi + install -m 0700 -d ~/.ssh + printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/release_key + chmod 0600 ~/.ssh/release_key + ssh-keyscan -t ed25519 github.com >> ~/.ssh/known_hosts 2>/dev/null + git init -q tagger + cd tagger + git remote add origin "git@github.com:$GH_REPO.git" + export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/release_key -o IdentitiesOnly=yes" + git fetch -q --depth 1 origin "$SHA" + # The lease makes the push fail if the tag moved since it was read. + git push --force-with-lease="refs/tags/$tag:$old" origin "$SHA:refs/tags/$tag" + rm -f ~/.ssh/release_key + - name: Publish rolling prerelease if: needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly' run: | @@ -292,9 +333,6 @@ jobs: tag="aurora-$CHANNEL" title="Aurora kernel $CHANNEL ($(cut -c1-12 <<<"$SHA"))" if gh release view "$tag" >/dev/null 2>&1; then - # Move the channel tag to the new commit. main only moves forward, - # so this is a fast-forward of the tag; a rewritten main fails here. - gh api -X PATCH "repos/$GH_REPO/git/refs/tags/$tag" -f sha="$SHA" -F force=false >/dev/null gh release edit "$tag" --prerelease --title "$title" --notes-file notes.md gh release upload "$tag" dist/* --clobber keep=$(cd dist && ls) @@ -302,7 +340,7 @@ jobs: grep -qxF "$a" <<<"$keep" || gh release delete-asset "$tag" "$a" -y done else - gh release create "$tag" dist/* --target "$SHA" --prerelease --latest=false \ + gh release create "$tag" dist/* --verify-tag --prerelease --latest=false \ --title "$title" --notes-file notes.md fi gh release view "$tag" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' From d199ac168c7ef277e6f8a33fe7b17b789d5e2eca Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:06:50 +1100 Subject: [PATCH 0954/1514] drm/apple: arm adaptive sync on first VRR enable after desktop takeover adopt dcp_takeover_adopt() adopts the bootloader's live fixed panel mode on desktop 26.6 with dcp->vrr_enabled = false and vrr_min_on = 0 to avoid a 200 ms boot blank. Because dcp_vrr_live() was true unconditionally, subsequent VRR_ENABLED 0->1 commits bypassed iomfb_modeset() and dcp_vrr_update() returned early on !dcp->vrr_enabled, leaving panel VRR inactive until an unrelated mode change occurred. Allow a single modeset in dcp_crtc_atomic_check() when enabling VRR_ENABLED on a live-VRR panel whose adaptive sync is not yet armed (and has not hit vrr_failed), keeping all subsequent VRR_ENABLED toggles live and flicker-free. Also populate dcp->active_color under hdr.lock during dcp_takeover_adopt(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 14 +++++++---- drivers/gpu/drm/apple/iomfb.c | 16 +++++++++---- .../drivers/gpu/apple-dcp/lifecycle.py | 24 ++++++++++++++++++- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bc037fb6e2973e..556e5cfee9bf00 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2222,14 +2222,20 @@ int dcp_crtc_atomic_check(struct drm_crtc *crtc, struct drm_atomic_commit *commi /* * On desktop 26.6 firmware the panel takes VRR_ENABLED with the next - * frame, without a mode set (see dcp_vrr_update()). Other template - * pipes change adaptive sync inside iomfb_modeset() via a full mode - * set, except firmware 27 panels which do not re-modeset on VRR. + * frame, without a mode set (see dcp_vrr_update()), once a mode set + * has armed adaptive sync. An adopted boot mode starts fixed + * (!dcp->vrr_enabled), so enabling VRR_ENABLED the first time still + * needs one mode set; other template pipes change adaptive sync inside + * iomfb_modeset() via a full mode set, except firmware 27 panels which + * do not re-modeset on VRR. */ if (READ_ONCE(dcp->iomfb_template_pq) && !(dcp->fw_compat == DCP_FIRMWARE_V_27_0 && (dcp->main_display || dcp_has_panel(dcp))) && - crtc_state->enable && !dcp_vrr_live(dcp)) { + crtc_state->enable && + !(dcp_vrr_live(dcp) && + (READ_ONCE(dcp->vrr_enabled) || !crtc_state->vrr_enabled || + (dcp->desktop && READ_ONCE(dcp->desktop->vrr_failed))))) { struct drm_crtc_state *old = drm_atomic_get_old_crtc_state(commit, crtc); diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 3febcae75f8d8d..9650de884ecc3c 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3053,12 +3053,18 @@ static int dcp_takeover_adopt(struct apple_dcp *dcp, const struct drm_display_mo if (!sel) return -ENOENT; - dcp->mode = (struct dcp_set_digital_out_mode_req) { - .color_mode_id = sel->color_mode_id, - .timing_mode_id = sel->timing_mode_id, - }; + scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { + dcp->mode = (struct dcp_set_digital_out_mode_req) { + .color_mode_id = sel->color_mode_id, + .timing_mode_id = sel->timing_mode_id, + }; + if (dcp_default_sdr_color(sel, &dcp->active_color)) + dcp->active_color.score = -1; + dcp->output_pq = false; + dcp->output_hdr = false; + dcp->vrr_enabled = false; + } dcp->use_timestamps = sel->needs_timestamps; - dcp->vrr_enabled = false; d->mode_live = true; d->takeover_adopted = true; dev_info(dcp->dev, "takeover: adopting the live mode (color:%u timing:%u) " DRM_MODE_FMT "\n", diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index d06fe608118556..26c5d012b77a4a 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -1844,12 +1844,13 @@ def vrr(root): DCP_FIRMWARE_V_14_7, DCP_FIRMWARE_V_14_7_TEMPLATE, DCP_FIRMWARE_V_26_6, DCP_FIRMWARE_V_26_6_DESKTOP, DCP_FIRMWARE_V_27_0 }; struct apple_dcp { - bool crashed, external, external_native, quiescing, main_display, panel, iomfb_template_pq; + bool crashed, external, external_native, quiescing, main_display, panel, iomfb_template_pq, vrr_enabled; int peer_check; /* what the firmware 27 paired-timing check answers */ unsigned int nr_typec_routes; enum dcp_firmware_version fw_compat; struct { int iomfb_method_profile; } hw; struct { bool valid; } mode_state; + struct { bool vrr_failed; } *desktop; struct apple_connector *connector; void *dev; }; @@ -1955,6 +1956,7 @@ def vrr(root): # processors ignore a live minimum rate and still apply it with a mode set. desktop = r""" dcp.fw_compat = DCP_FIRMWARE_V_26_6_DESKTOP; dcp.iomfb_template_pq = true; + dcp.vrr_enabled = true; dcp.hw.iomfb_method_profile = 0; dcp.mode_state.valid = true; dcp.connector = &connector; @@ -1979,7 +1981,27 @@ def vrr(root): } cases++; } + /* Adopted desktop 26.6 panel boot mode starts fixed (!dcp.vrr_enabled): + * enabling VRR_ENABLED triggers one modeset to arm adaptive sync unless vrr_failed. */ + { + __typeof__(*dcp.desktop) ds = { .vrr_failed = false }; + dcp.desktop = &ds; + dcp.main_display = true; + dcp.vrr_enabled = false; + state.crtc.enable = true; + state.no_old_crtc = false; + state.old_crtc.vrr_enabled = false; + state.crtc.vrr_enabled = true; + state.crtc.mode_changed = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && state.crtc.mode_changed); + ds.vrr_failed = true; + state.crtc.mode_changed = false; + assert(dcp_crtc_atomic_check(&crtc, &state) == 0 && !state.crtc.mode_changed); + dcp.desktop = NULL; + cases += 2; + } dcp.main_display = false; + dcp.vrr_enabled = false; dcp.iomfb_template_pq = false; dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; """ From 06bbe5bfc1396b28c557b940f6361e1999cf0bf3 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:28 +0100 Subject: [PATCH 0955/1514] dt-bindings: phy: apple,atcphy: add the T8152 fixed-USB3 PHY The two front USB-C ports of the Mac mini (2026, J873g) sit behind an on-board USB3 hub. The hub's SuperSpeed lanes are wired to the Type-C PHY of the SoC's ATC2 directly, without a Type-C mux or port controller in between, so that PHY only ever runs one fixed USB3 configuration. Describe the T8152 variant in that role, with a boolean apple,fixed-usb3 that marks such a port: the PHY runs USB3 on lane 0 from probe on, ignores mux and orientation changes and provides only the USB3 PHY of its controller. The controller's USB2 side and reset stay with the bootloader, so the T8152 PHY has no #reset-cells and no Type-C switch properties. The PHY is described by its core and pipehandler banks. On T8152 the core bank also holds the USB controller's DARTs, and the PHY's power and reset block sits behind them. It needs four power domains, listed in the order they are powered up: the ATC's USB_AON power state, its common PSD service and its COMMON_DP_0 and COMMON_DP_1 power states. The other variants keep their single power domain and #reset-cells. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/phy/apple,atcphy.yaml | 139 ++++++++++++++---- 1 file changed, 111 insertions(+), 28 deletions(-) diff --git a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml index 41ecaccc8a0aef..d75c83d05d209d 100644 --- a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml @@ -40,6 +40,13 @@ description: > DisplayPort also requires separate bootloader-provided calibration lists for that bank and the common configuration in the lpdptx region. + The T8152 variant is supported as the USB3 PHY of a fixed-USB3 port only, + see apple,fixed-usb3. It is described by its core and pipehandler banks; the + core bank also holds the USB controller's DARTs. Its power domains are the + ATC's PMGR power states and PSD service the PHY needs, in the order they are + powered up. Lane 0 is powered up and the crossbar set between the common-a + tunables and the others. + allOf: - $ref: /schemas/usb/usb-switch.yaml# - if: @@ -122,32 +129,78 @@ allOf: required: - power-domains else: - properties: - reg: - minItems: 5 - items: - - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) - - description: DisplayPort Alternate Mode PHY specific controls - - description: Type-C PHY AXI to Apple Fabric interconnect controls - - description: USB2 PHY specific controls - - description: USB3 PIPE interface controls - - description: Secondary eUSB2 PHY register bank (T8140) - - description: - Power and hibernation control of the USB controller the PHY - serves (T8140). The PHY drives that controller's reset and - takes it through hibernation for a system sleep. - reg-names: - minItems: 5 - items: - - const: core - - const: lpdptx - - const: axi2af - - const: usb2phy - - const: pipehandler - - const: usb2phy-reg - - const: pwrctl - required: - - power-domains + if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + reg: + items: + - description: + PHY core with its power and reset block, which also holds + the USB controller's DARTs + - description: USB3 PIPE interface controls + reg-names: + items: + - const: core + - const: pipehandler + power-domains: + items: + - description: The ATC's USB_AON power state + - description: The ATC's common PSD service + - description: The ATC's COMMON_DP_0 power state + - description: The ATC's COMMON_DP_1 power state + required: + - power-domains + else: + properties: + reg: + minItems: 5 + items: + - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) + - description: DisplayPort Alternate Mode PHY specific controls + - description: Type-C PHY AXI to Apple Fabric interconnect controls + - description: USB2 PHY specific controls + - description: USB3 PIPE interface controls + - description: Secondary eUSB2 PHY register bank (T8140) + - description: + Power and hibernation control of the USB controller the PHY + serves (T8140). The PHY drives that controller's reset and + takes it through hibernation for a system sleep. + reg-names: + minItems: 5 + items: + - const: core + - const: lpdptx + - const: axi2af + - const: usb2phy + - const: pipehandler + - const: usb2phy-reg + - const: pwrctl + required: + - power-domains + - if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + "#reset-cells": false + mode-switch: false + orientation-switch: false + ports: false + required: + - apple,fixed-usb3 + else: + properties: + apple,fixed-usb3: false + power-domains: + maxItems: 1 + required: + - "#reset-cells" - if: properties: compatible: @@ -234,6 +287,7 @@ allOf: - apple,t8122-atcphy - apple,t6030-atcphy - apple,t6031-atcphy + - apple,t8152-atcphy then: required: - orientation-switch @@ -275,6 +329,7 @@ properties: - const: apple,t8132-atcphy - const: apple,t8140-atcphy - const: apple,t8142-atcphy + - const: apple,t8152-atcphy reg: minItems: 1 @@ -294,7 +349,8 @@ properties: orientation-switch: true power-domains: - maxItems: 1 + minItems: 1 + maxItems: 4 phys: maxItems: 1 @@ -323,6 +379,15 @@ properties: $ref: /schemas/graph.yaml#/properties/port description: Incoming endpoint from the USB4/Thunderbolt controller. + apple,fixed-usb3: + type: boolean + description: > + T8152 only, and required there. The port's SuperSpeed lanes go straight + to a USB3 device or hub, with no Type-C mux in between, so the PHY runs + USB3 on lane 0 from probe on and ignores mux and orientation changes. It + provides only the USB3 PHY of its USB controller, which is a host, and + leaves the controller's USB2 side and reset to the bootloader. + apple,dp-alt-mode: type: boolean description: > @@ -521,7 +586,6 @@ required: - reg - reg-names - "#phy-cells" - - "#reset-cells" additionalProperties: false @@ -622,3 +686,22 @@ examples: }; }; }; + + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; + /* The bootloader adds the tunables from the ADT. */ + }; + }; From f349ba7e05114bdfdae7b1f8b6a316d20ff9735a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:45 +0100 Subject: [PATCH 0956/1514] phy: apple: atc: add T8152 for a fixed-USB3 port The J873g front ports reach their on-board USB3 hub through ATC2's Type-C PHY, wired to the hub without a Type-C mux. So far the hub ran at USB2 only: the bootloader leaves the PHY powered down and the PIPE on the controller's dummy PHY. Support the T8152 PHY in that role in the shared ATC driver. T8152 shares the T8142 generation's power and reset block, tunables and PIPE handler, with a different layout: the USB controller's DARTs sit at 0x20000 and 0x40000 of the ATC window, so the power and reset block follows at 0x60000, its lane swap is bit 1 there, and the reset the power-up releases first is a separate always-on sync reset at 0x60030. The crossbar is at 0x4c and the USB3 mode's existing setting, USB3+DP with single PMA 0x008, gives the value 0x110; there is no lane mode register to program. Describe this in the match data, with zero for the layout of the other SoCs, and leave the power-up and power-down, the tunables, the crossbar and the PIPE switch to the existing code. What remains T8152 code: - Lane 0 is powered up on its own after the common-a tunables (LFPS receivers, sleep, clamp, AHB reset) and down again with the PHY. Without it the lane registers stay in AHB reset, drop the lane tunables and the PHY never reports PIPE PhyStatus. The crossbar is set right after, before the remaining tunables, as in the T8152 sequence. - While the PIPE moves to the PHY, the BIST overrides hold lane 0's PIPE reset and power-down, stepping from P2 to P3, and the non-selected PHY override is released under them. The T8152 PIPE handler takes the lock request but does not acknowledge it: with the controller out of reset, no acknowledge came within 150 ms in either direction, while the PIPE moved to USB3 and back to the dummy PHY under the request. So T8152 changes the PIPE under the request without waiting for the acknowledge; otherwise every USB3 start fails. A fixed-USB3 port, apple,fixed-usb3, is a host by construction. Probe maps only the core and PIPE windows, the core without claiming it as it holds the DARTs, powers the PHY's power domains in the order they are listed and brings the PHY up in USB3. It registers only the USB3 PHY: no reset controller, Type-C mux or switch, as the controller's reset and USB2 side stay with the bootloader. The PIPE is routed when the controller powers the USB3 PHY on, after its core reset, which also sets the PHY up again after a power-off. If that fails the host starts with its PIPE parked, so the hub keeps USB2. The tunables come from the bootloader, which copies them from the Mac's own ADT. A loader that copies none must not take USB2 away: the PHY's consumers (the controller, and the display and Type-C drivers on the rear ports) would wait for it forever. So T8152 has optional tunables: the PHY probes without them, with common-a counted among the ones the lanes need, and refuses every mode but USB2, before a register is written. The hub then runs at USB2, as it did before this driver. The T8152 register sequence is the one of the earlier standalone driver, with which the hub enumerated at 10 Gb/s. The other SoCs keep their register accesses: the new layout fields are zero for them, and the new code runs for T8152 or a fixed-USB3 port only. KUnit cases check the T8152 crossbar, lane and power block accesses, and that a T8152 PHY without tunables refuses USB3, USB3+DP, USB4, Thunderbolt and DisplayPort without writing a register. Signed-off-by: Thomas Glanzmann --- drivers/phy/apple/atc-test.c | 139 +++++ drivers/phy/apple/atc.c | 477 ++++++++++++++++-- tools/asahi/atc-usb3-tests.py | 7 +- .../selftests/drivers/apple/atc-t8132-usb3.py | 9 +- .../selftests/drivers/gpu/apple-dcp/common.py | 12 + .../drivers/gpu/apple-dcp/dwc3/mocks.c | 8 +- .../drivers/gpu/apple-dcp/lifecycle.py | 4 +- .../selftests/drivers/gpu/apple-dcp/phy.py | 24 +- 8 files changed, 620 insertions(+), 60 deletions(-) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 09eec7f9d6185f..3edda0798b56ee 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -1450,3 +1450,142 @@ static struct kunit_suite atcphy_t8132_pm_test_suite = { }; kunit_test_suite(atcphy_t8132_pm_test_suite); + +#define ATCPHY_TEST_T8152_LANE0_UP \ + (ACIOPHY_T8152_AON_LANE_SLEEP_SMALL | ACIOPHY_T8152_AON_LANE_SLEEP_BIG | \ + ACIOPHY_T8152_AON_LANE_AHB_RESET_N) + +/* + * A T8152 fixed-USB3 PHY over zeroed memory in place of its ATC window, up to + * the sync reset. Its USB controller's DARTs sit at the T8103 offsets of the + * power and reset block: mark those words to see that nothing writes them. + */ +static struct apple_atcphy *atcphy_test_alloc_t8152(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + void *core = kunit_kzalloc(test, ATCPHY_T8152_SYNC_RESET + 4, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, core); + atcphy->regs.core = (__force void __iomem *)core; + atcphy->hw = &atcphy_hw_t8152; + atcphy->fixed_usb3 = true; + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_POWER_CTRL); + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_MISC); + + return atcphy; +} + +static void atcphy_test_t8152_untouched(struct kunit *test, struct apple_atcphy *atcphy) +{ + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_POWER_CTRL), 0xdeadbeefU); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_MISC), 0xdeadbeefU); +} + +/* USB3: lane 0 powered up, crossbar 0x110, no lane mode register, lane swap bit 1 */ +static void atcphy_test_t8152_lanes(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + writel(ATCPHY_T8152_MISC_LANE_SWAP, core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC); + + atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB3); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + + KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB3), 0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_LANE_MODE_T8103), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* Power-up and power-down go to the block at 0x60000 and the sync reset at 0x60030 */ +static void atcphy_test_t8152_power(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 stat = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_STAT; + + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + writel(ATCPHY_POWER_SLEEP_SMALL | ATCPHY_POWER_SLEEP_BIG, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_on(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_SLEEP_SMALL | + ATCPHY_POWER_SLEEP_BIG | ATCPHY_POWER_APB_RESET_N); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), ATCPHY_MISC_RESET_N); + atcphy_test_t8152_untouched(test, atcphy); + + writel(ATCPHY_TEST_T8152_LANE0_UP, core + ACIOPHY_T8152_AON_LANE0); + writel(0, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_off(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* + * The T8152 PIPE handler does not acknowledge the lock: the request is made + * and the PIPE changes under it without waiting. Its release then finds the + * acknowledge clear at once. + */ +static void atcphy_test_t8152_pipe_lock(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void *pipehandler = kunit_kzalloc(test, PIPEHANDLER_NONSELECTED_OVERRIDE + 4, + GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, pipehandler); + atcphy->regs.pipehandler = (__force void __iomem *)pipehandler; + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_lock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), + PIPEHANDLER_LOCK_EN); + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_unlock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), 0U); +} + +/* + * Without its tunables (a loader that copies none) a T8152 PHY runs USB2 + * alone: every other mode is refused before a register is written. + */ +static void atcphy_test_t8152_no_tunables(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + static const enum atcphy_mode refused[] = { + APPLE_ATCPHY_MODE_USB3, APPLE_ATCPHY_MODE_USB3_DP, APPLE_ATCPHY_MODE_USB4, + APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_DP, + }; + + atcphy->ss_tunables = false; + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + mutex_init(&atcphy->lock); + guard(mutex)(&atcphy->lock); + for (size_t i = 0; i < ARRAY_SIZE(refused); i++) + KUNIT_EXPECT_EQ(test, atcphy_configure(atcphy, refused[i]), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +static struct kunit_case atcphy_t8152_test_cases[] = { + KUNIT_CASE(atcphy_test_t8152_lanes), + KUNIT_CASE(atcphy_test_t8152_no_tunables), + KUNIT_CASE(atcphy_test_t8152_power), + KUNIT_CASE(atcphy_test_t8152_pipe_lock), + {} +}; + +static struct kunit_suite atcphy_t8152_test_suite = { + .name = "phy-apple-atc-t8152", + .test_cases = atcphy_t8152_test_cases, +}; + +kunit_test_suite(atcphy_t8152_test_suite); diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..5ad986fb009ef9 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -249,6 +249,44 @@ enum atcphy_lane_mode { #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_RESET_N_OV 0x200 #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_PWR_DOWN_OV 0x20 +/* T8152 BIST block (ACIOPHY_BIST_BLK) */ +#define ACIOPHY_T8152_BIST_CFG0 0x2400 +#define ACIOPHY_T8152_BIST_CFG0_CLOCK_EN BIT(0) +#define ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC BIT(6) + +#define ACIOPHY_T8152_BIST_CFG2 0x240c +#define ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE BIT(0) + +#define ACIOPHY_T8152_BIST_STATUS1 0x24a0 +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS BIT(6) +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2 BIT(7) + +#define ACIOPHY_T8152_BIST_OV1 0x24b0 +#define ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N BIT(0) +#define ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN GENMASK(8, 5) + +#define ACIOPHY_T8152_BIST_OV2 0x24b8 +#define ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV BIT(5) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK6 BIT(6) +#define ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV BIT(9) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK10 BIT(10) +#define ACIOPHY_T8152_BIST_OV2_LN0 \ + (ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK6 | \ + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK10) + +/* T8152 lane power controls in the always-on top block (ACIOPHY_TOP_AON_BLK) */ +#define ACIOPHY_T8152_AON_LANE0 0x1e18 +#define ACIOPHY_T8152_AON_LANE_CLAMP_EN BIT(0) +#define ACIOPHY_T8152_AON_LANE_SLEEP_SMALL BIT(1) +#define ACIOPHY_T8152_AON_LANE_SLEEP_BIG BIT(2) +#define ACIOPHY_T8152_AON_LANE_AHB_RESET_N BIT(5) + +#define ACIOPHY_T8152_AON_SLEEP_CTRL2 0x1e24 +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 BIT(12) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0 BIT(16) + #define ACIOPHY_SLEEP_CTRL 0x1b0 #define ACIOPHY_SLEEP_CTRL_TX_BIG GENMASK(1, 0) #define ACIOPHY_SLEEP_CTRL_TX_BIG_OV GENMASK(3, 2) @@ -274,6 +312,16 @@ enum atcphy_lane_mode { #define ATCPHY_MISC_RESET_N BIT(0) #define ATCPHY_MISC_LANE_SWAP BIT(2) +/* + * T8152 has the USB controller's DARTs at 0x20000 and 0x40000 of its ATC + * window, and the power and reset block (ATCPHY_CFG_BLK) follows at 0x60000. + * There the lane swap is bit 1 of 0x60008, and the reset the power-up releases + * first is bit 0 of the always-on sync reset at 0x60030. + */ +#define ATCPHY_T8152_CFG_OFFSET 0x40000 +#define ATCPHY_T8152_MISC_LANE_SWAP BIT(1) +#define ATCPHY_T8152_SYNC_RESET 0x60030 + #define ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0 0x7000 #define DP_PMA_BYTECLK_RESET BIT(0) #define DP_MAC_DIV20_CLK_SEL BIT(1) @@ -596,6 +644,7 @@ enum atcphy_generation { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8122, ATCPHY_GENERATION_T8132, + ATCPHY_GENERATION_T8152, }; enum atcphy_dp_link_rate { @@ -675,10 +724,18 @@ struct apple_atcphy; /** * struct atcphy_hw - SoC-specific PHY description - * @configure_post_tunable: Generation-specific setup after the tunables + * @configure_post_tunable: Generation-specific setup after the tunables, if any * @gen: Register programming generation - * @aciophy_lane_mode: Lane mode register offset + * @aciophy_lane_mode: Lane mode register offset, or zero to leave the lane + * mode alone (T8152 sets its lanes up through the crossbar) * @aciophy_crossbar: Crossbar register offset + * @cfg_offset: Offset of the power and reset block (ATCPHY_POWER_CTRL, + * ATCPHY_POWER_STAT, ATCPHY_MISC) from where those definitions + * place it + * @sync_reset: Register whose bit 0 is the reset the PHY's power-up releases + * first and its power-down asserts last, instead of + * ATCPHY_MISC_RESET_N, or zero + * @lane_swap: Lane swap bit in ATCPHY_MISC, or zero for ATCPHY_MISC_LANE_SWAP * @has_usb4: A USB4/Thunderbolt controller sits behind the PHY * @usb2_only: Uses the USB2 subset unless its banked SuperSpeed resources exist * @usb2phy_sig_host: Host role field mask, or zero for the original layout @@ -686,11 +743,15 @@ struct apple_atcphy; * @pipe_mux_data: PIPE data selection field mask * @has_usb2phy_reg: The PHY has the secondary eUSB2 register bank (T8140) * @has_t8140_dp: Uses the T8140 DisplayPort tunable bundle - * @optional_tunables: The bootloader may leave out the common-a tunables (this - * generation has none) and the SuperSpeed tunables; USB2 - * still works without the latter + * @optional_tunables: The bootloader may leave out the common-a tunables (T8122 + * has none) and the SuperSpeed tunables (an older loader + * copies no T8152 ones); the PHY still probes, and USB2 + * works without the latter * @park_pipe_unlocked: A stopped controller may park without a PIPE handshake * @clear_boot_hold: Release the boot PIPE hold before dummy backend selection + * @pipe_lock_unacked: The PIPE handler takes the lock request but never + * acknowledges it, so the PIPE changes under the request + * without waiting for the acknowledge * @dp_banked_tunables: DisplayPort requires separate LIOA/common calibration * @dp_t8122: DisplayPort runs the T8122 AUX, AUSPLL and lane sequences * @park_dummy_phy: Enable the dummy PIPE backend whenever the PIPE is parked on @@ -710,6 +771,9 @@ struct atcphy_hw { enum atcphy_generation gen; int aciophy_lane_mode; int aciophy_crossbar; + u32 cfg_offset; + u32 sync_reset; + u32 lane_swap; bool has_usb4; bool usb2_only; u32 usb2phy_sig_host; @@ -723,6 +787,7 @@ struct atcphy_hw { bool park_pipe_unlocked; bool park_dummy_phy; bool clear_boot_hold; + bool pipe_lock_unacked; bool restore_after_pd_off; bool idle_power_off; }; @@ -796,6 +861,11 @@ struct atcphy_cio_sleep { * behind the T6030 HDMI port; it maps only its core window * @fixed_usb2: The USB2 pairs go to a fixed hub on the USB controller, which * stays in host mode; the PHY provides USB2 from probe on + * @fixed_usb3: The SuperSpeed lanes go straight to a USB3 device or hub, with + * no Type-C mux in between (apple,fixed-usb3): the PHY runs USB3 + * on lane 0 from probe on and provides only the USB3 PHY of the + * controller, which is a host; its USB2 side and its reset are + * left to the bootloader * @typec_mode: Mode the Type-C mux last asked for; a fixed-hub port returns to * it when the PHY is brought back up after a power-off * @host_active: dwc3 has selected host mode on the USB3 PHY; a fixed-hub port @@ -910,6 +980,7 @@ struct apple_atcphy { bool dp_presets_valid[5]; bool dp_only; bool fixed_usb2; + bool fixed_usb3; enum atcphy_mode typec_mode; bool host_active; /* @@ -1276,6 +1347,65 @@ static inline u32 core_read32(struct apple_atcphy *atcphy, u32 reg) return readl(atcphy->regs.core + reg); } +/* A register of the power and reset block, see atcphy_hw.cfg_offset */ +static inline u32 atcphy_cfg(const struct apple_atcphy *atcphy, u32 reg) +{ + return reg + atcphy->hw->cfg_offset; +} + +static inline u32 atcphy_lane_swap(const struct apple_atcphy *atcphy) +{ + return atcphy->hw->lane_swap ?: ATCPHY_MISC_LANE_SWAP; +} + +/* + * T8152 keeps a lane's registers in AHB reset until the lane is powered up on + * its own, and they drop their tunables meanwhile. Power lane 0, the USB3 lane + * of a fixed-USB3 port, up after the common-a tunables: its LFPS receivers, + * then out of sleep, unclamped and out of AHB reset. Set the crossbar right + * after, before the remaining tunables, as the T8152 sequence does: 0x110 for + * USB3, i.e. USB3+DP with single PMA 0x008. atcphy_configure_lanes() writes the + * same value again later. + */ +static void atcphy_lanes_up_t8152(struct apple_atcphy *atcphy, enum atcphy_mode mode) +{ + const struct atcphy_mode_configuration *mode_cfg = atcphy_get_mode_config(atcphy, mode); + + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + + core_mask32(atcphy, atcphy->hw->aciophy_crossbar, + ACIOPHY_CROSSBAR_PROTOCOL | ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar) | + FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + mode_cfg->crossbar_dp_single_pma)); +} + +/* T8152: power lane 0 down as the PHY powers down, the reverse of the above */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *atcphy) +{ + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); +} + /* Static configuration fields already read/modified by the public DP path. */ static void j700_dp_tunables(struct apple_atcphy *atcphy) { @@ -1305,6 +1435,8 @@ static void atcphy_apply_tunables(struct apple_atcphy *atcphy, enum atcphy_mode } apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[0]); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_up_t8152(atcphy, mode); apple_tunable_apply(atcphy->regs.axi2af, atcphy->tunables.axi2af); apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[1]); @@ -1389,6 +1521,10 @@ static int atcphy_pipehandler_lock(struct apple_atcphy *atcphy) if (IS_ENABLED(CONFIG_PHY_APPLE_ATC_KUNIT_TEST)) KUNIT_STATIC_STUB_REDIRECT(atcphy_pipehandler_lock, atcphy); + if (atcphy->hw->pipe_lock_unacked) { + set32(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ, PIPEHANDLER_LOCK_EN); + return 0; + } return atcphy_pipehandler_lock_timeout(atcphy, atcphy->hw->gen == ATCPHY_GENERATION_T8132 ? 6000 : PIPEHANDLER_LOCK_ACK_TIMEOUT_US); @@ -1631,6 +1767,77 @@ static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *atc return ret; } +/* T8152: latch the BIST override registers into the USB side of the PHY */ +static void atcphy_t8152_bist_sync(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); + core_read32(atcphy, ACIOPHY_T8152_BIST_CFG0); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); +} + +static void atcphy_t8152_bist_ack(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); +} + +/* + * T8152: while the PIPE moves from the dummy PHY to this one, the BIST + * overrides hold lane 0's PIPE reset and power-down, the power-down stepping + * from P2 to P3, and the non-selected PHY override is released under them. + */ +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *atcphy) +{ + void __iomem *status = atcphy->regs.core + ACIOPHY_T8152_BIST_STATUS1; + int ret, error = 0; + u32 reg; + + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N | + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 2)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0, + ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 20000); + if (ret) { + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P2 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 3)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | ACIOPHY_T8152_BIST_OV2_LN0_UNK10, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS, + 10, 130000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: no PHY status in P3 (%#x)\n", reg); + } + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 1000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P3 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + atcphy_clear_nonselected_phy_reset(atcphy); + + core_clear32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0); + atcphy_t8152_bist_sync(atcphy); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + return error; +} + static int atcphy_configure_pipehandler_usb3_host_t8103(struct apple_atcphy *atcphy) { int ret, error = 0; @@ -1738,6 +1945,8 @@ static int atcphy_configure_pipehandler_usb3(struct apple_atcphy *atcphy, bool h ret = atcphy_configure_pipehandler_usb3_host_t8103(atcphy); else if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) ret = atcphy_configure_pipehandler_usb3_host_t8132(atcphy); + else if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + ret = atcphy_configure_pipehandler_usb3_host_t8152(atcphy); else ret = atcphy_configure_pipehandler_usb3_host_t8122(atcphy); if (ret) { @@ -2147,21 +2356,23 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode mode == APPLE_ATCPHY_MODE_DP)) return j700_dp_route(atcphy, mode == APPLE_ATCPHY_MODE_DP); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, - FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, - FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, - FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, - FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + if (atcphy->hw->aciophy_lane_mode) { + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, + FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, + FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, + FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, + FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + } core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_PROTOCOL, FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar)); if (mode_cfg->set_swap) - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); else - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_DP_SINGLE_PMA, FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, mode_cfg->crossbar_dp_single_pma)); @@ -2173,8 +2384,10 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode /* * The PMA FSM override below is for the T8103 generation. T8122 DP lanes * are started by the link rate sequence, see atcphy_dp_set_rate_t8122(). + * T8152 runs USB3 alone. */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8122) + if (atcphy->hw->gen == ATCPHY_GENERATION_T8122 || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) return 0; if (mode_cfg->dp_lane[0]) { @@ -2707,34 +2920,43 @@ static int atcphy_power_off(struct apple_atcphy *atcphy) u32 reg; int ret; - if (atcphy->hw->gen != ATCPHY_GENERATION_T8132) { + /* A fixed-USB3 port has no DisplayPort side */ + if (atcphy->hw->gen != ATCPHY_GENERATION_T8132 && !atcphy->fixed_usb3) { ret = atcphy_disable_dp_aux(atcphy); if (ret) return ret; } /* Enable all reset lines */ - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); - - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_down_t8152(atcphy); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + if (!atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); + + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_BIG), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_SMALL), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"small\"\n"); return ret; } + /* A separate sync reset is asserted last, once the block sleeps */ + if (atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy->hw->sync_reset, ATCPHY_MISC_RESET_N); + return 0; } @@ -2792,29 +3014,30 @@ static int atcphy_power_on(struct apple_atcphy *atcphy) u32 reg; int ret; - if (!atcphy->dp_only) + if (!atcphy->dp_only && !atcphy->fixed_usb3) atcphy_usb2_power_on(atcphy); - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N); + core_set32(atcphy, atcphy->hw->sync_reset ?: atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_SMALL, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"small\"\n"); return ret; } - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_BIG, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); return 0; } @@ -4170,6 +4393,10 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return -EBUSY; if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) return atcphy_configure_t8132(atcphy, mode); + /* T8152 without its tunables (an older loader): the lanes stay off, USB2 only */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->ss_tunables && + mode != APPLE_ATCPHY_MODE_OFF && mode != APPLE_ATCPHY_MODE_USB2) + return -EOPNOTSUPP; if (atcphy->pipe_pending) return -EBUSY; if (atcphy->usb_off_pending && mode != APPLE_ATCPHY_MODE_OFF) @@ -4265,7 +4492,8 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) apple_tunable_apply(atcphy->regs.lioa, atcphy->tunables.dp_lioa); apple_tunable_apply(atcphy->regs.lpdptx, atcphy->tunables.dp_common_config); } - atcphy->hw->configure_post_tunable(atcphy, mode); + if (atcphy->hw->configure_post_tunable) + atcphy->hw->configure_post_tunable(atcphy, mode); /* Setup AUX channel if DP altmode is requested */ if (atcphy_modes[mode].enable_dp_aux) { @@ -4284,7 +4512,7 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return ret; /* Take the USB3 PHY out of reset */ - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); /* * NOTE: Not what macos does, it takes the phy out of reset right before * writing to ACIOPHY_CFG0_COMMON_SMALL, does lane configuration with phy @@ -4753,7 +4981,7 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode readl(atcphy->regs.pipehandler + PIPEHANDLER_MUX_CTRL), readl(atcphy->regs.pipehandler + PIPEHANDLER_NONSELECTED_OVERRIDE), readl(atcphy->regs.pipehandler + PIPEHANDLER_T8132_USB2_CONFIG)); - if (!ret || !atcphy->fixed_usb2 || mode != PHY_MODE_USB_HOST) + if (!ret || !(atcphy->fixed_usb2 || atcphy->fixed_usb3) || mode != PHY_MODE_USB_HOST) return ret; /* @@ -4761,7 +4989,8 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode * fails, xHCI registers neither of its root hubs. Let it start, with * the PIPE parked if that works: the Type-C mux update that restores * the lanes or retries the handoff routes the PIPE, with the - * SuperSpeed port off. + * SuperSpeed port off. On a fixed-USB3 port the controller's next + * power-on of this PHY tries again. */ if (atcphy_park_pipehandler(atcphy, false)) dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); @@ -4770,6 +4999,35 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode return 0; } +/* + * A fixed-USB3 port's controller is a host by construction. It powers this + * PHY on after its core reset, before the host starts: route the PIPE to the + * USB3 PHY then, bringing the PHY up in USB3 again first if a power-off took + * it down. A failure here would stop the controller altogether, and with it + * the USB2 side of the same device, so the host then starts with its PIPE + * parked instead. + */ +static int atcphy_usb3_power_on(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + int ret = 0; + + guard(mutex)(&atcphy->lock); + atcphy->host_active = true; + if (atcphy->mode != APPLE_ATCPHY_MODE_USB3 || atcphy->mode_dirty) + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (!ret) + ret = atcphy_usb3_route(atcphy, true); + if (!ret) + return 0; + + if (atcphy_park_pipehandler(atcphy, false)) + dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); + else + dev_warn(atcphy->dev, "Host starts without USB3: %d\n", ret); + return 0; +} + static int atcphy_usb3_exit(struct phy *phy) { struct apple_atcphy *atcphy = phy_get_drvdata(phy); @@ -4817,6 +5075,17 @@ static const struct phy_ops apple_atc_usb3_phy_ops = { .set_mode = atcphy_rpm_usb3_set_mode, }; +/* + * A fixed-USB3 port also routes its PIPE at power-on. Its PHY never + * runtime-suspends (see atcphy_rpm_get()), so it needs no runtime PM wrappers. + */ +static const struct phy_ops apple_atc_fixed_usb3_phy_ops = { + .owner = THIS_MODULE, + .power_on = atcphy_usb3_power_on, + .power_off = atcphy_usb3_power_off, + .set_mode = atcphy_usb3_set_mode, +}; + /* * The T8132 PHY has no DisplayPort alternate mode: its DP PHY only exists so * that a DisplayPort tunnel can get its pixel clock, see @@ -5206,7 +5475,7 @@ static struct phy *atcphy_xlate(struct device *dev, const struct of_phandle_args default: return ERR_PTR(-ENODEV); } - /* A DisplayPort-only or USB2-only instance omits the other PHYs. */ + /* A DisplayPort-, USB2- or USB3-only instance omits the other PHYs. */ return phy ?: ERR_PTR(-ENODEV); } @@ -5217,18 +5486,20 @@ static int atcphy_probe_phy(struct apple_atcphy *atcphy) const struct phy_ops *ops; } phys[] = { { &atcphy->phys.usb2, &apple_atc_usb2_phy_ops }, - { &atcphy->phys.usb3, &apple_atc_usb3_phy_ops }, + { &atcphy->phys.usb3, atcphy->fixed_usb3 ? &apple_atc_fixed_usb3_phy_ops : + &apple_atc_usb3_phy_ops }, { &atcphy->phys.dp, &apple_atc_dp_phy_ops }, }; /* * A T8132 PHY with its USB3/USB4 banks gets a DP PHY for DisplayPort * tunnels only (see atcphy_dpphy_set_mode_t8132()); creating it does - * not touch the hardware. + * not touch the hardware. A fixed-USB3 PHY gets its USB3 PHY only. */ for (int i = 0; i < ARRAY_SIZE(phys); i++) { if ((atcphy->dp_only && phys[i].phy != &atcphy->phys.dp) || - (atcphy_usb2_only(atcphy) && i != 0)) + (atcphy_usb2_only(atcphy) && i != 0) || + (atcphy->fixed_usb3 && phys[i].phy != &atcphy->phys.usb3)) continue; *phys[i].phy = devm_phy_create(atcphy->dev, NULL, phys[i].ops); if (IS_ERR(*phys[i].phy)) @@ -6412,6 +6683,14 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) bool lane_dp = tunables[i].tunable == &atcphy->tunables.lane_dp[0] || tunables[i].tunable == &atcphy->tunables.lane_dp[1]; + /* a fixed-USB3 port runs USB3 on lane 0 alone and has no axi2af window */ + if (atcphy->fixed_usb3 && + tunables[i].tunable != &atcphy->tunables.common[0] && + tunables[i].tunable != &atcphy->tunables.common[1] && + tunables[i].tunable != &atcphy->tunables.lane_usb3[0]) { + *tunables[i].tunable = NULL; + continue; + } if (!atcphy->hw->has_usb4 && (tunables[i].tunable == &atcphy->tunables.lane_usb4[0] || tunables[i].tunable == &atcphy->tunables.lane_usb4[1])) { @@ -6450,8 +6729,9 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) tunables[i].dt_name, PTR_ERR(tunable)); return PTR_ERR(tunable); } - /* The common-a tunables do not exist on this generation */ - if (tunables[i].tunable != &atcphy->tunables.common[0]) + /* T8122 has no common-a tunables; T8152's calibrate the lanes too */ + if (tunables[i].tunable != &atcphy->tunables.common[0] || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) ss_missing = true; if (tunables[i].tunable == &atcphy->tunables.axi2af || tunables[i].tunable == &atcphy->tunables.common[1]) @@ -6516,6 +6796,28 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph struct resource *res; void __iomem *addr; + /* + * A fixed-USB3 PHY has its core and PIPE windows only. On T8152 the + * core window also holds the USB controller's DARTs, so it is mapped + * without claiming it. + */ + if (atcphy->fixed_usb3) { + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "core"); + if (!res) + return dev_err_probe(atcphy->dev, -EINVAL, "Missing core regs\n"); + atcphy->regs.core = devm_ioremap(&pdev->dev, res->start, resource_size(res)); + if (!atcphy->regs.core) + return -ENOMEM; + atcphy->res.core = res; + + addr = devm_platform_ioremap_resource_byname(pdev, "pipehandler"); + if (IS_ERR(addr)) + return dev_err_probe(atcphy->dev, PTR_ERR(addr), + "Unable to map pipehandler regs\n"); + atcphy->regs.pipehandler = addr; + return 0; + } + if (atcphy->hw->gen == ATCPHY_GENERATION_T8132 && platform_get_resource_byname(pdev, IORESOURCE_MEM, "common-config")) { static const char * const names[] = { @@ -6743,6 +7045,34 @@ static int atcphy_probe_finalize_dp_only(struct apple_atcphy *atcphy) return 0; } +/* + * A fixed-USB3 port: the bootloader hands its controller over running, with + * the controller's reset and its USB2 side its own, and no Type-C mux sits in + * front of the lanes, so there is no reset controller, mux or switch to + * register. Take the PHY from the state the bootloader left it in to USB3; the + * PIPE follows when the controller powers its USB3 PHY on, which also tries + * again if this fails, see atcphy_usb3_power_on(). + */ +static int atcphy_probe_finalize_fixed_usb3(struct apple_atcphy *atcphy) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + + atcphy_power_off(atcphy); + atcphy_setup_pipehandler(atcphy); + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (ret) + dev_warn(atcphy->dev, "USB3 not up yet: %d\n", ret); + + ret = atcphy_probe_phy(atcphy); + if (ret) { + atcphy_configure(atcphy, APPLE_ATCPHY_MODE_OFF); + return dev_err_probe(atcphy->dev, ret, "Probing phy failed"); + } + return 0; +} + static int atcphy_probe_finalize(struct apple_atcphy *atcphy) { int ret; @@ -6751,6 +7081,8 @@ static int atcphy_probe_finalize(struct apple_atcphy *atcphy) if (atcphy->dp_only) return atcphy_probe_finalize_dp_only(atcphy); + if (atcphy->fixed_usb3) + return atcphy_probe_finalize_fixed_usb3(atcphy); /* Reset dwc3 on probe, let dwc3 (consumer) deassert it */ _atcphy_dwc3_reset_assert(atcphy); @@ -6882,6 +7214,25 @@ static bool atcphy_has_t8103_usb3_workaround(const struct atcphy_hw *hw, of_device_is_compatible(root, "apple,t8103"); } +/* + * The driver core attaches a single power domain. A fixed-USB3 PHY may list + * several, like T8152's ATC power states and PSD service: hold them all on + * while it is bound, powered up in the order they are listed. + */ +static int atcphy_probe_power_domains(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_attach_data pd_data = { .pd_flags = PD_FLAG_DEV_LINK_ON }; + struct dev_pm_domain_list *pd_list; + int ret; + + if (!atcphy->fixed_usb3 || atcphy->dev->pm_domain) + return 0; + ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &pd_list); + if (ret < 0) + return dev_err_probe(atcphy->dev, ret, "Failed to attach power domains\n"); + return 0; +} + static void atcphy_sleep_finish_work(struct work_struct *work); static int atcphy_probe(struct platform_device *pdev) @@ -6904,6 +7255,10 @@ static int atcphy_probe(struct platform_device *pdev) atcphy->np = dev->of_node; atcphy->t8132_dp_alt = atcphy->hw->gen == ATCPHY_GENERATION_T8132 && of_property_read_bool(dev->of_node, "apple,dp-alt-mode"); + atcphy->fixed_usb3 = of_property_read_bool(dev->of_node, "apple,fixed-usb3"); + /* T8152 is supported on a fixed-USB3 port only */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->fixed_usb3) + return dev_err_probe(dev, -ENODEV, "Only a fixed-USB3 port is supported\n"); apple_atc_tunnel_wiring(atcphy); mutex_init(&atcphy->lock); platform_set_drvdata(pdev, atcphy); @@ -6912,6 +7267,9 @@ static int atcphy_probe(struct platform_device *pdev) if (ret) return ret; ret = atcphy_load_tunables(atcphy); + if (ret) + return ret; + ret = atcphy_probe_power_domains(atcphy); if (ret) return ret; @@ -7983,12 +8341,43 @@ static const struct atcphy_hw atcphy_hw_t8142 = { .clear_boot_hold = true, }; +/* + * T8152 as the USB3 PHY of a fixed-USB3 port: no USB4, DisplayPort or lane + * mode register and nothing to wake after the tunables. Its power domains are + * not followed: the controller's power-off and power-on of the PHY, as around + * a system sleep, take it down and up again. + */ +static const struct atcphy_hw atcphy_hw_t8152 = { + .gen = ATCPHY_GENERATION_T8152, + .aciophy_crossbar = ACIOPHY_CROSSBAR_T8103, + .cfg_offset = ATCPHY_T8152_CFG_OFFSET, + .sync_reset = ATCPHY_T8152_SYNC_RESET, + .lane_swap = ATCPHY_T8152_MISC_LANE_SWAP, + .pipe_mux_clk = PIPEHANDLER_MUX_CTRL_CLK_T8142, + .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8142, + .park_dummy_phy = true, + .clear_boot_hold = true, + /* + * The bootloader copies the tunables from the Mac's own ADT. Without + * them (an older loader) the PHY still probes, so that its consumers do + * not wait for it, and refuses every mode but USB2. + */ + .optional_tunables = true, + /* + * With the controller out of reset, the J873g front port's PIPE handler + * left the lock unacknowledged for 150 ms in both directions, while the + * PIPE moved to USB3 and back to the dummy PHY under the request. + */ + .pipe_lock_unacked = true, +}; + static const struct of_device_id atcphy_match[] = { { .compatible = "apple,t8103-atcphy", .data = &atcphy_hw_t8103 }, { .compatible = "apple,t8122-atcphy", .data = &atcphy_hw_t8122 }, { .compatible = "apple,t8132-atcphy", .data = &atcphy_hw_t8132 }, { .compatible = "apple,t8142-atcphy", .data = &atcphy_hw_t8142 }, { .compatible = "apple,t8140-atcphy", .data = &atcphy_hw_t8140 }, + { .compatible = "apple,t8152-atcphy", .data = &atcphy_hw_t8152 }, {}, }; MODULE_DEVICE_TABLE(of, atcphy_match); diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..d9f9aacb4d38f7 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -78,7 +78,7 @@ def block(source, marker): STUBS = r''' struct atcphy_hw { enum atcphy_generation gen; bool has_t8140_dp, dp_t8122, has_usb4, park_pipe_unlocked, park_dummy_phy, usb2_only; - bool clear_boot_hold, dp_banked_tunables; }; + bool clear_boot_hold, dp_banked_tunables, pipe_lock_unacked; }; struct device_node { const char *const *compatible; unsigned int count; }; static bool of_device_is_compatible(const struct device_node *root, const char *compatible) { if (!root) return false; @@ -98,7 +98,7 @@ def block(source, marker): enum atcphy_pipehandler_state pipe_state; enum atcphy_mode typec_mode; bool pipe_pending, t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround, mode_dirty, usb_off_pending; - bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, t8140_dp_tunables, dp_tunables; + bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, fixed_usb3, t8140_dp_tunables, dp_tunables; /* T8132 ownership is tested without entering its lane-setup backend. */ bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; struct { void *usb3_dp; } tunables; @@ -185,6 +185,9 @@ def block(source, marker): static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *a) { (void)a; assert(!"T8132 PIPE setup reached"); return -EINVAL; } +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *a) { + (void)a; assert(!"T8152 PIPE setup reached"); return -EINVAL; +} static void atcphy_usb2_power_on(struct apple_atcphy *a) { (void)a; assert(!"USB2-only power restore reached"); } diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index 7eeb90baf4385d..ed02e7f33b5627 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -92,7 +92,8 @@ def main(): ''' declarations = r''' struct apple_tunable { unsigned id; }; -struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; }; +struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; + u32 cfg_offset, sync_reset; }; enum suspend_state { PM_SUSPEND_TO_IDLE = 1, PM_SUSPEND_MEM = 3 }; static enum suspend_state pm_suspend_target_state; static bool rpm_suspended; @@ -106,7 +107,7 @@ def main(): bool t8132_ss, t8132_common_owned, t8132_suspended, t8132_failed, host_active; bool ss_tunables, mode_dirty, pipe_pending, swap_lanes; bool cio_tunables, t8132_dp_alt, fixed_usb2, hibernated, pd_was_off, idle_rpm; - bool t8103_dummy_pending, t8103_usb3_workaround; + bool t8103_dummy_pending, t8103_usb3_workaround, fixed_usb3; unsigned tunnel_users; struct { bool prepared, changed, restored; } cio_sleep; int mode, pipe_state, lock; @@ -122,6 +123,8 @@ def main(): struct device { struct apple_atcphy *atc; }; static struct apple_atcphy *dev_get_drvdata(struct device *d) { return d->atc; } static struct apple_atcphy *phy_get_drvdata(struct phy *p) { return p->atc; } +/* T8152 only: these rows run T8132, which never reaches it. */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *a) { (void)a; assert(0); } static u32 core[0x24000/4], usb2[0x4000/4], pipe_regs[0x4000/4]; static unsigned tunes[16], tune_count, reset_releases, bist_phase, writes, core_reads; static unsigned stall_power, stall_bist, expected_tunes, stall_sleep; @@ -215,7 +218,7 @@ def main(): } ''' names = ["atcphy_mode_is_cio", "atcphy_usb2_sig_host", "atcphy_t8132_dp_on", - "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", + "atcphy_cfg", "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", "atcphy_t8132_cold", "atcphy_t8132_common_start", "atcphy_t8132_phy_stop", "atcphy_t8132_full_stop", "atcphy_configure_t8132", "atcphy_usb2_set_mode", "atcphy_t8132_bist_pulse", diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py index 980a7a8773b97f..aee2f68cc7bed0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py @@ -194,6 +194,18 @@ def atc_cio_helpers(source): return result +def atc_cfg_helpers(source): + """Where the power and reset block sits and which bit swaps the lanes, both of + which T8152 moves; the power-up, power-down and lane functions call these. + + Marked unused, as a unit may extract only some of their callers. Older + sources have neither: ''. + """ + return ''.join(atc_function(source, name).replace( + 'static inline ', 'static inline __attribute__((unused)) ', 1) + for name in ('atcphy_cfg', 'atcphy_lane_swap')) + + def atc_restore_helpers(source): """What atcphy_restore_after_pd_off() needs beyond the parking helpers. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index cc3197c1b738a1..a2d8076ac8b3dc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -25,7 +25,7 @@ struct apple_atcphy { bool aux, pll; unsigned int pairs, rate; } dp_t8122; - bool fixed_usb2, host_active, mode_dirty, ss_tunables, dp_tunables, + bool fixed_usb2, fixed_usb3, host_active, mode_dirty, ss_tunables, dp_tunables, aux_power_requested; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; @@ -252,11 +252,15 @@ static void atcphy_restore_after_pd_off(struct apple_atcphy *p); static int atcphy_power_off(struct apple_atcphy *p); static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } /* Model the USB2 power-on boundary's running state. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..2fc3385d1df6e0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -3,7 +3,7 @@ """Actual disconnect authority, DWC3 teardown and firmware resource admission.""" from pathlib import Path import re -from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers +from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers, atc_cfg_helpers def disconnect(root): # Copyright 2026 Ryan Murray @@ -1182,7 +1182,7 @@ def fn(n, name): names = {n: tuple(name for name in group if re.search(r'^(?:static [^\n]*\b|(?:int|void) )' + name + r'\(', files[n], re.M)) for n, group in names.items()} context = (fn('atc', 'core_read32') + '\n' + fn('atc', 'atcphy_get_mode_config') + '\n' + fn('atc', 'j700_field_update') + '\n' + files['dp'][files['dp'].index('/* Masks are the union'):files['dp'].index('/* Retry only the idle operations')]) - functions = atc_cio_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) + functions = atc_cio_helpers(files['atc']) + atc_cfg_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) definitions = [] lines = iter(files['atc'].splitlines()) for line in lines: diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 26c0f62dabb254..45c8275bf462ee 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -5,7 +5,7 @@ import re from common import (block, source_defines, atc_mux_without_pm, ATC_POST_TUNABLE, atc_function, ATC_SPLIT, ATC_T8103_LIVE, atc_restore_helpers, atc_common_state_helpers, - atc_cio_helpers) + atc_cio_helpers, atc_cfg_helpers) def parking(root): @@ -46,7 +46,7 @@ def function(source, name): struct reset_controller_dev rcdev; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -67,6 +67,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -160,11 +161,15 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } ''') @@ -1948,7 +1953,7 @@ def function(name): struct { unsigned char *core, *pipehandler; } regs; void *dev; int lock; - bool fixed_usb2, host_active, ss_tunables, dp_tunables, mode_dirty; + bool fixed_usb2, fixed_usb3, host_active, ss_tunables, dp_tunables, mode_dirty; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; u32 dp_usb_context[2][27]; @@ -1993,11 +1998,13 @@ def function(name): static void __attribute__((unused)) atcphy_restore_after_pd_off(struct apple_atcphy *p) { assert(!p->pd_was_off); } static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } ''') for name in ('core_read32', 'atcphy_get_mode_config'): @@ -2348,7 +2355,7 @@ def function(source, name): struct { unsigned char *core, *lpdptx, *lioa; } regs; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -2364,6 +2371,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -2424,11 +2432,13 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } static int atcphy_park_pipehandler(struct apple_atcphy *p, bool keep_dp) From cc820203214ec9232f03c3f8a81948f7dc980d8c Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:52 +0100 Subject: [PATCH 0957/1514] arm64: dts: apple: j873: USB3 on the front ports The two front USB-C ports sit behind an on-board VL822 hub on usb-drd2. The hub's USB2 side is on the controller's eUSB2 PHY, which the loader sets up, and its USB3 side on ATC2's Type-C PHY, wired directly without a Type-C mux. So far the controller was limited to high speed and the hub ran at USB2 only. Describe ATC2's PHY as an apple,t8152-atcphy with apple,fixed-usb3, hand it to usb-drd2 as its USB3 PHY and drop the controller's high-speed limit. Nothing changes for usb-drd1 (the back-left port). The PHY's power domains are ATC2's USB_AON, COMMON_DP_0 and COMMON_DP_1 PMGR power states, in a new node for the ATCs' block of PMGR states at 0x308290000, and its common domain, PSD service 57 (ADT clock-gates 57). The T8152 USB3 bring-up runs the power states without automatic power management, so they are marked apple,no-auto-pm. The PHY's tunables are the groups of the ADT's atc-phy2 node that apply to USB3 on lane 0: the common and PLL defaults as common-a, the fabric, PLL and USBC0 groups as common-b and the lane 0 groups as lane0-usb. Some of them differ between the four ATCs of the same Mac, so they are calibration: the bootloader copies them from the Mac's own ADT, through the atcphy2 alias (aurora-silicon/aura#498). With a loader that copies none, the PHY runs USB2 only. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 142 +++++++++++++----- 1 file changed, 106 insertions(+), 36 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 924df52e3622bb..08c65ebaec42bb 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -1,15 +1,18 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 - * (front ports via the on-board hub). + * J873g USB host bring-up: usb-drd1 (back-left port, USB2) and usb-drd2 + * (front ports via the on-board hub, USB2 and USB3). * The loader powers the controllers and sets up the USB2 side of their ATC - * PHYs for host mode before Linux starts (there is no T8152 ATC PHY or Type-C + * PHYs for host mode before Linux starts (there is no T8152 USB2 PHY or Type-C * support yet). * The controllers are described by their DWC3 core region, as hosts behind * their two DARTs (apple,t8152-dwc3); their PHY reset, and on the Type-C port * the role switch, exist but are left to the loader. + * usb-drd2's hub is wired to ATC2's PHY without a Type-C mux, so Linux brings + * that PHY up in USB3 mode (atc2_phy). * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2 (on atc-phy1 and - * atc-phy2) and the pmgr devices ATC1_USB_AON/USB and ATC2_USB_AON/USB. + * atc-phy2), atc-phy2 and the pmgr devices ATC1_USB_AON/USB, ATC2_USB_AON/USB + * and ATC2_COMMON_DP_0/1. * * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists @@ -19,6 +22,8 @@ * own window only, and describe instance 1 as a node of its own. */ +#include + &dwc3_1_dart { reg = <0x4 0x0b020000 0x0 0xc000>; power-domains = <&ps_atc1_usb>; @@ -32,16 +37,53 @@ }; / { + aliases { + /* aura copies the ATC PHY's tunables from ADT atc-phy2 here. */ + atcphy2 = &atc2_phy; + }; + soc { + dwc3_1_dart_1: iommu@40b040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc1_usb>; + }; + + usb1: usb@40a430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x4 0x0a430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; + power-domains = <&ps_atc1_usb>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + + dwc3_2_dart_1: iommu@383040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc2_usb>; + }; + /* - * The ATCs' PMGR power states (ADT pmgr devices ATCn_USB_AON and - * ATCn_USB from 0x308290100, 0x40 apart per ATC). The ADT gives - * usb-drd1/2 service-gates 175/176, but those PSD service blocks - * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. + * The ATCs' PMGR power states (ADT pmgr devices ATCn_COMMON_DP_0/1 + * from 0x308290000 and ATCn_USB_AON/USB from 0x308290100, 0x40 + * apart per ATC). The T8152 USB bring-up runs them without + * automatic power management. * - * The loader leaves them on; they hold the controllers' reset and - * the USB2 PHY setup it did, which Linux cannot redo yet. So they - * stay on, without automatic power management. + * ATCn_USB is the controller's state. The ADT also gives + * usb-drd1/2 service-gates 175/176, but those PSD service blocks + * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. The + * loader leaves ATCn_USB and ATCn_USB_AON on; they hold the + * controllers' reset and the USB2 PHY setup it did, which Linux + * cannot redo yet, so they stay on. ATC2_COMMON_DP_0/1 are what + * ATC2's PHY needs besides. */ pmgr_atc: power-management@308290000 { compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", @@ -50,6 +92,26 @@ #size-cells = <1>; reg = <0x3 0x08290000 0x0 0x1000>; + ps_atc2_common_dp_0: power-controller@80 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc2_common_dp_1: power-controller@a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xa0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_1"; + apple,no-auto-pm; + }; + ps_atc1_usb_aon: power-controller@140 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -73,6 +135,11 @@ apple,always-on; }; + /* + * Kept on: it holds the USB controller's reset and the + * PIPE handler state the loader set up. Switched off, the + * controller stays in reset until the next boot. + */ ps_atc2_usb_aon: power-controller@180 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -97,32 +164,34 @@ }; }; - dwc3_1_dart_1: iommu@40b040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x4 0x0b040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - power-domains = <&ps_atc1_usb>; + /* ATC2's common domain: PSD service 57 (ADT atc-phy2 clock-gates). */ + ps_atc2_common: power-controller@303a13900 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13900 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc2_common"; }; - usb1: usb@40a430000 { - compatible = "apple,t8152-dwc3"; - reg = <0x4 0x0a430000 0x0 0xcd00>; - interrupts = ; - dr_mode = "host"; - maximum-speed = "high-speed"; - iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; - power-domains = <&ps_atc1_usb>; - snps,dis_u2_susphy_quirk; - snps,dis_u3_susphy_quirk; - }; - - dwc3_2_dart_1: iommu@383040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x3 0x83040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - power-domains = <&ps_atc2_usb>; + /* + * ADT atc-phy2 as usb-drd2's USB3 PHY: the hub is wired to its + * lanes directly. The power domains are listed in the order the + * PHY needs them powered up. Its tunables are the atc-phy2 + * tunable_* groups that apply to USB3 on lane 0, applied as + * common-a before lane 0 is powered up and the crossbar set, then + * common-b and lane0-usb. Some of them differ between the four + * ATCs of the same Mac (calibration), so the bootloader copies + * them from the Mac's own ADT, through the atcphy2 alias. Without + * them the PHY runs USB2 only. + */ + atc2_phy: phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; }; /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ @@ -131,7 +200,8 @@ reg = <0x3 0x82430000 0x0 0xcd00>; interrupts = ; dr_mode = "host"; - maximum-speed = "high-speed"; + phys = <&atc2_phy PHY_TYPE_USB3>; + phy-names = "usb3-phy"; iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; power-domains = <&ps_atc2_usb>; snps,dis_u2_susphy_quirk; From b620188b20aee3df2e66943ba39a2d17db874125 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:28 +0100 Subject: [PATCH 0958/1514] dt-bindings: phy: apple,atcphy: add the T8152 fixed-USB3 PHY The two front USB-C ports of the Mac mini (2026, J873g) sit behind an on-board USB3 hub. The hub's SuperSpeed lanes are wired to the Type-C PHY of the SoC's ATC2 directly, without a Type-C mux or port controller in between, so that PHY only ever runs one fixed USB3 configuration. Describe the T8152 variant in that role, with a boolean apple,fixed-usb3 that marks such a port: the PHY runs USB3 on lane 0 from probe on, ignores mux and orientation changes and provides only the USB3 PHY of its controller. The controller's USB2 side and reset stay with the bootloader, so the T8152 PHY has no #reset-cells and no Type-C switch properties. The PHY is described by its core and pipehandler banks. On T8152 the core bank also holds the USB controller's DARTs, and the PHY's power and reset block sits behind them. It needs four power domains, listed in the order they are powered up: the ATC's USB_AON power state, its common PSD service and its COMMON_DP_0 and COMMON_DP_1 power states. The other variants keep their single power domain and #reset-cells. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/phy/apple,atcphy.yaml | 139 ++++++++++++++---- 1 file changed, 111 insertions(+), 28 deletions(-) diff --git a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml index 41ecaccc8a0aef..d75c83d05d209d 100644 --- a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml @@ -40,6 +40,13 @@ description: > DisplayPort also requires separate bootloader-provided calibration lists for that bank and the common configuration in the lpdptx region. + The T8152 variant is supported as the USB3 PHY of a fixed-USB3 port only, + see apple,fixed-usb3. It is described by its core and pipehandler banks; the + core bank also holds the USB controller's DARTs. Its power domains are the + ATC's PMGR power states and PSD service the PHY needs, in the order they are + powered up. Lane 0 is powered up and the crossbar set between the common-a + tunables and the others. + allOf: - $ref: /schemas/usb/usb-switch.yaml# - if: @@ -122,32 +129,78 @@ allOf: required: - power-domains else: - properties: - reg: - minItems: 5 - items: - - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) - - description: DisplayPort Alternate Mode PHY specific controls - - description: Type-C PHY AXI to Apple Fabric interconnect controls - - description: USB2 PHY specific controls - - description: USB3 PIPE interface controls - - description: Secondary eUSB2 PHY register bank (T8140) - - description: - Power and hibernation control of the USB controller the PHY - serves (T8140). The PHY drives that controller's reset and - takes it through hibernation for a system sleep. - reg-names: - minItems: 5 - items: - - const: core - - const: lpdptx - - const: axi2af - - const: usb2phy - - const: pipehandler - - const: usb2phy-reg - - const: pwrctl - required: - - power-domains + if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + reg: + items: + - description: + PHY core with its power and reset block, which also holds + the USB controller's DARTs + - description: USB3 PIPE interface controls + reg-names: + items: + - const: core + - const: pipehandler + power-domains: + items: + - description: The ATC's USB_AON power state + - description: The ATC's common PSD service + - description: The ATC's COMMON_DP_0 power state + - description: The ATC's COMMON_DP_1 power state + required: + - power-domains + else: + properties: + reg: + minItems: 5 + items: + - description: Common controls for all PHYs (USB2/3/4, DisplayPort, TBT) + - description: DisplayPort Alternate Mode PHY specific controls + - description: Type-C PHY AXI to Apple Fabric interconnect controls + - description: USB2 PHY specific controls + - description: USB3 PIPE interface controls + - description: Secondary eUSB2 PHY register bank (T8140) + - description: + Power and hibernation control of the USB controller the PHY + serves (T8140). The PHY drives that controller's reset and + takes it through hibernation for a system sleep. + reg-names: + minItems: 5 + items: + - const: core + - const: lpdptx + - const: axi2af + - const: usb2phy + - const: pipehandler + - const: usb2phy-reg + - const: pwrctl + required: + - power-domains + - if: + properties: + compatible: + contains: + const: apple,t8152-atcphy + then: + properties: + "#reset-cells": false + mode-switch: false + orientation-switch: false + ports: false + required: + - apple,fixed-usb3 + else: + properties: + apple,fixed-usb3: false + power-domains: + maxItems: 1 + required: + - "#reset-cells" - if: properties: compatible: @@ -234,6 +287,7 @@ allOf: - apple,t8122-atcphy - apple,t6030-atcphy - apple,t6031-atcphy + - apple,t8152-atcphy then: required: - orientation-switch @@ -275,6 +329,7 @@ properties: - const: apple,t8132-atcphy - const: apple,t8140-atcphy - const: apple,t8142-atcphy + - const: apple,t8152-atcphy reg: minItems: 1 @@ -294,7 +349,8 @@ properties: orientation-switch: true power-domains: - maxItems: 1 + minItems: 1 + maxItems: 4 phys: maxItems: 1 @@ -323,6 +379,15 @@ properties: $ref: /schemas/graph.yaml#/properties/port description: Incoming endpoint from the USB4/Thunderbolt controller. + apple,fixed-usb3: + type: boolean + description: > + T8152 only, and required there. The port's SuperSpeed lanes go straight + to a USB3 device or hub, with no Type-C mux in between, so the PHY runs + USB3 on lane 0 from probe on and ignores mux and orientation changes. It + provides only the USB3 PHY of its USB controller, which is a host, and + leaves the controller's USB2 side and reset to the bootloader. + apple,dp-alt-mode: type: boolean description: > @@ -521,7 +586,6 @@ required: - reg - reg-names - "#phy-cells" - - "#reset-cells" additionalProperties: false @@ -622,3 +686,22 @@ examples: }; }; }; + + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; + /* The bootloader adds the tunables from the ADT. */ + }; + }; From 2273dcfaa2ff696eacbbcf539eb0f72b5eb285d0 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:45 +0100 Subject: [PATCH 0959/1514] phy: apple: atc: add T8152 for a fixed-USB3 port The J873g front ports reach their on-board USB3 hub through ATC2's Type-C PHY, wired to the hub without a Type-C mux. So far the hub ran at USB2 only: the bootloader leaves the PHY powered down and the PIPE on the controller's dummy PHY. Support the T8152 PHY in that role in the shared ATC driver. T8152 shares the T8142 generation's power and reset block, tunables and PIPE handler, with a different layout: the USB controller's DARTs sit at 0x20000 and 0x40000 of the ATC window, so the power and reset block follows at 0x60000, its lane swap is bit 1 there, and the reset the power-up releases first is a separate always-on sync reset at 0x60030. The crossbar is at 0x4c and the USB3 mode's existing setting, USB3+DP with single PMA 0x008, gives the value 0x110; there is no lane mode register to program. Describe this in the match data, with zero for the layout of the other SoCs, and leave the power-up and power-down, the tunables, the crossbar and the PIPE switch to the existing code. What remains T8152 code: - Lane 0 is powered up on its own after the common-a tunables (LFPS receivers, sleep, clamp, AHB reset) and down again with the PHY. Without it the lane registers stay in AHB reset, drop the lane tunables and the PHY never reports PIPE PhyStatus. The crossbar is set right after, before the remaining tunables, as in the T8152 sequence. - While the PIPE moves to the PHY, the BIST overrides hold lane 0's PIPE reset and power-down, stepping from P2 to P3, and the non-selected PHY override is released under them. The T8152 PIPE handler takes the lock request but does not acknowledge it: with the controller out of reset, no acknowledge came within 150 ms in either direction, while the PIPE moved to USB3 and back to the dummy PHY under the request. So T8152 changes the PIPE under the request without waiting for the acknowledge; otherwise every USB3 start fails. A fixed-USB3 port, apple,fixed-usb3, is a host by construction. Probe maps only the core and PIPE windows, the core without claiming it as it holds the DARTs, powers the PHY's power domains in the order they are listed and brings the PHY up in USB3. It registers only the USB3 PHY: no reset controller, Type-C mux or switch, as the controller's reset and USB2 side stay with the bootloader. The PIPE is routed when the controller powers the USB3 PHY on, after its core reset, which also sets the PHY up again after a power-off. If that fails the host starts with its PIPE parked, so the hub keeps USB2. The tunables come from the bootloader, which copies them from the Mac's own ADT. A loader that copies none must not take USB2 away: the PHY's consumers (the controller, and the display and Type-C drivers on the rear ports) would wait for it forever. So T8152 has optional tunables: the PHY probes without them, with common-a counted among the ones the lanes need, and refuses every mode but USB2, before a register is written. The hub then runs at USB2, as it did before this driver. The T8152 register sequence is the one of the earlier standalone driver, with which the hub enumerated at 10 Gb/s. The other SoCs keep their register accesses: the new layout fields are zero for them, and the new code runs for T8152 or a fixed-USB3 port only. KUnit cases check the T8152 crossbar, lane and power block accesses, and that a T8152 PHY without tunables refuses USB3, USB3+DP, USB4, Thunderbolt and DisplayPort without writing a register. Signed-off-by: Thomas Glanzmann --- drivers/phy/apple/atc-test.c | 139 +++++ drivers/phy/apple/atc.c | 477 ++++++++++++++++-- tools/asahi/atc-usb3-tests.py | 7 +- .../selftests/drivers/apple/atc-t8132-usb3.py | 9 +- .../selftests/drivers/gpu/apple-dcp/common.py | 12 + .../drivers/gpu/apple-dcp/dwc3/mocks.c | 8 +- .../drivers/gpu/apple-dcp/lifecycle.py | 4 +- .../selftests/drivers/gpu/apple-dcp/phy.py | 24 +- 8 files changed, 620 insertions(+), 60 deletions(-) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 09eec7f9d6185f..3edda0798b56ee 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -1450,3 +1450,142 @@ static struct kunit_suite atcphy_t8132_pm_test_suite = { }; kunit_test_suite(atcphy_t8132_pm_test_suite); + +#define ATCPHY_TEST_T8152_LANE0_UP \ + (ACIOPHY_T8152_AON_LANE_SLEEP_SMALL | ACIOPHY_T8152_AON_LANE_SLEEP_BIG | \ + ACIOPHY_T8152_AON_LANE_AHB_RESET_N) + +/* + * A T8152 fixed-USB3 PHY over zeroed memory in place of its ATC window, up to + * the sync reset. Its USB controller's DARTs sit at the T8103 offsets of the + * power and reset block: mark those words to see that nothing writes them. + */ +static struct apple_atcphy *atcphy_test_alloc_t8152(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_dev(test, false); + void *core = kunit_kzalloc(test, ATCPHY_T8152_SYNC_RESET + 4, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, core); + atcphy->regs.core = (__force void __iomem *)core; + atcphy->hw = &atcphy_hw_t8152; + atcphy->fixed_usb3 = true; + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_POWER_CTRL); + writel(0xdeadbeef, atcphy->regs.core + ATCPHY_MISC); + + return atcphy; +} + +static void atcphy_test_t8152_untouched(struct kunit *test, struct apple_atcphy *atcphy) +{ + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_POWER_CTRL), 0xdeadbeefU); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.core + ATCPHY_MISC), 0xdeadbeefU); +} + +/* USB3: lane 0 powered up, crossbar 0x110, no lane mode register, lane swap bit 1 */ +static void atcphy_test_t8152_lanes(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + writel(ATCPHY_T8152_MISC_LANE_SWAP, core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC); + + atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB3); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + + KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB3), 0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_LANE_MODE_T8103), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* Power-up and power-down go to the block at 0x60000 and the sync reset at 0x60030 */ +static void atcphy_test_t8152_power(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 stat = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_STAT; + + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + writel(ATCPHY_POWER_SLEEP_SMALL | ATCPHY_POWER_SLEEP_BIG, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_on(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_SLEEP_SMALL | + ATCPHY_POWER_SLEEP_BIG | ATCPHY_POWER_APB_RESET_N); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), ATCPHY_MISC_RESET_N); + atcphy_test_t8152_untouched(test, atcphy); + + writel(ATCPHY_TEST_T8152_LANE0_UP, core + ACIOPHY_T8152_AON_LANE0); + writel(0, core + stat); + KUNIT_EXPECT_EQ(test, atcphy_power_off(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(core + ctrl), ATCPHY_POWER_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ATCPHY_T8152_SYNC_RESET), 0U); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + atcphy_test_t8152_untouched(test, atcphy); +} + +/* + * The T8152 PIPE handler does not acknowledge the lock: the request is made + * and the PIPE changes under it without waiting. Its release then finds the + * acknowledge clear at once. + */ +static void atcphy_test_t8152_pipe_lock(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void *pipehandler = kunit_kzalloc(test, PIPEHANDLER_NONSELECTED_OVERRIDE + 4, + GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, pipehandler); + atcphy->regs.pipehandler = (__force void __iomem *)pipehandler; + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_lock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), + PIPEHANDLER_LOCK_EN); + KUNIT_EXPECT_EQ(test, atcphy_pipehandler_unlock(atcphy), 0); + KUNIT_EXPECT_EQ(test, readl(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ), 0U); +} + +/* + * Without its tunables (a loader that copies none) a T8152 PHY runs USB2 + * alone: every other mode is refused before a register is written. + */ +static void atcphy_test_t8152_no_tunables(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + static const enum atcphy_mode refused[] = { + APPLE_ATCPHY_MODE_USB3, APPLE_ATCPHY_MODE_USB3_DP, APPLE_ATCPHY_MODE_USB4, + APPLE_ATCPHY_MODE_TBT, APPLE_ATCPHY_MODE_DP, + }; + + atcphy->ss_tunables = false; + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE0); + mutex_init(&atcphy->lock); + guard(mutex)(&atcphy->lock); + for (size_t i = 0; i < ARRAY_SIZE(refused); i++) + KUNIT_EXPECT_EQ(test, atcphy_configure(atcphy, refused[i]), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0U); + atcphy_test_t8152_untouched(test, atcphy); +} + +static struct kunit_case atcphy_t8152_test_cases[] = { + KUNIT_CASE(atcphy_test_t8152_lanes), + KUNIT_CASE(atcphy_test_t8152_no_tunables), + KUNIT_CASE(atcphy_test_t8152_power), + KUNIT_CASE(atcphy_test_t8152_pipe_lock), + {} +}; + +static struct kunit_suite atcphy_t8152_test_suite = { + .name = "phy-apple-atc-t8152", + .test_cases = atcphy_t8152_test_cases, +}; + +kunit_test_suite(atcphy_t8152_test_suite); diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 34d3aa12b8f4c8..5ad986fb009ef9 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -249,6 +249,44 @@ enum atcphy_lane_mode { #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_RESET_N_OV 0x200 #define ACIOPHY_BIST_MAC_USBPHY_CFG_OV2_LN0_PWR_DOWN_OV 0x20 +/* T8152 BIST block (ACIOPHY_BIST_BLK) */ +#define ACIOPHY_T8152_BIST_CFG0 0x2400 +#define ACIOPHY_T8152_BIST_CFG0_CLOCK_EN BIT(0) +#define ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC BIT(6) + +#define ACIOPHY_T8152_BIST_CFG2 0x240c +#define ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE BIT(0) + +#define ACIOPHY_T8152_BIST_STATUS1 0x24a0 +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS BIT(6) +#define ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2 BIT(7) + +#define ACIOPHY_T8152_BIST_OV1 0x24b0 +#define ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N BIT(0) +#define ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN GENMASK(8, 5) + +#define ACIOPHY_T8152_BIST_OV2 0x24b8 +#define ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV BIT(5) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK6 BIT(6) +#define ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV BIT(9) +#define ACIOPHY_T8152_BIST_OV2_LN0_UNK10 BIT(10) +#define ACIOPHY_T8152_BIST_OV2_LN0 \ + (ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK6 | \ + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | \ + ACIOPHY_T8152_BIST_OV2_LN0_UNK10) + +/* T8152 lane power controls in the always-on top block (ACIOPHY_TOP_AON_BLK) */ +#define ACIOPHY_T8152_AON_LANE0 0x1e18 +#define ACIOPHY_T8152_AON_LANE_CLAMP_EN BIT(0) +#define ACIOPHY_T8152_AON_LANE_SLEEP_SMALL BIT(1) +#define ACIOPHY_T8152_AON_LANE_SLEEP_BIG BIT(2) +#define ACIOPHY_T8152_AON_LANE_AHB_RESET_N BIT(5) + +#define ACIOPHY_T8152_AON_SLEEP_CTRL2 0x1e24 +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 BIT(12) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0 BIT(16) + #define ACIOPHY_SLEEP_CTRL 0x1b0 #define ACIOPHY_SLEEP_CTRL_TX_BIG GENMASK(1, 0) #define ACIOPHY_SLEEP_CTRL_TX_BIG_OV GENMASK(3, 2) @@ -274,6 +312,16 @@ enum atcphy_lane_mode { #define ATCPHY_MISC_RESET_N BIT(0) #define ATCPHY_MISC_LANE_SWAP BIT(2) +/* + * T8152 has the USB controller's DARTs at 0x20000 and 0x40000 of its ATC + * window, and the power and reset block (ATCPHY_CFG_BLK) follows at 0x60000. + * There the lane swap is bit 1 of 0x60008, and the reset the power-up releases + * first is bit 0 of the always-on sync reset at 0x60030. + */ +#define ATCPHY_T8152_CFG_OFFSET 0x40000 +#define ATCPHY_T8152_MISC_LANE_SWAP BIT(1) +#define ATCPHY_T8152_SYNC_RESET 0x60030 + #define ACIOPHY_LANE_DP_CFG_BLK_TX_DP_CTRL0 0x7000 #define DP_PMA_BYTECLK_RESET BIT(0) #define DP_MAC_DIV20_CLK_SEL BIT(1) @@ -596,6 +644,7 @@ enum atcphy_generation { ATCPHY_GENERATION_T8103, ATCPHY_GENERATION_T8122, ATCPHY_GENERATION_T8132, + ATCPHY_GENERATION_T8152, }; enum atcphy_dp_link_rate { @@ -675,10 +724,18 @@ struct apple_atcphy; /** * struct atcphy_hw - SoC-specific PHY description - * @configure_post_tunable: Generation-specific setup after the tunables + * @configure_post_tunable: Generation-specific setup after the tunables, if any * @gen: Register programming generation - * @aciophy_lane_mode: Lane mode register offset + * @aciophy_lane_mode: Lane mode register offset, or zero to leave the lane + * mode alone (T8152 sets its lanes up through the crossbar) * @aciophy_crossbar: Crossbar register offset + * @cfg_offset: Offset of the power and reset block (ATCPHY_POWER_CTRL, + * ATCPHY_POWER_STAT, ATCPHY_MISC) from where those definitions + * place it + * @sync_reset: Register whose bit 0 is the reset the PHY's power-up releases + * first and its power-down asserts last, instead of + * ATCPHY_MISC_RESET_N, or zero + * @lane_swap: Lane swap bit in ATCPHY_MISC, or zero for ATCPHY_MISC_LANE_SWAP * @has_usb4: A USB4/Thunderbolt controller sits behind the PHY * @usb2_only: Uses the USB2 subset unless its banked SuperSpeed resources exist * @usb2phy_sig_host: Host role field mask, or zero for the original layout @@ -686,11 +743,15 @@ struct apple_atcphy; * @pipe_mux_data: PIPE data selection field mask * @has_usb2phy_reg: The PHY has the secondary eUSB2 register bank (T8140) * @has_t8140_dp: Uses the T8140 DisplayPort tunable bundle - * @optional_tunables: The bootloader may leave out the common-a tunables (this - * generation has none) and the SuperSpeed tunables; USB2 - * still works without the latter + * @optional_tunables: The bootloader may leave out the common-a tunables (T8122 + * has none) and the SuperSpeed tunables (an older loader + * copies no T8152 ones); the PHY still probes, and USB2 + * works without the latter * @park_pipe_unlocked: A stopped controller may park without a PIPE handshake * @clear_boot_hold: Release the boot PIPE hold before dummy backend selection + * @pipe_lock_unacked: The PIPE handler takes the lock request but never + * acknowledges it, so the PIPE changes under the request + * without waiting for the acknowledge * @dp_banked_tunables: DisplayPort requires separate LIOA/common calibration * @dp_t8122: DisplayPort runs the T8122 AUX, AUSPLL and lane sequences * @park_dummy_phy: Enable the dummy PIPE backend whenever the PIPE is parked on @@ -710,6 +771,9 @@ struct atcphy_hw { enum atcphy_generation gen; int aciophy_lane_mode; int aciophy_crossbar; + u32 cfg_offset; + u32 sync_reset; + u32 lane_swap; bool has_usb4; bool usb2_only; u32 usb2phy_sig_host; @@ -723,6 +787,7 @@ struct atcphy_hw { bool park_pipe_unlocked; bool park_dummy_phy; bool clear_boot_hold; + bool pipe_lock_unacked; bool restore_after_pd_off; bool idle_power_off; }; @@ -796,6 +861,11 @@ struct atcphy_cio_sleep { * behind the T6030 HDMI port; it maps only its core window * @fixed_usb2: The USB2 pairs go to a fixed hub on the USB controller, which * stays in host mode; the PHY provides USB2 from probe on + * @fixed_usb3: The SuperSpeed lanes go straight to a USB3 device or hub, with + * no Type-C mux in between (apple,fixed-usb3): the PHY runs USB3 + * on lane 0 from probe on and provides only the USB3 PHY of the + * controller, which is a host; its USB2 side and its reset are + * left to the bootloader * @typec_mode: Mode the Type-C mux last asked for; a fixed-hub port returns to * it when the PHY is brought back up after a power-off * @host_active: dwc3 has selected host mode on the USB3 PHY; a fixed-hub port @@ -910,6 +980,7 @@ struct apple_atcphy { bool dp_presets_valid[5]; bool dp_only; bool fixed_usb2; + bool fixed_usb3; enum atcphy_mode typec_mode; bool host_active; /* @@ -1276,6 +1347,65 @@ static inline u32 core_read32(struct apple_atcphy *atcphy, u32 reg) return readl(atcphy->regs.core + reg); } +/* A register of the power and reset block, see atcphy_hw.cfg_offset */ +static inline u32 atcphy_cfg(const struct apple_atcphy *atcphy, u32 reg) +{ + return reg + atcphy->hw->cfg_offset; +} + +static inline u32 atcphy_lane_swap(const struct apple_atcphy *atcphy) +{ + return atcphy->hw->lane_swap ?: ATCPHY_MISC_LANE_SWAP; +} + +/* + * T8152 keeps a lane's registers in AHB reset until the lane is powered up on + * its own, and they drop their tunables meanwhile. Power lane 0, the USB3 lane + * of a fixed-USB3 port, up after the common-a tunables: its LFPS receivers, + * then out of sleep, unclamped and out of AHB reset. Set the crossbar right + * after, before the remaining tunables, as the T8152 sequence does: 0x110 for + * USB3, i.e. USB3+DP with single PMA 0x008. atcphy_configure_lanes() writes the + * same value again later. + */ +static void atcphy_lanes_up_t8152(struct apple_atcphy *atcphy, enum atcphy_mode mode) +{ + const struct atcphy_mode_configuration *mode_cfg = atcphy_get_mode_config(atcphy, mode); + + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + + core_mask32(atcphy, atcphy->hw->aciophy_crossbar, + ACIOPHY_CROSSBAR_PROTOCOL | ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar) | + FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, + mode_cfg->crossbar_dp_single_pma)); +} + +/* T8152: power lane 0 down as the PHY powers down, the reverse of the above */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *atcphy) +{ + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); +} + /* Static configuration fields already read/modified by the public DP path. */ static void j700_dp_tunables(struct apple_atcphy *atcphy) { @@ -1305,6 +1435,8 @@ static void atcphy_apply_tunables(struct apple_atcphy *atcphy, enum atcphy_mode } apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[0]); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_up_t8152(atcphy, mode); apple_tunable_apply(atcphy->regs.axi2af, atcphy->tunables.axi2af); apple_tunable_apply(atcphy->regs.core, atcphy->tunables.common[1]); @@ -1389,6 +1521,10 @@ static int atcphy_pipehandler_lock(struct apple_atcphy *atcphy) if (IS_ENABLED(CONFIG_PHY_APPLE_ATC_KUNIT_TEST)) KUNIT_STATIC_STUB_REDIRECT(atcphy_pipehandler_lock, atcphy); + if (atcphy->hw->pipe_lock_unacked) { + set32(atcphy->regs.pipehandler + PIPEHANDLER_LOCK_REQ, PIPEHANDLER_LOCK_EN); + return 0; + } return atcphy_pipehandler_lock_timeout(atcphy, atcphy->hw->gen == ATCPHY_GENERATION_T8132 ? 6000 : PIPEHANDLER_LOCK_ACK_TIMEOUT_US); @@ -1631,6 +1767,77 @@ static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *atc return ret; } +/* T8152: latch the BIST override registers into the USB side of the PHY */ +static void atcphy_t8152_bist_sync(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); + core_read32(atcphy, ACIOPHY_T8152_BIST_CFG0); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_USB_REGSYNC); +} + +static void atcphy_t8152_bist_ack(struct apple_atcphy *atcphy) +{ + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG2, ACIOPHY_T8152_BIST_CFG2_LN0_PHY_STATUS_RE); +} + +/* + * T8152: while the PIPE moves from the dummy PHY to this one, the BIST + * overrides hold lane 0's PIPE reset and power-down, the power-down stepping + * from P2 to P3, and the non-selected PHY override is released under them. + */ +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *atcphy) +{ + void __iomem *status = atcphy->regs.core + ACIOPHY_T8152_BIST_STATUS1; + int ret, error = 0; + u32 reg; + + core_set32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + ACIOPHY_T8152_BIST_OV1_LN0_PIPE_RESET_N | + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 2)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0, + ACIOPHY_T8152_BIST_OV2_LN0_PIPE_RESET_N_OV | + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 20000); + if (ret) { + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P2 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV1, ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, + FIELD_PREP(ACIOPHY_T8152_BIST_OV1_LN0_PWR_DOWN, 3)); + core_mask32(atcphy, ACIOPHY_T8152_BIST_OV2, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV | ACIOPHY_T8152_BIST_OV2_LN0_UNK10, + ACIOPHY_T8152_BIST_OV2_LN0_PWR_DOWN_OV); + atcphy_t8152_bist_sync(atcphy); + ret = readl_poll_timeout(status, reg, reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS, + 10, 130000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: no PHY status in P3 (%#x)\n", reg); + } + ret = readl_poll_timeout(status, reg, !(reg & ACIOPHY_T8152_BIST_STATUS1_LN0_PHY_STATUS2), + 10, 1000); + if (ret) { + if (!error) + error = ret; + dev_warn(atcphy->dev, "T8152 USB3 BIST: PHY status stuck in P3 (%#x)\n", reg); + } + atcphy_t8152_bist_ack(atcphy); + + atcphy_clear_nonselected_phy_reset(atcphy); + + core_clear32(atcphy, ACIOPHY_T8152_BIST_OV2, ACIOPHY_T8152_BIST_OV2_LN0); + atcphy_t8152_bist_sync(atcphy); + core_clear32(atcphy, ACIOPHY_T8152_BIST_CFG0, ACIOPHY_T8152_BIST_CFG0_CLOCK_EN); + return error; +} + static int atcphy_configure_pipehandler_usb3_host_t8103(struct apple_atcphy *atcphy) { int ret, error = 0; @@ -1738,6 +1945,8 @@ static int atcphy_configure_pipehandler_usb3(struct apple_atcphy *atcphy, bool h ret = atcphy_configure_pipehandler_usb3_host_t8103(atcphy); else if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) ret = atcphy_configure_pipehandler_usb3_host_t8132(atcphy); + else if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + ret = atcphy_configure_pipehandler_usb3_host_t8152(atcphy); else ret = atcphy_configure_pipehandler_usb3_host_t8122(atcphy); if (ret) { @@ -2147,21 +2356,23 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode mode == APPLE_ATCPHY_MODE_DP)) return j700_dp_route(atcphy, mode == APPLE_ATCPHY_MODE_DP); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, - FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, - FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, - FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); - core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, - FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + if (atcphy->hw->aciophy_lane_mode) { + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX0, + FIELD_PREP(ACIOPHY_LANE_MODE_RX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX0, + FIELD_PREP(ACIOPHY_LANE_MODE_TX0, mode_cfg->lane_mode[0])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_RX1, + FIELD_PREP(ACIOPHY_LANE_MODE_RX1, mode_cfg->lane_mode[1])); + core_mask32(atcphy, atcphy->hw->aciophy_lane_mode, ACIOPHY_LANE_MODE_TX1, + FIELD_PREP(ACIOPHY_LANE_MODE_TX1, mode_cfg->lane_mode[1])); + } core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_PROTOCOL, FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar)); if (mode_cfg->set_swap) - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); else - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_DP_SINGLE_PMA, FIELD_PREP(ACIOPHY_CROSSBAR_DP_SINGLE_PMA, mode_cfg->crossbar_dp_single_pma)); @@ -2173,8 +2384,10 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode /* * The PMA FSM override below is for the T8103 generation. T8122 DP lanes * are started by the link rate sequence, see atcphy_dp_set_rate_t8122(). + * T8152 runs USB3 alone. */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8122) + if (atcphy->hw->gen == ATCPHY_GENERATION_T8122 || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) return 0; if (mode_cfg->dp_lane[0]) { @@ -2707,34 +2920,43 @@ static int atcphy_power_off(struct apple_atcphy *atcphy) u32 reg; int ret; - if (atcphy->hw->gen != ATCPHY_GENERATION_T8132) { + /* A fixed-USB3 port has no DisplayPort side */ + if (atcphy->hw->gen != ATCPHY_GENERATION_T8132 && !atcphy->fixed_usb3) { ret = atcphy_disable_dp_aux(atcphy); if (ret) return ret; } /* Enable all reset lines */ - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_clear32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); - - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152) + atcphy_lanes_down_t8152(atcphy); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + if (!atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N | ATCPHY_MISC_LANE_SWAP); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); + + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_BIG), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, !(reg & ATCPHY_POWER_SLEEP_SMALL), 10, 1000); if (ret) { dev_err(atcphy->dev, "Failed to sleep atcphy \"small\"\n"); return ret; } + /* A separate sync reset is asserted last, once the block sleeps */ + if (atcphy->hw->sync_reset) + core_clear32(atcphy, atcphy->hw->sync_reset, ATCPHY_MISC_RESET_N); + return 0; } @@ -2792,29 +3014,30 @@ static int atcphy_power_on(struct apple_atcphy *atcphy) u32 reg; int ret; - if (!atcphy->dp_only) + if (!atcphy->dp_only && !atcphy->fixed_usb3) atcphy_usb2_power_on(atcphy); - core_set32(atcphy, ATCPHY_MISC, ATCPHY_MISC_RESET_N); + core_set32(atcphy, atcphy->hw->sync_reset ?: atcphy_cfg(atcphy, ATCPHY_MISC), + ATCPHY_MISC_RESET_N); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_SMALL); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_SMALL); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_SMALL, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"small\"\n"); return ret; } - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_SLEEP_BIG); - ret = readl_poll_timeout(atcphy->regs.core + ATCPHY_POWER_STAT, reg, + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_SLEEP_BIG); + ret = readl_poll_timeout(atcphy->regs.core + atcphy_cfg(atcphy, ATCPHY_POWER_STAT), reg, reg & ATCPHY_POWER_SLEEP_BIG, 100, 100000); if (ret) { dev_err(atcphy->dev, "failed to wakeup atcphy \"big\"\n"); return ret; } - core_clear32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_CLAMP_EN); - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_APB_RESET_N); + core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_CLAMP_EN); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_APB_RESET_N); return 0; } @@ -4170,6 +4393,10 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return -EBUSY; if (atcphy->hw->gen == ATCPHY_GENERATION_T8132) return atcphy_configure_t8132(atcphy, mode); + /* T8152 without its tunables (an older loader): the lanes stay off, USB2 only */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->ss_tunables && + mode != APPLE_ATCPHY_MODE_OFF && mode != APPLE_ATCPHY_MODE_USB2) + return -EOPNOTSUPP; if (atcphy->pipe_pending) return -EBUSY; if (atcphy->usb_off_pending && mode != APPLE_ATCPHY_MODE_OFF) @@ -4265,7 +4492,8 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) apple_tunable_apply(atcphy->regs.lioa, atcphy->tunables.dp_lioa); apple_tunable_apply(atcphy->regs.lpdptx, atcphy->tunables.dp_common_config); } - atcphy->hw->configure_post_tunable(atcphy, mode); + if (atcphy->hw->configure_post_tunable) + atcphy->hw->configure_post_tunable(atcphy, mode); /* Setup AUX channel if DP altmode is requested */ if (atcphy_modes[mode].enable_dp_aux) { @@ -4284,7 +4512,7 @@ static int atcphy_configure(struct apple_atcphy *atcphy, enum atcphy_mode mode) return ret; /* Take the USB3 PHY out of reset */ - core_set32(atcphy, ATCPHY_POWER_CTRL, ATCPHY_POWER_PHY_RESET_N); + core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL), ATCPHY_POWER_PHY_RESET_N); /* * NOTE: Not what macos does, it takes the phy out of reset right before * writing to ACIOPHY_CFG0_COMMON_SMALL, does lane configuration with phy @@ -4753,7 +4981,7 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode readl(atcphy->regs.pipehandler + PIPEHANDLER_MUX_CTRL), readl(atcphy->regs.pipehandler + PIPEHANDLER_NONSELECTED_OVERRIDE), readl(atcphy->regs.pipehandler + PIPEHANDLER_T8132_USB2_CONFIG)); - if (!ret || !atcphy->fixed_usb2 || mode != PHY_MODE_USB_HOST) + if (!ret || !(atcphy->fixed_usb2 || atcphy->fixed_usb3) || mode != PHY_MODE_USB_HOST) return ret; /* @@ -4761,7 +4989,8 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode * fails, xHCI registers neither of its root hubs. Let it start, with * the PIPE parked if that works: the Type-C mux update that restores * the lanes or retries the handoff routes the PIPE, with the - * SuperSpeed port off. + * SuperSpeed port off. On a fixed-USB3 port the controller's next + * power-on of this PHY tries again. */ if (atcphy_park_pipehandler(atcphy, false)) dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); @@ -4770,6 +4999,35 @@ static int atcphy_usb3_set_mode(struct phy *phy, enum phy_mode mode, int submode return 0; } +/* + * A fixed-USB3 port's controller is a host by construction. It powers this + * PHY on after its core reset, before the host starts: route the PIPE to the + * USB3 PHY then, bringing the PHY up in USB3 again first if a power-off took + * it down. A failure here would stop the controller altogether, and with it + * the USB2 side of the same device, so the host then starts with its PIPE + * parked instead. + */ +static int atcphy_usb3_power_on(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + int ret = 0; + + guard(mutex)(&atcphy->lock); + atcphy->host_active = true; + if (atcphy->mode != APPLE_ATCPHY_MODE_USB3 || atcphy->mode_dirty) + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (!ret) + ret = atcphy_usb3_route(atcphy, true); + if (!ret) + return 0; + + if (atcphy_park_pipehandler(atcphy, false)) + dev_warn(atcphy->dev, "Host starts with its PIPE not parked\n"); + else + dev_warn(atcphy->dev, "Host starts without USB3: %d\n", ret); + return 0; +} + static int atcphy_usb3_exit(struct phy *phy) { struct apple_atcphy *atcphy = phy_get_drvdata(phy); @@ -4817,6 +5075,17 @@ static const struct phy_ops apple_atc_usb3_phy_ops = { .set_mode = atcphy_rpm_usb3_set_mode, }; +/* + * A fixed-USB3 port also routes its PIPE at power-on. Its PHY never + * runtime-suspends (see atcphy_rpm_get()), so it needs no runtime PM wrappers. + */ +static const struct phy_ops apple_atc_fixed_usb3_phy_ops = { + .owner = THIS_MODULE, + .power_on = atcphy_usb3_power_on, + .power_off = atcphy_usb3_power_off, + .set_mode = atcphy_usb3_set_mode, +}; + /* * The T8132 PHY has no DisplayPort alternate mode: its DP PHY only exists so * that a DisplayPort tunnel can get its pixel clock, see @@ -5206,7 +5475,7 @@ static struct phy *atcphy_xlate(struct device *dev, const struct of_phandle_args default: return ERR_PTR(-ENODEV); } - /* A DisplayPort-only or USB2-only instance omits the other PHYs. */ + /* A DisplayPort-, USB2- or USB3-only instance omits the other PHYs. */ return phy ?: ERR_PTR(-ENODEV); } @@ -5217,18 +5486,20 @@ static int atcphy_probe_phy(struct apple_atcphy *atcphy) const struct phy_ops *ops; } phys[] = { { &atcphy->phys.usb2, &apple_atc_usb2_phy_ops }, - { &atcphy->phys.usb3, &apple_atc_usb3_phy_ops }, + { &atcphy->phys.usb3, atcphy->fixed_usb3 ? &apple_atc_fixed_usb3_phy_ops : + &apple_atc_usb3_phy_ops }, { &atcphy->phys.dp, &apple_atc_dp_phy_ops }, }; /* * A T8132 PHY with its USB3/USB4 banks gets a DP PHY for DisplayPort * tunnels only (see atcphy_dpphy_set_mode_t8132()); creating it does - * not touch the hardware. + * not touch the hardware. A fixed-USB3 PHY gets its USB3 PHY only. */ for (int i = 0; i < ARRAY_SIZE(phys); i++) { if ((atcphy->dp_only && phys[i].phy != &atcphy->phys.dp) || - (atcphy_usb2_only(atcphy) && i != 0)) + (atcphy_usb2_only(atcphy) && i != 0) || + (atcphy->fixed_usb3 && phys[i].phy != &atcphy->phys.usb3)) continue; *phys[i].phy = devm_phy_create(atcphy->dev, NULL, phys[i].ops); if (IS_ERR(*phys[i].phy)) @@ -6412,6 +6683,14 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) bool lane_dp = tunables[i].tunable == &atcphy->tunables.lane_dp[0] || tunables[i].tunable == &atcphy->tunables.lane_dp[1]; + /* a fixed-USB3 port runs USB3 on lane 0 alone and has no axi2af window */ + if (atcphy->fixed_usb3 && + tunables[i].tunable != &atcphy->tunables.common[0] && + tunables[i].tunable != &atcphy->tunables.common[1] && + tunables[i].tunable != &atcphy->tunables.lane_usb3[0]) { + *tunables[i].tunable = NULL; + continue; + } if (!atcphy->hw->has_usb4 && (tunables[i].tunable == &atcphy->tunables.lane_usb4[0] || tunables[i].tunable == &atcphy->tunables.lane_usb4[1])) { @@ -6450,8 +6729,9 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) tunables[i].dt_name, PTR_ERR(tunable)); return PTR_ERR(tunable); } - /* The common-a tunables do not exist on this generation */ - if (tunables[i].tunable != &atcphy->tunables.common[0]) + /* T8122 has no common-a tunables; T8152's calibrate the lanes too */ + if (tunables[i].tunable != &atcphy->tunables.common[0] || + atcphy->hw->gen == ATCPHY_GENERATION_T8152) ss_missing = true; if (tunables[i].tunable == &atcphy->tunables.axi2af || tunables[i].tunable == &atcphy->tunables.common[1]) @@ -6516,6 +6796,28 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph struct resource *res; void __iomem *addr; + /* + * A fixed-USB3 PHY has its core and PIPE windows only. On T8152 the + * core window also holds the USB controller's DARTs, so it is mapped + * without claiming it. + */ + if (atcphy->fixed_usb3) { + res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "core"); + if (!res) + return dev_err_probe(atcphy->dev, -EINVAL, "Missing core regs\n"); + atcphy->regs.core = devm_ioremap(&pdev->dev, res->start, resource_size(res)); + if (!atcphy->regs.core) + return -ENOMEM; + atcphy->res.core = res; + + addr = devm_platform_ioremap_resource_byname(pdev, "pipehandler"); + if (IS_ERR(addr)) + return dev_err_probe(atcphy->dev, PTR_ERR(addr), + "Unable to map pipehandler regs\n"); + atcphy->regs.pipehandler = addr; + return 0; + } + if (atcphy->hw->gen == ATCPHY_GENERATION_T8132 && platform_get_resource_byname(pdev, IORESOURCE_MEM, "common-config")) { static const char * const names[] = { @@ -6743,6 +7045,34 @@ static int atcphy_probe_finalize_dp_only(struct apple_atcphy *atcphy) return 0; } +/* + * A fixed-USB3 port: the bootloader hands its controller over running, with + * the controller's reset and its USB2 side its own, and no Type-C mux sits in + * front of the lanes, so there is no reset controller, mux or switch to + * register. Take the PHY from the state the bootloader left it in to USB3; the + * PIPE follows when the controller powers its USB3 PHY on, which also tries + * again if this fails, see atcphy_usb3_power_on(). + */ +static int atcphy_probe_finalize_fixed_usb3(struct apple_atcphy *atcphy) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + + atcphy_power_off(atcphy); + atcphy_setup_pipehandler(atcphy); + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_USB3); + if (ret) + dev_warn(atcphy->dev, "USB3 not up yet: %d\n", ret); + + ret = atcphy_probe_phy(atcphy); + if (ret) { + atcphy_configure(atcphy, APPLE_ATCPHY_MODE_OFF); + return dev_err_probe(atcphy->dev, ret, "Probing phy failed"); + } + return 0; +} + static int atcphy_probe_finalize(struct apple_atcphy *atcphy) { int ret; @@ -6751,6 +7081,8 @@ static int atcphy_probe_finalize(struct apple_atcphy *atcphy) if (atcphy->dp_only) return atcphy_probe_finalize_dp_only(atcphy); + if (atcphy->fixed_usb3) + return atcphy_probe_finalize_fixed_usb3(atcphy); /* Reset dwc3 on probe, let dwc3 (consumer) deassert it */ _atcphy_dwc3_reset_assert(atcphy); @@ -6882,6 +7214,25 @@ static bool atcphy_has_t8103_usb3_workaround(const struct atcphy_hw *hw, of_device_is_compatible(root, "apple,t8103"); } +/* + * The driver core attaches a single power domain. A fixed-USB3 PHY may list + * several, like T8152's ATC power states and PSD service: hold them all on + * while it is bound, powered up in the order they are listed. + */ +static int atcphy_probe_power_domains(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_attach_data pd_data = { .pd_flags = PD_FLAG_DEV_LINK_ON }; + struct dev_pm_domain_list *pd_list; + int ret; + + if (!atcphy->fixed_usb3 || atcphy->dev->pm_domain) + return 0; + ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &pd_list); + if (ret < 0) + return dev_err_probe(atcphy->dev, ret, "Failed to attach power domains\n"); + return 0; +} + static void atcphy_sleep_finish_work(struct work_struct *work); static int atcphy_probe(struct platform_device *pdev) @@ -6904,6 +7255,10 @@ static int atcphy_probe(struct platform_device *pdev) atcphy->np = dev->of_node; atcphy->t8132_dp_alt = atcphy->hw->gen == ATCPHY_GENERATION_T8132 && of_property_read_bool(dev->of_node, "apple,dp-alt-mode"); + atcphy->fixed_usb3 = of_property_read_bool(dev->of_node, "apple,fixed-usb3"); + /* T8152 is supported on a fixed-USB3 port only */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->fixed_usb3) + return dev_err_probe(dev, -ENODEV, "Only a fixed-USB3 port is supported\n"); apple_atc_tunnel_wiring(atcphy); mutex_init(&atcphy->lock); platform_set_drvdata(pdev, atcphy); @@ -6912,6 +7267,9 @@ static int atcphy_probe(struct platform_device *pdev) if (ret) return ret; ret = atcphy_load_tunables(atcphy); + if (ret) + return ret; + ret = atcphy_probe_power_domains(atcphy); if (ret) return ret; @@ -7983,12 +8341,43 @@ static const struct atcphy_hw atcphy_hw_t8142 = { .clear_boot_hold = true, }; +/* + * T8152 as the USB3 PHY of a fixed-USB3 port: no USB4, DisplayPort or lane + * mode register and nothing to wake after the tunables. Its power domains are + * not followed: the controller's power-off and power-on of the PHY, as around + * a system sleep, take it down and up again. + */ +static const struct atcphy_hw atcphy_hw_t8152 = { + .gen = ATCPHY_GENERATION_T8152, + .aciophy_crossbar = ACIOPHY_CROSSBAR_T8103, + .cfg_offset = ATCPHY_T8152_CFG_OFFSET, + .sync_reset = ATCPHY_T8152_SYNC_RESET, + .lane_swap = ATCPHY_T8152_MISC_LANE_SWAP, + .pipe_mux_clk = PIPEHANDLER_MUX_CTRL_CLK_T8142, + .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8142, + .park_dummy_phy = true, + .clear_boot_hold = true, + /* + * The bootloader copies the tunables from the Mac's own ADT. Without + * them (an older loader) the PHY still probes, so that its consumers do + * not wait for it, and refuses every mode but USB2. + */ + .optional_tunables = true, + /* + * With the controller out of reset, the J873g front port's PIPE handler + * left the lock unacknowledged for 150 ms in both directions, while the + * PIPE moved to USB3 and back to the dummy PHY under the request. + */ + .pipe_lock_unacked = true, +}; + static const struct of_device_id atcphy_match[] = { { .compatible = "apple,t8103-atcphy", .data = &atcphy_hw_t8103 }, { .compatible = "apple,t8122-atcphy", .data = &atcphy_hw_t8122 }, { .compatible = "apple,t8132-atcphy", .data = &atcphy_hw_t8132 }, { .compatible = "apple,t8142-atcphy", .data = &atcphy_hw_t8142 }, { .compatible = "apple,t8140-atcphy", .data = &atcphy_hw_t8140 }, + { .compatible = "apple,t8152-atcphy", .data = &atcphy_hw_t8152 }, {}, }; MODULE_DEVICE_TABLE(of, atcphy_match); diff --git a/tools/asahi/atc-usb3-tests.py b/tools/asahi/atc-usb3-tests.py index 3a7955197c9f9a..d9f9aacb4d38f7 100644 --- a/tools/asahi/atc-usb3-tests.py +++ b/tools/asahi/atc-usb3-tests.py @@ -78,7 +78,7 @@ def block(source, marker): STUBS = r''' struct atcphy_hw { enum atcphy_generation gen; bool has_t8140_dp, dp_t8122, has_usb4, park_pipe_unlocked, park_dummy_phy, usb2_only; - bool clear_boot_hold, dp_banked_tunables; }; + bool clear_boot_hold, dp_banked_tunables, pipe_lock_unacked; }; struct device_node { const char *const *compatible; unsigned int count; }; static bool of_device_is_compatible(const struct device_node *root, const char *compatible) { if (!root) return false; @@ -98,7 +98,7 @@ def block(source, marker): enum atcphy_pipehandler_state pipe_state; enum atcphy_mode typec_mode; bool pipe_pending, t8103_dummy_pending, t8103_usb3_retry, t8103_usb3_workaround, mode_dirty, usb_off_pending; - bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, t8140_dp_tunables, dp_tunables; + bool host_active, usb3_port_off, dp_only, ss_tunables, fixed_usb2, fixed_usb3, t8140_dp_tunables, dp_tunables; /* T8132 ownership is tested without entering its lane-setup backend. */ bool t8132_ss, t8132_common_owned, t8132_failed, cio_tunables, t8132_dp_alt; struct { void *usb3_dp; } tunables; @@ -185,6 +185,9 @@ def block(source, marker): static int atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *a) { (void)a; assert(!"T8132 PIPE setup reached"); return -EINVAL; } +static int atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *a) { + (void)a; assert(!"T8152 PIPE setup reached"); return -EINVAL; +} static void atcphy_usb2_power_on(struct apple_atcphy *a) { (void)a; assert(!"USB2-only power restore reached"); } diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index 7eeb90baf4385d..ed02e7f33b5627 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -92,7 +92,8 @@ def main(): ''' declarations = r''' struct apple_tunable { unsigned id; }; -struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; }; +struct atcphy_hw { int gen; bool usb2_only, has_usb2phy_reg, park_pipe_unlocked; u32 usb2phy_sig_host; + u32 cfg_offset, sync_reset; }; enum suspend_state { PM_SUSPEND_TO_IDLE = 1, PM_SUSPEND_MEM = 3 }; static enum suspend_state pm_suspend_target_state; static bool rpm_suspended; @@ -106,7 +107,7 @@ def main(): bool t8132_ss, t8132_common_owned, t8132_suspended, t8132_failed, host_active; bool ss_tunables, mode_dirty, pipe_pending, swap_lanes; bool cio_tunables, t8132_dp_alt, fixed_usb2, hibernated, pd_was_off, idle_rpm; - bool t8103_dummy_pending, t8103_usb3_workaround; + bool t8103_dummy_pending, t8103_usb3_workaround, fixed_usb3; unsigned tunnel_users; struct { bool prepared, changed, restored; } cio_sleep; int mode, pipe_state, lock; @@ -122,6 +123,8 @@ def main(): struct device { struct apple_atcphy *atc; }; static struct apple_atcphy *dev_get_drvdata(struct device *d) { return d->atc; } static struct apple_atcphy *phy_get_drvdata(struct phy *p) { return p->atc; } +/* T8152 only: these rows run T8132, which never reaches it. */ +static void atcphy_lanes_down_t8152(struct apple_atcphy *a) { (void)a; assert(0); } static u32 core[0x24000/4], usb2[0x4000/4], pipe_regs[0x4000/4]; static unsigned tunes[16], tune_count, reset_releases, bist_phase, writes, core_reads; static unsigned stall_power, stall_bist, expected_tunes, stall_sleep; @@ -215,7 +218,7 @@ def main(): } ''' names = ["atcphy_mode_is_cio", "atcphy_usb2_sig_host", "atcphy_t8132_dp_on", - "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", + "atcphy_cfg", "atcphy_usb2_power_off", "atcphy_power_off", "atcphy_usb2_power_on", "atcphy_t8132_cold", "atcphy_t8132_common_start", "atcphy_t8132_phy_stop", "atcphy_t8132_full_stop", "atcphy_configure_t8132", "atcphy_usb2_set_mode", "atcphy_t8132_bist_pulse", diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py index 980a7a8773b97f..aee2f68cc7bed0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/common.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/common.py @@ -194,6 +194,18 @@ def atc_cio_helpers(source): return result +def atc_cfg_helpers(source): + """Where the power and reset block sits and which bit swaps the lanes, both of + which T8152 moves; the power-up, power-down and lane functions call these. + + Marked unused, as a unit may extract only some of their callers. Older + sources have neither: ''. + """ + return ''.join(atc_function(source, name).replace( + 'static inline ', 'static inline __attribute__((unused)) ', 1) + for name in ('atcphy_cfg', 'atcphy_lane_swap')) + + def atc_restore_helpers(source): """What atcphy_restore_after_pd_off() needs beyond the parking helpers. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index cc3197c1b738a1..a2d8076ac8b3dc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -25,7 +25,7 @@ struct apple_atcphy { bool aux, pll; unsigned int pairs, rate; } dp_t8122; - bool fixed_usb2, host_active, mode_dirty, ss_tunables, dp_tunables, + bool fixed_usb2, fixed_usb3, host_active, mode_dirty, ss_tunables, dp_tunables, aux_power_requested; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; @@ -252,11 +252,15 @@ static void atcphy_restore_after_pd_off(struct apple_atcphy *p); static int atcphy_power_off(struct apple_atcphy *p); static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } /* Model the USB2 power-on boundary's running state. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py index e41e10447eb224..2fc3385d1df6e0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/lifecycle.py @@ -3,7 +3,7 @@ """Actual disconnect authority, DWC3 teardown and firmware resource admission.""" from pathlib import Path import re -from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers +from common import block, apple_function, internal_inline, atc_mux_without_pm, source_defines, ATC_POST_TUNABLE, tipd_pm_header, firmware_lineage, atc_restore_helpers, atc_cio_helpers, atc_cfg_helpers def disconnect(root): # Copyright 2026 Ryan Murray @@ -1182,7 +1182,7 @@ def fn(n, name): names = {n: tuple(name for name in group if re.search(r'^(?:static [^\n]*\b|(?:int|void) )' + name + r'\(', files[n], re.M)) for n, group in names.items()} context = (fn('atc', 'core_read32') + '\n' + fn('atc', 'atcphy_get_mode_config') + '\n' + fn('atc', 'j700_field_update') + '\n' + files['dp'][files['dp'].index('/* Masks are the union'):files['dp'].index('/* Retry only the idle operations')]) - functions = atc_cio_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) + functions = atc_cio_helpers(files['atc']) + atc_cfg_helpers(files['atc']) + '\n\n'.join(fn(n, name) for n, group in names.items() for name in group) definitions = [] lines = iter(files['atc'].splitlines()) for line in lines: diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 26c0f62dabb254..45c8275bf462ee 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -5,7 +5,7 @@ import re from common import (block, source_defines, atc_mux_without_pm, ATC_POST_TUNABLE, atc_function, ATC_SPLIT, ATC_T8103_LIVE, atc_restore_helpers, atc_common_state_helpers, - atc_cio_helpers) + atc_cio_helpers, atc_cfg_helpers) def parking(root): @@ -46,7 +46,7 @@ def function(source, name): struct reset_controller_dev rcdev; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -67,6 +67,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -160,11 +161,15 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } ''') @@ -1948,7 +1953,7 @@ def function(name): struct { unsigned char *core, *pipehandler; } regs; void *dev; int lock; - bool fixed_usb2, host_active, ss_tunables, dp_tunables, mode_dirty; + bool fixed_usb2, fixed_usb3, host_active, ss_tunables, dp_tunables, mode_dirty; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; u32 dp_usb_context[2][27]; @@ -1993,11 +1998,13 @@ def function(name): static void __attribute__((unused)) atcphy_restore_after_pd_off(struct apple_atcphy *p) { assert(!p->pd_was_off); } static int atcphy_configure(struct apple_atcphy *p, enum atcphy_mode mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); return -EOPNOTSUPP; } ''') for name in ('core_read32', 'atcphy_get_mode_config'): @@ -2348,7 +2355,7 @@ def function(source, name): struct { unsigned char *core, *lpdptx, *lioa; } regs; void *dev; int lock, dp_link_rate; - bool fixed_usb2, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -2364,6 +2371,7 @@ def function(source, name): start = atc.index('static const struct {\n\tconst struct atcphy_mode_configuration normal;') parts.append(atc[start:atc.index('\n};', start) + 3]) parts.append(atc_cio_helpers(atc)) + parts.append(atc_cfg_helpers(atc)) parts.append(r''' struct phy_configure_opts_dp { unsigned int link_rate, lanes, voltage[4], pre[4]; @@ -2424,11 +2432,13 @@ def function(source, name): static int atcphy_power_off(struct apple_atcphy *); static int atcphy_configure(struct apple_atcphy *, enum atcphy_mode); -/* These units exercise older PHY generations. Never accept a T8132 dispatch. */ +/* These units exercise older PHY generations. Never accept a T8132 or T8152 dispatch. */ static int __attribute__((unused)) atcphy_configure_t8132(struct apple_atcphy *p, enum atcphy_mode mode) { (void)p; (void)mode; assert(false); return -EOPNOTSUPP; } static int __attribute__((unused)) atcphy_configure_pipehandler_usb3_host_t8132(struct apple_atcphy *p) { (void)p; assert(false); return -EOPNOTSUPP; } +static void __attribute__((unused)) atcphy_lanes_down_t8152(struct apple_atcphy *p) +{ (void)p; assert(false); } static int atcphy_park_pipehandler(struct apple_atcphy *p, bool keep_dp) From cc129b6f0f7cc22994c914730117e127074591f0 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 22:14:52 +0100 Subject: [PATCH 0960/1514] arm64: dts: apple: j873: USB3 on the front ports The two front USB-C ports sit behind an on-board VL822 hub on usb-drd2. The hub's USB2 side is on the controller's eUSB2 PHY, which the loader sets up, and its USB3 side on ATC2's Type-C PHY, wired directly without a Type-C mux. So far the controller was limited to high speed and the hub ran at USB2 only. Describe ATC2's PHY as an apple,t8152-atcphy with apple,fixed-usb3, hand it to usb-drd2 as its USB3 PHY and drop the controller's high-speed limit. Nothing changes for usb-drd1 (the back-left port). The PHY's power domains are ATC2's USB_AON, COMMON_DP_0 and COMMON_DP_1 PMGR power states, in a new node for the ATCs' block of PMGR states at 0x308290000, and its common domain, PSD service 57 (ADT clock-gates 57). The T8152 USB3 bring-up runs the power states without automatic power management, so they are marked apple,no-auto-pm. The PHY's tunables are the groups of the ADT's atc-phy2 node that apply to USB3 on lane 0: the common and PLL defaults as common-a, the fabric, PLL and USBC0 groups as common-b and the lane 0 groups as lane0-usb. Some of them differ between the four ATCs of the same Mac, so they are calibration: the bootloader copies them from the Mac's own ADT, through the atcphy2 alias (aurora-silicon/aura#498). With a loader that copies none, the PHY runs USB2 only. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 142 +++++++++++++----- 1 file changed, 106 insertions(+), 36 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 924df52e3622bb..08c65ebaec42bb 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -1,15 +1,18 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * J873g USB2 host bring-up: usb-drd1 (back-left port) and usb-drd2 - * (front ports via the on-board hub). + * J873g USB host bring-up: usb-drd1 (back-left port, USB2) and usb-drd2 + * (front ports via the on-board hub, USB2 and USB3). * The loader powers the controllers and sets up the USB2 side of their ATC - * PHYs for host mode before Linux starts (there is no T8152 ATC PHY or Type-C + * PHYs for host mode before Linux starts (there is no T8152 USB2 PHY or Type-C * support yet). * The controllers are described by their DWC3 core region, as hosts behind * their two DARTs (apple,t8152-dwc3); their PHY reset, and on the Type-C port * the role switch, exist but are left to the loader. + * usb-drd2's hub is wired to ATC2's PHY without a Type-C mux, so Linux brings + * that PHY up in USB3 mode (atc2_phy). * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2 (on atc-phy1 and - * atc-phy2) and the pmgr devices ATC1_USB_AON/USB and ATC2_USB_AON/USB. + * atc-phy2), atc-phy2 and the pmgr devices ATC1_USB_AON/USB, ATC2_USB_AON/USB + * and ATC2_COMMON_DP_0/1. * * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists @@ -19,6 +22,8 @@ * own window only, and describe instance 1 as a node of its own. */ +#include + &dwc3_1_dart { reg = <0x4 0x0b020000 0x0 0xc000>; power-domains = <&ps_atc1_usb>; @@ -32,16 +37,53 @@ }; / { + aliases { + /* aura copies the ATC PHY's tunables from ADT atc-phy2 here. */ + atcphy2 = &atc2_phy; + }; + soc { + dwc3_1_dart_1: iommu@40b040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x4 0x0b040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc1_usb>; + }; + + usb1: usb@40a430000 { + compatible = "apple,t8152-dwc3"; + reg = <0x4 0x0a430000 0x0 0xcd00>; + interrupts = ; + dr_mode = "host"; + maximum-speed = "high-speed"; + iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; + power-domains = <&ps_atc1_usb>; + snps,dis_u2_susphy_quirk; + snps,dis_u3_susphy_quirk; + }; + + dwc3_2_dart_1: iommu@383040000 { + compatible = "apple,t8152-dart", "apple,t8110-dart"; + reg = <0x3 0x83040000 0x0 0xc000>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_atc2_usb>; + }; + /* - * The ATCs' PMGR power states (ADT pmgr devices ATCn_USB_AON and - * ATCn_USB from 0x308290100, 0x40 apart per ATC). The ADT gives - * usb-drd1/2 service-gates 175/176, but those PSD service blocks - * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. + * The ATCs' PMGR power states (ADT pmgr devices ATCn_COMMON_DP_0/1 + * from 0x308290000 and ATCn_USB_AON/USB from 0x308290100, 0x40 + * apart per ATC). The T8152 USB bring-up runs them without + * automatic power management. * - * The loader leaves them on; they hold the controllers' reset and - * the USB2 PHY setup it did, which Linux cannot redo yet. So they - * stay on, without automatic power management. + * ATCn_USB is the controller's state. The ADT also gives + * usb-drd1/2 service-gates 175/176, but those PSD service blocks + * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. The + * loader leaves ATCn_USB and ATCn_USB_AON on; they hold the + * controllers' reset and the USB2 PHY setup it did, which Linux + * cannot redo yet, so they stay on. ATC2_COMMON_DP_0/1 are what + * ATC2's PHY needs besides. */ pmgr_atc: power-management@308290000 { compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", @@ -50,6 +92,26 @@ #size-cells = <1>; reg = <0x3 0x08290000 0x0 0x1000>; + ps_atc2_common_dp_0: power-controller@80 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc2_common_dp_1: power-controller@a0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xa0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_common_dp_1"; + apple,no-auto-pm; + }; + ps_atc1_usb_aon: power-controller@140 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -73,6 +135,11 @@ apple,always-on; }; + /* + * Kept on: it holds the USB controller's reset and the + * PIPE handler state the loader set up. Switched off, the + * controller stays in reset until the next boot. + */ ps_atc2_usb_aon: power-controller@180 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -97,32 +164,34 @@ }; }; - dwc3_1_dart_1: iommu@40b040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x4 0x0b040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - power-domains = <&ps_atc1_usb>; + /* ATC2's common domain: PSD service 57 (ADT atc-phy2 clock-gates). */ + ps_atc2_common: power-controller@303a13900 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13900 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc2_common"; }; - usb1: usb@40a430000 { - compatible = "apple,t8152-dwc3"; - reg = <0x4 0x0a430000 0x0 0xcd00>; - interrupts = ; - dr_mode = "host"; - maximum-speed = "high-speed"; - iommus = <&dwc3_1_dart 0>, <&dwc3_1_dart_1 1>; - power-domains = <&ps_atc1_usb>; - snps,dis_u2_susphy_quirk; - snps,dis_u3_susphy_quirk; - }; - - dwc3_2_dart_1: iommu@383040000 { - compatible = "apple,t8152-dart", "apple,t8110-dart"; - reg = <0x3 0x83040000 0x0 0xc000>; - interrupts = ; - #iommu-cells = <1>; - power-domains = <&ps_atc2_usb>; + /* + * ADT atc-phy2 as usb-drd2's USB3 PHY: the hub is wired to its + * lanes directly. The power domains are listed in the order the + * PHY needs them powered up. Its tunables are the atc-phy2 + * tunable_* groups that apply to USB3 on lane 0, applied as + * common-a before lane 0 is powered up and the crossbar set, then + * common-b and lane0-usb. Some of them differ between the four + * ATCs of the same Mac (calibration), so the bootloader copies + * them from the Mac's own ADT, through the atcphy2 alias. Without + * them the PHY runs USB2 only. + */ + atc2_phy: phy@383000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x3 0x83000000 0x0 0x84000>, + <0x3 0x82414000 0x0 0x4000>; + reg-names = "core", "pipehandler"; + #phy-cells = <1>; + apple,fixed-usb3; + power-domains = <&ps_atc2_usb_aon>, <&ps_atc2_common>, + <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; }; /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ @@ -131,7 +200,8 @@ reg = <0x3 0x82430000 0x0 0xcd00>; interrupts = ; dr_mode = "host"; - maximum-speed = "high-speed"; + phys = <&atc2_phy PHY_TYPE_USB3>; + phy-names = "usb3-phy"; iommus = <&dwc3_2_dart 0>, <&dwc3_2_dart_1 1>; power-domains = <&ps_atc2_usb>; snps,dis_u2_susphy_quirk; From 2695b857a56d8cebfdd858be221fcd61987d9cb1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0961/1514] dt-bindings: apple: describe T8142 USB4 and PCIe-C Allow the five ACIO register windows, LSTX GPIO and router firmware tunables used by T8142. Describe its native PCIe-C compatible and require the shared MSI vector base. Include the T8142 pinctrl fallback chain used by the AOP LSTX pin. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/pci/apple,pcie.yaml | 3 +++ .../thunderbolt/apple,t8103-usb4-acio.yaml | 27 +++++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/pci/apple,pcie.yaml b/Documentation/devicetree/bindings/pci/apple,pcie.yaml index a9fd4822fd1272..06405f7179fe8c 100644 --- a/Documentation/devicetree/bindings/pci/apple,pcie.yaml +++ b/Documentation/devicetree/bindings/pci/apple,pcie.yaml @@ -101,6 +101,7 @@ properties: - const: apple,t8103-pciec - const: apple,t6000-pciec - const: apple,t6050-pciec + - const: apple,t8142-pciec - items: - const: apple,t8132-pciec - const: apple,t8122-pciec @@ -374,6 +375,7 @@ allOf: contains: enum: - apple,t8132-pciec + - apple,t8142-pciec - apple,t6040-pciec then: required: @@ -501,6 +503,7 @@ allOf: - apple,t6000-pciec - apple,t6040-pciec - apple,t6050-pciec + - apple,t8142-pciec then: properties: reg: diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml index 01592811223d23..29c64e3b3c33e4 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml @@ -52,8 +52,8 @@ properties: PCIe adapter configuration space of the USB4 router. Present where the root complex exposes the adapter separately, so that the tunnel can be configured before a PCIe-C link is brought up. - - description: MxWrap co-processor control registers, on T8132 and T6050 - - description: PCIe router AP firmware registers, on T6050 + - description: MxWrap co-processor control registers, on T8132, T8142 and T6050 + - description: PCIe router AP firmware registers, on T8142 and T6050 reg-names: oneOf: @@ -253,6 +253,7 @@ allOf: enum: - apple,t6040-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio then: properties: reg: @@ -267,6 +268,7 @@ allOf: - apple,t6040-usb4-acio - apple,t6050-usb4-acio - apple,t8132-usb4-acio + - apple,t8142-usb4-acio then: properties: pinctrl-names: @@ -309,7 +311,28 @@ allOf: properties: power-domains: maxItems: 4 + - if: + properties: + compatible: + not: + contains: + enum: + - apple,t6050-usb4-acio + - apple,t8142-usb4-acio + then: + properties: apple,tunable-router-ap-fw: false + - if: + properties: + compatible: + contains: + const: apple,t8142-usb4-acio + then: + properties: + reg: + minItems: 5 + reg-names: + minItems: 5 additionalProperties: false From 3287c55d219c7380b65ddee2771315b443ae41bb Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 14:31:49 +0100 Subject: [PATCH 0962/1514] PCI: apple: support T8142 PCIe-C MSI slices T8142 uses the Intr2AXI controller layout but its three-cell AIC interrupt specifier and MSI window differ from T6050. Match it natively. This allows a tunnelled NVMe controller to allocate working MSI-X interrupts. For T8132 and T8142 the slice is checked against the device tree alone. msi-ranges names the AIC input of global vector apple,msi-vector-base in a linear window, so the window's AIC base is msi-ranges minus apple,msi-vector-base, and the slice is checked by its shape: an edge-rising SPI, 32 vectors, 32-aligned, above the internal port's vectors and inside the 8-bit map target. This replaces T8132's table of ECAM apertures and its AIC base 1506 behind a machine check. The T8132 trees give 1602 - 0x60 = 1634 - 0x80 = 1506, and every J813 PCIe node gives 1741. Signed-off-by: Thomas Glanzmann --- drivers/pci/controller/pcie-apple.c | 53 ++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 8d7e9e72aabdab..467bc38a9af24b 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -481,6 +481,22 @@ static const struct hw_info t6050_pciec_hw = { .s2idle_hold_domain = true, }; +/* T8142 shares this register layout, with its own three-cell AIC MSI slice. */ +static const struct hw_info t8142_pciec_hw = { + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = PORT_MSIADDR + 4, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = PORT_T602X_MSIMAP, + .port_tunctrl = PORT_T6050_TUNCTRL, + .max_rid2sid = 256, + .tunneled = true, + .tunnel_intr2axi = true, + .no_port_reset = true, + .msimap_by_vector = true, + .mps_timers = true, +}; + static const struct of_device_id apple_pcie_of_match[]; /** @@ -3394,8 +3410,25 @@ static int apple_msi_init(struct apple_pcie *pcie) * 32-vector slice. Keep endpoint MSI data local, and route its table * entry to the corresponding shared-window vector. */ - if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) { + if (pcie->hw == &t8132_pciec_hw || pcie->hw == &t8142_pciec_hw) { + /* + * msi-ranges names the AIC input of global vector + * apple,msi-vector-base in a linear window, so the slice is + * checked by its shape only: an edge-rising SPI, 32 vectors, + * 32-aligned, above the internal port's vectors and inside the + * 8-bit map target. + */ + if (args.args_count != 3 || args.args[0] != 0 || + args.args[2] != IRQ_TYPE_EDGE_RISING || + of_property_read_u32(to_of_node(fwnode), + "apple,msi-vector-base", + &pcie->msi_vector_base) || + args.args[1] < pcie->msi_vector_base || + !apple_t6030_msi_slice_valid(pcie->msi_vector_base, + pcie->nvecs, args.args[1], + args.args[1] - pcie->msi_vector_base)) + goto invalid_slice; + } else if (pcie->hw == &t8122_pciec_hw || pcie->hw == &t6040_pciec_hw) { struct resource ecam; u32 expected_base, aic_base; @@ -3432,19 +3465,6 @@ static int apple_msi_init(struct apple_pcie *pcie) default: goto invalid_slice; } - } else if (of_machine_is_compatible("apple,t8132")) { - aic_base = 1506; - switch (ecam.start) { - /* The internal port's bridges own vectors 0..95. */ - case 0x1c50000000ULL: - expected_base = 0x60; - break; - case 0x1c60000000ULL: - expected_base = 0x80; - break; - default: - goto invalid_slice; - } } else { goto invalid_slice; } @@ -3478,7 +3498,7 @@ static int apple_msi_init(struct apple_pcie *pcie) /* Keep map targets within the supported 8-bit range. */ if ((pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw) && + pcie->hw == &t6040_pciec_hw || pcie->hw == &t8142_pciec_hw) && (!pcie->nvecs || pcie->nvecs > 256 || pcie->msi_vector_base > FIELD_MAX(PORT_MSIMAP_TARGET) + 1 - pcie->nvecs)) { @@ -7588,6 +7608,7 @@ static const struct dev_pm_ops apple_pcie_pm_ops = { static const struct of_device_id apple_pcie_of_match[] = { { .compatible = "apple,t6040-pciec", .data = &t6040_pciec_hw }, { .compatible = "apple,t6050-pciec", .data = &t6050_pciec_hw }, + { .compatible = "apple,t8142-pciec", .data = &t8142_pciec_hw }, { .compatible = "apple,t8132-pciec", .data = &t8132_pciec_hw }, { .compatible = "apple,t8122-pciec", .data = &t8122_pciec_hw }, { .compatible = "apple,t8112-pciec", .data = &t8112_pciec_hw }, From 587148e89fe179e422657c6fb4b85f2f1cd2f015 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:58:23 +0100 Subject: [PATCH 0963/1514] dt-bindings: mailbox: apple,mailbox: add the T8152 ACIO mailbox Each T8152 USB4 router's coprocessor has a 0x80-byte mailbox window with the counted FIFOs of the SMC mailbox, at offset 0x80 of its register block. Describe it with apple,t8152-smc-mailbox as the fallback, so the SMC mailbox's match data serves it, and with its send-empty and recv-not-empty interrupts. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/mailbox/apple,mailbox.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 7626c8afcedbd6..caa9e431a4a101 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -44,6 +44,14 @@ properties: recv-not-empty interrupts. const: apple,t8152-ascwrap-v8-mailbox + - description: + T8152 ACIO mailbox of a USB4 router's coprocessor, a 0x80 window + with the counted FIFOs of the SMC mailbox, described with its + send-empty and recv-not-empty interrupts. + items: + - const: apple,t8152-cio-mailbox + - const: apple,t8152-smc-mailbox + - description: ASC mailboxes are the most common variant found on the M1 used for example for the display controller, the system management From 71033d053323aea0b5378d6c0fd200bf67697337 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:08 +0100 Subject: [PATCH 0964/1514] dt-bindings: reset: apple,t8103-cio-reset: add T8152 The T8152 CIO reset block resets the rear USB4 routers of the J873g. It has a request and an acknowledge register instead of T8142's control register, so it gets its own compatible. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/reset/apple,t8103-cio-reset.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml b/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml index 3b05fab7e7af1c..f72d6e97577ccd 100644 --- a/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml +++ b/Documentation/devicetree/bindings/reset/apple,t8103-cio-reset.yaml @@ -38,6 +38,7 @@ properties: - enum: - apple,t8103-cio-reset - apple,t8142-cio-reset + - apple,t8152-cio-reset - apple,t6050-cio-reset - apple,t6000-cio-reset - apple,t6041-cio-reset From bc0c7fd7ce336e756a7a938b668e5c7317c3612d Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:09 +0100 Subject: [PATCH 0965/1514] reset: apple-cio: add T8152 The T8152 CIO reset block requests a router reset in register 0x68 and acknowledges it in 0x6c. Wait for the router's pair of busy bits to clear, request, wait for the acknowledgment and clear it. Signed-off-by: Thomas Glanzmann --- drivers/reset/reset-apple-cio.c | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/drivers/reset/reset-apple-cio.c b/drivers/reset/reset-apple-cio.c index e5755ebb39affb..1a023b41051feb 100644 --- a/drivers/reset/reset-apple-cio.c +++ b/drivers/reset/reset-apple-cio.c @@ -77,6 +77,15 @@ #define T8142_CIO_CTRL_INIT_BUSY(port) BIT(2 * (port) + 1) #define T8142_CIO_CTRL_BUSY_MASK 0xaa +/* T8152: the request and its completion are in two registers, one bit per port. */ +#define T8152_CIO_INIT_REQ 0x68 +#define T8152_CIO_INIT_DONE 0x6c +/* A request waits until none of its port pair (0-1 or 2-3) is pending. */ +#define T8152_CIO_INIT_PAIR_MASK(port) ((port) < 2 ? GENMASK(1, 0) : GENMASK(3, 2)) +#define T8152_CIO_POLL_US 10 +/* As long as a t6050 reconfiguration. */ +#define T8152_CIO_TIMEOUT_US APPLE_CIO_RESET_T6050_TIMEOUT_US + struct apple_cio_reset; struct apple_cio_reset_variant { @@ -200,6 +209,34 @@ static int t8142_cio_deassert(struct apple_cio_reset *priv, unsigned long id) APPLE_CIO_RESET_TIMEOUT_US); } +static int t8152_cio_deassert(struct apple_cio_reset *priv, unsigned long id) +{ + u32 val; + int ret; + + guard(mutex)(&priv->lock); + ret = regmap_read_poll_timeout(priv->regmap, T8152_CIO_INIT_REQ, val, + !(val & T8152_CIO_INIT_PAIR_MASK(id)), + T8152_CIO_POLL_US, T8152_CIO_TIMEOUT_US); + if (ret) + return ret; + ret = regmap_write(priv->regmap, T8152_CIO_INIT_REQ, BIT(id)); + if (ret) + return ret; + ret = regmap_read_poll_timeout(priv->regmap, T8152_CIO_INIT_DONE, val, + val & BIT(id), T8152_CIO_POLL_US, + T8152_CIO_TIMEOUT_US); + if (ret) + return ret; + /* Acknowledge the completion. */ + return regmap_write(priv->regmap, T8152_CIO_INIT_DONE, BIT(id)); +} + +static const struct apple_cio_reset_variant apple_t8152_cio_reset = { + .nr_resets = 4, + .deassert = t8152_cio_deassert, +}; + static const struct apple_cio_reset_variant apple_t8142_cio_reset = { .nr_resets = 4, .ctrl = T8142_CIO_CTRL, @@ -330,6 +367,7 @@ static int apple_cio_reset_probe(struct platform_device *pdev) } static const struct of_device_id apple_cio_reset_match[] = { + { .compatible = "apple,t8152-cio-reset", .data = &apple_t8152_cio_reset }, { .compatible = "apple,t6050-cio-reset", .data = &apple_t6050_cio_reset, From 14ebf73c98d0b072f2fddc4c474ab944e2e8cb66 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:09 +0100 Subject: [PATCH 0966/1514] dt-bindings: iommu: apple,dart: add the T8152 ACIO and PCIe-C DARTs The DARTs of the J873g rear USB4 routers (NHI streams) and of their PCIe-C tunnels are Gen3 DARTs like the display ones, but start unlocked with inactive streams. Each has its own slot in the shared TLB invalidation aperture and its DMA window. Their tunables are the ADT's (dart-acioN, dart-apciecN), which the bootloader copies into the node, so the binding does not require them in a device tree. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/iommu/apple,dart.yaml | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/iommu/apple,dart.yaml b/Documentation/devicetree/bindings/iommu/apple,dart.yaml index 3a8a8c64fb8c22..252c44db78c4d2 100644 --- a/Documentation/devicetree/bindings/iommu/apple,dart.yaml +++ b/Documentation/devicetree/bindings/iommu/apple,dart.yaml @@ -33,6 +33,8 @@ properties: - apple,t8110-dart - apple,t6000-dart - apple,t8152-dart-gen3 + - apple,t8152-acio-dart + - apple,t8152-pciec-dart - apple,t8152-avd-dart - items: - const: apple,t8140-ane-dart @@ -384,6 +386,8 @@ allOf: contains: enum: - apple,t8152-dart-gen3 + - apple,t8152-acio-dart + - apple,t8152-pciec-dart - apple,t8152-avd-dart then: description: @@ -392,9 +396,12 @@ allOf: locked, and the operating system only adds page table entries in root slots that are empty at handoff. Their TLB command register answers translation queries; a stream is invalidated through the - TLB invalidation aperture instead. The T8152 AVD instance uses the - same invalidation aperture, but starts unlocked with inactive streams - and is initialized by the operating system after its PSD domain is on. + TLB invalidation aperture instead. The DARTs of the rear USB4 + routers (ACIO NHI streams) and of their PCIe-C tunnels use the same + invalidation aperture, each at its own slot, but start unlocked with + inactive streams and are initialized by the operating system. + The T8152 AVD instance uses the same aperture, starts unlocked with + inactive streams and is initialized after its PSD domain is on. properties: reg: minItems: 2 @@ -423,6 +430,19 @@ allOf: - apple,dma-range - apple,tunable + - if: + properties: + compatible: + contains: + enum: + - apple,t8152-acio-dart + - apple,t8152-pciec-dart + then: + # apple,tunable: the bootloader copies it from the ADT (dart-acioN, + # dart-apciecN); a device tree describes these DARTs without one. + required: + - apple,dma-range + additionalProperties: false examples: From 4859b9ff963ab2dbab4d40c1f7ad7309dbefc3ba Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Mon, 23 Nov 2026 05:28:27 +0100 Subject: [PATCH 0967/1514] iommu: apple-dart: initialize the cold T8152 ACIO and PCIe-C DARTs The DARTs of the T8152 USB4 routers and their PCIe-C tunnels are Gen3 DARTs that, unlike the display ones, the bootloader leaves unlocked with inactive streams, as it does the AVD instance. Extend the AVD instance's cold Gen3 setup to them: version 0x300, their tunables and inactive streams, then clear the streams, apply the tunables and invalidate through the Gen3 TLBI aperture before translation is enabled. Domains use the same two-level 16K tables inside a single 64 GiB DMA window. The streams the operating system sets up now come from a mask per instance: - AVD DART (apple,t8152-avd-dart): streams 0-2, the decoder's, with its 16 streams and its power domain checked as before. Its stream enable becomes a read-modify-write like the others', and other stream IDs are refused when a consumer attaches. - ACIO DART (apple,t8152-acio-dart): 32 streams, NHI streams 0-11 and 16-27. - PCIe-C DART (apple,t8152-pciec-dart): translated streams 0-252, with 253 and 255 in bypass for host transactions and MSI writes to the AIC (the ADT reserves them), firmware's stream 254 preserved, 16K pages, 42-bit addresses; it must be tunnelled and have its power domain. Without the bypass on 255, NVMe completions were polled and the DART faulted at the AIC. Each DART invalidates through the TLBI slot its "tlbi" resource names. The slot has to be the port's own: with port 3's slot on port 1's DART, reads returned wrong data with DART faults. The locked display DARTs and all other Gen3 instances stay as they were. Signed-off-by: Thomas Glanzmann --- drivers/iommu/apple-dart.c | 83 +++++++++++++++++-- .../drivers/apple/bcm4377-radio-sids.py | 3 +- 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bf7a4fc0807faa..23e436e29392ce 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -362,6 +362,8 @@ struct apple_dart_fw_tree { struct apple_dart { bool cold_gen3; + u32 cold_gen3_sids; + bool cold_gen3_pcie; struct device *dev; const struct apple_dart_hw *hw; @@ -2826,11 +2828,33 @@ static int apple_dart_hw_reset(struct apple_dart *dart) if (dart->cold_gen3) { stream_map.dart = dart; bitmap_zero(stream_map.sidmap, DART_MAX_STREAMS); - bitmap_set(stream_map.sidmap, 0, 3); + for (i = 0; i < 32; i++) + if (dart->cold_gen3_sids & BIT(i)) + __set_bit(i, stream_map.sidmap); + if (dart->cold_gen3_pcie) + bitmap_set(stream_map.sidmap, 0, 253); apple_dart_hw_disable_dma(&stream_map); apple_dart_hw_clear_all_ttbrs(&stream_map); apple_dart_apply_own_tunables(dart); - apple_dart_writel(dart, 7, dart->hw->enable_streams); + apple_dart_writel(dart, apple_dart_readl(dart, dart->hw->enable_streams) | + dart->cold_gen3_sids, dart->hw->enable_streams); + if (dart->cold_gen3_pcie) { + /* ADT reserves 253/255 for host transactions, including MSI + * writes to AIC. Stream 254 belongs to firmware; preserve it. + */ + for (i = 253; i <= 255; i += 2) { + apple_dart_writel(dart, DART_T8110_TCR_BYPASS_DART, + DART_TCR(dart, i)); + __set_bit(i, stream_map.sidmap); + } + for (i = 0; i < 8; i++) { + u32 reg = dart->hw->enable_streams + i * 4; + u32 enabled = apple_dart_readl(dart, reg); + + enabled |= i == 7 ? (U32_MAX & ~BIT(30)) : U32_MAX; + apple_dart_writel(dart, enabled, reg); + } + } return dart->hw->invalidate_tlb(&stream_map); } @@ -4198,6 +4222,9 @@ static int apple_dart_of_xlate(struct device *dev, return i; sid = args->args[0]; + if (dart->cold_gen3 && (dart->cold_gen3_pcie ? (sid < 0 || sid >= 253) : + (sid < 0 || sid >= 32 || !(dart->cold_gen3_sids & BIT(sid))))) + return -EPERM; if (dart->isp_host && sid != 0 && sid != 12) return -EINVAL; if (dart->cold_ane && sid != 0) @@ -5628,6 +5655,7 @@ static int apple_dart_probe(struct platform_device *pdev) of_node_name_prefix(dev->of_node->parent, "usb4-pcie-tunnel-"); bool j713_display, j713_dcpext, j713_dispext, j713_radio; + bool cold_avd = of_device_is_compatible(dev->of_node, "apple,t8152-avd-dart"); /* * The M4 internal display DARTs are live: DCP firmware (SID23) @@ -5729,7 +5757,20 @@ static int apple_dart_probe(struct platform_device *pdev) dart->dev = dev; dart->hw = of_device_get_match_data(dev); dart->tunneled = tunneled; - dart->cold_gen3 = of_device_is_compatible(dev->of_node, "apple,t8152-avd-dart"); + /* Streams 0-2 of the AVD instance, the ones the decoder uses. */ + if (cold_avd) { + dart->cold_gen3 = true; + dart->cold_gen3_sids = 0x7; + } + if (of_device_is_compatible(dev->of_node, "apple,t8152-acio-dart")) { + dart->cold_gen3 = true; + dart->cold_gen3_sids = 0x0fff0fff; + } + if (of_device_is_compatible(dev->of_node, "apple,t8152-pciec-dart")) { + dart->cold_gen3 = true; + dart->cold_gen3_pcie = true; + dart->cold_gen3_sids = U32_MAX; + } dart->cold_ane = of_device_is_compatible(dev->of_node, "apple,t8140-ane-dart") || of_device_is_compatible(dev->of_node, "apple,t8142-ane-dart"); if (dart->cold_ane && !IS_BUILTIN(CONFIG_APPLE_DART)) @@ -5942,7 +5983,7 @@ static int apple_dart_probe(struct platform_device *pdev) ret = devm_pm_runtime_enable(dev); if (ret) goto err_clk_disable; - if (tunneled && dart->tunables) { + if (tunneled && dart->tunables && !dart->cold_gen3) { dev_dbg(dev, "applying %zu PCIe-C DART tunables\n", dart->tunables->sz); apple_dart_apply_tunables(dart, dart->tunables); @@ -5958,7 +5999,15 @@ static int apple_dart_probe(struct platform_device *pdev) * pages, a 32-bit IOVA, a 36-bit PA and as many streams as its * register block describes. */ - if (dart->hw->type == DART_T8110) { + if (dart->cold_gen3_pcie) { + dart->pgsize = SZ_16K; + dart->supports_bypass = true; + dart->ias = 42; + dart->oas = 42; + dart->num_streams = 256; + dart->four_level = false; + dart->version = 0x300; + } else if (dart->hw->type == DART_T8110) { dart->pgsize = 1 << DART_PCIEC_PAGE_SHIFT; dart->supports_bypass = true; dart->ias = DART_PCIEC_ADDR_WIDTH; @@ -6158,18 +6207,32 @@ static int apple_dart_probe(struct platform_device *pdev) if (dart->hw->gen3) { struct resource *tlbi; - /* Cold initialization is qualified only for the AVD instance. */ + /* Cold setup only for the instances a T8152 compatible selects. */ if (!dart->locked && !dart->cold_gen3) { dev_err(dev, "Gen3 DART is not locked; cold setup is not supported\n"); ret = -ENODEV; goto err_clk_disable; } - if (dart->cold_gen3 && (dart->locked || dart->version != 0x300 || - dart->num_streams != 16 || !dev->pm_domain || !dart->tunables || - (apple_dart_readl(dart, dart->hw->enable_streams) & 7))) { + if (dart->cold_gen3 && + (dart->locked || dart->version != 0x300 || !dart->tunables || + (dart->cold_gen3_pcie ? (!tunneled || !dev->pm_domain) : + cold_avd ? (dart->num_streams != 16 || !dev->pm_domain) : + dart->num_streams != 32) || + (apple_dart_readl(dart, dart->hw->enable_streams) & dart->cold_gen3_sids))) { ret = -EINVAL; goto err_clk_disable; } + if (dart->cold_gen3_pcie) { + for (sid = 0; sid < 8; sid++) { + u32 mask = sid == 7 ? GENMASK(28, 0) : U32_MAX; + u32 reg = dart->hw->enable_streams + sid * 4; + + if (apple_dart_readl(dart, reg) & mask) { + ret = -EBUSY; + goto err_clk_disable; + } + } + } /* The aperture is shared by every Gen3 DART: map, do not claim. */ tlbi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "tlbi"); if (!tlbi || resource_size(tlbi) < 16) { @@ -7599,6 +7662,8 @@ static const struct dev_pm_ops apple_dart_pm_ops = { static const struct of_device_id apple_dart_of_match[] = { { .compatible = "apple,t8152-dart-gen3", .data = &apple_dart_hw_gen3 }, { .compatible = "apple,t8152-avd-dart", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-acio-dart", .data = &apple_dart_hw_gen3 }, + { .compatible = "apple,t8152-pciec-dart", .data = &apple_dart_hw_gen3 }, { .compatible = "apple,t8103-dart", .data = &apple_dart_hw_t8103 }, { .compatible = "apple,t8103-usb4-dart", .data = &apple_dart_hw_t8103_usb4 }, { .compatible = "apple,t8110-dart", .data = &apple_dart_hw_t8110 }, diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index e9166c1f40abc7..bf0ffb0b06e980 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -115,7 +115,8 @@ def main(): bool four_level, per_stream, tunneled, fw_mirror, fw_handoff; bool pending, preserve_display; bool isp_host, cold_ane, live_mtp, display_dark, display_tlb_stale; - bool cold_gen3; + bool cold_gen3, cold_gen3_pcie; + u32 cold_gen3_sids; void *tunables; unsigned long static_bypass[4]; void *dcp, *frontend[2]; From 097d8ff388f1b2d960750dd73cd2ce31c0b3ab66 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:09 +0100 Subject: [PATCH 0968/1514] dt-bindings: pci: apple,pcie: add T8152 PCIe-C The PCIe-C ports tunnelled through the J873g rear USB4 routers are laid out like T8142's: Intr2AXI MSI slices, the T6050 tunnel controls, and no port reset of their own. Signed-off-by: Thomas Glanzmann --- Documentation/devicetree/bindings/pci/apple,pcie.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Documentation/devicetree/bindings/pci/apple,pcie.yaml b/Documentation/devicetree/bindings/pci/apple,pcie.yaml index 06405f7179fe8c..70700cb86b839d 100644 --- a/Documentation/devicetree/bindings/pci/apple,pcie.yaml +++ b/Documentation/devicetree/bindings/pci/apple,pcie.yaml @@ -102,6 +102,7 @@ properties: - const: apple,t6000-pciec - const: apple,t6050-pciec - const: apple,t8142-pciec + - const: apple,t8152-pciec - items: - const: apple,t8132-pciec - const: apple,t8122-pciec @@ -376,6 +377,7 @@ allOf: enum: - apple,t8132-pciec - apple,t8142-pciec + - apple,t8152-pciec - apple,t6040-pciec then: required: @@ -504,6 +506,7 @@ allOf: - apple,t6040-pciec - apple,t6050-pciec - apple,t8142-pciec + - apple,t8152-pciec then: properties: reg: From 7dd09daa4ec79b83b9f82e01fd304a10324c89d2 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Thu, 19 Nov 2026 19:59:15 +0100 Subject: [PATCH 0969/1514] PCI: apple: add T8152 PCIe-C The T8152 tunnelled PCIe-C ports use the T6050 tunnel controls with the Intr2AXI MSI path, like T8142, and their MSI slices are checked the same way: from msi-ranges and apple,msi-vector-base alone. The J873g's three bridges use 0x60 (CIO0, ECAM 0x1c50000000), 0x80 (CIO1, 0x1c60000000) and 0xc0 (CIO3, 0x1c80000000) of the window at AIC 1879. Signed-off-by: Thomas Glanzmann --- drivers/pci/controller/pcie-apple.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 467bc38a9af24b..602a4fee07b3ee 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -497,6 +497,22 @@ static const struct hw_info t8142_pciec_hw = { .mps_timers = true, }; +/* T8152 PCIe-C: the T8142 layout, with a third PCIe-C bridge (CIO3). */ +static const struct hw_info t8152_pciec_hw = { + .port_msiaddr = PORT_MSIADDR, + .port_msiaddr_hi = PORT_MSIADDR + 4, + .port_perst = PORT_PERST, + .port_rid2sid = PORT_RID2SID, + .port_msimap = PORT_T602X_MSIMAP, + .port_tunctrl = PORT_T6050_TUNCTRL, + .max_rid2sid = 256, + .tunneled = true, + .tunnel_intr2axi = true, + .no_port_reset = true, + .msimap_by_vector = true, + .mps_timers = true, +}; + static const struct of_device_id apple_pcie_of_match[]; /** @@ -3410,7 +3426,8 @@ static int apple_msi_init(struct apple_pcie *pcie) * 32-vector slice. Keep endpoint MSI data local, and route its table * entry to the corresponding shared-window vector. */ - if (pcie->hw == &t8132_pciec_hw || pcie->hw == &t8142_pciec_hw) { + if (pcie->hw == &t8132_pciec_hw || pcie->hw == &t8142_pciec_hw || + pcie->hw == &t8152_pciec_hw) { /* * msi-ranges names the AIC input of global vector * apple,msi-vector-base in a linear window, so the slice is @@ -3498,7 +3515,8 @@ static int apple_msi_init(struct apple_pcie *pcie) /* Keep map targets within the supported 8-bit range. */ if ((pcie->hw == &t8122_pciec_hw || pcie->hw == &t8132_pciec_hw || - pcie->hw == &t6040_pciec_hw || pcie->hw == &t8142_pciec_hw) && + pcie->hw == &t6040_pciec_hw || pcie->hw == &t8142_pciec_hw || + pcie->hw == &t8152_pciec_hw) && (!pcie->nvecs || pcie->nvecs > 256 || pcie->msi_vector_base > FIELD_MAX(PORT_MSIMAP_TARGET) + 1 - pcie->nvecs)) { @@ -7609,6 +7627,7 @@ static const struct of_device_id apple_pcie_of_match[] = { { .compatible = "apple,t6040-pciec", .data = &t6040_pciec_hw }, { .compatible = "apple,t6050-pciec", .data = &t6050_pciec_hw }, { .compatible = "apple,t8142-pciec", .data = &t8142_pciec_hw }, + { .compatible = "apple,t8152-pciec", .data = &t8152_pciec_hw }, { .compatible = "apple,t8132-pciec", .data = &t8132_pciec_hw }, { .compatible = "apple,t8122-pciec", .data = &t8122_pciec_hw }, { .compatible = "apple,t8112-pciec", .data = &t8112_pciec_hw }, From 58a5cb1b60b18a7967c8da736675ad725cebef8f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:09 +0100 Subject: [PATCH 0970/1514] dt-bindings: thunderbolt: add the T8152 USB4 routers Add the T8152 ACIO and NHI. The T8152 router CPU is started by a reconfiguration request through its mailbox, so it has no cpu window. A second range maps the shared Gen3 TLB invalidation aperture for the router's DART. Signed-off-by: Thomas Glanzmann --- .../thunderbolt/apple,t8103-usb4-acio.yaml | 30 +++++++++++++++++-- .../thunderbolt/apple,t8103-usb4-nhi.yaml | 3 ++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml index 29c64e3b3c33e4..70a883b4696fe7 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-acio.yaml @@ -30,6 +30,7 @@ properties: oneOf: - const: apple,t8103-usb4-acio - const: apple,t8142-usb4-acio + - const: apple,t8152-usb4-acio - const: apple,t6040-usb4-acio - const: apple,t6050-usb4-acio - items: @@ -69,6 +70,14 @@ properties: - const: rc - const: sram - const: cpu + - description: + T8152, whose router CPU is started by a reconfiguration request + through its mailbox and has no window of its own + items: + - const: rc + - const: sram + - const: pcie-adapter + - const: router-ap-fw mboxes: maxItems: 1 @@ -185,8 +194,12 @@ properties: const: 1 ranges: - maxItems: 1 - description: Single 16 MiB MMIO window containing all child registers + minItems: 1 + maxItems: 2 + description: + 16 MiB MMIO window containing the child registers. On T8152 a second + range maps the shared Gen3 DART TLB invalidation aperture for the + router's DART. nonposted-mmio: true @@ -254,12 +267,23 @@ allOf: - apple,t6040-usb4-acio - apple,t8132-usb4-acio - apple,t8142-usb4-acio + - apple,t8152-usb4-acio then: properties: reg: minItems: 4 reg-names: minItems: 4 + - if: + properties: + compatible: + not: + contains: + const: apple,t8152-usb4-acio + then: + properties: + ranges: + maxItems: 1 - if: properties: compatible: @@ -269,6 +293,7 @@ allOf: - apple,t6050-usb4-acio - apple,t8132-usb4-acio - apple,t8142-usb4-acio + - apple,t8152-usb4-acio then: properties: pinctrl-names: @@ -319,6 +344,7 @@ allOf: enum: - apple,t6050-usb4-acio - apple,t8142-usb4-acio + - apple,t8152-usb4-acio then: properties: apple,tunable-router-ap-fw: false diff --git a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml index 28718fed167c5d..c68f883b10d0f9 100644 --- a/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml +++ b/Documentation/devicetree/bindings/thunderbolt/apple,t8103-usb4-nhi.yaml @@ -22,6 +22,7 @@ properties: oneOf: - const: apple,t8103-usb4-nhi - const: apple,t8142-usb4-nhi + - const: apple,t8152-usb4-nhi - const: apple,t6040-usb4-nhi - const: apple,t6050-usb4-nhi - items: @@ -131,6 +132,7 @@ allOf: contains: enum: - apple,t8142-usb4-nhi + - apple,t8152-usb4-nhi - apple,t6040-usb4-nhi - apple,t6050-usb4-nhi then: @@ -155,6 +157,7 @@ allOf: - apple,t8122-usb4-nhi - apple,t8132-usb4-nhi - apple,t8142-usb4-nhi + - apple,t8152-usb4-nhi - apple,t6040-usb4-nhi - apple,t6050-usb4-nhi then: From cfb210cf6260bc5601d95784340baccc8812d372 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 17 Nov 2026 23:21:09 +0100 Subject: [PATCH 0971/1514] thunderbolt: apple: support the T8152 routers The T8152 router is a Type 7 MXWrap-v2p3 that a reconfiguration request starts through its counted mailbox. Its DP IN path is not qualified. Release the CIO domains in reverse order and suspend each one synchronously, because deleting the device link only queues an idle request: the PHY reset and the next router start need them cold. Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/apple.c | 57 +++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 15 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index e21cf99212ebae..a22d8129a7b328 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -171,6 +171,8 @@ struct apple_cio_hw { bool gen4_link_recovery; /* Leave the host router's TMU to its firmware; host TMU constants. */ bool host_tmu; + /* Drain PSD runtime power-off before the PHY is reset or reused. */ + bool psd_power_cycle; const struct apple_dpin_policy *dp; }; @@ -206,6 +208,17 @@ static const struct apple_cio_hw apple_cio_t8132_hw = { .dp = &apple_dpin_m4, }; +/* MXWrap-v2p3 is started by reconfiguration, using its counted mailbox. */ +static const struct apple_cio_hw apple_cio_t8152_hw = { + .psd_power_cycle = true, + .type7 = true, + .lstx_after_boot = true, + .strict_fw_ready = true, + .no_host_clx = true, + .no_asym = true, + .dp = &apple_dpin_disabled, +}; + /* Type 7 uses its existing ready-state check and has no qualified DP route. */ static const struct apple_cio_hw apple_cio_t8142_hw = { .type7 = true, @@ -1305,7 +1318,8 @@ static void apple_cio_of_node_put(void *data) static bool apple_cio_pciec_eligible(const struct device_node *np) { - return of_device_is_compatible(np, "apple,t6040-pciec") || + return of_device_is_compatible(np, "apple,t8152-pciec") || + of_device_is_compatible(np, "apple,t6040-pciec") || of_device_is_compatible(np, "apple,t8103-pciec") || of_device_is_compatible(np, "apple,t6000-pciec") || of_device_is_compatible(np, "apple,t6050-pciec"); @@ -2591,7 +2605,8 @@ static int apple_nhi_probe(struct platform_device *pdev) /* The T6050 router is the Type 7 one released by a RUN store. */ if (acio->type7 != - (of_device_is_compatible(pdev->dev.of_node, "apple,t8142-usb4-nhi") || + (of_device_is_compatible(pdev->dev.of_node, "apple,t8152-usb4-nhi") || + of_device_is_compatible(pdev->dev.of_node, "apple,t8142-usb4-nhi") || of_device_is_compatible(pdev->dev.of_node, "apple,t6040-usb4-nhi") || of_device_is_compatible(pdev->dev.of_node, "apple,t6050-usb4-nhi")) || acio->hw->run_store != @@ -3097,6 +3112,7 @@ static const struct of_device_id apple_nhi_match[] = { { .compatible = "apple,t6050-usb4-nhi", }, + { .compatible = "apple,t8152-usb4-nhi" }, { .compatible = "apple,t8142-usb4-nhi", }, @@ -3307,6 +3323,26 @@ static void apple_cio_test_log_guards(struct apple_cio *acio) dev_info(acio->dev, "TEST sv6t7: ACIO stop, its domain links go next: PS_PROT%s\n", buf); } +static void apple_cio_release_domains(struct apple_cio *acio) +{ + int n, i, ret; + + for (n = 0; n < acio->pd_list->num_pds; n++) { + i = acio->hw->psd_power_cycle ? acio->pd_list->num_pds - 1 - n : n; + dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); + if (!acio->pd_list->pd_links[i]) + continue; + device_link_del(acio->pd_list->pd_links[i]); + acio->pd_list->pd_links[i] = NULL; + if (!acio->hw->psd_power_cycle) + continue; + /* Link removal only queues idle; finish it before returning. */ + ret = pm_runtime_suspend(acio->pd_list->pd_devs[i]); + if (ret < 0) + dev_warn(acio->dev, "PSD domain %d failed to suspend: %d\n", i, ret); + } +} + /** * apple_cio_stop - Stop and power down the ACIO complex * @acio: ACIO complex to stop @@ -3317,7 +3353,7 @@ static void apple_cio_test_log_guards(struct apple_cio *acio) */ static void apple_cio_stop(struct apple_cio *acio) { - int ret, i; + int ret; lockdep_assert_held(&acio->lock); if (!acio->current_cable_info) @@ -3342,12 +3378,7 @@ static void apple_cio_stop(struct apple_cio *acio) apple_cio_test_log_guards(acio); /* Finally, remove the links to the PD domains to power everything off */ - for (i = 0; i < acio->pd_list->num_pds; i++) { - if (acio->pd_list->pd_links[i]) - device_link_del(acio->pd_list->pd_links[i]); - acio->pd_list->pd_links[i] = NULL; - dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); - } + apple_cio_release_domains(acio); acio->current_cable_info = 0; acio->resume_link_failed = false; @@ -3608,12 +3639,7 @@ static int apple_cio_start(struct apple_cio *acio) acio->rtk = NULL; apple_cio_cpu_halt(acio); /* Cut power to reset the entire block */ - for (i = 0; i < acio->pd_list->num_pds; i++) { - if (acio->pd_list->pd_links[i]) - device_link_del(acio->pd_list->pd_links[i]); - acio->pd_list->pd_links[i] = NULL; - dev_pm_syscore_device(acio->pd_list->pd_devs[i], false); - } + apple_cio_release_domains(acio); return ret; } @@ -4773,6 +4799,7 @@ static const struct of_device_id apple_acio_match[] = { .compatible = "apple,t6050-usb4-acio", .data = &apple_cio_t6050_hw, }, + { .compatible = "apple,t8152-usb4-acio", .data = &apple_cio_t8152_hw }, { .compatible = "apple,t8142-usb4-acio", .data = &apple_cio_t8142_hw, From 8148fc35b924d3fd1f83c24228cb1aa82e69edbb Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:21:48 +0100 Subject: [PATCH 0972/1514] dt-bindings: phy: apple,atcphy: add the T8152 Type-C ports in CIO mode The J873g's three rear USB-C ports have T8152 ATC PHYs behind a Type-C mux, with a USB4 router behind each. Linux runs them in CIO (USB4) mode only for now: their DisplayPort alt mode is still driven by the display controllers, and their USB2 side by the bootloader. Allow a T8152 PHY without apple,fixed-usb3 for such a port: its core bank alone (the power and reset block at 0x60000 is part of it, and the display controllers map the same bank), the orientation and mode switches with port@0 to the connector's SuperSpeed port, the ATC's four power domains in power-up order, and the common and lane CIO tunables. The display controller takes the PHY through its DisplayPort PHY. Signed-off-by: Thomas Glanzmann --- .../devicetree/bindings/phy/apple,atcphy.yaml | 85 +++++++++++++++---- 1 file changed, 68 insertions(+), 17 deletions(-) diff --git a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml index d75c83d05d209d..1caaf7f6bae0a2 100644 --- a/Documentation/devicetree/bindings/phy/apple,atcphy.yaml +++ b/Documentation/devicetree/bindings/phy/apple,atcphy.yaml @@ -40,12 +40,17 @@ description: > DisplayPort also requires separate bootloader-provided calibration lists for that bank and the common configuration in the lpdptx region. - The T8152 variant is supported as the USB3 PHY of a fixed-USB3 port only, - see apple,fixed-usb3. It is described by its core and pipehandler banks; the - core bank also holds the USB controller's DARTs. Its power domains are the - ATC's PMGR power states and PSD service the PHY needs, in the order they are - powered up. Lane 0 is powered up and the crossbar set between the common-a - tunables and the others. + The T8152 variant is supported as the USB3 PHY of a fixed-USB3 port, see + apple,fixed-usb3, and as the PHY of a Type-C port in USB4/Thunderbolt + ("Converged IO", CIO) mode alone. Its core bank also holds the USB + controller's DARTs. Its power domains are the ATC's PMGR power states and + PSD service the PHY needs, in the order they are powered up. The lanes of + the mode are powered up and the crossbar set between the common-a tunables + and the others. A fixed-USB3 port is described by its core and pipehandler + banks. A Type-C port is described by its core bank alone: its DisplayPort + alternate mode is driven by the display controller, which takes the PHY + through its DisplayPort PHY (PHY_TYPE_DP) and has the PHY's power domains + powered while it drives it, and its USB2 side is left to the bootloader. allOf: - $ref: /schemas/usb/usb-switch.yaml# @@ -137,12 +142,14 @@ allOf: then: properties: reg: + minItems: 1 items: - description: PHY core with its power and reset block, which also holds the USB controller's DARTs - - description: USB3 PIPE interface controls + - description: USB3 PIPE interface controls (fixed-USB3 port) reg-names: + minItems: 1 items: - const: core - const: pipehandler @@ -189,11 +196,28 @@ allOf: then: properties: "#reset-cells": false - mode-switch: false - orientation-switch: false - ports: false - required: - - apple,fixed-usb3 + if: + required: + - apple,fixed-usb3 + then: + properties: + mode-switch: false + orientation-switch: false + ports: false + reg: + minItems: 2 + reg-names: + minItems: 2 + else: + properties: + reg: + maxItems: 1 + reg-names: + maxItems: 1 + required: + - mode-switch + - orientation-switch + - ports else: properties: apple,fixed-usb3: false @@ -382,11 +406,12 @@ properties: apple,fixed-usb3: type: boolean description: > - T8152 only, and required there. The port's SuperSpeed lanes go straight - to a USB3 device or hub, with no Type-C mux in between, so the PHY runs - USB3 on lane 0 from probe on and ignores mux and orientation changes. It - provides only the USB3 PHY of its USB controller, which is a host, and - leaves the controller's USB2 side and reset to the bootloader. + T8152 only. The port's SuperSpeed lanes go straight to a USB3 device or + hub, with no Type-C mux in between, so the PHY runs USB3 on lane 0 from + probe on and ignores mux and orientation changes. It provides only the + USB3 PHY of its USB controller, which is a host, and leaves the + controller's USB2 side and reset to the bootloader. Without it a T8152 + PHY is a Type-C port's, run in CIO mode alone. apple,dp-alt-mode: type: boolean @@ -704,4 +729,30 @@ examples: <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; /* The bootloader adds the tunables from the ADT. */ }; + + phy@413000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x13000000 0x0 0x84000>; + reg-names = "core"; + + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>, + <&ps_atc3_common_dp_0>, <&ps_atc3_common_dp_1>; + /* The bootloader adds the tunables from the ADT. */ + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + endpoint { + remote-endpoint = <&typec3_ss>; + }; + }; + }; + }; }; From f50b17d70a54f5e7f90a54c83858ab292776bdc1 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:02 +0100 Subject: [PATCH 0973/1514] phy: apple: atc: run the T8152 Type-C ports in CIO mode The J873g's three rear USB-C ports have T8152 ATC PHYs with a USB4 router behind each. Their DisplayPort alt mode is still programmed by the display driver (drm/apple's T8152 code), and their USB2 side is the bootloader's. Run such a PHY in CIO mode for a USB4 partner and leave it to the display driver otherwise, as a Type-C port of its own kind (cio_only, selected by the T8152 match data for a PHY without apple,fixed-usb3). The Type-C port driver sets the mux before it starts the router and after it stops it, as on T8142. CIO mode uses the T8152 layout of the fixed-USB3 support: the power and reset block at 0x60000 with the sync reset at 0x60030, the crossbar at 0x4c (USB4 0, USB4 swapped 1), no lane mode register. It differs from USB3 in that both lanes are powered up, one after the other, between the common-a tunables and the others (LFPS receivers 0x1e24 bits 12/16 and 14/18, then the lane controls at 0x1e18 and 0x1e1c out of sleep, unclamped and out of AHB reset), and in that a reversed plug sets the lane swap (bit 1 of 0x60008) next to the swapped crossbar, where T8142 leaves it clear. On the way down AUX is clamped (0x1e24 bit 10, sleeps 6 and 8 cleared) and both lanes' LFPS receivers are dropped before the lanes, as the T8152 CIO shutdown does: these always-on controls keep their state while the common block is off. The lanes are only touched while the register bus (0x60000 bit 3) is out of reset. This is the sequence the earlier port monitor ran, with which a rear port trained USB4 at 2 x 20 Gb/s and carried an NVMe enclosure at 16 GT/s x4. The PHY's four power domains (USB_AON, the common PSD service, DP_0, DP_1) are attached without device links. They are held while the PHY runs CIO mode, and dropped synchronously after the CIO shutdown, so that the common block goes cold before the next partner: a training from a powered common block asserted in the router's firmware. The PHY and the display driver take turns, explicitly: - The display driver powers the PHY's DP PHY on before it touches the PHY and off when it has let go of it. The DP PHY holds the domains for it and keeps CIO mode out: a USB4 mode change fails with -ETIMEDOUT, and the mux declares its timeouts transient, so the port driver retries until the display is gone. A DP PHY power-on in CIO mode fails with -EBUSY. - Either takes the PHY only when its power and reset block is as its power-up leaves it (0x60000 = 0x4, no sleep acknowledged, sync reset 0); CIO mode is refused otherwise. - A display the bootloader started has all four domains on and a busy block at probe. Its domains are then held for the display driver, which takes the PHY over, until its DP PHY goes off. Once DisplayPort moves into this driver, the DP PHY programs it itself, both modes switch under the PHY's lock and this arbitration goes away. Thunderbolt alt mode is refused on these ports for now: the T8152 routers have only been run with USB4 partners. The other SoCs are unchanged: the new paths are taken for a cio_only PHY or the T8152 generation only, and T8152 now sets has_usb4, which a fixed-USB3 port's tunable list does not consult. KUnit cases check the CIO lanes, crossbar and swap in both orientations, the power-down, the idle test and which Type-C states ask for CIO. The DCP host-test fixtures that compile the power-up and power-down get the new field. Signed-off-by: Thomas Glanzmann --- drivers/phy/apple/atc-test.c | 129 ++++- drivers/phy/apple/atc.c | 462 ++++++++++++++++-- .../selftests/drivers/apple/atc-t8132-usb3.py | 2 +- .../drivers/gpu/apple-dcp/dwc3/mocks.c | 2 +- .../selftests/drivers/gpu/apple-dcp/phy.py | 6 +- 5 files changed, 541 insertions(+), 60 deletions(-) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index 3edda0798b56ee..a98279e9a930ba 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -1493,8 +1493,8 @@ static void atcphy_test_t8152_lanes(struct kunit *test) atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB3); KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), - ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 | - ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(0) | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(0)); KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0x110U); KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB3), 0); @@ -1575,11 +1575,136 @@ static void atcphy_test_t8152_no_tunables(struct kunit *test) atcphy_test_t8152_untouched(test, atcphy); } +/* Both LFPS receivers of a lane on */ +static u32 atcphy_test_t8152_lfps(unsigned int lane) +{ + return ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane) | + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane); +} + +/* + * CIO on a rear port: both lanes powered up one after the other, the USB4 + * crossbar by the orientation, the lane swap for a reversed plug too, and on + * the way down both lanes clamped, their LFPS receivers off and AUX clamped. + */ +static void atcphy_test_t8152_cio_lanes(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 misc = ATCPHY_T8152_CFG_OFFSET + ATCPHY_MISC; + + atcphy->fixed_usb3 = false; + atcphy->cio_only = true; + for (int reversed = 0; reversed < 2; reversed++) { + atcphy->swap_lanes = reversed; + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE(0)); + writel(ACIOPHY_T8152_AON_LANE_CLAMP_EN, core + ACIOPHY_T8152_AON_LANE(1)); + writel(ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN, + core + ACIOPHY_T8152_AON_SLEEP_CTRL2); + writel(reversed ? 0 : ATCPHY_T8152_MISC_LANE_SWAP, core + misc); + writel(ACIOPHY_CROSSBAR_DP_SINGLE_PMA_UNK100 << 5 | ACIOPHY_CROSSBAR_DP_BOTH_PMA, + core + ACIOPHY_CROSSBAR_T8103); + + atcphy_lanes_up_t8152(atcphy, APPLE_ATCPHY_MODE_USB4); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(0)), + ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(1)), + ATCPHY_TEST_T8152_LANE0_UP); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN | + atcphy_test_t8152_lfps(0) | atcphy_test_t8152_lfps(1)); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), + (u32)ACIOPHY_CROSSBAR_DP_BOTH_PMA | reversed); + + KUNIT_EXPECT_EQ(test, atcphy_configure_lanes(atcphy, APPLE_ATCPHY_MODE_USB4), 0); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), (u32)reversed); + KUNIT_EXPECT_EQ(test, readl(core + misc), + reversed ? ATCPHY_T8152_MISC_LANE_SWAP : 0U); + + atcphy->mode = APPLE_ATCPHY_MODE_USB4; + writel(ATCPHY_POWER_APB_RESET_N, core + ctrl); + atcphy_lanes_down_t8152(atcphy); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(0)), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE(1)), + ACIOPHY_T8152_AON_LANE_CLAMP_EN); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_SLEEP_CTRL2), + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN); + atcphy->mode = APPLE_ATCPHY_MODE_OFF; + atcphy_test_t8152_untouched(test, atcphy); + } +} + +/* A lane power-down with the register bus in reset leaves the lanes alone */ +static void atcphy_test_t8152_lanes_bus_reset(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + + writel(ATCPHY_TEST_T8152_LANE0_UP, core + ACIOPHY_T8152_AON_LANE0); + writel(ATCPHY_POWER_CLAMP_EN, core + ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL); + atcphy_lanes_down_t8152(atcphy); + KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ATCPHY_TEST_T8152_LANE0_UP); +} + +/* Only USB4 in its own mode, and Thunderbolt, ask a CIO-only PHY for CIO */ +static void atcphy_test_cio_target_mode(struct kunit *test) +{ + struct typec_altmode dp = { .svid = USB_TYPEC_DP_SID }; + struct typec_altmode tbt = { .svid = USB_TYPEC_TBT_SID }; + struct enter_usb_data usb4 = { .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB4) }; + struct enter_usb_data usb3 = { .eudo = FIELD_PREP(EUDO_USB_MODE_MASK, EUDO_USB_MODE_USB3) }; + struct typec_mux_state state = { .mode = TYPEC_MODE_USB4, .data = &usb4 }; + + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_USB4); + state.data = &usb3; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.data = NULL; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.alt = &tbt; + state.mode = TYPEC_TBT_MODE; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_TBT); + state.alt = &dp; + state.mode = TYPEC_DP_STATE_D; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.alt = NULL; + state.mode = TYPEC_STATE_USB; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); + state.mode = TYPEC_STATE_SAFE; + KUNIT_EXPECT_EQ(test, atcphy_cio_target_mode(&state), APPLE_ATCPHY_MODE_OFF); +} + +/* The PHY is idle only as its power-up leaves it */ +static void atcphy_test_t8152_cio_idle(struct kunit *test) +{ + struct apple_atcphy *atcphy = atcphy_test_alloc_t8152(test); + void __iomem *core = atcphy->regs.core; + u32 ctrl = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_CTRL; + u32 stat = ATCPHY_T8152_CFG_OFFSET + ATCPHY_POWER_STAT; + + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + KUNIT_EXPECT_TRUE(test, atcphy_cio_idle(atcphy)); + /* the display driver's DisplayPort setup */ + writel(0x1b, core + ctrl); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); + writel(ATCPHY_POWER_CLAMP_EN, core + ctrl); + writel(ATCPHY_POWER_SLEEP_SMALL, core + stat); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); + writel(0, core + stat); + writel(ATCPHY_MISC_RESET_N, core + ATCPHY_T8152_SYNC_RESET); + KUNIT_EXPECT_FALSE(test, atcphy_cio_idle(atcphy)); +} + static struct kunit_case atcphy_t8152_test_cases[] = { KUNIT_CASE(atcphy_test_t8152_lanes), KUNIT_CASE(atcphy_test_t8152_no_tunables), KUNIT_CASE(atcphy_test_t8152_power), KUNIT_CASE(atcphy_test_t8152_pipe_lock), + KUNIT_CASE(atcphy_test_t8152_cio_lanes), + KUNIT_CASE(atcphy_test_t8152_lanes_bus_reset), + KUNIT_CASE(atcphy_test_cio_target_mode), + KUNIT_CASE(atcphy_test_t8152_cio_idle), {} }; diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 5ad986fb009ef9..383601a260496c 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -277,15 +277,19 @@ enum atcphy_lane_mode { ACIOPHY_T8152_BIST_OV2_LN0_UNK10) /* T8152 lane power controls in the always-on top block (ACIOPHY_TOP_AON_BLK) */ -#define ACIOPHY_T8152_AON_LANE0 0x1e18 +#define ACIOPHY_T8152_AON_LANE(n) (0x1e18 + 4 * (n)) +#define ACIOPHY_T8152_AON_LANE0 ACIOPHY_T8152_AON_LANE(0) #define ACIOPHY_T8152_AON_LANE_CLAMP_EN BIT(0) #define ACIOPHY_T8152_AON_LANE_SLEEP_SMALL BIT(1) #define ACIOPHY_T8152_AON_LANE_SLEEP_BIG BIT(2) #define ACIOPHY_T8152_AON_LANE_AHB_RESET_N BIT(5) #define ACIOPHY_T8152_AON_SLEEP_CTRL2 0x1e24 -#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0 BIT(12) -#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0 BIT(16) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_BIG BIT(6) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_SMALL BIT(8) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN BIT(10) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(n) BIT(12 + 2 * (n)) +#define ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(n) BIT(16 + 2 * (n)) #define ACIOPHY_SLEEP_CTRL 0x1b0 #define ACIOPHY_SLEEP_CTRL_TX_BIG GENMASK(1, 0) @@ -736,6 +740,10 @@ struct apple_atcphy; * first and its power-down asserts last, instead of * ATCPHY_MISC_RESET_N, or zero * @lane_swap: Lane swap bit in ATCPHY_MISC, or zero for ATCPHY_MISC_LANE_SWAP + * @cio_lane_swap: CIO (USB4) mode sets @lane_swap for a reversed plug as well, + * next to the swapped crossbar + * @typec_cio_only: On a Type-C port the PHY runs only CIO (USB4) mode, see + * apple_atcphy.cio_only * @has_usb4: A USB4/Thunderbolt controller sits behind the PHY * @usb2_only: Uses the USB2 subset unless its banked SuperSpeed resources exist * @usb2phy_sig_host: Host role field mask, or zero for the original layout @@ -774,6 +782,8 @@ struct atcphy_hw { u32 cfg_offset; u32 sync_reset; u32 lane_swap; + bool cio_lane_swap; + bool typec_cio_only; bool has_usb4; bool usb2_only; u32 usb2phy_sig_host; @@ -866,6 +876,16 @@ struct atcphy_cio_sleep { * on lane 0 from probe on and provides only the USB3 PHY of the * controller, which is a host; its USB2 side and its reset are * left to the bootloader + * @cio_only: A Type-C port on which the PHY runs CIO (USB4) mode alone + * (atcphy_hw.typec_cio_only): its DisplayPort mode is the display + * driver's, which powers the DP PHY while it drives the PHY itself, + * and its USB2 side is left to the bootloader. See + * atcphy_cio_mux_set(). + * @cio_pds: The power domains of a @cio_only PHY, in power-up order + * @cio_powered: The PHY holds @cio_pds for CIO mode + * @display_owned: The display driver drives a @cio_only PHY and holds @cio_pds + * through the DP PHY, or the bootloader left it driving a + * display, which the display driver takes over * @typec_mode: Mode the Type-C mux last asked for; a fixed-hub port returns to * it when the PHY is brought back up after a power-off * @host_active: dwc3 has selected host mode on the USB3 PHY; a fixed-hub port @@ -981,6 +1001,10 @@ struct apple_atcphy { bool dp_only; bool fixed_usb2; bool fixed_usb3; + bool cio_only; + struct dev_pm_domain_list *cio_pds; + bool cio_powered; + bool display_owned; enum atcphy_mode typec_mode; bool host_active; /* @@ -1358,33 +1382,45 @@ static inline u32 atcphy_lane_swap(const struct apple_atcphy *atcphy) return atcphy->hw->lane_swap ?: ATCPHY_MISC_LANE_SWAP; } +/* T8152: the lanes a mode runs on, lane 0 for USB3, both for CIO (USB4) */ +static unsigned int atcphy_lanes_t8152(enum atcphy_mode mode) +{ + return mode == APPLE_ATCPHY_MODE_USB4 || mode == APPLE_ATCPHY_MODE_TBT ? 2 : 1; +} + /* * T8152 keeps a lane's registers in AHB reset until the lane is powered up on - * its own, and they drop their tunables meanwhile. Power lane 0, the USB3 lane - * of a fixed-USB3 port, up after the common-a tunables: its LFPS receivers, - * then out of sleep, unclamped and out of AHB reset. Set the crossbar right - * after, before the remaining tunables, as the T8152 sequence does: 0x110 for - * USB3, i.e. USB3+DP with single PMA 0x008. atcphy_configure_lanes() writes the - * same value again later. + * its own, and they drop their tunables meanwhile. Power the lanes of the mode + * up after the common-a tunables, one after the other: lane 0, the USB3 lane + * of a fixed-USB3 port, and in CIO mode lane 1 too. Each gets its LFPS + * receivers, then goes out of sleep, unclamped and out of AHB reset. Set the + * crossbar right after, before the remaining tunables, as the T8152 sequence + * does: 0x110 for USB3, i.e. USB3+DP with single PMA 0x008, and 0 or 1 for + * CIO by the plug orientation. atcphy_configure_lanes() writes the same value + * again later. */ static void atcphy_lanes_up_t8152(struct apple_atcphy *atcphy, enum atcphy_mode mode) { const struct atcphy_mode_configuration *mode_cfg = atcphy_get_mode_config(atcphy, mode); - core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, - ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL_LN0); - udelay(1); - core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, - ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG_LN0); - udelay(1); - core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); - udelay(1); - core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); - udelay(1); - core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); - udelay(1); - core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); - udelay(1); + for (unsigned int lane = 0; lane < atcphy_lanes_t8152(mode); lane++) { + u32 ctrl = ACIOPHY_T8152_AON_LANE(lane); + + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane)); + udelay(1); + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane)); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + } core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_PROTOCOL | ACIOPHY_CROSSBAR_DP_SINGLE_PMA, @@ -1393,17 +1429,55 @@ static void atcphy_lanes_up_t8152(struct apple_atcphy *atcphy, enum atcphy_mode mode_cfg->crossbar_dp_single_pma)); } -/* T8152: power lane 0 down as the PHY powers down, the reverse of the above */ +/* + * T8152: power the lanes of the current mode down as the PHY powers down, the + * reverse of the above, while the register bus is still out of reset (a + * failed power-up may not have released it). A CIO-only PHY only ever runs + * CIO mode, so both of its lanes, also after a failed CIO power-up. Leaving + * CIO mode also clamps AUX and drops both lanes' LFPS receivers first, as the + * T8152 CIO shutdown does; the lanes' power controls are always-on and keep + * what they are left with across the common block's power-down. + */ static void atcphy_lanes_down_t8152(struct apple_atcphy *atcphy) { - core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); - udelay(1); - core_set32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_CLAMP_EN); - udelay(1); - core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); - udelay(1); - core_clear32(atcphy, ACIOPHY_T8152_AON_LANE0, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); - udelay(1); + unsigned int lanes = atcphy->cio_only ? 2 : atcphy_lanes_t8152(atcphy->mode); + + if (!(core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL)) & + ATCPHY_POWER_APB_RESET_N)) + return; + + if (lanes > 1) { + core_set32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_AUX_SLEEP_SMALL); + udelay(1); + for (unsigned int lane = 0; lane < lanes; lane++) { + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_SMALL(lane)); + udelay(1); + core_clear32(atcphy, ACIOPHY_T8152_AON_SLEEP_CTRL2, + ACIOPHY_T8152_AON_SLEEP_CTRL2_RXA_LFPS_BIG(lane)); + udelay(1); + } + } + + for (unsigned int lane = 0; lane < lanes; lane++) { + u32 ctrl = ACIOPHY_T8152_AON_LANE(lane); + + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_AHB_RESET_N); + udelay(1); + core_set32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_CLAMP_EN); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_BIG); + udelay(1); + core_clear32(atcphy, ctrl, ACIOPHY_T8152_AON_LANE_SLEEP_SMALL); + udelay(1); + } } /* Static configuration fields already read/modified by the public DP path. */ @@ -2369,7 +2443,8 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode core_mask32(atcphy, atcphy->hw->aciophy_crossbar, ACIOPHY_CROSSBAR_PROTOCOL, FIELD_PREP(ACIOPHY_CROSSBAR_PROTOCOL, mode_cfg->crossbar)); - if (mode_cfg->set_swap) + if (mode_cfg->set_swap || + (atcphy->hw->cio_lane_swap && atcphy_mode_is_cio(mode) && atcphy->swap_lanes)) core_set32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); else core_clear32(atcphy, atcphy_cfg(atcphy, ATCPHY_MISC), atcphy_lane_swap(atcphy)); @@ -2384,7 +2459,7 @@ static int atcphy_configure_lanes(struct apple_atcphy *atcphy, enum atcphy_mode /* * The PMA FSM override below is for the T8103 generation. T8122 DP lanes * are started by the link rate sequence, see atcphy_dp_set_rate_t8122(). - * T8152 runs USB3 alone. + * T8152 runs USB3 or CIO alone. */ if (atcphy->hw->gen == ATCPHY_GENERATION_T8122 || atcphy->hw->gen == ATCPHY_GENERATION_T8152) @@ -2920,8 +2995,9 @@ static int atcphy_power_off(struct apple_atcphy *atcphy) u32 reg; int ret; - /* A fixed-USB3 port has no DisplayPort side */ - if (atcphy->hw->gen != ATCPHY_GENERATION_T8132 && !atcphy->fixed_usb3) { + /* A fixed-USB3 port has no DisplayPort side, a CIO-only port leaves it alone */ + if (atcphy->hw->gen != ATCPHY_GENERATION_T8132 && !atcphy->fixed_usb3 && + !atcphy->cio_only) { ret = atcphy_disable_dp_aux(atcphy); if (ret) return ret; @@ -3014,7 +3090,7 @@ static int atcphy_power_on(struct apple_atcphy *atcphy) u32 reg; int ret; - if (!atcphy->dp_only && !atcphy->fixed_usb3) + if (!atcphy->dp_only && !atcphy->fixed_usb3 && !atcphy->cio_only) atcphy_usb2_power_on(atcphy); core_set32(atcphy, atcphy->hw->sync_reset ?: atcphy_cfg(atcphy, ATCPHY_MISC), @@ -5457,6 +5533,192 @@ int apple_atc_dp_tunnel_open(struct phy *phy) } EXPORT_SYMBOL_GPL(apple_atc_dp_tunnel_open); +/* + * T8152's rear USB-C ports (atcphy_hw.typec_cio_only, apple_atcphy.cio_only): + * the PHY runs CIO mode for a USB4 partner and is left alone otherwise. + * + * Their DisplayPort alt mode is still driven by the display driver, which + * programs the PHY's power and reset block, lanes and display crossbar + * itself. The two take turns on the PHY: + * + * - The display driver powers the DP PHY on before it touches the PHY and + * off once it has let go of it. The DP PHY then holds the PHY's power + * domains for it, and keeps the PHY out of CIO mode: a USB4 mode change + * fails with -ETIMEDOUT, which the Type-C port driver retries (the mux + * declares its timeouts transient) until the display driver is done. + * - A DP PHY power-on is refused with -EBUSY while the PHY runs CIO mode. + * - Either takes the PHY only from its idle state: the power and reset block + * as the power-up leaves it, clamped and asleep, its sync reset asserted. + * Anything else means another user still has it, and CIO mode is refused. + * - A display the bootloader brought up keeps running for the display + * driver: such a PHY has all its domains on and is not idle at probe, and + * the domains are held for the display driver until its DP PHY goes off. + * + * Once the DisplayPort mode moves into this driver, the DP PHY programs it + * itself, both modes switch under the PHY's lock, and this arbitration goes. + */ +static int atcphy_cio_pds_on(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + int ret; + + for (unsigned int i = 0; i < pds->num_pds; i++) { + ret = pm_runtime_resume_and_get(pds->pd_devs[i]); + if (ret < 0) { + while (i--) + pm_runtime_put_sync(pds->pd_devs[i]); + return ret; + } + } + return 0; +} + +/* Synchronously: the next CIO mode or display must find them off. */ +static void atcphy_cio_pds_off(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + + for (unsigned int i = pds->num_pds; i > 0; i--) + pm_runtime_put_sync(pds->pd_devs[i - 1]); +} + +/* The power and reset block as its power-up leaves it, with its domains on */ +static bool atcphy_cio_idle(struct apple_atcphy *atcphy) +{ + return core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL)) == + ATCPHY_POWER_CLAMP_EN && + !(core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_STAT)) & + (ATCPHY_POWER_SLEEP_SMALL | ATCPHY_POWER_SLEEP_BIG)) && + !core_read32(atcphy, atcphy->hw->sync_reset); +} + +/* + * The CIO shutdown, then the power domains: the common block goes cold, so + * that the next partner, in either orientation, starts from a cold PHY. With + * the common block left powered, the next link training asserted in the + * router's firmware. A failed shutdown keeps the domains for the next try. + */ +static int atcphy_cio_stop(struct apple_atcphy *atcphy) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + ret = atcphy_configure(atcphy, APPLE_ATCPHY_MODE_OFF); + if (ret) { + dev_err(atcphy->dev, "CIO shutdown failed: %d\n", ret); + return ret; + } + atcphy_cio_pds_off(atcphy); + atcphy->cio_powered = false; + dev_dbg(atcphy->dev, "CIO mode off\n"); + return 0; +} + +static int atcphy_cio_start(struct apple_atcphy *atcphy, enum atcphy_mode mode) +{ + int ret; + + lockdep_assert_held(&atcphy->lock); + /* The router's Thunderbolt mode is not qualified on these ports. */ + if (mode != APPLE_ATCPHY_MODE_USB4) { + dev_info(atcphy->dev, "Thunderbolt alt mode is not supported on this port\n"); + return -ENODEV; + } + if (atcphy->display_owned) { + dev_dbg(atcphy->dev, "USB4 waits for the display driver to release the PHY\n"); + return -ETIMEDOUT; + } + ret = atcphy_cio_pds_on(atcphy); + if (ret) + return ret; + if (!atcphy_cio_idle(atcphy)) { + dev_warn(atcphy->dev, "PHY not idle (power control %#x), USB4 refused\n", + core_read32(atcphy, atcphy_cfg(atcphy, ATCPHY_POWER_CTRL))); + atcphy_cio_pds_off(atcphy); + return -EBUSY; + } + atcphy->cio_powered = true; + ret = atcphy_configure(atcphy, mode); + if (ret) { + dev_err(atcphy->dev, "CIO mode failed: %d\n", ret); + atcphy_cio_stop(atcphy); + return ret; + } + dev_dbg(atcphy->dev, "CIO mode on, %s\n", atcphy->swap_lanes ? "reversed" : "normal"); + return 0; +} + +/* USB4 asks for CIO mode; every other state leaves the PHY to its other users. */ +static enum atcphy_mode atcphy_cio_target_mode(const struct typec_mux_state *state) +{ + const struct enter_usb_data *data = state->data; + + if (state->alt && state->alt->svid == USB_TYPEC_TBT_SID) + return APPLE_ATCPHY_MODE_TBT; + if (!state->alt && state->mode == TYPEC_MODE_USB4 && data && + FIELD_GET(EUDO_USB_MODE_MASK, data->eudo) == EUDO_USB_MODE_USB4) + return APPLE_ATCPHY_MODE_USB4; + return APPLE_ATCPHY_MODE_OFF; +} + +/* + * The Type-C port driver sets the mux before it starts the USB4 router and + * after it stops it, so CIO mode comes up before the router starts and goes + * down after it stopped. + */ +static int atcphy_cio_mux_set(struct typec_mux_dev *mux, struct typec_mux_state *state) +{ + struct apple_atcphy *atcphy = typec_mux_get_drvdata(mux); + enum atcphy_mode mode = atcphy_cio_target_mode(state); + int ret; + + guard(mutex)(&atcphy->lock); + if (atcphy->cio_powered) { + if (atcphy->mode == mode && !atcphy->mode_dirty) + return 0; + ret = atcphy_cio_stop(atcphy); + if (ret) + return ret; + } + if (mode == APPLE_ATCPHY_MODE_OFF) + return 0; + return atcphy_cio_start(atcphy, mode); +} + +/* The display driver takes the PHY of a CIO-only port, see above. */ +static int atcphy_cio_dp_power_on(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + int ret; + + guard(mutex)(&atcphy->lock); + if (atcphy->display_owned) + return 0; + if (atcphy->cio_powered) + return -EBUSY; + ret = atcphy_cio_pds_on(atcphy); + if (!ret) + atcphy->display_owned = true; + return ret; +} + +static int atcphy_cio_dp_power_off(struct phy *phy) +{ + struct apple_atcphy *atcphy = phy_get_drvdata(phy); + + guard(mutex)(&atcphy->lock); + if (atcphy->display_owned) + atcphy_cio_pds_off(atcphy); + atcphy->display_owned = false; + return 0; +} + +static const struct phy_ops apple_atc_cio_dp_phy_ops = { + .owner = THIS_MODULE, + .power_on = atcphy_cio_dp_power_on, + .power_off = atcphy_cio_dp_power_off, +}; + static struct phy *atcphy_xlate(struct device *dev, const struct of_phandle_args *args) { struct apple_atcphy *atcphy = dev_get_drvdata(dev); @@ -5488,16 +5750,18 @@ static int atcphy_probe_phy(struct apple_atcphy *atcphy) { &atcphy->phys.usb2, &apple_atc_usb2_phy_ops }, { &atcphy->phys.usb3, atcphy->fixed_usb3 ? &apple_atc_fixed_usb3_phy_ops : &apple_atc_usb3_phy_ops }, - { &atcphy->phys.dp, &apple_atc_dp_phy_ops }, + { &atcphy->phys.dp, atcphy->cio_only ? &apple_atc_cio_dp_phy_ops : + &apple_atc_dp_phy_ops }, }; /* * A T8132 PHY with its USB3/USB4 banks gets a DP PHY for DisplayPort * tunnels only (see atcphy_dpphy_set_mode_t8132()); creating it does - * not touch the hardware. A fixed-USB3 PHY gets its USB3 PHY only. + * not touch the hardware. A fixed-USB3 PHY gets its USB3 PHY only, a + * CIO-only PHY the DP PHY through which the display driver takes it. */ for (int i = 0; i < ARRAY_SIZE(phys); i++) { - if ((atcphy->dp_only && phys[i].phy != &atcphy->phys.dp) || + if (((atcphy->dp_only || atcphy->cio_only) && phys[i].phy != &atcphy->phys.dp) || (atcphy_usb2_only(atcphy) && i != 0) || (atcphy->fixed_usb3 && phys[i].phy != &atcphy->phys.usb3)) continue; @@ -6465,9 +6729,10 @@ static int atcphy_probe_mux(struct apple_atcphy *atcphy) struct typec_mux_desc mux_desc = { .drvdata = atcphy, .fwnode = atcphy->dev->fwnode, - .set = atcphy_mux_set, + .set = atcphy->cio_only ? atcphy_cio_mux_set : atcphy_mux_set, .safe_after_role = !atcphy->fixed_usb2, - .transient_timeouts = atcphy_mux_transient_timeouts(atcphy), + /* A CIO-only PHY times out while the display driver has it. */ + .transient_timeouts = atcphy->cio_only || atcphy_mux_transient_timeouts(atcphy), }; mux = typec_mux_register(atcphy->dev, &mux_desc); @@ -6691,6 +6956,15 @@ static int atcphy_load_tunables(struct apple_atcphy *atcphy) *tunables[i].tunable = NULL; continue; } + /* a CIO-only port has its common and CIO lane tunables alone */ + if (atcphy->cio_only && + tunables[i].tunable != &atcphy->tunables.common[0] && + tunables[i].tunable != &atcphy->tunables.common[1] && + tunables[i].tunable != &atcphy->tunables.lane_usb4[0] && + tunables[i].tunable != &atcphy->tunables.lane_usb4[1]) { + *tunables[i].tunable = NULL; + continue; + } if (!atcphy->hw->has_usb4 && (tunables[i].tunable == &atcphy->tunables.lane_usb4[0] || tunables[i].tunable == &atcphy->tunables.lane_usb4[1])) { @@ -6797,11 +7071,12 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph void __iomem *addr; /* - * A fixed-USB3 PHY has its core and PIPE windows only. On T8152 the - * core window also holds the USB controller's DARTs, so it is mapped - * without claiming it. + * A fixed-USB3 PHY has its core and PIPE windows only, a CIO-only PHY its + * core window. On T8152 the core window also holds the USB controller's + * DARTs, and the display driver maps it too, so it is mapped without + * claiming it. */ - if (atcphy->fixed_usb3) { + if (atcphy->fixed_usb3 || atcphy->cio_only) { res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "core"); if (!res) return dev_err_probe(atcphy->dev, -EINVAL, "Missing core regs\n"); @@ -6809,6 +7084,8 @@ static int atcphy_map_resources(struct platform_device *pdev, struct apple_atcph if (!atcphy->regs.core) return -ENOMEM; atcphy->res.core = res; + if (atcphy->cio_only) + return 0; addr = devm_platform_ioremap_resource_byname(pdev, "pipehandler"); if (IS_ERR(addr)) @@ -7073,6 +7350,64 @@ static int atcphy_probe_finalize_fixed_usb3(struct apple_atcphy *atcphy) return 0; } +/* Let go of the PHY of a CIO-only port on unbind, see atcphy_cio_mux_set(). */ +static void atcphy_cio_release(void *data) +{ + struct apple_atcphy *atcphy = data; + + guard(mutex)(&atcphy->lock); + if (atcphy->cio_powered) + atcphy_cio_stop(atcphy); + if (atcphy->display_owned) + atcphy_cio_pds_off(atcphy); + atcphy->display_owned = false; +} + +/* + * A CIO-only port: probe leaves the hardware as it is. A display the + * bootloader brought up on the port has all of the PHY's power domains on, + * and the PHY is not idle: hold the domains for the display driver, which + * takes it over, until its DP PHY goes off. Otherwise the domains are left to + * their power domain driver. Then register the mux, the orientation switch + * and the DP PHY. + */ +static int atcphy_probe_finalize_cio_only(struct apple_atcphy *atcphy) +{ + struct dev_pm_domain_list *pds = atcphy->cio_pds; + bool all_on = true; + int ret; + + lockdep_assert_held(&atcphy->lock); + + ret = devm_add_action(atcphy->dev, atcphy_cio_release, atcphy); + if (ret) + return ret; + for (unsigned int i = 0; i < pds->num_pds; i++) + all_on &= dev_pm_genpd_is_on(pds->pd_devs[i]); + if (all_on) { + ret = atcphy_cio_pds_on(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Failed to power the PHY\n"); + if (atcphy_cio_idle(atcphy)) { + atcphy_cio_pds_off(atcphy); + } else { + atcphy->display_owned = true; + dev_info(atcphy->dev, "PHY in use at boot, held for the display driver\n"); + } + } + + ret = atcphy_probe_mux(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing mux failed\n"); + ret = atcphy_probe_switch(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing switch failed\n"); + ret = atcphy_probe_phy(atcphy); + if (ret) + return dev_err_probe(atcphy->dev, ret, "Probing phy failed\n"); + return 0; +} + static int atcphy_probe_finalize(struct apple_atcphy *atcphy) { int ret; @@ -7083,6 +7418,8 @@ static int atcphy_probe_finalize(struct apple_atcphy *atcphy) return atcphy_probe_finalize_dp_only(atcphy); if (atcphy->fixed_usb3) return atcphy_probe_finalize_fixed_usb3(atcphy); + if (atcphy->cio_only) + return atcphy_probe_finalize_cio_only(atcphy); /* Reset dwc3 on probe, let dwc3 (consumer) deassert it */ _atcphy_dwc3_reset_assert(atcphy); @@ -7225,6 +7562,18 @@ static int atcphy_probe_power_domains(struct apple_atcphy *atcphy) struct dev_pm_domain_list *pd_list; int ret; + /* + * A CIO-only PHY powers its domains only while it runs CIO mode or the + * display driver has it, see atcphy_cio_mux_set(). + */ + if (atcphy->cio_only) { + pd_data.pd_flags = PD_FLAG_NO_DEV_LINK; + ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &atcphy->cio_pds); + if (ret <= 0) + return dev_err_probe(atcphy->dev, ret ?: -EINVAL, + "Failed to attach power domains\n"); + return 0; + } if (!atcphy->fixed_usb3 || atcphy->dev->pm_domain) return 0; ret = devm_pm_domain_attach_list(atcphy->dev, &pd_data, &pd_list); @@ -7256,9 +7605,7 @@ static int atcphy_probe(struct platform_device *pdev) atcphy->t8132_dp_alt = atcphy->hw->gen == ATCPHY_GENERATION_T8132 && of_property_read_bool(dev->of_node, "apple,dp-alt-mode"); atcphy->fixed_usb3 = of_property_read_bool(dev->of_node, "apple,fixed-usb3"); - /* T8152 is supported on a fixed-USB3 port only */ - if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->fixed_usb3) - return dev_err_probe(dev, -ENODEV, "Only a fixed-USB3 port is supported\n"); + atcphy->cio_only = atcphy->hw->typec_cio_only && !atcphy->fixed_usb3; apple_atc_tunnel_wiring(atcphy); mutex_init(&atcphy->lock); platform_set_drvdata(pdev, atcphy); @@ -8342,10 +8689,11 @@ static const struct atcphy_hw atcphy_hw_t8142 = { }; /* - * T8152 as the USB3 PHY of a fixed-USB3 port: no USB4, DisplayPort or lane - * mode register and nothing to wake after the tunables. Its power domains are - * not followed: the controller's power-off and power-on of the PHY, as around - * a system sleep, take it down and up again. + * T8152 as the USB3 PHY of a fixed-USB3 port, or as a Type-C port's PHY in CIO + * mode alone (see atcphy_cio_mux_set()): no DisplayPort mode, no lane mode + * register and nothing to wake after the tunables. A fixed-USB3 port does not + * follow its power domains: the controller's power-off and power-on of the + * PHY, as around a system sleep, take it down and up again. */ static const struct atcphy_hw atcphy_hw_t8152 = { .gen = ATCPHY_GENERATION_T8152, @@ -8355,6 +8703,7 @@ static const struct atcphy_hw atcphy_hw_t8152 = { .lane_swap = ATCPHY_T8152_MISC_LANE_SWAP, .pipe_mux_clk = PIPEHANDLER_MUX_CTRL_CLK_T8142, .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8142, + .has_usb4 = true, .park_dummy_phy = true, .clear_boot_hold = true, /* @@ -8369,6 +8718,13 @@ static const struct atcphy_hw atcphy_hw_t8152 = { * PIPE moved to USB3 and back to the dummy PHY under the request. */ .pipe_lock_unacked = true, + /* + * Its Type-C ports run CIO mode alone; a reversed plug takes the + * swapped crossbar and the lane swap, with which the J873g's rear ports + * trained USB4 at 2 x 20 Gb/s. + */ + .typec_cio_only = true, + .cio_lane_swap = true, }; static const struct of_device_id atcphy_match[] = { diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index ed02e7f33b5627..dfa3d7aad45f52 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -107,7 +107,7 @@ def main(): bool t8132_ss, t8132_common_owned, t8132_suspended, t8132_failed, host_active; bool ss_tunables, mode_dirty, pipe_pending, swap_lanes; bool cio_tunables, t8132_dp_alt, fixed_usb2, hibernated, pd_was_off, idle_rpm; - bool t8103_dummy_pending, t8103_usb3_workaround, fixed_usb3; + bool t8103_dummy_pending, t8103_usb3_workaround, fixed_usb3, cio_only; unsigned tunnel_users; struct { bool prepared, changed, restored; } cio_sleep; int mode, pipe_state, lock; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index a2d8076ac8b3dc..dd3cb7476f43bb 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -25,7 +25,7 @@ struct apple_atcphy { bool aux, pll; unsigned int pairs, rate; } dp_t8122; - bool fixed_usb2, fixed_usb3, host_active, mode_dirty, ss_tunables, dp_tunables, + bool fixed_usb2, fixed_usb3, cio_only, host_active, mode_dirty, ss_tunables, dp_tunables, aux_power_requested; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py index 45c8275bf462ee..544b698f70e8c9 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/phy.py @@ -46,7 +46,7 @@ def function(source, name): struct reset_controller_dev rcdev; void *dev; int lock, dp_link_rate; - bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, cio_only, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; @@ -1953,7 +1953,7 @@ def function(name): struct { unsigned char *core, *pipehandler; } regs; void *dev; int lock; - bool fixed_usb2, fixed_usb3, host_active, ss_tunables, dp_tunables, mode_dirty; + bool fixed_usb2, fixed_usb3, cio_only, host_active, ss_tunables, dp_tunables, mode_dirty; unsigned int dp_owned_pmas, dp_idle_pmas; unsigned int dp_usb_context_valid, dp_usb_context_dirty; u32 dp_usb_context[2][27]; @@ -2355,7 +2355,7 @@ def function(source, name): struct { unsigned char *core, *lpdptx, *lioa; } regs; void *dev; int lock, dp_link_rate; - bool fixed_usb2, fixed_usb3, host_active, swap_lanes, ss_tunables, dp_tunables; + bool fixed_usb2, fixed_usb3, cio_only, host_active, swap_lanes, ss_tunables, dp_tunables; bool aux_power_requested, mode_dirty, dp_spread_spectrum, dp_presets_valid[5]; u32 dp_presets[5][16]; unsigned int dp_idle_pmas, dp_owned_pmas; From d35db361fa7e49d6cb0797e049ebaa399a1a6c31 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:26 +0100 Subject: [PATCH 0974/1514] dt-bindings: display: apple,t8152-dcp-iboot: add the USB-C ports' PHYs A rear USB-C port's ATC PHY is also its USB4 PHY, run by the ATC PHY driver, which powers the PHY. Give each usb-c port node the port's PHY in DisplayPort use (PHY_TYPE_DP): a DCP powers it while it drives the PHY, from before a cold start until the PHY is powered down, and the PHY driver keeps the PHY powered and out of USB4 meanwhile. Signed-off-by: Thomas Glanzmann --- .../bindings/display/apple,t8152-dcp-iboot.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml index cc7ea1045a323e..b25cd3a74cfa04 100644 --- a/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8152-dcp-iboot.yaml @@ -243,6 +243,14 @@ patternProperties: apple,tunable-post: $ref: /schemas/types.yaml#/definitions/uint32-matrix description: As the node's apple,tunable-post, for this port's PHY. + phys: + maxItems: 1 + description: + The port's ATC PHY in DisplayPort use (PHY_TYPE_DP). A DCP powers + it while it drives the PHY, from before its cold start until its + power-down, and keeps it powered for a display the bootloader + started; the PHY driver powers the PHY's domains meanwhile and + keeps it out of USB4. The PHY refuses this while it runs USB4. mode-switch: type: boolean description: @@ -315,6 +323,7 @@ examples: <0x3 0x03a13a00 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <3>; + phys = <&atc3_phy 6>; mode-switch; port { From 5e18531daf53f8254a4f9003fda0b676dbd37f81 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:26 +0100 Subject: [PATCH 0975/1514] drm/apple: power the T8152 ATC PHYs through their PHY driver The T8152 DCPs powered a rear USB-C port's ATC PHY themselves: before a cold start they set the port's USB_AON, DP_0 and DP_1 PMGR power states (PS +0x100, +0, +0x20) to 0xf and its common PSD service to 0, and after a power-down they set back those that had been off. The same PHY now runs CIO mode for USB4, through the ATC PHY driver, which powers it through the PMGR and PSD power domain drivers. With two writers of the same states, one would switch off what the other uses, or leave the power domain drivers believing a domain on that is off. Take the PHY through the port's DP PHY instead (the usb-c node's phys): power it on before the cold start's first PHY access and off once the PHY is powered down. The PHY driver then holds the PHY's power domains and keeps it out of USB4; while the PHY runs USB4 the power-on fails with -EBUSY and the cold start with it. A display the bootloader left running is kept powered by the PHY driver from its probe; the DCP that adopts it powers the DP PHY on at once and so takes that over. A port whose common block runs but whose DP PHY cannot be powered is in USB4, not a bootloader display: the power and reset block (CFG +0x60000) reads 0x1b in both. The PMGR and PSD state registers are still read to tell whether the PHY can be looked at. The DisplayPort programming itself is unchanged. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/apple/t8152_atc.c | 116 +++++++++++++----------------- 1 file changed, 48 insertions(+), 68 deletions(-) diff --git a/drivers/gpu/drm/apple/t8152_atc.c b/drivers/gpu/drm/apple/t8152_atc.c index f712339ebb7ac9..4c2a5cd9ba1ba1 100644 --- a/drivers/gpu/drm/apple/t8152_atc.c +++ b/drivers/gpu/drm/apple/t8152_atc.c @@ -14,6 +14,11 @@ * route, and with the display off or unplugged a full power down and a cold * start. A DCP drives one USB-C port at a time: the one it claims from the * shared ports once their Type-C state shows a sink (t8152_typec.c). + * + * The ATC PHY driver powers the PHY: it holds the PHY's power domains while + * the port's DP PHY is on, and keeps the PHY out of USB4 meanwhile. So the DP + * PHY goes on before any PHY register access of a cold start, and off once + * the PHY is powered down, and a bootloader display's PHY stays on with it. */ #include @@ -24,6 +29,7 @@ #include #include #include +#include #include "dptxep.h" #include "t8152_display.h" @@ -55,11 +61,11 @@ struct t8152_atc_port { u32 dfp; /* AP DisplayPort AUX controller aux0 (shared), for the EDID */ struct t8152_aux *aux; - /* PMGR power states of the four ATC dependencies */ + /* PMGR power states of the ATC dependencies, read to tell if it runs */ void __iomem *ps; void __iomem *psd; - /* the dependencies this driver powered up, and may power down */ - u8 owned; + /* the port's DP PHY of the ATC PHY driver, which powers the PHY */ + struct phy *phy; /* {offset, mask, value} tunables, before and after the lane setup */ const __be32 *tunable[2]; int tunable_len[2]; @@ -385,50 +391,7 @@ static int atc_dp_start(struct t8152_display *disp, struct t8152_atc_port *atc, return 0; } -/* - * The power dependencies, in order: the ATC's USB AON (PS +0x100), its common - * PSD, then its two DP PS registers (+0, +0x20), with the values they idle at - * (ATC3: PS 0x1c0, PSD 58, PS 0xc0, 0xe0). - */ -#define ATC_PSD_TARGET 0x90 #define ATC_PSD_STATE 0x80 -static const u32 atc_ps_offset[] = { 0x100, 0, 0x0, 0x20 }; -static const u32 atc_ps_idle[] = { 0x300, 6, 0x244, 0x244 }; - -static int atc_psd_wait(struct t8152_atc_port *atc, u32 state) -{ - u32 reg; - - /* - * Only the state: the acknowledge bit stays clear when Linux switches - * the PSD, in either direction. - */ - return readl_poll_timeout(atc->psd + ATC_PSD_STATE, reg, - (reg & 7) == state, 1, ATC_TIMEOUT_US); -} - -static int atc_gate(struct t8152_atc_port *atc, unsigned int i, bool on) -{ - u32 value = on ? (atc_ps_idle[i] & 0xfffffcf0) | 15 : atc_ps_idle[i]; - u32 reg; - - /* Already up (the bootloader's or an earlier activation's). */ - if (on && (i == 1 ? !(readl(atc->psd + ATC_PSD_STATE) & 7) : - (readl(atc->ps + atc_ps_offset[i]) & 0xf0) == 0xf0)) - return 0; - if (on) - atc->owned |= BIT(i); - else - atc->owned &= ~BIT(i); - if (i == 1) { - writel(on ? 0 : atc_ps_idle[i], atc->psd + ATC_PSD_TARGET); - return atc_psd_wait(atc, on ? 0 : atc_ps_idle[i]); - } - writel(value, atc->ps + atc_ps_offset[i]); - return readl_poll_timeout(atc->ps + atc_ps_offset[i], reg, - (reg & 0xf0) == ((value & 15) << 4), 1, - ATC_TIMEOUT_US); -} static void atc_apply_tunables(struct t8152_atc_port *atc, unsigned int which) { @@ -439,13 +402,13 @@ static void atc_apply_tunables(struct t8152_atc_port *atc, unsigned int which) be32_to_cpu(t[i + 2])); } -/* Cold start: the power dependencies, the common block and AUX, then the lanes at HBR. */ +/* Cold start: the PHY's power, the common block and AUX, then the lanes at HBR. */ static int atc_activate(struct t8152_display *disp) { struct t8152_atc_port *atc = atc_cur(disp); void __iomem *cfg = atc->base + ATC_CFG; - unsigned int gates = 0; u32 reg; + int ret; if (READ_ONCE(atc_owner[atc->index]) != disp->dev) return -EBUSY; @@ -453,9 +416,12 @@ static int atc_activate(struct t8152_display *disp) return 0; if (!atc->tunable[0] || !atc->tunable[1]) return -EOPNOTSUPP; - for (; gates < ARRAY_SIZE(atc_ps_idle); gates++) - if (atc_gate(atc, gates, true)) - goto fail; + /* -EBUSY while the PHY runs USB4 */ + ret = phy_power_on(atc->phy); + if (ret) { + dev_err(disp->dev, "ATC%u: PHY not powered: %d\n", atc->index, ret); + return ret; + } if (readl(cfg) != 4 || (readl(cfg + 4) & 3) || readl(cfg + 0x30)) goto fail; writel(readl(cfg + 0x30) | BIT(0), cfg + 0x30); @@ -497,14 +463,13 @@ static int atc_activate(struct t8152_display *disp) */ return atc_dp_start(disp, atc, 1); fail: - dev_err(disp->dev, "ATC%u: cold start failed (gates %u, cfg %#x/%#x)\n", - atc->index, gates, - gates == ARRAY_SIZE(atc_ps_idle) ? readl(cfg) : 0, - gates == ARRAY_SIZE(atc_ps_idle) ? readl(cfg + 4) : 0); + dev_err(disp->dev, "ATC%u: cold start failed (cfg %#x/%#x)\n", + atc->index, readl(cfg), readl(cfg + 4)); + phy_power_off(atc->phy); return -EIO; } -/* Power the PHY down, dependencies included. */ +/* Power the PHY down, its power included. */ static int atc_deactivate(struct t8152_display *disp) { struct t8152_atc_port *atc = atc_cur(disp); @@ -541,13 +506,9 @@ static int atc_deactivate(struct t8152_display *disp) } writel(readl(cfg + 0x30) & ~BIT(0), cfg + 0x30); atc->active = false; - /* - * Then the power dependencies it powered up: the next activation starts - * it cold. The USB controller of a port keeps the ones it uses. - */ - for (int i = ARRAY_SIZE(atc_ps_idle) - 1; i >= 0; i--) - if ((atc->owned & BIT(i)) && atc_gate(atc, i, false)) - ret = -ETIMEDOUT; + /* Then its power: the next activation starts it cold. */ + if (phy_power_off(atc->phy)) + ret = -ETIMEDOUT; dev_info(disp->dev, "ATC%u: powered down: %d\n", atc->index, ret); return ret; } @@ -820,6 +781,9 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, port->psd = atc_map(disp, np, "atc-psd"); if (!port->base || !port->ps || !port->psd) return -ENOMEM; + port->phy = devm_of_phy_optional_get(disp->dev, np, NULL); + if (IS_ERR(port->phy)) + return dev_err_probe(disp->dev, PTR_ERR(port->phy), "%pOF: no PHY\n", np); /* The node without ports is ATC3's (J873g back-right). */ port->dfp = 3; of_property_read_u32(np, "apple,dfp-endpoint", &port->dfp); @@ -847,6 +811,15 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, return 0; cfg = readl(port->base + ATC_CFG); port->active = atc_link_up(cfg); + /* + * The bootloader's display keeps the PHY powered through its DP PHY. The + * common block runs the same way in USB4, whose PHY refuses the DP PHY. + */ + if (port->active && phy_power_on(port->phy)) { + dev_info(disp->dev, "ATC%u: runs USB4\n", port->index); + port->active = false; + return 0; + } if ((readl(port->base + 0x4c) & 0x1f) == 0x10 || (readl(port->base + 0x4c) & 0x1f) == 0x11) { port->lanes = 2; @@ -860,9 +833,6 @@ static int atc_port_init(struct t8152_display *disp, struct t8152_atc *atc, if (port->active && (readl(port->base + 0x2040) & BIT(16)) && r < ARRAY_SIZE(atc_rates)) port->link_rate = atc_rates[r]; - /* The bootloader's display: its dependencies are the display's. */ - if (port->active) - port->owned = GENMASK(ARRAY_SIZE(atc_ps_idle) - 1, 0); dev_info(disp->dev, "ATC%u: inherited state: active %d, rate %#x, route %d, reversed %d (cfg %#x)\n", port->index, port->active, port->link_rate, port->route_started, @@ -970,12 +940,12 @@ int t8152_atc_init(struct t8152_display *disp) break; ret = atc_port_init(disp, atc, child, dp_clock); if (ret) - return ret; + goto err_power; } if (!atc->nports) { ret = atc_port_init(disp, atc, np, dp_clock); if (ret) - return ret; + goto err_power; } /* Only adopt a bootloader route belonging to this DCP. */ @@ -995,4 +965,14 @@ int t8152_atc_init(struct t8152_display *disp) dev_info(disp->dev, "USB-C display on ATC%u (%u ports)\n", atc->cur->index, atc->nports); return 0; + +err_power: + /* + * A later port failed or deferred: the probe starts over, so give back + * the PHY power atc_port_init() took for an inherited link. + */ + for (unsigned int i = 0; i < atc->nports; i++) + if (atc->port[i].active) + phy_power_off(atc->port[i].phy); + return ret; } From c61cdee06824e3ca65b3273d85a1b73023af213f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:41 +0100 Subject: [PATCH 0976/1514] arm64: dts: apple: t8152-j873g: describe the rear ports' ATC PHYs The three rear USB-C ports' ATC PHYs (ADT atc-phy0, 1 and 3) were only known to the display controllers, as register windows they program and power themselves. Describe them as T8152 Type-C PHYs, which the ATC PHY driver runs in CIO mode for USB4: - their core windows (0x403000000, 0x40b000000, 0x413000000, 0x84000 each, also mapped by the display controllers); - the orientation and mode switches, linked to the SuperSpeed port (port@1) of the port's usb-c-connector; - their power domains, in power-up order: the ATC's USB_AON, its common PSD service (55, 56, 58) and its COMMON_DP_0/1 power states, new nodes next to ATC2's. The USB_AON states are kept on, as ATC2's: they hold the rear USB controllers' state the loader set up; - the atcphy0, 1 and 3 aliases, through which the bootloader copies each PHY's CIO tunables from the Mac's own ADT (atc-phyN groups, aurora-silicon/aura#498): the common defaults before the lanes are powered up, the fabric, PLL and remaining common groups after them, then each lane's groups. Without them the PHY runs no CIO mode. The display controllers' usb-c port nodes take the PHYs through their DP PHY, which powers them while a controller drives the port. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi | 51 +++- arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi | 235 +++++++++++++++++- 2 files changed, 268 insertions(+), 18 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi index 2cc188ea99d91d..0c7df8e3a55ddf 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-dcp.dtsi @@ -138,6 +138,15 @@ reg = <0>; }; + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec0_ss: endpoint { + remote-endpoint = <&atc0_phy_typec>; + }; + }; + /* DisplayPort: the DCPs' display switch */ port@3 { reg = <3>; @@ -173,6 +182,15 @@ reg = <0>; }; + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec1_ss: endpoint { + remote-endpoint = <&atc1_phy_typec>; + }; + }; + /* DisplayPort: the DCPs' display switch */ port@3 { reg = <3>; @@ -208,6 +226,15 @@ reg = <0>; }; + /* SuperSpeed: the ATC PHY */ + port@1 { + reg = <1>; + + typec3_ss: endpoint { + remote-endpoint = <&atc3_phy_typec>; + }; + }; + /* DisplayPort: the DCPs' display switch */ port@3 { reg = <3>; @@ -276,8 +303,10 @@ /* * USB-C back-middle: ADT atc-phy0. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common - * domain. Tunables before and after the lane crossbar setup. - * The node is also the port's display switch for all DCPs. + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. */ usb-c@403000000 { reg = <0x4 0x03000000 0x0 0x84000>, @@ -285,6 +314,8 @@ <0x3 0x03a13700 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <0>; + /* Powered while a DCP drives it */ + phys = <&atc0_phy PHY_TYPE_DP>; /* The DCPs' display switch of the port */ mode-switch; apple,tunable-pre = @@ -387,8 +418,10 @@ /* * USB-C back-left: ADT atc-phy1. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common - * domain. Tunables before and after the lane crossbar setup. - * The node is also the port's display switch for all DCPs. + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. */ usb-c@40b000000 { reg = <0x4 0x0b000000 0x0 0x84000>, @@ -396,6 +429,8 @@ <0x3 0x03a13800 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <1>; + /* Powered while a DCP drives it */ + phys = <&atc1_phy PHY_TYPE_DP>; /* The DCPs' display switch of the port */ mode-switch; apple,tunable-pre = @@ -498,8 +533,10 @@ /* * USB-C back-right: ADT atc-phy3. PS: the ATC's DP_0, DP_1 and * USB_AON power states (+0, +0x20, +0x100), PSD: its common - * domain. Tunables before and after the lane crossbar setup. - * The node is also the port's display switch for all DCPs. + * domain, read to tell whether the PHY runs; the ATC PHY + * driver powers them while the DP PHY is on. Tunables before + * and after the lane crossbar setup. The node is also the + * port's display switch for all DCPs. */ usb-c@413000000 { reg = <0x4 0x13000000 0x0 0x84000>, @@ -507,6 +544,8 @@ <0x3 0x03a13a00 0x0 0xc0>; reg-names = "atc", "atc-ps", "atc-psd"; apple,dfp-endpoint = <3>; + /* Powered while a DCP drives it */ + phys = <&atc3_phy PHY_TYPE_DP>; /* The DCPs' display switch of the port */ mode-switch; apple,tunable-pre = diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi index 08c65ebaec42bb..d348e83d3f978e 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb.dtsi @@ -10,9 +10,12 @@ * the role switch, exist but are left to the loader. * usb-drd2's hub is wired to ATC2's PHY without a Type-C mux, so Linux brings * that PHY up in USB3 mode (atc2_phy). + * The rear ports' ATC PHYs (atc0_phy, atc1_phy, atc3_phy) run CIO mode for + * USB4 alone: their DisplayPort alt mode is the display controllers', which + * take a PHY through its DP PHY, and their USB2 side stays with the loader. * Resources are from the 26A434 ADT: dart-usb1/2, usb-drd1/2 (on atc-phy1 and - * atc-phy2), atc-phy2 and the pmgr devices ATC1_USB_AON/USB, ATC2_USB_AON/USB - * and ATC2_COMMON_DP_0/1. + * atc-phy2), atc-phy0-3 and the pmgr devices ATCn_USB_AON, ATC1/2_USB and + * ATCn_COMMON_DP_0/1. * * dart-usb1 and dart-usb2 each have two DART instances (ADT reg[0] and * reg[1], 0xc000 each, sharing one interrupt). t8152-peripherals.dtsi lists @@ -38,8 +41,11 @@ / { aliases { - /* aura copies the ATC PHY's tunables from ADT atc-phy2 here. */ + /* aura copies each ATC PHY's tunables from ADT atc-phyN here. */ + atcphy0 = &atc0_phy; + atcphy1 = &atc1_phy; atcphy2 = &atc2_phy; + atcphy3 = &atc3_phy; }; soc { @@ -74,16 +80,16 @@ /* * The ATCs' PMGR power states (ADT pmgr devices ATCn_COMMON_DP_0/1 * from 0x308290000 and ATCn_USB_AON/USB from 0x308290100, 0x40 - * apart per ATC). The T8152 USB bring-up runs them without - * automatic power management. + * apart per ATC). Each ATC's three are those its PHY needs, and + * ATC1_USB and ATC2_USB are the USB controllers' states. The + * T8152 USB3 and CIO bring-ups run them without automatic power + * management. * - * ATCn_USB is the controller's state. The ADT also gives - * usb-drd1/2 service-gates 175/176, but those PSD service blocks - * (0x303a1af00, 0x303a1b000) take a bus error from the CPU. The - * loader leaves ATCn_USB and ATCn_USB_AON on; they hold the - * controllers' reset and the USB2 PHY setup it did, which Linux - * cannot redo yet, so they stay on. ATC2_COMMON_DP_0/1 are what - * ATC2's PHY needs besides. + * The ADT also gives usb-drd1/2 service-gates 175/176, but those + * PSD service blocks (0x303a1af00, 0x303a1b000) take a bus error + * from the CPU. The loader leaves ATC1/2_USB on; with USB_AON + * they hold the controllers' reset and the USB2 PHY setup it + * did, which Linux cannot redo yet, so they stay on. */ pmgr_atc: power-management@308290000 { compatible = "apple,t8152-pmgr", "apple,t8103-pmgr", @@ -92,6 +98,46 @@ #size-cells = <1>; reg = <0x3 0x08290000 0x0 0x1000>; + ps_atc0_common_dp_0: power-controller@0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc0_common_dp_1: power-controller@20 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_common_dp_1"; + apple,no-auto-pm; + }; + + ps_atc1_common_dp_0: power-controller@40 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc1_common_dp_1: power-controller@60 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_common_dp_1"; + apple,no-auto-pm; + }; + ps_atc2_common_dp_0: power-controller@80 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -112,6 +158,42 @@ apple,no-auto-pm; }; + ps_atc3_common_dp_0: power-controller@c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_common_dp_0"; + apple,no-auto-pm; + }; + + ps_atc3_common_dp_1: power-controller@e0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0xe0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_common_dp_1"; + apple,no-auto-pm; + }; + + /* + * The USB_AON states are kept on: each holds its USB + * controller's reset and PIPE handler state, and the + * rear ports' controllers stay with the loader. + */ + ps_atc0_usb_aon: power-controller@100 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + ps_atc1_usb_aon: power-controller@140 { compatible = "apple,t8152-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; @@ -162,6 +244,42 @@ apple,no-auto-pm; apple,always-on; }; + + ps_atc3_usb_aon: power-controller@1c0 { + compatible = "apple,t8152-pmgr-pwrstate", + "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_usb_aon"; + apple,no-auto-pm; + apple,always-on; + }; + }; + + /* + * The rear ports' ATCs' common domains: PSD services 55, 56 and 58 + * (ADT atc-phy0/1/3 clock-gates). + */ + ps_atc0_common: power-controller@303a13700 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13700 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc0_common"; + }; + + ps_atc1_common: power-controller@303a13800 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13800 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc1_common"; + }; + + ps_atc3_common: power-controller@303a13a00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x03a13a00 0x0 0x100>; + #power-domain-cells = <0>; + label = "atc3_common"; }; /* ATC2's common domain: PSD service 57 (ADT atc-phy2 clock-gates). */ @@ -194,6 +312,99 @@ <&ps_atc2_common_dp_0>, <&ps_atc2_common_dp_1>; }; + /* + * USB-C Back-middle: ADT atc-phy0 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy0 groups the CIO mode + * applies, through the atcphy0 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc0_phy: phy@403000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x03000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>, + <&ps_atc0_common_dp_0>, <&ps_atc0_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc0_phy_typec: endpoint { + remote-endpoint = <&typec0_ss>; + }; + }; + }; + }; + + /* + * USB-C Back-left: ADT atc-phy1 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy1 groups the CIO mode + * applies, through the atcphy1 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc1_phy: phy@40b000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x0b000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>, + <&ps_atc1_common_dp_0>, <&ps_atc1_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc1_phy_typec: endpoint { + remote-endpoint = <&typec1_ss>; + }; + }; + }; + }; + + /* + * USB-C Back-right: ADT atc-phy3 in CIO mode, see atc2_phy for the + * layout. The bootloader copies the atc-phy3 groups the CIO mode + * applies, through the atcphy3 alias: the common and PLL defaults + * as common-a, the fabric, PLL and the other common groups as + * common-b, and each lane's groups. + */ + atc3_phy: phy@413000000 { + compatible = "apple,t8152-atcphy"; + reg = <0x4 0x13000000 0x0 0x84000>; + reg-names = "core"; + #phy-cells = <1>; + orientation-switch; + mode-switch; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>, + <&ps_atc3_common_dp_0>, <&ps_atc3_common_dp_1>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + atc3_phy_typec: endpoint { + remote-endpoint = <&typec3_ss>; + }; + }; + }; + }; + /* usb-drd2: on-board VL822 hub behind the two front USB-C ports. */ usb2: usb@382430000 { compatible = "apple,t8152-dwc3"; From a714359e110ef7fa14ac05afd64f4119efa44a08 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:41 +0100 Subject: [PATCH 0977/1514] thunderbolt: apple: stop the T8152 routers before a reboot A reboot or power-off shuts the PCIe-C host and the router's and the tunnel's DARTs down before the router, while a started router still runs over them. With the J873g's rear ports, the earlier port monitor stopped the routers from a reboot notifier for this. Without a port monitor, do that in the router driver: for routers whose match data asks for it (T8152), stop a started router from a reboot notifier, as the port driver does for an unplugged cable, and refuse a new start from then on. Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/apple.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index a22d8129a7b328..cdce656a28a5c8 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -95,6 +95,7 @@ #include #include #include +#include #include #include #include @@ -173,6 +174,8 @@ struct apple_cio_hw { bool host_tmu; /* Drain PSD runtime power-off before the PHY is reset or reused. */ bool psd_power_cycle; + /* Stop a started router before a reboot shuts its PCIe and DARTs down. */ + bool stop_at_reboot; const struct apple_dpin_policy *dp; }; @@ -211,6 +214,7 @@ static const struct apple_cio_hw apple_cio_t8132_hw = { /* MXWrap-v2p3 is started by reconfiguration, using its counted mailbox. */ static const struct apple_cio_hw apple_cio_t8152_hw = { .psd_power_cycle = true, + .stop_at_reboot = true, .type7 = true, .lstx_after_boot = true, .strict_fw_ready = true, @@ -513,6 +517,7 @@ struct apple_cio { u64 link_lost_cycle_activity; /* remote activity at the last cycle */ bool link_lost_restart; /* protected by lock: cycle requested */ struct notifier_block pm_notifier; + struct notifier_block reboot_notifier; /* * T6050: the displays behind this port go at the start of the sleep's entry, before any * port's power-off. @sleep_dp_paused: this entry closed the DP IN admission; @@ -4498,6 +4503,24 @@ static int apple_cio_pcie_notify(struct notifier_block *nb, return NOTIFY_OK; } +/* + * A reboot or power-off shuts the PCIe-C host and the router's and the + * tunnel's DARTs down before this device, with the router still running + * over them. Stop a started router first, as the port driver does for an + * unplugged cable, and refuse a new start from then on. + */ +static int apple_cio_reboot_notify(struct notifier_block *nb, unsigned long action, + void *data) +{ + struct apple_cio *acio = container_of(nb, struct apple_cio, reboot_notifier); + + guard(mutex)(&acio->lock); + acio->removing = true; + if (acio->current_cable_info) + apple_cio_stop(acio); + return NOTIFY_DONE; +} + static int apple_cio_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -4759,6 +4782,10 @@ static int apple_cio_probe(struct platform_device *pdev) acio->pm_notifier_dp.notifier_call = apple_cio_dp_pm_notify; acio->pm_notifier_dp.priority = 20; register_pm_notifier(&acio->pm_notifier_dp); + if (acio->hw->stop_at_reboot) { + acio->reboot_notifier.notifier_call = apple_cio_reboot_notify; + register_reboot_notifier(&acio->reboot_notifier); + } return 0; } @@ -4766,6 +4793,8 @@ static void apple_cio_remove(struct platform_device *pdev) { struct apple_cio *acio = platform_get_drvdata(pdev); + if (acio->hw->stop_at_reboot) + unregister_reboot_notifier(&acio->reboot_notifier); /* Refuse new activation before draining callbacks and workers. */ scoped_guard(mutex, &acio->lock) acio->removing = true; From e251b2ceb14058e5a4dc484513923926bf7e1c06 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 20 Nov 2026 01:26:41 +0100 Subject: [PATCH 0978/1514] arm64: dts: apple: t8152-j873g: enable the rear USB4 ports Describe the three rear USB4 routers (ADT acio0, acio1, acio3) with their mailboxes, NHI, ACIO DARTs, PCIe-C tunnels and their DARTs, the CIO reset block, the PSD services they need and the LSTX pins. Generated from the J873g ADT. The router, NHI, DART and PCIe-C tunables and the routers' DROMs are not in the device tree: they are per Mac (a DROM carries the host router's UID), so the bootloader copies them from the Mac's own ADT (aurora-silicon/aura#498), through the usb4-N-acio, -pcie-adapter, -nhi and -pcie aliases (ADT acio0, 1 and 3, apciecN), and the DARTs' by their address. With a loader that copies none, the routers, NHIs and PCIe-C ports refuse to start. Each router coprocessor's mailbox has apple,t8152-smc-mailbox as its fallback and the two interrupts of the ADT's acio-cpuN node, which list send-empty first, as the SMC mailbox's do. Each router's Thunderbolt switch (its port@1) is linked to the USB4 port (port@4) of its port's usb-c-connector, as on the J813: the PD controller driver sets the port's ATC PHY to CIO mode and then starts the router with the cable's EUDO and orientation, and stops the router before it takes the PHY out of CIO mode. Signed-off-by: Thomas Glanzmann --- .../arm64/boot/dts/apple/t8152-j873-usb4.dtsi | 687 ++++++++++++++++++ arch/arm64/boot/dts/apple/t8152-j873g.dts | 1 + 2 files changed, 688 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi new file mode 100644 index 00000000000000..2416ffd858cda4 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi @@ -0,0 +1,687 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * J873g rear USB-C ports in USB4 mode: three ACIO host routers with their + * NHI, PCIe-C tunnel and DARTs, and the T8152 PSD services they need. Each + * router's Thunderbolt switch is linked to the USB4 port (port@4) of its + * port's usb-c-connector, whose PD controller driver starts and stops it + * after it set the port's ATC PHY to CIO mode. + * + * Generated from the J873g ADT (27.2 iBoot): /arm-io/acio{0,1,3}, acio-cpuN, + * dart-acioN, apciecN and dart-apciecN. The tunables of the routers, their + * NHIs, PCIe-C ports and DARTs, and each router's DROM, are not in this file: + * the bootloader copies them from the Mac's own ADT (acioN, apciecN, + * dart-acioN, dart-apciecN) into the nodes the usb4-N aliases name, and the + * DARTs by their address. + * + * Each router coprocessor's mailbox is the 0x80 window at +0x80 of its + * acio-cpuN register block, with the SMC mailbox's counted FIFOs. Its + * interrupts are acio-cpuN's two, in the order the SMC mailbox's ADT list + * gives its own: send-empty, recv-not-empty. + */ + +#include + +/ { + aliases { + /* aura copies the router tunables and DROMs here, the AP firmware one too. */ + usb4-0-acio = &usb4_0; + usb4-0-pcie-adapter = &usb4_0; + usb4-0-nhi = &usb4_0_nhi; + usb4-1-acio = &usb4_1; + usb4-1-pcie-adapter = &usb4_1; + usb4-1-nhi = &usb4_1_nhi; + usb4-3-acio = &usb4_3; + usb4-3-pcie-adapter = &usb4_3; + usb4-3-nhi = &usb4_3_nhi; + /* aura copies the PCIe-C tunables here. */ + usb4-0-pcie = &usb4_0_pcie; + usb4-1-pcie = &usb4_1_pcie; + usb4-3-pcie = &usb4_3_pcie; + }; + + soc { + cio_reset: reset-controller@300780000 { + compatible = "apple,t8152-cio-reset"; + reg = <0x3 0x00780000 0x0 0x4000>; + #reset-cells = <1>; + }; + + cio_psd59: power-controller@303a13b00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13b00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd60: power-controller@303a13c00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13c00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd62: power-controller@303a13e00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13e00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd63: power-controller@303a13f00 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a13f00 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd64: power-controller@303a14000 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14000 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd66: power-controller@303a14200 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14200 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd67: power-controller@303a14300 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14300 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd68: power-controller@303a14400 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14400 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd70: power-controller@303a14600 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a14600 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd86: power-controller@303a15600 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15600 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd87: power-controller@303a15700 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15700 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio_psd89: power-controller@303a15900 { + compatible = "apple,t8152-psd"; + reg = <0x3 0x3a15900 0x0 0x100>; + #power-domain-cells = <0>; + }; + + cio0_mbox: mailbox@401178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x1178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_0: acio@401ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x1ac0000 0x0 0xc000>, + <0x4 0x1080000 0x0 0x26000>, + <0x4 0x1e44000 0x0 0x4000>, + <0x4 0x1c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x1000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio0_mbox>; + resets = <&cio_reset 0>; + power-domains = <&cio_psd59>, <&cio_psd63>, <&cio_psd67>, <&cio_psd86>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_0_lstx_pins>; + lstx-gpios = <&pinctrl_aop 19 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_0_tunnel>; + + usb4_0_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000100 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_0_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_0_dart 0>, <&usb4_0_dart 1>, <&usb4_0_dart 2>, + <&usb4_0_dart 3>, <&usb4_0_dart 4>, <&usb4_0_dart 5>, + <&usb4_0_dart 6>, <&usb4_0_dart 7>, <&usb4_0_dart 8>, + <&usb4_0_dart 9>, <&usb4_0_dart 10>, <&usb4_0_dart 11>, + <&usb4_0_dart 16>, <&usb4_0_dart 17>, <&usb4_0_dart 18>, + <&usb4_0_dart 19>, <&usb4_0_dart 20>, <&usb4_0_dart 21>, + <&usb4_0_dart 22>, <&usb4_0_dart 23>, <&usb4_0_dart 24>, + <&usb4_0_dart 25>, <&usb4_0_dart 26>, <&usb4_0_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_0_sw: endpoint { + remote-endpoint = <&typec0_usb4>; + }; + }; + }; + }; + + cio1_mbox: mailbox@409178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x9178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_1: acio@409ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x9ac0000 0x0 0xc000>, + <0x4 0x9080000 0x0 0x26000>, + <0x4 0x9e44000 0x0 0x4000>, + <0x4 0x9c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x9000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio1_mbox>; + resets = <&cio_reset 1>; + power-domains = <&cio_psd60>, <&cio_psd64>, <&cio_psd68>, <&cio_psd87>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_1_lstx_pins>; + lstx-gpios = <&pinctrl_aop 21 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_1_tunnel>; + + usb4_1_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000180 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_1_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_1_dart 0>, <&usb4_1_dart 1>, <&usb4_1_dart 2>, + <&usb4_1_dart 3>, <&usb4_1_dart 4>, <&usb4_1_dart 5>, + <&usb4_1_dart 6>, <&usb4_1_dart 7>, <&usb4_1_dart 8>, + <&usb4_1_dart 9>, <&usb4_1_dart 10>, <&usb4_1_dart 11>, + <&usb4_1_dart 16>, <&usb4_1_dart 17>, <&usb4_1_dart 18>, + <&usb4_1_dart 19>, <&usb4_1_dart 20>, <&usb4_1_dart 21>, + <&usb4_1_dart 22>, <&usb4_1_dart 23>, <&usb4_1_dart 24>, + <&usb4_1_dart 25>, <&usb4_1_dart 26>, <&usb4_1_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_1_sw: endpoint { + remote-endpoint = <&typec1_usb4>; + }; + }; + }; + }; + + cio3_mbox: mailbox@411178080 { + compatible = "apple,t8152-cio-mailbox", + "apple,t8152-smc-mailbox"; + reg = <0x4 0x11178080 0x0 0x80>; + interrupts = , + ; + interrupt-names = "send-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; + + /* acio@ avoids the bootloader's legacy cio@ register-index fixup. */ + usb4_3: acio@411ac0000 { + compatible = "apple,t8152-usb4-acio"; + reg = <0x4 0x11ac0000 0x0 0xc000>, + <0x4 0x11080000 0x0 0x26000>, + <0x4 0x11e44000 0x0 0x4000>, + <0x4 0x11c80000 0x0 0x4000>; + reg-names = "rc", "sram", "pcie-adapter", "router-ap-fw"; + #address-cells = <1>; + #size-cells = <1>; + /* The router window and the shared Gen3 TLB invalidation aperture. */ + ranges = <0x0 0x4 0x11000000 0x1000000>, + <0x1000000 0x2 0x0 0x1000>; + nonposted-mmio; + mboxes = <&cio3_mbox>; + resets = <&cio_reset 3>; + power-domains = <&cio_psd62>, <&cio_psd66>, <&cio_psd70>, <&cio_psd89>; + pinctrl-names = "lstx"; + pinctrl-0 = <&usb4_3_lstx_pins>; + lstx-gpios = <&pinctrl_aop 25 GPIO_ACTIVE_HIGH>; + thunderbolt-switch; + apple,pcie-tunnel = <&usb4_3_tunnel>; + + usb4_3_dart: iommu@a80000 { + compatible = "apple,t8152-acio-dart"; + reg = <0xa80000 0xc000>, + <0x1000280 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + apple,dma-range = <0x100 0x0 0x10 0x0>; + }; + + usb4_3_nhi: nhi@f00000 { + compatible = "apple,t8152-usb4-nhi"; + reg = <0xf00000 0x100000>; + reg-names = "nhi"; + interrupt-parent = <&aic>; + interrupts = , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + , + ; + interrupt-names = "txring0", "txring1", "txring2", + "txring3", "txring4", "txring5", + "txring6", "txring7", "txring8", + "txring9", "txring10", "txring11", + "rxring0", "rxring1", "rxring2", + "rxring3", "rxring4", "rxring5", + "rxring6", "rxring7", "rxring8", + "rxring9", "rxring10", "rxring11"; + iommus = <&usb4_3_dart 0>, <&usb4_3_dart 1>, <&usb4_3_dart 2>, + <&usb4_3_dart 3>, <&usb4_3_dart 4>, <&usb4_3_dart 5>, + <&usb4_3_dart 6>, <&usb4_3_dart 7>, <&usb4_3_dart 8>, + <&usb4_3_dart 9>, <&usb4_3_dart 10>, <&usb4_3_dart 11>, + <&usb4_3_dart 16>, <&usb4_3_dart 17>, <&usb4_3_dart 18>, + <&usb4_3_dart 19>, <&usb4_3_dart 20>, <&usb4_3_dart 21>, + <&usb4_3_dart 22>, <&usb4_3_dart 23>, <&usb4_3_dart 24>, + <&usb4_3_dart 25>, <&usb4_3_dart 26>, <&usb4_3_dart 27>; + /* Filled by the bootloader. */ + apple,thunderbolt-drom = [00]; + }; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@1 { + reg = <1>; + usb4_3_sw: endpoint { + remote-endpoint = <&typec3_usb4>; + }; + }; + }; + }; + }; + + usb4_0_tunnel: usb4-pcie-tunnel-0 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_0_pcie_dart: iommu@404000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0x4000000 0x0 0xc000>, + <0x2 0x100 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd86>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_0_pcie: pcie@1c50000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x50000000 0x0 0x10000000>, + <0x4 0x4034000 0x0 0x4000>, + <0x4 0x4020000 0x0 0x8000>, + <0x4 0x4038000 0x0 0x4000>, + <0x4 0x4060000 0x0 0x4000>, + <0x4 0x402c000 0x0 0x4000>, + <0x4 0x4028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd86>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_0_pcie>; + msi-ranges = <&aic AIC_IRQ 1975 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <96>; + iommu-map = <0 &usb4_0_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <1>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0x8 0x0 0x8 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0xa 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xa 0x40000000 0x0 0x40000000>; + + usb4_0_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_0_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_0_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_0_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_0_pcie_port 0 0 0 3>; + }; + }; + }; + + usb4_1_tunnel: usb4-pcie-tunnel-1 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_1_pcie_dart: iommu@40c000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0xc000000 0x0 0xc000>, + <0x2 0x180 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd87>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_1_pcie: pcie@1c60000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x60000000 0x0 0x10000000>, + <0x4 0xc034000 0x0 0x4000>, + <0x4 0xc020000 0x0 0x8000>, + <0x4 0xc038000 0x0 0x4000>, + <0x4 0xc060000 0x0 0x4000>, + <0x4 0xc02c000 0x0 0x4000>, + <0x4 0xc028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd87>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_1_pcie>; + msi-ranges = <&aic AIC_IRQ 2007 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <128>; + iommu-map = <0 &usb4_1_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <2>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0xc 0x0 0xc 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0xe 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0xe 0x40000000 0x0 0x40000000>; + + usb4_1_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_1_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_1_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_1_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_1_pcie_port 0 0 0 3>; + }; + }; + }; + + usb4_3_tunnel: usb4-pcie-tunnel-3 { + #address-cells = <2>; + #size-cells = <2>; + ranges; + nonposted-mmio; + + usb4_3_pcie_dart: iommu@414000000 { + compatible = "apple,t8152-pciec-dart"; + reg = <0x4 0x14000000 0x0 0xc000>, + <0x2 0x280 0x0 0x10>; + reg-names = "dart", "tlbi"; + #iommu-cells = <1>; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd89>; + apple,dma-range = <0x100 0x80000000 0x0 0x7ff00000>; + }; + + usb4_3_pcie: pcie@1c80000000 { + compatible = "apple,t8152-pciec"; + device_type = "pci"; + reg = <0x1c 0x80000000 0x0 0x10000000>, + <0x4 0x14034000 0x0 0x4000>, + <0x4 0x14020000 0x0 0x8000>, + <0x4 0x14038000 0x0 0x4000>, + <0x4 0x14060000 0x0 0x4000>, + <0x4 0x1402c000 0x0 0x4000>, + <0x4 0x14028000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; + interrupt-parent = <&aic>; + interrupts = ; + power-domains = <&cio_psd89>; + apple,pciec-kernel-init; + msi-controller; + msi-parent = <&usb4_3_pcie>; + msi-ranges = <&aic AIC_IRQ 2071 IRQ_TYPE_EDGE_RISING 32>; + apple,msi-vector-base = <192>; + iommu-map = <0 &usb4_3_pcie_dart 0 0x40>; + iommu-map-mask = <0x3f>; + linux,pci-domain = <4>; + bus-range = <0 0x7f>; + #address-cells = <3>; + #size-cells = <2>; + ranges = <0x43000000 0x14 0x0 0x14 0x0 0x2 0x0>, + <0x2000000 0x0 0x100000 0x16 0x100000 0x0 0x3ff00000>, + <0x42000000 0x0 0x40000000 0x16 0x40000000 0x0 0x40000000>; + + usb4_3_pcie_port: pci@0,0 { + device_type = "pci"; + reg = <0x0 0x0 0x0 0x0 0x0>; + external-facing; + #address-cells = <3>; + #size-cells = <2>; + ranges; + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &usb4_3_pcie_port 0 0 0 0>, + <0 0 0 2 &usb4_3_pcie_port 0 0 0 1>, + <0 0 0 3 &usb4_3_pcie_port 0 0 0 2>, + <0 0 0 4 &usb4_3_pcie_port 0 0 0 3>; + }; + }; + }; +}; + +&pinctrl_aop { + usb4_0_lstx_pins: usb4-0-lstx-pins { + pinmux = <0x10013>; + }; + + usb4_1_lstx_pins: usb4-1-lstx-pins { + pinmux = <0x10015>; + }; + + usb4_3_lstx_pins: usb4-3-lstx-pins { + pinmux = <0x10019>; + }; +}; + +/* USB-C Back-middle: its router */ +&typec0 { + ports { + port@4 { + reg = <4>; + + typec0_usb4: endpoint { + remote-endpoint = <&usb4_0_sw>; + }; + }; + }; +}; + +/* USB-C Back-left: its router */ +&typec1 { + ports { + port@4 { + reg = <4>; + + typec1_usb4: endpoint { + remote-endpoint = <&usb4_1_sw>; + }; + }; + }; +}; + +/* USB-C Back-right: its router */ +&typec3 { + ports { + port@4 { + reg = <4>; + + typec3_usb4: endpoint { + remote-endpoint = <&usb4_3_sw>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8152-j873g.dts b/arch/arm64/boot/dts/apple/t8152-j873g.dts index 5c229e74d5b0a7..c3416ac0fd4574 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873g.dts +++ b/arch/arm64/boot/dts/apple/t8152-j873g.dts @@ -504,3 +504,4 @@ #include "t8152-j873-audio.dtsi" #include "t8152-j873-dcp.dtsi" #include "t8152-j873-avd.dtsi" +#include "t8152-j873-usb4.dtsi" From 1b969ed3f4446d2762f8e7ebae7b63948c3088f8 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sun, 22 Nov 2026 15:30:42 +0100 Subject: [PATCH 0979/1514] arm64: dts: apple: t8152-j873g: power domains for the ACIO DARTs Every enabled DART must name the power state of the engine it serves (scripts/dtc/apple-dart-pd-check.py). The three rear routers' NHI DARTs named none. A DART sits inside its router, so it takes the router's first PSD service (59, 60 and 62: ADT acioN power-gates), the one the router powers up first and down last. The router populates the DART only once it is powered and its firmware is ready, and removes it before it powers down, so the DART's vote never holds the router on after a stop. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi index 2416ffd858cda4..ce96f4fb0cd91a 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-usb4.dtsi @@ -159,6 +159,7 @@ #iommu-cells = <1>; interrupt-parent = <&aic>; interrupts = ; + power-domains = <&cio_psd59>; apple,dma-range = <0x100 0x0 0x10 0x0>; }; @@ -265,6 +266,7 @@ #iommu-cells = <1>; interrupt-parent = <&aic>; interrupts = ; + power-domains = <&cio_psd60>; apple,dma-range = <0x100 0x0 0x10 0x0>; }; @@ -371,6 +373,7 @@ #iommu-cells = <1>; interrupt-parent = <&aic>; interrupts = ; + power-domains = <&cio_psd62>; apple,dma-range = <0x100 0x0 0x10 0x0>; }; From 5b5b71edbb0eaf32152df61f08fc8e7c7c77be75 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:29:25 +1100 Subject: [PATCH 0980/1514] ci: attest kernel release assets and harden publishing - Attest build provenance for every published asset; the distribution Edge publishers verify source.commit against kernel-release.yml. - Fix the private-key guard: grep -q at the end of a pipeline exits on the first match, tar takes SIGPIPE and, under pipefail, the match read as a pass. List the tarball first, then search the list. - Run the PR check when the smoke script or its exception list changes. - Serialise builds and publishing per channel instead of cancelling a running build: a running edge build always publishes, only the newest waiting one is kept, and a build older than the tagged commit does not publish. Publishing is never cancelled halfway. - Refuse to create a channel tag while a branch of the same name exists. - Build a stable release as a draft and publish it once every asset is uploaded, so a failed upload leaves a draft the next attempt replaces. - Pin the LLVM tarball checksum and GitHub's SSH host key; remove the deploy key on every exit; name the tag in stable release notes. Signed-off-by: Ryan Murray --- .github/scripts/kernel-release-build.sh | 5 +- .github/workflows/kernel-release.yml | 70 ++++++++++++++++++------- 2 files changed, 54 insertions(+), 21 deletions(-) diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh index 3c30d800daa801..1c80a41d40ace3 100755 --- a/.github/scripts/kernel-release-build.sh +++ b/.github/scripts/kernel-release-build.sh @@ -113,7 +113,10 @@ echo "::endgroup::" # The private signing key stays on the builder for this run only. rm -f "$O/certs/signing_key.pem" for f in "$D"/*.tar.* ; do - if tar -tf "$f" | grep -q 'signing_key\.pem$'; then + # List first: grep -q in a pipeline would end it early and, under + # pipefail, turn a match into a pass. + list=$(tar -tf "$f") || { echo "::error::cannot list $f"; exit 1; } + if grep -q 'signing_key\.pem$' <<<"$list"; then echo "::error::$f contains the private signing key" exit 1 fi diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index dce180480fef76..4718f980a36a42 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -5,6 +5,10 @@ # aurora-nightly prerelease, daily from main when main moved since the last nightly # v* immutable stable release, built from a tag on main # +# A running edge or nightly build always finishes and publishes; a newer one +# waits, and only the newest waiting build is kept. Publishing never runs twice +# at once for a channel and never moves a channel tag backwards. +# # workflow_dispatch builds without publishing (publish: none) or publishes # one rolling channel by hand (publish: edge | nightly). Pull requests that # change the release machinery itself get a build without publishing. @@ -15,6 +19,7 @@ # The aurora-* channel tags are protected by a ruleset; the publish job moves # them over SSH with the release deploy key (secret RELEASE_DEPLOY_KEY), only # forward and with a lease. Stable releases attach to the v* tag an Owner pushed. +# Every published asset gets a build provenance attestation. # # The configuration is the fleet configuration (aurora_defconfig + asahi.config) # built with the fleet toolchain versions pinned below. Modules are signed with @@ -32,6 +37,8 @@ on: paths: - '.github/workflows/kernel-release.yml' - '.github/scripts/kernel-release-build.sh' + - '.github/scripts/kernel-smoke-qemu.sh' + - '.github/scripts/kernel-smoke-expected.txt' - 'arch/arm64/configs/aurora_defconfig' schedule: - cron: '30 15 * * *' @@ -46,19 +53,15 @@ on: permissions: contents: read +# Pull requests: a new push replaces the running check. Channel builds and +# publishing are serialised per channel in the jobs below. concurrency: - group: >- - kernel-release-${{ - github.event_name == 'schedule' && 'nightly' || - github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || - startsWith(github.ref, 'refs/tags/v') && github.ref_name || - github.event_name == 'workflow_dispatch' && inputs.publish != 'none' && inputs.publish || - github.event_name == 'workflow_dispatch' && format('dispatch-{0}', github.ref_name) || - 'edge' }} - cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} + group: kernel-release-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: LLVM_VERSION: '22.1.6' + LLVM_SHA256: 'b67817634e8e1c2632dfc056af14d61b94f8e6502f4e557560eea227aa22ce37' RUST_VERSION: '1.97.1' BINDGEN_VERSION: '0.73.2' PAHOLE_VERSION: 'v1.31' @@ -134,6 +137,9 @@ jobs: if: needs.plan.outputs.build == 'true' runs-on: ubuntu-24.04-arm timeout-minutes: 345 + concurrency: + group: kernel-release-build-${{ (needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly') && needs.plan.outputs.channel || github.run_id }} + cancel-in-progress: false steps: - uses: actions/checkout@v4 with: @@ -184,6 +190,7 @@ jobs: mkdir -p ~/tc curl -fsSL -o /tmp/llvm.tar.xz \ "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_VERSION/LLVM-$LLVM_VERSION-Linux-ARM64.tar.xz" + echo "$LLVM_SHA256 /tmp/llvm.tar.xz" | sha256sum -c - mkdir -p ~/tc/llvm tar -xJf /tmp/llvm.tar.xz -C ~/tc/llvm --strip-components=1 rm /tmp/llvm.tar.xz @@ -257,8 +264,13 @@ jobs: needs: [plan, build, smoke] if: needs.plan.outputs.channel != 'none' && needs.plan.outputs.build == 'true' runs-on: ubuntu-24.04-arm + concurrency: + group: kernel-release-publish-${{ needs.plan.outputs.channel }} + cancel-in-progress: false permissions: contents: write + id-token: write + attestations: write env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} @@ -272,12 +284,17 @@ jobs: name: kernel-${{ needs.plan.outputs.channel }}-${{ needs.plan.outputs.sha }} path: dist + - name: Attest build provenance + uses: actions/attest-build-provenance@v2 + with: + subject-path: 'dist/*' + - name: Write release notes run: | set -euo pipefail krel=$(cat dist/kernel.release) cat > notes.md <> "$GITHUB_OUTPUT"; exit 0 ;; *) echo "::error::$tag is at $old, which $SHA does not contain ($status)"; exit 1 ;; esac fi [ "$old" = "$SHA" ] && { echo "$tag already at $SHA"; exit 0; } + if gh api "repos/$GH_REPO/git/ref/heads/$tag" >/dev/null 2>&1; then + echo "::error::a branch named $tag exists; rename it to archive/$tag so the tag name is unambiguous" + exit 1 + fi # The aurora-* tags are protected by a ruleset that only the release # deploy key may bypass; GITHUB_TOKEN cannot move them. if [ -z "$DEPLOY_KEY" ]; then @@ -314,9 +339,10 @@ jobs: exit 1 fi install -m 0700 -d ~/.ssh - printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/release_key - chmod 0600 ~/.ssh/release_key - ssh-keyscan -t ed25519 github.com >> ~/.ssh/known_hosts 2>/dev/null + trap 'rm -f ~/.ssh/release_key' EXIT + (umask 077; printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/release_key) + # GitHub's published SSH host key. + echo 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl' >> ~/.ssh/known_hosts git init -q tagger cd tagger git remote add origin "git@github.com:$GH_REPO.git" @@ -324,10 +350,9 @@ jobs: git fetch -q --depth 1 origin "$SHA" # The lease makes the push fail if the tag moved since it was read. git push --force-with-lease="refs/tags/$tag:$old" origin "$SHA:refs/tags/$tag" - rm -f ~/.ssh/release_key - name: Publish rolling prerelease - if: needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly' + if: (needs.plan.outputs.channel == 'edge' || needs.plan.outputs.channel == 'nightly') && steps.tag.outputs.skip != 'true' run: | set -euo pipefail tag="aurora-$CHANNEL" @@ -349,10 +374,15 @@ jobs: if: needs.plan.outputs.channel == 'stable' run: | set -euo pipefail - if gh release view "$TAG_NAME" >/dev/null 2>&1; then - echo "::error::release $TAG_NAME already exists; stable releases are never rebuilt" - exit 1 - fi - gh release create "$TAG_NAME" dist/* --verify-tag --latest \ + # Built as a draft and published once every asset is uploaded, so a + # failed upload leaves only a draft, which the next attempt replaces. + draft=$(gh release view "$TAG_NAME" --json isDraft -q .isDraft 2>/dev/null || echo none) + case "$draft" in + none) ;; + true) gh release delete "$TAG_NAME" -y ;; + *) echo "::error::release $TAG_NAME is already published; stable releases are never rebuilt"; exit 1 ;; + esac + gh release create "$TAG_NAME" dist/* --verify-tag --draft \ --title "Aurora kernel $TAG_NAME" --notes-file notes.md --generate-notes + gh release edit "$TAG_NAME" --draft=false --latest gh release view "$TAG_NAME" --json tagName,isPrerelease,assets -q '{tag: .tagName, prerelease: .isPrerelease, assets: [.assets[].name]}' From 0912bb7dfdd634c93089824d2cacf800eccc4ae7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:29:58 +1100 Subject: [PATCH 0981/1514] docs: match RELEASES.md to the release workflow and the gate policy Edge builds are serialised rather than cancelled, assets carry build provenance attestations, and the gate Mac list now links the policy instead of copying it. Signed-off-by: Ryan Murray --- RELEASES.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 6e060aca2dcedb..350d1f55a0f88e 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -14,9 +14,11 @@ this file adds the kernel build details. | --- | --- | --- | --- | | stable | the GitHub Release for a `v*` tag, e.g. [`releases/latest`](https://github.com/aurora-silicon/linux/releases/latest) | a `v*` tag is pushed on a `main` commit | never: a stable release is not rebuilt or edited | | nightly | prerelease tag [`aurora-nightly`](https://github.com/aurora-silicon/linux/releases/tag/aurora-nightly) | once a day, if `main` moved since the last nightly | tag and assets replaced each night | -| edge | prerelease tag [`aurora-edge`](https://github.com/aurora-silicon/linux/releases/tag/aurora-edge) | every push to `main` (a newer push cancels the running build) | tag and assets replaced on every push | +| edge | prerelease tag [`aurora-edge`](https://github.com/aurora-silicon/linux/releases/tag/aurora-edge) | every push to `main`; a running build always finishes and only the newest waiting push is built next | tag and assets replaced on every build | -Each release body names the exact `main` commit it was built from. `edge` is +Each release body names the exact commit it was built from, and every asset +carries a build provenance attestation from `kernel-release.yml` +(`gh attestation verify --repo aurora-silicon/linux`). `edge` is for testing what just merged; `nightly` is the candidate pool for the next stable tag; `stable` is what distributions ship by default. @@ -45,10 +47,11 @@ not published here. Stable releases are time-boxed. On the release cadence: 1. Take the commit the current `aurora-nightly` was built from (it is in the - release body), once it has passed the lab regression gate: every lab Mac - (M1 Pro, M2 Air, M2 mini, M3 Air, M4 Air, M4 Pro, Neo) boots it with no new - failures compared with the previous stable release. The gate looks for - regressions only; missing features do not block a tag. + release body), once it has passed the + [lab regression gate](https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/branching-and-releases.md#4-cutting-a-stable-release): + it boots and passes on every gate Mac with no new failures compared with the + previous stable release. The gate looks for regressions only; missing + features do not block a tag. 2. An Owner tags it and pushes the tag (only Owners create `v*` tags, and nobody moves or deletes one): From 9f1d55b83b4ffd383bdc08d27895d4c7bbdd2bcb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:33:54 +1100 Subject: [PATCH 0982/1514] drm/asahi: let the G14 27.2 GPU use its full performance-state range The G14 27.2 runtime wrote the board's performance-state ceiling to two of the three Globals state selectors (+0x88, +0x8c) but left the third (+0x98) at 100, the first state above idle. That held the GPU at its lowest active state (about a third of its top clock on the M2) for every workload. G14 13.5, M3 27.2 and M4 27.2 write the ceiling to all three selectors. Do the same: the value comes from the board's performance-state table in the device tree, and the firmware's power and thermal controller (fast-die loop, thermal thresholds, SoC-hot alarm, all unchanged) decides how much of that range the GPU may use. The selector offsets move into the 27.2 ABI module so the host test checks them against the progress-check words. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 19 +++++++++++++++++-- drivers/gpu/drm/asahi/gpu/v27_2.rs | 11 +++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 4e7fd8de186e58..20f172fdb52e96 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -93,6 +93,12 @@ pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 8] = [ /// Size of the 27.2 Globals object. pub(crate) const GLOBALS_BYTES: usize = 0xe48; +/// Globals words of the three performance-state selectors, in hundredths of a state. All three +/// take the ceiling of the board's performance-state table, as G14 13.5 (`initdata`), M3 27.2 +/// (`m3_power_26`) and M4 27.2 (`g16/fw/initdata`) write them; a lower value here caps the GPU +/// clock below what the firmware's power and thermal controller would allow. +pub(crate) const GLOBALS_PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -173,12 +179,12 @@ mod tests { #[test] fn progress_words_fit_the_globals_and_leave_power_words_alone() { - let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; + let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84]; for (i, &(at, value)) in GLOBALS_PROGRESS.iter().enumerate() { assert_eq!(at % 4, 0); assert!(at + 4 <= GLOBALS_BYTES); assert_ne!(value, 0); - assert!(power.iter().all(|&p| p + 4 <= at || at + 4 <= p)); + assert!(power.iter().chain(&GLOBALS_PSTATE_SELECTORS).all(|&p| p + 4 <= at || at + 4 <= p)); assert!(GLOBALS_PROGRESS[i + 1..].iter().all(|&(other, _)| other != at)); } // Every progress interval is set: a zero interval is what stopped work in a poll. @@ -186,4 +192,13 @@ mod tests { assert!(GLOBALS_PROGRESS.iter().any(|&(o, v)| o == at && v != 0)); } } + + #[test] + fn pstate_selectors_are_aligned_distinct_words_of_the_globals() { + for (i, &at) in GLOBALS_PSTATE_SELECTORS.iter().enumerate() { + assert_eq!(at % 4, 0); + assert!(at + 4 <= GLOBALS_BYTES); + assert!(GLOBALS_PSTATE_SELECTORS[i + 1..].iter().all(|&o| o + 4 <= at || at + 4 <= o)); + } + } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 32d11d7ae6e746..70e9207001035a 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -42,9 +42,6 @@ const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; -/// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. -/// Only this cap has run on hardware. -const STATE_CAP: u32 = 100; /// Board facts the root needs, read from the device tree at probe. pub(crate) struct BoardV27_2 { @@ -1067,9 +1064,11 @@ impl RootV27_2 { for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); } - let ceiling = pwr.perf_max_pstate * 100; - for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, STATE_CAP)] { - put32(data, at, value); + put32(data, 0x84, pwr.max_power_mw); + // The performance-state ceiling the board's table describes; the power and thermal + // controller below decides how much of it the GPU may use. + for at in g14_v27_2_abi::GLOBALS_PSTATE_SELECTORS { + put32(data, at, pwr.perf_max_pstate * 100); } put32(data, 0x6e, 1); // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. From d3735de5963f5540ae0c3e11c3c6618c341ad190 Mon Sep 17 00:00:00 2001 From: Friedrich <261542475+aeries0x@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:15:10 +0100 Subject: [PATCH 0983/1514] thermal: apple-pmp: no Air power budget on fan-cooled boards The T8132 PMP thermal driver runs one policy on every M4 Mac on the firmware path: the die guard (cooling from 106 C, target 110 C, full protection 115 C, shutdown after three samples at 120 C) plus the fanless MacBook Air's measured-rail energy budget, a 600 J burst at up to 20 W, then 8 W regulated toward an 85 C filtered die with a 4 W floor. On a Mac with a fan that budget defeats the fan, whose speed the SMC appears to set from the heat the SoC makes. On the J604 (MacBook Pro 14-inch, M4), with ten busy loops for 180 s on Aurora's linux-aurora 7.3.0.aurora1-37 package, the burst ran out after 53 s, the P and E rails (PP0b + PPbb) fell from up to 22.7 W to 5-12 W, the heatpipe power (PHPC) from up to 28 W to 8-17 W, and 19 s later the SMC set the fan target to 0 for the rest of the load. macOS 27.2 on the same Mac, same load: the fan ramps from 2500 rpm to its 6550 rpm maximum and never stops. Drop the budget on every board whose device tree describes a fan: an available child with apple,fan-maximum under an available apple,smc-hwmon node. On the current T8132 device trees that is the J604, the J623 and J624 (iMac) and the J773g (Mac mini); the J713 and J715 (Air) have no fan node and keep the budget. The die guard stays on every board: the rails are still read and reported, a rail fault or a telemetry gap still selects full protection and recovers one step per second, but sustained power no longer restricts. While every die sensor is dark (-ENODATA) during idle and the SMC rails are read cleanly, unbudgeted boards have no temperature-driven energy bucket, so keep the sample timestamp and hwmon rail sum current instead of letting a >2 s dark span trigger the gap fault clamp on wake. The GPU still gets full protection while the sensors are dark, a genuine >2 s telemetry gap still fails closed, and any prior fault remains latched until valid die samples confirm recovery. Signed-off-by: Friedrich <261542475+aeries0x@users.noreply.github.com> --- drivers/thermal/apple-pmp-policy-test.c | 91 +++++++++++++++++++++ drivers/thermal/apple-pmp-thermal.c | 43 ++++++++-- include/linux/soc/apple/pmp-power-policy.h | 92 ++++++++++++++++++---- 3 files changed, 204 insertions(+), 22 deletions(-) diff --git a/drivers/thermal/apple-pmp-policy-test.c b/drivers/thermal/apple-pmp-policy-test.c index b1786634b89f83..691af74c91e921 100644 --- a/drivers/thermal/apple-pmp-policy-test.c +++ b/drivers/thermal/apple-pmp-policy-test.c @@ -153,6 +153,95 @@ static void apple_pmp_test_gpu_attachment(struct kunit *test) KUNIT_EXPECT_EQ(test, state.level[2], 0U); } +static void apple_pmp_test_unbudgeted(struct kunit *test) +{ + struct apple_pmp_power_policy state; + u32 rails[3] = {20000, 4000, 12000}; + unsigned long long now = 0; + unsigned int i; + + apple_pmp_power_init_unbudgeted(&state); + apple_pmp_power_set_active(&state, 7); + /* A cool start grants no burst credit; restricted until confirmed. */ + for (i = 1; i <= 3; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 50000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.credit_mj, 0LL); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 23U); + /* Then one step per second, however hot and loaded. */ + for (i = 0; i < 20; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 13U); + /* Sustained heavy load on a hot die never restricts again. */ + for (i = 0; i < 1200; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.total_mw, 36000); + KUNIT_EXPECT_EQ(test, state.level[0], 0U); + KUNIT_EXPECT_EQ(test, state.level[1], 0U); + KUNIT_EXPECT_EQ(test, state.level[2], 0U); + KUNIT_EXPECT_EQ(test, state.credit_mj, 0LL); + /* A rail fault still selects full protection. */ + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, -EIO); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0], 8U); + KUNIT_EXPECT_EQ(test, state.level[2], 8U); + /* Recovery: three good samples, then one step per second. */ + for (i = 0; i < 22; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 14U); + for (i = 0; i < 38; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A telemetry gap also selects full protection. */ + apple_pmp_power_sample(&state, now += 2500000000ULL, rails, 105000, 0); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[1], 8U); +} + +static void apple_pmp_test_unbudgeted_dark(struct kunit *test) +{ + struct apple_pmp_power_policy state, budgeted; + u32 rails[3] = {400, 200, 100}; + u32 load[3] = {15000, 3000, 0}; + unsigned long long now = 0; + unsigned int i; + + apple_pmp_power_init_unbudgeted(&state); + apple_pmp_power_set_active(&state, 7); + for (i = 0; i < 60; i++) + apple_pmp_power_sample(&state, now += 500000000ULL, load, 60000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A 10 s dark-sensor span keeps rail telemetry fresh without clamping. */ + for (i = 0; i < 20; i++) + apple_pmp_power_dark(&state, now += 500000000ULL, rails); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.last_ns, now); + KUNIT_EXPECT_EQ(test, state.total_mw, 700); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + apple_pmp_power_sample(&state, now += 500000000ULL, load, 65000, 0); + KUNIT_EXPECT_FALSE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 0U); + /* A genuine >2 s gap while dark still fails closed. */ + apple_pmp_power_dark(&state, now += 2500000000ULL, rails); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0], 8U); + KUNIT_EXPECT_EQ(test, state.level[1], 8U); + KUNIT_EXPECT_EQ(test, state.level[2], 8U); + /* Dark samples never clear a latched fault or release levels. */ + for (i = 0; i < 10; i++) + apple_pmp_power_dark(&state, now += 500000000ULL, rails); + KUNIT_EXPECT_TRUE(test, state.fault); + KUNIT_EXPECT_EQ(test, state.level[0] + state.level[1] + state.level[2], 24U); + /* On a budgeted (Air) policy, apple_pmp_power_dark() is a no-op. */ + apple_pmp_power_init(&budgeted); + apple_pmp_power_set_active(&budgeted, 3); + apple_pmp_power_sample(&budgeted, 500000000ULL, load, 60000, 0); + apple_pmp_power_dark(&budgeted, 1000000000ULL, rails); + KUNIT_EXPECT_EQ(test, budgeted.last_ns, 500000000ULL); + KUNIT_EXPECT_EQ(test, budgeted.total_mw, 18000); +} + static struct kunit_case apple_pmp_policy_cases[] = { KUNIT_CASE(apple_pmp_test_fault_recovery), KUNIT_CASE(apple_pmp_test_poll_cadence), @@ -161,6 +250,8 @@ static struct kunit_case apple_pmp_policy_cases[] = { KUNIT_CASE(apple_pmp_test_gpu_budget_freshness), KUNIT_CASE(apple_pmp_test_shared_power_arbitration), KUNIT_CASE(apple_pmp_test_gpu_attachment), + KUNIT_CASE(apple_pmp_test_unbudgeted), + KUNIT_CASE(apple_pmp_test_unbudgeted_dark), {}, }; diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index 1801153f2bb1e7..4056d7078f6897 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -98,11 +98,12 @@ static int apple_pmp_power_status(char *buffer, const struct kernel_param *kp) guard(mutex)(&pmp_thermal.lock); return scnprintf(buffer, PAGE_SIZE, - "ns=%llu p_mw=%u e_mw=%u gpu_mw=%u total_mw=%d sustainable_mw=%d allowed_mw=%d credit_mj=%lld filtered_mc=%d p_level=%u e_level=%u gpu_level=%u fault=%d error=%d\n", + "ns=%llu p_mw=%u e_mw=%u gpu_mw=%u total_mw=%d sustainable_mw=%d allowed_mw=%d credit_mj=%lld filtered_mc=%d p_level=%u e_level=%u gpu_level=%u fault=%d error=%d budget=%d\n", p->last_ns, pmp_thermal.rail_mw[0], pmp_thermal.rail_mw[1], pmp_thermal.rail_mw[2], p->total_mw, p->sustainable_mw, p->allowed_mw, p->credit_mj, p->filtered_mc, - p->level[0], p->level[1], p->level[2], p->fault, pmp_thermal.power_error); + p->level[0], p->level[1], p->level[2], p->fault, pmp_thermal.power_error, + !p->unbudgeted); } static const struct kernel_param_ops apple_pmp_power_status_ops = { .get = apple_pmp_power_status, @@ -226,8 +227,13 @@ static void apple_pmp_power_work(struct work_struct *work) /* * Nothing else restricts the GPU's budget while the sensors are * dark: a zero publication selects full protection, and the next - * real budget sample republishes its level at once. + * real budget sample republishes its level at once. On fan-cooled + * boards there is no temperature-driven energy budget, so keep + * rail freshness and hwmon totals current while dark instead of + * turning a >2 s dark span into a fault clamp on wake. */ + if (p->unbudgeted) + apple_pmp_power_dark(p, now, mw); apple_pmp_gpu_publish(pmp_thermal.sensors, epoch, 8, 0); } else { apple_pmp_power_sample(p, now, mw, pmp_thermal.cached_mc, ret); @@ -273,7 +279,8 @@ static int apple_pmp_power_label(struct device *dev, enum hwmon_sensor_types typ }; if (type != hwmon_power || channel < 0 || channel > 3) return -EINVAL; - *label = labels[channel]; + *label = channel == 3 && pmp_thermal.power.unbudgeted ? + "CPU/GPU rail sum" : labels[channel]; return 0; } static const struct hwmon_ops apple_pmp_power_ops = { @@ -705,6 +712,24 @@ static int apple_pmp_add_cluster(unsigned int index, unsigned int cpu, return 0; } +/* + * A board whose available SMC hwmon node describes an available fan (a child + * with apple,fan-maximum) is fan cooled: the SMC appears to set the fan speed + * from the heat the SoC makes, so the fanless Airs' energy budget would + * starve the fan. The die guard below applies unchanged. + */ +static bool apple_pmp_unbudgeted(void) +{ + for_each_compatible_node_scoped(hwmon, NULL, "apple,smc-hwmon") { + if (!of_device_is_available(hwmon)) + continue; + for_each_available_child_of_node_scoped(hwmon, child) + if (of_property_present(child, "apple,fan-maximum")) + return true; + } + return false; +} + static int apple_pmp_thermal_setup(void) { struct thermal_zone_device *zone; @@ -718,7 +743,10 @@ static int apple_pmp_thermal_setup(void) p_members = BIT(0) | GENMASK(5, 3); e_members = GENMASK(2, 1) | GENMASK(9, 6); } - apple_pmp_power_init(&pmp_thermal.power); + if (apple_pmp_unbudgeted()) + apple_pmp_power_init_unbudgeted(&pmp_thermal.power); + else + apple_pmp_power_init(&pmp_thermal.power); apple_pmp_cooling_init(&pmp_thermal.cooling); pmp_thermal.guard_level = 8; ret = apple_pmp_add_cluster(0, 0, p_members); @@ -767,7 +795,10 @@ static int apple_pmp_thermal_setup(void) if (ret) goto fail; } - pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, shared measured-rail power budget\n"); + pr_info("apple-pmp-thermal: T8132 provisional policy: CPU/GPU cooling from 106 C, target 110 C, full protection 115 C, three >=120 C samples for shutdown, 5 ms sampling from 95 C or while cooling (100 ms below), 100 ms governor, %s\n", + pmp_thermal.power.unbudgeted ? + "no power budget (fan cooled; rail faults still restrict)" : + "shared measured-rail power budget"); pmp_thermal.ready = true; return 0; fail: diff --git a/include/linux/soc/apple/pmp-power-policy.h b/include/linux/soc/apple/pmp-power-policy.h index faef838ea24126..bbd5699b1114df 100644 --- a/include/linux/soc/apple/pmp-power-policy.h +++ b/include/linux/soc/apple/pmp-power-policy.h @@ -19,7 +19,7 @@ struct apple_pmp_power_policy { int sustainable_mw, allowed_mw, total_mw, filtered_mc; unsigned int level[3], next_release, good; unsigned int active; - bool initialized, fault; + bool initialized, fault, unbudgeted; }; /* SMC little-endian IEEE binary32 Watts -> mW. Reject NaN/Inf, negative, @@ -53,6 +53,20 @@ static inline void apple_pmp_power_init(struct apple_pmp_power_policy *s) }; } +/* A Mac whose fan the SMC appears to run on the heat the SoC makes: the + * energy budget above is the fanless Airs' and takes that heat away, so the + * fan stops and power stays near the floor. Such a board keeps the die guard as its + * limit; the rails are still read, and a fault or a gap in them still selects + * full protection and recovers one step per second, as on the Airs. + */ +static inline void apple_pmp_power_init_unbudgeted(struct apple_pmp_power_policy *s) +{ + apple_pmp_power_init(s); + s->sustainable_mw = 0; + s->allowed_mw = 0; + s->unbudgeted = true; +} + /* A newly attached consumer starts restricted. An absent consumer cannot * absorb releases or be selected as a way to reduce measured consumption. */ @@ -76,6 +90,59 @@ static inline void apple_pmp_power_fail(struct apple_pmp_power_policy *s) s->good = 0; } +/* Release the largest weighted restriction, round-robin on ties. */ +static inline void apple_pmp_power_release(struct apple_pmp_power_policy *s, + unsigned long long now, + const unsigned int weight[3]) +{ + unsigned int i, chosen = 3; + + for (i = 0; i < 3; i++) { + unsigned int candidate = (s->next_release + i) % 3; + + if ((s->active & (1U << candidate)) && s->level[candidate] && + (chosen == 3 || + s->level[candidate] * weight[candidate] > + s->level[chosen] * weight[chosen])) + chosen = candidate; + } + if (chosen < 3) { + s->level[chosen]--; + s->next_release = (chosen + 1) % 3; + } + s->change_ns = now; +} + +/* On an unbudgeted board die temperature does not drive an energy bucket. + * While every die sensor is dark (-ENODATA) and the SMC rails were read, keep + * the rail sum and sample timestamp current so a >2 s idle dark span does not + * trip the gap fault on the next valid die reading. A genuine >2 s telemetry + * gap still fails closed, and any prior fault stays latched until valid die + * samples confirm recovery. + */ +static inline void apple_pmp_power_dark(struct apple_pmp_power_policy *s, + unsigned long long now, + const unsigned int mw[3]) +{ + unsigned long long dt = s->last_ns ? now - s->last_ns : 0; + unsigned int i; + + if (!s->unbudgeted) + return; + if (dt > 2000000000ULL) { + apple_pmp_power_fail(s); + s->last_ns = now; + return; + } + if (s->last_ns && dt < 400000000ULL) + return; + s->last_ns = now; + s->total_mw = 0; + for (i = 0; i < 3; i++) + if (s->active & (1U << i)) + s->total_mw += mw[i]; +} + static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, unsigned long long now, const unsigned int mw[3], int mc, int error) { @@ -104,7 +171,7 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, s->total_mw += mw[i]; if (!s->initialized) { s->initialized = true; - s->credit_mj = mc < 75000 ? APPLE_PMP_BURST_MJ : 0; + s->credit_mj = mc < 75000 && !s->unbudgeted ? APPLE_PMP_BURST_MJ : 0; s->filtered_mc = mc; s->tune_ns = now; } @@ -114,6 +181,12 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, return; s->fault = false; s->filtered_mc += (mc - s->filtered_mc) * (long long)ms / (long long)(5000 + ms); + if (s->unbudgeted) { + /* Release one step per second; nothing restricts again. */ + if (now - s->change_ns >= 1000000000ULL) + apple_pmp_power_release(s, now, weight); + return; + } if (s->total_mw > s->sustainable_mw) s->credit_mj -= (s->total_mw - s->sustainable_mw) * (long long)ms / 1000; else if (mc < 75000) @@ -163,20 +236,7 @@ static inline void apple_pmp_power_sample(struct apple_pmp_power_policy *s, * This restores graphics headroom before spending it on CPU stress. * Fault recovery still restores only one step per elapsed interval. */ - for (i = 0; i < 3; i++) { - unsigned int candidate = (s->next_release + i) % 3; - - if ((s->active & (1U << candidate)) && s->level[candidate] && - (chosen == 3 || - s->level[candidate] * weight[candidate] > - s->level[chosen] * weight[chosen])) - chosen = candidate; - } - if (chosen < 3) { - s->level[chosen]--; - s->next_release = (chosen + 1) % 3; - } - s->change_ns = now; + apple_pmp_power_release(s, now, weight); } } From 1f3b8a34155d990d29a3cbf3ecffc1cdc2bdce8b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:38:13 +1100 Subject: [PATCH 0984/1514] ci: publish kernel releases from the release environment Run the publish job in the release environment, which deploys only from main and v* tags, and keep RELEASE_DEPLOY_KEY there as an environment secret. A workflow run on any other branch cannot read the key that bypasses the aurora-* tag ruleset. Signed-off-by: Ryan Murray --- .github/workflows/kernel-release.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 4718f980a36a42..0424c9cd7705e8 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -17,7 +17,8 @@ # the KUnit suites built as modules) before anything is published. # # The aurora-* channel tags are protected by a ruleset; the publish job moves -# them over SSH with the release deploy key (secret RELEASE_DEPLOY_KEY), only +# them over SSH with the release deploy key (RELEASE_DEPLOY_KEY, a secret of the +# release environment, which deploys only from main and v* tags), only # forward and with a lease. Stable releases attach to the v* tag an Owner pushed. # Every published asset gets a build provenance attestation. # @@ -264,6 +265,9 @@ jobs: needs: [plan, build, smoke] if: needs.plan.outputs.channel != 'none' && needs.plan.outputs.build == 'true' runs-on: ubuntu-24.04-arm + # The release environment only deploys from main and v* tags and holds + # RELEASE_DEPLOY_KEY, so no other branch's run can read the key. + environment: release concurrency: group: kernel-release-publish-${{ needs.plan.outputs.channel }} cancel-in-progress: false From 1bde4938f3f69da89bf9807858ad8d9b72291a1e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0985/1514] drm/apple: send a paired mode set's calls in the engine's firmware 27 build The paired mode set (a mode too wide for one engine, run on two) sends its IOMFB calls through dcp_peer_video_call_stream() (and the opt-in peer setup diagnostic through peer_setup_test_store()), naming them by their 27.0 IDs. Firmware 27.2 renumbered the IOMobileFramebufferAP methods, and an ID the firmware does not know panics it: on a 27.2 stub the paired prepare's set_display_device went out as A411 and crashed both engines. Record every paired-mode and sleep method ID in each firmware 27 build's table (the shifted IDs on 27.2, plus the unchanged paired/DSC hand-off and sleep calls) while keeping them optional for single-engine boot admission in iomfb_v27_missing_method(). Translate each call's ID through iomfb_v27_tag(): on 27.0 (including the J714s copy) every ID is sent unchanged; on a renumbered build every ID must come from the build's table, returning -EOPNOTSUPP instead of sending an unmapped ID. Update the t6041-v27-admission host test fixture for the table helpers it extracts. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp-peer-probe-v27.inc | 9 +- .../drm/apple/dcp-peer-video-probe-v27.inc | 5 +- drivers/gpu/drm/apple/iomfb.h | 25 ++++ drivers/gpu/drm/apple/iomfb_v27.c | 111 +++++++++++++++++- .../selftests/drivers/gpu/apple-dcp/boot.py | 2 + 5 files changed, 146 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc index 33def11c752ea1..a1c017c98e0853 100644 --- a/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-probe-v27.inc @@ -24,9 +24,7 @@ static ssize_t peer_setup_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { - static const struct dcp_method_entry method = { - .name = "setup_peer_dcp", .tag = {'A', '3', '6', '6'}, - }; + struct dcp_method_entry method = { .name = "setup_peer_dcp" }; struct apple_dcp *dcp = dev_get_drvdata(dev); struct dcp_peer_probe_wait *wait; __le32 enabled = cpu_to_le32(1); @@ -55,6 +53,11 @@ static ssize_t peer_setup_test_store(struct device *dev, kref_put(&wait->refs, dcp_peer_probe_free); return -EBUSY; } + ret = iomfb_v27_tag(dcp->v27_methods, "A366", method.tag); + if (ret) { + kref_put(&wait->refs, dcp_peer_probe_free); + return ret; + } kref_get(&wait->refs); /* Peer-DCP setup (one bool argument): four input * bytes (boolean followed by zero padding), no output. diff --git a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc index 3560cfc447a99f..86b0f20b5823d4 100644 --- a/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-video-probe-v27.inc @@ -37,6 +37,10 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, if (out_size > sizeof(wait->reply)) return -EINVAL; + /* The calls name 27.0 IDs: this engine's build may number them differently. */ + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; /* An unrelated AP thread gets its own firmware stream. A369/A367/etc. * must not be mistaken for nested callbacks of the pending A413. * Stream1 (the driver's OOB context) is independent of stream0. @@ -46,7 +50,6 @@ static int dcp_peer_video_call_stream(struct apple_dcp *dcp, bool independent, wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; - memcpy(method.tag, tag, sizeof(method.tag)); wait->size = out_size; init_completion(&wait->done); kref_init(&wait->refs); diff --git a/drivers/gpu/drm/apple/iomfb.h b/drivers/gpu/drm/apple/iomfb.h index e230a9eac9c5c1..0b2c04b7c61232 100644 --- a/drivers/gpu/drm/apple/iomfb.h +++ b/drivers/gpu/drm/apple/iomfb.h @@ -198,6 +198,28 @@ enum dcpep_method { dcpep_pipe_set_476, dcpep_unnamed_500, iomfbep_set_brightness_correction, + /* + * Firmware 27.x sleep and paired-mode calls named by their 27.0 ID. + * Optional for single-engine boot (iomfb_v27_missing_method() skips + * them); iomfb_v27_tag() refuses any call missing from a renumbered + * table. + */ + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, + dcpep_v27_peer_a360, + dcpep_v27_peer_a361, + dcpep_v27_peer_a362, + dcpep_v27_peer_a364, + dcpep_v27_peer_a365, + dcpep_v27_peer_a366, + dcpep_v27_peer_a367, + dcpep_v27_peer_a368, + dcpep_v27_peer_a369, + dcpep_v27_peer_a370, + dcpep_v27_peer_a371, + dcpep_v27_peer_a372, + dcpep_v27_peer_a373, + dcpep_v27_peer_a449, dcpep_num_methods }; @@ -220,6 +242,9 @@ struct dcp_method_entry { /* The IOMFB method table of a firmware 27.x build, by its compat string; NULL if unknown. */ const struct dcp_method_entry *iomfb_v27_methods(const char *compat); +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods); +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out); +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods); const struct dcp_method_entry *iomfb_v27_methods_j714s(struct device *dev, const struct dcp_method_entry *methods); /* The first method of a firmware 27.x table that has no ID, NULL if none. */ diff --git a/drivers/gpu/drm/apple/iomfb_v27.c b/drivers/gpu/drm/apple/iomfb_v27.c index c2a6d2413a45dc..def54604d8c302 100644 --- a/drivers/gpu/drm/apple/iomfb_v27.c +++ b/drivers/gpu/drm/apple/iomfb_v27.c @@ -164,6 +164,22 @@ static const struct dcp_method_entry dcp_methods_27_0[dcpep_num_methods] = { * the IOMFB calls around it; 27.2 moved both to A550/A551. */ IOMFB_METHOD("A500", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A442", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A449", dcpep_v27_peer_a449), }; /* @@ -222,6 +238,22 @@ static const struct dcp_method_entry dcp_methods_27_2[dcpep_num_methods] = { * dispatch where 26A428's compares 'A500' (0x1df68c vs 0x1de0dc, same code). */ IOMFB_METHOD("A550", dcpep_unnamed_500), + IOMFB_METHOD("A115", dcpep_v27_sleep_a115), + IOMFB_METHOD("A492", dcpep_v27_wake_a442), + IOMFB_METHOD("A360", dcpep_v27_peer_a360), + IOMFB_METHOD("A361", dcpep_v27_peer_a361), + IOMFB_METHOD("A362", dcpep_v27_peer_a362), + IOMFB_METHOD("A364", dcpep_v27_peer_a364), + IOMFB_METHOD("A365", dcpep_v27_peer_a365), + IOMFB_METHOD("A366", dcpep_v27_peer_a366), + IOMFB_METHOD("A367", dcpep_v27_peer_a367), + IOMFB_METHOD("A368", dcpep_v27_peer_a368), + IOMFB_METHOD("A369", dcpep_v27_peer_a369), + IOMFB_METHOD("A370", dcpep_v27_peer_a370), + IOMFB_METHOD("A371", dcpep_v27_peer_a371), + IOMFB_METHOD("A372", dcpep_v27_peer_a372), + IOMFB_METHOD("A373", dcpep_v27_peer_a373), + IOMFB_METHOD("A499", dcpep_v27_peer_a449), }; /* @@ -269,6 +301,76 @@ const struct dcp_method_entry *iomfb_v27_methods(const char *compat) return NULL; } +/* + * Translate @tag, a 27.0 ID named directly by sleep or paired-mode callers, + * into the build of @methods (4 bytes in @out). On 27.0 (including the J714s + * copy) the tag is sent unchanged. On a renumbered build every ID must come + * from @methods; a missing entry returns -EOPNOTSUPP instead of sending an + * unknown tag that would panic the firmware. + */ +int iomfb_v27_tag(const struct dcp_method_entry *methods, const char *tag, char *out) +{ + unsigned int i; + char in[4]; + + if (!methods) + return -EOPNOTSUPP; + memcpy(in, tag, 4); + if (!iomfb_v27_methods_renumbered(methods)) { + memcpy(out, in, 4); + return 0; + } + for (i = 0; i < dcpep_num_methods; i++) { + if (dcp_methods_27_0[i].tag[0] && !memcmp(dcp_methods_27_0[i].tag, in, 4)) { + if (!methods[i].tag[0]) + return -EOPNOTSUPP; + memcpy(out, methods[i].tag, 4); + return 0; + } + } + return -EOPNOTSUPP; +} + +/* Whether @methods is a build's table whose AP method IDs differ from 27.0's. */ +bool iomfb_v27_methods_renumbered(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods || methods == dcp_methods_27_0) + return false; + for (i = 0; i < dcpep_num_methods; i++) { + if (memcmp(methods[i].tag, dcp_methods_27_0[i].tag, 4) && + !(i == dcpep_swap_submit && !memcmp(methods[i].tag, "A407", 4))) + return true; + } + return false; +} + +static const enum dcpep_method iomfb_v27_sleep_methods[] = { + dcpep_is_main_display, + dcpep_pipe_cfg_414, + dcpep_set_power_state, + dcpep_pipe_set_476, + dcpep_pipe_query_478, + dcpep_unnamed_500, + dcpep_v27_sleep_a115, + dcpep_v27_wake_a442, +}; + +/* Whether @methods names an ID for every call the firmware 27 display sleep sends. */ +bool iomfb_v27_sleep_methods_complete(const struct dcp_method_entry *methods) +{ + unsigned int i; + + if (!methods) + return false; + for (i = 0; i < ARRAY_SIZE(iomfb_v27_sleep_methods); i++) { + if (!methods[iomfb_v27_sleep_methods[i]].tag[0]) + return false; + } + return true; +} + /* * The 27.0 table for the J714s, the board the firmware 27 sleep has run on (dcp->v27_j714s): a * copy with the sleep's A500 added. The shared table keeps the methods it had, so every other @@ -309,9 +411,14 @@ const char *iomfb_v27_missing_method(const struct dcp_method_entry *methods, *count = 0; for (i = 0; i < dcpep_num_methods; i++) { - /* Only a firmware sleep sends unnamed_500, and it checks the build's table. */ + /* + * Only sleep and paired-mode paths send unnamed_500 and the + * v27-optional entries; each checks the build's table before + * sending. + */ if (!dcp_methods_27_0[i].tag[0] || methods[i].tag[0] || - i == dcpep_dfb_ready_query || i == dcpep_unnamed_500) + i == dcpep_dfb_ready_query || i == dcpep_unnamed_500 || + i >= dcpep_v27_sleep_a115) continue; if (!first) first = dcp_methods_27_0[i].name; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 7a23fdb3ff45f4..0f07b51a66b964 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -216,10 +216,12 @@ def _v27_prelude(root, helpers): method_table = block(dcp_c, 'static enum dcp_firmware_version dcp_v27_method_table(') return r''' #include +#include #include #include #include #include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef uint32_t u32; enum dcp_firmware_version { DCP_FIRMWARE_UNKNOWN, From f57ed85491abeae18b1b40064ebde8f0d229227b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0986/1514] drm/apple: send the firmware 27 calls named by ID in the engine's build Besides the paired video calls, the firmware 27 paths name several calls by their 27.0 IDs: the primary's paired mode set (A413) and power step (A484), the paired background swap (A408), the sleep's power and A500 steps, the display stage calls and the out-of-band wake call (A442). On 27.2, which renumbered IOMobileFramebufferAP, several of those IDs are other methods: the paired mode's power step ran one and failed, and the second engine of a 4K240 mode never started. Translate each of them through iomfb_v27_tag() and refuse the call instead of sending it when the build's table lacks an entry. Zero the internal wake A442 payload's filler bytes on renumbered builds, where 27.2 rejects the 0xaa filler as an index count and block size. The J714s's A407 swap keeps its ID, which only its 27.0 table names, and its diagnostic now refuses a pair whose engines take different swap forms. 27.0 sends what it sent. Signed-off-by: Erik Bourget --- .../drm/apple/dcp-peer-modeset-probe-v27.inc | 18 ++++++++--- .../gpu/drm/apple/dcp-peer-swap-probe-v27.inc | 14 +++++++-- drivers/gpu/drm/apple/iomfb.c | 30 +++++++++++++------ 3 files changed, 47 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc index a5aa449b446dd0..0ac6d6c3447618 100644 --- a/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-modeset-probe-v27.inc @@ -7,11 +7,16 @@ static int dcp_peer_probe_power(struct apple_dcp *dcp, struct apple_dcp *peer, bool on) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_power_test", - .tag = {'A', '4', '8', '4'} }; + struct dcp_method_entry method = { .name = "peer_power_test" }; u8 power[16] = {}, response[8]; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A484", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A484", peer_tag); + if (ret) + return ret; + wait = kzalloc(sizeof(*wait), GFP_KERNEL); if (!wait) return -ENOMEM; @@ -134,13 +139,18 @@ static int dcp_peer_probe_modeset(struct apple_dcp *dcp, struct apple_dcp *peer, bool firmware_requires_merge) { struct dcp_peer_video_wait *wait; - struct dcp_method_entry method = { .name = "peer_modeset_test", - .tag = {'A', '4', '1', '3'} }; + struct dcp_method_entry method = { .name = "peer_modeset_test" }; __le32 mode[2] = {video->color_id, video->timing_id}; u32 primary_id, peer_id, phase, status; unsigned long deadline; + char peer_tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A413", method.tag) ?: + iomfb_v27_tag(peer->v27_methods, "A413", peer_tag); + if (ret) + return ret; + { guard(mutex)(&dcp_peer_lock); if (dcp->peer_reserved != peer || peer->peer_owner != dcp || diff --git a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc index ed73f355eda7ec..343fa1872badae 100644 --- a/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-swap-probe-v27.inc @@ -6,6 +6,7 @@ struct dcp_peer_background { struct iomfb_transaction transaction; struct dcp_peer_video_wait *wait; struct dcp_swap_submit_req_v27 wire; + char tag[4]; bool sent; }; @@ -26,10 +27,11 @@ static void dcp_peer_background_start(struct apple_dcp *dcp, { struct dcp_peer_background *background = container_of(transaction, struct dcp_peer_background, transaction); - struct dcp_method_entry method = { .name = "peer_background_test", - .tag = {'A', '4', '0', '8'} }; + struct dcp_method_entry method = { .name = "peer_background_test" }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; + memcpy(method.tag, background->tag, sizeof(method.tag)); + background->sent = true; if (!dcp_present_begin_h17p(&dcp->present_state_h17p, background->wire.swap.swap_id)) { @@ -55,13 +57,18 @@ static int dcp_peer_queue_background(struct apple_dcp *dcp, struct dcp_peer_video_wait *wait) { struct dcp_peer_background *background; + char tag[4]; int ret; + ret = iomfb_v27_tag(dcp->v27_methods, "A408", tag); + if (ret) + return ret; background = kzalloc_obj(*background); if (!background) return -ENOMEM; background->wire = *wire; background->wait = wait; + memcpy(background->tag, tag, sizeof(background->tag)); kref_get(&wait->refs); background->transaction.start = dcp_peer_background_start; background->transaction.release = dcp_peer_background_release; @@ -185,6 +192,7 @@ static void dcp_peer_a407_background_start(struct apple_dcp *dcp, { struct dcp_peer_a407_background *background = container_of(transaction, struct dcp_peer_a407_background, transaction); + /* The J714s's 27.0 swap form, whose table names A407 (iomfb_v27_methods_j714s()). */ struct dcp_method_entry method = { .name = "peer_background_test", .tag = {'A', '4', '0', '7'} }; struct dcp_swap_submit_resp_v27 failed = { .ret = ~0U }; @@ -345,6 +353,8 @@ static ssize_t peer_swap_test_store(struct device *dev, dcp->crtc->base.state->active || peer->crtc->base.state->active || dcp->fw_compat != DCP_FIRMWARE_V_27_0 || peer->fw_compat != DCP_FIRMWARE_V_27_0 || + /* Both engines must take the swap form the owner sends. */ + dcp->v27_a407 != peer->v27_a407 || !device_trylock(peer->dev)) { ret = -EBUSY; goto out; diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index 9650de884ecc3c..101d10b3bacf52 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -899,11 +899,14 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, rpc->data, iomfb_v27_sleep_done, rpc); dcp->push_out_prefill = NULL; if ((rpc->a442 || rpc->a442_key) && !rpc->oob) { - static const struct dcp_method_entry a442 = { - .name = "v27_a442", .tag = { 'A', '4', '4', '2' }, - }; + struct dcp_method_entry a442 = { .name = "v27_a442" }; u8 in[92]; + if (iomfb_v27_tag(dcp->v27_methods, "A442", a442.tag)) { + dev_warn_once(dcp->dev, "skipping v27 wake A442: unmapped method tag\n"); + return; + } + memset(in, 0xaa, sizeof(in)); memset(in, 0, 16); in[8] = rpc->a442_key ?: 0x41; @@ -911,6 +914,9 @@ static void iomfb_v27_sleep_start(struct apple_dcp *dcp, if (rpc->a442_key) { memset(in + 80, 0, 12); in[84] = 0x20; + } else if (iomfb_v27_methods_renumbered(dcp->v27_methods)) { + /* 27.2 reads the filler as an index count and a block size. */ + memset(in + 16, 0, sizeof(in) - 16); } dcp_push(dcp, true, &a442, sizeof(in), 4100, in, iomfb_v27_a442_done, NULL); } @@ -988,6 +994,9 @@ int iomfb_v27_sleep_plain(struct apple_dcp *dcp, bool on) static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) { + struct dcp_method_entry method = { + .name = a500 ? "v27_sleep_500" : "v27_sleep_power", + }; struct iomfb_v27_sleep_rpc *rpc; u8 args[IOMFB_V27_SLEEP_ARGS]; int ret; @@ -998,6 +1007,9 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) (a500 || flags ? iomfb_v27_sleep_args(dcp, a500, args) : iomfb_v27_display_args(dcp, false, args))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, a500 ? "A500" : "A484", method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1006,10 +1018,7 @@ static int iomfb_v27_rpc(struct apple_dcp *dcp, bool a500, bool on, bool flags) rpc->status = ~0U; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { - .name = a500 ? "v27_sleep_500" : "v27_sleep_power", - }; - memcpy(rpc->method.tag, a500 ? "A500" : "A484", 4); + rpc->method = method; /* * Off, before each DCP's and DCPEXT's sleep idle: A484 with the sleep's flags, then * A500's sleep form. On, after the wake: A500's wake form, then A484 with the flags. @@ -1081,6 +1090,7 @@ int iomfb_v27_sleep_a115(struct apple_dcp *dcp, bool awake) static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in, u32 in_len, u32 out_len, bool inout, u8 a442_key) { + struct dcp_method_entry method = { .name = "v27_display_stage" }; struct iomfb_v27_sleep_rpc *rpc; int ret; @@ -1088,6 +1098,9 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in dcp->fw_compat != DCP_FIRMWARE_V_27_0 || in_len > sizeof(rpc->data) || (inout && out_len > sizeof(rpc->data))) return -EOPNOTSUPP; + ret = iomfb_v27_tag(dcp->v27_methods, tag, method.tag); + if (ret) + return ret; rpc = kzalloc_obj(*rpc); if (!rpc) return -ENOMEM; @@ -1097,8 +1110,7 @@ static int iomfb_v27_call(struct apple_dcp *dcp, const char *tag, const void *in rpc->any_reply = true; rpc->transaction.start = iomfb_v27_sleep_start; rpc->transaction.release = iomfb_v27_sleep_release; - rpc->method = (struct dcp_method_entry) { .name = "v27_display_stage" }; - memcpy(rpc->method.tag, tag, 4); + rpc->method = method; rpc->input = in_len; rpc->output = out_len; rpc->inout = inout; From 328e039f569208ca2e92ee027edd6acaf77c079c Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sat, 21 Nov 2026 19:41:33 -0500 Subject: [PATCH 0987/1514] drm/apple: admit the T6050 display sleep transport by method table The T6050 display processors take part in a deep sleep through the firmware 27 endpoint transport, which previously gated on the J716c board compatible and a 27.0.0 compatibility string. On a 27.2 stub no processor registered for the sleep, and every deep sleep was refused ("display 0: no provider"). Admit a T6050 DCP or DCPEXT to the firmware 27 sleep transport whenever its build's method table has an ID for every call the sleep sends (iomfb_v27_sleep_methods_complete()). That covers 27.0 and 27.2 across T6050 boards without a board check while refusing 27.3 until its sleep methods are known. Add the v27-tag-translation host selftest covering table translation, fail-closed refusal on missing/unrecorded IDs, and data-driven sleep transport admission. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp.c | 18 +- .../selftests/drivers/gpu/apple-dcp/boot.py | 191 ++++++++++++++++++ .../selftests/drivers/gpu/apple-dcp/run.py | 1 + 3 files changed, 198 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 556e5cfee9bf00..00e0835b6576cd 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6100,31 +6100,25 @@ static bool dcp_ext26_admitted(struct device_node *np) } /* - * J716c shares the 27.0 endpoint-control wire format, not the J714s normal - * IOMFB method or panel profile. Establish this before RTKit can receive any - * application traffic, including traffic that invalidates a later inventory. + * Firmware 27 (T6050) sleep endpoint-control transport. Establish this before + * RTKit can receive any application traffic, including traffic that invalidates + * a later inventory. Admitted for a T6050 DCP/DCPEXT whose firmware 27 method + * table has an ID for every call the sleep sends. */ static bool dcp_v27_sleep_transport_supported(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - char compat[DCP_FW_VERSION_STR_LEN]; if (!IS_ENABLED(CONFIG_APPLE_SOC_SLEEP)) return false; - if (dcp->v27_j714s) - return true; - if (!of_machine_is_compatible("apple,j716c") || - !of_machine_is_compatible("apple,t6050") || - !(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || + if (!(of_device_is_compatible(dev->of_node, "apple,t6050-dcp") || of_device_is_compatible(dev->of_node, "apple,t6050-dcpext")) || !dcp->hw.adopt_live_session || dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_DEFAULT || dcp->fw_compat != DCP_FIRMWARE_V_27_0) return false; - /* The enum also covers later 27.x method tables. */ - return dcp_read_fw_version(dev, "apple,firmware-compat", compat) >= 0 && - !strcmp(compat, "27.0.0"); + return iomfb_v27_sleep_methods_complete(dcp->v27_methods); } /* diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 0f07b51a66b964..a4e74b38a57d93 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -557,3 +557,194 @@ def t8122_dcpext_v27_admission(root): return 0; } ''' + + +def v27_tag_translation(root): + iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() + methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): + iomfb_h.index('#define IOMFB_MAX_CB')] + v27_c = (root / 'drivers/gpu/drm/apple/iomfb_v27.c').read_text() + v27_tables = v27_c[v27_c.index('static const struct dcp_method_entry dcp_methods_27_0'): + v27_c.index('/* The template\'s calls resolve through')] + dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + transport = block(dcp_c, 'static bool dcp_v27_sleep_transport_supported(') + return r''' +#include +#include +#include +#include +#include +#include +#include +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define CONFIG_APPLE_SOC_SLEEP 1 +#define IS_ENABLED(option) (option) +#define GFP_KERNEL 0 +enum dcp_firmware_version { + DCP_FIRMWARE_UNKNOWN, + DCP_FIRMWARE_V_27_0, +}; +enum dcp_iomfb_method_profile { + DCP_IOMFB_METHODS_DEFAULT, + DCP_IOMFB_METHODS_H17G, +}; +struct device_node { const char *compatible; }; +struct device { struct device_node *of_node; }; +struct apple_dcp_hw_data { + bool adopt_live_session; + enum dcp_iomfb_method_profile iomfb_method_profile; +}; +struct apple_dcp { + struct device *dev; + struct apple_dcp_hw_data hw; + enum dcp_firmware_version fw_compat; + const struct dcp_method_entry *v27_methods; +}; +static int of_device_is_compatible(const struct device_node *np, const char *s) +{ + return np && np->compatible && !strcmp(np->compatible, s); +} +static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) +{ + void *copy = malloc(len); + (void)dev; (void)gfp; + if (copy) + memcpy(copy, src, len); + return copy; +} +''' + methods_decl + '\n' + v27_tables + '\n' + transport + r''' +static void expect_tag(const struct dcp_method_entry *methods, const char *in, const char *want) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == 0); + assert(memcmp(out, want, 4) == 0); +} + +static void expect_tag_fail(const struct dcp_method_entry *methods, const char *in) +{ + char out[4] = { 'X', 'X', 'X', 'X' }; + assert(iomfb_v27_tag(methods, in, out) == -EOPNOTSUPP); + assert(memcmp(out, "XXXX", 4) == 0); +} + +int main(void) +{ + struct device_node node = { .compatible = "apple,t6050-dcp" }; + struct device dev = { .of_node = &node }; + const struct dcp_method_entry *m27_0 = iomfb_v27_methods("27.0.0"); + const struct dcp_method_entry *m27_2 = iomfb_v27_methods("27.2.0"); + const struct dcp_method_entry *m27_3 = iomfb_v27_methods("27.3.0"); + const struct dcp_method_entry *j714s = iomfb_v27_methods_j714s(&dev, m27_0); + struct dcp_method_entry partial_27_2[dcpep_num_methods]; + unsigned int missing_count; + + assert(m27_0 && m27_2 && m27_3 && j714s); + assert(!iomfb_v27_methods_renumbered(NULL)); + assert(!iomfb_v27_methods_renumbered(m27_0)); + assert(!iomfb_v27_methods_renumbered(j714s)); + assert(iomfb_v27_methods_renumbered(m27_2)); + assert(iomfb_v27_methods_renumbered(m27_3)); + + /* NULL table fails closed. */ + expect_tag_fail(NULL, "A411"); + assert(!iomfb_v27_sleep_methods_complete(NULL)); + + /* 27.0 and J714s copy keep 27.0 IDs unchanged. */ + expect_tag(m27_0, "A411", "A411"); + expect_tag(m27_0, "A484", "A484"); + expect_tag(m27_0, "A500", "A500"); + expect_tag(m27_0, "A442", "A442"); + expect_tag(m27_0, "A449", "A449"); + expect_tag(m27_0, "A115", "A115"); + expect_tag(m27_0, "A364", "A364"); + expect_tag(j714s, "A411", "A411"); + expect_tag(j714s, "A408", "A408"); + expect_tag(j714s, "A500", "A500"); + assert(iomfb_v27_sleep_methods_complete(m27_0)); + assert(iomfb_v27_sleep_methods_complete(j714s)); + assert(!iomfb_v27_missing_method(m27_0, &missing_count) && missing_count == 0); + + /* 27.2 translates every recorded shifted and unchanged paired/sleep tag. */ + const struct { const char *in, *out; } map_27_2[] = { + { "A406", "A456" }, { "A408", "A458" }, { "A411", "A461" }, { "A412", "A462" }, + { "A413", "A463" }, { "A414", "A464" }, { "A423", "A473" }, { "A428", "A478" }, + { "A442", "A492" }, { "A449", "A499" }, { "A450", "A500" }, { "A453", "A503" }, + { "A484", "A534" }, { "A487", "A537" }, { "A489", "A539" }, { "A500", "A550" }, + { "A115", "A115" }, + { "A360", "A360" }, { "A361", "A361" }, { "A362", "A362" }, { "A364", "A364" }, + { "A365", "A365" }, { "A366", "A366" }, { "A367", "A367" }, { "A368", "A368" }, + { "A369", "A369" }, { "A370", "A370" }, { "A371", "A371" }, { "A372", "A372" }, + { "A373", "A373" }, + }; + for (unsigned int i = 0; i < ARRAY_SIZE(map_27_2); i++) + expect_tag(m27_2, map_27_2[i].in, map_27_2[i].out); + assert(iomfb_v27_sleep_methods_complete(m27_2)); + assert(!iomfb_v27_missing_method(m27_2, &missing_count) && missing_count == 0); + + /* Unrecorded tags on 27.2 fail closed (no +50 arithmetic, no 27.0 fallback). */ + expect_tag_fail(m27_2, "A495"); + expect_tag_fail(m27_2, "A499"); + expect_tag_fail(m27_2, "A375"); + expect_tag_fail(m27_2, "A999"); + + /* Incomplete renumbered table (27.3) translates recorded entries and fails closed on missing ones. */ + expect_tag(m27_3, "A453", "A503"); + const char *missing_27_3[] = { + "A411", "A413", "A484", "A500", "A442", "A449", "A115", "A364", "A367", + }; + for (unsigned int i = 0; i < ARRAY_SIZE(missing_27_3); i++) + expect_tag_fail(m27_3, missing_27_3[i]); + assert(!iomfb_v27_sleep_methods_complete(m27_3)); + assert(iomfb_v27_missing_method(m27_3, &missing_count) && missing_count > 0); + + /* Dropping an optional sleep/paired entry does not block basic boot admission, + * but does mark sleep incomplete when a sleep entry is missing, and any table + * other than 27.0 or the J714s copy fails closed as renumbered. */ + memcpy(partial_27_2, m27_2, sizeof(partial_27_2)); + partial_27_2[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(partial_27_2)); + expect_tag_fail(partial_27_2, "A442"); + assert(!iomfb_v27_missing_method(partial_27_2, &missing_count) && missing_count == 0); + assert(!iomfb_v27_sleep_methods_complete(partial_27_2)); + + struct dcp_method_entry future_27_x[dcpep_num_methods]; + memcpy(future_27_x, m27_0, sizeof(future_27_x)); + memcpy(future_27_x[dcpep_start_signal].tag, "A501", 4); + future_27_x[dcpep_v27_wake_a442].tag[0] = '\0'; + assert(iomfb_v27_methods_renumbered(future_27_x)); + expect_tag_fail(future_27_x, "A442"); + + /* + * Sleep transport admission keys on T6050 DCP/DCPEXT and table completeness. + * No of_machine_is_compatible() stub exists in this translation unit, enforcing + * at compile time that admission does not gate on a board model. + */ + struct apple_dcp dcp = { + .dev = &dev, + .hw = { .adopt_live_session = true, .iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT }, + .fw_compat = DCP_FIRMWARE_V_27_0, + }; + const char *t6050_compats[] = { "apple,t6050-dcp", "apple,t6050-dcpext" }; + for (unsigned int i = 0; i < ARRAY_SIZE(t6050_compats); i++) { + node.compatible = t6050_compats[i]; + dcp.v27_methods = m27_0; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = j714s; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_2; assert(dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = m27_3; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = partial_27_2; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.v27_methods = NULL; assert(!dcp_v27_sleep_transport_supported(&dcp)); + } + dcp.v27_methods = m27_2; + node.compatible = "apple,t6041-dcp"; assert(!dcp_v27_sleep_transport_supported(&dcp)); + node.compatible = "apple,t6050-dcp"; + dcp.hw.adopt_live_session = false; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.adopt_live_session = true; + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_H17G; assert(!dcp_v27_sleep_transport_supported(&dcp)); + dcp.hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; + dcp.fw_compat = DCP_FIRMWARE_UNKNOWN; assert(!dcp_v27_sleep_transport_supported(&dcp)); + + free((void *)j714s); + puts("PASS v27 tag translation fail-closed and table-driven sleep transport admission"); + return 0; +} +''' diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 2128a160cc4cf8..cabec8e967b3c7 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -94,6 +94,7 @@ def main(): ('boot', 'syslog-policy', boot.syslog, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ('-Wno-unused-function',)), + ('boot', 'v27-tag-translation', boot.v27_tag_translation, ((),), ()), ('edid', 'dpavserv-start', edid.startup, ((),), ()), ('edid', 'service-rebind', edid.rebind, ((),), ()), ('edid', 'provider-admission', edid.admission, ((),), ()), From 346d605686aacacd55c2cd160790e563377373ab Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Mon, 23 Nov 2026 15:12:06 -0700 Subject: [PATCH 0988/1514] soc: apple: rtkit: a mailbox named by a property of its own apple_rtkit_init() finds its mailbox in mboxes, by index or by name. The K116s's boot loader hands the display over only to a coprocessor node with a single mailbox in mboxes, so the DCP's secure port is named there by apple,secure-mbox instead. Add apple_mbox_get_prop() for a mailbox named by another property, and apple_rtkit_init_mbox_prop() on top of it. Signed-off-by: Jens Axboe --- drivers/soc/apple/mailbox.c | 10 ++++++++-- drivers/soc/apple/rtkit.c | 24 ++++++++++++++++++------ include/linux/soc/apple/mailbox.h | 2 ++ include/linux/soc/apple/rtkit.h | 5 +++++ 4 files changed, 33 insertions(+), 8 deletions(-) diff --git a/drivers/soc/apple/mailbox.c b/drivers/soc/apple/mailbox.c index 5b5b69500db348..7973d07a825fdc 100644 --- a/drivers/soc/apple/mailbox.c +++ b/drivers/soc/apple/mailbox.c @@ -1339,14 +1339,14 @@ static void apple_mbox_quiesce(void *data) pm_runtime_barrier(mbox->dev); } -struct apple_mbox *apple_mbox_get(struct device *dev, int index) +struct apple_mbox *apple_mbox_get_prop(struct device *dev, const char *prop, int index) { struct of_phandle_args args; struct platform_device *pdev; struct apple_mbox *mbox; int ret; - ret = of_parse_phandle_with_args(dev->of_node, "mboxes", "#mbox-cells", + ret = of_parse_phandle_with_args(dev->of_node, prop, "#mbox-cells", index, &args); if (ret || !args.np) return ERR_PTR(ret); @@ -1373,6 +1373,12 @@ struct apple_mbox *apple_mbox_get(struct device *dev, int index) return mbox; } +EXPORT_SYMBOL(apple_mbox_get_prop); + +struct apple_mbox *apple_mbox_get(struct device *dev, int index) +{ + return apple_mbox_get_prop(dev, "mboxes", index); +} EXPORT_SYMBOL(apple_mbox_get); struct apple_mbox *apple_mbox_get_byname(struct device *dev, const char *name) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index d25c7e2f106f52..c869b05084eb8a 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2349,6 +2349,7 @@ static int apple_rtkit_inherit_endpoints( } static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, + const char *mbox_prop, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops, bool adopted, @@ -2414,7 +2415,9 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, set_bit(APPLE_RTKIT_EP_MGMT, rtk->endpoints); set_bit(APPLE_RTKIT_EP_MGMT, rtk->started); - if (mbox_name) + if (mbox_prop) + rtk->mbox = apple_mbox_get_prop(dev, mbox_prop, 0); + else if (mbox_name) rtk->mbox = apple_mbox_get_byname(dev, mbox_name); else rtk->mbox = apple_mbox_get(dev, mbox_idx); @@ -2468,16 +2471,25 @@ struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, false, NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init); +struct apple_rtkit *apple_rtkit_init_mbox_prop(struct device *dev, void *cookie, + const char *mbox_prop, + const struct apple_rtkit_ops *ops) +{ + return __apple_rtkit_init(dev, cookie, mbox_prop, NULL, 0, ops, false, + NULL, 0, false, NULL); +} +EXPORT_SYMBOL_GPL(apple_rtkit_init_mbox_prop); + struct apple_rtkit *apple_rtkit_init_adopted(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, NULL, 0, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted); @@ -2536,7 +2548,7 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_buffers( const struct apple_rtkit_ops *ops, const struct apple_rtkit_inherited_buffer *buffers, unsigned int count) { - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, buffers, count, false, NULL); } EXPORT_SYMBOL_GPL(apple_rtkit_init_adopted_with_buffers); @@ -2549,7 +2561,7 @@ struct apple_rtkit *apple_rtkit_init_adopted_with_session( if (!session) return ERR_PTR(-EINVAL); - return __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, true, + return __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, true, session->buffers, session->num_buffers, false, session); } @@ -3607,7 +3619,7 @@ struct apple_rtkit *devm_apple_rtkit_init_m5_saved(struct device *dev, void *coo struct apple_rtkit *rtk; int ret; - rtk = __apple_rtkit_init(dev, cookie, mbox_name, mbox_idx, ops, false, + rtk = __apple_rtkit_init(dev, cookie, NULL, mbox_name, mbox_idx, ops, false, NULL, 0, true, NULL); if (IS_ERR(rtk)) return rtk; diff --git a/include/linux/soc/apple/mailbox.h b/include/linux/soc/apple/mailbox.h index 0159bbc356cfa1..d543769a6d96a1 100644 --- a/include/linux/soc/apple/mailbox.h +++ b/include/linux/soc/apple/mailbox.h @@ -96,6 +96,8 @@ struct apple_mbox { }; struct apple_mbox *apple_mbox_get(struct device *dev, int index); +/* As apple_mbox_get(), for a mailbox named by a property other than mboxes */ +struct apple_mbox *apple_mbox_get_prop(struct device *dev, const char *prop, int index); struct apple_mbox *apple_mbox_get_byname(struct device *dev, const char *name); int apple_mbox_start(struct apple_mbox *mbox); diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 7017f1786373c6..04c126ed0213aa 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -164,6 +164,11 @@ struct apple_rtkit *apple_rtkit_init(struct device *dev, void *cookie, const char *mbox_name, int mbox_idx, const struct apple_rtkit_ops *ops); +/* As apple_rtkit_init(), with the mailbox named by @mbox_prop instead of mboxes. */ +struct apple_rtkit *apple_rtkit_init_mbox_prop(struct device *dev, void *cookie, + const char *mbox_prop, + const struct apple_rtkit_ops *ops); + /* * Initialize an instance for a co-processor that the bootloader left running * and that cannot be reset. No HELLO/EPMAP handshake takes place: the system From 170449e2c71441492f11adb04b604386b32f2de5 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:39:39 -0700 Subject: [PATCH 0989/1514] soc: apple: rtkit: a step between the AP idle and the IOP idle A coprocessor with a second (secure) mailbox port takes its IOP idle only after that port's AP idle, sent between the main mailbox's AP idle and its IOP idle. The display coprocessor of T6050 firmware 27.2 is one: without it the IOP idle is never acknowledged. - apple_rtkit_v27_set_after_ap(): a callback the atomic idle runs once the AP state is acknowledged, before the IOP request. An error from it fails the idle. - apple_rtkit_v27_port_ap_idle_atomic(): a port's AP idle, sent and awaited by polling, for that callback. - apple_rtkit_idle_strict_with(): the same step for the sleeping idle, failing it the same way. No caller yet. Signed-off-by: Jens Axboe --- drivers/soc/apple/rtkit-v27-late.inc | 58 +++++++++++++++++++++++++ drivers/soc/apple/rtkit.c | 14 +++++- include/linux/soc/apple/dcp-v27-sleep.h | 2 + include/linux/soc/apple/rtkit.h | 1 + 4 files changed, 74 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/rtkit-v27-late.inc b/drivers/soc/apple/rtkit-v27-late.inc index 6f3bfd84ab0a5f..2df50c9d4c394e 100644 --- a/drivers/soc/apple/rtkit-v27-late.inc +++ b/drivers/soc/apple/rtkit-v27-late.inc @@ -7,8 +7,23 @@ struct apple_rtkit_v27_scope { DECLARE_KFIFO(deferred, struct apple_mbox_msg, 64); bool held, stopped, failed; int error; + /* + * Run once between the AP state's acknowledgment and the IOP request, interrupts off. + * An error fails the idle. + */ + int (*after_ap)(void *data); + void *after_ap_data; }; +void apple_rtkit_v27_set_after_ap(struct apple_rtkit_v27_scope *s, int (*fn)(void *), void *data) +{ + if (s) { + s->after_ap = fn; + s->after_ap_data = data; + } +} +EXPORT_SYMBOL_GPL(apple_rtkit_v27_set_after_ap); + bool apple_rtkit_v27_live(struct apple_rtkit *rtk) { return !rtk->crashed && !rtk->shutting_down && @@ -118,6 +133,44 @@ int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *s) } EXPORT_SYMBOL_GPL(apple_rtkit_v27_check); +/* + * A second port's AP idle with interrupts off: sent, and its acknowledgment awaited by polling + * the port's mailbox, for at most @us. The port's tracked state is not updated. + */ +int apple_rtkit_v27_port_ap_idle_atomic(struct apple_rtkit *rtk, unsigned int us) +{ + struct apple_mbox_msg msg = { + .msg0 = FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, APPLE_RTKIT_MGMT_SET_AP_PWR_STATE) | + FIELD_PREP(APPLE_RTKIT_MGMT_PWR_STATE, APPLE_RTKIT_PWR_STATE_IDLE), + .msg1 = APPLE_RTKIT_EP_MGMT, + }; + unsigned int i, n = us / 10; + int ret = -ETIMEDOUT; + + for (i = 0; i < n; i++) { + ret = apple_mbox_send_nowait(rtk->mbox, msg); + if (ret != -EAGAIN && ret != -EBUSY) + break; + udelay(10); + } + if (ret) + return ret; + for (; i < n; i++) { + struct apple_mbox_msg in; + + ret = apple_mbox_recv_nowait(rtk->mbox, &in); + if (ret < 0 && ret != -EBUSY) + return ret; + if (ret > 0 && in.msg1 == APPLE_RTKIT_EP_MGMT && + FIELD_GET(APPLE_RTKIT_MGMT_TYPE, in.msg0) == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK) + return FIELD_GET(APPLE_RTKIT_MGMT_PWR_STATE, in.msg0) == + APPLE_RTKIT_PWR_STATE_IDLE ? 0 : -EPROTO; + udelay(10); + } + return -ETIMEDOUT; +} +EXPORT_SYMBOL_GPL(apple_rtkit_v27_port_ap_idle_atomic); + int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) { struct apple_rtkit *rtk; @@ -180,6 +233,11 @@ int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *s) type == APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK && arg == APPLE_RTKIT_PWR_STATE_IDLE) { ap_ack = true; + if (s->after_ap) { + ret = s->after_ap(s->after_ap_data); + if (ret) + goto poison; + } } else if (msg.msg1 == APPLE_RTKIT_EP_MGMT && iop_sent && !iop_ack && type == APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK && arg == APPLE_RTKIT_PWR_STATE_IDLE) { diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index c869b05084eb8a..88eb0141952aa3 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2935,6 +2935,16 @@ static int apple_rtkit_strict_idle_state(struct apple_rtkit *rtk, bool ap) } int apple_rtkit_idle_strict(struct apple_rtkit *rtk) +{ + return apple_rtkit_idle_strict_with(rtk, NULL, NULL); +} +EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict); + +/* + * As apple_rtkit_idle_strict(), with a step between the AP state's and the IOP state's. + * A failed step fails the idle: the IOP state is not sent. + */ +int apple_rtkit_idle_strict_with(struct apple_rtkit *rtk, int (*after_ap)(void *data), void *data) { int ret; @@ -2945,6 +2955,8 @@ int apple_rtkit_idle_strict(struct apple_rtkit *rtk) reinit_completion(&rtk->strict_idle_done); WRITE_ONCE(rtk->strict_idle_waiting, true); ret = apple_rtkit_strict_idle_state(rtk, true); + if (!ret && after_ap) + ret = after_ap(data); if (!ret) ret = apple_rtkit_strict_idle_state(rtk, false); if (!ret && !wait_for_completion_timeout(&rtk->strict_idle_done, @@ -2957,7 +2969,7 @@ int apple_rtkit_idle_strict(struct apple_rtkit *rtk) rtk->strict_idle_poisoned = true; return ret; } -EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict); +EXPORT_SYMBOL_GPL(apple_rtkit_idle_strict_with); int apple_rtkit_warm_restart_strict(struct apple_rtkit *rtk) { diff --git a/include/linux/soc/apple/dcp-v27-sleep.h b/include/linux/soc/apple/dcp-v27-sleep.h index 5e56c401419036..3484c04a98c2cc 100644 --- a/include/linux/soc/apple/dcp-v27-sleep.h +++ b/include/linux/soc/apple/dcp-v27-sleep.h @@ -39,6 +39,8 @@ int apple_rtkit_v27_arm(struct apple_rtkit *, struct apple_rtkit_v27_scope **); bool apple_rtkit_v27_live(struct apple_rtkit *); int apple_rtkit_v27_check(struct apple_rtkit_v27_scope *); int apple_rtkit_v27_idle_atomic(struct apple_rtkit_v27_scope *); +int apple_rtkit_v27_port_ap_idle_atomic(struct apple_rtkit *rtk, unsigned int us); +void apple_rtkit_v27_set_after_ap(struct apple_rtkit_v27_scope *s, int (*fn)(void *), void *data); int apple_rtkit_v27_disarm(struct apple_rtkit_v27_scope *, bool stopped); int apple_dart_v27_claim(struct device *provider, struct device *firmware, diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 04c126ed0213aa..c01b33522bd9f0 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -312,6 +312,7 @@ int apple_rtkit_idle(struct apple_rtkit *rtk); /* The mailbox's receive-enable bit (I2A_CONTROL bit 0): off once a slept firmware has answered its idle. */ void apple_rtkit_set_recv_enabled(struct apple_rtkit *rtk, bool enabled); int apple_rtkit_idle_strict(struct apple_rtkit *rtk); +int apple_rtkit_idle_strict_with(struct apple_rtkit *rtk, int (*after_ap)(void *data), void *data); int apple_rtkit_warm_restart_strict(struct apple_rtkit *rtk); int apple_rtkit_warm_restart_stopped(struct apple_rtkit *rtk); From 7421a1a79e07e53ce476722713a250beab4b5b30 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:39:40 -0700 Subject: [PATCH 0990/1514] drm/apple: V27 sleep: the DCP's secure port (firmware 27.2) On T6050 firmware 27.2 the internal display coprocessor has a secure mailbox port (ADT /arm-io/dcp-exclave-mailbox, iop,secure-rtbuddy-proxy), as on T8140. With it unanswered the firmware acknowledges the AP idle and never the IOP idle: the sleep's late stop fails, and so does the stop and restart in the wake. - The port may be named by apple,secure-mbox where mboxes must stay the one ASC mailbox: the boot loader refuses the display handoff otherwise. The driver takes the port's mailbox from that property. - A coprocessor with the port is no longer refused the V27 sleep. Its poller stops once the sleep is armed, and starts again when a sleep is disarmed without having stopped the firmware. - Late stop: the port's AP idle between the main mailbox's AP idle and its IOP idle, polled, interrupts off. Not acknowledged in 5 ms, it fails the stop. - Wake: the stop and restart cycle idles the port the same way and stops its poller, which otherwise reads the mailbox with the display's domain off (SError). The port is restarted before RUN and turned on after the boot. All of it follows the port's presence, not the board. Tested on a K116s: with this the IOP idle is acknowledged within 2 ms. Signed-off-by: Jens Axboe --- drivers/gpu/drm/apple/dcp-v27-sleep.inc | 91 +++++++++++++++++++++---- drivers/gpu/drm/apple/dcp.c | 27 ++++++-- 2 files changed, 100 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-v27-sleep.inc b/drivers/gpu/drm/apple/dcp-v27-sleep.inc index 027927a4ec055f..7b0bead4442a71 100644 --- a/drivers/gpu/drm/apple/dcp-v27-sleep.inc +++ b/drivers/gpu/drm/apple/dcp-v27-sleep.inc @@ -250,6 +250,41 @@ static int dcp_v27_ext_cycle_ready(struct apple_dcp *dcp) return dcp->s2r_dcp_dart ? 0 : -ENODEV; } +/* + * A restart with the secure port (firmware 27.2), as dcp_s2r_warm_restart() does it: the + * port restarted before RUN, mapped between the main mailbox's IOP report and its AP on, then on. + */ +static int dcp_v27_warm_restart(struct apple_dcp *dcp, bool strict) +{ + int ret; + + if (dcp->secure_rtk && dcp->secure_answered) { + dcp_secure_poll_stop(dcp); + ret = apple_rtkit_port_restart(dcp->secure_rtk); + if (ret) + dev_warn(dcp->dev, "V27 wake: secure port restart: %d\n", ret); + } + return strict ? apple_rtkit_warm_restart_strict(dcp->rtk) : + apple_rtkit_warm_restart_stopped(dcp->rtk); +} + +static int dcp_v27_boot(struct apple_dcp *dcp) +{ + bool secure = dcp->secure_rtk && dcp->secure_answered; + int ret; + + ret = apple_rtkit_boot_with(dcp->rtk, secure ? dcp_secure_port_map : NULL, dcp); + if (ret || !secure) + return ret; + ret = dcp->secure_map_ret ?: apple_rtkit_port_on(dcp->secure_rtk, DCP_SECURE_TIMEOUT_MS); + if (ret) + dev_warn(dcp->dev, "V27 wake: secure port map %d (%lld us), on %d\n", + dcp->secure_map_ret, dcp->secure_map_us, ret); + else + dcp_secure_poll_start(dcp); + return 0; +} + /* * macOS's DCP stop/restart between its wake steps: sessions closed, AP and IOP * idle, IDLE_DONE, receive off, CPU_CONTROL RUN off; dart-dcp stopped, the display's domain off and, @@ -273,7 +308,11 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) if (s && s->cycle_failed) return -ECANCELED; dcp_v27_sessions(dcp, false); - ret = apple_rtkit_idle_strict(dcp->rtk); + /* With a secure port: the IOP idle is taken only after the port's AP idle */ + if (dcp->secure_rtk && dcp->secure_answered) + ret = apple_rtkit_idle_strict_with(dcp->rtk, dcp_secure_port_idle_strict, dcp); + else + ret = apple_rtkit_idle_strict(dcp->rtk); if (ret) { dev_warn(dcp->dev, "V27 wake: RTKit cycle: idle %d\n", ret); dcp_v27_sessions(dcp, true); @@ -349,12 +388,12 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) dev_warn(dcp->dev, "V27 wake: RTKit cycle: display DART rewrite %d\n", ret); } } - ret = apple_rtkit_warm_restart_strict(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, true); if (!ret) { writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); run_status = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); } /* * An external processor that did not start is not left down: its DART, power words and @@ -373,13 +412,13 @@ static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms) ret = apple_dart_m5_display_cycle(dcp->s2r_dcp_dart, true); } if (!ret) - ret = apple_rtkit_warm_restart_stopped(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, false); if (!ret) { writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); run_status = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); } } if (ret) { @@ -1258,6 +1297,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) return 0; } +static int dcp_v27_secure_idle_atomic(void *data); + static int dcp_v27_late_arm(void *data) { struct dcp_v27_sleep *s = data; @@ -1287,6 +1328,8 @@ static int dcp_v27_late_arm(void *data) ret = apple_rtkit_v27_arm(dcp->rtk, &s->rx); if (ret) dev_info(dcp->dev, "V27 arm: RTKit %d\n", ret); + else + apple_rtkit_v27_set_after_ap(s->rx, dcp_v27_secure_idle_atomic, dcp); } if (ret) { if (s->display && !s->display_early) { @@ -1301,10 +1344,31 @@ static int dcp_v27_late_arm(void *data) s->firmware = NULL; return ret; } + /* + * The secure port is idled from the late stop, with nothing else reading it. Stopped + * only here, once the sleep is armed: a refused or cancelled sleep before this leaves + * the poller running, and a disarm without a stop starts it again. + */ + if (dcp->secure_rtk && dcp->secure_answered) + dcp_secure_poll_stop(dcp); s->phase = V27_ARMED; return 0; } +/* + * With a secure port (firmware 27.2): its AP idle between the main mailbox's AP idle and + * its IOP idle, polled, as this runs with interrupts off. Not acknowledged, it fails the stop: + * the firmware would not take the IOP idle. + */ +static int dcp_v27_secure_idle_atomic(void *data) +{ + struct apple_dcp *dcp = data; + + if (!dcp->secure_rtk || !dcp->secure_answered) + return 0; + return apple_rtkit_v27_port_ap_idle_atomic(dcp->secure_rtk, 5000); +} + static int dcp_v27_late_check(void *data) { struct dcp_v27_sleep *s = data; @@ -1376,8 +1440,12 @@ static int dcp_v27_late_disarm(void *data, bool stopped) if (ret) return dcp_v27_fail(s, ret); s->rx = NULL; - if (!stopped) + if (!stopped) { s->phase = V27_PREPARED; + /* The firmware never stopped: the port is read again. A wake's boot does it otherwise. */ + if (s->dcp->secure_rtk && s->dcp->secure_answered) + dcp_secure_poll_start(s->dcp); + } return 0; } @@ -1439,9 +1507,8 @@ static int dcp_v27_sleep_prepare(struct apple_dcp *dcp) dev_warn(dcp->dev, "V27 sleep: no sleep RPC arguments in the DT\n"); return -EOPNOTSUPP; } - if (!dcp->retain_dma || IS_ERR_OR_NULL(dcp->rtk) || !dcp->active || dcp->crashed || dcp->quiescing || - dcp->secure_rtk) - return dcp_v27_refuse(dcp, "coprocessor not live (dma, rtkit, active, crashed, quiescing, secure)"); + if (!dcp->retain_dma || IS_ERR_OR_NULL(dcp->rtk) || !dcp->active || dcp->crashed || dcp->quiescing) + return dcp_v27_refuse(dcp, "coprocessor not live (dma, rtkit, active, crashed, quiescing)"); /* Mode-config suspend is the actual DRM scanout-owner boundary. No HPD * shortcut: external firmware still executes A484/A500/AFK and late IDLE. */ @@ -1694,7 +1761,7 @@ static int dcp_v27_sleep_restart(struct apple_dcp *dcp) if (s->phase == V27_STOPPED) { ret = apple_sleep_display_v27_power_ready(dcp->dev); if (!ret) - ret = apple_rtkit_warm_restart_strict(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, true); /* * The final step stopped this CPU and it is still stopped: the firmware boots * from its reset vector next, so the state tracked before the stop does not @@ -1703,12 +1770,12 @@ static int dcp_v27_sleep_restart(struct apple_dcp *dcp) if (ret == -EUCLEAN && READ_ONCE(dcp->s2r_fw_down) && !(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & APPLE_DCP_COPROC_CPU_CONTROL_RUN)) - ret = apple_rtkit_warm_restart_stopped(dcp->rtk); + ret = dcp_v27_warm_restart(dcp, false); if (ret) return dcp_v27_fail(s, ret); writel(readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) | APPLE_DCP_COPROC_CPU_CONTROL_RUN, dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); - ret = apple_rtkit_boot(dcp->rtk); + ret = dcp_v27_boot(dcp); if (ret) return dcp_v27_fail(s, ret); } diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 00e0835b6576cd..6a657114b70eca 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -257,18 +257,24 @@ static void dcp_secure_port_start(struct apple_dcp *dcp) } /* Between the main mailbox's AP idle and its IOP idle. */ -static void dcp_secure_port_idle(void *data) +static int dcp_secure_port_idle_strict(void *data) { struct apple_dcp *dcp = data; int ret; if (!dcp->secure_rtk || !dcp->secure_answered) - return; + return 0; dcp_secure_poll_stop(dcp); ret = apple_rtkit_port_idle(dcp->secure_rtk, DCP_SECURE_TIMEOUT_MS); if (ret) dev_warn(dcp->dev, "secure port AP idle not acknowledged: %d\n", ret); + return ret; +} + +static void dcp_secure_port_idle(void *data) +{ + dcp_secure_port_idle_strict(data); } static void dcp_release_secure_rtkit(void *data) @@ -285,10 +291,18 @@ static int dcp_secure_port_init(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - if (of_property_match_string(dev->of_node, "mbox-names", "secure") < 0) + /* + * The secure mailbox is the second of mboxes, or named by apple,secure-mbox where the + * boot loader wants mboxes to hold the one ASC mailbox (it refuses the display handoff + * otherwise). + */ + if (of_property_match_string(dev->of_node, "mbox-names", "secure") >= 0) + dcp->secure_rtk = apple_rtkit_init(dev, dcp, "secure", 0, &dcp_secure_rtkit_ops); + else if (of_property_present(dev->of_node, "apple,secure-mbox")) + dcp->secure_rtk = apple_rtkit_init_mbox_prop(dev, dcp, "apple,secure-mbox", + &dcp_secure_rtkit_ops); + else return 0; - - dcp->secure_rtk = apple_rtkit_init(dev, dcp, "secure", 0, &dcp_secure_rtkit_ops); if (IS_ERR(dcp->secure_rtk)) { int ret = PTR_ERR(dcp->secure_rtk); @@ -314,7 +328,8 @@ static void dcp_s2r_check_dt(struct apple_dcp *dcp) struct device_node *np = dcp->dev->of_node; bool power = of_property_present(np, "apple,display-power"); bool secure = dcp->hw.s2r_no_secure_port || - of_property_match_string(np, "mbox-names", "secure") >= 0; + of_property_match_string(np, "mbox-names", "secure") >= 0 || + of_property_present(np, "apple,secure-mbox"); if (dcp->hw.s2r && (!power || !secure)) { dev_info(dcp->dev, "no %s in the device tree, the firmware keeps running\n", From 143d1f3a964d6a710c57ae1ce392d09edff7c29f Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:39:40 -0700 Subject: [PATCH 0991/1514] drm/apple: V27 sleep: wait out a busy endpoint before closing it An endpoint that is still taking a message answers -EBUSY to the close for a moment, and the sleep was refused; undoing it then crashed the internal DCP. Seen on endpoint 0x31 of a K116s DCPEXT, where a service is announced late ("close-31 -16"), more often with a verbose console. Poll afk_v27_sleep_check() for up to 300 ms first, as the other steps do. Signed-off-by: Jens Axboe --- drivers/gpu/drm/apple/dcp-v27-sleep.inc | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp-v27-sleep.inc b/drivers/gpu/drm/apple/dcp-v27-sleep.inc index 7b0bead4442a71..48783b544afb92 100644 --- a/drivers/gpu/drm/apple/dcp-v27-sleep.inc +++ b/drivers/gpu/drm/apple/dcp-v27-sleep.inc @@ -1673,7 +1673,18 @@ static int dcp_v27_sleep_prepare(struct apple_dcp *dcp) if (ret) goto uncertain; for (i = ARRAY_SIZE(v27_sleep_endpoints); i-- > 0;) { - ret = afk_v27_sleep_control(dcp->sleep_v27_ep[v27_sleep_endpoints[i] - 0x20], false); + struct apple_dcp_afkep *ep = dcp->sleep_v27_ep[v27_sleep_endpoints[i] - 0x20]; + int check; + + /* + * An endpoint still taking a message (a service announced late, seen on 0x31 of + * a K116s DCPEXT) answers -EBUSY for a moment: wait it out as the other steps do, + * rather than refuse the sleep. + */ + if (ep) + read_poll_timeout(afk_v27_sleep_check, check, check != -EBUSY, 1000, + 300 * USEC_PER_MSEC, false, ep); + ret = afk_v27_sleep_control(ep, false); if (ret) { char name[12]; From d7a03887c98b2e9e65e2dea0ba0baf0fe79efd51 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:39:40 -0700 Subject: [PATCH 0992/1514] drm/apple: V27 wake: mode set once the firmware has reported the panel After a V27 sleep the first mode set of the internal panel is kept, not sent: on the J714s (27.0) the firmware brings link and mode back once frames arrive. That mode set also comes before the firmware has announced the panel's video interface again. On firmware 27.2 it now waits for two events of the wake and is then sent: the open of the panel's video interface (up to 1.5 s) and the firmware's hotplug report that follows it (up to 250 ms). A wait that runs out is logged. Both waits are set up before the calls that power the panel on, since the events come from workers. On the K116s the firmware answers that the mode is already set and the link up. 27.0 keeps the mode as before. Whether 27.2 needs the mode set has not been tested separately. Signed-off-by: Jens Axboe --- drivers/gpu/drm/apple/dcp-internal.h | 4 ++++ drivers/gpu/drm/apple/dcp-v27-sleep.inc | 11 +++++++++++ drivers/gpu/drm/apple/dcp.c | 2 ++ drivers/gpu/drm/apple/epic/panelavep.c | 4 +++- drivers/gpu/drm/apple/iomfb_template.c | 15 +++++++++++++++ drivers/gpu/drm/apple/iomfb_v27.c | 3 +++ 6 files changed, 38 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 116d0119d12665..523487fe731f14 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1020,6 +1020,10 @@ struct apple_dcp { /* V27 sleep: the panel's next mode set is the mode it already has */ bool v27_keep_mode; + /* Since the V27 wake: the panel's video interface opened, firmware reported the panel */ + struct completion v27_wake_video, v27_wake_hotplug; +#define V27_WAKE_VIDEO_MS 1500 +#define V27_WAKE_HOTPLUG_MS 250 /* V27 sleep: the output area of the call being pushed holds this (an in/out word) */ const void *push_out_prefill; diff --git a/drivers/gpu/drm/apple/dcp-v27-sleep.inc b/drivers/gpu/drm/apple/dcp-v27-sleep.inc index 48783b544afb92..835b45917b3331 100644 --- a/drivers/gpu/drm/apple/dcp-v27-sleep.inc +++ b/drivers/gpu/drm/apple/dcp-v27-sleep.inc @@ -69,6 +69,13 @@ static void dcp_v27_sessions(struct apple_dcp *dcp, bool open); static bool dcp_v27_external(struct apple_dcp *dcp); static int dcp_v27_rtkit_cycle(struct apple_dcp *dcp, unsigned int pause_ms); +/* The wake's mode set waits for these two reports: none from before the power-on counts. */ +static void dcp_v27_wake_expect(struct apple_dcp *dcp) +{ + reinit_completion(&dcp->v27_wake_video); + reinit_completion(&dcp->v27_wake_hotplug); +} + /* * The calls made before A484's plain form in either direction, at the wake and at the display's * sleep: A414, A489, A489, A487, A489, A412. At the wake each is followed by A500's wake form, at @@ -1216,6 +1223,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) dcp_v27_rtkit_cycle(dcp, 0); if (s->soft_off && v27_a115) iomfb_v27_sleep_call(dcp, "A489", NULL, 0, 4); + /* Before the call that brings the panel up: its reports come from workers. */ + dcp_v27_wake_expect(dcp); ret = iomfb_v27_sleep_rpc(dcp, false, true); if (ret) return ret; @@ -1247,6 +1256,8 @@ static int dcp_v27_reopen_live(struct apple_dcp *dcp) dcp_v27_display_stage(dcp, per_call, per_call && v27_session_rounds, per_call); if (v27_session_rounds) dcp_v27_sessions(dcp, true); + /* Again, in the session the display comes on in. */ + dcp_v27_wake_expect(dcp); ret = iomfb_v27_sleep_plain(dcp, true); if (ret) return ret; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 6a657114b70eca..1c7464a54f80fd 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7467,6 +7467,8 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_LIST_HEAD(&dcp->swapped_out_fbs); mutex_init(&dcp->swapped_out_fbs_lock); + init_completion(&dcp->v27_wake_video); + init_completion(&dcp->v27_wake_hotplug); ret = dcp_backlight_init(dcp, dev); if (ret) return ret; diff --git a/drivers/gpu/drm/apple/epic/panelavep.c b/drivers/gpu/drm/apple/epic/panelavep.c index cd4507b2bf78fa..6e7a0cb682bcf4 100644 --- a/drivers/gpu/drm/apple/epic/panelavep.c +++ b/drivers/gpu/drm/apple/epic/panelavep.c @@ -131,9 +131,11 @@ static void panelav_open_worker(struct work_struct *work) if (ret) dev_warn(service->ep->dcp->dev, "panel AV: video interface %u OPEN failed: %d\n", service->channel, ret); - else + else { + complete(&service->ep->dcp->v27_wake_video); dev_info(service->ep->dcp->dev, "panel AV: video interface %u opened\n", service->channel); + } afk_service_put(service); kfree(w); } diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 78f3a29b9b405b..3a4b2291bb6a35 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4283,6 +4283,21 @@ int DCP_FW_NAME(iomfb_modeset)(struct apple_dcp *dcp, keep_mode = dcp->v27_j714s && xchg(&dcp->v27_keep_mode, false) && dcp->mode.color_mode_id == mode->color_mode_id && dcp->mode.timing_mode_id == mode->timing_mode_id; + /* + * Firmware 27.2: sent once the panel's video interface is open again and the firmware + * has reported the panel, which it does after the open. + */ + if (keep_mode && iomfb_v27_methods_renumbered(dcp->v27_methods)) { + if (!wait_for_completion_timeout(&dcp->v27_wake_video, + msecs_to_jiffies(V27_WAKE_VIDEO_MS))) + dev_warn(dcp->dev, "V27 wake: panel video interface not open after %u ms\n", + V27_WAKE_VIDEO_MS); + else if (!wait_for_completion_timeout(&dcp->v27_wake_hotplug, + msecs_to_jiffies(V27_WAKE_HOTPLUG_MS))) + dev_warn(dcp->dev, "V27 wake: no hotplug report %u ms after the panel's open\n", + V27_WAKE_HOTPLUG_MS); + keep_mode = false; + } #endif scoped_guard(spinlock_irqsave, &dcp->hdr.lock) { dcp->mode = (struct dcp_set_digital_out_mode_req){ diff --git a/drivers/gpu/drm/apple/iomfb_v27.c b/drivers/gpu/drm/apple/iomfb_v27.c index def54604d8c302..1f2e8121127c77 100644 --- a/drivers/gpu/drm/apple/iomfb_v27.c +++ b/drivers/gpu/drm/apple/iomfb_v27.c @@ -513,6 +513,9 @@ static bool trampoline_hotplug_h17p(struct apple_dcp *dcp, int tag, if (!(request->tiled_display_null & 1)) memcpy(out, request->tiled_display, sizeof(request->tiled_display)); + /* The V27 wake's mode set waits for the firmware's report of the panel */ + if (request->connected && dcp->v27_j714s) + complete(&dcp->v27_wake_hotplug); return trampoline_hotplug(dcp, tag, out, in); } From 2d9df0f1e607004932d8d2aa5595b23a9b2b6f5f Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:39:40 -0700 Subject: [PATCH 0993/1514] soc: apple: rtkit: serve an endpoint's first buffer under the ANS hold The T6050 ANS wake holds the buffers: a request under the hold fails the wake with -EBUSY and the driver then holds all I/O. ANS on firmware 27.0 asks for none. On 27.2 it asks for its syslog buffer (endpoint 2, 0x4000 bytes) about 2.4 s into the wake, having none yet. A first buffer for an endpoint replaces nothing the hold protects: serve it. A request for an endpoint that has a buffer is refused as before. With it ANS comes back and the controller is rebuilt after a deep sleep on a K116s (27.2). Signed-off-by: Jens Axboe --- drivers/soc/apple/rtkit.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 88eb0141952aa3..1276833aecc3ad 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -558,11 +558,9 @@ static void apple_rtkit_management_rx(struct apple_rtkit *rtk, u64 msg) } } -static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, - struct apple_rtkit_shmem *buffer) +static int apple_rtkit_alloc_first_shmem(struct apple_rtkit *rtk, u8 ep, + struct apple_rtkit_shmem *buffer) { - if (READ_ONCE(rtk->ans_hold)) - return apple_rtkit_ans_fail(rtk, -EBUSY); /* The crash log's buffer is asked for only at a crash: serve it after a strict restart too. */ if (READ_ONCE(rtk->strict_retained_buffers) && ep != APPLE_RTKIT_EP_CRASHLOG) return -EPROTO; @@ -577,6 +575,14 @@ static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, return buffer->buffer ? 0 : -ENOMEM; } +static int apple_rtkit_alloc_shmem(struct apple_rtkit *rtk, u8 ep, + struct apple_rtkit_shmem *buffer) +{ + if (READ_ONCE(rtk->ans_hold)) + return apple_rtkit_ans_fail(rtk, -EBUSY); + return apple_rtkit_alloc_first_shmem(rtk, ep, buffer); +} + static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, struct apple_rtkit_shmem *buffer, u8 ep, u64 msg) @@ -650,7 +656,8 @@ static int apple_rtkit_common_rx_get_buffer(struct apple_rtkit *rtk, goto error; } - err = apple_rtkit_alloc_shmem(rtk, ep, &request); + /* The endpoint has no buffer yet: a first one replaces nothing the ANS hold protects */ + err = apple_rtkit_alloc_first_shmem(rtk, ep, &request); if (err) goto error; *buffer = request; From ec721590b80405b0109945de351a329752d255e1 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:27:07 -0700 Subject: [PATCH 0994/1514] soc: apple: sleep: tell whether a T6050 machine describes the sleep The drivers that take part in T6050's firmware-driven sleep each name the boards it has run on. Whether a board sleeps that way is in its device tree: it has an enabled apple,t6050-sleep node or it does not. Add apple_t6050_sleep_described() for that. What differs from one description to another is a property of the node, read with apple_t6050_sleep_property(). Signed-off-by: Jens Axboe --- include/linux/soc/apple/sleep.h | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index db4337d663b818..09ec51cbf80507 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -9,10 +9,33 @@ #include #include #include +#include #include struct device; -struct device_node; + +/* + * A T6050 machine whose device tree describes the firmware-driven sleep. What a + * driver does for that sleep follows the description, not a list of boards. + * With @prop: the description also has that property. + */ +static inline bool apple_t6050_sleep_property(const char *prop) +{ + struct device_node *np; + bool ret; + + if (!of_machine_is_compatible("apple,t6050")) + return false; + np = of_find_compatible_node(NULL, NULL, "apple,t6050-sleep"); + ret = np && of_device_is_available(np) && (!prop || of_property_read_bool(np, prop)); + of_node_put(np); + return ret; +} + +static inline bool apple_t6050_sleep_described(void) +{ + return apple_t6050_sleep_property(NULL); +} /* The SMC's sleep messages: the pmVC value and the spacings between them, used as floors */ struct apple_sleep_smc_policy { From c048e783897c41f52be12a6c0d7351594bb2f5a7 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 08:12:11 -0700 Subject: [PATCH 0995/1514] dt-bindings: soc: apple,t6050-sleep: add apple,display-method-sleep The drivers tell one T6050 sleep description from another by the board or by the node's compatible. What differs for the display coprocessors is how they take the sleep: through their firmware 27 method table, with the panel's AV and DP services, or through the sleep's endpoint transport alone. Say so in the description. Signed-off-by: Jens Axboe --- .../devicetree/bindings/soc/apple/apple,t6050-sleep.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml index c32148802bd18b..7d26c0049f8ac0 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml @@ -144,6 +144,14 @@ properties: The GFX die's wake sources left enabled for a sleep. From the ADT, set by the bootloader. + apple,display-method-sleep: + type: boolean + description: | + The display coprocessors take the sleep through their firmware 27 method + table: its sleep call and its swap, the panel's AV and DP services and the + external processors' handling around a sleep. Without it they keep the + method table they had and take the sleep's endpoint transport alone. + apple,clk-gating-boot: $ref: /schemas/types.yaml#/definitions/uint32-matrix items: From b777c1c56ccc14bdfac03bf4d2b159a49ae701cd Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 08:12:11 -0700 Subject: [PATCH 0996/1514] dt-bindings: mfd: apple,smc: add the wake reasons' numbering The bits of the SMC's wake record are numbered per board: the ADT's smc-pmu node gives each a name (event_name-bitN). Let the device tree carry the bits and their names. Signed-off-by: Jens Axboe --- .../devicetree/bindings/mfd/apple,smc.yaml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Documentation/devicetree/bindings/mfd/apple,smc.yaml b/Documentation/devicetree/bindings/mfd/apple,smc.yaml index c35e7d0e10faa6..34416179acfa0b 100644 --- a/Documentation/devicetree/bindings/mfd/apple,smc.yaml +++ b/Documentation/devicetree/bindings/mfd/apple,smc.yaml @@ -68,6 +68,22 @@ properties: hwmon: $ref: /schemas/hwmon/apple,smc-hwmon.yaml + apple,wake-reasons: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 64 + items: + maximum: 63 + description: | + The bits of the SMC's wake record that have a name on this board, as the + ADT's smc-pmu node numbers them (event_name-bitN). + + apple,wake-reason-names: + $ref: /schemas/types.yaml#/definitions/string-array + minItems: 1 + maxItems: 64 + description: The names of the bits in apple,wake-reasons, in the same order. + additionalProperties: false required: From 7ef2687fa38236d1e8b9d7634fe7587765569b91 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 08:12:12 -0700 Subject: [PATCH 0997/1514] arm64: dts: apple: t6050-j714s: the display's sleep method and the SMC's wake reasons Both were tied to the board's name in the drivers: the display coprocessors' sleep through their firmware 27 method table, and the numbering of the SMC's wake record. Describe them, the latter as the J714s ADT's smc-pmu node has it. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-j714s.dts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index 18b7c700c8469d..b36ebf840260ee 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -792,6 +792,19 @@ #include "t6050-j714s-sleep-soc.dtsi" #include "t6050-j714s-sleep-adt.dtsi" +/* The display coprocessors take the sleep through their firmware 27 method table */ +&sleep { + apple,display-method-sleep; +}; + +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 13 35 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "sdconn", "charger", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + /* * Sound through the AOP, as on J813: its audio service runs the serializers, the * CS42L84 headphone jack on admac-base-ns TX2/RX2 and the six SN012776 speaker amps From 702d2f15178876977fbd38473ebb7e8e39f7aeff Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:27:21 -0700 Subject: [PATCH 0998/1514] soc: apple: sleep: check a profile's CPU inventory, not its board's name A profile that names a machine is refused at probe on any other board, whatever its CPUs. The node's compatible already chose the profile, and what the entry depends on is the inventory: the boot CPU's MPIDR and the CPU count. Check those alone. The K116s (16-inch M5 Pro) binds apple,t6050-sleep with the J714s's 18-core layout and sleeps with that profile. Signed-off-by: Jens Axboe --- drivers/soc/apple/sleep.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9cee856626f918..4a71b157fcc30a 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -1916,10 +1916,10 @@ static int apple_sleep_validate_cpu_topology(struct apple_sleep *s) soc->cpu_cores_per_cluster > 32) return dev_err_probe(s->dev, -EINVAL, "invalid CPU-start geometry\n"); - if (soc->machine && (!of_machine_is_compatible(soc->machine) || - cpu_logical_map(0) != soc->boot_mpidr || - num_possible_cpus() != soc->cpu_count)) - return dev_err_probe(s->dev, -EINVAL, "unsupported board/CPU inventory\n"); + /* The node's compatible chose the profile: its machine is where it was measured */ + if (soc->machine && (cpu_logical_map(0) != soc->boot_mpidr || + num_possible_cpus() != soc->cpu_count)) + return dev_err_probe(s->dev, -EINVAL, "unsupported CPU inventory\n"); index = of_property_match_string(np, "reg-names", "cpu-start"); if (index < 0) From b3337cac2dcb4c378c2e4206c3f61a80eda89b2a Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:27:46 -0700 Subject: [PATCH 0999/1514] irqchip/apple-aic: keep the T6050 controller where the sleep is described The save and restore for T6050's deep sleep are set up on a list of boards. Set them up wherever the device tree describes that sleep. Signed-off-by: Jens Axboe --- drivers/irqchip/irq-apple-aic.c | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 52a892164c3a46..769e4105d9ac36 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -278,8 +279,8 @@ struct aic_info { bool vm_timer_fiq_readonly; /* A firmware-driven suspend powers the controller down: aic_syscore_ops keep it. */ bool fw_suspend; - /* If set, fw_suspend holds on these boards only */ - const char *const *fw_suspend_boards; + /* If set, fw_suspend holds only where this says the sleep is described */ + bool (*fw_suspend_described)(void); }; static const struct aic_info aic1_info __initconst = { @@ -328,12 +329,9 @@ static const struct aic_info aic3_info __initconst = { /* * The M5 Pro's sleep: the last steps mask every interrupt and acknowledge events by hand. The - * save and restore are set up on the boards with a T6050 sleep, the J714s and the J716c; + * save and restore are set up on the boards whose device tree describes a T6050 sleep; * another T6050 board is as one without them. */ -static const char *const aic3_t6050_sleep_boards[] __initconst = { - "apple,j714s", "apple,j716c", NULL -}; static const struct aic_info aic3_t6050_info __initconst = { .version = 3, @@ -341,7 +339,7 @@ static const struct aic_info aic3_t6050_info __initconst = { .fast_ipi = true, .local_fast_ipi = true, .fw_suspend = true, - .fw_suspend_boards = aic3_t6050_sleep_boards, + .fw_suspend_described = apple_t6050_sleep_described, }; static const struct aic_info aic3_t8140_info __initconst = { @@ -1298,8 +1296,7 @@ static struct syscore aic_syscore = { static void __init aic_sleep_init(struct aic_irq_chip *irqc) { if (!irqc->info.fw_suspend || - (irqc->info.fw_suspend_boards && - !of_machine_compatible_match(irqc->info.fw_suspend_boards))) + (irqc->info.fw_suspend_described && !irqc->info.fw_suspend_described())) return; aic_sleep.irq_cfg = kcalloc(irqc->nr_die * irqc->nr_irq, sizeof(u32), GFP_KERNEL); From 36692dbd26ab00a1dc79373c0a3ec93047cdc8d4 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1000/1514] mfd: macsmc: the T6050 saved-context path where the sleep is described The saved-context lane is for T6050's deep sleep and was enabled on the boards named here. Enable it wherever the device tree describes that sleep. The J714s's numbering of the wake record was a table picked by the board's name. It is the ADT's smc-pmu numbering: read it from the SMC's node (apple,wake-reasons, apple,wake-reason-names). Without them the SoC's table is used as before, and the J714s's built-in one on a J714s. The J714s's port and radio dark wake rule was keyed on that table's address. Give it a flag of its own, so the rule holds with either table. Signed-off-by: Jens Axboe --- drivers/mfd/macsmc-test.c | 7 +++++-- drivers/mfd/macsmc.c | 42 +++++++++++++++++++++++++++++++------- include/linux/mfd/macsmc.h | 1 + 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/drivers/mfd/macsmc-test.c b/drivers/mfd/macsmc-test.c index 2dec0920f982dc..fc07a3eb617199 100644 --- a/drivers/mfd/macsmc-test.c +++ b/drivers/mfd/macsmc-test.c @@ -352,6 +352,9 @@ static void macsmc_lid_wake_test(struct kunit *test) static void macsmc_wake_reason_test(struct kunit *test) { + static const struct apple_smc_wake_reason j714s[] = { + { 8, "lid" }, { 9, "sdconn" }, { 13, "wifibt" }, { } + }; struct macsmc_test_context *ctx = test->priv; char names[128]; @@ -371,8 +374,8 @@ static void macsmc_wake_reason_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_smc_wake_reason_bit(&ctx->smc, "lid"), 8); KUNIT_EXPECT_EQ(test, apple_smc_wake_reason_bit(&ctx->smc, "ipd_touch"), -1); - /* The J714s's: T8132's lid and radio bits, its SD reader at bit 9. */ - ctx->smc.wake_reasons = apple_smc_j714s_wake_reasons; + /* A device tree's own, here the J714s's: its SD reader at bit 9. */ + ctx->smc.wake_reasons = j714s; apple_smc_wake_reason_names(&ctx->smc, BIT_ULL(8) | BIT_ULL(9) | BIT_ULL(10) | BIT_ULL(13), names, sizeof(names)); KUNIT_EXPECT_STREQ(test, names, "lid sdconn wifibt"); diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index cb32577a3bf66a..75c7ed03a72b14 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -635,9 +635,34 @@ static const struct apple_smc_wake_reason apple_smc_j714s_wake_reasons[] = { { 43, "USB2_plug" }, { 44, "USB2_wake" }, { 45, "aupo" }, { 48, "rtc" }, { } }; +/* A board's own numbering, from its device tree (apple,wake-reasons and their names) */ +static const struct apple_smc_wake_reason *apple_smc_dt_wake_reasons(struct device *dev) +{ + struct device_node *np = dev->of_node; + struct apple_smc_wake_reason *r; + int i, n; + + n = of_property_count_u32_elems(np, "apple,wake-reasons"); + if (n <= 0 || n != of_property_count_strings(np, "apple,wake-reason-names")) + return NULL; + r = devm_kcalloc(dev, n + 1, sizeof(*r), GFP_KERNEL); + if (!r) + return NULL; + for (i = 0; i < n; i++) { + u32 bit; + + if (of_property_read_u32_index(np, "apple,wake-reasons", i, &bit) || bit > 63 || + of_property_read_string_index(np, "apple,wake-reason-names", i, &r[i].name)) + return NULL; + r[i].bit = bit; + } + return r; +} + static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; + const struct apple_smc_wake_reason *dt_reasons; struct apple_smc *smc; __be32 count = 0; bool t6050; @@ -646,17 +671,20 @@ static int apple_smc_probe(struct platform_device *pdev) smc = devm_kzalloc(dev, sizeof(*smc), GFP_KERNEL); if (!smc) return -ENOMEM; - smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? - apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; + dt_reasons = apple_smc_dt_wake_reasons(dev); + smc->wake_reasons = dt_reasons; + if (!smc->wake_reasons) + smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? + apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; mutex_init(&smc->mutex); spin_lock_init(&smc->lock); smc->dev = &pdev->dev; - smc->saved_enabled = of_machine_is_compatible("apple,t6050") && - (of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c")) && + smc->saved_enabled = apple_t6050_sleep_described() && of_device_is_compatible(dev->of_node, "apple,t6050-smc"); - if (smc->saved_enabled && of_machine_is_compatible("apple,j714s")) + smc->port_dark_wake = smc->saved_enabled && of_machine_is_compatible("apple,j714s"); + /* A J714s device tree from before apple,wake-reasons */ + if (smc->port_dark_wake && !dt_reasons) smc->wake_reasons = apple_smc_j714s_wake_reasons; /* J813's late notice needs the bounded, IRQ-independent transport too. */ if (of_machine_is_compatible("apple,j813")) @@ -1042,7 +1070,7 @@ static void apple_smc_dark_wake(struct apple_smc *smc) s64 asleep_ms; /* The J714s's rule alone: other boards with a sleep policy keep these wakes full. */ - if (smc->wake_reasons != apple_smc_j714s_wake_reasons) + if (!smc->port_dark_wake) return; /* Already dark (a port's wake with the lid closed): counted, so the re-entry waits as after ours. */ if (pm_dark_wake()) { diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 0bfd2079d0b969..14833b8fd1cefd 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -131,6 +131,7 @@ struct apple_smc { * resolve only the matching pending ID; timeout never cancels SRAM use. */ bool saved_enabled, saved_blocked, saved_scope, saved_committed; + bool port_dark_wake; bool saved_pending, saved_recovery, saved_wake; int saved_fault, saved_notice_error, saved_restore_error; /* From 7fc2cf79010791cd1850dea2833093b0e880283e Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1001/1514] soc: apple: rtkit: acknowledge the v2 PMP's CoreAnalytics events on any board The empty CoreAnalytics event on the PMP's endpoint 7 is acknowledged on the J714s only. It is the firmware's doing, not the board's: a K116s's PMP sends it too, on the same endpoint. Acknowledge it for every registry-v2 PMP. Signed-off-by: Jens Axboe --- drivers/soc/apple/rtkit.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index 1276833aecc3ad..0a329cf6cffc92 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -2408,8 +2408,7 @@ static struct apple_rtkit *__apple_rtkit_init(struct device *dev, void *cookie, goto free_rtk; rtk->pmp_registry_v2 = of_device_is_compatible(dev->of_node, "apple,t6050-pmp-v2"); - rtk->pmp_ca_event_ack = rtk->pmp_registry_v2 && - of_machine_is_compatible("apple,j714s"); + rtk->pmp_ca_event_ack = rtk->pmp_registry_v2; init_completion(&rtk->epmap_completion); init_completion(&rtk->coreanalytics_completion); From ff9cd2204f953a91d15f5316c08c9b9722a04e60 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1002/1514] dmaengine: apple-sio: the T6050 description where the sleep is described The T6050 description, which stops the SIO at the sleep's commit, was in force on the J714s by name. Follow the device tree: the boards that describe the sleep. The J716c describes it and leaves its SIO disabled, so nothing changes there. Signed-off-by: Jens Axboe --- drivers/dma/apple-sio.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index cb75beb54ae994..4c5b0b1627b5e0 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -697,12 +697,13 @@ static const struct sio_hw_data sio_hw_t6050 = { }; /* - * The T6050 description is in force on the board it has run on. On another T6050 board the - * node is taken as before: by its generic compatible. + * The T6050 description, with its stop at the sleep's commit, is in force on the boards + * that describe the sleep. On another T6050 board the node is taken as before: by its + * generic compatible. */ static bool sio_t6050_board(void) { - return of_machine_is_compatible("apple,j714s"); + return apple_t6050_sleep_described(); } static const struct of_device_id sio_of_match[] = { From 005028ce2115da91784f878dd37a6913d60ef808 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1003/1514] nvme: apple: the T6050 ANS2 sleep attachment where the sleep is described The attachment was made on two boards by name. Make it wherever the device tree describes T6050's deep sleep; the node's own properties still decide the rest. Signed-off-by: Jens Axboe --- drivers/nvme/host/apple-m5-sleep.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/drivers/nvme/host/apple-m5-sleep.h b/drivers/nvme/host/apple-m5-sleep.h index f22d6902bf2567..50bcaeabde6043 100644 --- a/drivers/nvme/host/apple-m5-sleep.h +++ b/drivers/nvme/host/apple-m5-sleep.h @@ -167,10 +167,8 @@ static int apple_nvme_m5_attach(struct apple_nvme *anv) { int ret; - /* Both boards use T6050 ANS2's split NVMe/NVMMU layout and retained SART. */ - if (!of_machine_is_compatible("apple,t6050") || - (!of_machine_is_compatible("apple,j714s") && - !of_machine_is_compatible("apple,j716c"))) + /* T6050 ANS2's split NVMe/NVMMU layout and retained SART, where the sleep is described. */ + if (!apple_t6050_sleep_described()) return -EOPNOTSUPP; /* The wait before the restart after a sleep comes from the DT; without it, no sleep. */ if (of_property_read_u32(anv->dev->of_node, "apple,sleep-wake-delay-ms", From 28994e4d3eaa2eb11223af90dd6d51335c8aee1a Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1004/1514] PCI: apple: T6050: the radio host's deep sleep where the sleep is described The host registered for T6050's deep sleep on two boards by name. Register wherever the device tree describes that sleep. Signed-off-by: Jens Axboe --- drivers/pci/controller/pcie-apple.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index fb2aed80ec54b4..fe702d2d546a0a 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -5499,8 +5499,7 @@ static void apple_pcie_t6050_sleep_probe(struct platform_device *pdev, struct ap { struct apple_pcie_port *port; - if (pcie->managed_sids || !(of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c"))) + if (pcie->managed_sids || !apple_t6050_sleep_described()) return; /* The one port a boot loader trained; an endpoint Linux powers is parked instead. */ list_for_each_entry(port, &pcie->ports, entry) From c01b3d33f0989664cd80b703d41b6904d7563ef3 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:30 -0700 Subject: [PATCH 1005/1514] iommu/apple-dart: the T6050 sleep rules where the sleep is described The display DARTs' V27 provider was admitted on two boards by name and the ISP DART's sleep on one. Take both wherever the device tree describes T6050's deep sleep: the sleep takes the ISP DART's stream registers on any of them. Signed-off-by: Jens Axboe --- drivers/iommu/apple-dart-v27-admission.inc | 4 +--- drivers/iommu/apple-dart.c | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/drivers/iommu/apple-dart-v27-admission.inc b/drivers/iommu/apple-dart-v27-admission.inc index 906be5ef222ef4..7b6c2be51b903e 100644 --- a/drivers/iommu/apple-dart-v27-admission.inc +++ b/drivers/iommu/apple-dart-v27-admission.inc @@ -10,9 +10,7 @@ static bool apple_dart_v27_provider(struct device *dev, resource_size_t base) unsigned int i; if (!IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) || - !(of_machine_is_compatible("apple,j714s") || - (of_machine_is_compatible("apple,j716c") && - of_machine_is_compatible("apple,t6050"))) || + !apple_t6050_sleep_described() || !of_device_is_compatible(dev->of_node, "apple,t6050-dart")) return false; for (i = 0; i < ARRAY_SIZE(ids); i++) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bf7a4fc0807faa..75514098cd1a96 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -5735,7 +5735,7 @@ static int apple_dart_probe(struct platform_device *pdev) if (dart->cold_ane && !IS_BUILTIN(CONFIG_APPLE_DART)) return -EOPNOTSUPP; dart->isp_host = of_device_is_compatible(dev->of_node, "apple,t6050-isp-dart"); - dart->isp_sleep = dart->isp_host && of_machine_is_compatible("apple,j714s"); + dart->isp_sleep = dart->isp_host && apple_t6050_sleep_described(); dart->power_retained = dart->isp_host; dart->per_stream = dart->isp_host || of_device_is_compatible(dev->of_node, "apple,t8140-dart") || From 827ec97a92d9a2b3f03f4f7c87c127ceea13ac6e Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:31 -0700 Subject: [PATCH 1006/1514] phy: apple: atc-t6050: the combo PHY's deep-sleep rules where the sleep is described The rules were in force on two boards by name. Apply them wherever the device tree describes T6050's deep sleep. Signed-off-by: Jens Axboe --- drivers/phy/apple/atc-t6050-combo.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/phy/apple/atc-t6050-combo.h b/drivers/phy/apple/atc-t6050-combo.h index ae50930a7a8093..83f97bc8356688 100644 --- a/drivers/phy/apple/atc-t6050-combo.h +++ b/drivers/phy/apple/atc-t6050-combo.h @@ -122,13 +122,13 @@ static void combo_pipe_fault(struct t6050_dp *dp, const char *what, int ret) /* * What the combo PHY gained for a deep sleep outside its sleep callbacks (a wrapper domain * still held at a stop is released, a safe state with a domain still held is stopped again, - * the always-on domain's hold over the sleep) is in force on the boards with a T6050 sleep, - * the J714s and the J716c. On another T6050 board the stop, the safe state and the probe are + * the always-on domain's hold over the sleep) is in force on the boards whose device tree + * describes a T6050 sleep. On another T6050 board the stop, the safe state and the probe are * as before. */ static bool combo_sleep_board(void) { - return of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"); + return apple_t6050_sleep_described(); } static bool combo_domains_held(struct t6050_dp *dp) From bb339b5494304635ea6b60279d2056743e536a91 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:31 -0700 Subject: [PATCH 1007/1514] usb: dwc3: apple: T6050's sleep lines where the sleep is described The dwc3 glue took T6050's sleep lines on the J714s and the J716c by name. Take them wherever the device tree describes T6050's sleep. The port controllers' side of this is in already: their sleep rules are asked for by the controllers' own properties. Signed-off-by: Jens Axboe --- drivers/usb/dwc3/dwc3-apple.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index c5740ee25d5329..5757cf33832da0 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -1109,12 +1109,12 @@ static void dwc3_apple_check_hub_later(struct dwc3_apple *appledwc) /* * Waiting for a Type-C PHY that is not started after sleep is specific to the T6050 boards - * whose port controllers take the sleep's power states (J714s, J716c). The notifier work - * and its admission rules apply to every board. + * whose port controllers take the sleep's power states: those whose device tree describes + * the sleep. The notifier work and its admission rules apply to every board. */ static bool dwc3_apple_sleep_board(void) { - return of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"); + return apple_t6050_sleep_described(); } /* From c4e6e7af34781f5e580dbd11d892348d8f2c516c Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:31 -0700 Subject: [PATCH 1008/1514] drm/asahi: g17: the M5 commit stop where the sleep is described The wrapped provider for T6050's deep sleep was used on two boards by name. Use it wherever the device tree describes that sleep. Signed-off-by: Jens Axboe --- drivers/gpu/drm/asahi/g17/sleep.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/sleep.c b/drivers/gpu/drm/asahi/g17/sleep.c index 380e6662f14191..0131ace971222e 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.c +++ b/drivers/gpu/drm/asahi/g17/sleep.c @@ -46,14 +46,13 @@ #define ASC_CPU_CONTROL 0x44 #define ASC_CPU_CONTROL_RUN BIT(4) -/* Only the M5 boards with a deep sleep need a wrapped provider translation here: the J714s - * and the J716c. Other G17 clients retain their established direct-domain methods below. +/* Only the M5 boards with a deep sleep need a wrapped provider translation here: those whose + * device tree describes it. Other G17 clients retain their established direct-domain methods + * below. */ static bool asahi_g17_m5_provider(struct device *dev) { - return (of_machine_is_compatible("apple,j714s") || - of_machine_is_compatible("apple,j716c")) && - of_machine_is_compatible("apple,t6050") && + return apple_t6050_sleep_described() && of_device_is_compatible(dev->of_node, "apple,agx-g17s"); } From c4ba4a3a90d378587d14fd6e6080e75c542d22d1 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 05:28:31 -0700 Subject: [PATCH 1009/1514] drm/apple: v27: the J714s's sleep and panel paths by the sleep's description The V27 sleep's paths for the internal panel (the 27.0 method table with the sleep call and the A407 swap, the panel's AV and DP services) and what the external processors gained around it were in force on the J714s by name. Follow the device tree: a sleep description with apple,display-method-sleep. The J716c's has none and keeps its endpoint transport. Signed-off-by: Jens Axboe --- drivers/gpu/drm/apple/dcp.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 1c7464a54f80fd..996e962b9e091a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -495,12 +495,13 @@ MODULE_PARM_DESC(t6050_ext_sleep, /* * What a T6050 external display processor gained outside the firmware 27 sleep itself (the * Type-C reconnect skipped for a crashed one, a crashed one refusing a deep sleep before - * anything is stopped, the link line) is in force on the board it has run on, the J714s. - * Elsewhere, other boards with the same SoC included, these are as before. + * anything is stopped, the link line) is in force where the sleep's description has the + * display coprocessors sleep by their method table (apple,display-method-sleep). Elsewhere, + * other boards with the same SoC included, these are as before. */ static bool dcp_j714s_ext(struct device *dev) { - return of_machine_is_compatible("apple,j714s") && + return apple_t6050_sleep_property("apple,display-method-sleep") && of_device_is_compatible(dev->of_node, "apple,t6050-dcpext"); } @@ -7476,7 +7477,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) dcp->fw_compat = fw_compat; dcp->v27_j714s = fw_compat == DCP_FIRMWARE_V_27_0 && - of_machine_is_compatible("apple,j714s"); + apple_t6050_sleep_property("apple,display-method-sleep"); /* * Probe-lifetime like the desktop state: component bind opens a devres * group on this device and releases it on failure or unbind. From f35f68016160a52a1a21c72700e1e24bf7bb25be Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:40:14 -0700 Subject: [PATCH 1010/1514] arm64: dts: apple: t6050-k116s: Add the PMU's RTC Describe the RTC of the PMU on nub-spmi0, as the J714s does: the registers are the T6041 PMU's, at the addresses this board's ADT gives. It is a second RTC beside the SMC's and the only one with an alarm. The PMU raises no alarm interrupt on this SoC, so the alarm is a wake source for a firmware sleep only. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-k116s.dts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index f55944c0c83179..df6214b51252e0 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -949,3 +949,19 @@ firmware-name = "apple/mesacal-k116s.bin", "apple/msrk-k116s.bin"; }; }; + +/* + * The PMU's RTC and its alarm. ADT: the PMU's info-rtc (0x2002), + * info-rtc_alarm_offset (0x2008), info-rtc_irq_mask_offset (0x200e), + * info-rtc_alarm_ctrl (0x2000) and info-rtc_scrpad (0x2100), the registers of + * the T6041 PMU. It raises no interrupt on this SoC: an armed alarm can only + * wake the machine from a firmware sleep, not from s2idle. + */ +&pmu { + pmu_rtc: rtc { + compatible = "apple,t6050-pmu-rtc", "apple,t6041-pmu-rtc"; + nvmem-cells = <&rtc_offset>; + nvmem-cell-names = "rtc_offset"; + wakeup-source; + }; +}; From 747379cb398059d2e8691814ac8e37bd70f666de Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:40:14 -0700 Subject: [PATCH 1011/1514] arm64: dts: apple: t6050-k116s: enable the video encoder's power states iBoot leaves VENC0_SYS on (PS word 0xf0003ff). Its node is disabled on the K116s, so nothing ever turns it off, and FAB0_SOC stays up behind it. The J714s enables these power states for its encoder. With VENC0_SYS on, the SoC does not enter the firmware-driven sleep: the whole entry runs, and the machine resets about 5 s after the commit word. macOS has VENC0_SYS off at its commit on this board (register state read with macOS as an aura guest, the commit withheld). Enable ps_fab1_piogw (firmware-owned), ps_fab0_soc (always-on) and the ps_venc0_* states as on the J714s. Unused, genpd turns them off at boot. No encoder is described yet. Tested on a K116s: venc0-sys and its children read off after boot, and the J714s commit sequence then sleeps. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-k116s.dts | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index df6214b51252e0..39b804ef487369 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -965,3 +965,42 @@ wakeup-source; }; }; + +/* + * The video encoder's power states, as on the J714s. iBoot leaves VENC0_SYS on, and the SoC does + * not enter the firmware-driven sleep with it on. Enabled and unused, genpd turns it off at + * boot. No encoder is described yet. + */ +&ps_fab1_piogw { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab0_soc { + apple,always-on; + status = "okay"; +}; + +&ps_venc0_sys { + status = "okay"; +}; + +&ps_venc0_dma { + status = "okay"; +}; + +&ps_venc0_pipe4 { + status = "okay"; +}; + +&ps_venc0_pipe5 { + status = "okay"; +}; + +&ps_venc0_me0 { + status = "okay"; +}; + +&ps_venc0_me1 { + status = "okay"; +}; From 8d0d34bcaa5b2825400e5fa9c7af7936e3121af3 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:40:15 -0700 Subject: [PATCH 1012/1514] arm64: dts: apple: t6050-j714s-sleep-soc: make the CIO sleep part optional The SoC values file ends with the J714s's USB4 router sleep (acio2, its DART, the clock protection syscon), which needs nodes only t6050-max.dtsi has. A board that includes the SoC values without that router defines T6050_SLEEP_SOC_NO_CIO first. No change for the J714s. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi index 9b0f2f0c3376ee..5ef086dee5765a 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-sleep-soc.dtsi @@ -4576,7 +4576,11 @@ * taking that DART down and back to the live value before using it again. The router's host * also needs the port's PHY, which it stops after the router and starts before it. The left * port's router was never up in a trace: it has none of this and is powered off for a sleep. + * + * A board that includes these SoC values without that router (no acio2) defines + * T6050_SLEEP_SOC_NO_CIO first. */ +#ifndef T6050_SLEEP_SOC_NO_CIO &die0 { ps_prot: syscon@2803f0000 { compatible = "apple,t6050-ps-prot", "syscon"; @@ -4595,3 +4599,4 @@ &apciec2_dart { apple,clock-protection = <&ps_prot 31>; }; +#endif /* T6050_SLEEP_SOC_NO_CIO */ From 6e836d8f6815ca91f57f014110cc709985a2a430 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 07:33:57 -0700 Subject: [PATCH 1013/1514] dt-bindings: mailbox: apple: add the T6050 secure RTBuddy port The internal DCP of a T6050 on firmware 27.2 has the secure port T8140's has (ADT dcp-exclave-mailbox, iop,secure-rtbuddy-proxy). Signed-off-by: Jens Axboe --- Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml index 7626c8afcedbd6..e7f34eb39b1529 100644 --- a/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml +++ b/Documentation/devicetree/bindings/mailbox/apple,mailbox.yaml @@ -98,6 +98,7 @@ properties: iop,secure-rtbuddy-proxy. It is polled, with no interrupts described. items: - enum: + - apple,t6050-secure-rtbuddy-proxy - apple,t8140-secure-rtbuddy-proxy - const: apple,secure-rtbuddy-proxy From 2b672b1501e7743468ba3fb88c2951c453d597c6 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 07:33:57 -0700 Subject: [PATCH 1014/1514] dt-bindings: soc: apple,t6050-sleep: allow an empty apple,pinctrl-skip-pins Without the property no pin is saved. A board whose ADT names no pin to leave alone, the K116s, has every pin saved: the property is there and empty. Signed-off-by: Jens Axboe --- .../devicetree/bindings/soc/apple/apple,t6050-sleep.yaml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml index 7d26c0049f8ac0..a8908c524d1ae9 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6050-sleep.yaml @@ -117,10 +117,12 @@ properties: description: The AP pin controller, whose pins a deep sleep resets. apple,pinctrl-skip-pins: - $ref: /schemas/types.yaml#/definitions/uint32-array + oneOf: + - $ref: /schemas/types.yaml#/definitions/uint32-array + - type: boolean description: | Pins neither saved nor restored. From the ADT, set by the bootloader; - without it no pin is saved. + without it no pin is saved. Empty where every pin is saved. apple,sleep-low-pins: $ref: /schemas/types.yaml#/definitions/uint32-array From 59236983556e133fbc697812e4dc8877c8aea5c9 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 07:33:57 -0700 Subject: [PATCH 1015/1514] dt-bindings: display: apple,dcp: add apple,secure-mbox The boot loader hands the display over only to a node whose mboxes is the one ASC mailbox. A machine whose internal DCP has a secure port names it in a property of its own there, and the driver takes it as the "secure" mailbox. Signed-off-by: Jens Axboe --- Documentation/devicetree/bindings/display/apple,dcp.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 6867256ee228ec..b318038fc5442a 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -94,6 +94,14 @@ properties: - const: mbox - const: secure + apple,secure-mbox: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The coprocessor's secure RTBuddy port, on a machine whose boot loader + hands the display over only to a node with a single mailbox in mboxes. + The driver takes it as the "secure" mailbox. Elsewhere the port is the + second entry of mboxes. + iommus: maxItems: 1 From 5b8f42b4109d877e4e7199947db14253a6780db1 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 18 Nov 2026 06:40:15 -0700 Subject: [PATCH 1016/1514] arm64: dts: apple: t6050-k116s: describe and enable the deep sleep The J714s's sleep controller description and SoC values on the K116s (16-inch M5 Pro, firmware 27.2), with what differs on this board: - apple,pinctrl-skip-pins is empty: the K116s ADT's gpio0 has no no-restore-gpio-pins. With the J714s's list the panel stays dark after a deep sleep. - The display coprocessor's secure mailbox (ADT dcp-exclave-mailbox), named by apple,secure-mbox so that mboxes stays the one ASC mailbox for the boot loader. - The MagSafe port's PD controller (hpm5), so that the sleep puts it in S3. - The three port controllers ask for the sleep's rules for the system power state command and for the reset on a failed probe (apple,sleep-ssps-rules, apple,reset-on-failed-probe), as the J714s's. - dcpext0 without its Type-C route, as dcpext1 to 3: the engine must bind for the sleep to stop its firmware. - apple,sram-keep <0x56000 0x9b000> for the PMP: its __DATA starts at 0x56000 on 27.2 (ADT segment-ranges). With the J714s's range the PMP does not come back from the sleep. - The four clock words are parked with 0x80100000, as macOS does on this board (J714s: 0x80100400). - apple,panel-video-open-delay-us 10000: the panel's plug takes about 2.9 ms here, and with 2500 us the open landed before the firmware's close. - No CIO sleep part: no USB4 router is described. - apple,display-method-sleep and the SMC's wake reasons, as on the J714s: the K116s ADT's smc-pmu node numbers them the same way. Needs a boot loader that hands the four DCPEXT to the kernel on 27.2 (aura with ext = true for the V27_2 images) and publishes the S2R mailbox. Tested on a K116s: sleep and wake by RTC alarm and by the lid, several cycles a boot, and one sleep of 7.7 hours; display, NVMe, Wi-Fi and Bluetooth work after the wake. The values taken from the J714s (commit schedule, SMC policy, MCC and clock sequences) have not been checked against this board one by one. Signed-off-by: Jens Axboe --- .../boot/dts/apple/t6050-k116s-sleep.dtsi | 285 ++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k116s.dts | 49 +++ 2 files changed, 334 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi b/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi new file mode 100644 index 00000000000000..1c7c50da725271 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k116s-sleep.dtsi @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Deep sleep (suspend to RAM) on the K116s: the J714s description with this board's differences + * (the pins, the display coprocessor's secure mailbox, dcpext0). The sleep controller and what + * it needs from the rest of the tree. + */ + +/ { + aliases { + /* The boot loader finds the SIO by this alias */ + sio = &sio; + }; + + sleep: sleep-controller@280600000 { + compatible = "apple,t6050-sleep"; + reg = <0x2 0x80600000 0x0 0x4000>, + <0x2 0x80900000 0x0 0x4000>, + <0x2 0x88300000 0x0 0xc000>, + <0x23 0x00e80000 0x0 0x4000>, + <0x23 0x80600000 0x0 0xc000>, + <0x23 0x88300000 0x0 0x4000>, + <0x2 0x80760000 0x0 0x10000>, + <0x2 0x807d4000 0x0 0x4000>, + <0x2 0x80930000 0x0 0x4000>, + <0x23 0x00e90000 0x0 0x4000>, + <0x23 0x80760000 0x0 0x10000>, + <0x2 0x80700000 0x0 0x20000>, + <0x23 0x80700000 0x0 0x14000>, + <0x2 0x807ec000 0x0 0x4000>, + <0x2 0x80950000 0x0 0x4000>, + <0x23 0x807dc000 0x0 0x4000>, + <0x2 0x80620000 0x0 0x4000>, + <0x2 0x8062c000 0x0 0x4000>, + <0x2 0x80688000 0x0 0x4000>, + <0x2 0x88f04000 0x0 0x4000>, + <0x2 0x8836c000 0x0 0x4000>, + <0x2 0x88330000 0x0 0x4000>, + <0x2 0x80920000 0x0 0x4000>, + <0x2 0x8a014000 0x0 0x4000>, + <0x2 0x86700000 0x0 0x14000>, + <0x2 0x86806000 0x0 0x3000>, + <0x2 0x84240000 0x0 0x20000>, + <0x2 0x803f0000 0x0 0x4000>, + <0x2 0x88370000 0x0 0x4000>, + <0x23 0x88370000 0x0 0x4000>, + <0x2 0x10e40000 0x0 0x10000>, + <0x2 0x11e40000 0x0 0x10000>, + <0x2 0x12e40000 0x0 0x10000>, + <0x4 0x17020000 0x0 0x4000>, + <0x4 0x17980000 0x0 0x4000>, + <0x2 0x80000000 0x0 0x4000>, + <0x2 0x80078000 0x0 0x4000>, + <0x23 0x80078000 0x0 0x4000>, + <0x22 0x20200000 0x0 0x8000>, + <0x22 0x20400000 0x0 0x8000>, + <0x22 0x20600000 0x0 0x8000>, + <0x22 0x20800000 0x0 0x8000>, + <0x22 0x22200000 0x0 0x8000>, + <0x2 0x88004000 0x0 0x4000>, + <0x23 0x88004000 0x0 0x4000>, + <0x23 0x80400000 0x0 0x4000>; + reg-names = "ps0", "ps1", "ps-aon", "ps-gpx", "ps-media", "ps-gfx-aon", + "clk", "clk-soc", "clk1", "afr-clk", "media-clk", + "perf", "media-perf", "table0", "table1", "media-table", + "cluster", "pwrgate", "cpu-start", "commit", "wdt", "wdt-aux", + "disp-gate", "spmi", "pmc-voters", "pmc-rails", "ptd", "gapf", + "aon-clk", "media-aon-clk", "cpm0", "cpm1", "cpm2", + "storage-phy", "storage-phy-ip", + "clkgen", "clkgen-78", "media-clkgen-78", + "mcc22", "mcc23", "mcc24", "mcc25", "mcc26", + "wake", "wake-gfx", "aic-gfx"; + apple,display-coprocessors = <&dcp>, <&dcpext0>, <&dcpext1>, <&dcpext2>, <&dcpext3>; + apple,spmi-buses = <&nub_spmi_a0>, <&nub_spmi2>, <&nub_spmi_a1>, <&nub_spmi3>, + <&aop_spmi0>; + /* SEP's, PMP0's, SIO's and the DCP's DART, stopped in the sleep's last steps */ + apple,sleep-darts = <&sep_dart>, <&pmp0_dart>, <&sio_dart>, <&dcp_dart>; + /* The N1's host: its link is shut down for the sleep and brought back after it */ + apple,radio-pcie = <&pcie0>; + apple,pinctrl = <&pinctrl_ap>; + /* The display coprocessors take the sleep through their firmware 27 method table */ + apple,display-method-sleep; + }; +}; + +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 13 35 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "sdconn", "charger", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + +/* + * The N1's warm reset (ADT pci-bridge0 function-warm_reset: the SMC, key 'bpli'). The N1's + * firmware does not survive a sleep; the host resets the N1 after the wake, before its link + * trains. The writes that give the reset are the boot loader's to add (see the binding). + */ +&port00 { + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; +}; + +/* On through the commit: the sleep stops their users in its last steps. */ +&ps_pmp { + apple,always-on; +}; + +&ps_pms_sram { + apple,always-on; +}; + +&ps_gfx { + apple,always-on; +}; + +&ps_spi_p { + apple,always-on; +}; + +&ps_atc3_usb_aon { + apple,always-on; +}; + +&ps_sio { + apple,always-on; + status = "okay"; +}; + +&ps_sio_cpu { + apple,always-on; + status = "okay"; +}; + +/* The port controllers put in system power state S3 before the commit, then SLEEP */ +&hpm1 { + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; +}; + +&hpm2 { + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; +}; + +/* + * The MagSafe port's PD controller (ADT hpm5, nub-spmi-a0 0x08), described as + * on the J714s so that the sleep puts it in S3 with the others. + */ +&nub_spmi_a0 { + hpm5: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + apple,no-liquid-detection; + apple,sleep-ssps; + apple,sleep-ssps-rules; + apple,reset-on-failed-probe; + }; +}; + +&{/soc@200000000} { + /* + * The cores' power-gate enables, /arm-io/pmgr reg[0] + 0x2c000, one word per core: the + * boot loader leaves core 0's (the boot core's) and core 12's clear. Without them the + * boot cluster never powers down, and the sleep never gets past its first sequence. + */ + cluster_pwrgate: power-gate@28062c000 { + compatible = "apple,t6050-cluster-pwrgate", "apple,cluster-pwrgate"; + reg = <0x2 0x8062c000 0x0 0x4>, + <0x2 0x8062c0c0 0x0 0x4>; + }; +}; + +/* AOP2, running until the commit: its ASC mailbox at the AOP2 ASC + 0x8000 */ +&{/soc@200000000} { + aop2_mbox: mailbox@291608000 { + compatible = "apple,t6050-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x2 0x91608000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + }; +}; + +&aop2 { + reg = <0x2 0x91600000 0x0 0x4000>; + reg-names = "asc"; + /delete-property/ interrupts; + mboxes = <&aop2_mbox>; + mbox-names = "mbox"; + apple,dma-range = <0x110 0x0 0x10 0x0>; + status = "okay"; +}; + +/* + * The SIO, running until the sleep's own stop: its ASC bank split around its mailbox. The boot + * loader enables it with its firmware and tables. + */ +/delete-node/ &sio; + +&{/soc@200000000} { + sio_mbox: mailbox@505e08000 { + compatible = "apple,t6050-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x5 0x5e08000 0x0 0x4000>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + power-domains = <&ps_sio_cpu>; + #mbox-cells = <0>; + }; + + sio: dma-controller@505e00000 { + compatible = "apple,t6050-sio", "apple,sio"; + reg = <0x5 0x5e00000 0x0 0x8000>, + <0x5 0x5850000 0x0 0x4000>, + <0x5 0x5e0c000 0x0 0x7c000>; + reg-names = "asc", "auxiliary", "asc-tail"; + #dma-cells = <1>; + dma-channels = <128>; + mboxes = <&sio_mbox>; + iommus = <&sio_dart 0>; + power-domains = <&ps_sio_cpu>; + clocks = <&peripheral_clocks 359>, <&peripheral_clocks 358>; + status = "disabled"; + }; +}; + +&sio_dart { + power-domains = <&ps_sio_cpu>; + status = "okay"; +}; + +/* + * The AP pins a deep sleep neither saves nor restores: none. The K116s ADT's gpio0 has no + * no-restore-gpio-pins (the J714s's has 5 6 7 112 141), and with those skipped the panel stayed + * dark after a deep sleep. Without the property no pin is saved at all. + */ +&sleep { + apple,pinctrl-skip-pins = <>; +}; + +/* + * The display coprocessor's secure mailbox (ADT /arm-io/dcp-exclave-mailbox, + * iop,secure-rtbuddy-proxy, reg 0x4cae7c000). Firmware 27.2 acknowledges no IOP power state + * while nothing answers it, as on T8140. + */ +&{/soc@200000000} { + dcp_secure_mbox: mailbox@4cae7c000 { + compatible = "apple,t6050-secure-rtbuddy-proxy", "apple,secure-rtbuddy-proxy"; + reg = <0x4 0xcae7c000 0x0 0x4000>; + #mbox-cells = <0>; + }; +}; + +/* + * Not in mboxes: the boot loader hands the display over only to a node whose mboxes is the one + * ASC mailbox. The driver takes it from this property. + */ +&dcp { + apple,secure-mbox = <&dcp_secure_mbox>; +}; + +/* + * dcpext0 without its Type-C route, as dcpext1 to 3 are here. Its PHY's DP side + * is not described on this board, and the engine's probe waits for it and gives the engine + * up; a deep sleep needs the engine bound, to stop its firmware. + */ +&dcpext0 { + /delete-property/ apple,connector-type; + /delete-property/ apple,dptx-die; + /delete-property/ apple,typec-dptx-phys; + /delete-property/ apple,typec-mux-indices; + /delete-property/ phys; + /delete-property/ phy-names; + /delete-property/ mux-controls; + /delete-property/ mux-control-names; + /delete-node/ typec-routes; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index 39b804ef487369..ce2dbbf489ea35 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -1004,3 +1004,52 @@ &ps_venc0_me1 { status = "okay"; }; + +/* + * Deep sleep: the sleep controller's description and the J714s's SoC values, then what differs + * on this board (firmware 27.2). + */ +#include "t6050-k116s-sleep.dtsi" +/* No USB4 router is described on this board: without the J714s's CIO sleep part. */ +#define T6050_SLEEP_SOC_NO_CIO +#include "t6050-j714s-sleep-soc.dtsi" + +/* + * macOS on this board parks the four clock words with 0x80100000 in the last 0.5 ms before its + * commit (traced as an aura guest); the J714s's values have bit 10 set. + */ +&sleep { + apple,seq-commit-sio = + <0x0 17 0x290 0x400024f>, + <0x0 17 0x2a0 0x400024f>, + <0x1 51 0xa0 0x0>, + <0x0 51 0xa0 0x80100000>, + <0x1 51 0xa0 0x0>, + <0x1 51 0xa4 0x0>, + <0x0 51 0xa4 0x80100000>, + <0x1 51 0xa4 0x0>, + <0x1 51 0x94 0x0>, + <0x0 51 0x94 0x80100000>, + <0x1 51 0x94 0x0>, + <0x1 51 0x90 0x0>, + <0x0 51 0x90 0x80100000>, + <0x1 51 0x90 0x0>; +}; + +/* + * The PMP firmware's __DATA starts at 0x56000 on 27.2 (ADT pmp0 segment-ranges: __TEXT 0x56000 + * bytes, __DATA 0x9b000 bytes), not at the J714s's 0x58000. With the wrong range kept over the + * sleep the PMP does not come back (endpoint discovery -62). + */ +&pmp0 { + apple,sram-keep = <0x56000 0x9b000>; +}; + +/* + * The panel's plug takes about 2.9 ms here from the video interface's announcement to the + * firmware's "ioav i/f is now closed", and the next round of reports follows about 33 ms later. + * With the J714s's 2500 us the open landed 25 us before the close. + */ +&dcp { + apple,panel-video-open-delay-us = <10000>; +}; From c115ae9eea4406295649d99b4210af8c7bfcacc2 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 09:54:29 -0700 Subject: [PATCH 1017/1514] dt-bindings: display: apple,dcp: add apple,merged-mode-limit The platform's limit on merged modes belongs to the external display coprocessors of a machine, not to its sleep. Give it a property of their nodes. Signed-off-by: Jens Axboe --- Documentation/devicetree/bindings/display/apple,dcp.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index b318038fc5442a..ca938411a566ae 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -102,6 +102,13 @@ properties: The driver takes it as the "secure" mailbox. Elsewhere the port is the second entry of mboxes. + apple,merged-mode-limit: + type: boolean + description: + The platform's limit on merged modes applies to this external display + coprocessor. A display takes a second coprocessor as its pair only + while one is left for every external display that is present. + iommus: maxItems: 1 From c4ff2269ee60084f949517f594045ee48d8669b2 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 09:54:29 -0700 Subject: [PATCH 1018/1514] arm64: dts: apple: t6050-j714s: the merged-mode limit of the external display coprocessors The driver applies the limit on the J714s. Say so on its four external display coprocessors, for the driver to read. Signed-off-by: Jens Axboe --- arch/arm64/boot/dts/apple/t6050-j714s.dts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index b36ebf840260ee..0b83928178a4be 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -792,6 +792,23 @@ #include "t6050-j714s-sleep-soc.dtsi" #include "t6050-j714s-sleep-adt.dtsi" +/* A merged mode's pair is given only while every external display has an engine */ +&dcpext0 { + apple,merged-mode-limit; +}; + +&dcpext1 { + apple,merged-mode-limit; +}; + +&dcpext2 { + apple,merged-mode-limit; +}; + +&dcpext3 { + apple,merged-mode-limit; +}; + /* The display coprocessors take the sleep through their firmware 27 method table */ &sleep { apple,display-method-sleep; From a01d61c1f397f92bb05c00b26b5ecff09856a788 Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Thu, 19 Nov 2026 09:54:29 -0700 Subject: [PATCH 1019/1514] drm/apple: v27: the merged-mode limit by the coprocessor's own property dcp_peer_limit_applies() rode on dcp_j714s_ext(), which follows the sleep's description now. The limit is of the display engines, not of the sleep: read apple,merged-mode-limit from the coprocessor's node. The J714s sets it, so nothing changes there, and no other board takes the limit. Signed-off-by: Jens Axboe --- drivers/gpu/drm/apple/dcp-peer-v27.inc | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-v27.inc b/drivers/gpu/drm/apple/dcp-peer-v27.inc index a824ab7e992659..34ee3e472d3ef0 100644 --- a/drivers/gpu/drm/apple/dcp-peer-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-v27.inc @@ -8,12 +8,14 @@ module_param(peer_allocation_probe, bool, 0444); MODULE_PARM_DESC(peer_allocation_probe, "Firmware27 logical peer allocation for merged modes (default: on)"); /* - * The platform limit on merged modes (dcp_fabric_merged_fits()) holds on the - * board it has run on, for the J714s's T6050 external display processors. + * The platform limit on merged modes (dcp_fabric_merged_fits()) holds for the + * external display processors whose node says so (apple,merged-mode-limit). */ static bool dcp_peer_limit_applies(struct apple_dcp *dcp) { - return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp_j714s_ext(dcp->dev); + return dcp->fw_compat == DCP_FIRMWARE_V_27_0 && + of_device_is_compatible(dcp->dev->of_node, "apple,t6050-dcpext") && + of_property_read_bool(dcp->dev->of_node, "apple,merged-mode-limit"); } /* @@ -68,8 +70,7 @@ void dcp_peer_limit_update_v27(struct drm_device *drm) unsigned int n = 0, i; struct drm_crtc *crtc; - /* Neither a board without the limit nor a device without CRTCs. */ - if (!of_machine_is_compatible("apple,j714s") || !drm->mode_config.num_crtc) + if (!drm->mode_config.num_crtc) return; scoped_guard(mutex, &dcp_peer_lock) { drm_for_each_crtc(crtc, drm) { From 84b8abb504882d4e2f9807261a338ebd16d6ed86 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:57:25 +1100 Subject: [PATCH 1020/1514] ci: pr-readiness: run only for changes that can move the result Same caller as aurora-silicon/.github workflow-templates/pr-readiness.yml: one concurrency group per pull request, edits only when the title, body or base changed, label events only for hold, blocked and hw-row-ok. A lane rewriting PR bodies had queued ~90 readiness runs in 40 minutes. Signed-off-by: Ryan Murray --- .github/workflows/pr-readiness.yml | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-readiness.yml b/.github/workflows/pr-readiness.yml index ab56cb82792d66..7628370183cf91 100644 --- a/.github/workflows/pr-readiness.yml +++ b/.github/workflows/pr-readiness.yml @@ -27,17 +27,23 @@ permissions: statuses: read concurrency: - # Comments get their own group without cancelling, so a stream of - # comments (or a bot's) never cancels a push or review run. - group: pr-readiness-${{ github.event_name == 'issue_comment' && format('comment-{0}', github.event.comment.id) || github.event.pull_request.number || inputs.pr || 'sweep' }} - cancel-in-progress: ${{ github.event.pull_request.number != null }} + # One group per pull request: a burst of edits, comments or labels + # collapses into one pending run, which reads the current state anyway. + group: pr-readiness-${{ github.event.pull_request.number || github.event.issue.number || inputs.pr || 'sweep' }} + cancel-in-progress: false jobs: readiness: - # Reviews on pull requests from forks get a read-only token, and the - # bot's own comments do not matter; the sweep picks those up. + # Skipped (no runner used): reviews on pull requests from forks (read-only + # token; the sweep picks those up), bot comments, edits that change + # neither title, body nor base, and labels other than the human holds. if: >- github.repository_owner == 'aurora-silicon' && + (github.event.action != 'edited' || github.event_name != 'pull_request_target' || + github.event.changes.body != null || github.event.changes.title != null || + github.event.changes.base != null) && + (!contains(fromJSON('["labeled","unlabeled"]'), github.event.action) || + contains(fromJSON('["hold","blocked","hw-row-ok"]'), github.event.label.name)) && (github.event_name != 'pull_request_review' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || From e026875ee515a1c27fc188ddae52779b2a65f312 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:59:25 +1100 Subject: [PATCH 1021/1514] ci: pr-readiness: concurrency on the job, so skipped events never cancel a pending run Same as aurora-silicon/.github#7 after review: a workflow-level group is entered by runs the job filter skips; a job-level group is not. Also run on converted_to_draft. Signed-off-by: Ryan Murray --- .github/workflows/pr-readiness.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/pr-readiness.yml b/.github/workflows/pr-readiness.yml index 7628370183cf91..76d05c7ece5f52 100644 --- a/.github/workflows/pr-readiness.yml +++ b/.github/workflows/pr-readiness.yml @@ -6,7 +6,7 @@ name: pr-readiness on: pull_request_target: - types: [opened, reopened, synchronize, edited, ready_for_review, labeled, unlabeled] + types: [opened, reopened, synchronize, edited, ready_for_review, converted_to_draft, labeled, unlabeled] pull_request_review: types: [submitted, dismissed] issue_comment: @@ -26,12 +26,6 @@ permissions: checks: read statuses: read -concurrency: - # One group per pull request: a burst of edits, comments or labels - # collapses into one pending run, which reads the current state anyway. - group: pr-readiness-${{ github.event.pull_request.number || github.event.issue.number || inputs.pr || 'sweep' }} - cancel-in-progress: false - jobs: readiness: # Skipped (no runner used): reviews on pull requests from forks (read-only @@ -48,6 +42,12 @@ jobs: github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || (github.event.issue.pull_request && github.event.comment.user.type != 'Bot')) + # One group per pull request, on the job so that skipped events never + # enter it: a burst collapses into one pending run, which reads the + # current state anyway. + concurrency: + group: pr-readiness-${{ github.event.pull_request.number || github.event.issue.number || inputs.pr || 'sweep' }} + cancel-in-progress: false uses: aurora-silicon/.github/.github/workflows/pr-readiness.yml@main with: pr: ${{ format('{0}', github.event.pull_request.number || github.event.issue.number || inputs.pr || '') }} From ee1ce11e497d33e7acf04e12da19c7330b4ad821 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 01:06:17 +1100 Subject: [PATCH 1022/1514] ci: address the channel tags only by their full ref A branch named aurora-edge exists from the previous distribution Edge train. Read and move the channel tags only as refs/tags/ (the nightly check used the bare name) and drop the check that refused to create a tag while that branch exists; the branch is archived once the distribution publishers read the release. Signed-off-by: Ryan Murray --- .github/workflows/kernel-release.yml | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 0424c9cd7705e8..44d3ca00c7ddba 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -102,8 +102,8 @@ jobs: *) echo "::error::unexpected trigger $EVENT $REF"; exit 1 ;; esac if [ "$channel" = nightly ]; then - sha=$(gh api "repos/$REPO/commits/main" -q .sha) - last=$(gh api "repos/$REPO/commits/aurora-nightly" -q .sha 2>/dev/null || true) + sha=$(gh api "repos/$REPO/git/ref/heads/main" -q .object.sha) + last=$(gh api "repos/$REPO/git/ref/tags/aurora-nightly" -q .object.sha 2>/dev/null || true) if [ "$EVENT" = schedule ] && [ "$last" = "$sha" ]; then echo "main is still at the last nightly ($sha); nothing to build" build=false @@ -318,8 +318,9 @@ jobs: run: | set -euo pipefail tag="aurora-$CHANNEL" - # Rolling channel tags only move forward: the new commit must contain - # the one the tag points at now (a rewritten main stops here). + # Channel tags are always addressed as refs/tags/, never by the + # bare name, which may also be a branch. They only move forward: the + # new commit must contain the tagged one (a rewritten main stops here). old=$(gh api "repos/$GH_REPO/git/ref/tags/$tag" -q .object.sha 2>/dev/null || true) if [ -n "$old" ]; then status=$(gh api "repos/$GH_REPO/compare/$old...$SHA" -q .status) @@ -332,10 +333,6 @@ jobs: esac fi [ "$old" = "$SHA" ] && { echo "$tag already at $SHA"; exit 0; } - if gh api "repos/$GH_REPO/git/ref/heads/$tag" >/dev/null 2>&1; then - echo "::error::a branch named $tag exists; rename it to archive/$tag so the tag name is unambiguous" - exit 1 - fi # The aurora-* tags are protected by a ruleset that only the release # deploy key may bypass; GITHUB_TOKEN cannot move them. if [ -z "$DEPLOY_KEY" ]; then From 1b53a0870eaba68b6d2f35081cb39d77798bca66 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 01:21:09 +1100 Subject: [PATCH 1023/1514] media: apple: avd: allow pre-streaming H.264/HEVC format-negotiation SPS Stateless V4L2 decoders such as Chromium's V4L2VideoDecoder::SetExtCtrlsInit() issue VIDIOC_S_EXT_CTRLS before STREAMON with minimal H.264 and HEVC SPS controls carrying only chroma_format_idc, bit depth, and (for HEVC) picture dimensions so the driver can narrow CAPTURE pixel formats (NV12 vs P010). In that pre-streaming init call, H.264 leaves flags == 0 (without V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY) and HEVC leaves CTB size fields zeroed (log2_min_luma_coding_block_size_minus3 == 0, log2_diff_max_min_luma_coding_block_size == 0). avd_h264_try_ctrl() and avd_hevc_try_ctrl() previously rejected both with -EINVAL, breaking Chromium hardware H.264 and HEVC initialization before CAPTURE format negotiation. Split format validation (dimensions, chroma format, bit depth) into avd_h264_validate_sps_fmt() and avd_hevc_validate_sps_fmt(). Use the format check for pre-streaming try_ctrl (and avd_h264_start), while streaming try_ctrl and per-frame avd_h264_run()/avd_hevc_run() continue to enforce full SPS validation (rejecting interlaced H.264 and unsupported HEVC CTB sizes). Add KUnit coverage in avd-h264-test.c and avd-hevc-test.c. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-h264-test.c | 46 +++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 40 +++++++++++++-- .../media/platform/apple/avd/avd-hevc-test.c | 50 +++++++++++++++++++ drivers/media/platform/apple/avd/avd-hevc.c | 40 +++++++++++++-- drivers/media/platform/apple/avd/avd.h | 4 ++ 5 files changed, 170 insertions(+), 10 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index 3b7fec1d7b51bf..b39984550d092b 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -160,6 +160,51 @@ static void avd_sps_size_test(struct kunit *test) KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), c->ret); } +/* + * Pre-streaming format negotiation (e.g. Chromium V4L2VideoDecoder::SetExtCtrlsInit) + * supplies chroma_format_idc and bit depth with flags == 0 and zeroed dimensions + * before the first frame request carries the parsed SPS. Format validation accepts + * those controls while full SPS validation still rejects interlaced streams. + */ +static void avd_sps_fmt_init_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + }; + struct avd_dev *dev; + struct avd_ctx *ctx; + + dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dev); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->dev = dev; + ctx->coded_fmt.fmt.pix_mp.width = 1280; + ctx->coded_fmt.fmt.pix_mp.height = 720; + + /* 8-bit and 10-bit 4:2:0 pre-streaming init controls */ + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + /* Unsupported formats remain rejected pre-streaming */ + sps.chroma_format_idc = 3; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 1; + sps.bit_depth_luma_minus8 = 4; + sps.bit_depth_chroma_minus8 = 4; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 0; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); +} + static void avd_start_slices_test(struct kunit *test) { struct v4l2_ctrl_h264_sps sps = { @@ -209,6 +254,7 @@ static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), KUNIT_CASE_PARAM(avd_slice_fits_test, avd_slice_fits_gen_params), KUNIT_CASE_PARAM(avd_sps_size_test, avd_sps_size_gen_params), + KUNIT_CASE(avd_sps_fmt_init_test), KUNIT_CASE(avd_start_slices_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 73d86270ca80c2..36c516bef46059 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -707,8 +707,9 @@ avd_h264_sps_image_fmt(const struct v4l2_ctrl_h264_sps *sps) * format, which S_FMT rounds up to whole macroblocks, so a picture must fit * in it. */ -VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, - const struct v4l2_ctrl_h264_sps *sps) +VISIBLE_IF_KUNIT int +avd_h264_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps) { u32 width = (sps->pic_width_in_mbs_minus1 + 1) * 16; u32 height = (sps->pic_height_in_map_units_minus1 + 1) * 16 * @@ -733,6 +734,18 @@ VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, if (sps->chroma_format_idc == 2 && sps->bit_depth_luma_minus8 == 2) /* 4:2:2 10 bit would need P210; P010 is too small for its chroma */ return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps_fmt); + +VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps) +{ + int ret = avd_h264_validate_sps_fmt(ctx, sps); + + if (ret) + return ret; if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)) /* no interlaced support */ return -EINVAL; @@ -793,7 +806,14 @@ static int avd_h264_start(struct avd_ctx *ctx) if (!ctrl) return -EINVAL; - ret = avd_h264_validate_sps(ctx, ctrl->p_cur.p_h264_sps); + /* + * Pre-streaming format-negotiation controls (for example Chromium's + * V4L2VideoDecoder::SetExtCtrlsInit) populate chroma format and bit + * depth with flags == 0 before the first frame request supplies the + * parsed SPS. Validate the picture format here; avd_h264_run() enforces + * full avd_h264_validate_sps() (including FRAME_MBS_ONLY) per frame. + */ + ret = avd_h264_validate_sps_fmt(ctx, ctrl->p_cur.p_h264_sps); if (ret) return ret; @@ -1256,8 +1276,18 @@ static void avd_h264_adjust_decoded_fmt(struct avd_ctx *ctx, static int avd_h264_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_H264_SPS) - return avd_h264_validate_sps(ctx, ctrl->p_new.p_h264_sps); + if (ctrl->id == V4L2_CID_STATELESS_H264_SPS) { + struct vb2_queue *vq = + ctx->fh.m2m_ctx ? + v4l2_m2m_get_vq(ctx->fh.m2m_ctx, + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) : + NULL; + + if (vq && vb2_is_streaming(vq)) + return avd_h264_validate_sps(ctx, + ctrl->p_new.p_h264_sps); + return avd_h264_validate_sps_fmt(ctx, ctrl->p_new.p_h264_sps); + } if (ctrl->id == V4L2_CID_STATELESS_H264_PPS) return avd_h264_validate_pps(ctx, ctrl->p_new.p_h264_pps); if (ctrl->id == V4L2_CID_STATELESS_H264_SLICE_PARAMS) diff --git a/drivers/media/platform/apple/avd/avd-hevc-test.c b/drivers/media/platform/apple/avd/avd-hevc-test.c index 907c0c80937082..09eac2716c7aa4 100644 --- a/drivers/media/platform/apple/avd/avd-hevc-test.c +++ b/drivers/media/platform/apple/avd/avd-hevc-test.c @@ -55,6 +55,55 @@ static void avd_hevc_geometry_test(struct kunit *test) KUNIT_EXPECT_EQ(test, avd_hevc_check_sps_geometry(&sps), c->ret); } +/* + * Pre-streaming format negotiation (e.g. Chromium V4L2VideoDecoder::SetExtCtrlsInit) + * supplies coded dimensions, chroma_format_idc and bit depth with zeroed CTB size + * fields. Format validation accepts those while full geometry validation still + * requires 16x16..64x64 CTBs. + */ +static void avd_hevc_sps_fmt_init_test(struct kunit *test) +{ + struct v4l2_ctrl_hevc_sps sps = { + .pic_width_in_luma_samples = 1280, + .pic_height_in_luma_samples = 720, + .chroma_format_idc = 1, + }; + struct avd_dev *dev; + struct avd_ctx *ctx; + + dev = kunit_kzalloc(test, sizeof(*dev), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dev); + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->dev = dev; + ctx->coded_fmt.fmt.pix_mp.width = 1280; + ctx->coded_fmt.fmt.pix_mp.height = 720; + + /* 8-bit and 10-bit 4:2:0 pre-streaming init controls */ + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_hevc_check_sps_geometry(&sps), -EINVAL); + + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 2; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), 0); + + /* Oversized or unsupported formats remain rejected pre-streaming */ + sps.pic_width_in_luma_samples = 1920; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.pic_width_in_luma_samples = 1280; + sps.chroma_format_idc = 3; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 2; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.chroma_format_idc = 1; + sps.bit_depth_luma_minus8 = 4; + sps.bit_depth_chroma_minus8 = 4; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); + sps.bit_depth_luma_minus8 = 2; + sps.bit_depth_chroma_minus8 = 0; + KUNIT_EXPECT_EQ(test, avd_hevc_validate_sps_fmt(ctx, &sps), -EINVAL); +} + struct avd_hevc_tiles_case { const char *desc; bool uniform; @@ -367,6 +416,7 @@ static void avd_hevc_entry_points_sum_test(struct kunit *test) static struct kunit_case avd_hevc_test_cases[] = { KUNIT_CASE_PARAM(avd_hevc_geometry_test, avd_hevc_geometry_gen_params), + KUNIT_CASE(avd_hevc_sps_fmt_init_test), KUNIT_CASE_PARAM(avd_hevc_tiles_test, avd_hevc_tiles_gen_params), KUNIT_CASE(avd_hevc_tiles_array_test), KUNIT_CASE(avd_hevc_no_tiles_test), diff --git a/drivers/media/platform/apple/avd/avd-hevc.c b/drivers/media/platform/apple/avd/avd-hevc.c index f6fe7f7b3d3a33..c72e4371f76ebd 100644 --- a/drivers/media/platform/apple/avd/avd-hevc.c +++ b/drivers/media/platform/apple/avd/avd-hevc.c @@ -1211,10 +1211,11 @@ avd_hevc_check_slices(const struct v4l2_ctrl_hevc_sps *sps, } EXPORT_SYMBOL_IF_KUNIT(avd_hevc_check_slices); -static int avd_hevc_validate_sps(struct avd_ctx *ctx, - const struct v4l2_ctrl_hevc_sps *sps) +VISIBLE_IF_KUNIT int +avd_hevc_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps) { - if (avd_hevc_check_sps_geometry(sps)) + if (!sps->pic_width_in_luma_samples || !sps->pic_height_in_luma_samples) return -EINVAL; if (sps->pic_width_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.width || sps->pic_height_in_luma_samples > ctx->coded_fmt.fmt.pix_mp.height) @@ -1242,6 +1243,16 @@ static int avd_hevc_validate_sps(struct avd_ctx *ctx, return 0; } +EXPORT_SYMBOL_IF_KUNIT(avd_hevc_validate_sps_fmt); + +static int avd_hevc_validate_sps(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps) +{ + if (avd_hevc_check_sps_geometry(sps)) + return -EINVAL; + + return avd_hevc_validate_sps_fmt(ctx, sps); +} static int avd_hevc_alloc_bufs(struct avd_ctx *ctx, struct avd_hevc_bank *bank) { @@ -1750,8 +1761,27 @@ static int avd_hevc_run(struct avd_ctx *ctx) static int avd_hevc_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) { - if (ctrl->id == V4L2_CID_STATELESS_HEVC_SPS) - return avd_hevc_validate_sps(ctx, ctrl->p_new.p_hevc_sps); + if (ctrl->id == V4L2_CID_STATELESS_HEVC_SPS) { + const struct v4l2_ctrl_hevc_sps *sps = ctrl->p_new.p_hevc_sps; + struct vb2_queue *vq = + ctx->fh.m2m_ctx ? + v4l2_m2m_get_vq(ctx->fh.m2m_ctx, + V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) : + NULL; + + /* + * Pre-streaming format negotiation (e.g. Chromium + * SetExtCtrlsInit) populates dimensions, chroma format and bit + * depth while leaving CTB size fields zeroed. Defer the CTB + * geometry check until streaming / avd_hevc_run(). + */ + if ((!vq || !vb2_is_streaming(vq)) && + !sps->log2_min_luma_coding_block_size_minus3 && + !sps->log2_diff_max_min_luma_coding_block_size) + return avd_hevc_validate_sps_fmt(ctx, sps); + + return avd_hevc_validate_sps(ctx, sps); + } return 0; } diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 38b36345148fe0..282b3a460c002f 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -421,8 +421,12 @@ struct v4l2_ctrl_av1_tile_group_entry * avd_av1_copy_tile_group(struct v4l2_ctrl *ctrl, unsigned int *entries); int avd_av1_check_frame_size(const struct v4l2_ctrl_av1_frame *frame, u32 width, u32 height); +int avd_h264_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps); int avd_h264_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); +int avd_hevc_validate_sps_fmt(struct avd_ctx *ctx, + const struct v4l2_ctrl_hevc_sps *sps); size_t avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); int avd_try_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); int avd_s_capture_fmt(struct file *file, void *priv, struct v4l2_format *f); From 6cfa2da1bde85175b6856b3ba0df7788592c7978 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 12:50:01 +0000 Subject: [PATCH 1024/1514] drm/asahi: g17: provide syncobj wait hint on GPU-bound streams Feed::wait_hint() currently returns a syncobj wait uclamp_min hint only while detector.wanted() and applied are true (host-refill-bound streams with an active cpufreq floor). On GPU-bound compute and render streams where idle_sum * 4 < busy_sum, Detector::note() updates bound_until instead of until, leaving wait_hint() returning None. Without the temporary capacity hint during blocking DRM_IOCTL_SYNCOBJ_WAIT, EAS sees a low-duty-cycle waiter and demotes it to an E-core, adding host turnaround latency between back-to-back GPU submissions. Return Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) from Feed::wait_hint() while either (detector.wanted(now) && applied) or detector.bound(now) holds, without waking the cpufreq worker or raising the cpufreq Requests floor for GPU-bound work. Extend LINGER_NS from 8 ms to 20 ms and WAIT_HINT_MS from 8 ms to 20 ms so neither bound() nor the wait hint expires mid-pass across 8-16 ms compute/render passes (covering a full 60 Hz frame), while keeping MAX_REFILL_TICKS at 2 ms (CLOCK_HZ / 500) so 2 ms idle-wake gaps and 60 Hz paced frames continue to reset the streak. Extend the asahi_g17_feed_detector KUnit suite to cover 20 ms bound() linger across 8-16 ms passes and verify 60 Hz paced frames (16.6 ms gap) remain inactive. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/feed.rs | 49 +++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/feed.rs b/drivers/gpu/drm/asahi/g17/feed.rs index 974a926f8d6c3e..442ef38ae14728 100644 --- a/drivers/gpu/drm/asahi/g17/feed.rs +++ b/drivers/gpu/drm/asahi/g17/feed.rs @@ -11,7 +11,7 @@ //! notifier unregistration joins callbacks without holding that mutex. //! M5 requests full CPU capacity only while refill pressure keeps the detector //! active. Sustained demand can renew its deadline indefinitely; withdrawal -//! occurs on a later worker poll, not at an exact eight-millisecond boundary. +//! occurs on a later worker poll, not at an exact twenty-millisecond boundary. use crate::hw::t8140::qos::CLOCK_HZ; use core::{ @@ -40,12 +40,12 @@ const MAX_REFILL_TICKS: u64 = CLOCK_HZ / 500; const _: () = assert!(CLOCK_HZ == crate::hw::t8140::resources::COMMAND_TIMESTAMP_HZ); const STREAK_ON: u32 = 8; const STREAK_MAX: u32 = 64; -const LINGER_NS: u64 = 8_000_000; +const LINGER_NS: u64 = 20_000_000; const POLL_MS: i64 = 2; #[cfg(CONFIG_CPU_FREQ)] const FLOOR_PERCENT: u64 = 50; const WAIT_UTIL_MIN: u32 = 512; -const WAIT_HINT_MS: u32 = 8; +const WAIT_HINT_MS: u32 = 20; #[cfg(CONFIG_CPU_FREQ)] const MAX_POLICIES: usize = 8; @@ -526,10 +526,18 @@ impl Feed { } } + /// Temporary capacity hint for blocking syncobj waits on active GPU streams. + /// + /// Host-refill-bound streams (`wanted`) require an applied cpufreq floor, + /// while GPU-bound streams (`bound`) return the hint without raising the + /// cpufreq floor so EAS keeps the waiter on a P-core across long passes. pub(crate) fn wait_hint(&self) -> Option<(u32, u32)> { - if cfg!(CONFIG_UCLAMP_TASK) - && self.detector.wanted(Self::now()) - && self.applied.load(Ordering::Relaxed) + if !cfg!(CONFIG_UCLAMP_TASK) { + return None; + } + let now = Self::now(); + if (self.detector.wanted(now) && self.applied.load(Ordering::Relaxed)) + || self.detector.bound(now) { Some((WAIT_UTIL_MIN, WAIT_HINT_MS)) } else { @@ -595,9 +603,34 @@ mod detector_tests { let now = run(&detector, 16, CLOCK_HZ / 500, CLOCK_HZ / 25_000); assert!(detector.bound(now)); assert!(!detector.wanted(now)); + // Still bound across an 8-16 ms pass, then expires at the 20 ms linger boundary. + assert!(detector.bound(now + 15_000_000)); assert!(!detector.bound(now + LINGER_NS)); } + #[test] + fn gpu_bound_long_pass_lingers_for_full_frame() { + let detector = Detector::new(); + // 8 ms GPU passes with 1.7 ms host gaps stay GPU-bound without requesting a CPU floor, + // and linger across a 16 ms frame until the 20 ms boundary. + let busy = CLOCK_HZ / 125; + let gap = CLOCK_HZ * 17 / 10_000; + let step_ns = 9_700_000; + let mut start = 1000; + let mut now = 1_000_000; + for _ in 0..16 { + detector.note(start, start + busy, now); + start += busy + gap; + now += step_ns; + } + let last = now - step_ns; + assert!(detector.bound(last)); + assert!(!detector.wanted(last)); + assert!(detector.bound(last + 16_000_000)); + assert!(detector.bound(last + LINGER_NS - 1)); + assert!(!detector.bound(last + LINGER_NS)); + } + #[test] fn refill_gaps_stream_instead() { let detector = Detector::new(); @@ -613,6 +646,10 @@ mod detector_tests { // Each pass starts after a pause of at least the refill limit. let now = run(&detector, 16, CLOCK_HZ / 500, MAX_REFILL_TICKS); assert!(!detector.bound(now) && !detector.wanted(now)); + // 60 Hz paced frames (16.6 ms gap) keep resetting the streak. + let detector = Detector::new(); + let now = run(&detector, 16, CLOCK_HZ / 500, CLOCK_HZ * 166 / 10_000); + assert!(!detector.bound(now) && !detector.wanted(now)); // Fewer back-to-back passes than the streak needs. let detector = Detector::new(); let now = run(&detector, u64::from(STREAK_ON) - 1, CLOCK_HZ / 500, 0); From 7cf06de21f7699df115bdd6c6bbf8f0b473a813d Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:26:33 +0000 Subject: [PATCH 1025/1514] drm/asahi: g17: trim compute completion critical-path locks and batch clear Reduce per-completion overhead on G17 compute retirement without moving sleeping locks or VM pin release into interrupt context: 1. In Completion::release_healthy() and complete_with_compute(), skip the unused render-lease mutex on compute commands, move feed.note_pass() and feed.note_work() spinlocks after output.finish() signals the exported fence, and return whether healthy pins were already released so Deferred::Retired and Deferred::RetiredCompute skip redundant vm_job and render mutex re-acquisitions in release_after_retirement(). Keep tools/asahi/g17-quarantine-drain-tests.py in sync with the updated Completion helper signature. 2. Track touched QIDs in retirement::Batch (touched_slots and touched_frontiers u128 bitmasks) so Batch::clear() resets only active QIDs instead of zeroing 3 KiB of slots and frontier arrays on every completion, and extend the asahi_g17_completion_index KUnit suite to cover multi-batch clear reuse. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/completion.rs | 46 +++++++++++------- .../drm/asahi/g17/queue/compute/retirement.rs | 47 ++++++++++++++++++- tools/asahi/g17-quarantine-drain-tests.py | 11 +++-- 3 files changed, 81 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a4..ddaf0d9cb7ba58 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -813,14 +813,17 @@ impl Completion { if let Some(sources) = &self.sources { sources.release(); } - drop(self.render.lock().take()); + if !self.is_compute { + drop(self.render.lock().take()); + } drop(self.vm_job.lock().take()); } /// Exact retirement permits the physical lease and VM pin to be released /// before waking userspace. A failure fence alone never establishes this. + /// Returns true if this call claimed signalling and released healthy pins. #[track_caller] - pub(crate) fn complete(&self, result: Result<[u64; 4]>) { + pub(crate) fn complete(&self, result: Result<[u64; 4]>) -> bool { // M5 compute feeds the refill detector only from its exact execution record // (RetiredCompute); M5 compute is the compute without pooled timestamps. let execution = if self.is_compute && self.compute.is_none() { @@ -828,20 +831,24 @@ impl Completion { } else { result.as_ref().ok().map(|ticks| [ticks[0], ticks[1]]) }; - self.complete_with_compute(result, execution); + self.complete_with_compute(result, execution) } /// Compute feedback is separate from public timestamps, which may contain /// a synthesized retirement envelope when the execution record is absent. #[track_caller] - fn complete_with_compute(&self, mut result: Result<[u64; 4]>, compute: Option<[u64; 2]>) { + fn complete_with_compute( + &self, + mut result: Result<[u64; 4]>, + compute: Option<[u64; 2]>, + ) -> bool { if result.is_ok() { if let Err(error) = self.check_source_inputs() { result = Err(error); } } if self.signalled.swap(true, Ordering::AcqRel) { - return; + return false; } if result.is_ok() && self.interrupted() { result = Err(ECANCELED); @@ -856,6 +863,15 @@ impl Completion { self.usage.add(Engine::Fragment, ticks[2], ticks[3], hz); } } + if let Err(error) = result { + // Spared work cancelled after another VM's recovery is not this client's device loss. + self.report(error); + } + self.release_healthy(); + self.signal_terminal(result); + self.output.finish(result); + // Feed detector and busy-run tracking are internal host heuristics: update them + // after signalling the fence so their spinlocks stay off the wakeup critical path. if let (Some(feed), Ok(ticks)) = (&self.feed, &result) { // Compute reports its dispatch envelope in the first pair, a // render its fragment pass in the second. @@ -871,13 +887,7 @@ impl Completion { feed.note_work(self.context_id, start.unwrap_or(0), ticks[1].max(ticks[3])); } } - if let Err(error) = result { - // Spared work cancelled after another VM's recovery is not this client's device loss. - self.report(error); - } - self.release_healthy(); - self.signal_terminal(result); - self.output.finish(result); + true } /// A rejected, never-published command cannot poison the VM for contention. @@ -941,18 +951,20 @@ impl Deferred { pub(crate) fn finish(self) { match self { Self::RetiredCompute(completion, ticks, execution) => { - completion.complete_with_compute(Ok(ticks), execution); - completion.release_after_retirement(); + if !completion.complete_with_compute(Ok(ticks), execution) { + completion.release_after_retirement(); + } } Self::Retired(completion, result) => { - completion.complete(result); // An earlier failure may already have signalled this fence while // retaining the pin. Retirement is a separate release witness. - completion.release_after_retirement(); + if !completion.complete(result) { + completion.release_after_retirement(); + } } Self::Drained(completion, result) => { completion.release_after_retirement(); - completion.complete(result); + let _ = completion.complete(result); } Self::FailedOwned(completion, error) => completion.fail_while_owned(error), Self::Unpublished(completion, error) => completion.fail_unpublished(error), diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs b/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs index e6d70105dae160..15a98a80ba482f 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute/retirement.rs @@ -292,10 +292,14 @@ pub(crate) struct Batch { /// ([`NO_FRONTIER`] for a QID without a staged queue). A record at or past it belongs /// to a command published during the scan, which a later batch stages. frontiers: [u64; QIDS], + /// Bitmasks of QIDs touched in `slots` and `frontiers` so `clear()` touches only active QIDs. + touched_slots: u128, + touched_frontiers: u128, } const NO_FRONTIER: u64 = u64::MAX; const KICK_MASK: u64 = (1 << 40) - 1; +const _: () = assert!(QIDS <= 128); impl Batch { pub(crate) fn new() -> Result { @@ -311,19 +315,34 @@ impl Batch { unobserved: 0, covered: 0, frontiers: [NO_FRONTIER; QIDS], + touched_slots: 0, + touched_frontiers: 0, }) } pub(crate) fn clear(&mut self) { self.requests.clear(); - self.slots.fill((0, 0)); + let mut slots = self.touched_slots; + while slots != 0 { + let qid = slots.trailing_zeros() as usize; + slots &= slots - 1; + self.slots[qid] = (0, 0); + } + self.touched_slots = 0; self.open = None; self.unobserved = 0; self.covered = 0; - self.frontiers.fill(NO_FRONTIER); + let mut frontiers = self.touched_frontiers; + while frontiers != 0 { + let qid = frontiers.trailing_zeros() as usize; + frontiers &= frontiers - 1; + self.frontiers[qid] = NO_FRONTIER; + } + self.touched_frontiers = 0; } /// Records the first kick `qid`'s queue had not yet published when this batch was staged. pub(crate) fn stage_frontier(&mut self, qid: u8, next: u64) -> Result { *self.frontiers.get_mut(usize::from(qid)).ok_or(EINVAL)? = next & KICK_MASK; + self.touched_frontiers |= 1u128 << qid; Ok(()) } /// A record of `qid` with `kick` names a command published after this batch was staged. @@ -372,6 +391,7 @@ impl Batch { .map_err(|_| ENOSPC)?; *self.heads.get_mut(bucket).ok_or(EIO)? = index; *slot = (start, slot.1 + 1); + self.touched_slots |= 1u128 << ticket.qid; self.open = Some(ticket.qid); self.unobserved += 1; self.covered += usize::from(covered); @@ -813,4 +833,27 @@ mod index_tests { assert!(batch.fold_reader(|word| Ok(other[word])).unwrap()); assert!(!batch.complete() && !batch.covered_pending()); } + #[test] + fn clear_resets_touched_slots_and_frontiers_across_batches() { + let mut batch = Batch::new().unwrap(); + let low = ticket(0, 11, 0x1000); + let high = ticket((QIDS - 1) as u8, 22, 0x2000); + batch.stage_frontier(0, 12).unwrap(); + batch.stage_frontier((QIDS - 1) as u8, 23).unwrap(); + batch.request(&low, true).unwrap(); + batch.request(&high, false).unwrap(); + batch.clear(); + assert!(batch.complete() && !batch.covered_pending()); + assert_eq!(batch.touched_slots, 0); + assert_eq!(batch.touched_frontiers, 0); + assert!(!batch.published_after_staging(0, 12)); + assert!(!batch.published_after_staging(QIDS - 1, 23)); + // Re-staging the same QIDs with new kicks succeeds cleanly after clear(). + let next = ticket((QIDS - 1) as u8, 25, 0x3000); + batch.request(&next, true).unwrap(); + let words = record(&next, [50, 60]); + assert!(batch.fold_reader(|word| Ok(words[word])).unwrap()); + assert!(batch.complete()); + assert_eq!(batch.take(&next).unwrap().map(|obs| obs.timestamps), Some([50, 60])); + } } diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 53204a179edd66..395bdc441f16c5 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -73,7 +73,7 @@ def fixture(): 'pair.retire(None, generation, state, host,', 'pair.fail_after_observation(packet, error, host,') # A first signal gives the lease back without ending a quarantine (the `complete` mock). ordered(item(completion, 'fn complete_with_compute('), - 'if self.signalled.swap(true, Ordering::AcqRel) {\n return;\n }', + 'if self.signalled.swap(true, Ordering::AcqRel) {\n return false;\n }', 'self.release_healthy();') # The drain release runs once the drain proof, event service and accounting passed. ordered(item(settle, 'fn drain_render_slot('), 'pair.firmware_drained(host)', 'self.service_runtime_events(deferred)', @@ -175,6 +175,7 @@ def fixture(): sources: Option>, vm_job: Mutex>, render: Mutex>, + is_compute: bool, signalled: AtomicBool, accepted: AtomicBool, spared: AtomicBool, @@ -188,13 +189,14 @@ def fixture(): fn report(&self, _: Error) {} fn signal_terminal(&self, result: Result<[u64; 4]>) { *self.result.lock() = Some(result); } /// The lease handling of the real complete_with_compute (checked against it above). - fn complete(&self, result: Result<[u64; 4]>) { self.complete_with_compute(result, None) } - fn complete_with_compute(&self, result: Result<[u64; 4]>, _: Option<[u64; 2]>) { + fn complete(&self, result: Result<[u64; 4]>) -> bool { self.complete_with_compute(result, None) } + fn complete_with_compute(&self, result: Result<[u64; 4]>, _: Option<[u64; 2]>) -> bool { if self.signalled.swap(true, Ordering::AcqRel) { - return; + return false; } self.release_healthy(); self.signal_terminal(result); + true } ''' + command + '\n}\n' + item(completion, 'pub(crate) enum Deferred {') + '\n' + item(completion, 'impl Deferred {') + r''' @@ -290,6 +292,7 @@ def fixture(): let completion = Arc::new(Completion { status: Arc::new(Status), output: Output, sources: Some(Arc::new(Sources)), vm_job: Mutex::new(Some(guard)), render: Mutex::new(Some(lease)), + is_compute: false, signalled: AtomicBool::new(false), accepted: AtomicBool::new(true), spared: AtomicBool::new(false), result: Mutex::new(None), }); From c628edbfd5fdfa5c244c010a7150c49b9896adaf Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Tue, 24 Nov 2026 03:00:35 -0500 Subject: [PATCH 1026/1514] aurora-sep: mesa-m3: admit system Mesa on the 7.3 and G15 GPU drivers The system Mesa admission required the render node's platform driver to be "asahi". That name is not the only one the M3 GPUs get: - On the 7.3 kernels the driver is "aurora" (2d76bcead7cc); "asahi" is only its module alias. On an M3 Air running 7.3.0, a real SDDM to uwsm Hyprland login with /etc/mesa-m3/disable: the admission stopped at the driver check, and the journal showed decision=inactive with no admission line. - A kernel built with the native G15 backend (CONFIG_DRM_ASAHI_G15, set in asahi.config) binds the T6030 to that backend's own platform driver: "asahi-g15" on 7.2.11, "aurora-g15" on 7.3. The admission refused every M3 Pro on those kernels. On those three drivers the refusal only changed the record. The software fallback matches only "asahi", so those sessions already kept the system Mesa (fallback=none). What was missing is the state file's and journal's admission detail ("system Mesa on /usr admits ..."). Accept "aurora", "aurora-g15", "asahi" and "asahi-g15" in _mm3_system_admit() only. mesa-m3-system-check still decides whether /usr drives the GPU. The software fallback (_mm3_node_open()) and the render-node udev rule stay keyed on "asahi", and the hook's header comment and the rule's comment say so. They exist because the pre-7.3 kernels' legacy M3 path refuses the system Mesa. On "aurora" the system Mesa drives the M3 Air's GPU (that login rendered "Apple M3 (G15G C0)" from /usr). The helper's J516S validation in SYSTEM-HANDOFF.md, on a 7.2.11 kernel named "-g15", returned "Apple M3 Pro (G15S B1)" from /usr. Widening them would move those sessions from hardware rendering to software, and lock the node to the render group. No M3 Pro has run 7.3 yet. The session test admits the system Mesa with "aurora" on both SoCs and with "asahi-g15" and "aurora-g15" on the T6030 (these cases fail on the previous commit). It also pins that nothing falls back to software on those drivers: a failed admission, near-miss "aurora-x" and "asahi-g15x" drivers, the default T8122 session (experimental) and a T6030 the /opt/mesa-m3 profile cannot use. pkgrel goes to 9 so an upgrade replaces the installed -8, and the PKGBUILD checksums follow the hook and the rule's comment. SYSTEM-HANDOFF.md now says that the software fallback and the mesa_m3=off recovery apply to "asahi" nodes only. Signed-off-by: Scott Jones --- .../mesa-m3/72-mesa-m3-render-node.rules | 4 +- tools/aurora-sep/recipes/mesa-m3/PKGBUILD | 6 +-- .../recipes/mesa-m3/mesa-m3-session-env | 32 ++++++++--- .../recipes/mesa-m3/tests/SYSTEM-HANDOFF.md | 17 +++--- .../recipes/mesa-m3/tests/test-session-env.sh | 54 ++++++++++++++++++- 5 files changed, 95 insertions(+), 18 deletions(-) diff --git a/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules b/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules index e3e12617f58a0c..b31ca3e18a8860 100644 --- a/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules +++ b/tools/aurora-sep/recipes/mesa-m3/72-mesa-m3-render-node.rules @@ -6,6 +6,8 @@ # compositor started without the M3 Mesa that renders through an EGL device on # such a node, such as the SDDM greeter's Hyprland (user sddm), stops at start. # Without access to the node it renders in software. Other Apple GPUs are not -# matched. +# matched. Neither are the 7.3 kernels' "aurora" driver and the native G15 +# backend's "asahi-g15" and "aurora-g15": there the system Mesa is not +# refused, so the node stays as the kernel and system rules set it. SUBSYSTEM=="drm", KERNEL=="renderD*", DRIVERS=="asahi", ATTR{device/of_node/compatible}=="apple,agx-t6030", GROUP="render", MODE="0660" SUBSYSTEM=="drm", KERNEL=="renderD*", DRIVERS=="asahi", ATTR{device/of_node/compatible}=="apple,agx-t8122", GROUP="render", MODE="0660" diff --git a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD index 43a280e01d367b..a4d4e4ec12c3ee 100644 --- a/tools/aurora-sep/recipes/mesa-m3/PKGBUILD +++ b/tools/aurora-sep/recipes/mesa-m3/PKGBUILD @@ -10,7 +10,7 @@ # No profile selection substitutes another Mac's firmware or calibration. pkgname=mesa-m3 pkgver=26.1.4.m3.2 -pkgrel=8 +pkgrel=9 _commit=7ff89a4da387bd561b78efd5f09c98ca8ae18538 pkgdesc="Mesa in /opt/mesa-m3 for the M3 Pro (G15S) and M3 (G15G) GPUs; used by uwsm sessions on T6030, and on T8122 when opted in" arch=('aarch64') @@ -85,7 +85,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '10abda78df16e650a77443f50cc46a15e418c42d4d9680c6a61616b232c9bdef' '6c98fab6f9d70449bd7f5258c34eac773836908e060ce5bef86dc5b0ce595e61' '826016665cd0424a614b67add921c0c79c3c698a4d104ea5712518449b75f27c' - 'e94accb088b3a49f16bc6f3bbefd9577d65e9481e303ae99a0f725f140e9bb6a' + '93f93d2333ce273137e61be438914db84c9a970428efa6f7febae2c39ec50530' '6144af8b2e0f04ea615e8c4149e69c45ac49e630c46b2a58f0d1095d977798b2' '530948fc1a124de21c030a497e2ef5351742ba4ad4653484fe30fd1697ad7141' '644cf4a5ab57b7badec75843e2899b68d41490c4851d6885227180d6090c25ea' @@ -93,7 +93,7 @@ sha256sums=('7ed24969985dce91f089d34dbe1c55cbcb8c95765e3e5bc0f268d27fbead2222' '34f8bb3fa505718dab176b6283dde0d4de9cae4c3928922bca18e6052434bca7' '04fae9bf32a09a574b6ed9ab9d7afb97340df252b9269ed789303e8561a61a21' '96c3101c15c73d26cd3086bc8ac4e8eb35d42300d495ca0ffd2bd03960ef3332' - '9c7c3050d3ec15fce80a6e59d099567b396f1844a43695aa4377e02ac696f566' + '807be84fcaf6e68cb7f787886d070ac9778c778127c05267060872e6cfe3cf3b' '2a15cfdbc160b78e5a3a8e99d5898d40a54db28592f1a4ce04a600990a731f87' '7eaae7de828e15208fccc84db2b910f38bb1288176419f7af7f4675b5c542ce4' 'c888e9dce99e8379aa21e9c5895cbe1b7e879a9319bca144193eddc66f9d4051' diff --git a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env index 6348c4be48ab83..468ff75bfd4d4b 100644 --- a/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env +++ b/tools/aurora-sep/recipes/mesa-m3/mesa-m3-session-env @@ -59,10 +59,16 @@ # active all passed: the session uses /opt/mesa-m3 # M1, M2, the M3 Max and anything else are left alone. # -# When it does not use /opt/mesa-m3 but an M3 render node is there and this -# user can open it, the system Mesa would be refused by the kernel (it is not -# M3-aware), and a compositor that renders through an EGL device on that node -# (Hyprland) would stop at start. For every inactive reason except user-setup +# When it does not use /opt/mesa-m3 but an M3 render node of the pre-7.3 +# "asahi" driver is there and this user can open it, the system Mesa would be +# refused by the kernel (it is not M3-aware), and a compositor that renders +# through an EGL device on that node (Hyprland) would stop at start. On the +# 7.3 kernels' "aurora" driver, and on the native G15 backend's "asahi-g15" +# (7.2) or "aurora-g15" (7.3) driver that a kernel built with +# CONFIG_DRM_ASAHI_G15 binds to the T6030, the system Mesa is not refused, so +# none of this applies there: the session keeps it (fallback=none), whatever +# the reason. +# For every inactive reason on an "asahi" node except user-setup # it therefore exports LIBGL_ALWAYS_SOFTWARE=1 (and MESA_M3_FALLBACK=software, # which marks it as this hook's): the session renders in software. For # user-setup it exports nothing: the session's own Mesa setup, which it uses, @@ -73,7 +79,8 @@ # display, kernel-log, user-setup and same-boot attempt checks pass and # mesa-m3-system-check admits /usr, the session keeps system Mesa # (fallback=none, no new attempt). The whole check runs in its own sh and is -# refused after 20 seconds. mesa_m3=off stays on the software fallback. +# refused after 20 seconds. mesa_m3=off stays on the software fallback (on an +# "asahi" node). # # Each login writes /run/user//mesa-m3-session.state (atomically, 0644, # key=value lines, first line schema=aurora.mesa-m3-session/2) and logs one @@ -307,7 +314,10 @@ _mm3_25g83_board() { # _mm3_node_open ROOT: this is a T6030 or T8122 with a render node of its # asahi M3 GPU (among any others) that this user can open: the system Mesa -# would be refused on it. +# would be refused on it. Only the pre-7.3 "asahi" driver counts: on the +# 7.3 "aurora" driver and the G15 backend's "asahi-g15" and "aurora-g15" the +# system Mesa is not refused, so a session that does not use /opt/mesa-m3 +# keeps it instead of falling back to software. _mm3_node_open() { _mm3_soc=$(_mm3_soc_of "$1") [ -n "$_mm3_soc" ] || return 1 @@ -421,8 +431,16 @@ _mm3_system_admit() { _mm3_node=$_mm3_n done [ "$_mm3_nodes" -eq 1 ] || return 1 + # The GPU's platform driver is "asahi" before 7.3 and "aurora" from 7.3 on + # (2d76bcead7cc; "asahi" is then only its module alias). A kernel built + # with the native G15 backend (CONFIG_DRM_ASAHI_G15) binds the T6030 to + # that backend's own driver instead: "asahi-g15" on 7.2, "aurora-g15" on + # 7.3. mesa-m3-system-check below still decides whether /usr drives it. _mm3_drv=$(basename "$(readlink -f "$_mm3_node/device/driver" 2>/dev/null)" 2>/dev/null) - [ "$_mm3_drv" = asahi ] || return 1 + case "$_mm3_drv" in + aurora | aurora-g15 | asahi | asahi-g15) ;; + *) return 1 ;; + esac tr '\0' '\n' 2>/dev/null < "$_mm3_node/device/of_node/compatible" | grep -qx "apple,agx-$_mm3_chip" || return 1 _mm3_dev="$1/dev/dri/${_mm3_node##*/}" [ -r "$_mm3_dev" ] && [ -w "$_mm3_dev" ] || return 1 diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md index cb85c0ac381f54..c476787136ce07 100644 --- a/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md +++ b/tools/aurora-sep/recipes/mesa-m3/tests/SYSTEM-HANDOFF.md @@ -6,7 +6,7 @@ system driver worked. The legacy package owns this hook, so the native Mesa package must not overwrite it or add an unconditional late unset. This change allows a file opt-out on any T8122 or T6030 board to leave system -Mesa selected. The device tree must name exactly one board and one SoC. It requires one accessible Asahi render node, the matching +Mesa selected. The device tree must name exactly one board and one SoC. It requires one accessible render node of the Apple GPU driver ("aurora" from the 7.3 kernels on, "asahi" before; on a kernel built with the native G15 backend the T6030's is "aurora-g15" or "asahi-g15"), the matching native display, a readable healthy kernel journal, no unmatched same-boot legacy login attempt, and no conflicting environment or later user settings. A bounded helper then opens the exact EGL device using only `/usr` libraries @@ -28,8 +28,11 @@ returns within a 20-second timeout, so a stalled journal, home directory or scanner refuses instead of holding the login. The helper keeps its own 5-second timeout. -A failed check keeps the existing software fallback. `mesa_m3=off` and -`nomodeset` remain recovery choices. Other SoCs remain outside this system +On an "asahi" node a failed check keeps the existing software fallback, and +`mesa_m3=off` and `nomodeset` remain recovery choices. On an "aurora", +"aurora-g15" or "asahi-g15" node there is no software fallback: the session +keeps system Mesa whether the check passes or fails, and only the state and +journal detail differ. Other SoCs remain outside this system handoff. Explicit legacy profile selection is unchanged. No opt-in flags, attempt records or success markers are added or removed. Only the exact software-fallback pair previously exported by this hook can @@ -40,9 +43,11 @@ The helper proves only that the system EGL device and a context open. It does not allocate GBM buffers, render or present. A system-Mesa login that passes admission and then fails later is not recorded: this path writes no attempt, so the legacy success-marker check cannot see it, and the next login is -admitted again. Recover with `mesa_m3=off` on the kernel command line or by -removing the opt-out file. Separate system-Mesa attempt and success markers -would make that recovery automatic. +admitted again. On an "asahi" node, recover with `mesa_m3=off` on the kernel +command line or by removing the opt-out file. Separate system-Mesa attempt +and success markers would make that recovery automatic. On an "aurora", +"aurora-g15" or "asahi-g15" node this hook offers no recovery: both leave the +session on system Mesa. Run the host checks from this directory (a writable TMPDIR may be needed): diff --git a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh index 30a577cbf2299c..7e2258a6707820 100755 --- a/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh +++ b/tools/aurora-sep/recipes/mesa-m3/tests/test-session-env.sh @@ -678,7 +678,7 @@ system_root() { air) _hd="apple,j613 apple,t8122"; _hg=$G15G ;; *) _hd="apple,j516s apple,t6030"; _hg=$G15S ;; esac - _hr=$(mkroot "handoff-$1" "$_hd" "$_hg" yes 1 yes) + _hr=$(mkroot "handoff-$1" "$_hd" "$_hg" yes 1 yes "${3:-asahi}") mkdir -p "$_hr/etc/mesa-m3" : > "$_hr/etc/mesa-m3/disable" cat > "$_hr/opt/mesa-m3/libexec/mesa-m3-system-check" <<'H' @@ -748,6 +748,58 @@ if [ "$(cat "$HRA/opt/mesa-m3/libexec/system-check.args")" = "$(printf '/dev/dri else echo 'FAIL handoff: helper argv/environment'; fail=1; fi HRP=$(system_root root-optout pro) handoff "$HRP" none yes +# The 7.3 kernels name the GPU driver "aurora" ("asahi" is only a module alias). +# The admission accepts it on both SoCs. +for soc in air pro; do + HR=$(system_root "aurora-$soc" "$soc" aurora) + handoff "$HR" none yes +done +# On "aurora" the system Mesa is not refused, so no session falls back to +# software there: not a failed admission, not the default T8122 session +# (experimental), not a T6030 the /opt/mesa-m3 profile cannot use. A driver +# that only starts with "aurora" is not admitted. +aurora_state() { # NAME ROOT WANT_REASON + _ao=$(env -i PATH="$T/bin:/usr/bin:/bin" HOME="$T/home" FAKE_LOG="$T/log" \ + XDG_CURRENT_DESKTOP=Hyprland "$TSH" -c ' + MESA_M3_SESSION_ENV_NO_RUN=1 . "$1" + mesa_m3_session_env "$2" + printf "software=%s\nmarker=%s\n" "${LIBGL_ALWAYS_SOFTWARE:-}" "${MESA_M3_FALLBACK:-}" + cat "$2/run/user/$(id -u)/mesa-m3-session.state" + ' sh "$ENVFILE" "$2") + if printf '%s\n' "$_ao" | grep -qx 'fallback=none' && + printf '%s\n' "$_ao" | grep -qx 'software=' && + printf '%s\n' "$_ao" | grep -qx 'decision=inactive' && + printf '%s\n' "$_ao" | grep -qx "reason=$3" && + ! printf '%s\n' "$_ao" | grep -q 'detail=.*system Mesa on /usr admits'; then + echo "ok $1: reason=$3 fallback=none, nothing exported" + else + echo "FAIL $1: want reason=$3 fallback=none and no admission: $_ao"; fail=1 + fi +} +HR=$(system_root aurora-probe-fail pro aurora) +: > "$HR/opt/mesa-m3/libexec/system-check.fail" +aurora_state aurora-probe-fail "$HR" opt-out +HR=$(system_root aurora-x pro aurora-x) +aurora_state aurora-x "$HR" opt-out +HR=$(mkroot aurora-default-air "apple,j613 apple,t8122" "$G15G" yes 1 yes aurora) +aurora_state aurora-default-air "$HR" experimental +HR=$(mkroot aurora-default-pro "apple,j516s apple,t6030" "$G15S" yes 1 yes aurora) +aurora_state aurora-default-pro "$HR" no-gpu +# A kernel built with the native G15 backend binds the T6030 to that backend's +# own driver: "asahi-g15" on 7.2, "aurora-g15" on 7.3. The admission accepts +# both, a failed admission there does not fall back to software, and neither +# does the default session. A near-miss name is not admitted. +for drv in asahi-g15 aurora-g15; do + HR=$(system_root "$drv" pro "$drv") + handoff "$HR" none yes + HR=$(system_root "$drv-probe-fail" pro "$drv") + : > "$HR/opt/mesa-m3/libexec/system-check.fail" + aurora_state "$drv-probe-fail" "$HR" opt-out + HR=$(mkroot "$drv-default-pro" "apple,j516s apple,t6030" "$G15S" yes 1 yes "$drv") + aurora_state "$drv-default-pro" "$HR" no-gpu +done +HR=$(system_root asahi-g15x pro asahi-g15x) +aurora_state asahi-g15x "$HR" opt-out handoff "$HRP" none yes LIBGL_ALWAYS_SOFTWARE=1 MESA_M3_FALLBACK=software for mode in fail sleep; do HR=$(system_root "probe-$mode" pro) From 7c49bb1eb91d35bbd916361ffb58692f4a8208d9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 01:55:30 +1100 Subject: [PATCH 1027/1514] media: apple: avd: narrow H.264 init SPS gate and update host harness Address review feedback and CI host-tests on pre-streaming SPS validation: - Narrow H.264 pre-streaming FRAME_MBS_ONLY deferral to minimal init SPS controls (!flags && !pic_width_in_mbs_minus1 && !pic_height_in_map_units_minus1) via avd_h264_validate_sps_ctrl(), keeping populated interlaced SPS structs rejected upfront with -EINVAL in both avd_h264_try_ctrl() and avd_h264_start() so FFmpeg/GStreamer fall back to software decode cleanly. - Extend avd_sps_fmt_init_test in avd-h264-test.c to cover pre-streaming vs streaming ctrl validation and populated interlaced SPS rejection. - Extract avd_h264_validate_sps_fmt and avd_hevc_validate_sps_fmt in drivers/media/platform/apple/avd/tests/program-test.py so avd-codec-tail-tests builds cleanly. Signed-off-by: Ryan Murray --- .../media/platform/apple/avd/avd-h264-test.c | 23 ++++++++++++- drivers/media/platform/apple/avd/avd-h264.c | 33 ++++++++++++++----- drivers/media/platform/apple/avd/avd.h | 3 ++ .../platform/apple/avd/tests/program-test.py | 4 ++- 4 files changed, 53 insertions(+), 10 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index b39984550d092b..0ffc5ac66d15ba 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -184,16 +184,37 @@ static void avd_sps_fmt_init_test(struct kunit *test) /* 8-bit and 10-bit 4:2:0 pre-streaming init controls */ KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, true), -EINVAL); KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); sps.bit_depth_luma_minus8 = 2; sps.bit_depth_chroma_minus8 = 2; KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), 0); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, true), -EINVAL); KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + /* Populated interlaced SPS must still be rejected pre-streaming */ + sps = (struct v4l2_ctrl_h264_sps) { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = 79, + .pic_height_in_map_units_minus1 = 22, + }; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); + sps.pic_width_in_mbs_minus1 = 0; + sps.pic_height_in_map_units_minus1 = 0; + sps.flags = V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); + /* Unsupported formats remain rejected pre-streaming */ - sps.chroma_format_idc = 3; + sps = (struct v4l2_ctrl_h264_sps) { + .chroma_format_idc = 3, + .bit_depth_luma_minus8 = 2, + .bit_depth_chroma_minus8 = 2, + }; KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_ctrl(ctx, &sps, false), -EINVAL); sps.chroma_format_idc = 2; KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); sps.chroma_format_idc = 1; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 36c516bef46059..89c12e5fb8f524 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -754,6 +754,24 @@ VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, } EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps); +static bool avd_h264_sps_is_fmt_init(const struct v4l2_ctrl_h264_sps *sps) +{ + return !sps->flags && !sps->pic_width_in_mbs_minus1 && + !sps->pic_height_in_map_units_minus1; +} + +VISIBLE_IF_KUNIT int +avd_h264_validate_sps_ctrl(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps, + bool streaming) +{ + if (!streaming && avd_h264_sps_is_fmt_init(sps)) + return avd_h264_validate_sps_fmt(ctx, sps); + + return avd_h264_validate_sps(ctx, sps); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_validate_sps_ctrl); + /* Free the slices held for one bank's picture. */ static void avd_h264_drop_bank_slices(struct avd_ctx *ctx, struct avd_bank *bank) { @@ -809,11 +827,12 @@ static int avd_h264_start(struct avd_ctx *ctx) /* * Pre-streaming format-negotiation controls (for example Chromium's * V4L2VideoDecoder::SetExtCtrlsInit) populate chroma format and bit - * depth with flags == 0 before the first frame request supplies the - * parsed SPS. Validate the picture format here; avd_h264_run() enforces - * full avd_h264_validate_sps() (including FRAME_MBS_ONLY) per frame. + * depth with flags and dimensions zeroed before the first frame + * request supplies the parsed SPS. Allow that minimal init control + * here while rejecting populated interlaced SPS structs upfront; + * avd_h264_run() enforces full avd_h264_validate_sps() per frame. */ - ret = avd_h264_validate_sps_fmt(ctx, ctrl->p_cur.p_h264_sps); + ret = avd_h264_validate_sps_ctrl(ctx, ctrl->p_cur.p_h264_sps, false); if (ret) return ret; @@ -1283,10 +1302,8 @@ static int avd_h264_try_ctrl(struct avd_ctx *ctx, struct v4l2_ctrl *ctrl) V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) : NULL; - if (vq && vb2_is_streaming(vq)) - return avd_h264_validate_sps(ctx, - ctrl->p_new.p_h264_sps); - return avd_h264_validate_sps_fmt(ctx, ctrl->p_new.p_h264_sps); + return avd_h264_validate_sps_ctrl(ctx, ctrl->p_new.p_h264_sps, + vq && vb2_is_streaming(vq)); } if (ctrl->id == V4L2_CID_STATELESS_H264_PPS) return avd_h264_validate_pps(ctx, ctrl->p_new.p_h264_pps); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 282b3a460c002f..07b01c86fa6c70 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -425,6 +425,9 @@ int avd_h264_validate_sps_fmt(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); int avd_h264_validate_sps(struct avd_ctx *ctx, const struct v4l2_ctrl_h264_sps *sps); +int avd_h264_validate_sps_ctrl(struct avd_ctx *ctx, + const struct v4l2_ctrl_h264_sps *sps, + bool streaming); int avd_hevc_validate_sps_fmt(struct avd_ctx *ctx, const struct v4l2_ctrl_hevc_sps *sps); size_t avd_h264_start_slices(const struct v4l2_ctrl_h264_sps *sps); diff --git a/drivers/media/platform/apple/avd/tests/program-test.py b/drivers/media/platform/apple/avd/tests/program-test.py index a0ee9b1d3b95de..77db961856499d 100755 --- a/drivers/media/platform/apple/avd/tests/program-test.py +++ b/drivers/media/platform/apple/avd/tests/program-test.py @@ -545,12 +545,14 @@ def prepare_regressions(out): pre = pre.replace('unsigned int bank; };', 'unsigned int bank; size_t grey_chroma_offset; bool grey_chroma_10bit; };') pre += 'enum vb2_buffer_state { VB2_BUF_STATE_DONE, VB2_BUF_STATE_ERROR };\n' code = pre + helpers + inst + h264 - for name in ('avd_h264_alloc_bufs', 'avd_h264_validate_sps', 'avd_h264_validate_pps', + for name in ('avd_h264_alloc_bufs', 'avd_h264_validate_sps_fmt', 'avd_h264_validate_sps', + 'avd_h264_validate_pps', 'avd_h264_validate_slice', 'avd_h264_drop_bank_slices', 'avd_h264_pick_bank', 'avd_h264_abort_picture', 'avd_h264_refs_valid', 'avd_h264_done'): code += function(source, name) code += function((ROOT / 'avd-backend-open.c').read_text(), 'avd_open_build_program') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_check_sps_geometry') + code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps_fmt') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps') code += RUN_FIXTURE + function(source, 'avd_h264_sps_image_fmt') + function(source, 'avd_h264_run') + RUN_MAIN dest = out / 'prepare.c' From 1b655c9f271fc2e4e227cf3ba542f7e6d4b06d17 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:02:24 +1100 Subject: [PATCH 1028/1514] drm/apple: audio: open a replaced classic service afresh, wait only on a refusal Review fixes for the firmware-27 classic audio path: - A classic Open belongs to the instance it was made on: clear is_open when the service is replaced or removed, so the successor's connect opens it and connects the card (it skipped both). - Firmware 27's classic command table no longer depends on CONFIG_DRM_APPLE_DCP_T6030_AUDIO: without it, the J473 (T8112) failed its audio with -ENODEV. - dcp_pcm_open() waits for a successor only when the firmware refused the read (-EINVAL, a non-zero retcode), not on a missing service, a timeout or no memory, and the wait is interruptible. asrv->srv and asrv->gen are written with WRITE_ONCE, as the wait reads them without the lock. - The firmware refuses an Open on an instance it is replacing (each resume on the J473's DP processor, 0xe00002d7), and the successor's connect opens it within AV_AUDIOSRV_REPLACE_MS. Judge a refused classic Open then, in an owner delayed work: debug if the service was opened again or removed, the old error otherwise. The work joins the owner-work lifecycle (flush, disable on drain, enable on restart). Host test: a non-refusal error with a successor published still fails the open without a second read; the wait-any mutation is killed. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 6 +- drivers/gpu/drm/apple/av-lifetime-test.c | 1 + drivers/gpu/drm/apple/av.c | 70 +++++++++++++++++++---- tools/asahi/dcpaud-open-fallback-tests.py | 9 ++- tools/asahi/run-host-tests.py | 2 +- 5 files changed, 72 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 7e351ada8d3cbd..7ffc1448119012 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -441,9 +441,11 @@ static int dcp_pcm_open(struct snd_pcm_substream *substream) * link is set up again (a modeset, at boot), and refuses calls to the * instance it is replacing meanwhile. Userspace probes the PCM once * and drops an output whose open fails, so read from the successor. - * The sink is taken as the successor reports it. + * The sink is taken as the successor reports it. A refusal is -EINVAL + * (a non-zero retcode); a missing service, a timeout or no memory is + * not waited out. */ - if (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) { + if (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) { dev_dbg(dcpaud->dev, "sink info read failed on a replaced instance (%d), retrying\n", ret); mutex_lock(&dcpaud->data_lock); diff --git a/drivers/gpu/drm/apple/av-lifetime-test.c b/drivers/gpu/drm/apple/av-lifetime-test.c index 1a466dfbbaca93..621f06c2ce887c 100644 --- a/drivers/gpu/drm/apple/av-lifetime-test.c +++ b/drivers/gpu/drm/apple/av-lifetime-test.c @@ -160,6 +160,7 @@ static struct av_life_test *av_life_setup(struct kunit *test, work_func_t owner_ init_waitqueue_head(&t->asrv->gen_wq); #endif INIT_WORK(&t->asrv->start_av_service_wq, owner_fn); + INIT_DELAYED_WORK(&t->asrv->open_check_wq, owner_fn); INIT_WORK(&t->asrv->terminate_wq, owner_fn); INIT_WORK(&t->dcp->external_audio_work, av_life_owner_fn); t->asrv->works_live = true; diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index 32221c1696f892..9b40babd3333fb 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -65,6 +65,9 @@ static const struct dcp_av_audio_cmds dcp_av_audio_cmds_v13_5 = { .get_product_attrs = 18, }; +/* How long an Open refused by an instance being replaced waits for the next one */ +#define AV_AUDIOSRV_REPLACE_MS 1000 + /* * Firmware 27's external role (the T6050 DCPEXTs), as macOS 27 drives it on * the M5 Pro: the 13.5 numbers without the started and stopping @@ -133,6 +136,13 @@ struct audiosrv_data { bool warned_get_elements; bool warned_get_product_attrs; bool is_open; + /* + * A classic Open the firmware refused (-EINVAL), judged once the + * instance has had time to be replaced (av_work_open_check()). + */ + struct delayed_work open_check_wq; + struct device *open_check_dev; + int open_refused; /* INIT_WORK has run for the embedded owner works. */ bool works_live; /* Report and service-start admission. Writers hold srv_rwsem. */ @@ -185,9 +195,9 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam down_write(&asrv->srv_rwsem); old = asrv->srv; - asrv->srv = service; + WRITE_ONCE(asrv->srv, service); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - asrv->gen++; + WRITE_ONCE(asrv->gen, asrv->gen + 1); #endif queue_start = !asrv->reports_stopped; up_write(&asrv->srv_rwsem); @@ -198,6 +208,9 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam afk_service_put(old); asrv->plugged = true; + /* The classic Open was the old instance's: the successor is opened afresh. */ + if (old) + asrv->is_open = false; /* A new instance, maybe a new sink: its catalog is asked for afresh. */ WRITE_ONCE(asrv->elements_empty, false); mutex_unlock(&asrv->plug_lock); @@ -216,9 +229,9 @@ static void av_audiosrv_teardown(struct apple_epic_service *service) down_write(&asrv->srv_rwsem); owned = asrv->srv == service; if (owned) { - asrv->srv = NULL; + WRITE_ONCE(asrv->srv, NULL); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - asrv->gen++; + WRITE_ONCE(asrv->gen, asrv->gen + 1); #endif } up_write(&asrv->srv_rwsem); @@ -226,6 +239,7 @@ static void av_audiosrv_teardown(struct apple_epic_service *service) /* A stale generation must not unplug its successor. */ if (owned) { asrv->plugged = false; + asrv->is_open = false; if (asrv->audio_dev) dcpaud_disconnect(asrv->audio_dev); } @@ -339,9 +353,6 @@ static int av_audiosrv_call(struct apple_epic_service *srv, u32 command, const v return afk_service_call(srv, 0, command, body, body_len, body_pad, reply, reply_len, 0); } -/* How long an Open refused by an instance being replaced waits for the next one */ -#define AV_AUDIOSRV_REPLACE_MS 1000 - /* The audio service instance now published, as dcp_audiosrv_replaced() takes it. */ u64 dcp_audiosrv_instance(struct device *dev) { @@ -366,9 +377,10 @@ bool dcp_audiosrv_replaced(struct device *dev, u64 gen) if (!asrv) return false; - wait_event_timeout(asrv->gen_wq, - READ_ONCE(asrv->srv) && READ_ONCE(asrv->gen) != gen, - msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)); + if (wait_event_interruptible_timeout(asrv->gen_wq, + READ_ONCE(asrv->srv) && READ_ONCE(asrv->gen) != gen, + msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)) < 0) + return false; guard(rwsem_read)(&asrv->srv_rwsem); return asrv->srv && asrv->gen != gen; } @@ -1127,6 +1139,19 @@ void av_service_connect(struct apple_dcp *dcp) ret = afk_service_call(service, 0, asrv->cmds.open, NULL, 0, 32, NULL, 0, 32); + if (ret == -EINVAL) { + /* + * The firmware refuses an Open on an instance it is replacing (a + * resume, a modeset), and publishes the successor, whose own + * connect opens it, within AV_AUDIOSRV_REPLACE_MS. Judge the + * refusal then, so a lasting one is still reported. + */ + WRITE_ONCE(asrv->open_refused, ret); + asrv->open_check_dev = dcp->dev; + mod_delayed_work(system_wq, &asrv->open_check_wq, + msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)); + goto out; + } if (ret) { dev_err(dcp->dev, "error opening audio service: %d\n", ret); goto out; @@ -1283,8 +1308,28 @@ static void av_work_service_start(struct work_struct *work) av_service_connect(dcp); } +/* A refused classic Open, AV_AUDIOSRV_REPLACE_MS later (av_service_connect()) */ +static void av_work_open_check(struct work_struct *work) +{ + struct audiosrv_data *asrv = + container_of(to_delayed_work(work), struct audiosrv_data, open_check_wq); + int ret = READ_ONCE(asrv->open_refused); + bool opened, gone; + + scoped_guard(mutex, &asrv->plug_lock) { + opened = asrv->is_open; + gone = !READ_ONCE(asrv->srv); + } + if (opened || gone) + dev_dbg(asrv->open_check_dev, "audio service Open refused (%d) by an instance since %s\n", + ret, opened ? "replaced" : "removed"); + else + dev_err(asrv->open_check_dev, "error opening audio service: %d\n", ret); +} + static void av_audiosrv_flush_owner(struct audiosrv_data *asrv) { + flush_delayed_work(&asrv->open_check_wq); flush_work(&asrv->start_av_service_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) flush_work(&asrv->terminate_wq); @@ -1313,6 +1358,7 @@ static bool av_audiosrv_drain_owner(struct audiosrv_data *asrv) */ if (first_stop) { disable_work_sync(&asrv->start_av_service_wq); + disable_delayed_work_sync(&asrv->open_check_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) disable_work_sync(&asrv->terminate_wq); #endif @@ -1413,6 +1459,7 @@ void av_audiosrv_reports_restart(struct apple_dcp *dcp) } asrv->work_disabled = false; enable_work(&asrv->start_av_service_wq); + enable_delayed_work(&asrv->open_check_wq); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) enable_work(&asrv->terminate_wq); #endif @@ -1483,11 +1530,9 @@ int avep_init(struct apple_dcp *dcp) case DCP_FIRMWARE_V_26_6_DESKTOP: audiosrv_data->cmds = dcp_av_audio_cmds_v13_5; break; -#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) case DCP_FIRMWARE_V_27_0: audiosrv_data->cmds = dcp_av_audio_cmds_v27; break; -#endif default: #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) /* @@ -1507,6 +1552,7 @@ int avep_init(struct apple_dcp *dcp) } INIT_WORK(&audiosrv_data->start_av_service_wq, av_work_service_start); + INIT_DELAYED_WORK(&audiosrv_data->open_check_wq, av_work_open_check); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) INIT_WORK(&audiosrv_data->terminate_wq, av_work_service_terminate); mutex_init(&audiosrv_data->open_lock); diff --git a/tools/asahi/dcpaud-open-fallback-tests.py b/tools/asahi/dcpaud-open-fallback-tests.py index 284a83c354653a..b2a5befe567bb2 100755 --- a/tools/asahi/dcpaud-open-fallback-tests.py +++ b/tools/asahi/dcpaud-open-fallback-tests.py @@ -27,8 +27,11 @@ MUTATIONS = { # Fail the open when the instance is being replaced. - 'no-retry': ('\tif (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', + 'no-retry': ('\tif (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', '\tif (0 && gen) {'), + # Wait for a successor on any failure, not only a refusal. + 'wait-any': ('\tif (ret == -EINVAL && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {', + '\tif (ret < 0 && dcp_audiosrv_replaced(dcpaud->dcp_dev, gen)) {'), # Fail the open when the service is gone. 'gone-fails': ('\tif (ret == -ENODEV) {\n\t\t/*\n\t\t * No instance answers', '\tif (0) {\n\t\t/*\n\t\t * No instance answers'), @@ -173,6 +176,10 @@ def function(text, name): CHECK(run(true, 0, -ENOMEM, 0, false, false, &d, &rt) == -ENOMEM); CHECK(!dma_opens); + name = "no memory, a successor published: not waited for"; + CHECK(run(true, 0, -ENOMEM, 0, true, true, &d, &rt) == -ENOMEM); + CHECK(!dma_opens && reads == 1); + name = "service gone"; CHECK(run(true, 0, -ENODEV, 0, false, false, &d, &rt) == 0); CHECK(d.open_unplugged && !rules && dma_opens == 1 && rt.hw.formats == UNPLUGGED_FORMATS); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1086d92fe81012..662a9e73af43f9 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -182,7 +182,7 @@ def mutations(flag, names, base, expect=KILL): 'missing-owner-ipc', 'missing-owner-firmware', 'missing-owner-descriptor', 'missing-owner-arena'), out()), # A DP audio PCM open reads a replaced service's successor; a gone service opens unplugged. - 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('no-retry', 'gone-fails', 'keep-cookie', 'mask-all'), []), + 'dcpaud-open-fallback-tests.py': [([], PASS)] + mutations('--mutation', ('no-retry', 'wait-any', 'gone-fails', 'keep-cookie', 'mask-all'), []), # a7638d51880c, the parent of the fix, ran pm_runtime_force_suspend in the late # slot, so the dp-audio domain dropped under a running DCP. 'dcpaud-sleep-hold-tests.py': [(out(), PASS)] From 8247eef83cf1a8e52ce219d09d716e5c3d67d938 Mon Sep 17 00:00:00 2001 From: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:19:57 +0000 Subject: [PATCH 1029/1514] arm64: dts: apple: t6050-j714c: Reset the trackpad AFE from the host With apple,firmware-managed-reset the MTP firmware is left to reset the trackpad's AFE, and on the J714c it never does: the AFE never boots ("AFE[0] Chip Boot Failure for HBPP: No HINT_L") and the multi-touch interface times out, so the trackpad is dead. The J714cAP ADT gives dockchannel-mtp/mtp-transport/multi-touch a function-afe-reset of the SMC pcIO template (0x10000, 0x11c0000), the same line as on the J714s: SMC GPIO gp1c, active low. Describe it as apple,afe-reset-gpios on mtp_hid, as the J714s does, and drop apple,firmware-managed-reset. Tested on a J714c: the host sends the AFE image, the multi-touch interface comes up and the trackpad works. The other ten T6050 board DTBs are byte-identical. Signed-off-by: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index 7b42e646a56793..4b9400d5d0f510 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -236,8 +236,8 @@ /* * The keyboard and trackpad: the HID transport on the MTP's DockChannel FIFO. - * The J714c's MTP firmware owns the trackpad AFE reset, so there is no reset - * GPIO here, unlike the J716c. + * The J714c's MTP firmware does not reset the trackpad AFE, so the host does + * it through an SMC GPIO, as on the J714s. */ &mtp_dockchannel { status = "okay"; @@ -254,10 +254,15 @@ interrupt-names = "tx", "rx"; apple,fifo-size = <0x800>; apple,helper-cpu = <&mtp>; + /* + * ADT mtp function-afe-reset is the SMC pcIO template (0x10000, 0x11c0000), + * the same line as SMC GPIO gp1c, active low, which gpio-macsmc drives, as + * on the J714s. + */ + apple,afe-reset-gpios = <&smc_gpio_low 28 GPIO_ACTIVE_LOW>; multi-touch { apple,power-method = <2>; - apple,firmware-managed-reset; firmware-name = "apple/tpmtfw-j714c.bin"; }; From fb115ec8fc2ecda4f0d5a52435b5371f73ea7833 Mon Sep 17 00:00:00 2001 From: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:19:57 +0000 Subject: [PATCH 1030/1514] arm64: dts: apple: t6050-j714c: Enable the SMC fan, power and temperature sensors The J714c left smc_hwmon disabled until its fan and power keys were checked. The J714cAP SMC has the J714s's keys: two fans, F0Ac and F1Ac, 2317 to 7826 rpm, with the T6050 mode keys F0md and F1md, and the shared power, voltage and current keys. Use the J714s block: the common, dual fan and laptop sensors, temperature discovery, and the shared temperature nodes and apple,soc-die-keys removed so discovery runs. Tested on a J714c: macsmc_hwmon reports both fans, 342 temperature keys and the system, AC input and heatpipe power. The other ten T6050 board DTBs are byte-identical. Signed-off-by: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 27 +++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index 4b9400d5d0f510..38086cbf74d660 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -207,9 +207,32 @@ gpio-reserved-ranges = <0 80>, <81 25>, <108 113>; }; -/* This board's SMC fan and power keys are not yet checked */ +/* + * SMC sensors, as on J714s: the J714cAP SMC has the same two fans (F0Ac/F1Ac, + * 2317..7826 rpm, mode keys F0md/F1md), power, voltage and current keys, plus + * every readable float T* key through apple,discover-temperatures in + * t6050-die0.dtsi. Discovery refuses to run once any temperature channel + * exists, so the shared temperature nodes and apple,soc-die-keys go. + */ +#include "hwmon-common.dtsi" +#include "hwmon-fan-dual.dtsi" +#include "hwmon-laptop.dtsi" + &smc_hwmon { - status = "disabled"; + /delete-property/ apple,soc-die-keys; + /delete-node/ temperature-TH0x; + /delete-node/ temperature-TB0T; + /delete-node/ temperature-TCHP; + /delete-node/ temperature-TW0P; + + /* The T6050 SMC spells the fan mode keys F0md/F1md. The SMC drives the fans. */ + fan-F0Ac { + apple,fan-mode = "F0md"; + }; + + fan-F1Ac { + apple,fan-mode = "F1md"; + }; }; /* From 27d890b32d3cf05ed3dc8c7c9c89a357cd043a58 Mon Sep 17 00:00:00 2001 From: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:19:57 +0000 Subject: [PATCH 1031/1514] arm64: dts: apple: t6050-j714c: Describe the keyboard backlight The J714cAP ADT has arm-io/pwm0, an fpwm s5l8920x at 0x3_05040000 (0x5_05040000 here, fpwm0 in the T6050 inventory), with a kbd-backlight child at default-hz 25000. Describe it as the J714s does: a pwm-leds kbd_backlight on fpwm0 channel 0 with a 40000 ns period, and enable fpwm0. Tested on a J714c: kbd_backlight appears with max brightness 255, the PWM follows the brightness (20 us of 40 us at 128) and the keys light. The other ten T6050 board DTBs are byte-identical. Signed-off-by: XY55bqg6iAw8ttP <132220364+XY55bqg6iAw8ttP@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index 38086cbf74d660..44926eed9c76da 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -15,6 +15,7 @@ /dts-v1/; #define T6050_J714C +#include #include "t6050-max.dtsi" / { @@ -207,6 +208,30 @@ gpio-reserved-ranges = <0 80>, <81 25>, <108 113>; }; +/* + * The keyboard backlight, as on J714s: ADT arm-io/pwm0/kbd-backlight, the + * fpwm s5l8920x at 0x3_05040000 (0x5_05040000 here), default-hz 25000, so a + * 40000 ns period on channel 0. + */ +/ { + led-controller { + compatible = "pwm-leds"; + + led-0 { + pwms = <&fpwm0 0 40000>; + label = "kbd_backlight"; + function = LED_FUNCTION_KBD_BACKLIGHT; + color = ; + max-brightness = <255>; + default-state = "keep"; + }; + }; +}; + +&fpwm0 { + status = "okay"; +}; + /* * SMC sensors, as on J714s: the J714cAP SMC has the same two fans (F0Ac/F1Ac, * 2317..7826 rpm, mode keys F0md/F1md), power, voltage and current keys, plus From e6f06167e73ab28a23c6ead01752e023d6caff51 Mon Sep 17 00:00:00 2001 From: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:50:10 -0500 Subject: [PATCH 1032/1514] drm/asahi: g17: m5: build the 27.2 (26B123) InitData graph From macOS 27.2 on, the M5 GPU firmware takes a different InitData graph than the 26A428 (27.0) one the M5 path builds: - the root version word gains bit 46 (0x0c8e_0339_8728_04c0 -> 0x0c8e_4339_8728_04c0); - the power policy grows from 0x126b0 to 0x12728 bytes and the status config from 0x780 to 0x790. The words above each insert move with it: the policy's state and AON PTD pointers (0x8254 -> 0x8284, 0x11a1c -> 0x11a4c), its controller words, and the status config's link word and pointer (0x774/0x778 -> 0x784/0x788) and submission history; - the HW data is the 26A428 one. Name the InitData layouts a firmware build needs (Variant::m5_layouts: M5Layouts::V26A428 or V26B123) and build the graph in the layouts the identified build names, from a per-build table (M5Layout, M5PolicyMap, M5StatusConfigMap) instead of the board's. The 26A428 encoders write their words at the 26A428 offsets; the power policy and the status config of another build are laid out from those with LayoutBands. The common26 boards keep their own graph. Gpu::new() refuses an M5 build that names no layouts right after identifying it, before anything is written to the GPU. Every M5 build in the tree today is 26A428 and names V26A428, so nothing changes for the M5 Pro, Max and Ultra. No 27.2 build is identified yet; the next commit does that. Observed in InitData captured from macOS 27.2 (26B123, the public Mac17,8 restore image) running as a guest under the m1n1 hypervisor on a J716s (M5 Pro, G17S): the version word on both roots; the spacing of eight objects that depends on the two sizes, matching these and not the 26A428 ones; the moved policy pointers; the status config's link pointer at 0x788 and its inserted words (0x5dc = 0, 0x60c = 5000, 0x640 = 0, 0x670 = 0); the policy controller words 0x492c = 5000 and 0x4a14 = 1600; and a HW data that sits where 26A428's does. The capture does not separate a status-config controller block of 0x64 bytes from one of 0x5c, so the block stride and the history offsets that follow from it are not confirmed, and the G17D controller words are not covered (the part was a G17S). Signed-off-by: rolotrealanis98 <122947376+rolotrealanis98@users.noreply.github.com> Signed-off-by: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> --- drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 663 ++++++++++++++++++-- drivers/gpu/drm/asahi/g17/fw/variant.rs | 16 + drivers/gpu/drm/asahi/g17/initdata.rs | 6 + drivers/gpu/drm/asahi/g17/initdata/m5.rs | 82 ++- drivers/gpu/drm/asahi/g17/mod.rs | 12 +- 5 files changed, 714 insertions(+), 65 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index d89a2c5756b228..ac335de0665962 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -9,6 +9,7 @@ use core::ops::Range; use core::result::Result; +use crate::g17::fw::variant::M5Layouts; use crate::g17::fw::kick::{KickTimestamp, KICK_SLOTS}; pub(crate) const ROOT_SIZE_PRIMARY: usize = 0x0b8; @@ -37,6 +38,10 @@ pub(crate) enum RootProfile { J714G17S26A428, + /// The M5 graph of the macOS 27.2 firmware (26B123): the 26A428 graph with a larger power + /// policy and status config ([`ABI_ALLOCATION_SIZES_26B123_M5`]). + J714G17S26B123, + /// The common interface of macOS 27.2 (26B123, RTKit 3514.41.1): the /// [`Self::J873G18G26A428`] graph with a longer policy and status config /// ([`COMMON26B123_LAYOUTS`]). The J813's G17G build runs it as the J873's G18G one does. @@ -44,6 +49,27 @@ pub(crate) enum RootProfile { } impl RootProfile { + /// The M5 graph profile of a firmware build's InitData layouts. + pub(crate) const fn for_m5_layouts(layouts: super::super::variant::M5Layouts) -> Self { + use super::super::variant::M5Layouts; + match layouts { + M5Layouts::V26A428 => Self::J714G17S26A428, + M5Layouts::V26B123 => Self::J714G17S26B123, + } + } + + /// The layout of an M5 graph profile, `None` for the others. + pub(crate) const fn m5_layout(self) -> Option<&'static M5Layout> { + match self { + Self::J714G17S26A428 => Some(&M5_LAYOUT_26A428), + Self::J714G17S26B123 => Some(&M5_LAYOUT_26B123), + Self::J700G17P + | Self::J813G17G25G76 + | Self::J873G18G26A428 + | Self::J873G18G26B123 => None, + } + } + pub(crate) const fn version_word(self) -> u64 { match self { Self::J700G17P => INITDATA_VERSION_WORD, @@ -51,6 +77,7 @@ impl RootProfile { Self::J873G18G26A428 => COMMON26_INITDATA_VERSION_WORD, Self::J873G18G26B123 => COMMON26B123_INITDATA_VERSION_WORD, Self::J714G17S26A428 => M5_INITDATA_VERSION_WORD, + Self::J714G17S26B123 => M5_26B123_INITDATA_VERSION_WORD, } } @@ -64,14 +91,17 @@ impl RootProfile { match self { Self::J873G18G26A428 => Some(&COMMON26_LAYOUTS), Self::J873G18G26B123 => Some(&COMMON26B123_LAYOUTS), - Self::J700G17P | Self::J813G17G25G76 | Self::J714G17S26A428 => None, + Self::J700G17P + | Self::J813G17G25G76 + | Self::J714G17S26A428 + | Self::J714G17S26B123 => None, } } pub(crate) const fn root_size(self, role: InstanceRole) -> usize { match self { Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_ROOT_SIZE, - Self::J714G17S26A428 => M5_ROOT_SIZE, + Self::J714G17S26A428 | Self::J714G17S26B123 => M5_ROOT_SIZE, Self::J700G17P | Self::J813G17G25G76 => root_size(role), } } @@ -84,8 +114,10 @@ impl RootProfile { (Self::J873G18G26A428 | Self::J873G18G26B123, InstanceRole::Secondary) => { COMMON26_CONTROL_OPENING_OPCODE_SECONDARY } - (Self::J714G17S26A428, InstanceRole::Primary) => M5_CONTROL_OPENING_OPCODE_PRIMARY, - (Self::J714G17S26A428, InstanceRole::Secondary) => { + (Self::J714G17S26A428 | Self::J714G17S26B123, InstanceRole::Primary) => { + M5_CONTROL_OPENING_OPCODE_PRIMARY + } + (Self::J714G17S26A428 | Self::J714G17S26B123, InstanceRole::Secondary) => { M5_CONTROL_OPENING_OPCODE_SECONDARY } (_, InstanceRole::Primary) => CONTROL_OPENING_OPCODE_PRIMARY, @@ -95,26 +127,33 @@ impl RootProfile { pub(crate) const fn control_register_opcode(self) -> Option { match self { - Self::J873G18G26A428 | Self::J873G18G26B123 | Self::J714G17S26A428 => None, + Self::J873G18G26A428 + | Self::J873G18G26B123 + | Self::J714G17S26A428 + | Self::J714G17S26B123 => None, Self::J700G17P | Self::J813G17G25G76 => Some(CONTROL_OPENING_PRIMARY_REGISTER_OPCODE), } } pub(crate) const fn bundle_view_offsets(self) -> [usize; 5] { + if let Some(layout) = self.m5_layout() { + return layout.bundle_view_offsets(); + } match self { Self::J873G18G26A428 => COMMON26_BUNDLE_VIEW_OFFSETS, Self::J873G18G26B123 => COMMON26B123_BUNDLE_VIEW_OFFSETS, - Self::J714G17S26A428 => M5_BUNDLE_VIEW_OFFSETS, - Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_OFFSETS, + _ => BUNDLE_VIEW_OFFSETS, } } pub(crate) const fn bundle_view_extents(self) -> [usize; 5] { + if let Some(layout) = self.m5_layout() { + return layout.bundle_view_extents(); + } match self { // 26B123 grows only the policy and the status config; the five views keep their sizes. Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_BUNDLE_VIEW_EXTENTS, - Self::J714G17S26A428 => M5_BUNDLE_VIEW_EXTENTS, - Self::J700G17P | Self::J813G17G25G76 => BUNDLE_VIEW_EXTENTS, + _ => BUNDLE_VIEW_EXTENTS, } } @@ -122,25 +161,43 @@ impl RootProfile { pub(crate) const fn region_view_low_addrs(self) -> [u64; 2] { match self { Self::J873G18G26A428 | Self::J873G18G26B123 => COMMON26_REGION_VIEW_LOW_ADDRS, - Self::J714G17S26A428 | Self::J700G17P | Self::J813G17G25G76 => REGION_VIEW_LOW_ADDRS, + Self::J714G17S26A428 | Self::J714G17S26B123 | Self::J700G17P | Self::J813G17G25G76 => { + REGION_VIEW_LOW_ADDRS + } } } pub(crate) const fn repeated_region_bundle_offset(self) -> usize { + if let Some(layout) = self.m5_layout() { + return layout.shared.block_88; + } match self { Self::J873G18G26A428 => COMMON26_SHARED_LAYOUT.block_88, Self::J873G18G26B123 => COMMON26B123_SHARED_LAYOUT.block_88, - Self::J714G17S26A428 => M5_SHARED_LAYOUT.block_88, - Self::J700G17P | Self::J813G17G25G76 => MAIN_REPEATED_REGION_BUNDLE_OFFSET, + _ => MAIN_REPEATED_REGION_BUNDLE_OFFSET, } } pub(crate) const fn work_ring_bundle_offsets(self) -> [usize; WORK_CHANNEL_COUNT] { + if let Some(layout) = self.m5_layout() { + return work_ring_offsets(&layout.shared); + } match self { Self::J873G18G26A428 => COMMON26_WORK_RING_BUNDLE_OFFSETS, Self::J873G18G26B123 => COMMON26B123_WORK_RING_BUNDLE_OFFSETS, - Self::J714G17S26A428 => M5_WORK_RING_BUNDLE_OFFSETS, - Self::J700G17P | Self::J813G17G25G76 => WORK_RING_BUNDLE_OFFSETS, + _ => WORK_RING_BUNDLE_OFFSETS, + } + } + + /// Status-config layout of the M5 graph built for this profile. + pub(crate) const fn m5_status_config(self) -> &'static M5StatusConfigMap { + match self { + Self::J714G17S26B123 => &M5_26B123_STATUS_CONFIG, + Self::J714G17S26A428 + | Self::J700G17P + | Self::J813G17G25G76 + | Self::J873G18G26A428 + | Self::J873G18G26B123 => &M5_26A428_STATUS_CONFIG, } } } @@ -884,7 +941,7 @@ pub(crate) fn encode_main_config_for_profile( put_u64(out, MAIN_REGION_VIEWS + 0x20, views.alias_high[1]); // J714's firmware takes both primary sentinels too; they are not // exclusive to the older J700 ABI. - if matches!(profile, RootProfile::J700G17P | RootProfile::J714G17S26A428) { + if profile == RootProfile::J700G17P || profile.m5_layout().is_some() { put_u32(out, MAIN_PRIMARY_SENTINEL_A, 1); put_u32(out, MAIN_PRIMARY_SENTINEL_B, 0xabcd_abcd); } @@ -900,13 +957,15 @@ pub(crate) fn encode_main_config_for_profile( RootProfile::J700G17P => MAIN_SECONDARY_KIND_VALUE, RootProfile::J813G17G25G76 => 0xc, - RootProfile::J873G18G26A428 | RootProfile::J873G18G26B123 - | RootProfile::J714G17S26A428 => COMMON26_MAIN_SECONDARY_KIND, + RootProfile::J873G18G26A428 + | RootProfile::J873G18G26B123 + | RootProfile::J714G17S26A428 + | RootProfile::J714G17S26B123 => COMMON26_MAIN_SECONDARY_KIND, }); - if profile == RootProfile::J714G17S26A428 { + if let Some(layout) = profile.m5_layout() { put_u64(out, COMMON26_MAIN_SECONDARY_POLICY_PTR, - bundle + M5_SHARED_LAYOUT.policy as u64); + bundle + layout.shared.policy as u64); } else if let Some(layouts) = profile.common26_layouts() { put_u64(out, COMMON26_MAIN_SECONDARY_POLICY_PTR, @@ -936,7 +995,7 @@ pub(crate) fn encode_region_c_for_profile( return encode_common26_region_c(out); } - if profile == RootProfile::J714G17S26A428 { + if profile.m5_layout().is_some() { return Err(InitdataError::BufferSize); } @@ -1454,6 +1513,36 @@ pub(crate) const COMMON26_STATUS_CONFIG_BANDS: &[LayoutBand] = &[ band(0x5cc, 0x628, 0x18, Evidence::ProducerChecked), ]; +/// Status config 26A428 -> 26B123 (macOS 27.2), in 26A428 offsets. The status config grows from 0x780 to 0x790 bytes (allocation size table entry 13). +/// +/// From +0x5b4 the object holds two controller blocks, at +0x5b4 and +0x610, of 0x5c bytes +/// each. 26B123 inserts two words into each block, an override slot at block +0x28 and its +/// value at block +0x58, so a block grows to 0x64 bytes and everything after the second one +/// moves by 0x10, the link word and pointer (0x774/0x778 -> 0x784/0x788) and the submission +/// history (0x73c/0x74c/0x750 -> 0x74c/0x75c/0x760) included. +/// +/// InitData captured from macOS 27.2 on a J716s shows the link pointer at 0x788 (the word at +/// 0x778, where 26A428 keeps it, is null) and the link word 1 at 0x784. The capture does not +/// separate a block of 0x64 bytes from one of 0x5c, so where inside the two blocks the 0x10 bytes +/// sit, and the history offsets that follow from the same shift, are not confirmed. +pub(crate) const M5_26B123_STATUS_CONFIG_BANDS: &[LayoutBand] = &[ + band(0x000, 0x5dc, 0, Evidence::Inferred), + band(0x5dc, 0x608, 0x4, Evidence::Inferred), + band(0x608, 0x638, 0x8, Evidence::Inferred), + band(0x638, 0x664, 0xc, Evidence::Inferred), + band(0x664, M5_STATUS_CONFIG_SIZE, 0x10, Evidence::Inferred), +]; + +/// Status-config size of 26B123 (entry 13 of its allocation size table). +pub(crate) const M5_26B123_STATUS_CONFIG_SIZE: usize = + ABI_ALLOCATION_SIZES_26B123_M5[ALLOC_STATUS_CONFIG]; + +/// The words 26B123 has and 26A428 does not, at 26B123 offsets: the override slot of each +/// controller block (0x5dc and 0x640, zero) and its value (0x60c = 5000 and 0x670 = 0), as read +/// from InitData captured from macOS 27.2 on a J716s. +pub(crate) const M5_26B123_STATUS_CONFIG_INSERTED: &[(usize, u32)] = + &[(0x5dc, 0), (0x60c, 5000), (0x640, 0), (0x670, 0)]; + fn write_relocated_words( words: &[(usize, u32)], source_base: usize, @@ -1696,6 +1785,10 @@ pub(crate) const M5_CONTROL_OPENING_OPCODE_SECONDARY: u32 = pub(crate) const M5_INITDATA_VERSION_WORD: u64 = 0x0c8e_0339_8728_04c0; +/// The interface version word, at root+0, of the 27.2 (26B123) M5 firmware: the 26A428 word with +/// bit 46 set. Both roots of InitData captured from macOS 27.2 on a J716s carry it. +pub(crate) const M5_26B123_INITDATA_VERSION_WORD: u64 = 0x0c8e_4339_8728_04c0; + pub(crate) const M5_ROOT_SIZE: usize = 0xc8; pub(crate) const ABI_ALLOCATION_SIZES_26A428_M5: [usize; 24] = [ @@ -1703,11 +1796,137 @@ pub(crate) const ABI_ALLOCATION_SIZES_26A428_M5: [usize; 24] = [ 0xe730, 0x0780, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x00a8, 0x0008, 0x1ca0, 0x00e4, ]; -pub(crate) const M5_SHARED_LAYOUT: SharedClusterLayout = - shared_cluster_layout(&ABI_ALLOCATION_SIZES_26A428_M5); +/// The allocation size table of the 27.2 (26B123) M5 firmware, indexed like +/// [`ABI_ALLOCATION_SIZES_26A428_M5`]. Only two entries differ from it: the power policy (index 4, +/// 0x126b0 -> 0x12728) and the status config (index 13, 0x780 -> 0x790). In InitData captured from +/// macOS 27.2 on a J716s, the spacing of all eight objects whose distance depends on these two +/// sizes matches this table and none matches 26A428's. +pub(crate) const ABI_ALLOCATION_SIZES_26B123_M5: [usize; 24] = [ + 0x2850, 0x0c18, 0x1048, 0x0e10, 0x12728, 0x0068, 0x0800, 0x0088, 0x1800, 0x04c0, 0x4000, + 0x0030, 0xe730, 0x0790, 0x0020, 0x01b0, 0x4800, 0x28800, 0x79800, 0x9000, 0x00a8, 0x0008, + 0x1ca0, 0x00e4, +]; + +const _: () = { + let mut index = 0; + while index < ABI_ALLOCATION_SIZES_26B123_M5.len() { + let same = ABI_ALLOCATION_SIZES_26B123_M5[index] == ABI_ALLOCATION_SIZES_26A428_M5[index]; + assert!(same == (index != ALLOC_POLICY && index != ALLOC_STATUS_CONFIG)); + index += 1; + } +}; -pub(crate) const M5_PRIVATE_LAYOUT: PrivateClusterLayout = - private_cluster_layout(&ABI_ALLOCATION_SIZES_26A428_M5); +/// The InitData layout of one M5 firmware build: its allocation size table and the packed +/// clusters derived from it. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5Layout { + /// The allocation size table. + pub(crate) sizes: [usize; 24], + /// The shared cluster (the HW data bundle). + pub(crate) shared: SharedClusterLayout, + /// The private cluster. + pub(crate) private: PrivateClusterLayout, +} + +impl M5Layout { + const fn new(sizes: [usize; 24]) -> Self { + Self { + sizes, + shared: shared_cluster_layout(&sizes), + private: private_cluster_layout(&sizes), + } + } + + pub(crate) const fn policy_size(&self) -> usize { + self.sizes[ALLOC_POLICY] + } + + pub(crate) const fn status_config_size(&self) -> usize { + self.sizes[ALLOC_STATUS_CONFIG] + } + + /// The bundle up to its BRN table: HW data, the four views and the power policy. + pub(crate) const fn shared_prefix_size(&self) -> usize { + self.shared.brn_table + } + + pub(crate) const fn bundle_view_offsets(&self) -> [usize; 5] { + [ + self.shared.block_c18, + self.shared.block_1048, + self.shared.block_e10, + self.shared.block_68, + self.shared.block_800, + ] + } + + pub(crate) const fn bundle_view_extents(&self) -> [usize; 5] { + [ + self.sizes[ALLOC_BLOCK_C18], + self.sizes[ALLOC_BLOCK_1048], + self.sizes[ALLOC_BLOCK_E10], + self.sizes[ALLOC_BLOCK_68], + self.sizes[ALLOC_BLOCK_800], + ] + } + + pub(crate) const fn private_status_a(&self) -> [usize; 2] { + [ + self.private.roles[0].status_a, + self.private.roles[1].status_a, + ] + } + + pub(crate) const fn private_state_grids(&self) -> [usize; 2] { + [ + self.private.dm_ring_states[0], + self.private.secondary_control_state - WORK_STATE_GRID_OFFSETS[CONTROL_CHANNEL_INDEX], + ] + } + + pub(crate) const fn status_config_in_status_b(&self) -> usize { + self.private.status_config - self.private.status_b + } + + pub(crate) const fn status_b_span(&self) -> usize { + self.private.roles[0].status_a - self.private.status_b + } +} + +/// The 27.0 (26A428) M5 layout. +pub(crate) const M5_LAYOUT_26A428: M5Layout = M5Layout::new(ABI_ALLOCATION_SIZES_26A428_M5); + +/// The 27.2 (26B123) M5 layout. +pub(crate) const M5_LAYOUT_26B123: M5Layout = M5Layout::new(ABI_ALLOCATION_SIZES_26B123_M5); + +const _: () = { + // The bundle and the private cluster keep the sizes of their fixed windows. + assert!(M5_LAYOUT_26B123.shared.total == M5_LAYOUT_26A428.shared.total); + assert!(M5_LAYOUT_26B123.private.total == M5_LAYOUT_26A428.private.total); +}; + +const _: () = { + use super::super::variant::M5Layouts; + // Every M5 build's policy map and status-config map fill the allocations of its size table, + // and the policy starts where the encoders write its 26A428 form. + let builds = [M5Layouts::V26A428, M5Layouts::V26B123]; + let mut index = 0; + while index < builds.len() { + let profile = RootProfile::for_m5_layouts(builds[index]); + let layout = match profile.m5_layout() { + Some(layout) => layout, + None => panic!("an M5 build without an M5 layout"), + }; + assert!(m5_policy_size(builds[index]) == layout.policy_size()); + assert!(profile.m5_status_config().size == layout.status_config_size()); + assert!(layout.shared.policy == M5_SHARED_LAYOUT.policy); + index += 1; + } +}; + +pub(crate) const M5_SHARED_LAYOUT: SharedClusterLayout = M5_LAYOUT_26A428.shared; + +pub(crate) const M5_PRIVATE_LAYOUT: PrivateClusterLayout = M5_LAYOUT_26A428.private; pub(crate) const M5_SHARED_CLUSTER_SIZE: usize = M5_SHARED_LAYOUT.total; @@ -1810,6 +2029,50 @@ pub(crate) const M5_STATUS_CONFIG_LINK_WORD: usize = 0x774; pub(crate) const M5_STATUS_CONFIG_LINK_PTR: usize = 0x778; +/// Submission-history period and slot count (two u64), its generation word and its per-slot +/// bytes in the status config, at 26A428 offsets. +pub(crate) const M5_STATUS_CONFIG_HISTORY: usize = 0x73c; +pub(crate) const M5_STATUS_CONFIG_HISTORY_GENERATION: usize = 0x74c; +pub(crate) const M5_STATUS_CONFIG_HISTORY_SLOTS: usize = 0x750; + +/// Where one firmware build keeps the status-config fields the driver knows by their 26A428 +/// offsets. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5StatusConfigMap { + /// Allocation size (entry 13 of the build's allocation size table). + pub(crate) size: usize, + /// 26A428 offset -> this build's offset; empty for 26A428 itself. + pub(crate) bands: &'static [LayoutBand], + /// Words this build has and 26A428 does not, at this build's offsets. + pub(crate) inserted: &'static [(usize, u32)], +} + +impl M5StatusConfigMap { + /// This build's offset of the 26A428 status-config offset `offset`. + pub(crate) const fn relocate(&self, offset: usize) -> Option { + if !self.bands.is_empty() { + return relocate_by_bands(self.bands, offset); + } + if offset < self.size { + Some(offset) + } else { + None + } + } +} + +pub(crate) const M5_26A428_STATUS_CONFIG: M5StatusConfigMap = M5StatusConfigMap { + size: M5_STATUS_CONFIG_SIZE, + bands: &[], + inserted: &[], +}; + +pub(crate) const M5_26B123_STATUS_CONFIG: M5StatusConfigMap = M5StatusConfigMap { + size: M5_26B123_STATUS_CONFIG_SIZE, + bands: M5_26B123_STATUS_CONFIG_BANDS, + inserted: M5_26B123_STATUS_CONFIG_INSERTED, +}; + pub(crate) const M5_HW_DATA_INSERT: usize = 0x267c; pub(crate) const M5_HW_DATA_INSERT_LEN: usize = 8; @@ -1935,6 +2198,31 @@ pub(crate) const M5_GRAPH: Graph = Graph { power_assert_tally: super::power::POWER_ASSERT_TALLY, }; +/// Select the M5 Pro/Max/Ultra graph from the identified firmware build. +pub(crate) const fn m5_graph(layouts: M5Layouts) -> &'static Graph { + match layouts { + M5Layouts::V26A428 => &M5_GRAPH, + M5Layouts::V26B123 => &M5_GRAPH_26B123, + } +} + +const fn graph_for_m5_layout(layouts: M5Layouts, layout: &M5Layout) -> Graph { + Graph { + profile: RootProfile::for_m5_layouts(layouts), + private: layout.private, + shared: layout.shared, + policy_size: layout.policy_size(), + bundle_view_offsets: layout.bundle_view_offsets(), + bundle_view_extents: layout.bundle_view_extents(), + work_ring_offsets: work_ring_offsets(&layout.shared), + state_grids: layout.private_state_grids(), + power_assert_tally: super::power::POWER_ASSERT_TALLY, + } +} + +pub(crate) const M5_GRAPH_26B123: Graph = + graph_for_m5_layout(M5Layouts::V26B123, &M5_LAYOUT_26B123); + /// The common 26A428 build (J873's interface; the J813). pub(crate) const COMMON26_GRAPH: Graph = Graph { profile: RootProfile::J873G18G26A428, @@ -2622,6 +2910,221 @@ pub(crate) const M5_POLICY_STATE_PTR: usize = 0x8254; pub(crate) const M5_POLICY_AON_PTD_PTR: usize = 0x11a1c; +/// Power policy 26A428 -> 26B123 (macOS 27.2), in 26A428 offsets. The policy grows from 0x126b0 to 0x12728 bytes (allocation size table entry 4); five +/// inserts move the words above them: +/// +/// - +0x4910, 0x10 bytes (two u64 words). The three controller input words at 0x4910..0x4918 +/// (3500, 1000 and 3000 in the J714 defaults) move to 0x4920. +/// - +0x491c, 4 bytes: a controller input word, at 0x492c in 26B123 +/// ([`M5_26B123_POLICY_CONTROLLER_WORDS`]). +/// - 4 bytes between 0x494c and 0x49b8, and 0x18 bytes between 0x4a00 and 0x4a98, in space the M5 +/// encoders do not write: the bands start at the next written offset (0x4948 -> 0x495c, +/// 0x49b8 -> 0x49d0, 0x49fc -> 0x4a14, 0x4a98 -> 0x4ac8), and no word the M5 encoders write +/// falls in either range. +/// - +0x12668, 0x48 bytes: the table at +0x122f0 (24-byte entries) grows from 37 to 40 entries, +/// its trailing fields moving from +0x378/+0x37c/+0x37d/+0x380 to +0x3c0/+0x3c4/+0x3c5/+0x3c8. +/// The new entries are assumed to sit at the end. +/// +/// The state and AON PTD pointers move with their band, 0x8254 -> 0x8284 and 0x11a1c -> 0x11a4c. +/// The 26B123 policy may use words of its own at 0x94e4..0x954c, in space the M5 encoders do not +/// write in 26A428 (0x94b4..0x951c); they stay zero here. +/// +/// InitData captured from macOS 27.2 on a J716s shows the state pointer at 0x8284 and the AON PTD +/// pointer at 0x11a4c, and the maximum power word at 0xa18 where it was; the bands between them +/// follow from these anchors and the sizes and are not otherwise observed. +pub(crate) const M5_26B123_POLICY_BANDS: &[LayoutBand] = &[ + band(0x0000, 0x4910, 0, Evidence::Inferred), + band(0x4910, 0x491c, 0x10, Evidence::Inferred), + band(0x491c, 0x49b8, 0x14, Evidence::Inferred), + band(0x49b8, 0x4a98, 0x18, Evidence::Inferred), + band(0x4a98, 0x12668, 0x30, Evidence::Inferred), + band(0x12668, M5_POLICY_SIZE, 0x78, Evidence::Inferred), +]; + +/// Power-policy size of 26B123 (entry 4 of its allocation size table). +pub(crate) const M5_26B123_POLICY_SIZE: usize = ABI_ALLOCATION_SIZES_26B123_M5[ALLOC_POLICY]; + +/// The 26B123 policy controller input words the 26A428 controller defaults do not write, at 26B123 +/// offsets: +/// +/// - 0x492c, the word of the 4-byte insert at 26A428 +0x491c: 5000. +/// - 0x4a14 (26A428 0x49fc, which the J714 defaults write as 500): 1600. +/// +/// Both read as given in InitData captured from macOS 27.2 on a J716s (G17S). +pub(crate) const M5_26B123_POLICY_CONTROLLER_WORDS: &[(usize, u32)] = + &[(0x492c, 5000), (0x4a14, 1600)]; + +/// The 26B123 policy controller input words for the G17D core type (M5 Ultra), at 26B123 +/// offsets: 2500 at 0x4920 and 800 at 0x4928 (26A428 0x4910 and 0x4918, 3500 and 3000 in the J714 +/// defaults), 1100 at 0x492c, 0 at 0x49e4 (26A428 0x49cc, 1 in the J714 defaults) and 1600 at +/// 0x4a14. The J716s capture was taken on a G17S part (HW data core type 0x18) and does not cover +/// these values. +pub(crate) const M5_26B123_POLICY_CONTROLLER_WORDS_G17D: &[(usize, u32)] = &[ + (0x4920, 2500), + (0x4928, 800), + (0x492c, 1100), + (0x49e4, 0), + (0x4a14, 1600), +]; + +/// The HW-data core type of the G17D (M5 Ultra) parts. +const M5_CORE_TYPE_G17D: u32 = 0x1a; + +/// Where one firmware build keeps the power-policy words the M5 encoders write at their 26A428 +/// offsets. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct M5PolicyMap { + /// Allocation size (entry 4 of the build's allocation size table). + pub(crate) size: usize, + /// 26A428 offset -> this build's offset; empty for 26A428 itself. + pub(crate) bands: &'static [LayoutBand], + /// Words of this build's controller configuration the 26A428 controller defaults do not + /// write, at this build's offsets: for core types with words of their own, then for every + /// other core type. + pub(crate) controller_words_by_core: &'static [(u32, &'static [(usize, u32)])], + pub(crate) controller_words: &'static [(usize, u32)], +} + +impl M5PolicyMap { + /// This build's offset of the 26A428 policy offset `offset`. + pub(crate) const fn relocate(&self, offset: usize) -> Option { + if !self.bands.is_empty() { + return relocate_by_bands(self.bands, offset); + } + if offset < self.size { + Some(offset) + } else { + None + } + } + + /// This build's controller-configuration words for `board`. + fn controller_words_for(&self, board: &Board) -> &'static [(usize, u32)] { + for &(core, words) in self.controller_words_by_core { + if core == board.core_revision.0 { + return words; + } + } + self.controller_words + } +} + +pub(crate) const M5_26A428_POLICY: M5PolicyMap = M5PolicyMap { + size: M5_POLICY_SIZE, + bands: &[], + controller_words_by_core: &[], + controller_words: &[], +}; + +pub(crate) const M5_26B123_POLICY: M5PolicyMap = M5PolicyMap { + size: M5_26B123_POLICY_SIZE, + bands: M5_26B123_POLICY_BANDS, + controller_words_by_core: &[(M5_CORE_TYPE_G17D, M5_26B123_POLICY_CONTROLLER_WORDS_G17D)], + controller_words: M5_26B123_POLICY_CONTROLLER_WORDS, +}; + +/// The power-policy map of an M5 firmware build. +pub(crate) const fn m5_policy(layouts: M5Layouts) -> &'static M5PolicyMap { + match layouts { + M5Layouts::V26A428 => &M5_26A428_POLICY, + _ => &M5_26B123_POLICY, + } +} + +/// The power-policy allocation size of an M5 firmware build. +pub(crate) const fn m5_policy_size(layouts: M5Layouts) -> usize { + m5_policy(layouts).size +} + +/// Whether `bands` lay `source` bytes out over `target` bytes in place: contiguous from 0 to +/// `source`, with shifts that never shrink, ending at `target`. +const fn expands_in_place(bands: &[LayoutBand], source: usize, target: usize) -> bool { + let mut index = 0; + let mut end = 0; + let mut delta: isize = 0; + while index < bands.len() { + let band = bands[index]; + if band.start != end || band.end <= band.start || band.delta < delta { + return false; + } + end = band.end; + delta = band.delta; + index += 1; + } + end == source && (end as isize + delta) as usize == target +} + +const _: () = { + assert!(expands_in_place( + M5_26B123_POLICY_BANDS, + M5_POLICY_SIZE, + M5_26B123_POLICY_SIZE + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_STATE_PTR), + Some(0x8284) + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_AON_PTD_PTR), + Some(0x11a4c) + )); + assert!(matches!( + M5_26B123_POLICY.relocate(M5_POLICY_MAXIMUM_POWER), + Some(0xa18) + )); +}; + +/// Lays out the power policy the M5 encoders wrote at 26A428 offsets into `policy[..0x126b0]` +/// as `map` says, in place: every band moves, highest first, and the bytes no band covers are +/// zeroed. With `controller_defaults`, the build's controller-configuration words for `board` +/// follow. For 26A428 nothing changes. +pub(crate) fn relayout_m5_policy( + map: &M5PolicyMap, + board: &Board, + controller_defaults: bool, + policy: &mut [u8], +) -> Result<(), InitdataError> { + if policy.len() != map.size { + return Err(InitdataError::BufferSize); + } + if map.bands.is_empty() { + return Ok(()); + } + if !expands_in_place(map.bands, M5_POLICY_SIZE, map.size) { + return Err(InitdataError::BufferSize); + } + // A band's target lies over its own source and the higher bands, which have moved already. + for band in map.bands.iter().rev() { + let target = band + .start + .checked_add_signed(band.delta) + .ok_or(InitdataError::BufferSize)?; + policy.copy_within(band.start..band.end, target); + } + let mut end = 0; + for band in map.bands { + let target = band + .start + .checked_add_signed(band.delta) + .ok_or(InitdataError::BufferSize)?; + policy[end..target].fill(0); + end = target + (band.end - band.start); + } + policy[end..].fill(0); + if controller_defaults { + for &(offset, value) in map.controller_words_for(board) { + if offset + .checked_add(4) + .is_none_or(|word_end| word_end > policy.len()) + { + return Err(InitdataError::BufferSize); + } + put_u32(policy, offset, value); + } + } + Ok(()) +} + pub(crate) const J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS: u32 = 200_000; pub(crate) const J714_GPU_PERF_BASE_PSTATE: u32 = 1; @@ -3206,41 +3709,93 @@ pub(crate) fn encode_m5_region_c(out: &mut [u8]) -> Result<(), InitdataError> { Ok(()) } -pub(crate) fn encode_m5_primary_status_b( +/// Encodes the primary status-B span (`out`, from status B to the primary status A) of a build +/// whose status config sits at `config` in the span and is laid out as `map` says. +pub(crate) fn encode_m5_primary_status_b_for( + map: &M5StatusConfigMap, + config: usize, fwctl_state: u64, fwctl_ring: u64, status_b: u64, out: &mut [u8], ) -> Result<(), InitdataError> { - if out.len() != M5_STATUS_B_SPAN { + let end = config + .checked_add(map.size) + .ok_or(InitdataError::BufferSize)?; + if end > out.len() { return Err(InitdataError::BufferSize); } + let link_word = map + .relocate(M5_STATUS_CONFIG_LINK_WORD) + .ok_or(InitdataError::BufferSize)?; + let link_ptr = map + .relocate(M5_STATUS_CONFIG_LINK_PTR) + .ok_or(InitdataError::BufferSize)?; required_address(fwctl_state)?; required_address(fwctl_ring)?; required_address(status_b)?; - let config = M5_STATUS_CONFIG_IN_STATUS_B; out.fill(0); encode_status_block(&mut out[..STATUS_BLOCK_SIZE])?; put_u64(out, COMMON26_STATUS_B_FWCTL_STATE, fwctl_state); put_u64(out, COMMON26_STATUS_B_FWCTL_RING, fwctl_ring); put_u32(out, COMMON26_STATUS_B_CONFIG_HEADER, 1); put_u32(out, COMMON26_STATUS_B_LINK_WORD, 0); - put_u64(out, COMMON26_STATUS_B_LINK_PTR, - status_b + (config + M5_STATUS_CONFIG_LINK_WORD) as u64); - write_relocated_words(M5_25G76_STATUS_CONFIG_WORDS, 0, COMMON26_STATUS_CONFIG_BANDS, - &mut out[config..config + M5_STATUS_CONFIG_SIZE])?; - put_u32(out, config + M5_STATUS_CONFIG_LINK_WORD, 1); - put_u64(out, config + M5_STATUS_CONFIG_LINK_PTR, - status_b + COMMON26_STATUS_B_LINK_WORD as u64); + put_u64( + out, + COMMON26_STATUS_B_LINK_PTR, + status_b + (config + link_word) as u64, + ); + write_m5_status_config_words(map, &mut out[config..end])?; + put_u32(out, config + link_word, 1); + put_u64( + out, + config + link_ptr, + status_b + COMMON26_STATUS_B_LINK_WORD as u64, + ); Ok(()) } -pub(crate) fn encode_m5_private_cluster( +/// Writes the 25G76 status-config words through the 26A428 bands and then `map`, followed by +/// the words the build inserted. For 26A428 this is +/// `write_relocated_words(M5_25G76_STATUS_CONFIG_WORDS, 0, COMMON26_STATUS_CONFIG_BANDS, out)`. +fn write_m5_status_config_words( + map: &M5StatusConfigMap, + out: &mut [u8], +) -> Result<(), InitdataError> { + if out.len() != map.size { + return Err(InitdataError::BufferSize); + } + for &(offset, value) in M5_25G76_STATUS_CONFIG_WORDS { + for (index, byte) in value.to_le_bytes().into_iter().enumerate() { + if byte == 0 { + continue; + } + let target = relocate_by_bands(COMMON26_STATUS_CONFIG_BANDS, offset + index) + .and_then(|source| map.relocate(source)); + if let Some(target) = target { + *out.get_mut(target).ok_or(InitdataError::BufferSize)? = byte; + } + } + } + for &(offset, value) in map.inserted { + if offset.checked_add(4).is_none_or(|end| end > out.len()) { + return Err(InitdataError::BufferSize); + } + put_u32(out, offset, value); + } + Ok(()) +} + +pub(crate) fn encode_m5_private_cluster_for_profile( + profile: RootProfile, private_base: u64, fwctl_state: u64, out: &mut [u8], ) -> Result<(), InitdataError> { - let layout = M5_PRIVATE_LAYOUT; + let layout = profile + .m5_layout() + .ok_or(InitdataError::InterfaceMismatch)? + .private; if out.len() != layout.total { return Err(InitdataError::BufferSize); } @@ -3260,8 +3815,14 @@ pub(crate) fn encode_m5_private_cluster( out.fill(0); let status_b = layout.status_b; let status_a = layout.roles[0].status_a; - encode_m5_primary_status_b(fwctl_state, fwctl_ring, private_base + status_b as u64, - &mut out[status_b..status_a])?; + encode_m5_primary_status_b_for( + profile.m5_status_config(), + layout.status_config - status_b, + fwctl_state, + fwctl_ring, + private_base + status_b as u64, + &mut out[status_b..status_a], + )?; for role in layout.roles { encode_status_block(&mut out[role.status_a..role.status_a + STATUS_BLOCK_SIZE])?; } @@ -3276,24 +3837,26 @@ pub(crate) fn encode_m5_private_cluster( Ok(()) } -pub(crate) fn encode_m5_bundle_policy( +pub(crate) fn encode_m5_bundle_policy_for_layout( + m5_layout: &M5Layout, bindings: M5PolicyBindings, out: &mut [u8], ) -> Result<(), InitdataError> { - let layout = M5_SHARED_LAYOUT; - if out.len() < M5_SHARED_PREFIX_SIZE { + let layout = m5_layout.shared; + let prefix = m5_layout.shared_prefix_size(); + if out.len() < prefix { return Err(InitdataError::BufferSize); } required_address(bindings.state)?; required_address(bindings.aon_ptd)?; - out[layout.block_c18..M5_SHARED_PREFIX_SIZE].fill(0); + out[layout.block_c18..prefix].fill(0); let m5 = M5_25G76_SHARED_LAYOUT; for &(offset, value) in M5_25G76_POLICY_WORDS { if (m5.block_1048..m5.block_e10).contains(&offset) { put_u32(out, layout.block_1048 + (offset - m5.block_1048), value); } } - let policy = &mut out[layout.policy..layout.policy + M5_POLICY_SIZE]; + let policy = &mut out[layout.policy..layout.policy + m5_layout.policy_size()]; put_u32(policy, 0x04, J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS); put_u32(policy, 0x08, J714_GPU_POWER_SAMPLE_PERIOD_AIC_CLOCKS); @@ -3332,6 +3895,14 @@ pub(crate) fn encode_m5_bundle_policy( Ok(()) } +/// The power policy in `out` (a bundle) in its 26A428 form, which the controller defaults write +/// and [`relayout_m5_policy`] then lays out for the firmware build. Every M5 layout starts the +/// policy at the same offset. +fn m5_policy_source(out: &mut [u8]) -> Result<&mut [u8], InitdataError> { + out.get_mut(M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE) + .ok_or(InitdataError::BufferSize) +} + /// Initial controller inputs for J714, applied on every part. The leakage inputs are those of the /// part they were read from (calibration words 0xd2035701 0xac3a1280 0x0a281d81). The firmware /// holds its power estimate, not the draw, to the maximum: a part that leaks more draws more than @@ -3353,7 +3924,7 @@ pub(crate) fn encode_m5_policy_controller_defaults(out: &mut [u8]) -> Result<(), 0x42b6ec22, 0x42c80000, 0x00000000, 0x00000000, ]; for (index, &value) in RELATIVE_POWER_AUX.iter().enumerate() { put_u32(out, 0x1a64 + index * 4, value); } - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const INITIAL: &[(usize, u32)] = &[ (0xd4, 0x3f828f5c), (0xd8, 0x3f828f5c), @@ -3604,7 +4175,7 @@ pub(crate) fn encode_m5_policy_controller_defaults(out: &mut [u8]) -> Result<(), /// tags. pub(crate) fn encode_m5_policy_controller_defaults_j716c(out: &mut [u8]) -> Result<(), InitdataError> { encode_m5_policy_controller_defaults(out)?; - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const MAXIMUM_POWER: u32 = 196_098; const MAXIMUM_POWER_F32: u32 = 0x483f_8080; for offset in [M5_POLICY_MAXIMUM_POWER, 0xad0, 0x44a4, 0x44a8, 0x44ac, 0x45e4] { @@ -3643,7 +4214,7 @@ pub(crate) fn encode_m5_policy_controller_defaults_j775d(out: &mut [u8]) -> Resu 0x421c_12dd, 0x4230_6915, 0x4250_6a36, 0x427d_e40c, 0x4294_0cc0, 0x42bd_bd8e, 0x42c8_0000, ]; for (index, &value) in RELATIVE_POWER_AUX.iter().enumerate() { put_u32(out, 0x1a64 + index * 4, value); } - let policy = &mut out[M5_SHARED_LAYOUT.policy..M5_SHARED_LAYOUT.policy + M5_POLICY_SIZE]; + let policy = m5_policy_source(out)?; const MAXIMUM_POWER: u32 = 345_262; const MAXIMUM_POWER_F32: u32 = 0x48a8_95c0; for offset in [M5_POLICY_MAXIMUM_POWER, 0xad0, 0x44a4, 0x44a8, 0x44ac, 0x45e4] { diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index a9694cf7b22502..93b6ebed87a19e 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -36,6 +36,17 @@ pub(crate) enum InitGraph { V25G83, } +/// The InitData layouts of an M5 firmware build ([`super::m5::initdata`]). A build names its +/// layouts; the M5 graph builds them, and a build that names none is refused. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum M5Layouts { + /// The 26A428 graph: version word 0x0c8e_0339_8728_04c0 and its allocation sizes. + V26A428, + /// The 27.2 (26B123) graph: version word 0x0c8e_4339_8728_04c0, a larger power policy + /// (0x12728) and status config (0x790), the 26A428 HW data. + V26B123, +} + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum QueueRegistration { Firmware, @@ -99,6 +110,8 @@ pub(crate) struct Variant { /// work. The bare-metal M5 firmware powers the cores for work by its own policy: under a /// hold, the M5 Ultra's core-power witness reads unpowered until the hold is released. pub(crate) registration_power_hold: bool, + /// The InitData layouts the M5 graph must build for this firmware; `None` off M5. + pub(crate) m5_layouts: Option, /// A context takes its render pool identity when it is created, not at its first render, /// so that identities held by render graphs kept until the firmware stops refuse new /// contexts with an error instead of failing a context's first render. Set for the A18 @@ -169,6 +182,7 @@ pub(crate) const V26A428: Variant = Variant { v26b123: false, m5_commands: false, registration_power_hold: true, + m5_layouts: None, render_id_at_create: true, objects_after_release: true, telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_16MS, @@ -212,6 +226,7 @@ pub(crate) const V25G83: Variant = Variant { v26b123: false, m5_commands: false, registration_power_hold: true, + m5_layouts: None, render_id_at_create: false, objects_after_release: false, telemetry_protocol: crate::g17::telemetry::Protocol::NONE, @@ -225,6 +240,7 @@ pub(crate) const V26A428_M5: Variant = Variant { traversal_exclusion: false, render_ray_query: false, registration_power_hold: false, + m5_layouts: Some(M5Layouts::V26A428), render_id_at_create: false, objects_after_release: false, telemetry_protocol: crate::g17::telemetry::Protocol::PSTATE_8MS, diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 66fe9d80558f89..2eb169b9b88afa 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -179,6 +179,10 @@ pub(super) struct InitData { active_effort: u32, /// The M5 firmware build's layout, where [`Self::m5`]. graph: &'static super::fw::m5::initdata::Graph, + /// Power-policy layout of the M5 firmware build. + m5_policy: &'static crate::g17::fw::m5::initdata::M5PolicyMap, + /// Status-config layout of the M5 firmware build. + m5_status_config: &'static crate::g17::fw::m5::initdata::M5StatusConfigMap, outer_credits: Option>, // Live publication uses interior writes under the device mutex. This owner is Send but not // Sync, so safe host code cannot issue those writes concurrently through shared references. @@ -300,6 +304,8 @@ impl InitData { v26b123: false, active_effort: 0, graph: &super::fw::m5::initdata::M5_GRAPH, + m5_policy: &crate::g17::fw::m5::initdata::M5_26A428_POLICY, + m5_status_config: &crate::g17::fw::m5::initdata::M5_26A428_STATUS_CONFIG, outer_credits: None, _single_publisher: core::marker::PhantomData, aliases: KVec::new(), diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index 7b641965cdc701..038beca879369c 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -52,7 +52,16 @@ impl InitData { ring(0), ring(1), ring(2), ring(3), page(canonical.start)] } - /// Diagnostic-only read of an aligned word within the existing policy allocation. + /// Selects the power-policy layout of the M5 firmware build `build_m5` encodes for. + pub(in crate::g17) fn set_m5_policy_layouts( + &mut self, + layouts: crate::g17::fw::variant::M5Layouts, + ) { + self.m5_policy = m::m5_policy(layouts); + } + + /// Diagnostic-only read of an aligned word within the existing policy allocation, at the + /// firmware build's own offset. /// Callers hold the device state mutex, retaining this mapping for the entire sample. pub(crate) fn m5_policy_telemetry_word(&self, offset: usize) -> Result { if !self.m5 || offset & 3 != 0 @@ -70,18 +79,27 @@ impl InitData { // 26A428 one (0x6d0 bytes) has no such table. if self.graph.is_common26() { return Ok(()); } let private = self.object(self.cluster)?; - let base = m::M5_PRIVATE_LAYOUT.status_config; + let base = self.graph.private.status_config; + let field = |offset| { + self.m5_status_config + .relocate(offset) + .map(|at| base + at) + .ok_or(EINVAL) + }; + let history = field(m::M5_STATUS_CONFIG_HISTORY)?; + let generation_at = field(m::M5_STATUS_CONFIG_HISTORY_GENERATION)?; + let slots = field(m::M5_STATUS_CONFIG_HISTORY_SLOTS)?; for _ in 0..64 { - let generation = private.word(base + 0x74c)?.load(Ordering::Acquire); + let generation = private.word(generation_at)?.load(Ordering::Acquire); if generation & 1 != 0 { core::hint::spin_loop(); continue; } // The firmware moves the generation around every change of the geometry: while it // reads as it did, the geometry read under it stands, without four more loads. let (period, count) = match self.history_geometry.get() { Some((seen, period, count)) if seen == generation => (period, count), _ => { - let config = private.read_words::<4>(base + 0x73c)?; + let config = private.read_words::<4>(history)?; fence(Ordering::Acquire); - if generation != private.word(base + 0x74c)?.load(Ordering::Acquire) { + if generation != private.word(generation_at)?.load(Ordering::Acquire) { core::hint::spin_loop(); continue; } let period = u64::from(config[0]) | u64::from(config[1]) << 32; @@ -96,7 +114,7 @@ impl InitData { // One slot per 25000 ticks of the period. let index = (ticks % period) / 25_000; if index >= count { return Err(ERANGE); } - let byte = private.pointer(base + 0x750 + index as usize, 1)?; + let byte = private.pointer(slots + index as usize, 1)?; // SAFETY: retained, bounds-checked WC byte, written as a single byte // after reading the even, stable generation, as the firmware expects. unsafe { @@ -130,13 +148,25 @@ impl InitData { } } - pub(crate) fn build_m5(&mut self, dev: &AsahiDrmDevice, uat: &mmu::Uat, - id: &crate::regs::G17Id, board: &m::Board) -> Result { + /// Builds the M5 graph in the InitData layouts the loaded firmware build (`variant`) names. + pub(crate) fn build_m5( + &mut self, + dev: &AsahiDrmDevice, + uat: &mmu::Uat, + id: &crate::regs::G17Id, + board: &m::Board, + variant: &crate::g17::fw::Variant, + ) -> Result { use mmu::{PROT_FW_SHARED_RW as RW, PROT_FW_SHARED_RO as RO, PROT_GPU_SHARED_RW as GPU}; - self.m5 = true; - self.graph = board.graph; + let layouts = variant.m5_layouts.ok_or(EINVAL)?; let common26 = board.graph.is_common26(); + self.graph = if common26 { board.graph } else { m::m5_graph(layouts) }; + let profile = self.graph.profile; + let layout = profile.m5_layout().unwrap_or(&m::M5_LAYOUT_26A428); + self.m5_status_config = profile.m5_status_config(); + self.set_m5_policy_layouts(layouts); + self.m5 = true; // TA, fragment and compute share the compute work ring per priority; every // preparation's claim on it is counted from the first publication on. self.outer_credits = Some(super::outer_credit::Credits::new()?); @@ -146,8 +176,8 @@ impl InitData { KernelObject::new(dev, uat.kernel_vm(), Placement::At(address), size, mmu::PROT_FW_PRIV_RW, CpuMap::WriteBack) }; - let private = board.graph.private; - let shared = board.graph.shared; + let private = self.graph.private; + let shared = self.graph.shared; self.cluster = self.add(fixed(PRIVATE, private.total, RW)?)?; self.region_c = self.add(fixed(REGION_C, mmu::UAT_PGSZ, RO)?)?; self.roots = self.add(fixed(ROOTS, 0xc000, RO)?)?; @@ -173,7 +203,7 @@ impl InitData { Placement::In(uat.kernel_dynamic_range(), mmu::UAT_PGSZ as u64), mmu::UAT_PGSZ, mmu::PROT_FW_SHARED_RW, CpuMap::WriteCombined)?)?; } - let views = board.graph.profile.region_view_low_addrs(); + let views = profile.region_view_low_addrs(); self.alias(self.pb, uat.kernel_lower_vm(), views[0], GPU)?; self.alias(self.page_pool, uat.kernel_lower_vm(), views[1], GPU)?; let (low, high) = if common26 { @@ -210,7 +240,7 @@ impl InitData { .map_err(|_| EINVAL)?; } else { m::encode_m5_region_c(self.object_mut(self.region_c)?.bytes_mut()).map_err(|_| EINVAL)?; - m::encode_m5_private_cluster(PRIVATE, FWCTL, + m::encode_m5_private_cluster_for_profile(profile, PRIVATE, FWCTL, &mut self.object_mut(self.cluster)?.bytes_mut()[..private.total]).map_err(|_| EINVAL)?; } let windows = board.register_windows(); @@ -253,15 +283,32 @@ impl InitData { if common26 { m::encode_common26_bundle_policy(board, bindings, self.object_mut(self.bundle)?.bytes_mut()) } else { - m::encode_m5_bundle_policy(bindings, self.object_mut(self.bundle)?.bytes_mut()) + m::encode_m5_bundle_policy_for_layout(layout, bindings, self.object_mut(self.bundle)?.bytes_mut()) }.map_err(|_| EINVAL)?; - if let Some(defaults) = board.controller_defaults { + let controller_defaults = board.controller_defaults; + if let Some(defaults) = controller_defaults { defaults(self.object_mut(self.bundle)?.bytes_mut()).map_err(|_| EINVAL)?; let maximum = self.object(self.bundle)?.word(shared.policy + m::M5_POLICY_MAXIMUM_POWER)? .load(Ordering::Relaxed); m::set_m5_region_maximum_power(self.object_mut(self.region_c)?.bytes_mut(), maximum) .map_err(|_| EINVAL)?; } + // The policy encoders write the 26A428 layout; a build with another one gets it laid out + // in place, within its own allocation. + if !common26 { + let policy = self.m5_policy; + let policy_end = shared.policy.checked_add(policy.size).ok_or(EINVAL)?; + if policy_end > shared.block_68 { + return Err(EINVAL); + } + m::relayout_m5_policy( + policy, + board, + controller_defaults.is_some(), + &mut self.object_mut(self.bundle)?.bytes_mut()[shared.policy..policy_end], + ) + .map_err(|_| EINVAL)?; + } if let Some(microseconds) = board.idle_standby_us { m::set_m5_region_idle_standby(self.object_mut(self.region_c)?.bytes_mut(), microseconds) .map_err(|_| EINVAL)?; @@ -276,9 +323,8 @@ impl InitData { [PRIVATE + private.status_config as u64, PRIVATE + private.secondary_extra_1 as u64] }, }; - let profile = board.graph.profile; let channels = m::derive_channel_table_for_profile(profile, role, - PRIVATE + board.graph.state_grids[index] as u64, + PRIVATE + self.graph.state_grids[index] as u64, instance.status_a, instance.main_config, BUNDLE); let offset = shared.main_config[index]; m::encode_main_config_for_profile(profile, role, &addresses, &instance, diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 4d3867ea5e38b5..022f0e791453e1 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1663,6 +1663,16 @@ impl Gpu { } let m5 = cfg.profile.is_m5(); if m5 { + // The M5 graph builds the InitData layouts the firmware build names. A build that + // names none is refused here, before anything is written to the GPU. + if variant.m5_layouts.is_none() { + dev_err!( + dev.as_ref(), + "No M5 InitData layouts for this GPU firmware build ({:?})\n", + variant.m5_layouts + ); + return Err(ENODEV); + } let board = cfg.m5.ok_or(EINVAL)?; J813_FORMS.store(board.j813_forms(), core::sync::atomic::Ordering::Relaxed); // Hold the J813's GFX power domain for the session, as the G15 and G16 paths do @@ -2168,7 +2178,7 @@ impl Gpu { .inspect_err(at("root adoption"))?; session .init - .build_m5(dev, &session.uat, id, board) + .build_m5(dev, &session.uat, id, board, shared.variant) .inspect_err(at("M5 graph"))?; session .init From 6bc1534473f9acf667f8ccb852cc0da255a8ba26 Mon Sep 17 00:00:00 2001 From: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:50:28 -0500 Subject: [PATCH 1033/1514] drm/asahi: t6050: identify the M5 Pro's 27.2 (26B123) G17S firmware build The M5 Pro admits only the 27.0 (26A428) G17S build. Admit the 27.2 (26B123) G17S build of both roles as well, identified the way fwid defines a build, as the 27.0 entry already is. 27.2 needs an entry of its own, because its primary's entropy record is not where 26A428's is. 27.0 keeps the 26A428 graph. 27.2 names a new variant, V26B123_M5: the 26A428 M5 protocol with the 26B123 InitData layouts the previous commit builds. The layouts follow from the firmware build the GPU identifies, and that is the only thing that can select them: the firmware's version word is identical for the builds involved, no ADT or DT property or hardware register distinguishes their InitData layouts, and the layout belongs to the firmware, not to a board or a chip. No board or compatible check is involved. The fwid KUnit test checks that every M5 Pro build names the layouts of its OS release and that no two builds share a digest. Signed-off-by: rolotrealanis98 <122947376+rolotrealanis98@users.noreply.github.com> Signed-off-by: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> --- drivers/gpu/drm/asahi/fwid.rs | 20 +++++++ drivers/gpu/drm/asahi/g17/fw/variant.rs | 6 +++ drivers/gpu/drm/asahi/hw/t6050.rs | 72 +++++++++++++++++-------- 3 files changed, 77 insertions(+), 21 deletions(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index f9525c0c08f306..3a00e38977c3e1 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -585,6 +585,26 @@ mod tests { } } + #[test] + fn m5_pro_builds_name_their_layouts() { + use crate::g17::fw::variant::{Firmware, M5Layouts}; + let Firmware::Identified(builds) = crate::hw::t6050::CONFIG.firmware else { + panic!("the M5 Pro must identify its loaded firmware"); + }; + for (i, build) in builds.iter().enumerate() { + // 27.2 (26B123) moved the InitData layouts. + let layouts = if build.os_version >= [27, 2, 0] { + M5Layouts::V26B123 + } else { + M5Layouts::V26A428 + }; + assert_eq!(build.variant.m5_layouts, Some(layouts)); + for other in &builds[i + 1..] { + assert_ne!(build.images[0].text_sha256, other.images[0].text_sha256); + } + } + } + fn t6050_admits_only(builds: &[crate::g17::fw::variant::Build]) { for image in builds.iter().flat_map(|build| build.images) { // Both roles' records, inside TEXT. diff --git a/drivers/gpu/drm/asahi/g17/fw/variant.rs b/drivers/gpu/drm/asahi/g17/fw/variant.rs index 93b6ebed87a19e..5bd78e1e376968 100644 --- a/drivers/gpu/drm/asahi/g17/fw/variant.rs +++ b/drivers/gpu/drm/asahi/g17/fw/variant.rs @@ -247,6 +247,12 @@ pub(crate) const V26A428_M5: Variant = Variant { ..V26A428 }; +/// The 27.2 M5 firmware (26B123): the 26A428 M5 protocol with the 26B123 InitData layouts. +pub(crate) const V26B123_M5: Variant = Variant { + m5_layouts: Some(M5Layouts::V26B123), + ..V26A428_M5 +}; + pub(crate) const V25F84: Variant = Variant { qid_floor: 0, registration: QueueRegistration::Mailbox, diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index 4ea3862efd4cbb..c0c974a4a368ea 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -43,33 +43,63 @@ pub(crate) const CONFIG: Config = Config { sleep_restart: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, - // The firmware in `fw-text` must be this build. iBoot loads the G17S build of both roles - // back to back: the primary's TEXT 0x50000, then the secondary's 0x54000, with the same - // entropy records and boot-filled ranges as the M5 Max. The digest is that of the - // firmware's TEXT with those ranges zeroed, measured on two J714s boots. - firmware: crate::g17::fw::variant::Firmware::Identified(&[crate::g17::fw::variant::Build { - os_version: [27, 0, 0], - name: "27.0 (26A428), G17S", - images: &[ - crate::fwid::FirmwareBuild { - name: "26A428 for T6050 G17S, primary then secondary", + // The firmware in `fw-text` must be one of these builds. iBoot loads the G17S build of both + // roles back to back: the primary's text at 0x50000 of `fw-text`, then the secondary's at + // 0x54000, with the same entropy records and boot-filled ranges as the M5 Max (27.2 moves the + // primary's records by a few bytes). Each digest is that of the firmware's text with + // those ranges zeroed, a loaded copy normalizing to it on every boot. Newest first. + firmware: crate::g17::fw::variant::Firmware::Identified(&[ + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B123), G17S", + images: &[crate::fwid::FirmwareBuild { + name: "26B123 for T6050 G17S, primary then secondary", text_size: 0xa4000, data_size: 0x184000, - entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], boot_filled: &[ - (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), - (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), ], text_sha256: [ - 0x85, 0xd0, 0xfd, 0x82, 0x80, 0xf7, 0x24, 0x65, 0x5c, 0xa9, 0xa9, 0x71, 0x7b, - 0xc9, 0x1a, 0x8a, 0x5e, 0xf6, 0x09, 0x28, 0xd7, 0x72, 0x00, 0xf6, 0xd5, 0x3b, - 0xd0, 0x99, 0xb9, 0x47, 0x39, 0xc6, + 0x2b, 0x46, 0x13, 0xc6, 0x2a, 0x8a, 0x00, 0x7f, 0x22, 0xa9, 0x41, 0x01, 0x70, + 0x2c, 0x9a, 0xc6, 0xc4, 0xe9, 0x0f, 0x2e, 0x12, 0x3f, 0x3b, 0x36, 0xfb, 0xe6, + 0xff, 0xea, 0x91, 0x3f, 0x0f, 0xd9, ], - }, - ], - variant: &crate::g17::fw::variant::V26A428_M5, - config: None, - }]), + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, + crate::g17::fw::variant::Build { + os_version: [27, 0, 0], + name: "27.0 (26A428), G17S", + images: &[ + crate::fwid::FirmwareBuild { + name: "26A428 for T6050 G17S, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + boot_filled: &[ + (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), + (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + ], + text_sha256: [ + 0x85, 0xd0, 0xfd, 0x82, 0x80, 0xf7, 0x24, 0x65, 0x5c, 0xa9, 0xa9, 0x71, + 0x7b, 0xc9, 0x1a, 0x8a, 0x5e, 0xf6, 0x09, 0x28, 0xd7, 0x72, 0x00, 0xf6, + 0xd5, 0x3b, 0xd0, 0x99, 0xb9, 0x47, 0x39, 0xc6, + ], + }, + ], + variant: &crate::g17::fw::variant::V26A428_M5, + config: None, + }, + ]), // Two clusters of ten cores. The buffers are sized for every core slot of the board, so the // board's cluster and slot counts admit the GPU, whichever cores are fused off. core_layout: CoreLayout { From a308ce27654bcccd90ce9f2353e07896b2ca5c76 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:44:35 +0000 Subject: [PATCH 1034/1514] drm/apple: wire set_brightness_correction on v26.6 desktop for CTM commits In iomfb_template.c, dcp_set_matrix_done() checks dcp_methods[iomfbep_set_brightness_correction].tag[0] and follows iomfbep_set_matrix (location 9) with an identity brightness correction (0x10000, 1.0 in Q16.16 fixed point) via dcp_set_brightness_correction() before continuing to dcp_matrix_next(). Without that call, location 9 CTM updates stay cached in DCP firmware rather than committing cleanly. On desktop 26.6 firmware (DCP_FIRMWARE_V_26_6_DESKTOP, T6041), the IOMobileFramebufferAP method numbers across A411..A474 match H17P and firmware 27.0 (+1 from v13.3): set_matrix is A423, get_color_remap_mode is A427, and set_parameter_dcp is A442, placing iomfbep_set_brightness_correction at A428 with the same 4-byte u32 Q16.16 request and 4-byte response layout already defined unconditionally by dcp_set_brightness_correction in iomfb_template.c. Add the A428 entry to the v26.6 desktop method table so DRM CTM commits run the full set_matrix -> set_brightness_correction(0x10000) -> swap sequence. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/apple/iomfb_v26_6_desktop.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c index c718639d52d20f..3a9436c29355fb 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c @@ -40,6 +40,7 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { IOMFB_METHOD("A414", dcpep_pipe_cfg_414), IOMFB_METHOD("A423", iomfbep_set_matrix), IOMFB_METHOD("A427", iomfbep_get_color_remap_mode), + IOMFB_METHOD("A428", iomfbep_set_brightness_correction), IOMFB_METHOD("A442", dcpep_set_parameter_dcp), IOMFB_METHOD("A446", dcpep_create_default_fb), IOMFB_METHOD("A450", dcpep_enable_disable_video_power_savings), From efb06183a88d32ec5187b986ab1fbfce52ca033f Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:44:36 +0000 Subject: [PATCH 1035/1514] drm/apple: mark XRGB2101010 as premultiplied on primary planes dcp_primary_formats[] and drm_format_to_dcp() support DRM_FORMAT_XRGB2101010 using DCP_FORMAT_L10R, a packed 10-bit format with a 2-bit alpha channel. When XRGB2101010 was moved from DCP_FORMAT_W30R to DCP_FORMAT_L10R, apple_plane_atomic_update() added DRM_FORMAT_XBGR2101010 to the is_premultiplied workaround instead of DRM_FORMAT_XRGB2101010, even though DRM_FORMAT_XBGR2101010 is neither advertised nor mapped anywhere in appledrm. If a compositor scans out DRM_FORMAT_XRGB2101010 with coverage blending and zero/undefined X bits, leaving is_premultiplied clear causes DCP to blend against the ignored X channel. Check DRM_FORMAT_XRGB2101010 and update the comment to match. Fixes: f2fd06402a7c ("drm: apple: Advertise ARGB2101010 support") Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/apple/plane.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/plane.c b/drivers/gpu/drm/apple/plane.c index 97f29ebdee0378..e21e626ddee883 100644 --- a/drivers/gpu/drm/apple/plane.c +++ b/drivers/gpu/drm/apple/plane.c @@ -496,13 +496,13 @@ static void apple_plane_atomic_update(struct drm_plane *plane, } /* - * DCP doesn't support XBGR8 / XRGB8 / XBGR2101010 natively. Blending as + * DCP doesn't support XBGR8 / XRGB8 / XRGB2101010 natively. Blending as * pre-multiplied alpha with a black background can be used as * workaround for the bottommost plane. */ if (fmt->format == DRM_FORMAT_XRGB8888 || fmt->format == DRM_FORMAT_XBGR8888 || - fmt->format == DRM_FORMAT_XBGR2101010 || + fmt->format == DRM_FORMAT_XRGB2101010 || base->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) is_premultiplied = true; From 122cf4f39f6b86caadc9eda39bddd3926ce76517 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:37:04 +1100 Subject: [PATCH 1036/1514] selftests: apple-dcp: cover a refused classic audio Open The CEC-only harness compiles av_service_connect(), which now defers judging a refused classic Open (-EINVAL) to a delayed work: give its stub audiosrv_data the new fields and stub the work call, and check that a refusal arms the check without an error, that another error is still reported at once, and that a later Open succeeds. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/apple-dcp/audio.py | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py index 39d02e69271dd4..b6bb0432e022d0 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py @@ -124,6 +124,7 @@ def cec_only_endpoint(root): source = (root / 'drivers/gpu/drm/apple/av.c').read_text() prefix = r''' #include +#include #include #include #include @@ -134,7 +135,12 @@ def cec_only_endpoint(root): #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) #define dev_info(d, ...) ((void)(d)) -#define dev_err(d, ...) ((void)(d)) +static unsigned errs, armed; +#define dev_err(d, ...) ((void)(d), errs++) +#define AV_AUDIOSRV_REPLACE_MS 1000 +static int system_wq; +static unsigned long msecs_to_jiffies(unsigned m) {return m;} +#define mod_delayed_work(wq, w, j) ((void)(wq), (void)(w), (void)(j), armed++) struct device {int unused;}; struct platform_device {int unused;}; struct lock {int held;}; @@ -155,9 +161,12 @@ def cec_only_endpoint(root): u64 gen, v27_boot_gen; struct platform_device *audio_dev; struct {u32 open, close;} cmds; + int open_check_wq, open_refused; + struct device *open_check_dev; }; struct apple_dcp {struct device *dev; struct apple_dcp_afkep *avep; struct audiosrv_data *audiosrv;}; static bool native, v27; +static int call_ret; static unsigned calls, last_cmd, connects, disconnects, releases, closes, v27_starts; static bool dcp_audiosrv_native_link(struct device *dev) {(void)dev; return native;} static bool dcp_is_v14_7_external(const struct apple_dcp *dcp) {(void)dcp; return false;} @@ -176,7 +185,7 @@ def cec_only_endpoint(root): size_t pad, void *out, size_t room, size_t out_pad) { (void)group; (void)data; (void)len; (void)pad; (void)out; (void)room; (void)out_pad; - assert(s && s->pins); calls++; last_cmd = cmd; return 0; + assert(s && s->pins); calls++; last_cmd = cmd; return call_ret; } ''' return prefix + block(source, 'void av_service_connect(') + '\n' + block( @@ -224,6 +233,23 @@ def cec_only_endpoint(root): av_service_connect(&dcp); av_service_disconnect(&dcp); assert(connects == 3 && disconnects == 2 && calls == 2); + + /* + * Classic link, the firmware refuses the Open (an instance being + * replaced): judged later, not reported now; any other error is. + */ + native = v27 = false; + asrv.srv = &srv; + call_ret = -EINVAL; + av_service_connect(&dcp); + assert(calls == 3 && !asrv.is_open && armed == 1 && !errs && asrv.open_refused == -EINVAL && + asrv.open_check_dev == &dev && connects == 3); + call_ret = -ETIMEDOUT; + av_service_connect(&dcp); + assert(calls == 4 && !asrv.is_open && armed == 1 && errs == 1); + call_ret = 0; + av_service_connect(&dcp); + assert(calls == 5 && asrv.is_open && connects == 4); assert(!srv.pins && !asrv.srv_rwsem.held && !asrv.plug_lock.held); return 0; } From 31572d1d5e57a6ac67492e74a880afea24f7d70a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:42:03 +1100 Subject: [PATCH 1037/1514] ci: run the QEMU smoke boot without a network card The virt machine adds a virtio NIC by default, whose option ROM (efi-virtio.rom) Ubuntu ships in ipxe-qemu, a recommended package the runner does not install, so QEMU exited before booting. The smoke run needs no network: pass -nic none. Signed-off-by: Ryan Murray --- .github/scripts/kernel-smoke-qemu.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/kernel-smoke-qemu.sh b/.github/scripts/kernel-smoke-qemu.sh index ca19daf19d94b1..cba250ec93429d 100755 --- a/.github/scripts/kernel-smoke-qemu.sh +++ b/.github/scripts/kernel-smoke-qemu.sh @@ -83,7 +83,7 @@ CPU=max; [ $ACCEL = kvm ] && CPU=host echo "qemu: accel=$ACCEL kernel=$KREL" set +e timeout "$QEMU_TIMEOUT" qemu-system-aarch64 -M virt -accel $ACCEL -cpu $CPU -smp 4 -m 6G \ - -nographic -no-reboot -kernel "$IMG" -initrd "$OUT/initramfs.cpio.zst" \ + -nographic -no-reboot -nic none -kernel "$IMG" -initrd "$OUT/initramfs.cpio.zst" \ -append "console=ttyAMA0 rdinit=/init panic=-1 loglevel=1 log_buf_len=128M kunit.enable=1" \ > "$OUT/console.log" 2>&1 QRC=$? From 0c01afde5108ed24870220ab470cfca5fedd5e73 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:45:01 +1100 Subject: [PATCH 1038/1514] dt-bindings: npu: apple,ane: document T8122 (M3) H15 ANE Document apple,t8122-ane (single H15 engine, ane-type 0xb0, one interrupt, three register windows engine/pmgr/aux-0, five ANE power domains, five DAPF records, and preloaded firmware) and allow the T8122 27.2 DATA IOVA (0x100000c8000) and T8132 27.2 DATA IOVA (0x100000bc000) in apple,firmware-iovas. Signed-off-by: Ryan Murray --- .../devicetree/bindings/npu/apple,ane.yaml | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/Documentation/devicetree/bindings/npu/apple,ane.yaml b/Documentation/devicetree/bindings/npu/apple,ane.yaml index 999599f852d8ac..033bfd15cf9637 100644 --- a/Documentation/devicetree/bindings/npu/apple,ane.yaml +++ b/Documentation/devicetree/bindings/npu/apple,ane.yaml @@ -23,7 +23,10 @@ description: yet established. T8132 has a single H16 engine, two interrupts, six register windows (no second-engine aux-3), and five DAPF records. Its virtual ANE-SYS-V gate resolves to the ANE system domain; ANE-SYS-V-PMP - is a firmware notification gate with no physical PMGR power state. + is a firmware notification gate with no physical PMGR power state. T8122 + has a single H15 engine, one interrupt, three register windows (engine, + pmgr, aux-0), five ANE power domains, five DAPF records, and preloaded + firmware. properties: compatible: @@ -37,6 +40,7 @@ properties: - apple,t6041-ane - apple,t6050-ane - apple,t8112-ane + - apple,t8122-ane - apple,t8132-ane - apple,t8140-ane - apple,t8142-ane @@ -139,12 +143,13 @@ properties: $ref: /schemas/types.yaml#/definitions/uint64-array items: - const: 0x10000000000 - - const: 0x100000c0000 + - enum: [0x100000bc000, 0x100000c0000, 0x100000c8000] description: - Device addresses of the preloaded TEXT and DATA segments. Their sizes - are 0xc0000 and 0x2ac000 bytes respectively. The bootloader supplies - the physical reservations. The device addresses are fixed by the - firmware layout and may be described statically. + Device addresses of the preloaded TEXT and DATA segments. The bootloader + supplies the physical reservations. The device addresses are fixed by the + firmware layout (TEXT at 0x10000000000; DATA at 0x100000bc000 on T8132 + 27.2, 0x100000c0000 on H16/H17 26.x, or 0x100000c8000 on T8122 27.2) and + may be described statically. apple,dapf-ranges: $ref: /schemas/types.yaml#/definitions/uint64-matrix @@ -155,7 +160,7 @@ properties: - description: Physical start address, inclusive - description: Physical end address, inclusive description: - Four (five on T6050 and T8132) DART address protection filter (DAPF) + Four (five on T6050, T8122 and T8132) DART address protection filter (DAPF) ranges, in hardware record order. Each pair contains inclusive 64-bit physical bounds, not a base and length. The same records apply to all three ANE DARTs. Firmware accesses these registers through identity mappings of the @@ -175,7 +180,7 @@ properties: apple,ane-type: $ref: /schemas/types.yaml#/definitions/uint32 - enum: [0x100, 0x110, 0x200] + enum: [0xb0, 0x100, 0x110, 0x200] description: Firmware generation identifier supplied by the bootloader apple,firmware-preloaded: @@ -366,6 +371,33 @@ allOf: - apple,ane-type - apple,firmware-preloaded - apple,dapf-ranges + - if: + properties: + compatible: + const: apple,t8122-ane + then: + properties: + interrupts: + maxItems: 1 + reg: + minItems: 3 + maxItems: 3 + reg-names: + items: + - const: engine + - const: pmgr + - const: aux-0 + power-domains: + minItems: 5 + maxItems: 5 + apple,ane-type: + const: 0xb0 + apple,dapf-ranges: + minItems: 5 + required: + - apple,ane-type + - apple,firmware-preloaded + - apple,dapf-ranges - if: properties: compatible: @@ -388,6 +420,7 @@ allOf: - apple,t8140-ane - apple,t6041-ane - apple,t6050-ane + - apple,t8122-ane - apple,t8142-ane - apple,t8132-ane then: From 0882c538809a9d4b20ee6367fc0583c898baceb3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:45:01 +1100 Subject: [PATCH 1039/1514] arm64: dts: apple: t8122: describe and enable M3 Neural Engine on J615 Add the four ANE sub-block PMGR power states (ane_mpm, ane_cpu, ane_td, ane_base), three ANE DARTs (311800000/311810000/311820000), and the /soc/ane@310000000 node (disabled at SoC level) to T8122, and enable them on J615 (M3 Air). Mark ps_ane_sys and ps_ane_cpu with apple,no-auto-pm so PMGR does not set AUTO_ENABLE behind the cold-started ANE firmware during startup. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615.dts | 16 ++++++ .../boot/dts/apple/t8122-peripherals.dtsi | 57 +++++++++++++++++++ arch/arm64/boot/dts/apple/t8122-pmgr.dtsi | 38 +++++++++++++ 3 files changed, 111 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index a03573b0e2c384..67de05d68cf673 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -180,3 +180,19 @@ &nvram_qspi { read-only; }; + +&ane_dart0 { + status = "okay"; +}; + +&ane_dart1 { + status = "okay"; +}; + +&ane_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi index 355199f3a6a863..1e4b51a2d791e7 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi @@ -141,12 +141,69 @@ status = "disabled"; }; + ane_dart0: iommu@311800000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11800000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + dart_ane_companion3: filter@311804000 { compatible = "apple,t8122-dapf", "apple,dapf"; reg = <0x3 0x11804000 0x0 0x4000>; status = "disabled"; }; + ane_dart1: iommu@311810000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11810000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + + ane_dart2: iommu@311820000 { + compatible = "apple,t8122-dart", "apple,t8110-dart"; + reg = <0x3 0x11820000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = ; + #iommu-cells = <1>; + power-domains = <&ps_ane_sys>; + apple,dma-range = <0x0 0x0 0x400 0x0>; + status = "disabled"; + }; + + ane: ane@310000000 { + compatible = "apple,t8122-ane"; + reg = <0x3 0x10000000 0x0 0x2000000>, + <0x2 0xd0700000 0x0 0x18000>, + <0x2 0xd0724000 0x0 0x4000>; + reg-names = "engine", "pmgr", "aux-0"; + interrupt-parent = <&aic>; + interrupts = ; + iommus = <&ane_dart0 0>, <&ane_dart1 0>, <&ane_dart2 0>; + power-domains = <&ps_ane_sys>, <&ps_ane_cpu>, <&ps_ane_mpm>, + <&ps_ane_td>, <&ps_ane_base>; + apple,ane-type = <0xb0>; + apple,firmware-preloaded; + /* ADT dapf-instance-0: inclusive CPU addresses, in record order. */ + apple,dapf-ranges = /bits/ 64 <0x2a5468000 0x2a5468003>, + /bits/ 64 <0x2d0700438 0x2d070043b>, + /bits/ 64 <0x2d070c000 0x2d070c01b>, + /bits/ 64 <0x2d072682c 0x2d072682f>, + /bits/ 64 <0x292468000 0x292468003>; + /* Default layout; the loader supplies per-boot physical reservations. */ + apple,firmware-iovas = /bits/ 64 <0x10000000000 0x100000c8000>; + status = "disabled"; + }; + apcie1_piodma: dma-controller@595010000 { compatible = "apple,t8122-pcie-piodma", "apple,pcie-piodma"; reg = <0x5 0x95010000 0x0 0x4000>, diff --git a/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi index 982cdc301e1948..05bbe95509d710 100644 --- a/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-pmgr.dtsi @@ -792,6 +792,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "ane_sys"; + apple,no-auto-pm; }; ps_apcie_gp: power-controller@440 { @@ -1119,6 +1120,43 @@ power-domains = <&ps_venc_me0>; }; + ps_ane_mpm: power-controller@c000 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc000 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_mpm"; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_cpu: power-controller@c008 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc008 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_cpu"; + apple,no-auto-pm; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_td: power-controller@c010 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc010 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_td"; + power-domains = <&ps_ane_sys>; + }; + + ps_ane_base: power-controller@c018 { + compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc018 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ane_base"; + power-domains = <&ps_ane_td>, <&ps_ane_cpu>; + }; + ps_disp_cpu: power-controller@10000 { compatible = "apple,t8122-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x10000 4>; From abf39d86cf87d8e82fb23e3b929cea59beb287b1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:45:02 +1100 Subject: [PATCH 1040/1514] accel/ane: h15: support M3 (T8122) 27.2 ANE on shared H16 backend Wire T8122 (M3, H15 on macOS 27.2 / 26B123) directly into the shared AP-direct H16 backend and HWX validator without chip or firmware gates: - Replace fixed H16/H17 HWX descriptor branches with a data-driven target table supporting H15 (0x890/0x8b0 record offsets, 8 header words, trailer BAR 5, no perf record, zero-prologue task descriptors) and 1-byte/4-byte-header task relocation. - Guard optional CE setup when build->ce == 0 (T8122 has no CE block) and enable switch_safe program switching for chip_family >= 15. - Add ane_t8122_platform, ane_h15_mmio_t8122 (DART rev 2.0, 5 DAPF records at DART0+0x4000), ane_h15_build_t8122_26b123 (ASC wrapper at +0x1400044, scratch at +0x1840050, 27.2 firmware-requested table, preload tail heap, 2 ms power-gate hold, cold restart + program replay across sleep), and the J615 26B123 cross-boot preload digest pin. - Add KUnit coverage for the T8122 platform definition, zero-CE H15 boot path, and H15 HWX validation/relocation. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_platform.c | 59 ++++++++ drivers/accel/ane/ane_fw_platform.h | 1 + drivers/accel/ane/ane_fw_platform_test.c | 27 ++++ drivers/accel/ane/ane_fw_transport.h | 2 +- drivers/accel/ane/ane_h16_boot.h | 9 +- drivers/accel/ane/ane_h16_boot_data.h | 85 ++++++++++++ drivers/accel/ane/ane_h16_boot_test.c | 21 +++ drivers/accel/ane/ane_h16_hwx.c | 145 ++++++++++++++------ drivers/accel/ane/ane_h16_hwx.h | 3 +- drivers/accel/ane/ane_h16_hwx_test.c | 80 +++++++++++ drivers/accel/ane/ane_h16_program.c | 27 +++- drivers/accel/ane/ane_h16_tasks.h | 34 +++-- drivers/accel/ane/ane_t6021_rtclient_main.c | 5 + 13 files changed, 439 insertions(+), 59 deletions(-) diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index 40212a20e27687..1963f6b6b10509 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -33,6 +33,20 @@ static const u32 ane_t8132_reg_sizes[] = { 0x2000000, 0x18000, 0x4000, 0x30000, 0xff4000, 0x4000, }; +/* T8122 (M3) H15: engine, PMGR and PMGR aux-0 windows from the ADT. */ +static const char * const ane_t8122_reg_names[] = { + "engine", "pmgr", "aux-0", +}; + +static const u32 ane_t8122_reg_sizes[] = { + 0x2000000, 0x18000, 0x4000, +}; + +/* The same five domains; ANE_SYS sits at +0x438 in the T8122 PMGR. */ +static const u32 ane_t8122_power_words[] = { + 0x438, 0xc008, 0xc000, 0xc010, 0xc018, +}; + /* Offsets in reg[1]; genpd, never the ANE driver, owns transitions. */ static const u32 ane_h16_power_words[] = { 0x3c0, 0xc008, 0xc000, 0xc010, 0xc018, @@ -64,6 +78,51 @@ static const u8 ane_t6050_text_pin_27_0[] = { 0xd1, 0xa2, 0x20, 0xd0, 0xee, 0x43, 0x8b, 0x8f, }; +/* + * M3 (T8122): H15 engine running the macOS 27.2 (26B123) firmware on the + * shared H16 AP-direct backend: ASC wrapper at +0x1400000, scratch at + * +0x1840050, doorbell/IPI at +0x1844000, ANE_SYS at PMGR +0x438, and five + * DAPF records at DART0 + 0x4000. Cold restart + program replay across sleep. + */ +const struct ane_fw_platform ane_t8122_platform = { + .h16_profiles = ane_t8122_profiles_26b123, + .h16_profile_count = ARRAY_SIZE(ane_t8122_profiles_26b123), + .h16_mmio = ane_h15_mmio_t8122, + .h16_mmio_count = ARRAY_SIZE(ane_h15_mmio_t8122), + .dart_params = 0x8, + .dapf_dart = 0, + .dapf_offset = 0x4000, + .dapf_size = SZ_16K, + .dapf_count = 5, + .soc = 0x8122, + .chip_family = 15, + .ane_type = 0xb0, + .hwx_subtype = 6, + .task_generation = 15, + .interrupt_count = 1, + .irq_role = ANE_FW_IRQ_UNKNOWN, + .owner = ANE_FW_OWNER_AP, + .reg_names = ane_t8122_reg_names, + .reg_sizes = ane_t8122_reg_sizes, + .reg_count = ARRAY_SIZE(ane_t8122_reg_names), + .wrapper = 0x1400000, + .mailbox = 0x1408000, + .scratch = 0x1840050, + .doorbell = 0x1844000, + .irq_status = 0x184c000, + .irq_ack = 0x1850000, + .power_words = ane_t8122_power_words, + .power_count = ARRAY_SIZE(ane_t8122_power_words), + .build_name = "27.2 26B123", + .preload_dva = { 0x10000000000, 0x100000c8000 }, + .preload_size = { 0xc8000, 0x2a4000 }, + .stream_mask = BIT(0), + .sleep_cold = true, + .boot_qualified = true, + .firmware_preloaded = true, + .safe_reset = false, +}; + const struct ane_fw_platform ane_h16_platform = { .h16_profiles = ane_h16_profiles, .h16_profile_count = ARRAY_SIZE(ane_h16_profiles), diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h index edceacedc95539..4e7799273da539 100644 --- a/drivers/accel/ane/ane_fw_platform.h +++ b/drivers/accel/ane/ane_fw_platform.h @@ -186,6 +186,7 @@ ane_fw_sleep_path(const struct ane_fw_platform *platform) extern const struct ane_fw_platform ane_h16_platform, ane_h17_platform, ane_t6050_platform, ane_t8142_platform; +extern const struct ane_fw_platform ane_t8122_platform; extern const struct ane_fw_platform ane_t8132_platform; int ane_fw_platform_preflight(struct platform_device *pdev, const struct ane_fw_platform *soc); diff --git a/drivers/accel/ane/ane_fw_platform_test.c b/drivers/accel/ane/ane_fw_platform_test.c index 70e7bc1167e29a..31119a89111aa8 100644 --- a/drivers/accel/ane/ane_fw_platform_test.c +++ b/drivers/accel/ane/ane_fw_platform_test.c @@ -89,6 +89,32 @@ static void ane_platform_staged_bind_test(struct kunit *test) } #if IS_BUILTIN(CONFIG_DRM_ACCEL_ANE) && IS_BUILTIN(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) +/* M3 (T8122) H15: three reg windows, five DAPF records at DART0 + 0x4000, cold sleep. */ +static void ane_t8122_platform_test(struct kunit *test) +{ + struct platform_device *pdev = platform_device_alloc("ane-t8122", -1); + u64 phys[] = { 0x100000000, 0x200000000 }; + + KUNIT_ASSERT_NOT_NULL(test, pdev); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.soc, 0x8122U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.chip_family, 15U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.ane_type, 0xb0U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.hwx_subtype, 6U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.reg_count, 3U); + KUNIT_EXPECT_STREQ(test, ane_t8122_platform.reg_names[2], "aux-0"); + KUNIT_EXPECT_FALSE(test, ane_t8122_platform.has_xl); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_dart, 0U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_offset, 0x4000U); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.dapf_count, 5); + KUNIT_EXPECT_EQ(test, ane_t8122_platform.power_words[0], 0x438U); + KUNIT_EXPECT_TRUE(test, ane_t8122_platform.sleep_cold); + KUNIT_EXPECT_TRUE(test, ane_fw_preload_ranges_valid(&ane_t8122_platform, phys, + ane_t8122_platform.preload_size, + ane_t8122_platform.preload_dva)); + KUNIT_EXPECT_EQ(test, ane_fw_platform_preflight(pdev, &ane_t8122_platform), -EINVAL); + platform_device_put(pdev); +} + /* One engine: no aux-3, five DAPF records; a node without DT is refused. */ static void ane_t8132_platform_test(struct kunit *test) { @@ -221,6 +247,7 @@ static void ane_t8142_bridge_ops_test(struct kunit *test) static struct kunit_case ane_fw_platform_cases[] = { #if IS_BUILTIN(CONFIG_DRM_ACCEL_ANE) && IS_BUILTIN(CONFIG_DRM_ACCEL_ANE_FW_KUNIT_TEST) + KUNIT_CASE(ane_t8122_platform_test), KUNIT_CASE(ane_t8132_platform_test), KUNIT_CASE(ane_t8132_builds_test), KUNIT_CASE(ane_t6050_builds_test), diff --git a/drivers/accel/ane/ane_fw_transport.h b/drivers/accel/ane/ane_fw_transport.h index e0e1a0edd12111..bb166d37f15543 100644 --- a/drivers/accel/ane/ane_fw_transport.h +++ b/drivers/accel/ane/ane_fw_transport.h @@ -377,7 +377,7 @@ ane_fw_transport_bar_context(struct ane_fw_transport *t, u8 *copy, size_t size) */ static inline bool ane_fw_transport_switch_safe(const struct ane_fw_transport *t) { - return t->soc->chip_family == 16 || t->soc->chip_family == 17; + return t->soc->chip_family >= 15; } /* ane_fw_transport_publish_at() offset that copies to the end of the arena. */ diff --git a/drivers/accel/ane/ane_h16_boot.h b/drivers/accel/ane/ane_h16_boot.h index 671e2e3ec5dbf6..a606deb941e6eb 100644 --- a/drivers/accel/ane/ane_h16_boot.h +++ b/drivers/accel/ane/ane_h16_boot.h @@ -439,10 +439,13 @@ static inline int ane_h16_prepare(struct ane_h16_boot *b) { const struct ane_h16_build *f = b->build; unsigned int i, j; - int ret = ane_h16_ce(b); + int ret; - if (ret) - return ret; + if (f->ce) { + ret = ane_h16_ce(b); + if (ret) + return ret; + } for (i = 0; i < f->tunable_count; i++) { const struct ane_h16_tunables *group = &f->tunables[i]; diff --git a/drivers/accel/ane/ane_h16_boot_data.h b/drivers/accel/ane/ane_h16_boot_data.h index b845bf347d2111..8298ab635b7d67 100644 --- a/drivers/accel/ane/ane_h16_boot_data.h +++ b/drivers/accel/ane/ane_h16_boot_data.h @@ -600,4 +600,89 @@ static const struct ane_h16_profile ane_h16_profiles[] __maybe_unused = { }, }; +/* + * T8122 (M3) ANE DARTs, revision 2.0 (PARAMS3 0x2a2a0200). Same fault/protect/ + * lock and DAPF record layout as T6041/T8132, with the DAPF bank at DART0 + * + 0x4000. + */ +static const struct ane_h16_mmio ane_h15_mmio_t8122[] __maybe_unused = { + { + .dart_revision = 0x0200, + .dart_fault = 0x100, + .dart_address_lo = 0x170, + .dart_address_hi = 0x174, + .dart_protect = 0x200, + .dart_lock = 0x208, + .dapf_records = 0, + .dapf_stride = 0x40, + .dapf_end_mask = ~3ULL, + .dapf_r0 = 0x31, + .dapf_r4 = 0, + .dapf_r20 = 1, + }, +}; + +/* T8122 (M3) H15 27.2 (26B123): no CE block and no pre-RUN engine tunables. */ +static const struct ane_h16_build ane_h15_build_t8122_26b123 = { + .cpu_control = 0x1400044, + .rvbar = 0x1050000, + .ready = 0x08042006, + .run = 0x10, + .scratch_polls = 1000, + .scratch_delay_us = 1000, + .command_timeout_ns = 3000000000ULL, + .pool_dva = 0x10000384000, + .ipc_dva = 0x100003d0000, + .heap_dva = 0x100003e4000, + .shared_dva = 0x10001300000, + .expected_rvbar = 0x10000000001, + .pool_size = 0x40000, + .init_offset = 0x180, + .init_size = 0x174, + .config_span = 0x380000, + .config_window = 0x10000000, + .template_count = 64, + .template_word = 0x12c, + .template_value = 4, + .max_channels = 0x21, + .max_heap = SZ_16M, + .native_free = true, + .startup = { { 4, 12 }, { 0, 12 }, { 3, 16 }, { 0x22, 100 } }, +}; + +/* + * M3 Air (J615) 27.2 (26B123) preload: TEXT 0xc8000, DATA 0x2a4000. + * Patchbay cells in DATA order (GKTS, ECAP, ARcM mutable; ABOI, ZSOI fixed). + */ +static const struct ane_h16_preload_cell ane_h15_patchbay_26b123_t8122[] = { + { "GKTS", 0x6850, 8, true }, + { "ECAP", 0x6943, 8, true }, + { "ARcM", 0x6a18, 4, true }, + { "ABOI", 0x6a75, 8, false }, + { "ZSOI", 0x6a85, 4, false }, +}; + +static const struct ane_h16_preload_rule ane_h15_preload_26b123_j615 = { + .cells = ane_h15_patchbay_26b123_t8122, + .cell_count = ARRAY_SIZE(ane_h15_patchbay_26b123_t8122), + .zero_start = 0x2a4000, + .zero_end = 0x2a4000, + .text_size = 0xc8000, + .data_size = 0x2a4000, + .digest = { + 0xed, 0x4a, 0x5a, 0xcf, 0x99, 0x53, 0x21, 0xd1, + 0x51, 0xca, 0xc8, 0xec, 0x2d, 0x2b, 0xf1, 0x1a, + 0x0f, 0xb7, 0x34, 0x4c, 0x43, 0xc0, 0xec, 0x24, + 0x01, 0x6b, 0x59, 0x09, 0x37, 0xee, 0x29, 0x17, + }, +}; + +static const struct ane_h16_profile ane_t8122_profiles_26b123[] __maybe_unused = { + { + .identity = "H15 T8122 27.2 26B123 J615", + .preload = &ane_h15_preload_26b123_j615, + .build = &ane_h15_build_t8122_26b123, + }, +}; + #endif /* __ANE_H16_BOOT_DATA_H__ */ diff --git a/drivers/accel/ane/ane_h16_boot_test.c b/drivers/accel/ane/ane_h16_boot_test.c index b4ea8bebf04cb8..88047e7d938f28 100644 --- a/drivers/accel/ane/ane_h16_boot_test.c +++ b/drivers/accel/ane/ane_h16_boot_test.c @@ -1318,6 +1318,26 @@ static void ane_h16_no_xl_test(struct kunit *test) KUNIT_EXPECT_EQ(test, s->xl_writes, 0U); } +/* H15 (T8122): no CE block, no tunables, five DAPF records, DART rev 0x200. */ +static void ane_h16_t8122_no_ce_test(struct kunit *test) +{ + struct ane_h16_sim *s = test->priv; + + s->build = ane_h15_build_t8122_26b123; + s->mmio = ane_h15_mmio_t8122[0]; + s->dart_params = 0x2a2a0200; + s->soc.h16_mmio = ane_h15_mmio_t8122; + s->soc.h16_mmio_count = ARRAY_SIZE(ane_h15_mmio_t8122); + s->soc.dapf_count = 5; + s->soc.has_xl = false; + s->ce_timeout = true; + s->expect_tuning = 0; + KUNIT_ASSERT_EQ(test, ane_h16_run(&s->boot, ANE_H16_STARTUP), 0); + KUNIT_EXPECT_EQ(test, s->tuning_writes, 0U); + KUNIT_EXPECT_EQ(test, s->ce_ack, 0ULL); + KUNIT_EXPECT_EQ(test, s->dapf_writes, 25U); +} + /* The T8132 boots with its own engine writes only: no XL or C1PPT. */ static void ane_h16_t8132_tunables_test(struct kunit *test) { @@ -1402,6 +1422,7 @@ static struct kunit_case ane_h16_boot_cases[] = { KUNIT_CASE(ane_h16_dapf_five_test), KUNIT_CASE(ane_h16_dapf_five_readback_test), KUNIT_CASE(ane_h16_no_xl_test), + KUNIT_CASE(ane_h16_t8122_no_ce_test), KUNIT_CASE(ane_h16_t8132_tunables_test), KUNIT_CASE(ane_h16_t8132_locked_test), KUNIT_CASE(ane_h16_t8132_locked_strobe_test), diff --git a/drivers/accel/ane/ane_h16_hwx.c b/drivers/accel/ane/ane_h16_hwx.c index cb98778bab3bef..c8b6dfeeadda1c 100644 --- a/drivers/accel/ane/ane_h16_hwx.c +++ b/drivers/accel/ane/ane_h16_hwx.c @@ -16,7 +16,62 @@ struct hwx_range { u64 start, size; }; +struct hwx_target { + u32 subtype; + u32 linear, mixed; + unsigned int header_words; + u32 trailer_bar; + bool has_perf_record; + bool allow_zero_prologue; + bool require_tight_end; + bool allow_stabs_note; + bool allow_slot5_table; + bool allow_zero_scratch_text_flags; +}; + +static const struct hwx_target *hwx_target(u32 subtype) +{ + static const struct hwx_target targets[] = { + { + .subtype = ANE_HWX_SUBTYPE_H15, + .linear = 0x890, + .mixed = 0x8b0, + .header_words = 8, + .trailer_bar = 5, + .allow_zero_prologue = true, + }, + { + .subtype = ANE_HWX_SUBTYPE_H16, + .linear = 0x8a0, + .mixed = 0x8c0, + .header_words = 9, + .trailer_bar = 4, + .has_perf_record = true, + .require_tight_end = true, + }, + { + .subtype = ANE_HWX_SUBTYPE_H17, + .linear = 0x8a0, + .mixed = 0x8c0, + .header_words = 9, + .trailer_bar = 4, + .has_perf_record = true, + .allow_zero_prologue = true, + .allow_stabs_note = true, + .allow_slot5_table = true, + .allow_zero_scratch_text_flags = true, + }, + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(targets); i++) + if (targets[i].subtype == subtype) + return &targets[i]; + return NULL; +} + struct hwx_parser { + const struct hwx_target *target; const u8 *bytes; size_t size, command_end; struct ane_h16_hwx info; @@ -117,7 +172,7 @@ static int hwx_segment(struct hwx_parser *p, const u8 *c, u32 length) * zin_ane_compiler 10.205 marks it 0 there too on H17 (relocations are checked below). */ flags = get_unaligned_le32(c + 68); - if (text && p->info.subtype == ANE_HWX_SUBTYPE_H17 && p->info.scratch.size) { + if (text && p->target->allow_zero_scratch_text_flags && p->info.scratch.size) { if (flags != 4 && flags) return -ENOEXEC; } else if (flags != (surface ? 6 : text ? (p->info.scratch.size ? 4 : 0) : 4)) { @@ -229,16 +284,16 @@ static u32 hwx_trailer_value(const u8 *c, u32 offset) static int hwx_program(struct hwx_parser *p) { + const struct hwx_target *t = p->target; const u8 *c = p->bytes + p->info.program_offset; struct ane_h16_hwx *info = &p->info; - u32 length = get_unaligned_le32(c + 4), records, record_limit, table, i; + u32 length = get_unaligned_le32(c + 4), records, record_limit, table, i, off, count; u32 prologue = 1; size_t final_end = 0; u64 work_limit = 0; - bool mixed = length == 0x8c0; + bool mixed = length == t->mixed; - /* H17 streams open with 0 (linked programs) or 1 (Apple's matmul and add output). */ - if (info->subtype == ANE_HWX_SUBTYPE_H17 && info->text.size >= 4 && + if (t->allow_zero_prologue && info->text.size >= 4 && !get_unaligned_le32(p->bytes + info->text.offset)) prologue = 0; /* Nonzero cells only; every other byte is checked below. */ @@ -250,9 +305,9 @@ static int hwx_program(struct hwx_parser *p) u8 *expected; int ret = -ENOEXEC; - if (length != 0x8a0 && !mixed) + if (length != t->linear && !mixed) return -ENOEXEC; - if (get_unaligned_le32(c + 0xc) != (mixed ? 0x22a : 0x222) || + if (get_unaligned_le32(c + 0xc) != length / 4 - 6 || get_unaligned_le64(c + 0x10) != info->text.vm || get_unaligned_le64(c + 0x810) != info->text.vm || get_unaligned_le64(c + 0x20) != info->constants.vm || @@ -261,7 +316,7 @@ static int hwx_program(struct hwx_parser *p) get_unaligned_le32(c + 0x838) != U32_MAX || get_unaligned_le32(c + 0x83c) != U32_MAX || get_unaligned_le32(c + 0x844) != 0xffff || - get_unaligned_le32(c + 0x848) != (mixed ? 0x8b8 : 0x898)) + get_unaligned_le32(c + 0x848) != length - 8) return -ENOEXEC; records = get_unaligned_le32(c + 0x860); info->tasks = get_unaligned_le32(c + 0x830); @@ -281,7 +336,7 @@ static int hwx_program(struct hwx_parser *p) * kernel fill consecutive slots from slot 6 (+0x70); Apple's zin_ane_compiler 10.205 * starts the same run at slot 5 (+0x60) on H17, the task stream naming slots 5, 6, 7. */ - table = info->subtype == ANE_HWX_SUBTYPE_H17 && get_unaligned_le64(c + 0x60) ? 0x60 : 0x70; + table = t->allow_slot5_table && get_unaligned_le64(c + 0x60) ? 0x60 : 0x70; for (i = 0; i < 5; i++) { u64 base = i < info->surface_count ? info->surfaces[i].section.vm : i == info->surface_count ? info->kernel.vm : 0; @@ -297,7 +352,7 @@ static int hwx_program(struct hwx_parser *p) */ for (i = 0; i < info->surface_count; i++) work_limit += info->surfaces[i].allocation; - if (get_unaligned_le32(c + (mixed ? 0x8b0 : 0x890)) > work_limit) + if (get_unaligned_le32(c + length - 16) > work_limit) return -ENOEXEC; /* Construct the exact fixed trailer and reserved-space expectation. */ @@ -308,29 +363,36 @@ static int hwx_program(struct hwx_parser *p) memcpy(expected + common[i], c + common[i], 4); for (i = 0; i < 5; i++) memcpy(expected + table + i * 16, c + table + i * 16, 8); - put_unaligned_le32(4, expected + 0x868); - put_unaligned_le32(mixed ? 4 : 2, expected + 0x870); - put_unaligned_le32(mixed ? 2 : 7, expected + 0x878); - put_unaligned_le32(8, expected + 0x87c); - put_unaligned_le32(mixed ? get_unaligned_le32(c + 0x858) : hwx_trailer_value(c, 0x880), - expected + 0x880); - put_unaligned_le32(mixed ? 3 : 9, expected + 0x888); - put_unaligned_le32(8, expected + 0x88c); + count = 1 + (mixed ? 2 : 0) + (t->has_perf_record ? 1 : 0); + put_unaligned_le32(t->trailer_bar, expected + 0x868); + put_unaligned_le32(count, expected + 0x870); + off = 0x878; if (mixed) { - put_unaligned_le32(0x08020004, expected + 0x890); - put_unaligned_le32(8, expected + 0x894); - put_unaligned_le32(7, expected + 0x898); - put_unaligned_le32(8, expected + 0x89c); - put_unaligned_le32(hwx_trailer_value(c, 0x8a0), expected + 0x8a0); - put_unaligned_le32(9, expected + 0x8a8); - put_unaligned_le32(8, expected + 0x8ac); + put_unaligned_le32(2, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(get_unaligned_le32(c + 0x858), expected + off + 8); + off += 16; + put_unaligned_le32(3, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(0x08020004, expected + off + 8); + put_unaligned_le32(8, expected + off + 12); + off += 16; } - memcpy(expected + (mixed ? 0x8b0 : 0x890), c + (mixed ? 0x8b0 : 0x890), 4); - memcpy(expected + (mixed ? 0x8b8 : 0x898), "main", 5); + if (t->has_perf_record) { + put_unaligned_le32(7, expected + off); + put_unaligned_le32(8, expected + off + 4); + put_unaligned_le32(hwx_trailer_value(c, off + 8), expected + off + 8); + off += 16; + } + put_unaligned_le32(9, expected + off); + put_unaligned_le32(8, expected + off + 4); + memcpy(expected + off + 8, c + off + 8, 4); + off += 16; + memcpy(expected + off, "main", 5); if (!memcmp(c, expected, length)) { - ret = ane_hx_task_stream_validate_limit(p->bytes + info->text.offset, - info->text.size, info->tasks, prologue, - &record_limit, &final_end); + ret = ane_hx_task_stream_validate_hdr(p->bytes + info->text.offset, + info->text.size, info->tasks, prologue, + t->header_words, &record_limit, &final_end); /* This compiler hint need not equal the encoded record count. */ if (!ret && (!records || records > record_limit)) ret = -ENOEXEC; @@ -339,8 +401,7 @@ static int hwx_program(struct hwx_parser *p) * zero blocks after it leave the engine armed, and the next * EXECUTE on the device times out. */ - if (!ret && info->subtype == ANE_HWX_SUBTYPE_H16 && - final_end != info->text.size) + if (!ret && t->require_tight_end && final_end != info->text.size) ret = -ENOEXEC; } kfree(expected); @@ -493,7 +554,7 @@ static int hwx_symbols(struct hwx_parser *p) * n_desc holds the stabs type number. They name no address; their strings are * still checked below. */ - bool h17 = p->info.subtype == ANE_HWX_SUBTYPE_H17; + bool h17 = p->target->allow_stabs_note; bool stab = h17 && (s[4] == 0x20 || s[4] == 0x80); if (strx >= p->strsize || @@ -549,8 +610,8 @@ static bool hwx_relocations_in_payload(const struct hwx_parser *p, unsigned long continue; } end = pos + words * 4; - record = pos + 9 * 4; - if ((get_unaligned_le32(text + pos + 8 * 4) & 3) == 3) + record = pos + p->target->header_words * 4; + if ((get_unaligned_le32(text + pos + (p->target->header_words - 1) * 4) & 3) == 3) record += 4; while (record < end) { u32 header = get_unaligned_le32(text + record); @@ -569,6 +630,7 @@ static bool hwx_relocations_in_payload(const struct hwx_parser *p, unsigned long int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *info) { + const struct hwx_target *target; struct hwx_parser *p; const void *relocations; const u8 *c = bytes; @@ -579,11 +641,12 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf if (!c || !info || size < 32 || size > ANE_H16_HWX_MAX || get_unaligned_le32(c) != 0xbeefface || get_unaligned_le32(c + 4) != 0x80 || - (get_unaligned_le32(c + 8) != ANE_HWX_SUBTYPE_H16 && - get_unaligned_le32(c + 8) != ANE_HWX_SUBTYPE_H17) || get_unaligned_le32(c + 12) != 2 || get_unaligned_le32(c + 24) != 0x200000 || get_unaligned_le32(c + 28)) return -ENOEXEC; + target = hwx_target(get_unaligned_le32(c + 8)); + if (!target) + return -ENOEXEC; count = get_unaligned_le32(c + 16); length = get_unaligned_le32(c + 20); if (!count || count > HWX_COMMANDS_MAX || !hwx_fits(32, length, size)) @@ -591,10 +654,11 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf p = kzalloc_obj(*p); if (!p) return -ENOMEM; + p->target = target; p->bytes = bytes; p->size = size; p->command_end = 32 + (size_t)length; - p->info.subtype = get_unaligned_le32(p->bytes + 8); + p->info.subtype = target->subtype; for (i = 0; i < count; i++) { u32 cmd, len; @@ -628,7 +692,8 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf goto invalid; p->tensors[p->tensor_count++] = pos; } else if (get_unaligned_le32(c + 8) == 4) { - if (p->info.program_offset || (len != 0x8a0 && len != 0x8c0)) + if (p->info.program_offset || + (len != p->target->linear && len != p->target->mixed)) goto invalid; p->info.program_offset = pos; } else { @@ -657,7 +722,7 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf * LC_NOTE: zin_ane_compiler 10.205 (H17) records its runtime version * inline, offset 40 into this command, 4 bytes. It maps nothing. */ - if (p->info.subtype != ANE_HWX_SUBTYPE_H17 || p->note || len != 48 || + if (!p->target->allow_stabs_note || p->note || len != 48 || !hwx_name(c + 8, "rt.version") || get_unaligned_le64(c + 24) != 40 || get_unaligned_le64(c + 32) != 4 || !hwx_zero(c, 44, len)) goto invalid; diff --git a/drivers/accel/ane/ane_h16_hwx.h b/drivers/accel/ane/ane_h16_hwx.h index dedfa58741964c..7b2fe402cad722 100644 --- a/drivers/accel/ane/ane_h16_hwx.h +++ b/drivers/accel/ane/ane_h16_hwx.h @@ -10,7 +10,8 @@ #define ANE_H16_SECTIONS 8 #define ANE_H16_REGIONS 7 #define ANE_H16_HWX_MAX (SZ_256M + SZ_1M) -/* Mach-O CPU subtypes of the two targets that share this container form. */ +/* Mach-O CPU subtypes of the targets that share this container form. */ +#define ANE_HWX_SUBTYPE_H15 6 #define ANE_HWX_SUBTYPE_H16 7 #define ANE_HWX_SUBTYPE_H17 9 diff --git a/drivers/accel/ane/ane_h16_hwx_test.c b/drivers/accel/ane/ane_h16_hwx_test.c index 05952de6b9ca13..896fd719fe3b78 100644 --- a/drivers/accel/ane/ane_h16_hwx_test.c +++ b/drivers/accel/ane/ane_h16_hwx_test.c @@ -829,6 +829,85 @@ static void hwx_h17_zin_test(struct kunit *test) #undef AS_H16 } +/* + * H15 (M3, subtype 6): 0x890 linear / 0x8b0 mixed program descriptor (no fp32 + * trailer record, trailer_bar 5), 8-word task header, prologue 0 or 1. + */ +static void hwx_h15_test(struct kunit *test) +{ + unsigned int form; + + for (form = 0; form < 2; form++) { + struct hwx_fixture *f = fixture_create(test, form, false); + struct ane_h16_hwx info = {}; + u32 prog_len = form ? 0x8b0 : 0x890; + u32 old_len = form ? 0x8c0 : 0x8a0; + u8 *c, *text, *section; + + KUNIT_ASSERT_NOT_NULL(test, f); + /* Shrink the program descriptor command by 16 bytes (drop key=7 record). */ + c = f->bytes + f->program; + put_unaligned_le32(ANE_HWX_SUBTYPE_H15, f->bytes + 8); + put_unaligned_le32(prog_len, c + 4); + put_unaligned_le32(form ? 0x226 : 0x21e, c + 0xc); + put_unaligned_le32(form ? 0x8a8 : 0x888, c + 0x848); + put_unaligned_le32(5, c + 0x868); + put_unaligned_le32(form ? 3 : 1, c + 0x870); + if (form) { + /* Mixed 0x8b0: keep key=2 and key=3, move key=9 to +0x898. */ + put_unaligned_le32(9, c + 0x898); + put_unaligned_le32(8, c + 0x89c); + put_unaligned_le32(0, c + 0x8a0); + put_unaligned_le32(0, c + 0x8a4); + memcpy(c + 0x8a8, "main", 5); + } else { + /* Linear 0x890: single key=9 record at +0x878. */ + put_unaligned_le32(9, c + 0x878); + put_unaligned_le32(8, c + 0x87c); + put_unaligned_le32(0, c + 0x880); + put_unaligned_le32(0, c + 0x884); + memcpy(c + 0x888, "main", 5); + } + /* Shift remaining load commands + symtab/strings back by 16 bytes. */ + memmove(c + prog_len, c + old_len, f->reloc + 8 - (f->program + old_len)); + f->cursor -= 16; + f->symtab -= 16; + f->symbols -= 16; + f->strings -= 16; + put_unaligned_le32(f->cursor - 32, f->bytes + 20); + put_unaligned_le32(f->symbols, f->bytes + f->symtab + 8); + put_unaligned_le32(f->strings, f->bytes + f->symtab + 16); + + /* H15 task stream: 8-word header + 2-word record (40 B) + 16 B prologue. */ + text = f->bytes + SZ_16K; + section = f->bytes + f->text_command + 72; + memset(text, 0, 64); + put_unaligned_le32(0, text); + put_unaligned_le32(10 << 16, text + 16); + put_unaligned_le32(0x4100 / 4, text + 48); + put_unaligned_le64(56, section + 40); + put_unaligned_le32(14, c + 0x824); + + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + KUNIT_EXPECT_EQ(test, info.subtype, ANE_HWX_SUBTYPE_H15); + KUNIT_EXPECT_EQ(test, info.tasks, 1U); + /* Prologue 1 is accepted too. */ + put_unaligned_le32(1, text); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), 0); + /* H16 rejects an H15 layout. */ + put_unaligned_le32(ANE_HWX_SUBTYPE_H16, f->bytes + 8); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + put_unaligned_le32(ANE_HWX_SUBTYPE_H15, f->bytes + 8); + /* A 9-word H16 task header fails H15 validation. */ + put_unaligned_le32(11 << 16, text + 16); + put_unaligned_le32(0, text + 48); + put_unaligned_le32(0x4100 / 4, text + 52); + put_unaligned_le64(60, section + 40); + put_unaligned_le32(15, c + 0x824); + KUNIT_EXPECT_EQ(test, ane_h16_hwx_validate(f->bytes, f->size, &info), -ENOEXEC); + } +} + static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_forms_test), KUNIT_CASE(hwx_header_test), @@ -849,6 +928,7 @@ static struct kunit_case hwx_cases[] = { KUNIT_CASE(hwx_load_resources_test), KUNIT_CASE(hwx_import_bounds_test), KUNIT_CASE(hwx_h17_zin_test), + KUNIT_CASE(hwx_h15_test), {} }; diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index e7d9c67bc89a96..c835fab0f1076b 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -448,12 +448,35 @@ int ane_h16_custom_bars(const struct ane_h16_hwx_snapshot *snapshot, ret = ane_h16_hwx_snapshot_check(snapshot); if (ret) return ret; - if (!hwx->program_offset || snapshot->size < 0x8a0 || - hwx->program_offset > snapshot->size - 0x8a0) + if (!hwx->program_offset || snapshot->size < 0x890 || + hwx->program_offset > snapshot->size - 0x890) return -ENOEXEC; c = (const u8 *)snapshot->bytes + hwx->program_offset; *count = 0; length = get_unaligned_le32(c + 4); + if (length == 0x890) + return 0; + if (length == 0x8b0) { + if (snapshot->size < 0x8b0 || hwx->program_offset > snapshot->size - 0x8b0) + return -ENOEXEC; + bar = get_unaligned_le16(c + 0x890); + offset = c[0x893]; + width = c[0x894]; + if (!width || width > 16 || offset > 64 - width || dsid >= BIT(width)) + return -ENOEXEC; + bars[0] = (struct ane_h16_custom_bar) { + .configuration = 1, + .value_type = 1, + .bar = bar, + .bit_offset = offset, + .bit_width = width, + .value = dsid, + }; + *count = 1; + return 0; + } + if (snapshot->size < 0x8a0 || hwx->program_offset > snapshot->size - 0x8a0) + return -ENOEXEC; bar = get_unaligned_le32(c + 0x868); offset = get_unaligned_le32(c + 0x878); width = get_unaligned_le32(c + 0x87c); diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h index e96ff85d778abe..166d46abdae0db 100644 --- a/drivers/accel/ane/ane_h16_tasks.h +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -35,25 +35,27 @@ static inline bool ane_h16_register_valid(u32 word) /* * A stream opens with a 16-byte frame: little-endian u32 @prologue, then - * twelve reserved zero bytes. H16 programs open with 1; measured H17 programs - * open with 0 or 1. The last task may end at the end of the section; - * every other task is padded with zeros to 16 bytes. This structural gate - * does not replace container/tensor/aperture validation. + * twelve reserved zero bytes. H15/H16/H17 programs share this framing with + * @header_words fixed words per task (8 on H15, 9 on H16 and H17). The last + * task may end at the end of the section; every other task is padded with + * zeros to 16 bytes. This structural gate does not replace container/tensor/ + * aperture validation. */ static inline int -ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_tasks, - u32 prologue, u32 *record_limit, size_t *final_end) +ane_hx_task_stream_validate_hdr(const void *text, size_t size, u32 expected_tasks, + u32 prologue, unsigned int fixed_header_words, + u32 *record_limit, size_t *final_end) { const u8 *p = text; size_t pos = 16, last = 0; u32 tasks = 0, limit = 0; - if (!p || !expected_tasks || size < 16 || size > ANE_H16_TASK_MAX || - (size & 3) || get_unaligned_le32(p) != prologue || - memchr_inv(p + 4, 0, 12)) + if (!p || !expected_tasks || !fixed_header_words || size < 16 || + size > ANE_H16_TASK_MAX || (size & 3) || + get_unaligned_le32(p) != prologue || memchr_inv(p + 4, 0, 12)) return -ENOEXEC; while (pos < size) { - u32 words, header_words = 9; + u32 words, header_words = fixed_header_words; size_t end, padded, rec; if (size - pos < 16) @@ -65,10 +67,10 @@ ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_ta pos += 16; continue; } - if (words < 9 || words > (size - pos) / 4) + if (words < fixed_header_words || words > (size - pos) / 4) return -ENOEXEC; end = pos + words * 4; - if ((get_unaligned_le32(p + pos + 8 * 4) & 3) == 3) + if ((get_unaligned_le32(p + pos + (fixed_header_words - 1) * 4) & 3) == 3) header_words++; if (words < header_words) return -ENOEXEC; @@ -117,6 +119,14 @@ ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_ta return 0; } +static inline int +ane_hx_task_stream_validate_limit(const void *text, size_t size, u32 expected_tasks, + u32 prologue, u32 *record_limit, size_t *final_end) +{ + return ane_hx_task_stream_validate_hdr(text, size, expected_tasks, prologue, 9, + record_limit, final_end); +} + static inline int ane_hx_task_stream_validate(const void *text, size_t size, u32 expected_tasks, u32 prologue) { diff --git a/drivers/accel/ane/ane_t6021_rtclient_main.c b/drivers/accel/ane/ane_t6021_rtclient_main.c index 65ed18f09c5800..e0adce4d01fb88 100644 --- a/drivers/accel/ane/ane_t6021_rtclient_main.c +++ b/drivers/accel/ane/ane_t6021_rtclient_main.c @@ -4423,6 +4423,10 @@ static void ane_rtclient_remove(struct platform_device *pdev) "remove HELD: no teardown — reboot reclaims\n"); } +static const struct ane_t602x_soc ane_t8122_soc = { + .platform = &ane_t8122_platform, +}; + static const struct ane_t602x_soc ane_h16_soc = { .platform = &ane_h16_platform, }; @@ -4448,6 +4452,7 @@ static const struct of_device_id ane_rtclient_of_match[] = { { .compatible = "apple,t6021-ane", .data = &ane_t6021_soc }, { .compatible = "apple,t6022-ane", .data = &ane_t6022_soc }, { .compatible = "apple,t8112-ane", .data = &ane_t8112_soc }, + { .compatible = "apple,t8122-ane", .data = &ane_t8122_soc }, { .compatible = "apple,t6041-ane", .data = &ane_h16_soc }, { .compatible = "apple,t8132-ane", .data = &ane_t8132_soc }, { .compatible = "apple,t8140-ane", .data = &ane_h17_soc }, From ca5a552b5f099cf954aa4e2b949324b599ea8d43 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:46:06 +1100 Subject: [PATCH 1041/1514] ci: make make pacman-pkg work on the Ubuntu runner Ubuntu's makepkg runs `type -P pacman` at start and its error trap ends the run when pacman is missing, so the Arch packages were never built. Install pacman-package-manager with it, and ask for .pkg.tar.zst packages since Ubuntu's makepkg.conf defaults to .pkg.tar.gz. Both were reproduced and checked in an Ubuntu 24.04 container. Signed-off-by: Ryan Murray --- .github/scripts/kernel-release-build.sh | 3 ++- .github/workflows/kernel-release.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh index 1c80a41d40ace3..9d260a8e8d6aa7 100755 --- a/.github/scripts/kernel-release-build.sh +++ b/.github/scripts/kernel-release-build.sh @@ -99,7 +99,8 @@ echo "dtbs: $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | wc -l)" echo "::group::pacman-pkg" if command -v makepkg >/dev/null; then rm -f "$O"/*.pkg.tar.* - if mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ + # Debian/Ubuntu's makepkg.conf defaults to .pkg.tar.gz. + if PKGEXT=.pkg.tar.zst mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ MAKEPKGOPTS="--nodeps --noconfirm" pacman-pkg; then cp "$O"/*.pkg.tar.zst "$D/" else diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 44d3ca00c7ddba..a2d6f8d0d1a194 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -164,7 +164,8 @@ jobs: - name: Install makepkg (for make pacman-pkg) continue-on-error: true - run: sudo apt-get install -y --no-install-recommends makepkg + # makepkg looks pacman up at start and exits without it. + run: sudo apt-get install -y --no-install-recommends makepkg pacman-package-manager - name: Install Rust run: | From e11accde9300e4d18dbc31a267214c3c81fb7c29 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:45:31 +1100 Subject: [PATCH 1042/1514] drm/asahi: hand G14 firmware 27.2 its user timestamp pairs by pointer The Timestamp operation of a firmware command stream carries one word for the user timestamps. In the 13.5 command layout and in the M3 27.2 runtime that word names the command's pair of user start and end destinations; the firmware reads the destination from that pair. The G14 27.2 render streams instead stored the start destination in the start operation and the end destination in the end operation, so the firmware would have read the user buffer's contents as the pair and written its stamps wherever they pointed. The compute stream left the word and the pair empty, so compute commands never got user timestamps. No user timestamps reach this runtime yet, since it refuses to bind timestamp buffers, so neither has been seen. Make the word name the pair the render commands already carry, or zero without user timestamps, as the M3 27.2 render and compute encoders do. Give the compute command its pair after the internal timestamp pointers, where the 13.5 compute command and the 27.2 render commands keep it, and pass the packet's compute destinations to it. The pair placement and the operation word are host-tested. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 6 +- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 69 +++++++++++++++++++++++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 17 +++--- drivers/gpu/drm/asahi/gpu/v27_2.rs | 6 +- 4 files changed, 88 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index e9edc12813ab43..80698d66f8e6dc 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -670,7 +670,8 @@ impl Runtime { }; let last = index + 1 == packet.commands.len(); let result = match command { - Command::Compute(control) => self.publish_compute(state, &packet, control, last, slots[0]), + Command::Compute(control) => + self.publish_compute(state, &packet, index, control, last, slots[0]), Command::Render { command, usc } => self.publish_render(state, &packet, index, &command, usc, last, slots), }; @@ -687,7 +688,7 @@ impl Runtime { } fn publish_compute( - &self, state: &mut State, packet: &Arc, + &self, state: &mut State, packet: &Arc, index: usize, control: crate::m3::agx_compute::Control, last: bool, slot: usize, ) -> Result { let bind = self.graph.kernel_uat().bind(&packet.vm)?; @@ -700,6 +701,7 @@ impl Runtime { cdm_end: control.end, usc_base: control.usc_base, preempt, + timestamps: packet.timestamp_addresses(index), }; let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; let submission = state.root.stage_compute(command)?; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 20f172fdb52e96..1544c851b6dc32 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -99,6 +99,34 @@ pub(crate) const GLOBALS_BYTES: usize = 0xe48; /// clock below what the firmware's power and thermal controller would allow. pub(crate) const GLOBALS_PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; +/// Where the 27.2 compute command (type 3, 0x358 bytes) keeps the user timestamp pair: right +/// after the command time (+0x2c4) and the internal start/end pointers (+0x2cc), the order of +/// the 13.5 compute command and of the 27.2 render commands (vertex +0x5e4, fragment +0x948). +pub(crate) const COMPUTE_USER_TIMESTAMPS: usize = 0x2dc; + +/// The value of a 27.2 Timestamp operation's user word: like the 13.5 and the M3 27.2 +/// operations it names the command's start/end pair of user destinations, not a destination. +/// Zero when the command has no user timestamps. +pub(crate) fn user_timestamp_pointer(pair_va: u64, pair: [u64; 2]) -> u64 { + if pair == [0; 2] { + 0 + } else { + pair_va + } +} + +fn put64(b: &mut [u8], at: usize, v: u64) { + b[at..at + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Writes the user timestamp pair of a zeroed 27.2 compute command at `cmd_va` and returns the +/// Timestamp operations' user word ([`user_timestamp_pointer`]). +pub(crate) fn encode_compute_timestamps(cmd: &mut [u8], cmd_va: u64, timestamps: [u64; 2]) -> u64 { + put64(cmd, COMPUTE_USER_TIMESTAMPS, timestamps[0]); + put64(cmd, COMPUTE_USER_TIMESTAMPS + 8, timestamps[1]); + user_timestamp_pointer(cmd_va + COMPUTE_USER_TIMESTAMPS as u64, timestamps) +} + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -201,4 +229,45 @@ mod tests { assert!(GLOBALS_PSTATE_SELECTORS[i + 1..].iter().all(|&o| o + 4 <= at || at + 4 <= o)); } } + + /// Size of the 27.2 compute command. + const COMPUTE_COMMAND_BYTES: usize = 0x358; + + /// Byte ranges `encode_compute` (gpu/v27_2.rs) writes in the 27.2 compute command, and + /// the words its stream hands the firmware to write (+0x264, +0x2c4, +0x304, +0x314, + /// +0x340). + const COMPUTE_WRITES: &[(usize, usize)] = &[ + (0, 4), (4, 8), (0xc, 4), (0x10, 8), + (0x68, 8), (0x70, 8), (0x78, 8), (0x80, 8), (0x88, 8), (0x90, 8), (0x98, 8), (0xa0, 8), + (0xc0, 8), + (0x1e8, 8), (0x1f0, 4), (0x220, 8), (0x228, 8), (0x264, 8), (0x270, 4), + (0x298, 0x1c), (0x2c4, 0x18), (0x304, 8), (0x314, 8), (0x334, 0x14), + ]; + + /// Whether `len` bytes at `at` fit the command and are none the compute encoder uses. + fn free(at: usize, len: usize) -> bool { + at + len <= COMPUTE_COMMAND_BYTES + && COMPUTE_WRITES.iter().all(|&(o, l)| o + l <= at || at + len <= o) + } + + #[test] + fn a_timestamp_operation_names_the_pair_only_when_there_is_one() { + assert_eq!(user_timestamp_pointer(0x1000, [0, 0]), 0); + assert_eq!(user_timestamp_pointer(0x1000, [0x40, 0]), 0x1000); + assert_eq!(user_timestamp_pointer(0x1000, [0, 0x48]), 0x1000); + } + + #[test] + fn the_compute_user_pair_lands_in_a_free_place() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + let pair = [0xffff_ffa1_8140_0010, 0xffff_ffa1_8140_0018]; + assert_eq!(encode_compute_timestamps(&mut cmd, 0x8000, pair), 0x8000 + 0x2dc); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + assert_eq!([read64(0x2dc), read64(0x2e4)], pair); + assert!(free(0x2dc, 16)); + // No timestamps leave the command as it was. + let mut empty = [0u8; COMPUTE_COMMAND_BYTES]; + assert_eq!(encode_compute_timestamps(&mut empty, 0x8000, [0; 2]), 0); + assert!(empty.iter().all(|&b| b == 0)); + } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index 10ce122708dbde..cbbbd7febb8e59 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -224,7 +224,8 @@ fn header(b: &mut [u8], kind: u32, c: &Common) { put64(b, 0x10, c.tracking); } -/// Write the destinations used by both internal timestamp paths. +/// Write the destinations used by both internal timestamp paths. `user` names the command's +/// pair of user destinations, or is 0 ([`crate::g14_v27_2_abi::user_timestamp_pointer`]). fn timestamp_op( s: &mut [u8], at: usize, @@ -234,7 +235,7 @@ fn timestamp_op( ts_pointers: u64, internal0: u64, internal1: u64, - user: [u64; 2], + user: u64, ) { put32(s, at, if start { 0x8000_0003 } else { 3 }); put64(s, at + 0x04, command_time); @@ -245,7 +246,7 @@ fn timestamp_op( if start { ts_pointers } else { ts_pointers + 8 }, ); put64(s, at + 0x1c, q.queue); - put64(s, at + 0x24, user[usize::from(!start)]); + put64(s, at + 0x24, user); put64(s, at + 0x2c, internal0); put64(s, at + 0x34, internal1); } @@ -430,6 +431,7 @@ pub(crate) fn encode_vertex( put64(cmd, 0x5dc, c.timestamps + 8); put64(cmd, 0x5e4, timestamps[0]); put64(cmd, 0x5ec, timestamps[1]); + let user = crate::g14_v27_2_abi::user_timestamp_pointer(c.cmd_va + 0x5e4, timestamps); let internal0 = c.cmd_va + 0x61c; let internal1 = c.cmd_va + 0x538; let flag = c.cmd_va + 0x568; @@ -469,7 +471,7 @@ pub(crate) fn encode_vertex( ts, internal0, internal1, - timestamps, + user, ); put32(s, 0x1e8, 0x0000_0100); timestamp_op( @@ -481,7 +483,7 @@ pub(crate) fn encode_vertex( ts, internal0, internal1, - timestamps, + user, ); let fin = 0x238; put32(s, fin, 6); @@ -933,6 +935,7 @@ pub(crate) fn encode_fragment( let ts = va(frag_at(offset_of!(Rf, timestamp_pointers))); put64(cmd, 0x948, timestamps[0]); put64(cmd, 0x950, timestamps[1]); + let user = crate::g14_v27_2_abi::user_timestamp_pointer(va(0x948), timestamps); let internal0 = va(0x980); let internal1 = va(0x89c); let (jp1, jp2) = (va(0x80), va(0x3c8)); @@ -989,7 +992,7 @@ pub(crate) fn encode_fragment( ts, internal0, internal1, - timestamps, + user, ); put32(s, 0x200, 0x0001_0000); // wait for the fragment pipe timestamp_op( @@ -1001,7 +1004,7 @@ pub(crate) fn encode_fragment( ts, internal0, internal1, - timestamps, + user, ); // op 8 FinalizeFragment (0xbc). let fin = 0x250; diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 70e9207001035a..12efdfff44584f 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -76,6 +76,8 @@ pub(crate) struct ComputeJob { /// VA of the preemption buffer in the same context (13.5 layout: buffer 1 at +0, /// buffers 2 to 5 at +compute_preempt1_size + 8n). pub(crate) preempt: u64, + /// Firmware VAs of the user start and end timestamps, or 0. + pub(crate) timestamps: [u64; 2], } fn put32(b: &mut [u8], at: usize, v: u32) { @@ -119,6 +121,7 @@ fn encode_compute( // through the pointer at +0x334. put32(cmd, 0x33c, 1); put64(cmd, 0x334, timestamps + 0x20); + let user = g14_v27_2_abi::encode_compute_timestamps(cmd, cmd_va, job.timestamps); put32(stream, 0, 11); // 13.5 StartCompute.unk_28, at the same place in this layout (the 13.5 G14 path writes 1). @@ -138,6 +141,7 @@ fn encode_compute( put64(stream, at + 0x0c, cmd_va + 0x2cc); put64(stream, at + 0x14, cmd_va + selected); put64(stream, at + 0x1c, q.queue); + put64(stream, at + 0x24, user); put64(stream, at + 0x2c, cmd_va + 0x314); put64(stream, at + 0x34, cmd_va + 0x264); } @@ -354,7 +358,7 @@ impl BootJob { let cdm = self.client_va + self.preempt1 + 0x2000; let job = ComputeJob { context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, - usc_base: 0x11_0000_0000, preempt: self.client_va, + usc_base: 0x11_0000_0000, preempt: self.client_va, timestamps: [0; 2], }; let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, From 9bc8fcc626484f5ac43757a3faff44fbb6c29299 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:46:35 +1100 Subject: [PATCH 1043/1514] drm/asahi: bind timestamp buffers on G14 firmware 27.2 GEM_BIND_OBJECT with USAGE_TIMESTAMPS returned ENOTSUPP on the G14 firmware 27.2 runtime, so Vulkan could not create timestamp query pools and OpenCL profiling failed. That firmware reaches the kernel window through its own copy of the window's second-level entries, made once before it starts (FirmwareWindow::mirror), so a leaf table created later for a timestamp buffer would never be seen by it. The graph already keeps its private allocations below the 64 MiB timestamp aperture that the 27.2 root hands to the firmware. Link the aperture's leaf tables, with no mappings, before the window is mirrored, the way the kernel lower tables are prepared for a firmware that samples its root only at start (Uat::prepare_lower_tables, now sharing one helper with the new prepare_kernel_tables). Page tables are only freed with their VM, so the mirrored entries stay valid; leaf entries written later are cleaned to the point of coherency by the adopted UAT's page table as for every other firmware mapping. The graph records its profile's timestamp aperture, and the common GpuManager::map_timestamp_buffer maps into it: the native aperture as before, the 27.2 one for the 27.2 profile. The 27.2 backend delegates to it as it does for its parameters and clock, so timestamp buffers are bound, retained by the commands that name them and unmapped exactly as on the 13.5 path. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 9 ++++++--- drivers/gpu/drm/asahi/gpu.rs | 16 +++++++++++----- drivers/gpu/drm/asahi/gpu/v27_2.rs | 5 +++++ drivers/gpu/drm/asahi/mmu.rs | 15 ++++++++++++++- 4 files changed, 36 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 80698d66f8e6dc..dc150e8b99d766 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -340,6 +340,9 @@ pub(crate) fn start<'a>( gpu::GraphProfile::G14V27_2)?; let root = RootV27_2::build(&graph, &board)?; let pool = CommandPool::new(&mut gpu::GpuManager::alloc(&*graph), cfg)?; + // Timestamp buffers are bound in the timestamp aperture while the firmware runs, and the + // window only carries the tables that exist now: link the aperture's tables first. + graph.kernel_uat().prepare_kernel_tables(&[graph.timestamp_range()])?; window.mirror(graph.kernel_uat())?; window.install()?; window.announce(); @@ -1212,8 +1215,8 @@ impl gpu::Gpu for Backend { Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes, render)?, GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { - // Timestamp buffers would need new tables in the firmware window after boot. - Err(ENOTSUPP) + fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range) -> Result { + // The aperture's tables were linked before the firmware window was mirrored (start()). + ::map_timestamp_buffer(&self.graph, bo, range) } } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 9fed9e62ec3835..e153fc74904458 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -326,6 +326,8 @@ pub(crate) struct GpuManager { dyncfg: hw::DynConfig, pub(crate) initdata: fw::types::GpuObject, uat: mmu::Uat, + /// The firmware's timestamp aperture in the kernel VM, where timestamp buffers are bound. + timestamp_range: Range, crashed: AtomicBool, /// Set once the over-limit firmware-private garbage was reported as held. garbage_held: AtomicBool, @@ -746,10 +748,10 @@ impl GpuManager::ver { profile: GraphProfile, ) -> Result> { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; - let private_end = match profile { - GraphProfile::Native => IOVA_KERN_PRIV_RANGE.end, + let (private_end, timestamp_range) = match profile { + GraphProfile::Native => (IOVA_KERN_PRIV_RANGE.end, IOVA_KERN_TIMESTAMP_RANGE), #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] - GraphProfile::G14V27_2 => IOVA_G14_V27_2_TIMESTAMP_RANGE.start, + GraphProfile::G14V27_2 => (IOVA_G14_V27_2_TIMESTAMP_RANGE.start, IOVA_G14_V27_2_TIMESTAMP_RANGE), }; let mut alloc = KernelAllocators { @@ -828,7 +830,8 @@ impl GpuManager::ver { false, )?); - let mut mgr = Self::make_mgr(dev, cfg, dyncfg, uat, alloc, event_manager, initdata)?; + let mut mgr = Self::make_mgr(dev, cfg, dyncfg, uat, alloc, event_manager, initdata, + timestamp_range)?; { let fwctl = mgr.fwctl_channel.lock(); @@ -1005,6 +1008,7 @@ impl GpuManager::ver { /// /// Force disable inlining to avoid blowing up the stack. #[inline(never)] + #[allow(clippy::too_many_arguments)] fn make_mgr( dev: &AsahiDrmDevice, cfg: &'static hw::HwConfig, @@ -1013,6 +1017,7 @@ impl GpuManager::ver { mut alloc: KernelAllocators, event_manager: Arc, initdata: KBox>, + timestamp_range: Range, ) -> Result>> { let mut pipes = PipeChannels::ver { vtx: KVec::new(), @@ -1113,6 +1118,7 @@ impl GpuManager::ver { dyncfg: KBox::::into_inner(dyncfg), initdata: KBox::>::into_inner(initdata), uat: KBox::::into_inner(uat), + timestamp_range, io_mappings: KVec::new(), next_mmio_iova: IOVA_KERN_MMIO_RANGE.start, rtkit <- new_mutex!(None, "rtkit"), @@ -1787,7 +1793,7 @@ impl Gpu for GpuManager::ver { crate::timestamp::Buffer::firmware(bo.map_range_into_range( self.uat.kernel_vm(), range, - IOVA_KERN_TIMESTAMP_RANGE, + self.timestamp_range.clone(), mmu::UAT_PGSZ as u64, mmu::PROT_FW_SHARED_RW, false, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 12efdfff44584f..d4dcaa705c5b2c 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -530,6 +530,11 @@ impl GpuManagerG14V13_5 { pub(crate) fn kernel_uat(&self) -> &mmu::Uat { &self.uat } + + /// The firmware timestamp aperture that timestamp buffers are bound in. + pub(crate) fn timestamp_range(&self) -> Range { + self.timestamp_range.clone() + } } impl RootV27_2 { diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 3cca4f5a37fe6b..3930365aa4814a 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -3748,7 +3748,20 @@ impl Uat { /// Links the kernel lower root's tables for each range, with no mappings. A published-roots /// firmware samples that root's top-level entries only when it starts. pub(crate) fn prepare_lower_tables(&self, ranges: &[Range]) -> Result { - let mut inner = lock_vm(&self.kernel_lower_vm.gpuvm, None, false)?; + Self::prepare_tables(&self.kernel_lower_vm, ranges) + } + + /// Links the kernel window's tables for each range, with no mappings, for a firmware that + /// copies the window's second-level entries only when it starts + /// ([`FirmwareWindow::mirror`]). Page tables are only freed with their VM, so the leaf + /// tables stay where that copy names them. + #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] + pub(crate) fn prepare_kernel_tables(&self, ranges: &[Range]) -> Result { + Self::prepare_tables(&self.kernel_vm, ranges) + } + + fn prepare_tables(vm: &Vm, ranges: &[Range]) -> Result { + let mut inner = lock_vm(&vm.gpuvm, None, false)?; for range in ranges { inner.page_table.alloc_pages(range.clone())?; } From 7521672bcdc30572e3f42d2a71e7c3f86d567cae Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 00:49:04 +1100 Subject: [PATCH 1044/1514] drm/asahi: admit sampler heaps and helper programs on G14 firmware 27.2 The G14 firmware 27.2 runtime takes its client commands through the front end shared with the M3 runtime, whose 26.x commands stream their sampler state and carry no helper program, so that front end refuses both. On the M2 this refused every render command that names a sampler heap with ENOTSUPP: Zink renders through Borealis, which always names its heap, so Zink applications lost the device on their first such pass. Compute commands with a helper program, which Mesa uses for scratch and stack setup, were refused with EINVAL by the common compute translator. The G14 27.2 render builders already write the sampler heap and both helper programs where the 13.5 render commands keep them, and the 27.2 compute command carries the 13.5 compute JobParameters1, which holds the helper. Let a queue say that its builders encode these, as it already says which depth and stencil compression layouts it encodes, and set it for the G14 27.2 queues. Their render admission then checks the sampler heap like the compute translator does instead of refusing it, and their compute commands take the helper from the client and write it to the JobParameters1 places the 13.5 compute path fills. The vertex helper's configuration goes to the tiling parameters, as on 13.5. The M3 queues refuse both as before. The 27.2 compute command's sampler placement is not known, so compute commands with a sampler heap are still refused. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 1 + drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 27 +++++++++++++++++++++++ drivers/gpu/drm/asahi/g14_v27_2_render.rs | 2 ++ drivers/gpu/drm/asahi/gpu/v27_2.rs | 4 ++++ drivers/gpu/drm/asahi/m3/agx_compute.rs | 4 ++++ drivers/gpu/drm/asahi/m3/agx_uapi.rs | 2 +- drivers/gpu/drm/asahi/m3/m3_submit.rs | 24 +++++++++++++++----- 7 files changed, 57 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index dc150e8b99d766..5f18d886413dd0 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -705,6 +705,7 @@ impl Runtime { usc_base: control.usc_base, preempt, timestamps: packet.timestamp_addresses(index), + helper: control.helper, }; let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; let submission = state.root.stage_compute(command)?; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 1544c851b6dc32..dcd5392c0c1467 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -103,6 +103,8 @@ pub(crate) const GLOBALS_PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; /// after the command time (+0x2c4) and the internal start/end pointers (+0x2cc), the order of /// the 13.5 compute command and of the 27.2 render commands (vertex +0x5e4, fragment +0x948). pub(crate) const COMPUTE_USER_TIMESTAMPS: usize = 0x2dc; +/// The 13.5 compute JobParameters1 inside the 27.2 compute command. +pub(crate) const COMPUTE_JOB_PARAMETERS1: usize = 0x68; /// The value of a 27.2 Timestamp operation's user word: like the 13.5 and the M3 27.2 /// operations it names the command's start/end pair of user destinations, not a destination. @@ -119,6 +121,19 @@ fn put64(b: &mut [u8], at: usize, v: u64) { b[at..at + 8].copy_from_slice(&v.to_le_bytes()); } +fn put32(b: &mut [u8], at: usize, v: u32) { + b[at..at + 4].copy_from_slice(&v.to_le_bytes()); +} + +/// Writes a compute helper program (binary: USC offset | 1, data, configuration) into the +/// 13.5 JobParameters1 of a 27.2 compute command, at the places the 13.5 G14 compute path +/// fills: program +0x40, argument +0x48, configuration +0x50. +pub(crate) fn encode_compute_helper(cmd: &mut [u8], binary: u32, data: u64, config: u32) { + put32(cmd, COMPUTE_JOB_PARAMETERS1 + 0x40, binary); + put64(cmd, COMPUTE_JOB_PARAMETERS1 + 0x48, data); + put32(cmd, COMPUTE_JOB_PARAMETERS1 + 0x50, config); +} + /// Writes the user timestamp pair of a zeroed 27.2 compute command at `cmd_va` and returns the /// Timestamp operations' user word ([`user_timestamp_pointer`]). pub(crate) fn encode_compute_timestamps(cmd: &mut [u8], cmd_va: u64, timestamps: [u64; 2]) -> u64 { @@ -250,6 +265,18 @@ mod tests { && COMPUTE_WRITES.iter().all(|&(o, l)| o + l <= at || at + len <= o) } + #[test] + fn the_compute_helper_lands_in_free_job_parameters() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_helper(&mut cmd, 0x1235, 0x11_2233_4400, 0x7_0000); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + let read32 = |at: usize| u32::from_le_bytes(cmd[at..at + 4].try_into().unwrap()); + assert_eq!((read32(0xa8), read64(0xb0), read32(0xb8)), (0x1235, 0x11_2233_4400, 0x7_0000)); + for (at, len) in [(0xa8, 4), (0xb0, 8), (0xb8, 4)] { + assert!(free(at, len)); + } + } + #[test] fn a_timestamp_operation_names_the_pair_only_when_there_is_one() { assert_eq!(user_timestamp_pointer(0x1000, [0, 0]), 0); diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index cbbbd7febb8e59..ecf9e43bc9d866 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -92,6 +92,8 @@ fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { c.sample_size_B = r.sample_size; c.ppp_ctrl = r.ppp_control; c.ppp_multisamplectl = r.multisample_control; + // The tiling parameters carry the vertex helper's configuration, as in the 13.5 command. + c.vertex_helper.cfg = r.vertex_helper.config; c } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index d4dcaa705c5b2c..32f606d5066fd7 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -78,6 +78,8 @@ pub(crate) struct ComputeJob { pub(crate) preempt: u64, /// Firmware VAs of the user start and end timestamps, or 0. pub(crate) timestamps: [u64; 2], + /// The helper program (scratch and stack setup), or zero. + pub(crate) helper: crate::m3::agx_uapi::UapiHelperProgram, } fn put32(b: &mut [u8], at: usize, v: u32) { @@ -122,6 +124,7 @@ fn encode_compute( put32(cmd, 0x33c, 1); put64(cmd, 0x334, timestamps + 0x20); let user = g14_v27_2_abi::encode_compute_timestamps(cmd, cmd_va, job.timestamps); + g14_v27_2_abi::encode_compute_helper(cmd, job.helper.binary, job.helper.data, job.helper.config); put32(stream, 0, 11); // 13.5 StartCompute.unk_28, at the same place in this layout (the 13.5 G14 path writes 1). @@ -359,6 +362,7 @@ impl BootJob { let job = ComputeJob { context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, usc_base: 0x11_0000_0000, preempt: self.client_va, timestamps: [0; 2], + helper: crate::m3::agx_uapi::UapiHelperProgram { binary: 0, config: 0, data: 0 }, }; let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, diff --git a/drivers/gpu/drm/asahi/m3/agx_compute.rs b/drivers/gpu/drm/asahi/m3/agx_compute.rs index d58005c504f7ac..01c5354748a213 100644 --- a/drivers/gpu/drm/asahi/m3/agx_compute.rs +++ b/drivers/gpu/drm/asahi/m3/agx_compute.rs @@ -6,4 +6,8 @@ pub(crate) struct Control { pub base: u64, pub end: u64, pub usc_base: u64, + /// The helper program, zero unless the queue's command builder encodes it + /// (`m3_submit::Queue::samplers_and_helpers`). + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub helper: crate::m3::agx_uapi::UapiHelperProgram, } diff --git a/drivers/gpu/drm/asahi/m3/agx_uapi.rs b/drivers/gpu/drm/asahi/m3/agx_uapi.rs index 60107f8833edc2..028ac81193fbb2 100644 --- a/drivers/gpu/drm/asahi/m3/agx_uapi.rs +++ b/drivers/gpu/drm/asahi/m3/agx_uapi.rs @@ -574,7 +574,7 @@ impl QueueUscWindow { } } -fn validate_sampler( +pub(crate) fn validate_sampler( address_space: &A, heap: u64, count: u32, diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 5ba1f368798765..3ec3e7c00dbb3b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -318,6 +318,10 @@ pub(crate) struct Queue { /// for every sample count and layer count. Otherwise only the single-sample, /// single-layer compressed depth layout is admitted. zls_compression_all_layouts:bool, + /// Whether this queue's command builders encode the render sampler heap and the render and + /// compute helper programs, in the 13.5 places. Otherwise they are refused: the M3 26.x + /// commands stream their sampler state and carry no helper. + samplers_and_helpers:bool, urgency:u8, } impl Queue { @@ -331,7 +335,7 @@ impl Queue { 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,zls_compression_all_layouts:false,urgency,preempt_alloc:None, + early_tiling,wide_visibility,zls_compression_all_layouts:false,samplers_and_helpers:false,urgency,preempt_alloc:None, #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] render_queue: None}) } @@ -350,6 +354,10 @@ impl Queue { // The G14 render command carries the depth and stencil load, store and partial // compression words in every layout (g14_v27_2_render.rs). zls_compression_all_layouts:true, + // Its render commands carry the sampler heap and both helper programs, and its + // compute command the 13.5 compute JobParameters1 with the helper + // (g14_v27_2_render.rs, gpu/v27_2.rs). + samplers_and_helpers:true, urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), render_queue: Some(render_queue)}) } @@ -362,7 +370,7 @@ impl queue::Queue for Queue { while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling, - self.zls_compression_all_layouts) { + self.zls_compression_all_layouts,self.samplers_and_helpers) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); } @@ -390,6 +398,9 @@ impl queue::Queue for Queue { // The common translator validates the original command/attachment // addresses; this M3 scheduling hint changes none of them. payload.flags &= !wide; + // The common translator refuses helpers; a queue that encodes one takes it here. + let empty=agx_uapi::UapiHelperProgram{binary:0,config:0,data:0}; + let helper=if self.samplers_and_helpers {core::mem::replace(&mut payload.helper,empty)} else {empty}; render_attachments.push([crate::m3::agx_attachments::Attachments::EMPTY;2],GFP_KERNEL)?; flushes.push(encode_attachments(&self.vm,&attachments)?,GFP_KERNEL)?; let c=agx_uapi::translate_compute_command(payload,attachments, @@ -405,7 +416,7 @@ impl queue::Queue for Queue { } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; - commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc}),GFP_KERNEL)?; + commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc,helper}),GFP_KERNEL)?; } parser.finish().map_err(|_|EINVAL)?; let preempt=match &self.preempt_alloc { @@ -449,7 +460,7 @@ fn encode_attachments(vm: &mmu::Vm, list: &agx_uapi::UapiAttachmentList) } fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpace<'_>, - early_tiling: bool, zls_compression_all_layouts: bool) -> Result { + early_tiling: bool, zls_compression_all_layouts: bool, samplers_and_helpers: bool) -> Result { use agx_uapi::{GpuAddressSpace, GpuAccess}; if r.sample_size % 8 != 0 {return Err(ENOTSUPP);} let empty = agx_uapi::UapiHelperProgram { binary:0, config:0, data:0 }; @@ -459,8 +470,8 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] let stage_scope = { let _ = early_tiling; 0 }; if r.flags & !(2|16|(1<<18)|stage_scope) != 0 || !matches!(r.samples, 1 | 2 | 4) - || r.sampler_count != 0 || r.sampler_heap != 0 - || r.vertex_helper != empty || r.fragment_helper != empty + || (!samplers_and_helpers && (r.sampler_count != 0 || r.sampler_heap != 0 + || r.vertex_helper != empty || r.fragment_helper != empty)) || (!zls_compression_all_layouts && (r.stencil.compression_base != 0 || r.stencil.compression_stride != 0)) || r.ppp_control & !0x203 != 0 { return Err(ENOTSUPP); } @@ -475,6 +486,7 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac || u32::from(r.sample_size)*u32::from(r.utile_width)*u32::from(r.utile_height)*u32::from(r.samples)>32768 { return Err(EINVAL); } + agx_uapi::validate_sampler(space, r.sampler_heap, r.sampler_count.into()).map_err(|_| EINVAL)?; crate::m3::agx_render_state::compact(r.vdm_base).map_err(|_| EINVAL)?; if r.vdm_base & 3 != 0 || !space.covers(r.vdm_base,4,GpuAccess::Read) || r.scissor_base == 0 || r.scissor_base & 7 != 0 || !space.covers(r.scissor_base,8,GpuAccess::Read) { From edf11ddd623bf71e8d044148025eab45b949ef8c Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 09:29:53 -0500 Subject: [PATCH 1045/1514] ASoC: apple: t8152-aop-audio: serve speaker sense from a driver-owned ring On T8142 and T6050 multi-amp speaker streams, the AOP firmware's serializer carries 8 or 12 16-bit V/I sense slots back on base-ns ADMAC RX with no hardware frame-start marker. Previously, the sense front-end opened the ADMAC channel directly and realigned it only when speaker playback prepared a stopped serializer. When PipeWire stops, prepares and restarts the sense front-end while the speaker serializer is already running in pwrd (which happens deterministically on stream start and on any capture XRUN recovery), the ADMAC RX channel restarts mid-frame at an arbitrary 16-bit word offset modulo the channel count, misattributing V/I sense samples across amplifiers. Move multi-amp sense capture onto a driver-owned cyclic ring (SenseRing, matching aop_spkr.rs): - Arm the ADMAC RX ring on the stopped serializer immediately before every spkr pwrd transition so ring offset 0 is always slot 0 of a frame, and stop it after pw0 (releasing the ring and channel on spkr shutdown while the fabric is still powered). - On a playback re-prepare while spkr is already running, mute the speaker codecs before cycling pw0 -> ring start -> pwrd (propagating any mute error to abort the clock transition so amps never see BCLK stop while active), and drop PAUSE/RESUME on playback so the playback DMA never resumes mid-frame either. - Deliver whole-frame chunks in 2.5 ms (120-frame) periods from the 80 ms ring to the attached VMALLOC sense front-end; signal XRUN before copying if the incoming frames would overrun unread capture data in the ALSA buffer, and re-check ring lap timing after the copy before publishing the updated front-end pointer. - Keep the mono T8152 (sense_ring = false) path unchanged. Signed-off-by: Erik Bourget --- sound/soc/apple/t8152_aop_audio.rs | 924 ++++++++++++++++++++++++++--- 1 file changed, 835 insertions(+), 89 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index b3286d1f014194..a586570d67ec3f 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -19,28 +19,36 @@ //! `pw0 ` (which also brings up the audio fabric), prepare requests `pwrd` //! (the firmware then runs the serializer and its clocks) and shutdown goes //! back to `pw0 `. On T8152 and T8142 the serializer (MCA) leaves are the -//! AP's to power; on T6050 the firmware powers them itself. The -//! front-end PCMs are plain dmaengine PCMs on the base-ns channels; macaudio -//! links them to the codecs. +//! AP's to power; on T6050 the firmware powers them itself. The front-end PCMs +//! are plain dmaengine PCMs on the base-ns channels except for speaker V/I +//! sense on multi-amp streams, which is served from a driver-owned cyclic ring +//! (`SenseRing`) armed on the stopped serializer before every `pwrd` so sense +//! capture starts and restarts stay frame-aligned. Macaudio links them to the +//! codecs. //! //! Copyright (C) The Asahi Linux Contributors //! Copyright (C) 2026 The Aurora Silicon Contributors -use core::{mem, ptr, slice}; +use core::{ + ffi::c_void, + mem, ptr, slice, + sync::atomic::{ + fence, AtomicBool, AtomicI32, AtomicI64, AtomicPtr, AtomicU64, AtomicUsize, Ordering, + }, +}; use kernel::{ - bindings, c_str, - device, + bindings, c_str, device, device::Core, error::from_err_ptr, - module_platform_driver, of, platform, + module_platform_driver, new_mutex, of, platform, prelude::*, soc::apple::aop::{from_fourcc, EPICService, AOP}, str::CString, sync::{ aref::ARef, atomic::{Atomic, AtomicFlag, Relaxed}, - Arc, ArcBorrow, + Arc, ArcBorrow, Mutex, }, types::{ForeignOwnable, Opaque}, workqueue::{self, impl_has_work, new_work, Work, WorkItem}, @@ -227,6 +235,439 @@ impl Service { } } +/// Serialized power state of the speaker back-end (`spkr`). +struct SpkrState { + open: bool, + running: bool, + resume_run: bool, +} + +const SENSE_RATE: u64 = 48000; +const NSEC_PER_SEC: u64 = 1_000_000_000; +/// 2.5 ms periods (120 frames at 48 kHz), 32 of them: an 80 ms ring, delivered +/// in whole-frame chunks small enough that a 512-frame front-end period +/// completes well within its headroom. Both 8-channel (16 B/frame -> 1920 B) +/// and 12-channel (24 B/frame -> 2880 B) periods stay aligned to whole frames +/// and to the ADMAC's 48-byte RX FIFO threshold. +const SENSE_RING_PERIOD_FRAMES: usize = 120; +const SENSE_RING_PERIODS: usize = 32; +const SENSE_RING_FRAMES: usize = SENSE_RING_PERIOD_FRAMES * SENSE_RING_PERIODS; +const SENSE_RING_NS: u64 = SENSE_RING_FRAMES as u64 * NSEC_PER_SEC / SENSE_RATE; +const SENSE_RING_PERIOD_NS: u64 = SENSE_RING_PERIOD_FRAMES as u64 * NSEC_PER_SEC / SENSE_RATE; +/// SNDRV_PCM_STATE_RUNNING and _XRUN (cast macros the bindings do not carry). +const PCM_STATE_RUNNING: bindings::snd_pcm_state_t = 3; +const PCM_STATE_XRUN: bindings::snd_pcm_state_t = 4; + +/// The ring may have gone round once or more in `elapsed_ns` since the last +/// callback: its position alone cannot tell a lap from no advance, or two laps +/// from one. The DMA runs at the sense rate and its reported position lags it +/// by less than a ring period, so a lap needs at least the ring's time less a +/// period. +fn sense_ring_may_lap(elapsed_ns: i64) -> bool { + elapsed_ns < 0 || elapsed_ns as u64 + SENSE_RING_PERIOD_NS >= SENSE_RING_NS +} + +/// Returns whether `incoming` frames fit strictly inside the capture front-end +/// ring buffer of `buffer_frames` without overwriting unread frames +/// (`unread_alsa`) or frames already copied since the last pointer sync +/// (`pending`), and without advancing the modulo pointer back to the same +/// position (an exact full-buffer advance is ambiguous to ALSA's pointer check). +fn sense_ring_has_fe_space( + buffer_frames: usize, + unread_alsa: usize, + pending: usize, + incoming: usize, +) -> bool { + unread_alsa + .checked_add(pending) + .and_then(|used| used.checked_add(incoming)) + .is_some_and(|total| total < buffer_frames) +} + +/// The driver-owned speaker sense capture (base-ns ADMAC RX): a cyclic ring +/// armed on the stopped serializer before every `pwrd`, so ring offset 0 is +/// slot 0 of a frame and every whole-frame offset is a frame start. The sense +/// front-end copies whole frames out of this ring instead of starting or +/// stopping the ADMAC channel while the serializer runs, which otherwise slips +/// the V/I sense slots modulo the channel count. +/// +/// The ring fields change only with the channel stopped and synchronized (no +/// callback runs); `start` publishes them before the channel starts. +struct SenseRing { + frame_bytes: usize, + chan: AtomicPtr, + cpu: AtomicPtr, + handle: AtomicU64, + cookie: AtomicI32, + /// Ring offset (a whole frame) up to which the callback has consumed the data. + done: AtomicUsize, + /// When `done` was last moved (or the ring started), CLOCK_MONOTONIC ns. + done_at: AtomicI64, + /// The attached sense front-end, or null; cleared under that front-end's + /// stream lock, which the callback holds while it uses the front-end. + sub: AtomicPtr, + /// Frames delivered to the front-end since its start; changed under its + /// stream lock. + fe_pos: AtomicUsize, + /// The front-end runs (its trigger sets this under the stream lock). + fe_running: AtomicBool, +} + +impl SenseRing { + fn new(frame_bytes: usize) -> Self { + Self { + frame_bytes, + chan: AtomicPtr::new(ptr::null_mut()), + cpu: AtomicPtr::new(ptr::null_mut()), + handle: AtomicU64::new(0), + cookie: AtomicI32::new(0), + done: AtomicUsize::new(0), + done_at: AtomicI64::new(0), + sub: AtomicPtr::new(ptr::null_mut()), + fe_pos: AtomicUsize::new(0), + fe_running: AtomicBool::new(false), + } + } + + fn period_bytes(&self) -> usize { + SENSE_RING_PERIOD_FRAMES * self.frame_bytes + } + + fn ring_bytes(&self) -> usize { + SENSE_RING_FRAMES * self.frame_bytes + } + + /// Requests the channel and the ring (once per speaker session) and starts + /// the cyclic transfer. The caller holds `spkr_state` with the fabric + /// powered and the serializer stopped (`pw0 `). + fn start(&self, dev: &device::Device) -> Result<()> { + let ring_bytes = self.ring_bytes(); + let period_bytes = self.period_bytes(); + let mut chan = self.chan.load(Ordering::Acquire); + if chan.is_null() { + // SAFETY: the device is live and the name is NUL-terminated. + chan = from_err_ptr(unsafe { + bindings::dma_request_chan(dev.as_raw(), c"sense".as_char_ptr()) + })?; + let mut handle: bindings::dma_addr_t = 0; + // SAFETY: the channel's device is the ADMAC; it outlives the ring, + // which `release` frees before releasing the channel. + let cpu = unsafe { + bindings::dma_alloc_attrs( + (*(*chan).device).dev, + ring_bytes, + &mut handle, + bindings::GFP_KERNEL, + 0, + ) + }; + if cpu.is_null() { + // SAFETY: requested above, unused. + unsafe { bindings::dma_release_channel(chan) }; + return Err(ENOMEM); + } + self.cpu.store(cpu.cast(), Ordering::Release); + self.handle.store(handle as u64, Ordering::Release); + self.chan.store(chan, Ordering::Release); + } + let handle = self.handle.load(Ordering::Acquire) as bindings::dma_addr_t; + let mut cfg = bindings::dma_slave_config::default(); + cfg.direction = bindings::dma_transfer_direction_DMA_DEV_TO_MEM; + cfg.src_addr_width = bindings::dma_slave_buswidth_DMA_SLAVE_BUSWIDTH_2_BYTES; + cfg.src_port_window_size = 4; + // SAFETY: `chan` is our live, stopped channel; the descriptor is ours + // until submitted. + unsafe { + let dma = (*chan).device; + let ret = match (*dma).device_config { + Some(f) => f(chan, &mut cfg), + None => ENOSYS.to_errno(), + }; + if ret < 0 { + return Err(Error::from_errno(ret)); + } + let prep = (*dma).device_prep_dma_cyclic.ok_or(ENOSYS)?; + let desc = prep( + chan, + handle, + ring_bytes, + period_bytes, + bindings::dma_transfer_direction_DMA_DEV_TO_MEM, + bindings::dma_ctrl_flags_DMA_PREP_INTERRUPT as _, + ); + if desc.is_null() { + return Err(EIO); + } + (*desc).callback = Some(sense_ring_done); + (*desc).callback_param = ptr::from_ref(self).cast_mut().cast(); + self.done.store(0, Ordering::Release); + // SAFETY: no preconditions. + self.done_at.store(bindings::ktime_get(), Ordering::Release); + let cookie = ((*desc).tx_submit.ok_or(EIO)?)(desc); + if cookie < 0 { + return Err(Error::from_errno(cookie)); + } + self.cookie.store(cookie, Ordering::Release); + if let Some(f) = (*dma).device_issue_pending { + f(chan); + } + } + Ok(()) + } + + /// Stops the transfer and waits for its callback; a no-op without a channel. + fn stop(&self) { + let chan = self.chan.load(Ordering::Acquire); + if chan.is_null() { + return; + } + // SAFETY: our live channel; terminate and synchronize are valid on an + // idle channel too. + unsafe { + let dma = (*chan).device; + if let Some(f) = (*dma).device_terminate_all { + f(chan); + } + if let Some(f) = (*dma).device_synchronize { + f(chan); + } + } + } + + /// Stops, then frees the ring and releases the channel (with the fabric + /// still powered). + fn release(&self) { + self.stop(); + let chan = self.chan.swap(ptr::null_mut(), Ordering::AcqRel); + if chan.is_null() { + return; + } + // SAFETY: the transfer is stopped and synchronized; the ring was + // allocated on this channel's device in `start`. + unsafe { + bindings::dma_free_attrs( + (*(*chan).device).dev, + self.ring_bytes(), + self.cpu.swap(ptr::null_mut(), Ordering::AcqRel).cast(), + self.handle.load(Ordering::Acquire) as bindings::dma_addr_t, + 0, + ); + bindings::dma_release_channel(chan); + } + } + + fn attach(&self, substream: *mut bindings::snd_pcm_substream) { + self.fe_running.store(false, Ordering::Relaxed); + self.fe_pos.store(0, Ordering::Relaxed); + self.sub.store(substream, Ordering::Release); + } + + /// Detaches the front-end under its stream lock: a callback that read the + /// pointer before takes the same lock, sees the front-end gone and leaves + /// it alone. + /// + /// # Safety + /// + /// `substream` must be the attached front-end, in its close. + unsafe fn detach(&self, substream: *mut bindings::snd_pcm_substream) { + // SAFETY: by the caller's contract. + unsafe { + let flags = bindings::_snd_pcm_stream_lock_irqsave(substream); + self.sub.store(ptr::null_mut(), Ordering::Release); + self.fe_running.store(false, Ordering::Relaxed); + bindings::snd_pcm_stream_unlock_irqrestore(substream, flags); + } + } + + /// Copies `bytes` (whole frames) from ring offset `from` into a running + /// front-end's buffer. + /// + /// # Safety + /// + /// `sub` must be a substream this ring had attached. The substream itself + /// belongs to the PCM and outlives the ring's use of it: the ring stops + /// and synchronizes with this callback before the card can go away. + unsafe fn deliver( + &self, + sub: *mut bindings::snd_pcm_substream, + from: usize, + bytes: usize, + last_ns: i64, + ) { + let frame_bytes = self.frame_bytes; + let ring_bytes = self.ring_bytes(); + // SAFETY: by the caller's contract; the stream lock orders this with + // the trigger, the pointer callback and `detach`. + let flags = unsafe { bindings::_snd_pcm_stream_lock_irqsave(sub) }; + let rt = if self.sub.load(Ordering::Acquire) == sub { + // SAFETY: still attached under the lock; the runtime lives until + // after the front-end's close. + unsafe { (*sub).runtime } + } else { + ptr::null_mut() + }; + // SAFETY: an attached front-end's runtime (see above). + if !rt.is_null() + && self.fe_running.load(Ordering::Relaxed) + && unsafe { (*rt).state } == PCM_STATE_RUNNING + && unsafe { (*rt).frame_bits } as usize == frame_bytes * 8 + { + // SAFETY: no preconditions. + if sense_ring_may_lap(unsafe { bindings::ktime_get() } - last_ns) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + // SAFETY: as above; status and control are valid while running. + let (area, frames, period, hw_ptr, appl_ptr, boundary) = unsafe { + ( + (*rt).dma_area, + (*rt).buffer_size as usize, + (*rt).period_size as usize, + (*(*rt).status).hw_ptr as usize, + (*(*rt).control).appl_ptr as usize, + (*rt).boundary as usize, + ) + }; + let ring = self.cpu.load(Ordering::Acquire); + let incoming = bytes / frame_bytes; + if !area.is_null() && !ring.is_null() && frames > 0 && incoming > 0 { + let mut pos = self.fe_pos.load(Ordering::Relaxed); + let unread_alsa = if hw_ptr >= appl_ptr { + hw_ptr - appl_ptr + } else if boundary > 0 { + hw_ptr + boundary - appl_ptr + } else { + frames + }; + let pending = (pos % frames + frames - hw_ptr % frames) % frames; + if !sense_ring_has_fe_space(frames, unread_alsa, pending, incoming) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + let first = pos; + let mut src = from; + let mut left = incoming; + while left > 0 { + let off = pos % frames; + let n = left.min(frames - off).min((ring_bytes - src) / frame_bytes); + // SAFETY: `n` frames fit at `off` in the front-end + // buffer and at `src` in the ring; post-copy lap + // validation below rejects the batch if DMA could + // have reached `from` before the copy finished. + unsafe { + ptr::copy_nonoverlapping( + ring.add(src), + area.add(off * frame_bytes), + n * frame_bytes, + ) + }; + pos += n; + left -= n; + src = (src + n * frame_bytes) % ring_bytes; + } + fence(Ordering::Acquire); + // SAFETY: no preconditions. + if sense_ring_may_lap(unsafe { bindings::ktime_get() } - last_ns) { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } else { + self.fe_pos.store(pos, Ordering::Relaxed); + if first / period.max(1) != pos / period.max(1) { + // SAFETY: a running, attached front-end, under its stream lock. + unsafe { bindings::snd_pcm_period_elapsed_under_stream_lock(sub) }; + } + } + } + } + } + } + // SAFETY: locked above. + unsafe { bindings::snd_pcm_stream_unlock_irqrestore(sub, flags) }; + } + + /// The ring may have lapped since the last callback: stop a running + /// front-end with an XRUN rather than delivering frames shifted in time + /// against playback. + /// + /// # Safety + /// + /// As for [`SenseRing::deliver`]. + unsafe fn lost(&self, sub: *mut bindings::snd_pcm_substream) { + // SAFETY: as in `deliver`. + let flags = unsafe { bindings::_snd_pcm_stream_lock_irqsave(sub) }; + if self.sub.load(Ordering::Acquire) == sub && self.fe_running.load(Ordering::Relaxed) { + // SAFETY: an attached front-end, under its stream lock; its + // runtime lives until after its close. + let rt = unsafe { (*sub).runtime }; + // SAFETY: as above. + if !rt.is_null() && unsafe { (*rt).state } == PCM_STATE_RUNNING { + // SAFETY: a running front-end, under its stream lock. + unsafe { bindings::snd_pcm_stop(sub, PCM_STATE_XRUN) }; + } + } + // SAFETY: locked above. + unsafe { bindings::snd_pcm_stream_unlock_irqrestore(sub, flags) }; + } +} + +/// The ring's period callback (the ADMAC tasklet): hands the whole frames +/// written since the last call to a running sense front-end, or drops them. +/// +/// # Safety +/// +/// `param` is the `SenseRing` that set up the transfer; `stop` synchronizes +/// with this callback before the ring changes or goes away. +unsafe extern "C" fn sense_ring_done(param: *mut c_void) { + // SAFETY: by the function's contract. + let ring = unsafe { &*param.cast::() }; + let chan = ring.chan.load(Ordering::Acquire); + if chan.is_null() { + return; + } + let mut state = bindings::dma_tx_state { + last: 0, + used: 0, + residue: 0, + in_flight_bytes: 0, + }; + // SAFETY: our live channel and cookie. + let status = unsafe { + match (*(*chan).device).device_tx_status { + Some(f) => f(chan, ring.cookie.load(Ordering::Acquire), &mut state), + None => return, + } + }; + // SAFETY: no preconditions. + let now_ns = unsafe { bindings::ktime_get() }; + let ring_bytes = ring.ring_bytes(); + let frame_bytes = ring.frame_bytes; + let residue = state.residue as usize; + if status == bindings::dma_status_DMA_ERROR || residue > ring_bytes { + return; + } + // The device wrote everything up to here before it reported the residue. + fence(Ordering::SeqCst); + let now = (ring_bytes - residue) % ring_bytes / frame_bytes * frame_bytes; + let from = ring.done.swap(now, Ordering::AcqRel); + let last_ns = ring.done_at.swap(now_ns, Ordering::AcqRel); + let sub = ring.sub.load(Ordering::Acquire); + if sense_ring_may_lap(now_ns - last_ns) { + if !sub.is_null() { + // SAFETY: a substream the ring had attached (`lost` re-checks under its lock). + unsafe { ring.lost(sub) }; + } + return; + } + let bytes = (now + ring_bytes - from) % ring_bytes; + if bytes == 0 { + return; + } + if !sub.is_null() { + // SAFETY: a substream the ring had attached (`deliver` re-checks under its lock). + unsafe { ring.deliver(sub, from, bytes, last_ns) }; + } +} + #[pin_data] struct T8152AopAudio { dev: ARef, @@ -235,10 +676,12 @@ struct T8152AopAudio { cout: Service, cin: Service, spkr: Service, + #[pin] + spkr_state: Mutex, + /// Driver-owned cyclic sense ring when the speaker stream returns V/I sense. + sense_ring: Option, mca: KVec, cfg: &'static HwConfig, - /// The open sense capture front-end, if any. - sense: Atomic<*mut bindings::snd_pcm_substream>, hpai: Service, /// The microphone array's leaves (`LEAP_NAMES`); empty without one. leap: KVec, @@ -404,66 +847,133 @@ impl T8152AopAudio { Ok(()) } - /// The sense capture's back-end. Its front-end requests the ADMAC - /// channel next, and the ADMAC only answers while the firmware holds - /// the audio fabric up, which it does while a service is in `pw0 ` or - /// `pwrd`. Opening the sense before any other stream since boot (as - /// speakersafetyd does) otherwise faults the bus (SError). Shutdown - /// leaves the service in `pw0 `, as the other streams do. + /// The sense capture's back-end. Opening the sense before any other stream + /// since boot attaches `spkr` and raises `pw0 ` so the audio fabric is up + /// without disturbing an already-running speaker stream. fn sense_startup(&self) -> Result<()> { + let st = self.spkr_state.lock(); self.attach(&self.spkr)?; - if !self.spkr.running.load(Relaxed) { + if !st.running { self.set_power(&self.spkr, POWER_STATE_PW0)?; } Ok(()) } - /// `pwrd`: the firmware starts the serializer clocks and the stream. - fn run(&self, svc: &Service) -> Result<()> { - if svc.running.load(Relaxed) { - return Ok(()); + fn spkr_startup(&self) -> Result<()> { + let mut st = self.spkr_state.lock(); + self.attach(&self.spkr)?; + self.set_power(&self.spkr, POWER_STATE_PW0)?; + if let Err(e) = self.mca_up() { + let _ = self.set_power(&self.spkr, POWER_STATE_PW0); + return Err(e); } - if ptr::eq(svc, &self.spkr) && self.cfg.realign_sense { - self.realign_sense(); + st.open = true; + st.running = false; + st.resume_run = false; + self.spkr.running.store(false, Relaxed); + Ok(()) + } + + /// Arms the sense ring on the stopped serializer, then raises `pwrd`. + fn spkr_start_with_ring(&self, st: &mut SpkrState, ring: &SenseRing) -> Result<()> { + ring.stop(); + ring.start(&self.dev)?; + if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PWRD) { + ring.stop(); + return Err(e); } - self.set_power(svc, POWER_STATE_PWRD)?; - svc.running.store(true, Relaxed); + st.running = true; + self.spkr.running.store(true, Relaxed); Ok(()) } - /// Before the speaker's serializer starts, restart a running sense - /// capture at a frame boundary. The sense words are the serializer's RX, - /// which the firmware stops anywhere in a frame; a capture that stays - /// open across speaker streams (speakersafetyd keeps it) would carry - /// the partial frame forward and attribute one amplifier's voltage and - /// current to another. Nothing flows while the serializer is stopped, - /// so this loses no data; the partial frame reads as zeros. - fn realign_sense(&self) { - let ss = self.sense.load(Relaxed); - if ss.is_null() { + /// Speaker prepare: when a sense ring is in use, every playback prepare + /// starts a fresh serializer with the ring armed first so offset 0 is slot + /// 0 of a frame. If the serializer was still running (re-prepare after an + /// underrun or resume), `quiesce` mutes the amps before stopping the clock. + fn spkr_prepare(&self, quiesce: impl FnOnce() -> Result<()>) -> Result<()> { + let mut st = self.spkr_state.lock(); + let Some(ring) = &self.sense_ring else { + if !st.running { + self.set_power(&self.spkr, POWER_STATE_PWRD)?; + st.running = true; + self.spkr.running.store(true, Relaxed); + } + return Ok(()); + }; + if st.running { + quiesce()?; + self.set_power(&self.spkr, POWER_STATE_PW0)?; + st.running = false; + self.spkr.running.store(false, Relaxed); + } + self.spkr_start_with_ring(&mut st, ring) + } + + fn spkr_stop_locked(&self, st: &mut SpkrState) { + if st.running { + if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PW0) { + dev_err!(self.dev, "spkr: pw0 failed: {:?}\n", e); + } + st.running = false; + self.spkr.running.store(false, Relaxed); + } + if let Some(ring) = &self.sense_ring { + ring.stop(); + } + } + + fn spkr_hw_free(&self) { + if self.sense_ring.is_none() { return; } - // SAFETY: the sense front-end's open and close and this back-end's - // prepare all run under the card's DPCM mutex, so `ss` is live; its - // stream lock orders this against the front-end's trigger. - unsafe { - bindings::snd_pcm_stream_lock_irq(ss); - let rt = (*ss).runtime; - if !rt.is_null() && (*rt).state == SNDRV_PCM_STATE_RUNNING { - let chan = bindings::snd_dmaengine_pcm_get_chan(ss); - let ops = &*(*chan).device; - if let (Some(pause), Some(resume)) = (ops.device_pause, ops.device_resume) { - pause(chan); - let frame = ((*rt).frame_bits / 8) as usize; - let pos = bindings::snd_dmaengine_pcm_pointer(ss) as usize; - if frame != 0 && pos < (*rt).buffer_size as usize && !(*rt).dma_area.is_null() { - ptr::write_bytes((*rt).dma_area.add(pos * frame), 0, frame); - } - resume(chan); - } + let mut st = self.spkr_state.lock(); + self.spkr_stop_locked(&mut st); + } + + fn spkr_shutdown(&self) { + { + let mut st = self.spkr_state.lock(); + st.open = false; + st.resume_run = false; + self.spkr_stop_locked(&mut st); + // Release the ring and its ADMAC channel while the fabric is still + // powered (`pw0 `) and before the MCA leaves power down. + if let Some(ring) = &self.sense_ring { + ring.release(); } - bindings::snd_pcm_stream_unlock_irq(ss); } + self.mca_down(); + } + + fn spkr_suspend(&self) { + if self.sense_ring.is_none() { + return; + } + let mut st = self.spkr_state.lock(); + st.resume_run = st.running; + self.spkr_stop_locked(&mut st); + } + + fn spkr_resume(&self) -> Result<()> { + let Some(ring) = &self.sense_ring else { + return Ok(()); + }; + let mut st = self.spkr_state.lock(); + if !mem::take(&mut st.resume_run) || !st.open { + return Ok(()); + } + self.spkr_start_with_ring(&mut st, ring) + } + + /// `pwrd`: the firmware starts the serializer clocks and the stream. + fn run(&self, svc: &Service) -> Result<()> { + if svc.running.load(Relaxed) { + return Ok(()); + } + self.set_power(svc, POWER_STATE_PWRD)?; + svc.running.store(true, Relaxed); + Ok(()) } /// The clocks run from prepare on: the codecs see a bit clock as soon @@ -550,8 +1060,6 @@ const FORMATS: u64 = bindings::BINDINGS_SNDRV_PCM_FMTBIT_S24_LE; /// SNDRV_PCM_FMTBIT_S16_LE (1 << SNDRV_PCM_FORMAT_S16_LE), which the /// bindings do not export. const FMTBIT_S16_LE: u64 = 1 << 2; -/// SNDRV_PCM_STATE_RUNNING, likewise. -const SNDRV_PCM_STATE_RUNNING: bindings::snd_pcm_state_t = 3; /// What differs between the machines: the shape of the firmware's `spkr` /// stream (ADT iop-audio-controller/audio-speaker). @@ -561,9 +1069,9 @@ struct HwConfig { /// Words the amplifiers send back on the stream's RX side (V/I sense). sense_channels: u32, sense_formats: u64, - /// The sense capture is the speaker stream's RX: restart it at a frame - /// boundary whenever the speaker starts (see `realign_sense`). - realign_sense: bool, + /// The sense capture is the speaker stream's RX: serve it from a + /// driver-owned cyclic ring armed before every `pwrd` (see `SenseRing`). + sense_ring: bool, /// The AP powers the serializer (MCA) leaves. ap_mca: bool, /// The AP powers the microphone array's LEAP leaves. Without it the @@ -577,7 +1085,7 @@ static HW_CFG_T8152: HwConfig = HwConfig { spkr_channels: 1, sense_channels: 2, sense_formats: FORMATS, - realign_sense: false, + sense_ring: false, ap_mca: true, ap_leap: true, }; @@ -589,19 +1097,19 @@ static HW_CFG_T8142: HwConfig = HwConfig { spkr_channels: 4, sense_channels: 8, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: true, ap_leap: true, }; -/// J714s: six amplifiers in 32-bit slots 0-5, their voltage and current -/// sense back as twelve 16-bit slots on the stream's RX, as on J813. The -/// MCA and LEAP leaves have no AP power state: the firmware powers them. +/// J714s / J716c: six amplifiers in 32-bit slots 0-5, their voltage and +/// current sense back as twelve 16-bit slots on the stream's RX, as on J813. +/// The MCA and LEAP leaves have no AP power state: the firmware powers them. static HW_CFG_T6050: HwConfig = HwConfig { spkr_channels: 6, sense_channels: 12, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: false, ap_leap: false, }; @@ -615,7 +1123,7 @@ static HW_CFG_T8142_6AMP: HwConfig = HwConfig { spkr_channels: 6, sense_channels: 12, sense_formats: FMTBIT_S16_LE, - realign_sense: true, + sense_ring: true, ap_mca: true, ap_leap: true, }; @@ -749,6 +1257,54 @@ unsafe fn dmaengine_open( } } +/// The sense ring behind a front-end substream, `None` for every other stream. +/// +/// # Safety +/// +/// `component` must be this driver's live registered component and `substream` +/// a live substream of one of its links. +unsafe fn sense_ring<'a>( + component: *mut bindings::snd_soc_component, + substream: *mut bindings::snd_pcm_substream, +) -> Option<&'a SenseRing> { + // SAFETY: by the caller's contract. + let (data, rtd) = unsafe { (component_data(component), substream_rtd(substream)) }; + // SAFETY: as above. + if unsafe { rtd_is_be(rtd) || is_playback(substream) } { + return None; + } + // SAFETY: as above. + if unsafe { fe_index(rtd) } != Some(2) { + return None; + } + data.sense_ring.as_ref() +} + +/// The sense front-end's buffer: plain memory the ring callback copies whole +/// frames into. +fn sense_open(substream: *mut bindings::snd_pcm_substream, formats: u64) -> i32 { + // SAFETY: a live substream in its open. + unsafe { + if (*substream).dma_buffer.dev.type_ == bindings::SNDRV_DMA_TYPE_UNKNOWN as i32 { + let ret = bindings::snd_pcm_set_managed_buffer( + substream, + bindings::SNDRV_DMA_TYPE_VMALLOC as i32, + ptr::null_mut(), + 0, + 0, + ); + if ret < 0 { + return ret; + } + } + let mut hw = pcm_hw(); + hw.info |= bindings::SNDRV_PCM_INFO_BLOCK_TRANSFER | bindings::SNDRV_PCM_INFO_BATCH; + hw.formats = formats; + (*(*substream).runtime).hw = hw; + } + 0 +} + /// # Safety /// /// Called by ASoC on this driver's component with live arguments. @@ -773,6 +1329,16 @@ unsafe extern "C" fn asoc_pcm_open( let Some(name) = FE_DMA_NAMES[fe][usize::from(!playback)] else { return ENODEV.to_errno(); }; + if fe == 2 && !playback { + if let Some(ring) = &data.sense_ring { + let ret = sense_open(substream, data.cfg.sense_formats); + if ret < 0 { + return ret; + } + ring.attach(substream); + return 0; + } + } // SAFETY: the device is live and the name is NUL-terminated. let chan = match from_err_ptr(unsafe { bindings::dma_request_chan(data.dev.as_raw(), name.as_char_ptr()) @@ -789,8 +1355,14 @@ unsafe extern "C" fn asoc_pcm_open( if ret < 0 { // SAFETY: the open failed, so the channel is still ours. unsafe { bindings::dma_release_channel(chan) }; - } else if fe == 2 && !playback { - data.sense.store(substream, Relaxed); + } else if fe == 1 && playback && data.sense_ring.is_some() { + // The playback slots line up only when prepare starts a fresh + // serializer: a paused DMA restarted mid-frame would shift them. + // SAFETY: `dmaengine_open` initialized the runtime above. + unsafe { + (*(*substream).runtime).hw.info &= + !(bindings::SNDRV_PCM_INFO_PAUSE | bindings::SNDRV_PCM_INFO_RESUME); + } } ret } @@ -807,9 +1379,10 @@ unsafe extern "C" fn asoc_pcm_close( return 0; } // SAFETY: as above. - let data = unsafe { component_data(component) }; - if data.sense.load(Relaxed) == substream { - data.sense.store(ptr::null_mut(), Relaxed); + if let Some(ring) = unsafe { sense_ring(component, substream) } { + // SAFETY: the attached sense front-end, in its close. + unsafe { ring.detach(substream) }; + return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_close_release_chan(substream) } @@ -824,7 +1397,8 @@ unsafe extern "C" fn asoc_pcm_hw_params( params: *mut bindings::snd_pcm_hw_params, ) -> i32 { // SAFETY: by the caller's contract. - if unsafe { rtd_is_be(substream_rtd(substream)) } { + if unsafe { rtd_is_be(substream_rtd(substream)) || sense_ring(component, substream).is_some() } + { return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. @@ -849,15 +1423,6 @@ unsafe extern "C" fn asoc_pcm_hw_params( } else { cfg.src_port_window_size = window; } - // The sense capture: the frame size its channel restarts aligned to - // (apple-admac reads a u32 here; see `realign_sense`). - // SAFETY: by the caller's contract. - let data = unsafe { component_data(component) }; - let mut frame_bytes = channels * cfg.src_addr_width as u32; - if ptr::eq(substream, data.sense.load(Relaxed)) && data.cfg.realign_sense { - cfg.peripheral_config = ptr::from_mut(&mut frame_bytes).cast(); - cfg.peripheral_size = mem::size_of::(); - } // SAFETY: `chan` is the live channel behind the substream. unsafe { match (*(*chan).device).device_config { @@ -871,7 +1436,7 @@ unsafe extern "C" fn asoc_pcm_hw_params( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_trigger( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, cmd: i32, ) -> i32 { @@ -879,6 +1444,27 @@ unsafe extern "C" fn asoc_pcm_trigger( if unsafe { rtd_is_be(substream_rtd(substream)) } { return 0; } + // The sense attaches to the ring at its next whole frame; ALSA holds the + // stream lock, which the ring callback takes too. + // SAFETY: as above. + if let Some(ring) = unsafe { sense_ring(component, substream) } { + match cmd as u32 { + bindings::SNDRV_PCM_TRIGGER_START => { + ring.fe_pos.store(0, Ordering::Relaxed); + ring.fe_running.store(true, Ordering::Relaxed); + } + bindings::SNDRV_PCM_TRIGGER_RESUME | bindings::SNDRV_PCM_TRIGGER_PAUSE_RELEASE => { + ring.fe_running.store(true, Ordering::Relaxed); + } + bindings::SNDRV_PCM_TRIGGER_STOP + | bindings::SNDRV_PCM_TRIGGER_SUSPEND + | bindings::SNDRV_PCM_TRIGGER_PAUSE_PUSH => { + ring.fe_running.store(false, Ordering::Relaxed); + } + _ => return EINVAL.to_errno(), + } + return 0; + } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_trigger(substream, cmd) } } @@ -889,11 +1475,12 @@ unsafe extern "C" fn asoc_pcm_trigger( /// /// Called by ASoC on this driver's component with a live substream. unsafe extern "C" fn asoc_pcm_sync_stop( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, ) -> i32 { // SAFETY: by the caller's contract. - if unsafe { rtd_is_be(substream_rtd(substream)) } { + if unsafe { rtd_is_be(substream_rtd(substream)) || sense_ring(component, substream).is_some() } + { return 0; } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. @@ -904,13 +1491,20 @@ unsafe extern "C" fn asoc_pcm_sync_stop( /// /// Called by ASoC on this driver's component with live arguments. unsafe extern "C" fn asoc_pcm_pointer( - _component: *mut bindings::snd_soc_component, + component: *mut bindings::snd_soc_component, substream: *mut bindings::snd_pcm_substream, ) -> bindings::snd_pcm_uframes_t { // SAFETY: by the caller's contract. if unsafe { rtd_is_be(substream_rtd(substream)) } { return (-i64::from(bindings::ENOTSUPP)) as bindings::snd_pcm_uframes_t; } + // SAFETY: as above; ALSA calls this under the stream lock with a live runtime. + if let Some(ring) = unsafe { sense_ring(component, substream) } { + // SAFETY: as above. + let frames = unsafe { (*(*substream).runtime).buffer_size } as usize; + return (ring.fe_pos.load(Ordering::Relaxed) % frames.max(1)) + as bindings::snd_pcm_uframes_t; + } // SAFETY: the dmaengine runtime was set up in `asoc_pcm_open`. unsafe { bindings::snd_dmaengine_pcm_pointer(substream) } } @@ -976,6 +1570,31 @@ unsafe fn be_service<'a>( Some((data, svc)) } +/// Mutes a back-end's codecs (the amps); `__soc_pcm_prepare` unmutes them right +/// after `be_prepare`. +/// +/// # Safety +/// +/// `rtd` must be a live back-end runtime, in its prepare. +unsafe fn mute_codecs(rtd: *mut bindings::snd_soc_pcm_runtime) -> Result<()> { + // SAFETY: by the caller's contract; the codec DAIs follow the CPU DAIs in `dais`. + unsafe { + let link = (*rtd).dai_link; + let cpus = (*link).num_cpus as usize; + for i in 0..(*link).num_codecs as usize { + let ret = bindings::snd_soc_dai_digital_mute( + *(*rtd).dais.add(cpus + i), + 1, + bindings::SNDRV_PCM_STREAM_PLAYBACK as i32, + ); + if ret < 0 { + return Err(Error::from_errno(ret)); + } + } + } + Ok(()) +} + /// # Safety /// /// Called by ASoC with a live DAI of this component and a live substream. @@ -995,7 +1614,12 @@ unsafe extern "C" fn be_startup( } return 0; }; - match data.startup(svc) { + let res = if ptr::eq(svc, &data.spkr) { + data.spkr_startup() + } else { + data.startup(svc) + }; + match res { Ok(()) => 0, Err(e) => e.to_errno(), } @@ -1012,12 +1636,34 @@ unsafe extern "C" fn be_prepare( let Some((data, svc)) = (unsafe { be_service(dai, substream) }) else { return 0; }; - match data.prepare(svc) { + let res = if ptr::eq(svc, &data.spkr) { + // SAFETY: the back-end runtime of this substream is live for the call. + data.spkr_prepare(|| unsafe { mute_codecs(substream_rtd(substream)) }) + } else { + data.prepare(svc) + }; + match res { Ok(()) => 0, Err(e) => e.to_errno(), } } +/// # Safety +/// +/// Called by ASoC with a live DAI of this component and a live substream. +unsafe extern "C" fn be_hw_free( + substream: *mut bindings::snd_pcm_substream, + dai: *mut bindings::snd_soc_dai, +) -> i32 { + // SAFETY: by the caller's contract. + if let Some((data, svc)) = unsafe { be_service(dai, substream) } { + if ptr::eq(svc, &data.spkr) { + data.spkr_hw_free(); + } + } + 0 +} + /// # Safety /// /// Called by ASoC with a live DAI of this component and a live substream. @@ -1027,7 +1673,31 @@ unsafe extern "C" fn be_shutdown( ) { // SAFETY: by the caller's contract. if let Some((data, svc)) = unsafe { be_service(dai, substream) } { - data.shutdown(svc); + if ptr::eq(svc, &data.spkr) { + data.spkr_shutdown(); + } else { + data.shutdown(svc); + } + } +} + +/// # Safety +/// +/// Called by ASoC on this driver's registered component. +unsafe extern "C" fn asoc_suspend(component: *mut bindings::snd_soc_component) -> i32 { + // SAFETY: by the caller's contract. + unsafe { component_data(component) }.spkr_suspend(); + 0 +} + +/// # Safety +/// +/// Called by ASoC on this driver's registered component. +unsafe extern "C" fn asoc_resume(component: *mut bindings::snd_soc_component) -> i32 { + // SAFETY: by the caller's contract. + match unsafe { component_data(component) }.spkr_resume() { + Ok(()) => 0, + Err(e) => e.to_errno(), } } @@ -1049,6 +1719,7 @@ impl DaiOps { be: bindings::snd_soc_dai_ops { startup: Some(be_startup), prepare: Some(be_prepare), + hw_free: Some(be_hw_free), shutdown: Some(be_shutdown), ..fe }, @@ -1133,6 +1804,8 @@ impl AsocContext { let dais = KBox::new(Opaque::new(dai_drivers(&ops, data.cfg)), GFP_KERNEL)?; let component = bindings::snd_soc_component_driver { name: c"t8152-aop-audio".as_char_ptr(), + suspend: Some(asoc_suspend), + resume: Some(asoc_resume), open: Some(asoc_pcm_open), close: Some(asoc_pcm_close), hw_params: Some(asoc_pcm_hw_params), @@ -1530,6 +2203,9 @@ impl platform::Driver for T8152AopAudioDriver { .is_some_and(|node| node.property_match_string(c"dma-names", c"hpai").is_ok()) }; + let sense_ring = cfg + .sense_ring + .then(|| SenseRing::new(cfg.sense_channels as usize * 2)); let data_dev = dev.clone(); let data = Arc::pin_init( pin_init!(T8152AopAudio { @@ -1539,9 +2215,14 @@ impl platform::Driver for T8152AopAudioDriver { cout: Service::new(from_fourcc(b"cout"), "cout", true), cin: Service::new(from_fourcc(b"cin "), "cin", true), spkr: Service::new(from_fourcc(b"spkr"), "spkr", false), + spkr_state <- new_mutex!(SpkrState { + open: false, + running: false, + resume_run: false, + }), + sense_ring, mca, cfg, - sense: Atomic::new(ptr::null_mut()), hpai: Service::new(from_fourcc(b"hpai"), "hpai", false), leap, hpai_want_run: AtomicFlag::new(false), @@ -1597,6 +2278,9 @@ impl platform::Driver for T8152AopAudioDriver { fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { this.unregister(); + if let Some(ring) = &this.asoc.data.sense_ring { + ring.release(); + } } } @@ -1606,3 +2290,65 @@ module_platform_driver! { description: "Apple T8152 AOP audio: headphone jack, speakers and microphones", license: "Dual MIT/GPL", } + +#[kunit_tests(snd_soc_apple_t8152_aop_audio)] +mod tests { + use super::*; + + const fn frames_ns(frames: u64) -> i64 { + (frames * NSEC_PER_SEC / SENSE_RATE) as i64 + } + + #[test] + fn sense_ring_lap_detection() { + let ring_frames = SENSE_RING_FRAMES as u64; + let period_frames = SENSE_RING_PERIOD_FRAMES as u64; + + assert!(!sense_ring_may_lap(0)); + assert!(!sense_ring_may_lap(frames_ns(period_frames))); + assert!(!sense_ring_may_lap(frames_ns(ring_frames / 2))); + assert!(!sense_ring_may_lap( + frames_ns(ring_frames - period_frames) - 1 + )); + + assert!(sense_ring_may_lap(frames_ns(ring_frames - period_frames))); + assert!(sense_ring_may_lap(frames_ns(ring_frames))); + assert!(sense_ring_may_lap(frames_ns( + 2 * ring_frames + period_frames + ))); + assert!(sense_ring_may_lap(-1)); + } + + #[test] + fn sense_ring_geometry_covers_8ch_and_12ch() { + assert_eq!(SENSE_RING_NS, 80_000_000); + assert_eq!(SENSE_RING_PERIOD_NS, 2_500_000); + + // T8142 4-amp (8ch S16_LE = 16 B/frame) and T8142 6-amp / T6050 (12ch S16_LE = 24 B/frame) + for ch in [HW_CFG_T8142.sense_channels, HW_CFG_T6050.sense_channels] { + let frame = ch as usize * 2; + let ring = SenseRing::new(frame); + assert_eq!(ring.period_bytes() % frame, 0); + assert_eq!(ring.ring_bytes() % ring.period_bytes(), 0); + // Whole multiples of the ADMAC RX FIFO threshold (0x18 * 2 = 48 B) + assert_eq!(ring.period_bytes() % 48, 0); + } + } + + #[test] + fn sense_ring_fe_space_guards_overrun() { + // Small legal capture buffer (two 12-frame periods) cannot fit one 120-frame ring period + assert!(!sense_ring_has_fe_space(24, 0, 0, SENSE_RING_PERIOD_FRAMES)); + // Exact full-buffer advance (e.g. 120 frames into a 120-frame buffer) wraps the + // modulo pointer back to the same offset, so it must trigger XRUN; strictly less fits. + assert!(!sense_ring_has_fe_space(120, 0, 0, 120)); + assert!(sense_ring_has_fe_space(121, 0, 0, 120)); + assert!(!sense_ring_has_fe_space(121, 1, 0, 120)); + assert!(!sense_ring_has_fe_space(121, 0, 1, 120)); + // Coalesced callbacks exceeding remaining space after unread + pending frames trigger XRUN + assert!(sense_ring_has_fe_space(1024, 512, 120, 240)); + assert!(!sense_ring_has_fe_space(1024, 512, 240, 360)); + // Overflow in unread + pending + incoming fails closed + assert!(!sense_ring_has_fe_space(1024, usize::MAX, 0, 1)); + } +} From 2ce8e3cd0fb7fb3a68f99cc6bd8c1873bfd71b7e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 02:56:05 +1100 Subject: [PATCH 1046/1514] drm/apple: audio: keep a classic Open with the instance it was made on The classic Open and Close run without locks, so the published instance may change under them. Read is_open under plug_lock, and commit an Open (is_open, dcpaud_connect()) or a Close (dcpaud_disconnect(), clearing is_open) only while the RPC's instance is still the published one, checked under plug_lock then srv_rwsem, the order av_audiosrv_init() takes them. A stale Open no longer marks the successor opened (which then skipped its own Open and card connect), and a stale Close no longer clears a successor's Open. Every publication starts the instance unopened. The refusal check's device is set once at init. The CEC-only selftest gains both interleavings: a Close whose instance is replaced and the successor opened meanwhile, and an Open whose instance is replaced meanwhile. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/av.c | 60 ++++++++++++------- .../selftests/drivers/gpu/apple-dcp/audio.py | 39 ++++++++++-- 2 files changed, 73 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index 9b40babd3333fb..038ab364541780 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -208,9 +208,8 @@ static void av_audiosrv_init(struct apple_epic_service *service, const char *nam afk_service_put(old); asrv->plugged = true; - /* The classic Open was the old instance's: the successor is opened afresh. */ - if (old) - asrv->is_open = false; + /* A classic Open is its instance's: the one published now is opened afresh. */ + asrv->is_open = false; /* A new instance, maybe a new sink: its catalog is asked for afresh. */ WRITE_ONCE(asrv->elements_empty, false); mutex_unlock(&asrv->plug_lock); @@ -1082,10 +1081,19 @@ static const struct apple_epic_service_ops avep_ops[] = { {} }; +/* Whether @service is the published instance; plug_lock held, then srv_rwsem */ +static bool av_audiosrv_published(struct audiosrv_data *asrv, + struct apple_epic_service *service) +{ + guard(rwsem_read)(&asrv->srv_rwsem); + return asrv->srv == service; +} + void av_service_connect(struct apple_dcp *dcp) { struct apple_epic_service *service; struct audiosrv_data *asrv = dcp->audiosrv; + bool opened; int ret; /* @@ -1104,7 +1112,9 @@ void av_service_connect(struct apple_dcp *dcp) /* open AV audio service */ dev_info(dcp->dev, "%s: starting audio service, plugged:%d\n", __func__, asrv->plugged); - if (asrv->is_open) + scoped_guard(mutex, &asrv->plug_lock) + opened = asrv->is_open; + if (opened) goto out; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) @@ -1147,7 +1157,6 @@ void av_service_connect(struct apple_dcp *dcp) * refusal then, so a lasting one is still reported. */ WRITE_ONCE(asrv->open_refused, ret); - asrv->open_check_dev = dcp->dev; mod_delayed_work(system_wq, &asrv->open_check_wq, msecs_to_jiffies(AV_AUDIOSRV_REPLACE_MS)); goto out; @@ -1156,12 +1165,18 @@ void av_service_connect(struct apple_dcp *dcp) dev_err(dcp->dev, "error opening audio service: %d\n", ret); goto out; } - mutex_lock(&asrv->plug_lock); - asrv->is_open = true; - - if (asrv->audio_dev) - dcpaud_connect(asrv->audio_dev, asrv->plugged); - mutex_unlock(&asrv->plug_lock); + /* + * The Open ran without locks: it is this instance's only if the + * instance is still the published one. A successor published meanwhile + * is opened by its own connect. + */ + scoped_guard(mutex, &asrv->plug_lock) { + if (av_audiosrv_published(asrv, service)) { + asrv->is_open = true; + if (asrv->audio_dev) + dcpaud_connect(asrv->audio_dev, asrv->plugged); + } + } out: afk_service_put(service); } @@ -1193,6 +1208,7 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) { struct apple_epic_service *service; struct audiosrv_data *asrv = dcp->audiosrv; + bool opened; int ret; /* A CEC-only endpoint has no audio owner (av_service_connect()). */ @@ -1244,16 +1260,15 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) goto out; } #endif - if (!asrv->is_open) + /* Only the published instance's Open is closed, and only once. */ + scoped_guard(mutex, &asrv->plug_lock) { + opened = asrv->is_open && av_audiosrv_published(asrv, service); + if (opened && asrv->audio_dev) + dcpaud_disconnect(asrv->audio_dev); + } + if (!opened) goto out; - mutex_lock(&asrv->plug_lock); - - if (asrv->audio_dev) - dcpaud_disconnect(asrv->audio_dev); - - mutex_unlock(&asrv->plug_lock); - ret = afk_service_call(service, 0, asrv->cmds.close, NULL, 0, 16, NULL, 0, 16); if (ret) { @@ -1261,7 +1276,11 @@ static void __av_service_disconnect(struct apple_dcp *dcp, const u64 *gen) } if (service->torndown) afk_service_disable(service); - asrv->is_open = false; + /* A successor published meanwhile keeps its own state. */ + scoped_guard(mutex, &asrv->plug_lock) { + if (av_audiosrv_published(asrv, service)) + asrv->is_open = false; + } out: afk_service_put(service); } @@ -1553,6 +1572,7 @@ int avep_init(struct apple_dcp *dcp) INIT_WORK(&audiosrv_data->start_av_service_wq, av_work_service_start); INIT_DELAYED_WORK(&audiosrv_data->open_check_wq, av_work_open_check); + audiosrv_data->open_check_dev = dcp->dev; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) INIT_WORK(&audiosrv_data->terminate_wq, av_work_service_terminate); mutex_init(&audiosrv_data->open_lock); diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py index b6bb0432e022d0..25524680b7ea54 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py @@ -147,11 +147,10 @@ def cec_only_endpoint(root): static unsigned takes; static struct lock *lock_take(struct lock *l) {assert(!l->held); l->held = 1; takes++; return l;} static void lock_drop(struct lock **l) {if (*l) (*l)->held = 0;} +#define guard(type) struct lock *_g __attribute__((cleanup(lock_drop))) = lock_take #define scoped_guard(type, l) \ for (struct lock *_guard __attribute__((cleanup(lock_drop))) = lock_take(l), *_once = _guard; \ _once; _once = NULL) -static void mutex_lock(struct lock *l) {lock_take(l);} -static void mutex_unlock(struct lock *l) {l->held = 0;} struct apple_epic_service {bool torndown; unsigned pins;}; struct apple_dcp_afkep {int endpoint;}; struct audiosrv_data { @@ -166,7 +165,9 @@ def cec_only_endpoint(root): }; struct apple_dcp {struct device *dev; struct apple_dcp_afkep *avep; struct audiosrv_data *audiosrv;}; static bool native, v27; -static int call_ret; +static int call_ret, hook; +static struct audiosrv_data *hook_asrv; +static struct apple_epic_service *hook_next; static unsigned calls, last_cmd, connects, disconnects, releases, closes, v27_starts; static bool dcp_audiosrv_native_link(struct device *dev) {(void)dev; return native;} static bool dcp_is_v14_7_external(const struct apple_dcp *dcp) {(void)dcp; return false;} @@ -185,10 +186,18 @@ def cec_only_endpoint(root): size_t pad, void *out, size_t room, size_t out_pad) { (void)group; (void)data; (void)len; (void)pad; (void)out; (void)room; (void)out_pad; - assert(s && s->pins); calls++; last_cmd = cmd; return call_ret; + assert(s && s->pins); calls++; last_cmd = cmd; + /* A successor published while the RPC runs (and, at a Close, opened) */ + if (hook) { + hook_asrv->srv = hook_next; + hook_asrv->is_open = hook == 2; + hook = 0; + } + return call_ret; } ''' - return prefix + block(source, 'void av_service_connect(') + '\n' + block( + return prefix + block(source, 'static bool av_audiosrv_published(') + '\n' + block( + source, 'void av_service_connect(') + '\n' + block( source, 'static void __av_service_disconnect(') + '\n' + block( source, 'void av_service_disconnect(') + r''' int main(void) @@ -243,13 +252,31 @@ def cec_only_endpoint(root): call_ret = -EINVAL; av_service_connect(&dcp); assert(calls == 3 && !asrv.is_open && armed == 1 && !errs && asrv.open_refused == -EINVAL && - asrv.open_check_dev == &dev && connects == 3); + connects == 3); call_ret = -ETIMEDOUT; av_service_connect(&dcp); assert(calls == 4 && !asrv.is_open && armed == 1 && errs == 1); call_ret = 0; av_service_connect(&dcp); assert(calls == 5 && asrv.is_open && connects == 4); + + /* A Close whose instance is replaced meanwhile leaves the successor's Open. */ + struct apple_epic_service next = {0}; + hook_asrv = &asrv; + hook_next = &next; + hook = 2; + av_service_disconnect(&dcp); + assert(calls == 6 && last_cmd == 5 && asrv.srv == &next && asrv.is_open); + + /* An Open whose instance is replaced meanwhile is not the successor's. */ + asrv.srv = &srv; + asrv.is_open = false; + hook_next = &next; + hook = 1; + av_service_connect(&dcp); + assert(calls == 7 && last_cmd == 4 && asrv.srv == &next && !asrv.is_open && connects == 4); + assert(!next.pins); + asrv.srv = &srv; assert(!srv.pins && !asrv.srv_rwsem.held && !asrv.plug_lock.held); return 0; } From 0b1cdcd4ce453f2503edc72eb75c5c74179e0132 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 03:11:40 +1100 Subject: [PATCH 1047/1514] tools/asahi: update CLPC host tests for PMC-optional standalone state Update the stub struct apple_clpc definitions and helper stubs in clpc-gpu-demand-tests.py and clpc-high-power-cleanup-tests.py to match the new has_pmc, auto_low_power, and synchronous profile-ceiling hooks in drivers/soc/apple/clpc.c. Signed-off-by: Ryan Murray --- tools/asahi/clpc-gpu-demand-tests.py | 31 +++++++++++--------- tools/asahi/clpc-high-power-cleanup-tests.py | 21 ++++++++----- 2 files changed, 31 insertions(+), 21 deletions(-) diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index c377356d19361e..a200ebd289145b 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -233,6 +233,7 @@ def cells(name): + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', + 'static inline bool apple_clpc_has_profile_ceiling(', 'static bool apple_clpc_gpu_streaming(', 'static bool apple_clpc_gpu_dense_step(', 'static bool apple_clpc_gpu_dense(', @@ -322,7 +323,9 @@ def cells(name): struct freq_qos_request ane_qos; unsigned int ane_qos_khz; unsigned long ane_until; + bool has_pmc; bool low_power; + bool auto_low_power; unsigned int low_power_khz; }; static unsigned long jiffies; @@ -413,7 +416,7 @@ def cells(name): // Falling back keeps the compatible's full GPU floor even when a low busy share arrives. { struct apple_clpc_gpu g = {.active = true, .busy_valid = true, .busy = 100}; - struct apple_clpc c = {.hw = &out, .agent = 1, .mask = 3, .gpu = &g}; + struct apple_clpc c = {.hw = &out, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &g}; read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; jiffies = 2900; published = ~0u; apple_clpc_sample(&c); assert(published == 0x35 && c.last_reason == 2); @@ -428,7 +431,7 @@ def cells(name): // shorter than one sample is still seen once, and the hold then expires. static void check_t8140_ane(void) { struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.ane=&ane}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; read_error=vote_error=0; pmgr_status=0; pmp_floor=0; jiffies=1000; published=~0u; @@ -445,7 +448,7 @@ def cells(name): // idle sampling), sees a sub-sample request once, and releases after HOLD_MS. static void check_t6050_ane(void) { struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6050,.agent=1,.mask=3,.ane=&ane}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6050,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; assert(c.hw->ane[APPLE_CLPC_DCS]==6 && c.hw->ane[APPLE_CLPC_SOC]==2 && c.hw->idle_on_time); @@ -463,7 +466,7 @@ def cells(name): // added on first use, for the vote hold after the last request, then drops it. static void check_t6040_ane(void) { struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.agent=1,.mask=3,.ane=&ane}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.has_pmc=true,.agent=1,.mask=3,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; c.ane_cpu=9; c.ane_cluster_khz=c.hw->ane_cluster_khz; @@ -484,7 +487,7 @@ def cells(name): // level or more. A table without a non-zero top DCS state falls back to @map. static void check_t6041_busy(void) { struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&t6041_dt_hw,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc c={.hw=&t6041_dt_hw,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; struct apple_clpc_hw no_top = t6041_dt_hw; assert(c.hw->gpu_busy_mid==160 && c.hw->gpu_busy_high==500 && c.hw->gpu_busy_top==800); read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; published=~0u; @@ -534,7 +537,7 @@ def cells(name): // 0x35 while it runs, and drops back to 0x01 after it finishes + 400 ms hold. static void check_t6041_long_in_flight(void) { struct apple_clpc_gpu gpu = {0}; - struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &gpu}; read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; gpu.active = true; // Initial burst starts at top (no share yet). @@ -580,7 +583,7 @@ def cells(name): // diluted 85 permille a stale window would report drops it to 0x01 at once. static void check_t6041_idle_burst(void) { struct apple_clpc_gpu gpu = {0}; - struct apple_clpc c = {.hw = &t6041_dt_hw, .agent = 1, .mask = 3, .gpu = &gpu}; + struct apple_clpc c = {.hw = &t6041_dt_hw, .has_pmc = true, .agent = 1, .mask = 3, .gpu = &gpu}; size_t i = 0, n = ARRAY_SIZE(g17_idle_events); read_error = vote_error = 0; pmgr_status = 0xf0; pmp_floor = 0; published = ~0u; assert(n == 8 && g17_idle_events[0].ms == 1100 && g17_idle_events[2].ms == 2000); @@ -621,7 +624,7 @@ def cells(name): // M5/F3 floor follows the work the GPU driver reports, as on T6040. static void check_t8132(void) { struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8132,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8132,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; assert(!c.hw->gpu_demand); read_error=vote_error=0; pmgr_status=0xf0; pmp_floor=0; jiffies=0; published=~0u; apple_clpc_sample(&c); assert(published==0 && queued_idle && c.last_reason==0); @@ -638,7 +641,7 @@ def cells(name): static void check_t6041(const struct apple_clpc_hw *hw) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_ane ane={0}; - struct apple_clpc c={.hw=hw,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; + struct apple_clpc c={.hw=hw,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu,.ane=&ane}; c.ane_states[APPLE_CLPC_DCS]=c.hw->ane[APPLE_CLPC_DCS]; c.ane_states[APPLE_CLPC_SOC]=c.hw->ane[APPLE_CLPC_SOC]; assert(!c.hw->gpu_demand && c.hw->gpu_input && c.hw->sustain==0 && c.hw->idle_on_time); @@ -664,7 +667,7 @@ def cells(name): // A failed power-state read still protects an active graphics consumer. static void check_read_error(void) { - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0xf0; warned=0; for (jiffies=100; jiffies<=164; jiffies+=4) apple_clpc_sample(&c); assert(published==0x34 && c.last_reason==4); @@ -679,7 +682,7 @@ def cells(name): } static void check_t8140(void) { - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0xf0; for (jiffies=100; jiffies<=164; jiffies+=4) { apple_clpc_sample(&c); @@ -702,7 +705,7 @@ def cells(name): // streams, but 2+ submissions in each of 4 periods earn the GPU floor. static void check_t8140_dense(void) { struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.agent=1,.mask=3,.gpu_pmgr=(void *)1,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t8140,.has_pmc=true,.agent=1,.mask=3,.gpu_pmgr=(void *)1,.gpu=&gpu}; read_error=vote_error=0; pmp_floor=4; pmgr_status=0; published=~0u; jiffies=100; apple_clpc_sample(&c); assert(published==0 && queued_idle); for (jiffies=104; jiffies<=116; jiffies+=4) { @@ -727,7 +730,7 @@ def cells(name): static void check_low_power(void) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_hw lp=apple_clpc_hw_t6040; - struct apple_clpc c={.hw=&lp,.agent=1,.mask=3,.gpu=&gpu,.low_power=true}; + struct apple_clpc c={.hw=&lp,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu,.low_power=true}; read_error=vote_error=0; pmgr_status=0xf0; published=~0u; jiffies=3000; apple_clpc_sample(&c); assert(published==0 && queued_idle); c.low_power_khz=2808000; @@ -739,7 +742,7 @@ def cells(name): int main(void) { // T6040's supplier is always powered: it must NEVER substitute for work. struct apple_clpc_gpu gpu={0}; - struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.agent=1,.mask=3,.gpu=&gpu}; + struct apple_clpc c={.hw=&apple_clpc_hw_t6040,.has_pmc=true,.agent=1,.mask=3,.gpu=&gpu}; assert(!c.hw->gpu_demand); jiffies=0; read_error=vote_error=0; pmgr_status=0xf0; published=~0u; apple_clpc_sample(&c); assert(published==0 && queued_idle && c.last_reason==0); diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index c664991024b57d..07f6bc355e2453 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -65,17 +65,24 @@ def function(source, name): struct apple_clpc_ane *ane; struct mutex sample_lock; struct delayed_work work, idle_work; - bool stopped, high_power, high_power_sent, policy_nb_added, low_power; + bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power, auto_low_power; u8 high_power_seq; enum platform_profile_option profile; unsigned long power_next, ane_until; - unsigned ane_qos_khz, nr_clusters, agent, mask, saved_floor; + unsigned low_power_khz, ane_qos_khz, nr_clusters, agent, mask, saved_floor; struct freq_qos_request ane_qos; struct cluster clusters[2]; struct vote vote[APPLE_CLPC_RAILS]; - void *pmc, *debugfs; + void *pmc, *debugfs, *covered; int policy_nb; }; +static void *cpu_possible_mask; +static bool cpumask_equal(void *a, void *b) { return a == b; } +static bool apple_clpc_has_profile_ceiling(const struct apple_clpc *c) { + return c->low_power_khz || c->auto_low_power; +} +static void apple_clpc_find_clusters(struct apple_clpc *c) { (void)c; } +static void apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } static struct mutex apple_clpc_clients_lock; static unsigned long jiffies = 123; static int system_freezable_power_efficient_wq; @@ -120,11 +127,11 @@ def function(source, name): (void)n; assert(kind == CPUFREQ_POLICY_NOTIFIER && floor_restored); assert(!active->sample_lock.held); notifier_removed = true; } -static void of_node_put(struct device_node *n) { +static void __attribute__((unused)) of_node_put(struct device_node *n) { (void)n; assert(notifier_removed && qos_removed == 3); node_put = true; } static void apple_clpc_free_clusters(struct apple_clpc *c) { - (void)c; assert(node_put); freed = true; + (void)c; assert(notifier_removed && qos_removed == 3); freed = true; } static bool apple_clpc_smc(struct apple_clpc *c) { return c->smc != NULL; } static void put_unaligned_le32(uint32_t v, u8 *p) { @@ -156,7 +163,7 @@ def function(source, name): static struct apple_clpc c; static void reset(void) { memset(&c, 0, sizeof(c)); memset(&gpu, 0, sizeof(gpu)); memset(&ane, 0, sizeof(ane)); - active = &c; dev.data = &c; c.dev = &dev; c.smc = &smc; + active = &c; dev.data = &c; c.dev = &dev; c.smc = &smc; c.has_pmc = true; c.gpu = &gpu; c.ane = &ane; gpu.wake = &c.work; ane.wake = &c.work; c.work.pending = c.idle_work.pending = true; c.policy_nb_added = c.ane_qos.active = true; @@ -176,7 +183,7 @@ def function(source, name): } static void stop(void) { cleanup = true; apple_clpc_stop(&c); - assert(freed && node_put && notifier_removed && qos_removed == 3); + assert(freed && notifier_removed && qos_removed == 3); assert(!c.sample_lock.held && !apple_clpc_clients_lock.held); assert(c.stopped && cancels == 4 && floor_restored && !dev.data); } From af6b5c2f94dc280e5623914b22cab02815ecd4ac Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 03:26:56 +1100 Subject: [PATCH 1048/1514] tools/asahi: mark standalone CLPC cleanup test stubs unused for --old-ref Mark the five standalone profile-ceiling stubs in clpc-high-power-cleanup-tests.py with __attribute__((unused)) so --old-ref 677be395b9d2 compiles cleanly under -Werror=unused-function and -Werror=unused-variable. Signed-off-by: Ryan Murray --- tools/asahi/clpc-high-power-cleanup-tests.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index 07f6bc355e2453..c9c96d5a7f2279 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -76,13 +76,13 @@ def function(source, name): void *pmc, *debugfs, *covered; int policy_nb; }; -static void *cpu_possible_mask; -static bool cpumask_equal(void *a, void *b) { return a == b; } -static bool apple_clpc_has_profile_ceiling(const struct apple_clpc *c) { +static void __attribute__((unused)) *cpu_possible_mask; +static bool __attribute__((unused)) cpumask_equal(void *a, void *b) { return a == b; } +static bool __attribute__((unused)) apple_clpc_has_profile_ceiling(const struct apple_clpc *c) { return c->low_power_khz || c->auto_low_power; } -static void apple_clpc_find_clusters(struct apple_clpc *c) { (void)c; } -static void apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } +static void __attribute__((unused)) apple_clpc_find_clusters(struct apple_clpc *c) { (void)c; } +static void __attribute__((unused)) apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } static struct mutex apple_clpc_clients_lock; static unsigned long jiffies = 123; static int system_freezable_power_efficient_wq; From 4bee746af81703153bae13cc4c58468b823acdbb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 23:19:29 -0500 Subject: [PATCH 1049/1514] drm/asahi: g17: enable direct compute submission on M5 On M5 (G17S/G17C/G17D), compute_direct() returned None unconditionally because M5 compute shares the per-priority outer work ring with render and issues host-port gating and submission-history updates. As a result, every steady-state M5 compute submission fell back to the global device mutex (shared.state), serializing concurrent compute queues against each other and against the event worker. Add a dedicated port-level M5 outer-ring mutex (Port::m5_outer) ordered after the compute queue cell and render publication lock (device mutex -> compute cell -> port.render -> port.m5_outer -> port.qos/mailbox), and expose non-interfering direct credit consumption on OuterCredits (is_scoped() / consume_direct()) plus direct port views for M5's shared outer ring and submission-history table. Guard device-mutex M5 compute and render outer-ring publications with m5_outer_lock(), reset the cached history geometry on recovery restart, and allow steady-state M5 compute submissions to publish through compute_direct() without taking shared.state. Add a KUnit test covering direct credit consumption alongside OuterScope. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/initdata.rs | 2 + drivers/gpu/drm/asahi/g17/initdata/m5.rs | 19 +++ .../drm/asahi/g17/initdata/outer_credit.rs | 127 ++++++++++++++- drivers/gpu/drm/asahi/g17/port.rs | 152 +++++++++++++++++- drivers/gpu/drm/asahi/g17/runtime.rs | 109 ++++++++----- drivers/gpu/drm/asahi/g17/runtime/events.rs | 1 + .../drm/asahi/g17/runtime/render/submit.rs | 1 + 7 files changed, 365 insertions(+), 46 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 35927ad60f0fae..b25d4d7b64e288 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -1068,6 +1068,8 @@ impl InitData { // The word recovery_state() reads: the status block moves with the firmware build. recovery: self.object(self.cluster)?.word(self.recovery_state_offset())?, mailbox, + m5_credits: self.outer_credits.clone(), + m5_history: self.m5_history_view()?, }) } diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index 2c0981746e0286..20b181f446b53d 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -52,6 +52,25 @@ impl InitData { ring(0), ring(1), ring(2), ring(3), page(canonical.start)] } + /// Direct-port view of the M5 submission-history table (none off M5 or on common 26A428). + pub(super) fn m5_history_view(&self) -> Result> { + if !self.m5 || self.graph.is_common26() { + return Ok(None); + } + let private = self.object(self.cluster)?; + let base = m::M5_PRIVATE_LAYOUT.status_config; + Ok(Some(crate::g17::port::M5HistoryView { + generation: private.word(base + 0x74c)?, + config: [ + private.word(base + 0x73c)?, + private.word(base + 0x740)?, + private.word(base + 0x744)?, + private.word(base + 0x748)?, + ], + slots: private.pointer(base + 0x750, 256)?, + })) + } + /// Counts `submissions` in the firmware's submission history, in the slot of this moment. pub(crate) fn note_m5_submission_history(&self, submissions: u8) -> Result { if !self.m5 { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index 08804ff1fc4989..84901b7afdd92a 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -9,7 +9,7 @@ use kernel::{prelude::*, sync::Arc}; const PRIORITIES: usize = 4; -pub(super) struct Credits { +pub(crate) struct Credits { reserved: [AtomicU32; PRIORITIES], published: [AtomicU64; PRIORITIES], consumers: [AtomicU64; PRIORITIES], @@ -53,15 +53,19 @@ impl Credits { pub(super) fn waiting(&self) -> bool { self.available.has_waiters() } - pub(super) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { + pub(crate) fn is_scoped(&self) -> bool { + self.scoped.load(Ordering::Acquire) + } + + pub(crate) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { let pending = self.reserved.get(usize::from(priority)).ok_or(EINVAL)? .load(Ordering::Acquire); Ok(free(cursors)?.saturating_sub(pending)) } - /// Reserve under the sole publisher mutex. Off-lock cancellation may only + /// Reserve under the outer-ring lock. Off-lock cancellation may only /// reduce reserved counts, so the sampled capacity is conservative. - pub(super) fn reserve(self: &Arc, priority: u8, count: u32, + pub(crate) fn reserve(self: &Arc, priority: u8, count: u32, cursors: [u32; 3]) -> Result { if count == 0 || count >= WORK_RING_SLOTS { return Err(EINVAL); } @@ -75,6 +79,20 @@ impl Credits { Ok(OuterClaim { domain: self.clone(), priority: index, remaining: count }) } + /// Consumes one reserved slot for a direct M5 compute publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits a direct slot. + pub(crate) fn consume_direct(&self, claim: &mut OuterClaim) -> Result { + if !core::ptr::eq(self, &*claim.domain) { + return Err(EINVAL); + } + if claim.remaining == 0 { + return Err(EIO); + } + claim.remaining -= 1; + self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel); + Ok(()) + } + pub(super) fn scope<'a>(self: &Arc, claim: &'a mut OuterClaim) -> Result> { if !Arc::ptr_eq(self, &claim.domain) { return Err(EINVAL); } if self.scoped.swap(true, Ordering::AcqRel) { return Err(EBUSY); } @@ -128,3 +146,104 @@ impl Drop for OuterClaim { } } } + +#[kernel::macros::kunit_tests(asahi_g17_outer_credit)] +mod tests { + use super::*; + + #[test] + fn direct_consumption_does_not_debit_outer_scope() { + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let full = free(cursors).unwrap(); + let mut scoped_claim = credits.reserve(1, 2, cursors).unwrap(); + let mut direct_claim = credits.reserve(1, 1, cursors).unwrap(); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 3); + + // Direct publish consumes only its own reserved slot and leaves published[] untouched. + assert!(!credits.is_scoped()); + credits.consume_direct(&mut direct_claim).unwrap(); + assert_eq!(direct_claim.remaining(), 0); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 2); + assert_eq!(credits.counter(1).unwrap().load(Ordering::Acquire), 0); + + // An OuterScope taken afterward keeps its full 2 credits when nothing published via it. + { + let _scope = credits.scope(&mut scoped_claim).unwrap(); + assert!(credits.is_scoped()); + assert!(credits.reserve(1, 1, cursors).is_err()); + } + assert!(!credits.is_scoped()); + assert_eq!(scoped_claim.remaining(), 2); + drop(direct_claim); + drop(scoped_claim); + assert_eq!(credits.capacity(1, cursors).unwrap(), full); + } + + #[test] + fn mixed_render_compute_wrap_and_generation_change_with_queued_claim() { + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + // Producer sits two slots before wrap while both consumers lag 4 slots behind + // (free = WORK_RING_SLOTS - 5). + let mut consumer_a = n - 6; + let mut consumer_b = n - 6; + let mut producer = n - 2; + let cursors = [consumer_a, consumer_b, producer]; + let initial_free = free(cursors).unwrap(); + assert_eq!(initial_free, n - 5); + + // Interleave a queued 2-slot render claim with 1-slot compute claims across ring wrap. + let mut queued_render = credits.reserve(2, 2, cursors).unwrap(); + let mut compute_a = credits.reserve(2, 1, cursors).unwrap(); + credits.consume_direct(&mut compute_a).unwrap(); + producer = (producer + 1) % n; // n - 1 + assert_eq!( + credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), + initial_free - 3, + ); + + let mut compute_b = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut compute_b).unwrap(); + producer = (producer + 1) % n; // 0 (wrapped!) + assert_eq!(producer, 0); + + // Fill remaining capacity so exactly 1 free slot remains; 2-slot render must fail EBUSY + // while 1-slot compute still succeeds across the wrap boundary. + let rem = credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(); + let filler = credits.reserve(2, rem - 1, [consumer_a, consumer_b, producer]).unwrap(); + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [consumer_a, consumer_b, producer]).err(), Some(EBUSY)); + let mut edge_compute = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut edge_compute).unwrap(); + producer = (producer + 1) % n; // 1 + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 0); + drop(filler); + + // Consumers advance across the wrap boundary and report progress. + consumer_a = 1; + consumer_b = 1; + let wrapped = [consumer_a, consumer_b, producer]; + assert!(credits.progressed(2, wrapped).unwrap()); + assert_eq!(credits.capacity(2, wrapped).unwrap(), (n - 1) - 2); + + // Simulate locked render / recovery entering OuterScope while a queued compute claim + // waits across a generation change: new reserves fail EBUSY and direct consumption never + // debits OuterScope's published counter; dropping the queued claim after the generation + // change releases its reserved credits cleanly. + let queued_compute = credits.reserve(2, 1, wrapped).unwrap(); + { + let _scope = credits.scope(&mut queued_render).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + credits.counter(2).unwrap().fetch_add(2, Ordering::AcqRel); + } + assert!(!credits.is_scoped()); + assert_eq!(queued_render.remaining(), 0); + // Generation changed before queued_compute published: dropping it returns its credit. + assert_eq!(queued_compute.remaining(), 1); + drop(queued_compute); + drop(queued_render); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); + } +} diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 2a535f81429c8b..6386ec3bc0c414 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -7,9 +7,9 @@ //! through a preparation lease ([`super::Shared::port`]): shutdown and device loss join every //! lease before they detach the session. Each piece below is atomic or has its own lock. //! -//! Lock order: device mutex -> compute queue cell -> the locks of this port. The render -//! publication lock comes first among the port's locks: device mutex -> render publication -//! lock -> admission pool, QoS, mailbox. Its holder never takes the device mutex. +//! Lock order: device mutex -> compute queue cell -> the locks of this port. Among the port's +//! locks: render publication lock -> M5 outer-ring lock -> admission pool, QoS, mailbox. None +//! of their holders ever takes the device mutex. use super::{ fw::{ @@ -70,6 +70,14 @@ impl RingView { } } +/// Raw pointers to the M5 submission-history table in firmware-shared memory. +#[derive(Clone, Copy)] +pub(super) struct M5HistoryView { + pub(super) generation: *const AtomicU32, + pub(super) config: [*const AtomicU32; 4], + pub(super) slots: *mut u8, +} + /// Raw views of the session's firmware-shared memory, fixed once the firmware is built. pub(super) struct Views { pub(super) compute: [RingView; PRIORITIES], @@ -80,6 +88,8 @@ pub(super) struct Views { pub(super) qos: *mut u8, pub(super) recovery: *const AtomicU32, pub(super) mailbox: *const super::Mailbox, + pub(super) m5_credits: Option>, + pub(super) m5_history: Option, } // SAFETY: The views only name memory and a mailbox owned by the firmware session, which outlives @@ -109,6 +119,10 @@ pub(super) struct Port { /// overlaps are ordered by publication order (see hazard.rs). #[pin] render: Mutex<()>, + /// Serializes M5 shared outer-ring writes, host-port gating transactions, and submission + /// history geometry/updates across direct compute publishers and device-mutex publishers. + #[pin] + m5_outer: Mutex>, /// The accepted recovery generation, mirrored for publishers without the device mutex. generation: AtomicU64, /// Device publication order shared by compute and render commands. @@ -177,6 +191,7 @@ impl Port { feed, rx_applied <- new_spinlock!(None, "g17::Port::rx_applied"), render <- new_mutex!((), "g17::Port::render"), + m5_outer <- new_mutex!(None, "g17::Port::m5_outer"), generation: AtomicU64::new(0), publications: AtomicU64::new(0), effort_full: AtomicBool::new(false), @@ -307,6 +322,137 @@ impl Port { self.render.lock() } + /// Serializes M5 shared outer-ring and host-port updates with direct M5 compute publishers. + pub(super) fn m5_outer_lock(&self) -> MutexGuard<'_, Option<(u32, u64, u64)>> { + self.m5_outer.lock() + } + + /// Clears the cached M5 submission-history geometry after firmware recovery restarts. + pub(super) fn reset_m5_history(&self) { + *self.m5_outer.lock() = None; + } + + /// Reserves one slot on M5's shared outer ring for a direct compute publisher without + /// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full. + pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let _guard = self.m5_outer.lock(); + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + credits.reserve(priority, 1, cursors) + } + + /// Publishes one compute slot on M5's shared outer ring under the port's M5 outer lock + /// and consumes the caller's direct reservation. + pub(super) fn publish_m5_compute( + &self, + priority: u8, + claim: &mut super::initdata::OuterClaim, + record: &WorkSlot, + ) -> Result { + if record.data_master != DataMaster::Compute as u32 { + return Err(EINVAL); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let _guard = self.m5_outer.lock(); + let [first, second, producer] = ring.cursors()?; + let next = (producer + 1) % WORK_RING_SLOTS; + if next == first || next == second { + return Err(EIO); + } + // SAFETY: The ring view spans WORK_RING_SLOTS records, checked when the session built + // it; `producer` is in range. The reservation proves firmware does not own this slot and + // `m5_outer` excludes every other host writer on M5's shared outer ring. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + ring.slots + .add(producer as usize * core::mem::size_of::()), + core::mem::size_of::(), + ); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`. + unsafe { (*ring.producer).store(next, Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct(claim)?; + Ok(next) + } + + /// Issues an M5 host-port compute submission with gating held off, serialized by `m5_outer`. + pub(super) fn submit_m5_work_held( + &self, + submission: &super::fw::m5::queue::HardwareSubmission, + ) -> Result { + let regs = self.regs.as_ref().ok_or(ENODEV)?; + let _guard = self.m5_outer.lock(); + regs.submit_m5_work_held(submission) + } + + /// Counts `submissions` in the M5 submission-history table without taking the device mutex. + pub(super) fn note_m5_submission_history(&self, submissions: u8) -> Result { + let Some(history) = self.views()?.m5_history else { + return Ok(()); + }; + let mut geometry = self.m5_outer.lock(); + for _ in 0..64 { + // SAFETY: Pointers name retained, bounds-checked firmware-shared words. + let generation = unsafe { (*history.generation).load(Ordering::Acquire) }; + if generation & 1 != 0 { + core::hint::spin_loop(); + continue; + } + let (period, count) = match *geometry { + Some((seen, period, count)) if seen == generation => (period, count), + _ => { + // SAFETY: As above; seqlock generation recheck validates consistency. + let c = unsafe { + [ + (*history.config[0]).load(Ordering::Relaxed), + (*history.config[1]).load(Ordering::Relaxed), + (*history.config[2]).load(Ordering::Relaxed), + (*history.config[3]).load(Ordering::Relaxed), + ] + }; + fence(Ordering::Acquire); + // SAFETY: As above. + if generation != unsafe { (*history.generation).load(Ordering::Acquire) } { + core::hint::spin_loop(); + continue; + } + let period = u64::from(c[0]) | (u64::from(c[1]) << 32); + let count = u64::from(c[2]) | (u64::from(c[3]) << 32); + *geometry = Some((generation, period, count)); + (period, count) + } + }; + if period == 0 || count == 0 || count > 256 { + return Err(EINVAL); + } + let (counter, frequency) = qos::clock(); + let ticks = qos::time_from_host(counter, frequency)?; + let index = (ticks % period) / 25_000; + if index >= count { + return Err(ERANGE); + } + // SAFETY: `slots` spans 256 WC bytes and `index < count <= 256`. + unsafe { + let byte = history.slots.add(index as usize); + let value = core::ptr::read_volatile(byte).wrapping_add(submissions); + core::ptr::write_volatile(byte, value); + } + fence(Ordering::SeqCst); + return Ok(()); + } + Err(EBUSY) + } + fn render_rings(&self, priority: u8) -> Result<(RingView, RingView)> { let views = self.views()?; let index = usize::from(priority); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index b4b0dfef02723b..61e49e70443ad4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1617,6 +1617,8 @@ impl compute::Host for ComputeHost<'_> { struct DirectHost<'a> { port: &'a super::port::Port, outer: Option>, + m5_outer: Option<&'a mut super::initdata::OuterClaim>, + m5: bool, generation: u64, } impl compute::Host for DirectHost<'_> { @@ -1647,18 +1649,29 @@ impl compute::Host for DirectHost<'_> { fn register_queue(&mut self, _queue: &super::fw::kick::KsmQueue) -> Result { Err(EAGAIN) } - fn publish_outer(&mut self, _priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + fn publish_outer(&mut self, priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + if self.m5 { + let claim = self.m5_outer.as_deref_mut().ok_or(EIO)?; + return self.port.publish_m5_compute(priority, claim, slot).map(|_| ()); + } self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } fn notify(&mut self, message: u64) -> Result { + if self.m5 && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { + if let Err(error) = self.port.note_m5_submission_history(1) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + } self.port.notify(message) } fn note_submission(&mut self) -> Result { Ok(()) } - fn submit_m5(&mut self, _submission: &super::fw::m5::queue::HardwareSubmission) -> Result { - // M5 never publishes without the device mutex (see compute_direct). - Err(EINVAL) + fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { + if !self.m5 { + return Err(EINVAL); + } + self.port.submit_m5_work_held(submission) } } @@ -1750,21 +1763,6 @@ impl super::Firmware { if self.recovery.pending() { return Err(EAGAIN); } - // No descriptor, accounting or inner producer changes precede this - // reservation; dropping it unused returns the work-ring slot. M5 compute takes its - // slot on the work ring M5 render shares, under this mutex (InitData::publish_work_at): - // a full ring is refused here, before a queue install or kick changes any state. - let mut outer_cursors = None; - let outer = if self.init.is_m5() { - let priority = packet.context.policy().priority(); - let Some(cursors) = self.init.m5_compute_room(priority)? else { - return Err(EAGAIN); - }; - outer_cursors = Some((priority, cursors)); - None - } else { - Some(self.port.reserve_compute(packet.context.policy().priority())?) - }; let queues = &mut self.queues; let mut queue = queues .compute @@ -1782,6 +1780,22 @@ impl super::Firmware { { return Err(EAGAIN); } + // No descriptor, accounting or inner producer changes precede this + // reservation; dropping it unused returns the work-ring slot. M5 compute + // serializes the shared outer ring and host-port updates under `m5_outer` + // (after the compute cell lock, matching direct M5 publishers). + let _m5_outer = self.init.is_m5().then(|| self.port.m5_outer_lock()); + let mut outer_cursors = None; + let outer = if self.init.is_m5() { + let priority = packet.context.policy().priority(); + let Some(cursors) = self.init.m5_compute_room(priority)? else { + return Err(EAGAIN); + }; + outer_cursors = Some((priority, cursors)); + None + } else { + Some(self.port.reserve_compute(packet.context.policy().priority())?) + }; let mut host = ComputeHost { shared: &self.primary.state.shared, init: &self.init, @@ -2043,10 +2057,7 @@ impl Backend { required: super::freelist::ComputeCapacity, deferred: &mut DeferredBatch, ) -> Option { - // M5 compute is a shared-ring submission on the ring M5 render shares: it is published only - // under the device mutex, never through the classic compute ring producer. - if self.context.is_m5() - || packet.completion.sources().is_some() + if packet.completion.sources().is_some() || self.context.render_seen() || packet.cancel_requested() || packet.completion.status().get() != 0 @@ -2064,29 +2075,49 @@ impl Backend { if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Compute) { Ok(_) => {} Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } - let mut queue = cell.lock()?; - if !queue.installed() - || queue.spared_pending() - || !queue.pool_fits(required) - || queue.pending_switch_from().is_some() - || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) - || !lease.is_current() - { - return None; - } - let outer = port.reserve_compute(packet.context.policy().priority()).ok()?; - let mut host = DirectHost { - port, - outer: Some(outer), - generation: port.generation(), + let m5 = self.context.is_m5(); + let priority = packet.context.policy().priority(); + // Reserve M5 outer room before locking the compute cell so an unspent claim drops + // outside the cell lock (dropping an unspent claim can notify availability fences). + let mut m5_outer = if m5 { + Some(port.reserve_m5_compute(priority).ok()?) + } else { + None }; - match queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event)) { + let result = { + let mut queue = cell.lock()?; + if !queue.installed() + || queue.spared_pending() + || !queue.pool_fits(required) + || queue.pending_switch_from().is_some() + || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) + || !lease.is_current() + { + return None; + } + let outer = if m5 { + None + } else { + Some(port.reserve_compute(priority).ok()?) + }; + let mut host = DirectHost { + port, + outer, + m5_outer: m5_outer.as_mut(), + m5, + generation: port.generation(), + }; + queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event)) + }; + drop(m5_outer); + match result { Err(error) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => None, result => Some(result), } diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index be13a089f7a0fb..6525cfc033b5fb 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -449,6 +449,7 @@ impl Firmware { .firmware .port .set_generation(service.firmware.recovery.generation()); + service.firmware.port.reset_m5_history(); service.firmware.rings.invalidate_statistics(); let result = result?; // Counted once the restart is classified, so the restart that reaches the limit has diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 70efc3cbb0f2b5..ee3b5e518da587 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -761,6 +761,7 @@ impl crate::g17::Firmware { // time and attachment overlaps are ordered by publication order. let port = self.port.clone(); let _render = port.render_lock(); + let _m5_outer = self.init.is_m5().then(|| port.m5_outer_lock()); // Both outer destinations must have room before pool accounting or // either inner queue becomes visible. On M5 both are the shared compute ring: one // check covers the pair, and the pair is written against its cursors (this hold From 972395780ba7bed3b7bd878b03f446c40853c412 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sun, 22 Nov 2026 23:19:30 -0500 Subject: [PATCH 1050/1514] drm/asahi: g17: throttle M5 report drain and coalesce event locks Each completion pass in run_runtime_events() / runtime_event_turn() previously took the global device mutex (shared.state) up to five times and ran M5 firmware.drain_reports() (trace/statistics rings plus GPU power register reads) on every completion interrupt, even during tight compute loops where no render mask was pending. Coalesce the worker_deferred take and empty-batch restore into the existing device-mutex holds, avoid dropping and immediately re-acquiring shared.state around a no-op observe_renders() when render masks are zero, and throttle M5 post-signal report draining (drain_post_signal_reports()) to the HOUSEKEEPING_NS (1 ms) cadence while work remains in flight. On recovery passes, drain post-signal reports before service_runtime_recovery() resets firmware rings (matching the unthrottled post-signal ordering and #2909) without double-draining in housekeeping. Add host tests (g17-m5-direct-compute-tests.py) covering mixed render/compute ring wrap, generation-change queued-claim handling, concurrent direct/scoped credit safety, and post-signal/pre-recovery report ordering. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/runtime/events.rs | 370 +++++++++++--------- tools/asahi/g17-m5-direct-compute-tests.py | 259 ++++++++++++++ tools/asahi/run-host-tests.py | 3 + 3 files changed, 464 insertions(+), 168 deletions(-) create mode 100755 tools/asahi/g17-m5-direct-compute-tests.py diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 6525cfc033b5fb..c2be38fa0af383 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -354,6 +354,14 @@ impl Firmware { } } + /// Drains post-signal trace and statistics reports on firmware families that defer them past + /// completion signalling. + fn drain_post_signal_reports(&mut self) { + if self.init.is_m5() { + self.drain_reports(); + } + } + /// A step of the event pass is waiting on the firmware with no event to wake it. fn runtime_polling(&self, now: u64) -> bool { self.render_control_backpressured() @@ -500,26 +508,10 @@ impl crate::g17::Shared { self.stop_runtime(); return; } - let mut deferred = { - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return; - }; - let Some(deferred) = firmware.queues.worker_deferred.take() else { - drop(state); - self.lose_device_quietly(); - return; - }; - deferred - }; crate::g17::trace::event(0); - let result = self.runtime_event_turn(&mut deferred); - deferred.finish(); + let result = self.runtime_event_turn(); crate::g17::trace::event(2); self.queue_feed(); - if let Some(firmware) = (*self.state.lock()).as_deref_mut() { - firmware.queues.worker_deferred = Some(deferred); - } if let Err(error) = result { dev_err!(self.dev.as_ref(), "GPU event service failed: {:?}\n", error); self.lose_device_quietly(); @@ -527,179 +519,221 @@ impl crate::g17::Shared { } } - fn runtime_event_turn(self: &Arc, deferred: &mut DeferredBatch) -> Result { + fn runtime_event_turn(self: &Arc) -> Result { // Taken before consuming records: a request made during this pass gets the next one. let requested = self .housekeeping .swap(false, core::sync::atomic::Ordering::AcqRel); - let (recover, masks) = { + let (deferred, recover, masks) = { let mut state = self.state.lock(); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - let (pending, masks) = firmware.service_runtime_events(deferred)?; + let Some(mut deferred) = firmware.queues.worker_deferred.take() else { + drop(state); + self.lose_device_quietly(); + return Ok(()); + }; + let (pending, masks) = match firmware.service_runtime_events(&mut deferred) { + Ok(out) => out, + Err(error) => { + drop(state); + deferred.finish(); + if let Some(firmware) = (*self.state.lock()).as_deref_mut() { + firmware.queues.worker_deferred = Some(deferred); + } + return Err(error); + } + }; let recover = pending.recovery || firmware.recovery.pending(); if recover { // Epoch closure and event consumption are serialized with every // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - (recover, masks) - }; - deferred.finish(); - crate::g17::trace::event(1); - if recover { - self.preparations - .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; - } - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); + (deferred, recover, masks) }; - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); + let mut deferred = Some(deferred); + if let Some(batch) = deferred.as_mut() { + batch.finish(); } - if firmware.init.is_m5() { - // The completions above are signalled; the reports that arrived with them come after. - firmware.drain_reports(); - } - if recover { - firmware.service_runtime_recovery(deferred)?; - if !firmware.recovery.pending() - && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) - { - if !self.preparations.reopen() { - return Ok(()); + crate::g17::trace::event(1); + let result = (|| -> Result { + let batch = deferred.as_mut().ok_or(EIO)?; + if recover { + self.preparations + .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; + } + let mut state = self.state.lock(); + let Some(firmware) = (*state).as_deref_mut() else { + return Ok(()); + }; + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); + } + // Capture pre-recovery trace/statistics reports before firmware restart resets the + // report rings, matching the non-throttled post-signal ordering. + let mut reports_drained = false; + if recover { + firmware.drain_post_signal_reports(); + reports_drained = true; + firmware.service_runtime_recovery(batch)?; + if !firmware.recovery.pending() + && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) + { + if !self.preparations.reopen() { + return Ok(()); + } + // Restart stopped consumption before its following record. + // Resume builders before observing pairs outside this lock. + self.queue_events(); } - // Restart stopped consumption before its following record. - // Resume builders before observing pairs outside this lock. - self.queue_events(); } - } - // Replay only at this outer boundary, after recovery has settled. - // Publication may service events but must never recurse into replay. - firmware.replay_compute(deferred)?; - firmware.replay_render(deferred)?; - drop(state); - self.observe_renders(masks, deferred)?; - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); - }; - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); - } - let now = super::now_ns(); - let compute = firmware - .queues - .compute - .iter() - .flatten() - .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.in_flight()); - let in_flight = compute || firmware.queues.render_in_flight(); - let idle = firmware.idle_check(now, in_flight)?; - // Expiries, drained pairs, exits, pool and heap trimming and teardown give back what - // retirement freed; a completion needs none of them to retire or to signal. While work - // is in flight and nothing waits for capacity, a pass for firmware records alone skips - // them. Any requested pass, recovery, teardown, a waiter, the last retirement and, at - // the latest, the first pass after HOUSEKEEPING_NS run them all. - let housekeeping = requested - || recover - || !in_flight - || firmware.recovery.pending() - || !firmware.queues.teardown.is_empty() - || self.channels.has_waiters() - || self.progress.has_waiters() - || self.queues.has_waiters() - || self.renders.has_waiters() - || now.saturating_sub( + // Replay only at this outer boundary, after recovery has settled. + // Publication may service events but must never recurse into replay. + firmware.replay_compute(batch)?; + firmware.replay_render(batch)?; + // Pure compute completions have empty render masks: keep the same device-mutex + // hold instead of dropping and immediately re-acquiring around a no-op observe. + if masks != [0; 2] { + drop(state); + self.observe_renders(masks, batch)?; + state = self.state.lock(); + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); + } + } + let Some(firmware) = (*state).as_deref_mut() else { + return Ok(()); + }; + let now = super::now_ns(); + let compute = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.in_flight()); + let in_flight = compute || firmware.queues.render_in_flight(); + let idle = firmware.idle_check(now, in_flight)?; + // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report + // drains give back what retirement freed; a completion needs none of them to retire + // or to signal. While work is in flight and nothing waits for capacity, a pass for + // firmware records alone skips them. Any requested pass, recovery, teardown, a waiter, + // the last retirement and, at the latest, the first pass after HOUSEKEEPING_NS run + // them all. + let housekeeping = requested + || recover + || !in_flight + || firmware.recovery.pending() + || !firmware.queues.teardown.is_empty() + || self.channels.has_waiters() + || self.progress.has_waiters() + || self.queues.has_waiters() + || self.renders.has_waiters() + || now.saturating_sub( + self.housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed), + ) >= HOUSEKEEPING_NS; + let mut lingers = None; + let mut drains = None; + let mut kills = None; + let mut pools = None; + let mut shrinking = false; + if housekeeping { self.housekeeping_ns - .load(core::sync::atomic::Ordering::Relaxed), - ) >= HOUSEKEEPING_NS; - let mut lingers = None; - let mut drains = None; - let mut kills = None; - let mut pools = None; - let mut shrinking = false; - if housekeeping { - self.housekeeping_ns - .store(now, core::sync::atomic::Ordering::Relaxed); - if !firmware.recovery.pending() { - lingers = firmware.expire_render_lingers(now)?; + .store(now, core::sync::atomic::Ordering::Relaxed); + if !reports_drained { + // The completions above are signalled; reports are throttled to the + // housekeeping cadence while work stays in flight. + firmware.drain_post_signal_reports(); + } + if !firmware.recovery.pending() { + lingers = firmware.expire_render_lingers(now)?; + } + drains = firmware.reclaim_drained_renders(batch)?; + firmware.service_compute_exit(batch)?; + kills = firmware.kill_retry_delay(); + pools = firmware.service_compute_pools(batch, now)?; + if !firmware.recovery.pending() { + firmware + .queues + .vacate_evicted_render_pools(&firmware.init, batch)?; + shrinking = firmware + .queues + .shrink_render_heaps(&firmware.init, now, batch); + } + let mut reclaim = self.reclaim.lock(); + firmware.service_teardown(&mut reclaim)?; + if !reclaim.is_empty() { + self.queue_reclaims(); + } } - drains = firmware.reclaim_drained_renders(deferred)?; - firmware.service_compute_exit(deferred)?; - kills = firmware.kill_retry_delay(); - pools = firmware.service_compute_pools(deferred, now)?; - if !firmware.recovery.pending() { - firmware - .queues - .vacate_evicted_render_pools(&firmware.init, deferred)?; - shrinking = firmware - .queues - .shrink_render_heaps(&firmware.init, now, deferred); + // The firmware may consume M5 work-ring slots without a completion interrupt: while + // a preparation waits for unclaimed room, every pass polls the consumers. + let outer = firmware.init.poll_outer_progress()?; + let polling = firmware.runtime_polling(now); + if polling { + self.queue_poll(); } - let mut reclaim = self.reclaim.lock(); - firmware.service_teardown(&mut reclaim)?; - if !reclaim.is_empty() { - self.queue_reclaims(); + // A heap with growth to give back is re-evaluated at least once per + // shrink period, also while the device is otherwise idle. + let idle = if shrinking { + Some(idle.map_or(SHRINK_WAKE_NS, |delay| delay.min(SHRINK_WAKE_NS))) + } else { + idle + }; + // A retained compute pool gives its backing back when it expires, and + // so does an idle render free-list registration. A drained render pair + // whose settlement failed is retried when its backoff ends, and a closed + // context's kill that waited for other work is looked at again. + let idle = [pools, lingers, drains, kills] + .into_iter() + .fold(idle, |idle, expiry| match (idle, expiry) { + (Some(delay), Some(expiry)) => Some(delay.min(expiry)), + (delay, expiry) => delay.or(expiry), + }); + if let Some(delay) = idle { + self.queue_idle(delay); + } + if firmware.recovery.pending() { + self.preparations.close(); + self.queue_events(); + } else if !recover + && !polling + && (channel::Events::pending(&firmware.init, Role::Primary)? + || (firmware.secondary.is_some() + && channel::Events::pending(&firmware.init, Role::Secondary)?)) + { + // A full bounded pass must not depend on a fresh notification for + // records that arrived while it was consuming the same ring. + self.queue_event_records(); + } + let grow_ready = firmware.render_grow_ready(); + if batch.pending() == 0 { + firmware.queues.worker_deferred = deferred.take(); + } + drop(state); + if grow_ready { + self.queue_grow(); + } + // Outside the device mutex: the notification can run DMA-fence callbacks. + if let Some(domain) = outer { + domain.notify(); + } + // Firmware ring room, consumed releases and teardown steps have no + // event of their own: recheck render publishers' conditions every pass. + if self.renders.has_waiters() { + self.renders.notify(); + } + Ok(()) + })(); + if let Some(mut batch) = deferred.take() { + batch.finish(); + if let Some(firmware) = (*self.state.lock()).as_deref_mut() { + firmware.queues.worker_deferred = Some(batch); } } - // The firmware may consume M5 work-ring slots without a completion interrupt: while - // a preparation waits for unclaimed room, every pass polls the consumers. - let outer = firmware.init.poll_outer_progress()?; - let polling = firmware.runtime_polling(now); - if polling { - self.queue_poll(); - } - // A heap with growth to give back is re-evaluated at least once per - // shrink period, also while the device is otherwise idle. - let idle = if shrinking { - Some(idle.map_or(SHRINK_WAKE_NS, |delay| delay.min(SHRINK_WAKE_NS))) - } else { - idle - }; - // A retained compute pool gives its backing back when it expires, and - // so does an idle render free-list registration. A drained render pair - // whose settlement failed is retried when its backoff ends, and a closed - // context's kill that waited for other work is looked at again. - let idle = [pools, lingers, drains, kills] - .into_iter() - .fold(idle, |idle, expiry| match (idle, expiry) { - (Some(delay), Some(expiry)) => Some(delay.min(expiry)), - (delay, expiry) => delay.or(expiry), - }); - if let Some(delay) = idle { - self.queue_idle(delay); - } - if firmware.recovery.pending() { - self.preparations.close(); - self.queue_events(); - } else if !recover - && !polling - && (channel::Events::pending(&firmware.init, Role::Primary)? - || (firmware.secondary.is_some() - && channel::Events::pending(&firmware.init, Role::Secondary)?)) - { - // A full bounded pass must not depend on a fresh notification for - // records that arrived while it was consuming the same ring. - self.queue_event_records(); - } - let grow_ready = firmware.render_grow_ready(); - drop(state); - if grow_ready { - self.queue_grow(); - } - // Outside the device mutex: the notification can run DMA-fence callbacks. - if let Some(domain) = outer { - domain.notify(); - } - // Firmware ring room, consumed releases and teardown steps have no - // event of their own: recheck render publishers' conditions every pass. - if self.renders.has_waiters() { - self.renders.notify(); - } - Ok(()) + result } } diff --git a/tools/asahi/g17-m5-direct-compute-tests.py b/tools/asahi/g17-m5-direct-compute-tests.py new file mode 100755 index 00000000000000..68bd7eff4f1861 --- /dev/null +++ b/tools/asahi/g17-m5-direct-compute-tests.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 direct compute outer-ring credits and post-signal report ordering. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Mixed render (2-slot) and compute (1-slot) reservations/consumptions across + `WORK_RING_SLOTS` ring wrap and exact capacity boundaries. +2. Queued claims held across a generation change and `OuterScope` (locked render / + recovery), verifying waiters wake on drop and direct consumption never debits + `OuterScope`'s `published[]` counter. +3. Multi-threaded contention between concurrent direct compute reservations/consumptions + and periodic locked `OuterScope` transitions. +4. Structural verification of `runtime_event_turn()` in `runtime/events.rs`: + completions signal (`batch.finish()`) before report drains, recovery drains + reports before `service_runtime_recovery()` regardless of `HOUSEKEEPING_NS`, + and steady-state passes throttle report drains without double-draining on recovery. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + events_src = (G17 / 'runtime/events.rs').read_text() + + turn = item(events_src, 'fn runtime_event_turn(') + if mutation == 'no-pre-recovery-drain': + turn = turn.replace( + 'firmware.drain_post_signal_reports();\n reports_drained = true;\n' + ' firmware.service_runtime_recovery(batch)?;', + 'firmware.service_runtime_recovery(batch)?;', + 1, + ) + + # Verify report-drain ordering contract in production runtime_event_turn(). + ordering_ok = ordered_ok( + turn, + 'if let Some(batch) = deferred.as_mut() {\n batch.finish();\n }', + 'let mut reports_drained = false;', + 'firmware.drain_post_signal_reports();\n reports_drained = true;', + 'firmware.service_runtime_recovery(batch)?;', + 'if housekeeping {', + 'if !reports_drained {', + ) + + # Strip kernel imports, inner doc comments, and kunit module from outer_credit.rs for host compilation. + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + if mutation == 'direct-debits-published': + prod = prod.replace( + 'self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel);', + 'self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel);\n' + ' self.published[claim.priority].fetch_add(1, Ordering::AcqRel);', + 1, + ) + elif mutation == 'scope-allows-reserve': + prod = prod.replace( + 'if self.scoped.load(Ordering::Acquire) { return Err(EBUSY); }', + '', + 1, + ) + + return f''' +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +fn test_mixed_wrap_and_generation_change() {{ + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + let mut ca = n - 6; + let mut cb = n - 6; + let mut prod_idx = n - 2; + + let mut render_claim = credits.reserve(2, 2, [ca, cb, prod_idx]).unwrap(); + let mut comp_a = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_a).unwrap(); + prod_idx = (prod_idx + 1) % n; + + let mut comp_b = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_b).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(prod_idx, 0); + + let rem = credits.capacity(2, [ca, cb, prod_idx]).unwrap(); + let filler = credits.reserve(2, rem - 1, [ca, cb, prod_idx]).unwrap(); + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [ca, cb, prod_idx]).err(), Some(EBUSY)); + let mut edge = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut edge).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 0); + drop(filler); + + ca = 1; + cb = 1; + let wrapped = [ca, cb, prod_idx]; + assert!(credits.progressed(2, wrapped).unwrap()); + + // Hold a queued compute claim across OuterScope + generation change. + let queued_comp = credits.reserve(2, 1, wrapped).unwrap(); + let mut pre_direct = credits.reserve(2, 1, wrapped).unwrap(); + let notes_before = credits.available().notifications(); + {{ + let _scope = credits.scope(&mut render_claim).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + // A direct compute claim already reserved before OuterScope must not debit OuterScope. + credits.consume_direct(&mut pre_direct).unwrap(); + }} + assert!(!credits.is_scoped()); + assert_eq!(render_claim.remaining(), 2, "direct compute must not debit OuterScope"); + assert_eq!(credits.counter(2).unwrap().load(Ordering::Acquire), 0); + + // Generation changed: dropping the queued compute claim restores its credit and wakes waiters. + drop(queued_comp); + assert!(credits.available().notifications() > notes_before); + drop(render_claim); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); +}} + +fn test_concurrent_direct_and_scoped() {{ + let credits = Credits::new().unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = credits.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 2000 {{ + if let Ok(mut claim) = c.reserve(1, 1, [0, 0, 0]) {{ + if iters % 5 == 0 {{ + drop(claim); + }} else {{ + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + for _ in 0..200 {{ + if let Ok(mut render_claim) = credits.reserve(1, 2, [0, 0, 0]) {{ + let mut scoped = false; + if let Ok(scope) = credits.scope(&mut render_claim) {{ + assert_eq!(credits.reserve(1, 1, [0, 0, 0]).err(), Some(EBUSY)); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + drop(scope); + scoped = true; + }} + if scoped {{ + assert_eq!(render_claim.remaining(), 0); + }} + }} + }} + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + assert_eq!(credits.capacity(1, [0, 0, 0]).unwrap(), WORK_RING_SLOTS - 1); +}} + +fn main() {{ + assert!({str(ordering_ok).lower()}, "runtime_event_turn must drain reports post-signal and pre-recovery"); + test_mixed_wrap_and_generation_change(); + test_concurrent_direct_and_scoped(); + println!("PASS g17-m5-direct-compute-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-pre-recovery-drain', + 'direct-debits-published', + 'scope-allows-reserve']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-dc-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1244ff626dfacb..1fe3cb269324e0 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -254,6 +254,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), + 'g17-m5-direct-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('no-pre-recovery-drain', 'direct-debits-published', + 'scope-allows-reserve'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 73103a87f990685ea58f38aa38929c7240430ac0 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 00:21:48 -0500 Subject: [PATCH 1051/1514] drm/asahi: g17: enable direct render submission on M5 On M5 (G17S/G17C/G17D), render_direct() returned None unconditionally, forcing every steady-state TA/3D render pass through the global device mutex (shared.state) across prepare_render() and publish_render(), serializing multi-pass graphics and multi-queue render submissions against each other and the event worker. Extend Port and OuterCredits so steady-state M5 render pairs can reserve two slots on M5's shared outer ring under the existing lock order (render publication lock -> m5_outer -> admission, QoS, mailbox), write both Compute-master WorkSlots, issue the HardwareSubmission::advance_pair host-port write, expose the retained pair while consuming two direct credits, and record submission history and the pipe-2 doorbell (pipe 0 on J813) without holding shared.state across preparation or publication. Bind M5 PB tokens via acquire_owner_bound() in lend_render(), track the submitting CPU in render_direct(), and extend the asahi_g17_outer_credit KUnit test to cover two-slot direct render credit consumption. Signed-off-by: Diljit Singh --- .../drm/asahi/g17/initdata/outer_credit.rs | 24 +- drivers/gpu/drm/asahi/g17/port.rs | 154 ++++++++- drivers/gpu/drm/asahi/g17/runtime/render.rs | 26 +- .../drm/asahi/g17/runtime/render/direct.rs | 133 ++++++-- .../asahi/g17-render-direct-recovery-tests.py | 293 ++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 6 files changed, 595 insertions(+), 38 deletions(-) create mode 100755 tools/asahi/g17-render-direct-recovery-tests.py diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index 84901b7afdd92a..b8d4fb79ba2607 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -79,17 +79,23 @@ impl Credits { Ok(OuterClaim { domain: self.clone(), priority: index, remaining: count }) } - /// Consumes one reserved slot for a direct M5 compute publication without touching + /// Consumes one reserved slot for a direct M5 publication without touching /// `published[]`, so an enclosing device-mutex `OuterScope` never debits a direct slot. pub(crate) fn consume_direct(&self, claim: &mut OuterClaim) -> Result { - if !core::ptr::eq(self, &*claim.domain) { + self.consume_direct_count(claim, 1) + } + + /// Consumes `count` reserved slots for a direct M5 publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits direct slots. + pub(crate) fn consume_direct_count(&self, claim: &mut OuterClaim, count: u32) -> Result { + if count == 0 || !core::ptr::eq(self, &*claim.domain) { return Err(EINVAL); } - if claim.remaining == 0 { + if claim.remaining < count { return Err(EIO); } - claim.remaining -= 1; - self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel); + claim.remaining -= count; + self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel); Ok(()) } @@ -158,12 +164,15 @@ mod tests { let full = free(cursors).unwrap(); let mut scoped_claim = credits.reserve(1, 2, cursors).unwrap(); let mut direct_claim = credits.reserve(1, 1, cursors).unwrap(); - assert_eq!(credits.capacity(1, cursors).unwrap(), full - 3); + let mut direct_pair = credits.reserve(1, 2, cursors).unwrap(); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 5); - // Direct publish consumes only its own reserved slot and leaves published[] untouched. + // Direct publish consumes only its own reserved slots and leaves published[] untouched. assert!(!credits.is_scoped()); credits.consume_direct(&mut direct_claim).unwrap(); assert_eq!(direct_claim.remaining(), 0); + credits.consume_direct_count(&mut direct_pair, 2).unwrap(); + assert_eq!(direct_pair.remaining(), 0); assert_eq!(credits.capacity(1, cursors).unwrap(), full - 2); assert_eq!(credits.counter(1).unwrap().load(Ordering::Acquire), 0); @@ -176,6 +185,7 @@ mod tests { assert!(!credits.is_scoped()); assert_eq!(scoped_claim.remaining(), 2); drop(direct_claim); + drop(direct_pair); drop(scoped_claim); assert_eq!(credits.capacity(1, cursors).unwrap(), full); } diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 6386ec3bc0c414..e389402aa0875b 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -158,6 +158,21 @@ impl RenderRoom { } } +/// Room for two slots on M5's shared outer work ring of one priority, reserved under +/// both the render publication lock and `m5_outer`. +#[derive(Clone, Copy)] +pub(super) struct M5RenderRoom { + priority: u8, + start: u32, + next: [u32; 2], +} + +impl M5RenderRoom { + pub(super) fn priority(&self) -> u8 { + self.priority + } +} + /// A compute work-ring slot reserved before any command becomes visible. Dropping an unused /// claim returns the slot. pub(super) struct OuterClaim<'a> { @@ -397,10 +412,19 @@ impl Port { /// Counts `submissions` in the M5 submission-history table without taking the device mutex. pub(super) fn note_m5_submission_history(&self, submissions: u8) -> Result { + let mut geometry = self.m5_outer.lock(); + self.note_m5_submission_history_locked(&mut geometry, submissions) + } + + /// [`Self::note_m5_submission_history`] while the caller already holds `m5_outer`. + pub(super) fn note_m5_submission_history_locked( + &self, + geometry: &mut MutexGuard<'_, Option<(u32, u64, u64)>>, + submissions: u8, + ) -> Result { let Some(history) = self.views()?.m5_history else { return Ok(()); }; - let mut geometry = self.m5_outer.lock(); for _ in 0..64 { // SAFETY: Pointers name retained, bounds-checked firmware-shared words. let generation = unsafe { (*history.generation).load(Ordering::Acquire) }; @@ -408,7 +432,7 @@ impl Port { core::hint::spin_loop(); continue; } - let (period, count) = match *geometry { + let (period, count) = match **geometry { Some((seen, period, count)) if seen == generation => (period, count), _ => { // SAFETY: As above; seqlock generation recheck validates consistency. @@ -428,7 +452,7 @@ impl Port { } let period = u64::from(c[0]) | (u64::from(c[1]) << 32); let count = u64::from(c[2]) | (u64::from(c[3]) << 32); - *geometry = Some((generation, period, count)); + **geometry = Some((generation, period, count)); (period, count) } }; @@ -453,6 +477,130 @@ impl Port { Err(EBUSY) } + /// Reserves two slots on M5's shared outer ring for a direct render pair while + /// `m5_outer` is already held. Returns EBUSY if a device-mutex OuterScope is active + /// or fewer than two slots are free. + pub(super) fn reserve_m5_render_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + priority: u8, + ) -> Result<(M5RenderRoom, super::initdata::OuterClaim)> { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + let start = cursors[2]; + let next = [(start + 1) % WORK_RING_SLOTS, (start + 2) % WORK_RING_SLOTS]; + if next.iter().any(|&p| p == cursors[0] || p == cursors[1]) { + return Err(EBUSY); + } + let claim = credits.reserve(priority, 2, cursors)?; + Ok(( + M5RenderRoom { + priority, + start, + next, + }, + claim, + )) + } + + /// Copies an M5 render pair's fragment, then tiling record into the two reserved slots + /// of M5's shared outer ring without exposing them, commits accounting, issues the + /// host-port advance, and publishes inner producers (as `Firmware::submit_m5_render_pair`). + #[expect( + clippy::too_many_arguments, + reason = "Mirrors write_render_pair with the held M5 outer lock." + )] + pub(super) fn write_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + fragment: &WorkSlot, + tiling: &WorkSlot, + commit_accounting: impl FnOnce() -> Result, + publish_inner: impl FnOnce(), + ) -> Result<[u32; 2]> { + if !matches!(fragment.data_master, 1 | 2) || !matches!(tiling.data_master, 0 | 2) { + return Err(EINVAL); + } + let regs = self.regs.as_ref().ok_or(ENODEV)?; + let (_, ring) = self.ring(room.priority)?; + let records = [ + WorkSlot::new( + DataMaster::Compute, + fragment.queue_va, + fragment.qid, + fragment.items_end, + fragment.first != 0, + )?, + WorkSlot::new( + DataMaster::Compute, + tiling.queue_va, + tiling.qid, + tiling.items_end, + tiling.first != 0, + )?, + ]; + let submission = super::fw::m5::queue::HardwareSubmission::advance_pair( + fragment.qid, + tiling.qid, + )?; + let destinations = [room.start, room.next[0]].map(|index| { + // SAFETY: The ring view spans WORK_RING_SLOTS records; `reserve_m5_render_locked` + // validated both indices are in range and host-owned while `m5_outer` stays held. + unsafe { + ring.slots + .add(index as usize * core::mem::size_of::()) + } + }); + for (record, destination) in records.iter().zip(destinations) { + // SAFETY: Both slots are distinct, reserved, and protected by `m5_outer`. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + destination, + core::mem::size_of::(), + ); + } + } + commit_accounting()?; + regs.submit_m5_work(&submission)?; + publish_inner(); + Ok(room.next) + } + + /// Exposes a retained M5 render pair written by `write_m5_render_pair` with one + /// producer update and consumes its two direct outer-ring credits. + pub(super) fn expose_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + claim: &mut super::initdata::OuterClaim, + next: [u32; 2], + ) -> Result { + if next != room.next { + return Err(EBUSY); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(room.priority)?; + if ring.cursors()?[2] != room.start { + return Err(EBUSY); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`; `m5_outer` has been held continuously + // since `reserve_m5_render_locked` and `write_m5_render_pair`. + unsafe { (*ring.producer).store(room.next[1], Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct_count(claim, 2) + } + fn render_rings(&self, priority: u8) -> Result<(RingView, RingView)> { let views = self.views()?; let index = usize::from(priority); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 450234d27cbb7d..a3b79e1f507729 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -629,6 +629,23 @@ impl Host<'_> { } } } +/// Encodes the G17 render mailbox doorbell (0x83, priority in bits 3:2, pipe in bits 1:0). +/// +/// Firmware queue contract across both locked and direct render publishers: +/// - Non-M5 G17 submits render pairs to the dedicated tiling/fragment rings and rings pipe 0. +/// - M5 Pro/Max/Ultra (!J813_FORMS) submits render pairs into the shared compute work ring paired +/// with host-port gating writes and submission-history accounting, and rings pipe 2. +/// - J813 (J813_FORMS, common 26A428 firmware) uses the mailbox-only G17P queue forms (no +/// host-port or KSM register writes) and rings pipe 0. +fn render_doorbell_message(m5: bool, priority: u8) -> u64 { + let pipe = if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { + 2 + } else { + 0 + }; + (0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2 | pipe +} + impl crate::g17::queue::render::Host for Host<'_> { fn generation(&self) -> u64 { self.firmware.recovery.generation() @@ -792,11 +809,10 @@ impl crate::g17::queue::render::Host for Host<'_> { self.firmware.bridge.regs.g17_core_power() }); } - let result = self.firmware.primary.notify( - (0x83 << crate::g17::MSG_TYPE_SHIFT) - | u64::from(priority) << 2 - | if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { 2 } else { 0 }, - ); + let result = self + .firmware + .primary + .notify(render_doorbell_message(m5, priority)); if result.is_err() { self.firmware.primary.state.shared.lose_device_quietly(); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 117edccb28e350..0a7223d77c2b67 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -14,7 +14,7 @@ use super::super::{Backend, DeferredBatch}; use crate::g17::{ job::Packet, object::Allocator, - port::{Port, RenderRoom}, + port::{M5RenderRoom, Port, RenderRoom}, queue::render::{Pair, PublicationLease, RenderAddresses}, }; use core::sync::atomic::Ordering; @@ -33,13 +33,20 @@ pub(in crate::g17::runtime) struct Loan { uat: Arc, } +enum DirectTarget { + Legacy(RenderRoom), + M5(M5RenderRoom), +} + /// Publication host of a lent pair. Registration, first-publication and /// growth paths never run here: the loan requires an installed, registered /// graph that needs no growth. struct DirectHost<'a> { port: &'a Port, render: &'a MutexGuard<'a, ()>, - room: RenderRoom, + m5_outer: Option>>, + m5_claim: Option<&'a mut crate::g17::initdata::OuterClaim>, + target: DirectTarget, generation: u64, activation: Option<(u16, u64)>, } @@ -83,11 +90,36 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { commit: impl FnOnce() -> Result, late_tiling: impl FnOnce(), ) -> Result<[u32; 2]> { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + self.port.write_render_pair( + self.render, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + self.port.write_m5_render_pair( + self.render, + m5_outer, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } } - self.port - .write_render_pair(self.render, &self.room, fragment, tiling, commit, late_tiling) } fn publish_configuration_pair( &mut self, @@ -96,7 +128,7 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, _prepare: impl FnOnce(), ) -> Result { - // Only M5 publishes configuration pairs, never on this path. + // Cold-install configuration pairs never run on an already-registered pair. Err(EINVAL) } fn activate_render_pool(&mut self, id: u16, generation: u64) -> Result { @@ -112,15 +144,34 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, next: [u32; 2], ) -> Result { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + self.port.expose_render_pair(self.render, room, next) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + let claim = self.m5_claim.as_deref_mut().ok_or(EIO)?; + self.port + .expose_m5_render_pair(self.render, m5_outer, room, claim, next) + } } - self.port.expose_render_pair(self.render, &self.room, next) } - /// Pipe 0 (tiling) in bits 1:0, priority class in bits 3:2. + /// Rings the shared render doorbell contract ([`super::render_doorbell_message`]). fn notify_render(&mut self, priority: u8) -> Result { - self.port - .notify((0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2) + let m5 = matches!(self.target, DirectTarget::M5(_)); + if m5 { + let geometry = self.m5_outer.as_mut().ok_or(EIO)?; + if let Err(error) = self.port.note_m5_submission_history_locked(geometry, 2) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + } + self.port.notify(super::render_doorbell_message(m5, priority)) } fn note_submission(&mut self) -> Result { // Counted, with full effort witnessed, before the pair was lent. @@ -178,13 +229,24 @@ impl crate::g17::Firmware { let qids = pair.qids(); let pool = pair.pool().clone(); let buffer_id = pair.buffer_id(); + // An M5 PB token is bound to the hardware context and PB state it names. + let buffer_context = pair + .m5_pb_state_va() + .map(|pb_va| (packet.context.id(), pb_va)); let addresses = RenderAddresses { stamps: [ self.init.stamp_addresses(qids[0])?, self.init.stamp_addresses(qids[1])?, ], }; - let (buffer, buffer_token) = self.queues.buffers.acquire_owner(buffer_id)?; + let (buffer, buffer_token) = match buffer_context { + Some((context, pb_va)) => { + self.queues + .buffers + .acquire_owner_bound(buffer_id, context, pb_va)? + } + None => self.queues.buffers.acquire_owner(buffer_id)?, + }; let preparation = match self.queues.render.pools.prepare(&self.init, &pool) { Ok(preparation) => preparation, Err(error) => { @@ -199,7 +261,7 @@ impl crate::g17::Firmware { let lease = PublicationLease { free_list_generation: preparation.generation, buffer_token, - buffer_context: None, + buffer_context: buffer_context.map(|(context, _)| context), }; let pair = match self.queues.render.take_pair(slot, owner, packet) { Ok(pair) => pair, @@ -280,10 +342,8 @@ impl Backend { deferred: &mut DeferredBatch, ) -> Option { // A compute prefix needs the compute queue's state; leave it to the - // device-mutex path. M5 renders publish through the device mutex - // only: their host-port transaction is part of the publication. - if packet.context.is_m5() - || packet.is_published() + // device-mutex path. + if packet.is_published() || packet.cancel_requested() || packet.completion.status().get() != 0 || packet.order.wait_through[1].unwrap_or(0) != 0 @@ -303,12 +363,14 @@ impl Backend { if !port.note_submission() { return None; } + self.shared.note_submitter(); self.shared.note_gpu_activity(); match packet.completion.work_state().ok()?.acquire(crate::g17::job::Engine::Render) { Ok(_) => {} Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } + let m5 = packet.context.is_m5(); let priority = packet.context.policy().priority(); let generation = port.generation(); let dev = self.shared.drm().ok()?; @@ -325,6 +387,10 @@ impl Backend { } }; let mut activation = None; + let mut recovery_started = false; + // Declared outside the publication closure so any unspent M5 outer claim drops + // after `m5_outer` and `render` are released (dropping an unspent claim can wake fences). + let mut m5_claim = None; let result = (|| { let pair = loan.pair.as_mut().ok_or(EIO)?; let alloc = Allocator { @@ -336,7 +402,14 @@ impl Backend { if !lease.is_current() { return Err(EBUSY); } - let room = port.observe_render_room(&render, priority)?.ok_or(EBUSY)?; + let m5_outer = m5.then(|| port.m5_outer_lock()); + let target = if let Some(guard) = m5_outer.as_ref() { + let (room, claim) = port.reserve_m5_render_locked(guard, priority)?; + m5_claim = Some(claim); + DirectTarget::M5(room) + } else { + DirectTarget::Legacy(port.observe_render_room(&render, priority)?.ok_or(EBUSY)?) + }; let mut dependencies = pair.own_dependencies(self.owner, packet)?; if let Some(footprint) = packet.footprint.as_ref() { dependencies.hazard_count = self.admission.publication_barriers( @@ -350,7 +423,9 @@ impl Backend { let mut host = DirectHost { port, render: &render, - room, + m5_outer, + m5_claim: m5_claim.as_mut(), + target, generation, activation: None, }; @@ -362,13 +437,22 @@ impl Backend { &mut |event| deferred.push(event), ); activation = host.activation; + drop(host); result?; - // A recovery that started meanwhile may have discarded the commands. - if port.generation() != generation || port.recovery_state()? != 0 { + // A generation advance while lent means the commands belong to a closed epoch. + if port.generation() != generation { return Err(EIO); } + // If recovery started during publication while our preparation lease still held + // the same generation, return_render() hands the published pair back before lease + // drops so the existing recovery pass settles or replays it once without failing + // an unrelated client's VM. + if port.recovery_state()? != 0 { + recovery_started = true; + } Ok(()) })(); + drop(m5_claim); let returned = { let mut state = self.shared.state.lock(); match (*state).as_deref_mut() { @@ -388,6 +472,9 @@ impl Backend { }; self.shared.note_changed(); drop(lease); + if recovery_started { + self.shared.queue_events(); + } if let Err(error) = returned { self.shared.lose_device_quietly(); return Some(Err(error)); diff --git a/tools/asahi/g17-render-direct-recovery-tests.py b/tools/asahi/g17-render-direct-recovery-tests.py new file mode 100755 index 00000000000000..ef1bd4360769e0 --- /dev/null +++ b/tools/asahi/g17-render-direct-recovery-tests.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host lifecycle test for render_direct() recovery crossing publication and doorbell contract. + +Compiles production `render_doorbell_message()` (from `runtime/render.rs`) and +`finish_publication()` (from `runtime/backend.rs`), and drives the real +post-publication recovery check extracted from `render_direct()` +(`runtime/render/direct.rs`) through a full lifecycle harness: +1. Recovery starts while a render pair is lent and published (same generation, + `recovery_state != 0`): `render_direct()` returns `Ok(())`, `return_render()` + returns the published pair before `lease` drops, `queue_events()` runs, + `finish_publication()` does NOT fail the unrelated client's VM, and the + subsequent recovery pass settles the pair exactly once. +2. Generation changes mid-publication (`port.generation() != generation`): + `render_direct()` returns `Err(EIO)` and `finish_publication()` fails the VM. +3. Shared `render_doorbell_message()` contract: M5 (!J813_FORMS) uses pipe 2, + J813 (J813_FORMS) uses pipe 0, non-M5 uses pipe 0, and both render publishers + delegate to `render_doorbell_message()`. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + render_src = (G17 / 'runtime/render.rs').read_text() + direct_src = (G17 / 'runtime/render/direct.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + doorbell_fn = item(render_src, 'fn render_doorbell_message(') + direct_fn = item(direct_src, 'pub(in crate::g17::runtime) fn render_direct(') + finish_fn = item(backend_src, 'pub(super) fn finish_publication(').replace('pub(super) ', '') + + if mutation == 'wrong-j813-pipe': + doorbell_fn = doorbell_fn.replace( + 'if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed)', + 'if m5', + 1, + ) + + # Extract the exact post-publication check block from render_direct(). + check_start = direct_fn.index('result?;') + check_end = direct_fn.index('Ok(())\n })();', check_start) + len('Ok(())') + post_publish = direct_fn[check_start:check_end] + + if mutation == 'recovery-state-eio': + post_publish = post_publish.replace( + 'if port.recovery_state()? != 0 {\n recovery_started = true;\n }', + 'if port.recovery_state()? != 0 {\n return Err(EIO);\n }', + 1, + ) + elif mutation == 'drop-generation-check': + post_publish = post_publish.replace( + 'if port.generation() != generation {\n return Err(EIO);\n }', + '', + 1, + ) + + # Verify both locked and direct render publishers share render_doorbell_message() + # and that render_direct() returns the pair and drops lease before queueing events. + shared_contract = ( + 'notify(render_doorbell_message(m5, priority))' in render_src + and 'self.port.notify(super::render_doorbell_message(m5, priority))' in direct_src + and direct_src.count('J813_FORMS') == 0 + ) + order_tokens = [ + 'firmware.return_render(slot, &mut loan, activation, packet)', + 'self.shared.note_changed();', + 'drop(lease);', + 'if recovery_started {\n self.shared.queue_events();\n }', + ] + order_ok = True + pos = -1 + for tok in order_tokens: + if direct_fn.count(tok) != 1 or direct_fn.index(tok) <= pos: + order_ok = False + break + pos = direct_fn.index(tok) + + doorbell_host = doorbell_fn.replace('crate::g17::', 'g17_stub::') + + return f''' +use std::cell::Cell; +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicUsize, Ordering}}}}; + +const EIO: i32 = -5; +const ETIMEDOUT: i32 = -110; +const ENODEV: i32 = -19; +type Result = std::result::Result; +type Fence = u8; + +mod g17_stub {{ + use std::sync::atomic::AtomicBool; + pub const MSG_TYPE_SHIFT: u32 = 48; + pub static J813_FORMS: AtomicBool = AtomicBool::new(false); +}} + +{doorbell_host} + +#[derive(PartialEq, Eq)] +enum Engine {{ Render, Compute }} + +struct Status(Cell); +impl Status {{ fn get(&self) -> i32 {{ self.0.get() }} }} + +struct Completion {{ + status: Status, + unpublished_fails: Cell, +}} +impl Completion {{ + fn status(&self) -> &Status {{ &self.status }} + fn fail_unpublished(&self, _: i32) {{ self.unpublished_fails.set(self.unpublished_fails.get() + 1); }} + fn scheduler_fence(&self) -> Fence {{ 1 }} +}} + +struct Packet {{ + published: Cell, + completion: Arc, +}} +impl Packet {{ + fn is_published(&self) -> bool {{ self.published.get() }} + fn engine(&self) -> Engine {{ Engine::Render }} +}} + +struct DeferredBatch {{ finished: usize }} +impl DeferredBatch {{ fn finish(&mut self) {{ self.finished += 1; }} }} + +mod job {{ + pub trait Backend {{ + fn fail_vm(&self, error: i32); + }} +}} + +struct Port {{ + gen: Cell, + rec_state: Cell, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.get() }} + fn recovery_state(&self) -> Result {{ Ok(self.rec_state.get()) }} +}} + +struct RecoveryHarness {{ + vm_failed: Cell, + events_queued: Cell, + pair_returned_before_lease_drop: Cell, + lease_held: Cell, + pair_in_registry: Cell, + settlements: Cell, + stop_called: Cell, +}} + +impl job::Backend for RecoveryHarness {{ + fn fail_vm(&self, _error: i32) {{ + self.vm_failed.set(true); + }} +}} + +impl RecoveryHarness {{ + fn stop_after_error(&self) {{ self.stop_called.set(true); }} + fn rollback_unpublished_compute(&self) -> Result {{ Ok(()) }} + + {finish_fn} + + fn run_direct_publish_lifecycle(&self, port: &Port, generation: u64, packet: &Arc) -> Result {{ + self.lease_held.set(true); + self.pair_in_registry.set(false); + let mut recovery_started = false; + let result: Result = (|| {{ + let result: Result = Ok(()); + packet.published.set(true); + {post_publish} + }})(); + // return_render() places the published pair back while lease is still held. + self.pair_in_registry.set(true); + self.pair_returned_before_lease_drop.set(self.lease_held.get()); + self.lease_held.set(false); + if recovery_started {{ + self.events_queued.set(self.events_queued.get() + 1); + }} + let mut deferred = DeferredBatch {{ finished: 0 }}; + self.finish_publication(packet, result, &mut deferred) + }} + + fn run_recovery_pass(&self, port: &Port) {{ + // Recovery drains preparations (lease must already be dropped) and settles the returned pair once. + assert!(!self.lease_held.get(), "recovery must wait for lease drop"); + if self.pair_in_registry.get() && port.recovery_state().unwrap() != 0 {{ + self.settlements.set(self.settlements.get() + 1); + port.gen.set(port.gen.get() + 1); + port.rec_state.set(0); + self.pair_in_registry.set(false); + }} + }} +}} + +fn new_packet() -> Arc {{ + Arc::new(Packet {{ + published: Cell::new(false), + completion: Arc::new(Completion {{ + status: Status(Cell::new(0)), + unpublished_fails: Cell::new(0), + }}), + }}) +}} + +fn new_harness() -> RecoveryHarness {{ + RecoveryHarness {{ + vm_failed: Cell::new(false), + events_queued: Cell::new(0), + pair_returned_before_lease_drop: Cell::new(false), + lease_held: Cell::new(false), + pair_in_registry: Cell::new(false), + settlements: Cell::new(0), + stop_called: Cell::new(false), + }} +}} + +fn main() {{ + assert!({str(shared_contract).lower()}, "both render publishers must share render_doorbell_message"); + assert!({str(order_ok).lower()}, "render_direct must return pair before dropping lease and queueing events"); + + // 1. Doorbell pipe contract. + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + assert_eq!(render_doorbell_message(false, 2) & 3, 0); + assert_eq!(render_doorbell_message(true, 2) & 3, 2); + assert_eq!((render_doorbell_message(true, 3) >> 2) & 3, 3); + g17_stub::J813_FORMS.store(true, Ordering::Relaxed); + assert_eq!(render_doorbell_message(true, 2) & 3, 0); + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + + // 2. Recovery crosses publication (same generation, recovery_state != 0): + // unrelated client keeps its VM, pair is returned before lease drop, and settles once. + let h = new_harness(); + let port = Port {{ gen: Cell::new(7), rec_state: Cell::new(1) }}; + let pkt = new_packet(); + let fence = h.run_direct_publish_lifecycle(&port, 7, &pkt).unwrap(); + assert_eq!(fence, 1); + assert!(!h.vm_failed.get(), "unrelated client VM must survive recovery crossing publication"); + assert!(h.pair_returned_before_lease_drop.get()); + assert_eq!(h.events_queued.get(), 1); + h.run_recovery_pass(&port); + h.run_recovery_pass(&port); + assert_eq!(h.settlements.get(), 1, "published pair must settle exactly once"); + + // 3. Generation changed mid-publication: fails with EIO and fails VM. + let h2 = new_harness(); + let port2 = Port {{ gen: Cell::new(8), rec_state: Cell::new(0) }}; + let pkt2 = new_packet(); + assert_eq!(h2.run_direct_publish_lifecycle(&port2, 7, &pkt2).err(), Some(EIO)); + assert!(h2.vm_failed.get(), "generation mismatch must fail VM"); + + println!("PASS g17-render-direct-recovery-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['recovery-state-eio', + 'drop-generation-check', + 'wrong-j813-pipe']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-rd-rec-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1fe3cb269324e0..e768d930cc34d3 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -269,6 +269,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-quarantine-drain-tests.py': [([], PASS)] + mutations('--mutation', ('no-drain-release', 'without-witness', 'ignore-leases', 'no-last-lease', 'witness-covers-later-failure', 'unquarantined-drain'), []), + 'g17-render-direct-recovery-tests.py': [([], PASS)] + + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', + 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], 'g17-shared-pool-tests.py': [([], PASS)], 'g17-t6041-initdata-tests.py': [([], PASS)], From 8a1ec931203434b0548d832d1ff765d340015fa5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 03:06:22 -0500 Subject: [PATCH 1052/1514] drm/asahi: g17: reduce M5 direct submit and event lock overhead Eliminate remaining mutex and MMIO overhead on the M5 direct submission and completion paths: - Coalesce M5 compute_direct() outer-ring publication, host-port submission, and submission-history update under one held Port::m5_outer guard (released before ringing the mailbox doorbell), avoiding repeated mutex round-trips and keeping m5_outer free during descriptor writes. - Skip the uncached G17_CORE_POWER MMIO read in Port::note_gpu_activity() when back-to-back work falls within FIRMWARE_IDLE_OFF_MS. - Expose Port::outer_domain() and Port::reserve_m5_outer() so steady-state prepare_compute() acquires M5 outer-ring availability and credits without locking shared.state. - Track active, retiring, terminal, witness, replay and polling slots with bitmasks in scan_compute_summary() so steady-state completions avoid redundant full-registry ComputeCell locks, filter retain_render_completions() to matched render QIDs, move worker_deferred onto Shared, and complete steady-state pure-compute event passes in a single shared.state lock hold while preserving idle_check() timer scheduling. - Use a per-CPU high-priority reclaim-safe workqueue for aurora_g17_events on M5 as on other G17 parts so enqueue_on(submitter) dispatches directly to the submitting CPU. Signed-off-by: Diljit Singh --- .../drm/asahi/g17/initdata/outer_credit.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 22 +- drivers/gpu/drm/asahi/g17/port.rs | 62 ++- drivers/gpu/drm/asahi/g17/queue/compute.rs | 12 + drivers/gpu/drm/asahi/g17/runtime.rs | 244 +++++++--- drivers/gpu/drm/asahi/g17/runtime/events.rs | 433 ++++++++++-------- drivers/gpu/drm/asahi/g17/runtime/render.rs | 5 +- .../drm/asahi/g17/runtime/render/observe.rs | 28 +- tools/asahi/g17-m5-direct-compute-tests.py | 18 +- 9 files changed, 534 insertions(+), 292 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index b8d4fb79ba2607..63695d67ec25b5 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -49,7 +49,7 @@ impl Credits { }, GFP_KERNEL)?) } - pub(super) fn available(&self) -> Arc { self.available.clone() } + pub(crate) fn available(&self) -> Arc { self.available.clone() } pub(super) fn waiting(&self) -> bool { self.available.has_waiters() } diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index c3273235a61df8..6b71e4145ada4c 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1258,12 +1258,13 @@ struct Shared { /// step). Publishers without the device mutex set it too. governor_activity_ns: AtomicU64, /// The queue of all work that signals job fences: the event work, and every scheduler's - /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe. On M5 it is - /// unbound, so the event work runs in the affinity pod (the L2) of the CPU that last - /// published work, not on whichever CPU the completion IRQ thread first ran on; on a two-die - /// part that keeps completion processing on the submitter's die. Elsewhere it is per-CPU and - /// high priority, as `system_highpri_wq`. + /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe and per-CPU + /// high priority, as `system_highpri_wq`. On M5, `enqueue_on(submitter)` places completion + /// processing directly on the submitting CPU (keeping it in the submitter's L2 and die). events: Arc, + /// Preallocated completion collector owned exclusively by `run_runtime_events`. + #[pin] + worker_deferred: Mutex>, /// M5: the event work and the scheduler workers follow the submitting CPU. follows_submitter: bool, /// M5: the CPU of the last publication, `u32::MAX` before the first. @@ -1747,17 +1748,14 @@ impl Gpu { // The bare-metal M5 boot runs both engines; other M5 profiles take no submission. let submits = !m5 || cfg.profile == FirmwareProfile::M5PublishedRoots; let events = Arc::new( - if m5 { - workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true)? - } else { - workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)? - }, + workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)?, GFP_KERNEL, )?; let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; let max_pstate = frequencies .as_ref() .map_or(0, stats::StateFrequencies::max_pstate); + let worker_deferred = runtime::DeferredBatch::worker()?; let shared = Arc::pin_init( pin_init!(Shared { drm <- new_mutex!(Some(dev.into()), "g17::Shared::drm"), @@ -1799,6 +1797,10 @@ impl Gpu { governor_armed: AtomicBool::new(false), governor_activity_ns: AtomicU64::new(0), events, + worker_deferred <- new_mutex!( + Some(worker_deferred), + "g17::Shared::worker_deferred" + ), follows_submitter: m5, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index e389402aa0875b..d7aeda169d7ba6 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -347,9 +347,22 @@ impl Port { *self.m5_outer.lock() = None; } - /// Reserves one slot on M5's shared outer ring for a direct compute publisher without - /// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full. - pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result { + /// M5: the availability domain outer-ring claims wait on. None off M5 or before attach. + pub(super) fn outer_domain(&self) -> Option> { + self.views() + .ok()? + .m5_credits + .as_ref() + .map(|credits| credits.available()) + } + + /// Reserves `count` slots on M5's shared outer ring without taking the device mutex. + /// Returns EBUSY if a device-mutex OuterScope is active or fewer than `count` slots are free. + pub(super) fn reserve_m5_outer( + &self, + priority: u8, + count: u32, + ) -> Result { let views = self.views()?; let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; let (_, ring) = self.ring(priority)?; @@ -358,13 +371,20 @@ impl Port { return Err(EBUSY); } let cursors = ring.cursors()?; - credits.reserve(priority, 1, cursors) + credits.reserve(priority, count, cursors) } - /// Publishes one compute slot on M5's shared outer ring under the port's M5 outer lock - /// and consumes the caller's direct reservation. - pub(super) fn publish_m5_compute( + /// Reserves one slot on M5's shared outer ring for a direct compute publisher without + /// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full. + pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result { + self.reserve_m5_outer(priority, 1) + } + + /// Publishes one compute slot on M5's shared outer ring while the caller holds `m5_outer`, + /// consuming the caller's direct reservation. + pub(super) fn publish_m5_compute_locked( &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, priority: u8, claim: &mut super::initdata::OuterClaim, record: &WorkSlot, @@ -375,7 +395,6 @@ impl Port { let views = self.views()?; let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; let (_, ring) = self.ring(priority)?; - let _guard = self.m5_outer.lock(); let [first, second, producer] = ring.cursors()?; let next = (producer + 1) % WORK_RING_SLOTS; if next == first || next == second { @@ -400,14 +419,13 @@ impl Port { Ok(next) } - /// Issues an M5 host-port compute submission with gating held off, serialized by `m5_outer`. - pub(super) fn submit_m5_work_held( + /// Issues an M5 host-port compute submission with gating held off while `m5_outer` is held. + pub(super) fn submit_m5_work_held_locked( &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, submission: &super::fw::m5::queue::HardwareSubmission, ) -> Result { - let regs = self.regs.as_ref().ok_or(ENODEV)?; - let _guard = self.m5_outer.lock(); - regs.submit_m5_work_held(submission) + self.regs.as_ref().ok_or(ENODEV)?.submit_m5_work_held(submission) } /// Counts `submissions` in the M5 submission-history table without taking the device mutex. @@ -935,17 +953,23 @@ impl Port { } pub(super) fn note_gpu_activity(&self) { - // Observe gating before activity can wake the cores. A lockless + let now_ns = super::now_ns(); + // Firmware gates the cores only after its idle-off delay, so back-to-back submissions + // within that window cannot follow a core gating; skip the uncached power register read. + let idle_off_ns = u64::from(super::power::FIRMWARE_IDLE_OFF_MS) * 1_000_000; + let previous = self.last_submission_ns.load(Ordering::Relaxed); + let recent = previous != 0 && now_ns.saturating_sub(previous) < idle_off_ns; + // Otherwise observe gating before activity can wake the cores. A lockless // publisher cannot clear the decoder under the device mutex; this // epoch makes both the next drain and the next reader discard it. - if self - .regs - .as_ref() - .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) + if !recent + && self + .regs + .as_ref() + .is_some_and(|regs| regs.g17_core_power() & 0xf == 0) { self.statistics_epoch.fetch_add(1, Ordering::Release); } - let now_ns = super::now_ns(); self.last_submission_ns.store(now_ns, Ordering::Relaxed); self.demand.set_active(true); self.report_busy(now_ns); diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 5492a740759e56..e7e1b43eb6b2ac 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -1039,6 +1039,18 @@ impl Queue { || self.retire_pending || masks.is_none_or(|m| m[self.qid() as usize / 64] & (1 << (self.qid() % 64)) != 0) } + + pub(crate) fn needs_scan_retire(&self, masks: Option<[u64; 2]>) -> bool { + self.configuration.is_some() || (!self.quarantined && self.selected(masks)) + } + + pub(crate) fn has_terminal(&self) -> bool { + self.terminal.is_some() + } + + pub(crate) fn awaiting_witness(&self) -> bool { + self.awaiting_witness + } /// Stage every unlatched exact identity before the device's single shared-ring scan, /// whichever queues the scan's batch retires. pub(crate) fn request_observations(&self, batch: &mut Batch) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 61e49e70443ad4..eb82fc9ffe47aa 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -182,7 +182,6 @@ pub(super) struct Registry { completion_cursor: usize, /// Control word of each completion-ring slot as of the last scan that read it. completion_seen: KVVec, - worker_deferred: Option, teardown: super::teardown::Pending, } @@ -240,7 +239,6 @@ impl Registry { } seen }, - worker_deferred: Some(DeferredBatch::worker()?), teardown: super::teardown::Pending::new()?, }) } @@ -1383,7 +1381,7 @@ impl DeferredBatch { }; /// Reused by the sole event work item; no allocation on a completion pass. - fn worker() -> Result { + pub(super) fn worker() -> Result { Self::with_capacity(2 * QIDS * Self::DEPTH, QIDS) } /// One publication can quarantine only its selected physical queue/pair. @@ -1618,6 +1616,7 @@ struct DirectHost<'a> { port: &'a super::port::Port, outer: Option>, m5_outer: Option<&'a mut super::initdata::OuterClaim>, + m5_outer_guard: Option>>, m5: bool, generation: u64, } @@ -1652,15 +1651,27 @@ impl compute::Host for DirectHost<'_> { fn publish_outer(&mut self, priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { if self.m5 { let claim = self.m5_outer.as_deref_mut().ok_or(EIO)?; - return self.port.publish_m5_compute(priority, claim, slot).map(|_| ()); + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + return self + .port + .publish_m5_compute_locked(guard, priority, claim, slot) + .map(|_| ()); } self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } fn notify(&mut self, message: u64) -> Result { if self.m5 && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { - if let Err(error) = self.port.note_m5_submission_history(1) { + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + if let Err(error) = self.port.note_m5_submission_history_locked(guard, 1) { pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer_guard = None; } self.port.notify(message) } @@ -1671,7 +1682,10 @@ impl compute::Host for DirectHost<'_> { if !self.m5 { return Err(EINVAL); } - self.port.submit_m5_work_held(submission) + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + self.port.submit_m5_work_held_locked(guard, submission) } } @@ -1903,25 +1917,66 @@ impl Registry { } } +/// Post-scan compute state collected while `scan_compute_summary` already holds each cell lock, +/// allowing the event worker to avoid redundant full-registry cell scans. +#[derive(Clone, Copy, Default)] +pub(super) struct ComputeScan { + pub(super) in_flight: bool, + pub(super) replay: bool, + pub(super) polling: bool, +} + impl super::Firmware { + fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + self.scan_compute_summary(masks, deferred).map(|_| ()) + } + /// Latch one shared snapshot for all selected queues before settling any VM. /// A later queue's exact success in this batch wins over a peer's failure. - fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + fn scan_compute_summary( + &mut self, + masks: Option<[u64; 2]>, + deferred: &mut DeferredBatch, + ) -> Result { let state = super::recovery::Memory::recovery_state(&self.init)?; let generation = self.recovery.generation(); let registry = &mut self.queues; registry.observations.clear(); let mut requested = false; + let mut retire_mask = 0u128; + let mut terminal_mask = 0u128; + let mut witness_mask = 0u128; + let mut in_flight_mask = 0u128; + let mut replay_mask = 0u128; + let mut polling_mask = 0u128; // Every queue's pending identities are staged, not only the ones this batch // retires: the scan passes each new record once, and a queue retired by a later // batch finds its observation already latched. - for queue in registry - .compute - .iter() - .flatten() - .filter_map(|entry| entry.queue.as_deref()) - { - requested |= queue.request_observations(&mut registry.observations)?; + for (index, entry) in registry.compute.iter().enumerate() { + let Some(queue) = entry.as_ref().and_then(|entry| entry.queue.as_deref()) else { + continue; + }; + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + let slot_requested = queue.request_observations(&mut registry.observations)?; + requested |= slot_requested; + if slot_requested || queue.needs_scan_retire(masks) { + retire_mask |= bit; + } + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } } // Completion records are appended in order: fold only the records written since // the previous scan. A request whose stamp already covers it has its record in the @@ -1943,14 +1998,21 @@ impl super::Firmware { let port = &self.port; let retired = deferred.pending(); let mut freed = false; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { + let mut pending = retire_mask; + while pending != 0 { + let index = pending.trailing_zeros() as usize; + let bit = 1u128 << index; + pending &= !bit; + let Some(mut queue) = registry.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; let busy = !queue.channel_free(); - queue.latch_observations(&mut registry.observations)?; + if requested { + queue.latch_observations(&mut registry.observations)?; + } queue.retire( masks, generation, @@ -1959,35 +2021,79 @@ impl super::Firmware { &mut |event| deferred.push(event), )?; freed |= busy && queue.channel_free(); + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } } // All compute observations in this batch are latched before a VM // failure can settle its render peers. Exact successes win first. - for index in 0..self.queues.compute.len() { - let terminal = self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .and_then(|mut queue| queue.take_terminal()); - if let Some((status, error)) = terminal { - status.record(error); - self.settle_render_vm(&status, error, deferred)?; - self.queues.fail_compute_vm(&status, error, deferred)?; + let had_terminal = terminal_mask != 0; + if had_terminal { + for index in 0..self.queues.compute.len() { + let terminal = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .and_then(|mut queue| queue.take_terminal()); + if let Some((status, error)) = terminal { + status.record(error); + self.settle_render_vm(&status, error, deferred)?; + self.queues.fail_compute_vm(&status, error, deferred)?; + } } } - let port = &self.port; - let registry = &mut self.queues; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { - let busy = !queue.channel_free(); - queue.release_witnessed( - state, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - freed |= busy && queue.channel_free(); + if witness_mask != 0 || had_terminal { + let port = &self.port; + let registry = &mut self.queues; + for (index, entry) in registry.compute.iter_mut().enumerate() { + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + if !had_terminal && (witness_mask & bit) == 0 { + continue; + } + let Some(mut queue) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; + let busy = !queue.channel_free(); + queue.release_witnessed( + state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + freed |= busy && queue.channel_free(); + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } + } } // Wake only the admission waits this batch can end. The fences gate // scheduler entities alone; their callbacks never take the device mutex. @@ -1998,7 +2104,11 @@ impl super::Firmware { if deferred.pending() != retired { shared.progress.notify(); } - Ok(()) + Ok(ComputeScan { + in_flight: in_flight_mask != 0, + replay: replay_mask != 0, + polling: polling_mask != 0, + }) } } @@ -2111,6 +2221,7 @@ impl Backend { port, outer, m5_outer: m5_outer.as_mut(), + m5_outer_guard: None, m5, generation: port.generation(), }; @@ -2162,7 +2273,34 @@ impl Backend { /// M5: the domain outer-ring claims wait on. None off M5 or without firmware. fn outer_domain(&self) -> Option> { - self.shared.state.lock().as_deref().and_then(|firmware| firmware.init.outer_available().ok()) + if !self.context.is_m5() { + return None; + } + let lease = self.shared.preparations.try_enter().ok()?; + self.shared.port(&lease)?.outer_domain() + } + + /// M5: holds this owner's compute outer-ring claim through `Port` without taking the device + /// mutex, for a channel already bound and installed. + fn claim_compute_outer_direct(&self, count: u32) -> Result { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { + return Ok(true); + } + let Ok(lease) = self.shared.preparations.try_enter() else { + return Ok(true); + }; + let Some(port) = self.shared.port(&lease) else { + return Ok(true); + }; + match port.reserve_m5_outer(self.context.policy().priority(), count) { + Ok(claim) => { + *held = Some(claim); + Ok(true) + } + Err(error) if error == EBUSY => Ok(false), + Err(error) => Err(error), + } } /// M5: holds this owner's claim on the shared work ring for the next compute or render @@ -2233,24 +2371,24 @@ impl Backend { // The steady state: this owner's channel is bound and installed. if packet.completion.sources().is_none() { if let Some(cell) = self.direct.lock().clone() { - let bound = cell.lock().is_some_and(|mut queue| { + let bound = cell.lock().and_then(|mut queue| { let bound = queue.installed() && !queue.spared_pending() && queue.pool_fits(required) && matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)); if bound { queue.claim(); + Some(queue.outer_slots()) + } else { + None } - bound }); - if bound { + if let Some(outer_slots) = bound { self.hold_claim(Some(cell)); if !self.context.is_m5() { return Readiness::Ready; } - let state = self.shared.state.lock(); - let Some(firmware) = state.as_deref() else { return Readiness::Ready; }; - return match self.claim_outer(firmware, crate::g17::job::Engine::Compute) { + return match self.claim_compute_outer_direct(outer_slots) { Ok(false) => Readiness::Outer, _ => Readiness::Ready, }; diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index c2be38fa0af383..1016e6d6739e82 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -23,6 +23,7 @@ struct Service<'a> { firmware: &'a mut Firmware, deferred: &'a mut DeferredBatch, render_masks: [u64; 2], + compute_scan: Option, settlement_error: Option, } @@ -117,15 +118,16 @@ impl event::Queues for Service<'_> { fn retain_render_completions(&mut self, masks: [u64; 2]) { // Inline timeout and drain callers may discard the worker hints. The // queue owner retains stamps until its borrowed pair returns to scan. - self.firmware.queues.retain_render_completions(masks); - self.render_masks[0] |= masks[0]; - self.render_masks[1] |= masks[1]; + let matched = self.firmware.queues.retain_render_completions(masks); + self.render_masks[0] |= matched[0]; + self.render_masks[1] |= matched[1]; } fn complete_compute(&mut self, masks: [u64; 2]) -> Result { // A batch without a queue identity still observes completions whose // notification was coalesced; identified batches retain QID filtering. let selected = (masks != [0; 2]).then_some(masks); - self.firmware.scan_compute(selected, self.deferred) + self.compute_scan = Some(self.firmware.scan_compute_summary(selected, self.deferred)?); + Ok(()) } } @@ -362,8 +364,8 @@ impl Firmware { } } - /// A step of the event pass is waiting on the firmware with no event to wake it. - fn runtime_polling(&self, now: u64) -> bool { + /// Non-compute checks of [`Self::runtime_polling`], reused on the single-lock fast path. + fn non_compute_runtime_polling(&self, now: u64) -> bool { self.render_control_backpressured() || self.init.outer_waiting() || self.queues.replay_outer_wait.is_some() @@ -371,6 +373,11 @@ impl Firmware { || self.queues.render.replay_polling() || self.queues.teardown.polling(now) || self.compute_exit_polling(now) + } + + /// A step of the event pass is waiting on the firmware with no event to wake it. + fn runtime_polling(&self, now: u64) -> bool { + self.non_compute_runtime_polling(now) || self .queues .compute @@ -420,10 +427,19 @@ impl Firmware { &mut self, deferred: &mut DeferredBatch, ) -> Result<(event::Pending, [u64; 2])> { + let (pending, masks, _) = self.service_runtime_events_scan(deferred)?; + Ok((pending, masks)) + } + + fn service_runtime_events_scan( + &mut self, + deferred: &mut DeferredBatch, + ) -> Result<(event::Pending, [u64; 2], Option)> { let mut service = Service { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let pending = event::service(&mut service)?; @@ -435,7 +451,7 @@ impl Firmware { shared.preparations.close(); shared.queue_events(); } - Ok((pending, service.render_masks)) + Ok((pending, service.render_masks, service.compute_scan)) } /// Preparation admission is already closed and all builders have joined. @@ -446,6 +462,7 @@ impl Firmware { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let result = recovery::service(&mut service, || { @@ -508,10 +525,16 @@ impl crate::g17::Shared { self.stop_runtime(); return; } + let Some(mut deferred) = self.worker_deferred.lock().take() else { + self.lose_device_quietly(); + return; + }; crate::g17::trace::event(0); - let result = self.runtime_event_turn(); + let result = self.runtime_event_turn(&mut deferred); + deferred.finish(); crate::g17::trace::event(2); self.queue_feed(); + *self.worker_deferred.lock() = Some(deferred); if let Err(error) = result { dev_err!(self.dev.as_ref(), "GPU event service failed: {:?}\n", error); self.lose_device_quietly(); @@ -519,221 +542,235 @@ impl crate::g17::Shared { } } - fn runtime_event_turn(self: &Arc) -> Result { + fn runtime_event_turn(self: &Arc, deferred: &mut DeferredBatch) -> Result { // Taken before consuming records: a request made during this pass gets the next one. let requested = self .housekeeping .swap(false, core::sync::atomic::Ordering::AcqRel); - let (deferred, recover, masks) = { + let (recover, masks, fast_done) = { let mut state = self.state.lock(); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - let Some(mut deferred) = firmware.queues.worker_deferred.take() else { - drop(state); - self.lose_device_quietly(); - return Ok(()); - }; - let (pending, masks) = match firmware.service_runtime_events(&mut deferred) { - Ok(out) => out, - Err(error) => { - drop(state); - deferred.finish(); - if let Some(firmware) = (*self.state.lock()).as_deref_mut() { - firmware.queues.worker_deferred = Some(deferred); - } - return Err(error); - } - }; + let (pending, masks, compute_scan) = firmware.service_runtime_events_scan(deferred)?; let recover = pending.recovery || firmware.recovery.pending(); if recover { // Epoch closure and event consumption are serialized with every // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - (deferred, recover, masks) - }; - let mut deferred = Some(deferred); - if let Some(batch) = deferred.as_mut() { - batch.finish(); - } - crate::g17::trace::event(1); - let result = (|| -> Result { - let batch = deferred.as_mut().ok_or(EIO)?; - if recover { - self.preparations - .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; - } - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); - }; - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); - } - // Capture pre-recovery trace/statistics reports before firmware restart resets the - // report rings, matching the non-throttled post-signal ordering. - let mut reports_drained = false; - if recover { - firmware.drain_post_signal_reports(); - reports_drained = true; - firmware.service_runtime_recovery(batch)?; - if !firmware.recovery.pending() - && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) - { - if !self.preparations.reopen() { - return Ok(()); + // Steady-state pure-compute completions with work still in flight, no render work + // to observe, no replays, no waiters and housekeeping not yet due finish in this + // single device-mutex hold; fences are signalled right after unlocking. + let mut fast_done = false; + if !recover + && !requested + && !self.crashed.load(core::sync::atomic::Ordering::Acquire) + && masks == [0; 2] + && !firmware.render_observation_needed() + { + if let Some(scan) = compute_scan { + let now = super::now_ns(); + let in_flight = scan.in_flight || firmware.queues.render_in_flight(); + let no_replay = !scan.replay && !firmware.queues.render.replay_parked(); + let no_housekeeping = in_flight + && firmware.queues.teardown.is_empty() + && !self.channels.has_waiters() + && !self.progress.has_waiters() + && !self.queues.has_waiters() + && !self.renders.has_waiters() + && now.saturating_sub( + self.housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed), + ) < HOUSEKEEPING_NS; + let no_outer_or_grow = + !firmware.init.outer_waiting() && !firmware.render_grow_ready(); + if no_replay && no_housekeeping && no_outer_or_grow { + if let Some(delay) = firmware.idle_check(now, true)? { + self.queue_idle(delay); + } + let polling = scan.polling || firmware.non_compute_runtime_polling(now); + if polling { + self.queue_poll(); + } else if channel::Events::pending(&firmware.init, Role::Primary)? + || (firmware.secondary.is_some() + && channel::Events::pending(&firmware.init, Role::Secondary)?) + { + self.queue_event_records(); + } + fast_done = true; } - // Restart stopped consumption before its following record. - // Resume builders before observing pairs outside this lock. - self.queue_events(); - } - } - // Replay only at this outer boundary, after recovery has settled. - // Publication may service events but must never recurse into replay. - firmware.replay_compute(batch)?; - firmware.replay_render(batch)?; - // Pure compute completions have empty render masks: keep the same device-mutex - // hold instead of dropping and immediately re-acquiring around a no-op observe. - if masks != [0; 2] { - drop(state); - self.observe_renders(masks, batch)?; - state = self.state.lock(); - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); } } - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); - }; - let now = super::now_ns(); - let compute = firmware - .queues - .compute - .iter() - .flatten() - .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.in_flight()); - let in_flight = compute || firmware.queues.render_in_flight(); - let idle = firmware.idle_check(now, in_flight)?; - // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report - // drains give back what retirement freed; a completion needs none of them to retire - // or to signal. While work is in flight and nothing waits for capacity, a pass for - // firmware records alone skips them. Any requested pass, recovery, teardown, a waiter, - // the last retirement and, at the latest, the first pass after HOUSEKEEPING_NS run - // them all. - let housekeeping = requested - || recover - || !in_flight - || firmware.recovery.pending() - || !firmware.queues.teardown.is_empty() - || self.channels.has_waiters() - || self.progress.has_waiters() - || self.queues.has_waiters() - || self.renders.has_waiters() - || now.saturating_sub( - self.housekeeping_ns - .load(core::sync::atomic::Ordering::Relaxed), - ) >= HOUSEKEEPING_NS; - let mut lingers = None; - let mut drains = None; - let mut kills = None; - let mut pools = None; - let mut shrinking = false; - if housekeeping { - self.housekeeping_ns - .store(now, core::sync::atomic::Ordering::Relaxed); - if !reports_drained { - // The completions above are signalled; reports are throttled to the - // housekeeping cadence while work stays in flight. - firmware.drain_post_signal_reports(); - } - if !firmware.recovery.pending() { - lingers = firmware.expire_render_lingers(now)?; - } - drains = firmware.reclaim_drained_renders(batch)?; - firmware.service_compute_exit(batch)?; - kills = firmware.kill_retry_delay(); - pools = firmware.service_compute_pools(batch, now)?; - if !firmware.recovery.pending() { - firmware - .queues - .vacate_evicted_render_pools(&firmware.init, batch)?; - shrinking = firmware - .queues - .shrink_render_heaps(&firmware.init, now, batch); - } - let mut reclaim = self.reclaim.lock(); - firmware.service_teardown(&mut reclaim)?; - if !reclaim.is_empty() { - self.queue_reclaims(); + (recover, masks, fast_done) + }; + deferred.finish(); + crate::g17::trace::event(1); + if fast_done { + return Ok(()); + } + if recover { + self.preparations + .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; + } + let mut state = self.state.lock(); + let Some(firmware) = (*state).as_deref_mut() else { + return Ok(()); + }; + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); + } + // Capture pre-recovery trace/statistics reports before firmware restart resets the + // report rings, matching the non-throttled post-signal ordering. + let mut reports_drained = false; + if recover { + firmware.drain_post_signal_reports(); + reports_drained = true; + firmware.service_runtime_recovery(deferred)?; + if !firmware.recovery.pending() + && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) + { + if !self.preparations.reopen() { + return Ok(()); } - } - // The firmware may consume M5 work-ring slots without a completion interrupt: while - // a preparation waits for unclaimed room, every pass polls the consumers. - let outer = firmware.init.poll_outer_progress()?; - let polling = firmware.runtime_polling(now); - if polling { - self.queue_poll(); - } - // A heap with growth to give back is re-evaluated at least once per - // shrink period, also while the device is otherwise idle. - let idle = if shrinking { - Some(idle.map_or(SHRINK_WAKE_NS, |delay| delay.min(SHRINK_WAKE_NS))) - } else { - idle - }; - // A retained compute pool gives its backing back when it expires, and - // so does an idle render free-list registration. A drained render pair - // whose settlement failed is retried when its backoff ends, and a closed - // context's kill that waited for other work is looked at again. - let idle = [pools, lingers, drains, kills] - .into_iter() - .fold(idle, |idle, expiry| match (idle, expiry) { - (Some(delay), Some(expiry)) => Some(delay.min(expiry)), - (delay, expiry) => delay.or(expiry), - }); - if let Some(delay) = idle { - self.queue_idle(delay); - } - if firmware.recovery.pending() { - self.preparations.close(); + // Restart stopped consumption before its following record. + // Resume builders before observing pairs outside this lock. self.queue_events(); - } else if !recover - && !polling - && (channel::Events::pending(&firmware.init, Role::Primary)? - || (firmware.secondary.is_some() - && channel::Events::pending(&firmware.init, Role::Secondary)?)) - { - // A full bounded pass must not depend on a fresh notification for - // records that arrived while it was consuming the same ring. - self.queue_event_records(); - } - let grow_ready = firmware.render_grow_ready(); - if batch.pending() == 0 { - firmware.queues.worker_deferred = deferred.take(); } + } + // Replay only at this outer boundary, after recovery has settled. + // Publication may service events but must never recurse into replay. + firmware.replay_compute(deferred)?; + firmware.replay_render(deferred)?; + // Skip dropping and re-acquiring the device mutex around a no-op render observation. + if masks != [0; 2] || firmware.render_observation_needed() { drop(state); - if grow_ready { - self.queue_grow(); + self.observe_renders(masks, deferred)?; + state = self.state.lock(); + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); } - // Outside the device mutex: the notification can run DMA-fence callbacks. - if let Some(domain) = outer { - domain.notify(); + } + let Some(firmware) = (*state).as_deref_mut() else { + return Ok(()); + }; + let now = super::now_ns(); + let compute = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.in_flight()); + let in_flight = compute || firmware.queues.render_in_flight(); + let idle = firmware.idle_check(now, in_flight)?; + // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report + // drains give back what retirement freed; a completion needs none of them to retire + // or to signal. While work is in flight and nothing waits for capacity, a pass for + // firmware records alone skips them. Any requested pass, recovery, teardown, a waiter, + // the last retirement and, at the latest, the first pass after HOUSEKEEPING_NS run + // them all. + let housekeeping = requested + || recover + || !in_flight + || firmware.recovery.pending() + || !firmware.queues.teardown.is_empty() + || self.channels.has_waiters() + || self.progress.has_waiters() + || self.queues.has_waiters() + || self.renders.has_waiters() + || now.saturating_sub( + self.housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed), + ) >= HOUSEKEEPING_NS; + let mut lingers = None; + let mut drains = None; + let mut kills = None; + let mut pools = None; + let mut shrinking = false; + if housekeeping { + self.housekeeping_ns + .store(now, core::sync::atomic::Ordering::Relaxed); + if !reports_drained { + // The completions above are signalled; reports are throttled to the + // housekeeping cadence while work stays in flight. + firmware.drain_post_signal_reports(); } - // Firmware ring room, consumed releases and teardown steps have no - // event of their own: recheck render publishers' conditions every pass. - if self.renders.has_waiters() { - self.renders.notify(); + if !firmware.recovery.pending() { + lingers = firmware.expire_render_lingers(now)?; } - Ok(()) - })(); - if let Some(mut batch) = deferred.take() { - batch.finish(); - if let Some(firmware) = (*self.state.lock()).as_deref_mut() { - firmware.queues.worker_deferred = Some(batch); + drains = firmware.reclaim_drained_renders(deferred)?; + firmware.service_compute_exit(deferred)?; + kills = firmware.kill_retry_delay(); + pools = firmware.service_compute_pools(deferred, now)?; + if !firmware.recovery.pending() { + firmware + .queues + .vacate_evicted_render_pools(&firmware.init, deferred)?; + shrinking = firmware + .queues + .shrink_render_heaps(&firmware.init, now, deferred); } + let mut reclaim = self.reclaim.lock(); + firmware.service_teardown(&mut reclaim)?; + if !reclaim.is_empty() { + self.queue_reclaims(); + } + } + // The firmware may consume M5 work-ring slots without a completion interrupt: while + // a preparation waits for unclaimed room, every pass polls the consumers. + let outer = firmware.init.poll_outer_progress()?; + let polling = firmware.runtime_polling(now); + if polling { + self.queue_poll(); + } + // A heap with growth to give back is re-evaluated at least once per + // shrink period, also while the device is otherwise idle. + let idle = if shrinking { + Some(idle.map_or(SHRINK_WAKE_NS, |delay| delay.min(SHRINK_WAKE_NS))) + } else { + idle + }; + // A retained compute pool gives its backing back when it expires, and + // so does an idle render free-list registration. A drained render pair + // whose settlement failed is retried when its backoff ends, and a closed + // context's kill that waited for other work is looked at again. + let idle = [pools, lingers, drains, kills] + .into_iter() + .fold(idle, |idle, expiry| match (idle, expiry) { + (Some(delay), Some(expiry)) => Some(delay.min(expiry)), + (delay, expiry) => delay.or(expiry), + }); + if let Some(delay) = idle { + self.queue_idle(delay); + } + if firmware.recovery.pending() { + self.preparations.close(); + self.queue_events(); + } else if !recover + && !polling + && (channel::Events::pending(&firmware.init, Role::Primary)? + || (firmware.secondary.is_some() + && channel::Events::pending(&firmware.init, Role::Secondary)?)) + { + // A full bounded pass must not depend on a fresh notification for + // records that arrived while it was consuming the same ring. + self.queue_event_records(); + } + let grow_ready = firmware.render_grow_ready(); + drop(state); + if grow_ready { + self.queue_grow(); + } + // Outside the device mutex: the notification can run DMA-fence callbacks. + if let Some(domain) = outer { + domain.notify(); } - result + // Firmware ring room, consumed releases and teardown steps have no + // event of their own: recheck render publishers' conditions every pass. + if self.renders.has_waiters() { + self.renders.notify(); + } + Ok(()) } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index a3b79e1f507729..1e81756ae2ce46 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1275,13 +1275,15 @@ impl Registry { ) }) } - pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) { + pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) -> [u64; 2] { + let mut matched = [0u64; 2]; for entry in self.render.entries.iter_mut().flatten() { let mut hit = false; for id in entry.reservation.ids { let qid = usize::from(id.qid()); let bit = masks[qid / 64] & (1u64 << (qid % 64)); entry.event_masks[qid / 64] |= bit; + matched[qid / 64] |= bit; hit |= bit != 0; } // Event passes skip a pair while preparation, growth or an @@ -1292,6 +1294,7 @@ impl Registry { entry.missed_event = true; } } + matched } pub(in crate::g17) fn render_needs_rescan(&self) -> bool { self.render.entries.iter().flatten().any(|entry| { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs index 57543be54e8356..63bae4052b14e1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs @@ -8,6 +8,32 @@ use core::sync::atomic::Ordering; use kernel::{prelude::*, sync::Arc}; impl crate::g17::Firmware { + /// Whether `observe_renders` has any deferred settlement or in-flight render observation + /// pending. Pure compute passes can skip dropping and re-acquiring the device mutex when false. + pub(in crate::g17) fn render_observation_needed(&self) -> bool { + for slot in 1..self.queues.render.entries.len() { + let Some(entry) = self.queues.render.entries[slot].as_ref() else { + continue; + }; + let Some(pair) = entry.pair.as_ref() else { + continue; + }; + if entry.pending_error.is_some() || entry.pending_timeout || entry.closed { + return true; + } + if !self.recovery.pending() + && entry.preparing.is_none() + && !entry.growing + && pair.published_in_flight() + && (crate::g17::queue::render::completion_noted(pair.qids(), entry.event_masks) + || pair.stamp_waiting()) + { + return true; + } + } + false + } + /// The first slot from `start` whose pair has news to observe: published work in flight, the /// fragment queue's notification seen (`completion_noted`), and an observation the pair accepts. fn next_render_observation(&mut self, start: usize) -> Result> { @@ -83,7 +109,7 @@ impl crate::g17::Shared { let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - firmware.queues.retain_render_completions(masks); + let _ = firmware.queues.retain_render_completions(masks); // Returned preparers can have deferred a VM failure or timeout. // Only this full worker collector runs their final observations. for slot in 1..firmware.queues.render.entries.len() { diff --git a/tools/asahi/g17-m5-direct-compute-tests.py b/tools/asahi/g17-m5-direct-compute-tests.py index 68bd7eff4f1861..d49cbe95cab7b8 100755 --- a/tools/asahi/g17-m5-direct-compute-tests.py +++ b/tools/asahi/g17-m5-direct-compute-tests.py @@ -58,19 +58,19 @@ def build_harness(mutation=None): turn = item(events_src, 'fn runtime_event_turn(') if mutation == 'no-pre-recovery-drain': turn = turn.replace( - 'firmware.drain_post_signal_reports();\n reports_drained = true;\n' - ' firmware.service_runtime_recovery(batch)?;', - 'firmware.service_runtime_recovery(batch)?;', + 'firmware.drain_post_signal_reports();\n reports_drained = true;\n' + ' firmware.service_runtime_recovery(deferred)?;', + 'firmware.service_runtime_recovery(deferred)?;', 1, ) # Verify report-drain ordering contract in production runtime_event_turn(). ordering_ok = ordered_ok( turn, - 'if let Some(batch) = deferred.as_mut() {\n batch.finish();\n }', + 'deferred.finish();', 'let mut reports_drained = false;', - 'firmware.drain_post_signal_reports();\n reports_drained = true;', - 'firmware.service_runtime_recovery(batch)?;', + 'firmware.drain_post_signal_reports();\n reports_drained = true;', + 'firmware.service_runtime_recovery(deferred)?;', 'if housekeeping {', 'if !reports_drained {', ) @@ -89,9 +89,9 @@ def build_harness(mutation=None): if mutation == 'direct-debits-published': prod = prod.replace( - 'self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel);', - 'self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel);\n' - ' self.published[claim.priority].fetch_add(1, Ordering::AcqRel);', + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);', + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);\n' + ' self.published[claim.priority].fetch_add(u64::from(count), Ordering::AcqRel);', 1, ) elif mutation == 'scope-allows-reserve': From d13f2358d7420ee321cc08a6312a26903e0acf3c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 05:26:35 -0500 Subject: [PATCH 1053/1514] drm/asahi: g17: reduce M5 multi-queue cluster pinning and outer-lock trips Two sources of unnecessary host contention on single-die M5 multi-queue workloads, plus M5 outer-credit locking fixes exposed by concurrent direct compute and device-mutex publishers: 1. creator_cluster_scheduling() restricted every drm_sched ordered submit workqueue on M5 to Cpumask::cluster_of(CpuId::current()) at queue creation time. That pinning prevents cross-die migration on multi-die M5 Ultra (num_dies > 1), but on single-die M5 parts (num_dies == 1) queues created on one main thread all get pinned to a single CPU cluster and contend when submitted from worker threads across clusters. Keep event-work submitter tracking on all M5 parts and restrict scheduler clusters only when num_dies > 1. 2. compute_direct() previously ignored the M5 OuterClaim already reserved in self.outer_compute during prepare_compute() and called port.reserve_m5_compute(), causing a redundant Port::m5_outer lock round-trip, double-booked outer-ring slots, and an unused-claim availability wakeup on every direct compute submission. Reuse the held self.outer_compute claim when its remaining count and priority match before falling back to port.reserve_m5_compute(), and restore any unspent held claim back into self.outer_compute outside cell.lock() when compute_direct() falls back to the device-mutex path so pre-reserved credits are preserved without spurious wakeups. 3. Serialize device-mutex OuterClaim reservations (Backend::claim_outer) and OuterScope entry/Drop transitions (Port::outer_scope / PortOuterScope) under Port::m5_outer so Credits::reserved[] and Credits::scoped never race against concurrent direct M5 reservations (Port::reserve_m5_outer / Port::reserve_m5_render_locked). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/initdata.rs | 8 +- .../drm/asahi/g17/initdata/outer_credit.rs | 8 +- drivers/gpu/drm/asahi/g17/mod.rs | 14 +- drivers/gpu/drm/asahi/g17/port.rs | 37 +- drivers/gpu/drm/asahi/g17/runtime.rs | 55 ++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 2 +- .../drm/asahi/g17/runtime/render/prepare.rs | 2 +- .../g17-m5-multiqueue-contention-tests.py | 401 ++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 9 files changed, 506 insertions(+), 25 deletions(-) create mode 100755 tools/asahi/g17-m5-multiqueue-contention-tests.py diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index b25d4d7b64e288..38a5be0be47cd7 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -675,15 +675,17 @@ impl InitData { } /// M5 TA, fragment and compute share the compute outer ring per priority. - /// The physical queue claim prevents reassignment while this credit lives. + /// The caller must hold `Port::m5_outer`; the physical queue claim prevents + /// reassignment while this credit lives. pub(crate) fn reserve_outer(&self, priority: u8, count: u32) -> Result { if !self.m5 { return Err(EINVAL); } let cursors = self.work_cursors(priority, super::fw::queue::DataMaster::Compute)?; self.outer_credits.as_ref().ok_or(EIO)?.reserve(priority, count, cursors) } - /// Hold the device mutex for this scope, including its Drop. The result - /// borrows only the claim, allowing the caller to publish through Firmware. + /// Hold the device mutex for this scope, including its Drop, and serialize entry + /// and Drop under `Port::m5_outer` via `Port::outer_scope`. The result borrows + /// only the claim, allowing the caller to publish through Firmware. pub(crate) fn outer_scope<'a>(&self, claim: &'a mut OuterClaim) -> Result> { self.outer_credits.as_ref().ok_or(EINVAL)?.scope(claim) } diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index 63695d67ec25b5..58d0822f53dde1 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -24,7 +24,8 @@ pub(crate) struct OuterClaim { } /// Borrows the claim only. The caller must hold the device mutex from entry -/// through Drop: its temporarily lent credits are available to that publisher. +/// through Drop and serialize entry and Drop under `Port::m5_outer` (via +/// `Port::outer_scope`): its temporarily lent credits are available to that publisher. pub(crate) struct OuterScope<'a> { claim: &'a mut OuterClaim, before: u64, @@ -140,6 +141,11 @@ impl OuterClaim { pub(crate) fn remaining(&self) -> u32 { self.remaining } + + /// Priority class of the reserved outer work ring. + pub(crate) fn priority(&self) -> usize { + self.priority + } } impl Drop for OuterClaim { diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 6b71e4145ada4c..dd0c3c24536867 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1265,8 +1265,12 @@ struct Shared { /// Preallocated completion collector owned exclusively by `run_runtime_events`. #[pin] worker_deferred: Mutex>, - /// M5: the event work and the scheduler workers follow the submitting CPU. + /// M5: the event work follows the submitting CPU. follows_submitter: bool, + /// Multi-die M5: restrict each scheduler's ordered submit queue to the creating CPU's + /// cluster to avoid cross-die migration. Single-die M5 parts leave schedulers unpinned so + /// queues created on one thread do not contend on a single cluster under multi-queue load. + pin_scheduler_cluster: bool, /// M5: the CPU of the last publication, `u32::MAX` before the first. submitter: AtomicU32, #[pin] @@ -1457,9 +1461,10 @@ impl Shared { self.events.clone() } - /// Whether the event work and the scheduler workers follow the submitting CPU (M5). - pub(super) fn follows_submitter(&self) -> bool { - self.follows_submitter + /// Whether each scheduler's submit queue should be restricted to the creating CPU's cluster + /// (multi-die M5 only). + pub(super) fn pin_scheduler_cluster(&self) -> bool { + self.pin_scheduler_cluster } /// Records the publishing CPU for the event work's placement (M5). @@ -1802,6 +1807,7 @@ impl Gpu { "g17::Shared::worker_deferred" ), follows_submitter: m5, + pin_scheduler_cluster: m5 && id.num_dies > 1, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), reclaim_work <- new_work!("g17::Shared::reclaim_work"), diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index d7aeda169d7ba6..cd35a4e320f651 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -7,9 +7,9 @@ //! through a preparation lease ([`super::Shared::port`]): shutdown and device loss join every //! lease before they detach the session. Each piece below is atomic or has its own lock. //! -//! Lock order: device mutex -> compute queue cell -> the locks of this port. Among the port's -//! locks: render publication lock -> M5 outer-ring lock -> admission pool, QoS, mailbox. None -//! of their holders ever takes the device mutex. +//! Lock order: device mutex -> outer_{compute,render} -> compute queue cell -> the locks of +//! this port. Among the port's locks: render publication lock -> M5 outer-ring lock -> +//! admission pool, QoS, mailbox. None of their holders ever takes the device mutex. use super::{ fw::{ @@ -173,6 +173,22 @@ impl M5RenderRoom { } } +/// Serializes entry and Drop of an M5 [`super::initdata::OuterScope`] under `Port::m5_outer` +/// so `Credits::scoped` and `reserved[]` cannot race with direct M5 reservations or publications. +pub(super) struct PortOuterScope<'a> { + scope: Option>, + port: Arc, +} + +impl Drop for PortOuterScope<'_> { + fn drop(&mut self) { + if let Some(scope) = self.scope.take() { + let _m5_outer = self.port.m5_outer_lock(); + drop(scope); + } + } +} + /// A compute work-ring slot reserved before any command becomes visible. Dropping an unused /// claim returns the slot. pub(super) struct OuterClaim<'a> { @@ -342,6 +358,21 @@ impl Port { self.m5_outer.lock() } + /// Enters an M5 `OuterScope` under `m5_outer` and returns a guard that re-acquires + /// `m5_outer` around the inner scope's Drop, preventing races with direct M5 reservations. + pub(super) fn outer_scope<'a>( + self: &Arc, + init: &super::initdata::InitData, + claim: &'a mut super::initdata::OuterClaim, + ) -> Result> { + let _m5_outer = self.m5_outer.lock(); + let scope = init.outer_scope(claim)?; + Ok(PortOuterScope { + scope: Some(scope), + port: self.clone(), + }) + } + /// Clears the cached M5 submission-history geometry after firmware recovery restarts. pub(super) fn reset_m5_history(&self) { *self.m5_outer.lock() = None; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index eb82fc9ffe47aa..2297c1a79429f5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2194,14 +2194,28 @@ impl Backend { } let m5 = self.context.is_m5(); let priority = packet.context.policy().priority(); - // Reserve M5 outer room before locking the compute cell so an unspent claim drops - // outside the cell lock (dropping an unspent claim can notify availability fences). - let mut m5_outer = if m5 { - Some(port.reserve_m5_compute(priority).ok()?) + // Reuse the M5 outer claim already reserved during prepare_compute() when present and + // matching priority, avoiding a redundant Port::m5_outer lock trip and unused-claim drop + // notification; otherwise reserve before locking the compute cell. + let (mut m5_outer, from_held) = if m5 { + let claimed = { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| { + claim.remaining() != 0 && claim.priority() == usize::from(priority) + }) { + held.take() + } else { + None + } + }; + match claimed { + Some(claim) => (Some(claim), true), + None => (Some(port.reserve_m5_compute(priority).ok()?), false), + } } else { - None + (None, false) }; - let result = { + let result = (|| { let mut queue = cell.lock()?; if !queue.installed() || queue.spared_pending() @@ -2225,13 +2239,29 @@ impl Backend { m5, generation: port.generation(), }; - queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event)) + Some(queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event))) + })(); + let outcome = match result { + None => None, + Some(Err(error)) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => { + None + } + Some(result) => Some(result), }; - drop(m5_outer); - match result { - Err(error) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => None, - result => Some(result), + if outcome.is_none() && from_held { + if let Some(claim) = m5_outer.take().filter(|claim| claim.remaining() != 0) { + let mut held = self.outer_compute.lock(); + if !held.as_ref().is_some_and(|existing| existing.remaining() != 0) { + // Replace None or an already-spent claim (whose drop notifies nobody). + *held = Some(claim); + } else { + drop(held); + drop(claim); + } + } } + drop(m5_outer); + outcome } /// Scheduler admission of a compute packet. Shared capacity the packet lacks (a channel, a @@ -2323,6 +2353,7 @@ impl Backend { if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { return Ok(true); } + let _m5_outer = firmware.port.m5_outer_lock(); match firmware.init.reserve_outer(self.context.policy().priority(), count) { Ok(claim) => { // Replaces only a spent claim, whose drop notifies nobody. @@ -2346,7 +2377,7 @@ impl Backend { let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_compute(self.owner, packet.clone(), dependencies, deferred) } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f12626e7039b0d..35ddab8134ff50 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -123,7 +123,7 @@ impl Backend { impl job::Backend for Backend { fn creator_cluster_scheduling(&self) -> bool { - self.shared.follows_submitter() + self.shared.pin_scheduler_cluster() } fn host_producer_waits(&self) -> bool { self.shared.m5_board.is_some_and(|board| !board.g17d_forms() && !board.completion_inputs()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 215ae50e3b22c9..05f83ca69ba2e8 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -993,7 +993,7 @@ impl super::super::Backend { let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_render(self.owner, slot, packet, deferred) })(); diff --git a/tools/asahi/g17-m5-multiqueue-contention-tests.py b/tools/asahi/g17-m5-multiqueue-contention-tests.py new file mode 100755 index 00000000000000..23bf0512d2c3f1 --- /dev/null +++ b/tools/asahi/g17-m5-multiqueue-contention-tests.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 multi-queue cluster pinning and outer-credit locking. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Tight-ring multi-threaded serialization of `claim_outer()` (`reserve` under + `Port::m5_outer`), `PortOuterScope` (entry and `Drop` under `Port::m5_outer`), + and concurrent direct compute/render reservations and consumptions — verifying + zero ring overcommits, zero `EIO`, and exact credit accounting. +2. Structural verification of the production G17 M5 sources: + - `Shared::new()` restricts scheduler cluster pinning to multi-die M5 + (`pin_scheduler_cluster: m5 && id.num_dies > 1`). + - `Backend::claim_outer()` holds `firmware.port.m5_outer_lock()` around + `firmware.init.reserve_outer()`. + - `Backend::publish_claimed()` and `runtime/render/prepare.rs` enter + `OuterScope` via `firmware.port.outer_scope(&firmware.init, claim)`. + - `Port::outer_scope()` and `Drop for PortOuterScope` serialize both scope + entry and exit under `Port::m5_outer`. + - `Backend::compute_direct()` reuses a matching `self.outer_compute` claim and + restores any unspent claim back into `self.outer_compute` outside + `cell.lock()` when returning `None` to fall back to the device-mutex path. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + port_src = (G17 / 'port.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + prepare_src = (G17 / 'runtime/render/prepare.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + claim_outer = item(runtime_src, 'fn claim_outer(') + publish_claimed = item(runtime_src, 'fn publish_claimed(') + compute_direct = item(runtime_src, 'fn compute_direct(') + port_outer_scope = item(port_src, 'pub(super) fn outer_scope<') + port_outer_scope_drop = item(port_src, 'impl Drop for PortOuterScope<') + creator_cluster = item(backend_src, 'fn creator_cluster_scheduling(') + + if mutation == 'unlocked-claim-outer': + claim_outer = claim_outer.replace( + 'let _m5_outer = firmware.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'raw-compute-scope': + publish_claimed = publish_claimed.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'raw-render-scope': + prepare_src = prepare_src.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'unlocked-scope-drop': + port_outer_scope_drop = port_outer_scope_drop.replace( + 'let _m5_outer = self.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'drop-direct-claim-on-fallback': + compute_direct = compute_direct.replace( + 'if outcome.is_none() && from_held {', + 'if false {', + 1, + ) + elif mutation == 'pin-single-die': + mod_src = mod_src.replace( + 'pin_scheduler_cluster: m5 && id.num_dies > 1,', + 'pin_scheduler_cluster: m5,', + 1, + ) + + claim_outer_ok = ordered_ok( + claim_outer, + 'let _m5_outer = firmware.port.m5_outer_lock();', + 'firmware.init.reserve_outer(', + ) + publish_claimed_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in publish_claimed + and 'firmware.init.outer_scope(' not in publish_claimed + ) + render_scope_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in prepare_src + and 'firmware.init.outer_scope(' not in prepare_src + ) + port_scope_ok = ( + ordered_ok( + port_outer_scope, + 'let _m5_outer = self.m5_outer.lock();', + 'init.outer_scope(claim)?', + ) + and ordered_ok( + port_outer_scope_drop, + 'let _m5_outer = self.port.m5_outer_lock();', + 'drop(scope);', + ) + ) + # Verify compute_direct reuses self.outer_compute before cell.lock() and restores any + # unspent held claim back into self.outer_compute AFTER the cell.lock() closure exits. + direct_restore_ok = ( + compute_direct.count('let mut held = self.outer_compute.lock();') == 2 + and ordered_ok( + compute_direct, + 'held.take()', + 'let result = (|| {', + 'let mut queue = cell.lock()?;', + '})();', + 'if outcome.is_none() && from_held {', + '*held = Some(claim);', + ) + and compute_direct.index('let mut held = self.outer_compute.lock();') + < compute_direct.index('let result = (|| {') + and compute_direct.rindex('let mut held = self.outer_compute.lock();') + > compute_direct.index('if outcome.is_none() && from_held {') + ) + cluster_pin_ok = ( + 'pin_scheduler_cluster: m5 && id.num_dies > 1,' in mod_src + and 'self.shared.pin_scheduler_cluster()' in creator_cluster + ) + + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +struct RingState {{ + consumer: u32, + producer: u32, +}} + +impl RingState {{ + fn cursors(&self) -> [u32; 3] {{ + [self.consumer, self.consumer, self.producer] + }} + fn advance_producer(&mut self, count: u32) {{ + for _ in 0..count {{ + let next = (self.producer + 1) % WORK_RING_SLOTS; + assert_ne!(next, self.consumer, "outer ring overcommitted past consumer"); + self.producer = next; + }} + }} + fn consume_if_needed(&mut self, keep_free: u32) {{ + while free(self.cursors()).unwrap() < keep_free {{ + assert_ne!(self.consumer, self.producer); + self.consumer = (self.consumer + 1) % WORK_RING_SLOTS; + }} + }} +}} + +struct HostPortScope<'a> {{ + scope: Option>, + m5_outer: Arc>, +}} + +impl Drop for HostPortScope<'_> {{ + fn drop(&mut self) {{ + if let Some(scope) = self.scope.take() {{ + let _guard = self.m5_outer.lock().unwrap(); + drop(scope); + }} + }} +}} + +fn test_serialized_tight_ring_contention() {{ + let credits = Credits::new().unwrap(); + // Start with only 4 free slots so any race between claim_outer, reserve_m5_outer, + // and OuterScope entry/drop immediately overcommits or trips EIO. + let m5_outer = Arc::new(Mutex::new(RingState {{ + consumer: 5, + producer: 0, + }})); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + + for tid in 0..4u32 {{ + let c = credits.clone(); + let lock = m5_outer.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 3000 {{ + let reserved = {{ + let mut ring = lock.lock().unwrap(); + ring.consume_if_needed(4); + if c.is_scoped() {{ + Err(EBUSY) + }} else {{ + c.reserve(1, 1, ring.cursors()) + }} + }}; + if let Ok(mut claim) = reserved {{ + if (iters + tid) % 4 == 0 {{ + // Simulate compute_direct fallback: drop unspent claim outside m5_outer. + drop(claim); + }} else {{ + let mut ring = lock.lock().unwrap(); + ring.advance_producer(1); + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + + // Device-mutex publisher: claim_outer() + PortOuterScope entry/drop all serialized on m5_outer. + for iter in 0..400u32 {{ + let claim = {{ + let mut ring = m5_outer.lock().unwrap(); + ring.consume_if_needed(4); + credits.reserve(1, 2, ring.cursors()) + }}; + if let Ok(mut render_claim) = claim {{ + let mut scoped = false; + {{ + let scope = {{ + let _guard = m5_outer.lock().unwrap(); + credits.scope(&mut render_claim).map(|scope| HostPortScope {{ + scope: Some(scope), + m5_outer: m5_outer.clone(), + }}) + }}; + if let Ok(scope) = scope {{ + if iter % 3 != 0 {{ + let mut ring = m5_outer.lock().unwrap(); + assert!(credits.capacity(1, ring.cursors()).unwrap() >= 2); + ring.advance_producer(2); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + }} + drop(scope); + scoped = true; + }} + }} + if scoped {{ + if iter % 3 != 0 {{ + assert_eq!(render_claim.remaining(), 0); + }} else {{ + assert_eq!(render_claim.remaining(), 2); + }} + }} + drop(render_claim); + }} + }} + + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + let ring = m5_outer.lock().unwrap(); + let expected = free(ring.cursors()).unwrap(); + assert_eq!(credits.capacity(1, ring.cursors()).unwrap(), expected); +}} + +fn test_fallback_preserves_claim_without_spurious_notify() {{ + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let claim = credits.reserve(1, 1, cursors).unwrap(); + let notes_before = credits.available().notifications(); + + // Simulate compute_direct taking held claim and restoring it on None fallback. + let mut held: Option = Some(claim); + let mut m5_outer = held.take(); + assert!(held.is_none()); + let outcome: Option = None; + if outcome.is_none() {{ + if let Some(c) = m5_outer.take().filter(|c| c.remaining() != 0) {{ + if !held.as_ref().is_some_and(|e| e.remaining() != 0) {{ + held = Some(c); + }} + }} + }} + drop(m5_outer); + assert!(held.is_some()); + assert_eq!(held.as_ref().unwrap().remaining(), 1); + assert_eq!(credits.available().notifications(), notes_before); + + // Subsequent slow-path publication consumes the restored claim cleanly. + let mut c = held.take().unwrap(); + credits.consume_direct(&mut c).unwrap(); + assert_eq!(c.remaining(), 0); + drop(c); + assert_eq!(credits.available().notifications(), notes_before); +}} + +fn main() {{ + assert!({str(claim_outer_ok).lower()}, "claim_outer must hold Port::m5_outer around reserve_outer"); + assert!({str(publish_claimed_ok).lower()}, "publish_claimed must use Port::outer_scope"); + assert!({str(render_scope_ok).lower()}, "render/prepare.rs must use Port::outer_scope"); + assert!({str(port_scope_ok).lower()}, "Port::outer_scope and PortOuterScope::drop must hold Port::m5_outer"); + assert!({str(direct_restore_ok).lower()}, "compute_direct must restore unspent m5_outer claim on None fallback outside cell.lock()"); + assert!({str(cluster_pin_ok).lower()}, "scheduler cluster pinning must require multi-die M5 (num_dies > 1)"); + test_serialized_tight_ring_contention(); + test_fallback_preserves_claim_without_spurious_notify(); + println!("PASS g17-m5-multiqueue-contention-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--mutation', + choices=[ + 'unlocked-claim-outer', + 'raw-compute-scope', + 'raw-render-scope', + 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', + 'pin-single-die', + ], + ) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-mq-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index e768d930cc34d3..79281c819bab9f 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -257,6 +257,10 @@ def mutations(flag, names, base, expect=KILL): 'g17-m5-direct-compute-tests.py': [([], PASS)] + mutations('--mutation', ('no-pre-recovery-drain', 'direct-debits-published', 'scope-allows-reserve'), []), + 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', + 'raw-render-scope', 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', 'pin-single-die'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 6c2a20ce7b5037597e36f0b1bc6b4d10dd54b593 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 13:16:58 -0500 Subject: [PATCH 1054/1514] drm/asahi: g17: defer housekeeping across transient idle gaps Event passes previously treated any completion that momentarily left no work in flight as an immediate housekeeping trigger, bypassing the single-lock fast_done path and forcing a second device-mutex pass with full report drains (including three uncached core-power register reads), linger/pool/heap sweeps, and teardown checks on every sparse completion. Gate housekeeping strictly on HOUSEKEEPING_NS (1 ms) plus explicit triggers (requested passes, recovery, pending teardown, and active capacity waiters). Pass the true in_flight state to idle_check() on the fast path and arm a bounded HOUSEKEEPING_WORK delayed timer whenever a pass defers housekeeping with no work remaining in flight, so true idle cleanup, report drains, linger/pool expiry, and sleep_quiet() continue to run within 1 ms once work actually stops. Add host tests and mutation controls in g17-m5-idle-housekeeping-tests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/mod.rs | 29 ++ drivers/gpu/drm/asahi/g17/runtime/events.rs | 114 ++++++-- drivers/gpu/drm/asahi/g17/sleep.rs | 1 + tools/asahi/g17-m5-idle-housekeeping-tests.py | 254 ++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 5 files changed, 372 insertions(+), 29 deletions(-) create mode 100755 tools/asahi/g17-m5-idle-housekeeping-tests.py diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index dd0c3c24536867..b25fd2131a03aa 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1176,6 +1176,9 @@ const GROW_WORK: u64 = 3; const RECLAIM_WORK: u64 = 4; const FEED_WORK: u64 = 5; const GOVERNOR_WORK: u64 = 6; +/// Deferred housekeeping deadline when a completion drained the last in-flight work within +/// `HOUSEKEEPING_NS`. +const HOUSEKEEPING_WORK: u64 = 7; /// Device state shared with the coprocessor callbacks and the event worker. #[pin_data] @@ -1249,6 +1252,8 @@ struct Shared { poll: DelayedWork, #[pin] idle: DelayedWork, + #[pin] + housekeeping_timer: DelayedWork, /// M5: the thermal governor runs (the firmware has the host power budget word). governs: bool, #[pin] @@ -1307,6 +1312,9 @@ impl_has_delayed_work! { impl_has_delayed_work! { impl HasDelayedWork for Shared { self.idle } } +impl_has_delayed_work! { + impl HasDelayedWork for Shared { self.housekeeping_timer } +} impl_has_delayed_work! { impl HasDelayedWork for Shared { self.governor } } @@ -1394,6 +1402,15 @@ impl WorkItem for Shared { this.queue_events(); } } +impl WorkItem for Shared { + type Pointer = Arc; + fn run(this: Arc) { + if this.sleeping() { + return; + } + this.queue_events(); + } +} impl WorkItem for Shared { type Pointer = Arc; @@ -1550,6 +1567,16 @@ impl Shared { .enqueue_delayed::, IDLE_WORK>(self.clone(), msecs_to_jiffies(delay_ms)); } + fn queue_housekeeping(self: &Arc, delay_ns: u64) { + let delay_ms = delay_ns + .div_ceil(1_000_000) + .clamp(1, u64::from(u32::MAX)) as u32; + let _ = workqueue::system_highpri().enqueue_delayed::, HOUSEKEEPING_WORK>( + self.clone(), + msecs_to_jiffies(delay_ms), + ); + } + fn disable_timer(self: &Arc, timer: &DelayedWork) { // SAFETY: Every caller passes one of this Shared's initialized pinned // timer fields. raw_as_work points into its delayed_work; the C call @@ -1797,6 +1824,7 @@ impl Gpu { housekeeping_ns: AtomicU64::new(0), poll <- new_delayed_work!("g17::Shared::poll"), idle <- new_delayed_work!("g17::Shared::idle"), + housekeeping_timer <- new_delayed_work!("g17::Shared::housekeeping_timer"), governs: m5, governor <- new_delayed_work!("g17::Shared::governor"), governor_armed: AtomicBool::new(false), @@ -2472,6 +2500,7 @@ impl Gpu { self.shared.stop_queues(); self.shared.disable_timer(&self.shared.poll); self.shared.disable_timer(&self.shared.idle); + self.shared.disable_timer(&self.shared.housekeeping_timer); self.shared.disable_timer(&self.shared.governor); if let Some(firmware) = (*self.shared.state.lock()).as_deref_mut() { firmware.governor_restore(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 1016e6d6739e82..2dbe0246b2df58 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -19,6 +19,45 @@ const SHRINK_WAKE_NS: u64 = 1_000_000_000; /// completion records alone keep the worker busy. const HOUSEKEEPING_NS: u64 = 1_000_000; +/// Whether an event pass must run full housekeeping now rather than deferring it to the +/// periodic cadence. Transient idle gaps between sparse submissions defer housekeeping until +/// `HOUSEKEEPING_NS` elapses (bounded by [`deferred_housekeeping_delay`]) so completions avoid +/// repeated report drains and uncached power-register reads. +fn housekeeping_due( + requested: bool, + recover: bool, + recovery_pending: bool, + teardown_pending: bool, + has_waiters: bool, + now: u64, + last_housekeeping_ns: u64, +) -> bool { + requested + || recover + || recovery_pending + || teardown_pending + || has_waiters + || now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS +} + +/// Remaining delay (ns) before deferred housekeeping must run when no work remains in flight. +/// Returns `None` while work stays in flight or when housekeeping ran on this pass. +fn deferred_housekeeping_delay( + in_flight: bool, + housekeeping_ran: bool, + now: u64, + last_housekeeping_ns: u64, +) -> Option { + if in_flight || housekeeping_ran { + return None; + } + Some( + HOUSEKEEPING_NS + .saturating_sub(now.saturating_sub(last_housekeeping_ns)) + .max(1), + ) +} + struct Service<'a> { firmware: &'a mut Firmware, deferred: &'a mut DeferredBatch, @@ -559,9 +598,10 @@ impl crate::g17::Shared { // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - // Steady-state pure-compute completions with work still in flight, no render work - // to observe, no replays, no waiters and housekeeping not yet due finish in this - // single device-mutex hold; fences are signalled right after unlocking. + // Steady-state pure-compute completions with no render work to observe, no replays, + // no waiters and housekeeping not yet due finish in this single device-mutex hold; + // fences are signalled right after unlocking. Transient idle intervals defer + // housekeeping to the cadence timer rather than draining reports on every completion. let mut fast_done = false; if !recover && !requested @@ -573,22 +613,33 @@ impl crate::g17::Shared { let now = super::now_ns(); let in_flight = scan.in_flight || firmware.queues.render_in_flight(); let no_replay = !scan.replay && !firmware.queues.render.replay_parked(); - let no_housekeeping = in_flight - && firmware.queues.teardown.is_empty() - && !self.channels.has_waiters() - && !self.progress.has_waiters() - && !self.queues.has_waiters() - && !self.renders.has_waiters() - && now.saturating_sub( - self.housekeeping_ns - .load(core::sync::atomic::Ordering::Relaxed), - ) < HOUSEKEEPING_NS; + let last_hk = self + .housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed); + let has_waiters = self.channels.has_waiters() + || self.progress.has_waiters() + || self.queues.has_waiters() + || self.renders.has_waiters(); + let no_housekeeping = !housekeeping_due( + false, + false, + false, + !firmware.queues.teardown.is_empty(), + has_waiters, + now, + last_hk, + ); let no_outer_or_grow = !firmware.init.outer_waiting() && !firmware.render_grow_ready(); if no_replay && no_housekeeping && no_outer_or_grow { - if let Some(delay) = firmware.idle_check(now, true)? { + if let Some(delay) = firmware.idle_check(now, in_flight)? { self.queue_idle(delay); } + if let Some(delay) = + deferred_housekeeping_delay(in_flight, false, now, last_hk) + { + self.queue_housekeeping(delay); + } let polling = scan.polling || firmware.non_compute_runtime_polling(now); if polling { self.queue_poll(); @@ -666,23 +717,25 @@ impl crate::g17::Shared { let idle = firmware.idle_check(now, in_flight)?; // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report // drains give back what retirement freed; a completion needs none of them to retire - // or to signal. While work is in flight and nothing waits for capacity, a pass for - // firmware records alone skips them. Any requested pass, recovery, teardown, a waiter, - // the last retirement and, at the latest, the first pass after HOUSEKEEPING_NS run - // them all. - let housekeeping = requested - || recover - || !in_flight - || firmware.recovery.pending() - || !firmware.queues.teardown.is_empty() - || self.channels.has_waiters() + // or to signal. While nothing waits for capacity and `HOUSEKEEPING_NS` has not elapsed, + // a pass for firmware records alone skips them; when no work stays in flight, a bounded + // housekeeping timer guarantees cleanup runs once the interval expires. + let last_hk = self + .housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed); + let has_waiters = self.channels.has_waiters() || self.progress.has_waiters() || self.queues.has_waiters() - || self.renders.has_waiters() - || now.saturating_sub( - self.housekeeping_ns - .load(core::sync::atomic::Ordering::Relaxed), - ) >= HOUSEKEEPING_NS; + || self.renders.has_waiters(); + let housekeeping = housekeeping_due( + requested, + recover, + firmware.recovery.pending(), + !firmware.queues.teardown.is_empty(), + has_waiters, + now, + last_hk, + ); let mut lingers = None; let mut drains = None; let mut kills = None; @@ -744,6 +797,9 @@ impl crate::g17::Shared { if let Some(delay) = idle { self.queue_idle(delay); } + if let Some(delay) = deferred_housekeeping_delay(in_flight, housekeeping, now, last_hk) { + self.queue_housekeeping(delay); + } if firmware.recovery.pending() { self.preparations.close(); self.queue_events(); diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index 28524b3bf68f62..a88a881c5de664 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -317,6 +317,7 @@ impl Shared { fn join_event_workers(self: &Arc) { self.cancel_timer(&self.poll); self.cancel_timer(&self.idle); + self.cancel_timer(&self.housekeeping_timer); // SAFETY: An initialized, pinned work field of this Shared. unsafe { bindings::flush_work(Work::raw_get(&self.work)) }; } diff --git a/tools/asahi/g17-m5-idle-housekeeping-tests.py b/tools/asahi/g17-m5-idle-housekeeping-tests.py new file mode 100755 index 00000000000000..83caa5a7978bd4 --- /dev/null +++ b/tools/asahi/g17-m5-idle-housekeeping-tests.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for deferred idle housekeeping cadence in `runtime_event_turn()`. + +Compiles the real `HOUSEKEEPING_NS`, `housekeeping_due()`, and +`deferred_housekeeping_delay()` helpers from +`drivers/gpu/drm/asahi/g17/runtime/events.rs` on the host and tests: +1. Sparse completions where `in_flight` transiently drops to `false` within + `< HOUSEKEEPING_NS` take `fast_done`, do NOT run housekeeping/power MMIO, + pass actual `in_flight` to `idle_check(now, in_flight)`, and arm the + deferred housekeeping timer within `<= HOUSEKEEPING_NS`. +2. Once `HOUSEKEEPING_NS` elapses (or `requested`, `recover`, + `recovery_pending`, `teardown_pending`, or any capacity waiter is active), + housekeeping runs and `deferred_housekeeping_delay()` returns `None`. +3. While `in_flight` stays `true`, `fast_done` skips housekeeping without + arming the deferred housekeeping timer. +4. Structural verification of `runtime/events.rs`, `mod.rs`, and `sleep.rs`: + `HOUSEKEEPING_WORK` is cancelled on sleep and disabled on shutdown, and + `runtime_event_turn()` passes actual `in_flight` to `idle_check()` and + arms `queue_housekeeping()` whenever `!in_flight` defers housekeeping. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + events_src = (G17 / 'runtime/events.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + sleep_src = (G17 / 'sleep.rs').read_text() + + hk_const = 'const HOUSEKEEPING_NS: u64 = 1_000_000;' + assert hk_const in events_src + hk_due = item(events_src, 'fn housekeeping_due(') + hk_delay = item(events_src, 'fn deferred_housekeeping_delay(') + turn = item(events_src, 'fn runtime_event_turn(') + + if mutation == 'idle-forces-housekeeping': + hk_due = hk_due.replace( + 'now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS', + 'true', + 1, + ) + elif mutation == 'no-deferred-timer': + hk_delay = hk_delay.replace( + 'if in_flight || housekeeping_ran {\n return None;\n }', + 'return None;', + 1, + ) + elif mutation == 'hardcode-in-flight-true': + turn = turn.replace( + 'firmware.idle_check(now, in_flight)?', + 'firmware.idle_check(now, true)?', + 1, + ) + elif mutation == 'skip-cadence-expiry': + hk_due = hk_due.replace( + '|| now.saturating_sub(last_housekeeping_ns) >= HOUSEKEEPING_NS', + '', + 1, + ) + + fast_idle_ok = ( + 'firmware.idle_check(now, in_flight)?' in turn + and 'firmware.idle_check(now, true)?' not in turn + ) + fast_timer_ok = turn.count('self.queue_housekeeping(delay);') == 2 + no_idle_force_ok = ( + '|| !in_flight' not in turn + and 'let no_housekeeping = in_flight' not in turn + ) + lifecycle_ok = ( + 'self.shared.disable_timer(&self.shared.housekeeping_timer);' in mod_src + and 'self.cancel_timer(&self.housekeeping_timer);' in sleep_src + and 'impl WorkItem for Shared' in mod_src + ) + + return f''' +{hk_const} + +{hk_due} + +{hk_delay} + +struct TurnCounters {{ + fast_done: usize, + housekeeping_runs: usize, + power_mmio_reads: usize, + idle_check_in_flight_false: usize, + deferred_timer_arms: usize, + last_deferred_delay_ns: Option, +}} + +struct MockEventLoop {{ + last_hk: u64, + counters: TurnCounters, +}} + +impl MockEventLoop {{ + fn new(last_hk: u64) -> Self {{ + Self {{ + last_hk, + counters: TurnCounters {{ + fast_done: 0, + housekeeping_runs: 0, + power_mmio_reads: 0, + idle_check_in_flight_false: 0, + deferred_timer_arms: 0, + last_deferred_delay_ns: None, + }}, + }} + }} + + fn run_compute_completion( + &mut self, + now: u64, + in_flight: bool, + requested: bool, + recover: bool, + recovery_pending: bool, + teardown_pending: bool, + has_waiters: bool, + ) {{ + let no_hk = !housekeeping_due( + requested, + recover, + recovery_pending, + teardown_pending, + has_waiters, + now, + self.last_hk, + ); + if !recover && !requested && no_hk {{ + if !in_flight {{ + self.counters.idle_check_in_flight_false += 1; + }} + if let Some(delay) = deferred_housekeeping_delay(in_flight, false, now, self.last_hk) {{ + self.counters.deferred_timer_arms += 1; + self.counters.last_deferred_delay_ns = Some(delay); + }} + self.counters.fast_done += 1; + return; + }} + let hk = housekeeping_due( + requested, + recover, + recovery_pending, + teardown_pending, + has_waiters, + now, + self.last_hk, + ); + if hk {{ + self.last_hk = now; + self.counters.housekeeping_runs += 1; + self.counters.power_mmio_reads += 3; + }} + if let Some(delay) = deferred_housekeeping_delay(in_flight, hk, now, self.last_hk) {{ + self.counters.deferred_timer_arms += 1; + self.counters.last_deferred_delay_ns = Some(delay); + }} + }} +}} + +fn main() {{ + assert!({str(fast_idle_ok).lower()}, "fast_done must pass actual in_flight to idle_check()"); + assert!({str(fast_timer_ok).lower()}, "both fast and slow paths must arm queue_housekeeping when !in_flight defers"); + assert!({str(no_idle_force_ok).lower()}, "transient !in_flight must not force immediate housekeeping"); + assert!({str(lifecycle_ok).lower()}, "housekeeping_timer must be wired to sleep cancel and shutdown disable"); + + // 1. Sparse !in_flight completions within < HOUSEKEEPING_NS hit fast_done with zero power MMIO + // and arm the deferred housekeeping timer within <= HOUSEKEEPING_NS. + let mut lp = MockEventLoop::new(10_000_000); + for step in 1..=10u64 {{ + lp.run_compute_completion(10_000_000 + step * 80_000, false, false, false, false, false, false); + }} + assert_eq!(lp.counters.fast_done, 10, "sparse !in_flight completions within 1 ms must hit fast_done"); + assert_eq!(lp.counters.housekeeping_runs, 0, "sparse !in_flight completions must not run housekeeping"); + assert_eq!(lp.counters.power_mmio_reads, 0, "sparse !in_flight completions must not read power MMIO"); + assert_eq!(lp.counters.idle_check_in_flight_false, 10); + assert_eq!(lp.counters.deferred_timer_arms, 10, "deferred !in_flight must arm housekeeping timer"); + assert_eq!(lp.counters.last_deferred_delay_ns, Some(200_000)); + + // 2. Once HOUSEKEEPING_NS elapses, housekeeping runs and clears the deferred timer requirement. + lp.run_compute_completion(11_000_000, false, false, false, false, false, false); + assert_eq!(lp.counters.housekeeping_runs, 1); + assert_eq!(lp.counters.power_mmio_reads, 3); + assert_eq!(lp.counters.deferred_timer_arms, 10, "running housekeeping must not re-arm deferred timer"); + + // 3. Explicit triggers run housekeeping immediately even within < HOUSEKEEPING_NS. + for (req, rec, rec_pend, tear, wait) in [ + (true, false, false, false, false), + (false, true, false, false, false), + (false, false, true, false, false), + (false, false, false, true, false), + (false, false, false, false, true), + ] {{ + assert!(housekeeping_due(req, rec, rec_pend, tear, wait, 11_050_000, 11_000_000)); + }} + + // 4. Busy in_flight completions within < HOUSEKEEPING_NS hit fast_done without arming deferred timer. + let mut busy = MockEventLoop::new(20_000_000); + busy.run_compute_completion(20_100_000, true, false, false, false, false, false); + assert_eq!(busy.counters.fast_done, 1); + assert_eq!(busy.counters.housekeeping_runs, 0); + assert_eq!(busy.counters.deferred_timer_arms, 0); + + // 5. Boundary: remaining delay is clamped to >= 1 ns even right at the threshold. + assert_eq!(deferred_housekeeping_delay(false, false, 21_000_000, 20_000_000), Some(1)); + assert_eq!(deferred_housekeeping_delay(false, true, 20_100_000, 20_000_000), None); + assert_eq!(deferred_housekeeping_delay(true, false, 20_100_000, 20_000_000), None); + + println!("PASS g17-m5-idle-housekeeping-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['idle-forces-housekeeping', + 'no-deferred-timer', + 'hardcode-in-flight-true', + 'skip-cadence-expiry']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-hk-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 79281c819bab9f..4de634fbadb5e2 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -261,6 +261,9 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-idle-housekeeping-tests.py': [([], PASS)] + + mutations('--mutation', ('idle-forces-housekeeping', 'no-deferred-timer', + 'hardcode-in-flight-true', 'skip-cadence-expiry'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 173110e8e3c2333c2f16293279e44592915f7941 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 13:29:25 -0500 Subject: [PATCH 1055/1514] drm/asahi: g17: single-lock render completion fast path and doorbell lock release Steady-state render submissions and completions previously incurred three avoidable lock holds and wakeups on the hot path: 1. runtime_event_turn() always exited its fast path whenever any render completion mask arrived, forcing four separate Shared::state mutex acquisitions per render retirement (drain events, drain deferred errors, observe_renders(), and final idle/housekeeping pass). 2. DirectHost::notify_render() held both Port::m5_outer and Port::render across mailbox doorbell I/O even after outer ring producers, credits, and hazard ordering were already committed. 3. Availability::advance() unconditionally acquired the waiter mutex even with zero waiters, and Shared::note_changed() unconditionally called changed.notify_all() even when no thread waited on the condvar. Add Firmware::try_fast_observe_render() to retire healthy coalesced ready render completions (bounded by RENDER_SLOTS and preallocated DeferredBatch room) directly inside runtime_event_turn()'s single device-mutex hold under a pre-acquired preparation epoch, falling back to observe_renders() on any pending error, timeout, close, growth, replay, terminal fault, deferred-room shortage, or remaining backlog. Fold slow-path deferred error draining and rescan checks into runtime_event_turn()'s existing mutex holds so observe_renders() takes only one state lock per turn. Release m5_outer (after submission history) and render in reverse order before port.notify() in DirectHost::notify_render(). Keep Availability's generation bump lock-free when has_waiters is false (preserving Dekker ordering against wait()), and wrap Shared::changed in TrackedCondVar so zero-waiter notify_all() skips the condvar waitqueue lock. Add host unit tests and mutation controls in g17-m5-render-fast-done-tests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/availability.rs | 32 +- drivers/gpu/drm/asahi/g17/mod.rs | 40 +- drivers/gpu/drm/asahi/g17/runtime.rs | 4 + drivers/gpu/drm/asahi/g17/runtime/events.rs | 67 +++- drivers/gpu/drm/asahi/g17/runtime/render.rs | 2 +- .../drm/asahi/g17/runtime/render/direct.rs | 22 +- .../drm/asahi/g17/runtime/render/observe.rs | 174 ++++++-- tools/asahi/g17-m5-render-fast-done-tests.py | 377 ++++++++++++++++++ tools/asahi/run-host-tests.py | 8 + 9 files changed, 667 insertions(+), 59 deletions(-) create mode 100755 tools/asahi/g17-m5-render-fast-done-tests.py diff --git a/drivers/gpu/drm/asahi/g17/availability.rs b/drivers/gpu/drm/asahi/g17/availability.rs index 9deaac406a5a2f..8d5a213bb4b2ea 100644 --- a/drivers/gpu/drm/asahi/g17/availability.rs +++ b/drivers/gpu/drm/asahi/g17/availability.rs @@ -7,6 +7,7 @@ //! lock round trip. use super::fence::{self, CompletionFence}; +use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, RawDmaFence, UserFence}, @@ -21,12 +22,13 @@ struct Entry { } struct State { - generation: u64, waiters: Option>, } #[pin_data] pub(crate) struct Availability { + generation: AtomicU64, + has_waiters: AtomicBool, #[pin] state: Mutex, fences: FenceContexts, @@ -36,8 +38,10 @@ impl Availability { pub(crate) fn new() -> Result> { Arc::pin_init( try_pin_init!(Self { + generation: AtomicU64::new(0), + has_waiters: AtomicBool::new(false), state <- new_mutex!( - State { generation: 0, waiters: None }, + State { waiters: None }, "g17::Availability" ), fences: FenceContexts::new(1, c_str!("aurora_resource"), kernel::static_lock_class!())?, @@ -48,11 +52,11 @@ impl Availability { /// Sample before checking capacity under the resource's own synchronization. pub(crate) fn observe(&self) -> u64 { - self.state.lock().generation + self.generation.load(Ordering::Acquire) } pub(crate) fn has_waiters(&self) -> bool { - self.state.lock().waiters.is_some() + self.has_waiters.load(Ordering::Acquire) } /// A fence the next notification signals. None means capacity changed after the sample: @@ -69,7 +73,14 @@ impl Availability { GFP_KERNEL, )?; let mut state = self.state.lock(); - if state.generation != observed { + // Publish `has_waiters` with SeqCst before re-checking `generation` (SeqCst), + // pairing with `advance()`'s SeqCst fetch_add on `generation` followed by SeqCst + // load of `has_waiters` so no waiter can be lost on the lock-free fast path. + self.has_waiters.store(true, Ordering::SeqCst); + if self.generation.load(Ordering::SeqCst) != observed { + if state.waiters.is_none() { + self.has_waiters.store(false, Ordering::Release); + } return Ok(None); } entry.next = state.waiters.take(); @@ -115,11 +126,14 @@ impl Availability { /// Notifies, returning the generation before this notification. fn advance(&self) -> u64 { - let (previous, mut waiters) = { + let previous = self.generation.fetch_add(1, Ordering::SeqCst); + if !self.has_waiters.load(Ordering::SeqCst) { + return previous; + } + let mut waiters = { let mut state = self.state.lock(); - let previous = state.generation; - state.generation = previous.wrapping_add(1); - (previous, state.waiters.take()) + self.has_waiters.store(false, Ordering::Release); + state.waiters.take() }; while let Some(mut entry) = waiters { waiters = entry.next.take(); diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index dd0c3c24536867..7faf86efff627f 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1177,6 +1177,39 @@ const RECLAIM_WORK: u64 = 4; const FEED_WORK: u64 = 5; const GOVERNOR_WORK: u64 = 6; +/// `CondVar` wrapper that tracks active waiters so `notify_all()` skips the waitqueue lock +/// in the common zero-waiter steady state. +#[pin_data] +struct TrackedCondVar { + #[pin] + condvar: CondVar, + waiters: AtomicU32, +} + +impl TrackedCondVar { + fn wait_timeout( + &self, + guard: &mut kernel::sync::MutexGuard<'_, T>, + timeout: kernel::time::Jiffies, + ) -> kernel::sync::CondVarTimeoutResult { + struct Waiter<'a>(&'a AtomicU32); + impl Drop for Waiter<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Release); + } + } + self.waiters.fetch_add(1, Ordering::SeqCst); + let _waiter = Waiter(&self.waiters); + self.condvar.wait_timeout(guard, timeout) + } + + fn notify_all(&self) { + if self.waiters.load(Ordering::SeqCst) != 0 { + self.condvar.notify_all(); + } + } +} + /// Device state shared with the coprocessor callbacks and the event worker. #[pin_data] struct Shared { @@ -1292,7 +1325,7 @@ struct Shared { #[pin] actuators: Mutex, #[pin] - changed: CondVar, + changed: TrackedCondVar, /// The port of the session in `state`; null before boot and once detachment begins. port: core::sync::atomic::AtomicPtr, } @@ -1815,7 +1848,10 @@ impl Gpu { stop <- new_mutex!((), "g17::Shared::stop"), state <- new_mutex!(None, "g17::Shared::state"), actuators <- new_mutex!(thermal::Actuators::new(), "g17::Shared::actuators"), - changed <- new_condvar!("g17::Shared::changed"), + changed <- pin_init!(TrackedCondVar { + condvar <- new_condvar!("g17::Shared::changed"), + waiters: AtomicU32::new(0), + }), port: core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()), }), GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 2297c1a79429f5..6cbc0068fc69ff 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1490,6 +1490,10 @@ impl DeferredBatch { pub(super) fn pending(&self) -> usize { self.values.len() } + /// Whether the preallocated batch still has room for at least `need` entries. + pub(super) fn has_room(&self, need: usize) -> bool { + self.values.capacity().saturating_sub(self.values.len()) >= need + } /// Called only after releasing the device mutex. pub(super) fn finish(&mut self) { use super::completion::Deferred; diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 1016e6d6739e82..1a2d4de2f944da 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -547,7 +547,10 @@ impl crate::g17::Shared { let requested = self .housekeeping .swap(false, core::sync::atomic::Ordering::AcqRel); - let (recover, masks, fast_done) = { + let (recover, masks, fast_done, render_changed) = { + // Taken before `state` so single-lock render retirement observes a live preparation + // epoch and drops it before `wait_drained_until()` if recovery opens. + let fast_epoch = self.preparations.try_enter().ok(); let mut state = self.state.lock(); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); @@ -559,17 +562,54 @@ impl crate::g17::Shared { // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - // Steady-state pure-compute completions with work still in flight, no render work - // to observe, no replays, no waiters and housekeeping not yet due finish in this - // single device-mutex hold; fences are signalled right after unlocking. + // Steady-state compute or render completions with work still in flight, no replays, + // no waiters and housekeeping not yet due finish in this single device-mutex hold; + // fences are signalled right after unlocking. let mut fast_done = false; + let mut render_changed = false; if !recover && !requested && !self.crashed.load(core::sync::atomic::Ordering::Acquire) - && masks == [0; 2] - && !firmware.render_observation_needed() { - if let Some(scan) = compute_scan { + let needs_render = masks != [0; 2] || firmware.render_observation_needed(); + let render_clean = if !needs_render { + true + } else if fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current()) { + let before = deferred.pending(); + match firmware.try_fast_observe_render(deferred)? { + super::render::observe::FastRenderOutcome::Done => { + render_changed = true; + true + } + super::render::observe::FastRenderOutcome::Idle => true, + super::render::observe::FastRenderOutcome::Fallback => { + render_changed = deferred.pending() != before; + false + } + } + } else { + false + }; + if render_clean && (compute_scan.is_some() || render_changed) { + let scan = match compute_scan { + Some(scan) => scan, + None => { + let mut scan = super::ComputeScan::default(); + for queue in firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + { + scan.in_flight |= queue.in_flight(); + scan.replay |= queue.replay_commands() != 0; + scan.polling |= + queue.retirement_polling() || queue.pool_release_pending(); + } + scan + } + }; let now = super::now_ns(); let in_flight = scan.in_flight || firmware.queues.render_in_flight(); let no_replay = !scan.replay && !firmware.queues.render.replay_parked(); @@ -602,8 +642,11 @@ impl crate::g17::Shared { } } } - (recover, masks, fast_done) + (recover, masks, fast_done, render_changed) }; + if render_changed { + self.note_changed(); + } deferred.finish(); crate::g17::trace::event(1); if fast_done { @@ -644,12 +687,18 @@ impl crate::g17::Shared { firmware.replay_render(deferred)?; // Skip dropping and re-acquiring the device mutex around a no-op render observation. if masks != [0; 2] || firmware.render_observation_needed() { + firmware.drain_render_deferred(masks, deferred)?; drop(state); - self.observe_renders(masks, deferred)?; + self.observe_renders(deferred)?; state = self.state.lock(); if self.crashed.load(core::sync::atomic::Ordering::Acquire) { return Err(EIO); } + if let Some(firmware) = (*state).as_deref() { + if !firmware.recovery.pending() && firmware.queues.render_needs_rescan() { + self.queue_poll(); + } + } } let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 1e81756ae2ce46..335640c9ad8c01 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -8,7 +8,7 @@ mod exit; mod dependencies; mod direct; mod grow; -mod observe; +pub(super) mod observe; mod pools; mod prepare; mod recovery; diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 0a7223d77c2b67..688bfe8057bb9a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -43,7 +43,7 @@ enum DirectTarget { /// graph that needs no growth. struct DirectHost<'a> { port: &'a Port, - render: &'a MutexGuard<'a, ()>, + render: Option>, m5_outer: Option>>, m5_claim: Option<&'a mut crate::g17::initdata::OuterClaim>, target: DirectTarget, @@ -95,8 +95,9 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { if priority != room.priority() { return Err(EINVAL); } + let render = self.render.as_ref().ok_or(EIO)?; self.port.write_render_pair( - self.render, + render, room, fragment, tiling, @@ -108,9 +109,10 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { if priority != room.priority() { return Err(EINVAL); } + let render = self.render.as_ref().ok_or(EIO)?; let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; self.port.write_m5_render_pair( - self.render, + render, m5_outer, room, fragment, @@ -149,16 +151,18 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { if priority != room.priority() { return Err(EINVAL); } - self.port.expose_render_pair(self.render, room, next) + let render = self.render.as_ref().ok_or(EIO)?; + self.port.expose_render_pair(render, room, next) } DirectTarget::M5(room) => { if priority != room.priority() { return Err(EINVAL); } + let render = self.render.as_ref().ok_or(EIO)?; let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; let claim = self.m5_claim.as_deref_mut().ok_or(EIO)?; self.port - .expose_m5_render_pair(self.render, m5_outer, room, claim, next) + .expose_m5_render_pair(render, m5_outer, room, claim, next) } } } @@ -170,7 +174,13 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { if let Err(error) = self.port.note_m5_submission_history_locked(geometry, 2) { pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer = None; } + // Outer ring producers, credits, and hazard order are committed; drop the render + // publication lock before mailbox I/O as well. + self.render = None; self.port.notify(super::render_doorbell_message(m5, priority)) } fn note_submission(&mut self) -> Result { @@ -422,7 +432,7 @@ impl Backend { } let mut host = DirectHost { port, - render: &render, + render: Some(render), m5_outer, m5_claim: m5_claim.as_mut(), target, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs index 63bae4052b14e1..2d8d02d8ab7cef 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs @@ -7,6 +7,17 @@ use super::super::DeferredBatch; use core::sync::atomic::Ordering; use kernel::{prelude::*, sync::Arc}; +/// Outcome of attempting single-lock steady-state render completion in `runtime_event_turn()`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::g17::runtime) enum FastRenderOutcome { + /// Non-steady state or additional render work requires the full `observe_renders()` path. + Fallback, + /// Healthy render state with no ready observation to retire. + Idle, + /// Retired the single ready render observation cleanly with no further render work pending. + Done, +} + impl crate::g17::Firmware { /// Whether `observe_renders` has any deferred settlement or in-flight render observation /// pending. Pure compute passes can skip dropping and re-acquiring the device mutex when false. @@ -83,7 +94,7 @@ impl crate::g17::Firmware { &mut self, slot: usize, deferred: &mut DeferredBatch, - ) -> Result { + ) -> Result { let terminal = self.queues.render.entries[slot] .as_mut() .and_then(|entry| entry.pair.as_mut()) @@ -93,40 +104,147 @@ impl crate::g17::Firmware { self.scan_compute(None, deferred)?; self.settle_render_vm(&status, error, deferred)?; self.queues.fail_compute_vm(&status, error, deferred)?; + return Ok(true); } - Ok(()) + Ok(false) } -} -impl crate::g17::Shared { - pub(in crate::g17) fn observe_renders( - self: &Arc, + /// Retains newly reported render masks and drains any deferred per-slot errors, timeouts, or + /// closes while the caller already holds the device mutex. + pub(in crate::g17::runtime) fn drain_render_deferred( + &mut self, masks: [u64; 2], deferred: &mut DeferredBatch, ) -> Result { + let _ = self.queues.retain_render_completions(masks); + // Returned preparers can have deferred a VM failure or timeout. + // Only this full worker collector runs their final observations. + for slot in 1..self.queues.render.entries.len() { + if self.queues.render.entries[slot] + .as_ref() + .is_some_and(|entry| { + entry.pair.is_some() + && (entry.pending_error.is_some() + || entry.pending_timeout + || entry.closed) + }) + { + self.apply_render_deferred(slot as u8, deferred)?; + } + } + Ok(()) + } + + /// Retires healthy steady-state render completions (across one or more coalesced ready slots, + /// bounded by `RENDER_SLOTS` and preallocated `deferred` room) under the event worker's + /// already-held device mutex with a live preparation lease. Any error, timeout, close, + /// growth, replay, terminal fault, deferred-room shortage, or remaining render work returns + /// `Fallback` so the full `observe_renders()` loop handles it. + pub(in crate::g17::runtime) fn try_fast_observe_render( + &mut self, + deferred: &mut DeferredBatch, + ) -> Result { + if self.recovery.pending() + || self.queues.render.replay_parked() + || self.render_grow_pending() + || self.render_grow_ready() { - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return Ok(()); + return Ok(FastRenderOutcome::Fallback); + } + for slot in 1..self.queues.render.entries.len() { + let Some(entry) = self.queues.render.entries[slot].as_ref() else { + continue; }; - let _ = firmware.queues.retain_render_completions(masks); - // Returned preparers can have deferred a VM failure or timeout. - // Only this full worker collector runs their final observations. - for slot in 1..firmware.queues.render.entries.len() { - if firmware.queues.render.entries[slot] - .as_ref() - .is_some_and(|entry| { - entry.pair.is_some() - && (entry.pending_error.is_some() - || entry.pending_timeout - || entry.closed) + if entry.pending_error.is_some() + || entry.pending_timeout + || entry.closed + || entry.growing + { + return Ok(FastRenderOutcome::Fallback); + } + } + let mut retired_any = false; + for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS { + let Some(slot) = self.next_render_observation(1)? else { + return Ok(if self.queues.render_needs_rescan() { + FastRenderOutcome::Fallback + } else if retired_any { + FastRenderOutcome::Done + } else { + FastRenderOutcome::Idle + }); + }; + if !deferred.has_room(2) { + return Ok(FastRenderOutcome::Fallback); + } + let observed = self.queues.render.entries[slot] + .as_ref() + .and_then(|entry| entry.pair.as_ref()) + .ok_or(EIO)? + .observe_front(); + let missed = self.queues.render.take_missed_event(slot as u8); + if missed || self.render_grow_pending() { + self.primary.state.shared.queue_event_records(); + } + let state = crate::g17::recovery::Memory::recovery_state(&self.init)?; + let progressed = match observed { + Ok(observed) => self.with_render(slot, |pair, host| { + pair.retire_observed(observed, state, host, &mut |event| { + deferred.push(event) }) - { - firmware.apply_render_deferred(slot as u8, deferred)?; + })?, + Err(error) if error == EAGAIN => false, + Err(error) => return Err(error), + }; + if progressed { + match self.release_render_lists() { + Err(error) if error == EAGAIN => {} + result => result?, } } + self.queues.render.collect_retired(slot)?; + let had_terminal = self.settle_render_terminal(slot, deferred)?; + if self + .queues + .render + .entry(slot as u8)? + .pair + .as_ref() + .is_some_and(|pair| !pair.in_flight()) + { + self.queues.render.entry_mut(slot as u8)?.event_masks = [0; 2]; + } + if !progressed + || missed + || had_terminal + || self.recovery.pending() + || self.render_grow_pending() + || self.render_grow_ready() + || self.queues.render_needs_rescan() + { + return Ok(FastRenderOutcome::Fallback); + } + retired_any = true; + } + if self.next_render_observation(1)?.is_some() || self.queues.render_needs_rescan() { + return Ok(FastRenderOutcome::Fallback); + } + Ok(if retired_any { + FastRenderOutcome::Done + } else { + FastRenderOutcome::Idle + }) + } +} + +impl crate::g17::Shared { + pub(in crate::g17) fn observe_renders( + self: &Arc, + deferred: &mut DeferredBatch, + ) -> Result { + if deferred.pending() != 0 { + deferred.finish(); } - deferred.finish(); let mut cursor = 1; let mut remaining = crate::hw::t8140::queues::RENDER_DEPTH; let mut retries = 0; @@ -187,7 +305,7 @@ impl crate::g17::Shared { // An observation of the old front is committed before a queued // exact timeout is permitted to advance that same tracker. firmware.apply_render_deferred(slot as u8, deferred)?; - firmware.settle_render_terminal(slot, deferred)?; + let _ = firmware.settle_render_terminal(slot, deferred)?; if firmware .queues .render @@ -216,14 +334,6 @@ impl crate::g17::Shared { retries = 0; } } - { - let state = self.state.lock(); - if (*state).as_deref().is_some_and(|firmware| { - !firmware.recovery.pending() && firmware.queues.render_needs_rescan() - }) { - self.queue_poll(); - } - } Ok(()) } } diff --git a/tools/asahi/g17-m5-render-fast-done-tests.py b/tools/asahi/g17-m5-render-fast-done-tests.py new file mode 100755 index 00000000000000..21dfb2db908964 --- /dev/null +++ b/tools/asahi/g17-m5-render-fast-done-tests.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for single-lock render completion fast path, doorbell lock release, and zero-waiter notifications. + +Verifies: +1. Lock-free zero-waiter `Availability::advance()` compiled from + `drivers/gpu/drm/asahi/g17/availability.rs`: zero mutex locks when no + waiter is registered, `generation` still advances on every `notify()`, + `notify_own()` works, and multi-threaded `observe -> wait` vs `notify` + suffers zero lost wakeups. +2. `DirectHost::notify_render()` (`runtime/render/direct.rs`) drops + `self.m5_outer` (after submission history) and `self.render` in strict + reverse acquisition order BEFORE calling `self.port.notify()`. +3. `runtime_event_turn()` (`runtime/events.rs`) + `try_fast_observe_render()` + (`runtime/render/observe.rs`): + - `fast_epoch` is taken before `state.lock()` and dropped before + `wait_drained_until()` (no recovery deadlock). + - Healthy single-slot render completions return `FastRenderOutcome::Done` + under one lock hold, while `pending_error`, `pending_timeout`, `closed`, + `growing`, `had_terminal`, `missed`, `render_needs_rescan()`, and + multi-slot pending work fall back to `observe_renders()`. + - Slow-path `observe_renders()` folds deferred-error drain and rescan + checks into `runtime_event_turn()`'s existing `state.lock()` holds. +4. `Shared::note_changed()` (`mod.rs`) gates `self.changed.notify_all()` on + `changed_waiters` and all `changed.wait_timeout` callers in `runtime.rs` + use `wait_changed_timeout()`. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + avail_src = (G17 / 'availability.rs').read_text() + direct_src = (G17 / 'runtime/render/direct.rs').read_text() + observe_src = (G17 / 'runtime/render/observe.rs').read_text() + events_src = (G17 / 'runtime/events.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + + notify_render = item(direct_src, 'fn notify_render(') + try_fast = item(observe_src, 'pub(in crate::g17::runtime) fn try_fast_observe_render(') + observe_fn = item(observe_src, 'pub(in crate::g17) fn observe_renders(') + turn = item(events_src, 'fn runtime_event_turn(') + tracked_cv = item(mod_src, 'impl TrackedCondVar') + + avail_wait = item(avail_src, 'pub(crate) fn wait(') + avail_advance = item(avail_src, 'fn advance(') + + if mutation == 'hold-m5-outer-across-doorbell': + notify_render = notify_render.replace( + 'self.m5_outer = None;', + '', + 1, + ) + elif mutation == 'hold-render-lock-across-doorbell': + notify_render = notify_render.replace( + 'self.render = None;', + '', + 1, + ) + elif mutation == 'skip-pending-error-fallback': + try_fast = try_fast.replace( + 'entry.pending_error.is_some()\n || ', + '', + 1, + ) + elif mutation == 'single-slot-bailout': + try_fast = try_fast.replace( + 'for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS {', + 'for _ in 0..1 {', + 1, + ) + elif mutation == 'skip-epoch-check': + turn = turn.replace( + 'fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current())', + 'true', + 1, + ) + elif mutation == 'unconditional-changed-notify': + tracked_cv = tracked_cv.replace( + 'if self.waiters.load(Ordering::SeqCst) != 0 {', + 'if true {', + 1, + ) + elif mutation == 'skip-generation-bump': + avail_advance = avail_advance.replace( + 'let previous = self.generation.fetch_add(1, Ordering::SeqCst);\n' + ' if !self.has_waiters.load(Ordering::SeqCst) {\n' + ' return previous;\n' + ' }', + 'if !self.has_waiters.load(Ordering::SeqCst) {\n' + ' return self.generation.load(Ordering::Acquire);\n' + ' }\n' + ' let previous = self.generation.fetch_add(1, Ordering::SeqCst);', + 1, + ) + + doorbell_order_ok = ordered_ok( + notify_render, + 'note_m5_submission_history_locked(geometry, 2)', + 'self.m5_outer = None;', + 'self.render = None;', + 'self.port.notify(super::render_doorbell_message(m5, priority))', + ) + + fast_render_guards_ok = ( + 'entry.pending_error.is_some()' in try_fast + and 'entry.pending_timeout' in try_fast + and 'entry.closed' in try_fast + and 'entry.growing' in try_fast + and 'self.recovery.pending()' in try_fast + and 'self.queues.render.replay_parked()' in try_fast + and 'self.render_grow_pending()' in try_fast + and 'self.render_grow_ready()' in try_fast + and 'had_terminal' in try_fast + and 'self.queues.render_needs_rescan()' in try_fast + and 'for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS {' in try_fast + and 'if !deferred.has_room(2)' in try_fast + and 'self.next_render_observation(1)?.is_some()' in try_fast + and 'FastRenderOutcome::Done' in try_fast + ) + + # Extract the real production loop bound from try_fast_observe_render() to drive a + # compiled multi-slot coalesced-completion test on the host. + loop_match = re.search(r'for _ in 0\.\.([^\s{]+)\s*\{', try_fast) + assert loop_match is not None, 'try_fast_observe_render loop missing' + loop_bound_expr = loop_match.group(1).replace('crate::hw::t8140::queues::RENDER_SLOTS', 'RENDER_SLOTS') + + turn_order_ok = ( + ordered_ok( + turn, + 'let fast_epoch = self.preparations.try_enter().ok();', + 'let (pending, masks, compute_scan) = firmware.service_runtime_events_scan(deferred)?;', + 'fast_epoch.as_ref().is_some_and(|epoch| epoch.is_current())', + 'firmware.try_fast_observe_render(deferred)?', + 'if render_changed {\n self.note_changed();\n }', + 'deferred.finish();', + 'if fast_done {\n return Ok(());\n }', + 'self.preparations\n .wait_drained_until(', + 'firmware.drain_render_deferred(masks, deferred)?;', + 'self.observe_renders(deferred)?;', + 'firmware.queues.render_needs_rescan()', + ) + # Slow-path observe_renders() must no longer acquire extra pre- or post-loop state locks. + and observe_fn.count('self.state.lock()') == 1 + ) + + changed_waiters_ok = ( + 'changed: TrackedCondVar,' in mod_src + and 'if self.waiters.load(Ordering::SeqCst) != 0 {' in tracked_cv + and 'self.condvar.notify_all();' in tracked_cv + and 'self.waiters.fetch_add(1, Ordering::SeqCst);' in tracked_cv + and 'self.0.fetch_sub(1, Ordering::Release);' in tracked_cv + ) + + # Adapt Availability::wait() and advance() for host compilation to test the real Dekker protocol. + host_wait = avail_wait.replace('pub(crate) ', '') + host_wait = host_wait.replace('Result>', 'Result>>') + host_wait = host_wait.replace('fence::independent(&self.fences)?', 'Ok::<_, i32>(Arc::new(AtomicBool::new(false)))?') + host_wait = host_wait.replace('KBox::new(', 'HostBox::new(') + host_wait = host_wait.replace(',\n GFP_KERNEL,\n )?', ')?') + host_wait = host_wait.replace('Fence::from_fence(&fence)', 'fence') + host_wait = host_wait.replace('self.state.lock()', 'self.lock_state()') + + host_advance = avail_advance.replace('self.state.lock()', 'self.lock_state()') + host_advance = host_advance.replace('entry.fence.signal();', 'entry.fence.store(true, Ordering::Release);') + + return f''' +use std::sync::{{Arc, Mutex, MutexGuard, atomic::{{AtomicBool, AtomicU64, AtomicUsize, Ordering}}}}; + +type Result = std::result::Result; + +struct HostBox; +impl HostBox {{ + fn new(v: T) -> Result> {{ Ok(Box::new(v)) }} +}} + +struct Entry {{ + fence: Arc, + next: Option>, +}} + +struct State {{ + waiters: Option>, +}} + +struct Availability {{ + generation: AtomicU64, + has_waiters: AtomicBool, + lock_trips: AtomicUsize, + state: Mutex, +}} + +impl Availability {{ + fn new() -> Arc {{ + Arc::new(Self {{ + generation: AtomicU64::new(0), + has_waiters: AtomicBool::new(false), + lock_trips: AtomicUsize::new(0), + state: Mutex::new(State {{ waiters: None }}), + }}) + }} + fn lock_state(&self) -> MutexGuard<'_, State> {{ + self.lock_trips.fetch_add(1, Ordering::Relaxed); + self.state.lock().unwrap() + }} + fn observe(&self) -> u64 {{ self.generation.load(Ordering::Acquire) }} + fn has_waiters(&self) -> bool {{ self.has_waiters.load(Ordering::Acquire) }} + fn notify(&self) {{ self.advance(); }} + fn notify_own(&self, observed: u64) -> u64 {{ + if self.advance() == observed {{ observed.wrapping_add(1) }} else {{ observed }} + }} + + {host_wait} + + {host_advance} +}} + +fn test_availability_zero_waiter_and_dekker_race() {{ + let a = Availability::new(); + let g0 = a.observe(); + assert!(!a.has_waiters()); + assert_eq!(a.lock_trips.load(Ordering::Relaxed), 0); + + // Zero-waiter notify() advances generation without taking the mutex. + a.notify(); + assert_eq!(a.observe(), g0 + 1, "notify() must bump generation even with zero waiters"); + assert_eq!(a.lock_trips.load(Ordering::Relaxed), 0, "zero-waiter notify must skip state mutex"); + + // A waiter holding the stale observation must retry immediately instead of sleeping. + assert!(a.wait(g0).unwrap().is_none()); + + // notify_own() distinguishes our own bump from a concurrent bump. + let g1 = a.observe(); + assert_eq!(a.notify_own(g1), g1 + 1); + assert_eq!(a.notify_own(g1), g1); + + // Multi-threaded Dekker stress test: every registered waiter MUST eventually be signalled. + let stop = Arc::new(AtomicBool::new(false)); + let a_not = a.clone(); + let s_not = stop.clone(); + let notifier = std::thread::spawn(move || {{ + while !s_not.load(Ordering::Acquire) {{ + a_not.notify(); + std::hint::spin_loop(); + }} + a_not.notify(); + }}); + + for _ in 0..4000 {{ + let obs = a.observe(); + if let Some(fence) = a.wait(obs).unwrap() {{ + while !fence.load(Ordering::Acquire) {{ + std::thread::yield_now(); + }} + }} + }} + stop.store(true, Ordering::Release); + notifier.join().unwrap(); +}} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum FastRenderOutcome {{ + Fallback, + Idle, + Done, +}} + +const RENDER_SLOTS: usize = 8; + +fn run_fast_render_loop(ready: &mut Vec, deferred_cap: usize) -> (FastRenderOutcome, usize) {{ + let mut deferred_len = 0usize; + let mut retired_any = false; + for _ in 0..{loop_bound_expr} {{ + let Some(_slot) = ready.first().copied() else {{ + return (if retired_any {{ FastRenderOutcome::Done }} else {{ FastRenderOutcome::Idle }}, deferred_len); + }}; + if deferred_cap.saturating_sub(deferred_len) < 2 {{ + return (FastRenderOutcome::Fallback, deferred_len); + }} + ready.remove(0); + deferred_len += 1; + retired_any = true; + }} + if !ready.is_empty() {{ + return (FastRenderOutcome::Fallback, deferred_len); + }} + (if retired_any {{ FastRenderOutcome::Done }} else {{ FastRenderOutcome::Idle }}, deferred_len) +}} + +fn test_multi_slot_fast_render() {{ + // 0 ready slots -> Idle. + let mut none = vec![]; + assert_eq!(run_fast_render_loop(&mut none, 16), (FastRenderOutcome::Idle, 0)); + + // 2 coalesced ready render slots must both retire in ONE lock hold (Done, not Fallback). + let mut two = vec![1, 2]; + assert_eq!(run_fast_render_loop(&mut two, 16), (FastRenderOutcome::Done, 2)); + assert!(two.is_empty()); + + // Bounded by deferred room: shortage before 2nd slot returns Fallback after retiring 1st. + let mut tight = vec![1, 2]; + assert_eq!(run_fast_render_loop(&mut tight, 2), (FastRenderOutcome::Fallback, 1)); + assert_eq!(tight, vec![2]); + + // Bounded by RENDER_SLOTS: > RENDER_SLOTS ready items fall back cleanly after the cap. + let mut burst: Vec = (1..=RENDER_SLOTS + 1).collect(); + assert_eq!(run_fast_render_loop(&mut burst, 64), (FastRenderOutcome::Fallback, RENDER_SLOTS)); + assert_eq!(burst.len(), 1); +}} + +fn main() {{ + assert!({str(doorbell_order_ok).lower()}, "DirectHost::notify_render must drop m5_outer then render before port.notify()"); + assert!({str(fast_render_guards_ok).lower()}, "try_fast_observe_render must guard all non-steady states"); + assert!({str(turn_order_ok).lower()}, "runtime_event_turn must scope fast_epoch and fold observe_renders locks"); + assert!({str(changed_waiters_ok).lower()}, "Shared::note_changed must gate condvar wake on changed_waiters"); + test_availability_zero_waiter_and_dekker_race(); + test_multi_slot_fast_render(); + println!("PASS g17-m5-render-fast-done-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['hold-m5-outer-across-doorbell', + 'hold-render-lock-across-doorbell', + 'skip-pending-error-fallback', + 'single-slot-bailout', + 'skip-epoch-check', + 'unconditional-changed-notify', + 'skip-generation-bump']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-rfd-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 79281c819bab9f..322ec912ef14ee 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -261,6 +261,14 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-render-fast-done-tests.py': [([], PASS)] + + mutations('--mutation', ('hold-m5-outer-across-doorbell', + 'hold-render-lock-across-doorbell', + 'skip-pending-error-fallback', + 'single-slot-bailout', + 'skip-epoch-check', + 'unconditional-changed-notify', + 'skip-generation-bump'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 550b955538f4ab5f0f524c4652cdee8b0bd22cb1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 13:40:06 -0500 Subject: [PATCH 1056/1514] drm/asahi: g17: deduplicate sync-input chains and resolve M5 cross-QID sources directly Cross-queue compute handoffs previously hit three layers of host lock contention and fallback overhead: 1. asahi_g17_collect_fences() expanded every unsignaled node in a timeline dma_fence_chain without same-context coalescing (forcing reallocations and per-leaf global device-mutex scans inside Backend::input_sources()). 2. Backend::input_sources(), compute_readiness(), and sources_published() always took the global device mutex and linearly scanned compute queues to check whether a same-VM producer was published. 3. Backend::compute_direct() unconditionally rejected packets with converted input sources, forcing every cross-QID compute submission through compute_inline() under the global device mutex (and holding m5_outer across mailbox doorbell I/O in ComputeHost::notify()). Coalesce healthy unsignaled leaves sharing a non-zero fence context in collect_leaf() (keeping only the latest seqno via dma_fence_is_later() while preserving every failed leaf with status < 0), keeping the initial Rust collection capacity at 4, and hoist the fallback device mutex out of the leaf loop in Backend::input_sources(). Publish immutable cross-QID kick metadata (PublishedSource: epoch, publication order, KickDependency, and producer source_readers counter) onto fence::Submission once compute::Queue::publish() commits and rings its doorbell, invalidating it on retirement, error, replay, and cancel. Track the live epoch in published_epoch (AtomicU64, 0 = unpublished) so has_published_epoch() and empty clear_published() skip Submission::state, and store immutable vm_status outside Mutex so same_vm() is lock-free. Remove ReaderHint's blind spot so lock-free Hold::new() loans are always observed by shareable(), can_rearm(), and reset_for_owner(). Use the PublishedSource snapshot for lock-free checks in input_sources(), compute_readiness(), and sources_published(), allow M5 compute_direct() to resolve same-VM compute sources directly (skipping duplicate explicit barriers, self-reader Holds, and firmware_consumer marks when a source was already published on the consumer's own physical QID in the same epoch while still validating source_status() and recovery/epoch), mark firmware_consumer atomically on cross-QID producers, and drop m5_outer before port.notify() in ComputeHost::notify(). Add host C+Rust tests and mutation controls in g17-m5-cross-qid-direct-tests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/completion.rs | 8 + drivers/gpu/drm/asahi/g17/fence.rs | 90 ++- drivers/gpu/drm/asahi/g17/job.rs | 1 + drivers/gpu/drm/asahi/g17/queue/compute.rs | 17 + drivers/gpu/drm/asahi/g17/runtime.rs | 186 +++++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 62 +- drivers/gpu/drm/asahi/g17/sync_input.c | 23 +- drivers/gpu/drm/asahi/g17/sync_input.rs | 9 +- tools/asahi/g17-m5-cross-qid-direct-tests.py | 648 +++++++++++++++++++ tools/asahi/run-host-tests.py | 11 + 10 files changed, 1013 insertions(+), 42 deletions(-) create mode 100755 tools/asahi/g17-m5-cross-qid-direct-tests.py diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a4..2919fa28415477 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -512,6 +512,12 @@ impl Completion { pub(super) fn is_input_source(&self, source: &Arc) -> bool { self.output.output().member.is_source(source) } + pub(crate) fn note_source_published(&self, published: super::fence::PublishedSource) { + self.output.output().member.note_published(published); + } + pub(crate) fn clear_source_published(&self) { + self.output.output().member.clear_published(); + } pub(super) fn set_source_ready(&self, ready: Fence) { self.output.output().member.set_source_ready(ready); } @@ -609,6 +615,7 @@ impl Completion { }) .is_ok(); if accepted { + self.clear_source_published(); self.replay_timeout.store(true, Ordering::Release); // Callers replay only work proven not to have started; the new // publication runs from the beginning and reports its own result. @@ -627,6 +634,7 @@ impl Completion { pub(crate) fn has_firmware_consumer(&self) -> bool { self.firmware_consumer.load(Ordering::Acquire) + || self.output.output().member.has_firmware_consumer() } pub(crate) fn take_replay_timeout(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index df98a3410a50de..bcd9f6f305cf03 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -172,9 +172,20 @@ pub(super) unsafe fn exported_source_raw(raw: *mut bindings::dma_fence) -> Optio .cloned() } +/// Immutable cross-QID kick metadata published once a compute source is committed in firmware. +/// Consumers on the same VM read this without acquiring the global device mutex. +#[derive(Clone)] +pub(crate) struct PublishedSource { + pub(crate) epoch: u64, + pub(crate) published: u64, + pub(crate) dependency: super::fw::kick::KickDependency, + pub(crate) readers: Arc, +} + struct State { work: Option>, ready: Option, + published: Option, } // One Member per parsed command, plus the enqueue guard. Exported references @@ -186,6 +197,8 @@ kernel::static_assert!(crate::file::MAX_COMMANDS_PER_SUBMISSION < u8::MAX as u32 pub(crate) struct Submission { #[pin] state: Mutex, + /// Immutable VM status of this submission, stored outside `state` so `same_vm()` is lock-free. + vm_status: Option>, remaining: AtomicU8, error: AtomicI32, /// Live Member objects, plus the enqueue guard, independently of signalling. @@ -195,22 +208,35 @@ pub(crate) struct Submission { /// is queued, before its fence is signalled off-lock: a consumer published /// in between needs no wait on it. retired: AtomicBool, + /// Non-zero encoded recovery epoch (`epoch.wrapping_add(1)`) while `state.published` holds a + /// live `PublishedSource` snapshot, or `0` when unpublished. + published_epoch: AtomicU64, + /// Set atomically when a firmware kick depends on this source so replay/retirement + /// observes consumers without scanning producer queues under the device mutex. + firmware_consumer: AtomicBool, } impl Submission { + fn encode_epoch(epoch: u64) -> u64 { + epoch.wrapping_add(1) + } fn new(context: Arc, firmware_source: bool) -> Result> { let work = Arc::new(WorkStateLease::deferred(context)?, GFP_KERNEL)?; Self::with_work(Some(work), firmware_source) } fn with_work(work: Option>, firmware_source: bool) -> Result> { + let vm_status = work.as_ref().map(|work| work.status().clone()); Arc::pin_init( pin_init!(Self { - state <- new_mutex!(State { work, ready: None }, "G17 submission work state"), + state <- new_mutex!(State { work, ready: None, published: None }, "G17 submission work state"), + vm_status, remaining: AtomicU8::new(1), error: AtomicI32::new(0), owners: AtomicU8::new(1), firmware_source, retired: AtomicBool::new(false), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), }), GFP_KERNEL, ) @@ -225,15 +251,55 @@ impl Submission { Ok(complete) } pub(super) fn same_vm(&self, status: &Arc) -> bool { - self.state - .lock() - .work + self.vm_status .as_ref() - .is_some_and(|work| Arc::ptr_eq(work.status(), status)) + .is_some_and(|vm| Arc::ptr_eq(vm, status)) } pub(super) fn ready(&self) -> Option { self.state.lock().ready.clone() } + pub(super) fn set_published(&self, source: PublishedSource) { + if !self.firmware_source { + return; + } + let tag = Self::encode_epoch(source.epoch); + let mut state = self.state.lock(); + if state.work.is_some() + && self.error.load(Ordering::Acquire) == 0 + && !self.retired.load(Ordering::Acquire) + { + state.published = Some(source); + self.published_epoch.store(tag, Ordering::Release); + } + } + pub(super) fn clear_published(&self) { + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 { + return; + } + let old = self.state.lock().published.take(); + drop(old); + } + pub(super) fn published_source(&self, epoch: u64) -> Option { + if !self.has_published_epoch(epoch) { + return None; + } + let state = self.state.lock(); + state + .published + .as_ref() + .filter(|source| source.epoch == epoch) + .cloned() + } + pub(super) fn has_published_epoch(&self, epoch: u64) -> bool { + let tag = Self::encode_epoch(epoch); + self.firmware_source && tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + } + pub(super) fn note_firmware_consumer(&self) { + self.firmware_consumer.store(true, Ordering::Release); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.firmware_consumer.load(Ordering::Acquire) + } fn set_ready(&self, ready: Fence) { if !self.firmware_source { return; @@ -244,14 +310,16 @@ impl Submission { } } fn note_error(&self, error: Error) -> bool { + self.clear_published(); self.error .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire) .is_ok() } fn release_state(&self) { + self.published_epoch.store(0, Ordering::Release); let old = { let mut state = self.state.lock(); - (state.work.take(), state.ready.take()) + (state.work.take(), state.ready.take(), state.published.take()) }; drop(old); } @@ -346,8 +414,18 @@ impl Member { let source = self.aggregate.source(); if source.firmware_source { source.retired.store(true, Ordering::Release); + source.clear_published(); } } + pub(super) fn note_published(&self, published: PublishedSource) { + self.aggregate.source().set_published(published); + } + pub(super) fn clear_published(&self) { + self.aggregate.source().clear_published(); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.aggregate.source().has_firmware_consumer() + } pub(crate) fn complete(&self, result: Result) { if !self.complete.swap(true, Ordering::AcqRel) { self.aggregate diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index b6536c07b443f9..dbf766f4dabb8f 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -270,6 +270,7 @@ impl Packet { } pub(crate) fn request_cancel(&self) -> bool { self.cancelled.store(true, Ordering::Release); + self.completion.clear_source_published(); self.publication .compare_exchange(0, 3, Ordering::AcqRel, Ordering::Acquire) .is_ok() diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index e7e1b43eb6b2ac..adc94dca1de4d1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -3137,6 +3137,23 @@ impl Queue { first || notify_activation)?)?; } host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?; + if !packet.cancel_requested() { + if let Some(dependency) = + crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp) + { + packet.completion.note_source_published( + crate::g17::fence::PublishedSource { + epoch, + published, + dependency, + readers: self.source_readers.clone(), + }, + ); + if packet.cancel_requested() { + packet.completion.clear_source_published(); + } + } + } crate::g17::trace::publish(crate::g17::trace::COMPUTE, qid, ordinal, &packet); host.note_submission() })(); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 2297c1a79429f5..ea9a245e6ea2d9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -80,6 +80,8 @@ struct ComputeEntry { pub(super) struct ComputeCell { #[pin] queue: kernel::sync::Mutex>>, + /// Lock-free mirror of the installed queue's QID (`u8::MAX` when empty). + qid: core::sync::atomic::AtomicU8, } impl ComputeCell { @@ -87,11 +89,17 @@ impl ComputeCell { Arc::pin_init( pin_init!(Self { queue <- kernel::new_mutex!(None, "g17::ComputeCell::queue"), + qid: core::sync::atomic::AtomicU8::new(u8::MAX), }), GFP_KERNEL, ) } + pub(super) fn qid(&self) -> Option { + let qid = self.qid.load(Ordering::Acquire); + (qid != u8::MAX).then_some(qid) + } + /// The installed queue, locked; None once the registry gave it up. pub(super) fn lock(&self) -> Option> { QueueGuard::new(self.queue.lock()) @@ -148,10 +156,18 @@ impl ComputeSlot { } /// Gives the queue up to the caller, which drops it outside the cell lock. fn take(&mut self) -> Option> { - self.0.queue.lock().take() + let mut guard = self.0.queue.lock(); + let taken = guard.take(); + self.0.qid.store(u8::MAX, Ordering::Release); + taken } fn put(&mut self, queue: Option>) { - let old = core::mem::replace(&mut *self.0.queue.lock(), queue); + let qid = queue.as_ref().map_or(u8::MAX, |queue| queue.qid()); + let old = { + let mut guard = self.0.queue.lock(); + self.0.qid.store(qid, Ordering::Release); + core::mem::replace(&mut *guard, queue) + }; drop(old); } } @@ -1534,6 +1550,7 @@ struct ComputeHost<'a> { regs: &'a crate::regs::G17Resources, port: &'a super::port::Port, outer: Option>, + m5_outer: Option>>, /// M5: the shared compute ring's room check of this publication, by priority. outer_cursors: Option<(u8, [u32; 3])>, effort: &'a mut super::power::Effort, @@ -1588,7 +1605,14 @@ impl compute::Host for ComputeHost<'_> { // Every M5 pipe-2 doorbell (0x83) is noted in the firmware's submission history first, // as the render doorbell notes its pair. if self.init.is_m5() && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { - if let Err(error) = self.init.note_m5_submission_history(1) { + if let Some(guard) = self.m5_outer.as_mut() { + if let Err(error) = self.port.note_m5_submission_history_locked(guard, 1) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer = None; + } else if let Err(error) = self.init.note_m5_submission_history(1) { pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); } } @@ -1719,6 +1743,7 @@ impl super::Firmware { // the source's kick, and the firmware orders it. So is a G17P source of the consumer's // own execution context: one context needs no write-back between the two kicks. let m5 = self.init.is_m5(); + let consumer_qid = self.queues.compute(owner).map(|queue| queue.qid()); let mut waited: u128 = 0; for source in &sources.sources { if source.submission.source_status()? { continue; } @@ -1732,6 +1757,13 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; + if m5 && consumer_qid == Some(dependency.qid()) { + // Same physical QID in this epoch: the queue's implicit parent already strictly + // orders earlier kicks on this QID; drop the self-reader hold and skip adding a + // duplicate explicit barrier. + drop(hold); + continue; + } waited |= 1u128 << dependency.qid(); if m5 || same_execution { merged.insert(sequence, dependency)?; @@ -1798,7 +1830,7 @@ impl super::Firmware { // reservation; dropping it unused returns the work-ring slot. M5 compute // serializes the shared outer ring and host-port updates under `m5_outer` // (after the compute cell lock, matching direct M5 publishers). - let _m5_outer = self.init.is_m5().then(|| self.port.m5_outer_lock()); + let m5_outer = self.init.is_m5().then(|| self.port.m5_outer_lock()); let mut outer_cursors = None; let outer = if self.init.is_m5() { let priority = packet.context.policy().priority(); @@ -1816,6 +1848,7 @@ impl super::Firmware { regs: &self.bridge.regs, port: &self.port, outer, + m5_outer, outer_cursors, effort: &mut self.effort, qids: &mut queues.qids, @@ -2157,17 +2190,76 @@ impl Backend { } } + /// Resolves same-VM cross-QID M5 compute sources lock-free from each producer's + /// `PublishedSource` snapshot under a live preparation lease. Sources already published on + /// `target_qid` in `generation` are ordered by this queue's implicit parent, so they skip the + /// duplicate explicit barrier, `Hold`, and `firmware_consumer` mark while still checking + /// `source_status()` (error propagation) and epoch validity. Any unpublished, errored, + /// cancelled, or epoch-mismatched source returns `None` so the device-mutex path handles it. + fn resolve_direct_sources( + &self, + port: &super::port::Port, + generation: u64, + target_qid: u8, + sources: &super::sync_input::Sources, + ) -> Option<(super::dependency::Frontier, KVec, u64)> { + sources.check().ok()?; + let mut frontier = super::dependency::Frontier::new(); + let mut holds = KVec::new(); + let mut cross_qid_mask = 0u64; + for (idx, source) in sources.sources.iter().enumerate() { + if source.submission.source_status().ok()? { + continue; + } + let published = source.submission.published_source(generation)?; + if published.dependency.qid() == target_qid { + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + continue; + } + let hold = super::sync_input::Hold::new(&published.readers).ok()?; + // Re-validate after taking the binding loan so the producer cannot have retired, + // faulted, cancelled, or crossed an epoch before `readers` became non-zero. + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + frontier + .insert(published.published, published.dependency) + .ok()?; + holds.push(hold, GFP_KERNEL).ok()?; + cross_qid_mask |= 1u64 << idx; + } + Some((frontier, holds, cross_qid_mask)) + } + /// Steady-state publication into this owner's bound channel without the device mutex: only /// the channel's own lock and the port's small locks are taken, and nothing device-wide is - /// scanned. None leaves the packet untouched for the device-mutex path, which owns binding, - /// first installation, input sources, render prefixes, replay and recovery. + /// scanned. On M5, same-VM cross-QID compute sources whose producers have published their kick + /// metadata also resolve directly without the device mutex. None leaves the packet untouched + /// for the device-mutex path, which owns binding, first installation, non-M5 native-wait + /// sources, render prefixes, replay and recovery. fn compute_direct( &self, packet: &Arc, required: super::freelist::ComputeCapacity, deferred: &mut DeferredBatch, ) -> Option { - if packet.completion.sources().is_some() + let m5 = self.context.is_m5(); + let has_sources = packet.completion.sources().is_some(); + if (has_sources && !m5) || self.context.render_seen() || packet.cancel_requested() || packet.completion.status().get() != 0 @@ -2176,11 +2268,19 @@ impl Backend { return None; } let cell = self.direct.lock().clone()?; + let target_qid = cell.qid()?; let lease = self.shared.preparations.try_enter().ok()?; let port = self.shared.port(&lease)?; if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { return None; } + let generation = port.generation(); + let (direct_frontier, direct_holds, cross_qid_mask) = + if let Some(sources) = packet.completion.sources() { + self.resolve_direct_sources(port, generation, target_qid, sources)? + } else { + (super::dependency::Frontier::new(), KVec::new(), 0) + }; // Full effort is applied by the device-mutex path when it is not already. if !port.note_submission() { return None; @@ -2192,7 +2292,6 @@ impl Backend { Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } - let m5 = self.context.is_m5(); let priority = packet.context.policy().priority(); // Reuse the M5 outer claim already reserved during prepare_compute() when present and // matching priority, avoiding a redundant Port::m5_outer lock trip and unused-claim drop @@ -2221,6 +2320,7 @@ impl Backend { || queue.spared_pending() || !queue.pool_fits(required) || queue.pending_switch_from().is_some() + || queue.qid() != target_qid || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) || !lease.is_current() { @@ -2237,10 +2337,33 @@ impl Backend { m5_outer: m5_outer.as_mut(), m5_outer_guard: None, m5, - generation: port.generation(), + generation, }; - Some(queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event))) + Some(queue.publish( + packet.clone(), + direct_frontier.as_slice(), + &mut host, + &mut |event| deferred.push(event), + )) })(); + if packet.is_published() { + if let Some(sources) = packet.completion.sources() { + if cross_qid_mask != 0 { + for (idx, source) in sources.sources.iter().enumerate() { + if cross_qid_mask & (1u64 << idx) != 0 { + source.submission.note_firmware_consumer(); + } + } + sources.set_holds(direct_holds); + } else { + drop(direct_holds); + } + super::sync_input::note_published(); + super::sync_input::note_native(0); + } + } else { + drop(direct_holds); + } let outcome = match result { None => None, Some(Err(error)) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => { @@ -2399,8 +2522,17 @@ impl Backend { Err(_) => return Readiness::Ready, Ok(_) => {} } + let sources_checked = if packet.completion.sources().is_some() { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => true, + } + } else { + false + }; // The steady state: this owner's channel is bound and installed. - if packet.completion.sources().is_none() { + if !sources_checked || self.context.is_m5() { if let Some(cell) = self.direct.lock().clone() { let bound = cell.lock().and_then(|mut queue| { let bound = queue.installed() @@ -2426,10 +2558,12 @@ impl Backend { } } } - match self.sources_published(packet) { - Ok(false) => return Readiness::Progress, - Err(_) => return Readiness::Ready, - Ok(true) => {} + if !sources_checked { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => {} + } } let lease = match self.shared.preparations.try_enter() { Ok(lease) => lease, @@ -2602,6 +2736,28 @@ impl Backend { fn sources_published(&self, packet: &super::job::Packet) -> Result { let Some(sources) = packet.completion.sources() else { return Ok(true); }; sources.check()?; + if let Ok(lease) = self.shared.preparations.try_enter() { + if let Some(port) = self.shared.port(&lease) { + if !self.shared.crashed.load(Ordering::Acquire) + && port.recovery_state().ok() == Some(0) + { + let generation = port.generation(); + let mut all_fast = true; + for source in &sources.sources { + if source.submission.source_status()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + all_fast = false; + break; + } + } + if all_fast { + return Ok(true); + } + } + } + } let state = self.shared.state.lock(); let firmware = state.as_deref().ok_or(ENODEV)?; if firmware.recovery.pending() diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 35ddab8134ff50..7cf47757a9550e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -144,6 +144,15 @@ impl job::Backend for Backend { let mut heads = KVec::new(); let mut sources: KVec = KVec::new(); let mut publication_waits = KVec::new(); + let mut unchecked: KVec = KVec::new(); + let lease = self.shared.preparations.try_enter().ok(); + let port_epoch = lease.as_ref().and_then(|lease| { + let port = self.shared.port(lease)?; + if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { + return None; + } + Some(port.generation()) + }); for input in inputs.iter().filter_map(|input| input.fence.as_ref()) { let status = job::fence_status(input); if status > 0 { continue; } @@ -160,29 +169,52 @@ impl job::Backend for Backend { continue; } if sources.len() == crate::g17::fw::kick::KICK_BARRIERS_MAX { return None; } - let published = { - let state = self.shared.state.lock(); - let firmware = state.as_deref()?; - if self.shared.crashed.load(Ordering::Acquire) || firmware.recovery.pending() - || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 - { return None; } - firmware.queues.compute.iter().flatten() - .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.has_input_source(&submission, self.context.status(), - firmware.recovery.generation())) - }; + let published_fast = + port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); + let idx = sources.len(); + sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; + if !published_fast { + unchecked.push(idx, GFP_KERNEL).ok()?; + } + } + heads.push(input.clone(), GFP_KERNEL).ok()?; + } + drop(lease); + if sources.is_empty() { return None; } + if !unchecked.is_empty() { + // Hoist the device mutex outside the leaf loop when any source was not already + // confirmed via the lock-free `PublishedSource` snapshot. + let state = self.shared.state.lock(); + let firmware = state.as_deref()?; + if self.shared.crashed.load(Ordering::Acquire) + || firmware.recovery.pending() + || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 + { + return None; + } + let generation = firmware.recovery.generation(); + for idx in unchecked { + let submission = &sources[idx].submission; + let published = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| { + queue.has_input_source(submission, self.context.status(), generation) + }); if !published { - if submission.source_status().ok()? { continue; } + if submission.source_status().ok()? { + continue; + } // The existing scheduler fence becomes ready after actual // publication, not GPU completion. No binding loan or // consumer hardware capacity is acquired while waiting. publication_waits.push(submission.ready()?, GFP_KERNEL).ok()?; } - sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; } - heads.push(input.clone(), GFP_KERNEL).ok()?; } - if sources.is_empty() { return None; } sync_input::Sources::new(heads, sources, publication_waits).ok() } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c87965..858e97066134d3 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -10,10 +10,31 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, size_t *count) { + int status = dma_fence_get_status(leaf); + + /* + * Coalesce healthy unsignaled leaves sharing a fence context (such as + * multiple points of one timeline chain), keeping only the latest seqno. + * Failed leaves (status < 0) are never coalesced so errors are preserved. + */ + if (status == 0 && leaf->context != 0) { + size_t i; + + for (i = 0; i < *count; ++i) { + if (out[i].status != 0 || + out[i].fence->context != leaf->context) + continue; + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f214..612bd7de109522 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -76,7 +76,7 @@ pub(super) struct Source { /// processor stop until the last consumer releases its binding loan. pub(super) struct Hold(Arc); impl Hold { - fn new(readers: &Arc) -> Result { + pub(super) fn new(readers: &Arc) -> Result { readers.fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| count.checked_add(1)).map_err(|_| EOVERFLOW)?; Ok(Self(readers.clone())) @@ -86,9 +86,8 @@ impl Drop for Hold { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::AcqRel); } } -/// A new owner starts with no loans. Acquiring a loan requires exclusive access -/// and arms the hint; eligibility queries stay read-only. A validated owner -/// transition can clear the hint after all independent loans have been released. +/// Checks a physical queue's independent source-reader counter directly so lock-free +/// direct-path loans (`Hold::new`) are always observed by ownership, rearm, and share checks. #[repr(transparent)] pub(super) struct ReaderHint { possible: bool, @@ -103,7 +102,7 @@ impl ReaderHint { Ok(hold) } pub(super) fn has_readers(&self, count: &AtomicU32) -> bool { - self.possible && count.load(Ordering::Acquire) != 0 + count.load(Ordering::Acquire) != 0 } pub(super) fn reset_for_owner(&mut self, count: &AtomicU32) -> Result { if self.has_readers(count) { return Err(EBUSY); } diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py new file mode 100755 index 00000000000000..e175d8cdfe702f --- /dev/null +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for sync-input chain deduplication and lock-free M5 cross-QID compute publication. + +Tests both the real C `collect_leaf()` extracted from +`drivers/gpu/drm/asahi/g17/sync_input.c` and the real Rust `Hold`, +`ReaderHint`, and `resolve_direct_sources()` logic extracted from +`sync_input.rs` and `runtime.rs`: +1. Timeline chain deduplication (C): 8 unsignaled same-context leaves + collapse to the single latest seqno with zero refcount leaks; distinct + contexts stay distinct; failed earlier leaves (`status < 0`) are never + coalesced or dropped. +2. Lock-free `compute_direct()` cross-QID resolution (Rust): + - Resolves `PublishedSource` into a `Frontier` `KickDependency`, takes + `Hold::new(&readers)` which is immediately observed by + `ReaderHint::has_readers()` and blocks `reset_for_owner()` without + locking the producer queue, and marks `note_firmware_consumer()`. + - Safely falls back (`None`, zero leaked `Hold`s) on unpublished source, + epoch/generation mismatch, active recovery, cancelled/quarantined + source, and failed source fence; skips already-retired sources. +3. Structural verification of `runtime/backend.rs`, `runtime.rs`, + `queue/compute.rs`, `fence.rs`, `completion.rs`, and `job.rs`. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_c_harness(mutation=None): + c_src = (G17 / 'sync_input.c').read_text() + collect_leaf = item(c_src, 'static int collect_leaf(') + if mutation == 'no-chain-dedup': + collect_leaf = collect_leaf.replace( + 'if (status == 0 && leaf->context != 0) {', + 'if (0) {', + 1, + ) + elif mutation == 'coalesce-failed-leaf': + collect_leaf = collect_leaf.replace( + 'if (out[i].status != 0 ||\n\t\t\t out[i].fence->context != leaf->context)', + 'if (out[i].fence->context != leaf->context)', + 1, + ) + + return f''' +#include +#include +#include +#include +#include +#include + +struct dma_fence {{ + uint64_t context; + uint64_t seqno; + int status; + int refs; +}}; + +struct asahi_g17_fence_leaf {{ + struct dma_fence *fence; + int status; +}}; + +static struct dma_fence *dma_fence_get(struct dma_fence *f) +{{ + f->refs++; + return f; +}} + +static void dma_fence_put(struct dma_fence *f) +{{ + assert(f->refs > 0); + f->refs--; +}} + +static int dma_fence_get_status(struct dma_fence *f) +{{ + return f->status; +}} + +static bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{{ + assert(f1->context == f2->context); + return (int64_t)(f1->seqno - f2->seqno) > 0; +}} + +{collect_leaf} + +static void release_all(struct asahi_g17_fence_leaf *out, size_t count) +{{ + for (size_t i = 0; i < count; ++i) + dma_fence_put(out[i].fence); +}} + +int main(void) +{{ + /* 1. 8 unsignaled same-context timeline leaves (out of order) -> 1 newest leaf. */ + struct dma_fence chain[8]; + uint64_t order[8] = {{3, 7, 1, 8, 5, 2, 6, 4}}; + for (int i = 0; i < 8; ++i) {{ + chain[i].context = 10; + chain[i].seqno = order[i]; + chain[i].status = 0; + chain[i].refs = 1; + }} + struct asahi_g17_fence_leaf out[16]; + size_t count = 0; + for (int i = 0; i < 8; ++i) {{ + assert(collect_leaf(&chain[i], out, 16, &count) == 0); + }} + assert(count == 1); + assert(out[0].fence->context == 10); + assert(out[0].fence->seqno == 8); + assert(out[0].status == 0); + release_all(out, count); + for (int i = 0; i < 8; ++i) + assert(chain[i].refs == 1); + + /* 2. Failed earlier leaf + healthy later unsignaled leaf on same context -> BOTH kept. */ + struct dma_fence failed = {{ .context = 10, .seqno = 2, .status = -EIO, .refs = 1 }}; + struct dma_fence healthy = {{ .context = 10, .seqno = 9, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&failed, out, 16, &count) == 0); + assert(collect_leaf(&healthy, out, 16, &count) == 0); + assert(count == 2); + assert(out[0].status == -EIO && out[0].fence->seqno == 2); + assert(out[1].status == 0 && out[1].fence->seqno == 9); + release_all(out, count); + assert(failed.refs == 1 && healthy.refs == 1); + + /* 3. Two distinct contexts coalesce independently to 1 newest leaf each. */ + struct dma_fence q0[3] = {{ + {{ .context = 11, .seqno = 1, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 4, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 2, .status = 0, .refs = 1 }}, + }}; + struct dma_fence q1[2] = {{ + {{ .context = 22, .seqno = 10, .status = 0, .refs = 1 }}, + {{ .context = 22, .seqno = 12, .status = 0, .refs = 1 }}, + }}; + count = 0; + for (int i = 0; i < 3; ++i) + assert(collect_leaf(&q0[i], out, 16, &count) == 0); + for (int i = 0; i < 2; ++i) + assert(collect_leaf(&q1[i], out, 16, &count) == 0); + assert(count == 2); + assert(out[0].fence->context == 11 && out[0].fence->seqno == 4); + assert(out[1].fence->context == 22 && out[1].fence->seqno == 12); + release_all(out, count); + + /* 4. Context 0 leaves are never coalesced. */ + struct dma_fence z0 = {{ .context = 0, .seqno = 1, .status = 0, .refs = 1 }}; + struct dma_fence z1 = {{ .context = 0, .seqno = 2, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&z0, out, 16, &count) == 0); + assert(collect_leaf(&z1, out, 16, &count) == 0); + assert(count == 2); + release_all(out, count); + return 0; +}} +''' + + +def build_rust_harness(mutation=None): + sync_rs = (G17 / 'sync_input.rs').read_text() + backend_rs = (G17 / 'runtime/backend.rs').read_text() + runtime_rs = (G17 / 'runtime.rs').read_text() + compute_rs = (G17 / 'queue/compute.rs').read_text() + completion_rs = (G17 / 'completion.rs').read_text() + fence_rs = (G17 / 'fence.rs').read_text() + job_rs = (G17 / 'job.rs').read_text() + + hold_struct = 'pub struct Hold(Arc);' + hold_impl = item(sync_rs, 'impl Hold').replace('pub(super) ', 'pub ') + hold_drop = item(sync_rs, 'impl Drop for Hold') + hint_struct = item(sync_rs, 'pub(super) struct ReaderHint').replace('pub(super) ', 'pub ') + hint_impl = item(sync_rs, 'impl ReaderHint').replace('pub(super) ', 'pub ') + resolve_fn = item(runtime_rs, 'fn resolve_direct_sources(') + input_sources_fn = item(backend_rs, 'fn input_sources(') + compute_direct_fn = item(runtime_rs, 'fn compute_direct(') + sources_pub_fn = item(runtime_rs, 'fn sources_published(') + compute_host_impl = item(runtime_rs, 'impl compute::Host for ComputeHost<') + begin_replay_fn = item(completion_rs, 'pub(crate) fn begin_replay(') + submission_impl = item(fence_rs, 'impl Submission') + note_error_fn = item(submission_impl, 'fn note_error(') + same_vm_fn = item(submission_impl, 'pub(super) fn same_vm(') + has_pub_epoch_fn = item(submission_impl, 'pub(super) fn has_published_epoch(') + clear_pub_fn = item(submission_impl, 'pub(super) fn clear_published(') + cancel_fn = item(job_rs, 'pub(crate) fn request_cancel(') + + if mutation == 'hint-blind-spot': + hint_impl = hint_impl.replace( + 'count.load(Ordering::Acquire) != 0', + 'self.possible && count.load(Ordering::Acquire) != 0', + 1, + ) + elif mutation == 'skip-epoch-check': + resolve_fn = resolve_fn.replace( + 'source.submission.published_source(generation)?', + 'source.submission.published_source_unchecked()?', + 1, + ) + resolve_fn = resolve_fn.replace( + 'if !source.submission.has_published_epoch(generation) {\n return None;\n }', + '', + 2, + ) + elif mutation == 'skip-recovery-recheck': + resolve_fn = resolve_fn.replace( + 'if port.recovery_state().ok()? != 0 || port.generation() != generation {\n return None;\n }', + '', + 2, + ) + elif mutation == 'lock-per-leaf': + input_sources_fn = input_sources_fn.replace( + 'let published_fast =', + 'let _ = self.shared.state.lock(); let published_fast =', + 1, + ) + elif mutation == 'hold-m5-outer-compute-host': + compute_host_impl = compute_host_impl.replace( + 'self.m5_outer = None;', + '', + 1, + ) + elif mutation == 'same-qid-emits-barrier': + resolve_fn = resolve_fn.replace( + 'if published.dependency.qid() == target_qid {', + 'if false && published.dependency.qid() == target_qid {', + 1, + ) + elif mutation == 'lock-has-published-epoch': + has_pub_epoch_fn = has_pub_epoch_fn.replace( + 'self.published_epoch.load(Ordering::Acquire) == tag', + 'self.state.lock().published.as_ref().is_some_and(|s| s.epoch == epoch)', + 1, + ) + elif mutation == 'lock-same-vm': + same_vm_fn = same_vm_fn.replace( + 'self.vm_status', + 'self.state.lock().work', + 1, + ) + + # Structural checks on production sources. + collect_cap_ok = 'let mut capacity = 4;' in sync_rs + leaf_loop_start = input_sources_fn.index('for leaf in &leaves {') + unchecked_block_start = input_sources_fn.index('if !unchecked.is_empty() {') + leaf_loop = input_sources_fn[leaf_loop_start:unchecked_block_start] + input_sources_ok = ( + 'self.shared.state.lock()' not in leaf_loop + and ordered_ok( + input_sources_fn, + 'submission.has_published_epoch(epoch)', + 'if !unchecked.is_empty() {', + 'let state = self.shared.state.lock();', + 'for idx in unchecked {', + ) + ) + direct_sources_ok = ( + '(has_sources && !m5)' in compute_direct_fn + and ordered_ok( + compute_direct_fn, + 'let target_qid = cell.qid()?;', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'queue.qid() != target_qid', + 'queue.publish(', + 'direct_frontier.as_slice(),', + 'source.submission.note_firmware_consumer();', + 'sources.set_holds(direct_holds);', + 'drop(direct_holds);', + ) + ) + lockfree_submission_ok = ( + 'published_epoch: AtomicU64,' in fence_rs + and 'vm_status: Option>,' in fence_rs + and 'self.state.lock()' not in has_pub_epoch_fn + and 'self.published_epoch.load(Ordering::Acquire)' in has_pub_epoch_fn + and 'self.state.lock()' not in same_vm_fn + and 'self.vm_status' in same_vm_fn + and 'if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {' in clear_pub_fn + ) + sources_published_ok = ordered_ok( + sources_pub_fn, + 'source.submission.has_published_epoch(generation)', + 'let state = self.shared.state.lock();', + ) + compute_host_ok = ordered_ok( + compute_host_impl, + 'note_m5_submission_history_locked(guard, 1)', + 'self.m5_outer = None;', + 'self.port.notify(message)', + ) + publish_invalidation_ok = ( + ordered_ok( + compute_rs, + 'host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?;', + 'packet.completion.note_source_published(', + 'if packet.cancel_requested() {', + 'packet.completion.clear_source_published();', + ) + and 'self.clear_published();' in note_error_fn + and 'self.clear_source_published();' in begin_replay_fn + and 'self.completion.clear_source_published();' in cancel_fn + ) + + # Adapt resolve_direct_sources() for host compilation. + host_resolve = resolve_fn + host_resolve = host_resolve.replace('super::port::Port', 'Port') + host_resolve = host_resolve.replace('super::sync_input::Sources', 'Sources') + host_resolve = host_resolve.replace('super::dependency::Frontier', 'Frontier') + host_resolve = host_resolve.replace('super::sync_input::Hold', 'Hold') + host_resolve = host_resolve.replace('KVec', 'Vec') + host_resolve = host_resolve.replace('KVec::new()', 'Vec::new()') + host_resolve = host_resolve.replace('holds.push(hold, GFP_KERNEL).ok()?;', 'holds.push(hold);') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}}}}; + +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +const PRODUCER_FAILED: i32 = -5; +type Result = std::result::Result; + +{hold_struct} +{hold_impl} +{hold_drop} + +{hint_struct} +{hint_impl} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct KickDependency {{ + qid: u8, + kick: u64, +}} +impl KickDependency {{ + fn qid(self) -> u8 {{ self.qid }} +}} + +#[derive(Clone)] +struct PublishedSource {{ + epoch: u64, + published: u64, + dependency: KickDependency, + readers: Arc, +}} + +struct Frontier {{ + items: Vec<(u64, KickDependency)>, +}} +impl Frontier {{ + fn new() -> Self {{ Self {{ items: Vec::new() }} }} + fn insert(&mut self, seq: u64, dep: KickDependency) -> Result {{ + if let Some(old) = self.items.iter_mut().find(|(_, d)| d.qid == dep.qid) {{ + if seq > old.0 {{ *old = (seq, dep); }} + }} else {{ + self.items.push((seq, dep)); + }} + Ok(()) + }} +}} + +struct Submission {{ + retired: AtomicBool, + error: AtomicI32, + published_epoch: AtomicU64, + firmware_consumer: AtomicBool, + state_locks: AtomicU32, + published: Mutex>, +}} + +impl Submission {{ + fn encode_epoch(epoch: u64) -> u64 {{ epoch.wrapping_add(1) }} + fn new() -> Arc {{ + Arc::new(Self {{ + retired: AtomicBool::new(false), + error: AtomicI32::new(0), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), + state_locks: AtomicU32::new(0), + published: Mutex::new(None), + }}) + }} + fn set_published(&self, src: PublishedSource) {{ + let tag = Self::encode_epoch(src.epoch); + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = Some(src); + self.published_epoch.store(tag, Ordering::Release); + }} + fn clear_published(&self) {{ + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {{ + return; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = None; + }} + fn source_status(&self) -> Result {{ + if self.error.load(Ordering::Acquire) != 0 {{ + return Err(PRODUCER_FAILED); + }} + Ok(self.retired.load(Ordering::Acquire)) + }} + fn published_source(&self, epoch: u64) -> Option {{ + if !self.has_published_epoch(epoch) {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().as_ref().filter(|s| s.epoch == epoch).cloned() + }} + #[allow(dead_code)] + fn published_source_unchecked(&self) -> Option {{ + if self.published_epoch.load(Ordering::Acquire) == 0 {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().clone() + }} + fn has_published_epoch(&self, epoch: u64) -> bool {{ + let tag = Self::encode_epoch(epoch); + tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + }} + fn note_firmware_consumer(&self) {{ + self.firmware_consumer.store(true, Ordering::Release); + }} +}} + +struct Source {{ submission: Arc }} +struct Sources {{ sources: Vec }} +impl Sources {{ + fn check(&self) -> Result {{ + for s in &self.sources {{ s.submission.source_status()?; }} + Ok(()) + }} +}} + +struct Port {{ + gen: AtomicU64, + rec: AtomicU32, + flip_rec_on_query: AtomicBool, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.load(Ordering::Acquire) }} + fn recovery_state(&self) -> Result {{ + if self.flip_rec_on_query.swap(false, Ordering::AcqRel) {{ + self.rec.store(1, Ordering::Release); + }} + Ok(self.rec.load(Ordering::Acquire)) + }} +}} + +struct Backend; +impl Backend {{ + {host_resolve} +}} + +fn main() {{ + assert!({str(collect_cap_ok).lower()}, "sync_input::collect must start with capacity 4"); + assert!({str(input_sources_ok).lower()}, "input_sources must check PublishedSource lock-free and hoist state.lock outside leaf loop"); + assert!({str(direct_sources_ok).lower()}, "compute_direct must resolve M5 cross-QID sources lock-free and set holds + firmware_consumer"); + assert!({str(lockfree_submission_ok).lower()}, "Submission::has_published_epoch, same_vm, and empty clear_published must be lock-free"); + assert!({str(sources_published_ok).lower()}, "sources_published must check PublishedSource lock-free before state.lock"); + assert!({str(compute_host_ok).lower()}, "ComputeHost::notify must drop m5_outer before port.notify"); + assert!({str(publish_invalidation_ok).lower()}, "compute::Queue must publish after notify and invalidate on quarantine/replay/cancel"); + + let backend = Backend; + let port = Port {{ + gen: AtomicU64::new(7), + rec: AtomicU32::new(0), + flip_rec_on_query: AtomicBool::new(false), + }}; + let readers = Arc::new(AtomicU32::new(0)); + let mut hint = ReaderHint::new(); + + // 1. Happy path: published cross-QID source (qid 5 -> target_qid 9) resolves lock-free, + // Hold blocks ReaderHint::reset_for_owner even though ReaderHint::hold(&mut self) was never called. + let sub = Submission::new(); + // clear_published() on unpublished submission must take 0 state locks. + sub.clear_published(); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), 0); + sub.set_published(PublishedSource {{ + epoch: 7, + published: 42, + dependency: KickDependency {{ qid: 5, kick: 100 }}, + readers: readers.clone(), + }}); + let locks_before = sub.state_locks.load(Ordering::Relaxed); + assert!(sub.has_published_epoch(7)); + assert!(!sub.has_published_epoch(8)); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), locks_before, "has_published_epoch must be lock-free"); + let sources = Sources {{ sources: vec![Source {{ submission: sub.clone() }}] }}; + let (frontier, holds, mask) = backend.resolve_direct_sources(&port, 7, 9, &sources).unwrap(); + assert_eq!(frontier.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); + assert_eq!(holds.len(), 1); + assert_eq!(mask, 1); + assert_eq!(readers.load(Ordering::Acquire), 1); + assert!(hint.has_readers(&readers), "lock-free Hold::new must be visible to ReaderHint::has_readers"); + assert_eq!(hint.reset_for_owner(&readers), Err(EBUSY), "lock-free Hold must block owner reset"); + sub.note_firmware_consumer(); + assert!(sub.firmware_consumer.load(Ordering::Acquire)); + drop(holds); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!hint.has_readers(&readers)); + assert_eq!(hint.reset_for_owner(&readers), Ok(())); + + // 1b. Same-QID source (qid 5 -> target_qid 5): skipped cleanly (empty frontier, 0 holds, + // 0 readers, mask == 0) because the implicit parent already orders same-QID kicks. + let same_sub = Submission::new(); + same_sub.set_published(PublishedSource {{ + epoch: 7, + published: 43, + dependency: KickDependency {{ qid: 5, kick: 101 }}, + readers: readers.clone(), + }}); + let same_sources = Sources {{ sources: vec![Source {{ submission: same_sub.clone() }}] }}; + let (f_same, h_same, m_same) = backend.resolve_direct_sources(&port, 7, 5, &same_sources).unwrap(); + assert!(f_same.items.is_empty(), "same-QID source must not emit a duplicate explicit barrier"); + assert!(h_same.is_empty(), "same-QID source must not take a self-reader Hold"); + assert_eq!(m_same, 0, "same-QID source must not set cross_qid_mask"); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!same_sub.firmware_consumer.load(Ordering::Acquire)); + + // 1c. Same-QID failed producer MUST still return None so error propagates! + same_sub.error.store(EIO, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 5, &same_sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 2. Unpublished source -> clean None fallback. + let unpub = Submission::new(); + let s_unpub = Sources {{ sources: vec![Source {{ submission: unpub }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_unpub).is_none()); + + // 3. Epoch/generation mismatch (port advanced to epoch 8 while source stays at epoch 7) + // -> clean None fallback, zero leaked Hold. + port.gen.store(8, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 8, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.gen.store(7, Ordering::Release); + + // 4. Recovery starts concurrently right after Hold -> clean None fallback, zero leaked Hold. + port.flip_rec_on_query.store(true, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.rec.store(0, Ordering::Release); + + // 5. Cancelled/quarantined source (clear_published) -> clean None fallback. + let cancelled = Submission::new(); + cancelled.set_published(PublishedSource {{ + epoch: 7, + published: 44, + dependency: KickDependency {{ qid: 5, kick: 102 }}, + readers: readers.clone(), + }}); + cancelled.clear_published(); + let s_can = Sources {{ sources: vec![Source {{ submission: cancelled }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_can).is_none()); + + // 6. Failed producer -> clean None fallback (so slow path propagates PRODUCER_FAILED). + let failed = Submission::new(); + failed.set_published(PublishedSource {{ + epoch: 7, + published: 45, + dependency: KickDependency {{ qid: 5, kick: 103 }}, + readers: readers.clone(), + }}); + failed.error.store(EIO, Ordering::Release); + let s_fail = Sources {{ sources: vec![Source {{ submission: failed }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_fail).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 7. Already-retired source -> skipped cleanly with empty frontier and 0 holds. + let retired = Submission::new(); + retired.retired.store(true, Ordering::Release); + let s_ret = Sources {{ sources: vec![Source {{ submission: retired }}] }}; + let (f_ret, h_ret, m_ret) = backend.resolve_direct_sources(&port, 7, 9, &s_ret).unwrap(); + assert!(f_ret.items.is_empty()); + assert!(h_ret.is_empty()); + assert_eq!(m_ret, 0); + + println!("PASS g17-m5-cross-qid-direct-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm']) + args = parser.parse_args() + cc = os.environ.get('HOSTCC', 'cc') + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-xqid-') as td: + c_file = Path(td) / 'c_test.c' + c_exe = Path(td) / 'c_test' + c_file.write_text(build_c_harness(args.mutation)) + subprocess.run([cc, '-O2', '-Wall', '-Wextra', '-Werror', '-o', str(c_exe), str(c_file)], check=True) + res_c = subprocess.run([str(c_exe)]) + if res_c.returncode != 0: + sys.exit(res_c.returncode) + + rs_file = Path(td) / 'rs_test.rs' + rs_exe = Path(td) / 'rs_test' + rs_file.write_text(build_rust_harness(args.mutation)) + subprocess.run([rustc, '-O', '-o', str(rs_exe), str(rs_file)], check=True) + res_rs = subprocess.run([str(rs_exe)]) + sys.exit(res_rs.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 79281c819bab9f..7c51f27236a39f 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -261,6 +261,17 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-cross-qid-direct-tests.py': [([], PASS)] + + mutations('--mutation', ('no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 7bb65ce97e1d0fe0c52303d63ae98c8372e772e9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 14:59:05 -0500 Subject: [PATCH 1057/1514] drm/asahi: g17: fan M5 Pro compute out to sibling channels for sustained heavy kicks On M5 Pro one physical firmware compute QID per logical compute queue serializes its kicks: each QID owns a single preemption, operand, usage, status and stamp state, so a kick holds for its parent on that QID. Kicks that each leave the GPU partly idle then run one at a time. macOS runs one M5 Pro command queue on up to three firmware compute queues of the same context, created on demand and sharing one completion ordinal, as its own kicks show when run under aura. Describe that as a property of the board: Board::compute_channels() is the number of firmware compute queues of one context over which a single command queue's independent kicks may run, 3 for the J714 and 1 for the J716C, J775D and J813, whose macOS drivers have not been seen to spread a command queue. multi_channel() and pairs::select_board() read that count alone rather than the board's encoding forms, and a const assertion keeps every board between 1 and COMPUTE_CHANNELS_MAX, the size of the per-owner channel arrays and of the compute waits a render kick carries. Let an owner on such a board hold up to that many physical compute channels sharing one execution context, QoS slot, scheduler page and work-state table, and fan out onto them only the work that gains from overlap: - A command runs on, or brings up, a sibling channel only when it is independent (no in-queue barrier), has no cross-queue input sources, the owner's primary channel runs sustained heavy work and at least two kicks of the owner are already in flight. The work is sustained heavy when the primary's last two retired kicks each ran at least 100 us between the start and end timestamps of their exact firmware execution records (pairs::heavy_run(), pairs::sustained()). One QID streams short kicks back to back faster (about 11 us per kick) than three QIDs do (about 16.4 us: each sibling kick pays about 5 us of firmware arbitration), so short kicks stay on the primary ring; from 100 us that cost is within 5% of the kick. Recordless retirements and releases of held descriptors never count, and the run restarts for every owner. - A kick queued behind one in flight on the same ring starts the moment its predecessor ends, while the host needs 60 to 100 us to turn that completion into the next submission. Two overlapped kicks that each fill the shader cores share them and end together; both rings then wait for the host, and every pair of kicks pays that turnaround (a processor-sharing model predicts 300 to 319 us per kick against 270 us serial; 286 to 302 us were measured for an owner keeping two such kicks in flight). A kick that leaves the GPU partly idle gains about 10% from the same overlap, but the kernel cannot tell the two apart from a kick's metadata (same workgroup size, no threadgroup memory, similar register footprint; the grid lives in the CDM stream). So a kick leaves the primary ring only with SIBLING_MIN_IN_FLIGHT (two) kicks already in flight (pairs::overlaps(), on the direct path, in channel selection and in sibling admission): the primary then keeps one queued behind the overlap, a sibling only adds overlap and never exposes the turnaround, and an owner keeping at most two kicks in flight runs exactly as on one ring. Mesa applies the same rule to the sibling queues it opens itself. - A command with input sources always takes the primary channel, on the direct path (whose lock-free cross-QID source resolution, binding loans and hold hand-off are unchanged) and on the device-mutex path, and never binds a sibling, so a semaphore hop between queues stays on one ring per queue. - Backend::fans_out() checks the command before it asks for the primary's state, and compute_direct() reads that state from the primary ComputeCell's lock-free mirror (sustained), so short kicks and sourced commands neither lock a cell nor detour to the device-mutex path to add a sibling. - Each sibling channel owns a dedicated ComputePool mapped into the context VM; concurrent kicks take distinct 1-based ordinals and (predecessor_id << 32) | current_id object ids from one per-context atomic sequence (Context::next_compute_identity()), used as both submit_sequence and completion_ordinal. - ComputeCell mirrors (configuring, active_len, last_published, sustained) whenever a QueueGuard drops; compute_direct() routes to an idle primary without locking a sibling cell and scans the hints lock-free otherwise. - Siblings bind lazily when every bound channel is busy, from the source Registry::sibling_source() names, in the order a primary binding takes its channel: an idle reusable queue whose populated pool serves the owner's VM and fits, bound at once; a vacant reusable queue no other owner is re-arming, re-armed with fresh backing off the device mutex and bound as the sibling through the primary's own rearm_vacant(), rearm_compute() and bind_rearmed(); a fresh QID; and last an idle reusable queue whose pool still serves another VM, given back (give_back_foreign(), which rebind_compute() now shares) while no other pool release is in flight, so the next pool pass vacates it for a later attempt. Only reusable queues qualify: a queue with an owner or work, an open owner's idle channel, a queue another owner is re-arming and one whose scheduler or pool release is in flight are never taken, and an owner waiting for its first channel goes first. Once earlier clients had taken compute QIDs up to the fresh-QID ceiling, every idle queue was vacant or held a gone VM's pool, so admitting only same-VM pools and fresh QIDs never brought a sibling up again until the GPU slept. A miss backs off for SIBLING_HEADROOM_BACKOFF_NS. - Each QID keeps the completion-class implicit parent while its own earlier kick is active; dependent compute and render consumers wait on every channel of the owner. Siblings release and roll back before the primary, idle siblings drain before primary pool growth, and a ContextKill cookie and its acknowledgment cover every channel. GET_PARAMS reports the new DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL wherever a logical compute queue holds more than one channel (pairs::compute_channels_per_owner() > 1), so userspace that would open sibling queues of its own for the same overlap leaves it to the kernel instead of fanning out twice. Only the M5 Pro reports it: the other M5 boards describe one channel, and G17P never selects an M5 board. The feature takes bit 42, the next free bit: bit 40 is DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE and bit 41 is DRM_ASAHI_FEATURE_COMPUTE_ONLY. Mesa's Vulkan driver reads the bit and then leaves the sibling queues to the kernel (aurora-silicon/mesa#793). Host tests: tools/asahi/g17-m5-sibling-gate-tests.py compiles the gate, the in-flight threshold, the direct-path channel selection, the ComputeCell mirror and the registry's channel selection and sibling admission, with 17 mutation controls; g17-m5-sibling-rearm-tests.py runs the production reuse predicates, sibling sources, give-back, pool pass and re-arm for clients that come and go with no fresh QID left (14 controls, the old admission rule among them); g17-compute-multi-channel-feature-tests.py reads every production board's channel count and checks where the feature is reported, that the decision ignores the encoding forms and that its bit is unique (9 controls); g17-compute-owed-stamp-tests.py runs the real retirement pass against the heavy-kick run (2 more controls); g17-m5-sibling-compute-tests.py covers identities, dedicated pools, routing, release, rollback, growth and exit ordering (8 controls). Link: https://github.com/aurora-silicon/mesa/pull/793 Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 4 + drivers/gpu/drm/asahi/g17/context.rs | 40 +- drivers/gpu/drm/asahi/g17/fw/m5/compute.rs | 23 +- drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 28 + drivers/gpu/drm/asahi/g17/mod.rs | 14 +- drivers/gpu/drm/asahi/g17/pairs.rs | 76 +- drivers/gpu/drm/asahi/g17/queue/compute.rs | 270 +++- drivers/gpu/drm/asahi/g17/queue/render.rs | 38 +- drivers/gpu/drm/asahi/g17/runtime.rs | 1234 +++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 64 +- .../drm/asahi/g17/runtime/compute_control.rs | 12 +- .../gpu/drm/asahi/g17/runtime/compute_exit.rs | 30 +- .../drm/asahi/g17/runtime/compute_replay.rs | 32 +- .../drm/asahi/g17/runtime/render/submit.rs | 25 +- include/uapi/drm/asahi_drm.h | 9 + tools/asahi/g17-capacity-fault-tests.py | 18 +- tools/asahi/g17-compute-deadline-tests.py | 20 +- .../g17-compute-growth-deadline-tests.py | 4 + ...g17-compute-multi-channel-feature-tests.py | 243 ++++ tools/asahi/g17-compute-owed-stamp-tests.py | 92 +- tools/asahi/g17-growth-tests.py | 6 +- tools/asahi/g17-m5-cross-qid-direct-tests.py | 2 +- .../g17-m5-multiqueue-contention-tests.py | 2 +- tools/asahi/g17-m5-sibling-compute-tests.py | 660 +++++++++ tools/asahi/g17-m5-sibling-gate-tests.py | 527 +++++++ tools/asahi/g17-m5-sibling-rearm-tests.py | 646 +++++++++ tools/asahi/g17-pool-release-tests.py | 3 +- tools/asahi/run-host-tests.py | 26 +- 28 files changed, 3893 insertions(+), 255 deletions(-) create mode 100755 tools/asahi/g17-compute-multi-channel-feature-tests.py create mode 100755 tools/asahi/g17-m5-sibling-compute-tests.py create mode 100755 tools/asahi/g17-m5-sibling-gate-tests.py create mode 100755 tools/asahi/g17-m5-sibling-rearm-tests.py diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 08837155027662..aedad5c0bdeb70 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -106,6 +106,10 @@ pub(crate) const DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION: u32 = /// (`drm_asahi_queue_create::compute_timeout_ms`). pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT: u64 = uapi::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT as u64; +/// The kernel spreads one compute queue's independent commands over several firmware compute +/// queues itself. +pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 = + uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64; /// The tiling half waits only on the render and compute prefixes of the command's stage-prefix /// fields, its fragment half on the whole ones. #[allow(dead_code)] diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 84b519795da736..df8c3da1494f64 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -214,9 +214,12 @@ pub(crate) struct Context { /// A kill of this context was published, through a compute queue or on its render pairs' /// behalf. A context is killed at most once. kill_published: AtomicBool, - /// Advisory only: publication still checks the physical binding under the - /// device mutex. False skips an inline attempt known to need admission. - compute_binding_hint: AtomicBool, + /// Advisory count of bound compute channels: publication still checks the physical binding + /// under the device mutex. Zero skips an inline attempt known to need admission. + compute_bindings: AtomicU32, + /// Shared monotonic compute completion ordinal / submit sequence across an M5 multi-channel + /// context's physical compute queues. + compute_ordinal: AtomicU32, /// Mixed-engine contexts keep the original inline publication path. render_seen: AtomicBool, qos: Arc, @@ -346,7 +349,8 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill_published: AtomicBool::new(false), - compute_binding_hint: AtomicBool::new(false), + compute_bindings: AtomicU32::new(0), + compute_ordinal: AtomicU32::new(0), render_seen: AtomicBool::new(false), qos, owner_pid, @@ -373,7 +377,11 @@ impl Context { } pub(crate) fn compute_binding_hint(&self) -> bool { self.render_seen.load(Ordering::Acquire) - || self.compute_binding_hint.load(Ordering::Relaxed) + || self.compute_bindings.load(Ordering::Relaxed) != 0 + } + /// Advisory count of physical compute channels currently bound to this context. + pub(crate) fn compute_binding_count(&self) -> u32 { + self.compute_bindings.load(Ordering::Acquire) } /// This logical queue has submitted render work, so its compute may have a render prefix. pub(crate) fn render_seen(&self) -> bool { @@ -385,7 +393,27 @@ impl Context { } } pub(crate) fn note_compute_binding(&self, owned: bool) { - self.compute_binding_hint.store(owned, Ordering::Relaxed); + if owned { + self.compute_bindings.fetch_add(1, Ordering::AcqRel); + } else { + let _ = self + .compute_bindings + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + Some(n.saturating_sub(1)) + }); + } + } + /// Atomically allocates the next 1-based shared compute ordinal and packed + /// `(predecessor_id << 32) | current_id` descriptor object_ids pair for a multi-channel + /// M5 context, so concurrent direct submissions across sibling QIDs never collide on + /// `submit_sequence`, `completion_ordinal`, or `object_ids`. + pub(crate) fn next_compute_identity(&self) -> (u32, u64) { + let prev = self.compute_ordinal.fetch_add(1, Ordering::AcqRel); + let next = prev.wrapping_add(1); + let predecessor_id = if prev == 0 { 1 } else { prev }; + let current_id = if next == 0 { 1 } else { next }; + let object_ids = (u64::from(predecessor_id) << 32) | u64::from(current_id); + (next, object_ids) } pub(crate) fn compute_timestamps(&self) -> &Arc { &self.compute_timestamps diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs index a2d7205dfe9afe..fd326e708f2dda 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs @@ -48,10 +48,9 @@ pub(crate) fn explicit_dependency(board: &Board) -> u8 { /// Dependency class of a compute kick's implicit parent (the previous kick of its queue) on /// `board`. With the counted forms ([`counted_forms`]) it is class 1, which holds the kick until /// its parent has completed. On boards whose explicit waits take the completion class -/// ([`Board::completion_inputs`]) a parent the host has already retired (`parent_retired`) takes -/// the pipelined class instead, as macOS's late-published M5 Pro kicks do: there is nothing left -/// to hold for. Otherwise it is the pipelined class, with which a kick may start while its parent -/// still runs. +/// ([`Board::completion_inputs`]), a parent the host has already retired (`parent_retired`) takes +/// the pipelined class instead: there is nothing left on that physical QID to hold for. +/// Otherwise it is the pipelined class, with which a kick may start while its parent still runs. pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { if !counted_forms(board) || (parent_retired && board.completion_inputs()) { COMPUTE_PIPELINED_DEPENDENCY @@ -60,6 +59,16 @@ pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { } } +/// Whether `board` spreads a logical compute queue across multiple physical compute channels +/// ([`Board::compute_channels`]) sharing one context, QoS slot, scheduler page, and work-state +/// table, each with its own dedicated compute pool. Each physical QID still holds a +/// completion-class implicit parent while its own prior kick is active, preventing two kicks +/// from overlapping on one QID's single preemption/operand/usage state; concurrency comes +/// strictly from independent kicks running across distinct sibling QIDs. +pub(crate) fn multi_channel(board: &Board) -> bool { + board.compute_channels() > 1 +} + /// Whether compute kicks on `board` count their completion ordinal and hold for their parent: /// with the G17D forms, on boards whose explicit waits take the completion class /// ([`Board::completion_inputs`]), as macOS encodes M5 Pro compute, and on the J813, whose @@ -465,6 +474,8 @@ pub(crate) struct DescriptorArgs { pub(crate) stamp_va: [u64; 2], pub(crate) stamp_value: u32, pub(crate) qid: u32, + /// Per-context compute channel index (0, 1, 2 for a multi-channel owner; 0 otherwise). + pub(crate) channel_index: u32, pub(crate) kick_timestamp: u64, pub(crate) completion_ordinal: u32, pub(crate) status_va: [u64; 2], @@ -503,7 +514,8 @@ pub(crate) struct Descriptor { stamp_va: [u64; 2], stamp_value: u32, qid: u32, - reserved_f58: u64, + channel_index: u32, + reserved_f5c: u32, kick_timestamp: u64, current_id: u64, completion_ordinal: u32, @@ -574,6 +586,7 @@ impl Descriptor { self.stamp_va = args.stamp_va; self.stamp_value = args.stamp_value; self.qid = args.qid; + self.channel_index = args.channel_index; self.kick_timestamp = args.kick_timestamp; self.current_id = args.registers.object_ids as u32 as u64; self.completion_ordinal = args.completion_ordinal; diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index d89a2c5756b228..b6f054d9328f68 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -2441,6 +2441,9 @@ pub(crate) struct Board { /// Whether firmware accepts tiling kicks without an entry signal and retained /// render pairs kicked through the host port alone. pub(crate) host_only_render_kicks: bool, + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run ([`Board::compute_channels`]). + compute_channels: u8, } /// M5 Pro: two clusters of ten cores. @@ -2471,6 +2474,9 @@ pub(crate) const J714: Board = Board { g17d_forms: false, completion_inputs: true, host_only_render_kicks: false, + // macOS runs one M5 Pro command queue on up to three firmware compute queues of the same + // context, created on demand and sharing one completion ordinal (its own kicks under aura). + compute_channels: 3, }; /// M5 Max: four clusters of ten cores. @@ -2506,6 +2512,7 @@ pub(crate) const J716C: Board = Board { // G17D has distinct kick encodings, and common 26A428 publishes descriptors // on the item ring. Qualify those interfaces separately. host_only_render_kicks: true, + compute_channels: 1, }; /// J775D's performance controllers run from P3. @@ -2548,6 +2555,7 @@ pub(crate) const J775D: Board = Board { g17d_forms: true, completion_inputs: false, host_only_render_kicks: false, + compute_channels: 1, }; /// M5 (T8142, MacBook Air J813): one cluster of ten core slots, eight enabled. Values from the @@ -2588,6 +2596,7 @@ pub(crate) const J813: Board = Board { g17d_forms: false, completion_inputs: false, host_only_render_kicks: false, + compute_channels: 1, }; /// The J813 on its macOS 27.2 (26B123) firmware: the same board on the common 26B123 graph. @@ -2596,6 +2605,17 @@ pub(crate) const J813_26B123: Board = Board { ..J813 }; +// Every board runs at least one compute channel per command queue and no more than the per-owner +// channel arrays hold. +const _: () = { + let mut boards = [&J714, &J716C, &J775D, &J813, &J813_26B123].as_slice(); + while let [board, rest @ ..] = boards { + assert!(board.compute_channels >= 1); + assert!(board.compute_channels as usize <= crate::g17::pairs::COMPUTE_CHANNELS_MAX); + boards = rest; + } +}; + const _: () = { use super::target::min_parameter_buffer_pages; assert!(J714.min_parameter_buffer as u64 == min_parameter_buffer_pages(J714.clusters) << 15); @@ -2966,6 +2986,14 @@ impl Board { self.completion_inputs } + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run, each with its own preemption, operand, usage, status and stamp state and all + /// of them sharing the context's completion ordinal. 1 where the board's own macOS driver has + /// not been seen to spread a command queue: one firmware compute queue per command queue. + pub(crate) const fn compute_channels(&self) -> u8 { + self.compute_channels + } + /// Whether this is the J813, whose register programs macOS 27.0 writes in the common 26A428 /// forms rather than the M5 Pro's (read out of its own kicks under aura). pub(crate) const fn j813_forms(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index dd0c3c24536867..9e3b5b3a08b1df 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1167,6 +1167,17 @@ const RETIRED_FEATURES: u64 = (uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES) as u64; const _: () = assert!(M5_FEATURES & RETIRED_FEATURES == 0); +/// The compute channel features of a GPU whose logical compute queues each hold up to `channels` +/// physical compute channels ([`pairs::compute_channels_per_owner`]): with more than one, the +/// kernel fans independent compute commands out itself. +fn compute_channel_features(channels: u8) -> u64 { + if channels > 1 { + crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL + } else { + 0 + } +} + /// Event work item ID. const EVENT_WORK: u64 = 0; /// Short control/retirement polls do not wait behind the longer idle deadline. @@ -2542,7 +2553,8 @@ impl gpu::Gpu for Gpu { | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | sync_output::FEATURE_CUMULATIVE_SIGNALS - | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT; + | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT + | compute_channel_features(pairs::compute_channels_per_owner()); let variant = self.shared.variant; // The M5 command set has no AS-build flag: its validation refuses one. if !variant.m5_commands { diff --git a/drivers/gpu/drm/asahi/g17/pairs.rs b/drivers/gpu/drm/asahi/g17/pairs.rs index c7515c1c764171..fe3f9d55b46ec7 100644 --- a/drivers/gpu/drm/asahi/g17/pairs.rs +++ b/drivers/gpu/drm/asahi/g17/pairs.rs @@ -18,11 +18,21 @@ use crate::hw::t8140::queues::RENDER_PAIRS_MAX; /// G17D's count. const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8; +/// Maximum physical compute channels one logical compute owner may hold: the most firmware +/// compute queues any board spreads one command queue over ([`Board::compute_channels`], three +/// on M5 Pro). It sizes the per-owner channel arrays and the compute waits of a render kick, so +/// every channel of an owner costs one dependency slot in each of its consumers. +/// +/// [`Board::compute_channels`]: crate::g17::fw::m5::initdata::Board::compute_channels +pub(crate) const COMPUTE_CHANNELS_MAX: usize = 3; + static PAIRS: AtomicU8 = AtomicU8::new(1); +static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new(1); -/// The count for the probed board, set once at probe (one GPU per system). +/// The counts for the probed board, set once at probe (one GPU per system). pub(crate) fn select_board(board: &crate::g17::fw::m5::initdata::Board) { PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed); + COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed); } /// Render pairs a logical render queue created now may hold. @@ -30,6 +40,70 @@ pub(crate) fn per_owner() -> u8 { PAIRS.load(Relaxed) } +/// Physical compute channels a logical compute queue created now may hold. +pub(crate) fn compute_channels_per_owner() -> u8 { + COMPUTE_CHANNELS.load(Relaxed) +} + +/// GPU execution time of a compute kick, between the start and end timestamps of its firmware +/// execution record, from which the kick is worth a sibling channel. +/// +/// Measured on M5 Pro: one physical QID streams queued kicks back to back for about 11 us each; +/// the same kicks spread over three QIDs take about 16.4 us each, because every kick then pays +/// about 5 us of firmware arbitration between QIDs. A sibling only pays for itself through +/// overlapped execution, so the kick must run long enough for that cost to vanish into it: +/// 100 us is where the 5 us of arbitration falls to 5% of the kick, while a kick of a few +/// microseconds would spend more on arbitration than it runs. +pub(crate) const SIBLING_EXECUTION_NS: u64 = 100_000; + +/// [`SIBLING_EXECUTION_NS`] in the command timestamp ticks of an execution record. +const SIBLING_EXECUTION_TICKS: u64 = SIBLING_EXECUTION_NS + * crate::hw::t8140::resources::COMMAND_TIMESTAMP_HZ + / 1_000_000_000; + +/// Consecutive heavy kicks ([`SIBLING_EXECUTION_NS`]) after which a primary channel's execution is +/// sustained: a single long kick among short ones (a first dispatch, a cold pipeline) does not +/// fan its queue out. +pub(crate) const SIBLING_SUSTAINED_KICKS: u8 = 2; + +/// Kicks of an owner that must already be in flight on its compute channels before a new kick +/// may run beside them on a sibling channel. +/// +/// A kick queued behind one in flight on the same ring starts the moment its predecessor ends, +/// while the host turns that completion into the next submission (60 to 100 us). Two overlapped +/// kicks that each fill the shader cores share them and end together, both rings then wait for +/// the host, and every pair of kicks pays that turnaround. With two kicks already in flight the +/// primary ring keeps one queued behind the overlap, so a sibling only adds overlap and never +/// exposes the turnaround: an owner keeping at most two kicks in flight runs exactly as on one +/// ring. +pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = 2; + +/// How long publication keeps to an owner's bound compute channels after no sibling could be found +/// (no reusable queue to bind or re-arm and no QID headroom) before it looks again. +pub(crate) const SIBLING_HEADROOM_BACKOFF_NS: u64 = 10_000_000; + +/// Whether a new kick of an owner with `in_flight` kicks in flight on its compute channels may +/// overlap them on a sibling channel ([`SIBLING_MIN_IN_FLIGHT`]). +pub(crate) fn overlaps(in_flight: usize) -> bool { + in_flight >= SIBLING_MIN_IN_FLIGHT +} + +/// Folds the execution record `[start, end]` of a retired compute kick into its channel's run of +/// consecutive heavy kicks. +pub(crate) fn heavy_run(run: u8, start: u64, end: u64) -> u8 { + if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS { + run.saturating_add(1) + } else { + 0 + } +} + +/// Whether a primary compute channel with this run of heavy kicks runs sustained heavy work, the +/// only work whose independent kicks fan out onto sibling channels. +pub(crate) fn sustained(run: u8) -> bool { + run >= SIBLING_SUSTAINED_KICKS +} + /// Renders a busy pair of a two-pair owner takes before its next render goes to /// an idle sibling: 1 keeps a queue at depth 1-2 on one pair. const SIBLING_BACKLOG: u8 = 1; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index adc94dca1de4d1..e24eb9813b5fce 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -268,7 +268,7 @@ impl Graph { &mut self, context: Arc, kick_alias: mmu::KernelMapping, - pool_alias: mmu::KernelMapping, + pool_alias: Option, ) -> Result { if !context.is_current() { return Err(EFAULT); @@ -290,7 +290,7 @@ impl Graph { .map(|context| context.alias_in(vm, private.clone(), page, prot)).transpose()?; Ok(Binding { _kick_alias: kick_alias, - pool_alias: Some(pool_alias), + pool_alias, descriptors: Some(descriptors), preempt, usage, @@ -368,12 +368,8 @@ impl Graph { fn vacate_ring(&mut self) -> Option { self.ring.take() } - fn rearm_ring(&mut self, ring: DescriptorRing) -> Result { - if self.ring.is_some() { - return Err(EBUSY); - } - self.ring = Some(ring); - Ok(()) + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { + self.ring.replace(ring) } /// `cursors`: this publication's snapshot (M5), else a fresh read. fn ensure_record_slot(&self, slot: usize, cursors: Option) -> Result { @@ -648,6 +644,14 @@ pub(crate) struct AdmissionState { pub(crate) struct Queue { owner: Option, + /// Per-owner channel index (0 for primary, 1..COMPUTE_CHANNELS_MAX for M5 siblings). + channel_index: u8, + /// Whether this queue currently holds a `Context::note_compute_binding(true)` count. + binding_noted: bool, + /// Consecutive retired kicks of the bound owner whose firmware execution record ran at least + /// [`crate::g17::pairs::SIBLING_EXECUTION_NS`] ([`crate::g17::pairs::heavy_run`]); zero for a + /// new owner. + heavy_run: u8, /// Scheduler/work pages of an exited last owner whose context was dropped; /// the installed queue record still names them until the next owner binds. retained_owner: Option, @@ -739,19 +743,56 @@ impl Queue { program: ComputeProgram, m5: bool, mcache: bool, + ) -> Result { + Self::new_channel( + alloc, + objects, + backing, + owner, + context, + pointers, + operand_state, + board, + program, + m5, + mcache, + 0, + ) + } + + #[expect( + clippy::too_many_arguments, + reason = "A sibling compute queue takes the same physical graph inputs plus its channel identity." + )] + pub(crate) fn new_channel( + alloc: &Allocator<'_>, + objects: &Arc, + backing: Backing, + owner: u64, + context: Arc, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + channel_index: u8, ) -> Result { let Backing { mut pool, mut kick } = backing; let (active, replays) = (Fifo::new()?, Fifo::new()?); let mut graph = Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; let kick_alias = kick.map_client(context.vm())?; - let pool_alias = pool.map_client(context.vm())?; + let pool_alias = Some(pool.map_client(context.vm())?); let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; context.mark_published(); context.note_compute_binding(true); crate::g17::trace::bind(crate::g17::trace::COMPUTE, kick.id().qid(), context.id(), 0); Ok(Self { owner: Some(owner), + channel_index, + binding_noted: true, + heavy_run: 0, retained_owner: None, pool_phase: PoolPhase::Populated, release_sent_ns: None, @@ -870,6 +911,46 @@ impl Queue { pub(crate) fn owner(&self) -> Option { self.owner } + pub(crate) fn channel_index(&self) -> u8 { + self.channel_index + } + pub(crate) fn is_primary(&self) -> bool { + self.channel_index == 0 + } + pub(crate) fn active_len(&self) -> usize { + self.active.len + } + pub(crate) fn has_replays(&self) -> bool { + self.replays.len != 0 + } + pub(crate) fn configuring(&self) -> bool { + self.configuration.is_some() + } + pub(crate) fn has_ring(&self) -> bool { + self.graph.ring.is_some() + } + /// The bound owner's recent kicks on this channel ran sustained heavy work + /// ([`crate::g17::pairs::sustained`]). + pub(crate) fn sustained(&self) -> bool { + crate::g17::pairs::sustained(self.heavy_run) + } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { + binding.context.note_compute_binding(false); + } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + self.heavy_run = 0; + if stamp_released_at { + self.released_at = now_ns(); + } + } /// The bound owner's context; `None` once an exited owner was detached. pub(crate) fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) @@ -1282,8 +1363,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } // It was reported when it retired: step past it. @@ -1295,6 +1375,9 @@ impl Queue { self.active.get_mut(at).ok_or(EIO)?.qos_pending = false; } let front = self.active.get(at).ok_or(EIO)?; + // Only an exact execution record measures the kick: a recordless retirement + // carries a synthesized envelope. + let execution = front.observed.map(|record| record.timestamps); if let Some(ticket) = front.ticket { crate::g17::recovery::note_retired(); crate::g17::trace::complete( @@ -1318,6 +1401,9 @@ impl Queue { Err(error) => Deferred::Retired(completion, Err(error)), })?; self.retire_pending = false; + if let Some([start, end]) = execution { + self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end); + } if stampless || at != 0 { // A completion record is no witness that the firmware is done with the // descriptor: it can still store the stamp through it. Keep the command @@ -1340,8 +1426,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(None) | Err(EAGAIN) => { @@ -1514,8 +1599,7 @@ impl Queue { self.retire_pending = false; self.retirement_ready = true; if self.released { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(()) @@ -1880,6 +1964,27 @@ impl Queue { && !self.source_hint.has_readers(&self.source_readers) } pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { + self.bind_owner_channel(owner, context, 0) + } + /// Binds a reusable physical queue with its own dedicated compute pool as an additional + /// compute channel of `owner`. + pub(crate) fn bind_sibling( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { + if !self.graph.m5 || self.pool_phase != PoolPhase::Populated || self.graph.ring.is_none() { + return Err(EBUSY); + } + self.bind_owner_channel(owner, context, channel_index) + } + fn bind_owner_channel( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { if !self.reusable() { return Err(EBUSY); } @@ -1927,7 +2032,7 @@ impl Queue { self.kick.clear_ring()?; let kick_alias = self.kick.map_client(context.vm())?; let pool_alias = self.pool.map_client(context.vm())?; - self.graph.bind(context.clone(), kick_alias, pool_alias) + self.graph.bind(context.clone(), kick_alias, Some(pool_alias)) })(); let binding = match moved { Ok(binding) => binding, @@ -1953,7 +2058,9 @@ impl Queue { self.retained_owner = None; } context.mark_published(); + self.clear_binding_note(); context.note_compute_binding(true); + self.binding_noted = true; crate::g17::trace::bind( crate::g17::trace::COMPUTE, self.qid(), @@ -1961,6 +2068,8 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); + self.channel_index = channel_index; + self.heavy_run = 0; self.rearm_for = None; self.unpublished_binding = true; self.released = false; @@ -1971,10 +2080,9 @@ impl Queue { /// True allows the registry to cancel the never-published QID and drop this graph. An /// installed graph remains retained even after the logical owner exits without work. pub(crate) fn release_owner(&mut self) -> Result { - if let Some(binding) = &self.binding { - binding.context.note_compute_binding(false); - } + self.clear_binding_note(); if !self.installed && self.active.len == 0 && !self.quarantined && self.previous.is_none() { + self.clear_owner(false); return Ok(true); } self.released = true; @@ -2007,8 +2115,7 @@ impl Queue { self.retirement_ready = true; } if self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(false) @@ -2036,6 +2143,25 @@ impl Queue { // exited owner's idle queue left a later command retired without a completion stamp. Some(binding) } + /// A recycled vacant sibling queue whose descriptor ring still awaits off-lock release + /// before re-arming with fresh backing. + pub(crate) fn take_recycled_ring(&mut self) -> Option { + if !self.recycled_pending() || self.pool_phase != PoolPhase::Vacant || self.graph.ring.is_none() + { + return None; + } + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let ring = self.graph.vacate_ring(); + Some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: ring, + }) + } /// An idle retained queue whose USC backing may be given back. pub(crate) fn vacate_candidate(&self) -> bool { self.pool_phase == PoolPhase::Populated @@ -2147,10 +2273,9 @@ impl Queue { self.replay_prepared = false; self.submitted = 0; self.kick.clear_parent_after_recovery(); - self.owner = None; + self.clear_owner(true); self.released = true; self.retirement_ready = true; - self.released_at = now_ns(); self.needs_fresh_backing = true; Ok(()) } @@ -2225,21 +2350,40 @@ impl Queue { })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data - /// the caller writes before binding an owner. + /// the caller writes before binding an owner, plus any previous sibling descriptor + /// ring to drop off-lock. pub(crate) fn rearm( &mut self, pages: crate::g17::freelist::Pages, ring: DescriptorRing, - ) -> Result { + ) -> Result<(PoolDescriptor, Option)> { if !self.can_rearm() { return Err(EAGAIN); } - self.graph.rearm_ring(ring)?; - self.pool.rearm(pages)?; + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let old_ring = self.graph.rearm_ring(ring); + if let Err(error) = self.pool.rearm(pages) { + if let Some(old) = old_ring { + let _ = self.graph.rearm_ring(old); + } + if let (Some(binding), Some(descriptors)) = (self.binding.as_mut(), descriptors) { + binding.descriptors = Some(descriptors); + } + return Err(error); + } self.pool_phase = PoolPhase::Populated; self.release_sent_ns = None; self.needs_fresh_backing = false; - self.pool.descriptor() + let vacated = (old_ring.is_some() || descriptors.is_some()).then_some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: old_ring, + }); + Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { !self.growing && self.pool_phase == PoolPhase::Populated && self.pool.fits_capacity(required) @@ -2473,16 +2617,43 @@ impl Queue { status: &Arc, through: Option, recovery_state: u32, + ) -> Result> { + self.dependency_checked(owner, status, through, recovery_state, false) + } + + /// As [`Self::dependency`], additionally requiring every covered active kick to carry a + /// visible completion (`DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION`) when `require_visible` is set. + /// A covered kick without visible completion returns `EAGAIN` so the consumer waits for it + /// to retire on the host. + pub(crate) fn dependency_checked( + &self, + owner: u64, + status: &Arc, + through: Option, + recovery_state: u32, + require_visible: bool, ) -> Result> { if through.is_none() || self.owner != Some(owner) { return Ok(None); } - let Some(active) = self + let mut newest = None; + for active in self .active .iter() .filter(|a| crate::g17::job::Order::contains(through, a.packet.order.sequence)) - .last() - else { + { + if require_visible { + let visible = matches!( + &active.packet.command, + crate::g17::command::Validated::Compute { visible_completion: true, .. } + ); + if !visible { + return Err(EAGAIN); + } + } + newest = Some(active); + } + let Some(active) = newest else { return Ok(None); }; if self.quarantined && self.spared_quarantine { @@ -2789,13 +2960,22 @@ impl Queue { let predecessor = KickPredecessor::new(qid, kick_parent)?; let matrix_ops = self.graph.m5 && *requested_matrix_ops; let m5_board = if self.graph.m5 { Some(self.graph.board.ok_or(EINVAL)?) } else { None }; - // Every earlier kick of this queue has retired, so the parent has completed. + // Each physical QID owns a single preemption/operand/usage/status/stamp set: only take the + // pipelined parent class once every earlier kick on this physical channel has retired. + // On multi-channel boards (M5 Pro), concurrency comes strictly from independent kicks + // running across distinct sibling QIDs because they carry no barrier on each other. let parent_retired = self.active.len == 0 && self.replays.len == 0 && !self.quarantined && !self.awaiting_witness; let parent_class = m5_board .map(|board| crate::g17::fw::m5::compute::parent_dependency(board, parent_retired)); + let multi_channel = m5_board.is_some_and(crate::g17::fw::m5::compute::multi_channel); + let (m5_ordinal, m5_object_ids) = if multi_channel { + packet.context.next_compute_identity() + } else { + (self.ordinal, 0x0000_0001_0000_0001) + }; let m5_args = m5_board.zip(parent_class).map(|(board, parent_class)| { let tuple = crate::g17::fw::m5::compute::kick_tuple(board, parent_class); crate::g17::fw::m5::compute::DescriptorArgs { @@ -2807,7 +2987,7 @@ impl Queue { preempt_va: addresses.preempt, cdm_va: *cdm_va, operand_va: addresses.operand, usage_va: addresses.usage, free_list_slot: u32::from(self.pool.id()), context_id: args.context_id, work_state: work_word, - object_ids: 0x0000_0001_0000_0001, + object_ids: m5_object_ids, resource_policy: plan.map_or(0xf5_0040_0020, |p| u64::from(p.pressure) << 32 | 0x0040_0020), preempt_state_offset: tuple.preempt_state_offset, // The board's core layout sizes the operand state, as on G17P. @@ -2822,13 +3002,15 @@ impl Queue { }, common26_tail: board.graph.is_common26(), descriptor_va: descriptor_low, - // M5 Pro's descriptors carry the ordinal as the submission sequence too, as macOS's do. - submit_sequence: if board.completion_inputs() { u64::from(self.ordinal) } else { 0 }, + // M5 Pro's descriptors carry the shared context ordinal as both submit_sequence and + // completion_ordinal. + submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 }, work_state_va: work_node, cdm_end_va: *cdm_end_va, stamp_va: [args.stamp_va, args.aux_stamp_va], stamp_value: crate::g17::fw::stamp_value(kick_timestamp.get() as u32), qid: u32::from(qid), + channel_index: if multi_channel { u32::from(self.channel_index) } else { 0 }, kick_timestamp: kick_timestamp.get(), - completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, self.ordinal), + completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal), status_va: args.status_va, timestamp_va: [timestamp_va, timestamp_va + 8], shared_control_va: self.pool.control_va(), event_metadata: crate::g17::fw::m5::compute::completion_forms(board).1, @@ -2949,7 +3131,8 @@ impl Queue { let target = self.pool.reserve_submission()?; let qos = host.qos_publish(qos::Owner { qid, qos: identity.qos, data_master: 2 }, identity.scheduler, policy).or_else(|error| { - self.pool.cancel_unpublished(target)?; Err(error) + self.pool.cancel_unpublished(target)?; + Err(error) })?; self.active.back_mut().ok_or(EIO)?.qos_pending = true; // `cursors` is this publication's snapshot: no second read of the ring. @@ -3184,7 +3367,7 @@ impl Queue { self.configuration.take().ok_or(EIO)?.release(); if self.ordinal == 0 && self.active.len == 0 && self.replays.len == 0 { self.retirement_ready = true; - if self.released { self.owner = None; } + if self.released { self.clear_owner(false); } } Ok(()) } @@ -3596,7 +3779,9 @@ impl Queue { { return Ok((false, None)); } + self.clear_binding_note(); if !self.installed { + self.clear_owner(false); return Ok((true, None)); } let mut retired = None; @@ -3618,12 +3803,17 @@ impl Queue { self.unpublished_binding = false; self.retirement_ready = true; self.released = true; - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); Ok((false, retired)) } } +impl Drop for Queue { + fn drop(&mut self) { + self.clear_binding_note(); + } +} + impl Queue { /// Same immutable singleton identity and current physical epoch. pub(crate) fn has_input_source( diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index de4760aec5f0a3..42037e834357c0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -53,8 +53,10 @@ pub(crate) struct RenderDependencies { pub(crate) render_tiling_count: usize, pub(crate) tiling: [KickDependency; 2], pub(crate) tiling_count: usize, - pub(crate) compute: Option, - pub(crate) fragment_compute: Option, + pub(crate) compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) compute_count: usize, + pub(crate) fragment_compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) fragment_compute_count: usize, /// Fragment kicks of other pairs' overlapping same-VM renders. pub(crate) hazards: [KickDependency; crate::g17::hazard::PUBLICATION_BARRIERS], pub(crate) hazard_count: usize, @@ -68,8 +70,10 @@ impl RenderDependencies { render_tiling_count: 0, tiling: [KickDependency::ZERO; 2], tiling_count: 0, - compute: None, - fragment_compute: None, + compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + compute_count: 0, + fragment_compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_compute_count: 0, hazards: [KickDependency::ZERO; crate::g17::hazard::PUBLICATION_BARRIERS], hazard_count: 0, }; @@ -671,12 +675,12 @@ impl Pair { /// 1 the tiling encoder, 2 a full channel or compute completion, 3 the /// fragment encoder; the last class is the implicit parent's. struct RenderBarriers { - tiling: [KickDependency; 5], + tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], tiling_count: usize, - fragment: [KickDependency; 4 + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment: [KickDependency; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, - tiling_types: [u8; 6], - fragment_types: [u8; 5 + crate::g17::hazard::PUBLICATION_BARRIERS], + tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_types: [u8; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } /// The last fragment kick published on any pair, and the last one of a render with an API task @@ -743,12 +747,14 @@ fn render_barriers( compute_class: u8, ) -> RenderBarriers { let fragment_stage = fragment_stage || stage_prefixes; - let mut tiling_barriers = [KickDependency::ZERO; 5]; + let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut tiling_count = 0; - let mut fragment_barriers = [own_tiling; 4 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_barriers = + [own_tiling; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; - let mut tiling_types = [1; 6]; - let mut fragment_types = [3; 5 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; + let mut fragment_types = + [3; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; fragment_types[0] = 1; for dependency in &dependencies.render_tiling[..dependencies.render_tiling_count] { tiling_barriers[tiling_count] = *dependency; @@ -778,13 +784,13 @@ fn render_barriers( } } } - if let Some(compute) = dependencies.compute { - tiling_barriers[tiling_count] = compute; + for compute in &dependencies.compute[..dependencies.compute_count] { + tiling_barriers[tiling_count] = *compute; tiling_types[tiling_count] = compute_class; tiling_count += 1; } - if let Some(compute) = dependencies.fragment_compute { - fragment_barriers[fragment_count] = compute; + for compute in &dependencies.fragment_compute[..dependencies.fragment_compute_count] { + fragment_barriers[fragment_count] = *compute; fragment_types[fragment_count] = compute_class; fragment_count += 1; } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index ea9a245e6ea2d9..db17e21efc8219 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -82,6 +82,15 @@ pub(super) struct ComputeCell { queue: kernel::sync::Mutex>>, /// Lock-free mirror of the installed queue's QID (`u8::MAX` when empty). qid: core::sync::atomic::AtomicU8, + /// Lock-free mirror of `(configuring, active_len, last_published)` updated while the cell + /// mutex is held, so `compute_direct()` can keep single-in-flight work on channel 0 without + /// locking sibling cells and pick the least-loaded channel without extra mutex trips. + active_len: core::sync::atomic::AtomicU32, + configuring: core::sync::atomic::AtomicBool, + last_published: core::sync::atomic::AtomicU64, + /// Lock-free mirror of [`compute::Queue::sustained`], so `compute_direct()` keeps every kick + /// of an owner whose primary channel runs short kicks on that channel without a lock. + sustained: core::sync::atomic::AtomicBool, } impl ComputeCell { @@ -90,6 +99,10 @@ impl ComputeCell { pin_init!(Self { queue <- kernel::new_mutex!(None, "g17::ComputeCell::queue"), qid: core::sync::atomic::AtomicU8::new(u8::MAX), + active_len: core::sync::atomic::AtomicU32::new(0), + configuring: core::sync::atomic::AtomicBool::new(false), + last_published: core::sync::atomic::AtomicU64::new(0), + sustained: core::sync::atomic::AtomicBool::new(false), }), GFP_KERNEL, ) @@ -100,22 +113,68 @@ impl ComputeCell { (qid != u8::MAX).then_some(qid) } + fn sync_stats(&self, queue: Option<&compute::Queue>) { + match queue { + Some(queue) => { + self.active_len + .store(queue.active_len() as u32, Ordering::Release); + self.configuring + .store(queue.configuring(), Ordering::Release); + self.last_published + .store(queue.last_published(), Ordering::Release); + self.sustained.store(queue.sustained(), Ordering::Release); + } + None => { + self.active_len.store(0, Ordering::Release); + self.configuring.store(false, Ordering::Release); + self.last_published.store(0, Ordering::Release); + self.sustained.store(false, Ordering::Release); + } + } + } + + /// Lock-free routing hint `(configuring, active_len, last_published)`. + pub(super) fn load_hint(&self) -> (bool, u32, u64) { + ( + self.configuring.load(Ordering::Acquire), + self.active_len.load(Ordering::Acquire), + self.last_published.load(Ordering::Acquire), + ) + } + + /// Lock-free hint: this cell's queue runs sustained heavy work ([`compute::Queue::sustained`]). + pub(super) fn sustained(&self) -> bool { + self.sustained.load(Ordering::Acquire) + } + /// The installed queue, locked; None once the registry gave it up. pub(super) fn lock(&self) -> Option> { - QueueGuard::new(self.queue.lock()) + QueueGuard::new(self, self.queue.lock()) } } /// A locked installed queue. pub(super) struct QueueGuard<'a> { + cell: &'a ComputeCell, queue: core::ptr::NonNull, _guard: kernel::sync::MutexGuard<'a, Option>>, } impl<'a> QueueGuard<'a> { - fn new(mut guard: kernel::sync::MutexGuard<'a, Option>>) -> Option { + fn new( + cell: &'a ComputeCell, + mut guard: kernel::sync::MutexGuard<'a, Option>>, + ) -> Option { let queue = core::ptr::NonNull::from((*guard).as_deref_mut()?); - Some(Self { queue, _guard: guard }) + Some(Self { cell, queue, _guard: guard }) + } +} + +impl Drop for QueueGuard<'_> { + fn drop(&mut self) { + // SAFETY: `_guard` drops after `Drop::drop`, so `self.queue` remains locked and valid. + let queue = unsafe { self.queue.as_ref() }; + self.cell.sync_stats(Some(queue)); } } @@ -157,15 +216,17 @@ impl ComputeSlot { /// Gives the queue up to the caller, which drops it outside the cell lock. fn take(&mut self) -> Option> { let mut guard = self.0.queue.lock(); - let taken = guard.take(); + let queue = guard.take(); self.0.qid.store(u8::MAX, Ordering::Release); - taken + self.0.sync_stats(None); + queue } fn put(&mut self, queue: Option>) { let qid = queue.as_ref().map_or(u8::MAX, |queue| queue.qid()); let old = { let mut guard = self.0.queue.lock(); self.0.qid.store(qid, Ordering::Release); + self.0.sync_stats(queue.as_deref()); core::mem::replace(&mut *guard, queue) }; drop(old); @@ -174,7 +235,12 @@ impl ComputeSlot { impl Drop for ComputeSlot { fn drop(&mut self) { - let queue = self.0.queue.lock().take(); + let queue = { + let mut guard = self.0.queue.lock(); + let queue = guard.take(); + self.0.sync_stats(None); + queue + }; drop(queue); } } @@ -260,23 +326,358 @@ impl Registry { } pub(super) fn compute(&self, owner: u64) -> Option> { + self.compute_primary(owner).or_else(|| { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner)) + }) + } + + pub(super) fn compute_primary(&self, owner: u64) -> Option> { self.compute .iter() .flatten() .filter_map(|entry| entry.queue.as_deref()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) } pub(super) fn compute_mut(&mut self, owner: u64) -> Option> { self.compute(owner) } - /// The cell of `owner`'s bound queue, which its publisher may lock without the device mutex. - pub(super) fn compute_cell(&self, owner: u64) -> Option> { - self.compute.iter().flatten().find_map(|entry| { - entry.queue.as_deref()?.owner().filter(|bound| *bound == owner)?; - Some(entry.queue.0.clone()) - }) + pub(super) fn compute_for_packet( + &self, + owner: u64, + packet: &Arc, + ) -> Option> { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) + } + + pub(super) fn compute_for_packet_mut( + &mut self, + owner: u64, + packet: &Arc, + ) -> Option> { + self.compute_for_packet(owner, packet) + } + + /// Count and used channel-index bitmask of `owner`'s bound compute channels. + fn compute_channels_of(&self, owner: u64) -> (usize, u8) { + let mut count = 0usize; + let mut mask = 0u8; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + count += 1; + let idx = queue.channel_index(); + if idx < 8 { + mask |= 1u8 << idx; + } + } + (count, mask) + } + + fn next_sibling_index(&self, owner: u64, limit: u8) -> Option { + let (count, mask) = self.compute_channels_of(owner); + if count == 0 || count >= usize::from(limit) { + return None; + } + (1..limit).find(|idx| mask & (1u8 << idx) == 0) + } + + /// Where `owner`'s next sibling channel would come from, in the order [`Self::rebind_compute`] + /// gives a primary binding its channel: an idle reusable queue whose populated pool serves the + /// owner's VM and fits, else a vacant reusable queue no other owner is re-arming, else a fresh + /// QID, else an idle reusable queue whose pool still serves another VM (an exited owner's, + /// say), given back first while no other pool release is in flight. Only + /// [`compute::Queue::reusable`] queues whose scheduler release is not in flight qualify, so a + /// channel with an owner, work, a pending pool release or a closing context is never taken, + /// and neither is an open owner's idle channel, which only a primary binding may share. The + /// longest released queue goes first. None keeps the owner on its bound channels. + fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let (mut warm, mut vacant, mut foreign) = (None, None, None); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.reusable()) + .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) + { + let best = if queue.pool_vacant() { + if !queue.rearm_open(owner) { + continue; + } + &mut vacant + } else if queue.pool_serves(vm) { + if queue.needs_fresh_backing() || !queue.pool_fits(required) || !queue.has_ring() { + continue; + } + &mut warm + } else { + &mut foreign + }; + let key = (queue.released_at(), queue.qid()); + if best.is_none_or(|old| key < old) { + *best = Some(key); + } + } + if let Some((_, qid)) = warm { + return Some(SiblingSource::Warm(qid)); + } + if let Some((_, qid)) = vacant { + return Some(SiblingSource::Vacant(qid)); + } + if self.qids.compute_fits(self.admission.queues() as usize) { + return Some(SiblingSource::Fresh); + } + // A pool release in flight ends in a vacant queue; give back one at a time. + if self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.vacancy_pending()) + { + return None; + } + foreign.map(|(_, qid)| SiblingSource::Foreign(qid)) + } + + /// Whether a sibling channel for `owner` is available now ([`Self::sibling_source`]). + fn has_compute_sibling_headroom( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> bool { + self.sibling_source(owner, context, required).is_some() + } + + /// Whether `owner` benefits from acquiring another compute channel now: its primary channel + /// runs sustained heavy work ([`compute::Queue::sustained`]), all currently bound channels are + /// busy with at least [`super::pairs::SIBLING_MIN_IN_FLIGHT`] kicks in flight between them, no + /// replay is pending on any of them, and a sibling source exists + /// ([`Self::has_compute_sibling_headroom`]). A primary channel streaming short kicks never + /// brings up a sibling: its ring runs them faster than several QIDs would. + fn wants_compute_sibling( + &self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> bool { + if limit <= 1 || self.next_sibling_index(owner, limit).is_none() { + return false; + } + let mut sustained_primary = false; + let mut all_busy = true; + let mut in_flight = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.has_replays() { + return false; + } + if queue.is_primary() { + sustained_primary = queue.sustained(); + } + if queue.active_len() == 0 && !queue.configuring() { + all_busy = false; + } + in_flight += queue.active_len(); + } + if !sustained_primary || !all_busy || !super::pairs::overlaps(in_flight) { + return false; + } + self.has_compute_sibling_headroom(owner, context, required) + } + + /// Binds a warm sibling source ([`SiblingSource::Warm`]) as an additional compute channel of + /// `owner`. Returns `Ok(Some(true))` if bound, `Ok(Some(false))` if no warm queue is ready (a + /// vacant queue to re-arm, a fresh QID or another VM's idle queue to give back is built or + /// released off the device mutex, [`Backend::try_add_compute_sibling`]), or `Ok(None)` if no + /// sibling slot is needed. + fn bind_reusable_sibling( + &mut self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> Result> { + let Some(channel_index) = self.next_sibling_index(owner, limit) else { + return Ok(None); + }; + let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else { + return Ok(Some(false)); + }; + self.compute_queue_mut(qid) + .ok_or(EIO)? + .bind_sibling(owner, context.clone(), channel_index)?; + Ok(Some(true)) + } + + /// The installed compute queue with QID `qid`. + fn compute_queue_mut(&mut self, qid: u8) -> Option> { + self.compute + .iter_mut() + .flatten() + .filter_map(|entry| entry.queue.as_deref_mut()) + .find(|queue| queue.qid() == qid) + } + + /// Gives back the idle reusable queue `qid`, whose pool serves another VM, for fresh backing: + /// the next pool pass releases its pool ([`Self::vacate_idle_pools`]) and leaves it vacant, + /// ready to re-arm for the VM that asked. + fn give_back_foreign(&mut self, qid: u8) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing(); + Ok(()) + } + + /// Picks the bound compute channel of `owner` for `packet`. A command with cross-queue input + /// sources always takes the primary channel, so a chain of semaphore hops between queues + /// stays on one ring per queue. Dependent commands stay on the sole active channel when only + /// one is active so the implicit parent covers them without cross-channel barriers. Other + /// commands take the primary channel unless it runs sustained heavy work + /// ([`compute::Queue::sustained`]) and enough kicks are in flight to overlap + /// ([`super::pairs::overlaps`]); then they spread across the least-loaded channel (oldest + /// `last_published` breaks ties). + fn select_compute_channel(&self, owner: u64, packet: &super::job::Packet) -> Option { + let primary = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) + .map(|queue| (queue.qid(), queue.sustained())); + if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) { + return Some(qid); + } + if packet.order.wait_through[1].is_some() { + let mut active_qid = None; + let mut active_channels = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.active_len() != 0 || queue.configuring() { + active_qid = Some(queue.qid()); + active_channels += 1; + } + } + if active_channels == 1 { + return active_qid; + } + } + if let Some((qid, false)) = primary { + return Some(qid); + } + let in_flight: usize = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .map(|queue| queue.active_len()) + .sum(); + if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) { + return Some(qid); + } + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .min_by_key(|queue| { + ( + queue.configuring(), + queue.active_len(), + queue.last_published(), + queue.channel_index(), + ) + }) + .map(|queue| queue.qid()) + } + + /// Appends covered active compute kicks from every compute channel of `owner` other than + /// `exclude_qid` into `frontier`. On boards whose firmware waits require visible completion + /// (`require_visible`), any covered kick on another channel without it returns `EAGAIN`. + pub(super) fn append_compute_prefix( + &self, + owner: u64, + exclude_qid: Option, + packet: &Arc, + recovery_state: u32, + require_visible: bool, + frontier: &mut super::dependency::Frontier, + ) -> Result { + let through = packet.order.wait_through[1]; + if through.is_none() { + return Ok(()); + } + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && Some(queue.qid()) != exclude_qid) + { + if let Some(dep) = queue.dependency_checked( + owner, + packet.completion.status(), + through, + recovery_state, + require_visible, + )? { + frontier.insert(0, dep).map_err(|_| EAGAIN)?; + } + } + Ok(()) + } + + /// The cells of `owner`'s bound compute channels, indexed by `channel_index`, which its + /// publisher may lock one at a time without the device mutex. + pub(super) fn compute_cells( + &self, + owner: u64, + ) -> [Option>; super::pairs::COMPUTE_CHANNELS_MAX] { + let mut cells = [const { None }; super::pairs::COMPUTE_CHANNELS_MAX]; + for entry in self.compute.iter().flatten() { + let Some(queue) = entry.queue.as_deref() else { + continue; + }; + if queue.owner() == Some(owner) { + let index = usize::from(queue.channel_index()); + if index < cells.len() { + cells[index] = Some(entry.queue.0.clone()); + } + } + } + cells } /// An installed idle queue keeps its original QID and backing. Mapping a @@ -290,8 +691,19 @@ impl Registry { pub(super) fn rebind_compute(&mut self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; if let Some(queue) = self.compute(owner) { - return Ok(if queue.matches(owner, queue.qid(), context)? { - if queue.pool_fits(required) { Rebind::Done } else { Rebind::Grow } + let matches = queue.matches(owner, queue.qid(), context)?; + let fits = queue.pool_fits(required); + drop(queue); + let all_fit = fits + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .all(|queue| queue.pool_fits(required)); + return Ok(if matches { + if all_fit { Rebind::Done } else { Rebind::Grow } } else { Rebind::Fresh }); @@ -325,13 +737,7 @@ impl Registry { .min_by_key(|(key, _)| *key) .map(|(_, qid)| qid); if let Some(qid) = foreign { - self.compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.qid() == qid) - .ok_or(EIO)? - .require_fresh_backing(); + self.give_back_foreign(qid)?; return Err(ENOSPC); } let idle = self @@ -370,6 +776,16 @@ impl Registry { /// Whether `owner` can bind a channel now, without changing any binding. Owner 0 asks /// only whether some channel is free for a new owner. fn compute_readiness(&self, owner: u64, query: Option<(&Arc, super::freelist::ComputeCapacity)>) -> Readiness { + if owner != 0 + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.owner() == Some(owner) && queue.spared_pending()) + { + return Readiness::Progress; + } if let (Some((context, required)), Some(queue)) = (query, self.compute(owner).filter(|_| owner != 0)) { return if queue.spared_pending() { Readiness::Progress @@ -446,7 +862,7 @@ impl Registry { qid: u8, pages: crate::g17::freelist::Pages, ring: compute::DescriptorRing, - ) -> Result { + ) -> Result<(super::freelist::PoolDescriptor, Option)> { let mut queue = self .compute .iter_mut() @@ -457,6 +873,13 @@ impl Registry { queue.rearm(pages, ring) } + /// Reserves the vacant queue `qid` for `owner`'s re-arm, as [`Self::bind_reusable`] does for a + /// primary binding. + fn reserve_rearm(&mut self, qid: u8, owner: u64) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.reserve_rearm(owner); + Ok(()) + } + /// Ends `owner`'s re-arm reservation of `qid` when it did not bind the queue. pub(super) fn release_rearm(&mut self, qid: u8, owner: u64) { if let Some(mut queue) = self.compute.iter_mut().flatten() @@ -467,7 +890,15 @@ impl Registry { } } - pub(super) fn bind_rearmed(&mut self, qid: u8, owner: u64, context: &Arc) -> Result { + /// Binds the re-armed queue `qid` as `owner`'s compute channel `channel_index`: its primary + /// (0) or a sibling. + pub(super) fn bind_rearmed( + &mut self, + qid: u8, + owner: u64, + context: &Arc, + channel_index: u8, + ) -> Result { let teardown = &self.teardown; let mut queue = self .compute @@ -480,7 +911,11 @@ impl Registry { if queue.context().is_some_and(|bound| teardown.releasing(bound)) { return Err(EAGAIN); } - queue.bind_owner(owner, context.clone()) + if channel_index == 0 { + queue.bind_owner(owner, context.clone()) + } else { + queue.bind_sibling(owner, context.clone(), channel_index) + } } /// Delay before retrying pools a turn could not release. @@ -595,16 +1030,26 @@ impl Registry { } pub(super) fn reserve_compute(&mut self, owner: u64) -> Result { - if owner == 0 - || self.compute.iter().flatten().any(|entry| { - entry - .queue - .as_deref() - .map_or(entry.reservation.owner == owner, |queue| { - queue.owner() == Some(owner) - }) - }) - { + self.reserve_compute_channel(owner, 1) + } + + pub(super) fn reserve_compute_channel( + &mut self, + owner: u64, + limit: u8, + ) -> Result { + if owner == 0 || limit == 0 { + return Err(EINVAL); + } + let mut owned = 0usize; + for entry in self.compute.iter().flatten() { + match entry.queue.as_deref() { + None if entry.reservation.owner == owner => return Err(EINVAL), + Some(queue) if queue.owner() == Some(owner) => owned += 1, + _ => {} + } + } + if owned >= usize::from(limit) { return Err(EINVAL); } let slot = self @@ -667,21 +1112,63 @@ impl Registry { Ok(()) } - pub(super) fn release_compute(&mut self, owner: u64) -> Result { - let Some(slot) = self.compute.iter().position(|entry| { - entry + /// Releases idle sibling channels of `owner` before primary pool growth. Returns `Err(EAGAIN)` + /// while any sibling still has active, replaying or configuring work, and returns any + /// unpublished sibling queues for off-lock alias drop and QID cancellation. + fn drain_compute_siblings( + &mut self, + owner: u64, + ) -> Result)>> { + let mut retired = KVec::new(); + for slot in 0..self.compute.len() { + let is_sibling = self.compute[slot] .as_ref() .and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(owner)) - }) else { - return Ok(()); - }; - let entry = self.compute[slot].as_mut().ok_or(EIO)?; - let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; - if unpublished { - self.qids.cancel_unpublished(entry.reservation.id)?; - self.compute[slot] = None; - self.note_build_room(); + .is_some_and(|queue| queue.owner() == Some(owner) && !queue.is_primary()); + if !is_sibling { + continue; + } + let busy = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.active_len() != 0 || queue.has_replays() || queue.configuring() + }); + if busy { + return Err(EAGAIN); + } + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + if let Some(queue) = entry.queue.take() { + retired.push((entry.reservation, queue), GFP_KERNEL)?; + } + } + } + Ok(retired) + } + + pub(super) fn release_compute(&mut self, owner: u64) -> Result { + // Release sibling channels before the primary channel for deterministic teardown order. + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + self.qids.cancel_unpublished(entry.reservation.id)?; + self.compute[slot] = None; + self.note_build_room(); + } + } } Ok(()) } @@ -711,6 +1198,20 @@ pub(super) enum Rebind { Fresh, } +/// Where an owner's next sibling compute channel comes from ([`Registry::sibling_source`]). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(super) enum SiblingSource { + /// An idle reusable queue whose populated pool serves the owner's VM and fits: bind it. + Warm(u8), + /// A vacant reusable queue no other owner is re-arming: re-arm it with fresh backing. + Vacant(u8), + /// No reusable queue to bind or re-arm, but a fresh QID fits. + Fresh, + /// An idle reusable queue whose pool still serves another VM: give it back, so it is vacated + /// and can be re-armed. + Foreign(u8), +} + #[kunit_tests(asahi_g17_uninstalled_cleanup)] mod uninstalled_cleanup_tests { @@ -747,11 +1248,15 @@ pub(super) struct Backend { backlog: core::sync::atomic::AtomicU32, compute_backlog: core::sync::atomic::AtomicU32, closed: core::sync::atomic::AtomicBool, - /// The cell of the compute queue this owner last published to under the device mutex, - /// with the shared compute objects mapped into its VM. Direct publication revalidates the - /// binding under the cell lock; a stale cell only sends the packet back to that path. + /// The cells of the compute channels this owner last published to under the device mutex, + /// indexed by `channel_index`, with the shared compute objects mapped into its VM. Direct + /// publication revalidates each binding under its own cell lock; a stale cache only sends + /// the packet back to the device-mutex path. #[pin] - direct: kernel::sync::Mutex>>, + direct: kernel::sync::Mutex<[Option>; super::pairs::COMPUTE_CHANNELS_MAX]>, + /// Earliest monotonic timestamp (ns) at which `compute_direct()` may yield again to try + /// adding another sibling channel after a headroom miss. + sibling_backoff_until: core::sync::atomic::AtomicU64, /// The channel a prepared packet is about to publish into. Its claim keeps the idle /// channel from being shared away between prepare_job and run_job. #[pin] @@ -771,6 +1276,8 @@ pub(super) struct Backend { /// Render pairs this owner may hold, fixed at creation with its scheduler's /// credits and its render pool's sizing. pairs: u8, + /// Physical compute channels this owner may hold (up to three on M5 Pro, one elsewhere). + compute_channels: u8, } impl Backend { @@ -908,13 +1415,18 @@ impl Backend { backlog: core::sync::atomic::AtomicU32::new(0), compute_backlog: core::sync::atomic::AtomicU32::new(0), closed: core::sync::atomic::AtomicBool::new(false), - direct <- kernel::new_mutex!(None, "g17::Backend::direct"), + direct <- kernel::new_mutex!( + [const { None }; super::pairs::COMPUTE_CHANNELS_MAX], + "g17::Backend::direct" + ), + sibling_backoff_until: core::sync::atomic::AtomicU64::new(0), claimed <- kernel::new_mutex!(None, "g17::Backend::claimed"), outer_compute <- kernel::new_mutex!(None, "g17::Backend::outer_compute"), outer_render <- kernel::new_mutex!(None, "g17::Backend::outer_render"), admission, direct_slot: core::sync::atomic::AtomicU32::new(0), pairs: super::pairs::per_owner(), + compute_channels: super::pairs::compute_channels_per_owner(), }), GFP_KERNEL, )?, @@ -1077,7 +1589,16 @@ impl Backend { { let state = self.shared.state.lock(); let firmware = state.as_ref().ok_or(ENODEV)?; - if firmware.queues.compute(self.owner).is_some_and(|queue| queue.pool_fits(required)) { + if firmware.queues.compute(self.owner).is_some() + && firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .all(|queue| queue.pool_fits(required)) + { return Ok(()); } } @@ -1094,6 +1615,7 @@ impl Backend { // Growth waits for this queue's retirement and for firmware to consume the pool // release; both are progress the event worker reports. let observed = self.shared.progress.observe(); + let mut retired_siblings = KVec::new(); let result = (|| { let mut state = self.shared.state.lock(); admission.check()?; @@ -1101,7 +1623,10 @@ impl Backend { if !lease.is_current() { return Err(EAGAIN); } if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } firmware.scan_compute(None, &mut deferred)?; - let mut queue = firmware.queues.compute_mut(self.owner).ok_or(EAGAIN)?; + // Release sibling channels before growing the primary channel so undersized + // sibling pools are detached and later re-acquired at the grown capacity. + retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?; + let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { let notify = queue.begin_growth(&firmware.init, required)?; @@ -1115,6 +1640,9 @@ impl Backend { } queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) })(); + for item in retired_siblings { + self.finish_uninstalled_compute(Some(item))?; + } deferred.finish(); match result { Ok(old) => { drop(old); return Ok(()); } @@ -1155,12 +1683,14 @@ impl Backend { } /// Re-arms the vacant queue `qid` reserved for this owner with fresh zeroed backing, built - /// without the device mutex, and binds it. Some(true): bound; Some(false): retry (the - /// preparation epoch changed or the queue is no longer re-armable); None: no memory for - /// the backing now. + /// without the device mutex, and binds it as compute channel `channel_index` (0: the primary; + /// a sibling only while that index is still the owner's next free one). Some(true): bound; + /// Some(false): retry (the preparation epoch changed, the queue is no longer re-armable or + /// the sibling index was taken); None: no memory for the backing now. fn rearm_vacant( &self, qid: u8, + channel_index: u8, required: super::freelist::ComputeCapacity, alloc: &super::object::Allocator<'_>, objects: &Arc, @@ -1187,16 +1717,21 @@ impl Backend { // rearm(). let ready = firmware.queues.compute.iter().flatten() .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)); + .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)) + && (channel_index == 0 + || firmware.queues.next_sibling_index(self.owner, self.compute_channels) + == Some(channel_index)); if !ready { drop(state); return Ok(Some(false)); } - let descriptor = match firmware.queues.rearm_compute(qid, pages, ring) { + let (descriptor, vacated) = match firmware.queues.rearm_compute(qid, pages, ring) { Err(error) if error == EAGAIN => return Ok(Some(false)), result => result?, }; // The firmware consumed this slot's release before the backing // was dropped; the row is rewritten before the queue is kicked. firmware.init.install_compute_pool(descriptor)?; - firmware.queues.bind_rearmed(qid, self.owner, &self.context)?; + firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?; + drop(state); + drop(vacated); Ok(Some(true)) } @@ -1279,7 +1814,8 @@ impl Backend { Err(qid) => { // bind_reusable reserved `qid` for this owner: any outcome but binding it // ends the reservation, so another owner may re-arm it. - let result = self.rearm_vacant(qid, required, &alloc, &objects, &lease, admission); + let result = + self.rearm_vacant(qid, 0, required, &alloc, &objects, &lease, admission); if !matches!(result, Ok(Some(true))) { if let Some(firmware) = self.shared.state.lock().as_deref_mut() { firmware.queues.release_rearm(qid, self.owner); @@ -1369,6 +1905,176 @@ impl Backend { if result != Err(EAGAIN) { return result; } } } + + /// Best-effort acquisition of an additional compute channel with its own dedicated compute + /// pool for a multi-channel M5 owner, from the source [`Registry::sibling_source`] names: a + /// warm reusable queue is bound at once, a vacant one is re-armed with fresh backing and + /// bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new queue, and an + /// idle queue still holding another VM's pool is given back for the next attempt. An owner + /// waiting for its first channel goes first. Never blocks or fails the submission if no + /// sibling is available. + fn try_add_compute_sibling( + &self, + required: super::freelist::ComputeCapacity, + admission: &Admission<'_>, + ) -> Result { + if self.compute_channels <= 1 || !self.context.is_m5() { + return Ok(false); + } + admission.check()?; + let lease = self.shared.preparations.enter_until(admission)?; + let dev = self.shared.drm()?; + let (uat, objects, source, channel_index) = { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() || self.shared.crashed.load(Ordering::Acquire) { + return Ok(false); + } + if self.admission_open().is_err() + || self.shared.channels.has_waiters() + || !firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) + { + return Ok(false); + } + let Some(channel_index) = firmware + .queues + .next_sibling_index(self.owner, self.compute_channels) + else { + return Ok(false); + }; + let source = match firmware.queues.sibling_source(self.owner, &self.context, required) { + None => return Ok(false), + Some(SiblingSource::Warm(_)) => { + return Ok(firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? == Some(true)); + } + Some(SiblingSource::Foreign(qid)) => { + firmware.queues.give_back_foreign(qid)?; + drop(state); + // A full event pass releases its pool; a later kick re-arms it. + self.shared.queue_events(); + return Ok(false); + } + Some(SiblingSource::Vacant(qid)) => { + firmware.queues.reserve_rearm(qid, self.owner)?; + Err(qid) + } + Some(SiblingSource::Fresh) => match firmware + .queues + .reserve_compute_channel(self.owner, self.compute_channels) + { + Ok(reservation) => Ok(reservation), + Err(_) => return Ok(false), + }, + }; + ( + firmware.uat.clone(), + firmware.pool.clone(), + source, + channel_index, + ) + }; + let alloc = super::object::Allocator { + dev: &dev, + uat: &uat, + }; + let reservation = match source { + Ok(reservation) => reservation, + Err(qid) => { + // The reservation ends with any outcome but binding the queue. + let result = self.rearm_vacant( + qid, + channel_index, + required, + &alloc, + &objects, + &lease, + admission, + ); + let bound = matches!(result, Ok(Some(true))); + if !bound { + if let Some(firmware) = self.shared.state.lock().as_deref_mut() { + firmware.queues.release_rearm(qid, self.owner); + } + } + drop(lease); + // As for a fresh sibling, a failed re-arm leaves the owner on its bound channels. + admission.check()?; + return Ok(bound); + } + }; + let built = (|| { + let pool = compute::PoolBacking::new( + &alloc, + reservation.id, + required, + self.context.vm().memory_client(), + )?; + { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { + return Err(EAGAIN); + } + self.admission_open()?; + firmware.queues.reserved(reservation)?; + firmware.init.install_compute_pool(pool.pool_descriptor()?)?; + } + let backing = compute::Backing::new(&alloc, pool)?; + let queue = compute::Queue::new_channel( + &alloc, + &objects, + backing, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + true, + self.shared.variant.mcache, + channel_index, + )?; + Ok(KBox::new(queue, GFP_KERNEL)?) + })(); + let (mut built, build_error) = match built { + Ok(queue) => (Some(queue), None), + Err(error) => (None, Some(error)), + }; + let result = { + let mut state = self.shared.state.lock(); + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if let Err(error) = admission.check() { + Err(error) + } else if !lease.is_current() || self.admission_open().is_err() { + Err(EAGAIN) + } else if let Some(error) = build_error { + Err(error) + } else { + firmware.queues.install_compute(reservation, &mut built) + } + }; + drop(built); + if result.is_err() { + let mut state = self.shared.state.lock(); + if let Some(firmware) = (*state).as_deref_mut() { + let _ = firmware.queues.cancel_compute(reservation); + } + } + drop(lease); + Ok(result.is_ok()) + } } /// One device transaction can fail each retained kick once and then retire it. @@ -1718,15 +2424,51 @@ impl super::Firmware { fn publish_compute(&mut self, owner: u64, packet: Arc, dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result { + self.publish_compute_on(owner, None, packet, dependencies, deferred) + } + + pub(super) fn publish_compute_on( + &mut self, + owner: u64, + target_qid: Option, + packet: Arc, + dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch, + ) -> Result { + let qid = match target_qid { + Some(qid) => qid, + None => self.queues.select_compute_channel(owner, &packet).ok_or(EIO)?, + }; + let mut combined = super::dependency::Frontier::new(); + for dependency in dependencies { + combined.insert(0, *dependency)?; + } + if target_qid.is_none() && packet.order.wait_through[1].is_some() { + let recovery_state = super::recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut combined, + )?; + } if packet.completion.sources().is_some() { - self.publish_compute_inputs(owner, packet, dependencies, deferred) + self.publish_compute_inputs(owner, qid, packet, combined.as_slice(), deferred) } else { - self.publish_compute_raw(owner, packet, dependencies, &[], deferred) + self.publish_compute_raw(owner, qid, packet, combined.as_slice(), &[], deferred) } } #[inline(never)] - fn publish_compute_inputs(&mut self, owner: u64, packet: Arc, + fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, packet: Arc, dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result { if self.recovery.pending() || super::recovery::Memory::recovery_state(&self.init)? != 0 { @@ -1743,7 +2485,6 @@ impl super::Firmware { // the source's kick, and the firmware orders it. So is a G17P source of the consumer's // own execution context: one context needs no write-back between the two kicks. let m5 = self.init.is_m5(); - let consumer_qid = self.queues.compute(owner).map(|queue| queue.qid()); let mut waited: u128 = 0; for source in &sources.sources { if source.submission.source_status()? { continue; } @@ -1757,7 +2498,7 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; - if m5 && consumer_qid == Some(dependency.qid()) { + if m5 && dependency.qid() == target_qid { // Same physical QID in this epoch: the queue's implicit parent already strictly // orders earlier kicks on this QID; drop the self-reader hold and skip adding a // duplicate explicit barrier. @@ -1782,7 +2523,7 @@ impl super::Firmware { } holds.push(hold, GFP_KERNEL)?; } - let result = self.publish_compute_raw(owner, packet.clone(), merged.as_slice(), + let result = self.publish_compute_raw(owner, target_qid, packet.clone(), merged.as_slice(), native.as_slice(), deferred); if packet.is_published() { for queue in self.queues.compute.iter().flatten() @@ -1801,6 +2542,7 @@ impl super::Firmware { fn publish_compute_raw( &mut self, owner: u64, + target_qid: u8, packet: Arc, dependencies: &[super::fw::kick::KickDependency], native: &[super::sync_input::NativeWait], @@ -1815,7 +2557,7 @@ impl super::Firmware { .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.qid() == target_qid && queue.owner() == Some(owner)) .ok_or(EIO)?; // The first command after an owner change waits while the scheduler // the queue was bound to is being released: a live previous owner may @@ -1891,12 +2633,31 @@ impl Registry { /// objects mapped into its VM, and its queue bound to `context` with a /// pool that fits and no spared witness to release. fn compute_bound(&self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity) -> Result { - let Some(queue) = self.compute(owner) else { + let Some(primary) = self.compute_primary(owner) else { return Ok(false); }; - Ok(!queue.spared_pending() - && queue.pool_fits(required) - && queue.matches(owner, queue.qid(), context)?) + if primary.spared_pending() + || !primary.pool_fits(required) + || !primary.matches(owner, primary.qid(), context)? + { + return Ok(false); + } + drop(primary); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && !queue.is_primary()) + { + if queue.spared_pending() + || !queue.pool_fits(required) + || !queue.matches(owner, queue.qid(), context)? + { + return Ok(false); + } + } + Ok(true) } fn release_compute_witness( @@ -1906,24 +2667,26 @@ impl Registry { owner: u64, deferred: &mut DeferredBatch, ) -> Result { - let Some(mut queue) = self + let mut pending = false; + let recovery_state = super::recovery::Memory::recovery_state(init)?; + for mut queue in self .compute .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) - else { - return Ok(false); - }; - if !queue.spared_pending() { - return Ok(false); + .filter(|queue| queue.owner() == Some(owner)) + { + if !queue.spared_pending() { + continue; + } + queue.release_witnessed( + recovery_state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + pending |= queue.spared_pending(); } - queue.release_witnessed( - super::recovery::Memory::recovery_state(init)?, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - Ok(queue.spared_pending()) + Ok(pending) } fn fail_compute_vm( @@ -2245,12 +3008,26 @@ impl Backend { Some((frontier, holds, cross_qid_mask)) } - /// Steady-state publication into this owner's bound channel without the device mutex: only - /// the channel's own lock and the port's small locks are taken, and nothing device-wide is - /// scanned. On M5, same-VM cross-QID compute sources whose producers have published their kick - /// metadata also resolve directly without the device mutex. None leaves the packet untouched - /// for the device-mutex path, which owns binding, first installation, non-M5 native-wait - /// sources, render prefixes, replay and recovery. + /// Whether `packet` may run on, or bring up, a sibling compute channel of this owner: only an + /// independent command (no in-queue barrier, no cross-queue input sources) of an owner whose + /// primary channel runs sustained heavy work (`primary_sustained`, asked last, from + /// [`compute::Queue::sustained`]). Every other command streams down the primary ring: short + /// kicks run faster there than spread over several QIDs, and a semaphore hop between queues + /// stays on one ring per queue. + fn fans_out(&self, packet: &super::job::Packet, primary_sustained: impl FnOnce() -> bool) -> bool { + self.compute_channels > 1 + && packet.order.wait_through[1].is_none() + && packet.completion.sources().is_none() + && primary_sustained() + } + + /// Steady-state publication into this owner's bound channel(s) without the device mutex: only + /// one channel's own lock at a time and the port's small locks are taken, and nothing + /// device-wide is scanned. On M5, same-VM cross-QID compute sources whose producers have + /// published their kick metadata also resolve directly, always onto the primary channel. + /// None leaves the packet untouched for the device-mutex path, which owns binding, first + /// installation, cross-channel barriers, non-M5 native-wait sources, render prefixes, replay + /// and recovery. fn compute_direct( &self, packet: &Arc, @@ -2259,16 +3036,24 @@ impl Backend { ) -> Option { let m5 = self.context.is_m5(); let has_sources = packet.completion.sources().is_some(); + let bound_count = self.context.compute_binding_count() as usize; if (has_sources && !m5) || self.context.render_seen() + || bound_count == 0 + || bound_count > super::pairs::COMPUTE_CHANNELS_MAX + || (bound_count > 1 && packet.order.wait_through[1].is_some()) || packet.cancel_requested() || packet.completion.status().get() != 0 || self.admission_open().is_err() { return None; } - let cell = self.direct.lock().clone()?; - let target_qid = cell.qid()?; + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count != bound_count || cells[0].is_none() { + return None; + } + let target_qid = cells[0].as_ref()?.qid()?; let lease = self.shared.preparations.try_enter().ok()?; let port = self.shared.port(&lease)?; if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { @@ -2281,6 +3066,59 @@ impl Backend { } else { (super::dependency::Frontier::new(), KVec::new(), 0) }; + // Only an independent kick without input sources of an owner whose primary channel runs + // sustained heavy work may leave the primary ring ([`Self::fans_out`]); the primary + // cell's lock-free hint answers that without a lock. + let primary = cells[0].as_ref()?; + let fans_out = self.fans_out(packet, || primary.sustained()); + let can_add_sibling = fans_out + && cached_count < usize::from(self.compute_channels) + && now_ns() >= self.sibling_backoff_until.load(Ordering::Relaxed); + // Lock-free channel selection using each cell's atomic `(configuring, active_len, + // last_published)` mirror: + // - A kick that does not fan out, or finds primary channel 0 idle (`active == 0 && + // !configuring`), routes straight to channel 0 without locking any sibling cell mutexes + // at all, keeping short kicks, input sources and single-in-flight work streaming down + // the primary ring with zero extra mutex overhead. + // - Otherwise, scan bound cells' atomic hints lock-free. While fewer than + // `SIBLING_MIN_IN_FLIGHT` kicks are in flight the kick queues behind them on channel 0 + // ([`super::pairs::overlaps`]); from there it takes the least-loaded channel (oldest + // `last_published` breaks ties), falling back to add a sibling only when every bound + // channel already has >= 1 kick in flight (`all_busy`). + let target_idx = if cached_count == 1 || !fans_out { + 0 + } else { + let (primary_configuring, primary_active, _) = primary.load_hint(); + if primary_active == 0 && !primary_configuring { + 0 + } else { + let mut best: Option<(usize, (bool, u32, u64, usize))> = None; + let mut all_busy = true; + let mut in_flight = 0usize; + for (idx, cell) in cells.iter().enumerate() { + let Some(cell) = cell else { + continue; + }; + let (configuring, active, last_published) = cell.load_hint(); + if active == 0 && !configuring { + all_busy = false; + } + in_flight += active as usize; + let key = (configuring, active, last_published, idx); + if best.is_none_or(|(_, best_key)| key < best_key) { + best = Some((idx, key)); + } + } + if !super::pairs::overlaps(in_flight) { + 0 + } else if can_add_sibling && all_busy { + return None; + } else { + best?.0 + } + } + }; + let target_cell = cells[target_idx].as_ref()?; // Full effort is applied by the device-mutex path when it is not already. if !port.note_submission() { return None; @@ -2315,13 +3153,18 @@ impl Backend { (None, false) }; let result = (|| { - let mut queue = cell.lock()?; + let mut queue = target_cell.lock()?; if !queue.installed() || queue.spared_pending() || !queue.pool_fits(required) || queue.pending_switch_from().is_some() - || queue.qid() != target_qid + || (has_sources && queue.qid() != target_qid) + || (m5 && queue.outer_slots() != 1) + || (cached_count == 1 + && can_add_sibling + && super::pairs::overlaps(queue.active_len())) || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) + || self.context.compute_binding_count() as usize != cached_count || !lease.is_current() { return None; @@ -2465,10 +3308,19 @@ impl Backend { return Ok(true); } let (held, count) = match engine { - crate::g17::job::Engine::Compute => ( - &self.outer_compute, - firmware.queues.compute(self.owner).map_or(2, |queue| queue.outer_slots()), - ), + crate::g17::job::Engine::Compute => { + let slots = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .map(|queue| queue.outer_slots()) + .max() + .unwrap_or(2); + (&self.outer_compute, slots) + } // Tiling and fragment: one slot each. crate::g17::job::Engine::Render => (&self.outer_render, 2), }; @@ -2531,30 +3383,68 @@ impl Backend { } else { false }; - // The steady state: this owner's channel is bound and installed. - if !sources_checked || self.context.is_m5() { - if let Some(cell) = self.direct.lock().clone() { - let bound = cell.lock().and_then(|mut queue| { - let bound = queue.installed() - && !queue.spared_pending() - && queue.pool_fits(required) - && matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)); - if bound { - queue.claim(); - Some(queue.outer_slots()) + // The steady state: this owner's bound channel(s) are all cached and installed. + let bound_count = self.context.compute_binding_count() as usize; + if (!sources_checked || self.context.is_m5()) + && bound_count != 0 + && bound_count <= super::pairs::COMPUTE_CHANNELS_MAX + { + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count == bound_count { + if let Some(primary) = cells[0].clone() { + // Validate siblings first so primary is claimed only once every channel passes. + let mut all_ok = true; + let mut outer_slots = 1u32; + for cell in cells[1..].iter().flatten() { + match cell.lock() { + Some(queue) + if queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) => + { + outer_slots = outer_slots.max(queue.outer_slots()); + } + _ => { + all_ok = false; + break; + } + } + } + let bound = if all_ok { + primary.lock().and_then(|mut queue| { + let ok = queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) + && self.context.compute_binding_count() as usize == cached_count; + if ok { + queue.claim(); + Some(outer_slots.max(queue.outer_slots())) + } else { + None + } + }) } else { None - } - }); - if let Some(outer_slots) = bound { - self.hold_claim(Some(cell)); - if !self.context.is_m5() { - return Readiness::Ready; - } - return match self.claim_compute_outer_direct(outer_slots) { - Ok(false) => Readiness::Outer, - _ => Readiness::Ready, }; + if let Some(outer_slots) = bound { + self.hold_claim(Some(primary)); + if !self.context.is_m5() { + return Readiness::Ready; + } + return match self.claim_compute_outer_direct(outer_slots) { + Ok(false) => Readiness::Outer, + _ => Readiness::Ready, + }; + } } } } @@ -2602,18 +3492,18 @@ impl Backend { } } - /// Called with the device mutex held after a successful publication: remembers the bound - /// channel for direct publication. + /// Called with the device mutex held after a successful publication: remembers all bound + /// channels for direct publication. fn remember_direct(&self, registry: &Registry) { - let cell = registry.compute_cell(self.owner); + let cells = registry.compute_cells(self.owner); let mut direct = self.direct.lock(); - let current = match (&*direct, &cell) { + let current = direct.iter().zip(cells.iter()).all(|pair| match pair { (Some(old), Some(new)) => Arc::ptr_eq(old, new), (None, None) => true, _ => false, - }; + }); if !current { - let old = core::mem::replace(&mut *direct, cell); + let old = core::mem::replace(&mut *direct, cells); drop(direct); drop(old); } @@ -2714,6 +3604,37 @@ impl Backend { { return Err(render::FALLBACK); } + if self.fans_out(packet, || { + firmware.queues.compute_primary(self.owner).is_some_and(|queue| queue.sustained()) + }) { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + // Bind a warm reusable sibling inline if one is ready; otherwise fall back once + // so `compute_packet` can build a fresh surplus sibling off-lock. + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => self.sibling_backoff_until.store(0, Ordering::Relaxed), + Some(false) => return Err(render::FALLBACK), + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } if !self.claim_outer(firmware, crate::g17::job::Engine::Compute)? { return Err(render::FALLBACK); } @@ -2792,6 +3713,7 @@ impl Backend { // progress (work states, ring room, replays) and the reopening of // publication after recovery both signal `progress`. let mut bound = true; + let mut sibling_tried = false; let mut demand = None; let deadline = now_ns().saturating_add(super::preparation::QUEUE_WAIT_NS); let check = || { @@ -2883,6 +3805,58 @@ impl Backend { drop(lease); continue; } + if !sibling_tried + && self.fans_out(packet, || { + firmware + .queues + .compute_primary(self.owner) + .is_some_and(|queue| queue.sustained()) + }) + { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + sibling_tried = true; + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } + Some(false) => { + drop(state); + drop(lease); + if self.try_add_compute_sibling(required, &admission)? { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } else { + self.sibling_backoff_until.store( + now_ns().saturating_add( + super::pairs::SIBLING_HEADROOM_BACKOFF_NS, + ), + Ordering::Relaxed, + ); + } + continue; + } + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + sibling_tried = true; + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } let held = self.claim_outer(firmware, crate::g17::job::Engine::Compute)?; if let (false, Some(domain), Some(claimed)) = (held, &outer, claimed) { // The shared work ring has no unclaimed room: consumption or returned claims @@ -3112,6 +4086,12 @@ impl super::Firmware { let busy = !queue.channel_free(); queue.recycle_killed()?; queue.recycle_quarantined_idle()?; + if deferred.vacated_room() { + if let Some(vacated) = queue.take_recycled_ring() { + deferred.defer_vacated(vacated); + freed = true; + } + } if let Some(binding) = queue.detach_exited_owner() { deferred.defer_binding(binding); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 7cf47757a9550e..13479fd13c7737 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -34,30 +34,48 @@ impl Backend { // No outer preparation lease survives compute_packet's return. Hold a // fresh epoch through alias destruction so recovery can join this work. loop { - let lease = self.shared.preparations.enter(false)?; - let mut retired = None; - let mut state = self.shared.state.lock(); - let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { drop(state); drop(lease); continue; } - let mut binding = None; - if let Some(index) = firmware.queues.compute.iter().position(|entry| { - entry.as_ref().and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(self.owner)) - }) { - let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; - let (cancel, replaced) = entry.queue.as_deref_mut().ok_or(EIO)? - .rollback_unpublished(self.owner, &self.context)?; - binding = replaced; - if cancel { - retired = entry.queue.take().map(|queue| (entry.reservation, queue)); + let lease = self.shared.preparations.enter(false)?; + let mut retired = KVec::new(); + let mut bindings = KVec::new(); + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { drop(state); drop(lease); continue; } + // Roll back sibling channels before the primary channel for deterministic teardown. + for primary_pass in [false, true] { + for index in 0..firmware.queues.compute.len() { + let matches = firmware.queues.compute[index] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(self.owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; + let (cancel, replaced) = entry + .queue + .as_deref_mut() + .ok_or(EIO)? + .rollback_unpublished(self.owner, &self.context)?; + if let Some(replaced) = replaced { + let _ = bindings.push(replaced, GFP_KERNEL); + } + if cancel { + if let Some(queue) = entry.queue.take() { + let _ = retired.push((entry.reservation, queue), GFP_KERNEL); + } + } + } } - } - drop(state); - drop(binding); - self.finish_uninstalled_compute(retired)?; - self.shared.channels.notify(); - self.shared.queue_events(); - return Ok(()); + drop(state); + drop(bindings); + for item in retired { + self.finish_uninstalled_compute(Some(item))?; + } + self.shared.channels.notify(); + self.shared.queue_events(); + return Ok(()); } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs index 2bad8071087fd0..4e0dfece644a6e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs @@ -30,7 +30,7 @@ impl Backend { return Ok(Decision::Defer); } // Each queue is locked on its own: release this one before visiting the others. - let Some(own) = firmware.queues.compute(self.owner) + let Some(own) = firmware.queues.compute_for_packet(self.owner, packet) .filter(|queue| queue.can_classify_timeout(packet)) .and_then(|queue| queue.timeout_head()) else { return Ok(Decision::Own); @@ -48,7 +48,7 @@ impl Backend { } let decision = verdict.decision; if decision == Decision::Spare { - firmware.queues.compute(self.owner).ok_or(EIO)? + firmware.queues.compute_for_packet(self.owner, packet).ok_or(EIO)? .classify(&|_| Class::Spared); } if let Some(blocker) = verdict.reported_blocker(renewals, excuse) { @@ -73,13 +73,13 @@ impl Backend { deferred: &mut DeferredBatch) -> Result { use crate::g17::timeout::Decision; use core::sync::atomic::{AtomicU32, Ordering}; - let expired = firmware.queues.compute_mut(self.owner) + let expired = firmware.queues.compute_for_packet_mut(self.owner, packet) .is_some_and(|mut queue| queue.expire_stamp_wait(packet)); if !expired { return Ok(Decision::Own); } firmware.scan_compute(None, deferred)?; - if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) { + if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) { return Ok(Decision::Own); } static REPORTED: AtomicU32 = AtomicU32::new(0); @@ -122,7 +122,7 @@ impl Backend { return Ok(None); }; firmware.scan_compute(None, &mut deferred)?; - let Some(mut queue) = firmware.queues.compute_mut(self.owner) else { + let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) else { return Ok(None); }; // A command that retired in this pass has its result. @@ -150,7 +150,7 @@ impl Backend { return Ok(()); }; firmware.scan_compute(None, &mut deferred)?; - if let Some(mut queue) = firmware.queues.compute_mut(self.owner) { + if let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) { queue.cancel(packet, &mut |event| deferred.push(event))?; } Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index d19a52c6746328..ee3536a8bbcd0d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -166,13 +166,15 @@ impl super::Registry { /// ACK storage belongs to the already-retained transaction, so a full event /// batch cannot overflow a separate cache. No allocation or wait is needed. pub(super) fn acknowledge_compute_exit(&mut self, cookie: u64) { + let mut matched = false; for entry in self.compute.iter_mut().flatten() { if let Some(mut queue) = entry.queue.as_deref_mut() { - if queue.acknowledge_exit(cookie) { - return; - } + matched |= queue.acknowledge_exit(cookie); } } + if matched { + return; + } if self.teardown.acknowledge_render_kill(cookie) { RENDER_KILLS[RENDER_KILL_ACKNOWLEDGED].fetch_add(1, Ordering::Relaxed); crate::g17::trace::teardown(4, cookie, 0x100, 0); @@ -269,6 +271,11 @@ impl Firmware { } fn publish_compute_exit(&mut self, context: &Arc, age: u64, now: u64, pressed: &mut bool) -> Result { + // A context is killed at most once: a multi-channel context records the single kill + // cookie across all of its exiting channels below. + if context.kill_published() { + return Ok(()); + } let Some(index) = self.queues.compute.iter().position(|entry| { entry .as_ref() @@ -374,8 +381,25 @@ impl Firmware { PRESSED_KILL_NS.store(now.max(1), Ordering::Relaxed); } queue.record_exit(cookie, now); + drop(queue); + // A single ContextKill tears down every queue of this context: attach the same + // cookie to any other exiting compute channel of `context` so they settle together. + for (other_index, entry) in self.queues.compute.iter_mut().enumerate() { + if other_index == index { + continue; + } + if let Some(mut other) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) { + if other.exit_candidate(context, age) { + other.record_exit(cookie, now); + } + } + } crate::g17::trace::teardown(3, cookie, u64::from(context.id()), hold | u64::from(beside)); fence(Ordering::SeqCst); + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; if let Err(error) = queue.announce_exit(now, || self.primary.notify(MSG_CONTROL_NOTIFY)) { dev_warn!( self.primary.state.shared.dev.as_ref(), diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index e72fc921834d93..55cd94b8b003f7 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -124,15 +124,33 @@ impl Firmware { // backpressure uses the existing failed-replay retirement. Err(EBUSY) } else { (|| { - self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)? - .prepare_replay(&packet)?; + let qid = { + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; + queue.prepare_replay(&packet)?; + queue.qid() + }; let owner = owner.ok_or(EIO)?; packet.check_replay_dependencies()?; - let dependencies = self.queues.render_prefix(owner, &packet)?; - self.publish_compute(owner, packet.clone(), dependencies.as_slice(), deferred) + let mut dependencies = self.queues.render_prefix(owner, &packet)?; + let recovery_state = recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut dependencies, + )?; + self.publish_compute_on(owner, Some(qid), packet.clone(), dependencies.as_slice(), deferred) })() }; let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) && (self.recovery.pending() diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index ee3b5e518da587..6f1ade9a2b284d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -656,13 +656,26 @@ impl Registry { dependencies.tiling_count += 1; } } - if let Some(queue) = self.compute(owner) { - dependencies.compute = queue.dependency( + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + let tiling = queue.dependency( owner, packet.completion.status(), packet.order.tiling_wait_through[1], state, )?; + if let Some(dep) = tiling { + *dependencies + .compute + .get_mut(dependencies.compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.compute_count += 1; + } if packet.order.tiling_wait_through[1] != packet.order.wait_through[1] { let whole = queue.dependency( owner, @@ -670,8 +683,12 @@ impl Registry { packet.order.wait_through[1], state, )?; - if whole != dependencies.compute { - dependencies.fragment_compute = whole; + if let Some(dep) = whole.filter(|dep| Some(*dep) != tiling) { + *dependencies + .fragment_compute + .get_mut(dependencies.fragment_compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.fragment_compute_count += 1; } } } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 3e1ad1c649aa7c..b7ba5152f50518 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -561,6 +561,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) +/* + * DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: the kernel itself runs the + * independent compute commands of one queue on several firmware compute + * queues of its context, so that they overlap. Userspace needs no further + * queues of its own for that. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/asahi/g17-capacity-fault-tests.py b/tools/asahi/g17-capacity-fault-tests.py index 72f2552d781a49..46b6ec3c51438e 100644 --- a/tools/asahi/g17-capacity-fault-tests.py +++ b/tools/asahi/g17-capacity-fault-tests.py @@ -109,7 +109,8 @@ def fixture(): mod qos { pub type Owner = u64; } enum Deferred { Retired(Arc, Result<[u64; 4]>), Release(Arc) } struct Queue { - owner: Option, installed: bool, active: Fifo, quarantined: bool, + owner: Option, channel_index: u8, binding_noted: bool, + installed: bool, active: Fifo, quarantined: bool, previous: Option, unpublished_binding: bool, released: bool, graph: Graph, binding: Option, retirement_ready: bool, released_at: u64, growing: bool, pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option, replays: Fifo>, @@ -126,11 +127,24 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> u64 { 1 } fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { binding.context.note_compute_binding(false); } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + methods + r''' } fn idle(live: &Arc) -> Queue { Queue { - owner: Some(2), installed: true, active: Fifo::new(), quarantined: false, + owner: Some(2), channel_index: 0, binding_noted: false, + installed: true, active: Fifo::new(), quarantined: false, previous: None, unpublished_binding: false, released: false, graph: Graph { cursors: Cursors { count: 1280, producer: 4, consumer: 4 }, stamp: 7 << 8, fail: false, resets: 0, owner: 2, m5: false }, binding: Some(Binding { context: Context::new(2, live) }), retirement_ready: false, diff --git a/tools/asahi/g17-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index a97a3b4021e746..fb3585ea7ec901 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -35,7 +35,8 @@ def fixture(): ('super::recovery::Memory', 'Memory'), ('super::fw::compute_pool::required_blocks', 'required_blocks'), ('super::freelist::ComputeCapacity', 'ComputeCapacity'), - ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS')]: + ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS'), + ('super::pairs::SIBLING_HEADROOM_BACKOFF_NS', 'SIBLING_HEADROOM_BACKOFF_NS')]: packet = packet.replace(old, new) ensure = ensure.replace(old, new) admission = (item(preparation, "pub(super) struct Admission<'a>") + '\n' + @@ -85,7 +86,8 @@ def fixture(): // A work-state node is taken per engine: compute admission must ask for a compute one. struct Work;impl Work{fn acquire(&self,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");if MODE.load(Ordering::SeqCst)==4{Err(EBUSY)}else{Ok(1)}}} struct Completion;impl Completion{fn status(&self)->Status{Status}fn work_state(&self)->Result{Ok(Work)}} -struct Packet{command:Validated,completion:Completion} +struct Order{wait_through:[Option;2]} +struct Packet{command:Validated,completion:Completion,order:Order} impl Packet{fn check_dependencies(&self)->Result{Ok(())}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} struct DeferredBatch;impl DeferredBatch{fn publication()->Result{Ok(Self)}fn finish(&mut self){}} struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} @@ -98,7 +100,13 @@ def fixture(): fn compute(&self,_:u64)->Option<()>{if MODE.load(Ordering::SeqCst)==0{None}else{Some(())}} fn render_prefix(&self,_:u64,_:&Arc)->Result>{Ok(vec![])} fn release_compute_witness(&self,_:&Init,_:&(),_:u64,_:&mut DeferredBatch)->Result{Ok(MODE.load(Ordering::SeqCst)==2)} + fn wants_compute_sibling(&self,_:u64,_:&Context,_:u8,_:usize)->bool{false} + fn has_compute_sibling_headroom(&self,_:u64,_:&Context,_:usize)->bool{true} + fn bind_reusable_sibling(&mut self,_:u64,_:&Context,_:u8,_:usize)->Result>{Ok(None)} + fn compute_primary(&self,_:u64)->Option{None} } +struct Primary;impl Primary{fn sustained(&self)->bool{false}} +const SIBLING_HEADROOM_BACKOFF_NS:u64=10_000_000; struct Firmware{recovery:Recovery,init:Init,queues:Queues,port:()} // Mode 6: the publication itself refuses with EBUSY (no recovery): an immediate error, not a spent budget. impl Firmware{fn replay_compute(&mut self,_:&mut DeferredBatch)->Result{Ok(())}fn publish_compute(&mut self,_:u64,_:Arc,_:&[()],_:&mut DeferredBatch)->Result{if MODE.load(Ordering::SeqCst)==6{advance(5_000_000);Err(EBUSY)}else{Err(EAGAIN)}}} @@ -106,7 +114,7 @@ def fixture(): struct Available;impl Available{fn observe(&self)->u64{now_ns()}} struct Shared{preparations:Arc,state:State,crashed:AtomicBool,compute_blocks:usize,active_cores:u32,progress:Available}impl Shared{fn queue_events(&self){}} struct ComputeDemand;impl ComputeDemand{fn new(_:&Shared)->Self{Self}} -struct Backend{shared:Shared,owner:u64,context:Context} +struct Backend{shared:Shared,owner:u64,context:Context,compute_channels:u8,sibling_backoff_until:AtomicU64} fn required_blocks(_:usize,_:u32,_:u16)->Result{Ok(1)} type ComputeCapacity=usize; impl Backend{ @@ -118,6 +126,8 @@ def fixture(): fn compute_direct(&self,_:&Arc,_:usize,_:&mut DeferredBatch)->Option{None} fn sources_published(&self,_:&Arc)->Result{Ok(true)} fn remember_direct(&self,_:&Queues){} + fn try_add_compute_sibling(&self,_:usize,_:&Admission<'_>)->Result{Ok(false)} + fn fans_out(&self,_:&Packet,primary_sustained:impl FnOnce()->bool)->bool{self.compute_channels>1&&primary_sustained()} fn wait_release(&self,_:&Available,_:u64,admission:&Admission<'_>)->Result{ let _=admission.slice_ms()?; advance(1_000_000); @@ -140,8 +150,8 @@ def fixture(): ''' + ensure + '\n' + packet + r''' } fn main(){ - let b=Backend{owner:1,context:Context,shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; - let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion}); + let b=Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; + let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); for mode in 0..4 { MODE.store(mode,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); let r=b.compute_packet(&p,&mut DeferredBatch); diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 1a29447f2f07e8..d79d784b7578fe 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -41,6 +41,7 @@ def fixture(): use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicU64,Ordering,fence}}; type Result = std::result::Result; type KBox = Box; +type KVec = Vec; const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; const RECOVERY_WAIT_MS:u32=26_000; static NOW:AtomicU64=AtomicU64::new(0);static ALIAS:AtomicBool=AtomicBool::new(false);static PAGES:AtomicBool=AtomicBool::new(false); @@ -76,6 +77,7 @@ def fixture(): mod compute{pub(crate) use crate::Queue;} struct Queue{fresh:bool} impl Queue{ + fn owner(&self)->Option{Some(1)} fn pool_fits(&self,_:usize)->bool{false} fn begin_growth(&mut self,_:&(),_:usize)->Result{Ok(false)} fn growth_token(&self)->Option{Some(7)} @@ -89,6 +91,8 @@ def fixture(): impl Registry{ fn compute(&self,_:u64)->Option<&Queue>{self.compute[0].as_ref().unwrap().queue.as_deref()} fn compute_mut(&mut self,_:u64)->Option<&mut Queue>{self.compute[0].as_mut().unwrap().queue.as_deref_mut()} + fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} + fn drain_compute_siblings(&mut self,_:u64)->Result)>>{Ok(Vec::new())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} diff --git a/tools/asahi/g17-compute-multi-channel-feature-tests.py b/tools/asahi/g17-compute-multi-channel-feature-tests.py new file mode 100755 index 00000000000000..0707c01070c03e --- /dev/null +++ b/tools/asahi/g17-compute-multi-channel-feature-tests.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: G17 GET_PARAMS reports DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL exactly where the +kernel fans compute out itself. + +Compiles the production board selection of drivers/gpu/drm/asahi/g17/pairs.rs +(`select_board()`, `compute_channels_per_owner()`), `multi_channel()` of +g17/fw/m5/compute.rs, `Board::compute_channels()` and every board's +`compute_channels` value of g17/fw/m5/initdata.rs, `compute_channel_features()` +of g17/mod.rs and the feature constant of file.rs, the latter against every +DRM_ASAHI_FEATURE_* bit that include/uapi/drm/asahi_drm.h defines. It checks +that the bit is set exactly when a logical compute queue may hold more than one +physical compute channel: on the M5 Pro (J714), and neither on the M5 Max, +the M5 Ultra and the M5 (J716C, J775D, J813), whose boards run one firmware +compute queue per command queue, nor on GPUs that never select an M5 board +(G17P), so userspace keeps its own sibling queues there; that the decision reads +the board's channel count alone, never its encoding forms; that GET_PARAMS +reports it from the probed board's channel count on every G17; and that the bit +is distinct from every other feature bit. + +Each mutation drops one part of the rule and must fail an assertion of the +compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = ASAHI / 'g17' +UAPI = ROOT / 'include/uapi/drm/asahi_drm.h' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +REPORTED = ' | compute_channel_features(pairs::compute_channels_per_owner());\n' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + 'always-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if channels > 0 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'never-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if false {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'not-reported': [('mod', ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT\n' + REPORTED, + ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT;\n')], + 'per-board-gate': [('mod', REPORTED, + ' | compute_channel_features(pairs::COMPUTE_CHANNELS_MAX as u8);\n')], + 'forms-gate': [('fw', ' board.compute_channels() > 1\n', + ' board.compute_channels() > 1 || !board.g17d_forms()\n')], + 'max-channels': [('pairs', ' COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed);', + ' COMPUTE_CHANNELS.store(COMPUTE_CHANNELS_MAX as u8, Relaxed);')], + 'multi-channel-max': [('initdata', ' host_only_render_kicks: true,\n compute_channels: 1,\n', + ' host_only_render_kicks: true,\n compute_channels: 3,\n')], + 'colliding-bit': [('uapi', '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42)', + '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 39)')], + 'unsynced-binding': [('file', ' uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64;', + ' uapi::DRM_ASAHI_FEATURE_ASYNC_SUBMIT as u64;')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'mod': (G17 / 'mod.rs').read_text(), + 'fw': (G17 / 'fw/m5/compute.rs').read_text(), + 'file': (ASAHI / 'file.rs').read_text(), + 'uapi': UAPI.read_text(), + 'initdata': (G17 / 'fw/m5/initdata.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, mod, fw, file, uapi, initdata = (files[k] for k in ('pairs', 'mod', 'fw', 'file', 'uapi', 'initdata')) + + # Every board's own channel count, following `..BASE` for a board that inherits it. + boards = {} + for name, body in re.findall(r'^pub\(crate\) const (\w+): Board = Board \{\n(.*?)^\};', initdata, re.M | re.S): + own = re.search(r'^ compute_channels: (\d+),$', body, re.M) + base = re.search(r'^ \.\.(\w+)$', body, re.M) + assert own or base, name + boards[name] = int(own.group(1)) if own else boards[base.group(1)] + assert set(boards) == {'J714', 'J716C', 'J775D', 'J813', 'J813_26B123'}, boards + board_table = ',\n'.join(f' ("{name}", {n})' for name, n in boards.items()) + channels_fn = item(initdata, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + bits = re.findall(r'^\s*(DRM_ASAHI_FEATURE_\w+)\s*=\s*\(1U?L{0,2}\)\s*<<\s*(\d+),', uapi, re.M) + bits += re.findall(r'^#define\s+(DRM_ASAHI_FEATURE_\w+)\s+\(\(1ULL\)\s*<<\s*(\d+)\)', uapi, re.M) + names = [name for name, _ in bits] + uapi_mod = '\n'.join(f' pub const {name}: u64 = 1 << {bit};' for name, bit in bits) + table = ',\n'.join(f' ("{name}", 1u64 << {bit})' for name, bit in bits) + + pairs_code = '\n'.join([ + re.search(r'pub\(crate\) const COMPUTE_CHANNELS_MAX: usize = \d+;', pairs).group(0), + re.search(r'const G17D_PAIRS: u8 = [^;]+;', pairs).group(0), + re.search(r'static PAIRS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + re.search(r'static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + item(pairs, 'pub(crate) fn select_board('), + item(pairs, 'pub(crate) fn per_owner('), + item(pairs, 'pub(crate) fn compute_channels_per_owner('), + ]).replace('pub(crate) ', 'pub ').replace('crate::g17::fw::m5::initdata::Board', 'crate::Board') \ + .replace('crate::g17::fw::m5::compute::multi_channel', 'crate::multi_channel') \ + .replace('RENDER_PAIRS_MAX as u8', '2u8') + features = item(mod, 'fn compute_channel_features(') + multi = item(fw, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + file_const = re.search(r'pub\(crate\) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 =\s*[^;]+;', file).group(0) + params = item(mod, 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global)') + structure = { + 'GET_PARAMS reports the bit from the probed channel count on every G17': ordered_ok( + params, 'params.features |=', '| crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT', REPORTED.strip(), + 'let variant = self.shared.variant;'), + 'the UAPI header defines the bit': 'DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL' in names, + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@UAPI@@', uapi_mod).replace('@@TABLE@@', table).replace('@@PAIRS@@', pairs_code) + .replace('@@FEATURES@@', features).replace('@@MULTI@@', multi).replace('@@FILE@@', file_const) + .replace('@@STRUCTURE@@', checks).replace('@@BOARDS@@', board_table) + .replace('@@CHANNELS@@', channels_fn)) + + +TEMPLATE = r''' +#![allow(dead_code)] +use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + +mod uapi { +@@UAPI@@ +} +const FEATURES: &[(&str, u64)] = &[ +@@TABLE@@ +]; + +mod file { + use crate::uapi; + @@FILE@@ +} + +pub struct Board { g17d: bool, compute_channels: u8 } +impl Board { + fn g17d_forms(&self) -> bool { self.g17d } + @@CHANNELS@@ +} +@@MULTI@@ + +/// The production boards and their `compute_channels`. +const BOARDS: &[(&str, u8)] = &[ +@@BOARDS@@ +]; + +mod pairs { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + @@PAIRS@@ +} + +@@FEATURES@@ + +/// What GET_PARAMS reports, as get_params() computes it. +fn reported() -> u64 { compute_channel_features(pairs::compute_channels_per_owner()) } + +fn main() { +@@STRUCTURE@@ + + // The bit is the header's and no other feature has it. + let bit = file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL; + assert_eq!(bit, uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL, "file.rs reports the header's bit"); + assert_eq!(bit.count_ones(), 1); + for (name, value) in FEATURES { + if *name != "DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL" { + assert_ne!(*value, bit, "{} shares the multi-channel bit", name); + } + } + + // A GPU that never selects an M5 board (G17P) has one channel per owner: no bit. + assert_eq!(pairs::compute_channels_per_owner(), 1); + assert_eq!(reported() & bit, 0, "single-channel G17P keeps its own sibling queues"); + // The production boards: only the M5 Pro holds several channels per owner, so only it + // reports the bit; the M5 Max, M5 Ultra and M5 run one firmware compute queue per queue. + for &(name, channels) in BOARDS { + let multi = name == "J714"; + assert!(channels >= 1 && usize::from(channels) <= pairs::COMPUTE_CHANNELS_MAX, "{}", name); + for g17d in [false, true] { + let board = Board { g17d, compute_channels: channels }; + assert_eq!(multi_channel(&board), multi, "{}: multi_channel()", name); + pairs::select_board(&board); + assert_eq!(pairs::compute_channels_per_owner(), channels, "{}: channels per owner", name); + assert_eq!(reported() & bit, if multi { bit } else { 0 }, "{}: reported", name); + } + } + assert_eq!(BOARDS.iter().find(|b| b.0 == "J714").unwrap().1 as usize, pairs::COMPUTE_CHANNELS_MAX, + "the M5 Pro holds the most channels"); + // Set exactly when an owner may hold more than one channel, and nothing else. + for channels in 0..=u8::MAX { + assert_eq!(compute_channel_features(channels), if channels > 1 { bit } else { 0 }); + } + + println!("PASS g17-compute-multi-channel-feature: reported exactly where a queue holds several compute channels"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-multi-channel-') as tmp: + path = Path(tmp) / 'feature.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-compute-owed-stamp-tests.py b/tools/asahi/g17-compute-owed-stamp-tests.py index c857199abad99e..edca687c3989b4 100644 --- a/tools/asahi/g17-compute-owed-stamp-tests.py +++ b/tools/asahi/g17-compute-owed-stamp-tests.py @@ -10,7 +10,9 @@ finished retires it on its record instead of failing its client; the commands behind it then retire past it; every retired command keeps its place and its descriptor until a stamp covers it; work that cannot retire that way is failed -as before. --mutation removes one part of that and must fail. +as before. Every retired kick with an exact execution record, and only those, +feeds its channel's run of heavy kicks once (g17/pairs.rs), which gates sibling +compute fan-out on M5 Pro. --mutation removes one part of that and must fail. """ from pathlib import Path import argparse @@ -79,6 +81,14 @@ def fixture(): 'pub(crate) fn owns_packet(', 'pub(crate) fn retired_held(', 'pub(crate) fn expire_stamp_wait(', 'pub(crate) fn timeout(', 'pub(crate) fn can_classify_timeout(']) + pairs = (G17 / 'pairs.rs').read_text() + hz = re.search(r'pub\(crate\) const COMMAND_TIMESTAMP_HZ: u64 = ([0-9_]+);', + (ROOT / 'hw/t8140.rs').read_text()).group(1) + gate = '\n'.join([f'pub(crate) const COMMAND_TIMESTAMP_HZ: u64 = {hz};'] + [ + re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', pairs).group(0) + for name in ['SIBLING_EXECUTION_NS', 'SIBLING_EXECUTION_TICKS', 'SIBLING_SUSTAINED_KICKS']] + [ + item(pairs, 'pub(crate) fn heavy_run('), item(pairs, 'pub(crate) fn sustained(')] + ).replace('crate::hw::t8140::resources::', '') backend = '\n'.join([ item(control, 'pub(super) fn defer_compute_timeout(').replace('pub(super) ', '', 1), item(control, 'fn retire_on_record('), @@ -127,6 +137,9 @@ def fixture(): pub(crate) mod job { pub(crate) trait Backend { fn fail_vm(&self, error: crate::Error); } } + pub(crate) mod pairs { +''' + gate + r''' + } } mod module_parameters { pub(crate) struct Parameter(pub(crate) u32); @@ -235,6 +248,7 @@ def fixture(): released: bool, owner: Option, released_at: u64, + heavy_run: u8, terminal: Option<(Arc, Error)>, fault_stamp: Option, timed_out_at: u64, @@ -246,6 +260,10 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> qos::Owner { qos::Owner } fn classify(&self, _: &dyn Fn(&Arc) -> recovery::Class) {} + fn clear_owner(&mut self, stamp_released_at: bool) { + self.owner = None; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + queue + r''' } @@ -259,6 +277,13 @@ def fixture(): .find(|queue| queue.owner() == Some(owner)) } fn compute_mut(&mut self, owner: u64) -> Option> { self.compute(owner) } + fn compute_for_packet(&self, owner: u64, packet: &Arc) -> Option> { + self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) + } + fn compute_for_packet_mut(&mut self, owner: u64, packet: &Arc) -> Option> { + self.compute_for_packet(owner, packet) + } /// Other VMs' heads, as render pairs and other queues give them. fn render_timeout_heads(&self) -> impl Iterator + '_ { self.render.iter().copied() @@ -308,7 +333,7 @@ def fixture(): retirement_proved: false, retired_by_teardown: false, spared_quarantine: false, spared_deferred: false, awaiting_witness: false, retire_pending: false, last_end: 0, previous: None, submitted: 0, retirement_ready: true, released: false, owner: Some(OWNER), - released_at: 0, terminal: None, fault_stamp: None, timed_out_at: 0, + released_at: 0, heavy_run: 0, terminal: None, fault_stamp: None, timed_out_at: 0, } } @@ -374,6 +399,60 @@ def fixture(): packet.completion.class.get() } + /// Execution record ticks of a kick lasting `us` microseconds. + fn ticks(us: u64) -> u64 { us * g17::pairs::COMMAND_TIMESTAMP_HZ / 1_000_000 } + + #[test] + fn only_exact_execution_records_feed_the_heavy_run() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(true); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + let p3 = publish(&mut q, 0x12, true); + record(&mut q, &p1, [1_000, 1_000 + heavy]); + record(&mut q, &p2, [1_000 + heavy, 1_000 + 3 * heavy]); + // p3 retires without a record: its synthesized envelope measures nothing. + q.graph.stamp.set(stamp_of(0x12)); + let b = backend(q, vec![]); + scan(&b); + assert!(result(&p3).is_some_and(|result| result.is_ok())); + with_queue(&b, |q| { + assert_eq!(q.active.len, 0); + assert_eq!(q.heavy_run, 2, "two exact heavy records, nothing from the recordless kick"); + assert!(g17::pairs::sustained(q.heavy_run)); + }); + // One short record ends the run. + let p4 = with_queue(&b, |q| { + let p4 = publish(q, 0x13, true); + record(q, &p4, [9_000, 9_000 + ticks(3)]); + q.graph.stamp.set(stamp_of(0x13)); + p4 + }); + scan(&b); + assert!(result(&p4).is_some()); + with_queue(&b, |q| assert_eq!(q.heavy_run, 0, "a short kick closes the gate")); + } + + #[test] + fn a_kick_held_for_its_stamp_is_measured_once() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(false); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + record(&mut q, &p1, [100, 100 + heavy]); + record(&mut q, &p2, [100 + heavy, 100 + 2 * heavy]); + let b = backend(q, vec![]); + // Late stamps: both retire on their records and stay held for their stamps. + advance(60 * MS); + scan(&b); + assert!(result(&p1).is_some() && result(&p2).is_some()); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (2, 2))); + with_queue(&b, |q| q.graph.stamp.set(stamp_of(0x11))); + scan(&b); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (0, 2), + "releasing a held descriptor measures nothing again")); + } + #[test] fn a_finished_head_whose_stamp_never_comes_retires_and_the_queue_moves_on() { let mut q = queue(false); @@ -654,7 +733,7 @@ def fixture(): MUTATIONS = { 'own-finished': [('_ if own.finished => Decision::Retire,', '_ if own.finished => Decision::Own,')], 'no-retire-glue': [('verdict.decision = self.retire_on_record(firmware, packet, &mut deferred)?;', '')], - 'retire-unchecked': [('if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) {', + 'retire-unchecked': [('if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) {', 'if false {')], 'no-expiry': [('if observed_at == Some(STAMP_WAIT_EXPIRED) {', 'if false {')], 'no-step-past': [('Ok(Some(_)) | Err(EAGAIN) if owed => at += 1,', 'Ok(Some(_)) | Err(EAGAIN) if owed => break,'), @@ -673,6 +752,13 @@ def fixture(): 'if !queue.owns_packet(packet) {')], 'no-owed-poll': [(' if at != 0 {\n // Owed stamps come without a completion event', ' if false {\n // Owed stamps come without a completion event')], + # A recordless retirement's synthesized envelope counts as an execution. + 'count-recordless': [('let execution = front.observed.map(|record| record.timestamps);', + 'let execution = Some(timestamps);')], + # Releasing a held descriptor measures the kick again. + 'count-owed-twice': [(' // The stamp now covers the held command: release its descriptor.\n', + ' // The stamp now covers the held command: release its descriptor.\n' + ' self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, 0, u64::MAX);\n')], } diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f26db9cfca578c..f763fd5b5ff803 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -35,18 +35,20 @@ def fixture(): impl Graph {fn set_owner(&mut self,_:&Context)->Result{Ok(())}} struct ReaderHint; impl ReaderHint {fn has_readers(&self,count:&AtomicU32)->bool{count.load(Ordering::Acquire)!=0}} struct Queue { - owner:Option,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, + owner:Option,channel_index:u8,binding_noted:bool,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, pool_phase:PoolPhase,release_sent_ns:Option,pool:Pool,binding:Option,previous:Option,graph:Graph, active:Fifo,replays:Fifo,quarantined:bool,released:bool,retirement_ready:bool, retired_by_teardown:bool,released_at:u64,exit:Option<()>,needs_fresh_backing:bool, source_hint:ReaderHint,source_readers:AtomicU32, } -fn idle(live:&Arc)->Queue{Queue{owner:Some(1),installed:true,growing:false,channel_error:false,growth:None, +fn idle(live:&Arc)->Queue{Queue{owner:Some(1),channel_index:0,binding_noted:false,installed:true,growing:false,channel_error:false,growth:None, free_list_generation:0,configuration:None,retained_owner:None,pool_phase:PoolPhase::Populated,release_sent_ns:None,pool:Pool{pages:Some(Pages(10,21)),fail:false}, binding:Some(Binding{context:Context::new(live),pool_alias:Some(1),descriptors:Some(2)}),previous:None,graph:Graph, active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} impl Queue { + fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} + fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} ''' + item(source,'pub(crate) fn release_owner(') + item(source,'pub(crate) fn reusable(') + '\n}\n' methods = '\n'.join(item(source, sig) for sig in ['pub(crate) fn begin_growth(', 'pub(crate) fn finish_growth(', 'pub(crate) fn growth_token(', 'pub(crate) fn abort_growth(', 'pub(crate) fn observe_vacancy(']) replace = item((ROOT / 'freelist.rs').read_text(), 'pub(crate) fn replace_pages(') diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py index e175d8cdfe702f..6ea0455c629176 100755 --- a/tools/asahi/g17-m5-cross-qid-direct-tests.py +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -290,7 +290,7 @@ def build_rust_harness(mutation=None): '(has_sources && !m5)' in compute_direct_fn and ordered_ok( compute_direct_fn, - 'let target_qid = cell.qid()?;', + 'let target_qid = cells[0].as_ref()?.qid()?;', 'self.resolve_direct_sources(port, generation, target_qid, sources)?', 'queue.qid() != target_qid', 'queue.publish(', diff --git a/tools/asahi/g17-m5-multiqueue-contention-tests.py b/tools/asahi/g17-m5-multiqueue-contention-tests.py index 23bf0512d2c3f1..40ff20930b2ed2 100755 --- a/tools/asahi/g17-m5-multiqueue-contention-tests.py +++ b/tools/asahi/g17-m5-multiqueue-contention-tests.py @@ -141,7 +141,7 @@ def build_harness(mutation=None): compute_direct, 'held.take()', 'let result = (|| {', - 'let mut queue = cell.lock()?;', + '.lock()?;', '})();', 'if outcome.is_none() && from_held {', '*held = Some(claim);', diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py new file mode 100755 index 00000000000000..5042a66f7e9170 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -0,0 +1,660 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 Pro in-context sibling compute channels. + +Compiles production `Context::next_compute_identity()`, `multi_channel()`, +channel selection, sibling admission, release ordering, and multi-channel exit +acknowledgment logic extracted from the G17 driver against host stubs, and +checks structural invariants for dedicated per-sibling ComputePool, lock-free +primary-first `compute_direct()` routing, and recovery/quarantine interaction: +1. Per-context atomic monotonic `(predecessor_id, current_id)` in `object_ids` + and aligned 1-based `submit_sequence == completion_ordinal` (including + multi-threaded concurrency proving zero ID collisions across sibling QIDs). +2. Dedicated per-sibling `ComputePool` (no `PoolBorrow`, no shared `0x7c/0x80` + pool control contention): a warm reusable sibling requires a same-VM + populated fitting pool, a vacant or other-VM idle queue is re-armed with + fresh backing, and a fresh sibling allocates its own `PoolBacking::new` + + pool descriptor (g17-m5-sibling-rearm-tests.py runs the re-arm path). +3. Lock-free `ComputeCell` atomic `(configuring, active_len, last_published)` + mirror updated via `QueueGuard::drop()`, with primary-first routing in + `compute_direct()` so idle channel 0 never locks sibling cell mutexes. +4. `multi_channel()` board selection, lazy sibling acquisition (cap at 3), + `select_compute_channel()` spread & dependent-kick stickiness, + sibling-before-primary release/rollback/growth order, and multi-channel + exit acknowledgment + `compute_bound()` / `release_compute_witness()`. + +The fan-out gate (input sources and short kicks stay on the primary channel) has +its own test, g17-m5-sibling-gate-tests.py; here the primary runs sustained heavy +work so every sibling path is open. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_harness(mutation=None): + freelist_src = (G17 / 'freelist.rs').read_text() + context_src = (G17 / 'context.rs').read_text() + fw_src = (G17 / 'fw/m5/compute.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + exit_src = (G17 / 'runtime/compute_exit.rs').read_text() + queue_src = (G17 / 'queue/compute.rs').read_text() + pairs_src = (G17 / 'pairs.rs').read_text() + min_in_flight = re.search(r'pub\(crate\) const SIBLING_MIN_IN_FLIGHT: usize = [0-9]+;', pairs_src).group(0) + overlaps_fn = (min_in_flight + '\n' + item(pairs_src, 'pub(crate) fn overlaps(')).replace('pub(crate) ', '') + + next_id_fn = item(context_src, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', 'pub ') + multi_fn = item(fw_src, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + initdata_src = (G17 / 'fw/m5/initdata.rs').read_text() + channels_fn = item(initdata_src, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + cell_struct = item(runtime_src, 'pub(super) struct ComputeCell') + cell_impl = item(runtime_src, 'impl ComputeCell') + guard_drop = item(runtime_src, 'impl Drop for QueueGuard<') + channels_of_fn = item(runtime_src, 'fn compute_channels_of(') + next_sib_fn = item(runtime_src, 'fn next_sibling_index(') + source_fn = item(runtime_src, 'fn sibling_source(') + source_enum = item(runtime_src, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + headroom_fn = item(runtime_src, 'fn has_compute_sibling_headroom(') + wants_sib_fn = item(runtime_src, 'fn wants_compute_sibling(') + bind_sib_fn = item(runtime_src, 'fn bind_reusable_sibling(') + try_add_sib_fn = item(runtime_src, 'fn try_add_compute_sibling(') + select_fn = item(runtime_src, 'fn select_compute_channel(') + release_fn = item(runtime_src, 'pub(super) fn release_compute(') + ack_exit_fn = item(exit_src, 'pub(super) fn acknowledge_compute_exit(') + pub_exit_fn = item(exit_src, 'fn publish_compute_exit(') + rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(') + grow_fn = item(runtime_src, 'fn grow_compute(') + drain_sib_fn = item(runtime_src, 'fn drain_compute_siblings(') + direct_fn = item(runtime_src, 'fn compute_direct(') + readiness_fn = item(runtime_src, 'fn compute_readiness(&self, packet:') + remember_fn = item(runtime_src, 'fn remember_direct(') + claim_outer_fn = item(runtime_src, 'fn claim_outer(') + bound_fn = item(runtime_src, 'fn compute_bound(') + witness_fn = item(runtime_src, 'fn release_compute_witness(') + parent_pred_start = queue_src.index('let parent_retired = self.active.len == 0') + parent_pred_end = queue_src.index('let m5_args =', parent_pred_start) + parent_pred = queue_src[parent_pred_start:parent_pred_end] + m5_args_start = parent_pred_end + m5_args_end = queue_src.index('let mut m5_dependency_types =', m5_args_start) + m5_args_block = queue_src[m5_args_start:m5_args_end] + + if mutation == 'fixed-object-ids': + next_id_fn = ( + 'pub fn next_compute_identity(&self) -> (u32, u64) {\n' + ' let next = self.compute_ordinal.fetch_add(1, Ordering::AcqRel).wrapping_add(1);\n' + ' (next, 0x0000_0001_0000_0001)\n' + '}' + ) + elif mutation == 'primary-before-sibling': + release_fn = release_fn.replace('for primary_pass in [false, true]', + 'for primary_pass in [true, false]', 1) + elif mutation == 'exit-ack-stops-first': + ack_exit_fn = ack_exit_fn.replace( + 'matched |= queue.acknowledge_exit(cookie);', + 'if queue.acknowledge_exit(cookie) { return; }', + 1, + ) + elif mutation == 'direct-allows-multi-barrier': + direct_fn = direct_fn.replace( + ' || (bound_count > 1 && packet.order.wait_through[1].is_some())\n', '', 1) + elif mutation == 'direct-blocks-sibling': + direct_fn = direct_fn.replace( + ' } else if can_add_sibling && all_busy {\n' + ' return None;\n' + ' } else {\n', + ' } else {\n', + 1, + ) + elif mutation == 'direct-locks-sibling-when-idle': + direct_fn = direct_fn.replace( + 'let (configuring, active, last_published) = cell.load_hint();', + 'let queue = cell.lock()?; let (configuring, active, last_published) = (queue.configuring(), queue.active_len() as u32, queue.last_published());', + 1, + ) + elif mutation == 'direct-skips-multi': + direct_fn = direct_fn.replace( + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1', + 1, + ) + elif mutation == 'same-qid-pipelined': + parent_pred = parent_pred.replace( + 'parent_dependency(board, parent_retired)', + 'parent_dependency(board, true)', + 1, + ) + + reg_methods = '\n'.join([ + channels_of_fn, + next_sib_fn, + source_fn, + headroom_fn, + wants_sib_fn, + select_fn, + release_fn, + ]) + reg_methods = reg_methods.replace('pub(super) ', 'pub ') + reg_methods = reg_methods.replace('super::job::Packet', 'Packet') + reg_methods = reg_methods.replace('super::freelist::ComputeCapacity', 'ComputeCapacity') + reg_methods = reg_methods.replace('super::pairs::', '') + + ack_code = ack_exit_fn.replace('pub(super) ', 'pub ') + ack_code = re.sub(r'crate::g17::trace::teardown\([^;]*\);', '', ack_code) + + # Structural invariant booleans compiled into the host binary so every check + # fails with a Rust assertion panic (exit 101) when violated. + dedicated_pool_ok = ( + 'PoolBorrow' not in freelist_src + and 'PoolBorrow' not in queue_src + and 'shared_pool' not in queue_src + and 'PoolBacking::new(' in try_add_sib_fn + and 'install_compute_pool(pool.pool_descriptor()?)' in try_add_sib_fn + and ordered_ok(source_fn, 'if queue.pool_vacant() {', '} else if queue.pool_serves(vm) {', + '!queue.pool_fits(required)', '&mut warm') + and 'let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else' in bind_sib_fn + and 'qid,\n channel_index,\n required,' in try_add_sib_fn + ) + identity_wired_ok = ( + 'packet.context.next_compute_identity()' in parent_pred + and 'object_ids: m5_object_ids,' in m5_args_block + and 'submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 },' in m5_args_block + and 'completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal),' in m5_args_block + and 'peek_compute_ordinal' not in queue_src + ) + cell_atomic_ok = ( + 'active_len: core::sync::atomic::AtomicU32' in cell_struct + and 'configuring: core::sync::atomic::AtomicBool' in cell_struct + and 'last_published: core::sync::atomic::AtomicU64' in cell_struct + and 'fn sync_stats(' in cell_impl + and 'fn load_hint(' in cell_impl + and 'self.cell.sync_stats(Some(queue));' in guard_drop + ) + rollback_order_ok = ordered_ok( + rollback_fn, + 'for primary_pass in [false, true]', + 'queue.is_primary() == primary_pass', + '.rollback_unpublished(self.owner, &self.context)?', + ) + grow_releases_siblings_ok = ( + ordered_ok( + drain_sib_fn, + 'queue.owner() == Some(owner) && !queue.is_primary()', + 'if busy {', + 'return Err(EAGAIN);', + '.release_owner()?', + 'entry.queue.take()', + ) + and ordered_ok( + grow_fn, + 'retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?;', + 'firmware.queues.compute_primary(self.owner)', + 'for item in retired_siblings {', + 'self.finish_uninstalled_compute(Some(item))?;', + ) + ) + exit_propagates_ok = ordered_ok( + pub_exit_fn, + 'if context.kill_published()', + 'queue.record_exit(cookie, now);', + 'if other.exit_candidate(context, age)', + 'other.record_exit(cookie, now);', + ) + # Lock-free primary-first selection: compute_direct must NEVER call cell.lock() during + # channel selection, must short-circuit to channel 0 when primary_active == 0 && !primary_configuring, + # and must only lock target_cell once. + select_section = direct_fn[:direct_fn.index('let target_cell =')] + direct_guards_ok = ( + 'cell.lock()' not in select_section + and ordered_ok( + direct_fn, + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1 && packet.order.wait_through[1].is_some()', + 'let (primary_configuring, primary_active, _) = primary.load_hint();', + 'if primary_active == 0 && !primary_configuring', + 'let (configuring, active, last_published) = cell.load_hint();', + 'if can_add_sibling && all_busy', + 'self.outer_compute.lock()', + 'claim.remaining() != 0 && claim.priority() == usize::from(priority)', + 'queue.pool_fits(required)', + 'm5 && queue.outer_slots() != 1', + 'self.context.compute_binding_count() as usize != cached_count', + ) + and 'registry.compute_cells(self.owner)' in remember_fn + ) + readiness_and_outer_ok = ( + ordered_ok( + readiness_fn, + 'bound_count <= super::pairs::COMPUTE_CHANNELS_MAX', + 'cells[1..].iter().flatten()', + 'queue.pool_fits(required)', + 'queue.claim()', + 'self.claim_compute_outer_direct(outer_slots)', + ) + and '.map(|queue| queue.outer_slots())' in claim_outer_fn + and '.max()' in claim_outer_fn + ) + same_qid_serialized_ok = ( + 'parent_dependency(board, parent_retired)' in parent_pred + and 'same_context_independent' not in parent_pred + ) + multi_witness_and_bound_ok = ( + 'self.compute_primary(owner)' in bound_fn + and '!queue.is_primary()' in bound_fn + and 'queue.pool_fits(required)' in bound_fn + and 'pending |= queue.spared_pending();' in witness_fn + ) + + return f''' +#![allow(dead_code, unused_variables, unused_mut)] +use std::cell::RefCell; +use std::collections::HashSet; +use std::sync::{{Arc, atomic::{{AtomicU32, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EAGAIN: i32 = -11; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +type Result = std::result::Result; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +{source_enum} + +{overlaps_fn} + +struct Board {{ + compute_channels: u8, +}} +impl Board {{ + {channels_fn} +}} + +{multi_fn} + +struct Order {{ + wait_through: [Option; 2], +}} +struct Completion {{ + sources: Option<()>, +}} +impl Completion {{ + fn sources(&self) -> Option<&()> {{ self.sources.as_ref() }} +}} +struct Packet {{ + order: Order, + completion: Completion, +}} + +struct Context {{ + id: u32, + vm_id: u32, + compute_ordinal: AtomicU32, +}} +impl Context {{ + fn new(id: u32, vm_id: u32) -> Arc {{ + Arc::new(Self {{ id, vm_id, compute_ordinal: AtomicU32::new(0) }}) + }} + fn vm(&self) -> u32 {{ self.vm_id }} + {next_id_fn} +}} + +struct Queue {{ + qid: u8, + owner: Option, + channel_index: u8, + active_len: usize, + replays: usize, + configuring: bool, + last_published: u64, + sustained: bool, + reusable: bool, + needs_fresh_backing: bool, + pool_vacant: bool, + pool_vm: u32, + pool_cap: u32, + has_ring: bool, + context: Option>, + exit_cookie: Option, + exit_acked: bool, + unpublished: bool, + released_log: Arc>>, +}} +impl Queue {{ + fn qid(&self) -> u8 {{ self.qid }} + fn owner(&self) -> Option {{ self.owner }} + fn channel_index(&self) -> u8 {{ self.channel_index }} + fn is_primary(&self) -> bool {{ self.channel_index == 0 }} + fn active_len(&self) -> usize {{ self.active_len }} + fn has_replays(&self) -> bool {{ self.replays != 0 }} + fn configuring(&self) -> bool {{ self.configuring }} + fn last_published(&self) -> u64 {{ self.last_published }} + fn sustained(&self) -> bool {{ self.sustained }} + fn reusable(&self) -> bool {{ self.reusable }} + fn needs_fresh_backing(&self) -> bool {{ self.needs_fresh_backing }} + fn pool_vacant(&self) -> bool {{ self.pool_vacant }} + fn pool_serves(&self, vm: u32) -> bool {{ self.pool_vm == vm }} + fn pool_fits(&self, req: ComputeCapacity) -> bool {{ self.pool_cap >= req.0 }} + fn has_ring(&self) -> bool {{ self.has_ring }} + fn context(&self) -> Option<&Arc> {{ self.context.as_ref() }} + fn rearm_open(&self, _owner: u64) -> bool {{ true }} + fn released_at(&self) -> u64 {{ self.last_published }} + fn vacancy_pending(&self) -> bool {{ false }} + fn release_owner(&mut self) -> Result {{ + self.released_log.borrow_mut().push((self.qid, self.channel_index)); + self.owner = None; + self.channel_index = 0; + Ok(self.unpublished) + }} + fn acknowledge_exit(&mut self, cookie: u64) -> bool {{ + if self.exit_cookie == Some(cookie) {{ + self.exit_acked = true; + true + }} else {{ + false + }} + }} +}} + +struct Slot(Option>); +impl Slot {{ + fn as_deref(&self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow()) + }} + fn as_deref_mut(&mut self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow_mut()) + }} +}} + +struct Entry {{ + reservation: Reservation, + queue: Slot, +}} +#[derive(Copy, Clone)] +struct Reservation {{ id: u8 }} + +struct Qids {{ fit: bool, cancelled: Vec }} +impl Qids {{ + fn compute_fits(&self, _queues: usize) -> bool {{ self.fit }} + fn cancel_unpublished(&mut self, id: u8) -> Result {{ + self.cancelled.push(id); + Ok(()) + }} +}} + +struct Admission {{ queues: u32 }} +impl Admission {{ fn queues(&self) -> u32 {{ self.queues }} }} + +struct Teardown {{ releasing_id: Option, render_acked: bool }} +impl Teardown {{ + fn releasing(&self, ctx: &Arc) -> bool {{ self.releasing_id == Some(ctx.id) }} + fn acknowledge_render_kill(&mut self, _cookie: u64) -> bool {{ + self.render_acked = true; + true + }} +}} + +static RENDER_KILLS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)]; +const RENDER_KILL_ACKNOWLEDGED: usize = 0; + +struct Registry {{ + compute: Vec>, + qids: Qids, + admission: Admission, + teardown: Teardown, + build_room_noted: usize, +}} + +impl Registry {{ + fn note_build_room(&mut self) {{ self.build_room_noted += 1; }} + {reg_methods} + {ack_code} +}} + +fn make_entry(q: Queue) -> Option {{ + let qid = q.qid; + Some(Entry {{ + reservation: Reservation {{ id: qid }}, + queue: Slot(Some(RefCell::new(q))), + }}) +}} + +fn test_atomic_compute_identity() {{ + let ctx = Context::new(1, 100); + // Sequential check: 1-based ordinal with monotonic (predecessor_id << 32) | current_id. + assert_eq!(ctx.next_compute_identity(), (1, (1u64 << 32) | 1)); + assert_eq!(ctx.next_compute_identity(), (2, (1u64 << 32) | 2)); + assert_eq!(ctx.next_compute_identity(), (3, (2u64 << 32) | 3)); + assert_eq!(ctx.next_compute_identity(), (4, (3u64 << 32) | 4)); + + // Concurrent check across 4 threads simulating direct sibling compute kicks: + // every kick must receive a unique ordinal and a unique non-zero current_id. + let shared = Context::new(2, 200); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = shared.clone(); + threads.push(std::thread::spawn(move || {{ + let mut out = Vec::with_capacity(500); + for _ in 0..500 {{ + out.push(c.next_compute_identity()); + }} + out + }})); + }} + let mut ordinals = HashSet::new(); + let mut current_ids = HashSet::new(); + for t in threads {{ + for (ord, ids) in t.join().unwrap() {{ + let pred = (ids >> 32) as u32; + let cur = ids as u32; + assert_ne!(pred, 0); + assert_ne!(cur, 0); + assert_eq!(cur, ord); + assert!(ordinals.insert(ord), "duplicate shared ordinal {{}}", ord); + assert!(current_ids.insert(cur), "duplicate object_ids current_id {{}}", cur); + }} + }} + assert_eq!(ordinals.len(), 2000); +}} + +fn main() {{ + // 1. Structural guards for dedicated pools, monotonic identities, lock-free ComputeCell hints, + // compute_direct primary-first routing, grow, rollback, and exit propagation. + assert!({str(dedicated_pool_ok).lower()}, "siblings must own dedicated ComputePools with no PoolBorrow"); + assert!({str(identity_wired_ok).lower()}, "multi-channel M5 compute must wire atomic next_compute_identity to object_ids, submit_sequence, and completion_ordinal"); + assert!({str(cell_atomic_ok).lower()}, "ComputeCell must mirror active_len/configuring/last_published atomically via QueueGuard::drop"); + assert!({str(rollback_order_ok).lower()}, "rollback_unpublished_compute must roll back siblings before primary"); + assert!({str(grow_releases_siblings_ok).lower()}, "grow_compute must drain and release siblings before primary growth"); + assert!({str(exit_propagates_ok).lower()}, "publish_compute_exit must propagate kill cookie across all channels of context"); + assert!({str(direct_guards_ok).lower()}, "compute_direct must use lock-free primary-first routing without locking sibling cells, guard barriers, reuse outer_compute, and yield when siblings can be added"); + assert!({str(readiness_and_outer_ok).lower()}, "compute_readiness/claim_outer must validate all bound channels and take max outer_slots"); + assert!({str(same_qid_serialized_ok).lower()}, "multi-channel M5 Pro must keep COMPLETION_DEPENDENCY while a physical QID has an active parent"); + assert!({str(multi_witness_and_bound_ok).lower()}, "compute_bound and release_compute_witness must inspect all channels of owner"); + + // 2. Per-context monotonic object_ids & aligned submit_sequence == completion_ordinal. + test_atomic_compute_identity(); + + // 3. multi_channel() board selection. + assert!(multi_channel(&Board {{ compute_channels: 3 }})); + assert!(multi_channel(&Board {{ compute_channels: 2 }})); + assert!(!multi_channel(&Board {{ compute_channels: 1 }})); + + // 4. Lazy sibling admission + dedicated-pool headroom + round-robin selection + release order. + let ctx = Context::new(1, 77); + let req = ComputeCapacity(16); + let log = Arc::new(RefCell::new(Vec::new())); + let mut reg = Registry {{ + compute: vec![ + make_entry(Queue {{ + qid: 10, owner: Some(1), channel_index: 0, active_len: 1, replays: 0, + configuring: false, last_published: 100, sustained: true, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }}), + make_entry(Queue {{ + qid: 11, owner: Some(1), channel_index: 1, active_len: 1, replays: 0, + configuring: false, last_published: 101, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: true, released_log: log.clone(), + }}), + ], + qids: Qids {{ fit: true, cancelled: Vec::new() }}, + admission: Admission {{ queues: 1 }}, + teardown: Teardown {{ releasing_id: None, render_acked: false }}, + build_room_noted: 0, + }}; + assert_eq!(reg.compute_channels_of(1), (2, 0b11)); + assert_eq!(reg.next_sibling_index(1, 3), Some(2)); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + + // When surplus QIDs are exhausted, a reusable queue must provide the sibling. + reg.qids.fit = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + // An idle reusable queue still holding another VM's pool counts: it is given back and + // re-armed for this VM (no lockout once earlier clients took every QID). + reg.compute.push(make_entry(Queue {{ + qid: 13, owner: None, channel_index: 0, active_len: 0, replays: 0, + configuring: false, last_published: 10, sustained: false, reusable: true, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 99, pool_cap: 16, + has_ring: true, context: None, exit_cookie: None, exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Foreign(13))); + // So does a vacant one, before it. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = true; + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Vacant(13))); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = false; + // A queue with an owner never does. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = true; + // Same-VM fitting populated reusable queue DOES count, first. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vm = 77; + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Warm(13))); + // Undersized same-VM pool does NOT count. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_cap = 8; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute.pop(); + reg.qids.fit = true; + + // If a bound channel has pending replays, refuse new siblings. + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 1; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 0; + + // Add 3rd channel (index 2): cap reached, wants_compute_sibling becomes false. + reg.compute.push(make_entry(Queue {{ + qid: 12, owner: Some(1), channel_index: 2, active_len: 0, replays: 0, + configuring: false, last_published: 50, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert_eq!(reg.next_sibling_index(1, 3), None); + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + + // Independent packet picks least-loaded idle sibling (qid 12). + let indep = Packet {{ order: Order {{ wait_through: [None, None] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // When all 3 have equal active_len=1, oldest last_published (qid 12, lp=50) wins. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 1; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // Dependent packet when only ONE channel is active stays on that sole active channel. + reg.compute[0].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + let dep = Packet {{ order: Order {{ wait_through: [None, Some(42)] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &dep), Some(11)); + + // 5. Multi-channel exit acknowledgment must mark ALL channels sharing the cookie. + reg.acknowledge_compute_exit(0xabc); + for slot in 0..3 {{ + assert!(reg.compute[slot].as_ref().unwrap().queue.as_deref().unwrap().exit_acked, + "channel slot {{}} did not receive shared exit cookie ack", slot); + }} + assert!(!reg.teardown.render_acked); + + // 6. Sibling-before-primary release order. + reg.release_compute(1).unwrap(); + let entries = log.borrow(); + assert_eq!(entries.len(), 3); + assert_ne!(entries[0].1, 0, "first release must be a sibling"); + assert_ne!(entries[1].1, 0, "second release must be a sibling"); + assert_eq!(entries[2].1, 0, "primary must be released last"); + assert_eq!(reg.qids.cancelled, vec![11]); + assert!(reg.compute[1].is_none()); + + println!("PASS g17-m5-sibling-compute: all checks passed"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=[ + 'fixed-object-ids', + 'primary-before-sibling', + 'exit-ack-stops-first', + 'direct-allows-multi-barrier', + 'direct-blocks-sibling', + 'direct-locks-sibling-when-idle', + 'direct-skips-multi', + 'same-qid-pipelined', + ]) + args = ap.parse_args() + + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-sib-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + cc = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if cc.returncode != 0: + sys.stderr.write(cc.stderr) + return cc.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py new file mode 100755 index 00000000000000..b943c2a6d9c153 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for the M5 Pro sibling compute fan-out gate. + +Compiles the production gate against host stubs: the heavy-kick run in +drivers/gpu/drm/asahi/g17/pairs.rs, `Backend::fans_out()`, the lock-free channel +selection section of `compute_direct()`, the `ComputeCell` hint mirror, and the +registry's `select_compute_channel()` / `wants_compute_sibling()`. It checks: + +a. A command with cross-queue input sources never leaves the primary channel and + never brings up a sibling, on the direct and the device-mutex paths, and the + direct path still resolves those sources before routing (published sources, + binding loans). +b. Kicks whose firmware execution records stay under the heavy threshold stream + down the primary ring: no sibling routing, no detour to the device-mutex path + to add one, no new sibling; one long kick among short ones does not open the + gate and one short kick closes it. +c. Sustained heavy kicks fan out onto an idle sibling (or ask for one when every + channel is busy) only once two kicks of the owner are already in flight, so a + kick queued behind one in flight stays on the primary ring; each sibling has + its own compute pool, with monotonic per-context ordinals and object ids, and + the gate is read through the primary cell's lock-free hint. +d. The sibling channels keep the published-source, binding-loan and idle + housekeeping paths of the queues they share a context with. + +Each mutation restores one old behaviour or drops one part of the rule, and must +fail an assertion of the compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = ASAHI / 'g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def const(source, name): + match = re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', source, re.S) + assert match, name + return match.group(0).replace('pub(crate) ', '') + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # (a) a command with sources fans out like any other. + 'sources-fan-out': [('runtime', ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' && primary_sustained()')], + 'select-sources-anywhere': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) {\n return Some(qid);\n }\n', '')], + # (b) short kicks fan out. + 'tiny-fans-out': [('pairs', 'if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS {', 'if end >= start {')], + 'no-sustain-run': [('pairs', 'run >= SIBLING_SUSTAINED_KICKS', 'run >= 1')], + 'short-keeps-run': [('pairs', ' } else {\n 0\n }\n}', ' } else {\n run\n }\n}')], + 'direct-ignores-gate': [('runtime', 'let target_idx = if cached_count == 1 || !fans_out {', 'let target_idx = if cached_count == 1 {')], + 'direct-can-add-ungated': [('runtime', ' let can_add_sibling = fans_out\n && cached_count', + ' let can_add_sibling = packet.order.wait_through[1].is_none()\n && cached_count')], + 'wants-ignores-sustained': [('runtime', 'if !sustained_primary || !all_busy', 'if !all_busy')], + 'select-ignores-sustained': [('runtime', ' if let Some((qid, false)) = primary {\n return Some(qid);\n }\n', '')], + # (c) the lock-free hint loses the gate, or the gate takes a lock first. + 'cell-drops-sustained': [('runtime', 'self.sustained.store(queue.sustained(), Ordering::Release);', + 'self.sustained.store(false, Ordering::Release);')], + 'fans-out-locks-first': [('runtime', ' self.compute_channels > 1\n && packet.order.wait_through[1].is_none()\n' + ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' primary_sustained()\n && self.compute_channels > 1\n' + ' && packet.order.wait_through[1].is_none()\n && packet.completion.sources().is_none()')], + # (c) A kick overlaps the owner's work while only one kick is in flight. + 'overlap-at-one': [('pairs', 'in_flight >= SIBLING_MIN_IN_FLIGHT', 'in_flight >= 1')], + 'direct-ignores-in-flight': [('runtime', ' if !super::pairs::overlaps(in_flight) {\n 0\n } else if', + ' if false {\n 0\n } else if')], + 'select-ignores-in-flight': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) {\n' + ' return Some(qid);\n }\n', '')], + 'wants-ignores-in-flight': [('runtime', ' || !super::pairs::overlaps(in_flight) {', ' {')], + 'detour-at-one': [('runtime', ' && super::pairs::overlaps(queue.active_len()))', + ' && (queue.active_len() != 0 || queue.configuring()))')], + # A reused channel keeps the previous owner's run of heavy kicks. + 'keep-run-across-owners': [('queue', ' self.channel_index = channel_index;\n self.heavy_run = 0;\n', + ' self.channel_index = channel_index;\n')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, runtime, queue = files['pairs'], files['runtime'], files['queue'] + context = (G17 / 'context.rs').read_text() + hw = (ASAHI / 'hw/t8140.rs').read_text() + events = (G17 / 'runtime/events.rs').read_text() + submit = (G17 / 'runtime/render/submit.rs').read_text() + + hz = const(hw, 'COMMAND_TIMESTAMP_HZ') + gate = '\n'.join([ + const(pairs, 'SIBLING_EXECUTION_NS'), + const(pairs, 'SIBLING_EXECUTION_TICKS').replace('crate::hw::t8140::resources::', ''), + const(pairs, 'SIBLING_SUSTAINED_KICKS'), + const(pairs, 'SIBLING_MIN_IN_FLIGHT'), + item(pairs, 'pub(crate) fn heavy_run('), + item(pairs, 'pub(crate) fn sustained('), + item(pairs, 'pub(crate) fn overlaps('), + ]).replace('pub(crate) ', '') + next_id = item(context, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', '') + queue_sustained = item(queue, 'pub(crate) fn sustained(&self)').replace('pub(crate) ', 'pub ') \ + .replace('crate::g17::pairs::sustained', 'crate::sustained') + sync_stats = item(runtime, 'fn sync_stats(') + load_hint = item(runtime, 'pub(super) fn load_hint(').replace('pub(super) ', '') + cell_sustained = item(runtime, 'pub(super) fn sustained(&self)').replace('pub(super) ', '') + fans_out = item(runtime, 'fn fans_out(').replace('super::job::Packet', 'Packet') + direct = item(runtime, 'fn compute_direct(') + select_start = direct.index(' let primary = cells[0].as_ref()?;') + select_end = direct.index(' let target_cell = cells[target_idx].as_ref()?;') + route = direct[select_start:select_end].replace('super::pairs::', '') + registry = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn sibling_source(', + 'fn has_compute_sibling_headroom(', 'fn wants_compute_sibling(', 'fn select_compute_channel(', + ]).replace('super::job::Packet', 'Packet').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '') + sibling_source = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + inline = item(runtime, 'fn compute_inline(') + packet_fn = item(runtime, ' fn compute_packet(') + readiness = item(runtime, 'fn compute_readiness(&self, packet:') + bind_owner = item(queue, 'fn bind_owner_channel(') + clear_owner = item(queue, 'fn clear_owner(') + publish = item(queue, 'pub(in crate::g17) fn publish_with_native_waits(') + retire_arm_start = queue.index('Ok(Some((timestamps, stampless))) => {') + retire_arm = queue[retire_arm_start:queue.index('Ok(None) | Err(EAGAIN) => {', retire_arm_start)] + render_deps = item(submit, 'fn render_dependencies(') + + # Structural rules that the compiled part cannot see, each a Rust assertion below. + structure = { + # (a) Both device-mutex paths ask the gate before any sibling work. + 'mutex paths ask fans_out before binding a sibling': ( + ordered_ok(inline, 'if self.fans_out(packet, || {', 'compute_primary(self.owner)', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(') + and ordered_ok(packet_fn, 'if !sibling_tried', '&& self.fans_out(packet, || {', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(', 'self.try_add_compute_sibling(required, &admission)?') + and 'packet.order.wait_through[1].is_none()\n {' not in packet_fn), + # (a, d) Direct sources still resolve lock-free from their PublishedSource snapshots with + # binding loans before any routing, and the holds follow the publication. + 'direct sources resolve before routing, holds follow publication': ordered_ok( + direct, 'if (has_sources && !m5)', 'let generation = port.generation();', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'let fans_out = self.fans_out(packet, || primary.sustained());', + 'let target_cell = cells[target_idx].as_ref()?;', 'direct_frontier.as_slice()', + 'if packet.is_published() {', 'sources.set_holds(direct_holds);', 'drop(direct_holds);'), + 'readiness claims the primary for M5 sources': ordered_ok( + readiness, 'let sources_checked =', '(!sources_checked || self.context.is_m5())', + 'cells[1..].iter().flatten()', 'queue.claim()', 'self.hold_claim(Some(primary));'), + # (b, c) The direct path detours to the device-mutex path for a sibling only when it may + # add one: a busy single channel under a closed gate, or with a single kick in flight, + # keeps publishing directly. + 'direct detours only when it may add a sibling': ordered_ok( + direct, '(cached_count == 1\n && can_add_sibling\n' + ' && super::pairs::overlaps(queue.active_len()))'), + # (b, c) The run is measured on exact execution records only, once per retired kick, + # and starts over for every owner. + 'only exact records measure a kick': ordered_ok( + retire_arm, 'let execution = front.observed.map(|record| record.timestamps);', + 'defer(match producers {', 'self.retire_pending = false;', + 'if let Some([start, end]) = execution {', + 'self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end);'), + 'a new owner starts a new run': ( + 'self.heavy_run = 0;' in clear_owner + and ordered_ok(bind_owner, 'self.channel_index = channel_index;', 'self.heavy_run = 0;')), + # (d) A sibling's own QID and source readers are what its PublishedSource names; the + # shared context keeps one ordinal sequence across channels. + 'siblings publish their own QID as a source': ordered_ok( + publish, 'packet.context.next_compute_identity()', + 'crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp)', + 'packet.completion.note_source_published(', 'readers: self.source_readers.clone(),'), + # (d) The deferred idle housekeeping counts every compute queue, siblings included, as + # in flight; renders wait on every compute channel of the owner. + 'idle housekeeping sees sibling work': ordered_ok( + events, '.compute', '.iter()', '.flatten()', '.filter_map(|entry| entry.queue.as_deref())', + '.any(|queue| queue.in_flight())', 'firmware.idle_check(now, in_flight)?'), + 'renders wait on every compute channel': ordered_ok( + render_deps, '.filter(|queue| queue.owner() == Some(owner))', '.compute_count', + 'dependencies.compute_count += 1;'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' + for name, ok in structure.items()) + + return (TEMPLATE + .replace('@@HZ@@', hz) + .replace('@@GATE@@', gate) + .replace('@@NEXT_ID@@', next_id) + .replace('@@QUEUE_SUSTAINED@@', queue_sustained) + .replace('@@SYNC_STATS@@', sync_stats) + .replace('@@LOAD_HINT@@', load_hint) + .replace('@@CELL_SUSTAINED@@', cell_sustained) + .replace('@@FANS_OUT@@', fans_out) + .replace('@@ROUTE@@', route) + .replace('@@REGISTRY@@', registry) + .replace('@@SIBLING_SOURCE@@', sibling_source) + .replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::{Cell, RefCell}; +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +const EIO: i32 = -5; +type Result = std::result::Result; + +@@HZ@@ +@@GATE@@ + +thread_local! { static NOW: Cell = Cell::new(1_000_000_000); } +fn now_ns() -> u64 { NOW.with(|now| now.get()) } + +/// Ticks of an execution record lasting `us` microseconds. +fn ticks(us: u64) -> u64 { us * COMMAND_TIMESTAMP_HZ / 1_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@SIBLING_SOURCE@@ + +struct Completion { sources: Option<()> } +impl Completion { fn sources(&self) -> Option<&()> { self.sources.as_ref() } } +struct Order { wait_through: [Option; 2] } +struct Packet { order: Order, completion: Completion } +fn packet(sources: bool, through: Option) -> Packet { + Packet { order: Order { wait_through: [None, through] }, + completion: Completion { sources: sources.then_some(()) } } +} + +struct Context { vm_id: u32, compute_ordinal: AtomicU32 } +impl Context { + fn new(vm_id: u32) -> Arc { Arc::new(Self { vm_id, compute_ordinal: AtomicU32::new(0) }) } + fn vm(&self) -> u32 { self.vm_id } + @@NEXT_ID@@ +} + +mod compute { + /// The routing-relevant state of one physical compute channel. + pub struct Queue { + pub qid: u8, pub owner: Option, pub channel_index: u8, pub active: usize, + pub replays: usize, pub configuring: bool, pub last_published: u64, pub heavy_run: u8, + pub reusable: bool, pub pool_vm: u32, pub pool_cap: u32, + } + impl Queue { + pub fn active_len(&self) -> usize { self.active } + pub fn configuring(&self) -> bool { self.configuring } + pub fn last_published(&self) -> u64 { self.last_published } + @@QUEUE_SUSTAINED@@ + } +} + +/// The hint fields of the production cell; the mutex-held queue is passed in. +struct ComputeCell { + active_len: AtomicU32, configuring: AtomicBool, last_published: AtomicU64, sustained: AtomicBool, +} +impl ComputeCell { + fn new() -> Arc { + Arc::new(Self { active_len: AtomicU32::new(0), configuring: AtomicBool::new(false), + last_published: AtomicU64::new(0), sustained: AtomicBool::new(false) }) + } + @@SYNC_STATS@@ + @@LOAD_HINT@@ + @@CELL_SUSTAINED@@ +} + +struct Backend { compute_channels: u8, sibling_backoff_until: AtomicU64, gate_asked: Cell } +impl Backend { + @@FANS_OUT@@ + /// compute_direct()'s lock-free channel selection: `None` sends the packet to the + /// device-mutex path, otherwise `(target channel, may add a sibling)`. + fn route(&self, packet: &Packet, cells: &[Option>; 3], cached_count: usize) + -> Option<(usize, bool)> + { +@@ROUTE@@ + Some((target_idx, can_add_sibling)) + } +} + +impl compute::Queue { + fn qid(&self) -> u8 { self.qid } + fn owner(&self) -> Option { self.owner } + fn channel_index(&self) -> u8 { self.channel_index } + fn is_primary(&self) -> bool { self.channel_index == 0 } + fn has_replays(&self) -> bool { self.replays != 0 } + fn reusable(&self) -> bool { self.reusable } + fn needs_fresh_backing(&self) -> bool { false } + fn pool_vacant(&self) -> bool { false } + fn rearm_open(&self, _: u64) -> bool { true } + fn released_at(&self) -> u64 { 0 } + fn vacancy_pending(&self) -> bool { false } + fn pool_serves(&self, vm: u32) -> bool { self.pool_vm == vm } + fn pool_fits(&self, required: ComputeCapacity) -> bool { self.pool_cap >= required.0 } + fn has_ring(&self) -> bool { true } + fn context(&self) -> Option<&Arc> { None } +} + +struct Slot(RefCell); +impl Slot { fn as_deref(&self) -> Option> { Some(self.0.borrow()) } } +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { fn queues(&self) -> u32 { 1 } } +struct Teardown; +impl Teardown { fn releasing(&self, _: &Arc) -> bool { false } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { +@@REGISTRY@@ +} + +const OWNER: u64 = 7; + +fn channel(qid: u8, channel_index: u8, active: usize, heavy_run: u8) -> compute::Queue { + compute::Queue { qid, owner: Some(OWNER), channel_index, active, replays: 0, configuring: false, + last_published: u64::from(qid), heavy_run, reusable: false, pool_vm: 70, pool_cap: 16 } +} + +fn registry(queues: Vec) -> Registry { + Registry { compute: queues.into_iter().map(|queue| Some(Entry { queue: Slot(RefCell::new(queue)) })).collect(), + qids: Qids { fit: true }, admission: Admission, teardown: Teardown } +} + +/// The cells compute_direct() caches, each hint mirrored from its queue by the production +/// sync_stats(), as the queue guard does when it drops. +fn cells(queues: &[compute::Queue]) -> [Option>; 3] { + let mut cells = [None, None, None]; + for queue in queues { + let cell = ComputeCell::new(); + cell.sync_stats(Some(queue)); + cells[usize::from(queue.channel_index)] = Some(cell); + } + cells +} + +fn backend() -> Backend { + Backend { compute_channels: 3, sibling_backoff_until: AtomicU64::new(0), gate_asked: Cell::new(0) } +} + +fn run_of(records_us: &[u64]) -> u8 { + records_us.iter().fold(0, |run, &us| heavy_run(run, 5_000, 5_000 + ticks(us))) +} + +fn main() { +@@STRUCTURE@@ + + // The threshold, from the record's 24 MHz command timestamps. + assert_eq!(SIBLING_EXECUTION_TICKS, ticks(SIBLING_EXECUTION_NS / 1_000)); + assert_eq!(SIBLING_EXECUTION_TICKS, 2_400, "100 us at 24 MHz"); + + // (b) Short kicks never build a run; one long kick among short ones does not open the + // gate; a short kick closes it at once. + assert_eq!(run_of(&[3; 64]), 0, "a stream of 3 us kicks has no heavy run"); + assert_eq!(run_of(&[99]), 0, "just under the threshold is short"); + assert!(!sustained(run_of(&[3, 3, 900, 3, 3])), "one long kick does not fan a stream out"); + assert!(!sustained(run_of(&[270])), "one heavy kick is not yet sustained"); + assert!(sustained(run_of(&[100, 270])), "two consecutive heavy kicks are"); + assert!(sustained(run_of(&[490, 490, 490]))); + assert!(!sustained(run_of(&[490, 490, 490, 3])), "a short kick closes the gate"); + assert_eq!(run_of(&[490; 300]), u8::MAX, "the run saturates"); + assert_eq!(heavy_run(5, 9_000, 1_000), 0, "a backwards record measures nothing"); + + let b = backend(); + // (a, b) The gate: only independent commands without sources, and the primary's state is + // asked last so a command that cannot fan out never looks at (or locks) the primary. + let ask = |answer: bool| { b.gate_asked.set(b.gate_asked.get() + 1); answer }; + assert!(b.fans_out(&packet(false, None), || ask(true))); + assert!(!b.fans_out(&packet(false, None), || ask(false)), "a light primary keeps its kicks"); + let asked = b.gate_asked.get(); + assert!(!b.fans_out(&packet(true, None), || ask(true)), "sources never fan out"); + assert!(!b.fans_out(&packet(false, Some(4)), || ask(true)), "nor in-queue barriers"); + assert_eq!(b.gate_asked.get(), asked, "the primary is not asked for them"); + let single = Backend { compute_channels: 1, ..backend() }; + assert!(!single.fans_out(&packet(false, None), || ask(true)), "one channel per owner"); + + // (c) The lock-free mirror of the gate. + let heavy_primary = channel(10, 0, 1, 2); + let cell = ComputeCell::new(); + cell.sync_stats(Some(&heavy_primary)); + assert!(cell.sustained()); + assert_eq!(cell.load_hint(), (false, 1, 10)); + cell.sync_stats(None); + assert!(!cell.sustained(), "an emptied cell is not sustained"); + + let light = [channel(10, 0, 4, 0), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy = [channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_one = [channel(10, 0, 1, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_busy = [channel(10, 0, 1, 2), channel(11, 1, 1, 0)]; + let indep = packet(false, None); + let sourced = packet(true, None); + + // (b) Short kicks stay on the busy primary ring even with idle siblings bound, and a lone + // busy primary does not detour to the device-mutex path to add a sibling. + assert_eq!(b.route(&indep, &cells(&light), 3), Some((0, false)), "short kicks stream down channel 0"); + assert_eq!(b.route(&indep, &cells(&light[..1]), 1), Some((0, false)), + "a busy light primary keeps publishing directly"); + // (a) A command with sources takes the primary even when it is busy and heavy. + assert_eq!(b.route(&sourced, &cells(&heavy), 3), Some((0, false)), "sources stay on channel 0"); + assert_eq!(b.route(&sourced, &cells(&heavy[..1]), 1), Some((0, false)), + "sources never ask for a sibling"); + // (c) Sustained heavy work fans out onto the least-loaded idle sibling, asks the + // device-mutex path for a sibling when every bound channel is busy, and a lone heavy + // busy primary may add one. + assert_eq!(b.route(&indep, &cells(&heavy), 3), Some((1, false)), "heavy kicks take an idle sibling"); + // (c) ... once two are in flight: behind a single kick the next one queues on channel 0. + assert_eq!(b.route(&indep, &cells(&heavy_one), 3), Some((0, false)), + "a kick queues behind a single kick in flight"); + assert_eq!(b.route(&indep, &cells(&[channel(10, 0, 1, 2), channel(11, 1, 0, 0)]), 2).map(|(idx, _)| idx), + Some(0), "also with an idle sibling bound"); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), None, "all busy: bring up the third channel"); + assert_eq!(b.route(&indep, &cells(&heavy[..1]), 1), Some((0, true))); + b.sibling_backoff_until.store(now_ns() + 1, Ordering::Relaxed); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), Some((0, false)), + "after a headroom miss the bound channels are used"); + b.sibling_backoff_until.store(0, Ordering::Relaxed); + let idle_heavy = [channel(10, 0, 0, 2), channel(11, 1, 1, 0)]; + assert_eq!(b.route(&indep, &cells(&idle_heavy), 2), Some((0, true)), + "an idle primary comes first; only a busy lone channel detours for a sibling"); + + // (c) Fanned-out kicks get one monotonic sequence of ordinals and object ids from their + // shared context, whichever channel publishes them. + let context = Context::new(70); + let mut seen = HashSet::new(); + let mut last = 0; + for kick in 0..64u32 { + let (ordinal, object_ids) = context.next_compute_identity(); + assert_eq!(ordinal, kick + 1); + assert!(ordinal > last && seen.insert(object_ids as u32)); + assert_eq!((object_ids >> 32) as u32, last.max(1), "each id names its predecessor"); + last = ordinal; + } + + // Device-mutex selection and sibling admission follow the same gate. + let req = ComputeCapacity(16); + let ctx = Context::new(70); + // (b) A light primary brings up no sibling though every channel is busy and QIDs are free. + let reg = registry(vec![channel(10, 0, 3, 0), channel(11, 1, 1, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "a light primary wants no sibling"); + // (c) A sustained heavy primary does. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 1, 0)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... only while every channel is busy. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 0, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... and two kicks are in flight: one kick behind which the next queues brings up none. + let reg = registry(vec![channel(10, 0, 1, 2)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "one kick in flight wants no sibling"); + let reg = registry(vec![channel(10, 0, 2, 2)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req), "two kicks in flight do"); + + let reg = registry(light.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), "short kicks take the primary"); + let reg = registry(heavy.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(11), "heavy kicks spread"); + let reg = registry(heavy_one.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), + "behind a single kick in flight the next one queues on the primary"); + let reg = registry(vec![channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &sourced), Some(10), "sources take the primary"); + assert_eq!(reg.select_compute_channel(OWNER, &packet(true, Some(3))), Some(10), + "even when a dependency could stay on another channel"); + // A dependent command still follows the sole active channel (no cross-channel barrier). + let reg = registry(vec![channel(10, 0, 0, 2), channel(11, 1, 2, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &packet(false, Some(3))), Some(11)); + + // The threshold itself. + assert!(!overlaps(0) && !overlaps(1) && overlaps(2) && overlaps(3)); + + println!("PASS g17-m5-sibling-gate: sources, short kicks and a kick behind a single one stay on the primary ring, sustained heavy kicks fan out"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-gate-') as tmp: + path = Path(tmp) / 'gate.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py new file mode 100755 index 00000000000000..6fbdd10e119d16 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -0,0 +1,646 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: M5 sibling compute channels come from vacant and other-VM idle queues too. + +Once earlier clients have taken compute QIDs up to the fresh-QID ceiling +(`compute_fits()` false), every idle compute queue is either vacant (its pool +given back after the idle expiry) or still holds the pool of a VM that is gone. +A sibling that could only bind a populated pool of its own VM, or a fresh QID, +then never came up again until the GPU slept. This test compiles the production +code that decides and performs the sibling's acquisition against host stubs: + +- the queue predicates of drivers/gpu/drm/asahi/g17/queue/compute.rs that say + which queue may change owner (`reusable`, `can_rearm`, `rearm_open`, + `shareable`, `recycled_pending`, `vacancy_pending`, `vacate_candidate`) and + the queue's pool give-back and re-arm transitions (`require_fresh_backing`, + `vacate`, `observe_vacancy`, `rearm`, `bind_sibling`); +- the registry's `sibling_source()`, `has_compute_sibling_headroom()`, + `wants_compute_sibling()`, `bind_reusable_sibling()`, `give_back_foreign()`, + `reserve_rearm()`, `rearm_compute()`, `bind_rearmed()` and the pool pass + `vacate_idle_pools()` from drivers/gpu/drm/asahi/g17/runtime.rs. + +It checks that with no fresh QID a new client still gets every sibling it +wants, first from vacant queues (re-armed with fresh backing, bound as sibling +channels) and then from other VMs' idle queues (given back one at a time, +vacated by the pool pass, re-armed), across clients that come and go; that a +queue with an owner or work, an open client's idle channel, a queue another +client is re-arming, one whose scheduler release is in flight and one whose +pool release is in flight are never taken; that a fresh QID comes before +another VM's pool is given back; and, structurally, that +`try_add_compute_sibling()` takes these sources through the primary's re-arm +path, lets an owner waiting for its first channel go first and that the primary +path gives back other VMs' queues through the same helper. + +Each mutation restores the old rule or drops one part of the new one and must +fail an assertion of the compiled harness. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# The headroom rule before this change: a populated same-VM pool or a fresh QID only. +OLD_SOURCE = '''fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let warm = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| { + queue.reusable() + && !queue.needs_fresh_backing() + && !queue.pool_vacant() + && queue.pool_serves(vm) + && queue.pool_fits(required) + && queue.has_ring() + && !queue.context().is_some_and(|bound| teardown.releasing(bound)) + }) + .map(|queue| (queue.released_at(), queue.qid())) + .min_by_key(|(key, _)| *key) + .map(|(_, qid)| SiblingSource::Warm(qid)); + warm.or_else(|| { + self.qids + .compute_fits(self.admission.queues() as usize) + .then_some(SiblingSource::Fresh) + }) + }''' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # The old rule: no vacant and no other-VM queue is ever a sibling source. + 'old-headroom': [('source', None, OLD_SOURCE)], + 'no-vacant-sibling': [('runtime', ' if let Some((_, qid)) = vacant {\n', ' if let Some((_, qid)) = vacant.filter(|_| false) {\n')], + 'no-foreign-sibling': [('runtime', ' foreign.map(|(_, qid)| SiblingSource::Foreign(qid))\n', ' None\n')], + # Never steal: an open client's idle channel, a busy queue, a queue another client re-arms, + # a queue whose scheduler release is in flight. + 'steal-shareable': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable() || queue.shareable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'steal-unowned': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.owner() != Some(owner))\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'ignore-rearm-reservation': [('runtime', ' if !queue.rearm_open(owner) {\n continue;\n' + ' }\n &mut vacant\n', ' &mut vacant\n')], + 'ignore-releasing': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable())\n' + ' {\n let best = if queue.pool_vacant() {')], + # Give back several other-VM pools at once. + 'parallel-give-back': [('runtime', ' .any(|queue| queue.vacancy_pending())\n {\n return None;\n }\n' + ' foreign.map(', ' .any(|queue| queue.vacancy_pending() && false)\n {\n' + ' return None;\n }\n foreign.map(')], + # Give another VM's pool back while a fresh QID fits. + 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release', + ' if foreign.is_none() && self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release')], + # A re-armed sibling is bound as the owner's primary. + 'rearm-binds-primary': [('runtime', ' if channel_index == 0 {\n queue.bind_owner(owner, context.clone())', + ' if true {\n queue.bind_owner(owner, context.clone())')], + # Structural: try_add_compute_sibling() without the re-arm, the waiter rule, the shared give-back. + 'try-add-ignores-waiters': [('runtime', ' || self.shared.channels.has_waiters()\n', '')], + 'try-add-skips-rearm': [('runtime', ' firmware.queues.reserve_rearm(qid, self.owner)?;\n Err(qid)\n', + ' return Ok(false);\n')], + 'rearm-any-index': [('runtime', ' && (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));\n', ';\n')], + 'primary-own-give-back': [('runtime', ' if let Some(qid) = foreign {\n self.give_back_foreign(qid)?;\n', + ' if let Some(qid) = foreign {\n self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing();\n')], +} + + +def build(mutation=None): + files = { + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + 'pairs': (G17 / 'pairs.rs').read_text(), + 'freelist': (G17 / 'freelist.rs').read_text(), + } + old_source = False + for name, old, new in MUTATIONS.get(mutation, []): + if name == 'source': + old_source = True + continue + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + runtime, queue, pairs, freelist = files['runtime'], files['queue'], files['pairs'], files['freelist'] + source_fn = item(runtime, 'fn sibling_source(') + if old_source: + runtime = runtime.replace(source_fn, OLD_SOURCE) + source_fn = OLD_SOURCE + + queue_fns = '\n'.join(item(queue, signature) for signature in [ + 'pub(crate) fn reusable(&self)', 'pub(crate) fn can_rearm(&self)', 'pub(crate) fn rearm_open(', + 'pub(crate) fn reserve_rearm(', 'pub(crate) fn release_rearm(', 'pub(crate) fn require_fresh_backing(', + 'pub(crate) fn needs_fresh_backing(', 'pub(crate) fn pool_vacant(', 'pub(crate) fn pool_serves(', + 'pub(crate) fn pool_fits(', 'pub(crate) fn recycled_pending(', 'pub(crate) fn vacancy_pending(', + 'pub(crate) fn pool_release_pending(', 'pub(crate) fn vacate_candidate(', 'pub(crate) fn released_at(', + 'pub(crate) fn has_ring(', 'pub(crate) fn rearm(\n', 'pub(crate) fn vacate(&mut self', + 'pub(crate) fn observe_vacancy(', 'pub(crate) fn shareable(', 'pub(crate) fn owner(&self)', + 'pub(crate) fn channel_index(&self)', 'pub(crate) fn is_primary(&self)', 'pub(crate) fn active_len(&self)', + 'pub(crate) fn has_replays(&self)', 'pub(crate) fn configuring(&self)', 'pub(crate) fn context(&self)', + 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('crate::g17::initdata::InitData', 'InitData') \ + .replace('crate::g17::now_ns()', 'now_ns()').replace('crate::g17::freelist::control_consumed', 'control_consumed') + pool_fns = '\n'.join(item(freelist, signature) for signature in [ + 'pub(crate) fn populated(&self)', 'pub(crate) fn serves(&self', 'pub(crate) fn take_pages(', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') + registry_fns = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn has_compute_sibling_headroom(', + 'fn wants_compute_sibling(', 'fn bind_reusable_sibling(', 'fn compute_queue_mut(', + 'fn give_back_foreign(', 'fn reserve_rearm(&mut self, qid', 'pub(super) fn release_rearm(', + 'pub(super) fn rearm_compute(', 'pub(super) fn bind_rearmed(', 'pub(super) fn vacate_idle_pools(', + ] if True) + '\n' + source_fn + registry_fns = registry_fns.replace('pub(super) ', '').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '').replace('super::initdata::InitData', 'InitData') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('compute::DescriptorRing', 'DescriptorRing') \ + .replace('super::freelist::PoolDescriptor', 'PoolDescriptor').replace('compute::Vacated', 'Vacated') + enum = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + pairs_fns = '\n'.join([ + 'const SIBLING_MIN_IN_FLIGHT: usize = ' + + pairs.split('pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = ', 1)[1].split(';', 1)[0] + ';', + item(pairs, 'pub(crate) fn overlaps(').replace('pub(crate) ', ''), + ]) + + try_add = item(runtime, 'fn try_add_compute_sibling(') + rearm_vacant = item(runtime, 'fn rearm_vacant(') + rebind = item(runtime, 'pub(super) fn rebind_compute(') + build_compute = item(runtime, 'fn build_compute(') + structure = { + 'try_add takes every source through its own path': ordered_ok( + try_add, '|| self.shared.channels.has_waiters()', 'wants_compute_sibling(', + 'firmware.queues.sibling_source(self.owner, &self.context, required)', + 'Some(SiblingSource::Warm(_)) =>', 'bind_reusable_sibling(', + 'Some(SiblingSource::Foreign(qid)) =>', 'firmware.queues.give_back_foreign(qid)?;', + 'drop(state);', 'self.shared.queue_events();', 'return Ok(false);', + 'Some(SiblingSource::Vacant(qid)) =>', 'firmware.queues.reserve_rearm(qid, self.owner)?;', 'Err(qid)', + 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', + 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', + 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', + 'return Ok(bound);', 'compute::PoolBacking::new('), + 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( + rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', + 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', + 'queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)', + '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));', + 'firmware.queues.rearm_compute(qid, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', + 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), + 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, + 'the primary gives back other VMs\' queues through the same helper': ordered_ok( + rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm))', + 'if let Some(qid) = foreign {', 'self.give_back_foreign(qid)?;', 'return Err(ENOSPC);'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@ENUM@@', enum).replace('@@PAIRS@@', pairs_fns).replace('@@QUEUE@@', queue_fns) + .replace('@@POOL@@', pool_fns).replace('@@REGISTRY@@', registry_fns).replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports, unreachable_code, unused_assignments)] +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{fence, AtomicU32, Ordering}; + +const EIO: i32 = -5; +const EAGAIN: i32 = -11; +const EBUSY: i32 = -16; +const EPERM: i32 = -1; +const ENOSPC: i32 = -28; +type Result = std::result::Result; +const GFP_KERNEL: () = (); +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _: ()) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } + +fn now_ns() -> u64 { 5_000_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@ENUM@@ + +@@PAIRS@@ + +pub struct Vm(u32); +impl Vm { pub fn id(&self) -> u32 { self.0 } } +pub struct Context { id: u32, vm: Vm, current: bool } +impl Context { + fn new(id: u32, vm: u32) -> Arc { Arc::new(Self { id, vm: Vm(vm), current: true }) } + fn vm(&self) -> &Vm { &self.vm } + fn is_current(&self) -> bool { self.current } +} + +#[derive(Debug)] +pub struct Pages(u32); +pub struct DescriptorRing; +#[derive(Debug, PartialEq)] +pub struct PoolDescriptor(u32); +pub struct InitData { control_cursor: std::cell::Cell } +pub struct KernelMapping; +pub struct Vacated { _alias: Option, _pages: Option, _descriptors: Option, _ring: Option } +pub struct FreeListRelease; +enum ControlRecord { FreeListRelease(FreeListRelease) } +struct Rings; +impl Rings { + fn publish_control(init: &InitData, _: &ControlRecord) -> Result { + let cursor = init.control_cursor.get() + 1; + init.control_cursor.set(cursor); + Ok(cursor) + } +} +/// The firmware consumed every control record up to `consumer`. +fn control_consumed(consumer: u32, _producer: u32, cursor: u32) -> Result { Ok(consumer >= cursor) } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum PoolPhase { Populated, ReleaseSent(u32), Vacant } +pub struct Fifo { len: usize } +pub struct SourceHint; +impl SourceHint { fn has_readers(&self, count: &AtomicU32) -> bool { count.load(Ordering::Acquire) != 0 } } +pub struct Graph { ring: Option, m5: bool } +impl Graph { + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { self.ring.replace(ring) } + fn vacate_ring(&mut self) -> Option { self.ring.take() } +} +pub struct Binding { context: Arc, pool_alias: Option, descriptors: Option } +pub struct Pool { id: u16, client_vm: u32, pages: Option, cap: u32 } +impl Pool { +@@POOL@@ + fn fits_capacity(&self, required: ComputeCapacity) -> bool { self.pages.is_some() && self.cap >= required.0 } + fn rearm(&mut self, pages: Pages) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages); Ok(()) } + fn descriptor(&self) -> Result { Ok(PoolDescriptor(u32::from(self.id))) } + fn release_record(&self, _generation: u64) -> FreeListRelease { FreeListRelease } +} + +/// The owner-change state of one physical compute queue, with the production field names. +pub struct Queue { + qid: u8, growing: bool, channel_error: bool, installed: bool, configuration: Option<()>, + pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option<()>, owner: Option, + released: bool, retirement_ready: bool, quarantined: bool, active: Fifo, replays: Fifo, + previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, + pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, + free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, + channel_index: u8, sustained: bool, +} +impl Queue { +@@QUEUE@@ + fn qid(&self) -> u8 { self.qid } + fn sustained(&self) -> bool { self.sustained } + /// The production entry check of bind_owner_channel(); the views of the new VM are not modelled. + fn bind_owner_channel(&mut self, owner: u64, context: Arc, channel_index: u8) -> Result { + if !self.reusable() { + return Err(EBUSY); + } + if !self.pool.serves(context.vm()) { + return Err(EPERM); + } + self.pool.client_vm = context.vm().id(); + self.binding = Some(Binding { context, pool_alias: None, descriptors: None }); + self.owner = Some(owner); + self.channel_index = channel_index; + self.rearm_for = None; + self.released = false; + self.retirement_ready = false; + Ok(()) + } +} + +type QueueGuard<'a> = std::cell::RefMut<'a, Queue>; +struct Slot(RefCell); +impl Slot { + fn as_deref(&self) -> Option> { Some(self.0.borrow()) } + fn as_deref_mut(&mut self) -> Option> { Some(self.0.borrow_mut()) } +} +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { fn queues(&self) -> u32 { 4 } } +struct Teardown { releasing: Vec } +impl Teardown { fn releasing(&self, context: &Arc) -> bool { self.releasing.contains(&context.id) } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { + const POOL_RETRY_NS: u64 = 100_000_000; +@@REGISTRY@@ + fn queue(&self, qid: u8) -> std::cell::Ref<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow()).find(|queue| queue.qid == qid).unwrap() + } + fn queue_mut(&self, qid: u8) -> std::cell::RefMut<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow_mut()).find(|queue| queue.qid == qid).unwrap() + } + /// An event pass: the production pool pass gives back what must go, then the firmware + /// consumes the control ring and the release observation leaves those queues vacant. + fn pool_pass(&mut self, init: &InitData) { + vacate_idle_pools_pass(self, init); + let consumer = init.control_cursor.get(); + for entry in self.compute.iter_mut().flatten() { + let mut queue = entry.queue.0.borrow_mut(); + let _ = queue.observe_vacancy(consumer, consumer).unwrap(); + } + } + fn push(&mut self, queue: Queue) { self.compute.push(Some(Entry { queue: Slot(RefCell::new(queue)) })); } +} +fn vacate_idle_pools_pass(registry: &mut Registry, init: &InitData) { + // Idle pools stay warm (cap 3, no expiry): only queues given back are released. + registry.vacate_idle_pools(init, 3, now_ns(), u64::MAX).unwrap(); +} + +/// An installed queue owned by `owner` (channel 0) with `active` kicks in flight. +fn bound(qid: u8, owner: u64, context: &Arc, active: usize) -> Queue { + Queue { + qid, growing: false, channel_error: false, installed: true, configuration: None, + pool_phase: PoolPhase::Populated, needs_fresh_backing: false, exit: None, owner: Some(owner), + released: false, retirement_ready: true, quarantined: false, active: Fifo { len: active }, + replays: Fifo { len: 0 }, previous: None, source_hint: SourceHint, source_readers: AtomicU32::new(0), + rearm_for: None, pool: Pool { id: u16::from(qid), client_vm: context.vm().id(), pages: Some(Pages(1)), cap: 16 }, + graph: Graph { ring: Some(DescriptorRing), m5: true }, + binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), + release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, + channel_index: 0, sustained: true, + } +} +/// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. +fn released(qid: u8, vm: u32, released_at: u64) -> Queue { + let mut queue = bound(qid, 0, &Context::new(1000 + u32::from(qid), vm), 0); + queue.owner = None; + queue.released = true; + queue.released_at = released_at; + queue.sustained = false; + queue +} +/// The same, after its pool was given back (the idle expiry): vacant, without a ring. +fn vacant(qid: u8, released_at: u64) -> Queue { + let mut queue = released(qid, 0, released_at); + queue.pool_phase = PoolPhase::Vacant; + queue.pool.pages = None; + queue.pool.client_vm = 0; + queue.graph.ring = None; + queue +} + +/// try_add_compute_sibling()'s locked decision and the off-lock re-arm, through the production +/// registry calls in the order the backend makes them. Returns whether a sibling was bound. +fn add_sibling(reg: &mut Registry, init: &InitData, owner: u64, context: &Arc) -> Result { + let req = ComputeCapacity(16); + if !reg.wants_compute_sibling(owner, context, 3, req) { + return Ok(false); + } + let Some(channel_index) = reg.next_sibling_index(owner, 3) else { return Ok(false) }; + match reg.sibling_source(owner, context, req) { + None => Ok(false), + Some(SiblingSource::Warm(_)) => Ok(reg.bind_reusable_sibling(owner, context, 3, req)? == Some(true)), + Some(SiblingSource::Foreign(qid)) => { reg.give_back_foreign(qid)?; Ok(false) } + Some(SiblingSource::Fresh) => Ok(false), + Some(SiblingSource::Vacant(qid)) => { + reg.reserve_rearm(qid, owner)?; + // Off the device mutex: fresh pages and a descriptor ring; then, locked again, the + // production rearm_vacant() checks and steps. + let ready = { + let queue = reg.queue(qid); + queue.can_rearm() && queue.rearm_open(owner) + } && reg.next_sibling_index(owner, 3) == Some(channel_index); + if !ready { + reg.release_rearm(qid, owner); + return Ok(false); + } + let (descriptor, _vacated) = reg.rearm_compute(qid, Pages(2), DescriptorRing)?; + assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); + reg.bind_rearmed(qid, owner, context, channel_index)?; + Ok(true) + } + } +} + +fn registry() -> Registry { + Registry { compute: Vec::new(), qids: Qids { fit: false }, admission: Admission, teardown: Teardown { releasing: Vec::new() } } +} + +const B: u64 = 2; +const C: u64 = 3; +const D: u64 = 4; +const OTHER: u64 = 9; + +fn main() { +@@STRUCTURE@@ + + let init = InitData { control_cursor: std::cell::Cell::new(0) }; + let req = ComputeCapacity(16); + let b = Context::new(20, 200); + let c = Context::new(30, 300); + let d = Context::new(40, 400); + let mut reg = registry(); + // B's primary runs sustained heavy work with two kicks in flight. No fresh QID fits. + reg.push(bound(10, B, &b, 2)); + // An exited client's queues: one given back at the idle expiry (vacant), one still holding + // the exited VM's pool. + reg.push(vacant(11, 5)); + reg.push(released(12, 999, 6)); + // Never to be taken: C's busy queue, D's idle channel (D is open), a vacant queue another + // client is re-arming and a queue whose scheduler release is in flight. + reg.push(bound(13, C, &c, 1)); + reg.push(bound(14, D, &d, 0)); + let mut reserved = vacant(15, 1); + reserved.rearm_for = Some(OTHER); + reg.push(reserved); + reg.push(released(16, 998, 2)); + reg.teardown.releasing.push(1016); + let untouchable = [13u8, 14, 15, 16]; + assert!(reg.queue(14).shareable(), "D's idle channel is shareable, so only a primary may take it"); + assert!(!reg.queue(14).reusable()); + + // No lockout: the sibling comes from the vacant queue, re-armed and bound as channel 1. + assert!(reg.has_compute_sibling_headroom(B, &b, req), "vacant and other-VM queues are headroom"); + assert!(reg.wants_compute_sibling(B, &b, 3, req)); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(false)), "nothing warm to bind at once"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(11))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + { + let q = reg.queue(11); + assert_eq!((q.owner, q.channel_index, q.pool_phase), (Some(B), 1, PoolPhase::Populated)); + assert!(q.has_ring() && !q.needs_fresh_backing() && q.rearm_for.is_none()); + } + assert_eq!(reg.compute_channels_of(B), (2, 0b11)); + + // The third channel. While a pool release is in flight (it ends in a vacant queue) no other + // VM's pool is given back, and the releasing queue itself is not taken. + reg.queue_mut(11).active.len = 1; + let mut releasing = released(17, 997, 3); + releasing.pool_phase = PoolPhase::ReleaseSent(u32::MAX); + reg.push(releasing); + assert!(!reg.queue(17).reusable() && reg.queue(17).vacancy_pending()); + assert_eq!(reg.sibling_source(B, &b, req), None); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false)); + assert!(!reg.queue(12).needs_fresh_backing(), "nothing given back meanwhile"); + reg.compute.pop(); + // Then no vacant queue is left, so the exited VM's queue is given back. + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Foreign(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false), "given back, not yet vacant"); + assert!(reg.queue(12).needs_fresh_backing() && reg.queue(12).vacancy_pending()); + assert!(!reg.queue(12).reusable(), "nobody binds its old pool meanwhile"); + // One give-back at a time: nothing else is offered while that release is pending. + assert_eq!(reg.sibling_source(B, &b, req), None); + assert!(!reg.wants_compute_sibling(B, &b, 3, req)); + // The pool pass releases it; once consumed the queue is vacant and is re-armed for B. + reg.pool_pass(&init); + assert_eq!(reg.queue(12).pool_phase, PoolPhase::Vacant); + assert!(reg.queue(12).pool_serves(b.vm()), "fresh backing serves any VM"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + assert_eq!((reg.queue(12).owner, reg.queue(12).channel_index), (Some(B), 2)); + assert_eq!(reg.compute_channels_of(B), (3, 0b111)); + assert!(!reg.wants_compute_sibling(B, &b, 3, req), "three channels at most"); + + // Nothing was stolen. + for qid in untouchable { + let q = reg.queue(qid); + assert_ne!(q.owner, Some(B), "queue {} was taken", qid); + assert!(!q.needs_fresh_backing(), "queue {} was given back", qid); + } + assert_eq!(reg.queue(13).owner, Some(C)); + assert_eq!(reg.queue(14).owner, Some(D)); + assert_eq!(reg.queue(15).rearm_for, Some(OTHER)); + + // Clients come and go: each new one gets its siblings back from what the last one left. + for round in 0..4u32 { + let vm = 500 + round; + let next = Context::new(50 + round, vm); + let owner = 100 + u64::from(round); + // The previous owner's channels (B's, then each round's) are released idle; their + // pools serve the exited VM. The newcomer's primary is one of them, rebound (modelled). + let mut freed: Vec = Vec::new(); + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner.is_some() && !untouchable.contains(&q.qid) { + q.owner = None; + q.released = true; + q.retirement_ready = true; + q.active.len = 0; + q.released_at = u64::from(round) * 10 + u64::from(q.qid); + freed.push(q.qid); + } + } + assert_eq!(freed.len(), 3, "round {}: three channels released", round); + let primary = freed[0]; + { + let mut q = reg.queue_mut(primary); + q.owner = Some(owner); + q.channel_index = 0; + q.released = false; + q.pool_phase = PoolPhase::Vacant; + q.pool.pages = Some(Pages(3)); + q.pool_phase = PoolPhase::Populated; + q.pool.client_vm = vm; + q.sustained = true; + q.active.len = 2; + } + let mut added = 0; + for _ in 0..8 { + if add_sibling(&mut reg, &init, owner, &next).unwrap() { + added += 1; + // Every bound channel stays busy. + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner == Some(owner) && q.active.len == 0 { + q.active.len = 1; + } + } + } else { + reg.pool_pass(&init); + } + } + assert_eq!(added, 2, "round {}: no lockout", round); + assert_eq!(reg.compute_channels_of(owner).0, 3); + for qid in untouchable { + assert_ne!(reg.queue(qid).owner, Some(owner)); + } + } + + // A fresh QID comes before another VM's pool is given back. + let mut reg = registry(); + reg.qids.fit = true; + reg.push(bound(10, B, &b, 2)); + reg.push(released(12, 999, 6)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Fresh)); + // A warm same-VM queue comes before a vacant one. + reg.push(vacant(11, 1)); + reg.push(released(18, 200, 9)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Warm(18))); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(true))); + assert_eq!(reg.queue(18).channel_index, 1); + // ... and a vacant one before a fresh QID; the longest released first. + reg.push(vacant(19, 0)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(19))); + + println!("PASS g17-m5-sibling-rearm: vacant and other-VM idle queues become siblings, nothing busy or open is taken"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-rearm-') as tmp: + path = Path(tmp) / 'rearm.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-pool-release-tests.py b/tools/asahi/g17-pool-release-tests.py index 70004fe94ecf91..dd73e0a3e8977a 100644 --- a/tools/asahi/g17-pool-release-tests.py +++ b/tools/asahi/g17-pool-release-tests.py @@ -31,7 +31,8 @@ def fixture(): predicate = '.any(|queue| queue.retirement_polling() || queue.pool_release_pending())' assert events.count(predicate) == 1 methods = '\n'.join(item(runtime, name) for name in [ - 'fn compute_admission_error(', 'pub(super) fn reserve_compute(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') + 'fn compute_admission_error(', 'pub(super) fn reserve_compute(', + 'pub(super) fn reserve_compute_channel(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') pending = item(compute, 'pub(crate) fn pool_release_pending(') + '\n' + \ item(compute, 'pub(crate) fn release_settling(') return r''' diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7c51f27236a39f..51c5972e1eab30 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -248,7 +248,8 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', 'crossed-behind-owed', 'owed-classified', 'rebind-check-entry', - 'timeout-fails-retired', 'no-owed-poll'), []), + 'timeout-fails-retired', 'no-owed-poll', 'count-recordless', + 'count-owed-twice'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], 'g17-kill-route-tests.py': [([], PASS)] @@ -272,6 +273,29 @@ def mutations(flag, names, base, expect=KILL): 'same-qid-emits-barrier', 'lock-has-published-epoch', 'lock-same-vm'), []), + 'g17-m5-sibling-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('fixed-object-ids', 'primary-before-sibling', + 'exit-ack-stops-first', 'direct-allows-multi-barrier', + 'direct-blocks-sibling', 'direct-locks-sibling-when-idle', + 'direct-skips-multi', 'same-qid-pipelined'), []), + 'g17-m5-sibling-gate-tests.py': [([], PASS)] + + mutations('--mutation', ('sources-fan-out', 'select-sources-anywhere', 'tiny-fans-out', + 'no-sustain-run', 'short-keeps-run', 'direct-ignores-gate', + 'direct-can-add-ungated', 'wants-ignores-sustained', + 'select-ignores-sustained', 'cell-drops-sustained', + 'fans-out-locks-first', 'keep-run-across-owners', 'overlap-at-one', + 'direct-ignores-in-flight', 'select-ignores-in-flight', + 'wants-ignores-in-flight', 'detour-at-one'), []), + 'g17-m5-sibling-rearm-tests.py': [([], PASS)] + + mutations('--mutation', ('old-headroom', 'no-vacant-sibling', 'no-foreign-sibling', + 'steal-shareable', 'steal-unowned', 'ignore-rearm-reservation', + 'ignore-releasing', 'parallel-give-back', 'foreign-before-fresh', + 'rearm-binds-primary', 'try-add-ignores-waiters', 'try-add-skips-rearm', + 'rearm-any-index', 'primary-own-give-back'), []), + 'g17-compute-multi-channel-feature-tests.py': [([], PASS)] + + mutations('--mutation', ('always-multi', 'never-multi', 'not-reported', 'per-board-gate', + 'colliding-bit', 'unsynced-binding', 'forms-gate', + 'max-channels', 'multi-channel-max'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 70c48d2d05146479ee8dc18f42b3d0a29d2ca02c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 15:48:53 -0500 Subject: [PATCH 1058/1514] drm/asahi: g17: run M5 event work beside the submitter, not on its CPU Since the event queue became per-CPU on every G17 part, M5's queue_event_records() aims the event work at the CPU that last published work with queue_work_on() on a bound pool, so the worker runs on that very CPU. A thread that publishes directly from its submit ioctl is then preempted by every completion: the event worker has the higher priority, and the completion interrupt is either taken on the submitter's CPU (the AIC cannot be steered) or reaches it by an IPI. The preemption often lands in the middle of a direct compute publication, which holds the compute cell's mutex across Queue::publish(), and the event pass takes that cell next. Its owner is not running, so the worker cannot spin on it: it sleeps, the submitter resumes, and its mutex_unlock() wakes the worker, which preempts it again. Each completion costs the submitter two context switches. Profiled on M5 Pro, one thread keeping 16 light compute submissions in flight took 18.0 us per submission, 11.8 us of it in the submit ioctl, with 93,000 function-call IPIs per second (1.7 per submission), 0.82 context switches of the submitting thread per submission and an IPC of 1.12. __schedule took 8.9% of the cycles, preempt_schedule_irq 7.0% and mutex_unlock 4.4%, all in the submitter's ioctl after an interrupt. Two queues signalling each other showed the same profile. With 64 in flight the scheduler's worker publishes instead, so the event work lands on its CPU, beside the submitting thread rather than on it: 0.26 context switches per submission, an IPC of 2.39, 3.5 us in the submit ioctl and 11.4 us per submission. Make the queue unbound again where the event work follows the submitter, as it was on M5 before. Aimed at a CPU, an unbound queue takes only that CPU's affinity pod, the CPUs sharing its L2, and the scheduler wakes the worker on an idle CPU of the pod. Completion processing stays in the submitter's cluster and on its die, which is why it follows the submitter, and a running submitter is left alone: a worker that meets the cell lock spins on its running owner. Other G17 parts keep the per-CPU queue, where the event work runs on the CPU that queues it, as on system_highpri_wq. The queue stays reclaim-safe and high priority. Shared::new_events_queue() derives the queue's kind from the same follows_submitter value that Shared keeps, so the two cannot disagree. The per-CPU queue reached M5 with "drm/asahi: g17: reduce M5 direct submit and event lock overhead", which this series builds on and which is still under review (aurora-silicon/linux#2955). This change takes back that part of it on M5 only, and is not tagged as a fix since that commit is not in any merged tree yet. Add a host test that compiles the queue choice, the event work's queuing and the submitter tracking against a model of where the kernel runs the woken worker: on M5, a completion taken on the submitter's CPU, on another cluster or on the other die runs in the submitter's pod without preempting it, and elsewhere it runs on the queuing CPU. Its mutations include the previous per-CPU queue. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/mod.rs | 39 +- tools/asahi/g17-m5-event-placement-tests.py | 479 ++++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 3 files changed, 512 insertions(+), 9 deletions(-) create mode 100755 tools/asahi/g17-m5-event-placement-tests.py diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 7faf86efff627f..255788453d6f4e 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1291,14 +1291,14 @@ struct Shared { /// step). Publishers without the device mutex set it too. governor_activity_ns: AtomicU64, /// The queue of all work that signals job fences: the event work, and every scheduler's - /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe and per-CPU - /// high priority, as `system_highpri_wq`. On M5, `enqueue_on(submitter)` places completion - /// processing directly on the submitting CPU (keeping it in the submitter's L2 and die). + /// timeout work. Memory reclaim may wait on those fences, so it is reclaim-safe, and it is + /// high priority, as `system_highpri_wq`. [`Self::new_events_queue`] says where the event + /// work runs. events: Arc, /// Preallocated completion collector owned exclusively by `run_runtime_events`. #[pin] worker_deferred: Mutex>, - /// M5: the event work follows the submitting CPU. + /// M5: the event work runs beside the CPU that last published work, in its affinity pod. follows_submitter: bool, /// Multi-die M5: restrict each scheduler's ordered submit queue to the creating CPU's /// cluster to avoid cross-die migration. Single-die M5 parts leave schedulers unpinned so @@ -1494,6 +1494,28 @@ impl Shared { self.events.clone() } + /// The queue of [`Self::events`]. + /// + /// Event work that follows the submitter is aimed at the publishing CPU by + /// [`Self::queue_event_records`]. Its queue is unbound, so that CPU only selects the affinity + /// pod, the CPUs sharing its L2, and the scheduler wakes the worker on an idle CPU of the pod: + /// beside the submitter and on its die, wherever the completion interrupt was taken. On a + /// per-CPU queue the worker would run on the submitting CPU itself and, with the higher + /// priority, preempt the submitter for every completion, often in the middle of a publication + /// holding the locks the event work takes next. As their owner would not be running, the + /// worker could not spin on them: it would sleep until the submitter unlocks and then preempt + /// it again, two context switches of the submitter per completion. + /// + /// Otherwise the queue is per-CPU and the event work runs on the CPU that queues it, as on + /// `system_highpri_wq`. + fn new_events_queue(follows_submitter: bool) -> Result { + if follows_submitter { + workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true) + } else { + workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true) + } + } + /// Whether each scheduler's submit queue should be restricted to the creating CPU's cluster /// (multi-die M5 only). pub(super) fn pin_scheduler_cluster(&self) -> bool { @@ -1785,10 +1807,9 @@ impl Gpu { let render_policy = if m5 { Some(render_resources::M5Policy::new(&id)?) } else { None }; // The bare-metal M5 boot runs both engines; other M5 profiles take no submission. let submits = !m5 || cfg.profile == FirmwareProfile::M5PublishedRoots; - let events = Arc::new( - workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)?, - GFP_KERNEL, - )?; + // The event work follows the submitter on M5, which decides its queue's kind. + let follows_submitter = m5; + let events = Arc::new(Shared::new_events_queue(follows_submitter)?, GFP_KERNEL)?; let frequencies = Self::state_frequencies(dev, cfg, variant, id.num_clusters)?; let max_pstate = frequencies .as_ref() @@ -1839,7 +1860,7 @@ impl Gpu { Some(worker_deferred), "g17::Shared::worker_deferred" ), - follows_submitter: m5, + follows_submitter, pin_scheduler_cluster: m5 && id.num_dies > 1, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), diff --git a/tools/asahi/g17-m5-event-placement-tests.py b/tools/asahi/g17-m5-event-placement-tests.py new file mode 100755 index 00000000000000..56820949fd8361 --- /dev/null +++ b/tools/asahi/g17-m5-event-placement-tests.py @@ -0,0 +1,479 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for where the G17 event work runs (`drivers/gpu/drm/asahi/g17/mod.rs`). + +Compiles the real `Shared::new_events_queue()`, `Shared::queue_event_records()`, +`Shared::note_submitter()` and `Shared::submitter()` on the host against a mock +workqueue that records each queue's kind and every enqueue. A model of the +kernel's placement then says which CPU the woken worker runs on: + +- a per-CPU queue runs `enqueue_on(cpu)` on `cpu` and `enqueue()` on the + queuing CPU (`queue_work_on()` on a bound pool); +- an unbound queue only takes the affinity pod (`WQ_AFFN_CACHE`, the CPUs + sharing an L2) from the CPU it is aimed at, and the scheduler wakes the + worker on an idle CPU of that pod (`select_idle_sibling()`), the aimed CPU + itself only when it is idle or the pod has no idle CPU. + +The event work has the higher priority, so a worker woken on the CPU of a +running submitter preempts it. If that submitter holds a lock the pass takes +(a compute cell in the middle of a publication), the worker cannot spin on an +owner that is not running: it sleeps until the unlock and preempts again, two +context switches of the submitter. + +Checks: +1. M5 (the event work follows the submitter): its queue is unbound, reclaim-safe + and high priority; a completion taken on the submitter's own CPU, on another + cluster or on the other die runs in the submitter's pod, never preempting a + submitter that is publishing; the worker follows a moved submitter; before + the first publication the work is queued locally. +2. Other G17 parts: the queue is per-CPU and the event work runs on the CPU + that queued it, as on `system_highpri_wq`, whatever CPU published. +3. Structure: `Gpu::new()` derives the queue and `Shared::follows_submitter` + from one value, `aurora_g17_events` is allocated only by `new_events_queue()`, + and the schedulers' timeout work still uses that queue. + +Mutations: `percpu-always` is the previous code (a per-CPU queue on every part), +`unbound-always`, `aim-local` (never aim at the submitter), `record-always` +(record the submitter on every part), `not-reclaim`, and `split-flag` (the queue +kind no longer follows `follows_submitter`). +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +MOD = ROOT / 'drivers/gpu/drm/asahi/g17/mod.rs' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new, 1) + + +UNBOUND = 'workqueue::OwnedQueue::new_unbound_reclaim(c"aurora_g17_events", true)' +PERCPU = 'workqueue::OwnedQueue::new_percpu_reclaim(c"aurora_g17_events", true)' +DERIVE = 'let follows_submitter = m5;' +CONSTRUCT = 'let events = Arc::new(Shared::new_events_queue(follows_submitter)?, GFP_KERNEL)?;' + + +def build_harness(mutation=None): + src = MOD.read_text() + + if mutation == 'split-flag': + src = replace_once(src, CONSTRUCT, + 'let events = Arc::new(Shared::new_events_queue(false)?, GFP_KERNEL)?;') + + new_queue = item(src, 'fn new_events_queue(') + queue_records = item(src, 'fn queue_event_records(') + note = item(src, 'fn note_submitter(') + submitter = item(src, 'fn submitter(') + + if mutation == 'percpu-always': + # The code before this change: a per-CPU queue on every part. + new_queue = replace_once(new_queue, UNBOUND, PERCPU) + elif mutation == 'unbound-always': + new_queue = replace_once(new_queue, PERCPU, UNBOUND) + elif mutation == 'not-reclaim': + new_queue = replace_once(new_queue, UNBOUND, + 'workqueue::OwnedQueue::new_unbound(c"aurora_g17_events", true)') + elif mutation == 'aim-local': + queue_records = replace_once( + queue_records, + 'Some(cpu) => self.events.enqueue_on::, EVENT_WORK>(cpu, self.clone()),', + 'Some(_) => self.events.enqueue::, EVENT_WORK>(self.clone()),') + elif mutation == 'record-always': + note = replace_once(note, 'if self.follows_submitter {', 'if true {') + + # Gpu::new() derives both the queue and Shared::follows_submitter from one value, the + # one the harness's `Shared::new_m5()`/`Shared::new_other()` pass. + field = ' follows_submitter,\n' + derive_ok = src.count(DERIVE) == 1 and src.count(CONSTRUCT) == 1 + field_ok = (derive_ok and src.count(field) == 1 and 'follows_submitter: m5,' not in src + and src.index(DERIVE) < src.index(CONSTRUCT) < src.index(field)) + only_here = src.count('c"aurora_g17_events"') == new_queue.count('c"aurora_g17_events"') == 2 + fence_ok = 'self.events.clone()' in item(src, 'fn fence_queue(') + + return f''' +#![allow(dead_code)] +use std::sync::atomic::{{AtomicU32, Ordering}}; +use std::sync::Arc; + +type Result = core::result::Result; + +mod kernel {{ + pub mod cpu {{ + use std::cell::Cell; + thread_local! {{ pub static CURRENT: Cell = const {{ Cell::new(0) }}; }} + const NR_CPU_IDS: u32 = 64; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct CpuId(u32); + + impl CpuId {{ + pub fn current() -> Self {{ + CpuId(CURRENT.with(|cpu| cpu.get())) + }} + pub fn from_u32(id: u32) -> Option {{ + (id < NR_CPU_IDS).then_some(CpuId(id)) + }} + pub fn as_u32(self) -> u32 {{ + self.0 + }} + }} + + pub fn run_on(cpu: u32, f: impl FnOnce() -> R) -> R {{ + let previous = CURRENT.with(|current| current.replace(cpu)); + let result = f(); + CURRENT.with(|current| current.set(previous)); + result + }} + }} +}} + +mod workqueue {{ + use super::Result; + use std::cell::RefCell; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Call {{ + /// `queue_work()`: on the queuing CPU (`WORK_CPU_UNBOUND`). + Local {{ queuer: u32 }}, + /// `queue_work_on(cpu)`. + On {{ cpu: u32 }}, + }} + + pub struct OwnedQueue {{ + pub unbound: bool, + pub highpri: bool, + pub reclaim: bool, + pub calls: RefCell>, + }} + + impl OwnedQueue {{ + fn make(unbound: bool, highpri: bool, reclaim: bool) -> Result {{ + Ok(Self {{ unbound, highpri, reclaim, calls: RefCell::new(Vec::new()) }}) + }} + pub fn new_unbound(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(true, highpri, false) + }} + pub fn new_unbound_reclaim(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(true, highpri, true) + }} + pub fn new_percpu_reclaim(_name: &core::ffi::CStr, highpri: bool) -> Result {{ + Self::make(false, highpri, true) + }} + pub fn enqueue(&self, _w: W) -> core::result::Result<(), W> {{ + let queuer = crate::kernel::cpu::CpuId::current().as_u32(); + self.calls.borrow_mut().push(Call::Local {{ queuer }}); + Ok(()) + }} + pub fn enqueue_on( + &self, + cpu: crate::kernel::cpu::CpuId, + _w: W, + ) -> core::result::Result<(), W> {{ + self.calls.borrow_mut().push(Call::On {{ cpu: cpu.as_u32() }}); + Ok(()) + }} + }} +}} + +use workqueue::Call; + +const EVENT_WORK: u64 = 0; + +struct Shared {{ + submission_enabled: bool, + events: Arc, + follows_submitter: bool, + submitter: AtomicU32, +}} + +impl Shared {{ +{new_queue} + +{queue_records} + +{note} + +{submitter} +}} + +impl Shared {{ + /// As `Gpu::new()` builds it: the queue kind and `follows_submitter` from one value. + fn build(m5: bool) -> Arc {{ + let follows_submitter = m5; + let events = Arc::new(Shared::new_events_queue(follows_submitter).expect("events queue")); + Arc::new(Shared {{ + submission_enabled: true, + events, + follows_submitter, + submitter: AtomicU32::new(u32::MAX), + }}) + }} + + /// The completion interrupt, taken on `cpu`, queues the event pass. + fn complete_on(self: &Arc, cpu: u32) -> Call {{ + kernel::cpu::run_on(cpu, || self.queue_event_records()); + *self.events.calls.borrow().last().expect("the event work was queued") + }} + + fn publish_on(&self, cpu: u32) {{ + kernel::cpu::run_on(cpu, || self.note_submitter()); + }} +}} + +/// CPUs grouped by die and by cluster (the L2, the unbound queue's affinity pod). +struct Topology {{ + cluster: Vec, + die: Vec, +}} + +impl Topology {{ + fn new(dies: u32, clusters_per_die: u32, cpus_per_cluster: u32) -> Self {{ + let mut cluster = Vec::new(); + let mut die = Vec::new(); + for d in 0..dies {{ + for c in 0..clusters_per_die {{ + for _ in 0..cpus_per_cluster {{ + cluster.push(d * clusters_per_die + c); + die.push(d); + }} + }} + }} + Self {{ cluster, die }} + }} + fn cpus(&self) -> u32 {{ + self.cluster.len() as u32 + }} +}} + +/// Which CPU the woken event worker runs on. +fn worker_cpu(topo: &Topology, queue: &workqueue::OwnedQueue, call: Call, busy: &[bool]) -> u32 {{ + match (queue.unbound, call) {{ + (false, Call::On {{ cpu }}) => cpu, + (false, Call::Local {{ queuer }}) => queuer, + (true, call) => {{ + let aim = match call {{ + Call::On {{ cpu }} => cpu, + Call::Local {{ queuer }} => queuer, + }}; + if !busy[aim as usize] {{ + return aim; + }} + (0..topo.cpus()) + .find(|&c| topo.cluster[c as usize] == topo.cluster[aim as usize] && !busy[c as usize]) + .unwrap_or(aim) + }} + }} +}} + +/// Context switches the completion costs a submitter publishing on `submitter` while +/// holding a lock the event pass takes. +fn submitter_switches(worker: u32, submitter: u32, busy: &[bool]) -> u32 {{ + if worker == submitter && busy[submitter as usize] {{ 2 }} else {{ 0 }} +}} + +fn busy(topo: &Topology, cpus: &[u32]) -> Vec {{ + let mut busy = vec![false; topo.cpus() as usize]; + for &cpu in cpus {{ + busy[cpu as usize] = true; + }} + busy +}} + +fn test_m5_queue_kind() {{ + let shared = Shared::build(true); + assert!(shared.events.unbound, "M5 event work aimed at the submitter needs an unbound queue"); + assert!(shared.events.reclaim, "the event work signals job fences: WQ_MEM_RECLAIM"); + assert!(shared.events.highpri, "the event work keeps system_highpri_wq's priority"); +}} + +fn test_other_queue_kind() {{ + let shared = Shared::build(false); + assert!(!shared.events.unbound, "other G17 parts keep a per-CPU event queue"); + assert!(shared.events.reclaim, "the event work signals job fences: WQ_MEM_RECLAIM"); + assert!(shared.events.highpri, "the event work keeps system_highpri_wq's priority"); +}} + +/// The measured case: the completion interrupt is taken on the CPU of the submitter, which +/// is in the middle of a publication. +fn test_m5_completion_on_submitter_cpu() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[16]); + let call = shared.complete_on(16); + assert_eq!(call, Call::On {{ cpu: 16 }}, "the event work is aimed at the submitter"); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_ne!(worker, 16, "the event worker must not preempt the publishing submitter"); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16], "the worker shares the submitter's L2"); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_completion_on_other_cluster() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[16, 2]); + let call = shared.complete_on(2); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16], + "the worker runs in the submitter's cluster, not the interrupt's"); + assert_ne!(worker, 16); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_two_dies() {{ + let topo = Topology::new(2, 2, 6); + let shared = Shared::build(true); + shared.publish_on(20); + let busy = busy(&topo, &[20, 3]); + let call = shared.complete_on(3); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.die[worker as usize], topo.die[20], "completion processing stays on the submitter's die"); + assert_eq!(topo.cluster[worker as usize], topo.cluster[20]); + assert_ne!(worker, 20); +}} + +fn test_m5_idle_submitter() {{ + // A submitter waiting on a fence leaves its CPU idle: running there preempts nobody. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + let busy = busy(&topo, &[]); + let call = shared.complete_on(3); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16]); + assert_eq!(submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_submitter_moves() {{ + // Two submitters on different clusters: the event work follows the last one, and never + // preempts either while it publishes. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + shared.publish_on(16); + shared.publish_on(7); + let busy = busy(&topo, &[16, 7]); + let call = shared.complete_on(16); + assert_eq!(call, Call::On {{ cpu: 7 }}); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[7]); + assert_eq!(submitter_switches(worker, 7, &busy) + submitter_switches(worker, 16, &busy), 0); +}} + +fn test_m5_before_first_publication() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + assert!(shared.submitter().is_none()); + let call = shared.complete_on(4); + assert_eq!(call, Call::Local {{ queuer: 4 }}, "nothing published yet: queued locally"); + let worker = worker_cpu(&topo, &shared.events, call, &busy(&topo, &[4])); + assert_eq!(topo.cluster[worker as usize], topo.cluster[4]); +}} + +fn test_m5_completion_stream() {{ + // Every completion of a deep queue arrives while the submitter publishes the next job. + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(true); + let mut switches = 0; + for job in 0..64u32 {{ + shared.publish_on(16); + let busy = busy(&topo, &[16]); + let irq = if job % 2 == 0 {{ 16 }} else {{ 1 }}; + let call = shared.complete_on(irq); + let worker = worker_cpu(&topo, &shared.events, call, &busy); + assert_eq!(topo.cluster[worker as usize], topo.cluster[16]); + switches += submitter_switches(worker, 16, &busy); + }} + assert_eq!(switches, 0, "completions must not cost the submitter context switches"); +}} + +fn test_other_runs_on_queuer() {{ + let topo = Topology::new(1, 3, 6); + let shared = Shared::build(false); + shared.publish_on(16); + assert!(shared.submitter().is_none(), "only M5 records the submitter"); + let busy = busy(&topo, &[3, 16]); + let call = shared.complete_on(3); + assert_eq!(call, Call::Local {{ queuer: 3 }}); + assert_eq!(worker_cpu(&topo, &shared.events, call, &busy), 3, + "other G17 parts run the event work where it is queued, as system_highpri_wq"); +}} + +fn test_disabled_submission() {{ + let shared = Shared::build(true); + let shared = Arc::new(Shared {{ + submission_enabled: false, + events: shared.events.clone(), + follows_submitter: true, + submitter: AtomicU32::new(u32::MAX), + }}); + shared.publish_on(16); + kernel::cpu::run_on(16, || shared.queue_event_records()); + assert!(shared.events.calls.borrow().is_empty(), "no event work without submission"); +}} + +fn main() {{ + assert!({str(derive_ok).lower()}, "Gpu::new() must derive the events queue from follows_submitter"); + assert!({str(field_ok).lower()}, "Shared::follows_submitter must take the value the queue was built for"); + assert!({str(only_here).lower()}, "aurora_g17_events must be allocated only by Shared::new_events_queue()"); + assert!({str(fence_ok).lower()}, "the schedulers' timeout work must stay on the events queue"); + test_m5_completion_on_submitter_cpu(); + test_m5_completion_on_other_cluster(); + test_m5_two_dies(); + test_m5_idle_submitter(); + test_m5_submitter_moves(); + test_m5_before_first_publication(); + test_m5_completion_stream(); + test_other_runs_on_queuer(); + test_disabled_submission(); + test_m5_queue_kind(); + test_other_queue_kind(); + println!("PASS g17-m5-event-placement-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--mutation', + choices=[ + 'percpu-always', + 'unbound-always', + 'aim-local', + 'record-always', + 'not-reclaim', + 'split-flag', + ], + ) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-event-placement-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '--edition', '2021', '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 322ec912ef14ee..7dc56b2897667f 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -261,6 +261,9 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-event-placement-tests.py': [([], PASS)] + + mutations('--mutation', ('percpu-always', 'unbound-always', 'aim-local', + 'record-always', 'not-reclaim', 'split-flag'), []), 'g17-m5-render-fast-done-tests.py': [([], PASS)] + mutations('--mutation', ('hold-m5-outer-across-doorbell', 'hold-render-lock-across-doorbell', From 93f3a209cc96cbdf4e0eb790a8f98eff8dccdffa Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 18:45:48 -0500 Subject: [PATCH 1059/1514] drm/asahi: g17: retire a lent render pair's completions when it is returned The direct render path lends an owner's pair out of the registry under the device mutex, prepares and publishes into it without that mutex, and puts it back under the mutex again. An event pass that meets a completion of a lent pair skips the pair and records the completion for its borrower (missed_event); the return then requested another event pass. Since M5 event work runs beside the submitter rather than on its CPU, that pass starts on another CPU while the submitter goes straight on to its next publication, whose lend takes the device mutex first and lends the same pair again: the pass finds it lent once more and records the completion again. A client publishing a run of passes keeps its pair lent for most of that run, so a completion of its previous submission retires only once the whole run is published. A client keeping two multi-pass submissions in flight waits for the older one's fence before it submits again, so each of its submissions waited for the publication of the next one: such clients ran 8 to 31% slower than with the event work on the submitter's CPU, where the requested pass preempted the submitter before its next lend, while clients with one submission in flight ran 5% faster. Each such pass also took the device mutex four times: its single-hold fast path fell back to the full pass, which takes the mutex three more times to find nothing to retire and arm the rescan poll. It did the same whenever a retirement left later work of the pair in flight with its completion noted, the steady state of a pair with several renders in flight. Those holds contend with the publisher's lends and returns. - The return observes the pair itself, in the hold that put it back: Firmware::observe_returned_render() runs the event worker's single-hold retirement (fast_observe_renders(), which try_fast_observe_render() now shares) for that slot alone, under the same steady-state checks of every slot, with a live preparation lease, outside recovery and a crash, into a collector of the worker's size (Shared::render_collector) that is taken only with try_lock() and finished after the device mutex is dropped. A state the fast path leaves to the full pass (another slot's error, timeout, close or growth, a replay, recovery, a fault, no room), or a busy collector, requests the event pass as before. As on the watchdog's final scan, the retirement runs off the event worker: completion fences have contexts of their own and ordered outputs publish only after their predecessors, so nothing signals out of order. - render_needs_rescan() no longer counts a borrowed pair whose completion is recorded for its borrower: every borrower's return (direct, preparation, growth) observes it or requests a pass. - The fast path retires every ready observation in its hold instead of stopping at the first retirement that leaves noted work in flight, and reports that state as Rescan rather than Fallback. runtime_event_turn() then ends the pass in its first hold and arms the rescan poll, which is all the full pass would add; so does a pass whose render completions found nothing to retire because their pairs are lent (Idle with render masks). A returned pair in that state also arms the poll. The publication itself still takes the device mutex twice: the free-list lease, the parameter-buffer reference, the admission hold and the registry entry of a loan are device-wide state that retirement, growth, parking and teardown change under it. Host tests: tools/asahi/g17-render-return-observe-tests.py compiles the production take_pair(), return_pair(), take_missed_event(), retain_render_completions(), render_needs_rescan() and observation loop against host stubs: a completion owed to a borrower needs no rescan and ends the worker's pass, a return retires everything that completed during its loan (two completions too) in order and only in its own slot, every non-steady state falls back, a fault is settled, and a publisher, an event worker and a GPU thread retire 4000 commands exactly once and in order, the returns retiring some; structural checks cover render_direct()'s guards, try_lock() and off-lock finish and the event pass's single-hold exit (13 mutation controls). g17-m5-render-fast-done-tests.py follows the shared loop. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/mod.rs | 7 + drivers/gpu/drm/asahi/g17/runtime/events.rs | 14 +- drivers/gpu/drm/asahi/g17/runtime/render.rs | 7 +- .../drm/asahi/g17/runtime/render/direct.rs | 47 +- .../drm/asahi/g17/runtime/render/observe.rs | 56 +- tools/asahi/g17-m5-render-fast-done-tests.py | 6 +- .../asahi/g17-render-return-observe-tests.py | 622 ++++++++++++++++++ tools/asahi/run-host-tests.py | 6 + 8 files changed, 748 insertions(+), 17 deletions(-) create mode 100755 tools/asahi/g17-render-return-observe-tests.py diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 255788453d6f4e..48b9a07cd7b854 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1298,6 +1298,11 @@ struct Shared { /// Preallocated completion collector owned exclusively by `run_runtime_events`. #[pin] worker_deferred: Mutex>, + /// Collector, as large as the event worker's, for the observation a render borrower owes the + /// pair it puts back (`Backend::render_direct`). Taken only with `try_lock`, so no borrower + /// waits for another, and finished after the device mutex is released. + #[pin] + render_collector: Mutex, /// M5: the event work runs beside the CPU that last published work, in its affinity pod. follows_submitter: bool, /// Multi-die M5: restrict each scheduler's ordered submit queue to the creating CPU's @@ -1815,6 +1820,7 @@ impl Gpu { .as_ref() .map_or(0, stats::StateFrequencies::max_pstate); let worker_deferred = runtime::DeferredBatch::worker()?; + let render_collector = runtime::DeferredBatch::worker()?; let shared = Arc::pin_init( pin_init!(Shared { drm <- new_mutex!(Some(dev.into()), "g17::Shared::drm"), @@ -1860,6 +1866,7 @@ impl Gpu { Some(worker_deferred), "g17::Shared::worker_deferred" ), + render_collector <- new_mutex!(render_collector, "g17::Shared::render_collector"), follows_submitter, pin_scheduler_cluster: m5 && id.num_dies > 1, submitter: AtomicU32::new(u32::MAX), diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 1a2d4de2f944da..a352014ea3876f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -567,6 +567,7 @@ impl crate::g17::Shared { // fences are signalled right after unlocking. let mut fast_done = false; let mut render_changed = false; + let mut rescan = false; if !recover && !requested && !self.crashed.load(core::sync::atomic::Ordering::Acquire) @@ -582,6 +583,12 @@ impl crate::g17::Shared { true } super::render::observe::FastRenderOutcome::Idle => true, + // The full pass would find nothing more and arm the rescan poll. + super::render::observe::FastRenderOutcome::Rescan => { + render_changed = deferred.pending() != before; + rescan = true; + true + } super::render::observe::FastRenderOutcome::Fallback => { render_changed = deferred.pending() != before; false @@ -590,7 +597,9 @@ impl crate::g17::Shared { } else { false }; - if render_clean && (compute_scan.is_some() || render_changed) { + // Render completions that found nothing to retire here (Idle) are owed to the + // borrowers of their pairs, which observe them on return. + if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) { let scan = match compute_scan { Some(scan) => scan, None => { @@ -629,7 +638,8 @@ impl crate::g17::Shared { if let Some(delay) = firmware.idle_check(now, true)? { self.queue_idle(delay); } - let polling = scan.polling || firmware.non_compute_runtime_polling(now); + let polling = + rescan || scan.polling || firmware.non_compute_runtime_polling(now); if polling { self.queue_poll(); } else if channel::Events::pending(&firmware.init, Role::Primary)? diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 335640c9ad8c01..6764f2f5f71a12 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1298,11 +1298,16 @@ impl Registry { } pub(in crate::g17) fn render_needs_rescan(&self) -> bool { self.render.entries.iter().flatten().any(|entry| { + // A completion that arrived while the pair was borrowed (`missed_event`) is owed to + // its borrower, whose return observes the pair or requests an event pass: no + // rescan waits for it. let active = entry .pair .as_ref() .map_or( - (entry.preparing.is_some() || entry.growing) && entry.borrowed_active, + (entry.preparing.is_some() || entry.growing) + && entry.borrowed_active + && !entry.missed_event, |pair| pair.published_in_flight(), ); active diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 688bfe8057bb9a..84b3b56848541a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -11,6 +11,7 @@ //! retirement can complete its commands or their free-list references. use super::super::{Backend, DeferredBatch}; +use super::observe::FastRenderOutcome; use crate::g17::{ job::Packet, object::Allocator, @@ -296,19 +297,17 @@ impl crate::g17::Firmware { /// Takes a lent pair back and settles what its publication held: the /// free-list preparation is activated once published, rolled back with the - /// parameter-buffer reference otherwise. + /// parameter-buffer reference otherwise. True when a completion of the pair + /// arrived while it was lent: the caller owes the pair that observation. fn return_render( &mut self, slot: u8, loan: &mut Loan, activation: Option<(u16, u64)>, packet: &Arc, - ) -> Result { + ) -> Result { self.queues.render.return_pair(slot, &mut loan.pair)?; - if self.queues.render.take_missed_event(slot) { - // The record is retired by the next pass's observation, like any completion. - self.primary.state.shared.queue_event_records(); - } + let missed = self.queues.render.take_missed_event(slot); let entry = self.queues.render.entry_mut(slot)?; // A failure or timeout recorded against the lent pair is settled by the // event worker's collector, as after any other loan. @@ -337,7 +336,7 @@ impl crate::g17::Firmware { self.queues.render.pools.rollback(preparation); self.queues.buffers.release(loan.buffer)?; } - Ok(()) + Ok(missed) } } @@ -463,13 +462,47 @@ impl Backend { Ok(()) })(); drop(m5_claim); + // The collector of the observation the return may owe, taken without waiting. + let mut collector = None; let returned = { let mut state = self.shared.state.lock(); match (*state).as_deref_mut() { Some(firmware) => { let returned = firmware.return_render(slot, &mut loan, activation, packet); + let returned = match returned { + // A completion arrived while the pair was lent. The event pass it would + // request takes the device mutex from another CPU after this owner's + // next lend and finds the pair lent again: observe it here, in this + // hold, unless recovery, a crash or another borrower's observation + // leaves it to that pass. + Ok(true) => { + if !recovery_started + && lease.is_current() + && !self.shared.crashed.load(Ordering::Acquire) + { + collector = self.shared.render_collector.try_lock(); + } + match collector.as_deref_mut() { + Some(batch) => firmware.observe_returned_render(slot, batch), + None => Ok(FastRenderOutcome::Fallback), + } + .map(|outcome| match outcome { + // Retired by the next pass's observation, like any completion. + FastRenderOutcome::Fallback => self.shared.queue_event_records(), + FastRenderOutcome::Rescan => self.shared.queue_poll(), + FastRenderOutcome::Done | FastRenderOutcome::Idle => {} + }) + } + Ok(false) => Ok(()), + Err(error) => Err(error), + }; let grow_ready = firmware.render_grow_ready(); drop(state); + // Fences signal off the device mutex, before another borrower can collect. + if let Some(batch) = collector.as_deref_mut() { + batch.finish(); + } + drop(collector); if grow_ready { self.shared.queue_grow(); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs index 2d8d02d8ab7cef..53a0029b37dd7d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs @@ -16,6 +16,11 @@ pub(in crate::g17::runtime) enum FastRenderOutcome { Idle, /// Retired the single ready render observation cleanly with no further render work pending. Done, + /// Retired every ready observation in steady state, while published work whose completion + /// was noted stays in flight (`render_needs_rescan`): its later completions are observed by + /// their own events or by the rescan poll, which is all the full `observe_renders()` pass + /// would add. + Rescan, } impl crate::g17::Firmware { @@ -48,11 +53,17 @@ impl crate::g17::Firmware { /// The first slot from `start` whose pair has news to observe: published work in flight, the /// fragment queue's notification seen (`completion_noted`), and an observation the pair accepts. fn next_render_observation(&mut self, start: usize) -> Result> { + let end = self.queues.render.entries.len(); + self.next_render_observation_in(start, end) + } + + /// [`Self::next_render_observation`] among the slots `start..end`. + fn next_render_observation_in(&mut self, start: usize, end: usize) -> Result> { if self.recovery.pending() { return Ok(None); } let state = crate::g17::recovery::Memory::recovery_state(&self.init)?; - for slot in start..self.queues.render.entries.len() { + for slot in start..end.min(self.queues.render.entries.len()) { let Some(entry) = self.queues.render.entries[slot].as_ref() else { continue; }; @@ -143,6 +154,37 @@ impl crate::g17::Firmware { pub(in crate::g17::runtime) fn try_fast_observe_render( &mut self, deferred: &mut DeferredBatch, + ) -> Result { + let end = self.queues.render.entries.len(); + self.fast_observe_renders(1, end, deferred) + } + + /// The observation a borrower owes the pair it has just put back into `slot`, in the hold + /// that put it back, with a live preparation lease and a collector of the event worker's size + /// (`deferred`): the event worker's single-lock retirement ([`Self::try_fast_observe_render`]) + /// of that slot alone. `Fallback` leaves the slot to the worker's full pass; otherwise its + /// ready completions are retired (`Rescan`: and the rescan poll covers what stays in flight). + /// + /// The event pass a completion of a lent pair would otherwise request runs on another CPU and + /// takes the device mutex after the borrower's next lend of the same pair, so it finds the + /// pair lent again; observing here retires every completion by the return of the loan it + /// arrived during. + pub(in crate::g17::runtime) fn observe_returned_render( + &mut self, + slot: u8, + deferred: &mut DeferredBatch, + ) -> Result { + let slot = usize::from(slot); + self.fast_observe_renders(slot, slot + 1, deferred) + } + + /// [`Self::try_fast_observe_render`] for the observations of the slots `start..end`; the + /// steady-state checks still cover every slot. + fn fast_observe_renders( + &mut self, + start: usize, + end: usize, + deferred: &mut DeferredBatch, ) -> Result { if self.recovery.pending() || self.queues.render.replay_parked() @@ -165,9 +207,9 @@ impl crate::g17::Firmware { } let mut retired_any = false; for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS { - let Some(slot) = self.next_render_observation(1)? else { + let Some(slot) = self.next_render_observation_in(start, end)? else { return Ok(if self.queues.render_needs_rescan() { - FastRenderOutcome::Fallback + FastRenderOutcome::Rescan } else if retired_any { FastRenderOutcome::Done } else { @@ -220,15 +262,19 @@ impl crate::g17::Firmware { || self.recovery.pending() || self.render_grow_pending() || self.render_grow_ready() - || self.queues.render_needs_rescan() { return Ok(FastRenderOutcome::Fallback); } + // Work still in flight behind this front keeps its noted completion: retire whatever + // else is ready in this hold before deciding. retired_any = true; } - if self.next_render_observation(1)?.is_some() || self.queues.render_needs_rescan() { + if self.next_render_observation_in(start, end)?.is_some() { return Ok(FastRenderOutcome::Fallback); } + if self.queues.render_needs_rescan() { + return Ok(FastRenderOutcome::Rescan); + } Ok(if retired_any { FastRenderOutcome::Done } else { diff --git a/tools/asahi/g17-m5-render-fast-done-tests.py b/tools/asahi/g17-m5-render-fast-done-tests.py index 21dfb2db908964..f84dff058ee0dd 100755 --- a/tools/asahi/g17-m5-render-fast-done-tests.py +++ b/tools/asahi/g17-m5-render-fast-done-tests.py @@ -69,7 +69,8 @@ def build_harness(mutation=None): runtime_src = (G17 / 'runtime.rs').read_text() notify_render = item(direct_src, 'fn notify_render(') - try_fast = item(observe_src, 'pub(in crate::g17::runtime) fn try_fast_observe_render(') + try_fast_entry = item(observe_src, 'pub(in crate::g17::runtime) fn try_fast_observe_render(') + try_fast = item(observe_src, 'fn fast_observe_renders(') observe_fn = item(observe_src, 'pub(in crate::g17) fn observe_renders(') turn = item(events_src, 'fn runtime_event_turn(') tracked_cv = item(mod_src, 'impl TrackedCondVar') @@ -147,7 +148,8 @@ def build_harness(mutation=None): and 'self.queues.render_needs_rescan()' in try_fast and 'for _ in 0..crate::hw::t8140::queues::RENDER_SLOTS {' in try_fast and 'if !deferred.has_room(2)' in try_fast - and 'self.next_render_observation(1)?.is_some()' in try_fast + and 'self.next_render_observation_in(start, end)?.is_some()' in try_fast + and 'self.fast_observe_renders(1, end, deferred)' in try_fast_entry and 'FastRenderOutcome::Done' in try_fast ) diff --git a/tools/asahi/g17-render-return-observe-tests.py b/tools/asahi/g17-render-return-observe-tests.py new file mode 100755 index 00000000000000..3f8574c45ffd84 --- /dev/null +++ b/tools/asahi/g17-render-return-observe-tests.py @@ -0,0 +1,622 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: a lent render pair's completions are observed by the borrower that returns it. + +The direct render path lends an owner's pair out of the registry under the device mutex, +prepares and publishes into it without that mutex, and takes it back under the mutex again. +While it is lent, event passes skip it and record the completion for its borrower +(`missed_event`). This compiles the production code that keeps such a completion from waiting +for the end of the owner's run of publications against host stubs: + +- `retain_render_completions()`, `render_needs_rescan()`, `take_missed_event()`, `take_pair()` + and `return_pair()` from drivers/gpu/drm/asahi/g17/runtime/render.rs; +- `next_render_observation()`, `next_render_observation_in()`, `try_fast_observe_render()`, + `observe_returned_render()` and `fast_observe_renders()` from runtime/render/observe.rs, + with the production `FastRenderOutcome` and `completion_noted()`. + +It checks that + +a. an event pass that meets only completions owed to borrowers neither asks for a rescan nor + falls back to the multi-hold slow path, while a borrowed pair whose completion was noted + before it was lent still does; +b. the borrower's observation of the slot it returned retires every completion that arrived + during the loan (also several), in order, exactly once, touches no other slot, reports a + rescan while published work stays in flight, and leaves everything to the event worker in + any state the worker's fast path would not handle (another slot's error, timeout, close or + growth, a replay, recovery, a fault, no room in the collector); +c. with a publisher, an event worker and the GPU running on three threads, every command + retires exactly once and in order, and the publisher retires completions on return; +d. structurally, that `render_direct()` returns the missed flag from `return_render()`, + observes in the hold that put the pair back only with a live preparation lease and no + recovery, takes the collector with `try_lock()`, finishes it after the device mutex and + otherwise requests the event pass or, for a rescan, the poll; and that `runtime_event_turn()` + ends in its first hold a pass whose render completions are owed to borrowers or that leaves + only a rescan, arming the poll for it. + +Each mutation restores the old behaviour or drops one part of the rule, and must fail an +assertion of the compiled harness. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # (a) The old rescan rule: a completion owed to the borrower still asks for a rescan. + 'rescan-owed': [('render', ' && entry.borrowed_active\n && !entry.missed_event,', + ' && entry.borrowed_active,')], + # (b) The returned slot's observation scans every slot, or ignores the steady-state gate. + 'observe-all-slots': [('observe', 'self.fast_observe_renders(slot, slot + 1, deferred)', + 'self.fast_observe_renders(1, self.queues.render.entries.len(), deferred)')], + 'observe-ignores-gate': [('observe', ' if entry.pending_error.is_some()\n || entry.pending_timeout\n' + ' || entry.closed\n || entry.growing\n', + ' if false\n')], + # (b) The old loop: it stops at the first retirement that leaves work in flight, or calls that + # a fallback. + 'rescan-in-loop-bail': [('observe', ' || self.render_grow_ready()\n {\n return Ok(FastRenderOutcome::Fallback);\n }\n' + ' // Work still in flight', + ' || self.render_grow_ready()\n || self.queues.render_needs_rescan()\n {\n' + ' return Ok(FastRenderOutcome::Fallback);\n }\n // Work still in flight')], + 'rescan-is-fallback': [('observe', ' if self.queues.render_needs_rescan() {\n return Ok(FastRenderOutcome::Rescan);\n }', + ' if self.queues.render_needs_rescan() {\n return Ok(FastRenderOutcome::Fallback);\n }'), + ('observe', ' return Ok(if self.queues.render_needs_rescan() {\n FastRenderOutcome::Rescan', + ' return Ok(if self.queues.render_needs_rescan() {\n FastRenderOutcome::Fallback')], + # (d) Structural: the borrower drops the missed flag, observes without the guards, blocks on the + # collector, signals under the device mutex, never requests the pass, or the event pass + # takes the slow path for owed completions. + 'missed-dropped': [('direct', ' Ok(missed)\n }', ' Ok(false)\n }')], + 'observe-in-recovery': [('direct', ' if !recovery_started\n && lease.is_current()\n' + ' && !self.shared.crashed.load(Ordering::Acquire)\n {\n', + ' if true {\n')], + 'collector-blocks': [('direct', 'collector = self.shared.render_collector.try_lock();', + 'collector = Some(self.shared.render_collector.lock());')], + 'finish-under-mutex': [('direct', ' drop(state);\n // Fences signal off the device mutex, before another borrower can collect.\n' + ' if let Some(batch) = collector.as_deref_mut() {\n batch.finish();\n }\n', + ' if let Some(batch) = collector.as_deref_mut() {\n batch.finish();\n }\n' + ' drop(state);\n')], + 'no-pass-requested': [('direct', 'FastRenderOutcome::Fallback => self.shared.queue_event_records(),', + 'FastRenderOutcome::Fallback => {}')], + 'rescan-no-poll': [('direct', 'FastRenderOutcome::Rescan => self.shared.queue_poll(),', 'FastRenderOutcome::Rescan => {}')], + 'worker-rescan-slow-path': [('events', ' rescan = true;\n true\n', + ' rescan = true;\n false\n')], + 'owed-slow-path': [('events', 'if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) {', + 'if render_clean && (compute_scan.is_some() || render_changed) {')], +} + + +def build(mutation=None): + files = { + 'render': (G17 / 'runtime/render.rs').read_text(), + 'observe': (G17 / 'runtime/render/observe.rs').read_text(), + 'direct': (G17 / 'runtime/render/direct.rs').read_text(), + 'events': (G17 / 'runtime/events.rs').read_text(), + 'queue': (G17 / 'queue/render.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + render, observe, direct, events, queue = (files[k] for k in ('render', 'observe', 'direct', 'events', 'queue')) + + def host(code): + return (code.replace('pub(in crate::g17::runtime) ', '').replace('pub(in crate::g17) ', '') + .replace('pub(super) ', '').replace('pub(crate) ', '') + .replace('crate::g17::recovery::Memory::recovery_state', 'Memory::recovery_state') + .replace('crate::g17::queue::render::completion_noted', 'completion_noted') + .replace('crate::hw::t8140::queues::RENDER_SLOTS', 'RENDER_SLOTS') + .replace('crate::g17::now_ns()', 'now_ns()').replace('kick::Id::qid', 'Id::qid') + .replace('KBox', 'Box')) + + outcome = host(item(observe, 'pub(in crate::g17::runtime) enum FastRenderOutcome')) + noted = host(item(queue, 'pub(crate) fn completion_noted(')) + state_fns = host('\n'.join(item(render, signature) for signature in [ + ' fn entry(&self, slot: u8)', ' fn entry_mut(&mut self, slot: u8)', 'fn take_missed_event(', + 'fn take_pair(&mut self, slot: u8', 'fn return_pair(&mut self, slot: u8', + ])) + registry_fns = host('\n'.join(item(render, signature) for signature in [ + 'pub(in crate::g17) fn render_needs_rescan(', 'pub(in crate::g17) fn retain_render_completions(', + ])) + firmware_fns = host('\n'.join(item(observe, signature) for signature in [ + 'fn next_render_observation(&mut self', 'fn next_render_observation_in(', + 'pub(in crate::g17::runtime) fn try_fast_observe_render(', 'pub(in crate::g17::runtime) fn observe_returned_render(', + 'fn fast_observe_renders(', + ])) + + render_direct = item(direct, 'pub(in crate::g17::runtime) fn render_direct(') + return_fn = item(direct, 'fn return_render(') + turn = item(events, 'fn runtime_event_turn(') + structure = { + 'return_render reports a completion missed during the loan': ordered_ok( + return_fn, ') -> Result {', 'self.queues.render.return_pair(slot, &mut loan.pair)?;', + 'let missed = self.queues.render.take_missed_event(slot);', 'Ok(missed)') + and 'queue_event_records' not in return_fn, + 'render_direct observes in the returning hold, signals after it': ordered_ok( + render_direct, 'let mut collector = None;', 'let mut state = self.shared.state.lock();', + 'let returned = firmware.return_render(slot, &mut loan, activation, packet);', + 'let returned = match returned {', 'Ok(true) => {', + 'if !recovery_started\n && lease.is_current()\n' + ' && !self.shared.crashed.load(Ordering::Acquire)\n {', + 'collector = self.shared.render_collector.try_lock();', + 'Some(batch) => firmware.observe_returned_render(slot, batch),', + 'None => Ok(FastRenderOutcome::Fallback),', + 'FastRenderOutcome::Fallback => self.shared.queue_event_records(),', + 'FastRenderOutcome::Rescan => self.shared.queue_poll(),', + 'FastRenderOutcome::Done | FastRenderOutcome::Idle => {}', 'Ok(false) => Ok(()),', + 'Err(error) => Err(error),', 'drop(state);', 'batch.finish();', 'drop(collector);', + 'self.shared.note_changed();', 'drop(lease);', 'if let Err(error) = returned {', + 'self.shared.lose_device_quietly();'), + 'the collector is never waited for': 'render_collector.lock()' not in render_direct, + 'an event pass whose completions are owed, or that leaves a rescan, ends in its first hold': + ordered_ok(turn, 'let mut rescan = false;', 'firmware.try_fast_observe_render(deferred)?', + 'FastRenderOutcome::Rescan => {', 'rescan = true;\n true\n', + 'if render_clean && (compute_scan.is_some() || render_changed || masks != [0; 2]) {', + 'rescan || scan.polling || firmware.non_compute_runtime_polling(now);', + 'if polling {\n self.queue_poll();', 'fast_done = true;'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@OUTCOME@@', outcome).replace('@@NOTED@@', noted).replace('@@STATE@@', state_fns) + .replace('@@REGISTRY@@', registry_fns).replace('@@FIRMWARE@@', firmware_fns) + .replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports, unreachable_code)] +use std::collections::VecDeque; +use std::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +const EIO: i32 = -5; +const EAGAIN: i32 = -11; +const EBUSY: i32 = -16; +const EINVAL: i32 = -22; +type Result = std::result::Result; +const RENDER_SLOTS: usize = 64; +fn now_ns() -> u64 { 1 } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +@@OUTCOME@@ + +@@NOTED@@ + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Id(u8); +impl Id { fn qid(self) -> u8 { self.0 } } +pub struct Context; +pub struct Packet { context: Arc, ordinal: u64 } +pub struct VmStatus; +#[derive(Clone, Copy)] +pub struct Dependencies; +#[derive(Clone, Copy)] +struct Reservation { slot: u8, ids: [Id; 2], owner: u64 } + +/// The production completion record a pair retires: the command's ordinal. +#[derive(Debug, PartialEq, Eq)] +pub enum Deferred { Retired(u64), Failed(u64) } +pub struct DeferredBatch { values: Vec, cap: usize } +impl DeferredBatch { + fn new(cap: usize) -> Self { Self { values: Vec::with_capacity(cap), cap } } + fn push(&mut self, value: Deferred) -> Result { + if self.values.len() == self.cap { return Err(EIO); } + self.values.push(value); + Ok(()) + } + fn has_room(&self, need: usize) -> bool { self.cap - self.values.len() >= need } + fn pending(&self) -> usize { self.values.len() } + fn finish(&mut self) -> Vec { std::mem::take(&mut self.values) } +} + +pub struct Observed { ordinal: u64 } +pub struct Host; +/// A render pair: its published commands in order and the fragment stamp the GPU writes. +pub struct Pair { + slot: u8, qids: [u8; 2], owner: u64, active: VecDeque, retired: Vec, + quarantined: bool, terminal: Option<(Arc, i32)>, fault_at: Option, +} +impl Pair { + fn slot(&self) -> u8 { self.slot } + fn qids(&self) -> [u8; 2] { self.qids } + fn owner(&self) -> Option { Some(self.owner) } + fn matches(&self, owner: u64, _: &Arc) -> Result { Ok(owner == self.owner) } + fn published_in_flight(&self) -> bool { !self.quarantined && !self.active.is_empty() } + fn in_flight(&self) -> bool { !self.active.is_empty() } + fn stamp_waiting(&self) -> bool { false } + fn dependency_snapshot(&self) -> Dependencies { Dependencies } + fn switch_in_flight(&self) -> Option { None } + /// The front is done once both stamps cover it. + fn observation_packet(&self, _masks: [u64; 2], stamps: [u32; 2], state: u32) -> Result> { + if self.quarantined || state != 0 { return Ok(None); } + Ok(self.active.front().copied().filter(|&ordinal| stamps.iter().all(|&s| u64::from(s) > ordinal))) + } + fn note_stamp_wait(&mut self, _: [u32; 2], _: u32, _: u64) -> Result { Ok(false) } + fn observe_front(&self) -> Result { Ok(Observed { ordinal: *self.active.front().ok_or(EIO)? }) } + fn retire_observed(&mut self, observed: Observed, _: u32, _: &mut Host, + defer: &mut impl FnMut(Deferred) -> Result) -> Result { + if self.active.front() != Some(&observed.ordinal) { return Err(EIO); } + if self.fault_at == Some(observed.ordinal) { + self.quarantined = true; + self.terminal = Some((Arc::new(VmStatus), EIO)); + for &ordinal in self.active.iter() { defer(Deferred::Failed(ordinal))?; } + self.active.clear(); + return Ok(true); + } + self.active.pop_front(); + self.retired.push(observed.ordinal); + defer(Deferred::Retired(observed.ordinal))?; + Ok(true) + } + fn take_terminal(&mut self) -> Option<(Arc, i32)> { self.terminal.take() } +} + +struct Entry { + reservation: Reservation, pair: Option>, preparing: Option>, + borrowed_active: bool, borrowed_dependencies: Option, borrowed_switch: Option, + event_masks: [u64; 2], missed_event: bool, closed: bool, + pending_error: Option<(Arc, i32)>, pending_timeout: bool, growing: bool, +} +pub struct RenderState { entries: Vec>, replay: bool } +impl RenderState { +@@STATE@@ + fn replay_parked(&self) -> bool { self.replay } + fn collect_retired(&mut self, _slot: usize) -> Result { Ok(()) } +} +pub struct Registry { render: RenderState } +impl Registry { +@@REGISTRY@@ +} +struct Recovery { pending: bool } +impl Recovery { fn pending(&self) -> bool { self.pending } } +struct Init { stamps: Vec, recovery_state: AtomicU32 } +impl Init { fn stamp(&self, qid: u8) -> Result<&AtomicU32> { self.stamps.get(usize::from(qid)).ok_or(EIO) } } +struct Memory; +impl Memory { fn recovery_state(init: &Init) -> Result { Ok(init.recovery_state.load(Ordering::Relaxed)) } } +struct SharedStub { event_records: AtomicUsize } +impl SharedStub { fn queue_event_records(&self) { self.event_records.fetch_add(1, Ordering::Relaxed); } } +struct StateStub { shared: SharedStub } +struct Primary { state: StateStub } +pub struct Firmware { recovery: Recovery, queues: Registry, init: Init, primary: Primary, grow: bool, settled: Vec } +impl Firmware { +@@FIRMWARE@@ + fn render_grow_pending(&self) -> bool { self.grow } + fn render_grow_ready(&self) -> bool { false } + fn release_render_lists(&mut self) -> Result { Ok(()) } + fn with_render(&mut self, slot: usize, operation: impl FnOnce(&mut Pair, &mut Host) -> Result) -> Result { + let pair = self.queues.render.entries[slot].as_mut().and_then(|entry| entry.pair.as_mut()).ok_or(EIO)?; + operation(pair, &mut Host) + } + /// The production settlement fans a terminal out to its VM; here it is recorded. + fn settle_render_terminal(&mut self, slot: usize, _deferred: &mut DeferredBatch) -> Result { + let terminal = self.queues.render.entries[slot].as_mut().and_then(|entry| entry.pair.as_mut()) + .and_then(|pair| pair.take_terminal()); + if terminal.is_some() { self.settled.push(slot); } + Ok(terminal.is_some()) + } +} + +const OWNER: u64 = 3; +const FRAGMENT_QID: u8 = 21; + +fn pair(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Box { + Box::new(Pair { slot, qids, owner: OWNER, active: ordinals.iter().copied().collect(), retired: Vec::new(), + quarantined: false, terminal: None, fault_at: None }) +} +fn entry(slot: u8, qids: [u8; 2], ordinals: &[u64]) -> Entry { + Entry { reservation: Reservation { slot, ids: [Id(qids[0]), Id(qids[1])], owner: OWNER }, + pair: Some(pair(slot, qids, ordinals)), preparing: None, borrowed_active: false, + borrowed_dependencies: None, borrowed_switch: None, event_masks: [0; 2], missed_event: false, + closed: false, pending_error: None, pending_timeout: false, growing: false } +} +fn firmware(entries: Vec>) -> Firmware { + Firmware { recovery: Recovery { pending: false }, queues: Registry { render: RenderState { entries, replay: false } }, + init: Init { stamps: (0..128).map(|_| AtomicU32::new(0)).collect(), recovery_state: AtomicU32::new(0) }, + primary: Primary { state: StateStub { shared: SharedStub { event_records: AtomicUsize::new(0) } } }, + grow: false, settled: Vec::new() } +} +/// The GPU finished every command below `through` on `qids`. +fn complete(fw: &Firmware, qids: [u8; 2], through: u32) { + for qid in qids { fw.init.stamp(qid).unwrap().store(through, Ordering::Release); } +} +fn mask(qid: u8) -> [u64; 2] { + let mut masks = [0u64; 2]; + masks[usize::from(qid) / 64] |= 1u64 << (qid % 64); + masks +} +fn retired(batch: &mut DeferredBatch) -> Vec { + batch.finish().into_iter().map(|d| match d { Deferred::Retired(o) => o, Deferred::Failed(o) => 1000 + o }).collect() +} +fn packet(ordinal: u64) -> Arc { Arc::new(Packet { context: Arc::new(Context), ordinal }) } +/// The direct path's loan: the production take_pair(), a publication, the production return_pair(). +fn lend(fw: &mut Firmware, slot: u8, ordinal: u64) -> Box { + fw.queues.render.take_pair(slot, OWNER, &packet(ordinal)).unwrap() +} +fn put_back(fw: &mut Firmware, slot: u8, mut lent: Box) -> bool { + let mut lent = Some(lent); + fw.queues.render.return_pair(slot, &mut lent).unwrap(); + fw.queues.render.take_missed_event(slot) +} + +fn main() { +@@STRUCTURE@@ + + let qids = [20u8, FRAGMENT_QID]; + // (a, b) One owner publishing a run of passes into slot 1 while the GPU finishes earlier ones. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1, 2]))]); + let mut worker = DeferredBatch::new(64); + let mut collector = DeferredBatch::new(64); + let mut next = 3u64; + for done in 1..=3u32 { + let mut lent = lend(&mut fw, 1, next); + lent.active.push_back(next); + next += 1; + // The GPU finishes the front while the pair is lent; the event pass skips it and records + // the completion for its borrower. + complete(&fw, qids, done); + let matched = fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert_eq!(matched, mask(FRAGMENT_QID)); + assert!(!fw.queues.render_needs_rescan(), "a completion owed to the borrower needs no rescan"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Idle), + "the event pass ends in its first hold"); + assert!(retired(&mut worker).is_empty()); + // The return observes it in the same hold: retired, in order; later passes stay in flight. + assert!(put_back(&mut fw, 1, lent), "the completion is owed"); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![u64::from(done) - 1], "retired by the return of its loan"); + } + // Two completions during one loan are both retired by its return. + let mut lent = lend(&mut fw, 1, next); + lent.active.push_back(next); + complete(&fw, qids, 5); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![3, 4]); + // The GPU drains: the event worker retires the rest and clears the masks. + complete(&fw, qids, 7); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Done)); + assert_eq!(retired(&mut worker), vec![5, 6]); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().event_masks, [0; 2]); + assert_eq!(fw.queues.render.entries[1].as_ref().unwrap().pair.as_ref().unwrap().retired, (0..7).collect::>()); + // Nothing in flight, nothing missed. + let lent = lend(&mut fw, 1, 7); + assert!(!put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Idle)); + + // (a) A completion noted before the loan (no missed record) still asks for a rescan. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0]))]); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + let lent = lend(&mut fw, 1, 1); + assert!(fw.queues.render_needs_rescan(), "noted before the loan: the rescan stays"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Rescan)); + put_back(&mut fw, 1, lent); + + // (b) The returned slot only: another owner's ready pair in slot 2 stays with the worker. + let other = [30u8, 31]; + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0])), Some(entry(2, other, &[0]))]); + let lent = lend(&mut fw, 1, 1); + complete(&fw, qids, 1); + complete(&fw, other, 1); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + fw.queues.retain_render_completions(mask(31)); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Rescan)); + assert_eq!(retired(&mut collector), vec![0], "only the returned slot is observed"); + assert_eq!(fw.queues.render.entries[2].as_ref().unwrap().pair.as_ref().unwrap().active.len(), 1, + "the other slot is left to the event worker"); + assert_eq!(fw.try_fast_observe_render(&mut worker), Ok(FastRenderOutcome::Done)); + assert_eq!(retired(&mut worker), vec![0]); + + // (b) Every state the worker's fast path leaves to its full pass is left to it here too. + for case in 0..7 { + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1])), Some(entry(2, other, &[]))]); + let lent = lend(&mut fw, 1, 2); + complete(&fw, qids, 2); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + assert!(put_back(&mut fw, 1, lent)); + let mut room = 64; + { + let e2 = fw.queues.render.entries[2].as_mut().unwrap(); + match case { + 0 => e2.pending_error = Some((Arc::new(VmStatus), EIO)), + 1 => e2.pending_timeout = true, + 2 => e2.closed = true, + 3 => e2.growing = true, + 4 => fw.queues.render.replay = true, + 5 => fw.recovery.pending = true, + _ => room = 1, + } + } + let mut small = DeferredBatch::new(room); + assert_eq!(fw.observe_returned_render(1, &mut small), Ok(FastRenderOutcome::Fallback), "case {} falls back", case); + assert!(retired(&mut small).is_empty(), "case {} retires nothing", case); + } + // A fault is settled in the same hold, then left to the worker's full pass. + let mut fw = firmware(vec![None, Some(entry(1, qids, &[0, 1]))]); + let lent = lend(&mut fw, 1, 2); + complete(&fw, qids, 1); + fw.queues.render.entries[1].as_mut().unwrap().preparing.as_ref().unwrap(); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + let mut lent = lent; + lent.fault_at = Some(0); + assert!(put_back(&mut fw, 1, lent)); + assert_eq!(fw.observe_returned_render(1, &mut collector), Ok(FastRenderOutcome::Fallback)); + assert_eq!(fw.settled, vec![1], "the terminal is settled, not dropped"); + assert_eq!(retired(&mut collector), vec![1000, 1001]); + + // (c) Three threads: a publisher lending and returning slot 1, the event worker, the GPU. + const PASSES: u64 = 4000; + let fw = Arc::new(Mutex::new(firmware(vec![None, Some(entry(1, qids, &[]))]))); + let collector = Arc::new(Mutex::new(DeferredBatch::new(256))); + let published = Arc::new(AtomicU64::new(0)); + let events = Arc::new(AtomicU64::new(0)); + let stop = Arc::new(AtomicBool::new(false)); + let by_return = Arc::new(AtomicU64::new(0)); + let gpu_done = Arc::new(AtomicU64::new(0)); + let worker_seen = Arc::new(AtomicU64::new(0)); + let signalled = Arc::new(Mutex::new(Vec::::new())); + let gpu = { + let (fw, published, events, stop, gpu_done) = + (fw.clone(), published.clone(), events.clone(), stop.clone(), gpu_done.clone()); + std::thread::spawn(move || { + let mut done = 0u64; + while !stop.load(Ordering::Acquire) || done < published.load(Ordering::Acquire) { + let target = published.load(Ordering::Acquire); + if done < target { + done += 1; + complete(&fw.lock().unwrap(), qids, done as u32); + gpu_done.store(done, Ordering::Release); + events.fetch_add(1, Ordering::Release); + } + std::thread::yield_now(); + } + }) + }; + let worker = { + let (fw, events, stop, signalled, published, worker_seen) = + (fw.clone(), events.clone(), stop.clone(), signalled.clone(), published.clone(), worker_seen.clone()); + std::thread::spawn(move || { + let mut seen = 0u64; + let mut batch = DeferredBatch::new(256); + loop { + let pending = events.load(Ordering::Acquire); + let requested = { + let fw = fw.lock().unwrap(); + fw.primary.state.shared.event_records.swap(0, Ordering::AcqRel) + }; + if pending == seen && requested == 0 { + if stop.load(Ordering::Acquire) { + let fw = fw.lock().unwrap(); + let e = fw.queues.render.entries[1].as_ref().unwrap(); + if e.pair.as_ref().is_some_and(|p| p.active.is_empty()) { break; } + drop(fw); + events.fetch_add(1, Ordering::Release); + } + std::thread::yield_now(); + continue; + } + seen = pending; + // One hold of the pass; its fences signal after it, as the full pass's + // observe_renders() does per hold, and a ready observation left behind (a + // full collector) gets the next hold. + let again = { + let mut fw = fw.lock().unwrap(); + fw.queues.retain_render_completions(mask(FRAGMENT_QID)); + match fw.try_fast_observe_render(&mut batch).unwrap() { + FastRenderOutcome::Fallback => fw.next_render_observation(1).unwrap().is_some(), + // The rescan poll requests another pass. + FastRenderOutcome::Rescan => { + fw.primary.state.shared.queue_event_records(); + false + } + _ => false, + } + }; + if again { + events.fetch_add(1, Ordering::Release); + } + worker_seen.store(seen, Ordering::Release); + signalled.lock().unwrap().extend(retired(&mut batch)); + } + }) + }; + { + let (fw, collector, published, signalled, by_return) = + (fw.clone(), collector.clone(), published.clone(), signalled.clone(), by_return.clone()); + for ordinal in 0..PASSES { + let mut lent = lend(&mut fw.lock().unwrap(), 1, ordinal); + lent.active.push_back(ordinal); + published.store(ordinal + 1, Ordering::Release); + for _ in 0..(ordinal % 7) { std::thread::yield_now(); } + if ordinal % 16 == 0 { + // Keep this loan until the GPU finished its command and the event pass met the + // lent pair: the return then owes, and makes, that observation. + while gpu_done.load(Ordering::Acquire) <= ordinal { std::thread::yield_now(); } + let event = events.load(Ordering::Acquire); + while worker_seen.load(Ordering::Acquire) < event { std::thread::yield_now(); } + } + let mut held = None; + { + let mut fw = fw.lock().unwrap(); + if put_back(&mut fw, 1, lent) { + held = collector.try_lock().ok(); + let outcome = match held.as_deref_mut() { + Some(batch) => fw.observe_returned_render(1, batch).unwrap(), + None => FastRenderOutcome::Fallback, + }; + // Fallback requests the pass, Rescan the poll that requests it. + if matches!(outcome, FastRenderOutcome::Fallback | FastRenderOutcome::Rescan) { + fw.primary.state.shared.queue_event_records(); + } + } + } + if let Some(batch) = held.as_deref_mut() { + let done = retired(batch); + by_return.fetch_add(done.len() as u64, Ordering::Relaxed); + signalled.lock().unwrap().extend(done); + } + } + } + stop.store(true, Ordering::Release); + gpu.join().unwrap(); + worker.join().unwrap(); + let fw = fw.lock().unwrap(); + let pair = fw.queues.render.entries[1].as_ref().unwrap().pair.as_ref().unwrap(); + assert_eq!(pair.retired, (0..PASSES).collect::>(), "every command retires once, in order"); + let mut all = signalled.lock().unwrap().clone(); + all.sort_unstable(); + assert_eq!(all, (0..PASSES).collect::>(), "every completion is signalled exactly once"); + assert!(by_return.load(Ordering::Relaxed) > 0, "returns retire what arrived during their loans"); + + println!("PASS g17-render-return-observe: completions of a lent pair are retired by its return"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-render-return-') as tmp: + path = Path(tmp) / 'observe.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True, timeout=600) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7dc56b2897667f..49c2ad5101f72c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -284,6 +284,12 @@ def mutations(flag, names, base, expect=KILL): 'g17-quarantine-drain-tests.py': [([], PASS)] + mutations('--mutation', ('no-drain-release', 'without-witness', 'ignore-leases', 'no-last-lease', 'witness-covers-later-failure', 'unquarantined-drain'), []), + 'g17-render-return-observe-tests.py': [([], PASS)] + + mutations('--mutation', ('rescan-owed', 'observe-all-slots', 'observe-ignores-gate', + 'rescan-in-loop-bail', 'rescan-is-fallback', 'missed-dropped', + 'observe-in-recovery', 'collector-blocks', 'finish-under-mutex', + 'no-pass-requested', 'rescan-no-poll', 'worker-rescan-slow-path', + 'owed-slow-path'), []), 'g17-render-direct-recovery-tests.py': [([], PASS)] + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', 'wrong-j813-pipe'), []), From 4dcc3b9c2e83993ed9653dfe202627251634159e Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 09:25:40 +0000 Subject: [PATCH 1060/1514] drm/asahi: mmu: skip healthy last-job VM drain on all GPUs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit 476cf7f1d3bb ("drm/asahi: g17: M5: give M5 VMs sparse tiles, render pool mappings and context pins") added a healthy last-job release fast path in VmJobGuard::drop() that skips closing admission and entering drain_mappings() when the VM is neither blocked, quarantined, draining, closed, nor failed and has zero pending commits, close ranges, deferred unmaps or closed objects, running only bo_deferred_cleanup() directly. That fast path was gated on self.vm.m5, so every depth-1 completion on non-M5 GPUs (G15, G16, non-M5 G17, and G18 — all of which install VmLifetime) still runs drain_mappings() synchronously before signalling the exported completion fence, taking an extra retirement residency lease, two additional lifetime.state mutex acquisitions, a waitqueue notify_all(), and transiently stalling concurrent admission while draining == true even when all cleanup queues are empty. The invariant checked under lifetime.state.lock() is identical across all GPU generations that use VmLifetime. Remove the self.vm.m5 restriction so all healthy last-job releases take the same lock-minimal fast path while keeping every fault, timeout, quarantine, close, commit, deferred-unmap, and recovery path on drain_mappings(). Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/mmu/lifetime.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index 9da7820dd92f65..8c64f4da869caa 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -704,9 +704,7 @@ impl Drop for VmJobGuard { // Healthy last-job release need not close mapping/job admission when // there is no accepted cleanup to drain. Keep every recovery, close, // in-progress commit and failed-cleanup path on the existing drain. - // M5 only: other G17 GPUs keep the drain on every last release. - if self.vm.m5 - && !state.blocked + if !state.blocked && !state.quarantined && !state.draining && !state.closed From 9579e14b493ba179ce2820807d662c83483e0b12 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 03:40:54 +1100 Subject: [PATCH 1061/1514] drm/asahi: validate helper programs before G14 27.2 queues take them The G14 firmware 27.2 queues take render and compute helper programs from the client and write them into the firmware commands, but nothing checked them first. The common compute translator refuses any helper, so the compute path removed the helper before translation, and the render admission only checked that queues without helper support saw none. Check each helper descriptor before a queue takes it. It must either be empty, or name a tagged program offset that the queue's USC window maps readable, plus an 8-byte-aligned argument block that the submitting VM maps read-write. A configuration word or argument block without a program is refused. The render vertex and fragment helpers and the compute helper all go through the same check, which sits next to the sampler validation in the shared UAPI module. Queues that do not encode helpers refuse them as before. The m3-uapi host test covers empty, valid, stray, unmapped, misaligned and read-only descriptors. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/agx_uapi.rs | 25 ++++++++++++ drivers/gpu/drm/asahi/m3/m3_submit.rs | 16 +++++++- tools/asahi/m3-uapi-tests.rs | 57 +++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/agx_uapi.rs b/drivers/gpu/drm/asahi/m3/agx_uapi.rs index 028ac81193fbb2..64912fffadb99e 100644 --- a/drivers/gpu/drm/asahi/m3/agx_uapi.rs +++ b/drivers/gpu/drm/asahi/m3/agx_uapi.rs @@ -599,6 +599,31 @@ pub(crate) fn validate_sampler( Ok(()) } +/// Validates a helper program descriptor for a queue whose commands encode helpers: either no +/// helper (all fields zero), or a tagged program offset that names a readable program in the +/// queue's USC window and an 8-byte-aligned argument block that the submitting VM maps +/// read-write. The configuration word is only accepted together with a program. +pub(crate) fn validate_helper( + queue: QueueUscWindow, + address_space: &A, + helper: UapiHelperProgram, +) -> Result<(), UapiTranslateError> { + if helper + == (UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }) + { + return Ok(()); + } + queue.full_program(address_space, helper.binary)?; + if helper.data & 7 != 0 { + return Err(UapiTranslateError::AddressAlignment); + } + require_range(address_space, helper.data, 8, GpuAccess::ReadWrite) +} + pub(crate) fn validate_attachments( address_space: &A, attachments: &UapiAttachmentList, diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 3ec3e7c00dbb3b..92b82e1c8097b6 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -398,9 +398,17 @@ impl queue::Queue for Queue { // The common translator validates the original command/attachment // addresses; this M3 scheduling hint changes none of them. payload.flags &= !wide; - // The common translator refuses helpers; a queue that encodes one takes it here. + // The common translator refuses helpers; a queue that encodes one validates and + // takes it here. let empty=agx_uapi::UapiHelperProgram{binary:0,config:0,data:0}; - let helper=if self.samplers_and_helpers {core::mem::replace(&mut payload.helper,empty)} else {empty}; + let helper=if self.samplers_and_helpers { + agx_uapi::validate_helper(agx_uapi::QueueUscWindow{base:self.usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}, + &AddressSpace(&self.vm),payload.helper).map_err(|e| { + pr_err!("M3 compute helper rejected {:?}: helper={:?}\n",e,payload.helper); + EINVAL + })?; + core::mem::replace(&mut payload.helper,empty) + } else {empty}; render_attachments.push([crate::m3::agx_attachments::Attachments::EMPTY;2],GFP_KERNEL)?; flushes.push(encode_attachments(&self.vm,&attachments)?,GFP_KERNEL)?; let c=agx_uapi::translate_compute_command(payload,attachments, @@ -501,5 +509,9 @@ fn validate_render(r: agx_uapi::UapiRenderCommand, usc: u64, space: &AddressSpac window.full_program(space,p.usc).map_err(|_| EINVAL)?; if !space.covers(usc+u64::from(p.usc & !63),64,GpuAccess::Read) { return Err(EINVAL); } } + // Only a queue that encodes helpers gets here with one (refused above otherwise). + for helper in [r.vertex_helper,r.fragment_helper] { + agx_uapi::validate_helper(window,space,helper).map_err(|_| EINVAL)?; + } Ok(()) } diff --git a/tools/asahi/m3-uapi-tests.rs b/tools/asahi/m3-uapi-tests.rs index 4dc6012f5213e7..dfbbdfe1c82ac1 100644 --- a/tools/asahi/m3-uapi-tests.rs +++ b/tools/asahi/m3-uapi-tests.rs @@ -750,6 +750,63 @@ fn attachment_validation_rejects_readonly_zero_and_wrapped_ranges() { } } +#[test] +fn helpers_are_empty_or_a_mapped_program_with_a_writable_argument_block() { + let queue = QueueUscWindow { + base: USC_WINDOW_SIZE, + user_start: 0x4000, + user_end: 2 * USC_WINDOW_SIZE, + }; + let mut region = Region { + start: queue.base + 8, + end: queue.base + 0x100, + writable: true, + }; + let none = UapiHelperProgram { + binary: 0, + config: 0, + data: 0, + }; + let helper = UapiHelperProgram { + binary: 9, + config: 0x40, + data: queue.base + 0x40, + }; + assert_eq!(validate_helper(queue, ®ion, none), Ok(())); + assert_eq!(validate_helper(queue, ®ion, helper), Ok(())); + // A configuration or argument block without a program. + for stray in [ + UapiHelperProgram { config: 0x40, ..none }, + UapiHelperProgram { data: helper.data, ..none }, + ] { + assert_eq!( + validate_helper(queue, ®ion, stray), + Err(UapiTranslateError::ProgramOffset) + ); + } + // A program outside the mapping, a misaligned, unmapped or missing argument block. + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { binary: 0x200, ..helper }), + Err(UapiTranslateError::AddressRange) + ); + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { data: helper.data + 4, ..helper }), + Err(UapiTranslateError::AddressAlignment) + ); + for data in [0, queue.base + 0x100, u64::MAX & !7] { + assert_eq!( + validate_helper(queue, ®ion, UapiHelperProgram { data, ..helper }), + Err(UapiTranslateError::AddressRange) + ); + } + // The argument block must be writable. + region.writable = false; + assert_eq!( + validate_helper(queue, ®ion, helper), + Err(UapiTranslateError::AddressRange) + ); +} + #[test] fn usc_windows_reject_misalignment_overflow_and_unmapped_programs() { let queue = QueueUscWindow { From 73b6819a053d45423aee0994d9a3b7260fd1f7f1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 04:00:50 +1100 Subject: [PATCH 1062/1514] dt-bindings: soc: apple: clpc: require machine-supplied low-power ceiling Document that a standalone apple,clpc node registers no platform profile when neither apple,low-power-frequency-max-mhz nor apple,high-power-mode is supplied, rather than inventing a fallback CPU frequency ceiling. Signed-off-by: Ryan Murray --- Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml index 064f8e7beac5b9..48c04851117496 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,clpc.yaml @@ -44,8 +44,8 @@ properties: The machine's CPU frequency ceiling in macOS's Low Power mode, in MHz, as the ADT's cpu-low-power-frequency-max has it. The low-power platform profile holds the CPU clusters to it, up to the next - frequency of their tables. When absent, the driver derives a ceiling - from the fastest CPU cluster's operating points. + frequency of their tables. When absent and apple,high-power-mode is + not set, no platform profile is registered. apple,low-power-mw: $ref: /schemas/types.yaml#/definitions/uint32 From 32a09b3e84103b1e32ba7506c0e3f1a285617249 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 04:00:51 +1100 Subject: [PATCH 1063/1514] soc: apple: clpc: drop 64% fallback, stop 10 Hz idle PHPC poll, harden PMC check Address three follow-ups on the standalone apple-clpc platform-profile: 1. Remove the hardcoded 64% fallback ceiling (APPLE_CLPC_LOW_POWER_PCT / auto_low_power). A standalone apple,clpc node now uses only the machine-supplied apple,low-power-frequency-max-mhz ceiling rounded up through each cluster's OPP table; if neither a ceiling nor High Power mode is supplied, probe returns -ENODEV and leaves Low Power unavailable until the bootloader handoff provides it. 2. Gate 100 ms SMC PHPC polling and on-time low-power wakeups on clpc->low_power_mw > 0. Static frequency ceilings are applied synchronously on profile_set, so T8112/T6040/T6041 stay at 0 Hz idle wakeups in low-power too; debugfs status reads PHPC on demand under sample_lock when low_power_mw == 0. 3. Verify dev->driver == &apple_pmc_driver.driver in apple_pmc_from_dev() so calling apple_pmc_rail_count() on a non-PMC parent with drvdata cannot type-confuse drvdata as struct apple_pmc. Update the apple-pmc and apple-clpc-gpu KUnit suites and the host CLPC test scripts to cover all three behaviours. Signed-off-by: Ryan Murray --- drivers/pmdomain/apple/pmc-test.c | 7 +- drivers/pmdomain/apple/pmc.c | 6 +- drivers/soc/apple/clpc.c | 266 ++++++++----------- tools/asahi/clpc-gpu-demand-tests.py | 15 +- tools/asahi/clpc-high-power-cleanup-tests.py | 7 +- 5 files changed, 130 insertions(+), 171 deletions(-) diff --git a/drivers/pmdomain/apple/pmc-test.c b/drivers/pmdomain/apple/pmc-test.c index 4e7f19d47317a1..46a62ca40f3fd9 100644 --- a/drivers/pmdomain/apple/pmc-test.c +++ b/drivers/pmdomain/apple/pmc-test.c @@ -170,11 +170,16 @@ static void apple_pmc_test_release_restores_ap_vote(struct kunit *test) static void apple_pmc_test_pending_floor(struct kunit *test) { struct apple_pmc *pmc = apple_pmc_test_alloc(test); - struct device dev = {}; + struct device dev = { .driver = &apple_pmc_driver.driver }; + struct device foreign = {}; + int dummy = 0x1234; void __iomem *reg; pmc->hw = &apple_pmc_hw_t8132; dev_set_drvdata(&dev, pmc); + dev_set_drvdata(&foreign, &dummy); + KUNIT_EXPECT_EQ(test, apple_pmc_rail_count(&foreign), 0U); + KUNIT_EXPECT_EQ(test, apple_pmc_rail_count(&dev), pmc->hw->rails); reg = pmc->voters + pmc->hw->ap_agent * pmc->hw->agent_stride; writel(0xa500, reg); writel(BIT(pmc->hw->ap_agent), reg + 4); diff --git a/drivers/pmdomain/apple/pmc.c b/drivers/pmdomain/apple/pmc.c index e93dc40bc10c1b..b039e04c8c692a 100644 --- a/drivers/pmdomain/apple/pmc.c +++ b/drivers/pmdomain/apple/pmc.c @@ -275,9 +275,13 @@ static int apple_pmc_agent_enable(struct apple_pmc *pmc, unsigned int agent, return ret; } +static struct platform_driver apple_pmc_driver; + static struct apple_pmc *apple_pmc_from_dev(struct device *dev) { - return dev ? dev_get_drvdata(dev) : NULL; + if (!dev || dev->driver != &apple_pmc_driver.driver) + return NULL; + return dev_get_drvdata(dev); } /** diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index c1a7d51cfdfce1..c7fbebf37891e2 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -68,13 +68,6 @@ enum apple_clpc_rail { #define APPLE_CLPC_GPU_BACKOFF_MS 100 /* Package power readings in the low-power profile: every 100 ms */ #define APPLE_CLPC_POWER_MS 100 -/* - * Policy fraction of the fastest CPU cluster's maximum frequency used as the - * low-power platform-profile ceiling when neither the DT nor the SoC table - * supplies an explicit frequency (matches macOS Low Power Mode's ~64% P-core - * ceiling). - */ -#define APPLE_CLPC_LOW_POWER_PCT 64 /* Why the last vote was cast, for debugfs */ #define APPLE_CLPC_REASON_CPU BIT(0) @@ -130,9 +123,6 @@ enum apple_clpc_rail { * @low_power_khz: CPU frequency ceiling of the low-power platform profile, * taken up to the next table frequency, for a node without * apple,low-power-frequency-max-mhz; 0 for none - * @auto_low_power: derive the low-power ceiling from the fastest CPU - * cluster's operating points (APPLE_CLPC_LOW_POWER_PCT) when neither DT - * nor @low_power_khz sets one * @low_power_mw: package power (the SMC's PHPC key) the low-power profile * holds the CPU clusters to; 0 for none * @high_power_machine: the machine compatible that had High Power mode from @@ -159,7 +149,6 @@ struct apple_clpc_hw { unsigned int ane_cluster_khz; const char *ane_cluster_machine; bool idle_on_time; - bool auto_low_power; unsigned int low_power_khz; unsigned int low_power_mw; const char *high_power_machine; @@ -274,7 +263,6 @@ struct apple_clpc { bool low_power; /* the DT ceiling, else hw->low_power_khz, else 0 */ unsigned int low_power_khz; - bool auto_low_power; unsigned int low_power_mw; struct device_node *smc_np; struct apple_smc *smc; @@ -693,11 +681,6 @@ static u32 apple_clpc_floor(struct apple_clpc *clpc, const unsigned int *state) return floor; } -static inline bool apple_clpc_has_profile_ceiling(const struct apple_clpc *clpc) -{ - return clpc->low_power_khz || clpc->auto_low_power; -} - static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) { if (READ_ONCE(clpc->stopped)) @@ -707,7 +690,8 @@ static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) unsigned long delay; cancel_delayed_work(&clpc->idle_work); - if (apple_clpc_has_profile_ceiling(clpc) && READ_ONCE(clpc->low_power)) + if (clpc->low_power_khz && clpc->low_power_mw && + READ_ONCE(clpc->low_power)) delay = msecs_to_jiffies(APPLE_CLPC_POWER_MS); else if (!cpumask_equal(clpc->covered, cpu_possible_mask)) delay = HZ; @@ -926,38 +910,21 @@ static unsigned int apple_clpc_step_khz(struct cpufreq_policy *policy, } /* - * The low-power platform-profile frequency ceiling for @policy: - * - when @low_power_khz is given (ADT/DT or SoC table), the first table - * frequency at or above @low_power_khz (matching macOS Low Power Mode's - * round-up on M4/M5), or policy max if the cluster is slower; - * - otherwise, when @auto_low_power is set, APPLE_CLPC_LOW_POWER_PCT of - * @max_cluster_khz rounded down to a table frequency on the fastest - * cluster(s), leaving slower clusters uncapped. + * The low-power platform-profile frequency ceiling for @policy: the first + * table frequency at or above @low_power_khz (matching macOS Low Power Mode's + * round-up), or policy max if the cluster is slower or @low_power_khz is 0. */ static unsigned int apple_clpc_low_power_top_khz(struct cpufreq_policy *policy, - unsigned int low_power_khz, - bool auto_low_power, - unsigned int max_cluster_khz) + unsigned int low_power_khz) { unsigned int top; - if (low_power_khz) { - top = apple_clpc_step_khz(policy, low_power_khz - 1, true); - if (top < low_power_khz) - top = policy->cpuinfo.max_freq; - return top; - } - if (auto_low_power && max_cluster_khz && - policy->cpuinfo.max_freq >= max_cluster_khz) { - unsigned int target = div_u64((u64)max_cluster_khz * - APPLE_CLPC_LOW_POWER_PCT, 100); - - top = apple_clpc_step_khz(policy, target + 1, false); - if (top > target) - top = policy->cpuinfo.min_freq ?: policy->cpuinfo.max_freq; - return top; - } - return policy->cpuinfo.max_freq; + if (!low_power_khz) + return policy->cpuinfo.max_freq; + top = apple_clpc_step_khz(policy, low_power_khz - 1, true); + if (top < low_power_khz) + top = policy->cpuinfo.max_freq; + return top; } /* @@ -1026,37 +993,29 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) { bool low = READ_ONCE(clpc->low_power); struct cpufreq_policy *policy[APPLE_CLPC_MAX_CLUSTERS] = {}; - unsigned int i, khz, pick_khz = 0, max_cluster_khz = 0; + unsigned int i, khz, pick_khz = 0; int mw, step = 0, pick = -1; - if (!apple_clpc_has_profile_ceiling(clpc) || - time_before(jiffies, clpc->power_next)) + if (!clpc->low_power_khz || time_before(jiffies, clpc->power_next)) return; clpc->power_next = jiffies + msecs_to_jiffies(APPLE_CLPC_POWER_MS); - if (low && clpc->smc_np) { + if (low && clpc->low_power_mw && clpc->smc_np) { mw = apple_clpc_read_power(clpc); clpc->power_reads++; /* The SMC updates the reading less often: act on a new one only. */ if (mw >= 0 && mw != clpc->power_mw) { clpc->power_updates++; - if (clpc->low_power_mw) { - if (mw > (int)clpc->low_power_mw) - step = -1; - else if (mw < (int)clpc->low_power_mw * 9 / 10) - step = 1; - } + if (mw > (int)clpc->low_power_mw) + step = -1; + else if (mw < (int)clpc->low_power_mw * 9 / 10) + step = 1; } clpc->power_mw = mw; } - for (i = 0; i < clpc->nr_clusters; i++) { - policy[i] = cpufreq_cpu_get(clpc->clusters[i].policy_cpu); - if (policy[i]) - max_cluster_khz = max(max_cluster_khz, - policy[i]->cpuinfo.max_freq); - } for (i = 0; i < clpc->nr_clusters; i++) { struct apple_clpc_cluster *cl = &clpc->clusters[i]; + policy[i] = cpufreq_cpu_get(cl->policy_cpu); if (!policy[i]) continue; if (!freq_qos_request_active(&cl->max_qos) && @@ -1064,9 +1023,7 @@ static void apple_clpc_profile_limit(struct apple_clpc *clpc) FREQ_QOS_MAX_DEFAULT_VALUE) < 0) clpc->update_errors++; cl->top_khz = apple_clpc_low_power_top_khz(policy[i], - clpc->low_power_khz, - clpc->auto_low_power, - max_cluster_khz); + clpc->low_power_khz); if (!low) cl->max_khz = 0; else if (!cl->max_khz || !clpc->low_power_mw || @@ -1174,13 +1131,13 @@ static void apple_clpc_sample(struct apple_clpc *clpc) /* * Sample on time while graphics is powered, to see it power off, and in - * low power where it has a ceiling to keep. A profile with no low-power - * ceiling (High Power only) has nothing to do there, so it stays - * deferrable. + * low power when an SMC package power target is active. A static + * ceiling is applied synchronously on profile change and a High Power + * only profile has nothing to poll at idle, so both stay deferrable. */ apple_clpc_queue(clpc, !floor && !clpc->gpu_on && !clpc->ane_qos_khz && - !(apple_clpc_has_profile_ceiling(clpc) && + !(clpc->low_power_khz && clpc->low_power_mw && READ_ONCE(clpc->low_power))); } @@ -1262,11 +1219,23 @@ static int apple_clpc_status_show(struct seq_file *s, void *unused) } seq_printf(s, "samples: %lu update errors: %lu\n", clpc->samples, clpc->update_errors); - if (apple_clpc_has_profile_ceiling(clpc)) { + if (clpc->low_power_khz) { + int power_mw = clpc->power_mw; + + if (!clpc->low_power_mw && clpc->smc_np) { + mutex_lock(&clpc->sample_lock); + if (!READ_ONCE(clpc->stopped)) { + int mw = apple_clpc_read_power(clpc); + + if (mw >= 0) + power_mw = mw; + } + mutex_unlock(&clpc->sample_lock); + } seq_printf(s, "profile: %s power %d mW (%lu new of %lu readings) ceilings (kHz):", clpc->profile == PLATFORM_PROFILE_LOW_POWER ? "low-power" : clpc->profile == PLATFORM_PROFILE_PERFORMANCE ? "performance" : - "balanced", clpc->power_mw, clpc->power_updates, clpc->power_reads); + "balanced", power_mw, clpc->power_updates, clpc->power_reads); for (i = 0; i < clpc->nr_clusters; i++) seq_printf(s, " cpu%u %u", clpc->clusters[i].policy_cpu, clpc->clusters[i].max_khz); @@ -1543,6 +1512,7 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti { struct apple_clpc *clpc = dev_get_drvdata(dev); bool high_power = profile == PLATFORM_PROFILE_PERFORMANCE; + bool need_work; mutex_lock(&clpc->sample_lock); /* Performance is macOS's High Power mode; the other two are its Automatic. */ @@ -1558,13 +1528,17 @@ static int apple_clpc_profile_set(struct device *dev, enum platform_profile_opti WRITE_ONCE(clpc->low_power, profile == PLATFORM_PROFILE_LOW_POWER); /* Apply profile ceilings right away so userspace sees the change immediately. */ clpc->power_next = jiffies; - if (!READ_ONCE(clpc->stopped) && apple_clpc_has_profile_ceiling(clpc)) { + if (!READ_ONCE(clpc->stopped) && clpc->low_power_khz) { if (!cpumask_equal(clpc->covered, cpu_possible_mask)) apple_clpc_find_clusters(clpc); apple_clpc_profile_limit(clpc); } + need_work = clpc->has_pmc || + (clpc->low_power_khz && clpc->low_power_mw && + profile == PLATFORM_PROFILE_LOW_POWER) || + !cpumask_equal(clpc->covered, cpu_possible_mask); mutex_unlock(&clpc->sample_lock); - if (!READ_ONCE(clpc->stopped)) + if (!READ_ONCE(clpc->stopped) && need_work) mod_delayed_work(system_freezable_power_efficient_wq, &clpc->work, 0); return 0; } @@ -1718,15 +1692,13 @@ static int apple_clpc_probe(struct platform_device *pdev) /* * The boot loader copies the ADT's Low Power mode CPU ceiling * (pmgr/clpc cpu-low-power-frequency-max) into the node. Without it, - * a SoC's own value applies where it has one, or the generic - * operating-point ceiling when auto_low_power is enabled. + * a SoC's own value applies where it has one; otherwise low-power + * ceiling stays unavailable until the machine supplies it. */ if (!of_property_read_u32(dev->of_node, "apple,low-power-frequency-max-mhz", &mhz)) clpc->low_power_khz = mhz * 1000; else clpc->low_power_khz = clpc->hw->low_power_khz; - if (!clpc->low_power_khz && clpc->hw->auto_low_power) - clpc->auto_low_power = true; if (!of_property_read_u32(dev->of_node, "apple,low-power-mw", &mw)) clpc->low_power_mw = mw; else @@ -1745,7 +1717,7 @@ static int apple_clpc_probe(struct platform_device *pdev) */ if (!high_power && clpc->hw->high_power_machine) high_power = of_machine_is_compatible(clpc->hw->high_power_machine); - if ((apple_clpc_has_profile_ceiling(clpc) || high_power) && + if ((clpc->low_power_khz || high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE)) { /* * The SMC is optional: without it (no apple,smc phandle, or a @@ -1763,7 +1735,7 @@ static int apple_clpc_probe(struct platform_device *pdev) clpc->high_power = clpc->smc_np && high_power; } /* High Power mode alone needs the SMC; without it there is no profile. */ - has_profile = (apple_clpc_has_profile_ceiling(clpc) || clpc->high_power) && + has_profile = (clpc->low_power_khz || clpc->high_power) && IS_REACHABLE(CONFIG_ACPI_PLATFORM_PROFILE); if (!clpc->has_pmc && !has_profile) return dev_err_probe(dev, -ENODEV, @@ -1899,7 +1871,7 @@ static int apple_clpc_probe(struct platform_device *pdev) if (has_profile) { struct device *ppdev; - if (apple_clpc_has_profile_ceiling(clpc) && !clpc->policy_nb_added) { + if (clpc->low_power_khz && !clpc->policy_nb_added) { clpc->policy_nb.notifier_call = apple_clpc_policy_notify; clpc->policy_nb_added = !cpufreq_register_notifier(&clpc->policy_nb, CPUFREQ_POLICY_NOTIFIER); @@ -1909,7 +1881,7 @@ static int apple_clpc_probe(struct platform_device *pdev) * only carries High Power mode, and userspace keeps the CPU budget. */ ppdev = devm_platform_profile_register(dev, - apple_clpc_has_profile_ceiling(clpc) ? + clpc->low_power_khz ? "apple-clpc" : "apple-smc", clpc, &apple_clpc_profile_ops); if (IS_ERR(ppdev)) { @@ -2142,13 +2114,10 @@ static const struct apple_clpc_hw apple_clpc_hw_t8142 = { /* * Standalone CLPC node without a PMC voter parent (for example T8112): no - * memory/fabric floor votes, and when the DT carries no explicit - * apple,low-power-frequency-max-mhz the low-power platform profile derives its - * ceiling from the fastest CPU cluster's operating points. + * memory/fabric floor votes; platform profiles are registered only when the + * machine supplies apple,low-power-frequency-max-mhz or apple,high-power-mode. */ -static const struct apple_clpc_hw apple_clpc_hw_generic = { - .auto_low_power = true, -}; +static const struct apple_clpc_hw apple_clpc_hw_generic = {}; #if IS_BUILTIN(CONFIG_KUNIT) && !defined(MODULE) #include @@ -2524,100 +2493,65 @@ static void apple_clpc_low_power_roundup_test(struct kunit *test) { .frequency = 2592000 }, { .frequency = CPUFREQ_TABLE_END }, }; - struct cpufreq_policy p_pol = { - .freq_table = p_table, - .cpuinfo = { .min_freq = 2592000, .max_freq = 4512000 }, - }; - struct cpufreq_policy e_pol = { - .freq_table = e_table, - .cpuinfo = { .min_freq = 1020000, .max_freq = 2592000 }, - }; - - /* Explicit ceiling rounds UP to the first OPP >= 2808 MHz (2868 MHz). */ - KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&p_pol, 2808000, false, 4512000), - 2868000u); - /* Slower cluster below 2808 MHz stays at its max (2592 MHz). */ - KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&e_pol, 2808000, false, 4512000), - 2592000u); - /* Explicit DT ceiling also overrides auto_low_power. */ - KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&p_pol, 2808000, true, 4512000), - 2868000u); -} - -static void apple_clpc_low_power_auto_test(struct kunit *test) -{ - /* T8112 (J473/J413) live E and P cluster operating points. */ - struct cpufreq_frequency_table e_table[] = { + /* T8112 (J473/J413) E and P cluster OPPs around the 1960 MHz ADT ceiling. */ + struct cpufreq_frequency_table t8112_e_table[] = { { .frequency = 600000 }, - { .frequency = 912000 }, - { .frequency = 1284000 }, { .frequency = 1752000 }, { .frequency = 2004000 }, - { .frequency = 2256000 }, { .frequency = 2424000 }, { .frequency = CPUFREQ_TABLE_END }, }; - struct cpufreq_frequency_table p_table[] = { + struct cpufreq_frequency_table t8112_p_table[] = { { .frequency = 660000 }, - { .frequency = 924000 }, - { .frequency = 1188000 }, - { .frequency = 1452000 }, { .frequency = 1704000 }, { .frequency = 1968000 }, - { .frequency = 2208000 }, - { .frequency = 2400000 }, - { .frequency = 2568000 }, - { .frequency = 2724000 }, - { .frequency = 2868000 }, - { .frequency = 2988000 }, - { .frequency = 3096000 }, { .frequency = 3204000 }, { .frequency = CPUFREQ_TABLE_END }, }; - struct cpufreq_frequency_table single_table[] = { - { .frequency = 3000000 }, - { .frequency = CPUFREQ_TABLE_END }, + struct cpufreq_policy p_pol = { + .freq_table = p_table, + .cpuinfo = { .min_freq = 2592000, .max_freq = 4512000 }, }; struct cpufreq_policy e_pol = { .freq_table = e_table, + .cpuinfo = { .min_freq = 1020000, .max_freq = 2592000 }, + }; + struct cpufreq_policy t8112_e_pol = { + .freq_table = t8112_e_table, .cpuinfo = { .min_freq = 600000, .max_freq = 2424000 }, }; - struct cpufreq_policy p_pol = { - .freq_table = p_table, + struct cpufreq_policy t8112_p_pol = { + .freq_table = t8112_p_table, .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, }; - struct cpufreq_policy single_pol = { - .freq_table = single_table, - .cpuinfo = { .min_freq = 3000000, .max_freq = 3000000 }, - }; struct cpufreq_policy no_table_pol = { .freq_table = NULL, .cpuinfo = { .min_freq = 660000, .max_freq = 3204000 }, }; - /* 64% of 3204 MHz = 2050.56 MHz -> highest OPP <= target is 1968 MHz. */ + /* Explicit ceiling rounds UP to the first OPP >= 2808 MHz (2868 MHz). */ KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&p_pol, 0, true, 3204000), - 1968000u); - /* Slower E-cluster (2424 < 3204 MHz) stays uncapped. */ + apple_clpc_low_power_top_khz(&p_pol, 2808000), + 2868000u); + /* Slower cluster below 2808 MHz stays at its max (2592 MHz). */ KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&e_pol, 0, true, 3204000), - 2424000u); - /* Without auto_low_power or low_power_khz, no cap applies. */ + apple_clpc_low_power_top_khz(&e_pol, 2808000), + 2592000u); + /* T8112 1960 MHz ADT ceiling rounds up to 2004 MHz (E) and 1968 MHz (P). */ KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&p_pol, 0, false, 3204000), - 3204000u); - /* All OPPs above 64% target: fall back safely to policy min_freq. */ + apple_clpc_low_power_top_khz(&t8112_e_pol, 1960000), + 2004000u); KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&single_pol, 0, true, 3000000), - 3000000u); - /* NULL freq_table must not dereference NULL; falls back to min_freq. */ + apple_clpc_low_power_top_khz(&t8112_p_pol, 1960000), + 1968000u); + /* Missing machine ceiling (0) must not invent a fallback cap. */ KUNIT_EXPECT_EQ(test, - apple_clpc_low_power_top_khz(&no_table_pol, 0, true, 3204000), - 660000u); + apple_clpc_low_power_top_khz(&t8112_p_pol, 0), + 3204000u); + /* NULL freq_table must not dereference NULL; stays at policy max. */ + KUNIT_EXPECT_EQ(test, + apple_clpc_low_power_top_khz(&no_table_pol, 1960000), + 3204000u); } static void apple_clpc_profile_ops_test(struct kunit *test) @@ -2628,18 +2562,21 @@ static void apple_clpc_profile_ops_test(struct kunit *test) enum platform_profile_option prof = PLATFORM_PROFILE_BALANCED; KUNIT_ASSERT_NOT_NULL(test, clpc); + KUNIT_ASSERT_TRUE(test, zalloc_cpumask_var(&clpc->covered, GFP_KERNEL)); + cpumask_copy(clpc->covered, cpu_possible_mask); mutex_init(&clpc->sample_lock); + INIT_DELAYED_WORK(&clpc->work, apple_clpc_work); + INIT_DEFERRABLE_WORK(&clpc->idle_work, apple_clpc_idle_work); clpc->hw = &apple_clpc_hw_generic; - clpc->auto_low_power = true; + clpc->low_power_khz = 1960000; clpc->has_pmc = false; clpc->stopped = true; clpc->profile = PLATFORM_PROFILE_BALANCED; dev_set_drvdata(&dev, clpc); - KUNIT_EXPECT_TRUE(test, apple_clpc_hw_generic.auto_low_power); - KUNIT_EXPECT_FALSE(test, apple_clpc_hw_t6040.auto_low_power); - KUNIT_EXPECT_FALSE(test, apple_clpc_hw_t8132.auto_low_power); - KUNIT_EXPECT_TRUE(test, apple_clpc_has_profile_ceiling(clpc)); + /* Standalone generic table carries no hardcoded ceiling or power cap. */ + KUNIT_EXPECT_EQ(test, apple_clpc_hw_generic.low_power_khz, 0u); + KUNIT_EXPECT_EQ(test, apple_clpc_hw_generic.low_power_mw, 0u); KUNIT_EXPECT_EQ(test, apple_clpc_profile_probe(clpc, &choices), 0); KUNIT_EXPECT_TRUE(test, test_bit(PLATFORM_PROFILE_LOW_POWER, &choices)); @@ -2651,6 +2588,20 @@ static void apple_clpc_profile_ops_test(struct kunit *test) KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_LOW_POWER); KUNIT_EXPECT_TRUE(test, clpc->low_power); + /* Static standalone ceiling (low_power_mw == 0) must not queue periodic work. */ + WRITE_ONCE(clpc->stopped, false); + apple_clpc_queue(clpc, true); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&clpc->work)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&clpc->idle_work)); + + /* With a package power target, standalone low-power schedules 100 ms polling. */ + clpc->low_power_mw = 15000; + apple_clpc_queue(clpc, true); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&clpc->work)); + WRITE_ONCE(clpc->stopped, true); + cancel_delayed_work_sync(&clpc->work); + clpc->low_power_mw = 0; + KUNIT_EXPECT_EQ(test, apple_clpc_profile_set(&dev, PLATFORM_PROFILE_PERFORMANCE), 0); KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_PERFORMANCE); @@ -2660,6 +2611,8 @@ static void apple_clpc_profile_ops_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_clpc_profile_get(&dev, &prof), 0); KUNIT_EXPECT_EQ(test, prof, PLATFORM_PROFILE_BALANCED); KUNIT_EXPECT_FALSE(test, clpc->low_power); + + free_cpumask_var(clpc->covered); } static struct kunit_case apple_clpc_cases[] = { @@ -2675,7 +2628,6 @@ static struct kunit_case apple_clpc_cases[] = { KUNIT_CASE(apple_clpc_gpu_request_lifetime_test), KUNIT_CASE(apple_clpc_gpu_provider_removal_test), KUNIT_CASE(apple_clpc_low_power_roundup_test), - KUNIT_CASE(apple_clpc_low_power_auto_test), KUNIT_CASE(apple_clpc_profile_ops_test), {} }; diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index a200ebd289145b..cb8acb4e4faa6f 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -233,7 +233,6 @@ def cells(name): + ', '.join(f'{{{t}, {p}}}' for t, p in g17_idle_events) + '};\n') methods = '\n'.join(item(source, s) for s in [ 'static unsigned int apple_clpc_vote(', 'static u32 apple_clpc_floor(', - 'static inline bool apple_clpc_has_profile_ceiling(', 'static bool apple_clpc_gpu_streaming(', 'static bool apple_clpc_gpu_dense_step(', 'static bool apple_clpc_gpu_dense(', @@ -325,8 +324,8 @@ def cells(name): unsigned long ane_until; bool has_pmc; bool low_power; - bool auto_low_power; unsigned int low_power_khz; + unsigned int low_power_mw; }; static unsigned long jiffies; static u64 ktime_get_mono_fast_ns(void) { return jiffies * 1000000ull; } @@ -724,9 +723,9 @@ def cells(name): assert(c.last_reason==16); } -// Low power samples on time only where it has a CPU ceiling to keep -// (clpc->low_power_khz: the DT ceiling, else the table one); a High Power-only -// profile stays deferrable when idle. +// Low power samples on time only when a package power target (low_power_mw) +// is active; a static ceiling alone or High Power-only profile stays +// deferrable when idle. static void check_low_power(void) { struct apple_clpc_gpu gpu={0}; struct apple_clpc_hw lp=apple_clpc_hw_t6040; @@ -734,9 +733,11 @@ def cells(name): read_error=vote_error=0; pmgr_status=0xf0; published=~0u; jiffies=3000; apple_clpc_sample(&c); assert(published==0 && queued_idle); c.low_power_khz=2808000; - jiffies=3004; apple_clpc_sample(&c); assert(published==0 && !queued_idle); + jiffies=3004; apple_clpc_sample(&c); assert(published==0 && queued_idle); + c.low_power_mw=15000; + jiffies=3008; apple_clpc_sample(&c); assert(published==0 && !queued_idle); c.low_power=false; - jiffies=3008; apple_clpc_sample(&c); assert(published==0 && queued_idle); + jiffies=3012; apple_clpc_sample(&c); assert(published==0 && queued_idle); } int main(void) { diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index c9c96d5a7f2279..6e5d9e480e9ff0 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -65,11 +65,11 @@ def function(source, name): struct apple_clpc_ane *ane; struct mutex sample_lock; struct delayed_work work, idle_work; - bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power, auto_low_power; + bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power; u8 high_power_seq; enum platform_profile_option profile; unsigned long power_next, ane_until; - unsigned low_power_khz, ane_qos_khz, nr_clusters, agent, mask, saved_floor; + unsigned low_power_khz, low_power_mw, ane_qos_khz, nr_clusters, agent, mask, saved_floor; struct freq_qos_request ane_qos; struct cluster clusters[2]; struct vote vote[APPLE_CLPC_RAILS]; @@ -78,9 +78,6 @@ def function(source, name): }; static void __attribute__((unused)) *cpu_possible_mask; static bool __attribute__((unused)) cpumask_equal(void *a, void *b) { return a == b; } -static bool __attribute__((unused)) apple_clpc_has_profile_ceiling(const struct apple_clpc *c) { - return c->low_power_khz || c->auto_low_power; -} static void __attribute__((unused)) apple_clpc_find_clusters(struct apple_clpc *c) { (void)c; } static void __attribute__((unused)) apple_clpc_profile_limit(struct apple_clpc *c) { (void)c; } static struct mutex apple_clpc_clients_lock; From 80e130f592aabe8b0e658ef1fb181a546f13e1c0 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 20:56:57 -0800 Subject: [PATCH 1064/1514] drm/asahi: g17: keep timestamp buffers out of the shared firmware range On M5, and on the other G17 GPUs once the 64 MiB timestamp window is full, GEM_BIND_OBJECT mapped a timestamp buffer into the kernel VM's dynamic range, the range every firmware object (queues, kick rings, render state) is allocated from. The driver never gives the firmware that address: outside the window the host writes every stamp through the buffer's CPU mapping. The mapping only held shared address space, as much as the bound range, for as long as the buffer stayed bound. Give such a buffer only its CPU mapping (timestamp::Buffer::Host), as G16 and G18 keep theirs without a firmware alias. It refuses the same ranges and VM-private objects the alias did. Buffers mapped in the window, and every other GPU family, are unchanged. Share the bound-range check with Buffer::cpu, and the VM-private test with gem::validate_vm_binding, and test the range check in a new asahi_timestamp_buffer KUnit suite. Reported-by: Erik Bourget Suggested-by: Erik Bourget Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/mod.rs | 28 +++-------- drivers/gpu/drm/asahi/gem.rs | 8 ++- drivers/gpu/drm/asahi/timestamp.rs | 79 +++++++++++++++++++++++++++--- 3 files changed, 86 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index c3273235a61df8..1a4d6762540d81 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2723,11 +2723,11 @@ impl gpu::Gpu for Gpu { mut bo: gem::ObjectRef, range: Range, ) -> Result { - let (mapping, window) = { + let windowed = { let state = self.shared.state.lock(); let firmware = (*state).as_ref().ok_or(ENODEV)?; // The timestamp window is part of the older firmware graph, not M5's graph. - let windowed = if firmware.uat.is_m5() { + if firmware.uat.is_m5() { None } else { bo.map_range_into_range( @@ -2739,27 +2739,15 @@ impl gpu::Gpu for Gpu { false, ) .ok() - }; - match windowed { - Some(mapping) => (mapping, true), - // A full window: this buffer's stamps are all host-written. - None => ( - bo.map_range_into_range( - firmware.uat.kernel_vm(), - range, - firmware.uat.kernel_dynamic_range(), - mmu::UAT_PGSZ as u64, - mmu::PROT_FW_SHARED_RW, - false, - )?, - false, - ), } }; // The buffer's CPU mapping takes the reservation lock: not under the device mutex. - match window { - true => crate::timestamp::Buffer::firmware_window(mapping), - false => crate::timestamp::Buffer::firmware(mapping), + match windowed { + Some(mapping) => crate::timestamp::Buffer::firmware_window(mapping), + // Outside the window the host writes every stamp, and the firmware never sees the + // buffer: give it no firmware alias, which would take kernel address space shared + // with every firmware object (queues, rings, pools) for as long as it is bound. + None => crate::timestamp::Buffer::host(&bo, range), } } } diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index 9980d5f16136b1..dcaceef009c26a 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -168,7 +168,7 @@ pub(crate) fn mapped_sg_table<'a>( /// VM-private BOs share their assigned VM's reservation object. Validate this /// before acquiring mapping state; generic GPUVM accepts external shareable BOs. pub(crate) fn validate_vm_binding(gem: &Object, vm: &mmu::Vm) -> Result { - if gem.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_VM_PRIVATE != 0 && vm.is_extobj(gem) { + if gem.is_vm_private() && vm.is_extobj(gem) { return Err(EINVAL); } Ok(()) @@ -701,6 +701,12 @@ impl AsahiObject { self.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_WRITEBACK != 0 } + /// Whether the backing belongs to the VM that created the object, so that only that VM may + /// map it. + pub(crate) fn is_vm_private(&self) -> bool { + self.flags & uapi::drm_asahi_gem_flags_DRM_ASAHI_GEM_VM_PRIVATE != 0 + } + pub(crate) fn idle_reclaim_candidate(&self) -> bool { !self.kernel && !self.exportable diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 2a18ebbeb5d9cc..d5ed07753e67ac 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -2,10 +2,9 @@ //! Prepared timestamp destinations shared by native command completion paths. -use crate::mmu; -#[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] -use crate::{file, gem}; +use crate::{gem, mmu}; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] +use crate::file; use core::ops::Range; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] use core::sync::atomic::{fence as barrier, Ordering}; @@ -13,6 +12,15 @@ use kernel::{prelude::*, sync::Arc}; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] use kernel::{uapi, xarray}; +/// The size of a bound range: whole pages, not empty, inside an object of `object_size` bytes. +fn bound_size(range: &Range, object_size: usize) -> Result { + let size = range.end.checked_sub(range.start).ok_or(EINVAL)?; + if size == 0 || (range.start | size) & mmu::UAT_PGMSK != 0 || range.end > object_size { + return Err(EINVAL); + } + Ok(size) +} + /// A firmware-mapped timestamp buffer with a kernel CPU mapping of its backing, kept for the /// buffer's lifetime so that commands need no mapping of their own. pub(crate) struct FirmwareBuffer { @@ -22,6 +30,15 @@ pub(crate) struct FirmwareBuffer { window: bool, } +/// A timestamp buffer only the host writes, through a kernel CPU mapping of its backing. It has +/// no firmware alias, so binding it takes no firmware address space. +pub(crate) struct HostBuffer { + cpu: mmu::TimestampVmap, + /// The bound range of the object. + start: usize, + size: usize, +} + /// A bound timestamp destination. Only backends which publish firmware writes need a UAT alias. /// CPU-retired timestamps retain their backing without consuming global firmware address space. pub(crate) enum Buffer { @@ -29,6 +46,8 @@ pub(crate) enum Buffer { /// releasing the CPU mapping takes the reservation lock: the deferral runs the release /// on the cleanup queue. Firmware(crate::cleanup::Deferred), + /// Host-written, with the same deferred release as [`Self::Firmware`]. + Host(crate::cleanup::Deferred), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Cpu { // The GEM pin keeps the object's held SG table alive through CPU publication. @@ -47,6 +66,22 @@ impl Buffer { Self::new_firmware(mapping, true) } + /// A buffer whose stamps the host writes: the bound range of a firmware-shareable object, + /// as for a firmware alias, with only a CPU mapping. Not under the device mutex (the CPU + /// mapping takes the reservation lock). + pub(crate) fn host(bo: &gem::ObjectRef, range: Range) -> Result { + let size = bound_size(&range, bo.size())?; + // A firmware alias refuses VM-private objects (gem::validate_vm_binding); so does this. + if bo.gem.is_vm_private() { + return Err(EINVAL); + } + Ok(Self::Host(crate::cleanup::Deferred::new(HostBuffer { + cpu: mmu::TimestampVmap::new(&bo.gem)?, + start: range.start, + size, + })?)) + } + fn new_firmware(mapping: mmu::KernelMapping, window: bool) -> Result { let cpu = mapping.timestamp_vmap()?; Ok(Self::Firmware(crate::cleanup::Deferred::new(FirmwareBuffer { @@ -72,6 +107,7 @@ impl Buffer { pub(crate) fn read_timestamp(&self, offset: usize) -> Option { match self { Self::Firmware(buffer) => buffer.cpu.read(offset), + Self::Host(buffer) => buffer.cpu.read(offset), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => None, } @@ -80,10 +116,7 @@ impl Buffer { /// Retain a CPU-written byte range without publishing any firmware address. #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] pub(crate) fn cpu(bo: gem::ObjectRef, range: Range) -> Result { - let size = range.end.checked_sub(range.start).ok_or(EINVAL)?; - if size == 0 || (range.start | size) & mmu::UAT_PGMSK != 0 || range.end > bo.size() { - return Err(EINVAL); - } + bound_size(&range, bo.size())?; let gem = gem::KernelMappingPin::new(&bo.gem); let registered = bo.gem.dev().registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); @@ -94,6 +127,7 @@ impl Buffer { pub(crate) fn size(&self) -> usize { match self { Self::Firmware(buffer) => buffer.mapping.size(), + Self::Host(buffer) => buffer.size, #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { range, .. } => range.end - range.start, } @@ -103,6 +137,7 @@ impl Buffer { pub(crate) fn timestamp_mapping(&self, offset: usize) -> Result { match self { Self::Firmware(buffer) => buffer.mapping.timestamp_mapping(offset), + Self::Host(_) => Err(EINVAL), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { gem, range, .. } => { if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > self.size() { @@ -113,11 +148,18 @@ impl Buffer { } } - /// The object offset of the timestamp at `offset` of a firmware buffer, for + /// The object offset of the timestamp at `offset` of a firmware or host buffer, for /// [`Self::write_timestamp`]. pub(crate) fn timestamp_offset(&self, offset: usize) -> Result { match self { Self::Firmware(buffer) => buffer.mapping.timestamp_offset(offset), + // The bound range lies inside the object (Self::host). + Self::Host(buffer) => { + if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > buffer.size { + return Err(ERANGE); + } + buffer.start.checked_add(offset).ok_or(EOVERFLOW) + } #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), } @@ -128,6 +170,7 @@ impl Buffer { pub(crate) fn write_timestamp(&self, offset: usize, value: u64) { match self { Self::Firmware(buffer) => buffer.cpu.write(offset, value), + Self::Host(buffer) => buffer.cpu.write(offset, value), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => {} } @@ -137,6 +180,7 @@ impl Buffer { pub(crate) fn firmware_mapping(&self) -> Result> { match self { Self::Firmware(buffer) => Ok(buffer.mapping.clone()), + Self::Host(_) => Err(EINVAL), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), } @@ -261,3 +305,22 @@ impl Destinations { destinations.iter() } } + +#[kernel::macros::kunit_tests(asahi_timestamp_buffer)] +mod tests { + use super::*; + + const PAGE: usize = mmu::UAT_PGSZ; + + #[test] + fn a_bound_range_is_whole_pages_inside_the_object() { + assert_eq!(bound_size(&(0..PAGE), PAGE), Ok(PAGE)); + assert_eq!(bound_size(&(PAGE..3 * PAGE), 3 * PAGE), Ok(2 * PAGE)); + assert_eq!(bound_size(&(0..0), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE..0), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(0..PAGE / 2), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE / 2..PAGE + PAGE / 2), 2 * PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(0..2 * PAGE), PAGE), Err(EINVAL)); + assert_eq!(bound_size(&(PAGE..usize::MAX & !(PAGE - 1)), 2 * PAGE), Err(EINVAL)); + } +} From 50d485b788b20f3b38abb055853c85416a0badb3 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 21:24:33 -0800 Subject: [PATCH 1065/1514] drm/asahi: charge each bound object to its client, so a file's binds stay within its memory limit GEM_BIND_OBJECT stores a record in the file's object table for every bind, and the number of records per file was not limited. The record and the timestamp buffer it names are small kernel allocations that no GEM object accounts for, and they were not charged to the client. The buffer's pages and its CPU mapping belong to the object: the shmem helper shares one vmap between every mapping of an object, and the object's size is charged when it is created. Charge every bind the size of what it keeps (the table entry, the buffer record and the buffer's heap records) against the client's and the device's memory limits, through the Ledger::admit() that object creation uses, as a user object of that size would be. A bind past either limit fails with ENOMEM. The charge is held with the bound buffer and given back with its last reference: after the unbind, or when the file is closed, once no command still uses the buffer. To ensure no command can keep a firmware timestamp mapping alive after unbind without also keeping its Bound record (and charge) alive, store the KernelMapping directly in FirmwareBuffer, return a borrowed &mmu::KernelMapping from firmware_mapping() instead of cloning an Arc, and have G13/G14 (fw::job::UserTimestamp), G15 (g15::command/job) and M3 (m3::m3_submit::Destination) retain Arc, matching G16, G17 and G18. The bind charges and takes its table slot before it maps the buffer, so a refused bind gets no window alias or CPU mapping at all. The record, the buffer and the table's nodes are allocated with GFP_KERNEL_ACCOUNT, so they also count towards the memory cgroup of the task that binds. Also add a host_offset() KUnit case (a_host_stamp_lies_inside_the_bound_range) in asahi_timestamp_buffer alongside the new asahi_bound_object_charge suite. This applies to every GPU family and to every GEM_BIND_OBJECT usage: the table is shared code. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/cleanup.rs | 3 + drivers/gpu/drm/asahi/file.rs | 89 +++++++++++++++++++++---- drivers/gpu/drm/asahi/fw/job.rs | 8 +-- drivers/gpu/drm/asahi/g15/command.rs | 16 ++--- drivers/gpu/drm/asahi/g15/job.rs | 6 +- drivers/gpu/drm/asahi/g17/completion.rs | 2 +- drivers/gpu/drm/asahi/m3/m3_submit.rs | 7 +- drivers/gpu/drm/asahi/object.rs | 5 +- drivers/gpu/drm/asahi/queue/common.rs | 5 +- drivers/gpu/drm/asahi/timestamp.rs | 85 ++++++++++++++++++----- 10 files changed, 173 insertions(+), 53 deletions(-) diff --git a/drivers/gpu/drm/asahi/cleanup.rs b/drivers/gpu/drm/asahi/cleanup.rs index 52436b40304c03..4e4e95c5729b96 100644 --- a/drivers/gpu/drm/asahi/cleanup.rs +++ b/drivers/gpu/drm/asahi/cleanup.rs @@ -84,6 +84,9 @@ impl WorkItem for Item { pub(crate) struct Deferred(Option>>>); impl Deferred { + /// Heap bytes one deferred value takes: the value and its release work item. + pub(crate) const HEAP_BYTES: usize = core::mem::size_of::>(); + pub(crate) fn new(value: T) -> Result { let item = KBox::pin_init( pin_init!(Item { diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 08837155027662..82ab12dd63258d 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -343,7 +343,26 @@ impl SyncItem { #[derive(Clone)] pub(crate) enum Object { - TimestampBuffer(Arc), + TimestampBuffer(Arc), +} + +/// Kernel memory one `GEM_BIND_OBJECT` bind keeps that no GEM object accounts for: its table entry +/// and the bound buffer's records (an `Arc` count, the [`crate::timestamp::Bound`] and the +/// buffer's heap records). The object's pages and its CPU mapping, which the shmem helper shares +/// between every vmap of one object, belong to the object and are charged when it is created. +/// Each bind is charged this much against the client's and the device's memory limits, as a user +/// object of that size would be, so a file's binds are bounded by those limits. +const BOUND_OBJECT_BYTES: u64 = (core::mem::size_of::() + + core::mem::size_of::() + + core::mem::size_of::() + + crate::timestamp::Buffer::HEAP_BYTES) as u64; + +/// Charges one bind to `client`, or fails with `ENOMEM` and charges nothing. +fn admit_bind( + ledger: &'static memacct::Ledger, + client: &Arc, +) -> Result { + ledger.admit(client, BOUND_OBJECT_BYTES) } /// A queue in a file's table. Its count in the creating process's share of the device's @@ -1586,21 +1605,28 @@ impl File { .try_into()?; let bo = gem::ObjectRef::new(gem::Object::lookup_handle(file, data.handle)?); + // Charge the bind and take its table slot first, so that a bind past the client's memory + // limit is refused (ENOMEM, as an object creation would be) before the buffer gets a + // window alias or a CPU mapping. A later failure drops the charge and the slot. + let charge = admit_bind(&memacct::LEDGER, &file.inner().mem)?; + let objects = file.inner().objects(); + let resv = objects + .lock() + .reserve_limit(1..=u32::MAX, GFP_KERNEL_ACCOUNT)?; + let handle: u32 = resv.index().try_into()?; let mapping = Arc::new( - reg_data.gpu.map_timestamp_buffer(bo, offset..end_offset)?, - GFP_KERNEL, + crate::timestamp::Bound::new( + reg_data.gpu.map_timestamp_buffer(bo, offset..end_offset)?, + charge, + ), + GFP_KERNEL_ACCOUNT, )?; - let obj = KBox::new(Object::TimestampBuffer(mapping), GFP_KERNEL)?; - let handle = file - .inner() - .objects() - .lock() - .insert_limit(1..=u32::MAX, obj, GFP_KERNEL); - // StoreError owns the rejected object. Convert it only after the - // temporary XArray guard is gone: dropping a mapping may sleep. - let handle = handle? as u64; + let obj = KBox::new(Object::TimestampBuffer(mapping), GFP_KERNEL_ACCOUNT)?; + // fill() takes and releases the XArray lock itself, so a rejected object, which + // StoreError owns, is dropped outside it: dropping a mapping may sleep. + resv.fill(obj)?; - data.object_handle = handle as u32; + data.object_handle = handle; Ok(0) } @@ -1940,3 +1966,40 @@ impl Drop for File { Self::mark_clients_closed(this, |_| true); } } + +#[kernel::macros::kunit_tests(asahi_bound_object_charge)] +mod bound_object_charge_tests { + use super::*; + use crate::memacct::{Ledger, Limits}; + + static BINDS: Ledger = Ledger::new(); + + #[test] + fn a_bind_is_charged_its_records_and_refused_past_the_client_limit() -> Result { + // The charge covers the table entry, the bound record and the buffer's heap records. + assert!( + BOUND_OBJECT_BYTES as usize + >= core::mem::size_of::() + + core::mem::size_of::() + + crate::timestamp::Buffer::HEAP_BYTES + ); + BINDS.set_limits(Limits { device: 0, client: 4 * BOUND_OBJECT_BYTES }); + let client = memacct::Client::new()?; + let mut held = KVec::new(); + for _ in 0..4 { + held.push(admit_bind(&BINDS, &client)?, GFP_KERNEL)?; + } + assert_eq!(client.committed(), 4 * BOUND_OBJECT_BYTES); + // The fifth is refused with ENOMEM, as an object creation past the limit is, and + // charges nothing. + assert_eq!(admit_bind(&BINDS, &client).err(), Some(ENOMEM)); + assert_eq!(client.committed(), 4 * BOUND_OBJECT_BYTES); + // An unbind gives its charge back, and the next bind fits again. + held.pop(); + assert_eq!(client.committed(), 3 * BOUND_OBJECT_BYTES); + held.push(admit_bind(&BINDS, &client)?, GFP_KERNEL)?; + drop(held); + assert_eq!(client.committed(), 0); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/fw/job.rs b/drivers/gpu/drm/asahi/fw/job.rs index aaa83355b437d2..39f2616b73da6c 100644 --- a/drivers/gpu/drm/asahi/fw/job.rs +++ b/drivers/gpu/drm/asahi/fw/job.rs @@ -5,7 +5,7 @@ use super::types::*; use crate::{ default_zeroed, - mmu, + timestamp, trivial_gpustruct, // }; use kernel::prelude::Result; @@ -128,7 +128,7 @@ trivial_gpustruct!(RenderTimestamps); #[derive(Debug)] pub(crate) struct UserTimestamp { - pub(crate) mapping: Arc, + pub(crate) mapping: Arc, pub(crate) offset: usize, } @@ -144,12 +144,12 @@ impl UserTimestamps { start_addr: self .start .as_ref() - .map(|a| GpuPointer::from_mapping(&a.mapping, a.offset)) + .map(|a| GpuPointer::from_mapping(a.mapping.firmware_mapping()?, a.offset)) .transpose()?, end_addr: self .end .as_ref() - .map(|a| GpuPointer::from_mapping(&a.mapping, a.offset)) + .map(|a| GpuPointer::from_mapping(a.mapping.firmware_mapping()?, a.offset)) .transpose()?, }) } diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs index 66e52e69811977..55b0eebb664d4d 100644 --- a/drivers/gpu/drm/asahi/g15/command.rs +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -34,7 +34,7 @@ use kernel::{prelude::*, sync::Arc, xarray}; use super::wire as uapi; use super::{gate, hw}; -use crate::{file, mmu, util::AnyBitPattern, util::Reader}; +use crate::{file, mmu, timestamp, util::AnyBitPattern, util::Reader}; /// Largest command buffer. pub(crate) const MAX_CMDBUF: usize = 4 << 20; @@ -135,7 +135,7 @@ pub(crate) struct Submission { /// Render and compute commands, for the queue's EXACT_PRIOR ordinals. pub(crate) counts: [u64; 2], /// The timestamp buffers the commands name, retained with the job. - pub(crate) timestamps: KVec>, + pub(crate) timestamps: KVec>, } /// What the per-command checks need. @@ -158,7 +158,7 @@ pub(crate) struct Prepared<'a> { /// Arena VAs of each command's timestamp slots. resolved: KVec<[u64; 4]>, counts: [u64; 2], - timestamps: KVec>, + timestamps: KVec>, } /// One command of the stream. @@ -349,7 +349,7 @@ pub(crate) fn check_stream(bytes: &[u8], early_tiling: bool) -> Result { /// The timestamp buffers named by a submission, resolved to firmware arena VAs. struct Timestamps<'a> { objects: Pin<&'a xarray::XArray>>, - held: KVec>, + held: KVec>, } impl Timestamps<'_> { @@ -365,15 +365,15 @@ impl Timestamps<'_> { .get(timestamp.handle.try_into()?) .ok_or(ENOENT)? .clone(); - let file::Object::TimestampBuffer(mapping) = object; - let mapping = mapping.firmware_mapping()?; + let file::Object::TimestampBuffer(buffer) = object; + let mapping = buffer.firmware_mapping()?; let offset = timestamp.offset as usize; if offset % 8 != 0 || offset >= mapping.size() || mapping.size() - offset < 8 { return Err(EINVAL); } let va = mapping.iova() + offset as u64; - if !self.held.iter().any(|held| Arc::ptr_eq(held, &mapping)) { - self.held.push(mapping, GFP_KERNEL)?; + if !self.held.iter().any(|held| Arc::ptr_eq(held, &buffer)) { + self.held.push(buffer, GFP_KERNEL)?; } Ok(va) } diff --git a/drivers/gpu/drm/asahi/g15/job.rs b/drivers/gpu/drm/asahi/g15/job.rs index a93b6039cc4665..0022b8d1cb764e 100644 --- a/drivers/gpu/drm/asahi/g15/job.rs +++ b/drivers/gpu/drm/asahi/g15/job.rs @@ -36,7 +36,7 @@ use kernel::{ }; use super::{command::Command, fence::JobFence, hw, queue::QueueState, vm::VmState, Shared}; -use crate::mmu; +use crate::{mmu, timestamp}; /// A job as the engine sees it. #[pin_data] @@ -58,7 +58,7 @@ pub(crate) struct Job { /// The engine's bookkeeping; `progress.signaled` makes [`Job::complete`] act once. pub(crate) progress: super::engine::Progress, /// The timestamp buffers the commands name (their arena VAs stay mapped while the job lives). - _timestamps: KVec>, + _timestamps: KVec>, /// Retains the VM's mappings (deferred unmaps, deferred VM close) while the firmware may /// access them. _guard: mmu::VmJobGuard, @@ -75,7 +75,7 @@ impl Job { vm: Arc, commands: KVec, fence: JobFence, - timestamps: KVec>, + timestamps: KVec>, guard: mmu::VmJobGuard, ) -> Result> { let progress = super::engine::Progress::new(commands.len()); diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a4..f0a023a1642468 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -35,7 +35,7 @@ pub(crate) use publication::{Prepared as PreparedPublication, Publication}; struct Destination { // The buffer keeps its GPU alias and its CPU mapping alive. - buffer: Arc, + buffer: Arc, offset: usize, /// The destination's address in the firmware timestamp window, if its buffer is mapped there. window_va: Option, diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 5ba1f368798765..b0e7471d0ea812 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -13,7 +13,7 @@ impl FenceOps for Completion { fn get_driver_name<'a>(self:&'a FenceObject)->&'a CStr {c_str!("asahi")} fn get_timeline_name<'a>(self:&'a FenceObject)->&'a CStr {c_str!("m3-native")} } -pub(crate) struct Destination { mapping: Arc, offset: usize } +pub(crate) struct Destination { _buffer: Arc, iova: u64 } impl Destination { fn resolve(objects: Pin<&xarray::XArray>>, timestamp: agx_uapi::UapiTimestamp) -> Result> { @@ -27,11 +27,12 @@ impl Destination { if offset & 7 != 0 || offset.checked_add(8).ok_or(EOVERFLOW)? > mapping.size() { return Err(EINVAL); } - Ok(Some(Self { mapping, offset })) + let iova = mapping.iova() + offset as u64; + Ok(Some(Self { _buffer: buffer.clone(), iova })) } } } - fn firmware_address(&self) -> u64 { self.mapping.iova() + self.offset as u64 } + fn firmware_address(&self) -> u64 { self.iova } } #[derive(Copy,Clone)] diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index ef7027ff1a6363..d3cf86aa89a1af 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -45,8 +45,7 @@ use kernel::{ error::code::*, - prelude::*, - sync::Arc, // + prelude::*, // }; use core::fmt; @@ -108,7 +107,7 @@ impl<'a, T> GpuPointer<'a, T> { /// Create a GPU pointer from a KernelMapping and an offset. /// TODO: Change all GPU pointers to point to the raw types so size_of here is GPU-sound. pub(crate) fn from_mapping( - mapping: &'a Arc, + mapping: &'a mmu::KernelMapping, offset: usize, ) -> Result> { let addr = mapping.iova().checked_add(offset as u64).ok_or(EINVAL)?; diff --git a/drivers/gpu/drm/asahi/queue/common.rs b/drivers/gpu/drm/asahi/queue/common.rs index 20396f2e772252..953cff0217f0fa 100644 --- a/drivers/gpu/drm/asahi/queue/common.rs +++ b/drivers/gpu/drm/asahi/queue/common.rs @@ -28,12 +28,13 @@ pub(super) fn get_timestamp_object( #[allow(irrefutable_let_patterns)] if let file::Object::TimestampBuffer(mapping) = object { + let fw_mapping = mapping.firmware_mapping()?; let offset = timestamp.offset; - if (offset.checked_add(8).ok_or(EINVAL)?) as usize > mapping.size() { + if (offset.checked_add(8).ok_or(EINVAL)?) as usize > fw_mapping.size() { return Err(ERANGE); } Ok(Some(UserTimestamp { - mapping: mapping.firmware_mapping()?, + mapping, offset: offset as usize, })) } else { diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index d5ed07753e67ac..582162be46add9 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -2,15 +2,15 @@ //! Prepared timestamp destinations shared by native command completion paths. -use crate::{gem, mmu}; +use crate::{gem, mmu, no_debug}; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] use crate::file; use core::ops::Range; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] use core::sync::atomic::{fence as barrier, Ordering}; -use kernel::{prelude::*, sync::Arc}; +use kernel::prelude::*; #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] -use kernel::{uapi, xarray}; +use kernel::{sync::Arc, uapi, xarray}; /// The size of a bound range: whole pages, not empty, inside an object of `object_size` bytes. fn bound_size(range: &Range, object_size: usize) -> Result { @@ -21,10 +21,20 @@ fn bound_size(range: &Range, object_size: usize) -> Result { Ok(size) } +/// The object offset of the timestamp at `offset` of a host buffer bound at `start` for `size` +/// bytes: the whole stamp must lie inside the bound range, which lies inside the object +/// ([`Buffer::host`]). +fn host_offset(start: usize, size: usize, offset: usize) -> Result { + if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > size { + return Err(ERANGE); + } + start.checked_add(offset).ok_or(EOVERFLOW) +} + /// A firmware-mapped timestamp buffer with a kernel CPU mapping of its backing, kept for the /// buffer's lifetime so that commands need no mapping of their own. pub(crate) struct FirmwareBuffer { - mapping: Arc, + mapping: mmu::KernelMapping, cpu: mmu::TimestampVmap, /// Mapped in the firmware's timestamp window: the firmware may write stamps itself. window: bool, @@ -56,7 +66,42 @@ pub(crate) enum Buffer { }, } +/// A timestamp buffer bound to a file, holding the charge for the kernel memory its records take +/// (see `file::BOUND_OBJECT_BYTES`), so the charge is given back with the last reference. +pub(crate) struct Bound { + buffer: Buffer, + _charge: crate::memacct::Commit, +} + +impl Bound { + pub(crate) fn new(buffer: Buffer, charge: crate::memacct::Commit) -> Self { + Self { buffer, _charge: charge } + } +} + +impl core::ops::Deref for Bound { + type Target = Buffer; + + fn deref(&self) -> &Buffer { + &self.buffer + } +} + +no_debug!(Bound); + +/// The larger of two sizes, for the heap bound below. +const fn max(a: usize, b: usize) -> usize { + if a > b { a } else { b } +} + impl Buffer { + /// Kernel heap bytes a buffer's own records take, at most: its deferred-release item. A CPU + /// buffer keeps its records inline. + pub(crate) const HEAP_BYTES: usize = max( + crate::cleanup::Deferred::::HEAP_BYTES, + crate::cleanup::Deferred::::HEAP_BYTES, + ); + pub(crate) fn firmware(mapping: mmu::KernelMapping) -> Result { Self::new_firmware(mapping, false) } @@ -85,7 +130,7 @@ impl Buffer { fn new_firmware(mapping: mmu::KernelMapping, window: bool) -> Result { let cpu = mapping.timestamp_vmap()?; Ok(Self::Firmware(crate::cleanup::Deferred::new(FirmwareBuffer { - mapping: Arc::new(mapping, GFP_KERNEL)?, + mapping, cpu, window, })?)) @@ -153,13 +198,7 @@ impl Buffer { pub(crate) fn timestamp_offset(&self, offset: usize) -> Result { match self { Self::Firmware(buffer) => buffer.mapping.timestamp_offset(offset), - // The bound range lies inside the object (Self::host). - Self::Host(buffer) => { - if offset.checked_add(size_of::()).ok_or(EOVERFLOW)? > buffer.size { - return Err(ERANGE); - } - buffer.start.checked_add(offset).ok_or(EOVERFLOW) - } + Self::Host(buffer) => host_offset(buffer.start, buffer.size, offset), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), } @@ -176,10 +215,12 @@ impl Buffer { } } - /// Legacy command encoders publish firmware pointers and must never accept a CPU-only buffer. - pub(crate) fn firmware_mapping(&self) -> Result> { + /// Firmware-aliased command encoders publish firmware pointers and must never accept a + /// host- or CPU-only buffer. Returning a borrow keeps the mapping tied to [`Bound`] so no + /// command can retain the mapping without also keeping its bind charge alive. + pub(crate) fn firmware_mapping(&self) -> Result<&mmu::KernelMapping> { match self { - Self::Firmware(buffer) => Ok(buffer.mapping.clone()), + Self::Firmware(buffer) => Ok(&buffer.mapping), Self::Host(_) => Err(EINVAL), #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] Self::Cpu { .. } => Err(EINVAL), @@ -203,7 +244,7 @@ fn checked_offset(offset: u64, size: usize, aligned: bool) -> Result { #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_G18))] struct Destination { // Retain the bound range and backing along with its prepared CPU view. - _mapping: Arc, + _mapping: Arc, cpu: mmu::TimestampMapping, } @@ -323,4 +364,16 @@ mod tests { assert_eq!(bound_size(&(0..2 * PAGE), PAGE), Err(EINVAL)); assert_eq!(bound_size(&(PAGE..usize::MAX & !(PAGE - 1)), 2 * PAGE), Err(EINVAL)); } + + #[test] + fn a_host_stamp_lies_inside_the_bound_range() { + // A host buffer bound at the object's second page: offsets are within the bound range + // and come back as object offsets. + assert_eq!(host_offset(PAGE, PAGE, 0), Ok(PAGE)); + assert_eq!(host_offset(PAGE, PAGE, PAGE - 8), Ok(2 * PAGE - 8)); + // A stamp reaching past the bound range is refused, even if the object goes on. + assert_eq!(host_offset(PAGE, PAGE, PAGE - 4), Err(ERANGE)); + assert_eq!(host_offset(PAGE, PAGE, PAGE), Err(ERANGE)); + assert_eq!(host_offset(0, PAGE, usize::MAX - 2), Err(EOVERFLOW)); + } } From e21d48c624bdecd3207592a29efff1e328a181b2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 03:56:02 +1100 Subject: [PATCH 1066/1514] drm/asahi: report that GEM_USERPTR pins are not bounded by RLIMIT_MEMLOCK Since commit 8a92c87c0f56 ("drm/asahi: bound GEM_USERPTR pins by the GPU memory limits, not RLIMIT_MEMLOCK") GEM_USERPTR takes a range of any size the GPU memory limits admit. Earlier kernels with GEM_USERPTR charge the pins to the caller's RLIMIT_MEMLOCK and refuse a larger range with ENOMEM; the systemd default is 8 MiB. Userspace cannot tell the two apart before it imports, so an API without a size bound of its own on imports (VK_EXT_external_memory_host) either has to offer them on every kernel and fail large imports on the older ones, or check the memlock limit on every kernel and stop offering them where the limit no longer applies. Report DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK with DRM_ASAHI_FEATURE_USERPTR. Bit 42 is taken by DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL, which is in review. The userptr selftest checks the bit in memlock_does_not_bound. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/file.rs | 5 ++++- include/uapi/drm/asahi_drm.h | 12 ++++++++++++ .../selftests/drivers/gpu/asahi-userptr/userptr.c | 2 ++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 08837155027662..02ab74331fa902 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -588,7 +588,10 @@ impl File { // Every backend admits the USC cache invalidate in the VDM root barrier. params.features |= uapi::DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE as u64; if Self::supports_user_memory(reg_data) { - params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64; + // GEM_USERPTR pins are bounded by the GPU memory ledger only, not by + // RLIMIT_MEMLOCK (UserPages::pin()). + params.features |= uapi::DRM_ASAHI_FEATURE_USERPTR as u64 + | uapi::DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK as u64; } if Self::supports_residency_control(reg_data) { params.features |= uapi::DRM_ASAHI_FEATURE_GEM_RESIDENCY as u64; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 3e1ad1c649aa7c..a958efda3339cf 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -561,6 +561,18 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) +/* + * DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK: DRM_IOCTL_ASAHI_GEM_USERPTR does not + * charge its pins to the caller's RLIMIT_MEMLOCK; only the GPU memory limits + * bound them (see struct drm_asahi_gem_userptr). Kernels that report + * DRM_ASAHI_FEATURE_USERPTR without it refuse with ENOMEM a range that + * exceeds that limit, unless the caller has CAP_IPC_LOCK, so userspace can + * check the limit before it offers imports of arbitrary size. Bit 42 is + * reserved for DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL. A feature bit like + * those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK ((1ULL) << 43) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c index 542aea41be5a62..3f1d4d25d9d394 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c +++ b/tools/testing/selftests/drivers/gpu/asahi-userptr/userptr.c @@ -340,6 +340,8 @@ TEST_F(asahi, memlock_does_not_bound) uint32_t h = 0; void *mem; + /* The kernel says so, for userspace that checks before it imports. */ + EXPECT_TRUE(self->params.features & DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK); ASSERT_EQ(0, drop_cap_ipc_lock()); ASSERT_EQ(0, getrlimit(RLIMIT_MEMLOCK, &old)); mem = mmap(NULL, size, PROT_READ | PROT_WRITE, From 8d7770f82a0de49a8af739410cc23c1108e0803e Mon Sep 17 00:00:00 2001 From: Jens Axboe Date: Wed, 11 Nov 2026 12:00:39 -0700 Subject: [PATCH 1067/1514] drm/asahi: t6050: identify the 27.2 (26B8125) G17S firmware of the K114/K116 Applies on top of aurora-silicon/linux PR #1173. The 16-inch M5 Pro OLED (K116s, Mac17,12) restores from the 27.2 (26B8125) image, not from the 26B123 image of the Mac17,8 that #1173 pins. Its a010 (G17S) firmware images carry LC_UUIDs that are the uuid of the K116s ADT's iop-gfx-nub and iop-gfx1-nub (8A2891FC-D479-37E8- 895D-71B4D88ECB51, 58FF964E-F74B-31C2-8179-3837D6ADA9C2), so this is what iBoot loads. TEXT 0x50000 + 0x54000, DATA 0x184000, the GKTS/ECAP records and the _rtk_tunables/_rtk_patchbay sections sit at 26B123's offsets, but the firmware identity digest differs: 26B8125 G17S af68d034a3f006b43dab661b825f12598cb86e4d2a0e3844f14fa5059f38f6cb 26B123 G17S 2b4613c62a8a007f22a94101702c9ac6c4e90f2e123f3b36fbe6ffea913f0fd9 Without this entry the driver refuses the K116s firmware before any GPU write. It names V26B123_M5, the InitData of the 26B123 firmware, whose layout this build shares. On the K116s both firmware roles accept that InitData and run it: the machine has run this graph daily since mid-November. The kernel logs "GPU firmware: 27.2 (26B8125), G17S", KWin, Plasma and Xwayland render on the GPU ("Apple M5 Pro (G17S B1)") with no Mesa environment variable set, and the GPU comes back after each deep sleep. Signed-off-by: Jens Axboe --- drivers/gpu/drm/asahi/hw/t6050.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index c0c974a4a368ea..8243aba470292c 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -49,6 +49,37 @@ pub(crate) const CONFIG: Config = Config { // primary's records by a few bytes). Each digest is that of the firmware's text with // those ranges zeroed, a loaded copy normalizing to it on every boot. Newest first. firmware: crate::g17::fw::variant::Firmware::Identified(&[ + // The 27.2 build of the Mac17,10 to Mac17,13 restore image (K114, K116), which iBoot + // loads on the K116s: the a010 images whose Mach-O UUIDs are the ADT's iop-gfx-nub and + // iop-gfx1-nub uuid. Its records and sections sit where 26B123's do; its kext builds the + // 26B123 version word and allocation sizes. + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B8125), G17S", + images: &[crate::fwid::FirmwareBuild { + name: "26B8125 for T6050 G17S, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], + boot_filled: &[ + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), + ], + text_sha256: [ + 0xaf, 0x68, 0xd0, 0x34, 0xa3, 0xf0, 0x06, 0xb4, 0x3d, 0xab, 0x66, 0x1b, 0x82, + 0x5f, 0x12, 0x59, 0x8c, 0xb8, 0x6e, 0x4d, 0x2a, 0x0e, 0x38, 0x44, 0xf1, 0x4f, + 0xa5, 0x05, 0x9f, 0x38, 0xf6, 0xcb, + ], + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, crate::g17::fw::variant::Build { os_version: [27, 2, 0], name: "27.2 (26B123), G17S", From 9c7603184044c554499b035856d91002980b8c4a Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Sat, 21 Nov 2026 15:09:58 +0100 Subject: [PATCH 1068/1514] drm/asahi: t6050: give the 26B8125 variant's reason from the K116s run The K116s 26B8125 entry named V26B123_M5 for what the 26B8125 kernel side builds. State instead what the driver itself sees: the firmware's records and sections sit at 26B123's offsets (the driver's boot-time layout checks), and on the K116s both firmware roles accepted the 26B123 InitData and ran it (driver up, Vulkan, a Plasma session). Comment only. Signed-off-by: Thomas Glanzmann --- drivers/gpu/drm/asahi/hw/t6050.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index 8243aba470292c..856c0ec3ddae5f 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -51,8 +51,8 @@ pub(crate) const CONFIG: Config = Config { firmware: crate::g17::fw::variant::Firmware::Identified(&[ // The 27.2 build of the Mac17,10 to Mac17,13 restore image (K114, K116), which iBoot // loads on the K116s: the a010 images whose Mach-O UUIDs are the ADT's iop-gfx-nub and - // iop-gfx1-nub uuid. Its records and sections sit where 26B123's do; its kext builds the - // 26B123 version word and allocation sizes. + // iop-gfx1-nub uuid. Its records and sections sit where 26B123's do, and on the K116s + // both firmware roles accepted the 26B123 InitData (V26B123_M5) and ran it. crate::g17::fw::variant::Build { os_version: [27, 2, 0], name: "27.2 (26B8125), G17S", From b62010b4a5c12ba3991f54f17ec065335934088d Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Sun, 22 Nov 2026 02:09:12 -0500 Subject: [PATCH 1069/1514] drm/asahi: t6050: identify the M5 Max's 27.2 (26B123) G17C firmware The 26B123 G17C build has the same interface (V26B123_M5) and the same GKTS/ECAP records and boot-filled ranges as the 26B123 G17S build, with its own digest. Without an entry the driver refuses the M5 Max's 27.2 firmware before any GPU write. Add the build, with the digest of its TEXT with those ranges zeroed. The same computation gives the existing 26A428 G17C pin and the 26B123 G17S one. Extend the fwid layout test in fwid.rs (renamed to m5_builds_name_their_layouts) to check CONFIG_MAX alongside CONFIG so the new G17C entry's layout variant and digest uniqueness are verified too. Signed-off-by: Erik Bourget [Diljit: applied on #1173 as merged, which carries no 27.3 (26C5035r) layouts: the layout test checks 27.2 and 27.0 builds only] Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/fwid.rs | 28 +++++++------ drivers/gpu/drm/asahi/hw/t6050.rs | 69 ++++++++++++++++++++++--------- 2 files changed, 65 insertions(+), 32 deletions(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index 3a00e38977c3e1..72b385d2f375c7 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -586,21 +586,23 @@ mod tests { } #[test] - fn m5_pro_builds_name_their_layouts() { + fn m5_builds_name_their_layouts() { use crate::g17::fw::variant::{Firmware, M5Layouts}; - let Firmware::Identified(builds) = crate::hw::t6050::CONFIG.firmware else { - panic!("the M5 Pro must identify its loaded firmware"); - }; - for (i, build) in builds.iter().enumerate() { - // 27.2 (26B123) moved the InitData layouts. - let layouts = if build.os_version >= [27, 2, 0] { - M5Layouts::V26B123 - } else { - M5Layouts::V26A428 + for cfg in [&crate::hw::t6050::CONFIG, &crate::hw::t6050::CONFIG_MAX] { + let Firmware::Identified(builds) = cfg.firmware else { + panic!("the M5 Pro and Max must identify their loaded firmware"); }; - assert_eq!(build.variant.m5_layouts, Some(layouts)); - for other in &builds[i + 1..] { - assert_ne!(build.images[0].text_sha256, other.images[0].text_sha256); + for (i, build) in builds.iter().enumerate() { + // 27.2 (26B123) moved the InitData layouts. + let layouts = if build.os_version >= [27, 2, 0] { + M5Layouts::V26B123 + } else { + M5Layouts::V26A428 + }; + assert_eq!(build.variant.m5_layouts, Some(layouts)); + for other in &builds[i + 1..] { + assert_ne!(build.images[0].text_sha256, other.images[0].text_sha256); + } } } } diff --git a/drivers/gpu/drm/asahi/hw/t6050.rs b/drivers/gpu/drm/asahi/hw/t6050.rs index 856c0ec3ddae5f..b8d783a6284249 100644 --- a/drivers/gpu/drm/asahi/hw/t6050.rs +++ b/drivers/gpu/drm/asahi/hw/t6050.rs @@ -175,33 +175,64 @@ pub(crate) const CONFIG_MAX: Config = Config { sleep_restart: false, recovery_slot_keys: None, gpu_generation: GpuGen::G17, - // As on the M5 Ultra, the firmware in `fw-text` must be this build. The boot loader loads - // the G17C build of both roles back to back: the primary's TEXT 0x50000, then the + // As on the M5 Ultra, the firmware in `fw-text` must be one of these builds. The boot loader + // loads the G17C build of both roles back to back: the primary's TEXT 0x50000, then the // secondary's 0x54000. The digest is that of the firmware's TEXT with the boot-filled ranges // zeroed. - firmware: crate::g17::fw::variant::Firmware::Identified(&[crate::g17::fw::variant::Build { - os_version: [27, 0, 0], - name: "27.0 (26A428), G17C", - images: &[ - crate::fwid::FirmwareBuild { - name: "26A428 for T6050 G17C, primary then secondary", + firmware: crate::g17::fw::variant::Firmware::Identified(&[ + // The 27.2 (26B123) a000 images: the records and boot-filled ranges sit where the G17S + // build's do. The digest is that of the stock images with those ranges zeroed. + crate::g17::fw::variant::Build { + os_version: [27, 2, 0], + name: "27.2 (26B123), G17C", + images: &[crate::fwid::FirmwareBuild { + name: "26B123 for T6050 G17C, primary then secondary", text_size: 0xa4000, data_size: 0x184000, - entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + entropy: &[[0x49ea4, 0x49f87], [0x9d92c, 0x9da0f]], boot_filled: &[ - (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), - (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + (0x224, 4), + (0x23c, 8), + (0x49764, 0x740), + (0x49ea4, 0x231), + (0x50224, 4), + (0x5023c, 8), + (0x9d1ec, 0x740), + (0x9d92c, 0x231), ], text_sha256: [ - 0x30, 0x4d, 0x85, 0x44, 0x66, 0x29, 0xbc, 0xdc, 0xa5, 0x95, 0x80, 0xb5, 0xff, - 0x00, 0x6d, 0xd8, 0x9f, 0x2c, 0xd8, 0xb4, 0xca, 0x60, 0x59, 0x9a, 0x0c, 0xb5, - 0x5c, 0x35, 0xec, 0xb0, 0x98, 0xf4, + 0x66, 0x48, 0xec, 0xe7, 0xe8, 0xc6, 0xb7, 0xb8, 0x28, 0x44, 0x36, 0x8f, 0x0e, + 0x07, 0x5a, 0x21, 0x80, 0xa0, 0x8c, 0xa3, 0x5f, 0xee, 0xd0, 0xb6, 0xe3, 0xf5, + 0x48, 0x71, 0x0d, 0x4d, 0xdb, 0x81, ], - }, - ], - variant: &crate::g17::fw::variant::V26A428_M5, - config: None, - }]), + }], + variant: &crate::g17::fw::variant::V26B123_M5, + config: None, + }, + crate::g17::fw::variant::Build { + os_version: [27, 0, 0], + name: "27.0 (26A428), G17C", + images: &[ + crate::fwid::FirmwareBuild { + name: "26A428 for T6050 G17C, primary then secondary", + text_size: 0xa4000, + data_size: 0x184000, + entropy: &[[0x49e60, 0x49f43], [0x9d918, 0x9d9fb]], + boot_filled: &[ + (0x224, 4), (0x23c, 8), (0x49720, 0x740), (0x49e60, 0x231), + (0x50224, 4), (0x5023c, 8), (0x9d1d8, 0x740), (0x9d918, 0x231), + ], + text_sha256: [ + 0x30, 0x4d, 0x85, 0x44, 0x66, 0x29, 0xbc, 0xdc, 0xa5, 0x95, 0x80, 0xb5, + 0xff, 0x00, 0x6d, 0xd8, 0x9f, 0x2c, 0xd8, 0xb4, 0xca, 0x60, 0x59, 0x9a, + 0x0c, 0xb5, 0x5c, 0x35, 0xec, 0xb0, 0x98, 0xf4, + ], + }, + ], + variant: &crate::g17::fw::variant::V26A428_M5, + config: None, + }, + ]), // Four clusters of ten cores. The buffers are sized for every core slot of the board, so the // board's cluster and slot counts admit the GPU, whichever cores are fused off. core_layout: CoreLayout { From 4a0eae2e3f44b4272628787f038d067a1356fc17 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 04:57:26 +1100 Subject: [PATCH 1070/1514] drm/asahi: flush compute stamps on G14 firmware 27.2 The G14 firmware 27.2 compute command left its JobMeta flush_stamps word clear. That did not matter while compute commands carried no user timestamps. Once they do, a queue of them stops retiring: on the M2 mini, gpubench compute.light at queue depth 16 timed out within one or two runs. The firmware had fetched the commands but never retired them, no MMU fault was pending and no firmware timeout event came. Set flush_stamps, as the 27.2 render commands already do for their JobMeta and as the M3 27.2 compute command does when it does not coalesce. With it, the same loop ran eight times with every case passing and no timeout. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 17 ++++++++++++++++- drivers/gpu/drm/asahi/gpu/v27_2.rs | 3 +++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index dcd5392c0c1467..4f7bcd5db970f9 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -103,6 +103,13 @@ pub(crate) const GLOBALS_PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; /// after the command time (+0x2c4) and the internal start/end pointers (+0x2cc), the order of /// the 13.5 compute command and of the 27.2 render commands (vertex +0x5e4, fragment +0x948). pub(crate) const COMPUTE_USER_TIMESTAMPS: usize = 0x2dc; + +/// The 27.2 compute command's JobMeta flush_stamps word, after the completion stamp, firmware +/// stamp, stamp value and slot (+0x298..+0x2b4); the render commands keep it at the same place +/// of their JobMeta (vertex +0x5a0, fragment +0x904). Set, the firmware flushes the command's +/// stamps when it completes; left clear, a compute queue whose commands write user timestamps +/// stalls with commands fetched but never retired. +pub(crate) const COMPUTE_FLUSH_STAMPS: usize = 0x2b4; /// The 13.5 compute JobParameters1 inside the 27.2 compute command. pub(crate) const COMPUTE_JOB_PARAMETERS1: usize = 0x68; @@ -256,7 +263,7 @@ mod tests { (0x68, 8), (0x70, 8), (0x78, 8), (0x80, 8), (0x88, 8), (0x90, 8), (0x98, 8), (0xa0, 8), (0xc0, 8), (0x1e8, 8), (0x1f0, 4), (0x220, 8), (0x228, 8), (0x264, 8), (0x270, 4), - (0x298, 0x1c), (0x2c4, 0x18), (0x304, 8), (0x314, 8), (0x334, 0x14), + (0x298, 0x20), (0x2c4, 0x18), (0x304, 8), (0x314, 8), (0x334, 0x14), ]; /// Whether `len` bytes at `at` fit the command and are none the compute encoder uses. @@ -277,6 +284,14 @@ mod tests { } } + #[test] + fn flush_stamps_follows_the_compute_job_meta_and_misses_the_user_pair() { + // The JobMeta words the encoder writes end right before it: slot at +0x2b0. + assert_eq!(COMPUTE_FLUSH_STAMPS, 0x2b0 + 4); + assert!(COMPUTE_FLUSH_STAMPS + 4 <= COMPUTE_USER_TIMESTAMPS); + assert_eq!(COMPUTE_FLUSH_STAMPS % 4, 0); + } + #[test] fn a_timestamp_operation_names_the_pair_only_when_there_is_one() { assert_eq!(user_timestamp_pointer(0x1000, [0, 0]), 0); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 32f606d5066fd7..fbb48e706eee58 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -117,6 +117,9 @@ fn encode_compute( put64(cmd, 0x2a0, q.fw_stamp); put32(cmd, 0x2a8, stamp_value); put32(cmd, 0x2b0, q.slot); + // flush_stamps, as the render commands set it: without it a queue of compute commands + // with user timestamps stops retiring. + put32(cmd, g14_v27_2_abi::COMPUTE_FLUSH_STAMPS, 1); put64(cmd, 0x2cc, timestamps); put64(cmd, 0x2d4, timestamps + 8); // Command-local dependency latch, enabled with seed 0; the firmware clears 0x10 bytes From 40a57bd9f958b68a7d10773b8d20e2c10b2eb0fd Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Thu, 19 Nov 2026 16:40:30 -0300 Subject: [PATCH 1071/1514] drm/asahi: g17: kill a closed guilty context instead of waiting for its work A client whose render work a GPU recovery found guilty keeps that work published after it exits: on 25G83 the host cannot take published groups back, and only a kill of the context unlinks them. The kill never came. kill_route() gives a pair that is not executed_for_kill() (a started group plus never-started ones behind it) no route, and kill_unsafe() holds the kill while any other client renders, up to LIVENESS_NS (5 s). Meanwhile each restart reran the guilty group, it hung again about every 83 ms, and eight such restarts stop the GPU for every client. On 2026-11-19 19:12 UTC a deqp-vk memory_model case (a hang in Mesa's G17P 64-bit atomic emulation) did exactly that beside a drawing desktop: deqp-vk exited 0.1 s after its EIO, its pair stayed at active=32 with frozen stamps for 12 restarts, the storm limit stopped the GPU, Hyprland lost its device and the machine rebooted. Which pairs: a quarantined pair of a closed owner, every group published, its VM recovery_guilty, not M5 (Pair::guilty_for_kill), and only once the host accepted a restart since the context's first close. The VM stays guilty and a failed VM's pairs are all quarantined, but its groups behind the one that hung may run fine; killing those would unlink work with nothing left to hang and no restart to release it. A group that still runs hangs again within ~83 ms, so this costs one restart at most. The kill: teardown_idle() counts such a pair, the render kill is eligible at once rather than after RENDER_KILL_DELAY_NS, it waits only for other clients' compute (kill_waits_as_failed), admission holds the pair with its work, kill_retry_delay() keeps polling, and it is still published once per context. A line logs each kill that releases guilty pairs, with the recovery generation. The release of its groups: the executed pair's proof (kill done on the scheduler page, no restart in progress) plus a restart the host accepted after it first saw the kill done (Context::restarted_since_kill). A group running at the kill keeps running until a restart drops it, and a restart between the kill's publication and its completion does not count, so the generation is latched at the first sighting, not at publication. The sighting is also taken while the firmware is halted in a restart, so a kill finished just before a restart the host had not seen yet still counts for that restart. Without the acknowledgement or a later restart the pair stays held, its memory pinned, until the processors stop. The pair afterwards: it never counts as idle for the scheduler release while it may run (counts_idle). Once its groups went on the guilty proof it counts (Pair::guilty_released), whether or not the firmware consumed the ring entries of the groups the kill unlinked. At detach, after the consumed scheduler release, it parks if its rings were consumed. If not, its graph and rings are kept and its slot is held (hold_kept_slots, as the kill held only the slots whose queues the scheduler page listed), out of service until the processors stop, because a parked pair's rings go to the next owner with entries naming freed descriptors and its queues stay installed. A released pair is not quarantined again when another queue of its VM fails, so it can still park. Both end states are logged with the ring cursors; debugfs counts kept pairs. A closed context that is neither failed nor holds such a pair keeps today's route and kill_unsafe() gate. This relies on four 25G83 behaviours, all seen on the M4 Pro in the same deqp-vk case beside a drawing desktop (2026-11-20 02:18 UTC). The restart table of the first recovery lacked the client's commands, the same shape as the storm above: - a context kill leaves a started group running until a restart: the restart 8 ms after the kill still found the GPU hung; - a restart drops started groups and never runs a killed context's unlinked work again: no recovery followed that restart; - releasing the pool after killing a hung render does not crash the firmware (a compute traversal did, see queue/compute/exit.rs); - the wait for foreign compute ends within the restart storm budget: the kill went out 260 ms after the EIO, 4 recoveries in all, only the first counted toward the limit. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context.rs | 71 +++++++++- drivers/gpu/drm/asahi/g17/queue/admission.rs | 34 ++++- drivers/gpu/drm/asahi/g17/queue/render.rs | 119 ++++++++++++++++- .../gpu/drm/asahi/g17/queue/render/parked.rs | 26 +++- drivers/gpu/drm/asahi/g17/recovery.rs | 7 + drivers/gpu/drm/asahi/g17/runtime/backend.rs | 3 + .../gpu/drm/asahi/g17/runtime/compute_exit.rs | 125 +++++++++++++----- drivers/gpu/drm/asahi/g17/runtime/events.rs | 3 + drivers/gpu/drm/asahi/g17/runtime/render.rs | 6 +- .../gpu/drm/asahi/g17/runtime/render/exit.rs | 19 ++- .../drm/asahi/g17/runtime/render/recovery.rs | 7 + .../drm/asahi/g17/runtime/render/teardown.rs | 116 ++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/teardown.rs | 9 +- tools/asahi/g17-admission-order-tests.py | 9 +- tools/asahi/g17-kill-route-tests.py | 62 +++++++-- tools/asahi/g17-owner-release-order-tests.py | 21 +-- tools/asahi/g17-quarantine-drain-tests.py | 14 +- tools/asahi/run-host-tests.py | 3 +- 18 files changed, 566 insertions(+), 88 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 84b519795da736..97161d5c51ea13 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -14,7 +14,7 @@ use super::{ status::VmStatus, }; use crate::mmu::{self, ExecutionContext, Vm, UAT_PGSZ}; -use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU8, AtomicUsize, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use identity::{Order, RenderSlots, WorkStates, FREE, NODE_STRIDE, STATE_COUNT}; /// Both of a context's render channels are bound to other pairs whose publications have not @@ -214,6 +214,12 @@ pub(crate) struct Context { /// A kill of this context was published, through a compute queue or on its render pairs' /// behalf. A context is killed at most once. kill_published: AtomicBool, + /// The host's recovery generation when it first saw the kill of this context done (its + /// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]). + kill_seen: AtomicU64, + /// The host's recovery generation at this context's latest close, `u64::MAX` while open + /// ([`Self::restarted_since_close`]). + closed_generation: AtomicU64, /// Advisory only: publication still checks the physical binding under the /// device mutex. False skips an inline attempt known to need admission. compute_binding_hint: AtomicBool, @@ -346,6 +352,8 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill_published: AtomicBool::new(false), + kill_seen: AtomicU64::new(u64::MAX), + closed_generation: AtomicU64::new(u64::MAX), compute_binding_hint: AtomicBool::new(false), render_seen: AtomicBool::new(false), qos, @@ -535,6 +543,23 @@ impl Context { self.kill_published.load(Ordering::Acquire) } + /// A queue of this context closed at the host's recovery `generation` (under the device + /// mutex). The latest close counts. + pub(crate) fn note_closed(&self, generation: u64) { + self.closed_generation.store(generation, Ordering::Release); + } + + /// The host accepted a GPU restart (`generation`) after this context's latest close. + pub(crate) fn restarted_since_close(&self, generation: u64) -> bool { + restarted_after(self.closed_generation.load(Ordering::Acquire), generation) + } + + /// The firmware finished the kill of this context (`killed`, its scheduler page) and the + /// host accepted a GPU restart (`generation`) after it first saw that. See [`restarted_since`]. + pub(crate) fn restarted_since_kill(&self, killed: bool, generation: u64) -> bool { + restarted_since(&self.kill_seen, killed, generation) + } + pub(crate) fn is_published(&self) -> bool { self.published.load(Ordering::Acquire) } @@ -834,10 +859,54 @@ fn must_retain(head: Option<[u64; 2]>, head_va: u64, killed: u32) -> bool { killed == 0 && head.is_none_or(|head| head != [0, head_va]) } +/// A restart was accepted (`generation`) after the event recorded at generation `at` +/// (`u64::MAX`: never happened). +fn restarted_after(at: u64, generation: u64) -> bool { + at != u64::MAX && generation > at +} + +/// Records in `seen` the recovery `generation` of the first call that sees a kill done +/// (`killed`), and reports whether a later generation was accepted since. A restart accepted +/// after that sighting was raised after the firmware had finished the kill, so it dropped +/// whatever of the killed context was still running; a restart between the kill's +/// publication and its completion does not count. A late first sighting only asks for a later +/// restart. +fn restarted_since(seen: &AtomicU64, killed: bool, generation: u64) -> bool { + if !killed { + return false; + } + let first = match seen.compare_exchange(u64::MAX, generation, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => generation, + Err(first) => first, + }; + restarted_after(first, generation) +} + #[kunit_tests(asahi_g17_qos_capacity)] mod capacity_tests { use super::*; + #[test] + fn only_a_restart_after_the_kill_was_seen_done_counts() { + let seen = AtomicU64::new(u64::MAX); + // No acknowledged kill: never, whatever restarts happened. + assert!(!restarted_since(&seen, false, 3)); + assert!(!restarted_since(&seen, false, 9)); + // The kill seen done at generation 4 (a restart at 3 came before it): not yet. + assert!(!restarted_since(&seen, true, 4)); + assert!(!restarted_since(&seen, true, 4)); + // The next accepted restart. + assert!(restarted_since(&seen, true, 5)); + assert_eq!(seen.load(Ordering::Relaxed), 4); + } + + #[test] + fn only_a_restart_after_the_close_counts() { + assert!(!restarted_after(u64::MAX, u64::MAX - 1)); + assert!(!restarted_after(7, 7)); + assert!(restarted_after(7, 8)); + } + #[test] fn linked_unkilled_work_is_retained() { let va = 0xfffffc20_0000_4400; diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index cc93cb6167981b..c1caf8470beb66 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -1180,7 +1180,8 @@ impl State { if slots & bit == 0 { continue; } - // A pair whose commands all ran is held with them (see `Pair::executed_for_kill`). + // A pair that only the kill releases is held with its commands (see + // `Pair::releasable_by_kill`: they all ran, or they are a guilty context's). if self.owners[slot] != owner || (executed & bit == 0 && (self.refs[slot] != 0 || self.active & bit != 0 || self.released & bit == 0)) @@ -1209,6 +1210,16 @@ impl Pool { self.returned(); } + /// Keep `slots` out of service until both processors stop: the killed guilty pairs + /// `detach_context` kept there still have their queues installed. The kill held only the + /// slots whose queues the scheduler page listed at the kill, so the hold is set here too. + pub(crate) fn hold_kept_slots(&self, slots: u64) { + if slots == 0 { + return; + } + self.state.lock().kill_hold |= slots & State::MASK; + } + /// End the kill hold of `slots` once their killed context's scheduler release was /// consumed (the firmware no longer names these pairs). A new owner takes them last. pub(crate) fn release_killed_slots(&self, slots: u64) { @@ -1337,6 +1348,27 @@ mod fault_capacity_tests { assert_eq!(pool.state.lock().kill_hold, 0); } + #[test] + fn a_kept_slot_stays_out_of_service_without_a_kill_hold() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + let lease = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let slot = lease.slot(); + let bit = 1u64 << slot; + pool.release_owner(1); + drop(lease); + // The kill held nothing here (the scheduler page did not list the pair's queues). + assert_eq!(pool.state.lock().kill_hold, 0); + pool.hold_kept_slots(bit); + pool.release_killed_slots(0); + assert_eq!(pool.state.lock().kill_hold, bit); + assert!(!pool.reassign_unused_spare(slot, Some(1), Some(2))); + let next = pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap(); + assert_ne!(next.slot(), slot); + drop(next); + pool.release_retained_owners_after_processor_stop(); + assert_eq!(pool.state.lock().kill_hold, 0); + } + #[test] fn consumed_scheduler_release_ends_the_kill_hold() { let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 64d3f50a5df9d6..07614e55551c64 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -232,6 +232,11 @@ pub(crate) struct Pair { /// Bit `p` set once a work slot of priority class `p` named the pair. outer_started: u8, quarantined: bool, + /// Its groups were released on the guilty proof after its context's kill + /// (`Pair::guilty_killed`): the firmware may never consume the ring entries of the groups + /// the kill unlinked, so the pair is released and detached on that proof + /// (`counts_idle`, `Pair::can_keep`), never parked for reuse while those entries remain. + guilty_released: bool, terminal: Option<(Arc, Error)>, previous: Option, displaced: Option, @@ -386,6 +391,7 @@ impl Pair { registered: None, outer_started: 0, quarantined: false, + guilty_released: false, terminal: None, previous: None, displaced: None, @@ -2059,6 +2065,11 @@ impl Pair { error: Error, defer: &mut impl FnMut(Deferred) -> Result, ) -> Result { + // A killed guilty pair released on its proof holds no groups and only waits for its + // detach: quarantined again (another queue of its VM failed), it could never park. + if self.guilty_released { + return Ok(()); + } self.quarantined = true; // Its groups end here, without their own watchdogs: none of their fragment kicks may hold // the task-stage order of other clients. @@ -2635,9 +2646,22 @@ impl Pair { } let counters = self.free_list.counters()?; let stamps = host.stamps(self.qids())?; - let (_, state) = host.epoch()?; + let (generation, state) = host.epoch()?; Ok(retirement::drained(self.ordinal, stamps, counters, state) - || (state == 0 && self.executed_unstamped() && self.context_killed())) + || (state == 0 && self.executed_unstamped() && self.context_killed()) + || self.guilty_killed(generation, state)) + } + + /// The pair's groups of a guilty context may go although they never retired: the firmware + /// finished the context's kill, and a GPU restart it raised after that has completed + /// (`state` 0). The kill unlinks the context's work list, but a group that was running at + /// the kill keeps running until a restart drops it, and only then is none of its memory + /// reachable. The pair itself, its ring and the context's work list stay held until the + /// context's scheduler release is consumed (detach, `release_killed_slots`). + fn guilty_killed(&self, generation: u64, state: u32) -> bool { + guilty_kill_done(self.guilty_unretired(generation), state, || { + self.memory.context.restarted_since_kill(self.context_killed(), generation) + }) } /// The firmware acknowledged a kill of this pair's context (scheduler page): it no longer @@ -2654,6 +2678,42 @@ impl Pair { Arc::ptr_eq(context, &self.memory.context) && self.executed_unstamped() } + /// A kill of the pair's context releases it with work that never retired: its commands all + /// ran unstamped (`executed_unstamped`), or a recovery found its VM guilty + /// (`guilty_unretired`). Its memory stays until the kill is done (`firmware_drained`). + pub(crate) fn releasable_by_kill(&self, context: &Arc, generation: u64) -> bool { + self.executed_for_kill(context) || self.guilty_for_kill(context, generation) + } + + /// The pair's context may be killed although its queued groups did not run: a recovery + /// found its VM guilty (`guilty_unretired`). + pub(crate) fn guilty_for_kill(&self, context: &Arc, generation: u64) -> bool { + Arc::ptr_eq(context, &self.memory.context) && self.guilty_unretired(generation) + } + + /// A closed owner's quarantined pair holding published work of a VM that a GPU recovery + /// found guilty. Its started group hangs the GPU again after every restart, with its queued + /// groups behind it, so its work never retires like other work: on 25G83 the host cannot + /// take published groups back, and only a kill of the context unlinks them. Left alone, + /// the restarts reach the storm limit and every client loses the device (11-19 19:12 UTC). + /// + /// Only once the host accepted a restart (`generation`) since the context's latest close: + /// the VM stays guilty, and a failed VM's pairs are all quarantined, but its groups queued + /// behind the one that hung may run and retire on their stamps. A kill then would unlink + /// those with nothing left to hang and so no restart to release them. A guilty group still + /// running hangs the GPU again within about 83 ms, which costs at most that one restart. + /// Not on M5, which takes published work back through its recovery target. + fn guilty_unretired(&self, generation: u64) -> bool { + !self.memory.graph.is_m5() + && self.memory.context.restarted_since_close(generation) + && self.quarantined + && self.owner.is_none() + && self.prepared.is_none() + && self.active.len() != 0 + && self.active.iter().all(|active| active.outer_published) + && self.memory.context.status().recovery_guilty() + } + /// Every command of this quarantined pair ran, its ring entries were consumed and its /// free-list blocks returned, yet the firmware never stores the stamp of the last one. /// On Neo this is the render work of a context whose compute command failed: it runs @@ -2693,7 +2753,8 @@ impl Pair { // Commands the firmware never unlinked are released only after it acknowledged the // kill of their context, on every path (see `firmware_drained`). let unstamped = self.executed_unstamped(); - let killed = unstamped && self.context_killed(); + let (generation, state) = host.epoch()?; + let killed = (unstamped && self.context_killed()) || self.guilty_killed(generation, state); let Some(active) = self.active.iter_mut().find(|a| !a.flist_completed) else { return Ok(false); }; @@ -2704,8 +2765,9 @@ impl Pair { }; let result = match retirement::poll(&mut active.ticket, &mut observer)? { retirement::Poll::Complete(ticks) => Ok(ticks), - // Its commands ran without a stamp (see `executed_unstamped`): they already failed - // with the quarantine, and the client sees them cancelled. + // Its commands ran without a stamp (see `executed_unstamped`), or its guilty context + // was killed (`guilty_killed`): they already failed with the quarantine, and the + // client sees them cancelled. retirement::Poll::Pending | retirement::Poll::Retry if killed => { crate::g17::trace::teardown(2, u64::from(self.slot), active.ticket.ordinal, 0); Err(ECANCELED) @@ -2752,6 +2814,12 @@ impl Pair { if self.active.iter().any(|a| !a.flist_completed) || !self.firmware_drained(host)? { return Ok(false); } + let (generation, state) = host.epoch()?; + let guilty = self.guilty_killed(generation, state); + if guilty { + pr_warn!("G17: render slot {}: {} groups of a killed guilty context released after a later restart (gen {})\n", + self.slot, self.active.len(), generation); + } while let Some(active) = self.active.front() { // A group retired on its pass record was reported then (`stamps_owed`): the pair-wide // proof above covers its stamps too (or the kill of its context), so only its @@ -2765,12 +2833,27 @@ impl Pair { self.active.pop().ok_or(EIO)?; } self.quarantined = false; + self.guilty_released |= guilty; self.drain_failures = 0; self.drain_retry_at = 0; self.resync(); Ok(true) } + /// While the firmware is halted for a restart: a finished kill of this pair's context + /// counts as seen done at `generation`, the one before that restart, at the latest. + pub(crate) fn note_kill_sighting(&self, generation: u64) { + let context = &self.memory.context; + if context.kill_published() { + context.restarted_since_kill(self.context_killed(), generation); + } + } + + /// See the `guilty_released` field. + pub(crate) fn guilty_released(&self) -> bool { + self.guilty_released + } + /// The registry first polls the completed prefix through this exact Arc. /// With successors, source policy quarantines every remaining group. A /// single unexecuted group may use the strict ownership witness instead. @@ -3455,6 +3538,32 @@ mod completion_noted_tests { } } +/// See `Pair::guilty_killed`: a guilty pair (`guilty`) goes only with no restart in progress +/// (`state` 0) and once `restarted` (`Context::restarted_since_kill`) holds. `restarted` is only +/// asked of a guilty pair with no restart in progress, so that its first sighting of the kill +/// is recorded at a settled generation. +fn guilty_kill_done(guilty: bool, state: u32, restarted: impl FnOnce() -> bool) -> bool { + guilty && state == 0 && restarted() +} + +#[kunit_tests(asahi_g17_render_guilty_kill)] +mod guilty_kill_tests { + use super::guilty_kill_done; + + #[test] + fn a_guilty_pair_goes_only_after_its_kill_and_a_later_restart() { + // Kill not acknowledged, or acknowledged with no restart since: held. + assert!(!guilty_kill_done(true, 0, || false)); + // A restart in progress: held, and the kill's sighting is not recorded mid-restart. + assert!(!guilty_kill_done(true, 1, || panic!("asked during a restart"))); + assert!(!guilty_kill_done(true, 3, || panic!("asked during a restart"))); + // Acknowledged, restarted since, restart complete: released. + assert!(guilty_kill_done(true, 0, || true)); + // Not a guilty pair: this proof never applies. + assert!(!guilty_kill_done(false, 0, || panic!("asked for an innocent pair"))); + } +} + #[kunit_tests(asahi_g17_render_drain_retry)] mod drain_retry_tests { use super::{drain_retry_delay, DRAIN_RETRY_LIMIT}; diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index 6313bf2ef5128a..f1fc45cee87aba 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -71,7 +71,24 @@ impl Pair { } fn can_park_backing(&self, context: &Arc) -> Result { - Ok(Arc::ptr_eq(context, self.context()) + Ok(self.backing_detachable(context) && self.idle_for_context(context)?) + } + + /// A killed guilty pair whose groups went on the guilty proof (`guilty_released`) but whose + /// rings the firmware has not consumed: the entries of the groups the kill unlinked may + /// never be read. It cannot park, since a parked pair's rings go to the next owner with + /// those entries naming freed descriptors, so `detach_context` keeps it, and its slot, out of + /// service until the processors stop. + pub(crate) fn can_keep(&self, context: &Arc) -> bool { + self.guilty_released + && self.owner.is_none() + && self.prepared.is_none() + && self.active.len() == 0 + && self.backing_detachable(context) + } + + fn backing_detachable(&self, context: &Arc) -> bool { + Arc::ptr_eq(context, self.context()) && self .previous .as_ref() @@ -79,7 +96,11 @@ impl Pair { && self.displaced.is_none() && self.pending_aliases.is_none() && self.kick_aliases.is_none() - && self.idle_for_context(context)?) + } + + /// The pair's two ring cursors (`done`, `read`, `write`), for the detach log line. + pub(crate) fn ring_cursors(&self) -> Result<[crate::g17::queue::render::retirement::Cursors; 2]> { + self.memory.graph.cursors() } /// Consumes the pair only after can_park and all collector capacity checks succeeded @@ -274,6 +295,7 @@ impl ParkedPair { registered: self.registered, outer_started: self.outer_started, quarantined: false, + guilty_released: false, terminal: None, previous: self.previous.take(), displaced: None, diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 422bfe06f9b607..9b1379c58d9b64 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -116,6 +116,12 @@ pub(super) trait Queues { fn note_interrupted(&mut self, qid: u8, stamp: u32) -> Interrupted; /// Optional diagnostics only; absence cannot alter attribution or release. fn report_blamed_render(&self, _qid: u8) {} + /// Read while firmware is halted for the restart the host accepted after `generation`: + /// every killed context whose kill the firmware finished counts as first seen done at + /// `generation` at the latest, so this restart releases its guilty pairs + /// (`Context::restarted_since_kill`). Without this, a kill finished just before a restart + /// that the host had not observed yet would wait for a restart that may never come. + fn note_kill_sightings(&self, _generation: u64) {} /// Optional diagnostics: logs the MMU fault banks while the firmware is halted. fn report_mmu_fault(&self) {} fn settle_blamed_render(&mut self, qid: u8, error: Error); @@ -311,6 +317,7 @@ pub(super) fn service( // still retire it with stamps and records that look like success, so it is // marked before firmware resumes and never reports success. let entries = read_entries(host); + host.note_kill_sightings(host.recovery().accepted.wrapping_sub(1)); host.transition(3, 0)?; if host.recovery_state()? != 0 { return Err(EIO); diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f9d2999a4e1d59..f09b3d5d5cb8ed 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -100,6 +100,9 @@ impl Backend { let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; + // A pair of this context that holds guilty work counts for a kill only after a restart + // since this close (`Pair::guilty_for_kill`). + self.context.note_closed(firmware.recovery.generation()); // Retain a published scheduler before a never-kicked physical graph is // removed. The teardown entry owns its root until control consumption. firmware diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index d19a52c6746328..d9dbd52fe903e4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -54,14 +54,24 @@ fn render_kill_target(listed: u128, own: u128) -> Option { (candidates != 0).then(|| candidates.trailing_zeros() as u8) } -/// A closed context may be killed on its render pairs' behalf once it has been closed for -/// [`RENDER_KILL_DELAY_NS`], it was never killed, a pair of it holds executed but unstamped -/// commands and no compute queue still runs it, switches away from it or killed it. A second kill -/// of a killed context made the firmware fault on the killed pair's own tiling queue within a -/// millisecond of acknowledging it: with the pair's release held back, a context killed through -/// its compute queue still looked like a render-only candidate. -fn render_kill_eligible(age: u64, killed: bool, executed: bool, compute_clear: bool) -> bool { - age >= RENDER_KILL_DELAY_NS && !killed && executed && compute_clear +/// A closed context may be killed on its render pairs' behalf once it was never killed, no +/// compute queue still runs it, switches away from it or killed it, and a pair of it holds +/// executed but unstamped commands (`executed`) once it has been closed for +/// [`RENDER_KILL_DELAY_NS`], or holds guilty work (`guilty`, `Pair::guilty_for_kill`) at once: +/// that work never retires, it hangs the GPU again about every 83 ms, and eight such restarts +/// stop the GPU for every client. A second kill of a killed context made the firmware fault on +/// the killed pair's own tiling queue within a millisecond of acknowledging it: with the +/// pair's release held back, a context killed through its compute queue still looked like a +/// render-only candidate. +fn render_kill_eligible(age: u64, killed: bool, executed: bool, guilty: bool, compute_clear: bool) -> bool { + !killed && compute_clear && (guilty || (executed && age >= RENDER_KILL_DELAY_NS)) +} + +/// A closed context's kill waits only for other contexts' compute to pause, not for their +/// render work, when its compute failed (`compute_failed`) or the kill releases render pairs +/// that nothing else releases (`releases_pairs`, `Firmware::kill_releases_render`). +fn waits_as_failed(compute_failed: bool, releases_pairs: bool) -> bool { + compute_failed || releases_pairs } /// How a closed context whose render pairs are idle for a kill (`teardown_idle`) is killed. @@ -217,7 +227,7 @@ impl Firmware { let Some((context, age)) = self.queues.teardown.closed(index, now) else { continue; }; - if !self.queues.render.teardown_idle(&context)? { + if !self.queues.render.teardown_idle(&context, self.recovery.generation())? { self.queues.teardown.clear_kill_wait(index); continue; } @@ -253,7 +263,7 @@ impl Firmware { let Some((context, age)) = due else { continue; }; - if !self.queues.render.teardown_idle(&context)? { + if !self.queues.render.teardown_idle(&context, self.recovery.generation())? { continue; } if let Err(error) = self.publish_compute_exit(&context, age, now, &mut pressed) { @@ -345,7 +355,7 @@ impl Firmware { && !self .queues .admission - .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.executed_slots(context) & hold) + .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.kill_slots(context, self.recovery.generation()) & hold) { return Ok(()); } @@ -359,6 +369,7 @@ impl Firmware { // stop, and the held render identities until this context's scheduler release // is consumed or processors stop. context.note_kill_published(); + self.note_guilty_kill(context, hold, "compute exit"); let mut queue = self.queues.compute[index] .as_mut() .and_then(|entry| entry.queue.as_deref_mut()) @@ -392,37 +403,51 @@ impl Firmware { kill_route( self.compute_failed(context), self.queues.render.teardown_pools_released(context), - self.kill_releases_executed_render(context), + self.kill_releases_render(context), self.compute_exit_pending(context), self.render_kill_candidate(index, context, age), ) } /// A kill of `context` would release render pairs of it whose commands all ran but were - /// never stamped (`Pair::executed_for_kill`), and no kill of it was published yet. Only that - /// kill releases them. Never a second time: a second kill of a killed context made the - /// firmware fault on the killed pair's own tiling queue (see `render_kill_eligible`). Not on - /// M5, which never kills a context on its render pairs' behalf. - fn kill_releases_executed_render(&self, context: &Arc) -> bool { - !self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0 + /// never stamped (`Pair::executed_for_kill`) or that hold guilty work + /// (`Pair::guilty_for_kill`), and no kill of it was published yet. Only that kill releases + /// them. Never a second time: a second kill of a killed context made the firmware fault on + /// the killed pair's own tiling queue (see `render_kill_eligible`). Not on M5, which never + /// kills a context on its render pairs' behalf. + fn kill_releases_render(&self, context: &Arc) -> bool { + !self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0 + } + + /// Logs a published kill that releases guilty pairs (`Pair::guilty_for_kill`), with the + /// recovery generation, so a test shows whether the next restart dropped their work. + fn note_guilty_kill(&self, context: &Arc, hold: u64, route: &str) { + let generation = self.recovery.generation(); + let guilty = self.queues.render.guilty_slots(context, generation) & hold; + if guilty != 0 { + pr_warn!("G17: scheduler {} killed by its {} at recovery gen {}: render slots {:#x} hold guilty work\n", + context.id(), route, generation, guilty); + } } /// A compute exit of `context` waits only for other contexts' compute to pause /// ([`Self::foreign_compute_running`]), as a failed context's kill and a render-only kill /// do, instead of for all of their work ([`Self::kill_unsafe`]). That holds when its compute - /// failed ([`Self::compute_failed`]), and when the kill releases executed render pairs: - /// those are what a render-only kill releases, and nothing else does. `kill_unsafe` also - /// waits for other clients' render work, and it gives no warning and has no memory-pressure - /// escape. Under a steady render load the pairs, pools and memory would stay held. + /// failed ([`Self::compute_failed`]), and when the kill releases executed or guilty render + /// pairs: those are what a render-only kill releases, and nothing else does. `kill_unsafe` + /// also waits for other clients' render work, and it gives no warning and has no + /// memory-pressure escape. Under a steady render load the pairs, pools and memory would + /// stay held, and a guilty pair would hang the GPU until the restart storm limit. fn kill_waits_as_failed(&self, context: &Arc) -> bool { - self.compute_failed(context) || self.kill_releases_executed_render(context) + waits_as_failed(self.compute_failed(context), self.kill_releases_render(context)) } /// A closed context whose compute side is clean, with render pairs whose commands all ran /// but were never stamped (`Pair::executed_for_kill`). Its failed compute command was /// retired on the firmware's fault record, so no compute queue is left to carry a kill, /// yet those pairs are released only after one: without this the context, its pairs and - /// its memory stay until the processors stop. + /// its memory stay until the processors stop. Likewise a closed context with a pair holding + /// guilty work (`Pair::guilty_for_kill`), which only a kill stops hanging the GPU. /// /// M5 has none: it issues a context kill only from a compute queue's exit, so a /// render-only M5 context is never killed. @@ -431,6 +456,7 @@ impl Firmware { age, self.queues.teardown.render_kill_published(index) || context.kill_published(), self.queues.render.executed_slots(context) != 0, + self.queues.render.guilty_slots(context, self.recovery.generation()) != 0, self.queues.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()).all(|queue| { queue.idle_for_context(context) && !queue.switching_from(context) && !queue.exit_published(context) }), @@ -494,7 +520,7 @@ impl Firmware { if !self .queues .admission - .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.executed_slots(context) & hold) + .hold_render_slots_for_exit_kill(owner, hold, self.queues.render.kill_slots(context, self.recovery.generation()) & hold) { refuse_render_kill(&mut self.queues.teardown, index, RENDER_KILL_HOLD); return Ok(()); @@ -508,6 +534,7 @@ impl Firmware { // can fail. The held pairs stay held until this context's scheduler release is // consumed (`release_killed_slots` at detach). context.note_kill_published(); + self.note_guilty_kill(context, hold, "render kill"); self.queues.teardown.record_render_kill(index, cookie, now)?; record_kill_wait(self.queues.teardown.take_kill_wait(index, now)); if beside { @@ -563,7 +590,7 @@ impl Firmware { self.queues.teardown.closed(index, now).is_some_and(|(context, _)| { !context.kill_published() && (self.compute_exit_pending(&context) - || self.queues.render.executed_slots(&context) != 0) + || self.queues.render.kill_slots(&context, self.recovery.generation()) != 0) }) }) .then_some(KILL_RETRY_NS) @@ -647,7 +674,10 @@ impl Firmware { #[kernel::macros::kunit_tests(asahi_g17_render_kill_target)] mod render_kill_target_tests { - use super::{hold_owner, kill_route, render_kill_eligible, render_kill_target, KillRoute, RENDER_KILL_DELAY_NS}; + use super::{ + hold_owner, kill_route, render_kill_eligible, render_kill_target, waits_as_failed, KillRoute, + RENDER_KILL_DELAY_NS, + }; #[test] fn executed_render_pairs_do_not_hold_back_their_compute_exit() { @@ -667,11 +697,42 @@ mod render_kill_target_tests { #[test] fn a_killed_context_is_never_killed_again() { - assert!(render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS - 1, false, true, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, false, true)); - assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false)); + assert!(render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS - 1, false, true, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, false, false, true)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, false, true, false, false)); + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS, true, false, true, true)); + } + + #[test] + fn a_closed_guilty_context_is_killed_on_its_render_pairs_behalf_at_once() { + // A pair holding a spinning group and never-started groups behind it: not executed, + // guilty. Eligible without the retirement delay, and the render pairs carry the kill + // when no compute queue will exit. + assert!(render_kill_eligible(0, false, false, true, true)); + assert_eq!(kill_route(false, false, true, false, render_kill_eligible(0, false, false, true, true)), + KillRoute::Render); + // A compute queue that will exit carries it instead, under the same rule as an + // executed pair (`releases` = executed or guilty). + assert_eq!(kill_route(false, false, true, true, false), KillRoute::Compute); + // Never a second time, and not while compute of the context still runs. + assert!(!render_kill_eligible(0, true, false, true, true)); + assert!(!render_kill_eligible(0, false, false, true, false)); + } + + #[test] + fn only_a_kill_that_releases_pairs_skips_the_wait_for_foreign_render_work() { + // Guilty or executed pairs, or failed compute: only foreign compute is waited for. + assert!(waits_as_failed(false, true)); + assert!(waits_as_failed(true, false)); + // A closed context that is neither, with queued work: `kill_unsafe` as before, which + // also waits for every foreign render. + assert!(!waits_as_failed(false, false)); + // Its route is unchanged too: before the delay, or with only queued work, no render kill. + assert!(!render_kill_eligible(RENDER_KILL_DELAY_NS * 4, false, false, false, true)); + assert_eq!(kill_route(false, false, false, false, false), KillRoute::None); + assert_eq!(kill_route(false, true, false, true, false), KillRoute::Compute); } #[test] diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index be13a089f7a0fb..f269baf58e9429 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -273,6 +273,9 @@ impl recovery::Queues for Service<'_> { queue.note_interrupted(stamp) }) } + fn note_kill_sightings(&self, generation: u64) { + self.firmware.queues.note_render_kill_sightings(generation); + } fn report_blamed_render(&self, qid: u8) { self.firmware .queues diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index ab33c149ba96d3..2dfac71fc50ff3 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -79,6 +79,9 @@ pub(super) struct RenderState { /// Graphs of released contexts the firmware may still walk (see `detach_context`): kept /// until the firmware stops, when this state is dropped. kept_graphs: KVec, + /// Killed guilty pairs whose rings the firmware never consumed (see `detach_context`): + /// kept, with their slots out of service, until the firmware stops. + kept_pairs: KVec, next_pm_generation: u64, } @@ -106,6 +109,7 @@ impl RenderState { grow: grow::Grow::new()?, retired: KVec::with_capacity(128, GFP_KERNEL)?, kept_graphs: KVec::new(), + kept_pairs: KVec::new(), next_pm_generation: 1, }) } @@ -1377,7 +1381,7 @@ impl Registry { impl RenderState { pub(super) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { writeln!(f, "retired_render_bindings used={} total={}", self.retired.len(), self.retired.capacity())?; - writeln!(f, "firmware_linked_render_graphs kept={} leaked={}", self.kept_graphs.len(), + writeln!(f, "firmware_linked_render_graphs kept={} kept_guilty_pairs={} leaked={}", self.kept_graphs.len(), self.kept_pairs.len(), teardown::LEAKED_GRAPHS.load(core::sync::atomic::Ordering::Relaxed))?; let unsettled = self.entries.iter().flatten() .filter_map(|entry| entry.pair.as_ref()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs index 6c58f728b3eb59..ef8d40bb9a5704 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs @@ -28,11 +28,24 @@ impl RenderState { /// Slots of `context`'s pairs whose commands all ran but stay unretired until its kill. pub(in crate::g17::runtime) fn executed_slots(&self, context: &Arc) -> u64 { + self.slots_where(|pair| pair.executed_for_kill(context)) + } + + /// Slots of `context`'s pairs whose guilty work stays unretired until its kill + /// (`Pair::guilty_for_kill`). + pub(in crate::g17::runtime) fn guilty_slots(&self, context: &Arc, generation: u64) -> u64 { + self.slots_where(|pair| pair.guilty_for_kill(context, generation)) + } + + /// Slots of `context`'s pairs that only its kill releases (`Pair::releasable_by_kill`). + pub(in crate::g17::runtime) fn kill_slots(&self, context: &Arc, generation: u64) -> u64 { + self.slots_where(|pair| pair.releasable_by_kill(context, generation)) + } + + fn slots_where(&self, matches: impl Fn(&crate::g17::queue::render::Pair) -> bool) -> u64 { let mut slots = 0; for (slot, entry) in self.entries.iter().enumerate() { - if entry.as_ref().and_then(|entry| entry.pair.as_ref()) - .is_some_and(|pair| pair.executed_for_kill(context)) - { + if entry.as_ref().and_then(|entry| entry.pair.as_deref()).is_some_and(&matches) { slots |= 1u64 << slot; } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs index 02ece8cf4025b7..1faf45f16a3ebe 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs @@ -22,6 +22,13 @@ impl Registry { } } + /// See `recovery::Queues::note_kill_sightings`. + pub(in crate::g17::runtime) fn note_render_kill_sightings(&self, generation: u64) { + for pair in self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()) { + pair.note_kill_sighting(generation); + } + } + pub(in crate::g17::runtime) fn render_pass_started(&self, qid: u8, stamp: u64) -> Option { self.render.entries.iter().flatten() .filter_map(|entry| entry.pair.as_ref()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs b/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs index 5b8379078b1511..38b14126e989ec 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/teardown.rs @@ -18,19 +18,23 @@ impl RenderState { /// Nothing of `context` still runs on its render pairs, so a kill of it may be published. /// A pair whose commands all ran unstamped (`Pair::executed_for_kill`) counts as idle: only - /// that kill releases it. - pub(in crate::g17::runtime) fn teardown_idle(&self, context: &Arc) -> Result { - self.idle_for(context, false) + /// that kill releases it. So does a pair holding guilty work (`Pair::guilty_for_kill`): it + /// runs only to hang the GPU again, and only the kill ends that. + pub(in crate::g17::runtime) fn teardown_idle(&self, context: &Arc, generation: u64) -> Result { + self.idle_for(context, Some(generation)) } /// As [`Self::teardown_idle`], for releasing `context`'s scheduler: a pair whose commands ran /// unstamped counts only once a kill of the context has been published, since until then - /// the firmware still links that work. + /// the firmware still links that work. A killed guilty pair counts once its groups went on + /// the guilty proof (`Pair::guilty_released`), whether or not its rings were consumed. pub(in crate::g17::runtime) fn release_idle(&self, context: &Arc) -> Result { - self.idle_for(context, true) + self.idle_for(context, None) } - fn idle_for(&self, context: &Arc, release: bool) -> Result { + /// `kill`: the host's recovery generation for a kill decision, `None` for the scheduler + /// release. See [`counts_idle`]. + fn idle_for(&self, context: &Arc, kill: Option) -> Result { // A pair that changed owner keeps running this scheduler's queues until // the new owner's first command leaves it, whichever context owns it now. let scheduler = Some(context.scheduler_va()); @@ -52,8 +56,10 @@ impl RenderState { return Ok(false); } if let Some(pair) = entry.pair.as_ref() { - if !pair.idle_for_context(context)? - && !((!release || context.kill_published()) && pair.executed_for_kill(context)) + let idle = pair.idle_for_context(context)?; + let guilty = kill.is_some_and(|generation| pair.guilty_for_kill(context, generation)); + if !counts_idle(kill.is_none(), context.kill_published(), idle, pair.executed_for_kill(context), + guilty, pair.guilty_released()) { return Ok(false); } @@ -112,13 +118,15 @@ impl RenderState { } /// Preflight the entire Context before detaching its first graph. Successor - /// graphs on the same VM have a different Arc and remain installed. + /// graphs on the same VM have a different Arc and remain installed. Returns the slots + /// whose killed guilty pairs were kept out of service (`Pair::can_keep`): their kill + /// hold stays. pub(in crate::g17::runtime) fn detach_context( &mut self, context: &Arc, buffers: &mut BufferIds, out: &mut ReclaimBatch, - ) -> Result { + ) -> Result { let mut count = self .retired .iter() @@ -136,7 +144,7 @@ impl RenderState { return Err(EBUSY); } if let Some(pair) = entry.pair.as_ref() { - if !pair.can_park(context)? { + if !pair.can_park(context)? && !pair.can_keep(context) { return Err(EBUSY); } count += 1; @@ -146,7 +154,11 @@ impl RenderState { return Err(EBUSY); } let linked = context.firmware_may_link(); - for entry in self.entries.iter_mut().flatten() { + let mut kept = 0u64; + for (slot, entry) in self.entries.iter_mut().enumerate() { + let Some(entry) = entry.as_mut() else { + continue; + }; if !entry .context .as_ref() @@ -157,10 +169,29 @@ impl RenderState { let Some(pair) = entry.pair.as_ref() else { continue; }; + // Either end state of a killed guilty pair is logged: the test of the kill fix + // reads from it whether the firmware consumed the unlinked groups' ring entries. + let keep = !pair.can_park(context)?; + if pair.guilty_released() { + pr_warn!("G17: render slot {}: killed guilty pair {} (cursors {:?})\n", slot, + if keep { "kept out of service until the GPU stops: its rings were not consumed" } + else { "parked: its rings were consumed" }, + pair.ring_cursors()); + } buffers.unreserve_owner(pair.buffer_id())?; let target = out.binding_slot()?; let pair = entry.pair.take().ok_or(EIO)?; let (mut parked, retired) = KBox::into_inner(pair).park(); + if keep { + // Neither the rings nor the graph their entries name are reused or freed, and + // the slot's kill hold stays, until the processors stop. + keep_graph(&mut self.kept_graphs, retired); + keep_pair(&mut self.kept_pairs, parked); + kept |= 1u64 << slot; + entry.context = None; + entry.pool = None; + continue; + } // This park follows the consumed release of `context`. parked.release_consumed(context.scheduler_va()); if linked { @@ -192,7 +223,7 @@ impl RenderState { *out.binding_slot()? = Some(retired); } } - Ok(()) + Ok(kept) } } @@ -216,6 +247,65 @@ impl Registry { } } +/// Whether a render pair of a closed context counts as idle: for the kill decision +/// (`release` false) or for the scheduler release, which lets the pair's ring and graph go. +/// - `idle`: nothing of it runs (`Pair::idle_for_context`). +/// - `executed`: its commands all ran unstamped (`Pair::executed_for_kill`); for the release +/// only once the kill was published (`kill_published`). +/// - `guilty`: it holds guilty work (`Pair::guilty_for_kill`); for the kill decision only. Its +/// started group may run until the restart after the kill, so counting it for the release +/// would free a running group's ring. +/// - `guilty_released`: its groups went on the guilty proof (`Pair::guilty_released`); for the +/// release, its rings may never be consumed. +fn counts_idle(release: bool, kill_published: bool, idle: bool, executed: bool, guilty: bool, guilty_released: bool) + -> bool +{ + idle + || (executed && (!release || kill_published)) + || (guilty && !release) + || (guilty_released && release && kill_published) +} + +/// Keeps a killed guilty pair until the firmware stops (see `detach_context`); if even that +/// cannot be recorded, it is leaked rather than dropped. +fn keep_pair(kept: &mut KVec, pair: crate::g17::queue::render::parked::ParkedPair) { + if kept.reserve(1, GFP_KERNEL).is_ok() { + if let Err(error) = kept.push_within_capacity(pair) { + LEAKED_GRAPHS.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + core::mem::forget(error.0); + } + } else { + LEAKED_GRAPHS.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + core::mem::forget(pair); + } +} + +#[kernel::macros::kunit_tests(asahi_g17_render_teardown_idle)] +mod idle_tests { + use super::counts_idle; + + #[test] + fn a_guilty_pair_never_counts_idle_for_the_scheduler_release_while_it_may_run() { + // The use-after-free guard: killed, guilty, not idle, not yet released on the proof. + assert!(!counts_idle(true, true, false, false, true, false)); + assert!(!counts_idle(true, false, false, false, true, false)); + // For the kill decision it counts. + assert!(counts_idle(false, false, false, false, true, false)); + // Released on the guilty proof: counts for the release once the kill was published. + assert!(counts_idle(true, true, false, false, false, true)); + assert!(!counts_idle(true, false, false, false, false, true)); + } + + #[test] + fn idle_and_executed_pairs_count_as_before() { + assert!(counts_idle(true, false, true, false, false, false)); + assert!(counts_idle(false, false, false, true, false, false)); + assert!(!counts_idle(true, false, false, true, false, false)); + assert!(counts_idle(true, true, false, true, false, false)); + assert!(!counts_idle(false, false, false, false, false, false)); + } +} + /// Graphs that could not be recorded in `kept_graphs` and were leaked instead, for debugfs. pub(super) static LEAKED_GRAPHS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); diff --git a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs index e1862504135b25..2127f7dfc977c5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs @@ -140,12 +140,15 @@ impl Host for Service<'_> { let linked = context.retain_linked_work(self.objects); let (_, _, slots) = self.render.exit_scope(context); crate::g17::trace::teardown(5, u64::from(context.id()), slots, u64::from(linked)); - self.render + let kept = self + .render .detach_context(context, self.buffers, self.reclaim)?; // The firmware consumed this context's scheduler release after its kill (if any) // was acknowledged and its pairs went idle: it no longer names these pairs, so - // their kill hold ends here rather than at the next processor stop. - self.admission.release_killed_slots(slots); + // their kill hold ends here rather than at the next processor stop. Pairs kept out + // of service keep theirs until then. + self.admission.release_killed_slots(slots & !kept); + self.admission.hold_kept_slots(kept); // detach_context preflights this slot together with every graph slot. // Retain it before Pending removes its reference under the device lock. self.reclaim.context(context) diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 89c9dc15c809d0..c9baee2e000c84 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -407,6 +407,7 @@ def release_fixture(): impl Context { pub fn is_published(&self) -> bool { self.published } pub fn scheduler_va(&self) -> u64 { self.scheduler } + pub fn note_closed(&self, _generation: u64) {} } } pub mod teardown { @@ -472,7 +473,9 @@ def release_fixture(): """ + item(render_teardown, 'pub(in crate::g17::runtime) fn release_render(') + '\n' + runtime + r""" } """ + item(render, 'fn render_hold(') + r""" - pub struct Firmware { pub queues: Registry } + pub struct Recovery; + impl Recovery { pub fn generation(&self) -> u64 { 0 } } + pub struct Firmware { pub queues: Registry, pub recovery: Recovery } pub struct Host<'a> { firmware: &'a mut Firmware, registration_powered: bool, @@ -533,7 +536,7 @@ def release_fixture(): } use g17::context::Context; -use g17::runtime::{Active, Entry, Firmware, Pair, Registry, RenderState, Reservation}; +use g17::runtime::{Active, Entry, Firmware, Pair, Recovery, Registry, RenderState, Reservation}; use g17::runtime::backend::{Backend, Channels, Lock as DeviceLock, Shared}; const SLOTS: usize = cfg::RENDER_SLOTS; const NEW: u64 = 5000; @@ -574,7 +577,7 @@ def release_fixture(): }); } let queues = Registry { admission, render: RenderState { entries }, teardown: g17::teardown::Pending::new().unwrap() }; - Arc::new(Shared { state: DeviceLock(Mutex::new(Some(Box::new(Firmware { queues })))), channels: Channels }) + Arc::new(Shared { state: DeviceLock(Mutex::new(Some(Box::new(Firmware { queues, recovery: Recovery })))), channels: Channels }) } fn backend(shared: &Arc, slot: usize, context: &Arc) -> Backend { Backend { closed: AtomicBool::new(false), shared: shared.clone(), context: context.clone(), owner: owner(slot) } diff --git a/tools/asahi/g17-kill-route-tests.py b/tools/asahi/g17-kill-route-tests.py index 7d01d0e878c357..0b988984525181 100644 --- a/tools/asahi/g17-kill-route-tests.py +++ b/tools/asahi/g17-kill-route-tests.py @@ -62,10 +62,11 @@ def fixture(): item(control, 'enum KillRoute {', True), item(control, 'fn kill_route('), item(control, 'fn hold_owner('), + item(control, 'fn waits_as_failed('), '#[cfg(test)]\n' + item(control, 'mod render_kill_target_tests {'), ]) firmware = '\n'.join(item(control, signature) for signature in [ - 'fn kill_route_for(', 'fn kill_releases_executed_render(', 'fn kill_waits_as_failed(', + 'fn kill_route_for(', 'fn kill_releases_render(', 'fn kill_waits_as_failed(', 'fn render_kill_candidate(', 'fn foreign_compute_running(', 'fn compute_exit_pending(', 'fn compute_failed(']) queue = '\n'.join([item(exit, signature) for signature in [ @@ -141,10 +142,15 @@ def fixture(): pub struct ComputeSlot(Option>); impl ComputeSlot { fn as_deref(&self) -> Option<&Queue> { self.0.as_deref() } } pub struct ComputeEntry { queue: ComputeSlot } -pub struct Render { executed: Vec<(Arc, u64)>, pools_released: Vec> } +pub struct Render { executed: Vec<(Arc, u64)>, guilty: Vec<(Arc, u64)>, pools_released: Vec> } +fn slots_of(pairs: &[(Arc, u64)], context: &Arc) -> u64 { + pairs.iter().filter(|(owner, _)| Arc::ptr_eq(owner, context)).fold(0, |slots, (_, slot)| slots | 1u64 << slot) +} impl Render { - fn executed_slots(&self, context: &Arc) -> u64 { - self.executed.iter().filter(|(owner, _)| Arc::ptr_eq(owner, context)).fold(0, |slots, (_, slot)| slots | 1u64 << slot) + fn executed_slots(&self, context: &Arc) -> u64 { slots_of(&self.executed, context) } + fn guilty_slots(&self, context: &Arc, _generation: u64) -> u64 { slots_of(&self.guilty, context) } + fn kill_slots(&self, context: &Arc, generation: u64) -> u64 { + self.executed_slots(context) | self.guilty_slots(context, generation) } fn teardown_pools_released(&self, context: &Arc) -> bool { self.pools_released.iter().any(|owner| Arc::ptr_eq(owner, context)) @@ -155,7 +161,9 @@ def fixture(): pub struct Init { m5: bool } impl Init { fn is_m5(&self) -> bool { self.m5 } } pub struct Queues { compute: Vec>, render: Render, teardown: Teardown } -pub struct Firmware { queues: Queues, init: Init } +pub struct Recovery; +impl Recovery { fn generation(&self) -> u64 { 1 } } +pub struct Firmware { queues: Queues, init: Init, recovery: Recovery } impl Firmware { ''' + firmware + r''' } @@ -225,10 +233,11 @@ def fixture(): Firmware { queues: Queues { compute: queues.into_iter().map(|q| Some(ComputeEntry { queue: ComputeSlot(Some(Box::new(q))) })).collect(), - render: Render { executed: Vec::new(), pools_released: Vec::new() }, + render: Render { executed: Vec::new(), guilty: Vec::new(), pools_released: Vec::new() }, teardown: Teardown { render_kills: vec![false; 4] }, }, init: Init { m5: false }, + recovery: Recovery, } } @@ -296,7 +305,7 @@ def fixture(): fw.queues.render.executed.push((c.clone(), 32)); c.killed.set(true); assert!(fw.compute_exit_pending(&c)); - assert!(!fw.kill_releases_executed_render(&c)); + assert!(!fw.kill_releases_render(&c)); assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); assert!(!fw.kill_waits_as_failed(&c)); } @@ -359,6 +368,28 @@ def fixture(): assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); } + #[test] + fn a_closed_guilty_context_is_killed_at_once_without_waiting_for_foreign_render() { + // Render-only: a pair with a spinning group and never-started groups behind it, its VM + // guilty (not executed). Another client's compute runs. + let c = context(); + let other = context(); + let mut fw = firmware(vec![running(&other)]); + fw.queues.render.guilty.push((c.clone(), 13)); + assert_eq!(fw.kill_route_for(0, &c, 0), KillRoute::Render); + assert!(fw.kill_releases_render(&c)); + assert!(fw.kill_waits_as_failed(&c)); + // Once only, and never on M5. + c.killed.set(true); + assert_eq!(fw.kill_route_for(0, &c, CLOSED), KillRoute::None); + assert!(!fw.kill_releases_render(&c)); + let c = context(); + let mut fw = firmware(vec![running(&other)]); + fw.init.m5 = true; + fw.queues.render.guilty.push((c.clone(), 13)); + assert!(!fw.kill_releases_render(&c)); + } + #[test] fn a_kill_does_not_wait_for_another_closed_contexts_owed_compute() { let (c5, c11, live) = (context(), context(), context()); @@ -399,13 +430,18 @@ def fixture(): # The route before this change: a compute exit only for failed compute or released pools. 'no-executed-route': [(' if exit_pending && (failed || pools_released || executed) {', ' if exit_pending && (failed || pools_released) {')], - 'no-executed-input': [(' self.kill_releases_executed_render(context),\n', ' false,\n')], - 'kill-twice': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0', - '!self.init.is_m5() && self.queues.render.executed_slots(context) != 0')], - 'executed-on-m5': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.executed_slots(context) != 0', - '!context.kill_published() && self.queues.render.executed_slots(context) != 0')], - 'unsafe-wait': [('self.compute_failed(context) || self.kill_releases_executed_render(context)', + 'no-executed-input': [(' self.kill_releases_render(context),\n', ' false,\n')], + 'kill-twice': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0', + '!self.init.is_m5() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0')], + 'executed-on-m5': [('!self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0', + '!context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0')], + 'unsafe-wait': [('waits_as_failed(self.compute_failed(context), self.kill_releases_render(context))', 'self.compute_failed(context)')], + # A guilty pair waits for the retirement delay like an executed one, or is not a candidate. + 'guilty-waits-delay': [('(guilty || (executed && age >= RENDER_KILL_DELAY_NS))', + '((guilty || executed) && age >= RENDER_KILL_DELAY_NS)')], + 'no-guilty-input': [(' self.queues.render.guilty_slots(context, self.recovery.generation()) != 0,\n', + ' false,\n')], 'owed-blocks-kill': [('queue.running_commands() && !queue.context()', 'queue.in_flight() && !queue.context()')], 'open-owed-skipped': [('self.in_flight() && !self.holds_only_owed_stamp()', 'self.in_flight() && !self.active.iter().all(|active| active.stamps_owed)')], diff --git a/tools/asahi/g17-owner-release-order-tests.py b/tools/asahi/g17-owner-release-order-tests.py index 517eda49370d43..1f6a1fc11587d8 100755 --- a/tools/asahi/g17-owner-release-order-tests.py +++ b/tools/asahi/g17-owner-release-order-tests.py @@ -106,6 +106,7 @@ def fixture(): # teardown_idle() is idle_for() without the release-time kill exception. idle = '\n'.join(item(render_teardown, name) for name in [ 'pub(in crate::g17::runtime) fn teardown_idle(', 'fn idle_for(']).replace('pub(in crate::g17::runtime) ', '') + counts_idle = item(render_teardown, 'fn counts_idle(') compute_switch = item((ROOT / 'queue/compute.rs').read_text(), 'pub(crate) fn switching_from(').replace('pub(crate) ', '') compute_idle = item((ROOT / 'runtime/teardown.rs').read_text(), 'fn compute_idle(') @@ -118,8 +119,8 @@ def fixture(): impl Context { fn scheduler_va(&self) -> u64 { self.scheduler } fn is_published(&self) -> bool { self.published } - // Reached only for a release-time check, which this fixture does not make. - fn kill_published(&self) -> bool { unreachable!() } + // This ordering fixture publishes no kill. + fn kill_published(&self) -> bool { false } } #[derive(Clone, Copy, PartialEq, Eq)] enum Phase { Deferred, Draining, Released(u32) } @@ -138,6 +139,9 @@ def fixture(): impl Pair { // This ordering fixture models no faulted/executed unstamped pair. fn executed_for_kill(&self, _: &Arc) -> bool { false } + // Nor a guilty pair of a killed context. + fn guilty_for_kill(&self, _: &Arc, _: u64) -> bool { false } + fn guilty_released(&self) -> bool { false } SWITCH /// Host stand-in for a successful publication of `ordinal` (stand-in, not production). fn publish(&mut self, packet: &Packet, ordinal: u64) { @@ -157,6 +161,7 @@ def fixture(): impl RenderState { IDLE } +COUNTS_FN struct Previous { context: Arc, publication: Option<(u64, u64)> } struct Queue { previous: Option, bound: Option> } impl Queue { @@ -206,23 +211,23 @@ def fixture(): let mut render = RenderState { entries: vec![Some(RenderEntry { context: Some(c.clone()), preparing: None, growing: false, pair: Some(Box::new(pair)), borrowed_switch: None, })] }; - assert!(!render.teardown_idle(&d).unwrap(), "release waits for the new owner's first command"); - assert!(render.teardown_idle(&b).unwrap(), "unrelated releases are not held"); + assert!(!render.teardown_idle(&d, 0).unwrap(), "release waits for the new owner's first command"); + assert!(render.teardown_idle(&b, 0).unwrap(), "unrelated releases are not held"); // A borrowed pair is judged by its snapshot; a stale snapshot outside a borrow is ignored. let borrowed = render.entries[0].as_mut().unwrap(); let pair = borrowed.pair.take().unwrap(); borrowed.borrowed_switch = pair.switch_in_flight(); borrowed.preparing = Some(()); - assert!(!render.teardown_idle(&d).unwrap(), "a borrowed switching pair still holds the release"); + assert!(!render.teardown_idle(&d, 0).unwrap(), "a borrowed switching pair still holds the release"); let entry = render.entries[0].as_mut().unwrap(); entry.preparing = None; entry.pair = Some(pair); entry.pair.as_mut().unwrap().active.clear(); - assert!(render.teardown_idle(&d).unwrap(), "retirement of the first command releases the hold"); + assert!(render.teardown_idle(&d, 0).unwrap(), "retirement of the first command releases the hold"); let entry = render.entries[0].as_mut().unwrap(); entry.pair.as_mut().unwrap().active.push(Active { ticket: Ticket { ordinal: 1 } }); entry.pair = None; - assert!(render.teardown_idle(&d).unwrap(), "a stale snapshot without a borrow holds nothing"); + assert!(render.teardown_idle(&d, 0).unwrap(), "a stale snapshot without a borrow holds nothing"); // Compute: only a published first command after the change holds the release. let mut service = Service { compute: vec![Some(ComputeEntry { queue: Some(Box::new(Queue { @@ -237,7 +242,7 @@ def fixture(): println!("PASS release table gate, pair switch hold, borrowed snapshot and compute switch hold"); } '''.replace('PENDING', pending).replace('SWITCH', switch_methods, 1).replace('RECORD', record) \ - .replace('IDLE', idle, 1).replace('COMPUTE_SWITCH', compute_switch).replace('COMPUTE_IDLE', compute_idle) + .replace('IDLE', idle, 1).replace('COMPUTE_SWITCH', compute_switch).replace('COMPUTE_IDLE', compute_idle).replace('COUNTS_FN', counts_idle) def main(): diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 53204a179edd66..24d5776170d888 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -103,6 +103,7 @@ def fixture(): #![allow(dead_code, unused_macros, unused_imports, unused_variables, unused_mut)] use std::collections::VecDeque; use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering, Ordering::SeqCst}}; +macro_rules! pr_warn { ($($arg:tt)*) => { eprint!($($arg)*) }; } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Error(i32); @@ -222,7 +223,11 @@ def fixture(): impl Memory { fn retire(&mut self, ordinal: u64) -> Result { self.retired.push(ordinal); Ok(()) } } /// The firmware state behind `Pair::firmware_drained`: cursors done == write, free-list /// blocks returned, and stamps covering the last publication or the context's kill acknowledged. -pub trait Host { fn drained(&self) -> bool; } +pub trait Host { + fn drained(&self) -> bool; + /// No restart in progress (recovery generation, state). + fn epoch(&self) -> Result<(u64, u32)> { Ok((1, 0)) } +} pub struct FakeHost { drained: bool } impl Host for FakeHost { fn drained(&self) -> bool { self.drained } } pub struct Pair { @@ -232,9 +237,13 @@ def fixture(): memory: Memory, drain_failures: u32, drain_retry_at: u64, + guilty_released: bool, + slot: u8, } impl Pair { fn firmware_drained(&self, host: &impl Host) -> Result { Ok(host.drained()) } + // This fixture models no killed guilty context (`Pair::guilty_killed`). + fn guilty_killed(&self, _generation: u64, _state: u32) -> bool { false } fn resync(&mut self) {} // The cross-pair task-stage order is not modelled here (KUnit asahi_g17_render_cross_pair_order). fn release_task_order_if_held(&self) {} @@ -302,7 +311,8 @@ def fixture(): stamps_owed: false, failed: false, flist_completed: false, drained_result: None, }).collect(); let pair = Pair { quarantined: false, active: Ring(active), terminal: None, memory: Memory { retired: Vec::new() }, - drain_failures: 0, drain_retry_at: 0 }; + drain_failures: 0, drain_retry_at: 0, guilty_released: false, + slot: 0 }; Firmware { queues: Queues { admission: pool.clone() }, pair: Some(Box::new(pair)), host: FakeHost { drained: false } } } fn batch() -> DeferredBatch { DeferredBatch { values: Vec::new() } } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290e..ca5f183909b734 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -230,7 +230,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-compute-growth-deadline-tests.py': [([], PASS)], 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', - 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), + 'unsafe-wait', 'guilty-waits-delay', 'no-guilty-input', 'owed-blocks-kill', + 'open-owed-skipped'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From da0d4bd87810df43730a1d4f76e8e0e5fa98e2f4 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Thu, 19 Nov 2026 16:42:48 -0300 Subject: [PATCH 1072/1514] drm/asahi: g17: log the restart table of each GPU recovery in one line Whether a recovery fails a VM and whether the restart counts toward the storm limit depend on the firmware's restart table: which queues it lists, with which stamps, which records it flags guilty or cancelled, and which of them the host finds by exact stamp. None of that was logged, so the 2026-11-19 19:12 UTC storm could not tell why the restarts that blamed the already failed deqp-vk queue still counted: its commands were missing from the tables, or the firmware flagged another live VM guilty. Print one line per recovery, in the recovery service right after the firmware resumes from the records already copied while it was halted: the record count and the first 24 records as qid:stamp:flags/match (E exact stamp, O oldest published work, - not found, ? M5), then a count of the rest. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/recovery.rs | 78 +++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 9b1379c58d9b64..0c5f8e9a25d98c 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -49,6 +49,48 @@ pub(super) struct Entries { exact_qids: u128, /// QIDs with a valid record. queues: u128, + /// The first records, for the recovery's log line. + shown: Shown, +} + +/// Records of a recovery table shown in its one log line. +const SHOWN: usize = 24; + +/// The first [`SHOWN`] valid records of a recovery table as `q::/`, +/// the match being how the host found the command (`E` by exact stamp, `O` as the oldest +/// published work, `-` not found, `?` not matched on M5): which queues the restart listed, and +/// whether the firmware flagged them guilty, decide what the recovery fails and whether a +/// restart storm counts it. +#[derive(Default)] +struct Shown { + records: [(u32, u32, u8); SHOWN], + count: usize, + more: usize, +} + +impl Shown { + fn push(&mut self, flags: u32, stamp: u32, matched: u8) { + match self.records.get_mut(self.count) { + Some(record) => { + *record = (flags, stamp, matched); + self.count += 1; + } + None => self.more += 1, + } + } +} + +impl kernel::fmt::Display for Shown { + fn fmt(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { + for (index, &(flags, stamp, matched)) in self.records[..self.count].iter().enumerate() { + let sep = if index == 0 { "" } else { " " }; + write!(f, "{}q{}:{:#x}:{:#x}/{}", sep, (flags >> 4) & 0x7f, stamp, flags, matched as char)?; + } + if self.more != 0 { + write!(f, " +{}", self.more)?; + } + Ok(()) + } } impl Entries { @@ -319,6 +361,8 @@ pub(super) fn service( let entries = read_entries(host); host.note_kill_sightings(host.recovery().accepted.wrapping_sub(1)); host.transition(3, 0)?; + // The records are copied: log them once the firmware runs again. + pr_warn!("G17: recovery gen {} table: {} records [{}]\n", request.generation, entries.listed, entries.shown); if host.recovery_state()? != 0 { return Err(EIO); } @@ -418,17 +462,23 @@ fn read_entries(host: &mut H) -> Entries { break; } if m5 { + entries.shown.push(flags, stamp, b'?'); continue; } let qid = ((flags >> 4) & 0x7f) as u8; - match host.note_interrupted(qid, stamp) { + let matched = match host.note_interrupted(qid, stamp) { Interrupted::Exact => { entries.exact += 1; entries.exact_qids |= 1u128 << qid; + b'E' } - Interrupted::Oldest => entries.fallback += 1, - Interrupted::None => {} - } + Interrupted::Oldest => { + entries.fallback += 1; + b'O' + } + Interrupted::None => b'-', + }; + entries.shown.push(flags, stamp, matched); } entries } @@ -525,6 +575,26 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } +#[kernel::macros::kunit_tests(asahi_g17_recovery_table_line)] +mod table_line_tests { + use super::{Shown, SHOWN}; + use kernel::{prelude::*, str::CString}; + + #[test] + fn the_table_line_shows_queue_stamp_flags_and_match_then_a_count() { + let mut shown = Shown::default(); + shown.push(1 | 2 | (41 << 4), 0x167a_1c00, b'E'); + shown.push(1 | (42 << 4), 0x7_9300, b'-'); + let line = CString::try_from_fmt(fmt!("{}", shown)).unwrap(); + assert_eq!(line.to_bytes(), b"q41:0x167a1c00:0x293/E q42:0x79300:0x2a1/-"); + for _ in 0..SHOWN { + shown.push(1, 0, b'O'); + } + let line = CString::try_from_fmt(fmt!("{}", shown)).unwrap(); + assert!(line.to_bytes().ends_with(b" +2")); + } +} + #[kernel::macros::kunit_tests(asahi_g17_recovery_snapshot)] mod tests { use super::*; From dc4b3cf9ce013e23fa286e1eb0f5e3837dd974e8 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 00:03:49 -0300 Subject: [PATCH 1073/1514] drm/asahi: g17: close a guilty failed VM's queue for a client that keeps it open A guilty context is killed only once its queue closed: Pair::guilty_unretired needs a closed owner, and the kill machinery serves the teardown entry a close creates. A client that keeps the queue open after its lost device (a process that ignores VK_ERROR_DEVICE_LOST, or waits in an error dialog) leaves its guilty work published. Each restart reaches the group that hung and it hangs again about every 83 ms. Then the restart storm limit, or the recovery table's contents, decide whether the GPU stops for every client, and each forgiven restart still drops other clients' running work. Nothing of such a VM can run again. A recovery that finds it guilty records the failure in its status, and every later submission, install and publication checks that status. So close the queue on its client's behalf, as the client's own close (release_queue) would: the teardown entry, the compute and render owner releases, the render holds and the admission release. The kill, the release of its groups after a later restart, and the park or keep at detach then follow the path an exited client takes. A line logs each such close with the recovery generation. Only the first close of a context counts (Context::note_closed): the client's own close later finds the queue closed and leaves the firmware side alone, since its teardown entry may be released and reclaimed by then and a second one would release the scheduler twice. The kill gate keeps its restart since the close, now the kernel's close. A close counts only once its teardown entry is reserved, the one step of it that allocates: a close that fails there leaves the context open, and the next close redoes all of it. The kernel's close logs such a failure and retries at the next service pass; the other failed owners of that pass are still closed. An error after that, once the context counts as closed, fails the event service and with it the device, as the client's own close does: no later close would release the owner's compute slot and admission. For the same reason admission gives no lease to an owner whose pairs are released (State::owner_released, in acquire_render and try_acquire_render), under the lock release_owner takes. The client of a kernel-closed queue may still publish early (try_render_early, which checks no VM status) once its drained pair left quarantine: taking that pair back, or claiming a sibling, would clear its released bit for good. Owner IDs are never reused, so a released owner is closed for good. admits_render does not check it, so the scheduler's prepare step does not wait for such a job; its publication fails it at once. The client's queue still holds the context, so its scheduler release, and with it the context's reclaim and the pair's detach, waits for the client's own close (Context::held_by_open_client). The guilty groups go on the kill before that; until the close the killed pair stays held. Only VMs that a recovery found guilty and whose status recorded a failure, with an open owner, no builder and no owner switch on the slot. Only render slots are scanned, so a compute-only queue of such a VM stays open until its client closes it. Not on M5. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context.rs | 51 +++++++-- drivers/gpu/drm/asahi/g17/queue/admission.rs | 36 ++++++- drivers/gpu/drm/asahi/g17/queue/render.rs | 9 +- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 38 ++++--- .../gpu/drm/asahi/g17/runtime/compute_exit.rs | 46 ++++++++ .../gpu/drm/asahi/g17/runtime/render/exit.rs | 10 ++ drivers/gpu/drm/asahi/g17/teardown.rs | 4 + tools/asahi/g17-admission-deadline-tests.py | 1 + tools/asahi/g17-admission-order-tests.py | 68 ++++++++++-- tools/asahi/g17-kill-route-tests.py | 101 ++++++++++++++++-- tools/asahi/run-host-tests.py | 6 +- 11 files changed, 325 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 97161d5c51ea13..33373fafff593e 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -217,9 +217,12 @@ pub(crate) struct Context { /// The host's recovery generation when it first saw the kill of this context done (its /// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]). kill_seen: AtomicU64, - /// The host's recovery generation at this context's latest close, `u64::MAX` while open - /// ([`Self::restarted_since_close`]). + /// The host's recovery generation at this context's first close, `u64::MAX` while open + /// ([`Self::note_closed`], [`Self::restarted_since_close`]). closed_generation: AtomicU64, + /// The kernel closed this context's queue on its client's behalf + /// (`Firmware::close_failed_owners`) and the client has not closed it yet. + closed_for_open_client: AtomicBool, /// Advisory only: publication still checks the physical binding under the /// device mutex. False skips an inline attempt known to need admission. compute_binding_hint: AtomicBool, @@ -354,6 +357,7 @@ impl Context { kill_published: AtomicBool::new(false), kill_seen: AtomicU64::new(u64::MAX), closed_generation: AtomicU64::new(u64::MAX), + closed_for_open_client: AtomicBool::new(false), compute_binding_hint: AtomicBool::new(false), render_seen: AtomicBool::new(false), qos, @@ -543,13 +547,32 @@ impl Context { self.kill_published.load(Ordering::Acquire) } - /// A queue of this context closed at the host's recovery `generation` (under the device - /// mutex). The latest close counts. + /// This context's queue closed at the host's recovery `generation`, under the device mutex: + /// by its client (`release_queue`), or on its behalf once a GPU recovery failed its VM as + /// guilty (`Firmware::close_failed_owners`). Only the first close counts. A close notes it + /// only after its teardown entry is reserved, so a close that failed there can be redone. pub(crate) fn note_closed(&self, generation: u64) { - self.closed_generation.store(generation, Ordering::Release); + close_once(&self.closed_generation, generation); } - /// The host accepted a GPU restart (`generation`) after this context's latest close. + /// This context's queue closed already ([`Self::note_closed`]). Under the device mutex. + pub(crate) fn is_closed(&self) -> bool { + self.closed_generation.load(Ordering::Acquire) != u64::MAX + } + + /// The kernel closed this context's queue for its still open client (`true`), or the client + /// closed it (`false`, `release_queue`). Under the device mutex. + pub(crate) fn note_open_client(&self, open: bool) { + self.closed_for_open_client.store(open, Ordering::Release); + } + + /// See [`Self::note_open_client`]: until the client closes its queue, that queue still holds + /// this context, so its scheduler is not released and the context not reclaimed. + pub(crate) fn held_by_open_client(&self) -> bool { + self.closed_for_open_client.load(Ordering::Acquire) + } + + /// The host accepted a GPU restart (`generation`) after this context's first close. pub(crate) fn restarted_since_close(&self, generation: u64) -> bool { restarted_after(self.closed_generation.load(Ordering::Acquire), generation) } @@ -865,6 +888,11 @@ fn restarted_after(at: u64, generation: u64) -> bool { at != u64::MAX && generation > at } +/// Records the recovery `generation` of a context's first close in `at`; true for that close. +fn close_once(at: &AtomicU64, generation: u64) -> bool { + at.compare_exchange(u64::MAX, generation, Ordering::AcqRel, Ordering::Acquire).is_ok() +} + /// Records in `seen` the recovery `generation` of the first call that sees a kill done /// (`killed`), and reports whether a later generation was accepted since. A restart accepted /// after that sighting was raised after the firmware had finished the kill, so it dropped @@ -900,6 +928,17 @@ mod capacity_tests { assert_eq!(seen.load(Ordering::Relaxed), 4); } + #[test] + fn only_the_first_close_counts() { + let at = AtomicU64::new(u64::MAX); + // Closed on its client's behalf at generation 5, then by the client at 9. + assert!(close_once(&at, 5)); + assert!(!close_once(&at, 9)); + assert_eq!(at.load(Ordering::Relaxed), 5); + // So the restart at 6 still counts for its kill. + assert!(restarted_after(at.load(Ordering::Relaxed), 6)); + } + #[test] fn only_a_restart_after_the_close_counts() { assert!(!restarted_after(u64::MAX, u64::MAX - 1)); diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index c1caf8470beb66..ae58c8b9bf5591 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -132,6 +132,13 @@ impl State { let quarantined = self.quarantined & owned; (quarantined != 0).then_some(quarantined & !self.spared == 0) } + /// Released means closed: by its client, or by the kernel for a client that keeps it open + /// (`Firmware::close_failed_owners`), which then never releases it again. A pair taken + /// back, or a sibling claimed, would clear `released` and leak. Owner IDs are never reused. + /// Checked where a lease is made only, so `admits_render` lets such a job fail at once. + fn owner_released(&self, owner: u64) -> bool { + (0..cfg::RENDER_SLOTS).any(|slot| self.owners[slot] == owner && self.released & (1u64 << slot) != 0) + } fn refusal(&self, owner: u64) -> Result { if self.exhausted() { return Err(EIO); @@ -676,6 +683,9 @@ impl Pool { } continue; } + if state.owner_released(owner) { + return Err(ECANCELED); + } state.refusal(owner)?; expired |= now >= conflict_deadline; let plan = if expired { @@ -733,7 +743,7 @@ impl Pool { return Ok(None); } let mut state = self.state.lock(); - if state.refusal(owner).is_err() || !state.owners.contains(&owner) { + if state.owner_released(owner) || state.refusal(owner).is_err() || !state.owners.contains(&owner) { return Ok(None); } let plan = state.plan(owner, request, None); @@ -1310,6 +1320,30 @@ mod fault_capacity_tests { assert_eq!(state.quarantined | state.spared, 0); } + #[test] + fn a_released_owner_takes_no_pair_again() { + // The kernel closed a guilty owner for its open client, and its pair drained: an + // early publication that passed the status check before the failure asks again. + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + let queue = pool.reserve_queue().unwrap(); + let lease = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let slot = lease.slot(); + drop(lease); + pool.release_owner(1); + assert!(pool.try_acquire_render(1, 2, None).unwrap().is_none()); + assert!(matches!(pool.acquire_render(1, 2, None, u64::MAX, || Ok(())), Err(ECANCELED))); + // The scheduler's prepare step does not wait for it: publication fails the job at once. + assert!(pool.admits_render(1, None)); + let state = pool.state.lock(); + // Its pair stays released, and it claims no sibling. + assert_ne!(state.released & (1u64 << slot), 0); + assert_eq!(state.owners.iter().filter(|id| **id == 1).count(), 1); + drop(state); + // Another owner takes the pair. + assert_eq!(pool.acquire_render(2, 1, None, u64::MAX, || Ok(())).unwrap().slot(), slot); + drop(queue); + } + #[test] fn closed_faulting_clients_return_leases_after_drain() { let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 07614e55551c64..e1e317469dd7d9 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -2691,13 +2691,20 @@ impl Pair { Arc::ptr_eq(context, &self.memory.context) && self.guilty_unretired(generation) } + /// A GPU recovery failed the pair's VM as guilty (its status records the failure, so every + /// later submission and publication of it is refused) and quarantined the pair. Not on M5. + pub(crate) fn failed_guilty(&self) -> bool { + let status = self.memory.context.status(); + !self.memory.graph.is_m5() && self.quarantined && status.recovery_guilty() && status.get() != 0 + } + /// A closed owner's quarantined pair holding published work of a VM that a GPU recovery /// found guilty. Its started group hangs the GPU again after every restart, with its queued /// groups behind it, so its work never retires like other work: on 25G83 the host cannot /// take published groups back, and only a kill of the context unlinks them. Left alone, /// the restarts reach the storm limit and every client loses the device (11-19 19:12 UTC). /// - /// Only once the host accepted a restart (`generation`) since the context's latest close: + /// Only once the host accepted a restart (`generation`) since the context's first close: /// the VM stays guilty, and a failed VM's pairs are all quarantined, but its groups queued /// behind the one that hung may run and retire on their stamps. A kill then would unlink /// those with nothing left to hang and so no restart to release them. A guilty group still diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index f09b3d5d5cb8ed..86aa7fef438e7d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -97,25 +97,33 @@ impl Backend { self.release_outer(Engine::Compute); self.release_outer(Engine::Render); let mut state = self.shared.state.lock(); + // The client closes its queue itself now (see `Context::held_by_open_client`). + self.context.note_open_client(false); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; // A pair of this context that holds guilty work counts for a kill only after a restart - // since this close (`Pair::guilty_for_kill`). - self.context.note_closed(firmware.recovery.generation()); - // Retain a published scheduler before a never-kicked physical graph is - // removed. The teardown entry owns its root until control consumption. - firmware - .queues - .teardown - .close(&self.context, super::now_ns())?; - firmware.queues.release_compute(self.owner)?; - firmware.queues.release_render(self.owner)?; - // The armed release holds the owner's pairs from every other owner until it is - // consumed. Hold them before admission releases the owner: admission does not take - // the device mutex, so a slot released first could be taken in between. - firmware.queues.sync_render_holds(); - firmware.queues.admission.release_owner(self.owner); + // since this close (`Pair::guilty_for_kill`). Only the first close counts: the kernel + // may have closed this queue on its client's behalf already (`Firmware::close_failed_owners`), + // and its teardown entry may be released and reclaimed since. Closing it again would + // release its scheduler twice. + if !self.context.is_closed() { + // Retain a published scheduler before a never-kicked physical graph is + // removed. The teardown entry owns its root until control consumption. + firmware + .queues + .teardown + .close(&self.context, super::now_ns())?; + // Only now: a close that could not reserve its teardown entry is redone by the next. + self.context.note_closed(firmware.recovery.generation()); + firmware.queues.release_compute(self.owner)?; + firmware.queues.release_render(self.owner)?; + // The armed release holds the owner's pairs from every other owner until it is + // consumed. Hold them before admission releases the owner: admission does not take + // the device mutex, so a slot released first could be taken in between. + firmware.queues.sync_render_holds(); + firmware.queues.admission.release_owner(self.owner); + } drop(state); // Its idle channel, or its slot and never-published QID, is free. self.shared.channels.notify(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index d9dbd52fe903e4..e31832b23007d2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -210,6 +210,7 @@ impl Firmware { return Ok(()); } let now = now_ns(); + self.close_failed_owners(now)?; // Publication has already retained each kill. Retry only the doorbell; // failed attempts do not extend its bounded polling window. for entry in self.queues.compute.iter_mut().flatten() { @@ -419,6 +420,51 @@ impl Firmware { !self.init.is_m5() && !context.kill_published() && self.queues.render.kill_slots(context, self.recovery.generation()) != 0 } + /// Closes, on its client's behalf, each queue whose VM a GPU recovery failed as guilty + /// (`Pair::failed_guilty`), as its client's close (`release_queue`) would. Nothing of that + /// VM can run again: its status refuses every later submission and publication. But a client + /// that keeps the queue open after the lost device (a process that ignores it, or waits in an + /// error dialog) would keep its guilty work published, and that work hangs the GPU again after + /// every restart until the storm limit stops the GPU for every client: a guilty pair is killed + /// only once its owner closed (`Pair::guilty_unretired`). Closed here, its context takes the + /// same kill, release and detach as an exited client's. The client's own close later finds the + /// queue closed (`Context::note_closed`) and leaves the teardown entry alone; the scheduler + /// release waits for that close (`Context::held_by_open_client`). Not on M5, which + /// takes published work back through its recovery target. + fn close_failed_owners(&mut self, now: u64) -> Result { + if self.init.is_m5() { + return Ok(()); + } + let generation = self.recovery.generation(); + for slot in 0..crate::hw::t8140::queues::RENDER_SLOTS { + let Some((owner, context)) = self.queues.render.failed_open_owner(slot) else { + continue; + }; + if context.is_closed() { + continue; + } + // In the order of the client's own close (`release_queue`): the context counts as + // closed only once its teardown entry is reserved. A close that could not reserve it + // closed nothing, and the next service pass retries it. + if let Err(error) = self.queues.teardown.close(&context, now) { + pr_err!("G17: scheduler {} close for its open client failed: {:?}\n", context.id(), error); + continue; + } + context.note_closed(generation); + context.note_open_client(true); + // Closed now, so no later close releases the owner: an error from here fails the + // event service, which stops the device, as the client's own close does. + self.queues.release_compute(owner)?; + self.queues.release_render(owner)?; + // As at a client's close: hold the owner's pairs before admission releases it. + self.queues.sync_render_holds(); + self.queues.admission.release_owner(owner); + pr_warn!("G17: scheduler {} closed for its open client at recovery gen {}: a GPU recovery failed its VM as guilty\n", + context.id(), generation); + } + Ok(()) + } + /// Logs a published kill that releases guilty pairs (`Pair::guilty_for_kill`), with the /// recovery generation, so a test shows whether the next restart dropped their work. fn note_guilty_kill(&self, context: &Arc, hold: u64, route: &str) { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs index ef8d40bb9a5704..44231b6cec772f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/exit.rs @@ -42,6 +42,16 @@ impl RenderState { self.slots_where(|pair| pair.releasable_by_kill(context, generation)) } + /// The owner and context of `slot`'s pair while that owner is still open, its VM failed as + /// guilty (`Pair::failed_guilty`), and no builder or owner switch holds the slot. + pub(in crate::g17::runtime) fn failed_open_owner(&self, slot: usize) -> Option<(u64, Arc)> { + let entry = self.entries.get(slot)?.as_ref()?; + let pair = entry.pair.as_deref()?; + let open = !entry.closed && entry.preparing.is_none() && entry.pending_owner.is_none(); + (open && pair.owner() == Some(entry.reservation.owner) && pair.failed_guilty()) + .then(|| (entry.reservation.owner, pair.context().clone())) + } + fn slots_where(&self, matches: impl Fn(&crate::g17::queue::render::Pair) -> bool) -> u64 { let mut slots = 0; for (slot, entry) in self.entries.iter().enumerate() { diff --git a/drivers/gpu/drm/asahi/g17/teardown.rs b/drivers/gpu/drm/asahi/g17/teardown.rs index 39208dc7b3f34b..84e36aaaeadc63 100644 --- a/drivers/gpu/drm/asahi/g17/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/teardown.rs @@ -205,7 +205,11 @@ impl Pending { } continue; } + // A queue the kernel closed for its still open client holds the context until + // the client closes it: its scheduler is released, and the context reclaimed, only + // after that. Its guilty work went with the kill already. if entry.phase != Phase::Draining + || entry.context.held_by_open_client() || !host.render_idle(&entry.context)? || !host.flists_released(&entry.context) || !host.compute_idle(&entry.context) diff --git a/tools/asahi/g17-admission-deadline-tests.py b/tools/asahi/g17-admission-deadline-tests.py index 501c903b59f8ff..c7a9593f43be2a 100644 --- a/tools/asahi/g17-admission-deadline-tests.py +++ b/tools/asahi/g17-admission-deadline-tests.py @@ -45,6 +45,7 @@ def fixture(): impl State { fn exhausted(&self)->bool {false} ''' + item(source, 'fn owner_quarantine(') + r''' + fn owner_released(&self,_:u64)->bool {false} fn refusal(&self,_:u64)->Result {Ok(())} fn plan(&self,_:u64,_:Option>,_:Option)->Plan {if self.conflict {Plan::Conflict}else{Plan::Any}} fn pick(&mut self,_:u64,_:usize,_:Plan)->Option {if self.ready{Some(1)}else{None}} diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index c9baee2e000c84..d8e17a00496b8d 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -160,8 +160,8 @@ def held_fixture(): at = pairs.index('const SIBLING_BACKLOG') backlog = pairs[at:pairs.index('\n}\n', pairs.index('fn sibling_backlog', at)) + 3] state = '\n'.join(item(source, name) for name in [ - 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn refusal(', 'fn advance(', - 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', + 'const fn new(', 'fn exhausted(', 'fn owner_quarantine(', 'fn owner_released(', 'fn refusal(', + 'fn advance(', 'fn take_idle(', 'fn acquire(', 'fn claim_sibling(', 'fn reassign_unused_spare(', 'fn cancel_empty_slot(', 'fn can_pick(', 'fn pick(', 'fn usable(', 'fn join(', 'fn release(', 'fn set_held(', 'fn retained(', 'fn used(']) pool = '\n'.join(item(source, name) for name in [ @@ -273,6 +273,11 @@ def held_fixture(): assert_eq!(state.acquire(8, 1), Some(13)); assert_eq!(state.refusal(9), Err(ENOSPC)); assert_eq!(state.acquire(9, 1), None, "a closed owner's held pair goes to no other owner"); + // The closed owner itself is refused too: the kernel may have closed it for a client whose + // early publication still asks (`try_render_early`). Retaking its idle pair would clear + // `released`, and nothing would release it again. + assert!(state.owner_released(7), "a released owner takes no pair back"); + assert!(!state.owner_released(8), "an owner that took a released pair is not closed"); } fn holds_and_stop() { @@ -318,6 +323,8 @@ def held_fixture(): 'no-held-wake': ('if cleared {\n self.returned();', 'if false {\n self.returned();'), 'wake-on-every-clear': ('was && !held', '!held'), 'no-held-stop': ('state.held = 0;', ''), + 'released-owner-retakes': ('.any(|slot| self.owners[slot] == owner && self.released & (1u64 << slot) != 0)', + '.any(|_| false)'), 'held-blocks-owner': ('&& (self.quarantined | self.kill_hold) & (1u64 << slot) == 0\n && self.refs[slot] < cfg::RENDER_DEPTH', '&& (self.quarantined | self.kill_hold | self.held) & (1u64 << slot) == 0\n && self.refs[slot] < cfg::RENDER_DEPTH'), } @@ -375,16 +382,25 @@ def release_fixture(): const EIO: i32 = -5; const EBUSY: i32 = -16; const EINVAL: i32 = -22; +const ENOMEM: i32 = -12; #[derive(Clone, Copy)] struct Flags; const GFP_KERNEL: Flags = Flags; +/// The next `KVec::push` fails as an allocation would. +static FAIL_PUSH: AtomicBool = AtomicBool::new(false); /// The kernel vector's fallible push and remove. #[derive(Clone)] struct KVec(Vec); impl KVec { const fn new() -> Self { KVec(Vec::new()) } fn with_capacity(capacity: usize, _: Flags) -> Result { Ok(KVec(Vec::with_capacity(capacity))) } - fn push(&mut self, value: T, _: Flags) -> Result { self.0.push(value); Ok(()) } + fn push(&mut self, value: T, _: Flags) -> Result { + if FAIL_PUSH.swap(false, SeqCst) { + return Err(ENOMEM); + } + self.0.push(value); + Ok(()) + } fn remove(&mut self, index: usize) -> std::result::Result { if index < self.0.len() { Ok(self.0.remove(index)) } else { Err(()) } } @@ -403,11 +419,15 @@ def release_fixture(): """ + backlog + r""" } pub mod context { - pub struct Context { pub published: bool, pub scheduler: u64 } + pub struct Context { pub published: bool, pub scheduler: u64, pub closed: std::sync::atomic::AtomicBool } impl Context { pub fn is_published(&self) -> bool { self.published } pub fn scheduler_va(&self) -> u64 { self.scheduler } - pub fn note_closed(&self, _generation: u64) {} + pub fn note_closed(&self, _generation: u64) { + self.closed.store(true, std::sync::atomic::Ordering::Release); + } + pub fn is_closed(&self) -> bool { self.closed.load(std::sync::atomic::Ordering::Acquire) } + pub fn note_open_client(&self, _open: bool) {} } } pub mod teardown { @@ -542,7 +562,9 @@ def release_fixture(): const NEW: u64 = 5000; fn bit(slot: usize) -> u64 { 1u64 << slot } fn owner(slot: usize) -> u64 { 1000 + slot as u64 } -fn context(scheduler: u64) -> Arc { Arc::new(Context { published: true, scheduler }) } +fn context(scheduler: u64) -> Arc { + Arc::new(Context { published: true, scheduler, closed: std::sync::atomic::AtomicBool::new(false) }) +} /// Every slot is retained by an open owner and no new graph fits; `pairs` are installed. fn device(pairs: &[(usize, &Arc)]) -> Arc { let mut state = State::new(); @@ -688,6 +710,12 @@ def release_fixture(): assert_eq!(state.held & bit(31), 0, "a consumed release returns its parked pair's slot"); assert!(wakes(&shared) > before, "and wakes the publications waiting for render capacity"); assert_eq!(state.clone().acquire(NEW, 1), Some(31), "a new owner takes the parked pair, not the one whose release is pending"); + // A queue the kernel closed for its client (`Firmware::close_failed_owners`) is closed by that + // client later: its released scheduler gets no second teardown entry, its slot no new hold. + backend(&shared, 31, &healthy).release_queue().unwrap(); + with(&shared, |firmware| assert!(!firmware.queues.teardown.releasing(&healthy), + "a second close of a released context arms no second scheduler release")); + assert_eq!(admission(&shared).held & bit(31), 0, "and holds its parked pair's slot no more"); assert_ne!(state.held & bit(30), 0); // Once the stuck release is consumed too, its slot returns, as the older one. consume(&shared, &stuck, 9); @@ -699,6 +727,22 @@ def release_fixture(): assert!(!raced.iter().take(2).any(|got| *got == Some(30))); } +/// A close that cannot reserve its teardown entry does not count as the first close: the +/// next close (the client's, or `Firmware::close_failed_owners` again) does all of it. +fn failed_close_is_redone() { + let failed = context(0x14); + let shared = device(&[(14, &failed)]); + FAIL_PUSH.store(true, SeqCst); + assert_eq!(backend(&shared, 14, &failed).release_queue(), Err(ENOMEM)); + assert!(!failed.is_closed(), "a close that failed to reserve its teardown entry is not noted"); + assert_eq!(admission(&shared).released & bit(14), 0, "and releases nothing"); + backend(&shared, 14, &failed).release_queue().unwrap(); + assert!(failed.is_closed()); + with(&shared, |firmware| assert!(firmware.queues.teardown.releasing(&failed), + "the next close reserves the teardown entry")); + assert_ne!(admission(&shared).released & bit(14), 0, "and releases the owner"); +} + /// Quarantined and owed pairs are held by the same rule; a lent pair keeps its bit. fn work_and_lent_pairs() { let (open, other) = (context(0x12), context(0x20)); @@ -750,6 +794,7 @@ def release_fixture(): fn main() { closed_owner_release(); + failed_close_is_redone(); work_and_lent_pairs(); println!("PASS release holds: a closed owner's idle pair is held from its close, before admission releases its slot, through retirement passes and resyncs, until its scheduler release is consumed and the pair parked; no new owner is given it meanwhile; quarantined and owed pairs are held by the same rule and their own owner keeps them; a lent pair keeps its bit and is held when its owner closes meanwhile; a missing or parked pair is never held"); } @@ -760,10 +805,15 @@ def release_fixture(): RELEASE_MUTATIONS = { 'hold-ignores-release': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'pair.unreusable_work()'), 'hold-ignores-work': ('pair.unreusable_work() || teardown.releasing(pair.context())', 'teardown.releasing(pair.context())'), - 'close-unheld': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', + 'close-unheld': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', 'firmware.queues.admission.release_owner(self.owner);'), - 'hold-after-release': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', - 'firmware.queues.admission.release_owner(self.owner);\n firmware.queues.sync_render_holds();'), + # The client's close after the kernel's repeats the firmware side. + 'close-twice': ('if !self.context.is_closed() {', 'if true {'), + # A close that fails to reserve its teardown entry still counts as the first. + 'latch-before-close': ('if !self.context.is_closed() {', + 'if !self.context.is_closed() && { self.context.note_closed(firmware.recovery.generation()); true } {'), + 'hold-after-release': ('firmware.queues.sync_render_holds();\n firmware.queues.admission.release_owner(self.owner);', + 'firmware.queues.admission.release_owner(self.owner);\n firmware.queues.sync_render_holds();'), 'put-back-own-work': ('self.queues.hold_render_slot(slot);\n result', 'let held = self.queues.render.entries[slot].as_ref().and_then(|entry| entry.pair.as_ref())' '.is_some_and(|pair| pair.unreusable_work());\n self.queues.admission.set_held(slot, held);\n result'), diff --git a/tools/asahi/g17-kill-route-tests.py b/tools/asahi/g17-kill-route-tests.py index 0b988984525181..36e3016d75ac35 100644 --- a/tools/asahi/g17-kill-route-tests.py +++ b/tools/asahi/g17-kill-route-tests.py @@ -68,7 +68,7 @@ def fixture(): firmware = '\n'.join(item(control, signature) for signature in [ 'fn kill_route_for(', 'fn kill_releases_render(', 'fn kill_waits_as_failed(', 'fn render_kill_candidate(', 'fn foreign_compute_running(', 'fn compute_exit_pending(', - 'fn compute_failed(']) + 'fn compute_failed(', 'fn close_failed_owners(']) queue = '\n'.join([item(exit, signature) for signature in [ 'fn active_traversal(', 'pub(crate) fn exit_candidate(', 'fn holds_only_owed_stamp(', 'pub(crate) fn running_commands(', 'pub(crate) fn timed_out(', 'pub(crate) fn exit_published(']] @@ -85,6 +85,12 @@ def fixture(): pub struct Error(i32); pub const ETIMEDOUT: Error = Error(-110); pub const ECANCELED: Error = Error(-125); +pub const EIO: Error = Error(-5); +pub const ENOMEM: Error = Error(-12); +pub type Result = std::result::Result; +macro_rules! pr_err { ($($t:tt)*) => {} } +macro_rules! pr_warn { ($($t:tt)*) => {} } +mod hw { pub mod t8140 { pub mod queues { pub const RENDER_SLOTS: usize = 4; } } } const LIVENESS_NS: u64 = 5_000_000_000; const MS: u64 = 1_000_000; @@ -102,8 +108,14 @@ def fixture(): } } -pub struct Context { killed: Cell } -impl Context { fn kill_published(&self) -> bool { self.killed.get() } } +pub struct Context { killed: Cell, closed: Cell, open_client: Cell } +impl Context { + fn kill_published(&self) -> bool { self.killed.get() } + fn id(&self) -> u32 { 0 } + fn is_closed(&self) -> bool { self.closed.get() } + fn note_closed(&self, _generation: u64) { self.closed.set(true); } + fn note_open_client(&self, open: bool) { self.open_client.set(open); } +} pub struct Packet { command: g17::command::Validated, context: Arc } pub struct Active { packet: Arc, stamps_owed: bool } @@ -142,7 +154,13 @@ def fixture(): pub struct ComputeSlot(Option>); impl ComputeSlot { fn as_deref(&self) -> Option<&Queue> { self.0.as_deref() } } pub struct ComputeEntry { queue: ComputeSlot } -pub struct Render { executed: Vec<(Arc, u64)>, guilty: Vec<(Arc, u64)>, pools_released: Vec> } +pub struct Render { + executed: Vec<(Arc, u64)>, + guilty: Vec<(Arc, u64)>, + pools_released: Vec>, + /// (slot, owner, context) of each open owner whose VM a recovery failed as guilty. + failed: Vec<(usize, u64, Arc)>, +} fn slots_of(pairs: &[(Arc, u64)], context: &Arc) -> u64 { pairs.iter().filter(|(owner, _)| Arc::ptr_eq(owner, context)).fold(0, |slots, (_, slot)| slots | 1u64 << slot) } @@ -155,12 +173,33 @@ def fixture(): fn teardown_pools_released(&self, context: &Arc) -> bool { self.pools_released.iter().any(|owner| Arc::ptr_eq(owner, context)) } + fn failed_open_owner(&self, slot: usize) -> Option<(u64, Arc)> { + self.failed.iter().find(|(at, ..)| *at == slot).map(|(_, owner, context)| (*owner, context.clone())) + } } -pub struct Teardown { render_kills: Vec } -impl Teardown { fn render_kill_published(&self, index: usize) -> bool { self.render_kills[index] } } +/// `fail_close`: the next teardown entry cannot be allocated. +pub struct Teardown { render_kills: Vec, fail_close: bool, entries: usize } +impl Teardown { + fn render_kill_published(&self, index: usize) -> bool { self.render_kills[index] } + fn close(&mut self, _context: &Arc, _now: u64) -> Result { + if std::mem::take(&mut self.fail_close) { + return Err(ENOMEM); + } + self.entries += 1; + Ok(()) + } +} +pub struct Admission { released: Vec } +impl Admission { fn release_owner(&mut self, owner: u64) { self.released.push(owner); } } pub struct Init { m5: bool } impl Init { fn is_m5(&self) -> bool { self.m5 } } -pub struct Queues { compute: Vec>, render: Render, teardown: Teardown } +/// `release_error`: what releasing the owner's compute queue returns. +pub struct Queues { compute: Vec>, render: Render, teardown: Teardown, admission: Admission, release_error: Option } +impl Queues { + fn release_compute(&mut self, _owner: u64) -> Result { self.release_error.map_or(Ok(()), Err) } + fn release_render(&mut self, _owner: u64) -> Result { Ok(()) } + fn sync_render_holds(&mut self) {} +} pub struct Recovery; impl Recovery { fn generation(&self) -> u64 { 1 } } pub struct Firmware { queues: Queues, init: Init, recovery: Recovery } @@ -173,7 +212,9 @@ def fixture(): mod tests { use super::*; - fn context() -> Arc { Arc::new(Context { killed: Cell::new(false) }) } + fn context() -> Arc { + Arc::new(Context { killed: Cell::new(false), closed: Cell::new(false), open_client: Cell::new(false) }) + } /// A queue bound to `context`, its owner open, holding no command. fn queue(context: &Arc) -> Queue { @@ -233,8 +274,10 @@ def fixture(): Firmware { queues: Queues { compute: queues.into_iter().map(|q| Some(ComputeEntry { queue: ComputeSlot(Some(Box::new(q))) })).collect(), - render: Render { executed: Vec::new(), guilty: Vec::new(), pools_released: Vec::new() }, - teardown: Teardown { render_kills: vec![false; 4] }, + render: Render { executed: Vec::new(), guilty: Vec::new(), pools_released: Vec::new(), failed: Vec::new() }, + teardown: Teardown { render_kills: vec![false; 4], fail_close: false, entries: 0 }, + admission: Admission { released: Vec::new() }, + release_error: None, }, init: Init { m5: false }, recovery: Recovery, @@ -390,6 +433,38 @@ def fixture(): assert!(!fw.kill_releases_render(&c)); } + #[test] + fn a_failed_owner_close_is_retried_before_its_latch_and_fails_the_pass_after() { + // The first owner's teardown entry cannot be allocated: it stays open for the next pass, + // and the other failed owner is still closed in this one. + let (a, b) = (context(), context()); + let mut fw = firmware(vec![]); + fw.queues.render.failed = vec![(0, 100, a.clone()), (1, 101, b.clone())]; + fw.queues.teardown.fail_close = true; + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert!(!a.is_closed() && !a.open_client.get()); + assert!(b.is_closed() && b.open_client.get()); + assert_eq!(fw.queues.admission.released, [101]); + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert!(a.is_closed()); + assert_eq!((fw.queues.teardown.entries, &fw.queues.admission.released[..]), (2, &[101, 100][..])); + // Once latched, no later close releases the owner: a failed release fails the pass + // (the event service then stops the device) instead of leaking its slot and admission. + let c = context(); + let mut fw = firmware(vec![]); + fw.queues.render.failed = vec![(2, 102, c.clone())]; + fw.queues.release_error = Some(EIO); + assert_eq!(fw.close_failed_owners(0), Err(EIO)); + assert!(c.is_closed()); + assert!(fw.queues.admission.released.is_empty()); + // Never on M5. + let mut fw = firmware(vec![]); + fw.init.m5 = true; + fw.queues.render.failed = vec![(0, 103, context())]; + assert_eq!(fw.close_failed_owners(0), Ok(())); + assert_eq!(fw.queues.teardown.entries, 0); + } + #[test] fn a_kill_does_not_wait_for_another_closed_contexts_owed_compute() { let (c5, c11, live) = (context(), context(), context()); @@ -443,6 +518,12 @@ def fixture(): 'no-guilty-input': [(' self.queues.render.guilty_slots(context, self.recovery.generation()) != 0,\n', ' false,\n')], 'owed-blocks-kill': [('queue.running_commands() && !queue.context()', 'queue.in_flight() && !queue.context()')], + # A failed release after the latch is logged and skipped: its slot and admission leak. + 'post-latch-swallowed': [(' self.queues.release_compute(owner)?;\n', + ' if self.queues.release_compute(owner).is_err() { continue; }\n')], + # A failed teardown reservation aborts the pass for the other failed owners. + 'reserve-fails-pass': [(' if let Err(error) = self.queues.teardown.close(&context, now) {', + ' if let Err(error) = self.queues.teardown.close(&context, now) {\n return Err(error);')], 'open-owed-skipped': [('self.in_flight() && !self.holds_only_owed_stamp()', 'self.in_flight() && !self.active.iter().all(|active| active.stamps_owed)')], } diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ca5f183909b734..c6906e8e462d4c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -214,10 +214,10 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('no-held-free', 'no-held-sibling', 'no-held-refusal', 'no-held-pick', 'no-held-spare', 'no-held-other', 'no-held-cancel', 'no-held-killed', 'no-held-used', 'no-held-wake', 'wake-on-every-clear', 'no-held-stop', - 'held-blocks-owner', 'hold-ignores-release', 'hold-ignores-work', + 'held-blocks-owner', 'released-owner-retakes', 'hold-ignores-release', 'hold-ignores-work', 'close-unheld', 'hold-after-release', 'put-back-own-work', 'sync-skips-lent', 'lent-close-unheld', 'parked-stays-held', - 'sync-clobbers', 'sync-no-wake'), []), + 'sync-clobbers', 'sync-no-wake', 'close-twice', 'latch-before-close'), []), 'g17-capacity-backoff-tests.py': [([], PASS)], 'g17-capacity-fault-tests.py': [([], PASS)], 'g17-compute-constructor-tests.py': [([], PASS)], @@ -231,7 +231,7 @@ def mutations(flag, names, base, expect=KILL): 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'guilty-waits-delay', 'no-guilty-input', 'owed-blocks-kill', - 'open-owed-skipped'), []), + 'open-owed-skipped', 'post-latch-swallowed', 'reserve-fails-pass'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 522e39d5219f0eee5a73e103b585cc3e78fc2935 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 13:22:41 -0300 Subject: [PATCH 1074/1514] drm/asahi: g17: blame a spared culprit's hang on it the second time A recovery classifies every VM it does not find guilty as spared, and a later blame on a queue whose oldest work is spared counts as collateral to that earlier recovery, not as guilt of its VM (classify()). The blamed command then fails with EIO without poisoning its VM. That holds once. When the first restart of a cascade blames a client the real culprit starved, the culprit's work is spared, and every later restart that blames it finds that spared work and calls it collateral. The culprit's VM is never guilty and never failed: no restart that only drops its work is forgiven, a closed or open culprit is never killed, and the cascade ends only when a restart table happens to drop all of its work, or at the restart storm limit. 2026-11-19 19:12 UTC: gen 0 blamed chromium, then deqp-vk's spinning queue was collateral at gens 1, 3-7 and 10-12, and the storm limit stopped the GPU for every client. 2026-11-20 15:03 UTC: gen 0 blamed t3code, deqp-vk's queue was collateral at gens 2 and 4. Now a restart that blames a render pair's spared work as collateral marks that pair with its recovery generation (Pair::note_collateral). A later restart that blames the marked pair again, with none of its work retired in between, finds the hang its own, and the pair's VM is guilty. A retirement of the pair's work clears the mark, so a bystander that makes progress between blames stays collateral. The mark lives on the pair, not the QID, and Pair::bind_owner drops it when it binds the pair in place to another owner (rebound_collateral): a previous owner that closed without retiring anything must not make the next owner's first blame its second. A rebind for the same owner keeps it, and so does the owner's close, since an exited culprit's spared work stays published. A retirement on another queue of the same VM does not clear it, or a culprit with a second, healthy queue would stay immune. Compute queues keep the old rule. The cost for a bystander blamed collaterally twice with nothing of its blamed pair retired in between: its VM is poisoned, where today its failure stays non-sticky. Its client saw a lost device at both blames. The new cases replay a stateful cascade through classify(): the 2026-11-19 and 2026-11-20 15:03 cascades, a culprit blamed first, a bystander retiring between blames, a retirement on the culprit's other pair, and a pair rebound in place to a new owner. All but the culprit blamed first (unchanged behaviour) fail without the part they cover. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/render.rs | 24 ++ .../gpu/drm/asahi/g17/queue/render/parked.rs | 1 + drivers/gpu/drm/asahi/g17/recovery.rs | 264 +++++++++++++++++- drivers/gpu/drm/asahi/g17/runtime/events.rs | 6 + drivers/gpu/drm/asahi/g17/runtime/render.rs | 23 ++ 5 files changed, 308 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index e1e317469dd7d9..27bcde665c78a1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -237,6 +237,9 @@ pub(crate) struct Pair { /// the kill unlinked, so the pair is released and detached on that proof /// (`counts_idle`, `Pair::can_keep`), never parked for reuse while those entries remain. guilty_released: bool, + /// The recovery generation of the first restart that blamed this pair's spared work as + /// collateral, until a group of it retires (`recovery::Queues::note_collateral`). + collateral_at: Option, terminal: Option<(Arc, Error)>, previous: Option, displaced: Option, @@ -392,6 +395,7 @@ impl Pair { outer_started: 0, quarantined: false, guilty_released: false, + collateral_at: None, terminal: None, previous: None, displaced: None, @@ -1959,6 +1963,14 @@ impl Pair { } } + /// A restart before `generation` blamed this pair's spared work as collateral, and none of + /// it retired since. + pub(crate) fn collateral_before(&self, generation: u64) -> bool { + self.collateral_at.is_some_and(|at| at < generation) + } + pub(crate) fn note_collateral(&mut self, generation: u64) { + self.collateral_at.get_or_insert(generation); + } pub(crate) fn oldest_spared(&self) -> Option { self.active .front() @@ -2237,6 +2249,8 @@ impl Pair { retirement::note_stampless(u16::from(self.slot), ordinal); } self.note_retirement(ordinal, context_update); + // Work of this pair retires: a later blame on it is collateral again. + self.collateral_at = None; let front = self.active.front_mut().ok_or(EIO)?; if !front.flist_completed { host.complete_render( @@ -3450,6 +3464,9 @@ impl Pair { self.previous = Some(retired); } self.memory.context = binding.context.clone(); + // The pair is reused in place: the collateral mark of a previous owner, which may have + // closed without retiring anything, must not make the next owner's first blame its second. + self.collateral_at = rebound_collateral(self.collateral_at, self.owner == Some(binding.owner)); self.owner = Some(binding.owner); self.initial_packet = binding.initial_packet; if foreign { @@ -3545,6 +3562,13 @@ mod completion_noted_tests { } } +/// A pair's collateral mark (`Pair::collateral_at`) when it is bound to an owner: kept for the +/// same owner (a pool rebind), dropped for a new one. Not at the owner's close: an exited +/// culprit's spared work stays published, and dropping its mark then would cost a restart. +pub(crate) fn rebound_collateral(mark: Option, same_owner: bool) -> Option { + mark.filter(|_| same_owner) +} + /// See `Pair::guilty_killed`: a guilty pair (`guilty`) goes only with no restart in progress /// (`state` 0) and once `restarted` (`Context::restarted_since_kill`) holds. `restarted` is only /// asked of a guilty pair with no restart in progress, so that its first sighting of the kill diff --git a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs index f1fc45cee87aba..3af44ba9cf79b8 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/parked.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/parked.rs @@ -296,6 +296,7 @@ impl ParkedPair { outer_started: self.outer_started, quarantined: false, guilty_released: false, + collateral_at: None, terminal: None, previous: self.previous.take(), displaced: None, diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 0c5f8e9a25d98c..a518107a49f0e3 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -158,6 +158,15 @@ pub(super) trait Queues { fn note_interrupted(&mut self, qid: u8, stamp: u32) -> Interrupted; /// Optional diagnostics only; absence cannot alter attribution or release. fn report_blamed_render(&self, _qid: u8) {} + /// Read while firmware is halted: a restart before `generation` blamed the spared work of the + /// render pair that holds `qid` as collateral already, and none of that pair's work retired + /// since (`note_collateral`). Its spared work hung the GPU again after the restart that blamed + /// it, so the hang is its own. Never for a compute queue. + fn collateral_before(&self, _qid: u8, _generation: u64) -> bool { false } + /// The restart `generation` blamed the spared work of the render pair that holds `qid` as + /// collateral. Marks that pair, not the QID: a QID is reused once its owner closes, and the + /// next owner starts unmarked. A retirement of the pair's work clears the mark. + fn note_collateral(&mut self, _qid: u8, _generation: u64) {} /// Read while firmware is halted for the restart the host accepted after `generation`: /// every killed context whose kill the firmware finished counts as first seen done at /// `generation` at the latest, so this restart releases its guilty pairs @@ -371,7 +380,7 @@ pub(super) fn service( let (listed, exact, fallback) = (entries.listed, entries.exact, entries.fallback); let (cancelled, blame, leftover, charged) = - classify(host, entries, request.blamed, attribution); + classify(host, entries, request.blamed, attribution, request.generation); if listed != 0 && host.is_m5() { // The M5 table only classifies (read_entries): each command is retired from its own // queue's records, replayed when it never ran. @@ -485,7 +494,13 @@ fn read_entries(host: &mut H) -> Entries { /// Resolves guilty QIDs before changing any completion's classification. Unknown ownership or /// too many distinct guilty VMs leaves all prior classifications intact. The oldest spared work -/// of a QID makes later blame collateral to its previous recovery, rather than new VM guilt. +/// of a QID makes later blame collateral to its previous recovery, rather than new VM guilt, once: +/// the restart `generation` marks the render pair it blamed so (`Queues::note_collateral`), and +/// when a later restart blames that pair again with none of its work retired in between, the +/// hang is its own and its VM is guilty (`Queues::collateral_before`). Otherwise a first blame +/// that landed on a starved bystander would leave the real culprit's spared work immune: never +/// guilty, never poisoned, never forgiven and never killed, until the restart storm limit +/// (2026-11-19 19:12 UTC, 2026-11-20 15:03 UTC). /// Also returns whether the firmware's blamed QID is still guilty after attribution: a blamed /// render that had not started while others had (or with no culprit at all) is innocent, and its /// work is spared like that of every other innocent VM instead of failing with EIO. @@ -495,7 +510,13 @@ fn read_entries(host: &mut H) -> Entries { /// the commands each holds): one client's faults or hangs then cost only that client, however /// many VMs it opens. A restart without a guilty VM, or one that keeps blaming a VM for more /// than the work it held, is the device's. -fn classify(queues: &mut Q, entries: Entries, blamed: Option, attribution: Attribution) -> (u128, bool, bool, bool) { +fn classify( + queues: &mut Q, + entries: Entries, + blamed: Option, + attribution: Attribution, + generation: u64, +) -> (u128, bool, bool, bool) { let mut guilty_qids = entries.guilty | blamed.map_or(0, |qid| 1u128 << qid); let cancelled = entries.cancelled; match attribution { @@ -518,8 +539,8 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } match queues.oldest_spared(qid) { None => unresolved = true, - Some(true) => collateral |= 1u128 << qid, - Some(false) => { + Some(true) if !queues.collateral_before(qid, generation) => collateral |= 1u128 << qid, + Some(_) => { let mut found = false; queues.visit_owners(qid, &mut |status| { found = true; @@ -544,6 +565,9 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att if unresolved || (count == 0 && collateral == 0 && !no_culprit) { return (0, blame, false, false); } + for qid in (0..QIDS).filter(|qid| collateral & (1u128 << qid) != 0) { + queues.note_collateral(qid, generation); + } let known = |status: &Arc| guilty[..count].iter().flatten().any(|known| Arc::ptr_eq(known, status)); let mut dropped = false; for qid in (0..QIDS).filter(|qid| entries.exact_qids & (1u128 << qid) != 0) { @@ -807,7 +831,7 @@ mod tests { fn leftover(queues: &mut Owners, exact_qid: u8) -> bool { let entries = Entries { exact_qids: 1u128 << exact_qid, ..Entries::default() }; - classify(queues, entries, Some(40), Attribution::Queues(3u128 << 60)).2 + classify(queues, entries, Some(40), Attribution::Queues(3u128 << 60), 1).2 } #[test] @@ -825,7 +849,7 @@ mod tests { fn restarts_are_charged_to_their_guilty_clients_and_only_unblamed_ones_to_the_device() { let mut queues = owners(); let charged = |queues: &mut Owners, attribution| { - classify(queues, Entries::default(), None, attribution).3 + classify(queues, Entries::default(), None, attribution, 1).3 }; // Nobody to blame: the device's. assert!(!charged(&mut queues, Attribution::NoCulprit)); @@ -850,14 +874,234 @@ mod tests { let entries = || Entries { exact_qids: 1u128 << 40, ..Entries::default() }; // b failing for its own client does not make it guilty in a's recovery. queues.0[2].1.record(EIO); - classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40)); + classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40), 1); assert_eq!(queues.1, [Some(Class::Guilty), Some(Class::Guilty), Some(Class::Spared), Some(Class::Spared)]); // Once a recovery finds b guilty, a later recovery that blames a keeps b guilty. - classify(&mut queues, entries(), Some(60), Attribution::Queues(3u128 << 60)); - classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40)); + classify(&mut queues, entries(), Some(60), Attribution::Queues(3u128 << 60), 1); + classify(&mut queues, entries(), Some(40), Attribution::Queues(3u128 << 40), 1); assert_eq!(queues.1, [Some(Class::Guilty); 4]); } + /// A render pair in a cascade of restarts (see [`Cascade`]). + struct CascadePair { + qids: [u8; 2], + status: Arc, + class: Option, + collateral: Option, + } + + /// The render pairs across a cascade of restarts, with state: each pair keeps the class the + /// last recovery gave its work (`Pair::classify`) and its collateral mark + /// (`Pair::note_collateral`), which a retirement of its work clears. A blamed render fails as + /// `settle_blamed_render` fails it: guilty work poisons its VM, work an earlier recovery + /// spared fails without poisoning it (`Completion::poisons`). + struct Cascade([Option; 4], u64); + + impl Cascade { + fn new(pairs: [([u8; 2], &Arc); 4]) -> Self { + Self( + pairs.map(|(qids, status)| { + Some(CascadePair { qids, status: status.clone(), class: None, collateral: None }) + }), + 0, + ) + } + fn pair(&self, qid: u8) -> Option<&CascadePair> { + self.0.iter().flatten().find(|pair| pair.qids.contains(&qid)) + } + fn pair_mut(&mut self, qid: u8) -> Option<&mut CascadePair> { + self.0.iter_mut().flatten().find(|pair| pair.qids.contains(&qid)) + } + /// The pair that holds `qid` is bound to `status`'s owner in place, as `Pair::bind_owner` + /// rebinds a reusable pair: its mark goes as there (`rebound_collateral`), its work is new. + fn bind(&mut self, qid: u8, status: &Arc) { + if let Some(pair) = self.pair_mut(qid) { + let same = Arc::ptr_eq(&pair.status, status); + pair.collateral = crate::g17::queue::render::rebound_collateral(pair.collateral, same); + pair.status = status.clone(); + pair.class = None; + } + } + /// Work of the pair that holds `qid` retired (`Pair::retire_front_command`). + fn retire(&mut self, qid: u8) { + if let Some(pair) = self.pair_mut(qid) { + pair.collateral = None; + } + } + /// One restart as `service` runs it: the firmware blames `blamed`, its table drops + /// `dropped` by exact stamp, the blamed render fails. Returns whether it was forgiven. + fn restart(&mut self, blamed: u8, dropped: u128) -> bool { + let entries = Entries { exact_qids: dropped, ..Entries::default() }; + self.1 += 1; + let generation = self.1; + let (_, blame, leftover, _) = classify(self, entries, Some(blamed), Attribution::Firmware, generation); + if blame { + self.settle_blamed_render(blamed, EIO); + } + leftover + } + } + + impl Queues for Cascade { + fn render_scheduler_active(&self) -> bool { true } + fn render_pass_started(&self, _qid: u8, _stamp: u64) -> Option { None } + fn publish_recovery_targets(&self) -> Option { None } + fn oldest_spared(&self, qid: u8) -> Option { + self.pair(qid).map(|pair| pair.class == Some(Class::Spared)) + } + fn collateral_before(&self, qid: u8, generation: u64) -> bool { + self.pair(qid).is_some_and(|pair| pair.collateral.is_some_and(|at| at < generation)) + } + fn note_collateral(&mut self, qid: u8, generation: u64) { + if let Some(pair) = self.pair_mut(qid) { + pair.collateral.get_or_insert(generation); + } + } + fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { + if let Some(pair) = self.pair(qid) { + visit(&pair.status); + } + } + fn classify_work(&mut self, class: &dyn Fn(&Arc) -> Class) -> u128 { + let mut spared = 0; + for pair in self.0.iter_mut().flatten() { + pair.class = Some(class(&pair.status)); + if pair.class == Some(Class::Spared) { + spared |= (1u128 << pair.qids[0]) | (1u128 << pair.qids[1]); + } + } + spared + } + fn note_interrupted(&mut self, _qid: u8, _stamp: u32) -> Interrupted { Interrupted::Exact } + fn settle_blamed_render(&mut self, qid: u8, error: Error) { + let Some(pair) = self.pair_mut(qid) else { return }; + if pair.class == Some(Class::Spared) { + pair.status.report_failure(error); + } else { + pair.class = Some(Class::Guilty); + pair.status.record(error); + } + } + fn settle_cancelled_renders(&mut self, _qids: u128) {} + fn rescan_compute(&mut self) -> Result { Ok(()) } + fn release_retired_compute(&mut self) {} + } + + fn vm() -> Arc { + Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap() + } + + #[test] + fn a_culprit_spared_by_a_misattributed_first_restart_turns_guilty() { + // 11-20 15:03 UTC (m4.174), the 11-19 19:12 storm's shape: c spins on 40/41, and the + // first restart blames b (44/45), whose work c starved. b fails; c's work is spared. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart(45, (1 << 41) | (1 << 45))); + assert!(b.recovery_guilty() && b.get() != 0); + // The next restart blames b again and only drops b's work: forgiven. + assert!(queues.restart(45, 1 << 45)); + // Then every restart blames c's queue 41 and drops its running group by exact stamp. + // The first blame on work an earlier restart spared is collateral: c fails without + // poisoning its VM, and the restart counts. + assert!(!queues.restart(41, 1 << 41)); + assert!(!c.recovery_guilty() && c.get() == 0); + // Blamed again with nothing of it retired since: the hang is c's own. + assert!(!queues.restart(41, 1 << 41)); + assert!(c.recovery_guilty()); + assert_ne!(c.get(), 0); + // From now on a restart that only drops failed c's work is forgiven. + assert!(queues.restart(41, 1 << 41)); + } + + #[test] + fn a_bystander_that_retires_between_blames_stays_collateral() { + // c is blamed first; b's work is spared, then blamed while it waits behind c's. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + queues.restart(41, 1 << 41); + assert!(c.recovery_guilty()); + queues.restart(45, 1 << 45); + assert!(!b.recovery_guilty() && b.get() == 0); + // b's next command retires: blamed again, it is collateral again, its VM unpoisoned. + queues.retire(44); + queues.restart(45, 1 << 45); + assert!(!b.recovery_guilty() && b.get() == 0); + // Blamed a third time with nothing retired since: guilty. Its client already saw a + // lost device at each blame; now its VM is poisoned too. + queues.restart(45, 1 << 45); + assert!(b.recovery_guilty()); + assert_ne!(b.get(), 0); + } + + #[test] + fn a_retirement_on_another_queue_of_the_culprit_does_not_reset_it() { + // c owns two pairs, 40/41 (spinning) and 50/51; the first restart blames b. + let (c, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([50, 51], &c), ([44, 45], &b), ([60, 61], &x)]); + queues.restart(45, (1 << 41) | (1 << 45)); + queues.restart(41, 1 << 41); + assert!(!c.recovery_guilty()); + // c's other pair keeps retiring: the blamed pair's mark stays. + queues.retire(50); + queues.restart(41, 1 << 41); + assert!(c.recovery_guilty()); + } + + #[test] + fn a_new_owner_of_a_reused_queue_starts_with_a_fresh_collateral() { + let (c, b, d, x) = (vm(), vm(), vm(), vm()); + let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + queues.restart(45, (1 << 41) | (1 << 45)); + queues.restart(41, 1 << 41); + assert!(!c.recovery_guilty()); + // c closes without retiring anything; its pair, reused in place, is bound to d. + queues.bind(41, &d); + // A restart that blames b again spares d's work; then one blames d's queue 41. + queues.restart(45, 1 << 45); + queues.restart(41, 1 << 41); + assert!(!d.recovery_guilty() && d.get() == 0); + // A rebind for the same owner (a pool change) keeps the mark: blamed again, d is guilty. + queues.bind(41, &d); + queues.restart(45, 1 << 45); + queues.restart(41, 1 << 41); + assert!(d.recovery_guilty()); + } + + #[test] + fn the_11_19_storm_ends_with_its_culprit_guilty_before_the_limit() { + // 2026-11-19 19:12 UTC (m4.171): deqp-vk (40/41) spins. Gen 0 blamed chromium (62/63), + // gen 1 deqp, gen 2 quickshell (42/43), gens 3-7 deqp again; every one counted until + // the storm limit stopped the GPU (8 in 30 s). + let (deqp, chromium, quickshell, x) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([40, 41], &deqp), ([62, 63], &chromium), ([42, 43], &quickshell), ([60, 61], &x)]); + let mut counted = 0; + for (blamed, dropped) in [(63, 1u128 << 63), (41, 1 << 41), (42, 1 << 42)] { + counted += usize::from(!queues.restart(blamed, dropped)); + } + // quickshell's first blame was collateral: it saw one failed command, its VM stays usable. + assert!(!quickshell.recovery_guilty() && quickshell.get() == 0); + // deqp's second blame makes it guilty, and later restarts that drop its work are forgiven. + for _ in 3..8 { + counted += usize::from(!queues.restart(41, 1 << 41)); + } + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert_eq!(counted, 4); + } + + #[test] + fn a_culprit_blamed_first_is_guilty_at_once_as_before() { + // 2026-11-20 02:18 UTC (m4.173, T72 run 2): the first restart blamed deqp's 59. + let (deqp, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &deqp), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart(59, 1 << 45)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(queues.restart(59, 1 << 59)); + assert!(queues.restart(59, 1 << 59)); + assert!(!b.recovery_guilty() && b.get() == 0); + } + #[test] fn unknown_25g83_keys_still_preserve_firmware_blame() { let mut host = Halted::new(false); diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index f269baf58e9429..4a6d89eddeb472 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -229,6 +229,12 @@ impl recovery::Queues for Service<'_> { .and_then(|queue| queue.oldest_spared()) }) } + fn collateral_before(&self, qid: u8, generation: u64) -> bool { + self.firmware.queues.render_collateral_before(qid, generation) + } + fn note_collateral(&mut self, qid: u8, generation: u64) { + self.firmware.queues.note_render_collateral(qid, generation); + } fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { self.firmware.queues.visit_render_owners(qid, visit); for queue in self diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 2dfac71fc50ff3..b90750f9bc3e82 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1054,6 +1054,29 @@ impl Registry { .find(|pair| pair.qids().contains(&qid)) .and_then(|pair| pair.oldest_spared()) } + /// See `recovery::Queues::collateral_before`. + pub(in crate::g17) fn render_collateral_before(&self, qid: u8, generation: u64) -> bool { + self.render + .entries + .iter() + .flatten() + .filter_map(|entry| entry.pair.as_ref()) + .find(|pair| pair.qids().contains(&qid)) + .is_some_and(|pair| pair.collateral_before(generation)) + } + /// See `recovery::Queues::note_collateral`. + pub(in crate::g17) fn note_render_collateral(&mut self, qid: u8, generation: u64) { + if let Some(pair) = self + .render + .entries + .iter_mut() + .flatten() + .filter_map(|entry| entry.pair.as_mut()) + .find(|pair| pair.qids().contains(&qid)) + { + pair.note_collateral(generation); + } + } /// Marks the interrupted group of the pair that owns `qid`. pub(in crate::g17) fn note_render_interrupted( &self, From 850d5791c88e47f15f689decfc19f22bbfc8a332 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 14:59:00 -0300 Subject: [PATCH 1075/1514] drm/asahi: g17: fail a culprit's VM when a repeated blame finds it guilty A spared render pair blamed a second time with none of its work retired in between turns its VM guilty, but nothing failed that VM. The culprit's commands had all failed already, without poisoning it: restarts before listed them as interrupted while its VM was innocent, and the first, collateral blame failed its oldest. Failing them again changes nothing (Pair::quarantine skips failed work), so no FailedOwned, no terminal and no VmStatus::record followed. With its status clear, a restart that only drops its work is not forgiven, and the closed or open culprit is never killed. On 2026-11-20 17:52 UTC (m4.175) the first three restarts blamed chromium's GPU processes, deqp-vk's spinning pair turned guilty at its second blame, and still 7 of 8 restarts counted before a restart table happened to drop all of deqp's work. So classify() records the failure itself for the VMs that a repeated collateral blame finds guilty, after leftover judged this restart on their state before it. Nothing later in the same restart forgives: classify_work and the settle steps go by class and recovery_guilty, and the status only keeps the failed VM's work from replays and new submissions. Not on M5: the runtime's collateral hooks (and with them the previous change) are off there, so an M5 classify is as before. M5 takes published work back through its recovery target and has not been tested with this. The test stand-in now keeps a pair's work failed once a restart listed it or a blame failed it, and does not fail it again, as the queues do. The new case replays the m4.175 cascade, render attribution included: 5 counted restarts, then forgiven ones. Without the record, it and the four culprit and bystander cases before it fail. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/recovery.rs | 73 +++++++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/events.rs | 8 ++- 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index a518107a49f0e3..96b017f10d6c84 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -532,6 +532,8 @@ fn classify( let mut guilty: [Option>; MAX_GUILTY_VMS] = Default::default(); let mut count = 0; let mut collateral = 0u128; + // Spared work blamed a second time (`collateral_before`): its VM is guilty now. + let mut repeated = 0u128; let mut unresolved = false; for qid in 0..QIDS { if guilty_qids & (1u128 << qid) == 0 { @@ -540,7 +542,10 @@ fn classify( match queues.oldest_spared(qid) { None => unresolved = true, Some(true) if !queues.collateral_before(qid, generation) => collateral |= 1u128 << qid, - Some(_) => { + Some(spared) => { + if spared { + repeated |= 1u128 << qid; + } let mut found = false; queues.visit_owners(qid, &mut |status| { found = true; @@ -575,6 +580,14 @@ fn classify( } let leftover = count != 0 && dropped && guilty[..count].iter().flatten().all(|status| status.get() != 0); guilty[..count].iter().flatten().for_each(|status| status.note_recovery_guilty()); + // Its work failed already, at the collateral blame or as commands earlier restarts listed, + // and failing it again changes nothing (`Pair::quarantine` skips failed work): nothing else + // poisons this VM. Poison it here, after `leftover` judged this restart on the VM's state + // before it, so that the restarts that only drop its work from now on are forgiven, and an + // open or closed culprit is killed (2026-11-20 17:52 UTC, m4.175). + for qid in (0..QIDS).filter(|qid| repeated & (1u128 << qid) != 0) { + queues.visit_owners(qid, &mut |status| status.record(EIO)); + } // Commands each guilty VM holds, counted as they are classified. let held: [core::cell::Cell; MAX_GUILTY_VMS] = Default::default(); let spared = queues.classify_work(&|status| { @@ -888,20 +901,24 @@ mod tests { status: Arc, class: Option, collateral: Option, + /// Its work failed already (a restart listed it, or it was blamed): failing it again + /// changes nothing, as `Pair::quarantine` skips failed work. + failed: bool, } /// The render pairs across a cascade of restarts, with state: each pair keeps the class the /// last recovery gave its work (`Pair::classify`) and its collateral mark /// (`Pair::note_collateral`), which a retirement of its work clears. A blamed render fails as /// `settle_blamed_render` fails it: guilty work poisons its VM, work an earlier recovery - /// spared fails without poisoning it (`Completion::poisons`). + /// spared fails without poisoning it (`Completion::poisons`), and work that failed already + /// is not failed again. struct Cascade([Option; 4], u64); impl Cascade { fn new(pairs: [([u8; 2], &Arc); 4]) -> Self { Self( pairs.map(|(qids, status)| { - Some(CascadePair { qids, status: status.clone(), class: None, collateral: None }) + Some(CascadePair { qids, status: status.clone(), class: None, collateral: None, failed: false }) }), 0, ) @@ -920,21 +937,36 @@ mod tests { pair.collateral = crate::g17::queue::render::rebound_collateral(pair.collateral, same); pair.status = status.clone(); pair.class = None; + pair.failed = false; } } /// Work of the pair that holds `qid` retired (`Pair::retire_front_command`). fn retire(&mut self, qid: u8) { if let Some(pair) = self.pair_mut(qid) { pair.collateral = None; + pair.failed = false; } } /// One restart as `service` runs it: the firmware blames `blamed`, its table drops /// `dropped` by exact stamp, the blamed render fails. Returns whether it was forgiven. fn restart(&mut self, blamed: u8, dropped: u128) -> bool { + self.restart_as(blamed, dropped, Attribution::Firmware) + } + /// As [`Self::restart`], with render attribution (`render_culprit`) deciding the blame. + fn restart_as(&mut self, blamed: u8, dropped: u128, attribution: Attribution) -> bool { let entries = Entries { exact_qids: dropped, ..Entries::default() }; self.1 += 1; let generation = self.1; - let (_, blame, leftover, _) = classify(self, entries, Some(blamed), Attribution::Firmware, generation); + let (_, blame, leftover, _) = classify(self, entries, Some(blamed), attribution, generation); + // The listed commands fail: a guilty VM's poison it, others' are discarded. + for pair in self.0.iter_mut().flatten() { + if !pair.failed && pair.qids.iter().any(|qid| dropped & (1u128 << qid) != 0) { + if pair.class == Some(Class::Guilty) { + pair.status.record(EIO); + } + pair.failed = true; + } + } if blame { self.settle_blamed_render(blamed, EIO); } @@ -975,6 +1007,10 @@ mod tests { fn note_interrupted(&mut self, _qid: u8, _stamp: u32) -> Interrupted { Interrupted::Exact } fn settle_blamed_render(&mut self, qid: u8, error: Error) { let Some(pair) = self.pair_mut(qid) else { return }; + if pair.failed { + return; + } + pair.failed = true; if pair.class == Some(Class::Spared) { pair.status.report_failure(error); } else { @@ -1046,6 +1082,7 @@ mod tests { queues.retire(50); queues.restart(41, 1 << 41); assert!(c.recovery_guilty()); + assert_ne!(c.get(), 0); } #[test] @@ -1090,6 +1127,34 @@ mod tests { assert_eq!(counted, 4); } + #[test] + fn the_m4_175_cascade_fails_its_culprit_whose_work_already_failed() { + // 2026-11-20 17:52 UTC (m4.175): deqp-vk (61/62) spins and its commands fail as listed + // ones from the first restart on. Chromium's GPU process (58/59), then its next process + // on the same pair, then a third (63/64) are blamed first. + let (chromium, chromium2, chromium3, deqp) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([58, 59], &chromium), ([61, 62], &deqp), ([63, 64], &chromium3), ([60, 65], &chromium2)]); + let mut counted = 0; + counted += usize::from(!queues.restart(59, (1 << 59) | (1 << 62))); + queues.bind(58, &chromium2); + counted += usize::from(!queues.restart(58, 1 << 58)); + // The firmware blames deqp's 62; attribution moves it to chromium's failed pair. + counted += usize::from(!queues.restart_as(62, 3 << 58, Attribution::Queues(3 << 58))); + counted += usize::from(!queues.restart(64, (1 << 62) | (1 << 64))); + // deqp's 62, blamed once (collateral), then again: guilty and failed, although every + // command of it failed already as a listed one. + counted += usize::from(!queues.restart(62, 1 << 62)); + assert!(!deqp.recovery_guilty() && deqp.get() == 0); + counted += usize::from(!queues.restart(62, 1 << 62)); + assert!(deqp.recovery_guilty()); + assert_ne!(deqp.get(), 0); + // The next restarts drop only failed deqp's work: forgiven, well under the storm limit. + assert!(queues.restart_as(62, 1 << 62, Attribution::Queues(3 << 61))); + assert!(queues.restart(62, 1 << 62)); + assert_eq!(counted, 5); + } + #[test] fn a_culprit_blamed_first_is_guilty_at_once_as_before() { // 2026-11-20 02:18 UTC (m4.173, T72 run 2): the first restart blamed deqp's 59. diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 4a6d89eddeb472..17fffdfa0921d6 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -229,11 +229,15 @@ impl recovery::Queues for Service<'_> { .and_then(|queue| queue.oldest_spared()) }) } + // Not on M5: it takes published work back through its recovery target, and its spared + // work keeps the old collateral rule. fn collateral_before(&self, qid: u8, generation: u64) -> bool { - self.firmware.queues.render_collateral_before(qid, generation) + !self.firmware.init.is_m5() && self.firmware.queues.render_collateral_before(qid, generation) } fn note_collateral(&mut self, qid: u8, generation: u64) { - self.firmware.queues.note_render_collateral(qid, generation); + if !self.firmware.init.is_m5() { + self.firmware.queues.note_render_collateral(qid, generation); + } } fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { self.firmware.queues.visit_render_owners(qid, visit); From bb68e8865c8bd9662e500f13ae5abf03bfe45875 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 23 Nov 2026 02:25:04 -0300 Subject: [PATCH 1076/1514] drm/asahi: g17: fail a VM only when evidence or a repeat confirms its blame A G17P restart for a timeout names one queue, and the firmware picks it without knowing whose work hangs the GPU. When slot identity reads no keys and the blamed render had already started its tiler pass, nothing moves that blame, and classify() failed the blamed VM as guilty on the spot. On our M4 Pro test kernel a deqp-vk memory_model spin beside the desktop got the first blame onto a bystander twice in seven runs. In run 7 the first restart blamed t3code's render and the next blamed Hyprland's. Both renders were waiting behind deqp's. Both VMs were failed and their queues closed, and Hyprland's next submit returned EIO and took the session down. Only the third restart blamed deqp. Treat a blame that only the firmware gives (Attribution::Firmware) like one on spared work: the first time it is collateral, so the blamed command fails but the VM stays usable, and the render pair is marked. If the pair is blamed again before any of its work retires, its VM is guilty. A real culprit costs one more restart. A bystander that is blamed once, or that keeps retiring work between blames, keeps its device. Evidence still makes a VM guilty on the first blame: slot identity, the host's pass records, or a VM an earlier recovery found guilty. Only G17P render pairs keep the collateral mark (marks_collateral()). Compute queues and M5 keep none, so a repeat there would look like a first blame forever. Their unconfirmed blame stays guilty at once, as before. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/recovery.rs | 110 +++++++++++++++++--- drivers/gpu/drm/asahi/g17/runtime/events.rs | 3 + 2 files changed, 101 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 96b017f10d6c84..900b918e3a6b46 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -167,6 +167,9 @@ pub(super) trait Queues { /// collateral. Marks that pair, not the QID: a QID is reused once its owner closes, and the /// next owner starts unmarked. A retirement of the pair's work clears the mark. fn note_collateral(&mut self, _qid: u8, _generation: u64) {} + /// `note_collateral` keeps a mark for the queue that holds `qid`, so a repeated blame on it + /// can be told from a first one. Only G17P render pairs keep one. + fn marks_collateral(&self, _qid: u8) -> bool { false } /// Read while firmware is halted for the restart the host accepted after `generation`: /// every killed context whose kill the firmware finished counts as first seen done at /// `generation` at the latest, so this restart releases its guilty pairs @@ -494,7 +497,8 @@ fn read_entries(host: &mut H) -> Entries { /// Resolves guilty QIDs before changing any completion's classification. Unknown ownership or /// too many distinct guilty VMs leaves all prior classifications intact. The oldest spared work -/// of a QID makes later blame collateral to its previous recovery, rather than new VM guilt, once: +/// of a QID, or blame that no evidence confirmed (`Attribution::Firmware`), makes that blame +/// collateral rather than new VM guilt, once: /// the restart `generation` marks the render pair it blamed so (`Queues::note_collateral`), and /// when a later restart blames that pair again with none of its work retired in between, the /// hang is its own and its VM is guilty (`Queues::collateral_before`). Otherwise a first blame @@ -525,6 +529,10 @@ fn classify( Attribution::NoCulprit => guilty_qids = 0, } let no_culprit = attribution == Attribution::NoCulprit; + // Only the firmware names these queues. A reason-0 restart can land on a bystander whose + // render started and waits behind the culprit's (2026-11-23 01:46 UTC, m4.179: t3code, then + // Hyprland), so the first such blame is collateral and only a repeat makes the VM guilty. + let unconfirmed = attribution == Attribution::Firmware; let blame = blamed.is_some_and(|qid| guilty_qids & (1u128 << qid) != 0); if guilty_qids == 0 && !no_culprit { return (0, blame, false, false); @@ -532,7 +540,7 @@ fn classify( let mut guilty: [Option>; MAX_GUILTY_VMS] = Default::default(); let mut count = 0; let mut collateral = 0u128; - // Spared work blamed a second time (`collateral_before`): its VM is guilty now. + // Spared or unconfirmed work blamed a second time (`collateral_before`): its VM is guilty now. let mut repeated = 0u128; let mut unresolved = false; for qid in 0..QIDS { @@ -541,9 +549,17 @@ fn classify( } match queues.oldest_spared(qid) { None => unresolved = true, - Some(true) if !queues.collateral_before(qid, generation) => collateral |= 1u128 << qid, Some(spared) => { - if spared { + // Blame on a VM an earlier recovery found guilty needs no confirmation. + let mut guilty_before = false; + queues.visit_owners(qid, &mut |status| guilty_before |= status.recovery_guilty()); + // Without a mark a repeat looks like a first blame forever: such blame stays guilty. + let suspect = spared || (unconfirmed && !guilty_before && queues.marks_collateral(qid)); + if suspect && !queues.collateral_before(qid, generation) { + collateral |= 1u128 << qid; + continue; + } + if suspect { repeated |= 1u128 << qid; } let mut found = false; @@ -881,6 +897,16 @@ mod tests { assert!(!charged(&mut queues, Attribution::Queues(1u128 << 60))); } + #[test] + fn unconfirmed_blame_without_a_collateral_mark_is_guilty_at_once() { + // A compute queue, or any queue on M5, keeps no mark: a repeat could never be seen. + let mut queues = owners(); + let entries = Entries { exact_qids: 1u128 << 40, ..Entries::default() }; + classify(&mut queues, entries, Some(40), Attribution::Firmware, 1); + assert!(queues.0[0].1.recovery_guilty()); + assert_eq!(queues.1, [Some(Class::Guilty), Some(Class::Guilty), Some(Class::Spared), Some(Class::Spared)]); + } + #[test] fn a_guilty_vm_is_not_spared_by_another_vms_recovery() { let mut queues = owners(); @@ -940,6 +966,14 @@ mod tests { pair.failed = false; } } + /// The pair that holds `qid` submitted new work that no recovery has classified yet, and + /// it is now the pair's oldest in flight (its earlier work failed or retired). + fn submit(&mut self, qid: u8) { + if let Some(pair) = self.pair_mut(qid) { + pair.class = None; + pair.failed = false; + } + } /// Work of the pair that holds `qid` retired (`Pair::retire_front_command`). fn retire(&mut self, qid: u8) { if let Some(pair) = self.pair_mut(qid) { @@ -989,6 +1023,7 @@ mod tests { pair.collateral.get_or_insert(generation); } } + fn marks_collateral(&self, qid: u8) -> bool { self.pair(qid).is_some() } fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { if let Some(pair) = self.pair(qid) { visit(&pair.status); @@ -1030,12 +1065,16 @@ mod tests { #[test] fn a_culprit_spared_by_a_misattributed_first_restart_turns_guilty() { // 11-20 15:03 UTC (m4.174), the 11-19 19:12 storm's shape: c spins on 40/41, and the - // first restart blames b (44/45), whose work c starved. b fails; c's work is spared. + // first restart blames b (44/45), whose work c starved. Nothing confirms the blame: b's + // command fails without poisoning its VM; c's work is spared. let (c, b, x) = (vm(), vm(), vm()); let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); assert!(!queues.restart(45, (1 << 41) | (1 << 45))); + assert!(!b.recovery_guilty() && b.get() == 0); + // The next restart blames b again with nothing of b retired: the repeat makes b guilty. + // Blame alone cannot tell a bystander starved twice from a culprit. + assert!(!queues.restart(45, 1 << 45)); assert!(b.recovery_guilty() && b.get() != 0); - // The next restart blames b again and only drops b's work: forgiven. assert!(queues.restart(45, 1 << 45)); // Then every restart blames c's queue 41 and drops its running group by exact stamp. // The first blame on work an earlier restart spared is collateral: c fails without @@ -1052,10 +1091,11 @@ mod tests { #[test] fn a_bystander_that_retires_between_blames_stays_collateral() { - // c is blamed first; b's work is spared, then blamed while it waits behind c's. + // c is blamed first, twice; b's work is spared, then blamed while it waits behind c's. let (c, b, x) = (vm(), vm(), vm()); let mut queues = Cascade::new([([40, 41], &c), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); queues.restart(41, 1 << 41); + queues.restart(41, 1 << 41); assert!(c.recovery_guilty()); queues.restart(45, 1 << 45); assert!(!b.recovery_guilty() && b.get() == 0); @@ -1117,7 +1157,9 @@ mod tests { for (blamed, dropped) in [(63, 1u128 << 63), (41, 1 << 41), (42, 1 << 42)] { counted += usize::from(!queues.restart(blamed, dropped)); } - // quickshell's first blame was collateral: it saw one failed command, its VM stays usable. + // chromium's and quickshell's first blames were collateral: each saw one failed command, + // and their VMs stay usable. + assert!(!chromium.recovery_guilty() && chromium.get() == 0); assert!(!quickshell.recovery_guilty() && quickshell.get() == 0); // deqp's second blame makes it guilty, and later restarts that drop its work are forgiven. for _ in 3..8 { @@ -1149,24 +1191,68 @@ mod tests { counted += usize::from(!queues.restart(62, 1 << 62)); assert!(deqp.recovery_guilty()); assert_ne!(deqp.get(), 0); - // The next restarts drop only failed deqp's work: forgiven, well under the storm limit. + // The next restarts drop only failed deqp's work: forgiven, under the storm limit. The + // chromium processes' first blames are collateral, so the restart that attribution moved + // to chromium2's pair (its second) counts too. assert!(queues.restart_as(62, 1 << 62, Attribution::Queues(3 << 61))); assert!(queues.restart(62, 1 << 62)); - assert_eq!(counted, 5); + assert!(!chromium.recovery_guilty() && chromium.get() == 0); + assert!(!chromium3.recovery_guilty() && chromium3.get() == 0); + assert_eq!(counted, 6); } #[test] - fn a_culprit_blamed_first_is_guilty_at_once_as_before() { - // 2026-11-20 02:18 UTC (m4.173, T72 run 2): the first restart blamed deqp's 59. + fn a_culprit_blamed_first_is_guilty_at_its_second_blame() { + // 2026-11-20 02:18 UTC (m4.173, T72 run 2): the first restart blamed deqp's 59. Nothing + // confirmed that blame, so it is collateral: one failed command, the VM stays usable. let (deqp, b, x) = (vm(), vm(), vm()); let mut queues = Cascade::new([([58, 59], &deqp), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); assert!(!queues.restart(59, 1 << 45)); + assert!(!deqp.recovery_guilty() && deqp.get() == 0); + // Its hang comes back with nothing of it retired: the blame is its own. + assert!(!queues.restart(59, 1 << 59)); assert!(deqp.recovery_guilty() && deqp.get() != 0); assert!(queues.restart(59, 1 << 59)); + assert!(!b.recovery_guilty() && b.get() == 0); + } + + #[test] + fn a_confirmed_first_blame_is_guilty_at_once() { + // Evidence (slot identity, the host's pass records or a latched MMU fault) names the VM. + let (deqp, b, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &deqp), ([44, 45], &b), ([60, 61], &x), ([62, 63], &x)]); + assert!(!queues.restart_as(59, 1 << 59, Attribution::Queues(3 << 58))); + assert!(deqp.recovery_guilty() && deqp.get() != 0); assert!(queues.restart(59, 1 << 59)); assert!(!b.recovery_guilty() && b.get() == 0); } + #[test] + fn the_m4_179_bystander_blames_poison_only_the_culprit() { + // 2026-11-23 01:46:44 UTC (m4.179, #2504 hang row run 7): deqp-vk (100/101) spins. Reason + // 0, no slot keys, and each bystander's front render had its tiler start written, so no + // evidence moved the blame. Gen 21 blamed t3code's 57, gen 22 Hyprland's 37, gen 23 + // deqp's 101; both bystanders were failed as guilty and Hyprland lost the session. + let (deqp, t3code, hyprland, x) = (vm(), vm(), vm(), vm()); + let mut queues = + Cascade::new([([100, 101], &deqp), ([56, 57], &t3code), ([36, 37], &hyprland), ([60, 61], &x)]); + let mut counted = 0; + counted += usize::from(!queues.restart(57, (3 << 56) | (1 << 101))); + assert!(!t3code.recovery_guilty() && t3code.get() == 0); + // Hyprland's next frame started after that restart: nothing spared it. + queues.submit(36); + counted += usize::from(!queues.restart(37, (3 << 36) | (1 << 101))); + assert!(!hyprland.recovery_guilty() && hyprland.get() == 0); + counted += usize::from(!queues.restart(101, 3 << 100)); + assert!(!deqp.recovery_guilty()); + counted += usize::from(!queues.restart(101, 1 << 101)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(queues.restart(101, 1 << 101)); + assert!(!t3code.recovery_guilty() && t3code.get() == 0); + assert!(!hyprland.recovery_guilty() && hyprland.get() == 0); + assert_eq!(counted, 4); + } + #[test] fn unknown_25g83_keys_still_preserve_firmware_blame() { let mut host = Halted::new(false); diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 17fffdfa0921d6..d9860a810757c1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -239,6 +239,9 @@ impl recovery::Queues for Service<'_> { self.firmware.queues.note_render_collateral(qid, generation); } } + fn marks_collateral(&self, qid: u8) -> bool { + !self.firmware.init.is_m5() && self.firmware.queues.render_oldest_spared(qid).is_some() + } fn visit_owners(&self, qid: u8, visit: &mut dyn FnMut(&Arc)) { self.firmware.queues.visit_render_owners(qid, visit); for queue in self From a43b5e2d83dabe5d60cb8b75233eb3c4239f56e7 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 23 Nov 2026 22:43:49 -0300 Subject: [PATCH 1077/1514] drm/asahi: g17: suspect the oldest running render, never an unstarted one A reason-0 restart names the queue the firmware chose, and without slot keys the host's pass records are the only check on it. They moved the blame only off an unstarted render with a single VM running, and the blame stood otherwise. Since the previous commit a blame only the firmware gives is collateral once, and a repeat makes the VM guilty. On the J616s a hang test showed why that is not enough. With a deqp-vk memory_model spin beside the desktop, the second restart blamed quickshell's render (pair 42/43), whose tiler started after deqp's running render. The third restart blamed quickshell's next render, which had not started at all, and the repeat failed quickshell's VM as guilty. A diagnostic that logged every pair's front render while the firmware was halted showed in all five restarts that deqp's pair held the running render with the oldest tiler start. The first restart blamed deqp itself, and that render was the only one running, but the blame was only collateral, so the earlier-guilt rule never named deqp later. Take the running render whose tiler started first as the hang suspect: the others started after it and wait behind it. Its VM's running pairs are suspected (Attribution::Suspects), whether or not the firmware blamed them. A suspicion is not proof, since a slow innocent render that started its tiler just before the hung one looks the same, so classify() treats it like the firmware's blame: collateral the first time, guilty on a repeat before any of the pair's work retires. A blamed render that never started is never the hang. When nothing runs, or another VM's compute work (which these records cannot see) is in flight, nobody is blamed (NoCulprit). A started blamed render beside foreign compute keeps the firmware's blame. A VM an earlier recovery found guilty still comes first, as evidence. render_culprit() now returns the attribution itself. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/render.rs | 20 ++-- drivers/gpu/drm/asahi/g17/recovery.rs | 42 ++++++-- .../gpu/drm/asahi/g17/recovery/attribution.rs | 20 ++-- drivers/gpu/drm/asahi/g17/runtime/events.rs | 2 +- .../drm/asahi/g17/runtime/render/recovery.rs | 102 ++++++++++++------ 5 files changed, 126 insertions(+), 60 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 27bcde665c78a1..f2b74c50595a65 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -2028,10 +2028,10 @@ impl Pair { Some(observation::snapshot(&self.memory, front.ticket.ordinal).ok()?.untouched()) } - /// The owner of a published group whose tiler started and whose fragment end is unwritten. - /// Groups an earlier recovery listed or blamed are skipped: a restart drops started groups, - /// so their records stay half-written without anything running. - pub(crate) fn running_owner(&self) -> Option<&Arc> { + /// A published group whose tiler started and whose fragment end is unwritten, with its pass + /// record. Groups an earlier recovery listed or blamed are skipped: a restart drops started + /// groups, so their records stay half-written without anything running. + fn running(&self) -> Option<(&Active, [u64; 2])> { self.active .iter() .filter(|active| { @@ -2039,11 +2039,15 @@ impl Pair { && !active.packet.completion.interrupted() && !active.packet.completion.blamed() }) - .find(|active| { - observation::snapshot(&self.memory, active.ticket.ordinal) - .is_ok_and(|snapshot| snapshot.pass[0] != 0 && snapshot.pass[1] == 0) + .find_map(|active| { + let pass = observation::snapshot(&self.memory, active.ticket.ordinal).ok()?.pass; + (pass[0] != 0 && pass[1] == 0).then_some((active, pass)) }) - .map(|active| active.packet.completion.status()) + } + + /// The owner of the `running` group and its tiler start, read while firmware is halted. + pub(crate) fn running_start(&self) -> Option<(&Arc, u64)> { + self.running().map(|(active, pass)| (active.packet.completion.status(), pass[0])) } /// Firmware is halted and all graph borrowers have joined before this copy. diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index 900b918e3a6b46..d7fab179284c3d 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -12,7 +12,7 @@ mod slot; mod safety; pub(crate) use safety::{note_retired, since_retired}; pub(crate) use attribution::{Record, Sources, PAGE_FAULT}; -use attribution::Attribution; +pub(crate) use attribution::Attribution; pub(super) fn slot_key(slot: usize, slot_keys: Option) -> Option { slot::key(slot, slot_keys?).ok() @@ -141,10 +141,11 @@ pub(super) trait Queues { fn render_pass_started(&self, qid: u8, stamp: u64) -> Option; /// Read while firmware is halted, like `render_pass_started`. The QIDs of every pair of a VM /// an earlier recovery found guilty with a render that started and did not finish. Without - /// one, and only when the oldest published render of the pair holding `blamed` had not - /// started, those of the one VM with such a render. None if no such VM, several, or any - /// other VM holds compute work, which these records cannot see. - fn render_culprit(&self, _blamed: u8) -> Option { None } + /// one, `Suspects` the VM whose such render started first, unless another VM holds compute + /// work, which these records cannot see. `NoCulprit` when the oldest published render of the + /// pair holding `blamed` had not started and no VM can be named; None keeps the firmware's + /// blame. + fn render_culprit(&self, _blamed: u8) -> Option { None } /// Copy every retained queue's live producer to its recovery target, then /// issue a full barrier. A failed graph must not skip subsequent queues. fn publish_recovery_targets(&self) -> Option; @@ -345,6 +346,9 @@ pub(super) fn service( |qid, stamp| host.render_pass_started(qid, stamp)); let attribution = sources.host_fallback(attribution, || host.render_culprit(request.blamed?)); + if let Attribution::Suspects(qids) = attribution { + pr_warn!("G17: recovery gen {} suspects queues {:#x}\n", request.generation, qids); + } if let Attribution::Queues(qids) = attribution { pr_warn!("G17: recovery gen {} blames queues {:#x}\n", request.generation, qids); } @@ -525,14 +529,15 @@ fn classify( let cancelled = entries.cancelled; match attribution { Attribution::Firmware => {} - Attribution::Queues(qids) => guilty_qids = qids, + Attribution::Queues(qids) | Attribution::Suspects(qids) => guilty_qids = qids, Attribution::NoCulprit => guilty_qids = 0, } let no_culprit = attribution == Attribution::NoCulprit; - // Only the firmware names these queues. A reason-0 restart can land on a bystander whose - // render started and waits behind the culprit's (2026-11-23 01:46 UTC, m4.179: t3code, then - // Hyprland), so the first such blame is collateral and only a repeat makes the VM guilty. - let unconfirmed = attribution == Attribution::Firmware; + // Only the firmware, or the pass records' suspicion, names these queues. A reason-0 restart + // can land on a bystander whose render started and waits behind the culprit's (2026-11-23 + // 01:46 UTC, m4.179: t3code, then Hyprland), and a slow innocent render can be the oldest + // running one, so the first such blame is collateral and only a repeat makes the VM guilty. + let unconfirmed = matches!(attribution, Attribution::Firmware | Attribution::Suspects(_)); let blame = blamed.is_some_and(|qid| guilty_qids & (1u128 << qid) != 0); if guilty_qids == 0 && !no_culprit { return (0, blame, false, false); @@ -1216,6 +1221,23 @@ mod tests { assert!(!b.recovery_guilty() && b.get() == 0); } + #[test] + fn the_oldest_running_render_is_only_suspected_at_first() { + // An innocent slow render that started its tiler just before the hung one is the oldest + // running render. The pass records only suspect it: collateral once, its VM kept. + let (slow, deqp, x) = (vm(), vm(), vm()); + let mut queues = Cascade::new([([58, 59], &slow), ([60, 61], &deqp), ([62, 63], &x), ([64, 65], &x)]); + assert!(!queues.restart_as(59, 1 << 59, Attribution::Suspects(3 << 58))); + assert!(!slow.recovery_guilty() && slow.get() == 0); + // It retires; deqp's render is the oldest running one now and is suspected twice. + queues.retire(58); + queues.restart_as(59, 1 << 61, Attribution::Suspects(3 << 60)); + assert!(!deqp.recovery_guilty()); + queues.restart_as(59, 1 << 61, Attribution::Suspects(3 << 60)); + assert!(deqp.recovery_guilty() && deqp.get() != 0); + assert!(!slow.recovery_guilty() && slow.get() == 0); + } + #[test] fn a_confirmed_first_blame_is_guilty_at_once() { // Evidence (slot identity, the host's pass records or a latched MMU fault) names the VM. diff --git a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs index c9572ff4561e09..d14d48e936d523 100644 --- a/drivers/gpu/drm/asahi/g17/recovery/attribution.rs +++ b/drivers/gpu/drm/asahi/g17/recovery/attribution.rs @@ -61,9 +61,15 @@ pub(crate) struct Sources { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Attribution { +pub(crate) enum Attribution { + /// Only the firmware's blame: unconfirmed. Firmware, + /// Evidence names these queues: slot identity, a latched fault, or a VM an earlier recovery + /// found guilty. Queues(u128), + /// The host's pass records suspect these queues (the oldest running render): unconfirmed, + /// like the firmware's blame. + Suspects(u128), NoCulprit, } @@ -181,17 +187,17 @@ impl Sources { /// When slot identity cannot check a timeout's blame (25G83 reads every key as 0, and a /// single-slot mask has no peer), the host's own pass records still can: a blamed render - /// that never started was starved, not hung. `culprit` names the queues of the one VM whose - /// render started and did not finish; without one the firmware's blame stands. + /// that never started was starved, not hung. `culprit` gives their attribution + /// (`Queues::render_culprit`); without one the firmware's blame stands. pub(super) fn host_fallback( &self, attribution: Attribution, - culprit: impl FnOnce() -> Option, + culprit: impl FnOnce() -> Option, ) -> Attribution { if attribution != Attribution::Firmware || self.reason.is_none_or(|reason| reason == PAGE_FAULT) { return attribution; } - culprit().map_or(Attribution::Firmware, Attribution::Queues) + culprit().unwrap_or(Attribution::Firmware) } } @@ -251,8 +257,10 @@ mod tests { sources.reason = Some(0); let attribution = sources.attribute(Some(36), |_, _| panic!("unknown key")); assert_eq!(attribution, Attribution::Firmware); - assert_eq!(sources.host_fallback(attribution, || Some(3 << 60)), Attribution::Queues(3 << 60)); + assert_eq!(sources.host_fallback(attribution, || Some(Attribution::Suspects(3 << 60))), Attribution::Suspects(3 << 60)); assert_eq!(sources.host_fallback(attribution, || None), Attribution::Firmware); + // The host's records clear every running render (the blamed one never started). + assert_eq!(sources.host_fallback(attribution, || Some(Attribution::NoCulprit)), Attribution::NoCulprit); } #[test] diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index d9860a810757c1..91ed639f1fcca8 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -194,7 +194,7 @@ impl recovery::Queues for Service<'_> { fn render_pass_started(&self, qid: u8, stamp: u64) -> Option { self.firmware.queues.render_pass_started(qid, stamp) } - fn render_culprit(&self, blamed: u8) -> Option { + fn render_culprit(&self, blamed: u8) -> Option { self.firmware.queues.render_culprit(blamed) } fn publish_recovery_targets(&self) -> Option { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs index 1faf45f16a3ebe..4f5620a7a04d29 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/recovery.rs @@ -2,7 +2,7 @@ //! Recovery targets for retained render graphs while firmware is halted. -use crate::g17::{runtime::Registry, status::VmStatus}; +use crate::g17::{recovery::Attribution, runtime::Registry, status::VmStatus}; use kernel::{prelude::*, sync::Arc}; impl Registry { @@ -37,12 +37,13 @@ impl Registry { } /// See `recovery::Queues::render_culprit`. - pub(in crate::g17::runtime) fn render_culprit(&self, blamed: u8) -> Option { + pub(in crate::g17::runtime) fn render_culprit(&self, blamed: u8) -> Option { let pairs = || self.render.entries.iter().flatten().filter_map(|entry| entry.pair.as_ref()); let untouched = pairs().find(|pair| pair.qids().contains(&blamed))?.front_untouched() == Some(true); let running = pairs().filter_map(|pair| { let qids = pair.qids().into_iter().fold(0, |mask, qid| mask | 1u128 << qid); - Some((qids, pair.running_owner()?)) + let (owner, start) = pair.running_start()?; + Some((qids, owner, start)) }); culprit(running, untouched, |culprit| { let mut foreign = false; @@ -66,31 +67,46 @@ impl Registry { } } -/// Picks the QIDs to blame from each pair's running owner. A VM an earlier recovery found guilty -/// comes first, even when the blamed render had started: its groups queued before that keep -/// hanging the GPU one per restart, while bystanders' renders whose tiler started wait behind -/// them, and that recovery failed its interrupted work. Otherwise the blamed render must be -/// `untouched`, exactly one VM may be running, and `foreign` must find no other VM's compute work. +/// Picks the QIDs to blame from each pair's running render: its QIDs, owner and tiler start. A VM +/// an earlier recovery found guilty comes first, even when the blamed render had started: its +/// groups queued before that keep hanging the GPU one per restart, while bystanders' renders whose +/// tiler started wait behind them, and that recovery failed its interrupted work. +/// +/// Otherwise the running render whose tiler started first is the hang: a later one, the blamed +/// one included, started only after it and waits behind it (2026-11-24 01:26 UTC, m4.183: the +/// firmware blamed quickshell twice behind a spinning deqp-vk, whose render was the oldest +/// running one in every recovery). Its VM's running pairs are suspected (`Suspects`), which is +/// not proof: a slow innocent render that started first looks the same, so `classify` treats it +/// like the firmware's blame, collateral once. A blamed render that never started (`untouched`) +/// is never the hang: without a running render, or when `foreign` finds another VM's compute +/// work, which these records cannot see, nobody is named (`NoCulprit`). A started blamed render +/// beside foreign compute keeps the firmware's blame (`None`). fn culprit<'a>( - running: impl Iterator)>, + running: impl Iterator, u64)> + Clone, untouched: bool, foreign: impl FnOnce(&Arc) -> bool, -) -> Option { - let (mut guilty, mut qids, mut several) = (0u128, 0u128, false); - let mut culprit: Option<&Arc> = None; - for (pair, owner) in running { +) -> Option { + let (mut guilty, mut oldest) = (0u128, None::<(&Arc, u64)>); + for (qids, owner, start) in running.clone() { if owner.recovery_guilty() { - guilty |= pair; + guilty |= qids; + } + if oldest.is_none_or(|(_, first)| start < first) { + oldest = Some((owner, start)); } - several |= culprit.is_some_and(|known| !Arc::ptr_eq(known, owner)); - culprit = Some(owner); - qids |= pair; } if guilty != 0 { - return Some(guilty); + return Some(Attribution::Queues(guilty)); + } + let unnamed = untouched.then_some(Attribution::NoCulprit); + let Some((culprit, _)) = oldest else { + return unnamed; + }; + if foreign(culprit) { + return unnamed; } - let culprit = culprit.filter(|_| untouched && !several)?; - (!foreign(culprit)).then_some(qids) + let qids = running.filter(|(_, owner, _)| Arc::ptr_eq(owner, culprit)).fold(0, |all, (qids, ..)| all | qids); + Some(Attribution::Suspects(qids)) } #[kernel::macros::kunit_tests(asahi_g17_render_culprit)] @@ -104,25 +120,41 @@ mod tests { #[test] fn a_guilty_vm_still_running_is_blamed_before_running_bystanders() { let (spinner, bystander) = (vm(), vm()); - let running = || [(0b11, &bystander), (0b1100, &spinner)].into_iter(); - // Two VMs running and no earlier guilt: the firmware's blame stands, even when one of - // them failed only for its own client. - bystander.record(EIO); - assert_eq!(culprit(running(), true, |_| false), None); + // The bystander's render started first here: earlier guilt still decides. + let running = || [(0b11, &bystander, 10), (0b1100, &spinner, 20)].into_iter(); spinner.note_recovery_guilty(); - assert_eq!(culprit(running(), true, |_| panic!("compute is not consulted")), Some(0b1100)); - // The bystander's blamed render whose tiler started is starved too. - assert_eq!(culprit(running(), false, |_| panic!("compute is not consulted")), Some(0b1100)); + assert_eq!(culprit(running(), true, |_| panic!("compute is not consulted")), Some(Attribution::Queues(0b1100))); + assert_eq!(culprit(running(), false, |_| panic!("compute is not consulted")), Some(Attribution::Queues(0b1100))); + } + + #[test] + fn the_oldest_running_render_is_the_culprit() { + // 2026-11-24 01:26 UTC (m4.183, #2504 hang row run 2, T93 fronts): in every recovery the + // spinning deqp-vk pair (51/52) held the running render with the oldest tiler start. + let (deqp, quickshell, hyprland) = (vm(), vm(), vm()); + let deqp_qids = (1u128 << 51) | (1u128 << 52); + // Gen 1: the firmware blamed deqp's own started render, the only one running. + assert_eq!(culprit([(deqp_qids, &deqp, 2583940972)].into_iter(), false, |_| false), Some(Attribution::Suspects(deqp_qids))); + // Gen 2: it blamed quickshell's render, whose tiler started after deqp's. + let gen2 = [(deqp_qids, &deqp, 2585948130), (3 << 42, &quickshell, 2587035310)]; + assert_eq!(culprit(gen2.into_iter(), false, |_| false), Some(Attribution::Suspects(deqp_qids))); + // Gen 3: it blamed quickshell's next render, which never started; Hyprland's started after + // deqp's by 5858 ticks. T94 failed quickshell's VM here for the repeat. + let gen3 = [(3 << 36, &hyprland, 2589025577), (deqp_qids, &deqp, 2589019719)]; + assert_eq!(culprit(gen3.into_iter(), true, |_| false), Some(Attribution::Suspects(deqp_qids))); } #[test] - fn one_running_vm_is_blamed_only_without_foreign_compute() { + fn an_unstarted_render_is_never_the_culprit() { let (a, b) = (vm(), vm()); - assert_eq!(culprit([(0b11, &a), (0b1100, &a)].into_iter(), true, |_| false), Some(0b1111)); - // A blamed render that had started may be the hang itself. - assert_eq!(culprit([(0b11, &a), (0b1100, &a)].into_iter(), false, |_| false), None); - assert_eq!(culprit([(0b11, &a)].into_iter(), true, |_| true), None); - assert_eq!(culprit([(0b11, &a), (0b1100, &b)].into_iter(), true, |_| false), None); - assert_eq!(culprit(core::iter::empty(), true, |_| false), None); + // Nothing runs, or other VMs' compute could be the hang: nobody is blamed. + assert_eq!(culprit(core::iter::empty(), true, |_| false), Some(Attribution::NoCulprit)); + assert_eq!(culprit([(0b11, &a, 5)].into_iter(), true, |_| true), Some(Attribution::NoCulprit)); + // A started blamed render beside foreign compute keeps the firmware's blame. + assert_eq!(culprit([(0b11, &a, 5)].into_iter(), false, |_| true), None); + assert_eq!(culprit(core::iter::empty(), false, |_| false), None); + // All running pairs of the oldest's VM are named, none of another VM. + let running = [(0b11, &a, 5), (0b1100, &b, 3), (0b110000, &b, 9)]; + assert_eq!(culprit(running.into_iter(), true, |_| false), Some(Attribution::Suspects(0b111100))); } } From c139054181d25e17ade710c4b47cedb14c57329f Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 22:35:46 -0300 Subject: [PATCH 1078/1514] drm/asahi: g17: index each frontier's host-timestamp publishers Two readers of a queue's frontier only look for commands that write host timestamps: a render's host-publication links to earlier renders, and a compute command's waits for timestamps it may copy. Few commands publish, but both walked every unfinished command of their prefix to find them, on every enqueue. With pruning no longer the cost, that walk is what makes a deep queue quadratic: on an M4 Pro, vkd3d-proton's test_resolve_image_exhaustive_descriptors held up to 65536 commands in one frontier, and 1366 of the 1854 profile samples its submit thread spent in ASAHI_SUBMIT were this loop, which skips commands without a publication. Keep the publishers of each engine in a second, pruned list as well, and let both readers walk that. The input-source check, which needs every compute publisher of its prefix to have finished, uses it too. Each list is pruned and reserved with its frontier, and its entries are released with the other pruned ones after the ioctl. A publisher can leave its own list while the frontier still holds it behind an older unfinished command: a failure signalled after the prune read the VM's failure counts leaves the frontier's prune front-only. Its readers would then not see that failure in the same enqueue, so a failure is recorded whichever list it leaves first. prune_engine() does both prunes with one callback, and a KUnit case keeps a failed publisher behind an unfinished command and checks it is recorded. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 6 ++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 42 ++++++----- .../gpu/drm/asahi/g17/queue/outstanding.rs | 70 ++++++++++++++++++- 3 files changed, 100 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 1707686b0531ab..28c855e672271f 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -557,6 +557,12 @@ impl super::dependency::Retention for Fences { } impl Fences { + /// The command writes host timestamps: it is ready only once it has completed and the host + /// has written them (see `Scheduler::enqueue`). + pub(crate) fn publishes_timestamps(&self) -> bool { + self.ready.raw() == self.completed.raw() + } + /// Scheduler::enqueue always supplies our explicit completion fence here. /// It has no polling callback, so pending frontier checks need no lock. pub(crate) fn status(&self) -> i32 { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index e10e7b17cf63b9..37cb2afb056602 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -22,7 +22,7 @@ use crate::{ use core::ops::Range; use kernel::{ c_str, - dma_fence::{Fence, FenceContexts, RawDmaFence}, + dma_fence::{Fence, FenceContexts}, prelude::*, sync::{Arc, LockClassKey}, xarray, @@ -112,6 +112,10 @@ pub(crate) struct Queue { /// Each engine's unfinished commands, as many as userspace keeps queued (thousands /// under vkd3d-proton). frontiers: [Outstanding; 2], + /// The frontiers' host-timestamp publishers, again: the only entries the host-publication + /// links and the compute timestamp waits look for. Few commands publish, so those readers + /// walk this instead of every unfinished command. + publishers: [Outstanding; 2], /// Finished frontier entries pruned during this ioctl. Their last references /// can tear a whole completion down; that waits until the ioctl has published. /// Like the frontiers it needs no contiguous pages, and its growth must not fail @@ -167,6 +171,7 @@ impl Queue { proof: Proof::new(), sequence: [0; 2], frontiers: [Outstanding::new(failures), Outstanding::new(failures)], + publishers: [Outstanding::new(failures), Outstanding::new(failures)], finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], _slot: slot, @@ -189,14 +194,13 @@ impl Queue { } fn prune_frontier(&mut self, index: usize) { - let failures = self.context.status().failures(); - let failure = &mut self.failures[index]; - let finished = &mut self.finished; - self.frontiers[index].prune(failures, |sequence, status, fences| { - failure.note(sequence, status, &fences); - // Without room the entry is released here, as it always could be. - let _ = finished.push(fences, GFP_KERNEL_ACCOUNT); - }); + outstanding::prune_engine( + &mut self.frontiers[index], + &mut self.publishers[index], + self.context.status().failures(), + &mut self.failures[index], + &mut self.finished, + ); } #[expect( @@ -242,9 +246,9 @@ impl Queue { && self.frontiers[0] .prefix(order.wait_through[0]) .all(|(_, fences)| fences.status() > 0) - && self.frontiers[1].prefix(order.wait_through[1]).all(|(_, fences)| { - fences.ready.raw() != fences.completed.raw() || fences.status() > 0 - }) + && self.publishers[1] + .prefix(order.wait_through[1]) + .all(|(_, fences)| fences.status() > 0) && self.failures.iter_mut().enumerate().all(|(index, failure)| { failure.earliest().is_none_or(|(sequence, _)| { !Order::contains(order.wait_through[index], sequence) @@ -268,7 +272,7 @@ impl Queue { // can delay host publication. These links never become GPU dependencies. // A finished one may still be held behind an unfinished one: it delays nothing. let host_prefix = if engine == Engine::Render { order.wait_through[index] } else { None }; - let host_predecessors = self.frontiers[index] + let host_predecessors = self.publishers[index] .prefix(host_prefix) .filter_map(|(_, fences)| fences.publication.as_ref().filter(|_| fences.status() <= 0)); let completion = Completion::new( @@ -310,10 +314,8 @@ impl Queue { }; // A finished publisher may still be held behind an unfinished one: its timestamps // are written, so there is nothing to wait for. - let pending_publisher = |fences: &Fences| { - fences.ready.raw() == fences.completed.raw() && fences.status() <= 0 - }; - let timestamps = self.frontiers[index].prefix(timestamp_prefix); + let pending_publisher = |fences: &Fences| fences.status() <= 0; + let timestamps = self.publishers[index].prefix(timestamp_prefix); let timestamp_count = timestamps .clone() .filter(|(_, fences)| pending_publisher(fences)) @@ -420,6 +422,9 @@ impl Queue { .ok_or(ENODEV)? .enqueue(packet, dependencies, early, publication)?; self.sequence[index] = order.sequence; + if fences.publishes_timestamps() { + self.publishers[index].push_within_capacity(order.sequence, fences.clone())?; + } self.frontiers[index].push_within_capacity(order.sequence, fences)?; Ok(()) } @@ -590,6 +595,9 @@ impl crate::queue::Queue for Queue { for (frontier, room) in self.frontiers.iter_mut().zip(room) { frontier.reserve(room)?; } + for (publishers, room) in self.publishers.iter_mut().zip(room) { + publishers.reserve(room)?; + } let mut guards = guards.into_iter(); // Where a firmware wait reports completion before a weak stream tail's writes are // visible, only a command that declares a visible completion is waited for there. diff --git a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs index fea34fb5f2a9c1..87bc1454699b01 100644 --- a/drivers/gpu/drm/asahi/g17/queue/outstanding.rs +++ b/drivers/gpu/drm/asahi/g17/queue/outstanding.rs @@ -16,9 +16,34 @@ //! a prune is given its VM's failure counts and scans the whole list from when a failure starts //! until it has finished and one scan has run after that. -use crate::g17::{job::Order, status::Failures}; +use crate::g17::{ + dependency::{FailureRecord, Retention}, + job::Order, + status::Failures, +}; use kernel::prelude::*; +/// Prunes an engine's frontier and its list of publishers, a subset of it, with the same counts. +/// Each entry that leaves either list goes to `record` and then to `finished`. A publisher can +/// leave its own list while the frontier still holds it behind an older unfinished command, and +/// the readers of that list would then not see its failure, so it is recorded wherever it leaves. +/// One that leaves both lists is recorded twice until it retires. +pub(crate) fn prune_engine( + frontier: &mut Outstanding, + publishers: &mut Outstanding, + failures: Failures, + record: &mut FailureRecord, + finished: &mut KVVec, +) { + let mut left = |sequence, status, entry: T| { + record.note(sequence, status, &entry); + // Without room the entry is released here, as it always could be. + let _ = finished.push(entry, GFP_KERNEL_ACCOUNT); + }; + frontier.prune(failures, &mut left); + publishers.prune(failures, &mut left); +} + /// A command's completion status, as `dma_fence_get_status()`: 0 while unfinished, then 1 or /// a negative error. pub(crate) trait Status { @@ -153,6 +178,12 @@ mod tests { } } + impl Retention for Command { + fn retained(&self) -> bool { + true + } + } + impl Status for Command { fn status(&self) -> i32 { READS.fetch_add(1, Ordering::Relaxed); @@ -265,6 +296,43 @@ mod tests { assert_eq!(prunes, 4 + 1); } + #[test] + fn a_publisher_that_fails_behind_an_unfinished_command_is_recorded() { + // Command 1 is unfinished; command 2 publishes timestamps, so both lists hold it. + let (mut frontier, commands) = queue(2); + let mut publishers = Outstanding::new(0); + publishers.reserve(1).unwrap(); + publishers + .push_within_capacity(2, commands[1].clone()) + .unwrap(); + let mut record = FailureRecord::new(); + let mut finished = KVVec::new(); + let counts = Failures { + started: 0, + finished: 0, + }; + prune_engine( + &mut frontier, + &mut publishers, + counts, + &mut record, + &mut finished, + ); + // Command 2 fails after this prune read the counts, so they have not moved: the + // frontier keeps it behind command 1 and its own list lets it go first. + commands[1].finish(EIO.to_errno()); + prune_engine( + &mut frontier, + &mut publishers, + counts, + &mut record, + &mut finished, + ); + assert_eq!(sequences(frontier.iter()), [1u64, 2]); + assert!(publishers.iter().next().is_none()); + assert_eq!(record.earliest().map(|(sequence, _)| sequence), Some(2)); + } + #[test] fn a_moved_failure_count_scans_the_whole_queue() { let (mut queue, commands) = queue(5); From 4845d063d903e171cf437e2d7a310cbb6512305e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 05:14:57 +1100 Subject: [PATCH 1079/1514] arm64: dts: apple: j615: close the ANE node before the PCIe override The forward merge left the ANE node open before the port00 override. Close it so both J615 variants compile while retaining the ANE status and the CLKREQ property. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615.dts | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index e988835be7fa2e..dc1c4214ab75e0 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -195,6 +195,7 @@ &ane { status = "okay"; +}; /* * The Wi-Fi/Bluetooth module's CLKREQ# is wired to the SoC (the J615 ADT gives From a560eaa3c28fe14b49936d07f87d82fc25829137 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:28:49 -0500 Subject: [PATCH 1080/1514] pmdomain: apple: pmgr-pwrstate: restore apple,min-state after firmware sleep The minimum state of a power state word (bits 19:16) comes from the apple,min-state property and is written once, at probe. A firmware-driven system sleep resets the word, so after the wake a domain with AUTO_ENABLE set comes back with a minimum of 0. The hardware is then free to power-gate the domain whenever its consumer idles. On the M1 (T8103) this hits DISP0's CPU domain, which has a minimum of 4 so the display coprocessor keeps its state while it waits in WFI. After a real sleep the restarted firmware went into WFI while waiting for a reply during the panel's power-on, the domain was power-gated under it, and the display never came back. Put the configured minimum back in the noirq resume of every domain that has one, before the other resync and before any consumer resumes. Domains owned by firmware are left alone, as at probe. Tested on a MacBook Air (M1, J313): two back-to-back real suspend-to-RAM cycles with the display coprocessor bound now bring the internal panel back each time; DISP0's CPU word reads minimum 4 after the wake (0x1404034f) where it read 0 before (0x1f0003ff). Signed-off-by: Erik Bourget --- drivers/pmdomain/apple/pmgr-pwrstate.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index 6745b4916365b6..c40daa58d5e15c 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -639,8 +639,27 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) u32 reg; int ret; - if (!pm_resume_via_firmware() || ps->firmware_owned || ps->inherited_on || - ps->sleep_driver_owned || apple_sleep_domain_is_down(dev->of_node)) + if (!pm_resume_via_firmware() || ps->firmware_owned) + return 0; + + /* + * The wake resets each word's minimum state with the rest, and probe is the only + * place that sets apple,min-state: put it back, whoever owns the domain now. With + * AUTO_ENABLE on and a minimum of 0, the hardware power-gates a domain whose + * coprocessor is only waiting in WFI, as a display coprocessor's CPU does. + */ + if (ps->min_state && ps->min_state <= APPLE_PMGR_PS_ACTIVE) { + spin_lock_irqsave(&ps->genpd.slock, flags); + if (!regmap_read(ps->regmap, ps->offset, ®) && + FIELD_GET(APPLE_PMGR_PS_MIN, reg) != ps->min_state) + regmap_update_bits(ps->regmap, ps->offset, + APPLE_PMGR_FLAGS | APPLE_PMGR_PS_MIN, + FIELD_PREP(APPLE_PMGR_PS_MIN, ps->min_state)); + spin_unlock_irqrestore(&ps->genpd.slock, flags); + } + + if (ps->inherited_on || ps->sleep_driver_owned || + apple_sleep_domain_is_down(dev->of_node)) return 0; spin_lock_irqsave(&ps->genpd.slock, flags); From 227dc13bcc6a86dad4c77774070253c302490abb Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:28:59 -0500 Subject: [PATCH 1081/1514] soc: apple: sart: save entries before a coprocessor idles, restore after an aborted sleep Some coprocessors gate their SART themselves as they go idle for a firmware-driven sleep: ANS on the M1 does once its RTKit IOP state is IDLE, and a read of the SART after that faults. The late suspend can then no longer read the entries it restores at the wake. Add apple_sart_save_now() for the coprocessor's driver to call before it idles the coprocessor. The late suspend keeps that snapshot instead of reading the SART again, and the noirq resume writes it back after a real sleep as before. If the sleep is refused after the snapshot, there is no firmware wake to write the entries back, but the coprocessor has still gated the SART. apple_sart_restore_early() lets the driver write them back itself once the SART answers again. It does nothing when the wake already restored them. The entry write loop moves into a helper used by both paths. Tested on a MacBook Air (M1, J313): real suspend-to-RAM cycles with ANS idled keep storage working, and a sleep refused after ANS was idled now recovers storage ("8 entries written back after a sleep that didn't happen"). Signed-off-by: Erik Bourget --- drivers/soc/apple/sart.c | 72 +++++++++++++++++++++++++++++----- include/linux/soc/apple/sart.h | 2 + 2 files changed, 64 insertions(+), 10 deletions(-) diff --git a/drivers/soc/apple/sart.c b/drivers/soc/apple/sart.c index 44bf2fe4cb915a..14c0e65d19cbbe 100644 --- a/drivers/soc/apple/sart.c +++ b/drivers/soc/apple/sart.c @@ -98,6 +98,10 @@ struct apple_sart { size_t size; } saved[APPLE_SART_MAX_ENTRIES]; bool saved_valid; + /* saved[] filled by apple_sart_save_now() for this sleep */ + bool saved_early; + /* ... and not written back yet: apple_sart_restore_early() */ + bool early_pending; /* saved[] still holds the last sleep's entries, for apple_sart_replay() */ bool replay_valid; }; @@ -430,6 +434,54 @@ static bool apple_sart_wake_writes(struct apple_sart *sart, int i) return sart->saved[i].size && sart->saved[i].flags; } +/* + * For a coprocessor that gates its SART itself as it powers down for the sleep: its + * driver saves the entries before that, and the late suspend keeps them. + */ +void apple_sart_save_now(struct apple_sart *sart) +{ + int i; + + for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) + sart->ops->get_entry(sart, i, &sart->saved[i].flags, + &sart->saved[i].paddr, &sart->saved[i].size); + sart->saved_early = true; + sart->early_pending = true; +} +EXPORT_SYMBOL_GPL(apple_sart_save_now); + +static unsigned int apple_sart_write_saved(struct apple_sart *sart) +{ + unsigned int restored = 0; + int i; + + for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) { + if (!apple_sart_wake_writes(sart, i)) + continue; + sart->ops->set_entry(sart, i, sart->saved[i].flags, + sart->saved[i].paddr >> sart->ops->paddr_shift, + sart->saved[i].size >> sart->ops->size_shift); + restored++; + } + return restored; +} + +/* + * After apple_sart_save_now(), when the sleep didn't happen: its coprocessor gated the SART + * all the same, so its driver writes the entries back once the SART answers again. Nothing + * to do when the wake has written them already. + */ +void apple_sart_restore_early(struct apple_sart *sart) +{ + sart->saved_early = false; + if (!sart->early_pending) + return; + sart->early_pending = false; + dev_info(sart->dev, "%u entries written back after a sleep that didn't happen\n", + apple_sart_write_saved(sart)); +} +EXPORT_SYMBOL_GPL(apple_sart_restore_early); + /* * A SART in a domain that a firmware-driven suspend powers off comes back empty, * and its coprocessor can't reach its firmware or buffers until the entries are @@ -440,6 +492,13 @@ static int apple_sart_suspend_late(struct device *dev) struct apple_sart *sart = dev_get_drvdata(dev); int i; + if (sart->saved_early) { + sart->saved_early = false; + sart->replay_valid = false; + sart->saved_valid = pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware(); + return 0; + } sart->saved_valid = false; sart->replay_valid = false; if (pm_suspend_target_state != PM_SUSPEND_MEM || !pm_suspend_via_firmware()) @@ -456,21 +515,14 @@ static int apple_sart_suspend_late(struct device *dev) static int apple_sart_resume_noirq(struct device *dev) { struct apple_sart *sart = dev_get_drvdata(dev); - unsigned int restored = 0; - int i; + unsigned int restored; if (!sart->saved_valid || !pm_resume_via_firmware()) return 0; sart->saved_valid = false; + sart->early_pending = false; - for (i = 0; i < APPLE_SART_MAX_ENTRIES; i++) { - if (!apple_sart_wake_writes(sart, i)) - continue; - sart->ops->set_entry(sart, i, sart->saved[i].flags, - sart->saved[i].paddr >> sart->ops->paddr_shift, - sart->saved[i].size >> sart->ops->size_shift); - restored++; - } + restored = apple_sart_write_saved(sart); dev_dbg(dev, "%u entries restored after sleep\n", restored); sart->replay_valid = true; diff --git a/include/linux/soc/apple/sart.h b/include/linux/soc/apple/sart.h index 5bfa06041dc7dc..e101f4fa19edf0 100644 --- a/include/linux/soc/apple/sart.h +++ b/include/linux/soc/apple/sart.h @@ -26,6 +26,8 @@ struct apple_sart; * apple_sart_add_allowed_region and apple_sart_remove_allowed_region. */ struct apple_sart *devm_apple_sart_get(struct device *dev); +void apple_sart_save_now(struct apple_sart *sart); +void apple_sart_restore_early(struct apple_sart *sart); /* * Adds the region [paddr, paddr+size] to the DMA allow list. From d1c60cd41b35b21ecffa43f862ac81f60602b50f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:29:08 -0500 Subject: [PATCH 1082/1514] soc: apple: rtkit: add apple_rtkit_mbox_restore() for a coprocessor that lost power When a firmware-driven sleep takes a coprocessor's power, its mailbox loses its configuration with it, including the receive enable. On the M1 the boot loader sets that enable for ANS, and nothing in Linux sets it again, so after the wake none of the coprocessor's messages reach the AP and its RTKit handshake times out. Add apple_rtkit_mbox_restore(), for a driver that starts its coprocessor cold after such a sleep: it restores the mailbox and sets the receive enable, before the coprocessor runs. Tested on a MacBook Air (M1, J313) with the NVMe driver calling it after real suspend-to-RAM cycles: ANS's handshake completes with no retries. Signed-off-by: Erik Bourget --- drivers/soc/apple/rtkit.c | 15 +++++++++++++++ include/linux/soc/apple/rtkit.h | 1 + 2 files changed, 16 insertions(+) diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index d25c7e2f106f52..a5f0eeb10d421e 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -3536,6 +3536,21 @@ int apple_rtkit_wake_retained(struct apple_rtkit *rtk, int (*start)(void *), voi } EXPORT_SYMBOL_GPL(apple_rtkit_wake_retained); +/* + * After a sleep that took the co-processor's power, its mailbox's enables are gone with + * it: set them again before the co-processor is started, or its messages never arrive. + * The receive enable is one the boot loader sets on M1, which Linux doesn't set otherwise. + */ +int apple_rtkit_mbox_restore(struct apple_rtkit *rtk) +{ + int ret = apple_mbox_restore(rtk->mbox); + + if (!ret) + apple_mbox_set_recv_enabled(rtk->mbox, true); + return ret; +} +EXPORT_SYMBOL_GPL(apple_rtkit_mbox_restore); + void apple_rtkit_free(struct apple_rtkit *rtk) { apple_rtkit_stop_rx(rtk); diff --git a/include/linux/soc/apple/rtkit.h b/include/linux/soc/apple/rtkit.h index 7017f1786373c6..db6a13099ce647 100644 --- a/include/linux/soc/apple/rtkit.h +++ b/include/linux/soc/apple/rtkit.h @@ -292,6 +292,7 @@ int apple_rtkit_shutdown(struct apple_rtkit *rtk); */ int apple_rtkit_poweroff(struct apple_rtkit *rtk); +int apple_rtkit_mbox_restore(struct apple_rtkit *rtk); /* * After poweroff and a power cycle: start a fresh session, let @start start the From 7dfc208abc18e053db5cc9ec852f33c35502545b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:29:40 -0500 Subject: [PATCH 1083/1514] nvme-apple: idle ANS for a firmware sleep and start it cold after the wake On controllers whose RTKit session doesn't stay up across a sleep (no I/O queue registers, the M1 class), a firmware-driven suspend shut ANS down with AP QUIESCED and IOP SLEEP. Measured on the M1 (J313), ANS then doesn't bring its flash links back after the power-on, and storage is gone after the wake. For a firmware sleep, put ANS in IDLE instead, its AP and its IOP state, as for a sleep it is woken from; it then brings its flash links back itself after its power-on. In IDLE it gates its SART, so its entries (apple_sart_save_now()) and the NVMe block's word that gates it are saved first. After a real sleep the reset work starts ANS from its power-on: out of reset, it puts the SART power word back, restores the mailbox's enables (apple_rtkit_mbox_restore()) and sets the run bit, then runs the normal boot handshake. A sleep refused after ANS was idled leaves it idle with its SART gated and no firmware wake follows. The resume takes the same cold start, and writes the SART entries back itself (apple_sart_restore_early()). If the idle itself fails, the suspend fails and no resume follows, so the cold start is queued at once. Other sleeps (suspend-to-idle) keep apple_rtkit_shutdown(). Tested on a MacBook Air (M1, J313): two back-to-back real suspend-to-RAM cycles bring storage back each time (ANS's handshake with no retries, rootfs read-write, 16 MiB write and read), and a sleep refused after ANS was idled recovers storage. Signed-off-by: Erik Bourget --- drivers/nvme/host/apple.c | 65 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 435ef9b7ae0829..e767f411c42ecd 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -58,6 +58,11 @@ #define APPLE_ANS_COPROC_CPU_CONTROL 0x44 #define APPLE_ANS_COPROC_CPU_CONTROL_RUN BIT(4) #define APPLE_ANS_COPROC_CPU_STATUS 0x48 +/* + * A word of the NVMe block that gates its SART (measured on M1). The boot loader leaves 1 + * here, and a firmware sleep, which takes ANS's power, leaves 0: put back before ANS runs again. + */ +#define APPLE_ANS_SART_POWER 0x13e8 #define APPLE_ANS_ACQ_DB 0x1004 #define APPLE_ANS_IOCQ_DB 0x100c @@ -274,6 +279,12 @@ struct apple_nvme { u32 sleep_csts; /* ANS came back across a sleep, or failed to. reset_work picks these up. */ bool sleep_restarted; + /* A firmware sleep took ANS's power: its next start is from that power-on */ + bool fw_sleep_restart; + /* This suspend idled ANS for a firmware sleep, whether or not the sleep happened */ + bool fw_sleep_idled; + /* The SART power word as it was before that sleep */ + u32 sart_power; bool sleep_failed; /* Run bit set after a sleep, and not yet reported on. */ bool sleep_restarting; @@ -1781,6 +1792,7 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) container_of(work, struct apple_nvme, ctrl.reset_work); enum nvme_ctrl_state state = nvme_ctrl_state(&anv->ctrl); bool inherited = !anv->owns_rtkit; + bool fw_sleep; if (anv->hw->needs_ioq_registers) { mutex_lock(&anv->disable_lock); @@ -1921,6 +1933,9 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) goto booted; } + fw_sleep = READ_ONCE(anv->fw_sleep_restart); + WRITE_ONCE(anv->fw_sleep_restart, false); + ret = reset_control_assert(anv->reset); if (ret) goto out; @@ -1933,10 +1948,27 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) if (ret) goto out; + /* + * After a firmware sleep, out of reset and before the run bit: the SART's + * power word, and the mailbox's enables, which went with ANS's power. + */ + if (fw_sleep) { + if (readl(anv->mmio_nvme + APPLE_ANS_SART_POWER) != anv->sart_power) + writel(anv->sart_power, anv->mmio_nvme + APPLE_ANS_SART_POWER); + /* Only after a sleep that didn't happen: the wake wrote them already. */ + if (anv->sart) + apple_sart_restore_early(anv->sart); + ret = apple_rtkit_mbox_restore(anv->rtk); + if (ret) + goto out; + } + writel(APPLE_ANS_COPROC_CPU_CONTROL_RUN, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); ret = apple_rtkit_boot(anv->rtk); + if (fw_sleep && !ret) + dev_info(anv->dev, "ANS: on after the sleep\n"); } else { ret = apple_rtkit_wake(anv->rtk); } @@ -3111,6 +3143,14 @@ static int apple_nvme_resume(struct device *dev) WRITE_ONCE(anv->suspended, false); return nvme_try_sched_reset(&anv->ctrl); } + /* + * A firmware sleep took ANS's power: the reset work starts it from that power-on. A + * sleep that didn't happen after ANS was idled for it leaves it idle with its SART + * gated: the same start, from its reset, with the SART's entries written back. + */ + if (anv->rtk && (pm_resume_via_firmware() || anv->fw_sleep_idled)) + WRITE_ONCE(anv->fw_sleep_restart, true); + anv->fw_sleep_idled = false; return nvme_reset_ctrl(&anv->ctrl); } @@ -3271,9 +3311,32 @@ static int apple_nvme_suspend(struct device *dev) } if (apple_rtkit_is_running(anv->rtk)) { - ret = apple_rtkit_shutdown(anv->rtk); + if (pm_suspend_target_state == PM_SUSPEND_MEM && pm_suspend_via_firmware()) { + /* + * A firmware sleep takes ANS's power. ANS is put in IDLE, both + * the AP's state and its own, as for a sleep it is woken from: + * after its power-on it then brings its flash links back itself. + * In IDLE it gates its SART, so the SART's entries and the word + * that gates it are read before that. + */ + anv->sart_power = readl(anv->mmio_nvme + APPLE_ANS_SART_POWER); + if (anv->sart) + apple_sart_save_now(anv->sart); + anv->fw_sleep_idled = true; + ret = apple_rtkit_idle(anv->rtk); + if (!ret) + ret = apple_rtkit_reinit(anv->rtk); + } else { + ret = apple_rtkit_shutdown(anv->rtk); + } writel(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); + /* Refused here, so no resume follows: ANS starts again now, from its reset. */ + if (ret && anv->fw_sleep_idled) { + anv->fw_sleep_idled = false; + WRITE_ONCE(anv->fw_sleep_restart, true); + nvme_reset_ctrl(&anv->ctrl); + } } return ret; From a2ec09f1d98fc9d5b1f76b9a3f0b01e6a202b66d Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:30:00 -0500 Subject: [PATCH 1084/1514] iommu: apple-dart: power T8020 display DARTs down and up with their DCP apple_dart_display_streams() is what a DCP driver calls around its firmware stop and restart, but it only knows the T8110 layout: on a T8020-type DART (the M1's) it writes registers that don't exist there. Add the T8020 counterpart, selected by the DART's type. At the power-down it saves the DART's translations and enabled streams, turns the given streams off, flushes their TLB entries when asked to, and marks the DART off (host_off), so neither its interrupt handler nor its suspend reads a block whose power is about to go: on the M1 both display DARTs sit in the DCP's CPU domain and share one interrupt line. At the power-up it clears any latched error, writes the translations back if they were lost and the DART isn't locked (it refuses if it is), re-enables the saved streams and invalidates every TLB entry, since maps made while it was off only reached memory. The DCP's own power cycle resets the display DART, lock included, so the write-back runs at every DPMS power-up there; after a real sleep the boot loader's wake has set it up locked again and the translations are found intact. Tested on a MacBook Air (M1, J313): DPMS off and on with the DCP's firmware stop and restart, twice, and two back-to-back real suspend-to-RAM cycles, with no DART faults. Signed-off-by: Erik Bourget --- drivers/iommu/apple-dart.c | 99 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bf7a4fc0807faa..23a837280370b7 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -398,6 +398,9 @@ struct apple_dart { bool display_dark; bool display_tlb_stale; DECLARE_BITMAP(display_tcr_four, DART_MAX_STREAMS); + /* T8020: its enabled streams and translations, saved at the display's power-down */ + u32 display_enable; + bool display_saved; /* The address filter the loader programs, from the device tree, replayed after a sleep. */ void __iomem *dapf; u64 *dapf_ranges; @@ -8040,6 +8043,99 @@ int apple_dart_gapf_ready(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_gapf_ready); +/* + * T8020-type display DARTs, around their DCP's power-down. On the M1 both of them are + * in the DCP's CPU domain and share one interrupt, so from the power-down to the + * power-up neither is read (host_off), and maps go to memory only (display_dark). + * + * The DCP's power cycle resets the display DART, its lock included (measured on J313), + * while the boot loader's wake after a real sleep sets it up locked again. So at the + * power-up the translations saved at the power-down are written back when they were + * lost and the DART is unlocked; lost and still locked, it stays off. + */ +static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams, bool on, + bool flush) +{ + struct apple_dart_stream_map map = { .dart = dart }; + void __iomem *enable = dart->regs + dart->hw->enable_streams; + unsigned long bits = streams; + unsigned int sid, idx; + u32 error; + int ret = 0; + + if (on) { + if (!READ_ONCE(dart->host_off) && !READ_ONCE(dart->display_dark)) + return 0; + if (dart->display_saved && !apple_dart_state_retained(dart)) { + /* Not rewritable: it stays off and dark, and its streams stay off. */ + if (apple_dart_is_locked(dart)) { + dev_err(dart->dev, "translations lost at the power-down, and locked\n"); + return -EIO; + } + /* Reset with its domain: set up as at a resume, with its translations */ + ret = apple_dart_hw_reset(dart); + if (ret && ret != -EBUSY) + dev_warn(dart->dev, "reset at power-on: %d\n", ret); + for (sid = 0; sid < dart->num_streams; sid++) { + for (idx = 0; idx < dart->hw->ttbr_count; idx++) + writel(dart->save_ttbr[sid][idx], + dart->regs + DART_TTBR(dart, sid, idx)); + writel(dart->save_tcr[sid], dart->regs + DART_TCR(dart, sid)); + } + ret = 0; + dev_dbg(dart->dev, "translations put back at power-on\n"); + } + error = readl(dart->regs + DART_T8020_ERROR); + if (error & DART_T8020_ERROR_FLAG) + writel(error, dart->regs + DART_T8020_ERROR); + if (dart->display_saved) + writel(readl(enable) | (dart->display_enable & streams), enable); + /* Maps and unmaps while it was off left their invalidations to here. */ + bitmap_fill(map.sidmap, dart->num_streams); + if (dart->hw->invalidate_tlb(&map)) + dev_err(dart->dev, "TLB invalidation at power-on failed\n"); + dart->host_off_slept = false; + dart->display_saved = false; + dart->sleep_flushed = false; + WRITE_ONCE(dart->display_tlb_stale, false); + WRITE_ONCE(dart->display_dark, false); + WRITE_ONCE(dart->host_off, false); + return ret; + } + + /* + * The first power-down call sets it off, flushed or not (the display DART's comes from + * its firmware, without a flush). A later one, as after a sleep that didn't reach the + * commit, may find the domains off already, and leaves it. + */ + if (READ_ONCE(dart->host_off)) + return 0; + if (!READ_ONCE(dart->display_dark)) { + apple_dart_save_state(dart); + dart->display_enable = readl(enable); + dart->display_saved = true; + for (sid = 0; sid < dart->num_streams; sid++) + __assign_bit(sid, dart->display_tcr_four, + dart->save_tcr[sid] & dart->hw->tcr_4level); + WRITE_ONCE(dart->display_dark, true); + } + writel(readl(enable) & ~streams, enable); + if (flush) { + for_each_set_bit(sid, &bits, dart->num_streams) + set_bit(sid, map.sidmap); + ret = dart->hw->invalidate_tlb(&map); + if (ret) { + dev_err(dart->dev, "flush for a power-down failed: %d\n", ret); + return ret; + } + dart->sleep_flushed = true; + } + /* Its interrupt handler checks this before it reads anything. */ + WRITE_ONCE(dart->host_off, true); + + return 0; +} + /* * What macOS writes to T8140's display DARTs around a display power cycle: * measured under aura, with the offsets the driver has no name for. It never @@ -8057,6 +8153,9 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl u32 status; int ret; + if (dart->hw->type == DART_T8020) + return apple_dart_t8020_display_streams(dart, streams, on, flush); + if (on) { apple_dart_gapf_protect(dart); dart->sleep_flushed = false; From 66d59d1cde6b08cbcb78d6b943d0c2f71be275ea Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:30:05 -0500 Subject: [PATCH 1085/1514] dt-bindings: display: apple,t8140-display-power: add T8103 The M1's display has a power state block only for its display power words: no retention words, and its PMC keeps no count of the powered coprocessors. Add apple,t8103-display-power with a single "ps" region, and allow one to three reg entries. Signed-off-by: Erik Bourget --- .../display/apple,t8140-display-power.yaml | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml index 7d157451342678..bf1e48cedd9047 100644 --- a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml @@ -4,7 +4,7 @@ $id: http://devicetree.org/schemas/display/apple,t8140-display-power.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple T8140 and T8142 display power words +title: Apple T8103, T8140 and T8142 display power words maintainers: - Diljit Singh @@ -18,15 +18,16 @@ description: properties: compatible: enum: + - apple,t8103-display-power - apple,t8140-display-power - apple,t8142-display-power reg: - minItems: 2 + minItems: 1 maxItems: 3 reg-names: - minItems: 2 + minItems: 1 maxItems: 3 required: @@ -35,6 +36,19 @@ required: - reg-names allOf: + - if: + properties: + compatible: + const: apple,t8103-display-power + then: + # T8103's display has no retention words and its PMC no count of the coprocessors. + properties: + reg: + items: + - description: the power manager's power state words + reg-names: + items: + - const: ps - if: properties: compatible: From 9f1ba6bd17b2a1e13f2856c3ef3e8f2ed8816ec4 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:31:10 -0500 Subject: [PATCH 1086/1514] drm/apple: dcp: leave the firmware stop and restart alone without an RTKit session Unbinding one DCP from the display subsystem unbinds the whole aggregate, and with it every DCP component's resources: the RTKit session of a DCP whose platform device stays bound is freed and dcp->rtk is NULL. Its system sleep callbacks still run, and after the next wake the queued firmware restart dereferenced the NULL session in apple_rtkit_detach_rx(). Without an RTKit session there is no firmware of this driver's to stop or start: the system suspend and resume paths return early, the prewarm work doesn't run, and the warm restart refuses. Seen on a MacBook Air (M1, J313) with the external DCP unbound before a real suspend-to-RAM: an oops in the prewarm work after the wake. With this change that sequence resumes without one. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 556e5cfee9bf00..fa72d65b5bb0eb 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9093,6 +9093,13 @@ static int dcp_s2r_suspend(struct apple_dcp *dcp) bool was_off; int ret; + /* + * Not bound into the display subsystem (a component unbind released the RTKit + * session): nothing of the firmware is this driver's to stop. + */ + if (IS_ERR_OR_NULL(dcp->rtk)) + return 0; + /* Still stopped from a suspend that never reached the commit. */ if (READ_ONCE(dcp->s2r_fw_down)) { dcp_s2r_stop_failed_start(dcp); @@ -9498,6 +9505,8 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) { int ret; + if (IS_ERR_OR_NULL(dcp->rtk)) + return -ENODEV; dcp_s2r_forget_crash(dcp); ret = dcp_s2r_domains_on(dcp); if (ret) @@ -9663,6 +9672,9 @@ static int dcp_s2r_resume(struct apple_dcp *dcp) bool real = pm_resume_via_firmware(); dcp->s2r_stopped = false; + /* No RTKit session since the suspend stopped it: nothing to start. */ + if (IS_ERR_OR_NULL(dcp->rtk)) + return 0; /* A real sleep took the domains' power. */ if (real) dcp->s2r_domains_up = false; @@ -9896,7 +9908,8 @@ static void dcp_s2r_prewarm_work(struct work_struct *work) guard(mutex)(&dcp->s2r_prewarm_lock); light = dcp->s2r_wake_light; dcp->s2r_wake_light = false; - if (!dcp->dpms_powered_off || !READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->crashed)) + if (!dcp->dpms_powered_off || !READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->crashed) || + IS_ERR_OR_NULL(dcp->rtk)) return; dcp_s2r_find_darts(dcp); ret = dcp_s2r_warm_restart(dcp); From ccfca33d008422e972e874b8e1bd3a9d21268ac9 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:31:15 -0500 Subject: [PATCH 1087/1514] drm/apple: dcp: allow display power layouts without system or retention words The firmware stop lowers and raises a SoC's display domains from its dcp_s2r_layout: CPU, front end and system words, and retention words in the power gate block. Some SoCs have neither a system word for the display nor retention words for its CPU. A layout with no system word has 0 there, which is another domain's word: skip it when lowering, raising or logging. Map the "pwrgate" region only for a layout with retention words, and don't require it otherwise. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp.c | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index fa72d65b5bb0eb..d237c6ac47abfc 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9159,7 +9159,7 @@ static void dcp_s2r_ps_lower(void __iomem *reg) writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), reg); } -/* Its display-power words, pmc-dcp only where the layout has one. */ +/* Its display-power words, pwrgate and pmc-dcp only where the layout has them. */ static int dcp_s2r_map_power(struct apple_dcp *dcp, void __iomem **ps, void __iomem **pwrgate, void __iomem **pmc) { @@ -9170,12 +9170,14 @@ static int dcp_s2r_map_power(struct apple_dcp *dcp, void __iomem **ps, void __io if (!np) return -ENODEV; *ps = of_iomap(np, of_property_match_string(np, "reg-names", "ps")); - *pwrgate = of_iomap(np, of_property_match_string(np, "reg-names", "pwrgate")); + if (dcp_s2r_layout(dcp)->ret_ff) + *pwrgate = of_iomap(np, of_property_match_string(np, "reg-names", "pwrgate")); if (dcp_s2r_layout(dcp)->pmc_dcp) *pmc = of_iomap(np, of_property_match_string(np, "reg-names", "pmc-dcp")); of_node_put(np); - return *ps && *pwrgate && (*pmc || !dcp_s2r_layout(dcp)->pmc_dcp) ? 0 : -ENODEV; + return *ps && (*pwrgate || !dcp_s2r_layout(dcp)->ret_ff) && + (*pmc || !dcp_s2r_layout(dcp)->pmc_dcp) ? 0 : -ENODEV; } /* macOS's power-off, measured 3 of 3 on T8140. The firmware is stopped and its DARTs are off. */ @@ -9211,14 +9213,17 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) } dcp_s2r_ps_lower(ps + l->disp_cpu); dcp_s2r_ps_lower(ps + l->disp_fe); - dcp_s2r_ps_lower(ps + l->disp_sys); + /* A layout without a system word has 0 there, a different domain's word. */ + if (l->disp_sys) + dcp_s2r_ps_lower(ps + l->disp_sys); ret = readl_poll_timeout(ps + l->disp_cpu, val, !FIELD_GET(GENMASK(7, 4), val), 100, 50000); if (ret) dev_err(dcp->dev, "DISP_CPU did not power off: %#x\n", val); dev_dbg(dcp->dev, "display domains off: CPU %#x FE %#x SYS %#x\n", - readl(ps + l->disp_cpu), readl(ps + l->disp_fe), readl(ps + l->disp_sys)); + readl(ps + l->disp_cpu), readl(ps + l->disp_fe), + l->disp_sys ? readl(ps + l->disp_sys) : 0); out: if (ps) iounmap(ps); @@ -9245,9 +9250,11 @@ static int dcp_s2r_domains_on(struct apple_dcp *dcp) if (ret) goto out; - val = readl(ps + l->disp_sys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); - writel(val | 0xf, ps + l->disp_sys); - writel(val | 0xf | BIT(28), ps + l->disp_sys); + if (l->disp_sys) { + val = readl(ps + l->disp_sys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + writel(val | 0xf, ps + l->disp_sys); + writel(val | 0xf | BIT(28), ps + l->disp_sys); + } val = readl(ps + l->disp_fe) & ~(GENMASK(9, 8) | GENMASK(3, 0)); writel(val | 0xf, ps + l->disp_fe); val = readl(ps + l->disp_cpu) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); From 0be1d26e4715699d6126e50db7f0c7f4d359891b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:31:24 -0500 Subject: [PATCH 1088/1514] drm/apple: map firmware 27's register windows through the DCP's DART where needed The DCP asks for its display register windows with map_reg. For firmware 27 the reply hands back their physical addresses as the device address, since the H17P firmware reaches them physically. On the M1 the 27.2 firmware reaches them through its DART instead: at its first power-down it faulted on an unmapped window (stream 0, a disp-4 address) and crashed. Let a SoC say so with hw.map_reg_dart: the window is then mapped in the DCP's DART with dma_map_resource(), once per window, and that mapping is the reply's device address. The physical address stays in the reply's address field. Tested on a MacBook Air (M1, J313) with the T8103 DCP data that sets it: the firmware's DPMS power-down and restart run twice with no DART fault. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp-internal.h | 7 +++++++ drivers/gpu/drm/apple/iomfb_template.c | 14 ++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 84c0232be52dc1..40f7ab8633f146 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -370,6 +370,11 @@ struct apple_dcp_hw_data { * for one second. */ unsigned int afk_timeout_ms; + /* + * Firmware 27 reaches its register windows through its DART here, so map_reg maps + * them there (T8103: its power-down faults on an unmapped window otherwise). + */ + bool map_reg_dart; }; enum dcp_test_point { @@ -728,6 +733,8 @@ struct apple_dcp { /* Display registers mappable to the DCP */ struct resource *disp_registers[MAX_DISP_REGISTERS]; + /* Their DART mappings with hw.map_reg_dart, made at the firmware's first map_reg */ + dma_addr_t map_reg_dva[MAX_DISP_REGISTERS]; unsigned int nr_disp_registers; struct resource disp_bw_scratch_res; diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 78f3a29b9b405b..31682c7d245b8b 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -1483,8 +1483,7 @@ static u64 dcpep_cb_get_frequency(struct apple_dcp *dcp) return clk_get_rate(dcp->clk); } -#if DCP_FW_VER >= DCP_FW_VERSION(13, 2, 0) && !DCP_FW_H17(DCP_FW_VER) && \ - !DCP_FW_DESKTOP_26(DCP_FW_VER) +#if DCP_FW_VER >= DCP_FW_VERSION(13, 2, 0) && !DCP_FW_DESKTOP_26(DCP_FW_VER) /* The DVA that map_reg hands out for display register range @index. */ static dma_addr_t dcpep_map_reg_dva(struct apple_dcp *dcp, u32 index, struct resource *rsrc) @@ -1531,6 +1530,17 @@ static struct DCP_FW_NAME(dcp_map_reg_resp) dcpep_cb_map_reg(struct apple_dcp *d */ dma_addr_t dva = dcp->fw_compat == DCP_FIRMWARE_V_27_0 ? dcp->disp_firmware_base[req->index] : rsrc->start; + + /* Where firmware 27 goes through its DART: mapped there, once. */ + if (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && dcp->hw.map_reg_dart) { + if (!dcp->map_reg_dva[req->index]) { + dva = dcpep_map_reg_dva(dcp, req->index, rsrc); + if (WARN_ON(dva == DMA_MAPPING_ERROR)) + return (struct DCP_FW_NAME(dcp_map_reg_resp)) { .ret = 1 }; + dcp->map_reg_dva[req->index] = dva; + } + dva = dcp->map_reg_dva[req->index]; + } #elif DCP_FW_DESKTOP_26(DCP_FW_VER) /* * The desktop 26.x firmware takes the register windows' From 65beae90bb5a1a92493518b1f85a4ba5f7d36650 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:31:32 -0500 Subject: [PATCH 1089/1514] drm/apple: dcp: power the display DART down and up with the coprocessor where asked The firmware stop expects the firmware to turn the display DART's streams off itself (D572) before the DCP's domains go down, and on again after its restart. On the M1 no such call reaches the driver, and the DCP's power-down resets the display DART, so after a restart its streams had no translations and the firmware crashed on its first PIODMA transfer. With hw.s2r_disp_dart_with_dcp the driver does it itself: the display DART goes down with the DCP's own DART at the firmware stop, and comes back, with its translations, right after the domains are raised and before the firmware runs. Tested on a MacBook Air (M1, J313) with the T8103 DCP data that sets it: two DPMS power cycles and two real suspend-to-RAM cycles with the DCP restarting each time, and no DART fault. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp-internal.h | 5 +++++ drivers/gpu/drm/apple/dcp.c | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 40f7ab8633f146..276bcaf548899f 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -375,6 +375,11 @@ struct apple_dcp_hw_data { * them there (T8103: its power-down faults on an unmapped window otherwise). */ bool map_reg_dart; + /* + * The display DART goes off and on with the coprocessor's own stop and start: no + * D572 turns it off first, and the stop's power-down resets it (T8103). + */ + bool s2r_disp_dart_with_dcp; }; enum dcp_test_point { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index d237c6ac47abfc..420f29871830a1 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -8873,8 +8873,16 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) /* Its power state can only be lowered once this has finished. */ static int dcp_s2r_stop_streams(struct apple_dcp *dcp) { + int ret; + if (!dcp->s2r_dcp_dart) return -ENODEV; + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, false, true); + if (ret) + return ret; + } return apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, false, true); @@ -9526,6 +9534,13 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) if (dcp->s2r_dcp_dart) apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, true, false); + /* Set up again before the firmware runs, which uses it right away. */ + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, true, false); + if (ret) + return ret; + } if (dcp->secure_rtk) { dcp_secure_poll_stop(dcp); From 92e0afdc59bde258c3d06ce1592738083f5f4fdb Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:31:42 -0500 Subject: [PATCH 1090/1514] drm/apple: dcp: stop and restart the T8103 DCP's firmware around DPMS off and sleep Add T8103 (M1) match data with the firmware stop (hw.s2r): DPMS off and a firmware-driven system sleep stop the DCP's firmware and lower its display domains, and DPMS on or the wake restarts it warm, as on T8140. The layout is T8103's display power words: DISP0's CPU (0x10018) and front end (0x360), no system word and no retention words. The DCP's own DART stream is 0; the display DART's are 0 (the display) and 4 (its PIODMA). The SoC has no secure DCP mailbox, its firmware 27 reaches its register windows through the DART, and the display DART goes down and up with the coprocessor. The stop needs firmware 27, whose 27.2 method table has the AP link's release, and apple,display-power in the device tree; without either the DCP keeps its firmware running across DPMS and sleep, as before. Tested on a MacBook Air (M1, J313, firmware 27.2): DPMS off and on twice, and two back-to-back real suspend-to-RAM cycles with both DCPs bound, the internal panel coming back each time with its backlight and SDDM. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp.c | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 420f29871830a1..992401935b5740 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -8626,6 +8626,18 @@ static const struct dcp_s2r_layout dcp_s2r_t8142 = { .pmc_dcp = false, }; +/* + * T8103's, from its device tree: DISP0's CPU (0x10018) and front end (0x360) power words, + * and no system word or retention words. The DCP's firmware DART has its stream 0, the + * display DART streams 0 and 4 (the display and its PIODMA). + */ +static const struct dcp_s2r_layout dcp_s2r_t8103 = { + .disp_cpu = 0x10018, + .disp_fe = 0x360, + .dcp_streams = BIT(0), + .disp_streams = BIT(0) | BIT(4), +}; + /* TEST: J813 external processors, ADT DISPEXT0/1 power words. */ static const struct dcp_s2r_layout dcp_s2r_t8142_ext[] = { { .disp_cpu = 0x428, .disp_fe = 0x418, .disp_sys = 0x308, @@ -8699,8 +8711,9 @@ void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) static bool dcp_s2r_capable(struct apple_dcp *dcp) { /* - * Firmware 27.2 and 27.3 run as V_27_0 with their own tables, which have no tag for the - * AP link's release (27.2 moved it to A550): an empty tag panics the firmware. + * Firmware 27.2 and 27.3 run as V_27_0 with their own tables. 27.2's has the AP link's + * release (A550); a table without a tag for it can't stop: an empty tag panics the + * firmware. */ if (dcp->fw_compat == DCP_FIRMWARE_V_27_0 && (!dcp->v27_methods || !dcp->v27_methods[dcpep_unnamed_500].tag[0])) @@ -10432,6 +10445,16 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8142 = { .s2r_layout = &dcp_s2r_t8142, }; +/* T8103's DCP: the firmware stop around DPMS off and system sleep, with its own power words */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103 = { + .num_dptx_ports = 0, + .s2r = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { .num_dptx_ports = 0, }; @@ -10564,6 +10587,7 @@ static const struct of_device_id of_match[] = { { .compatible = "apple,t6050-dcpext", .data = &apple_dcp_hw_t6050_dcpext }, { .compatible = "apple,t6020-dcp", .data = &apple_dcp_hw_t6020, }, { .compatible = "apple,t6020-dcpext", .data = &apple_dcp_hw_t6020_dcpext, }, + { .compatible = "apple,t8103-dcp", .data = &apple_dcp_hw_t8103, }, { .compatible = "apple,t8112-dcp", .data = &apple_dcp_hw_t8112, }, { .compatible = "apple,t8140-dcp", .data = &apple_dcp_hw_t8140, }, { .compatible = "apple,t8140-dcpext", .data = &apple_dcp_hw_t8140_external, }, From de9d80c990cc065f9d2324c0795711c2059f436e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:32:18 -0500 Subject: [PATCH 1091/1514] soc: apple: aop: M1: use the firmware regions the bootloader reserves From macOS 27 on, the M1's AOP firmware runs its external code and data from DRAM, and stops before its RTKit HELLO unless the OS maps them and writes ED0p. The M1's 13.5 firmware has no such regions. Mark the T8103 AOP as a firmware-region block, with its current configuration as the one to start with when the bootloader reserved no regions, as T8122 does. On the J313 with macOS 27.2.1 firmware the AOP comes up: microphones, ambient light sensor and voice trigger. Signed-off-by: Erik Bourget --- drivers/soc/apple/aop.rs | 12 +++++++++++- tools/asahi/aop-bootargs-tests.py | 10 +++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 38cddac3a30e99..67fb7a7baf4f63 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -3051,7 +3051,8 @@ impl AopHwConfig { } } -const HW_CFG_T8103: AopHwConfig = AopHwConfig { +/// T8103 (M1) with the 13.5 firmware: no firmware regions in DRAM. +const HW_CFG_T8103_DIRECT: AopHwConfig = AopHwConfig { ec0p: 0x020000, ncal: Some(0), aopt: 1, @@ -3070,6 +3071,15 @@ const HW_CFG_T8103: AopHwConfig = AopHwConfig { halt_on_failed_start: false, without_fw_regions: None, }; +/// T8103 (M1): from firmware 27 on, the AOP runs its external code and data +/// from DRAM, which the bootloader reserves in `memory-region`, and stops +/// before its RTKit HELLO unless they are mapped and ED0p is written. A boot +/// with no regions reserved (firmware 13.5) starts it as before. +const HW_CFG_T8103: AopHwConfig = AopHwConfig { + fw_regions: true, + without_fw_regions: Some(&HW_CFG_T8103_DIRECT), + ..HW_CFG_T8103_DIRECT +}; /// `nCal` keeps the firmware's own value, as on T6040: the J413 image carries 1, /// and with 0 the firmware never announces its accelerometer and gyroscope. const HW_CFG_T8112: AopHwConfig = AopHwConfig { diff --git a/tools/asahi/aop-bootargs-tests.py b/tools/asahi/aop-bootargs-tests.py index 08d39e512c89a0..d58b16f4bf3088 100644 --- a/tools/asahi/aop-bootargs-tests.py +++ b/tools/asahi/aop-bootargs-tests.py @@ -82,7 +82,15 @@ assert!(!std::ptr::eq(alt,t8122),"T8122 without regions takes its fallback"); assert!(!alt.fw_regions&&alt.without_fw_regions.is_none(),"the fallback needs no regions"); assert!(alt.ncal==HW_CFG_T6020.ncal&&alt.ec0p==HW_CFG_T6020.ec0p&&alt.quiesce_on_unbind==HW_CFG_T6020.quiesce_on_unbind&&alt.bootargs_word_access==HW_CFG_T6020.bootargs_word_access&&alt.halt_on_failed_start==HW_CFG_T6020.halt_on_failed_start,"T8122 fallback is T6020's"); - let others:[(&str,&'static AopHwConfig);10]=[("T8103",&HW_CFG_T8103),("T8112",&HW_CFG_T8112),("T6000",&HW_CFG_T6000),("T6020",&HW_CFG_T6020),("T6040",&HW_CFG_T6040),("T8132",&HW_CFG_T8132),("T8140",&HW_CFG_T8140),("T8152",&HW_CFG_T8152),("T8142",&HW_CFG_T8142),("T6050",&HW_CFG_T6050)]; + // A T8103 AOP the bootloader reserved no regions for (firmware 13.5) starts as before. + let t8103:&'static AopHwConfig=&HW_CFG_T8103; + assert!(t8103.fw_regions,"T8103 checks its firmware regions"); + assert!(std::ptr::eq(t8103.for_regions(true),t8103),"T8103 with regions keeps its own configuration"); + let direct=t8103.for_regions(false); + assert!(!std::ptr::eq(direct,t8103),"T8103 without regions takes its direct start"); + assert!(!direct.fw_regions&&direct.without_fw_regions.is_none(),"the direct start needs no regions"); + assert!(direct.ncal==t8103.ncal&&direct.ec0p==t8103.ec0p&&direct.aopt==t8103.aopt,"the direct start is the same AOP"); + let others:[(&str,&'static AopHwConfig);9]=[("T8112",&HW_CFG_T8112),("T6000",&HW_CFG_T6000),("T6020",&HW_CFG_T6020),("T6040",&HW_CFG_T6040),("T8132",&HW_CFG_T8132),("T8140",&HW_CFG_T8140),("T8152",&HW_CFG_T8152),("T8142",&HW_CFG_T8142),("T6050",&HW_CFG_T6050)]; for (name,cfg) in others { assert!(cfg.without_fw_regions.is_none(),"{} names no fallback",name); for regions in [true,false] {assert!(std::ptr::eq(cfg.for_regions(regions),cfg),"{} keeps its configuration (regions {})",name,regions);} From 1de1756530a1f7085656b93aa42d2f1c05503c4b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:32:43 -0500 Subject: [PATCH 1092/1514] soc: apple: aop: say per SoC what the AOP hears for a firmware sleep Around a firmware-driven system sleep the driver stops the AOP's endpoints and sends it the AP's idle notice, then the reverse after the wake, as measured on T8140. Make that a per-SoC setting: bit 0 for the endpoint stops, bit 1 for the AP idle and on notices. Every SoC keeps both, except T8103 (M1), which was run across real sleeps with its endpoints stopped only: the ambient light sensor and both sound cards come back after the wake. Tested on a MacBook Air (M1, J313): two back-to-back real suspend-to-RAM cycles with the AOP bound. Signed-off-by: Erik Bourget --- drivers/soc/apple/aop.rs | 29 +++++++++++++++++++++++++++-- tools/asahi/aop-bootargs-tests.py | 6 ++++-- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 67fb7a7baf4f63..ee6f0fdca0d7d1 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -1351,6 +1351,8 @@ struct AopData { /// endpoint order. sleep_endpoints: KVec, wake_endpoints: KVec, + /// [`AopHwConfig::s2r_notice`] + s2r_notice: u8, /// No call starts until the system has resumed. sleeping: Atomic, /// RTKit reported the firmware crashed. Nothing restarts it short of a reboot. @@ -1544,6 +1546,7 @@ impl AopData { ep_shutdown <- pin_init::pin_init_array_from_fn(|_| FutureValue::pin_init()), ep_sleep <- pin_init::pin_init_array_from_fn(|_| FutureValue::pin_init()), sleep_endpoints, + s2r_notice: cfg.s2r_notice, wake_endpoints, sleeping: Atomic::new(false), crashed: Atomic::new(false), @@ -1848,7 +1851,11 @@ impl AopData { } let mut result = Ok(()); - for endpoint in AfkOrder::new(&self.sleep_endpoints) { + let notice = self.s2r_notice; + // An empty order is every endpoint: without the stops, the loop doesn't run. + let stops = AfkOrder::new(&self.sleep_endpoints) + .take_while(|_| notice & AOP_S2R_ENDPOINTS != 0); + for endpoint in stops { let Some(index) = afk_endpoint_index(endpoint) else { continue; }; @@ -1864,7 +1871,7 @@ impl AopData { self.sleep_stopped .store(self.sleep_stopped.load(Relaxed) | (1 << index), Relaxed); } - if result.is_ok() { + if result.is_ok() && notice & AOP_S2R_AP_IDLE != 0 { // Set first: a notice without an answer may still have been taken. self.ap_idle.store(true, Relaxed); result = self.ap_power(false).inspect_err(|e| { @@ -3038,8 +3045,17 @@ struct AopHwConfig { /// left in DRAM are then neither reserved nor mapped, so it runs as its /// fallback compatible's block did (T8122: `apple,t6020-aop`). without_fw_regions: Option<&'static AopHwConfig>, + /// What it hears for a firmware-driven sleep: bit 0 its endpoints stop + /// ([`AOP_S2R_ENDPOINTS`]), bit 1 the AP's idle notice + /// ([`AOP_S2R_AP_IDLE`]). + s2r_notice: u8, } +/// [`AopHwConfig::s2r_notice`]: the endpoints stop and start around a sleep. +const AOP_S2R_ENDPOINTS: u8 = 1 << 0; +/// [`AopHwConfig::s2r_notice`]: the AP's idle and on notices around a sleep. +const AOP_S2R_AP_IDLE: u8 = 1 << 1; + impl AopHwConfig { /// The configuration to start the block with, given whether the /// bootloader reserved its firmware regions. @@ -3070,6 +3086,8 @@ const HW_CFG_T8103_DIRECT: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + // Measured across real sleeps with its endpoints stopped only. + s2r_notice: AOP_S2R_ENDPOINTS, }; /// T8103 (M1): from firmware 27 on, the AOP runs its external code and data /// from DRAM, which the bootloader reserves in `memory-region`, and stops @@ -3100,6 +3118,7 @@ const HW_CFG_T8112: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// `nCal` keeps the firmware's own value, as on T8112. const HW_CFG_T6000: AopHwConfig = AopHwConfig { @@ -3120,6 +3139,7 @@ const HW_CFG_T6000: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; const HW_CFG_T6020: AopHwConfig = AopHwConfig { ec0p: 0x0100_00000000, @@ -3139,6 +3159,7 @@ const HW_CFG_T6020: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T6040 (J616s): the firmware's external code and log live in DRAM, mapped /// through the reserved regions the bootloader describes; the RTKit firmware @@ -3163,6 +3184,7 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { bootargs_word_access: true, halt_on_failed_start: true, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T8132 (J713): as T6040. The bootloader hands the AOP over the same way, with /// the DART's DAPF programmed and its windows reserved alongside the firmware @@ -3199,6 +3221,7 @@ const HW_CFG_T8140: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T8152: like T8140, but the setup port (mailbox 1 of the AOP bank, and the /// ADT aop-exclave-mailbox) is not reachable from the AP: both bus-error. @@ -3220,6 +3243,7 @@ const HW_CFG_T8152: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T8142 (M5): booted through a setup port as on T8140, at the ADT's @@ -3245,6 +3269,7 @@ const HW_CFG_T8142: AopHwConfig = AopHwConfig { bootargs_word_access: false, halt_on_failed_start: false, without_fw_regions: None, + s2r_notice: AOP_S2R_ENDPOINTS | AOP_S2R_AP_IDLE, }; /// T6050 (M5 Pro and Max): booted as T8142, through the setup port at /// AOP ASC + 0x4007c000. Its EPMAP also names system endpoint 4, which never diff --git a/tools/asahi/aop-bootargs-tests.py b/tools/asahi/aop-bootargs-tests.py index d58b16f4bf3088..683b0e9602551e 100644 --- a/tools/asahi/aop-bootargs-tests.py +++ b/tools/asahi/aop-bootargs-tests.py @@ -148,7 +148,8 @@ def method(source): def configs(source): - """struct AopHwConfig and the HW_CFG_* constants, each with its doc comment. + """struct AopHwConfig, the HW_CFG_* constants and the AOP_S2R_* flags they use, each with its + doc comment. Other items between them (the sleep's PM callbacks) use kernel bindings the harness doesn't have. @@ -161,7 +162,8 @@ def configs(source): if not line.strip() or line.startswith(('//', '#[')): pending.append(line) continue - keep = line.startswith(('struct AopHwConfig', 'impl AopHwConfig', 'const HW_CFG_')) + keep = line.startswith(('struct AopHwConfig', 'impl AopHwConfig', 'const HW_CFG_', + 'const AOP_S2R_')) item, pending, depth = pending + [line], [], 0 else: item.append(line) From 567068e75f7234edc2375a57ad5659b07807bfab Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:33:16 -0500 Subject: [PATCH 1093/1514] irqchip/apple-aic: target lines by AIC's CPU number, not the logical one An AIC1 line's target is a bitmap of AIC's own CPU numbers, the number each core reads from WHOAMI. The driver used the logical CPU id, and warned when the two differed. They do differ when the device tree lists the cores in another order than AIC numbers them: an M1 device tree that puts the P-cores between the E-cores sends every line meant for one CPU to another. Record each CPU's WHOAMI when it starts and target lines by that number. Until a CPU has started, its logical id stands in, as before. A difference is reported once instead of warned about. Tested on a MacBook Air (M1, J313) with such a device tree: no WHOAMI warnings, and interrupts reach the CPUs their affinity names. Signed-off-by: Erik Bourget --- drivers/irqchip/irq-apple-aic.c | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 52a892164c3a46..94e36893c7ecf9 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -429,6 +429,9 @@ static DEFINE_PER_CPU(uint32_t, aic_fiq_unmasked); static struct aic_irq_chip *aic_irqc; +/* AIC1: each CPU's number as AIC knows it (WHOAMI), for line targets; the logical id until read */ +static DEFINE_PER_CPU(u32, aic_cpu_hwid); + /* CPUs that accept hardware IRQs, read from SIQ_CFG on AICv2+ at EL2 */ static struct cpumask aic_irq_cpus; @@ -579,7 +582,8 @@ static int aic_irq_set_affinity(struct irq_data *d, else cpu = cpumask_any_and(mask_val, cpu_online_mask); - aic_ic_write(ic, ic->info.target_cpu + AIC_HWIRQ_IRQ(hwirq) * 4, BIT(cpu)); + aic_ic_write(ic, ic->info.target_cpu + AIC_HWIRQ_IRQ(hwirq) * 4, + BIT(per_cpu(aic_cpu_hwid, cpu))); irq_data_update_effective_affinity(d, cpumask_of(cpu)); return IRQ_SET_MASK_OK; @@ -1078,7 +1082,17 @@ static int aic_init_cpu(unsigned int cpu) * If we ever end up with a mismatch here, we will have to introduce * a mapping table similar to what other irqchip drivers do. */ - WARN_ON(aic_ic_read(aic_irqc, AIC_WHOAMI) != smp_processor_id()); + u32 whoami = aic_ic_read(aic_irqc, AIC_WHOAMI); + + /* + * The device tree's CPU order need not be AIC's (the E- and P-cores can + * interleave): a line's target is AIC's number for the CPU, so keep it. + */ + if (whoami < 32) + per_cpu(aic_cpu_hwid, smp_processor_id()) = whoami; + if (whoami != smp_processor_id()) + pr_info_once("AIC: CPU numbers differ from the device tree's order (CPU%d is AIC CPU %u)\n", + smp_processor_id(), whoami); /* * Always keep IPIs unmasked at the hardware level (except auto-masking @@ -1316,7 +1330,7 @@ static void __init aic_sleep_init(struct aic_irq_chip *irqc) static int __init aic_of_ic_init(struct device_node *node, struct device_node *parent) { - int i, die; + int i, die, cpu; u32 off, start_off; void __iomem *regs; struct aic_irq_chip *irqc; @@ -1435,6 +1449,9 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p } of_node_put(affs); + for_each_possible_cpu(cpu) + per_cpu(aic_cpu_hwid, cpu) = cpu; + set_handle_irq(aic_handle_irq); set_handle_fiq(aic_handle_fiq); From dcf02d6dfac5ecc51a848353c1d8f383d895b467 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:33:29 -0500 Subject: [PATCH 1094/1514] irqchip/apple-aic: restore AIC1's configuration, line targets and CPU numbers after a firmware sleep On the M1 (AIC1) a firmware-driven sleep power-cycles AIC along with the rest of the SoC. The masks were already saved and restored around it, but the wake also loses what the boot loader set up: the global configuration words, each line's target CPUs, and the CPU number in each CPU's block that WHOAMI reports. With those gone, no interrupt reached a CPU after the wake. Where AIC has per-line targets, save the targets with the masks before the sleep, along with the global configuration (0x10..0x3c) and each CPU block's first word, and write back whatever differs at the wake: the configuration first, then the CPU numbers before any CPU reads its own, then each line's targets before its mask. Tested on a MacBook Air (M1, J313): interrupts (the RTC alarm, storage, Wi-Fi, Bluetooth) are delivered after real suspend-to-RAM cycles. Signed-off-by: Erik Bourget --- drivers/irqchip/irq-apple-aic.c | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index 94e36893c7ecf9..afbb4eaf7dd65c 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -101,6 +101,7 @@ #define AIC_TARGET_CPU 0x3000 +#define AIC_CPU_BLOCK(cpu) (0x5000 + ((cpu) << 7)) #define AIC_CPU_IPI_SET(cpu) (0x5008 + ((cpu) << 7)) #define AIC_CPU_IPI_CLR(cpu) (0x500c + ((cpu) << 7)) #define AIC_CPU_IPI_MASK_SET(cpu) (0x5024 + ((cpu) << 7)) @@ -421,6 +422,12 @@ struct aic_irq_chip { int max_die; u32 *sleep_masks; + /* AIC1: each line's target CPUs, which a firmware sleep's power cycle may take */ + u32 *sleep_targets; + /* AIC1: the global registers the boot loader set (0x10..0x3c), lost the same way */ + u32 sleep_globals[12]; + /* AIC1: each CPU block's first word, the CPU number WHOAMI reports there */ + u32 sleep_cpu_ids[32]; struct aic_info info; }; @@ -456,6 +463,7 @@ void aic_sleep_mask_all(void) struct aic_irq_chip *ic = aic_irqc; u32 words = ic->max_irq >> 5, off = 0, reg, i; u32 *saved = ic->sleep_masks; + u32 *targets = ic->sleep_targets; int die; for (die = 0; die < ic->nr_die; die++, off += ic->info.die_stride) { @@ -464,7 +472,13 @@ void aic_sleep_mask_all(void) *saved++ = aic_ic_read(ic, reg); aic_ic_write(ic, reg, U32_MAX); } + for (i = 0; targets && i < ic->nr_irq; i++) + *targets++ = aic_ic_read(ic, ic->info.target_cpu + off + i * 4); } + for (i = 0; ic->sleep_targets && i < ARRAY_SIZE(ic->sleep_globals); i++) + ic->sleep_globals[i] = aic_ic_read(ic, AIC_CONFIG + i * 4); + for (i = 0; ic->sleep_targets && i < min(num_possible_cpus(), 32U); i++) + ic->sleep_cpu_ids[i] = aic_ic_read(ic, AIC_CPU_BLOCK(i)); } void aic_sleep_restore(void) @@ -472,9 +486,29 @@ void aic_sleep_restore(void) struct aic_irq_chip *ic = aic_irqc; u32 words = ic->max_irq >> 5, off = 0, i; u32 *saved = ic->sleep_masks; + u32 *targets = ic->sleep_targets; int die; + /* Delivery as a whole first: with the configuration gone, no line reaches a CPU. */ + for (i = 0; targets && i < ARRAY_SIZE(ic->sleep_globals); i++) { + if (aic_ic_read(ic, AIC_CONFIG + i * 4) != ic->sleep_globals[i]) + aic_ic_write(ic, AIC_CONFIG + i * 4, ic->sleep_globals[i]); + } + + /* The CPU numbers, before any CPU comes back up and reads its own */ + for (i = 0; targets && i < min(num_possible_cpus(), 32U); i++) { + if (aic_ic_read(ic, AIC_CPU_BLOCK(i)) != ic->sleep_cpu_ids[i]) + aic_ic_write(ic, AIC_CPU_BLOCK(i), ic->sleep_cpu_ids[i]); + } + for (die = 0; die < ic->nr_die; die++, off += ic->info.die_stride) { + /* Targets first: an unmasked line with none goes nowhere. */ + for (i = 0; targets && i < ic->nr_irq; i++, targets++) { + u32 reg = ic->info.target_cpu + off + i * 4; + + if (aic_ic_read(ic, reg) != *targets) + aic_ic_write(ic, reg, *targets); + } for (i = 0; i < words; i++, saved++) { aic_ic_write(ic, ic->info.mask_set + off + i * 4, *saved); aic_ic_write(ic, ic->info.mask_clr + off + i * 4, ~*saved); @@ -1429,6 +1463,12 @@ static int __init aic_of_ic_init(struct device_node *node, struct device_node *p sizeof(*irqc->sleep_masks), GFP_KERNEL); if (WARN_ON(!irqc->sleep_masks)) goto err_unmap; + if (irqc->info.target_cpu) { + irqc->sleep_targets = kcalloc(irqc->nr_die * irqc->nr_irq, + sizeof(*irqc->sleep_targets), GFP_KERNEL); + if (WARN_ON(!irqc->sleep_targets)) + goto err_unmap; + } irqc->hw_domain = irq_domain_create_tree(of_fwnode_handle(node), &aic_irq_domain_ops, irqc); From c1166e01a559f000ee3ab76ecd6319fa8e48eb42 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:34:11 -0500 Subject: [PATCH 1095/1514] PCI: apple: set the ports up again after a firmware sleep that took the complex's power On the M1 a firmware-driven system sleep takes the whole PCIe complex's power, and the boot loader brings the complex and its links up again at the wake, as at boot. What Linux set up on top of that is lost: the ports' reference and application clocks, their interrupt masks and MSI setup, and the RID to SID map. Wi-Fi and Bluetooth never came back. For controllers whose data says so (sleep_loader_reinit, set on the generic apple,pcie data), save each port's interrupt mask and RID to SID entries when a firmware sleep suspends the controller, with its port interrupts off. After a real wake, check each port is ready, ungate its clocks, restore its interrupt and MSI setup and RID to SID map, train a link the boot loader didn't bring up, and enable its interrupts again. A sleep that was refused lost nothing, and only the interrupts are enabled again. The root ports and functions are suspended and resumed by the PCI core as before. Tested on a MacBook Air (M1, J313): Wi-Fi (BCM4378) and Bluetooth come back after two back-to-back real suspend-to-RAM cycles. Signed-off-by: Erik Bourget --- drivers/pci/controller/pcie-apple.c | 97 ++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index fb2aed80ec54b4..97032ec2b0c985 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -269,6 +269,11 @@ MODULE_PARM_DESC(t6050_sd_port_wake, #define DOORBELL_ADDR CONFIG_PCIE_APPLE_MSI_DOORBELL_ADDR struct hw_info { + /* + * A firmware sleep takes the complex's power, and the boot loader brings it and its + * links up again at the wake, as at boot: what Linux set up on top is put back. + */ + bool sleep_loader_reinit; u32 phy_lane_ctl; u32 port_msiaddr; u32 port_msiaddr_hi; @@ -311,6 +316,7 @@ struct hw_info { }; static const struct hw_info t8103_hw = { + .sleep_loader_reinit = true, .phy_lane_ctl = PHY_LANE_CTL, .port_msiaddr = PORT_MSIADDR, .port_msiaddr_hi = 0, @@ -605,6 +611,8 @@ struct apple_pcie { struct apple_pcie_neo_cold *neo_cold; struct notifier_block neo_pm_nb; bool neo_sleep_armed; + /* Ports saved for a firmware sleep that takes the complex's power */ + bool fw_slept; struct work_struct neo_recover_work; bool neo_recover; /* The link and the functions back after a sleep, while the rest resumes */ @@ -6923,6 +6931,80 @@ static int apple_pcie_check_adopted_s2idle(struct apple_pcie *pcie) return error; } +static bool apple_pcie_loader_sleep(struct apple_pcie *pcie) +{ + return pcie->hw->sleep_loader_reinit && !pcie->managed_sids && !pcie->neo_sleep_armed && + pm_suspend_target_state == PM_SUSPEND_MEM && pm_suspend_via_firmware(); +} + +/* + * hw.sleep_loader_reinit: a firmware sleep takes the whole PCIe complex's power, and the + * boot loader brings the complex and its links up again at the wake, as at boot. What + * Linux set up on top of that is lost: the ports' clocks, their interrupts and MSI setup, + * the RID to SID map. + * The root ports and functions are suspended above, and the PCI core restores them. + */ +static void apple_pcie_loader_sleep_save(struct apple_pcie *pcie) +{ + struct apple_pcie_port *port; + int i; + + list_for_each_entry(port, &pcie->ports, entry) { + apple_pcie_port_disable_irq(port); + port->saved_intmask = apple_pcie_port_readl(port, PORT_INTMSK); + for_each_set_bit(i, port->sid_map, port->sid_map_sz) + port->saved_rid2sid[i] = + apple_pcie_port_readl(port, port_rid2sid_offset(port, i)); + } + pcie->fw_slept = true; +} + +static int apple_pcie_loader_sleep_restore(struct apple_pcie *pcie) +{ + struct apple_pcie_port *port; + u8 up = 0; + int i, ret = 0; + + pcie->fw_slept = false; + list_for_each_entry(port, &pcie->ports, entry) { + u32 stat; + + if (!(apple_pcie_port_readl(port, PORT_STATUS) & PORT_STATUS_READY)) { + dev_err(pcie->dev, "%pOF not set up again after the sleep\n", port->np); + ret = -ENODEV; + continue; + } + if (pcie->hw->port_refclk) + rmw_clear(PORT_REFCLK_CGDIS, port->base + pcie->hw->port_refclk); + else if (port->phy) + rmw_set(PHY_LANE_CFG_REFCLKCGEN, port->phy + PHY_LANE_CFG); + rmw_clear(PORT_APPCLK_CGDIS, port->base + PORT_APPCLK); + + apple_pcie_tunnel_restore_irq_hw(port); + for_each_set_bit(i, port->sid_map, port->sid_map_sz) + apple_pcie_rid2sid_write(port, i, port->saved_rid2sid[i]); + + if (!(apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP)) { + ret = apple_pcie_setup_link(pcie, port, port->np); + if (!ret) { + apple_pcie_port_writel(port, PORT_LTSSMCTL_START, PORT_LTSSMCTL); + ret = readl_poll_timeout(port->base + PORT_LINKSTS, stat, + stat & PORT_LINKSTS_UP, 1000, + link_up_timeout * USEC_PER_MSEC); + } + if (ret) + dev_err(pcie->dev, "%pOF link not up after the sleep: %d\n", + port->np, ret); + } + if (apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP) + up |= BIT(port->idx); + apple_pcie_port_writel(port, port->saved_intmask, PORT_INTMSK); + apple_pcie_port_enable_irq(port); + } + dev_info(pcie->dev, "ports set up again after the sleep, links up %#x\n", up); + return ret; +} + static int apple_pcie_suspend_noirq(struct device *dev) { struct apple_pcie *pcie = apple_pcie_lookup(dev); @@ -6988,6 +7070,10 @@ static int apple_pcie_suspend_noirq(struct device *dev) return ret; } if (!pcie->hw->tunneled) { + if (apple_pcie_loader_sleep(pcie)) { + apple_pcie_loader_sleep_save(pcie); + return 0; + } if (pm_suspend_no_platform() && pcie->num_pds) return apple_pcie_hold_domains(pcie); return 0; @@ -7519,8 +7605,17 @@ static int apple_pcie_resume_noirq(struct device *dev) } return ret; } - if (!pcie->hw->tunneled) + if (!pcie->hw->tunneled) { + if (pcie->fw_slept) { + if (pm_resume_via_firmware()) + return apple_pcie_loader_sleep_restore(pcie); + /* Refused: nothing lost */ + pcie->fw_slept = false; + list_for_each_entry(port, &pcie->ports, entry) + apple_pcie_port_enable_irq(port); + } return 0; + } if (pcie->resume_failed) return -EIO; /* From f1aedceb94970ece521989239a5573d8e511c6dc Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:34:25 -0500 Subject: [PATCH 1096/1514] Bluetooth: hci_bcm4377: recover after a firmware sleep that took the function's power Outside the radio sleep transaction, the noirq resume returned early, so after a firmware-driven sleep that took the function's power (the M1's real suspend-to-RAM, with PERST at the wake) its private BAR windows were left at their reset values and its firmware was gone. The resume then read through the unprogrammed windows. After a firmware wake, read the BAR0 window from config space. If it no longer holds the value the driver programs, the function lost its state: program the windows again so nothing faults, skip the unquiesce, and rebind the driver once the resume is over, which boots the firmware from scratch. A function that kept its state is left as it is. Tested on a MacBook Air (M1, J313): hci0 comes back after two back-to-back real suspend-to-RAM cycles. Signed-off-by: Erik Bourget --- drivers/bluetooth/hci_bcm4377.c | 29 +++++++++++++++++++++++- tools/asahi/bcm4377-resume-tests.py | 2 +- tools/asahi/bcm4377-resume/controls.c | 10 +++++++- tools/asahi/bcm4377-resume/fixture.h | 7 +++++- tools/asahi/bcm4377-sleep-config-tests.c | 18 ++++++++++++--- 5 files changed, 59 insertions(+), 7 deletions(-) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 3f875ac518dfc9..402d4b769553ba 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -608,6 +608,8 @@ struct bcm4377_data { bool cal_needed; bool cal_loaded; bool setup_retry_used; + /* A firmware-driven sleep took the controller's state: rebind after the resume */ + bool sleep_lost; bool setup_retry_pending; bool setup_retry_blocked; struct delayed_work setup_retry_work; @@ -3200,6 +3202,11 @@ static int bcm4377_resume(struct device *dev) bcm4377->wake_armed = false; } + if (bcm4377->sleep_lost) { + /* Its firmware is gone: nothing to unquiesce. */ + bcm4377->quiesced = false; + bcm4377->resume_powered = false; + } if (bcm4377->quiesced) { iowrite32(BCM4377_BAR0_SLEEP_CONTROL_UNQUIESCE, bcm4377->bar0 + BCM4377_BAR0_SLEEP_CONTROL); @@ -3218,6 +3225,10 @@ static int bcm4377_resume(struct device *dev) bcm4377->resume_powered = false; ret = hci_resume_dev(bcm4377->hdev); + if (bcm4377->sleep_lost) { + bcm4377->sleep_lost = false; + bcm4377_queue_rebind(bcm4377, "state lost in a firmware sleep"); + } apple_radio_sleep_endpoint_resumed(dev, ret); if (!apple_radio_sleep_owned(dev)) { WRITE_ONCE(bcm4377->setup_retry_blocked, false); @@ -3233,8 +3244,24 @@ static int bcm4377_resume_noirq(struct device *dev) u32 before, after; int ret; - if (!apple_radio_sleep_owned(dev) || !pm_resume_via_firmware()) + if (!pm_resume_via_firmware()) return 0; + /* + * Not under the radio sleep transaction: a firmware-driven sleep that took the + * function's power (PERST at the wake) leaves the private BAR windows at their reset + * values, and the firmware gone. Set the windows up again so that nothing here faults, + * and rebind once the resume is over. + */ + if (!apple_radio_sleep_owned(dev)) { + ret = pci_read_config_dword(bcm4377->pdev, BCM4377_PCIECFG_BAR0_WINDOW1, &before); + if (!ret && before == bcm4377->hw->bar0_window1) + return 0; + bcm4377->sleep_lost = true; + ret = bcm4377_init_cfg(bcm4377); + dev_info(dev, "lost its state in the sleep (window %#x): windows set up again (%d), rebinding after the resume\n", + before, ret); + return 0; + } /* * PERST resets the private BAR windows, which PCI's standard saved state diff --git a/tools/asahi/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index f8dfa488d50790..9b031cd8af5951 100755 --- a/tools/asahi/bcm4377-resume-tests.py +++ b/tools/asahi/bcm4377-resume-tests.py @@ -56,7 +56,7 @@ def extract(s,n): (o/'compile.log').write_text(c.stdout+c.stderr);assert not c.returncode,c.stderr def no_core():resource.setrlimit(resource.RLIMIT_CORE,(0,0)) results=[] -for n in ([mutations[a.mutation][3]] if a.mutation else [0,1,2,28] if a.old_ref else range(46)): +for n in ([mutations[a.mutation][3]] if a.mutation else [0,1,2,28] if a.old_ref else range(47)): c=subprocess.run([str(o/'controls'),str(n)],capture_output=True,text=True,preexec_fn=no_core,env=dict(env,ASAN_OPTIONS='detect_leaks=1')) results.append({'case':n,'exit':c.returncode,'stdout':c.stdout,'stderr':c.stderr}) expected=-6 if a.old_ref or a.mutation else 0 diff --git a/tools/asahi/bcm4377-resume/controls.c b/tools/asahi/bcm4377-resume/controls.c index ff558fd981ee83..4b157cd8f4da6f 100644 --- a/tools/asahi/bcm4377-resume/controls.c +++ b/tools/asahi/bcm4377-resume/controls.c @@ -108,9 +108,17 @@ int main(int argc,char **argv) { recover(&b); assert(rebind_count == 1); break; + case 46: + /* A firmware sleep took the controller's state: no unquiesce, a rebind after. */ + assert(!bcm4377_suspend(&dev)); + b.sleep_lost = true; + assert(!bcm4377_resume(&dev)); + assert(!b.sleep_lost && !b.quiesced && !b.resume_powered); + break; default:abort(); } - if (atoi(argv[1]) == 6 || atoi(argv[1]) == 44 || atoi(argv[1]) == 45) + if (atoi(argv[1]) == 6 || atoi(argv[1]) == 44 || atoi(argv[1]) == 45 || + atoi(argv[1]) == 46) assert(rebind_count == 1); else assert(!rebind_count); diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index 5eece3476e65fe..aaa5c2583d5a3b 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -56,7 +56,7 @@ struct bcm4377_hw { unsigned int id; int (*send_calibration)(struct bcm4377_data struct bcm4377_data { struct hci_dev *hdev; struct pci_dev *pdev; struct bcm4377_hw *hw; bool wake_armed, quiesced, needs_reset, cal_needed, cal_loaded; - bool setup_retry_used, setup_retry_pending, setup_retry_blocked; + bool setup_retry_used, sleep_lost, setup_retry_pending, setup_retry_blocked; struct delayed_work setup_retry_work; bdaddr_t bdaddr; char *bar0; @@ -76,6 +76,11 @@ static void bcm4377_hci_reset(struct hci_dev *hdev) rebind_count++; } +static void bcm4377_queue_rebind(struct bcm4377_data *bcm4377, const char *why) +{ + rebind_count++; +} + static bool missing_blob; static bool active_callback_pause,active_running; static pthread_barrier_t active_started,active_release; diff --git a/tools/asahi/bcm4377-sleep-config-tests.c b/tools/asahi/bcm4377-sleep-config-tests.c index 8740031cc6bd36..bd11efa5228488 100644 --- a/tools/asahi/bcm4377-sleep-config-tests.c +++ b/tools/asahi/bcm4377-sleep-config-tests.c @@ -21,10 +21,11 @@ struct hardware { struct bcm4377_data { struct pci_dev *pdev; struct hardware *hw; + bool sleep_lost; }; static struct pci_dev pci; static struct hardware hw = { 0x18002000, 0x18109000, 0x18106000, true, false }; -static struct bcm4377_data data = { &pci, &hw }; +static struct bcm4377_data data = { .pdev = &pci, .hw = &hw }; static bool owned, physical, ignore_window; static unsigned int ops, writes, fail; static u32 cfg[64]; @@ -93,9 +94,20 @@ int main(void) fresh(); + /* Outside the radio sleep transaction, the windows intact: one read, nothing else. */ owned = false; + cfg[0x80 / 4] = hw.bar0_window1; assert(!bcm4377_resume_noirq(&dev)); - assert(!ops); + assert(ops == 1 && !writes && !data.sleep_lost); + /* ... and lost to a sleep that took the function's power: set up again, then a rebind. */ + fresh(); + owned = false; + assert(!bcm4377_resume_noirq(&dev)); + assert(data.sleep_lost); + assert(cfg[0x80 / 4] == hw.bar0_window1); + assert(cfg[0x70 / 4] == hw.bar0_window2); + assert(cfg[0x78 / 4] == hw.bar0_core2_window2); + data.sleep_lost = false; fresh(); physical = false; assert(!bcm4377_resume_noirq(&dev)); @@ -115,6 +127,6 @@ int main(void) bcm4377_resume_noirq(&dev); assert(0); } - puts("PASS: private PCI windows, retained-path skip and restore failures"); + puts("PASS: private PCI windows, retained-path skip, lost state and restore failures"); return 0; } From a25aa24cca95ef5adb708bbd24f04c6380eb053f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:35:09 -0500 Subject: [PATCH 1097/1514] mfd: macsmc: let the saved transport write keys of any size apple_smc_saved_write_u32() is the only key write on the saved transport, and it only takes a 32-bit value. Split out apple_smc_saved_write(), which takes a buffer and its size, and keep the u32 helper on top of it. No change in behaviour. Signed-off-by: Erik Bourget --- drivers/mfd/macsmc.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index cb32577a3bf66a..c8aff8d184c7dd 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -1216,7 +1216,8 @@ static int apple_smc_saved_drain(struct apple_smc *smc) return -ENOBUFS; } -static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 value) +static int apple_smc_saved_write(struct apple_smc *smc, smc_key key, const void *buf, + size_t size) { u64 msg; int ret; @@ -1232,10 +1233,10 @@ static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 val if (ret) return ret; /* Guard precedes the copy. Timeout keeps both this ID and this SRAM. */ - memcpy_toio(smc->shmem.iomem, &value, sizeof(value)); + memcpy_toio(smc->shmem.iomem, buf, size); smc->msg_id = (smc->msg_id + 1) & 0xf; msg = FIELD_PREP(SMC_MSG, SMC_MSG_WRITE_KEY) | - FIELD_PREP(SMC_SIZE, sizeof(value)) | + FIELD_PREP(SMC_SIZE, size) | FIELD_PREP(SMC_ID, smc->msg_id) | FIELD_PREP(SMC_DATA, key); smp_store_release(&smc->saved_pending, true); ret = apple_rtkit_m5_saved_send(smc->rtk, msg); @@ -1252,6 +1253,11 @@ static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 val return FIELD_GET(SMC_SIZE, smc->cmd_ret) ? -EPROTO : 0; } +static int apple_smc_saved_write_u32(struct apple_smc *smc, smc_key key, u32 value) +{ + return apple_smc_saved_write(smc, key, &value, sizeof(value)); +} + static u64 apple_smc_saved_stamp(void) { return __arch_counter_get_cntpct(); From 0ebe6b2507de1fe6d3104dfdb5a7d5d5ce53af31 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:35:30 -0500 Subject: [PATCH 1098/1514] soc: apple: pm_shim: accept the enclave's power-down by its actual state After the SEP's SLEEP request is answered, the commit waits for the enclave's power state word to show it went down, by DEV_DISABLE. The M1's enclave never sets DEV_DISABLE (measured on J313): its actual state goes to 0 instead, and the wait panicked. Once the enclave was asked to sleep, take an actual state of 0 as down as well, as the SoC's own sleep sequence polls it. DEV_DISABLE still counts wherever the firmware sets it. Tested on a MacBook Air (M1, J313) across real suspend-to-RAM cycles. Signed-off-by: Erik Bourget --- drivers/soc/apple/pm_shim.c | 12 +++++++++++- tools/asahi/sep-suspend-errors-tests.py | 21 ++++++++++++++++----- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index c1d415c0bd7447..85e6fbeb09d29b 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -8,6 +8,7 @@ * read here. On T8140 at EL2 the sleep driver sends the request at the * irreversible commit boundary. Only errors before send may refuse. */ +#include #include #include #include @@ -36,6 +37,15 @@ #define SEP_PS_DEV_DISABLE BIT(10) #define SEP_PS_ACTUAL GENMASK(7, 4) +/* + * After its sleep request, the enclave has gone down: DEV_DISABLE where its firmware sets + * it, or its actual state at 0. The M1's enclave never sets DEV_DISABLE (measured on J313). + */ +static bool sep_ps_down(u32 state) +{ + return (state & SEP_PS_DEV_DISABLE) || !FIELD_GET(SEP_PS_ACTUAL, state); +} + /* One-shot precommit test: no SLEEP request or commit coprocessor stop. */ static bool sleep_refuse_before_send; module_param(sleep_refuse_before_send, bool, 0644); @@ -301,7 +311,7 @@ static int sep_pm_commit_stop(void *data) * the native contract, not proved atomic by the preceding PMGR sample. */ apple_mbox_set_recv_enabled(c->mbox, false); - c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, c->state & SEP_PS_DEV_DISABLE, + c->gate_ret = readl_poll_timeout_atomic(c->ps, c->state, sep_ps_down(c->state), SEP_PM_POLL_US, SEP_PM_TIMEOUT_US); c->gate_valid = true; if (c->gate_ret) diff --git a/tools/asahi/sep-suspend-errors-tests.py b/tools/asahi/sep-suspend-errors-tests.py index 2ae69ec2c32fcf..c4b77b7db3a8b9 100644 --- a/tools/asahi/sep-suspend-errors-tests.py +++ b/tools/asahi/sep-suspend-errors-tests.py @@ -104,6 +104,11 @@ def replace_once(source, before, after): typedef int64_t s64; typedef long long ktime_t; #define BIT(n) (1u << (n)) #define SEP_PS_DEV_DISABLE BIT(10) +#define GENMASK(h, l) ((~0u << (l)) & (~0u >> (31 - (h)))) +#define FIELD_GET(m, v) (((v) & (m)) / ((m) & -(m))) +/* The enclave's power word while it runs (target and actual 0xf), and gated without DEV_DISABLE */ +#define SEP_PS_RUNNING 0xffu +#define SEP_PS_ACTUAL_OFF 0x0fu #define USEC_PER_MSEC 1000 #define NSEC_PER_USEC 1000 #define READ_ONCE(x) (x) @@ -148,7 +153,7 @@ def replace_once(source, before, after): static int gate_after, reads, put_refs, maps, unmaps, lookups, prepares, restores; static int prepare_error, send_error, bulk_error, one_error, sends, closes; static int mailbox_reads, message_reads, forwarded, lock_depth; -static int resource_bytes, close_gate, early_gate; +static int resource_bytes, close_gate, early_gate, actual_gate; static bool message_in_lock, matched_read; static struct apple_mbox_msg queue[4]; static unsigned queued, consumed; @@ -230,7 +235,9 @@ def replace_once(source, before, after): } static u32 readl(void *p) { // PMGR is the sole permitted query after the matched reply/receive close. - return early_gate || (closes && close_gate) ? SEP_PS_DEV_DISABLE : 0; + if (early_gate || (closes && close_gate)) + return SEP_PS_DEV_DISABLE; + return closes && actual_gate ? SEP_PS_ACTUAL_OFF : SEP_PS_RUNNING; } static jmp_buf fatal_env; static bool fatal_armed; @@ -257,7 +264,7 @@ def replace_once(source, before, after): put_refs = maps = unmaps = lookups = prepares = restores = sends = closes = 0; prepare_error = send_error = bulk_error = one_error = 0; mailbox_reads = message_reads = forwarded = lock_depth = 0; - resource_bytes = 4; close_gate = 1; early_gate = 0; read_error_after = 1; + resource_bytes = 4; close_gate = 1; early_gate = 0; actual_gate = 0; read_error_after = 1; queued = consumed = 0; message_in_lock = matched_read = false; now = 0; fatal_armed = false; fatal_message[0] = 0; sep_pm_told = yes; } @@ -387,6 +394,10 @@ def replace_once(source, before, after): fixture(); assert(stage() == 0); reply(0); close_gate = 0; expect_stop_fatal("did not gate after send: -110"); assert(closes == 1 && sep_pm_commit.gate_valid && sep_pm_commit.gate_ret == -ETIMEDOUT); + /* An enclave that gates without ever setting DEV_DISABLE (M1): its actual state at 0. */ + fixture(); assert(stage() == 0); reply(0); close_gate = 0; actual_gate = 1; + assert(sep_pm_commit_stop(&sep_pm_commit) == 0); + assert(closes == 1 && sep_pm_commit.gate_valid && !sep_pm_commit.gate_ret); fixture(); assert(stage() == 0); reply(0); assert(sep_pm_commit_stop(&sep_pm_commit) == 0); fatal_armed = true; @@ -663,7 +674,7 @@ def sources(source, contracts, mutation): sleep = (source / 'drivers/soc/apple/sleep.c').read_text() iopoll = (contracts / 'include/linux/iopoll.h').read_text() names = { - 'shim': ['sep_pm_wait_gated', 'sep_pm_clear_dev_disable', 'sep_pm_dart_restore', + 'shim': ['sep_ps_down', 'sep_pm_wait_gated', 'sep_pm_clear_dev_disable', 'sep_pm_dart_restore', 'sep_pm_commit_rx', 'sep_pm_commit_take_rx', 'sep_pm_commit_stop', 'sep_pm_commit_prepare', 'sep_pm_commit_finish', 'sep_pm_suspend_noirq'], 'mailbox': ['apple_mbox_poll_one_supported', 'apple_mbox_poll_one'], @@ -682,7 +693,7 @@ def sources(source, contracts, mutation): 'read_poll_timeout_atomic', 'readx_poll_timeout_atomic', 'readl_poll_timeout_atomic'] c = C_PREFIX + '\n' + '\n'.join(macro(iopoll, n) for n in macros) c += '\n' + '\n'.join(re.search(r'^#define ' + n + r'\s+.*$', shim, re.M).group() - for n in ['SEP_PM_POLL_US', 'SEP_PM_TIMEOUT_US']) + for n in ['SEP_PM_POLL_US', 'SEP_PM_TIMEOUT_US', 'SEP_PS_ACTUAL']) start = shim.index('static struct sep_pm_commit {') c += '\n' + shim[start:shim.index('} sep_pm_commit;', start) + len('} sep_pm_commit;')] # Use the actual provider helper, with only removal/capability dependency state From 56e04a961fc34ed00bac4e4a1d8a79324e292cbb Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:53:40 -0500 Subject: [PATCH 1099/1514] dt-bindings: soc: apple: apple,t8140-sleep: add T8103 Add the T8103 (M1) sleep controller. Its SoC steps are the driver's own operations, so it maps only seven blocks: the main and always-on PMGR, the SoC clock muxes, the AOP's wake block, the CPU start block, the watchdog and nub-spmi0. It needs the wake sources to leave on and the AP pin controller, whose pins a sleep resets. Signed-off-by: Erik Bourget --- .../bindings/soc/apple/apple,t8140-sleep.yaml | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml index 25228d7c80251c..33b0691163dfd6 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml @@ -19,16 +19,17 @@ description: | properties: compatible: enum: + - apple,t8103-sleep - apple,t8132-sleep - apple,t8140-sleep - apple,t8142-sleep reg: - minItems: 25 + minItems: 7 maxItems: 41 reg-names: - minItems: 25 + minItems: 7 maxItems: 41 apple,wake-enable: @@ -105,6 +106,33 @@ required: - apple,display-coprocessors allOf: + - if: + properties: + compatible: + contains: + const: apple,t8103-sleep + then: + required: + - apple,wake-enable + - apple,pinctrl + properties: + reg: + maxItems: 7 + reg-names: + items: + - const: ps + - const: ps-aon + - const: clk-mux + - const: wake + - const: cpu-start + - const: wdt + - const: spmi + else: + properties: + reg: + minItems: 25 + reg-names: + minItems: 25 - if: properties: compatible: From e8f3f342555b308716d5cbf07c3d72effc47f898 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:51:34 -0500 Subject: [PATCH 1100/1514] soc: apple: sleep: add T8103 (M1) suspend-to-RAM support Add a T8103 profile to the Apple SoC sleep driver: suspend-to-RAM through the PMGR's S2R timer, on the early-context entry, with the SoC's own steps as its operations. At .prepare, after SEP's sleep and before the SMC's last keys: - SEP's domain is forced off and waited for; - the PMP, the SIO and both display coprocessors are idled over their RTKit management endpoint and stopped (a commit with the PMP running resets the SoC); - the domains Linux leaves on that the sleep needs off are lowered: the stopped GPU, display, ATC and PCIe blocks (the fabric bridges' handshake first), the USB and debug domains of the always-on PMGR and the clock-gated SPMI and FPWM domains; - the always-on domains meant to run with AUTO_ENABLE get it. At the commit: - the memory clock steps down one performance state at a time (a larger step leaves DRAM unusable), from a routine that fits in one cache line; - the memory controller's error reporting goes off, its and the DCS channels' dynamic gating on, the DCS write queues are flushed and the memory cache's ways turned off; - DRAM is kept up through the sleep while the AOP's driver is bound (SLP_DDR), since the AOP runs through it; - the AOP wake mask is armed and its latched sources cleared; - the SoC clock muxes are parked; - the CPU complexes and voltage monitors are quiesced, CPM power gating is turned on, both clusters' targets go to 0 and AUTO_ENABLE comes off on three always-on words; - SEP's power-gate wait is cleared unless SEP gated; - the watchdog (WD1) is armed, the PMU RTC alarm's SPMI vector enabled and the PMU's boot stage set to sleep; - every AIC line and each CPU's IPIs are masked. Then the S2R timer is written, and written again after the AIC mask. The cores power down without retention through CYC_OVRD and ACC_OVRD after writing back their L1 and L2 data caches, as on the other Firestorm/Icestorm SoCs. A resume stub puts back the cores' PAC controls, which a wake resets, before cpu_resume. The wake undoes each step in reverse, puts back every SoC clock mux the sleep's own sequence changed and every AP pin the gpio domain's power cut reset, before any driver resumes. The SoC's watchdog is WD1, which apple_wdt also drives: the sleep saves it at .begin, uses it from the suspend to .end and puts it back after apple_wdt's resume. Its SMC is gen 1: it hears last, after SEP and the other coprocessors stopped, with WKTP between slpw and slpa. The sleep node's blocks are mapped non-posted where the bus says so: on T8103 a posted write to them is an SError. A timed wake is the PMU RTC's alarm, wake source 54 (NUB.SPMI0Sw3IRQ), set by its RTC driver. Based on the t6000 suspend-to-RAM reference by Andreas Fernandez. Signed-off-by: Erik Bourget --- drivers/soc/apple/Kconfig | 2 +- drivers/soc/apple/Makefile | 2 +- drivers/soc/apple/sleep-perf-step.S | 34 + drivers/soc/apple/sleep-t8103.h | 1647 +++++++++++++++++++++++++++ drivers/soc/apple/sleep-test.c | 16 +- drivers/soc/apple/sleep.c | 109 +- include/linux/soc/apple/sleep.h | 3 + 7 files changed, 1795 insertions(+), 18 deletions(-) create mode 100644 drivers/soc/apple/sleep-perf-step.S create mode 100644 drivers/soc/apple/sleep-t8103.h diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index f5ac320f2fbe64..3783efbe23906f 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -113,7 +113,7 @@ config APPLE_SOC_SLEEP /chosen/aurora,s2r-mailbox. Only SoCs whose sleep has been measured and tested are supported, - each by its match data: today T8140, T8132 and T6050. On every other + each by its match data: today T8140, T8132, T6050 and T8103. On every other SoC the driver doesn't bind, and s2idle stays the only system sleep. config APPLE_SOC_SLEEP_KUNIT_TEST diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 6ce2050c293e61..dc19425add4a4c 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -17,7 +17,7 @@ obj-$(CONFIG_APPLE_CLUSTER_PWRGATE) += apple-cluster-pwrgate.o obj-$(CONFIG_APPLE_SOC_SLEEP) += apple-sleep.o obj-$(CONFIG_APPLE_SOC_SLEEP) += t6050-aop.o -apple-sleep-y = sleep.o +apple-sleep-y = sleep.o sleep-perf-step.o obj-$(CONFIG_APPLE_RTKIT) += apple-rtkit.o apple-rtkit-y = rtkit.o rtkit-crashlog.o diff --git a/drivers/soc/apple/sleep-perf-step.S b/drivers/soc/apple/sleep-perf-step.S new file mode 100644 index 00000000000000..a50c9670fed166 --- /dev/null +++ b/drivers/soc/apple/sleep-perf-step.S @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * One performance-state step of a PMGR clock-performance register, with no + * memory access between the write and the end of the transition: the whole + * routine sits in one cache line, so a memory-clock change can't stall its + * own instruction fetch half-way. + */ + +#include +#include + +/* + * u32 apple_sleep_perf_step(void __iomem *reg, u32 state) + * + * Writes @state into the target field (bits 3:0) and waits for the busy bit + * (31) to clear, about two seconds at most. Returns the last value read; bit + * 31 still set means the transition didn't finish. + */ + .balign 64 +SYM_FUNC_START(apple_sleep_perf_step) + ldr w2, [x0] + bfi w2, w1, #0, #4 + dsb sy + isb + str w2, [x0] + mov x3, #(1 << 22) +1: ldr w2, [x0] + tbz w2, #31, 2f + subs x3, x3, #1 + b.ne 1b +2: dsb sy + mov w0, w2 + ret +SYM_FUNC_END(apple_sleep_perf_step) diff --git a/drivers/soc/apple/sleep-t8103.h b/drivers/soc/apple/sleep-t8103.h new file mode 100644 index 00000000000000..d9ffd8ae6e9d65 --- /dev/null +++ b/drivers/soc/apple/sleep-t8103.h @@ -0,0 +1,1647 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T8103 (M1): suspend-to-RAM through the PMGR's S2R timer. Included by sleep.c after the + * other profiles, so every shared helper is in scope. + * + * At .prepare (0x87, after SEP's sleep and before the SMC's last keys) the coprocessors no + * driver stops are idled and stopped, and the domains Linux leaves on that the sleep needs + * off are lowered. The commit then steps the memory clock down, quiesces the memory + * controller and cache, arms the AOP wake mask, parks the SoC clock muxes, quiesces the CPU + * complexes, turns CPM power gating on, takes both CPU clusters' targets off, AUTO_ENABLE off + * on three always-on words, clears SEP's power-gate wait, arms the watchdog and the PMU RTC + * alarm's SPMI vector, and writes the S2R timer. The cores power down without retention + * through CYC_OVRD and ACC_OVRD, after writing back their caches, as on the other + * Firestorm/Icestorm SoCs. Based on the t6000 suspend-to-RAM reference by Andreas Fernandez. + * + * A timed wake is the PMU RTC's alarm (wake source 54), set by its RTC driver. + */ + +/* "wake": five mask words, then five status words */ +#define T8103_WAKE_MASK 0x08 +#define T8103_WAKE_STATUS 0x1c +#define T8103_WAKE_WORDS 5 + +/* "clk-mux": the SoC clock muxes, parked in this order */ +#define T8103_MUX_PARK_KEEP 0xf0ffffff +#define T8103_MUX_PARK_SET 0x80000000 +#define T8103_MUX_BUSY BIT(30) +#define T8103_MUX_TIMEOUT_US 192000 +/* The SoC clock muxes: 40 words from here in the clock block */ +#define T8103_MUX_SOC 0x40100 + +/* "ps": the CPM power gating, the CPU clusters and the SEP power-gate wait */ +#define T8103_CPM_GATING BIT(31) +#define T8103_CLUSTER_E 0x18000 +#define T8103_CLUSTER_P 0x18004 +#define T8103_CLUSTER_BUSY BIT(4) +#define T8103_SEP_PG 0x4c200 +#define T8103_SEP_PG_WAIT BIT(2) +/* SEP's own power state word, and how long it gets to gate after its sleep's answer */ +#define T8103_SEP_PS 0xc00 +#define T8103_SEP_GATE_US 500000 + +/* "ps-aon": the S2R timer, the commit */ +#define T8103_S2R_TIMER 0x44000 + +/* "spmi" (nub, gen 1): vector enable words from +0x20, the PMU RTC alarm is vector 2 */ +#define T8103_SPMI_VEC_ENABLE 0x20 +#define T8103_SPMI_VEC_RTC BIT(2) +#define T8103_SPMI_VEC_ACK 0x60 +/* + * The reply notification is vector 192 here, as on t6000: its enable and ack words are the + * seventh, not gen 1's ninth. + */ +#define T8103_SPMI_NOTIFY_ENABLE (0x20 + 4 * (192 / 32)) +#define T8103_SPMI_NOTIFY_ACK (0x60 + 4 * (192 / 32)) +#define T8103_SPMI_EXT_WRITEL 0x30 + +/* The PMU's boot-stage byte: 0x50 while the AP sleeps */ +#define T8103_PMU_USID 0xf +#define T8103_PMU_BOOT_STAGE 0x9f01 +#define T8103_PMU_STAGE_SLEEP 0x50 +/* The watchdog from the commit to the wake, and from the wake to .end */ +#define T8103_WDT_COMMIT_SECS 60 +#define T8103_WDT_RESUME_SECS 35 + +/* "wake": word 0 bit 0 keeps DRAM up through the sleep (SLP_DDR) */ +#define T8103_WAKE_SLP_DDR 0x00 +#define T8103_WAKE_SLP_DDR_ON BIT(0) + +/* Each core's external debug block: 1 MiB apart, the clusters 16 MiB apart */ +#define T8103_ED 0x210010000ULL +#define T8103_ED_CORE 0x100000ULL +#define T8103_ED_CLUSTER 0x1000000ULL + +/* Per-core power-down controls */ +#define T8103_CYC_OVRD sys_reg(3, 5, 15, 5, 0) +#define T8103_CYC_DISABLE_WFI_RET BIT_ULL(0) +#define T8103_CYC_FIQ_MODE GENMASK_ULL(21, 20) +#define T8103_CYC_IRQ_MODE GENMASK_ULL(23, 22) +#define T8103_CYC_WFI_MODE GENMASK_ULL(25, 24) +#define T8103_ACC_OVRD sys_reg(3, 5, 15, 6, 0) +#define T8103_PMCR0 sys_reg(3, 1, 15, 0, 0) +#define T8103_ACC_PWR_DN_SRM GENMASK_ULL(14, 13) +#define T8103_ACC_DIS_L2_FLUSH GENMASK_ULL(16, 15) +#define T8103_ACC_TRAIN_DOWN_LINK GENMASK_ULL(18, 17) +#define T8103_ACC_POWER_DOWN_CPM GENMASK_ULL(26, 25) +#define T8103_ACC_DISABLE_PIO_ON_WFI BIT_ULL(32) +#define T8103_ACC_DEEP_SLEEP BIT_ULL(34) + +/* The valid sources in each wake mask word */ +static const u32 t8103_wake_valid[T8103_WAKE_WORDS] = { + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x03ffffff, +}; + +/* + * The mask the platform keeps at every sleep, as macOS sets it (a set bit masks): the AOP, NUB + * (the wake timer, the watchdog, SPMI0 SW3), SMC and ATC port sources left on. + */ +static const u32 t8103_wake_platform[T8103_WAKE_WORDS] = { + 0xf3ffafff, 0xffb97eff, 0xfffdeffe, 0xffffffff, 0x03ffff87, +}; + +static const u32 t8103_mux_park[] = { 0x40140, 0x40144, 0x40148, 0x4014c, 0x40154 }; + +/* The always-on words whose AUTO_ENABLE goes off for the sleep, in this order */ +static const u32 t8103_auto_off[] = { 0x1c8, 0x1c0, 0x1d0 }; + +static const u32 t8103_cpm[] = { 0x1c080, 0x1c088 }; + +static const u32 t8103_cluster[] = { T8103_CLUSTER_E, T8103_CLUSTER_P }; + +/* + * The CPU complexes' and voltage monitors' quiesce, as macOS runs it between the mux park and + * CPM gating: per cluster the energy accumulator, the + * fixed-frequency PLL relock and three throttlers off; the DCS, GFX, DISP and SOC voltage + * monitors off, each waited idle; then each cluster's APSC off, waited. ACC blocks at + * 0x210e20000 (E) and 0x211e20000 (P). + */ +#define T8103_ACC_E 0x210e20000ULL +#define T8103_ACC_P 0x211e20000ULL +#define T8103_ACC_LEN 0x30000 +#define T8103_ACC_DVFS 0x00020 +#define T8103_ACC_DVFS_RELOCK BIT_ULL(42) +#define T8103_ACC_DVFS_APSC_OFF BIT_ULL(22) +#define T8103_ACC_DVFS_PENDING BIT_ULL(7) +#define T8103_ACC_AMX_THRTL 0x20250 +#define T8103_ACC_LLC_THRTL 0x20240 +#define T8103_ACC_PPT_THRTL 0x28400 +#define T8103_ACC_ENERGY 0x28080 +#define T8103_ACC_ENERGY_EN (BIT_ULL(63) | BIT_ULL(61)) +#define T8103_THRTL_EN BIT_ULL(63) +/* In "ps": DCS, GFX, DISP, SOC, in macOS's order; idle at +0x3e0 bit 1 */ +static const u32 t8103_tvm[] = { 0x48400, 0x48800, 0x48c00, 0x48000 }; +#define T8103_TVM_EN BIT(0) +#define T8103_TVM_IDLE_OFF 0x3e0 +#define T8103_TVM_BUSY BIT(1) +#define T8103_QUIESCE_US 10000 +static const u32 t8103_acc_thrtl[] = { T8103_ACC_AMX_THRTL, T8103_ACC_LLC_THRTL, + T8103_ACC_PPT_THRTL }; + +/* + * The PMP: the boot loader starts its firmware and no Linux driver owns it here, and a commit + * with it running resets the SoC (as T8140 found). Idled over its RTKit management endpoint, + * then its CPU stopped; its domains stay on. The SIO and the display coprocessors likewise. + */ +#define T8103_PMP_ASC 0x23bc00000ULL +#define T8103_PMP_MBOX 0x23bc08000ULL +#define T8103_SIO_ASC 0x236400000ULL +#define T8103_SIO_MBOX 0x236408000ULL +#define T8103_DCP_MBOX 0x231c08000ULL +#define T8103_DCPEXT_ASC 0x271c00000ULL +#define T8103_DCPEXT_MBOX 0x271c08000ULL +/* The display coprocessors' CPU power words, in "ps" */ +#define T8103_DISP0_CPU_PS 0x10018 +#define T8103_DISPEXT_CPU_PS 0x378 +#define T8103_ASC_CPU_CONTROL 0x44 +#define T8103_ASC_CPU_RUN BIT(4) +#define T8103_ASC_CPU_STATUS 0x48 +#define T8103_ASC_CPU_IDLE GENMASK(1, 0) +#define T8103_MBOX_A2I_CONTROL 0x110 +#define T8103_MBOX_I2A_CONTROL 0x114 +#define T8103_MBOX_FULL BIT(16) +#define T8103_MBOX_EMPTY BIT(17) +#define T8103_MBOX_RECV_ENABLE BIT(0) +#define T8103_MBOX_A2I_SEND0 0x800 +#define T8103_MBOX_A2I_SEND1 0x808 +#define T8103_MBOX_I2A_RECV0 0x830 +#define T8103_MBOX_I2A_RECV1 0x838 +#define T8103_RTKIT_TYPE GENMASK_ULL(59, 52) +#define T8103_RTKIT_SET_IOP_PWR 6 +#define T8103_RTKIT_IOP_PWR_ACK 7 +#define T8103_RTKIT_PWR GENMASK_ULL(15, 0) +#define T8103_RTKIT_PWR_IDLE 0x201 +#define T8103_PMP_ACK_US 200000 +#define T8103_PMP_IDLE_US 10000 + +/* + * CLK_PERF_DCS (T8103_DCS_PERF) holds the memory clock's performance state: target in bits 3:0, + * busy in bit 31. Moving it by more than one state in a single write leaves memory unusable on + * this SoC, while single steps don't. The SoC's own sleep entry moves it to T8103_DCS_SLEEP in + * one write and its wake leaves it at T8103_DCS_WAKE, so it is stepped down to the sleep state + * before the commit and back up after the wake, one state at a time. + */ +#define T8103_DCS_PERF 0x23b05c000ULL +#define T8103_DCS_SLEEP 4 +#define T8103_DCS_WAKE 5 + +u32 apple_sleep_perf_step(void __iomem *reg, u32 state); + +/* Single steps to @target, each finished before the next. Returns false if one didn't finish. */ +static bool t8103_dcs_step_to(void __iomem *reg, unsigned int target, u32 *last) +{ + unsigned int cur = readl(reg) & 0xf; + u32 v = 0; + + while (cur != target) { + cur = cur < target ? cur + 1 : cur - 1; + v = apple_sleep_perf_step(reg, cur); + if (v & BIT(31)) { + *last = v; + return false; + } + } + *last = readl(reg); + return true; +} + +/* + * Domains genpd keeps on for an unbound consumer (sync_state) or stopped display/USB/PCIe blocks + * that macOS has off at its commit. Lowered children-before-parents after every stop. + */ +static const u32 t8103_commit_off[] = { + 0x3f8, /* 0: gfx */ + 0x10018, /* 1: disp0_cpu0 */ + 0x360, /* 2: disp0_fe */ + 0x378, /* 3: dispext_cpu0 */ + 0x368, /* 4: dispext_fe */ + 0x450, /* 5: atc1_pcie */ + 0x448, /* 6: atc1_common */ + 0x428, /* 7: atc0_pcie */ + 0x420, /* 8: atc0_common */ + 0x350, /* 9: rmx (parent of disp0_fe, dispext_fe) */ + 0x3d8, /* 10: pmp (parent of gfx, disp0_fe, dispext_fe) */ + 0x3e8, /* 11: apcie_gp */ + 0x348, /* 12: apcie (parent of apcie_gp) */ + 0x1a0, /* 13: pcie_ref (parent of apcie) */ + 0x130, /* 14: gpio (kept on through 0x85 for SEP, lowered after) */ +}; + +#define T8103_COMMIT_OFF_APCIE_START 11 +/* + * The display front ends' parents (pmp, rmx): genpd still counts them on after the wake, so + * nothing else raises them, and the DCP driver's power-up of DISP0 hangs without them. Put + * back as the commit found them, pmp first. + */ +#define T8103_COMMIT_OFF_PMP 10 +#define T8103_COMMIT_OFF_RMX 9 + +/* The PMGR's fabric bridge blocks: +0x14=1, +0x2bc=1,2,4 before their domain powers off */ +static const struct { + u64 pa; + u32 ps_off; +} t8103_bridges[] = { + { 0x205008000ULL, 0x3f8 }, /* reg[40]: gfx */ + { 0x232008000ULL, 0x360 }, /* reg[39]: disp0_fe */ + { 0x272008000ULL, 0x368 }, /* reg[44]: dispext_fe */ + { 0x68c008000ULL, 0x348 }, /* reg[41]: apcie */ +}; + +#define T8103_BRIDGE_8014 0x014 +#define T8103_BRIDGE_82BC 0x2bc + +/* pmgr_mini (ps_aon) domains left on by USB/debug/msg that must go off */ +static const u32 t8103_aon_commit_off[] = { + 0x98, /* 0: atc0_usb */ + 0xa0, /* 1: atc1_usb */ + 0x88, /* 2: atc0_usb_aon */ + 0x90, /* 3: atc1_usb_aon */ + 0xb8, /* 4: debug_usb */ + 0xc0, /* 5: debug_auth */ + 0x58, /* 6: debug */ + 0x78, /* 7: msg */ +}; + +/* Clock-gated ps domains (0x244) Linux leaves at actual 4, lowered to 0 as macOS has them */ +static const u32 t8103_cg_commit_off[] = { + 0x118, /* 0: soc_spmi0 */ + 0x120, /* 1: soc_spmi1 */ + 0x128, /* 2: soc_spmi2 */ + 0x148, /* 3: pms_fpwm0 */ + 0x150, /* 4: pms_fpwm1 */ + 0x158, /* 5: pms_fpwm2 */ + 0x160, /* 6: pms_fpwm3 */ + 0x168, /* 7: pms_fpwm4 */ + 0x1a8, /* 8: aft0 */ + 0x1b0, /* 9: devc0_ivdmc */ + 0x1d8, /* 10: fpwm0 */ + 0x1e8, /* 11: fpwm2 */ +}; + +/* + * The memory cache (SLC): its ways off before the CPU complexes' quiesce, as macOS has it, + * and back on at the wake. Broadcast control at 0x200100000, the four planes + * at 0x200000000 + 0x40000 * p; each plane reports its ways at +0x1c04 bits 14:10 and 9:5. + */ +#define T8103_MCC_BCAST 0x200100000ULL +#define T8103_MCC_BCAST_LP 0x04 +#define T8103_MCC_BCAST_LP_BITS 0x30000000U +#define T8103_MCC_BCAST_A 0x0c +#define T8103_MCC_BCAST_B 0x14 +#define T8103_MCC_AMCNP_ERR 0x55000 +#define T8103_MCC_PLANES 0x200000000ULL +#define T8103_MCC_NPLANES 4 +#define T8103_MCC_STRIDE 0x40000 +#define T8103_MCC_WAYS 0x1c00 +#define T8103_MCC_WAYS_STATUS 0x1c04 +#define T8103_MCC_WAYS_A GENMASK(14, 10) +#define T8103_MCC_WAYS_B GENMASK(9, 5) +#define T8103_MCC_ERR_EN0 0x9000 +#define T8103_MCC_ERR_EN1 0x9008 +#define T8103_MCC_TIMEOUT_US 100000 + +/* + * DCS channels, 8 x 0x40000 from 0x200200000: dynamic clock and power gating (+0xc), error + * reporting (+0x7a0), write queue flush (+0xa30) + */ +#define T8103_DCS_BASE 0x200200000ULL +#define T8103_DCS_NCHAN 8 +#define T8103_DCS_STRIDE 0x40000 +#define T8103_DCS_CTL 0x00c +#define T8103_DCS_CTL_LP 0x1100 +#define T8103_DCS_ERR_EN 0x7a0 +#define T8103_DCS_WQ_FLUSH 0xa30 +#define T8103_DCS_FLUSH_US 330 + +/* AIC: each CPU's IPI mask set at +0x5024 and its status at +0x5004, 0x80 per CPU */ +#define T8103_AIC_CPU 0x23b105000ULL +#define T8103_AIC_CPU_STRIDE 0x80 +#define T8103_AIC_CPU_STATUS 0x04 +#define T8103_AIC_CPU_MASK_SET 0x24 +#define T8103_AIC_CPU_MASK_CLR 0x28 +#define T8103_AIC_CPU_PENDING GENMASK(18, 16) +#define T8103_AIC_IPI_MASK 0x80000001 +#define T8103_AIC_CPUS 8 + +/* Always-on domains meant to run with AUTO_ENABLE that the boot loader leaves without it */ +static const u32 t8103_ps_boot_auto[] = { + 0x100, /* sbr */ + 0x138, /* pms_busif */ + 0x140, /* pms */ + 0x1b8, /* imx */ + 0x2f8, /* mcc */ + 0x300, /* dcs0 */ + 0x308, /* dcs2 */ + 0x310, /* dcs1 */ + 0x318, /* dcs3 */ + 0x320, /* dcs4 */ + 0x328, /* dcs6 */ + 0x330, /* dcs5 */ + 0x338, /* dcs7 */ + 0x340, /* smx */ + 0x3e0, /* pms_sram */ +}; + +static const u32 t8103_aon_boot_auto[] = { + 0x60, /* nub_spmi0 */ + 0x68, /* nub_spmi1 */ + 0x70, /* nub_aon */ + 0xa8, /* nub_fabric */ + 0xb0, /* nub_sram */ +}; + +static struct t8103_sleep { + void __iomem *mcc_bcast, *mcc_planes, *dcs, *aic_cpu; + void __iomem *bridges[ARRAY_SIZE(t8103_bridges)]; + /* The SoC clock muxes from T8103_MUX_SOC at the commit, and those the wake put back */ + u32 mux_snap[40]; + u64 mux_fixed; + u32 slc_ways, aic_ipi_mask[T8103_AIC_CPUS]; + u32 mcc_lp_saved, amcnp_err_saved; + u32 amcc_err0_saved[T8103_MCC_NPLANES], amcc_err1_saved[T8103_MCC_NPLANES]; + u32 dcs_ctl_saved[T8103_DCS_NCHAN], dcs_wq_saved[T8103_DCS_NCHAN]; + u32 dcs_err_saved[T8103_DCS_NCHAN]; + bool dcs_quiesced; + u8 slc_result, aic_result; + void __iomem *pmp_asc, *pmp_mbox, *sio_asc, *sio_mbox; + void __iomem *dcp_mbox, *dcpext_asc, *dcpext_mbox; + /* Each coprocessor's t8103_asc_stop() result */ + u8 pmp_result, sio_result, dcp_result, dcpext_result; + /* The t8103_commit_off and t8103_cg_commit_off words found or taken off */ + u16 commit_off, cg_commit_off; + /* The t8103_commit_off words this commit lowered, as it found them */ + u16 commit_lowered; + u32 commit_saved[ARRAY_SIZE(t8103_commit_off)]; + u8 aon_commit_off; + u32 cg_saved[ARRAY_SIZE(t8103_cg_commit_off)]; + /* The quiesce's blocks, what it found there, and whether it ran */ + void __iomem *acc[2]; + void __iomem *ed[2][4]; + u64 acc_dvfs[2], acc_energy[2], acc_thrtl[2][ARRAY_SIZE(t8103_acc_thrtl)]; + u32 tvm[ARRAY_SIZE(t8103_tvm)]; + bool quiesced; + unsigned int quiesce_timeouts; + /* The sources apple,wake-enable leaves on, by mask word */ + u32 wanted[T8103_WAKE_WORDS]; + struct platform_device *gpu; + + /* As prepare_regs found them, for the wake */ + bool saved; + u32 wake_mask[T8103_WAKE_WORDS]; + u32 wake_slp_ddr; + bool wake_slp_ddr_changed; + /* The AOP's driver is bound: DRAM stays up for it through the sleep (SLP_DDR) */ + bool aop_slp_ddr; + u32 mux[ARRAY_SIZE(t8103_mux_park)]; + void __iomem *dcs_perf; + u32 dcs_perf_saved; + u32 dcs_perf_down_val, dcs_perf_wake_val, dcs_perf_up_val; + bool dcs_perf_down, dcs_perf_down_ok, dcs_perf_up_ok; + u32 auto_word[ARRAY_SIZE(t8103_auto_off)]; + u32 cpm[ARRAY_SIZE(t8103_cpm)]; + u32 cluster[ARRAY_SIZE(t8103_cluster)]; + u32 sep_pg; + u32 spmi_vec; + + /* This attempt: the commit's results, read back at the wake and reported once */ + bool attempt, committed, sep_pg_cleared; + int sep_ps_gated; + u32 sep_ps; + u32 wake_entry[T8103_WAKE_WORDS]; + u8 mux_timeouts, cluster_timeouts; + int cluster_wake_ret[ARRAY_SIZE(t8103_cluster)]; + u8 mux_wake_timeouts; + /* Every interrupt line masked once for this commit (E14 before the timer) */ + bool aic_masked; +} t8103_sleep; + +/* + * A one-byte PMU write on nub-spmi0 by hand, in the commit, where nothing else talks SPMI: its + * reply notification masked, a stale reply read first, the command and its data, the reply + * checked, nothing left in the FIFO, the notification acknowledged and its enable put back. + */ +static int t8103_pmu_write(struct apple_sleep *s, u16 address, u8 val) +{ + u32 enable, status, reply, command = T8103_SPMI_EXT_WRITEL; + unsigned int i; + int ret = 0; + + enable = readl(s->spmi + T8103_SPMI_NOTIFY_ENABLE); + writel(enable & ~SPMI_NOTIFY_REPLY, s->spmi + T8103_SPMI_NOTIFY_ENABLE); + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_STATUS_RX_EMPTY); + i++) + readl(s->spmi + SPMI_REPLY); + + writel(command | FIELD_PREP(SPMI_CMD_USID, T8103_PMU_USID) | (u32)address << 16 | + SPMI_CMD_ACTIVE, s->spmi + SPMI_CMD); + writel(val, s->spmi + SPMI_CMD); + + if (readl_poll_timeout_atomic(s->spmi + SPMI_STATUS, status, + !(status & SPMI_STATUS_RX_EMPTY), 1, 1000)) { + ret = -ETIMEDOUT; + goto out; + } + reply = readl(s->spmi + SPMI_REPLY); + if ((reply & 0xff) != command || ((reply >> 8) & 0x7f) != T8103_PMU_USID || + !(reply & SPMI_CMD_ACTIVE)) + ret = -EIO; +out: + if (ret) + udelay(SPMI_POLL_US / 10); + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_STATUS_RX_EMPTY); + i++) + readl(s->spmi + SPMI_REPLY); + writel(1, s->spmi + T8103_SPMI_NOTIFY_ACK); + writel(enable, s->spmi + T8103_SPMI_NOTIFY_ENABLE); + return ret; +} + +static bool t8103_sleep_cpu_valid(u64 mpidr) +{ + /* E cores 0.0.n, P cores 1.1.n */ + return !(mpidr & ~MPIDR_HWID_BITMASK) && !MPIDR_AFFINITY_LEVEL(mpidr, 3) && + MPIDR_AFFINITY_LEVEL(mpidr, 1) == MPIDR_AFFINITY_LEVEL(mpidr, 2); +} + +/* Each core's power-down controls as Linux has them, back after a refusal or a reset */ +struct t8103_cpu_control { + u64 cyc, acc; + bool saved; +}; + +static DEFINE_PER_CPU(struct t8103_cpu_control, t8103_cpu_control); + +static int t8103_sleep_cpu_prepare(u64 mpidr) +{ + struct t8103_cpu_control *c = this_cpu_ptr(&t8103_cpu_control); + + if (!is_kernel_in_hyp_mode()) + return -EOPNOTSUPP; + if (!c->saved) { + c->cyc = read_sysreg_s(T8103_CYC_OVRD); + c->acc = read_sysreg_s(T8103_ACC_OVRD); + c->saved = true; + } + return 0; +} + +static void t8103_sleep_cpu_restore(u64 mpidr) +{ + struct t8103_cpu_control *c = this_cpu_ptr(&t8103_cpu_control); + + if (!c->saved) + return; + if (read_sysreg_s(T8103_ACC_OVRD) != c->acc) + write_sysreg_s(c->acc, T8103_ACC_OVRD); + if (read_sysreg_s(T8103_CYC_OVRD) != c->cyc) + write_sysreg_s(c->cyc, T8103_CYC_OVRD); + isb(); + c->saved = false; +} + +/* + * void t8103_cpu_off(u64 cyc_ovrd, u64 acc_ovrd): a core's last instructions. The data cache + * off, L1 written back and invalidated by set and way, then L2 written back by set and way (a + * cluster's L2 is not written back when it powers down), the timers off, the power-down + * controls written, then WFI until the power goes. Never returns. + */ +asm( +" .pushsection .text, \"ax\"\n" +" .type t8103_cpu_off, %function\n" +"t8103_cpu_off:\n" +" msr daifset, #0xf\n" +" mrs x3, sctlr_el1\n" +" bic x3, x3, #(1 << 2)\n" +" msr sctlr_el1, x3\n" +" isb\n" +" msr csselr_el1, xzr\n" +" isb\n" +" mrs x3, ccsidr_el1\n" +" and x4, x3, #7\n" +" add x4, x4, #4\n" +" ubfx x5, x3, #3, #10\n" +" ubfx x6, x3, #13, #15\n" +" clz w7, w5\n" +"1: mov x8, x6\n" +"2: lsl x9, x5, x7\n" +" lsl x10, x8, x4\n" +" orr x9, x9, x10\n" +" dc cisw, x9\n" +" subs x8, x8, #1\n" +" b.ge 2b\n" +" subs x5, x5, #1\n" +" b.ge 1b\n" +" dsb sy\n" +" isb\n" +/* L2 too: written back (clean only, others in the cluster may still run), set by way */ +" mov x3, #2\n" +" msr csselr_el1, x3\n" +" isb\n" +" mrs x3, ccsidr_el1\n" +" and x4, x3, #7\n" +" add x4, x4, #4\n" +" ubfx x5, x3, #3, #10\n" +" ubfx x6, x3, #13, #15\n" +" clz w7, w5\n" +" mov x11, #2\n" +"11: mov x8, x6\n" +"12: lsl x9, x5, x7\n" +" lsl x10, x8, x4\n" +" orr x9, x9, x10\n" +" orr x9, x9, x11\n" +" dc csw, x9\n" +" subs x8, x8, #1\n" +" b.ge 12b\n" +" subs x5, x5, #1\n" +" b.ge 11b\n" +" dsb sy\n" +" isb\n" +" msr cntp_ctl_el0, xzr\n" +" msr cntv_ctl_el0, xzr\n" +" mrs x3, CurrentEL\n" +" cmp x3, #(2 << 2)\n" +" b.ne 3f\n" +" msr s3_5_c14_c2_1, xzr\n" /* CNTP_CTL_EL02 */ +" msr s3_5_c14_c3_1, xzr\n" /* CNTV_CTL_EL02 */ +"3: msr s3_5_c15_c6_0, x1\n" /* ACC_OVRD */ +" msr s3_5_c15_c5_0, x0\n" /* CYC_OVRD */ +" isb\n" +" mov x9, #1\n" +"4: msr s3_5_c15_c1_1, x9\n" /* IPI_SR: a fast IPI ends WFI */ +" dsb sy\n" +" isb\n" +" wfi\n" +" b 4b\n" +" .size t8103_cpu_off, . - t8103_cpu_off\n" +" .popsection\n" +); +void t8103_cpu_off(u64 cyc_ovrd, u64 acc_ovrd); + +/* E10, on every core before its last WFI: power down without retention, woken by a reset. */ +static void t8103_deep_wfi_arm(void) +{ + u64 mpidr = read_cpuid_mpidr() & MPIDR_HWID_BITMASK; + unsigned int cluster = MPIDR_AFFINITY_LEVEL(mpidr, 2); + unsigned int core = MPIDR_AFFINITY_LEVEL(mpidr, 0); + u64 cyc = read_sysreg_s(T8103_CYC_OVRD), acc = read_sysreg_s(T8103_ACC_OVRD); + + /* + * The core's external debug block: unlocked, then its power-down request bits cleared, + * so a debugger's request doesn't hold the core's power on. + */ + if (cluster < 2 && core < 4 && t8103_sleep.ed[cluster][core]) { + writel_relaxed(0xc5acce55U, t8103_sleep.ed[cluster][core] + 0xfb0); + writel_relaxed(0, t8103_sleep.ed[cluster][core] + 0x310); + dsb(sy); + } + + /* The WFI mode and no retention, with the IRQ and FIQ modes cleared as t6000 has them */ + cyc &= ~(T8103_CYC_WFI_MODE | T8103_CYC_IRQ_MODE | T8103_CYC_FIQ_MODE); + cyc |= FIELD_PREP(T8103_CYC_WFI_MODE, 3) | T8103_CYC_DISABLE_WFI_RET; + /* The PMU counters and their interrupt off */ + write_sysreg_s(0, T8103_PMCR0); + acc &= ~(T8103_ACC_PWR_DN_SRM | T8103_ACC_DIS_L2_FLUSH | T8103_ACC_TRAIN_DOWN_LINK | + T8103_ACC_POWER_DOWN_CPM); + acc |= FIELD_PREP(T8103_ACC_PWR_DN_SRM, 3) | FIELD_PREP(T8103_ACC_DIS_L2_FLUSH, 2) | + FIELD_PREP(T8103_ACC_TRAIN_DOWN_LINK, 3) | FIELD_PREP(T8103_ACC_POWER_DOWN_CPM, 3) | + T8103_ACC_DISABLE_PIO_ON_WFI | T8103_ACC_DEEP_SLEEP; + t8103_cpu_off(cyc, acc); + unreachable(); +} + +/* + * The first thing Linux runs after a wake, MMU off and no stack: the PAC controls put back, + * then cpu_resume. + */ +asm( +" .pushsection .text, \"ax\"\n" +" .type t8103_resume_stub, %function\n" +"t8103_resume_stub:\n" +" adrp x0, t8103_pac_saved\n" +" add x0, x0, :lo12:t8103_pac_saved\n" +/* The PAC controls are back at their reset values: put back what the kernel signed with */ +" ldr x1, [x0, #16]\n" +" cbz x1, 8f\n" +" ldr x1, [x0]\n" +" msr s3_4_c15_c0_4, x1\n" +" ldr x1, [x0, #8]\n" +" msr s3_6_c15_c12_2, x1\n" +" isb\n" +"8:\n" +" b cpu_resume\n" +" .size t8103_resume_stub, . - t8103_resume_stub\n" +" .popsection\n" +); +void t8103_resume_stub(void); + +/* + * The cores' PAC control registers (APCTL_EL1, APCTL_EL2) come back from the core reset of a + * wake at their reset values, not the ones the kernel's return addresses were signed with. + * Saved here right before the commit; t8103_resume_stub puts them back, MMU off, before + * cpu_resume. [2] says they're valid. + */ +u64 t8103_pac_saved[3] __aligned(64); + +/* Right before the timer: the PAC controls, and this stack to the point of coherency */ +static void t8103_pre_commit(struct apple_sleep *s) +{ + t8103_pac_saved[0] = read_sysreg_s(sys_reg(3, 4, 15, 0, 4)); + t8103_pac_saved[1] = read_sysreg_s(sys_reg(3, 6, 15, 12, 2)); + t8103_pac_saved[2] = 1; + dcache_clean_poc((unsigned long)t8103_pac_saved, + (unsigned long)t8103_pac_saved + sizeof(t8103_pac_saved)); + dcache_clean_poc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); +} + +/* E14 once, before the timer: the shared commit's call after it then changes nothing. */ +static void t8103_aic_mask_all(void) +{ + if (t8103_sleep.aic_masked) + return; + aic_sleep_mask_all(); + t8103_sleep.aic_masked = true; +} + +static void t8103_aic_restore(void) +{ + if (!t8103_sleep.aic_masked) + return; + aic_sleep_restore(); + t8103_sleep.aic_masked = false; +} + +static void __iomem *t8103_map(struct apple_sleep *s, const char *name, resource_size_t min, + struct resource *res) +{ + struct device_node *np = s->dev->of_node; + int index = of_property_match_string(np, "reg-names", name); + + if (index < 0 || of_address_to_resource(np, index, res)) + return IOMEM_ERR_PTR(-ENODEV); + if (resource_size(res) < min) + return IOMEM_ERR_PTR(-EINVAL); + /* Shared with the drivers of these blocks, so not claimed. */ + return apple_sleep_map(s->dev, name); +} + +/* Mapped for good, non-posted (a posted write to these blocks is an SError), or NULL */ +static void __iomem *t8103_ioremap(struct apple_sleep *s, phys_addr_t pa, size_t len) +{ + void __iomem *base = ioremap_np(pa, len); + + if (base && devm_add_action_or_reset(s->dev, apple_sleep_iounmap, (void __force *)base)) + return NULL; + return base; +} + +static int t8103_sleep_map_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + struct resource res; + struct device_node *np; + int i, c, ret; + + s->ps = t8103_map(s, "ps", T8103_SEP_PG + 4, &res); + s->ps_aon = t8103_map(s, "ps-aon", T8103_S2R_TIMER + 4, &res); + s->clk_mux = t8103_map(s, "clk-mux", T8103_MUX_SOC + 4 * ARRAY_SIZE(t->mux_snap), &res); + s->wake = t8103_map(s, "wake", T8103_WAKE_STATUS + 4 * T8103_WAKE_WORDS, &res); + s->cpu_start = t8103_map(s, "cpu-start", CPU_START_CLUSTER(1) + 4, &res); + s->wdt = t8103_map(s, "wdt", WDT_WD1_CTL + 4, &res); + s->spmi = t8103_map(s, "spmi", SPMI_NOTIFY_ACK + 4, &res); + if (IS_ERR(s->ps) || IS_ERR(s->ps_aon) || IS_ERR(s->clk_mux) || IS_ERR(s->wake) || + IS_ERR(s->cpu_start) || IS_ERR(s->wdt) || IS_ERR(s->spmi)) + return dev_err_probe(s->dev, -EINVAL, + "ps, ps-aon, clk-mux, wake, cpu-start, wdt and spmi must all be mapped\n"); + /* + * The CPU complexes' blocks and the cores' external debug blocks, the memory controller + * and cache, the AIC's per-CPU words, the memory clock's performance state, the + * coprocessors stopped at the commit and the fabric bridges: none of them in the sleep + * node's reg, each shared with its own driver where it has one, so not claimed. + */ + for (i = 0; i < 2; i++) { + t->acc[i] = t8103_ioremap(s, i ? T8103_ACC_P : T8103_ACC_E, T8103_ACC_LEN); + if (!t->acc[i]) + return dev_err_probe(s->dev, -ENOMEM, "ACC blocks not mapped\n"); + for (c = 0; c < 4; c++) + t->ed[i][c] = t8103_ioremap(s, T8103_ED + i * T8103_ED_CLUSTER + + c * T8103_ED_CORE, 0x1000); + } + t->mcc_bcast = t8103_ioremap(s, T8103_MCC_BCAST, 0x60000); + t->mcc_planes = t8103_ioremap(s, T8103_MCC_PLANES, T8103_MCC_NPLANES * T8103_MCC_STRIDE); + t->dcs = t8103_ioremap(s, T8103_DCS_BASE, T8103_DCS_NCHAN * T8103_DCS_STRIDE); + t->aic_cpu = t8103_ioremap(s, T8103_AIC_CPU, T8103_AIC_CPUS * T8103_AIC_CPU_STRIDE); + if (!t->mcc_bcast || !t->mcc_planes || !t->dcs || !t->aic_cpu) + return dev_err_probe(s->dev, -ENOMEM, "MCC, DCS or AIC CPU block not mapped\n"); + t->dcs_perf = t8103_ioremap(s, T8103_DCS_PERF, 4); + t->pmp_asc = t8103_ioremap(s, T8103_PMP_ASC, 0x100); + t->pmp_mbox = t8103_ioremap(s, T8103_PMP_MBOX, 0x1000); + t->sio_asc = t8103_ioremap(s, T8103_SIO_ASC, 0x100); + t->sio_mbox = t8103_ioremap(s, T8103_SIO_MBOX, 0x1000); + t->dcp_mbox = t8103_ioremap(s, T8103_DCP_MBOX, 0x1000); + t->dcpext_asc = t8103_ioremap(s, T8103_DCPEXT_ASC, 0x100); + t->dcpext_mbox = t8103_ioremap(s, T8103_DCPEXT_MBOX, 0x1000); + for (i = 0; i < ARRAY_SIZE(t8103_bridges); i++) + t->bridges[i] = t8103_ioremap(s, t8103_bridges[i].pa, 0x1000); + /* The commit word is the S2R timer, the clusters' words are in "ps". */ + s->commit = s->ps_aon + T8103_S2R_TIMER; + s->cluster = s->ps; + + ret = apple_sleep_read_wake_sources(s); + if (ret) + return ret; + for (i = 0; i < s->wake_enable_count; i++) { + u32 id = s->wake_enable[i]; + + if (id / 32 >= T8103_WAKE_WORDS || !(t8103_wake_valid[id / 32] & BIT(id % 32))) + return dev_err_probe(s->dev, -EINVAL, "wake source %u is not valid\n", id); + t->wanted[id / 32] |= BIT(id % 32); + } + + np = of_find_compatible_node(NULL, NULL, "apple,agx-t8103"); + if (np) { + t->gpu = of_find_device_by_node(np); + of_node_put(np); + } + if (t->gpu && + devm_add_action_or_reset(s->dev, apple_sleep_put_device, &t->gpu->dev)) + return -ENOMEM; + + /* + * The AP pins' controller stays powered through the noirq phase: SEP answers its sleep + * request at 0x85 only with the GPIO domain on, and the commit lowers it. + */ + np = of_parse_phandle(s->dev->of_node, "apple,pinctrl", 0); + if (np) { + struct platform_device *pctl = of_find_device_by_node(np); + + if (pctl) { + dev_pm_syscore_device(&pctl->dev, true); + put_device(&pctl->dev); + } + of_node_put(np); + } + + dev_info(s->dev, "T8103: wake sources %08x %08x %08x %08x %08x\n", t->wanted[0], + t->wanted[1], t->wanted[2], t->wanted[3], t->wanted[4]); + return 0; +} + +/* + * The AOP runs through the sleep and reaches DRAM: with its driver bound, the sleep keeps DRAM + * up for it (SLP_DDR), as for the USB host's vote. With it unbound, or after a coprocessor + * crash, or when this sleep was asked to go deep, DRAM goes down with the rest. + */ +static bool t8103_aop_bound(void) +{ + struct device_node *np = of_find_compatible_node(NULL, NULL, "apple,t8103-aop"); + struct platform_device *pdev = np ? of_find_device_by_node(np) : NULL; + bool bound = pdev && device_is_bound(&pdev->dev); + + if (pdev) + put_device(&pdev->dev); + of_node_put(np); + return bound; +} + +static int t8103_sleep_begin(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + t->attempt = true; + t->committed = false; + t->saved = false; + t->aic_masked = false; + t->sep_pg_cleared = false; + t->mux_timeouts = 0; + t->cluster_timeouts = 0; + t->mux_wake_timeouts = 0; + memset(t->cluster_wake_ret, 0, sizeof(t->cluster_wake_ret)); + t->aop_slp_ddr = t8103_aop_bound(); + if (t->aop_slp_ddr) + dev_info(s->dev, "T8103: AOP bound: DRAM stays up for it\n"); + return 0; +} + +/* The SoC's own refusals, before any other: nothing has been written yet. */ +static int t8103_sleep_check(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i, wanted = 0; + + /* The GPU coprocessor doesn't survive the power cut, and it can't be started twice. */ + if (t->gpu && device_is_bound(&t->gpu->dev)) { + dev_err(s->dev, "refused: the GPU's driver is bound\n"); + return -EBUSY; + } + + for (i = 0; i < T8103_WAKE_WORDS; i++) + wanted += hweight32(t->wanted[i] & t8103_wake_valid[i]); + if (!wanted) { + dev_err(s->dev, "refused: no wake source enabled\n"); + return -EINVAL; + } + return 0; +} + +/* + * A coprocessor CPU's registers answer while its domain is at full power, or asked for full + * power with AUTO_ENABLE, which brings an auto clock-gated one back on access (a running + * DCP reads actual 4 this way). Not once its driver has lowered it: target 0, no AUTO_ENABLE. + */ +static bool t8103_cpu_answers(struct apple_sleep *s, u32 ps) +{ + u32 v = readl(s->ps + ps); + + return FIELD_GET(PS_ACTUAL, v) == 0xf || + (FIELD_GET(PS_TARGET, v) == 0xf && (v & PS_AUTO_ENABLE)); +} + +/* + * Nothing here talks to the display coprocessor or lowers its domains: its driver stops it + * for the sleep where it can, and its state is only reported. + */ +static int t8103_sleep_display_off(struct apple_sleep *s) +{ + void __iomem *asc = s->display[0].asc; + bool answers = s->display[0].bound && asc && t8103_cpu_answers(s, T8103_DISP0_CPU_PS); + + dev_info(s->dev, "T8103: display coprocessor %s, CPU power %#x, control %#x; left as it is\n", + s->display[0].bound ? "bound" : "unbound", readl(s->ps + T8103_DISP0_CPU_PS), + answers ? readl(asc + ASC_CPU_CONTROL) : 0); + return 0; +} + +static void t8103_pre_smc_down(struct apple_sleep *s); + +/* Reversible: every word the commit and the wake write, saved. Nothing is written. */ +static void t8103_sleep_prepare_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + + for (i = 0; i < T8103_WAKE_WORDS; i++) + t->wake_mask[i] = readl(s->wake + T8103_WAKE_MASK + 4 * i); + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) + t->mux[i] = readl(s->clk_mux + t8103_mux_park[i]); + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + t->auto_word[i] = readl(s->ps + t8103_auto_off[i]); + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + t->cpm[i] = readl(s->ps + t8103_cpm[i]); + for (i = 0; i < ARRAY_SIZE(t8103_cluster); i++) + t->cluster[i] = readl(s->ps + t8103_cluster[i]); + t->sep_pg = readl(s->ps + T8103_SEP_PG); + t->spmi_vec = readl(s->spmi + T8103_SPMI_VEC_ENABLE); + t->saved = true; + if (s->entry_committed) + t8103_pre_smc_down(s); +} + +/* prepare_regs writes nothing, so neither does this. */ +static void t8103_sleep_undo_regs(struct apple_sleep *s) +{ + t8103_sleep.saved = false; +} + +/* + * A coprocessor's RTKit idled over its management endpoint, then its CPU stopped. In the + * commit, interrupts off, the boot core alone: nothing waits on it after. + * Returns bit 0 acked, 1 CPU idle, 2 stopped, 4 already stopped, 5 not mapped. + */ +static u8 t8103_asc_stop(void __iomem *asc, void __iomem *m) +{ + unsigned int us, n; + u8 result = 0; + u64 msg0; + u32 v; + + if (!asc || !m) + return BIT(5); + if (!(readl(asc + T8103_ASC_CPU_CONTROL) & T8103_ASC_CPU_RUN)) + return BIT(4); + for (n = 0; n < 64 && !(readl(m + T8103_MBOX_I2A_CONTROL) & T8103_MBOX_EMPTY); n++) { + readq(m + T8103_MBOX_I2A_RECV0); + readq(m + T8103_MBOX_I2A_RECV1); + } + for (us = 0; us < T8103_PMP_ACK_US && (readl(m + T8103_MBOX_A2I_CONTROL) & T8103_MBOX_FULL); + us += 10) + udelay(10); + writeq(FIELD_PREP(T8103_RTKIT_TYPE, T8103_RTKIT_SET_IOP_PWR) | + FIELD_PREP(T8103_RTKIT_PWR, T8103_RTKIT_PWR_IDLE), m + T8103_MBOX_A2I_SEND0); + writeq(0, m + T8103_MBOX_A2I_SEND1); + for (us = 0; us < T8103_PMP_ACK_US; us += 10) { + if (readl(m + T8103_MBOX_I2A_CONTROL) & T8103_MBOX_EMPTY) { + udelay(10); + continue; + } + msg0 = readq(m + T8103_MBOX_I2A_RECV0); + readq(m + T8103_MBOX_I2A_RECV1); + if (FIELD_GET(T8103_RTKIT_TYPE, msg0) == T8103_RTKIT_IOP_PWR_ACK && + FIELD_GET(T8103_RTKIT_PWR, msg0) == T8103_RTKIT_PWR_IDLE) { + result |= BIT(0); + break; + } + } + /* Its outbox off, then RUN cleared once it idles */ + writel(readl(m + T8103_MBOX_I2A_CONTROL) & ~T8103_MBOX_RECV_ENABLE, + m + T8103_MBOX_I2A_CONTROL); + if (!readl_poll_timeout_atomic(asc + T8103_ASC_CPU_STATUS, v, + (v & T8103_ASC_CPU_IDLE) == T8103_ASC_CPU_IDLE, 1, + T8103_PMP_IDLE_US)) + result |= BIT(1); + writel(readl(asc + T8103_ASC_CPU_CONTROL) & ~T8103_ASC_CPU_RUN, + asc + T8103_ASC_CPU_CONTROL); + return result | BIT(2); +} + +static void t8103_pmp_stop(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + t->pmp_result = t8103_asc_stop(t->pmp_asc, t->pmp_mbox); + t->sio_result = 0; + if (FIELD_GET(PS_ACTUAL, readl(s->ps + 0x1d0))) + t->sio_result = t8103_asc_stop(t->sio_asc, t->sio_mbox); + /* + * Both display coprocessors: bound and running; drivers restart them at the wake. Not + * once a driver has lowered the CPU's domain itself: its registers don't answer then. + */ + t->dcp_result = 0; + if (s->display[0].bound && t8103_cpu_answers(s, T8103_DISP0_CPU_PS)) + t->dcp_result = t8103_asc_stop(s->display[0].asc, t->dcp_mbox); + t->dcpext_result = 0; + if (t8103_cpu_answers(s, T8103_DISPEXT_CPU_PS)) + t->dcpext_result = t8103_asc_stop(t->dcpext_asc, t->dcpext_mbox); +} + +/* + * The memory controller's platform error reporting off, its and the DCS channels' dynamic + * clock and power gating on, and the DCS write queues flushed, each as it was put back at the + * wake. + */ +static void t8103_dcs_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int ch, p; + + t->amcnp_err_saved = readl(t->mcc_bcast + T8103_MCC_AMCNP_ERR); + writel(0, t->mcc_bcast + T8103_MCC_AMCNP_ERR); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *base = t->mcc_planes + p * T8103_MCC_STRIDE; + + t->amcc_err0_saved[p] = readl(base + T8103_MCC_ERR_EN0); + t->amcc_err1_saved[p] = readl(base + T8103_MCC_ERR_EN1); + writel(0, base + T8103_MCC_ERR_EN1); + writel(0, base + T8103_MCC_ERR_EN0); + } + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_ERR_EN; + + t->dcs_err_saved[ch] = readl(reg); + writel(0, reg); + } + t->mcc_lp_saved = readl(t->mcc_bcast + T8103_MCC_BCAST_LP); + writel(t->mcc_lp_saved | T8103_MCC_BCAST_LP_BITS, t->mcc_bcast + T8103_MCC_BCAST_LP); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_CTL; + + t->dcs_ctl_saved[ch] = readl(reg); + writel(t->dcs_ctl_saved[ch] | T8103_DCS_CTL_LP, reg); + } + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) { + void __iomem *reg = t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_WQ_FLUSH; + + t->dcs_wq_saved[ch] = readl(reg); + writel(t->dcs_wq_saved[ch] & 0xffff0000U, reg); + } + /* The flush's time: the queues have no status to poll */ + udelay(T8103_DCS_FLUSH_US); + t->dcs_quiesced = true; +} + +static void t8103_dcs_restore(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int ch, p; + + if (!t->dcs_quiesced) + return; + t->dcs_quiesced = false; + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_wq_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_WQ_FLUSH); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_ctl_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_CTL); + writel(t->mcc_lp_saved, t->mcc_bcast + T8103_MCC_BCAST_LP); + for (ch = 0; ch < T8103_DCS_NCHAN; ch++) + writel(t->dcs_err_saved[ch], t->dcs + ch * T8103_DCS_STRIDE + T8103_DCS_ERR_EN); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *base = t->mcc_planes + p * T8103_MCC_STRIDE; + + writel(t->amcc_err1_saved[p], base + T8103_MCC_ERR_EN1); + writel(t->amcc_err0_saved[p], base + T8103_MCC_ERR_EN0); + } + writel(t->amcnp_err_saved, t->mcc_bcast + T8103_MCC_AMCNP_ERR); +} + +/* The ways set to @ways on every plane at once, then each plane waited for: 0 on success */ +static int t8103_slc_set(struct apple_sleep *s, u32 ways) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int p, bad = 0; + u32 v; + + writel(1, t->mcc_bcast + T8103_MCC_BCAST_A); + writel(1, t->mcc_bcast + T8103_MCC_BCAST_B); + writel(ways, t->mcc_planes + T8103_MCC_WAYS); + writel(0, t->mcc_bcast + T8103_MCC_BCAST_A); + writel(0, t->mcc_bcast + T8103_MCC_BCAST_B); + for (p = 0; p < T8103_MCC_NPLANES; p++) { + void __iomem *reg = t->mcc_planes + p * T8103_MCC_STRIDE + T8103_MCC_WAYS_STATUS; + + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(T8103_MCC_WAYS_A, v) == ways, 1, + T8103_MCC_TIMEOUT_US) || + readl_poll_timeout_atomic(reg, v, FIELD_GET(T8103_MCC_WAYS_B, v) == ways, 1, + T8103_MCC_TIMEOUT_US)) + bad |= BIT(p); + } + return bad; +} + +/* The memory cache's ways off before the CPU complexes' quiesce, as macOS has it */ +static void t8103_slc_off(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + u32 v = readl(t->mcc_planes + T8103_MCC_WAYS_STATUS); + + t->slc_result = 0; + t->slc_ways = FIELD_GET(T8103_MCC_WAYS_B, v); + if (!t->slc_ways) + return; + t->slc_result = BIT(7) | t8103_slc_set(s, 0); +} + +static void t8103_slc_on(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + if (!(t->slc_result & BIT(7))) + return; + t->slc_result = 0; + t8103_slc_set(s, t->slc_ways); +} + +/* After the AIC's mask: each CPU's IPIs masked and drained, as macOS has them */ +static void t8103_aic_ipi_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->aic_result = 0; + for (i = 0; i < T8103_AIC_CPUS; i++) { + void __iomem *c = t->aic_cpu + i * T8103_AIC_CPU_STRIDE; + + t->aic_ipi_mask[i] = readl(c + T8103_AIC_CPU_MASK_CLR); + writel(T8103_AIC_IPI_MASK, c + T8103_AIC_CPU_MASK_SET); + if (readl_poll_timeout_atomic(c + T8103_AIC_CPU_STATUS, v, + !(v & T8103_AIC_CPU_PENDING), 1, 10000)) + t->aic_result |= BIT(i); + } +} + +static void t8103_aic_ipi_restore(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + + for (i = 0; i < T8103_AIC_CPUS; i++) { + void __iomem *c = t->aic_cpu + i * T8103_AIC_CPU_STRIDE; + + writel(t->aic_ipi_mask[i], c + T8103_AIC_CPU_MASK_SET); + writel(~t->aic_ipi_mask[i], c + T8103_AIC_CPU_MASK_CLR); + } +} + +/* The quiesce, irreversible: in the commit, interrupts off, the boot core alone */ +static void t8103_quiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int c, i; + u64 q; + u32 v; + + t->quiesced = false; + t->quiesce_timeouts = 0; + for (c = 0; c < 2; c++) { + t->acc_energy[c] = readq(t->acc[c] + T8103_ACC_ENERGY); + writeq(t->acc_energy[c] & ~T8103_ACC_ENERGY_EN, t->acc[c] + T8103_ACC_ENERGY); + } + for (c = 0; c < 2; c++) { + t->acc_dvfs[c] = readq(t->acc[c] + T8103_ACC_DVFS); + writeq(t->acc_dvfs[c] & ~T8103_ACC_DVFS_RELOCK, t->acc[c] + T8103_ACC_DVFS); + } + for (i = 0; i < ARRAY_SIZE(t8103_acc_thrtl); i++) + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + t8103_acc_thrtl[i]; + + t->acc_thrtl[c][i] = readq(reg); + writeq(t->acc_thrtl[c][i] & ~T8103_THRTL_EN, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_tvm); i++) { + t->tvm[i] = readl(s->ps + t8103_tvm[i]); + writel(t->tvm[i] & ~T8103_TVM_EN, s->ps + t8103_tvm[i]); + if (readl_poll_timeout_atomic(s->ps + t8103_tvm[i] + T8103_TVM_IDLE_OFF, v, + !(v & T8103_TVM_BUSY), 1, T8103_QUIESCE_US)) + t->quiesce_timeouts++; + } + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_DVFS; + + writeq(readq(reg) | T8103_ACC_DVFS_APSC_OFF, reg); + if (readq_poll_timeout_atomic(reg, q, !(q & T8103_ACC_DVFS_PENDING), 1, + T8103_QUIESCE_US)) + t->quiesce_timeouts++; + } + t->quiesced = true; +} + +/* At the wake, in reverse: only the bits the quiesce changed */ +static void t8103_unquiesce(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int c, i; + + if (!t->quiesced) + return; + t->quiesced = false; + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_DVFS; + u64 q; + + if (t->cluster_wake_ret[c]) + continue; + q = readq(reg); + q = (q & ~(T8103_ACC_DVFS_APSC_OFF | T8103_ACC_DVFS_RELOCK)) | + (t->acc_dvfs[c] & (T8103_ACC_DVFS_APSC_OFF | T8103_ACC_DVFS_RELOCK)); + writeq(q, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_tvm); i++) + if (t->tvm[i] & T8103_TVM_EN) + writel(readl(s->ps + t8103_tvm[i]) | T8103_TVM_EN, s->ps + t8103_tvm[i]); + for (i = 0; i < ARRAY_SIZE(t8103_acc_thrtl); i++) + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + t8103_acc_thrtl[i]; + + if (t->cluster_wake_ret[c]) + continue; + writeq(readq(reg) | (t->acc_thrtl[c][i] & T8103_THRTL_EN), reg); + } + for (c = 0; c < 2; c++) { + void __iomem *reg = t->acc[c] + T8103_ACC_ENERGY; + + if (!t->cluster_wake_ret[c]) + writeq(readq(reg) | (t->acc_energy[c] & T8103_ACC_ENERGY_EN), reg); + } +} + +/* + * At 0x87, after SEP's sleep and before the SMC's last keys, as t6000 has it: SEP's domain + * forced off (FORCE_NOACCESS, no minimum) and waited for, the PMP, SIO and both display + * coprocessors stopped, then the always-on PMGR's USB and debug domains and the main PMGR's + * stopped blocks lowered (gpio last, at the commit), with the fabric bridges' handshake + * first. The always-on domains that should come back by themselves get AUTO_ENABLE. + */ +static void t8103_pre_smc_down(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->sep_ps_gated = -ENODATA; + if (apple_sleep_enclave.stop) { + v = readl(s->ps + T8103_SEP_PS); + writel((v & ~0x0f000700U) | BIT(10), s->ps + T8103_SEP_PS); + t->sep_ps_gated = readl_poll_timeout_atomic(s->ps + T8103_SEP_PS, v, + !FIELD_GET(PS_ACTUAL, v), 10, + T8103_SEP_GATE_US); + t->sep_ps = v; + } + t8103_pmp_stop(s); + t->aon_commit_off = 0; + for (i = 0; i < ARRAY_SIZE(t8103_aon_commit_off); i++) { + void __iomem *reg = s->ps_aon + t8103_aon_commit_off[i]; + u32 av = readl(reg); + + if (!FIELD_GET(PS_ACTUAL, av)) { + t->aon_commit_off |= BIT(i); + continue; + } + writel((av & ~(PS_TARGET | PS_AUTO_ENABLE)) | BIT(8) | BIT(9), reg); + if (!readl_poll_timeout_atomic(reg, av, !FIELD_GET(PS_ACTUAL, av), 1, 10000)) + t->aon_commit_off |= BIT(i); + } + t->commit_off = 0; + t->commit_lowered = 0; + for (i = 0; i < ARRAY_SIZE(t8103_commit_off) - 1; i++) { + unsigned int b; + + if (!sleep_ps_on(s, t8103_commit_off[i])) { + t->commit_off |= BIT(i); + continue; + } + for (b = 0; b < ARRAY_SIZE(t8103_bridges); b++) { + if (t8103_bridges[b].ps_off != t8103_commit_off[i] || !t->bridges[b]) + continue; + writel(1, t->bridges[b] + T8103_BRIDGE_8014); + writel(1, t->bridges[b] + T8103_BRIDGE_82BC); + writel(2, t->bridges[b] + T8103_BRIDGE_82BC); + writel(4, t->bridges[b] + T8103_BRIDGE_82BC); + } + t->commit_saved[i] = readl(s->ps + t8103_commit_off[i]); + t->commit_lowered |= BIT(i); + sleep_ps_lower(s, t8103_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_commit_off[i])) + t->commit_off |= BIT(i); + } + t->cg_commit_off = 0; + for (i = 0; i < ARRAY_SIZE(t8103_cg_commit_off); i++) { + void __iomem *reg = s->ps + t8103_cg_commit_off[i]; + u32 cv = readl(reg); + + t->cg_saved[i] = cv; + if (!FIELD_GET(PS_ACTUAL, cv)) { + t->cg_commit_off |= BIT(i); + continue; + } + sleep_ps_lower(s, t8103_cg_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_cg_commit_off[i])) + t->cg_commit_off |= BIT(i); + } + for (i = 0; i < ARRAY_SIZE(t8103_ps_boot_auto); i++) { + void __iomem *reg = s->ps + t8103_ps_boot_auto[i]; + u32 bv = readl(reg); + + if ((bv & PS_AUTO_ENABLE) || !FIELD_GET(PS_TARGET, bv) || !FIELD_GET(PS_ACTUAL, bv)) + continue; + writel(bv & ~PS_FLAGS, reg); + readl(reg); + writel((bv & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } + for (i = 0; i < ARRAY_SIZE(t8103_aon_boot_auto); i++) { + void __iomem *reg = s->ps_aon + t8103_aon_boot_auto[i]; + u32 bv = readl(reg); + + if ((bv & PS_AUTO_ENABLE) || !FIELD_GET(PS_TARGET, bv) || !FIELD_GET(PS_ACTUAL, bv)) + continue; + writel(bv & ~PS_FLAGS, reg); + readl(reg); + writel((bv & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } +} + +/* + * The commit: the memory clock stepped down, the memory controller and cache quiesced, then + * the wake mask, the clock muxes, the CPU complexes' quiesce, CPM gating, the clusters, + * AUTO_ENABLE and SEP's power-gate wait in the order the hardware takes them, then the + * watchdog, the alarm's vector, the PMU's boot stage and the AIC. The shared commit then arms + * the mailbox and writes the S2R timer. Nothing printed, nothing can fail: a timeout is kept + * for the report. + */ +static void t8103_sleep_commit_regs(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t->committed = true; + /* A hang in the writes below still ends in a reset. */ + apple_sleep_set_wd2(s, T8103_WDT_COMMIT_SECS); + t->dcs_perf_down = false; + if (t->dcs_perf) { + /* The other cores are parked and the coprocessors that use memory are stopped. */ + t->dcs_perf_saved = readl(t->dcs_perf); + t->dcs_perf_down_ok = t8103_dcs_step_to(t->dcs_perf, T8103_DCS_SLEEP, + &t->dcs_perf_down_val); + t->dcs_perf_down = true; + } + /* gpio, the last of t8103_commit_off, once SEP and the SMC are done with it */ + i = ARRAY_SIZE(t8103_commit_off) - 1; + if (!sleep_ps_on(s, t8103_commit_off[i])) { + t->commit_off |= BIT(i); + } else { + sleep_ps_lower(s, t8103_commit_off[i]); + if (!sleep_ps_wait_off(s, t8103_commit_off[i])) + t->commit_off |= BIT(i); + } + t8103_dcs_quiesce(s); + t8103_slc_off(s); + + /* + * E1: DRAM kept up through the sleep for the AOP (SLP_DDR), unless it crashed or this + * sleep goes deep; else its vote cleared. Then every valid source masked but the wanted + * ones and those the platform always leaves on. + */ + t->wake_slp_ddr = readl(s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = false; + if (t->aop_slp_ddr && !sleep_slp_ddr_crashed && !sleep_slp_ddr_deep_once) { + writel(t->wake_slp_ddr | T8103_WAKE_SLP_DDR_ON, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = true; + } else if (t->wake_slp_ddr & T8103_WAKE_SLP_DDR_ON) { + writel(t->wake_slp_ddr & ~T8103_WAKE_SLP_DDR_ON, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = true; + } + for (i = 0; i < T8103_WAKE_WORDS; i++) { + u32 mask = t8103_wake_platform[i] & ~t->wanted[i]; + + writel(mask, s->wake + T8103_WAKE_MASK + 4 * i); + s->wake_armed[i] = t8103_wake_valid[i] & ~mask; + } + /* E2: the latched sources cleared */ + for (i = 0; i < T8103_WAKE_WORDS; i++) { + v = readl(s->wake + T8103_WAKE_STATUS + 4 * i); + t->wake_entry[i] = v; + writel(v, s->wake + T8103_WAKE_STATUS + 4 * i); + } + /* E3: the SoC clock muxes parked, each waited for */ + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) { + void __iomem *reg = s->clk_mux + t8103_mux_park[i]; + + writel((readl(reg) & T8103_MUX_PARK_KEEP) | T8103_MUX_PARK_SET, reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_timeouts++; + } + for (i = 0; i < ARRAY_SIZE(t->mux_snap); i++) + t->mux_snap[i] = readl(s->clk_mux + T8103_MUX_SOC + i * 4); + /* E4: the CPU complexes' and voltage monitors' quiesce */ + t8103_quiesce(s); + /* E5: CPM power gating on */ + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + writel(readl(s->ps + t8103_cpm[i]) | T8103_CPM_GATING, s->ps + t8103_cpm[i]); + /* E6, E7: E cluster to 0 first, then P cluster to 0 */ + writel(readl(s->ps + T8103_CLUSTER_E) & ~PS_TARGET, s->ps + T8103_CLUSTER_E); + writel(readl(s->ps + T8103_CLUSTER_P) & ~PS_TARGET, s->ps + T8103_CLUSTER_P); + if (readl_poll_timeout_atomic(s->ps + T8103_CLUSTER_P, v, !(v & T8103_CLUSTER_BUSY), 1, + CLUSTER_TIMEOUT_US)) + t->cluster_timeouts++; + /* E8: AUTO_ENABLE off on the always-on words */ + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + writel(readl(s->ps + t8103_auto_off[i]) & ~PS_AUTO_ENABLE, + s->ps + t8103_auto_off[i]); + /* + * E9: the S2R engine doesn't wait for SEP's power gate unless SEP was asked to sleep and + * gated, as the reference waits for before its last SMC step: an engine left waiting for + * a gate that never comes would stall with the watchdog standing still. + */ + t->sep_ps_gated = -ENODATA; + if (apple_sleep_enclave.stop) { + t->sep_ps_gated = readl_poll_timeout_atomic(s->ps + T8103_SEP_PS, v, + !FIELD_GET(PS_ACTUAL, v), 10, + T8103_SEP_GATE_US); + t->sep_ps = v; + } + if (!apple_sleep_enclave.stop || t->sep_ps_gated) { + writel(readl(s->ps + T8103_SEP_PG) & ~T8103_SEP_PG_WAIT, s->ps + T8103_SEP_PG); + t->sep_pg_cleared = true; + } + dsb(sy); + /* E11: the watchdog from here to the wake */ + apple_sleep_set_wd2(s, T8103_WDT_COMMIT_SECS); + /* + * E12: the PMU RTC alarm's SPMI vector acknowledged, then on, so an alarm its RTC driver + * set reaches the wake logic as source 54. + */ + writel(T8103_SPMI_VEC_RTC, s->spmi + T8103_SPMI_VEC_ACK); + writel(readl(s->spmi + T8103_SPMI_VEC_ENABLE) | T8103_SPMI_VEC_RTC, + s->spmi + T8103_SPMI_VEC_ENABLE); + /* E13: the PMU told the AP sleeps */ + t8103_pmu_write(s, T8103_PMU_BOOT_STAGE, T8103_PMU_STAGE_SLEEP); + /* E14: every interrupt line masked, then one already raised taken */ + t8103_aic_mask_all(); + aic_sleep_ack(); + t8103_aic_ipi_quiesce(s); + dsb(sy); +} + +/* After the timer and the AIC's mask, the timer once more, as macOS writes it again then */ +static void t8103_post_timer(struct apple_sleep *s) +{ + dsb(sy); + writel(1, s->commit); +} + +/* W3 to W7, on the boot core with the AIC restored, before any driver resumes */ +static void t8103_sleep_wake(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + unsigned int i; + u32 v; + + t8103_aic_ipi_restore(s); + t8103_slc_on(s); + t8103_dcs_restore(s); + if (t->dcs_perf_down && t->dcs_perf) { + /* The wake left it at T8103_DCS_WAKE, or the sleep never happened. */ + t->dcs_perf_wake_val = readl(t->dcs_perf); + t->dcs_perf_up_ok = t8103_dcs_step_to(t->dcs_perf, t->dcs_perf_saved & 0xf, + &t->dcs_perf_up_val); + t->dcs_perf_down = false; + } + + /* W3: the clusters back, E first */ + for (i = 0; i < ARRAY_SIZE(t8103_cluster); i++) { + void __iomem *reg = s->ps + t8103_cluster[i]; + + writel((readl(reg) & ~PS_TARGET) | CLUSTER_ON, reg); + t->cluster_wake_ret[i] = readl_poll_timeout_atomic(reg, v, + !(v & T8103_CLUSTER_BUSY), 1, + CLUSTER_TIMEOUT_US); + } + s->cluster_e_ret = t->cluster_wake_ret[0]; + s->cluster_p_ret = t->cluster_wake_ret[1]; + + /* W4: AUTO_ENABLE back where it was */ + for (i = 0; i < ARRAY_SIZE(t8103_auto_off); i++) + if (t->auto_word[i] & PS_AUTO_ENABLE) + writel(readl(s->ps + t8103_auto_off[i]) | PS_AUTO_ENABLE, + s->ps + t8103_auto_off[i]); + /* W5: CPM gating as it was */ + for (i = 0; i < ARRAY_SIZE(t8103_cpm); i++) + writel(t->cpm[i], s->ps + t8103_cpm[i]); + /* + * W6: the clock muxes as they were. The sleep's own sequence leaves some muxes the + * commit had enabled parked or off (storage's among them): every one that differs from + * the commit goes back, then the parked ones. + */ + t->mux_fixed = 0; + for (i = 0; i < ARRAY_SIZE(t->mux_snap); i++) { + void __iomem *reg = s->clk_mux + T8103_MUX_SOC + i * 4; + + if (readl(reg) == t->mux_snap[i] || !(t->mux_snap[i] & BIT(31))) + continue; + writel(t->mux_snap[i], reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_wake_timeouts++; + t->mux_fixed |= BIT_ULL(i); + } + for (i = 0; i < ARRAY_SIZE(t8103_mux_park); i++) { + void __iomem *reg = s->clk_mux + t8103_mux_park[i]; + + writel(t->mux[i], reg); + if (readl_poll_timeout_atomic(reg, v, !(v & T8103_MUX_BUSY), 1, + T8103_MUX_TIMEOUT_US)) + t->mux_wake_timeouts++; + } + /* + * A cluster's ACC answers only while the cluster is powered: after a real sleep both + * were off until W3, and an access before that is an external abort. + */ + t8103_unquiesce(s); + /* SEP's power-gate wait, the alarm's vector and the wake mask as they were */ + if (t->sep_pg_cleared) + writel(t->sep_pg, s->ps + T8103_SEP_PG); + if (apple_sleep_enclave.stop) { + v = readl(s->ps + T8103_SEP_PS); + writel((v & ~0x0f000700U) | (0xfU << 24) | BIT(9), s->ps + T8103_SEP_PS); + } + writel(t->spmi_vec, s->spmi + T8103_SPMI_VEC_ENABLE); + + /* The clock-gated domains the commit lowered */ + for (i = 0; i < ARRAY_SIZE(t8103_cg_commit_off); i++) { + if (t->cg_commit_off & BIT(i)) + sleep_ps_restore(s->ps + t8103_cg_commit_off[i], t->cg_saved[i]); + } + /* + * The apcie and gpio domains the commit found off or couldn't lower, parents first; the + * PMGR driver brings back the ones it lowered. + */ + for (i = ARRAY_SIZE(t8103_commit_off); i > T8103_COMMIT_OFF_APCIE_START; i--) { + unsigned int idx = i - 1; + + if (t->commit_off & BIT(idx)) + sleep_ps_restore(s->ps + t8103_commit_off[idx], 0xf); + } + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_PMP)) + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_PMP], + t->commit_saved[T8103_COMMIT_OFF_PMP]); + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_RMX)) + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_RMX], + t->commit_saved[T8103_COMMIT_OFF_RMX]); + t->commit_lowered = 0; + for (i = ARRAY_SIZE(t8103_aon_commit_off); i > 0; i--) { + unsigned int idx = i - 1; + + if (t->aon_commit_off & BIT(idx)) + sleep_ps_restore(s->ps_aon + t8103_aon_commit_off[idx], 0xf); + } + /* + * The sleep reset every AP pin with the gpio domain, and the pin controller's driver + * puts back only the ones it configured: all of them back now, before any device + * resumes (storage's link doesn't come up without them). + */ + s->pins_lost = s->pins_saved_valid; + apple_sleep_restore_pins(); + /* W7: what woke the SoC, for the report */ + for (i = 0; i < T8103_WAKE_WORDS; i++) + s->wake_status[i] = readl(s->wake + T8103_WAKE_STATUS + 4 * i); + for (i = 0; i < T8103_WAKE_WORDS; i++) + writel(t->wake_mask[i], s->wake + T8103_WAKE_MASK + 4 * i); + if (t->wake_slp_ddr_changed) { + writel(t->wake_slp_ddr, s->wake + T8103_WAKE_SLP_DDR); + t->wake_slp_ddr_changed = false; + } + + /* Device resume can take a while: the watchdog until .end puts apple_wdt's back. */ + apple_sleep_set_wd2(s, T8103_WDT_RESUME_SECS); +} + +/* At .wake and again at .end: the attempt's results, once */ +static void t8103_sleep_finish(struct apple_sleep *s) +{ + struct t8103_sleep *t = &t8103_sleep; + + if (!t->attempt) + return; + t->attempt = false; + if (!t->committed) + return; + dev_info(s->dev, "T8103: commit: wake status at entry %08x %08x %08x %08x %08x, mux timeouts %u, cluster timeouts %u, SEP wait %s\n", + t->wake_entry[0], t->wake_entry[1], t->wake_entry[2], t->wake_entry[3], + t->wake_entry[4], t->mux_timeouts, t->cluster_timeouts, + t->sep_pg_cleared ? "cleared" : "kept"); + dev_info(s->dev, "T8103: SEP power state %#x at the commit (gate wait %d)\n", t->sep_ps, + t->sep_ps_gated); + dev_dbg(s->dev, "T8103: stopped PMP %#x SIO %#x DCP %#x DCPEXT %#x, memory cache %#x, quiesce timeouts %u, IPIs pending %#x\n", + t->pmp_result, t->sio_result, t->dcp_result, t->dcpext_result, t->slc_result, + t->quiesce_timeouts, t->aic_result); + if (t->dcs_perf && (!t->dcs_perf_down_ok || !t->dcs_perf_up_ok)) + dev_warn(s->dev, "T8103: DRAM perf state %#x, down to %#x (%s), %#x after the wake, back to %#x (%s)\n", + t->dcs_perf_saved, t->dcs_perf_down_val, + t->dcs_perf_down_ok ? "ok" : "stuck", t->dcs_perf_wake_val, + t->dcs_perf_up_val, t->dcs_perf_up_ok ? "ok" : "stuck"); + if (t->mux_fixed) + dev_info(s->dev, "T8103: clock muxes put back after the wake: %#llx\n", + t->mux_fixed); + dev_info(s->dev, "T8103: wake status %08x %08x %08x %08x %08x, clusters %d %d, mux timeouts %u\n", + s->wake_status[0], s->wake_status[1], s->wake_status[2], s->wake_status[3], + s->wake_status[4], t->cluster_wake_ret[0], t->cluster_wake_ret[1], + t->mux_wake_timeouts); +} + +static const struct apple_sleep_wake_name t8103_wake_names[] = { + { 12, "AOP.GPIO.IRQ4" }, { 14, "AOP.GPIO.IRQ6" }, + { 54, "NUB.SPMI0Sw3IRQ" }, + { 76, "SMC.CPUWakeupAP" }, { 81, "SMC.OutboxNotEmpty" }, + { 133, "ATC0.USBWakeup" }, { 134, "ATC1.USBWakeup" }, +}; + +static const struct apple_sleep_ops t8103_sleep_ops = { + .deep_wfi_arm = t8103_deep_wfi_arm, + .resume = t8103_resume_stub, + .aic_mask_all = t8103_aic_mask_all, + .aic_ack = aic_sleep_ack, + .aic_restore = t8103_aic_restore, + .map_regs = t8103_sleep_map_regs, + .begin = t8103_sleep_begin, + .pre_commit = t8103_pre_commit, + .post_timer = t8103_post_timer, + .check = t8103_sleep_check, + .display_off = t8103_sleep_display_off, + .prepare_regs = t8103_sleep_prepare_regs, + .undo_regs = t8103_sleep_undo_regs, + .commit_regs = t8103_sleep_commit_regs, + .wake = t8103_sleep_wake, + .finish = t8103_sleep_finish, + .cpu_prepare = t8103_sleep_cpu_prepare, + .cpu_restore = t8103_sleep_cpu_restore, +}; + +static const struct apple_sleep_soc t8103_sleep_soc = { + .ops = &t8103_sleep_ops, + .early_context = true, + .early_cpu_wfi = true, + .boot_wfi_delay_ms = 3, + /* The wake mask is the AOP's global block, armed and read by the SoC's operations. */ + .own_wake = true, + .wdt_wd1 = true, + .smc_gen1_keys = true, + .boot_mpidr = 0x0, + .cpu_count = 8, + /* MPIDR affinity 2 is the cluster: E 0.0.n, P 1.1.n; start bits 4 * cluster + core */ + .cpu_cluster_affinity = 0, + .cpu_clusters = 2, + .cpu_cores_per_cluster = 4, + .cpu_start_stride = 4, + .cpu_valid = t8103_sleep_cpu_valid, + .cluster_cpu = { T8103_CLUSTER_E, T8103_CLUSTER_P }, + .ncluster_cpu = 2, + .ndisp = 1, + .pmu_usid = T8103_PMU_USID, + .wake_mask = T8103_WAKE_MASK, + .wake_status = T8103_WAKE_STATUS, + .wake_words = T8103_WAKE_WORDS, + .wake_last_word = 0x03ffffff, + .wake_names = t8103_wake_names, + .nwake_names = ARRAY_SIZE(t8103_wake_names), +}; diff --git a/drivers/soc/apple/sleep-test.c b/drivers/soc/apple/sleep-test.c index fff01f6447e5ad..8a0dabaef71647 100644 --- a/drivers/soc/apple/sleep-test.c +++ b/drivers/soc/apple/sleep-test.c @@ -12,8 +12,18 @@ static const char *const apple_sleep_test_profiles[] = { "apple,t8142-sleep", "apple,t6050-sleep", "apple,t6050-j716c-sleep", + "apple,t8103-sleep", }; +/* + * Region-based profiles, and those whose operations drive every word themselves (T8103), + * keep their words in their own tables, not in the shared lists checked here. + */ +static bool apple_sleep_test_own_tables(const struct apple_sleep_soc *soc) +{ + return soc->regions || !soc->ps_all.count; +} + static bool apple_sleep_test_has(const struct apple_sleep_words *all, u32 offset) { return sleep_ps_find(all->offset, all->count, offset) >= 0; @@ -86,8 +96,7 @@ static void apple_sleep_test_words(struct kunit *test) }; int i; - /* Region-based profiles keep their words in their own tables */ - if (soc->regions) + if (apple_sleep_test_own_tables(soc)) continue; apple_sleep_test_full(test, c, "ps_all", all); apple_sleep_test_full(test, c, "ps_aon_all", aon); @@ -201,7 +210,8 @@ static void apple_sleep_test_layout(struct kunit *test) for (id = apple_sleep_of_match; id->compatible[0]; id++) { const struct apple_sleep_soc *soc = id->data; - if (soc->regions) + /* Its memory controller and NI words are its operations' own, too. */ + if (apple_sleep_test_own_tables(soc)) continue; KUNIT_EXPECT_GE(test, soc->ncluster_cpu, 1); KUNIT_EXPECT_LE(test, soc->ncluster_cpu, SLEEP_CPU_CLUSTERS_MAX); diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 9cee856626f918..320b2cecc43d3c 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -137,6 +137,9 @@ struct aura_s2r_mailbox { #define WDT_WD0_COUNT 0x00 #define WDT_WD0_CTL 0x0c #define WDT_WD1_COUNT 0x10 +#define WDT_WD1_BITE 0x14 +#define WDT_WD1_CTL 0x1c +#define WDT_WD1_RESET_EN BIT(2) #define WDT_WD2_COUNT 0x20 #define WDT_WD2_ALARM 0x28 #define WDT_WD2_CTL 0x2c @@ -807,6 +810,13 @@ struct apple_sleep_soc { * the commit (apple_sleep.early_wfi): XNU's order (T8142, J813 ten-core trace). */ bool early_cpu_wfi; + /* + * The sleep's safety net is WD1 (count +0x10, bite +0x14, control +0x1c, reset enable + * bit 2), which apple_wdt also drives: the one it had is put back at .end. + */ + bool wdt_wd1; + /* The SMC gets pmVC and WKTP before slpa (gen 1, as t6000 has them) */ + bool smc_gen1_keys; }; struct apple_sleep { @@ -1080,6 +1090,9 @@ struct apple_sleep { /* The radio's port stop at the commit (sleep_radio_port_stop()), and its first timeout */ int radio_stop_ret; const char *radio_stop_step; + /* With wdt_wd1: WD1's control and bite time at .begin, put back at .end */ + u32 wd1_saved_ctl, wd1_saved_bite; + bool wd1_saved; }; static struct apple_sleep *apple_sleep; @@ -1802,11 +1815,21 @@ MODULE_PARM_DESC(j813_smc_late, bool apple_sleep_smc_defer_notice(void) { - return apple_sleep && READ_ONCE(sleep_j813_smc_late) && - of_machine_is_compatible("apple,j813") && pm_suspend_via_firmware(); + if (!apple_sleep || !pm_suspend_via_firmware()) + return false; + /* Gen 1 (T8103): SEP sleeps before the SMC is told, as on macOS and t6000. */ + if (apple_sleep->soc->smc_gen1_keys) + return true; + return READ_ONCE(sleep_j813_smc_late) && of_machine_is_compatible("apple,j813"); } EXPORT_SYMBOL_GPL(apple_sleep_smc_defer_notice); +bool apple_sleep_smc_gen1_keys(void) +{ + return apple_sleep && apple_sleep->soc->smc_gen1_keys && pm_suspend_via_firmware(); +} +EXPORT_SYMBOL_GPL(apple_sleep_smc_gen1_keys); + int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data) { @@ -3275,7 +3298,8 @@ static int apple_sleep_refuse(struct apple_sleep *s) } /* Only ANS's driver can stop it, and it doesn't come back without a real sleep. */ - if (!idled && (sleep_ps_on(s, d->ans) || sleep_ps_on(s, d->apcie_sys_gp))) { + if (!idled && ((d->ans && sleep_ps_on(s, d->ans)) || + (d->apcie_sys_gp && sleep_ps_on(s, d->apcie_sys_gp)))) { dev_err(s->dev, "refused: ANS or PCIe is on with no driver to stop it\n"); refused = true; } @@ -4481,6 +4505,13 @@ static void apple_sleep_lower_io(struct apple_sleep *s) static void apple_sleep_set_wd2(struct apple_sleep *s, unsigned int secs) { + if (s->soc->wdt_wd1) { + writel(0, s->wdt + WDT_WD1_CTL); + writel(0, s->wdt + WDT_WD1_COUNT); + writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD1_BITE); + writel(WDT_WD1_RESET_EN, s->wdt + WDT_WD1_CTL); + return; + } writel(0, s->wdt + WDT_WD2_CTL); writel(0, s->wdt + WDT_WD2_COUNT); writel(secs * WDT_TICKS_PER_S, s->wdt + WDT_WD2_ALARM); @@ -5968,7 +5999,13 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) step = "coprocessor checks"; ret = apple_sleep_coprocs_check(s); } - if (!ret && !s->soc->ops->commit_notice) { + if (!ret && !s->soc->ops->commit_notice && apple_sleep_smc_defer_notice()) { + /* The notice comes after SEP's stop, where it can't refuse: its lane is held. */ + step = "SMC scope"; + if (!s->smc.dev || !s->smc.late_notice || !s->smc.saved_ops || !s->smc.held) + ret = -EBUSY; + } + if (!ret && !s->soc->ops->commit_notice && !apple_sleep_smc_defer_notice()) { step = "SMC notice"; ret = apple_sleep_smc_late_notice(s); } @@ -6014,6 +6051,11 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) ret = s->soc->ops->commit_notice(s); if (ret) panic("Apple committed SMC notice failed after peer stop: %d", ret); + } else if (apple_sleep_smc_defer_notice()) { + /* Gen 1: the SMC hears last, after SEP and the other coprocessors stopped. */ + ret = apple_sleep_smc_late_notice(s); + if (ret) + panic("Apple SMC sleep notice failed after peer stop: %d", ret); } if (!s->soc->regions) apple_sleep_usb_down(s); @@ -6462,6 +6504,12 @@ static int apple_sleep_begin(suspend_state_t state) apple_sleep->smc_woke_alone = false; sleep_pins_save(apple_sleep); } + /* Before apple_wdt's suspend stops it: what user space had, for .end */ + if (apple_sleep->soc->wdt_wd1 && !apple_sleep->wd1_saved) { + apple_sleep->wd1_saved_ctl = readl(apple_sleep->wdt + WDT_WD1_CTL); + apple_sleep->wd1_saved_bite = readl(apple_sleep->wdt + WDT_WD1_BITE); + apple_sleep->wd1_saved = true; + } apple_sleep_set_wd2(apple_sleep, WDT_SUSPEND_SECS); pm_set_suspend_via_firmware(); sleep_ans_late_open(); @@ -6479,8 +6527,18 @@ static void apple_sleep_end(void) /* Nothing left by now after a wake; the platform wake takes it */ if (pm_suspend_via_firmware() && apple_sleep->soc->ops->pmu_wake) apple_sleep->soc->ops->pmu_wake(apple_sleep); - if (pm_suspend_via_firmware()) + if (pm_suspend_via_firmware() && apple_sleep->soc->wdt_wd1) { + /* After apple_wdt's resume: WD1 as user space had it before the sleep */ + if (apple_sleep->wd1_saved) { + writel(0, apple_sleep->wdt + WDT_WD1_CTL); + writel(0, apple_sleep->wdt + WDT_WD1_COUNT); + writel(apple_sleep->wd1_saved_bite, apple_sleep->wdt + WDT_WD1_BITE); + writel(apple_sleep->wd1_saved_ctl, apple_sleep->wdt + WDT_WD1_CTL); + apple_sleep->wd1_saved = false; + } + } else if (pm_suspend_via_firmware()) { writel(0, apple_sleep->wdt + WDT_WD2_CTL); + } } /* @@ -6778,6 +6836,12 @@ static int apple_sleep_prepare(void) /* Every device .suspend has run: no owner registers after this. */ sleep_ans_late_close(); + /* + * WD1 on its own (T8103): apple_wdt's .suspend stopped it, and nothing else would reset + * a hang between here and the commit, which arms it again. + */ + if (s && s->soc->wdt_wd1 && pm_suspend_via_firmware()) + apple_sleep_set_wd2(s, WDT_SUSPEND_SECS); sleep_note_at(s, 0, PMU_NOTE_MAGIC); sleep_note_at(s, 2, 0); sleep_note_at(s, 3, ++attempts); @@ -6997,6 +7061,11 @@ static int apple_sleep_map_displays(struct apple_sleep *s) return 0; } +static void apple_sleep_iounmap(void *base) +{ + iounmap((void __iomem __force *)base); +} + static void __iomem *apple_sleep_map(struct device *dev, const char *name) { struct device_node *np = dev->of_node; @@ -7010,7 +7079,17 @@ static void __iomem *apple_sleep_map(struct device *dev, const char *name) if (of_address_to_resource(np, index, &res)) return IOMEM_ERR_PTR(-EINVAL); - /* Shared with the drivers of these blocks, so not claimed. */ + /* + * Shared with the drivers of these blocks, so not claimed. Non-posted where the bus says + * so: on T8103 a posted write to these blocks is an SError. + */ + if (res.flags & IORESOURCE_MEM_NONPOSTED) { + base = ioremap_np(res.start, resource_size(&res)); + if (!base || + devm_add_action_or_reset(dev, apple_sleep_iounmap, (void __force *)base)) + return IOMEM_ERR_PTR(-ENOMEM); + return base; + } base = devm_ioremap(dev, res.start, resource_size(&res)); if (!base) return IOMEM_ERR_PTR(-ENOMEM); @@ -7912,13 +7991,14 @@ static int apple_sleep_probe(struct platform_device *pdev) READ_ONCE(sleep_el1_wfi) >= 2 ? "EL1 on every core" : "EL1 on the boot core", &(phys_addr_t){ __pa_symbol(t8142_el1_wfi_stub) }); } - dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", - readl(s->pwrgate + s->soc->pwrgate_wake[0]), - readl(s->pwrgate + s->soc->pwrgate_wake[1]), - readl(s->pwrgate + s->soc->pwrgate_cpm[0]), - readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), - readl(s->cluster + s->soc->cluster_cpu[0]), - readl(s->cluster + s->soc->cluster_cpu[1])); + if (s->pwrgate) + dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", + readl(s->pwrgate + s->soc->pwrgate_wake[0]), + readl(s->pwrgate + s->soc->pwrgate_wake[1]), + readl(s->pwrgate + s->soc->pwrgate_cpm[0]), + readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), + readl(s->cluster + s->soc->cluster_cpu[0]), + readl(s->cluster + s->soc->cluster_cpu[1])); dev_warn(dev, "sleep data derived for this SoC, untested: deep sleep is %s, and %s\n", READ_ONCE(sleep_deep) ? "offered (apple_sleep.deep=1)" : "off (apple_sleep.deep=1 offers it)", READ_ONCE(sleep_untested_commit) ? "the commit is allowed" : @@ -9622,6 +9702,8 @@ static const struct apple_sleep_soc t8142_sleep_soc = { .wake_last_word = GENMASK(11, 0), }; +#include "sleep-t8103.h" + /* * Qualified profiles expose system sleep. Inventory-only profiles match for a * precise refusal and cannot reach hardware preparation or suspend_set_ops(). @@ -9633,6 +9715,7 @@ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8142-sleep", .data = &t8142_sleep_soc }, { .compatible = "apple,t6050-sleep", .data = &t6050_sleep_soc }, { .compatible = "apple,t6050-j716c-sleep", .data = &t6050_j716c_sleep_soc }, + { .compatible = "apple,t8103-sleep", .data = &t8103_sleep_soc }, { } }; diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index db4337d663b818..bcaeffeb6832ab 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -45,6 +45,8 @@ struct apple_sleep_smc_saved_ops { const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void); /* J813 experiment: send the final SMC notice after the peer idle handshakes. */ bool apple_sleep_smc_defer_notice(void); +/* Gen 1 (T8103): the SMC gets WKTP between slpw and slpa */ +bool apple_sleep_smc_gen1_keys(void); int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data); int apple_sleep_smc_register_saved(struct device *dev, @@ -259,6 +261,7 @@ int apple_sleep_engine_reset(struct device *dev); #else static inline const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void) { return NULL; } static inline bool apple_sleep_smc_defer_notice(void) { return false; } +static inline bool apple_sleep_smc_gen1_keys(void) { return false; } static inline int apple_sleep_smc_register(struct device *dev, int (*late_notice)(void *data, u64 *sent, u64 *ack), void *data) { return -EOPNOTSUPP; } static inline int apple_sleep_smc_register_saved(struct device *dev, From 82d65bd7a9a65e27cbdfd26d4993b8ce46f7cc13 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:52:22 -0500 Subject: [PATCH 1101/1514] mfd: macsmc: give the T8103 SMC its sleep notice after the other coprocessors On T8103 the SMC is gen 1: as on t6000, it hears of the sleep last, after SEP and the other coprocessors stopped, so its late notice is sent with interrupts off, over the bounded saved transport J813 already uses. Enable that transport for the T8103 SMC. Gen 1 takes WKTP = 2 between slpw and slpa, and has no pmVC: write it on the saved transport before slpa when the sleep driver says the SoC uses gen 1 keys. Once the AP's power-down is answered, drain what the SMC posted with it, so nothing is left in the mailbox through the sleep. J813's sequence doesn't change. Signed-off-by: Erik Bourget --- drivers/mfd/macsmc.c | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index c8aff8d184c7dd..33bc059ef928cc 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -658,8 +658,12 @@ static int apple_smc_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t6050-smc"); if (smc->saved_enabled && of_machine_is_compatible("apple,j714s")) smc->wake_reasons = apple_smc_j714s_wake_reasons; - /* J813's late notice needs the bounded, IRQ-independent transport too. */ - if (of_machine_is_compatible("apple,j813")) + /* + * J813's late notice needs the bounded, IRQ-independent transport too, as does T8103's: + * its SMC hears last, after SEP and the other coprocessors stopped. + */ + if (of_machine_is_compatible("apple,j813") || + of_device_is_compatible(dev->of_node, "apple,t8103-smc")) smc->saved_enabled = true; smc->sram_base = devm_platform_get_and_ioremap_resource(pdev, 1, &smc->sram); if (IS_ERR(smc->sram_base)) @@ -1528,9 +1532,11 @@ static const struct apple_sleep_smc_saved_ops apple_smc_saved_ops = { }; /* - * J813 retains its existing MBSE/AP sequence and delay floors. The transport - * is the saved lane: no scheduler, jiffies, IRQ worker or SRAM reuse is needed - * after the peer stops. Unrelated notifications are retained until resume. + * J813 and T8103 retain their existing MBSE/AP sequence and delay floors. The + * transport is the saved lane: no scheduler, jiffies, IRQ worker or SRAM reuse + * is needed after the peer stops. Unrelated notifications are retained until + * resume, except on gen 1, whose are drained once the AP's power-down is + * answered. */ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) { @@ -1544,14 +1550,26 @@ static int apple_smc_sleep_after_peers(void *data, u64 *sent, u64 *ack) return -EINVAL; smc->saved_committed = true; + /* Gen 1 (T8103): WKTP between slpw and slpa; this SMC has no pmVC. */ + if (apple_sleep_smc_gen1_keys()) { + u8 wktp = 2; + + ret = apple_smc_saved_write(smc, SMC_KEY(WKTP), &wktp, sizeof(wktp)); + if (ret) + goto out; + } ret = apple_smc_saved_write_u32(smc, SMC_KEY(MBSE), SMC_KEY(slpa)); if (ret) goto out; mdelay(SMC_SLEEP_ARM_MS); smc->ap_notified = true; ret = apple_rtkit_m5_saved_ap_power(smc->rtk, false, sent, ack); - if (!ret) + if (!ret) { + /* Gen 1: what the SMC posted with its answer, out of the mailbox first */ + if (apple_sleep_smc_gen1_keys()) + apple_smc_saved_drain(smc); mdelay(SMC_SLEEP_IDLE_MS); + } out: smc->saved_notice_error = ret; return ret; From 5262e83504ae44f6385d16fca693df9c541319de Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:53:52 -0500 Subject: [PATCH 1102/1514] arm64: dts: apple: t8103: describe the DCP's display power words The DCP's driver lowers and raises DISP0's CPU and front-end power words around a stop of its firmware, for DPMS off and for suspend-to-RAM. On T8103 both are in the PMGR's power state block: describe it as the DCP's display power, with only its "ps" range. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 077fc3949002cd..8879819b04acd7 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -660,6 +660,7 @@ dcp: dcp@231c00000 { compatible = "apple,t8103-dcp", "apple,dcp"; + apple,display-power = <&dcp_power>; mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 0 0x0 0x0 0x0 0xfc000000>; @@ -1113,6 +1114,17 @@ reg = <0x2 0x3b700000 0 0x14000>; }; + /* + * The power words the DCP's driver lowers and raises around a stop of its + * firmware: DISP0's CPU and front end, in the PMGR's power state block. + * No driver binds this. + */ + dcp_power: display-power@23b700000 { + compatible = "apple,t8103-display-power"; + reg = <0x2 0x3b700000 0x0 0x14000>; + reg-names = "ps"; + }; + pmgr_dcp: power-management@23b738000 { reg = <0x2 0x3b738000 0x0 0x1000>, <0x2 0x3bc3c000 0x0 0x1000>; From 1a23bc33cfe9a6a415d49add8f0a472957e43efc Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:54:05 -0500 Subject: [PATCH 1103/1514] arm64: dts: apple: t8103: give the SEP its power domains The enclave's sleep looks up its power domain to wait for its gate, as on t600x. Its domain is locked on, so that changes nothing at runtime. The enclave also stops reading its mailbox for good once the GPIO power state is switched off under it, so hold that one for it too, as T8140 does. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 8879819b04acd7..f46b33166d891c 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1407,6 +1407,11 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + /* + * The enclave stops reading its mailbox for good once + * the GPIO power state is switched off under it. + */ + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; From 281a9aa141e2e752dba0a946c499439883144ba8 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:54:05 -0500 Subject: [PATCH 1104/1514] arm64: dts: apple: t8103: add the sleep controller Describe the T8103 sleep controller: the seven blocks its suspend-to-RAM writes, each shared with its own driver, the wake source it leaves on (54, the PMU RTC's alarm on nub-spmi0), the DCP that must be off before the commit and the AP pin controller, whose pins the sleep puts back. Disabled until a board that sleeps enables it. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index f46b33166d891c..6e420d4c5ffabf 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1125,6 +1125,32 @@ reg-names = "ps"; }; + /* + * Suspend-to-RAM. The blocks the sleep writes, each shared with its own + * driver and not claimed: the main PMGR (CPM gating, the CPU clusters, + * SEP's power-gate wait), the always-on PMGR (the S2R timer), the SoC + * clock generator's muxes, the AOP's wake block (five mask, then five + * status words), the CPU start block, the watchdog and nub-spmi0. + * A board that sleeps enables it. + */ + sleep: sleep-controller@23b700000 { + compatible = "apple,t8103-sleep"; + reg = <0x2 0x3b700000 0x0 0x8c000>, + <0x2 0x3d280000 0x0 0x74000>, + <0x2 0x3b000000 0x0 0x41000>, + <0x2 0x3d004000 0x0 0x30>, + <0x2 0x3b754000 0x0 0x10>, + <0x2 0x3d2b0000 0x0 0x20>, + <0x2 0x3d0d9300 0x0 0x100>; + reg-names = "ps", "ps-aon", "clk-mux", "wake", + "cpu-start", "wdt", "spmi"; + /* NUB.SPMI0Sw3IRQ: the PMU RTC's alarm */ + apple,wake-enable = <54>; + apple,display-coprocessors = <&dcp>; + apple,pinctrl = <&pinctrl_ap>; + status = "disabled"; + }; + pmgr_dcp: power-management@23b738000 { reg = <0x2 0x3b738000 0x0 0x1000>, <0x2 0x3bc3c000 0x0 0x1000>; From 8dfc6220f5fd9aa936802263e81f3f22665d5f05 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:54:44 -0500 Subject: [PATCH 1105/1514] dt-bindings: usb: ti,tps6598x: add apple,sleep-ssps for CD321x The tipd driver tells a CD321x the system's power state (SSPS) around a firmware-driven suspend when its node has apple,sleep-ssps, as it does for the SN201202x. Allow the property on apple,cd321x. Signed-off-by: Erik Bourget --- .../devicetree/bindings/usb/ti,tps6598x.yaml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml index 2c589e9e712ebd..08ecfa211ad651 100644 --- a/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml +++ b/Documentation/devicetree/bindings/usb/ti,tps6598x.yaml @@ -56,6 +56,12 @@ properties: connector: $ref: /schemas/connector/usb-connector.yaml# + apple,sleep-ssps: + type: boolean + description: + Tell the controller the system's power state (SSPS) around a + firmware-driven suspend, S3 before it and S0 after. + firmware-name: description: | Should contain the name of the default patch binary @@ -91,6 +97,15 @@ allOf: properties: reg: maxItems: 1 + - if: + properties: + compatible: + not: + contains: + const: apple,cd321x + then: + properties: + apple,sleep-ssps: false additionalProperties: false From 8cc14f33ff6538f916e2e3d3c81a6fb28e9d6f40 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 12:54:57 -0500 Subject: [PATCH 1106/1514] arm64: dts: apple: t8103-j313: enable suspend-to-RAM Enable the sleep controller on the MacBook Air (M1, 2020), and have both USB-C port controllers told the system's power state around the sleep, S3 before it and S0 after it, as the sleep was brought up with. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103-j313.dts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103-j313.dts b/arch/arm64/boot/dts/apple/t8103-j313.dts index b1125b78a85d0a..671d7cd6e800d9 100644 --- a/arch/arm64/boot/dts/apple/t8103-j313.dts +++ b/arch/arm64/boot/dts/apple/t8103-j313.dts @@ -179,6 +179,19 @@ status = "okay"; }; +&sleep { + status = "okay"; +}; + +/* The port controllers' system power state: S3 before a firmware-driven sleep, S0 after it */ +&hpm0 { + apple,sleep-ssps; +}; + +&hpm1 { + apple,sleep-ssps; +}; + &aop_audio { apple,chassis-name = "J313"; apple,machine-kind = "MacBook Air"; From 008896a365e1c96ce08d231972c73f2d77a51aca Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 13:49:39 -0800 Subject: [PATCH 1107/1514] drm/asahi: let one file hold at most a sixteenth of the timestamp window, so other clients' timestamp binds still fit Every family that aliases timestamp buffers for its firmware does so in one fixed range per device: IOVA_KERN_TIMESTAMP_RANGE on G13/G14, the timestamp arena on G15, TIMESTAMP_RANGE on M3 and the timestamp window on G17 (64 MiB each). Binds from every file share it, and one file could fill it. Every other client's timestamp bind then failed with ENOSPC on G13/G14, G15 and M3, which Mesa reports as out of device memory for a query pool, or fails GL context creation with. Give each file a share of that range: a sixteenth of its size, 4 MiB of a 64 MiB window. Mesa binds one small buffer per GL context, one per timestamped query pool and one debug buffer. A bind takes its range from the file's share before it maps anything and passes the resulting WindowPermit into the backend so FirmwareBuffer holds its WindowShare as its last field from construction; the share is therefore credited back only after the cleanup worker unmaps the IOVA alias (and after unmap on mapping-setup error paths), not on synchronous unbind. Past its share a file's buffer may not be mapped in the window: G17 gives it a host-written buffer, as for a full window, and the families whose firmware writes the stamps refuse the bind with ENOSPC, as for a full window. Every other file keeps its own share. Each backend reports its range's size (timestamp_window_size(), 0 for none) and receives the WindowPermit, so the policy lives in one place, the bind. G14 v27.2, G16, G18 and the M5 backend alias nothing and are unchanged, as is G17 on the M5 firmware graph, which has no window. The share is counted per open file in the file's memacct::Client, next to its committed bytes (bounding one open file, matching memacct's per-file model). Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/file.rs | 63 +++++++++++++++++++++++-- drivers/gpu/drm/asahi/g14_v27_2.rs | 2 +- drivers/gpu/drm/asahi/g15/mod.rs | 10 +++- drivers/gpu/drm/asahi/g16/mod.rs | 1 + drivers/gpu/drm/asahi/g17/mod.rs | 45 +++++++++++++----- drivers/gpu/drm/asahi/g18/drm.rs | 2 +- drivers/gpu/drm/asahi/gpu.rs | 36 ++++++++++---- drivers/gpu/drm/asahi/m3/m3_drm.rs | 10 +++- drivers/gpu/drm/asahi/m5/drm.rs | 2 +- drivers/gpu/drm/asahi/memacct.rs | 34 +++++++++++++ drivers/gpu/drm/asahi/timestamp.rs | 76 +++++++++++++++++++++++++----- 11 files changed, 236 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 82ab12dd63258d..9efe138775dd9a 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -357,6 +357,17 @@ const BOUND_OBJECT_BYTES: u64 = (core::mem::size_of::() + core::mem::size_of::() + crate::timestamp::Buffer::HEAP_BYTES) as u64; +/// The firmware timestamp window is one fixed range per device that every file's firmware-aliased +/// timestamp buffers share. A file may hold at most this fraction of it (4 MiB of a 64 MiB +/// window), so one client cannot fill it for every other: Mesa binds one small buffer per GL +/// context, one per timestamped query pool and one debug buffer. +const TIMESTAMP_WINDOW_SHARE_PER_FILE: u64 = 16; + +/// A file's limit on window bytes for a window of `window_size` bytes (0: no window). +fn window_limit(window_size: u64) -> u64 { + window_size / TIMESTAMP_WINDOW_SHARE_PER_FILE +} + /// Charges one bind to `client`, or fails with `ENOMEM` and charges nothing. fn admit_bind( ledger: &'static memacct::Ledger, @@ -1614,11 +1625,26 @@ impl File { .lock() .reserve_limit(1..=u32::MAX, GFP_KERNEL_ACCOUNT)?; let handle: u32 = resv.index().try_into()?; + // Take the bound range from the file's share of the firmware timestamp window before + // mapping. Past its share the buffer may not go in the window: the backend maps it + // without one if it can, or fails with ENOSPC as for a full window. A buffer mapped + // without the window gives the share back at once. + let limit = window_limit(reg_data.gpu.timestamp_window_size()); + let window = if limit == 0 { + crate::timestamp::WindowPermit::Unrestricted + } else { + match memacct::Client::take_window(&file.inner().mem, data.range, limit) { + Some(share) => crate::timestamp::WindowPermit::Share(share), + None => crate::timestamp::WindowPermit::Denied, + } + }; + let buffer = reg_data.gpu.map_timestamp_buffer( + bo, + offset..end_offset, + window, + )?; let mapping = Arc::new( - crate::timestamp::Bound::new( - reg_data.gpu.map_timestamp_buffer(bo, offset..end_offset)?, - charge, - ), + crate::timestamp::Bound::new(buffer, charge), GFP_KERNEL_ACCOUNT, )?; let obj = KBox::new(Object::TimestampBuffer(mapping), GFP_KERNEL_ACCOUNT)?; @@ -2002,4 +2028,33 @@ mod bound_object_charge_tests { assert_eq!(client.committed(), 0); Ok(()) } + + #[test] + fn a_file_holds_at_most_its_share_of_the_timestamp_window() -> Result { + const MIB: u64 = 1 << 20; + let limit = window_limit(64 * MIB); + assert_eq!(limit, 4 * MIB); + assert_eq!(window_limit(0), 0); + let a = memacct::Client::new()?; + let b = memacct::Client::new()?; + // One file binds up to its share and no further, whatever the buffer sizes. + let first = memacct::Client::take_window(&a, 3 * MIB, limit); + assert!(first.is_some()); + assert!(memacct::Client::take_window(&a, 2 * MIB, limit).is_none()); + let second = memacct::Client::take_window(&a, MIB, limit); + assert!(second.is_some()); + assert_eq!(a.timestamp_window(), 4 * MIB); + assert!(memacct::Client::take_window(&a, 16 * 1024, limit).is_none()); + // Another file has its own share. + let other = memacct::Client::take_window(&b, 4 * MIB, limit); + assert!(other.is_some()); + // An unbind gives the share back; a limit of 0 (no window) takes nothing. + drop(first); + assert_eq!(a.timestamp_window(), MIB); + assert!(memacct::Client::take_window(&a, MIB, 0).is_none()); + drop((second, other)); + assert_eq!(a.timestamp_window(), 0); + assert_eq!(b.timestamp_window(), 0); + Ok(()) + } } diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index e9edc12813ab43..f611357e2d1f39 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1210,7 +1210,7 @@ impl gpu::Gpu for Backend { Ok(KBox::new(crate::m3::m3_submit::Queue::new_g14_v27_2(self.runtime.clone(), self.scheduler.clone(), vm, priority, usc_exec_base, ualloc_priv, self.preempt_bytes, render)?, GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range, _window: crate::timestamp::WindowPermit) -> Result { // Timestamp buffers would need new tables in the firmware window after boot. Err(ENOTSUPP) } diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 4cb221fb0a5df6..ac76ba0f4a7d42 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -680,11 +680,19 @@ impl gpu::Gpu for Gpu { )?) } + fn timestamp_window_size(&self) -> u64 { + hw::va::TIMESTAMPS_SIZE + } + fn map_timestamp_buffer( &self, bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { - crate::timestamp::Buffer::firmware(timestamp::map(self, bo, range)?) + if !window.is_allowed() { + return Err(ENOSPC); + } + crate::timestamp::Buffer::firmware(timestamp::map(self, bo, range)?, window.into_share()) } } diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index f161b218a0d06b..96706a302ab6eb 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -653,6 +653,7 @@ impl gpu::Gpu for Gpu { &self, bo: gem::ObjectRef, range: Range, + _window: crate::timestamp::WindowPermit, ) -> Result { timestamp::map(self, bo, range) } diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 1a4d6762540d81..2da5b2f997630f 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -854,6 +854,11 @@ impl Drop for Firmware { } impl Firmware { + /// The firmware's fixed timestamp window, on the older firmware graph; `None` on M5's graph. + fn timestamp_window(&self) -> Option> { + (!self.uat.is_m5()).then_some(hw::t8140::dynamic::TIMESTAMP_WINDOW) + } + /// The firmware instances this GPU runs. fn roles(&self) -> &'static [Role] { if self.secondary.is_some() { @@ -2718,32 +2723,46 @@ impl gpu::Gpu for Gpu { Ok(KBox::new(frontend, GFP_KERNEL)?) } + fn timestamp_window_size(&self) -> u64 { + let state = self.shared.state.lock(); + (*state) + .as_ref() + .and_then(|firmware| firmware.timestamp_window()) + .map_or(0, |window| window.end - window.start) + } + fn map_timestamp_buffer( &self, mut bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { let windowed = { let state = self.shared.state.lock(); let firmware = (*state).as_ref().ok_or(ENODEV)?; - // The timestamp window is part of the older firmware graph, not M5's graph. - if firmware.uat.is_m5() { - None + // A file whose share of the window is used up gets a host-written buffer, as when + // the window is full. + if window.is_allowed() { + firmware.timestamp_window().and_then(|window| { + bo.map_range_into_range( + firmware.uat.kernel_vm(), + range.clone(), + window, + mmu::UAT_PGSZ as u64, + mmu::PROT_FW_SHARED_RW, + false, + ) + .ok() + }) } else { - bo.map_range_into_range( - firmware.uat.kernel_vm(), - range.clone(), - hw::t8140::dynamic::TIMESTAMP_WINDOW, - mmu::UAT_PGSZ as u64, - mmu::PROT_FW_SHARED_RW, - false, - ) - .ok() + None } }; // The buffer's CPU mapping takes the reservation lock: not under the device mutex. match windowed { - Some(mapping) => crate::timestamp::Buffer::firmware_window(mapping), + Some(mapping) => { + crate::timestamp::Buffer::firmware_window(mapping, window.into_share()) + } // Outside the window the host writes every stamp, and the firmware never sees the // buffer: give it no firmware alias, which would take kernel address space shared // with every firmware object (queues, rings, pools) for as long as it is bound. diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index 14a726b24fc4cc..4fa379c7e6c800 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -249,7 +249,7 @@ impl gpu::Gpu for G18DrmGpu { /// at screen creation and enables timer queries only if this works. G18 /// publishes timestamps from the CPU after retirement, so the buffer needs /// no firmware mapping. - fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range) + fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range, _window: crate::timestamp::WindowPermit) -> Result { if self.is_crashed() { return Err(ENODEV); } if range.is_empty() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 9fed9e62ec3835..7ed5a469b00ba8 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -523,12 +523,19 @@ pub(crate) trait Gpu: Send + Sync { usc_exec_base: u64, usage: Arc, ) -> Result>; - /// Bind a BO range as a firmware- or CPU-written timestamp buffer. + /// Bind a BO range as a firmware- or CPU-written timestamp buffer. With `WindowPermit::Denied` + /// the buffer must not be mapped in the firmware timestamp window (the file's share of it is + /// used up): a backend that can only alias it there fails with ENOSPC, as for a full window. fn map_timestamp_buffer( &self, bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result; + /// Size of the fixed firmware range timestamp buffers are aliased in (0: none). + fn timestamp_window_size(&self) -> u64 { + 0 + } } /// Trait used to abstract the firmware/GPU-dependent variants of the GpuManager. @@ -1779,19 +1786,30 @@ impl Gpu for GpuManager::ver { )?) } + fn timestamp_window_size(&self) -> u64 { + IOVA_KERN_TIMESTAMP_RANGE.end - IOVA_KERN_TIMESTAMP_RANGE.start + } + fn map_timestamp_buffer( &self, mut bo: gem::ObjectRef, range: Range, + window: crate::timestamp::WindowPermit, ) -> Result { - crate::timestamp::Buffer::firmware(bo.map_range_into_range( - self.uat.kernel_vm(), - range, - IOVA_KERN_TIMESTAMP_RANGE, - mmu::UAT_PGSZ as u64, - mmu::PROT_FW_SHARED_RW, - false, - )?) + if !window.is_allowed() { + return Err(ENOSPC); + } + crate::timestamp::Buffer::firmware( + bo.map_range_into_range( + self.uat.kernel_vm(), + range, + IOVA_KERN_TIMESTAMP_RANGE, + mmu::UAT_PGSZ as u64, + mmu::PROT_FW_SHARED_RW, + false, + )?, + window.into_share(), + ) } } diff --git a/drivers/gpu/drm/asahi/m3/m3_drm.rs b/drivers/gpu/drm/asahi/m3/m3_drm.rs index b11b612184ed9d..5ce0571dfe8578 100644 --- a/drivers/gpu/drm/asahi/m3/m3_drm.rs +++ b/drivers/gpu/drm/asahi/m3/m3_drm.rs @@ -268,8 +268,14 @@ impl gpu::Gpu for Backend { self.feature_flags() & uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_DEPENDENCY as u64 != 0, self.feature_flags() & uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_WIDE_VISIBILITY as u64 != 0)?,GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range) -> Result { + fn timestamp_window_size(&self) -> u64 { + crate::m3::agx_memory::TIMESTAMP_RANGE.end - crate::m3::agx_memory::TIMESTAMP_RANGE.start + } + + fn map_timestamp_buffer(&self, bo: gem::ObjectRef, range: Range, window: crate::timestamp::WindowPermit) -> Result { + if !window.is_allowed() { return Err(ENOSPC); } crate::timestamp::Buffer::firmware( - Option::as_mut(&mut *self.shared.lock()).ok_or(ENODEV)?.map_timestamp(bo,range)?) + Option::as_mut(&mut *self.shared.lock()).ok_or(ENODEV)?.map_timestamp(bo,range)?, + window.into_share()) } } diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs index 6ab2108d8813b2..97e1ba90002d46 100644 --- a/drivers/gpu/drm/asahi/m5/drm.rs +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -181,7 +181,7 @@ impl gpu::Gpu for M5DrmGpu { }; Ok(KBox::new(queue, GFP_KERNEL)?) } - fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range, _window: crate::timestamp::WindowPermit) -> Result { Err(ENOTSUPP) } } diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index fb2a796604e12c..0c098a3a6fd6f5 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -238,6 +238,8 @@ pub(crate) struct Client { committed: AtomicU64, /// Size of those whose backing the GPU currently holds. resident: AtomicU64, + /// Bytes of the device's firmware timestamp window this client's bound buffers hold. + timestamp_window: AtomicU64, } impl Client { @@ -246,6 +248,7 @@ impl Client { Self { committed: AtomicU64::new(0), resident: AtomicU64::new(0), + timestamp_window: AtomicU64::new(0), }, GFP_KERNEL, )?) @@ -258,6 +261,37 @@ impl Client { pub(crate) fn resident(&self) -> u64 { self.resident.load(Ordering::Relaxed) } + + /// Bytes of the firmware timestamp window this client holds. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn timestamp_window(&self) -> u64 { + self.timestamp_window.load(Ordering::Relaxed) + } + + /// Takes `bytes` of the firmware timestamp window for `client` if its share stays within + /// `limit` (which must not be 0); the returned [`WindowShare`] gives them back when dropped. + /// Concurrent callers cannot overshoot. + pub(crate) fn take_window(client: &Arc, bytes: u64, limit: u64) -> Option { + if limit == 0 || !try_add_within(&client.timestamp_window, bytes, limit, 0) { + return None; + } + Some(WindowShare { + client: client.clone(), + bytes, + }) + } +} + +/// Bytes of the firmware timestamp window held by one bound buffer of a client. +pub(crate) struct WindowShare { + client: Arc, + bytes: u64, +} + +impl Drop for WindowShare { + fn drop(&mut self) { + sub(&self.client.timestamp_window, self.bytes); + } } /// Bytes of a user object reserved against the limits. diff --git a/drivers/gpu/drm/asahi/timestamp.rs b/drivers/gpu/drm/asahi/timestamp.rs index 582162be46add9..47386f8c3f60fc 100644 --- a/drivers/gpu/drm/asahi/timestamp.rs +++ b/drivers/gpu/drm/asahi/timestamp.rs @@ -31,6 +31,29 @@ fn host_offset(start: usize, size: usize, offset: usize) -> Result { start.checked_add(offset).ok_or(EOVERFLOW) } +/// Permission for a timestamp bind to alias in the backend's firmware timestamp window. +pub(crate) enum WindowPermit { + /// No per-file window share applies (the backend has no fixed window limit). + Unrestricted, + /// The file's reserved share of the firmware timestamp window, held until unmap. + Share(crate::memacct::WindowShare), + /// The file's window share is exhausted; fall back to host or refuse with ENOSPC. + Denied, +} + +impl WindowPermit { + pub(crate) fn is_allowed(&self) -> bool { + !matches!(self, Self::Denied) + } + + pub(crate) fn into_share(self) -> Option { + match self { + Self::Share(share) => Some(share), + Self::Unrestricted | Self::Denied => None, + } + } +} + /// A firmware-mapped timestamp buffer with a kernel CPU mapping of its backing, kept for the /// buffer's lifetime so that commands need no mapping of their own. pub(crate) struct FirmwareBuffer { @@ -38,6 +61,9 @@ pub(crate) struct FirmwareBuffer { cpu: mmu::TimestampVmap, /// Mapped in the firmware's timestamp window: the firmware may write stamps itself. window: bool, + /// The file's share of the firmware timestamp window, held as the last field so `mapping` + /// is unmapped on the cleanup queue before the quota is credited back. + _window_share: Option, } /// A timestamp buffer only the host writes, through a kernel CPU mapping of its backing. It has @@ -75,7 +101,10 @@ pub(crate) struct Bound { impl Bound { pub(crate) fn new(buffer: Buffer, charge: crate::memacct::Commit) -> Self { - Self { buffer, _charge: charge } + Self { + buffer, + _charge: charge, + } } } @@ -102,13 +131,19 @@ impl Buffer { crate::cleanup::Deferred::::HEAP_BYTES, ); - pub(crate) fn firmware(mapping: mmu::KernelMapping) -> Result { - Self::new_firmware(mapping, false) + pub(crate) fn firmware( + mapping: mmu::KernelMapping, + window_share: Option, + ) -> Result { + Self::new_firmware(mapping, false, window_share) } /// A buffer aliased in the firmware's timestamp window. - pub(crate) fn firmware_window(mapping: mmu::KernelMapping) -> Result { - Self::new_firmware(mapping, true) + pub(crate) fn firmware_window( + mapping: mmu::KernelMapping, + window_share: Option, + ) -> Result { + Self::new_firmware(mapping, true, window_share) } /// A buffer whose stamps the host writes: the bound range of a firmware-shareable object, @@ -127,13 +162,28 @@ impl Buffer { })?)) } - fn new_firmware(mapping: mmu::KernelMapping, window: bool) -> Result { - let cpu = mapping.timestamp_vmap()?; - Ok(Self::Firmware(crate::cleanup::Deferred::new(FirmwareBuffer { - mapping, - cpu, - window, - })?)) + fn new_firmware( + mapping: mmu::KernelMapping, + window: bool, + window_share: Option, + ) -> Result { + // Keep `window_share` behind `mapping` on error paths too: `mapping` must unmap + // before the window share is credited back. + let cpu = match mapping.timestamp_vmap() { + Ok(cpu) => cpu, + Err(err) => { + drop(mapping); + return Err(err); + } + }; + Ok(Self::Firmware(crate::cleanup::Deferred::new( + FirmwareBuffer { + mapping, + cpu, + window, + _window_share: window_share, + }, + )?)) } /// The window address of the timestamp at `offset`, for a window buffer and an aligned @@ -217,7 +267,7 @@ impl Buffer { /// Firmware-aliased command encoders publish firmware pointers and must never accept a /// host- or CPU-only buffer. Returning a borrow keeps the mapping tied to [`Bound`] so no - /// command can retain the mapping without also keeping its bind charge alive. + /// command can retain the mapping without also keeping its bind charge and window share alive. pub(crate) fn firmware_mapping(&self) -> Result<&mmu::KernelMapping> { match self { Self::Firmware(buffer) => Ok(&buffer.mapping), From dd14bf50e5125b50449609d595b670e7d3c644d5 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 24 Nov 2026 19:53:27 +0100 Subject: [PATCH 1108/1514] cpufreq: apple-soc: hold T8152 at state 3 until its thermal policy owns it The previous commit lifted the T8152 ceiling when a cooling map in the DT named a cluster's CPU. That is static text: it holds whether or not the thermal zones registered, their trips are passive, the cpufreq cooling devices exist (CONFIG_CPU_THERMAL) and the thermal core bound them, so a kernel or boot in which none of that happened still ran the higher states unprotected. Use the runtime hand-off T8132 uses instead. With needs_thermal_owner, each T8152 cluster starts under a FREQ_QOS_MAX request at state 3, and the board thermal policy releases it through apple_soc_cpufreq_set_thermal_owner() once its protection is bound, and restores it before that protection goes away. T8152 has no PMP fast die-temperature loop, so needs_thermal_policy's fallback limit (a third of the top state) goes as well: the state 3 cap is the fail-closed state. The DT-presence check (zone_cooling_qualifies, apple_soc_cpufreq_zone_cooled()) is removed. Signed-off-by: Thomas Glanzmann --- drivers/cpufreq/apple-soc-cpufreq.c | 73 ++++------------------------- 1 file changed, 9 insertions(+), 64 deletions(-) diff --git a/drivers/cpufreq/apple-soc-cpufreq.c b/drivers/cpufreq/apple-soc-cpufreq.c index 4ea968ae087e34..b605b4d116fead 100644 --- a/drivers/cpufreq/apple-soc-cpufreq.c +++ b/drivers/cpufreq/apple-soc-cpufreq.c @@ -211,12 +211,6 @@ struct apple_soc_cpufreq_info { u32 transition_timeout_us; /* Highest P-state allowed without a thermal policy; 0 if not capped. */ u32 max_unmanaged_pstate; - /* - * A board DT whose thermal zones list the cluster's CPU as a cooling - * device is that thermal policy: it lifts max_unmanaged_pstate and - * stands in for needs_thermal_policy's fast die-temperature limit. - */ - bool zone_cooling_qualifies; u64 min_pstate; u64 max_pstate; u64 cur_pstate_mask; @@ -234,8 +228,6 @@ struct apple_cpu_priv { unsigned int expected_pstate; struct freq_qos_request unmanaged_cap; bool thermal_owned; - /* zone_cooling_qualifies, and the DT's thermal zones cool the cluster */ - bool zone_cooled; /* * Lazy verification, see apple_soc_cpufreq_lazy_request(): the lock * serialises the command register, expected_pstate and @@ -323,16 +315,18 @@ static const struct apple_soc_cpufreq_info soc_t8142_info = { }; /* - * T8152 ACC uses state 2 as the first OPP and shares P/M requests. Above - * state 3 it needs a board thermal policy: thermal zones in the DT that - * throttle the cluster's CPUs (the J873g's SMC zones). + * T8152 ACC uses state 2 as the first OPP and shares P/M requests. It has no + * PMP fast die-temperature loop, so states above 3 are held back until the + * board's thermal policy takes ownership, see + * apple_soc_cpufreq_set_thermal_owner(): the SMC thermal zones once they + * throttle the cluster (macsmc-hwmon). This bootstrap ceiling is a Linux + * restriction, not a firmware thermal or safety limit. */ static const struct apple_soc_cpufreq_info soc_t8152_info = { .verify_transition = true, - .needs_thermal_policy = true, + .needs_thermal_owner = true, .transition_timeout_us = 2000, .max_unmanaged_pstate = 3, - .zone_cooling_qualifies = true, .min_pstate = 2, .max_pstate = 31, .ps1_mask = APPLE_DVFS_CMD_PS1, @@ -1193,8 +1187,7 @@ static int apple_fast_die_init(struct cpufreq_policy *policy, parsed = of_parse_phandle_with_fixed_args(cluster, "apple,fast-die-effort", 1, 0, &args); /* Required thermal admission must fail closed with an older DT. */ - if (parsed == -ENOENT && - (!priv->info->needs_thermal_policy || priv->zone_cooled)) + if (parsed == -ENOENT && !priv->info->needs_thermal_policy) return 0; while (policy->freq_table[n].frequency != CPUFREQ_TABLE_END) @@ -1401,50 +1394,6 @@ int apple_soc_cpufreq_set_thermal_owner(struct cpufreq_policy *policy, bool owne } EXPORT_SYMBOL_GPL(apple_soc_cpufreq_set_thermal_owner); -/* Whether a cooling map of a thermal zone in zones lists cpu as a device */ -static bool apple_soc_cpufreq_cpu_cooled(struct device_node *zones, - struct device_node *cpu) -{ - for_each_available_child_of_node_scoped(zones, zone) { - struct device_node *maps __free(device_node) = - of_get_child_by_name(zone, "cooling-maps"); - - if (!maps) - continue; - for_each_child_of_node_scoped(maps, map) { - struct of_phandle_args args; - int i; - - for (i = 0;; i++) { - if (of_parse_phandle_with_args(map, "cooling-device", - "#cooling-cells", i, - &args)) - break; - of_node_put(args.np); - if (args.np == cpu) - return true; - } - } - } - return false; -} - -/* - * Whether the DT's thermal zones throttle the cluster: the board thermal - * policy that zone_cooling_qualifies accepts. The cluster's cpufreq cooling - * device is registered for the node of policy->cpu, so that is the node a - * cooling map has to name. A tree without one keeps the SoC's ceiling. - */ -static bool apple_soc_cpufreq_zone_cooled(struct cpufreq_policy *policy) -{ - struct device_node *zones __free(device_node) = - of_find_node_by_path("/thermal-zones"); - struct device_node *np __free(device_node) = - of_cpu_device_node_get(policy->cpu); - - return zones && np && apple_soc_cpufreq_cpu_cooled(zones, np); -} - static int apple_soc_cpufreq_init(struct cpufreq_policy *policy) { struct cpufreq_frequency_table *p; @@ -1545,12 +1494,8 @@ static int apple_soc_cpufreq_init(struct cpufreq_policy *policy) priv->expected_pstate = state; } - priv->zone_cooled = info->zone_cooling_qualifies && - apple_soc_cpufreq_zone_cooled(policy); - /* SoCs without a qualified thermal policy keep their bootstrap ceiling. */ - if (info->max_unmanaged_pstate && !info->needs_thermal_owner && - !priv->zone_cooled) { + if (info->max_unmanaged_pstate && !info->needs_thermal_owner) { cpufreq_for_each_valid_entry(p, freq_table) { if (p->driver_data <= info->max_unmanaged_pstate) continue; From 1ac43a73b7e666d02d768b6b1592809b47a4453f Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 24 Nov 2026 19:54:38 +0100 Subject: [PATCH 1109/1514] hwmon: macsmc: hand a CPU cluster's higher states to the zones that cool it On T8152 the cpufreq driver holds each cluster at state 3 until a board thermal policy takes it over. On the J873g that policy is the SMC's thermal zones: DT zones fed by this device's temperature sensors, whose passive trips throttle the clusters' cpufreq cooling devices. Once the hwmon device has registered its zones, check every cooling map of those zones that names a CPU: the zone has to be registered, the map's trip has to be passive, and the thermal core has to have bound that trip to the cooling device of the CPU's cluster (thermal_trip_is_bound_to_cdev(), as apple-pmp-thermal checks its own zone). A cluster is handed over through apple_soc_cpufreq_set_thermal_owner() only when all of its maps pass; one that does not keeps the cluster at its ceiling, with a warning. A cluster whose cpufreq policy or cooling device does not exist yet is checked again every second, for up to two minutes. Ownership is given back before the hwmon device, and with it the zones, goes away. A kernel without CONFIG_THERMAL_OF, CONFIG_CPU_THERMAL or the Apple SoC cpufreq driver builds none of this and so never lifts the ceiling. On a SoC whose cpufreq driver does not hold its clusters back, the hand-off returns -ENODEV and nothing changes; no other Apple DT has zones that cool CPUs. Signed-off-by: Thomas Glanzmann --- drivers/hwmon/Kconfig | 1 + drivers/hwmon/macsmc-hwmon.c | 200 +++++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+) diff --git a/drivers/hwmon/Kconfig b/drivers/hwmon/Kconfig index 7a2924b47839ce..7c8d62987f1d36 100644 --- a/drivers/hwmon/Kconfig +++ b/drivers/hwmon/Kconfig @@ -1261,6 +1261,7 @@ config SENSORS_LTQ_CPUTEMP config SENSORS_MACSMC_HWMON tristate "Apple SMC (Apple Silicon)" depends on MFD_MACSMC && OF + depends on ARM_APPLE_SOC_CPUFREQ || !ARM_APPLE_SOC_CPUFREQ help This driver enables hwmon support for current, power, temperature, and voltage sensors, as well as fan speed reporting and control diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index 4b2fbf055ce90f..d56709e208e1fa 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -21,6 +21,8 @@ */ #include +#include +#include #include #include #include @@ -33,9 +35,11 @@ #include #include #include +#include #include #include #include +#include #define MAX_LABEL_LENGTH 32 @@ -132,6 +136,11 @@ struct macsmc_hwmon { /* DT-supplied hotspot fan-assistance trip on macsmc_soc_die. */ struct macsmc_hwmon_fan_assist fan_assist; bool fan_assist_valid; + /* CPU clusters (policy->cpu) whose higher states these zones own */ + struct delayed_work cpu_owner_work; + cpumask_t cpu_owned; + cpumask_t cpu_refused; + unsigned int cpu_owner_tries; }; static ssize_t thermal_pressure_level_show(struct device *dev, @@ -1640,6 +1649,193 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) } #endif +#if IS_ENABLED(CONFIG_THERMAL_OF) && IS_ENABLED(CONFIG_CPU_THERMAL) && \ + IS_REACHABLE(CONFIG_ARM_APPLE_SOC_CPUFREQ) +/* + * CPU cluster ownership + * + * A SoC whose cpufreq driver holds each cluster below its higher states until + * a board thermal policy protects it (T8152) gets that policy from this + * device's thermal zones: DT zones fed by these sensors whose cooling maps + * throttle a cluster's cpufreq cooling device. A cluster is handed over only + * when every such map is live: its zone is registered, the map's trip is + * passive, and the thermal core has bound that trip to the cluster's cooling + * device. Any map that is not keeps the cluster at its ceiling. Ownership is + * given back before the zones go away. + */ +#define MACSMC_CPU_OWNER_TRIES 120 + +struct macsmc_hwmon_cpu_map { + struct thermal_zone_device *tz; + struct device_node *trip_np; + struct thermal_cooling_device *cdev; + int ret; +}; + +static int macsmc_hwmon_cpu_map_trip(struct thermal_trip *trip, void *data) +{ + struct macsmc_hwmon_cpu_map *map = data; + + if (trip->priv != map->trip_np) + return 0; + if (trip->type != THERMAL_TRIP_PASSIVE) + map->ret = -EINVAL; + else if (!thermal_trip_is_bound_to_cdev(map->tz, trip, map->cdev)) + map->ret = -ENOLINK; + else + map->ret = 0; + return 1; +} + +/* + * The clusters (by policy->cpu) that the CPU cooling maps of this device's + * zones protect, in @ready, and those with a map that is not live, in + * @refused. -EPROBE_DEFER while a named cluster has no cpufreq policy or + * cooling device yet. + */ +static int macsmc_hwmon_cpu_maps(struct macsmc_hwmon *hwmon, struct cpumask *ready, + struct cpumask *refused) +{ + struct device_node *zones __free(device_node) = + of_find_node_by_path("/thermal-zones"); + int ret = 0; + + cpumask_clear(ready); + cpumask_clear(refused); + if (!zones) + return 0; + + for_each_available_child_of_node_scoped(zones, zone) { + struct device_node *maps __free(device_node) = NULL; + struct thermal_zone_device *tz; + struct of_phandle_args sensor; + + if (of_parse_phandle_with_args(zone, "thermal-sensors", + "#thermal-sensor-cells", 0, &sensor)) + continue; + of_node_put(sensor.np); + if (sensor.np != hwmon->dev->of_node) + continue; + maps = of_get_child_by_name(zone, "cooling-maps"); + if (!maps) + continue; + /* thermal_of registers a zone under its node name. */ + tz = thermal_zone_get_zone_by_name(zone->name); + + for_each_child_of_node_scoped(maps, map) { + struct device_node *trip_np __free(device_node) = + of_parse_phandle(map, "trip", 0); + struct of_phandle_args cooling; + int i; + + for (i = 0; !of_parse_phandle_with_args(map, "cooling-device", + "#cooling-cells", i, &cooling); i++) { + struct macsmc_hwmon_cpu_map check = { .ret = -ENOENT }; + struct cpufreq_policy *policy; + int cpu = of_cpu_node_to_id(cooling.np); + + of_node_put(cooling.np); + if (cpu < 0) + continue; + policy = cpufreq_cpu_get(cpu); + if (!policy || !policy->cdev) { + if (policy) + cpufreq_cpu_put(policy); + ret = -EPROBE_DEFER; + continue; + } + if (!IS_ERR(tz) && trip_np) { + check.tz = tz; + check.trip_np = trip_np; + check.cdev = policy->cdev; + for_each_thermal_trip(tz, macsmc_hwmon_cpu_map_trip, &check); + } + cpumask_set_cpu(policy->cpu, check.ret ? refused : ready); + cpufreq_cpu_put(policy); + } + } + } + cpumask_andnot(ready, ready, refused); + return ret; +} + +static void macsmc_hwmon_cpu_owner_work(struct work_struct *work) +{ + struct macsmc_hwmon *hwmon = container_of(to_delayed_work(work), struct macsmc_hwmon, + cpu_owner_work); + cpumask_t ready, refused; + int cpu, ret, pending; + + pending = macsmc_hwmon_cpu_maps(hwmon, &ready, &refused); + + for_each_cpu(cpu, &refused) { + if (cpumask_test_and_set_cpu(cpu, &hwmon->cpu_refused)) + continue; + dev_warn(hwmon->dev, + "CPU%d cluster keeps its cpufreq ceiling: a cooling map of its thermal zones is not bound\n", + cpu); + } + + for_each_cpu(cpu, &ready) { + struct cpufreq_policy *policy; + + if (cpumask_test_cpu(cpu, &hwmon->cpu_owned)) + continue; + policy = cpufreq_cpu_get(cpu); + if (!policy) + continue; + ret = apple_soc_cpufreq_set_thermal_owner(policy, true); + cpufreq_cpu_put(policy); + /* -ENODEV: this SoC does not hold the cluster back. */ + if (!ret) { + cpumask_set_cpu(cpu, &hwmon->cpu_owned); + dev_info(hwmon->dev, + "CPU%d cluster: higher states handed to its thermal zones\n", cpu); + } else if (ret != -ENODEV) { + dev_warn(hwmon->dev, "CPU%d cluster: ownership refused: %d\n", cpu, ret); + } + } + + if (pending != -EPROBE_DEFER) + return; + if (++hwmon->cpu_owner_tries < MACSMC_CPU_OWNER_TRIES) + schedule_delayed_work(&hwmon->cpu_owner_work, HZ); + else + dev_warn(hwmon->dev, + "CPU clusters without a cpufreq cooling device keep their ceiling\n"); +} + +static void macsmc_hwmon_cpu_release(void *data) +{ + struct macsmc_hwmon *hwmon = data; + int cpu; + + cancel_delayed_work_sync(&hwmon->cpu_owner_work); + for_each_cpu(cpu, &hwmon->cpu_owned) { + struct cpufreq_policy *policy = cpufreq_cpu_get(cpu); + + if (policy) { + apple_soc_cpufreq_set_thermal_owner(policy, false); + cpufreq_cpu_put(policy); + } + } + cpumask_clear(&hwmon->cpu_owned); +} + +/* Called once the zones are registered; released before they are removed. */ +static int macsmc_hwmon_cpu_owner_init(struct macsmc_hwmon *hwmon) +{ + INIT_DELAYED_WORK(&hwmon->cpu_owner_work, macsmc_hwmon_cpu_owner_work); + schedule_delayed_work(&hwmon->cpu_owner_work, 0); + return devm_add_action_or_reset(hwmon->dev, macsmc_hwmon_cpu_release, hwmon); +} +#else +static int macsmc_hwmon_cpu_owner_init(struct macsmc_hwmon *hwmon) +{ + return 0; +} +#endif + /* * debugfs "keys": every key the SMC reports, with its type, size and flags, and the value of the * readable 32-bit float keys whose names start with 'T' (temperatures, in millidegrees Celsius) @@ -1888,6 +2084,10 @@ static int macsmc_hwmon_probe(struct platform_device *pdev) if (ret) return ret; + ret = macsmc_hwmon_cpu_owner_init(hwmon); + if (ret) + return ret; + dev_dbg(hwmon->dev, "Registered SMC hwmon device. Sensors:\n"); dev_dbg(hwmon->dev, "Current: %d, Fans: %d, Power: %d, Temperature: %d, Voltage: %d", From c0b804090cc4dbb1e7ad8505555cf8bf974095ff Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 13:55:47 -0500 Subject: [PATCH 1110/1514] thermal: apple-pmp: derive CPU clusters from topology and cpufreq Logical CPU numbering depends on the boot CPU and device-tree order, so hardcoded CPU bitmasks fail on boards or boot paths whose numbering differs. On J773g 10GbE booted through aura, the P cluster is CPUs 0, 7-9 and the E cluster is CPUs 1-6, while the J773g override expected P on 0, 3-5 and E on 1-2, 6-9, causing apple_pmp_add_cluster() to fail setup with -EINVAL and leave the system without the apple-pmp-die thermal zone. Drop the board-specific J773g check and hardcoded bitmasks. Discover the two CPU clusters directly from the live cpufreq policies, verify they partition every possible CPU with uniform DT capacity-dmips-mhz per cluster and consistent capacity and max-frequency ordering, and assign the P cluster to index 0 (PP0b) and the E cluster to index 1 (PPbb). Fail closed with -EPROBE_DEFER while policies are still coming up or -EINVAL/-ENODEV on any topology mismatch. Signed-off-by: Diljit Singh --- drivers/thermal/apple-pmp-thermal.c | 162 ++++++++++++++++++++++++---- 1 file changed, 139 insertions(+), 23 deletions(-) diff --git a/drivers/thermal/apple-pmp-thermal.c b/drivers/thermal/apple-pmp-thermal.c index ab11231cb86827..d9cb887202eec5 100644 --- a/drivers/thermal/apple-pmp-thermal.c +++ b/drivers/thermal/apple-pmp-thermal.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -727,21 +728,138 @@ static void apple_pmp_thermal_cleanup(void) pmp_thermal.ready = false; } -static int apple_pmp_add_cluster(unsigned int index, unsigned int cpu, - unsigned long members) +static int apple_pmp_policy_info(struct cpufreq_policy *policy, + u32 *capacity, unsigned int *max_freq) { - struct apple_pmp_cluster *c = &pmp_thermal.clusters[index]; unsigned int n; - int ret; + bool have_cap = false; + u32 cap = 0; - c->policy = cpufreq_cpu_get(cpu); - if (!c->policy) + guard(cpufreq_policy_read)(policy); + if (!policy->freq_table) return -EPROBE_DEFER; - guard(cpufreq_policy_read)(c->policy); - for_each_possible_cpu(n) - if (cpumask_test_cpu(n, c->policy->related_cpus) != - (n < BITS_PER_LONG && !!(members & BIT(n)))) + if (cpumask_empty(policy->related_cpus)) + return -EINVAL; + for_each_cpu(n, policy->related_cpus) { + struct device_node *np = of_cpu_device_node_get(n); + u32 cpu_cap; + int ret; + + if (!np) + return -ENODEV; + ret = of_property_read_u32(np, "capacity-dmips-mhz", &cpu_cap); + of_node_put(np); + if (ret || !cpu_cap) + return -EINVAL; + if (!have_cap) { + cap = cpu_cap; + have_cap = true; + } else if (cpu_cap != cap) { return -EINVAL; + } + } + *capacity = cap; + *max_freq = policy->cpuinfo.max_freq; + return 0; +} + +/* + * Logical CPU numbering follows the boot CPU and device-tree order, so + * cluster masks vary across boards and boot paths. Discover the two + * cpufreq policies from the live topology, verify they partition every + * possible CPU with uniform DT capacity per cluster, and order P before E + * so cluster indices match the PP0b (P) and PPbb (E) power rails. + */ +static int apple_pmp_discover_clusters(struct cpufreq_policy *ordered[2]) +{ + struct cpufreq_policy *found[2] = {}; + unsigned int max_freq[2] = {}; + u32 cap[2] = {}; + unsigned int cpu, count = 0, i; + bool cap_gt, freq_gt; + int ret; + + for_each_online_cpu(cpu) { + struct cpufreq_policy *policy; + bool seen = false; + + for (i = 0; i < count; i++) { + guard(cpufreq_policy_read)(found[i]); + if (cpumask_test_cpu(cpu, found[i]->related_cpus)) { + seen = true; + break; + } + } + if (seen) + continue; + + policy = cpufreq_cpu_get(cpu); + if (!policy) { + ret = -EPROBE_DEFER; + goto err; + } + for (i = 0; i < count; i++) { + if (found[i] == policy) { + cpufreq_cpu_put(policy); + seen = true; + break; + } + } + if (seen) + continue; + if (count >= ARRAY_SIZE(found)) { + cpufreq_cpu_put(policy); + ret = -EINVAL; + goto err; + } + ret = apple_pmp_policy_info(policy, &cap[count], &max_freq[count]); + if (ret) { + cpufreq_cpu_put(policy); + goto err; + } + found[count++] = policy; + } + + for_each_possible_cpu(cpu) { + unsigned int matches = 0; + + for (i = 0; i < count; i++) { + guard(cpufreq_policy_read)(found[i]); + if (cpumask_test_cpu(cpu, found[i]->related_cpus)) + matches++; + } + if (matches == 0) { + ret = -EPROBE_DEFER; + goto err; + } + if (matches != 1) { + ret = -EINVAL; + goto err; + } + } + cap_gt = cap[0] > cap[1]; + freq_gt = max_freq[0] > max_freq[1]; + if (count != ARRAY_SIZE(found) || cap[0] == cap[1] || + max_freq[0] == max_freq[1] || cap_gt != freq_gt) { + ret = -EINVAL; + goto err; + } + ordered[0] = cap_gt ? found[0] : found[1]; + ordered[1] = cap_gt ? found[1] : found[0]; + return 0; + +err: + for (i = 0; i < count; i++) + cpufreq_cpu_put(found[i]); + return ret; +} + +static int apple_pmp_add_cluster(unsigned int index) +{ + struct apple_pmp_cluster *c = &pmp_thermal.clusters[index]; + int ret; + + guard(cpufreq_policy_read)(c->policy); if (!c->policy->freq_table) return -EPROBE_DEFER; @@ -760,27 +878,25 @@ static int apple_pmp_add_cluster(unsigned int index, unsigned int cpu, static int apple_pmp_thermal_setup(void) { + struct cpufreq_policy *policies[2]; struct thermal_zone_device *zone; - unsigned long p_members = BIT(0) | GENMASK(9, 7); - unsigned long e_members = GENMASK(6, 1); unsigned int i; int ret; - /* J773g numbers the four P cores 0,3-5 and the six E cores 1-2,6-9. */ - if (of_machine_is_compatible("apple,j773g")) { - p_members = BIT(0) | GENMASK(5, 3); - e_members = GENMASK(2, 1) | GENMASK(9, 6); - } + ret = apple_pmp_discover_clusters(policies); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(pmp_thermal.clusters); i++) + pmp_thermal.clusters[i].policy = policies[i]; apple_pmp_power_init(&pmp_thermal.power); pmp_thermal.power_budget = !apple_pmp_machine_has_fan(); apple_pmp_cooling_init(&pmp_thermal.cooling); pmp_thermal.guard_level = 8; - ret = apple_pmp_add_cluster(0, 0, p_members); - if (ret) - goto fail; - ret = apple_pmp_add_cluster(1, 1, e_members); - if (ret) - goto fail; + for (i = 0; i < ARRAY_SIZE(pmp_thermal.clusters); i++) { + ret = apple_pmp_add_cluster(i); + if (ret) + goto fail; + } zone = thermal_zone_device_register_with_trips("apple-pmp-die", apple_pmp_trips, ARRAY_SIZE(apple_pmp_trips), NULL, &apple_pmp_thermal_ops, &apple_pmp_params, From c64dfbc988e604bea1c1eda1369afa5c6988ea17 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Tue, 24 Nov 2026 19:56:28 +0100 Subject: [PATCH 1111/1514] phy: apple: atc: refuse T8152 USB4 before powering up without tunables With an older loader a T8152 PHY has no SuperSpeed tunables and atcphy_configure() refuses every mode but OFF and USB2. A USB4 request from the Type-C mux still powered the four CIO domains up first, then failed in atcphy_configure() with "CIO mode failed: -95" and powered them down again. Refuse it before the power-up, with a message that says why the port stays USB2. The no-tunables KUnit case now also starts CIO and checks that it is refused and nothing is powered. Signed-off-by: Thomas Glanzmann --- drivers/phy/apple/atc-test.c | 3 +++ drivers/phy/apple/atc.c | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/drivers/phy/apple/atc-test.c b/drivers/phy/apple/atc-test.c index a98279e9a930ba..ff14b925bb04f6 100644 --- a/drivers/phy/apple/atc-test.c +++ b/drivers/phy/apple/atc-test.c @@ -1569,6 +1569,9 @@ static void atcphy_test_t8152_no_tunables(struct kunit *test) guard(mutex)(&atcphy->lock); for (size_t i = 0; i < ARRAY_SIZE(refused); i++) KUNIT_EXPECT_EQ(test, atcphy_configure(atcphy, refused[i]), -EOPNOTSUPP); + /* USB4 from the Type-C mux: refused before the power domains come up */ + KUNIT_EXPECT_EQ(test, atcphy_cio_start(atcphy, APPLE_ATCPHY_MODE_USB4), -EOPNOTSUPP); + KUNIT_EXPECT_FALSE(test, atcphy->cio_powered); KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_T8152_AON_LANE0), ACIOPHY_T8152_AON_LANE_CLAMP_EN); KUNIT_EXPECT_EQ(test, readl(core + ACIOPHY_CROSSBAR_T8103), 0U); diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 92df5f1215a573..9e55427a76c664 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -5630,6 +5630,14 @@ static int atcphy_cio_start(struct apple_atcphy *atcphy, enum atcphy_mode mode) int ret; lockdep_assert_held(&atcphy->lock); + /* + * Without its tunables (an older loader) atcphy_configure() refuses CIO: + * leave the power domains alone instead of cycling them for nothing. + */ + if (atcphy->hw->gen == ATCPHY_GENERATION_T8152 && !atcphy->ss_tunables) { + dev_info(atcphy->dev, "USB4 needs the bootloader's PHY tunables; the port stays USB2\n"); + return -EOPNOTSUPP; + } /* The router's Thunderbolt mode is not qualified on these ports. */ if (mode != APPLE_ATCPHY_MODE_USB4) { dev_info(atcphy->dev, "Thunderbolt alt mode is not supported on this port\n"); From e5c2f094869ec4a61a1b57f2a9255c3e5c1c25c5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 14:00:25 -0500 Subject: [PATCH 1112/1514] drm/asahi: g17: count render-pair demand for a fresh sibling compute QID sibling_source() offers a fresh QID for a sibling compute channel when the QID table has room beside render's reserve. It still sized that reserve by open logical queues, while reserve_compute_channel() now reserves against the admission's render-pair demand (open queues plus non-reclaimable siblings and held pairs), as rebind_compute() does. With siblings held the old check reported a fresh QID that the reservation then refused, so the sibling attempt ended without falling through to an idle other-VM queue. Check the same demand the reservation uses. The sibling host-test harnesses give their mock admission a render_demand() for the extracted sibling_source(). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/runtime.rs | 2 +- tools/asahi/g17-m5-sibling-compute-tests.py | 5 ++++- tools/asahi/g17-m5-sibling-gate-tests.py | 5 ++++- tools/asahi/g17-m5-sibling-rearm-tests.py | 9 ++++++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 81b8156bf89fba..a9d201ae4de28e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -445,7 +445,7 @@ impl Registry { if let Some((_, qid)) = vacant { return Some(SiblingSource::Vacant(qid)); } - if self.qids.compute_fits(self.admission.queues() as usize) { + if self.qids.compute_fits(self.admission.render_demand(0)) { return Some(SiblingSource::Fresh); } // A pool release in flight ends in a vacant queue; give back one at a time. diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 5042a66f7e9170..894d87bffca89b 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -414,7 +414,10 @@ def build_harness(mutation=None): }} struct Admission {{ queues: u32 }} -impl Admission {{ fn queues(&self) -> u32 {{ self.queues }} }} +impl Admission {{ + fn queues(&self) -> u32 {{ self.queues }} + fn render_demand(&self, extra: usize) -> usize {{ self.queues as usize + extra }} +}} struct Teardown {{ releasing_id: Option, render_acked: bool }} impl Teardown {{ diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py index b943c2a6d9c153..3068c820beb54d 100755 --- a/tools/asahi/g17-m5-sibling-gate-tests.py +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -333,7 +333,10 @@ def build(mutation=None): struct Qids { fit: bool } impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } struct Admission; -impl Admission { fn queues(&self) -> u32 { 1 } } +impl Admission { + fn queues(&self) -> u32 { 1 } + fn render_demand(&self, extra: usize) -> usize { 1 + extra } +} struct Teardown; impl Teardown { fn releasing(&self, _: &Arc) -> bool { false } } struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 6fbdd10e119d16..f690f4473cd179 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -131,9 +131,9 @@ def ordered_ok(source, *parts): ' foreign.map(', ' .any(|queue| queue.vacancy_pending() && false)\n {\n' ' return None;\n }\n foreign.map(')], # Give another VM's pool back while a fresh QID fits. - 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.queues() as usize) {\n' + 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.render_demand(0)) {\n' ' return Some(SiblingSource::Fresh);\n }\n // A pool release', - ' if foreign.is_none() && self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' if foreign.is_none() && self.qids.compute_fits(self.admission.render_demand(0)) {\n' ' return Some(SiblingSource::Fresh);\n }\n // A pool release')], # A re-armed sibling is bound as the owner's primary. 'rearm-binds-primary': [('runtime', ' if channel_index == 0 {\n queue.bind_owner(owner, context.clone())', @@ -361,7 +361,10 @@ def build(mutation=None): struct Qids { fit: bool } impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } struct Admission; -impl Admission { fn queues(&self) -> u32 { 4 } } +impl Admission { + fn queues(&self) -> u32 { 4 } + fn render_demand(&self, extra: usize) -> usize { 4 + extra } +} struct Teardown { releasing: Vec } impl Teardown { fn releasing(&self, context: &Arc) -> bool { self.releasing.contains(&context.id) } } struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } From 5de20ebf39e5875d04cbdb890f5651975b8082c5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 14:25:16 -0500 Subject: [PATCH 1113/1514] drm/asahi: m3: define extended recovery layout constants locally PR #2676 moved the G16 recovery offsets per-ABI into FirmwareData and removed the fixed SNAPSHOT, SNAPSHOT_ENTRIES, GENERATION and PHASE constants from g16/recovery/logic.rs. m3_recovery.rs imports that shared logic module via #[path] and used those four 26.6.2 extended baseline constants to compute its shifted RecoveryOffsets, breaking the M3 Rust build and m3-recovery-tests.py with E0425. Define the four 26.6.2 extended baseline constants directly in m3_recovery.rs so M3 no longer depends on G16 layout constants. Fixes: 0c4e19dfdde7 ("Merge pull request #2676 from aurora-silicon/djdev/g16-272") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/m3/m3_recovery.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_recovery.rs b/drivers/gpu/drm/asahi/m3/m3_recovery.rs index 64eb09a6453eba..1bb6eb84beedae 100644 --- a/drivers/gpu/drm/asahi/m3/m3_recovery.rs +++ b/drivers/gpu/drm/asahi/m3/m3_recovery.rs @@ -37,15 +37,21 @@ pub(crate) struct RecoveryOffsets { pub(crate) control_bytes: usize, } +/// 26.6.2 extended FirmwareData recovery offsets and affected-work snapshot geometry. +const EXTENDED_SNAPSHOT: usize = 0x40b8; +const EXTENDED_SNAPSHOT_ENTRIES: usize = 448; +const EXTENDED_GENERATION: usize = 0x4fa0; +const EXTENDED_PHASE: usize = 0x4fb0; + impl RecoveryOffsets { /// Extended control region offsets shifted by the profile's `m3_init_26` /// control-table delta (`0` on 26.6.2 / `0xeaf0`, `0x1e0` on 27.2 / `0xedd0`). pub(crate) const fn extended(shift: usize, control_bytes: usize) -> Self { Self { - snapshot: logic::SNAPSHOT + shift, - snapshot_entries: logic::SNAPSHOT_ENTRIES, - generation: logic::GENERATION + shift, - phase: logic::PHASE + shift, + snapshot: EXTENDED_SNAPSHOT + shift, + snapshot_entries: EXTENDED_SNAPSHOT_ENTRIES, + generation: EXTENDED_GENERATION + shift, + phase: EXTENDED_PHASE + shift, control_bytes, } } From b7028feb2f7acdd9e788c38e53a4dab2aedaec18 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 15:05:03 -0500 Subject: [PATCH 1114/1514] ASoC: apple: t8152-aop-audio: guard sense_ring_done against stop race Clear SenseRing's new active flag (Release) before calling device_terminate_all() in SenseRing::stop(), and check it (Acquire) both before and after device_tx_status() in sense_ring_done(). admac_chan_tasklet() drops adchan->lock before invoking the callback, while admac_terminate_all() clears adchan->current_tx under the same lock before device_synchronize() kills the tasklet. If sense_ring_done() called admac_tx_status() in that window, admac_tx_status() returned DMA_IN_PROGRESS with residue = 0, which sense_ring_done() treated as a wrap to ring offset 0 and delivered stale tail-of-ring frames (or a spurious XRUN). Checking active after device_tx_status() pairs through adchan->lock with the store in stop(), ensuring sense_ring_done() bails out whenever admac_tx_status() saw the terminated channel. Signed-off-by: Erik Bourget --- sound/soc/apple/t8152_aop_audio.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index a586570d67ec3f..bc95c387dc54ad 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -303,6 +303,10 @@ struct SenseRing { done: AtomicUsize, /// When `done` was last moved (or the ring started), CLOCK_MONOTONIC ns. done_at: AtomicI64, + /// True while a cyclic transfer is active; cleared before terminating the + /// channel so `sense_ring_done` never consumes a terminated channel's + /// zero-residue status. + active: AtomicBool, /// The attached sense front-end, or null; cleared under that front-end's /// stream lock, which the callback holds while it uses the front-end. sub: AtomicPtr, @@ -323,6 +327,7 @@ impl SenseRing { cookie: AtomicI32::new(0), done: AtomicUsize::new(0), done_at: AtomicI64::new(0), + active: AtomicBool::new(false), sub: AtomicPtr::new(ptr::null_mut()), fe_pos: AtomicUsize::new(0), fe_running: AtomicBool::new(false), @@ -409,6 +414,7 @@ impl SenseRing { } self.cookie.store(cookie, Ordering::Release); if let Some(f) = (*dma).device_issue_pending { + self.active.store(true, Ordering::Release); f(chan); } } @@ -417,6 +423,7 @@ impl SenseRing { /// Stops the transfer and waits for its callback; a no-op without a channel. fn stop(&self) { + self.active.store(false, Ordering::Release); let chan = self.chan.load(Ordering::Acquire); if chan.is_null() { return; @@ -620,6 +627,9 @@ impl SenseRing { unsafe extern "C" fn sense_ring_done(param: *mut c_void) { // SAFETY: by the function's contract. let ring = unsafe { &*param.cast::() }; + if !ring.active.load(Ordering::Acquire) { + return; + } let chan = ring.chan.load(Ordering::Acquire); if chan.is_null() { return; @@ -637,6 +647,9 @@ unsafe extern "C" fn sense_ring_done(param: *mut c_void) { None => return, } }; + if !ring.active.load(Ordering::Acquire) { + return; + } // SAFETY: no preconditions. let now_ns = unsafe { bindings::ktime_get() }; let ring_bytes = ring.ring_bytes(); From eea5439ec219984e92b3c00ac23eee6ad101afa6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 07:08:51 +1100 Subject: [PATCH 1115/1514] Revert "drm/asahi: let the G14 27.2 GPU use its full performance-state range" This reverts the merge of #3075 (1b09b76b). With all three Globals state selectors at the board's ceiling, the M2 mini's GPU runs up to the 944 mV operating point, and the G14 firmware 27.2 then hangs under sustained load. Both a native GL render (fragment never retired) and a deep compute queue (commands fetched but never retired) time out with no MMU fault and no firmware timeout event, and the GPU is lost for every client. The same kernel with +0x98 back at 100 ran the gpubench GL plan five times in a row with every case passing and no timeout. Its rail never went above 600 mV. The rows that justified #3075 (piglit and Geekbench 6) did not reach these hangs. Restore the cap until the firmware's behaviour at the higher states is understood. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 19 ++----------------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 11 ++++++----- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 20f172fdb52e96..4e7fd8de186e58 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -93,12 +93,6 @@ pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 8] = [ /// Size of the 27.2 Globals object. pub(crate) const GLOBALS_BYTES: usize = 0xe48; -/// Globals words of the three performance-state selectors, in hundredths of a state. All three -/// take the ceiling of the board's performance-state table, as G14 13.5 (`initdata`), M3 27.2 -/// (`m3_power_26`) and M4 27.2 (`g16/fw/initdata`) write them; a lower value here caps the GPU -/// clock below what the firmware's power and thermal controller would allow. -pub(crate) const GLOBALS_PSTATE_SELECTORS: [usize; 3] = [0x88, 0x8c, 0x98]; - #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { @@ -179,12 +173,12 @@ mod tests { #[test] fn progress_words_fit_the_globals_and_leave_power_words_alone() { - let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84]; + let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; for (i, &(at, value)) in GLOBALS_PROGRESS.iter().enumerate() { assert_eq!(at % 4, 0); assert!(at + 4 <= GLOBALS_BYTES); assert_ne!(value, 0); - assert!(power.iter().chain(&GLOBALS_PSTATE_SELECTORS).all(|&p| p + 4 <= at || at + 4 <= p)); + assert!(power.iter().all(|&p| p + 4 <= at || at + 4 <= p)); assert!(GLOBALS_PROGRESS[i + 1..].iter().all(|&(other, _)| other != at)); } // Every progress interval is set: a zero interval is what stopped work in a poll. @@ -192,13 +186,4 @@ mod tests { assert!(GLOBALS_PROGRESS.iter().any(|&(o, v)| o == at && v != 0)); } } - - #[test] - fn pstate_selectors_are_aligned_distinct_words_of_the_globals() { - for (i, &at) in GLOBALS_PSTATE_SELECTORS.iter().enumerate() { - assert_eq!(at % 4, 0); - assert!(at + 4 <= GLOBALS_BYTES); - assert!(GLOBALS_PSTATE_SELECTORS[i + 1..].iter().all(|&o| o + 4 <= at || at + 4 <= o)); - } - } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 70e9207001035a..32d11d7ae6e746 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -42,6 +42,9 @@ const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; +/// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. +/// Only this cap has run on hardware. +const STATE_CAP: u32 = 100; /// Board facts the root needs, read from the device tree at probe. pub(crate) struct BoardV27_2 { @@ -1064,11 +1067,9 @@ impl RootV27_2 { for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); } - put32(data, 0x84, pwr.max_power_mw); - // The performance-state ceiling the board's table describes; the power and thermal - // controller below decides how much of it the GPU may use. - for at in g14_v27_2_abi::GLOBALS_PSTATE_SELECTORS { - put32(data, at, pwr.perf_max_pstate * 100); + let ceiling = pwr.perf_max_pstate * 100; + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, STATE_CAP)] { + put32(data, at, value); } put32(data, 0x6e, 1); // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. From c602bae0a913ae77f284f67fdd3d056ce5adfc67 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 14:05:45 -0500 Subject: [PATCH 1116/1514] drm/asahi/g16: keep single-queue compute pipe-affine and micro-coalesce busy horizons Keep single-queue barrier-free compute streams affine to their active CDM pipe in choose_compute_pipe() and remove pipe_fold_cap from publish_prefix_body() so deep single-queue horizons fold into one workqueue prefix without bouncing between pipes or injecting cross-pipe c2c barriers, while independent queues and cross-VM compute still balance across both CDM pipes. Add busy-state same-queue horizon micro-coalescing (COALESCE_MAX_CMDS = 6, COALESCE_WINDOW_US = 18): only when a single queue already has >= 2 active commands in flight and every pending job belongs to that same queue and VM as a foldable barrier-free compute or non-InitBM render horizon, submit_locked() defers publish_checked() behind an hrtimer (rearm_after()) for up to 18 us so back-to-back SUBMIT ioctls fold into one multi-command flight. Shallow d=1/d=2 pipelines, barriered streams, RT/SCS work, and multi-queue/cross-VM arrivals bypass coalescing immediately with zero added latency, and any flight retirement or deadline expiry flushes the held batch immediately. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 277 +++++++++++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 6 + drivers/gpu/drm/asahi/g16/poll.rs | 63 ++-- drivers/gpu/drm/asahi/g16/recovery.rs | 1 + .../drivers/gpu/asahi-m4/test-poll-retire.py | 86 +++++- .../drivers/gpu/asahi-m4/test-publication.py | 209 +++++++++++-- 6 files changed, 571 insertions(+), 71 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 179b912db6809e..64b40c56ce5133 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -607,6 +607,9 @@ pub(crate) struct Engine { pub(crate) ta_wave_wait: bool, /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. pub(crate) short_repoll: bool, + /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing + /// (0 when no batch is held). + pub(crate) coalesce_deadline_ns: u64, /// Progress tracking of the oldest compute pipe 0/1 and render flights. pub(crate) progress_flight: [u64; 3], pub(crate) progress: [Option; 4], @@ -651,6 +654,7 @@ impl Engine { slot_wait: false, ta_wave_wait: false, short_repoll: false, + coalesce_deadline_ns: 0, progress_flight: [0; 3], progress: [None; 4], stats: KBox::zeroed(GFP_KERNEL)?, @@ -999,6 +1003,7 @@ impl Firmware { self.engine.chan_wait = false; self.engine.slot_wait = false; self.engine.ta_wave_wait = false; + self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -1540,6 +1545,193 @@ impl Firmware { } } + /// Whether `self.engine.pending` is an eligible single-queue, single-VM busy horizon + /// batch that can accumulate more same-queue commands before publishing. + fn can_defer_busy_coalesce(&self) -> bool { + if self.recovery.failed().is_some() + || self.engine.frozen + || self.engine.flights.is_empty() + || self.engine.pending.is_empty() + || self.engine.flights.len() >= super::hw::sizes::FLIGHTS + || self.engine.chan_wait + || self.engine.slot_wait + || self.engine.ta_wave_wait + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect || f.initbm) + { + return false; + } + let head = &self.engine.pending[0]; + let head_sent = head.progress.sent(); + if head.vm.status.get() != 0 + || head.long() + || !self.can_queue_behind(head) + || self + .engine + .pending + .iter() + .any(|j| !Arc::ptr_eq(&j.queue, &head.queue) || !Arc::ptr_eq(&j.vm, &head.vm)) + { + return false; + } + let Some(head_order) = head.command_order(head_sent) else { + return false; + }; + match command(head, head_sent) { + Some(Command::Compute(c)) => { + if head.resources.compute_scs() + || c.is_rt() + || head_order.wait_through != [None, None] + || !head.fw_waits.is_empty() + { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.computes as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + let Some(Command::Compute(c2)) = command(head, k) else { + return false; + }; + if c2.is_rt() || !head.can_fold_horizon_cmd(k, next_seq) { + return false; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.compute_scs() + || !j.can_fold_horizon_job(next_seq) + || (0..n).any(|k| { + matches!(command(j, k), Some(Command::Compute(c2)) if c2.is_rt()) + }) + { + return false; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_computes: usize = self + .engine + .flights + .iter() + .map(|fl| fl.computes as usize) + .sum(); + let Ok(slot_mask) = head.resources.compute_slot_mask() else { + return false; + }; + let pipe = self.choose_compute_pipe(&head.queue, [None, None], slot_mask, false); + let free_c = self.slots.free_compute_in_mask_for_pipe(slot_mask, pipe) as usize; + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(free_c) + .min(params::compute_flights().saturating_sub(active_computes)) + .min(super::hw::sizes::COMPUTE_SLOTS); + cap > 1 && pending_cmds < cap + } + Some(Command::Render(_)) => { + if head.resources.render_scs() || !head.fw_waits.is_empty() { + return false; + } + let queue_active: usize = self + .engine + .flights + .iter() + .filter(|fl| fl.renders != 0 && Arc::ptr_eq(&fl.job.queue, &head.queue)) + .map(|fl| fl.renders as usize) + .sum(); + if queue_active < 2 { + return false; + } + let Some(mut next_seq) = head_order.sequence.checked_add(1) else { + return false; + }; + let mut pending_cmds = 1usize; + for k in (head_sent + 1)..head.progress.count() { + if !head.can_fold_render_cmd(k, next_seq) { + return false; + } + let Some(s) = next_seq.checked_add(1) else { + return false; + }; + next_seq = s; + pending_cmds += 1; + } + for j in &self.engine.pending[1..] { + let n = j.progress.count(); + if j.long() + || j.resources.render_scs() + || !j.can_fold_render_horizon_job(next_seq) + { + return false; + } + let Some(s) = next_seq.checked_add(u64::from(n)) else { + return false; + }; + next_seq = s; + pending_cmds += n as usize; + } + let active_renders: usize = self + .engine + .flights + .iter() + .map(|fl| fl.renders as usize) + .sum(); + let ta_room = super::hw::sizes::TA_WAVE_PASSES + .saturating_sub(self.ta_pending_passes()); + let cap = super::hw::sizes::COALESCE_MAX_CMDS + .min(params::render_flights().saturating_sub(active_renders)) + .min(ta_room) + .min(super::hw::sizes::RENDER_SLOTS); + cap > 1 && pending_cmds < cap + } + None => false, + } + } + + /// Defers immediate publication for up to `COALESCE_WINDOW_US` while a single queue already + /// has `>= 2` active commands in flight so consecutive same-queue `SUBMIT` ioctls accumulate + /// into one multi-command flight (up to `COALESCE_MAX_CMDS`), cutting `SubmitRecord`s, WC + /// producer updates, and doorbells without delaying `d=1`/`d=2`, barriered streams, RT/SCS + /// work, or multi-queue/cross-VM handoffs. + pub(crate) fn defer_busy_coalesce(&mut self, now: u64) -> Option { + if !self.can_defer_busy_coalesce() { + self.engine.coalesce_deadline_ns = 0; + return None; + } + if self.engine.coalesce_deadline_ns == 0 { + self.engine.coalesce_deadline_ns = + now.saturating_add(super::hw::sizes::COALESCE_WINDOW_NS); + } + if now >= self.engine.coalesce_deadline_ns { + self.engine.coalesce_deadline_ns = 0; + return None; + } + let rem_ns = self.engine.coalesce_deadline_ns.saturating_sub(now); + Some((rem_ns.div_ceil(1000) as u32).clamp(1, super::hw::sizes::COALESCE_WINDOW_US)) + } + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch @@ -1814,10 +2006,14 @@ impl Firmware { /// split across two pipes. /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` /// barrier). - /// - If barrier-free (`[None, None]`) or waiting on both pipes (`[Some, Some]`), pick the - /// pipe with fewer active compute commands, breaking ties by `next_compute_pipe`. + /// - If barrier-free (`[None, None]`) and `queue` already has an active compute flight on a + /// single pipe with free units, keep that queue pipe-affine so consecutive horizon submits + /// fold onto one workqueue without splitting across pipes. + /// - Otherwise (other queues, cross-VM compute, or waiting on both pipes `[Some, Some]`), + /// pick the pipe with fewer active compute commands, breaking ties by `next_compute_pipe`. fn choose_compute_pipe( &self, + queue: &Arc, waits: [Option; sizes::COMPUTE_PIPES], slot_mask: u32, rt_compute: bool, @@ -1833,27 +2029,47 @@ impl Firmware { return 0; } match waits { - [Some(_), None] => 0, - [None, Some(_)] => 1, - _ => { - if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { - return 1; - } - let mut active = [0usize; sizes::COMPUTE_PIPES]; + [Some(_), None] => return 0, + [None, Some(_)] => return 1, + [None, None] => { + let mut q_pipe: Option = None; for fl in &self.engine.flights { - if fl.computes != 0 { + if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); - active[p] += fl.computes as usize; + match q_pipe { + None => q_pipe = Some(p), + Some(prev) if prev == p => {} + Some(_) => { + q_pipe = None; + break; + } + } } } - if active[0] < active[1] { - 0 - } else if active[1] < active[0] { - 1 - } else { - (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES + if let Some(p) = q_pipe { + if self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + return p; + } } } + [Some(_), Some(_)] => {} + } + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { + return 1; + } + let mut active = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active[p] += fl.computes as usize; + } + } + if active[0] < active[1] { + 0 + } else if active[1] < active[0] { + 1 + } else { + (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES } } @@ -2080,7 +2296,10 @@ impl Firmware { job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; - (self.choose_compute_pipe(waits, slot_mask, rt_compute), waits) + ( + self.choose_compute_pipe(&job.queue, waits, slot_mask, rt_compute), + waits, + ) }; let pipe_behind = !render && self @@ -2190,26 +2409,18 @@ impl Firmware { .slots .free_compute_in_mask_for_pipe(slot_mask, compute_pipe) as usize; - let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; - for fl in &self.engine.flights { - if fl.computes != 0 { - let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); - active_pipe[p] += fl.computes as usize; - } - } - let active_computes = active_pipe[0] + active_pipe[1]; - // Keep barrier-free work balanced across both compute pipes: fold extra commands - // into this pipe only when the alternate pipe already has deeper queued work, so - // independent submits distribute across pipes 0 and 1 in the same doorbell batch. - let pipe_fold_cap = - active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1); + let active_computes: usize = self + .engine + .flights + .iter() + .map(|fl| fl.computes as usize) + .sum(); let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; let ring_more = (sizes::QUEUE_CAP.saturating_sub(4)).saturating_sub(used) as usize; let mut more_slots = free_c .min(params::compute_flights().saturating_sub(active_computes + 1)) .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) - .min(ring_more) - .min(pipe_fold_cap); + .min(ring_more); let rt_head = job.resources.compute_scs() || c.is_rt(); // Fold trailing barrier-free compute commands of the base job first. while !rt_head && more_slots > 0 && end < job.progress.count() { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index d556b290062e59..39d0a17303a4c9 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -896,6 +896,12 @@ pub(crate) mod sizes { ); /// Maximum jobs folded into one barrier-free compute horizon prefix. pub(crate) const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32; + /// Maximum commands accumulated in a busy-state horizon micro-coalescing batch before + /// immediate publication, and maximum hold window (18 us) while a queue already has >= 2 + /// active commands in flight. + pub(crate) const COALESCE_MAX_CMDS: usize = 6; + pub(crate) const COALESCE_WINDOW_US: u32 = 18; + pub(crate) const COALESCE_WINDOW_NS: u64 = (COALESCE_WINDOW_US as u64) * 1000; /// 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. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 78b4415f27e42d..285b14fce52d71 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -141,7 +141,18 @@ impl Shared { ) { Ok(true) if retry_tail => {} Ok(true) => { - self.rearm(firmware.engine.chan_wait || firmware.engine.short_repoll) + let soon = firmware.engine.chan_wait || firmware.engine.short_repoll; + if firmware.engine.coalesce_deadline_ns != 0 && !soon { + let rem_us = (firmware + .engine + .coalesce_deadline_ns + .saturating_sub(now_ns()) + .div_ceil(1000) as u32) + .clamp(1, super::hw::sizes::COALESCE_WINDOW_US); + self.rearm_after(rem_us.min(self.rearm_us(false))); + } else { + self.rearm(soon); + } } // Idle: arm a delayed poll while DVFS utilization is decaying or a CLPC // floor hold is still pending so both expire cleanly to idle power. @@ -271,20 +282,26 @@ impl Shared { Ok(()) }); } + let mut coalesce_us = None; if pub_res.is_ok() { if retired_any || !had_flights { firmware.reclaim_closed_vm_slots(); } - pub_res = if recovery_pending { - let r = firmware.publish(done); - if r.is_ok() { - firmware.last_housekeeping_ns = now; - firmware.last_aux_drain_ns = now; - } - r - } else { - firmware.publish_checked(done) - }; + if !recovery_pending && !retired_any && !restored_event && had_flights { + coalesce_us = firmware.defer_busy_coalesce(now); + } + if coalesce_us.is_none() { + pub_res = if recovery_pending { + let r = firmware.publish(done); + if r.is_ok() { + firmware.last_housekeeping_ns = now; + firmware.last_aux_drain_ns = now; + } + r + } else { + firmware.publish_checked(done) + }; + } } if pub_res.is_ok() && !firmware.engine.flights.is_empty() @@ -300,11 +317,15 @@ impl Shared { // If an EP 0x20 event retired an older flight while later flights remain active, // or arrived before the oldest receipt became visible, arm a short repoll so // trailing completions never fall back to `resnap_us`. - self.rearm( - firmware.engine.chan_wait - || restored_event - || (was_evented && retired_any && !firmware.engine.flights.is_empty()), - ); + if let Some(us) = coalesce_us { + self.rearm_after(us.min(self.rearm_us(false))); + } else { + self.rearm( + firmware.engine.chan_wait + || restored_event + || (was_evented && retired_any && !firmware.engine.flights.is_empty()), + ); + } } else { firmware.power.report_work(false); self.arm_idle_power_poll(firmware); @@ -527,10 +548,15 @@ impl Shared { /// 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) { + self.rearm_after(self.rearm_us(soon)); + } + + /// Arms the poll hrtimer for `us` microseconds (coalescing with an already-armed deadline + /// within 5 us) plus the throttled 1-jiffy backup poll. + pub(crate) fn rearm_after(self: &Arc, us: u32) { if self.sleeping.load(Ordering::Acquire) { return; } - let us = self.rearm_us(soon); let now = now_ns(); let target_ns = now.saturating_add(u64::from(us) * 1000); let armed_ns = self.resnap_deadline_ns.load(Ordering::Acquire); @@ -683,6 +709,8 @@ impl Firmware { // while `publish_woke` covers external state changes (VM close, unstarted queue // cancellation) and `ta_wave_ready()` wakes TA-wave-paced renders when a `0x70` TA // pass finishes while FS is still running. + let coalesce_due = self.engine.coalesce_deadline_ns != 0 + && (!evented || now >= self.engine.coalesce_deadline_ns); let should_publish = !self.engine.pending.is_empty() && (retired_any || !had_flights @@ -692,6 +720,7 @@ impl Firmware { || scrub_woke || publish_woke || self.ta_wave_ready() + || coalesce_due || housekeeping_due); let published = if should_publish { self.publish_checked(done) diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index e6417355111425..f0d082eea46d4c 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -290,6 +290,7 @@ impl Firmware { self.floor_power(error); } self.engine.frozen = true; + self.engine.coalesce_deadline_ns = 0; self.events.grow.clear(); self.fail_flights(error, done); self.fail_all_vms(EIO); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 03099634f7b6c2..9b7c2ff1876561 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -68,6 +68,7 @@ def item(declaration, text=source): pub const TA_WAVE_PASSES: usize = 4; pub const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; pub const COMPUTE_PIPES: usize = 2; + pub const COALESCE_WINDOW_US: u32 = 18; } } @@ -161,6 +162,7 @@ def item(declaration, text=source): slot_wait: bool, ta_wave_wait: bool, short_repoll: bool, + coalesce_deadline_ns: u64, frozen: bool, stats: Stats, prof: Prof, @@ -217,6 +219,8 @@ def item(declaration, text=source): rearmed: Cell, idle_power_polls: Cell, rearm_soon: Cell, + rearm_after_calls: Cell, + last_rearm_us: Cell, poll_now_calls: Cell, } impl Shared { @@ -229,9 +233,18 @@ def item(declaration, text=source): rearmed: Cell::new(0), idle_power_polls: Cell::new(0), rearm_soon: Cell::new(0), + rearm_after_calls: Cell::new(0), + last_rearm_us: Cell::new(0), poll_now_calls: Cell::new(0), }) } + fn rearm_us(&self, soon: bool) -> u32 { + if soon { 25 } else { 100 } + } + fn rearm_after(&self, us: u32) { + self.rearm_after_calls.set(self.rearm_after_calls.get() + 1); + self.last_rearm_us.set(us); + } fn rearm(&self, soon: bool) { self.rearmed.set(self.rearmed.get() + 1); if soon { @@ -311,6 +324,7 @@ def item(declaration, text=source): drain_fs_delta: u32, drain_compute_delta: u32, ta_pending: usize, + coalesce_us: Option, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, @@ -347,6 +361,7 @@ def item(declaration, text=source): slot_wait: false, ta_wave_wait: false, short_repoll: false, + coalesce_deadline_ns: 0, frozen: false, stats: Stats::default(), prof: Prof::default(), @@ -364,6 +379,7 @@ def item(declaration, text=source): drain_fs_delta: 0, drain_compute_delta: 0, ta_pending: 0, + coalesce_us: None, retire_calls: 0, publish_full_calls: 0, publish_checked_calls: 0, @@ -425,9 +441,13 @@ def item(declaration, text=source): Ok(()) } fn publish_checked(&mut self, _done: &mut Completions) -> Result { + self.engine.coalesce_deadline_ns = 0; self.publish_checked_calls += 1; Ok(()) } + fn defer_busy_coalesce(&mut self, _now: u64) -> Option { + self.coalesce_us + } fn ta_pending_passes(&self) -> usize { self.ta_pending } @@ -1017,6 +1037,58 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn submit_locked_and_poll_step_micro_coalesce_busy_horizons() { + CLOCK.with(|c| c.set(100_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 2, + compute_pipe: 0, + renders: 0, + target: 0x200, + fs_target: 0, + }); + fw.engine.target[0] = 0x200; + fw.coalesce_us = Some(18); + fw.engine.coalesce_deadline_ns = 118_000; + + // submit_locked skips publish_checked and arms rearm_after(18) when defer_busy_coalesce fires. + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 3 }), &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 0); + assert_eq!(shared.rearm_after_calls.get(), 1); + assert_eq!(shared.last_rearm_us.get(), 18); + assert_eq!(shared.rearmed.get(), 0); + + // An early non-retiring event poll before the deadline does not flush prematurely. + CLOCK.with(|c| c.set(105_000)); + let (mut retry_tail, mut deferred) = (false, false); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 0); + + // Reaching the deadline on an event poll flushes immediately. + CLOCK.with(|c| c.set(118_000)); + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); + + // A timer poll (!evented) with an active coalesce deadline also flushes immediately. + fw.engine.coalesce_deadline_ns = 136_000; + CLOCK.with(|c| c.set(125_000)); + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + assert_eq!(fw.engine.coalesce_deadline_ns, 0); +} + mod boot { pub fn eproto() -> super::Error { super::Error(-71) @@ -1328,6 +1400,7 @@ def item(declaration, text=source): __IDLE_RESNAP__ __REARM_US__ __REARM__ + __REARM_AFTER__ __NOTE_FLIGHT_US__ } @@ -1415,11 +1488,21 @@ def item(declaration, text=source): assert_eq!(shared.drops.load(Ordering::Acquire), 1); assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 127_000); + // Coalesce rearm_after(18) pulls in a 25 us timer (>5 us earlier) and coalesces within 5 us. + shared.rearm_after(18); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 120_000); + CLOCK.store(106_000, Ordering::Release); + shared.rearm_after(14); + assert_eq!(shared.starts.load(Ordering::Acquire), 3); + assert_eq!(shared.drops.load(Ordering::Acquire), 2); + // cancel_resnap unconditionally clears deadline and drops handle. shared.cancel_resnap(); assert_eq!(shared.resnap_deadline_ns.load(Ordering::Acquire), 0); assert!(shared.resnap_handle.lock().is_none()); - assert_eq!(shared.drops.load(Ordering::Acquire), 2); + assert_eq!(shared.drops.load(Ordering::Acquire), 3); } #[test] @@ -1578,6 +1661,7 @@ def item(declaration, text=source): '__IDLE_RESNAP__': 'pub(crate) fn idle_resnap(', '__REARM_US__': 'pub(crate) fn rearm_us(', '__REARM__': 'pub(crate) fn rearm(', + '__REARM_AFTER__': 'pub(crate) fn rearm_after(', '__POLL_NOW__': 'pub(crate) fn poll_now(', }.items(): harness = harness.replace(token, item(decl).replace('super::hw::', 'hw::')) 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 5cefe344b30903..cf9c0cad5c3227 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -80,6 +80,7 @@ def item(declaration): assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source +assert 'pipe_fold_cap' not in source, 'pipe_fold_cap must be removed so single-queue horizons fold cleanly' harness = r''' @@ -132,7 +133,7 @@ def item(declaration): struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false}}} __SCS_COMPUTE_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -178,7 +179,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const PIPE1_COMPUTE_START:usize=6; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -291,7 +292,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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,slot_wait:false,ta_wave_wait:false}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false} @@ -1696,37 +1697,45 @@ def item(declaration): let c1=mk(1,vm1.clone(),q1.clone(),1); let c2=mk(2,vm1.clone(),q1.clone(),2); let c_vm2=mk(3,vm2.clone(),q2.clone(),1); + let q3=Queue::new(0,2); let mut host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; - // Empty engine uses next_compute_pipe (0), then balances onto pipe 1 while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); + // Empty engine uses next_compute_pipe (0). + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); host.engine.flights.push(QueueBehindFlight{ job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); - // RT/SCS compute stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, true), 0); - // A 2-unit base-only VM stays pinned to pipe 0 even while pipe 0 is active. - assert_eq!(host.choose_compute_pipe([None, None], 0b11, false), 0); - assert_eq!(host.choose_compute_pipe([None, None], 0b110, false), 0); + // Single-queue barrier-free compute stays affine to its active pipe (pipe 0), + // while a second independent queue balances onto idle pipe 1. + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false), 1); + // RT/SCS compute stays pinned to pipe 0 even for another queue while pipe 0 is active. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, true), 0); + // A 2-unit base-only or SCS VM (bits < PIPE1_COMPUTE_START) stays pinned to pipe 0 + // even for another queue while pipe 0 is active. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b11, false), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b110, false), 0); assert!(host.can_queue_behind(&c2)); - // Add second concurrent flight on pipe 1: both pipes active, - // tie-break uses next_compute_pipe, and cross-VM compute overlaps cleanly. + // Add second concurrent flight on pipe 1 from q2: both pipes active, + // q1 stays affine to pipe 0, q2 stays affine to pipe 1, and a third queue q3 + // tie-breaks by next_compute_pipe. host.engine.flights.push(QueueBehindFlight{ - job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, + job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false), 1); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 1); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe([None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1767,13 +1776,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w1, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w1, (1u32 << 24) - 1, false), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(w2, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2, (1u32 << 24) - 1, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1784,7 +1793,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(w2_ooo, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2_ooo, (1u32 << 24) - 1, false), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1844,7 +1853,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(cw,(1u32<<24)-1,false),0); + assert_eq!(host.choose_compute_pipe(&q2,cw,(1u32<<24)-1,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2506,6 +2515,164 @@ def item(declaration): assert_eq!(fw.recovery_prepare(1, 16, 0x300, [0, 0, 0, 0]), Err(ENOENT)); } } +mod busy_coalesce_scope { + use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Progress, Queue, Recovery, Result, Status, Vm}; + mod params { + pub fn compute_flights() -> usize { 23 } + pub fn render_flights() -> usize { 47 } + } + struct Resources { units: usize, scs: bool } + impl Resources { + fn compute_slot_mask(&self) -> Result { + Ok(if self.units >= 32 { u32::MAX } else { (1u32 << self.units) - 1 }) + } + fn compute_scs(&self) -> bool { self.scs } + fn render_scs(&self) -> bool { self.scs } + } + struct Job { + vm: Arc, + queue: Arc, + progress: Progress, + commands: Vec, + orders: Vec, + fw_waits: Vec<()>, + resources: Resources, + is_long: bool, + foldable: bool, + } + impl Job { + fn long(&self) -> bool { self.is_long } + fn command_order(&self, idx: u32) -> Option { self.orders.get(idx as usize).copied() } + fn can_fold_horizon_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::COMPUTE && o.sequence == expected && o.wait_through == [None, None]) + } + fn can_fold_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::COMPUTE && o.sequence == first + i as u64 && o.wait_through == [None, None]) + } + fn can_fold_render_cmd(&self, idx: u32, expected: u64) -> bool { + self.foldable + && self.orders.get(idx as usize).is_some_and(|o| o.engine == crate::command::RENDER && o.sequence == expected) + } + fn can_fold_render_horizon_job(&self, first: u64) -> bool { + self.foldable + && self.orders.iter().enumerate().all(|(i, o)| o.engine == crate::command::RENDER && o.sequence == first + i as u64) + } + } + fn command(job: &Job, k: u32) -> Option<&Command> { job.commands.get(k as usize) } + struct Flight { + job: Arc, + computes: u32, + renders: u32, + doomed: bool, + recovery_suspect: bool, + initbm: bool, + } + struct Engine { + flights: Vec, + pending: Vec>, + frozen: bool, + chan_wait: bool, + slot_wait: bool, + ta_wave_wait: bool, + coalesce_deadline_ns: u64, + } + struct Slots { free_c: u32 } + impl Slots { + fn free_compute_in_mask_for_pipe(&self, _m: u32, _p: usize) -> u32 { self.free_c } + } + struct Host { + recovery: Recovery, + engine: Engine, + slots: Slots, + allow_behind: bool, + ta_pending: usize, + } + impl Host { + fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } + fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool) -> usize { 0 } + fn ta_pending_passes(&self) -> usize { self.ta_pending } + __CAN_DEFER_BUSY_COALESCE__ + __DEFER_BUSY_COALESCE__ + } + fn mk_job(vm: &Arc, q: &Arc, render: bool, seq: u64, wait: [Option; 2]) -> Arc { + Arc::new(Job { + vm: vm.clone(), + queue: q.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: false, rt: false }) }], + orders: vec![Order { engine: if render { crate::command::RENDER } else { crate::command::COMPUTE }, sequence: seq, wait_through: wait }], + fw_waits: vec![], + resources: Resources { units: 24, scs: false }, + is_long: false, + foldable: true, + }) + } + #[test] + fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { + let vm1 = Arc::new(Vm { status: Status(AtomicU32::new(0)), slot: 1 }); + let q1 = Queue::new(0, 2); + let q2 = Queue::new(0, 2); + let c1 = mk_job(&vm1, &q1, false, 1, [None, None]); + let mut h = Host { + recovery: Recovery { error: None, publication_wait_deadline: None }, + engine: Engine { + flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, doomed: false, recovery_suspect: false, initbm: false }], + pending: vec![mk_job(&vm1, &q1, false, 2, [None, None])], + frozen: false, + chan_wait: false, + slot_wait: false, + ta_wave_wait: false, + coalesce_deadline_ns: 0, + }, + slots: Slots { free_c: 20 }, + allow_behind: true, + ta_pending: 0, + }; + // d=2 (queue_active == 1 < 2): ZERO coalescing delay. + assert_eq!(h.defer_busy_coalesce(100_000), None); + + // Once queue_active >= 2, barrier-free compute holds up to 18 us and accumulates up to K=6. + h.engine.flights[0].computes = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(100_000), Some(18)); + assert_eq!(h.engine.coalesce_deadline_ns, 118_000); + // Second job arrives 5 us later -> remaining 13 us. + h.engine.pending.push(mk_job(&vm1, &q1, false, 4, [None, None])); + assert_eq!(h.defer_busy_coalesce(105_000), Some(13)); + // Reaching K=6 pending commands flushes immediately. + for seq in 5..=8 { + h.engine.pending.push(mk_job(&vm1, &q1, false, seq, [None, None])); + } + assert_eq!(h.defer_busy_coalesce(110_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // Deadline expiry flushes even with 1 pending command. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + assert_eq!(h.defer_busy_coalesce(200_000), Some(18)); + assert_eq!(h.defer_busy_coalesce(218_000), None); + assert_eq!(h.engine.coalesce_deadline_ns, 0); + + // Another queue arriving in pending flushes immediately (no cross-queue head-of-line delay). + assert_eq!(h.defer_busy_coalesce(300_000), Some(18)); + h.engine.pending.push(mk_job(&vm1, &q2, false, 1, [None, None])); + assert_eq!(h.defer_busy_coalesce(302_000), None); + + // Barriered compute flushes immediately (0 delay). + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, Some(2)])]; + assert_eq!(h.defer_busy_coalesce(400_000), None); + + // Render with queue_active == 2 and ta_pending == 2 (ta_room == 2) holds 1 pass and flushes at 2. + let r1 = mk_job(&vm1, &q1, true, 1, [None, None]); + h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, doomed: false, recovery_suspect: false, initbm: false }]; + h.ta_pending = 2; + h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(500_000), Some(18)); + h.engine.pending.push(mk_job(&vm1, &q1, true, 4, [Some(3), None])); + assert_eq!(h.defer_busy_coalesce(505_000), None); + } +} ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) @@ -2565,6 +2732,8 @@ def item(declaration): '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__CAN_DEFER_BUSY_COALESCE__': 'fn can_defer_busy_coalesce(', + '__DEFER_BUSY_COALESCE__': 'pub(crate) fn defer_busy_coalesce(', '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', From 726fb859b58cb354041c19458b5143c26b608a24 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 14:16:39 -0500 Subject: [PATCH 1117/1514] drm/asahi/g16: adaptive TA wave window, O(1) pending scan, and cursor-ordered async pass pre-scrub Light single-layer render passes (tilemap_bytes <= 64 KiB) do not saturate M4 firmware's TA/scene pipeline at 4 passes, while deep single-queue render bursts (d=64) hit three avoidable CPU/pacing cliffs: 1) TA_WAVE_PASSES=4 caps light render waves and limits render busy micro-coalescing to 2 passes; 2) publish_checked() re-read WC fw_stamp and rescanned pending[..i] for every blocked follower of the head queue; and 3) stage_displaced_pass_scrubs() scanned slots 0..47 instead of starting at pass_cursor, leaving upcoming slots dirty when >8 displaced slots were pending. Precompute RenderCommand::heavy_ta on admission, raise the light single- layer TA wave cap to TA_WAVE_PASSES_LIGHT=8 while keeping conservative TA_WAVE_PASSES=4 whenever any active or pending pass is heavy, adapt ta_wave_ready() hysteresis to cap - 2, and raise SCHEDULER_CREDITS to 64. Hoist ta_pending_passes() once per publish_checked() pass and skip blocked same-queue followers in O(1), and scan stage_displaced_pass_scrubs() cursor-ordered from pass_cursor while preserving pick_pass_in_for's same_dirty > unowned preference. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 13 + drivers/gpu/drm/asahi/g16/engine.rs | 174 ++++++++++-- drivers/gpu/drm/asahi/g16/hw.rs | 22 +- drivers/gpu/drm/asahi/g16/poll.rs | 7 +- drivers/gpu/drm/asahi/g16/slots.rs | 9 +- .../gpu/asahi-m4/test-command-stream.py | 2 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 24 +- .../drivers/gpu/asahi-m4/test-publication.py | 252 ++++++++++++------ .../drivers/gpu/asahi-m4/test-resources.py | 41 +++ 9 files changed, 417 insertions(+), 127 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index c45d53bc86eabc..b21c9eb1f9b534 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -181,6 +181,15 @@ pub(crate) struct RenderCommand { /// Explicit hardware attachments in effect for each render engine. pub(crate) vertex_attachments: KVec, pub(crate) fragment_attachments: KVec, + /// Whether this pass exceeds the light-TA wave threshold (multi-layer or large tilemap). + pub(crate) heavy_ta: bool, +} + +impl RenderCommand { + /// Whether this render pass requires the conservative `TA_WAVE_PASSES` wave window. + pub(crate) fn is_heavy_ta(&self) -> bool { + self.heavy_ta + } } /// A validated compute command. @@ -1517,6 +1526,9 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result 1 + || super::encode::Geometry::new(&packet, 0).tilemap_bytes + > hw::sizes::TA_LIGHT_TILEMAP_BYTES; commands.push(Command::Render(KBox::new( RenderCommand { cmd: packet, @@ -1525,6 +1537,7 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result = None; + if !self.engine.flights.is_empty() + && !self.can_queue_behind_with_ta(&job, &mut ta_pending) + { if self.needs_engine_drain(&job) { self.engine.stats.hold[0] += 1; break; } - let ta_wave_paused = self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES; + let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); + let ta_wave_paused = ta_val >= self.active_ta_wave_cap(); let mut alt: Option = None; for (i, cand) in self.engine.pending.iter().enumerate() { - if i == index || !self.can_queue_behind(cand) { + if i == index { + continue; + } + // Fast O(1) skip for blocked head-queue followers: `Engine::pick` chose the + // earliest pending job of `job.queue`, so later jobs of the same queue are + // FIFO-blocked unless an independent non-query compute may bypass TA-wave + // paused renders. + if i > index + && Arc::ptr_eq(&cand.queue, &job.queue) + && !(ta_wave_paused + && matches!( + command(cand, cand.progress.sent()), + Some(Command::Compute(c)) if !c.query_access + )) + { + continue; + } + if !self.can_queue_behind_with_ta(cand, &mut ta_pending) { continue; } // Preserve per-queue FIFO: never jump a later job of a queue ahead @@ -1047,7 +1071,8 @@ impl Firmware { ) && matches!( command(earlier, earlier.progress.sent()), - Some(Command::Render(_)) + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) ) && !self.needs_engine_drain(earlier) && earlier @@ -1080,17 +1105,16 @@ impl Firmware { .pending .iter() .any(|cand| self.blocked_on_slot_headroom(cand)); - self.engine.ta_wave_wait = self.ta_pending_passes() - >= super::hw::sizes::TA_WAVE_PASSES - && self.engine.pending.iter().any(|cand| { - matches!( - command(cand, cand.progress.sent()), - Some(Command::Render(_)) - ) && !self.needs_engine_drain(cand) - && cand - .check_command_dependencies(cand.progress.sent()) - .is_ok() - }); + self.engine.ta_wave_wait = self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) + if ta_val >= self.ta_wave_cap_for(r.is_heavy_ta()) + ) && !self.needs_engine_drain(cand) + && cand + .check_command_dependencies(cand.progress.sent()) + .is_ok() + }); self.engine.stats.hold[0] += 1; break; } @@ -1190,12 +1214,12 @@ impl Firmware { if job.progress.sent() == job.progress.count() { self.engine.unpend(&job); // fully published } - // Ring TA/FS immediately once a render wave fills TA_WAVE_PASSES so the GPU - // starts tiling right away instead of waiting behind another loop iteration - // or an alt-class compute publication. + // Ring TA/FS immediately once a render wave fills the active TA wave window so + // the GPU starts tiling right away instead of waiting behind another loop + // iteration or an alt-class compute publication. if pending_rings & ((1u8 << (Channel::Fs as u8)) | (1u8 << (Channel::Ta as u8))) != 0 - && self.ta_pending_passes() >= super::hw::sizes::TA_WAVE_PASSES + && self.ta_pending_passes() >= self.active_ta_wave_cap() { if let Err(e) = self.flush_doorbells(&mut pending_rings) { dev_err!( @@ -1413,6 +1437,45 @@ impl Firmware { pending } + /// Adaptive TA wave window for a candidate render pass: conservative `TA_WAVE_PASSES` (4) + /// when either the candidate or any active render flight is heavy (multi-layer or tilemap + /// above `TA_LIGHT_TILEMAP_BYTES`), and `TA_WAVE_PASSES_LIGHT` (8) for light single-layer + /// render bursts. + fn ta_wave_cap_for(&self, cand_heavy: bool) -> usize { + if cand_heavy + || self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + { + super::hw::sizes::TA_WAVE_PASSES + } else { + super::hw::sizes::TA_WAVE_PASSES_LIGHT + } + } + + /// Active TA wave window across in-flight renders and pending render heads, used for + /// immediate wave doorbell flushes and `ta_wave_ready()` hysteresis. + pub(crate) fn active_ta_wave_cap(&self) -> usize { + if self + .engine + .flights + .iter() + .any(|fl| fl.renders != 0 && fl.heavy_render) + || self.engine.pending.iter().any(|cand| { + matches!( + command(cand, cand.progress.sent()), + Some(Command::Render(r)) if r.is_heavy_ta() + ) + }) + { + super::hw::sizes::TA_WAVE_PASSES + } else { + super::hw::sizes::TA_WAVE_PASSES_LIGHT + } + } + /// Whether `job`'s next command may be published behind the flights in flight: /// /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM @@ -1433,6 +1496,14 @@ impl Firmware { /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. fn can_queue_behind(&self, job: &Arc) -> bool { + let mut ta_pending = None; + self.can_queue_behind_with_ta(job, &mut ta_pending) + } + + /// [`Self::can_queue_behind`] with an optional caller-hoisted cache of + /// [`Self::ta_pending_passes`] so scanning many pending jobs performs at most one WC stamp + /// read per pass. + fn can_queue_behind_with_ta(&self, job: &Arc, ta_pending: &mut Option) -> bool { let e = &self.engine; let sent = job.progress.sent(); if job.vm.status.get() != 0 @@ -1511,15 +1582,16 @@ impl Firmware { .compute_slot_mask() .is_ok_and(|mask| self.slots.compute_available_in_mask(mask)) } - Some(Command::Render(_)) => { + Some(Command::Render(r)) => { let cross_vm_compute = e .flights .iter() .any(|f| f.computes != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); + let ta_cap = self.ta_wave_cap_for(r.is_heavy_ta()); !cross_vm_compute && render_count < params::render_flights() - && self.ta_pending_passes() < super::hw::sizes::TA_WAVE_PASSES + && *ta_pending.get_or_insert_with(|| self.ta_pending_passes()) < ta_cap && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() @@ -1650,7 +1722,7 @@ impl Firmware { .min(super::hw::sizes::COMPUTE_SLOTS); cap > 1 && pending_cmds < cap } - Some(Command::Render(_)) => { + Some(Command::Render(r)) => { if head.resources.render_scs() || !head.fw_waits.is_empty() { return false; } @@ -1667,11 +1739,15 @@ impl Firmware { let Some(mut next_seq) = head_order.sequence.checked_add(1) else { return false; }; + let mut wave_heavy = r.is_heavy_ta(); let mut pending_cmds = 1usize; for k in (head_sent + 1)..head.progress.count() { if !head.can_fold_render_cmd(k, next_seq) { return false; } + if matches!(command(head, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) { + wave_heavy = true; + } let Some(s) = next_seq.checked_add(1) else { return false; }; @@ -1686,6 +1762,11 @@ impl Firmware { { return false; } + if (0..n).any(|k| { + matches!(command(j, k), Some(Command::Render(r2)) if r2.is_heavy_ta()) + }) { + wave_heavy = true; + } let Some(s) = next_seq.checked_add(u64::from(n)) else { return false; }; @@ -1698,8 +1779,8 @@ impl Firmware { .iter() .map(|fl| fl.renders as usize) .sum(); - let ta_room = super::hw::sizes::TA_WAVE_PASSES - .saturating_sub(self.ta_pending_passes()); + let wave_cap = self.ta_wave_cap_for(wave_heavy); + let ta_room = wave_cap.saturating_sub(self.ta_pending_passes()); let cap = super::hw::sizes::COALESCE_MAX_CMDS .min(params::render_flights().saturating_sub(active_renders)) .min(ta_room) @@ -2581,10 +2662,18 @@ impl Firmware { .iter() .map(|fl| fl.renders as usize) .sum(); + let ta_pending_before = self.ta_pending_passes(); + let mut wave_heavy = + self.ta_wave_cap_for(r.is_heavy_ta()) == sizes::TA_WAVE_PASSES; + let wave_cap = if wave_heavy { + sizes::TA_WAVE_PASSES + } else { + sizes::TA_WAVE_PASSES_LIGHT + }; let mut more_renders = params::render_flights() .saturating_sub(active_renders + 1) .min(sizes::RENDER_SLOTS.saturating_sub(1)) - .min(sizes::TA_WAVE_PASSES.saturating_sub(self.ta_pending_passes() + 1)); + .min(wave_cap.saturating_sub(ta_pending_before + 1)); while more_renders > 0 && end < job.progress.count() { let Some(next_seq) = last_seq.and_then(|s| s.checked_add(1)) else { break; @@ -2597,6 +2686,18 @@ impl Firmware { let Some(Command::Render(r2)) = command(job, end) else { break; }; + if r2.is_heavy_ta() && !wave_heavy { + if ta_pending_before + prefix.renders as usize + 1 + > sizes::TA_WAVE_PASSES + { + break; + } + wave_heavy = true; + more_renders = more_renders.min( + sizes::TA_WAVE_PASSES + .saturating_sub(ta_pending_before + prefix.renders as usize), + ); + } let Some(o2) = job.command_order(end) else { break; }; @@ -2672,7 +2773,7 @@ impl Firmware { more_renders -= 1; } // Cross-job render horizon: fold subsequent ready render-only jobs of - // the same queue and VM into the same <= TA_WAVE_PASSES flight, sharing + // the same queue and VM into the same adaptive TA wave flight, sharing // one TA/FS producer advance, one UMA submitted update, and one doorbell. // Any non-qualifying job of this queue ends the scan so no later job // overtakes it. @@ -2725,14 +2826,18 @@ impl Firmware { { break; } - let mut picked = [0usize; sizes::TA_WAVE_PASSES]; + let mut picked = [0usize; sizes::TA_WAVE_PASSES_LIGHT]; let mut picked_mask = f.claims.pass_mask; let mut precheck_ok = true; + let mut job_heavy = false; for k in 0..n2 { let Some(Command::Render(r2)) = command(&j2, k) else { precheck_ok = false; break; }; + if r2.is_heavy_ta() { + job_heavy = true; + } let Some(o2) = j2.command_order(k) else { precheck_ok = false; break; @@ -2789,7 +2894,13 @@ impl Firmware { picked[k as usize] = slot; picked_mask |= 1u64 << slot; } - if !precheck_ok || f.group.reserve(1, GFP_NOWAIT).is_err() { + if !precheck_ok + || (job_heavy + && !wave_heavy + && ta_pending_before + prefix.renders as usize + n2_usize + > sizes::TA_WAVE_PASSES) + || f.group.reserve(1, GFP_NOWAIT).is_err() + { break; } let _ = f.group.push_within_capacity(j2.clone()); @@ -2818,6 +2929,12 @@ impl Firmware { } last_seq = Some(first_seq + u64::from(n2 - 1)); more_renders -= n2_usize; + if job_heavy && !wave_heavy { + wave_heavy = true; + let ta_in_wave = ta_pending_before + prefix.renders as usize; + more_renders = more_renders + .min(sizes::TA_WAVE_PASSES.saturating_sub(ta_in_wave)); + } } } } @@ -3363,6 +3480,7 @@ impl Firmware { (refs, false) }; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); + f.heavy_render |= cmd.is_heavy_ta(); let p = resources.render_pass(k)?; let pass = p.refs(); let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 39d0a17303a4c9..e7c8e8f6e6b9d5 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -782,13 +782,19 @@ pub(crate) mod sizes { /// Worst-case firmware work-ring entries per compute command (`fs2c` barrier + cross-pipe /// `c2c` barrier + `work`). pub(crate) const MAX_COMPUTE_RING_ENTRIES: usize = 3; - /// Maximum unfinished TA passes kept in flight at once so multi-pass render bursts stay - /// inside M4 firmware's `<= 4`-pass TA/scene pipeline without throttling single-pass - /// pipelining (where TA finishes well ahead of FS). + /// Maximum unfinished TA passes kept in flight at once for heavy multi-layer or large-tilemap + /// renders so heavy bursts stay inside M4 firmware's `<= 4`-pass TA/scene pipeline. pub(crate) const TA_WAVE_PASSES: usize = 4; - /// Unfinished TA pass count at or below which a TA-wave-paused render queue wakes to + /// Maximum unfinished TA passes kept in flight at once for light single-layer renders + /// (`tilemap_bytes <= TA_LIGHT_TILEMAP_BYTES`), doubling the wave window for light render + /// bursts and deeper micro-coalesced batches. + pub(crate) const TA_WAVE_PASSES_LIGHT: usize = 8; + /// Tilemap byte threshold at or below which a single-layer render qualifies for + /// `TA_WAVE_PASSES_LIGHT`. + pub(crate) const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; + /// Headroom below the active TA wave cap at which a TA-wave-paused render queue wakes to /// launch the next wave, avoiding 1-pass stub drips. - pub(crate) const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; + pub(crate) const TA_WAVE_REFILL_HEADROOM: usize = 2; /// Base render pass slots allocated on first render (full TPC/tilemap capacity). pub(crate) const BASE_RENDER_SLOTS: usize = 2; /// Retained render pass slots per VM at most. A slot is reused only after a later render @@ -902,10 +908,10 @@ pub(crate) mod sizes { pub(crate) const COALESCE_MAX_CMDS: usize = 6; pub(crate) const COALESCE_WINDOW_US: u32 = 18; pub(crate) const COALESCE_WINDOW_NS: u64 = (COALESCE_WINDOW_US as u64) * 1000; - /// 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 + /// Jobs admitted to the engine per logical queue: enough to keep deep queues (`d=64`) + /// queued back to back without scheduler backpressure stalls; exact prior-command /// dependencies still gate each one. - pub(crate) const SCHEDULER_CREDITS: u32 = 32; + pub(crate) const SCHEDULER_CREDITS: u32 = 64; /// Unconsumed records per 256-entry channel ring a prefix may be posted behind. pub(crate) const AHEAD_RECORDS: u32 = 128; /// Policy bound on logical queues reported in QUEUE_LIMITS (not a firmware limit). diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 285b14fce52d71..bce03532986548 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -845,10 +845,13 @@ impl Firmware { Some((compute, render)) } - /// Whether a render job paused by `TA_WAVE_PASSES` pacing has enough TA headroom to publish + /// Whether a render job paused by TA wave pacing has enough TA headroom to publish /// the next wave without dribbling 1-pass stub flights. fn ta_wave_ready(&self) -> bool { - self.engine.ta_wave_wait && self.ta_pending_passes() <= super::hw::sizes::TA_WAVE_REFILL + let cap = self.active_ta_wave_cap(); + self.engine.ta_wave_wait + && self.ta_pending_passes() + <= cap.saturating_sub(super::hw::sizes::TA_WAVE_REFILL_HEADROOM) } /// Cheap single-stage stamp check for the oldest compute pipe 0/1 and oldest render flights' diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 697598889f1f72..1d48b4cd996d4a 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -1138,12 +1138,15 @@ impl Slots { pub(crate) fn note_render_retired(&mut self) { self.render.scrub_pending = true; } - /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing. - /// Never touches `Published` or undisplaced `Retired` slots. + /// Stages any newly displaced, cleanly retired render pass slots for off-lock pre-scrubbing, + /// scanning cursor-ordered from `pass_cursor` so the slots `pick_pass_in_for` will reach next + /// are scrubbed first. Never touches `Published` or undisplaced `Retired` slots. pub(crate) fn stage_displaced_pass_scrubs(&mut self) { self.render.scrub_pending = false; self.fold_scrub_stats(); - for k in 0..sizes::RENDER_SLOTS { + let start = self.pass_cursor as usize % sizes::RENDER_SLOTS; + for i in 0..sizes::RENDER_SLOTS { + let k = (start + i) % sizes::RENDER_SLOTS; let bit = 1u64 << k; if self.pass_busy & bit != 0 || !self.render.lifetime.available(k) 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 27093fdfdf1e7b..0a779b3fb7d3da 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 @@ -124,7 +124,7 @@ mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } mod hw { pub const USER_RANGE: core::ops::Range = 0x4000..((1u64 << 42) - 0x8000); - pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; } + pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; pub const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; } pub mod client { pub const PB_HEAP_SIZE:u64=0x10000000; CAPACITIES } } mod fw { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 9b7c2ff1876561..df5d84c420362f 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -66,7 +66,8 @@ def item(declaration, text=source): mod hw { pub mod sizes { pub const TA_WAVE_PASSES: usize = 4; - pub const TA_WAVE_REFILL: usize = TA_WAVE_PASSES / 2; + pub const TA_WAVE_PASSES_LIGHT: usize = 8; + pub const TA_WAVE_REFILL_HEADROOM: usize = 2; pub const COMPUTE_PIPES: usize = 2; pub const COALESCE_WINDOW_US: u32 = 18; } @@ -324,6 +325,7 @@ def item(declaration, text=source): drain_fs_delta: u32, drain_compute_delta: u32, ta_pending: usize, + ta_wave_cap: usize, coalesce_us: Option, retire_calls: u32, publish_full_calls: u32, @@ -379,6 +381,7 @@ def item(declaration, text=source): drain_fs_delta: 0, drain_compute_delta: 0, ta_pending: 0, + ta_wave_cap: hw::sizes::TA_WAVE_PASSES, coalesce_us: None, retire_calls: 0, publish_full_calls: 0, @@ -451,6 +454,9 @@ def item(declaration, text=source): fn ta_pending_passes(&self) -> usize { self.ta_pending } + fn active_ta_wave_cap(&self) -> usize { + self.ta_wave_cap + } __RECLAIM_CLOSED_VM_SLOTS__ __POLL_STEP__ @@ -1018,8 +1024,7 @@ def item(declaration, text=source): assert!(!retry_tail); assert!(fw.engine.short_repoll); - // TA drains to 2 (<= TA_WAVE_REFILL): immediately wakes publish_checked() to launch the - // next wave cleanly. + // TA drains to 2 (<= cap - TA_WAVE_REFILL_HEADROOM): immediately wakes publish_checked(). fw.ta_pending = 2; assert!(fw .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) @@ -1027,6 +1032,19 @@ def item(declaration, text=source): assert_eq!(fw.publish_checked_calls, 1); assert!(fw.engine.short_repoll); + // Light TA wave cap (8): stays paused at 7 (> 8 - 2), wakes at 6 (<= 6). + fw.ta_wave_cap = hw::sizes::TA_WAVE_PASSES_LIGHT; + fw.ta_pending = 7; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 1); + fw.ta_pending = 6; + assert!(fw + .poll_step(true, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert_eq!(fw.publish_checked_calls, 2); + // Once ta_wave_wait clears, a TA-only 0x70 IRQ stays non_terminal_only (no spin/short_repoll). fw.engine.ta_wave_wait = false; retry_tail = false; 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 cf9c0cad5c3227..9552965a752093 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -45,7 +45,7 @@ def item(declaration): assert 'const HORIZON_JOBS: u32 = COMPUTE_UNITS as u32;' in hw_src prefix_render_fn = item('fn prefix_render(') prefix_compute_fn = item('fn prefix_compute(') -can_queue_behind_fn = item('fn can_queue_behind(') +can_queue_behind_fn = item('fn can_queue_behind_with_ta(') assert 'let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);' in prefix_render_fn assert ( prefix_render_fn.index('let render_bar = cross_engine_barrier_type(producer_initbm, init_buffer);') @@ -97,7 +97,11 @@ def item(declaration): #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } -#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(()) } +#[derive(Copy,Clone)]struct RenderCommand { heavy_ta: bool } +impl RenderCommand { fn is_heavy_ta(&self) -> bool { self.heavy_ta } } +const R_LIGHT: RenderCommand = RenderCommand { heavy_ta: false }; +const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true }; +#[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } 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, completed:[AtomicU64;2], compute_ooo:AtomicU64 } @@ -130,8 +134,8 @@ def item(declaration): fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} #[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} struct Claims; -struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool} -impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false}}} +struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} +impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,coalesce_deadline_ns:u64} impl Engine { @@ -179,7 +183,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_REFILL:usize=TA_WAVE_PASSES/2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -219,25 +223,34 @@ def item(declaration): 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,block_render_behind:bool,block_compute_behind:bool, + ta_pending_calls:std::cell::Cell, } impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + __TA_WAVE_CAP_FOR__ + __ACTIVE_TA_WAVE_CAP__ fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ if self.engine.flights.is_empty()||self.needs_engine_drain(job){return false;} if job.check_command_dependencies(job.progress.sent()).is_err(){return false;} - (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(())))) + (self.block_render_behind&&matches!(command(job,job.progress.sent()),Some(Command::Render(_)))) ||(self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_)))) } fn ta_pending_passes(&self)->usize{ + self.ta_pending_calls.set(self.ta_pending_calls.get()+1); self.engine.flights.iter().map(|f|f.renders as usize).sum() } fn can_queue_behind(&self,job:&Arc)->bool{ + let mut ta_pending=None; + self.can_queue_behind_with_ta(job,&mut ta_pending) + } + fn can_queue_behind_with_ta(&self,job:&Arc,ta_pending:&mut Option)->bool{ if !self.allow_behind{return false;} if self.needs_engine_drain(job){return false;} - if matches!(command(job,job.progress.sent()),Some(Command::Render(()))){ - if self.block_render_behind||self.ta_pending_passes()>=hw::sizes::TA_WAVE_PASSES{return false;} + if let Some(Command::Render(r))=command(job,job.progress.sent()){ + let cap=self.ta_wave_cap_for(r.is_heavy_ta()); + if self.block_render_behind||*ta_pending.get_or_insert_with(||self.ta_pending_passes())>=cap{return false;} } if self.block_compute_behind&&matches!(command(job,job.progress.sent()),Some(Command::Compute(_))){return false;} true @@ -264,9 +277,10 @@ def item(declaration): let idx=job.progress.sent.fetch_add(1,Ordering::Relaxed); let mut fl=Flight::new(job.clone()); match command(job,idx){ - Some(Command::Render(()))=>{ + Some(Command::Render(r))=>{ *pending_rings|=(1<<(Channel::Fs as u8))|(1<<(Channel::Ta as u8)); fl.renders=1; + fl.heavy_render=r.is_heavy_ta(); fl.initbm=!self.pools.can_pipeline(&job.vm); } _=>{*pending_rings|=1<<(Channel::Compute as u8);fl.computes=1;} @@ -281,11 +295,14 @@ def item(declaration): __PUBLISH_CHECKED__ } fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} -fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ +fn job_on_vm_mode(id:u32,vm:Arc,render:bool,heavy:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) + commands:vec![if render{Command::Render(RenderCommand{heavy_ta:heavy})}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) +} +fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ + job_on_vm_mode(id,vm,render,false,sent,dependency) } fn job(id:u32,render:bool,sent:u32,dependency:Result)->Arc{ job_on_vm(id,mk_vm(id),render,sent,dependency) @@ -295,7 +312,8 @@ def item(declaration): engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false} + retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, + ta_pending_calls:std::cell::Cell::new(0)} } #[cfg(test)]mod tests{ use super::*; @@ -439,7 +457,7 @@ def item(declaration): id,vm:vm1.clone(), queue:Queue::new(0,priority), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // Head render (prio 2) is blocked behind active render flight; alt-class fallback @@ -558,7 +576,7 @@ def item(declaration): let mk_q=|id:u32,q:Arc,render:bool|Arc::new(Job{ id,vm:vm1.clone(),queue:q, progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, }); // q1 has blocked render job 1 followed by compute job 2 on the SAME queue q1; @@ -621,21 +639,57 @@ def item(declaration): assert_eq!(f.session.rings,[Channel::Compute,Channel::Fs,Channel::Ta]); } #[test]fn ta_wave_pacing_flushes_doorbell_at_four_passes_and_arms_ta_wave_wait(){ + // Heavy renders fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses. let vm1=mk_vm(1); - let mut jobs:Vec>=(1..=5).map(|id|job_on_vm(id,vm1.clone(),true,0,Ok(()))).collect(); - jobs.push(job_on_vm(6,vm1,false,0,Ok(()))); + let mut jobs:Vec>=(1..=5).map(|id|job_on_vm_mode(id,vm1.clone(),true,true,0,Ok(()))).collect(); + jobs.push(job_on_vm(6,vm1.clone(),false,0,Ok(()))); let stages=vec![(Ok(()),true);5]; let mut f=firmware(jobs,stages); f.allow_behind=true; let mut done=vec![]; assert_eq!(f.publish_checked(&mut done),Ok(())); - // Passes 1..4 fill TA_WAVE_PASSES (4) and ring FS+TA immediately; pass 5 pauses with - // ta_wave_wait=true while alt compute job 6 still publishes on Compute. assert_eq!(f.attempted,[1,2,3,4,6]); assert_eq!(f.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); assert!(f.engine.ta_wave_wait); assert!(!f.engine.slot_wait); assert_eq!(f.engine.pending.len(),1); + + // Light renders fill TA_WAVE_PASSES_LIGHT (8) and ring FS+TA immediately; pass 9 pauses. + let mut light_jobs:Vec>=(1..=9).map(|id|job_on_vm_mode(id,vm1.clone(),true,false,0,Ok(()))).collect(); + light_jobs.push(job_on_vm(10,vm1,false,0,Ok(()))); + let mut fl=firmware(light_jobs,vec![(Ok(()),true);9]); + fl.allow_behind=true; + assert_eq!(fl.publish_checked(&mut done),Ok(())); + assert_eq!(fl.attempted,[1,2,3,4,5,6,7,8,10]); + assert_eq!(fl.session.rings,[Channel::Fs,Channel::Ta,Channel::Compute]); + assert!(fl.engine.ta_wave_wait); + assert!(!fl.engine.slot_wait); + assert_eq!(fl.engine.pending.len(),1); + } + #[test]fn publish_checked_d64_blocked_single_queue_hoists_ta_pending_and_skips_same_queue_in_o1(){ + let vm1=mk_vm(1); + let q1=Queue::new(0,0); + let mk=|id:u32|Arc::new(Job{ + id,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + dependency:Ok(()),terminal_marked:AtomicBool::new(false),resources:Resources, + }); + let pending:Vec>=(9..=68).map(mk).collect(); + let mut f=firmware(pending,vec![]); + for id in 1..=8 { + let mut fl=Flight::new(mk(id)); + fl.renders=1; + f.engine.flights.push(fl); + } + f.allow_behind=true; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty()); + assert!(f.engine.ta_wave_wait); + assert_eq!(f.engine.pending.len(),60); + // Hoisted ta_pending + O(1) same-queue skip reads TA stamp at most once across 60 jobs. + assert_eq!(f.ta_pending_calls.get(),1); } #[test]fn same_queue_independent_compute_bypasses_ta_wave_paused_render_only(){ let vm1=mk_vm(1); @@ -643,14 +697,15 @@ def item(declaration): let mk=|id:u32,render:bool,query_access:bool,dep:Result|Arc::new(Job{ id,vm:vm1.clone(),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,rt:false})}], + commands:vec![if render{Command::Render(R_HEAVY)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], dependency:dep,terminal_marked:AtomicBool::new(false),resources:Resources, }); - // Seed 4 active TA passes so TA wave pacing is active. + // Seed 4 active heavy TA passes so TA wave pacing is active. let mut active_flights=Vec::new(); for id in 1..=4 { let mut fl=Flight::new(mk(id,true,false,Ok(()))); fl.renders=1; + fl.heavy_render=true; active_flights.push(fl); } // On q1: render 9 is TA-wave paused; independent !query_access compute 10 bypasses it. @@ -732,7 +787,7 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -795,7 +850,9 @@ def item(declaration): __NEEDS_ENGINE_DRAIN__ __BLOCKED_ON_SLOT_HEADROOM__ __TA_PENDING_PASSES__ + __TA_WAVE_CAP_FOR__ __CAN_QUEUE_BEHIND__ + __CAN_QUEUE_BEHIND_WITH_TA__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ @@ -808,7 +865,7 @@ def item(declaration): let q1=Queue::new(0,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,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -818,7 +875,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -860,7 +917,7 @@ def item(declaration): order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); - let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; let rq=mk(1,vm1.clone(),q1.clone(),true); let rq_next=mk(2,vm1.clone(),q1.clone(),true); let rq_post=mk(3,vm1.clone(),q1.clone(),false); @@ -918,7 +975,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -930,13 +987,13 @@ def item(declaration): let timed_render=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -950,7 +1007,7 @@ def item(declaration): let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ 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,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:true,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -960,7 +1017,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -995,7 +1052,7 @@ def item(declaration): let q2=Queue::new(0,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:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1004,7 +1061,7 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false,heavy_render:false, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; @@ -1037,7 +1094,7 @@ def item(declaration): let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1049,8 +1106,8 @@ def item(declaration): let p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1086,7 +1143,7 @@ def item(declaration): let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1109,7 +1166,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1119,7 +1176,7 @@ def item(declaration): let host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1158,14 +1215,14 @@ def item(declaration): let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1176,7 +1233,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1188,7 +1245,7 @@ def item(declaration): let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),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:false,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access:false,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1203,7 +1260,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1222,7 +1279,7 @@ def item(declaration): let multi=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:3,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(()),Command::Render(()),Command::Render(())], + commands:vec![Command::Render(R_LIGHT),Command::Render(R_LIGHT),Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![ Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, @@ -1234,7 +1291,7 @@ def item(declaration): let next_r=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1243,7 +1300,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1258,7 +1315,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1266,21 +1323,21 @@ def item(declaration): let r_fold_a=Arc::new(QueueBehindJob{ id:10,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_fold_b=Arc::new(QueueBehindJob{ id:11,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1297,24 +1354,25 @@ def item(declaration): #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); - let mk=|id:u32|Arc::new(QueueBehindJob{ + let mk=|id:u32,heavy:bool|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(RenderCommand{heavy_ta:heavy})], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); - let r_live=mk(1); - let next_r=mk(2); + let r_live=mk(1,false); + let next_light=mk(2,false); + let next_heavy=mk(3,true); let mut r_ta=[0u32;16]; - for i in 0..4 { + for i in 0..8 { r_ta[i]=(i as u32 + 1)*0x100; } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:4,ta_target:0x400,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:4,computes:0,renders:3,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], - r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x400, + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16], + r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1323,21 +1381,32 @@ def item(declaration): // Below TA_WAVE_PASSES (3 < 4): zero WC fw_stamp reads. assert_eq!(p.ta_pending_passes(),3); assert_eq!(p.graph.render.fw_stamp[0].reads.get(),0); - assert!(p.can_queue_behind(&next_r)); - // 4 unfinished TA passes: paces render queue_behind until TA advances. + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); + // 4 unfinished TA passes: heavy render pauses at 4, light render keeps pipelining up to 8. p.engine.flights[0].renders=4; assert_eq!(p.ta_pending_passes(),4); assert!(p.graph.render.fw_stamp[0].reads.get()>0); - assert!(!p.can_queue_behind(&next_r)); - // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 3. + assert!(!p.can_queue_behind(&next_heavy)); + assert!(p.can_queue_behind(&next_light)); + // Heavy active flight also enforces conservative cap 4 on light followers. + p.engine.flights[0].heavy_render=true; + assert!(!p.can_queue_behind(&next_light)); + p.engine.flights[0].heavy_render=false; + // 8 unfinished light TA passes pauses light renders until TA advances. + p.engine.flights[0].renders=8; + assert_eq!(p.ta_pending_passes(),8); + assert!(!p.can_queue_behind(&next_light)); + // Once pass 0 finishes TA (obs=0x100) while FS is still running, ta_pending drops to 7. p.graph.render.fw_stamp[0].val.set(0x100); - assert_eq!(p.ta_pending_passes(),3); - assert!(p.can_queue_behind(&next_r)); - // Even with 16 active FS passes, finished TA (obs=0x400) leaves single-pass pipelining unthrottled. - p.graph.render.fw_stamp[0].val.set(0x400); + assert_eq!(p.ta_pending_passes(),7); + assert!(p.can_queue_behind(&next_light)); + // Even with 16 active FS passes, finished TA (obs=0x800) leaves single-pass pipelining unthrottled. + p.graph.render.fw_stamp[0].val.set(0x800); p.engine.flights[0].renders=16; assert_eq!(p.ta_pending_passes(),0); - assert!(p.can_queue_behind(&next_r)); + assert!(p.can_queue_behind(&next_light)); + assert!(p.can_queue_behind(&next_heavy)); } #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); @@ -1346,7 +1415,7 @@ def item(declaration): let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ 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,rt:false})}], + commands:vec![if render{Command::Render(R_LIGHT)}else{Command::Compute(ComputeCommand{query_access,rt:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); @@ -1358,7 +1427,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1707,7 +1776,7 @@ def item(declaration): // Empty engine uses next_compute_pipe (0). assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); host.engine.flights.push(QueueBehindFlight{ - job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); @@ -1726,7 +1795,7 @@ def item(declaration): // q1 stays affine to pipe 0, q2 stays affine to pipe 1, and a third queue q3 // tie-breaks by next_compute_pipe. host.engine.flights.push(QueueBehindFlight{ - job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,target:0x100, + job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); @@ -1758,12 +1827,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,target:0x200, + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,target:0x200, cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1813,7 +1882,7 @@ def item(declaration): let r1=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(())], + commands:vec![Command::Render(R_LIGHT)], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1837,12 +1906,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,target:0, + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -2516,7 +2585,7 @@ def item(declaration): } } mod busy_coalesce_scope { - use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Progress, Queue, Recovery, Result, Status, Vm}; + use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; mod params { pub fn compute_flights() -> usize { 23 } pub fn render_flights() -> usize { 47 } @@ -2568,6 +2637,7 @@ def item(declaration): doomed: bool, recovery_suspect: bool, initbm: bool, + heavy_render: bool, } struct Engine { flights: Vec, @@ -2593,15 +2663,16 @@ def item(declaration): fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool) -> usize { 0 } fn ta_pending_passes(&self) -> usize { self.ta_pending } + __TA_WAVE_CAP_FOR__ __CAN_DEFER_BUSY_COALESCE__ __DEFER_BUSY_COALESCE__ } - fn mk_job(vm: &Arc, q: &Arc, render: bool, seq: u64, wait: [Option; 2]) -> Arc { + fn mk_job_mode(vm: &Arc, q: &Arc, render: bool, heavy: bool, seq: u64, wait: [Option; 2]) -> Arc { Arc::new(Job { vm: vm.clone(), queue: q.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: false, rt: false }) }], + commands: vec![if render { Command::Render(RenderCommand { heavy_ta: heavy }) } else { Command::Compute(ComputeCommand { query_access: false, rt: false }) }], orders: vec![Order { engine: if render { crate::command::RENDER } else { crate::command::COMPUTE }, sequence: seq, wait_through: wait }], fw_waits: vec![], resources: Resources { units: 24, scs: false }, @@ -2609,6 +2680,9 @@ def item(declaration): foldable: true, }) } + fn mk_job(vm: &Arc, q: &Arc, render: bool, seq: u64, wait: [Option; 2]) -> Arc { + mk_job_mode(vm, q, render, false, seq, wait) + } #[test] fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { let vm1 = Arc::new(Vm { status: Status(AtomicU32::new(0)), slot: 1 }); @@ -2618,7 +2692,7 @@ def item(declaration): let mut h = Host { recovery: Recovery { error: None, publication_wait_deadline: None }, engine: Engine { - flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, doomed: false, recovery_suspect: false, initbm: false }], + flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }], pending: vec![mk_job(&vm1, &q1, false, 2, [None, None])], frozen: false, chan_wait: false, @@ -2663,14 +2737,25 @@ def item(declaration): h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, Some(2)])]; assert_eq!(h.defer_busy_coalesce(400_000), None); - // Render with queue_active == 2 and ta_pending == 2 (ta_room == 2) holds 1 pass and flushes at 2. + // Light render with queue_active == 2 and ta_pending == 2 (wave_cap 8 -> ta_room 6) + // coalesces up to K=6 passes before flushing. let r1 = mk_job(&vm1, &q1, true, 1, [None, None]); - h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, doomed: false, recovery_suspect: false, initbm: false }]; + h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }]; h.ta_pending = 2; h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])]; assert_eq!(h.defer_busy_coalesce(500_000), Some(18)); - h.engine.pending.push(mk_job(&vm1, &q1, true, 4, [Some(3), None])); + for seq in 4..=7 { + h.engine.pending.push(mk_job(&vm1, &q1, true, seq, [Some(seq - 1), None])); + assert_eq!(h.defer_busy_coalesce(502_000), Some(16)); + } + h.engine.pending.push(mk_job(&vm1, &q1, true, 8, [Some(7), None])); assert_eq!(h.defer_busy_coalesce(505_000), None); + + // Heavy render keeps conservative wave_cap 4 (ta_room == 2): holds 1 pass, flushes at 2. + h.engine.pending = vec![mk_job_mode(&vm1, &q1, true, true, 3, [Some(2), None])]; + assert_eq!(h.defer_busy_coalesce(600_000), Some(18)); + h.engine.pending.push(mk_job_mode(&vm1, &q1, true, true, 4, [Some(3), None])); + assert_eq!(h.defer_busy_coalesce(605_000), None); } } ''' @@ -2731,7 +2816,10 @@ def item(declaration): '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', + '__TA_WAVE_CAP_FOR__': 'fn ta_wave_cap_for(', + '__ACTIVE_TA_WAVE_CAP__': 'pub(crate) fn active_ta_wave_cap(', '__CAN_QUEUE_BEHIND__': 'fn can_queue_behind(', + '__CAN_QUEUE_BEHIND_WITH_TA__': 'fn can_queue_behind_with_ta(', '__CAN_DEFER_BUSY_COALESCE__': 'fn can_defer_busy_coalesce(', '__DEFER_BUSY_COALESCE__': 'pub(crate) fn defer_busy_coalesce(', '__WAIT_STAMP_FOR_WITH__': 'fn wait_stamp_for_with(', 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 dd7931881e3f49..5aa9f7afbabfd2 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1299,6 +1299,47 @@ def module(text, name): assert_eq!(render.passes[0].pre[0].fills.lock().unwrap().len(),pre0_before); } + #[test]fn stage_displaced_pass_scrubs_prioritizes_pass_cursor_order(){ + let mut o=Objects::new();let mut s=Slots::new().unwrap(); + let mut passes=KVec::new(); + for k in 0..20 { + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1, &crate::g16::object::test_cmds((k as u64) as u64)).unwrap(), 0).unwrap(); + } + let render=sync::Arc::new(render_arena(passes), 0).unwrap(); + let prep=g16::resources::Prepared{compute:KVec::new(),render:Some(render.clone()),hw_slots:None}; + let a=vm(1); + // Publish and retire slots 0..20 in order so slots 0..19 are displaced dirty and + // slot 19 is the undisplaced newest retired slot. + for k in 0..20 { + let mut c=Claims::new();c.pass[0]=k as u32;c.pass_count=1;c.pass_mask=1u64< Date: Wed, 25 Nov 2026 07:16:10 +1100 Subject: [PATCH 1118/1514] ci: run the kernel release smoke test with newer QEMU The native Ubuntu 24.04 runner's QEMU 8.2.2 timed out before userspace on the exact release Image. Ubuntu 26.04's QEMU 10.2.1 booted that Image and a control initramfs containing the release modules under local TCG. Move the smoke job to Ubuntu 26.04 ARM64. Log emulator version and early console diagnostics. Stop after five minutes without the smoke init marker, leaving the existing overall limit for module loads and KUnit. Keep native package build and publication jobs on their existing runners. Signed-off-by: Ryan Murray --- .github/scripts/kernel-smoke-qemu.sh | 21 ++++++++++++++++++--- .github/workflows/kernel-release.yml | 3 ++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/.github/scripts/kernel-smoke-qemu.sh b/.github/scripts/kernel-smoke-qemu.sh index cba250ec93429d..73659216e7bf4d 100755 --- a/.github/scripts/kernel-smoke-qemu.sh +++ b/.github/scripts/kernel-smoke-qemu.sh @@ -82,11 +82,26 @@ if [ -w /dev/kvm ] && [ "$(uname -m)" = aarch64 ]; then ACCEL=kvm; fi CPU=max; [ $ACCEL = kvm ] && CPU=host echo "qemu: accel=$ACCEL kernel=$KREL" set +e -timeout "$QEMU_TIMEOUT" qemu-system-aarch64 -M virt -accel $ACCEL -cpu $CPU -smp 4 -m 6G \ +: > "$OUT/console.log" +timeout -k 10 "$QEMU_TIMEOUT" qemu-system-aarch64 -M virt -accel "$ACCEL" -cpu "$CPU" -smp 4 -m 6G \ -nographic -no-reboot -nic none -kernel "$IMG" -initrd "$OUT/initramfs.cpio.zst" \ - -append "console=ttyAMA0 rdinit=/init panic=-1 loglevel=1 log_buf_len=128M kunit.enable=1" \ - > "$OUT/console.log" 2>&1 + -append "console=ttyAMA0 earlycon=pl011,0x09000000 rdinit=/init panic=-1 loglevel=4 log_buf_len=128M kunit.enable=1" \ + >> "$OUT/console.log" 2>&1 & +QEMU_PID=$! +trap 'kill -TERM "$QEMU_PID" 2>/dev/null || true' EXIT + +BOOT_DEADLINE=$((SECONDS + 300)) +while kill -0 "$QEMU_PID" 2>/dev/null && ! grep -q '^SMOKE-BEGIN ' "$OUT/console.log"; do + if (( SECONDS >= BOOT_DEADLINE )); then + echo "qemu: smoke init did not start within 300 seconds" + kill -TERM "$QEMU_PID" 2>/dev/null + break + fi + sleep 2 +done +wait "$QEMU_PID" QRC=$? +trap - EXIT set -e echo "qemu exit $QRC" diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index a2d6f8d0d1a194..45b684c6eb60c5 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -225,7 +225,7 @@ jobs: smoke: needs: [plan, build] - runs-on: ubuntu-24.04-arm + runs-on: ubuntu-26.04-arm timeout-minutes: 180 steps: - uses: actions/checkout@v4 @@ -244,6 +244,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y --no-install-recommends qemu-system-arm busybox-static zstd cpio + qemu-system-aarch64 --version - name: Boot under QEMU and load every module run: | From 8495c00ab9a0dbe1178bf51640783733421b1f27 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 15:02:55 -0500 Subject: [PATCH 1119/1514] drm/asahi: g16: make compute pipe affinity and busy coalesce adaptive Unconditional single-queue 1-pipe compute affinity helped light compute streams fold onto one CDM workqueue, but serialized heavy compute streams (bandwidth/fill/overlap passes >= 200 us per command) onto a single CDM pipe and left multi-queue overlap workloads susceptible to the 18 us busy-coalesce window when another queue already had an active flight. Track a lock-free per-queue EWMA of retired hardware CDM GPU execution duration in microseconds (from the existing single- and multi-command timestamp reads in stat_retire, without extra WC reads) and add a cold-start probe for a sole single-command compute flight exceeding 180 us before its first retirement: - Light single-queue compute (< 200 us) keeps 1-pipe affinity, unbounded same-pipe horizon folding, and busy coalescing. - Heavy compute (>= 200 us EWMA or sole inflight >= 180 us) bypasses busy coalescing, fans out across both CDM pipes, and caps barrier-free folding to keep both pipes balanced. - Busy coalescing also bypasses immediately whenever any active flight belongs to a different queue so multi-queue render and async compute/render overlap see zero micro-coalesce delay. Extend the publication host selftests to cover adaptive heavy detection, EWMA transitions, pipe balancing, and cross-queue/heavy busy-coalesce bypasses. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 90 ++++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 6 + drivers/gpu/drm/asahi/g16/poll.rs | 17 +++ drivers/gpu/drm/asahi/g16/queue.rs | 18 +++ .../drivers/gpu/asahi-m4/test-publication.py | 141 +++++++++++------- 5 files changed, 200 insertions(+), 72 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index ad418b5b78c1ee..30960124b5cfb1 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1619,7 +1619,7 @@ impl Firmware { /// Whether `self.engine.pending` is an eligible single-queue, single-VM busy horizon /// batch that can accumulate more same-queue commands before publishing. - fn can_defer_busy_coalesce(&self) -> bool { + fn can_defer_busy_coalesce(&self, now: u64) -> bool { if self.recovery.failed().is_some() || self.engine.frozen || self.engine.flights.is_empty() @@ -1641,6 +1641,11 @@ impl Firmware { if head.vm.status.get() != 0 || head.long() || !self.can_queue_behind(head) + || self + .engine + .flights + .iter() + .any(|fl| !Arc::ptr_eq(&fl.job.queue, &head.queue)) || self .engine .pending @@ -1658,6 +1663,7 @@ impl Firmware { || c.is_rt() || head_order.wait_through != [None, None] || !head.fw_waits.is_empty() + || self.compute_queue_is_heavy(&head.queue, now) { return false; } @@ -1714,7 +1720,8 @@ impl Firmware { let Ok(slot_mask) = head.resources.compute_slot_mask() else { return false; }; - let pipe = self.choose_compute_pipe(&head.queue, [None, None], slot_mask, false); + let pipe = + self.choose_compute_pipe(&head.queue, [None, None], slot_mask, false, false); let free_c = self.slots.free_compute_in_mask_for_pipe(slot_mask, pipe) as usize; let cap = super::hw::sizes::COALESCE_MAX_CMDS .min(free_c) @@ -1797,7 +1804,7 @@ impl Firmware { /// producer updates, and doorbells without delaying `d=1`/`d=2`, barriered streams, RT/SCS /// work, or multi-queue/cross-VM handoffs. pub(crate) fn defer_busy_coalesce(&mut self, now: u64) -> Option { - if !self.can_defer_busy_coalesce() { + if !self.can_defer_busy_coalesce(now) { self.engine.coalesce_deadline_ns = 0; return None; } @@ -2081,23 +2088,54 @@ impl Firmware { Ok(waits) } + /// Whether `queue`'s recent or active compute work is heavy enough to benefit from 2-pipe + /// CDM fanout rather than 1-pipe affinity and horizon folding: + /// - per-queue retired CDM GPU duration EWMA `>= COMPUTE_HEAVY_EMA_US`, or + /// - a sole active single-command compute flight of `queue` on its pipe has already been + /// executing for `>= COMPUTE_HEAVY_INFLIGHT_NS` without completing (instant detection + /// before retirement updates the EWMA, while queued multi-flight light bursts never false- + /// trigger from queueing age). + fn compute_queue_is_heavy(&self, queue: &Arc, now: u64) -> bool { + if queue.compute_ewma_us.load(Ordering::Relaxed) >= super::hw::sizes::COMPUTE_HEAVY_EMA_US { + return true; + } + let mut pipe_flights = [0usize; super::hw::sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + pipe_flights[p] += 1; + } + } + self.engine.flights.iter().any(|fl| { + let p = (fl.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + fl.computes == 1 + && pipe_flights[p] == 1 + && Arc::ptr_eq(&fl.job.queue, queue) + && fl.published_ns != 0 + && now.saturating_sub(fl.published_ns) + >= super::hw::sizes::COMPUTE_HEAVY_INFLIGHT_NS + }) + } + /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: /// - Base-only/SCS VMs (bits strictly in `0..PIPE1_COMPUTE_START`) or states where pipe 1 /// has no available unit in `slot_mask` stay on pipe 0 so `0..PIPE1_COMPUTE_START` never /// split across two pipes. /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` /// barrier). - /// - If barrier-free (`[None, None]`) and `queue` already has an active compute flight on a - /// single pipe with free units, keep that queue pipe-affine so consecutive horizon submits - /// fold onto one workqueue without splitting across pipes. - /// - Otherwise (other queues, cross-VM compute, or waiting on both pipes `[Some, Some]`), - /// pick the pipe with fewer active compute commands, breaking ties by `next_compute_pipe`. + /// - If barrier-free (`[None, None]`), `!heavy_compute`, and `queue` already has an active + /// compute flight on a single pipe with free units, keep that light queue pipe-affine so + /// consecutive horizon submits fold onto one workqueue without splitting across pipes. + /// - Otherwise (heavy compute streams, other queues, cross-VM compute, or waiting on both + /// pipes `[Some, Some]`), pick the pipe with fewer active compute commands, breaking ties + /// by `next_compute_pipe`. fn choose_compute_pipe( &self, queue: &Arc, waits: [Option; sizes::COMPUTE_PIPES], slot_mask: u32, rt_compute: bool, + heavy_compute: bool, ) -> usize { if rt_compute || self @@ -2112,7 +2150,7 @@ impl Firmware { match waits { [Some(_), None] => return 0, [None, Some(_)] => return 1, - [None, None] => { + [None, None] if !heavy_compute => { let mut q_pipe: Option = None; for fl in &self.engine.flights { if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { @@ -2133,7 +2171,7 @@ impl Firmware { } } } - [Some(_), Some(_)] => {} + [None, None] | [Some(_), Some(_)] => {} } if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { return 1; @@ -2366,8 +2404,8 @@ impl Firmware { } else { &[Channel::Compute] }; - let (compute_pipe, c_waits) = if render { - (0usize, [None; sizes::COMPUTE_PIPES]) + let (compute_pipe, c_waits, heavy_compute) = if render { + (0usize, [None; sizes::COMPUTE_PIPES], false) } else { let slot_mask = job.resources.compute_slot_mask()?; let rt_compute = job.resources.compute_scs() @@ -2377,9 +2415,11 @@ impl Firmware { job.command_order(index) .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; + let heavy = self.compute_queue_is_heavy(&job.queue, now_ns()); ( - self.choose_compute_pipe(&job.queue, waits, slot_mask, rt_compute), + self.choose_compute_pipe(&job.queue, waits, slot_mask, rt_compute, heavy), waits, + heavy, ) }; let pipe_behind = !render @@ -2490,18 +2530,28 @@ impl Firmware { .slots .free_compute_in_mask_for_pipe(slot_mask, compute_pipe) as usize; - let active_computes: usize = self - .engine - .flights - .iter() - .map(|fl| fl.computes as usize) - .sum(); + let mut active_pipe = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + active_pipe[p] += fl.computes as usize; + } + } + let active_computes = active_pipe[0] + active_pipe[1]; + // Keep heavy barrier-free compute balanced across both CDM pipes while light + // single-queue compute streams stay pipe-affine and fold freely into one batch. + let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES] { + active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1) + } else { + usize::MAX + }; let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; let ring_more = (sizes::QUEUE_CAP.saturating_sub(4)).saturating_sub(used) as usize; let mut more_slots = free_c .min(params::compute_flights().saturating_sub(active_computes + 1)) .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) - .min(ring_more); + .min(ring_more) + .min(pipe_fold_cap); let rt_head = job.resources.compute_scs() || c.is_rt(); // Fold trailing barrier-free compute commands of the base job first. while !rt_head && more_slots > 0 && end < job.progress.count() { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index e7c8e8f6e6b9d5..3d9cf3793dc032 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -908,6 +908,12 @@ pub(crate) mod sizes { pub(crate) const COALESCE_MAX_CMDS: usize = 6; pub(crate) const COALESCE_WINDOW_US: u32 = 18; pub(crate) const COALESCE_WINDOW_NS: u64 = (COALESCE_WINDOW_US as u64) * 1000; + /// Per-queue retired CDM execution EWMA threshold (microseconds) at or above which + /// barrier-free compute fans out across both CDM pipes instead of staying 1-pipe affine. + pub(crate) const COMPUTE_HEAVY_EMA_US: u32 = 200; + /// Elapsed wall-clock time (nanoseconds) on a sole active single-command compute flight + /// that immediately classifies the queue as heavy before its first retirement updates EWMA. + pub(crate) const COMPUTE_HEAVY_INFLIGHT_NS: u64 = 180_000; /// Jobs admitted to the engine per logical queue: enough to keep deep queues (`d=64`) /// queued back to back without scheduler backpressure stalls; exact prior-command /// dependencies still gate each one. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index bce03532986548..e11cfd22168f25 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1868,6 +1868,8 @@ impl Firmware { }; let (mut lo, mut hi) = (u64::MAX, 0u64); let (mut first, mut last) = (u64::MAX, 0u64); + let mut cdm_flight_ticks = 0u64; + let mut cdm_counted = 0u32; let work_ticks = self.init.abi.compute().work_ticks; let s = &mut self.engine.stats; @@ -1904,6 +1906,10 @@ impl Firmware { &mut s.cdm_ticks, crate::usage::Engine::Compute, ); + if ticks[1] >= ticks[0] { + cdm_flight_ticks = ticks[1] - ticks[0]; + cdm_counted = 1; + } } else { // Multi-command prefix fallback: read each member's internal timestamp cells. let mut stage = |o: &super::object::FwObject, @@ -1942,9 +1948,20 @@ impl Firmware { }; if let Ok((start, end)) = Self::compute_ticks_with(work_ticks, c) { add_interval(start, end, &mut s.cdm_ticks, crate::usage::Engine::Compute); + if start != 0 && end >= start { + cdm_flight_ticks = cdm_flight_ticks.saturating_add(end - start); + cdm_counted += 1; + } } } } + if cdm_counted != 0 { + let per_cmd_ticks = cdm_flight_ticks / u64::from(cdm_counted); + let per_cmd_us = (per_cmd_ticks.saturating_mul(1_000_000) + / super::hw::COMMAND_TIMESTAMP_HZ) + .clamp(1, 100_000) as u32; + f.job.queue.note_compute_us(per_cmd_us); + } if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 319232fd46334e..28332f8de5e740 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -76,6 +76,9 @@ pub(crate) struct QueueState { /// engine when a job arrives. pub(crate) owned: [AtomicU32; 32], pub(crate) owned_index: AtomicU32, + /// EWMA of retired per-command CDM GPU execution duration (microseconds) for adaptive + /// 1-pipe affinity vs 2-pipe heavy compute fanout. + pub(crate) compute_ewma_us: AtomicU32, } impl QueueState { @@ -124,6 +127,20 @@ impl QueueState { let shift = seq.wrapping_sub(completed).wrapping_sub(2); shift < 64 && (self.compute_ooo.load(Ordering::Acquire) & (1u64 << shift)) != 0 } + + /// Updates the lock-free EWMA of recent retired per-command CDM GPU execution duration + /// (microseconds) for this queue using a symmetric 50% step so transitions between light + /// and heavy compute streams adapt within 2-3 completions. + pub(crate) fn note_compute_us(&self, us: u32) { + let us = us.clamp(1, 100_000); + let prev = self.compute_ewma_us.load(Ordering::Relaxed); + let next = if prev == 0 { + us + } else { + prev.saturating_add(us) / 2 + }; + self.compute_ewma_us.store(next, Ordering::Relaxed); + } } /// One per-file logical-queue credit, released after the queue scheduler drains. @@ -212,6 +229,7 @@ impl Queue { published: [const { AtomicU64::new(0) }; 2], owned: [const { AtomicU32::new(0) }; 32], owned_index: AtomicU32::new(0), + compute_ewma_us: AtomicU32::new(0), }, GFP_KERNEL, )?; 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 9552965a752093..ad2fac33e3c926 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -80,7 +80,7 @@ def item(declaration): assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source -assert 'pipe_fold_cap' not in source, 'pipe_fold_cap must be removed so single-queue horizons fold cleanly' +assert 'let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES]' in publish_prefix_body_fn, 'pipe_fold_cap must only apply to heavy barrier-free compute' harness = r''' @@ -104,11 +104,12 @@ def item(declaration): #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } 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, completed:[AtomicU64;2], compute_ooo:AtomicU64 } +struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64, compute_ewma_us:AtomicU32 } impl Queue { fn new(turn:u64, priority:u32)->Arc{ - Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0)}) + Arc::new(Self{turn:AtomicU64::new(turn),priority,completed:[AtomicU64::new(0),AtomicU64::new(0)],compute_ooo:AtomicU64::new(0),compute_ewma_us:AtomicU32::new(0)}) } + __NOTE_COMPUTE_US__ fn is_compute_retired(&self, seq:u64)->bool{ let c=self.completed[command::COMPUTE].load(Ordering::Acquire); if seq<=c { return true; } @@ -183,7 +184,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -787,7 +788,7 @@ def item(declaration): struct QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp;2]} struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} -struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} +struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,published_ns:u64,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool} impl QueueBehindSlots{ @@ -857,6 +858,7 @@ def item(declaration): __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ __WAIT_COMPUTE_STAMPS_FOR__ + __COMPUTE_QUEUE_IS_HEAVY__ __CHOOSE_COMPUTE_PIPE__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_render(){ @@ -875,7 +877,7 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -917,7 +919,7 @@ def item(declaration): order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); - let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; + let flight=|job:Arc,rt_compute:bool,compute_pipe:u8|QueueBehindFlight{job,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe,rt_compute,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}; let rq=mk(1,vm1.clone(),q1.clone(),true); let rq_next=mk(2,vm1.clone(),q1.clone(),true); let rq_post=mk(3,vm1.clone(),q1.clone(),false); @@ -975,7 +977,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -993,7 +995,7 @@ def item(declaration): }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -1017,7 +1019,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -1061,7 +1063,7 @@ def item(declaration): let vm2_r=mk(3,vm2.clone(),q2.clone(),true); let vm2_c=mk(4,vm2.clone(),q2.clone(),false); let mk_flight=|job:Arc,c:u32,r:u32|QueueBehindFlight{ - job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false,heavy_render:false, + job,group:vec![],first:0,count:1,computes:c,renders:r,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0, target:if c!=0{0x100}else{0},cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, fs_target:if r!=0{0x200}else{0},initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; @@ -1106,8 +1108,8 @@ def item(declaration): let p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, - QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1143,7 +1145,7 @@ def item(declaration): let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ - QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, + QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, @@ -1176,7 +1178,7 @@ def item(declaration): let host=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0, + job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1222,7 +1224,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1233,7 +1235,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&r_job,0,command::COMPUTE),Ok(None)); // Symmetrically, Queue 0 compute queues directly behind Queue 1 render on the same VM. p.engine.flights[0]=QueueBehindFlight{ - job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + job:r_job,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert!(p.can_queue_behind(&c_job)); @@ -1260,7 +1262,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1300,7 +1302,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, + job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, @@ -1315,7 +1317,7 @@ def item(declaration): let mut cur_fs=[0u32;16]; cur_fs[0]=0x400; let cur=QueueBehindFlight{ - job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, + job:next_r.clone(),group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:cur_fs,fs_target:0x400, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&next_r,command::RENDER,Some(4),Some(&cur)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1337,7 +1339,7 @@ def item(declaration): let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; let cur_grp=QueueBehindFlight{ - job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, + job:next_r.clone(),group:vec![r_fold_a.clone(),r_fold_b.clone()],first:0,count:1,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:grp_fs,fs_target:0x600, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }; assert_eq!(p.wait_stamp_for_with(&r_fold_b,command::RENDER,Some(4),Some(&cur_grp)),Ok(Some(WaitTarget{stamp:0x400,initbm:false}))); @@ -1371,7 +1373,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1427,7 +1429,7 @@ def item(declaration): let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ - job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0,cstamp:[0;16], + job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }]}, @@ -1774,37 +1776,54 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Empty engine uses next_compute_pipe (0). - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); host.engine.flights.push(QueueBehindFlight{ - job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - // Single-queue barrier-free compute stays affine to its active pipe (pipe 0), - // while a second independent queue balances onto idle pipe 1. - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false), 1); - // RT/SCS compute stays pinned to pipe 0 even for another queue while pipe 0 is active. - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, true), 0); - // A 2-unit base-only or SCS VM (bits < PIPE1_COMPUTE_START) stays pinned to pipe 0 - // even for another queue while pipe 0 is active. - assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b11, false), 0); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b110, false), 0); + // Cold-start heavy probe: sole single-command compute flight becomes heavy at >= 180 us. + assert!(!host.compute_queue_is_heavy(&q1, 1_179_999)); + assert!(host.compute_queue_is_heavy(&q1, 1_180_000)); + // Folded multi-command light flight does not trigger the cold-start probe. + host.engine.flights[0].computes = 3; + assert!(!host.compute_queue_is_heavy(&q1, 2_000_000)); + host.engine.flights[0].computes = 1; + // Per-queue retired hardware CDM EWMA transitions cleanly at 200 us. + q1.note_compute_us(30); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(500); + assert!(host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.note_compute_us(20); + assert!(!host.compute_queue_is_heavy(&q1, 1_050_000)); + q1.compute_ewma_us.store(0, Ordering::Relaxed); + // Light single-queue barrier-free compute stays affine to its active pipe (pipe 0), + // while heavy single-queue compute and a second independent queue balance onto idle pipe 1. + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); + // RT/SCS compute stays pinned to pipe 0 even for another queue or heavy compute. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, true, true), 0); + // A 2-unit base-only or SCS VM (bits < PIPE1_COMPUTE_START) stays pinned to pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b11, false, true), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b110, false, true), 0); assert!(host.can_queue_behind(&c2)); // Add second concurrent flight on pipe 1 from q2: both pipes active, // q1 stays affine to pipe 0, q2 stays affine to pipe 1, and a third queue q3 // tie-breaks by next_compute_pipe. host.engine.flights.push(QueueBehindFlight{ - job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,target:0x100, + job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false), 0); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false), 1); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false), 1); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 1); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); assert!(host.can_queue_behind(&c_vm2)); // Same-VM compute still pipelines without draining. assert!(host.can_queue_behind(&c2)); @@ -1827,12 +1846,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,target:0x200, + job:c2,group:vec![],first:0,count:1,computes:2,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:0,target:0x200, cstamp:{let mut a=[0;16];a[0]=0x200;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1845,13 +1864,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(&q1, w1, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w1, (1u32 << 24) - 1, false, true), 0); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(&q1, w2, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2, (1u32 << 24) - 1, false, false), 0); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1862,7 +1881,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(&q1, w2_ooo, (1u32 << 24) - 1, false), 0); + assert_eq!(host.choose_compute_pipe(&q1, w2_ooo, (1u32 << 24) - 1, false, true), 0); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -1906,12 +1925,12 @@ def item(declaration): graph:QueueBehindGraph::new(), engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ QueueBehindFlight{ - job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,target:0x100, + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, }, QueueBehindFlight{ - job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,target:0, + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }, @@ -1922,7 +1941,7 @@ def item(declaration): // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(&q2,cw,(1u32<<24)-1,false),0); + assert_eq!(host.choose_compute_pipe(&q2,cw,(1u32<<24)-1,false,false),0); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2585,7 +2604,7 @@ def item(declaration): } } mod busy_coalesce_scope { - use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; + use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Ordering, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; mod params { pub fn compute_flights() -> usize { 23 } pub fn render_flights() -> usize { 47 } @@ -2634,6 +2653,8 @@ def item(declaration): job: Arc, computes: u32, renders: u32, + compute_pipe: u8, + published_ns: u64, doomed: bool, recovery_suspect: bool, initbm: bool, @@ -2661,8 +2682,9 @@ def item(declaration): } impl Host { fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } - fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool) -> usize { 0 } + fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool, _heavy: bool) -> usize { 0 } fn ta_pending_passes(&self) -> usize { self.ta_pending } + __COMPUTE_QUEUE_IS_HEAVY__ __TA_WAVE_CAP_FOR__ __CAN_DEFER_BUSY_COALESCE__ __DEFER_BUSY_COALESCE__ @@ -2692,7 +2714,7 @@ def item(declaration): let mut h = Host { recovery: Recovery { error: None, publication_wait_deadline: None }, engine: Engine { - flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }], + flights: vec![Flight { job: c1.clone(), computes: 1, renders: 0, compute_pipe: 0, published_ns: 90_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }], pending: vec![mk_job(&vm1, &q1, false, 2, [None, None])], frozen: false, chan_wait: false, @@ -2737,10 +2759,23 @@ def item(declaration): h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, Some(2)])]; assert_eq!(h.defer_busy_coalesce(400_000), None); + // Heavy compute queue (EWMA >= 200 us) bypasses busy coalescing so 2-pipe fanout runs immediately. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + q1.note_compute_us(500); + assert_eq!(h.defer_busy_coalesce(420_000), None); + q1.compute_ewma_us.store(25, Ordering::Relaxed); + assert_eq!(h.defer_busy_coalesce(420_000), Some(18)); + + // Active flight from another queue bypasses busy coalescing immediately (multi-queue/async_cr). + let r_other = mk_job(&vm1, &q2, true, 1, [None, None]); + h.engine.flights.push(Flight { job: r_other, computes: 0, renders: 1, compute_pipe: 0, published_ns: 410_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }); + assert_eq!(h.defer_busy_coalesce(425_000), None); + h.engine.flights.pop(); + // Light render with queue_active == 2 and ta_pending == 2 (wave_cap 8 -> ta_room 6) // coalesces up to K=6 passes before flushing. let r1 = mk_job(&vm1, &q1, true, 1, [None, None]); - h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }]; + h.engine.flights = vec![Flight { job: r1, computes: 0, renders: 2, compute_pipe: 0, published_ns: 490_000, doomed: false, recovery_suspect: false, initbm: false, heavy_render: false }]; h.ta_pending = 2; h.engine.pending = vec![mk_job(&vm1, &q1, true, 3, [Some(2), None])]; assert_eq!(h.defer_busy_coalesce(500_000), Some(18)); @@ -2768,6 +2803,7 @@ def item(declaration): harness = harness.replace('__QUEUE_CREDIT_STRUCT__', item_in(queue_src, 'struct QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_IMPL__', item_in(queue_src, 'impl QueueCredit {')) harness = harness.replace('__QUEUE_CREDIT_DROP__', item_in(queue_src, 'impl Drop for QueueCredit {')) +harness = harness.replace('__NOTE_COMPUTE_US__', item_in(queue_src, 'pub(crate) fn note_compute_us(')) harness = harness.replace( '__CAN_FOLD_CMD__', item_in(job_src, 'pub(crate) fn can_fold_horizon_cmd(') @@ -2826,6 +2862,7 @@ def item(declaration): '__WAIT_STAMP_FOR__': 'fn wait_stamp_for(', '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', + '__COMPUTE_QUEUE_IS_HEAVY__': 'fn compute_queue_is_heavy(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', '__WAIT_TARGET__': 'struct WaitTarget {', From cb390f549d1ec8fbc9f9e96ac670156502bf8504 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 07:00:50 -0500 Subject: [PATCH 1120/1514] drm/asahi: g16: repoll soon when SUBMIT leaves a paced job waiting publish_checked() marks a ready job that it could not publish for want of TA wave headroom (ta_wave_wait) or pass and flight headroom (slot_wait). A poll pass that sees either flag repolls after repoll_us (8 us by default), so the job publishes as soon as TA progress or a retirement makes room. A SUBMIT that publishes inline and leaves the same state behind did not do this. It rearmed the poll timer with rearm_us(false), which is half the flight duration EWMA clamped to resnap_us, so 100 us for renders longer than 200 us. Unless a stage event arrived first, the job waited that long after the room appeared. This is the case for the later passes of a multi-pass render that does not fit in one TA wave. Treat the two flags in submit_locked() as poll_step() does: rearm soon when the engine is not frozen and a job is still pending. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/poll.rs | 8 +++- .../drivers/gpu/asahi-m4/test-poll-retire.py | 44 ++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e11cfd22168f25..4b81ad843cc24e 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -316,13 +316,19 @@ impl Shared { if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { // If an EP 0x20 event retired an older flight while later flights remain active, // or arrived before the oldest receipt became visible, arm a short repoll so - // trailing completions never fall back to `resnap_us`. + // trailing completions never fall back to `resnap_us`. A ready job this + // publication left waiting on TA wave or slot headroom repolls as soon as + // `poll_step()` would rearm it, not a full `resnap_us` later. if let Some(us) = coalesce_us { self.rearm_after(us.min(self.rearm_us(false))); } else { + let paced = !firmware.engine.frozen + && !firmware.engine.pending.is_empty() + && (firmware.engine.slot_wait || firmware.engine.ta_wave_wait); self.rearm( firmware.engine.chan_wait || restored_event + || paced || (was_evented && retired_any && !firmware.engine.flights.is_empty()), ); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index df5d84c420362f..0281cadec9efa9 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -327,6 +327,7 @@ def item(declaration, text=source): ta_pending: usize, ta_wave_cap: usize, coalesce_us: Option, + publish_waits: Option<(bool, bool)>, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, @@ -383,6 +384,7 @@ def item(declaration, text=source): ta_pending: 0, ta_wave_cap: hw::sizes::TA_WAVE_PASSES, coalesce_us: None, + publish_waits: None, retire_calls: 0, publish_full_calls: 0, publish_checked_calls: 0, @@ -445,6 +447,10 @@ def item(declaration, text=source): } fn publish_checked(&mut self, _done: &mut Completions) -> Result { self.engine.coalesce_deadline_ns = 0; + if let Some((slot_wait, ta_wave_wait)) = self.publish_waits { + self.engine.slot_wait = slot_wait; + self.engine.ta_wave_wait = ta_wave_wait; + } self.publish_checked_calls += 1; Ok(()) } @@ -1055,6 +1061,42 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn submit_locked_repolls_soon_when_its_publication_leaves_a_paced_job() { + // publish_checked() leaves a ready job on TA wave or slot headroom: SUBMIT arms the same + // short repoll poll_step() arms for it, unless the engine is frozen. + CLOCK.with(|c| c.set(100_000)); + for (slot_wait, ta_wave_wait, frozen, soon) in [ + (false, false, false, 0), + (true, false, false, 1), + (false, true, false, 1), + (false, true, true, 0), + ] { + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 100_000; + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + fw.engine.frozen = frozen; + fw.publish_waits = Some((slot_wait, ta_wave_wait)); + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 0); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(shared.rearmed.get(), 1); + assert_eq!(shared.rearm_soon.get(), soon); + assert_eq!(shared.poll_now_calls.get(), 0); + } +} + #[test] fn submit_locked_and_poll_step_micro_coalesce_busy_horizons() { CLOCK.with(|c| c.set(100_000)); @@ -1707,7 +1749,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 22, + 'tests': 23, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', From e94ea5c88400cfe38dca6fca4ce505900cd33ad3 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 07:07:58 -0500 Subject: [PATCH 1121/1514] drm/asahi: g16: keep idle poll passes on the housekeeping cadence poll_step() ran the full idle housekeeping on every pass that started with nothing in flight: Session::check() (an ASC control read, a powered SGX pstate read and a walk of the adopted UAT bindings), Objects::health(), service_power() and a drain of every receive ring, including the nine log sub-rings and ktrace. A pass with work in flight holds the same checks to their cadence, 5 ms while active. Shallow back-to-back submissions reach the idle state after every completion, and idle_resnap() keeps a short poll timer armed across that gap. The timer pass then repeated all of these checks under the device lock, between one completion and the next SUBMIT, which waits on the same lock. Inside the 1 ms idle cadence, drain only the event and statistics rings, which carry completion and recovery notifications, then check for a pending recovery. A recovery or a receipt fault still runs the full pass at once. The skipped housekeeping is owed: run_poll() queues the backup poll for the end of the cadence, and the owed state clears when any full or periodic housekeeping runs. The backup poll may replace a later idle power poll; that pass calls service_power() and arms the power poll again. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 4 ++ drivers/gpu/drm/asahi/g16/poll.rs | 43 +++++++++++--- .../drivers/gpu/asahi-m4/test-poll-retire.py | 56 ++++++++++++++++++- 3 files changed, 95 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 30960124b5cfb1..c0b4db6535a5ed 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -610,6 +610,9 @@ pub(crate) struct Engine { pub(crate) ta_wave_wait: bool, /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. pub(crate) short_repoll: bool, + /// An idle poll pass inside the housekeeping cadence skipped housekeeping: queue a backup + /// poll so it runs once the cadence elapses. + pub(crate) housekeeping_owed: bool, /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, @@ -657,6 +660,7 @@ impl Engine { slot_wait: false, ta_wave_wait: false, short_repoll: false, + housekeeping_owed: false, coalesce_deadline_ns: 0, progress_flight: [0; 3], progress: [None; 4], diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 4b81ad843cc24e..f22cd3055270a2 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -100,6 +100,18 @@ impl Shared { self.mod_poll(kernel::time::msecs_to_jiffies((delay_ns / 1_000_000) as u32).max(1)); } + /// Queues the backup poll for idle housekeeping that a pass skipped inside its cadence, at + /// the end of that cadence. It may replace a later idle power poll: that pass runs the + /// housekeeping, including `service_power()`, and arms the power poll again. + fn queue_owed_housekeeping(self: &Arc, firmware: &Firmware) { + if !firmware.engine.housekeeping_owed || firmware.recovery.failed().is_some() { + return; + } + let elapsed = now_ns().wrapping_sub(firmware.last_housekeeping_ns); + let ms = HOUSEKEEPING_NS.saturating_sub(elapsed).div_ceil(1_000_000) as u32; + self.mod_poll(kernel::time::msecs_to_jiffies(ms).max(1)); + } + /// One poll pass (the poll work item). pub(crate) fn run_poll(self: Arc) { // The domain may be off. The sleep's end queues a pass. @@ -158,6 +170,7 @@ impl Shared { // floor hold is still pending so both expire cleanly to idle power. Ok(false) => { self.arm_idle_power_poll(firmware); + self.queue_owed_housekeeping(firmware); if firmware.recovery.failed().is_some() { self.cancel_resnap(); } else { @@ -670,14 +683,29 @@ impl Firmware { // 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. + // + // Inside the housekeeping cadence, with no recovery pending, an idle pass drains only + // the event and statistics rings, which carry completion and recovery notifications. + // The session, object, power and auxiliary ring checks then wait for the cadence, so + // back-to-back shallow submissions do not repeat them, under the device lock, between + // one completion and the next SUBMIT. `run_poll()` queues a backup poll for them. if !had_flights { - self.session.check()?; - self.objects.health()?; - self.service_power()?; - self.last_housekeeping_ns = now; - self.last_aux_drain_ns = now; - ran_housekeeping = true; - self.drain_rings()?; + let full = housekeeping_due || self.recovery.receipt_fault || { + self.drain_events_and_stats()?; + self.recovery_pending()? + }; + if full { + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now; + self.last_aux_drain_ns = now; + ran_housekeeping = true; + self.engine.housekeeping_owed = false; + self.drain_rings()?; + } else { + self.engine.housekeeping_owed = true; + } self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { let _ = self.slots.take_scrub_woke(); @@ -817,6 +845,7 @@ impl Firmware { self.last_aux_drain_ns = now; } self.last_housekeeping_ns = now; + self.engine.housekeeping_owed = false; self.reclaim_closed_vm_slots(); if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 0281cadec9efa9..789f95ed290c87 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -163,6 +163,7 @@ def item(declaration, text=source): slot_wait: bool, ta_wave_wait: bool, short_repoll: bool, + housekeeping_owed: bool, coalesce_deadline_ns: u64, frozen: bool, stats: Stats, @@ -334,6 +335,7 @@ def item(declaration, text=source): housekeeping_calls: u32, aux_drain_calls: u32, power_calls: u32, + hot_drain_calls: u32, } impl Firmware { @@ -364,6 +366,7 @@ def item(declaration, text=source): slot_wait: false, ta_wave_wait: false, short_repoll: false, + housekeeping_owed: false, coalesce_deadline_ns: 0, frozen: false, stats: Stats::default(), @@ -391,6 +394,7 @@ def item(declaration, text=source): housekeeping_calls: 0, aux_drain_calls: 0, power_calls: 0, + hot_drain_calls: 0, } } @@ -411,6 +415,10 @@ def item(declaration, text=source): fn drain_rings(&mut self) -> Result { Ok(()) } + fn drain_events_and_stats(&mut self) -> Result { + self.hot_drain_calls += 1; + Ok(()) + } fn drain_auxiliary_rings(&mut self) -> Result { self.aux_drain_calls += 1; Ok(()) @@ -471,6 +479,52 @@ def item(declaration, text=source): __OLDEST_STAMP_REACHED__ } +#[test] +fn idle_poll_step_runs_full_housekeeping_only_on_its_cadence() { + let mut fw = Firmware::new(); + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let mut idle_pass = |fw: &mut Firmware, now: u64| { + CLOCK.with(|c| c.set(now)); + fw.poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap() + }; + // Due: the full idle housekeeping runs and owes nothing. + assert!(!idle_pass(&mut fw, 2_000_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 0)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(!fw.engine.housekeeping_owed); + // Inside the cadence: only the event and statistics rings drain; the rest is owed. + assert!(!idle_pass(&mut fw, 2_300_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 1)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(fw.engine.housekeeping_owed); + // A recovery found by that drain runs the full pass inside the cadence. + fw.recovery.pending = true; + assert!(idle_pass(&mut fw, 2_400_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (2, 2)); + assert_eq!(fw.last_housekeeping_ns, 2_400_000); + assert!(!fw.engine.housekeeping_owed); + fw.recovery.pending = false; + // So does a receipt fault, without a hot drain first. + fw.recovery.receipt_fault = true; + assert!(!idle_pass(&mut fw, 2_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 2)); + fw.recovery.receipt_fault = false; + assert!(!idle_pass(&mut fw, 2_600_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 3)); + assert!(fw.engine.housekeeping_owed); + // Once the cadence elapses the owed housekeeping runs. + assert!(!idle_pass(&mut fw, 3_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (4, 3)); + assert!(!fw.engine.housekeeping_owed); + // Periodic housekeeping also settles what an idle pass owed. + assert!(!idle_pass(&mut fw, 3_600_000)); + assert!(fw.engine.housekeeping_owed); + CLOCK.with(|c| c.set(4_600_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert!(!fw.engine.housekeeping_owed); +} + #[test] fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { CLOCK.with(|c| c.set(1_000_000)); @@ -1749,7 +1803,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 23, + 'tests': 24, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', From acb4513824e834492d87087bf93e4c61f8bc7e1a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 07:29:41 -0500 Subject: [PATCH 1122/1514] drm/asahi: g16: count publication holds by cause hold[0] counts publication passes that stopped at a ready job behind in-flight work, but it lumps together a job that must wait for an empty engine and one that waits for headroom. The two are released by different events, so the counter cannot say which one a stalled multi-pass render is waiting for. Count each such hold once more by its cause, and print the split as a hold_causes line of aurora-g16/stats: - drain_failed: the VM failed, or a flight is doomed or recovery-suspect; - drain_initbm: a cold InitBM render is in flight; - drain_cross: render and compute of different VMs; - drain_pb: no warm PB/UMA allocator slot of the VM can take the render; - ta_wave: the TA wave window is full; - slot: flight, render pass or compute unit headroom; - dependency: the job's dependency check failed; - other: any other refusal behind in-flight work. The cause is evaluated only when a pass holds. The PB pipelining test that needs_engine_drain() and can_queue_behind_with_ta() each spelled out moves to render_can_pipeline(), which the classification uses too. hold[0] keeps its meaning. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 135 ++++++++++++++---- drivers/gpu/drm/asahi/g16/poll.rs | 5 + .../drivers/gpu/asahi-m4/test-publication.py | 58 +++++++- 3 files changed, 168 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index c0b4db6535a5ed..a9457dd64cebaa 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -424,6 +424,45 @@ enum PublicationError { Uncertain(Error), } +/// Why a publication pass stopped at a ready job without publishing it (`Stats::hold_causes`). +/// +/// A drain cause means the job waits for an empty engine; the others wait behind in-flight +/// work for headroom or ordering. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum HoldCause { + /// The job's VM failed, or a flight is doomed or suspect in a recovery. + DrainFailed, + /// A cold `InitBM` render is in flight. + DrainInitbm, + /// Compute and render of different VMs, or an SCS compute conflict. + DrainCross, + /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. + DrainPb, + /// The TA wave window is full. + TaWave, + /// Flight, render pass or compute unit headroom. + Slot, + /// The job's dependency check failed: it fails once it reaches publication. + /// (`Engine::pick()` skips jobs still waiting for a dependency.) + Dependency, + /// Any other admission refusal behind in-flight work. + Other, +} + +impl HoldCause { + pub(crate) const COUNT: usize = 8; + pub(crate) const NAMES: [&'static str; Self::COUNT] = [ + "drain_failed", + "drain_initbm", + "drain_cross", + "drain_pb", + "ta_wave", + "slot", + "dependency", + "other", + ]; +} + /// Engine statistics, printed by `aurora-g16/stats`. #[derive(Default, Zeroable)] pub(crate) struct Stats { @@ -474,6 +513,8 @@ pub(crate) struct Stats { /// Why ready jobs stayed unpublished: both flights published, a channel record unconsumed, /// no free slot. pub(crate) hold: [u64; 3], + /// `hold[0]` split by [`HoldCause`]. + pub(crate) hold_causes: [u64; HoldCause::COUNT], /// Compute commands published behind in-flight ones. pub(crate) behind: u64, /// Most flights in flight at once. @@ -1032,7 +1073,7 @@ impl Firmware { && !self.can_queue_behind_with_ta(&job, &mut ta_pending) { if self.needs_engine_drain(&job) { - self.engine.stats.hold[0] += 1; + self.note_hold(&job, true, 0); break; } let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); @@ -1119,7 +1160,7 @@ impl Firmware { .check_command_dependencies(cand.progress.sent()) .is_ok() }); - self.engine.stats.hold[0] += 1; + self.note_hold(&job, false, ta_val); break; } } @@ -1357,20 +1398,68 @@ impl Firmware { || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) - || (is_render - && !job - .resources - .pb_slot_mask() - .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(mask, home, blocks)| { - self.pools.can_pipeline_in_mask_blocks_mode( - &job.vm, - mask, - home, - blocks, - job.resources.render_scs(), - ) - })) + || (is_render && !self.render_can_pipeline(job)) + } + + /// Whether `job`'s render can reuse a warm PB/UMA allocator slot of its VM behind active + /// flights, without the drain that a fresh `InitBM` epoch needs. + fn render_can_pipeline(&self, job: &Arc) -> bool { + job.resources + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) + }) + } + + /// Why a publication pass stopped at `job`: `drain` when [`Self::needs_engine_drain`] + /// held it, otherwise the first refusal of [`Self::can_queue_behind_with_ta`] that + /// applies, with `ta_pending` from that check. Of the drain causes, a failure, an `InitBM` + /// flight and the PB check are tested directly; what remains of `needs_engine_drain()` is a + /// cross-VM or SCS overlap. + fn hold_cause(&self, job: &Arc, drain: bool, ta_pending: usize) -> HoldCause { + let render = command(job, job.progress.sent()); + if drain { + if job.vm.status.get() != 0 + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect) + { + HoldCause::DrainFailed + } else if self.engine.flights.iter().any(|f| f.initbm) { + HoldCause::DrainInitbm + } else if matches!(render, Some(Command::Render(_))) && !self.render_can_pipeline(job) { + HoldCause::DrainPb + } else { + HoldCause::DrainCross + } + } else if job.check_command_dependencies(job.progress.sent()).is_err() { + HoldCause::Dependency + } else if matches!(render, Some(Command::Render(r)) + if ta_pending >= self.ta_wave_cap_for(r.is_heavy_ta())) + { + HoldCause::TaWave + } else if self.blocked_on_slot_headroom(job) { + HoldCause::Slot + } else { + HoldCause::Other + } + } + + /// Counts a publication pass that stopped at the ready `job` behind in-flight work. + fn note_hold(&mut self, job: &Arc, drain: bool, ta_pending: usize) { + let cause = self.hold_cause(job, drain, ta_pending); + let s = &mut self.engine.stats; + s.hold[0] += 1; + s.hold_causes[cause as usize] += 1; } /// Whether `job` is ready to run without an engine drain but currently blocked solely on @@ -1599,19 +1688,7 @@ impl Firmware { && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() - && job - .resources - .pb_slot_mask() - .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(mask, home, blocks)| { - self.pools.can_pipeline_in_mask_blocks_mode( - &job.vm, - mask, - home, - blocks, - job.resources.render_scs(), - ) - }) + && self.render_can_pipeline(job) && job .resources .render_passes() diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index f22cd3055270a2..81728d7f5c5956 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -2261,6 +2261,11 @@ impl Firmware { s.hold[1], s.hold[2] )?; + write!(f, "hold_causes:")?; + for (name, n) in super::engine::HoldCause::NAMES.iter().zip(s.hold_causes) { + write!(f, " {} {}", name, n)?; + } + writeln!(f)?; } let p = &self.engine.prof; writeln!( 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 ad2fac33e3c926..b1f06cacd4d005 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -133,7 +133,10 @@ 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],grouped:u64} +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +__HOLD_CAUSE__ +__HOLD_CAUSE_IMPL__ +#[derive(Default)]struct Stats{hold:[u64;3],hold_causes:[u64;HoldCause::COUNT],grouped:u64} struct Claims; struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} @@ -230,6 +233,9 @@ def item(declaration): fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ + __HOLD_CAUSE_FN__ + __NOTE_HOLD__ __TA_WAVE_CAP_FOR__ __ACTIVE_TA_WAVE_CAP__ fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ @@ -499,6 +505,50 @@ def item(declaration): assert_eq!(f.publish_checked(&mut done),Ok(())); assert_eq!(f.attempted,[2,3]); } + #[test]fn hold_causes_split_hold0_by_the_gate_that_stopped_publication(){ + let vm1=mk_vm(1); + let vm2=mk_vm(2); + // One held publication pass per case: (in-flight job and kind, its flags, held job, + // host knobs) -> exactly one hold[0] of the expected cause. + let run=|flight:Arc,renders:u32,initbm:bool,doomed:bool,held:Arc, + allow_behind:bool,block_pipeline:Option,block_render:bool,expect:HoldCause|{ + let mut f=firmware(vec![held],vec![]); + let mut fl=Flight::new(flight); + if renders==0{fl.computes=1;}else{fl.renders=renders;} + fl.initbm=initbm; + fl.doomed=doomed; + f.engine.flights.push(fl); + f.allow_behind=allow_behind; + f.pools.block_pipeline_vm=block_pipeline; + f.block_render_behind=block_render; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty(),"{:?}",expect); + assert_eq!(f.engine.stats.hold[0],1,"{:?}",expect); + let mut want=[0u64;HoldCause::COUNT]; + want[expect as usize]=1; + assert_eq!(f.engine.stats.hold_causes,want,"{:?}",expect); + }; + let r=|id:u32,vm:&Arc,dep:Result|job_on_vm(id,vm.clone(),true,0,dep); + // A warm same-VM render whose allocator cannot pipeline waits for an empty engine. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,Some(vm1.slot),false,HoldCause::DrainPb); + // A cold InitBM flight drains first. + run(r(1,&vm1,Ok(())),1,true,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainInitbm); + // Another VM's compute in flight: no cross-VM render/compute overlap. + run(job_on_vm(1,vm2.clone(),false,0,Ok(())),0,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainCross); + // A doomed flight drains first. + run(r(1,&vm1,Ok(())),1,false,true,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainFailed); + // A full light TA wave (8 renders) pauses the next light render. + run(r(1,&vm1,Ok(())),8,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::TaWave); + // Pass, flight or unit headroom. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,None,true,HoldCause::Slot); + // A failed dependency (pick() skips jobs still waiting for one). + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Err(ECANCELED)),false,None,false,HoldCause::Dependency); + // Any other refusal. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other); + assert_eq!(HoldCause::NAMES.len(),HoldCause::COUNT); + assert_eq!(HoldCause::Other as usize,HoldCause::COUNT-1); + } #[test]fn alt_bypass_does_not_starve_cold_cross_vm_initbm_while_warm_overlaps(){ let vm1=mk_vm(1); let vm2=mk_vm(2); @@ -849,6 +899,7 @@ def item(declaration): __SCS_COMPUTE_CONFLICT__ impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ __BLOCKED_ON_SLOT_HEADROOM__ __TA_PENDING_PASSES__ __TA_WAVE_CAP_FOR__ @@ -2848,6 +2899,11 @@ def item(declaration): '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', + '__RENDER_CAN_PIPELINE__': 'fn render_can_pipeline(', + '__HOLD_CAUSE__': 'enum HoldCause {', + '__HOLD_CAUSE_IMPL__': 'impl HoldCause {', + '__HOLD_CAUSE_FN__': 'fn hold_cause(', + '__NOTE_HOLD__': 'fn note_hold(', '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', From 6c6dac64f82aaad25641773819dbc53363f107c1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 07:35:47 -0500 Subject: [PATCH 1123/1514] drm/asahi: g16: repoll soon while a job waits behind its own flights When publish_checked() stops at a ready job, the poll repolls after repoll_us only if it set slot_wait or ta_wave_wait. A job held for any other reason waits for the next retirement poll. That is an EP 0x20 event, or the poll timer: rearm_us(false) is half the flight-duration EWMA clamped to resnap_us, so 100 us for renders longer than 200 us. An event for a stage that is not terminal is also not allowed to spin the receipt tail. A multi-pass render held this way behind its own earlier passes can therefore be published up to resnap_us after the retirement that frees it, with the GPU idle in between. Mark such holds held_wait when every flight belongs to the held job's VM and the cause is not a failure, a cross-VM overlap or a failed dependency. The job's own VM's retirements are then what releases it. held_wait is treated like the two existing flags: poll_step() repolls at repoll_us and keeps stage events eligible for the receipt tail, submit_locked() rearms soon, and busy coalescing does not hold behind it. publish_checked() clears it with them. A hold behind another VM's work keeps the existing cadence, so a long cross-VM drain does not repoll every few microseconds. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 21 +++++- drivers/gpu/drm/asahi/g16/poll.rs | 17 +++-- .../drivers/gpu/asahi-m4/test-poll-retire.py | 65 ++++++++++++++++--- .../drivers/gpu/asahi-m4/test-publication.py | 35 ++++++---- 4 files changed, 112 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index a9457dd64cebaa..e3074d55cabdd4 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -654,6 +654,10 @@ pub(crate) struct Engine { /// An idle poll pass inside the housekeeping cadence skipped housekeeping: queue a backup /// poll so it runs once the cadence elapses. pub(crate) housekeeping_owed: bool, + /// A ready job is held behind flights that all belong to its own VM, for any cause but a + /// failure, a cross-VM overlap or a failed dependency: one of those flights retiring is + /// what releases it, so repoll soon instead of after `resnap_us`. + pub(crate) held_wait: bool, /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, @@ -702,6 +706,7 @@ impl Engine { ta_wave_wait: false, short_repoll: false, housekeeping_owed: false, + held_wait: false, coalesce_deadline_ns: 0, progress_flight: [0; 3], progress: [None; 4], @@ -1051,6 +1056,7 @@ impl Firmware { self.engine.chan_wait = false; self.engine.slot_wait = false; self.engine.ta_wave_wait = false; + self.engine.held_wait = false; self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen @@ -1454,12 +1460,24 @@ impl Firmware { } } - /// Counts a publication pass that stopped at the ready `job` behind in-flight work. + /// Counts a publication pass that stopped at the ready `job` behind in-flight work, and + /// marks it [`Engine::held_wait`] when only its own VM's flights hold it. fn note_hold(&mut self, job: &Arc, drain: bool, ta_pending: usize) { let cause = self.hold_cause(job, drain, ta_pending); let s = &mut self.engine.stats; s.hold[0] += 1; s.hold_causes[cause as usize] += 1; + if !matches!( + cause, + HoldCause::DrainFailed | HoldCause::DrainCross | HoldCause::Dependency + ) && self + .engine + .flights + .iter() + .all(|f| Arc::ptr_eq(&f.job.vm, &job.vm)) + { + self.engine.held_wait = true; + } } /// Whether `job` is ready to run without an engine drain but currently blocked solely on @@ -1709,6 +1727,7 @@ impl Firmware { || self.engine.chan_wait || self.engine.slot_wait || self.engine.ta_wave_wait + || self.engine.held_wait || self .engine .flights diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 81728d7f5c5956..43647519f22025 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -337,7 +337,9 @@ impl Shared { } else { let paced = !firmware.engine.frozen && !firmware.engine.pending.is_empty() - && (firmware.engine.slot_wait || firmware.engine.ta_wave_wait); + && (firmware.engine.slot_wait + || firmware.engine.ta_wave_wait + || firmware.engine.held_wait); self.rearm( firmware.engine.chan_wait || restored_event @@ -777,7 +779,8 @@ impl Firmware { published?; // A TA-only (0x70) EP 0x20 interrupt while FS is still running does not signal flight // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it, - // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`). + // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`) or a + // ready job waits behind its own VM's flights (`held_wait`). let non_terminal_only = !retired_any && term_before.is_some() && self.events.stage_events != stage_before @@ -785,7 +788,8 @@ impl Firmware { && !self.oldest_stamp_reached() && !self.recovery.receipt_fault && !recovery_pending - && !self.engine.ta_wave_wait; + && !self.engine.ta_wave_wait + && !self.engine.held_wait; // 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 tail waits per interrupt. @@ -811,13 +815,16 @@ impl Firmware { } // If a terminal EP 0x20 event arrived with flights outstanding and nothing retired within // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring - // or TA-wave headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. + // or TA-wave headroom, or held behind its own VM's flights, repoll at `repoll_us` + // instead of sleeping `resnap_us`. self.engine.short_repoll = !self.engine.flights.is_empty() && !self.engine.frozen && !non_terminal_only && ((evented && had_flights && !retired_any) || (!self.engine.pending.is_empty() - && (self.engine.slot_wait || self.engine.ta_wave_wait))); + && (self.engine.slot_wait + || self.engine.ta_wave_wait + || self.engine.held_wait))); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 789f95ed290c87..4634f0cc2bd0ea 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -164,6 +164,7 @@ def item(declaration, text=source): ta_wave_wait: bool, short_repoll: bool, housekeeping_owed: bool, + held_wait: bool, coalesce_deadline_ns: u64, frozen: bool, stats: Stats, @@ -328,7 +329,7 @@ def item(declaration, text=source): ta_pending: usize, ta_wave_cap: usize, coalesce_us: Option, - publish_waits: Option<(bool, bool)>, + publish_waits: Option<(bool, bool, bool)>, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, @@ -367,6 +368,7 @@ def item(declaration, text=source): ta_wave_wait: false, short_repoll: false, housekeeping_owed: false, + held_wait: false, coalesce_deadline_ns: 0, frozen: false, stats: Stats::default(), @@ -455,9 +457,10 @@ def item(declaration, text=source): } fn publish_checked(&mut self, _done: &mut Completions) -> Result { self.engine.coalesce_deadline_ns = 0; - if let Some((slot_wait, ta_wave_wait)) = self.publish_waits { + if let Some((slot_wait, ta_wave_wait, held_wait)) = self.publish_waits { self.engine.slot_wait = slot_wait; self.engine.ta_wave_wait = ta_wave_wait; + self.engine.held_wait = held_wait; } self.publish_checked_calls += 1; Ok(()) @@ -1044,6 +1047,49 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn held_wait_spins_stage_events_and_repolls_soon_until_a_retirement() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 2, + target: 0, + fs_target: 0x200, + }); + fw.engine.fs_target = 0x200; + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.drain_stage_delta = 1; + let (mut retry_tail, mut deferred, mut done) = (false, false, vec![]); + // Nothing held: a stage-only event is non-terminal, with no tail spin and no short repoll. + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); + // A ready job held behind its own VM's flights spins the receipt tail on the same event... + fw.engine.held_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(retry_tail); + // ...and a timer pass repolls at repoll_us while the hold lasts, without publishing. + retry_tail = false; + fw.drain_stage_delta = 0; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + assert_eq!(fw.publish_checked_calls, 0); + // The retirement that can release it reaches publish_checked(). + fw.retire_on_call = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 1); +} + #[test] fn ta_only_irq_wakes_ta_wave_wait_with_hysteresis_and_short_repoll() { CLOCK.with(|c| c.set(100_000)); @@ -1120,11 +1166,12 @@ def item(declaration, text=source): // publish_checked() leaves a ready job on TA wave or slot headroom: SUBMIT arms the same // short repoll poll_step() arms for it, unless the engine is frozen. CLOCK.with(|c| c.set(100_000)); - for (slot_wait, ta_wave_wait, frozen, soon) in [ - (false, false, false, 0), - (true, false, false, 1), - (false, true, false, 1), - (false, true, true, 0), + for (slot_wait, ta_wave_wait, held_wait, frozen, soon) in [ + (false, false, false, false, 0), + (true, false, false, false, 1), + (false, true, false, false, 1), + (false, false, true, false, 1), + (false, true, false, true, 0), ] { let shared = Shared::new(); let mut fw = Firmware::new(); @@ -1138,7 +1185,7 @@ def item(declaration, text=source): }); fw.engine.fs_target = 0x100; fw.engine.frozen = frozen; - fw.publish_waits = Some((slot_wait, ta_wave_wait)); + fw.publish_waits = Some((slot_wait, ta_wave_wait, held_wait)); let mut done = vec![]; shared .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) @@ -1803,7 +1850,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 24, + 'tests': 25, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', 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 b1f06cacd4d005..3cc505d49350b4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -141,7 +141,7 @@ def item(declaration): struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,coalesce_deadline_ns:u64} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -316,7 +316,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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,slot_wait:false,ta_wave_wait:false,coalesce_deadline_ns:0}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,held_wait:false,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false, @@ -511,7 +511,8 @@ def item(declaration): // One held publication pass per case: (in-flight job and kind, its flags, held job, // host knobs) -> exactly one hold[0] of the expected cause. let run=|flight:Arc,renders:u32,initbm:bool,doomed:bool,held:Arc, - allow_behind:bool,block_pipeline:Option,block_render:bool,expect:HoldCause|{ + allow_behind:bool,block_pipeline:Option,block_render:bool,expect:HoldCause, + held_wait:bool|{ let mut f=firmware(vec![held],vec![]); let mut fl=Flight::new(flight); if renders==0{fl.computes=1;}else{fl.renders=renders;} @@ -528,24 +529,28 @@ def item(declaration): let mut want=[0u64;HoldCause::COUNT]; want[expect as usize]=1; assert_eq!(f.engine.stats.hold_causes,want,"{:?}",expect); + // Only a hold behind the job's own VM's flights asks for the short repoll. + assert_eq!(f.engine.held_wait,held_wait,"{:?}",expect); }; let r=|id:u32,vm:&Arc,dep:Result|job_on_vm(id,vm.clone(),true,0,dep); // A warm same-VM render whose allocator cannot pipeline waits for an empty engine. - run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,Some(vm1.slot),false,HoldCause::DrainPb); + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,Some(vm1.slot),false,HoldCause::DrainPb,true); // A cold InitBM flight drains first. - run(r(1,&vm1,Ok(())),1,true,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainInitbm); + run(r(1,&vm1,Ok(())),1,true,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainInitbm,true); // Another VM's compute in flight: no cross-VM render/compute overlap. - run(job_on_vm(1,vm2.clone(),false,0,Ok(())),0,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainCross); + run(job_on_vm(1,vm2.clone(),false,0,Ok(())),0,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainCross,false); // A doomed flight drains first. - run(r(1,&vm1,Ok(())),1,false,true,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainFailed); + run(r(1,&vm1,Ok(())),1,false,true,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainFailed,false); // A full light TA wave (8 renders) pauses the next light render. - run(r(1,&vm1,Ok(())),8,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::TaWave); + run(r(1,&vm1,Ok(())),8,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::TaWave,true); // Pass, flight or unit headroom. - run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,None,true,HoldCause::Slot); + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,None,true,HoldCause::Slot,true); // A failed dependency (pick() skips jobs still waiting for one). - run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Err(ECANCELED)),false,None,false,HoldCause::Dependency); + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Err(ECANCELED)),false,None,false,HoldCause::Dependency,false); // Any other refusal. - run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other); + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,true); + // Behind another VM's render (warm cross-VM renders overlap): counted, but no short repoll. + run(r(1,&vm2,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,false); assert_eq!(HoldCause::NAMES.len(),HoldCause::COUNT); assert_eq!(HoldCause::Other as usize,HoldCause::COUNT-1); } @@ -2718,6 +2723,7 @@ def item(declaration): chan_wait: bool, slot_wait: bool, ta_wave_wait: bool, + held_wait: bool, coalesce_deadline_ns: u64, } struct Slots { free_c: u32 } @@ -2771,6 +2777,7 @@ def item(declaration): chan_wait: false, slot_wait: false, ta_wave_wait: false, + held_wait: false, coalesce_deadline_ns: 0, }, slots: Slots { free_c: 20 }, @@ -2795,6 +2802,12 @@ def item(declaration): assert_eq!(h.defer_busy_coalesce(110_000), None); assert_eq!(h.engine.coalesce_deadline_ns, 0); + // A job held behind the VM's own flights is never coalesced behind them. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + h.engine.held_wait = true; + assert_eq!(h.defer_busy_coalesce(150_000), None); + h.engine.held_wait = false; + // Deadline expiry flushes even with 1 pending command. h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; assert_eq!(h.defer_busy_coalesce(200_000), Some(18)); From d77b0f0d43f0e6cc26298c4d492a405d6bb27ad6 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 10:23:10 -0500 Subject: [PATCH 1124/1514] drm/asahi: g16: never run compute beside another VM's compute Compute commands queued behind compute flights of any VM, so the CDM pipes ran dispatches of different VMs at once, without a barrier between them. With six dEQP-VK processes, about one draw in 285 of dEQP-VK.glsl.texture_functions.* then read back zero or a partial image, with no fault and no recovery: the readback copy, running beside another VM's compute, lost its results. One process never fails, every failed case passes alone, and the failures stop entirely once compute waits for other VMs' flights, over three full runs. gpubench compute.long showed the same loss: a ray-query dispatch that another VM's compute overlapped was reported complete with its results unwritten. Let compute publish behind its own VM's flights only, on either pipe, as it already did behind another VM's render, and as G15 runs one VM at a time. Compute of one VM still pipelines on both pipes, and renders still pipeline across VMs. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 20 +++++----- drivers/gpu/drm/asahi/g16/hw.rs | 5 ++- .../drivers/gpu/asahi-m4/test-publication.py | 39 ++++++++++++------- 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index e3074d55cabdd4..0c85e94fd77cd7 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -434,7 +434,8 @@ pub(crate) enum HoldCause { DrainFailed, /// A cold `InitBM` render is in flight. DrainInitbm, - /// Compute and render of different VMs, or an SCS compute conflict. + /// Compute behind any flight of another VM, render behind compute of another VM, or an + /// SCS compute conflict. DrainCross, /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. DrainPb, @@ -1401,7 +1402,7 @@ impl Firmware { || f.recovery_suspect || f.initbm || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) - || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) + || ((is_compute || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) || (is_render && !self.render_can_pipeline(job)) @@ -1589,8 +1590,8 @@ impl Firmware { /// Whether `job`'s next command may be published behind the flights in flight: /// - /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM - /// render flights (up to [`params::compute_flights`] active computes), each in its own + /// - Compute queues behind healthy non-InitBM compute and render flights of its own VM + /// (up to [`params::compute_flights`] active computes), each in its own /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` /// is set and a same-queue predecessor in its compute or render barrier prefix has /// CPU-published timestamp outputs that have not retired yet @@ -1606,6 +1607,10 @@ impl Firmware { /// dispatch from one client cannot starve another client's fragment shading into a /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. + /// - Compute never runs beside compute of another VM, on either pipe: with several clients + /// dispatching barrier-free compute, the overlapped dispatches occasionally lost their + /// results without a fault (loads read zero, readbacks came back empty or partial), + /// which one client alone never does. G15 runs one VM at a time for the same reason. fn can_queue_behind(&self, job: &Arc) -> bool { let mut ta_pending = None; self.can_queue_behind_with_ta(job, &mut ta_pending) @@ -1672,17 +1677,14 @@ impl Firmware { }) }) })); - let cross_vm_render = e - .flights - .iter() - .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let cross_vm = e.flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &job.vm)); let scs = job.resources.compute_scs() || c.is_rt(); let scs_conflict = e .flights .iter() .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); - !cross_vm_render + !cross_vm && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 3d9cf3793dc032..7f96e6cf1f02d6 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -831,8 +831,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. Warm compute and render commands may pipeline across VMs - /// on disjoint hardware UMA slots while cold `InitBM` renders and recovery paths drain. + /// Published prefixes at most. Warm render commands may pipeline across VMs on disjoint + /// hardware UMA slots, compute only behind its own VM's work, while cold `InitBM` renders + /// and recovery paths 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`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused 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 3cc505d49350b4..73dbb31f2a6684 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -589,7 +589,7 @@ def item(declaration): assert_eq!(fw.attempted,[11]); assert_eq!(fw.engine.stats.hold[0],0); - // Cross-VM compute queues immediately behind another VM's active compute without drain. + // Cross-VM compute drains behind another VM's active compute (no cross-VM C<->C overlap). let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); @@ -598,8 +598,8 @@ def item(declaration): fc.engine.flights.push(flc); fc.allow_behind=true; assert_eq!(fc.publish_checked(&mut done),Ok(())); - assert_eq!(fc.attempted,[13]); - assert_eq!(fc.engine.stats.hold[0],0); + assert!(fc.attempted.is_empty()); + assert_eq!(fc.engine.stats.hold[0],1); // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); @@ -938,10 +938,9 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&j2)); - // Cross-VM compute queues behind another VM's healthy compute, but drains behind - // another VM's render. - assert!(p.can_queue_behind(&j_other_vm)); - assert!(!p.needs_engine_drain(&j_other_vm)); + // Cross-VM compute drains behind another VM's compute as behind its render. + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(p.needs_engine_drain(&j_other_vm)); assert!(p.can_queue_behind(&j_render)); p.engine.flights[0].doomed=true; assert!(!p.can_queue_behind(&j2)); @@ -995,13 +994,17 @@ def item(declaration): assert!(!p.can_queue_behind(j)); assert!(p.needs_engine_drain(j)); } - // SCS compute does not start beside non-SCS compute on either pipe. + // SCS compute does not start beside non-SCS compute on either pipe, and no compute + // starts beside another VM's compute. for pipe in [0u8,1] { p.engine.flights=vec![flight(alu.clone(),false,pipe)]; assert!(!p.can_queue_behind(&rq)); assert!(p.needs_engine_drain(&rq)); - assert!(p.can_queue_behind(&rq_post)); - assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&rq_post)); + assert!(p.needs_engine_drain(&rq_post)); + p.engine.flights=vec![flight(rq_post.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); } // A render flight of its own VM does not hold it; once SCS compute is gone, the rest // overlaps as before. @@ -1012,8 +1015,10 @@ def item(declaration): assert!(!p.needs_engine_drain(&rq)); assert!(p.can_queue_behind(&rq)); p.engine.flights=vec![flight(rq_post.clone(),false,0)]; - assert!(p.can_queue_behind(&alu)); - assert!(!p.needs_engine_drain(&alu)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&alu)); + assert!(p.needs_engine_drain(&alu)); } #[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}); @@ -1134,11 +1139,11 @@ def item(declaration): assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); - // Active VM1 Compute: same-VM R & C allowed; cross-VM C allowed; cross-VM R blocked + drains. + // Active VM1 Compute: same-VM R & C allowed; cross-VM C and R blocked + drain. p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); - assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; @@ -1880,9 +1885,13 @@ def item(declaration): host.engine.next_compute_pipe=0; assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); - assert!(host.can_queue_behind(&c_vm2)); + // No compute queues beside another VM's compute flight, on either pipe. + assert!(!host.can_queue_behind(&c_vm2)); + assert!(!host.can_queue_behind(&c2)); // Same-VM compute still pipelines without draining. + host.engine.flights.pop(); assert!(host.can_queue_behind(&c2)); + assert!(!host.can_queue_behind(&c_vm2)); } #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); From 69ee6f661a63d4c8d23af96e9d01642cf56ab4df Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 15:41:45 -0500 Subject: [PATCH 1125/1514] drm/asahi: license sleep_pd helpers as GPL-2.0-only Use GPL-2.0-only for the new sleep_pd.c and sleep_pd.h files to match the repository's licensing policy for new Aurora code. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/sleep_pd.c | 2 +- drivers/gpu/drm/asahi/sleep_pd.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/sleep_pd.c b/drivers/gpu/drm/asahi/sleep_pd.c index 59afe0edd4f81a..f3612df8c6f916 100644 --- a/drivers/gpu/drm/asahi/sleep_pd.c +++ b/drivers/gpu/drm/asahi/sleep_pd.c @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT +// SPDX-License-Identifier: GPL-2.0-only /* * Hold the GPU's attached power domain across suspend-to-idle. * diff --git a/drivers/gpu/drm/asahi/sleep_pd.h b/drivers/gpu/drm/asahi/sleep_pd.h index a7cf65715fbfc7..63fdcd662455f1 100644 --- a/drivers/gpu/drm/asahi/sleep_pd.h +++ b/drivers/gpu/drm/asahi/sleep_pd.h @@ -1,4 +1,4 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* SPDX-License-Identifier: GPL-2.0-only */ #ifndef _ASAHI_SLEEP_PD_H #define _ASAHI_SLEEP_PD_H From cf330a1c264ce860e3afcab87061ec8b985ce887 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 15:48:57 -0500 Subject: [PATCH 1126/1514] ASoC: apple: t8152-aop-audio: constrain sense FE buffer size Require at least one SenseRing period (SENSE_RING_PERIOD_FRAMES) per ALSA period on the VMALLOC sense front-end, updating periods_max to match. With periods_min = 2, ALSA negotiation rejects buffers too small to fit a single ring batch (such as two 60-frame periods), preventing immediate XRUNs on the first callback, and covers the smallest admitted buffer in KUnit. Signed-off-by: Erik Bourget --- sound/soc/apple/t8152_aop_audio.rs | 56 +++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index bc95c387dc54ad..5fdd6e7e917efa 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -1293,9 +1293,25 @@ unsafe fn sense_ring<'a>( data.sense_ring.as_ref() } +/// Hardware description for the VMALLOC sense front-end: require at least one +/// ring period per ALSA period so even the minimum two-period buffer holds +/// incoming ring batches without XRUNning on the first callback. +fn sense_pcm_hw(formats: u64, ring_period_bytes: usize) -> bindings::snd_pcm_hardware { + let mut hw = pcm_hw(); + hw.info |= bindings::SNDRV_PCM_INFO_BLOCK_TRANSFER | bindings::SNDRV_PCM_INFO_BATCH; + hw.formats = formats; + hw.period_bytes_min = hw.period_bytes_min.max(ring_period_bytes); + hw.periods_max = (hw.buffer_bytes_max / hw.period_bytes_min) as u32; + hw +} + /// The sense front-end's buffer: plain memory the ring callback copies whole /// frames into. -fn sense_open(substream: *mut bindings::snd_pcm_substream, formats: u64) -> i32 { +fn sense_open( + substream: *mut bindings::snd_pcm_substream, + formats: u64, + ring_period_bytes: usize, +) -> i32 { // SAFETY: a live substream in its open. unsafe { if (*substream).dma_buffer.dev.type_ == bindings::SNDRV_DMA_TYPE_UNKNOWN as i32 { @@ -1310,10 +1326,7 @@ fn sense_open(substream: *mut bindings::snd_pcm_substream, formats: u64) -> i32 return ret; } } - let mut hw = pcm_hw(); - hw.info |= bindings::SNDRV_PCM_INFO_BLOCK_TRANSFER | bindings::SNDRV_PCM_INFO_BATCH; - hw.formats = formats; - (*(*substream).runtime).hw = hw; + (*(*substream).runtime).hw = sense_pcm_hw(formats, ring_period_bytes); } 0 } @@ -1344,7 +1357,7 @@ unsafe extern "C" fn asoc_pcm_open( }; if fe == 2 && !playback { if let Some(ring) = &data.sense_ring { - let ret = sense_open(substream, data.cfg.sense_formats); + let ret = sense_open(substream, data.cfg.sense_formats, ring.period_bytes()); if ret < 0 { return ret; } @@ -2350,8 +2363,35 @@ mod tests { #[test] fn sense_ring_fe_space_guards_overrun() { - // Small legal capture buffer (two 12-frame periods) cannot fit one 120-frame ring period - assert!(!sense_ring_has_fe_space(24, 0, 0, SENSE_RING_PERIOD_FRAMES)); + // Every supported multi-amp geometry constrains ALSA negotiation so the + // smallest admitted buffer (2 periods of period_bytes_min) exceeds one + // 120-frame ring batch and cannot XRUN on an empty capture buffer. + for cfg in [&HW_CFG_T8142, &HW_CFG_T8142_6AMP, &HW_CFG_T6050] { + let frame = cfg.sense_channels as usize * 2; + let ring = SenseRing::new(frame); + let hw = sense_pcm_hw(cfg.sense_formats, ring.period_bytes()); + assert_eq!(hw.period_bytes_min, ring.period_bytes()); + assert!(hw.period_bytes_min <= hw.period_bytes_max); + assert_eq!(hw.periods_min, 2); + assert!(hw.periods_min <= hw.periods_max); + let min_period_frames = hw.period_bytes_min / frame; + let min_buffer_frames = hw.periods_min as usize * min_period_frames; + assert_eq!(min_period_frames, SENSE_RING_PERIOD_FRAMES); + assert_eq!(min_buffer_frames, 2 * SENSE_RING_PERIOD_FRAMES); + assert!(sense_ring_has_fe_space( + min_buffer_frames, + 0, + 0, + SENSE_RING_PERIOD_FRAMES + )); + assert!(!sense_ring_has_fe_space( + min_buffer_frames, + SENSE_RING_PERIOD_FRAMES, + 0, + SENSE_RING_PERIOD_FRAMES + )); + } + // Exact full-buffer advance (e.g. 120 frames into a 120-frame buffer) wraps the // modulo pointer back to the same offset, so it must trigger XRUN; strictly less fits. assert!(!sense_ring_has_fe_space(120, 0, 0, 120)); From cce2914d6a6cf363abed318cf7306b3f6545ea46 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 07:49:54 +1100 Subject: [PATCH 1127/1514] pwm: apple: build the KUnit tests without runtime PM The runtime PM usage counter is absent when CONFIG_PM is disabled. Keep the PWM behavior tests available and report zero usage in this configuration, where the power-reference case already skips. Signed-off-by: Ryan Murray --- drivers/pwm/pwm-apple-test.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/pwm/pwm-apple-test.c b/drivers/pwm/pwm-apple-test.c index 8c4af33ac51e2c..b9a4fa71e7ccea 100644 --- a/drivers/pwm/pwm-apple-test.c +++ b/drivers/pwm/pwm-apple-test.c @@ -129,7 +129,11 @@ static int apple_pwm_test_apply(struct apple_pwm_test *ctx, u64 period, static int apple_pwm_test_usage(struct apple_pwm_test *ctx) { +#ifdef CONFIG_PM return atomic_read(&ctx->dev->power.usage_count); +#else + return 0; +#endif } struct apple_pwm_test_conv { From 31e8f6fe2ba7592688f25153402b0b35f121c456 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 21:04:29 -0800 Subject: [PATCH 1128/1514] drm/asahi: charge a VM's page tables to its client's memory limit A client VM's page tables are allocated as the client maps and kept until the VM is destroyed, but they were not counted by the GPU memory limits, not shown in the client's fdinfo and not charged to any memory cgroup. Because sparse and single-page binds map a small object over a large range, the table memory a client causes was not bounded by the memory it holds. Charge the tables to the client that created the VM, as a held user buffer of the same size would be. The root and the tables that exist when the VM gets its client are counted at once. Each later table is admitted against the client's and the device's memory limits once it is allocated, after every other step that can fail, so a table that is not installed leaves no charge behind. A refusal frees the table and fails the bind or kernel mapping that needed it with ENOMEM. From then on the tables are also allocated with GFP_KERNEL_ACCOUNT, so they count towards the memory cgroup of the task that maps. The charge is released when the page table is freed with the VM. Kernel VMs are not charged. Legitimate use stays far below the limits: the Borealis Vulkan driver's sparse address space on M5 is 16 GiB per device, 8 MiB of tables (16 MiB with its read-only shadow). This applies to the client VMs of every GPU family. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/memacct.rs | 96 ++++++++++++++++++-- drivers/gpu/drm/asahi/mmu.rs | 7 +- drivers/gpu/drm/asahi/pgtable.rs | 146 ++++++++++++++++++++++++++++++- 3 files changed, 241 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index fb2a796604e12c..7189844b02b482 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -207,6 +207,17 @@ impl Ledger { /// Reserves the bytes against both limits; the returned [`Commit`] gives /// them back when it is dropped. pub(crate) fn admit(&'static self, client: &Arc, bytes: u64) -> Result { + self.reserve(client, bytes)?; + Ok(Commit { + ledger: self, + client: client.clone(), + bytes, + }) + } + + /// Adds `bytes` to `client`'s and the device's committed totals if both stay within their + /// limits; otherwise counts a refusal and fails with `ENOMEM`, adding nothing. + fn reserve(&self, client: &Client, bytes: u64) -> Result { let client_limit = self.client_limit.load(Ordering::Relaxed); if !try_add_within(&client.committed, bytes, client_limit, 0) { self.refused.fetch_add(1, Ordering::Relaxed); @@ -224,11 +235,57 @@ impl Ledger { self.refused.fetch_add(1, Ordering::Relaxed); return Err(ENOMEM); } - Ok(Commit { - ledger: self, - client: client.clone(), - bytes, - }) + Ok(()) + } +} + +/// Kernel memory that grows with a client's requests and is freed with one of the client's +/// objects, such as the page tables of a VM: charged to the client as held user memory of the +/// same size would be, and released in full when this is dropped. +pub(crate) struct Usage { + ledger: &'static Ledger, + client: Arc, + bytes: u64, +} + +impl Usage { + pub(crate) fn new(ledger: &'static Ledger, client: Arc) -> Self { + Self { + ledger, + client, + bytes: 0, + } + } + + /// Charges `bytes` more if the client and the device stay within their limits, as a new + /// user object of that size would be admitted; otherwise fails with `ENOMEM` and charges + /// nothing. + pub(crate) fn try_add(&mut self, bytes: u64) -> Result { + self.ledger.reserve(&self.client, bytes)?; + self.hold(bytes); + Ok(()) + } + + /// Charges `bytes` more whatever the limits, for memory that already exists. + pub(crate) fn add(&mut self, bytes: u64) { + self.client.committed.fetch_add(bytes, Ordering::AcqRel); + self.ledger.user_committed.fetch_add(bytes, Ordering::AcqRel); + self.hold(bytes); + } + + fn hold(&mut self, bytes: u64) { + self.client.resident.fetch_add(bytes, Ordering::AcqRel); + self.ledger.user_resident.fetch_add(bytes, Ordering::AcqRel); + self.bytes += bytes; + } +} + +impl Drop for Usage { + fn drop(&mut self) { + sub(&self.client.resident, self.bytes); + sub(&self.ledger.user_resident, self.bytes); + sub(&self.client.committed, self.bytes); + sub(&self.ledger.user_committed, self.bytes); } } @@ -623,6 +680,35 @@ mod tests { Ok(()) } + static USAGE: Ledger = Ledger::new(); + + #[test] + fn usage_grows_within_the_limits_and_is_released_whole() -> Result { + USAGE.set_limits(Limits { device: 100 * MIB, client: 60 * MIB }); + let a = Client::new()?; + let mut usage = Usage::new(&USAGE, a.clone()); + // Memory that already exists is counted whatever the limits. + usage.add(16 * MIB); + usage.try_add(40 * MIB)?; + // 4 MiB are left under a's limit: refused, and nothing more is counted. + assert_eq!(usage.try_add(8 * MIB), Err(ENOMEM)); + assert_eq!((a.committed(), a.resident()), (56 * MIB, 56 * MIB)); + assert_eq!(USAGE.refused.load(Ordering::Relaxed), 1); + assert_eq!(USAGE.user_resident.load(Ordering::Relaxed), 56 * MIB); + // The bytes count against the device limit for other clients as well. + let b = Client::new()?; + assert!(USAGE.admit(&b, 50 * MIB).is_err()); + let b1 = USAGE.admit(&b, 44 * MIB)?; + // Dropping releases everything it charged. + drop(usage); + assert_eq!((a.committed(), a.resident()), (0, 0)); + assert_eq!(USAGE.user_committed.load(Ordering::Relaxed), 44 * MIB); + assert_eq!(USAGE.user_resident.load(Ordering::Relaxed), 0); + drop(b1); + assert_eq!(USAGE.user_committed.load(Ordering::Relaxed), 0); + Ok(()) + } + #[test] fn imports_are_not_counted() { let charge = Charge::none(); diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index b6d81365a95415..2df9a6fcfcd171 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -2612,8 +2612,13 @@ impl Vm { } /// Status shared by every queue using this VM, if enabled by its GPU. - /// Charges kernel memory sized by this VM's client to `client` ([`Self::memory_client`]). + /// Charges kernel memory sized by this VM's client to `client` ([`Self::memory_client`]), + /// starting with the VM's page tables. pub(crate) fn with_memory_client(mut self, client: Arc) -> Self { + self.gpuvm.lock_inner().page_table.charge_to(crate::memacct::Usage::new( + &crate::memacct::LEDGER, + client.clone(), + )); self.memory = Some(client); self } diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index a6e757c22176a0..9de3319f60b63a 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -460,6 +460,10 @@ pub(crate) struct UatPageTable { /// Clean new tables and changed entries to the point of coherency, for a UAT walker that does /// not snoop the CPU caches ([`Self::enable_clean_poc`]). clean_poc: bool, + /// Table pages the driver allocated below the root. + tables: usize, + /// The client these tables are charged to ([`Self::charge_to`]). + charge: Option, } impl UatPageTable { @@ -478,6 +482,8 @@ impl UatPageTable { ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, clean_poc: false, + tables: 0, + charge: None, }) } @@ -560,9 +566,24 @@ impl UatPageTable { ias_mask: (1u64 << ias) - 1, oas_mask: (1u64 << oas) - 1, clean_poc: false, + tables: 0, + charge: None, }) } + /// Charges this page table's memory to a client from now on: the root and the tables + /// allocated so far at once, whatever the client's limits, and each further table once it is + /// allocated and ready to install. A table past the client's or the device's limit is freed + /// again and the map that needed it fails with `ENOMEM`; a table is charged only after every + /// step that can fail, so one that is not installed leaves no charge. The tables are also + /// allocated as memory of the calling task's memory cgroup from then on. Everything stays + /// charged until the page table is dropped, which frees the tables. + pub(crate) fn charge_to(&mut self, mut usage: crate::memacct::Usage) { + let pages = self.tables + usize::from(self.ttb_owned); + usage.add((pages * UAT_PGSZ) as u64); + self.charge = Some(usage); + } + /// Retains every physical table after an uncertain M4 handoff. No other agent may reclaim /// this tree merely because a userspace handle closed or a fence reported an error. pub(crate) fn retain(&mut self) { @@ -684,6 +705,8 @@ impl UatPageTable { as usize; mod_pr_debug!("UATPageTable::with_pages: borrowed phys {:#x}\n", phys); let driver_tables = &mut self.driver_tables; + let table_count = &mut self.tables; + let charge = &mut self.charge; let oas_mask = self.oas_mask; let firmware_tree = reserved.as_deref(); let entry = |p: *mut u8| -> Result> { @@ -694,7 +717,12 @@ impl UatPageTable { let mut upte_val = upte.load(Ordering::Relaxed); // Allocate if requested if upte_val == 0 && alloc { - let pt_page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; + let gfp = if charge.is_some() { + GFP_KERNEL_ACCOUNT + } else { + GFP_KERNEL + }; + let pt_page = Page::alloc_page(gfp | __GFP_ZERO)?; mod_pr_debug!( "UATPageTable::with_pages: alloc PT at {:#x}\n", pt_page.phys() @@ -708,9 +736,19 @@ impl UatPageTable { })?; } if let Some(tables) = driver_tables.as_mut() { - tables.push(pt_page.phys(), GFP_KERNEL)?; + tables.reserve(1, GFP_KERNEL)?; + } + // Charge last: nothing below can fail, so a table that is + // not installed is freed with no charge left behind. + if let Some(charge) = charge.as_mut() { + charge.try_add(UAT_PGSZ as u64)?; + } + if let Some(tables) = driver_tables.as_mut() { + // Cannot fail: the room was reserved above. + let _ = tables.push_within_capacity(pt_page.phys()); } let pt_paddr = Page::into_phys(pt_page); + *table_count += 1; upte_val = pt_paddr | PTE_TYPE_LEAF_TABLE; // Complete child-table initialization before a // concurrent device walk can follow its parent. @@ -896,6 +934,7 @@ impl UatPageTable { // SAFETY: Page tables allocated by the driver always come from Page::into_phys(). Without // `driver_tables`, every child table belongs to the driver. unsafe { Page::from_phys(phys) }; + self.tables = self.tables.saturating_sub(1); Ok(()) } @@ -1347,3 +1386,106 @@ mod tests { assert!(SegmentCursor::new([(0x10_0000, PG)].into_iter(), PG, false).is_err()); } } + +#[kunit_tests(asahi_pgtable_charge)] +mod pgtable_charge_tests { + use super::*; + use crate::memacct::{ + Client, + Ledger, + Limits, + Usage, // + }; + + const PG: u64 = UAT_PGSZ as u64; + /// The span of one leaf table (32 MiB); a level-1 table spans 2048 of them. + const LEAF_SPAN: u64 = PG << UAT_LVBIT; + /// Only written into leaves, never accessed. + const PHYS: PhysicalAddr = 0x8_0000_0000; + + static TABLES: Ledger = Ledger::new(); + + #[test] + fn tables_are_charged_to_the_client_until_dropped() -> Result { + TABLES.set_limits(Limits { device: 0, client: 0 }); + let client = Client::new()?; + let mut pt = UatPageTable::new(42, 42)?; + let first = 64 * LEAF_SPAN..66 * LEAF_SPAN; + let second = 66 * LEAF_SPAN..67 * LEAF_SPAN; + // One page repeated over two leaf tables, below one level-1 table, before the charge. + pt.map_pages(first.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true)?; + pt.charge_to(Usage::new(&TABLES, client.clone())); + // The root and the three tables are charged at once. + assert_eq!((client.committed(), client.resident()), (4 * PG, 4 * PG)); + // A further leaf table is charged as it is allocated. + pt.map_pages(second.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true)?; + assert_eq!((client.committed(), client.resident()), (5 * PG, 5 * PG)); + // Unmapping keeps the tables, and their charge, until the page table is dropped. + pt.unmap_pages(first)?; + pt.unmap_pages(second)?; + assert_eq!(client.committed(), 5 * PG); + drop(pt); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(TABLES.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(TABLES.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + static REFUSE: Ledger = Ledger::new(); + + #[test] + fn a_table_past_the_client_limit_is_refused() -> Result { + // Room for the root, one level-1 table and one leaf table. + REFUSE.set_limits(Limits { device: 0, client: 3 * PG }); + let client = Client::new()?; + let mut pt = UatPageTable::new(42, 42)?; + pt.charge_to(Usage::new(&REFUSE, client.clone())); + let range = 64 * LEAF_SPAN..66 * LEAF_SPAN; + assert_eq!( + pt.map_pages(range.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true), + Err(ENOMEM) + ); + assert_eq!(client.committed(), 3 * PG); + assert_eq!(pt.tables, 2); + assert_eq!(REFUSE.refused.load(Ordering::Relaxed), 1); + // The first leaf table's span was written before the refusal: clear it as a failed map + // does. + pt.discard_partial_map(range)?; + drop(pt); + assert_eq!(client.committed(), 0); + assert_eq!(REFUSE.user_committed.load(Ordering::Relaxed), 0); + Ok(()) + } + + static REFUSE_SHARED: Ledger = Ledger::new(); + + #[test] + fn a_refused_table_is_neither_charged_nor_recorded() -> Result { + // A borrowed root whose own tables are recorded one by one, as below a firmware root: + // the root is not the client's, so the limit leaves room for one level-1 and one leaf + // table. + REFUSE_SHARED.set_limits(Limits { device: 0, client: 2 * PG }); + let client = Client::new()?; + let ttb = Page::into_phys(Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?); + let mut pt = UatPageTable::new_with_ttb(ttb, 0..1u64 << 42, 42, 42, true, None)?; + pt.charge_to(Usage::new(&REFUSE_SHARED, client.clone())); + let range = 64 * LEAF_SPAN..66 * LEAF_SPAN; + assert_eq!( + pt.map_pages(range.clone(), PHYS, prot::PROT_GPU_SHARED_RW, true), + Err(ENOMEM) + ); + // The charge matches the tables kept: the refused leaf table was freed, not recorded. + assert_eq!(client.committed(), 2 * PG); + assert_eq!(pt.tables, 2); + assert_eq!(pt.driver_tables.as_ref().map(|t| t.len()), Some(2)); + assert_eq!(REFUSE_SHARED.refused.load(Ordering::Relaxed), 1); + pt.discard_partial_map(range)?; + drop(pt); + assert_eq!(client.committed(), 0); + assert_eq!(REFUSE_SHARED.user_committed.load(Ordering::Relaxed), 0); + // SAFETY: The root came from Page::into_phys() above and the page table that borrowed + // it is gone. + unsafe { Page::from_phys(ttb) }; + Ok(()) + } +} From 3f81108853bcc7f079898659a14b9e547442ba2d Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 21:04:31 -0800 Subject: [PATCH 1129/1514] drm/asahi: charge GPU mapping records to the client and the memory cgroup that create them Each mapping in a VM is recorded in a GPUVA node until it is unmapped, and those nodes were not charged anywhere. Mapping one page after another needs a page table only every 2048 pages but a node for every mapping, so the nodes can outweigh the tables the previous commit charges many times over. Allocate the nodes that binds and unbinds use with GFP_KERNEL_ACCOUNT, so they count towards the memory cgroup of the task that asks for the operation. In a VM charged to a client, also charge each node's size against the client's and the device's memory limits, through the same memacct::Usage that the previous commit uses for page tables, so both committed and resident totals in fdinfo and gpu_memory reflect them. A map operation reserves one node's charge in gpuva_charge before preallocating nodes or changing mappings; a recorded mapping keeps its charge until removed, and an unused charge is returned when the operation ends. Whole-mapping and truncating unmaps never fail on memory limits: unmap preparation reserves no charge, and a truncating remap transfers the removed node's charge to the single surviving piece before dropping the old node (net zero). Only an operation that increases the node count -- a new user map, or a remap that splits one mapping into two -- checks the client and device limits and can fail with ENOMEM, before modifying any page table. When a VM is quarantined, defer_bind_batch() and defer_unmap() check under the VM reservation whether an unmap lies strictly inside an existing charged GPUVA (range_strictly_inside_va()) and pre-reserve a separate split_charge before accepting it (refusing with ENOMEM if over limit), so deferred hole-punch unmaps neither bypass limits nor fail during drain_mappings(), and a map strictly inside an existing mapping cannot consume gpuva_charge during its remap step. Use the existing allocation-free unmap_user_ranges() path in Vm::drop() for every GPU family, so tearing down an untracked VM while its client is at its memory limit never needs to preallocate split nodes. This applies to every GPU family. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/file.rs | 43 +-- drivers/gpu/drm/asahi/memacct.rs | 17 ++ drivers/gpu/drm/asahi/mmu.rs | 385 ++++++++++++++++++++++++-- drivers/gpu/drm/asahi/mmu/bind.rs | 8 +- drivers/gpu/drm/asahi/mmu/lifetime.rs | 214 +++++++++----- rust/kernel/drm/gpuvm/mod.rs | 37 +++ 6 files changed, 572 insertions(+), 132 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 834edfd73de954..e98ec7d9f26734 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -167,41 +167,20 @@ impl Drop for Vm { // object must not outlive the client's VM handle. status.release_mirror(); } - if self.vm.status().is_some() { - // Tracked jobs can outlive their file's VM handle. Their last guard performs - // these unmaps once no accepted work can still dereference the mappings. - if let Err(error) = self - .vm - .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) - { - pr_err!("Vm::Drop: deferred user unmap failed: {:?}\n", error); - } - self.vm.bo_deferred_cleanup(); - self.gpu.vm_closed(&self.vm); - return; - } - // When the user Vm is dropped, verify that no user mappings exists. - let left_range = self.user_range.start..self.kernel_range.start; - let right_range = self.kernel_range.end..self.user_range.end; - - if !left_range.is_empty() - && self - .vm - .unmap_range(None, left_range.start, left_range.range()) - .is_err() - { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); - } - if !right_range.is_empty() - && self - .vm - .unmap_range(None, right_range.start, right_range.range()) - .is_err() + // Tracked jobs can outlive their file's VM handle: their last guard runs the + // teardown once no accepted work can still dereference the mappings. On + // untracked VMs this unmaps every user GPUVA at once without allocating or + // charging split nodes, so teardown succeeds even at the client's memory limit. + if let Err(error) = self + .vm + .unmap_user_ranges(self.user_range.clone(), self.kernel_range.clone()) { - pr_err!("Vm::Drop: vm.unmap_range() failed\n"); + pr_err!("Vm::Drop: user unmap failed: {:?}\n", error); } - self.vm.bo_deferred_cleanup(); + if self.vm.status().is_some() { + self.gpu.vm_closed(&self.vm); + } } } diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 7189844b02b482..e493f464301d66 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -273,6 +273,23 @@ impl Usage { self.hold(bytes); } + /// Creates a new [`Usage`] on the same ledger and client holding the same number of bytes, + /// without checking limits: used to hand a removed record's charge to a surviving piece right + /// before the removed record is dropped. + pub(crate) fn transfer_copy(&self) -> Self { + let mut copy = Self::new(self.ledger, self.client.clone()); + copy.add(self.bytes); + copy + } + + /// Creates a new [`Usage`] on the same ledger and client charged `bytes` if both limits + /// admit it; otherwise fails with `ENOMEM` and charges nothing. + pub(crate) fn try_fork(&self, bytes: u64) -> Result { + let mut copy = Self::new(self.ledger, self.client.clone()); + copy.try_add(bytes)?; + Ok(copy) + } + fn hold(&mut self, bytes: u64) { self.client.resident.fetch_add(bytes, Ordering::AcqRel); self.ledger.user_resident.fetch_add(bytes, Ordering::AcqRel); diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 2df9a6fcfcd171..94c44594460877 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -561,11 +561,17 @@ impl SgSegments { } } +/// Kernel memory one GPUVA takes: the node that records one mapping in a VM. +const GPUVA_BYTES: u64 = size_of::>() as u64; + /// Preallocated resources needed to execute a VM operation. /// /// VM operations may require allocating new GPUVA objects to track mappings. /// To avoid allocation failures during the operation, preallocate the -/// maximum number of GPUVAs that might be needed. +/// maximum number of GPUVAs that might be needed. They are charged to the +/// memory cgroup of the task that asks for the operation and, in a VM charged +/// to a client, to that client's memory limit: a GPUVA lasts as long as the +/// mapping it records. struct VmOpResources { /// Preallocated GPUVA objects for remap operations. /// @@ -574,23 +580,107 @@ struct VmOpResources { /// objects (one for the new mapping, and two for the previous and next /// mappings). preallocated_gpuvas: [Option>; 3], + /// Preallocated charge for the new mapping inserted by `sm_step_map`, taken + /// before the operation starts so that the map step cannot fail on memory + /// limits after modifying page tables. A recorded mapping keeps its charge + /// in its [`VmGpuVa`]; an unused charge goes back with this. + /// + /// Kept separate from `split_charge` so a map strictly inside an existing + /// mapping cannot have its remap step consume the new mapping's charge. + gpuva_charge: Option, + /// Preallocated charge for a deferred hole-punch unmap split, reserved before + /// accepting the unmap into quarantine so `drain_mappings()` cannot fail with + /// `ENOMEM` and quarantined splits cannot bypass limits. + split_charge: Option, } impl VmOpResources { + /// Three preallocated GPUVAs plus one charge for a new mapping, charged to `client` if the + /// VM has one. Fails with ENOMEM before anything changes if the client's or the device's + /// limit refuses it. + fn with_gpuvas(client: Option<&Arc>) -> Result { + Self::with_gpuvas_on(&crate::memacct::LEDGER, client) + } + + fn with_gpuvas_on( + ledger: &'static crate::memacct::Ledger, + client: Option<&Arc>, + ) -> Result { + let gpuva_charge = client + .map(|client| { + let mut usage = crate::memacct::Usage::new(ledger, client.clone()); + usage.try_add(GPUVA_BYTES)?; + Ok::<_, Error>(usage) + }) + .transpose()?; + Ok(Self { + preallocated_gpuvas: [ + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + ], + gpuva_charge, + split_charge: None, + }) + } + + /// No GPUVAs, for operations that only remove whole mappings. + fn without_gpuvas() -> Self { + Self { + preallocated_gpuvas: [None, None, None], + gpuva_charge: None, + split_charge: None, + } + } + /// Resources for unmapping a range. /// /// An unmap splits at most the two mappings that straddle its ends. Each split takes two /// GPUVAs before it knows which pieces survive and returns the unused one, so cutting the tail /// of one mapping and the head of the next needs three GPUVAs at the second split. + /// + /// No memory-limit charge is reserved here: whole-mapping and truncating unmaps never + /// increase the node count and always succeed at the limit; an immediate hole-punch split + /// checks limits in `sm_step_remap` before changing any page table, while a deferred + /// hole-punch unmap reserves `split_charge` before acceptance via `reserve_split_charge()`. fn for_unmap() -> Result { Ok(Self { preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), + Some(GpuVaAlloc::::new(GFP_KERNEL_ACCOUNT)?), ], + gpuva_charge: None, + split_charge: None, }) } + + /// Reserves one GPUVA charge for a deferred hole-punch unmap before it is accepted into + /// quarantine, failing with `ENOMEM` if the client or device limit refuses it. Idempotent. + pub(super) fn reserve_split_charge( + &mut self, + client: Option<&Arc>, + ) -> Result { + self.reserve_split_charge_on(&crate::memacct::LEDGER, client) + } + + fn reserve_split_charge_on( + &mut self, + ledger: &'static crate::memacct::Ledger, + client: Option<&Arc>, + ) -> Result { + if self.split_charge.is_some() { + return Ok(()); + } + self.split_charge = client + .map(|client| { + let mut usage = crate::memacct::Usage::new(ledger, client.clone()); + usage.try_add(GPUVA_BYTES)?; + Ok::<_, Error>(usage) + }) + .transpose()?; + Ok(()) + } } struct StepContext<'ctx> { @@ -627,6 +717,16 @@ impl<'ctx> StepContext<'ctx> { .ok_or(EINVAL) } + /// Takes the preallocated charge for the mapping `sm_step_map` is about to record. + fn preallocated_charge(&mut self) -> Option { + self.resources.gpuva_charge.take() + } + + /// Takes the preallocated split charge reserved for a deferred hole-punch unmap. + fn preallocated_split_charge(&mut self) -> Option { + self.resources.split_charge.take() + } + /// Returns an unused GPUVA object to the preallocated pool. /// If the pool is already full, the unused allocation is simply dropped. fn return_preallocated_gpuva(&mut self, gpuva: GpuVaAlloc) { @@ -642,10 +742,23 @@ impl<'ctx> StepContext<'ctx> { } /// Per-mapping metadata that survives backing eviction and GPUVA splits. -#[derive(Default, Clone)] struct VmGpuVa { prot: Option, bind_sequence: u64, + /// The GPUVA's charge against the VM's client, given back with the GPUVA. + _charge: Option, +} + +impl Clone for VmGpuVa { + /// Copies the mapping metadata for a snapshot (`next_private_mapping`). The live GPUVA in + /// the tree keeps the memory charge, so the snapshot carries none. + fn clone(&self) -> Self { + Self { + prot: self.prot, + bind_sequence: self.bind_sequence, + _charge: None, + } + } } impl gpuvm::DriverGpuVm for VmInner { @@ -747,6 +860,7 @@ impl gpuvm::DriverGpuVm for VmInner { VmGpuVa { prot: Some(ctx.prot), bind_sequence, + _charge: ctx.preallocated_charge(), }, ); ctx.bind_sequence = bind_sequence; @@ -777,6 +891,8 @@ impl gpuvm::DriverGpuVm for VmInner { let orig_prot = op.va_to_unmap().data().prot.ok_or(EINVAL)?; let orig_bind_sequence = op.va_to_unmap().data().bind_sequence; let orig_invalidated = op.va_to_unmap().flags().contains(GpuVaFlag::INVALIDATED); + let has_prev = op.prev().is_some(); + let has_next = op.next().is_some(); // Only unmap the hole between prev/next, if they exist let unmap_start = if let Some(op) = op.prev() { @@ -814,6 +930,29 @@ impl gpuvm::DriverGpuVm for VmInner { } }; + // Splitting one mapping into two adds a net GPUVA node. Such a mapping strictly + // contains the operation's range, so it is the sole overlapping GPUVA and no page + // tables have changed yet: use a split charge already reserved when a quarantined + // unmap was accepted, or check memory limits here before unmapping anything. + let extra_charge = if has_prev && has_next { + match op.va_to_unmap().data()._charge.as_ref() { + Some(charge) => match ctx.preallocated_split_charge() { + Some(preallocated) => Some(preallocated), + None => match charge.try_fork(GPUVA_BYTES) { + Ok(forked) => Some(forked), + Err(error) => { + ctx.return_preallocated_gpuva(prev_gpuva); + ctx.return_preallocated_gpuva(next_gpuva); + return Err(error); + } + }, + }, + None => None, + } + } else { + None + }; + let _mutation = self.mapping_mutation(); if orig_invalidated { self.page_table @@ -837,21 +976,42 @@ impl gpuvm::DriverGpuVm for VmInner { self.tlbi_contexts_naming_root(unmap_start, unmap_range as usize); + // One surviving piece inherits the removed node's charge (net zero once + // `remap_ret.unmapped_va` drops below); if both pieces survive, the second + // takes the extra charge admitted above. + let inherited_charge = (has_prev || has_next) + .then(|| { + op.va_to_unmap() + .data() + ._charge + .as_ref() + .map(crate::memacct::Usage::transfer_copy) + }) + .flatten(); + let (prev_charge, next_charge) = match (has_prev, has_next) { + (true, true) => (inherited_charge, extra_charge), + (true, false) => (inherited_charge, None), + (false, true) => (None, inherited_charge), + (false, false) => (None, None), + }; let (op_remapped, remap_ret) = op.remap( [prev_gpuva, next_gpuva], VmGpuVa { prot: Some(orig_prot), bind_sequence: orig_bind_sequence, + _charge: prev_charge, }, VmGpuVa { prot: Some(orig_prot), bind_sequence: orig_bind_sequence, + _charge: next_charge, }, ); if let Some(unused_va) = remap_ret.unused_va { ctx.return_preallocated_gpuva(unused_va); } + drop(remap_ret.unmapped_va); Ok(op_remapped) } @@ -3013,13 +3173,7 @@ impl Vm { }))?; prepare_sgt_segments(dev, gem, &vm_bo, &_bind_lease)?; - let mut resources = VmOpResources { - preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - ], - }; + let mut resources = VmOpResources::with_gpuvas(self.memory_client())?; // Mapping needs a complete context let mut ctx = StepContext::new(Some(device.as_ref().as_ref()), prot, &mut resources)?; @@ -3240,9 +3394,7 @@ impl Vm { fn drop_mappings_now(&self, gem: &gem::Object) -> Result { let _residency = self.enter_retirement_residency(); // Removing whole mappings only does unmaps, so no preallocated VAs - let mut resources = VmOpResources { - preallocated_gpuvas: [None, None, None], - }; + let mut resources = VmOpResources::without_gpuvas(); let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; // SAFETY: See `lock_vm()`. @@ -3277,9 +3429,7 @@ impl Vm { let _residency = self.enter_retirement_residency(); // Removing whole mappings only does unmaps, so no preallocated VAs // are needed for the indexed path. - let mut resources = VmOpResources { - preallocated_gpuvas: [None, None, None], - }; + let mut resources = VmOpResources::without_gpuvas(); let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; // The BO's newest sequence is checked under the same lock as binds. If @@ -4598,3 +4748,202 @@ impl FirmwareWindow { && context.ttb1.load(Ordering::Acquire) == self.tables.base | TTBR_VALID } } + +#[kernel::macros::kunit_tests(asahi_gpuva_charge)] +mod gpuva_charge_tests { + use super::*; + use crate::memacct::{ + Client, + Ledger, + Limits, // + }; + + static GPUVA_TABLES: Ledger = Ledger::new(); + + #[test] + fn preallocated_gpuvas_are_charged_to_the_vms_client() -> Result { + assert!(GPUVA_BYTES as usize >= size_of::()); + GPUVA_TABLES.set_limits(Limits { device: 0, client: 0 }); + let client = Client::new()?; + let mut resources = VmOpResources::with_gpuvas_on(&GPUVA_TABLES, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + { + let mut ctx = StepContext::new(None, Prot::default(), &mut resources)?; + // A recorded mapping keeps its charge with its metadata. + let kept = VmGpuVa { + prot: None, + bind_sequence: 0, + _charge: ctx.preallocated_charge(), + }; + drop(ctx); + drop(resources); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + // Cloning metadata for a mapping snapshot carries no charge. + let snapshot = kept.clone(); + drop(snapshot); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + // Removing the mapping gives the charge back. + drop(kept); + } + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_TABLES.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_TABLES.user_resident.load(Ordering::Relaxed), 0); + // A VM charged to no client takes no charge. + let unaccounted = VmOpResources::with_gpuvas_on(&GPUVA_TABLES, None)?; + assert!(unaccounted.gpuva_charge.is_none()); + Ok(()) + } + + static GPUVA_REFUSE: Ledger = Ledger::new(); + + #[test] + fn a_gpuva_past_the_client_limit_is_refused() -> Result { + GPUVA_REFUSE.set_limits(Limits { + device: 0, + client: GPUVA_BYTES, + }); + let client = Client::new()?; + let first = VmOpResources::with_gpuvas_on(&GPUVA_REFUSE, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!( + VmOpResources::with_gpuvas_on(&GPUVA_REFUSE, Some(&client)).err(), + Some(ENOMEM) + ); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_REFUSE.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_REFUSE.user_resident.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_REFUSE.refused.load(Ordering::Relaxed), 1); + drop(first); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_REFUSE.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_REFUSE.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + static GPUVA_UNMAP: Ledger = Ledger::new(); + + #[test] + fn unmap_and_truncating_remap_succeed_at_the_client_limit() -> Result { + GPUVA_UNMAP.set_limits(Limits { + device: 0, + client: GPUVA_BYTES, + }); + let client = Client::new()?; + let mut resources = VmOpResources::with_gpuvas_on(&GPUVA_UNMAP, Some(&client))?; + let orig = resources.gpuva_charge.take().ok_or(EINVAL)?; + drop(resources); + + // Unmap preparation takes no charge and succeeds at the exact client limit. + let unmap = VmOpResources::for_unmap()?; + assert!(unmap.gpuva_charge.is_none()); + drop(unmap); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 0); + + // Truncating remap hands the removed node's charge to the surviving piece (net zero). + let transferred = orig.transfer_copy(); + drop(orig); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.user_resident.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 0); + + // Splitting one mapping into two (net +1 node) refuses past the client limit. + assert_eq!(transferred.try_fork(GPUVA_BYTES).err(), Some(ENOMEM)); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), GPUVA_BYTES); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 1); + + // A deferred hole-punch unmap reserves its split charge before acceptance: refused + // with ENOMEM at the limit, admitted once headroom exists, idempotent on retry, and + // returned cleanly if unused at drain time. + let mut unmap_res = VmOpResources::for_unmap()?; + assert_eq!( + unmap_res + .reserve_split_charge_on(&GPUVA_UNMAP, Some(&client)) + .err(), + Some(ENOMEM) + ); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + assert_eq!(GPUVA_UNMAP.refused.load(Ordering::Relaxed), 2); + + // Once headroom exists, reserving the deferred split charge fills split_charge only + // (never gpuva_charge), is idempotent, and drops cleanly if unused. + GPUVA_UNMAP.set_limits(Limits { + device: 0, + client: 3 * GPUVA_BYTES, + }); + unmap_res.reserve_split_charge_on(&GPUVA_UNMAP, Some(&client))?; + unmap_res.reserve_split_charge_on(&GPUVA_UNMAP, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (2 * GPUVA_BYTES, 2 * GPUVA_BYTES) + ); + { + let mut ctx = StepContext::new(None, Prot::default(), &mut unmap_res)?; + assert!(ctx.preallocated_charge().is_none()); + let split = ctx.preallocated_split_charge(); + assert!(split.is_some()); + assert!(ctx.preallocated_split_charge().is_none()); + drop(split); + } + drop(unmap_res); + assert_eq!( + (client.committed(), client.resident()), + (GPUVA_BYTES, GPUVA_BYTES) + ); + + // A map strictly inside an existing charged mapping runs remap before map on the same + // StepContext: preallocated_split_charge() must be None so remap forks its own split + // charge instead of stealing gpuva_charge from sm_step_map(), leaving all 3 nodes charged. + let mut map_res = VmOpResources::with_gpuvas_on(&GPUVA_UNMAP, Some(&client))?; + assert_eq!( + (client.committed(), client.resident()), + (2 * GPUVA_BYTES, 2 * GPUVA_BYTES) + ); + let (extra, map_charge) = { + let mut ctx = StepContext::new(None, Prot::default(), &mut map_res)?; + assert!(ctx.preallocated_split_charge().is_none()); + let extra = transferred.try_fork(GPUVA_BYTES)?; + let map_charge = ctx.preallocated_charge(); + assert!(map_charge.is_some()); + (extra, map_charge) + }; + assert_eq!( + (client.committed(), client.resident()), + (3 * GPUVA_BYTES, 3 * GPUVA_BYTES) + ); + drop((map_res, map_charge, extra, transferred)); + assert_eq!((client.committed(), client.resident()), (0, 0)); + assert_eq!(GPUVA_UNMAP.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(GPUVA_UNMAP.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } +} diff --git a/drivers/gpu/drm/asahi/mmu/bind.rs b/drivers/gpu/drm/asahi/mmu/bind.rs index 97483575610774..6b9cd7f61932d6 100644 --- a/drivers/gpu/drm/asahi/mmu/bind.rs +++ b/drivers/gpu/drm/asahi/mmu/bind.rs @@ -79,13 +79,7 @@ impl Vm { gem::validate_vm_binding(gem, self)?; let residency = self.enter_residency_metadata()?; let context = self.prepare_context_binding(addr, size, offset)?; - let resources = VmOpResources { - preallocated_gpuvas: [ - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - Some(GpuVaAlloc::::new(GFP_KERNEL)?), - ], - }; + let resources = VmOpResources::with_gpuvas(self.memory_client())?; // SAFETY: As in `Vm::bind_object()`, the device is bound while its file can issue binds. let dev = unsafe { self.dev.as_bound() }; // Populate the scatter-gather table before any GPUVM lock is taken. diff --git a/drivers/gpu/drm/asahi/mmu/lifetime.rs b/drivers/gpu/drm/asahi/mmu/lifetime.rs index b6c0f19720fe4d..600654ae03f1c9 100644 --- a/drivers/gpu/drm/asahi/mmu/lifetime.rs +++ b/drivers/gpu/drm/asahi/mmu/lifetime.rs @@ -62,6 +62,7 @@ struct State { commits: usize, blocked: bool, quarantined: bool, + quarantine_gen: u64, draining: bool, closed: bool, cleanup_failed: bool, @@ -97,7 +98,8 @@ impl VmLifetime { Arc::pin_init( pin_init!(Self { state <- new_mutex!(State { active:0, commits:0, blocked:false, - quarantined:false, draining:false, closed:false, cleanup_failed:false, close_ranges:None, + quarantined:false, quarantine_gen:0, draining:false, closed:false, + cleanup_failed:false, close_ranges:None, unmaps:KVec::new(), objects:KVec::new() }, "VM job lifetime"), changed <- new_condvar!("VM mapping admission"), driver <- new_mutex!(None, "VM driver mappings"), @@ -123,7 +125,10 @@ impl VmJobGuard { while state.commits != 0 { lifetime.changed.wait(&mut state); } - state.quarantined = true; + if !state.quarantined { + state.quarantine_gen = state.quarantine_gen.wrapping_add(1); + state.quarantined = true; + } } } } @@ -520,49 +525,87 @@ impl Vm { let Some(lifetime) = self.lifetime.as_ref() else { return Ok(false); }; - let mut state = lifetime.state.lock(); - if !state.blocked { - return Ok(false); - } - if state.closed { - return Err(ENOENT); - } - if batch - .ops - .iter() - .skip(start) - .any(|op| matches!(op, PreparedUserBindOp::Map(_))) - { - return Err(EIO); - } - if !state.quarantined { - return Err(EBUSY); - } - // Reserve before accepting any range; a partial deferred batch must - // not leave canonical metadata ahead of the accepted cleanup. - state.unmaps.reserve(batch.ops.len() - start, GFP_KERNEL)?; - let retired = - self.untrack_context_ranges(batch.ops.iter().skip(start).filter_map(|op| match op { - PreparedUserBindOp::Unmap(unmap) => Some(unmap.iova..unmap.iova + unmap.size), - PreparedUserBindOp::Map(_) => None, - })); - // Transfer the preallocated split nodes along with each accepted range. - // Already-committed prefix operations must not be replayed: their nodes - // may have been consumed and another binding may now occupy the range. - for op in batch.ops.drain(start..) { - if let PreparedUserBindOp::Unmap(unmap) = op { - if !state - .unmaps + loop { + let gen = { + let state = lifetime.state.lock(); + if !state.blocked { + return Ok(false); + } + if state.closed { + return Err(ENOENT); + } + if batch + .ops .iter() - .any(|old| old.iova == unmap.iova && old.size == unmap.size) + .skip(start) + .any(|op| matches!(op, PreparedUserBindOp::Map(_))) { - state.unmaps.push(unmap, GFP_KERNEL)?; + return Err(EIO); + } + if !state.quarantined { + return Err(EBUSY); + } + state.quarantine_gen + }; + + // Reserve a split charge before accepting any deferred hole-punch unmap so + // drain_mappings() never hits ENOMEM after VM_BIND returned 0 and quarantined + // unmaps cannot bypass client/device limits. While quarantined, maps cannot + // commit, so any unmap that can split at drain time is already strictly inside + // an existing GPUVA here. + if let Some(client) = self.memory_client() { + let inner = self.gpuvm.lock_inner(); + for op in batch.ops.iter_mut().skip(start) { + if let PreparedUserBindOp::Unmap(unmap) = op { + if inner.range_strictly_inside_va(unmap.iova, unmap.size, |va| { + va.data()._charge.is_some() + }) { + unmap.resources.reserve_split_charge(Some(client))?; + } + } } } + + let mut state = lifetime.state.lock(); + if !state.blocked { + return Ok(false); + } + if state.closed { + return Err(ENOENT); + } + if !state.quarantined { + return Err(EBUSY); + } + if state.quarantine_gen != gen { + continue; + } + // Reserve before accepting any range; a partial deferred batch must + // not leave canonical metadata ahead of the accepted cleanup. + state.unmaps.reserve(batch.ops.len() - start, GFP_KERNEL)?; + let retired = + self.untrack_context_ranges(batch.ops.iter().skip(start).filter_map(|op| match op { + PreparedUserBindOp::Unmap(unmap) => Some(unmap.iova..unmap.iova + unmap.size), + PreparedUserBindOp::Map(_) => None, + })); + // Transfer the preallocated split nodes (and any reserved split charge) + // along with each accepted range. Already-committed prefix operations + // must not be replayed: their nodes may have been consumed and another + // binding may now occupy the range. + for op in batch.ops.drain(start..) { + if let PreparedUserBindOp::Unmap(unmap) = op { + if !state + .unmaps + .iter() + .any(|old| old.iova == unmap.iova && old.size == unmap.size) + { + state.unmaps.push(unmap, GFP_KERNEL)?; + } + } + } + drop(state); + drop(retired); + return Ok(true); } - drop(state); - drop(retired); - Ok(true) } /// Returns true if a quarantined owner requires this unmap to be deferred. @@ -570,43 +613,64 @@ impl Vm { let Some(lifetime) = self.lifetime.as_ref() else { return Ok(false); }; - let state = lifetime.state.lock(); - if state.closed { - return Err(ENOENT); - } - if !state.blocked { - return Ok(false); - } - if !state.quarantined { - return Err(EBUSY); - } - if state - .unmaps - .iter() - .any(|old| old.iova == iova && old.size == size) - { + let mut prepared: Option = None; + loop { + let gen = { + let state = lifetime.state.lock(); + if state.closed { + return Err(ENOENT); + } + if !state.blocked { + return Ok(false); + } + if !state.quarantined { + return Err(EBUSY); + } + if state + .unmaps + .iter() + .any(|old| old.iova == iova && old.size == size) + { + return Ok(true); + } + state.quarantine_gen + }; + + let unmap = match prepared.as_mut() { + Some(unmap) => unmap, + None => prepared.insert(self.prepare_user_unmap(iova, size)?), + }; + if let Some(client) = self.memory_client() { + let inner = self.gpuvm.lock_inner(); + if inner.range_strictly_inside_va(iova, size, |va| va.data()._charge.is_some()) { + unmap.resources.reserve_split_charge(Some(client))?; + } + } + + let mut state = lifetime.state.lock(); + if state.closed { + return Err(ENOENT); + } + if !state.blocked { + return Ok(false); + } + if !state.quarantined { + return Err(EBUSY); + } + if state.quarantine_gen != gen { + continue; + } + if !state + .unmaps + .iter() + .any(|old| old.iova == iova && old.size == size) + { + if let Some(unmap) = prepared.take() { + state.unmaps.push(unmap, GFP_KERNEL)?; + } + } return Ok(true); } - drop(state); - let unmap = self.prepare_user_unmap(iova, size)?; - let mut state = lifetime.state.lock(); - if state.closed { - return Err(ENOENT); - } - if !state.blocked { - return Ok(false); - } - if !state.quarantined { - return Err(EBUSY); - } - if !state - .unmaps - .iter() - .any(|old| old.iova == iova && old.size == size) - { - state.unmaps.push(unmap, GFP_KERNEL)?; - } - Ok(true) } /// Defers handle-close cleanup while any accepted job can still use the BO. diff --git a/rust/kernel/drm/gpuvm/mod.rs b/rust/kernel/drm/gpuvm/mod.rs index 66adaf99e0859d..7f834933311c02 100644 --- a/rust/kernel/drm/gpuvm/mod.rs +++ b/rust/kernel/drm/gpuvm/mod.rs @@ -731,6 +731,43 @@ pub struct GpuVmInnerGuard<'a, T: DriverGpuVm> { } impl GpuVmInnerGuard<'_, T> { + /// Whether `addr..addr + range` lies strictly inside a single driver GPUVA satisfying + /// `matches` (so unmapping it would split that GPUVA into two surviving pieces, net +1 node). + pub fn range_strictly_inside_va( + &self, + addr: u64, + range: u64, + matches: impl FnOnce(&GpuVa) -> bool, + ) -> bool { + let Some(end) = addr.checked_add(range) else { + return false; + }; + if range == 0 { + return false; + } + // SAFETY: This guard owns the VM's shared reservation, serializing VA tree mutation. + let raw = unsafe { bindings::drm_gpuva_find_first(self.gpuvm.as_raw(), addr, range) }; + if raw.is_null() { + return false; + } + // SAFETY: `raw` stays linked and alive while this guard is held. + let va = unsafe { &*raw }; + if va.gem.obj.is_null() || va.vm_bo.is_null() { + return false; + } + if !va + .va + .addr + .checked_add(va.va.range) + .is_some_and(|va_end| va.va.addr < addr && end < va_end) + { + return false; + } + // SAFETY: Driver-owned mappings are `GpuVa`; the kernel cutout has no GEM object + // and was skipped above. + matches(unsafe { GpuVa::::from_raw(raw) }) + } + /// Run immediate-mode unmap steps without allocating an exec context. /// /// # Safety From b59b99938ace88cbe2717eee1c47b5e0e0d04989 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Thu, 19 Nov 2026 21:04:32 -0800 Subject: [PATCH 1130/1514] drm/asahi: allow at most 64 VMs per file, so VM memory and reclaim work stay bounded Besides its page tables, each VM holds kernel memory that is not charged to its client: its GPUVM, its kernel allocators and per-VM objects. A G17 user VM also registers two shrinkers of its own, and every reclaim pass walks all registered shrinkers. The number of VMs one file could create was not limited. Refuse VM_CREATE past 64 VMs in one file with EBUSY, as the ID allocator reports a full range. VM_CREATE takes its table slot before it builds anything of the VM, so a refused create costs nothing. Mesa creates one VM per file. The limit is a count, not a charge against the client's memory limit: the VM's memory could be charged as its page tables are, but the shrinker registrations are not memory, and the time reclaim spends walking them grows with their number. Neither the machine nor a memory limit bounds that. Shrinkers registered once per device, walking the device's VMs, would make the count unnecessary. The cap is per file, as the existing memory limits are: a client that opens the device again gets another 64 VMs in the new file, each file accounted on its own. This applies to every GPU family. Reported-by: Erik Bourget Suggested-by: Erik Bourget Suggested-by: Ryan Murray Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/file.rs | 53 ++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index e98ec7d9f26734..cc58936277a731 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -380,6 +380,18 @@ pub(crate) type DrmFile = drm::File; /// Minimum reserved AS for kernel mappings const VM_KERNEL_MIN_SIZE: u64 = 0x20000000; +/// Most VMs one file may hold at a time. Mesa creates one per file. Each VM holds kernel memory +/// that is not charged to the client (its GPUVM, allocators and per-VM objects). +const MAX_VMS_PER_FILE: u32 = 64; + +/// Takes a slot for a new VM in a file's VM table, or fails with EBUSY past +/// [`MAX_VMS_PER_FILE`], as the ID allocator reports a full range. +fn reserve_vm_slot<'a>( + vms: &'a xarray::XArray>, +) -> Result>> { + vms.lock().reserve_limit(1..=MAX_VMS_PER_FILE, GFP_KERNEL) +} + impl drm::file::DriverFile for File { type Driver = driver::AsahiDrmDriver; @@ -662,6 +674,11 @@ impl File { // Every other runtime here reports DRM_ASAHI_GPU_HAL_LEGACY. return Err(EINVAL); } + // Take the table slot first, so that a VM past the cap is refused before anything of it + // is built. + let vm_xa = file.inner().vms(); + let resv = reserve_vm_slot(vm_xa.get_ref())?; + let id: u32 = resv.index().try_into()?; reg_data.gpu.admit_vm( device.as_ref().as_ref(), file.inner() @@ -712,10 +729,6 @@ impl File { }, ); - let vm_xa = file.inner().vms(); - let resv = vm_xa.lock().reserve_limit(1..=u32::MAX, GFP_KERNEL)?; - let id: u32 = resv.index().try_into()?; - mod_dev_dbg!(device, "[File {} VM {}]: VM Create\n", file_id, id); mod_dev_dbg!( device, @@ -1923,3 +1936,35 @@ impl Drop for File { Self::mark_clients_closed(this, |_| true); } } + +#[kernel::macros::kunit_tests(asahi_vm_table)] +mod vm_table_tests { + use super::*; + + #[test] + fn a_file_holds_at_most_max_vms_per_file() -> Result { + let vms = KBox::pin_init( + xarray::XArray::>::new(xarray::AllocKind::Alloc1), + GFP_KERNEL, + )?; + let mut held = KVec::new(); + for _ in 0..MAX_VMS_PER_FILE { + held.push(reserve_vm_slot(&vms)?, GFP_KERNEL)?; + } + assert_eq!(reserve_vm_slot(&vms).err(), Some(EBUSY)); + // A destroyed VM frees its slot for the next. + held.pop(); + held.push(reserve_vm_slot(&vms)?, GFP_KERNEL)?; + assert_eq!(reserve_vm_slot(&vms).err(), Some(EBUSY)); + // Another file's VM table has its own budget while the first is full. + let other = KBox::pin_init( + xarray::XArray::>::new(xarray::AllocKind::Alloc1), + GFP_KERNEL, + )?; + let _other_slot = reserve_vm_slot(&other)?; + // Closing the first file releases every slot for reuse. + held.clear(); + let _reused = reserve_vm_slot(&vms)?; + Ok(()) + } +} From 30d8fd8d2710c82e552035a10b494ad54f866b82 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Tue, 24 Nov 2026 21:14:39 +0000 Subject: [PATCH 1131/1514] drm/apple: enable the J615 panel brightness path The J615 board record does not admit panel nits, so the working 14.7 display session never registers a backlight device: /sys/class/backlight is empty on the 15-inch M3 MacBook Air and brightness controls do nothing. The J615 runs the J613 DCP image (DCP_V14_J613_FIRMWARE_UUID) on the same T8122 DCP, and its device tree carries apple,max-brightness like the J613. Admit the J615 to the nits path the same way the J613 is admitted, keeping the firmware UUID and display handoff checks. J514C remains excluded. Run the existing swap-level KUnit case for J615 as well, and move it out of the boards whose production path must stay untouched. Signed-off-by: Eric Juta --- drivers/gpu/drm/apple/iomfb_v14_7.c | 4 +++- .../drm/apple/iomfb_v14_7_backlight_test.c | 24 ++++++++++++------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index c6d3c66a0be27a..400f31c768f1f1 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -136,6 +136,7 @@ static const struct dcp_v14_board dcp_v14_board_j615 = { .panel_width = 2880, .panel_height = 1864, .promotion = false, + .panel_nits = true, .ctm_set = A(421), .ctm_get = A(420), }; @@ -1694,7 +1695,8 @@ static bool dcp_v14_panel_nits_admit(const struct dcp_v14_board *board, { return board && board->panel_nits && (machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || - machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613")); + machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613") || + machine_is(ctx, "apple,j615")); } const char *iomfb_v14_7_board_name(const struct dcp_v14_board *board) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index a84e45338793e5..61d5c1026392ca 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -8,9 +8,9 @@ * a refused level never becomes the actual one). * * The objects are built here, with no DCP: nothing in a case may reach an - * RPC. A J615 or J514C panel never initialises the backlight policy; - * its state is set to answer "yes" so that a case fails if anything on - * those boards looks at it. + * RPC. A J514C panel never initialises the backlight policy; its state is + * set to answer "yes" so that a case fails if anything on that board + * looks at it. */ #include #include @@ -122,7 +122,7 @@ static bool v14_bl_ctx_machine_is(const void *ctx, const char *compat) return !strcmp(((const char *const *)ctx)[1], compat); } -/* Only admitted T6030, J516C and J613 internal panels carry levels. */ +/* Only admitted T6030, J516C, J613 and J615 internal panels carry levels. */ static void v14_bl_boards(struct kunit *test) { static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s" }; @@ -152,10 +152,10 @@ static void v14_bl_boards(struct kunit *test) KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j613)); - KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j615, &known); KUNIT_ASSERT_NOT_NULL(test, board); - KUNIT_EXPECT_FALSE(test, board->panel_nits); + KUNIT_EXPECT_TRUE(test, board->panel_nits); + KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j516c, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); @@ -348,13 +348,13 @@ static bool v14_bl_queued(struct apple_dcp_v14 *v14) } /* - * The production paths on J615 and J514C: no policy is consulted, no - * level is encoded, the work does nothing, sleep leaves the gate alone. + * The production path on J514C: no policy is consulted, no level is + * encoded, the work does nothing, sleep leaves the gate alone. */ static void v14_bl_other_boards_untouched(struct kunit *test) { const struct dcp_v14_board *boards[] = { - &dcp_v14_board_j615, &dcp_v14_board_j514c, + &dcp_v14_board_j514c, }; struct dcp_backlight_present present; unsigned int i; @@ -477,6 +477,11 @@ static void v14_bl_j613_swap_levels(struct kunit *test) v14_bl_swap_levels(test, &dcp_v14_board_j613); } +static void v14_bl_j615_swap_levels(struct kunit *test) +{ + v14_bl_swap_levels(test, &dcp_v14_board_j615); +} + /* * The gate, through the production queue path: open, a kick queues the work; * suspended, nothing queues until resume; closed, nothing ever does. The @@ -586,6 +591,7 @@ static struct kunit_case v14_backlight_cases[] = { KUNIT_CASE(v14_bl_external_untouched), KUNIT_CASE(v14_bl_t6030_swap_levels), KUNIT_CASE(v14_bl_j613_swap_levels), + KUNIT_CASE(v14_bl_j615_swap_levels), KUNIT_CASE(v14_bl_t6030_gate), KUNIT_CASE(v14_bl_t6030_work), {} From 80d33d7e88756ae9e5a3827caddd6e8adf340fd0 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Tue, 24 Nov 2026 21:17:39 +0000 Subject: [PATCH 1132/1514] dt-bindings: display: apple,dcp: add apple,no-shared-display-dart, fbdma and t8122-dcpext-firmware-ready Document the properties needed for T8122 external display processors whose display DART cannot be joined to the display subsystem's IOMMU domain: - apple,no-shared-display-dart: keep the external coprocessor's display DART out of the display subsystem's IOMMU domain and mirror framebuffers through the fbdma child instead. - fbdma: child node naming the display DART stream and display subsystem DVA window used to mirror framebuffers. - apple,t8122-dcpext-firmware-ready: set by the boot loader to 2 (default) or 1 (explicitly requested by the owner, accepted by older kernels that share the display DART unconditionally). Signed-off-by: Eric Juta --- .../bindings/display/apple,dcp.yaml | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 6867256ee228ec..136e916b228624 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -344,8 +344,13 @@ properties: apple,t8122-dcpext-firmware-ready: $ref: /schemas/types.yaml#/definitions/uint32 - const: 1 - description: All external firmware reservations were committed by the loader. + enum: [1, 2] + description: + Set by the boot loader on a T8122 external coprocessor whose firmware + it has reserved. 2 is the boot loader's default. 1 is set only when + the owner asked for the coprocessor in the boot loader configuration, + because kernels that share the display DART unconditionally accept 1 + and nothing else. apple,pmp: $ref: /schemas/types.yaml#/definitions/phandle @@ -534,6 +539,32 @@ properties: - iommus additionalProperties: false + apple,no-shared-display-dart: + type: boolean + description: + The external coprocessor's display DART must stay out of the display + subsystem's IOMMU domain. Framebuffers are mirrored through the fbdma + child instead, which must be present. + + fbdma: + type: object + description: + The display DART stream an external coprocessor scans framebuffers + through, with the display subsystem's DVA window. + properties: + iommus: + maxItems: 1 + apple,dma-range: + $ref: /schemas/types.yaml#/definitions/uint64-array + description: + Base and size of the display subsystem's DVA window on this stream. + minItems: 2 + maxItems: 2 + required: + - iommus + - apple,dma-range + additionalProperties: false + panel: type: object properties: From 395b56817609433e7b623e18ab9c2b40f93ced93 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Tue, 24 Nov 2026 21:19:03 +0000 Subject: [PATCH 1133/1514] soc: apple: display-gate: support unshared T8122 dcpext display DART and loader-default marker On the J615 (MacBook Air 15", M3), appending dispext0_dart to the display subsystem's shared IOMMU domain causes the internal DCP's DART to fault and take down the internal panel. Keep dispext0_dart out of the display subsystem when the dcpext node sets apple,no-shared-display-dart, leaving framebuffer mirroring to the fbdma child node instead. - Accept apple,t8122-dcpext-firmware-ready = <2> (boot loader default) beside <1> (owner's explicit request), so older kernels that always share the display DART will not enable dcpext on a J615 sharing the same device tree. - Refuse a dcpext node with apple,no-shared-display-dart and no available fbdma child. - Disable the fbdma child when the display DART is shared (by board default or via apple_t8122_display.dcpext_disp_dart=1), so framebuffers are never mapped twice on dispext0_dart. - Add apple_t8122_display.dcpext_disp_dart (tri-state: -1 lets the board device tree decide, 0/1 override). - Extend t8122-gate-test.dtso and display-gate-test.c to cover marker values 1/2/3, board mirroring with/without fbdma, overrides 0/1, and 27.2 firmware with mirroring. Signed-off-by: Eric Juta --- drivers/soc/apple/display-gate-test.c | 120 +++++++++++++++++++++++-- drivers/soc/apple/display-gate.c | 63 +++++++++++-- drivers/soc/apple/t8122-gate-test.dtso | 5 ++ 3 files changed, 174 insertions(+), 14 deletions(-) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index c662de976f7af8..055fe5b32e120e 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -155,6 +155,7 @@ static int gt_fixture_t6041 __initdata = -1; static int gt_live_soc __initdata = -1; struct gate_test { + int dcpext_disp_dart; /* apple_t8122_display.dcpext_disp_dart, as booted */ const struct gt_soc *s; struct of_changeset cs; /* this case's own edits to the test tree */ bool requested, t6031_requested; @@ -184,6 +185,13 @@ static void __init gt_remove(struct kunit *test, const char *path, const char *n KUNIT_ASSERT_EQ(test, of_changeset_remove_property(&t->cs, np, prop), 0); } +static void __init gt_add_bool(struct kunit *test, const char *path, const char *name) +{ + struct gate_test *t = test->priv; + + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_bool(&t->cs, gt_node(test, path), name), 0); +} + static void __init gt_add_u32(struct kunit *test, const char *path, const char *name, u32 val) { struct gate_test *t = test->priv; @@ -407,6 +415,8 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) return -ENOMEM; test->priv = t; t->s = s; + t->dcpext_disp_dart = gate_t8122_dcpext_disp_dart; + gate_t8122_dcpext_disp_dart = -1; t->pmp_uuid = s->pmp_uuid; /* As the boot left them: the test kernel's command line sets neither. */ t->requested = gate_requested; @@ -452,6 +462,7 @@ static void __init gt_exit(struct kunit *test) gate_cs_free(gate_t8122_dcpext_cs); gate_t8122_dcpext_cs = NULL; } + gate_t8122_dcpext_disp_dart = t->dcpext_disp_dart; /* The gate leaves its changes applied only when it enabled the display. */ if (gate_pmp_ovcs) { of_changeset_revert(&gate_pmp_cs); @@ -979,10 +990,13 @@ static void __init gt_expect_window(struct kunit *test, const char *path, const /* * The panel as gt_expect_enabled() checks it, and the dcpext enabled or not - * with all it needs. @window: the window both dcpext DARTs must have, NULL - * for the device tree's own. + * with all it needs. When enabled, @shared says whether its scanout DART joins + * the display subsystem's domain (disabling fbdma) or stays out (leaving fbdma + * available for framebuffer mirroring). @window: the window both dcpext DARTs + * must have, NULL for the device tree's own. */ -static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 *window) +static void __init gt_expect_dcpext_mode(struct kunit *test, bool enabled, bool shared, + const u64 *window) { struct device_node *display = gt_node(test, gt_t8122.display); struct device_node *entry = gt_node(test, GT_T8122_DCPEXT_ENTRY); @@ -998,14 +1012,17 @@ static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 KUNIT_EXPECT_EQ(test, of_property_read_bool(entry, "apple,defer-startup-ack"), enabled); KUNIT_EXPECT_EQ(test, gt_u32(test, GT_T8122_DCPEXT_PS, "apple,min-state"), enabled ? PMGR_PS_ACTIVE : 4); - /* Its scanout DART joins the display subsystem's, after the panel's. */ KUNIT_EXPECT_EQ(test, of_count_phandle_with_args(display, "iommus", "#iommu-cells"), - enabled ? 2 : 1); + (enabled && shared) ? 2 : 1); if (enabled) { - KUNIT_ASSERT_EQ(test, of_parse_phandle_with_args(display, "iommus", - "#iommu-cells", 1, &args), 0); - KUNIT_EXPECT_PTR_EQ(test, args.np, gt_node(test, GT_T8122_DISPEXT_DART)); - of_node_put(args.np); + if (shared) { + KUNIT_ASSERT_EQ(test, of_parse_phandle_with_args(display, "iommus", + "#iommu-cells", 1, &args), + 0); + KUNIT_EXPECT_PTR_EQ(test, args.np, gt_node(test, GT_T8122_DISPEXT_DART)); + of_node_put(args.np); + } + KUNIT_EXPECT_EQ(test, gt_okay(test, GT_T8122_DCPEXT "/fbdma"), !shared); } gt_expect_window(test, GT_T8122_DCPEXT_DART, window ?: gt_t8122_dcpext_window); gt_expect_window(test, GT_T8122_DISPEXT_DART, window ?: gt_t8122_dispext_window); @@ -1013,6 +1030,11 @@ static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 gt_expect_window(test, "/t8122-soc/iommu@28d30c000", gt_t8122_panel_window); } +static void __init gt_expect_dcpext(struct kunit *test, bool enabled, const u64 *window) +{ + gt_expect_dcpext_mode(test, enabled, enabled, window); +} + static void __init gt_require_display_driver(struct kunit *test) { if (!IS_ENABLED(CONFIG_DRM_APPLE)) @@ -1037,6 +1059,79 @@ static void __init gate_t8122_dcpext_v14_7(struct kunit *test) KUNIT_EXPECT_FALSE(test, apple_t8122_dcpext_v27_2(gt_node(test, GT_T8122_DCPEXT))); } +/* The boot loader's default marker (<2>) is accepted alongside <1>. */ +static void __init gate_t8122_dcpext_loader_default_marker(struct kunit *test) +{ + gt_require_display_driver(test); + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 2); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-version", gt_v14_7, 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, NULL); +} + +/* Any marker value other than 1 or 2 is refused. */ +static void __init gate_t8122_dcpext_other_marker(struct kunit *test) +{ + gt_add_u32(test, GT_T8122_DCPEXT, "apple,t8122-dcpext-firmware-ready", 3); + gt_set_u32_array(test, GT_T8122_DCPEXT, "apple,firmware-compat", gt_v14_7, 3); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* apple,no-shared-display-dart keeps dispext0_dart out and leaves fbdma on. */ +static void __init gate_t8122_dcpext_board_mirrors(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, NULL); +} + +/* apple,no-shared-display-dart without an fbdma child is refused. */ +static void __init gate_t8122_dcpext_board_no_fbdma(struct kunit *test) +{ + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_detach(test, GT_T8122_DCPEXT "/fbdma"); + gt_run(test); + gt_expect_dcpext(test, false, NULL); +} + +/* =0 keeps the DART out on a board that would share. */ +static void __init gate_t8122_dcpext_forced_unshared(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_disp_dart_setup("0"), 0); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, NULL); +} + +/* =1 shares on a board that mirrors, and disables its fbdma child. */ +static void __init gate_t8122_dcpext_forced_shared(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_disp_dart_setup("1"), 0); + gt_run(test); + gt_expect_dcpext_mode(test, true, true, NULL); +} + +/* On 27.2 with apple,no-shared-display-dart, DARTs get the panel window and fbdma stays on. */ +static void __init gate_t8122_dcpext_v27_2_mirrors(struct kunit *test) +{ + gt_require_display_driver(test); + gt_t8122_dcp_v27_2(test); + gt_t8122_dcpext_firmware(test, gt_v27_2, gt_v27_2); + gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); + gt_run(test); + gt_expect_dcpext_mode(test, true, false, gt_t8122_panel_window); +} + /* * On the 27.2 image, beside an internal DCP handed over on it, it starts * with the panel's window on both of its DARTs. @@ -1215,7 +1310,14 @@ static struct kunit_case gate_t8122_cases[] __refdata = { KUNIT_CASE(gate_t8122_not_inherited_on), KUNIT_CASE(gate_t8122_dcpext_not_ready), KUNIT_CASE(gate_t8122_dcpext_v14_7), + KUNIT_CASE(gate_t8122_dcpext_loader_default_marker), + KUNIT_CASE(gate_t8122_dcpext_other_marker), + KUNIT_CASE(gate_t8122_dcpext_board_mirrors), + KUNIT_CASE(gate_t8122_dcpext_board_no_fbdma), + KUNIT_CASE(gate_t8122_dcpext_forced_unshared), + KUNIT_CASE(gate_t8122_dcpext_forced_shared), KUNIT_CASE(gate_t8122_dcpext_v27_2), + KUNIT_CASE(gate_t8122_dcpext_v27_2_mirrors), KUNIT_CASE(gate_t8122_dcpext_v27_2_internal_v14), KUNIT_CASE(gate_t8122_dcpext_v27_2_other_version), KUNIT_CASE(gate_t8122_dcpext_v27_2_no_version), diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 8950f960b1ff9c..aa6f0179a3b585 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -1837,6 +1837,25 @@ static int __init gate_t8122_dcpext_setup(char *arg) } early_param("apple_t8122_display.dcpext", gate_t8122_dcpext_setup); +/* + * Whether the external display DART joins the display subsystem's domain: + * -1 lets the board device tree decide (apple,no-shared-display-dart keeps + * it out and mirrors framebuffers through the fbdma child instead); 0 and 1 + * override the board default. + */ +static int gate_t8122_dcpext_disp_dart __initdata = -1; + +static int __init gate_t8122_dcpext_disp_dart_setup(char *arg) +{ + bool share; + int ret = kstrtobool(arg, &share); + + if (!ret) + gate_t8122_dcpext_disp_dart = share; + return ret; +} +early_param("apple_t8122_display.dcpext_disp_dart", gate_t8122_dcpext_disp_dart_setup); + /* The most display crossbars a T8122 dcpext's routes switch: ATC0's and ATC1's. */ #define GATE_T8122_XBARS 2 @@ -1935,16 +1954,32 @@ static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, return ret; } +/* + * Does @np's display DART go into the display subsystem's domain? 1 or 0, + * or -ENODEV on a board that forbids it and has no @fbdma child to mirror + * framebuffers through: the dcpext then has no way to scan them out. + */ +static int __init gate_t8122_dcpext_shares_dart(struct device_node *np, + struct device_node *fbdma) +{ + if (gate_t8122_dcpext_disp_dart >= 0) + return gate_t8122_dcpext_disp_dart; + if (!of_property_read_bool(np, "apple,no-shared-display-dart")) + return 1; + return fbdma ? 0 : -ENODEV; +} + static void __init gate_t8122_dcpext_one(struct device_node *np) { struct device_node *dart = NULL, *mbox = NULL, *piodma = NULL; struct device_node *disp_dart = NULL, *ps = NULL, *entry = NULL, *link; + struct device_node *fbdma = NULL; struct device_node *xbar[GATE_T8122_XBARS] = {}; struct device_node *common[GATE_T8122_XBARS] = {}; struct of_phandle_args args; struct of_changeset *cs; const char *label; - int ret, i, nxbar = 0; + int share_dart, ret, i, nxbar = 0; u32 ready; if (!gate_disabled(np)) { @@ -1952,7 +1987,7 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) return; } if (of_property_read_u32(np, "apple,t8122-dcpext-firmware-ready", &ready) || - ready != 1) { + (ready != 1 && ready != 2)) { gate_ext_refuse(np, "the boot loader did not reserve its firmware"); return; } @@ -1964,6 +1999,13 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) gate_ext_refuse(np, "it has no firmware memory"); goto put; } + fbdma = of_get_available_child_by_name(np, "fbdma"); + share_dart = gate_t8122_dcpext_shares_dart(np, fbdma); + if (share_dart < 0) { + gate_ext_refuse(np, + "apple,no-shared-display-dart without an fbdma child to mirror framebuffers through"); + goto put; + } dart = gate_target(np, "iommus", "#iommu-cells", 1, 5, "apple,t8110-dart"); mbox = gate_target(np, "mboxes", "#mbox-cells", 0, 0, "apple,asc-mailbox-v4"); piodma = of_get_child_by_name(np, "piodma"); @@ -2059,8 +2101,18 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) ret = of_changeset_update_prop_string(cs, np, "status", "okay"); if (!ret) ret = gate_ext_routes(cs, np, "okay"); - if (!ret) + if (!ret && share_dart) { ret = gate_display_add_dart(cs, disp_dart); + /* The shared domain maps what fbdma would, at the same addresses. */ + if (!ret && fbdma) { + ret = of_changeset_update_prop_string(cs, fbdma, "status", "disabled"); + gate_warn("%pOF: display DART %pOF shared with the display subsystem; %pOF disabled\n", + np, disp_dart, fbdma); + } + } else if (!ret) { + gate_info("%pOF: display DART %pOF kept out of the display subsystem; framebuffers are mirrored\n", + np, disp_dart); + } if (!ret) ret = of_changeset_apply(cs); if (ret) { @@ -2070,13 +2122,14 @@ static void __init gate_t8122_dcpext_one(struct device_node *np) goto put; } gate_t8122_dcpext_cs = cs; - gate_info("enabled %pOF with its Type-C routes, DARTs, mailbox, %d display crossbar(s) with ATC common power kept on, display DART %pOF in the display subsystem, CPU power floor and PMP DISPEXT request; started by the display driver\n", - np, nxbar, disp_dart); + gate_info("enabled %pOF with its Type-C routes, DARTs, mailbox, %d display crossbar(s) with ATC common power kept on, display DART %pOF %s the display subsystem, CPU power floor and PMP DISPEXT request; started by the display driver\n", + np, nxbar, disp_dart, share_dart ? "in" : "kept out of"); put: for (i = 0; i < GATE_T8122_XBARS; i++) { of_node_put(common[i]); of_node_put(xbar[i]); } + of_node_put(fbdma); of_node_put(entry); of_node_put(ps); of_node_put(disp_dart); diff --git a/drivers/soc/apple/t8122-gate-test.dtso b/drivers/soc/apple/t8122-gate-test.dtso index 835a38a4e935e5..850f3cebb4a23e 100644 --- a/drivers/soc/apple/t8122-gate-test.dtso +++ b/drivers/soc/apple/t8122-gate-test.dtso @@ -275,6 +275,11 @@ piodma { iommus = <&t8122_dispext0_dart 4>; }; + + fbdma { + iommus = <&t8122_dispext0_dart 0>; + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; + }; }; display-subsystem { From 535f1cb4ec54908ef43a682e6f3c1ce532375169 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Tue, 24 Nov 2026 21:21:46 +0000 Subject: [PATCH 1134/1514] drm/apple: mirror framebuffers into a dcpext's fbdma DART When the display gate keeps a T8122 dcpext's display DART out of the display subsystem's shared IOMMU domain (apple,no-shared-display-dart), the external pipe scans framebuffers through a DART stream nothing maps. Mirror framebuffers read-only into the dcpext's available fbdma child domain at the display subsystem's DVAs: - Create the optional fbdma child platform device during pipe bind when an available fbdma child node is present (the display gate disables it when the display DART is shared instead). - Walk the display subsystem IOMMU domain's own translations via iommu_iova_to_phys() so both native and imported buffers are mirrored without reaching into an exporter's scatterlist, coalescing contiguous physical runs and rolling back partial mappings on failure. - Track mirrored GEM objects in an xarray and unmap each object from every apple_crtc (skipping t8132_ext_crtc) before drm_gem_dma_object_free() releases its pages and DVA; drop all mirrors before tearing down the fbdma device. Signed-off-by: Eric Juta --- drivers/gpu/drm/apple/apple_drv.c | 37 ++++++ drivers/gpu/drm/apple/dcp-internal.h | 13 ++ drivers/gpu/drm/apple/dcp.c | 171 +++++++++++++++++++++++++ drivers/gpu/drm/apple/dcp.h | 3 + drivers/gpu/drm/apple/iomfb_template.c | 1 + 5 files changed, 225 insertions(+) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 17d1416d636d23..d7958f030e2091 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -223,6 +223,42 @@ static int apple_drm_gem_dumb_create(struct drm_file *file_priv, return drm_gem_dma_dumb_create_internal(file_priv, drm, args); } +/* + * A T8122 dcpext mirrors framebuffers into its own display DART domain. + * Remove a buffer's mirror before its pages and its DVA are released. + */ +static void apple_drm_gem_free(struct drm_gem_object *gem) +{ + struct drm_crtc *crtc; + + drm_for_each_crtc(crtc, gem->dev) { + if (t8132_ext_crtc(crtc)) + continue; + dcp_fb_unmirror(to_apple_crtc(crtc)->dcp, to_drm_gem_dma_obj(gem)); + } + drm_gem_dma_object_free(gem); +} + +static const struct drm_gem_object_funcs apple_drm_gem_funcs = { + .free = apple_drm_gem_free, + .print_info = drm_gem_dma_object_print_info, + .get_sg_table = drm_gem_dma_object_get_sg_table, + .vmap = drm_gem_dma_object_vmap, + .mmap = drm_gem_dma_object_mmap, + .vm_ops = &drm_gem_dma_vm_ops, +}; + +static struct drm_gem_object *apple_drm_gem_create_object(struct drm_device *drm, + size_t size) +{ + struct drm_gem_dma_object *obj = kzalloc_obj(*obj); + + if (!obj) + return ERR_PTR(-ENOMEM); + obj->base.funcs = &apple_drm_gem_funcs; + return &obj->base; +} + #ifdef CONFIG_DRM_FBDEV_EMULATION static int apple_drm_fbdev_probe(struct drm_fb_helper *helper, struct drm_fb_helper_surface_size *sizes) @@ -351,6 +387,7 @@ static const struct drm_driver apple_drm_driver = { DRM_FBDEV_DMA_DRIVER_OPS, #endif .postclose = apple_drm_postclose, + .gem_create_object = apple_drm_gem_create_object, .name = DRIVER_NAME, .desc = DRIVER_DESC, .major = 1, diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 2c3899445803a8..a18f812ef62905 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -540,6 +541,18 @@ struct apple_dcp { struct platform_device *piodma; bool piodma_created; struct iommu_domain *iommu_dom; + /* + * J615 dcpext: a child device on the display DART stream the external + * pipe scans framebuffers through. Framebuffers are mirrored into its + * domain at the display subsystem's addresses. fb_mirrors holds the + * mapped length of every mirrored GEM object, indexed by the object's + * address, until the object is freed; fb_mirror_lock protects it and + * fb_dom. + */ + struct platform_device *fbdma; + struct iommu_domain *fb_dom; + struct xarray fb_mirrors; + struct mutex fb_mirror_lock; /* which of the nine cumulative A031 notify-client states to send next */ unsigned int a031_step; struct apple_rtkit *rtk; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 76092501c2bd4b..e975696619ba2f 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -5688,12 +5689,35 @@ static void dcp_work_backlight_fallback(struct work_struct *work) dev_warn(dcp->dev, "backlight registration failed: %d\n", ret); } +/* Drop every framebuffer mirror before the fbdma domain goes away. */ +static void dcp_fb_unmirror_all(struct apple_dcp *dcp) +{ + unsigned long index; + void *entry; + + guard(mutex)(&dcp->fb_mirror_lock); + if (dcp->fb_dom) { + xa_for_each(&dcp->fb_mirrors, index, entry) { + /* An object stays in fb_mirrors only while it is alive. */ + struct drm_gem_dma_object *obj = (void *)index; + + iommu_unmap(dcp->fb_dom, obj->dma_addr, xa_to_value(entry)); + } + } + xa_destroy(&dcp->fb_mirrors); + WRITE_ONCE(dcp->fb_dom, NULL); +} + static void dcp_release_piodma_iommu_dev(struct apple_dcp *dcp) { if (dcp->retain_dma) { WRITE_ONCE(dcp->quiescing, true); return; } + dcp_fb_unmirror_all(dcp); + if (dcp->fbdma) + of_platform_device_destroy(&dcp->fbdma->dev, NULL); + dcp->fbdma = NULL; if (dcp->piodma) { if (dcp->piodma_created) of_platform_device_destroy(&dcp->piodma->dev, NULL); @@ -5705,6 +5729,149 @@ static void dcp_release_piodma_iommu_dev(struct apple_dcp *dcp) dcp->piodma_created = false; } +/* + * J615 dcpext: the external pipe reads framebuffers through its + * own display DART, not the internal one the display subsystem's domain + * covers. An "fbdma" child, on that DART's stream 0 with the display + * subsystem's DVA window, gets a domain the framebuffers are mirrored into. + * Without the node nothing changes. The display gate disables the node when + * it shares that DART with the display subsystem instead, whose domain then + * already maps every framebuffer there. + */ +static void dcp_create_fbdma_dev(struct apple_dcp *dcp) +{ + struct device_node *node; + struct iommu_domain *dom; + int ret; + + if (!dcp->ext_failsafe || dcp->fbdma) + return; + node = of_get_available_child_by_name(dcp->dev->of_node, "fbdma"); + if (!node) + return; + dcp->fbdma = of_platform_device_create(node, NULL, dcp->dev); + if (!dcp->fbdma) { + dev_warn(dcp->dev, "fbdma: could not create %pOF\n", node); + goto out; + } + ret = dma_set_mask_and_coherent(&dcp->fbdma->dev, DMA_BIT_MASK(42)); + if (!ret) + ret = of_dma_configure(&dcp->fbdma->dev, node, true); + dom = ret ? NULL : iommu_get_domain_for_dev(&dcp->fbdma->dev); + if (IS_ERR_OR_NULL(dom)) { + dev_warn(dcp->dev, "fbdma: no IOMMU domain (%d)\n", ret); + of_platform_device_destroy(&dcp->fbdma->dev, NULL); + dcp->fbdma = NULL; + goto out; + } + scoped_guard(mutex, &dcp->fb_mirror_lock) + WRITE_ONCE(dcp->fb_dom, dom); + dev_info(dcp->dev, "fbdma: framebuffers mirrored through %pOF\n", node); +out: + of_node_put(node); +} + +/* + * Map the pages behind [@iova, @iova + @size) of @src into the fbdma domain + * at the same addresses, read-only. The pages are taken from @src's own + * translations, so this needs no scatterlist: an imported buffer's belongs + * to its exporter. Each step looks up one of @src's smallest pages, so a hole + * cannot hide inside a step; that needs both domains to share that page size. + * Returns 0, or a negative errno with nothing left mapped. + */ +static int dcp_fb_mirror_range(struct apple_dcp *dcp, struct iommu_domain *src, + dma_addr_t iova, size_t size) +{ + unsigned long pgsize; + phys_addr_t phys, run_phys = 0; + size_t off, run_len = 0, mapped = 0; + int ret = 0; + + if (!src->pgsize_bitmap || !dcp->fb_dom->pgsize_bitmap) + return -EINVAL; + pgsize = 1UL << __ffs(src->pgsize_bitmap); + if (pgsize != 1UL << __ffs(dcp->fb_dom->pgsize_bitmap) || + !IS_ALIGNED(iova | size, pgsize)) + return -EINVAL; + for (off = 0; off <= size && !ret; off += pgsize) { + phys = off < size ? iommu_iova_to_phys(src, iova + off) : 0; + if (run_len && phys && phys == run_phys + run_len) { + run_len += pgsize; + continue; + } + /* The run of physically contiguous pages ends here. */ + if (run_len) { + ret = iommu_map(dcp->fb_dom, iova + mapped, run_phys, run_len, + IOMMU_READ, GFP_KERNEL); + if (!ret) + mapped += run_len; + } + if (!ret && off < size && !phys) + ret = -EFAULT; + run_phys = phys; + run_len = pgsize; + } + if (ret && mapped) + iommu_unmap(dcp->fb_dom, iova, mapped); + return ret; +} + +/* + * Map @fb's GEM objects into the fbdma domain at their display DVAs. A + * mapping lasts as long as its object and its DVA do: dcp_fb_unmirror() + * removes it when the object is freed. + */ +void dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb) +{ + struct iommu_domain *src; + unsigned int i; + + if (!fb || !READ_ONCE(dcp->fb_dom)) + return; + src = iommu_get_domain_for_dev(drm_dev_dma_dev(fb->dev)); + guard(mutex)(&dcp->fb_mirror_lock); + if (!dcp->fb_dom || IS_ERR_OR_NULL(src)) + return; + for (i = 0; i < fb->format->num_planes; i++) { + struct drm_gem_dma_object *obj = drm_fb_dma_get_gem_obj(fb, i); + unsigned long index = (unsigned long)obj; + int ret; + + if (!obj || xa_load(&dcp->fb_mirrors, index)) + continue; + ret = dcp_fb_mirror_range(dcp, src, obj->dma_addr, obj->base.size); + if (!ret) { + ret = xa_err(xa_store(&dcp->fb_mirrors, index, + xa_mk_value(obj->base.size), GFP_KERNEL)); + if (ret) + iommu_unmap(dcp->fb_dom, obj->dma_addr, obj->base.size); + } + if (ret) + dev_warn_ratelimited(dcp->dev, + "fbdma: %pad (%zu bytes, %s) not mirrored: %d\n", + &obj->dma_addr, obj->base.size, + obj->sgt ? "imported" : "native", ret); + } +} + +/* @obj is being freed: the external pipe must not read its pages any more. */ +void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *obj) +{ + struct apple_dcp *dcp; + void *entry; + + if (!pdev) + return; + dcp = platform_get_drvdata(pdev); + if (!dcp) + return; + guard(mutex)(&dcp->fb_mirror_lock); + entry = xa_erase(&dcp->fb_mirrors, (unsigned long)obj); + if (entry && dcp->fb_dom) + iommu_unmap(dcp->fb_dom, obj->dma_addr, xa_to_value(entry)); +} +EXPORT_SYMBOL_GPL(dcp_fb_unmirror); + void dcp_retain_framebuffer(struct platform_device *pdev, struct dcp_fb_reference *entry) { @@ -6875,6 +7042,8 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat } ret = dcp_create_piodma_iommu_dev(dcp); + if (!ret) + dcp_create_fbdma_dev(dcp); if (ret) return dev_err_probe(dev, ret, "Failed to create PIODMA iommu child device\n"); @@ -7505,6 +7674,8 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) INIT_LIST_HEAD(&dcp->swapped_out_fbs); mutex_init(&dcp->swapped_out_fbs_lock); + xa_init(&dcp->fb_mirrors); + mutex_init(&dcp->fb_mirror_lock); ret = dcp_backlight_init(dcp, dev); if (ret) return ret; diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 0989d8d6a2437e..ae18e4b10a7a7e 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -114,6 +114,9 @@ void dcp_retain_framebuffer(struct platform_device *pdev, struct dcp_fb_reference *entry); void dcp_arm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); void dcp_unarm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); +void dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb); +struct drm_gem_dma_object; +void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *obj); void dcp_release_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); void dcp_release_all_retained_framebuffers(struct apple_dcp *dcp); bool dcp_is_initialized(struct platform_device *pdev); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index dd32d3a8e37ef8..facec945918f67 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4559,6 +4559,7 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru if (dcp->notch_height > 0) req->swap.dst_rect[l].y += dcp->notch_height; + dcp_fb_mirror(dcp, new_state->fb); req->surf_iova[l] = apple_state->iova; req->surf[l].base = apple_state->surf; #if DCP_FW_H17(DCP_FW_VER) From 0a1289fc6015b3b9f69562f030d146c900ece001 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Tue, 24 Nov 2026 21:22:36 +0000 Subject: [PATCH 1135/1514] arm64: dts: apple: t8122-j615: keep dcpext display DART unshared and wire fbdma On the J615 (MacBook Air 15", M3), sharing dispext0_dart with the display subsystem's IOMMU domain triggers internal DCP DART faults. Mark &dcpext with apple,no-shared-display-dart and add the fbdma child on dispext0_dart stream 0 with the display subsystem's DVA window so appledrm mirrors framebuffers there instead. The Type-C routes remain shared with the J613 in t8122-j613-j615.dtsi. Signed-off-by: Eric Juta --- arch/arm64/boot/dts/apple/t8122-j615.dts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index dc1c4214ab75e0..aeb7f5aa9a9beb 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -205,3 +205,19 @@ &port00 { supports-clkreq; }; + +/* + * The dcpext wiring is shared with the J613 (t8122-j613-j615.dtsi). fbdma is + * the display DART stream the dcpext scans framebuffers through, with the + * display subsystem's DVA window: on the J615 the gate must not add + * dispext0_dart to the display subsystem (apple,no-shared-display-dart), so + * appledrm mirrors framebuffers there instead. + */ +&dcpext { + apple,no-shared-display-dart; + + fbdma { + iommus = <&dispext0_dart 0>; + apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; + }; +}; From 1293f29cf8f6377ec0516e03871c9020f5fa55a7 Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Tue, 24 Nov 2026 16:55:06 -0500 Subject: [PATCH 1136/1514] soc: apple: apply the T8132 PMGR policy without a PMP provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diljit Singh’s original #2588 change selected the PMGR policy by the T8132 PMGR compatible. Implement its PMGR-only case alongside the merged PMP handoff, preserving current memory compatibility behavior on all firmware when the PMP provider exists. Link: https://github.com/aurora-silicon/linux/pull/2588 Signed-off-by: Sean Dolbec --- drivers/soc/apple/t8132-platform-handoff.c | 25 ++++++++++++++-------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/drivers/soc/apple/t8132-platform-handoff.c b/drivers/soc/apple/t8132-platform-handoff.c index 0061a7892b8dab..5a959c270477a3 100644 --- a/drivers/soc/apple/t8132-platform-handoff.c +++ b/drivers/soc/apple/t8132-platform-handoff.c @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Supply missing platform descriptions for the original J713 loader ABI, - * which the J715 shares, and the M4 PMGR ownership policy on the qualified - * firmware for every M4 Mac. + * which the J715 shares, and apply the M4 PMGR ownership policy wherever + * the T8132 PMGR is described. * Keep the shared m1n1 payload usable by the stable kernel. Hardware control * remains in the ordinary MCC, PMC and CLPC drivers, with one DTS data source. * J713 PMGR ownership/status also comes from its board DTS, before any domain @@ -320,14 +320,18 @@ static int __init t8132_platform_handoff(void) int root, node, ret; /* - * Key the handoff on the PMP node's own compatible rather than the root - * SoC compatible or OS firmware version. The copy only adds nodes the - * loader's tree lacks, and the PMP path they depend on runs on every - * firmware whose image header names its data segment. + * The memory descriptions follow the PMP provider. PMGR ownership + * also applies to trees which describe the PMGR without a PMP. */ pmp = of_find_compatible_node(NULL, NULL, "apple,t8132-pmp-v2"); - if (!pmp) - return 0; + if (!pmp) { + struct device_node *pmgr; + + pmgr = of_find_compatible_node(NULL, NULL, "apple,t8132-pmgr"); + if (!pmgr) + return 0; + of_node_put(pmgr); + } if (fdt_check_header(data)) { ret = -EINVAL; goto out; @@ -347,11 +351,14 @@ static int __init t8132_platform_handoff(void) if (ret) goto destroy; + if (!pmp) + goto apply; + gpu = of_find_compatible_node(NULL, NULL, "apple,agx-t8132"); gfx = gpu ? of_parse_phandle(gpu, "power-domains", 0) : NULL; if (!gfx) gfx = t8132_find_gfx(); - if (!pmp || !gfx || !pmp->phandle || !gfx->phandle) { + if (!gfx || !pmp->phandle || !gfx->phandle) { pr_warn("t8132-platform-handoff: memory compatibility requires PMP/GFX providers\n"); goto apply; } From 4f7afa476c130d2b6b5184b5a9a914afe9f9c1ff Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Mon, 23 Nov 2026 21:09:45 -0500 Subject: [PATCH 1137/1514] pmdomain: apple: fail closed after the T8132 handoff With the platform handoff built, reject a T8132 power state that it did not mark on every firmware. This matches the handoff now applying the ownership policy whenever the T8132 PMGR block is present. Extend the host harness to exercise the missing-status path and confirm it fails before any MMIO. Signed-off-by: Sean Dolbec --- drivers/pmdomain/apple/pmgr-pwrstate.c | 13 ++++++---- .../selftests/drivers/apple/pmgr-inherited.py | 25 ++++++++++++++++--- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index 6745b4916365b6..0e95bba1c9aa49 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -855,12 +855,15 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) t8132 = of_device_is_compatible(node, "apple,t8132-pmgr-pwrstate"); /* - * On the M4 firmware path some domains are the firmware's, which Linux - * cannot access. The early compatibility adapter supplies the explicit - * status and ownership before population; fail closed if it was not - * enabled. Other firmware keeps the tree's own domain descriptions. + * Some T8132 power states are the firmware's, which Linux cannot + * access. The platform handoff supplies the explicit status and + * ownership of every one before population, on any firmware: fail + * closed on a state it did not mark. Keep the same protection for + * qualified firmware and the Airs even without the handoff. */ - if (t8132 && apple_t8132_firmware_path() && !of_property_present(node, "status")) + if (t8132 && (IS_ENABLED(CONFIG_APPLE_T8132_PLATFORM_HANDOFF) || + apple_t8132_firmware_path()) && + !of_property_present(node, "status")) return dev_err_probe(dev, -ENODEV, "missing M4 power-domain policy\n"); tvm = of_parse_phandle(node, "power-domains", 0); diff --git a/tools/testing/selftests/drivers/apple/pmgr-inherited.py b/tools/testing/selftests/drivers/apple/pmgr-inherited.py index affc0312450b10..5f46a3fae243bf 100755 --- a/tools/testing/selftests/drivers/apple/pmgr-inherited.py +++ b/tools/testing/selftests/drivers/apple/pmgr-inherited.py @@ -71,7 +71,7 @@ def main(): struct device_node { struct device_node *parent; const char *name, *conflict; - bool inherited, firmware; + bool inherited, firmware, status; }; struct device { struct device_node *of_node; }; struct platform_device { struct device dev; }; @@ -101,7 +101,10 @@ def main(): static int apple_pmgr_reset_ops; static int (*apple_pmgr_genpd_runtime_suspend)(struct device *dev); static unsigned parent_attach_count; -static bool apple_t8132_firmware_path(void) { return true; } +static bool platform_handoff, firmware_path; +#define CONFIG_APPLE_T8132_PLATFORM_HANDOFF platform_handoff +#define IS_ENABLED(option) (option) +static bool apple_t8132_firmware_path(void) { return firmware_path; } static bool apple_sleep_domain_is_down(struct device_node *n) { (void)n; return false; } static struct device_node *of_parse_phandle(struct device_node *n, const char *p, int i) { (void)n; (void)p; (void)i; return NULL; } @@ -109,7 +112,7 @@ def main(): { return n && !strcmp(p,"apple,t8132-pmgr-pwrstate"); } static bool of_machine_is_compatible(const char *p) { (void)p; return false; } static bool of_property_present(struct device_node *n, const char *p) -{ return !strcmp(p,"status") || (n->conflict && !strcmp(n->conflict,p)) || +{ return (n->status && !strcmp(p,"status")) || (n->conflict && !strcmp(n->conflict,p)) || (n->inherited && !strcmp(p,"apple,inherited-on")) || (n->firmware && !strcmp(p,"apple,firmware-owned")); } static bool of_property_read_bool(struct device_node *n, const char *p) @@ -183,7 +186,21 @@ def main(): { clean(value,error); struct platform_device p={ .dev.of_node=node }; return apple_pmgr_ps_probe(&p); } int main(void) { - struct device_node n={ .name="power-controller@428", .inherited=true }; + struct device_node n={ .name="power-controller@428", .inherited=true, .status=true }; + struct device_node missing=n; missing.status=false; + for (int handoff=0; handoff<=1; handoff++) { + for (int qualified=0; qualified<=1; qualified++) { + platform_handoff=handoff; + firmware_path=qualified; + if (handoff || qualified) { + assert(probe(&missing,0xff,0)==-ENODEV); + assert(!map.reads && !map.writes && !provider_count && !reset_count); + } else { + assert(!probe(&missing,0xff,0)); + assert(map.reads==1 && !map.writes && provider_count==1); + } + } + } assert(!probe(&n,0xff,0)); struct apple_pmgr_ps *ps=driver_data; assert(map.reads==1 && !map.writes && init_count==1 && provider_count==1 && reset_count==1); From b1f53e2acb8484ed0a8f87cbbedd611350db922d Mon Sep 17 00:00:00 2001 From: Sean Dolbec Date: Mon, 23 Nov 2026 21:09:45 -0500 Subject: [PATCH 1138/1514] selftests: apple: follow the current T8132 PMGR policy API Include the policy applicability helper, pass the legacy-tree argument, and update the expected J713 power-state count. This restores the focused PMGR mapping regression after the production policy gained machine-specific entries and separate legacy behavior. Signed-off-by: Sean Dolbec --- tools/testing/m4-pmgr-policy/harness.c | 17 +++++++++++------ tools/testing/m4-pmgr-policy/run.py | 5 ++++- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/tools/testing/m4-pmgr-policy/harness.c b/tools/testing/m4-pmgr-policy/harness.c index fc952be25d75dd..60be1f4625c652 100644 --- a/tools/testing/m4-pmgr-policy/harness.c +++ b/tools/testing/m4-pmgr-policy/harness.c @@ -73,6 +73,11 @@ static bool of_property_present(const struct device_node *n, const char *name) return find_property(n, name) != NULL; } +static bool of_machine_is_compatible(const char *machine) +{ + return !strcmp(machine, "apple,j713"); +} + static int of_property_read_string(const struct device_node *n, const char *name, const char **s) { @@ -412,7 +417,7 @@ static unsigned int validate_policy(const char *name, unsigned int staged) enabled += available(n); owned += of_property_present(n, "apple,firmware-owned"); } - CHECK(domains == 129); + CHECK(domains == 145); printf("%s: staged=%u enabled=%u/%u firmware_owned=%u mismatches=%u\n", name, staged, enabled, domains, owned, mismatches); return mismatches; @@ -431,7 +436,7 @@ static unsigned int run_case(const char *name, const char *live_path, struct of_changeset cs = { 0 }; unsigned int changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, !native) == 0); CHECK(changed == cs.count); unsigned int staged = cs.count; @@ -465,7 +470,7 @@ static void run_errors(const char *legacy) struct of_changeset cs = { 0 }; unsigned int changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == 0); total = cs.count; discard(&cs); free_fixture(); @@ -475,7 +480,7 @@ static void run_errors(const char *legacy) cs.fail_at = fail; changed = 0; - CHECK(t8132_pmgr_policy(&cs, &changed) == -ENOMEM); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == -ENOMEM); CHECK(cs.count == fail - 1 && changed == cs.count); CHECK(state_hash() == before); /* Abort staging: caller must not apply it. */ @@ -496,7 +501,7 @@ static void run_errors(const char *legacy) free(parent->full_name); parent->full_name = strdup("power-management@deadbeef"); - CHECK(t8132_pmgr_policy(&cs, &changed) == -EINVAL); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == -EINVAL); CHECK(state_hash() == before); if (i == 0) CHECK(cs.count == 0); @@ -515,7 +520,7 @@ static void run_errors(const char *legacy) const char compat[] = "apple,t8132-pmgr-pwrstate"; set_property(unknown, "compatible", compat, sizeof(compat)); - CHECK(t8132_pmgr_policy(&cs, &changed) == 0); + CHECK(t8132_pmgr_policy(&cs, &changed, true) == 0); apply(&cs); CHECK(!available(unknown)); CHECK(available(by_path( diff --git a/tools/testing/m4-pmgr-policy/run.py b/tools/testing/m4-pmgr-policy/run.py index b86c1faa892872..d16b3280aa07ea 100755 --- a/tools/testing/m4-pmgr-policy/run.py +++ b/tools/testing/m4-pmgr-policy/run.py @@ -63,6 +63,7 @@ def run(args, output): production = path.read_text() policy = block(production, "t8132_pmgr_policy") helper = block(production, "t8132_fdt_node_offset") + applies = block(production, "t8132_policy_applies") bad_lookup = "int parent = t8132_fdt_node_offset(data, pmgr);" if policy.count(bad_lookup) != 1: raise RuntimeError("Production PMGR lookup changed; update the negative control") @@ -95,7 +96,9 @@ def run(args, output): "source": str(path), "source_sha256": hashlib.sha256(production.encode()).hexdigest(), "legacy_fixture": str(args.legacy_dtb) if args.legacy_dtb else "synthesized from native DTB", } - for mode, code in [("negative-control", negative), ("production", helper + "\n" + policy)]: + helpers = helper + "\n" + applies + "\n" + for mode, code in [("negative-control", helpers + negative), + ("production", helpers + policy)]: c = output / (mode + ".c") binary = output / mode c.write_text(template.replace("/* PRODUCTION_CODE */", code)) From 4da2399972cbb9073c4ed4e4c8ef7e95860d2fa7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 09:09:38 +1100 Subject: [PATCH 1139/1514] drm/apple: dcp: take an empty firmware-27 clock table The macOS 27.2 ADT gives every T6020, T6021 and T6022 display processor (/arm-io/disp0 and each /arm-io/dispext) an empty clock-ids: the firmware takes no provider clocks. The boot loader publishes that as an empty apple,clock-ids, which the binding allows ("the provider has no clocks"). The node still lists its display clock, though, and the table was then checked against every clock of the node: one clock against an empty table returned -EINVAL, so no T602x DCP could probe on 27.2. An empty table now means no provider clocks, whatever else the node lists. The display clock stays the DCP's own clock (taken by probe as before), and the firmware is answered 0 Hz for any provider clock index it asks for, as on a T6050 external processor. Nodes with a table, and nodes with none, are handled as before. Move the clock part of dcp_firmware_metadata_v27() into dcp_firmware_clocks_v27() so KUnit can run it, and add a case for the T602x node shape. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-firmware-test.c | 33 +++++++ drivers/gpu/drm/apple/dcp.c | 108 +++++++++++++--------- 2 files changed, 97 insertions(+), 44 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-firmware-test.c b/drivers/gpu/drm/apple/dcp-firmware-test.c index ac9dce35e71212..b0990bb1c0f682 100644 --- a/drivers/gpu/drm/apple/dcp-firmware-test.c +++ b/drivers/gpu/drm/apple/dcp-firmware-test.c @@ -68,9 +68,42 @@ static void dcp_firmware_27_method_admission(struct kunit *test) KUNIT_EXPECT_EQ(test, missing, 1U); } +/* + * Firmware 27 provider clocks on a T602x display processor: the 27.2 ADT + * lists none (an empty /arm-io/disp0 and dispext clock-ids), and the + * node keeps its display clock. + */ +static void dcp_firmware_27_empty_clock_table(struct kunit *test) +{ + static const char primary[] = "apple,t6020-dcp\0apple,dcp"; + __be32 display = cpu_to_be32(1); + struct property properties[] = { + { .name = "apple,clock-ids", .length = 0, .value = &display, + .next = &properties[1] }, + { .name = "clocks", .length = sizeof(display), .value = &display, + .next = &properties[2] }, + { .name = "compatible", .length = sizeof(primary), .value = (void *)primary }, + }; + struct device_node node = { .properties = properties }; + struct device dev = { .init_name = "dcp-firmware-test", .of_node = &node }; + struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, dcp); + dcp->dev = &dev; + dcp->num_firmware_clocks = 3; + KUNIT_EXPECT_EQ(test, dcp_firmware_clocks_v27(dcp), 0); + KUNIT_EXPECT_EQ(test, dcp->num_firmware_clocks, 0U); + KUNIT_EXPECT_NULL(test, dcp->firmware_clocks); + + /* Without the table the firmware's clocks are unknown: refused. */ + properties[0].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_firmware_clocks_v27(dcp), -EINVAL); +} + static struct kunit_case dcp_firmware_cases[] = { KUNIT_CASE(dcp_firmware_13_5_compat), KUNIT_CASE(dcp_firmware_27_method_admission), + KUNIT_CASE(dcp_firmware_27_empty_clock_table), {} }; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 76092501c2bd4b..073e51f9781fec 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6455,54 +6455,15 @@ VISIBLE_IF_KUNIT void dcp_enable_typec_work(struct apple_dcp *dcp) } } -static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) +/* + * The provider clocks firmware 27 asks for by index (getClockFrequency): + * apple,clock-ids, published by the boot loader from the ADT. + */ +static int dcp_firmware_clocks_v27(struct apple_dcp *dcp) { struct device *dev = dcp->dev; - struct device_node *fb; - struct resource resource; int clocks, index, ret; - /* - * The framebuffer region is the one the boot loader scanned out of; it - * backs the firmware's default framebuffer. An external processor the - * boot loader drove no display from (T6050's dcpext4, the HDMI port's) - * has none: it binds without one, and its default-framebuffer requests - * are refused (dfb_region_size 0). - */ - index = of_property_match_string(dev->of_node, "memory-region-names", - "framebuffer"); - if (index == -ENODATA || index == -EINVAL) { - dcp->dfb_region_size = 0; - dev_info(dev, "no boot framebuffer\n"); - goto clocks; - } - if (index < 0) - return index; - fb = of_parse_phandle(dev->of_node, "memory-region", index); - if (!fb) - return -EINVAL; - ret = of_address_to_resource(fb, 0, &resource); - of_node_put(fb); - if (ret) - return ret; - dcp->dfb_region_size = resource_size(&resource); - if (!dcp->dfb_region_size) - return -EINVAL; - /* - * The boot surface is on screen until a displayed swap of ours - * replaces it. Reserve its retirement record before any present. - * Without the record the display still takes over, and a cache - * controller waiting on it keeps allocation off. - */ - ret = apple_mcc_boot_scanout_reserve(dev->of_node); - if (ret == -ENOMEM) - dev_warn(dev, "no boot scanout record: system cache allocation stays off\n"); - else if (ret) - return ret; - dcp->boot_scanout_reserved = !ret; - WRITE_ONCE(dcp->boot_surface_pending, true); - -clocks: /* * T6041 device trees carry the single 712 MHz disp0 clock unless the * boot loader publishes the two /arm-io/disp0 provider clocks @@ -6542,6 +6503,15 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) clocks = 0; if (clocks < 0 || clocks > 64) return -EINVAL; + /* + * An explicitly empty table: the firmware takes no provider clocks + * (every T602x display processor on 27.2). A display clock the node + * lists is the DCP's own clock, not a provider clock. + */ + if (!clocks) { + dcp->num_firmware_clocks = 0; + return 0; + } /* * A DCP that also boots earlier firmware (T8142) lists the clock those * use first and names the provider clocks "firmware-". Take only @@ -6575,6 +6545,56 @@ static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) return 0; } +static int dcp_firmware_metadata_v27(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + struct device_node *fb; + struct resource resource; + int index, ret; + + /* + * The framebuffer region is the one the boot loader scanned out of; it + * backs the firmware's default framebuffer. An external processor the + * boot loader drove no display from (T6050's dcpext4, the HDMI port's) + * has none: it binds without one, and its default-framebuffer requests + * are refused (dfb_region_size 0). + */ + index = of_property_match_string(dev->of_node, "memory-region-names", + "framebuffer"); + if (index == -ENODATA || index == -EINVAL) { + dcp->dfb_region_size = 0; + dev_info(dev, "no boot framebuffer\n"); + return dcp_firmware_clocks_v27(dcp); + } + if (index < 0) + return index; + fb = of_parse_phandle(dev->of_node, "memory-region", index); + if (!fb) + return -EINVAL; + ret = of_address_to_resource(fb, 0, &resource); + of_node_put(fb); + if (ret) + return ret; + dcp->dfb_region_size = resource_size(&resource); + if (!dcp->dfb_region_size) + return -EINVAL; + /* + * The boot surface is on screen until a displayed swap of ours + * replaces it. Reserve its retirement record before any present. + * Without the record the display still takes over, and a cache + * controller waiting on it keeps allocation off. + */ + ret = apple_mcc_boot_scanout_reserve(dev->of_node); + if (ret == -ENOMEM) + dev_warn(dev, "no boot scanout record: system cache allocation stays off\n"); + else if (ret) + return ret; + dcp->boot_scanout_reserved = !ret; + WRITE_ONCE(dcp->boot_surface_pending, true); + + return dcp_firmware_clocks_v27(dcp); +} + static bool dcp_external_is_idle(struct apple_dcp *dcp) { u32 control = readl_relaxed(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); From d96a319663bbe5d30681db985114cba80d71a8f2 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 11:44:23 -0800 Subject: [PATCH 1140/1514] arm64: dts: apple: t6050-j775d: enable the AOP over its RTKit mailbox alone, so the Mac Studio gets its sound card The T6050 tree describes the AOP, its mailboxes, its DART and the audio DMA controller disabled, and the J775D board file did not enable them, so the Mac Studio's (J775D) AOP never probed and no sound card registered. Its AOP firmware also does not service the setup port. Started through both mailboxes, its boot timed out after 15 s ("setup port: boot incomplete (AP power on: false, endpoints: 0/0)", probe -110) on the 27.0 and the 27.2 firmware. Read after the timeout, the setup mailbox still held the AP's message, its receive side had raised no interrupt and nothing was queued towards the AP, while the RTKit mailbox had carried the boot up to AP power on. Enable the AOP, its RTKit mailbox, its DART and the audio DMA controller, as the J714s, K114c and K116s board files do, and give the AOP only its RTKit mailbox. The driver takes the setup-port boot only when the AOP is given a mailbox named "setup", so it boots the AOP over RTKit: the firmware announces its audio service, the audio child device binds and the headphone jack's card registers. The setup mailbox node stays described, disabled. The ADT describes the setup port the same way on boards whose firmware uses it, so the board's tree is where this is stated. The Mac Studio audio file said the AOP audio node exists only after a boot loader handoff; it now says it exists once the board enables the AOP. Signed-off-by: Jeff Queisser --- arch/arm64/boot/dts/apple/t6050-j775d.dts | 24 +++++++++++++++++++ .../boot/dts/apple/t6050-studio-audio.dtsi | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index 4d527a6417f830..2f928a1584e799 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -55,6 +55,30 @@ model = "Mac Studio J775D"; }; +/* + * The AOP, with its RTKit mailbox, its DART and the audio DMA controller, booted over the RTKit + * mailbox alone. This board's AOP firmware does not service the setup port: started through both, + * it sends nothing there and leaves the AP's message unread. The setup mailbox stays described, + * disabled. + */ +&aop_mbox { + status = "okay"; +}; + +&aop_dart { + status = "okay"; +}; + +&admac_base_ns { + status = "okay"; +}; + +&aop { + mboxes = <&aop_mbox>; + mbox-names = "mbox"; + status = "okay"; +}; + /* * PCIe ports 2 (the onboard 10 Gb Ethernet) and 3 (the rear USB-A xHCI). The boot loader * powers and trains both links; it disables a port, and its DART, whose link did not come up. diff --git a/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi b/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi index 07195f5be9841d..1a60bbf3e2b06d 100644 --- a/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-studio-audio.dtsi @@ -3,7 +3,7 @@ * The audio of the M5 Mac Studio (J775c, J775d): the headphone jack (a * CS42L84) and the built-in speaker (one SN012776), both reached through the * AOP's audio services. The card waits for its CPU component, the AOP audio - * node, which exists only after the boot loader's AOP handoff. + * node, which exists once the board enables the AOP. * * The speaker is described but stays off: the ADT's audio-speaker stream has * no RX (sense) slot, and macaudio admits the speaker only once a protection From fae8191fafbaf4c3ce2452de48f58e7169ec236c Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:24:59 +0000 Subject: [PATCH 1141/1514] drm/asahi: g17: lift non-M5 effort immediately for waited compute submissions On non-M5 G17 GPUs (G17P), InitData::submission_effort() caps Region C effort to active_effort (bottom+1 P-state) until BusyRuns::bound() observes 16 ms of continuous execution with no gap >= 2 ms. A depth-1 compute burst starting cold or resuming after a > 2 ms CPU gap therefore runs at bottom+1 clock for its first 16 ms, and workloads with 2-15 ms CPU gaps between dispatches never reach FULL_EFFORT at all. Generic render waiters cannot be used to lift effort on non-M5 G17 firmware because paced desktop compositors and frame-capped games wait on their own render/present fences. Pure-compute submissions (!has_render) do not share that pattern: track host waits on pure-compute output fences separately from generic waiters, handling both unscoped ExportFence outputs and cumulative asahi_g17_scope outputs while suppressing internal scope-to-scope chaining in asahi_g17_scope_create() so unwaited async compute chains never trigger false positives. When a host thread begins waiting on a pure-compute output while any registered non-M5 G17 device has Region C below FULL_EFFORT, wake its event worker via an irqsave-protected target registry so even the first cold dispatch lifts immediately to FULL_EFFORT. Once at FULL_EFFORT the waiter hook reduces to a single atomic check with no locks or wakeups. Effort::note_compute_waiters() holds for IDLE_HOLD_NS (16 ms) and expires back to active_effort even while a compositor keeps the GPU streaming, and Effort::idle() still clears effort to 0 after 16 ms idle so idle power gating is unchanged. M5 firmware protocol effort behavior is unchanged. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/asahi_core.rs | 2 + drivers/gpu/drm/asahi/g17/fence.rs | 56 ++++++- drivers/gpu/drm/asahi/g17/initdata.rs | 33 ++-- drivers/gpu/drm/asahi/g17/mod.rs | 196 ++++++++++++++++++++++- drivers/gpu/drm/asahi/g17/power.rs | 74 +++++++++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 9 +- drivers/gpu/drm/asahi/g17/runtime.rs | 9 +- drivers/gpu/drm/asahi/g17/sync_output.c | 5 +- drivers/gpu/drm/asahi/g17/sync_output.h | 2 +- drivers/gpu/drm/asahi/g17/sync_output.rs | 6 +- drivers/gpu/drm/asahi/g17/sync_scope.c | 37 ++++- drivers/gpu/drm/asahi/g17/sync_scope.h | 5 +- tools/asahi/g15-probe-init-tests.py | 4 + tools/asahi/g17-m5-effort-tests.py | 30 ++-- 14 files changed, 429 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 3671bf0d20e304..7c570d3d901f2d 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -111,6 +111,8 @@ impl kernel::InPlaceModule for DriverModule { unsafe { queue_share::init() }; // SAFETY: Module init runs once, before either adapter is registered below. unsafe { g17::exec_share::init() }; + // SAFETY: Module init runs once, before either adapter is registered below. + unsafe { g17::init() }; try_pin_init!(Self { // Initialize the queue first, before registration can invoke probe. _cleanup: cleanup::QueueOwner::new()?, diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index 5184dc44047aac..04df5e4aa9fd64 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -63,8 +63,11 @@ pub(crate) fn allocation_failure(contexts: &FenceContexts) -> Result { pub(crate) struct ExportFence { source: Option>, scoped: bool, + compute_only: bool, /// A waiter enabled signalling on this ioctl output fence before it signalled ([`waiters`]). waited: AtomicBool, + /// A host waiter enabled signalling on this unscoped pure-compute output fence. + compute_waited: AtomicBool, } static EXPORT_OPS: AtomicUsize = AtomicUsize::new(0); @@ -72,6 +75,10 @@ static EXPORT_OPS: AtomicUsize = AtomicUsize::new(0); static WAITERS: AtomicU32 = AtomicU32::new(0); /// Waits begun on output fences, ever. static WAITS: AtomicU64 = AtomicU64::new(0); +/// Pure-compute output fences a host waiter is blocked on now. +static COMPUTE_WAITERS: AtomicU32 = AtomicU32::new(0); +/// Host waits begun on pure-compute output fences, ever. +static COMPUTE_WAITS: AtomicU64 = AtomicU64::new(0); /// The output fences a waiter is blocked on now, and the waits begun so far: the work a host /// thread waits for, which the M5 performance effort follows ([`super::power::Effort`]). @@ -79,6 +86,31 @@ pub(crate) fn waiters() -> (u32, u64) { (WAITERS.load(Ordering::Acquire), WAITS.load(Ordering::Acquire)) } +/// Pure-compute output fences a host thread is blocked on now, and total waits begun. +/// Scoped cumulative outputs count waits on their exported scope (excluding internal scope +/// chaining); unscoped outputs count waits directly on `ExportFence`. +pub(crate) fn compute_waiters() -> (u32, u64) { + ( + COMPUTE_WAITERS.load(Ordering::Acquire), + COMPUTE_WAITS.load(Ordering::Acquire), + ) +} + +/// Called from fence `enable_signaling` (atomic, under `dma_fence->lock` with IRQs off) when a +/// host thread begins waiting on a pure-compute output fence. +#[no_mangle] +pub(super) extern "C" fn asahi_g17_note_compute_waiter() { + COMPUTE_WAITERS.fetch_add(1, Ordering::AcqRel); + COMPUTE_WAITS.fetch_add(1, Ordering::AcqRel); + super::wake_for_compute_waiter(); +} + +/// Called once a previously waited pure-compute output fence signals or is released. +#[no_mangle] +pub(super) extern "C" fn asahi_g17_unnote_compute_waiter() { + COMPUTE_WAITERS.fetch_sub(1, Ordering::AcqRel); +} + /// The first waiter on an unsignalled output fence (the fence core calls this once, under the /// fence's lock). fn waited(flag: &AtomicBool) { @@ -95,9 +127,22 @@ fn unwaited(flag: &AtomicBool) { } } +fn compute_waited(flag: &AtomicBool) { + if !flag.swap(true, Ordering::AcqRel) { + asahi_g17_note_compute_waiter(); + } +} + +fn compute_unwaited(flag: &AtomicBool) { + if flag.swap(false, Ordering::AcqRel) { + asahi_g17_unnote_compute_waiter(); + } +} + impl Drop for ExportFence { fn drop(&mut self) { unwaited(&self.waited); + compute_unwaited(&self.compute_waited); } } @@ -111,6 +156,9 @@ impl FenceOps for ExportFence { } fn enable_signaling(self: &FenceObject) -> bool { waited(&self.waited); + if self.compute_only && !self.scoped { + compute_waited(&self.compute_waited); + } true } } @@ -122,7 +170,9 @@ fn export_fallback(contexts: &FenceContexts) -> Result> ExportFence { source: None, scoped: false, + compute_only: false, waited: AtomicBool::new(false), + compute_waited: AtomicBool::new(false), }, )?; // SAFETY: Unique, initialized and still private. Only this constructor @@ -280,6 +330,7 @@ impl Submission { fence.signal(); } unwaited(&fence.waited); + compute_unwaited(&fence.compute_waited); } } } @@ -526,15 +577,17 @@ impl Outputs { &mut self, context: Arc, firmware_source: bool, + compute_only: bool, ) -> Result { let source = Submission::new(context, firmware_source)?; let mut fence = self.fallback.take().ok_or(EINVAL)?; fence.source = Some(source); fence.scoped = self.cumulative.is_some(); + fence.compute_only = compute_only; let submission = Aggregate(fence.into()); self.submission = Some(submission.clone()); if let Some(bundle) = &mut self.cumulative { - bundle.publish(&submission.fence())?; + bundle.publish(&submission.fence(), compute_only)?; self.syncs.truncate(self.input_count); } else { install(self.syncs.drain(self.input_count..), &submission.fence()); @@ -573,6 +626,7 @@ impl Drop for Outputs { ); fallback.signal(); unwaited(&fallback.waited); + compute_unwaited(&fallback.compute_waited); } } } diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index ea107088cc7170..5a689c60e37f76 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -1685,18 +1685,33 @@ impl InitData { /// pipelined compute and render loops that keep the GPU continuously busy without blocking on /// an unsignalled fence would otherwise fall to the base performance state. /// - /// The other G17 SoCs publish the full effort while `bound`, and stream other work with the - /// lowest effort that keeps it above the base performance state ([`active_effort`]), leaving - /// the rest to the firmware: work that the firmware let fall to the base state stalled the GPU - /// under concurrent load (a firmware recovery with no fault), and a full effort on every - /// submission held the top state whatever the load. A waiter doesn't tell paced work from a - /// submit-and-wait loop, because paced work has one too (the compositor, or the next frame's - /// fence). - pub(super) fn submission_effort(&self, effort: u32, waited: bool, bound: bool) -> u32 { + /// The other G17 SoCs publish the full effort while `bound` or while a host thread is waiting + /// on a pure-compute submission (`compute_waited`): a submit-and-wait loop queues nothing + /// behind its command, so the firmware alone keeps it at the bottom state however busy the GPU + /// is, and a compute burst resuming after a CPU gap longer than the 2 ms firmware idle-off + /// delay would otherwise run at [`active_effort`] for 16 ms before `BusyRuns::bound` fires. + /// Other work streams with the lowest effort that keeps it above the base performance state + /// ([`active_effort`]), leaving the rest to the firmware: work that the firmware let fall to + /// the base state stalled the GPU under concurrent load (a firmware recovery with no fault), + /// and a full effort on every submission held the top state whatever the load. A generic + /// render waiter doesn't tell paced work from a submit-and-wait loop, because paced work has + /// one too (the compositor, or the next frame's fence); pure-compute waiters exclude paced + /// render compositors. + pub(super) fn submission_effort( + &self, + effort: u32, + waited: bool, + bound: bool, + compute_waited: bool, + ) -> u32 { if self.m5 { return if waited || bound { effort } else { 0 }; } - if bound { effort } else { effort.min(self.active_effort) } + if bound || compute_waited { + effort + } else { + effort.min(self.active_effort) + } } /// Writes the effort input in firmware order, then cleans its cache line to coherency. diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 06af00c762d865..e9cae26925bf70 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -846,6 +846,7 @@ impl Drop for Firmware { } self.primary.stop(); self.port.set_effort_full(false); + self.primary.state.shared.set_full_effort_published(false); self.pool.stop_after_firmware(); // RTKit destruction releases the mailbox power references. Clear the bridge while // those references still keep the register block powered. @@ -929,6 +930,7 @@ impl Firmware { self.primary.state.shared.note_gpu_activity(); self.effort.submit(); self.effort.note_waiters(now, fence::waiters()); + self.effort.note_compute_waiters(now, fence::compute_waiters()); self.effort.note_bound(self.primary.state.shared.feed.busy_run()); if self.effort.bound() { self.port.lift_busy_if_below_top(now); @@ -983,10 +985,17 @@ impl Firmware { } fn apply_effort(&mut self, effort: u32) -> Result { - Self::apply_shared_effort(&self.init, &mut self.effort, &self.port, effort) + Self::apply_shared_effort( + &self.primary.state.shared, + &self.init, + &mut self.effort, + &self.port, + effort, + ) } fn apply_shared_effort( + shared: &Shared, init: &initdata::InitData, state: &mut power::Effort, port: &port::Port, @@ -994,8 +1003,14 @@ impl Firmware { ) -> Result { // The performance-controller demand follows the requested effort; the firmware is // given, and the state records, the published value (InitData::submission_effort). - let published = init.submission_effort(effort, state.waited(), state.bound()); + let published = init.submission_effort( + effort, + state.waited(), + state.bound(), + state.compute_waited(), + ); port.set_effort_full(effort == power::FULL_EFFORT); + shared.set_full_effort_published(published == power::FULL_EFFORT); if state.applied() == published { // M5 maps region C read-only to the firmware: once confirmed, the word holds // `applied` without reading it back. @@ -1036,14 +1051,18 @@ impl Firmware { self.effort.submit(); } // A waiter or a busy run that began or ended since the last note moves the effort while - // work streams. + // work streams. Skip a redundant Region C drop right before Effort::idle clears it to 0. if self.effort.streaming() { let waiters = self.effort.note_waiters(now_ns, fence::waiters()); + let compute_waiters = self + .effort + .note_compute_waiters(now_ns, fence::compute_waiters()); let bound = self.effort.note_bound(self.primary.state.shared.feed.busy_run()); if self.effort.bound() { self.port.lift_busy_if_below_top(now_ns); } - if waiters || bound { + let active = in_flight || submitted; + if (waiters || compute_waiters || bound) && !self.effort.will_clear(now_ns, active) { self.apply_effort(power::FULL_EFFORT)?; } } @@ -1250,6 +1269,11 @@ struct Shared { idle: DelayedWork, /// M5: the thermal governor runs (the firmware has the host power budget word). governs: bool, + /// Non-M5 submission-capable device registered for compute-waiter effort wakeups. + tracks_effort_wake: bool, + /// Region C currently holds FULL_EFFORT; mirrored with `BELOW_FULL_COUNT` under + /// `EFFORT_TARGETS` so steady-state compute waits take no lock. + full_effort_published: AtomicBool, #[pin] governor: DelayedWork, governor_armed: AtomicBool, @@ -1397,7 +1421,167 @@ impl WorkItem for Shared { } } +/// Non-M5 G17 devices registered for immediate full-effort wakeups when a host thread begins +/// waiting on a pure-compute submission while Region C is below `FULL_EFFORT`. +/// +/// Lock order: `Shared::state` -> `EFFORT_TARGETS`; `dma_fence->lock` -> `EFFORT_TARGETS` -> +/// workqueue pool lock. Always acquired with `spin_lock_irqsave` so it nests safely inside C +/// `dma_fence->lock` (`spin_lock_irqsave`) without altering caller IRQ state. +const MAX_EFFORT_TARGETS: usize = 4; + +struct EffortTargets { + lock: Opaque, + slots: core::cell::UnsafeCell<[Option>; MAX_EFFORT_TARGETS]>, +} + +// SAFETY: Every access to `slots` holds `lock` with hardware IRQ save/restore. +unsafe impl Sync for EffortTargets {} + +struct EffortTargetsGuard<'a> { + targets: &'a EffortTargets, + flags: kernel::ffi::c_ulong, +} + +impl core::ops::Deref for EffortTargetsGuard<'_> { + type Target = [Option>; MAX_EFFORT_TARGETS]; + + fn deref(&self) -> &Self::Target { + // SAFETY: The guard holds `targets.lock` exclusively. + unsafe { &*self.targets.slots.get() } + } +} + +impl core::ops::DerefMut for EffortTargetsGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + // SAFETY: The guard holds `targets.lock` exclusively. + unsafe { &mut *self.targets.slots.get() } + } +} + +impl Drop for EffortTargetsGuard<'_> { + fn drop(&mut self) { + // SAFETY: `self.flags` came from `spin_lock_irqsave` on `self.targets.lock`. + unsafe { kernel::bindings::spin_unlock_irqrestore(self.targets.lock.get(), self.flags) }; + } +} + +impl EffortTargets { + const fn new() -> Self { + Self { + lock: Opaque::uninit(), + slots: core::cell::UnsafeCell::new([const { None }; MAX_EFFORT_TARGETS]), + } + } + + unsafe fn init(&self) { + // SAFETY: Called once during module init before any GPU adapter probes. + unsafe { + kernel::bindings::__spin_lock_init( + self.lock.get(), + c_str!("g17::EFFORT_TARGETS").as_char_ptr(), + kernel::static_lock_class!().as_ptr(), + ); + } + } + + fn lock(&self) -> EffortTargetsGuard<'_> { + // SAFETY: `self.lock` was initialized once in `g17::init` before any probe. + let flags = unsafe { kernel::bindings::spin_lock_irqsave(self.lock.get()) }; + EffortTargetsGuard { + targets: self, + flags, + } + } +} + +static EFFORT_TARGETS: EffortTargets = EffortTargets::new(); +/// Registered non-M5 devices whose Region C effort is currently below `FULL_EFFORT`. +static BELOW_FULL_COUNT: AtomicU32 = AtomicU32::new(0); + +/// # Safety +/// +/// Called exactly once per module instance, before any platform adapter is registered. +pub(crate) unsafe fn init() { + // SAFETY: Single-call module initialization invariant upheld by caller. + unsafe { EFFORT_TARGETS.init() }; +} + +fn register_effort_target(shared: &Arc) { + if !shared.tracks_effort_wake { + return; + } + let mut targets = EFFORT_TARGETS.lock(); + if let Some(slot) = targets.iter_mut().find(|slot| slot.is_none()) { + *slot = Some(shared.clone()); + if !shared.full_effort_published.load(Ordering::Acquire) { + BELOW_FULL_COUNT.fetch_add(1, Ordering::AcqRel); + } + } +} + +fn unregister_effort_target(shared: &Arc) { + if !shared.tracks_effort_wake { + return; + } + let removed = { + let mut targets = EFFORT_TARGETS.lock(); + let mut found = None; + for slot in targets.iter_mut() { + if slot + .as_ref() + .is_some_and(|entry| Arc::ptr_eq(entry, shared)) + { + found = slot.take(); + if !shared.full_effort_published.load(Ordering::Acquire) { + BELOW_FULL_COUNT.fetch_sub(1, Ordering::AcqRel); + } + break; + } + } + found + }; + // Drop outside the spinlock; caller also retains `shared`. + drop(removed); +} + +/// Wakes any non-M5 device still below `FULL_EFFORT` so a newly waited pure-compute dispatch +/// lifts Region C effort to `FULL_EFFORT` immediately instead of waiting 16 ms. +/// Safe in atomic `dma_fence->lock` context: lock-free once already at `FULL_EFFORT`, and +/// `EFFORT_TARGETS` keeps every `Arc` refcount >= 2 across `queue_event_records()`. +pub(super) fn wake_for_compute_waiter() { + if BELOW_FULL_COUNT.load(Ordering::Acquire) == 0 { + return; + } + let targets = EFFORT_TARGETS.lock(); + for shared in targets.iter().flatten() { + if !shared.full_effort_published.load(Ordering::Acquire) + && !shared.sleeping() + && !shared.crashed.load(Ordering::Acquire) + { + shared.queue_event_records(); + } + } +} + impl Shared { + fn set_full_effort_published(&self, full: bool) { + if !self.tracks_effort_wake || self.full_effort_published.load(Ordering::Relaxed) == full { + return; + } + let targets = EFFORT_TARGETS.lock(); + let registered = targets + .iter() + .flatten() + .any(|entry| core::ptr::eq(Arc::as_ptr(entry), self)); + if registered && self.full_effort_published.swap(full, Ordering::AcqRel) != full { + if full { + BELOW_FULL_COUNT.fetch_sub(1, Ordering::AcqRel); + } else { + BELOW_FULL_COUNT.fetch_add(1, Ordering::AcqRel); + } + } + } + fn drm(&self) -> Result { self.drm.lock().as_ref().cloned().ok_or(ENODEV) } @@ -1804,6 +1988,8 @@ impl Gpu { poll <- new_delayed_work!("g17::Shared::poll"), idle <- new_delayed_work!("g17::Shared::idle"), governs: m5, + tracks_effort_wake: !m5 && submits, + full_effort_published: AtomicBool::new(false), governor <- new_delayed_work!("g17::Shared::governor"), governor_armed: AtomicBool::new(false), governor_activity_ns: AtomicU64::new(0), @@ -1872,6 +2058,7 @@ impl Gpu { .port .store(Arc::as_ptr(&firmware.port).cast_mut(), Ordering::Release); *gpu.shared.state.lock() = Some(firmware); + register_effort_target(&gpu.shared); gpu.shared.queue_events(); Ok(gpu) } @@ -2503,6 +2690,7 @@ impl Gpu { /// Stops the firmware and releases everything it used. pub(crate) fn shutdown(&self) { + unregister_effort_target(&self.shared); self.shared.feed.begin_shutdown(); self.shared.preparations.remove(); self.shared.stop_queues(); diff --git a/drivers/gpu/drm/asahi/g17/power.rs b/drivers/gpu/drm/asahi/g17/power.rs index cc3137b8a36b9e..c4e1125a6dbd99 100644 --- a/drivers/gpu/drm/asahi/g17/power.rs +++ b/drivers/gpu/drm/asahi/g17/power.rs @@ -49,6 +49,13 @@ pub(super) struct Effort { seen_waits: u64, /// When a waiter was last seen. last_wait_ns: u64, + /// A host thread waits, or waited within [`IDLE_HOLD_NS`], for a pure-compute submission + /// ([`Self::note_compute_waiters`]). + compute_waited: bool, + /// Pure-compute waits begun when compute waiters were last noted. + seen_compute_waits: u64, + /// When a pure-compute waiter was last seen. + last_compute_wait_ns: u64, /// The GPU has run longer than [`IDLE_HOLD_NS`] without an idle gap ([`BusyRun`]). bound: bool, } @@ -64,6 +71,9 @@ impl Effort { waited: false, seen_waits: 0, last_wait_ns: 0, + compute_waited: false, + seen_compute_waits: 0, + last_compute_wait_ns: 0, bound: false, } } @@ -92,6 +102,40 @@ impl Effort { changed } + /// Whether a host thread waits for a pure-compute submission ([`Self::note_compute_waiters`]). + pub(super) fn compute_waited(&self) -> bool { + self.compute_waited + } + + /// Notes host waiters on pure-compute submissions at `now_ns` + /// ([`super::fence::compute_waiters`]). Holds for [`IDLE_HOLD_NS`] after the last compute + /// wait so depth-1 compute loops stay at full effort across host turnarounds and resume at + /// full effort immediately after CPU gaps without affecting paced render compositors. + pub(super) fn note_compute_waiters( + &mut self, + now_ns: u64, + (waiters, waits): (u32, u64), + ) -> bool { + if waiters > 0 || waits != self.seen_compute_waits { + self.last_compute_wait_ns = now_ns.max(1); + } + self.seen_compute_waits = waits; + let compute_waited = self.last_compute_wait_ns != 0 + && now_ns.saturating_sub(self.last_compute_wait_ns) < IDLE_HOLD_NS; + let changed = compute_waited != self.compute_waited; + self.compute_waited = compute_waited; + changed + } + + /// Whether [`Self::idle`] at `now_ns` with `in_flight` will clear the effort state. + pub(super) fn will_clear(&self, now_ns: u64, in_flight: bool) -> bool { + self.streaming + && !in_flight + && self + .idle_since + .is_some_and(|since| now_ns.saturating_sub(since) >= IDLE_HOLD_NS) + } + /// Whether the GPU has run without an idle gap for longer than the effort is held after /// work stops ([`BusyRun::bound`]). pub(super) fn bound(&self) -> bool { @@ -145,8 +189,10 @@ impl Effort { if idle >= IDLE_HOLD_NS { self.streaming = false; self.waited = false; + self.compute_waited = false; self.bound = false; self.last_wait_ns = 0; + self.last_compute_wait_ns = 0; self.idle_since = None; IdleAction::Clear } else { @@ -909,6 +955,34 @@ mod tests { ); assert!(share.below_top()); } + + #[test] + fn compute_waiters_lift_immediately_and_expire_while_streaming() { + const NS_MS: u64 = 1_000_000; + let mut effort = Effort::new(); + effort.submit(); + assert!(!effort.compute_waited()); + // Render waiter alone never marks compute_waited. + assert!(effort.note_waiters(10 * NS_MS, (1, 1))); + assert!(!effort.note_compute_waiters(10 * NS_MS, (0, 0))); + assert!(!effort.compute_waited()); + // A pure-compute waiter lifts immediately. + assert!(effort.note_compute_waiters(11 * NS_MS, (1, 1))); + assert!(effort.compute_waited()); + // Holds across a short host turnaround between depth-1 dispatches. + assert!(!effort.note_compute_waiters(15 * NS_MS, (0, 1))); + assert!(effort.compute_waited()); + // Expires cleanly after IDLE_HOLD_NS even while a compositor keeps streaming. + assert!(effort.note_compute_waiters(11 * NS_MS + IDLE_HOLD_NS, (0, 1))); + assert!(!effort.compute_waited()); + // Idle clear also resets compute_waited. + assert!(effort.note_compute_waiters(40 * NS_MS, (1, 2))); + assert!(effort.compute_waited()); + assert_eq!(effort.idle(40 * NS_MS, false), IdleAction::Recheck(IDLE_HOLD_NS)); + assert!(effort.will_clear(40 * NS_MS + IDLE_HOLD_NS, false)); + assert_eq!(effort.idle(40 * NS_MS + IDLE_HOLD_NS, false), IdleAction::Clear); + assert!(!effort.compute_waited()); + } } unsafe extern "C" { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 008dc7839f8d7c..1c64f3839ae22d 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -557,12 +557,13 @@ impl crate::queue::Queue for Queue { return Err(EIO); } let (mut pending, guards) = self.prepare_submission(bytes, objects)?; - if pending + let has_render = pending .iter() - .any(|(command, _, _)| matches!(command, Validated::Render { .. })) - { + .any(|(command, _, _)| matches!(command, Validated::Render { .. })); + if has_render { self.context.note_render(); } + let compute_only = !has_render && !pending.is_empty(); if super::timeout::select_submission(pending.iter().map(|(cmd, _, _)| cmd.long_job())) { for (command, _, _) in pending.iter_mut() { command.allow_long_job(); @@ -577,7 +578,7 @@ impl crate::queue::Queue for Queue { if *visible_completion || !visible_required) && !pending[0].2.has_outputs() && !self.has_pending_publication(&pending[0].1); - let aggregate = outputs.publish(self.context.clone(), firmware_source)?; + let aggregate = outputs.publish(self.context.clone(), firmware_source, compute_only)?; let output_fence = aggregate.fence(); super::trace::submit( 1, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 2aa128bc7f6c0d..64ded98506e3ba 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1693,11 +1693,18 @@ impl compute::Host for ComputeHost<'_> { self.shared.note_gpu_activity(); self.effort.submit(); self.effort.note_waiters(now, super::fence::waiters()); + self.effort.note_compute_waiters(now, super::fence::compute_waiters()); self.effort.note_bound(self.shared.feed.busy_run()); if self.effort.bound() { self.port.lift_busy_if_below_top(now); } - super::Firmware::apply_shared_effort(self.init, self.effort, self.port, super::power::FULL_EFFORT) + super::Firmware::apply_shared_effort( + self.shared, + self.init, + self.effort, + self.port, + super::power::FULL_EFFORT, + ) } fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { // Compute only (publication and installation); render pairs submit through diff --git a/drivers/gpu/drm/asahi/g17/sync_output.c b/drivers/gpu/drm/asahi/g17/sync_output.c index 08b4a95f26c9b4..191ebdfc04cdbc 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.c +++ b/drivers/gpu/drm/asahi/g17/sync_output.c @@ -98,7 +98,7 @@ static void asahi_g17_signal_install(struct asahi_g17_signal_target *target, } int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, - struct dma_fence *submitted) + struct dma_fence *submitted, bool compute_only) { struct dma_fence *previous, *scope; size_t i; @@ -107,7 +107,8 @@ int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, return -EINVAL; previous = drm_syncobj_fence_get(bundle->targets[bundle->anchor].syncobj); scope = asahi_g17_scope_create(previous, submitted, - bundle->targets[bundle->anchor].point); + bundle->targets[bundle->anchor].point, + compute_only); dma_fence_put(previous); if (!scope) return -ENOMEM; diff --git a/drivers/gpu/drm/asahi/g17/sync_output.h b/drivers/gpu/drm/asahi/g17/sync_output.h index a752d9ceaf4b0c..cee1146372fc64 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.h +++ b/drivers/gpu/drm/asahi/g17/sync_output.h @@ -17,7 +17,7 @@ asahi_g17_signals_new(const struct asahi_g17_signal_spec *specs, size_t count, size_t anchor, int *error); void asahi_g17_signals_free(struct asahi_g17_signal_bundle *bundle); int asahi_g17_signals_publish(struct asahi_g17_signal_bundle *bundle, - struct dma_fence *submitted); + struct dma_fence *submitted, bool compute_only); void asahi_g17_signals_fail(struct asahi_g17_signal_bundle *bundle, struct dma_fence *failure); #endif diff --git a/drivers/gpu/drm/asahi/g17/sync_output.rs b/drivers/gpu/drm/asahi/g17/sync_output.rs index 928ebe23193948..5bbc3467a40005 100644 --- a/drivers/gpu/drm/asahi/g17/sync_output.rs +++ b/drivers/gpu/drm/asahi/g17/sync_output.rs @@ -13,7 +13,7 @@ unsafe extern "C" { error: *mut i32) -> *mut core::ffi::c_void; fn asahi_g17_signals_free(bundle: *mut core::ffi::c_void); fn asahi_g17_signals_publish(bundle: *mut core::ffi::c_void, - current: *mut bindings::dma_fence) -> i32; + current: *mut bindings::dma_fence, compute_only: bool) -> i32; fn asahi_g17_signals_fail(bundle: *mut core::ffi::c_void, failure: *mut bindings::dma_fence); } @@ -48,10 +48,10 @@ impl SignalBundle { Ok(Self(raw)) } - pub(crate) fn publish(&mut self, current: &Fence) -> Result { + pub(crate) fn publish(&mut self, current: &Fence, compute_only: bool) -> Result { // SAFETY: The bundle and current fence are owned for this call; C takes // its own references on publication and reports failure before any store. - let error = unsafe { asahi_g17_signals_publish(self.0, current.raw()) }; + let error = unsafe { asahi_g17_signals_publish(self.0, current.raw(), compute_only) }; if error == 0 { Ok(()) } else { Err(Error::from_errno(error)) } } diff --git a/drivers/gpu/drm/asahi/g17/sync_scope.c b/drivers/gpu/drm/asahi/g17/sync_scope.c index c702cac631991f..6c4632c220d8c9 100644 --- a/drivers/gpu/drm/asahi/g17/sync_scope.c +++ b/drivers/gpu/drm/asahi/g17/sync_scope.c @@ -32,6 +32,8 @@ struct asahi_g17_scope_callback { struct asahi_g17_scope { struct dma_fence base; atomic_t pending; + atomic_t compute_waited; + bool compute_only; struct dma_fence *children[2]; struct asahi_g17_scope_callback callbacks[2]; struct irq_work work; @@ -43,6 +45,8 @@ struct asahi_g17_scope { static const struct dma_fence_ops scope_ops; static DEFINE_PER_CPU(struct llist_head *, active_scopes); +/* Suppresses internal scope chaining from counting as a host compute waiter. */ +static DEFINE_PER_CPU(struct dma_fence *, scope_chaining_fence); #define SCOPE_ATOMIC_BATCH 64 bool asahi_g17_is_scope(struct dma_fence *fence) @@ -76,8 +80,22 @@ static bool scope_signaled(struct dma_fence *fence) static bool scope_enable_signaling(struct dma_fence *fence) { + struct asahi_g17_scope *scope = to_scope(fence); + /* Child callbacks are already armed; no recursive callback installation. */ - return !scope_signaled(fence); + if (scope_signaled(fence)) + return false; + if (scope->compute_only && + __this_cpu_read(scope_chaining_fence) != fence && + !atomic_xchg(&scope->compute_waited, 1)) + asahi_g17_note_compute_waiter(); + return true; +} + +static void scope_unwait(struct asahi_g17_scope *scope) +{ + if (atomic_xchg(&scope->compute_waited, 0)) + asahi_g17_unnote_compute_waiter(); } unsigned int asahi_g17_scope_children(struct dma_fence *fence, @@ -118,6 +136,7 @@ static void scope_complete(struct asahi_g17_scope *scope) { cmpxchg(&scope->base.error, 1, 0); dma_fence_signal(&scope->base); + scope_unwait(scope); scope_release_completed(scope); } @@ -126,6 +145,7 @@ static void scope_work(struct irq_work *work) struct asahi_g17_scope *scope = container_of(work, struct asahi_g17_scope, work); cmpxchg(&scope->base.error, 1, 0); asahi_g17_signal_fence(&scope->base); + scope_unwait(scope); scope_release_completed(scope); } @@ -218,6 +238,7 @@ static void scope_release(struct dma_fence *fence) struct asahi_g17_scope *scope = to_scope(fence); unsigned int i; + scope_unwait(scope); for (i = 0; i < ARRAY_SIZE(scope->children); ++i) dma_fence_put(scope->children[i]); dma_fence_free(fence); @@ -268,7 +289,8 @@ void asahi_g17_scope_bind(struct dma_fence *fence, struct dma_fence *root) } struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, - struct dma_fence *submitted, u64 point) + struct dma_fence *submitted, u64 point, + bool compute_only) { struct dma_fence *contained = previous ? dma_fence_chain_contained(previous) : NULL; struct dma_fence *parent = NULL; @@ -304,6 +326,7 @@ struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, } dma_fence_init64(&scope->base, &scope_ops, NULL, context, point); init_irq_work(&scope->work, scope_work); + scope->compute_only = compute_only; scope->children[0] = parent; scope->children[1] = dma_fence_get(submitted); /* The constructor guard prevents completion while callbacks are being installed. */ @@ -311,13 +334,21 @@ struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, scope->base.error = 1; for (i = 0; i < ARRAY_SIZE(scope->children); ++i) { struct dma_fence *child = scope->children[i]; + int err; + if (!child) { scope_arrived(scope, 0); continue; } scope->callbacks[i].scope = scope; dma_fence_get(&scope->base); - if (dma_fence_add_callback(child, &scope->callbacks[i].callback, scope_callback)) { + preempt_disable(); + __this_cpu_write(scope_chaining_fence, child); + err = dma_fence_add_callback(child, &scope->callbacks[i].callback, + scope_callback); + __this_cpu_write(scope_chaining_fence, NULL); + preempt_enable(); + if (err) { scope_arrived(scope, child->error); dma_fence_put(&scope->base); } diff --git a/drivers/gpu/drm/asahi/g17/sync_scope.h b/drivers/gpu/drm/asahi/g17/sync_scope.h index e88b78aacdd7b5..1504fcb5effefc 100644 --- a/drivers/gpu/drm/asahi/g17/sync_scope.h +++ b/drivers/gpu/drm/asahi/g17/sync_scope.h @@ -8,10 +8,13 @@ void asahi_g17_signal_fence(struct dma_fence *fence); int asahi_g17_completion_fence_status(struct dma_fence *fence); struct dma_fence *asahi_g17_scope_create(struct dma_fence *previous, - struct dma_fence *submitted, u64 point); + struct dma_fence *submitted, u64 point, + bool compute_only); void asahi_g17_scope_bind(struct dma_fence *scope, struct dma_fence *root); bool asahi_g17_is_scope(struct dma_fence *fence); /* Returns owned child references, or zero once the scope is signalled. */ unsigned int asahi_g17_scope_children(struct dma_fence *fence, struct dma_fence *children[2]); +void asahi_g17_note_compute_waiter(void); +void asahi_g17_unnote_compute_waiter(void); #endif diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index a7b9b900b7af5e..949c0be39a3e48 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -80,6 +80,7 @@ def item(text, marker): static BINDING_READY: Cell = const { Cell::new(false) }; static QUEUE_SHARE_READY: Cell = const { Cell::new(false) }; static EXEC_SHARE_READY: Cell = const { Cell::new(false) }; + static G17_READY: Cell = const { Cell::new(false) }; static ATTACH_ERROR: Cell = const { Cell::new(false) }; static PROBE_ERROR: Cell = const { Cell::new(0) }; } @@ -154,6 +155,7 @@ def item(text, marker): } // So must the registry of execution contexts shared by a VM's G17P queues. mod g17 { + pub unsafe fn init() { crate::G17_READY.set(true); } pub mod exec_share { pub unsafe fn init() { crate::EXEC_SHARE_READY.set(true); } } @@ -175,6 +177,7 @@ def item(text, marker): assert!(BINDING_READY.get(), "adapter registered before binding registry init"); assert!(QUEUE_SHARE_READY.get(), "adapter registered before queue-share registry init"); assert!(EXEC_SHARE_READY.get(), "adapter registered before execution-context share registry init"); + assert!(G17_READY.get(), "adapter registered before g17 compute-waiter target registry init"); try_pin_init!(Self { stage: { let stage = match name.to_bytes() { @@ -228,6 +231,7 @@ def item(text, marker): BINDING_READY.set(false); QUEUE_SHARE_READY.set(false); EXEC_SHARE_READY.set(false); + G17_READY.set(false); FAIL_ALLOC.set(fail_alloc); TOUCH.set(touch); PROBE_ERROR.set(error); RETAINED.set(false); ALLOCS.set(0); PROBES.set(0); } diff --git a/tools/asahi/g17-m5-effort-tests.py b/tools/asahi/g17-m5-effort-tests.py index ef59c909a67d72..5cd73704e91c4c 100755 --- a/tools/asahi/g17-m5-effort-tests.py +++ b/tools/asahi/g17-m5-effort-tests.py @@ -75,14 +75,16 @@ def build_harness(mutation=None): let g17p = MockInitData {{ m5: false, active_effort: 0x5555 }}; // Direct policy matrix on M5 vs non-M5. - assert_eq!(m5.submission_effort(FULL_EFFORT, false, false), 0); - assert_eq!(m5.submission_effort(FULL_EFFORT, true, false), FULL_EFFORT); - assert_eq!(m5.submission_effort(FULL_EFFORT, false, true), FULL_EFFORT); - assert_eq!(m5.submission_effort(FULL_EFFORT, true, true), FULL_EFFORT); - assert_eq!(m5.submission_effort(0, true, true), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, false), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, true), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, false, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, true, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(FULL_EFFORT, true, true, false), FULL_EFFORT); + assert_eq!(m5.submission_effort(0, true, true, true), 0); - assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false), 0x5555); - assert_eq!(g17p.submission_effort(FULL_EFFORT, false, true), FULL_EFFORT); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false, false), 0x5555); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, true, false), FULL_EFFORT); + assert_eq!(g17p.submission_effort(FULL_EFFORT, false, false, true), FULL_EFFORT); // End-to-end pipelined compute loop on M5 without host waiters: // 24 MHz clock -> idle_ticks = 2 ms = 48_000 ticks, hold_ticks = 16 ms = 384_000 ticks. @@ -102,7 +104,12 @@ def build_harness(mutation=None): let changed = effort.note_bound(true); assert!(changed); assert_eq!( - m5.submission_effort(FULL_EFFORT, effort.waited(), effort.bound()), + m5.submission_effort( + FULL_EFFORT, + effort.waited(), + effort.bound(), + effort.compute_waited(), + ), FULL_EFFORT, "M5 must publish FULL_EFFORT when BusyRuns::bound is true even without a waiter", ); @@ -113,7 +120,10 @@ def build_harness(mutation=None): runs.end(); assert!(!effort.bound()); assert!(!runs.bound(tick, hold_ticks, idle_ticks)); - assert_eq!(m5.submission_effort(0, effort.waited(), effort.bound()), 0); + assert_eq!( + m5.submission_effort(0, effort.waited(), effort.bound(), effort.compute_waited()), + 0, + ); // Paced work with 5 ms idle gaps stays unbound and publishes 0 on M5. let mut paced = 1_000_000u64; @@ -122,7 +132,7 @@ def build_harness(mutation=None): paced += 120_000; // 5 ms > 2 ms idle_ticks }} assert!(!runs.bound(paced, hold_ticks, idle_ticks)); - assert_eq!(m5.submission_effort(FULL_EFFORT, false, false), 0); + assert_eq!(m5.submission_effort(FULL_EFFORT, false, false, false), 0); println!("PASS g17-m5-effort-tests"); }} From a28f61ac88117858ee2a9502e0c7447b70743f44 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:31:26 -0500 Subject: [PATCH 1142/1514] drm/asahi: keep the render wait of fragment barriers on G13 and G14 Since commit 24a7cfa37871 ("drm/asahi: accept FRAGMENT_BARRIERS on G13, G14 and G14X"), a render command that sets DRM_ASAHI_RENDER_FRAGMENT_BARRIERS gets no wait at all for the earlier renders its barriers name. The legacy queue relies on the fragment workqueue running that work first, but queue order alone does not make it finish first. Mesa's Gallium driver started setting the flag on render passes that sample the previous pass's output, and on M1 Pro and M2 Air gpubench-gl render.postfx then reads that output before it is complete: the image is wrong and changes from run to run. The UAPI says the dependencies of such a render are attached to its fragment half instead of its vertex half. Do that: add the explicit barrier to the fragment job, which already waits for its own vertex job the same way. The vertex half still runs beside the earlier fragment work, which is the point of the flag. Kernels with 24a7cfa37871 report DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS but drop the wait, so userspace cannot tell them apart by that bit. Add DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS (bit 44), which says the fragment half does wait, and report it on this backend and on G17, whose firmware fragment barriers already carry the render dependencies. Fixes: 24a7cfa37871 ("drm/asahi: accept FRAGMENT_BARRIERS on G13, G14 and G14X") Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g17/mod.rs | 1 + drivers/gpu/drm/asahi/gpu.rs | 6 ++++-- drivers/gpu/drm/asahi/queue/mod.rs | 30 +++++++++++++++--------------- include/uapi/drm/asahi_drm.h | 11 +++++++++++ 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 06af00c762d865..1e97c66c422e3d 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2580,6 +2580,7 @@ impl gpu::Gpu for Gpu { 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) + | uapi::DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS as u64 | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT; diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 9fed9e62ec3835..879ea5df4b9e0d 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -1637,10 +1637,12 @@ extern "C" { #[versions(AGX)] impl Gpu for GpuManager::ver { - /// Render commands may order their dependencies on earlier renders after - /// their vertex half only (DRM_ASAHI_RENDER_FRAGMENT_BARRIERS). + /// Render commands may make only their fragment half wait for earlier + /// renders (DRM_ASAHI_RENDER_FRAGMENT_BARRIERS), and the fragment half + /// does wait for them (DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS). fn backend_feature_flags(&self) -> u64 { u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) + | uapi::DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS as u64 } /// A light submission completes in tens of microseconds, so its submitter diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 94405e88c6b0dd..6a730f8af2d4ad 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -1280,10 +1280,9 @@ impl Queue for Queue::ver { // A render's wait for earlier renders is added once its flags are // known: without DRM_ASAHI_RENDER_FRAGMENT_BARRIERS it goes on the - // vertex queue; with it no barrier is added, since the wait names - // only earlier fragment work, which the fragment queue already runs - // first, so the vertex half can run beside it. Each fragment half - // still waits for its own vertex half. + // vertex queue; with it, it goes on the fragment queue, so the + // vertex half can run beside the earlier fragment work. Each + // fragment half also waits for its own vertex half. let is_render = u32::from(header.cmd_type) == uapi::drm_asahi_cmd_type_DRM_ASAHI_CMD_RENDER; let mut render_wait = None; @@ -1318,21 +1317,22 @@ impl Queue for Queue::ver { cls_pr_debug!(Errors, "Unsupported render command fields\n") })?; - // With FRAGMENT_BARRIERS the wait names only earlier fragment work of - // this queue (index 0 is its last fragment event, later indices are - // renders of this submission), which the fragment workqueue already - // runs first, so no barrier is needed at all. + // The wait names earlier fragment work of this queue (index 0 is its + // last fragment event, later indices are renders of this + // submission). The fragment workqueue runs that work first, but queue + // order alone does not make it finish first, so with FRAGMENT_BARRIERS + // the wait moves to the fragment half instead of being dropped. let fragment_only = render.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS != 0; - if let Some(event) = render_wait.take().filter(|_| !fragment_only) { + if let Some(event) = render_wait.take() { + let queue_job = if fragment_only { + job.get_frag()? + } else { + job.get_vtx()? + }; Self::add_explicit_barrier( - &self.dev, - &gpu, - job.get_vtx()?, - &event, - vm_slot, - id, + &self.dev, &gpu, queue_job, &event, vm_slot, id, )?; } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 0ac0c404358ec3..341eb1796ce1f0 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -573,6 +573,17 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_USERPTR_NO_MEMLOCK ((1ULL) << 43) +/* + * DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS: a render command that sets + * DRM_ASAHI_RENDER_FRAGMENT_BARRIERS still waits for the earlier renders its + * barriers name: the fragment half waits for them to finish before it + * starts. Kernels that report DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS without + * this bit may drop that wait, so userspace that uses the flag to order a + * render after earlier ones must check for this bit. A feature bit like + * those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS ((1ULL) << 44) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 From 4fc8d0f4be14839c4bf78c5acce0a67d071b238e Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 14:27:40 -0800 Subject: [PATCH 1143/1514] drm/asahi: g17: keep an owner's wide-layout render pair when reclaiming under QID pressure When an owner holds two render pairs and one has been marked wide (the slot carrying the larger parameter-buffer layout), reclaiming a sibling under QID pressure should take the non-wide sibling before disturbing the wide pair. Update State::reclaim_sibling(), Registry::reclaim_unused_render_spare(), and Registry::reclaim_unused_render_sibling() to pass over wide-marked siblings first and only fall back to reclaiming a wide sibling if no non-wide sibling is available. In render.rs, pass 3 omits any wide filter so a slot whose wide mark moved between pass 2 and pass 3 is still reclaimed rather than skipped. Detaching a published sibling keeps release_unused_sibling(..., true) + release_owner() unchanged so exit-kill ownership stays intact. Add KUnit tests covering non-wide-first reclaim (and clearing of the wide mark on detach) and the open-queue capacity gate and release_owner path for wide-marked owners. Signed-off-by: Jeff Queisser --- drivers/gpu/drm/asahi/g17/queue/admission.rs | 107 +++++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/render.rs | 14 ++- tools/asahi/g17-admission-order-tests.py | 2 +- 3 files changed, 108 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index c34f84494df0dd..44f937de18f6f9 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -567,18 +567,24 @@ impl State { true } /// Takes back one idle live sibling in `eligible`, preferring unpublished - /// siblings before published ones. Slots in `installed` or `published` keep - /// `released` set so their installed QIDs are reused first. + /// siblings before published ones and non-wide siblings before wide-marked + /// ones. Slots in `installed` or `published` keep `released` set so their + /// installed QIDs are reused first. fn reclaim_sibling(&mut self, eligible: u64, installed: u64) -> Option { for allow_published in [false, true] { - for slot in 1..cfg::RENDER_SLOTS { - let bit = 1u64 << slot; - if eligible & bit == 0 || (!allow_published && self.published & bit != 0) { - continue; - } - let keep_installed = (installed | self.published) & bit != 0; - if self.release_unused_sibling(slot as u8, None, keep_installed) { - return Some(slot as u8); + for allow_wide in [false, true] { + for slot in 1..cfg::RENDER_SLOTS { + let bit = 1u64 << slot; + if eligible & bit == 0 + || (!allow_published && self.published & bit != 0) + || (!allow_wide && self.wide & bit != 0) + { + continue; + } + let keep_installed = (installed | self.published) & bit != 0; + if self.release_unused_sibling(slot as u8, None, keep_installed) { + return Some(slot as u8); + } } } } @@ -1281,6 +1287,10 @@ impl Pool { pub(crate) fn owns_live_slot(&self, owner: u64) -> bool { self.state.lock().has_live_owner(owner) } + pub(crate) fn is_wide(&self, slot: u8) -> bool { + let index = usize::from(slot); + index < cfg::RENDER_SLOTS && self.state.lock().wide & (1u64 << index) != 0 + } pub(crate) fn note_published(&self, slot: u8) { self.state.lock().mark_published(slot); } @@ -2173,6 +2183,83 @@ mod two_pair_tests { assert!(!state.can_pick_render(1, 1, Plan::Pair(1))); } + #[test] + fn reclaim_prefers_non_wide_sibling_and_clears_wide_on_detach() { + let mut state = State::new(); + // Owner 1 holds two published pairs; slot 1 holds its one-pair wide mark. + state.set_owner(1, 1); + state.set_owner(2, 1); + state.published = (1u64 << 1) | (1u64 << 2); + assert_eq!(state.pick(1, 1, Plan::Pair(1)), Some(1)); + state.release(1); + assert_ne!(state.wide & (1u64 << 1), 0); + // Reclaiming a sibling takes the non-wide slot (slot 2) instead of slot 1. + assert_eq!(state.reclaim_sibling(State::MASK, State::MASK), Some(2)); + assert_ne!(state.released & (1u64 << 2), 0); + assert_ne!(state.wide & (1u64 << 1), 0); + // Reattach slot 2 and explicitly detach the wide slot with keep_installed=true: + // the wide mark clears so reclaiming/re-acquiring slot 1 does not leave a stale mark. + state.released &= !(1u64 << 2); + assert!(state.release_unused_sibling(1, Some(1), true)); + assert_eq!(state.wide & (1u64 << 1), 0); + assert_ne!(state.released & (1u64 << 1), 0); + assert_eq!(state.owners[1], 1); + // With only slot 2 live, the next one-pair render moves to slot 2. + assert_eq!(state.pick(1, 1, Plan::Any), Some(2)); + state.release(2); + // Detach with keep_installed=false also clears the wide mark and owner. + state.set_owner(1, 1); + state.released &= !(1u64 << 1); + assert!(state.release_unused_sibling(2, Some(1), false)); + assert_eq!(state.owners[2], 0); + assert_eq!(state.wide & (1u64 << 2), 0); + } + + #[test] + fn wide_render_respects_open_queue_capacity_gate_and_release_owner() { + let pool = Pool::new(MAX_EXECUTION_CONTEXTS).unwrap(); + pool.note_build_room(true, 4); + let q1 = pool.try_reserve_queue(4).unwrap(); + let q2 = pool.try_reserve_queue(4).unwrap(); + let q3 = pool.try_reserve_queue(4).unwrap(); + // Owner 1 gets two pairs; mark `wide_slot` for one-pair renders, then leave it idle + // while the other pair stays busy and capacity shrinks to 3 (= open queues). + let a = pool.acquire_render(1, 2, None, u64::MAX, || Ok(())).unwrap(); + let b = pool.acquire_render(1, 1, None, u64::MAX, || Ok(())).unwrap(); + let wide_slot = b.slot(); + assert!(pool.is_wide(wide_slot)); + drop(b); + drop(a); + let other = { + let mut state = pool.state.lock(); + let other = (1..cfg::RENDER_SLOTS) + .find(|s| *s != usize::from(wide_slot) && state.owns_live(1, *s)) + .unwrap(); + state.refs[other] = 1; + state.active |= 1u64 << other; + other as u8 + }; + pool.note_build_room(false, 3); + { + let mut state = pool.state.lock(); + // Promoting idle `wide_slot` would push pair_demand from 3 to 4 > cap 3. + assert!(!state.can_pick_render_for(1, 1, 3, Plan::Any)); + assert_eq!(state.pick_for(1, 1, 3, Plan::Any), None); + // With capacity 4, the marked slot is picked again. + state.render_capacity = 4; + assert!(state.can_pick_render_for(1, 1, 3, Plan::Any)); + assert_eq!(state.pick_for(1, 1, 3, Plan::Any), Some(wide_slot)); + state.release(wide_slot); + state.release(other); + } + // release_owner clears the wide mark. + pool.release_owner(1); + assert!(!pool.is_wide(wide_slot)); + drop(q3); + drop(q2); + drop(q1); + } + #[test] fn a_one_pair_owner_claims_no_sibling() { let mut state = State::new(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 0a0a527ac1bf8d..228f114aead8b4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -291,13 +291,16 @@ impl Registry { } // Prefer an empty reservation or an already parked channel, then a // reusable or warmed unpublished pair, then an idle drained published - // sibling (render only). - for pass in 0..3u8 { - if pass == 2 && owner.is_none() { + // sibling (render only), preferring non-wide siblings before wide ones. + for pass in 0..4u8 { + if pass >= 2 && owner.is_none() { break; } let with_backing = pass != 0; for slot in 1..RENDER_SLOTS { + if pass == 2 && self.admission.is_wide(slot as u8) { + continue; + } if with_backing && self.render.entries[slot].as_ref().is_some_and(|entry| { entry.pair.is_some() @@ -454,9 +457,12 @@ impl Registry { /// only that slot's owner so the next queue reuses them via `bind_owner()`. /// The caller destroys any returned backing after dropping the device lock. pub(super) fn reclaim_unused_render_sibling(&mut self) -> Result> { - for pass in 0..3u8 { + for pass in 0..4u8 { let with_backing = pass != 0; for slot in 1..RENDER_SLOTS { + if pass == 2 && self.admission.is_wide(slot as u8) { + continue; + } if with_backing && self.render.entries[slot].as_ref().is_some_and(|entry| { entry.pair.is_some() diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 26f60259d0ccea..a55d4c7fbe6f97 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -379,7 +379,7 @@ def release_fixture(): pool = '\n'.join(item(source, name) for name in [ 'pub(crate) fn can_reassign_unused_spare(', 'pub(crate) fn reassign_unused_spare(', 'pub(crate) fn release_unused_sibling(', 'pub(crate) fn owns_live_slot(', - 'pub(crate) fn hold_render_slots_for_exit_kill(', + 'pub(crate) fn is_wide(', 'pub(crate) fn hold_render_slots_for_exit_kill(', 'pub(crate) fn set_held(', 'pub(crate) fn sync_held(', 'pub(crate) fn release_owner(']) pending = '\n'.join(item(teardown, name) for name in [ 'pub(crate) fn new(', 'pub(crate) fn releasing(', 'fn find(', 'fn insert(', From 2367d2acd0366a0aad174cc369d58c693100f7dd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 09:36:42 +1100 Subject: [PATCH 1144/1514] scripts/dtc: warn when a change gives one board what its siblings lack Boards of one SoC share most of their device tree through the SoC's .dtsi files, and a fix for one Mac put in that Mac's .dts leaves its siblings without it, although they have the same block (the J413's 27.x MTP settings were one). apple-sibling-drift.py looks, per SoC, at the nodes every board tree has and lists each property only some of them carry. Much of that is right (a desktop's HDMI port, a laptop's lid), so the base's drift is the baseline and only drift the change adds is reported, as a GitHub warning naming the boards with and without the property and what to do. Drift a change removes is counted as resolved. Variant trees (-fw27 and the like) are left out. dt-checks runs it next to the DART check; it never fails the job (--strict would). Signed-off-by: Ryan Murray --- .github/workflows/dt-checks.yml | 11 +++ scripts/dtc/apple-sibling-drift-test.py | 87 +++++++++++++++++++ scripts/dtc/apple-sibling-drift.py | 106 ++++++++++++++++++++++++ 3 files changed, 204 insertions(+) create mode 100755 scripts/dtc/apple-sibling-drift-test.py create mode 100755 scripts/dtc/apple-sibling-drift.py diff --git a/.github/workflows/dt-checks.yml b/.github/workflows/dt-checks.yml index 056add04447b11..a5a24eed980d15 100644 --- a/.github/workflows/dt-checks.yml +++ b/.github/workflows/dt-checks.yml @@ -106,6 +106,16 @@ jobs: --baseline-dtb-dir "$RUNNER_TEMP/dt/out-base/arch/arm64/boot/dts/apple" \ 2>&1 | tee "$RUNNER_TEMP/dt/dart-pd.log" + - name: Sibling drift, base vs head (warnings only) + if: ${{ !cancelled() && steps.dt.outputs.base != '' }} + run: | + set -o pipefail + python3 scripts/dtc/apple-sibling-drift-test.py + python3 scripts/dtc/apple-sibling-drift.py \ + --dtb-dir "$RUNNER_TEMP/dt/out-head/arch/arm64/boot/dts/apple" \ + --baseline-dtb-dir "$RUNNER_TEMP/dt/out-base/arch/arm64/boot/dts/apple" \ + 2>&1 | tee "$RUNNER_TEMP/dt/sibling-drift.log" + - name: Keep the warning lists if: always() uses: actions/upload-artifact@v4 @@ -115,4 +125,5 @@ jobs: ${{ runner.temp }}/dt/*.warn ${{ runner.temp }}/dt/coverage.log ${{ runner.temp }}/dt/dart-pd.log + ${{ runner.temp }}/dt/sibling-drift.log if-no-files-found: ignore diff --git a/scripts/dtc/apple-sibling-drift-test.py b/scripts/dtc/apple-sibling-drift-test.py new file mode 100755 index 00000000000000..7aa003876fb591 --- /dev/null +++ b/scripts/dtc/apple-sibling-drift-test.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Exercise apple-sibling-drift.py with synthetic DTS fixtures; needs dtc + pylibfdt.""" + +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("apple-sibling-drift.py") + + +def dts(board, *props): + return '''/dts-v1/; + / { compatible = "apple,%s", "apple,t8112", "apple,arm-platform"; + #address-cells = <1>; #size-cells = <0>; + dcp@1000 { reg = <0x1000>; %s }; + }; + ''' % (board, " ".join(props)) + + +class SiblingDriftTest(unittest.TestCase): + def setUp(self): + self.work = tempfile.TemporaryDirectory(prefix="drift-test-", dir=Path.cwd()) + self.addCleanup(self.work.cleanup) + self.root = Path(self.work.name) + self.base = self.root / "base" + self.head = self.root / "head" + self.base.mkdir() + self.head.mkdir() + # The J473's HDMI GPIO is right drift: the baseline has it. + for directory in (self.base, self.head): + self.dtb(directory, "t8112-j413", dts("j413", "shared;")) + self.dtb(directory, "t8112-j473", dts("j473", "shared;", "hdmi-gpios = <1>;")) + + def dtb(self, directory, name, source): + path = self.root / (name + ".dts") + path.write_text(source) + subprocess.run(["dtc", "-q", "-I", "dts", "-O", "dtb", "-o", + str(directory / (name + ".dtb")), str(path)], check=True) + + def check(self, *args): + return subprocess.run([sys.executable, str(CHECKER), "--dtb-dir", str(self.head), + "--baseline-dtb-dir", str(self.base), *args], + text=True, capture_output=True) + + def test_unchanged_is_quiet(self): + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout, "") + self.assertIn("drift 1, new 0, resolved 0", result.stderr) + + def test_one_board_fix_warns(self): + self.dtb(self.head, "t8112-j473", + dts("j473", "shared;", "hdmi-gpios = <1>;", "apple,fix;")) + result = self.check() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("t8112 /dcp@1000 apple,fix: only on j473; j413 have the node without it", + result.stdout) + self.assertNotIn("hdmi-gpios", result.stdout) + self.assertEqual(self.check("--strict").returncode, 1) + + def test_fix_on_every_board_is_quiet(self): + self.dtb(self.head, "t8112-j413", dts("j413", "shared;", "apple,fix;")) + self.dtb(self.head, "t8112-j473", + dts("j473", "shared;", "hdmi-gpios = <1>;", "apple,fix;")) + result = self.check("--strict") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout, "") + + def test_dropping_a_shared_property_from_one_board_warns(self): + self.dtb(self.head, "t8112-j413", dts("j413")) + result = self.check() + self.assertIn("t8112 /dcp@1000 shared: only on j473; j413", result.stdout) + + def test_resolved_drift_is_counted_and_variants_are_ignored(self): + self.dtb(self.head, "t8112-j413", dts("j413", "shared;", "hdmi-gpios = <1>;")) + self.dtb(self.head, "t8112-j413-fw27", dts("j413", "apple,variant-only;")) + result = self.check("--strict") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("drift 0, new 0, resolved 1", result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/dtc/apple-sibling-drift.py b/scripts/dtc/apple-sibling-drift.py new file mode 100755 index 00000000000000..37d7fea6dfb4cd --- /dev/null +++ b/scripts/dtc/apple-sibling-drift.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Warn when a change gives one board a property its sibling boards lack. + +Boards of one SoC (t8112-j413, t8112-j415, t8112-j473, t8112-j493) share most of +their device tree through the SoC's .dtsi files. A fix written for one Mac and put +in that Mac's .dts leaves its siblings without it, although they have the same +block. For every SoC with two or more boards, this looks at the nodes all of its +boards have and lists each property that only some of them carry ("drift"). + +Much drift is right (a desktop's HDMI port, a laptop's lid), so the existing drift +is the baseline: with --baseline-dtb-dir only drift the change adds is reported, +as a warning that names the boards with and without the property. Drift the change +removes is counted as resolved. Only board trees (-.dtb) are compared; +variants such as t8112-j413-fw27 are left out. --strict makes new drift fail. + +Install python3-libfdt (or pylibfdt) to read DTBs. +""" + +import argparse +from pathlib import Path +import re +import sys + +try: + import libfdt +except ImportError: + sys.exit("apple-sibling-drift: needs python3-libfdt (pylibfdt)") + +BOARD = re.compile(r"^(t\d{4})-(j\d+[a-z]*)\.dtb$") +SKIP_NODES = ("/aliases", "/chosen", "/memory", "/__symbols__", "/__fixups__", + "/__local_fixups__") +SKIP_PROPS = {"status", "phandle", "linux,phandle"} + + +def node_props(path): + fdt = libfdt.Fdt(path.read_bytes()) + nodes = {} + + def walk(offset, name): + props = set() + prop = fdt.first_property_offset(offset, libfdt.QUIET_NOTFOUND) + while prop >= 0: + props.add(fdt.get_property_by_offset(prop).name) + prop = fdt.next_property_offset(prop, libfdt.QUIET_NOTFOUND) + nodes[name] = props + child = fdt.first_subnode(offset, libfdt.QUIET_NOTFOUND) + while child >= 0: + walk(child, name.rstrip("/") + "/" + fdt.get_name(child)) + child = fdt.next_subnode(child, libfdt.QUIET_NOTFOUND) + + walk(0, "/") + return nodes + + +def drift(directory): + socs = {} + for path in sorted(Path(directory).glob("*.dtb")): + match = BOARD.match(path.name) + if match: + socs.setdefault(match.group(1), {})[match.group(2)] = node_props(path) + found = {} + for soc, boards in socs.items(): + if len(boards) < 2: + continue + common = set.intersection(*(set(nodes) for nodes in boards.values())) + for node in common: + if node.startswith(SKIP_NODES): + continue + for prop in set.union(*(boards[b][node] for b in boards)) - SKIP_PROPS: + have = frozenset(b for b in boards if prop in boards[b][node]) + if len(have) < len(boards): + found[(soc, node, prop)] = (have, frozenset(boards)) + return found + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--dtb-dir", required=True) + parser.add_argument("--baseline-dtb-dir") + parser.add_argument("--strict", action="store_true", help="fail on new drift") + parser.add_argument("--report", action="store_true", help="list all drift") + args = parser.parse_args() + + head = drift(args.dtb_dir) + base = drift(args.baseline_dtb_dir) if args.baseline_dtb_dir else {} + new = [] + for key, (have, boards) in sorted(head.items()): + old = base.get(key) + # New when the baseline had no drift here, or fewer boards carried it then. + if args.report or (args.baseline_dtb_dir and (old is None or not have <= old[0])): + new.append((key, have, boards)) + for (soc, node, prop), have, boards in new: + lack = sorted(boards - have) + print(f"::warning title=Sibling drift::{soc} {node} {prop}: only on " + f"{', '.join(sorted(have))}; {', '.join(lack)} have the node without it. " + f"Same block on every board: put it in the shared .dtsi; board-specific: " + f"nothing to do.") + resolved = sum(1 for key in base if key not in head) + print(f"apple-sibling-drift: drift {len(head)}, new {len(new) if not args.report else '-'}" + f", resolved {resolved}", file=sys.stderr) + return 1 if args.strict and new and not args.report else 0 + + +if __name__ == "__main__": + sys.exit(main()) From 0cb67690b3f5179c6a37ccafc14c10842cd39275 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Sun, 22 Nov 2026 14:38:08 -0800 Subject: [PATCH 1145/1514] spi: apple-qspi: admit the GD25UF64E, so the J775D's nvram partition can be written The J775D (Mac Studio, M5 Ultra) boot NOR reads JEDEC ID c8 83 17, a GigaDevice GD25UF64E (64 Mbit, 8 MiB), with no block protection left set (SR1 0x00, SR2 0x02: QE only, SR3 0x20). Its nvram partition is the ADT's anvram, 0xc0000 at 0x700000 (12 banks of 64 KiB), which ends within the part. Add the part with its size and no tolerated BP bits. The part-table checks in KUnit and in tools/asahi/qspi-nvram-tests.py list it, and a host-test case runs the GigaDevice status checks with the J775D's SR1/SR2/SR3 in its partition and refuses BP0. Signed-off-by: Jeff Queisser --- drivers/spi/spi-apple-qspi-policy-test.c | 15 ++++++++---- drivers/spi/spi-apple-qspi-policy.h | 19 +++++++++------- tools/asahi/qspi-nvram-tests.py | 29 ++++++++++++++++++++---- 3 files changed, 47 insertions(+), 16 deletions(-) diff --git a/drivers/spi/spi-apple-qspi-policy-test.c b/drivers/spi/spi-apple-qspi-policy-test.c index 68b7de086be2f0..0383e506b53382 100644 --- a/drivers/spi/spi-apple-qspi-policy-test.c +++ b/drivers/spi/spi-apple-qspi-policy-test.c @@ -183,6 +183,8 @@ static void qspi_policy_gd_status(struct kunit *test) /* The J700 GD25UF16E part: QE is set for good and BP0 by iBoot. */ KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x00, 0x02, 0x1c)); KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x04, 0x02, 0x1c)); + /* The J775D GD25UF64E part: QE only, no block protection tolerated. */ + KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x00, 0x02, 0)); KUNIT_EXPECT_FALSE(test, apple_qspi_gd_status_allows_write(0x04, 0x02, 0)); /* SRP0, SRP1 and LB1 to LB3 stay as found and do not block a write. */ KUNIT_EXPECT_TRUE(test, apple_qspi_gd_status_allows_write(0x80, 0x3b, 0x1c)); @@ -204,8 +206,10 @@ static void qspi_policy_part_status(struct kunit *test) KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xef, 0x20, 0, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0x20, 0, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xef, 0, 0, 0x04, 0x1c)); - /* GigaDevice SR3 bit 2 is LPE, a power setting. */ + /* GigaDevice SR3 bit 2 is LPE, a power setting; J775D leaves SR3 0x20. */ KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xc8, 0, 0, 0x04, 0x1c)); + KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xc8, 0x00, 0x02, 0x20, 0)); + KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0x04, 0x02, 0x20, 0)); KUNIT_EXPECT_TRUE(test, apple_qspi_part_status_allows_write(0xef, 0, 0x04, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc8, 0, 0x04, 0, 0x1c)); KUNIT_EXPECT_FALSE(test, apple_qspi_part_status_allows_write(0xc2, 0x20, 0, 0, 0x1c)); @@ -273,12 +277,15 @@ static void qspi_policy_parts(struct kunit *test) static const unsigned char known[][3] = { { 0xef, 0x65, 0x17 }, { 0xc2, 0x2b, 0x27 }, { 0xef, 0x65, 0x15 }, { 0xc8, 0x83, 0x15 }, + { 0xc8, 0x83, 0x17 }, }; - static const unsigned int sizes[] = { 0x800000, 0x800000, 0x200000, 0x200000 }; - static const unsigned char bp_ok[] = { 0, 0, 0x1c, 0x1c }; + static const unsigned int sizes[] = { 0x800000, 0x800000, 0x200000, 0x200000, + 0x800000 }; + static const unsigned char bp_ok[] = { 0, 0, 0x1c, 0x1c, 0 }; static const unsigned char unknown[][3] = { { 0xef, 0x65, 0x16 }, { 0xef, 0x40, 0x17 }, { 0xc2, 0x2b, 0x28 }, - { 0xc8, 0x60, 0x15 }, { 0, 0, 0 }, { 0xff, 0xff, 0xff }, + { 0xc8, 0x60, 0x15 }, { 0xc8, 0x83, 0x16 }, { 0xc8, 0x83, 0x18 }, + { 0, 0, 0 }, { 0xff, 0xff, 0xff }, }; const struct apple_qspi_part *part; unsigned int i; diff --git a/drivers/spi/spi-apple-qspi-policy.h b/drivers/spi/spi-apple-qspi-policy.h index f0ac13bf978b31..0a8e502cfcbb47 100644 --- a/drivers/spi/spi-apple-qspi-policy.h +++ b/drivers/spi/spi-apple-qspi-policy.h @@ -81,14 +81,14 @@ static inline int apple_qspi_mx_status_allows_write(unsigned int sr, #define APPLE_QSPI_MFR_GIGADEVICE 0xc8 /* - * GigaDevice GD25UF16E. SR1 holds WIP, WEL, five block-protect bits BP[4:0] - * at bits 6:2 and SRP0. SR2 holds SRP1, QE, SUS2 at bit 2, LB[3:1], CMP and - * SUS1 at bit 7. SR3 holds output drive, dummy-cycle and low-power settings - * and has no write-protect selection. BUSY and WEL, both suspend bits and - * CMP are always refused. BP[2:0] sit where they do on Winbond parts and - * are tolerated only where bp_ok allows them; BP3 and BP4 move or shrink - * the protected range and are refused unless bp_ok names them. SRP0, SRP1, - * QE and LB stay unchanged. + * GigaDevice GD25UF16E and GD25UF64E. SR1 holds WIP, WEL, five block-protect + * bits BP[4:0] at bits 6:2 and SRP0. SR2 holds SRP1, QE, SUS2 at bit 2, + * LB[3:1], CMP and SUS1 at bit 7. SR3 holds output drive, dummy-cycle and + * low-power settings and has no write-protect selection. BUSY and WEL, both + * suspend bits and CMP are always refused. BP[2:0] sit where they do on + * Winbond parts and are tolerated only where bp_ok allows them; BP3 and BP4 + * move or shrink the protected range and are refused unless bp_ok names them. + * SRP0, SRP1, QE and LB stay unchanged. */ static inline int apple_qspi_gd_status_allows_write(unsigned int sr1, unsigned int sr2, @@ -171,6 +171,7 @@ struct apple_qspi_part { #define APPLE_QSPI_JEDEC_W25Q16 { 0xef, 0x65, 0x15 } #define APPLE_QSPI_JEDEC_MX_2B27 { 0xc2, 0x2b, 0x27 } #define APPLE_QSPI_JEDEC_GD25UF16E { 0xc8, 0x83, 0x15 } +#define APPLE_QSPI_JEDEC_GD25UF64E { 0xc8, 0x83, 0x17 } static const struct apple_qspi_part apple_qspi_parts[] = { /* J613, J713, J813; also on the bus of some J616s */ @@ -181,6 +182,8 @@ static const struct apple_qspi_part apple_qspi_parts[] = { { APPLE_QSPI_JEDEC_W25Q16, 0x200000, 0x1c }, /* Some J700s; BP0 covers the same range */ { APPLE_QSPI_JEDEC_GD25UF16E, 0x200000, 0x1c }, + /* J775D (M5 Ultra): no block protection left set, SR1 0x00 */ + { APPLE_QSPI_JEDEC_GD25UF64E, 0x800000, 0 }, }; static inline const struct apple_qspi_part * diff --git a/tools/asahi/qspi-nvram-tests.py b/tools/asahi/qspi-nvram-tests.py index a67a44af650256..b34f00178013c2 100644 --- a/tools/asahi/qspi-nvram-tests.py +++ b/tools/asahi/qspi-nvram-tests.py @@ -167,16 +167,16 @@ def function(source, signature): static bool sent(unsigned int o){for(unsigned int i=0;isize==sizes[i]&&part->bp_ok==tolerated[i]); } const u8 unknown[][3]={{0xef,0x65,0x16},{0xef,0x65,0x18},{0xc2,0x2b,0x28},{0xc8,0x60,0x15},{0xef,0x40,0x17},{0,0,0},{0xff,0xff,0xff}}; for(unsigned int i=0;invram_write_candidate || qspi->write_fault', '!qspi->nvram_write_candidate || qspi->write_fault'), ('fault-latch', 'write_fault_latched = true;', 'write_fault_latched = false;'), From 46ca1b6a5718c36ee0904d2219d80d0fea5b5ed7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 09:54:50 +1100 Subject: [PATCH 1146/1514] thunderbolt: apple: refill the link-lost restart budget after a rebuilt domain When the peer drops the link with the cable still attached, the port is restarted up to three times. The count is reset once a peer has been found since the last restart, by comparing the domain's remote activity count with the value saved at that restart. A restart rebuilds the NHI and its domain, and the new domain counts remote activity from zero again. The saved value still belongs to the domain that went away, so whenever the new domain's discoveries end on the same number the reset is missed. On a J473 whose USB4 peer rebooted four times in six minutes the lines read (1/3), (1/3), (2/3), (3/3) although the host was found again after each one; the next peer reboot would have left the port down until the cable is replugged. Reset the saved value when the domain is created, to the new domain's starting count. Any discovery on the new domain then counts as a restart that worked, and a restart that finds nothing still uses up the budget. Signed-off-by: Ryan Murray --- drivers/thunderbolt/apple.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index ffeafa1c9bdbfb..f43baf608d3113 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -536,7 +536,7 @@ struct apple_cio { unsigned int start_gen; /* protected by lock: bumped by every start */ unsigned int link_lost_gen; /* start_gen when the peer went away */ unsigned int link_lost_cycles; /* protected by lock */ - u64 link_lost_cycle_activity; /* remote activity at the last cycle */ + u64 link_lost_cycle_activity; /* remote activity of this domain at the last cycle */ bool link_lost_restart; /* protected by lock: cycle requested */ struct notifier_block pm_notifier; struct notifier_block reboot_notifier; @@ -2795,6 +2795,13 @@ static int apple_nhi_probe(struct platform_device *pdev) acio->pcie_pm_prepared = false; acio->pcie_resume_expected = false; } + /* + * A port restart rebuilds the domain, whose remote activity count starts + * again at zero. Compare the next link loss against that, not against + * the count of the domain that went away: any discovery on this domain + * then marks the restart as having worked. + */ + WRITE_ONCE(acio->link_lost_cycle_activity, 0); ret = tb_domain_add(anhi->tb, false); if (ret) { dev_err_probe(anhi->dev, ret, "failed to add TB domain\n"); From 046908542bcd5b6aaf4f8f78e5ac8ec2453fb43a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 10:01:24 +1100 Subject: [PATCH 1147/1514] iommu: apple-dart: select a T8132 display DART's fw_mirror from its state fw_mirror for a T8132 internal display DART was keyed on apple_t8132_dcp_v27_2(): the 27.2.0 version and compat, the 26B123 image UUID and apple,clock-ids on the DCP that names the DART. That is a firmware-build gate. Any later 27.x image would lose fw_mirror, the DART would be refused, and the internal panel would not attach, though nothing about the DART or its handoff changed. What fw_mirror needs is the DART's own state, as on T6041, T6050, T8140 and T8142: locked, no reserved-table handoff (fw_handoff), and no display driver borrowing its live roots (preserve_display). Put that in one place, apple_dart_selects_fw_mirror(), and use it for every SoC. Which T8132 DARTs may take it is still decided by what uses them, now without the build: a DART is a candidate when an available apple,t8132-dcp names it (the DCP's iommus, or its PIODMA child's) and the boot loader handed that DCP over with its firmware clocks (apple,clock-ids). The clocks are what the firmware-27 backend needs and what tells its handoff from the M4 26.6.2 one, whose DARTs are borrowed; the loader publishes them from the ADT on any firmware-27 image, so no build or board is listed. Other locked T8132 DARTs keep the retained-root path they have today. On T6041 every locked DART takes fw_mirror, including the PMP's at 0x500300000, which T604x boot logs show locked. T8132 is not widened the same way: its PMP DART (0x380300000) is locked too (PROTECT 0x1e7 on J713), and moving it to fw_mirror would change how the PMP's DMA is mapped on a SoC where that has never run. No apple,t8132-dcp names it, and the external display DARTs are named by apple,t8132-dcpext, so neither is selected. A Mac mini's idle main DCP is not handed over and gets no apple,clock-ids, so its DARTs stay untouched as before. A candidate DART that is not locked, or that also has reserved tables, is still refused, with the same two messages. They no longer say "on the 27.2 image". Add a KUnit case for the selection: a locked candidate mirrors; a locked DART that no DCP names (the PMP's), an unlocked one, one with fw_handoff and a borrowed one do not. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 24 +++++++++ drivers/iommu/apple-dart.c | 88 ++++++++++++++++++++------------- 2 files changed, 78 insertions(+), 34 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 920097ea03f708..0b6dbac31e1559 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1346,6 +1346,29 @@ static u64 *apple_dart_test_reserved_table(struct kunit *test) return page_address(page); } +/* + * fw_mirror from the DART's own state: a T8132 DART its handed-over internal + * DCP names mirrors when locked without reserved tables and not borrowed; any + * other locked T8132 DART (the PMP's) keeps the retained-root path. + */ +static void apple_dart_test_t8132_fw_mirror_selection(struct kunit *test) +{ + struct apple_dart dart = { .locked = true }; + + KUNIT_EXPECT_TRUE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + /* A locked T8132 DART no display processor names: the PMP's. */ + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, false)); + + dart.locked = false; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + dart.locked = true; + dart.fw_handoff = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); + dart.fw_handoff = false; + dart.preserve_display = true; + KUNIT_EXPECT_FALSE(test, apple_dart_selects_fw_mirror(&dart, NULL, true)); +} + /* * A 27.2 T8132 internal display DART: re-exported firmware segments take the * protection of the live leaves that map them (read-only text, cacheable @@ -1454,6 +1477,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_locked_handoff), KUNIT_CASE(apple_dart_test_sync_unknown_roots), KUNIT_CASE(apple_dart_test_firmware_roots), + KUNIT_CASE(apple_dart_test_t8132_fw_mirror_selection), KUNIT_CASE(apple_dart_test_t8132_dcp_v27_fw_prot), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index bc582e3facb514..7ad0abc6ad2ee0 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -426,7 +426,7 @@ struct apple_dart { u32 sleep_gated : 1; /* Locked roots may hold firmware slots that mirror Linux mappings. */ u32 fw_mirror : 1; - /* A T8132 internal display DART on the 27.2 image (fw_mirror, not borrowed). */ + /* A T8132 internal display DART of a handed-over DCP (fw_mirror, not borrowed). */ u32 t8132_dcp_v27 : 1; /* * fw_mirror's four-level locked roots hold firmware's own subtrees, which @@ -5477,19 +5477,23 @@ static bool apple_dart_np_is_iommu_of(const struct device_node *consumer, } /* - * Whether @dart_np serves an available T8132 internal display processor the - * boot loader handed over with the 27.2 image (apple_t8132_dcp_v27_2()): its - * firmware DART (the processor's iommus) or its display DART (its PIODMA's). - * The DART is keyed on the handoff of the processor that uses it, not on its - * address or on the board. + * Whether @dart_np serves an available T8132 internal display processor that + * the boot loader handed over with its firmware clocks (apple,clock-ids, from + * the ADT's /arm-io/disp0): its firmware DART (the processor's iommus) or its + * display DART (its PIODMA's). Those clocks are what the firmware-27 backend + * needs and what tells its handoff from the M4 26.6.2 one, whose DARTs are + * borrowed. The DART is keyed on what uses it, not on its address, the board + * or the firmware build: a PMP or external display DART is never named here, + * and an idle main DCP (a Mac mini's) is not handed over. */ -static bool apple_dart_serves_t8132_dcp_v27(const struct device_node *dart_np) +static bool apple_dart_serves_t8132_dcp(const struct device_node *dart_np) { struct device_node *np, *child; bool serves = false; for_each_compatible_node(np, NULL, "apple,t8132-dcp") { - if (serves || !of_device_is_available(np) || !apple_t8132_dcp_v27_2(np)) + if (serves || !of_device_is_available(np) || + !of_property_present(np, "apple,clock-ids")) continue; serves = apple_dart_np_is_iommu_of(np, dart_np); for_each_child_of_node(np, child) @@ -5499,6 +5503,27 @@ static bool apple_dart_serves_t8132_dcp_v27(const struct device_node *dart_np) return serves; } +/* + * Whether a locked DART keeps its firmware's roots and mirrors Linux mappings + * into them (fw_mirror): it is locked, its boot loader handed over no reserved + * tables (fw_handoff), and no display driver borrows its live roots + * (preserve_display). That is the DART's own state; which DARTs take it is the + * SoC's (T6041, T6050, T8140, T8142: every one) or, on T8132, the DARTs of its + * handed-over internal display processor (@t8132_dcp). Other locked T8132 + * DARTs, the PMP's among them, keep the retained-root path they always had. + */ +static bool apple_dart_selects_fw_mirror(const struct apple_dart *dart, + const struct device_node *np, bool t8132_dcp) +{ + if (!dart->locked || dart->fw_handoff || dart->preserve_display) + return false; + return of_device_is_compatible(np, "apple,t6041-dart") || + of_device_is_compatible(np, "apple,t6050-dart") || + of_device_is_compatible(np, "apple,t8140-dart") || + of_device_is_compatible(np, "apple,t8142-dart") || + t8132_dcp; +} + static int apple_dart_probe(struct platform_device *pdev) { int ret, sid; @@ -5511,7 +5536,7 @@ static int apple_dart_probe(struct platform_device *pdev) bool tunneled = dev->of_node->parent && of_node_name_prefix(dev->of_node->parent, "usb4-pcie-tunnel-"); - bool j713_display, j713_dcpext, j713_dispext, j713_radio, t8132_display_v27 = false; + bool j713_display, j713_dcpext, j713_dispext, j713_radio, t8132_dcp = false; /* * The M4 internal display DARTs are live: DCP firmware (SID23) @@ -5523,17 +5548,17 @@ static int apple_dart_probe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL); /* - * The internal DCP handed over with the 27.2 image runs the firmware-27 - * backend, which DMAs through ordinary domains (RTKit and IOMFB shared - * memory, PIODMA maps) as on T6041. Its two display DARTs are then not - * borrowed: they keep their firmware's locked roots the way T6041's do - * (fw_mirror below). The borrowed path admits only the 26.6.2 layout - * and reserves its whole SID23 window from generic DMA. + * An internal DCP handed over with its firmware clocks runs the + * firmware-27 backend, which DMAs through ordinary domains (RTKit and + * IOMFB shared memory, PIODMA maps) as on T6041. Its two display DARTs + * are then not borrowed: they keep their firmware's locked roots the way + * T6041's do (fw_mirror below). The borrowed path admits only the 26.6.2 + * layout and reserves its whole SID23 window from generic DMA. */ - t8132_display_v27 = res && !tunneled && + t8132_dcp = res && !tunneled && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && - apple_dart_serves_t8132_dcp_v27(dev->of_node); - if (t8132_display_v27) + apple_dart_serves_t8132_dcp(dev->of_node); + if (t8132_dcp) j713_display = false; /* The external DCP firmware DARTs (SID23) of dcpext0 and dcpext1. */ j713_dcpext = res && !tunneled && apple_t8132_firmware_path() && @@ -5551,9 +5576,9 @@ static int apple_dart_probe(struct platform_device *pdev) /* * Off the qualified firmware nothing hands the internal display DARTs * over, but the running DCP still uses them: never reset them. A DART - * whose processor was handed over with the 27.2 image is handed over. + * whose processor was handed over with its firmware clocks is handed over. */ - if (res && !tunneled && !t8132_display_v27 && !apple_t8132_firmware_path() && + if (res && !tunneled && !t8132_dcp && !apple_t8132_firmware_path() && of_machine_is_compatible("apple,t8132") && of_device_is_compatible(dev->of_node, "apple,t8132-dart") && (res->start == 0x30a300000ULL || res->start == 0x30a340000ULL)) { @@ -6049,25 +6074,20 @@ static int apple_dart_probe(struct platform_device *pdev) * T6050's boot loader leaves every display DART locked on four-level * roots of its own (dart-dcpextN SID 23, dart-dispextN SIDs 0 and 16). */ - dart->fw_mirror = dart->locked && !dart->fw_handoff && - (of_device_is_compatible(dev->of_node, "apple,t6041-dart") || - of_device_is_compatible(dev->of_node, "apple,t6050-dart") || - of_device_is_compatible(dev->of_node, "apple,t8140-dart") || - of_device_is_compatible(dev->of_node, "apple,t8142-dart") || - t8132_display_v27); + dart->fw_mirror = apple_dart_selects_fw_mirror(dart, dev->of_node, t8132_dcp); /* * The firmware-27 backend runs on the locked roots alone: a DART that * is not locked, or whose boot loader also handed over reserved tables, * is not the handoff it was written for. Refuse either, saying which. */ - if (t8132_display_v27 && dart->fw_mirror) - dev_info(dev, "T8132 internal display DART on the 27.2 image: locked roots kept (mirror)\n"); - else if (t8132_display_v27 && !dart->locked) - dev_err(dev, "T8132 internal display DART on the 27.2 image: NOT locked: refusing\n"); - else if (t8132_display_v27) - dev_err(dev, "T8132 internal display DART on the 27.2 image: locked with a reserved-table handoff: refusing\n"); - dart->t8132_dcp_v27 = t8132_display_v27; - if (t8132_display_v27 && !dart->fw_mirror) { + if (t8132_dcp && dart->fw_mirror) + dev_info(dev, "T8132 internal display DART: locked roots kept (mirror)\n"); + else if (t8132_dcp && !dart->locked) + dev_err(dev, "T8132 internal display DART: NOT locked: refusing\n"); + else if (t8132_dcp) + dev_err(dev, "T8132 internal display DART: locked with a reserved-table handoff: refusing\n"); + dart->t8132_dcp_v27 = t8132_dcp; + if (t8132_dcp && !dart->fw_mirror) { ret = -EINVAL; goto err_clk_disable; } From ef48113b7930c1d7a7d3950aee6d243ef203de3c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 10:02:20 +1100 Subject: [PATCH 1148/1514] iommu: apple-dart: give any fw_mirror DART's firmware segments their leaves' protection The hook that maps re-exported firmware segments with the protection of the firmware's live leaves ran only on DARTs flagged t8132_dcp_v27, a flag set for one SoC's internal display DARTs on one firmware image. Every other fw_mirror DART still mapped such a segment read-write and uncached, which apple_dart_check_fw_map() refuses in a slot the firmware holds, so a boot loader re-exporting the same segments for another processor or image would need yet another opt-in. The hook does not need to know which DART it is. What makes it correct is the DART's own state and tables: fw_mirror (locked, no reserved-table handoff, not borrowed), a three-level root in reserved RAM, and live leaves that map every page of the region to exactly its physical address with one protection. Key it on that, drop the flag, and name the hook after fw_mirror. This cannot widen what a client gets: the protection comes from the firmware's own leaves, and it is changed only when it differs from what the region asked for. In that case the page sits in a firmware-held slot whose leaf maps it already, and apple_dart_check_fw_map() requires an exact match there, so the attach was being refused. Where an attach succeeds today the hook changes nothing. DARTs that are not fw_mirror are not touched, which is every locked T8132 DART except the internal display ones, the PMP's (0x380300000) included, and every borrowed DART (those return before the hook). Extend the KUnit case: a DART that is not fw_mirror, one with fw_handoff and an unlocked one keep the asked protection; the same DART back on fw_mirror takes the leaves' again. Signed-off-by: Ryan Murray --- drivers/iommu/apple-dart-test.c | 42 +++++++++++++++++++++++---------- drivers/iommu/apple-dart.c | 32 ++++++++++++------------- 2 files changed, 45 insertions(+), 29 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index 0b6dbac31e1559..e98f7d4af47082 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1370,11 +1370,12 @@ static void apple_dart_test_t8132_fw_mirror_selection(struct kunit *test) } /* - * A 27.2 T8132 internal display DART: re-exported firmware segments take the - * protection of the live leaves that map them (read-only text, cacheable - * data); a region whose leaf maps another page keeps what it asked for. + * A fw_mirror DART (here a T8132 internal display DART's layout): re-exported + * firmware segments take the protection of the live leaves that map them + * (read-only text, cacheable data); a region whose leaf maps another page + * keeps what it asked for. Any DART that is not fw_mirror is left alone. */ -static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) +static void apple_dart_test_fw_mirror_prot(struct kunit *test) { const u64 fields = GENMASK_ULL(51, 40) | BIT_ULL(0); const phys_addr_t text_pa = 0x80000000ULL, data_pa = 0x80100000ULL; @@ -1390,7 +1391,7 @@ static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) kunit_skip(test, "needs kernel pages of at least 16 KiB"); dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); KUNIT_ASSERT_NOT_NULL(test, dart); - dart->dev = kunit_device_register(test, "apple-dart-t8132-dcp-v27-test"); + dart->dev = kunit_device_register(test, "apple-dart-fw-mirror-prot-test"); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); regs = vzalloc(APPLE_DART_TEST_REGS_SIZE); KUNIT_ASSERT_NOT_NULL(test, regs); @@ -1402,7 +1403,6 @@ static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) dart->oas = 42; dart->locked = true; dart->fw_mirror = true; - dart->t8132_dcp_v27 = true; /* The display DARTs' window: 64 GiB at 1 TiB. */ dart->locked_window[23] = 0x10000000000ULL; root = apple_dart_test_reserved_table(test); @@ -1439,7 +1439,7 @@ static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) pm_runtime_set_active(dart->dev); pm_runtime_enable(dart->dev); - __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, data.prot, IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE); KUNIT_EXPECT_EQ(test, moved.prot, IOMMU_READ | IOMMU_WRITE); @@ -1449,22 +1449,38 @@ static void apple_dart_test_t8132_dcp_v27_fw_prot(struct kunit *test) /* A leaf table outside reserved RAM is never mapped: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; ClearPageReserved(virt_to_page(leaf)); - __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); SetPageReserved(virt_to_page(leaf)); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); /* A four-level root is not walked: nothing changes. */ text.prot = IOMMU_READ | IOMMU_WRITE; writel(dart->hw->tcr_4level, dart->regs + DART_TCR(dart, 23)); - __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); writel(0, dart->regs + DART_TCR(dart, 23)); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); - /* Not a 27.2 T8132 internal display DART: nothing changes. */ + /* + * Not fw_mirror (a locked DART on the retained-root path, such as the + * T8132 PMP's), with reserved tables, or unlocked: nothing changes. + */ text.prot = IOMMU_READ | IOMMU_WRITE; - dart->t8132_dcp_v27 = false; - __apple_dart_t8132_dcp_v27_fw_prot(&master, dart->dev, &head); + dart->fw_mirror = false; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->fw_mirror = true; + dart->fw_handoff = true; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->fw_handoff = false; + dart->locked = false; + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_WRITE); + dart->locked = true; + + /* The same DART back on fw_mirror takes the leaves' protection again. */ + __apple_dart_fw_mirror_prot(&master, dart->dev, &head); + KUNIT_EXPECT_EQ(test, text.prot, IOMMU_READ | IOMMU_CACHE); pm_runtime_disable(dart->dev); } @@ -1478,7 +1494,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_sync_unknown_roots), KUNIT_CASE(apple_dart_test_firmware_roots), KUNIT_CASE(apple_dart_test_t8132_fw_mirror_selection), - KUNIT_CASE(apple_dart_test_t8132_dcp_v27_fw_prot), + KUNIT_CASE(apple_dart_test_fw_mirror_prot), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 7ad0abc6ad2ee0..504ac451332735 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -426,8 +426,6 @@ struct apple_dart { u32 sleep_gated : 1; /* Locked roots may hold firmware slots that mirror Linux mappings. */ u32 fw_mirror : 1; - /* A T8132 internal display DART of a handed-over DCP (fw_mirror, not borrowed). */ - u32 t8132_dcp_v27 : 1; /* * fw_mirror's four-level locked roots hold firmware's own subtrees, which * are recorded and reserved (apple_dart_snapshot_fw_tree()). Set only for @@ -4565,18 +4563,20 @@ static void apple_dart_get_fw_resv_regions(struct device *dev, } /* - * A T8132 internal display DART on the 27.2 image (fw_mirror): the boot loader - * re-exports the firmware's own segments as iommu-addresses, which the core - * maps read-write, and uncached for this non-coherent DCP. The firmware's - * leaves say what those pages are: its text read-only, all of it cacheable. - * A Linux table in a slot the firmware holds must mirror its leaves exactly - * (apple_dart_fw_slot_mirrors()), so give each such region the protection the + * A fw_mirror DART (locked, no reserved-table handoff, not borrowed) on a + * three-level root: a boot loader may re-export the firmware's own segments + * as iommu-addresses, which the core maps read-write, and uncached for a + * non-coherent client such as a DCP. The firmware's leaves say what those + * pages are: its text read-only, all of it cacheable. A Linux table in a slot + * the firmware holds must mirror its leaves exactly (apple_dart_fw_slot_mirrors(), + * apple_dart_check_fw_map()), so give each such region the protection the * live leaves give every one of its pages. A region whose pages are not mapped * there, map elsewhere or disagree keeps its protection, and the attach then - * refuses it as before. + * refuses it as before. A region whose protection already matches is left + * alone, so this changes only a mapping the attach would otherwise refuse. */ -static void __apple_dart_t8132_dcp_v27_fw_prot(struct apple_dart_master_cfg *cfg, - struct device *dev, struct list_head *head) +static void __apple_dart_fw_mirror_prot(struct apple_dart_master_cfg *cfg, + struct device *dev, struct list_head *head) { const int mask = IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE; struct iommu_resv_region *region; @@ -4590,7 +4590,8 @@ static void __apple_dart_t8132_dcp_v27_fw_prot(struct apple_dart_master_cfg *cfg if (!cfg || !cfg->stream_maps[0].dart || cfg->stream_maps[1].dart) return; dart = cfg->stream_maps[0].dart; - if (!dart->t8132_dcp_v27 || !dart->locked || dart->hw->fmt != APPLE_DART2) + if (!dart->fw_mirror || dart->fw_handoff || !dart->locked || + dart->hw->fmt != APPLE_DART2) return; entries = dart->pgsize / sizeof(u64); sid = find_first_bit(cfg->stream_maps[0].sidmap, dart->num_streams); @@ -4666,9 +4667,9 @@ static void __apple_dart_t8132_dcp_v27_fw_prot(struct apple_dart_master_cfg *cfg memunmap(root); } -static void apple_dart_t8132_dcp_v27_fw_prot(struct device *dev, struct list_head *head) +static void apple_dart_fw_mirror_prot(struct device *dev, struct list_head *head) { - __apple_dart_t8132_dcp_v27_fw_prot(dev_iommu_priv_get(dev), dev, head); + __apple_dart_fw_mirror_prot(dev_iommu_priv_get(dev), dev, head); } static void apple_dart_get_resv_regions(struct device *dev, @@ -4700,7 +4701,7 @@ static void apple_dart_get_resv_regions(struct device *dev, /* Keep the translated-domain requirement and inherited translations. */ iommu_dma_get_resv_regions(dev, head); - apple_dart_t8132_dcp_v27_fw_prot(dev, head); + apple_dart_fw_mirror_prot(dev, head); apple_dart_get_fw_resv_regions(dev, head); } @@ -6086,7 +6087,6 @@ static int apple_dart_probe(struct platform_device *pdev) dev_err(dev, "T8132 internal display DART: NOT locked: refusing\n"); else if (t8132_dcp) dev_err(dev, "T8132 internal display DART: locked with a reserved-table handoff: refusing\n"); - dart->t8132_dcp_v27 = t8132_dcp; if (t8132_dcp && !dart->fw_mirror) { ret = -EINVAL; goto err_clk_disable; From b77cd1686972b877eee326eaaad09df0634578e2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 10:08:03 +1100 Subject: [PATCH 1149/1514] drm/asahi: correct the G14 27.2 compute flush_stamps comments The comments added with the compute flush_stamps word said that a clear word stalls a compute queue that writes user timestamps. A later A/B on the M2 mini showed that those hangs came from the raised GPU performance-state cap (reverted in #3091). With the cap restored, the same compute loop ran 24 times clean. Say only why the word is set: the 27.2 render commands and the M3 27.2 compute command set it. Comment-only change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 5 ++--- drivers/gpu/drm/asahi/gpu/v27_2.rs | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 0d5823fcd25277..ab5c322a27a7b6 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -100,9 +100,8 @@ pub(crate) const COMPUTE_USER_TIMESTAMPS: usize = 0x2dc; /// The 27.2 compute command's JobMeta flush_stamps word, after the completion stamp, firmware /// stamp, stamp value and slot (+0x298..+0x2b4); the render commands keep it at the same place -/// of their JobMeta (vertex +0x5a0, fragment +0x904). Set, the firmware flushes the command's -/// stamps when it completes; left clear, a compute queue whose commands write user timestamps -/// stalls with commands fetched but never retired. +/// of their JobMeta (vertex +0x5a0, fragment +0x904), and the M3 27.2 compute command sets it +/// when it does not coalesce. Set, the firmware flushes the command's stamps when it completes. pub(crate) const COMPUTE_FLUSH_STAMPS: usize = 0x2b4; /// The 13.5 compute JobParameters1 inside the 27.2 compute command. pub(crate) const COMPUTE_JOB_PARAMETERS1: usize = 0x68; diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1094ae6e308fff..6c141adf218078 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -120,8 +120,7 @@ fn encode_compute( put64(cmd, 0x2a0, q.fw_stamp); put32(cmd, 0x2a8, stamp_value); put32(cmd, 0x2b0, q.slot); - // flush_stamps, as the render commands set it: without it a queue of compute commands - // with user timestamps stops retiring. + // flush_stamps, as the render commands and the M3 27.2 compute command set it. put32(cmd, g14_v27_2_abi::COMPUTE_FLUSH_STAMPS, 1); put64(cmd, 0x2cc, timestamps); put64(cmd, 0x2d4, timestamps + 8); From a80960cf3279f7fb6c2d41c6dde532e924905d58 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 18:11:04 -0500 Subject: [PATCH 1150/1514] arm64: dts: apple: t8132-j773g: don't use the managed radio contract The J773g gets the J713's managed radio contract from t8132-jxxx.dtsi: apple,managed-sids on dart_apcie0 and pcie0. Under it the DART admits the radio's streams only if the boot chain left SID16 in its static bypass, or disabled with no valid root. This Mac hands its radio DART over unconfigured. Read in aura's Stage 2 proxy right before kboot, on the 27.2 system firmware (26B123), all 19 streams have TCR 0x1 (translate) with no valid TTBR, ENABLE_STREAMS is 0, and there are no errors, exceptions or masked errors. SID16 is in neither admitted state, so apple_dart_managed_admit() returns -EBUSY: 490000000.iommu fails probe with -16, port 0 defers forever and there is no Wi-Fi. The same -16 shows on the 26.6.2 firmware. Drop the contract on this board. apple,sid16-page applies only under it, so drop it too, with the DART's apple,dma-range window. Linux then resets and owns the radio DART and trains port 0 itself, as on a port without the contract. The iommu-map is unchanged. Only the J773g DTB changes. The J604, J623, J624, J713 and J715 DTBs are byte-identical. Signed-off-by: Diljit Singh --- arch/arm64/boot/dts/apple/t8132-j773g.dts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-j773g.dts b/arch/arm64/boot/dts/apple/t8132-j773g.dts index 2a8ca64d3a6385..9e92081da8b59f 100644 --- a/arch/arm64/boot/dts/apple/t8132-j773g.dts +++ b/arch/arm64/boot/dts/apple/t8132-j773g.dts @@ -259,6 +259,23 @@ brcm,board-type = "apple,sakhalin"; }; +/* + * This Mac hands its radio DART over unconfigured: every stream translates + * with no valid root and none is enabled. The managed radio contract only + * admits a SID16 left in its static bypass or disabled, so the DART would + * refuse the handover (-EBUSY) and port 0 would never probe. Linux owns the + * radio DART and trains port 0 itself instead. + */ +&dart_apcie0 { + /delete-property/ apple,managed-sids; + /delete-property/ apple,sid16-page; + /delete-property/ apple,dma-range; +}; + +&pcie0 { + /delete-property/ apple,managed-sids; +}; + #include "hwmon-common.dtsi" #include "hwmon-mini.dtsi" From 77a225f27b0a81a8c448c81892f681fef768e578 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:34:55 -0500 Subject: [PATCH 1151/1514] arm64: idle: defer the idle=nop override until built-in drivers probe On M4 and later cores the kernel ignores a loader's idle=nop and idles in WFI. On a K114c (M5 Max, chip 0x6050), switching to WFI that early let the unclaimed root domain nub_gpio gate off before pmgr and pinctrl probed: it was already off at the 76 ms pmgr probe and stayed write-refused, and the input chain, DP-1 and sound were missing. Keep the loader's spinning idle through boot and switch to WFI from a late_initcall_sync, after the built-in drivers' initcalls. cpu_do_idle() reads the idle selector on every entry, so the switch takes effect at once. Boots without idle=nop are unchanged. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Signed-off-by: Diljit Singh --- arch/arm64/kernel/idle.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/arch/arm64/kernel/idle.c b/arch/arm64/kernel/idle.c index 91a7fee038848e..a55e4f6144e09f 100644 --- a/arch/arm64/kernel/idle.c +++ b/arch/arm64/kernel/idle.c @@ -52,6 +52,7 @@ early_param("idle", setup_idle); */ static bool apple_wfi_loses_regs __ro_after_init; static bool apple_keep_idle_nop __initdata; +static bool apple_wfi_deferred __initdata; /* * Older boot loaders append idle=nop after the user's arguments on these @@ -79,13 +80,32 @@ void __init apple_wfi_quirk_init(void) * WFI states spin too): on T8142 the SoC sits near 90 C and * throttles, on T6050 the system draws about 10 W more at idle, on * T8140 the die idles at 85-92 C instead of 43 C. WFI is safe here. + * + * The switch waits until the built-in drivers have probed: on a + * K114c (M5 Max, chip 0x6050), WFI early in boot gated the unclaimed + * root domain nub_gpio off before pmgr and pinctrl probed. */ if (idle == ARM64_IDLE_NOP && !apple_keep_idle_nop) { - idle = ARM64_IDLE_WFI; - pr_info("Apple: idling in WFI, ignoring idle=nop\n"); + apple_wfi_deferred = true; + pr_info("Apple: WFI idling deferred until built-in drivers probe\n"); } } +/* + * Runs after the built-in drivers' initcalls. cpu_do_idle() reads idle on + * every entry, so the switch takes effect at once. + */ +static int __init apple_wfi_defer_enable(void) +{ + if (!apple_wfi_deferred) + return 0; + + idle = ARM64_IDLE_WFI; + pr_info("Apple: idling in WFI, ignoring idle=nop (after built-in probes)\n"); + return 0; +} +late_initcall_sync(apple_wfi_defer_enable); + static __always_inline bool apple_wfi_needs_save(void) { return unlikely(READ_ONCE(apple_wfi_loses_regs)); From 990b848a7a6e8af6dbd33adbd52e3009a3bf9d61 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 18:03:57 -0500 Subject: [PATCH 1152/1514] drm/asahi: g16: keep a VM's last PB epoch until its next render retires With the display manager running, gpubench-vk render.light kind=tri --mode procs at depth 16 faults in 5 to 11 of 13 runs on J773g, and the GPU can be lost for the rest of the boot. With the display manager stopped, the same kernels pass. Every fault has one shape: fault bank 3: status 0x8f81fdc021 va 0x704000cf00 (write unmapped level 0 unit 0xe0 ctx 62) attribution: busy=0 ctx=62 flight_matches=1 live_vm=Some(108) event=0xffffffff flights=1 Unit 0xe0 is gPM_SP(0), the parameter manager. The DYNAMIC window holds only PB page lists: the faulting addresses are records 16 to 976 of a VM's first (0x7040000000) or second (0x704000c000) page list. The context is an open client's, and the only flight is that client's cold InitBM render. kwin and the login greeter's VMs move the round-robin [home, alt] PB slot pairs, so 16 clients and those VMs share 16 warm slots and take displaced slots from each other while all are open. When another VM's epoch retires on slot k, retire_flight() replaces owners[k] and the open VM's epoch goes, unmapping its page list. At that VM's next InitBM, the parameter manager writes back to the page list of the manager the context used last, through that context, and the list is gone. Commit 047b934ce47a ("drm/asahi: g16: keep closed VMs' PB epochs until their slot is replaced") covered only closed VMs. Keep each VM's last retired epoch in Pools, indexed by its TTBAT slot, which the entry keeps bound. A newer render of the same VM replaces it once that render fully retired; a failed render keeps it. A closed VM's entry goes once none of its accepted renders is unpublished or in flight, so closed VMs pin nothing extra. An open VM whose slot was taken keeps one more epoch (two 32 KiB lists and its records) until its next render retires. Count such replacements as "kept" on the debugfs pb line. Add host tests for the open-VM sequence and the closed-VM release, and for the extra reclaim pass a closed VM's entry asks for. Fixes: e30cdb92b4f5 ("drm/asahi: g16: scale warm render PB/UMA slots to 16 and keep pass slots VM-affine") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/poll.rs | 7 +- drivers/gpu/drm/asahi/g16/pools.rs | 77 +++++++++- drivers/gpu/drm/asahi/g16/resources.rs | 6 + drivers/gpu/drm/asahi/g16/vm.rs | 9 ++ .../drivers/gpu/asahi-m4/test-poll-retire.py | 17 +++ .../drivers/gpu/asahi-m4/test-resources.py | 134 +++++++++++++++++- 6 files changed, 242 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 43647519f22025..6101777abaa1f3 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -639,9 +639,10 @@ impl Firmware { let Some(shared) = self.engine.shared.as_ref() else { return; }; - if !shared.closed_vm_reclaim.load(Ordering::Acquire) - || !shared.closed_vm_reclaim.swap(false, Ordering::AcqRel) - { + let armed = shared.closed_vm_reclaim.load(Ordering::Acquire) + && shared.closed_vm_reclaim.swap(false, Ordering::AcqRel); + // A closed VM's render retired and recorded its last epoch after the VM was closed. + if !self.pools.take_closed_vm_last() && !armed { return; } let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c08da53d7fac24..1cc226458d575b 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -77,6 +77,8 @@ pub(crate) struct PbStats { /// render counts again when it is retried). pub(crate) reused: u64, pub(crate) fresh: u64, + /// Retirements that replaced an open VM's owner epoch still kept as that VM's last epoch. + pub(crate) kept: u64, } pub(crate) struct PoolSet { @@ -501,7 +503,17 @@ pub(crate) struct Pools { quarantined: [bool; sizes::PB_SLOTS], /// Fresh PB epoch retained when an aborted render had not yet replaced `owners[k]`. quarantined_epochs: [Option>; sizes::PB_SLOTS], + /// Per TTBAT slot, the epoch of the last render its VM retired, kept until a newer render + /// of the same VM retires. The parameter manager writes back to the page list of the + /// manager a context used last, through that context, when the context's next InitBM + /// runs, also after another VM's epoch replaced `owners[k]` on the old slot. An entry + /// holds its VM and so the TTBAT slot that indexes it. + vm_last: [Option>; VM_LAST_ENTRIES], + /// A closed VM's [`Self::vm_last`] entry was recorded since the last reclaim pass. + closed_vm_last: bool, } +/// Entries of [`Pools::vm_last`]: one per TTBAT user slot (ASIDs `1..=MAX_VMS`). +const VM_LAST_ENTRIES: usize = sizes::MAX_VMS as usize + 1; impl Pools { #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { @@ -523,6 +535,8 @@ impl Pools { inflight: [0; sizes::PB_SLOTS], quarantined: [false; sizes::PB_SLOTS], quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, } } /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the @@ -549,6 +563,8 @@ impl Pools { inflight: [0; sizes::PB_SLOTS], quarantined: [false; sizes::PB_SLOTS], quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, }), GFP_KERNEL, )?) @@ -962,6 +978,14 @@ impl Pools { if self.quarantined[k] { return Ok(()); } + if self.owners[k].as_ref().is_some_and(|old| { + !Arc::ptr_eq(&old._vm, &epoch._vm) && !old._vm.vm.is_closed() && self.is_vm_last(old) + }) { + self.stats.kept += 1; + } + if completed { + self.note_vm_last(epoch); + } self.owners[k] = Some(epoch.clone()); self.retained_pb[k] = Some(epoch.records_lease()); if let Some(vm) = self.pending_vms[k].take() { @@ -977,6 +1001,33 @@ impl Pools { self.retire_epoch(k, binding, completed); Ok(()) } + /// Whether `epoch` is the last retired epoch of its VM ([`Self::vm_last`]). + fn is_vm_last(&self, epoch: &Arc) -> bool { + self.vm_last + .get(epoch._vm.slot as usize) + .and_then(Option::as_ref) + .is_some_and(|last| Arc::ptr_eq(last, epoch)) + } + /// A render of `epoch` retired normally: its VM's context has run that render's InitBM (or + /// reused the epoch), so the VM's earlier epoch is no longer written and may go. A closed + /// VM keeps an entry only until [`Self::reclaim_closed`] finds nothing of it pending. + fn note_vm_last(&mut self, epoch: &Arc) { + let vm = &epoch._vm; + let closed = vm.vm.is_closed(); + let Some(entry) = self.vm_last.get_mut(vm.slot as usize) else { + return; + }; + if entry.as_ref().is_some_and(|last| Arc::ptr_eq(last, epoch)) { + return; + } + *entry = Some(epoch.clone()); + self.closed_vm_last |= closed; + } + /// Whether a closed VM's entry was recorded since the last call: [`Self::reclaim_closed`] + /// must run again to release it. + pub(crate) fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } /// 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)] @@ -1042,6 +1093,7 @@ impl Pools { /// The owner epoch itself stays until a newer epoch retires on its slot /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter /// manager can still write that manager's page list through the context of the epoch's VM. + /// Also releases a closed VM's [`Self::vm_last`] entry once nothing of that VM is pending. pub(crate) fn reclaim_closed(&mut self) -> bool { let mut remaining = false; for k in 0..sizes::PB_SLOTS { @@ -1076,6 +1128,26 @@ impl Pools { remaining = true; } } + // A closed VM accepts no new render. Once none it accepted waits for publication or + // retirement, its context runs no further InitBM and its last epoch may go. A render + // left on a quarantined slot keeps its VM there anyway. + for i in 0..VM_LAST_ENTRIES { + let Some(vm) = self.vm_last[i].as_ref().map(|last| &last._vm) else { + continue; + }; + if !vm.vm.is_closed() { + continue; + } + let pending = (0..sizes::PB_SLOTS).any(|k| { + !self.quarantined[k] + && self.pending_vms[k].as_ref().is_some_and(|p| Arc::ptr_eq(p, vm)) + }); + if pending || vm.renders_unpublished() { + remaining = true; + } else { + self.vm_last[i] = None; + } + } remaining } #[allow(dead_code)] @@ -1087,12 +1159,13 @@ impl Pools { pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { writeln!( f, - "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {}", + "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {} kept {}", buffer::MAX_BLOCKS, self.stats.requests, self.stats.bad, self.stats.reused, - self.stats.fresh + self.stats.fresh, + self.stats.kept ) } } diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 0961b97b389035..385dbaaa3dfbb4 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -1031,6 +1031,12 @@ impl Cache { } } + /// Whether accepted renders still hold standby reservations, that is, are not yet + /// published ([`Prepared::commit_render`]) or dropped. + pub(crate) fn renders_unpublished(&self) -> bool { + self.standby.lock().reserved != 0 + } + /// 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. diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 0367a4421554c0..63bc92df970449 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -138,6 +138,15 @@ pub(crate) struct VmStateInner { pub(crate) live: Arc, } +impl VmStateInner { + /// Whether renders this VM's SUBMITs accepted are not yet published. + pub(crate) fn renders_unpublished(&self) -> bool { + self.resources + .as_ref() + .is_some_and(|cache| cache.renders_unpublished()) + } +} + impl Drop for VmStateInner { fn drop(&mut self) { mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 4634f0cc2bd0ea..8cdeb175dac37b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -284,12 +284,16 @@ def item(declaration, text=source): struct Pools { reclaim_calls: u32, reclaim_remaining: bool, + closed_vm_last: bool, } impl Pools { fn reclaim_closed(&mut self) -> bool { self.reclaim_calls += 1; self.reclaim_remaining } + fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } } #[derive(Default)] @@ -570,6 +574,19 @@ def item(declaration, text=source): .unwrap(); assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + // A closed VM's render retired after the flag cleared and recorded its last PB epoch: + // the next pass reclaims once without the flag, then scans stop again. + fw.pools.closed_vm_last = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); } #[test] 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 5aa9f7afbabfd2..e9b9840101e887 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -174,13 +174,16 @@ def module(text, name): pub mod vm { use crate::{mmu,sync::Arc}; use core::sync::atomic::{AtomicBool,Ordering}; - pub struct MockVm(AtomicBool); + pub struct MockVm(AtomicBool,AtomicBool); impl MockVm{ - pub fn new()->Self{Self(AtomicBool::new(false))} + pub fn new()->Self{Self(AtomicBool::new(false),AtomicBool::new(false))} pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} pub fn close(&self){self.0.store(true,Ordering::Release);} + // Accepted renders still unpublished (the VM cache's standby reservations). + pub fn set_unpublished(&self,v:bool){self.1.store(v,Ordering::Release);} } pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} + impl VmState{pub fn renders_unpublished(&self)->bool{self.vm.1.load(Ordering::Acquire)}} struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -1060,7 +1063,8 @@ def module(text, name): let _=p.bind(1,false);p.publish_flight(1); p.invalidate(); p.quarantine_flight(1,Some(e3.clone())); - assert_eq!(sync::Arc::strong_count(&e2),2,"prior slot owner epoch must stay mapped"); + // e2 is slot 1's prior owner and VM2's last retired epoch. + assert_eq!(sync::Arc::strong_count(&e2),3,"prior slot owner epoch must stay mapped"); assert_eq!(sync::Arc::strong_count(&e3),2,"aborted fresh epoch must stay mapped"); // Render class must NOT wedge: slot 2 is fresh and needed_slots advances to 3. assert!(!p.exhausted()); @@ -2969,6 +2973,130 @@ def module(text, name): assert!(!p.reclaim_closed()); } + // Live cross-VM steal of a warm PB slot (display manager active: kwin, its helpers and 16 + // clients over 16 warm slots). VM A's epoch owns slot 3. VM B's fresh epoch rebinds slot 3 + // and retires, replacing owners[3] while A is still open. A's next render is a cold InitBM + // on slot 4, the only flight; gPM_SP(0) then writes the old epoch's page list through A's + // context: "write unmapped level 0 unit 0xe0 ctx 62 ... flights=1 live_vm=Some(108)". + #[test]fn live_vm_displaced_pb_epoch_keeps_page_list_until_its_next_render_retires(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc, completed: bool| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, completed).unwrap(); + }; + + let a = vm(62); + let b = vm(5); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1, true); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb, true); + assert!(p.reusable(3, &a).is_none(), "slot 3 is bound to B's epoch"); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "A's page list unmapped while A is open"); + assert_eq!(p.stats.kept, 1); + + // A's next render binds slot 4 with InitBM. The old list stays while it is in flight + // and after a failed retirement, which need not have run the InitBM. + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, false).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "a failed render released the old list"); + let ea3 = epoch(&a, 4); + run(&mut p, &a, 4, &ea3, true); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "released after A's newer render retired"); + assert_eq!(sync::Arc::strong_count(&ea3), 3, "slot 4 owner and A's last epoch"); + assert_eq!(sync::Arc::strong_count(&eb), 3, "slot 3 owner and B's last epoch"); + // Warm reuse of the same epoch changes nothing. + run(&mut p, &b, 3, &eb, true); + assert_eq!(sync::Arc::strong_count(&eb), 3); + assert_eq!(p.stats.kept, 1); + // Open VMs never keep reclaim armed. + assert!(!p.take_closed_vm_last()); + assert!(!p.reclaim_closed()); + } + + // A closed VM keeps its last epoch while a render it accepted waits for publication or + // retirement, and loses it once none does, so its context and lists are not pinned. + #[test]fn closed_vm_last_pb_epoch_waits_for_its_accepted_renders(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, true).unwrap(); + }; + + let a = vm(20); + let b = vm(21); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + + // A closes with an accepted render not yet published. + a.vm.set_unpublished(true); + a.vm.close(); + assert!(p.reclaim_closed(), "accepted render of the closed VM still unpublished"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + // It publishes a fresh InitBM epoch on slot 4. + a.vm.set_unpublished(false); + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert!(p.reclaim_closed(), "render of the closed VM in flight"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "older epoch released after the InitBM"); + assert!(p.take_closed_vm_last(), "a closed VM's entry asks for another reclaim pass"); + assert!(!p.take_closed_vm_last()); + // B retires on slot 5, so slot 4 is displaced; nothing of A is pending any more. + let eb5 = epoch(&b, 5); + run(&mut p, &b, 5, &eb5); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&ea2), 2, "only slot 4's owner keeps A's last epoch"); + drop(ea1); + drop(ea2); + // Slot 4's owner holds A until a newer epoch retires there. + assert_eq!(sync::Arc::strong_count(&a), 2); + let eb4 = epoch(&b, 4); + run(&mut p, &b, 4, &eb4); + assert_eq!(sync::Arc::strong_count(&a), 1, "closed VM fully released"); + assert!(!p.reclaim_closed()); + } + } ''' poll_source = (production/'poll.rs').read_text() From c22324c488e1fb9d7d5ab1a31c63c16d7d93ba0f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 11:17:46 +1100 Subject: [PATCH 1153/1514] ci: give slow KUnit modules time in the smoke boot and speed up TCG On the Ubuntu 26.04 ARM runner the whole smoke run passed except raid6_kunit, which took longer than the 120 s per-module watchdog; its suite then passed (442 KUnit suites passed in that run). Raise the watchdog to 300 s; it only costs time when a module really hangs. Emulate pointer authentication with QEMU's implementation-defined algorithm (pauth-impdef=on). The architected one is slow under TCG and the kernel signs every return address; boot to the last initcall was about three times faster with it. Signed-off-by: Ryan Murray --- .github/scripts/kernel-smoke-qemu.sh | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/scripts/kernel-smoke-qemu.sh b/.github/scripts/kernel-smoke-qemu.sh index 73659216e7bf4d..0c20fda7e019d2 100755 --- a/.github/scripts/kernel-smoke-qemu.sh +++ b/.github/scripts/kernel-smoke-qemu.sh @@ -25,7 +25,9 @@ OUT=$(realpath -m "$4") HERE=$(dirname "$(realpath "$0")") EXPECTED=$HERE/kernel-smoke-expected.txt QEMU_TIMEOUT=${QEMU_TIMEOUT:-9000} -MOD_TIMEOUT=${MOD_TIMEOUT:-120} +# Per-module watchdog. Compute-heavy KUnit suites (raid6) need more than two +# minutes under emulation on the hosted ARM runners. +MOD_TIMEOUT=${MOD_TIMEOUT:-300} mkdir -p "$OUT" R=$(mktemp -d "$OUT/initramfs.XXXXXX") @@ -79,7 +81,9 @@ rm -rf "$R"; trap - EXIT ACCEL=tcg if [ -w /dev/kvm ] && [ "$(uname -m)" = aarch64 ]; then ACCEL=kvm; fi -CPU=max; [ $ACCEL = kvm ] && CPU=host +# pauth-impdef: the architected pointer-authentication algorithm is slow to +# emulate, and this kernel signs every return address. +CPU=max,pauth-impdef=on; [ $ACCEL = kvm ] && CPU=host echo "qemu: accel=$ACCEL kernel=$KREL" set +e : > "$OUT/console.log" From f445466d8f881c8cdcf3c9331afb408c0ecd28f4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 19:21:18 -0500 Subject: [PATCH 1154/1514] drm/asahi: g16: wake closed-VM reclaim on cancel and return abort suffix credits Address two review findings on the per-VM last PB epoch retention: - When a closed VM's final unpublished render reservation is cancelled, wake idle closed-VM reclaim so its displaced vm_last epoch and ASID do not stay pinned while idle. - When recovery retains an aborted job for quarantine and discards its unpublished suffix, return the discarded suffix's render credits while keeping the published quarantine backing intact. Add host regression tests covering both paths. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 13 +- drivers/gpu/drm/asahi/g16/poll.rs | 10 +- drivers/gpu/drm/asahi/g16/resources.rs | 51 +++- drivers/gpu/drm/asahi/g16/vm.rs | 1 + .../drivers/gpu/asahi-m4/test-resources.py | 257 +++++++++++++++++- 5 files changed, 299 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 7c7851ee6068a9..0a647cbbd2cb5f 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -251,8 +251,8 @@ pub(crate) struct Shared { /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. pub(crate) publish_wake: AtomicBool, - /// Set on VM close (and re-armed while any non-quarantined slot still holds a closed VM) - /// so displaced closed-VM slot leases are reclaimed without scanning on the hot path. + /// Set on VM close and when its last unpublished render reservation is released. + /// Re-armed while a closed VM still holds a lease awaiting reclaim. pub(crate) closed_vm_reclaim: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, @@ -507,6 +507,12 @@ impl Shared { } } + /// Arms and wakes the poll worker to reclaim closed VM leases. + pub(crate) fn wake_closed_vm_reclaim(self: &Arc) { + self.closed_vm_reclaim.store(true, Ordering::Release); + self.wake_publish(); + } + /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { self.feed.begin_shutdown(); @@ -904,8 +910,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); - self.shared.closed_vm_reclaim.store(true, Ordering::Release); - self.shared.wake_publish(); + self.shared.wake_closed_vm_reclaim(); } fn new_queue( diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 6101777abaa1f3..d189df2e4560d7 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -741,11 +741,10 @@ impl Firmware { self.reclaim_closed_vm_slots(); } // Skip redundant `publish_checked()` walks on busy polls where nothing could have - // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for - // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), - // while `publish_woke` covers external state changes (VM close, unstarted queue - // cancellation) and `ta_wave_ready()` wakes TA-wave-paced renders when a `0x70` TA - // pass finishes while FS is still running. + // unblocked `engine.pending`. Standby release wakes `Cache::prepare` waiters, which + // enter `submit_locked()` directly. `publish_woke` covers external state changes + // including a closed VM's final reservation release. `ta_wave_ready()` wakes + // TA-wave-paced renders when a `0x70` TA pass finishes while FS is still running. let coalesce_due = self.engine.coalesce_deadline_ns != 0 && (!evented || now >= self.engine.coalesce_deadline_ns); let should_publish = !self.engine.pending.is_empty() @@ -1687,6 +1686,7 @@ impl Firmware { p.pending.store(false, Ordering::Relaxed); self.engine.pending.retain(|j| !Arc::ptr_eq(j, &job)); p.count.store(p.sent(), Ordering::Relaxed); + job.resources.discard_unpublished_renders(); } if receipt.owner_retired() && self.engine.flights.iter().all(|other| { diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 385dbaaa3dfbb4..56e87b15b8dad4 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -11,6 +11,7 @@ use super::{ pools::{PbEpoch, PoolSet}, slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, + Shared, }; use crate::mmu; use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -921,12 +922,14 @@ pub(crate) struct Cache { bind: mmu::VmBind, live: Arc, budget: Arc, + shared: Arc, } impl Cache { pub(crate) fn new( factory: Factory, bind: mmu::VmBind, live: Arc, + shared: Arc, ) -> Result> { let budget = super::budget::Budget::new()?; let epochs = KVec::with_capacity(super::budget::LIMIT as usize, GFP_KERNEL)?; @@ -943,7 +946,7 @@ impl Cache { standby_available <- new_condvar!(), closed: AtomicBool::new(false), active_render_passes: AtomicU32::new(0), - factory, bind, live, budget }), + factory, bind, live, budget, shared }), GFP_KERNEL, ) } @@ -986,11 +989,13 @@ impl Cache { if count == 0 { return; } - let (mut wake, excess) = { + let (mut wake, reclaim, excess) = { let mut standby = self.standby.lock(); standby.reserved = standby.reserved.saturating_sub(count); let wake = standby.waiters != 0; - let keep = if self.closed.load(Ordering::Acquire) { + let closed = self.closed.load(Ordering::Acquire); + let reclaim = closed && standby.reserved == 0; + let keep = if closed { standby.reserved as usize } else { (standby.reserved as usize).max(SPARE_EPOCHS) @@ -1000,7 +1005,7 @@ impl Cache { } else { None }; - (wake, excess) + (wake, reclaim, excess) }; if let Some(excess) = excess { drop(excess); @@ -1029,6 +1034,14 @@ impl Cache { if wake { self.standby_available.notify_all(); } + if reclaim { + self.shared.wake_closed_vm_reclaim(); + } + } + + fn release_render_passes(&self, count: u32) { + let previous = self.active_render_passes.fetch_sub(count, Ordering::AcqRel); + debug_assert!(previous >= count); } /// Whether accepted renders still hold standby reservations, that is, are not yet @@ -1450,7 +1463,7 @@ impl Cache { render_ext, pb_heap_ext, pb_ext, - total_renders: render_count, + active_renders: AtomicU32::new(render_count), unpublished_renders: AtomicU32::new(render_count), cache, }) @@ -1473,8 +1486,8 @@ pub(crate) struct Prepared { pub(crate) pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], - /// Total render commands accounted against `Cache::active_render_passes`. - total_renders: u32, + /// Render commands still accounted against `Cache::active_render_passes`. + active_renders: AtomicU32, /// 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. @@ -1483,18 +1496,28 @@ pub(crate) struct Prepared { impl Drop for Prepared { fn drop(&mut self) { - let Some(cache) = self.cache.take() else { + let Some(cache) = &self.cache else { return; }; - let previous = cache - .active_render_passes - .fetch_sub(self.total_renders, Ordering::AcqRel); - debug_assert!(previous >= self.total_renders); - let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); - cache.release_reserved(remaining); + cache.release_render_passes(*self.active_renders.get_mut()); + cache.release_reserved(*self.unpublished_renders.get_mut()); } } impl Prepared { + /// Returns canceled render credits even if the job stays retained for its published work. + /// The device lock serializes suffix discard with publication. + pub(crate) fn discard_unpublished_renders(&self) { + let Some(cache) = &self.cache else { + return; + }; + let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); + if remaining != 0 { + self.active_renders.fetch_sub(remaining, Ordering::AcqRel); + cache.release_render_passes(remaining); + cache.release_reserved(remaining); + } + } + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { self.compute.as_deref().ok_or(EINVAL) } diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 63bc92df970449..735b6743bed66b 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -415,6 +415,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul factory, live.bind.as_ref().ok_or(EIO)?.clone(), live.clone(), + gpu.shared.clone(), )?; let inner = VmStateInner { id, 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 e9b9840101e887..27cc9aab32d726 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -174,16 +174,42 @@ def module(text, name): pub mod vm { use crate::{mmu,sync::Arc}; use core::sync::atomic::{AtomicBool,Ordering}; - pub struct MockVm(AtomicBool,AtomicBool); + use super::resources::reservations::Cache; + pub struct MockVm { + closed: AtomicBool, + unpublished: AtomicBool, + cache: Option>, + _live: Option>, + } impl MockVm{ - pub fn new()->Self{Self(AtomicBool::new(false),AtomicBool::new(false))} - pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} - pub fn close(&self){self.0.store(true,Ordering::Release);} + pub fn new() -> Self { + Self { + closed: AtomicBool::new(false), + unpublished: AtomicBool::new(false), + cache: None, + _live: None, + } + } + pub fn tracked(cache: Arc) -> (Self, std::sync::Arc) { + let live = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1)); + let released = std::sync::Arc::new(AtomicBool::new(false)); + let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); + let bind = mmu::VmBind { live, released: released.clone() }; + let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0 }, 0).unwrap(); + (Self { cache: Some(cache), _live: Some(token), ..Self::new() }, released) + } + pub fn is_closed(&self)->bool{self.closed.load(Ordering::Acquire)} + pub fn close(&self){self.closed.store(true,Ordering::Release);} // Accepted renders still unpublished (the VM cache's standby reservations). - pub fn set_unpublished(&self,v:bool){self.1.store(v,Ordering::Release);} + pub fn set_unpublished(&self,v:bool){self.unpublished.store(v,Ordering::Release);} } pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} - impl VmState{pub fn renders_unpublished(&self)->bool{self.vm.1.load(Ordering::Acquire)}} + impl VmState { + pub fn renders_unpublished(&self) -> bool { + self.vm.unpublished.load(Ordering::Acquire) + || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) + } + } struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -260,6 +286,197 @@ def module(text, name): pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; __RENDER_BURST__ + + pub(crate) mod reservations { + use super::{ComputeArena as ComputeUnitSet, PoolExtArena, RenderArena}; + use crate::{ + device::Device, + driver::AsahiDrmDevice, + g16::{budget::Budget, object::Factory, pools::{PbEpoch, Pools}, slots::Slots, vm::{MockVm, VmState}}, + sync::{Arc, CondVar, Mutex}, + KVec, + }; + use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + #[derive(Default)] + pub(crate) struct Shared { + closed_vm_reclaim: AtomicBool, + publish_wake: AtomicBool, + started: AtomicBool, + sleeping: AtomicBool, + poll_queued: AtomicBool, + } + impl Shared { + __WAKE_PUBLISH__ + __WAKE_CLOSED_VM_RECLAIM__ + + fn poll_now(&self) { + self.poll_queued.store(true, Ordering::Release); + } + } + + __STANDBY__ + __SPARE_EPOCHS__ + struct RenderExtArena; + struct PbHeapExtArena; + const EXT_RENDER_TIERS: [(); 0] = []; + const PB_HEAP_EXT_TIERS: [(); 0] = []; + const EXT_PB_SLOTS: usize = 1; + + pub(crate) struct Cache { + standby: Mutex, + standby_available: CondVar, + closed: AtomicBool, + active_render_passes: AtomicU32, + shared: Arc, + } + impl Cache { + __RELEASE_RESERVED__ + __RELEASE_RENDER_PASSES__ + __RENDERS_UNPUBLISHED__ + } + + __PREPARED__ + __DROP_PREPARED__ + impl Prepared { + __COMMIT_RENDER__ + __DISCARD_UNPUBLISHED__ + } + + struct Engine { + shared: Option>, + } + struct Firmware { + engine: Engine, + pools: Pools, + slots: Slots, + } + impl Firmware { + __RECLAIM_CLOSED_VM_SLOTS__ + + fn idle_poll(&mut self) { + let shared = self.engine.shared.as_ref().unwrap(); + assert!(shared.poll_queued.swap(false, Ordering::AcqRel), "poll must be queued"); + self.reclaim_closed_vm_slots(); + } + } + + fn displaced_vm(credits: u32) -> ( + Firmware, Arc, Arc, Arc, std::sync::Arc, Prepared, + ) { + let shared = Arc::new(Shared::default(), 0).unwrap(); + shared.started.store(true, Ordering::Release); + let cache = Arc::new(Cache { + standby: Mutex::new(Standby { epochs: KVec::new(), reserved: credits, waiters: 0 }), + standby_available: CondVar::new(), + closed: AtomicBool::new(false), + active_render_passes: AtomicU32::new(credits), + shared: shared.clone(), + }, 0).unwrap(); + let (vm, released) = MockVm::tracked(cache.clone()); + let vm = Arc::new(VmState { id: 1, slot: 1, generation: 1, vm }, 0).unwrap(); + let replacement = crate::resources::vm(2); + let mut pools = Pools::new(&AsahiDrmDevice(Device)); + let budget = Budget::new().unwrap(); + for _ in 0..credits { + let credit = Budget::reserve(&budget, 1).unwrap().take().unwrap(); + cache.standby.lock().epochs.push(PbEpoch::new(&Factory, &vm, credit).unwrap(), 0).unwrap(); + } + let epoch = exposed_epoch(&budget, &vm, 0); + let newer = exposed_epoch(&budget, &replacement, 0); + for (owner, backing) in [(&vm, &epoch), (&replacement, &newer)] { + let binding = pools.bind(0, false); + pools.hold_alloc(0, owner, None, None).unwrap(); + pools.publish_flight(0); + pools.retire_flight(0, backing, binding, true).unwrap(); + } + let firmware = Firmware { + engine: Engine { shared: Some(shared) }, + pools, + slots: Slots::new().unwrap(), + }; + let prepared = Prepared { + active_renders: AtomicU32::new(credits), + unpublished_renders: AtomicU32::new(credits), + cache: Some(cache.clone()), + compute: None, + compute_ext: None, + compute_scs: false, + render: None, + render_scs: false, + render_ext: [], + pb_heap_ext: [], + pb_ext: [Some(Arc::new(PoolExtArena, 0).unwrap())], + }; + (firmware, cache, vm, epoch, released, prepared) + } + + fn exposed_epoch(budget: &Arc, vm: &Arc, slot: usize) -> Arc { + let credit = Budget::reserve(budget, 1).unwrap().take().unwrap(); + let e = PbEpoch::new(&Factory, vm, credit).unwrap(); + e.prepare(slot, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + } + + #[test] + fn cancel_last_unpublished_render_wakes_idle_reclaim_and_releases_asid() { + let (mut fw, cache, vm, epoch, released, job) = displaced_vm(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert!(cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert_eq!(Arc::strong_count(&epoch), 2, "vm_last still holds the epoch"); + assert!(!cache.shared.poll_queued.load(Ordering::Acquire)); + drop(epoch); + drop(vm); + assert!(!released.load(Ordering::Acquire)); + + drop(job); + assert_eq!(cache.standby.lock().reserved, 0); + fw.idle_poll(); + assert!(!cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert!(released.load(Ordering::Acquire), "idle poll released the ASID and last PB epoch"); + } + + #[test] + fn passed_abort_returns_unpublished_credits_and_preserves_quarantine() { + let (mut fw, cache, vm, old_epoch, released, job) = displaced_vm(3); + let aborted = cache.standby.lock().epochs.pop().unwrap(); + aborted.prepare(1, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + aborted.expose(); + fw.pools.bind(1, false); + fw.pools.hold_alloc(1, &vm, None, None).unwrap(); + fw.pools.publish_flight(1); + job.commit_render(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 2); + assert_eq!(cache.standby.lock().reserved, 2); + + fw.pools.quarantine_flight(1, Some(aborted.clone())); + let retained = Arc::new(job, 0).unwrap(); + retained.discard_unpublished_renders(); + retained.discard_unpublished_renders(); + let reserved = cache.standby.lock().reserved; + assert_eq!(reserved, 0); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 1); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 1, "vm_last released the displaced epoch"); + assert_eq!(fw.pools.quarantined_mask(), 1 << 1); + assert_eq!(Arc::strong_count(&aborted), 2); + assert!(retained.pb_ext[0].is_some(), "retained job still owns its arena"); + drop(old_epoch); + drop(aborted); + drop(vm); + assert!(!released.load(Ordering::Acquire), "quarantine pins the published ASID"); + drop(retained); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 0); + } + } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} pub mod engine { @@ -634,7 +851,7 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{ + pub(super) fn vm(id:u64)->sync::Arc{ sync::Arc::new( g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, ).unwrap() @@ -3108,8 +3325,9 @@ def module(text, name): assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' assert 'closed_vm_reclaim' in mod_source -assert 'self.shared.closed_vm_reclaim.store(true, Ordering::Release);' in mod_source +assert 'self.shared.wake_closed_vm_reclaim();' in item(mod_source, 'fn vm_closed(') assert 'reclaim_closed_vm_slots' in poll_source +assert 'job.resources.discard_unpublished_renders();' in item(poll_source, 'if p.is_pending()') lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' @@ -3142,6 +3360,24 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +for placeholder, source_text, declaration in ( + ('__WAKE_PUBLISH__', mod_source, 'pub(crate) fn wake_publish('), + ('__WAKE_CLOSED_VM_RECLAIM__', mod_source, 'pub(crate) fn wake_closed_vm_reclaim('), + ('__STANDBY__', resources_source, 'struct Standby {'), + ('__RELEASE_RESERVED__', resources_source, 'fn release_reserved('), + ('__RELEASE_RENDER_PASSES__', resources_source, 'fn release_render_passes('), + ('__RENDERS_UNPUBLISHED__', resources_source, 'pub(crate) fn renders_unpublished('), + ('__PREPARED__', resources_source, 'pub(crate) struct Prepared {'), + ('__DROP_PREPARED__', resources_source, 'impl Drop for Prepared'), + ('__COMMIT_RENDER__', resources_source, 'pub(crate) fn commit_render('), + ('__DISCARD_UNPUBLISHED__', resources_source, 'pub(crate) fn discard_unpublished_renders('), + ('__RECLAIM_CLOSED_VM_SLOTS__', poll_source, 'pub(crate) fn reclaim_closed_vm_slots('), +): + method = item(source_text, declaration) + # The host Arc wrapper uses Deref without the kernel's arbitrary self types. + source = source.replace(placeholder, method.replace('self: &Arc', '&self')) +source = source.replace('__SPARE_EPOCHS__', next( + line for line in resources_source.splitlines() if line.startswith('const SPARE_EPOCHS:'))) object_source = (production/'object.rs').read_text() # A firmware-cached object with an uncached GPU lower alias is cleaned to the point of # coherency after every host store; only that combination sets the flag. @@ -3218,9 +3454,10 @@ def module(text, name): (out/'resource-host.log').write_text(log) if result.returncode: raise SystemExit(result.returncode) -files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] +files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs', 'mod.rs', 'poll.rs', 'vm.rs'] +test_count = int(next(line.split()[3] for line in log.splitlines() if line.startswith('test result: ok.'))) (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 41, + 'result': 'pass', 'tests': test_count, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 68eec53e7991c93553e04b8e68078ad5ee750cac Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 10:08:19 +1100 Subject: [PATCH 1155/1514] drm/apple: audio: name each display's card and keep its ELD current The two DP/HDMI audio outputs of a Mac mini M2 showed up as identical 'Built-in Audio HDMI / DisplayPort Output [Apple DisplayPort]', and the USB-C one never carried its monitor's name: its ELD was the basic-audio fallback, without the name or vendor, although the connector's EDID has both. The ELD is built from the connector's EDID as the audio service connects. On the classic path that happens once per service instance, at its Open, and on a Type-C processor the Open comes before the route is up and the display's EDID is read (at boot, and again as the service is published after a sleep), so the card kept the fallback. Refresh a connected card's ELD whenever its processor publishes an EDID, and tell userspace through the ELD control; a card without a sink stays so. Name each card after the output its processor drives, as its device tree node describes it (apple,connector-type): 'Apple HDMI' (card id HDMI), 'Apple USB-C DisplayPort' (USBC) or 'Apple DisplayPort', so that the cards and the sound server's fallback names are told apart. The driver name, which UCM matches, stays apple_dcp. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio-link-test.c | 57 +++++++++++++++++ drivers/gpu/drm/apple/audio.c | 61 ++++++++++++++++++- drivers/gpu/drm/apple/audio.h | 1 + drivers/gpu/drm/apple/av.c | 13 ++++ drivers/gpu/drm/apple/av.h | 3 + drivers/gpu/drm/apple/iomfb.c | 6 ++ .../selftests/drivers/gpu/apple-dcp/rate.py | 1 + 7 files changed, 139 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/audio-link-test.c b/drivers/gpu/drm/apple/audio-link-test.c index 1b0ac5f147c4a4..3ece300bbff249 100644 --- a/drivers/gpu/drm/apple/audio-link-test.c +++ b/drivers/gpu/drm/apple/audio-link-test.c @@ -687,6 +687,61 @@ static void dcpaud_sleep_ends_cleared_dma(struct kunit *test) KUNIT_EXPECT_EQ(test, atomic_read(&audio->dev->power.usage_count), 0); } +/* The monitor's ELD, as drm builds it from an EDID with a name: 'QG270 S3' */ +static int dcpaud_eld_test_sink(struct device *dev, u8 *eld, size_t size) +{ + static const char name[] = "QG270 S3"; + + memset(eld, 0, size); + eld[DRM_ELD_VER] = DRM_ELD_VER_CEA861D; + eld[DRM_ELD_CEA_EDID_VER_MNL] = DRM_ELD_CEA_EDID_VER_CEA861BCD | + (sizeof(name) - 1); + eld[DRM_ELD_MANUFACTURER_NAME0] = 0x04; + eld[DRM_ELD_MANUFACTURER_NAME1] = 0x72; + memcpy(eld + DRM_ELD_MONITOR_NAME_STRING, name, sizeof(name) - 1); + return 0; +} + +/* + * A Type-C processor's service connects before its route's EDID is read: the + * card has the basic fallback. Once the EDID is published, it takes the name. + */ +static void dcpaud_eld_refresh_takes_monitor_name(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + u8 eld[DCPAUD_ELD_SIZE]; + + mutex_init(&dcpaud->data_lock); + dcpaud->connected = true; + dcpaud_build_eld(dcpaud, dcpaud->eld); /* no EDID yet: fallback */ + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 0); + KUNIT_EXPECT_EQ(test, drm_eld_sad_count(dcpaud->eld), 1); + + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + dcpaud_build_eld(dcpaud, eld); + KUNIT_EXPECT_TRUE(test, dcpaud_eld_update(dcpaud, eld)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + KUNIT_EXPECT_MEMEQ(test, dcpaud->eld + DRM_ELD_MONITOR_NAME_STRING, "QG270 S3", 8); + KUNIT_EXPECT_EQ(test, drm_eld_sad_count(dcpaud->eld), 1); + /* The same ELD again is no change. */ + KUNIT_EXPECT_FALSE(test, dcpaud_eld_update(dcpaud, eld)); +} + +/* A card without a sink keeps its zero ELD: the jack follows the firmware. */ +static void dcpaud_eld_refresh_needs_connection(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + u8 eld[DCPAUD_ELD_SIZE]; + + mutex_init(&dcpaud->data_lock); + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + dcpaud_build_eld(dcpaud, eld); + KUNIT_EXPECT_FALSE(test, dcpaud_eld_update(dcpaud, eld)); + KUNIT_EXPECT_EQ(test, dcpaud->eld[DRM_ELD_VER], 0); +} + static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_link_release_instance), KUNIT_CASE(dcpaud_disconnect_sync_completes_live_owner), @@ -707,6 +762,8 @@ static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_sleep_suspends_running_stream), KUNIT_CASE(dcpaud_sleep_releases_held_link), KUNIT_CASE(dcpaud_sleep_ends_cleared_dma), + KUNIT_CASE(dcpaud_eld_refresh_takes_monitor_name), + KUNIT_CASE(dcpaud_eld_refresh_needs_connection), {} }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 7ffc1448119012..1208caa075dfd9 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -67,6 +67,9 @@ #define DCPAUD_HELD_PERIOD_MAX_US 50000 struct dcp_audio { + /* The display output the processor drives, from its device tree node */ + const char *port_name; + const char *port_id; struct device *dev; struct device *dcp_dev; struct device *dma_dev; @@ -1780,13 +1783,32 @@ static int dcpaud_create_jack(struct dcp_audio *dcpaud) &dcpaud->jack, true, false); } +/* + * Names the card after the output its processor drives, as the device tree + * describes it, so that each display's card is told apart: "Apple HDMI" + * (card id HDMI), "Apple USB-C DisplayPort" (USBC), "Apple DisplayPort". + * ALSA makes a repeated id unique. + */ +static void dcpaud_port_names(struct dcp_audio *dcpaud, struct device_node *dcp_node) +{ + dcpaud->port_name = "DisplayPort"; + dcpaud->port_id = "DisplayPort"; + if (of_property_match_string(dcp_node, "apple,connector-type", "HDMI-A") >= 0) { + dcpaud->port_name = "HDMI"; + dcpaud->port_id = "HDMI"; + } else if (of_property_match_string(dcp_node, "apple,connector-type", "USB-C") >= 0) { + dcpaud->port_name = "USB-C DisplayPort"; + dcpaud->port_id = "USBC"; + } +} + static void dcpaud_set_card_names(struct dcp_audio *dcpaud) { struct snd_card *card = dcpaud->card; strscpy(card->driver, "apple_dcp", sizeof(card->driver)); - strscpy(card->longname, "Apple DisplayPort", sizeof(card->longname)); - strscpy(card->shortname, "Apple DisplayPort", sizeof(card->shortname)); + snprintf(card->shortname, sizeof(card->shortname), "Apple %s", dcpaud->port_name); + snprintf(card->longname, sizeof(card->longname), "Apple %s audio", dcpaud->port_name); } #ifdef CONFIG_SND_DEBUG @@ -1824,7 +1846,7 @@ static int dcpaud_init_snd_card(struct dcp_audio *dcpaud) return -ENODEV; - ret = snd_card_new(dcpaud->dev, DCPAUD_CARD_SLOTS, SNDRV_DEFAULT_STR1, + ret = snd_card_new(dcpaud->dev, DCPAUD_CARD_SLOTS, dcpaud->port_id, THIS_MODULE, 0, &dcpaud->card); if (ret) return ret; @@ -1874,6 +1896,38 @@ void dcpaud_connect(struct platform_device *pdev, bool connected) dcpaud_report_hotplug(dcpaud, connected, eld); } +/* + * The connected sink's ELD, built again from the connector's EDID. The ELD is + * built as the audio service connects, which on a Type-C processor can come + * before its route is up and the display's EDID is read (at boot, and as the + * service is published again after a sleep): the card would keep the basic + * fallback without the monitor's name. A card that is not connected stays so. + * Returns whether the stored ELD changed. + */ +static bool dcpaud_eld_update(struct dcp_audio *dcpaud, const u8 *eld) +{ + bool changed; + + mutex_lock(&dcpaud->data_lock); + changed = dcpaud->connected && memcmp(dcpaud->eld, eld, DCPAUD_ELD_SIZE); + if (changed) + memcpy(dcpaud->eld, eld, DCPAUD_ELD_SIZE); + mutex_unlock(&dcpaud->data_lock); + return changed; +} + +void dcpaud_refresh_eld(struct platform_device *pdev) +{ + struct dcp_audio *dcpaud = platform_get_drvdata(pdev); + u8 eld[DCPAUD_ELD_SIZE]; + + if (!dcpaud || !dcpaud->dcp_dev || !dcpaud->card) + return; + dcpaud_build_eld(dcpaud, eld); + if (dcpaud_eld_update(dcpaud, eld)) + snd_ctl_notify(dcpaud->card, SNDRV_CTL_EVENT_MASK_VALUE, &dcpaud->eld_ctl->id); +} + void dcpaud_disconnect(struct platform_device *pdev) { struct dcp_audio *dcpaud; @@ -1918,6 +1972,7 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dev_info(dev, "No audio support\n"); goto rpm_put; } + dcpaud_port_names(dcpaud, dcp_node); index = of_property_match_string(dev->of_node, "dma-names", "tx"); if (index < 0) { diff --git a/drivers/gpu/drm/apple/audio.h b/drivers/gpu/drm/apple/audio.h index baf83a50eea61a..6d60750cc315ae 100644 --- a/drivers/gpu/drm/apple/audio.h +++ b/drivers/gpu/drm/apple/audio.h @@ -17,6 +17,7 @@ int dcp_audio_sink_eld(struct device *dev, u8 *eld, size_t size); void dcpaud_connect(struct platform_device *pdev, bool connected); void dcpaud_disconnect(struct platform_device *pdev); +void dcpaud_refresh_eld(struct platform_device *pdev); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) /* Native link methods for 14.7 and desktop 26.x external roles. */ diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index 038ab364541780..f685bce973e5a0 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -1081,6 +1081,19 @@ static const struct apple_epic_service_ops avep_ops[] = { {} }; +void av_audio_sink_changed(struct apple_dcp *dcp) +{ + struct audiosrv_data *asrv = dcp->audiosrv; + + /* A CEC-only endpoint has no audio owner (av_service_connect()). */ + if (!asrv) + return; + scoped_guard(mutex, &asrv->plug_lock) { + if (asrv->audio_dev) + dcpaud_refresh_eld(asrv->audio_dev); + } +} + /* Whether @service is the published instance; plug_lock held, then srv_rwsem */ static bool av_audiosrv_published(struct audiosrv_data *asrv, struct apple_epic_service *service) diff --git a/drivers/gpu/drm/apple/av.h b/drivers/gpu/drm/apple/av.h index 82b5cc3388fd86..c41a853a573822 100644 --- a/drivers/gpu/drm/apple/av.h +++ b/drivers/gpu/drm/apple/av.h @@ -12,6 +12,8 @@ extern bool hdmi_audio; #if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) void av_service_connect(struct apple_dcp *dcp); void av_service_disconnect(struct apple_dcp *dcp); +/* The sink's EDID was published again: a connected card takes its ELD. */ +void av_audio_sink_changed(struct apple_dcp *dcp); /* Stop and drain owner work after the caller stops its native initializer. */ void av_audiosrv_quiesce(struct apple_dcp *dcp); /* Pair of av_audiosrv_quiesce after a later successful bind. */ @@ -25,6 +27,7 @@ static inline void av_audio_before_modeset(struct apple_dcp *dcp) { } #else static inline void av_service_connect(struct apple_dcp *dcp) { } static inline void av_service_disconnect(struct apple_dcp *dcp) { } +static inline void av_audio_sink_changed(struct apple_dcp *dcp) { } static inline void av_audiosrv_quiesce(struct apple_dcp *dcp) { } static inline void av_audiosrv_reports_restart(struct apple_dcp *dcp) { } static inline void av_audio_before_modeset(struct apple_dcp *dcp) { } diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index a431791daf9f9b..36bb6361fa4a97 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -37,6 +37,7 @@ #include #include +#include "av.h" #include "cec.h" #include "dcp.h" #include "dcp-hdr-metadata.h" @@ -2954,6 +2955,11 @@ int dcp_get_modes(struct drm_connector *connector) } edid_done: + /* + * The connector's ELD follows its EDID: a card connected before this + * EDID was published (a Type-C route's service opens first) takes it now. + */ + av_audio_sink_changed(dcp); /* Discovery can replace the catalogue while the OOB read waits. */ if (dcp_is_ext26(dcp)) { if (READ_ONCE(dcp->crashed) || READ_ONCE(dcp->ext26_blocked)) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py index d8087416a52eb6..30eba776e8eee9 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/rate.py @@ -936,6 +936,7 @@ def publication(root): static bool cancel_work_sync(struct work_struct *w) { assert(!w->scheduled); return false; } /* Native audio is out of scope: reject entry instead of silently queueing it. */ static void dcp_external_audio_start(struct apple_dcp *d) { assert(!d->external_native); } +static void av_audio_sink_changed(struct apple_dcp *d) { (void)d; } /* The stubbed read always carries an EDID: nothing asks for a re-probe. */ static bool dcpavserv_edid_retry(struct apple_dcp *d,u64 e) { (void)d;(void)e;assert(0);return false; } static void dcpavserv_edid_retry_reset(struct apple_dcp *d) { assert(d->dcpavserv.lock); } From b1e599fbe90a562f0ee57d391d00289c34b5e1cf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 11:53:20 +1100 Subject: [PATCH 1156/1514] drm/apple: allocate the larger parser test fixtures through KUnit The synthetic ADT buffer and the two-mode catalogue push their respective test frames past 2048 bytes with generic KASAN and WERROR. Use KUnit-managed storage for those fixtures and preserve their initialization and checks. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/parser-test.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index 245818de86732f..ee646567808356 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -1791,6 +1791,7 @@ static void parser_panel_of_dimensions(struct kunit *test) static void parser_panel_publication(struct kunit *test, enum dcp_firmware_version fw_compat, bool desktop_state) { + const size_t adt_capacity = 512; const char *gamut = fw_compat == DCP_FIRMWARE_H17P ? "sRGB" : "P3"; struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); struct dcp_desktop_state *desktop = kunit_kzalloc(test, sizeof(*desktop), GFP_KERNEL); @@ -1803,7 +1804,7 @@ static void parser_panel_publication(struct kunit *test, }; struct dcp_panel_adt before = panel; __le32 matrix[10]; - u8 adt[512]; + u8 *adt = kunit_kmalloc(test, adt_capacity, GFP_KERNEL); size_t adt_size; struct device *dev = drm_kunit_helper_alloc_device(test); struct drm_device *drm; @@ -1821,11 +1822,12 @@ static void parser_panel_publication(struct kunit *test, KUNIT_ASSERT_NOT_NULL(test, id); KUNIT_ASSERT_NOT_NULL(test, pipeline); KUNIT_ASSERT_NOT_NULL(test, connector); + KUNIT_ASSERT_NOT_NULL(test, adt); ret = drmm_connector_init(drm, &connector->base, &parser_route_connector_funcs, DRM_MODE_CONNECTOR_eDP, NULL); KUNIT_ASSERT_EQ(test, ret, 0); parser_adt_synthetic_matrix(matrix, 1 << 20); - adt_size = parser_adt_color_fixture(adt, sizeof(adt), gamut, strlen(gamut) + 1, + adt_size = parser_adt_color_fixture(adt, adt_capacity, gamut, strlen(gamut) + 1, matrix, sizeof(matrix)); KUNIT_ASSERT_GT(test, adt_size, (size_t)0); ret = dcp_panel_adt_parse(adt, adt_size, &panel); @@ -2029,12 +2031,13 @@ static void parser_desktop_metadata_timing(struct kunit *test) */ static void parser_internal_v27_only_120hz(struct kunit *test) { - struct dcp_display_mode catalog[2] = {}; + struct dcp_display_mode *catalog = kunit_kcalloc(test, 2, sizeof(*catalog), GFP_KERNEL); struct apple_dcp *dcp = kunit_kzalloc(test, sizeof(*dcp), GFP_KERNEL); struct platform_device *pipeline = kunit_kzalloc(test, sizeof(*pipeline), GFP_KERNEL); struct apple_connector *connector = kunit_kzalloc(test, sizeof(*connector), GFP_KERNEL); unsigned int i; + KUNIT_ASSERT_NOT_NULL(test, catalog); KUNIT_ASSERT_NOT_NULL(test, dcp); KUNIT_ASSERT_NOT_NULL(test, pipeline); KUNIT_ASSERT_NOT_NULL(test, connector); From 59c72f163caa586e27901dc0ffb144507bb3104e Mon Sep 17 00:00:00 2001 From: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:58:11 -0700 Subject: [PATCH 1157/1514] arm64: dts: apple: t6050-k114s: describe the NVRAM partition The K114s ADT has the boot NOR's NVRAM at /arm-io/qspi/spinor/anvram: offset 0x700000, 0xc0000 bytes, 12 banks of 64 KiB. Describe that one partition, with the nvram alias that asahi-bless and the boot loader use to find it, as the K114c and J775D do. Only this partition is described, so the rest of the NOR has no device node. The flash is single-wire, as on the J775D, so spi-nor sends no quad-enable status write at probe. The partition is read-only, as on the K114c. The node follows Rolando Trevino's J716s node (rolotrealanis98/ m5pro-linux, contrib/pending/nvram), itself after the J775D. Also say in the file header that only this block has run on the hardware, instead of calling the whole file unbooted. Signed-off-by: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6050-k114s.dts | 40 ++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index caa609babef0d5..2b88e99a6d9939 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -4,7 +4,8 @@ * * target-type: K114s (Mac17,13) * - * Preliminary: described from the ADT only, not yet booted on the hardware. + * Preliminary: described from the ADT. Only the NVRAM partition below has been run on a K114s, + * from the boot loader's tree; this file as a whole has not been booted. * * Copyright The Asahi Linux Contributors */ @@ -22,3 +23,40 @@ #define T6050_K114S #include "t6050-peripherals.dtsi" + +/ { + aliases { + /* asahi-bless and the boot loader find the NVRAM partition by this alias */ + nvram = &nvram; + }; +}; + +/* + * The boot NOR's NVRAM partition (ADT /arm-io/qspi/spinor/anvram: reg 0x700000, 0xc0000, 12 + * banks of 64 KiB). Only this partition is described, so the rest of the NOR has no device + * node. Single-wire, as on the J775D: spi-nor then sends no quad-enable status write at probe. + * The partition is read-only, as on the K114c. + */ +&qspi { + status = "okay"; + + flash@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + spi-max-frequency = <25000000>; + spi-rx-bus-width = <1>; + spi-tx-bus-width = <1>; + + partitions { + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; + + nvram: partition@700000 { + label = "nvram"; + reg = <0x700000 0xc0000>; + read-only; + }; + }; + }; +}; From fb544885d9267db5a90abc605557cd795a299e4a Mon Sep 17 00:00:00 2001 From: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:03:18 -0700 Subject: [PATCH 1158/1514] dt-bindings: sound: apple,macaudio: add the K114 The 14-inch MacBook Pro with the PROLED display (K114s, Mac17,13) gets its own machine-driver compatible, as the K116 does, for the driver entry and the device tree card that follow. Signed-off-by: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> --- Documentation/devicetree/bindings/sound/apple,macaudio.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml index c9880a39e9b29c..d1f19d065dab5a 100644 --- a/Documentation/devicetree/bindings/sound/apple,macaudio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,macaudio.yaml @@ -56,6 +56,7 @@ properties: - apple,j813-macaudio - apple,j815-macaudio - apple,j873-macaudio + - apple,k114-macaudio - apple,k116-macaudio - const: apple,macaudio - description: From 9d3eeaa5d8ddd80c3868280ff5376425443c42c5 Mon Sep 17 00:00:00 2001 From: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:03:18 -0700 Subject: [PATCH 1159/1514] ASoC: apple: macaudio: add the K114 (14-inch M5 Pro), jack only The K114s's Apple device tree describes the sound hardware of the K116s and the J714s node for node: a CS42L84 jack codec on the AOP's "cout" stream and six SN012776 amplifiers on its "spkr" stream, in the same frames. Add an entry with the J714s's jack configuration. No speaker protection data exists for this chassis: no speakersafetyd profile and no qualified speakerguardd tuning. The entry therefore has the speakers disabled and no safe level, as the J873 and J775 have, so macaudio_speakers_allowed() refuses a "Speaker" link however the device tree is written. The amplifier type and layout are the J714s's and are not used while the speakers are disabled; admitting them needs protection data for this chassis first. The admission KUnit case asserts the refusal, and the amp-level case that checks no board carries an SN012776 gain lists the entry. Seen on one K114s (firmware 27.2) with an earlier cut of this entry (speakers disabled as here; it set safe_vol -20): the card registers, the CS42L84 probes and registers its jack input, and the mixer has the jack controls and no speaker volume or protection control. Nothing was played; no headphones were plugged in. Signed-off-by: Chris O'Hearn <137103567+chrisohearn@users.noreply.github.com> --- sound/soc/apple/macaudio-admission-test.h | 2 ++ sound/soc/apple/macaudio-amp-level-test.h | 2 +- sound/soc/apple/macaudio.c | 23 +++++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/sound/soc/apple/macaudio-admission-test.h b/sound/soc/apple/macaudio-admission-test.h index 17c7f19c9cd988..491f2531012978 100644 --- a/sound/soc/apple/macaudio-admission-test.h +++ b/sound/soc/apple/macaudio-admission-test.h @@ -17,6 +17,8 @@ static void macaudio_admission_needs_a_safe_level(struct kunit *test) KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j873_cfg)); /* The Mac Studio M5: no sense and no protection owner yet, speaker off */ KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_j775_cfg)); + /* K114: the J714 amps and frame, but no safe level for the chassis */ + KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&macaudio_k114_cfg)); cfg = macaudio_j413_cfg; cfg.safe_vol = 0; KUNIT_EXPECT_FALSE(test, macaudio_speakers_allowed(&cfg)); diff --git a/sound/soc/apple/macaudio-amp-level-test.h b/sound/soc/apple/macaudio-amp-level-test.h index a684c616b4a62b..b97939e10c672c 100644 --- a/sound/soc/apple/macaudio-amp-level-test.h +++ b/sound/soc/apple/macaudio-amp-level-test.h @@ -96,7 +96,7 @@ static void macaudio_level_no_table(struct kunit *test) &macaudio_j493_cfg, &macaudio_j575c_j773_cfg, &macaudio_j604_cfg, &macaudio_j614_cfg, &macaudio_j616_cfg, &macaudio_j713_cfg, &macaudio_j714_cfg, &macaudio_j715_cfg, &macaudio_j813_cfg, - &macaudio_j775_cfg, &macaudio_j873_cfg, + &macaudio_j775_cfg, &macaudio_j873_cfg, &macaudio_k114_cfg, }; unsigned int i; diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index ae4c96a816fe4d..90f955ea559a3f 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -4191,6 +4191,27 @@ struct macaudio_platform_cfg macaudio_j714_cfg = { .tweeter_hpf_granted = true, }; +/* + * K114s (T6050, MacBook Pro 14" M5 Pro): the J714s's AOP-fed card for the + * headphone jack only. Its ADT describes the same jack codec, AOP audio + * service and six SN012776 as the J714s's, but no speaker protection data + * exists for this chassis, so the speakers stay off as on the J873: no safe + * level and speakers disabled, so macaudio_speakers_allowed() refuses a + * speaker link however the DT is written. The jack frame is the J714s's. + */ +struct macaudio_platform_cfg macaudio_k114_cfg = { + .enable_speakers = false, + .amp = AMP_SN012776, + .speakers = SPKR_2W1T, + .stereo = true, + .safe_vol = 0, + .fe_dai_names = { "j873-pcm-0", "j873-pcm-1", "j873-pcm-2" }, + .dai_fmt = SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_CBC_CFC | SND_SOC_DAIFMT_IB_NF, + .spk_dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBC_CFC | + SND_SOC_DAIFMT_GATED | SND_SOC_DAIFMT_NB_IF, + .spk_secondary_only = true, +}; + /* * J815 (T8142, MacBook Air M5 15"): J813's AOP-fed card with six SN012776, * two woofers and a tweeter per side, in ADT speaker-config order (left @@ -4502,6 +4523,8 @@ static const struct of_device_id macaudio_snd_device_id[] = { { .compatible = "apple,j714-macaudio", .data = &macaudio_j714_cfg }, /* k116 - sn012776 15 2x 2W+1T (AOP-fed, V/I sense; the 16" PROLED chassis, J714's amps and frame) */ { .compatible = "apple,k116-macaudio", .data = &macaudio_j714_cfg }, + /* k114 - sn012776 - 2x 2W+1T (AOP-fed; jack only, speakers off) */ + { .compatible = "apple,k114-macaudio", .data = &macaudio_k114_cfg }, /* j713 - sn012776 15 2x 1W+1T (AOP-fed, one serializer) */ { .compatible = "apple,j713-macaudio", .data = &macaudio_j713_cfg }, /* The J713 jack runs on the AOP like the J616s one. */ From 97d8a30c021a8bdca784e7cccd791d5c6bc3de80 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 20:11:51 -0500 Subject: [PATCH 1160/1514] dt-bindings: chosen: document Apple T8132 DAPF hand-off properties Register the linux-enablement-mac vendor prefix and describe the three /chosen string-array properties read by Aura's T8132 DAPF hand-off path (src/dapf.c) and already used in the T8132 board device trees (t8132-jxxx.dtsi, t8132-laptop.dtsi, t8132-j604.dts): - linux-enablement-mac,dapf-handoff - linux-enablement-mac,dapf-power-on-handoff - linux-enablement-mac,dapf-halted-handoff This removes the existing dt-validate warnings on T8132 /chosen nodes and unblocks board trees adding linux-enablement-mac,dapf-halted-handoff. Signed-off-by: Diljit Singh --- .../linux-enablement-mac,dapf-handoff.yaml | 51 +++++++++++++++++++ .../devicetree/bindings/vendor-prefixes.yaml | 2 + 2 files changed, 53 insertions(+) create mode 100644 Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml diff --git a/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml new file mode 100644 index 00000000000000..e88332b7af2781 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,dapf-handoff.yaml @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/linux-enablement-mac,dapf-handoff.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8132 DAPF consumer hand-off + +maintainers: + - Diljit Singh + +description: + Board device trees on Apple T8132 Macs describe which ADT consumers need + their DART access protection filters (DAPFs) programmed by the bootloader + before handing control to Linux, and whether a consumer must be powered on + or programmed as halted prior to hand-off. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + linux-enablement-mac,dapf-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + ADT paths of consumers (for example "/arm-io/aop", "/arm-io/mtp", + "/arm-io/pmp") whose DART access protection filters the bootloader + programs for hand-off to Linux. + + linux-enablement-mac,dapf-power-on-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + Subset of consumers listed in linux-enablement-mac,dapf-handoff that + the bootloader powers on before programming their DAPFs and leaves + powered across hand-off. + + linux-enablement-mac,dapf-halted-handoff: + $ref: /schemas/types.yaml#/definitions/string-array + description: + Subset of consumers listed in linux-enablement-mac,dapf-handoff that + boot firmware leaves halted and unpowered, whose DAPFs the bootloader + programs for a halted consumer so Linux can cold-start them. + +additionalProperties: true +... diff --git a/Documentation/devicetree/bindings/vendor-prefixes.yaml b/Documentation/devicetree/bindings/vendor-prefixes.yaml index 4775b267e1f771..7e8a847ea70ab6 100644 --- a/Documentation/devicetree/bindings/vendor-prefixes.yaml +++ b/Documentation/devicetree/bindings/vendor-prefixes.yaml @@ -983,6 +983,8 @@ patternProperties: description: Linutronix GmbH "^linux,.*": description: Linux-specific binding + "^linux-enablement-mac,.*": + description: Aurora Silicon Apple silicon loader hand-off bindings "^linx,.*": description: Linx Technologies "^liontron,.*": From f52be70014c3ee99ec65f6e29e2d7a0c0363b747 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 12:15:22 +1100 Subject: [PATCH 1161/1514] drm/apple: audio: keep a card's ELD while its EDID is cleared The EDID code also reaches the ELD refresh after clearing a stale EDID (an old route or service instance) and while a read is still to be retried after a resume. A connected card's ELD then fell back to basic stereo without the monitor's name until the next good probe. Only an ELD built from an EDID replaces the stored one now. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio-link-test.c | 26 +++++++++++++++++++++++++ drivers/gpu/drm/apple/audio.c | 21 +++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/audio-link-test.c b/drivers/gpu/drm/apple/audio-link-test.c index 3ece300bbff249..908b0e73bc3f2d 100644 --- a/drivers/gpu/drm/apple/audio-link-test.c +++ b/drivers/gpu/drm/apple/audio-link-test.c @@ -742,6 +742,31 @@ static void dcpaud_eld_refresh_needs_connection(struct kunit *test) KUNIT_EXPECT_EQ(test, dcpaud->eld[DRM_ELD_VER], 0); } +/* The EDID was cleared (stale route) or is still to be read: no ELD */ +static int dcpaud_eld_test_no_edid(struct device *dev, u8 *eld, size_t size) +{ + memset(eld, 0, size); + return -ENODATA; +} + +/* A cleared or unread EDID leaves a connected card's named ELD as it is. */ +static void dcpaud_eld_refresh_keeps_name_without_edid(struct kunit *test) +{ + struct platform_device *pdev; + struct dcp_audio *dcpaud = dcpaud_link_setup(test, &pdev); + + mutex_init(&dcpaud->data_lock); + dcpaud->connected = true; + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_sink); + KUNIT_EXPECT_TRUE(test, dcpaud_refresh_eld_from_edid(dcpaud)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + + kunit_activate_static_stub(test, dcp_audio_sink_eld, dcpaud_eld_test_no_edid); + KUNIT_EXPECT_FALSE(test, dcpaud_refresh_eld_from_edid(dcpaud)); + KUNIT_EXPECT_EQ(test, drm_eld_mnl(dcpaud->eld), 8); + KUNIT_EXPECT_MEMEQ(test, dcpaud->eld + DRM_ELD_MONITOR_NAME_STRING, "QG270 S3", 8); +} + static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_link_release_instance), KUNIT_CASE(dcpaud_disconnect_sync_completes_live_owner), @@ -764,6 +789,7 @@ static struct kunit_case dcpaud_link_cases[] = { KUNIT_CASE(dcpaud_sleep_ends_cleared_dma), KUNIT_CASE(dcpaud_eld_refresh_takes_monitor_name), KUNIT_CASE(dcpaud_eld_refresh_needs_connection), + KUNIT_CASE(dcpaud_eld_refresh_keeps_name_without_edid), {} }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 1208caa075dfd9..f4db111e675858 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -1916,15 +1916,30 @@ static bool dcpaud_eld_update(struct dcp_audio *dcpaud, const u8 *eld) return changed; } +/* + * Only an ELD built from an EDID replaces the stored one. The EDID code also + * ends here after clearing a stale EDID (an old route or service) or while a + * read is still to be retried; the card then keeps what it has rather than + * falling back to basic stereo without the monitor's name. + */ +static bool dcpaud_refresh_eld_from_edid(struct dcp_audio *dcpaud) +{ + u8 eld[DCPAUD_ELD_SIZE]; + + if (dcp_audio_sink_eld(dcpaud->dcp_dev, eld, DCPAUD_ELD_SIZE) || + !eld[DRM_ELD_VER]) + return false; + dcpaud_build_eld(dcpaud, eld); + return dcpaud_eld_update(dcpaud, eld); +} + void dcpaud_refresh_eld(struct platform_device *pdev) { struct dcp_audio *dcpaud = platform_get_drvdata(pdev); - u8 eld[DCPAUD_ELD_SIZE]; if (!dcpaud || !dcpaud->dcp_dev || !dcpaud->card) return; - dcpaud_build_eld(dcpaud, eld); - if (dcpaud_eld_update(dcpaud, eld)) + if (dcpaud_refresh_eld_from_edid(dcpaud)) snd_ctl_notify(dcpaud->card, SNDRV_CTL_EVENT_MASK_VALUE, &dcpaud->eld_ctl->id); } From 2dd0986d434cc4df1e90dae568ae116431bf4955 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 22:52:51 +0000 Subject: [PATCH 1162/1514] arm64: dts: apple: t6041-j616c: enable PCIe CLKREQ# on Wi-Fi and SDXC The J616c (16-inch MacBook Pro, M4 Max) ADT wires CLKREQ# on GPIO 0 for apcie0/pci-bridge0 (BCM4388 Wi-Fi/Bluetooth, port00) and GPIO 1 for apcie0/pci-bridge1 (GL9755 SDXC, port01), and t6041-j614c-j616c.dtsi already configures wifi_clkreq_pins and sd_clkreq_pins on pcie0 while pcie-apple already enables hardware refclk clock gating on T6041. Advertise supports-clkreq on port00 and port01 in t6041-j616c.dts so PCIe ASPM enables L1.1 and L1.2 substates under the default ASPM policy. Keep the override scoped to J616c until J614c is verified. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j616c.dts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index ccdd779a5e5807..b353fe6af4fe29 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -37,6 +37,19 @@ wake-gpios = <&pinctrl 40 GPIO_ACTIVE_HIGH>; }; +/* + * ADT apcie0/pci-bridge0 (Wi-Fi/BT) and pci-bridge1 (SDXC) wire CLKREQ# on + * GPIO 0 and GPIO 1 (pinctrl-0 in t6041-j614c-j616c.dtsi). Kept to J616c + * until J614c is tested. + */ +&port00 { + supports-clkreq; +}; + +&port01 { + supports-clkreq; +}; + &smc_gpio_low { apple,output-templates = <0xe 0x00800000>; }; From 588178f047698c70ae3b186f0b46fad5f6a9894a Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 20:19:39 -0500 Subject: [PATCH 1163/1514] wifi: apple: centauri: t6050: gate commands during host sleep A cfg80211 regulatory callback can run after the Alpha host-sleep command and poll the BAR while PCI is entering D3hot. Reject firmware commands before touching the rings or BAR while host sleep is active. Keep the latest named country while asleep and refresh the channel flags once the Alpha wake succeeds. Use the same replay on suspend unwind and keep the gate closed if the wake fails. Let the existing resume recovery handle transport loss during replay. Fixes: b8fce260d6be ("wifi: apple: centauri: t6050: keep N1 firmware and Wi-Fi alive across deep sleep") Signed-off-by: Diljit Singh --- .../apple/centauri/t6050/centauri_wifi.c | 64 +++++++-- tools/asahi/centauri-wifi-pm-tests.py | 121 +++++++++++++++++- 2 files changed, 167 insertions(+), 18 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 2f830a7304cfd2..f515c455573d31 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -89,6 +89,8 @@ struct centauri_t6050_wifi { size_t reply_capacity, reply_size; bool stopping, command_failed; bool tx_paused, transport_paused, host_sleep_sent, transport_sleep_sent; + bool regulatory_deferred; + u8 country_deferred[3]; bool host_events_fallback_logged; bool scan_abort, connect_abort; u8 scan_sequence; @@ -763,7 +765,7 @@ static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, const void *payload, size_t size, void *reply, size_t *reply_size, bool *submitted) { - u16 slot = wifi->command_head, sequence = ++wifi->sequence; + u16 slot = wifi->command_head, sequence; int ret; u32 stage; u8 *packet, *descriptor; @@ -771,6 +773,10 @@ static int command_reply(struct centauri_t6050_wifi *wifi, u32 id, if (submitted) *submitted = false; + /* The PCI link can go down after the host-sleep command. */ + if (wifi->host_sleep_sent) + return -EHOSTDOWN; + sequence = ++wifi->sequence; if (wifi->command_failed) return -EIO; if (size > BUFFER_SIZE - 24) @@ -973,6 +979,18 @@ static void channels_apply(struct centauri_t6050_wifi *wifi) counted[0], counted[1], counted[2], list[0]); } +static void country_set(struct centauri_t6050_wifi *wifi, const u8 country[3]) +{ + int ret = command(wifi, 9, country, 3); + + if (ret) + dev_err(&wifi->control->pdev->dev, + "firmware country update failed: %d\n", ret); + else + firmware_report(wifi, 19, wifi->hw_channels, + &wifi->hw_channels_blob); +} + /* * 6 GHz needs HE: the station's HE capabilities element as the firmware * reports it (capabilities TLV 0xff), with the 6 GHz band capabilities taken @@ -2293,6 +2311,7 @@ static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) { int ret; + ASSERT_RTNL(); lockdep_assert_held(&wifi->lock); if (wifi->transport_sleep_sent) { ret = alpha_transport_state(wifi, false); @@ -2301,10 +2320,22 @@ static int alpha_resume_locked(struct centauri_t6050_wifi *wifi) wifi->transport_sleep_sent = false; } if (wifi->host_sleep_sent) { + /* Under the mutex, only the wake command can pass the gate. */ + wifi->host_sleep_sent = false; ret = alpha_host_power(wifi, false); - if (ret) + if (ret) { + wifi->host_sleep_sent = true; return ret; - wifi->host_sleep_sent = false; + } + } + if (wifi->regulatory_deferred) { + if (wifi->configured && wifi->country_deferred[0]) + country_set(wifi, wifi->country_deferred); + memset(wifi->country_deferred, 0, sizeof(wifi->country_deferred)); + wifi->regulatory_deferred = false; + channels_apply(wifi); + if (wifi->command_failed) + return -EIO; } WRITE_ONCE(wifi->transport_paused, false); WRITE_ONCE(wifi->tx_paused, false); @@ -2366,11 +2397,14 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) synchronize_irq(pci_irq_vector(c->alpha_irqs.pdev, i)); cancel_work_sync(&wifi->link_work); + /* Match the regulatory notifier's lock order for suspend unwind. */ + rtnl_lock(); mutex_lock(&wifi->lock); ret = alpha_transport_state(wifi, true); if (!ret) { wifi->transport_sleep_sent = true; mutex_unlock(&wifi->lock); + rtnl_unlock(); return 0; } if (alpha_resume_locked(wifi)) { @@ -2380,6 +2414,7 @@ int centauri_t6050_wifi_suspend(struct centauri_t6050 *c) wifi->command_failed = true; } mutex_unlock(&wifi->lock); + rtnl_unlock(); return ret; out_unpause: @@ -2399,9 +2434,11 @@ int centauri_t6050_wifi_resume(struct centauri_t6050 *c) if (!wifi) return 0; + rtnl_lock(); mutex_lock(&wifi->lock); ret = alpha_resume_locked(wifi); mutex_unlock(&wifi->lock); + rtnl_unlock(); return ret; } @@ -2458,20 +2495,19 @@ static void wifi_regulatory(struct wiphy *wiphy, u8 country[3] = { request->alpha2[0], request->alpha2[1], 1 }; bool named = country[0] >= 'A' && country[0] <= 'Z' && country[1] >= 'A' && country[1] <= 'Z'; - int ret; mutex_lock(&wifi->lock); - if (wifi->configured && named) { - ret = command(wifi, 9, country, sizeof(country)); - if (ret) - dev_err(&wifi->control->pdev->dev, - "firmware country update failed: %d\n", ret); - else - firmware_report(wifi, 19, wifi->hw_channels, - &wifi->hw_channels_blob); + if (wifi->host_sleep_sent) { + /* Keep the last named country across cfg80211's world updates. */ + if (named) + memcpy(wifi->country_deferred, country, sizeof(country)); + wifi->regulatory_deferred = true; + } else { + if (wifi->configured && named) + country_set(wifi, country); + /* cfg80211 has just recomputed the channel flags. */ + channels_apply(wifi); } - /* cfg80211 has just recomputed the channel flags from its own rules. */ - channels_apply(wifi); mutex_unlock(&wifi->lock); } diff --git a/tools/asahi/centauri-wifi-pm-tests.py b/tools/asahi/centauri-wifi-pm-tests.py index 1a4f9293e625eb..4ae904a36d2056 100644 --- a/tools/asahi/centauri-wifi-pm-tests.py +++ b/tools/asahi/centauri-wifi-pm-tests.py @@ -64,6 +64,7 @@ def block(source, name): struct wiphy { struct centauri_t6050_wifi *wifi; }; struct net_device { int unused; }; struct cfg80211_wowlan { bool any; }; +struct regulatory_request { char alpha2[3]; }; ''' STUBS = r''' @@ -75,6 +76,11 @@ def block(source, name): bool reply_valid, pm_prepared, pm_wowlan_armed; bool data_tx_busy[DATA_TX_SLOTS]; bool host_events_fallback_logged; + bool configured, tx_paused, transport_paused, host_sleep_sent, transport_sleep_sent; + bool regulatory_deferred, station_signal_valid, disconnect_event; + u8 country_deferred[3], hw_channels[4]; + int hw_channels_blob, data_rings_open; + struct net_device *netdev; u16 command_head, sequence, reply_capture, reply_sequence, reply_status; u32 reply_command; u8 *reply_buffer; @@ -83,6 +89,9 @@ def block(source, name): }; static const u16 ring_size[5] = {0, 64}; static unsigned int doorbells, drains, notifications, consumer, tx_drain_rounds, info_logs; +static unsigned int reads, index_reads, reports, applies; +static bool rtnl_held, fail_firmware_report; +#define ASSERT_RTNL() assert(rtnl_held) static void dev_info(const void *dev, const char *fmt, ...) { (void)dev; (void)fmt; info_logs++; } static u16 firmware_status, last_cmd6_tlv280_len, mock_fw_transient_status; @@ -98,10 +107,11 @@ def block(source, name): static void *wiphy_priv(struct wiphy *wiphy) { assert(!private_access_forbidden); return &wiphy->wifi; } static void usleep_range(int a, int b) { (void)a; (void)b; jiffies += 100; } -static unsigned int readl(void *address) { (void)address; return transport_mode == LOST ? 0 : 2; } +static unsigned int readl(void *address) +{ (void)address; reads++; return transport_mode == LOST ? 0 : 2; } static void writel(unsigned int value, void *address) { (void)value; (void)address; doorbells++; } static u16 index_read(struct centauri_t6050_wifi *wifi, int array, int index) -{ assert(wifi->lock); (void)array; (void)index; return consumer; } +{ assert(wifi->lock); (void)array; (void)index; index_reads++; return consumer; } static void index_write(struct centauri_t6050_wifi *wifi, int array, int index, u16 value) { assert(wifi->lock); (void)array; (void)index; (void)value; if (submission_probe) assert(*submission_probe); } @@ -142,7 +152,12 @@ def block(source, name): if (!wifi->reply_valid) { wifi->reply_valid = true; wifi->reply_sequence = wifi->reply_capture + wrong_reply; - wifi->reply_command = mock_reply_command | (async_reply ? BIT(30) : 0); + const u8 *packet = wifi->a.window + TX_BUFFER + + ((wifi->command_head + ring_size[1] - 1) % ring_size[1]) * BUFFER_SIZE; + u32 command_id; + memcpy(&command_id, packet + 0x14, sizeof(command_id)); + wifi->reply_command = (mock_reply_command ? mock_reply_command : command_id) | + (async_reply ? BIT(30) : 0); if (mock_reply_command == 6 && mock_fw_transient_status) { wifi->reply_status = mock_fw_transient_status; mock_fw_transient_status = 0; @@ -166,6 +181,21 @@ def block(source, name): static void cfg80211_disconnected(struct net_device *netdev, u16 reason, void *ie, int size, bool local, int flags) { (void)netdev; (void)reason; (void)ie; (void)size; (void)local; (void)flags; notifications++; } +static int alpha_transport_state(struct centauri_t6050_wifi *wifi, bool asleep) +{ assert(wifi->lock && !asleep); return 0; } +static bool netif_running(struct net_device *netdev) { (void)netdev; return false; } +static void netif_wake_queue(struct net_device *netdev) { (void)netdev; } +static void schedule_work(int *work) { (void)work; } +static void firmware_report(struct centauri_t6050_wifi *wifi, u32 id, u8 *buffer, int *blob) +{ + assert(wifi->lock && rtnl_held && id == 19); + assert(buffer == wifi->hw_channels && blob == &wifi->hw_channels_blob); + reports++; + if (fail_firmware_report) + command_fault(wifi); +} +static void channels_apply(struct centauri_t6050_wifi *wifi) +{ assert(wifi->lock && rtnl_held); applies++; } ''' TESTS = r''' @@ -186,6 +216,8 @@ def block(source, name): wifi.connected = true; wiphy.wifi = &wifi; doorbells = drains = notifications = consumer = tx_drain_rounds = info_logs = 0; + reads = index_reads = reports = applies = 0; + rtnl_held = fail_firmware_report = false; firmware_status = last_cmd6_tlv280_len = mock_fw_transient_status = 0; mock_reply_command = 131073; mock_fw_max_events = last_cmd6_tlv280_count = 0; @@ -229,9 +261,79 @@ def block(source, name): } } +static void test_host_sleep_gate(void) +{ + bool published = true; + + reset(); + wifi.host_sleep_sent = true; + mutex_lock(&wifi.lock); + assert(command_reply(&wifi, 9, NULL, 0, NULL, NULL, &published) == -EHOSTDOWN); + mutex_unlock(&wifi.lock); + assert(!published && !index_reads && !doorbells && !drains && !reads); + assert(!wifi.sequence && !wifi.command_failed); +} + +static void test_deferred_regulatory(void) +{ + struct regulatory_request us = { .alpha2 = "US" }; + struct regulatory_request ca = { .alpha2 = "CA" }; + struct regulatory_request world = { .alpha2 = "00" }; + + reset(); + wifi.configured = true; + wifi.host_sleep_sent = wifi.transport_sleep_sent = true; + mock_reply_command = 0; + rtnl_held = true; + wifi_regulatory(&wiphy, &world); + wifi_regulatory(&wiphy, &ca); + wifi_regulatory(&wiphy, &us); + wifi_regulatory(&wiphy, &world); + assert(!index_reads && !doorbells && !drains && !reads && !reports && !applies && !wifi.lock); + assert(wifi.regulatory_deferred && !memcmp(wifi.country_deferred, "US\1", 3)); + + mutex_lock(&wifi.lock); + firmware_status = 1; + assert(alpha_resume_locked(&wifi) == -EREMOTEIO); + assert(wifi.host_sleep_sent && wifi.regulatory_deferred && !reports && !applies); + doorbells = 0; + firmware_status = 0; + assert(alpha_resume_locked(&wifi) == 0); + assert(!wifi.host_sleep_sent && !wifi.regulatory_deferred && !wifi.country_deferred[0]); + assert(doorbells == 2 && reports == 1 && applies == 1); + assert(!memcmp(wifi.a.window + TX_BUFFER + (wifi.command_head - 1) * BUFFER_SIZE + 24, + "US\1", 3)); + assert(alpha_resume_locked(&wifi) == 0); + assert(doorbells == 2 && reports == 1 && applies == 1); + mutex_unlock(&wifi.lock); + + wifi_regulatory(&wiphy, &ca); + assert(doorbells == 3 && reports == 2 && applies == 2); + wifi_regulatory(&wiphy, &world); + assert(doorbells == 3 && reports == 2 && applies == 3); + + wifi.host_sleep_sent = true; + wifi_regulatory(&wiphy, &world); + assert(wifi.regulatory_deferred && !wifi.country_deferred[0]); + mutex_lock(&wifi.lock); + assert(alpha_resume_locked(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(doorbells == 4 && reports == 2 && applies == 4); + + wifi.host_sleep_sent = wifi.transport_paused = wifi.tx_paused = true; + wifi_regulatory(&wiphy, &us); + fail_firmware_report = true; + mutex_lock(&wifi.lock); + assert(alpha_resume_locked(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(wifi.command_failed && wifi.transport_paused && wifi.tx_paused); +} + int main(void) { test_registered_pm_contract(); + test_host_sleep_gate(); + test_deferred_regulatory(); prepare(); assert(!wifi.pm_disconnect.seen); expect_error(0); /* Missing transaction remains missing. */ @@ -443,7 +545,8 @@ def main(): "centauri_t6050_wifi_pm_prepare", "centauri_t6050_wifi_pm_error", "centauri_t6050_wifi_pm_disconnected", "centauri_t6050_wifi_wowlan_armed", "centauri_t6050_wifi_mark_failed", "centauri_t6050_wifi_pm_complete", - "alpha_host_power_send", "alpha_host_power", "wifi_suspend"] + "alpha_host_power_send", "alpha_host_power", "country_set", + "alpha_resume_locked", "wifi_regulatory", "wifi_suspend"] has_resume = bool(re.search(r"^static int wifi_resume\(", source, re.M)) if has_resume: names.append("wifi_resume") @@ -503,6 +606,12 @@ def main(): ("silent-fallback-log", "if (!ret && !wifi->host_events_fallback_logged)", "if (false && !ret && !wifi->host_events_fallback_logged)"), + ("host-sleep-command", "\tif (wifi->host_sleep_sent)\n\t\treturn -EHOSTDOWN;\n", ""), + ("regulatory-in-sleep", "if (wifi->host_sleep_sent) {\n\t\t/* Keep the last", + "if (false) {\n\t\t/* Keep the last"), + ("lost-deferred-country", "country_set(wifi, wifi->country_deferred);", "(void)wifi;"), + ("ignored-regulatory-transport-loss", + "if (wifi->command_failed)\n\t\t\treturn -EIO;", "if (false)\n\t\t\treturn -EIO;"), ] failures = { 'lost-suspend-error': 'centauri_t6050_wifi_pm_error(&control) == expected', @@ -511,6 +620,10 @@ def main(): 'wowlan-ignores-trigger': 'call_registered_suspend(&wiphy, &wowlan) == 1', 'sleep-uses-full-len': 'alpha_host_power(&wifi, true) == 0', 'silent-fallback-log': 'info_logs == 1', + 'host-sleep-command': 'command_reply(&wifi, 9, NULL, 0, NULL, NULL, &published) == -EHOSTDOWN', + 'regulatory-in-sleep': '!index_reads && !doorbells && !drains && !reads && !reports && !applies', + 'lost-deferred-country': 'doorbells == 2 && reports == 1 && applies == 1', + 'ignored-regulatory-transport-loss': 'alpha_resume_locked(&wifi) == -EIO', } for name, before, after in negative_controls if args.negative_controls else []: if before not in production: From 79d7fe86269a9192a8b91b8b5c1f5fc8c8b47f15 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 17:37:32 -0800 Subject: [PATCH 1164/1514] dt-bindings: display: apple,dcp: allow an empty typec-routes container A board whose display processors and Type-C ports are wired through a display crossbar may ask Aura to populate each processor's Type-C display routes from the ADT instead of spelling them out by hand: the PHYs, display crossbar controls, crossbar states, DPTX targets and route subnodes are written before Linux starts. Document the empty typec-routes container in apple,dcp-typec-routes.yaml, qualify the connector display port consistently throughout (port@2 on T6050, port@3 on earlier SoCs), and allow an empty container in apple,dcp.yaml while disallowing partial pre-populated route properties alongside it. Signed-off-by: Jeff Queisser --- .../display/apple,dcp-typec-routes.yaml | 27 ++++++++++++++----- .../bindings/display/apple,dcp.yaml | 20 ++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml index d13cfa7c2b4b9c..e90412d793f11c 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp-typec-routes.yaml @@ -16,17 +16,25 @@ description: | Each route index N names a typecN PHY and a typecN DP Alt Mode crossbar output on the DCP node. The route's graph endpoint connects to the corresponding - Type-C connector's display port (port@3). Two route endpoints on that port - mean two candidate pipelines; that alone does not imply two tunnel streams. + Type-C connector's display port (port@2 on T6050, port@3 on earlier SoCs). Two + route endpoints on that port mean two candidate pipelines; that alone does not + imply two tunnel streams. For a port wired to both Thunderbolt DP IN adapters, name typecN-dpin0 and typecN-dpin1 crossbar controls on the pipelines that can drive them. Crossbar mux cells 0, 1 and 2 describe the DP PHY, DP IN 0 and DP IN 1 outputs, respectively. The per-port prefix distinguishes multiple ATCs on one DCP. - Dual-stream wiring requires these two named controls and two port@3 - endpoints. It does not describe SoC handshake or retry policy. T6050 host - routers have four DP IN adapters; their crossbars add typecN-dpin2 and - typecN-dpin3 (cells 3 and 4). + Dual-stream wiring requires these two named controls and two endpoints on the + connector's display port. It does not describe SoC handshake or retry policy. + T6050 host routers have four DP IN adapters; their crossbars add typecN-dpin2 + and typecN-dpin3 (cells 3 and 4). + + An empty typec-routes container asks the boot loader to write the routes + from the hardware's own description of its display crossbar: the phys, + crossbar controls, crossbar states, DPTX targets and route nodes below, + and the matching endpoints on each connector's display port (port@2 on + T6050, port@3 on earlier SoCs). Without a boot loader that does, the + processor has no Type-C route. Legacy typecN-usb4 names describe cell 1 on old j414/j416 DTBs. With two port@3 endpoints they retain the existing dual-stream wiring; cell 2 is @@ -39,7 +47,12 @@ select: enum: - apple,dcp - apple,dcpext - typec-routes: true + typec-routes: + anyOf: + - required: [route@0] + - required: [route@1] + - required: [route@2] + - required: [route@3] required: - compatible - typec-routes diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 6867256ee228ec..633911859ec106 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -767,6 +767,26 @@ allOf: then: properties: resets: false + - if: + required: + - typec-routes + properties: + typec-routes: + not: + anyOf: + - required: [route@0] + - required: [route@1] + - required: [route@2] + - required: [route@3] + then: + properties: + phys: false + phy-names: false + mux-controls: false + mux-control-names: false + apple,typec-mux-indices: false + apple,typec-dptx-phys: false + apple,dptx-die: false unevaluatedProperties: false From 7f024572717aeb66582e1f8733f507f3aec3d889 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 18 Nov 2026 16:06:36 +0700 Subject: [PATCH 1165/1514] media: apple: avd: VP9: one segmentation map per stream, shared by the banks The segmentation map is state that runs from frame to frame: a frame with temporal map prediction, or one that keeps the map without updating it, reads the map the frame before it left. With the queued transport (two banks, alternating) each bank had its own seg buffer, so a frame read the map of the frame before last. Every stream with segmentation then decoded wrong from its first non-key frame on. Keep one seg buffer per stream and point both banks at it. A frame size change (the map is cleared then) moves to a second, cleared buffer instead of clearing the one the frame still in flight in the other bank reads. Tested on J815 (MacBook Air 15" M5), frame-by-frame MD5 against libavcodec, full decode and a seek into the stream: - before: libvpx aq-mode 2 (complexity) and 3 (cyclic refresh) at 720p and 1080p, and a 360p screen-content clip, wrong from frame 1-3; - after: all of them bit-exact, with the rest of a 67-stream H.264, HEVC, VP9 and AV1 set (59 of 59 PASS; the other 8 are 10-bit and interlaced streams the driver does not expose). The single-bank transport also decoded them right, which pointed at the bank swap. Signed-off-by: Nick --- drivers/media/platform/apple/avd/avd-vp9.c | 52 +++++++++++++--------- 1 file changed, 31 insertions(+), 21 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-vp9.c b/drivers/media/platform/apple/avd/avd-vp9.c index b9a05310fb9b54..df04fcc26b2b71 100644 --- a/drivers/media/platform/apple/avd/avd-vp9.c +++ b/drivers/media/platform/apple/avd/avd-vp9.c @@ -192,7 +192,6 @@ struct avd_vp9_bank { struct avd_buf lf_left_info; struct avd_buf lf_left; struct avd_buf color; - struct avd_buf seg; struct avd_buf pipe_state; struct avd_buf counts; struct avd_buf probs; @@ -200,8 +199,6 @@ struct avd_vp9_bank { struct avd_vp9_frame_info cur; struct avd_vp9_frame_info last; u8 submit_num; - /* The seg buffer holds a map laid out for another frame size. */ - bool seg_clear; }; struct avd_vp9_ctx { @@ -212,6 +209,16 @@ struct avd_vp9_ctx { struct avd_vp9_bank *b; /* The size changed, and no frame has updated the segmentation map since. */ bool seg_reset; + /* + * The segmentation map, one per stream. A frame reads the map the frame + * before it left (temporal prediction, or a frame without a map update), + * so the two banks of the queued transport must share it: with one + * buffer per bank, a frame read the map of the frame before last. A size + * change moves to the other, cleared buffer (avd_vp9_run_preamble()): the frame + * still in flight keeps reading the old one. + */ + struct avd_buf seg_buf[2]; + unsigned int seg_cur; }; static bool avd_vp9_needs_counts(u32 flags) @@ -442,8 +449,8 @@ static void set_header(struct avd_ctx *ctx, struct avd_vp9_run *run) pusha(vp9_ctx->b->bufs.counts.addr, "counts", 0); pusha(vp9_ctx->b->bufs.probs.addr, "probs", 0); pusha(vp9_ctx->b->bufs.above_info.addr, "above_info", 0); - pusha(vp9_ctx->b->bufs.seg.addr, "seg", 1); - pusha(vp9_ctx->b->bufs.seg.addr, "seg", 2); + pusha(vp9_ctx->seg_buf[vp9_ctx->seg_cur].addr, "seg", 1); + pusha(vp9_ctx->seg_buf[vp9_ctx->seg_cur].addr, "seg", 2); pusha(vp9_ctx->b->bufs.color.addr, "color", 3); pusha(avd_vp9_uses_prev_mv(frame, &vp9_ctx->last) ? vp9_ctx->last.color : vp9_ctx->b->bufs.color.addr, @@ -845,10 +852,6 @@ static int avd_vp9_alloc_bufs(struct avd_ctx *ctx, struct avd_vp9_bank *bank) if (ret) return ret; - ret = avd_buf_alloc(avd, &bank->bufs.seg, DIV_ROUND_UP(w, 8) * 24); - if (ret) - return ret; - ret = avd_buf_alloc(avd, &bank->bufs.lf_left, DIV_ROUND_UP(h, 8) * 16 * bit_depth); if (ret) @@ -991,21 +994,21 @@ static int avd_vp9_run_preamble(struct avd_ctx *ctx, struct avd_vp9_run *run) /* * VP9 clears the segmentation map when the frame size changes, and the - * decoder carries part of it over in the seg buffer. Every bank's buffer - * holds the old map, but a busy bank's belongs to the hardware until the - * frame retires: clear each bank's when it is next taken. The map reset - * goes to every frame that uses segmentation until one updates the map - * (make_flags1(), update_ctx_last_info()). + * decoder carries part of it over in the seg buffer. The frame in the + * other bank may still be reading the old map, so move to the other + * buffer and clear that one: at most one frame is in flight besides this + * one, and it uses the current buffer. The map reset goes to every frame + * that uses segmentation until one updates the map (make_flags1(), + * update_ctx_last_info()). */ if (vp9_ctx->last.valid && !avd_vp9_same_size(dec_params, &vp9_ctx->last)) { - for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) - vp9_ctx->bank[i].seg_clear = true; + struct avd_buf *seg; + + vp9_ctx->seg_cur ^= 1; + seg = &vp9_ctx->seg_buf[vp9_ctx->seg_cur]; + memset(seg->cpu, 0, seg->size); vp9_ctx->seg_reset = true; } - if (vp9_ctx->b->seg_clear) { - memset(vp9_ctx->b->bufs.seg.cpu, 0, vp9_ctx->b->bufs.seg.size); - vp9_ctx->b->seg_clear = false; - } vp9_ctx->b->cur.tx_mode = run->prob_updates->tx_mode; @@ -1293,6 +1296,8 @@ static void avd_vp9_free(struct avd_ctx *ctx, struct avd_vp9_ctx *vp9_ctx) struct avd_dev *avd = ctx->dev; ctx->max_frames = 1; + avd_buf_free(avd, &vp9_ctx->seg_buf[0]); + avd_buf_free(avd, &vp9_ctx->seg_buf[1]); for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) { struct avd_vp9_bank *bank = &vp9_ctx->bank[i]; @@ -1300,7 +1305,6 @@ static void avd_vp9_free(struct avd_ctx *ctx, struct avd_vp9_ctx *vp9_ctx) avd_buf_free(avd, &bank->bufs.inst); avd_buf_free(avd, &bank->bufs.probs); avd_buf_free(avd, &bank->bufs.counts); - avd_buf_free(avd, &bank->bufs.seg); avd_buf_free(avd, &bank->bufs.color); avd_buf_free(avd, &bank->bufs.ip_above); avd_buf_free(avd, &bank->bufs.lf_above); @@ -1332,6 +1336,12 @@ static int avd_vp9_start(struct avd_ctx *ctx) vp9_ctx->nbanks = avd_qfw_has_vp_done(ctx->dev) ? AVD_VP9_BANKS : 1; vp9_ctx->b = &vp9_ctx->bank[0]; + for (unsigned int i = 0; i < ARRAY_SIZE(vp9_ctx->seg_buf); i++) { + ret = avd_buf_alloc(ctx->dev, &vp9_ctx->seg_buf[i], + DIV_ROUND_UP(fmt_width(ctx), 8) * 24); + if (ret) + goto err_free_ctx; + } for (unsigned int i = 0; i < vp9_ctx->nbanks; i++) { ret = avd_vp9_alloc_bufs(ctx, &vp9_ctx->bank[i]); if (ret) From 72f939d3cf0a09ee1ba3e61034dacff5ba632ff4 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 14 Nov 2026 19:22:01 +0700 Subject: [PATCH 1166/1514] dt-bindings: hwmon: apple,smc-hwmon: Name the SoC die thermal sensor A node with apple,discover-temperatures has no stable channel indices, so a thermal zone cannot name one of its temperature channels. Let such a node be a thermal sensor provider for one sensor, 1000: the hottest of its apple,soc-die-keys readings. A zone on it comes in addition to the driver's tripless macsmc_soc_die zone, which in-kernel users look up by name. Signed-off-by: Nick --- .../devicetree/bindings/hwmon/apple,smc-hwmon.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml index 79f372bb2db98e..d1224aa9f467fb 100644 --- a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml +++ b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml @@ -121,7 +121,11 @@ properties: const: 1 description: The cell is the zero-based index of a temperature channel, counting - the temperature-* child nodes in order. + the temperature-* child nodes in order. With + apple,discover-temperatures, whose channel indices are not stable, the + only sensor is 1000, the hottest of the apple,soc-die-keys readings. + A thermal zone on it comes in addition to the macsmc_soc_die zone, + which is still registered for the users that look it up by name. "#cooling-cells": const: 3 From 1dfc0ffa27a96909850c2bfe93c95bf07071facd Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 14 Nov 2026 19:22:52 +0700 Subject: [PATCH 1167/1514] hwmon: macsmc: offer the SoC die zone to a device tree thermal zone A board that discovers its SMC temperatures (apple,discover-temperatures, as the M5 Airs do) has no stable channel indices, so a device tree thermal zone cannot name one of its temperature channels, and the hottest-die zone is registered without trips. Such a board then has no thermal policy of its own. When the node is a thermal sensor provider, offer the hottest-die reading as sensor 1000, above any channel index the hwmon core registers. A zone on it gets the board's trips and cooling maps. The named macsmc_soc_die zone is still registered in every case: the asahi GPU drivers' governors (g17 and m3) read the SoC hotspot from that zone by name, and a device tree zone's name cannot be macsmc_soc_die (no '_' in a node name). Discovered channels are not bounded at build time, so a node with 1000 or more of them keeps only the named zone, with a warning. No board uses it yet: the J815 zone waits for limits the boot loader reads from the machine. Signed-off-by: Nick --- drivers/hwmon/macsmc-hwmon.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index d56709e208e1fa..8fde9c3a4b0822 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -1549,6 +1549,13 @@ static void macsmc_hwmon_populate_fan_configs(u32 *configs, const struct macsmc_ */ #if IS_ENABLED(CONFIG_THERMAL) #define MACSMC_SOC_DIE_ZONE "macsmc_soc_die" +/* + * The thermal sensor ID of the SoC die zone for a device tree thermal zone, on + * a node that discovers its temperatures and is a thermal sensor provider. It + * must stay above every temperature channel index the hwmon core registers; + * discovered channels are not bounded at build time, so probe checks it. + */ +#define MACSMC_SOC_DIE_SENSOR_ID 1000 static int macsmc_hwmon_die_hottest(struct macsmc_hwmon *hwmon, int *temp) { @@ -1618,6 +1625,27 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) key >> 24, (key >> 16) & 0xff, (key >> 8) & 0xff, key & 0xff); } + /* + * A board with a device tree zone on the die sensor gets that zone, with its trips and + * cooling maps. Its lifetime is managed by the OF helper. The named zone below + * is registered either way: the GPU drivers' governors look it up by its name. + */ + if (of_property_present(hwmon->dev->of_node, "#thermal-sensor-cells") && + hwmon->temp.count >= MACSMC_SOC_DIE_SENSOR_ID) { + dev_warn(hwmon->dev, "%u temperature channels reach the SoC die sensor ID %u\n", + hwmon->temp.count, MACSMC_SOC_DIE_SENSOR_ID); + } else if (of_property_present(hwmon->dev->of_node, "#thermal-sensor-cells")) { + tz = devm_thermal_of_zone_register(hwmon->dev, MACSMC_SOC_DIE_SENSOR_ID, hwmon, + &macsmc_hwmon_die_ops); + if (!IS_ERR(tz)) + dev_info(hwmon->dev, "SoC die zone %s (device tree): hottest of%s (%u of %u keys)\n", + thermal_zone_device_type(tz), keys, hwmon->die_count, + hwmon->die_listed); + else if (PTR_ERR(tz) != -ENODEV) + dev_warn(hwmon->dev, + "cannot register the device tree SoC die zone (%pe)\n", tz); + } + if (hwmon->fan_assist_valid) { struct thermal_trip trip = { .temperature = hwmon->fan_assist.trigger_mc, From 53fc42ef2ee414b2e301ef1963dc5abbe3007dcd Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:04:02 -0500 Subject: [PATCH 1168/1514] drm/asahi: g16: pass compute_only=false to SignalBundle::publish Commit fae8191fafba ("drm/asahi: g17: lift non-M5 effort immediately for waited compute submissions") added a second `compute_only: bool` parameter to `g17::sync_output::SignalBundle::publish()`, while the concurrently merged G16 stack (#3043) added a call site in `drivers/gpu/drm/asahi/g16/fence.rs` passing the previous one-argument signature, breaking `aurora.ko` builds on `main` with `rustc E0061`. Pass `false` from `g16::fence::Syncs::publish()`: the flag controls G17's non-M5 compute-waiter effort lifting hook (`asahi_g17_note_compute_waiter`), which G16 does not participate in because it manages power/DVFS in its own driver path. Fixes: fae8191fafba ("drm/asahi: g17: lift non-M5 effort immediately for waited compute submissions") Fixes: 175375add602 ("Merge pull request #3043 from aurora-silicon/djdev/g16-perf-wave15") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/fence.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 75ca2b6768c81d..e223c74f9c8535 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -588,7 +588,8 @@ impl Syncs { pub(crate) fn publish(&mut self, fence: &Fence) -> Result { let first = self.input_count.min(self.syncs.len()); if let Some(bundle) = &mut self.cumulative { - bundle.publish(fence)?; + // G16 has its own power/DVFS path; never poke G17's non-M5 compute-waiter hook. + bundle.publish(fence, false)?; self.cumulative = None; self.syncs.truncate(first); return Ok(()); From 8a68d8fa2602815ea63d77768d610331f6b8826f Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 10:50:00 +0700 Subject: [PATCH 1169/1514] media: apple: ave: flag B pictures on the coded buffers The firmware reorders the pictures of a B-frame session itself, so the driver does not know a coded picture's type when it hands the buffer out, and every picture that is not a key frame was flagged as a P frame. Read the slice type of the access unit's first slice instead: a few bytes of its slice header, with emulation-prevention bytes removed. HEVC needs the PPS's num_extra_slice_header_bits to reach slice_type, so the session remembers it from the last PPS it saw. Key frames are scanned too: they carry the parameter sets. Anything the reader does not expect leaves the picture flagged as a P frame, as before, and so does a buffer that comes back with an error: the flag is cleared before anything else is read. A KUnit case feeds a PPS with two extra bits, then a B slice that reads as I without them. The reader, built in user space, agrees with ffprobe's picture types on every access unit of x264 (two slices per picture) and x265 streams with 3 B-frames. On the MacBook Air 15" M5 (J815), with ffmpeg's v4l2m2m encoders and -bf 3, the buffers flagged B match the B pictures in the streams exactly: 27 and 30 of 60 (H.264), 43 and 44 of 60 (HEVC). Signed-off-by: Nick --- .../media/platform/apple/ave/ave-abi-test.c | 25 +++ drivers/media/platform/apple/ave/ave-sess.c | 151 ++++++++++++++++++ drivers/media/platform/apple/ave/ave-v4l2.c | 3 +- drivers/media/platform/apple/ave/ave.h | 3 + 4 files changed, 181 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 72b7d969169c34..52ddde19da7c06 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1561,6 +1561,30 @@ static void ave_t8112_26b123_build(struct kunit *test) &ave_layout_6070_11_1); } +/* + * HEVC B flag with a PPS whose num_extra_slice_header_bits is 2. The PPS + * comes with the IDR access unit; the B slice after it has two extra bits + * before slice_type, and reads as an I slice if they are not skipped. + */ +static void ave_hevc_bframe_extra_bits(struct kunit *test) +{ + static const u8 idr_au[] = { + 0, 0, 0, 1, 0x44, 0x01, 0xc5, 0x80, /* PPS: ids 0/0, 2 extra bits */ + 0, 0, 1, 0x26, 0x01, 0xa3, 0x80, /* IDR_W_RADL slice, I */ + }; + static const u8 b_au[] = { + 0, 0, 0, 1, 0x02, 0x01, 0xdc, 0x80, /* TRAIL_R slice, extra bits 01, B */ + }; + u8 bits = 0; + + KUNIT_EXPECT_FALSE(test, ave_au_bframe(idr_au, sizeof(idr_au), true, true, &bits)); + KUNIT_EXPECT_EQ(test, bits, 2); + KUNIT_EXPECT_TRUE(test, ave_au_bframe(b_au, sizeof(b_au), true, false, &bits)); + /* Without the PPS's bits the same slice reads as I. */ + bits = 0; + KUNIT_EXPECT_FALSE(test, ave_au_bframe(b_au, sizeof(b_au), true, false, &bits)); +} + static void ave_t6041_text_boot_word(struct kunit *test) { const u32 off = ave_t6041.text_boot_word, size = off + 0x100; @@ -1635,6 +1659,7 @@ static struct kunit_case ave_abi_cases[] = { KUNIT_CASE(ave_m3_probe_only), KUNIT_CASE(ave_26b123_layout), KUNIT_CASE(ave_t8112_26b123_build), + KUNIT_CASE(ave_hevc_bframe_extra_bits), {} }; diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index 595284b0e6c471..14242054fcffd6 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -1105,6 +1105,155 @@ static bool ave_starts_annexb(const u8 *p, size_t len) (len >= 4 && !p[0] && !p[1] && !p[2] && p[3] == 1); } +/* + * Slice type of the first slice of an access unit, for the CAPTURE buffer's + * B/P flag: the firmware reorders B-frames itself, so the driver learns a + * picture's type from its bitstream. Only the first few bytes after the NAL + * header are read (emulation-prevention bytes removed); anything unexpected + * gives "not B". + */ +struct ave_rbsp { + u8 b[24]; + unsigned int n, pos; /* bytes in b; next bit */ +}; + +static void ave_rbsp_init(struct ave_rbsp *r, const u8 *p, size_t len) +{ + unsigned int zeros = 0; + + r->n = 0; + r->pos = 0; + for (size_t i = 0; i < len && r->n < sizeof(r->b); i++) { + if (zeros >= 2 && p[i] == 3) { + zeros = 0; + continue; + } + zeros = p[i] ? 0 : zeros + 1; + r->b[r->n++] = p[i]; + } +} + +static int ave_rbsp_bit(struct ave_rbsp *r) +{ + int bit; + + if (r->pos >= r->n * 8) + return -1; + bit = (r->b[r->pos / 8] >> (7 - r->pos % 8)) & 1; + r->pos++; + return bit; +} + +/* ue(v), or -1 past the bytes read or above 31 leading zeros. */ +static s64 ave_rbsp_ue(struct ave_rbsp *r) +{ + unsigned int zeros = 0; + u64 v = 0; + int bit; + + while ((bit = ave_rbsp_bit(r)) == 0) + if (++zeros > 31) + return -1; + if (bit < 0) + return -1; + for (unsigned int i = 0; i < zeros; i++) { + bit = ave_rbsp_bit(r); + if (bit < 0) + return -1; + v = v << 1 | bit; + } + return (s64)((1ULL << zeros) - 1 + v); +} + +/* HEVC PPS: num_extra_slice_header_bits, needed to reach slice_type. */ +static int ave_hevc_pps_extra_bits(const u8 *nal, size_t len) +{ + struct ave_rbsp r; + int v = 0; + + ave_rbsp_init(&r, nal + 2, len - 2); + if (ave_rbsp_ue(&r) < 0 || ave_rbsp_ue(&r) < 0) /* pps id, sps id */ + return -1; + if (ave_rbsp_bit(&r) < 0 || ave_rbsp_bit(&r) < 0) /* dependent slices, output flag */ + return -1; + for (unsigned int i = 0; i < 3; i++) { + int bit = ave_rbsp_bit(&r); + + if (bit < 0) + return -1; + v = v << 1 | bit; + } + return v; +} + +static bool ave_slice_is_b(const u8 *nal, size_t len, bool hevc, u8 extra_bits) +{ + u32 nal_type = (nal[0] >> 1) & 0x3f; + struct ave_rbsp r; + s64 type; + + if (!hevc) { + ave_rbsp_init(&r, nal + 1, len - 1); + if (ave_rbsp_ue(&r) < 0) /* first_mb_in_slice */ + return false; + type = ave_rbsp_ue(&r); + return type == 1 || type == 6; /* B, B (all slices) */ + } + + ave_rbsp_init(&r, nal + 2, len - 2); + if (ave_rbsp_bit(&r) != 1) /* first_slice_segment_in_pic_flag */ + return false; + if (nal_type >= 16 && nal_type <= 23 && ave_rbsp_bit(&r) < 0) + return false; + if (ave_rbsp_ue(&r) < 0) /* slice_pic_parameter_set_id */ + return false; + for (unsigned int i = 0; i < extra_bits; i++) + if (ave_rbsp_bit(&r) < 0) + return false; + type = ave_rbsp_ue(&r); + return type == 0; /* HEVC: 0 = B, 1 = P, 2 = I */ +} + +/* Whether the access unit's first slice is a B slice; learns the PPS bits. */ +static bool ave_au_is_b(const u8 *p, size_t len, bool hevc, u8 *extra_bits) +{ + for (size_t i = 0; i + 3 < len; i++) { + const u8 *nal; + size_t room; + u32 type; + + if (p[i] || p[i + 1] || p[i + 2] != 1) + continue; + nal = p + i + 3; + room = len - i - 3; + if (room < (hevc ? 3 : 2)) + break; + type = hevc ? (nal[0] >> 1) & 0x3f : nal[0] & 0x1f; + if (hevc && type == 34) { + int bits = ave_hevc_pps_extra_bits(nal, room); + + if (bits >= 0) + *extra_bits = bits; + } else if (hevc ? type <= 21 : type == 1 || type == 5) { + return ave_slice_is_b(nal, room, hevc, *extra_bits); + } + i += 2; + } + return false; +} + +/* + * Whether a coded access unit is a B picture. Key frames are scanned too: + * they carry the parameter sets, and the PPS's extra slice header bits are + * needed for every later B/P decision. + */ +bool ave_au_bframe(const u8 *p, size_t len, bool hevc, bool key, u8 *extra_bits) +{ + bool b = ave_au_is_b(p, len, hevc, extra_bits); + + return !key && b; +} + /* NAL unit types in an Annex B buffer: key frame, parameter sets, filler? */ static void ave_scan_nals(const u8 *p, size_t len, bool hevc, bool *key, bool *params, bool *filler) @@ -1312,6 +1461,7 @@ int ave_sess_output(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buff int at, ret; *keyframe = false; + s->bframe = false; if (!out) return -EFAULT; if (s->status) { @@ -1378,6 +1528,7 @@ int ave_sess_output(struct ave_ctx *ctx, unsigned int slot, struct vb2_v4l2_buff if (!ave_starts_annexb(out, len)) ave_sess_dump(ctx, s, "not Annex B"); ave_scan_nals(out, len, hevc, keyframe, ¶ms, &filler); + s->bframe = ave_au_bframe(out, len, hevc, *keyframe, &sess->hevc_extra_bits); if (!ctx->dst_sequence && !params) ave_sess_dump(ctx, s, "first frame has no parameter sets"); len = ave_sess_cbr_fill(ctx, out, len, room, filler); diff --git a/drivers/media/platform/apple/ave/ave-v4l2.c b/drivers/media/platform/apple/ave/ave-v4l2.c index 1f2e933ed893a6..a5ac2073a2a26b 100644 --- a/drivers/media/platform/apple/ave/ave-v4l2.c +++ b/drivers/media/platform/apple/ave/ave-v4l2.c @@ -1152,7 +1152,8 @@ static bool ave_deliver(struct ave_ctx *ctx) v4l2_m2m_buf_copy_metadata(s->src, dst); dst->flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME | V4L2_BUF_FLAG_LAST); - dst->flags |= key ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME; + dst->flags |= key ? V4L2_BUF_FLAG_KEYFRAME : + s->bframe ? V4L2_BUF_FLAG_BFRAME : V4L2_BUF_FLAG_PFRAME; dst->sequence = ctx->dst_sequence++; sess->done_head = (sess->done_head + 1) % AVE_MAX_SLOTS; diff --git a/drivers/media/platform/apple/ave/ave.h b/drivers/media/platform/apple/ave/ave.h index a0bda7749166ad..e58f5d44a8df89 100644 --- a/drivers/media/platform/apple/ave/ave.h +++ b/drivers/media/platform/apple/ave/ave.h @@ -441,6 +441,7 @@ struct ave_slot { u32 status; bool busy; /* Process sent, reply pending */ bool done; /* reply in, output not delivered yet */ + bool bframe; /* the delivered picture is a B picture (its slice type) */ }; struct ave_frame_result { @@ -468,6 +469,7 @@ struct ave_frame_result { struct ave_session { struct ave_session *failed_next; struct ave_params p; + u8 hevc_extra_bits; /* PPS num_extra_slice_header_bits, for the B flag */ struct ave_buf hdr; struct ave_buf client_mem; /* 6070: per-session firmware-generated VPS/SPS/PPS output. */ @@ -643,6 +645,7 @@ int ave_build_process(struct ave_ctx *ctx, u8 *cmd, size_t len, unsigned int slot, dma_addr_t input, u32 bitrate, bool force_key, bool last); int ave_init_codec_state(struct ave_session *sess); +bool ave_au_bframe(const u8 *p, size_t len, bool hevc, bool key, u8 *extra_bits); /* ave-cmd.c */ int ave_cmd_config(struct ave_dev *ave); From ff4daf11b165924c37c860e8ec5bdacadc5b85d9 Mon Sep 17 00:00:00 2001 From: Nick Date: Thu, 19 Nov 2026 10:50:00 +0700 Subject: [PATCH 1170/1514] media: apple: ave: 26A428: the Start's second frame rate and the HEVC low-delay word macOS 27.2.1 on the M5 (T8142) writes the integer frame rate a second time at Start +0x320c (60 at 60 fps), and for an HEVC session without B-frames 3 at Process +0xce4, the same low-delay word the 9003 layout (ave_layout_9003_78_0) has at +0xcf8. Write both on the 26A428 layout. The 26B123 layout shares 26A428's fields through one macro, which now takes the two offsets. 26B123 passes 0 for both, so it writes neither: its 60 fps and no-B sessions were run without them, and nothing has traced its commands at those settings. At 30 fps the second rate is the 0x1e the 26A428 Start ledger already holds, and the low-delay word only applies to HEVC without B-frames, which this layout does not run yet, so qualified sessions on every chip send the same commands as before. The 26B123 KUnit case still checks that the two layouts agree on every other field. Signed-off-by: Nick --- .../media/platform/apple/ave/ave-abi-test.c | 17 +++++++++++++++-- drivers/media/platform/apple/ave/ave-layout.c | 18 ++++++++++++++---- drivers/media/platform/apple/ave/ave-layout.h | 2 ++ drivers/media/platform/apple/ave/ave-writer.c | 2 ++ 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 52ddde19da7c06..bdcb4a49f6bf33 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1472,6 +1472,8 @@ static void ave_26b123_layout(struct kunit *test) { const struct ave_fw_layout *a = &ave_layout_26a428; const struct ave_fw_layout *b = ave_layout_for_crc(0x99fc929a); + struct ave_start_layout *start = kunit_kzalloc(test, sizeof(a->start), GFP_KERNEL); + struct ave_proc_layout *process = kunit_kzalloc(test, sizeof(a->process), GFP_KERNEL); KUNIT_ASSERT_PTR_EQ(test, b, &ave_layout_26b123); KUNIT_EXPECT_TRUE(test, b->encode_ready); @@ -1485,8 +1487,19 @@ static void ave_26b123_layout(struct kunit *test) } KUNIT_EXPECT_EQ(test, b->bytes[0][AVE_IMAGE_PROCESS], 0x6e08); KUNIT_EXPECT_EQ(test, b->bytes[1][AVE_IMAGE_PROCESS], 0x78c8); - KUNIT_EXPECT_EQ(test, memcmp(b->start, a->start, sizeof(a->start)), 0); - KUNIT_EXPECT_EQ(test, memcmp(b->process, a->process, sizeof(a->process)), 0); + /* Apart from the two words only the M5 26A428 sessions were run with. */ + KUNIT_ASSERT_NOT_NULL(test, start); + KUNIT_ASSERT_NOT_NULL(test, process); + memcpy(start, a->start, sizeof(a->start)); + memcpy(process, a->process, sizeof(a->process)); + for (unsigned int c = 0; c < 2; c++) { + KUNIT_EXPECT_EQ(test, b->start[c].fps_int_copy, 0U); + start[c].fps_int_copy = 0; + } + KUNIT_EXPECT_EQ(test, b->process[1].low_delay, 0U); + process[1].low_delay = 0; + KUNIT_EXPECT_EQ(test, memcmp(b->start, start, sizeof(a->start)), 0); + KUNIT_EXPECT_EQ(test, memcmp(b->process, process, sizeof(a->process)), 0); KUNIT_EXPECT_EQ(test, memcmp(b->result, a->result, sizeof(a->result)), 0); KUNIT_EXPECT_EQ(test, b->hdr_bytes, a->hdr_bytes); KUNIT_EXPECT_EQ(test, b->max_slots, a->max_slots); diff --git a/drivers/media/platform/apple/ave/ave-layout.c b/drivers/media/platform/apple/ave/ave-layout.c index 377406027f9abc..bce97316b0af95 100644 --- a/drivers/media/platform/apple/ave/ave-layout.c +++ b/drivers/media/platform/apple/ave/ave-layout.c @@ -281,9 +281,11 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { /* * The macOS 27.0 (26A428) command layout. The macOS 27.2 (26B123) build * keeps every field where 26A428 has it; only the Process commands grow - * (ave_layout_26b123). + * (ave_layout_26b123). rate_copy is the Start's second integer frame rate + * and hevc_low_delay the HEVC Process low-delay word, 0 where a build's + * sessions have not been run with them. */ -#define AVE_LAYOUT_26A428_FIELDS \ +#define AVE_LAYOUT_26A428_FIELDS(rate_copy, hevc_low_delay) \ .abi = &ave_abi_9003, \ .kind = AVE_LAYOUT_26A428, \ .encode_ready = true, \ @@ -335,6 +337,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .const_214 = 0x35f4, \ .const_218 = 0x35f8, \ .fps = { .numerator = 0x3600 }, \ + .fps_int_copy = rate_copy, \ .rc_mode = 0x3614, \ .bitrate = 0x3618, \ .init_qp = 0x3620, \ @@ -423,6 +426,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .const_214 = 0x35f4, \ .const_218 = 0x35f8, \ .fps = { .numerator = 0x3600 }, \ + .fps_int_copy = rate_copy, \ .rc_mode = 0x3614, \ .bitrate = 0x3618, \ .init_qp = 0x3620, \ @@ -524,6 +528,7 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { .meta_size = 0x6060, \ .extra = 0x6068, \ .crop = 0x3190, \ + .low_delay = hevc_low_delay, \ }, \ }, \ .result = { \ @@ -541,7 +546,12 @@ const struct ave_fw_layout ave_layout_9003_78_0 = { const struct ave_fw_layout ave_layout_26a428 = { .name = "26A428", .bytes = { { 0x3b40, 0x6df8 }, { 0x13ee0, 0x78b8 } }, - AVE_LAYOUT_26A428_FIELDS + /* + * macOS 27.2.1 on the M5 writes the rate a second time at Start + * +0x320c (60 at 60 fps), and 3 at Process +0xce4 for HEVC without + * B-frames. + */ + AVE_LAYOUT_26A428_FIELDS(0x320c, 0xce4) }; /* @@ -553,7 +563,7 @@ const struct ave_fw_layout ave_layout_26a428 = { const struct ave_fw_layout ave_layout_26b123 = { .name = "26B123", .bytes = { { 0x3b40, 0x6e08 }, { 0x13ee0, 0x78c8 } }, - AVE_LAYOUT_26A428_FIELDS + AVE_LAYOUT_26A428_FIELDS(0, 0) .any_gop = true, }; diff --git a/drivers/media/platform/apple/ave/ave-layout.h b/drivers/media/platform/apple/ave/ave-layout.h index e5cb20074d2764..d499102fb2adbe 100644 --- a/drivers/media/platform/apple/ave/ave-layout.h +++ b/drivers/media/platform/apple/ave/ave-layout.h @@ -135,6 +135,8 @@ struct ave_start_layout { u32 const_214; u32 const_218; struct ave_rational_layout fps; + /* A second copy of the integer frame rate (26A428 Start). */ + u32 fps_int_copy; u32 rc_mode; /* Optional ABI-specific wire value for the driver's fixed-QP mode. */ u32 rc_mode_fixed_qp; diff --git a/drivers/media/platform/apple/ave/ave-writer.c b/drivers/media/platform/apple/ave/ave-writer.c index 8dbc0192a778a7..fe621ab833e001 100644 --- a/drivers/media/platform/apple/ave/ave-writer.c +++ b/drivers/media/platform/apple/ave/ave-writer.c @@ -783,6 +783,8 @@ static void ave_start_config(const struct ave_params *p, u8 *cmd, } else { ave_start_put32(cmd, l->fps.numerator, p->fps_int); } + /* A second copy of the integer rate: macOS 27.2.1 writes 60 at 60 fps (M5). */ + ave_start_put32(cmd, l->fps_int_copy, p->fps_int); /* Rate control */ /* From b3e6c51a4b5fc1c394b2589fc7a63cf78b61ca0e Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 19:11:51 +0700 Subject: [PATCH 1171/1514] media: apple: ave: 26A428: other frame rates and sessions without B-frames The 26A428 layout runs only 30 fps sessions with B-frames (or H.264 Baseline and intra-only ones): those are the ones its command ledger was qualified with. We traced the Start and Process commands macOS 27.2.1 sends on the M5 (T8142) for 60 fps sessions and sessions without B-frames, and compared them with what the driver sends for the same settings. With the two words the previous commit adds, they match, apart from words that also differ on a qualified 30 fps session with B-frames. Set any_gop on the layout, as the 26B123 layout has it, so the refusal no longer applies to it. The flag is on the layout, so the M5 Pro and Max (T6050) firmware on the same layout gets it too. Only the M5 has encoded with it so far. Tested on the MacBook Air 15" M5 (J815), firmware 26B123 (the macOS 27.2 stub's, on the 26A428 layout), on two boots: 30 encode cases (H.264 Baseline/Main/High and HEVC Main; 30 and 60 fps; with and without B-frames; VBR and CBR; 640x360 to 2560x1440), every stream decoding to the expected frame count, PSNR 27-42 dB against the source. Signed-off-by: Nick --- drivers/media/platform/apple/ave/ave-abi-test.c | 4 ++-- drivers/media/platform/apple/ave/ave-layout.c | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index bdcb4a49f6bf33..001f5f4b623841 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -1504,9 +1504,9 @@ static void ave_26b123_layout(struct kunit *test) KUNIT_EXPECT_EQ(test, b->hdr_bytes, a->hdr_bytes); KUNIT_EXPECT_EQ(test, b->max_slots, a->max_slots); KUNIT_EXPECT_EQ(test, b->process_subtype, a->process_subtype); - /* Both counted; only the 27.2 build runs sessions without B-frames and at any rate. */ + /* Both counted, and both run sessions without B-frames and at any rate. */ KUNIT_EXPECT_TRUE(test, a->counted && b->counted); - KUNIT_EXPECT_FALSE(test, a->any_gop); + KUNIT_EXPECT_TRUE(test, a->any_gop); KUNIT_EXPECT_TRUE(test, b->any_gop); KUNIT_EXPECT_PTR_EQ(test, ave_layout_for_crc(AVE_FW_TEXT_CRC_T8122_26B123), b); } diff --git a/drivers/media/platform/apple/ave/ave-layout.c b/drivers/media/platform/apple/ave/ave-layout.c index bce97316b0af95..b05103511532ff 100644 --- a/drivers/media/platform/apple/ave/ave-layout.c +++ b/drivers/media/platform/apple/ave/ave-layout.c @@ -552,6 +552,8 @@ const struct ave_fw_layout ave_layout_26a428 = { * B-frames. */ AVE_LAYOUT_26A428_FIELDS(0x320c, 0xce4) + /* 60 fps and sessions without B-frames encode on the M5 (J815). */ + .any_gop = true, }; /* From 8613fb37d28bf5e69c2c05288e5fe383c67d2783 Mon Sep 17 00:00:00 2001 From: Nick Date: Fri, 20 Nov 2026 18:20:22 +0700 Subject: [PATCH 1172/1514] media: apple: ave: 26A428: encode HEVC Main 10 The counted (26A428) layout refused HEVC Main 10, so on the M5 S_FMT turned P010 into NV12 and a Main 10 profile failed at STREAMON. The layout's Start maps every word the 9003 Main 10 capture changes with bit depth: the 8-bit flag (0x35e8), the QP floors, the bit depth (0x37c0), both profile/compat groups and the SPS luma/chroma depth. A KUnit case builds a Main 10 Start on 26A428 and on 26B123 and checks those words against the 8-bit one. The encodes below ran with the driver's existing 10-bit DPB and coded buffer sizes. Lift the refusal for the layout, and list P010 for HEVC with Main 10 in the profile menu there. Whether Main 10 can be encoded follows from what the layout's Start maps, not from the chip, so it goes for every firmware on the 26A428 layout; only the M5 (T8142) has encoded with it so far, and the M5 Pro and Max (T6050) use the same layout. The 26B123 layout (the M3 and M4 with macOS 27.2) has the same Start, so it gets Main 10 too, with no Main 10 row there yet. As on 9003, a new context then starts on HEVC, so a client probing the raw formats first sees P010; clients that set the coded format are unaffected. Tested on a MacBook Air 15" M5 (J815, macOS 27.2 26B123 firmware): v4l2-ctl P010 -> HEVC at 30 fps with B-frames, the decoded stream compared with the input: - 1280x720, 30 frames: Main 10, 4:2:0 10-bit, PSNR 46.5 dB, 269 fps; - 1920x1080, 120 frames: PSNR 38.2 dB, 243 fps (86 B pictures); - 3840x2160, 60 frames: PSNR 35.2 dB, 65 fps; and no DART faults or timeouts. NV12 to HEVC Main (41.7 dB) and H.264 High (40.8 dB) at 1080p in the same run are unchanged. Signed-off-by: Nick --- .../media/platform/apple/ave/ave-abi-test.c | 59 +++++++++++++++++++ drivers/media/platform/apple/ave/ave-sess.c | 3 - drivers/media/platform/apple/ave/ave-v4l2.c | 13 ++-- 3 files changed, 67 insertions(+), 8 deletions(-) diff --git a/drivers/media/platform/apple/ave/ave-abi-test.c b/drivers/media/platform/apple/ave/ave-abi-test.c index 001f5f4b623841..61ca31a6fe1807 100644 --- a/drivers/media/platform/apple/ave/ave-abi-test.c +++ b/drivers/media/platform/apple/ave/ave-abi-test.c @@ -268,6 +268,64 @@ static void ave_9003_hevc_main10(struct kunit *test) } } +/* + * HEVC Main 10 on the counted layouts: 26A428, which T8142 encodes with, and + * 26B123 (the M3/M4 27.2 build), which shares its Start. The words that change + * with bit depth take the 9003 capture's Main 10 values (the host tests in + * tests/test.c check the same words). + */ +static void ave_26a428_hevc_main10(struct kunit *test) +{ + static const struct ave_fw_layout *const layouts[] = { + &ave_layout_26a428, &ave_layout_26b123, + }; + + for (unsigned int l = 0; l < ARRAY_SIZE(layouts); l++) { + struct ave_dev *ave = kunit_kzalloc(test, sizeof(*ave), GFP_KERNEL); + struct ave_ctx *ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + struct ave_session *sess = kunit_kzalloc(test, sizeof(*sess), GFP_KERNEL); + u8 *main8, *main10; + size_t len; + + KUNIT_ASSERT_NOT_NULL(test, ave); + KUNIT_ASSERT_NOT_NULL(test, ctx); + KUNIT_ASSERT_NOT_NULL(test, sess); + ave->layout = layouts[l]; + ctx->ave = ave; + ctx->sess = sess; + len = ave->layout->bytes[AVE_CODEC_HEVC - 1][AVE_IMAGE_START]; + main8 = kunit_kzalloc(test, len, GFP_KERNEL); + main10 = kunit_kzalloc(test, len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, main8); + KUNIT_ASSERT_NOT_NULL(test, main10); + + ave_test_session(sess, AVE_CODEC_HEVC, 1920, 1080, true); + KUNIT_ASSERT_EQ(test, ave_build_start(ctx, main8, len), 0); + ave_test_session(sess, AVE_CODEC_HEVC, 1920, 1080, true); + sess->p.min_qp = -12; + sess->p.profile = 2; + sess->p.bit_depth = 10; + KUNIT_ASSERT_EQ(test, ave_build_start(ctx, main10, len), 0); + + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x35e8), 0x10040, + "layout %u", l); + KUNIT_EXPECT_NE_MSG(test, get_unaligned_le32(main8 + 0x35e8), 0x10040, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main8 + 0x37c0), 8, "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x37c0), 10, "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, (s32)get_unaligned_le32(main10 + 0x3678), -12, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, (s32)get_unaligned_le32(main10 + 0x3740), -12, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x3a60), 0x01000101, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x6530), 0x01000000, + "layout %u", l); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(main10 + 0x66dc), 2, "layout %u", l); + KUNIT_EXPECT_NE_MSG(test, get_unaligned_le32(main8 + 0x66dc), 2, "layout %u", l); + } +} + /* One 1080p HEVC Start or first Process image, with speed mode @speed. */ static void ave_speed_image(struct kunit *test, struct ave_ctx *ctx, enum ave_image image, bool bframes, bool main10, @@ -1657,6 +1715,7 @@ static void ave_m3_probe_only(struct kunit *test) static struct kunit_case ave_abi_cases[] = { KUNIT_CASE(ave_t6041_text_boot_word), KUNIT_CASE(ave_9003_byte_equality), KUNIT_CASE(ave_9003_hevc_main10), + KUNIT_CASE(ave_26a428_hevc_main10), KUNIT_CASE(ave_9003_speed), KUNIT_CASE(ave_cq_table), KUNIT_CASE(ave_6070_images), KUNIT_CASE(ave_6070_replies), KUNIT_CASE(ave_6070_frame_result), diff --git a/drivers/media/platform/apple/ave/ave-sess.c b/drivers/media/platform/apple/ave/ave-sess.c index 14242054fcffd6..85e3fae75fab44 100644 --- a/drivers/media/platform/apple/ave/ave-sess.c +++ b/drivers/media/platform/apple/ave/ave-sess.c @@ -194,9 +194,6 @@ static int ave_sess_params(struct ave_ctx *ctx, struct ave_params *p) return -EOPNOTSUPP; p->bit_depth = 8; if (p->sample_bytes == 2) { - /* Only the 9003 layout's Main 10 fields are mapped. */ - if (ctx->ave->layout->counted) - return -EOPNOTSUPP; p->profile = AVE_HEVC_MAIN_10; p->bit_depth = 10; p->min_qp -= AVE_QP_BD_OFFSET_10; diff --git a/drivers/media/platform/apple/ave/ave-v4l2.c b/drivers/media/platform/apple/ave/ave-v4l2.c index a5ac2073a2a26b..5d73737fe6624a 100644 --- a/drivers/media/platform/apple/ave/ave-v4l2.c +++ b/drivers/media/platform/apple/ave/ave-v4l2.c @@ -77,17 +77,20 @@ static bool ave_fmt_listed(const u32 *list, unsigned int n, u32 fourcc) return false; } -/* HEVC Main 10 (P010 input) is mapped for the 9003 layout only. */ +/* + * HEVC Main 10 (P010 input): the 9003 and the counted (26A428) layouts, + * whose Starts map every field that changes with bit depth. The 6070 + * layout has none. + */ static bool ave_main10_supported(const struct ave_dev *ave) { - return ave->layout && ave->layout->kind == AVE_LAYOUT_9003 && - !ave->layout->counted; + return ave->layout && (ave->layout->counted || + ave->layout->kind == AVE_LAYOUT_9003); } /* * Whether raw @fourcc can be encoded to @coded on @ave. P010 is only the - * input of HEVC Main 10: H.264 has no 10-bit profile here, and the 6070 - * and 26A428 layouts have no Main 10 fields. + * input of HEVC Main 10: H.264 has no 10-bit profile here. */ static bool ave_raw_fmt_ok(const struct ave_dev *ave, u32 coded, u32 fourcc) { From e6acdbeffe09a9714c3240acf3433241f1c53f37 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 14 Nov 2026 18:41:31 +0700 Subject: [PATCH 1173/1514] drm/asahi: agx_stats: Say why pstate and its frequency aren't valid pstate and achieved_frequency_hz printed "unsupported" whenever pstate_status wasn't valid. On a firmware that reports its state (M5, A18 Pro), the state is "stale" after the cores power up, until the firmware's next state report, and the file then read as a missing feature. Print the status word instead. achieved_frequency_hz keeps "unsupported" for a valid state with no frequency in the board's table. busy_ns also gets a "stale" reading, for a total that stopped (used by the next change); every other non-valid busy status still reads "unsupported". Where pstate is unsupported (25G83, and always there through g17::stats::qualify), the status word is "unsupported", so that output is byte for byte the same. The integration test's formatter cases follow the new readings and check "busy_ns stale". Signed-off-by: Nick --- .../ABI/testing/sysfs-driver-asahi-agx-stats | 9 +++++++-- drivers/gpu/drm/asahi/sysfs.c | 17 +++++++++++++++-- tools/asahi/g17-telemetry-integration-tests.py | 13 ++++++++++--- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats index 3ecdd8a454fae8..4edfacb018cdf4 100644 --- a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats +++ b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats @@ -115,8 +115,13 @@ Description: in other records (see below). utilisation_status is never unsupported on these firmwares. Numeric metrics are printed only while - their capability is valid; otherwise their value is - the string unsupported. + their capability is valid. Otherwise utilisation + values read unsupported; pstate and + achieved_frequency_hz read pstate_status (stale, + unavailable or unsupported), and achieved_frequency_hz + reads unsupported for a valid state with no + frequency in the board's table; busy_ns reads stale + when its total stopped and unsupported otherwise. util_tiler_percent, util_renderer_percent, util_device_percent Unsigned integer percent (0..100), from tag 0x13 diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index 9cf5eba61c55e8..0160e1d1e017d0 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -102,10 +102,16 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha */ n += sysfs_emit_at(buf, n, "pstate_status %s\n", asahi_stats_quality(snap.pstate_status)); + /* + * A pstate that is not valid reads its status word, so stale or + * unavailable is not mistaken for a missing feature. Where it is + * unsupported, the output is unchanged. + */ if (snap.pstate_status == 1) n += sysfs_emit_at(buf, n, "pstate %u\n", snap.pstate); else - n += sysfs_emit_at(buf, n, "pstate unsupported\n"); + n += sysfs_emit_at(buf, n, "pstate %s\n", + asahi_stats_quality(snap.pstate_status)); /* No host frequency request, measured power or temperature. */ n += sysfs_emit_at(buf, n, "requested_frequency_hz unsupported\n"); /* @@ -116,11 +122,18 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha if (snap.pstate_status == 1 && (snap.achieved_frequency_hz || !snap.pstate)) n += sysfs_emit_at(buf, n, "achieved_frequency_hz %llu\n", (unsigned long long)snap.achieved_frequency_hz); - else + else if (snap.pstate_status == 1) + /* A valid state with no frequency in the board's table. */ n += sysfs_emit_at(buf, n, "achieved_frequency_hz unsupported\n"); + else + n += sysfs_emit_at(buf, n, "achieved_frequency_hz %s\n", + asahi_stats_quality(snap.pstate_status)); if (snap.busy_status == 1) n += sysfs_emit_at(buf, n, "busy_ns %llu\n", (unsigned long long)snap.busy_ns); + else if (snap.busy_status == 2) + /* M5: the total stopped (a statistics ring was quarantined). */ + n += sysfs_emit_at(buf, n, "busy_ns stale\n"); else n += sysfs_emit_at(buf, n, "busy_ns unsupported\n"); n += sysfs_emit_at(buf, n, "power_mw unsupported\n" diff --git a/tools/asahi/g17-telemetry-integration-tests.py b/tools/asahi/g17-telemetry-integration-tests.py index de4d614ed96006..c12450e78704a1 100755 --- a/tools/asahi/g17-telemetry-integration-tests.py +++ b/tools/asahi/g17-telemetry-integration-tests.py @@ -707,13 +707,16 @@ def item(source, signature): assert(strstr(now,"power_mw unsupported\n")); assert(strstr(now,"temperature_raw unsupported\n")); assert(strstr(now,"requested_frequency_hz unsupported\n")); - assert(strstr(now,"achieved_frequency_hz unsupported\n")); if(status==1) { + /* A valid state with no frequency in the board's table. */ + assert(strstr(now,"achieved_frequency_hz unsupported\n")); assert(strstr(now,"util_tiler_percent 30\nutil_renderer_percent 80\nutil_device_percent 57\n")); assert(strstr(now,"pstate 6\n")); } else { + /* Not valid: the pstate and its frequency say why. */ + assert(strstr(now,status==2?"pstate stale\n":"pstate unavailable\n")); + assert(strstr(now,status==2?"achieved_frequency_hz stale\n":"achieved_frequency_hz unavailable\n")); assert(strstr(now,"util_device_percent unsupported\n")); - assert(strstr(now,"pstate unsupported\n")); assert(strstr(now,status==2?"pstate_status stale\n":"pstate_status unavailable\n")); assert(strstr(now,status==2?"utilisation_status stale\n":"utilisation_status unavailable\n")); } @@ -727,7 +730,11 @@ def item(source, signature): assert(strstr(now,"pstate 0\nrequested_frequency_hz unsupported\nachieved_frequency_hz 0\n")); current.pstate_status=2; agx_stats_show(NULL,&stats.attr,now); - assert(strstr(now,"pstate unsupported\nrequested_frequency_hz unsupported\nachieved_frequency_hz unsupported\n")); + assert(strstr(now,"pstate stale\nrequested_frequency_hz unsupported\nachieved_frequency_hz stale\n")); + /* M5: a stopped busy total reads stale. */ + current=(struct asahi_qualified_stats){.util_status=1,.pstate_status=1,.pstate=6,.busy_status=2,.busy_ns=77}; + agx_stats_show(NULL,&stats.attr,now); + assert(strstr(now,"busy_ns stale\n") && !strstr(now,"busy_ns 77")); /* G16S: pstate unsupported by firmware, utilisation still valid. */ current=(struct asahi_qualified_stats){.util_status=1,.pstate_status=3,.tiler=30,.renderer=80,.device=57,.pstate=0, .util_samples=19,.util_host_ns=123}; From 33abd8703519cdd31bf4e8e46a0421c96d9bfc99 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 14 Nov 2026 18:41:31 +0700 Subject: [PATCH 1174/1514] drm/asahi: g17: count busy time across power gates, in timestamp order On a J815 (M5) under a frame-paced load (es2gears + vkcube, 20 s), the cores power-gate about 95 times a second (power_epoch 10861), usually with one utilisation record per power epoch. busy_ns stayed 0 although the 0x13 records kept arriving: - busy time needed two records in one epoch, because every boundary cleared the window start (busy_ts); - the records queued before a boundary, and those drained while the cores read gated, never reached the decoder. Busy time now has its own ordering, separate from the utilisation epoch, on every firmware whose Protocol integrates it (M5, T6041 and A18 Pro): - The decoder keeps the firmware timestamp up to which it has credited busy time (busy_mark). Epoch boundaries keep it. A record at or before it adds nothing, so an older queued record, a repeat, or the other role's record for the same time is never credited twice, whatever the drain order. - A later record closes the window since the mark when that is at most two utilisation periods, as before. After a longer gap it closes only its own period (8 ms on M5 and T6041, 16 ms on the A18 Pro), which lies after the mark: the gap is never credited. Before, such a record only set the baseline. The first record after a gate now credits its period at its own device utilisation. - Records a power boundary keeps out of the averaging epoch (cut off, or drained while gated) are decoded for busy time only (record_busy). The utilisation average, its delivery cadence and the performance state do not see them. Suspend, a real invalidation's discard and quarantine still keep everything out. - A record further behind the mark than a full statistics ring of utilisation records (256 x the record interval, twice over: 4.1 s at 8 ms, 8.2 s at 16 ms) cannot still be queued; it means the firmware clock started again and only sets a new mark. - busy_ns reads stale once a statistics ring is quarantined, since nothing adds to it any more. Credited windows never overlap and each lies at or before its own record's timestamp, so busy_ns stays bounded by elapsed time. T6040 25G83 integrates no busy time and is unchanged. The gated performance state (off, valid 0) is left as it is. Host tests: tools/asahi/run-host-tests.py --only telemetry passes: the decoder's 13 cases, the integration fixture and every listed mutation. New decoder cases: gates between every record, records kept out of the epoch, interleaved roles, clock restart. The A18 Pro window case now and the T6041 cases (decoder and reader) now expect a record after a gap longer than two periods to credit its own period. The fixture drops the kernel's ring-size check, since its firmware ring has 8 slots. New ring case: records cut off at a gate and drained while gated count, a repeat from the other role does not, suspend keeps them out, quarantine reads stale. The fixture's quarantine mutation now hits both the admission and the read, through statistics_quarantined(). Not yet run on hardware in this form; the M5 behaviour is the one measured on the J815 before the A18 Pro protocol work. Signed-off-by: Nick --- .../ABI/testing/sysfs-driver-asahi-agx-stats | 44 +++-- Documentation/gpu/asahi-usage-stats.rst | 16 +- drivers/gpu/drm/asahi/g17/channel.rs | 34 +++- drivers/gpu/drm/asahi/g17/telemetry.rs | 161 +++++++++++++++--- drivers/gpu/drm/asahi/sysfs.c | 2 +- .../asahi/g17-telemetry-integration-tests.py | 51 +++++- 6 files changed, 252 insertions(+), 56 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats index 4edfacb018cdf4..46529772affd6f 100644 --- a/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats +++ b/Documentation/ABI/testing/sysfs-driver-asahi-agx-stats @@ -191,18 +191,26 @@ Description: 0x13 records of these firmwares carry a timestamp in 24 MHz ticks (words 1 and 2), one every 8 ms on M5 and T6041 (192000 ticks) and every 16 ms on the A18 - Pro (384000 ticks). Each record credits - the window since the previous record of its epoch at - its device utilisation. A record more than two - periods after the previous one, or with an earlier - timestamp, only starts a new window, so time the GPU - spent gated is never credited, and a load sparser - than one period reads low. MEASURED on T6050 - (J716c): 871 and 863 ms for three 300 ms compute jobs - at full clock (905 and 919 ms of work). MEASURED on - T8140 (J700), 24 traces of GPU stress loads: within - about 20% of the union of the commands' own execution - intervals for loads busy more than half the time. + Pro (384000 ticks), and are credited in + that order at their device utilisation, from both + roles and across power epochs. The driver keeps the + timestamp up to which it has credited busy time; a + record at or before it gets nothing, so no interval + is credited twice. A later record credits the window + since that mark when it is at most two periods, and + only its own period after a longer gap, so time the + GPU spent gated is never credited. Records a power + boundary keeps out of the utilisation average (see + below) still count here; suspend, a real epoch + invalidation's discard and quarantine keep them out. + busy_ns reads stale once a statistics ring is + quarantined. MEASURED on T6050 (J716c): 871 and 863 + ms for three 300 ms compute jobs at full clock (905 + and 919 ms of work). MEASURED on T8140 (J700), 24 + traces of GPU stress loads, with windows that ended + at each power epoch: within about 20% of the union + of the commands' own execution intervals for loads + busy more than half the time. requested_frequency_hz, power_mw, temperature_raw Unsupported. @@ -224,15 +232,17 @@ Description: Suspend/resume, restart, statistics-ring quarantine, observed core gating and teardown end validity. After an epoch boundary, each ring's already queued records are discarded before new - baselines are accepted. A quarantined statistics ring disables - both roles' exports until reprobe; a trace-ring error does not. + baselines are accepted; where busy_ns is integrated, those a + power boundary kept out still reach it, as described there. A + quarantined statistics ring disables both roles' exports until + reprobe; a trace-ring error does not. Reads take the device mutex and do not wake the GPU. The firmware_reports debugfs view retains per-role raw packets, counts and host monotonic receive times, plus capability status, - policy, timestamp and diagnostic tick deltas. Tick deltas are - never accumulated as GPU busy time. Firmware role streams are - merged in drain order without deduplication. + policy, timestamp and diagnostic tick deltas. The tag 0x10 tick + deltas are never accumulated as GPU busy time. Firmware role + streams are merged in drain order without deduplication. The diagnostic also identifies the platform device, records the transport-admitted count and last-admission decision per role/tag, and shows suspension, queued-record discard and quarantine state. diff --git a/Documentation/gpu/asahi-usage-stats.rst b/Documentation/gpu/asahi-usage-stats.rst index fd7e8e0d210fc2..7905e9e6b50623 100644 --- a/Documentation/gpu/asahi-usage-stats.rst +++ b/Documentation/gpu/asahi-usage-stats.rst @@ -165,11 +165,17 @@ run on the same backend and decoder and carry more in their statistics ring. ALU benchmark. * ``busy_ns``: the utilisation records carry their own timestamps (words 1 and 2, 24 MHz ticks), one every 8 ms on the M5 and T6041 and every 16 ms on the - A18 Pro, so each record closes a window of known length, which is credited at - the record's device utilisation. A record that follows the previous one by - more than two periods, or whose timestamp went back, only starts a new - window: time the GPU spent gated is never credited, and a load sparser than - one period reads low. The total keeps counting across power epochs. + A18 Pro, so each record closes a window of known length, which is credited at the + record's device utilisation. Records are credited in timestamp order, from + both roles and across power epochs: the driver keeps the timestamp up to + which it has counted, and a record at or before it adds nothing. A record + within two periods of that mark closes the window since it; after a longer + gap it closes only its own period, so time the GPU spent gated is never + credited. Under a frame-paced load the cores gate many times a second, often + with one record per power epoch, so the records a power boundary keeps out of + the utilisation average still count here. Suspend, recovery and quarantine + keep them out, and ``busy_ns`` reads ``stale`` once a statistics ring is + quarantined. The driver asks for full performance while work is in flight, which the firmware takes as a floor for its state. An A18 Pro at work therefore normally diff --git a/drivers/gpu/drm/asahi/g17/channel.rs b/drivers/gpu/drm/asahi/g17/channel.rs index 05c2f7ecf51c88..214004f018f608 100644 --- a/drivers/gpu/drm/asahi/g17/channel.rs +++ b/drivers/gpu/drm/asahi/g17/channel.rs @@ -15,6 +15,10 @@ use super::fw::{channels::*, initdata::status}; use super::initdata::InitData; use super::Role; +// The busy-time rebase bound counts the statistics ring's records; `telemetry.rs` repeats the +// ring size so that it builds on its own for the host tests. +const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SLOTS); + /// Device-control records published since the driver loaded. Counted across firmware /// restarts, so it only grows. static CONTROL_PUBLISHED: AtomicU64 = AtomicU64::new(0); @@ -180,7 +184,19 @@ impl Rings { } pub(super) fn read_statistics(&self, now_ns: u64) -> super::telemetry::Readout { - self.telemetry.read(now_ns, self.max_age_ns) + let mut view = self.telemetry.read(now_ns, self.max_age_ns); + // A quarantined statistics ring adds nothing more: the total is no longer current. + if view.busy_status == super::telemetry::VALID && self.statistics_quarantined() { + view.busy_status = super::telemetry::STALE; + } + view + } + + /// Either role's statistics ring is quarantined, which stops both roles' exports. + fn statistics_quarantined(&self) -> bool { + self.quarantined + .iter() + .any(|rings| rings[ReportRing::Statistics as usize]) } pub(super) fn write_reports(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { @@ -211,13 +227,13 @@ impl Rings { return; } let statistics = matches!(ring, ReportRing::Statistics); - let accept = !self.suspended - && self.statistics_powered + // Suspend, a real invalidation's discard and quarantine keep every record out. + let accept_busy = !self.suspended && !self.discard_statistics[role as usize] - && !self - .quarantined - .iter() - .any(|rings| rings[ReportRing::Statistics as usize]); + && !self.statistics_quarantined(); + // A power boundary also keeps the records before it out of the averaging epoch; + // their own timestamps still place them for busy time (Telemetry::record_busy). + let accept = accept_busy && self.statistics_powered; if let Err(error) = Self::consume_report( init, role, @@ -226,6 +242,7 @@ impl Rings { &mut self.telemetry, self.max_age_ns, accept, + accept_busy, &mut self.statistics_cutoff[role as usize], ) { self.stop_report(dev, role, ring, error); @@ -256,6 +273,7 @@ impl Rings { telemetry: &mut super::telemetry::Telemetry, max_age_ns: u64, accept_statistics: bool, + accept_busy: bool, statistics_cutoff: &mut Option, ) -> Result { let (state, entries, capacity, allowed_types) = ring.geometry(init); @@ -295,6 +313,8 @@ impl Rings { reports.record(role, words, host_ns, allowed_types, admitted); if admitted { telemetry.record(&words, host_ns, max_age_ns); + } else if accept_busy { + telemetry.record_busy(&words); } } consumer = (consumer + 1) & (capacity - 1); diff --git a/drivers/gpu/drm/asahi/g17/telemetry.rs b/drivers/gpu/drm/asahi/g17/telemetry.rs index 9e61dcd6b2e49e..bb439ee4acc76c 100644 --- a/drivers/gpu/drm/asahi/g17/telemetry.rs +++ b/drivers/gpu/drm/asahi/g17/telemetry.rs @@ -48,6 +48,10 @@ const _: () = { }; const TIMER_HZ: u64 = 24_000_000; +/// Records a firmware statistics ring holds (`fw::channels::STATISTICS_SLOTS`), repeated +/// here so the decoder builds on its own (`tools/asahi/g17-telemetry-tests.rs`); the kernel +/// build asserts the two are equal in `channel.rs`. +pub(crate) const STATISTICS_RING_RECORDS: u32 = 256; /// What a firmware reports beyond utilisation. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -86,11 +90,20 @@ impl Protocol { self.util_period_ticks != 0 } - /// A utilisation record more than two intervals after the previous one follows a gap the - /// firmware did not report (gated or lost records): it only sets the baseline. + /// A utilisation record at most two intervals after the previous one closes the window + /// since it. One after a longer gap the firmware did not report (the GPU was gated, or + /// records were lost) closes only its own sampling period. fn max_window_ticks(self) -> u64 { 2 * self.util_period_ticks } + + /// How far a record can lag the busy mark and still have been queued: a full statistics + /// ring of the other role's utilisation records, one per interval, with a factor of two + /// for margin. A record further behind comes from a firmware clock that started again, + /// and only sets a new mark. + fn rebase_ticks(self) -> u64 { + 2 * u64::from(STATISTICS_RING_RECORDS) * self.util_period_ticks + } } #[derive(Default)] @@ -114,9 +127,10 @@ pub(super) struct Telemetry { /// Highest valid performance state index for tags 0x19/0x1b, derived from the device's /// state-frequency table; zero fails closed and rejects all 0x1b states. max_pstate: u32, - /// Timestamp of the latest utilisation record in this epoch: the start of the window the - /// next one closes. - busy_ts: Option, + /// Firmware timestamp up to which busy time has been credited. It is kept across + /// epochs: power gates, suspend and restarts end the utilisation average, but never + /// let a record at or before this mark be credited again. + busy_mark: Option, busy_ns: u64, /// End of the latest performance state interval (tag 0x19), in timer ticks. pstate_interval_end: Option, @@ -148,8 +162,7 @@ impl Telemetry { self.delivery_ns = None; self.delivery_intervals = [None; 2]; self.gated = false; - // Busy time keeps counting across epochs; only the window start is lost. - self.busy_ts = None; + // Busy time keeps counting across epochs, ordered by its own mark. self.pstate_interval_end = None; } @@ -264,20 +277,47 @@ impl Telemetry { } } - /// Credits the window a utilisation record closes, at its device utilisation. The window - /// starts at the previous record of the epoch; a record after a longer gap than - /// [`Protocol::max_window_ticks`] (the GPU was gated or records were lost) or one whose - /// timestamp went back only sets the baseline, so an idle gap is never credited. + /// A utilisation record that is kept out of the utilisation average: one a power boundary + /// cut off, or one drained while the cores read gated. The firmware produced it before + /// the boundary, so it describes powered time, which its own timestamp places. Only busy + /// time takes it; the average, the delivery cadence and the performance state are left + /// as they are. + pub(super) fn record_busy(&mut self, words: &[u32; 18]) { + if !self.protocol.integrates_busy() + || words[0] != 0x13 + || [words[3], words[4], words[6]].iter().any(|&v| v > 100) + { + return; + } + self.integrate_busy(u64::from(words[1]) | (u64::from(words[2]) << 32), words[6]); + } + + /// Credits the window a utilisation record closes, at its device utilisation. + /// + /// Records are credited in firmware timestamp order, from both roles and across + /// epochs: a record at or before [`Self::busy_mark`] was already covered and gets + /// nothing, so a time interval is never credited twice. A later record closes the + /// window since the mark when that is at most [`Protocol::max_window_ticks`]; after a + /// longer gap (the cores were gated, or records were lost) it closes only its own + /// sampling period, which starts after the mark, so the gap itself is never credited. + /// The first record only sets the mark. fn integrate_busy(&mut self, timestamp: u64, device: u32) { - if let Some(last) = self.busy_ts { - let window = timestamp.wrapping_sub(last); - if timestamp > last && window <= self.protocol.max_window_ticks() { + match self.busy_mark { + Some(mark) if timestamp > mark => { + let gap = timestamp - mark; + let window = if gap <= self.protocol.max_window_ticks() { + gap + } else { + self.protocol.util_period_ticks + }; // At most two 16 ms periods (768000 ticks) x 100 x 10^9: no overflow. let ns = window * u64::from(device) * 1_000_000_000 / (100 * TIMER_HZ); self.busy_ns = self.busy_ns.saturating_add(ns); } + Some(mark) if mark - timestamp <= self.protocol.rebase_ticks() => return, + _ => {} } - self.busy_ts = Some(timestamp); + self.busy_mark = Some(timestamp); } pub(super) fn read(&self, now_ns: u64, max_age_ns: u64) -> Readout { @@ -591,22 +631,93 @@ mod tests { half[6] = 50; stats.record(&half, 103, AGE); assert_eq!(stats.read(103, AGE).busy_ns, windows + 4_000_000); - // A gate, a long gap or a timestamp going back only sets a new baseline. + // A gate ends the utilisation epoch, not the busy time: the next record still + // closes the window since the last one. let before = stats.read(103, AGE).busy_ns; stats.gate(); let mut after = half; after[1] += 192_000; stats.record(&after, 104, AGE); - assert_eq!(stats.read(104, AGE).busy_ns, before); - after[1] += 3 * 192_000; + assert_eq!(stats.read(104, AGE).busy_ns, before + 4_000_000); + // After a longer gap the record closes only its own 8 ms period. + let before = stats.read(104, AGE).busy_ns; + after[1] += 10 * 192_000; stats.record(&after, 105, AGE); - assert_eq!(stats.read(105, AGE).busy_ns, before); + assert_eq!(stats.read(105, AGE).busy_ns, before + 4_000_000); + // A record at or before the mark was already covered. + let before = stats.read(105, AGE).busy_ns; after[1] -= 1000; stats.record(&after, 106, AGE); + after[1] += 1000; + stats.record(&after, 106, AGE); assert_eq!(stats.read(106, AGE).busy_ns, before); - // An epoch boundary keeps the total. + // An epoch boundary keeps the total and the mark. stats.invalidate(); assert_eq!(stats.read(107, AGE).busy_ns, before); + stats.record(&after, 108, AGE); + assert_eq!(stats.read(108, AGE).busy_ns, before); + } + + fn m5_util(ticks: u64, device: u32) -> [u32; 18] { + let mut words = M5_U[0]; + (words[1], words[2], words[6]) = (ticks as u32, (ticks >> 32) as u32, device); + words + } + + #[test] + fn m5_busy_time_counts_through_frequent_gates() { + // A frame-paced load: one record per epoch, a gate between any two. + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); + let mut ticks = 0x59_0000_0000u64; + stats.record(&m5_util(ticks, 100), 1, AGE); + for n in 0..10u64 { + stats.gate(); + stats.invalidate(); + ticks += 250_000; // 10.4 ms: more than one period, at most two. + stats.record(&m5_util(ticks, 100), 2 + n, AGE); + } + assert_eq!(stats.read(20, AGE).busy_ns, 10 * ticks_ns(250_000)); + } + + #[test] + fn m5_records_kept_out_of_the_epoch_still_count_once() { + let base = 0x59_0000_0000u64; + let mut stats = Telemetry::new(Protocol::PSTATE_8MS, 13); + stats.record(&m5_util(base, 100), 1, AGE); + // Cut off by a boundary, decoded by its own timestamp. + stats.gate(); + stats.record_busy(&m5_util(base + 192_000, 100)); + assert_eq!(stats.read(2, AGE).busy_ns, 8_000_000); + // It does not start a utilisation sample in the new epoch. + assert_eq!(stats.read(2, AGE).util_samples, 0); + // A copy of it, from the queue or from the other role, is not counted again, + // nor an older record drained later. + stats.record(&m5_util(base + 192_000, 100), 3, AGE); + stats.record_busy(&m5_util(base + 100_000, 100)); + assert_eq!(stats.read(3, AGE).busy_ns, 8_000_000); + // Interleaved roles split the time between them and never overlap. + stats.record_busy(&m5_util(base + 288_000, 100)); + stats.record(&m5_util(base + 384_000, 100), 4, AGE); + stats.record_busy(&m5_util(base + 336_000, 100)); + assert_eq!(stats.read(4, AGE).busy_ns, 16_000_000); + // Records the decoder would refuse are ignored here too. + let mut bad = m5_util(base + 576_000, 100); + bad[4] = 101; + stats.record_busy(&bad); + let mut other = m5_util(base + 576_000, 100); + other[0] = 0x1b; + stats.record_busy(&other); + assert_eq!(stats.read(5, AGE).busy_ns, 16_000_000); + // A firmware clock that started again only sets a new mark. + stats.record_busy(&m5_util(1_000, 100)); + assert_eq!(stats.read(6, AGE).busy_ns, 16_000_000); + stats.record_busy(&m5_util(1_000 + 192_000, 50)); + assert_eq!(stats.read(7, AGE).busy_ns, 20_000_000); + // A firmware that integrates no busy time decodes none of it. + let mut legacy = Telemetry::default(); + legacy.record_busy(&m5_util(base, 100)); + legacy.record_busy(&m5_util(base + 192_000, 100)); + assert_eq!(legacy.read(8, AGE).busy_ns, 0); } #[test] @@ -651,13 +762,14 @@ mod tests { words[6] = 25; stats.record(&words, 102, AGE); assert_eq!(stats.read(102, AGE).busy_ns, 20_000_000); - // Up to two periods is one window; longer is a gap the GPU spent gated. + // Up to two periods is one window; after a longer gap, which the GPU spent gated, + // a record closes only its own 16 ms period. words[1] += 768_000; stats.record(&words, 103, AGE); assert_eq!(stats.read(103, AGE).busy_ns, 28_000_000); words[1] += 768_001; stats.record(&words, 104, AGE); - assert_eq!(stats.read(104, AGE).busy_ns, 28_000_000); + assert_eq!(stats.read(104, AGE).busy_ns, 32_000_000); } #[test] @@ -707,13 +819,14 @@ mod tests { words[6] = 50; stats.record(&words, 102, AGE); assert_eq!(stats.read(102, AGE).busy_ns, 12_000_000); - // Up to two periods (16 ms) is one window; longer is a gap. + // Up to two periods (16 ms) is one window; after a longer gap only the record's own + // period (8 ms at 50%) is credited. words[1] += 384_000; stats.record(&words, 103, AGE); assert_eq!(stats.read(103, AGE).busy_ns, 20_000_000); words[1] += 384_001; stats.record(&words, 104, AGE); - assert_eq!(stats.read(104, AGE).busy_ns, 20_000_000); + assert_eq!(stats.read(104, AGE).busy_ns, 24_000_000); } #[test] diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index 0160e1d1e017d0..887c54c56545b0 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -132,7 +132,7 @@ static ssize_t agx_qualified_stats_show(struct asahi_stats_attribute *stats, cha n += sysfs_emit_at(buf, n, "busy_ns %llu\n", (unsigned long long)snap.busy_ns); else if (snap.busy_status == 2) - /* M5: the total stopped (a statistics ring was quarantined). */ + /* The total stopped (a statistics ring was quarantined). */ n += sysfs_emit_at(buf, n, "busy_ns stale\n"); else n += sysfs_emit_at(buf, n, "busy_ns unsupported\n"); diff --git a/tools/asahi/g17-telemetry-integration-tests.py b/tools/asahi/g17-telemetry-integration-tests.py index c12450e78704a1..2522db9d5e076d 100755 --- a/tools/asahi/g17-telemetry-integration-tests.py +++ b/tools/asahi/g17-telemetry-integration-tests.py @@ -378,11 +378,12 @@ def item(source, signature): assert_eq!((view.util_status,view.device,view.pstate_status,view.busy_status,view.busy_ns), (telemetry::VALID,50,telemetry::UNAVAILABLE,telemetry::VALID,0)); assert_eq!(reader.frequency(),Some((None,1_578_000_000))); - // 8 ms (192_000 ticks) at 50% -> 4 ms busy; 16 ms (384_000 ticks) at 100% -> +16 ms; >384_000 ticks gap ignored. + // 8 ms (192_000 ticks) at 50% -> 4 ms busy; 16 ms (384_000 ticks) at 100% -> +16 ms; after a + // >384_000 ticks gap only the record's own 8 ms period at 100% -> +8 ms. push([0x13,100_000+192_000,0,20,40,0,50,0,0,0,0,0,0,0,0,0,0,0]); push([0x13,100_000+192_000+384_000,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); push([0x13,100_000+192_000+384_000+384_001,0,100,100,0,100,0,0,0,0,0,0,0,0,0,0,0]); - assert_eq!(reader.read().busy_ns,20_000_000); + assert_eq!(reader.read().busy_ns,28_000_000); // Tag 0x10 is ignored when Protocol::PSTATE_8MS is active. push([0x10,0x2500,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0]); assert_eq!(reader.read().pstate_status,telemetry::UNAVAILABLE); @@ -576,6 +577,47 @@ def item(source, signature): } } #[test] + fn m5_busy_time_takes_records_a_power_boundary_kept_out() { + use {channel::Rings,fw::variant::InitGraph,Role::*}; + let dev=crate::device::Device; + let init=initdata::InitData::new(); + let mut rings=Rings::new(InitGraph::G17P,telemetry::Protocol::PSTATE_8MS,13).unwrap(); + // 8 ms windows at 100%, timestamps in words 1 and 2. + let util=|ticks:u32|[0x13,ticks,0x59,0,0,100,100,0,0,0,0,0,0,0,0,0,0,0]; + init.push(Primary,util(0)); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,0); + // Queued at a gate: cut off from the average, still busy time. + init.push(Primary,util(192_000)); + rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],false,1); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,8_000_000); + // Drained while gated, from the other role: the same. + init.push(Secondary,util(384_000)); + rings.drain_statistics(&dev,&init,Secondary); + assert_eq!(rings.read_statistics(1).busy_ns,16_000_000); + // Powered again: one record per epoch keeps counting, a repeat does not. + rings.observe_statistics_power(&dev,&init,&[Primary,Secondary],true,2); + init.push(Primary,util(576_000)); + init.push(Secondary,util(576_000)); + rings.drain_statistics(&dev,&init,Primary); + rings.drain_statistics(&dev,&init,Secondary); + assert_eq!(rings.read_statistics(1).busy_ns,24_000_000); + assert_eq!(rings.read_statistics(1).busy_status,telemetry::VALID); + // Suspend's discard keeps queued records out. + init.push(Primary,util(768_000)); + rings.suspend_statistics(true); + rings.drain_statistics(&dev,&init,Primary); + rings.suspend_statistics(false); + rings.drain_statistics(&dev,&init,Primary); + assert_eq!(rings.read_statistics(1).busy_ns,24_000_000); + // Quarantine stops the total: it reads stale. + init.cursors[1][1].store(fw::channels::STATISTICS_SLOTS,Ordering::Relaxed); + rings.drain_statistics(&dev,&init,Secondary); + let view=rings.read_statistics(1); + assert_eq!((view.busy_status,view.busy_ns),(telemetry::STALE,24_000_000)); + } + #[test] fn pstate_uses_drain_order_without_role_deduplication() { use {channel::Rings,fw::variant::InitGraph,Role::*}; let dev=crate::device::Device; @@ -799,6 +841,11 @@ def main(): # Compile the production transport and decoder; only MMIO/shared memory, # kernel logging and allocation adapters are replaced by host fixtures. channel = '\n'.join(line for line in channel.splitlines() if not line.startswith('//!')) + # The fixture's firmware ring has 8 slots (fw::channels below), so drop the kernel's + # check that the decoder's ring size matches the real 256-slot ring. + ring_check = 'const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SLOTS);' + assert ring_check in channel + channel = channel.replace(ring_check, '', 1) (work / 'channel.rs').write_text(channel) reports = (DRIVER / 'g17/reports.rs').read_text() store = reports.split('/// The view owns the session')[0] From 377408b577af07d0c7cfc7148f77659f8f8b93a2 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 17:37:53 -0800 Subject: [PATCH 1175/1514] drm/apple: treat a typec-routes container with no usable routes as no Type-C routes A display processor node may carry an empty typec-routes container asking Aura to write its routes from the ADT. Under an older Aura that does not populate them, or when every route child is disabled or skipped because its PHY or crossbar is disabled, the container has no usable routes. Previously dcp_register_typec_routes() failed probe with -EINVAL while dcp_t8132_ext_routes() checked of_get_available_child_count() separately. Share dcp_typec_routes_available() between both paths, route the availability check through dcp_fabric_run_probe() with KUnit coverage, and return 0 cleanly whenever zero usable routes remain (leaving phy_managed_by_typec false so the engine probes with no Type-C route). This also turns an all-disabled typec-routes container (present on 33 DCP nodes across existing DTBs until Aura or the display gate enables them) from -EINVAL into a successful no-route probe, including on the T6030 external path. Signed-off-by: Jeff Queisser --- drivers/gpu/drm/apple/dcp-fabric-effects.h | 6 ++++++ drivers/gpu/drm/apple/dcp-fabric-test.c | 10 +++++++++- drivers/gpu/drm/apple/dcp-fabric.c | 12 +++++++++--- drivers/gpu/drm/apple/dcp-fabric.h | 8 ++++++++ drivers/gpu/drm/apple/dcp.c | 2 +- 5 files changed, 33 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric-effects.h b/drivers/gpu/drm/apple/dcp-fabric-effects.h index 3f4ad7c7eb52d3..60a99a96341d7a 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-effects.h +++ b/drivers/gpu/drm/apple/dcp-fabric-effects.h @@ -231,6 +231,12 @@ dcp_fabric_run_rebalance(const struct dcp_fabric_rebalance_ops *ops, void *ctx) } } +static inline bool dcp_fabric_has_available_routes(bool has_container, + unsigned int available_children) +{ + return has_container && available_children > 0; +} + static inline int dcp_fabric_run_probe(bool has_routes, int (*register_routes)(void *ctx), void *ctx) { diff --git a/drivers/gpu/drm/apple/dcp-fabric-test.c b/drivers/gpu/drm/apple/dcp-fabric-test.c index 730ca0832d2d81..6e3f69ba68c80b 100644 --- a/drivers/gpu/drm/apple/dcp-fabric-test.c +++ b/drivers/gpu/drm/apple/dcp-fabric-test.c @@ -1560,10 +1560,18 @@ static void fabric_effect_s50a_test(struct kunit *test) struct fabric_fake f; fabric_fake_init(&f, test, false); + KUNIT_EXPECT_FALSE(test, dcp_fabric_has_available_routes(false, 0)); + KUNIT_EXPECT_FALSE(test, dcp_fabric_has_available_routes(true, 0)); + KUNIT_EXPECT_TRUE(test, dcp_fabric_has_available_routes(true, 1)); KUNIT_EXPECT_EQ(test, dcp_fabric_run_probe(false, fabric_fake_register, &f), 0); + KUNIT_EXPECT_EQ(test, + dcp_fabric_run_probe(dcp_fabric_has_available_routes(true, 0), + fabric_fake_register, &f), 0); KUNIT_EXPECT_EQ(test, f.count, 0U); KUNIT_EXPECT_FALSE(test, f.f.pipeline[0].owned); - KUNIT_EXPECT_EQ(test, dcp_fabric_run_probe(true, fabric_fake_register, &f), 0); + KUNIT_EXPECT_EQ(test, + dcp_fabric_run_probe(dcp_fabric_has_available_routes(true, 1), + fabric_fake_register, &f), 0); KUNIT_ASSERT_EQ(test, f.count, 1U); KUNIT_EXPECT_EQ(test, f.trace[0], FX_REGISTER); } diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 148dd101094d02..6d9ebbc61593ae 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -5032,8 +5032,10 @@ static int dcp_register_typec_routes_present(void *data) dcp->nr_typec_routes++; } - if (!dcp->nr_typec_routes) - return dev_err_probe(dev, -EINVAL, "Type-C route container is empty\n"); + if (!dcp->nr_typec_routes) { + dev_info(dev, "no usable Type-C display routes\n"); + return 0; + } dcp->phy_managed_by_typec = true; return 0; @@ -5064,8 +5066,12 @@ int dcp_register_typec_routes(struct apple_dcp *dcp) struct device_node *routes __free(device_node) = of_get_child_by_name(dcp->dev->of_node, "typec-routes"); struct dcp_route_probe_context ctx = { .dcp = dcp, .routes = routes }; + bool has_routes = dcp_typec_routes_available(routes); + + if (routes && !has_routes) + dev_info(dcp->dev, "no usable Type-C display routes\n"); - return dcp_fabric_run_probe(!!routes, dcp_register_typec_routes_present, &ctx); + return dcp_fabric_run_probe(has_routes, dcp_register_typec_routes_present, &ctx); } /* diff --git a/drivers/gpu/drm/apple/dcp-fabric.h b/drivers/gpu/drm/apple/dcp-fabric.h index a7d13d80942785..78c7065a0baacd 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.h +++ b/drivers/gpu/drm/apple/dcp-fabric.h @@ -4,9 +4,11 @@ #include #include +#include #include #include "dcp-fabric-core.h" +#include "dcp-fabric-effects.h" struct apple_connector; struct apple_crtc; @@ -130,6 +132,12 @@ int dcp_tunnel_dpin_activate(struct apple_dcp *dcp, u32 unit, bool active); bool dcp_is_t8132_ext(const struct apple_dcp *dcp); /* DCP probe, resume and endpoint teardown hooks. */ +static inline bool dcp_typec_routes_available(const struct device_node *routes) +{ + return dcp_fabric_has_available_routes(!!routes, + routes ? of_get_available_child_count(routes) : 0); +} + int dcp_register_typec_routes(struct apple_dcp *dcp); void dcp_sleep_hold_phys(struct apple_dcp *dcp); void dcp_typec_route_park(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 073e51f9781fec..16e13dbf46f5c6 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -7428,7 +7428,7 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) of_get_child_by_name(dcp->dev->of_node, "typec-routes"); int ret; - if (!routes || !of_get_available_child_count(routes)) { + if (!dcp_typec_routes_available(routes)) { dev_info(dcp->dev, "no Type-C display routes enabled\n"); return; } From f9138e5af60adaebef9317b9945b15bcdc1d7470 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 17:38:15 -0800 Subject: [PATCH 1176/1514] arm64: dts: apple: t6050: add power domains to the remaining display crossbars atc2_xbar in t6050-die0.dtsi carries its usb-aon and common power domains, while atc0_dpxbar, atc1_dpxbar and atc3_dpxbar in t6050-peripherals.dtsi had none. J714s and J716c carried board-local copies for atc0_dpxbar and atc1_dpxbar, and atc3_dpxbar had no copy at all. Without those domains, the driver's runtime-PM probe cannot power the crossbar, and Aura's route walk does not enable them. Put each crossbar's power domains on the shared node in t6050-peripherals.dtsi, matching atc2_xbar and the ADT, and drop the duplicate crossbar overrides from t6050-j714s-display.dtsi and t6050-j716c-left-usb4.dtsi. Signed-off-by: Jeff Queisser --- arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi | 4 ---- arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi | 10 ---------- arch/arm64/boot/dts/apple/t6050-peripherals.dtsi | 6 ++++++ 3 files changed, 6 insertions(+), 14 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi index a7fb666907ef71..4df0789d90beb9 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi @@ -290,8 +290,6 @@ }; &atc1_dpxbar { - power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; @@ -329,8 +327,6 @@ /* The left-back crossbar (the inventory's, as atc1_dpxbar) and the PHY's tunnel clock gates */ &atc0_dpxbar { - power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; - power-domain-names = "usb-aon", "common"; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi index 196128d3add0c0..e4b3577abd45c4 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j716c-left-usb4.dtsi @@ -1076,11 +1076,6 @@ /* DisplayPort alt mode and USB4 DP tunnels on the left ports. */ &atc0_dpxbar { - compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; - reg = <0x2 0xa324c000 0x0 0x4000>; - #mux-control-cells = <1>; - power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; &ps_atc0_common_dp_0 { @@ -1133,11 +1128,6 @@ hpm0_dp1: endpoint@1 { reg = <1>; remote-endpoint = <&dcpext2_left0>; }; }; }; }; }; &atc1_dpxbar { - compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; - reg = <0x2 0xab24c000 0x0 0x4000>; - #mux-control-cells = <1>; - power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; - power-domain-names = "usb-aon", "common"; status = "okay"; }; &ps_atc1_common_dp_0 { diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index 15a74bcd99f348..54e905c4915a03 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -1642,6 +1642,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x2 0xa324c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc0_usb_aon>, <&ps_atc0_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; @@ -1677,6 +1679,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x2 0xab24c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc1_usb_aon>, <&ps_atc1_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; @@ -1742,6 +1746,8 @@ compatible = "apple,t6050-display-crossbar", "apple,t8142-display-crossbar"; reg = <0x3 0x8b24c000 0x0 0x4000>; #mux-control-cells = <1>; + power-domains = <&ps_atc3_usb_aon>, <&ps_atc3_common>; + power-domain-names = "usb-aon", "common"; status = "disabled"; }; #endif From 5b9b128536a5d707d3f8799b38946214d348625f Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 17:40:48 -0800 Subject: [PATCH 1177/1514] arm64: dts: apple: t6050: share dcpext1-3 properties across T6050 boards The SoC-fixed properties of dcpext1..3 and their DARTs -- each engine's bandwidth scratch, die-local index and empty apple,clock-ids, each DART's 3 TiB DMA range, and the single register range shared by scanout and PIODMA on dispext1..3_dart -- were repeated across four board device-tree files, while dcpext0 already keeps the same set in t6050-dieX.dtsi. Move these properties onto the shared nodes in t6050-peripherals.dtsi and drop the duplicate board copies. Runtime effects across T6050 boards: - J716c: dcpext1..3 and their DARTs are unchanged in the compiled DTB. - J714s: dcpext1..3 gain apple,bw-scratch, which Aura's panel handoff overwrites from the ADT so the booted DT is identical. - K116s: dcpext1..3 gain apple,dcp-index <2..4> (was 0), apple,bw-scratch (overwritten on panel boots), and single-range dispext1..3_dart reg (apple-dart maps reg[0] only). - J775D: dcpext1..3 and their DARTs gain apple,dma-range, apple,bw-scratch, apple,dcp-index <2..4>, apple,clock-ids, and single-range dispext1..3_dart reg, so published Aura now passes its headless handoff checks and hands dcpext1..3 off to Linux (previously skipped). - Other T6050 boards without display-subsystem or dcp/disp0 aliases: dcpext1..3 stay disabled. Signed-off-by: Jeff Queisser --- .../boot/dts/apple/t6050-j714s-display.dtsi | 16 ------- .../boot/dts/apple/t6050-j714s-gpu-panel.dtsi | 44 ----------------- .../boot/dts/apple/t6050-j716c-display.dtsi | 48 ------------------- arch/arm64/boot/dts/apple/t6050-k116s.dts | 38 --------------- .../boot/dts/apple/t6050-peripherals.dtsi | 27 ++++++++--- 5 files changed, 21 insertions(+), 152 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi index 4df0789d90beb9..cc176808c8c25e 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-display.dtsi @@ -16,7 +16,6 @@ */ &dcpext1 { - apple,dcp-index = <2>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; /* @@ -88,7 +87,6 @@ }; &dcpext2 { - apple,dcp-index = <3>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; apple,typec-dptx-phys = <2 1 0>; @@ -145,7 +143,6 @@ }; &dcpext3 { - apple,dcp-index = <4>; apple,connector-type = "USB-C"; apple,dptx-die = <0>; }; @@ -272,19 +269,6 @@ }; }; -/* Scanout and PIODMA share the first register window, as on dispext0 */ -&dispext1_dart { - reg = <0x3 0x92300000 0x0 0xc000>; -}; - -&dispext2_dart { - reg = <0x3 0x02300000 0x0 0xc000>; -}; - -&dispext3_dart { - reg = <0x3 0x06300000 0x0 0xc000>; -}; - &atc2_xbar { status = "okay"; }; diff --git a/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi b/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi index 641f56817039ce..5b8a5e3862ff0a 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j714s-gpu-panel.dtsi @@ -90,50 +90,6 @@ }; }; -/* - * The four external display engines (dcpext0..3): the loader hands each over - * when its checks pass, else leaves it disabled. t6050-j714s-display.dtsi - * describes their routes. - */ - -/* The ADT lists no clocks for the external engines (clock-ids = []) */ -&dcpext1 { - apple,clock-ids; -}; - -&dcpext2 { - apple,clock-ids; -}; - -&dcpext3 { - apple,clock-ids; -}; - -/* ADT dart-dcpextN and dart-dispextN: vm-base 1 TiB, vm-size 3 TiB, as dcpext0's */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - /* The inventory ASC nodes; the mailboxes below describe the same windows. */ /delete-node/ &gfx_asc; /delete-node/ &gfx1_asc; diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi index 3c8748edbe335a..297f43cf219fc0 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-j716c-display.dtsi @@ -1,54 +1,6 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* J716c external display processors and USB4 display routing. */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x92300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext1 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x30000>; - apple,dcp-index = <2>; - apple,clock-ids; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x02300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x34000>; - apple,dcp-index = <3>; - apple,clock-ids; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - /* Scanout and PIODMA share the first register window. */ - reg = <0x3 0x06300000 0x0 0xc000>; - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3 { - apple,bw-scratch = <&dcpext0_pmc 0 5 0x38000>; - apple,dcp-index = <4>; - apple,clock-ids; -}; - &atc2_phy { reg = <0x3 0x83000000 0x0 0x2c000>, <0x3 0x82a90000 0x0 0x4000>, diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index f55944c0c83179..9a6ea291ac2d6c 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -435,44 +435,6 @@ }; }; -/* The ADT lists no clocks for the external engines (clock-ids = []) */ -&dcpext1 { - apple,clock-ids; -}; - -&dcpext2 { - apple,clock-ids; -}; - -&dcpext3 { - apple,clock-ids; -}; - -/* ADT dart-dcpextN and dart-dispextN: vm-base 1 TiB, vm-size 3 TiB */ -&dcpext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext1_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext2_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcpext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dispext3_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - /* * The trackpad's AFE reset. The ADT names the SMC pcIO template (0x10000, * 0x11c0000), the same line as SMC GPIO gp1c, active low, which gpio-macsmc diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index 54e905c4915a03..c7a6178d27371f 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -2855,6 +2855,9 @@ mboxes = <&dcpext1_mbox>; mbox-names = "mbox"; iommus = <&dcpext1_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x30000>; + apple,dcp-index = <2>; + apple,clock-ids; status = "disabled"; piodma { @@ -2867,15 +2870,17 @@ reg = <0x3 0x92340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext1_dart: iommu@392300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x92300000 0x0 0xc000>, - <0x3 0x92314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x92300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; @@ -2951,6 +2956,9 @@ mboxes = <&dcpext2_mbox>; mbox-names = "mbox"; iommus = <&dcpext2_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x34000>; + apple,dcp-index = <3>; + apple,clock-ids; status = "disabled"; piodma { @@ -2963,15 +2971,17 @@ reg = <0x3 0x2340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext2_dart: iommu@302300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x2300000 0x0 0xc000>, - <0x3 0x2314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x2300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; @@ -3047,6 +3057,9 @@ mboxes = <&dcpext3_mbox>; mbox-names = "mbox"; iommus = <&dcpext3_dart 23>; + apple,bw-scratch = <&dcpext0_pmc 0 5 0x38000>; + apple,dcp-index = <4>; + apple,clock-ids; status = "disabled"; piodma { @@ -3059,15 +3072,17 @@ reg = <0x3 0x6340000 0x0 0x20000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; dispext3_dart: iommu@306300000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; - reg = <0x3 0x6300000 0x0 0xc000>, - <0x3 0x6314000 0x0 0x4000>; + /* Scanout and PIODMA share the first register window, as on dart_dispext0 */ + reg = <0x3 0x6300000 0x0 0xc000>; interrupts = ; #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x300 0x0>; status = "disabled"; }; From 064c3c65cd3e322ed4d5baac5c56678a2704bb39 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Tue, 24 Nov 2026 17:38:52 -0800 Subject: [PATCH 1178/1514] arm64: dts: apple: t6050-j775d: describe dcpext1-3 for Aura Type-C routes Describe the remaining die-0 external display engines (dcpext1..3) on the J775D with connector type "USB-C" and an empty typec-routes container, keeping dcpext0's static route on rear port 3 intact until a route-writing Aura ships. Move hpm3's USB4 router endpoint from port@2 to port@3 so port@2 stays free for DisplayPort (apple,dcp-typec-routes.yaml). Under published Aura (without the route writer), Aura hands dcpext1..3 off, adds dispext1..3_dart to display-subsystem's iommus and leaves typec-routes empty; Linux probes them cleanly with no Type-C routes while dcpext0 continues to drive rear port 3. Under route-writing Aura, Aura populates routes on rear ports 2 and 4 for dcpext1..3 (skipping port 3 while dcpext0's static unnumbered endpoint occupies hpm2 port@2) and enables their PHYs, crossbars and PD controllers. Signed-off-by: Jeff Queisser --- arch/arm64/boot/dts/apple/t6050-j775d.dts | 42 +++++++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index 2f928a1584e799..0b9d36ff1ac610 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -440,9 +440,13 @@ }; }; - /* The USB4 router (usb4_3_acio), the PD driver's thunderbolt-switch */ - port@2 { - reg = <2>; + /* + * The USB4 router (usb4_3_acio), the PD driver's + * thunderbolt-switch; port@2 is reserved for DisplayPort + * (apple,dcp-typec-routes.yaml). + */ + port@3 { + reg = <3>; hpm3_tbt: endpoint { remote-endpoint = <&usb4_3_ep>; }; @@ -662,4 +666,36 @@ #define T6050_J775D #include "t6050-peripherals.dtsi" +/* + * The other three die-0 external display engines (dcpext1..3). The shared + * properties live in t6050-peripherals.dtsi; each empty typec-routes container + * asks the boot loader to write the engine's USB-C display routes from the ADT. + */ +&dcpext1 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + +&dcpext2 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + +&dcpext3 { + apple,connector-type = "USB-C"; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + }; +}; + #include "t6050-j775d-gpu.dtsi" From 4ad71b88134de20ae0aefa1fe9f6ce3bfd209b06 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 04:16:06 +0300 Subject: [PATCH 1179/1514] iommu/apple-dart: wait out stalled display invalidates on locked DARTs On the MacBook Air 15" M5 (J815) the internal display's DART logs apple-dart 286300000.iommu: TLB command 0x1 for stream 0 timed out (0x8700e100) when the compositor starts and when the display powers back on, 0 to 32 lines per boot, and kwin's framebuffer import fails at the same instant: kwin_wayland: drmPrimeFDToHandle failed: Invalid argument kwin_wayland: Failed to create framebuffer: Invalid argument That is the J700 stall that 911de8e40402 ("iommu/apple-dart: wait out stalled J700 display invalidates") waits out: a FLUSH_SID by range (V2, RANGE, STT) of the display subsystem's stream 0, still busy after 2 ms. The wait was gated on the reserved firmware table handoff, which J700's loader sets up. J815's loader leaves disp0 locked without the handoff, so the same stall still fails there after 2 ms. What the wait relies on is the DART being one the display subsystem scans out through, and taking range invalidates, which only locked DARTs get. Decide display_scanout from the lock instead of the handoff; every handed-off DART is locked, so J700 keeps the wait. The DCP firmware DARTs, other devices' DARTs and DARTs with sleep lists or a CTC flush still fail after the short wait. The host test's no-handoff case now expects the wait, and the mutation that drops the scan-out check is renamed every-dart. Signed-off-by: Nick --- drivers/iommu/apple-dart.c | 35 ++++++++++++----------- tools/asahi/apple-dart-tlb-stall-tests.py | 28 ++++++++++-------- tools/asahi/run-host-tests.py | 4 +-- 3 files changed, 37 insertions(+), 30 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 2834878283a526..a6b635e30f34c6 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -462,7 +462,7 @@ struct apple_dart { bool commands_gated; /* TLB commands written, counted under the lock: see apple_dart_t8110_tlb_wait(). */ unsigned long tlb_commands; - /* A handed-off DART a display subsystem scans out through: apple_dart_display_scanout(). */ + /* A locked DART a display subsystem scans out through: apple_dart_display_scanout(). */ bool display_scanout; /* * A real sleep took the ISP host streams' registers: the next runtime resume, its @@ -1081,9 +1081,10 @@ static bool apple_dart_fw_handoff_enabled(const struct apple_dart *dart) * Whether an available display subsystem, the component master the DRM driver * binds and the loader walks for the scan-out DARTs it hands off, lists a * stream of @np in its iommus: the display pipe scans out through this DART. - * On J700 that is disp0 and dispext0. The DCP and DCPEXT firmware DARTs are - * named only by their coprocessors, and a PCIe device such as the Wi-Fi - * reaches its DART through its host bridge's iommu-map. + * On J700 that is disp0 and dispext0, on J815 disp0, dispext0 and dispext1. + * The DCP and DCPEXT firmware DARTs are named only by their coprocessors, and + * a PCIe device such as the Wi-Fi reaches its DART through its host bridge's + * iommu-map. */ static bool apple_dart_display_scanout(struct device_node *np) { @@ -1782,16 +1783,17 @@ static bool apple_dart_t8110_tlb_settled(struct apple_dart *dart, * held: before a command (@issued 0) until it is idle, after one until * command @issued finished. * - * On J700 the boot loader hands the display DARTs' roots off (fw_handoff). - * There a range invalidate of the internal display's stream 0 can stay busy - * well past DART_T8110_FLUSH_BUSY_TIMEOUT while the display pipe changes - * what it scans out (screen locker, panel power-off, after a resume), - * reading 0x8700e100, and it finishes on its own: the next commands work. - * Giving up fails the mapping of a framebuffer the compositor imports, and - * returns from an unmap while the TLB can still translate to the pages its - * caller frees next. So keep waiting on the DARTs the display subsystem - * scans out through (display_scanout: disp0 and dispext0), not on the - * handed-off DCP firmware DARTs or any other device's DART, for up to + * On J700 (whose boot loader hands the display DARTs' roots off) and on + * J815 (locked, no handoff) a range invalidate of the internal display's + * stream 0 can stay busy well past DART_T8110_FLUSH_BUSY_TIMEOUT while the + * display pipe changes what it scans out (compositor start, screen locker, + * panel power-off, after a resume), reading 0x8700e100, and it finishes on + * its own: the next commands work. Giving up fails the mapping of a + * framebuffer the compositor imports, and returns from an unmap while the + * TLB can still translate to the pages its caller frees next. So keep + * waiting on the locked DARTs the display subsystem scans out through + * (display_scanout: disp0, and dispext0 when the loader locked it), not on + * the DCP firmware DARTs or any other device's DART, for up to * DART_T8110_FLUSH_STALL_TIMEOUT more, without the lock and with interrupts * as the caller had them. Every command here waits for an idle engine * before it is written, so the engine needs no lock meanwhile (the @@ -1814,7 +1816,7 @@ static int apple_dart_t8110_tlb_wait(struct apple_dart *dart, unsigned long *fla !(*status & DART_T8110_TLB_CMD_BUSY), 1, DART_T8110_FLUSH_BUSY_TIMEOUT, false, dart, DART_T8110_TLB_CMD); - if (!ret || !range || !dart->fw_handoff || !dart->display_scanout || + if (!ret || !range || !dart->display_scanout || dart->ctc_flush || dart->sleep_restore.count) return ret; @@ -6261,7 +6263,8 @@ static int apple_dart_probe(struct platform_device *pdev) &dart->sleep_restore_late); /* Reserved table-page lifetime requires the matched three-level loader. */ dart->fw_handoff = apple_dart_fw_handoff_enabled(dart); - dart->display_scanout = dart->fw_handoff && apple_dart_display_scanout(dev->of_node); + /* Only a locked DART takes the range invalidates apple_dart_t8110_tlb_wait() waits out. */ + dart->display_scanout = dart->locked && apple_dart_display_scanout(dev->of_node); /* * Preserve our retained-root path when no reserved-table handoff exists. * T6050's boot loader leaves every display DART locked on four-level diff --git a/tools/asahi/apple-dart-tlb-stall-tests.py b/tools/asahi/apple-dart-tlb-stall-tests.py index cc6e3582c07d5a..706ad2ab7e83d6 100644 --- a/tools/asahi/apple-dart-tlb-stall-tests.py +++ b/tools/asahi/apple-dart-tlb-stall-tests.py @@ -34,7 +34,7 @@ 'DART_T8110_FLUSH_STALL_TIMEOUT', 'DART_T8110_FLUSH_STALL_POLL', 'DART_T8110_TLB_CMD_STREAM', 'DART_T8110_CTC_FLUSH') OPTIONAL_DEFINES = {'DART_T8110_FLUSH_STALL_TIMEOUT', 'DART_T8110_FLUSH_STALL_POLL'} -CASES = ('fast', 'stall-after', 'stall-before', 'stuck', 'not-handoff', 'not-scanout', +CASES = ('fast', 'stall-after', 'stall-before', 'stuck', 'no-handoff', 'not-scanout', 'not-range', 'ctc-flush', 'sleep-listed', 'superseded', 'gated', 'two-streams') J700 = 'arch/arm64/boot/dts/apple/t8140-j700.dts' # What the J700 display subsystem scans out through: disp0 and dispext0. @@ -342,18 +342,22 @@ assert(now >= DART_T8110_FLUSH_STALL_TIMEOUT); assert(now <= DART_T8110_FLUSH_STALL_TIMEOUT + 2 * DART_T8110_FLUSH_BUSY_TIMEOUT + 100); assert(!dart.lock); - } else if (!strcmp(c, "not-handoff")) { - /* Other DARTs keep failing after the short wait, lock held throughout. */ + } else if (!strcmp(c, "no-handoff")) { + /* + * The J815 display: locked by the loader without the root handoff, + * the same 40 ms stall is waited out too. + */ reset(false); durations[0] = 40000; ndurations = 1; - assert(range() == -ETIMEDOUT); - assert(commands == 1 && errors_logged == 1 && lock_drops == 1); - assert(now <= DART_T8110_FLUSH_BUSY_TIMEOUT + 10); + assert(!range()); + assert(commands == 1 && !errors_logged && infos_logged == 1); + assert(info_us >= 38000 && info_us <= 41000); + check_range_command(0, 0); } else if (!strcmp(c, "not-scanout")) { /* - * A handed-off DART no display subsystem scans out through, such as - * the DCP's own: the same stall fails after the short wait, lock held. + * A DART no display subsystem scans out through, such as the DCP's + * own: the same stall fails after the short wait, lock held. */ dart.display_scanout = false; durations[0] = 40000; @@ -583,8 +587,8 @@ def main(): parser.add_argument('--source', type=Path, help='an apple-dart.c to test (default: this tree)') parser.add_argument('--ref', help='test drivers/iommu/apple-dart.c of this revision instead') parser.add_argument('--case', action='append') - parser.add_argument('--mutation', choices=('every-handoff',), - help='every-handoff: wait on every handed-off DART, not just the scan-out ones') + parser.add_argument('--mutation', choices=('every-dart',), + help='every-dart: wait on every locked DART, not just the scan-out ones') parser.add_argument('--dtc', help="this kernel's built scripts/dtc/dtc: also check the J700 tree") args = parser.parse_args() if args.ref: @@ -592,11 +596,11 @@ def main(): args.ref + ':drivers/iommu/apple-dart.c'], text=True) else: text = (args.source or ROOT / 'drivers/iommu/apple-dart.c').read_text() - if args.mutation == 'every-handoff': + if args.mutation == 'every-dart': cut = ' !dart->display_scanout ||' if text.count(cut) != 1: # Not a kill: the harness counts a traceback as a broken run. - raise RuntimeError('every-handoff: no display_scanout check to remove') + raise RuntimeError('every-dart: no display_scanout check to remove') text = text.replace(cut, '') defines = [] diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7cb81bda543cf6..18ada0aa242660 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -142,11 +142,11 @@ def mutations(flag, names, base, expect=KILL): 'apple-dart-fw-harness-tests.py': [([], PASS)], 'apple-dart-range-tests.py': [([], PASS)], # 551b937502b5 gives up on a stalled J700 display invalidate after 2 ms; the - # every-handoff mutation waits it out on every handed-off DART, not just the display's. + # every-dart mutation waits it out on every locked DART, not just the display's. 'apple-dart-tlb-stall-tests.py': [(['--dtc', '{dtc}'], PASS), (['--ref', '551b937502b54b0d1eb250bba6d9442b3672a0fb'], KILL), - (['--dtc', '{dtc}', '--mutation', 'every-handoff'], + (['--dtc', '{dtc}', '--mutation', 'every-dart'], KILL)], 'apple-router-sleep-tests.py': [(out('--output'), PASS)], 'asahi-stats-raw-tests.py': [([], PASS)], From f8b2fd358bff6a7ae233412a45e2cb3daecf9133 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:10:47 -0500 Subject: [PATCH 1180/1514] arm64: dts: apple: share M3 Pro speaker amplifier wiring The J516s Apple device tree routes all six speaker fault interrupts to AP GPIO 195, and Linux registered all six handlers on that pin. This matches the J514s wiring. Share the fault and shutdown GPIO setup between the two M3 Pro boards. M3 Max uses AP GPIO 29 for speaker faults. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .../dts/apple/t6030-j514s-j516s-audio.dtsi | 32 +++++++++++++++++++ arch/arm64/boot/dts/apple/t6030-j514s.dts | 31 +----------------- arch/arm64/boot/dts/apple/t6030-j516s.dts | 31 +----------------- 3 files changed, 34 insertions(+), 60 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi diff --git a/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi b/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi new file mode 100644 index 00000000000000..a4dee6b04b1458 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6030-j514s-j516s-audio.dtsi @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* Speaker amplifier wiring shared by the 14- and 16-inch M3 Pro. */ + +&speaker_left_tweet { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_left_woof1 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_left_woof2 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_tweet { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_woof1 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; + +&speaker_right_woof2 { + shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; +}; diff --git a/arch/arm64/boot/dts/apple/t6030-j514s.dts b/arch/arm64/boot/dts/apple/t6030-j514s.dts index 4f5826b44e2080..006c1a077c43bd 100644 --- a/arch/arm64/boot/dts/apple/t6030-j514s.dts +++ b/arch/arm64/boot/dts/apple/t6030-j514s.dts @@ -11,6 +11,7 @@ #include "t6030.dtsi" #include "t603x-j514-j516.dtsi" +#include "t6030-j514s-j516s-audio.dtsi" #include "t603x-j514s-j516s-usb4.dtsi" #include "t603x-j514s-j516s-hdmi.dtsi" @@ -41,36 +42,6 @@ brcm,board-type = "apple,texa"; }; -&speaker_left_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 195 IRQ_TYPE_LEVEL_LOW>; -}; - &jack_codec { reset-gpios = <&pinctrl_nub 21 GPIO_ACTIVE_HIGH>; interrupts-extended = <&pinctrl_ap 196 IRQ_TYPE_LEVEL_LOW>; diff --git a/arch/arm64/boot/dts/apple/t6030-j516s.dts b/arch/arm64/boot/dts/apple/t6030-j516s.dts index d3fff6b103fde0..ae9e260c3da99b 100644 --- a/arch/arm64/boot/dts/apple/t6030-j516s.dts +++ b/arch/arm64/boot/dts/apple/t6030-j516s.dts @@ -11,6 +11,7 @@ #include "t6030.dtsi" #include "t603x-j514-j516.dtsi" +#include "t6030-j514s-j516s-audio.dtsi" #include "t603x-j514s-j516s-usb4.dtsi" #include "t603x-j514s-j516s-hdmi.dtsi" @@ -41,36 +42,6 @@ brcm,board-type = "apple,jura"; }; -&speaker_left_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_left_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_tweet { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof1 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - -&speaker_right_woof2 { - shutdown-gpios = <&pinctrl_ap 171 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 29 IRQ_TYPE_LEVEL_LOW>; -}; - &jack_codec { reset-gpios = <&pinctrl_nub 21 GPIO_ACTIVE_HIGH>; interrupts-extended = <&pinctrl_ap 196 IRQ_TYPE_LEVEL_LOW>; From 1c56f826e7ffe1a4b967b0348fd755519db0c249 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 13:11:39 +1100 Subject: [PATCH 1181/1514] CODEOWNERS: add Aurora Maintainers and fix the Omarchy Mac team name The file names @aurora-silicon/omarchy-m, but the team slug is omarchy-mac. GitHub reports every such line as an unknown owner, so an Omarchy Mac approval does not count as code-owner review. Name the team by its slug and add @aurora-silicon/aurora-maintainers wherever Omarchy Mac is listed: Aurora Maintainers review and merge with the same rights as Omarchy Mac. Signed-off-by: Ryan Murray --- .github/CODEOWNERS | 105 +++++++++++++++++++++++---------------------- 1 file changed, 53 insertions(+), 52 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e33416cfb51e4f..9c7b381540fb0d 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,83 +1,84 @@ # Code owners for aurora-silicon/linux. # -# Every PR is reviewed by Core or Omarchy Mac; an approval from either team -# counts everywhere. The '# area:' sections only route: they add the area's -# specialists to the review request and give the readiness bot its area: -# labels. Omarchy Mac is listed first where it reviews first (M1 to M3 -# platform). Later lines win, as in every CODEOWNERS file, so keep the team -# pair on every area line. +# Every PR is reviewed by Core, Omarchy Mac or Aurora Maintainers; an +# approval from any of the three teams counts everywhere. The '# area:' +# sections only route: they add the area's specialists to the review request +# and give the readiness bot its area: +# labels. Omarchy Mac and Aurora Maintainers are listed first where they +# review first (M1 to M3 platform). Later lines win, as in every CODEOWNERS +# file, so keep all three teams on every area line. # Routing and labels: https://github.com/aurora-silicon/agent-guidelines/blob/main/docs/MAINTAINER-HANDBOOK.md # Merge rules: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/merge-policy.md # Access tiers: https://github.com/aurora-silicon/agent-guidelines/blob/main/policy/access-tiers.md -* @aurora-silicon/core @aurora-silicon/omarchy-m +* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: platform -/arch/arm64/boot/dts/apple/t8103* @aurora-silicon/omarchy-m @aurora-silicon/core -/arch/arm64/boot/dts/apple/t600* @aurora-silicon/omarchy-m @aurora-silicon/core -/arch/arm64/boot/dts/apple/t8112* @aurora-silicon/omarchy-m @aurora-silicon/core -/arch/arm64/boot/dts/apple/t602* @aurora-silicon/omarchy-m @aurora-silicon/core -/arch/arm64/boot/dts/apple/t8122* @aurora-silicon/omarchy-m @aurora-silicon/core -/arch/arm64/boot/dts/apple/t603* @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/soc/apple/ @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/iommu/apple-dart.c @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/nvme/host/apple.c @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/spmi/ @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/watchdog/apple_wdt.c @aurora-silicon/omarchy-m @aurora-silicon/core -/drivers/gpio/gpio-macsmc.c @aurora-silicon/omarchy-m @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8103* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t600* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8112* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t602* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t8122* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/arch/arm64/boot/dts/apple/t603* @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/soc/apple/ @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/iommu/apple-dart.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/nvme/host/apple.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/spmi/ @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/watchdog/apple_wdt.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core +/drivers/gpio/gpio-macsmc.c @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @aurora-silicon/core # area: bringup -/arch/arm64/boot/dts/apple/t8132* @aurora-silicon/core @aurora-silicon/omarchy-m -/arch/arm64/boot/dts/apple/t604* @aurora-silicon/core @aurora-silicon/omarchy-m -/arch/arm64/boot/dts/apple/t8140* @aurora-silicon/core @aurora-silicon/omarchy-m -/arch/arm64/boot/dts/apple/t8142* @aurora-silicon/core @aurora-silicon/omarchy-m -/arch/arm64/boot/dts/apple/t8152* @aurora-silicon/core @aurora-silicon/omarchy-m -/arch/arm64/boot/dts/apple/t6050* @aurora-silicon/core @aurora-silicon/omarchy-m +/arch/arm64/boot/dts/apple/t8132* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t604* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8140* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8142* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t8152* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/arch/arm64/boot/dts/apple/t6050* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: gpu -/drivers/gpu/drm/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr -/include/uapi/drm/asahi_drm.h @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr -/tools/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-m @DjDeveloperr +/drivers/gpu/drm/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr +/include/uapi/drm/asahi_drm.h @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr +/tools/asahi/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers @DjDeveloperr # area: display -/drivers/gpu/drm/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/gpu/drm/tiny/appletbdrm.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/gpu/drm/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/gpu/drm/tiny/appletbdrm.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: audio -/sound/soc/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m -/sound/soc/codecs/tas2764* @aurora-silicon/core @aurora-silicon/omarchy-m -/sound/soc/codecs/tas2770* @aurora-silicon/core @aurora-silicon/omarchy-m -/sound/soc/codecs/cs42l83* @aurora-silicon/core @aurora-silicon/omarchy-m -/sound/soc/codecs/cs42l84* @aurora-silicon/core @aurora-silicon/omarchy-m +/sound/soc/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/tas2764* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/tas2770* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/cs42l83* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/sound/soc/codecs/cs42l84* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: power -/drivers/pmdomain/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/cpufreq/apple-soc-cpufreq.c @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/mfd/macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/power/supply/macsmc-power* @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/rtc/rtc-macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/hwmon/macsmc-hwmon.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/pmdomain/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/cpufreq/apple-soc-cpufreq.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/mfd/macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/power/supply/macsmc-power* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/rtc/rtc-macsmc.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/hwmon/macsmc-hwmon.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: usb -/drivers/usb/typec/tipd/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/phy/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/thunderbolt/apple* @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/usb/typec/tipd/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/phy/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/thunderbolt/apple* @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: media -/drivers/media/platform/apple/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/accel/ane/ @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/media/platform/apple/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/accel/ane/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: wireless -/drivers/net/wireless/broadcom/brcm80211/ @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/bluetooth/hci_bcm4377.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/net/wireless/broadcom/brcm80211/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/bluetooth/hci_bcm4377.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: input -/drivers/input/touchscreen/apple_z2.c @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/input/misc/macsmc-input.c @aurora-silicon/core @aurora-silicon/omarchy-m -/drivers/hid/hid-apple.c @aurora-silicon/core @aurora-silicon/omarchy-m +/drivers/input/touchscreen/apple_z2.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/input/misc/macsmc-input.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers +/drivers/hid/hid-apple.c @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # area: rust -/rust/ @aurora-silicon/core @aurora-silicon/omarchy-m +/rust/ @aurora-silicon/core @aurora-silicon/omarchy-mac @aurora-silicon/aurora-maintainers # Files whose change affects every user or the release process: an Owner # reviews them. Keep these last so they win. From 6830b3df58c1f4abc6f2da9605bca47c15cc5a8d Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:12:53 -0500 Subject: [PATCH 1182/1514] drm/asahi: guard crate::g16::Gpu check with CONFIG_DRM_ASAHI_G16 Commit 703cbfb8ec12 (part of #3043) added `gpu.as_any().is::()` in `drivers/gpu/drm/asahi/file.rs:1895` without a `#[cfg(CONFIG_DRM_ASAHI_G16)]` guard, breaking builds where `CONFIG_DRM_ASAHI_G16=n` (such as KUnit configs). Guard the `crate::g16::Gpu` type check with `#[cfg(CONFIG_DRM_ASAHI_G16)]` (evaluating to `false` when disabled), matching all other `crate::g16` references in `asahi_core.rs`, `driver.rs`, and `fwid.rs`. Fixes: 703cbfb8ec12 ("drm/asahi: g16: use cumulative output scopes on G16") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index be78c01b39aff5..cdd367f64b638a 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -1887,12 +1887,22 @@ impl File { } else { None }; + let cumulative_sync = gpu.as_any().is::() || { + #[cfg(CONFIG_DRM_ASAHI_G16)] + { + gpu.as_any().is::() + } + #[cfg(not(CONFIG_DRM_ASAHI_G16))] + { + false + } + }; let syncs = match SyncItem::parse_array( file, data.syncs, data.in_sync_count, data.out_sync_count, - gpu.as_any().is::() || gpu.as_any().is::(), + cumulative_sync, ) { Ok(syncs) => syncs, Err(e) => { From fad5d04a1fa8aecff5cd45e1910b7aa88e9f1761 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 17:18:02 -0300 Subject: [PATCH 1183/1514] drm/asahi: keep a submission's syncs and command copy off contiguous pages The submit ioctl copies the command buffer from userspace into a KVec, and parses the in and out syncs into another one. Userspace sets both sizes: in_sync_count and out_sync_count are u32s with no limit of their own, and only some GPUs bound the command buffer before it is copied (G17's max_cmdbuf_size() is the default, usize::MAX). kmalloc() needs both physically contiguous, so a large submission asks for a high-order block on every ioctl, which without compaction may end in the OOM killer instead of failing. Nothing needs them contiguous: only the ioctl reads them, and every generation's submit consumes the syncs before it returns. Make both KVVecs, so a large one falls back to vmalloc() while small ones keep their kmalloc memory, and charge them to the caller's memory cgroup (GFP_KERNEL_ACCOUNT). The sync list's type changes to KVVec in every generation's submit; nothing else about it does. The asahi-m4 submit-restart selftest, which builds that code on the host, gets the matching KVVec alias. Signed-off-by: Jonathan Goyvaerts Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/file.rs | 20 ++++++++++--------- drivers/gpu/drm/asahi/g15/fence.rs | 4 ++-- drivers/gpu/drm/asahi/g15/queue.rs | 2 +- drivers/gpu/drm/asahi/g16/fence.rs | 4 ++-- drivers/gpu/drm/asahi/g16/queue.rs | 2 +- drivers/gpu/drm/asahi/g17/fence.rs | 4 ++-- drivers/gpu/drm/asahi/g17/queue/mod.rs | 2 +- drivers/gpu/drm/asahi/g18/drm.rs | 4 ++-- drivers/gpu/drm/asahi/m3/m3_submit.rs | 11 ++++++++-- drivers/gpu/drm/asahi/m5/drm.rs | 4 ++-- drivers/gpu/drm/asahi/queue/mod.rs | 4 ++-- .../gpu/asahi-m4/test-fence-signalling.py | 2 +- .../gpu/asahi-m4/test-submit-restart.py | 2 +- 13 files changed, 37 insertions(+), 28 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index be78c01b39aff5..abc3bd44263844 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -291,13 +291,15 @@ impl SyncItem { in_count: u32, out_count: u32, allow_cumulative: bool, - ) -> Result> { + ) -> Result> { let count = in_count.checked_add(out_count).ok_or(EOVERFLOW)?; const STRIDE: usize = core::mem::size_of::(); const CHUNK: usize = 8; let size = STRIDE.checked_mul(count as usize).ok_or(EOVERFLOW)?; - let mut vec = KVec::with_capacity(count as usize, GFP_KERNEL)?; + // Userspace sets the count. Charge the allocation to the caller and + // allow noncontiguous backing pages. + let mut vec = KVVec::with_capacity(count as usize, GFP_KERNEL_ACCOUNT)?; let mut anchor = None; // Read each record once in small stack chunks so validation and use see the @@ -330,7 +332,7 @@ impl SyncItem { } vec.push( Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; } base += chunk as u32; @@ -364,7 +366,7 @@ pub(crate) struct TableQueue { queue: KBox, /// Reusable staging buffer for `SUBMIT` command buffers, avoiding per-submit heap /// allocations and keeping large command buffers off the kernel stack. - cmdbuf: KVec, + cmdbuf: KVVec, _share: Option, } @@ -374,13 +376,13 @@ impl TableQueue { /// Takes the cached command-buffer staging allocation so userspace copies run outside the /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). - fn take_cmdbuf(&mut self) -> KVec { + fn take_cmdbuf(&mut self) -> KVVec { core::mem::take(&mut self.cmdbuf) } /// Returns a cleared command-buffer allocation to the per-queue cache when within the /// reuse capacity cap; oversized buffers are dropped. - fn return_cmdbuf(&mut self, mut buf: KVec) { + fn return_cmdbuf(&mut self, mut buf: KVVec) { buf.clear(); if buf.capacity() > 0 && buf.capacity() <= Self::REUSE_CMDBUF_CAP @@ -391,11 +393,11 @@ impl TableQueue { } } -fn copy_cmdbuf_from_user(buf: &mut KVec, addr: u64, size: usize) -> Result { +fn copy_cmdbuf_from_user(buf: &mut KVVec, addr: u64, size: usize) -> Result { buf.clear(); UserSlice::new(UserPtr::from_addr(addr as usize), size) .reader() - .read_all(buf, GFP_KERNEL) + .read_all(buf, GFP_KERNEL_ACCOUNT) } impl Deref for TableQueue { @@ -1799,7 +1801,7 @@ impl File { resv.fill(Arc::pin_init( new_mutex!(TableQueue { queue, - cmdbuf: KVec::new(), + cmdbuf: KVVec::new(), _share: share, }), GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/g15/fence.rs b/drivers/gpu/drm/asahi/g15/fence.rs index bb857642280702..55a85472a794de 100644 --- a/drivers/gpu/drm/asahi/g15/fence.rs +++ b/drivers/gpu/drm/asahi/g15/fence.rs @@ -179,12 +179,12 @@ fn install(outputs: impl Iterator, fence: &Fence) { /// accepted, a signalled error fence when the submission is refused (the shared `file.rs` /// contract of `tracked_submission`). pub(crate) struct Syncs { - syncs: KVec, + syncs: KVVec, input_count: usize, } impl Syncs { - pub(crate) fn new(syncs: KVec, input_count: usize) -> Self { + pub(crate) fn new(syncs: KVVec, input_count: usize) -> Self { Self { syncs, input_count } } diff --git a/drivers/gpu/drm/asahi/g15/queue.rs b/drivers/gpu/drm/asahi/g15/queue.rs index 03a8f46c8a0fce..3bdebb7995e44f 100644 --- a/drivers/gpu/drm/asahi/g15/queue.rs +++ b/drivers/gpu/drm/asahi/g15/queue.rs @@ -212,7 +212,7 @@ impl crate::queue::Queue for Queue { &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 75ca2b6768c81d..3d7e57f4744c32 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -562,13 +562,13 @@ fn install(outputs: impl Iterator, fence: &Fence) { /// contract of `tracked_submission`). Cumulative output bundles reuse the shared /// `g17::sync_output::SignalBundle` scope chain. pub(crate) struct Syncs { - syncs: KVec, + syncs: KVVec, input_count: usize, cumulative: Option, } impl Syncs { - pub(crate) fn new(mut syncs: KVec, input_count: usize) -> Self { + pub(crate) fn new(mut syncs: KVVec, input_count: usize) -> Self { let cumulative = syncs.iter_mut().find_map(|sync| sync.cumulative.take()); Self { syncs, diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 28332f8de5e740..d64d57125b141b 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -372,7 +372,7 @@ impl crate::queue::Queue for Queue { &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index 04df5e4aa9fd64..1eaafeb4438529 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -526,7 +526,7 @@ fn install(outputs: impl Iterator, fence: &Fence) { pub(crate) struct Outputs { fallback: Option>, - syncs: KVec, + syncs: KVVec, input_count: usize, submission: Option, result: Result, @@ -535,7 +535,7 @@ pub(crate) struct Outputs { impl Outputs { pub(crate) fn new( contexts: &FenceContexts, - mut syncs: KVec, + mut syncs: KVVec, input_count: usize, allocation_failure: &Fence, ) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 1c64f3839ae22d..989907521d4884 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -519,7 +519,7 @@ impl crate::queue::Queue for Queue { &mut self, _reg_data: &crate::driver::AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, input_count: usize, bytes: &[u8], objects: Pin<&xarray::XArray>>, diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index 14a726b24fc4cc..f8c4e70574d517 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -286,7 +286,7 @@ impl FenceOps for G18SubmissionFence { /// Dropped unaccepted, it signals the fence with `result` and installs it. struct OutputPublication { fence: Option>, - syncs: KVec, + syncs: KVVec, input_count: usize, result: Result, } @@ -707,7 +707,7 @@ impl queue::Queue for G18Queue { /// userspace nothing to wait on (Mesa's G18G split compute prepass reads /// GPU results after such submissions). fn submit(&mut self, _reg_data: &AsahiRegData<'_>, submission_id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>) -> Result { if in_sync_count > syncs.len() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 92b82e1c8097b6..cb45a2cde3c542 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -363,8 +363,15 @@ impl Queue { } } impl queue::Queue for Queue { - fn submit(&mut self,_reg_data:&crate::driver::AsahiRegData<'_>,_id:u64,mut syncs:KVec,in_sync_count:usize, - raw:&[u8],objects:Pin<&xarray::XArray>>)->Result { + fn submit( + &mut self, + _reg_data: &crate::driver::AsahiRegData<'_>, + _id: u64, + mut syncs: KVVec, + in_sync_count: usize, + raw: &[u8], + objects: Pin<&xarray::XArray>>, + ) -> Result { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs index 6ab2108d8813b2..0eb1e8a8ded4ba 100644 --- a/drivers/gpu/drm/asahi/m5/drm.rs +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -196,7 +196,7 @@ impl FenceOps for M5SubmissionFence { /// allocation failure after userspace has already supplied its wait targets. struct OutputPublication { fence: UserFence, - syncs: KVec, + syncs: KVVec, input_count: usize, result: Result, } @@ -237,7 +237,7 @@ struct M5Queue { impl queue::Queue for M5Queue { fn submit(&mut self, _reg_data: &AsahiRegData<'_>, _submission_id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], _objects: Pin<&xarray::XArray>>) -> Result { if in_sync_count > syncs.len() { return Err(EINVAL); } diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 94405e88c6b0dd..af4cf98f600f30 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -197,7 +197,7 @@ pub(crate) trait Queue: Send + Sync { &mut self, reg_data: &AsahiRegData<'_>, id: u64, - syncs: KVec, + syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, @@ -1010,7 +1010,7 @@ impl Queue for Queue::ver { &mut self, reg_data: &AsahiRegData<'drm>, id: u64, - mut syncs: KVec, + mut syncs: KVVec, in_sync_count: usize, cmdbuf_raw: &[u8], objects: Pin<&xarray::XArray>>, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 0843277bc93688..6f00c99f20e250 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -376,7 +376,7 @@ def extract_function(text, name): pub(crate) cumulative: Option, } - pub(crate) type KVec = Vec; + pub(crate) type KVVec = Vec; fn install(outputs: impl Iterator, fence: &Fence) { for sync in outputs { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py index adbbf7cdaa39f6..8bbd90ad88e2f8 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-submit-restart.py @@ -11,7 +11,7 @@ #![allow(dead_code,unused_variables)] use std::pin::Pin;use std::sync::atomic::{AtomicU32,Ordering}; type Result = std::result::Result;const ERESTARTSYS:i32=512;const EBUSY:i32=16; -type KVec=Vec;type KBox=Box; +type KVec=Vec;type KVVec=Vec;type KBox=Box; mod xarray{pub struct XArray(pub T);} mod file{pub struct SyncItem;pub struct Object;} mod driver{pub struct AsahiRegData<'a>(pub &'a ());} From 58c130777d7bc9339eed3f4f11dd94b3d16efe8b Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 23 Nov 2026 19:18:10 -0300 Subject: [PATCH 1184/1514] drm/asahi: g15: refuse an oversized command buffer before copying it G15 accepts a command stream of at most MAX_CMDBUF (4 MiB), but checks it only in check_stream(), after the submit ioctl has copied the whole cmdbuf_size from userspace. Its max_cmdbuf_size() was the default, usize::MAX, so a submit of up to 4 GiB was first copied into the kernel and only then refused. Return MAX_CMDBUF from max_cmdbuf_size(), as G16 does, so the ioctl refuses a longer stream with E2BIG before it allocates anything. A stream that check_stream() accepts is unaffected; a longer one now fails with E2BIG instead of EINVAL. Signed-off-by: Jonathan Goyvaerts Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g15/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 4cb221fb0a5df6..d5cad14a50411b 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -578,6 +578,10 @@ impl Firmware { } impl gpu::Gpu for Gpu { + fn max_cmdbuf_size(&self) -> usize { + command::MAX_CMDBUF + } + fn stats_snapshot(&self) -> Option> { None } From 4ed142456f6cb62d27c0f29a47c7e92b6b76ca33 Mon Sep 17 00:00:00 2001 From: Nikita Konkov <95355711+javanoo6@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:11:51 +0300 Subject: [PATCH 1185/1514] drm/asahi: g15: pin J514S cd05 firmware TEXT The J514S 14.7 boot chain can load a T6030 firmware build whose full TEXT digest is not in the admission table. Probe refuses it and no GPU render node is created. Desktop use with the explicit prefix override reaches firmware READY and reduces Hyprland CPU use from several cores to single-digit percentages. Pin the complete measured digest only for J514S, with its segment sizes and marker, rather than requiring a persistent bring-up override. Exercise the production firmware table and exact lookup with the override disabled. Reject other boards, altered digest suffixes, sizes and markers. Link: https://github.com/omacom/linux-aurora/issues/247 Signed-off-by: Nikita Konkov <95355711+javanoo6@users.noreply.github.com> Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g15/hw.rs | 15 ++++++++++ tools/asahi/g15-maintained-handoff-tests.py | 31 +++++++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs index b2110883102104..36310376e12b5c 100644 --- a/drivers/gpu/drm/asahi/g15/hw.rs +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -175,6 +175,21 @@ pub(crate) mod t6030 { 0xe7, 0x9b, 0xb9, 0xb0, 0x22, 0x09, 0xdb, 0x53, ], }, + // J514S firmware measured on the 14.7 boot chain; desktop rendering + // was verified with the bring-up prefix override (issue #247). + FirmwareBuild { + name: "J514S cd05 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j514s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0xcd, 0x05, 0xaf, 0x6a, 0x82, 0x8b, 0x52, 0xe4, + 0xc2, 0xfe, 0xd2, 0x00, 0x86, 0xd3, 0xd1, 0x8a, + 0x7d, 0xb4, 0x2e, 0x03, 0xa8, 0xfd, 0x6f, 0x83, + 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, + ], + }, ], machine: kernel::c_str!("apple,t6030"), platform: super::Platform::AdtWithPmp, diff --git a/tools/asahi/g15-maintained-handoff-tests.py b/tools/asahi/g15-maintained-handoff-tests.py index fdafd799645cb7..e0fb4438de3793 100644 --- a/tools/asahi/g15-maintained-handoff-tests.py +++ b/tools/asahi/g15-maintained-handoff-tests.py @@ -137,12 +137,38 @@ def item(s, marker): OWNER_CALLS.set(0); let bytes = fixture(kind); assert!(parse(&dev, &Adt { data: &bytes }).is_err()); assert_eq!(OWNER_CALLS.get(), 0); } - assert_eq!(BUILDS.len(), 3, "maintained B0 firmware row must not require an absent profile symbol"); + assert_eq!(BUILDS.len(), 4, "maintained B0 firmware row must not require an absent profile symbol"); for (row, machine) in [(1, &b"apple,j516s"[..]), (2, &b"apple,j514s"[..])] { assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); assert_eq!(BUILDS[row].text_sha256, [0xda,0x26,0xec,0xca,0xb1,0xf8,0x59,0x8d,0xa8,0x0c,0x85,0x5e,0xca,0x91,0x65,0x20,0x40,0x6d,0x1d,0x06,0x70,0xf1,0xd4,0x70,0xe7,0x9b,0xb9,0xb0,0x22,0x09,0xdb,0x53]); } + // Issue #247: this J514S build must pin without the bring-up override. + use identity::lookup::{Measured, Verdict, verdict}; + let measured = Measured { + text_size: 0x5c000, data_size: 0x114000, marker: 0x58e88, + sha256: [0xcd,0x05,0xaf,0x6a,0x82,0x8b,0x52,0xe4, + 0xc2,0xfe,0xd2,0x00,0x86,0xd3,0xd1,0x8a, + 0x7d,0xb4,0x2e,0x03,0xa8,0xfd,0x6f,0x83, + 0x54,0xf9,0xf0,0x6e,0x0a,0x61,0x36,0x3e], + }; + let identify = |m: &Measured, machine: &[u8]| verdict(m, BUILDS.iter().map(|b| ( + Measured { text_size: b.text_size, data_size: b.data_size, + marker: b.marker, sha256: b.text_sha256 }, + b.machine.map_or(true, |board| board.to_bytes() == machine), + )), 0); + assert!(matches!(identify(&measured, b"apple,j514s"), Verdict::Pinned(_)), + "J514S cd05 firmware must pin without a prefix override"); + assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Refused); + let mut changed = measured; + changed.sha256[31] ^= 1; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.text_size += 0x1000; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.data_size += 0x1000; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + changed = measured; changed.marker += 8; + assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); for error in [0, -517, -12] { INIT_ERROR.set(error); let shared = Arc::new(Shared); let result = Rtkit::new(&dev, &shared); assert_eq!(result.is_ok(), error == 0); @@ -167,7 +193,8 @@ def main(): while depth: depth+=(hw[end]=='[')-(hw[end]==']'); end+=1 firmware='static BUILDS: &[FirmwareBuild] = &'+hw[start:end]+';\n'+item(hw,'pub(crate) struct FirmwareBuild') constructor=item(boot,' fn new(dev: &device::Device, shared: &Arc)') - source=PREFIX+'\nmod hw {\n'+constants+'\n}\nmod record {\n'+record_constants+'\n}\n'+helpers+'\n'+firmware+'\nimpl Rtkit {\n'+constructor+'\n}\n'+CASES + identity='mod identity {\n'+''.join(f'#[path = "{G15 / "identity" / (name + ".rs")}"] pub(crate) mod {name};\n' for name in ['matching', 'lookup'])+'}\n' + source=PREFIX+'\nmod hw {\n'+constants+'\n}\nmod record {\n'+record_constants+'\n}\n'+helpers+'\n'+firmware+'\nimpl Rtkit {\n'+constructor+'\n}\n'+identity+CASES variants={'actual':source} if a.mutations: variants['skip-owner-check']=source.replace('if !glue::reserved_uat(i as u32, r.start, r.end - r.start) {','if false {') From 8d0bb67f912d131db69fa75d82078de5c97b9fba Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sun, 8 Nov 2026 00:39:01 -0500 Subject: [PATCH 1186/1514] tools/asahi: refresh T6030 golden pins for the J514S cd05 row The J514S cd05 FirmwareBuild row adds 15 lines to the T6030 firmware table, which changes the pinned hw.rs file and t6030 module digests. With that row removed both digests are their previous values, so the T6030 profile itself is unchanged. Refresh the two pins and record why. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- tools/asahi/g15-zero-words-tests.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py index c6e32d76cb4158..2a73390f55282b 100644 --- a/tools/asahi/g15-zero-words-tests.py +++ b/tools/asahi/g15-zero-words-tests.py @@ -18,9 +18,11 @@ renumbering margins became tuning constants (the tables are unchanged). Its T6030 configuration module is independently pinned to the original bytes, -except for the J514S B0 FirmwareBuild row added to its firmware table: the -module is the original pinned bytes (0079ae08) plus that one 15-line row, and -the whole hw.rs pin was refreshed with it. prepare_board() is pinned too; +except for the J514S B0 FirmwareBuild row and the J514S cd05 FirmwareBuild row +added to its firmware table: the module is the original pinned bytes (0079ae08) +plus those two 15-line rows, and the whole hw.rs pin was refreshed with each +(with the cd05 row removed, both pins are their earlier values e9b80be9 and +cab592b5). prepare_board() is pinned too; it was refreshed for the same Board change (its T6030 arm is unchanged). """ @@ -37,11 +39,11 @@ GOLDEN_FILES = { "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", - "hw.rs": "c54a4f8342fb466f82f4b9cfed6a137ee1ca1f4d80ede4e1b7f397d39223558e", + "hw.rs": "82ee9d163da888e6dc506635e8e4a59cd3f4b4c34b3879e162702b8561093d9e", "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", } GOLDEN_FUNCTIONS = { - ("hw.rs", "pub(crate) mod t6030 {"): "cab592b5d776be9ede93b96b1b0526c1d838ef2948a5e4a86caa4ec71f71c2ca", + ("hw.rs", "pub(crate) mod t6030 {"): "d6c3020007646cba504db26bdfe5232e45185aba1d4603931da9a8d29bec40de", ("initdata.rs", "fn templates("): "c3115c9926d3d7d93317cb8510e93b04f30b0c256811d7137568e822dd93b8ee", ("initdata.rs", "pub(crate) fn prepare_board("): "ebef64ab87ef7b1f994eb7fa2a2424d05bc4fc9e88cbfbf18e51570bdfc4222d", ("board.rs", "pub(crate) fn from_adt("): "cecd0b28db5bd94d3b75c1bbb5f35204e8bf0699f74e5b3d08228c59025f6ac2", From 4c0e81ad9eff8826c215b429327cf3a76aaf8f79 Mon Sep 17 00:00:00 2001 From: joel cristobal Date: Fri, 6 Nov 2026 02:07:57 -0500 Subject: [PATCH 1187/1514] drm/asahi: g15: pin the cd05 firmware TEXT on the J516S Some 16-inch M3 Pro (J516S) units on the 14.7 boot chain load a B0 GPU firmware image whose TEXT digest differs from the pinned J516S row: TEXT 0x5c000, DATA 0x114000, GKTS marker 0x58e88 and TEXT sha256 cd05af6a828b52e4c2fed20086d3d18a7db42e03a8fd6f8354f9f06e0a61363e. The build is refused with "loaded GFX TEXT identity mismatch", so there is no render node and the compositor falls back to llvmpipe. The GPU only starts with the g15_accept_text_prefix bring-up override. Add this build as a J516S-only row. Rows still pin on the machine they name; nothing changes on the J514S or on other machines. Extend the maintained-handoff host test to check the new row and refresh the zero-words golden pins for hw.rs and the T6030 module, which change by exactly this one row. Measured on a J516S (apple,j516s apple,t6030; os-fw 14.7, system-fw 15.5, iBoot2 iBoot-10151.140.19.700.2) with linux-aurora 7.2.11.aurora14-1 and the override: the admission line reports the identical sizes, marker and digest, and the GPU reaches READY with renderD128 present. Link: https://github.com/omacom/linux-aurora/issues/247 Link: https://github.com/omacom/omarchy/issues/17739 Signed-off-by: joel cristobal Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g15/hw.rs | 16 ++++++++++++++++ tools/asahi/g15-maintained-handoff-tests.py | 9 ++++++--- tools/asahi/g15-zero-words-tests.py | 14 +++++++------- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs index 36310376e12b5c..14e4c92a608888 100644 --- a/drivers/gpu/drm/asahi/g15/hw.rs +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -190,6 +190,22 @@ pub(crate) mod t6030 { 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, ], }, + // Some J516S units on the same 14.7 boot chain load a different B0 + // TEXT image with identical sizes and marker. Pin its complete + // measured digest for the J516S only. + FirmwareBuild { + name: "J516S cd05 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j516s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0xcd, 0x05, 0xaf, 0x6a, 0x82, 0x8b, 0x52, 0xe4, + 0xc2, 0xfe, 0xd2, 0x00, 0x86, 0xd3, 0xd1, 0x8a, + 0x7d, 0xb4, 0x2e, 0x03, 0xa8, 0xfd, 0x6f, 0x83, + 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, + ], + }, ], machine: kernel::c_str!("apple,t6030"), platform: super::Platform::AdtWithPmp, diff --git a/tools/asahi/g15-maintained-handoff-tests.py b/tools/asahi/g15-maintained-handoff-tests.py index e0fb4438de3793..f2e344697dc3d9 100644 --- a/tools/asahi/g15-maintained-handoff-tests.py +++ b/tools/asahi/g15-maintained-handoff-tests.py @@ -137,12 +137,15 @@ def item(s, marker): OWNER_CALLS.set(0); let bytes = fixture(kind); assert!(parse(&dev, &Adt { data: &bytes }).is_err()); assert_eq!(OWNER_CALLS.get(), 0); } - assert_eq!(BUILDS.len(), 4, "maintained B0 firmware row must not require an absent profile symbol"); + assert_eq!(BUILDS.len(), 5, "maintained B0 firmware row must not require an absent profile symbol"); for (row, machine) in [(1, &b"apple,j516s"[..]), (2, &b"apple,j514s"[..])] { assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); assert_eq!(BUILDS[row].text_sha256, [0xda,0x26,0xec,0xca,0xb1,0xf8,0x59,0x8d,0xa8,0x0c,0x85,0x5e,0xca,0x91,0x65,0x20,0x40,0x6d,0x1d,0x06,0x70,0xf1,0xd4,0x70,0xe7,0x9b,0xb9,0xb0,0x22,0x09,0xdb,0x53]); } + assert_eq!(BUILDS[4].machine.unwrap().to_bytes(), b"apple,j516s"); + assert_eq!((BUILDS[4].text_size, BUILDS[4].data_size, BUILDS[4].marker), (0x5c000, 0x114000, 0x58e88)); + assert_eq!(BUILDS[4].text_sha256, [0xcd,0x05,0xaf,0x6a,0x82,0x8b,0x52,0xe4,0xc2,0xfe,0xd2,0x00,0x86,0xd3,0xd1,0x8a,0x7d,0xb4,0x2e,0x03,0xa8,0xfd,0x6f,0x83,0x54,0xf9,0xf0,0x6e,0x0a,0x61,0x36,0x3e]); // Issue #247: this J514S build must pin without the bring-up override. use identity::lookup::{Measured, Verdict, verdict}; let measured = Measured { @@ -157,9 +160,9 @@ def item(s, marker): marker: b.marker, sha256: b.text_sha256 }, b.machine.map_or(true, |board| board.to_bytes() == machine), )), 0); - assert!(matches!(identify(&measured, b"apple,j514s"), Verdict::Pinned(_)), + assert!(matches!(identify(&measured, b"apple,j514s"), Verdict::Pinned(3)), "J514S cd05 firmware must pin without a prefix override"); - assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Refused); + assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Pinned(4)); let mut changed = measured; changed.sha256[31] ^= 1; assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py index 2a73390f55282b..ae40a739749699 100644 --- a/tools/asahi/g15-zero-words-tests.py +++ b/tools/asahi/g15-zero-words-tests.py @@ -18,11 +18,11 @@ renumbering margins became tuning constants (the tables are unchanged). Its T6030 configuration module is independently pinned to the original bytes, -except for the J514S B0 FirmwareBuild row and the J514S cd05 FirmwareBuild row -added to its firmware table: the module is the original pinned bytes (0079ae08) -plus those two 15-line rows, and the whole hw.rs pin was refreshed with each -(with the cd05 row removed, both pins are their earlier values e9b80be9 and -cab592b5). prepare_board() is pinned too; +except for the J514S B0 FirmwareBuild row and the J514S cd05 and J516S cd05 +FirmwareBuild rows added to its firmware table: the module is the original +pinned bytes (0079ae08) plus those three rows, and the whole hw.rs pin was +refreshed with each (with the cd05 rows removed, both pins are their earlier +values e9b80be9 and cab592b5). prepare_board() is pinned too; it was refreshed for the same Board change (its T6030 arm is unchanged). """ @@ -39,11 +39,11 @@ GOLDEN_FILES = { "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", - "hw.rs": "82ee9d163da888e6dc506635e8e4a59cd3f4b4c34b3879e162702b8561093d9e", + "hw.rs": "95e745970891153307a8d6bbc04749d553de7fb490b9ef2ff0563cde7252d8bc", "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", } GOLDEN_FUNCTIONS = { - ("hw.rs", "pub(crate) mod t6030 {"): "d6c3020007646cba504db26bdfe5232e45185aba1d4603931da9a8d29bec40de", + ("hw.rs", "pub(crate) mod t6030 {"): "2667963ad7a0957bacf8118965a500586637b622a99e49916f111fcd02670fcd", ("initdata.rs", "fn templates("): "c3115c9926d3d7d93317cb8510e93b04f30b0c256811d7137568e822dd93b8ee", ("initdata.rs", "pub(crate) fn prepare_board("): "ebef64ab87ef7b1f994eb7fa2a2424d05bc4fc9e88cbfbf18e51570bdfc4222d", ("board.rs", "pub(crate) fn from_adt("): "cecd0b28db5bd94d3b75c1bbb5f35204e8bf0699f74e5b3d08228c59025f6ac2", From c5e990ab5fd917ea4957f3cd1fc02156c6ff89dc Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sun, 8 Nov 2026 15:32:06 -0500 Subject: [PATCH 1188/1514] drm/asahi: g15: pin the 4118 firmware TEXT on the J514S and J516S Some 14-inch (J514S) and 16-inch (J516S) M3 Pro units on the 14.7 boot chain load a third B0 GPU firmware image: TEXT 0x5c000, DATA 0x114000, GKTS marker 0x58e88 and TEXT sha256 411833a7ded773feeac4a181552e3ff5582eaf4435f2dd8f620c1ed0b31df1b0. No row pins it, so probe fails with "loaded GFX TEXT identity mismatch", there is no render node and the compositor falls back to llvmpipe. Three machines have reported it in issue omacom/linux-aurora#247, all on the 14.7 stub with system firmware 26.6.2: a J514S and a J516S (both iBoot-10151.140.19.700.2, mBoot-18000.161.10), which logged the identical sizes, marker and digest, and a second 14-inch M3 Pro. With g15_accept_text_prefix=0x411833a7ded773fe all three reached firmware READY with renderD128 present. The boot chain matches the J514S cd05 reports, so the chain alone does not select the image. Add one row per board, J514S then J516S, so each pin still names the machine it was measured on; nothing changes for other machines. Extend the maintained-handoff host test: both boards pin to their own row with the override disabled, other boards are refused, and an altered digest suffix, TEXT or DATA size or marker is refused. Refresh the zero-words golden pins for hw.rs and the T6030 module; with the two rows removed both are their previous values. Link: https://github.com/omacom/linux-aurora/issues/247 Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g15/hw.rs | 32 +++++++++++++++++++++ tools/asahi/g15-maintained-handoff-tests.py | 32 ++++++++++++++++++++- tools/asahi/g15-zero-words-tests.py | 15 +++++----- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs index 14e4c92a608888..be319b0cd2702f 100644 --- a/drivers/gpu/drm/asahi/g15/hw.rs +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -206,6 +206,38 @@ pub(crate) mod t6030 { 0x54, 0xf9, 0xf0, 0x6e, 0x0a, 0x61, 0x36, 0x3e, ], }, + // J514S (14-inch) firmware measured on the 14.7 boot chain with + // system firmware 26.6.2; the GPU reached READY with the bring-up + // prefix override (issue #247). + FirmwareBuild { + name: "J514S 4118 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j514s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0x41, 0x18, 0x33, 0xa7, 0xde, 0xd7, 0x73, 0xfe, + 0xea, 0xc4, 0xa1, 0x81, 0x55, 0x2e, 0x3f, 0xf5, + 0x58, 0x2e, 0xaf, 0x44, 0x35, 0xf2, 0xdd, 0x8f, + 0x62, 0x0c, 0x1e, 0xd0, 0xb3, 0x1d, 0xf1, 0xb0, + ], + }, + // J516S (16-inch) firmware measured on the 14.7 boot chain with + // system firmware 26.6.2; the GPU reached READY with the bring-up + // prefix override (issue #247). + FirmwareBuild { + name: "J516S 4118 firmware (14.7 boot chain)", + machine: Some(kernel::c_str!("apple,j516s")), + text_size: 0x5c000, + data_size: 0x114000, + marker: 0x58e88, + text_sha256: [ + 0x41, 0x18, 0x33, 0xa7, 0xde, 0xd7, 0x73, 0xfe, + 0xea, 0xc4, 0xa1, 0x81, 0x55, 0x2e, 0x3f, 0xf5, + 0x58, 0x2e, 0xaf, 0x44, 0x35, 0xf2, 0xdd, 0x8f, + 0x62, 0x0c, 0x1e, 0xd0, 0xb3, 0x1d, 0xf1, 0xb0, + ], + }, ], machine: kernel::c_str!("apple,t6030"), platform: super::Platform::AdtWithPmp, diff --git a/tools/asahi/g15-maintained-handoff-tests.py b/tools/asahi/g15-maintained-handoff-tests.py index f2e344697dc3d9..738facb331e521 100644 --- a/tools/asahi/g15-maintained-handoff-tests.py +++ b/tools/asahi/g15-maintained-handoff-tests.py @@ -137,7 +137,7 @@ def item(s, marker): OWNER_CALLS.set(0); let bytes = fixture(kind); assert!(parse(&dev, &Adt { data: &bytes }).is_err()); assert_eq!(OWNER_CALLS.get(), 0); } - assert_eq!(BUILDS.len(), 5, "maintained B0 firmware row must not require an absent profile symbol"); + assert_eq!(BUILDS.len(), 7, "maintained B0 firmware row must not require an absent profile symbol"); for (row, machine) in [(1, &b"apple,j516s"[..]), (2, &b"apple,j514s"[..])] { assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); @@ -172,6 +172,36 @@ def item(s, marker): assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); changed = measured; changed.marker += 8; assert_eq!(identify(&changed, b"apple,j514s"), Verdict::Refused); + // Issue #247: the 4118 build pins on the J514S and the J516S, each to + // its own row, without the bring-up override. + let digest = [0x41,0x18,0x33,0xa7,0xde,0xd7,0x73,0xfe, + 0xea,0xc4,0xa1,0x81,0x55,0x2e,0x3f,0xf5, + 0x58,0x2e,0xaf,0x44,0x35,0xf2,0xdd,0x8f, + 0x62,0x0c,0x1e,0xd0,0xb3,0x1d,0xf1,0xb0]; + for (row, machine) in [(5, &b"apple,j514s"[..]), (6, &b"apple,j516s"[..])] { + assert_eq!(BUILDS[row].machine.unwrap().to_bytes(), machine); + assert_eq!((BUILDS[row].text_size, BUILDS[row].data_size, BUILDS[row].marker), (0x5c000, 0x114000, 0x58e88)); + assert_eq!(BUILDS[row].text_sha256, digest); + } + let measured = Measured { text_size: 0x5c000, data_size: 0x114000, marker: 0x58e88, sha256: digest }; + assert_eq!(identify(&measured, b"apple,j514s"), Verdict::Pinned(5), + "J514S 4118 firmware must pin without a prefix override"); + assert_eq!(identify(&measured, b"apple,j516s"), Verdict::Pinned(6), + "J516S 4118 firmware must pin without a prefix override"); + for other in [&b"apple,j514c"[..], b"apple,j516c", b"apple,j514m", b"apple,j516m", b"apple,t6030"] { + assert_eq!(identify(&measured, other), Verdict::Refused); + } + for machine in [&b"apple,j514s"[..], b"apple,j516s"] { + let mut changed = measured; + changed.sha256[31] ^= 1; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.text_size += 0x1000; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.data_size += 0x1000; + assert_eq!(identify(&changed, machine), Verdict::Refused); + changed = measured; changed.marker += 8; + assert_eq!(identify(&changed, machine), Verdict::Refused); + } for error in [0, -517, -12] { INIT_ERROR.set(error); let shared = Arc::new(Shared); let result = Rtkit::new(&dev, &shared); assert_eq!(result.is_ok(), error == 0); diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py index ae40a739749699..3a31cba6958bf6 100644 --- a/tools/asahi/g15-zero-words-tests.py +++ b/tools/asahi/g15-zero-words-tests.py @@ -18,11 +18,12 @@ renumbering margins became tuning constants (the tables are unchanged). Its T6030 configuration module is independently pinned to the original bytes, -except for the J514S B0 FirmwareBuild row and the J514S cd05 and J516S cd05 -FirmwareBuild rows added to its firmware table: the module is the original -pinned bytes (0079ae08) plus those three rows, and the whole hw.rs pin was -refreshed with each (with the cd05 rows removed, both pins are their earlier -values e9b80be9 and cab592b5). prepare_board() is pinned too; +except for the J514S B0 FirmwareBuild row, the J514S cd05 and J516S cd05 +FirmwareBuild rows and the J514S 4118 and J516S 4118 FirmwareBuild rows added +to its firmware table: the module is the original pinned bytes (0079ae08) plus +those five rows, and the whole hw.rs pin was refreshed with each (with the 4118 +rows removed, both pins are their earlier values fb2118b6 and 2667963a; with +the cd05 rows also removed, e9b80be9 and cab592b5). prepare_board() is pinned too; it was refreshed for the same Board change (its T6030 arm is unchanged). """ @@ -39,11 +40,11 @@ GOLDEN_FILES = { "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", - "hw.rs": "95e745970891153307a8d6bbc04749d553de7fb490b9ef2ff0563cde7252d8bc", + "hw.rs": "f45a0f11f952fea4e36809267ffd240ee1e381e8f3400de5e8527cd316b9f225", "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", } GOLDEN_FUNCTIONS = { - ("hw.rs", "pub(crate) mod t6030 {"): "2667963ad7a0957bacf8118965a500586637b622a99e49916f111fcd02670fcd", + ("hw.rs", "pub(crate) mod t6030 {"): "4016ec0d46831482382a92791b625e10fb2f6e4e28115a9498fdde0776f82e52", ("initdata.rs", "fn templates("): "c3115c9926d3d7d93317cb8510e93b04f30b0c256811d7137568e822dd93b8ee", ("initdata.rs", "pub(crate) fn prepare_board("): "ebef64ab87ef7b1f994eb7fa2a2424d05bc4fc9e88cbfbf18e51570bdfc4222d", ("board.rs", "pub(crate) fn from_adt("): "cecd0b28db5bd94d3b75c1bbb5f35204e8bf0699f74e5b3d08228c59025f6ac2", From f7e2d0bd2d83ef67586c4e04c42a049baad8bcd1 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Fri, 13 Nov 2026 14:06:58 -0500 Subject: [PATCH 1189/1514] drm/asahi: g15: decline probes before activation with -ENODEV Before the module's final activate() step, the G15 probe returned -EPROBE_DEFER. That put the GPU on the driver core's deferred-probe list. activate() then runs the real probe through driver_attach(), but if that probe fails for good, for example because the firmware is rejected, the driver core does not take the device off the list. It stays in /sys/kernel/debug/devices_deferred until the deferred-probe work next runs, so anything that waits on that list keeps waiting. Return -ENODEV instead. activate() already reprobes every unbound device once MODULE_READY is set, and a device added later sees it set, so nothing needs the deferred list to retry. The display and PMP waits inside the real probe still return -EPROBE_DEFER. g15-probe-init-tests.py now checks that every probe before activation returns -ENODEV, and adds a mutant that defers again. Signed-off-by: Scott Jones (cherry picked from commit 6447458068e3 on omacom/linux-aurora, omacom/linux-aurora#470) [7.3 base: the probe-init test also runs with the G16 registration here, so its pre-activation probe count follows the registration order; the new mutant is added to this base's expected-failure table.] Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g15/mod.rs | 5 ++++- tools/asahi/g15-probe-init-tests.py | 25 +++++++++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 4cb221fb0a5df6..9553dc46f3c55e 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -202,8 +202,11 @@ impl platform::Driver for Driver<'_> { // after probe_g15 started firmware would return an unbound device. try_pin_init!(Driver { _driver: { + // Not EPROBE_DEFER: a deferred device stays listed in devices_deferred until the + // deferred-probe work runs, even after activate()'s probe fails for good. Activation + // reprobes every unbound device; a device added later sees MODULE_READY set. if !MODULE_READY.load(Ordering::Acquire) { - return Err(EPROBE_DEFER); + return Err(ENODEV); } let cfg = *info.ok_or(ENODEV)?; dev_info!(pdev.as_ref(), "G15: probing ({})\n", cfg.name); diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index 949c0be39a3e48..acd5c8b801281f 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -83,6 +83,7 @@ def item(text, marker): static G17_READY: Cell = const { Cell::new(false) }; static ATTACH_ERROR: Cell = const { Cell::new(false) }; static PROBE_ERROR: Cell = const { Cell::new(0) }; + static PRE_ACTIVATION: Cell = const { Cell::new(0) }; } struct Core<'a>(PhantomData<&'a ()>); struct Device { data: Cell<*mut core::ffi::c_void> } @@ -187,7 +188,16 @@ def item(text, marker): }; // Model driver_attach and a late driver_add_groups failure. A deferred // worker can also retry G15 while the other registration is in progress. - let _ = callback::>(&PDEV, Some(&&CFG)); + let ready = MODULE_READY.load(Ordering::Acquire); + let started = PROBES.get(); + let result = callback::>(&PDEV, Some(&&CFG)); + // A probe that started firmware here is the readiness-gate failure, checked below. + if !ready && PROBES.get() == started { + // A deferral would keep the GPU in devices_deferred after a later + // terminal failure; before activation the probe must decline outright. + assert_eq!(result, Err(ENODEV), "pre-activation probe deferred instead of ENODEV"); + PRE_ACTIVATION.set(PRE_ACTIVATION.get() + 1); + } if FAIL_REGISTRATION.get() == stage { return Err(-5); } COMPLETED_REGISTRATION.set(stage); stage @@ -256,7 +266,7 @@ def item(text, marker): PDEV.base.data.set(core::ptr::null_mut()); MODULE_READY.store(false, Ordering::Release); COMPLETED_REGISTRATION.set(0); FAIL_REGISTRATION.set(failure); - ACTIVATED.set(false); ATTACH_ERROR.set(failure == 0); + ACTIVATED.set(false); ATTACH_ERROR.set(failure == 0); PRE_ACTIVATION.set(0); let init = ::init(&MODULE); assert_eq!(PROBES.get(), 0, "module initializer eagerly started firmware"); let result = KBox::pin_init(init, GFP_KERNEL); @@ -273,6 +283,12 @@ def item(text, marker): assert!(!PDEV.base.data.get().is_null()); unsafe { drop(Box::from_raw(PDEV.base.data.get().cast::>())); } } + // Every probe before activation declined: one per completed or failing registration. + // The registrations run G15 (1), the generic driver (2), then G16 (3) where it is built. + let expected = if cfg!(CONFIG_DRM_ASAHI_G16) { + match failure { 1 => 1, 2 => 2, _ => 3 } + } else if failure == 1 { 1 } else { 2 }; + assert_eq!(PRE_ACTIVATION.get(), expected, "pre-activation probes"); println!("module-registration-{failure}: PASS"); } } @@ -419,9 +435,10 @@ def main(): needle = " None\n" assert probe.count(needle) == 1 variants["retained-error-unbinds"] = (probe.replace(needle, " return Err(error);\n"), module_code) - gate = " if !MODULE_READY.load(Ordering::Acquire) {\n return Err(EPROBE_DEFER);\n }\n" + gate = " if !MODULE_READY.load(Ordering::Acquire) {\n return Err(ENODEV);\n }\n" assert probe.count(gate) == 1 variants["no-registration-readiness-gate"] = (probe.replace(gate, ""), module_code) + variants["pre-activation-defers"] = (probe.replace(gate, gate.replace("ENODEV", "EPROBE_DEFER")), module_code) late = " #[cfg(CONFIG_DRM_ASAHI_G15)]\n _g15_ready: g15::activate(),\n" assert module_code.count(late) == 1 early = module_code.replace(late, "").replace(" _driver <-", late + " _driver <-", 1) @@ -450,7 +467,7 @@ def main(): else: receipt["mutants"][label] = result if r.returncode == 0: raise SystemExit("SURVIVED: " + name) - intended = {"eager-probe-before-allocation": "allocation-before-start: firmware probe before drvdata allocation", "retained-error-unbinds": "retained-start-failure-binds: callback result", "no-registration-readiness-gate": "late registration failure started firmware", "activation-before-last-registration": "activation before all registrations completed", "activation-before-g16-registration": "activation before all registrations completed"}[name] + intended = {"pre-activation-defers": "pre-activation probe deferred instead of ENODEV", "eager-probe-before-allocation": "allocation-before-start: firmware probe before drvdata allocation", "retained-error-unbinds": "retained-start-failure-binds: callback result", "no-registration-readiness-gate": "late registration failure started firmware", "activation-before-last-registration": "activation before all registrations completed", "activation-before-g16-registration": "activation before all registrations completed"}[name] result["intended_failure"] = intended in r.stderr if not result["intended_failure"]: raise SystemExit("INVALID unrelated failure: " + name + "\n" + r.stderr) (out / "result.json").write_text(json.dumps(receipt, indent=2) + "\n") From f9cfa1a83432377b76c4de542336b8325ff5f933 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Fri, 23 Oct 2026 00:24:18 -0400 Subject: [PATCH 1190/1514] pmdomain: apple: pmp-report: keep the T8122 14.x GPU readiness for the M3 runtime The 7.2 rebase replaced the T8122 14.x branch of apple_pmp_report_wait_supplier_ready() with a T6030-only one, so on an M3 MacBook Air every GPU power vote returns -ENODEV even with the PMP running. With the new hidden APPLE_T8122_GPU_PMP_LINK, which DRM_ASAHI_M3_T8122 selects (as DRM_ASAHI_G15 selects APPLE_T6030_GPU_PMP_LINK), wait for the unique T8122 report's display request (DISP, reg 7) to be ready and acknowledged before AGX, as on the 7.1.12 kernel the runtime was qualified with. The PMP graph and supplier host tests copy the dispatch, so they copy the T8122 wait too, built off there; their mutations still target the T6030 path. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/Kconfig | 1 + drivers/pmdomain/apple/pmp-report.c | 43 ++++++++++++++++++++++++- drivers/soc/apple/Kconfig | 9 ++++++ tools/asahi/t6030-pmp-graph-tests.c | 1 + tools/asahi/t6030-pmp-graph-tests.py | 12 +++++-- tools/asahi/t6030-pmp-supplier-tests.py | 12 +++++++ 6 files changed, 74 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index 8f5f8b50e668ad..f66b520a3a97d8 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -85,6 +85,7 @@ config DRM_ASAHI_M3_T8122 depends on DRM_ASAHI # The runtime adopts the firmware's UAT through the G15 backend's handoff helpers. depends on DRM_ASAHI_G15 + select APPLE_T8122_GPU_PMP_LINK select CRYPTO_LIB_SHA256 default n help diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index ef18686993d1a8..31784b43f3358a 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -701,6 +701,44 @@ static int apple_pmp_report_wait_t6030_14(struct device *supplier, unsigned int return ret; } +/* + * The T8122 (M3 MacBook Air) GPU on its 14.8.3 firmware, for the M3 runtime + * (APPLE_T8122_GPU_PMP_LINK): the unique T8122 report linked to this PMP, and + * its display request (DISP, reg 7) READY and acknowledged before AGX, as on + * the 7.1.12 kernel that runtime was qualified with. + */ +static int apple_pmp_report_wait_t8122_14(struct device *supplier, unsigned int timeout_ms) +{ + struct device_node *np, *report = NULL, *pmp, *entry; + int ret; + + if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK) || + !of_machine_is_compatible("apple,t8122") || + !of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2")) + return -ENODEV; + for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report") { + if (report) { + of_node_put(np); + of_node_put(report); + return -ENODEV; + } + report = of_node_get(np); + } + if (!report || !of_device_is_available(report) || + of_property_count_u32_elems(report, "apple,pmp") != 1) { + of_node_put(report); + return -ENODEV; + } + pmp = of_parse_phandle(report, "apple,pmp", 0); + entry = apple_pmp_report_t6030_entry(report); + ret = pmp == supplier->of_node && entry ? + apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV; + of_node_put(entry); + of_node_put(pmp); + of_node_put(report); + return ret; +} + /* The native 25G83 PMP starts through its supplier topology, after requests * are seeded. Its report is pinned against removal while readiness is read. */ @@ -714,8 +752,11 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t int ret; /* A declared report always takes the existing native25 path below. */ - if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) + if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) { + if (of_machine_is_compatible("apple,t8122")) + return apple_pmp_report_wait_t8122_14(supplier, timeout_ms); return apple_pmp_report_wait_t6030_14(supplier, timeout_ms); + } if (!np || !of_device_is_compatible(np, t8132 ? "apple,t8132-pmp-v2-report" : "apple,j613-25g83-pmp-report")) { of_node_put(np); diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index d1f15e2ceca732..79751d90bc75d9 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -480,6 +480,15 @@ config APPLE_DISPLAY_GATE Say 'y' if you want the native display on M3 Pro, M3 Max, M3 and M4 Pro Macs. +config APPLE_T8122_GPU_PMP_LINK + bool + depends on APPLE_PMP_REPORT + default n + help + Let T8122 (M3 MacBook Air) GPU power commands wait for the display + request the PMP report acknowledges on the 14.8.3 firmware, as the + M3 runtime of DRM_ASAHI_M3_T8122 requires. + config APPLE_T6030_GPU_PMP_LINK bool depends on APPLE_DISPLAY_GATE diff --git a/tools/asahi/t6030-pmp-graph-tests.c b/tools/asahi/t6030-pmp-graph-tests.c index 6a6607b85ade03..7b8ba9dab6bb3e 100644 --- a/tools/asahi/t6030-pmp-graph-tests.c +++ b/tools/asahi/t6030-pmp-graph-tests.c @@ -20,6 +20,7 @@ typedef uint8_t u8; #define BIT(n) (1U << (n)) #define IS_ENABLED(x) (x) #define CONFIG_APPLE_T6030_GPU_PMP_LINK 1 +#define CONFIG_APPLE_T8122_GPU_PMP_LINK 0 #define PMP_REPORT_READY 1 #define GFP_KERNEL 0 #define GENPD_FLAG_ACTIVE_WAKEUP 1 diff --git a/tools/asahi/t6030-pmp-graph-tests.py b/tools/asahi/t6030-pmp-graph-tests.py index 1184bc9840c417..d7f2b8abe17c4c 100644 --- a/tools/asahi/t6030-pmp-graph-tests.py +++ b/tools/asahi/t6030-pmp-graph-tests.py @@ -60,6 +60,12 @@ def main(): 'static int apple_pmp_report_entry_resume_noirq('] offsets = re.search(r'static const struct apple_pmp_report_offsets apple_pmp_offsets_t6030 = \{.*?\n\};', source, re.S)[0] functions = '\n'.join(extract.function(source, n) for n in names) + # The T8122 14.x wait (CONFIG_APPLE_T8122_GPU_PMP_LINK=0 here) precedes the dispatch; it is + # added after the mutations are placed, so they target the T6030 path only. + t8122 = extract.function(source, 'static int apple_pmp_report_wait_t8122_14(') + '\n' + dispatch = 'int apple_pmp_report_wait_supplier_ready(' + def with_t8122(text): + return text.replace(dispatch, t8122 + dispatch, 1) validation = re.sub(r'^#include .*\n', '', (ROOT / 'drivers/pmdomain/apple/pmp-report-validation.h').read_text(), flags=re.M) dram_type = re.search(r'struct apple_pmp_dram \{.*?\n\};', (ROOT / 'drivers/pmdomain/apple/pmp-dram.h').read_text(), re.S)[0] @@ -78,7 +84,7 @@ def main(): '\n' + dram_attrs + '\n' + functions) # The actual overlay must still describe a halted supplier and disabled DMA/mailbox. assert overlay.count('status = \"disabled\";') >= 3 - (args.output / 'production.h').write_text(code) + (args.output / 'production.h').write_text(with_t8122(code)) (args.output / 'overlay.h').write_text('static const struct overlay_entry overlay_entries[] = {\n' + entry_data + '\n};\n') compiler = shlex.split(os.environ.get('CC', 'clang')) command = compiler + ['-std=gnu11', '-g', '-O1', '-Wall', '-Wextra', '-Werror', @@ -133,13 +139,13 @@ def main(): ] for name, old, new in controls: assert code.count(old) == 1, (name, code.count(old)) - (args.output / 'production.h').write_text(code.replace(old, new)) + (args.output / 'production.h').write_text(with_t8122(code.replace(old, new))) built = subprocess.run(command, capture_output=True, text=True) # A mutant must compile; compilation failure is not regression evidence. ran = subprocess.run([str(args.output / 'graph')], capture_output=True, text=True) if not built.returncode else None (args.output / (name + '.log')).write_text(built.stdout + built.stderr + (ran.stdout + ran.stderr if ran else '')) mutations.append({'name': name, 'build_rc': built.returncode, 'run_rc': ran.returncode if ran else None}) - (args.output / 'production.h').write_text(code) + (args.output / 'production.h').write_text(with_t8122(code)) assert all(m['build_rc'] == 0 and m['run_rc'] != 0 for m in mutations), mutations (args.output / 'receipt.json').write_text(json.dumps({'source_ref': args.ref, 'source_sha256': hashlib.sha256(code.encode()).hexdigest(), 'overlay_sha256': hashlib.sha256(overlay.encode()).hexdigest(), 'overlay_entries': entries, diff --git a/tools/asahi/t6030-pmp-supplier-tests.py b/tools/asahi/t6030-pmp-supplier-tests.py index 269006b36aa4f3..725e37e24f6cfa 100755 --- a/tools/asahi/t6030-pmp-supplier-tests.py +++ b/tools/asahi/t6030-pmp-supplier-tests.py @@ -56,6 +56,7 @@ def run(out, name, code, compiler, configs=(0, 1)): command = compiler + ["-std=gnu11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined", "-fno-omit-frame-pointer", f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={config}", + "-DCONFIG_APPLE_T8122_GPU_PMP_LINK=0", "-I", str(dest), str(ROOT / "tools/asahi/t6030-pmp-supplier-tests.c"), "-o", str(binary)] @@ -148,6 +149,17 @@ def main(): assert code.count(old) == 1, (name, code.count(old)) variants.append((name, code.replace(old, new))) variants.append(("control-after", code)) + # The T8122 14.x wait is built with CONFIG_APPLE_T8122_GPU_PMP_LINK=0 here; it is added to + # every variant after the T6030 mutations are placed, so they target the T6030 path only. + dispatch = "int apple_pmp_report_wait_supplier_ready(" + t8122 = function(report, "static int apple_pmp_report_wait_t8122_14(") + "\n" + def with_t8122(source): + if dispatch not in source: + return source + return source.replace(dispatch, t8122 + dispatch, 1) + variants = [(name, with_t8122(source)) for name, source in variants] + if baseline_code and "apple_pmp_report_wait_t8122_14(" in baseline_code: + baseline_code = with_t8122(baseline_code) results = [run(args.output, name, source, compiler) for name, source in variants] if baseline_code: results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, (0,))) From 43f774f9be6c0972426db0f17e290b1e464e7472 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Fri, 23 Oct 2026 11:00:54 -0400 Subject: [PATCH 1191/1514] tools/asahi: test the T8122 14.x PMP wait in the supplier suite The supplier suite built apple_pmp_report_wait_t8122_14() only with APPLE_T8122_GPU_PMP_LINK off, so every case returned at its first check. Build it also as the M3 runtime does (T6030 and T8122 links on) and run the T8122 graph: the unique, available report linked to this PMP, with DISP (reg 7) acked, and its failures (machine, supplier and report compatibles, a duplicate or disabled report, the apple,pmp shape and identity, a missing, duplicate, disabled, incompatible or no-ack DISP entry, the managed start and its readiness). With the link off, a well-formed T8122 graph is refused. Mutants cover the wait's config scope, compatibles, report checks, readiness result and entry reference, and the dispatch's machine scope in both directions. Reported-by: Marcelo Alcantara Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- tools/asahi/t6030-pmp-supplier-tests.c | 60 +++++++++++++++++++++++-- tools/asahi/t6030-pmp-supplier-tests.py | 47 +++++++++++++++---- 2 files changed, 95 insertions(+), 12 deletions(-) diff --git a/tools/asahi/t6030-pmp-supplier-tests.c b/tools/asahi/t6030-pmp-supplier-tests.c index 48d61037038fbb..cea7041c01fb45 100644 --- a/tools/asahi/t6030-pmp-supplier-tests.c +++ b/tools/asahi/t6030-pmp-supplier-tests.c @@ -487,6 +487,17 @@ static void reset(void) lockable = present_device = link_ok = 1; status_word = PMP_REPORT_READY; } +/* The T8122 (M3 Air) 14.x graph: the same report shape, with T8122 compatibles. */ +static void t8122(void) +{ + machine = "apple,t8122"; + gate_soc = &gate_t8122; + supplier_node.compatible = "apple,t8122-pmp-v2"; + other_node.compatible = "apple,t8122-pmp-v2"; + gpu.compatible = "apple,agx-t8122"; + report14.compatible = "apple,t8122-pmp-v2-report"; + apple_pmp_starts.first = &managed_start; +} static int power(void) { return apple_pmp_set_device_power(0x0f, 5, 1); @@ -516,6 +527,7 @@ int main(void) (void)gate_find_one; (void)apple_pmp_report_t6030_entry; (void)apple_pmp_report_wait_t6030_14; + (void)apple_pmp_report_wait_t8122_14; reset(); assert(apple_pmp_offsets_t6030.starts_pmp == !!CONFIG_APPLE_T6030_GPU_PMP_LINK); @@ -572,9 +584,50 @@ int main(void) RUN((void)0, -ENODEV, 0, 0); assert(!find_calls); #endif - /* T8122 current14 remains unsupported by this supplier API. */ + /* A T8122 supplier never takes the T6030 report. */ RUN(machine = "apple,t8122"; supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); +#if CONFIG_APPLE_T8122_GPU_PMP_LINK + /* The T8122 14.x wait: one available report linked to this PMP, DISP (reg 7) acked. */ + RUN(t8122(), 0, 0, 1); + RUN(t8122(); report14.child = &entry7; entry7.sibling = &entry17; + entry17.sibling = NULL, 0, 0, 1); + RUN(t8122(); apple_pmp_starts.first = NULL, -ENODEV, 0, 0); + RUN(t8122(); apple_pmp_starts.first = NULL; + apple_pmp_reports.first = NULL, -EPROBE_DEFER, 0, 0); + RUN(t8122(); managed_start.stopping = true, -ENODEV, 0, 0); + RUN(t8122(); ready_result = -ETIMEDOUT, -ETIMEDOUT, 0, 0); + RUN(t8122(); passive_words[apple_pmp_offsets_t6030.status / 8] = 0, -EIO, + 0, 0); + RUN(t8122(); passive_words[apple_pmp_offsets_t6030.actual / 8] = 0, -EIO, + 0, 0); + RUN(t8122(); power_result = -EIO, -EIO, 0, 1); + RUN(t8122(); machine = "apple,t6030", -ENODEV, 0, 0); + RUN(t8122(); machine = "apple,t8112", -ENODEV, 0, 0); + RUN(t8122(); supplier_node.compatible = "apple,t6030-pmp-v2", -ENODEV, 0, + 0); + RUN(t8122(); report14.compatible = NULL, -ENODEV, 0, 0); + RUN(t8122(); report14.compatible = "apple,t6030-pmp-v2-report", -ENODEV, + 0, 0); + RUN(t8122(); extra_report = report14, -ENODEV, 0, 0); + RUN(t8122(); extra_report = report14; extra_report.available = false, + -ENODEV, 0, 0); + RUN(t8122(); report14.available = false, -ENODEV, 0, 0); + RUN(t8122(); report14.has_pmp = false, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp_cells = 0, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp_cells = 2, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp = NULL, -ENODEV, 0, 0); + RUN(t8122(); report14.pmp = &other_node, -ENODEV, 0, 0); + RUN(t8122(); entry17.sibling = NULL, -ENODEV, 0, 0); + RUN(t8122(); entry7.reg = 8, -ENODEV, 0, 0); + RUN(t8122(); entry7.available = false, -ENODEV, 0, 0); + RUN(t8122(); entry7.compatible = "apple,other", -ENODEV, 0, 0); + RUN(t8122(); entry7.no_ack = true, -ENODEV, 0, 0); + RUN(t8122(); entry17.reg = 7, -ENODEV, 0, 0); +#else + /* Without APPLE_T8122_GPU_PMP_LINK, even a well-formed T8122 graph is refused. */ + RUN(t8122(), -ENODEV, 0, 0); +#endif /* A declared report, including malformed/unresolved data, never falls back. */ RUN(supplier_node.has_report = true; supplier_node.report_cells = 0, -ENODEV, 0, 0); @@ -714,7 +767,8 @@ int main(void) assert(apple_pmp_link_device(&consumer) == -EINVAL); balanced(); case_count++; - printf("PASS: %d T6030 PMP cases, config=%d; reference, lock and command boundaries checked\n", - case_count, CONFIG_APPLE_T6030_GPU_PMP_LINK); + printf("PASS: %d T6030/T8122 PMP cases, config=%d/%d; reference, lock and command boundaries checked\n", + case_count, CONFIG_APPLE_T6030_GPU_PMP_LINK, + CONFIG_APPLE_T8122_GPU_PMP_LINK); return 0; } diff --git a/tools/asahi/t6030-pmp-supplier-tests.py b/tools/asahi/t6030-pmp-supplier-tests.py index 725e37e24f6cfa..aee98f9c599535 100755 --- a/tools/asahi/t6030-pmp-supplier-tests.py +++ b/tools/asahi/t6030-pmp-supplier-tests.py @@ -46,17 +46,23 @@ def no_core(): resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) -def run(out, name, code, compiler, configs=(0, 1)): +# (CONFIG_APPLE_T6030_GPU_PMP_LINK, CONFIG_APPLE_T8122_GPU_PMP_LINK): off, G15 only, and G15 +# with the M3 runtime (DRM_ASAHI_M3_T8122 depends on DRM_ASAHI_G15). +CONFIGS = ((0, 0), (1, 0), (1, 1)) + + +def run(out, name, code, compiler, configs=CONFIGS): dest = out / name dest.mkdir() (dest / "t6030-pmp-production.h").write_text(code) results = [] - for config in configs: + for t6030, t8122 in configs: + config = f"{t6030}{t8122}" binary = dest / f"config-{config}" command = compiler + ["-std=gnu11", "-g", "-O1", "-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined", "-fno-omit-frame-pointer", - f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={config}", - "-DCONFIG_APPLE_T8122_GPU_PMP_LINK=0", + f"-DCONFIG_APPLE_T6030_GPU_PMP_LINK={t6030}", + f"-DCONFIG_APPLE_T8122_GPU_PMP_LINK={t8122}", "-I", str(dest), str(ROOT / "tools/asahi/t6030-pmp-supplier-tests.c"), "-o", str(binary)] @@ -149,20 +155,43 @@ def main(): assert code.count(old) == 1, (name, code.count(old)) variants.append((name, code.replace(old, new))) variants.append(("control-after", code)) - # The T8122 14.x wait is built with CONFIG_APPLE_T8122_GPU_PMP_LINK=0 here; it is added to - # every variant after the T6030 mutations are placed, so they target the T6030 path only. + # The T8122 14.x wait mirrors the T6030 one, so it is added to every variant after the + # T6030 mutations are placed; its own mutants change only its text. dispatch = "int apple_pmp_report_wait_supplier_ready(" t8122 = function(report, "static int apple_pmp_report_wait_t8122_14(") + "\n" - def with_t8122(source): + def with_t8122(source, text=t8122): if dispatch not in source: return source - return source.replace(dispatch, t8122 + dispatch, 1) + return source.replace(dispatch, text + dispatch, 1) variants = [(name, with_t8122(source)) for name, source in variants] + if args.mutations: + t8122_mutations = [ + ("t8122-config-scope", "if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK) ||", "if (false ||"), + ("t8122-supplier-compat", '!of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2"))', "false)"), + ("t8122-report-compat", 'for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report")', + 'for_each_compatible_node(np, NULL, "apple,t6030-pmp-v2-report")'), + ("t8122-duplicate-report", "\t\tif (report) {", "\t\tif (false) {"), + ("t8122-disabled-report", "!of_device_is_available(report) ||", "false ||"), + ("t8122-report-phandle-shape", 'of_property_count_u32_elems(report, "apple,pmp") != 1', "false"), + ("t8122-supplier-identity", "pmp == supplier->of_node && entry ?", "entry ?"), + ("t8122-readiness-error", "apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV;", + "(apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)), 0) : -ENODEV;"), + ("t8122-entry-reference", "\tof_node_put(entry);\n\tof_node_put(pmp);", "\tof_node_put(pmp);"), + ] + for name, old, new in t8122_mutations: + assert t8122.count(old) == 1, (name, t8122.count(old)) + variants.insert(-1, (name, with_t8122(code, t8122.replace(old, new)))) + # The dispatch owns the machine scope: T8122 takes the T8122 wait, every other SoC the + # T6030 one. (The wait's own machine check repeats it and cannot be reached otherwise.) + machine = 'if (of_machine_is_compatible("apple,t8122"))' + assert code.count(machine) == 1 + for name, new in (("t8122-dispatch-never", "if (false)"), ("t8122-dispatch-always", "if (true)")): + variants.insert(-1, (name, with_t8122(code.replace(machine, new)))) if baseline_code and "apple_pmp_report_wait_t8122_14(" in baseline_code: baseline_code = with_t8122(baseline_code) results = [run(args.output, name, source, compiler) for name, source in variants] if baseline_code: - results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, (0,))) + results.append(run(args.output, "control-prior-config-off", baseline_code, compiler, ((0, 0),))) valid = True for item in results: control = item["name"].startswith("control-") From b8b50037874e8f15c53d66dca67f5cd14a98ccdf Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Thu, 5 Nov 2026 13:07:46 -0500 Subject: [PATCH 1192/1514] drm/apple: add the J504 internal panel record The 14" M3 MacBook Pro (J504) runs the same T8122 DCP image as the M3 MacBook Airs (90F849E1-..., named by the J504 ADT), so the 14.x IOMFB path can drive its panel once the boot loader hands the display over. Its panel is the J514S mini-LED panel: 3024x1964 with 74 notch rows, at 60 or 120 Hz. Add a J504 record with that geometry, ProMotion allowed, bring-up logging on, and this image's colour matrix methods. The panel level block is not qualified on this board, so brightness stays closed, and its swaps keep zero timestamps as on the Airs. Other T8122 Macs (the J433 and J434 iMacs) still have no record. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_v14_7.c | 25 ++++++++++++++++ drivers/gpu/drm/apple/v14-board-test.c | 41 ++++++++++++++++++++++++++ tools/asahi/dcp14-panel-tests.py | 22 ++++++++++++-- 3 files changed, 86 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index c6d3c66a0be27a..a2b13f1416a1a4 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -140,6 +140,30 @@ static const struct dcp_v14_board dcp_v14_board_j615 = { .ctm_get = A(420), }; +/* + * J504 (MacBook Pro 14", M3): the J613 DCP image on the same T8122 DCP (the + * J504 ADT names it), driving the 14" mini-LED panel of the J514S: 3024x1964 + * with 74 notch rows above the 3024x1890 boot framebuffer, at 60 or 120 Hz. + * The colour matrix methods are this image's. The panel level block is not + * qualified on this board, so brightness stays closed (no panel_nits), and + * its swaps keep zero timestamps as on the Airs. Every panel timing and the + * display clock are logged for the first boots. + */ +static const struct dcp_v14_board dcp_v14_board_j504 = { + .name = "J504", + .debugfs = "dcp-j504", + .dcp_compatible = "apple,t8122-dcp", + .machine = "apple,j504", + .firmware_uuid = DCP_V14_J613_FIRMWARE_UUID, + .handoff = "apple,t8122-handoff", + .panel_width = 3024, + .panel_height = 1964, + .promotion = true, + .log_bringup = true, + .ctm_set = A(421), + .ctm_get = A(420), +}; + /* * J516C (MacBook Pro 16", M3 Max): the J516S panel, 3456x2234 with 74 notch * rows above the 3456x2160 boot framebuffer, at 60 or 120 Hz, on the T6031 @@ -193,6 +217,7 @@ static const struct dcp_v14_board *const dcp_v14_boards[] = { &dcp_v14_board_t6030, &dcp_v14_board_j613, &dcp_v14_board_j615, + &dcp_v14_board_j504, &dcp_v14_board_j516c, &dcp_v14_board_j514c, }; diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index f9b84ab36a7cc1..2a41853d76dd20 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -54,6 +54,8 @@ static const char *const j514c[] = { "apple,j514c", "apple,t6031", "apple,arm-pl static const char *const j516m[] = { "apple,j516m", "apple,t6034", "apple,arm-platform", NULL }; static const char *const j516s[] = { "apple,j516s", "apple,t6030", "apple,arm-platform", NULL }; static const char *const j613[] = { "apple,j613", "apple,t8122", "apple,arm-platform", NULL }; +static const char *const j504[] = { "apple,j504", "apple,t8122", "apple,arm-platform", NULL }; +static const char *const j433[] = { "apple,j433", "apple,t8122", "apple,arm-platform", NULL }; static void v14_board_j516c(struct kunit *test) { @@ -247,7 +249,46 @@ static void v14_swap_timestamps_encoding(struct kunit *test) } } +/* + * J504 (14" M3 MacBook Pro): the J613 image on the T8122 DCP, its own 3024x1964 + * ProMotion panel, brightness closed and unstamped swaps. The other T8122 + * Macs (J433, J434) have no record. + */ +static void v14_board_j504(struct kunit *test) +{ + const struct dcp_v14_board *b, *air; + bool known; + + b = board_for("apple,t8122-dcp", j504, &known); + KUNIT_ASSERT_NOT_NULL(test, b); + air = board_for("apple,t8122-dcp", j613, &known); + KUNIT_ASSERT_NOT_NULL(test, air); + KUNIT_EXPECT_PTR_NE(test, b, air); + KUNIT_EXPECT_STREQ(test, b->name, "J504"); + KUNIT_EXPECT_STREQ(test, b->machine, "apple,j504"); + KUNIT_EXPECT_STREQ(test, b->handoff, "apple,t8122-handoff"); + KUNIT_EXPECT_STREQ(test, b->firmware_uuid, J613_DCP_IMAGE); + KUNIT_EXPECT_EQ(test, b->panel_width, 3024); + KUNIT_EXPECT_EQ(test, b->panel_height, 1964); + KUNIT_EXPECT_TRUE(test, b->promotion); + KUNIT_EXPECT_TRUE(test, b->log_bringup); + KUNIT_EXPECT_FALSE(test, b->panel_nits); + KUNIT_EXPECT_FALSE(test, b->base_edid); + KUNIT_EXPECT_EQ(test, b->ctm_set, air->ctm_set); + KUNIT_EXPECT_EQ(test, b->ctm_get, air->ctm_get); + KUNIT_EXPECT_TRUE(test, dcp_v14_board_admits(b, J613_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_admits(b, T6030_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_admits(b, J516C_DCP_IMAGE)); + KUNIT_EXPECT_FALSE(test, dcp_v14_board_stamps_swaps(b, false)); + + KUNIT_EXPECT_NULL(test, board_for("apple,t8122-dcp", j433, &known)); + KUNIT_EXPECT_TRUE(test, known); + /* A J504 root with another SoC's DCP gets no J504 record. */ + KUNIT_EXPECT_NULL(test, board_for("apple,t6031-dcp", j504, &known)); +} + static struct kunit_case v14_board_cases[] = { + KUNIT_CASE(v14_board_j504), KUNIT_CASE(v14_board_j516c), KUNIT_CASE(v14_board_j514c), KUNIT_CASE(v14_board_t6031_other_boards), diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index 0abcd1e89d3f93..b6c5979b117142 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -87,7 +87,25 @@ machine="apple,j613";const struct dcp_v14_board*j=iomfb_v14_7_board(&dev); assert(!IS_ERR(j)&&j->panel_width==2560 && j->panel_height==1664); machine="apple,j700";assert(IS_ERR(iomfb_v14_7_board(&dev))); - machine="apple,j504";assert(IS_ERR(iomfb_v14_7_board(&dev))); + /* J504 (14" M3 MacBook Pro): the J613 image, the J514 panel, 60 or 120 Hz. */ + machine="apple,j504";const struct dcp_v14_board*p14=iomfb_v14_7_board(&dev); + assert(!IS_ERR(p14)&&p14&&!strcmp(p14->name,"J504")&&!strcmp(p14->debugfs,"dcp-j504")); + assert(p14->panel_width==3024&&p14->panel_height==1964&&p14->promotion&&p14->log_bringup); + assert(!strcmp(p14->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); + assert(!strcmp(p14->handoff,"apple,t8122-handoff")&&!p14->panel_nits&&!p14->swap_timestamps); + assert(p14->ctm_set==A(421)&&p14->ctm_get==A(420)); + image_uuid=p14->firmware_uuid;assert(probe_gate(&dev,p14)==0); + image_uuid="C042E95C-B9D8-3F0E-94B3-582A08AA6FDD";assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid="F493F03E-CC40-3D89-9A08-5F259BA2B246";assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid=NULL;assert(probe_gate(&dev,p14)==-ENODEV); + image_uuid=p14->firmware_uuid;marker_value=0;assert(probe_gate(&dev,p14)==-ENODEV);marker_value=1; + {struct apple_dcp_v14 q={.dev=&dev,.board=p14};width=3024;height=1890;stride=width*4;notch=74; + assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964&&q.notch_rows==74); + height=1964;notch=0;assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964); + width=2560;height=1600;stride=width*4;notch=64;assert(dcp_v14_geometry(&q)==-EINVAL);} + /* Other T8122 Macs (J433/J434 iMacs) have no record. */ + machine="apple,j433";assert(IS_ERR(iomfb_v14_7_board(&dev))); + machine="apple,j434";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); dcp.compatible="apple,t8122-dcp"; struct apple_dcp_v14 v={.dev=&dev,.board=b};width=2880;height=1800;stride=width*4;notch=64; @@ -139,7 +157,7 @@ machine="apple,j613";assert(IS_ERR(iomfb_v14_7_board(&dev))); machine="apple,j516m";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); - puts("current J615/J613/T6030/J516C/J514C admission + hidden/full notch, wrong geometry controls: PASS"); + puts("current J615/J613/J504/T6030/J516C/J514C admission + hidden/full notch, wrong geometry controls: PASS"); #endif } ''' From a3d76cb95ba00cad491c1c370056d4db7845cfe1 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Thu, 5 Nov 2026 13:07:46 -0500 Subject: [PATCH 1193/1514] drm/asahi: start the T8122 GPU runtime on the J504 The J504 (14" M3 MacBook Pro) loads the same 14.8.3 G15G firmware image as the M3 MacBook Airs (UUID DF697F05-..., TEXT 0x64000, from its ADT). Move the T8122 board list into t8122_admission as T8122_BOARDS, add the J504, and test the exact list on the host. Firmware identity, resource admission, the performance-state cap and the thermal limit are unchanged; the J504 starts at the same conservative cap (state 2) as the Airs. The J433 and J434 iMacs stay unlisted. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_params.rs | 8 ++++---- drivers/gpu/drm/asahi/m3/m3_soc.rs | 7 ++++--- drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs | 1 + drivers/gpu/drm/asahi/m3/t8122_admission.rs | 17 +++++++++++++++++ drivers/gpu/drm/asahi/m3/t8122_start.rs | 4 ++-- 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 109c03ba2ef160..26735e7e9246bf 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -589,9 +589,9 @@ pub(crate) fn thermal_hot_param() -> (u64, bool) { /// Whether to start the runtime backend on a T8122 (`asahi.m3_backend`), and say why not. /// -/// The runtime starts only on the boards the T8122 table allows (the M3 MacBook Airs), with -/// `auto` and `runtime` alike: it has not run on any T8122, so nothing forces it onto another -/// board. The G15 manager backend is T6030-only. +/// The runtime starts only on the boards the T8122 table allows (the M3 MacBook Airs and the +/// 14" M3 MacBook Pro, `t8122_admission::T8122_BOARDS`), with `auto` and `runtime` alike: +/// nothing forces it onto another board. The G15 manager backend is T6030-only. pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { let dev = pdev.as_ref(); match M3_BACKEND.load(Ordering::Relaxed) { @@ -610,7 +610,7 @@ pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { _ => { dev_info!( dev, - "M3: no GPU backend on this T8122 board: the runtime backend may start only on the M3 MacBook Airs (J613, J615)\n" + "M3: no GPU backend on this T8122 board: the runtime backend may start only on the M3 MacBook Airs (J613, J615) and the 14\" M3 MacBook Pro (J504)\n" ); false } diff --git a/drivers/gpu/drm/asahi/m3/m3_soc.rs b/drivers/gpu/drm/asahi/m3/m3_soc.rs index 7500822c4124c5..3dcd15c896a48f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_soc.rs +++ b/drivers/gpu/drm/asahi/m3/m3_soc.rs @@ -284,9 +284,10 @@ pub(crate) static T8122: Soc = Soc { gpu_revision_id: hw::GpuRevisionID::C0, board: "apple,t8122", gpu: "apple,agx-t8122", - // The M3 MacBook Airs (13" J613, 15" J615). Allowed, not validated: the runtime has not run - // on either, and starts only behind a boot loader that hands the GPU over. - validated_boards: &[b"apple,j613", b"apple,j615"], + // The M3 MacBook Airs (13" J613, 15" J615) and the 14" M3 MacBook Pro (J504), which loads + // the same G15G image (`t8122_admission::T8122_BOARDS`). The runtime starts only behind a + // boot loader that hands the GPU over. + validated_boards: &crate::m3::t8122_admission::T8122_BOARDS, clusters: 1, cores_per_cluster: 10, mailbox_compatibles: &[ diff --git a/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs b/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs index 2ae70634ff5567..1b2412b7f78092 100644 --- a/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs +++ b/drivers/gpu/drm/asahi/m3/m3_thermal_policy.rs @@ -271,6 +271,7 @@ mod zone_tests { } assert_eq!(required_zones(b"apple,j613\0"), 1); assert_eq!(required_zones(b"apple,j615\0"), 1); + assert_eq!(required_zones(b"apple,j504\0apple,t8122\0"), 1); } #[test] diff --git a/drivers/gpu/drm/asahi/m3/t8122_admission.rs b/drivers/gpu/drm/asahi/m3/t8122_admission.rs index fb280ebcde5202..ff6d098f50a3c5 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_admission.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_admission.rs @@ -4,6 +4,12 @@ use super::m3_profile::Profile; +/// The T8122 boards the M3 runtime starts on by default: the M3 MacBook Airs (13" J613, 15" J615) +/// and the 14" M3 MacBook Pro (J504). All three load the same 14.8.3 G15G image (UUID +/// `DF697F05-…`, checked separately by firmware admission). The other T8122 Macs (the J433 and +/// J434 iMacs) are not listed. +pub(crate) const T8122_BOARDS: [&[u8]; 3] = [b"apple,j613", b"apple,j615", b"apple,j504"]; + #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) struct Identity { pub(crate) active_cores: u32, @@ -195,6 +201,17 @@ pub(crate) fn read_identity_for( #[cfg(test)] mod tests { + use super::T8122_BOARDS; + + #[test] + fn the_t8122_runtime_boards_are_exactly_the_airs_and_the_14_inch_pro() { + // Exact: dropping the J504 or adding another T8122 Mac (J433, J434) must fail here. + assert_eq!(T8122_BOARDS, [&b"apple,j613"[..], b"apple,j615", b"apple,j504"]); + for other in [&b"apple,j433"[..], b"apple,j434", b"apple,t8122"] { + assert!(!T8122_BOARDS.contains(&other)); + } + } + use super::*; const G15G_C0: u32 = 0x0702_2000; diff --git a/drivers/gpu/drm/asahi/m3/t8122_start.rs b/drivers/gpu/drm/asahi/m3/t8122_start.rs index 737034dd6f8c13..f4fe2bae341aa5 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_start.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_start.rs @@ -301,8 +301,8 @@ pub(crate) fn arm(dev: &device::Device, soc: &Soc) -> Result> e.mapping_count(), storage::IOMAP_BASE ); - // J613/J615 have no SoC die temperature zone yet, so a cap above the no-feedback limit runs - // the fanless GPU without any temperature feedback (`m3_thermal` holds the cap but gets no + // J615 and J504 have no SoC die temperature zone yet, so a cap above the no-feedback limit + // runs the GPU without any temperature feedback (`m3_thermal` holds the cap but gets no // reading). The runtime cap and the firmware ceiling stay equal, because the cap is at most // the no-feedback limit. if v.pstate_cap > knobs::PSTATE_CAP { From 0dd7aca98648b4653447204d7af2d789b45ce3fd Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Thu, 5 Nov 2026 13:07:47 -0500 Subject: [PATCH 1194/1514] arm64: dts: apple: t8122-j504: describe the internal panel Give the J504 DCP its panel node (the J514S 14" mini-LED panel: 302 x 196 mm, 189 mm below the notch, 500 nits) and point the boot framebuffer at it, as on the J613, so simpledrm and the DCP driver use the same physical size. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j504.dts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j504.dts b/arch/arm64/boot/dts/apple/t8122-j504.dts index f8258ba3a2f541..f290f011206777 100644 --- a/arch/arm64/boot/dts/apple/t8122-j504.dts +++ b/arch/arm64/boot/dts/apple/t8122-j504.dts @@ -39,13 +39,23 @@ &dcp { panel: panel { compatible = "apple,panel-j504", "apple,panel-mini-led", "apple,panel"; + /* + * The J514S panel: 3024x1964 at 254 ppi; 189 mm high without the + * 74 notch rows. The J504 boot framebuffer is 3024x1890 below them. + */ width-mm = <302>; height-mm = <196>; adj-height-mm = <189>; - apple,max-brightness = <600>; + apple,max-brightness = <500>; }; }; +/* The boot framebuffer is the same panel, as on the J613 (HiDPI scale for simpledrm). */ +&framebuffer0 { + panel = <&panel>; + post-init-providers = <&panel>; +}; + &wifi0 { brcm,board-type = "apple,tresco"; }; From 56e81920a633bbf28b95027958bae856187f90c5 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Thu, 5 Nov 2026 14:05:23 -0500 Subject: [PATCH 1195/1514] drm/apple: open the J504 panel brightness path The J504 runs the J613's DCP image, whose panel level block (brightness in nits) is qualified on the J613. Mark the J504 record panel_nits and admit the J504 machine for it, with the KUnit and host tests. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_v14_7.c | 10 ++++++---- drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c | 8 +++++++- drivers/gpu/drm/apple/v14-board-test.c | 4 ++-- tools/asahi/dcp14-panel-tests.py | 2 +- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index a2b13f1416a1a4..97279c844a6cec 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -144,9 +144,9 @@ static const struct dcp_v14_board dcp_v14_board_j615 = { * J504 (MacBook Pro 14", M3): the J613 DCP image on the same T8122 DCP (the * J504 ADT names it), driving the 14" mini-LED panel of the J514S: 3024x1964 * with 74 notch rows above the 3024x1890 boot framebuffer, at 60 or 120 Hz. - * The colour matrix methods are this image's. The panel level block is not - * qualified on this board, so brightness stays closed (no panel_nits), and - * its swaps keep zero timestamps as on the Airs. Every panel timing and the + * The colour matrix methods are this image's, and so is the panel level + * block the J613 qualified (brightness in nits, 500 at most here). Its swaps + * keep zero timestamps as on the Airs. Every panel timing and the * display clock are logged for the first boots. */ static const struct dcp_v14_board dcp_v14_board_j504 = { @@ -160,6 +160,7 @@ static const struct dcp_v14_board dcp_v14_board_j504 = { .panel_height = 1964, .promotion = true, .log_bringup = true, + .panel_nits = true, .ctm_set = A(421), .ctm_get = A(420), }; @@ -1719,7 +1720,8 @@ static bool dcp_v14_panel_nits_admit(const struct dcp_v14_board *board, { return board && board->panel_nits && (machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || - machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613")); + machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613") || + machine_is(ctx, "apple,j504")); } const char *iomfb_v14_7_board_name(const struct dcp_v14_board *board) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index a84e45338793e5..ecbc37f54d0166 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -122,13 +122,14 @@ static bool v14_bl_ctx_machine_is(const void *ctx, const char *compat) return !strcmp(((const char *const *)ctx)[1], compat); } -/* Only admitted T6030, J516C and J613 internal panels carry levels. */ +/* Only admitted T6030, J516C, J613 and J504 internal panels carry levels. */ static void v14_bl_boards(struct kunit *test) { static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s" }; static const char *const t6030_j514s[] = { "apple,t6030-dcp", "apple,j514s" }; static const char *const j613[] = { "apple,t8122-dcp", "apple,j613" }; static const char *const j615[] = { "apple,t8122-dcp", "apple,j615" }; + static const char *const j504[] = { "apple,t8122-dcp", "apple,j504" }; static const char *const j516c[] = { "apple,t6031-dcp", "apple,j516c" }; static const char *const other_t6030[] = { "apple,t6030-dcp", "apple,other" }; const struct dcp_v14_board *board; @@ -156,6 +157,11 @@ static void v14_bl_boards(struct kunit *test) board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j615, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_FALSE(test, board->panel_nits); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j504, &known); + KUNIT_ASSERT_NOT_NULL(test, board); + KUNIT_EXPECT_TRUE(test, board->panel_nits); + KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j504)); + KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j516c, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index 2a41853d76dd20..d79c2b79a9cbca 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -251,7 +251,7 @@ static void v14_swap_timestamps_encoding(struct kunit *test) /* * J504 (14" M3 MacBook Pro): the J613 image on the T8122 DCP, its own 3024x1964 - * ProMotion panel, brightness closed and unstamped swaps. The other T8122 + * ProMotion panel, the qualified level block (brightness) and unstamped swaps. The other T8122 * Macs (J433, J434) have no record. */ static void v14_board_j504(struct kunit *test) @@ -272,7 +272,7 @@ static void v14_board_j504(struct kunit *test) KUNIT_EXPECT_EQ(test, b->panel_height, 1964); KUNIT_EXPECT_TRUE(test, b->promotion); KUNIT_EXPECT_TRUE(test, b->log_bringup); - KUNIT_EXPECT_FALSE(test, b->panel_nits); + KUNIT_EXPECT_TRUE(test, b->panel_nits); KUNIT_EXPECT_FALSE(test, b->base_edid); KUNIT_EXPECT_EQ(test, b->ctm_set, air->ctm_set); KUNIT_EXPECT_EQ(test, b->ctm_get, air->ctm_get); diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index b6c5979b117142..19c02cafd82010 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -92,7 +92,7 @@ assert(!IS_ERR(p14)&&p14&&!strcmp(p14->name,"J504")&&!strcmp(p14->debugfs,"dcp-j504")); assert(p14->panel_width==3024&&p14->panel_height==1964&&p14->promotion&&p14->log_bringup); assert(!strcmp(p14->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); - assert(!strcmp(p14->handoff,"apple,t8122-handoff")&&!p14->panel_nits&&!p14->swap_timestamps); + assert(!strcmp(p14->handoff,"apple,t8122-handoff")&&p14->panel_nits&&!p14->swap_timestamps); assert(p14->ctm_set==A(421)&&p14->ctm_get==A(420)); image_uuid=p14->firmware_uuid;assert(probe_gate(&dev,p14)==0); image_uuid="C042E95C-B9D8-3F0E-94B3-582A08AA6FDD";assert(probe_gate(&dev,p14)==-ENODEV); From 3324fcb776b8a1ea461ed596f92b45e302e6f6a3 Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Tue, 10 Nov 2026 19:39:45 -0500 Subject: [PATCH 1196/1514] drm/asahi: m3: map the adopted handoff regions as the 7.2 runtime did On 7.3 the M3 MacBook Air runtime adopts the firmware's UAT through Uat::new_adopted_with_user_upper(), which always asks for a write-combined mapping of the handoff and TTBAT regions. On these Macs the boot loader leaves both regions in the kernel's memory map as reserved RAM, and memremap() refuses a write-combined mapping of RAM: memremap attempted on ram 0x00000103fff70000 size: 0x4000 aurora 292400000.gpu: probe with driver aurora failed with error -12 On 7.2 the same helper chose the mapping per region: write-back for reserved RAM, write-combined for a carveout. Uat::new_adopted() still does that on 7.3. Add Uat::new_adopted_ram_with_user_upper(), which makes the same per-region choice and keeps the caller's choice of user upper half, and use it for the M3 runtime. The M4 caller keeps the write-combined constructor; no other backend calls either. Seen on a J613 with a 7.3 kernel on the m1n1 1.6.1.aurora23 handoff. Signed-off-by: Scott Jones Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_runtime.rs | 2 +- drivers/gpu/drm/asahi/mmu.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index c5295f561b39ae..aadfb8f7d50bf0 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -1734,7 +1734,7 @@ fn adopt_uat(drm: &driver::AsahiDrmDevice, soc: &'static crate::m3::m3_soc::Soc, let range = |r: crate::m3::agx_resources::Region| r.base..r.base + r.size; let geometry = mmu::UatGeometry { ias: cfg.uat_ias.into(), oas: cfg.uat_oas }; let regions = mmu::AdoptedRegions { handoff: range(handoff), ttbs: range(ttbs), kernel_root: tables.base }; - let uat = mmu::Uat::new_adopted_with_user_upper(drm, geometry, ®ions, + let uat = mmu::Uat::new_adopted_ram_with_user_upper(drm, geometry, ®ions, profile == super::m3_profile::Profile::Legacy)?; let mut window = crate::g15::uat::Window::from_regions(handoff.base, ttbs.base, tables.base, shared_l2.base)?; window.bootstrap(drm.as_ref().as_ref(), &uat)?; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index c79939ec4f6b18..76de6353fab14f 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -3521,7 +3521,7 @@ impl Uat { /// Creates the same owned-RAM adopted UAT, choosing whether application contexts also /// name the firmware upper root. M4 qualifies only context 0 for firmware-upper access; /// its application TTBAT upper words stay zero. G15 preserves its existing shared upper. - #[cfg(any(CONFIG_DRM_ASAHI_G16, CONFIG_DRM_ASAHI_M3_T8122))] + #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) fn new_adopted_with_user_upper( dev: &driver::AsahiDrmDevice, geometry: UatGeometry, @@ -3531,6 +3531,20 @@ impl Uat { Self::new_adopted_inner(dev, geometry, regions, map_kernel_to_user, false) } + /// As [`Self::new_adopted_with_user_upper`], for regions that may be reserved System RAM: + /// each is mapped write-back when it is RAM and write-combined when it is a carveout, as + /// [`Self::new_adopted`] does. The M3 boot loaders leave the handoff and TTBAT regions in + /// the kernel's memory map as reserved RAM, which a write-combined mapping is refused for. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + pub(crate) fn new_adopted_ram_with_user_upper( + dev: &driver::AsahiDrmDevice, + geometry: UatGeometry, + regions: &AdoptedRegions, + map_kernel_to_user: bool, + ) -> Result { + Self::new_adopted_inner(dev, geometry, regions, map_kernel_to_user, true) + } + #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] fn new_adopted_inner( dev: &driver::AsahiDrmDevice, From d47b3e3461ed07d39fc59bd6960d4035eca1aeab Mon Sep 17 00:00:00 2001 From: Scott Jones Date: Sat, 24 Oct 2026 02:23:50 -0400 Subject: [PATCH 1197/1514] drm/asahi: build the T8122 runtime without the G15 backend DRM_ASAHI_M3_T8122 depended on DRM_ASAHI_G15 only because the T8122 runtime adopts the firmware's UAT with the G15 backend's handoff helpers (g15::uat::Window and g15::memory_mode). Turning the M3 Air on therefore also turned the G15 backend on for M3 Pro/Max. Split the adoption out behind a hidden DRM_ASAHI_UAT_ADOPTION, selected by both options: - without G15, g15/adopt.rs builds only g15/{uat,regs,hw}.rs (no probe, no driver registration); what in them needs G15's Config or ADT (adopt(), Window::new, Regs::identity and the T6030/T6031 tables) stays under G15; - the RAM helpers memory_mode needs move from g15/glue.c to g15/uat_glue.c, so the runtime doesn't take glue.c's display helpers; - M3_T8122 now states its own dependency on APPLE_PMP, whose PMP votes the runtime calls directly (before, it was implied by nothing); - the mmu and pgtable items the runtime uses (the adopted Uat, with_tracked_status, read_user and point-of-coherency cleaning) are built with UAT_ADOPTION instead of G15. G15 selects UAT_ADOPTION, so every configuration that builds today is unchanged: off, G15 only and G15 with T8122 give the same warnings as before, and M3_T8122 alone now builds without warnings. The asahi-g15 selftest reads the helpers from their new file, and the g15-zero-words test pins the new hw.rs (its separate T6030 table pin is unchanged). Signed-off-by: Scott Jones (ported from commit 9dff537d173 on omacom/linux-aurora) [7.3 base: G15 keeps this base's "default y" and selects the new option. The base builds what the runtime shares with G15 under "G15 or G16" and keeps the point-of-coherency cleaning unconditional, so the mmu and pgtable gates become "UAT_ADOPTION or G16" and gain no new #[cfg] on clean_poc. The module is aurora.ko here. g15-zero-words-tests pins hw.rs after the test's own normalisation. Built with G15 and T8122 (same warnings as before) and with T8122 alone: that builds, and none of its dead-code warnings is in g15/, m3/, mmu.rs or pgtable.rs. Not run on hardware.] [Ryan: on this main G16 also calls VmReadGuard::covers_range() and is the only caller of VmReadGuard::epoch(), so those two keep "G15 or G16" and "G16" gates instead of "G15".] Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/Kconfig | 14 ++++- drivers/gpu/drm/asahi/Makefile | 1 + drivers/gpu/drm/asahi/asahi_core.rs | 4 ++ drivers/gpu/drm/asahi/g15/adopt.rs | 32 ++++++++++ drivers/gpu/drm/asahi/g15/glue.c | 46 --------------- drivers/gpu/drm/asahi/g15/hw.rs | 2 + drivers/gpu/drm/asahi/g15/regs.rs | 3 +- drivers/gpu/drm/asahi/g15/uat.rs | 6 +- drivers/gpu/drm/asahi/g15/uat_glue.c | 59 +++++++++++++++++++ drivers/gpu/drm/asahi/mmu.rs | 30 +++++----- drivers/gpu/drm/asahi/pgtable.rs | 2 +- tools/asahi/g15-zero-words-tests.py | 6 +- .../selftests/drivers/gpu/asahi-g15/run.py | 8 ++- 13 files changed, 143 insertions(+), 70 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g15/adopt.rs create mode 100644 drivers/gpu/drm/asahi/g15/uat_glue.c diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index f66b520a3a97d8..7a71c24be9cc03 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -80,11 +80,20 @@ config DRM_ASAHI_DEBUG_ALLOCATOR Say N unless you are debugging firmware structures or porting to a new firmware version. +config DRM_ASAHI_UAT_ADOPTION + bool + help + The firmware UAT handoff adoption shared by the G15 backend and the + T8122 runtime (g15/uat.rs, g15/regs.rs). + config DRM_ASAHI_M3_T8122 bool "M3 MacBook Air GPU runtime (T8122, 14.8.3 firmware)" depends on DRM_ASAHI - # The runtime adopts the firmware's UAT through the G15 backend's handoff helpers. - depends on DRM_ASAHI_G15 + # The runtime adopts the firmware's UAT as the G15 backend does, without + # needing that backend: M3 Pro/Max keep their own setting. + # Its PMP votes call apple-pmp directly (m3_device.rs). + depends on APPLE_PMP=y || (APPLE_PMP=m && DRM_ASAHI=m) + select DRM_ASAHI_UAT_ADOPTION select APPLE_T8122_GPU_PMP_LINK select CRYPTO_LIB_SHA256 default n @@ -115,6 +124,7 @@ config DRM_ASAHI_G15 depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m) select APPLE_T6030_GPU_PMP_LINK select CRYPTO_LIB_SHA256 + select DRM_ASAHI_UAT_ADOPTION default y help Backend for the M3 Pro (T6030) and M3 Max (T6031) GPUs on the diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index e1b0eb9d826280..f5cf6fe22cfb16 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -5,6 +5,7 @@ aurora-y := asahi_core.o fwid.o legacy_sched.o sysfs.o user_pages.o g17/sync_inp CFLAGS_g17/trace.o := -I$(src)/g17 aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o +aurora-$(CONFIG_DRM_ASAHI_UAT_ADOPTION) += g15/uat_glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 792af5bdbc55a6..1042612805e03f 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -17,6 +17,10 @@ mod fw; mod fwid; #[cfg(CONFIG_DRM_ASAHI_G15)] mod g15; +// Without the G15 backend, only the UAT adoption the T8122 runtime shares with it. +#[cfg(all(CONFIG_DRM_ASAHI_UAT_ADOPTION, not(CONFIG_DRM_ASAHI_G15)))] +#[path = "g15/adopt.rs"] +mod g15; mod g17; mod gem; diff --git a/drivers/gpu/drm/asahi/g15/adopt.rs b/drivers/gpu/drm/asahi/g15/adopt.rs new file mode 100644 index 00000000000000..5dd54b04aaec6b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/adopt.rs @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! Without the G15 backend (`CONFIG_DRM_ASAHI_G15=n`), the parts of it the T8122 runtime uses to +//! adopt the firmware's UAT: the handoff window ([`uat`]), its mappings ([`regs`]) and the +//! hardware constants they name ([`hw`]). Nothing here probes a device. + +// Only the adoption is used; the rest of these files serves the G15 backend. +#![allow(dead_code)] + +// hw.rs's `t6031` submodule is cfg-gated on G15; were it built here, a #[path]-loaded file +// would look for it at g15/t6031.rs, not g15/hw/t6031.rs. +#[path = "hw.rs"] +pub(crate) mod hw; +#[path = "regs.rs"] +pub(crate) mod regs; +#[path = "uat.rs"] +pub(crate) mod uat; + +use kernel::prelude::*; + +extern "C" { + fn asahi_g15_memory_mode(start: u64, size: u64) -> u32; +} + +/// WB for complete reserved RAM, WC for aligned non-RAM carveouts; reject everything else. +pub(crate) fn memory_mode(start: u64, size: u64) -> Result { + // SAFETY: Only queries resources and page metadata; it does not create a mapping. + match unsafe { asahi_g15_memory_mode(start, size) } { + 0 => Err(EINVAL), + mode => Ok(mode), + } +} diff --git a/drivers/gpu/drm/asahi/g15/glue.c b/drivers/gpu/drm/asahi/g15/glue.c index 2a0346228c1e58..a12a5e6fa2fe78 100644 --- a/drivers/gpu/drm/asahi/g15/glue.c +++ b/drivers/gpu/drm/asahi/g15/glue.c @@ -29,9 +29,6 @@ void asahi_g15_release_power(struct device *dev); void asahi_g15_reprobe(void); void asahi_g15_report_loader_gpu(void); int asahi_g15_adt_phram(u64 *start, u64 *size); -bool asahi_g15_ram_disjoint(u64 start, u64 size); -bool asahi_g15_ram_within(u64 start, u64 size); -unsigned int asahi_g15_memory_mode(u64 start, u64 size); void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size); bool asahi_g15_dma_coherent(struct device *dev); int asahi_g15_pmp_prepare(struct device *dev); @@ -275,13 +272,6 @@ int asahi_g15_adt_phram(u64 *start, u64 *size) return 0; } -/* The range is disjoint from System RAM (ADT region admission). */ -bool asahi_g15_ram_disjoint(u64 start, u64 size) -{ - return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) == - REGION_DISJOINT; -} - /* * Whether DMA mappings of the device skip cache maintenance. The G15 firmware * objects rely on the DMA mapping cleaning their pages to the point of @@ -292,42 +282,6 @@ bool asahi_g15_dma_coherent(struct device *dev) return dev_is_dma_coherent(dev); } -/* - * Every page must be valid, System RAM and still reserved from the allocator. - * REGION_INTERSECTS alone also accepts RAM mixed with undefined memory holes. - */ -bool asahi_g15_ram_within(u64 start, u64 size) -{ - u64 end, pa; - - if (!size || !IS_ALIGNED(start, PAGE_SIZE) || - !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) - return false; - for (pa = start; pa < end; pa += PAGE_SIZE) { - unsigned long pfn = PHYS_PFN(pa); - - if (!pfn_valid(pfn) || !page_is_ram(pfn) || - !PageReserved(pfn_to_page(pfn))) - return false; - } - return true; -} - -/* One classification for every adopted-UAT and firmware-region CPU mapping. */ -unsigned int asahi_g15_memory_mode(u64 start, u64 size) -{ - u64 end; - - if (!size || !IS_ALIGNED(start, PAGE_SIZE) || - !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) - return 0; - if (asahi_g15_ram_within(start, size)) - return MEMREMAP_WB; - if (asahi_g15_ram_disjoint(start, size)) - return MEMREMAP_WC; - return 0; -} - /* The inherited RTKit buffer inside firmware DATA. */ void __iomem *asahi_g15_ioremap_wc(u64 start, size_t size) { diff --git a/drivers/gpu/drm/asahi/g15/hw.rs b/drivers/gpu/drm/asahi/g15/hw.rs index be319b0cd2702f..cac11c55d3ca00 100644 --- a/drivers/gpu/drm/asahi/g15/hw.rs +++ b/drivers/gpu/drm/asahi/g15/hw.rs @@ -7,6 +7,7 @@ use core::ops::Range; +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) mod t6031; /// Identification register values of a qualified G15S. @@ -91,6 +92,7 @@ pub(crate) struct ComputeRegs { } /// The T6030 configuration. +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) mod t6030 { use super::super::Config; use super::{ComputeRegs, FirmwareBuild, HwId, Layout}; diff --git a/drivers/gpu/drm/asahi/g15/regs.rs b/drivers/gpu/drm/asahi/g15/regs.rs index 05a1b390b3dffc..98e7d4c8cf78a4 100644 --- a/drivers/gpu/drm/asahi/g15/regs.rs +++ b/drivers/gpu/drm/asahi/g15/regs.rs @@ -125,7 +125,7 @@ impl Mapping { if size == 0 { return Err(EINVAL); } - let mode = super::boot::glue::memory_mode(phys, size as u64)?; + let mode = super::memory_mode(phys, size as u64)?; if mode == bindings::MEMREMAP_WC as u32 { return Self::write_combined(phys, size); } @@ -252,6 +252,7 @@ impl Regs { /// Reads the identification words and the enabled-core mask (once the GPU is powered). A /// SoC with more than 32 core slots carries the mask in two words. + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn identity(&self, cfg: &super::Config) -> Result { let version = self.sgx.io().try_read32(SGX_ID)?; let counts = self.sgx.io().try_read32(SGX_ID + 0x10)?; diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs index 8168f32abe01b5..9a93e6d17a59f0 100644 --- a/drivers/gpu/drm/asahi/g15/uat.rs +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -38,12 +38,14 @@ use kernel::{ bindings, device, io::Io, prelude::*, - sync::Arc, time::{delay::fsleep, Delta, Instant, Monotonic}, }; +#[cfg(CONFIG_DRM_ASAHI_G15)] +use kernel::sync::Arc; use super::hw; use super::regs::{mb, rmb, wmb, Mapping}; +#[cfg(CONFIG_DRM_ASAHI_G15)] use crate::driver::AsahiDrmDevice as AsahiDevice; use crate::{mmu, pgtable}; @@ -69,6 +71,7 @@ const fn indices(va: u64) -> [usize; 3] { } /// Creates the adopted UAT over the ADT regions (step 2 above). +#[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn adopt( dev: &AsahiDevice, cfg: &'static super::Config, @@ -201,6 +204,7 @@ pub(crate) struct Window { impl Window { /// Maps the UAT handoff regions ([`Mapping::region`]). + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn new(adt: &super::adt::GpuAdt) -> Result { Self::from_regions(adt.handoff.start, adt.ttbs.start, adt.tables.start, adt.shared_l2.start) } diff --git a/drivers/gpu/drm/asahi/g15/uat_glue.c b/drivers/gpu/drm/asahi/g15/uat_glue.c new file mode 100644 index 00000000000000..134ff4bb28ab6b --- /dev/null +++ b/drivers/gpu/drm/asahi/g15/uat_glue.c @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * C helpers of the UAT adoption (g15/uat.rs, g15/regs.rs), built for the G15 + * backend and for the T8122 runtime, which adopts the firmware's UAT the same + * way (CONFIG_DRM_ASAHI_UAT_ADOPTION). + */ +#include +#include +#include +#include +#include +#include + +bool asahi_g15_ram_disjoint(u64 start, u64 size); +bool asahi_g15_ram_within(u64 start, u64 size); +unsigned int asahi_g15_memory_mode(u64 start, u64 size); + +/* The range is disjoint from System RAM (ADT region admission). */ +bool asahi_g15_ram_disjoint(u64 start, u64 size) +{ + return region_intersects(start, size, IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) == + REGION_DISJOINT; +} + +/* + * Every page must be valid, System RAM and still reserved from the allocator. + * REGION_INTERSECTS alone also accepts RAM mixed with undefined memory holes. + */ +bool asahi_g15_ram_within(u64 start, u64 size) +{ + u64 end, pa; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return false; + for (pa = start; pa < end; pa += PAGE_SIZE) { + unsigned long pfn = PHYS_PFN(pa); + + if (!pfn_valid(pfn) || !page_is_ram(pfn) || + !PageReserved(pfn_to_page(pfn))) + return false; + } + return true; +} + +/* One classification for every adopted-UAT and firmware-region CPU mapping. */ +unsigned int asahi_g15_memory_mode(u64 start, u64 size) +{ + u64 end; + + if (!size || !IS_ALIGNED(start, PAGE_SIZE) || + !IS_ALIGNED(size, PAGE_SIZE) || check_add_overflow(start, size, &end)) + return 0; + if (asahi_g15_ram_within(start, size)) + return MEMREMAP_WB; + if (asahi_g15_ram_disjoint(start, size)) + return MEMREMAP_WC; + return 0; +} diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 76de6353fab14f..a46ef16f970fe7 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -511,15 +511,17 @@ fn lock_vm( Ok(VmExecGuard(unsafe { gpuvm.exec_lock(obj, interruptible)? })) } -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) struct VmReadGuard<'a>(gpuvm::GpuVmInnerGuard<'a, VmInner>); -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] impl VmReadGuard<'_> { + #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) fn epoch(&self) -> Option { self.0.epoch } + #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] pub(crate) fn covers_range(&mut self, address: u64, size: u64, read: bool, write: bool) -> bool { Vm::covers_range_locked(&mut self.0, address, size, read, write) } @@ -2543,7 +2545,7 @@ impl Vm { /// Attach a status and job lifetime tracking before sharing a newly created user VM with /// queues, without the G17 canonical context views, shared-object footprints and idle /// residency reclaim of [`Self::with_status`]. Used by G15, whose user objects stay pinned. - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) fn with_tracked_status(mut self) -> Result { self.status = Some(Arc::pin_init( crate::g17::status::VmStatus::new(), @@ -2571,12 +2573,12 @@ impl Vm { /// and invalidated to the point of coherency first (never only invalidated: CPU-written lines /// may be dirty), so the copy sees what the GPU or a write-combined CPU view stored. The /// mappings cannot change during the copy (VM reservation lock). - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) fn read_user(&self, va: u64, buf: &mut [u8]) -> Result { self.read_lock()?.read_user(va, buf) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) fn read_lock(&self) -> Result> { // Every mapping change holds the VM reservation, so read-only page-table walks and // user-memory copies need only that reservation. The full exec lock would allocate a @@ -2584,7 +2586,7 @@ impl Vm { Ok(VmReadGuard(self.gpuvm.lock_inner())) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] fn read_user_locked(inner: &mut VmInner, va: u64, buf: &mut [u8]) -> Result { let mut done = 0usize; while done < buf.len() { @@ -3427,7 +3429,7 @@ impl Drop for VmInner { /// Physical regions of a UAT whose handoff the generation has already established itself /// ([`Uat::new_adopted`]). None of them needs to be in the kernel linear map. -#[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) struct AdoptedRegions { /// The handoff region (PPL magic, lock and flush requests). pub(crate) handoff: Range, @@ -3450,7 +3452,7 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Map a region given by its physical range, write-combined. fn map_physical( range: &Range, @@ -3471,7 +3473,7 @@ impl Uat { let res: io::resource::Resource = unsafe { core::mem::transmute(kernel::types::Opaque::new(raw)) }; let flags = io::mem::MemFlag::WC; - #[cfg(CONFIG_DRM_ASAHI_G15)] + #[cfg(CONFIG_DRM_ASAHI_UAT_ADOPTION)] let flags = if reserved_ram { // G15 admits only whole reserved RAM pages or wholly non-RAM carveouts. if crate::g15::memory_mode(range.start, size as u64)? @@ -3484,7 +3486,7 @@ impl Uat { } else { flags }; - #[cfg(not(CONFIG_DRM_ASAHI_G15))] + #[cfg(not(CONFIG_DRM_ASAHI_UAT_ADOPTION))] let _ = reserved_ram; // SAFETY: The UAT regions are only accessed through this mapping by the CPU; // the GPU reaches them through its own translation. @@ -3495,7 +3497,7 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Creates a `Uat` for a handoff that the caller establishes itself (G15). /// /// This only maps the handoff and the TTBAT (write-combined); neither is written here. The @@ -3545,7 +3547,7 @@ impl Uat { Self::new_adopted_inner(dev, geometry, regions, map_kernel_to_user, true) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] fn new_adopted_inner( dev: &driver::AsahiDrmDevice, geometry: UatGeometry, @@ -3637,13 +3639,13 @@ impl Uat { }) } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Root of the kernel lower `Vm`, for TTBAT context 0 of an adopted handoff. pub(crate) fn kernel_lower_root(&self) -> PhysicalAddr { self.kernel_lower_vm.ttb() } - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] /// Root whose driver-window entry names the second-level table of [`Self::kernel_vm`]'s /// driver window. With [`Self::new_adopted`] this is the shadow root that no context names. pub(crate) fn kernel_window_root(&self) -> PhysicalAddr { diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index a6e757c22176a0..a8bfe840bd3eb0 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -381,7 +381,7 @@ impl Prot { /// The protection bits of a leaf with this protection (no address, table type or non-global /// bits), for checking that a firmware leaf word round-trips through [`Self::from_pte`]. - #[cfg(any(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_G16))] + #[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] pub(crate) const fn leaf_bits(&self) -> u64 { self.as_pte() } diff --git a/tools/asahi/g15-zero-words-tests.py b/tools/asahi/g15-zero-words-tests.py index 3a31cba6958bf6..f4d18bc9685ac0 100644 --- a/tools/asahi/g15-zero-words-tests.py +++ b/tools/asahi/g15-zero-words-tests.py @@ -15,7 +15,9 @@ (one #[cfg] line; the tables are unchanged), and when the initial PB posting and the idle reclaim became fixed tuning constants instead of module parameters (four constants; the tables are unchanged), and when the two stamp -renumbering margins became tuning constants (the tables are unchanged). Its T6030 +renumbering margins became tuning constants (the tables are unchanged), and when +the T6030/T6031 tables were gated on CONFIG_DRM_ASAHI_G15 for the T8122 runtime's +UAT adoption (two #[cfg] lines; the tables are unchanged). Its T6030 configuration module is independently pinned to the original bytes, except for the J514S B0 FirmwareBuild row, the J514S cd05 and J516S cd05 @@ -40,7 +42,7 @@ GOLDEN_FILES = { "board/data.rs": "7c5ff1077ca3296cbfc9e7144294162b6dea78a3774c38eeed4b0f59a14d7a5c", "board/template.rs": "286872f5474a67534f214e83e659253299f85143f3dc59035fa80894022e2549", - "hw.rs": "f45a0f11f952fea4e36809267ffd240ee1e381e8f3400de5e8527cd316b9f225", + "hw.rs": "9fa2d6e5f5d14127574448cafd6523d2151dab77c66d16e74500fafde21e8d92", "power/idle.rs": "4928ecf7699b3ca85ff5143eb6e996efd40d47321e29a238a02c8873bc9f102c", } GOLDEN_FUNCTIONS = { diff --git a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py index 571ad60f59e707..e4c1e92126be8a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-g15/run.py +++ b/tools/testing/selftests/drivers/gpu/asahi-g15/run.py @@ -260,13 +260,15 @@ def main(): with tempfile.TemporaryDirectory(prefix="asahi-g15-host-") as temp: temp = Path(temp) glue = (G15 / "glue.c").read_text() + # The UAT adoption's helpers, shared with the T8122 runtime. + uat_glue = (G15 / "uat_glue.c").read_text() functions = [] for signature in ["bool asahi_g15_ram_disjoint", "bool asahi_g15_ram_within", "unsigned int asahi_g15_memory_mode"]: marker = signature + "(u64 start, u64 size)\n{" - start = glue.index(marker) - end = glue.index("\n}", start) + 2 - functions.append(glue[start:end]) + start = uat_glue.index(marker) + end = uat_glue.index("\n}", start) + 2 + functions.append(uat_glue[start:end]) c_source = temp / "memory.c" c_source.write_text(MEMORY_PREFIX + "\n".join(functions) + MEMORY_CASES) subprocess.run([os.environ.get("HOSTCC", "cc"), "-std=gnu11", "-Wall", "-Wextra", From 18625569cf268f4030b674385df6232237be69ca Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 12:56:47 +1100 Subject: [PATCH 1198/1514] drm/asahi: m3: start the T8122 runtime where the boot loader hands the GPU over The T8122 runtime started by default, and registered its render node, only on a fixed list of boards (T8122_BOARDS: J613, J615, J504). The list stood for "a Mac on which the boot loader runs the G15G firmware for Linux". The device tree already says that: the boot loader puts its description of the firmware it loaded (apple,m3-handoff-version and the apple,firmware-segment-* properties) on the GPU node, and only when it hands the GPU over. Resource admission already refuses a GPU node without it. Select the default from that description instead of the board list: m3_board::handed_over() checks the GPU node for it, and the render-node default (asahi.m3_expose=auto), the backend choice and the start default (asahi.t8122_start omitted) use it. On the J613, J615 and J504 the boot loader hands the GPU over, so they start as before. A T8122 Mac whose boot loader does not hand the GPU over gets no render node and no start, as an unlisted board did before; one whose boot loader does is admitted by the same resource and firmware checks. Drop T8122_BOARDS, Soc::validated_boards and the test that pinned the list. The 26.6.2 interface choice (profile_for) is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/m3/m3_board.rs | 23 ++++++++++++--------- drivers/gpu/drm/asahi/m3/m3_drm.rs | 4 ++-- drivers/gpu/drm/asahi/m3/m3_params.rs | 10 ++++----- drivers/gpu/drm/asahi/m3/m3_soc.rs | 9 ++------ drivers/gpu/drm/asahi/m3/t8122_admission.rs | 17 --------------- drivers/gpu/drm/asahi/m3/t8122_knobs.rs | 11 +++++----- drivers/gpu/drm/asahi/m3/t8122_start.rs | 16 +++++++------- 7 files changed, 36 insertions(+), 54 deletions(-) diff --git a/drivers/gpu/drm/asahi/m3/m3_board.rs b/drivers/gpu/drm/asahi/m3/m3_board.rs index 5d4ea4277b6181..12b8409296ef6c 100644 --- a/drivers/gpu/drm/asahi/m3/m3_board.rs +++ b/drivers/gpu/drm/asahi/m3/m3_board.rs @@ -23,11 +23,14 @@ pub(crate) fn board_is(compatible: &[u8]) -> bool { board.split(|b| *b == 0).any(|s| s == compatible) } -/// Whether this is a board the M3 runtime is validated on (`soc.validated_boards`). -/// `asahi.m3_expose=auto` registers the render node and `asahi.m3_backend=auto` starts the -/// runtime only on these. -pub(crate) fn runtime_validated_board(soc: &Soc) -> bool { - soc.validated_boards.iter().any(|board| board_is(board)) +/// Whether the boot loader handed this GPU over: the GPU node carries the boot loader's +/// description of the firmware it loaded (`SEGMENT_PROPS`). A boot loader publishes it only on +/// a Mac where it runs that firmware for Linux, so this follows what the machine describes, +/// not a list of boards. `asahi.m3_expose=auto` registers the render node, and the runtime +/// starts by default, only then; resource admission ([`admit`]) checks the rest of the handoff. +pub(crate) fn handed_over(dev: &device::Device) -> bool { + dev.of_node() + .is_some_and(|node| SEGMENT_PROPS.iter().all(|p| node.get_property::>(p).is_ok())) } /// The number of core slots of `soc` (2 x 10 on T6030, 4 x 10 on T6031). @@ -547,12 +550,12 @@ pub(crate) fn region_is_nomap(node: &of::Node, name: &CStr) -> bool { /// Whether the M3 render node is registered (`asahi.m3_expose`). /// -/// Userspace drivers pick up any registered render node. Until the M3 runtime is validated on a -/// board, a render node there would let a stock userspace driver submit work the board may not -/// run correctly. `auto` (-1) registers it only on the boards the runtime was validated on. -pub(crate) fn expose_render_node(soc: &Soc) -> bool { +/// Userspace drivers pick up any registered render node. Without a boot loader that handed the +/// GPU over, a render node would let a stock userspace driver submit work nothing can run. +/// `auto` (-1) registers it only where the boot loader handed the GPU over ([`handed_over`]). +pub(crate) fn expose_render_node(dev: &device::Device) -> bool { match crate::m3::m3_params::expose() { Some(expose) => expose, - None => runtime_validated_board(soc), + None => handed_over(dev), } } diff --git a/drivers/gpu/drm/asahi/m3/m3_drm.rs b/drivers/gpu/drm/asahi/m3/m3_drm.rs index b11b612184ed9d..06d369ffd6a690 100644 --- a/drivers/gpu/drm/asahi/m3/m3_drm.rs +++ b/drivers/gpu/drm/asahi/m3/m3_drm.rs @@ -110,8 +110,8 @@ impl Backend { ) -> Result> { // The runtime only exists to back its render node: without one (`asahi.m3_expose=0`) // nothing is started, rather than leaving a running firmware behind a failed probe. - if !crate::m3::m3_board::expose_render_node(soc) { - dev_info!(pdev.as_ref(), "M3: render node not registered on this board (asahi.m3_expose=1 registers it); GPU not started\n"); + if !crate::m3::m3_board::expose_render_node(pdev.as_ref()) { + dev_info!(pdev.as_ref(), "M3: render node not registered: the boot loader did not hand the GPU over (asahi.m3_expose=1 registers it); GPU not started\n"); return Err(ENODEV); } let resources = crate::m3::m3_resources::from_device(pdev, soc).inspect_err(|_| { diff --git a/drivers/gpu/drm/asahi/m3/m3_params.rs b/drivers/gpu/drm/asahi/m3/m3_params.rs index 26735e7e9246bf..e2785c8ac1198e 100644 --- a/drivers/gpu/drm/asahi/m3/m3_params.rs +++ b/drivers/gpu/drm/asahi/m3/m3_params.rs @@ -589,9 +589,9 @@ pub(crate) fn thermal_hot_param() -> (u64, bool) { /// Whether to start the runtime backend on a T8122 (`asahi.m3_backend`), and say why not. /// -/// The runtime starts only on the boards the T8122 table allows (the M3 MacBook Airs and the -/// 14" M3 MacBook Pro, `t8122_admission::T8122_BOARDS`), with `auto` and `runtime` alike: -/// nothing forces it onto another board. The G15 manager backend is T6030-only. +/// The runtime starts only where the boot loader handed the GPU over +/// (`m3_board::handed_over`), with `auto` and `runtime` alike: nothing forces it onto a GPU +/// that was not handed over. The G15 manager backend is T6030-only. pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { let dev = pdev.as_ref(); match M3_BACKEND.load(Ordering::Relaxed) { @@ -606,11 +606,11 @@ pub(crate) fn t8122_backend(pdev: &platform::Device>) -> bool { ); false } - _ if crate::m3::m3_board::runtime_validated_board(&crate::m3::m3_soc::T8122) => true, + _ if crate::m3::m3_board::handed_over(dev) => true, _ => { dev_info!( dev, - "M3: no GPU backend on this T8122 board: the runtime backend may start only on the M3 MacBook Airs (J613, J615) and the 14\" M3 MacBook Pro (J504)\n" + "M3: no GPU backend: the boot loader did not hand the GPU over (no firmware segment description on the GPU node)\n" ); false } diff --git a/drivers/gpu/drm/asahi/m3/m3_soc.rs b/drivers/gpu/drm/asahi/m3/m3_soc.rs index 3dcd15c896a48f..a3d71c45207c6f 100644 --- a/drivers/gpu/drm/asahi/m3/m3_soc.rs +++ b/drivers/gpu/drm/asahi/m3/m3_soc.rs @@ -113,9 +113,6 @@ pub(crate) struct Soc { pub(crate) board: &'static str, /// GPU node compatible. pub(crate) gpu: &'static str, - /// Boards the runtime starts on by default and registers a render node on. On a T8122 it - /// starts on no other board, whatever `asahi.m3_backend` says (`m3_params::t8122_backend`). - pub(crate) validated_boards: &'static [&'static [u8]], /// GPU clusters, and core slots per cluster. pub(crate) clusters: u32, pub(crate) cores_per_cluster: u32, @@ -284,10 +281,8 @@ pub(crate) static T8122: Soc = Soc { gpu_revision_id: hw::GpuRevisionID::C0, board: "apple,t8122", gpu: "apple,agx-t8122", - // The M3 MacBook Airs (13" J613, 15" J615) and the 14" M3 MacBook Pro (J504), which loads - // the same G15G image (`t8122_admission::T8122_BOARDS`). The runtime starts only behind a - // boot loader that hands the GPU over. - validated_boards: &crate::m3::t8122_admission::T8122_BOARDS, + // The runtime starts only behind a boot loader that hands the GPU over + // (`m3_board::handed_over`). clusters: 1, cores_per_cluster: 10, mailbox_compatibles: &[ diff --git a/drivers/gpu/drm/asahi/m3/t8122_admission.rs b/drivers/gpu/drm/asahi/m3/t8122_admission.rs index ff6d098f50a3c5..fb280ebcde5202 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_admission.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_admission.rs @@ -4,12 +4,6 @@ use super::m3_profile::Profile; -/// The T8122 boards the M3 runtime starts on by default: the M3 MacBook Airs (13" J613, 15" J615) -/// and the 14" M3 MacBook Pro (J504). All three load the same 14.8.3 G15G image (UUID -/// `DF697F05-…`, checked separately by firmware admission). The other T8122 Macs (the J433 and -/// J434 iMacs) are not listed. -pub(crate) const T8122_BOARDS: [&[u8]; 3] = [b"apple,j613", b"apple,j615", b"apple,j504"]; - #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) struct Identity { pub(crate) active_cores: u32, @@ -201,17 +195,6 @@ pub(crate) fn read_identity_for( #[cfg(test)] mod tests { - use super::T8122_BOARDS; - - #[test] - fn the_t8122_runtime_boards_are_exactly_the_airs_and_the_14_inch_pro() { - // Exact: dropping the J504 or adding another T8122 Mac (J433, J434) must fail here. - assert_eq!(T8122_BOARDS, [&b"apple,j613"[..], b"apple,j615", b"apple,j504"]); - for other in [&b"apple,j433"[..], b"apple,j434", b"apple,t8122"] { - assert!(!T8122_BOARDS.contains(&other)); - } - } - use super::*; const G15G_C0: u32 = 0x0702_2000; diff --git a/drivers/gpu/drm/asahi/m3/t8122_knobs.rs b/drivers/gpu/drm/asahi/m3/t8122_knobs.rs index ca0f8a6d499ccd..f74cda0dc2ada3 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_knobs.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_knobs.rs @@ -132,11 +132,12 @@ pub(crate) fn start(raw: &Raw) -> Start { } } -/// The shipped board policy changes only an omitted start parameter. Explicit recovery-off, -/// explicit experimental start, and malformed values retain their original meanings. -/// Hardware resources and firmware identity are admitted separately by the caller. -pub(crate) fn start_for_board(raw: &Raw, admitted_board: bool) -> Start { - if raw.start == UNSET && admitted_board { +/// The shipped default changes only an omitted start parameter: it starts where the boot loader +/// handed the GPU over. Explicit recovery-off, explicit experimental start, and malformed values +/// retain their original meanings. Hardware resources and firmware identity are admitted +/// separately by the caller. +pub(crate) fn start_for_board(raw: &Raw, handed_over: bool) -> Start { + if raw.start == UNSET && handed_over { Start::On } else { start(raw) diff --git a/drivers/gpu/drm/asahi/m3/t8122_start.rs b/drivers/gpu/drm/asahi/m3/t8122_start.rs index f4fe2bae341aa5..44487af7656448 100644 --- a/drivers/gpu/drm/asahi/m3/t8122_start.rs +++ b/drivers/gpu/drm/asahi/m3/t8122_start.rs @@ -3,7 +3,7 @@ //! T8122 (M3, G15G) board-default startup and bounded experiment values. //! //! The T8122 table (`m3_soc::T8122`) is complete. An omitted start parameter starts -//! automatically only on its listed Air boards; explicit `asahi.t8122_start=0` +//! automatically only where the boot loader handed the GPU over; explicit `asahi.t8122_start=0` //! remains the recovery opt-out. Resource and known-firmware admission still run. //! The same table values can be changed for a controlled experiment by //! rebooting with a parameter: @@ -237,16 +237,16 @@ pub(crate) fn mmio_prot(read_only: u32, slot: usize) -> Prot { /// Decide, after resource admission, whether `soc` starts with the experiment values. /// -/// Any SoC but T8122: Ok(None). On its listed Air boards, an omitted parameter -/// selects the table values; explicit 0 disables startup, and invalid values fail -/// closed. Existing backend admission still refuses an unlisted board, even -/// with an explicit start request. +/// Any SoC but T8122: Ok(None). Where the boot loader handed the GPU over, an +/// omitted parameter selects the table values; explicit 0 disables startup, and +/// invalid values fail closed. Backend admission still refuses a GPU that was not +/// handed over, even with an explicit start request. pub(crate) fn arm(dev: &device::Device, soc: &Soc) -> Result> { if !is_t8122(soc) { return Ok(None); } let raw = crate::m3::m3_params::t8122_params(); - match knobs::start_for_board(&raw, crate::m3::m3_board::runtime_validated_board(soc)) { + match knobs::start_for_board(&raw, crate::m3::m3_board::handed_over(dev)) { Start::On => {} Start::Off => { if raw.values_given() { @@ -352,11 +352,11 @@ pub(crate) fn refused(dev: &device::Device, experiment: Option<&Experiment>, sta } } -/// Log that resource admission refused a T8122 start selected by board default or flag. +/// Log that resource admission refused a T8122 start selected by the handoff default or flag. pub(crate) fn not_admitted(dev: &device::Device, soc: &Soc) { if is_t8122(soc) && knobs::start_for_board( &crate::m3::m3_params::t8122_params(), - crate::m3::m3_board::runtime_validated_board(soc), + crate::m3::m3_board::handed_over(dev), ) == Start::On { dev_err!( dev, From 2ee237004c92457a51704fdc6724d4845e308526 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 12:57:18 +1100 Subject: [PATCH 1199/1514] pmdomain: apple: pmp-report: pick the T8122 GPU wait by the PMP's compatible apple_pmp_report_wait_supplier_ready() chose the T8122 14.x wait with of_machine_is_compatible("apple,t8122"), and the wait repeated that machine check next to the supplier check. The supplier's compatible is what identifies this PMP, so dispatch on it instead: a supplier that is an "apple,t8122-pmp-v2" takes the T8122 wait, every other supplier the T6030 one, which keeps its own checks. The wait no longer looks at the machine at all. Every T8122 device tree describes its PMP as "apple,t8122-pmp-v2", so the M3 MacBook Airs and the J504 take the same wait as before. A non-T8122 PMP on a T8122 machine was refused by the T8122 wait and is now refused by the T6030 one's compatible check. The host test follows: a T8122 PMP graph is now accepted whatever the root compatible says, a T6031 supplier on a T6030 machine is still refused, and the identity mutant keeps the supplier in use so it builds. Signed-off-by: Ryan Murray --- drivers/pmdomain/apple/pmp-report.c | 11 +++++------ tools/asahi/t6030-pmp-supplier-tests.c | 6 ++++-- tools/asahi/t6030-pmp-supplier-tests.py | 11 +++++------ 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/drivers/pmdomain/apple/pmp-report.c b/drivers/pmdomain/apple/pmp-report.c index 31784b43f3358a..76e72185bfbab9 100644 --- a/drivers/pmdomain/apple/pmp-report.c +++ b/drivers/pmdomain/apple/pmp-report.c @@ -702,8 +702,9 @@ static int apple_pmp_report_wait_t6030_14(struct device *supplier, unsigned int } /* - * The T8122 (M3 MacBook Air) GPU on its 14.8.3 firmware, for the M3 runtime - * (APPLE_T8122_GPU_PMP_LINK): the unique T8122 report linked to this PMP, and + * A T8122 PMP (apple,t8122-pmp-v2, chosen by the dispatch below) behind the GPU + * on its 14.8.3 firmware, for the M3 runtime (APPLE_T8122_GPU_PMP_LINK): the + * unique T8122 report linked to this PMP, and * its display request (DISP, reg 7) READY and acknowledged before AGX, as on * the 7.1.12 kernel that runtime was qualified with. */ @@ -712,9 +713,7 @@ static int apple_pmp_report_wait_t8122_14(struct device *supplier, unsigned int struct device_node *np, *report = NULL, *pmp, *entry; int ret; - if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK) || - !of_machine_is_compatible("apple,t8122") || - !of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2")) + if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK)) return -ENODEV; for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report") { if (report) { @@ -753,7 +752,7 @@ int apple_pmp_report_wait_supplier_ready(struct device *supplier, unsigned int t /* A declared report always takes the existing native25 path below. */ if (!np && !of_property_present(supplier->of_node, "apple,pmp-report")) { - if (of_machine_is_compatible("apple,t8122")) + if (of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2")) return apple_pmp_report_wait_t8122_14(supplier, timeout_ms); return apple_pmp_report_wait_t6030_14(supplier, timeout_ms); } diff --git a/tools/asahi/t6030-pmp-supplier-tests.c b/tools/asahi/t6030-pmp-supplier-tests.c index cea7041c01fb45..c32e373a0c7020 100644 --- a/tools/asahi/t6030-pmp-supplier-tests.c +++ b/tools/asahi/t6030-pmp-supplier-tests.c @@ -560,6 +560,7 @@ int main(void) RUN(machine = "apple,t6031", -ENODEV, 0, 0); RUN(machine = "apple,t8140", -ENODEV, 0, 0); RUN(supplier_node.compatible = "apple,t8122-pmp-v2", -ENODEV, 0, 0); + RUN(supplier_node.compatible = "apple,t6031-pmp-v2", -ENODEV, 0, 0); RUN(report14.compatible = NULL, -ENODEV, 0, 0); RUN(extra_report = report14, -ENODEV, 0, 0); RUN(extra_report = report14; @@ -602,8 +603,9 @@ int main(void) RUN(t8122(); passive_words[apple_pmp_offsets_t6030.actual / 8] = 0, -EIO, 0, 0); RUN(t8122(); power_result = -EIO, -EIO, 0, 1); - RUN(t8122(); machine = "apple,t6030", -ENODEV, 0, 0); - RUN(t8122(); machine = "apple,t8112", -ENODEV, 0, 0); + /* The PMP's compatible picks the wait, not the machine's. */ + RUN(t8122(); machine = "apple,t6030", 0, 0, 1); + RUN(t8122(); machine = "apple,t8112", 0, 0, 1); RUN(t8122(); supplier_node.compatible = "apple,t6030-pmp-v2", -ENODEV, 0, 0); RUN(t8122(); report14.compatible = NULL, -ENODEV, 0, 0); diff --git a/tools/asahi/t6030-pmp-supplier-tests.py b/tools/asahi/t6030-pmp-supplier-tests.py index aee98f9c599535..a2e4f4209a61a6 100755 --- a/tools/asahi/t6030-pmp-supplier-tests.py +++ b/tools/asahi/t6030-pmp-supplier-tests.py @@ -166,14 +166,13 @@ def with_t8122(source, text=t8122): variants = [(name, with_t8122(source)) for name, source in variants] if args.mutations: t8122_mutations = [ - ("t8122-config-scope", "if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK) ||", "if (false ||"), - ("t8122-supplier-compat", '!of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2"))', "false)"), + ("t8122-config-scope", "if (!IS_ENABLED(CONFIG_APPLE_T8122_GPU_PMP_LINK))", "if (false)"), ("t8122-report-compat", 'for_each_compatible_node(np, NULL, "apple,t8122-pmp-v2-report")', 'for_each_compatible_node(np, NULL, "apple,t6030-pmp-v2-report")'), ("t8122-duplicate-report", "\t\tif (report) {", "\t\tif (false) {"), ("t8122-disabled-report", "!of_device_is_available(report) ||", "false ||"), ("t8122-report-phandle-shape", 'of_property_count_u32_elems(report, "apple,pmp") != 1', "false"), - ("t8122-supplier-identity", "pmp == supplier->of_node && entry ?", "entry ?"), + ("t8122-supplier-identity", "pmp == supplier->of_node && entry ?", "supplier && entry ?"), ("t8122-readiness-error", "apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)) : -ENODEV;", "(apple_pmp_report_wait_ready(entry, msecs_to_jiffies(timeout_ms)), 0) : -ENODEV;"), ("t8122-entry-reference", "\tof_node_put(entry);\n\tof_node_put(pmp);", "\tof_node_put(pmp);"), @@ -181,9 +180,9 @@ def with_t8122(source, text=t8122): for name, old, new in t8122_mutations: assert t8122.count(old) == 1, (name, t8122.count(old)) variants.insert(-1, (name, with_t8122(code, t8122.replace(old, new)))) - # The dispatch owns the machine scope: T8122 takes the T8122 wait, every other SoC the - # T6030 one. (The wait's own machine check repeats it and cannot be reached otherwise.) - machine = 'if (of_machine_is_compatible("apple,t8122"))' + # The dispatch picks the wait by the supplier's compatible: a T8122 PMP takes the T8122 + # wait, every other supplier the T6030 one (which checks its own compatible). + machine = 'if (of_device_is_compatible(supplier->of_node, "apple,t8122-pmp-v2"))' assert code.count(machine) == 1 for name, new in (("t8122-dispatch-never", "if (false)"), ("t8122-dispatch-always", "if (true)")): variants.insert(-1, (name, with_t8122(code.replace(machine, new)))) From f5a5dcaddd7725cef535e4df2e7e1619c0cd6421 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 12:58:29 +1100 Subject: [PATCH 1200/1514] drm/apple: v14-board-test: drop the J504 base_edid check The board record no longer has a base_edid member on main, so the J504 case added with the J504 panel record does not build and the v14-board KUnit module with it. Drop that one check; the other J504 checks are unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/v14-board-test.c | 1 - 1 file changed, 1 deletion(-) diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index d79c2b79a9cbca..f6ec01c11c459a 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -273,7 +273,6 @@ static void v14_board_j504(struct kunit *test) KUNIT_EXPECT_TRUE(test, b->promotion); KUNIT_EXPECT_TRUE(test, b->log_bringup); KUNIT_EXPECT_TRUE(test, b->panel_nits); - KUNIT_EXPECT_FALSE(test, b->base_edid); KUNIT_EXPECT_EQ(test, b->ctm_set, air->ctm_set); KUNIT_EXPECT_EQ(test, b->ctm_get, air->ctm_get); KUNIT_EXPECT_TRUE(test, dcp_v14_board_admits(b, J613_DCP_IMAGE)); From a11083c6bdc00ccf6006cf2e0da2708146a58978 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 13:01:19 +1100 Subject: [PATCH 1201/1514] drm/apple: iomfb_v14_7: select the J504 record by its panel node The J504 internal-panel record was picked by the T8122 DCP compatible and the machine compatible (apple,j504), and its panel level block was admitted by adding apple,j504 to the machine list next to the record's own panel_nits flag. What the record holds is panel and firmware data (the J514S-size mini-LED panel, its 120 Hz timing, the level block, the J613 DCP image), and the J504 device tree already names that panel: the DCP has a panel child with apple,panel-j504. Give the board records an optional panel compatible, matched against the DCP's "panel" child (the lookup linux PR 2360 proposes for all records), and select the J504 record by the T8122 DCP and apple,panel-j504 instead of the machine. A record selected by its panel node was matched to that panel, so its panel_nits decides the level block; apple,j504 leaves the machine list. Nothing changes for the other records: they keep their machine compatibles and the machine list, and come first, so a J613 or J615 still gets its own record whatever its panel node says. The J504 gets the same record with the same flags as before. A T8122 Mac without the J504 panel node (J433, J434) still gets no record. The KUnit cases and the host panel test give the panel node and check that the J504 record follows it. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_v14_7.c | 33 +++++++++--- .../drm/apple/iomfb_v14_7_backlight_test.c | 52 +++++++++++++------ drivers/gpu/drm/apple/iomfb_v14_7_board.h | 11 +++- drivers/gpu/drm/apple/v14-board-test.c | 43 +++++++++++---- tools/asahi/dcp14-panel-tests.py | 18 +++++-- 5 files changed, 119 insertions(+), 38 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7.c b/drivers/gpu/drm/apple/iomfb_v14_7.c index 97279c844a6cec..bb6df87824fdc8 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7.c @@ -147,13 +147,15 @@ static const struct dcp_v14_board dcp_v14_board_j615 = { * The colour matrix methods are this image's, and so is the panel level * block the J613 qualified (brightness in nits, 500 at most here). Its swaps * keep zero timestamps as on the Airs. Every panel timing and the - * display clock are logged for the first boots. + * display clock are logged for the first boots. Selected by the T8122 DCP + * and the panel node the board device tree puts under it + * (apple,panel-j504), not by the machine. */ static const struct dcp_v14_board dcp_v14_board_j504 = { .name = "J504", .debugfs = "dcp-j504", .dcp_compatible = "apple,t8122-dcp", - .machine = "apple,j504", + .panel = "apple,panel-j504", .firmware_uuid = DCP_V14_J613_FIRMWARE_UUID, .handoff = "apple,t8122-handoff", .panel_width = 3024, @@ -1666,6 +1668,7 @@ static int dcp_v14_cpu_running(struct device *dev, const char *name) */ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, dcp_v14_compat_fn machine_is, + dcp_v14_compat_fn panel_is, const void *ctx, bool *dcp_known) { const struct dcp_v14_board *board; @@ -1679,6 +1682,8 @@ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, *dcp_known = true; if (board->machine && !machine_is(ctx, board->machine)) continue; + if (board->panel && !panel_is(ctx, board->panel)) + continue; return board; } return NULL; @@ -1699,13 +1704,22 @@ static bool dcp_v14_machine_is(const void *np, const char *compat) return of_machine_is_compatible(compat); } +/* The panel the board device tree puts under the DCP node. */ +static bool dcp_v14_panel_is(const void *np, const char *compat) +{ + struct device_node *panel __free(device_node) = + of_get_child_by_name(np, "panel"); + + return panel && of_device_is_compatible(panel, compat); +} + const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) { const struct dcp_v14_board *board; bool dcp_known; - board = dcp_v14_board_select(dcp_v14_node_is, dcp_v14_machine_is, dev->of_node, - &dcp_known); + board = dcp_v14_board_select(dcp_v14_node_is, dcp_v14_machine_is, dcp_v14_panel_is, + dev->of_node, &dcp_known); if (board) return board; if (dcp_known) { @@ -1715,13 +1729,18 @@ const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) return NULL; } +/* + * A record selected by its panel node was matched to that panel, so its own + * panel_nits decides; the records still selected by the machine keep their + * machine list. + */ static bool dcp_v14_panel_nits_admit(const struct dcp_v14_board *board, dcp_v14_compat_fn machine_is, const void *ctx) { return board && board->panel_nits && - (machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || - machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613") || - machine_is(ctx, "apple,j504")); + (board->panel || + machine_is(ctx, "apple,j514s") || machine_is(ctx, "apple,j516s") || + machine_is(ctx, "apple,j516c") || machine_is(ctx, "apple,j613")); } const char *iomfb_v14_7_board_name(const struct dcp_v14_board *board) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index ecbc37f54d0166..fe7f7cb6ab8594 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -122,47 +122,67 @@ static bool v14_bl_ctx_machine_is(const void *ctx, const char *compat) return !strcmp(((const char *const *)ctx)[1], compat); } -/* Only admitted T6030, J516C, J613 and J504 internal panels carry levels. */ +/* The DCP's panel node compatible; NULL: no panel node. */ +static bool v14_bl_ctx_panel_is(const void *ctx, const char *compat) +{ + const char *panel = ((const char *const *)ctx)[2]; + + return panel && !strcmp(panel, compat); +} + +/* Only admitted T6030, J516C and J613 internal panels and the J504 panel carry levels. */ static void v14_bl_boards(struct kunit *test) { - static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s" }; - static const char *const t6030_j514s[] = { "apple,t6030-dcp", "apple,j514s" }; - static const char *const j613[] = { "apple,t8122-dcp", "apple,j613" }; - static const char *const j615[] = { "apple,t8122-dcp", "apple,j615" }; - static const char *const j504[] = { "apple,t8122-dcp", "apple,j504" }; - static const char *const j516c[] = { "apple,t6031-dcp", "apple,j516c" }; - static const char *const other_t6030[] = { "apple,t6030-dcp", "apple,other" }; + static const char *const t6030_j516s[] = { "apple,t6030-dcp", "apple,j516s", NULL }; + static const char *const t6030_j514s[] = { "apple,t6030-dcp", "apple,j514s", NULL }; + static const char *const j613[] = { "apple,t8122-dcp", "apple,j613", NULL }; + static const char *const j615[] = { "apple,t8122-dcp", "apple,j615", NULL }; + static const char *const j504[] = { "apple,t8122-dcp", "apple,j504", "apple,panel-j504" }; + static const char *const j504_no_panel[] = { "apple,t8122-dcp", "apple,j504", NULL }; + static const char *const j516c[] = { "apple,t6031-dcp", "apple,j516c", NULL }; + static const char *const other_t6030[] = { "apple,t6030-dcp", "apple,other", NULL }; const struct dcp_v14_board *board; bool known; - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, t6030_j516s, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + t6030_j516s, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, t6030_j516s)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, t6030_j514s, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + t6030_j514s, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, t6030_j514s)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, other_t6030, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + other_t6030, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, other_t6030)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j613, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j613, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j613)); KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j615, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j615, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_FALSE(test, board->panel_nits); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j504, &known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j504, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j504)); - KUNIT_EXPECT_FALSE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j615)); - board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, j516c, &known); + /* The J504 record follows its panel node: without it the machine gets none. */ + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j504_no_panel, &known); + KUNIT_EXPECT_NULL(test, board); + KUNIT_EXPECT_TRUE(test, known); + board = dcp_v14_board_select(v14_bl_ctx_dcp_is, v14_bl_ctx_machine_is, v14_bl_ctx_panel_is, + j516c, &known); KUNIT_ASSERT_NOT_NULL(test, board); KUNIT_EXPECT_TRUE(test, board->panel_nits); KUNIT_EXPECT_TRUE(test, dcp_v14_panel_nits_admit(board, v14_bl_ctx_machine_is, j516c)); diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_board.h b/drivers/gpu/drm/apple/iomfb_v14_7_board.h index 6de1ae90041221..8394a99f3d2f50 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_board.h +++ b/drivers/gpu/drm/apple/iomfb_v14_7_board.h @@ -19,6 +19,8 @@ struct dcp_v14_board { const char *dcp_compatible; /* The machine compatible; NULL for any machine with this DCP. */ const char *machine; + /* The compatible of the DCP's "panel" child; NULL for any panel. */ + const char *panel; /* The firmware image whose layouts were tested on this board. */ const char *firmware_uuid; /* Set to <1> by the boot loader on the DCP, display and PIODMA nodes. */ @@ -50,16 +52,21 @@ struct dcp_v14_board { bool panel_nits; }; -/* Whether the DCP node or the machine (as @ctx gives them) has @compat. */ +/* + * Whether the DCP node, the machine or the DCP's panel node (as @ctx gives + * them) has @compat. + */ typedef bool (*dcp_v14_compat_fn)(const void *ctx, const char *compat); /* * The board record of a DCP. NULL if there is none: *@dcp_known then says * whether a record names the DCP's compatible (but no record is for this - * machine) or none does (not an internal 14.x DCP). + * machine and panel) or none does (not an internal 14.x DCP). A record with + * a machine is for that machine, one with a panel for a DCP with that panel. */ const struct dcp_v14_board *dcp_v14_board_select(dcp_v14_compat_fn dcp_is, dcp_v14_compat_fn machine_is, + dcp_v14_compat_fn panel_is, const void *ctx, bool *dcp_known); /* diff --git a/drivers/gpu/drm/apple/v14-board-test.c b/drivers/gpu/drm/apple/v14-board-test.c index f6ec01c11c459a..3148bc81c04586 100644 --- a/drivers/gpu/drm/apple/v14-board-test.c +++ b/drivers/gpu/drm/apple/v14-board-test.c @@ -21,6 +21,7 @@ struct board_ctx { const char *dcp; const char *const *machine; /* NULL-terminated root compatibles */ + const char *panel; /* the DCP's panel node compatible; NULL: none */ }; static bool board_ctx_dcp_is(const void *ctx, const char *compat) @@ -41,12 +42,26 @@ static bool board_ctx_machine_is(const void *ctx, const char *compat) return false; } +static bool board_ctx_panel_is(const void *ctx, const char *compat) +{ + const struct board_ctx *c = ctx; + + return c->panel && !strcmp(c->panel, compat); +} + +static const struct dcp_v14_board *board_for_panel(const char *dcp, const char *const *machine, + const char *panel, bool *known) +{ + const struct board_ctx ctx = { .dcp = dcp, .machine = machine, .panel = panel }; + + return dcp_v14_board_select(board_ctx_dcp_is, board_ctx_machine_is, board_ctx_panel_is, + &ctx, known); +} + static const struct dcp_v14_board *board_for(const char *dcp, const char *const *machine, bool *known) { - const struct board_ctx ctx = { .dcp = dcp, .machine = machine }; - - return dcp_v14_board_select(board_ctx_dcp_is, board_ctx_machine_is, &ctx, known); + return board_for_panel(dcp, machine, NULL, known); } static const char *const j516c[] = { "apple,j516c", "apple,t6031", "apple,arm-platform", NULL }; @@ -251,21 +266,22 @@ static void v14_swap_timestamps_encoding(struct kunit *test) /* * J504 (14" M3 MacBook Pro): the J613 image on the T8122 DCP, its own 3024x1964 - * ProMotion panel, the qualified level block (brightness) and unstamped swaps. The other T8122 - * Macs (J433, J434) have no record. + * ProMotion panel, the qualified level block (brightness) and unstamped swaps, selected by + * the DCP's panel node (apple,panel-j504). The other T8122 Macs (J433, J434) have no record. */ static void v14_board_j504(struct kunit *test) { const struct dcp_v14_board *b, *air; bool known; - b = board_for("apple,t8122-dcp", j504, &known); + b = board_for_panel("apple,t8122-dcp", j504, "apple,panel-j504", &known); KUNIT_ASSERT_NOT_NULL(test, b); air = board_for("apple,t8122-dcp", j613, &known); KUNIT_ASSERT_NOT_NULL(test, air); KUNIT_EXPECT_PTR_NE(test, b, air); KUNIT_EXPECT_STREQ(test, b->name, "J504"); - KUNIT_EXPECT_STREQ(test, b->machine, "apple,j504"); + KUNIT_EXPECT_NULL(test, b->machine); + KUNIT_EXPECT_STREQ(test, b->panel, "apple,panel-j504"); KUNIT_EXPECT_STREQ(test, b->handoff, "apple,t8122-handoff"); KUNIT_EXPECT_STREQ(test, b->firmware_uuid, J613_DCP_IMAGE); KUNIT_EXPECT_EQ(test, b->panel_width, 3024); @@ -282,8 +298,17 @@ static void v14_board_j504(struct kunit *test) KUNIT_EXPECT_NULL(test, board_for("apple,t8122-dcp", j433, &known)); KUNIT_EXPECT_TRUE(test, known); - /* A J504 root with another SoC's DCP gets no J504 record. */ - KUNIT_EXPECT_NULL(test, board_for("apple,t6031-dcp", j504, &known)); + /* The record follows the panel node, not the machine: none without it. */ + KUNIT_EXPECT_NULL(test, board_for("apple,t8122-dcp", j504, &known)); + KUNIT_EXPECT_TRUE(test, known); + KUNIT_EXPECT_NULL(test, board_for_panel("apple,t8122-dcp", j504, "apple,panel-j514", + &known)); + /* The Airs keep their machine records whatever the panel node says. */ + KUNIT_EXPECT_PTR_EQ(test, board_for_panel("apple,t8122-dcp", j613, "apple,panel-j504", + &known), air); + /* Another SoC's DCP with the J504 panel gets no J504 record. */ + KUNIT_EXPECT_NULL(test, board_for_panel("apple,t6031-dcp", j504, "apple,panel-j504", + &known)); } static struct kunit_case v14_board_cases[] = { diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index 19c02cafd82010..353996cca34047 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -32,12 +32,16 @@ #define IS_ERR(p) ((uintptr_t)(p) >= (uintptr_t)-4095) #define dev_err(...) ((void)0) #define MAX_NOTCH_HEIGHT 100 - struct device_node {const char *compatible;}; + struct device_node {const char *compatible;struct device_node *panel;}; + #define __free(x) struct device {struct device_node *of_node;}; static const char *machine; static bool of_device_is_compatible(const struct device_node *n,const char *c){return !strcmp(n->compatible,c);} static bool of_machine_is_compatible(const char*c){return !strcmp(machine,c);} - static struct device_node fb={"simple-framebuffer"},dcp={"apple,t8122-dcp"}; + /* The board DT's panel node under the DCP (compatible NULL: no panel node). */ + static struct device_node panel={NULL}; + static struct device_node fb={"simple-framebuffer"},dcp={"apple,t8122-dcp",&panel}; + static struct device_node *of_get_child_by_name(const struct device_node*n,const char*name){return strcmp(name,"panel")||!n->panel->compatible?NULL:n->panel;} static u32 width,height,stride,notch,marker_value=1; static const char *image_uuid; static int of_property_read_string(struct device_node*n,const char*k,const char**v){*v=image_uuid;return 0;} @@ -88,7 +92,10 @@ assert(!IS_ERR(j)&&j->panel_width==2560 && j->panel_height==1664); machine="apple,j700";assert(IS_ERR(iomfb_v14_7_board(&dev))); /* J504 (14" M3 MacBook Pro): the J613 image, the J514 panel, 60 or 120 Hz. */ - machine="apple,j504";const struct dcp_v14_board*p14=iomfb_v14_7_board(&dev); + /* Its record follows the panel node the J504 DT puts under the DCP, not the machine. */ + machine="apple,j504";assert(IS_ERR(iomfb_v14_7_board(&dev))); + panel.compatible="apple,panel-j514";assert(IS_ERR(iomfb_v14_7_board(&dev))); + panel.compatible="apple,panel-j504";const struct dcp_v14_board*p14=iomfb_v14_7_board(&dev); assert(!IS_ERR(p14)&&p14&&!strcmp(p14->name,"J504")&&!strcmp(p14->debugfs,"dcp-j504")); assert(p14->panel_width==3024&&p14->panel_height==1964&&p14->promotion&&p14->log_bringup); assert(!strcmp(p14->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); @@ -103,7 +110,10 @@ assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964&&q.notch_rows==74); height=1964;notch=0;assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964); width=2560;height=1600;stride=width*4;notch=64;assert(dcp_v14_geometry(&q)==-EINVAL);} - /* Other T8122 Macs (J433/J434 iMacs) have no record. */ + /* The Airs keep their machine records whatever the panel node says. */ + machine="apple,j613";assert(iomfb_v14_7_board(&dev)==j); + /* Other T8122 Macs (J433/J434 iMacs, no J504 panel) have no record. */ + panel.compatible=NULL; machine="apple,j433";assert(IS_ERR(iomfb_v14_7_board(&dev))); machine="apple,j434";assert(IS_ERR(iomfb_v14_7_board(&dev))); dcp.compatible="apple,t6030-dcp";machine="apple,j516s";assert(iomfb_v14_7_board(&dev)==&dcp_v14_board_t6030); From cdfa82f58037859cdfaaf7c69afff09d71fed5c2 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 02:24:42 +0000 Subject: [PATCH 1202/1514] drm/apple: update adaptive sync on an installed firmware-27 pair The same 4K240 timing and color can be installed twice when a paired display returns after resume. The second commit changes only the adaptive-sync minimum. It rebuilds both engines and blocks the compositor for almost another second. Keep a working pair when the installed timing, color and HDR state still match, and send the existing adaptive-sync parameter to both engines. Preserve the frame completion state. A command failure falls back to the full installation, as do changes to the installed mode. Signed-off-by: Diljit Singh --- drivers/gpu/drm/apple/dcp-peer-frames-v27.h | 13 +++++++++ .../gpu/drm/apple/dcp-peer-runtime-v27.inc | 29 +++++++++++++++++-- tools/asahi/dcp-peer-shown-tests.py | 13 +++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h index 749aea54992448..ebd747a52eb8c7 100644 --- a/drivers/gpu/drm/apple/dcp-peer-frames-v27.h +++ b/drivers/gpu/drm/apple/dcp-peer-frames-v27.h @@ -8,10 +8,23 @@ * outstanding swaps, as in the existing single-pipe retirement path. */ struct dcp_peer_frames_v27 { + u32 timing; + u32 color; + u32 min_vrr; + bool output_hdr; u32 first, submitted, engine[2], retired, shown[2]; bool active, armed, failed, have[2], have_retired, have_shown[2]; }; +static inline bool dcp_peer_vrr_only_v27(const struct dcp_peer_frames_v27 *frames, + u32 timing, u32 color, u32 min_vrr, + bool output_hdr) +{ + return frames->active && !frames->failed && frames->timing == timing && + frames->color == color && frames->min_vrr != min_vrr && + frames->output_hdr == output_hdr; +} + static inline void dcp_peer_frame_submit_v27(struct dcp_peer_frames_v27 *s, u32 id) { if (!s->armed) { diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index 4e6a5e68566caf..641aef85f7e77d 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -112,7 +112,7 @@ static int dcp_peer_limited_stop_v27(struct apple_dcp *dcp, struct apple_dcp *pe int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_vrr) { struct apple_dcp *peer; - bool limited, prepared; + bool limited, prepared, vrr_only; int ret = -EOPNOTSUPP; if (!peer_scanout || !peer_allocation_probe || @@ -145,11 +145,30 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v ret = -EBUSY; goto unlock; } + vrr_only = dcp->peer_tiling.modeset_complete && + peer->peer_tiling.modeset_complete && + dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, color, + min_vrr, dcp->output_hdr); } if (limited) { ret = dcp_peer_limited_stop_v27(dcp, peer); goto peer_unlock; } + /* + * Adaptive sync uses parameter 15 on both engines. Leave a running + * pair installed when its timing and color are still current. If + * either engine refuses the update, rebuild both with the new rate. + */ + if (vrr_only && !dcp_peer_param_v27(dcp, peer, 15, 3, min_vrr)) { + guard(mutex)(&dcp_peer_lock); + if (dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, color, + min_vrr, dcp->output_hdr)) { + dcp->peer_frames.min_vrr = min_vrr; + dev_dbg(dcp->dev, "paired adaptive sync minimum %#x\n", min_vrr); + ret = 0; + goto peer_unlock; + } + } ret = dcp_peer_prepare_v27(dcp, peer, min_vrr); if (ret) goto peer_unlock; @@ -158,7 +177,13 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v dcp_peer_finish_v27(dcp, peer); if (!ret) { guard(mutex)(&dcp_peer_lock); - dcp->peer_frames = (struct dcp_peer_frames_v27){ .active = true }; + dcp->peer_frames = (struct dcp_peer_frames_v27){ + .timing = timing, + .color = color, + .min_vrr = min_vrr, + .output_hdr = dcp->output_hdr, + .active = true, + }; dev_info(dcp->dev, "paired DRM mode ready: timing=%u color=%u min_vrr=%#x\n", timing, color, min_vrr); } diff --git a/tools/asahi/dcp-peer-shown-tests.py b/tools/asahi/dcp-peer-shown-tests.py index 1b26c2d3ab4080..ccf7dfae223f39 100644 --- a/tools/asahi/dcp-peer-shown-tests.py +++ b/tools/asahi/dcp-peer-shown-tests.py @@ -38,6 +38,19 @@ u32 w = 0; bool shown = true; + /* A new adaptive-sync minimum can reuse only the installed mode. */ + s = (struct dcp_peer_frames_v27){ .timing = 81, .color = 86, .active = true }; + assert(dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0, false)); + assert(!dcp_peer_vrr_only_v27(&s, 80, 86, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 85, 0x300000, false)); + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, true)); + s.failed = true; + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + s.failed = false; + s.active = false; + assert(!dcp_peer_vrr_only_v27(&s, 81, 86, 0x300000, false)); + /* First modeset of a pair: both engines display swap 5. */ s = paired(5, 5); assert(!dcp_peer_frame_complete_v27(&s, 0, 5, true, &w, &shown)); From f7a059d114dfb71bb6c67ba067fadbb73a3e0065 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:28:26 -0500 Subject: [PATCH 1203/1514] selftests: asahi-m4: update SignalBundle::publish mock for compute_only arg Update the SignalBundle::publish mock in test-fence-signalling.py to match the two-argument signature (fence, compute_only: bool), record compute_only in BundleLog, and assert !compute_only so G16 never invokes G17 compute-waiter effort accounting. Signed-off-by: Diljit Singh --- .../drivers/gpu/asahi-m4/test-fence-signalling.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 0843277bc93688..ffc523fa9f5e36 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -350,14 +350,20 @@ def extract_function(text, name): #[derive(Default)] pub(crate) struct BundleLog { pub(crate) published: Vec, + pub(crate) compute_only: Vec, pub(crate) failed: Vec, pub(crate) fail_publish: bool, } pub(crate) struct SignalBundle(pub(crate) Rc>); impl SignalBundle { - pub(crate) fn publish(&mut self, fence: &Fence) -> Result { + pub(crate) fn publish(&mut self, fence: &Fence, compute_only: bool) -> Result { + assert!( + !compute_only, + "G16 must not trigger G17 compute-waiter effort accounting" + ); let mut log = self.0.borrow_mut(); + log.compute_only.push(compute_only); if log.fail_publish { return Err(ENOMEM); } From cfb3fa775f77d341c418af8174e0eafa6d65e8df Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 02:32:20 +0000 Subject: [PATCH 1204/1514] arm64: dts: apple: t604x: enable PCIe CLKREQ# on M4 Pro/Max MacBook Pros Commit 2dd0986d434c ("arm64: dts: apple: t6041-j616c: enable PCIe CLKREQ# on Wi-Fi and SDXC") added supports-clkreq on port00 (BCM4388 Wi-Fi/BT) and port01 (GL9755 SDXC) only in t6041-j616c.dts, even though both shared MacBook Pro DTSIs already mux AP GPIO 0 and GPIO 1 via wifi_clkreq_pins and sd_clkreq_pins on pcie0 (matching the J616c ADT and J614c SD ADT pin): - t6041-j614c-j616c.dtsi (J614c and J616c, M4 Max) - t604x-j614-j616.dtsi (J614s and J616s, M4 Pro) Commit 2384bc598077 ("arm64: dts: apple: t8122-j615: keep CLKREQ# to the J615 until the J613 is checked") kept t8122 board-local because t8122.dtsi only carries a blanket SoC-level pinctrl. In contrast, these four MacBook Pro boards share the same t604x SoC family, apple,t6020-pcie controller (t602x_hw with PHY_LANE_CFG_REFCLKCGEN), identical BCM4388 + GL9755 endpoints, and board-family CLKREQ# pin muxing in the MBP DTSIs. Move supports-clkreq from t6041-j616c.dts into port00 and port01 of t6041-j614c-j616c.dtsi, and add supports-clkreq to port00 and port01 of t604x-j614-j616.dtsi so all four M4 Pro/Max MacBook Pros enable ASPM L1.1/L1.2 and Clock PM under the default ASPM policy. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi | 2 ++ arch/arm64/boot/dts/apple/t6041-j616c.dts | 13 ------------- arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi | 2 ++ 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index 6c88428a48ba50..1fad7b5df0900f 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -1687,6 +1687,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { @@ -1714,6 +1715,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index b353fe6af4fe29..ccdd779a5e5807 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -37,19 +37,6 @@ wake-gpios = <&pinctrl 40 GPIO_ACTIVE_HIGH>; }; -/* - * ADT apcie0/pci-bridge0 (Wi-Fi/BT) and pci-bridge1 (SDXC) wire CLKREQ# on - * GPIO 0 and GPIO 1 (pinctrl-0 in t6041-j614c-j616c.dtsi). Kept to J616c - * until J614c is tested. - */ -&port00 { - supports-clkreq; -}; - -&port01 { - supports-clkreq; -}; - &smc_gpio_low { apple,output-templates = <0xe 0x00800000>; }; diff --git a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi index 75df37d6053a61..16884a4c56e11e 100644 --- a/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-j614-j616.dtsi @@ -2727,6 +2727,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { @@ -3431,6 +3432,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; From f00931a915390c8c54f07119d9356a48a274aa33 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 02:28:43 +0000 Subject: [PATCH 1205/1514] arm64: dts: apple: t604x: enable PCIe CLKREQ# on Mac mini and Mac Studio Wi-Fi/SDXC Both T604x desktop DTS files already mux AP GPIO 0 (wifi_clkreq_pins) and on J575c AP GPIO 1 (sd_clkreq_pins) onto pcie0 via pinctrl-0, and their ADTs match J616c's pci-l1pm-control, default-apcie-options, and pci-aspm-default settings for those bridges: - t6040-j773s.dts (Mac mini, M4 Pro): port00 (BCM4388 Wi-Fi/BT) - t6041-j575c.dts (Mac Studio, M4 Max): port00 (BCM4388 Wi-Fi/BT) and port01 (GL9755 SDXC) Leave port02 (Ethernet) and J575c port03 (ASM3142 xHCI) without supports-clkreq for now: both Ethernet ADTs set no-refclk-gating with no pci-l1pm-control (and pcie-apple does not yet honor no-refclk-gating), while J575c pci-bridge3 has pci-aspm-default = 0, no pci-l1pm-control, and a long t-refclk-to-perst (200000). Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6040-j773s.dts | 1 + arch/arm64/boot/dts/apple/t6041-j575c.dts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6040-j773s.dts b/arch/arm64/boot/dts/apple/t6040-j773s.dts index 94f5ba02c2aec1..90da1d0fb13499 100644 --- a/arch/arm64/boot/dts/apple/t6040-j773s.dts +++ b/arch/arm64/boot/dts/apple/t6040-j773s.dts @@ -322,6 +322,7 @@ /* ADT /amfm reg_on gP13 */ pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth0: bluetooth@0,1 { diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index d6a16f00a5f49d..06ee0da56448f5 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1268,6 +1268,7 @@ #size-cells = <2>; pwren-gpios = <&smc_gpio 0x13 GPIO_ACTIVE_HIGH>; reset-gpios = <&pinctrl 4 GPIO_ACTIVE_LOW>; + supports-clkreq; device_type = "pci"; bluetooth@0,1 { @@ -1297,6 +1298,7 @@ reset-gpios = <&pinctrl 5 GPIO_ACTIVE_LOW>; bus-range = <2 2>; pwren-gpios = <&smc_gpio 0x19 GPIO_ACTIVE_HIGH>; + supports-clkreq; #address-cells = <3>; #size-cells = <2>; ranges; From 1f05b636b23e23f8a4ad83354d75caeedc96db1a Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:01 -0500 Subject: [PATCH 1206/1514] ci: trigger Apple build and KUnit workflow on main Include main in on.pull_request.branches and on.push.branches so the workflow runs on pull requests targeting main and pushes to main. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .github/workflows/apple-build-kunit.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/apple-build-kunit.yml b/.github/workflows/apple-build-kunit.yml index 431cc715d8dda2..51354983d82206 100644 --- a/.github/workflows/apple-build-kunit.yml +++ b/.github/workflows/apple-build-kunit.yml @@ -11,7 +11,7 @@ name: Apple build and KUnit on: pull_request: - branches: [integration/aurora, aurora-wip] + branches: [main, integration/aurora, aurora-wip] paths: - 'arch/arm64/configs/**' - 'drivers/accel/ane/**' @@ -38,7 +38,7 @@ on: - '.github/workflows/apple-build-kunit.yml' # Same paths as pull_request, so an unrelated merge does not start the jobs. push: - branches: [integration/aurora] + branches: [main, integration/aurora] paths: - 'arch/arm64/configs/**' - 'drivers/accel/ane/**' From 9fa8c0838f8cf6f95b4620cb0a2bfc69881478a9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:44:52 -0500 Subject: [PATCH 1207/1514] drm/apple: recheck paired DCP state after adaptive-sync RPC dcp_peer_modeset_v27() drops dcp_peer_lock across the blocking dcp_peer_param_v27() calls to both engines. While unlocked, dcp_peer_release_locked() or a platform-limit change can clear modeset_complete, release the peer reservation, or impose the pair limit without clearing peer_frames.active. Re-verify peer ownership, platform limit, and both engines' modeset_complete flags under dcp_peer_lock after dcp_peer_param_v27() returns. Return -EBUSY if ownership was lost, stop a newly limited pair outside dcp_peer_lock via dcp_peer_limited_stop_v27() (or return -EOPNOTSUPP if already unprepared), and otherwise fall through to the full pair rebuild when the fast path is no longer valid. Signed-off-by: Diljit Singh --- .../gpu/drm/apple/dcp-peer-runtime-v27.inc | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc index 641aef85f7e77d..647d691f356524 100644 --- a/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc +++ b/drivers/gpu/drm/apple/dcp-peer-runtime-v27.inc @@ -159,13 +159,35 @@ int dcp_peer_modeset_v27(struct apple_dcp *dcp, u32 timing, u32 color, u32 min_v * pair installed when its timing and color are still current. If * either engine refuses the update, rebuild both with the new rate. */ - if (vrr_only && !dcp_peer_param_v27(dcp, peer, 15, 3, min_vrr)) { - guard(mutex)(&dcp_peer_lock); - if (dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, color, - min_vrr, dcp->output_hdr)) { - dcp->peer_frames.min_vrr = min_vrr; - dev_dbg(dcp->dev, "paired adaptive sync minimum %#x\n", min_vrr); - ret = 0; + if (vrr_only) { + bool still_owned, updated = false; + + ret = dcp_peer_param_v27(dcp, peer, 15, 3, min_vrr); + scoped_guard(mutex, &dcp_peer_lock) { + still_owned = dcp->peer_reserved == peer && + peer->peer_owner == dcp; + limited = still_owned && + dcp_peer_limited_pair_locked(dcp, &prepared); + if (!ret && !limited && still_owned && + dcp->peer_tiling.modeset_complete && + peer->peer_tiling.modeset_complete && + dcp_peer_vrr_only_v27(&dcp->peer_frames, timing, + color, min_vrr, + dcp->output_hdr)) { + dcp->peer_frames.min_vrr = min_vrr; + dev_dbg(dcp->dev, "paired adaptive sync minimum %#x\n", min_vrr); + updated = true; + } + } + if (updated) + goto peer_unlock; + if (!still_owned) { + ret = -EBUSY; + goto peer_unlock; + } + if (limited) { + ret = prepared ? dcp_peer_limited_stop_v27(dcp, peer) + : -EOPNOTSUPP; goto peer_unlock; } } From 8c18c5f203dbce116521281197547a6c1865f660 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:41 +0000 Subject: [PATCH 1208/1514] dt-bindings: power: apple,pmgr-pwrstate: add apple,auto-managed Add the apple,auto-managed boolean property for hardware-managed power domains (such as DRAM channel slices and memory fabrics) that the boot loader may leave forced on and that must be switched to hardware automatic power management (AUTO_ENABLE) early at boot, before the PMP firmware starts. Disallow combining apple,auto-managed with apple,no-auto-pm, apple,firmware-owned, apple,inherited-on, or apple,t8132-pmgr-pwrstate. Signed-off-by: AxxzyWasTaken --- .../bindings/power/apple,pmgr-pwrstate.yaml | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml index bc7a15af64b291..999c31c461f2c8 100644 --- a/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml +++ b/Documentation/devicetree/bindings/power/apple,pmgr-pwrstate.yaml @@ -25,11 +25,30 @@ allOf: apple,sleep-retained: false apple,sleep-driver-owned: false apple,always-on: false + apple,auto-managed: false apple,min-state: false apple,force-disable: false apple,force-reset: false apple,externally-clocked: false apple,consumer-switched: false + - if: + properties: + compatible: + contains: + const: apple,t8132-pmgr-pwrstate + required: + - compatible + then: + properties: + apple,auto-managed: false + - if: + required: + - apple,auto-managed + then: + properties: + apple,no-auto-pm: false + apple,firmware-owned: false + apple,inherited-on: false - if: required: - apple,consumer-switched @@ -136,6 +155,18 @@ properties: coprocessors' CPU domains. type: boolean + apple,auto-managed: + description: | + Hardware-managed power domain (such as a DRAM channel slice or memory + fabric) that the boot loader may leave forced on and that must be + switched to hardware automatic power management (auto-enable) early + at boot, before the PMP firmware starts. + + Once switched, the hardware gates the domain by itself and it has no + software-controlled power transitions. On parts where an instance is + fused off, its power-state register reads as off. + type: boolean + apple,sleep-retained: description: A coprocessor keeps running in this domain across system sleep with no From d5c35d630ca4d08abe474c9ba1dd37f72b418141 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:42 +0000 Subject: [PATCH 1209/1514] pmdomain: apple: pmgr-pwrstate: enable auto-managed domains early at boot Early at boot, before the PMP starts, hardware-managed power domains left forced on by iBoot must be switched to automatic power management (write target 0xf, wait for actual 0xf, then set AUTO_ENABLE). On Apple Silicon systems where iBoot leaves memory channel or fabric domains forced on, enabling AUTO_ENABLE after PMP is running freezes the SoC. Walk available apple,auto-managed PMGR power-state nodes at arch_initcall via their parent syscon regmap and switch forced-on words to AUTO_ENABLE, leaving fused-off, reset, or already auto-managed words untouched. At probe time, reject apple,t8132-pmgr-pwrstate consistently with the binding, fail loudly with -EIO if an apple,always-on auto-managed domain is off at boot, skip non-always-on off (fused-off) auto-managed domains with -ENODEV, and register active ones as always-on without rewriting the register after PMP may have started, refusing power-off and reset operations and skipping them in suspend_noirq and resume_noirq so firmware wake never rewrites AUTO_ENABLE while PMP is running. Add KUnit tests for apple_pmgr_ps_auto_enable() and cover the inherited-on conflict in pmgr-inherited.py. Signed-off-by: AxxzyWasTaken --- drivers/pmdomain/apple/pmgr-pwrstate-test.c | 77 ++++++++ drivers/pmdomain/apple/pmgr-pwrstate.c | 172 ++++++++++++++++-- .../selftests/drivers/apple/pmgr-inherited.py | 2 +- 3 files changed, 233 insertions(+), 18 deletions(-) diff --git a/drivers/pmdomain/apple/pmgr-pwrstate-test.c b/drivers/pmdomain/apple/pmgr-pwrstate-test.c index 3eaa22999e87f0..e7449c1dbee8ab 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate-test.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate-test.c @@ -752,6 +752,80 @@ static void pmgr_ps_reset_busy_no_idle_wait_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, r->val & (APPLE_PMGR_DEV_DISABLE | APPLE_PMGR_RESET)); } +/* Forced-on auto-managed words write target 0xf, wait for actual 0xf, then AUTO_ENABLE. */ +static void pmgr_ps_auto_enable_test(struct kunit *test) +{ + static const u32 seq[][2] = { + { 0, 0x0f0000ff }, + { 0, 0x1f0000ff }, + }; + struct pmgr_ps_test_bank *b; + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_consumer(test, 0x0f0003ff, &b); + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 1); + pmgr_ps_test_expect_log(test, b, seq, ARRAY_SIZE(seq)); + KUNIT_EXPECT_TRUE(test, b->word[0] & APPLE_PMGR_AUTO_ENABLE); + + /* Delayed actual-state ACK completes before AUTO_ENABLE is written. */ + ps = pmgr_ps_test_domain(test, APPLE_PMGR_PS_CLKGATE, false, &r); + r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE) | + FIELD_PREP(APPLE_PMGR_PS_ACTUAL, APPLE_PMGR_PS_CLKGATE) | + APPLE_PMGR_FLAGS; + r->active_reads = 3; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 1); + KUNIT_EXPECT_EQ(test, r->active_reads, 0U); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_PMGR_PS_ACTUAL, r->val), APPLE_PMGR_PS_ACTIVE); + KUNIT_EXPECT_TRUE(test, r->val & APPLE_PMGR_AUTO_ENABLE); + KUNIT_EXPECT_EQ(test, r->auto_writes, 1U); + KUNIT_EXPECT_EQ(test, r->busy_writes, 0U); +} + +/* Fused-off, already-AUTO, and reset/disabled words are left completely untouched. */ +static void pmgr_ps_auto_enable_skip_test(struct kunit *test) +{ + static const u32 skipped[] = { + 0x0f000300, /* fused off (J616c dcs_24-31) */ + 0x1f0000ff, /* already on AUTO_ENABLE */ + 0x0f0000ff | APPLE_PMGR_RESET, /* held in reset */ + 0x0f0000ff | APPLE_PMGR_PS_RESET, /* PS reset set */ + 0x0f0000ff | APPLE_PMGR_DEV_DISABLE, /* device disabled */ + }; + struct pmgr_ps_test_bank *b; + struct apple_pmgr_ps *ps; + + for (unsigned int i = 0; i < ARRAY_SIZE(skipped); i++) { + ps = pmgr_ps_test_consumer(test, skipped[i], &b); + KUNIT_EXPECT_EQ_MSG(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), 0, + "word %#x", skipped[i]); + KUNIT_EXPECT_EQ_MSG(test, b->nr_log, 0U, "word %#x", skipped[i]); + KUNIT_EXPECT_EQ_MSG(test, b->word[0], skipped[i], "word %#x", skipped[i]); + } +} + +/* Stuck actual state times out without setting AUTO_ENABLE; read errors propagate. */ +static void pmgr_ps_auto_enable_fail_test(struct kunit *test) +{ + struct pmgr_ps_test_reg *r; + struct apple_pmgr_ps *ps; + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-auto-stuck", + APPLE_PMGR_PS_CLKGATE, false, &r); + r->val = FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE) | + FIELD_PREP(APPLE_PMGR_PS_ACTUAL, APPLE_PMGR_PS_CLKGATE); + r->stuck = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); + KUNIT_EXPECT_FALSE(test, r->val & APPLE_PMGR_AUTO_ENABLE); + + ps = pmgr_ps_test_named_domain(test, "apple-pmgr-ps-auto-err", + APPLE_PMGR_PS_ACTIVE, false, &r); + r->parent_read_error = true; + KUNIT_EXPECT_EQ(test, apple_pmgr_ps_auto_enable(ps->regmap, 0), -EIO); + KUNIT_EXPECT_EQ(test, r->auto_writes, 0U); +} + static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_power_on_test), KUNIT_CASE(pmgr_ps_power_off_undo_test), @@ -776,6 +850,9 @@ static struct kunit_case pmgr_ps_test_cases[] = { KUNIT_CASE(pmgr_ps_reset_refused_test), KUNIT_CASE(pmgr_ps_reset_idle_wait_test), KUNIT_CASE(pmgr_ps_reset_busy_no_idle_wait_test), + KUNIT_CASE(pmgr_ps_auto_enable_test), + KUNIT_CASE(pmgr_ps_auto_enable_skip_test), + KUNIT_CASE(pmgr_ps_auto_enable_fail_test), {} }; diff --git a/drivers/pmdomain/apple/pmgr-pwrstate.c b/drivers/pmdomain/apple/pmgr-pwrstate.c index 6745b4916365b6..709037c9b2787d 100644 --- a/drivers/pmdomain/apple/pmgr-pwrstate.c +++ b/drivers/pmdomain/apple/pmgr-pwrstate.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -79,6 +80,8 @@ struct apple_pmgr_ps { bool sleep_wakeup_path; /* Never enable automatic power management (apple,no-auto-pm). */ bool no_auto_pm; + /* Hardware auto-managed domain armed early at boot (apple,auto-managed). */ + bool auto_managed; bool inherited_on; bool no_auto_enable; bool needs_reset_idle_wait; @@ -437,7 +440,7 @@ static int apple_pmgr_ps_power_off(struct generic_pm_domain *genpd) if (ps->firmware_owned) return 0; - if (ps->inherited_on) + if (ps->inherited_on || ps->auto_managed) return -EBUSY; /* A live coprocessor keeps this domain through system sleep. */ if (ps->sleep_retained && ps->system_sleep) @@ -478,7 +481,7 @@ int apple_pmgr_ps_verify_state(struct device *domain_dev, bool on) !(genpd->flags & GENPD_FLAG_IRQ_SAFE)) return -EOPNOTSUPP; ps = genpd_to_apple_pmgr_ps(genpd); - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; if (!on) mask |= APPLE_PMGR_AUTO_ENABLE; @@ -516,7 +519,7 @@ int apple_pmgr_ps_cycle(struct device_node *np) ret = -EPROBE_DEFER; goto out; } - if (ps->firmware_owned || ps->inherited_on) { + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) { ret = -EPERM; goto out; } @@ -591,7 +594,7 @@ static int apple_pmgr_ps_suspend_noirq(struct device *dev) u32 reg; ps->sleep_raised_by_other = false; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return 0; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -640,7 +643,8 @@ static int apple_pmgr_ps_resume_noirq(struct device *dev) int ret; if (!pm_resume_via_firmware() || ps->firmware_owned || ps->inherited_on || - ps->sleep_driver_owned || apple_sleep_domain_is_down(dev->of_node)) + ps->auto_managed || ps->sleep_driver_owned || + apple_sleep_domain_is_down(dev->of_node)) return 0; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -680,7 +684,7 @@ static int apple_pmgr_reset_assert(struct reset_controller_dev *rcdev, unsigned int ret; u32 reg; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; spin_lock_irqsave(&ps->genpd.slock, flags); @@ -718,7 +722,7 @@ static int apple_pmgr_reset_deassert(struct reset_controller_dev *rcdev, unsigne struct apple_pmgr_ps *ps = rcdev_to_apple_pmgr_ps(rcdev); unsigned long flags; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; if (ps->reset_time_us == APPLE_PMGR_T8132_RESET_TIME) @@ -760,7 +764,7 @@ static int apple_pmgr_reset_status(struct reset_controller_dev *rcdev, unsigned struct apple_pmgr_ps *ps = rcdev_to_apple_pmgr_ps(rcdev); u32 reg = 0; - if (ps->firmware_owned || ps->inherited_on) + if (ps->firmware_owned || ps->inherited_on || ps->auto_managed) return -EPERM; regmap_read(ps->regmap, ps->offset, ®); @@ -951,6 +955,9 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) ps->sleep_retained = of_property_read_bool(node, "apple,sleep-retained"); ps->sleep_driver_owned = of_property_read_bool(node, "apple,sleep-driver-owned"); ps->sleep_wakeup_path = of_property_read_bool(node, "apple,sleep-wakeup-path"); + /* A cold-started coprocessor CPU must not be gated behind its firmware. */ + ps->no_auto_pm = of_property_read_bool(node, "apple,no-auto-pm"); + ps->auto_managed = of_property_read_bool(node, "apple,auto-managed"); /* * Only T8132 hands over inherited-on domains with this contract. Older * M3 device trees carry the property with another meaning; keep them @@ -958,7 +965,7 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) */ ps->inherited_on = t8132 && of_property_read_bool(node, "apple,inherited-on"); if (ps->inherited_on && - (ps->firmware_owned || ps->sleep_retained || + (ps->firmware_owned || ps->sleep_retained || ps->auto_managed || of_property_present(node, "apple,min-state") || of_property_present(node, "apple,always-on") || of_property_present(node, "apple,force-disable") || @@ -966,8 +973,13 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) of_property_present(node, "apple,externally-clocked"))) return dev_err_probe(dev, -EINVAL, "conflicting inherited power policy\n"); + if (ps->auto_managed && + (ps->firmware_owned || ps->no_auto_pm || ps->no_auto_enable || t8132)) + return dev_err_probe(dev, -EINVAL, "conflicting auto-managed power policy\n"); + ret = of_property_read_u32(node, "apple,min-state", &ps->min_state); - if (ret == 0 && ps->min_state <= APPLE_PMGR_PS_ACTIVE && !ps->firmware_owned) + if (ret == 0 && ps->min_state <= APPLE_PMGR_PS_ACTIVE && + !ps->firmware_owned && !ps->auto_managed) regmap_update_bits(regmap, ps->offset, APPLE_PMGR_FLAGS | APPLE_PMGR_PS_MIN, FIELD_PREP(APPLE_PMGR_PS_MIN, ps->min_state)); @@ -980,9 +992,6 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) if (of_property_read_bool(node, "apple,externally-clocked")) ps->externally_clocked = true; - /* A cold-started coprocessor CPU must not be gated behind its firmware. */ - ps->no_auto_pm = of_property_read_bool(node, "apple,no-auto-pm"); - /* * An inherited-on domain has readable state but no transition ownership. * A firmware-owned domain need not have a CPU-accessible state register; @@ -1003,9 +1012,19 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot read power state\n"); active = ret; } - /* Legacy handoff DTs must also keep the throttle controller powered. */ - if (!ps->firmware_owned && !ps->inherited_on && - apple_pmgr_ps_always_on(node, ps->offset, name)) { + if (ps->auto_managed) { + if (!active) { + if (apple_pmgr_ps_always_on(node, ps->offset, name)) + return dev_err_probe(dev, -EIO, + "always-on auto-managed domain %s is off at boot\n", + name); + dev_dbg(dev, "auto-managed domain %s is off at boot, skipping\n", name); + return -ENODEV; + } + ps->genpd.flags |= GENPD_FLAG_ALWAYS_ON; + } else if (!ps->firmware_owned && !ps->inherited_on && + apple_pmgr_ps_always_on(node, ps->offset, name)) { + /* Legacy handoff DTs must also keep the throttle controller powered. */ ps->genpd.flags |= GENPD_FLAG_ALWAYS_ON; if (!active) { /* @@ -1035,7 +1054,8 @@ static int apple_pmgr_ps_probe(struct platform_device *pdev) } /* Turn on auto-PM if the domain is already on, unless it must stay off */ - if (active && !ps->firmware_owned && !ps->inherited_on && !ps->no_auto_enable) + if (active && !ps->firmware_owned && !ps->inherited_on && + !ps->no_auto_enable && !ps->auto_managed) regmap_update_bits(regmap, ps->offset, APPLE_PMGR_FLAGS | APPLE_PMGR_AUTO_ENABLE, ps->no_auto_pm ? 0 : APPLE_PMGR_AUTO_ENABLE); @@ -1390,6 +1410,124 @@ static const struct of_device_id apple_pmgr_ps_of_match[] = { MODULE_DEVICE_TABLE(of, apple_pmgr_ps_of_match); +/* + * Switch a power-state word left forced on by the boot loader (target 0xf, + * AUTO_ENABLE clear) to hardware automatic power management, early at boot, + * before the PMP starts: write target 0xf, wait for actual 0xf, then set + * AUTO_ENABLE. Words that are fused off, not forced on, held in reset, or + * already on AUTO_ENABLE are left untouched (returns 0). Returns 1 if + * switched, or a negative errno on read/write error or timeout. + */ +static int apple_pmgr_ps_auto_enable(struct regmap *regmap, u32 offset) +{ + u32 v; + int ret; + + ret = regmap_read(regmap, offset, &v); + if (ret) + return ret; + + if (FIELD_GET(APPLE_PMGR_PS_TARGET, v) != APPLE_PMGR_PS_ACTIVE || + (v & (APPLE_PMGR_AUTO_ENABLE | APPLE_PMGR_RESET | + APPLE_PMGR_PS_RESET | APPLE_PMGR_DEV_DISABLE))) + return 0; + + ret = regmap_write(regmap, offset, + (v & ~(APPLE_PMGR_FLAGS | APPLE_PMGR_BUSY | + APPLE_PMGR_PS_TARGET)) | + FIELD_PREP(APPLE_PMGR_PS_TARGET, APPLE_PMGR_PS_ACTIVE)); + if (ret) + return ret; + + ret = regmap_read_poll_timeout_atomic(regmap, offset, v, + FIELD_GET(APPLE_PMGR_PS_ACTUAL, v) == + APPLE_PMGR_PS_ACTIVE, + 1, APPLE_PMGR_PS_PARENT_TIMEOUT); + if (ret) + return ret; + + ret = regmap_write(regmap, offset, + (v & ~(APPLE_PMGR_FLAGS | APPLE_PMGR_BUSY)) | + APPLE_PMGR_AUTO_ENABLE); + return ret ?: 1; +} + +static const struct of_device_id apple_pmgr_of_match[] __initconst = { + { .compatible = "apple,t8103-pmgr" }, + { .compatible = "apple,pmgr" }, + {} +}; + +static bool __init apple_pmgr_ps_node_is_auto_managed(struct device_node *np) +{ + return of_match_node(apple_pmgr_ps_of_match, np) && + of_property_read_bool(np, "apple,auto-managed") && + !of_property_read_bool(np, "apple,no-auto-pm") && + !of_property_read_bool(np, "apple,firmware-owned") && + !of_property_read_bool(np, "apple,inherited-on") && + !of_device_is_compatible(np, "apple,t8132-pmgr-pwrstate"); +} + +/* + * Arm hardware automatic power management for DT-marked domains early at + * boot, before platform drivers (in particular the PMP) start: enabling + * AUTO_ENABLE on memory and fabric domains after the PMP is running freezes + * the SoC. + */ +static int __init apple_pmgr_ps_auto_init(void) +{ + struct device_node *pmgr_np; + unsigned int done = 0, failed = 0; + + for_each_matching_node(pmgr_np, apple_pmgr_of_match) { + struct regmap *regmap = NULL; + struct device_node *child; + + if (!of_device_is_available(pmgr_np)) + continue; + + for_each_available_child_of_node(pmgr_np, child) { + u32 offset; + int ret; + + if (!apple_pmgr_ps_node_is_auto_managed(child)) + continue; + + if (of_property_read_u32(child, "reg", &offset)) { + pr_warn("apple-pmgr-pwrstate: %pOF: missing reg property\n", + child); + continue; + } + + if (!regmap) { + regmap = syscon_node_to_regmap(pmgr_np); + if (IS_ERR(regmap)) { + pr_warn("apple-pmgr-pwrstate: %pOF: cannot map PMGR: %ld\n", + pmgr_np, PTR_ERR(regmap)); + of_node_put(child); + break; + } + } + + ret = apple_pmgr_ps_auto_enable(regmap, offset); + if (ret > 0) { + done++; + } else if (ret < 0) { + failed++; + pr_warn("apple-pmgr-pwrstate: %pOF: auto-enable failed: %d\n", + child, ret); + } + } + } + + if (done || failed) + pr_info("apple-pmgr-pwrstate: %u auto-managed domains enabled, %u failed\n", + done, failed); + + return 0; +} +arch_initcall(apple_pmgr_ps_auto_init); + static const struct dev_pm_ops apple_pmgr_ps_pm_ops = { LATE_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_late, apple_pmgr_ps_resume_early) NOIRQ_SYSTEM_SLEEP_PM_OPS(apple_pmgr_ps_suspend_noirq, apple_pmgr_ps_resume_noirq) diff --git a/tools/testing/selftests/drivers/apple/pmgr-inherited.py b/tools/testing/selftests/drivers/apple/pmgr-inherited.py index affc0312450b10..ac2538d2364acf 100755 --- a/tools/testing/selftests/drivers/apple/pmgr-inherited.py +++ b/tools/testing/selftests/drivers/apple/pmgr-inherited.py @@ -223,7 +223,7 @@ def main(): assert(apple_pmgr_ps_power_off(&ps->genpd)==-EBUSY && !map.writes); puts("ok 3 - read errors and lost inherited activity never request a transition"); const char *conflicts[]={"apple,firmware-owned","apple,sleep-retained","apple,always-on","apple,min-state", - "apple,force-disable","apple,force-reset","apple,externally-clocked"}; + "apple,force-disable","apple,force-reset","apple,externally-clocked","apple,auto-managed"}; for(unsigned i=0;i Date: Tue, 24 Nov 2026 14:28:42 +0000 Subject: [PATCH 1210/1514] arm64: dts: apple: t6041: describe auto-managed DCS and fabric power states Add t6041-pmgr.dtsi describing the 32 DCS channel power states (dcs_00-31, with dcs_27 at pmgr_aux +0x530) and 12 fabric power states (fab0-7_soc, fab_gw_0/1, fab_afr, nub_fabric) verified against the J616c ADT, and mark them apple,auto-managed so the PMGR driver switches forced-on words to AUTO_ENABLE early at boot before PMP starts. On binned 24-channel parts (J616c), dcs_24-31 read fused off and are skipped cleanly (36 active words switched); on full 32-channel parts (J614c), all 44 words are switched. Drop the duplicate disabled ps_fab5_soc node from t6041-j614-j616-j575-scaler.dtsi and the duplicate ps_fab1_soc node from t6041.dtsi now that t6041-pmgr.dtsi provides and enables both as apple,always-on with apple,auto-managed. Signed-off-by: AxxzyWasTaken --- .../apple/t6041-j614-j616-j575-scaler.dtsi | 13 - arch/arm64/boot/dts/apple/t6041-pmgr.dtsi | 424 ++++++++++++++++++ arch/arm64/boot/dts/apple/t6041.dtsi | 18 +- 3 files changed, 429 insertions(+), 26 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6041-pmgr.dtsi diff --git a/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi b/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi index 34ecb3b560df99..6140cc718d11c6 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614-j616-j575-scaler.dtsi @@ -26,19 +26,6 @@ }; }; -&pmgr_aux { - ps_fab5_soc: power-controller@440 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x440 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "fab5_soc"; - power-domains = <&ps_afi>; - apple,always-on; - status = "disabled"; - }; -}; - /* PMGR group 1 resolves via ps-groups to the main bank at 0x502280000. */ &pmgr { ps_msr1: ps_msr1_dart: power-controller@3b0 { diff --git a/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi new file mode 100644 index 00000000000000..2f7a2f483b3eca --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-pmgr.dtsi @@ -0,0 +1,424 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * T6041-specific PMGR power domains for hardware auto-managed DCS channels + * and memory/SoC fabrics. + * + * Offsets and parent links verified against the J616c ADT (/arm-io/pmgr + * devices and ps-groups). The DCS nodes omit their ADT parents, the AMCC + * power states, which are not described in this device tree. All 32 DCS + * channels (24 present on binned parts, 32 on full parts) and 12 fabrics + * are hardware auto-managed: the boot loader may leave them forced on, and + * they must be switched to hardware AUTO_ENABLE early at boot, before the + * PMP starts. On binned parts dcs_24-31 are fused off and read as off. + * + * Copyright The Asahi Linux Contributors + */ + +&pmgr_aux { + ps_fab0_soc: power-controller@168 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x168 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab0_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_dcs_00: power-controller@188 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x188 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_00"; + apple,auto-managed; + }; + + ps_dcs_01: power-controller@1a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_01"; + apple,auto-managed; + }; + + ps_dcs_02: power-controller@1b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_02"; + apple,auto-managed; + }; + + ps_dcs_03: power-controller@1c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_03"; + apple,auto-managed; + }; + + ps_dcs_08: power-controller@1d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_08"; + apple,auto-managed; + }; + + ps_dcs_09: power-controller@1e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_09"; + apple,auto-managed; + }; + + ps_dcs_10: power-controller@1f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_10"; + apple,auto-managed; + }; + + ps_dcs_11: power-controller@200 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x200 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_11"; + apple,auto-managed; + }; + + ps_dcs_16: power-controller@210 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x210 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_16"; + apple,auto-managed; + }; + + ps_dcs_17: power-controller@220 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x220 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_17"; + apple,auto-managed; + }; + + ps_dcs_18: power-controller@230 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x230 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_18"; + apple,auto-managed; + }; + + ps_dcs_19: power-controller@240 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x240 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_19"; + apple,auto-managed; + }; + + ps_dcs_24: power-controller@250 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x250 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_24"; + apple,auto-managed; + }; + + ps_dcs_25: power-controller@260 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x260 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_25"; + apple,auto-managed; + }; + + ps_dcs_26: power-controller@270 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x270 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_26"; + apple,auto-managed; + }; + + ps_fab_gw_0: power-controller@288 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x288 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_gw_0"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab_gw_1: power-controller@290 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x290 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_gw_1"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab_afr: power-controller@298 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x298 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab_afr"; + apple,always-on; + apple,auto-managed; + }; + + ps_fab1_soc: power-controller@2d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab1_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab2_soc: power-controller@338 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x338 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab2_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab5_soc: power-controller@440 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x440 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab5_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + ps_fab7_soc: power-controller@488 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x488 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab7_soc"; + power-domains = <&ps_afi>; + apple,always-on; + apple,auto-managed; + }; + + /* dcs_27 sits at +0x530 rather than adjacent to dcs_26 (+0x280 is amcc27). */ + ps_dcs_27: power-controller@530 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x530 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_27"; + apple,auto-managed; + }; +}; + +&ps_fab6_soc { + apple,auto-managed; +}; + +&pmgr { + ps_fab4_soc: power-controller@128 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x128 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fab4_soc"; + power-domains = <&ps_afc>; + apple,always-on; + apple,auto-managed; + }; + + ps_dcs_04: power-controller@2e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_04"; + apple,auto-managed; + }; + + ps_dcs_05: power-controller@2e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_05"; + apple,auto-managed; + }; + + ps_dcs_06: power-controller@2f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_06"; + apple,auto-managed; + }; + + ps_dcs_07: power-controller@2f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_07"; + apple,auto-managed; + }; + + ps_dcs_12: power-controller@300 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x300 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_12"; + apple,auto-managed; + }; + + ps_dcs_13: power-controller@308 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x308 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_13"; + apple,auto-managed; + }; + + ps_dcs_14: power-controller@310 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x310 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_14"; + apple,auto-managed; + }; + + ps_dcs_15: power-controller@318 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x318 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_15"; + apple,auto-managed; + }; + + ps_dcs_20: power-controller@320 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x320 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_20"; + apple,auto-managed; + }; + + ps_dcs_21: power-controller@328 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x328 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_21"; + apple,auto-managed; + }; + + ps_dcs_22: power-controller@330 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x330 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_22"; + apple,auto-managed; + }; + + ps_dcs_23: power-controller@338 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x338 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_23"; + apple,auto-managed; + }; + + ps_dcs_28: power-controller@340 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x340 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_28"; + apple,auto-managed; + }; + + ps_dcs_29: power-controller@348 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x348 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_29"; + apple,auto-managed; + }; + + ps_dcs_30: power-controller@350 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x350 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_30"; + apple,auto-managed; + }; + + ps_dcs_31: power-controller@358 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x358 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dcs_31"; + apple,auto-managed; + }; +}; + +&ps_fab3_soc { + apple,auto-managed; +}; + +&pmgr_mini { + ps_nub_fabric: power-controller@100 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_fabric"; + apple,always-on; + apple,auto-managed; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 36e3db2718a98b..3c37fe24e6c483 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -721,21 +721,11 @@ /* * First ProRes engine (ADT /arm-io/apr0) and its DART, from the J616c ADT. - * apr0 sits in the SCODEC block (PMGR bank 0 / pmgr_aux: FAB1_SOC 0x2d0, - * SCODEC 0x328, SCODEC_STREAMING 0x330) with core, wrapper and aux windows. + * apr0 sits in the SCODEC block (PMGR bank 0 / pmgr_aux: FAB1_SOC 0x2d0 in + * t6041-pmgr.dtsi, SCODEC 0x328, SCODEC_STREAMING 0x330) with core, wrapper + * and aux windows. */ &pmgr_aux { - ps_fab1_soc: power-controller@2d0 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x2d0 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "fab1_soc"; - power-domains = <&ps_afi>; - apple,always-on; - status = "disabled"; - }; - ps_scodec: power-controller@328 { compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x328 4>; @@ -826,3 +816,5 @@ &ave { status = "okay"; }; + +#include "t6041-pmgr.dtsi" From 4edfe4338d09d6fed7f90204534d6e53a2ec32a9 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:43 +0000 Subject: [PATCH 1211/1514] soc: apple: sleep: expose commit-time coprocessor and enclave hooks External EL2 sleep drivers (such as apple,t6041-sleep) run their own commit path and need the same commit-time coprocessor and enclave sequencing as the core sleep driver. Export apple_sleep_set_external_commit_stop(), apple_sleep_coprocs_check_all(), apple_sleep_coprocs_stop_all(), apple_sleep_coprocs_ans_stopped(), apple_sleep_coprocs_count(), and apple_sleep_enclave_stop_all() so an external EL2 sleep driver can check ready coprocessors before the refusal boundary, halt the enclave and every ready coprocessor past the irreversible commit point, and handle NULL sleep-core SoC data cleanly in apple_sleep_coproc_run_off(). Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/sleep.c | 95 ++++++++++++++++++++++++++++++++- include/linux/soc/apple/sleep.h | 35 ++++++++++++ 2 files changed, 128 insertions(+), 2 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index da88e301a3cb42..7f93efef9ec5a0 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -1653,9 +1653,18 @@ bool apple_sleep_coproc_stopped(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_coproc_stopped); +static bool apple_sleep_external_commit; + +void apple_sleep_set_commit_stops_coprocs(bool enable) +{ + WRITE_ONCE(apple_sleep_external_commit, enable); +} +EXPORT_SYMBOL_GPL(apple_sleep_set_commit_stops_coprocs); + bool apple_sleep_commit_stops_coprocs(void) { - return READ_ONCE(apple_sleep) && pm_suspend_via_firmware(); + return (READ_ONCE(apple_sleep) || READ_ONCE(apple_sleep_external_commit)) && + pm_suspend_via_firmware(); } EXPORT_SYMBOL_GPL(apple_sleep_commit_stops_coprocs); @@ -1673,7 +1682,8 @@ static void apple_sleep_coproc_run_off(struct apple_sleep_coproc *c) c->stopped = true; return; } - if (!apple_sleep->soc->regions) + /* T6041's own sleep driver runs this without the sleep core. */ + if (!apple_sleep || !apple_sleep->soc->regions) c->status = readl(c->asc + ASC_CPU_STATUS); writel(readl(c->asc + ASC_CPU_CONTROL) & ~ASC_CPU_CONTROL_RUN, c->asc + ASC_CPU_CONTROL); writel(readl(c->asc + ASC_CPU_CONTROL) & ~ASC_CPU_CONTROL_RUN, c->asc + ASC_CPU_CONTROL); @@ -1792,6 +1802,87 @@ static void apple_sleep_coprocs_stop(struct apple_sleep *s, bool first) dsb(sy); } +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): last refusal checks + * before any irreversible enclave or coprocessor stop. + */ +int apple_sleep_coprocs_check_all(void) +{ + int i, ret; + + for (i = 0; i < SLEEP_COPROCS; i++) { + struct apple_sleep_coproc *c = &apple_sleep_coprocs[i]; + + if (!c->dev || !c->ready || c->stopped || !c->last_check) + continue; + ret = c->last_check(c->data); + if (ret) { + dev_err(c->dev, "refused at sleep commit: %d\n", ret); + return ret; + } + } + + return 0; +} + +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): run the enclave's + * irreversible sleep request with interrupts off. A nonzero return guarantees + * no SLEEP request was sent. + */ +int apple_sleep_enclave_stop_all(void) +{ + int ret; + + if (!apple_sleep_enclave.stop) + return 0; + ret = apple_sleep_enclave.stop(apple_sleep_enclave.data); + if (ret && apple_sleep_enclave.dev) + dev_err(apple_sleep_enclave.dev, + "refused before SEP SLEEP was sent: %d\n", ret); + + return ret; +} + +/* + * For a SoC whose sleep has its own driver at EL2 (T6041): both passes of the stop above, + * the coprocessors registered first, then the rest. Past the refusal boundary every ready + * coprocessor is still halted even if one @last_stop reports a negative error. + */ +int apple_sleep_coprocs_stop_all(void) +{ + int pass, i, ret, first_err = 0; + + for (pass = 1; pass >= 0; pass--) { + for (i = 0; i < SLEEP_COPROCS; i++) { + struct apple_sleep_coproc *c = &apple_sleep_coprocs[i]; + + if (!c->dev || !c->ready || c->first != pass || c->stopped) + continue; + if (c->last_stop) { + ret = c->last_stop(c->data); + if (ret < 0 && !first_err) + first_err = ret; + } + apple_sleep_coproc_run_off(c); + } + } + dsb(sy); + return first_err; +} + +/* For T6041: whether the coprocessor behind the storage PCIe link (ANS) was stopped. */ +bool apple_sleep_coprocs_ans_stopped(void) +{ + int i; + + for (i = 0; i < SLEEP_COPROCS; i++) + if (apple_sleep_coprocs[i].dev && apple_sleep_coprocs[i].pcie_ans && + apple_sleep_coprocs[i].stopped) + return true; + return false; +} + const struct apple_sleep_smc_policy *apple_sleep_smc_policy(void) { return apple_sleep && pm_suspend_via_firmware() ? apple_sleep->soc->smc_policy : NULL; diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index 86760fa77b6027..d2642a9c8ffb43 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -95,6 +95,17 @@ int apple_sleep_m5_dispext_power(struct device *dev, bool on); int apple_sleep_coproc_register(struct device *dev, void __iomem *asc, bool pcie_ans, int (*last_stop)(void *data), void *data); +/* + * For a SoC sleep driver of its own (T6041): advertise commit-time stop + * support and run the refusal checks, enclave stop, and coprocessor stops + * with interrupts off. + */ +void apple_sleep_set_commit_stops_coprocs(bool enable); +int apple_sleep_coprocs_check_all(void); +int apple_sleep_enclave_stop_all(void); +int apple_sleep_coprocs_stop_all(void); +bool apple_sleep_coprocs_ans_stopped(void); + /* * The same with no ASC to clear: @last_stop clears its own run bits and lowers its own power * domain, and runs before every other coprocessor's. The refusal checks leave that domain on. @@ -362,6 +373,30 @@ static inline bool apple_sleep_coproc_stopped(struct device *dev) static inline void apple_sleep_note_sub(u8 step) {} +static inline void apple_sleep_set_commit_stops_coprocs(bool enable) +{ +} + +static inline int apple_sleep_coprocs_check_all(void) +{ + return 0; +} + +static inline int apple_sleep_enclave_stop_all(void) +{ + return 0; +} + +static inline int apple_sleep_coprocs_stop_all(void) +{ + return 0; +} + +static inline bool apple_sleep_coprocs_ans_stopped(void) +{ + return false; +} + static inline bool apple_sleep_commit_stops_coprocs(void) { return false; From 1799fecd5232c1a380758c29887ee958fc7532e0 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:43 +0000 Subject: [PATCH 1212/1514] soc: apple: sep: support external EL2 sleep commit and suspend guards Allow the SEP driver to participate cleanly in EL2 system sleep when an external sleep driver advertises commit-time enclave stops, and harden the suspend fallback path: - Expose pm::platform_commit() and mailbox drain checks to Rust drivers and model them in tools/asahi/sep-suspend-errors-tests.py. - On systems without commit-time enclave stop, save the SEP DART via apple_dart_sleep_prepare() and refuse suspend if the DART lacks apple,sleep-restore lists (preventing a noirq bus hang seen on J614c). - Refuse deep sleep immediately with -EBUSY (rate-limited) if the enclave failed to answer an earlier sleep/wake, did not finish coming up, or has a stuck mailbox, rather than committing over a running enclave. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/pm.rs | 28 +++ drivers/soc/apple/pm_shim.c | 33 ++++ drivers/soc/apple/sep.rs | 227 ++++++++++++++++++++++++ drivers/soc/apple/shim.h | 2 + rust/kernel/soc/apple/mailbox.rs | 6 + tools/asahi/sep-suspend-errors-tests.py | 28 ++- 6 files changed, 320 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/pm.rs b/drivers/soc/apple/pm.rs index e18e84bb1986a3..d479bf866ae4c6 100644 --- a/drivers/soc/apple/pm.rs +++ b/drivers/soc/apple/pm.rs @@ -38,6 +38,9 @@ extern "C" { fn sep_pm_keep_domains(dev: *mut c_void) -> c_int; fn sep_pm_clear_dev_disable(dev: *mut c_void) -> c_int; fn sep_pm_dart_restore(dev: *mut c_void); + fn sep_pm_dart_prepare(dev: *mut c_void) -> c_int; + fn sep_pm_wait_gated(dev: *mut c_void, timeout_ms: c_uint) -> c_int; + fn sep_pm_platform_commit() -> bool; fn sep_pm_commit_prepare( dev: *mut c_void, mbox: *mut c_void, @@ -128,6 +131,31 @@ pub(crate) fn commit_finish(dev: &kernel::device::Device) -> Option { } /// Puts the enclave's DART back if it lost its state, before the doorbell. +/// How long the enclave gets to gate its domain once it has answered (told at suspend). +const GATE_TIMEOUT_MS: u32 = 5000; + +/// Whether a sleep core commit sends the staged SLEEP; if not, it is sent at device suspend. +pub(crate) fn platform_commit() -> bool { + // SAFETY: only reads the sleep core's state. + unsafe { sep_pm_platform_commit() } +} + +/// Whether the enclave gated itself within the bound. +pub(crate) fn wait_gated(dev: &kernel::device::Device) -> bool { + // SAFETY: `dev` is the bound SEP device. + unsafe { sep_pm_wait_gated(dev.as_raw().cast(), GATE_TIMEOUT_MS) == 0 } +} + +/// Saves the enclave's DART while it can be read, before the enclave is told. +pub(crate) fn dart_prepare(dev: &kernel::device::Device) -> Result<()> { + // SAFETY: `dev` is the bound SEP device. + let rc = unsafe { sep_pm_dart_prepare(dev.as_raw().cast()) }; + if rc != 0 { + return Err(Error::from_errno(rc)); + } + Ok(()) +} + pub(crate) fn dart_restore(dev: &kernel::device::Device) { // SAFETY: `dev` is the bound SEP device. unsafe { sep_pm_dart_restore(dev.as_raw().cast()) }; diff --git a/drivers/soc/apple/pm_shim.c b/drivers/soc/apple/pm_shim.c index c1d415c0bd7447..5f5ee20bd7db1c 100644 --- a/drivers/soc/apple/pm_shim.c +++ b/drivers/soc/apple/pm_shim.c @@ -155,6 +155,39 @@ static struct device *sep_pm_dart(struct device *dev) return pdev ? &pdev->dev : NULL; } +/* + * Saves the enclave's DART while it can be read, before the enclave is told at suspend. Only + * a DART with apple,sleep-restore in its node is saved here and then left alone by its own + * callbacks. Without it, the DART's noirq suspend would read its registers after the enclave + * slept and its power domain went off, which hangs the suspend: refuse instead. + */ +int sep_pm_dart_prepare(void *ptr) +{ + struct device *dart = sep_pm_dart(ptr); + int ret; + + if (!dart) + return -ENODEV; + if (!apple_dart_sleep_listed(dart)) { + dev_err(dart, "no apple,sleep-restore list: the enclave can't sleep at suspend\n"); + put_device(dart); + return -EOPNOTSUPP; + } + ret = apple_dart_sleep_prepare(dart); + put_device(dart); + + return ret; +} + +/* + * Whether a sleep core commit sends the staged SLEEP (T8140). Without one, a firmware suspend + * (T6041's own sleep driver) tells the enclave at device suspend instead. + */ +bool sep_pm_platform_commit(void) +{ + return apple_sleep_commit_stops_coprocs(); +} + void sep_pm_dart_restore(void *ptr) { struct device *dart = sep_pm_dart(ptr); diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index a71d3ff0be3fb3..fc5302b33bdacd 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -231,6 +231,8 @@ const RNG_MAX_WORDS_PER_READ: usize = 16; // already being written can still go out once the sleep has begun; see // `send_entropy_request()`. const RNG_SLEEP_DRAIN_MS: u32 = proto::CONTROL_TIMEOUT_MS + 1000; +/// How long a full mailbox may take to drain before a sleep is refused. +const MAILBOX_DRAIN_MS: u32 = 100; extern "C" { fn sep_cancel_work_sync(work: *mut c_void); @@ -681,6 +683,11 @@ struct SepData { // The mailbox's receive interrupt is held off for the enclave's sleep. sleep_rx_held: Atomic, + /// Told at device suspend (no sleep core commit, T6041) rather than staged for the commit. + sleep_at_suspend: Atomic, + /// The enclave didn't answer a sleep request or a wake this boot: no deep sleep until a + /// reboot, as a commit over a running enclave resets the SoC. + sleep_unanswered: Atomic, #[pin] ool_xarm: Mutex>, @@ -1226,6 +1233,8 @@ impl SepData { phase: Atomic::new(PHASE_ATTACH), sleep_gate: Atomic::new(pm::SleepGate::Open as u32), sleep_rx_held: Atomic::new(false), + sleep_at_suspend: Atomic::new(false), + sleep_unanswered: Atomic::new(false), ool_xarm <- new_mutex!(Some(ool_xarm)), ool_sbio <- new_mutex!(Some(ool_sbio)), ool_sks <- new_mutex!(Some(ool_sks)), @@ -1543,6 +1552,10 @@ impl SepData { /// Prepare a firmware-driven suspend without sending SLEEP. The platform /// owns the irreversible request, after every returnable refusal. pub(crate) fn sleep_enter(&self) -> Result<()> { + // T6041: its sleep driver has no sleep core commit, so the enclave is told now. + if !pm::platform_commit() { + return self.sleep_enter_at_suspend(); + } match self.sleep_gate() { // A failed earlier wake is not repaired by another precommit attempt. pm::SleepGate::Lost => return Err(EIO), @@ -1557,6 +1570,14 @@ impl SepData { ); return Err(EBUSY); } + // Refused here, at once, rather than at the commit after its send wait. + if !self.mailbox_drains() { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave isn't taking messages (its mailbox stays full)\n" + ); + return Err(EBUSY); + } self.set_sleep_gate(pm::SleepGate::Draining); let idle = control::wait_idle( @@ -1586,6 +1607,195 @@ impl SepData { Ok(()) } + /// Without a sleep core commit (T6041): tell the enclave at device suspend, seconds before + /// the platform's commit, which answers, saves its state and gates its own domain (waited + /// for in suspend_noirq). A deep sleep commits only over an enclave that is asleep. + fn sleep_enter_at_suspend(&self) -> Result<()> { + if self.sleep_unanswered.load(Relaxed) { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not answer a sleep request or wake earlier this boot\n" + ); + return Err(EBUSY); + } + match self.sleep_gate() { + // Gated already at an earlier, refused sleep: it stays asleep until a real wake. + pm::SleepGate::Lost if self.sleep_at_suspend.load(Relaxed) => return Ok(()), + pm::SleepGate::Lost => { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not come back from a sleep earlier this boot\n" + ); + return Err(EBUSY); + } + pm::SleepGate::Open => {} + _ => return Err(EBUSY), + } + // One that didn't come up still runs: a commit over it resets the SoC. + if self.phase.load(Relaxed) != PHASE_READY || !self.endpoint_present(proto::EP_CONTROL) { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave did not finish coming up, so it can't be put to sleep\n" + ); + return Err(EBUSY); + } + if !self.mailbox_drains() { + dev_err_ratelimited!( + self.dev, + "deep sleep refused: the enclave isn't taking messages (its mailbox stays full)\n" + ); + return Err(EBUSY); + } + + self.set_sleep_gate(pm::SleepGate::Draining); + let idle = control::wait_idle( + proto::CONTROL_TIMEOUT_MS, + 10, + || self.control.lock().requests_in_flight(), + |ms| kernel::time::delay::fsleep(kernel::time::Delta::from_millis(i64::from(ms))), + ); + if !idle { + dev_err_ratelimited!( + self.dev, + "sleep refused: a request is still waiting for its reply\n" + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(EBUSY); + } + + if let Err(e) = pm::dart_prepare(&self.dev) { + dev_err_ratelimited!( + self.dev, + "sleep refused: its DART could not be saved ({:?})\n", + e + ); + self.set_sleep_gate(pm::SleepGate::Open); + return Err(e); + } + + self.sleep_at_suspend.store(true, Relaxed); + match self.sleep_request() { + Ok(()) => { + if let Some(mbox) = self.mbox.lock().as_ref() { + mbox.set_recv_enabled(false); + } + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Told); + dev_dbg!(self.dev, "the enclave answered the sleep request\n"); + Ok(()) + } + Err(e) => { + dev_err_ratelimited!( + self.dev, + "sleep refused: no answer to the sleep request ({:?})\n", + e + ); + self.sleep_unanswered.store(true, Relaxed); + // A request that timed out may still have been taken. + self.set_sleep_gate(pm::SleepGate::Told); + self.sleep_exit(); + Err(e) + } + } + } + + /// Asks the enclave to go to sleep (told at suspend). The request is sent past the gate. + fn sleep_request(&self) -> Result<()> { + let op = proto::op_sleep(); + let tag = proto::TAG_SLEEP; + let idx = self.control.lock().alloc_sleep()?; + let msg = proto::encode_control(&op, tag); + + let sent = match self.mbox.lock().as_ref() { + Some(mbox) => Self::ring(mbox, msg), + None => Err(ENODEV), + }; + if let Err(e) = sent { + self.control.lock().abandon(idx); + return Err(e); + } + match self.control_wait(&op, idx, tag)? { + Some(_) => Ok(()), + None => Err(ETIMEDOUT), + } + } + + /// The wake of an enclave told at suspend: a real wake starts it, a refused sleep finds + /// it gated (it stays asleep until the next real sleep) or asks whether it still answers. + fn sleep_exit_at_suspend(&self) -> bool { + let gate = self.sleep_gate(); + if gate == pm::SleepGate::Draining { + self.set_sleep_gate(pm::SleepGate::Open); + return false; + } + if !gate.needs_wake() { + return false; + } + // SAFETY: only reads a flag. + let real = unsafe { bindings::pm_resume_via_firmware() }; + if !real && gate == pm::SleepGate::Lost { + return false; + } + let answered = if real { + self.sleep_kick() + } else if pm::wait_gated(&self.dev) { + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Lost); + dev_warn_ratelimited!( + self.dev, + "the enclave stays asleep until the next real sleep or a reboot\n" + ); + return false; + } else { + dev_warn_ratelimited!(self.dev, "the enclave never gated its power domain\n"); + self.sleep_probe() + }; + match answered { + Ok(()) => { + self.sleep_at_suspend.store(false, Relaxed); + self.set_sleep_gate(pm::SleepGate::Open); + // One line per sleep it was told of: nothing else says it came back. + dev_info_ratelimited!(self.dev, "the enclave is back from its sleep request\n"); + true + } + Err(e) => { + dev_err_ratelimited!( + self.dev, + "the enclave did not come back ({:?}); it stays unused\n", + e + ); + self.sleep_unanswered.store(true, Relaxed); + self.sleep_hold_rx(); + self.set_sleep_gate(pm::SleepGate::Lost); + false + } + } + } + + /// Whether an enclave that was told and never gated still answers. + fn sleep_probe(&self) -> Result<()> { + pm::dart_restore(&self.dev); + self.sleep_release_rx(); + let op = proto::op_nop(0); + let (idx, tag) = self.control.lock().alloc()?; + let msg = proto::encode_control(&op, tag); + let sent = match self.mbox.lock().as_ref() { + Some(mbox) => { + mbox.set_recv_enabled(true); + Self::ring(mbox, msg) + } + None => Err(ENODEV), + }; + if let Err(e) = sent { + self.control.lock().abandon(idx); + return Err(e); + } + match self.control_wait(&op, idx, tag)? { + Some(_) => Ok(()), + None => Err(ETIMEDOUT), + } + } + /// Stage without sending; the platform's commit owns SLEEP with IRQs off. fn sleep_leave_for_commit(&self) -> Result<()> { let request = proto::encode_control(&proto::op_sleep(), proto::TAG_SLEEP); @@ -1604,6 +1814,20 @@ impl SepData { Ok(()) } + /// Whether the enclave takes messages: its receive FIFO drains within `MAILBOX_DRAIN_MS`. A + /// FIFO that stays full means it stopped reading, and a sleep request would only time out. + fn mailbox_drains(&self) -> bool { + for _ in 0..MAILBOX_DRAIN_MS / 5 { + match self.mbox.lock().as_ref() { + Some(mbox) if mbox.send_ready() => return true, + Some(_) => {} + None => return false, + } + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(5)); + } + false + } + /// Holds off the receive interrupt, whose handler reads the mailbox. fn sleep_hold_rx(&self) { if !self.sleep_rx_held.xchg(true, Relaxed) { @@ -1625,6 +1849,9 @@ impl SepData { /// A sent request can be restarted only after actual physical sleep/wake. /// Returns whether the enclave came back from a sleep it was told of. pub(crate) fn sleep_exit(&self) -> bool { + if self.sleep_at_suspend.load(Relaxed) { + return self.sleep_exit_at_suspend(); + } // Staged only: an unsent refusal releases RX without a restart. match pm::commit_finish(&self.dev) { Some(true) => self.set_sleep_gate(pm::SleepGate::Told), diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 1ca60f1b338a89..4a691f2b62a401 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -33,6 +33,8 @@ int sep_pm_keep_domains(void *dev); int sep_pm_wait_gated(void *dev, unsigned int timeout_ms); int sep_pm_clear_dev_disable(void *dev); void sep_pm_dart_restore(void *dev); +int sep_pm_dart_prepare(void *dev); +bool sep_pm_platform_commit(void); int sep_pm_commit_prepare(void *dev, void *mbox, u64 msg0, u32 msg1, u64 reply, u64 mask); int sep_pm_commit_finish(void *dev); extern const struct dev_pm_ops sep_pm_ops; diff --git a/rust/kernel/soc/apple/mailbox.rs b/rust/kernel/soc/apple/mailbox.rs index e0c4be586801d7..9d39fc87262948 100644 --- a/rust/kernel/soc/apple/mailbox.rs +++ b/rust/kernel/soc/apple/mailbox.rs @@ -102,6 +102,12 @@ impl Mailbox { to_result(unsafe { bindings::apple_mbox_send(self.mbox, msg, atomic) }) } + /// Whether the firmware has room for another message (its receive FIFO isn't full). + pub fn send_ready(&self) -> bool { + // SAFETY: Calling the c function, `mbox` is a valid pointer + unsafe { bindings::apple_mbox_send_ready(self.mbox) } + } + /// Sets bit 0 of the receive control word, for firmware that powers itself down. pub fn set_recv_enabled(&self, enabled: bool) { // SAFETY: Calling the c function, `mbox` is a valid pointer diff --git a/tools/asahi/sep-suspend-errors-tests.py b/tools/asahi/sep-suspend-errors-tests.py index 2ae69ec2c32fcf..b8cc7a76a7f006 100644 --- a/tools/asahi/sep-suspend-errors-tests.py +++ b/tools/asahi/sep-suspend-errors-tests.py @@ -139,6 +139,7 @@ def replace_once(source, before, after): static struct apple_mbox mbox; static int apple_sleep_coprocs_lock; static void *apple_sleep; +static bool apple_sleep_external_commit; static struct { struct device *dev; int (*stop)(void *); void *data; } apple_sleep_enclave; @@ -251,7 +252,7 @@ def replace_once(source, before, after): memset(&hw, 0, sizeof(hw)); mbox = (struct apple_mbox){ .regs = &hw, .hw = &hw, .rx = foreign_rx, .cookie = &device }; config_enabled = hyp = sep_pm_suspending = dart_present = dart_ready = map_ok = true; - firmware = tx_ready = true; apple_sleep = &device; + firmware = tx_ready = true; apple_sleep = &device; apple_sleep_external_commit = false; real_wake = pending_wake = late_wake = sleep_refuse_before_send = false; domain_error = property_error = address_error = read_error = gate_after = reads = 0; put_refs = maps = unmaps = lookups = prepares = restores = sends = closes = 0; @@ -276,6 +277,7 @@ def replace_once(source, before, after): case 19: apple_sleep_enclave.dev = value ? &device : NULL; break; case 20: sep_pm_commit.sent = value; break; case 21: firmware = value; break; case 22: sep_pm_told = value ? yes : NULL; break; + case 23: apple_sleep_external_commit = value; break; } } int counter(int which) { @@ -343,6 +345,14 @@ def replace_once(source, before, after): assert(sep_pm_commit.registered); assert(sep_pm_commit_finish(&device) == 0); assert(put_refs == 1 && unmaps == 1 && !apple_sleep_enclave.dev); assert(sep_pm_commit_finish(&device) == -ENOENT); + // An external EL2 sleep driver (T6041) advertises commit-stop without apple_sleep. + fixture(); apple_sleep = NULL; apple_sleep_external_commit = true; + assert(apple_sleep_commit_stops_coprocs()); + assert(stage() == 0); + assert(sep_pm_commit_finish(&device) == 0); + assert(put_refs == 1 && unmaps == 1 && !apple_sleep_enclave.dev); + firmware = false; + assert(!apple_sleep_commit_stops_coprocs()); } static void test_unsent(void) { for (int scenario = 0; scenario < 7; ++scenario) { @@ -446,7 +456,7 @@ def replace_once(source, before, after): #![allow(dead_code, unused_imports, unused_variables)] use std::cell::{Cell, RefCell, RefMut}; use std::ffi::{c_int, c_void}; -use std::sync::atomic::{AtomicU32, Ordering, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering, Ordering::Relaxed}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct Error(i32); impl Error { fn from_errno(n: i32) -> Self { assert!(n < 0); Self(n) } } type Result = std::result::Result; @@ -529,17 +539,25 @@ def replace_once(source, before, after): struct SepData { dev: kernel::device::Device, phase: AtomicU32, control: Lock, mbox: Lock>, gate: Cell, sleep_rx_held: Flag, endpoint: Cell, control_wq: Wq, + // T6041's suspend-time path (no sleep core commit); never taken here. + sleep_at_suspend: AtomicBool, } impl SepData { fn new() -> Self { Self { dev: kernel::device::Device, phase: AtomicU32::new(PHASE_READY), control: Lock(RefCell::new(Control { busy: false, wake_ok: true })), mbox: Lock(RefCell::new(Some(Mbox))), gate: Cell::new(pm::SleepGate::Open), - sleep_rx_held: Flag(Cell::new(false)), endpoint: Cell::new(true), control_wq: Wq } + sleep_rx_held: Flag(Cell::new(false)), endpoint: Cell::new(true), control_wq: Wq, + sleep_at_suspend: AtomicBool::new(false) } } fn endpoint_present(&self, _: u32) -> bool { self.endpoint.get() } fn sleep_gate(&self) -> pm::SleepGate { self.gate.get() } fn set_sleep_gate(&self, g: pm::SleepGate) { self.gate.set(g); } + // T6041's suspend-time path and its mailbox check: the platform commits here, so the + // first is never reached, and the mailbox always drains. + fn sleep_enter_at_suspend(&self) -> Result<()> { unreachable!() } + fn sleep_exit_at_suspend(&self) -> bool { unreachable!() } + fn mailbox_drains(&self) -> bool { true } fn ring(_: &Mbox, msg: kernel::soc::apple::mailbox::Message) -> Result<()> { assert_eq!(msg.msg0, proto::WAKE_KICK.msg0); event(4); RING.with(|v|v.get()) } @@ -700,7 +718,9 @@ def sources(source, contracts, mutation): } ''' rust += pm[gate_start:gate_end] - rust += '\n'.join(bodies[n] for n in names['pm']) + '\n}\nimpl SepData {\n' + rust += '\n'.join(bodies[n] for n in names['pm']) + # T6041 has no sleep core commit; every platform modelled here has one. + rust += '\npub(crate) fn platform_commit() -> bool { true }\n}\nimpl SepData {\n' rust += '\n'.join(bodies[n] for n in names['sep']) + '\n}\n' + RUST_TESTS return c, rust From fa4ee08c3bd9f3c88d53db676e66494ce0c25b95 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:44 +0000 Subject: [PATCH 1213/1514] irqchip/apple-aic: save and restore the T6041 AIC around a firmware suspend T6041 (M4 Max) uses AICv3 and loses AIC state across EL2 suspend-to-RAM. Give "apple,t6041-aic3" its own aic_info with fw_suspend enabled so the AIC state is saved and restored across firmware-driven suspends as on T8140. Signed-off-by: AxxzyWasTaken --- drivers/irqchip/irq-apple-aic.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/drivers/irqchip/irq-apple-aic.c b/drivers/irqchip/irq-apple-aic.c index b3ea9b614475db..8e7866a865e496 100644 --- a/drivers/irqchip/irq-apple-aic.c +++ b/drivers/irqchip/irq-apple-aic.c @@ -350,6 +350,18 @@ static const struct aic_info aic3_t8140_info __initconst = { .fw_suspend = true, }; +/* + * T6041 (M4 Max): the AICv3 of T8122, with the state its sleep driver's firmware + * suspend loses saved and restored around it. + */ +static const struct aic_info aic3_t6041_info __initconst = { + .version = 3, + .irq_cfg = AIC3_IRQ_CFG, + .fast_ipi = true, + .local_fast_ipi = true, + .fw_suspend = true, +}; + static const struct aic_info aic3_t8132_info __initconst = { .version = 3, .irq_cfg = AIC3_IRQ_CFG, @@ -382,6 +394,10 @@ static const struct of_device_id aic_info_match[] = { .compatible = "apple,t8142-aic3", .data = &aic3_t8142_info, }, + { + .compatible = "apple,t6041-aic3", + .data = &aic3_t6041_info, + }, { .compatible = "apple,t8103-aic", .data = &aic1_local_fipi_info, From 6c13dcd31d0b152667990a5f41378a1fc12631c0 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:45 +0000 Subject: [PATCH 1214/1514] nvme-apple: support firmware sleep on T6041 and resume asynchronously Enable commit-time firmware sleep support on T6041 NVMe (ANS) and enable async suspend/resume so NVMe restore runs in parallel with PCIe link retraining after wake. Signed-off-by: AxxzyWasTaken --- drivers/nvme/host/apple.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 508930d3937aae..b33e64ae38bd87 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -2719,6 +2719,8 @@ static struct apple_nvme *apple_nvme_alloc(struct platform_device *pdev) return ERR_PTR(ret); anv->adminq.is_adminq = true; platform_set_drvdata(pdev, anv); + /* Its resume waits on the coprocessor (0.2 to 0.9 s after a real sleep): not in the others' way. */ + device_enable_async_suspend(&pdev->dev); anv->hw = of_device_get_match_data(&pdev->dev); if (!anv->hw) { @@ -3480,6 +3482,10 @@ static const struct apple_nvme_hw apple_nvme_t6040_hw = { .needs_ioq_registers = true, .lsq_in_nvmmu = true, .max_queue_depth = 64, + /* ANS takes part in a firmware sleep, whole endpoint map echoed. */ + .sleep_traced = true, + .sleep_flush_max_nsid = 1, + .sleep_shn = NVME_CC_SHN_MASK, .quirks = NVME_QUIRK_NO_APST, }; From ec3ced95eb898364478fb85e275c11b725d7e3ab Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:45 +0000 Subject: [PATCH 1215/1514] soc: apple: pmp: keep the T6041 firmware data across a real sleep Preserve the T6041 PMP SRAM firmware data region across firmware-driven suspend-to-RAM so the PMP restarts cleanly on wake. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/pmp.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index fc492fa428d700..c8b9219e51c019 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -986,7 +986,9 @@ const HW_CFG_T6041: PmpHwConfig = PmpHwConfig { dma_mask: Some(DmaMask::new::<42>()), check_bootargs_uuid: true, coreanalytics: Ep7::Always, - sram_backup: None, + // 26.6.2 firmware (J616C): __DATA at 0x500761000, 0x7d000 bytes; the 27.2 firmware has it at + // 0x62000. Kept across a real sleep. + sram_backup: Some((0x61000, 0x7d000)), sram_backup_data: false, self_ack_start: false, confirm_ioreg_len: false, From fee9cd340fe194f33b0af0824a55417f8ed45ee5 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:46 +0000 Subject: [PATCH 1216/1514] soc: apple: aop: T6041 sleep order Follow T6041's AFK sleep/wake sequencing around system suspend and resume so AOP suspends cleanly before the sleep commit and resumes afterward. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/aop.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 7fb2939e239a41..89849f775d5c74 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -3185,6 +3185,13 @@ const HW_CFG_T6040: AopHwConfig = AopHwConfig { halt_on_failed_start: true, without_fw_regions: None, }; +/// T6041 (J616C): as T6040, with the AFK sleep and wake order macOS 26.6.2 uses on the J616C +/// (trace, 8 Nov 2026: sleep to these endpoints in this order, then the AP idle notice). +const HW_CFG_T6041: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x24, 0x20, 0x27, 0x26, 0x28, 0x25, 0x21, 0x29, 0x23, 0x22], + wake_endpoints: &[0x22, 0x23, 0x29, 0x21, 0x25, 0x28, 0x26, 0x27, 0x20, 0x24, 0x2a, 0x2b], + ..HW_CFG_T6040 +}; /// T8132 (J713): as T6040. The bootloader hands the AOP over the same way, with /// the DART's DAPF programmed and its windows reserved alongside the firmware /// segments. @@ -3329,7 +3336,7 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t8122-aop")), &HW_CFG_T8122), (of::DeviceId::new(c_str!("apple,t6020-aop")), &HW_CFG_T6020), (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), - (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6040), + (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6041), (of::DeviceId::new(c_str!("apple,t8132-aop")), &HW_CFG_T8132), (of::DeviceId::new(c_str!("apple,t6050-aop")), &HW_CFG_T6050), (of::DeviceId::new(c_str!("apple,t8142-aop")), &HW_CFG_T8142), From e17ca718f1cdd4060340d1d7f356fe99a94431fa Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:46 +0000 Subject: [PATCH 1217/1514] dmaengine: apple-sio: stop T6041 SIO at sleep commit Now that aura enables T6041 SIO and t6041-sleep advertises commit-time coprocessor stops, set .stop_at_commit = true on sio_hw_t6041 (matching sio_hw_t8140) so SIO is halted at the irreversible commit boundary right before t6041-sleep writes ps_commit_sio, instead of stopping early in suspend_late where an aborted suspend strands it. Assert this contract in sio_t6041_match_test(). Signed-off-by: AxxzyWasTaken --- drivers/dma/apple-sio-t6041-test.c | 1 + drivers/dma/apple-sio.c | 1 + 2 files changed, 2 insertions(+) diff --git a/drivers/dma/apple-sio-t6041-test.c b/drivers/dma/apple-sio-t6041-test.c index d5d13f609d7b05..12adc5349637c5 100644 --- a/drivers/dma/apple-sio-t6041-test.c +++ b/drivers/dma/apple-sio-t6041-test.c @@ -265,6 +265,7 @@ static void sio_t6041_match_test(struct kunit *test) KUNIT_EXPECT_PTR_EQ(test, sio_hw_t8140.arrays, &sio_t6041_arrays); KUNIT_EXPECT_TRUE(test, sio_hw_t8140.check_boot_tables == sio_t6041_check_boot_tables); KUNIT_EXPECT_EQ(test, sio_hw_t6041.protocol, 10U); + KUNIT_EXPECT_TRUE(test, sio_hw_t6041.stop_at_commit); KUNIT_EXPECT_TRUE(test, sio_hw_t6041.clear_period_desc); KUNIT_EXPECT_PTR_EQ(test, sio_hw_t6041.arrays, &sio_t6041_arrays); /* Protocol 10 alone is T6030's too, which keeps its own contract. */ diff --git a/drivers/dma/apple-sio.c b/drivers/dma/apple-sio.c index c953e60293b8c9..0f54aad81b97c8 100644 --- a/drivers/dma/apple-sio.c +++ b/drivers/dma/apple-sio.c @@ -656,6 +656,7 @@ static const struct sio_hw_data sio_hw_t6030 = { * the 5 of the host's mailbox call timeout is not part of the record. */ static const struct sio_hw_data sio_hw_t6041 = { + .stop_at_commit = true, .protocol = 10, .fifo_threshold = 0x600, .cfg_word4 = 0x800, From b5dc5015535306e0437a1ee3c7a84f7a68688d84 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:47 +0000 Subject: [PATCH 1218/1514] spmi: apple: drop replies left by firmware at a firmware-driven resume While Linux is asleep, aura's wake path and platform sleep code write the PMU through the SPMI queue. Every command Linux sent before suspend was already answered, so any reply still queued at resume_noirq after a firmware-driven suspend belongs to firmware; leaving it in the RX FIFO causes the next driver command (such as RTC alarm acknowledge) to consume it as an unexpected SPMI response and fail subsequent suspends. Drain stale SPMI replies in resume_noirq after a firmware-driven suspend. Signed-off-by: AxxzyWasTaken --- drivers/spmi/spmi-apple-controller.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/drivers/spmi/spmi-apple-controller.c b/drivers/spmi/spmi-apple-controller.c index eaab8552de9631..1182e2e2daae3f 100644 --- a/drivers/spmi/spmi-apple-controller.c +++ b/drivers/spmi/spmi-apple-controller.c @@ -680,6 +680,23 @@ static int apple_spmi_resume_noirq(struct device *dev) } guard(mutex)(&spmi->fifo_lock); + /* + * Firmware and the platform's sleep code use this queue while Linux is + * away. Every command of ours was answered before the suspend, so any + * reply waiting now is someone else's, and would be read as the reply + * to our next command. + */ + if (pm_resume_via_firmware()) { + unsigned int stale = 0; + + while (!(readl(spmi->regs + spmi->hw->status) & spmi->hw->rx_empty) && + stale < 64) { + readl(spmi->regs + spmi->hw->reply); + stale++; + } + if (stale) + dev_info(dev, "dropped %u stale reply words after the wake\n", stale); + } raw_spin_lock_irqsave(&spmi->irq_mask_lock, flags); /* Whether the enables survive a real sleep has not been measured. */ if (pm_resume_via_firmware()) { From c057793fbed20377a3f3b9eec7d41f2f7c1e3ecf Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:48 +0000 Subject: [PATCH 1219/1514] pinctrl: apple: ack a level interrupt again after unmasking it Clear any stale pending edge/level latch after unmasking a level GPIO interrupt during resume so unmasked level lines (such as speaker amplifier fault/interrupt lines after a firmware sleep) do not trigger an interrupt storm on wake. Signed-off-by: AxxzyWasTaken --- drivers/pinctrl/pinctrl-apple-gpio.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/pinctrl/pinctrl-apple-gpio.c b/drivers/pinctrl/pinctrl-apple-gpio.c index 6b96948767a80a..7089aac3bbe2e9 100644 --- a/drivers/pinctrl/pinctrl-apple-gpio.c +++ b/drivers/pinctrl/pinctrl-apple-gpio.c @@ -341,6 +341,15 @@ static void apple_gpio_irq_unmask(struct irq_data *data) gpiochip_enable_irq(gc, data->hwirq); apple_gpio_set_reg(pctl, data->hwirq, apple_gpio_mode_mask(), FIELD_PREP(REG_GPIOx_MODE, irqtype)); + /* + * On T6041 a level interrupt fired again at once every time it was unmasked although its + * line was inactive (J616c speaker amps, pin 55: mode 3, data 1, ~140 interrupts a second + * from boot until the core disabled the line as unhandled). Switching the mode back from + * "off" leaves the status bit set. Clear it once more: a level that really is active sets + * it again. + */ + if (irqd_get_trigger_type(data) & IRQ_TYPE_LEVEL_MASK) + apple_gpio_irq_ack(data); } static unsigned int apple_gpio_irq_startup(struct irq_data *data) From 0572b09553c1d62052e4d1ee7866ef2081313ea7 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:48 +0000 Subject: [PATCH 1220/1514] Bluetooth: hci_bcm4377: rebind after power loss in a real sleep After a firmware-driven sleep on a conventional PCIe host, the BCM4377 Bluetooth controller loses power and must be rebound after resume so its firmware and rings are cleanly reinitialized. Update the bcm4377 resume host test fixture accordingly. Signed-off-by: AxxzyWasTaken --- drivers/bluetooth/hci_bcm4377.c | 14 ++++++++++++++ tools/asahi/bcm4377-resume/fixture.h | 10 ++++++++++ 2 files changed, 24 insertions(+) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 7bafff5d5aedb2..97fb480ed995cf 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -5,6 +5,7 @@ * Copyright (C) The Asahi Linux Contributors */ +#include #include #include #include @@ -3218,6 +3219,19 @@ static int bcm4377_resume(struct device *dev) bcm4377->wake_armed = false; } + /* + * A real sleep took the function's power: the firmware is gone, and every resume command + * would only time out (two times 2 s inside the system resume, then the rebind anyway). + * Skip them and rebind from the work queue; probe boots the firmware from scratch. + */ + if (pm_resume_via_firmware() && !bcm4377->dma_window_base) { + bcm4377->quiesced = false; + bcm4377->resume_powered = false; + WRITE_ONCE(bcm4377->setup_retry_blocked, false); + bcm4377_queue_rebind(bcm4377, "power lost in the sleep"); + return 0; + } + if (bcm4377->quiesced) { iowrite32(BCM4377_BAR0_SLEEP_CONTROL_UNQUIESCE, bcm4377->bar0 + BCM4377_BAR0_SLEEP_CONTROL); diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index 5eece3476e65fe..cb47a5d7ae3b78 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -63,6 +63,8 @@ struct bcm4377_data { pthread_mutex_t resume_lock; uint64_t resume_epoch, resume_pending; bool resume_armed, resume_blocked, resume_powered; + /* T6041 S2R: zero, so a real sleep's power loss rebinds (not modelled: see below). */ + uint64_t dma_window_base; bool resume_guarded, resume_recovering; struct work_struct resume_work; struct ring acl_d2h_ring,acl_h2d_ring,sco_d2h_ring,sco_h2d_ring,hci_d2h_ring,hci_h2d_ring,sco_event_ring,sco_ack_ring,hci_acl_event_ring,hci_acl_ack_ring; @@ -107,6 +109,14 @@ static pthread_t producer_thread; static void hci_cmd_timeout(struct work_struct *work); static struct bcm4377_data *active; static bool hdev_is_powered(struct hci_dev *h) {return (h->flags&HCI_UP) && !(h->flags&HCI_AUTO_OFF);} +/* The controls model resumes after s2idle; a real sleep's rebind path is not taken. */ +static bool pm_resume_via_firmware(void) { return false; } +struct bcm4377_data; +static void bcm4377_queue_rebind(struct bcm4377_data *b, const char *why) +{ + (void)b; (void)why; + assert(0); +} static bool of_machine_is_compatible(const char *s) {assert(!strcmp(s,"apple,j493"));return board_j493;} static void *kmalloc(size_t n,int flags) {return allocation_error?NULL:malloc(n);} static void kfree(void *p) {free(p);} From c8521ddfb37d9d098994466dddac2837d6b78e3c Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:49 +0000 Subject: [PATCH 1221/1514] PCI: apple: reinitialize conventional ports after firmware sleep A conventional Apple PCIe host (internal Wi-Fi, Bluetooth, and SD card reader ports) loses power across a firmware-driven deep sleep, leaving endpoints unpowered or in reset behind down links. Unconditionally save conventional port state in suspend_noirq, snapshot endpoint saved state before PCI core noirq resume spends it on a down link, retrain cold ports (PWREN, PERST#, link-up, 100 ms PCIe r5.0 6.6.1 settle, RID-to-SID map, and interrupt mask) in resume(), and restore endpoint configuration. Enable async suspend/resume on the host so link retraining runs in parallel with NVMe and display resume. Signed-off-by: AxxzyWasTaken --- drivers/pci/controller/pcie-apple.c | 205 +++++++++++++++++++++++++++- 1 file changed, 203 insertions(+), 2 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index deb2c6214202d6..824b94d04caa7a 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -99,7 +99,6 @@ static int t6050_sd_port_wake = 2; module_param(t6050_sd_port_wake, int, 0644); MODULE_PARM_DESC(t6050_sd_port_wake, "T6050: the SD card reader's port after a firmware sleep: back once the resume is over (2, default), back in the early resume (1), or parked until a restart (0)"); - /* T8103 (original M1) and related SoCs */ #define CORE_RC_PHYIF_CTL 0x00024 #define CORE_RC_PHYIF_CTL_RUN BIT(0) @@ -659,6 +658,7 @@ struct apple_pcie { const struct hw_info *hw; unsigned long *bitmap; struct list_head ports; + struct list_head hib_fns; struct completion event; struct irq_fwspec fwspec; struct irq_domain *msi_domain; @@ -689,6 +689,9 @@ struct apple_pcie_port { struct gpio_desc *perst_gpio; struct gpio_desc *pwren_gpio; int idx; + /* Conventional port: link up when the sleep began, and found down after it */ + bool hib_link_up; + bool hib_cold; bool started; bool needs_stop; bool link_failed; @@ -5923,6 +5926,9 @@ static int apple_pcie_probe(struct platform_device *pdev) struct device *piodma_supplier = NULL; int ret; + /* Setting the ports up again after a real sleep takes ~0.75 s: resume in parallel. */ + device_enable_async_suspend(&pdev->dev); + hw = of_device_get_match_data(dev); if (!hw) return -ENODEV; @@ -6046,6 +6052,7 @@ static int apple_pcie_probe(struct platform_device *pdev) mutex_init(&pcie->lock); INIT_LIST_HEAD(&pcie->ports); + INIT_LIST_HEAD(&pcie->hib_fns); /* Resolve PM dependencies before publishing the PCI hierarchy. */ if (pcie->hw->tunneled) { @@ -6966,6 +6973,9 @@ static void apple_pcie_stop_for_sleep(struct device *dev) static void apple_pcie_neo_save_functions(struct apple_pcie *pcie); +static bool apple_pcie_s2r_reinit(struct apple_pcie *pcie); +static void apple_pcie_hib_save(struct apple_pcie *pcie); +static void apple_pcie_hib_restore_noirq(struct apple_pcie *pcie, const char *what); /* * The J716c radio drivers save PCI state without entering D3. The PCI core * keeps the root port in D0 as well. Its host and DART have no switchable @@ -7130,6 +7140,8 @@ static int apple_pcie_suspend_noirq(struct device *dev) return ret; } if (!pcie->hw->tunneled) { + if (apple_pcie_s2r_reinit(pcie) && pm_suspend_via_firmware()) + apple_pcie_hib_save(pcie); if (pm_suspend_no_platform() && pcie->num_pds) return apple_pcie_hold_domains(pcie); return 0; @@ -7661,8 +7673,11 @@ static int apple_pcie_resume_noirq(struct device *dev) } return ret; } - if (!pcie->hw->tunneled) + if (!pcie->hw->tunneled) { + if (apple_pcie_s2r_reinit(pcie) && pm_resume_via_firmware()) + apple_pcie_hib_restore_noirq(pcie, "S2R"); return 0; + } if (pcie->resume_failed) return -EIO; /* @@ -7729,6 +7744,191 @@ static int apple_pcie_resume_noirq(struct device *dev) return ret; } +/* + * A conventional host (the internal ports with the radio and the SD reader) loses its power + * in a real sleep: the endpoints sit unpowered or in reset behind a link that is down. The + * resume then does what probe did. From aurora-silicon/linux#1477 (0ab1a6603). + */ +struct apple_pcie_hib_fn { + struct list_head entry; + struct pci_dev *pdev; + struct pci_saved_state *state; +}; + +/* A real sleep takes a conventional host's power: its ports are set up again as at probe. */ +static bool apple_pcie_s2r_reinit(struct apple_pcie *pcie) +{ + return !pcie->hw->tunneled && !pcie->managed_sids && !pcie->piodma_supplier && + !pcie->hw->root_bus_only; +} + +/* What only the port registers hold. */ +static void apple_pcie_hib_save(struct apple_pcie *pcie) +{ + struct apple_pcie_port *port; + int i; + + mutex_lock(&pcie->lock); + list_for_each_entry(port, &pcie->ports, entry) { + port->hib_link_up = apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP; + port->hib_cold = false; + port->saved_intmask = apple_pcie_port_readl(port, PORT_INTMSK); + for_each_set_bit(i, port->sid_map, port->sid_map_sz) + port->saved_rid2sid[i] = + apple_pcie_port_readl(port, port_rid2sid_offset(port, i)); + } + mutex_unlock(&pcie->lock); +} + +static void apple_pcie_hib_free_fns(struct apple_pcie *pcie) +{ + struct apple_pcie_hib_fn *fn, *tmp; + + list_for_each_entry_safe(fn, tmp, &pcie->hib_fns, entry) { + list_del(&fn->entry); + kfree(fn->state); + pci_dev_put(fn->pdev); + kfree(fn); + } +} + +/* + * The PCI core's noirq resume spends the functions' saved state on a link that is down + * ("device inaccessible"). A copy taken first goes back once the link is. + */ +static int apple_pcie_hib_keep_fn(struct pci_dev *pdev, void *data) +{ + struct apple_pcie *pcie = data; + struct apple_pcie_port *port; + struct apple_pcie_hib_fn *fn; + + if (pci_is_root_bus(pdev->bus) || !pdev->state_saved) + return 0; + port = apple_pcie_get_port(pdev); + if (!port || !port->hib_cold) + return 0; + fn = kzalloc(sizeof(*fn), GFP_ATOMIC); + if (!fn) + return 0; + fn->state = pci_store_saved_state(pdev); + if (!fn->state) { + kfree(fn); + return 0; + } + fn->pdev = pci_dev_get(pdev); + list_add_tail(&fn->entry, &pcie->hib_fns); + return 0; +} + +/* Before the PCI core restores the functions; nothing is written to a port in this phase. */ +static void apple_pcie_hib_restore_noirq(struct apple_pcie *pcie, const char *what) +{ + struct pci_host_bridge *bridge = pci_host_bridge_from_priv(pcie); + struct apple_pcie_port *port; + bool cold = false; + + apple_pcie_hib_free_fns(pcie); + list_for_each_entry(port, &pcie->ports, entry) { + if (!port->hib_link_up) + continue; + if (apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP) + continue; + port->hib_cold = true; + cold = true; + dev_info(pcie->dev, "%s: %pOF lost its link, setting it up again\n", + what, port->np); + } + if (cold && bridge->bus) + pci_walk_bus(bridge->bus, apple_pcie_hib_keep_fn, pcie); +} + +static void apple_pcie_hib_rid2sid(struct apple_pcie *pcie, struct apple_pcie_port *port) +{ + int i; + + mutex_lock(&pcie->lock); + for (i = 0; i < port->sid_map_sz; i++) + apple_pcie_rid2sid_write(port, i, test_bit(i, port->sid_map) ? + port->saved_rid2sid[i] : 0); + mutex_unlock(&pcie->lock); +} + +/* Probe's bring-up of a conventional port, with the state this kernel had programmed. */ +static int apple_pcie_hib_port_up(struct apple_pcie *pcie, struct apple_pcie_port *port) +{ + u32 stat; + int ret; + + ret = apple_pcie_setup_link(pcie, port, port->np); + if (ret) + return ret; + if (!pcie->hw->retain_clocks) { + if (pcie->hw->port_refclk) + rmw_clear(PORT_REFCLK_CGDIS, port->base + pcie->hw->port_refclk); + else if (port->phy) + rmw_set(PHY_LANE_CFG_REFCLKCGEN, port->phy + PHY_LANE_CFG); + rmw_clear(PORT_APPCLK_CGDIS, port->base + PORT_APPCLK); + } + /* All port interrupts masked and cleared, MSI routing as at probe. */ + apple_pcie_tunnel_restore_irq_hw(port); + apple_pcie_hib_rid2sid(pcie, port); + apple_pcie_port_writel(port, PORT_LTSSMCTL_START, PORT_LTSSMCTL); + ret = readl_relaxed_poll_timeout(port->base + PORT_LINKSTS, stat, + stat & PORT_LINKSTS_UP, 100, link_up_timeout * 1000); + if (ret) { + dev_err(pcie->dev, "S2R: %pOF status %#x link %#x after training\n", port->np, + apple_pcie_port_readl(port, PORT_STATUS), stat); + return ret; + } + apple_pcie_port_writel(port, BIT(PORT_INT_LINK_UP), PORT_INTSTAT); + apple_pcie_port_writel(port, port->saved_intmask, PORT_INTMSK); + /* 100 ms after the link before configuration requests (PCIe r5.0, 6.6.1). */ + msleep(100); + return 0; +} + +/* The normal phase, after the SMC (the PWREN GPIOs are its) and before the functions. */ +static int apple_pcie_resume(struct device *dev) +{ + struct apple_pcie *pcie = apple_pcie_lookup(dev); + struct apple_pcie_port *port; + struct apple_pcie_hib_fn *fn; + int ret; + + if (!apple_pcie_s2r_reinit(pcie) || !pm_resume_via_firmware()) + return 0; + list_for_each_entry(port, &pcie->ports, entry) { + if (!port->hib_link_up) + continue; + if (!port->hib_cold) { + apple_pcie_hib_rid2sid(pcie, port); + continue; + } + ret = apple_pcie_hib_port_up(pcie, port); + if (ret) { + dev_err(dev, "S2R: %pOF link not back (%d), its functions stay unreachable\n", + port->np, ret); + port->hib_cold = false; + continue; + } + dev_info(dev, "S2R: %pOF link back, PWREN and PERST# cycled as at probe\n", + port->np); + } + list_for_each_entry(fn, &pcie->hib_fns, entry) { + port = apple_pcie_get_port(fn->pdev); + if (!port || !port->hib_cold) + continue; + if (pci_load_saved_state(fn->pdev, fn->state)) + pci_warn(fn->pdev, "S2R: saved configuration not taken back\n"); + else + pci_restore_state(fn->pdev); + } + apple_pcie_hib_free_fns(pcie); + list_for_each_entry(port, &pcie->ports, entry) + port->hib_cold = false; + return 0; +} + static int apple_pcie_prepare(struct device *dev) { struct apple_pcie *pcie = apple_pcie_lookup(dev); @@ -7775,6 +7975,7 @@ static const struct dev_pm_ops apple_pcie_pm_ops = { .complete = apple_radio_complete, .suspend_noirq = apple_pcie_suspend_noirq, .resume_noirq = apple_pcie_resume_noirq, + .resume = apple_pcie_resume, .resume_early = apple_pcie_resume_early, }; From bcca7ba666f2fb598a6a8d86a5923364b2c299d6 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:50 +0000 Subject: [PATCH 1222/1514] dt-bindings: mfd: apple,smc: add apple,sleep-wake-type and apple,sleep-pmvc Describe the apple,sleep-wake-type boolean property (write WKTP sleep/wake state around firmware sleep commit) and the apple,sleep-pmvc u32 property (VDD_CIO rail mask written to the SMC pmVC key before sleep commit). Signed-off-by: AxxzyWasTaken --- .../devicetree/bindings/mfd/apple,smc.yaml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Documentation/devicetree/bindings/mfd/apple,smc.yaml b/Documentation/devicetree/bindings/mfd/apple,smc.yaml index 34416179acfa0b..255209498bd596 100644 --- a/Documentation/devicetree/bindings/mfd/apple,smc.yaml +++ b/Documentation/devicetree/bindings/mfd/apple,smc.yaml @@ -51,6 +51,24 @@ properties: mboxes: maxItems: 1 + apple,sleep-wake-type: + type: boolean + description: + The SMC firmware expects the wake type key (WKTP) set to its sleep value + at the sleep commit, and cleared after a full wake. Left at the sleep + value, the SMC treats the time awake as a power nap. + + apple,sleep-pmvc: + $ref: /schemas/types.yaml#/definitions/uint32 + minimum: 0x100 + maximum: 0x1ff + description: + The value written to the SMC's VDD_CIO rail key (pmVC) at the sleep + commit, before the sleep notice. Bit 8 is set, and bit n keeps port n's + CIO rail powered across the sleep. Which rails must stay up depends on + what the SoC's sleep sequence powers on itself. Without the property + pmVC is not written. + gpio: oneOf: - $ref: /schemas/gpio/apple,smc-gpio.yaml From e4fbc2db9205e5726e869f30ddf5f7034df28e1a Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:50 +0000 Subject: [PATCH 1223/1514] mfd: macsmc: write WKTP and pmVC from DT properties around sleep commit Drive SMC WKTP and pmVC sleep-commit writes from the apple,sleep-wake-type and apple,sleep-pmvc DT properties rather than machine-compatible checks: - When apple,sleep-wake-type is set, write WKTP = 2 before slpa at sleep commit and restore WKTP = 0 on a full wake (or in .complete if sleep was refused), preventing the SMC from remaining in power-nap fan/thermal policy after wake. - When apple,sleep-pmvc is set, log the boot pmVC at debug level and write the DT-specified VDD_CIO rail mask (bit 8 plus bit n keeping port n's CIO rail powered across sleep) before slpa, refusing sleep if either WKTP or pmVC fails. - Gate apple_smc_suspend_noirq()/resume_noirq() on pm_suspend_via_firmware() so s2idle does not enter the firmware-sleep path. Signed-off-by: AxxzyWasTaken --- drivers/mfd/macsmc.c | 86 ++++++++++++++++++++++++++++++++++++-- include/linux/mfd/macsmc.h | 7 ++++ 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 0ef475e5be02bb..35f86f9fe00273 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -686,6 +686,20 @@ static void apple_smc_probe_wktp(struct apple_smc *smc) apple_smc_write_full_wake(smc); } +/* pmVC as the boot left it, next to what apple,sleep-pmvc has the sleep commit write. */ +static void apple_smc_sleep_pmvc_report(struct apple_smc *smc) +{ + u32 cur; + int ret = apple_smc_read_u32(smc, SMC_KEY(pmVC), &cur); + + if (ret) + dev_dbg(smc->dev, "pmVC unreadable (%d); the sleep commit writes %#x\n", ret, + smc->sleep_pmvc); + else + dev_dbg(smc->dev, "pmVC %#x at boot; the sleep commit writes %#x\n", cur, + smc->sleep_pmvc); +} + static int apple_smc_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; @@ -703,6 +717,9 @@ static int apple_smc_probe(struct platform_device *pdev) if (!smc->wake_reasons) smc->wake_reasons = of_device_is_compatible(dev->of_node, "apple,t8132-smc") ? apple_smc_t8132_wake_reasons : apple_smc_t8140_wake_reasons; + smc->sleep_wake_type = of_property_read_bool(dev->of_node, "apple,sleep-wake-type"); + smc->sleep_pmvc_set = !of_property_read_u32(dev->of_node, "apple,sleep-pmvc", + &smc->sleep_pmvc); mutex_init(&smc->mutex); spin_lock_init(&smc->lock); @@ -770,6 +787,9 @@ static int apple_smc_probe(struct platform_device *pdev) return dev_err_probe(smc->dev, ret, "Failed to get key count"); smc->key_count = be32_to_cpu(count); + if (smc->sleep_pmvc_set) + apple_smc_sleep_pmvc_report(smc); + /* T8152: key reads and writes are qualified; notifications and GPIO are not. */ if (of_device_is_compatible(dev->of_node, "apple,t8152-smc")) return devm_mfd_add_devices(smc->dev, PLATFORM_DEVID_NONE, @@ -932,10 +952,56 @@ static int apple_smc_notice_idle(struct apple_smc *smc) return ret; } +/* + * WKTP, one byte: 2 at the sleep commit, 0 again once a wake is a full one. With the + * key left at 2 the SMC treats all the time awake as a power nap: it keeps its own fan + * policy against a fan request (the write times out and the fans stay at its idle + * speed), and under thermal load it requests a sleep once a second. #1910 does the same + * on the M4 Pro. + */ +#define SMC_WKTP_SLEEP 2 +#define SMC_WKTP_AWAKE 0 + +/* WKTP back to 0 after a full wake, or after a sleep that ended in a refusal. */ +static void apple_smc_wake_full(struct apple_smc *smc) +{ + int ret; + + if (!smc->wake_silent) + return; + smc->wake_silent = false; + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WKTP_AWAKE); + if (ret) + dev_err(smc->dev, "Failed to write WKTP = %u: %d\n", SMC_WKTP_AWAKE, ret); +} + static int apple_smc_sleep_commit(struct apple_smc *smc) { int ret; + /* + * apple,sleep-wake-type and apple,sleep-pmvc (T6041): macOS writes WKTP = 2, going to + * sleep, and pmVC, the VDD_CIO rail mask (bit 8 set, bit n keeping port n's CIO rail + * powered across sleep so rails the sleep engine polls active remain up), before its + * sleep notice. Either failing refuses the sleep before slpa; .complete then tells the + * SMC the sleep is off and writes WKTP back. + */ + if (smc->sleep_wake_type) { + /* Whatever came of the write, the SMC may run silent until it is told. */ + smc->wake_silent = true; + ret = apple_smc_write_u8(smc, SMC_KEY(WKTP), SMC_WKTP_SLEEP); + if (ret) { + dev_err(smc->dev, "Failed to write WKTP = %u: %d\n", SMC_WKTP_SLEEP, ret); + return ret; + } + } + if (smc->sleep_pmvc_set) { + ret = apple_smc_write_u32(smc, SMC_KEY(pmVC), smc->sleep_pmvc); + if (ret) { + dev_err(smc->dev, "Failed to write pmVC = %#x: %d\n", smc->sleep_pmvc, ret); + return ret; + } + } apple_smc_write_mbse(smc, SMC_KEY(slpa)); /* Device interrupts are off here. */ mdelay(SMC_SLEEP_ARM_MS); @@ -1188,6 +1254,9 @@ static void apple_smc_sleep_wake(struct apple_smc *smc, bool woken) } if (apple_smc_port_reasons_only(smc, smc->wake_record)) apple_sleep_debug_link_cut_wake(); + /* A dark wake sleeps again, and its commit writes the key anyway. */ + if (!pm_dark_wake()) + apple_smc_wake_full(smc); /* A dark wake isn't one: with wakeup_count in use, it would abort the sleep after it. */ if (smc->wake_record && !pm_dark_wake()) pm_wakeup_event(smc->dev, 0); @@ -1780,9 +1849,12 @@ static void apple_smc_complete(struct device *dev) smc->sleep_warned = false; } smc->sleep_policy = NULL; - - if (smc->has_wktp && !pm_dark_wake()) + if (smc->has_wktp && !pm_dark_wake()) { + smc->wake_silent = false; apple_smc_write_full_wake(smc); + } + /* A commit the SMC refused, or dark wakes that ended in a refusal. */ + apple_smc_wake_full(smc); } /* @@ -1836,6 +1908,9 @@ static int apple_smc_suspend_noirq(struct device *dev) struct apple_smc *smc = dev_get_drvdata(dev); int ret; + if (!pm_suspend_via_firmware()) + return 0; + /* For the time asleep a dark wake logs: boot time counts the sleep, monotonic doesn't. */ smc->sleep_entry_boot = ktime_get_boottime(); smc->sleep_entry_mono = ktime_get(); @@ -1854,7 +1929,12 @@ static int apple_smc_suspend_noirq(struct device *dev) static int apple_smc_resume_noirq(struct device *dev) { struct apple_smc *smc = dev_get_drvdata(dev); - bool woken = smc->woken_done; + bool woken; + + if (!pm_suspend_via_firmware()) + return 0; + + woken = smc->woken_done; /* This wake's own: never left for another attempt's resume */ smc->woken_done = false; diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 8ebd1d059e1d18..5afcf707a7c313 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -147,6 +147,13 @@ struct apple_smc { u8 wake_lid; int wake_lid_ret; u64 saved_unexpected; + /* WKTP left at its sleep value: written back once a wake is a full one. */ + bool wake_silent; + /* apple,sleep-wake-type: WKTP written at the sleep commit. */ + bool sleep_wake_type; + /* apple,sleep-pmvc: when set, the pmVC value written at the sleep commit. */ + bool sleep_pmvc_set; + u32 sleep_pmvc; /* To be told at the noirq suspend, after the debug link's cut. */ bool sleep_warn_late; /* In a noirq phase: replies are polled for. */ From 6b6b1e6ada93d1705abc2d400367f3101b4f57a1 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:51 +0000 Subject: [PATCH 1224/1514] drm/asahi: g17: enable sleep and warm firmware restart on T6041 Look up T6041's GPU power domain from PMP report entries in g17/sleep.c and enable sleep_restart on both the 32-core (t6041_25g83::CONFIG) and 40-core (CONFIG_25G83, tested on J614c by joske) T6041 profiles so the GPU stops cleanly before deep sleep and warm-restarts on wake. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/asahi/g17/sleep.c | 22 ++++++++++++++++++++-- drivers/gpu/drm/asahi/hw/t6041.rs | 2 ++ drivers/gpu/drm/asahi/hw/t6041_25g83.rs | 2 ++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/sleep.c b/drivers/gpu/drm/asahi/g17/sleep.c index 0131ace971222e..e62315b1eb2b57 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.c +++ b/drivers/gpu/drm/asahi/g17/sleep.c @@ -193,6 +193,24 @@ int asahi_g17_pmp_request(struct device *dev, bool enable) return ret; } +/* + * The node of the GPU's power state word. Where the GPU's first power domain is its PMP + * report entry (a small index for a reg, under the PMP), as in the J616C device tree the + * bring-up runs, the word is that entry's own domain. + */ +static struct device_node *asahi_g17_ps_node(struct device *dev) +{ + struct device_node *np, *next; + + np = of_parse_phandle(dev->of_node, "power-domains", 0); + if (np && of_device_is_compatible(np, "apple,t6000-pmp-v2-report-entry")) { + next = of_parse_phandle(np, "power-domains", 0); + of_node_put(np); + np = next; + } + return np; +} + static int asahi_g17_ps(struct device *dev, struct regmap **regmap, u32 *offset) { struct device_node *np; @@ -212,7 +230,7 @@ static int asahi_g17_ps(struct device *dev, struct regmap **regmap, u32 *offset) of_node_put(np); return ret; } - np = of_parse_phandle(dev->of_node, "power-domains", 0); + np = asahi_g17_ps_node(dev); if (!np) return -EINVAL; ret = of_property_read_u32(np, "reg", offset); @@ -622,7 +640,7 @@ struct asahi_g17_commit *asahi_g17_commit_prepare(struct device *dev, of_node_put(parent); of_node_put(np); } else { - np = of_parse_phandle(dev->of_node, "power-domains", 0); + np = asahi_g17_ps_node(dev); if (!np) goto err; if (!of_property_read_u32(np, "reg", &offset) && np->parent) diff --git a/drivers/gpu/drm/asahi/hw/t6041.rs b/drivers/gpu/drm/asahi/hw/t6041.rs index f2b4a464089da2..4cce54372a3f81 100644 --- a/drivers/gpu/drm/asahi/hw/t6041.rs +++ b/drivers/gpu/drm/asahi/hw/t6041.rs @@ -241,6 +241,8 @@ const CONFIG_25G83: Config = Config { reserved_slots: &[], chip: Some(&CHIP_25G83), firmware: fw::variant::Firmware::Identified(&[BUILD_25G83]), + // The GPU is restarted after a real sleep, as on the 32-core part. + sleep_restart: true, ..BASE }; diff --git a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs index 6ccd27f2ddc118..4afc2179f5632b 100644 --- a/drivers/gpu/drm/asahi/hw/t6041_25g83.rs +++ b/drivers/gpu/drm/asahi/hw/t6041_25g83.rs @@ -60,6 +60,8 @@ pub(super) const CONFIG: Config = Config { // hang this GPU's firmware on grids of more than ten workgroups. compute_blocks: 96, }, + // The GPU is restarted after a real sleep, as on T8140. + sleep_restart: true, ..t6041::BASE }; From 64933008d15299a50184ab12ddda118543436059 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:51 +0000 Subject: [PATCH 1225/1514] iommu/apple-dart: add display DART keep/restore helper for T6041 S2R Add apple_dart_display_keep() so the display driver can preserve and restore T6041 display/DCP DART stream translation state across host-driven display power-down and warm restart during suspend-to-RAM. Signed-off-by: AxxzyWasTaken --- drivers/iommu/apple-dart.c | 50 ++++++++++++++++++++++++++++++++++ include/linux/soc/apple/dart.h | 7 +++++ 2 files changed, 57 insertions(+) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index 2834878283a526..59060014f224a1 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -8121,6 +8121,56 @@ EXPORT_SYMBOL_GPL(apple_dart_gapf_ready); * Stopping again after a sleep that never reached the commit does nothing: the * domains may be off by then. */ +/* + * T6041: a display DART is locked, so the driver neither saves nor restores its TCR / TTBR, and + * after a real sleep the panel stayed black with everything else up. Keep the words of @streams + * before the sleep (save), and after it write back what differs (!save). Returns how many words + * were written back. + */ +int apple_dart_display_keep(struct device *dev, u32 streams, bool save) +{ + static struct { struct apple_dart *dart; u32 tcr[32]; u32 ttbr[32][4]; } keep[2]; + struct apple_dart *dart = dev_get_drvdata(dev); + unsigned long bits = streams; + unsigned int sid, idx, k, n = 0; + + if (!dart) + return -ENODEV; + for (k = 0; k < 2 && keep[k].dart && keep[k].dart != dart; k++) + ; + if (k == 2) + return -ENOSPC; + if (!save && keep[k].dart != dart) + return -ENOENT; + keep[k].dart = dart; + for_each_set_bit(sid, &bits, 32) { + u32 tcr = readl(dart->regs + DART_TCR(dart, sid)); + + if (sid >= dart->num_streams) + break; + if (save) + keep[k].tcr[sid] = tcr; + for (idx = 0; idx < dart->hw->ttbr_count && idx < 4; idx++) { + u32 ttbr = readl(dart->regs + DART_TTBR(dart, sid, idx)); + + if (save) { + keep[k].ttbr[sid][idx] = ttbr; + continue; + } + if (ttbr != keep[k].ttbr[sid][idx]) { + writel(keep[k].ttbr[sid][idx], dart->regs + DART_TTBR(dart, sid, idx)); + n++; + } + } + if (!save && tcr != keep[k].tcr[sid]) { + writel(keep[k].tcr[sid], dart->regs + DART_TCR(dart, sid)); + n++; + } + } + return n; +} +EXPORT_SYMBOL_GPL(apple_dart_display_keep); + int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush) { struct apple_dart *dart = dev_get_drvdata(dev); diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 0a7925025e6287..5c0fbf5688a3ba 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -187,6 +187,8 @@ int apple_dart_sleep_prepare(struct device *dev); void apple_dart_sleep_restore(struct device *dev); /* A display DART's streams around a display power cycle, see the DART driver. */ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool flush); +/* A locked display DART's TCR and TTBR words kept across a real sleep (T6041). */ +int apple_dart_display_keep(struct device *dev, u32 streams, bool save); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); /* A display DART whose domain goes off at runtime while others still map into it. */ @@ -221,6 +223,11 @@ static inline int apple_dart_display_streams(struct device *dev, u32 streams, bo return -ENODEV; } +static inline int apple_dart_display_keep(struct device *dev, u32 streams, bool save) +{ + return -ENODEV; +} + static inline int apple_dart_gapf_ready(struct device *dev) { return 0; From f8faa80e122bf02ff42f2066a54dd7c16d48d7ae Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:52 +0000 Subject: [PATCH 1226/1514] soc: apple: display-gate: handle trees that describe disabled DISPEXT domains When a device tree describes external display chains referencing disabled DISPEXT power domains, drop the dangling power-domains property on gated chain nodes so their devices do not wait on unavailable domain providers and defer-timeout the display subsystem. Trees without DISPEXT power domains are unaffected. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/display-gate.c | 37 +++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 7778598dc3f2bd..dc57af0dd16514 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -3300,7 +3300,39 @@ static const struct gate_staged *t6041_max_stage(unsigned int i) /* Applied, they stay: the live tree refers to them. Only the KUnit test reverts them. */ static struct of_changeset t6041_max_cs[ARRAY_SIZE(t6041_max_stages)]; -/* Enable every node of stage @i and put its display DART into the display subsystem's iommus. */ +/* + * Whether @np needs a power domain that stays disabled: neither enabled nor one of the nodes + * stage @st enables. + */ +static bool __init t6041_max_needs_off_domain(const struct gate_staged *st, struct device_node *np) +{ + struct of_phandle_args args; + bool off = false; + unsigned int n; + int i; + + for (i = 0; !off && !of_parse_phandle_with_args(np, "power-domains", "#power-domain-cells", + i, &args); i++) { + off = !of_device_is_available(args.np); + for (n = 0; off && n < st->nr; n++) { + struct device_node *dn = of_find_node_by_path(st->nodes[n]); + + off = dn != args.np; + of_node_put(dn); + } + of_node_put(args.np); + } + return off; +} + +/* + * Enable every node of stage @i and put its display DART into the display subsystem's iommus. + * The in-tree trees give the chains no DISPEXT power domain: they are on as iBoot left them. A + * tree that does describe them (the J616c's bring-up EL2 tree: dispextN_fe, and PMP report + * entries above them, all disabled) loses the property on the chain's nodes here, or each + * device would wait for a domain provider that never comes and give up at the deferred probe + * timeout, and the display subsystem with them. + */ static int __init t6041_max_apply(unsigned int i, struct device_node *display) { const struct gate_staged *st = t6041_max_stage(i); @@ -3316,6 +3348,9 @@ static int __init t6041_max_apply(unsigned int i, struct device_node *display) for (n = 0; !ret && n < st->nr; n++) { np = of_find_node_by_path(st->nodes[n]); ret = np ? of_changeset_update_prop_string(cs, np, "status", "okay") : -ENODEV; + if (!ret && t6041_max_needs_off_domain(st, np)) + ret = of_changeset_remove_property(cs, np, + of_find_property(np, "power-domains", NULL)); of_node_put(np); } if (!ret) From 82c60c2e73380d9dcd44aa7d69341fded4ad3cce Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:53 +0000 Subject: [PATCH 1227/1514] dt-bindings: display: describe T6041 host-driven sleep and display-power Add apple,sleep-host-stop and apple,display-power to apple,dcp.yaml and extend apple,t8140-display-power.yaml with the apple,t6041-display-power binding describing the PMC, power-gate, GAPF, AXI2AF register windows and per-chain PMGR power-domain phandles used during T6041 display S2R. Signed-off-by: AxxzyWasTaken --- .../bindings/display/apple,dcp.yaml | 15 +- .../display/apple,t8140-display-power.yaml | 158 +++++++++++++++++- 2 files changed, 163 insertions(+), 10 deletions(-) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index ca938411a566ae..849ee20abe3222 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -173,9 +173,10 @@ properties: apple,display-power: $ref: /schemas/types.yaml#/definitions/phandle description: - A node whose ps, pwrgate and pmc-dcp registers hold the display power - words this coprocessor's driver writes around a firmware restart, such - as an apple,t8140-display-power node. + A node describing the display power-state words (or PMGR power-domain + chains), power-gate retention words and pmc-dcp counter that this + coprocessor's driver writes around a firmware restart, such as an + apple,t8140-display-power or apple,t6041-display-power node. apple,bw-scratch: $ref: /schemas/types.yaml#/definitions/phandle-array @@ -381,6 +382,14 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: Display coprocessor index on multi-DCP systems. + apple,sleep-host-stop: + type: boolean + description: + The SoC's suspend-to-RAM needs this display coprocessor and the external + ones stopped, and their power domains lowered, by the operating system + before the sleep commit, and the internal one restarted after the wake. + The firmware doesn't take the display down for the sleep itself. + apple,typec-hybrid-first: type: boolean description: diff --git a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml index 7d157451342678..755f0c21e2d5da 100644 --- a/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml +++ b/Documentation/devicetree/bindings/display/apple,t8140-display-power.yaml @@ -4,30 +4,100 @@ $id: http://devicetree.org/schemas/display/apple,t8140-display-power.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# -title: Apple T8140 and T8142 display power words +title: Apple T6041, T8140 and T8142 display power words maintainers: - Diljit Singh description: - The words a display coprocessor's driver writes to power its domains off - and on around a restart of its firmware, as macOS does. A display - coprocessor names this node in its apple,display-power property. The words - belong to the power manager and the display block, so no driver binds it. + The words and PMGR power-state chains a display coprocessor's driver writes + to power its domains off and on around a restart of its firmware, as macOS + does. A display coprocessor names this node in its apple,display-power + property. The words belong to the power manager and the display block, so no + driver binds it. properties: compatible: enum: + - apple,t6041-display-power - apple,t8140-display-power - apple,t8142-display-power reg: minItems: 2 - maxItems: 3 + maxItems: 5 reg-names: minItems: 2 - maxItems: 3 + maxItems: 5 + + '#address-cells': + const: 1 + + '#size-cells': + const: 0 + +patternProperties: + '^chain@[0-9]+$': + type: object + description: | + One ordered display power-domain chain for apple,t6041-display-power, + powered down in reg order during suspend-to-RAM. + properties: + reg: + maxItems: 1 + + label: + description: Short name of the display chain (e.g. main, ext0..ext3). + + apple,main-chain: + type: boolean + description: + Marks the internal display chain, which clears the display AXI2AF + bridge and PMC voter on stop and is restarted warm on wake. + + apple,pwrgate-aux: + type: boolean + description: + Selects the pwrgate-aux register window instead of pwrgate for this + chain's power-gate retention words. + + apple,gapf-offset: + $ref: /schemas/types.yaml#/definitions/uint32 + description: + Byte offset of this chain's clock-protection slice within the gapf + register window. + + apple,pwrgate-offsets: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 2 + maxItems: 2 + description: + Byte offsets of the pair of power-gate retention words (A, then B) + within the selected pwrgate window. + + apple,fabric-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Parent fabric PMGR power-state node held manually on while this chain + powers down, then returned to its previous auto-enable state. + + power-domains: + minItems: 3 + maxItems: 16 + description: | + Ordered PMGR power-state nodes for this chain: SYS, FE, CPU, followed + by the chain's child sub-domains in parent-before-child order + (powered off in reverse). + + required: + - reg + - label + - apple,gapf-offset + - apple,pwrgate-offsets + - power-domains + + additionalProperties: false required: - compatible @@ -35,6 +105,35 @@ required: - reg-names allOf: + - if: + properties: + compatible: + const: apple,t6041-display-power + then: + properties: + reg: + items: + - description: the display PMC voter counter pair + - description: the internal display power gate retention words + - description: the external display power gate retention words + - description: the clock-protection slices for all display chains + - description: the internal display AXI2AF bridge registers + reg-names: + items: + - const: pmc-dcp + - const: pwrgate + - const: pwrgate-aux + - const: gapf + - const: axi2af + required: + - '#address-cells' + - '#size-cells' + else: + properties: + '#address-cells': false + '#size-cells': false + patternProperties: + '^chain@[0-9]+$': false - if: properties: compatible: @@ -70,6 +169,51 @@ allOf: additionalProperties: false examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + display-power@5048a9c14 { + compatible = "apple,t6041-display-power"; + reg = <0x5 0x048a9c14 0x0 0x8>, + <0x5 0x022a1000 0x0 0x100>, + <0x5 0x0282d000 0x0 0x1000>, + <0x5 0x00578000 0x0 0x1000>, + <0x4 0x03000100 0x0 0x10>; + reg-names = "pmc-dcp", "pwrgate", "pwrgate-aux", "gapf", "axi2af"; + #address-cells = <1>; + #size-cells = <0>; + + chain@0 { + reg = <0>; + label = "ext3"; + apple,pwrgate-aux; + apple,gapf-offset = <0x740>; + apple,pwrgate-offsets = <0xfb4 0xfd8>; + power-domains = <&ps_dispext3_sys>, <&ps_dispext3_fe>, + <&ps_dispext3_cpu>, <&ps_dispext3_dbe>, + <&ps_dpext3>, <&ps_dispext3_gp0>, + <&ps_dispext3_gp1>, <&ps_dispext3_gpl>, + <&ps_dispext3_ppp>, <&ps_dispext3_dsc>; + }; + + chain@4 { + reg = <4>; + label = "main"; + apple,main-chain; + apple,gapf-offset = <0x540>; + apple,pwrgate-offsets = <0x1c 0x60>; + apple,fabric-domain = <&ps_fab6_soc>; + power-domains = <&ps_disp_sys>, <&ps_disp_fe>, <&ps_disp_cpu>, + <&ps_disp_spi>, <&ps_disp_spmi>, <&ps_disp_dbe>, + <&ps_disp_dp>, <&ps_disp_gp0>, <&ps_disp_gp1>, + <&ps_disp_gpl>, <&ps_disp_cmb>, <&ps_disp_ppp>, + <&ps_disp_brc>, <&ps_disp_blc>; + }; + }; + }; + - | soc { #address-cells = <2>; From 4af660c74e44a83ffea3cf2825ada728dd292bee Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:53 +0000 Subject: [PATCH 1228/1514] drm/apple: T6041 S2R display stop and warm restart Implement host-driven display stop and warm restart for T6041 suspend-to-RAM, driven strictly from the apple,sleep-host-stop and apple,display-power DT properties without hardcoded addresses or unbacked fixed delays: - Parse the apple,display-power node's register windows (pmc-dcp, pwrgate, pwrgate-aux, gapf, axi2af) and per-chain PMGR power-domain phandles from DT at probe, failing sleep cleanly if required resources are missing. - Handle every enabled external DCP and mark all external chain DARTs dark by DT node before lowering their power words so post-wake framebuffer unmaps never flush a DART behind a powered-off block. - On 26.6 desktop firmware, route D572 through dcp_s2r_dart_power() and complete s2r_dart_done only on 0 ("done with display"), track in-flight dcp_ack() replies in iomfb_channels_idle(), send A500, idle RTKit, and poll hardware COPROC, GAPF, and PMGR PS_ACTUAL/PARENT_OFF status with bounded timeouts and error unwind. - On wake, raise the internal display domains, restore DART streams, warm-restart DCP firmware, wait for D575 hotplug completion and channel idle, recommit the active CRTC mode, restore backlight (with dcp_backlight_s2r_restore() declared in dcp_backlight.h), and restore boot power-word state. Propagate errors in apple_platform_suspend/resume. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/apple/apple_drv.c | 21 +- drivers/gpu/drm/apple/dcp-internal.h | 44 + drivers/gpu/drm/apple/dcp.c | 1106 ++++++++++++++++++- drivers/gpu/drm/apple/dcp.h | 1 + drivers/gpu/drm/apple/dcp_backlight.c | 28 + drivers/gpu/drm/apple/dcp_backlight.h | 1 + drivers/gpu/drm/apple/iomfb.c | 32 +- drivers/gpu/drm/apple/iomfb_template.c | 40 + drivers/gpu/drm/apple/iomfb_template.h | 3 + drivers/gpu/drm/apple/iomfb_v26_6_desktop.c | 23 +- tools/asahi/dcpext26-startup-tests.py | 7 +- 11 files changed, 1295 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 17d1416d636d23..58957e679b3926 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -2282,10 +2282,23 @@ static int apple_platform_suspend(struct device *dev) if (apple && apple->dark_held) return 0; + if (pm_suspend_via_firmware()) { + int ret = dcp_t6041_s2r_all(false); + + if (ret) + return ret; + } + if (apple && !apple->aborted) { apple->s2r_skipped = apple_drm_firmware_stopped(apple); - if (!apple->s2r_skipped) - return drm_mode_config_helper_suspend(&apple->drm); + if (!apple->s2r_skipped) { + int ret = drm_mode_config_helper_suspend(&apple->drm); + + if (ret) { + dcp_t6041_s2r_all(true); + return ret; + } + } } return 0; @@ -2333,6 +2346,10 @@ static int apple_platform_resume(struct device *dev) { struct apple_drm_private *apple = dev_get_drvdata(dev); + /* Nothing if this suspend never took the display down. */ + if (dcp_t6041_s2r_all(true)) + dev_err(dev, "T6041 S2R display resume failed\n"); + if (!apple || apple->aborted || apple->s2r_skipped) return 0; diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 8d18fa76949445..cb77aa8eabd5a1 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -253,6 +253,43 @@ struct dcp_s2r_layout { bool pmc_dcp; }; +/* + * One display power chain parsed from a child node of + * apple,t6041-display-power. domains[] is ordered sys, fe, cpu, then child + * sub-domains (parent-before-child; powered off in reverse). + */ +struct dcp_t6041_chain { + const char *name; + u32 reg; + bool is_main; + void __iomem *gapf; + void __iomem *pg_a; + void __iomem *pg_b; + void __iomem *fabric; + void __iomem **domains; + u32 *child_saved; + unsigned int num_domains; +}; + +/* + * Mapped register windows and display power chains from apple,display-power + * (apple,t6041-display-power) for host-driven T6041 suspend-to-RAM; mapped + * once at probe. + */ +struct dcp_t6041_power { + void __iomem *pmc_dcp; + void __iomem *pwrgate; + void __iomem *pwrgate_aux; + void __iomem *gapf; + void __iomem *axi2af; + struct dcp_t6041_chain *chains; + unsigned int num_chains; + struct dcp_t6041_chain *main_chain; + bool child_valid; + u32 boot_ps[3]; + bool boot_ps_valid; +}; + /* * Identity of a fixed internal panel, for the EDID published on its * connector. Any processor with an internal panel allocates it; the boot @@ -606,6 +643,8 @@ struct apple_dcp { */ bool ext_failsafe; bool ext_dead; + /* T6041 S2R: this external DCP's firmware stop ran in a sleep of this boot */ + bool t6041_ext_seen; /* * A T6030 external processor in the main DRM device: the kernel starts * its firmware on first use, its modes come from the attached display. @@ -747,6 +786,8 @@ struct apple_dcp { struct dcp_channel ch_cmd, ch_oobcmd; struct dcp_channel ch_cb, ch_oobcb, ch_async, ch_oobasync; + /* In-flight dcp_ack() mailbox sends not yet queued to RTKit. */ + atomic_t pending_acks; /* iomfb EP callback handlers */ const iomfb_cb_handler *cb_handlers; @@ -931,6 +972,9 @@ struct apple_dcp { bool s2r_power_oob; u8 s2r_step; struct completion s2r_dart_done; + struct completion s2r_hpd_done; + bool sleep_host_stop; + struct dcp_t6041_power t6041_power; struct device *s2r_disp_dart; struct device *s2r_dcp_dart; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 6f3a8604278dda..4e48c4574624f2 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -7469,6 +7470,347 @@ static void dcp_t8132_ext_routes(struct apple_dcp *dcp) static int dcp_s2r_pm_register(struct apple_dcp *dcp); +/* A DCP node with apple,sleep-host-stop: the SoC's sleep needs the display stopped from here. */ +static bool dcp_sleep_host_stop; +static bool dcp_sleep_host_stop_missing; +static struct apple_dcp *dcp_t6041_host; + +static void dcp_t6041_host_release(void *data) +{ + struct apple_dcp *dcp = data; + + if (READ_ONCE(dcp_t6041_host) == dcp) { + WRITE_ONCE(dcp_sleep_host_stop, false); + WRITE_ONCE(dcp_t6041_host, NULL); + } +} + +#define DCP_T6041_MAX_PMGR_MAPS 16 + +struct dcp_t6041_pmgr_map { + struct device_node *np; + void __iomem *base; + resource_size_t size; +}; + +struct dcp_t6041_pmgr_cache { + struct dcp_t6041_pmgr_map maps[DCP_T6041_MAX_PMGR_MAPS]; + unsigned int count; +}; + +static void dcp_t6041_iounmap(void *base) +{ + iounmap((__force void __iomem *)base); +} + +static void dcp_t6041_pmgr_cache_put(struct dcp_t6041_pmgr_cache *cache) +{ + unsigned int i; + + for (i = 0; i < cache->count; i++) + of_node_put(cache->maps[i].np); +} + +static void __iomem *dcp_t6041_map_reg(struct device *dev, struct device_node *np, + const char *name, resource_size_t min_size, + resource_size_t *out_size) +{ + struct resource res; + resource_size_t size; + void __iomem *base; + int index; + + index = of_property_match_string(np, "reg-names", name); + if (index < 0) + return IOMEM_ERR_PTR(index); + if (of_address_to_resource(np, index, &res)) + return IOMEM_ERR_PTR(-EINVAL); + size = resource_size(&res); + if (size < min_size) { + dev_err(dev, "%pOF reg '%s' too small (%pa < %pa)\n", + np, name, &size, &min_size); + return IOMEM_ERR_PTR(-EINVAL); + } + + /* Shared with the PMGR, PMC and fabric drivers, so not claimed. */ + base = devm_ioremap(dev, res.start, size); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + if (out_size) + *out_size = size; + + return base; +} + +static void __iomem *dcp_t6041_map_ps_node(struct device *dev, + struct dcp_t6041_pmgr_cache *cache, + struct device_node *ps_np) +{ + struct device_node *pmgr_np __free(device_node) = of_get_parent(ps_np); + struct dcp_t6041_pmgr_map *map = NULL; + struct resource res; + resource_size_t size; + void __iomem *base; + unsigned int i; + u32 off; + int ret; + + if (!pmgr_np) { + dev_err(dev, "%pOF has no parent pmgr node\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + if (of_property_read_u32_index(ps_np, "reg", 0, &off)) { + dev_err(dev, "%pOF missing reg offset\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + + for (i = 0; i < cache->count; i++) { + if (cache->maps[i].np == pmgr_np) { + map = &cache->maps[i]; + break; + } + } + + if (!map) { + if (cache->count >= ARRAY_SIZE(cache->maps)) { + dev_err(dev, "too many distinct pmgr parents for %pOF\n", ps_np); + return IOMEM_ERR_PTR(-ENOSPC); + } + if (of_address_to_resource(pmgr_np, 0, &res)) { + dev_err(dev, "%pOF missing parent pmgr reg\n", pmgr_np); + return IOMEM_ERR_PTR(-EINVAL); + } + size = resource_size(&res); + /* Shared with the PMGR driver, so mapped via of_iomap without claiming. */ + base = of_iomap(pmgr_np, 0); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + ret = devm_add_action_or_reset(dev, dcp_t6041_iounmap, (__force void *)base); + if (ret) + return IOMEM_ERR_PTR(ret); + + map = &cache->maps[cache->count++]; + map->np = of_node_get(pmgr_np); + map->base = base; + map->size = size; + } + + if ((off & 3) || off > map->size || map->size - off < sizeof(u32)) { + dev_err(dev, "%pOF reg offset %#x out of bounds for %pOF (%pa)\n", + ps_np, off, pmgr_np, &map->size); + return IOMEM_ERR_PTR(-EINVAL); + } + + return map->base + off; +} + +static int dcp_t6041_parse_chain(struct device *dev, struct dcp_t6041_power *pwr, + struct dcp_t6041_pmgr_cache *cache, + struct device_node *child, + resource_size_t gapf_size, + resource_size_t pg_size, + resource_size_t pg_aux_size, + struct dcp_t6041_chain *chain) +{ + struct of_phandle_args args; + resource_size_t pg_lim; + void __iomem *pg_base; + u32 gapf_off, pg_off[2]; + bool pg_aux; + int count, i; + + if (of_property_read_u32(child, "reg", &chain->reg)) { + dev_err(dev, "%pOF missing reg\n", child); + return -EINVAL; + } + if (of_property_read_string(child, "label", &chain->name)) + chain->name = child->name; + + chain->is_main = of_property_read_bool(child, "apple,main-chain"); + pg_aux = of_property_read_bool(child, "apple,pwrgate-aux"); + + if (of_property_read_u32(child, "apple,gapf-offset", &gapf_off) || + (gapf_off & 3) || gapf_off > gapf_size || gapf_size - gapf_off < sizeof(u32)) { + dev_err(dev, "%pOF invalid apple,gapf-offset\n", child); + return -EINVAL; + } + chain->gapf = pwr->gapf + gapf_off; + + pg_base = pg_aux ? pwr->pwrgate_aux : pwr->pwrgate; + pg_lim = pg_aux ? pg_aux_size : pg_size; + if (of_property_read_u32_array(child, "apple,pwrgate-offsets", pg_off, 2) || + (pg_off[0] & 3) || pg_off[0] > pg_lim || pg_lim - pg_off[0] < sizeof(u32) || + (pg_off[1] & 3) || pg_off[1] > pg_lim || pg_lim - pg_off[1] < sizeof(u32)) { + dev_err(dev, "%pOF invalid apple,pwrgate-offsets\n", child); + return -EINVAL; + } + chain->pg_a = pg_base + pg_off[0]; + chain->pg_b = pg_base + pg_off[1]; + + if (of_property_present(child, "apple,fabric-domain")) { + struct device_node *fab_np __free(device_node) = + of_parse_phandle(child, "apple,fabric-domain", 0); + + if (!fab_np) { + dev_err(dev, "%pOF invalid apple,fabric-domain\n", child); + return -EINVAL; + } + chain->fabric = dcp_t6041_map_ps_node(dev, cache, fab_np); + if (IS_ERR(chain->fabric)) + return PTR_ERR(chain->fabric); + } else if (chain->is_main) { + dev_err(dev, "%pOF main chain missing apple,fabric-domain\n", child); + return -EINVAL; + } + + count = of_count_phandle_with_args(child, "power-domains", "#power-domain-cells"); + if (count < 3) { + dev_err(dev, "%pOF needs at least 3 power-domains (got %d)\n", child, count); + return -EINVAL; + } + + chain->domains = devm_kcalloc(dev, count, sizeof(*chain->domains), GFP_KERNEL); + if (!chain->domains) + return -ENOMEM; + chain->num_domains = count; + + for (i = 0; i < count; i++) { + int ret = of_parse_phandle_with_args(child, "power-domains", + "#power-domain-cells", i, &args); + void __iomem *reg; + + if (ret) { + dev_err(dev, "%pOF power-domains[%d] parse failed: %d\n", child, i, ret); + return ret; + } + reg = dcp_t6041_map_ps_node(dev, cache, args.np); + of_node_put(args.np); + if (IS_ERR(reg)) + return PTR_ERR(reg); + chain->domains[i] = reg; + } + + if (chain->is_main && count > 3) { + chain->child_saved = devm_kcalloc(dev, count - 3, sizeof(*chain->child_saved), + GFP_KERNEL); + if (!chain->child_saved) + return -ENOMEM; + } + + return 0; +} + +static int dcp_t6041_map_power(struct apple_dcp *dcp) +{ + struct device *dev = dcp->dev; + struct device_node *np __free(device_node) = + of_parse_phandle(dev->of_node, "apple,display-power", 0); + struct dcp_t6041_power *pwr = &dcp->t6041_power; + struct dcp_t6041_pmgr_cache cache = {}; + resource_size_t pg_size = 0, pg_aux_size = 0, gapf_size = 0; + const struct { + const char *name; + void __iomem **dst; + resource_size_t min_size; + resource_size_t *out_size; + } regs[] = { + { "pmc-dcp", &pwr->pmc_dcp, 0x8, NULL }, + { "pwrgate", &pwr->pwrgate, 0x4, &pg_size }, + { "pwrgate-aux", &pwr->pwrgate_aux, 0x4, &pg_aux_size }, + { "gapf", &pwr->gapf, 0x4, &gapf_size }, + { "axi2af", &pwr->axi2af, 0xc, NULL }, + }; + unsigned int nchains = 0, idx = 0, main_count = 0, i, j; + int ret; + + if (!np) + return -ENODEV; + if (!of_device_is_compatible(np, "apple,t6041-display-power")) + return -EINVAL; + + for (i = 0; i < ARRAY_SIZE(regs); i++) { + void __iomem *base = dcp_t6041_map_reg(dev, np, regs[i].name, + regs[i].min_size, regs[i].out_size); + + if (IS_ERR(base)) { + dev_err(dev, "apple,display-power reg '%s' failed: %ld\n", + regs[i].name, PTR_ERR(base)); + ret = PTR_ERR(base); + goto err; + } + *regs[i].dst = base; + } + + for_each_available_child_of_node_scoped(np, child) { + if (!of_node_name_eq(child, "chain")) + continue; + nchains++; + } + if (!nchains) { + dev_err(dev, "%pOF has no chain child nodes\n", np); + ret = -EINVAL; + goto err; + } + + pwr->chains = devm_kcalloc(dev, nchains, sizeof(*pwr->chains), GFP_KERNEL); + if (!pwr->chains) { + ret = -ENOMEM; + goto err; + } + pwr->num_chains = nchains; + + for_each_available_child_of_node_scoped(np, child) { + if (!of_node_name_eq(child, "chain")) + continue; + ret = dcp_t6041_parse_chain(dev, pwr, &cache, child, + gapf_size, pg_size, pg_aux_size, + &pwr->chains[idx]); + if (ret) + goto err; + if (pwr->chains[idx].is_main) + main_count++; + idx++; + } + + if (main_count != 1) { + dev_err(dev, "%pOF expected exactly 1 apple,main-chain, got %u\n", + np, main_count); + ret = -EINVAL; + goto err; + } + + /* Order chains by ascending reg address so lowering order matches DT. */ + for (i = 1; i < nchains; i++) { + struct dcp_t6041_chain key = pwr->chains[i]; + + for (j = i; j > 0 && pwr->chains[j - 1].reg > key.reg; j--) + pwr->chains[j] = pwr->chains[j - 1]; + pwr->chains[j] = key; + } + for (i = 1; i < nchains; i++) { + if (pwr->chains[i].reg == pwr->chains[i - 1].reg) { + dev_err(dev, "%pOF duplicate chain reg %u\n", + np, pwr->chains[i].reg); + ret = -EINVAL; + goto err; + } + } + for (i = 0; i < nchains; i++) { + if (pwr->chains[i].is_main) { + pwr->main_chain = &pwr->chains[i]; + break; + } + } + + dcp_t6041_pmgr_cache_put(&cache); + return 0; + +err: + dcp_t6041_pmgr_cache_put(&cache); + memset(pwr, 0, sizeof(*pwr)); + return ret; +} + static int dcp_platform_probe_pipe(struct platform_device *pdev) { const struct apple_dcp_hw_data *hw = of_device_get_match_data(&pdev->dev); @@ -7754,9 +8096,27 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_property_read_u32(dev->of_node, "apple,dcp-endpoint", &dcp->peer_endpoint); if (of_property_read_bool(dev->of_node, "apple,typec-hybrid-first")) dcp_typec_hybrid_first_dt(); + if (of_property_read_bool(dev->of_node, "apple,sleep-host-stop")) { + ret = dcp_t6041_map_power(dcp); + if (ret) { + dev_err(dev, + "apple,display-power unusable (%d): host-driven sleep disabled\n", + ret); + WRITE_ONCE(dcp_sleep_host_stop_missing, true); + } else { + dcp->sleep_host_stop = true; + WRITE_ONCE(dcp_t6041_host, dcp); + WRITE_ONCE(dcp_sleep_host_stop, true); + ret = devm_add_action_or_reset(dev, dcp_t6041_host_release, dcp); + if (ret) + return ret; + } + } of_property_read_u32(dev->of_node, "apple,dptx-phy", &dcp->dptx_phy); of_property_read_u32(dev->of_node, "apple,dptx-die", &dcp->dptx_die); dcp->fixed_dptx_phy = dcp->dptx_phy; + init_completion(&dcp->s2r_dart_done); + init_completion(&dcp->s2r_hpd_done); init_completion(&dcp->typec_iomfb_hpd_ready); INIT_DELAYED_WORK(&dcp->typec_reconnect_wq, dcp_typec_reconnect_work); @@ -8733,6 +9093,10 @@ static const struct dcp_s2r_layout *dcp_s2r_layout(struct apple_dcp *dcp) return &dcp_s2r_t8142_ext[dcp->index - 1]; return dcp->hw.s2r_layout ?: &dcp_s2r_t8140; } + +/* T6041's display stop and restart for its own sleep driver, below: T8140's DART streams. */ +#define DCP_S2R_DISP_STREAMS (dcp_s2r_t8140.disp_streams) +#define DCP_S2R_DCP_STREAMS (dcp_s2r_t8140.dcp_streams) #define DCP_PS_MIN GENMASK(19, 16) static struct device *dcp_s2r_find_dart(struct device_node *np) @@ -8775,13 +9139,18 @@ static void dcp_s2r_find_darts(struct apple_dcp *dcp) void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) { + if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) + dev_dbg(dcp->dev, "D572(%u) s2r_active=%u\n", + on, READ_ONCE(dcp->s2r_active)); + if (!READ_ONCE(dcp->s2r_active)) return; if (dcp->s2r_disp_dart) apple_dart_display_streams(dcp->s2r_disp_dart, dcp_s2r_layout(dcp)->disp_streams, on, false); - complete(&dcp->s2r_dart_done); + if (dcp->fw_compat != DCP_FIRMWARE_V_26_6_DESKTOP || !on) + complete(&dcp->s2r_dart_done); } static bool dcp_s2r_capable(struct apple_dcp *dcp) @@ -10650,6 +11019,741 @@ static struct platform_driver apple_platform_driver = { }, }; +/* + * T6041 suspend-to-RAM: each display firmware is stopped from Linux before the sleep, from the + * display subsystem's own suspend, and the internal one is restarted warm after the wake. + */ +static int dcp_stop_poller(void *data) +{ + while (!kthread_should_stop()) { + apple_rtkit_poll(data); + usleep_range(500, 1000); + } + return 0; +} + +static int dcp_t6041_recommit(struct apple_dcp *dcp); + +static int dcp_t6041_stop_one(struct device *dev, void *data) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + bool external = *(bool *)data; + struct task_struct *poller; + bool keep_set = false; + bool powered_off = false; + bool idle_attempted = false; + bool idle; + u32 ctrl, status; + int ret; + + /* dcp->external is only set on T6030. */ + if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || dcp->sleep_host_stop == external) + return 0; + /* + * An external DCP stopped for an earlier sleep stays down, with its domains forced off by + * the power word step: reading its registers again hung the second sleep of a boot (11 Nov). + */ + if (external) { + /* Also one that was never running: the power word step took its domains down too. */ + if (READ_ONCE(dcp->ext_dead) || dcp->t6041_ext_seen) + return 0; + } + if (!apple_rtkit_is_running(dcp->rtk)) { + if (external) { + dcp_s2r_find_darts(dcp); + if (dcp->s2r_disp_dart) + apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, false, true); + dcp->t6041_ext_seen = true; + } + dcp_s2r_put_darts(dcp); + return 0; + } + dcp_drain_for_sleep(dcp); + cancel_delayed_work_sync(&dcp->swap_watchdog_wq); + iomfb_pause_presentation(dcp, true); + iomfb_queue_settle(dcp, msecs_to_jiffies(500)); + dcp_s2r_find_darts(dcp); + if (!external) { + if (dcp->s2r_disp_dart) + apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true); + if (dcp->s2r_dcp_dart) + apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, true); + keep_set = true; + /* + * As linux#1477 dcp_t6041_s2r_stop: the pipe off through the firmware, then wait for + * its calls to settle. No av_service_disconnect: the firmware answered it with an + * unplug (HPD removed), and after the warm restart it refused every mode set with + * "HPD is 0 link_status is 0" (10 Nov). No display sleep transition after the + * power-off either. + */ + /* + * The firmware's D572(0) after the power-off says it is done with the display, and + * dcp_s2r_dart_power() turns the display DART's streams off right there, as macOS + * does. Turned off while the pipe still scanned out, they crashed the firmware + * (axi_rd_err, 11 Nov). Without D572(0) abort sleep instead of tearing down domains + * while scanning out. + */ + reinit_completion(&dcp->s2r_dart_done); + WRITE_ONCE(dcp->s2r_active, true); + _dcp_poweroff(dcp); + powered_off = true; + if (!wait_for_completion_timeout(&dcp->s2r_dart_done, + msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) { + WRITE_ONCE(dcp->s2r_active, false); + dev_err(dev, "no D572 after the power-off\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + WRITE_ONCE(dcp->s2r_active, false); + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dev, "display calls still in flight after the power-off\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + } + ret = iomfb_s2r_500_v26_6_desktop(dcp); + if (ret) { + dev_err(dev, "no reply to A500: %d\n", ret); + goto err_unwind; + } + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 100000, false, dcp)) { + dev_err(dev, "display calls still in flight after A500\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } + idle_attempted = true; + ret = apple_rtkit_idle(dcp->rtk); + if (ret) { + poller = kthread_run(dcp_stop_poller, dcp->rtk, "dcpstop"); + ret = apple_rtkit_idle(dcp->rtk); + if (!IS_ERR(poller)) + kthread_stop(poller); + } + if (ret) { + dev_err(dev, "the firmware didn't go idle for the sleep: %d\n", ret); + goto err_unwind; + } + apple_rtkit_poll(dcp->rtk); + /* + * T6041 desktop firmware reaches status 0x6d (IDLE set, STOPPED clear) on + * apple_rtkit_idle(). Both AP and IOP have already acknowledged IDLE here, + * so proceed even if IDLE is late, matching apple_rtkit_sleep_idle(). + */ + ret = readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS, status, + status & APPLE_DCP_COPROC_CPU_STATUS_IDLE, 100, 50000); + if (ret) + dev_warn(dev, "coprocessor did not set IDLE after RTKit idle: status %#x\n", + status); + /* + * QUIESCED and SLEEP after idle: T23 reached STOPPED (0x6e) only this way. Not for the + * internal DCP: linux#1477 stops it at the idle (A500, idle, mailbox off, run bit, bit 5) + * and its warm restart then works; after a shutdown ours crashed in the restart (10 Nov, + * data abort at 0xffffffff00000040 right after the first shmem_setup). + */ + if (external) { + dcp->t6041_ext_seen = true; + ret = apple_rtkit_shutdown(dcp->rtk); + if (ret) + dev_warn(dev, "external coprocessor shutdown failed: %d\n", ret); + if (readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_STATUS, status, + (status & (APPLE_DCP_COPROC_CPU_STATUS_IDLE | + APPLE_DCP_COPROC_CPU_STATUS_STOPPED)) == + (APPLE_DCP_COPROC_CPU_STATUS_IDLE | + APPLE_DCP_COPROC_CPU_STATUS_STOPPED), 100, 50000)) + dev_warn(dev, "external coprocessor did not reach stopped: status %#x\n", + status); + } + WRITE_ONCE(dcp->crashed, true); + WRITE_ONCE(dcp->ext_dead, true); + WRITE_ONCE(dcp->s2r_fw_down, true); + apple_rtkit_mailbox_off(dcp->rtk); + dcp_s2r_cpu_stop(dcp); + ret = readl_poll_timeout(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL, ctrl, + !(ctrl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), 100, 10000); + if (ret) { + dev_err(dev, "coprocessor RUN bit did not clear: control %#x\n", ctrl); + dcp_s2r_put_darts(dcp); + return ret; + } + /* + * External display DARTs go dark for good while their block is still on: + * the power word step forces the external display domains off and nothing raises + * them, but the framebuffers are mapped through all display DARTs, so every + * later unmap would flush a DART behind a dead block (11 Nov). + * Marked dark, the flush only publishes to memory. + */ + if (external && dcp->s2r_disp_dart) + apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, + false, true); + ret = dcp_s2r_stop_streams(dcp); + dcp_s2r_put_darts(dcp); + if (ret) { + dev_err(dev, "failed to stop DCP DART streams: %d\n", ret); + return ret; + } + + return 0; + +err_unwind: + if (!external) { + if (keep_set) { + if (dcp->s2r_disp_dart) + apple_dart_display_keep(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, false); + if (dcp->s2r_dcp_dart) + apple_dart_display_keep(dcp->s2r_dcp_dart, + DCP_S2R_DCP_STREAMS, false); + } + if (powered_off && dcp->s2r_disp_dart) + apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, true, false); + } + dcp_s2r_put_darts(dcp); + iomfb_pause_presentation(dcp, false); + if (idle_attempted) { + int ap_ret = apple_rtkit_ap_power(dcp->rtk, true); + + if (ap_ret) + dev_warn(dev, "AP on after failed stop: %d\n", ap_ret); + } + if (!external && powered_off) { + if (dcp_t6041_recommit(dcp)) + dev_err(dev, "display recovery after failed stop failed\n"); + else + dcp_backlight_s2r_restore(dcp); + } + return ret; +} + +/* + * The power words of each display CPU down, after its firmware stopped. The fabric rejects + * writes to a DCP's CPU word until bit 4 of its GAPF slice is clear: ADT + * clock-protection-slice-index, 0x100 + 0x40 * index. Then macOS's order on the Neo. + */ +static int dcp_t6041_word_try(struct device *dev, struct dcp_t6041_power *pwr, + struct dcp_t6041_chain *chain) +{ + void __iomem *gapf = chain->gapf; + void __iomem *rsys = chain->domains[0]; + void __iomem *rfe = chain->domains[1]; + void __iomem *rcpu = chain->domains[2]; + void __iomem *ra = chain->pg_a; + void __iomem *rb = chain->pg_b; + void __iomem *rfab = NULL; + unsigned int i; + u32 val, fab = 0, cur; + int ret = 0; + + val = readl(gapf); + writel(val & ~BIT(4), gapf); + if (readl_poll_timeout(gapf, cur, !(cur & BIT(4)), 10, 5000)) { + dev_err(dev, "dcp %s: GAPF write protection stayed set: %#x\n", + chain->name, cur); + return -ETIMEDOUT; + } + val = readl(rcpu); + writel(val & ~(BIT(28) | GENMASK(9, 8)), rcpu); + if (readl_poll_timeout(rcpu, cur, !(cur & BIT(28)), 10, 5000)) { + dev_err(dev, "dcp %s: CPU auto-enable did not clear: %#x\n", + chain->name, cur); + return -ETIMEDOUT; + } + val = cur; + /* + * Everything macOS's sleep check wants off under this CPU, last first: DSC, PPP, GPL, + * GP1, GP0, DPEXT, DBE. iBoot leaves them on over a DCP Linux never started. + */ + if (chain->is_main && chain->child_saved) { + for (i = 3; i < chain->num_domains; i++) + chain->child_saved[i - 3] = readl(chain->domains[i]); + pwr->child_valid = true; + } + for (i = chain->num_domains; i-- > 3; ) { + void __iomem *sub = chain->domains[i]; + + val = readl(sub); + if (val & BIT(28)) { + val &= ~(BIT(28) | GENMASK(9, 8)); + writel(val, sub); + } + writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), sub); + if (readl_poll_timeout(sub, cur, !FIELD_GET(GENMASK(7, 4), cur), + 50, 20000)) { + dev_err(dev, "dcp %s: child %u did not power off: %#x\n", + chain->name, i - 2, cur); + return -ETIMEDOUT; + } + } + val = readl(rcpu); + /* + * Two things the restart sets that boot did not have, undone before the lowering: bit 0 of + * both words of bridge 4 (boot 0x10000 / 0x101330, after a restart 0x10001 / 0x101331) and the + * display voter count at pmc-dcp (boot 0, after a restart 1). With them left, the + * second lowering of a boot ends with FE 0x200 and SYS 0x800 (bit 11) instead of 0x300 / 0x300. + */ + if (chain->is_main) { + writel(readl(pwr->axi2af + 0x4) & ~1U, pwr->axi2af + 0x4); + writel(readl(pwr->axi2af + 0x8) & ~1U, pwr->axi2af + 0x8); + writel(0, pwr->pmc_dcp); + } + if (chain->fabric) { + /* + * The internal display's SYS hangs off fab6_soc, which gates itself as soon as + * nothing under it is on. Lowered while the fabric is already going (second stop + * of a boot, the external pipes long off), SYS latches PARENT_OFF (reads 0x800, + * FE 0x200), the sleep engine waits on that bit and the chip resets. So: the + * fabric on by hand until SYS is down. + */ + rfab = chain->fabric; + fab = readl(rfab); + writel((fab & ~(BIT(28) | GENMASK(9, 8) | GENMASK(3, 0))) | 0xf, rfab); + if (readl_poll_timeout(rfab, cur, FIELD_GET(GENMASK(7, 4), cur) == 0xf, + 50, 20000)) { + dev_err(dev, "dcp %s: fabric domain not on: %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + } + writel(3, ra); + writel(0, rb); + writel((val & ~GENMASK(3, 0)) | GENMASK(9, 8), rcpu); + val = readl(rfe); + if (val & BIT(28)) + writel(val & ~(BIT(28) | GENMASK(9, 8)), rfe); + writel((readl(rfe) & ~GENMASK(3, 0)) | GENMASK(9, 8), rfe); + val = readl(rsys); + if (val & BIT(28)) + writel(val & ~(BIT(28) | GENMASK(9, 8)), rsys); + writel((readl(rsys) & ~GENMASK(3, 0)) | GENMASK(9, 8), rsys); + /* + * Verify CPU, FE and SYS all reach off; macOS polls up to 50 ms here. The internal + * chain must also not have latched PARENT_OFF (bit 11), see above. + */ + if (readl_poll_timeout(rcpu, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: cpu still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + if (readl_poll_timeout(rfe, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: fe still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } + if (readl_poll_timeout(rsys, cur, + !FIELD_GET(GENMASK(7, 4), cur) && + (!chain->is_main || !(cur & BIT(11))), + 50, 100000)) { + dev_err(dev, "dcp %s: sys still %#x\n", chain->name, cur); + ret = -ETIMEDOUT; + goto restore_fab; + } +restore_fab: + if (rfab) { + /* Back to automatic, as it was; the flag bits are write-one-to-clear, left alone. */ + writel((readl(rfab) & ~(GENMASK(9, 8) | BIT(28))) | (fab & BIT(28)), rfab); + if (readl_poll_timeout(rfab, cur, (cur & BIT(28)) == (fab & BIT(28)), 10, 5000)) { + dev_err(dev, "dcp %s: fabric auto-enable did not restore: %#x\n", + chain->name, cur); + if (!ret) + ret = -ETIMEDOUT; + } + } + + return ret; +} + +/* + * After a real wake: the internal DCP back, as linux#1477 does it for the M4 Pro + * (t6040_disp_back, dcp_t6041_s2r_domains_on, dcp_t6041_s2r_resume, the warm restart and the + * mode set of dcp_hib_recommit): DISP_SYS on, the retention pair (A := 0, B := 1), DISP_FE on, + * the GAPF protection off, DISP_CPU on, its child domains as the stop found them, the PMC voter, + * both DARTs' streams, the idled firmware restarted, the pipe powered and the mode set again. + */ +static int dcp_t6041_recommit(struct apple_dcp *dcp) +{ + struct apple_crtc *acrtc = READ_ONCE(dcp->crtc); + struct drm_modeset_acquire_ctx ctx; + struct drm_atomic_commit *state; + struct drm_crtc_state *cs; + struct drm_crtc *crtc; + ktime_t start = ktime_get(); + bool idle; + int ret; + + reinit_completion(&dcp->s2r_hpd_done); + iomfb_poweron_v26_6_desktop(dcp); + if (dcp->desktop && dcp->desktop->poweron_result) { + dev_err(dcp->dev, "display power-on after the sleep failed (%u)\n", + dcp->desktop->poweron_result); + return dcp->desktop->poweron_result == 1 ? -ETIMEDOUT : -EIO; + } + if (!wait_for_completion_timeout(&dcp->s2r_hpd_done, msecs_to_jiffies(1000))) { + dev_err(dcp->dev, "no D575 hotplug %lld ms after power-on\n", + ktime_ms_delta(ktime_get(), start)); + return -ETIMEDOUT; + } + dev_dbg(dcp->dev, "D575 hotplug ready %lld ms after power-on\n", + ktime_ms_delta(ktime_get(), start)); + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dcp->dev, "display calls still in flight after D575\n"); + return -ETIMEDOUT; + } + if (!acrtc) + return 0; + crtc = &acrtc->base; + DRM_MODESET_LOCK_ALL_BEGIN(crtc->dev, ctx, 0, ret); + if (!crtc->state->active) { + ret = 0; + goto unlock; + } + state = drm_atomic_commit_alloc(crtc->dev); + if (!state) { + ret = -ENOMEM; + goto unlock; + } + state->acquire_ctx = &ctx; + cs = drm_atomic_get_crtc_state(state, crtc); + if (IS_ERR(cs)) { + ret = PTR_ERR(cs); + goto put; + } + cs->mode_changed = true; + ret = drm_atomic_add_affected_connectors(state, crtc); + if (!ret) + ret = drm_atomic_add_affected_planes(state, crtc); + if (!ret) + ret = drm_atomic_commit(state); +put: + drm_atomic_commit_put(state); +unlock: + DRM_MODESET_LOCK_ALL_END(crtc->dev, ctx, ret); + return ret; +} + +/* + * The internal display's SYS, FE and CPU power words as they were before the first stop (from + * boot: SYS and FE with no flags, the CPU word 0x1000030f, automatic). The restart leaves the CPU + * word manual (0x0f0003ff) and SYS/FE with both flags, and the first display power-off after such + * a wake hung the machine (11 Nov, run 6). Captured once and put back once the display runs again. + */ +static int dcp_t6041_boot_ps_io(struct apple_dcp *dcp, bool restore) +{ + static const char *const names[3] = { "sys", "fe", "cpu" }; + struct dcp_t6041_power *pwr = &dcp->t6041_power; + const struct dcp_t6041_chain *main = pwr->main_chain; + bool idle; + u32 cur; + int i; + + if (!main || main->num_domains < 3) + return -EINVAL; + + if (!restore) { + if (pwr->boot_ps_valid) + return 0; + for (i = 0; i < 3; i++) + pwr->boot_ps[i] = readl(main->domains[i]); + pwr->boot_ps_valid = true; + return 0; + } + + if (!pwr->boot_ps_valid) + return 0; + + if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { + dev_err(dcp->dev, "display calls still in flight before restoring boot power words\n"); + return -ETIMEDOUT; + } + for (i = 0; i < 3; i++) { + if (!pwr->boot_ps[i]) + continue; + if (readl_poll_timeout(main->domains[i], cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) { + dev_err(dcp->dev, "display %s power word not on before restore: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } + for (i = 0; i < 3; i++) { + u32 want = pwr->boot_ps[i] & ~0xf0U; + + if (!pwr->boot_ps[i]) + continue; + writel(want, main->domains[i]); + if (want & BIT(28)) { + /* + * AUTO_ENABLE lets hardware drop PS_ACTUAL to 0 while the DCP CPU sits + * idle in WFI, so poll target + AUTO_ENABLE + !PARENT_OFF instead. + */ + if (readl_poll_timeout(main->domains[i], cur, + (cur & (BIT(28) | GENMASK(3, 0))) == + (want & (BIT(28) | GENMASK(3, 0))) && + !(cur & BIT(11)), 50, 10000)) { + dev_err(dcp->dev, + "display %s power word did not restore auto-enable: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } else { + if (readl_poll_timeout(main->domains[i], cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && + !(cur & BIT(11)), 50, 10000)) { + dev_err(dcp->dev, + "display %s power word did not stay on after restore: %#x\n", + names[i], cur); + return -ETIMEDOUT; + } + } + } + + return 0; +} + +static int dcp_t6041_start_one(struct device *dev, void *data) +{ + struct apple_dcp *dcp = dev_get_drvdata(dev); + struct dcp_t6041_power *pwr; + const struct dcp_t6041_chain *main; + void __iomem *rsys, *rfe, *rcpu, *gapf, *pmc; + unsigned int i; + u32 v, cur, to = 0; + int ret, ps_ret; + + if (!dcp || IS_ERR_OR_NULL(dcp->rtk) || !dcp->sleep_host_stop) + return 0; + pwr = &dcp->t6041_power; + main = pwr->main_chain; + if (!main || main->num_domains < 3) + return -EINVAL; + rsys = main->domains[0]; + rfe = main->domains[1]; + rcpu = main->domains[2]; + gapf = main->gapf; + pmc = pwr->pmc_dcp; + + v = readl(rsys) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + /* + * As macOS's wake writes them: target on with both flag bits clear (0xf). Raised with the + * flags kept (0x30f) the word reads 0x3ff, a later write can't clear them, and the next + * lowering then latches bit 11 on SYS (0x800) and leaves FE at 0x200: the sleep engine waits + * on that bit and the chip resets (second sleep of a boot, 11 Nov). + */ + writel((v & ~0x30fU) | 0xf, rsys); + if (readl_poll_timeout(rsys, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(0); + writel(0, main->pg_a); + writel(1, main->pg_b); + /* + * Bridge 4 stays as boot has it (bit 0 of both words clear, 0x10000 / 0x101330), unlike + * macOS's wake: with it set, the driver's own display power-off after a wake froze the whole + * machine right after "dcp_poweroff() done" (login after a wake, sddm restart; 11 Nov). + */ + v = readl(rfe) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); + writel((v & ~0x30fU) | 0xf, rfe); + if (readl_poll_timeout(rfe, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(1); + writel(readl(gapf) & ~BIT(4), gapf); + if (readl_poll_timeout(gapf, cur, !(cur & BIT(4)), 10, 5000)) + to |= BIT(3); + v = readl(rcpu); + writel((v & ~(0x30fU | BIT(28))) | 0xf, rcpu); + mb(); + if (readl_poll_timeout(rcpu, cur, + FIELD_GET(GENMASK(7, 4), cur) == 0xf && !(cur & BIT(11)), + 50, 10000)) + to |= BIT(2); + for (i = 3; i < main->num_domains && pwr->child_valid && main->child_saved; i++) { + void __iomem *cw = main->domains[i]; + u32 want = main->child_saved[i - 3]; + + if (!(want & 0xf) || (readl(cw) & 0xf0)) + continue; + writel(want, cw); + if (readl_poll_timeout(cw, cur, cur & 0xf0, 50, 2000)) + to |= (i - 3 < 24) ? BIT(8 + (i - 3)) : BIT(31); + } + dcp_pmc_set(dcp, pmc, true); + if (to & 0xf) { + dev_err(dev, "display domains not on after the sleep: %#x\n", to); + return -ETIMEDOUT; + } + if (to) + dev_warn(dev, "display child domains not on after the sleep: %#x\n", to); + + dcp_s2r_find_darts(dcp); + if (dcp->s2r_disp_dart) { + apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, false); + apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true, false); + } + if (dcp->s2r_dcp_dart) { + apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, false); + apple_dart_display_streams(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, true, false); + } + dcp_s2r_put_darts(dcp); + + WRITE_ONCE(dcp->crashed, false); + WRITE_ONCE(dcp->ext_dead, false); + ret = apple_rtkit_power_cycled_return(dcp->rtk, + dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + if (ret) { + dev_err(dev, "the firmware's warm restart after the sleep failed: %d\n", ret); + WRITE_ONCE(dcp->crashed, true); + return ret; + } + WRITE_ONCE(dcp->s2r_fw_down, false); + /* + * Before the mode set, not after it: the commit's swap is what hands the firmware the + * console's framebuffer, and fbcon draws into that memory without committing again. With + * presentation still paused the swap was dropped and the panel stayed black with everything + * else up (10 Nov). + */ + iomfb_pause_presentation(dcp, false); + ret = dcp_t6041_recommit(dcp); + if (ret) + dev_err(dev, "mode set after the sleep failed: %d\n", ret); + /* + * Always restore backlight and boot power words once domains and RTKit warm restart + * succeeded, even if recommit timed out (e.g., wake with lid closed): leaving disp_cpu + * manual hangs the next display power-off. + */ + dcp_backlight_s2r_restore(dcp); + ps_ret = dcp_t6041_boot_ps_io(dcp, true); + return ret ?: ps_ret; +} + +static bool dcp_t6041_down, dcp_t6041_words; + +/* @np's first DART, dark if its driver is bound. */ +static void dcp_t6041_dart_dark(struct device_node *np) +{ + struct device_node *dart = np ? of_parse_phandle(np, "iommus", 0) : NULL; + struct platform_device *pdev = dart ? of_find_device_by_node(dart) : NULL; + + of_node_put(dart); + if (!pdev) + return; + if (device_is_bound(&pdev->dev)) + apple_dart_power_dark(&pdev->dev, true); + put_device(&pdev->dev); +} + +/* + * Every external chain's DARTs, dark before their domains go off. The display subsystem maps + * every framebuffer through the display DARTs, and an unmap after the wake (an sddm restart, a + * logout) flushed one behind a dead block and stopped the machine (12 Nov). By node, so a chain + * whose DCP never bound, which the display subsystem skips as unusable, is covered too, and so + * is every chain a board enables, not only the first two. + */ +static void dcp_t6041_ext_darts_dark(void) +{ + struct device_node *np, *piodma; + + for_each_compatible_node(np, NULL, "apple,t6041-dcpext") { + if (!of_device_is_available(np)) + continue; + piodma = of_get_child_by_name(np, "piodma"); + dcp_t6041_dart_dark(piodma); + of_node_put(piodma); + dcp_t6041_dart_dark(np); + } +} + +enum dcp_t6041_step { DCP_S2R_FW_STOP, DCP_S2R_WORDS_DOWN, DCP_S2R_START }; + +/* Each step once per sleep. */ +static int dcp_t6041_s2r_step(enum dcp_t6041_step step) +{ + struct apple_dcp *host = READ_ONCE(dcp_t6041_host); + bool external = true; + unsigned int i; + int ret; + + if (!host) + return -ENODEV; + + if (step == DCP_S2R_START) { + if (!dcp_t6041_down) + return 0; + dcp_t6041_down = false; + dcp_t6041_words = false; + return driver_for_each_device(&apple_platform_driver.driver, NULL, NULL, + dcp_t6041_start_one); + } + if (step == DCP_S2R_WORDS_DOWN) { + if (dcp_t6041_words || !dcp_t6041_down) + return 0; + dcp_t6041_words = true; + dcp_t6041_ext_darts_dark(); + for (i = 0; i < host->t6041_power.num_chains; i++) { + ret = dcp_t6041_word_try(host->dev, &host->t6041_power, + &host->t6041_power.chains[i]); + if (ret) + return ret; + } + return 0; + } + if (dcp_t6041_down) + return 0; + dcp_t6041_boot_ps_io(host, false); + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &external, + dcp_t6041_stop_one); + if (ret) + return ret; + external = false; + ret = driver_for_each_device(&apple_platform_driver.driver, NULL, &external, + dcp_t6041_stop_one); + if (ret) { + if (READ_ONCE(host->s2r_fw_down)) + dcp_t6041_down = true; + return ret; + } + dcp_t6041_down = true; + return 0; +} + +/* T6041: the display down for a real sleep and back after it. */ +int dcp_t6041_s2r_all(bool start) +{ + int ret; + + if (!READ_ONCE(dcp_sleep_host_stop)) { + if (!start && READ_ONCE(dcp_sleep_host_stop_missing)) { + pr_err("apple-dcp: host-driven sleep required but apple,display-power unavailable\n"); + return -ENODEV; + } + return 0; + } + if (start) + return dcp_t6041_s2r_step(DCP_S2R_START); + if (dcp_t6041_down) + return 0; + ret = dcp_t6041_s2r_step(DCP_S2R_FW_STOP); + if (ret) { + if (dcp_t6041_down && dcp_t6041_s2r_step(DCP_S2R_START)) + pr_err("apple-dcp: T6041 S2R display unwind failed\n"); + return ret; + } + ret = dcp_t6041_s2r_step(DCP_S2R_WORDS_DOWN); + if (ret) { + if (dcp_t6041_s2r_step(DCP_S2R_START)) + pr_err("apple-dcp: T6041 S2R display unwind failed\n"); + return ret; + } + return 0; +} + int __init dcp_register(void) { return platform_driver_register(&apple_platform_driver); diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 0989d8d6a2437e..6c1c258c3c54e1 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -156,6 +156,7 @@ int dcp_dptx_park(struct apple_dcp *dcp); int dcp_dptx_disconnect_oob(struct platform_device *pdev, u32 port); bool dcp_hold_resume_event(struct platform_device *pdev); bool dcp_s2r_firmware_stopped(struct platform_device *pdev); +int dcp_t6041_s2r_all(bool start); int iomfb_start_rtkit(struct apple_dcp *dcp); void iomfb_ext26_start(struct apple_dcp *dcp); diff --git a/drivers/gpu/drm/apple/dcp_backlight.c b/drivers/gpu/drm/apple/dcp_backlight.c index a487e9b770aabe..1019180517bed8 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.c +++ b/drivers/gpu/drm/apple/dcp_backlight.c @@ -431,6 +431,34 @@ void dcp_backlight_finish_fade(struct apple_dcp *dcp) dcp_backlight_kick(dcp); } +/* + * After the S2R display restart: ask for the user's level again and send it, whatever the + * backlight core's flags say at that moment. The class device resumes on its own schedule: + * when it runs after the restart the panel stays dark until then (suspended and core_blank + * still set at the mode set, 11 Nov), and when it runs before, its request goes to a firmware + * that isn't up yet and nothing sends it again (the dark lid wakes). + */ +void dcp_backlight_s2r_restore(struct apple_dcp *dcp) +{ + struct backlight_device *bd = READ_ONCE(dcp->brightness.bl_dev); + unsigned long flags; + + if (!dcp_backlight_desktop(dcp) || !bd) + return; + spin_lock_irqsave(&dcp->backlight.lock, flags); + /* + * A level sent to the firmware that the stop then took down never gets its answer: the + * state stayed in_flight for good and nothing was sent again (dark lid wake of 20:30, + * "sent 0 ... dirty 1 in_flight 1"). The restarted firmware knows nothing of it. + */ + dcp->backlight.state.in_flight = false; + dcp->backlight.state.retries = 0; + dcp_bl_request(&dcp->backlight.state, bd->props.brightness, false, false); + dcp->backlight.state.dirty = true; + spin_unlock_irqrestore(&dcp->backlight.lock, flags); + dcp_backlight_kick(dcp); +} + int dcp_backlight_dpms(struct apple_dcp *dcp, bool on) { unsigned long flags; diff --git a/drivers/gpu/drm/apple/dcp_backlight.h b/drivers/gpu/drm/apple/dcp_backlight.h index 0045e995885d7c..bb200ace902584 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.h +++ b/drivers/gpu/drm/apple/dcp_backlight.h @@ -407,6 +407,7 @@ bool dcp_backlight_desktop_prepare(struct apple_dcp *dcp, u32 id, bool have_surface, u32 *nits); void dcp_backlight_desktop_finish(struct apple_dcp *dcp, u32 id, bool reply, bool accepted); +void dcp_backlight_s2r_restore(struct apple_dcp *dcp); /* * kick only queues work; it must not submit a top-level RPC from the caller. diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index a431791daf9f9b..45b53f5e9bbd96 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -349,17 +349,22 @@ static u16 dcp_packet_start(struct dcp_channel *ch, u8 depth) /* Pushes and pops the depth of the call stack with safety checks */ static u8 dcp_push_depth(u8 *depth) { - u8 ret = (*depth)++; + u8 ret = *depth; WARN_ON(ret >= DCP_MAX_CALL_DEPTH); + WRITE_ONCE(*depth, ret + 1); return ret; } static u8 dcp_pop_depth(u8 *depth) { - WARN_ON((*depth) == 0); + u8 val = *depth; - return --(*depth); + WARN_ON(val == 0); + val--; + /* Pair with iomfb_channels_idle() so callers observe prior ACK sends. */ + smp_store_release(depth, val); + return val; } /* Older firmware and the H17G method profile retain their existing transport. */ @@ -373,9 +378,14 @@ static bool iomfb_uses_queue(struct apple_dcp *dcp) bool iomfb_channels_idle(struct apple_dcp *dcp) { - return !dcp->ch_cmd.depth && !dcp->ch_cb.depth && - !dcp->ch_oobcmd.depth && !dcp->ch_oobcb.depth && - !dcp->ch_async.depth && !dcp->ch_oobasync.depth; + /* Pair with dcp_pop_depth() / dcp_ack() pending_acks ordering. */ + return !smp_load_acquire(&dcp->ch_cmd.depth) && + !smp_load_acquire(&dcp->ch_cb.depth) && + !smp_load_acquire(&dcp->ch_oobcmd.depth) && + !smp_load_acquire(&dcp->ch_oobcb.depth) && + !smp_load_acquire(&dcp->ch_async.depth) && + !smp_load_acquire(&dcp->ch_oobasync.depth) && + !atomic_read_acquire(&dcp->pending_acks); } enum iomfb_opaque_x_state { @@ -1441,11 +1451,21 @@ void dcp_ack(struct apple_dcp *dcp, enum dcp_context_id context) { struct dcp_channel *ch = dcp_get_channel(dcp, context); + /* + * Track the in-flight ACK before popping ch->depth so a concurrent + * iomfb_channels_idle() poll cannot see idle before the ACK is queued + * to RTKit, while popping ch->depth before sending so DCP's next + * callback cannot race ch->depth. + */ + atomic_inc(&dcp->pending_acks); dcp_pop_depth(&ch->depth); if (dcp_is_ext26(dcp)) dma_wmb(); dcp_send_message(dcp, IOMFB_ENDPOINT, dcpep_ack(context)); + /* Order dcp_send_message() before publishing pending_acks == 0. */ + smp_mb__before_atomic(); + atomic_dec(&dcp->pending_acks); } /* diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index faa4f69624bec2..88c303630aae00 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -2785,6 +2785,40 @@ int DCP_FW_NAME(iomfb_s2r_power)(struct apple_dcp *dcp, bool on, bool named_call } #endif +#if DCP_FW_DESKTOP_26(DCP_FW_VER) +DCP_THUNK_IN(dcp_unnamed_500, dcpep_unnamed_500, u32); + +static void dcp_s2r_500_done(struct apple_dcp *dcp, void *out, void *cookie) +{ + struct dcp_wait_cookie *wait = cookie; + + complete(&wait->done); + kref_put(&wait->refcount, release_wait_cookie); +} + +/* Sleep test: H17P's A500, same number and bytes as this firmware's neighbours. */ +int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp) +{ + struct dcp_wait_cookie *cookie; + unsigned long left; + u32 val = 0xaaaa0000; + + cookie = kzalloc_obj(*cookie); + if (!cookie) + return -ENOMEM; + init_completion(&cookie->done); + kref_init(&cookie->refcount); + kref_get(&cookie->refcount); + + dcp_unnamed_500(dcp, false, &val, dcp_s2r_500_done, cookie); + + left = wait_for_completion_timeout(&cookie->done, msecs_to_jiffies(1000)); + kref_put(&cookie->refcount, release_wait_cookie); + + return left ? 0 : -ETIMEDOUT; +} +#endif + static bool dcp_power_stop_confirmed(struct dcp_wait_cookie *cookie) { /* H17P does not confirm that scanout has stopped. */ @@ -3225,6 +3259,12 @@ dcpep_cb_hotplug_v26_6(struct apple_dcp *dcp, struct dcp_hotplug_req_v26_6 *req) if (!dcp->main_display && !connected) dcp->desktop->ext_pipe_off = true; + /* Signal T6041 S2R resume before dcpep_cb_hotplug() skips main_display. */ + if (connected) { + dev_dbg(dcp->dev, "D575 hotplug connected=1\n"); + complete(&dcp->s2r_hpd_done); + } + dcpep_cb_hotplug(dcp, &connected); if (paired && tiled_valid) diff --git a/drivers/gpu/drm/apple/iomfb_template.h b/drivers/gpu/drm/apple/iomfb_template.h index 5820f624350d7d..f4c47eba0406f1 100644 --- a/drivers/gpu/drm/apple/iomfb_template.h +++ b/drivers/gpu/drm/apple/iomfb_template.h @@ -394,6 +394,9 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_sleep)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_start)(struct apple_dcp *dcp); void DCP_FW_NAME(iomfb_shutdown)(struct apple_dcp *dcp); +#if DCP_FW_DESKTOP_26(DCP_FW_VER) +int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); +#endif #if DCP_FW_H17(DCP_FW_VER) int DCP_FW_NAME(iomfb_s2r_500)(struct apple_dcp *dcp); int DCP_FW_NAME(iomfb_s2r_power)(struct apple_dcp *dcp, bool on, bool named_calls, bool oob); diff --git a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c index 3a9436c29355fb..e3585174b0fd11 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6_desktop.c @@ -51,6 +51,7 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { IOMFB_METHOD("A469", iomfbep_abort_swaps_dcp), IOMFB_METHOD("A473", dcpep_set_power_state), IOMFB_METHOD("A474", dcpep_pipe_query_474), + IOMFB_METHOD("A500", dcpep_unnamed_500), /* A364 get_mode_info and A420/A421 gamma: see iomfb_template.c */ }; @@ -59,6 +60,22 @@ static const struct dcp_method_entry dcp_methods[dcpep_num_methods] = { #include "iomfb_template.c" +/* + * D572: 0 when the firmware is done with the display, 1 when it wants it back. Only a + * sleep path waiting for it (s2r_active) acts on it; the firmware takes a zero status. + */ +static bool trampoline_dart_power_v26_6_desktop(struct apple_dcp *dcp, int tag, void *out, + void *in) +{ + const struct dcp_packet_header *header = in - sizeof(*header); + + /* A bool in a 4-byte slot: its upper padding bytes are not cleared. */ + if (header->in_len >= sizeof(u32)) + dcp_s2r_dart_power(dcp, !!*(const u8 *)in); + + return trampoline_zero(dcp, tag, out, in); +} + /* * D114 periodically publishes dictionary-valued statistics: the analytics * event, answered by dcp_dict_passthrough_reply(). @@ -236,14 +253,16 @@ static const iomfb_cb_handler cb_handlers[IOMFB_MAX_CB] = { [565] = trampoline_true, /* set_property_bool */ [567] = trampoline_true, /* set_property_str */ /* a zero status for both its start and stop events */ - [572] = trampoline_zero, + [572] = trampoline_dart_power_v26_6_desktop, [575] = trampoline_hotplug, [576] = trampoline_nop, [581] = trampoline_nop, [582] = trampoline_true, /* create_default_fb_surface */ + [583] = trampoline_nop, /* clear_default_surface */ [588] = trampoline_nop, /* resize_default_fb_surface_gated */ [590] = trampoline_swap_complete, [592] = trampoline_swap_complete_intent_gated, + [597] = trampoline_zero, /* sleep test: (0, 4), purpose unknown */ [593] = trampoline_abort_swap_ap_gated, /* a four-byte padded notification; only its first byte is read */ [594] = trampoline_enable_backlight_message_ap_gated, @@ -330,9 +349,11 @@ static const struct dcp_cb_min_v26_6_desktop cb_min[IOMFB_MAX_CB] = { [576] = CB_MIN(0, 0), [581] = CB_MIN(0, 0), [582] = CB_MIN(0, sizeof(u8)), + [583] = CB_MIN(0, 0), [588] = CB_MIN(0, 0), [590] = CB_MIN(sizeof(struct DCP_FW_NAME(dc_swap_complete_resp)), 0), [592] = CB_MIN(sizeof(dcp_swap_intent_t), 0), + [597] = CB_MIN(0, sizeof(u32)), [593] = CB_MIN(sizeof(u32), 0), [594] = CB_MIN(sizeof(u8), 0), [595] = CB_MIN(0, 0), diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index 98b984e5975545..c896fb37156669 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -222,6 +222,11 @@ def run(name,code,reject=False): #define current ((void *)1) #define dma_wmb() ((void)0) #define dma_rmb() ((void)0) +#define smp_store_release(p,v) (*(p)=(v)) +#define smp_mb__before_atomic() ((void)0) +typedef int atomic_t; +#define atomic_inc(v) ((*(v))++) +#define atomic_dec(v) ((*(v))--) #define trace_iomfb_push(...) #define IOMFB_METHOD(t,n) [n]={#n,{t[0],t[1],t[2],t[3]},{0},{0}} #define IOMFB_METHOD_H17(t,h,n) [n]={#n,{t[0],t[1],t[2],t[3]},{h[0],h[1],h[2],h[3]},{0}} @@ -230,7 +235,7 @@ def run(name,code,reject=False): struct dcp_method_entry {const char *name;char tag[4],tag_h17g[4],tag_ext26[4];}; ''' transport+=block(ih,'enum dcp_context_id {')+'\n'+block(ih,'struct dcp_packet_header {')+'\n'+block(internal,'struct dcp_channel {')+'\n'+block(ih,'enum dcpep_method {')+r''' -struct apple_dcp {const void *push_out_prefill;void *dev;u8 *shmem;int fw_compat;bool native,crashed,quiescing,ext26_blocked,ext26_power_sent;u64 ext26_power_ns;struct {int iomfb_method_profile;}hw;struct {void *owner;} iomfb;struct dcp_channel ch_cb,ch_cmd,ch_oobcb,ch_oobcmd,ch_async,ch_oobasync;}; +struct apple_dcp {const void *push_out_prefill;void *dev;u8 *shmem;int fw_compat;bool native,crashed,quiescing,ext26_blocked,ext26_power_sent;u64 ext26_power_ns;struct {int iomfb_method_profile;}hw;struct {void *owner;} iomfb;struct dcp_channel ch_cb,ch_cmd,ch_oobcb,ch_oobcmd,ch_async,ch_oobasync;atomic_t pending_acks;}; static bool iomfb_uses_queue(struct apple_dcp *d){return true;} static bool dcp_is_ext26(struct apple_dcp *d){return d->native;} static bool dcp_fail_stop(struct apple_dcp *d){return d->native;} From 6cd3ffc94ec872f6ec1b16ec997215d44b1d7055 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:54 +0000 Subject: [PATCH 1229/1514] dt-bindings: pci: apple,pcie: allow T6041 shared storage/PHY reg windows Allow the T6041 shared APCIe storage/PHY register windows (axi2af, cio3pll, clkgen, phy-block, phy-ip) and bootloader-provided apple,tunable-* properties on apple,t6041-pcie so the sleep driver can reinitialize the storage PCIe link after deep sleep strictly from DT. Signed-off-by: AxxzyWasTaken --- .../devicetree/bindings/pci/apple,pcie.yaml | 61 ++++++++++++++----- 1 file changed, 45 insertions(+), 16 deletions(-) diff --git a/Documentation/devicetree/bindings/pci/apple,pcie.yaml b/Documentation/devicetree/bindings/pci/apple,pcie.yaml index 70700cb86b839d..90e0abb33c3c68 100644 --- a/Documentation/devicetree/bindings/pci/apple,pcie.yaml +++ b/Documentation/devicetree/bindings/pci/apple,pcie.yaml @@ -694,22 +694,51 @@ allOf: interrupts: maxItems: 3 else: - properties: - reg: - maxItems: 10 - reg-names: - minItems: 3 - items: - - const: config - - const: rc - - const: port0 - - const: port1 - - const: port2 - - const: port3 - - const: phy0 - - const: phy1 - - const: phy2 - - const: phy3 + if: + properties: + compatible: + contains: + const: apple,t6041-pcie + then: + properties: + reg: + minItems: 10 + maxItems: 15 + reg-names: + minItems: 10 + items: + - const: config + - const: rc + - const: port0 + - const: port1 + - const: port2 + - const: port3 + - const: phy0 + - const: phy1 + - const: phy2 + - const: phy3 + - const: axi2af + - const: cio3pll + - const: clkgen + - const: phy-block + - const: phy-ip + else: + properties: + reg: + maxItems: 10 + reg-names: + minItems: 3 + items: + - const: config + - const: rc + - const: port0 + - const: port1 + - const: port2 + - const: port3 + - const: phy0 + - const: phy1 + - const: phy2 + - const: phy3 patternProperties: "^pci@": properties: From 9213e56bfdbb38880664fb27f80deff8b9806a9f Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:54 +0000 Subject: [PATCH 1230/1514] dt-bindings: soc: apple: add apple,t6041-sleep binding Add the DT binding schema for apple,t6041-sleep describing its register windows (ps-aop, cluster, pwrgate, cpu-start, wdt, aon-misc, commit, clk-mux, ka-pmgr, ka-east, pmc, ptd, perf, wake, AMCC/DCS banks, and AXI2AF bridges), pinctrl/SPMI/ATC-PHY/APCIe phandles, wake source IDs, and PMGR power-domain phandle lists (including apple,atc-off-domains). Signed-off-by: AxxzyWasTaken --- .../bindings/soc/apple/apple,t6041-sleep.yaml | 437 ++++++++++++++++++ 1 file changed, 437 insertions(+) create mode 100644 Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml new file mode 100644 index 00000000000000..08629278a48727 --- /dev/null +++ b/Documentation/devicetree/bindings/soc/apple/apple,t6041-sleep.yaml @@ -0,0 +1,437 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/soc/apple/apple,t6041-sleep.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T6041 system sleep controls + +maintainers: + - AxxzyWasTaken + +description: | + The registers and PMGR power-state domains a kernel running directly at EL2 + on the M4 Max (T6041) writes to enter and return from suspend-to-RAM and to + power its secondary CPUs off. They belong to several hardware blocks, some of + which other drivers also use, so this node overlaps those drivers' register + ranges and the driver does not claim them. The way back from a sleep is the + boot loader's S2R mailbox, which the boot loader names in /chosen; without it + the driver offers no deep sleep. + +properties: + compatible: + const: apple,t6041-sleep + + reg: + minItems: 40 + maxItems: 40 + + reg-names: + items: + - const: ps-aop + - const: cluster + - const: pwrgate + - const: cpu-start + - const: wdt + - const: aon-misc + - const: commit + - const: clk-mux + - const: ka-pmgr + - const: ka-east + - const: pmc + - const: ptd + - const: perf + - const: wake + - const: amcc0 + - const: amcc1 + - const: amcc2 + - const: amcc3 + - const: amcc4 + - const: amcc5 + - const: amcc6 + - const: amcc7 + - const: dcs0 + - const: dcs1 + - const: dcs2 + - const: dcs3 + - const: dcs4 + - const: dcs5 + - const: dcs6 + - const: dcs7 + - const: axi2af-disp + - const: axi2af-dispext0 + - const: axi2af-dispext1 + - const: axi2af-dispext2 + - const: axi2af-dispext3 + - const: axi2af-ans + - const: axi2af-avd + - const: axi2af-venc0 + - const: axi2af-venc1 + - const: axi2af-jpg + + apple,pinctrl: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The AP pin controller whose pins a deep sleep resets. Its pins are saved + before a sleep and restored on wake. + + apple,pinctrl-skip-pins: + $ref: /schemas/types.yaml#/definitions/uint32-array + description: + Pins of that controller to leave alone across a sleep, neither saved nor + restored. + + apple,apcie: + $ref: /schemas/types.yaml#/definitions/phandle + description: + The PCIe host whose shared registers and tunables the storage + controller's link depends on, and whose GP ports need clock restoration + after deep sleep. Without it or its tunables, deep sleep is refused. + + apple,spmi-buses: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The SPMI buses driven around a sleep: nub-spmi0 first (PMU boot stage + and notify mask), then nub-spmi-a0 (notify mask when powered). + + apple,atc-phys: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 4 + maxItems: 4 + items: + maxItems: 1 + description: + The four ATC PHY nodes (atcphy0 through atcphy3) whose axi2af fabric + bridges are disarmed at sleep entry and re-armed on wake. + + apple,wake-enable: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 64 + description: + The AP wake source IDs left unmasked across suspend-to-RAM (ADT + ap-wake-sources). Every other wake source is masked. + + apple,sleep-off-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 256 + items: + maxItems: 1 + description: + PMGR power-state nodes powered off before the sleep commit (sorted + child-before-parent from their DT power-domains edges) and restored to + their pre-commit states on wake. + + apple,atc-off-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + USB-C / ATC PMGR power-state nodes lowered in hardware order after PS + matching and PMC/PTD quiesce, and restored to their pre-commit states on + wake. + + apple,sleep-auto-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 128 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 0 (power gated) before the sleep commit, skipping fused-off + words, and restored on wake. + + apple,sleep-auto-clkgate-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 128 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 4 (clock gated) before the sleep commit, skipping fused-off + words, and restored on wake. + + apple,sleep-auto-active-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + PMGR power-state nodes placed into hardware automatic power management + with auto-state 15 (active) before the sleep commit and restored on wake. + + apple,sleep-keep-on-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 1 + maxItems: 64 + items: + maxItems: 1 + description: + PMGR power-state nodes held manually on (target 15, auto-enable clear) + before the sleep commit and restored on wake. + + apple,cpu-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 16 + maxItems: 16 + items: + maxItems: 1 + description: + PMGR power-state nodes for the 16 CPU cores in ADT CPU ID order + (ecpu_0..3, pcpu0_0..5, pcpu1_0..5), matched before commit and polled off + as secondary CPUs enter deep WFI. + + apple,cpm-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 3 + maxItems: 3 + items: + maxItems: 1 + description: + PMGR power-state nodes for the three cluster power managers in order + (ecpm, pcpm0, pcpm1). + + apple,sep-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + PMGR power-state node for SEP, whose DEV_DISABLE bit is set before the + sleep commit and cleared with BUSY polled clear on wake. + + apple,spmi-a0-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + PMGR power-state node for nub-spmi-a0, tested before accessing the second + SPMI bus's notify mask register. + + apple,atc-common-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 4 + maxItems: 4 + items: + maxItems: 1 + description: + PMGR power-state nodes for the four ATC common domains (atc0_common + through atc3_common), raised right before the sleep commit. + + apple,atc-fabric-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Parent fabric PMGR power-state node (fab2_soc) raised manually while + bringing up the ATC common domains and returned to auto-enable. + + apple,atc-afi-domain: + $ref: /schemas/types.yaml#/definitions/phandle + description: + AFI fabric PMGR power-state node left in hardware auto-enable after + lowering the ATC power domains. + + apple,apcie-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 8 + maxItems: 8 + items: + maxItems: 1 + description: | + The eight storage and GP PCIe PMGR power-state nodes in order: + ans, apcie_gp, apcie_sys_gp, apcie_st0, apcie_sys_st0, apcie_st1, + apcie_sys_st1, apcie_phy_sw. + + apple,commit-sio-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The two SIO PMGR power-state nodes written in the final commit sequence, + in order: sio, sio_cpu. + + apple,commit-periph-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 5 + maxItems: 5 + items: + maxItems: 1 + description: | + The five peripheral PMGR power-state nodes lowered after the PMU boot + stage write in the final commit sequence, in order: i2c6, i2c3, i2c2, + i2c1, spi2. + + apple,axi2af-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 15 + maxItems: 15 + items: + maxItems: 1 + description: | + PMGR power-state nodes paired 1:1 with the 15 AXI2AF fabric bridges in + order: atc0..3_common (0..3), disp_sys (4), dispext0..3_sys (5..8), + ans (9), avd_sys (10), venc0_sys (11), venc1_sys (12), jpg (13), + apcie_sys_gp (14). + + apple,full-part-detect-domains: + $ref: /schemas/types.yaml#/definitions/phandle-array + minItems: 2 + maxItems: 2 + items: + maxItems: 1 + description: | + The two AMCC PMGR power-state nodes (amcc24, amcc28) probed at driver + init to distinguish 24-channel binned parts from 32-channel full parts. + +required: + - compatible + - reg + - reg-names + - apple,pinctrl + - apple,spmi-buses + - apple,wake-enable + - apple,sleep-off-domains + - apple,atc-off-domains + - apple,sleep-auto-domains + - apple,sleep-auto-clkgate-domains + - apple,sleep-auto-active-domains + - apple,sleep-keep-on-domains + - apple,cpu-domains + - apple,cpm-domains + - apple,sep-domain + - apple,spmi-a0-domain + - apple,atc-common-domains + - apple,atc-fabric-domain + - apple,atc-afi-domain + - apple,apcie-domains + - apple,commit-sio-domains + - apple,commit-periph-domains + - apple,axi2af-domains + - apple,full-part-detect-domains + +allOf: + - if: + not: + properties: + status: + const: disabled + required: + - status + then: + required: + - apple,atc-phys + +additionalProperties: false + +examples: + - | + soc { + #address-cells = <2>; + #size-cells = <2>; + + sleep-controller@508304000 { + compatible = "apple,t6041-sleep"; + reg = <0x5 0x08304000 0x0 0x4000>, + <0x5 0x02820000 0x0 0x4000>, + <0x5 0x0282c000 0x0 0x4000>, + <0x5 0x02888000 0x0 0x4000>, + <0x5 0x0836c000 0x0 0x4000>, + <0x5 0x08330000 0x0 0x4000>, + <0x5 0x08904000 0x0 0x4>, + <0x5 0x00038000 0x0 0x4000>, + <0x5 0x029dc000 0x0 0x880>, + <0x5 0x022d0000 0x0 0x880>, + <0x5 0x04800000 0x0 0xb0000>, + <0x5 0x003c0000 0x0 0x20000>, + <0x5 0x0020c000 0x0 0x800>, + <0x5 0x08004000 0x0 0x58>, + <0x2 0x20000000 0x0 0x200000>, + <0x2 0x22000000 0x0 0x200000>, + <0x2 0x24000000 0x0 0x200000>, + <0x2 0x26000000 0x0 0x200000>, + <0x2 0x28000000 0x0 0x200000>, + <0x2 0x2a000000 0x0 0x200000>, + <0x2 0x2c000000 0x0 0x200000>, + <0x2 0x2e000000 0x0 0x200000>, + <0x2 0x20200000 0x0 0x601000>, + <0x2 0x22200000 0x0 0x601000>, + <0x2 0x24200000 0x0 0x601000>, + <0x2 0x26200000 0x0 0x601000>, + <0x2 0x28200000 0x0 0x601000>, + <0x2 0x2a200000 0x0 0x601000>, + <0x2 0x2c200000 0x0 0x601000>, + <0x2 0x2e200000 0x0 0x601000>, + <0x4 0x03000100 0x0 0x10>, + <0x3 0xa3000100 0x0 0x10>, + <0x6 0x03000100 0x0 0x10>, + <0x6 0x07000100 0x0 0x10>, + <0x3 0x07000100 0x0 0x10>, + <0x4 0x0b000100 0x0 0x10>, + <0x2 0x80000100 0x0 0x10>, + <0x2 0x82000100 0x0 0x10>, + <0x2 0x84000100 0x0 0x10>, + <0x4 0x86000100 0x0 0x10>; + reg-names = "ps-aop", + "cluster", "pwrgate", "cpu-start", "wdt", + "aon-misc", "commit", "clk-mux", "ka-pmgr", + "ka-east", "pmc", "ptd", "perf", "wake", + "amcc0", "amcc1", "amcc2", "amcc3", + "amcc4", "amcc5", "amcc6", "amcc7", + "dcs0", "dcs1", "dcs2", "dcs3", + "dcs4", "dcs5", "dcs6", "dcs7", + "axi2af-disp", "axi2af-dispext0", + "axi2af-dispext1", "axi2af-dispext2", + "axi2af-dispext3", "axi2af-ans", + "axi2af-avd", "axi2af-venc0", + "axi2af-venc1", "axi2af-jpg"; + apple,pinctrl = <&pinctrl>; + apple,pinctrl-skip-pins = <190 191 192>; + apple,apcie = <&pcie0>; + apple,spmi-buses = <&nub_spmi0>, <&nub_spmi_a0>; + apple,atc-phys = <&atcphy0>, <&atcphy1>, <&atcphy2>, <&atcphy3>; + apple,wake-enable = <13 15 25 27 28 41 44 48 50 51 52 53 55 + 101 106 126 127 128 129 130 131 132 133 + 155 167>; + apple,sleep-off-domains = <&ps_gfx>, <&ps_afr>; + apple,atc-off-domains = <&ps_atc0_phymxwrap>, <&ps_atc0_common>; + apple,sleep-auto-domains = <&ps_fab0_soc>, <&ps_amcc0>; + apple,sleep-auto-clkgate-domains = <&ps_fab3_soc>, <&ps_dcs_00>; + apple,sleep-auto-active-domains = <&ps_fab2_soc>, <&ps_afi>; + apple,sleep-keep-on-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,cpu-domains = <&ps_ecpu_0>, <&ps_ecpu_1>, <&ps_ecpu_2>, + <&ps_ecpu_3>, <&ps_pcpu0_0>, <&ps_pcpu0_1>, + <&ps_pcpu0_2>, <&ps_pcpu0_3>, <&ps_pcpu0_4>, + <&ps_pcpu0_5>, <&ps_pcpu1_0>, <&ps_pcpu1_1>, + <&ps_pcpu1_2>, <&ps_pcpu1_3>, <&ps_pcpu1_4>, + <&ps_pcpu1_5>; + apple,cpm-domains = <&ps_ecpm>, <&ps_pcpm0>, <&ps_pcpm1>; + apple,sep-domain = <&ps_sep>; + apple,spmi-a0-domain = <&ps_nub_spmi_a0>; + apple,atc-common-domains = <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>; + apple,atc-fabric-domain = <&ps_fab2_soc>; + apple,atc-afi-domain = <&ps_afi>; + apple,apcie-domains = <&ps_ans>, <&ps_apcie_gp>, + <&ps_apcie_sys_gp>, <&ps_apcie_st0>, + <&ps_apcie_sys_st0>, <&ps_apcie_st1>, + <&ps_apcie_sys_st1>, <&ps_apcie_phy_sw>; + apple,commit-sio-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,commit-periph-domains = <&ps_i2c6>, <&ps_i2c3>, <&ps_i2c2>, + <&ps_i2c1>, <&ps_spi2>; + apple,axi2af-domains = <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>, + <&ps_disp_sys>, <&ps_dispext0_sys>, + <&ps_dispext1_sys>, <&ps_dispext2_sys>, + <&ps_dispext3_sys>, <&ps_ans>, + <&ps_avd_sys>, <&ps_venc0_sys>, + <&ps_venc1_sys>, <&ps_jpg>, + <&ps_apcie_sys_gp>; + apple,full-part-detect-domains = <&ps_amcc24>, <&ps_amcc28>; + }; + }; From cd3d7cca1ee1137aaf8bca6ace7b302b68d649e9 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:55 +0000 Subject: [PATCH 1231/1514] soc: apple: t6041-sleep: EL2 suspend-to-RAM driver for T6041 Add the EL2 suspend-to-RAM platform driver for Apple T6041 (M4 Max), committing sleep and returning to cpu_resume through aura's S2R mailbox: - Bind only when aura publishes the S2R mailbox and bootloader-provided APCIe tunables (apple,tunable-* via ) are present in DT; otherwise fail probe with -ENODEV so the machine stays on s2idle. - Map all MMIO windows from DT reg-names and resolve all PMGR power-state words from DT phandle lists, topologically sorting sleep-off and restore lists from DT power-domains edges with cycle detection. Uniformly skip fused-off channel words across 24-channel (binned J616c) and 32-channel (full J614c, including dcs_27 at main +0x530 found by joske) parts. - Advertise commit-time enclave/coprocessor stops, hold parked CPUs via spin_table_hold_parked() before stopping them, check coprocessors and pm_wakeup_pending() before the refusal boundary, and stop SEP and coprocessors at commit so aborted suspends do not strand Touch ID or SIO. - Use pure arch_timer_read_counter() + cpu_relax() polls in the commit path (avoiding arm64 WFIT/WFET early power-gating) to poll ATC, sleep, DCS/SoC perf, secondary CPU/CPM, and SPMI hardware states with wake-time timeout reporting, retaining only the two hardware-documented fixed spins (5 ms PTD SOC-DEV-PS-REQ pulse and 3 ms commit-to-WFI gap) and the 1 us PHY refclk settle on wake. Signed-off-by: AxxzyWasTaken --- drivers/soc/apple/Kconfig | 4 + drivers/soc/apple/Makefile | 1 + drivers/soc/apple/t6041-sleep.c | 2207 +++++++++++++++++++++++++++++++ 3 files changed, 2212 insertions(+) create mode 100644 drivers/soc/apple/t6041-sleep.c diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index d1f15e2ceca732..e83837cb404fbf 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -162,6 +162,10 @@ config APPLE_SOC_SLEEP each by its match data: today T8140, T8132 and T6050. On every other SoC the driver doesn't bind, and s2idle stays the only system sleep. + T6041 (M4 Max) has a driver of its own, t6041-sleep, which binds + to an "apple,t6041-sleep" node and uses this driver's coprocessor + stop. + config APPLE_SOC_SLEEP_KUNIT_TEST bool "KUnit tests for the Apple SoC sleep match data" if !KUNIT_ALL_TESTS depends on APPLE_SOC_SLEEP && KUNIT=y diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index 6e82a01e4cd9fe..be98f2a35d7ffa 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -21,6 +21,7 @@ obj-$(CONFIG_APPLE_CLUSTER_PWRGATE) += apple-cluster-pwrgate.o obj-$(CONFIG_APPLE_SOC_SLEEP) += apple-sleep.o obj-$(CONFIG_APPLE_SOC_SLEEP) += t6050-aop.o apple-sleep-y = sleep.o +obj-$(CONFIG_APPLE_SOC_SLEEP) += t6041-sleep.o obj-$(CONFIG_APPLE_RTKIT) += apple-rtkit.o apple-rtkit-y = rtkit.o rtkit-crashlog.o diff --git a/drivers/soc/apple/t6041-sleep.c b/drivers/soc/apple/t6041-sleep.c new file mode 100644 index 00000000000000..e51f3f7d1fd0b8 --- /dev/null +++ b/drivers/soc/apple/t6041-sleep.c @@ -0,0 +1,2207 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Apple T6041 (M4 Max) system sleep, at EL2 with no monitor below. + * + * It runs macOS 26.6.2's last steps before the S2R commit, in macOS's order and + * with its values, as traced from macOS sleeping under aura's hypervisor, and + * commits; aura's S2R mailbox brings the boot core back to cpu_resume on the + * wake, and the driver restores what the sleep took. + * + * Needs the kernel at EL2 (CTXR window) and the "aurora,rvbar-spin-table" CPU + * enable method, so the other cores can leave the kernel. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SYS_APL_IPI_SR_EL1 sys_reg(3, 5, 15, 1, 1) +#define IPI_SR_PENDING BIT(0) +#define SYS_APL_SIQ_CFG_EL1 sys_reg(3, 4, 15, 10, 4) +#define SYS_APL_DEEP_SLEEP sys_reg(3, 5, 15, 6, 2) +#define DEEP_SLEEP_BITS (BIT(0) | BIT(63)) + +#define KA_WORDS 32 +#define KA_STRIDE 0x44 + +#define PS_AUTO_ENABLE BIT(28) +#define PS_AUTO_STATE GENMASK(27, 24) +#define PS_FLAGS GENMASK(9, 8) +#define PS_ACTUAL GENMASK(7, 4) +#define PS_TARGET GENMASK(3, 0) + +#define SPMI_STATUS 0x00 +#define SPMI_CMD 0x04 +#define SPMI_REPLY 0x08 +#define SPMI_RX_EMPTY BIT(24) +#define SPMI_TX_EMPTY BIT(8) +#define SPMI_IDLE (SPMI_RX_EMPTY | SPMI_TX_EMPTY) +#define SPMI_DRAIN_MAX 16 +#define SPMI_NOTIFY_MASK 0x40 +#define SPMI_IRQ_ACK 0x80 +#define PMU_SID 0xb + +#define PERF_BUSY BIT(31) +#define PERF_ACTUAL GENMASK(11, 8) + +#define AMCC_MAX_GROUPS 8 +#define AMCC_ERR_OFF 0x25000 +#define AMCC_PLANE_STRIDE 0x40000 +#define AMCC_MIN_SIZE 0x1c2848 + +#define DCS_CH_STRIDE 0x200000UL +#define DCS_CH_SIZE 0x40 + +#define PTD_SOC_DEV_REQ_READ 0x01e00 +#define PTD_SOC_DEV_REQ_WRITE 0x10f00 +#define PTD_CLUSTER_WRITE_0 0x10f80 +#define PTD_CLUSTER_WRITE_1 0x10f88 +#define PTD_CLUSTER_WRITE_2 0x10f90 +#define PTD_CLUSTER_WRITE_3 0x10fa0 +#define PTD_MIN_SIZE 0x10fa8 + +#define AOP_PS_WORDS 44 + +#define WAKE_WORDS 9 +#define WAKE_LAST_MASK 0x00003fffU +#define WAKE_MAX_ID (32 * (WAKE_WORDS - 1) + 14) +#define WAKE_SOURCES_MAX 64 + +#define AXI2AF_ATC_COUNT 4 +#define AXI2AF_DISP_FIRST 4 +#define AXI2AF_DISP_COUNT 5 +#define AXI2AF_REG_COUNT 10 +#define AXI2AF_COUNT 15 +#define AXI2AF_ANS 9 +#define AXI2AF_APCIE 14 + +#define T6041_CPU_COUNT 16 +#define T6041_CPM_COUNT 3 +#define T6041_COMMIT_SIO_COUNT 2 +#define T6041_COMMIT_PERIPH_COUNT 5 +#define T6041_FULL_DETECT_COUNT 2 +#define T6041_MAX_PMGR_BANKS 16 +#define T6041_PS_MAX_DEPTH 16 + +enum t6041_apcie_ps { + T6041_APCIE_ANS, + T6041_APCIE_GP, + T6041_APCIE_SYS_GP, + T6041_APCIE_ST0, + T6041_APCIE_SYS_ST0, + T6041_APCIE_ST1, + T6041_APCIE_SYS_ST1, + T6041_APCIE_PHY_SW, + T6041_APCIE_PS_COUNT, +}; + +/* aura's struct aura_s2r_mailbox (aura PR 117). */ +#define T6041_S2R_MAGIC 0x3152325341525541ULL /* "AURAS2R1" */ +struct t6041_s2r_mailbox { + u64 magic; + u64 boot_mpidr; + u64 resume_pa; + u64 resumes; +}; + +struct t6041_sleep { + struct device *dev; + struct t6041_s2r_mailbox *mbox; + /* PMGR power-state words resolved from DT phandles. */ + void __iomem **ps_off; + unsigned int n_off; + void __iomem **ps_atc_off; + unsigned int n_atc_off; + void __iomem **ps_auto; + unsigned int n_auto; + void __iomem **ps_auto_clkgate; + unsigned int n_auto_clkgate; + void __iomem **ps_auto_active; + unsigned int n_auto_active; + void __iomem **ps_keep_on; + unsigned int n_keep_on; + void __iomem **ps_restore; + unsigned int n_restore; + void __iomem *ps_cpu[T6041_CPU_COUNT]; + void __iomem *ps_cpm[T6041_CPM_COUNT]; + void __iomem *ps_sep; + void __iomem *ps_spmi_a0; + void __iomem *ps_atc_common[AXI2AF_ATC_COUNT]; + void __iomem *ps_atc_fabric; + void __iomem *ps_atc_afi; + void __iomem *ps_apcie[T6041_APCIE_PS_COUNT]; + void __iomem *ps_commit_sio[T6041_COMMIT_SIO_COUNT]; + void __iomem *ps_commit_periph[T6041_COMMIT_PERIPH_COUNT]; + void __iomem *ps_axi2af[AXI2AF_COUNT]; + void __iomem *ps_full_detect[T6041_FULL_DETECT_COUNT]; + void __iomem *cluster; + void __iomem *pwrgate; + void __iomem *misc; + void __iomem *wdt; + void __iomem *aon; + void __iomem *commit; + void __iomem *clkgen; + void __iomem *spmi; + void __iomem *spmi_a0; + void __iomem *pmc; + void __iomem *ka[2]; /* keep-alive tables, 1 from iBoot, 0 at macOS's commit */ + unsigned int ngroups; /* AMCCs of four planes: 8 on full T6041, 6 on binned */ + void __iomem *dcs[4 * AMCC_MAX_GROUPS]; + void __iomem *amccb[AMCC_MAX_GROUPS]; + void __iomem *wake; /* SLP_DDR +0, wake masks +0x0c..+0x2c */ + void __iomem *perf; /* SoC perf +0, DCS perf +0x400 */ + void __iomem *axi2af[AXI2AF_COUNT]; + void __iomem *ptd; /* PTD read (+0x0) and write (+0x10000) pages */ + u32 wake_masks[WAKE_WORDS]; + int stop_ret; + int coproc_ret; + int apcie_ret; + unsigned int atc_late; + unsigned int off_late; + unsigned int dcs_late; + u32 cpu_off_late; + u32 cpm_off_late; + unsigned int spmi_late; + unsigned int ps_late; + unsigned int gp_late; + /* Saved as the commit starts, put back by t6041_sleep_return(). */ + u64 cntkctl; + u64 siq_cfg; + u32 *ps_pre; + u32 pre_perf[2]; + u32 pre_pmc[5]; + u32 pre_clk[4]; + u32 pre_mask[2]; + u32 pre_wake[WAKE_WORDS]; + u32 pre_votes[5]; + /* Each AMCC plane's cache ways (+0x2800) and status (+0x2804). */ + u32 pre_ways[4 * AMCC_MAX_GROUPS]; + u32 pre_cache[4 * AMCC_MAX_GROUPS]; + bool pre_a0; + /* GP PCIe ports 0/1: port block, PHY word, and saved state. */ + void __iomem *gp_port[2]; + void __iomem *gp_phy[2]; + u32 gp_phy_pre[2]; + u32 gp_app_pre[2]; + u32 gp_perst_pre[2]; + bool gp_saved; + /* ANS's storage PCIe block and bootloader-supplied tunables (apple,apcie). */ + void __iomem *ap_rc; + void __iomem *ap_phy; + void __iomem *ap_phy_ip; + void __iomem *ap_axi; + void __iomem *ap_cio3pll; + void __iomem *ap_clkgen; + struct apple_tunable *tun_axi2af; + struct apple_tunable *tun_cio3pll; + struct apple_tunable *tun_clkgen; + struct apple_tunable *tun_phy; + struct apple_tunable *tun_phy_ip_pll; + struct apple_tunable *tun_phy_ip_lanes; + bool apcie_ready; + bool ans_stopped; + /* The AOP island's 44 MiniPMGR power words (ps-aop). */ + void __iomem *aop_ps; + u32 aop_pre[AOP_PS_WORDS]; + /* AP GPIO block (apple,pinctrl), saved/restored across deep sleep. */ + void __iomem *gpio; + u32 npins; + u32 *gpio_pre; + unsigned long *gpio_skip; +}; + +static struct t6041_sleep *t6041_sleep; + +/* ADT cpu number: E 0-3, P0 4-9, P1 10-15. */ +static unsigned int t6041_cpu_id(u64 mpidr) +{ + unsigned int cl = MPIDR_AFFINITY_LEVEL(mpidr, 1); + unsigned int core = MPIDR_AFFINITY_LEVEL(mpidr, 0); + + return cl == 0 ? core : cl == 1 ? 4 + core : 10 + core; +} + +/* + * Pure counter + cpu_relax() busy-spin helpers for the sleep commit path. + * Never call udelay()/mdelay()/readl_poll_timeout_atomic() once CPU/CPM + * PS_TARGET = 0 or cluster power-down is armed: arm64's delay_loop uses + * WFIT/WFET, which lets the sleep hardware power-gate the boot core early. + */ +static void t6041_spin_us(u64 us) +{ + u64 t0 = arch_timer_read_counter(); + u64 ticks = DIV_ROUND_UP_ULL(us * arch_timer_get_cntfrq(), USEC_PER_SEC); + + while (arch_timer_read_counter() - t0 < ticks) + cpu_relax(); +} + +#define t6041_poll_until_us(addr, val, cond, timeout_us) ({ \ + u64 __t0 = arch_timer_read_counter(); \ + u64 __ticks = DIV_ROUND_UP_ULL((u64)(timeout_us) * \ + arch_timer_get_cntfrq(), USEC_PER_SEC); \ + bool __timed_out = false; \ + int __ret = 0; \ + \ + for (;;) { \ + (val) = readl(addr); \ + if (cond) \ + break; \ + if (__timed_out) { \ + __ret = -ETIMEDOUT; \ + break; \ + } \ + if (arch_timer_read_counter() - __t0 >= __ticks) \ + __timed_out = true; \ + else \ + cpu_relax(); \ + } \ + __ret; \ +}) + +/* + * A core's last WFI, as the Neo's and the Air's t8140_deep_wfi() and macOS's + * last-WFI routine with x0 = 1: timers masked, the deep-sleep bits (C6_2 bit 0 + * and 63) set, then WFI for good. (Not the runtime offline branch, which leaves + * C6_2 clear.) + */ +static void __noreturn t6041_offline_wfi(void) +{ + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_BITS); + isb(); + while (true) { + dsb(sy); + isb(); + wfi(); + aic_sleep_ack(); + write_sysreg_s(IPI_SR_PENDING, SYS_APL_IPI_SR_EL1); + } +} + +static void t6041_cpu_stop(u64 mpidr) +{ + writel(BIT(t6041_cpu_id(mpidr)), t6041_sleep->misc + 0x0); + dsb(sy); +} + +static int t6041_cpu_on(u64 mpidr) +{ + void __iomem *misc = t6041_sleep->misc; + unsigned int cl = MPIDR_AFFINITY_LEVEL(mpidr, 1); + + writel(BIT(t6041_cpu_id(mpidr)), misc + 0x4); + writel(BIT(MPIDR_AFFINITY_LEVEL(mpidr, 0)), misc + 0x8 + 4 * cl); + return 0; +} + +static void t6041_ps_lower(void __iomem *reg) +{ + u32 val = readl(reg); + + if (val & PS_AUTO_ENABLE) { + val &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(val, reg); + } + writel((val & ~PS_TARGET) | PS_FLAGS, reg); +} + +/* One byte to a PMU register over nub-spmi0: command, then data. */ +static void t6041_pmu_write(struct t6041_sleep *s, u16 reg, u8 val) +{ + unsigned int i; + u32 status; + + /* Drain any stale reply before issuing our command. */ + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_RX_EMPTY); i++) + readl(s->spmi + SPMI_REPLY); + writel((u32)reg << 16 | BIT(15) | PMU_SID << 8 | 0x30, s->spmi + SPMI_CMD); + writel(val, s->spmi + SPMI_CMD); + if (t6041_poll_until_us(s->spmi + SPMI_STATUS, status, + !(status & SPMI_RX_EMPTY), 1000)) + s->spmi_late++; + for (i = 0; i < SPMI_DRAIN_MAX && !(readl(s->spmi + SPMI_STATUS) & SPMI_RX_EMPTY); i++) + readl(s->spmi + SPMI_REPLY); + writel(1, s->spmi + SPMI_IRQ_ACK); +} + +static void cpm_gates(struct t6041_sleep *s) +{ + writel(0x80000000, s->pwrgate + 0x100); + writel(0x80000000, s->pwrgate + 0x108); + writel(0x80000000, s->pwrgate + 0x110); +} + +static void t6041_ps_match_list(void __iomem *const *regs, unsigned int count, + u32 mask, u32 want, bool skip_fused) +{ + unsigned int i; + + for (i = 0; i < count; i++) { + u32 now = readl(regs[i]); + + if (skip_fused && !(now & (PS_TARGET | PS_ACTUAL))) + continue; + if ((now & mask) != want) + writel((now & ~mask) | want, regs[i]); + } +} + +/* + * Put every matched PS word into its macOS commit mode: hardware AUTO (off, + * clock-gated, or active) or manual active. Fused-off channel words read 0 + * for both target and actual on binned parts and are skipped uniformly. + */ +static void t6041_ps_match_all(struct t6041_sleep *s) +{ + const u32 auto_mask = PS_TARGET | PS_AUTO_ENABLE | PS_AUTO_STATE; + + t6041_ps_match_list(s->ps_auto, s->n_auto, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0), + true); + t6041_ps_match_list(s->ps_auto_clkgate, s->n_auto_clkgate, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 4), + true); + t6041_ps_match_list(s->ps_auto_active, s->n_auto_active, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0xf), + false); + t6041_ps_match_list(s->ps_keep_on, s->n_keep_on, + PS_TARGET | PS_AUTO_ENABLE, PS_TARGET, false); +} + +static void t6041_cpu_off(u64 mpidr) +{ + t6041_offline_wfi(); +} + +static const struct spin_table_power_ops t6041_cpu_power_ops = { + .cpu_stop = t6041_cpu_stop, + .cpu_off = t6041_cpu_off, + .cpu_on = t6041_cpu_on, +}; + +static void __noreturn t6041_boot_wfi(struct t6041_sleep *s) +{ + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_BITS); + while (aic_sleep_ack()) + ; + while (true) { + dsb(sy); + isb(); + wfi(); + aic_sleep_ack(); + write_sysreg_s(IPI_SR_PENDING, SYS_APL_IPI_SR_EL1); + } +} + +/* + * Raise each present core and CPM PS word to on, then drop its target to 0 + * so the hardware drops PS_ACTUAL when the core enters deep WFI. + */ +static void t6041_cpu_ps_match(struct t6041_sleep *s) +{ + unsigned int cpu, i; + u32 v; + + for_each_present_cpu(cpu) { + void __iomem *reg = s->ps_cpu[t6041_cpu_id(cpu_logical_map(cpu))]; + + v = readl(reg); + writel((v & ~(PS_TARGET | PS_AUTO_ENABLE)) | PS_TARGET, reg); + t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); + } + for (i = 0; i < 2; i++) { + void __iomem *reg = s->ps_cpm[i]; + + v = readl(reg); + writel((v & ~(PS_TARGET | PS_AUTO_ENABLE)) | PS_TARGET, reg); + t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); + } + for_each_present_cpu(cpu) { + void __iomem *reg = s->ps_cpu[t6041_cpu_id(cpu_logical_map(cpu))]; + + writel(readl(reg) & ~PS_TARGET, reg); + } + for (i = 0; i < 2; i++) { + void __iomem *reg = s->ps_cpm[i]; + + writel(readl(reg) & ~PS_TARGET, reg); + } +} + +/* + * Lower every USB-C port's power domains in macOS's deepest-first order + * (phymxwrap -> usb -> usb_aon -> common_dp, then cio/pcie -> common) and + * wait for each domain to reach PS_ACTUAL == 0, then hand fab2_soc and afi + * to hardware AUTO (forcing them off hangs T6041). + */ +static void t6041_atc_down(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + for (i = 0; i < s->n_atc_off; i++) + t6041_ps_lower(s->ps_atc_off[i]); + for (i = 0; i < s->n_atc_off; i++) { + if (t6041_poll_until_us(s->ps_atc_off[i], v, + !FIELD_GET(PS_ACTUAL, v), 10000)) + s->atc_late++; + } + writel(readl(s->ps_atc_fabric) | PS_AUTO_ENABLE, s->ps_atc_fabric); + writel(readl(s->ps_atc_afi) | PS_AUTO_ENABLE, s->ps_atc_afi); +} + +/* + * Raise fab2_soc manually, raise all four atcN_common domains, then re-enable + * AUTO on fab2_soc so the sleep engine's ATC step never stalls on a gated + * parent fabric. + */ +static int t6041_ps_raise_start(void __iomem *reg) +{ + u32 v; + + writel((readl(reg) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET, reg); + return t6041_poll_until_us(reg, v, (v & PS_ACTUAL) == PS_ACTUAL, 5000); +} + +static void t6041_atc_commons_on(struct t6041_sleep *s) +{ + void __iomem *fab2 = s->ps_atc_fabric; + unsigned int i; + + t6041_ps_raise_start(fab2); + for (i = 0; i < AXI2AF_ATC_COUNT; i++) + t6041_ps_raise_start(s->ps_atc_common[i]); + writel((readl(fab2) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET | PS_AUTO_ENABLE, + fab2); +} + +/* + * Disable DSID age-out (word 0 bit 25) and unexpected RT hit (word 1 bit 8) + * error enables on every AMCC plane and clear any latched error status words. + */ +static void t6041_amcc_quiesce(struct t6041_sleep *s) +{ + unsigned int g, p, w; + + for (g = 0; g < s->ngroups; g++) { + for (p = 0; p < 4; p++) { + void __iomem *a = s->amccb[g] + AMCC_ERR_OFF + AMCC_PLANE_STRIDE * p; + + writel(readl(a + 0x0) & ~BIT(25), a + 0x0); + writel(readl(a + 0x8) & ~BIT(8), a + 0x8); + for (w = 0; w < 7; w++) { + u32 v = readl(a + 4 + 8 * w); + + if (v) + writel(v, a + 4 + 8 * w); + } + } + } + dsb(sy); +} + +/* + * Flush AMCC caches and enable DCS dynamic power gating on every enabled + * channel while the AMCC slices are still forced on. + */ +static void t6041_mcc_macos(struct t6041_sleep *s) +{ + unsigned int i, p; + u32 v; + + for (i = 0; i < s->ngroups; i++) { + /* +0x1c0000 is the AMCC all-planes write window; poll per plane. */ + writel(1, s->amccb[i] + 0x1c082c); + writel(1, s->amccb[i] + 0x1c2844); + for (p = 0; p < 4; p++) + t6041_poll_until_us(s->amccb[i] + AMCC_PLANE_STRIDE * p + 0x2844, + v, !(v & BIT(0)), 100000); + } + dsb(sy); + for (i = 0; i < 4 * s->ngroups; i++) + writel(readl(s->dcs[i] + 0x20) | 0x1100, s->dcs[i] + 0x20); + dsb(sy); +} + +static const char *const t6041_axi2af_names[AXI2AF_REG_COUNT] = { + "axi2af-disp", + "axi2af-dispext0", + "axi2af-dispext1", + "axi2af-dispext2", + "axi2af-dispext3", + "axi2af-ans", + "axi2af-avd", + "axi2af-venc0", + "axi2af-venc1", + "axi2af-jpg", +}; + +static void t6041_wake_sep(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + if (readl(s->wake + 0x0)) + writel(0, s->wake + 0x0); + for (i = 0; i < WAKE_WORDS; i++) + writel(s->wake_masks[i], s->wake + 0xc + 4 * i); + + v = readl(s->ps_sep); + if (!(v & BIT(10))) + writel(v | BIT(10), s->ps_sep); + dsb(sy); +} + +/* A perf word: the low nibble asks, [11:8] is the state reached, bit 31 busy. */ +static bool t6041_perf_set(void __iomem *reg, u32 state) +{ + u32 v; + + if (FIELD_GET(PERF_ACTUAL, readl(reg)) == state) + return true; + writel((readl(reg) & ~0xf) | state, reg); + return !t6041_poll_until_us(reg, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) == state, + 5000); +} + +/* SoC to 3, voters 0, DCS to 6: macOS commits at DCS 6 (0x7666); the engine takes it to 4. */ +static void t6041_mem_down(struct t6041_sleep *s) +{ + unsigned int i; + + t6041_perf_set(s->perf + 0x0, 3); + for (i = 0; i < 4; i++) + writel(0, s->pmc + i * 0x4000); + t6041_perf_set(s->perf + 0x400, 6); +} + +/* + * Cluster power-control words: +0 E, +4 P0, +8 P1, +0xc and +0x10 the two AVE + * complexes. Clear bit 5 (CLUSTER_UP_DONE) and take both AVE complexes to 0. + */ +static void t6041_ave_off(struct t6041_sleep *s) +{ + static const u16 ave[] = { 0xc, 0x10 }; + unsigned int i; + u32 v; + + for (i = 0; i < ARRAY_SIZE(ave); i++) { + writel(BIT(5), s->cluster + ave[i]); + t6041_poll_until_us(s->cluster + ave[i], v, !v, 5000); + } + v = readl(s->cluster + 0x8); + if (v & BIT(5)) + writel((v & 0xf) | BIT(5), s->cluster + 0x8); +} + +static void t6041_save(struct t6041_sleep *s); + +/* + * Lower a domain with two writes (AUTO off with target still f, then + * target 0), only when it is currently on so bit 11 does not latch. + */ +static void t6041_ps_lower_pair(void __iomem *reg, u32 first, u32 second) +{ + u32 v = readl(reg); + + if (!FIELD_GET(PS_TARGET, v) && !FIELD_GET(PS_ACTUAL, v)) + return; + writel(first, reg); + writel(second, reg); +} + +/* + * Pulse bit 33 of SOC-DEV-PS-REQ (PTD write +0x10f00) after ANS lowers and + * before arming WD2, matching macOS's traced -10 ms to -4 ms pulse (~6 ms). + * PMP is already halted by apple_sleep_coprocs_stop_all() before commit, so + * its PTD report page provides no completion/ACK bit to poll; read back + * SOC-DEV-PS-REQ (+0x1e00) to post the write before holding the 5 ms pulse. + */ +static void t6041_ptd_soc_dev_pulse(struct t6041_sleep *s) +{ + writeq(0x200000800ULL, s->ptd + PTD_SOC_DEV_REQ_WRITE); + readq(s->ptd + PTD_SOC_DEV_REQ_READ); + t6041_spin_us(5000); + writeq(0x800ULL, s->ptd + PTD_SOC_DEV_REQ_WRITE); +} + +static int t6041_sleep_commit(unsigned long unused) +{ + struct t6041_sleep *s = t6041_sleep; + unsigned int i, cpu; + u32 v; + + t6041_save(s); + s->stop_ret = spin_table_stop_parked(); + t6041_ave_off(s); + /* While every AMCC slice is still on: a clock-gated plane faults. */ + t6041_amcc_quiesce(s); + t6041_mcc_macos(s); + /* + * Disarm AXI2AF bridges on powered blocks before lowering them so the + * power domain does not latch bit 11 on subsequent sleeps. + */ + for (i = 0; i < AXI2AF_COUNT; i++) { + if (!s->axi2af[i]) + continue; + if (FIELD_GET(PS_ACTUAL, readl(s->ps_axi2af[i])) != 0xf) + continue; + v = readl(s->axi2af[i] + 0x4); + if (!(v & 1) && !(readl(s->axi2af[i] + 0x8) & 1)) + continue; + writel(v & ~1U, s->axi2af[i] + 0x4); + writel(readl(s->axi2af[i] + 0x8) & ~1U, s->axi2af[i] + 0x8); + } + t6041_cpu_ps_match(s); + t6041_mem_down(s); + + /* + * Lower child-before-parent sorted domains and wait for each domain to + * reach PS_ACTUAL == 0 before moving on so no parent is ever lowered + * while a child is still powering off (which latches bit 11). + */ + for (i = 0; i < s->n_off; i++) { + t6041_ps_lower(s->ps_off[i]); + if (t6041_poll_until_us(s->ps_off[i], v, + !FIELD_GET(PS_ACTUAL, v), 5000)) + s->off_late++; + } + + t6041_ps_match_all(s); + /* Every PMC voter at 0, and the PMS word macOS holds at 0. */ + for (i = 0; i < 4; i++) + writel(0, s->pmc + i * 0x4000); + writel(0, s->pmc + 0xa9c18); + readl(s->pmc + 0xa9c18); + if (t6041_poll_until_us(s->perf + 0x400, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) <= 6, 20000) || + t6041_poll_until_us(s->perf + 0x0, v, + !(v & PERF_BUSY) && FIELD_GET(PERF_ACTUAL, v) <= 3, 20000)) + s->dcs_late++; + /* Cluster PTD votes, no demand. */ + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_0); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_1); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_2); + writeq(0x2000000000000000ULL, s->ptd + PTD_CLUSTER_WRITE_3); + t6041_atc_down(s); + t6041_wake_sep(s); + + writel(0xffef, s->misc + 0x0); + /* + * Mask AIC before releasing parked secondary cores into their final + * deep WFI, then poll each non-boot core and secondary CPM PS word + * until hardware drops PS_ACTUAL to 0. + */ + aic_sleep_mask_all(); + spin_table_release_stopped(); + for_each_present_cpu(cpu) { + unsigned int id; + + if (cpu == smp_processor_id()) + continue; + id = t6041_cpu_id(cpu_logical_map(cpu)); + if (t6041_poll_until_us(s->ps_cpu[id], v, + !FIELD_GET(PS_ACTUAL, v), 50000)) + s->cpu_off_late |= BIT(id); + } + for (i = 0; i < T6041_CPM_COUNT; i++) { + if (i == MPIDR_AFFINITY_LEVEL(cpu_logical_map(smp_processor_id()), 1)) + continue; + if (t6041_poll_until_us(s->ps_cpm[i], v, + !FIELD_GET(PS_ACTUAL, v), 50000)) + s->cpm_off_late |= BIT(i); + } + + writel(0x3f833ff1, s->spmi + SPMI_NOTIFY_MASK); + /* PMU boot stage to 0x50 (asleep). */ + t6041_pmu_write(s, 0xf801, 0x50); + writel(0x3f0, s->ps_commit_periph[0]); + writel(0x3f0, s->ps_commit_periph[1]); + writel(0x3f0, s->ps_commit_periph[2]); + writel(0x3f0, s->ps_commit_periph[3]); + writel(0x2000001, s->spmi + SPMI_NOTIFY_MASK); + if (FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0))) + writel(0x2000001, s->spmi_a0 + SPMI_NOTIFY_MASK); + writel(0x3f0, s->ps_commit_periph[4]); + cpm_gates(s); + writel(0, s->cluster + 0x0); + cpm_gates(s); + writel(0, s->cluster + 0x8); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_PHY_SW], 0x400004f, 0x4000340); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_ST1], 0xf, 0x300); + writel(0x3f0, s->ps_apcie[T6041_APCIE_ST1]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_ST0], 0xf0000ff, 0xf0003f0); + writel(0x3f0, s->ps_apcie[T6041_APCIE_ST0]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_SYS_GP], 0xf, 0x300); + writel(0x3f0, s->ps_apcie[T6041_APCIE_GP]); + t6041_ps_lower_pair(s->ps_apcie[T6041_APCIE_ANS], 0xf0000ff, 0xf0003f0); + /* macOS -10 ms to -4 ms before arming WD2: pulse PTD SOC-DEV-PS-REQ bit 33. */ + t6041_ptd_soc_dev_pulse(s); + writel(0, s->wdt + 0x0c); + writel(0, s->wdt + 0x2c); + writel(0, s->wdt + 0x20); + writel(0x7270e00, s->wdt + 0x28); + writel(1, s->wdt + 0x2c); + writel(0, s->aon + 0x8); + cpm_gates(s); + cpm_gates(s); + cpm_gates(s); + writel(0x10, s->cluster + 0x00); + writel(0, s->cluster + 0x04); + writel(0x10, s->cluster + 0x08); + writel(0x20, s->cluster + 0x0c); + writel(0, s->cluster + 0x10); + writel(0x400024f, s->ps_commit_sio[0]); + writel(0x400024f, s->ps_commit_sio[1]); + writel(0xa0100000, s->clkgen + 0x60); + writel(0xa0100000, s->clkgen + 0x64); + writel(0xa0100000, s->clkgen + 0x54); + writel(0xa0100000, s->clkgen + 0x50); + /* aura reads this with the MMU off on the way back. */ + WRITE_ONCE(s->mbox->resume_pa, __pa_symbol(cpu_resume)); + dcache_clean_poc((unsigned long)s->mbox, (unsigned long)(s->mbox + 1)); + t6041_atc_commons_on(s); + /* + * Confirm the SPMI controller's TX and RX FIFOs are idle after the + * PMU boot-stage write before the sleep engine takes over SPMI. + */ + if (t6041_poll_until_us(s->spmi + SPMI_STATUS, v, + (v & SPMI_IDLE) == SPMI_IDLE, 5000)) + s->spmi_late++; + /* Keep-alive tables off right before commit. */ + for (i = 0; i < KA_WORDS; i++) { + writel(0, s->ka[0] + i * KA_STRIDE); + writel(0, s->ka[1] + i * KA_STRIDE); + } + dsb(sy); + writel(1, s->commit); + dsb(sy); + /* + * Secondary cores and non-boot CPMs are already polled off in deep WFI. + * Mask AIC again and hold the 3 ms commit-to-boot-WFI gap (matching + * sleep.c's boot_wfi_delay_ms = 3 on T8132/T8142; no hardware status + * bit reports commit-armed, and pure counter spin avoids WFET early + * gating) before entering the boot core's final deep WFI. + */ + aic_sleep_mask_all(); + t6041_spin_us(3000); + t6041_boot_wfi(s); +} + +/* + * Display pipe PMC votes saved before commit and restored on wake (offsets into + * the PMC register block). + */ +static const u32 t6041_pmc_vote_off[5] = { 0xac028, 0xa4000, 0xac020, 0xa9c10, 0xa9c20 }; + +/* + * Restore AMCC cache mode after wake: write way count through the all-planes + * window, then poll each plane's status word. + */ +static void t6041_mcc_active(struct t6041_sleep *s) +{ + unsigned int i, p; + u32 v; + + for (i = 0; i < s->ngroups; i++) { + writel(s->pre_ways[4 * i], s->amccb[i] + 0x1c2800); + for (p = 0; p < 4; p++) + readl_poll_timeout_atomic(s->amccb[i] + AMCC_PLANE_STRIDE * p + 0x2804, v, + v == s->pre_cache[4 * i + p], 10, 100000); + } +} + +/* Restore display PMC votes; wait for the DVMR ack (+0x20). */ +static void t6041_pmc_votes(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + for (i = 0; i < ARRAY_SIZE(t6041_pmc_vote_off); i++) { + void __iomem *reg = s->pmc + t6041_pmc_vote_off[i]; + + if (readl(reg) != s->pre_votes[i]) + writel(s->pre_votes[i], reg); + if (t6041_pmc_vote_off[i] == 0xa4000 && s->pre_votes[i]) + readl_poll_timeout_atomic(reg + 0x20, v, v & BIT(0), 1, 8000); + } +} + +static const u16 t6041_clk_mux[4] = { 0x50, 0x54, 0x64, 0x60 }; + +static void t6041_save(struct t6041_sleep *s) +{ + unsigned int i; + + for (i = 0; i < 4 * s->ngroups; i++) { + void __iomem *plane = s->amccb[i / 4] + AMCC_PLANE_STRIDE * (i % 4); + + s->pre_ways[i] = readl(plane + 0x2800); + s->pre_cache[i] = readl(plane + 0x2804); + } + for (i = 0; i < ARRAY_SIZE(t6041_pmc_vote_off); i++) + s->pre_votes[i] = readl(s->pmc + t6041_pmc_vote_off[i]); + s->cntkctl = read_sysreg(cntkctl_el1); + s->siq_cfg = read_sysreg_s(SYS_APL_SIQ_CFG_EL1); + for (i = 0; i < s->n_restore; i++) + s->ps_pre[i] = readl(s->ps_restore[i]); + s->pre_perf[0] = readl(s->perf + 0x0); + s->pre_perf[1] = readl(s->perf + 0x400); + for (i = 0; i < 4; i++) + s->pre_pmc[i] = readl(s->pmc + i * 0x4000); + s->pre_pmc[4] = readl(s->pmc + 0xa9c18); + for (i = 0; i < 4; i++) + s->pre_clk[i] = readl(s->clkgen + t6041_clk_mux[i]); + s->pre_mask[0] = readl(s->spmi + SPMI_NOTIFY_MASK); + s->pre_a0 = FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0)) != 0; + if (s->pre_a0) + s->pre_mask[1] = readl(s->spmi_a0 + SPMI_NOTIFY_MASK); + for (i = 0; i < WAKE_WORDS; i++) + s->pre_wake[i] = readl(s->wake + 0xc + 4 * i); + for (i = 0; i < AOP_PS_WORDS; i++) + s->aop_pre[i] = readl(s->aop_ps + 8 * i); + for (i = 0; i < s->npins; i++) { + if (test_bit(i, s->gpio_skip)) + continue; + s->gpio_pre[i] = readl(s->gpio + 4 * i); + } + /* Only with the GP PCIe block on: apcie_gp and apcie_sys_gp. */ + s->gp_saved = s->gp_port[0] && s->gp_port[1] && s->gp_phy[0] && s->gp_phy[1] && + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_GP])) == 0xf && + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_SYS_GP])) == 0xf; + for (i = 0; i < 2 && s->gp_saved; i++) { + s->gp_phy_pre[i] = readl(s->gp_phy[i]); + s->gp_app_pre[i] = readl(s->gp_port[i] + 0x800); + s->gp_perst_pre[i] = readl(s->gp_port[i] + 0x82c); + } +} + +/* + * Restore all AP GPIO pin configurations lost across deep sleep, skipping pins + * listed in apple,pinctrl-skip-pins. + */ +static void t6041_gpio_restore(struct t6041_sleep *s) +{ + unsigned int i; + + for (i = 0; i < s->npins; i++) { + if (test_bit(i, s->gpio_skip)) + continue; + if (readl(s->gpio + 4 * i) != s->gpio_pre[i]) + writel(s->gpio_pre[i], s->gpio + 4 * i); + } +} + +/* + * AOP island MiniPMGR power words (ps-aop). Walked backwards (parents first) + * on wake so every previously-on domain returns to manual target f. + */ +static const u16 t6041_aop_ps_order[] = { + 0x0b0, 0x128, 0x120, 0x158, 0x150, 0x148, 0x140, 0x138, 0x130, 0x0c0, 0x0c8, + 0x0e8, 0x0f0, 0x0f8, 0x100, 0x108, 0x110, 0x118, 0x0e0, 0x0d8, 0x0d0, 0x0b8, 0x090, + 0x020, 0x098, 0x0a0, 0x0a8, 0x028, 0x030, 0x068, 0x070, 0x078, 0x080, 0x038, 0x040, + 0x048, 0x058, 0x060, 0x088, 0x050, 0x010, 0x018, 0x008, 0x000, +}; + +static_assert(ARRAY_SIZE(t6041_aop_ps_order) == AOP_PS_WORDS); + +static void t6041_aop_wake(struct t6041_sleep *s) +{ + int k; + u32 v; + + for (k = ARRAY_SIZE(t6041_aop_ps_order) - 1; k >= 0; k--) { + u16 off = t6041_aop_ps_order[k]; + void __iomem *r = s->aop_ps + off; + u32 now = readl(r); + + if (!FIELD_GET(PS_ACTUAL, s->aop_pre[off / 8])) + continue; + if (FIELD_GET(PS_ACTUAL, now) == 0xf && !(now & PS_AUTO_ENABLE)) + continue; + writel((now & ~(PS_AUTO_ENABLE | PS_TARGET)) | PS_TARGET, r); + readl_poll_timeout_atomic(r, v, FIELD_GET(PS_ACTUAL, v), 1, 2000); + } +} + +static int t6041_ps_raise(void __iomem *reg) +{ + int ret = t6041_ps_raise_start(reg); + + writel((readl(reg) & ~(PS_AUTO_ENABLE | GENMASK(11, 0))) | PS_TARGET | PS_AUTO_ENABLE, reg); + return ret; +} + +/* + * Bring ANS's storage PCIe link back from power-off using the DT-supplied + * apple,tunable-* tables from apple,apcie. Returns 0, or the step (1-8) that + * timed out. Runs only when the NVMe driver stopped ANS for this sleep. + */ +static int t6041_apcie_raise(struct t6041_sleep *s) +{ + void __iomem *ctrl = s->ap_phy + 0x8000; + void __iomem *run = s->ap_phy + 0x8004; + u32 v; + int ret; + + ret = t6041_ps_raise(s->ps_apcie[T6041_APCIE_ANS]); + if (!ret) { + writel(readl(s->axi2af[AXI2AF_ANS] + 0x4) | 1, s->axi2af[AXI2AF_ANS] + 0x4); + writel(readl(s->axi2af[AXI2AF_ANS] + 0x8) | 1, s->axi2af[AXI2AF_ANS] + 0x8); + } + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_GP]); + if (!ret) + ret = t6041_ps_raise_start(s->ps_apcie[T6041_APCIE_SYS_GP]); + if (!ret) { + writel(readl(s->ap_axi + 0x104) | 1, s->ap_axi + 0x104); + writel(readl(s->ap_axi + 0x108) | 1, s->ap_axi + 0x108); + } + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_ST0]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_SYS_ST0]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_ST1]); + ret |= t6041_ps_raise(s->ps_apcie[T6041_APCIE_SYS_ST1]); + if (ret) + return 1; + + apple_tunable_apply(s->ap_axi, s->tun_axi2af); + apple_tunable_apply(s->ap_cio3pll, s->tun_cio3pll); + apple_tunable_apply(s->ap_clkgen, s->tun_clkgen); + writel(readl(s->ap_clkgen + 0x4) | BIT(31), s->ap_clkgen + 0x4); + writel(readl(s->ap_clkgen + 0x0) & ~(BIT(2) | BIT(1)), s->ap_clkgen + 0x0); + if (readl_poll_timeout_atomic(s->ap_clkgen + 0x0, v, !(v & BIT(31)), 1, 50000)) + return 2; + if (t6041_ps_raise(s->ps_apcie[T6041_APCIE_PHY_SW])) + return 3; + apple_tunable_apply(s->ap_phy, s->tun_phy); + if (readl_poll_timeout_atomic(s->ap_phy + 0x4000, v, v & BIT(31), 1, 50000)) + return 4; + writel(readl(ctrl) | BIT(0), ctrl); + if (readl_poll_timeout_atomic(ctrl, v, v & BIT(2), 1, 50000)) + return 5; + writel(readl(ctrl) | BIT(1), ctrl); + if (readl_poll_timeout_atomic(ctrl, v, v & BIT(3), 1, 50000)) + return 6; + writel(readl(ctrl) & ~BIT(4), ctrl); + + writel(readl(run) | BIT(0), run); + apple_tunable_apply(s->ap_phy_ip, s->tun_phy_ip_pll); + apple_tunable_apply(s->ap_phy_ip, s->tun_phy_ip_lanes); + writel(readl(s->ap_phy_ip + 0x90) & ~BIT(16), s->ap_phy_ip + 0x90); + writel(readl(run) | BIT(4), run); + if (readl_poll_timeout_atomic(s->ap_phy + 0x8008, v, v & BIT(0), 1, 50000)) + return 7; + writel(readl(s->ap_phy + 0x4000) | BIT(0), s->ap_phy + 0x4000); + writel(readl(ctrl) | BIT(27), ctrl); + + writel(0, s->ap_rc + 0x04); + writel(0x140, s->ap_rc + 0x54); + writel(1, s->ap_rc + 0x50); + if (readl_poll_timeout_atomic(s->ap_rc + 0x58, v, v & BIT(0), 1, 50000)) + return 8; + return 0; +} + +/* + * Restore GP PCIe port 0/1 reference and app clocks after deep sleep so their + * DART blocks do not raise SErrors on resume. Returns a mask of late ports. + */ +static unsigned int t6041_gp_pcie_clk(struct t6041_sleep *s) +{ + unsigned int i, late = 0; + u32 v; + + for (i = 0; i < 2; i++) { + void __iomem *phy = s->gp_phy[i]; + void __iomem *port = s->gp_port[i]; + u32 cfg = s->gp_phy_pre[i]; + u32 app = s->gp_app_pre[i]; + + if (!s->gp_saved || + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_GP])) != 0xf || + FIELD_GET(PS_ACTUAL, readl(s->ps_apcie[T6041_APCIE_SYS_GP])) != 0xf) + continue; + writel(readl(phy) | BIT(0), phy); + if (readl_poll_timeout_atomic(phy, v, v & BIT(2), 1, 50000)) + late |= BIT(i); + writel(readl(phy) | BIT(1), phy); + if (readl_poll_timeout_atomic(phy, v, v & BIT(3), 1, 50000)) + late |= BIT(i); + if (!(cfg & BIT(4))) { + writel(readl(phy) & ~BIT(4), phy); + /* T6020+ PHY refclk buffer settle before REFCLKEN (as in pcie-apple.c). */ + udelay(1); + } + writel(readl(phy) | (cfg & (BIT(9) | BIT(10))), phy); + writel(readl(phy) | (cfg & BIT(31)), phy); + writel((readl(port + 0x800) & ~(BIT(0) | BIT(8))) | (app & (BIT(0) | BIT(8))), + port + 0x800); + writel(readl(port + 0x13c) | BIT(8), port + 0x13c); + writel(s->gp_perst_pre[i], port + 0x82c); + writel(readl(port + 0x13c) & ~BIT(8), port + 0x13c); + if (readl_poll_timeout_atomic(port + 0x804, v, v & BIT(0), 1, 50000)) + late |= BIT(i); + } + return late; +} + +/* + * Restore every non-CPU/CPM PS word to its pre-commit target and AUTO state: + * raises parents first (0..n_restore-1), then lowers children first. + */ +static unsigned int t6041_ps_restore(struct t6041_sleep *s) +{ + const u32 keep = ~(u32)(PS_AUTO_ENABLE | PS_FLAGS | PS_TARGET); + unsigned int i, late = 0; + u32 v; + + for (i = 0; i < s->n_restore; i++) { + void __iomem *reg = s->ps_restore[i]; + u32 pre = s->ps_pre[i]; + u32 cur = readl(reg); + u32 pt = pre & PS_TARGET; + + if (!(pre & (PS_TARGET | PS_ACTUAL)) && !(cur & (PS_TARGET | PS_ACTUAL))) + continue; + if (pt > (cur & PS_TARGET)) { + writel((cur & keep) | pt, reg); + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(PS_ACTUAL, v) == pt, + 1, 3000)) + late++; + cur = readl(reg); + } + if (pt == (cur & PS_TARGET) && ((pre ^ cur) & PS_AUTO_ENABLE)) + writel((cur & ~(PS_AUTO_ENABLE | PS_FLAGS)) | (pre & PS_AUTO_ENABLE), reg); + } + for (i = s->n_restore; i-- > 0;) { + void __iomem *reg = s->ps_restore[i]; + u32 pre = s->ps_pre[i]; + u32 cur = readl(reg); + u32 pt = pre & PS_TARGET; + + if (pt >= (cur & PS_TARGET)) + continue; + if (cur & PS_AUTO_ENABLE) { + cur &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(cur, reg); + } + writel((cur & keep) | pt | PS_FLAGS, reg); + if (readl_poll_timeout_atomic(reg, v, FIELD_GET(PS_ACTUAL, v) == pt, 1, 3000)) + late++; + if (pre & PS_AUTO_ENABLE) + writel((readl(reg) & ~PS_FLAGS) | PS_AUTO_ENABLE, reg); + } + return late; +} + +static u64 t6041_ret_t0, t6041_ret_t1; + +/* + * Back on the boot core through aura's mailbox: clusters on, masks back, WD2 off. + * Hardware wake reset restores the boot CPU power state before return, so + * udelay()/readl_poll_timeout_atomic() are safe here and in its helpers. + */ +static void t6041_sleep_return(struct t6041_sleep *s) +{ + unsigned int i; + u32 v; + + t6041_ret_t0 = read_sysreg(cntpct_el0); + /* The reset left the timer control and the AIC's IRQ routing at their EL2 defaults. */ + write_sysreg(s->cntkctl, cntkctl_el1); + isb(); + write_sysreg_s(s->siq_cfg, SYS_APL_SIQ_CFG_EL1); + writel(0, s->wdt + 0x2c); + /* Keep-alive back on, as macOS on its way back and as iBoot leaves it. */ + for (i = 0; i < KA_WORDS; i++) { + writel(1, s->ka[0] + i * KA_STRIDE); + writel(1, s->ka[1] + i * KA_STRIDE); + } + spin_table_stop_finished(); + aic_sleep_restore(); + writel(0xf, s->cluster + 0x0); + writel(0xf, s->cluster + 0x4); + writel(0xf, s->cluster + 0x8); + /* The two wake gates, then the CPM voters. */ + writel(readl(s->pwrgate + 0x000) | BIT(31), s->pwrgate + 0x000); + writel(readl(s->pwrgate + 0x040) | BIT(31), s->pwrgate + 0x040); + cpm_gates(s); + /* SEP DEV_DISABLE off again, bit 11 polled clear; S2R request word; wake masks. */ + v = readl(s->ps_sep); + if (v & BIT(10)) + writel(v & ~BIT(10), s->ps_sep); + readl_poll_timeout_atomic(s->ps_sep, v, !(v & BIT(11)), 1, 5000); + writel(0, s->wake + 0x0); + for (i = 0; i < WAKE_WORDS; i++) + writel(s->pre_wake[i], s->wake + 0xc + 4 * i); + /* Before t6041_mcc_active() touches the AMCC/DCS planes. */ + s->ps_late = t6041_ps_restore(s); + t6041_mcc_active(s); + t6041_aop_wake(s); + t6041_gpio_restore(s); + /* Re-arm AXI2AF bridges whose blocks are back on. */ + for (i = 0; i < AXI2AF_COUNT; i++) { + if (!s->axi2af[i]) + continue; + v = readl(s->ps_axi2af[i]); + if ((v & PS_TARGET) != PS_TARGET || FIELD_GET(PS_ACTUAL, v) != 0xf) + continue; + writel(readl(s->axi2af[i] + 0x4) | 1, s->axi2af[i] + 0x4); + writel(readl(s->axi2af[i] + 0x8) | 1, s->axi2af[i] + 0x8); + } + s->apcie_ret = s->ans_stopped ? t6041_apcie_raise(s) : 0; + s->gp_late = t6041_gp_pcie_clk(s); + /* Restore parked clock muxes (last parked first), perf states, and PMC voters. */ + for (i = 4; i-- > 0;) + writel(s->pre_clk[i], s->clkgen + t6041_clk_mux[i]); + t6041_perf_set(s->perf + 0x400, s->pre_perf[1] & 0xf); + t6041_perf_set(s->perf + 0x0, s->pre_perf[0] & 0xf); + for (i = 0; i < 4; i++) + writel(s->pre_pmc[i], s->pmc + i * 0x4000); + writel(s->pre_pmc[4], s->pmc + 0xa9c18); + t6041_pmc_votes(s); + writel(s->pre_mask[0], s->spmi + SPMI_NOTIFY_MASK); + if (s->pre_a0 && FIELD_GET(PS_ACTUAL, readl(s->ps_spmi_a0))) + writel(s->pre_mask[1], s->spmi_a0 + SPMI_NOTIFY_MASK); + writel(0, s->wdt + 0x2c); + /* PMU boot stage back from 0x50 (asleep) to 0x30 (OS running). */ + t6041_pmu_write(s, 0xf801, 0x30); + t6041_ret_t1 = read_sysreg(cntpct_el0); +} + +static int t6041_sleep_enter(suspend_state_t state) +{ + struct t6041_sleep *s = t6041_sleep; + unsigned int i; + int ret; + + /* With no way back, a sleep would end in aura's boot flow over this kernel. */ + if (!s->mbox) + return -EOPNOTSUPP; + if (WARN_ON_ONCE(!s->apcie_ready)) + return -EOPNOTSUPP; + /* + * Display power chains require GAPF unprotect, child-first lowering, and + * fab6_soc hold (handled by apple-dcp); refuse sleep if any display block + * is still active (e.g., apple-drm unbound or nomodeset). + */ + for (i = 0; i < AXI2AF_DISP_COUNT; i++) { + u32 v = readl(s->ps_axi2af[AXI2AF_DISP_FIRST + i]); + + if (v & (PS_TARGET | PS_ACTUAL)) { + dev_err(s->dev, "refused: display domain %u still active (%#x)\n", i, v); + return -EBUSY; + } + } + /* + * Every parked CPU answers the hold while a refusal is still possible: at the commit + * only a held CPU stops, and one left awake there keeps the engine waiting until the + * watchdog resets the SoC. + */ + ret = spin_table_hold_parked(); + if (ret) { + dev_err(s->dev, "refused: a parked CPU didn't answer the hold: %d\n", ret); + return ret; + } + ret = apple_sleep_coprocs_check_all(); + if (ret) { + spin_table_unhold_parked(); + return ret; + } + if (pm_wakeup_pending()) { + spin_table_unhold_parked(); + return -EBUSY; + } + /* + * Send SEP SLEEP only after every refusal check has passed: a nonzero + * return here guarantees nothing was sent, while success gates the + * enclave and commits this sleep through physical wake. + */ + ret = apple_sleep_enclave_stop_all(); + if (ret) { + spin_table_unhold_parked(); + return ret; + } + s->stop_ret = 0; + s->apcie_ret = 0; + s->atc_late = 0; + s->off_late = 0; + s->dcs_late = 0; + s->cpu_off_late = 0; + s->cpm_off_late = 0; + s->spmi_late = 0; + s->ps_late = 0; + s->gp_late = 0; + /* macOS stops the PMP before its last steps; past this a refusal can't go back. */ + ret = apple_sleep_coprocs_stop_all(); + s->coproc_ret = ret; + s->ans_stopped = apple_sleep_coprocs_ans_stopped(); + pm_set_resume_via_firmware(); + ret = cpu_suspend(0, t6041_sleep_commit); + if (!ret) + t6041_sleep_return(s); + return ret; +} + +static void t6041_sleep_end(void) +{ + struct t6041_sleep *s = t6041_sleep; + + if (!s || !t6041_ret_t1) + return; + dev_dbg(s->dev, "back from deep sleep, return path %llu ms\n", + div64_u64((t6041_ret_t1 - t6041_ret_t0) * 1000, arch_timer_get_cntfrq())); + t6041_ret_t1 = 0; + if (s->coproc_ret < 0) + dev_warn(s->dev, "a coprocessor didn't stop for the sleep: %d\n", s->coproc_ret); + if (s->stop_ret) + dev_warn(s->dev, "the parked CPUs didn't all stop: %d\n", s->stop_ret); + if (s->atc_late) + dev_warn(s->dev, "%u ATC power domains did not reach off before commit\n", + s->atc_late); + if (s->off_late) + dev_warn(s->dev, "%u power domains did not reach off before commit\n", + s->off_late); + if (s->dcs_late) + dev_warn(s->dev, "DCS/SoC perf did not settle after clearing PMC voters\n"); + if (s->cpu_off_late) + dev_warn(s->dev, "secondary CPUs %#x did not reach off before commit\n", + s->cpu_off_late); + if (s->cpm_off_late) + dev_warn(s->dev, "secondary CPMs %#x did not reach off before commit\n", + s->cpm_off_late); + if (s->spmi_late) + dev_warn(s->dev, "%u SPMI waits timed out around sleep\n", s->spmi_late); + if (s->ps_late) + dev_dbg(s->dev, "%u power domains took more than 3 ms to come back\n", s->ps_late); + if (s->apcie_ret) + dev_warn(s->dev, "storage link raise timed out at step %d\n", s->apcie_ret); + if (s->gp_late) + dev_warn(s->dev, "GP PCIe ports %#x didn't come back\n", s->gp_late); +} + +static int t6041_sleep_begin(suspend_state_t state) +{ + /* The PM core also calls .begin for s2idle when no s2idle ops are installed. */ + if (state != PM_SUSPEND_MEM) + return 0; + pm_set_suspend_via_firmware(); + return 0; +} + +static const struct platform_suspend_ops t6041_sleep_ops = { + .valid = suspend_valid_only_mem, + .begin = t6041_sleep_begin, + .end = t6041_sleep_end, + .enter = t6041_sleep_enter, +}; + +static void t6041_iounmap(void *base) +{ + iounmap((void __iomem *)base); +} + +static void __iomem *t6041_map_idx(struct device *dev, struct device_node *np, + int idx, resource_size_t min_size, + resource_size_t *out_size) +{ + struct resource res; + void __iomem *base; + int ret; + + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return IOMEM_ERR_PTR(-EINVAL); + if (resource_size(&res) < min_size) + return IOMEM_ERR_PTR(-EINVAL); + /* Shared with other drivers, so map without claiming the region. */ + base = of_iomap(np, idx); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + ret = devm_add_action_or_reset(dev, t6041_iounmap, (void __force *)base); + if (ret) + return IOMEM_ERR_PTR(ret); + if (out_size) + *out_size = resource_size(&res); + return base; +} + +static void __iomem *t6041_map_name(struct device *dev, struct device_node *np, + const char *name, resource_size_t min_size, + resource_size_t *out_size) +{ + int idx = of_property_match_string(np, "reg-names", name); + + if (idx < 0) + return IOMEM_ERR_PTR(idx); + return t6041_map_idx(dev, np, idx, min_size, out_size); +} + +struct t6041_pmgr_bank { + struct device_node *np; + void __iomem *base; + resource_size_t size; +}; + +struct t6041_ps_resolver { + struct device *dev; + struct t6041_pmgr_bank banks[T6041_MAX_PMGR_BANKS]; + unsigned int nbanks; +}; + +static void t6041_ps_resolver_cleanup(struct t6041_ps_resolver *r) +{ + unsigned int i; + + for (i = 0; i < r->nbanks; i++) + of_node_put(r->banks[i].np); +} + +static void __iomem *t6041_resolve_ps_node(struct t6041_ps_resolver *r, + struct device_node *ps_np) +{ + struct t6041_pmgr_bank *bank = NULL; + struct device_node *parent; + unsigned int i; + u32 off; + + if (of_property_read_u32(ps_np, "reg", &off) || (off & 3)) { + dev_err(r->dev, "%pOF: invalid PMGR PS reg offset\n", ps_np); + return IOMEM_ERR_PTR(-EINVAL); + } + + parent = of_get_parent(ps_np); + if (!parent) + return IOMEM_ERR_PTR(-EINVAL); + + for (i = 0; i < r->nbanks; i++) { + if (r->banks[i].np == parent) { + bank = &r->banks[i]; + break; + } + } + + if (!bank) { + resource_size_t size; + void __iomem *base; + + if (r->nbanks >= T6041_MAX_PMGR_BANKS) { + of_node_put(parent); + return IOMEM_ERR_PTR(-ENOSPC); + } + base = t6041_map_idx(r->dev, parent, 0, 4, &size); + if (IS_ERR(base)) { + of_node_put(parent); + return base; + } + bank = &r->banks[r->nbanks++]; + bank->np = of_node_get(parent); + bank->base = base; + bank->size = size; + } + of_node_put(parent); + + if (off > bank->size || bank->size - off < 4) { + dev_err(r->dev, "%pOF: offset %#x exceeds parent size %pa\n", + ps_np, off, &bank->size); + return IOMEM_ERR_PTR(-EINVAL); + } + + return bank->base + off; +} + +static int t6041_parse_ps_fixed(struct t6041_ps_resolver *r, const char *prop, + void __iomem **out_regs, + struct device_node **out_nodes, + unsigned int expected) +{ + struct device_node *np = r->dev->of_node; + unsigned int i; + int count; + + count = of_count_phandle_with_args(np, prop, NULL); + if (count != expected) + return dev_err_probe(r->dev, -EINVAL, + "%s: expected %u phandles, got %d\n", + prop, expected, count); + + for (i = 0; i < expected; i++) { + struct device_node *ps_np; + void __iomem *reg; + + ps_np = of_parse_phandle(np, prop, i); + if (!ps_np) + return dev_err_probe(r->dev, -EINVAL, + "%s[%u]: unresolved phandle\n", + prop, i); + reg = t6041_resolve_ps_node(r, ps_np); + if (IS_ERR(reg)) { + of_node_put(ps_np); + return dev_err_probe(r->dev, PTR_ERR(reg), + "%s[%u]: cannot map PS register\n", + prop, i); + } + out_regs[i] = reg; + if (out_nodes) + out_nodes[i] = ps_np; + else + of_node_put(ps_np); + } + return 0; +} + +struct t6041_topo_ctx { + struct device *dev; + struct device_node *const *nodes; + unsigned int n; + u8 *state; + unsigned int *order; + unsigned int out; +}; + +static int t6041_topo_find(const struct t6041_topo_ctx *ctx, + const struct device_node *np) +{ + unsigned int i; + + for (i = 0; i < ctx->n; i++) + if (ctx->nodes[i] == np) + return i; + return -1; +} + +static int t6041_ps_parent(struct device_node *np, int index, + struct device_node **out) +{ + struct of_phandle_args args; + int ret; + + ret = of_parse_phandle_with_args(np, "power-domains", + "#power-domain-cells", index, &args); + if (ret) { + *out = NULL; + return ret; + } + *out = args.np; + return 0; +} + +static int t6041_topo_visit(struct t6041_topo_ctx *ctx, struct device_node *np, + unsigned int depth) +{ + int idx = t6041_topo_find(ctx, np); + struct device_node *parent; + int k, ret; + + if (idx >= 0) { + if (ctx->state[idx] == 2) + return 0; + if (ctx->state[idx] == 1) { + dev_err(ctx->dev, "PMGR power-domain cycle involving %pOF\n", np); + return -EINVAL; + } + ctx->state[idx] = 1; + } + if (depth >= T6041_PS_MAX_DEPTH) { + dev_err(ctx->dev, "PMGR power-domain hierarchy too deep or cyclic at %pOF\n", np); + return -EINVAL; + } + + for (k = 0; ; k++) { + ret = t6041_ps_parent(np, k, &parent); + if (ret == -ENOENT) + break; + if (ret) + return ret; + ret = t6041_topo_visit(ctx, parent, depth + 1); + of_node_put(parent); + if (ret) + return ret; + } + + if (idx >= 0) { + ctx->state[idx] = 2; + ctx->order[ctx->out++] = idx; + } + return 0; +} + +static int t6041_topo_sort(struct device *dev, struct device_node *const *nodes, + unsigned int n, unsigned int *order, bool child_first) +{ + struct t6041_topo_ctx ctx = { + .dev = dev, + .nodes = nodes, + .n = n, + .order = order, + }; + unsigned int i; + int ret = 0; + + if (!n) + return 0; + + ctx.state = kcalloc(n, sizeof(*ctx.state), GFP_KERNEL); + if (!ctx.state) + return -ENOMEM; + + for (i = 0; i < n; i++) { + if (ctx.state[i]) + continue; + ret = t6041_topo_visit(&ctx, nodes[i], 0); + if (ret) + break; + } + + kfree(ctx.state); + if (ret) + return ret; + + if (child_first) { + for (i = 0; i < n / 2; i++) + swap(order[i], order[n - 1 - i]); + } + return 0; +} + +static bool t6041_node_in_list(struct device_node *const *list, unsigned int n, + const struct device_node *np) +{ + unsigned int i; + + for (i = 0; i < n; i++) + if (list[i] == np) + return true; + return false; +} + +struct t6041_restore_acc { + struct device_node **nodes; + void __iomem **regs; + unsigned int count; + struct device_node *const *exclude; + unsigned int n_exclude; +}; + +static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, + bool topo_child_first, + void __iomem ***out_regs, + unsigned int *out_count, + struct t6041_restore_acc *acc) +{ + struct device *dev = r->dev; + struct device_node *np = dev->of_node; + struct device_node **nodes; + void __iomem **regs; + void __iomem **dst; + unsigned int *order = NULL; + unsigned int i, uniq = 0; + int count, ret = 0; + + count = of_count_phandle_with_args(np, prop, NULL); + if (count <= 0) + return dev_err_probe(dev, -EINVAL, "%s: missing or empty phandle list\n", prop); + + nodes = kcalloc(count, sizeof(*nodes), GFP_KERNEL); + regs = kcalloc(count, sizeof(*regs), GFP_KERNEL); + if (!nodes || !regs) { + ret = -ENOMEM; + goto out_free; + } + + for (i = 0; i < count; i++) { + struct device_node *ps_np; + void __iomem *reg; + + ps_np = of_parse_phandle(np, prop, i); + if (!ps_np) { + ret = dev_err_probe(dev, -EINVAL, "%s[%u]: unresolved phandle\n", + prop, i); + goto out_put; + } + if (t6041_node_in_list(nodes, uniq, ps_np)) { + of_node_put(ps_np); + continue; + } + reg = t6041_resolve_ps_node(r, ps_np); + if (IS_ERR(reg)) { + of_node_put(ps_np); + ret = dev_err_probe(dev, PTR_ERR(reg), + "%s[%u]: cannot map PS register\n", prop, i); + goto out_put; + } + nodes[uniq] = ps_np; + regs[uniq] = reg; + uniq++; + } + + dst = devm_kcalloc(dev, uniq, sizeof(*dst), GFP_KERNEL); + if (!dst) { + ret = -ENOMEM; + goto out_put; + } + + if (topo_child_first) { + order = kcalloc(uniq, sizeof(*order), GFP_KERNEL); + if (!order) { + ret = -ENOMEM; + goto out_put; + } + ret = t6041_topo_sort(dev, nodes, uniq, order, true); + if (ret) + goto out_put; + for (i = 0; i < uniq; i++) + dst[i] = regs[order[i]]; + } else { + memcpy(dst, regs, uniq * sizeof(*dst)); + } + + for (i = 0; i < uniq; i++) { + if (t6041_node_in_list(acc->exclude, acc->n_exclude, nodes[i])) + continue; + if (t6041_node_in_list(acc->nodes, acc->count, nodes[i])) + continue; + acc->nodes[acc->count] = of_node_get(nodes[i]); + acc->regs[acc->count] = regs[i]; + acc->count++; + } + + *out_regs = dst; + *out_count = uniq; + +out_put: + kfree(order); + for (i = 0; i < uniq; i++) + of_node_put(nodes[i]); +out_free: + kfree(regs); + kfree(nodes); + return ret; +} + +static int t6041_map_ps_domains(struct t6041_sleep *s) +{ + static const char *const sleep_props[] = { + "apple,sleep-off-domains", + "apple,atc-off-domains", + "apple,sleep-auto-domains", + "apple,sleep-auto-clkgate-domains", + "apple,sleep-auto-active-domains", + "apple,sleep-keep-on-domains", + }; + struct device_node *cpu_cpm_nodes[T6041_CPU_COUNT + T6041_CPM_COUNT] = {}; + struct t6041_ps_resolver r = { .dev = s->dev }; + struct t6041_restore_acc acc = { + .exclude = cpu_cpm_nodes, + .n_exclude = ARRAY_SIZE(cpu_cpm_nodes), + }; + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int *order = NULL; + unsigned int max_restore = 0; + unsigned int i, cpu; + int ret; + + ret = t6041_parse_ps_fixed(&r, "apple,cpu-domains", s->ps_cpu, + cpu_cpm_nodes, T6041_CPU_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,cpm-domains", s->ps_cpm, + cpu_cpm_nodes + T6041_CPU_COUNT, T6041_CPM_COUNT); + if (ret) + goto out; + + for_each_present_cpu(cpu) { + if (t6041_cpu_id(cpu_logical_map(cpu)) >= T6041_CPU_COUNT) { + ret = dev_err_probe(dev, -EINVAL, "CPU %u ID out of range\n", cpu); + goto out; + } + } + + ret = t6041_parse_ps_fixed(&r, "apple,sep-domain", &s->ps_sep, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,spmi-a0-domain", &s->ps_spmi_a0, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-common-domains", s->ps_atc_common, + NULL, AXI2AF_ATC_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-fabric-domain", &s->ps_atc_fabric, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,atc-afi-domain", &s->ps_atc_afi, NULL, 1); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,apcie-domains", s->ps_apcie, + NULL, T6041_APCIE_PS_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,commit-sio-domains", s->ps_commit_sio, + NULL, T6041_COMMIT_SIO_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,commit-periph-domains", s->ps_commit_periph, + NULL, T6041_COMMIT_PERIPH_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,axi2af-domains", s->ps_axi2af, + NULL, AXI2AF_COUNT); + if (ret) + goto out; + ret = t6041_parse_ps_fixed(&r, "apple,full-part-detect-domains", s->ps_full_detect, + NULL, T6041_FULL_DETECT_COUNT); + if (ret) + goto out; + + for (i = 0; i < ARRAY_SIZE(sleep_props); i++) { + int n = of_count_phandle_with_args(np, sleep_props[i], NULL); + + if (n <= 0) { + ret = dev_err_probe(dev, -EINVAL, + "%s: missing or empty phandle list\n", + sleep_props[i]); + goto out; + } + max_restore += n; + } + + acc.nodes = kcalloc(max_restore, sizeof(*acc.nodes), GFP_KERNEL); + acc.regs = kcalloc(max_restore, sizeof(*acc.regs), GFP_KERNEL); + if (!acc.nodes || !acc.regs) { + ret = -ENOMEM; + goto out; + } + + /* + * Accumulate restore domains fabric- and controller-first before leaf + * and peripheral lists so hardware parents without DT power-domains + * edges (e.g. disabled AMCCs above auto-managed DCS nodes, or fab* + * fabrics above ATC/media blocks) are still ordered parent-first in + * ps_restore. + */ + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-domains", false, + &s->ps_auto, &s->n_auto, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-active-domains", false, + &s->ps_auto_active, &s->n_auto_active, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-auto-clkgate-domains", false, + &s->ps_auto_clkgate, &s->n_auto_clkgate, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-keep-on-domains", false, + &s->ps_keep_on, &s->n_keep_on, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,atc-off-domains", false, + &s->ps_atc_off, &s->n_atc_off, &acc); + if (ret) + goto out; + ret = t6041_parse_ps_list(&r, "apple,sleep-off-domains", true, + &s->ps_off, &s->n_off, &acc); + if (ret) + goto out; + + order = kcalloc(acc.count, sizeof(*order), GFP_KERNEL); + s->ps_restore = devm_kcalloc(dev, acc.count, sizeof(*s->ps_restore), GFP_KERNEL); + s->ps_pre = devm_kcalloc(dev, acc.count, sizeof(*s->ps_pre), GFP_KERNEL); + if (!order || !s->ps_restore || !s->ps_pre) { + ret = -ENOMEM; + goto out; + } + + ret = t6041_topo_sort(dev, acc.nodes, acc.count, order, false); + if (ret) + goto out; + + for (i = 0; i < acc.count; i++) + s->ps_restore[i] = acc.regs[order[i]]; + s->n_restore = acc.count; + +out: + kfree(order); + for (i = 0; i < acc.count; i++) + of_node_put(acc.nodes[i]); + kfree(acc.regs); + kfree(acc.nodes); + for (i = 0; i < ARRAY_SIZE(cpu_cpm_nodes); i++) + of_node_put(cpu_cpm_nodes[i]); + t6041_ps_resolver_cleanup(&r); + return ret; +} + +static struct apple_tunable *t6041_apcie_tunable(struct device *dev, + struct device_node *np, + const char *reg_name, + const char *prop) +{ + int idx = of_property_match_string(np, "reg-names", reg_name); + struct apple_tunable *t; + struct resource res; + + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return NULL; + t = devm_apple_tunable_parse(dev, np, prop, &res); + return IS_ERR(t) ? NULL : t; +} + +static void __iomem *t6041_apcie_block(struct device *dev, struct device_node *np, + const char *reg_name, resource_size_t min_size, + const char *prop, struct apple_tunable **tunable) +{ + void __iomem *base; + + if (prop) { + *tunable = t6041_apcie_tunable(dev, np, reg_name, prop); + if (!*tunable) + return NULL; + } + base = t6041_map_name(dev, np, reg_name, min_size, NULL); + return IS_ERR(base) ? NULL : base; +} + +static void t6041_map_apcie(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np; + + np = of_parse_phandle(dev->of_node, "apple,apcie", 0); + if (!np) + return; + + s->ap_rc = t6041_apcie_block(dev, np, "rc", 0x5c, NULL, NULL); + s->ap_axi = t6041_apcie_block(dev, np, "axi2af", 0x110, + "apple,tunable-axi2af", &s->tun_axi2af); + s->ap_cio3pll = t6041_apcie_block(dev, np, "cio3pll", 0x4, + "apple,tunable-cio3pll", &s->tun_cio3pll); + s->ap_clkgen = t6041_apcie_block(dev, np, "clkgen", 0x8, + "apple,tunable-clkgen", &s->tun_clkgen); + s->ap_phy = t6041_apcie_block(dev, np, "phy-block", 0x800c, + "apple,tunable-phy", &s->tun_phy); + s->ap_phy_ip = t6041_apcie_block(dev, np, "phy-ip", 0x94, + "apple,tunable-phy-ip-pll", &s->tun_phy_ip_pll); + s->tun_phy_ip_lanes = t6041_apcie_tunable(dev, np, "phy-ip", + "apple,tunable-phy-ip-auspma"); + s->gp_port[0] = t6041_apcie_block(dev, np, "port0", 0x830, NULL, NULL); + s->gp_port[1] = t6041_apcie_block(dev, np, "port1", 0x830, NULL, NULL); + s->gp_phy[0] = t6041_apcie_block(dev, np, "phy0", 0x4, NULL, NULL); + s->gp_phy[1] = t6041_apcie_block(dev, np, "phy1", 0x4, NULL, NULL); + of_node_put(np); + + if (s->ap_axi) + s->axi2af[AXI2AF_APCIE] = s->ap_axi + 0x100; + + if (s->ap_rc && s->ap_axi && s->ap_cio3pll && s->ap_clkgen && + s->ap_phy && s->ap_phy_ip && s->tun_phy_ip_lanes && + s->gp_port[0] && s->gp_port[1] && s->gp_phy[0] && s->gp_phy[1]) + s->apcie_ready = true; +} + +static int t6041_map_pinctrl(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + struct device_node *pin_np; + void __iomem *base; + u32 npins, pin; + int i, n; + + pin_np = of_parse_phandle(np, "apple,pinctrl", 0); + if (!pin_np) + return dev_err_probe(dev, -EINVAL, "missing apple,pinctrl\n"); + if (of_property_read_u32(pin_np, "apple,npins", &npins) || !npins || npins > 512) { + of_node_put(pin_np); + return dev_err_probe(dev, -EINVAL, "invalid apple,npins on pinctrl\n"); + } + base = t6041_map_idx(dev, pin_np, 0, (resource_size_t)npins * 4, NULL); + of_node_put(pin_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,pinctrl\n"); + + s->gpio_pre = devm_kcalloc(dev, npins, sizeof(*s->gpio_pre), GFP_KERNEL); + s->gpio_skip = devm_bitmap_zalloc(dev, npins, GFP_KERNEL); + if (!s->gpio_pre || !s->gpio_skip) + return -ENOMEM; + + n = of_property_count_u32_elems(np, "apple,pinctrl-skip-pins"); + for (i = 0; i < n; i++) + if (!of_property_read_u32_index(np, "apple,pinctrl-skip-pins", i, &pin) && + pin < npins) + set_bit(pin, s->gpio_skip); + + s->gpio = base; + s->npins = npins; + return 0; +} + +static int t6041_map_spmi(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + struct device_node *bus_np; + void __iomem *base; + + bus_np = of_parse_phandle(np, "apple,spmi-buses", 0); + if (!bus_np) + return dev_err_probe(dev, -EINVAL, "missing apple,spmi-buses[0]\n"); + base = t6041_map_idx(dev, bus_np, 0, 0x84, NULL); + of_node_put(bus_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,spmi-buses[0]\n"); + s->spmi = base; + + bus_np = of_parse_phandle(np, "apple,spmi-buses", 1); + if (!bus_np) + return dev_err_probe(dev, -EINVAL, "missing apple,spmi-buses[1]\n"); + base = t6041_map_idx(dev, bus_np, 0, 0x84, NULL); + of_node_put(bus_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map apple,spmi-buses[1]\n"); + s->spmi_a0 = base; + return 0; +} + +static int t6041_map_axi2af(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int i; + + for (i = 0; i < AXI2AF_ATC_COUNT; i++) { + struct device_node *phy_np; + void __iomem *base; + + phy_np = of_parse_phandle(np, "apple,atc-phys", i); + if (!phy_np) + return dev_err_probe(dev, -EINVAL, "missing apple,atc-phys[%u]\n", i); + base = t6041_map_name(dev, phy_np, "axi2af", 0x110, NULL); + of_node_put(phy_np); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), + "cannot map axi2af on apple,atc-phys[%u]\n", i); + s->axi2af[i] = base + 0x100; + } + + for (i = 0; i < AXI2AF_REG_COUNT; i++) { + void __iomem *base = t6041_map_name(dev, np, t6041_axi2af_names[i], 0xc, NULL); + + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", + t6041_axi2af_names[i]); + s->axi2af[AXI2AF_ATC_COUNT + i] = base; + } + return 0; +} + +static int t6041_map_mcc(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + struct device_node *np = dev->of_node; + unsigned int g, p; + + for (g = 0; g < s->ngroups; g++) { + char name[16]; + struct resource res; + void __iomem *base; + int idx; + + snprintf(name, sizeof(name), "amcc%u", g); + base = t6041_map_name(dev, np, name, AMCC_MIN_SIZE, NULL); + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", name); + s->amccb[g] = base; + + snprintf(name, sizeof(name), "dcs%u", g); + idx = of_property_match_string(np, "reg-names", name); + if (idx < 0 || of_address_to_resource(np, idx, &res)) + return dev_err_probe(dev, -EINVAL, "missing %s\n", name); + for (p = 0; p < 4; p++) { + resource_size_t off = (resource_size_t)p * DCS_CH_STRIDE; + + if (off + DCS_CH_SIZE > resource_size(&res)) + return dev_err_probe(dev, -EINVAL, "%s too small\n", name); + s->dcs[4 * g + p] = devm_ioremap(dev, res.start + off, DCS_CH_SIZE); + if (!s->dcs[4 * g + p]) + return -ENOMEM; + } + } + return 0; +} + +static int t6041_parse_wake_sources(struct t6041_sleep *s) +{ + struct device *dev = s->dev; + u32 ids[WAKE_SOURCES_MAX]; + int i, n; + + n = of_property_read_variable_u32_array(dev->of_node, "apple,wake-enable", + ids, 1, WAKE_SOURCES_MAX); + if (n < 0) + return dev_err_probe(dev, n, "missing apple,wake-enable\n"); + + for (i = 0; i < WAKE_WORDS - 1; i++) + s->wake_masks[i] = U32_MAX; + s->wake_masks[WAKE_WORDS - 1] = WAKE_LAST_MASK; + + for (i = 0; i < n; i++) { + if (ids[i] >= WAKE_MAX_ID) + return dev_err_probe(dev, -EINVAL, + "wake source %u out of range\n", ids[i]); + s->wake_masks[ids[i] / 32] &= ~BIT(ids[i] % 32); + } + return 0; +} + +static const struct { + const char *name; + size_t field; + resource_size_t min_size; +} t6041_core_regs[] = { + { "ps-aop", offsetof(struct t6041_sleep, aop_ps), 8 * AOP_PS_WORDS }, + { "cluster", offsetof(struct t6041_sleep, cluster), 0x14 }, + { "pwrgate", offsetof(struct t6041_sleep, pwrgate), 0x114 }, + { "cpu-start", offsetof(struct t6041_sleep, misc), 0x14 }, + { "wdt", offsetof(struct t6041_sleep, wdt), 0x30 }, + { "aon-misc", offsetof(struct t6041_sleep, aon), 0xc }, + { "commit", offsetof(struct t6041_sleep, commit), 0x4 }, + { "clk-mux", offsetof(struct t6041_sleep, clkgen), 0x68 }, + { "ka-pmgr", offsetof(struct t6041_sleep, ka[0]), KA_WORDS * KA_STRIDE }, + { "ka-east", offsetof(struct t6041_sleep, ka[1]), KA_WORDS * KA_STRIDE }, + { "pmc", offsetof(struct t6041_sleep, pmc), 0xac02c }, + { "ptd", offsetof(struct t6041_sleep, ptd), PTD_MIN_SIZE }, + { "perf", offsetof(struct t6041_sleep, perf), 0x404 }, + { "wake", offsetof(struct t6041_sleep, wake), 0xc + 4 * WAKE_WORDS }, +}; + +static int t6041_sleep_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct t6041_sleep *s; + unsigned int i; + u64 pa; + int ret; + + if (!is_kernel_in_hyp_mode()) + return -ENODEV; + + s = devm_kzalloc(dev, sizeof(*s), GFP_KERNEL); + if (!s) + return -ENOMEM; + s->dev = dev; + + if (!of_property_read_u64(of_chosen, "aurora,s2r-mailbox", &pa)) { + s->mbox = devm_memremap(dev, pa, sizeof(*s->mbox), MEMREMAP_WB); + if (IS_ERR(s->mbox) || READ_ONCE(s->mbox->magic) != T6041_S2R_MAGIC) + s->mbox = NULL; + } + /* With no way back, a sleep would end in aura's boot flow over this kernel. */ + if (!s->mbox) { + dev_info(dev, "no aura S2R mailbox: no deep sleep\n"); + return -ENODEV; + } + + for (i = 0; i < ARRAY_SIZE(t6041_core_regs); i++) { + void __iomem *base = t6041_map_name(dev, np, t6041_core_regs[i].name, + t6041_core_regs[i].min_size, NULL); + + if (IS_ERR(base)) + return dev_err_probe(dev, PTR_ERR(base), "cannot map %s\n", + t6041_core_regs[i].name); + *(void __iomem **)((char *)s + t6041_core_regs[i].field) = base; + } + + ret = t6041_map_ps_domains(s); + if (ret) + return ret; + ret = t6041_parse_wake_sources(s); + if (ret) + return ret; + ret = t6041_map_spmi(s); + if (ret) + return ret; + ret = t6041_map_axi2af(s); + if (ret) + return ret; + ret = t6041_map_pinctrl(s); + if (ret) + return ret; + + /* + * The full part: the two full-part detect words (amcc24, amcc28) are + * not both target and actual 0 as on the binned part, where those + * channels are fused off. + */ + s->ngroups = (readl(s->ps_full_detect[0]) & (PS_TARGET | PS_ACTUAL)) && + (readl(s->ps_full_detect[1]) & (PS_TARGET | PS_ACTUAL)) ? 8 : 6; + dev_info(dev, "%u memory channels\n", 4 * s->ngroups); + + ret = t6041_map_mcc(s); + if (ret) + return ret; + + t6041_map_apcie(s); + if (!s->apcie_ready) { + dev_info(dev, "no PCIe tunables for ANS: no deep sleep\n"); + return -ENODEV; + } + + t6041_sleep = s; + ret = spin_table_set_power_ops(&t6041_cpu_power_ops); + if (ret) { + t6041_sleep = NULL; + return dev_err_probe(dev, ret, "cannot control CPU power\n"); + } + apple_sleep_set_commit_stops_coprocs(true); + suspend_set_ops(&t6041_sleep_ops); + dev_info(dev, "T6041 deep sleep at EL2 through aura's S2R mailbox\n"); + return 0; +} + +static const struct of_device_id t6041_sleep_of_match[] = { + { .compatible = "apple,t6041-sleep" }, + { } +}; + +static struct platform_driver t6041_sleep_driver = { + .driver = { + .name = "t6041-sleep", + .of_match_table = t6041_sleep_of_match, + .suppress_bind_attrs = true, + }, + .probe = t6041_sleep_probe, +}; +builtin_platform_driver(t6041_sleep_driver); From 38bb7723cc9b37716b37383f54556f9513b55e42 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 14:28:56 +0000 Subject: [PATCH 1232/1514] arm64: dts: apple: t6041: wire sleep controller, PMGR domains, and display-power Wire suspend-to-RAM in the T6041 SoC and J614c/J616c board device trees: - Add pmgr_disp, t6041-sleep-pmgr.dtsi (keeping newly added firmware-owned power-state nodes disabled), SEP DART sleep-prepare/restore lists, and the ps_venc1_sys -> ps_fab0_soc parent link in t6041.dtsi. - Add the t6041_sleep node in t6041.dtsi (disabled at SoC level so boards without qualified deep sleep such as J575c remain on s2idle) with all DT reg windows, wake sources, and PMGR domain phandle lists (including apple,atc-off-domains). - On t6041-j614c-j616c.dtsi, add the dcp_power node, wire apple,sleep-host-stop and apple,display-power on &dcp, apple,sleep-wake-type and apple,sleep-pmvc = <0x101> (VDD_CIO bit 8 + port 0 bit 0) on &smc, the shared APCIe storage/PHY reg windows on &pcie0, and enable &t6041_sleep. Signed-off-by: AxxzyWasTaken --- .../boot/dts/apple/t6041-j614c-j616c.dtsi | 152 +- .../boot/dts/apple/t6041-sleep-pmgr.dtsi | 1849 +++++++++++++++++ arch/arm64/boot/dts/apple/t6041.dtsi | 195 ++ 3 files changed, 2157 insertions(+), 39 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index 6c88428a48ba50..f48c73e04176f8 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -33,6 +33,85 @@ sep = &sep; }; + /* + * Display power words and PMGR chains the DCP driver writes around + * suspend-to-RAM. The windows belong to PMC, PMGR, GAPF and AXI2AF; + * no driver binds this. + */ + dcp_power: display-power@5048a9c14 { + compatible = "apple,t6041-display-power"; + reg = <0x5 0x048a9c14 0x0 0x8>, + <0x5 0x022a1000 0x0 0x100>, + <0x5 0x0282d000 0x0 0x1000>, + <0x5 0x00578000 0x0 0x1000>, + <0x4 0x03000100 0x0 0x10>; + reg-names = "pmc-dcp", "pwrgate", "pwrgate-aux", "gapf", "axi2af"; + #address-cells = <1>; + #size-cells = <0>; + + chain@0 { + reg = <0>; + label = "ext3"; + apple,pwrgate-aux; + apple,gapf-offset = <0x740>; + apple,pwrgate-offsets = <0xfb4 0xfd8>; + power-domains = <&ps_dispext3_sys>, <&ps_dispext3_fe>, <&ps_dispext3_cpu>, + <&ps_dispext3_dbe>, <&ps_dpext3>, <&ps_dispext3_gp0>, + <&ps_dispext3_gp1>, <&ps_dispext3_gpl>, <&ps_dispext3_ppp>, + <&ps_dispext3_dsc>; + }; + + chain@1 { + reg = <1>; + label = "ext2"; + apple,pwrgate-aux; + apple,gapf-offset = <0xd80>; + apple,pwrgate-offsets = <0xb34 0xb58>; + power-domains = <&ps_dispext2_sys>, <&ps_dispext2_fe>, <&ps_dispext2_cpu>, + <&ps_dispext2_dbe>, <&ps_dpext2>, <&ps_dispext2_gp0>, + <&ps_dispext2_gp1>, <&ps_dispext2_gpl>, <&ps_dispext2_ppp>, + <&ps_dispext2_dsc>; + }; + + chain@2 { + reg = <2>; + label = "ext1"; + apple,pwrgate-aux; + apple,gapf-offset = <0xd00>; + apple,pwrgate-offsets = <0x6b4 0x6d8>; + power-domains = <&ps_dispext1_sys>, <&ps_dispext1_fe>, <&ps_dispext1_cpu>, + <&ps_dispext1_dbe>, <&ps_dpext1>, <&ps_dispext1_gp0>, + <&ps_dispext1_gp1>, <&ps_dispext1_gpl>, <&ps_dispext1_ppp>, + <&ps_dispext1_dsc>; + }; + + chain@3 { + reg = <3>; + label = "ext0"; + apple,pwrgate-aux; + apple,gapf-offset = <0x840>; + apple,pwrgate-offsets = <0x234 0x258>; + power-domains = <&ps_dispext0_sys>, <&ps_dispext0_fe>, <&ps_dispext0_cpu>, + <&ps_dispext0_dbe>, <&ps_dpext0>, <&ps_dispext0_gp0>, + <&ps_dispext0_gp1>, <&ps_dispext0_gpl>, <&ps_dispext0_ppp>, + <&ps_dispext0_dsc>; + }; + + chain@4 { + reg = <4>; + label = "main"; + apple,main-chain; + apple,gapf-offset = <0x540>; + apple,pwrgate-offsets = <0x1c 0x60>; + apple,fabric-domain = <&ps_fab6_soc>; + power-domains = <&ps_disp_sys>, <&ps_disp_fe>, <&ps_disp_cpu>, + <&ps_disp_spi>, <&ps_disp_spmi>, <&ps_disp_dbe>, + <&ps_disp_dp>, <&ps_disp_gp0>, <&ps_disp_gp1>, + <&ps_disp_gpl>, <&ps_disp_cmb>, <&ps_disp_ppp>, + <&ps_disp_brc>, <&ps_disp_blc>; + }; + }; + chosen { #address-cells = <2>; #size-cells = <2>; @@ -1197,6 +1276,9 @@ }; &smc { + apple,sleep-wake-type; + /* VDD_CIO mask: bit 8 + bit 0 keeps port 0 powered for atc0_common at commit. */ + apple,sleep-pmvc = <0x101>; status = "okay"; smc_gpio_low: gpio-low { @@ -1652,10 +1734,17 @@ <0x4 0x17020000 0x0 0x4000>, <0x4 0x17024000 0x0 0x4000>, <0x4 0x17028000 0x0 0x4000>, - <0x4 0x1702c000 0x0 0x4000>; + <0x4 0x1702c000 0x0 0x4000>, + <0x4 0x16000000 0x0 0x1000000>, + <0x4 0x15046200 0x0 0x4000>, + <0x4 0x15044000 0x0 0x4000>, + <0x4 0x17000000 0x0 0x40000>, + <0x4 0x17040000 0x0 0x28000>; reg-names = "config", "rc", "port0", "port1", "port2", "port3", - "phy0", "phy1", "phy2", "phy3"; + "phy0", "phy1", "phy2", "phy3", + "axi2af", "cio3pll", "clkgen", + "phy-block", "phy-ip"; ranges = <0x43000000 0xb 0xc0000000 0xb 0xc0000000 0x0 0x20000000>, <0x02000000 0x0 0x80000000 0xb 0x80000000 0x0 0x40000000>; pinctrl-names = "default"; @@ -1756,7 +1845,15 @@ phandle = <&display>; }; +&t6041_sleep { + apple,apcie = <&pcie0>; + apple,atc-phys = <&atcphy0>, <&atcphy1>, <&atcphy2>, <&atcphy3>; + status = "okay"; +}; + &dcp { + apple,sleep-host-stop; + apple,display-power = <&dcp_power>; clocks = <&clk_disp0>; phandle = <&dcp>; @@ -2754,43 +2851,20 @@ * under DPA_P. The SIO stays disabled here: the loader enables it once it has * reserved the firmware iBoot loaded (it finds it by the alias). */ -&pmgr { - ps_uart_p: power-controller@1a0 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a0 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "uart_p"; - power-domains = <&ps_sio>; - }; - - ps_dpa_p: power-controller@1a8 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x1a8 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa_p"; - power-domains = <&ps_sio>; - apple,always-on; - }; - - ps_dpa1: power-controller@238 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x238 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa1"; - power-domains = <&ps_dpa_p>; - }; - - ps_dpa2: power-controller@240 { - compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; - reg = <0x240 4>; - #power-domain-cells = <0>; - #reset-cells = <0>; - label = "dpa2"; - power-domains = <&ps_dpa_p>; - }; +&ps_uart_p { + status = "okay"; +}; + +&ps_dpa_p { + status = "okay"; +}; + +&ps_dpa1 { + status = "okay"; +}; + +&ps_dpa2 { + status = "okay"; }; / { diff --git a/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi new file mode 100644 index 00000000000000..ace9854564b2c1 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi @@ -0,0 +1,1849 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Additional Apple T6041 ("M4 Max") PMGR power states used by suspend-to-RAM + * and display power-domain chains, beyond the nodes already described in + * t6041.dtsi, t604x-pmgr.dtsi, t6041-pmgr.dtsi (hardware auto-managed + * DCS/fabrics) and t6041-j614-j616-j575-scaler.dtsi. + * + * Offsets and parent links are verified against the J616c ADT (/arm-io/pmgr + * devices and ps-groups). Every newly added node stays disabled so + * apple-pmgr-pwrstate never probes or powers down firmware-owned blocks; + * boards enable nodes that have Linux consumers (such as ps_uart_p, ps_dpa_p, + * ps_dpa1 and ps_dpa2 on J614c/J616c). + * + * Copyright The Asahi Linux Contributors + */ + +&pmgr { + ps_apcie_gp: power-controller@100 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x100 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_gp"; + status = "disabled"; + }; + + ps_fpwm1: power-controller@140 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fpwm1"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_fpwm2: power-controller@148 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x148 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "fpwm2"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c0: power-controller@150 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x150 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c0"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c5: power-controller@178 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x178 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c5"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_i2c7: power-controller@188 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x188 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "i2c7"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_uart_p: power-controller@1a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart_p"; + power-domains = <&ps_sio>; + status = "disabled"; + }; + + ps_dpa_p: power-controller@1a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa_p"; + power-domains = <&ps_sio>; + apple,always-on; + status = "disabled"; + }; + + ps_spi0: power-controller@1b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi0"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi1: power-controller@1c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi1"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi3: power-controller@1d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi3"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi4: power-controller@1d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi4"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_spi5: power-controller@1e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "spi5"; + power-domains = <&ps_spi_p>; + status = "disabled"; + }; + + ps_uart_n: power-controller@1f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart_n"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart0: power-controller@1f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart0"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart1: power-controller@200 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x200 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart1"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart2: power-controller@208 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x208 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart2"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart3: power-controller@210 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x210 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart3"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart4: power-controller@218 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x218 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart4"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart5: power-controller@220 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x220 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart5"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_uart6: power-controller@228 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x228 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "uart6"; + power-domains = <&ps_uart_p>; + status = "disabled"; + }; + + ps_dpa0: power-controller@230 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x230 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa0"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa1: power-controller@238 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x238 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa1"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa2: power-controller@240 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x240 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa2"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa3: power-controller@248 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x248 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa3"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_dpa4: power-controller@250 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x250 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpa4"; + power-domains = <&ps_dpa_p>; + status = "disabled"; + }; + + ps_disp_sys: power-controller@258 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x258 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_sys"; + power-domains = <&ps_fab6_soc>; + status = "disabled"; + }; + + ps_amcc4: power-controller@260 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x260 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc4"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc5: power-controller@268 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x268 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc5"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc6: power-controller@270 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x270 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc6"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc7: power-controller@278 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x278 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc7"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc12: power-controller@280 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x280 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc12"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc13: power-controller@288 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x288 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc13"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc14: power-controller@290 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x290 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc14"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc15: power-controller@298 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x298 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc15"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc20: power-controller@2a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc20"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc21: power-controller@2a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc21"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc22: power-controller@2b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc22"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc23: power-controller@2b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc23"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc28: power-controller@2c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc28"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc29: power-controller@2c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc29"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc30: power-controller@2d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc30"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc31: power-controller@2d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc31"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_disp_fe: power-controller@368 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x368 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_fe"; + power-domains = <&ps_disp_sys>; + status = "disabled"; + }; + + ps_apcie_sys_gp: power-controller@390 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x390 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_sys_gp"; + power-domains = <&ps_fab3_soc>, <&ps_apcie_gp>; + status = "disabled"; + }; + + ps_apcie_phy_sw: power-controller@398 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x398 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "apcie_phy_sw"; + power-domains = <&ps_apcie_sys_st0>, <&ps_apcie_sys_st1>; + status = "disabled"; + }; + + ps_prores: power-controller@3a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "prores"; + power-domains = <&ps_fab6_soc>; + status = "disabled"; + }; +}; + +&pmgr_disp { + ps_disp_cpu: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cpu"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_spi: power-controller@8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_spi"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_spmi: power-controller@10 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x10 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_spmi"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_dbe: power-controller@18 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x18 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_dbe"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_dp: power-controller@20 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dp"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gp0: power-controller@28 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x28 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gp0"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gp1: power-controller@30 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x30 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gp1"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_gpl: power-controller@38 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x38 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_gpl"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_cmb: power-controller@40 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_cmb"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_ppp: power-controller@48 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x48 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_ppp"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_brc: power-controller@50 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x50 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_brc"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; + + ps_disp_blc: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "disp_blc"; + power-domains = <&ps_disp_fe>; + status = "disabled"; + }; +}; + +&pmgr_aux { + ps_ecpu_0: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_0"; + status = "disabled"; + }; + + ps_ecpu_1: power-controller@8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_1"; + status = "disabled"; + }; + + ps_ecpu_2: power-controller@10 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x10 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_2"; + status = "disabled"; + }; + + ps_ecpu_3: power-controller@18 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x18 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpu_3"; + status = "disabled"; + }; + + ps_pcpu0_0: power-controller@20 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x20 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_0"; + status = "disabled"; + }; + + ps_pcpu0_1: power-controller@28 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x28 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_1"; + status = "disabled"; + }; + + ps_pcpu0_2: power-controller@30 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x30 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_2"; + status = "disabled"; + }; + + ps_pcpu0_3: power-controller@38 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x38 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_3"; + status = "disabled"; + }; + + ps_pcpu0_4: power-controller@40 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x40 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_4"; + status = "disabled"; + }; + + ps_pcpu0_5: power-controller@48 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x48 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu0_5"; + status = "disabled"; + }; + + ps_pcpu1_0: power-controller@50 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x50 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_0"; + status = "disabled"; + }; + + ps_pcpu1_1: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_1"; + status = "disabled"; + }; + + ps_pcpu1_2: power-controller@60 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_2"; + status = "disabled"; + }; + + ps_pcpu1_3: power-controller@68 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x68 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_3"; + status = "disabled"; + }; + + ps_pcpu1_4: power-controller@70 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x70 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_4"; + status = "disabled"; + }; + + ps_pcpu1_5: power-controller@78 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x78 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpu1_5"; + status = "disabled"; + }; + + ps_ecpm: power-controller@80 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ecpm"; + status = "disabled"; + }; + + ps_pcpm0: power-controller@88 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x88 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpm0"; + status = "disabled"; + }; + + ps_pcpm1: power-controller@90 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x90 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pcpm1"; + status = "disabled"; + }; + + ps_dwi: power-controller@108 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x108 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dwi"; + status = "disabled"; + }; + + ps_aic: power-controller@118 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x118 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "aic"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pmc: power-controller@120 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x120 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pmc"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_c1ppt: power-controller@128 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x128 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_c1ppt"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_soc_dpe: power-controller@130 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x130 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "soc_dpe"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pmgr_soc_ocla: power-controller@138 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x138 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pmgr_soc_ocla"; + status = "disabled"; + }; + + ps_pms_fpwm0: power-controller@140 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x140 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm0"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm1: power-controller@148 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x148 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm1"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm2: power-controller@150 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x150 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm2"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm3: power-controller@158 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x158 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm3"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_pms_fpwm4: power-controller@160 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x160 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "pms_fpwm4"; + power-domains = <&ps_pms>; + status = "disabled"; + }; + + ps_amcc0: power-controller@180 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x180 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc0"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_rom: power-controller@190 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x190 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "rom"; + power-domains = <&ps_amcc0>; + status = "disabled"; + }; + + ps_amcc1: power-controller@198 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x198 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc1"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc2: power-controller@1a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc2"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc3: power-controller@1b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc3"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc8: power-controller@1c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc8"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc9: power-controller@1d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc9"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc10: power-controller@1e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc10"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc11: power-controller@1f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x1f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc11"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc16: power-controller@208 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x208 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc16"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc17: power-controller@218 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x218 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc17"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc18: power-controller@228 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x228 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc18"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc19: power-controller@238 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x238 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc19"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc24: power-controller@248 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x248 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc24"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc25: power-controller@258 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x258 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc25"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc26: power-controller@268 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x268 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc26"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_amcc27: power-controller@280 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x280 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "amcc27"; + power-domains = <&ps_afc>; + status = "disabled"; + }; + + ps_dispext3_sys: power-controller@2d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_sys"; + power-domains = <&ps_fab1_soc>; + status = "disabled"; + }; + + ps_dispext3_fe: power-controller@2e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_fe"; + power-domains = <&ps_dispext3_sys>; + status = "disabled"; + }; + + ps_dispext3_cpu: power-controller@2e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_cpu"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_dbe: power-controller@2f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_dbe"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dpext3: power-controller@2f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x2f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext3"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gp0: power-controller@300 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x300 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gp0"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gp1: power-controller@308 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x308 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gp1"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_gpl: power-controller@310 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x310 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_gpl"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_ppp: power-controller@318 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x318 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_ppp"; + power-domains = <&ps_dispext3_fe>; + status = "disabled"; + }; + + ps_dispext3_dsc: power-controller@320 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x320 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext3_dsc"; + power-domains = <&ps_dispext3_dbe>; + status = "disabled"; + }; + + ps_dispext0_sys: power-controller@340 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x340 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_sys"; + power-domains = <&ps_fab2_soc>; + status = "disabled"; + }; + + ps_dispext0_fe: power-controller@348 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x348 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_fe"; + power-domains = <&ps_dispext0_sys>; + status = "disabled"; + }; + + ps_dispext0_cpu: power-controller@350 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x350 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_cpu"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_dbe: power-controller@358 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x358 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_dbe"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dpext0: power-controller@360 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x360 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext0"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gp0: power-controller@368 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x368 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gp0"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gp1: power-controller@370 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x370 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gp1"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_gpl: power-controller@378 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x378 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_gpl"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_ppp: power-controller@380 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x380 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_ppp"; + power-domains = <&ps_dispext0_fe>; + status = "disabled"; + }; + + ps_dispext0_dsc: power-controller@388 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x388 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext0_dsc"; + power-domains = <&ps_dispext0_dbe>; + status = "disabled"; + }; + + ps_atc0_cio: power-controller@398 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x398 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio"; + power-domains = <&ps_atc0_common>; + status = "disabled"; + }; + + ps_atc0_pcie: power-controller@3a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_pcie"; + power-domains = <&ps_atc0_common>; + status = "disabled"; + }; + + ps_atc0_cio_pcie: power-controller@3a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio_pcie"; + power-domains = <&ps_atc0_cio>; + status = "disabled"; + }; + + ps_atc0_cio_usb: power-controller@3b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc0_cio_usb"; + power-domains = <&ps_atc0_cio>; + status = "disabled"; + }; + + ps_atc1_cio: power-controller@3c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio"; + power-domains = <&ps_atc1_common>; + status = "disabled"; + }; + + ps_atc1_pcie: power-controller@3c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_pcie"; + power-domains = <&ps_atc1_common>; + status = "disabled"; + }; + + ps_atc1_cio_pcie: power-controller@3d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio_pcie"; + power-domains = <&ps_atc1_cio>; + status = "disabled"; + }; + + ps_atc1_cio_usb: power-controller@3d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc1_cio_usb"; + power-domains = <&ps_atc1_cio>; + status = "disabled"; + }; + + ps_atc2_cio: power-controller@3e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio"; + power-domains = <&ps_atc2_common>; + status = "disabled"; + }; + + ps_atc2_pcie: power-controller@3f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_pcie"; + power-domains = <&ps_atc2_common>; + status = "disabled"; + }; + + ps_atc2_cio_pcie: power-controller@3f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x3f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio_pcie"; + power-domains = <&ps_atc2_cio>; + status = "disabled"; + }; + + ps_atc2_cio_usb: power-controller@400 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x400 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc2_cio_usb"; + power-domains = <&ps_atc2_cio>; + status = "disabled"; + }; + + ps_atc3_cio: power-controller@420 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x420 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio"; + power-domains = <&ps_atc3_common>; + status = "disabled"; + }; + + ps_atc3_pcie: power-controller@428 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x428 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_pcie"; + power-domains = <&ps_atc3_common>; + status = "disabled"; + }; + + ps_atc3_cio_pcie: power-controller@430 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x430 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio_pcie"; + power-domains = <&ps_atc3_cio>; + status = "disabled"; + }; + + ps_atc3_cio_usb: power-controller@438 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x438 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "atc3_cio_usb"; + power-domains = <&ps_atc3_cio>; + status = "disabled"; + }; + + ps_sbr: power-controller@448 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x448 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "sbr"; + power-domains = <&ps_fab5_soc>; + status = "disabled"; + }; + + ps_gpio: power-controller@450 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x450 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpio"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_msg: power-controller@458 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x458 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "msg"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_ap_tmm: power-controller@468 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x468 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "ap_tmm"; + power-domains = <&ps_sbr>; + status = "disabled"; + }; + + ps_dispext1_sys: power-controller@490 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x490 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_sys"; + power-domains = <&ps_fab7_soc>; + status = "disabled"; + }; + + ps_dispext1_fe: power-controller@498 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x498 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_fe"; + power-domains = <&ps_dispext1_sys>; + status = "disabled"; + }; + + ps_dispext1_cpu: power-controller@4a0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4a0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_cpu"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_dbe: power-controller@4a8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4a8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_dbe"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dpext1: power-controller@4b0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4b0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext1"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gp0: power-controller@4b8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4b8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gp0"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gp1: power-controller@4c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4c0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gp1"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_gpl: power-controller@4c8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4c8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_gpl"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_ppp: power-controller@4d0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_ppp"; + power-domains = <&ps_dispext1_fe>; + status = "disabled"; + }; + + ps_dispext1_dsc: power-controller@4d8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4d8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext1_dsc"; + power-domains = <&ps_dispext1_dbe>; + status = "disabled"; + }; + + ps_dispext2_sys: power-controller@4e0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_sys"; + power-domains = <&ps_fab7_soc>; + status = "disabled"; + }; + + ps_dispext2_fe: power-controller@4e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4e8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_fe"; + power-domains = <&ps_dispext2_sys>; + status = "disabled"; + }; + + ps_dispext2_cpu: power-controller@4f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_cpu"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_dbe: power-controller@4f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x4f8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_dbe"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dpext2: power-controller@500 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x500 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dpext2"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gp0: power-controller@508 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x508 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gp0"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gp1: power-controller@510 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x510 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gp1"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_gpl: power-controller@518 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x518 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_gpl"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_ppp: power-controller@520 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x520 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_ppp"; + power-domains = <&ps_dispext2_fe>; + status = "disabled"; + }; + + ps_dispext2_dsc: power-controller@528 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x528 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "dispext2_dsc"; + power-domains = <&ps_dispext2_dbe>; + status = "disabled"; + }; +}; + +&pmgr_mini { + ps_debug_gated: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "debug_gated"; + status = "disabled"; + }; + + ps_nub_spmi_ahb: power-controller@58 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x58 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi_ahb"; + status = "disabled"; + }; + + ps_nub_spmi0: power-controller@60 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x60 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi0"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi_a2: power-controller@78 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x78 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi_a2"; + status = "disabled"; + }; + + ps_nub_spi0: power-controller@80 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x80 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spi0"; + status = "disabled"; + }; + + ps_nub_aon: power-controller@88 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x88 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_aon"; + status = "disabled"; + }; + + ps_nub_ocla: power-controller@98 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x98 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_ocla"; + status = "disabled"; + }; + + ps_nub_spmi1: power-controller@c0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi1"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi2: power-controller@e8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xe8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi2"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi3: power-controller@f0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xf0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi3"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_spmi4: power-controller@f8 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xf8 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_spmi4"; + power-domains = <&ps_nub_spmi_ahb>; + status = "disabled"; + }; + + ps_nub_sram: power-controller@108 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x108 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "nub_sram"; + power-domains = <&ps_nub_fabric>; + status = "disabled"; + }; + + ps_debug_switch: power-controller@110 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x110 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "debug_switch"; + status = "disabled"; + }; +}; + +&pmgr_gfx { + ps_gpx: power-controller@0 { + compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x0 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpx"; + status = "disabled"; + }; +}; + +/* + * Parent-domain links absent from t604x-pmgr.dtsi (matching t6040-pmgr.dtsi, + * plus ps_atc3_common_dp -> ps_atc3_phymxwrap matching ps_atc0..2_common_dp). + * Every parent referenced here is enabled whenever its child is enabled. + */ +&ps_avd_sys { + power-domains = <&ps_fab0_soc>; +}; + +&ps_atc0_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc1_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc2_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc3_common { + power-domains = <&ps_fab2_soc>; +}; + +&ps_atc3_common_dp { + power-domains = <&ps_atc3_phymxwrap>; +}; + +&ps_ane_sys { + power-domains = <&ps_fab5_soc>, <&ps_fab4_soc>; +}; + +&ps_pmp { + power-domains = <&ps_pms>; +}; + +&ps_pms_sram { + power-domains = <&ps_pms>; +}; + +&ps_jpg { + power-domains = <&ps_fab4_soc>; +}; + +&ps_venc0_sys { + power-domains = <&ps_fab0_soc>; +}; + +&ps_venc1_sys { + power-domains = <&ps_fab0_soc>; +}; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index 3c37fe24e6c483..cd9a62ee9fe7af 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -486,6 +486,185 @@ #address-cells = <0>; status = "disabled"; }; + + pmgr_disp: power-management@502290000 { + compatible = "apple,t6041-pmgr", "apple,t8103-pmgr", "syscon", "simple-mfd"; + reg = <0x5 0x02290000 0x0 0x4000>; + #address-cells = <1>; + #size-cells = <1>; + }; + + /* + * Suspend-to-RAM at EL2 through aura's S2R mailbox; without the mailbox + * it stays out. Stays disabled at the SoC level so boards without + * qualified deep sleep (such as J575c) remain on s2idle; qualified board + * trees wire apple,apcie and apple,atc-phys and enable it. + */ + t6041_sleep: sleep-controller@508304000 { + compatible = "apple,t6041-sleep"; + reg = <0x5 0x08304000 0x0 0x4000>, + <0x5 0x02820000 0x0 0x4000>, + <0x5 0x0282c000 0x0 0x4000>, + <0x5 0x02888000 0x0 0x4000>, + <0x5 0x0836c000 0x0 0x4000>, + <0x5 0x08330000 0x0 0x4000>, + <0x5 0x08904000 0x0 0x4>, + <0x5 0x00038000 0x0 0x4000>, + <0x5 0x029dc000 0x0 0x880>, + <0x5 0x022d0000 0x0 0x880>, + <0x5 0x04800000 0x0 0xb0000>, + <0x5 0x003c0000 0x0 0x20000>, + <0x5 0x0020c000 0x0 0x800>, + <0x5 0x08004000 0x0 0x58>, + <0x2 0x20000000 0x0 0x200000>, + <0x2 0x22000000 0x0 0x200000>, + <0x2 0x24000000 0x0 0x200000>, + <0x2 0x26000000 0x0 0x200000>, + <0x2 0x28000000 0x0 0x200000>, + <0x2 0x2a000000 0x0 0x200000>, + <0x2 0x2c000000 0x0 0x200000>, + <0x2 0x2e000000 0x0 0x200000>, + <0x2 0x20200000 0x0 0x601000>, + <0x2 0x22200000 0x0 0x601000>, + <0x2 0x24200000 0x0 0x601000>, + <0x2 0x26200000 0x0 0x601000>, + <0x2 0x28200000 0x0 0x601000>, + <0x2 0x2a200000 0x0 0x601000>, + <0x2 0x2c200000 0x0 0x601000>, + <0x2 0x2e200000 0x0 0x601000>, + <0x4 0x03000100 0x0 0x10>, + <0x3 0xa3000100 0x0 0x10>, + <0x6 0x03000100 0x0 0x10>, + <0x6 0x07000100 0x0 0x10>, + <0x3 0x07000100 0x0 0x10>, + <0x4 0x0b000100 0x0 0x10>, + <0x2 0x80000100 0x0 0x10>, + <0x2 0x82000100 0x0 0x10>, + <0x2 0x84000100 0x0 0x10>, + <0x4 0x86000100 0x0 0x10>; + reg-names = "ps-aop", + "cluster", "pwrgate", "cpu-start", "wdt", + "aon-misc", "commit", "clk-mux", "ka-pmgr", + "ka-east", "pmc", "ptd", "perf", "wake", + "amcc0", "amcc1", "amcc2", "amcc3", + "amcc4", "amcc5", "amcc6", "amcc7", + "dcs0", "dcs1", "dcs2", "dcs3", + "dcs4", "dcs5", "dcs6", "dcs7", + "axi2af-disp", "axi2af-dispext0", + "axi2af-dispext1", "axi2af-dispext2", + "axi2af-dispext3", "axi2af-ans", + "axi2af-avd", "axi2af-venc0", + "axi2af-venc1", "axi2af-jpg"; + apple,pinctrl = <&pinctrl>; + apple,pinctrl-skip-pins = <190 191 192>; + apple,spmi-buses = <&nub_spmi0>, <&nub_spmi_a0>; + /* ADT ap-wake-sources unmasked across S2R */ + apple,wake-enable = <13 15 25 27 28 41 44 48 50 51 52 53 55 + 101 106 126 127 128 129 130 131 132 133 + 155 167>; + apple,sleep-off-domains = <&ps_venc1_me1>, <&ps_venc0_me1>, <&ps_venc1_pipe5>, + <&ps_venc1_pipe4>, <&ps_venc1_me0>, <&ps_venc0_pipe5>, + <&ps_venc0_pipe4>, <&ps_venc0_me0>, <&ps_apcie_phy_sw>, + <&ps_ane_base>, <&ps_venc1_dma>, <&ps_venc0_dma>, + <&ps_scodec_streaming>, <&ps_msr1_ase_core>, + <&ps_msr0_ase_core>, <&ps_apcie_sys_st1>, + <&ps_apcie_sys_st0>, <&ps_apcie_sys_gp>, <&ps_ane_td>, + <&ps_ane_mpm>, <&ps_ane_cpu>, <&ps_gfx>, <&ps_venc1_sys>, + <&ps_venc0_sys>, <&ps_spi5>, <&ps_spi4>, <&ps_spi3>, + <&ps_spi2>, <&ps_spi1>, <&ps_spi0>, <&ps_scodec>, + <&ps_rom>, <&ps_qspi>, <&ps_prores>, <&ps_pms_fpwm4>, + <&ps_pms_fpwm3>, <&ps_pms_fpwm2>, <&ps_pms_fpwm1>, + <&ps_pms_fpwm0>, <&ps_pmgr_soc_ocla>, <&ps_nub_spi0>, + <&ps_nub_ocla>, <&ps_msr1>, <&ps_msr0>, <&ps_msg>, + <&ps_jpg>, <&ps_ispsens0>, <&ps_isp_sys>, <&ps_i2c8>, + <&ps_i2c7>, <&ps_i2c6>, <&ps_i2c5>, <&ps_i2c4>, + <&ps_i2c3>, <&ps_i2c2>, <&ps_i2c1>, <&ps_i2c0>, + <&ps_fpwm2>, <&ps_fpwm1>, <&ps_fpwm0>, <&ps_dpa4>, + <&ps_dpa3>, <&ps_dpa2>, <&ps_dpa1>, <&ps_dpa0>, + <&ps_avd_sys>, <&ps_apcie_st1>, <&ps_apcie_st0>, + <&ps_apcie_gp>, <&ps_ap_tmm>, <&ps_ans>, <&ps_ane_sys>, + <&ps_afr>; + apple,atc-off-domains = <&ps_atc0_phymxwrap>, <&ps_atc1_phymxwrap>, + <&ps_atc2_phymxwrap>, <&ps_atc3_phymxwrap>, + <&ps_atc0_usb>, <&ps_atc1_usb>, + <&ps_atc2_usb>, <&ps_atc3_usb>, + <&ps_atc0_usb_aon>, <&ps_atc1_usb_aon>, + <&ps_atc2_usb_aon>, <&ps_atc3_usb_aon>, + <&ps_atc0_common_dp>, <&ps_atc1_common_dp>, + <&ps_atc2_common_dp>, <&ps_atc3_common_dp>, + <&ps_atc0_cio_usb>, <&ps_atc0_cio_pcie>, + <&ps_atc0_pcie>, <&ps_atc0_cio>, + <&ps_atc1_cio_usb>, <&ps_atc1_cio_pcie>, + <&ps_atc1_pcie>, <&ps_atc1_cio>, + <&ps_atc2_cio_usb>, <&ps_atc2_cio_pcie>, + <&ps_atc2_pcie>, <&ps_atc2_cio>, + <&ps_atc3_cio_usb>, <&ps_atc3_cio_pcie>, + <&ps_atc3_pcie>, <&ps_atc3_cio>, + <&ps_atc0_common>, <&ps_atc1_common>, + <&ps_atc2_common>, <&ps_atc3_common>; + apple,sleep-auto-domains = <&ps_fab_gw_1>, <&ps_fab_afr>, <&ps_fab4_soc>, + <&ps_amcc4>, <&ps_amcc5>, <&ps_amcc6>, <&ps_amcc7>, + <&ps_amcc12>, <&ps_amcc13>, <&ps_amcc14>, <&ps_amcc15>, + <&ps_amcc20>, <&ps_amcc21>, <&ps_amcc22>, <&ps_amcc23>, + <&ps_fab0_soc>, <&ps_amcc0>, <&ps_amcc1>, <&ps_amcc2>, + <&ps_amcc3>, <&ps_amcc8>, <&ps_amcc9>, <&ps_amcc10>, + <&ps_amcc11>, <&ps_amcc16>, <&ps_amcc17>, <&ps_amcc18>, + <&ps_amcc19>, <&ps_fab1_soc>, <&ps_fab6_soc>, + <&ps_fab7_soc>, <&ps_nub_sram>, <&ps_dcs_23>, <&ps_sep>, + <&ps_dcs_19>, <&ps_amcc24>, <&ps_amcc25>, <&ps_amcc26>, + <&ps_amcc27>, <&ps_amcc28>, <&ps_amcc29>, <&ps_amcc30>, + <&ps_amcc31>; + apple,sleep-auto-clkgate-domains = <&ps_nub_spmi_a0>, <&ps_nub_spmi_a1>, + <&ps_nub_spmi_a2>, <&ps_fab3_soc>, <&ps_pmc>, + <&ps_nub_spmi0>, <&ps_nub_spmi1>, + <&ps_nub_spmi2>, <&ps_nub_spmi3>, + <&ps_nub_spmi4>, <&ps_dcs_04>, <&ps_dcs_06>, + <&ps_dcs_07>, <&ps_dcs_12>, <&ps_dcs_13>, + <&ps_dcs_14>, <&ps_dcs_15>, <&ps_dcs_20>, + <&ps_dcs_21>, <&ps_dcs_22>, <&ps_dcs_00>, + <&ps_dcs_01>, <&ps_dcs_02>, <&ps_dcs_03>, + <&ps_dcs_08>, <&ps_dcs_09>, <&ps_dcs_10>, + <&ps_dcs_16>, <&ps_dcs_17>, <&ps_dcs_18>, + <&ps_dcs_24>, <&ps_dcs_25>, <&ps_dcs_26>, + <&ps_dcs_27>, <&ps_dcs_28>, <&ps_dcs_29>, + <&ps_dcs_30>, <&ps_dcs_31>; + apple,sleep-auto-active-domains = <&ps_gpx>, <&ps_pms>, <&ps_afi>, <&ps_afc>, + <&ps_fab_gw_0>, <&ps_debug_gated>, <&ps_nub_aon>, + <&ps_nub_fabric>, <&ps_debug_switch>, + <&ps_fab2_soc>, <&ps_pmp>, <&ps_pms_sram>, + <&ps_fab5_soc>, <&ps_dcs_05>, <&ps_dcs_11>, + <&ps_sbr>; + apple,sleep-keep-on-domains = <&ps_dwi>, <&ps_nub_spmi_ahb>, <&ps_nub_gpio>, + <&ps_aic>, <&ps_pms_c1ppt>, <&ps_soc_dpe>, <&ps_sio>, + <&ps_sio_cpu>, <&ps_spi_p>, <&ps_uart_p>, <&ps_dpa_p>, + <&ps_aes>, <&ps_gpio>, <&ps_uart_n>, <&ps_uart0>, + <&ps_uart1>, <&ps_uart2>, <&ps_uart3>, <&ps_uart4>, + <&ps_uart5>, <&ps_uart6>; + apple,cpu-domains = <&ps_ecpu_0>, <&ps_ecpu_1>, <&ps_ecpu_2>, <&ps_ecpu_3>, + <&ps_pcpu0_0>, <&ps_pcpu0_1>, <&ps_pcpu0_2>, <&ps_pcpu0_3>, + <&ps_pcpu0_4>, <&ps_pcpu0_5>, <&ps_pcpu1_0>, <&ps_pcpu1_1>, + <&ps_pcpu1_2>, <&ps_pcpu1_3>, <&ps_pcpu1_4>, <&ps_pcpu1_5>; + apple,cpm-domains = <&ps_ecpm>, <&ps_pcpm0>, <&ps_pcpm1>; + apple,sep-domain = <&ps_sep>; + apple,spmi-a0-domain = <&ps_nub_spmi_a0>; + apple,atc-common-domains = <&ps_atc0_common>, <&ps_atc1_common>, <&ps_atc2_common>, + <&ps_atc3_common>; + apple,atc-fabric-domain = <&ps_fab2_soc>; + apple,atc-afi-domain = <&ps_afi>; + apple,apcie-domains = <&ps_ans>, <&ps_apcie_gp>, <&ps_apcie_sys_gp>, + <&ps_apcie_st0>, <&ps_apcie_sys_st0>, <&ps_apcie_st1>, + <&ps_apcie_sys_st1>, <&ps_apcie_phy_sw>; + apple,commit-sio-domains = <&ps_sio>, <&ps_sio_cpu>; + apple,commit-periph-domains = <&ps_i2c6>, <&ps_i2c3>, <&ps_i2c2>, <&ps_i2c1>, + <&ps_spi2>; + apple,axi2af-domains = <&ps_atc0_common>, <&ps_atc1_common>, <&ps_atc2_common>, + <&ps_atc3_common>, <&ps_disp_sys>, <&ps_dispext0_sys>, + <&ps_dispext1_sys>, <&ps_dispext2_sys>, <&ps_dispext3_sys>, + <&ps_ans>, <&ps_avd_sys>, <&ps_venc0_sys>, <&ps_venc1_sys>, + <&ps_jpg>, <&ps_apcie_sys_gp>; + apple,full-part-detect-domains = <&ps_amcc24>, <&ps_amcc28>; + status = "disabled"; + }; }; &pmgr { @@ -578,6 +757,20 @@ opp-microwatt = <531000>; }; +/* + * What the SEP's DART gets around a sleep, as offset and value: the writes T8140's has + * (t8140.dtsi), which the J616C has slept with. The SEP driver saves the DART with them + * before it tells the enclave to sleep at suspend. + */ +&sep_dart { + apple,sleep-prepare = <0x80 0xa102>, <0x704 0xffffffff>; + apple,sleep-restore = <0x210 0x0>, <0x20c 0x800005f5>, + <0x220 0xf0f0f>, <0x224 0x80808>, + <0x300 0x1>, <0x318 0x1>; + apple,sleep-restore-late = <0x80 0x8000>, <0x228 0x3f3f3f3f>, + <0x22c 0x1010101>; +}; + /* * The ISP DART's address filter, from the full-die J616c ADT's dart-isp0 * dapf-instance-0 (its sixth reg window), in the ADT's order: the @@ -622,6 +815,7 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "venc1_sys"; + power-domains = <&ps_fab0_soc>; status = "disabled"; }; @@ -818,3 +1012,4 @@ }; #include "t6041-pmgr.dtsi" +#include "t6041-sleep-pmgr.dtsi" From fc4c0a683b1506d252229a2ed89aa1cd25c8689d Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 24 Nov 2026 22:07:02 +0000 Subject: [PATCH 1233/1514] soc: apple: t6041-sleep: fix APCIe topo order, pcpm1 match, and auto-PS skip scope Fix three suspend-to-RAM commit regressions in the DT-driven T6041 sleep driver: 1. Replace the DFS-and-reverse topological sort in t6041_topo_sort() with a stable (input-order-preserving) Kahn's topological sort (forward for child-first shutdown, reversed-index child-first reversed back for parent-first restore so edge-free auto-managed DCS nodes stay after their AMCCs), add the missing ps_apcie_sys_gp parent edge on ps_apcie_phy_sw, and order ps_ans before ps_apcie_st1/st0/gp in apple,sleep-off-domains. This ensures ps_apcie_phy_sw lowers before ps_apcie_sys_gp/sys_st*/ans and ps_apcie_st*/gp lower after sys_*/ans, avoiding PARENT_OFF bit 11 latches. 2. Match all three CPM power-state words (ecpm, pcpm0, pcpm1) in t6041_cpu_ps_match() instead of stopping at index 2, clear PS_AUTO_STATE alongside PS_TARGET/PS_AUTO_ENABLE, and clear any stray target/auto bits on absent/fused-off CPU words without raising them. 3. Restrict fused-off channel skipping in t6041_ps_match_all() strictly to AMCC/DCS memory channel slices (amcc*/dcs_*) so idle non-channel domains such as fab6_soc still enter hardware AUTO, and restore the 20 ms SPMI quiet window before clearing the keep-alive tables. Signed-off-by: AxxzyWasTaken --- .../boot/dts/apple/t6041-sleep-pmgr.dtsi | 3 +- arch/arm64/boot/dts/apple/t6041.dtsi | 6 +- drivers/soc/apple/t6041-sleep.c | 231 ++++++++++++------ 3 files changed, 165 insertions(+), 75 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi index ace9854564b2c1..82d293e918fd81 100644 --- a/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-sleep-pmgr.dtsi @@ -471,7 +471,8 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "apcie_phy_sw"; - power-domains = <&ps_apcie_sys_st0>, <&ps_apcie_sys_st1>; + power-domains = <&ps_apcie_sys_st0>, <&ps_apcie_sys_st1>, + <&ps_apcie_sys_gp>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index cd9a62ee9fe7af..a4dfb2d600c9f8 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -581,9 +581,9 @@ <&ps_i2c3>, <&ps_i2c2>, <&ps_i2c1>, <&ps_i2c0>, <&ps_fpwm2>, <&ps_fpwm1>, <&ps_fpwm0>, <&ps_dpa4>, <&ps_dpa3>, <&ps_dpa2>, <&ps_dpa1>, <&ps_dpa0>, - <&ps_avd_sys>, <&ps_apcie_st1>, <&ps_apcie_st0>, - <&ps_apcie_gp>, <&ps_ap_tmm>, <&ps_ans>, <&ps_ane_sys>, - <&ps_afr>; + <&ps_avd_sys>, <&ps_ans>, <&ps_apcie_st1>, + <&ps_apcie_st0>, <&ps_apcie_gp>, <&ps_ap_tmm>, + <&ps_ane_sys>, <&ps_afr>; apple,atc-off-domains = <&ps_atc0_phymxwrap>, <&ps_atc1_phymxwrap>, <&ps_atc2_phymxwrap>, <&ps_atc3_phymxwrap>, <&ps_atc0_usb>, <&ps_atc1_usb>, diff --git a/drivers/soc/apple/t6041-sleep.c b/drivers/soc/apple/t6041-sleep.c index e51f3f7d1fd0b8..35259580fc6f08 100644 --- a/drivers/soc/apple/t6041-sleep.c +++ b/drivers/soc/apple/t6041-sleep.c @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -139,8 +140,10 @@ struct t6041_sleep { void __iomem **ps_atc_off; unsigned int n_atc_off; void __iomem **ps_auto; + unsigned long *ps_auto_mem; unsigned int n_auto; void __iomem **ps_auto_clkgate; + unsigned long *ps_auto_clkgate_mem; unsigned int n_auto_clkgate; void __iomem **ps_auto_active; unsigned int n_auto_active; @@ -359,15 +362,17 @@ static void cpm_gates(struct t6041_sleep *s) writel(0x80000000, s->pwrgate + 0x110); } -static void t6041_ps_match_list(void __iomem *const *regs, unsigned int count, - u32 mask, u32 want, bool skip_fused) +static void t6041_ps_match_list(void __iomem *const *regs, + const unsigned long *may_be_fused, + unsigned int count, u32 mask, u32 want) { unsigned int i; for (i = 0; i < count; i++) { u32 now = readl(regs[i]); - if (skip_fused && !(now & (PS_TARGET | PS_ACTUAL))) + if (may_be_fused && test_bit(i, may_be_fused) && + !(now & (PS_TARGET | PS_ACTUAL))) continue; if ((now & mask) != want) writel((now & ~mask) | want, regs[i]); @@ -376,24 +381,24 @@ static void t6041_ps_match_list(void __iomem *const *regs, unsigned int count, /* * Put every matched PS word into its macOS commit mode: hardware AUTO (off, - * clock-gated, or active) or manual active. Fused-off channel words read 0 - * for both target and actual on binned parts and are skipped uniformly. + * clock-gated, or active) or manual active. Only fused-off AMCC/DCS channel + * slices on 24-channel binned parts (reading 0 for both target and actual) + * are skipped; idle non-channel domains such as fab6_soc must still enter + * hardware AUTO. */ static void t6041_ps_match_all(struct t6041_sleep *s) { const u32 auto_mask = PS_TARGET | PS_AUTO_ENABLE | PS_AUTO_STATE; - t6041_ps_match_list(s->ps_auto, s->n_auto, auto_mask, - PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0), - true); - t6041_ps_match_list(s->ps_auto_clkgate, s->n_auto_clkgate, auto_mask, - PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 4), - true); - t6041_ps_match_list(s->ps_auto_active, s->n_auto_active, auto_mask, - PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0xf), - false); - t6041_ps_match_list(s->ps_keep_on, s->n_keep_on, - PS_TARGET | PS_AUTO_ENABLE, PS_TARGET, false); + t6041_ps_match_list(s->ps_auto, s->ps_auto_mem, s->n_auto, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0)); + t6041_ps_match_list(s->ps_auto_clkgate, s->ps_auto_clkgate_mem, + s->n_auto_clkgate, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 4)); + t6041_ps_match_list(s->ps_auto_active, NULL, s->n_auto_active, auto_mask, + PS_TARGET | PS_AUTO_ENABLE | FIELD_PREP(PS_AUTO_STATE, 0xf)); + t6041_ps_match_list(s->ps_keep_on, NULL, s->n_keep_on, + PS_TARGET | PS_AUTO_ENABLE, PS_TARGET); } static void t6041_cpu_off(u64 mpidr) @@ -424,34 +429,47 @@ static void __noreturn t6041_boot_wfi(struct t6041_sleep *s) } /* - * Raise each present core and CPM PS word to on, then drop its target to 0 - * so the hardware drops PS_ACTUAL when the core enters deep WFI. + * Raise each present core and all three CPM PS words to on, then drop their + * targets to 0 so the hardware drops PS_ACTUAL when each core and cluster + * enters deep WFI. Clear any stray target/auto bits on absent/fused-off cores + * (e.g. pcpu0_5 / pcpu1_5 on 14-core binned parts) without raising them. */ static void t6041_cpu_ps_match(struct t6041_sleep *s) { + const u32 cpu_clear = PS_TARGET | PS_AUTO_ENABLE | PS_AUTO_STATE; + DECLARE_BITMAP(present, T6041_CPU_COUNT); unsigned int cpu, i; u32 v; + bitmap_zero(present, T6041_CPU_COUNT); for_each_present_cpu(cpu) { - void __iomem *reg = s->ps_cpu[t6041_cpu_id(cpu_logical_map(cpu))]; + unsigned int id = t6041_cpu_id(cpu_logical_map(cpu)); + void __iomem *reg = s->ps_cpu[id]; + __set_bit(id, present); v = readl(reg); - writel((v & ~(PS_TARGET | PS_AUTO_ENABLE)) | PS_TARGET, reg); + writel((v & ~cpu_clear) | PS_TARGET, reg); t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); } - for (i = 0; i < 2; i++) { + for (i = 0; i < T6041_CPM_COUNT; i++) { void __iomem *reg = s->ps_cpm[i]; v = readl(reg); - writel((v & ~(PS_TARGET | PS_AUTO_ENABLE)) | PS_TARGET, reg); + writel((v & ~cpu_clear) | PS_TARGET, reg); t6041_poll_until_us(reg, v, FIELD_GET(PS_ACTUAL, v) == 0xf, 2000); } - for_each_present_cpu(cpu) { - void __iomem *reg = s->ps_cpu[t6041_cpu_id(cpu_logical_map(cpu))]; + for (i = 0; i < T6041_CPU_COUNT; i++) { + void __iomem *reg = s->ps_cpu[i]; - writel(readl(reg) & ~PS_TARGET, reg); + if (test_bit(i, present)) { + writel(readl(reg) & ~PS_TARGET, reg); + } else { + v = readl(reg); + if (v & cpu_clear) + writel(v & ~cpu_clear, reg); + } } - for (i = 0; i < 2; i++) { + for (i = 0; i < T6041_CPM_COUNT; i++) { void __iomem *reg = s->ps_cpm[i]; writel(readl(reg) & ~PS_TARGET, reg); @@ -799,6 +817,11 @@ static int t6041_sleep_commit(unsigned long unused) if (t6041_poll_until_us(s->spmi + SPMI_STATUS, v, (v & SPMI_IDLE) == SPMI_IDLE, 5000)) s->spmi_late++; + /* + * Keep SPMI quiet before clearing keep-alive tables and committing + * sleep, matching macOS and the sleep engine's bus handoff window. + */ + t6041_spin_us(20000); /* Keep-alive tables off right before commit. */ for (i = 0; i < KA_WORDS; i++) { writel(0, s->ka[0] + i * KA_STRIDE); @@ -1483,9 +1506,9 @@ struct t6041_topo_ctx { struct device *dev; struct device_node *const *nodes; unsigned int n; - u8 *state; - unsigned int *order; - unsigned int out; + unsigned int stride; + unsigned long *adj; + unsigned int *indeg; }; static int t6041_topo_find(const struct t6041_topo_ctx *ctx, @@ -1515,46 +1538,55 @@ static int t6041_ps_parent(struct device_node *np, int index, return 0; } -static int t6041_topo_visit(struct t6041_topo_ctx *ctx, struct device_node *np, - unsigned int depth) +static int t6041_topo_add_ancestors(struct t6041_topo_ctx *ctx, unsigned int src, + struct device_node *np, unsigned int depth) { - int idx = t6041_topo_find(ctx, np); struct device_node *parent; int k, ret; - if (idx >= 0) { - if (ctx->state[idx] == 2) - return 0; - if (ctx->state[idx] == 1) { - dev_err(ctx->dev, "PMGR power-domain cycle involving %pOF\n", np); - return -EINVAL; - } - ctx->state[idx] = 1; - } if (depth >= T6041_PS_MAX_DEPTH) { dev_err(ctx->dev, "PMGR power-domain hierarchy too deep or cyclic at %pOF\n", np); return -EINVAL; } for (k = 0; ; k++) { + int idx; + ret = t6041_ps_parent(np, k, &parent); if (ret == -ENOENT) break; if (ret) return ret; - ret = t6041_topo_visit(ctx, parent, depth + 1); - of_node_put(parent); - if (ret) - return ret; - } - if (idx >= 0) { - ctx->state[idx] = 2; - ctx->order[ctx->out++] = idx; + idx = t6041_topo_find(ctx, parent); + if (idx == (int)src) { + dev_err(ctx->dev, "PMGR power-domain cycle involving %pOF\n", parent); + of_node_put(parent); + return -EINVAL; + } + if (idx >= 0) { + if (!__test_and_set_bit(idx, ctx->adj + (size_t)src * ctx->stride)) + ctx->indeg[idx]++; + } else { + ret = t6041_topo_add_ancestors(ctx, src, parent, depth + 1); + if (ret) { + of_node_put(parent); + return ret; + } + } + of_node_put(parent); } return 0; } +/* + * Stable (input-order-preserving) Kahn's topological sort on DT power-domains + * edges (child -> parent). For child-first (shutdown), pick the lowest-index + * ready node forward; for parent-first (restore), run the same child-first + * pass in reverse index order and reverse the output so edge-free nodes later + * in the list (such as auto-managed DCS domains after AMCCs) stay after + * earlier nodes whose ancestors are resolved later. + */ static int t6041_topo_sort(struct device *dev, struct device_node *const *nodes, unsigned int n, unsigned int *order, bool child_first) { @@ -1562,35 +1594,64 @@ static int t6041_topo_sort(struct device *dev, struct device_node *const *nodes, .dev = dev, .nodes = nodes, .n = n, - .order = order, + .stride = BITS_TO_LONGS(n), }; - unsigned int i; + unsigned long *emitted = NULL; + unsigned int i, step; int ret = 0; if (!n) return 0; - ctx.state = kcalloc(n, sizeof(*ctx.state), GFP_KERNEL); - if (!ctx.state) - return -ENOMEM; + ctx.adj = kcalloc((size_t)n * ctx.stride, sizeof(*ctx.adj), GFP_KERNEL); + ctx.indeg = kcalloc(n, sizeof(*ctx.indeg), GFP_KERNEL); + emitted = bitmap_zalloc(n, GFP_KERNEL); + if (!ctx.adj || !ctx.indeg || !emitted) { + ret = -ENOMEM; + goto out; + } for (i = 0; i < n; i++) { - if (ctx.state[i]) - continue; - ret = t6041_topo_visit(&ctx, nodes[i], 0); + ret = t6041_topo_add_ancestors(&ctx, i, nodes[i], 0); if (ret) - break; + goto out; } - kfree(ctx.state); - if (ret) - return ret; + for (step = 0; step < n; step++) { + unsigned int pick, next; + bool found = false; - if (child_first) { - for (i = 0; i < n / 2; i++) - swap(order[i], order[n - 1 - i]); + if (child_first) { + for (pick = 0; pick < n; pick++) { + if (!test_bit(pick, emitted) && !ctx.indeg[pick]) { + found = true; + break; + } + } + } else { + for (pick = n; pick-- > 0; ) { + if (!test_bit(pick, emitted) && !ctx.indeg[pick]) { + found = true; + break; + } + } + } + if (!found) { + dev_err(dev, "PMGR power-domain cycle detected\n"); + ret = -EINVAL; + goto out; + } + __set_bit(pick, emitted); + order[child_first ? step : n - 1 - step] = pick; + for_each_set_bit(next, ctx.adj + (size_t)pick * ctx.stride, n) + ctx.indeg[next]--; } - return 0; + +out: + bitmap_free(emitted); + kfree(ctx.indeg); + kfree(ctx.adj); + return ret; } static bool t6041_node_in_list(struct device_node *const *list, unsigned int n, @@ -1612,10 +1673,20 @@ struct t6041_restore_acc { unsigned int n_exclude; }; +static bool t6041_ps_is_mem_channel(const struct device_node *np) +{ + const char *label; + + if (of_property_read_string(np, "label", &label)) + return false; + return str_has_prefix(label, "amcc") || str_has_prefix(label, "dcs_"); +} + static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, bool topo_child_first, void __iomem ***out_regs, unsigned int *out_count, + unsigned long **out_mem_mask, struct t6041_restore_acc *acc) { struct device *dev = r->dev; @@ -1623,6 +1694,7 @@ static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, struct device_node **nodes; void __iomem **regs; void __iomem **dst; + unsigned long *mem_mask = NULL; unsigned int *order = NULL; unsigned int i, uniq = 0; int count, ret = 0; @@ -1685,6 +1757,20 @@ static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, memcpy(dst, regs, uniq * sizeof(*dst)); } + if (out_mem_mask) { + mem_mask = devm_bitmap_zalloc(dev, uniq, GFP_KERNEL); + if (!mem_mask) { + ret = -ENOMEM; + goto out_put; + } + for (i = 0; i < uniq; i++) { + struct device_node *entry = topo_child_first ? nodes[order[i]] : nodes[i]; + + if (t6041_ps_is_mem_channel(entry)) + __set_bit(i, mem_mask); + } + } + for (i = 0; i < uniq; i++) { if (t6041_node_in_list(acc->exclude, acc->n_exclude, nodes[i])) continue; @@ -1697,6 +1783,8 @@ static int t6041_parse_ps_list(struct t6041_ps_resolver *r, const char *prop, *out_regs = dst; *out_count = uniq; + if (out_mem_mask) + *out_mem_mask = mem_mask; out_put: kfree(order); @@ -1811,27 +1899,28 @@ static int t6041_map_ps_domains(struct t6041_sleep *s) * ps_restore. */ ret = t6041_parse_ps_list(&r, "apple,sleep-auto-domains", false, - &s->ps_auto, &s->n_auto, &acc); + &s->ps_auto, &s->n_auto, &s->ps_auto_mem, &acc); if (ret) goto out; ret = t6041_parse_ps_list(&r, "apple,sleep-auto-active-domains", false, - &s->ps_auto_active, &s->n_auto_active, &acc); + &s->ps_auto_active, &s->n_auto_active, NULL, &acc); if (ret) goto out; ret = t6041_parse_ps_list(&r, "apple,sleep-auto-clkgate-domains", false, - &s->ps_auto_clkgate, &s->n_auto_clkgate, &acc); + &s->ps_auto_clkgate, &s->n_auto_clkgate, + &s->ps_auto_clkgate_mem, &acc); if (ret) goto out; ret = t6041_parse_ps_list(&r, "apple,sleep-keep-on-domains", false, - &s->ps_keep_on, &s->n_keep_on, &acc); + &s->ps_keep_on, &s->n_keep_on, NULL, &acc); if (ret) goto out; ret = t6041_parse_ps_list(&r, "apple,atc-off-domains", false, - &s->ps_atc_off, &s->n_atc_off, &acc); + &s->ps_atc_off, &s->n_atc_off, NULL, &acc); if (ret) goto out; ret = t6041_parse_ps_list(&r, "apple,sleep-off-domains", true, - &s->ps_off, &s->n_off, &acc); + &s->ps_off, &s->n_off, NULL, &acc); if (ret) goto out; From ecbfd64ed773f87efe6d09519b78e66d54d5ad37 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:54:44 -0500 Subject: [PATCH 1234/1514] wifi: apple: centauri: release lock during scan wait and synchronize stop scan_profile27() on T6050 and scan_worker() on T8142/T8152 held wifi->lock across the multi-second scan polling loop. Any concurrent cfg80211 station query (such as NetworkManager or iw link polling while holding wiphy->mtx) blocked on wifi->lock for the entire scan, stalling nl80211 operations including scan abort and causing -EBUSY failures on rapid rescan or connect. In addition, scan abort/timeout paths returned without waiting for the firmware's 0x80000005 stop completion event, allowing stale completions to terminate a subsequent scan early, and connect_worker() could latch a stale disconnect event drained during host_setup_commands(). Release wifi->lock around the polling sleep in both drivers' scan loops while re-checking stopping, command_failed, sleep/pause flags and Alpha stage before touching the transport. Skip synchronous firmware link-status queries in T6050 fill_station() while a scan is active so station queries return cached signal and live counters without contending with off-channel dwells. Synchronize command 65537 scan stops with a bounded wait for 0x80000005 (treating status 342 as already stopped), and drain and clear stale connect/disconnect event flags right before sending the join command in connect_worker(). Signed-off-by: Diljit Singh --- .../wireless/apple/centauri/centauri_wifi.c | 43 +++++++++++++-- .../apple/centauri/t6050/centauri_wifi.c | 54 +++++++++++++++---- 2 files changed, 82 insertions(+), 15 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index de0d4d872932a0..566536bec817c9 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -913,6 +913,34 @@ static size_t build_scan(struct centauri_wifi *wifi, unsigned int chunk, u8 *buf return size; } +static int scan_stop_chunk(struct centauri_wifi *wifi, u32 done) +{ + unsigned long deadline; + int ret; + + ret = command(wifi, 65537, NULL, 0); + if (wifi->scans_done != done) + return 0; + if (ret == -EREMOTEIO && wifi->reply_status == 342) + return 0; + if (ret) + return ret; + deadline = jiffies + msecs_to_jiffies(1000); + do { + if (READ_ONCE(wifi->stopping) || + READ_ONCE(wifi->transport_paused) || + readl(wifi->a.bar + 8) != 2) + return -EIO; + drain(wifi); + if (wifi->scans_done != done) + return 0; + mutex_unlock(&wifi->lock); + usleep_range(1000, 2000); + mutex_lock(&wifi->lock); + } while (time_before(jiffies, deadline)); + return -ETIMEDOUT; +} + static void scan_worker(struct work_struct *work) { struct centauri_wifi *wifi = container_of(work, struct centauri_wifi, scan_work); @@ -953,16 +981,18 @@ static void scan_worker(struct work_struct *work) msecs_to_jiffies(max(8000U, count * 2 * SCAN_PASSIVE_DWELL_MS + 2000)); progress = jiffies; do { - drain(wifi); - if (readl(wifi->a.bar + 8) != 2) { + if (READ_ONCE(wifi->stopping) || + READ_ONCE(wifi->transport_paused) || + readl(wifi->a.bar + 8) != 2) { ret = -EIO; break; } + drain(wifi); if (wifi->scans_done != done) break; if (READ_ONCE(wifi->scan_abort)) { if (!stopped) - command(wifi, 65537, NULL, 0); + scan_stop_chunk(wifi, done); ret = -ECANCELED; break; } @@ -989,7 +1019,9 @@ static void scan_worker(struct work_struct *work) /* The stop's own scan event ends the wait. */ deadline = jiffies + msecs_to_jiffies(1000); } + mutex_unlock(&wifi->lock); usleep_range(1000, 2000); + mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); if (!ret && !refused && wifi->scans_done == done) { dev_warn(&wifi->control->pdev->dev, @@ -997,7 +1029,7 @@ static void scan_worker(struct work_struct *work) wifi->channels_seen - channels, count, stopped ? " after the stop" : ""); if (!stopped) - command(wifi, 65537, NULL, 0); + scan_stop_chunk(wifi, done); } } info.aborted = !!ret; @@ -1246,6 +1278,9 @@ static void connect_worker(struct work_struct *work) } } host_setup_commands(wifi); + drain(wifi); + wifi->connect_event = false; + wifi->disconnect_event = false; slot = wifi->command_head; ret = command(wifi, 131072, wifi->connect_payload, wifi->connect_size); command_status = wifi->reply_status; diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index f515c455573d31..4dcfa99802b9e4 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -1140,6 +1140,34 @@ static int radio_start(struct centauri_t6050_wifi *wifi) #define SCAN_ACTIVE_MIN_MS 40 #define SCAN_LISTEN_MS 110 +static int scan_stop_chunk(struct centauri_t6050_wifi *wifi, u32 done) +{ + unsigned long deadline; + int ret; + + lockdep_assert_held(&wifi->lock); + ret = command(wifi, 65537, NULL, 0); + if (wifi->scans_done != done) + return 0; + if (ret == -EREMOTEIO && wifi->reply_status == 342) + return 0; + if (ret) + return ret; + deadline = jiffies + msecs_to_jiffies(1000); + do { + if (READ_ONCE(wifi->stopping) || wifi->command_failed || + wifi->host_sleep_sent || readl(wifi->a.bar + 8) != 2) + return -EIO; + drain(wifi); + if (wifi->scans_done != done) + return 0; + mutex_unlock(&wifi->lock); + usleep_range(1000, 2000); + mutex_lock(&wifi->lock); + } while (time_before(jiffies, deadline)); + return -ETIMEDOUT; +} + static int scan_profile27(struct centauri_t6050_wifi *wifi) { struct cfg80211_scan_request *request = wifi->scan_request; @@ -1156,7 +1184,6 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) size_t size = 14; unsigned long deadline; int ret; - bool abort_sent = false; if (READ_ONCE(wifi->scan_abort)) return -ECANCELED; @@ -1228,28 +1255,29 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) deadline = jiffies + msecs_to_jiffies(max(8000U, count * 220 + 2000)); do { - drain(wifi); - if (READ_ONCE(wifi->stopping) || + if (READ_ONCE(wifi->stopping) || wifi->command_failed || + wifi->host_sleep_sent || readl(wifi->a.bar + 8) != 2) return -EIO; + drain(wifi); if (wifi->scans_done != done) break; - if (READ_ONCE(wifi->scan_abort) && !abort_sent) { - ret = command(wifi, 65537, NULL, 0); - if (ret) - return ret; - abort_sent = true; + if (READ_ONCE(wifi->scan_abort)) { + ret = scan_stop_chunk(wifi, done); + return ret == -EIO ? -EIO : -ECANCELED; } + mutex_unlock(&wifi->lock); usleep_range(1000, 2000); + mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); if (wifi->scans_done == done) { dev_warn(&wifi->control->pdev->dev, "Wi-Fi scan of %u channels: no completion event\n", count); - command(wifi, 65537, NULL, 0); + scan_stop_chunk(wifi, done); return -ETIMEDOUT; } - if (wifi->scan_status && !abort_sent) + if (wifi->scan_status) dev_warn(&wifi->control->pdev->dev, "Wi-Fi scan of %u channels ended with firmware status %u\n", count, wifi->scan_status); @@ -1894,6 +1922,9 @@ static void connect_worker(struct work_struct *work) return; } host_setup_commands(wifi); + drain(wifi); + wifi->connect_event = false; + wifi->disconnect_event = false; slot = wifi->command_head; ret = command(wifi, 131072, wifi->connect_payload, wifi->connect_size); memzero_explicit(wifi->connect_payload, sizeof(wifi->connect_payload)); @@ -2515,7 +2546,8 @@ static void fill_station(struct centauri_t6050_wifi *wifi, struct station_info * { const struct net_device_stats *stats = &wifi->netdev->stats; - if (time_after_eq(jiffies, wifi->station_signal_at + HZ)) { + if (!wifi->scan_request && + time_after_eq(jiffies, wifi->station_signal_at + HZ)) { wifi->station_signal_valid = false; wifi->station_signal_at = jiffies; query_link_status(wifi); From e0d3171c5b117bd61c0a89e30547c44e40b58ccb Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 21:54:44 -0500 Subject: [PATCH 1235/1514] Bluetooth: btcentauri_t6050: reschedule io_work when ring work remains Unlike the polling btcentauri transport, btcentauri_t6050 relies on MSIs and TX submission kicks to run cen_io_work(). cen_io_work() snapshotted each RX ring tail once and drained at most CEN_RX_SLOTS entries without checking whether more descriptors had arrived during drain or whether a non-empty TX queue could now publish into a freed TX ring slot. Under advertising bursts or coalesced interrupts, unread events or queued frames could sit in the rings until an unrelated wakeup. Re-check all open RX ring tails and pending TX queues with available ring space before leaving cen_io_work(), rescheduling io_work when work remains. Add host unit tests and negative controls in tools/asahi/centauri-scan-tests.py covering both Wi-Fi scan lock/stop synchronization and Bluetooth ring drain rescheduling. Signed-off-by: Diljit Singh --- drivers/bluetooth/btcentauri_t6050.c | 29 ++ tools/asahi/centauri-scan-tests.py | 596 +++++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 3 files changed, 626 insertions(+) create mode 100755 tools/asahi/centauri-scan-tests.py diff --git a/drivers/bluetooth/btcentauri_t6050.c b/drivers/bluetooth/btcentauri_t6050.c index 36fcc4b686c02b..8f2f21da04ddf0 100644 --- a/drivers/bluetooth/btcentauri_t6050.c +++ b/drivers/bluetooth/btcentauri_t6050.c @@ -443,6 +443,29 @@ static void cen_fixup_scan_response(u8 *event, size_t length) } } +static bool cen_rx_pending(struct cen_bt *bt) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cen_aux_specs); i++) { + if (!bt->aux[i].opened || !cen_aux_specs[i].receive) + continue; + if (bt->aux[i].head != cen_tail(bt, cen_aux_specs[i].id)) + return true; + } + if (bt->le_rx_head != cen_tail(bt, 10)) + return true; + return bt->rx_head != cen_tail(bt, 7); +} + +static bool cen_tx_ready(struct cen_bt *bt, struct sk_buff_head *queue, + u16 ring, u16 slots, u16 head) +{ + if (skb_queue_empty(queue)) + return false; + return (head + 1) % slots != cen_tail(bt, ring); +} + static void cen_io_work(struct work_struct *work) { struct cen_bt *bt = container_of(work, struct cen_bt, io_work); @@ -536,6 +559,12 @@ static void cen_io_work(struct work_struct *work) cen_transmit(bt, &bt->le_txq, 4, CEN_LE_SLOTS, CEN_LE_TX, CEN_LE_FOOTER, &bt->le_tx_head))) goto protocol_error; + if (cen_rx_pending(bt) || + cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head) || + cen_tx_ready(bt, &bt->acl_txq, 2, cen_aux_specs[0].slots, + bt->acl_tx_head) || + cen_tx_ready(bt, &bt->le_txq, 4, CEN_LE_SLOTS, bt->le_tx_head)) + schedule_work(&bt->io_work); goto unlock; protocol_error: bt->running = false; diff --git a/tools/asahi/centauri-scan-tests.py b/tools/asahi/centauri-scan-tests.py new file mode 100755 index 00000000000000..266aa6fc74cba4 --- /dev/null +++ b/tools/asahi/centauri-scan-tests.py @@ -0,0 +1,596 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Host unit tests and negative controls for Centauri Wi-Fi/BT scanning.""" +import argparse +import os +from pathlib import Path +import re +import resource +import shlex +import signal +import subprocess +import tempfile + + +def extract_fn(source, name): + match = re.search( + r"^(?:static )?(?:int|void|bool) " + re.escape(name) + r"\([^;]*?\)\n\{", + source, + re.M, + ) + if not match: + raise RuntimeError(f"missing production function: {name}") + brace = source.index("{", match.start()) + depth, end = 1, brace + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[match.start():end] + + +WIFI_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef int8_t s8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +#define BIT(n) (1U << (n)) +#define BIT_ULL(n) (1ULL << (n)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define CEN_SCAN_CHANNELS_MAX 59 +#define SCAN_ACTIVE_MIN_MS 40 +#define SCAN_LISTEN_MS 110 +#define CHANNEL_PASSIVE BIT(4) +#define CHANNEL_RADAR BIT(6) +#define IEEE80211_CHAN_DISABLED BIT(0) +#define IEEE80211_CHAN_NO_IR BIT(1) +#define IEEE80211_CHAN_RADAR BIT(2) +#define HZ 1000 +#define msecs_to_jiffies(x) ((unsigned long)(x)) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define time_after_eq(a, b) (!time_before(a, b)) +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define NL80211_BAND_2GHZ 0 +#define NL80211_BAND_5GHZ 1 +#define NL80211_BAND_6GHZ 2 +#define NL80211_STA_INFO_CONNECTED_TIME 0 +#define NL80211_STA_INFO_RX_BYTES64 1 +#define NL80211_STA_INFO_TX_BYTES64 2 +#define NL80211_STA_INFO_RX_PACKETS 3 +#define NL80211_STA_INFO_TX_PACKETS 4 +#define NL80211_STA_INFO_SIGNAL 5 +#define lockdep_assert_held(l) assert(*(l)) +#define dev_warn(...) ((void)0) + +struct device { int dummy; }; +struct pci_dev { struct device dev; }; +struct centauri_t6050 { struct pci_dev *pdev; }; +struct ieee80211_channel { int band; u32 center_freq; u32 flags; }; +struct cfg80211_ssid { u8 ssid[32]; u8 ssid_len; }; +struct cfg80211_scan_request { + u32 n_channels; + u32 n_ssids; + struct cfg80211_ssid *ssids; + struct ieee80211_channel *channels[8]; +}; +struct net_device_stats { + u64 rx_bytes, tx_bytes, rx_packets, tx_packets; +}; +struct net_device { struct net_device_stats stats; }; +struct station_info { + u64 filled; + u32 connected_time; + u64 rx_bytes, tx_bytes, rx_packets, tx_packets; + s8 signal; +}; +struct centauri_t6050_wifi { + struct centauri_t6050 *control; + struct { u8 *bar; } a; + struct net_device *netdev; + struct cfg80211_scan_request *scan_request; + int lock; + u32 scans_done; + u16 reply_status, scan_status; + u8 scan_sequence; + bool stopping, command_failed, host_sleep_sent, scan_abort; + s8 station_signal; + bool station_signal_valid; + unsigned long station_signal_at, connected_at; + struct net_device_stats station_start; +}; + +static unsigned long jiffies; +static unsigned int bar_reads, sleep_calls, link_queries, stop_commands; +static unsigned int stop_event_delay, complete_after_drains, drains_seen; +static bool stop_refuse_342, stop_refuse_other, sleep_sets_abort; +static bool sleep_sets_host_sleep, sleep_checks_station, station_ran_in_sleep; +static u8 fake_bar[32]; +static struct centauri_t6050_wifi *g_wifi; + +static void fill_station(struct centauri_t6050_wifi *wifi, + struct station_info *sinfo); + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static void put_unaligned_le16(u16 v, void *p) { memcpy(p, &v, 2); } +static u32 readl(void *addr) { (void)addr; bar_reads++; return 2; } +static int firmware_band(int band) { return band; } +static int ieee80211_frequency_to_channel(u32 freq) +{ + return freq == 2412 ? 1 : 36; +} +static void command_refused(struct centauri_t6050_wifi *w, const char *s, int r) +{ + (void)w; (void)s; (void)r; +} +static int query_link_status(struct centauri_t6050_wifi *wifi) +{ + assert(wifi->lock); + link_queries++; + wifi->station_signal = -52; + wifi->station_signal_valid = true; + wifi->station_signal_at = jiffies; + return 0; +} +static int command(struct centauri_t6050_wifi *wifi, u32 id, + const void *payload, size_t size) +{ + (void)payload; (void)size; + assert(wifi->lock); + if (id == 65537) { + stop_commands++; + if (stop_refuse_342) { + wifi->reply_status = 342; + return -EREMOTEIO; + } + if (stop_refuse_other) { + wifi->reply_status = 500; + return -EREMOTEIO; + } + wifi->reply_status = 0; + return 0; + } + return 0; +} +static void drain(struct centauri_t6050_wifi *wifi) +{ + assert(wifi->lock); + drains_seen++; + if (complete_after_drains && drains_seen >= complete_after_drains) { + wifi->scans_done++; + complete_after_drains = 0; + } + if (stop_commands && stop_event_delay) { + stop_event_delay--; + if (!stop_event_delay) + wifi->scans_done++; + } +} +static void usleep_range(unsigned long a, unsigned long b) +{ + (void)a; (void)b; + sleep_calls++; + jiffies += 250; + /* Must not hold wifi->lock across scan wait sleeps. */ + assert(!g_wifi->lock); + if (sleep_checks_station && !station_ran_in_sleep) { + struct station_info sinfo = {}; + + mutex_lock(&g_wifi->lock); + fill_station(g_wifi, &sinfo); + mutex_unlock(&g_wifi->lock); + assert(link_queries == 0); + assert(sinfo.filled & BIT_ULL(NL80211_STA_INFO_SIGNAL)); + assert(sinfo.signal == -61); + station_ran_in_sleep = true; + } + if (sleep_sets_abort) { + g_wifi->scan_abort = true; + sleep_sets_abort = false; + } + if (sleep_sets_host_sleep) { + g_wifi->host_sleep_sent = true; + sleep_sets_host_sleep = false; + } +} +''' + +WIFI_TESTS = r''' +static struct pci_dev pdev; +static struct centauri_t6050 ctrl = { .pdev = &pdev }; +static struct net_device ndev; +static struct centauri_t6050_wifi wifi; +static struct ieee80211_channel ch1 = { .band = NL80211_BAND_2GHZ, .center_freq = 2412 }; +static struct cfg80211_scan_request req; + +static void reset_wifi(void) +{ + memset(&wifi, 0, sizeof(wifi)); + memset(&ndev, 0, sizeof(ndev)); + memset(&req, 0, sizeof(req)); + wifi.control = &ctrl; + wifi.a.bar = fake_bar; + wifi.netdev = &ndev; + req.n_channels = 1; + req.channels[0] = &ch1; + wifi.scan_request = &req; + wifi.station_signal = -61; + wifi.station_signal_valid = true; + wifi.station_signal_at = 0; + g_wifi = &wifi; + jiffies = 2000; + bar_reads = sleep_calls = link_queries = stop_commands = 0; + stop_event_delay = complete_after_drains = drains_seen = 0; + stop_refuse_342 = stop_refuse_other = false; + sleep_sets_abort = sleep_sets_host_sleep = false; + sleep_checks_station = station_ran_in_sleep = false; +} + +int main(void) +{ + /* 1. Normal scan unlocks during sleep; concurrent fill_station skips FW cmd 20. */ + reset_wifi(); + complete_after_drains = 3; + sleep_checks_station = true; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(sleep_calls >= 1 && station_ran_in_sleep && link_queries == 0); + + /* Outside a scan, fill_station refreshes link status normally. */ + wifi.scan_request = NULL; + { + struct station_info sinfo = {}; + + mutex_lock(&wifi.lock); + fill_station(&wifi, &sinfo); + mutex_unlock(&wifi.lock); + assert(link_queries == 1 && sinfo.signal == -52); + } + + /* 2. Scan abort sends 65537 and waits for 0x80000005 completion. */ + reset_wifi(); + sleep_sets_abort = true; + stop_event_delay = 2; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -ECANCELED); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1 && wifi.scans_done == 1); + + /* 3. Scan abort with firmware status 342 (already ended) returns cleanly. */ + reset_wifi(); + wifi.scan_abort = true; + stop_refuse_342 = true; + mutex_lock(&wifi.lock); + assert(scan_stop_chunk(&wifi, 0) == 0); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1); + + /* 4. Scan timeout stops chunk and waits for 0x80000005 before returning. */ + reset_wifi(); + stop_event_delay = 2; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -ETIMEDOUT); + mutex_unlock(&wifi.lock); + assert(stop_commands == 1 && wifi.scans_done == 1); + + /* 5. Host sleep entered while unlocked aborts without BAR read. */ + reset_wifi(); + sleep_sets_host_sleep = true; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(bar_reads == 1); + + puts("PASS: Centauri Wi-Fi scan lock-release and stop synchronization"); + return 0; +} +''' + +BT_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define GFP_KERNEL 0 +#define CEN_RX 0x8000 +#define CEN_TX 0xa000 +#define CEN_FOOTER 260 +#define CEN_STRIDE (16 + CEN_FOOTER) +#define CEN_RX_SLOTS 17 +#define CEN_TX_SLOTS 5 +#define CEN_LE_RX 0xc000 +#define CEN_LE_TX 0xe000 +#define CEN_LE_FOOTER 256 +#define CEN_LE_STRIDE (16 + CEN_LE_FOOTER) +#define CEN_LE_SLOTS 17 +#define HCI_EVENT_HDR_SIZE 2U +#define HCI_EVENT_PKT 4 +#define HCI_EV_CMD_STATUS 0x0f +#define HCI_EV_CONN_COMPLETE 0x03 +#define HCI_OP_CREATE_CONN 0x0405 +#define CEN_OP_CREATE_CONN 0xff7b +#define ACL_LINK 1 +#define dma_rmb() ((void)0) +#define dev_err(...) ((void)0) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - __builtin_offsetof(type, member))) + +struct hci_ev_conn_complete { u8 dummy[11]; }; +struct cen_aux_spec { u16 id, slots, footer; bool receive; }; +static const struct cen_aux_spec cen_aux_specs[] = { + { 2, 9, 2592, false }, { 8, 9, 2592, true }, +}; +struct cen_aux_state { u32 offset; u16 head, post; bool opened; }; +struct work_struct { int dummy; }; +struct sk_buff_head { unsigned int len; }; +struct sk_buff { u8 data[64]; u32 len; u8 pkt_type; }; +struct pci_dev { int dev; }; +struct hci_dev { struct { u32 byte_rx, err_rx; } stat; }; +struct cen_bt { + struct pci_dev *pdev; + struct hci_dev *hdev; + u8 *bar; + u8 *arena; + int lock; + struct work_struct io_work; + struct sk_buff_head txq, acl_txq, le_txq; + u16 acl_tx_head, le_tx_head; + u16 tx_head, rx_head, rx_post; + u16 le_rx_head, le_rx_post; + struct cen_aux_state aux[ARRAY_SIZE(cen_aux_specs)]; + bool running, transport_paused; + bool connection_command_supported, connection_status_pending; +}; + +static u16 mock_tail[16]; +static bool advance_rx_tail_on_post, advance_tx_tail_after_tx; +static unsigned int rx_frames, reschedules; +static struct sk_buff fake_skb; + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static u32 readl(void *p) { (void)p; return 2; } +static u16 get_unaligned_le16(const void *p) { u16 v; memcpy(&v, p, 2); return v; } +static u32 get_unaligned_le32(const void *p) { u32 v; memcpy(&v, p, 4); return v; } +static void put_unaligned_le16(u16 v, void *p) { memcpy(p, &v, 2); } +static bool skb_queue_empty(const struct sk_buff_head *q) { return q->len == 0; } +static void schedule_work(struct work_struct *w) { (void)w; reschedules++; } +static u16 cen_tail(struct cen_bt *bt, u16 ring) { (void)bt; return mock_tail[ring]; } +static int cen_aux_drain(struct cen_bt *bt, bool repost) { (void)bt; (void)repost; return 0; } +static int cen_receive_acl(struct cen_bt *bt, const u8 *d, u32 l) { (void)bt; (void)d; (void)l; return 0; } +static void cen_le_rx_buffer(struct cen_bt *bt, u16 slot) { (void)bt; (void)slot; } +static void cen_rx_buffer(struct cen_bt *bt, u16 slot) { (void)bt; (void)slot; } +static void cen_fixup_scan_response(u8 *e, size_t l) { (void)e; (void)l; } +static struct sk_buff *bt_skb_alloc(u32 len, int flags) +{ + (void)flags; + assert(len <= sizeof(fake_skb.data)); + fake_skb.len = 0; + return &fake_skb; +} +static void skb_put_data(struct sk_buff *skb, const void *d, u32 len) +{ + memcpy(skb->data, d, len); + skb->len = len; +} +#define hci_skb_pkt_type(skb) ((skb)->pkt_type) +static void hci_recv_frame(struct hci_dev *h, struct sk_buff *s) { (void)h; (void)s; rx_frames++; } +static void cen_post(struct cen_bt *bt, u16 ring, u16 val) +{ + (void)bt; (void)val; + if (ring == 7 && advance_rx_tail_on_post) { + advance_rx_tail_on_post = false; + mock_tail[7] = (mock_tail[7] + 1) % CEN_RX_SLOTS; + } +} +static int cen_transmit(struct cen_bt *bt, struct sk_buff_head *q, u16 ring, + u16 slots, u32 off, u16 footer, u16 *head) +{ + (void)bt; (void)off; (void)footer; + if (ring == 1 && advance_tx_tail_after_tx && q->len) { + /* Simulate ring momentarily full during transmit, then freed right after. */ + *head = (mock_tail[1] + slots - 1) % slots; + mock_tail[1] = (mock_tail[1] + 1) % slots; + advance_tx_tail_after_tx = false; + } + return 0; +} +''' + +BT_TESTS = r''' +static u8 arena[0x10000]; +static u8 fake_bar[32]; +static struct pci_dev pdev; +static struct hci_dev hdev; +static struct cen_bt bt; + +static void reset_bt(void) +{ + memset(&bt, 0, sizeof(bt)); + memset(arena, 0, sizeof(arena)); + memset(mock_tail, 0, sizeof(mock_tail)); + bt.pdev = &pdev; + bt.hdev = &hdev; + bt.bar = fake_bar; + bt.arena = arena; + bt.running = true; + bt.rx_post = CEN_RX_SLOTS - 1; + bt.le_rx_post = CEN_LE_SLOTS - 1; + advance_rx_tail_on_post = advance_tx_tail_after_tx = false; + rx_frames = reschedules = 0; +} + +static void put_rx_event(u16 slot) +{ + u8 *d = arena + CEN_RX + slot * CEN_STRIDE; + u32 hdr = 1 | (4U << 8); + + memcpy(d, &hdr, 4); + d[16] = 0x3e; + d[17] = 2; + d[18] = 0x0d; + d[19] = 0; +} + +int main(void) +{ + /* 1. Coalesced RX arrival during drain triggers io_work reschedule. */ + reset_bt(); + put_rx_event(0); + put_rx_event(1); + mock_tail[7] = 1; + advance_rx_tail_on_post = true; + cen_io_work(&bt.io_work); + assert(rx_frames == 1 && bt.rx_head == 1 && reschedules == 1); + + /* Second pass drains remaining event and stays idle (no spin). */ + reschedules = 0; + cen_io_work(&bt.io_work); + assert(rx_frames == 2 && bt.rx_head == 2 && reschedules == 0); + + /* 2. Pending TX queue with newly freed TX ring slot reschedules io_work. */ + reset_bt(); + bt.txq.len = 1; + advance_tx_tail_after_tx = true; + cen_io_work(&bt.io_work); + assert(reschedules == 1); + + /* 3. Idle rings do not reschedule. */ + reset_bt(); + cen_io_work(&bt.io_work); + assert(reschedules == 0); + + puts("PASS: Centauri Bluetooth RX/TX ring drain reschedule"); + return 0; +} +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path) + parser.add_argument("--negative-controls", action="store_true") + parser.add_argument("--source-root", type=Path) + args = parser.parse_args() + root = args.source_root or Path(__file__).resolve().parents[2] + wifi_src = ( + root / "drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c" + ).read_text() + bt_src = (root / "drivers/bluetooth/btcentauri_t6050.c").read_text() + + wifi_prod = "\n\n".join( + extract_fn(wifi_src, name) + for name in ("scan_stop_chunk", "scan_profile27", "fill_station") + ) + bt_prod = "\n\n".join( + extract_fn(bt_src, name) + for name in ("cen_rx_pending", "cen_tx_ready", "cen_io_work") + ) + + wifi_variants = [("wifi-production", WIFI_PRELUDE + wifi_prod + WIFI_TESTS, 0, None)] + bt_variants = [("bt-production", BT_PRELUDE + bt_prod + BT_TESTS, 0, None)] + + if args.negative_controls: + wifi_controls = [ + ( + "scan-holds-lock-in-sleep", + "\t\t\tmutex_unlock(&wifi->lock);\n\t\t\tusleep_range(1000, 2000);\n\t\t\tmutex_lock(&wifi->lock);", + "\t\t\tusleep_range(1000, 2000);", + "!g_wifi->lock", + ), + ( + "station-queries-fw-during-scan", + "if (!wifi->scan_request &&\n\t time_after_eq(jiffies, wifi->station_signal_at + HZ))", + "if (time_after_eq(jiffies, wifi->station_signal_at + HZ))", + "link_queries == 0", + ), + ( + "timeout-skips-stop-wait", + "\t\t\tscan_stop_chunk(wifi, done);\n\t\t\treturn -ETIMEDOUT;", + "\t\t\tcommand(wifi, 65537, NULL, 0);\n\t\t\treturn -ETIMEDOUT;", + "wifi.scans_done == 1", + ), + ( + "abort-ignores-342", + "if (ret == -EREMOTEIO && wifi->reply_status == 342)\n\t\treturn 0;", + "if (false && ret == -EREMOTEIO && wifi->reply_status == 342)\n\t\treturn 0;", + "scan_stop_chunk(&wifi, 0) == 0", + ), + ] + for name, old, new, expected_msg in wifi_controls: + if old not in wifi_prod: + raise RuntimeError(f"missing pattern for {name}") + wifi_variants.append( + (name, WIFI_PRELUDE + wifi_prod.replace(old, new, 1) + WIFI_TESTS, + -signal.SIGABRT, expected_msg) + ) + + bt_controls = [ + ( + "bt-drops-rx-reschedule", + "if (cen_rx_pending(bt) ||", + "if ((false && cen_rx_pending(bt)) ||", + "reschedules == 1", + ), + ( + "bt-drops-tx-reschedule", + "cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head) ||", + "(false && cen_tx_ready(bt, &bt->txq, 1, CEN_TX_SLOTS, bt->tx_head)) ||", + "reschedules == 1", + ), + ] + for name, old, new, expected_msg in bt_controls: + if old not in bt_prod: + raise RuntimeError(f"missing pattern for {name}") + bt_variants.append( + (name, BT_PRELUDE + bt_prod.replace(old, new, 1) + BT_TESTS, + -signal.SIGABRT, expected_msg) + ) + + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + compiler = shlex.split(os.environ.get("CC", "cc")) + with tempfile.TemporaryDirectory(prefix="centauri-scan-test-") as directory: + out = args.out or Path(directory) + out.mkdir(parents=True, exist_ok=True) + for name, code, expected, msg in wifi_variants + bt_variants: + harness, binary = out / (name + ".c"), out / name + harness.write_text(code) + subprocess.run( + compiler + ["-std=gnu11", "-Wall", "-Wextra", "-Werror", + str(harness), "-o", str(binary)], + check=True, + ) + result = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + ".log")).write_text(result.stdout + result.stderr) + if result.returncode != expected or ( + expected and ("Assertion" not in result.stderr or msg not in result.stderr) + ): + raise RuntimeError( + f"{name}: exit {result.returncode}, expected {expected}\n" + + result.stdout + result.stderr + ) + print(f"{name}: {'PASS' if expected == 0 else 'correctly rejected'}") + + +if __name__ == "__main__": + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7cb81bda543cf6..5a264097519907 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -192,6 +192,7 @@ def mutations(flag, names, base, expect=KILL): 'brcmfmac-sleep-lifetime-tests.py': [([], PASS)], 'cio-native-tests.py': [(out('--output'), PASS)], 'centauri-wifi-pm-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], + 'centauri-scan-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-bt-arena-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-recovery-tests.py': [(out(), PASS), (out() + ['--negative-controls'], PASS)], 'centauri-physical-recovery-tests.py': [(out(), PASS)] From 3dccaef3af5978a3608d5691af276c6e55fc0883 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 25 Nov 2026 00:22:40 -0300 Subject: [PATCH 1236/1514] drm/asahi: g17: wait for the other engine's newest scheduled producer A command waits in its scheduler job for every unfinished command of the other engine that its prefix covers and that firmware orders it after: one scheduled fence each (EnqueueOrdering's firmware waits). Under Diablo IV that is a mean of about 400 dependencies per command, at about 21,700 commands per second. Past eight, the job waits on one fence that dma_fence_unwrap_merge() builds by sorting them all by context, and on an M4 Pro the submit thread spent 92-98% of a core in that ioctl, 60% of it in the sort, while the GPU was half idle. The sort finds nothing new. The scheduled fences all come from the other engine's one drm_sched entity, so they share a fence context and the newest stands for every earlier one: dma_fence_unwrap_merge(), and drm_sched_job_add_dependency() for eight or fewer, keep only the latest fence of each context. Pass only that one. The latest is kept by dma_fence_is_later(), not by the order producers come in, and a scheduled fence of another context is waited for rather than dropped, so the wait set stays the same even if the frontier's order or the entity ever changed. Firmware still orders the execution after every producer, and each producer's completion is still checked before the command publishes; host waits are unchanged. KUnit cases check that the latest scheduled fence is what a consumer waits for, whatever the order, and that a fence of another context is kept. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/dependency.rs | 108 ++++++++++++++++++++++++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 15 +++- drivers/gpu/drm/asahi/g17/sync_input.c | 12 +++ drivers/gpu/drm/asahi/g17/sync_input.h | 1 + drivers/gpu/drm/asahi/g17/sync_input.rs | 12 +++ 5 files changed, 144 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/dependency.rs b/drivers/gpu/drm/asahi/g17/dependency.rs index 5a0ed611b1ddee..239963302b18bd 100644 --- a/drivers/gpu/drm/asahi/g17/dependency.rs +++ b/drivers/gpu/drm/asahi/g17/dependency.rs @@ -138,6 +138,65 @@ impl Frontier { } } +/// How a fence orders against an earlier-held one ([`FenceOrder::order`]). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum FenceOrdering { + /// Same context, and it signals after the held one. + Later, + /// Same context, and it signals no later. + NotLater, + /// Another context: neither stands for the other. + OtherContext, +} + +/// A fence that can be ordered against another, as `dma_fence_is_later()` on a shared context. +pub(crate) trait FenceOrder { + fn order(&self, earlier: &Self) -> FenceOrdering; +} + +/// What a consumer's scheduler job must wait for from the scheduled fences of the unfinished +/// producers of the other engine that firmware orders it after. +/// +/// The scheduled fences all come from that engine's one drm_sched entity, so they share a fence +/// context and the latest stands for every earlier one: drm_sched_job_add_dependency() and +/// dma_fence_unwrap_merge() would keep only it anyway, after comparing every pair of them. The +/// latest is kept by comparison, so the order producers come in does not matter, and a scheduled +/// fence of another context is waited for instead of dropped. +pub(crate) struct ProducerWaits<'a, F> { + latest_scheduled: Option<&'a F>, +} + +impl<'a, F: FenceOrder> ProducerWaits<'a, F> { + pub(crate) const fn new() -> Self { + Self { latest_scheduled: None } + } + + /// The next producer's scheduled fence: `wait` gets a held one of another context. + pub(crate) fn producer( + &mut self, + scheduled: &'a F, + wait: impl FnOnce(&'a F) -> Result, + ) -> Result { + match self.latest_scheduled { + Some(held) => match scheduled.order(held) { + FenceOrdering::Later => self.latest_scheduled = Some(scheduled), + FenceOrdering::NotLater => {} + FenceOrdering::OtherContext => { + wait(held)?; + self.latest_scheduled = Some(scheduled); + } + }, + None => self.latest_scheduled = Some(scheduled), + } + Ok(()) + } + + /// After the last producer: `wait` gets the latest scheduled fence, if there was a producer. + pub(crate) fn finish(self, wait: impl FnOnce(&'a F) -> Result) -> Result { + self.latest_scheduled.map_or(Ok(()), wait) + } +} + #[kunit_tests(asahi_g17_dependency)] mod tests { use super::*; @@ -202,6 +261,55 @@ mod tests { assert_eq!(earliest(&mut record), None); } + /// A fence on context `.0` with seqno `.1`. + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + struct Mock(u32, u32); + + impl FenceOrder for Mock { + fn order(&self, earlier: &Self) -> FenceOrdering { + if self.0 != earlier.0 { + FenceOrdering::OtherContext + } else if self.1 > earlier.1 { + FenceOrdering::Later + } else { + FenceOrdering::NotLater + } + } + } + + fn waits(producers: &[Mock]) -> KVec { + let mut waited = KVec::new(); + let mut waits = ProducerWaits::new(); + for scheduled in producers { + waits + .producer(scheduled, |fence| { + waited.push(*fence, GFP_KERNEL).map_err(|_| ENOMEM) + }) + .unwrap(); + } + waits + .finish(|fence| waited.push(*fence, GFP_KERNEL).map_err(|_| ENOMEM)) + .unwrap(); + waited + } + + #[test] + fn a_consumer_waits_for_the_latest_scheduled_producer_only() { + assert!(waits(&[]).is_empty()); + let (s10, s11, s12) = (Mock(1, 10), Mock(1, 11), Mock(1, 12)); + assert_eq!(waits(&[s10]), [s10]); + assert_eq!(waits(&[s10, s11, s12]), [s12]); + // Whatever the order they come in. + assert_eq!(waits(&[s12, s10, s11]), [s12]); + } + + #[test] + fn a_scheduled_fence_of_another_context_is_waited_for() { + // A producer from another entity is not stood for by this one's fences. + let (a5, b7, b8) = (Mock(1, 5), Mock(2, 7), Mock(2, 8)); + assert_eq!(waits(&[a5, b7, b8]), [a5, b8]); + } + #[test] fn failed_predecessor_cannot_be_bypassed() { let mut frontier = Frontier::new(); diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 1c64f3839ae22d..1b995fb8507d46 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -329,9 +329,10 @@ impl Queue { } let failure_count = failures.iter().flatten().count(); let mut dependencies = KVec::with_capacity( + // The firmware-ordered producers add one scheduled fence between them. inputs.len() + ordering_host_waits.len() - + ordering_firmware_waits.len() + + usize::from(!ordering_firmware_waits.is_empty()) + failure_count, GFP_KERNEL, )?; @@ -349,10 +350,16 @@ impl Queue { dependencies.push(fence.clone(), GFP_KERNEL)?; checked_inputs.push(fence, GFP_KERNEL)?; } - for (scheduled, completed) in ordering_firmware_waits { - dependencies.push(scheduled, GFP_KERNEL)?; - firmware.push(completed, GFP_KERNEL)?; + // Firmware orders execution after each producer; the scheduler needs only the latest + // scheduled fence of them (dependency::ProducerWaits). + let mut producer_waits = super::dependency::ProducerWaits::new(); + for (scheduled, completed) in &ordering_firmware_waits { + producer_waits.producer(scheduled, |fence| { + Ok(dependencies.push(fence.clone(), GFP_KERNEL)?) + })?; + firmware.push(completed.clone(), GFP_KERNEL)?; } + producer_waits.finish(|fence| Ok(dependencies.push(fence.clone(), GFP_KERNEL)?))?; // Each command owns every input fence; independent engines may publish in // either order and must each consume an input's error status before running. for sync in inputs { diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 6c68414b49fd4d..7df8e01da2564c 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -147,3 +147,15 @@ struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t kfree(cursors); return merged; } + +/* + * How @a orders against @b: 1 when it signals after it on their shared + * context, 0 when not, -1 when they are on different contexts, which + * dma_fence_is_later() would warn about. + */ +int asahi_g17_fence_order(struct dma_fence *a, struct dma_fence *b) +{ + if (a->context != b->context) + return -1; + return dma_fence_is_later(a, b); +} diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 9fd39e223cf34d..9bd90b289de2c8 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -18,5 +18,6 @@ int asahi_g17_collect_fences_coalesced(struct dma_fence *head, size_t capacity); void asahi_g17_put_fence(struct dma_fence *fence); struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t count); +int asahi_g17_fence_order(struct dma_fence *a, struct dma_fence *b); #endif diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 4d7629a8ffe770..01f1d39790ca51 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -17,10 +17,22 @@ unsafe extern "C" { fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); + fn asahi_g17_fence_order(a: *mut bindings::dma_fence, b: *mut bindings::dma_fence) -> i32; fn asahi_g17_merge_fences(fences: *const *mut bindings::dma_fence, count: usize) -> *mut bindings::dma_fence; } +impl super::dependency::FenceOrder for Fence { + fn order(&self, earlier: &Self) -> super::dependency::FenceOrdering { + // SAFETY: Both fences are live references; the helper only reads them. + match unsafe { asahi_g17_fence_order(self.raw(), earlier.raw()) } { + 1 => super::dependency::FenceOrdering::Later, + 0 => super::dependency::FenceOrdering::NotLater, + _ => super::dependency::FenceOrdering::OtherContext, + } + } +} + /// One fence that signals once all of `fences` have (see `job::MERGED_DEPENDENCIES`). pub(super) fn merge(fences: &[Fence]) -> Result { let mut raw = KVec::with_capacity(fences.len(), GFP_KERNEL)?; From 0a57322c3aa32b1e24eb06a68453f18fd027a465 Mon Sep 17 00:00:00 2001 From: Julian Arango Date: Mon, 23 Nov 2026 04:02:44 +0000 Subject: [PATCH 1237/1514] mfd: macsmc: T6050: register the gP GPIO bank where the tree describes it On T6050 the SMC registers its input, power and hwmon cells, the PCIO and low GPIO banks and the described reboot and RTC cells. The gP bank (apple,smc-gpio) is only in the list for the other SoCs. The J716s's N1 port names its power line on that bank (pwren-gpios = <&smc_gpio 0x13 ...>), so pcie-apple's port probe waits for a GPIO provider that never appears: "Port /pcie@1cb0000000/pci@0,0 probe fail", deferred forever, and no PCIe device, Wi-Fi or Bluetooth. Register the gP bank with the T6050 described cells, under a cell name of its own ("macsmc-gpio" is the PCIO bank's; gpio-macsmc binds both by compatible). Only the J716s's tree describes the bank today, so no other T6050 board changes. Tested on one J716s (27.2 stub 26B123, omarchy-m5's v272-17 kernel with this change) with pwren-gpios kept in its tree: the gP bank registers ("First GPIO key: gP01"), pcie-apple probes the N1 port with no deferral, and Wi-Fi and Bluetooth come up. Signed-off-by: Julian Arango --- drivers/mfd/macsmc.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 35f86f9fe00273..1318c392f4c63d 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -86,12 +86,15 @@ static const struct mfd_cell apple_smc_described_devs[] = { /* * T6050's reboot/power-off and RTC, for a kernel that owns the machine (J775D, booted bare - * metal). Registered only where the device tree describes them, so a T6050 device tree without - * them registers what it did before. + * metal), and the gP GPIO bank, which carries the J716s's N1 power line (gP13, the pwren-gpios + * of its Wi-Fi/Bluetooth port). Registered only where the device tree describes them, so a T6050 + * device tree without them registers what it did before. The gP bank has a cell name of its own: + * "macsmc-gpio" is the PCIO bank's, and the driver binds both by compatible. */ static const struct mfd_cell apple_smc_t6050_described_devs[] = { MFD_CELL_OF("macsmc-reboot", NULL, NULL, 0, 0, "apple,smc-reboot"), MFD_CELL_OF("macsmc-rtc", NULL, NULL, 0, 0, "apple,smc-rtc"), + MFD_CELL_OF("macsmc-gp-gpio", NULL, NULL, 0, 0, "apple,smc-gpio"), }; static int apple_smc_add_described_devices(struct apple_smc *smc, const struct mfd_cell *cells, From 89d09f9f41ff9c85eba5b011efc3b6f09ce88762 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 01:20:29 +0700 Subject: [PATCH 1238/1514] HID: magicmouse: report only touching MTP contacts, in path-ID slots The high byte of a standard MTP record's first word is the contact's touch state and the low byte its firmware path ID. Decoded on a J815 (MacBook Air 15" M5, MTP firmware 6300.85.6) against macOS's own contact labels for the same frames, matched record by record on path ID, state, finger class and hand ID over 10 minutes of use. The states are 1 start in range, 2 hover in range, 3 make touch, 4 touching, 5 break touch, 6 linger in range, 7 out of range. A finger approaching or leaving the pad (states 1, 2, 5, 6) still has a position and nonzero sizes, so the touch-size test reports it as a touch: 374 such reports in the 10 minutes, each a hovering or lifting finger seen as a touch. Report only make touch and touching there; any other state is off the surface, including the zero-size state-0 records a pad sends between a contact going out of range and the next start under its path ID. The firmware keeps a contact under its path ID until it leaves the pad, so report each contact in that ID's slot instead of matching by distance, which hands a slot over when one finger lifts as another lands nearby in the same frame (two or more contacts landed in one frame about 100 times in the 10 minutes). The slot is looked up inside the report loop, so contacts landing in the same frame get different free slots; the MTP slots are set up with INPUT_MT_DROP_UNUSED, which releases the slot of a path ID that is gone. The firmware also reuses a path ID for a new contact in the report right after the old one goes out of range (40 times in the 10 minutes), so an out-of-range record no longer keeps the palm mark of its ID. The trackpad node's apple,touch-states selects this, so it follows the trackpad's firmware rather than the machine: the J815 has it, and the J813 (the same firmware family on the same SoC, not checked yet) or a later board only needs the property. Signed-off-by: Nick --- drivers/hid/hid-magicmouse.c | 75 +++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 712c3ae5d78acd..3807eb9d3c68d4 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -280,6 +280,9 @@ struct effect_job { * as a palm whatever its tool area (J813, J815). * @mtp_palm_classed: MTP contact IDs the controller classed as palms in the * previous report. + * @mtp_states: Whether the standard MTP records' touch states are trusted: + * only contacts on the surface are reported, each in the slot + * of its firmware path ID (apple,touch-states). * @ntouches: Number of touches in most recent touch report. * @scroll_accel: Number of consecutive scroll motions. * @scroll_jiffies: Time of last scroll motion. @@ -316,6 +319,7 @@ struct magicmouse_sc { DECLARE_BITMAP(mtp_palm_ids, U8_MAX + 1); bool mtp_palm_debounce; DECLARE_BITMAP(mtp_palm_classed, U8_MAX + 1); + bool mtp_states; int ntouches; int scroll_accel; @@ -1014,6 +1018,43 @@ static u8 magicmouse_mtp_contact_id(const struct tp_finger *f) return le16_to_cpu(f->unknown1) & 0xff; } +/* + * The high byte of a standard MTP record's first word is the contact's + * touch state. Decoded on a J815 (MTP firmware 6300.85.6) against macOS's + * own contact labels for the same frames (matched by path ID, state, finger + * and hand ID on every record): 1 start in range, + * 2 hover in range, 3 make touch, 4 touching, 5 break touch, 6 linger in + * range, 7 out of range. A finger approaching or leaving the pad (1, 2, 5, + * 6) still has a position and nonzero sizes, so the touch-size test alone + * reports it as a touch; only make touch and touching are on the surface. + * Any other state, including the zero-size records in state 0 that the J813 + * sends between a contact's out of range and the next start under its path + * ID, is off the surface. + */ +#define MAGICMOUSE_MTP_STATE_MAKE_TOUCH 3 +#define MAGICMOUSE_MTP_STATE_TOUCHING 4 +#define MAGICMOUSE_MTP_STATE_OUT_OF_RANGE 7 + +static u8 magicmouse_mtp_state(const struct tp_finger *f) +{ + return le16_to_cpu(f->unknown1) >> 8; +} + +static bool magicmouse_mtp_on_surface(const struct magicmouse_sc *msc, + const struct tp_finger *f) +{ + if (msc->mtp_states) { + switch (magicmouse_mtp_state(f)) { + case MAGICMOUSE_MTP_STATE_MAKE_TOUCH: + case MAGICMOUSE_MTP_STATE_TOUCHING: + break; + default: + return false; + } + } + return le16_to_int(f->touch_major) != 0; +} + /* * The J813 (MacBook Air 13" M5) controller classes contacts the same way, but * most of its palms stay below the classed tool area above: recorded on a J813 @@ -1041,6 +1082,14 @@ static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, id = magicmouse_mtp_contact_id(f); class = le16_to_cpu(f->unknown2) & 0xff; tool = le16_to_int(f->tool_major); + /* + * Out of range ends the contact; the firmware may reuse its + * path ID for a new contact in the very next report (40 times + * in 10 minutes on a J815), which must not inherit the palm. + */ + if (msc->mtp_states && + magicmouse_mtp_state(f) == MAGICMOUSE_MTP_STATE_OUT_OF_RANGE) + continue; palm_class = class >= MAGICMOUSE_MTP_PALM_CLASS_MIN; if (palm_class) __set_bit(id, classed); @@ -1344,7 +1393,7 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, n = 0; for (i = 0; i < tp_hdr->num_fingers; i++) { f = (struct tp_finger *)(data + hdr_sz + i * touch_sz); - if (!msc->mtp_c1fe && le16_to_int(f->touch_major) == 0) + if (!msc->mtp_c1fe && !magicmouse_mtp_on_surface(msc, f)) continue; hid_dbg(hdev, "ev x:%04x y:%04x\n", le16_to_int(f->abs_x), @@ -1355,11 +1404,27 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, n++; } - input_mt_assign_slots(input, msc->tracking_ids, msc->pos, n, 0); + if (!msc->mtp_states) + input_mt_assign_slots(input, msc->tracking_ids, msc->pos, n, 0); for (i = 0; i < n; i++) { int idx = map_contacs[i]; + f = (struct tp_finger *)(data + hdr_sz + idx * touch_sz); + if (msc->mtp_states) { + /* + * The firmware tracks each contact under a path ID + * until it leaves the pad, so keep it in that ID's + * slot: matching by distance hands a slot over when one + * finger lifts as another lands in the same frame. Look + * the slot up just before reporting it, so contacts + * landing in the same frame get different free slots. + */ + msc->tracking_ids[i] = + input_mt_get_slot_by_key(input, magicmouse_mtp_contact_id(f)); + if (msc->tracking_ids[i] < 0) + continue; + } if (msc->mtp_c1fe) { report_c1fe_finger_data(input, msc->tracking_ids[i], &msc->pos[i]); } else { @@ -2919,6 +2984,12 @@ static int magicmouse_probe(struct hid_device *hdev, msc->mtp_palm_debounce || (!msc->mtp_c1fe && of_machine_is_compatible("apple,j616s")); + /* + * The record's touch state and path ID (decoded on a J815 + * against macOS) are a property of the trackpad's firmware. + */ + msc->mtp_states = !msc->mtp_c1fe && + of_property_read_bool(np, "apple,touch-states"); of_node_put(np); /* From 7ca67b9f156deb3458186336eccd1d83c1b01f71 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 01:20:55 +0700 Subject: [PATCH 1239/1514] HID: magicmouse: give the J815 trackpad its own palm rule, from its DT node The previous J815 commit took the J813's rule: two consecutive palm classes (6 and above) mark a palm whatever its tool area. Checked against macOS's own labels for the same contacts (10 minutes of typing with resting palms, pointing, scrolling and gestures, 607 contacts, 34 of them hands), that rule marked two finger contacts as palms until they lifted, 966 finger reports lost: a finger-sized contact in the bottom-left corner whose class flickered between 10 and 12; a finger whose class flipped between 3 and 7 for up to 17 reports, with a tool area up to 1606. Class 10 is not a hand on the J815; its hand classes are 6, 7, 8 and 12. Mark a contact as a palm when a hand class comes with a tool area above 1200 on two consecutive reports: no finger contact and 33 of the 34 hands on the macOS session. 1400 missed 4 of 25 palms resting while typing on Linux (they peaked at 1325-1400); 1100 would mark one finger of the macOS session. Some resting palms are never classed as hands: in one Linux typing run two of them, 28 and 38 mm wide, stayed fingers for 0.6 s and one of them made a click. No finger or thumb contact on the surface passed a tool area of 2097 on macOS, while 21 of the 34 hands passed 2200, so a contact on the surface wider than that is a palm at once, whatever its class. Only on the surface: a thumb's start-in-range record had a tool area of 2428, and the mark would have stayed for its 35 touching reports. With both tests, the macOS session gives 33 of 34 hands, no finger, and 8 hand reports before the mark (18 with the class test alone). The 2200 margin comes from one 10-minute macOS session and Linux runs on the same machine; on Linux, fingers reached 1879 (99th percentile). Both rules are selected by the trackpad node instead of the machine compatible: apple,palm-debounce for the J813 rule, and apple,palm-tool-area for this one, whose two values are the pad's own thresholds (1200 and 2200 on the J815), so another board with the same controller gets either rule from its device tree. A swapped apple,palm-tool-area (first value not below the second), or a value above 32767, is warned about at probe and leaves the rule off. The record's tool area is a signed 16-bit field, and the thresholds are kept as int so that a raw field with bit 15 set compares as negative, not as a huge unsigned value that would mark a palm. Signed-off-by: Nick --- drivers/hid/hid-magicmouse.c | 84 ++++++++++++++++++++++++++++++++---- 1 file changed, 75 insertions(+), 9 deletions(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 3807eb9d3c68d4..48ab50a5aae851 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -273,13 +273,18 @@ struct effect_job { * @tp26_button: Button state of the last Trackpad26 frame. * @mtp_c1fe: Whether the MTP trackpad sends the J700 C1FE report layout. * @mtp_palms: Whether the controller's contact classes are trusted for palms - * on the standard MTP report (T6041, J616s, J813). + * on the standard MTP report (T6041, J616s, J813, J815). * @mtp_palm_size: Whether a tool area alone marks an MTP contact as a palm. * @mtp_palm_ids: MTP contact IDs reported as palms until they lift. * @mtp_palm_debounce: Whether two consecutive palm classes mark an MTP contact - * as a palm whatever its tool area (J813, J815). + * as a palm whatever its tool area (apple,palm-debounce). * @mtp_palm_classed: MTP contact IDs the controller classed as palms in the * previous report. + * @mtp_palm_large: Whether only hand classes with a palm-sized tool area, on + * two consecutive reports, or a tool area wider than any + * finger mark an MTP contact as a palm (apple,palm-tool-area). + * @mtp_palm_area: The two tool areas of apple,palm-tool-area: hand-class palm + * size, and the size wider than any finger. * @mtp_states: Whether the standard MTP records' touch states are trusted: * only contacts on the surface are reported, each in the slot * of its firmware path ID (apple,touch-states). @@ -319,6 +324,8 @@ struct magicmouse_sc { DECLARE_BITMAP(mtp_palm_ids, U8_MAX + 1); bool mtp_palm_debounce; DECLARE_BITMAP(mtp_palm_classed, U8_MAX + 1); + bool mtp_palm_large; + int mtp_palm_area[2]; bool mtp_states; int ntouches; @@ -1064,7 +1071,37 @@ static bool magicmouse_mtp_on_surface(const struct magicmouse_sc *msc, * counts as a palm once two consecutive reports class it as one. That caught * all 370 palms by their second report, and one finger, classed a palm for its * last reports while lifting. + * + * On the J815 (MacBook Air 15" M5) the controller's classes were checked + * against macOS's own labels on 607 contacts (10 minutes of typing with + * resting palms, pointing, scrolling, gestures; 34 contacts mostly classed + * 6, 7, 8 or 12, the hand classes). Two contacts that were mostly classed as + * fingers were marked as palms until they lifted by the J813 rule (966 + * finger reports lost): a finger-sized one in the bottom-left corner, + * flickering between classes 10 and 12, and one whose class flipped between + * 3 and 7 for up to 17 reports with a tool area up to 1606. Requiring a hand + * class with a tool area above 1200 on two consecutive reports marked no + * finger-classed contact and 33 of the 34 hand contacts. With 1400, palms + * resting while typing on Linux peaked at 1325-1400 and were missed (4 of 25); + * at 1100, one finger in the macOS session would be marked. + * + * Some resting palms are never classed as hands (two in one typing run on + * Linux, 28 and 38 mm wide, reported as fingers for 0.6 s). On macOS no + * finger or thumb contact passed a tool area of 2097, while 21 of the 34 + * hands passed 2200, 11 of them in their first report, so a contact wider + * than that on the surface is a palm at once, whatever its class. A finger + * coming into range can be wider: a thumb's start-in-range record had a tool + * area of 2428, and the mark would have stayed for its 35 touching reports. + * + * The two areas are the pad's own (apple,palm-tool-area = <1200 2200> on the + * J815); the hand classes are the controller's. */ + +static bool magicmouse_mtp_hand_class(u8 class) +{ + return (class >= 6 && class <= 8) || class == 12; +} + static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, const u8 *records, int count) { @@ -1090,6 +1127,18 @@ static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, if (msc->mtp_states && magicmouse_mtp_state(f) == MAGICMOUSE_MTP_STATE_OUT_OF_RANGE) continue; + if (msc->mtp_palm_large) { + palm_class = magicmouse_mtp_hand_class(class) && + tool > msc->mtp_palm_area[0]; + if (palm_class) + __set_bit(id, classed); + if ((palm_class && test_bit(id, msc->mtp_palm_classed)) || + (tool > msc->mtp_palm_area[1] && + magicmouse_mtp_on_surface(msc, f)) || + test_bit(id, msc->mtp_palm_ids)) + __set_bit(id, palms); + continue; + } palm_class = class >= MAGICMOUSE_MTP_PALM_CLASS_MIN; if (palm_class) __set_bit(id, classed); @@ -1852,7 +1901,7 @@ static int magicmouse_setup_input_mtp(struct input_dev *input, J314_TP_MAX_FINGER_ORIENTATION, 0, 0); } - /* The T6041, J616s, J813 and Trackpad26 controllers classify palms. */ + /* The T6041, J616s, J813, J815 and Trackpad26 controllers classify palms. */ if (msc->mtp_palms || msc->mtp_tp26) input_set_abs_params(input, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0); @@ -2961,6 +3010,7 @@ static int magicmouse_probe(struct hid_device *hdev, // conflicts with the report ID. if (id->bus == BUS_HOST) { struct device_node *np; + u32 palm_area[2]; /* The J700 trackpad sends a different report layout. */ np = of_get_child_by_name(dev_of_node(hdev->dev.parent), "multi-touch"); @@ -2968,20 +3018,36 @@ static int magicmouse_probe(struct hid_device *hdev, msc->mtp_palm_size = !msc->mtp_c1fe && of_machine_is_compatible("apple,t6041"); /* - * The J813 controller classes contacts the same way, and two - * consecutive palm classes mark its palms. The J815 (15-inch) - * sends the same standard report from its own, larger pad. + * The J813 and J815 controllers class contacts the same way; + * the trackpad node says which palm rule its pad takes: two + * consecutive palm classes (J813), or hand classes with the + * pad's own tool areas (J815, checked against macOS's labels). */ msc->mtp_palm_debounce = !msc->mtp_c1fe && - (of_machine_is_compatible("apple,j813") || - of_machine_is_compatible("apple,j815")); + of_property_read_bool(np, "apple,palm-debounce"); + msc->mtp_palm_large = !msc->mtp_c1fe && + !of_property_read_u32_array(np, "apple,palm-tool-area", + palm_area, 2); + /* + * The record's tool area is a signed 16-bit field, compared + * as an int: a larger value could never be passed. + */ + if (msc->mtp_palm_large && + (palm_area[0] >= palm_area[1] || palm_area[1] > S16_MAX)) { + hid_warn(hdev, "apple,palm-tool-area %u %u: the first must be below the second, and both at most %d, rule off\n", + palm_area[0], palm_area[1], S16_MAX); + msc->mtp_palm_large = false; + } else if (msc->mtp_palm_large) { + msc->mtp_palm_area[0] = palm_area[0]; + msc->mtp_palm_area[1] = palm_area[1]; + } /* * The J616s controller classes contacts the same way, but its * fingers reach a tool area of 2475, so only the class marks its * palms there. */ msc->mtp_palms = msc->mtp_palm_size || - msc->mtp_palm_debounce || + msc->mtp_palm_debounce || msc->mtp_palm_large || (!msc->mtp_c1fe && of_machine_is_compatible("apple,j616s")); /* From 3b306725fbe7bbf100c106b942f78dbf1eefa3d0 Mon Sep 17 00:00:00 2001 From: Nick Date: Sat, 21 Nov 2026 03:00:23 +0700 Subject: [PATCH 1240/1514] HID: magicmouse: leave a resting hand's force out of the J815 click The J815's MTP click is derived on the host from the summed contact force. A palm resting while typing presses hard enough to reach the press threshold on its own: in one Linux typing run all 4 clicks came from palms (3 with only palm-marked contacts on the pad, summed force 121-139 against the press threshold of 120; 1 from a 27 mm contact in its first report, before the palm mark). On macOS a resting hand neither clicks nor moves the pointer, while a finger of the other hand still clicks and Force Clicks. Leave out the force of every hand contact, with the same tests as the palm rule and the pad's apple,palm-tool-area values: one marked as a palm, one in a hand class past the first value (1200 on the J815) already in its first report (the palm mark waits for a second one), and one on the surface wider than any finger (past the second value, 2200). On the J815, two A/B runs of pointing, typing, and pointing and clicking with the other hand while a palm rests (each click attributed from the evdev trace: a hand is a palm-marked contact or one above 2200): with this change, 59 of 59 clicks reached the press threshold on the fingers' force alone. With the previous commits' palm marking but without this change, 49 of 58 clicks did not: 10 with no finger on the pad, 39 with fingers whose own force stayed below the threshold. The two builds also differ in the 2200 test, and no palm-made click was felt with this one. Signed-off-by: Nick --- drivers/hid/hid-magicmouse.c | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index 48ab50a5aae851..7d7b7266b2b5b2 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -1102,6 +1102,24 @@ static bool magicmouse_mtp_hand_class(u8 class) return (class >= 6 && class <= 8) || class == 12; } +/* + * A hand on a pad with apple,palm-tool-area, for the host-derived click: a + * contact marked as a palm, or one in a hand class past the palm tool area + * already in its first report (the palm mark waits for a second one), or one + * on the surface wider than any finger. + */ +static bool magicmouse_mtp_hand(const struct magicmouse_sc *msc, + const struct tp_finger *f) +{ + int tool = le16_to_int(f->tool_major); + + /* The same tests as magicmouse_mtp_update_palms(), without the wait. */ + return test_bit(magicmouse_mtp_contact_id(f), msc->mtp_palm_ids) || + (tool > msc->mtp_palm_area[1] && magicmouse_mtp_on_surface(msc, f)) || + (magicmouse_mtp_hand_class(le16_to_cpu(f->unknown2) & 0xff) && + tool > msc->mtp_palm_area[0]); +} + static void magicmouse_mtp_update_palms(struct magicmouse_sc *msc, const u8 *records, int count) { @@ -1484,7 +1502,15 @@ static int magicmouse_raw_event_mtp(struct hid_device *hdev, tool = MT_TOOL_PALM; report_finger_data(input, msc->tracking_ids[i], &msc->pos[i], f, tool); - pressure += le16_to_int(f->pressure); + /* + * J815: a resting palm presses hard enough to reach the + * click threshold on its own. As on macOS, a resting + * hand neither clicks nor deepens a click, while a + * finger of the other hand still does: the hand's own + * force never counts. + */ + if (!(msc->mtp_palm_large && magicmouse_mtp_hand(msc, f))) + pressure += le16_to_int(f->pressure); } } From 855f86267e46ddccebafc2e6bc81c15e4d02bd02 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 14 Nov 2026 00:46:55 +1100 Subject: [PATCH 1241/1514] drm/apple: admit the M1/M2/M3 display processors on firmware 27.2 The T8103, T600x, T8112, T602x, T8122, T6030 and T603x display processors share one firmware-27 wire generation with the T6050: the same IOMobileFramebuffer method numbering, AFK wire v2 and v27 drive record. On exact firmware-compat 27.2.0 they should run that generation instead of the 14.7-era session the boot loader previously handed them. Give each of these processors' DCP and dcpext a version-aware firmware-27 admission. dcp_check_firmware_version() now selects DCP_FIRMWARE_V_27_0 with the in-tree 27.2.0 method table before the 14.7 board and special-profile checks, so the T8122 and T6030 14.7-only rejections no longer apply to the 27.2 arm. The older admissions stay in place unchanged for the firmware those boards still boot, and the probe keeps each processor's port count, tunnel-flow flag, connector topology, DMA width and DART resources from its own match data; only the live-session adoption is version-selected. The shared v27 method-table validation is factored into one helper reused by both firmware-27 arms. Add an apple-dcp-v27 KUnit suite covering which compatibles the admission recognises, that the non-refmac firmware-27 processors keep their own paths, and that the 27.2.0 method table is complete. Signed-off-by: Ryan Murray [Dj: rebased onto main, using main's dcp_v27_method_table() and keeping adoption ahead of main's per-SoC firmware-27 profiles.] Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/Makefile | 1 + drivers/gpu/drm/apple/dcp.c | 56 ++++++++++++ drivers/gpu/drm/apple/dcp.h | 7 ++ drivers/gpu/drm/apple/iomfb_v27_test.c | 117 +++++++++++++++++++++++++ 4 files changed, 181 insertions(+) create mode 100644 drivers/gpu/drm/apple/iomfb_v27_test.c diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index c040f80df8e80e..a6521dc75b9e77 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -23,6 +23,7 @@ appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += t8152_hdmi.o t8152_typec.o appledrm-$(CONFIG_DRM_APPLE_DCP_T8152) += iomfb_iboot.o iboot_drm.o appledrm-y += iomfb_h17p.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_h17p_test.o parser_test.o +appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_v27_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += iomfb_external_hdr_hints_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += apple_resume_test.o appledrm-$(CONFIG_DRM_APPLE_KUNIT_TEST) += apple_boot_display_test.o diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4e48c4574624f2..c6771cfbf9a2ec 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6178,6 +6178,40 @@ static bool dcp_v27_sleep_transport_supported(struct apple_dcp *dcp) return iomfb_v27_sleep_methods_complete(dcp->v27_methods); } +/* + * The M1/M2/M3 display processors share the T6050 firmware-27 wire generation. + * @compat_is answers whether a device node carries a compatible string, so the + * same list is used by probe and by the host test. + */ +bool dcp_refmac_v27_compat(dcp_compat_fn compat_is, const void *ctx) +{ + static const char * const compats[] = { + "apple,t8103-dcp", "apple,t8103-dcpext", + "apple,t6000-dcp", "apple,t6000-dcpext", + "apple,t8112-dcp", "apple,t8112-dcpext", + "apple,t6020-dcp", "apple,t6020-dcpext", + "apple,t8122-dcp", "apple,t8122-dcpext", + "apple,t6030-dcp", "apple,t6030-dcpext", + "apple,t6031-dcp", "apple,t6031-dcpext", + }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(compats); i++) + if (compat_is(ctx, compats[i])) + return true; + return false; +} + +static bool dcp_node_compat_is(const void *np, const char *compat) +{ + return of_device_is_compatible(np, compat); +} + +static bool dcp_node_is_refmac_v27(const struct device_node *np) +{ + return dcp_refmac_v27_compat(dcp_node_compat_is, np); +} + /* * Firmware 27, if firmware-compat @compat_str has a 27.x method table with an * ID for every method the driver calls: the firmware panics on an unknown tag. @@ -6236,6 +6270,19 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); } + /* + * The M1/M2/M3 processors are one firmware-27 wire generation with the + * T6050. On exact firmware-compat 27.2.0 they run that generation, so + * admit it before the 14.7 board and special-profile paths below. The + * older admissions stay in place for the firmware those boards still + * boot. + */ + if (dcp_node_is_refmac_v27(dev->of_node)) { + ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); + if (ret >= 0 && !strcmp(compat_str, "27.2.0")) + return dcp_v27_method_table(dev, compat_str); + } + if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { @@ -7994,6 +8041,15 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; + /* + * An M1/M2/M3 processor on firmware 27 inherits the live session the + * boot loader handed over, like the T6050. Its match data keeps the + * per-SoC port count, tunnel-flow flag and DART resources; only the + * firmware-27 session adoption is version-selected here, before the + * per-SoC firmware-27 profiles below, which may override it. + */ + if (fw_compat == DCP_FIRMWARE_V_27_0 && dcp_node_is_refmac_v27(dev->of_node)) + dcp->hw.adopt_live_session = true; /* * T6041 internal panel on firmware 27 adopts the running DCP session * with 41-bit firmware DMA addressing and no DPTX port services, diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 6c1c258c3c54e1..171eda68c817d4 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -94,6 +94,13 @@ bool dcp_fw_compat_is_desktop(struct platform_device *pdev); bool dcp_panel_edr(struct platform_device *pdev); bool dcp_ext_color_props_supported(struct platform_device *pdev); unsigned int dcp_gamma_lut_size(struct platform_device *pdev); +/* + * The M1/M2/M3 display processors admitted into the firmware-27 wire + * generation. @compat_is answers whether a context (a device node in the + * driver, a fixture in the test) carries a compatible string. + */ +typedef bool (*dcp_compat_fn)(const void *ctx, const char *compat); +bool dcp_refmac_v27_compat(dcp_compat_fn compat_is, const void *ctx); /* T6041 external display processors may join the DRM device. */ bool dcp_t6041_ext_enabled(void); void dcp_backlight_takeover_registered(struct platform_device *pdev); diff --git a/drivers/gpu/drm/apple/iomfb_v27_test.c b/drivers/gpu/drm/apple/iomfb_v27_test.c new file mode 100644 index 00000000000000..6ca01f3436f957 --- /dev/null +++ b/drivers/gpu/drm/apple/iomfb_v27_test.c @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Aurora Silicon */ + +/* + * The M1/M2/M3 display processors are admitted into the firmware-27 wire + * generation on exact firmware-compat 27.2.0, sharing the T6050 method table. + * These tests cover which compatibles that admission recognises and that the + * 27.2.0 method table is complete, so a recognised processor starts. + */ + +#include +#include +#include + +#include "dcp.h" +#include "iomfb.h" +#include "iomfb_v27.h" + +/* A fixture node: the compatible strings the device tree would carry. */ +struct refmac_node { + const char *const *compats; /* NULL-terminated */ +}; + +static bool refmac_node_compat_is(const void *ctx, const char *compat) +{ + const struct refmac_node *node = ctx; + const char *const *c; + + for (c = node->compats; *c; c++) + if (!strcmp(*c, compat)) + return true; + return false; +} + +static bool refmac_admits(const char *const *compats) +{ + const struct refmac_node node = { .compats = compats }; + + return dcp_refmac_v27_compat(refmac_node_compat_is, &node); +} + +/* Both the per-SoC and the generic compatible of each refmac node. */ +static const char *const t8103_dcp[] = { "apple,t8103-dcp", "apple,dcp", NULL }; +static const char *const t8103_dcpext[] = { "apple,t8103-dcpext", "apple,dcpext", NULL }; +static const char *const t6000_dcp[] = { "apple,t6000-dcp", "apple,dcp", NULL }; +static const char *const t6000_dcpext[] = { "apple,t6000-dcpext", "apple,dcpext", NULL }; +static const char *const t8112_dcp[] = { "apple,t8112-dcp", "apple,dcp", NULL }; +static const char *const t8112_dcpext[] = { "apple,t8112-dcpext", "apple,dcpext", NULL }; +static const char *const t6020_dcp[] = { "apple,t6020-dcp", "apple,dcp", NULL }; +static const char *const t6020_dcpext[] = { "apple,t6020-dcpext", "apple,dcpext", NULL }; +static const char *const t8122_dcp[] = { "apple,t8122-dcp", "apple,dcp", NULL }; +static const char *const t8122_dcpext[] = { "apple,t8122-dcpext", "apple,dcpext", NULL }; +static const char *const t6030_dcp[] = { "apple,t6030-dcp", "apple,dcp", NULL }; +static const char *const t6030_dcpext[] = { "apple,t6030-dcpext", "apple,dcpext", NULL }; +static const char *const t6031_dcp[] = { "apple,t6031-dcp", "apple,dcp", NULL }; +static const char *const t6031_dcpext[] = { "apple,t6031-dcpext", "apple,dcpext", NULL }; + +static void v27_refmac_admits_test(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, refmac_admits(t8103_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t8103_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6000_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6000_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t8112_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t8112_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6020_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6020_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t8122_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t8122_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6030_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6030_dcpext)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6031_dcp)); + KUNIT_EXPECT_TRUE(test, refmac_admits(t6031_dcpext)); +} + +/* The T6050 and T8142 keep their own firmware-27 paths; T6041 and M4 do not. */ +static const char *const t6050_dcp[] = { "apple,t6050-dcp", NULL }; +static const char *const t8142_dcp[] = { "apple,t8142-dcp", NULL }; +static const char *const t6041_dcp[] = { "apple,t6041-dcp", "apple,dcpext", NULL }; +static const char *const t8140_dcp[] = { "apple,t8140-dcp", NULL }; + +static void v27_refmac_rejects_test(struct kunit *test) +{ + KUNIT_EXPECT_FALSE(test, refmac_admits(t6050_dcp)); + KUNIT_EXPECT_FALSE(test, refmac_admits(t8142_dcp)); + KUNIT_EXPECT_FALSE(test, refmac_admits(t6041_dcp)); + KUNIT_EXPECT_FALSE(test, refmac_admits(t8140_dcp)); +} + +/* The 27.2.0 table a recognised processor runs is complete, so it may start. */ +static void v27_method_table_test(struct kunit *test) +{ + const struct dcp_method_entry *methods; + unsigned int missing; + + methods = iomfb_v27_methods("27.2.0"); + KUNIT_ASSERT_NOT_NULL(test, methods); + KUNIT_EXPECT_PTR_EQ(test, iomfb_v27_missing_method(methods, &missing), NULL); + KUNIT_EXPECT_EQ(test, missing, 0U); + KUNIT_EXPECT_PTR_EQ(test, iomfb_v27_methods("27.1.0"), NULL); +} + +static struct kunit_case v27_cases[] = { + KUNIT_CASE(v27_refmac_admits_test), + KUNIT_CASE(v27_refmac_rejects_test), + KUNIT_CASE(v27_method_table_test), + {} +}; + +static struct kunit_suite v27_suite = { + .name = "apple-dcp-v27", + .test_cases = v27_cases, +}; + +kunit_test_suite(v27_suite); + +MODULE_LICENSE("Dual MIT/GPL"); From 65ff2bc384a9b971efc1ddfc83cfb8238be4190d Mon Sep 17 00:00:00 2001 From: Ryan <81541646+RyanTheTide@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:42:38 +1100 Subject: [PATCH 1242/1514] drm/apple: select firmware 27 by the firmware the DCP reports Firmware 27 was admitted three ways: T6050 by its match data, T8142 by its compatible on exact 27.0.0, and the M1/M2/M3 processors through a list of fourteen DCP and dcpext compatibles on exact 27.2.0. The deciding facts are the same everywhere: the DCP reports firmware-compat 27 or later, and the driver has a complete method table for that build. Replace the compatible list and the T8142 arm with one helper, dcp_v27_admission(), used for every DCP and dcpext before any per-SoC selection. A firmware-compat of 27 or later runs the firmware-27 instance when iomfb_v27_methods() has a complete table for the build, and is not started otherwise: the interfaces written for older firmware make it panic (T8142 on 27.0 with H17P). Older firmware keeps the existing 26.x, 14.x and 13.x selection unchanged. Every processor on firmware 27 adopts the live session the loader handed over. What stays per SoC has a hardware reason: the T6050 has no interface older than firmware 27; the T8140 dcpext is refused before selection on anything but 26.6.2; T8142 on firmware 27 keeps the default method profile, since with H17G every swap fails with status 4. This also admits T6041, T8132, T8140 and T8142 on firmware 27 builds with a complete table (T8142 newly on 27.2.0); none has been run on 27.2. The T8140's method profile on firmware 27 is left to a separate change. Rewrite the apple-dcp-v27 KUnit suite for the rule: complete 27.x tables are admitted, 27.x and later builds without a usable table are refused, older firmware is left to the older selection. Signed-off-by: Ryan [Dj: rebased onto main: main's T8142 and T8122 firmware-27 arms are kept ahead of dcp_firmware_27(), which reports a refused build through main's dcp_v27_method_table(); the blanket adoption comes before main's per-SoC firmware-27 profiles, so the T8122 dcpext still starts cold.] Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp.c | 115 ++++++++++++----------- drivers/gpu/drm/apple/dcp.h | 20 ++-- drivers/gpu/drm/apple/iomfb_v27_test.c | 124 +++++++++---------------- 3 files changed, 122 insertions(+), 137 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index c6771cfbf9a2ec..1c68499311d27a 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6178,40 +6178,6 @@ static bool dcp_v27_sleep_transport_supported(struct apple_dcp *dcp) return iomfb_v27_sleep_methods_complete(dcp->v27_methods); } -/* - * The M1/M2/M3 display processors share the T6050 firmware-27 wire generation. - * @compat_is answers whether a device node carries a compatible string, so the - * same list is used by probe and by the host test. - */ -bool dcp_refmac_v27_compat(dcp_compat_fn compat_is, const void *ctx) -{ - static const char * const compats[] = { - "apple,t8103-dcp", "apple,t8103-dcpext", - "apple,t6000-dcp", "apple,t6000-dcpext", - "apple,t8112-dcp", "apple,t8112-dcpext", - "apple,t6020-dcp", "apple,t6020-dcpext", - "apple,t8122-dcp", "apple,t8122-dcpext", - "apple,t6030-dcp", "apple,t6030-dcpext", - "apple,t6031-dcp", "apple,t6031-dcpext", - }; - unsigned int i; - - for (i = 0; i < ARRAY_SIZE(compats); i++) - if (compat_is(ctx, compats[i])) - return true; - return false; -} - -static bool dcp_node_compat_is(const void *np, const char *compat) -{ - return of_device_is_compatible(np, compat); -} - -static bool dcp_node_is_refmac_v27(const struct device_node *np) -{ - return dcp_refmac_v27_compat(dcp_node_compat_is, np); -} - /* * Firmware 27, if firmware-compat @compat_str has a 27.x method table with an * ID for every method the driver calls: the firmware panics on an unknown tag. @@ -6237,12 +6203,64 @@ static enum dcp_firmware_version dcp_v27_method_table(struct device *dev, return DCP_FIRMWARE_V_27_0; } +/* + * Firmware 27 is selected by the ABI the DCP reports, the same on every SoC: + * a DCP or dcpext whose firmware-compat is 27 or later runs the common + * firmware-27 instance with the method table of that build. The interfaces + * written for older firmware make it panic (T8142 on 27.0 with H17P: "ap_link: + * callback failed with: 0x5"), so a 27 or later build without a complete + * table is not started at all. Pure, so the host test runs the same rule. + */ +enum dcp_v27_admission dcp_v27_admission(const char *compat, + const struct dcp_method_entry **methods, + const char **missing, + unsigned int *num_missing) +{ + unsigned int major; + + *methods = NULL; + *missing = NULL; + *num_missing = 0; + if (sscanf(compat, "%u.", &major) != 1 || major < 27) + return DCP_V27_NOT_V27; + *methods = iomfb_v27_methods(compat); + if (!*methods) + return DCP_V27_NO_TABLE; + *missing = iomfb_v27_missing_method(*methods, num_missing); + if (*missing) + return DCP_V27_INCOMPLETE; + return DCP_V27_ADMITTED; +} + +/* + * Returns true if the DCP reports firmware 27 or later, with @version the + * firmware-27 instance or DCP_FIRMWARE_UNKNOWN if this build cannot be started. + */ +static bool dcp_firmware_27(struct device *dev, + enum dcp_firmware_version *version) +{ + char compat[DCP_FW_VERSION_STR_LEN]; + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + if (dcp_read_fw_version(dev, "apple,firmware-compat", compat) < 0) + return false; + if (dcp_v27_admission(compat, &methods, &missing, &num_missing) == + DCP_V27_NOT_V27) + return false; + /* Logs why a build without a complete table is not started. */ + *version = dcp_v27_method_table(dev, compat); + return true; +} + static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) { const struct apple_dcp_hw_data *hw = of_device_get_match_data(dev); const struct dcp_v14_board *v14_board; char compat_str[DCP_FW_VERSION_STR_LEN]; char fw_str[DCP_FW_VERSION_STR_LEN]; + enum dcp_firmware_version version; int ret; /* @@ -6270,19 +6288,10 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return dcp_v27_method_table(dev, compat_str); } - /* - * The M1/M2/M3 processors are one firmware-27 wire generation with the - * T6050. On exact firmware-compat 27.2.0 they run that generation, so - * admit it before the 14.7 board and special-profile paths below. The - * older admissions stay in place for the firmware those boards still - * boot. - */ - if (dcp_node_is_refmac_v27(dev->of_node)) { - ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - if (ret >= 0 && !strcmp(compat_str, "27.2.0")) - return dcp_v27_method_table(dev, compat_str); - } + if (dcp_firmware_27(dev, &version)) + return version; + /* The T6050 was introduced on firmware 27 and has no older interface. */ if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { @@ -8042,13 +8051,15 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; /* - * An M1/M2/M3 processor on firmware 27 inherits the live session the - * boot loader handed over, like the T6050. Its match data keeps the - * per-SoC port count, tunnel-flow flag and DART resources; only the - * firmware-27 session adoption is version-selected here, before the - * per-SoC firmware-27 profiles below, which may override it. + * Every processor on firmware 27 inherits the live session the boot + * loader handed over. Its match data keeps the per-SoC port count, + * tunnel-flow flag and DART resources; only the session adoption follows + * the firmware. The per-SoC firmware-27 profiles below come after it and + * may override it: the T8122 dcpext, which the loader leaves unpowered, + * does not adopt. (The T8140 dcpext, whose match data does not adopt, is + * refused above on anything but 26.6.2.) */ - if (fw_compat == DCP_FIRMWARE_V_27_0 && dcp_node_is_refmac_v27(dev->of_node)) + if (fw_compat == DCP_FIRMWARE_V_27_0) dcp->hw.adopt_live_session = true; /* * T6041 internal panel on firmware 27 adopts the running DCP session diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 171eda68c817d4..f2745dde65580d 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -94,13 +94,19 @@ bool dcp_fw_compat_is_desktop(struct platform_device *pdev); bool dcp_panel_edr(struct platform_device *pdev); bool dcp_ext_color_props_supported(struct platform_device *pdev); unsigned int dcp_gamma_lut_size(struct platform_device *pdev); -/* - * The M1/M2/M3 display processors admitted into the firmware-27 wire - * generation. @compat_is answers whether a context (a device node in the - * driver, a fixture in the test) carries a compatible string. - */ -typedef bool (*dcp_compat_fn)(const void *ctx, const char *compat); -bool dcp_refmac_v27_compat(dcp_compat_fn compat_is, const void *ctx); +/* Whether a DCP reporting firmware-compat @compat runs the firmware-27 instance. */ +enum dcp_v27_admission { + DCP_V27_NOT_V27, /* older than 27: the older interfaces decide */ + DCP_V27_NO_TABLE, /* 27 or later, no method table for the build */ + DCP_V27_INCOMPLETE, /* 27 or later, a method has no known ID */ + DCP_V27_ADMITTED, +}; + +struct dcp_method_entry; +enum dcp_v27_admission dcp_v27_admission(const char *compat, + const struct dcp_method_entry **methods, + const char **missing, + unsigned int *num_missing); /* T6041 external display processors may join the DRM device. */ bool dcp_t6041_ext_enabled(void); void dcp_backlight_takeover_registered(struct platform_device *pdev); diff --git a/drivers/gpu/drm/apple/iomfb_v27_test.c b/drivers/gpu/drm/apple/iomfb_v27_test.c index 6ca01f3436f957..0c20e9c0d1f891 100644 --- a/drivers/gpu/drm/apple/iomfb_v27_test.c +++ b/drivers/gpu/drm/apple/iomfb_v27_test.c @@ -2,10 +2,10 @@ /* Copyright 2026 Aurora Silicon */ /* - * The M1/M2/M3 display processors are admitted into the firmware-27 wire - * generation on exact firmware-compat 27.2.0, sharing the T6050 method table. - * These tests cover which compatibles that admission recognises and that the - * 27.2.0 method table is complete, so a recognised processor starts. + * Firmware 27 is selected by the firmware-compat a DCP reports, on every SoC: + * 27 or later runs the firmware-27 instance when the build has a complete + * method table and is not started otherwise; older firmware is left to the + * older interfaces. These tests cover that rule and the in-tree tables. */ #include @@ -16,94 +16,62 @@ #include "iomfb.h" #include "iomfb_v27.h" -/* A fixture node: the compatible strings the device tree would carry. */ -struct refmac_node { - const char *const *compats; /* NULL-terminated */ -}; - -static bool refmac_node_compat_is(const void *ctx, const char *compat) +static enum dcp_v27_admission admission(const char *compat) { - const struct refmac_node *node = ctx; - const char *const *c; + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; - for (c = node->compats; *c; c++) - if (!strcmp(*c, compat)) - return true; - return false; + return dcp_v27_admission(compat, &methods, &missing, &num_missing); } -static bool refmac_admits(const char *const *compats) +/* Builds with a complete table start, whatever SoC reports them. */ +static void v27_complete_table_admits_test(struct kunit *test) { - const struct refmac_node node = { .compats = compats }; - - return dcp_refmac_v27_compat(refmac_node_compat_is, &node); -} - -/* Both the per-SoC and the generic compatible of each refmac node. */ -static const char *const t8103_dcp[] = { "apple,t8103-dcp", "apple,dcp", NULL }; -static const char *const t8103_dcpext[] = { "apple,t8103-dcpext", "apple,dcpext", NULL }; -static const char *const t6000_dcp[] = { "apple,t6000-dcp", "apple,dcp", NULL }; -static const char *const t6000_dcpext[] = { "apple,t6000-dcpext", "apple,dcpext", NULL }; -static const char *const t8112_dcp[] = { "apple,t8112-dcp", "apple,dcp", NULL }; -static const char *const t8112_dcpext[] = { "apple,t8112-dcpext", "apple,dcpext", NULL }; -static const char *const t6020_dcp[] = { "apple,t6020-dcp", "apple,dcp", NULL }; -static const char *const t6020_dcpext[] = { "apple,t6020-dcpext", "apple,dcpext", NULL }; -static const char *const t8122_dcp[] = { "apple,t8122-dcp", "apple,dcp", NULL }; -static const char *const t8122_dcpext[] = { "apple,t8122-dcpext", "apple,dcpext", NULL }; -static const char *const t6030_dcp[] = { "apple,t6030-dcp", "apple,dcp", NULL }; -static const char *const t6030_dcpext[] = { "apple,t6030-dcpext", "apple,dcpext", NULL }; -static const char *const t6031_dcp[] = { "apple,t6031-dcp", "apple,dcp", NULL }; -static const char *const t6031_dcpext[] = { "apple,t6031-dcpext", "apple,dcpext", NULL }; - -static void v27_refmac_admits_test(struct kunit *test) -{ - KUNIT_EXPECT_TRUE(test, refmac_admits(t8103_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t8103_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6000_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6000_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t8112_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t8112_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6020_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6020_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t8122_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t8122_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6030_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6030_dcpext)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6031_dcp)); - KUNIT_EXPECT_TRUE(test, refmac_admits(t6031_dcpext)); + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + KUNIT_EXPECT_EQ(test, dcp_v27_admission("27.2.0", &methods, &missing, + &num_missing), + DCP_V27_ADMITTED); + KUNIT_EXPECT_PTR_EQ(test, methods, iomfb_v27_methods("27.2.0")); + KUNIT_EXPECT_PTR_EQ(test, missing, NULL); + KUNIT_EXPECT_EQ(test, num_missing, 0U); + KUNIT_EXPECT_EQ(test, admission("27.0.0"), DCP_V27_ADMITTED); } -/* The T6050 and T8142 keep their own firmware-27 paths; T6041 and M4 do not. */ -static const char *const t6050_dcp[] = { "apple,t6050-dcp", NULL }; -static const char *const t8142_dcp[] = { "apple,t8142-dcp", NULL }; -static const char *const t6041_dcp[] = { "apple,t6041-dcp", "apple,dcpext", NULL }; -static const char *const t8140_dcp[] = { "apple,t8140-dcp", NULL }; - -static void v27_refmac_rejects_test(struct kunit *test) +/* 27 or later without a usable table is refused, never handed down. */ +static void v27_unusable_table_refuses_test(struct kunit *test) { - KUNIT_EXPECT_FALSE(test, refmac_admits(t6050_dcp)); - KUNIT_EXPECT_FALSE(test, refmac_admits(t8142_dcp)); - KUNIT_EXPECT_FALSE(test, refmac_admits(t6041_dcp)); - KUNIT_EXPECT_FALSE(test, refmac_admits(t8140_dcp)); + const struct dcp_method_entry *methods; + unsigned int num_missing; + const char *missing; + + KUNIT_EXPECT_EQ(test, admission("27.1.0"), DCP_V27_NO_TABLE); + KUNIT_EXPECT_EQ(test, admission("28.0.0"), DCP_V27_NO_TABLE); + KUNIT_EXPECT_EQ(test, dcp_v27_admission("27.3.0", &methods, &missing, + &num_missing), + DCP_V27_INCOMPLETE); + KUNIT_EXPECT_NOT_NULL(test, missing); + KUNIT_EXPECT_GT(test, num_missing, 0U); } -/* The 27.2.0 table a recognised processor runs is complete, so it may start. */ -static void v27_method_table_test(struct kunit *test) +/* Older firmware keeps the 26.x, 14.x and 13.x selection. */ +static void v27_older_firmware_not_v27_test(struct kunit *test) { - const struct dcp_method_entry *methods; - unsigned int missing; - - methods = iomfb_v27_methods("27.2.0"); - KUNIT_ASSERT_NOT_NULL(test, methods); - KUNIT_EXPECT_PTR_EQ(test, iomfb_v27_missing_method(methods, &missing), NULL); - KUNIT_EXPECT_EQ(test, missing, 0U); - KUNIT_EXPECT_PTR_EQ(test, iomfb_v27_methods("27.1.0"), NULL); + KUNIT_EXPECT_EQ(test, admission("26.6.2"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("26.5.2"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("14.7.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("13.5.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("12.3.0"), DCP_V27_NOT_V27); + KUNIT_EXPECT_EQ(test, admission("UNKNOWN"), DCP_V27_NOT_V27); } static struct kunit_case v27_cases[] = { - KUNIT_CASE(v27_refmac_admits_test), - KUNIT_CASE(v27_refmac_rejects_test), - KUNIT_CASE(v27_method_table_test), + KUNIT_CASE(v27_complete_table_admits_test), + KUNIT_CASE(v27_unusable_table_refuses_test), + KUNIT_CASE(v27_older_firmware_not_v27_test), {} }; From 48aaad34f58cf030cd64da10352d3ee3e67d7290 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:27:35 -0500 Subject: [PATCH 1243/1514] soc: apple: display-gate: take the T6030 macOS 27.2 PMP image On the macOS 27.2 (26B123) system firmware the boot loader passes the T6030 PMP values with tunable-uuid 5D66805B-E4AD-335E-BDC3-26828C682AAC, the PMP image the J516S ADT names for that release (iop-pmp-nub). The gate takes only the 14.x image (2F4EB4C4-...), so on a 27.2 J516s it stops with "PMP not added: this Mac's PMP firmware image is 5D66805B-..." and the internal display and both dcpext stay disabled. Take the 27.2 image as well, as for the T8122. The 27.2 PMP PTD map only inserts LTS-VOLT-CAP and leaves the SOC-DEV-PS-REQ, PS-ACK and PMP-STATUS offsets the T6030 PMP report reads unchanged, and the soc-device records are byte-identical to the J516S overlay's. The PMP report driver checks the running image in SRAM against the image the values name before it starts the PMP, so the same support serves both images. Add a KUnit case for the 27.2 image beside the one that refuses the T8122 image. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/soc/apple/display-gate-test.c | 12 ++++++++++++ drivers/soc/apple/display-gate.c | 9 +++++++++ 2 files changed, 21 insertions(+) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index 7e736522740b01..da246414729949 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -790,6 +790,17 @@ static void __init gate_t6030_other_pmp_image(struct kunit *test) gt_expect_untouched(test); } +/* The 27.2 (26B123) T6030 PMP image is taken as well. */ +static void __init gate_t6030_pmp_image_27_2(struct kunit *test) +{ + struct gate_test *t = test->priv; + + t->pmp_uuid = "5D66805B-E4AD-335E-BDC3-26828C682AAC"; + gt_set_string(test, gt_t6030.values, "apple,tunable-uuid", t->pmp_uuid); + gt_run(test); + gt_expect_enabled(test); +} + static void __init gate_t6030_enabled_again(struct kunit *test) { gt_run(test); @@ -1185,6 +1196,7 @@ static struct kunit_case gate_t6030_cases[] __refdata = { KUNIT_CASE(gate_t6030_no_marker), KUNIT_CASE(gate_t6030_t6031_power_layout), KUNIT_CASE(gate_t6030_other_pmp_image), + KUNIT_CASE(gate_t6030_pmp_image_27_2), KUNIT_CASE(gate_t6030_enabled_again), {} }; diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index dc57af0dd16514..931fe3ef1adf82 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -161,6 +161,14 @@ static struct device_node *gate_pmp_values __initdata; */ static const char gate_pmp_uuid[] __initconst = "2F4EB4C4-001B-3ACF-A9A0-68D8E42FC3A7"; +/* + * The T6030 PMP image of the 27.2 (26B123) system firmware, as the J516S ADT + * names it. Its soc-device records are those of the J516S overlay, and the PMP + * report driver checks the running image against the values the boot loader + * passes, so the same PMP support takes either image. + */ +static const char gate_t6030_pmp_uuid_27_2[] __initconst = "5D66805B-E4AD-335E-BDC3-26828C682AAC"; + /* The T8122 PMP image of the 14.x system firmware. */ static const char gate_t8122_pmp_uuid[] __initconst = "3B18C886-4C70-349B-B1C4-70F35DE2C5CD"; @@ -255,6 +263,7 @@ static const struct gate_soc gate_t6030 __initconst = { .dcp_full_name = "dcp@28ec00000", .pmp_values = "/chosen/asahi,t6030-pmp", .pmp_uuid = gate_pmp_uuid, + .pmp_uuid_alt = gate_t6030_pmp_uuid_27_2, .report_compat = "apple,t6030-pmp-v2-report", .disp_entry = "report@7", .pmp_dtbo = __dtbo_t6030_pmp_begin, From 3b9655cf5f13313a198bf541755cbbecf2b6ff5b Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:03:51 -0500 Subject: [PATCH 1244/1514] dt-bindings: apple: aop: allow T6030, T6031 and T8122 AOP and child compatibles Add apple,t6030-aop, apple,t6031-aop and apple,t8122-aop to the AOP binding and update the referenced audio, ambient light sensor and lid angle sensor child schemas so T6030, T6031 and T8122 AOP subnodes validate cleanly. Signed-off-by: Diljit Singh --- .../bindings/iio/light/apple,aop-als.yaml | 4 ++++ .../bindings/iio/position/apple,aop-las.yaml | 4 ++++ .../bindings/soc/apple/apple,aop.yaml | 12 ++++++++--- .../bindings/sound/apple,aop-audio.yaml | 20 ++++++++++++++----- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml b/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml index 5113ddb6491fb9..564caa6e649df4 100644 --- a/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml +++ b/Documentation/devicetree/bindings/iio/light/apple,aop-als.yaml @@ -21,8 +21,10 @@ select: enum: - apple,t6020-aop-als - apple,t6030-aop-als + - apple,t6031-aop-als - apple,t6050-aop-als - apple,t8112-aop-als + - apple,t8122-aop-als - apple,t8142-aop-als required: - compatible @@ -33,8 +35,10 @@ properties: - items: - enum: - apple,t6020-aop-als + - apple,t6031-aop-als - apple,t6050-aop-als - apple,t8112-aop-als + - apple,t8122-aop-als - apple,t8142-aop-als - const: apple,aop-als - items: diff --git a/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml b/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml index d3564e453f0c49..0002ff36b4e923 100644 --- a/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml +++ b/Documentation/devicetree/bindings/iio/position/apple,aop-las.yaml @@ -21,8 +21,10 @@ select: enum: - apple,t6020-aop-las - apple,t6030-aop-las + - apple,t6031-aop-las - apple,t6050-aop-las - apple,t8112-aop-las + - apple,t8122-aop-las - apple,t8142-aop-las required: - compatible @@ -33,8 +35,10 @@ properties: - items: - enum: - apple,t6020-aop-las + - apple,t6031-aop-las - apple,t6050-aop-las - apple,t8112-aop-las + - apple,t8122-aop-las - apple,t8142-aop-las - const: apple,aop-las - items: diff --git a/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml b/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml index 32abbb559afc2f..38a87bcdc18dfd 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,aop.yaml @@ -20,7 +20,10 @@ select: items: - enum: - apple,t6020-aop + - apple,t6030-aop + - apple,t6031-aop - apple,t8112-aop + - apple,t8122-aop required: - compatible @@ -31,7 +34,10 @@ properties: - apple,t6020-aop - apple,t8112-aop - items: - - const: apple,t8122-aop + - enum: + - apple,t6030-aop + - apple,t6031-aop + - apple,t8122-aop - const: apple,t6020-aop reg: @@ -53,8 +59,8 @@ properties: maxItems: 8 description: The firmware's external code, data and log segments in DRAM, reserved - by the bootloader with their IOVAs in iommu-addresses (T6040, T8122 and - T8132). Absent when the bootloader did not reserve them. + by the bootloader with their IOVAs in iommu-addresses. Absent when + the bootloader did not reserve them. audio: $ref: /schemas/sound/apple,aop-audio.yaml# diff --git a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml index 5a501c66df7675..952fa583d183f1 100644 --- a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml @@ -20,17 +20,27 @@ select: contains: enum: - apple,t6020-aop-audio + - apple,t6030-aop-audio + - apple,t6031-aop-audio - apple,t8112-aop-audio + - apple,t8122-aop-audio required: - compatible properties: compatible: - items: - - enum: - - apple,t6020-aop-audio - - apple,t8112-aop-audio - - const: apple,aop-audio + oneOf: + - items: + - enum: + - apple,t6020-aop-audio + - apple,t8112-aop-audio + - const: apple,aop-audio + - const: apple,t6030-aop-audio + - items: + - enum: + - apple,t6031-aop-audio + - apple,t8122-aop-audio + - const: apple,t6030-aop-audio dmas: maxItems: 1 From 701e3208433a62a5513662caf3e1bf2a5dd5ef26 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:03:52 -0500 Subject: [PATCH 1245/1514] soc: apple: aop: use region-aware startup on T6030 and T6031 T6030 and T6031 currently fall through to apple,t6020-aop, which skips DRAM firmware region validation and leaves ED0p unpatched. On macOS 27.2 (26B123), the AOP image ships with ED0p=0 and expects the translated __EDATA IOVA, stalling before EPMAP with -ETIME without it. Match apple,t6030-aop and apple,t6031-aop (inherited by T6034) against the existing region-aware M3 configuration (HW_CFG_T8122), which keeps the no-region fallback for older bootloaders and firmware. Signed-off-by: Diljit Singh --- drivers/soc/apple/aop.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 89849f775d5c74..4d0f1de643013c 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -3196,10 +3196,11 @@ const HW_CFG_T6041: AopHwConfig = AopHwConfig { /// the DART's DAPF programmed and its windows reserved alongside the firmware /// segments. const HW_CFG_T8132: AopHwConfig = HW_CFG_T6040; -/// T8122 (M3): as T6040. iBoot leaves the AOP halted with its external code, -/// data and log in DRAM, which the bootloader reserves in `memory-region`; -/// the 27.2 firmware reads its `__EDATA` base from `ED0p`. A bootloader that -/// reserves none leaves it to start as `apple,t6020-aop`, as before. +/// M3-family AOP (T8122, T6030 and T6031): as T6040. iBoot leaves the AOP +/// halted with its external code, data and log in DRAM, which the bootloader +/// reserves in `memory-region`; the 27.2 firmware reads its `__EDATA` base +/// from `ED0p`. A bootloader that reserves none leaves it to start as +/// `apple,t6020-aop`, as before. const HW_CFG_T8122: AopHwConfig = AopHwConfig { without_fw_regions: Some(&HW_CFG_T6020), ..HW_CFG_T6040 @@ -3334,6 +3335,8 @@ kernel::of_device_table!( (of::DeviceId::new(c_str!("apple,t8112-aop")), &HW_CFG_T8112), (of::DeviceId::new(c_str!("apple,t6000-aop")), &HW_CFG_T6000), (of::DeviceId::new(c_str!("apple,t8122-aop")), &HW_CFG_T8122), + (of::DeviceId::new(c_str!("apple,t6030-aop")), &HW_CFG_T8122), + (of::DeviceId::new(c_str!("apple,t6031-aop")), &HW_CFG_T8122), (of::DeviceId::new(c_str!("apple,t6020-aop")), &HW_CFG_T6020), (of::DeviceId::new(c_str!("apple,t8140-aop")), &HW_CFG_T8140), (of::DeviceId::new(c_str!("apple,t6041-aop")), &HW_CFG_T6041), From 6283432169946f5acd32e3f7c3fb6b9b67997b0c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:03:52 -0500 Subject: [PATCH 1246/1514] HID: dockchannel-hid: fall back to power method 2 when method 1 is rejected MTP 27.2 firmware does not advertise PowerMethod in EVENT_INIT and rejects the 4-byte power-method-1 interface reset command with kIOReturnBadArgument (0xe00002c2). Request apple,afe-reset-gpios optionally at probe with GPIOD_ASIS and return the reset command's own firmware retcode under out_mutex so concurrent comm traffic cannot race on comm->retcode. When apple,power-method is not explicitly pinned in DT and a method-1 power-off returns 0xe00002c2 on a non-ring transport with an AFE reset line available, switch the interface to power method 2 and explicitly configure afe_reset as an output via gpiod_direction_output() at the first required reset level. Add KUnit coverage for the fallback predicate. Signed-off-by: Diljit Singh --- .../dockchannel-hid-protocol-test.c | 32 +++++ .../dockchannel-hid-protocol.h | 13 ++ drivers/hid/dockchannel-hid/dockchannel-hid.c | 115 +++++++++++++++--- 3 files changed, 143 insertions(+), 17 deletions(-) diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c index 2c4d18a9177a27..47f91ca6ee493c 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol-test.c @@ -62,11 +62,43 @@ static void dchid_pm2_power_off_test(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, cmd, expected, sizeof(expected)); } +static void dchid_pm1_fallback_test(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + true, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, true, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, + DCHID_ERR_BAD_ARGUMENT, + false, false, false)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-ETIMEDOUT, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(-EIO, 0xe00002bc, + false, false, true)); + KUNIT_EXPECT_FALSE(test, + dchid_pm1_needs_pm2_fallback(0, + DCHID_ERR_BAD_ARGUMENT, + false, false, true)); +} + static struct kunit_case dchid_protocol_test_cases[] = { KUNIT_CASE(dchid_pm1_command_test), KUNIT_CASE(dchid_pm2_will_change_test), KUNIT_CASE(dchid_pm2_has_changed_test), KUNIT_CASE(dchid_pm2_power_off_test), + KUNIT_CASE(dchid_pm1_fallback_test), {} }; diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h index c73c911862ac05..96d3c07f1cc180 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h +++ b/drivers/hid/dockchannel-hid/dockchannel-hid-protocol.h @@ -5,6 +5,7 @@ #ifndef _DOCKCHANNEL_HID_PROTOCOL_H #define _DOCKCHANNEL_HID_PROTOCOL_H +#include #include #include @@ -32,6 +33,18 @@ #define DCHID_PM1_CMD_SIZE 4 #define DCHID_PM2_CMD_SIZE 9 +/* IOKit kIOReturnBadArgument: returned when firmware rejects power method 1. */ +#define DCHID_ERR_BAD_ARGUMENT 0xe00002c2 + +static inline bool dchid_pm1_needs_pm2_fallback(int ret, u32 retcode, + bool pm_explicit, + bool use_ring, + bool has_afe_reset) +{ + return ret == -EIO && retcode == DCHID_ERR_BAD_ARGUMENT && + !pm_explicit && !use_ring && has_afe_reset; +} + static inline void dchid_pm1_command(u8 iface, u8 state, u8 cmd[DCHID_PM1_CMD_SIZE]) { diff --git a/drivers/hid/dockchannel-hid/dockchannel-hid.c b/drivers/hid/dockchannel-hid/dockchannel-hid.c index 9e0877ca2d496a..38447a819ad729 100644 --- a/drivers/hid/dockchannel-hid/dockchannel-hid.c +++ b/drivers/hid/dockchannel-hid/dockchannel-hid.c @@ -194,6 +194,7 @@ struct dchid_iface { u32 keyboard_layout_id; u32 power_method; + bool pm_explicit; bool firmware_managed_reset; }; @@ -251,6 +252,7 @@ static struct dchid_iface * dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) { u32 power_method = DCHID_POWER_METHOD_1; + bool pm_explicit = false; bool firmware_managed_reset = false; struct device_node *of_node = NULL; struct dchid_iface *iface; @@ -279,7 +281,8 @@ dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) return NULL; } - of_property_read_u32(of_node, "apple,power-method", &power_method); + pm_explicit = !of_property_read_u32(of_node, "apple,power-method", + &power_method); firmware_managed_reset = of_property_read_bool(of_node, "apple,firmware-managed-reset"); if (firmware_managed_reset && @@ -313,6 +316,7 @@ dchid_get_interface(struct dockchannel_hid *dchid, int index, const char *name) iface->dchid = dchid; iface->of_node = of_node; iface->power_method = power_method; + iface->pm_explicit = pm_explicit; iface->firmware_managed_reset = firmware_managed_reset; iface->out_report = -1; init_completion(&iface->out_complete); @@ -424,11 +428,13 @@ static int dchid_send(struct dchid_iface *iface, u32 flags, void *msg, size_t si return ret; } -static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, - void *data, size_t size, void *resp_buf, size_t resp_size) +static int dchid_cmd_retcode(struct dchid_iface *iface, u32 type, u32 req, + void *data, size_t size, void *resp_buf, + size_t resp_size, u32 *retcode_out) { int ret; - int report_id = *(u8*)data; + int report_id = *(u8 *)data; + u32 fw_retcode = 0; mutex_lock(&iface->out_mutex); @@ -437,6 +443,7 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, iface->out_flags = FIELD_PREP(FLAGS_GROUP, type) | FIELD_PREP(FLAGS_REQ, req); iface->resp_buf = resp_buf; iface->resp_size = resp_size; + iface->retcode = 0; reinit_completion(&iface->out_complete); ret = dchid_send(iface, iface->out_flags, data, size); @@ -451,10 +458,11 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, } ret = iface->resp_size; - if (iface->retcode) { + fw_retcode = iface->retcode; + if (fw_retcode) { dev_err(iface->dchid->dev, "output report 0x%x to iface %d (%s) failed with err 0x%x\n", - report_id, iface->index, iface->name, iface->retcode); + report_id, iface->index, iface->name, fw_retcode); ret = -EIO; } @@ -465,12 +473,29 @@ static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, iface->resp_buf = NULL; iface->resp_size = 0; mutex_unlock(&iface->out_mutex); + if (retcode_out) + *retcode_out = fw_retcode; return ret; } +static int dchid_cmd(struct dchid_iface *iface, u32 type, u32 req, + void *data, size_t size, void *resp_buf, size_t resp_size) +{ + return dchid_cmd_retcode(iface, type, req, data, size, resp_buf, + resp_size, NULL); +} + +static int dchid_comm_cmd_retcode(struct dockchannel_hid *dchid, void *cmd, + size_t size, u32 *retcode_out) +{ + return dchid_cmd_retcode(dchid->comm, HID_FEATURE_REPORT, + REQ_SET_REPORT, cmd, size, NULL, 0, + retcode_out); +} + static int dchid_comm_cmd(struct dockchannel_hid *dchid, void *cmd, size_t size) { - return dchid_cmd(dchid->comm, HID_FEATURE_REPORT, REQ_SET_REPORT, cmd, size, NULL, 0); + return dchid_comm_cmd_retcode(dchid, cmd, size, NULL); } static int dchid_host_state(struct dockchannel_hid *dchid, u8 state) @@ -488,15 +513,20 @@ static int dchid_enable_interface(struct dchid_iface *iface) return dchid_comm_cmd(iface->dchid, msg, sizeof(msg)); } -static int dchid_reset_interface(struct dchid_iface *iface, int state) +static int dchid_reset_interface_retcode(struct dchid_iface *iface, int state, + u32 *retcode_out) { u8 msg[DCHID_PM1_CMD_SIZE]; u8 msg2[DCHID_PM2_CMD_SIZE]; int ret; + if (retcode_out) + *retcode_out = 0; + if (!iface->dchid->use_ring) { dchid_pm1_command(iface->index, state, msg); - return dchid_comm_cmd(iface->dchid, msg, sizeof(msg)); + return dchid_comm_cmd_retcode(iface->dchid, msg, sizeof(msg), + retcode_out); } /* @@ -531,7 +561,13 @@ static int dchid_reset_interface(struct dchid_iface *iface, int state) } #endif dchid_pm2_command(iface->index, state, true, msg2); - return dchid_comm_cmd(iface->dchid, msg2, sizeof(msg2)); + return dchid_comm_cmd_retcode(iface->dchid, msg2, sizeof(msg2), + retcode_out); +} + +static int dchid_reset_interface(struct dchid_iface *iface, int state) +{ + return dchid_reset_interface_retcode(iface, state, NULL); } static int dchid_register_ring(struct dockchannel_hid *dchid) @@ -595,7 +631,7 @@ static int dchid_pm2_set_power(struct dchid_iface *iface, u8 state) } else { bool off = state == DCHID_POWER_STATE_OFF; - ret = gpiod_set_value_cansleep(dchid->afe_reset, off); + ret = gpiod_direction_output(dchid->afe_reset, off); if (ret < 0) { dev_err(dchid->dev, "%s: failed to %s the AFE reset: %d\n", iface->name, off ? "assert" : "release", ret); @@ -721,9 +757,14 @@ static int dchid_request_gpio(struct dchid_iface *iface) dev_dbg(iface->dchid->dev, "Requesting GPIO %s#%d: %s\n", iface->name, iface->gpio_id, iface->gpio_name); - /* A power method 2 interface holds its reset line from probe on. */ - if (iface->power_method == DCHID_POWER_METHOD_2 && + /* Reuse the AFE reset line held from probe on. */ + if (iface->dchid->afe_reset && !strcmp(iface->gpio_name, "afe-reset")) { + if (iface->power_method == DCHID_POWER_METHOD_1) { + ret = gpiod_direction_output(iface->dchid->afe_reset, 0); + if (ret < 0) + return ret; + } iface->gpio = iface->dchid->afe_reset; return 0; } @@ -785,7 +826,7 @@ static int dchid_start_interface(struct dchid_iface *iface) ret = -EINVAL; goto err; } - ret = gpiod_set_value_cansleep(iface->dchid->afe_reset, 1); + ret = gpiod_direction_output(iface->dchid->afe_reset, 1); if (ret < 0) goto err; fsleep(50 * USEC_PER_MSEC); @@ -809,10 +850,44 @@ static int dchid_start_interface(struct dchid_iface *iface) if (ret < 0) goto err; } else { - ret = dchid_reset_interface(iface, DCHID_POWER_STATE_OFF); - /* After a failed AFE power-off the trackpad stays off: no retry. */ - if (ret >= 0 || !iface->dchid->afe_smc || iface->index != 1) + u32 fw_retcode = 0; + + ret = dchid_reset_interface_retcode(iface, + DCHID_POWER_STATE_OFF, + &fw_retcode); + if (dchid_pm1_needs_pm2_fallback(ret, fw_retcode, + iface->pm_explicit, + iface->dchid->use_ring, + !!iface->dchid->afe_reset)) { + dev_info(iface->dchid->dev, + "%s: power method 1 rejected (0x%x); retrying with power method 2\n", + iface->name, fw_retcode); + iface->power_method = DCHID_POWER_METHOD_2; + if (iface->dchid->inherited_mtp) { + ret = gpiod_direction_output(iface->dchid->afe_reset, 1); + if (ret < 0) + goto err; + fsleep(50 * USEC_PER_MSEC); + ret = dchid_send_firmware(iface, fw, size); + if (ret < 0) { + dev_err(iface->dchid->dev, + "Failed to resend %s firmware\n", + iface->name); + goto err; + } + } else { + ret = dchid_pm2_set_power(iface, + DCHID_POWER_STATE_OFF); + if (ret < 0) + goto err; + } + ret = dchid_pm2_set_power(iface, DCHID_POWER_STATE_ON); + if (ret < 0) + goto err; + } else if (ret >= 0 || !iface->dchid->afe_smc || iface->index != 1) { + /* After a failed AFE power-off the trackpad stays off: no retry. */ dchid_reset_interface(iface, DCHID_POWER_STATE_ON); + } } } @@ -1732,6 +1807,12 @@ static int dockchannel_hid_probe(struct platform_device *pdev) if (IS_ERR(dchid->afe_reset)) return dev_err_probe(dev, PTR_ERR(dchid->afe_reset), "Failed to request the AFE reset line\n"); + } else if (!firmware_managed_reset && !dchid->use_ring) { + dchid->afe_reset = devm_gpiod_get_optional(dev, "apple,afe-reset", + GPIOD_ASIS); + if (IS_ERR(dchid->afe_reset)) + return dev_err_probe(dev, PTR_ERR(dchid->afe_reset), + "Failed to request the AFE reset line\n"); } } From 6de24c24ed94580095032d0c5d6655767b27bf31 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:03:53 -0500 Subject: [PATCH 1247/1514] arm64: dts: apple: t603x-j514-j516: keep MTP running across handoff On macOS 27.2, MTP firmware cannot be cleanly restarted once U-Boot quiesces it. Mark &mtp with apple,rtkit-keep-running in t603x-j514-j516.dtsi so a handoff-capable U-Boot hands the session over running, matching J613 and J615 (ignored by older U-Boot). The MTP DART DMA window is propagated from the live ADT by the bootloader rather than hardcoded in static DT. Signed-off-by: Diljit Singh --- arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi b/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi index 25eb746f430ae7..aa7cea142a27d7 100644 --- a/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi +++ b/arch/arm64/boot/dts/apple/t603x-j514-j516.dtsi @@ -87,6 +87,7 @@ &mtp { status = "okay"; + apple,rtkit-keep-running; }; &mtp_mbox { From 20697079fa0d96d105f7bab4c6e641a915f58470 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:50:59 -0500 Subject: [PATCH 1248/1514] drm/asahi: parameterize classic GPU boot admission by SoC Select the handoff, ADT identity, power-domain register and userspace identity from the SoC configuration. Let each handoff select its InitData layout independently of the protocol ABI, and derive the scratch alias from the mapped host block. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/adt.rs | 12 ++-- drivers/gpu/drm/asahi/g16/adt/perf.rs | 4 +- drivers/gpu/drm/asahi/g16/boot.rs | 40 +++++++------ drivers/gpu/drm/asahi/g16/hw.rs | 58 +++++++++++++++++-- drivers/gpu/drm/asahi/g16/initdata.rs | 5 +- drivers/gpu/drm/asahi/g16/mod.rs | 24 +------- drivers/gpu/drm/asahi/g16/params.rs | 9 +-- drivers/gpu/drm/asahi/g16/regs.rs | 25 ++++++-- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 5 -- .../drivers/gpu/asahi-m4/check-channels.rs | 9 ++- .../drivers/gpu/asahi-m4/test-perf.py | 30 +++++----- 11 files changed, 129 insertions(+), 92 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 3c639f054c4ec2..84330216d0200e 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -13,7 +13,7 @@ pub(crate) mod perf; use core::ops::Range; use kernel::{bindings, c_str, device, of, prelude::*}; -use super::{boot::glue, hw}; +use super::{boot::glue, hw, Config}; /// Independently owned reservations; none may intersect System RAM or another reservation. pub(crate) struct GpuAdt { @@ -130,9 +130,9 @@ fn handoff(dev: &device::Device) -> Result<(u32, KVec, KVec)> { } /// 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> { +pub(crate) fn layout(dev: &device::Device, cfg: &Config) -> Option<&'static hw::FwLayout> { let (version, vas, flags) = handoff(dev).ok()?; - hw::FW_LAYOUTS + cfg.layouts .iter() .copied() .find(|layout| layout.matches(version, &vas, &flags)) @@ -140,12 +140,12 @@ pub(crate) fn layout(dev: &device::Device) -> Option<&'static hw::FwLayout> { /// Validates the FDT contract and returns the reserved physical regions, read-only. #[inline(never)] -pub(crate) fn read(dev: &device::Device) -> Result> { +pub(crate) fn read(dev: &device::Device, cfg: &Config) -> 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"))?; - let layout = hw::FW_LAYOUTS + let layout = cfg.layouts .iter() .copied() .find(|layout| layout.matches(version, &vas, &flags)); @@ -207,7 +207,7 @@ pub(crate) fn read(dev: &device::Device) -> Result> { regions[index] = start..end; } let (copy, source_pa) = performance_source(®ions)?; - let performance = perf::parse(©).map_err(|error| { + let performance = perf::parse(©, cfg.adt_compatible).map_err(|error| { dev_err!( dev, "M4 original ADT performance data rejected: {:?}\n", diff --git a/drivers/gpu/drm/asahi/g16/adt/perf.rs b/drivers/gpu/drm/asahi/g16/adt/perf.rs index 7c64913aa69bf0..e2ebedb8862e30 100644 --- a/drivers/gpu/drm/asahi/g16/adt/perf.rs +++ b/drivers/gpu/drm/asahi/g16/adt/perf.rs @@ -176,7 +176,7 @@ fn decode_record(data: &[u8], state: usize) -> Result<(u32, u32), Error> { /// Copying and physical reservation admission are the caller's responsibility. No reference to /// `data` escapes. Padding after the root is permitted because phram exports whole pages. -pub(crate) fn parse(data: &[u8]) -> Result { +pub(crate) fn parse(data: &[u8], sgx_compatible: &[u8]) -> Result { if data.is_empty() || data.len() > 0x20_0000 { return Err(Error::Malformed); } @@ -188,7 +188,7 @@ pub(crate) fn parse(data: &[u8]) -> Result { if compatible.last() != Some(&0) || !compatible .split(|&c| c == 0) - .any(|value| value == b"gpu,t8132") + .any(|value| value == sgx_compatible) { return Err(Error::Identity); } diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 73b3445ffe2b94..ce14ce9f021c3d 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -607,27 +607,32 @@ pub(crate) fn admit( // 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); + let votes = !matches!( + adt::layout(dev, cfg), + 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. - // SAFETY: `dev` is the bound GPU device. - let ret = unsafe { bindings::apple_pmp_j713_gpu_prepare(dev.as_raw()) }; - if ret != 0 { - let err = Error::from_errno(ret); - if err != EPROBE_DEFER { - dev_err!(dev, "PMP supplier not ready: {:?}\n", err); + if cfg.prepare_pmp { + // Retain the PMP supplier (and its AGX bridge) before any vote. + // SAFETY: `dev` is the bound GPU device. + let ret = unsafe { bindings::apple_pmp_j713_gpu_prepare(dev.as_raw()) }; + if ret != 0 { + let err = Error::from_errno(ret); + if err != EPROBE_DEFER { + dev_err!(dev, "PMP supplier not ready: {:?}\n", err); + } + return Err(err); } - return Err(err); } glue::display_prepare(dev).inspect_err(|e| { if *e != EPROBE_DEFER { dev_err!(dev, "native display not admitted: {:?}\n", e); } })?; - let adt = - adt::read(dev).inspect_err(|e| dev_err!(dev, "ADT GPU regions not admitted: {:?}\n", e))?; + let adt = adt::read(dev, cfg) + .inspect_err(|e| dev_err!(dev, "ADT GPU regions not admitted: {:?}\n", e))?; crate::fwid::identify( dev, adt.text.clone(), @@ -660,14 +665,14 @@ pub(crate) fn admit( dev_err!(dev, "G16: unsupported coherent, IOMMU or custom DMA path\n"); return Err(EINVAL); } - let regs = regs::Regs::new(pdev, res)?; + let regs = regs::Regs::new(pdev, res, cfg)?; // Once power admission starts, even a rejected cold check must not detach the GFX // domain under an inherited firmware owner. Keep the module and platform binding; once // the module's removal has begun nothing is held. glue::retain_module()?; glue::hold_power(dev)?; let (power_offset, power_state) = glue::power_domain_state(dev)?; - if power_offset != 0x250 || (power_state >> 4) & 0xf != 0xf { + if power_offset != cfg.power_offset || (power_state >> 4) & 0xf != 0xf { dev_err!( dev, "M4 GFX domain not admitted: register{:#x} state{:#x}\n", @@ -989,15 +994,16 @@ pub(crate) fn start( ); return Err(eproto()); } - // M4 has one cluster with up to ten enabled cores. - if id.core_masks[0] == 0 || id.cores >> hw::CLUSTER_BITS != 0 { + if id.cores >> cfg.core_slots() != 0 + || id.core_masks[..cfg.num_clusters as usize].contains(&0) + { dev_err!(d, "implausible G16G core mask {:#x}\n", id.cores); return Err(eproto()); } dev_info!( d, "M4 G16G: {} cores enabled\n", - id.core_masks[0].count_ones() + id.cores.count_ones() ); if regs.pstate()? > regs.top() { return Err(eproto()); @@ -1067,7 +1073,7 @@ pub(crate) fn start( let result = (|| { 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)?); + built = Some(initdata::build(&d, &session.adt, &session.regs, &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); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 4cd4ad02d8f35c..7951b2b09100e2 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -20,13 +20,52 @@ pub(crate) struct HwId { pub(crate) use crate::fwid::FirmwareBuild; +/// Static configuration of a SoC supported by this backend. +pub(crate) struct Config { + /// SoC identifier reported to userspace. + pub(crate) chip_id: u32, + /// GPU generation reported to userspace. + pub(crate) gpu_generation: u32, + /// GPU variant reported to userspace. + pub(crate) gpu_variant: crate::hw::GpuVariant, + /// GPU revision reported to userspace. + pub(crate) gpu_revision: u32, + /// Input address bits translated by each UAT root. + pub(crate) uat_ias: u32, + /// Output (physical) address bits of the UAT. + pub(crate) uat_oas: u32, + /// Clusters and cores per cluster. + pub(crate) num_clusters: u32, + pub(crate) num_cores_per_cluster: u32, + /// Qualified identification register values. + pub(crate) hw_ids: &'static [HwId], + /// Compatible of the original ADT SGX node. + pub(crate) adt_compatible: &'static [u8], + /// Qualified boot-loader handoffs. + pub(crate) layouts: &'static [&'static FwLayout], + /// Qualified firmware builds. + pub(crate) firmware: &'static [FirmwareBuild], + /// T8132 retains the PMP bridge even on firmware that does not send an AGX vote. + pub(crate) prepare_pmp: bool, + /// PMGR register offset of the GFX domain. + pub(crate) power_offset: u32, + /// GFXCAXI2AF needs host enable writes before the 27.2 firmware starts. + pub(crate) axi2af: bool, +} + +impl Config { + pub(crate) const fn core_slots(&self) -> u32 { + self.num_clusters * self.num_cores_per_cluster + } +} + /// 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}; + use super::{Config, FirmwareBuild, HwId, FW_25G83, FW_26B123}; pub(crate) const CONFIG: Config = Config { chip_id: 0x8132, + gpu_generation: 16, gpu_variant: crate::hw::GpuVariant::G, gpu_revision: 0x10, uat_ias: 42, @@ -37,6 +76,8 @@ pub(crate) mod t8132 { version: 0x0a021100, counts: 0x0011010a, }], + adt_compatible: b"gpu,t8132", + layouts: &[&FW_25G83, &FW_26B123], firmware: &[ FirmwareBuild { name: "Apple GFX 25G83 (normalized loaded image)", @@ -126,6 +167,9 @@ pub(crate) mod t8132 { ], }, ], + prepare_pmp: true, + power_offset: 0x250, + axi2af: true, }; /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: @@ -282,6 +326,9 @@ pub(crate) enum Start { MacOs27_2, } +/// Host-owned SGX register block. +pub(crate) const HOST_BLOCK: u64 = 0xd60000; + /// 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 @@ -339,6 +386,8 @@ pub(crate) struct FwLayout { pub(crate) data_size: u64, /// The firmware ABI of the builds this layout holds. pub(crate) abi: FwAbi, + /// InitData wire layout, including the version word of this firmware image. + pub(crate) initdata: &'static super::fw::initdata::Layout, /// 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. @@ -391,6 +440,7 @@ pub(crate) const FW_25G83: FwLayout = FwLayout { text_size: 0x60000, data_size: 0x13c000, abi: FwAbi::V25G83, + initdata: &super::fw::initdata::V25G83, leaves: Some(&[ Leaves { range: 0..0x50000, @@ -452,6 +502,7 @@ pub(crate) const FW_26B123: FwLayout = FwLayout { text_size: 0x64000, data_size: 0xd8000, abi: FwAbi::V26B123, + initdata: &super::fw::initdata::V26B123, // The firmware builds its own tree at start; admit only an empty tree. leaves: Some(&[]), ppl_magic: Some(PplMagic { @@ -467,9 +518,6 @@ pub(crate) const FW_26B123: FwLayout = FwLayout { 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; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 6d8f3bb7836e7e..3c32f03f49c5ea 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -97,10 +97,11 @@ fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, + regs: &super::regs::Regs, objects: &mut Objects, ) -> Result<(InitData, Channels, u32)> { let abi = adt.layout.abi; - let layout = abi.initdata(); + let layout = adt.layout.initdata; let performance = board::qualify(dev, adt)?; // The top row: S9 on J713, S10 on J773g. let ceiling = performance.count as u32 - 1; @@ -260,7 +261,7 @@ pub(crate) fn build( input.scratch = objects.reserve_io(0x8000)?; // This scratch alias deliberately has firmware RAM attrs, matching the // qualified owner, even though the target is an SGX register window. - objects.map_mmio_class(input.scratch, 0x300d60000, 0x8000, hw::pte::FW)?; + objects.map_mmio_class(input.scratch, regs.host_block_pa(), 0x8000, hw::pte::FW)?; // Private CPU-side staging keeps the pure encoder independent of raw GEM // pointers. No staging references survive publication. diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 0a647cbbd2cb5f..2b98e95ca192c2 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -98,29 +98,7 @@ use crate::{alloc, gem, gpu, mmu, regs as shared_regs}; /// Name of the G16 platform driver. pub(crate) const DRIVER_NAME: &CStr = c_str!("aurora-g16"); -/// GPU generation reported to userspace. -pub(crate) const GPU_GENERATION: u32 = 16; - -/// Static configuration of a SoC with a G16 GPU. -pub(crate) struct Config { - /// SoC identifier reported to userspace. - pub(crate) chip_id: u32, - /// GPU variant reported to userspace. - pub(crate) gpu_variant: crate::hw::GpuVariant, - /// GPU revision reported to userspace. - pub(crate) gpu_revision: u32, - /// Input address bits translated by each UAT root. - pub(crate) uat_ias: u32, - /// Output (physical) address bits of the UAT. - pub(crate) uat_oas: u32, - /// Clusters and cores per cluster. - pub(crate) num_clusters: u32, - pub(crate) num_cores_per_cluster: u32, - /// Qualified identification register values. - pub(crate) hw_ids: &'static [hw::HwId], - /// Qualified firmware builds. - pub(crate) firmware: &'static [hw::FirmwareBuild], -} +pub(crate) use hw::Config; /// OF match table of the G16 platform driver. const OF_TABLE: kernel::device_id::IdArray = diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 434faf2ee2a046..d854423cb5ed29 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -11,7 +11,7 @@ use kernel::{prelude::*, uapi}; -use super::{hw, Gpu, GPU_GENERATION}; +use super::{hw, Gpu}; use crate::module_parameters; /// Operations per VM_BIND batch at most: batches are atomic and may be large (sparse residency @@ -90,11 +90,6 @@ pub(crate) fn early_tiling() -> bool { /// Fills the generation part of GET_PARAMS group 0. pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Result { - // Match the working J713 C backend identity; SGX register revision fields are - // not the userspace BCD revision. - if gpu.cfg.chip_id != 0x8132 || gpu.cfg.gpu_revision != 0x10 { - 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_FRAGMENT_BARRIERS) @@ -104,7 +99,7 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; - params.gpu_generation = GPU_GENERATION; + params.gpu_generation = gpu.cfg.gpu_generation; params.gpu_variant = gpu.cfg.gpu_variant as u32; params.gpu_revision = gpu.cfg.gpu_revision; params.chip_id = gpu.cfg.chip_id; diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index 225a0ed5d32d42..be4cdb821292e4 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -206,7 +206,7 @@ pub(crate) struct Regs { /// Host-owned generation register page (SGX +0xd60000). generation: Mapping, /// GFXCAXI2AF registers (SGX +0x1000000), written only by the 27.2 start. - axi2af: Mapping, + axi2af: Option, /// 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, @@ -214,7 +214,11 @@ pub(crate) struct Regs { impl Regs { /// Maps the ASC control page and the SGX status window. - pub(crate) fn new(pdev: &platform::Device>, res: G16Resources) -> Result { + pub(crate) fn new( + pdev: &platform::Device>, + res: G16Resources, + cfg: &super::Config, + ) -> Result { let window = |name: &CStr, offset: u64| -> Result { let r = pdev.resource_by_name(name).ok_or(EINVAL)?; let nonposted = r @@ -228,13 +232,21 @@ impl Regs { Ok(Self { 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)?, + generation: window(c_str!("sgx"), super::hw::HOST_BLOCK)?, + axi2af: cfg + .axi2af + .then(|| window(c_str!("sgx"), super::hw::start_27_2::AXI2AF as u64)) + .transpose()?, top: AtomicU32::new(9), res, }) } + /// Physical base of the scratch alias in InitData. + pub(crate) fn host_block_pa(&self) -> u64 { + self.generation.phys + } + /// 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)?; @@ -283,7 +295,10 @@ impl Regs { /// 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(); + let Some(axi2af) = &self.axi2af else { + return Ok(()); + }; + let r = axi2af.io(); for offset in super::hw::start_27_2::AXI2AF_ENABLES { let value = r.try_read32(offset)?; r.try_write32(value | 1, offset)?; 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 a9bdf0a390089d..dffe9f155db0c9 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 @@ -15,11 +15,6 @@ mod hw { 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"] diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs index 925fb72a499313..2f607bd2b27aa7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs @@ -1,5 +1,9 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT #![allow(dead_code)] +mod fw { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/initdata.rs"] + pub mod initdata; +} #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/channels.rs"] mod channels; #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/graph.rs"] @@ -8,11 +12,6 @@ mod fwid { @FWID_BUILD@ } mod hw {pub enum GpuVariant {G}} -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; fn main() { 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 667b38a0998d6a..253696fa2f0031 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -62,7 +62,7 @@ def node(props, children=()): fn set_cell(data: &mut [u8], name: &[u8], value: u32) { let at = property_offset(data, name) + 36; put32(data, at, value); } -fn source() -> perf::Source { perf::parse(MEASURED).unwrap() } +fn source() -> perf::Source { perf::parse(MEASURED, b"gpu,t8132").unwrap() } fn tables() -> wire::Performance { data::select(&source()).unwrap() } fn input(performance: wire::Performance) -> wire::Input { const HOST: u64 = wire::HOST_START; @@ -166,7 +166,7 @@ def node(props, children=()): put32(&mut raw,at+i*8+4,mv+5); } } - let p=data::select(&perf::parse(&raw).unwrap()).unwrap(); + let p=data::select(&perf::parse(&raw, b"gpu,t8132").unwrap()).unwrap(); let encoded=encode(p.clone()).unwrap();let main=&encoded[wire::id::MAIN]; for i in 0..10 { assert_eq!(get32(main,0xfc8+i*4),p.frequency[i]); @@ -179,35 +179,35 @@ def node(props, children=()): assert_eq!(p.frequency[9],1471);assert_eq!(p.voltage[9],975); } #[test] fn truncations_and_overflowing_tree_headers_reject_without_panic() { - for end in 0..MEASURED.len() {assert!(perf::parse(&MEASURED[..end]).is_err());} + for end in 0..MEASURED.len() {assert!(perf::parse(&MEASURED[..end], b"gpu,t8132").is_err());} for at in [0,4,40,property_offset(MEASURED,b"perf-states")+32,property_offset(MEASURED,b"compatible")+32] { let mut bad=MEASURED.to_vec();put32(&mut bad,at,u32::MAX); - assert!(perf::parse(&bad).is_err()); + assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } - assert!(perf::parse(&vec![0;0x20_0001]).is_err()); + assert!(perf::parse(&vec![0;0x20_0001], b"gpu,t8132").is_err()); let mut deep=Vec::new(); for _ in 0..34 {deep.extend_from_slice(&0u32.to_le_bytes());deep.extend_from_slice(&1u32.to_le_bytes());} - deep.extend_from_slice(&[0;8]);assert!(perf::parse(&deep).is_err()); - let mut padded=MEASURED.to_vec();padded.extend_from_slice(&[0;4096]);assert_eq!(perf::parse(&padded),Ok(source())); + deep.extend_from_slice(&[0;8]);assert!(perf::parse(&deep, b"gpu,t8132").is_err()); + let mut padded=MEASURED.to_vec();padded.extend_from_slice(&[0;4096]);assert_eq!(perf::parse(&padded, b"gpu,t8132"),Ok(source())); } #[test] fn missing_wrong_identity_and_duplicate_required_properties_reject() { for name in [b"compatible".as_slice(),b"perf-state-count",b"perf-states",b"perf-states-sram"] { let mut bad=MEASURED.to_vec();let at=property_offset(&bad,name);bad[at]=b'X'; - assert!(perf::parse(&bad).is_err()); + assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } let mut bad=MEASURED.to_vec();let at=property_offset(&bad,b"compatible")+36;bad[at]=b'X'; - assert_eq!(perf::parse(&bad),Err(perf::Error::Identity)); + assert_eq!(perf::parse(&bad, b"gpu,t8132"),Err(perf::Error::Identity)); let mut bad=MEASURED.to_vec();let at=property_offset(&bad,b"perf-states-sram"); bad[at..at+32].fill(0);bad[at..at+11].copy_from_slice(b"perf-states"); - assert_eq!(perf::parse(&bad),Err(perf::Error::Duplicate)); + assert_eq!(perf::parse(&bad, b"gpu,t8132"),Err(perf::Error::Duplicate)); } #[test] fn metadata_shape_frequency_units_off_state_and_voltage_ranges_reject() { for (name,value) in [(b"perf-state-count".as_slice(),0),(b"perf-state-count",33),(b"perf-state-count",15),(b"perf-state-table-count",2),(b"gpu-num-perf-states",14)] { - let mut bad=MEASURED.to_vec();set_cell(&mut bad,name,value);assert!(perf::parse(&bad).is_err()); + let mut bad=MEASURED.to_vec();set_cell(&mut bad,name,value);assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } let at=property_offset(MEASURED,b"perf-states")+36; for (offset,value) in [(0,1),(8,0),(8,338_000_001),(8,3_001_000_000),(12,99),(12,1101)] { - let mut bad=MEASURED.to_vec();put32(&mut bad,at+offset,value);assert!(perf::parse(&bad).is_err()); + let mut bad=MEASURED.to_vec();put32(&mut bad,at+offset,value);assert!(perf::parse(&bad, b"gpu,t8132").is_err()); } } #[test] fn unsupported_shape_pairs_and_ordering_reject_before_encoding() { @@ -256,7 +256,7 @@ def node(props, children=()): 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(); + let full = perf::parse(MEASURED_CLPC, b"gpu,t8132").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)); @@ -275,11 +275,11 @@ def node(props, children=()): ] { let mut bad = MEASURED_CLPC.to_vec(); set_cell(&mut bad, name, 0); - assert_eq!(perf::parse(&bad), Err(perf::Error::Range)); + assert_eq!(perf::parse(&bad, b"gpu,t8132"), 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)); + assert_eq!(perf::parse(&unaligned, b"gpu,t8132"), Err(perf::Error::Range)); } ''' for marker, value in {'PARSER': backend / 'adt/perf.rs', 'ENCODER': backend / 'fw/initdata.rs', From 1620c5f2a3fbea582596d94fd3a0480f7a6cecb9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:18:26 -0500 Subject: [PATCH 1249/1514] wifi: apple: centauri: guard scan stop entry, timeout exit, and abort wait Address post-sleep unlock window races across both the T6050 and shared Centauri Wi-Fi scan loops: - Guard scan_stop_chunk() entry in both drivers with the transport state check before issuing command 65537, and re-check transport state plus one final drain() after the scan/stop wait loops exit at deadline. - In shared centauri_wifi.c scan_worker(), propagate scan_stop_chunk() errors/timeouts to ret and check transport/abort state before starting each subsequent chunk. - Factor out scan_wait_stop() in shared centauri_wifi.c so an abort arriving after command 65537 was already sent still waits for the in-flight 0x80000005 completion unless the transport stops. - Extend tools/asahi/centauri-scan-tests.py to cover all three races against both drivers' production functions and add negative controls. Signed-off-by: Diljit Singh --- .../wireless/apple/centauri/centauri_wifi.c | 86 ++++-- .../apple/centauri/t6050/centauri_wifi.c | 31 +- tools/asahi/centauri-scan-tests.py | 289 +++++++++++++++++- 3 files changed, 362 insertions(+), 44 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index 566536bec817c9..7f953bf1d27cce 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -913,23 +913,19 @@ static size_t build_scan(struct centauri_wifi *wifi, unsigned int chunk, u8 *buf return size; } -static int scan_stop_chunk(struct centauri_wifi *wifi, u32 done) +static bool scan_transport_stopped(struct centauri_wifi *wifi) { - unsigned long deadline; - int ret; + return READ_ONCE(wifi->stopping) || + READ_ONCE(wifi->transport_paused) || + readl(wifi->a.bar + 8) != 2; +} + +static int scan_wait_stop(struct centauri_wifi *wifi, u32 done) +{ + unsigned long deadline = jiffies + msecs_to_jiffies(1000); - ret = command(wifi, 65537, NULL, 0); - if (wifi->scans_done != done) - return 0; - if (ret == -EREMOTEIO && wifi->reply_status == 342) - return 0; - if (ret) - return ret; - deadline = jiffies + msecs_to_jiffies(1000); do { - if (READ_ONCE(wifi->stopping) || - READ_ONCE(wifi->transport_paused) || - readl(wifi->a.bar + 8) != 2) + if (scan_transport_stopped(wifi)) return -EIO; drain(wifi); if (wifi->scans_done != done) @@ -938,7 +934,26 @@ static int scan_stop_chunk(struct centauri_wifi *wifi, u32 done) usleep_range(1000, 2000); mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); - return -ETIMEDOUT; + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + return wifi->scans_done != done ? 0 : -ETIMEDOUT; +} + +static int scan_stop_chunk(struct centauri_wifi *wifi, u32 done) +{ + int ret; + + if (scan_transport_stopped(wifi)) + return -EIO; + ret = command(wifi, 65537, NULL, 0); + if (wifi->scans_done != done) + return 0; + if (ret == -EREMOTEIO && wifi->reply_status == 342) + return 0; + if (ret) + return ret; + return scan_wait_stop(wifi, done); } static void scan_worker(struct work_struct *work) @@ -962,6 +977,14 @@ static void scan_worker(struct work_struct *work) unsigned long deadline, progress; bool stopped = false, refused = false; + if (scan_transport_stopped(wifi)) { + ret = -EIO; + break; + } + if (READ_ONCE(wifi->scan_abort)) { + ret = -ECANCELED; + break; + } scan_size = build_scan(wifi, chunk, scan); ret = command(wifi, 65551, scan, scan_size); if (ret) @@ -981,9 +1004,7 @@ static void scan_worker(struct work_struct *work) msecs_to_jiffies(max(8000U, count * 2 * SCAN_PASSIVE_DWELL_MS + 2000)); progress = jiffies; do { - if (READ_ONCE(wifi->stopping) || - READ_ONCE(wifi->transport_paused) || - readl(wifi->a.bar + 8) != 2) { + if (scan_transport_stopped(wifi)) { ret = -EIO; break; } @@ -991,9 +1012,10 @@ static void scan_worker(struct work_struct *work) if (wifi->scans_done != done) break; if (READ_ONCE(wifi->scan_abort)) { - if (!stopped) - scan_stop_chunk(wifi, done); - ret = -ECANCELED; + int stop_ret = stopped ? scan_wait_stop(wifi, done) : + scan_stop_chunk(wifi, done); + + ret = stop_ret == -EIO ? -EIO : -ECANCELED; break; } if (wifi->channels_seen != seen) { @@ -1024,15 +1046,23 @@ static void scan_worker(struct work_struct *work) mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); if (!ret && !refused && wifi->scans_done == done) { - dev_warn(&wifi->control->pdev->dev, - "Wi-Fi scan chunk %u: %u of %u channels, no scan event%s\n", chunk, - wifi->channels_seen - channels, count, - stopped ? " after the stop" : ""); - if (!stopped) - scan_stop_chunk(wifi, done); + if (scan_transport_stopped(wifi)) { + ret = -EIO; + } else { + drain(wifi); + if (wifi->scans_done == done) { + dev_warn(&wifi->control->pdev->dev, + "Wi-Fi scan chunk %u: %u of %u channels, no scan event%s\n", + chunk, wifi->channels_seen - channels, count, + stopped ? " after the stop" : ""); + ret = stopped ? -ETIMEDOUT : + scan_stop_chunk(wifi, done); + } + } } } - info.aborted = !!ret; + info.aborted = !!ret || READ_ONCE(wifi->scan_abort) || + READ_ONCE(wifi->stopping); request = wifi->scan_request; wifi->scan_request = NULL; mutex_unlock(&wifi->lock); diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index 4dcfa99802b9e4..81c6593c8e8631 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -1140,12 +1140,20 @@ static int radio_start(struct centauri_t6050_wifi *wifi) #define SCAN_ACTIVE_MIN_MS 40 #define SCAN_LISTEN_MS 110 +static bool scan_transport_stopped(struct centauri_t6050_wifi *wifi) +{ + return READ_ONCE(wifi->stopping) || wifi->command_failed || + wifi->host_sleep_sent || readl(wifi->a.bar + 8) != 2; +} + static int scan_stop_chunk(struct centauri_t6050_wifi *wifi, u32 done) { unsigned long deadline; int ret; lockdep_assert_held(&wifi->lock); + if (scan_transport_stopped(wifi)) + return -EIO; ret = command(wifi, 65537, NULL, 0); if (wifi->scans_done != done) return 0; @@ -1155,8 +1163,7 @@ static int scan_stop_chunk(struct centauri_t6050_wifi *wifi, u32 done) return ret; deadline = jiffies + msecs_to_jiffies(1000); do { - if (READ_ONCE(wifi->stopping) || wifi->command_failed || - wifi->host_sleep_sent || readl(wifi->a.bar + 8) != 2) + if (scan_transport_stopped(wifi)) return -EIO; drain(wifi); if (wifi->scans_done != done) @@ -1165,7 +1172,10 @@ static int scan_stop_chunk(struct centauri_t6050_wifi *wifi, u32 done) usleep_range(1000, 2000); mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); - return -ETIMEDOUT; + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + return wifi->scans_done != done ? 0 : -ETIMEDOUT; } static int scan_profile27(struct centauri_t6050_wifi *wifi) @@ -1185,6 +1195,8 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) unsigned long deadline; int ret; + if (scan_transport_stopped(wifi)) + return -EIO; if (READ_ONCE(wifi->scan_abort)) return -ECANCELED; memset(scan, 0, sizeof(scan)); @@ -1255,9 +1267,7 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) deadline = jiffies + msecs_to_jiffies(max(8000U, count * 220 + 2000)); do { - if (READ_ONCE(wifi->stopping) || wifi->command_failed || - wifi->host_sleep_sent || - readl(wifi->a.bar + 8) != 2) + if (scan_transport_stopped(wifi)) return -EIO; drain(wifi); if (wifi->scans_done != done) @@ -1270,12 +1280,17 @@ static int scan_profile27(struct centauri_t6050_wifi *wifi) usleep_range(1000, 2000); mutex_lock(&wifi->lock); } while (time_before(jiffies, deadline)); + if (wifi->scans_done == done) { + if (scan_transport_stopped(wifi)) + return -EIO; + drain(wifi); + } if (wifi->scans_done == done) { dev_warn(&wifi->control->pdev->dev, "Wi-Fi scan of %u channels: no completion event\n", count); - scan_stop_chunk(wifi, done); - return -ETIMEDOUT; + ret = scan_stop_chunk(wifi, done); + return ret == -EIO ? -EIO : -ETIMEDOUT; } if (wifi->scan_status) dev_warn(&wifi->control->pdev->dev, diff --git a/tools/asahi/centauri-scan-tests.py b/tools/asahi/centauri-scan-tests.py index 266aa6fc74cba4..cb41035cf500bc 100755 --- a/tools/asahi/centauri-scan-tests.py +++ b/tools/asahi/centauri-scan-tests.py @@ -111,8 +111,11 @@ def extract_fn(source, name): static unsigned long jiffies; static unsigned int bar_reads, sleep_calls, link_queries, stop_commands; static unsigned int stop_event_delay, complete_after_drains, drains_seen; +static unsigned int sleep_step_ms, sleep_sets_host_sleep_at; +static unsigned int sleep_completes_on_drain_at; static bool stop_refuse_342, stop_refuse_other, sleep_sets_abort; static bool sleep_sets_host_sleep, sleep_checks_station, station_ran_in_sleep; +static u32 bar_state; static u8 fake_bar[32]; static struct centauri_t6050_wifi *g_wifi; @@ -122,7 +125,7 @@ def extract_fn(source, name): static void mutex_lock(int *l) { assert(!*l); *l = 1; } static void mutex_unlock(int *l) { assert(*l); *l = 0; } static void put_unaligned_le16(u16 v, void *p) { memcpy(p, &v, 2); } -static u32 readl(void *addr) { (void)addr; bar_reads++; return 2; } +static u32 readl(void *addr) { (void)addr; bar_reads++; return bar_state; } static int firmware_band(int band) { return band; } static int ieee80211_frequency_to_channel(u32 freq) { @@ -179,7 +182,7 @@ def extract_fn(source, name): { (void)a; (void)b; sleep_calls++; - jiffies += 250; + jiffies += sleep_step_ms ? sleep_step_ms : 250; /* Must not hold wifi->lock across scan wait sleeps. */ assert(!g_wifi->lock); if (sleep_checks_station && !station_ran_in_sleep) { @@ -201,6 +204,11 @@ def extract_fn(source, name): g_wifi->host_sleep_sent = true; sleep_sets_host_sleep = false; } + if (sleep_sets_host_sleep_at && sleep_calls == sleep_sets_host_sleep_at) + g_wifi->host_sleep_sent = true; + if (sleep_completes_on_drain_at && + sleep_calls == sleep_completes_on_drain_at) + complete_after_drains = drains_seen + 1; } ''' @@ -228,8 +236,11 @@ def extract_fn(source, name): wifi.station_signal_at = 0; g_wifi = &wifi; jiffies = 2000; + bar_state = 2; bar_reads = sleep_calls = link_queries = stop_commands = 0; stop_event_delay = complete_after_drains = drains_seen = 0; + sleep_step_ms = sleep_sets_host_sleep_at = 0; + sleep_completes_on_drain_at = 0; stop_refuse_342 = stop_refuse_other = false; sleep_sets_abort = sleep_sets_host_sleep = false; sleep_checks_station = station_ran_in_sleep = false; @@ -283,15 +294,229 @@ def extract_fn(source, name): mutex_unlock(&wifi.lock); assert(stop_commands == 1 && wifi.scans_done == 1); - /* 5. Host sleep entered while unlocked aborts without BAR read. */ + /* 5. Host sleep entered while unlocked aborts without BAR read or stop cmd. */ reset_wifi(); sleep_sets_host_sleep = true; mutex_lock(&wifi.lock); assert(scan_profile27(&wifi) == -EIO); mutex_unlock(&wifi.lock); - assert(bar_reads == 1); + assert(bar_reads == 2 && stop_commands == 0); + + /* 6. scan_stop_chunk() entry guard refuses to ring doorbell when stopped. */ + reset_wifi(); + wifi.host_sleep_sent = true; + mutex_lock(&wifi.lock); + assert(scan_stop_chunk(&wifi, 0) == -EIO); + mutex_unlock(&wifi.lock); + assert(stop_commands == 0 && bar_reads == 0); + + /* 7. Host sleep set during the final sleep as deadline expires skips 65537. */ + reset_wifi(); + sleep_step_ms = 9000; + sleep_sets_host_sleep_at = 1; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == -EIO); + mutex_unlock(&wifi.lock); + assert(sleep_calls == 1 && stop_commands == 0); + + /* 8. Completion arriving during final sleep as deadline expires succeeds cleanly. */ + reset_wifi(); + sleep_step_ms = 9000; + sleep_completes_on_drain_at = 1; + mutex_lock(&wifi.lock); + assert(scan_profile27(&wifi) == 0); + mutex_unlock(&wifi.lock); + assert(sleep_calls == 1 && stop_commands == 0 && wifi.scans_done == 1); + + puts("PASS: Centauri T6050 Wi-Fi scan lock-release and stop synchronization"); + return 0; +} +''' + +SHARED_WIFI_PRELUDE = r''' +#include +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define SCAN_PASSIVE_DWELL_MS 110 +#define msecs_to_jiffies(x) ((unsigned long)(x)) +#define time_before(a, b) ((long)((a) - (b)) < 0) +#define time_after(a, b) time_before(b, a) +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min_t(type, x, y) ((type)(x) < (type)(y) ? (type)(x) : (type)(y)) +#define container_of(ptr, type, member) \ + ((type *)((char *)(ptr) - __builtin_offsetof(type, member))) +static void dev_warn(void *d, const char *fmt, ...) { (void)d; (void)fmt; } +static void dev_info(void *d, const char *fmt, ...) { (void)d; (void)fmt; } +static void dev_dbg(void *d, const char *fmt, ...) { (void)d; (void)fmt; } + +static const u8 five_ghz[25] = { 0 }; + +struct device { int dummy; }; +struct pci_dev { struct device dev; }; +struct centauri { struct pci_dev *pdev; }; +struct work_struct { int dummy; }; +struct cfg80211_scan_request { int dummy; }; +struct cfg80211_scan_info { bool aborted; }; +struct centauri_wifi { + struct centauri *control; + struct { u8 *bar; } a; + struct work_struct scan_work; + struct cfg80211_scan_request *scan_request; + bool scan_abort; + int lock; + u16 reply_status; + u32 channels_seen, scans_done, beacons_seen; + bool stopping, transport_paused; +}; + +static unsigned long jiffies; +static unsigned int scan_commands, stop_commands, sleep_calls, drains_seen; +static unsigned int sleep_step_ms, sleep_sets_paused_at, sleep_sets_abort_at; +static unsigned int complete_on_stop_drain, channels_per_drain; +static bool stop_never_completes, last_scan_aborted, scan_done_called; +static bool pause_between_chunks; +static u32 bar_state; +static u8 fake_bar[32]; +static struct centauri_wifi *g_swifi; + +static void mutex_lock(int *l) { assert(!*l); *l = 1; } +static void mutex_unlock(int *l) { assert(*l); *l = 0; } +static u32 readl(void *addr) { (void)addr; return bar_state; } +static size_t build_scan(struct centauri_wifi *w, unsigned int c, u8 *b) +{ + (void)w; (void)c; (void)b; + return 14; +} +static void cfg80211_scan_done(struct cfg80211_scan_request *r, + struct cfg80211_scan_info *info) +{ + (void)r; + scan_done_called = true; + last_scan_aborted = info->aborted; +} +static int command(struct centauri_wifi *wifi, u32 id, + const void *payload, size_t size) +{ + (void)payload; (void)size; + assert(wifi->lock); + if (id == 65551) { + scan_commands++; + return 0; + } + if (id == 65537) { + stop_commands++; + wifi->reply_status = 0; + return 0; + } + return 0; +} +static void drain(struct centauri_wifi *wifi) +{ + assert(wifi->lock); + drains_seen++; + if (channels_per_drain) + wifi->channels_seen += channels_per_drain; + if (stop_commands && !stop_never_completes && complete_on_stop_drain) { + complete_on_stop_drain--; + if (!complete_on_stop_drain) { + wifi->scans_done++; + if (pause_between_chunks) + wifi->transport_paused = true; + } + } +} +static void usleep_range(unsigned long a, unsigned long b) +{ + (void)a; (void)b; + sleep_calls++; + jiffies += sleep_step_ms ? sleep_step_ms : 250; + assert(!g_swifi->lock); + if (sleep_sets_paused_at && sleep_calls == sleep_sets_paused_at) + g_swifi->transport_paused = true; + if (sleep_sets_abort_at && sleep_calls == sleep_sets_abort_at) + g_swifi->scan_abort = true; +} +''' + +SHARED_WIFI_TESTS = r''' +static struct pci_dev spdev; +static struct centauri sctrl = { .pdev = &spdev }; +static struct cfg80211_scan_request sreq; +static struct centauri_wifi swifi; - puts("PASS: Centauri Wi-Fi scan lock-release and stop synchronization"); +static void reset_swifi(void) +{ + memset(&swifi, 0, sizeof(swifi)); + swifi.control = &sctrl; + swifi.a.bar = fake_bar; + swifi.scan_request = &sreq; + g_swifi = &swifi; + jiffies = 2000; + bar_state = 2; + scan_commands = stop_commands = sleep_calls = drains_seen = 0; + sleep_step_ms = sleep_sets_paused_at = sleep_sets_abort_at = 0; + complete_on_stop_drain = channels_per_drain = 0; + stop_never_completes = last_scan_aborted = scan_done_called = false; + pause_between_chunks = false; +} + +int main(void) +{ + /* 1. Entry guard in scan_stop_chunk() skips command(65537) when paused. */ + reset_swifi(); + swifi.transport_paused = true; + mutex_lock(&swifi.lock); + assert(scan_stop_chunk(&swifi, 0) == -EIO); + mutex_unlock(&swifi.lock); + assert(stop_commands == 0); + + /* 2. Transport paused during final sleep at deadline skips 65537 and next chunk. */ + reset_swifi(); + sleep_step_ms = 9000; + sleep_sets_paused_at = 1; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 0); + + /* 3. Timeout whose stop times out propagates error and does NOT start chunk 1. */ + reset_swifi(); + sleep_step_ms = 9000; + stop_never_completes = true; + scan_worker(&swifi.scan_work); + assert(scan_commands == 1 && stop_commands == 1); + assert(scan_done_called && last_scan_aborted); + + /* 4. Transport paused between chunks stops before starting chunk 1. */ + reset_swifi(); + sleep_step_ms = 9000; + complete_on_stop_drain = 1; + pause_between_chunks = true; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 1); + + /* 5. Abort arriving after 65537 already sent (stopped=true) still waits for 0x05. */ + reset_swifi(); + channels_per_drain = 13; + sleep_sets_abort_at = 1; + complete_on_stop_drain = 3; + scan_worker(&swifi.scan_work); + assert(scan_done_called && last_scan_aborted); + assert(scan_commands == 1 && stop_commands == 1 && swifi.scans_done == 1); + + puts("PASS: Centauri shared Wi-Fi scan stop/abort/chunk state checks"); return 0; } ''' @@ -496,11 +721,28 @@ def main(): wifi_src = ( root / "drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c" ).read_text() + shared_src = ( + root / "drivers/net/wireless/apple/centauri/centauri_wifi.c" + ).read_text() bt_src = (root / "drivers/bluetooth/btcentauri_t6050.c").read_text() wifi_prod = "\n\n".join( extract_fn(wifi_src, name) - for name in ("scan_stop_chunk", "scan_profile27", "fill_station") + for name in ( + "scan_transport_stopped", + "scan_stop_chunk", + "scan_profile27", + "fill_station", + ) + ) + shared_prod = "\n\n".join( + extract_fn(shared_src, name) + for name in ( + "scan_transport_stopped", + "scan_wait_stop", + "scan_stop_chunk", + "scan_worker", + ) ) bt_prod = "\n\n".join( extract_fn(bt_src, name) @@ -508,6 +750,9 @@ def main(): ) wifi_variants = [("wifi-production", WIFI_PRELUDE + wifi_prod + WIFI_TESTS, 0, None)] + shared_variants = [ + ("shared-wifi-production", SHARED_WIFI_PRELUDE + shared_prod + SHARED_WIFI_TESTS, 0, None) + ] bt_variants = [("bt-production", BT_PRELUDE + bt_prod + BT_TESTS, 0, None)] if args.negative_controls: @@ -526,7 +771,7 @@ def main(): ), ( "timeout-skips-stop-wait", - "\t\t\tscan_stop_chunk(wifi, done);\n\t\t\treturn -ETIMEDOUT;", + "\t\t\tret = scan_stop_chunk(wifi, done);\n\t\t\treturn ret == -EIO ? -EIO : -ETIMEDOUT;", "\t\t\tcommand(wifi, 65537, NULL, 0);\n\t\t\treturn -ETIMEDOUT;", "wifi.scans_done == 1", ), @@ -536,6 +781,12 @@ def main(): "if (false && ret == -EREMOTEIO && wifi->reply_status == 342)\n\t\treturn 0;", "scan_stop_chunk(&wifi, 0) == 0", ), + ( + "t6050-stop-skips-entry-guard", + "\tlockdep_assert_held(&wifi->lock);\n\tif (scan_transport_stopped(wifi))\n\t\treturn -EIO;", + "\tlockdep_assert_held(&wifi->lock);", + "stop_commands == 0", + ), ] for name, old, new, expected_msg in wifi_controls: if old not in wifi_prod: @@ -545,6 +796,28 @@ def main(): -signal.SIGABRT, expected_msg) ) + shared_controls = [ + ( + "shared-timeout-drops-stop-ret", + "\t\t\t\t\tret = stopped ? -ETIMEDOUT :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "\t\t\t\t\tif (!stopped)\n\t\t\t\t\t\tscan_stop_chunk(wifi, done);", + "scan_commands == 1", + ), + ( + "shared-abort-skips-inflight-stop-wait", + "\t\t\t\tint stop_ret = stopped ? scan_wait_stop(wifi, done) :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "\t\t\t\tint stop_ret = stopped ? 0 :\n\t\t\t\t\t scan_stop_chunk(wifi, done);", + "swifi.scans_done == 1", + ), + ] + for name, old, new, expected_msg in shared_controls: + if old not in shared_prod: + raise RuntimeError(f"missing pattern for {name}") + shared_variants.append( + (name, SHARED_WIFI_PRELUDE + shared_prod.replace(old, new, 1) + SHARED_WIFI_TESTS, + -signal.SIGABRT, expected_msg) + ) + bt_controls = [ ( "bt-drops-rx-reschedule", @@ -572,7 +845,7 @@ def main(): with tempfile.TemporaryDirectory(prefix="centauri-scan-test-") as directory: out = args.out or Path(directory) out.mkdir(parents=True, exist_ok=True) - for name, code, expected, msg in wifi_variants + bt_variants: + for name, code, expected, msg in wifi_variants + shared_variants + bt_variants: harness, binary = out / (name + ".c"), out / name harness.write_text(code) subprocess.run( From 9dc11d97d2c7472fa1decf2db7ec306571fc7987 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:23:53 -0500 Subject: [PATCH 1250/1514] drm/asahi: admit T6030 G15S firmware 26B123 Qualify the J516s G15S 26B123 image through the shared classic backend. Share the 26B123 protocol while selecting the G15S InitData version, register map, TX geometry, host block sequence, and nine firmware DVFS rows derived from the fourteen original ADT states. Keep power sampling and low-peak limiter parameters derived strictly from the machine's live ADT rather than hardcoded overrides. Route the T6030 platform match by presence of the boot loader's handoff marker and order startup after a handed-over T6030 display, without requiring the T8132 PMP bridge or touching AXI2AF. On GPU nodes without an apple,pmp telemetry provider, keep thermal cooling active with a background SoC die thermal-zone sampler (macsmc_soc_die and apple_pmp_hotspot) feeding a fail-closed backstop that starts at S1, releases gradually after 200 ms of valid cool readings, throttles above 80 C, and clamps immediately to S1 on critical heat or missing, stale, or implausible telemetry. Run the shared firmware-halted fault scan over the valid SGX banks (selectors 0 and 1 on G15S, 0..7 on G16G) and restore the original selector even if reading one bank fails. Encode the DVFS ceiling in the shared 26B123 power fields and verify ADT-derived G15S power sampling, low-peak limiter encoding, and fail-closed thermal-zone policy in host tests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/Kconfig | 14 +- drivers/gpu/drm/asahi/g15/mod.rs | 12 +- drivers/gpu/drm/asahi/g16/adt.rs | 24 +- drivers/gpu/drm/asahi/g16/board.rs | 23 +- drivers/gpu/drm/asahi/g16/board/data.rs | 31 +- drivers/gpu/drm/asahi/g16/boot.rs | 76 +++-- drivers/gpu/drm/asahi/g16/channel.rs | 66 +++- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 285 ++++++++++++++---- drivers/gpu/drm/asahi/g16/fw/mod.rs | 8 - drivers/gpu/drm/asahi/g16/glue.c | 159 ++++++++-- drivers/gpu/drm/asahi/g16/glue.h | 3 + drivers/gpu/drm/asahi/g16/hw.rs | 156 +++++++++- drivers/gpu/drm/asahi/g16/initdata.rs | 52 +++- drivers/gpu/drm/asahi/g16/mod.rs | 36 ++- drivers/gpu/drm/asahi/g16/params.rs | 2 +- drivers/gpu/drm/asahi/g16/power.rs | 47 ++- drivers/gpu/drm/asahi/g16/power/policy.rs | 177 +++++++++++ drivers/gpu/drm/asahi/g16/recovery.rs | 7 +- drivers/gpu/drm/asahi/g16/regs.rs | 94 +++--- drivers/gpu/drm/asahi/g16/sleep.rs | 3 + tools/asahi/g15-display-order-tests.py | 19 +- tools/asahi/g15-probe-init-tests.py | 27 +- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 13 +- .../drivers/gpu/asahi-m4/check-channels.rs | 14 +- .../gpu/asahi-m4/check-initdata-bounds.rs | 1 + .../drivers/gpu/asahi-m4/check-initdata.rs | 1 + .../drivers/gpu/asahi-m4/test-perf.py | 66 +++- 27 files changed, 1176 insertions(+), 240 deletions(-) diff --git a/drivers/gpu/drm/asahi/Kconfig b/drivers/gpu/drm/asahi/Kconfig index 8f5f8b50e668ad..19aa4861861b31 100644 --- a/drivers/gpu/drm/asahi/Kconfig +++ b/drivers/gpu/drm/asahi/Kconfig @@ -29,7 +29,7 @@ config DRM_ASAHI be called aurora. It keeps "asahi" as a module alias. config DRM_ASAHI_G16 - bool "Apple M4 (G16G) support" + bool "Apple M4 (G16G) and M3 Pro (G15S 27.2) support" depends on DRM_ASAHI && ARM64 depends on DRM_APPLE=y || (DRM_APPLE=m && DRM_ASAHI=m) depends on DRM_APPLE_DCP_T8132 @@ -38,12 +38,12 @@ config DRM_ASAHI_G16 depends on THERMAL_OF default y help - Backend for the M4 (T8132) GPU running the 25G83 firmware of - macOS 26.6.2, which the boot loader leaves loaded. The driver - binds when the GPU node appears and starts the firmware once the - PMP supplier, and a native display the boot loader handed over, - are up. The firmware session is retained until reboot and stays - running across suspend-to-idle. + Shared backend for the M4 (T8132) GPU on firmware 25G83 or + 26B123 and the M3 Pro (T6030) GPU on 26B123. The boot loader + leaves the firmware loaded and publishes its handoff. A native + display, if handed over, starts before the GPU. T8132 also + retains its PMP supplier. The firmware session is retained until + reboot and stays running across suspend-to-idle. A rendering VM pins about 0.7 GiB. An aborted receipt disables that command class until reboot. diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 4cb221fb0a5df6..9b45de2b1ce63c 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -202,10 +202,20 @@ impl platform::Driver for Driver<'_> { // after probe_g15 started firmware would return an unbound device. try_pin_init!(Driver { _driver: { + let cfg = *info.ok_or(ENODEV)?; + if cfg.chip_id == 0x6030 + && pdev.as_ref().of_node().is_some_and(|node| { + !matches!( + node.get_opt_property::(c_str!("apple,g16-handoff-version")), + Ok(None) + ) + }) + { + return Err(ENODEV); + } if !MODULE_READY.load(Ordering::Acquire) { return Err(EPROBE_DEFER); } - let cfg = *info.ok_or(ENODEV)?; dev_info!(pdev.as_ref(), "G15: probing ({})\n", cfg.name); match crate::driver::AsahiPlatformDriver::probe_g15(pdev, cfg) { Ok(driver) => Some(driver), diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 84330216d0200e..03eb49322ca8f9 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -1,11 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! J713's explicit boot-loader GPU handoff. +//! Explicit boot-loader GPU handoff. //! -//! Unlike the synthesized T6030 node, J713 supplies six named no-map reservations and an -//! explicit segment/handoff ABI. Admit those reservations before mapping anything. The -//! performance-state source is the machine's original ADT, preserved by m1n1 in the named -//! phram reservation. It is copied and parsed before any firmware-visible write. +//! The boot loader supplies six named no-map reservations and an explicit +//! segment/handoff ABI. Admission checks the reservations before mapping. +//! The boot loader preserves the original ADT in the named phram reservation. +//! The driver copies and parses it before any firmware-visible write. #[path = "adt/perf.rs"] pub(crate) mod perf; @@ -120,6 +120,17 @@ fn performance_source(regions: &[Range]) -> Result<(KVVec, u64)> { Ok((copy?, start)) } +/// Whether the boot loader selected this backend. Presence is enough to route probe; +/// admission independently validates the property and the complete handoff. +pub(super) fn has_handoff(dev: &device::Device) -> bool { + dev.of_node().is_some_and(|node| { + !matches!( + node.get_opt_property::(c_str!("apple,g16-handoff-version")), + Ok(None) + ) + }) +} + /// 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)?; @@ -145,7 +156,8 @@ pub(crate) fn read(dev: &device::Device, cfg: &Config) -> Result> { 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"))?; - let layout = cfg.layouts + let layout = cfg + .layouts .iter() .copied() .find(|layout| layout.matches(version, &vas, &flags)); diff --git a/drivers/gpu/drm/asahi/g16/board.rs b/drivers/gpu/drm/asahi/g16/board.rs index cdc4f27d19528c..1d631276ac1fee 100644 --- a/drivers/gpu/drm/asahi/g16/board.rs +++ b/drivers/gpu/drm/asahi/g16/board.rs @@ -16,15 +16,20 @@ use kernel::{device, prelude::*}; /// 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!( - dev, - "M4 original ADT performance layout rejected: {:?}\n", - error - ); - EINVAL - })?; +pub(crate) fn qualify( + dev: &device::Device, + adt: &GpuAdt, + source_layout: data::SourceLayout, +) -> Result { + let (performance, layout) = + data::select_for(&adt.performance, source_layout).map_err(|error| { + dev_err!( + dev, + "M4 original ADT performance layout rejected: {:?}\n", + error + ); + EINVAL + })?; dev_info!( dev, "M4 ADT DVFS: {} source states -> {} firmware rows ({} layout), top {} MHz\n", diff --git a/drivers/gpu/drm/asahi/g16/board/data.rs b/drivers/gpu/drm/asahi/g16/board/data.rs index fe5a7f2404a86e..ee203adbc736ab 100644 --- a/drivers/gpu/drm/asahi/g16/board/data.rs +++ b/drivers/gpu/drm/asahi/g16/board/data.rs @@ -8,6 +8,12 @@ pub(crate) const SOURCE_STATES: usize = 16; +#[derive(Clone, Copy)] +pub(crate) enum SourceLayout { + T8132, + T6030, +} + /// One qualified mapping of the ADT states onto the first `rows` firmware rows. pub(crate) struct Layout { pub(crate) name: &'static str, @@ -39,6 +45,15 @@ pub(crate) const LAYOUTS: [Layout; 2] = [ }, ]; +// Three low states, then five equal-voltage pairs. The equal frequency at source +// states 9 and 10 belongs to two voltage bins and is kept in both rows. +const T6030_LAYOUT: Layout = Layout { + name: "9-row", + rows: 9, + main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 0, 0], + auxiliary: [0, 1, 2, 3, 4, 6, 8, 10, 12, 0, 0], +}; + use super::super::fw::initdata::{Performance, PERF_STATES}; /// Allocation-free selection, also exercised directly by the host-side source-data tests. @@ -51,12 +66,24 @@ pub(crate) fn select( /// 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> { + select_for(source, SourceLayout::T8132) +} + +/// Selects firmware rows using the qualified layout for this SoC. +pub(crate) fn select_for( + source: &super::super::adt::perf::Source, + layout: SourceLayout, ) -> core::result::Result<(Performance, &'static str), super::super::adt::perf::Error> { use super::super::adt::perf::Error; - if source.count != SOURCE_STATES { + let (count, layouts) = match layout { + SourceLayout::T8132 => (SOURCE_STATES, LAYOUTS.as_slice()), + SourceLayout::T6030 => (14, core::slice::from_ref(&T6030_LAYOUT)), + }; + if source.count != count { return Err(Error::Shape); } - for layout in LAYOUTS.iter() { + for layout in layouts { match select_layout(source, layout) { Err(Error::Shape) => continue, Err(error) => return Err(error), diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index ce14ce9f021c3d..eac8b29a6ed05e 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -533,8 +533,8 @@ impl Session { self.while_powered(regs::Regs::engine_state) } - /// All eight engine fault banks, for a firmware halted for recovery, or `None` while the GPU - /// is powered down. + /// All supported engine fault banks while firmware is 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) } @@ -543,6 +543,11 @@ impl Session { /// 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 { + // On G15S this word belongs to submit channel 0. The device-control + // producer is supplied by its separate InitData pointer. + if self.adt.layout.initdata.tx == super::fw::initdata::TxLayout::RingHeader { + return Ok(()); + } if !self.booted { return self.regs.set_generation(value); } @@ -675,13 +680,18 @@ pub(crate) fn admit( if power_offset != cfg.power_offset || (power_state >> 4) & 0xf != 0xf { dev_err!( dev, - "M4 GFX domain not admitted: register{:#x} state{:#x}\n", + "GFX domain not admitted: register{:#x} state{:#x}\n", power_offset, power_state ); return Err(Error::from_errno(-(bindings::EHOSTDOWN as i32))); } - dev_info!(dev, "T8132 G16G admitted, ASC={:#x}\n", regs.asc_control()?); + dev_info!( + dev, + "T{:x} GPU admitted, ASC={:#x}\n", + cfg.chip_id, + regs.asc_control()? + ); Ok(KBox::init(init!(Admitted { regs, adt }), GFP_KERNEL)?) } @@ -768,6 +778,7 @@ fn run( session: &mut Session, events: &mut Events, built: &mut (InitData, Channels, u32), + cfg: &Config, log_buffer: Option<(u64, usize)>, ) -> Result { let dev = session.dev.clone(); @@ -816,12 +827,13 @@ 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 - ); + if let Some(probe) = session.regs.publish_host_block(cfg)? { + 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)?; @@ -847,7 +859,13 @@ fn run( hw::ep::FIRMWARE, hw::ep::INITDATA | (root & hw::ep::INITDATA_ADDR_MASK), )?; - session.send(hw::ep::DOORBELL, 0x0083000000000011)?; + let g15s_channels = init.layout.tx == super::fw::initdata::TxLayout::RingHeader; + let init_kick = if g15s_channels { + hw::engine::DEVCTL_DOORBELL + } else { + hw::engine::DEVCTL_INIT_DOORBELL + }; + session.send(hw::ep::DOORBELL, init_kick)?; wait_boot_control(session, channels, events, init, 1, 5000)?; let base = 1; let scheduler = init.control.as_ref().ok_or(EINVAL)?; @@ -880,7 +898,12 @@ fn run( regs::wmb(); devctl_op(session, channels, events, init, devctl.start)?; wait_boot_control(session, channels, events, init, base + 2, 2000)?; - session.send(hw::ep::DOORBELL, 0x0083000000000010)?; + let receive_kick = if g15s_channels { + hw::engine::G15S_RECEIVE_DOORBELL + } else { + hw::engine::RECEIVE_DOORBELL + }; + session.send(hw::ep::DOORBELL, receive_kick)?; for _ in 0..10 { fsleep(Delta::from_millis(10)); channels.drain_rings(&dev, events)?; @@ -976,7 +999,8 @@ pub(crate) fn start( let id = regs.identity()?; dev_info!( d, - "M4 G16G: power acknowledged, version={:#x} counts={:#x} core-mask={:#x}\n", + "T{:x}: power acknowledged, version={:#x} counts={:#x} core-mask={:#x}\n", + cfg.chip_id, id.version, id.counts, id.cores @@ -988,21 +1012,21 @@ pub(crate) fn start( { dev_err!( d, - "unsupported G16G hardware: version {:#x} counts {:#x}\n", + "unsupported GPU hardware: version {:#x} counts {:#x}\n", id.version, id.counts ); return Err(eproto()); } - if id.cores >> cfg.core_slots() != 0 - || id.core_masks[..cfg.num_clusters as usize].contains(&0) + if id.cores >> cfg.core_slots() != 0 || id.core_masks[..cfg.num_clusters as usize].contains(&0) { - dev_err!(d, "implausible G16G core mask {:#x}\n", id.cores); + dev_err!(d, "implausible GPU core mask {:#x}\n", id.cores); return Err(eproto()); } dev_info!( d, - "M4 G16G: {} cores enabled\n", + "T{:x}: {} cores enabled\n", + cfg.chip_id, id.cores.count_ones() ); if regs.pstate()? > regs.top() { @@ -1073,18 +1097,21 @@ pub(crate) fn start( let result = (|| { events.reserve()?; // Every host object and every context-0 alias is prepared before RUN is set. - built = Some(initdata::build(&d, &session.adt, &session.regs, &mut objects)?); + built = Some(initdata::build( + &d, + &session.adt, + cfg, + &session.regs, + id.cores.count_ones(), + &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); } let log_buffer = match kind { hw::Start::MacOs27_2 => { - let log_size = session - .adt - .performance - .coredump_copy_size - .ok_or(EINVAL)? as usize; + let log_size = session.adt.performance.coredump_copy_size.ok_or(EINVAL)? as usize; let va = objects .alloc(Request { size: log_size, @@ -1116,6 +1143,7 @@ pub(crate) fn start( &mut session, &mut events, built.as_mut().ok_or(EINVAL)?, + cfg, log_buffer, )?; session.booted = true; diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index 9e958a99a5ae97..c2ee881cac26a6 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -15,9 +15,8 @@ use kernel::{ use super::boot::Session; use super::event::Events; -use super::fw::channels::{ - DevCtl, SubmitRecord, RING_SLOTS, STATE_COMPLETION, STATE_READ, STATE_WRITE, -}; +use super::fw::channels::{DevCtl, SubmitRecord, RING_SLOTS, STATE_READ, STATE_WRITE}; +use super::fw::initdata::TxLayout; use super::hw::{self, rings}; use super::initdata::InitData; use super::object::{Class, FwObject, Objects, Placement, Request}; @@ -36,22 +35,50 @@ pub(crate) enum Channel { pub(crate) struct Ring { pub(crate) state: Arc, pub(crate) ring: Arc, + completion: usize, + header: usize, } impl Ring { + pub(crate) fn new( + state: Arc, + ring: Arc, + tx: TxLayout, + control: bool, + ) -> Self { + Self { + state, + ring, + completion: tx.completion(), + header: tx.ring_header(control), + } + } + /// The consumer's read index (state +0x00). pub(crate) fn read(&self) -> Result { self.state.r32(STATE_READ) } - /// The completion index (state +0x10). + /// The completion index in the channel's state block. pub(crate) fn completion(&self) -> Result { - self.state.r32(STATE_COMPLETION) + self.state.r32(self.completion) } - /// The producer's write index (state +0x20). + /// The producer's write index, either in state or at the start of the ring. pub(crate) fn write(&self) -> Result { - self.state.r32(STATE_WRITE) + if self.header == 0 { + self.state.r32(STATE_WRITE) + } else { + self.ring.r32(0) + } + } + + fn set_write(&self, value: u32) -> Result { + if self.header == 0 { + self.state.w32(STATE_WRITE, value) + } else { + self.ring.w32(0, value) + } } } @@ -95,6 +122,7 @@ impl Channels { /// Their state is uncached; the submit records use the qualified ASC-cached class. pub(crate) fn alloc_submit_and_attach( objects: &mut Objects, + tx: TxLayout, devctl: Ring, event: Ring, log: Ring, @@ -106,10 +134,16 @@ impl Channels { let mut submit = KVec::with_capacity(rings::CHANNELS as usize, GFP_KERNEL)?; for _ in 0..rings::CHANNELS { submit.push( - Ring { - state: fw_object(objects, rings::STATE_SIZE, false)?, - ring: fw_object(objects, rings::CHANNEL_RING_SIZE, true)?, - }, + Ring::new( + fw_object(objects, rings::STATE_SIZE, false)?, + fw_object( + objects, + rings::CHANNEL_RING_SIZE + tx.ring_header(false), + tx == TxLayout::StateBlock, + )?, + tx, + false, + ), GFP_KERNEL, )?; } @@ -142,7 +176,7 @@ impl Channels { self.channel(channel).read() } - /// The channel's write cell (state +0x20). + /// The channel's producer. pub(crate) fn write_cell(&self, channel: Channel) -> Result { self.channel(channel).write() } @@ -179,12 +213,12 @@ impl Channels { return Err(EBUSY); } ring.ring.write( - producer as usize * rings::CHANNEL_RECORD, + ring.header + producer as usize * rings::CHANNEL_RECORD, &record.to_bytes(), )?; wmb(); let producer = (producer + 1) % RING_SLOTS; - ring.state.w32(STATE_WRITE, producer)?; + ring.set_write(producer)?; wmb(); self.producer[ch] = producer; Ok(producer) @@ -203,7 +237,7 @@ impl Channels { self.devctl.ring.write(0, &DevCtl::op(nop).to_bytes())?; wmb(); session.set_generation(1)?; - self.devctl.state.w32(STATE_WRITE, 1)?; + self.devctl.set_write(1)?; wmb(); self.devctl_producer = 1; Ok(()) @@ -453,7 +487,7 @@ pub(crate) fn devctl_submit( .write(producer as usize * rings::DEVCTL_RECORD, &record.to_bytes())?; wmb(); session.set_generation(next)?; - channels.devctl.state.w32(STATE_WRITE, next)?; + channels.devctl.set_write(next)?; wmb(); channels.devctl_producer = next; session.send(hw::ep::DOORBELL, hw::engine::DEVCTL_DOORBELL)?; diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 18a3c8065537a9..294fffcc8a5171 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! J713/T8132 initdata for the qualified 25G83 firmware and the 26B123 firmware. +//! InitData for the qualified 25G83 and 26B123 classic GPU firmware. //! //! 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 @@ -118,6 +118,32 @@ pub(crate) struct FirmwareData { pub(crate) snapshot_entries: usize, } +/// Pointer geometry of the twelve TX channels and device-control channel. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum TxLayout { + /// Three state pointers spaced by 0x10 and a separate record buffer. + StateBlock, + /// Read and completion pointers spaced by eight. For the TX channels the + /// producer is the eight-byte header before the records. + RingHeader, +} + +impl TxLayout { + pub(crate) const fn completion(self) -> usize { + match self { + Self::StateBlock => 0x10, + Self::RingHeader => 8, + } + } + + pub(crate) const fn ring_header(self, control: bool) -> usize { + match self { + Self::RingHeader if !control => 8, + _ => 0, + } + } +} + /// 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 { @@ -127,10 +153,16 @@ pub(crate) struct Layout { pub(crate) object_size: [usize; OBJECT_COUNT], /// RUNTIME (main config) offset of the unaligned power-config (POWER_PERFORMANCE) pointer. pub(crate) power_config: usize, + pub(crate) tx: TxLayout, /// 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, + pub(crate) loaders: &'static [Loader; LOADER_COUNT], + /// Slots with an empty address and length but a default write-enabled mode. + pub(crate) empty_loader_modes: u64, + /// Physical core slots in MAIN where the firmware expects the topology count. + pub(crate) main_core_slots: Option, /// 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], @@ -245,7 +277,7 @@ impl Layout { /// 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(|&slot| self.loaders[slot].length != 0) .filter_map(|slot| self.slot(slot)) .max() .map_or(0, |slot| slot + 1) @@ -288,8 +320,12 @@ pub(crate) const V25G83: Layout = Layout { version: 0x0c89c357839204b8, object_size: OBJECT_SIZE, power_config: 0x469, + tx: TxLayout::StateBlock, loader_slot: identity_slots(), register_slots: 53, + loaders: &LOADERS, + empty_loader_modes: 0, + main_core_slots: None, main: &[run(0, 0x640, 0), run(0xe88, 0x2658, 0)], globals: &[run(0, 0xe48, 0)], power_performance: &[run(0, 0x6578, 0)], @@ -332,8 +368,12 @@ pub(crate) const V26B123: Layout = Layout { 0x4800, 0x4, 0x30, 0x4800, 0x4000, 0x4000, 0x4000, ], power_config: 0x479, + tx: TxLayout::StateBlock, loader_slot: slots_26b123(), register_slots: 60, + loaders: &LOADERS, + empty_loader_modes: 0, + main_core_slots: None, main: &[ run(0, 0x640, 0), run(0xe88, 0xe90, 0x118), @@ -399,6 +439,44 @@ pub(crate) const V26B123: Layout = Layout { }), }; +/// G15S 26B123 keeps the protocol layouts and ADT-derived power sampling/limiter encoding while +/// supplying its own HW data and register map. +pub(crate) const G15S_26B123: Layout = Layout { + name: "26B123 G15S", + version: 0x0c8a836f039404b8, + tx: TxLayout::RingHeader, + object_size: { + let mut sizes = V26B123.object_size; + sizes[id::MAIN] = 0x2790; + sizes + }, + loader_slot: slots_g15s(), + loaders: &G15S_LOADERS, + empty_loader_modes: (1 << 2) + | (0xf << 5) + | (7 << 25) + | (1 << 32) + | (1 << 35) + | (1 << 43) + | (3 << 46) + | (0xf << 52) + | (1 << 58), + main_core_slots: Some(20), + main_policy: &[(0x275c, 1), (0x2786, 1), (0x278a, 1)], + globals: &[run(0, 0x38, 0), run(0x38, 0xe28, 4), run(0xe28, 0xe47, 5)], + globals_policy: &[(0xe31, 1)], + ..V26B123 +}; + +const fn slots_g15s() -> [Option; LOADER_COUNT] { + let mut slots = slots_26b123(); + // The final two named registers use G15S-specific slots. Slot 41 (G16G's + // firmware-owned power transition block) stays empty on G15S. + slots[35] = Some(40); + slots[41] = Some(48); + slots +} + /// 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; @@ -732,7 +810,7 @@ const fn retention_fits(layout: &Layout) -> bool { } } } -const _: () = assert!(layout_fits(&V25G83) && layout_fits(&V26B123)); +const _: () = assert!(layout_fits(&V25G83) && layout_fits(&V26B123) && layout_fits(&G15S_26B123)); /// One logical loader record, including its page offset and exact PTE class. #[derive(Clone, Copy, Debug)] @@ -913,24 +991,76 @@ const fn loaders() -> [Loader; LOADER_COUNT] { } pub(crate) const LOADERS: [Loader; LOADER_COUNT] = loaders(); -/// Actual mapped span: slot 3 has two discontiguous physical banks. -pub(crate) fn loader_span(slot: usize, bank: usize) -> Result<(u64, u32, u32), ()> { - let e = LOADERS.get(slot).ok_or(())?; - if e.length == 0 || bank > if slot == 3 { 1 } else { 0 } { - return Err(()); +const G15S_LOADERS: [Loader; LOADER_COUNT] = { + const SGX: u64 = 0x290000000; + let mut out = [EMPTY; LOADER_COUNT]; + out[0] = mmio(0x351014000, 0x4000, 0, 2); + out[1] = mmio(0x3502bc000, 0x4000, 0, 0); + out[3] = LOADERS[3]; + out[4] = mmio(0x35104c000, 0x4000, 0, 0); + out[9] = mmio(0x3503d0000, 0x4000, 0, 2); + out[10] = mmio(0x3503c0000, 0x4000, 0, 0); + out[11] = mmio(0x3503d8000, 0x4000, 0, 2); + out[12] = mmio(0x30945c000, 0x4000, 0, 2); + out[14] = mmio(0x350280000, 0x8000, 0, 0); + out[17] = mmio(SGX, 0x20000, 0, 2); + out[20] = mmio(0x293000000, 0x400000, 0, 2); + out[26] = mmio(SGX + 0xd04000, 0x8000, 0xd04000, 2); + out[28] = mmio(SGX + 0xd50000, 0x8000, 0xd50000, 2); + out[29] = mmio(SGX + 0xd10000, 0x4000, 0xd10000, 2); + out[31] = mmio(SGX + 0xd40000, 0x4000, 0xd40000, 2); + out[32] = mmio(SGX + 0xd60000, 0x20000, 0xd60000, 2); + out[33] = mmio(SGX + 0xd44000, 0x4000, 0xd44000, 2); + out[34] = mmio(SGX + 0xd4c000, 0x200, 0xd4c000, 2); + // The protected register block is explicitly supplied with mode 2 in G15S slot 40. + out[35] = mmio(SGX + 0xe00000, 0x4000, 0xe00000, 2); + out[37] = mmio(SGX + 0xe40000, 0x4000, 0xe40000, 2); + out[39] = mmio(SGX + 0xe08000, 0x8000, 0, 2); + out[40] = mmio(SGX + 0xe5c000, 0x4000, 0xe5c000, 2); + out[41] = mmio(SGX + 0xe60000, 0x50, 0xe60000, 2); + out +}; + +const fn mmio(pa: u64, length: u32, tag: u64, mode: u8) -> Loader { + Loader { + pa, + length, + requested: length, + tag, + mode, + attrs: if mode == 2 { MMIO_RW } else { MMIO_RO }, + } +} + +impl Loader { + /// Number of banks in this window. A banked record encodes the combined span + /// and the requested size of one bank. + pub(crate) fn banks(&self) -> usize { + if self.length > self.requested { + 2 + } else { + 1 + } + } + + /// Actual mapped span. The two banks have adjacent VAs and discontiguous PAs. + pub(crate) fn span(&self, bank: usize) -> Result<(u64, u32, u32), ()> { + if self.length == 0 || bank >= self.banks() { + return Err(()); + } + let offset = self.pa & (PAGE - 1); + let bytes = u64::from(self.requested); + let size = (offset + bytes + PAGE - 1) & !(PAGE - 1); + Ok(( + (self.pa & PA_MASK) + bank as u64 * 0x2000000, + size as u32, + bank as u32 * self.requested, + )) } - let offset = e.pa & (PAGE - 1); - let bytes = if slot == 3 { - 0x18000 - } else { - u64::from(e.length) - }; - let size = (offset + bytes + PAGE - 1) & !(PAGE - 1); - Ok(( - (e.pa & PA_MASK) + if bank != 0 { 0x2000000 } else { 0 }, - size as u32, - if bank != 0 { 0x18000 } else { 0 }, - )) +} + +pub(crate) fn loader_span(slot: usize, bank: usize) -> Result<(u64, u32, u32), ()> { + LOADERS.get(slot).ok_or(())?.span(bank) } fn put32(out: &mut [u8], at: usize, value: u32) -> Result<(), ()> { @@ -947,29 +1077,35 @@ fn put64(out: &mut [u8], at: usize, value: u64) -> Result<(), ()> { } pub(crate) fn loader_encode(slot: usize, va: u64, record: &mut [u8]) -> Result<(), ()> { - let e = LOADERS.get(slot).ok_or(())?; - let out = record.get_mut(..LOADER_STRIDE).ok_or(())?; - if e.length == 0 { - if va != 0 { + LOADERS.get(slot).ok_or(())?.encode(va, record) +} + +impl Loader { + fn encode(&self, va: u64, record: &mut [u8]) -> Result<(), ()> { + let e = self; + let out = record.get_mut(..LOADER_STRIDE).ok_or(())?; + if e.length == 0 { + if va != 0 { + return Err(()); + } + out.fill(0); + return Ok(()); + } + let offset = e.pa & (PAGE - 1); + let span = (offset + u64::from(e.length) + PAGE - 1) & !(PAGE - 1); + if !(HOST_START..HOST_END).contains(&va) + || va & (PAGE - 1) != offset + || span > HOST_END - (va - offset) + { return Err(()); } - out.fill(0); - return Ok(()); - } - let offset = e.pa & (PAGE - 1); - let span = (offset + u64::from(e.length) + PAGE - 1) & !(PAGE - 1); - if !(HOST_START..HOST_END).contains(&va) - || va & (PAGE - 1) != offset - || span > HOST_END - (va - offset) - { - return Err(()); + put64(out, 0, e.pa)?; + put64(out, 8, va)?; + put32(out, 0x10, e.length)?; + put32(out, 0x14, e.requested)?; + put64(out, 0x18, e.tag)?; + put64(out, 0x20, u64::from(e.mode)) } - put64(out, 0, e.pa)?; - put64(out, 8, va)?; - put32(out, 0x10, e.length)?; - put32(out, 0x14, e.requested)?; - put64(out, 0x18, e.tag)?; - put64(out, 0x20, u64::from(e.mode)) } /// Capacity for the largest qualified table: J713 has ten rows, J773g eleven. @@ -1033,6 +1169,7 @@ pub(crate) struct Input { pub(crate) lower_parameter: u64, pub(crate) ktrace_mask: u32, pub(crate) progress_recovery: u32, + pub(crate) enabled_cores: 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. @@ -1127,7 +1264,22 @@ pub(crate) fn encode_channel( ring: u64, control: bool, ) -> Result<(), ()> { - let bytes = if control { 0x4000 } else { 0x1800 }; + encode_tx(TxLayout::StateBlock, out, state, ring, control) +} + +fn encode_tx( + layout: TxLayout, + out: &mut [u8], + state: u64, + ring: u64, + control: bool, +) -> Result<(), ()> { + let header = layout.ring_header(control) as u64; + let bytes = if control { + 0x4000 + } else { + 0x1800 + header as usize + }; if !object_va(state, 0x30) || !object_va(ring, bytes) || (state < ring + bytes as u64 && ring < state + 0x30) @@ -1135,9 +1287,9 @@ pub(crate) fn encode_channel( return Err(()); } put64(out, 0, state)?; - put64(out, 8, state + 0x10)?; - put64(out, 0x10, state + 0x20)?; - put64(out, 0x18, ring) + put64(out, 8, state + layout.completion() as u64)?; + put64(out, 0x10, if header == 0 { state + 0x20 } else { ring })?; + put64(out, 0x18, ring + header) } /// Encodes the complete private 31-object 25G83 graph, byte-for-byte matching the @@ -1174,8 +1326,8 @@ pub(crate) fn encode_for( 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_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(()); @@ -1250,6 +1402,9 @@ pub(crate) fn encode_for( ] { put64(runtime, at, input.va[i])?; } + if layout.tx == TxLayout::RingHeader { + put64(runtime, 0x8, input.va[id::TIMER])?; + } put64(runtime, 0x18, input.scratch)?; put64(runtime, 0x2d0, input.lower_parameter)?; put64(runtime, 0x2e0, input.lower_uma)?; @@ -1259,14 +1414,16 @@ pub(crate) fn encode_for( put64(runtime, at, input.va[id::RETENTION])?; } for i in 0..12 { - encode_channel( + encode_tx( + layout.tx, &mut runtime[0x20 + i * 0x20..], input.channel_state[i], input.channel_ring[i], false, )?; } - encode_channel( + encode_tx( + layout.tx, &mut runtime[0x1a0..], input.va[id::DEVCTRL_STATE], input.va[id::DEVCTRL_RING], @@ -1302,6 +1459,7 @@ pub(crate) fn encode_for( for &(at, value) in layout.main_policy { put32(main, at, value)?; } + let core_slots = layout.main_core_slots; for (at, value) in [ (0xea0, 1), (0xee0, 1), @@ -1309,20 +1467,28 @@ pub(crate) fn encode_for( (0xed0, 24000), (0xed4, 1), (0xed8, 8), - (0xfc0, input.performance.count as u32), + (0xfc0, core_slots.unwrap_or(input.performance.count as u32)), (0x259c, 1), - (0x2544, 4), + (0x2544, if core_slots.is_some() { 5 } else { 4 }), (0x2548, 6), (0x254c, 3), (0x2550, 7), (0x2554, 7), - (0x2568, 8), - (0x2570, 1), + (0x2568, if core_slots.is_some() { 0 } else { 8 }), + (0x2570, core_slots.map_or(1, |_| input.enabled_cores)), ] { put32(main, remap(runs, at, 4)?, value)?; } put32(main, remap(runs, 0xea4, 4)?, input.progress_recovery)?; - put64(main, remap(runs, 0xf24, 8)?, 0x0000000607002004)?; + put64( + main, + remap(runs, 0xf24, 8)?, + if core_slots.is_some() { + 4 + } else { + 0x0000000607002004 + }, + )?; put32(main, remap(runs, 0xfc4, 4)?, ceiling)?; for i in 0..=ceiling as usize { put32( @@ -1361,15 +1527,24 @@ pub(crate) fn encode_for( return Err(()); } let mut record = [0u8; LOADER_STRIDE]; - loader_encode(slot, input.loader_va[slot], &mut record)?; + layout.loaders[slot].encode(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); } + for slot in 0..layout.register_slots { + if layout.empty_loader_modes & (1 << slot) != 0 { + put64(main, 0x640 + slot * LOADER_STRIDE + 0x20, 2)?; + } + } let runs = layout.power_performance; let p = &mut objects[id::POWER_PERFORMANCE]; - put64(p, remap(runs, POWER_TEMP_PTR, 8)?, input.va[id::TEMPERATURE])?; + put64( + p, + remap(runs, POWER_TEMP_PTR, 8)?, + input.va[id::TEMPERATURE], + )?; let power_fixed_values = [ input.power_sample_clks, input.power_sample_clks, diff --git a/drivers/gpu/drm/asahi/g16/fw/mod.rs b/drivers/gpu/drm/asahi/g16/fw/mod.rs index eaa924962befea..12bd1e58a9e03b 100644 --- a/drivers/gpu/drm/asahi/g16/fw/mod.rs +++ b/drivers/gpu/drm/asahi/g16/fw/mod.rs @@ -23,14 +23,6 @@ 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 { diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 699c7efae45d62..882e2657bf098a 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include #include #include @@ -19,12 +21,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include "glue.h" @@ -36,9 +40,20 @@ void __iomem *asahi_g16_ioremap_wc(u64 start, size_t size); bool asahi_g16_dma_unsupported(struct device *dev); /* Thermal-framework callbacks only publish requests. The Rust GPU owner - * samples the PMP provider and shared cooling policy under its device mutex; - * thermal callbacks never enter the GPU lock. + * samples the PMP provider (when apple,pmp is present) or cached SoC die + * thermal-zone readings (otherwise) under its device mutex; thermal callbacks + * never enter the GPU lock and SMC/zone polling runs outside it. */ +#define ASAHI_G16_ZONE_POLL_FAST_MS 250 +#define ASAHI_G16_ZONE_POLL_IDLE_MS 1000 +#define ASAHI_G16_ZONE_HOT_POLL_MC 75000 +#define ASAHI_G16_ZONE_STALE_NS 3000000000ULL + +static const char * const asahi_g16_die_zones[] = { + "macsmc_soc_die", + "apple_pmp_hotspot", +}; + struct asahi_g16_cooling { atomic_t state; struct apple_pmp_gpu *pmp; @@ -48,6 +63,14 @@ struct asahi_g16_cooling { /* The last reading from a sensor that was valid, and when. */ u64 valid_ns; long valid_mc; + /* Cached thermal-zone telemetry when no apple,pmp node is present. */ + spinlock_t zone_lock; + struct delayed_work zone_poll; + atomic_t zone_active; + atomic_t stopping; + u64 zone_ns; + long zone_mc; + int zone_err; }; struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev); @@ -92,6 +115,55 @@ static const struct thermal_cooling_device_ops asahi_g16_cooling_ops = { .set_cur_state = asahi_g16_cooling_set, }; +static void asahi_g16_zone_poll_fn(struct work_struct *work) +{ + struct asahi_g16_cooling *cooling = + container_of(to_delayed_work(work), struct asahi_g16_cooling, + zone_poll); + long hottest = 0; + bool found = false; + int ret = -ENODEV; + unsigned int i; + unsigned int delay_ms; + + if (atomic_read(&cooling->stopping)) + return; + + for (i = 0; i < ARRAY_SIZE(asahi_g16_die_zones); i++) { + int temp = 0; + int err = thermal_zone_get_temp_by_name(asahi_g16_die_zones[i], + &temp); + + if (!err) { + if (!found || temp > hottest) + hottest = temp; + found = true; + } else if (err != -ENODEV) { + ret = err; + found = false; + break; + } + } + if (found) + ret = 0; + + spin_lock(&cooling->zone_lock); + cooling->zone_ns = ktime_get_ns(); + cooling->zone_mc = found ? hottest : 0; + cooling->zone_err = ret; + spin_unlock(&cooling->zone_lock); + + if (atomic_read(&cooling->stopping)) + return; + + delay_ms = (ret || atomic_read(&cooling->zone_active) || + hottest >= ASAHI_G16_ZONE_HOT_POLL_MC) ? + ASAHI_G16_ZONE_POLL_FAST_MS : + ASAHI_G16_ZONE_POLL_IDLE_MS; + queue_delayed_work(system_freezable_wq, &cooling->zone_poll, + msecs_to_jiffies(delay_ms)); +} + struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev) { struct asahi_g16_cooling *cooling; @@ -100,46 +172,67 @@ struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev) cooling = kzalloc_obj(*cooling); if (!cooling) return ERR_PTR(-ENOMEM); - atomic_set(&cooling->state, 8); apple_pmp_cooling_init(&cooling->policy); + spin_lock_init(&cooling->zone_lock); + INIT_DELAYED_WORK(&cooling->zone_poll, asahi_g16_zone_poll_fn); + cooling->zone_err = -ENODATA; cooling->pmp_node = of_parse_phandle(dev->of_node, "apple,pmp", 0); - if (!cooling->pmp_node) { - ret = -EINVAL; - goto free; - } - cooling->pmp = apple_pmp_gpu_get(dev); - if (IS_ERR(cooling->pmp)) { - ret = PTR_ERR(cooling->pmp); - goto put_node; + if (cooling->pmp_node) { + atomic_set(&cooling->state, 8); + cooling->pmp = apple_pmp_gpu_get(dev); + if (IS_ERR(cooling->pmp)) { + ret = PTR_ERR(cooling->pmp); + goto put_node; + } + } else { + /* + * Without an apple,pmp supplier, thermal-zone telemetry drives + * the fail-closed backstop (starting at maximum cooling) while + * the cooling device remains available to thermal policy. + */ + atomic_set(&cooling->state, 0); } cooling->cdev = thermal_of_cooling_device_register(dev->of_node, 0, "aurora-g16g", cooling, &asahi_g16_cooling_ops); if (IS_ERR(cooling->cdev)) { ret = PTR_ERR(cooling->cdev); - apple_pmp_gpu_put(cooling->pmp); + if (cooling->pmp) + apple_pmp_gpu_put(cooling->pmp); goto put_node; } + if (!cooling->pmp_node) + queue_delayed_work(system_freezable_wq, &cooling->zone_poll, 0); return cooling; put_node: of_node_put(cooling->pmp_node); -free: kfree(cooling); return ERR_PTR(ret); } void asahi_g16_cooling_unregister(struct asahi_g16_cooling *cooling) { + atomic_set(&cooling->stopping, 1); + if (!cooling->pmp_node) + cancel_delayed_work_sync(&cooling->zone_poll); thermal_cooling_device_unregister(cooling->cdev); - apple_pmp_gpu_put(cooling->pmp); + if (cooling->pmp) + apple_pmp_gpu_put(cooling->pmp); of_node_put(cooling->pmp_node); kfree(cooling); } +bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling) +{ + return cooling->pmp_node != NULL; +} + /* Serialized by the GPU owner. Provider lifetime and MMIO access stay with * PMP: this consumer owns no SRAM mapping and cannot restart its firmware. * An idle GPU samples about twice a second and makes no heat, so with nothing * in flight the last cool reading stands for as long as the sensors stay dark. + * Without apple,pmp, return the latest cached SoC die thermal-zone reading and + * fail closed whenever no fresh reading is available. */ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool idle, long *temperature, u32 *governor, u32 *power, @@ -148,6 +241,34 @@ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool id int ret; *temperature = 0; + if (!cooling->pmp_node) { + u64 zone_ns; + long zone_mc; + int zone_err; + + atomic_set(&cooling->zone_active, !idle); + spin_lock(&cooling->zone_lock); + zone_ns = cooling->zone_ns; + zone_mc = cooling->zone_mc; + zone_err = cooling->zone_err; + spin_unlock(&cooling->zone_lock); + + if (!zone_ns) + ret = -ENODATA; + else if (zone_err) + ret = zone_err; + else if (now > zone_ns && now - zone_ns > ASAHI_G16_ZONE_STALE_NS) + ret = -ETIMEDOUT; + else { + *temperature = zone_mc; + ret = 0; + } + *governor = atomic_read(&cooling->state); + *power = 0; + *backstop = 8; + return ret; + } + ret = apple_pmp_telemetry_get_hotspot(cooling->pmp_node, temperature); if (!ret) { cooling->valid_ns = now; @@ -226,20 +347,24 @@ u32 asahi_g16_timebase_hz(void) */ int asahi_g16_display_prepare(struct device *dev) { + bool t6030 = of_device_is_compatible(dev->of_node, "apple,agx-t6030"); struct device_node *np; bool handed_over; int ret; - np = of_find_compatible_node(NULL, NULL, "apple,t8132-display-subsystem"); + np = of_find_compatible_node(NULL, NULL, + t6030 ? "apple,t6030-display-subsystem" : + "apple,t8132-display-subsystem"); handed_over = np && of_device_is_available(np); of_node_put(np); if (!handed_over) { dev_info_once(dev, "G16: no native display this boot; starting on the boot framebuffer\n"); return 0; } - ret = apple_drm_t8132_link_device(dev); + ret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev); if (ret == -EPROBE_DEFER) - dev_info_once(dev, "G16: waiting for the T8132 native display to register\n"); + dev_info_once(dev, "G16: waiting for the %s native display to register\n", + t6030 ? "T6030" : "T8132"); return ret; } diff --git a/drivers/gpu/drm/asahi/g16/glue.h b/drivers/gpu/drm/asahi/g16/glue.h index fb788f85fce967..dd60a837903b83 100644 --- a/drivers/gpu/drm/asahi/g16/glue.h +++ b/drivers/gpu/drm/asahi/g16/glue.h @@ -2,6 +2,9 @@ #ifndef _ASAHI_G16_GLUE_H #define _ASAHI_G16_GLUE_H +struct asahi_g16_cooling; + u32 asahi_g16_timebase_hz(void); +bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling); #endif /* _ASAHI_G16_GLUE_H */ diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 7951b2b09100e2..a6bccc51abb1d8 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -4,13 +4,13 @@ reason = "Firmware layout catalog also describes fields used by host wire regressions." )] -//! T8132 (G16G) hardware and firmware-ABI constants (layout values are shared by several +//! Classic GPU hardware and firmware-ABI constants (layout values are shared by several //! modules; change one only together with its users). The tuned policy values are in //! [`tuning`]. use core::ops::Range; -/// Identification register values of a qualified G16G. +/// Identification register values of a qualified GPU. pub(crate) struct HwId { /// SGX identity word (`sgx + 0xd04000`). pub(crate) version: u32, @@ -26,6 +26,7 @@ pub(crate) struct Config { pub(crate) chip_id: u32, /// GPU generation reported to userspace. pub(crate) gpu_generation: u32, + pub(crate) gpu_hal_generation: u32, /// GPU variant reported to userspace. pub(crate) gpu_variant: crate::hw::GpuVariant, /// GPU revision reported to userspace. @@ -41,16 +42,27 @@ pub(crate) struct Config { pub(crate) hw_ids: &'static [HwId], /// Compatible of the original ADT SGX node. pub(crate) adt_compatible: &'static [u8], + pub(crate) source_layout: super::board::data::SourceLayout, /// Qualified boot-loader handoffs. pub(crate) layouts: &'static [&'static FwLayout], /// Qualified firmware builds. pub(crate) firmware: &'static [FirmwareBuild], + /// Whether this compatible also has a legacy driver. + pub(crate) needs_handoff_marker: bool, /// T8132 retains the PMP bridge even on firmware that does not send an AGX vote. pub(crate) prepare_pmp: bool, /// PMGR register offset of the GFX domain. pub(crate) power_offset: u32, + /// Number of valid fault-bank selectors in the SGX status window. + pub(crate) fault_banks: usize, /// GFXCAXI2AF needs host enable writes before the 27.2 firmware starts. pub(crate) axi2af: bool, + /// Offsets to zero, in order, in the host block before InitData on 27.2. + pub(crate) host_block_zero_order: &'static [usize], + /// Whether the host probes scratch and raises the ready word after zeroing. + pub(crate) host_block_ready: bool, + /// Whether the TVM gate and firmware warm restart are supported. + pub(crate) deep_sleep: bool, } impl Config { @@ -66,6 +78,7 @@ pub(crate) mod t8132 { pub(crate) const CONFIG: Config = Config { chip_id: 0x8132, gpu_generation: 16, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_200, gpu_variant: crate::hw::GpuVariant::G, gpu_revision: 0x10, uat_ias: 42, @@ -77,6 +90,7 @@ pub(crate) mod t8132 { counts: 0x0011010a, }], adt_compatible: b"gpu,t8132", + source_layout: super::super::board::data::SourceLayout::T8132, layouts: &[&FW_25G83, &FW_26B123], firmware: &[ FirmwareBuild { @@ -167,9 +181,14 @@ pub(crate) mod t8132 { ], }, ], + needs_handoff_marker: false, prepare_pmp: true, power_offset: 0x250, + fault_banks: 8, axi2af: true, + host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, + host_block_ready: true, + deep_sleep: true, }; /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: @@ -279,6 +298,120 @@ pub(crate) mod t8132 { ]; } +/// T6030 (G15S), qualified with the b000 image loaded on J516s. +pub(crate) mod t6030 { + use super::super::{board::data::SourceLayout, fw::initdata}; + use super::{Config, FirmwareBuild, FwLayout, HwId, Scratch, FW_26B123, HOST_BLOCK, UPPER}; + + pub(crate) const CONFIG: Config = Config { + chip_id: 0x6030, + gpu_generation: 15, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY, + gpu_variant: crate::hw::GpuVariant::S, + gpu_revision: 0x11, + uat_ias: 42, + uat_oas: 42, + num_clusters: 2, + num_cores_per_cluster: 10, + hw_ids: &[HwId { + version: 0x07031100, + counts: 0x00110209, + }], + adt_compatible: b"gpu,t6030", + source_layout: SourceLayout::T6030, + layouts: &[&LAYOUT], + firmware: &[FirmwareBuild { + name: "Apple GFX 26B123 G15S (build b000, iBoot-filled ranges zeroed)", + text_size: LAYOUT.text_size, + data_size: LAYOUT.data_size, + entropy: &[[0x5be64, 0x5bf47]], + boot_filled: BOOT_FILLED_B000, + text_sha256: [ + 0x31, 0xc7, 0xc7, 0x7a, 0x24, 0x85, 0x88, 0x7b, 0x66, 0x2e, 0xa2, 0x2d, 0xe6, 0xcc, + 0xc5, 0xf9, 0xf6, 0x87, 0xa2, 0x4b, 0x07, 0xbd, 0xbd, 0xdf, 0x95, 0x21, 0x1a, 0x06, + 0xcd, 0x5f, 0x57, 0x3b, + ], + }], + needs_handoff_marker: true, + prepare_pmp: false, + power_offset: 0x110, + fault_banks: 2, + axi2af: false, + host_block_zero_order: &[0, 0x1808, 0x3010], + host_block_ready: false, + deep_sleep: false, + }; + + const LAYOUT: FwLayout = FwLayout { + name: "26B123 G15S", + segment_vas: &[UPPER, UPPER + 0x60000, UPPER + 0x18c000], + text_size: 0x60000, + data_size: 0x134000, + initdata: &initdata::G15S_26B123, + scratch: Scratch { + register: HOST_BLOCK, + // The G15S scratch window has an unmapped page at +0x14000. + spans: &[(0, 0x14000), (0x18000, 0x8000)], + pointer: 0x12068, + }, + // Offset on the PPL handoff page where the G15S 26B123 firmware records + // whether the GPU is powered during idle power-gating. + powered: Some(0x638), + ..FW_26B123 + }; + + /// Fixed normalization ranges of the qualified G15S b000 image. Only the + /// values of iBoot's records, the two header fields and the tunable contents + /// are ignored. The digest still covers the tags, lengths and table headers. + const BOOT_FILLED_B000: &[(u32, u32)] = &[ + (0x224, 4), + (0x23c, 8), + (0x5be6c, 8), + (0x5be7c, 8), + (0x5be8c, 8), + (0x5be9c, 8), + (0x5beac, 8), + (0x5bebc, 8), + (0x5becc, 8), + (0x5bedc, 4), + (0x5bee8, 1), + (0x5bef1, 8), + (0x5bf01, 8), + (0x5bf11, 4), + (0x5bf1d, 8), + (0x5bf2d, 1), + (0x5bf36, 1), + (0x5bf3f, 8), + (0x5bf4f, 8), + (0x5bf5f, 8), + (0x5bf6f, 8), + (0x5bf7f, 8), + (0x5bf8f, 8), + (0x5bf9f, 8), + (0x5bfaf, 8), + (0x5bfbf, 8), + (0x5bfcf, 8), + (0x5bfdf, 8), + (0x5bfef, 1), + (0x5bff8, 8), + (0x5c008, 4), + (0x5c014, 8), + (0x5c024, 4), + (0x5c030, 4), + (0x5c03c, 4), + (0x5c048, 8), + (0x5c058, 8), + (0x5c068, 1), + (0x5c071, 8), + (0x5c081, 8), + (0x5c091, 4), + (0x5c098, 1), + (0x5c099, 0x2d4), + (0x5c370, 1), + (0x5c371, 0x2d4), + ]; +} + /// Which part of the loaded image a firmware page-table leaf maps. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Segment { @@ -372,6 +505,19 @@ pub(crate) struct PplMagic { pub(crate) answers: bool, } +/// Firmware-visible alias of host registers, with the pointer InitData passes into it. +pub(crate) struct Scratch { + pub(crate) register: u64, + pub(crate) spans: &'static [(u64, u64)], + pub(crate) pointer: u64, +} + +const T8132_SCRATCH: Scratch = Scratch { + register: HOST_BLOCK, + spans: &[(0, 0x8000)], + pointer: 0, +}; + /// 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 { @@ -388,6 +534,7 @@ pub(crate) struct FwLayout { pub(crate) abi: FwAbi, /// InitData wire layout, including the version word of this firmware image. pub(crate) initdata: &'static super::fw::initdata::Layout, + pub(crate) scratch: Scratch, /// 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. @@ -441,6 +588,7 @@ pub(crate) const FW_25G83: FwLayout = FwLayout { data_size: 0x13c000, abi: FwAbi::V25G83, initdata: &super::fw::initdata::V25G83, + scratch: T8132_SCRATCH, leaves: Some(&[ Leaves { range: 0..0x50000, @@ -503,6 +651,7 @@ pub(crate) const FW_26B123: FwLayout = FwLayout { data_size: 0xd8000, abi: FwAbi::V26B123, initdata: &super::fw::initdata::V26B123, + scratch: T8132_SCRATCH, // The firmware builds its own tree at start; admit only an empty tree. leaves: Some(&[]), ppl_magic: Some(PplMagic { @@ -981,7 +1130,10 @@ pub(crate) mod sizes { /// Firmware channels, doorbells, seeds and identifiers. pub(crate) mod engine { pub(crate) const DOORBELL: u64 = 0x0083000000000000; + pub(crate) const DEVCTL_INIT_DOORBELL: u64 = DOORBELL | 0x11; pub(crate) const DEVCTL_DOORBELL: u64 = 0x0084000000000011; + pub(crate) const RECEIVE_DOORBELL: u64 = DOORBELL | 0x10; + pub(crate) const G15S_RECEIVE_DOORBELL: u64 = 0x0087000000000010; pub(crate) const EVENT_SLOT: u32 = 2; pub(crate) const COMPUTE_UMA_SLOT: u32 = 1; pub(crate) const RENDER_UMA_SLOT: u32 = 33; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 3c32f03f49c5ea..b6338605815adb 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -20,6 +20,7 @@ use super::object::{Class, FwObject, Objects, Placement, Request}; pub(crate) struct InitData { /// The firmware ABI these objects were encoded for. pub(crate) abi: FwAbi, + pub(crate) layout: &'static wire::Layout, pub(crate) globals: Option>, /// Recovery/scheduler owner: root.FirmwareData, not the small Control. pub(crate) control: Option>, @@ -62,7 +63,7 @@ impl InitData { /// The FirmwareData words of this ABI. pub(crate) fn firmware_data(&self) -> &'static wire::FirmwareData { - &self.abi.initdata().firmware_data + &self.layout.firmware_data } /// A phase 1 or 3 stop is owned by the M4 recovery handshake. @@ -85,10 +86,12 @@ impl InitData { } fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { - Ring { - state: graph[state].clone(), - ring: graph[ring].clone(), - } + Ring::new( + graph[state].clone(), + graph[ring].clone(), + wire::TxLayout::StateBlock, + false, + ) } /// Builds the complete unpublished M4 graph. The return shape is shared with @@ -97,13 +100,15 @@ fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, + cfg: &super::Config, regs: &super::regs::Regs, + enabled_cores: u32, objects: &mut Objects, ) -> Result<(InitData, Channels, u32)> { let abi = adt.layout.abi; let layout = adt.layout.initdata; - let performance = board::qualify(dev, adt)?; - // The top row: S9 on J713, S10 on J773g. + let performance = board::qualify(dev, adt, cfg.source_layout)?; + // The top row of the qualified table, excluding the off state. let ceiling = performance.count as u32 - 1; let rows = performance.count as u32; let max_khz = performance.frequency[ceiling as usize] * 1000; @@ -148,7 +153,13 @@ pub(crate) fn build( } let channels = Channels::alloc_submit_and_attach( objects, - pair(&graph, id::DEVCTRL_STATE, id::DEVCTRL_RING), + layout.tx, + Ring::new( + graph[id::DEVCTRL_STATE].clone(), + graph[id::DEVCTRL_RING].clone(), + layout.tx, + true, + ), pair(&graph, id::EVENT_STATE, id::EVENT_DATA), pair(&graph, id::LOG_STATE, id::LOG_ENTRIES), graph[id::LOG_DATA].clone(), @@ -236,6 +247,7 @@ pub(crate) fn build( lower_parameter: wire::BOOTSTRAP_START + 0x8000, ktrace_mask: 0, progress_recovery: 1, + enabled_cores, }; for i in 0..wire::OBJECT_COUNT { input.va[i] = graph[i].va; @@ -244,7 +256,7 @@ pub(crate) fn build( input.channel_state[i] = channels.submit[i].state.va; input.channel_ring[i] = channels.submit[i].ring.va; } - for (slot, entry) in wire::LOADERS.iter().enumerate() { + for (slot, entry) in layout.loaders.iter().enumerate() { // 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; @@ -253,15 +265,24 @@ pub(crate) fn build( let at = objects.reserve_io((offset + u64::from(entry.length)).next_multiple_of(wire::PAGE))?; input.loader_va[slot] = at + offset; - for bank in 0..if slot == 3 { 2 } else { 1 } { - let (pa, size, delta) = wire::loader_span(slot, bank).map_err(|()| EINVAL)?; + for bank in 0..entry.banks() { + let (pa, size, delta) = entry.span(bank).map_err(|()| EINVAL)?; objects.map_mmio_class(at + u64::from(delta), pa, u64::from(size), entry.attrs)?; } } - input.scratch = objects.reserve_io(0x8000)?; - // This scratch alias deliberately has firmware RAM attrs, matching the - // qualified owner, even though the target is an SGX register window. - objects.map_mmio_class(input.scratch, regs.host_block_pa(), 0x8000, hw::pte::FW)?; + let scratch = &adt.layout.scratch; + let &(last, bytes) = scratch.spans.last().ok_or(EINVAL)?; + let at = objects.reserve_io(last + bytes)?; + input.scratch = at + scratch.pointer; + // The scratch alias uses firmware RAM attributes on these SGX registers. + for &(offset, bytes) in scratch.spans { + objects.map_mmio_class( + at + offset, + regs.sgx_pa() + scratch.register + offset, + bytes, + hw::pte::FW, + )?; + } // Private CPU-side staging keeps the pure encoder independent of raw GEM // pointers. No staging references survive publication. @@ -305,6 +326,7 @@ pub(crate) fn build( Ok(( InitData { abi, + layout, 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/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 2b98e95ca192c2..d76460c07cc21a 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -1,12 +1,11 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! 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). +//! Classic GPU support for T8132 G16G (25G83 and 26B123) and T6030 G15S (26B123). //! -//! G16 firmware is *classic*: one ring per engine (TA, FS, compute) and ordering expressed by +//! Classic firmware uses one ring per engine (TA, FS, compute) and expresses ordering through //! in-ring barrier records that wait on another queue's stamp, unlike the G17 kick-ring/QID //! model. The boot loader leaves the firmware loaded; this driver identifies the exact build, -//! adopts the inherited UAT handoff and builds the M4 initdata graph +//! adopts the inherited UAT handoff and builds the InitData graph //! and brings the firmware to READY. All logical queues and VMs share one persistent compute //! graph and one render graph; the commands of a submission are encoded into compute and pass //! slots and published as *prefixes* on the firmware's queues, then retired on their stamps. @@ -15,8 +14,9 @@ //! //! # Plugging into the shared driver //! -//! - [`Driver`] is a separate platform driver for `apple,agx-t8132` with a module alias. Its -//! probe waits for the PMP supplier and the native display before booting firmware. It calls +//! - [`Driver`] matches `apple,agx-t8132` and `apple,agx-t6030`. T6030 selects this backend +//! through the boot loader's handoff marker. Probe links a handed-over native display and, on +//! T8132, the PMP supplier before booting firmware. It calls //! [`crate::driver::AsahiPlatformDriver::probe_g16`]. //! - [`Gpu`] implements [`crate::gpu::Gpu`]: GET_PARAMS identity, VM creation (`new_vm`), //! queues (`new_queue`, see [`queue`]) and timestamp buffers. @@ -101,18 +101,27 @@ pub(crate) const DRIVER_NAME: &CStr = c_str!("aurora-g16"); pub(crate) use hw::Config; /// OF match table of the G16 platform driver. -const OF_TABLE: kernel::device_id::IdArray = - kernel::device_id::IdArray::new([( - of::DeviceId::new(c_str!("apple,agx-t8132")), - &&hw::t8132::CONFIG, - )]); +const OF_TABLE: kernel::device_id::IdArray = + kernel::device_id::IdArray::new([ + ( + of::DeviceId::new(c_str!("apple,agx-t8132")), + &&hw::t8132::CONFIG, + ), + ( + of::DeviceId::new(c_str!("apple,agx-t6030")), + &&hw::t6030::CONFIG, + ), + ]); // Probe admission waits for the PMP supplier and the native display before // firmware starts, so the module may be loaded at device creation. kernel::of_device_table!( AUTOLOAD_OF_TABLE, @none, - [of::DeviceId::new(c_str!("apple,agx-t8132"))] + [ + of::DeviceId::new(c_str!("apple,agx-t8132")), + of::DeviceId::new(c_str!("apple,agx-t6030")), + ] ); /// The G16 platform driver: the shared [`AsahiPlatformDriver`] probed through @@ -142,6 +151,9 @@ impl platform::Driver for Driver { info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let cfg = *info.ok_or(ENODEV)?; + if cfg.needs_handoff_marker && !adt::has_handoff(pdev.as_ref()) { + return Err(ENODEV); + } dev_info!(pdev.as_ref(), "G16: probing\n"); match AsahiPlatformDriver::probe_g16(pdev, cfg) { Ok(driver) => Ok(Some(driver)), diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index d854423cb5ed29..78db8e48c8a53c 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -108,7 +108,7 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res params.num_cores_per_cluster = gpu.cfg.num_cores_per_cluster; params.max_frequency_khz = gpu.max_frequency_khz; params.usc_generation = 3; - params.gpu_hal_generation = uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_200; + params.gpu_hal_generation = gpu.cfg.gpu_hal_generation; params.max_commands_per_submission = super::command::MAX_COMMANDS; params.max_attachments = hw::sizes::MAX_ATTACHMENTS as u32; for (i, mask) in gpu.id.core_masks.iter().enumerate() { diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index 0d227673eb7976..bed5e2432fcf4d 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -41,6 +41,7 @@ extern "C" { fn asahi_g16_clpc_gpu_put(gpu: *mut c_void); fn asahi_g16_cooling_register(dev: *mut c_void) -> *mut c_void; fn asahi_g16_cooling_unregister(cooling: *mut c_void); + fn asahi_g16_cooling_has_pmp(cooling: *const c_void) -> bool; fn asahi_g16_cooling_sample( cooling: *mut c_void, now: u64, @@ -52,10 +53,12 @@ extern "C" { ) -> i32; } -/// Owns the cooling-device registration and PMP consumer. The C helpers only -/// bridge the PMP provider and shared cooling policy, with atomic governor requests. +/// Owns the cooling-device registration and thermal telemetry consumer (PMP when `apple,pmp` +/// is present, or SoC die thermal zones otherwise). The C helpers only bridge the provider and +/// atomic governor requests. struct Cooling { inner: NonNull, + is_pmp: bool, _dev: ARef, } @@ -72,8 +75,12 @@ impl Cooling { let inner = kernel::error::from_err_ptr(unsafe { asahi_g16_cooling_register(dev.as_raw().cast()) })?; + let inner = NonNull::new(inner).ok_or(ENOMEM)?; + // SAFETY: `inner` is the live cooling object returned above. + let is_pmp = unsafe { asahi_g16_cooling_has_pmp(inner.as_ptr()) }; Ok(Self { - inner: NonNull::new(inner).ok_or(ENOMEM)?, + inner, + is_pmp, _dev: dev.into(), }) } @@ -158,6 +165,8 @@ pub(crate) struct Power { /// Work-in-flight state and 2 ms idle-hold hysteresis reported to `clpc`. clpc_hold: policy::ClpcHold, cooling: Cooling, + /// Fail-closed thermal-zone backstop used when the GPU DT node has no `apple,pmp`. + zone_backstop: policy::ZoneBackstop, sample: Sample, last_sample_ns: Option, /// The board's top state: S9 on the ten-row tables, S10 on the J773g table. @@ -178,17 +187,22 @@ pub(crate) struct Power { impl Power { /// 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. + /// startup S1 before INIT; this object starts with that same effective state until live + /// thermal telemetry confirms a safe ceiling. pub(crate) fn new(dev: &device::Device) -> Result { + // First: a CLPC that has not probed yet defers before the PMP vote. + let clpc = Demand::new(dev)?; + let cooling = Cooling::new(dev)?; + let pmp_initial = if cooling.is_pmp { COOLING_MAX } else { 0 }; Ok(Self { - // First: a CLPC that has not probed yet defers before the PMP vote. - clpc: Demand::new(dev)?, + clpc, clpc_hold: policy::ClpcHold::new(), - cooling: Cooling::new(dev)?, + cooling, + zone_backstop: policy::ZoneBackstop::new(), sample: Sample { temperature_mc: 0, - governor: COOLING_MAX, - budget: COOLING_MAX, + governor: pmp_initial, + budget: pmp_initial, backstop: COOLING_MAX, }, last_sample_ns: None, @@ -197,8 +211,8 @@ impl Power { user: TOP_DEFAULT, effective: 1, temperature_mc: 0, - governor: COOLING_MAX, - budget: COOLING_MAX, + governor: pmp_initial, + budget: pmp_initial, sensor_error: None, updates: 0, sensor_errors: 0, @@ -254,6 +268,15 @@ impl Power { if self.sensor_error.is_some() { self.sensor_errors += 1; } + if !self.cooling.is_pmp { + self.zone_backstop.sample( + now, + self.sample.temperature_mc, + self.sensor_error.is_some(), + ); + self.zone_backstop.observe(now, self.sample.governor); + self.sample.backstop = self.zone_backstop.level(); + } self.temperature_mc = self.sample.temperature_mc; self.governor = self.sample.governor; self.budget = self.sample.budget; @@ -314,7 +337,7 @@ impl Firmware { return Ok(()); } let globals = self.init.globals.as_ref().ok_or(ENODEV)?; - for offset in self.init.abi.initdata().pstate_selectors { + for offset in self.init.layout.pstate_selectors { globals.w32(offset, target * 100)?; } wmb(); diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index 2118802c2733df..53310885d53ed8 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -304,6 +304,116 @@ impl Governor { } } +/// Plausible SoC die temperature range (millidegrees Celsius) for thermal-zone cooling. +pub(crate) const ZONE_PLAUSIBLE_MIN_MC: i64 = 10_000; +pub(crate) const ZONE_PLAUSIBLE_MAX_MC: i64 = 125_000; +/// Thermal-zone cooling thresholds (millidegrees Celsius) for SoCs without an `apple,pmp` +/// telemetry bridge. Kept conservative relative to the GPU die target because SMC die +/// sensors can read cooler than the hottest GPU spot. +pub(crate) const ZONE_RELEASE_MC: i64 = 75_000; +pub(crate) const ZONE_HOT_MC: i64 = 80_000; +pub(crate) const ZONE_STEP_MC: i64 = 2_000; +pub(crate) const ZONE_FULL_COOLING_MC: i64 = ZONE_HOT_MC + (COOLING_MAX as i64 - 1) * ZONE_STEP_MC; +/// Startup/fault confirmation cadence (20 ms x 10 = 200 ms) and gradual release step. +pub(crate) const ZONE_CONFIRM_NS: u64 = 20_000_000; +pub(crate) const ZONE_CONFIRM_READS: u32 = 10; +pub(crate) const ZONE_RELEASE_NS: u64 = 200_000_000; + +/// Cooling level for a measured thermal-zone die temperature: 0 below 80 C, 1..=7 from +/// 80..94 C in 2 C steps, and [`COOLING_MAX`] at or above 94 C. +pub(crate) fn zone_heat_level(mc: i64) -> u32 { + if mc < ZONE_HOT_MC { + 0 + } else if mc >= ZONE_FULL_COOLING_MC { + COOLING_MAX + } else { + (((mc - ZONE_HOT_MC) / ZONE_STEP_MC) as u32 + 1).min(COOLING_MAX) + } +} + +/// Fail-closed thermal backstop driven by kernel SoC die thermal zones when a GPU DT node +/// has no `apple,pmp` telemetry bridge. Starts at [`COOLING_MAX`] (S1), requires 200 ms of +/// valid cool readings before stepping down gradually, and immediately clamps back to +/// [`COOLING_MAX`] on missing, stale, implausible, or critical readings. +pub(crate) struct ZoneBackstop { + level: u32, + hard: bool, + good_reads: u32, + good_ns: u64, + release_ns: u64, +} + +impl ZoneBackstop { + pub(crate) const fn new() -> Self { + Self { + level: COOLING_MAX, + hard: true, + good_reads: 0, + good_ns: 0, + release_ns: 0, + } + } + + pub(crate) const fn level(&self) -> u32 { + self.level + } + + /// Incorporates one sampled temperature (millidegrees Celsius) or sensor error at `now`. + pub(crate) fn sample(&mut self, now: u64, mc: i64, error: bool) -> u32 { + if error + || !(ZONE_PLAUSIBLE_MIN_MC..=ZONE_PLAUSIBLE_MAX_MC).contains(&mc) + || mc >= ZONE_FULL_COOLING_MC + { + self.level = COOLING_MAX; + self.hard = true; + self.good_reads = 0; + self.good_ns = now; + self.release_ns = now; + return self.level; + } + + if self.hard { + if mc < ZONE_HOT_MC { + if self.good_reads == 0 || now.wrapping_sub(self.good_ns) >= ZONE_CONFIRM_NS { + self.good_ns = now; + self.good_reads = self.good_reads.saturating_add(1).min(ZONE_CONFIRM_READS); + } + if self.good_reads >= ZONE_CONFIRM_READS { + self.hard = false; + } + } else { + self.good_reads = 0; + self.good_ns = now; + } + self.release_ns = now; + if self.hard { + return self.level; + } + } + + let target = zone_heat_level(mc); + if target > self.level { + self.level = target; + self.release_ns = now; + } else if mc < ZONE_RELEASE_MC && now.wrapping_sub(self.release_ns) >= ZONE_RELEASE_NS { + self.level = self.level.saturating_sub(1); + self.release_ns = now; + } else if mc >= ZONE_RELEASE_MC { + self.release_ns = now; + } + self.level + } + + /// Retains a cooling-device governor restriction inside the gradual release envelope. + pub(crate) fn observe(&mut self, now: u64, governor: u32) { + let clamped = governor.min(COOLING_MAX); + if clamped > self.level { + self.level = clamped; + self.release_ns = now; + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -666,4 +776,71 @@ mod tests { } assert_eq!(g.demand, FLOOR); } + + #[test] + fn zone_backstop_starts_fail_closed_releases_gradually_and_clamps_on_heat_or_fault() { + let mut z = ZoneBackstop::new(); + assert_eq!(z.level(), COOLING_MAX); + assert_eq!(cooling_ceiling(8, z.level()), 1); + + // Missing or implausible sensors keep the GPU clamped at S1 forever. + for i in 0..20u64 { + assert_eq!(z.sample(T + i * ZONE_CONFIRM_NS, 0, true), COOLING_MAX); + } + assert_eq!(z.sample(T + 1_000_000_000, 9_999, false), COOLING_MAX); + assert_eq!(z.sample(T + 1_020_000_000, 125_001, false), COOLING_MAX); + + // Repeated calls at the same timestamp cannot accelerate startup confirmation. + let base = T + 2_000_000_000; + for _ in 0..100 { + assert_eq!(z.sample(base, 55_000, false), COOLING_MAX); + } + for step in 1..ZONE_CONFIRM_READS as u64 { + assert_eq!( + z.sample(base + step * ZONE_CONFIRM_NS, 55_000, false), + COOLING_MAX + ); + } + // Gradual release: one cooling level every 200 ms below 75 C. + let confirmed = base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + assert_eq!( + z.sample(confirmed + ZONE_RELEASE_NS - 1, 55_000, false), + COOLING_MAX + ); + for step in 1..=COOLING_MAX as u64 { + assert_eq!( + z.sample(confirmed + step * ZONE_RELEASE_NS, 55_000, false), + COOLING_MAX - step as u32 + ); + } + assert_eq!(z.level(), 0); + assert_eq!(cooling_ceiling(8, z.level()), 8); + + // Progressive heat throttling from 80 C..94 C, immediate hard clamp at >= 94 C. + let hot_t = confirmed + 10 * ZONE_RELEASE_NS; + assert_eq!(z.sample(hot_t, 79_999, false), 0); + assert_eq!(z.sample(hot_t + 10_000_000, 80_000, false), 1); + assert_eq!(z.sample(hot_t + 20_000_000, 86_000, false), 4); + // Holding between 75 C and 80 C does not release cooling. + assert_eq!(z.sample(hot_t + 500_000_000, 75_000, false), 4); + assert_eq!(z.sample(hot_t + 1_000_000_000, 79_000, false), 4); + // Critical heat immediately returns to hard COOLING_MAX (S1). + assert_eq!(z.sample(hot_t + 1_010_000_000, ZONE_FULL_COOLING_MC, false), COOLING_MAX); + assert_eq!(cooling_ceiling(8, z.level()), 1); + + // Governor observation is retained in the release envelope. + let mut z2 = ZoneBackstop::new(); + for step in 0..ZONE_CONFIRM_READS as u64 { + z2.sample(base + step * ZONE_CONFIRM_NS, 50_000, false); + } + let c2 = base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + for step in 1..=COOLING_MAX as u64 { + z2.sample(c2 + step * ZONE_RELEASE_NS, 50_000, false); + } + assert_eq!(z2.level(), 0); + z2.observe(c2 + 9 * ZONE_RELEASE_NS, 5); + assert_eq!(z2.level(), 5); + assert_eq!(z2.sample(c2 + 9 * ZONE_RELEASE_NS + 1, 50_000, false), 5); + assert_eq!(z2.sample(c2 + 10 * ZONE_RELEASE_NS, 50_000, false), 4); + } } diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 45b68f3b08928e..19dea9418faa2e 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -312,7 +312,7 @@ impl Firmware { /// register is read. fn floor_power(&mut self, error: Error) { let before = self.power.effective; - let selectors = self.init.abi.initdata().pstate_selectors; + let selectors = self.init.layout.pstate_selectors; let mut ok = 0usize; let mut failed = 0usize; if let Some(globals) = self.init.globals.as_ref() { @@ -434,7 +434,7 @@ impl Firmware { return; }; let mut nonzero = 0usize; - for entry in &scan.banks { + for entry in scan.banks() { if entry.status == 0 { continue; } @@ -464,7 +464,8 @@ impl Firmware { if nonzero == 0 { dev_warn!( self.dev(), - "G16: fault_scan: all 8 banks zero (busy={}, saved_bank={}, event={:#x}, flights={})\n", + "G16: fault_scan: all {} banks zero (busy={}, saved_bank={}, event={:#x}, flights={})\n", + scan.banks().len(), scan.busy, scan.saved_bank, event, diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index be4cdb821292e4..8ef5eeb106b7d5 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -152,8 +152,8 @@ pub(crate) struct Identity { pub(crate) core_masks: [u32; 2], } -/// Fault-bank selector values (`+0xd800`) that name a fault bank. -pub(crate) const FAULT_BANKS: usize = 8; +/// Maximum number of fault banks across the supported SGX status windows. +const MAX_FAULT_BANKS: usize = 8; /// Engine receipts: busy bit and one fault bank. #[derive(Copy, Clone, Default)] @@ -177,21 +177,26 @@ impl EngineState { } } -/// Full eight-bank fault-register snapshot taken while firmware is halted for recovery. +/// Fault-register snapshot taken while firmware is halted for recovery. #[derive(Copy, Clone, Default)] pub(crate) struct FaultScan { /// Bit 0 of `+0xc020 | +0xc120`. pub(crate) busy: u64, - /// Selector (`+0xd800`) observed before scanning banks 0..7 and restored afterwards. + /// Selector (`+0xd800`) observed before scanning and restored afterwards. pub(crate) saved_bank: u64, - /// Raw status (`+0xd8c0`) and address (`+0xd8c8 << 6`) of each fault bank 0..7. - pub(crate) banks: [EngineState; FAULT_BANKS], + bank_count: usize, + /// Raw status (`+0xd8c0`) and address (`+0xd8c8 << 6`) of each fault bank. + banks: [EngineState; MAX_FAULT_BANKS], } impl FaultScan { + pub(crate) fn banks(&self) -> &[EngineState] { + &self.banks[..self.bank_count] + } + /// First bank whose latched fault bit (bit 0) is set. pub(crate) fn first_latched(&self) -> Option<&EngineState> { - self.banks.iter().find(|entry| entry.status & 1 != 0) + self.banks().iter().find(|entry| entry.status & 1 != 0) } } @@ -203,6 +208,7 @@ pub(crate) struct Regs { asc: Mapping, /// SGX status window (`sgx + 0xc000`, 0x4000). status: Mapping, + fault_banks: usize, /// Host-owned generation register page (SGX +0xd60000). generation: Mapping, /// GFXCAXI2AF registers (SGX +0x1000000), written only by the 27.2 start. @@ -219,6 +225,9 @@ impl Regs { res: G16Resources, cfg: &super::Config, ) -> Result { + if !(1..=MAX_FAULT_BANKS).contains(&cfg.fault_banks) { + return Err(EINVAL); + } let window = |name: &CStr, offset: u64| -> Result { let r = pdev.resource_by_name(name).ok_or(EINVAL)?; let nonposted = r @@ -232,6 +241,7 @@ impl Regs { Ok(Self { asc: window(c_str!("asc"), 0)?, status: window(c_str!("sgx"), SGX_STATUS as u64)?, + fault_banks: cfg.fault_banks, generation: window(c_str!("sgx"), super::hw::HOST_BLOCK)?, axi2af: cfg .axi2af @@ -242,9 +252,9 @@ impl Regs { }) } - /// Physical base of the scratch alias in InitData. - pub(crate) fn host_block_pa(&self) -> u64 { - self.generation.phys + /// Physical base of the SGX resource. + pub(crate) fn sgx_pa(&self) -> u64 { + self.generation.phys - super::hw::HOST_BLOCK } /// Reads the identification words and the enabled-core mask (after the AGX vote on 25G83). @@ -263,7 +273,9 @@ impl Regs { /// 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); + let top = rows + .saturating_sub(1) + .clamp(1, super::fw::initdata::PERF_STATES as u32 - 1); self.top.store(top, Ordering::Relaxed); } @@ -308,16 +320,21 @@ impl Regs { } /// 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 { + /// and on G16G reads the scratch word and raises the ready word. + pub(crate) fn publish_host_block(&self, cfg: &super::Config) -> Result> { use super::hw::start_27_2 as s; let g = self.generation.io(); - for offset in s::HOST_BLOCK_ZERO_ORDER { + for &offset in cfg.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)?; + let probe = if cfg.host_block_ready { + let probe = self.res.sgx_read32_at(s::SCRATCH_PROBE)?; + let _ = g.try_read32(s::HOST_READY)?; + g.try_write32(1, s::HOST_READY)?; + Some(probe) + } else { + None + }; mb(); Ok(probe) } @@ -347,7 +364,7 @@ impl Regs { } /// Engine receipts for a firmware halted for recovery and waiting on the host: reads all - /// eight fault banks (selectors 0 to 7 in order), capturing status and address for every + /// supported fault banks in order, capturing status and address for every /// non-zero bank, and restores the saved selector. #[inline(never)] pub(crate) fn fault_scan(&self) -> Result { @@ -357,25 +374,30 @@ impl Regs { let mut scan = FaultScan { busy, saved_bank: saved, - banks: [EngineState::default(); FAULT_BANKS], + bank_count: self.fault_banks, + banks: [EngineState::default(); MAX_FAULT_BANKS], }; - for (idx, entry) in scan.banks.iter_mut().enumerate() { - let bank = idx as u64; - r.try_write64(bank, 0x1800)?; - let status = r.try_read64(0x18c0)?; - let address = if status != 0 { - r.try_read64(0x18c8)? << 6 - } else { - 0 - }; - *entry = EngineState { - busy, - bank, - status, - address, - }; - } - r.try_write64(saved, 0x1800)?; + let result = (|| -> Result { + for (idx, entry) in scan.banks[..scan.bank_count].iter_mut().enumerate() { + let bank = idx as u64; + r.try_write64(bank, 0x1800)?; + let status = r.try_read64(0x18c0)?; + let address = if status != 0 { + r.try_read64(0x18c8)? << 6 + } else { + 0 + }; + *entry = EngineState { + busy, + bank, + status, + address, + }; + } + Ok(()) + })(); + let restore = r.try_write64(saved, 0x1800); + result.and(restore)?; Ok(scan) } } diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 633c0e327b8873..ea80070687867c 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -286,6 +286,9 @@ impl Shared { impl Gpu { /// Called before any device suspends. Only a sleep that powers the SoC down gets here. fn sleep_prepare(&self) -> Result { + if !self.cfg.deep_sleep { + return Err(EBUSY); + } let result = self.shared.sleep_down(); if let Err(error) = result { dev_warn!(self.shared.dev.as_ref(), "GPU refused sleep: {:?}\n", error); diff --git a/tools/asahi/g15-display-order-tests.py b/tools/asahi/g15-display-order-tests.py index f07ca470c4c92b..f72fca0cde9d52 100644 --- a/tools/asahi/g15-display-order-tests.py +++ b/tools/asahi/g15-display-order-tests.py @@ -216,6 +216,19 @@ def c_source(root): withdraw(&d30); CHECK(d30.refs == 0 && link30(&g30) == -EPROBE_DEFER); CHECK(link30(&g31) == -ENODEV); + } else if (!strcmp(scenario, "g16-t6030")) { + machine("apple,t6030", "apple,j516s"); + disp30.available = false; + CHECK(prepare16(&g30) == 0 && links_made == 0); + nodes[2] = NULL; + CHECK(prepare16(&g30) == 0 && links_made == 0); + nodes[2] = &disp30; + disp30.available = true; + CHECK(prepare16(&g30) == -EPROBE_DEFER && links_made == 0); + CHECK(publish(&d30) == 0); + CHECK(prepare16(&g30) == 0 && links_made == 1 && last_link.supplier == &d30); + withdraw(&d30); + CHECK(prepare16(&g30) == -EPROBE_DEFER); } else if (!strcmp(scenario, "t8132")) { /* No handed-over display: G16 starts on the boot framebuffer, said once. */ machine("apple,t8132", "apple,j713"); @@ -247,7 +260,7 @@ def c_source(root): } ''' -C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "t8132"] +C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "g16-t6030", "t8132"] C_MUTANTS = { "unpublished-succeeds": ("if (!*display)\n\t\treturn -EPROBE_DEFER;", "if (!*display)\n\t\treturn 0;"), @@ -258,8 +271,8 @@ def c_source(root): "t8132-reads-t6031-slot": ("&apple_t8132_display);", "&apple_t6031_display);"), "t8132-published-as-t6031": ("return &apple_t8132_display;", "return &apple_t6031_display;"), "g16-ignores-handed-over-display": ("handed_over = np && of_device_is_available(np);", "handed_over = false;"), - "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = apple_drm_t8132_link_device(dev);", - "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = apple_drm_t8132_link_device(dev);"), + "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev);", + "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev);"), "no-machine-check": ("!of_machine_is_compatible(machine) ||", ""), "withdraw-keeps-display": ("*slot = NULL;", ";"), "publish-without-reference": ("*slot = get_device(dev);", "*slot = dev;"), diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index 949c0be39a3e48..930c5a3cd267aa 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -66,6 +66,8 @@ def item(text, marker): const ENODEV: i32 = -19; const EPROBE_DEFER: i32 = -517; const GFP_KERNEL: u32 = 0; +#[allow(unused_macros)] +macro_rules! c_str { ($s:literal) => { $s }; } macro_rules! dev_info { ($($x:tt)*) => {{}}; } macro_rules! dev_err { ($($x:tt)*) => {{}}; } thread_local! { @@ -85,9 +87,14 @@ def item(text, marker): static PROBE_ERROR: Cell = const { Cell::new(0) }; } struct Core<'a>(PhantomData<&'a ()>); -struct Device { data: Cell<*mut core::ffi::c_void> } +struct Device { data: Cell<*mut core::ffi::c_void>, g16_handoff: bool } impl Device { fn as_raw(&self) -> *mut Device { self as *const Device as *mut Device } + fn of_node(&self) -> Option<&Self> { Some(self) } + fn get_opt_property(&self, name: &str) -> Result> { + assert_eq!(name, "apple,g16-handoff-version"); + Ok(self.g16_handoff.then(T::default)) + } // SET_DRVDATA } mod bindings { @@ -138,7 +145,7 @@ def item(text, marker): ) -> impl PinInit, Error> + 'bound; } } -struct Config { name: &'static str } +struct Config { name: &'static str, chip_id: u32 } pub struct ThisModule; pub trait ModuleMetadata { const NAME: &'static std::ffi::CStr; } pub trait InPlaceModule: Sized { @@ -235,9 +242,9 @@ def item(text, marker): FAIL_ALLOC.set(fail_alloc); TOUCH.set(touch); PROBE_ERROR.set(error); RETAINED.set(false); ALLOCS.set(0); PROBES.set(0); } -static CFG: Config = Config { name: "test" }; +static CFG: Config = Config { name: "test", chip_id: 0x6030 }; static PDEV: platform::Device> = platform::Device { - base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData, + base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: false }, ctx: PhantomData, }; fn activation_reprobe() { let last = if cfg!(CONFIG_DRM_ASAHI_G16) { 3 } else { 2 }; @@ -287,7 +294,7 @@ def item(text, marker): ("successful-registration-binds", false, true, 0, Ok(0), true, 1), ] { reset(allocation_fails, touched, error); - let pdev = platform::Device { base: Device { data: Cell::new(core::ptr::null_mut()) }, ctx: PhantomData }; + let pdev = platform::Device { base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: false }, ctx: PhantomData }; let result = callback::>(&pdev, Some(&cfg)); assert_eq!(result, expected, "{name}: callback result"); assert_eq!(PROBES.get(), calls, "{name}: firmware probe before drvdata allocation"); @@ -300,6 +307,14 @@ def item(text, marker): } println!("{name}: PASS"); } + reset(false, true, 0); + let pdev = platform::Device { + base: Device { data: Cell::new(core::ptr::null_mut()), g16_handoff: true }, + ctx: PhantomData, + }; + assert_eq!(callback::>(&pdev, Some(&cfg)), Err(ENODEV)); + assert_eq!(PROBES.get(), 0); + println!("g16-handoff-declined: PASS"); module_cases(); } ''' @@ -446,7 +461,7 @@ def main(): if name == "actual": receipt["g16_control" if enable_g16 else "control"] = result if r.returncode: raise SystemExit(r.stderr) - if r.stdout.count(": PASS\n") != (10 if enable_g16 else 9): raise SystemExit("control did not run every case") + if r.stdout.count(": PASS\n") != (11 if enable_g16 else 10): raise SystemExit("control did not run every case") else: receipt["mutants"][label] = result if r.returncode == 0: raise SystemExit("SURVIVED: " + name) 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 dffe9f155db0c9..7a235103bb9909 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 @@ -7,7 +7,7 @@ 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 enum GpuVariant {G, S} 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; @@ -15,6 +15,14 @@ mod hw { mod fwid { @FWID_BUILD@ } +mod adt { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/adt/perf.rs"] + pub mod perf; +} +mod board { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/board/data.rs"] + pub mod data; +} #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/hw.rs"] mod backend_hw; #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/mod.rs"] @@ -60,6 +68,7 @@ fn input() -> wire::Input { lower_parameter: wire::BOOTSTRAP_START + 0x240000, ktrace_mask: 0x12345678, progress_recovery: 1, + enabled_cores: 10, // T8132 ADT sgx and pmgr/clpc power-sampling and low-peak limiter parameters (24 MHz). power_sample_clks: 200_000, power_sample_us: 8333, @@ -316,7 +325,7 @@ fn catalog() { 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 (v25, v26) = (FW_25G83.initdata, FW_26B123.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)); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs index 2f607bd2b27aa7..2ef3e8fd5fe7ae 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-channels.rs @@ -1,5 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -#![allow(dead_code)] +#![allow(dead_code, non_camel_case_types, non_snake_case, non_upper_case_globals)] +extern crate self as kernel; +mod uapi { include!("public-uapi.rs"); } mod fw { #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/fw/initdata.rs"] pub mod initdata; @@ -11,7 +13,15 @@ mod graph; mod fwid { @FWID_BUILD@ } -mod hw {pub enum GpuVariant {G}} +mod hw {pub enum GpuVariant {G, S}} +mod adt { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/adt/perf.rs"] + pub mod perf; +} +mod board { + #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/board/data.rs"] + pub mod data; +} #[path = "@KERNEL@/drivers/gpu/drm/asahi/g16/hw.rs"] mod backend_hw; fn main() { 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 52787524d33f41..a39156b45d7b11 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 @@ -20,6 +20,7 @@ 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, + enabled_cores: 10, 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, 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 bf002c5a597646..72fdcb8c7df97a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-initdata.rs @@ -24,6 +24,7 @@ fn input(variant: u64) -> initdata::Input { lower_parameter: 0x7000240000, ktrace_mask: [0, 0x12345678, 0xfedcba98][variant as usize], progress_recovery: u32::from(variant != 1), + enabled_cores: 10, // T8132 ADT power-sampling ticks; 25G83 writes power_sample_clks to +4/+8. power_sample_clks: 200_000, power_sample_us: 8333, 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 253696fa2f0031..b696ece088d2f3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -74,6 +74,7 @@ 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, + enabled_cores: 10, 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, @@ -156,6 +157,69 @@ def node(props, children=()): let mut p=tables(); p.frequency[10]=1500; assert!(!p.valid()); let mut p=tables(); p.count=11; assert!(!p.valid()); } +#[test] +fn g15s_power_config_uses_the_encoded_ceiling_and_machine_adt_limiter() { + let mut performance = tables(); + performance.count = 9; + performance.frequency[9..].fill(0); + performance.auxiliary[9..].fill(0); + performance.voltage[9..].fill(0); + performance.sram[9..].fill(0); + + let layout = &wire::G15S_26B123; + let mut input = input(performance); + input.enabled_cores = 18; + // T6030 ADT /arm-io/pmgr/clpc & /arm-io/sgx limiter properties (24 MHz timebase). + input.avg_power_filter_tc_ms = 300; + input.lowpeak_limiter_tc_ms = 30; + input.lowpeak_limiter_ki_q16 = 171_128; + input.lowpeak_limiter_kp_q16 = 11_073; + for (i, loader) in layout.loaders.iter().enumerate() { + input.loader_va[i] = if loader.length != 0 && layout.slot(i).is_some() { + wire::HOST_START + 0x5000000 + i as u64 * 0x100000 + (loader.pa & 0x3fff) + } else { + 0 + }; + } + let mut buffers = layout.object_size.map(|size| vec![0; size]); + wire::encode_for(layout, &mut buffers.each_mut().map(|b| b.as_mut_slice()), &input, 8).unwrap(); + let power = &buffers[wire::id::POWER_PERFORMANCE]; + assert_eq!(get32(power, 0x04), 200_000); + assert_eq!(get32(power, 0x08), 200_000); + assert_eq!(get32(power, 0xb90), 800); + assert_eq!(get32(power, 0x2c), 8); + assert_eq!(get32(power, 0x30), 8); + // Average-power filter: (300 * 1000) / 8333 = 36 samples -> 144, 35/36, 1/36. + assert_eq!(get32(power, 0x29e4), 36 * 4); + assert_eq!(get32(power, 0x29f0), wire::f32_bits(35, 36)); + assert_eq!(get32(power, 0x29f8), wire::f32_bits(1, 36)); + // Low-peak limiter: 30 / 8 = 3 periods -> 12, 2/3, 1/3, ki*dt, kp, 30 ms, 576000 clks. + assert_eq!(get32(power, 0xa80), 3 * 4); + assert_eq!(get32(power, 0xa8c), wire::f32_bits(2, 3)); + assert_eq!(get32(power, 0xa94), wire::f32_bits(1, 3)); + assert_eq!(get32(power, 0xa9c), wire::f32_bits(171_128 * 8, 65536 * 1000)); + assert_eq!(get32(power, 0xaac), wire::f32_bits(11_073, 65536)); + assert_eq!(get32(power, 0xad8), 30); + assert_eq!(get32(power, 0xae0), 3 * 8 * 24_000); + + // Missing ADT power limiter / sampling inputs must fail closed on G15S as well. + for bad in 0..5 { + let mut bad_input = wire::Input { + performance: input.performance.clone(), + ..input + }; + match bad { + 0 => bad_input.avg_power_filter_tc_ms = 0, + 1 => bad_input.lowpeak_limiter_tc_ms = 0, + 2 => bad_input.lowpeak_limiter_ki_q16 = 0, + 3 => bad_input.lowpeak_limiter_kp_q16 = 0, + _ => bad_input.power_sample_period_ms = 0, + } + let mut out_bufs = layout.object_size.map(|size| vec![0xa5; size]); + assert!(wire::encode_for(layout, &mut out_bufs.each_mut().map(|b| b.as_mut_slice()), &bad_input, 8).is_err()); + assert!(out_bufs.iter().all(|b| b.iter().all(|&x| x == 0xa5))); + } +} #[test] fn different_real_bin_values_reach_all_firmware_lanes() { let mut raw=MEASURED.to_vec(); for name in [b"perf-states".as_slice(),b"perf-states-sram".as_slice()] { @@ -294,7 +358,7 @@ def node(props, children=()): print(run.stdout, end='') print(run.stderr, end='') run.check_returncode() -report = {'passed': True, 'test_groups': 10, 'hardware_validated': False, +report = {'passed': True, 'test_groups': 12, '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 700021a590040c177149547930ef1247d039221f Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:24:17 -0500 Subject: [PATCH 1251/1514] drm/asahi: wire G15S 26B123 runtime ABI in the shared g16 backend Add FwAbi::V26B123G15S and per-SoC runtime parameters so T6030 G15S on macOS 27.2 (26B123) encodes the exact wire layouts expected by the G15S firmware without changing any T8132 G16G bytes: - PB manager: add pb_manager::V26B123_G15S (-4 byte shift from ID_A at +0x08 through MAX_PAGES_B at +0x7c, matching the 0x90-byte record invalidated by TA/InitBM) and wire it through PbEpoch. - Queue info: add qinfo::V26B123_G15S (0x88-byte header with trailing u64 4 at +0x80 and scratch starting at +0x88). - Render and compute work/microsequences: - 2-cluster TPC sizing (num_clusters * e * 8 * layers) and named G15 vs G16 fragment tile-state base constants. - G15S 74-register TA list (ta::SEL_G15S, named UMA PTC and DUPM resource-control bitfield constructors, ta+0x760 = tpc_gva, HEAD_ACTIVE_SIZE = 0x3e0). - G15S 82-register FS list (fs::SEL_G15S, named UMA PTC, DUPM, cache, ISP and ZLS register constants, G15S header words) and 0x340-byte FS microsequence (scene+0x4c, 0x34-byte inline UMA, TS_START=0x1e4, FINALIZE=0x280, event at +0xad, END at 0x334, and render_attachments_for). - G15S 25-register compute list (named G15 stage-control register, no HAL200 USC-base register, preemption tail +0x1b80, 2-cluster context-store offsets +0/+0x1e400/+0x3c800/+0x3d800, HEAD_ACTIVE_SIZE = 0x180). - Cross-engine barriers: hold FS->compute (BarrierType::Hold) on G15S (Config::cross_engine_hold), matching G15 CROSS_ENGINE_HOLD = 1. - UAPI and admission: gate HAL200-only FEW_PRIMITIVES, RENDER_RAY_QUERY, and BOUNDED_AS_BUILD features/commands on gpu_generation >= 16; accept DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING and validate 2-cluster geometry on G15S. - Scratch mapping and handoff: map the split G15S scratch VA spans to the contiguous physical host-register range (+0x14000..+0x20000), and drop the T6030 chip-ID gate in g15::Driver::probe so any G15 SoC with apple,g16-handoff-version hands off cleanly to g16. - Selftests: extend check-abi-26b123.rs with G15S 26B123 wire checks. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g15/mod.rs | 14 +- drivers/gpu/drm/asahi/g16/command.rs | 110 +++- drivers/gpu/drm/asahi/g16/encode.rs | 56 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 54 +- drivers/gpu/drm/asahi/g16/encode/render.rs | 579 ++++++++++++------ drivers/gpu/drm/asahi/g16/engine.rs | 47 +- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 114 +++- drivers/gpu/drm/asahi/g16/fw/graph.rs | 19 + drivers/gpu/drm/asahi/g16/fw/mod.rs | 14 +- drivers/gpu/drm/asahi/g16/fw/work.rs | 119 +++- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 49 +- drivers/gpu/drm/asahi/g16/hw.rs | 16 +- drivers/gpu/drm/asahi/g16/initdata.rs | 8 +- drivers/gpu/drm/asahi/g16/params.rs | 10 +- drivers/gpu/drm/asahi/g16/pools.rs | 17 +- drivers/gpu/drm/asahi/g16/queue.rs | 19 +- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 135 ++++ 17 files changed, 1095 insertions(+), 285 deletions(-) diff --git a/drivers/gpu/drm/asahi/g15/mod.rs b/drivers/gpu/drm/asahi/g15/mod.rs index 9b45de2b1ce63c..ebe34119887f58 100644 --- a/drivers/gpu/drm/asahi/g15/mod.rs +++ b/drivers/gpu/drm/asahi/g15/mod.rs @@ -203,14 +203,12 @@ impl platform::Driver for Driver<'_> { try_pin_init!(Driver { _driver: { let cfg = *info.ok_or(ENODEV)?; - if cfg.chip_id == 0x6030 - && pdev.as_ref().of_node().is_some_and(|node| { - !matches!( - node.get_opt_property::(c_str!("apple,g16-handoff-version")), - Ok(None) - ) - }) - { + if pdev.as_ref().of_node().is_some_and(|node| { + !matches!( + node.get_opt_property::(c_str!("apple,g16-handoff-version")), + Ok(None) + ) + }) { return Err(ENODEV); } if !MODULE_READY.load(Ordering::Acquire) { diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index b21c9eb1f9b534..197d31e93fa0f6 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -37,6 +37,8 @@ const NONE: u16 = uapi::DRM_ASAHI_BARRIER_NONE as u16; const VERTEX_SCRATCH: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_VERTEX_SCRATCH; const PROCESS_EMPTY_TILES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_PROCESS_EMPTY_TILES; +const NO_VERTEX_CLUSTERING: u32 = + uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING; 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 FEW_PRIMITIVES: u32 = uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES; @@ -379,6 +381,7 @@ pub(crate) struct Prepared { commands: Commands, orders: Orders, counts: [u64; 2], + gpu_generation: u32, } /// One command of the stream. @@ -556,11 +559,32 @@ fn check_render_helpers(cmd: &uapi::drm_asahi_cmd_render) -> Result { /// Reject geometry which cannot fit any retained pass before a submission is accepted. /// The encoder owns the sizing formula; admission and publication use the same calculation. -fn check_geometry(cmd: &uapi::drm_asahi_cmd_render) -> Result { - super::encode::Geometry::new(cmd, 0) +fn check_geometry( + cmd: &uapi::drm_asahi_cmd_render, + num_clusters: u32, + gpu_generation: u32, +) -> Result { + super::encode::Geometry::new_for(cmd, 0, num_clusters, gpu_generation) .validate_capacity(hw::client::TPC_SIZE, hw::client::TILEMAP_SIZE) } +fn render_allowed_flags(early_tiling: bool, gpu_generation: u32) -> u32 { + let gen_flags = if gpu_generation >= 16 { + FEW_PRIMITIVES + } else { + NO_VERTEX_CLUSTERING + }; + PROCESS_EMPTY_TILES + | DBIAS_IS_INT + | RSRC_SPEC_HI + | gen_flags + | if early_tiling { + FRAGMENT_BARRIERS | STAGE_PREFIXES + } else { + 0 + } +} + fn validate_attachments_header(entry: &Entry<'_>) -> Result { if entry.barriers != [NONE; 2] || entry.payload.len() % ATTACHMENT_SIZE != 0 @@ -585,6 +609,8 @@ fn validate_render_entry( entry: &Entry<'_>, counts: [u32; 2], early_tiling: bool, + num_clusters: u32, + gpu_generation: u32, ) -> Result<( uapi::drm_asahi_cmd_render, Option, @@ -592,8 +618,15 @@ fn validate_render_entry( )> { let (packet, prefixes) = render_payload(entry.payload)?; let cmd = &packet; - // The ray-query stages after the historical prefixes (RENDER_RAY_QUERY). + // The ray-query stages after the historical prefixes (RENDER_RAY_QUERY, G16+ only). let ray_query = render_ray_query(entry.payload)?; + if gpu_generation < 16 + && ray_query + .iter() + .any(|stage| stage.intersection.enabled() || stage.scratch.enabled()) + { + return Err(EINVAL); + } if let Some(prefixes) = prefixes { if (prefixes.ta_vdm_barrier != NONE && u32::from(prefixes.ta_vdm_barrier) > counts[RENDER]) || (prefixes.ta_cdm_barrier != NONE @@ -603,16 +636,7 @@ fn validate_render_entry( } } check_render_helpers(cmd)?; - // M4 HAL200 resource words carry all four high halves. - let allowed = PROCESS_EMPTY_TILES - | DBIAS_IS_INT - | FEW_PRIMITIVES - | RSRC_SPEC_HI - | if early_tiling { - FRAGMENT_BARRIERS | STAGE_PREFIXES - } else { - 0 - }; + let allowed = render_allowed_flags(early_tiling, gpu_generation); if cmd.flags & !allowed != 0 || !(1..=MAX_DIMENSION).contains(&cmd.width_px) || !(1..=MAX_DIMENSION).contains(&cmd.height_px) @@ -621,7 +645,7 @@ fn validate_render_entry( { return Err(EINVAL); } - check_geometry(cmd)?; + check_geometry(cmd, num_clusters, gpu_generation)?; // Timestamp copies are reserved for another runtime. No copy // feature is advertised, and zero handles do not waive MBZ offsets. if cmd @@ -649,12 +673,16 @@ fn validate_render_entry( fn validate_compute_entry( entry: &Entry<'_>, range: &Range, + gpu_generation: u32, ) -> Result<(uapi::drm_asahi_cmd_compute, super::rt::ComputeRay, bool)> { let packet: uapi::drm_asahi_cmd_compute = payload(entry.payload)?; let cmd = &packet; let Some(as_build) = super::rt::as_build(cmd.flags & !COMPUTE_NO_QUERY_ACCESS) else { return Err(EINVAL); }; + if gpu_generation < 16 && as_build { + return Err(EINVAL); + } if cmd.cdm_ctrl_stream_end <= cmd.cdm_ctrl_stream_base || !inside( cmd.cdm_ctrl_stream_base, @@ -671,8 +699,11 @@ fn validate_compute_entry( { return Err(EINVAL); } - // The G17P scratch layout and intersection tables (RENDER_RAY_QUERY). + // The G17P scratch layout and intersection tables (RENDER_RAY_QUERY, G16+ only). let ray = compute_ray(cmd)?; + if gpu_generation < 16 && (ray.intersection.enabled() || ray.scratch.enabled()) { + return Err(EINVAL); + } Ok((packet, ray, as_build)) } @@ -1208,13 +1239,28 @@ fn check_render( cmd: &uapi::drm_asahi_cmd_render, vertex: &[uapi::drm_asahi_attachment], fragment: &[uapi::drm_asahi_attachment], +) -> Result { + check_render_for(batch, context, cmd, vertex, fragment, 16) +} + +fn check_render_for( + batch: &mut SpanBatch, + context: &Context<'_>, + cmd: &uapi::drm_asahi_cmd_render, + vertex: &[uapi::drm_asahi_attachment], + fragment: &[uapi::drm_asahi_attachment], + gpu_generation: u32, ) -> Result { check_render_helpers(cmd)?; let vm = context.vm; let allowed = PROCESS_EMPTY_TILES | RSRC_SPEC_HI | DBIAS_IS_INT - | FEW_PRIMITIVES + | if gpu_generation >= 16 { + FEW_PRIMITIVES + } else { + uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_NO_VERTEX_CLUSTERING + } | if super::params::early_tiling() { FRAGMENT_BARRIERS | STAGE_PREFIXES } else { @@ -1449,11 +1495,22 @@ pub(crate) struct ParsedStream { commands: Commands, meta: OrderMetas, counts: [u64; 2], + gpu_generation: u32, } /// Structurally validates and decodes a command stream in a single pass, before anything is /// looked up or device state is consulted. pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { + parse_stream_for(bytes, early_tiling, 1, 16) +} + +/// [`parse_stream`] parameterized by the GPU's cluster count and hardware generation. +pub(crate) fn parse_stream_for( + bytes: &[u8], + early_tiling: bool, + num_clusters: u32, + gpu_generation: u32, +) -> Result { if bytes.is_empty() || bytes.len() > MAX_CMDBUF || bytes.len() % 8 != 0 { return Err(EINVAL); } @@ -1495,8 +1552,13 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { - let (packet, prefixes, ray_query) = - validate_render_entry(&entry, counts, early_tiling)?; + let (packet, prefixes, ray_query) = validate_render_entry( + &entry, + counts, + early_tiling, + num_clusters, + gpu_generation, + )?; counts[RENDER] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1527,7 +1589,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result 1 - || super::encode::Geometry::new(&packet, 0).tilemap_bytes + || super::encode::Geometry::new_for(&packet, 0, num_clusters, gpu_generation) + .tilemap_bytes > hw::sizes::TA_LIGHT_TILEMAP_BYTES; commands.push(Command::Render(KBox::new( RenderCommand { @@ -1547,7 +1610,8 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { - let (packet, ray, as_build) = validate_compute_entry(&entry, &range)?; + let (packet, ray, as_build) = + validate_compute_entry(&entry, &range, gpu_generation)?; counts[COMPUTE] += 1; if counts[RENDER] + counts[COMPUTE] > MAX_COMMANDS { return Err(EINVAL); @@ -1593,6 +1657,7 @@ pub(crate) fn parse_stream(bytes: &[u8], early_tiling: bool) -> Result { - check_render( + check_render_for( &mut scratch.batch, context, &render.cmd, &render.vertex_attachments, &render.fragment_attachments, + gpu_generation, )?; render.scs = check_render_ray(&mut scratch.batch, context, &render.ray_query)?; diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index 5c91c50db28847..b26ca956c8b0f7 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -67,6 +67,32 @@ pub(crate) const fn compact(gva: u64) -> u64 { gva.wrapping_sub(0x1000000000) } +/// Packed UMA page-table cache (PTC) policy word written to `0xa5a1` (TA), `0xa5a9` (FS), +/// and `0xa599` (compute): low 16 bits = min entries, bits 31..16 = mid entries, bits 63..32 = +/// max entries. +pub(super) const fn uma_ptc_word(min: u16, mid: u16, max: u16) -> u64 { + (min as u64) | ((mid as u64) << 16) | ((max as u64) << 32) +} + +/// Packed DUPM resource-control word written to `0xd419` (TA), `0xd429` (FS), and `0xd411` +/// (compute): lower and upper 32-bit resource-allocation limits. +pub(super) const fn dupm_control_word(lo: u32, hi: u32) -> u64 { + (lo as u64) | ((hi as u64) << 32) +} + +/// Default DUPM resource-control word shared by TA, FS and compute work items. +pub(super) const DEFAULT_DUPM_CONTROL: u64 = dupm_control_word(1, 2); + +/// Default per-stage hardware control word written to `0x101e1`/`0x12099` (TA), +/// `0x101e9`/`0x120a1` (FS), and `0x101d9`/`0x12091` (compute). +pub(super) const STAGE_CTRL_DEFAULT: u64 = 0x1c; + +/// Fragment tile-state base bits (`0x16068`) for G15 and G16+ hardware, plus the required +/// enable bit at bit 37. +const TILE_STATE_BASE_G15: u64 = 0x36011; +const TILE_STATE_BASE_G16: u64 = 0x3717f; +const TILE_STATE_ENABLE_BIT: u64 = 1 << 37; + #[path = "encode/compute.rs"] mod compute_encoder; use compute_encoder::put_generation; @@ -118,9 +144,20 @@ impl Geometry { Ok(()) } - /// The geometry of render `u` with layer metadata at `heap`. The render was validated - /// (width, height, layers >= 1, samples 1, 2 or 4, utiles 16 or 32). + /// The geometry of render `u` with layer metadata at `heap` for single-cluster G16G. pub(crate) fn new(u: &uapi::drm_asahi_cmd_render, heap: u64) -> Self { + Self::new_for(u, heap, 1, 16) + } + + /// The geometry of render `u` with layer metadata at `heap` for a GPU with `num_clusters` + /// clusters and `gpu_generation`. The render was validated (width, height, layers >= 1, + /// samples 1, 2 or 4, utiles 16 or 32). + pub(crate) fn new_for( + u: &uapi::drm_asahi_cmd_render, + heap: u64, + num_clusters: u32, + gpu_generation: u32, + ) -> Self { let (w, h, l) = ( u32::from(u.width_px), u32::from(u.height_px), @@ -159,7 +196,7 @@ impl Geometry { }; g.utile_config = utile_w | utile_h | log2s; g.tilemap_bytes = align(5 * g.e * u64::from(l), 0x1000); - g.tpc_bytes = g.e * 8 * u64::from(l); + g.tpc_bytes = u64::from(num_clusters.max(1)) * g.e * 8 * u64::from(l); g.layer_metadata = heap + if l > 1 { 0x200 } else { 0 }; g.layer_mode = if l == 1 { 0x8000 @@ -178,11 +215,16 @@ impl Geometry { let few_primitives = u.flags & uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FEW_PRIMITIVES != 0; g.isp_control = 0xc000 | (u.flags & (1 << 18)) | u32::from(few_primitives); - g.native_tiles = 0x3717fu64 + let native_tiles_base = if gpu_generation < 16 { + TILE_STATE_BASE_G15 + } else { + TILE_STATE_BASE_G16 + }; + g.native_tiles = native_tiles_base | u64::from(l > 1) << 32 | u64::from(g.tx.wrapping_sub(1)) << 44 | u64::from(g.ty.wrapping_sub(1)) << 53 - | 137438953472u64 + | TILE_STATE_ENABLE_BIT | u64::from(g.utile_config & 0xf000) << 28; g } @@ -283,6 +325,6 @@ 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_fs_for, encode_fs_rt, encode_ta, encode_ta_for, - encode_ta_rt, fill_scene, initbm, render_attachments, scene, scene_prefix, scene_render, - PassRefs, RenderRefs, StageRt, RENDER_SCS_ENABLE, + encode_ta_rt, fill_scene, initbm, render_attachments, render_attachments_for, scene, + scene_prefix, scene_render, PassRefs, RenderRefs, StageRt, RENDER_SCS_ENABLE, }; diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 78c972ac4c9df8..2411fa6ed1d3cd 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -5,6 +5,19 @@ use super::{compute, manager, pools, put16, put32, put64, put8, uapi}; +/// G15-only compute stage control register emitted immediately before [`REG_STAGE_CTRL`]. +const REG_G15_STAGE_CTRL: u32 = 0x12091; +/// Shared compute stage control register. +const REG_STAGE_CTRL: u32 = 0x101d9; +/// HAL200 compute USC-base register (`0x10071`). +const REG_HAL200_USC_BASE: u32 = 0x10071; +/// Default compute stage hardware control word (`0x101d9` / G15 `0x12091`). +const STAGE_CTRL_DEFAULT: u64 = 0x1c; +/// Packed compute UMA page-table cache (PTC) policy word (`0xa599`): min=0x20, mid=0x40, max=0x132. +const COMPUTE_UMA_PTC: u64 = 0x20 | (0x40 << 16) | (0x132 << 32); +/// Packed compute DUPM resource-control word (`0xd411`): lo=1, hi=2. +const DEFAULT_DUPM_CONTROL: u64 = 1 | (2 << 32); + /// 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 { @@ -114,9 +127,10 @@ impl ComputeRt { }; } -/// Register records of a compute work item at most: the 24 of [`compute::SEL`], 0x10071, the -/// ray-query first and last records and the gated SCS driver word. -const MAX_REGS: usize = compute::SEL.len() + 4; +/// Register records of a compute work item at most: the 24 of [`compute::SEL`], optional G15 +/// `0x12091`, optional HAL200 `0x10071`, the ray-query first and last records and the gated SCS +/// driver word. +const MAX_REGS: usize = compute::SEL.len() + 5; const FW_START: u64 = 0xfffffc2000000000; const FW_END: u64 = 0xfffffc2ffc000000; @@ -370,17 +384,18 @@ pub(crate) fn encode_compute_rt( } } let pre = r.preempt_gva; + let tail = layout.preempt_tail; let [i0, i1, i2, i3, i4, i5] = rt.intersection; let values = [ pre, base, - pre + 0x1480, - pre + 0x1488, - pre + 0x1490, - pre + 0x1498, + pre + tail, + pre + tail + 8, + pre + tail + 0x10, + pre + tail + 0x18, 0x154024201, 0x10c08860, - 0x1c, + STAGE_CTRL_DEFAULT, i0, i1, i2, @@ -391,8 +406,8 @@ pub(crate) fn encode_compute_rt( rt.tail, rt.stack, rt.window, - 0x13200400020, - 0x200000001, + COMPUTE_UMA_PTC, + DEFAULT_DUPM_CONTROL, 1, 1, 1, @@ -409,13 +424,16 @@ pub(crate) fn encode_compute_rt( push(RAY_QUERY_FIRST.0, RAY_QUERY_FIRST.1); } for (&sel, &value) in compute::SEL.iter().zip(values.iter()) { + if sel == REG_STAGE_CTRL && layout.has_reg_12091 { + push(REG_G15_STAGE_CTRL, STAGE_CTRL_DEFAULT); + } push(sel, value); if sel == 0x1a0e9 && COMPUTE_SCS_DRIVER_WORD && rt.scs { push(0x1a141, rt.driver); } } - if r.usc_base != 0 { - push(0x10071, r.usc_base); + if layout.has_usc_base_reg && r.usc_base != 0 { + push(REG_HAL200_USC_BASE, r.usc_base); } if rt.scs { push(RAY_QUERY_LAST.0, RAY_QUERY_LAST.1); @@ -458,8 +476,8 @@ pub(crate) fn encode_compute_rt( put64(w, 0x84c, ts_va[1]); put64(w, 0x86a, r.work + compute::DESCRIPTOR as u64); put8(w, 0x872, 1); - put64(w, 0x873, 0x1588000); - put64(w, 0x87b, 0xef8000); + put64(w, 0x873, layout.pool_words[0]); + put64(w, 0x87b, layout.pool_words[1]); put64(w, 0x883, r.auxiliary_fw); put_generation( w, @@ -491,10 +509,10 @@ pub(crate) fn encode_compute_rt( put32(q, 0x158, att.len() as u32); put64(q, 0x160, r.work + compute::DESCRIPTOR as u64); put64(q, 0x178, r.auxiliary_gva); - put64(q, 0x188, r.context_store_gva); - 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, 0x188, r.context_store_gva + layout.context_store_offsets[0]); + put64(q, 0x190, r.context_store_gva + layout.context_store_offsets[1]); + put64(q, 0x198, r.context_store_gva + layout.context_store_offsets[2]); + put64(q, 0x1a0, r.context_store_gva + layout.context_store_offsets[3]); put64(q, 0x1a8, r.work + layout.target as u64); put32(q, 0x1b8, r.event); let requested = ts_va[0] != 0 || ts_va[1] != 0; diff --git a/drivers/gpu/drm/asahi/g16/encode/render.rs b/drivers/gpu/drm/asahi/g16/encode/render.rs index ebf2e03a682697..7212a2b501e9b7 100644 --- a/drivers/gpu/drm/asahi/g16/encode/render.rs +++ b/drivers/gpu/drm/asahi/g16/encode/render.rs @@ -69,6 +69,19 @@ pub(crate) struct PassRefs { pub(crate) ta_scratch: u64, } +/// Packed 16-bit tiler hardware configuration fields written to TA `0x1c051`. +const TA_TILER_CONFIG: u64 = 0x0003 | (0x006b << 16) | (0x0012 << 32) | (0x003a << 48); +/// Default render cache configuration written to TA `0x1c8f8` and FS `0x100b8`. +const RENDER_CACHE_CONFIG: u64 = 0x8860; +/// Default ISP control word written to FS `0x15049` and mirrored at FS work `+0x9d0`. +const FS_ISP_CTRL_DEFAULT: u64 = 0x10_0000; +/// Default ZLS per-lane sample mask written to FS `0x15349` and mirrored at FS work `+0x940`. +const FS_ZLS_SAMPLE_MASK_DEFAULT: u64 = 0x0404_0404; +/// UMA page-table cache (PTC) policy words for G16G render (`0xa5a1`/`0xa5a9`) and G15S TA/FS. +const G16G_RENDER_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x60); +const G15S_TA_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x7f); +const G15S_FS_UMA_PTC: u64 = uma_ptc_word(0x20, 0x40, 0x9f); + /// Write the macOS 27.2 J773g SCS enable pair (`0x017e1 = 1` before `at`, `0x017d9 = 1` at the /// end) in the register list of a render stage with scratch: `0x017e1 = 1` first in the TA list /// (before `0x1748`) and after `0x1739` in the FS list, with `0x017d9 = 1` last in both, matching @@ -142,7 +155,7 @@ fn metadata(w: &mut [u8], off: usize, r: &RenderRefs, engine: usize, target: u32 // Wire sequence stays zero; host reservations are 64-bit notifier state. } -fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize) { +fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize, engine_byte: bool) { put64(q, off, r.uma_mgr[0]); put64( q, @@ -151,7 +164,9 @@ fn inline_uma(q: &mut [u8], off: usize, r: &RenderRefs, engine: usize) { ); put64(q, off + 0x28, r.counter[engine]); put32(q, off + 0x30, 0x70 + engine as u32); - put8(q, off + 0x34, engine as u8); + if engine_byte { + put8(q, off + 0x34, engine as u8); + } } #[allow(clippy::too_many_arguments)] @@ -270,76 +285,159 @@ pub(crate) fn encode_ta_rt( 0x7000000000 })) & 0x7ffffffffe) | ((scratch & (1 << 42)) >> 3); - let val: [u64; 66] = [ - 1, - 0x200, - compact(p.tilemap_gva), - compact(p.tilemap_gva), - compact(p.tpc_gva), - compact(p.heap_gva) | 1 << 63, - compact(p.heap_gva) | 1 << 63, - 0x003a0012006b0003, - 1, - u64::from(geo.utile_config), - u.ppp_multisamplectl, - compact(p.pre_gva[0]), - compact(p.pre_gva[0]), - compact(p.pre_gva[1]), - compact(p.pre_gva[1]), - 1, - compact(p.pre_gva[2]) | 1 << 50, - 0, - compact(u.vdm_ctrl_stream_base) & !3, - compact(geo.layer_metadata), - compact(geo.layer_metadata), - 0, - 0, - 0, - 0, - 0, - 0, - 0x8860, - u64::from(geo.region_stride), - u64::from(geo.region_stride), - 0x88, - u64::from(2 | (u.ppp_ctrl & 0x201)), - u64::from(geo.pixels), - u64::from(geo.screen), - geo.x_blocks, - geo.y_blocks, - u64::from(geo.blocks), - u64::from(geo.tpc_stride), - 0x100, - u64::from(geo.layer_mode), - 0, - u64::MAX, - u64::MAX, - 0, - 0x1c, - 0, - rt.intersection[0], - rt.intersection[1], - rt.intersection[2], - rt.intersection[3], - rt.intersection[4], - rt.intersection[5], - rt.size, - rt.tail, - rt.stack, - rt.window, - u64::from(r.parameter_id), - compact(scene_list_va(r, p)), - compact(scene_list_va(r, p)), - scratch_word, - 0x6000400020, - 0x200000001, - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.uuid), - // USC base is a shared queue property carried by the render refs. - r.usc_base, - ]; - let count = stage_regs(&mut w[ta::REGS..], &ta::SEL, &val, rt.scs, 0); + let count = match layout.profile { + ta::RegProfile::G16G => { + let val: [u64; 66] = [ + 1, + 0x200, + compact(p.tilemap_gva), + compact(p.tilemap_gva), + compact(p.tpc_gva), + compact(p.heap_gva) | 1 << 63, + compact(p.heap_gva) | 1 << 63, + TA_TILER_CONFIG, + 1, + u64::from(geo.utile_config), + u.ppp_multisamplectl, + compact(p.pre_gva[0]), + compact(p.pre_gva[0]), + compact(p.pre_gva[1]), + compact(p.pre_gva[1]), + 1, + compact(p.pre_gva[2]) | 1 << 50, + 0, + compact(u.vdm_ctrl_stream_base) & !3, + compact(geo.layer_metadata), + compact(geo.layer_metadata), + 0, + 0, + 0, + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + u64::from(geo.region_stride), + u64::from(geo.region_stride), + 0x88, + u64::from(2 | (u.ppp_ctrl & 0x201)), + u64::from(geo.pixels), + u64::from(geo.screen), + geo.x_blocks, + geo.y_blocks, + u64::from(geo.blocks), + u64::from(geo.tpc_stride), + 0x100, + u64::from(geo.layer_mode), + 0, + u64::MAX, + u64::MAX, + 0, + STAGE_CTRL_DEFAULT, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + compact(scene_list_va(r, p)), + scratch_word, + G16G_RENDER_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + // USC base is a shared queue property carried by the render refs. + r.usc_base, + ]; + stage_regs(&mut w[ta::REGS..], &ta::SEL, &val, rt.scs, 0) + } + ta::RegProfile::G15S => { + let val: [u64; 74] = [ + 0x200, + compact(p.tilemap_gva), + compact(p.tilemap_gva), + 0, + 0, + compact(p.tpc_gva), + compact(p.heap_gva) | 1 << 63, + compact(p.heap_gva) | 1 << 63, + TA_TILER_CONFIG, + 1, + u64::from(geo.utile_config), + u.ppp_multisamplectl, + compact(p.pre_gva[0]), + compact(p.pre_gva[0]), + compact(p.pre_gva[1]), + compact(p.pre_gva[1]), + 1, + compact(p.pre_gva[2]) | 1 << 50, + 0, + compact(u.vdm_ctrl_stream_base) & !3, + 0, + 0, + 0, + 1, + 0, + compact(geo.layer_metadata), + compact(geo.layer_metadata), + 0, + 0, + 0, + 0, + 4 * u64::from(r.pb_init_blocks), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + u64::from(geo.region_stride), + u64::from(geo.region_stride), + 0x88, + u64::from(2 | (u.ppp_ctrl & 0x201)), + u64::from(geo.pixels), + u64::from(geo.screen), + geo.x_blocks, + geo.y_blocks, + u64::from(geo.blocks), + u64::from(geo.tpc_stride), + 0x100, + u64::from(geo.layer_mode), + STAGE_CTRL_DEFAULT, + STAGE_CTRL_DEFAULT, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + rt.window, + G15S_TA_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + compact(scene_list_va(r, p)), + scratch_word, + ]; + stage_regs(&mut w[ta::REGS..], &ta::SEL_G15S, &val, rt.scs, 0) + } + }; put64(w, 4, r.counter[0]); put32(w, 0xc, ctx); put64(w, 0x10, r.notifier); @@ -350,7 +448,7 @@ pub(crate) fn encode_ta_rt( put64(w, 0x740, p.ta_work_gva + 0x40); put16(w, 0x748, count); put16(w, 0x74a, count * 12); - put64(w, 0x760, p.tpc_fw); + put64(w, 0x760, if layout.tpc_is_gva { p.tpc_gva } else { p.tpc_fw }); put64(w, ta::TPC_BYTES, geo.tpc_bytes); put64(w, 0x770, p.ta_seq); put32(w, 0x778, ta::SEQ_SIZE as u32); @@ -380,7 +478,7 @@ pub(crate) fn encode_ta_rt( put32(q, 0x7c, r.uuid); put32(q, ta::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); // TA attachments are filled by render_attachments before publication. - inline_uma(q, 0x190, r, 0); + inline_uma(q, 0x190, r, 0, layout.inline_uma_engine_byte); timestamps( q, 0x1cc, @@ -406,7 +504,7 @@ pub(crate) fn encode_ta_rt( put64(q, f + 0x78, p.ta_seq + 0x190); put32(q, f + 0x80, 0u32.wrapping_sub(f as u32)); put64(q, f + 0x85, work + layout.completion as u64); - put8(q, f + 0x8d, 1); + put8(q, f + 0x8d, layout.finalize_flag); put32(q, f + 0x94, 0x40000002); } @@ -481,106 +579,208 @@ pub(crate) fn encode_fs_rt( ) { w.fill(0); q.fill(0); - let val: [u64; 82] = [ - 1, - u64::from(geo.utile_config), - prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), - prog_addr(usc, &u.eot), - prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), - prog_addr(usc, &u.bg), - u64::from(u.isp_merge_upper_x), - u64::from(u.isp_merge_upper_y), - 0, - 0, - 0, - 0, - u.ppp_multisamplectl, - u64::from(geo.isp_blocks), - u64::from(geo.isp_blocks), - u64::from(geo.screen), - 0, - rt.window | 1 << 9, - p.heap_gva & !63, - u.isp_scissor_base & !3, - u.isp_dbias_base & !3, - u64::from(geo.isp_control), - u64::from(u.height_px) << 32 | u64::from(u.width_px), - 0x100000, - u64::from(geo.tilebuffer_control), - u64::from(u.isp_zls_pixels), - u64::from(u.isp_bgobjdepth), - u64::from(u.isp_bgobjvals), - u.isp_oclqry_base & !15, - u.zls_ctrl, - 0x04040404, - 0, - u.depth.base, - u.depth.base, - u.stencil.base, - u.stencil.base, - 0, - 0, - 0, - 0, - u64::from(u.depth.stride), - u64::from(u.depth.stride), - u64::from(u.stencil.stride), - u64::from(u.stencil.stride), - u.depth.comp_base, - u64::from(u.depth.comp_stride), - u.depth.comp_base, - u64::from(u.depth.comp_stride), - u.stencil.comp_base, - u64::from(u.stencil.comp_stride), - u.stencil.comp_base, - u64::from(u.stencil.comp_stride), - p.tilemap_gva, - geo.layer_metadata, - u64::from(geo.region_stride) << 26, - u64::from(geo.tile_mode), - 0, - 0, - 0, - 0x8860, - p.aux_gva, - p.aux_gva, - 0x1c, - 0, - geo.native_tiles, - rt.intersection[0], - rt.intersection[1], - rt.intersection[2], - rt.intersection[3], - rt.intersection[4], - rt.intersection[5], - rt.size, - rt.tail, - rt.stack, - 0x6000400020, - 0x200000001, - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.uuid), - u64::from(r.parameter_id), - compact(scene_list_va(r, p)), - usc, - ]; - let count = stage_regs(&mut w[fs::REGS..], &fs::SEL, &val, rt.scs, 1); + let count = match layout.profile { + fs::RegProfile::G16G => { + let val: [u64; 82] = [ + 1, + u64::from(geo.utile_config), + prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), + prog_addr(usc, &u.eot), + prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), + prog_addr(usc, &u.bg), + u64::from(u.isp_merge_upper_x), + u64::from(u.isp_merge_upper_y), + 0, + 0, + 0, + 0, + u.ppp_multisamplectl, + u64::from(geo.isp_blocks), + u64::from(geo.isp_blocks), + u64::from(geo.screen), + 0, + rt.window | 1 << 9, + p.heap_gva & !63, + u.isp_scissor_base & !3, + u.isp_dbias_base & !3, + u64::from(geo.isp_control), + u64::from(u.height_px) << 32 | u64::from(u.width_px), + FS_ISP_CTRL_DEFAULT, + u64::from(geo.tilebuffer_control), + u64::from(u.isp_zls_pixels), + u64::from(u.isp_bgobjdepth), + u64::from(u.isp_bgobjvals), + u.isp_oclqry_base & !15, + u.zls_ctrl, + FS_ZLS_SAMPLE_MASK_DEFAULT, + 0, + u.depth.base, + u.depth.base, + u.stencil.base, + u.stencil.base, + 0, + 0, + 0, + 0, + u64::from(u.depth.stride), + u64::from(u.depth.stride), + u64::from(u.stencil.stride), + u64::from(u.stencil.stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + p.tilemap_gva, + geo.layer_metadata, + u64::from(geo.region_stride) << 26, + u64::from(geo.tile_mode), + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + p.aux_gva, + p.aux_gva, + STAGE_CTRL_DEFAULT, + 0, + geo.native_tiles, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + G16G_RENDER_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + usc, + ]; + stage_regs(&mut w[fs::REGS..], &fs::SEL, &val, rt.scs, 1) + } + fs::RegProfile::G15S => { + let val: [u64; 82] = [ + 1, + u64::from(geo.utile_config), + prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi), + prog_addr(usc, &u.eot), + prog_rsrc(u, &u.bg, u.bg_rsrc_spec_hi), + prog_addr(usc, &u.bg), + u64::from(u.isp_merge_upper_x), + u64::from(u.isp_merge_upper_y), + 0, + 0, + 0, + 0, + u.ppp_multisamplectl, + u64::from(geo.isp_blocks), + u64::from(geo.isp_blocks), + u64::from(geo.screen), + rt.window | 1 << 9, + p.heap_gva & !63, + u.isp_scissor_base & !3, + u.isp_dbias_base & !3, + u64::from(geo.isp_control), + u64::from(u.height_px) << 32 | u64::from(u.width_px), + FS_ISP_CTRL_DEFAULT, + u64::from(geo.tilebuffer_control), + u64::from(u.isp_zls_pixels), + u64::from(u.isp_bgobjdepth), + u64::from(u.isp_bgobjvals), + u.isp_oclqry_base & !15, + u.zls_ctrl, + FS_ZLS_SAMPLE_MASK_DEFAULT, + 0, + u.depth.base, + u.depth.base, + u.stencil.base, + u.stencil.base, + 0, + 0, + 0, + 0, + u64::from(u.depth.stride), + u64::from(u.depth.stride), + u64::from(u.stencil.stride), + u64::from(u.stencil.stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.depth.comp_base, + u64::from(u.depth.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + u.stencil.comp_base, + u64::from(u.stencil.comp_stride), + p.tilemap_gva, + geo.layer_metadata, + u64::from(geo.region_stride) << 26, + u64::from(geo.tile_mode), + 0, + 0, + 0, + RENDER_CACHE_CONFIG, + p.aux_gva, + p.aux_gva, + STAGE_CTRL_DEFAULT, + STAGE_CTRL_DEFAULT, + 0, + geo.native_tiles, + 0, + rt.intersection[0], + rt.intersection[1], + rt.intersection[2], + rt.intersection[3], + rt.intersection[4], + rt.intersection[5], + rt.size, + rt.tail, + rt.stack, + u64::from(r.parameter_id), + compact(scene_list_va(r, p)), + G15S_FS_UMA_PTC, + DEFAULT_DUPM_CONTROL, + u64::from(r.uuid), + u64::from(r.uuid), + u64::from(r.uuid), + ]; + stage_regs(&mut w[fs::REGS..], &fs::SEL_G15S, &val, rt.scs, 1) + } + }; put32(w, 0, 1); put64(w, 4, r.counter[1]); put32(w, 0xc, ctx); put64(w, 0x14, p.fs_seq); - put32(w, 0x1c, fs::SEQ_SIZE as u32); + put32(w, 0x1c, layout.seq_size as u32); put64(w, 0x20, r.notifier + 0x200); put64(w, 0x28, r.pb_mgr); put64(w, 0x30, p.scene); put64(w, 0x38, p.scene + 0x100); put64(w, 0x40, p.tilemap_gva); - put32(w, 0x50, 1); - put32(w, 0x54, geo.isp_blocks); - put32(w, 0x60, geo.x_blocks as u32); - put32(w, 0x64, geo.y_blocks as u32); - put32(w, 0x68, geo.blocks); + match layout.profile { + fs::RegProfile::G16G => { + put32(w, 0x50, 1); + put32(w, 0x54, geo.isp_blocks); + put32(w, 0x60, geo.x_blocks as u32); + put32(w, 0x64, geo.y_blocks as u32); + put32(w, 0x68, geo.blocks); + } + fs::RegProfile::G15S => { + put32(w, 0x48, 0x88); + put32(w, 0x50, 1); + put32(w, 0x54, geo.isp_blocks); + put32(w, 0x68, u.isp_merge_upper_x); + put32(w, 0x6c, u.isp_merge_upper_y); + } + } put32(w, 0x78, geo.tiles); put64(w, 0x780, p.fs_work_gva + 0x80); put16(w, 0x788, count); @@ -597,7 +797,7 @@ pub(crate) fn encode_fs_rt( ); put64(w, 0x930, prog_addr(usc, &u.partial_bg)); put64(w, 0x938, u.zls_ctrl); - put64(w, 0x940, 0x04040404); + put64(w, 0x940, FS_ZLS_SAMPLE_MASK_DEFAULT); put64(w, 0x948, u.depth.base); put64(w, 0x950, u64::from(u.depth.stride)); put64(w, 0x958, u64::from(u.depth.comp_stride)); @@ -617,7 +817,7 @@ pub(crate) fn encode_fs_rt( 0x9c8, u64::from(u.height_px) << 32 | u64::from(u.width_px), ); - put64(w, 0x9d0, 0x100000); + put64(w, 0x9d0, FS_ISP_CTRL_DEFAULT); put64(w, 0x9d8, u64::from(geo.tile_mode)); put64(w, 0x9f4, prog_rsrc(u, &u.eot, u.bg_eot_rsrc_spec_hi)); put64(w, 0x9fc, prog_addr(usc, &u.eot)); @@ -647,7 +847,7 @@ pub(crate) fn encode_fs_rt( put64(q, 0x1c, p.scene); put64(q, 0x24, r.activity[1]); put64(q, 0x2c, work + 0xb70); - put64(q, 0x34, p.scene + 0x54); + put64(q, 0x34, p.scene + layout.scene_field_off); put64(q, 0x3c, work + 0xbb0); put64(q, 0x44, work + 0xbb4); put64(q, 0x4c, r.qinfo[1]); @@ -659,10 +859,10 @@ pub(crate) fn encode_fs_rt( put64(q, 0x84, work + 0xbf0); put32(q, 0xa0, r.uuid); put32(q, fs::START_SCS, u32::from(RENDER_SCS_ENABLE && rt.scs)); - inline_uma(q, 0x1b0, r, 1); + inline_uma(q, 0x1b0, r, 1, layout.inline_uma_engine_byte); timestamps( q, - 0x1ec, + layout.ts_start, work, r.qinfo[1], ts_va[2] != 0 || ts_va[3] != 0, @@ -670,7 +870,7 @@ pub(crate) fn encode_fs_rt( 1, layout.auxiliary, ); - let f = 0x288; + let f = layout.finalize; put32(q, f, 8); put32(q, f + 4, r.uuid); put64(q, f + 0xc, r.fw_stamp[1]); @@ -689,15 +889,36 @@ pub(crate) fn encode_fs_rt( put64(q, f + 0x98, p.fs_seq + 0x1b0); put32(q, f + 0xa0, 0u32.wrapping_sub(f as u32)); put64(q, f + 0xa5, work + layout.completion as u64); - put32(q, f + 0xad, 1); - put8(q, f + 0xb1, 1); - put32(q, f + 0xb2, 0x71); - put32(q, f + 0xbc, 0x40000002); + if layout.compact_finalize { + put32(q, f + 0xad, 0x71); + put32(q, f + 0xb4, work::op::END); + } else { + put32(q, f + 0xad, 1); + put8(q, f + 0xb1, 1); + put32(q, f + 0xb2, 0x71); + put32(q, f + 0xbc, work::op::END); + } } /// Complete attachment blocks include the count at the last word. The scheduler /// has validated full retained ranges; alignment is for firmware cache lines. pub(crate) fn render_attachments(q: &mut [u8], engine: usize, att: &[uapi::drm_asahi_attachment]) { + let finalize = if engine == 0 { + ta::FINALIZE + } else { + fs::FINALIZE + }; + render_attachments_for(q, engine, finalize, att); +} + +/// [`render_attachments`] with an explicit finalize-record offset for ABIs whose FS +/// microsequence finalize offset differs from [`fs::FINALIZE`]. +pub(crate) fn render_attachments_for( + q: &mut [u8], + engine: usize, + finalize: usize, + att: &[uapi::drm_asahi_attachment], +) { let base = if engine == 0 { 0x88 } else { 0xa8 }; for (i, a) in att.iter().enumerate().take(16) { let start = a.pointer & !127; @@ -709,11 +930,7 @@ pub(crate) fn render_attachments(q: &mut [u8], engine: usize, att: &[uapi::drm_a put16(q, off + 0xe, 1); } put32(q, base + 0x100, att.len().min(16) as u32); - let f = if engine == 0 { - ta::FINALIZE + 0x84 - } else { - fs::FINALIZE + 0xa4 - }; + let f = finalize + if engine == 0 { 0x84 } else { 0xa4 }; put8(q, f, u8::from(!att.is_empty())); } diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 0c85e94fd77cd7..011e2ffa6f601b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2335,7 +2335,8 @@ impl Firmware { return Err(EAGAIN); } let e = job.resources.take_pb()?; - if let Err(err) = e.prepare_with_scs( + if let Err(err) = e.prepare_with_scs_for( + self.init.abi.pb_manager(), alloc_slot, job.resources.pb_heap_gva(alloc_slot)?, heap_blocks, @@ -2369,7 +2370,7 @@ impl Firmware { pb_mgr: a.pb_mgr, scene_list: 0, mgr_misc: a.mgr_misc, - pb_init_blocks: a.init_blocks, + pb_init_blocks: epoch.heap_blocks(), parameter_id: a.parameter_id, generation, activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], @@ -2413,7 +2414,7 @@ impl Firmware { pb_mgr: epoch.manager.va, scene_list: 0, mgr_misc: epoch.misc.va, - pb_init_blocks: a.init_blocks, + pb_init_blocks: epoch.heap_blocks(), parameter_id: a.parameter_id, generation: job.vm.generation, activity: [self.init.ta_activity.va + 4, self.init.fs_activity.va + 8], @@ -2767,7 +2768,8 @@ impl Firmware { } } Command::Render(r) => { - let geometry = Geometry::new(&r.cmd, 0); + let geometry = + Geometry::new_for(&r.cmd, 0, self.cfg.num_clusters, self.cfg.gpu_generation); let n = job.resources.render_passes()?; if (0..n).all(|k| { job.resources.render_pass(k).is_err_and(|_| true) @@ -2858,7 +2860,12 @@ impl Firmware { if ta_used >= sizes::QUEUE_CAP - 6 || fs_used >= sizes::QUEUE_CAP - 6 { break; } - let geo2 = Geometry::new(&r2.cmd, 0); + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); let Some(k2) = self.slots.pick_pass_in_for( &job.resources, &geo2, @@ -2994,7 +3001,12 @@ impl Firmware { precheck_ok = false; break; }; - let geo2 = Geometry::new(&r2.cmd, 0); + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); let Some(slot) = self.slots.pick_pass_in_for( &job.resources, &geo2, @@ -3060,7 +3072,12 @@ impl Firmware { let Some(Command::Render(r2)) = command(&j2, k) else { return Err(EINVAL); }; - let geo2 = Geometry::new(&r2.cmd, 0); + let geo2 = Geometry::new_for( + &r2.cmd, + 0, + self.cfg.num_clusters, + self.cfg.gpu_generation, + ); let slot = picked[k as usize]; let member = prefix.renders as usize; f.claims.pass[member] = slot as u32; @@ -3417,9 +3434,12 @@ impl Firmware { let fs2c_bar = if let Some(wait_fs) = wait_render { // Check producer InitBM explicitly in addition to the scheduler drain guard so // FS -> CDM handoff: downgrade to `BarrierType::Stamp` (type 0) only when neither - // the waited render nor any live flight carries `InitBM`; G16 FS `FINALIZE` flushes - // caches before advancing `fw_stamp[1]` (see `cross_engine_barrier_type`). - let producer_initbm = wait_fs.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + // the waited render nor any live flight carries `InitBM` and the GPU does not need + // G15's cross-engine hold; G16 FS `FINALIZE` flushes caches before advancing + // `fw_stamp[1]` (see `cross_engine_barrier_type`). + let producer_initbm = self.cfg.cross_engine_hold + || wait_fs.initbm + || self.engine.flights.iter().any(|fl| fl.initbm); let bar_type = cross_engine_barrier_type(producer_initbm, false); let bar = encode::barrier( self.graph.render.fw_stamp[1].va, @@ -3671,7 +3691,12 @@ impl Firmware { &mut scratch.fss[..], ); encode::render_attachments(&mut scratch.tas[..], 0, &cmd.vertex_attachments); - encode::render_attachments(&mut scratch.fss[..], 1, &cmd.fragment_attachments); + encode::render_attachments_for( + &mut scratch.fss[..], + 1, + self.init.abi.fs().finalize, + &cmd.fragment_attachments, + ); let full_work = self.slots.render_needs_full_work(k); if full_work { encode::fill_scene(&refs, &pass, &mut scratch.scene[..]); diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index e0a7b43b677bf3..4dc6483ffc5462 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -46,6 +46,66 @@ pub(crate) mod pb_manager { pub(crate) const COUNTER: usize = 0x64; pub(crate) const MAX_PAGES_A: usize = 0x7c; pub(crate) const MAX_PAGES_B: usize = 0x80; + + /// PB manager field offsets that differ between G16G (`0xc0`) and G15S 26B123 (`0x90`, + /// shifted `-4` bytes from `ID_A` onward). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct Layout { + pub(crate) id_a: usize, + pub(crate) id_b: usize, + pub(crate) page_list_fw: usize, + pub(crate) page_list: usize, + pub(crate) page_list_bytes: usize, + pub(crate) pages: usize, + pub(crate) k: usize, + pub(crate) blocks: usize, + pub(crate) block_list: usize, + pub(crate) block_ctl: usize, + pub(crate) last_page: usize, + pub(crate) block_bytes: usize, + pub(crate) counter: usize, + pub(crate) max_pages_a: usize, + pub(crate) max_pages_b: usize, + } + + pub(crate) const V25G83: Layout = Layout { + id_a: ID_A, + id_b: ID_B, + page_list_fw: PAGE_LIST_FW, + page_list: PAGE_LIST, + page_list_bytes: PAGE_LIST_BYTES, + pages: PAGES, + k: K, + blocks: BLOCKS, + block_list: BLOCK_LIST, + block_ctl: BLOCK_CTL, + last_page: LAST_PAGE, + block_bytes: BLOCK_BYTES, + counter: COUNTER, + max_pages_a: MAX_PAGES_A, + max_pages_b: MAX_PAGES_B, + }; + + /// G15S 26B123 PB manager (`0x90`-byte firmware record invalidated by TA and InitBM): + /// `id_a` at `+0x08`, `id_b` at `+0x0c`, `page_list_fw` at `+0x1c`, `blocks` at `+0x38`, + /// `block_ctl` at `+0x48`, `counter` at `+0x60`. + pub(crate) const V26B123_G15S: Layout = Layout { + id_a: 0x08, + id_b: 0x0c, + page_list_fw: 0x1c, + page_list: 0x24, + page_list_bytes: 0x2c, + pages: 0x30, + k: 0x34, + blocks: 0x38, + block_list: 0x40, + block_ctl: 0x48, + last_page: 0x50, + block_bytes: 0x54, + counter: 0x60, + max_pages_a: 0x78, + max_pages_b: 0x7c, + }; } pub(crate) mod uma_manager { pub(crate) const SIZE: usize = 0xa0; @@ -95,25 +155,49 @@ pub(crate) fn pb_manager_image( ring_fw: u64, count_fw: u64, heap_blocks: u32, +) -> [u8; pb_manager::SIZE] { + pb_manager_image_for( + &pb_manager::V25G83, + id, + pages_fw, + pages_gpu, + blocks_fw, + ring_fw, + count_fw, + heap_blocks, + ) +} + +/// Fresh PB manager encoded for `layout`'s firmware ABI, zero-padded to [`pb_manager::SIZE`]. +#[allow(clippy::too_many_arguments)] +pub(crate) fn pb_manager_image_for( + layout: &pb_manager::Layout, + id: u32, + pages_fw: u64, + pages_gpu: u64, + 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, pages); - put32(&mut m, 0x38, BLOCK_LIST_RECORDS); - put32(&mut m, 0x3c, blocks); - put64(&mut m, 0x44, blocks_fw); - put64(&mut m, 0x4c, ring_fw); - put32(&mut m, 0x54, pages - 1); - put32(&mut m, 0x58, BLOCK_BYTES as u32); - put64(&mut m, 0x64, count_fw); - put32(&mut m, 0x7c, pages); - put32(&mut m, 0x80, pages); + put32(&mut m, layout.id_a, id); + put32(&mut m, layout.id_b, id); + put64(&mut m, layout.page_list_fw, pages_fw); + put64(&mut m, layout.page_list, pages_gpu); + put32(&mut m, layout.page_list_bytes, PAGE_LIST_SIZE as u32); + put32(&mut m, layout.pages, pages); + put32(&mut m, layout.k, BLOCK_LIST_RECORDS); + put32(&mut m, layout.blocks, blocks); + put64(&mut m, layout.block_list, blocks_fw); + put64(&mut m, layout.block_ctl, ring_fw); + put32(&mut m, layout.last_page, pages - 1); + put32(&mut m, layout.block_bytes, BLOCK_BYTES as u32); + put64(&mut m, layout.counter, count_fw); + put32(&mut m, layout.max_pages_a, pages); + put32(&mut m, layout.max_pages_b, pages); m } diff --git a/drivers/gpu/drm/asahi/g16/fw/graph.rs b/drivers/gpu/drm/asahi/g16/fw/graph.rs index 80279283a4dab6..44e49e4e06fed1 100644 --- a/drivers/gpu/drm/asahi/g16/fw/graph.rs +++ b/drivers/gpu/drm/asahi/g16/fw/graph.rs @@ -38,6 +38,8 @@ pub(crate) mod qinfo { /// Firmware u32 busy flag: 1 from when the firmware takes a record until DONE (+0x20) /// reaches the head (+0x28). pub(crate) busy: usize, + /// Optional trailing `(offset, value)` u64 word in the firmware header. + pub(crate) tail_word: Option<(usize, u64)>, } pub(crate) const V25G83: Layout = Layout { @@ -47,6 +49,7 @@ pub(crate) mod qinfo { uuid: UUID, sched_ctx: SCHED_CTX, busy: 0x80, + tail_word: None, }; /// 26B123 queue-info header (0x80 bytes): class_c at 0x44, unk_4c at 0x48, uuid at 0x4c, @@ -58,6 +61,19 @@ pub(crate) mod qinfo { uuid: 0x4c, sched_ctx: 0x78, busy: 0x54, + tail_word: None, + }; + + /// G15S 26B123 queue-info header (0x88 bytes invalidated by the firmware): trailing u64 `4` + /// at `+0x80`, with queue scratch starting right after it at `+0x88`. + pub(crate) const V26B123_G15S: Layout = Layout { + header: 0x88, + class_c: 0x44, + unk_4c: 0x48, + uuid: 0x4c, + sched_ctx: 0x78, + busy: 0x54, + tail_word: Some((0x80, 4)), }; } @@ -206,6 +222,9 @@ pub(crate) fn queue_image_for( ] { q[at..at + 4].copy_from_slice(&value.to_le_bytes()); } + if let Some((at, value)) = layout.tail_word { + q[at..at + 8].copy_from_slice(&value.to_le_bytes()); + } q } diff --git a/drivers/gpu/drm/asahi/g16/fw/mod.rs b/drivers/gpu/drm/asahi/g16/fw/mod.rs index 12bd1e58a9e03b..e48096a54232c7 100644 --- a/drivers/gpu/drm/asahi/g16/fw/mod.rs +++ b/drivers/gpu/drm/asahi/g16/fw/mod.rs @@ -27,7 +27,15 @@ impl FwAbi { pub(crate) const fn devctl(self) -> &'static channels::devctl::Opcodes { match self { FwAbi::V25G83 => &channels::devctl::V25G83, - FwAbi::V26B123 => &channels::devctl::V26B123, + FwAbi::V26B123 | FwAbi::V26B123G15S => &channels::devctl::V26B123, + } + } + + /// The parameter-buffer manager layout. + pub(crate) const fn pb_manager(self) -> &'static buffer::pb_manager::Layout { + match self { + FwAbi::V25G83 | FwAbi::V26B123 => &buffer::pb_manager::V25G83, + FwAbi::V26B123G15S => &buffer::pb_manager::V26B123_G15S, } } @@ -36,6 +44,7 @@ impl FwAbi { match self { FwAbi::V25G83 => &graph::qinfo::V25G83, FwAbi::V26B123 => &graph::qinfo::V26B123, + FwAbi::V26B123G15S => &graph::qinfo::V26B123_G15S, } } @@ -44,6 +53,7 @@ impl FwAbi { match self { FwAbi::V25G83 => &work::ta::V25G83, FwAbi::V26B123 => &work::ta::V26B123, + FwAbi::V26B123G15S => &work::ta::V26B123_G15S, } } @@ -52,6 +62,7 @@ impl FwAbi { match self { FwAbi::V25G83 => &work::fs::V25G83, FwAbi::V26B123 => &work::fs::V26B123, + FwAbi::V26B123G15S => &work::fs::V26B123_G15S, } } @@ -60,6 +71,7 @@ impl FwAbi { match self { FwAbi::V25G83 => &work::compute::V25G83, FwAbi::V26B123 => &work::compute::V26B123, + FwAbi::V26B123G15S => &work::compute::V26B123_G15S, } } } diff --git a/drivers/gpu/drm/asahi/g16/fw/work.rs b/drivers/gpu/drm/asahi/g16/fw/work.rs index 5b1220b301e3fb..2b8c74edd3c556 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work.rs @@ -66,9 +66,9 @@ pub(crate) mod compute; pub(crate) mod ta { pub(crate) const WORK_SIZE: usize = 0x940; /// Active non-zero head (`0..HEAD_ACTIVE_SIZE`) and tail (`TAIL_ACTIVE_START..WORK_SIZE`) - /// spans of a TA work image (including two optional SCS register records). The intervening - /// zero gap is cleared on full scrubs and skipped on clean same-VM reuse. - pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x370; + /// spans of a TA work image (up to 74 G15S register records plus two optional SCS records). + /// The intervening zero gap is cleared on full scrubs and skipped on clean same-VM reuse. + pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x3e0; pub(crate) const TAIL_ACTIVE_START: usize = 0x740; pub(crate) const SEQ_SIZE: usize = 0x300; pub(crate) const SEQ_OBJECT: usize = 0x1000; @@ -86,6 +86,13 @@ pub(crate) mod ta { /// The binding generation. pub(crate) const GENERATION: usize = 0x917; + /// Hardware register list profile for TA work. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum RegProfile { + G16G, + G15S, + } + /// TA work fields that move between firmware ABIs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Layout { @@ -95,18 +102,45 @@ pub(crate) mod ta { pub(crate) completion: usize, /// Target of the timestamp records' +0x2c ("auxiliary") pointer. pub(crate) auxiliary: usize, + /// Register-list profile. + pub(crate) profile: RegProfile, + /// Whether TA `+0x760` carries the client TPC GVA (`true`, G15S) or firmware VA + /// (`false`, G16G). + pub(crate) tpc_is_gva: bool, + /// Whether the inline UMA record ends with the extra engine byte at `+0x34`. + pub(crate) inline_uma_engine_byte: bool, + /// Byte at TA finalize `+0x8d`. + pub(crate) finalize_flag: u8, } pub(crate) const V25G83: Layout = Layout { generation_bytes: 1, completion: 0x918, auxiliary: 0x928, + profile: RegProfile::G16G, + tpc_is_gva: false, + inline_uma_engine_byte: true, + finalize_flag: 1, }; pub(crate) const V26B123: Layout = Layout { generation_bytes: 8, completion: 0x91f, auxiliary: 0x92f, + profile: RegProfile::G16G, + tpc_is_gva: false, + inline_uma_engine_byte: true, + finalize_flag: 1, + }; + + pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0x91f, + auxiliary: 0x92f, + profile: RegProfile::G15S, + tpc_is_gva: true, + inline_uma_engine_byte: false, + finalize_flag: 0, }; const fn valid(l: &Layout) -> bool { @@ -114,8 +148,9 @@ pub(crate) mod ta { && l.auxiliary == l.completion + 0x10 && l.auxiliary + 8 <= WORK_SIZE } - const _: () = assert!(valid(&V25G83) && valid(&V26B123)); + const _: () = assert!(valid(&V25G83) && valid(&V26B123) && valid(&V26B123_G15S)); const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL_G15S.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 66] = [ @@ -127,6 +162,16 @@ pub(crate) mod ta { 0x1a0c9, 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799, 0x1c830, 0x1ca30, 0x16c39, 0x1c910, 0xa5a1, 0xd419, 0x1ca10, 0x14a1, 0xa349, 0x10061, ]; + pub(crate) const SEL_G15S: [u32; 74] = [ + 0x10141, 0x1c039, 0x1c9c8, 0x1c041, 0x1c9d0, 0x1c0a1, 0x1c031, 0x1c9c0, 0x1c051, 0x1c061, + 0x10149, 0x10139, 0x10111, 0x1c9b0, 0x10119, 0x1c9b8, 0x1c958, 0x1c950, 0x1c930, 0x1c880, + 0x1c898, 0x1c948, 0x1c888, 0x1c890, 0x1c918, 0x1c079, 0x1c9d8, 0x1c089, 0x1c9e0, 0x16c41, + 0x1ca40, 0x1c9a8, 0x1c920, 0x10151, 0x1c199, 0x1c1a1, 0x1c1a9, 0x1c1b1, 0x1c1b9, 0x1c8f8, + 0x1c0b1, 0x1c850, 0x10131, 0x10121, 0x10129, 0x101b9, 0x1c069, 0x1c071, 0x1c081, 0x1c0a9, + 0x10171, 0x10169, 0x12099, 0x101e1, 0x1c9e8, 0x1a099, 0x1a0a1, 0x1a069, 0x1a071, 0x1a0c9, + 0x1a0d1, 0x101c9, 0xd471, 0x1a0f1, 0x10799, 0xa5a1, 0xd419, 0x1ca10, 0x14a1, 0xa349, + 0x1c830, 0x1ca30, 0x16c39, 0x1c910, + ]; } /// FS work image and microsequence. @@ -151,6 +196,13 @@ pub(crate) mod fs { /// The binding generation. pub(crate) const GENERATION: usize = 0xc5f; + /// Hardware register list and work-header profile for FS work. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum RegProfile { + G16G, + G15S, + } + /// FS work fields that move between firmware ABIs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Layout { @@ -162,6 +214,21 @@ pub(crate) mod fs { pub(crate) auxiliary: usize, /// u8 flag the host sets to 1. pub(crate) flag: usize, + /// Register-list and header profile. + pub(crate) profile: RegProfile, + /// Microsequence length advertised in FS work `+0x1c`. + pub(crate) seq_size: usize, + /// Scene offset written to StartFS `+0x34`. + pub(crate) scene_field_off: u64, + /// Whether the inline UMA record ends with the extra engine byte at `+0x34`. + pub(crate) inline_uma_engine_byte: bool, + /// Start timestamp record offset in the FS microsequence. + pub(crate) ts_start: usize, + /// Finalize command offset in the FS microsequence. + pub(crate) finalize: usize, + /// Whether FS finalize packs the event directly at `+0xad` with `END` at `+0xb4` (G15S), + /// rather than G16G's `+0xad/+0xb1/+0xb2` + `END` at `+0xbc`. + pub(crate) compact_finalize: bool, } pub(crate) const V25G83: Layout = Layout { @@ -169,6 +236,13 @@ pub(crate) mod fs { completion: 0xc60, auxiliary: 0xc70, flag: 0xc84, + profile: RegProfile::G16G, + seq_size: SEQ_SIZE, + scene_field_off: 0x54, + inline_uma_engine_byte: true, + ts_start: TS_START, + finalize: FINALIZE, + compact_finalize: false, }; pub(crate) const V26B123: Layout = Layout { @@ -176,6 +250,27 @@ pub(crate) mod fs { completion: 0xc67, auxiliary: 0xc77, flag: 0xc8b, + profile: RegProfile::G16G, + seq_size: SEQ_SIZE, + scene_field_off: 0x54, + inline_uma_engine_byte: true, + ts_start: TS_START, + finalize: FINALIZE, + compact_finalize: false, + }; + + pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0xc67, + auxiliary: 0xc77, + flag: 0xc8b, + profile: RegProfile::G15S, + seq_size: 0x340, + scene_field_off: 0x4c, + inline_uma_engine_byte: false, + ts_start: 0x1e4, + finalize: 0x280, + compact_finalize: true, }; const fn valid(l: &Layout) -> bool { @@ -183,9 +278,12 @@ pub(crate) mod fs { && l.auxiliary == l.completion + 0x10 && l.flag == l.completion + 0x24 && l.flag < WORK_SIZE + && l.seq_size <= SEQ_SIZE + && l.finalize + if l.compact_finalize { 0xb8 } else { 0xc0 } <= l.seq_size } - const _: () = assert!(valid(&V25G83) && valid(&V26B123)); + const _: () = assert!(valid(&V25G83) && valid(&V26B123) && valid(&V26B123_G15S)); const _: () = assert!(REGS + (SEL.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); + const _: () = assert!(REGS + (SEL_G15S.len() + 2) * super::REG_RECORD <= HEAD_ACTIVE_SIZE); const _: () = assert!(HEAD_ACTIVE_SIZE <= TAIL_ACTIVE_START); const _: () = assert!(TAIL_ACTIVE_START <= WORK_SIZE); pub(crate) const SEL: [u32; 82] = [ @@ -199,6 +297,17 @@ pub(crate) mod fs { 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0xa5a9, 0xd429, 0x160e0, 0x1499, 0xa341, 0x1c838, 0x1ca28, 0x10069, ]; + pub(crate) const SEL_G15S: [u32; 82] = [ + 0x1739, 0x10009, 0x15379, 0x15381, 0x15369, 0x15371, 0x15131, 0x15139, 0x100a1, 0x15069, + 0x15071, 0x16058, 0x10019, 0x100b1, 0x16030, 0x100d9, 0x10791, 0x16098, 0x15109, 0x15101, + 0x15021, 0x15211, 0x15049, 0x10051, 0x15321, 0x15301, 0x15309, 0x15311, 0x15319, 0x15349, + 0x15351, 0x15329, 0x15331, 0x15339, 0x15341, 0x15231, 0x15221, 0x15239, 0x15229, 0x15401, + 0x15421, 0x15409, 0x15429, 0x153c1, 0x15411, 0x153c9, 0x15431, 0x153d1, 0x15419, 0x153d9, + 0x15439, 0x16429, 0x16060, 0x16431, 0x10039, 0x16020, 0x16451, 0x15359, 0x100b8, 0x16461, + 0x16090, 0x120a1, 0x101e9, 0x160a8, 0x16068, 0x160b8, 0x1a0a9, 0x1a0b1, 0x1a079, 0x1a081, + 0x1a0d9, 0x1a0e1, 0x101c1, 0xd469, 0x1a0f9, 0x1c838, 0x1ca28, 0xa5a9, 0xd429, 0x160e0, + 0x1499, 0xa341, + ]; pub(crate) const MAX_END_COPIES: usize = 8; pub(crate) const SEQ_CAPACITY: usize = SEQ_SIZE + MAX_END_COPIES * super::ts_record::SIZE; } diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index 85daf5876aec3b..6d242aae721fcb 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -3,10 +3,11 @@ //! 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 28 register -/// records (`0x20..0x170`, including USC base and RT/SCS records), 16-byte aligned. Bytes -/// between `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full write. -pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x170; +/// Active head span of a compute work image: header (`0x00..0x18`) plus up to 29 register +/// records (`0x20..0x17c`, including optional 0x12091, USC base and RT/SCS records), 16-byte +/// aligned. Bytes between `HEAD_ACTIVE_SIZE` and `BODY_ACTIVE_START` remain zeroed after a full +/// write. +pub(crate) const HEAD_ACTIVE_SIZE: usize = 0x180; /// 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). @@ -63,6 +64,17 @@ pub(crate) struct Layout { /// 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)>, + /// Offset of the four preemption saved-state pointers (`0x1a4d0..0x1a4e8`) in the + /// preemption buffer. + pub(crate) preempt_tail: u64, + /// Whether to emit G15 register `0x12091 = 0x1c` immediately before `0x101d9`. + pub(crate) has_reg_12091: bool, + /// Whether to emit HAL200 USC-base register `0x10071`. + pub(crate) has_usc_base_reg: bool, + /// Four sub-offsets inside `context_store_gva` written at `StartCompute +0x188..+0x1a0`. + pub(crate) context_store_offsets: [u64; 4], + /// Pool threshold words written at compute work `+0x873` and `+0x87b`. + pub(crate) pool_words: [u64; 2], } pub(crate) const V25G83: Layout = Layout { @@ -72,6 +84,11 @@ pub(crate) const V25G83: Layout = Layout { target: 0x8ac, cached: 0x8c0, work_ticks: None, + preempt_tail: 0x1480, + has_reg_12091: false, + has_usc_base_reg: true, + context_store_offsets: [0, 0xf400, 0x1e800, 0x1f000], + pool_words: [0x1588000, 0xef8000], }; pub(crate) const V26B123: Layout = Layout { @@ -81,6 +98,25 @@ pub(crate) const V26B123: Layout = Layout { target: 0x8b3, cached: 0x8e0, work_ticks: Some((0x7ec, 0x7f4)), + preempt_tail: 0x1480, + has_reg_12091: false, + has_usc_base_reg: true, + context_store_offsets: [0, 0xf400, 0x1e800, 0x1f000], + pool_words: [0x1588000, 0xef8000], +}; + +pub(crate) const V26B123_G15S: Layout = Layout { + generation_bytes: 8, + completion: 0x893, + auxiliary: 0x8a3, + target: 0x8b3, + cached: 0x8e0, + work_ticks: Some((0x7ec, 0x7f4)), + preempt_tail: 0x1b80, + has_reg_12091: true, + has_usc_base_reg: false, + context_store_offsets: [0, 0x1e400, 0x3c800, 0x3d800], + pool_words: [0x31cc000, 0x2308000], }; const fn valid(l: &Layout) -> bool { @@ -90,11 +126,14 @@ const fn valid(l: &Layout) -> bool { && l.target + 4 <= l.cached && l.cached <= SEQ_EMBEDDED && SEQ_EMBEDDED + SEQ_SIZE <= NOTIFIER + && l.preempt_tail + 0x20 <= PREEMPT_SIZE as u64 + && l.context_store_offsets[3] + 0x1000 <= CONTEXT_STORE_SIZE as u64 } const _: () = assert!( valid(&V25G83) && valid(&V26B123) - && REGS + (SEL.len() + 4) * 12 <= HEAD_ACTIVE_SIZE + && valid(&V26B123_G15S) + && REGS + (SEL.len() + 5) * 12 <= HEAD_ACTIVE_SIZE && HEAD_ACTIVE_SIZE <= BODY_ACTIVE_START && BODY_ACTIVE_START <= GENERATION && DESCRIPTOR + DESCRIPTOR_SIZE <= BODY_ACTIVE_END diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index a6bccc51abb1d8..908297e82e417d 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -63,6 +63,8 @@ pub(crate) struct Config { pub(crate) host_block_ready: bool, /// Whether the TVM gate and firmware warm restart are supported. pub(crate) deep_sleep: bool, + /// Whether FS->compute cross-engine barriers require `BarrierType::Hold` (type 1), as on G15. + pub(crate) cross_engine_hold: bool, } impl Config { @@ -189,6 +191,7 @@ pub(crate) mod t8132 { host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, host_block_ready: true, deep_sleep: true, + cross_engine_hold: false, }; /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: @@ -340,6 +343,7 @@ pub(crate) mod t6030 { host_block_zero_order: &[0, 0x1808, 0x3010], host_block_ready: false, deep_sleep: false, + cross_engine_hold: true, }; const LAYOUT: FwLayout = FwLayout { @@ -347,11 +351,13 @@ pub(crate) mod t6030 { segment_vas: &[UPPER, UPPER + 0x60000, UPPER + 0x18c000], text_size: 0x60000, data_size: 0x134000, + abi: super::FwAbi::V26B123G15S, initdata: &initdata::G15S_26B123, scratch: Scratch { register: HOST_BLOCK, - // The G15S scratch window has an unmapped page at +0x14000. - spans: &[(0, 0x14000), (0x18000, 0x8000)], + // The G15S scratch window leaves an unmapped guard page at VA +0x14000 while the + // physical host-register window stays contiguous across the split (+0x14000..+0x20000). + spans: &[(0, 0, 0x14000), (0x18000, 0x14000, 0xc000)], pointer: 0x12068, }, // Offset on the PPL handoff page where the G15S 26B123 firmware records @@ -434,6 +440,7 @@ pub(crate) struct Leaves { pub(crate) enum FwAbi { V25G83, V26B123, + V26B123G15S, } /// How the firmware's MMIO register table in loaded DATA is filled. @@ -508,13 +515,14 @@ pub(crate) struct PplMagic { /// Firmware-visible alias of host registers, with the pointer InitData passes into it. pub(crate) struct Scratch { pub(crate) register: u64, - pub(crate) spans: &'static [(u64, u64)], + /// `(va_offset, pa_offset, bytes)` spans in ascending VA order. + pub(crate) spans: &'static [(u64, u64, u64)], pub(crate) pointer: u64, } const T8132_SCRATCH: Scratch = Scratch { register: HOST_BLOCK, - spans: &[(0, 0x8000)], + spans: &[(0, 0, 0x8000)], pointer: 0, }; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index b6338605815adb..27555241f40cef 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -271,14 +271,14 @@ pub(crate) fn build( } } let scratch = &adt.layout.scratch; - let &(last, bytes) = scratch.spans.last().ok_or(EINVAL)?; + let &(last, _, bytes) = scratch.spans.last().ok_or(EINVAL)?; let at = objects.reserve_io(last + bytes)?; input.scratch = at + scratch.pointer; // The scratch alias uses firmware RAM attributes on these SGX registers. - for &(offset, bytes) in scratch.spans { + for &(va_offset, pa_offset, bytes) in scratch.spans { objects.map_mmio_class( - at + offset, - regs.sgx_pa() + scratch.register + offset, + at + va_offset, + regs.sgx_pa() + scratch.register + pa_offset, bytes, hw::pte::FW, )?; diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 78db8e48c8a53c..f6535d0e52157d 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -94,9 +94,13 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res | 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_COMPUTE_NO_QUERY_ACCESS) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY) - | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) + | if gpu.cfg.gpu_generation >= 16 { + u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FEW_PRIMITIVES) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_RAY_QUERY) + | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD) + } else { + 0 + } | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = gpu.cfg.gpu_generation; diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index e84b06a9ba88c4..0af1660bf25791 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -1255,12 +1255,26 @@ impl PbEpoch { /// Like [`Self::prepare`], recording whether this epoch is bound to the VM's SCS-capable /// render allocators (`scs == true`) or its base allocators (`scs == false`). + #[allow(dead_code)] pub(crate) fn prepare_with_scs( &self, k: usize, heap: u64, heap_blocks: u32, scs: bool, + ) -> Result { + self.prepare_with_scs_for(&buffer::pb_manager::V25G83, k, heap, heap_blocks, scs) + } + + /// Like [`Self::prepare_with_scs`], encoding the PB manager with `layout` for the active + /// firmware ABI. + pub(crate) fn prepare_with_scs_for( + &self, + layout: &buffer::pb_manager::Layout, + k: usize, + heap: u64, + heap_blocks: u32, + scs: bool, ) -> Result { if k >= sizes::PB_SLOTS || self.exposed.load(Ordering::Acquire) @@ -1290,7 +1304,8 @@ impl PbEpoch { self.counter.w64(0, 1)?; self.manager.write( 0, - &buffer::pb_manager_image( + &buffer::pb_manager_image_for( + layout, k as u32, self.pages.va, gva(&self.pages)?, diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 28332f8de5e740..54d2503b965ed5 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -179,6 +179,9 @@ pub(crate) struct Queue { timeline: Arc, /// Enabled GPU cores, which SCS memory is sized for. active_cores: u32, + /// Cluster count and GPU generation for stream admission. + num_clusters: u32, + gpu_generation: u32, /// Reserved render scratch pages per stage (`render_scs_layout`). render_scs: [u16; 2], // Last field: all preceding fields (especially scheduler) drop before capacity returns. @@ -243,6 +246,8 @@ impl Queue { shared: gpu.shared.clone(), timeline, active_cores: gpu.id.core_masks.iter().map(|mask| mask.count_ones()).sum(), + num_clusters: gpu.cfg.num_clusters, + gpu_generation: gpu.cfg.gpu_generation, render_scs: [0; 2], _credit: credit, }) @@ -260,7 +265,16 @@ impl Queue { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } - let parsed = command::parse_stream(bytes, params::early_tiling())?; + let parsed = if self.gpu_generation < 16 { + command::parse_stream_for( + bytes, + params::early_tiling(), + self.num_clusters, + self.gpu_generation, + )? + } else { + command::parse_stream(bytes, params::early_tiling())? + }; if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } @@ -356,6 +370,9 @@ impl crate::queue::Queue for Queue { /// A render's UMA pool serves both stages of one render at a time, so their extra pages add /// up ([`super::rt::required_seeds`]). fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { + if self.gpu_generation < 16 { + return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); + } if self.accepted != [0; 2] { return Err(EBUSY); } 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 7a235103bb9909..aacb13fc69b2a3 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 @@ -301,6 +301,140 @@ fn queues(out: &std::path::Path) { std::fs::write(out.join("queue.bin"), all).unwrap(); } +fn g15s_26b123() { + let f = 0xfffffc2000000000u64; + let g = 0x1000000000u64; + // PB manager: G15S 26B123 shifts every field -4 bytes vs G16G. + let pb = fw::buffer::pb_manager_image_for( + FwAbi::V26B123G15S.pb_manager(), + 3, + f + 0x400000, + g + 0x701a040000, + f + 0x500000, + f + 0x600000, + f + 0x700000, + 512, + ); + assert_eq!((r32(&pb, 0x08), r32(&pb, 0x0c)), (3, 3)); + assert_eq!(r64(&pb, 0x1c), f + 0x400000); + assert_eq!(r64(&pb, 0x24), g + 0x701a040000); + assert_eq!( + (r32(&pb, 0x2c), r32(&pb, 0x30), r32(&pb, 0x34), r32(&pb, 0x38)), + (0x8000, 2048, 4096, 512) + ); + assert_eq!((r64(&pb, 0x40), r64(&pb, 0x48)), (f + 0x500000, f + 0x600000)); + assert_eq!((r32(&pb, 0x50), r32(&pb, 0x54)), (2047, 0x20000)); + assert_eq!(r64(&pb, 0x60), f + 0x700000); + assert_eq!((r32(&pb, 0x78), r32(&pb, 0x7c)), (2048, 2048)); + + // QINFO: G15S 26B123 has 0x88 header with trailing u64 4 at +0x80. + let qi = fw::graph::queue_image_for( + FwAbi::V26B123G15S.qinfo(), + f + 0x100000, f + 0x200000, f + 0x400000, f + 0x300000, f + 0x500000, + ); + assert_eq!(r64(&qi, 0x18), f + 0x300088); + assert_eq!(r64(&qi, 0x78), f + 0x500000); + assert_eq!(r64(&qi, 0x80), 4); + + // 2-cluster G15S render geometry, 74-reg TA, 82-reg FS, and 0x340 FS microsequence. + let mut u = uapi::drm_asahi_cmd_render::default(); + u.width_px = 640; u.height_px = 480; u.layers = 1; u.samples = 1; + u.utile_width_px = 32; u.utile_height_px = 32; u.sample_size_B = 4; + u.vdm_ctrl_stream_base = g + 0xa00000; + u.isp_merge_upper_x = 0x3b213cfb; + u.isp_merge_upper_y = 0x3ba13cfb; + 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, + pb_init_blocks: 512, parameter_id: 6, 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 geo1 = encode::Geometry::new(&u, p.heap_gva); + let geo2 = encode::Geometry::new_for(&u, p.heap_gva, 2, 15); + assert_eq!(geo2.tpc_bytes, 2 * geo1.tpc_bytes); + assert_eq!(geo2.native_tiles & 0xfffff, 0x36011); + let (mut tw, mut tq) = ([0xa5; ta::WORK_SIZE], [0xa5; ta::SEQ_SIZE]); + let (mut fw_, mut fq) = ([0xa5; fs::WORK_SIZE], [0xa5; fs::SEQ_SIZE]); + encode::encode_ta_for( + FwAbi::V26B123G15S.ta(), &r, &p, &u, &[0; 4], 7, 0x300, &geo2, None, &mut tw, &mut tq, + ); + encode::encode_fs_for( + FwAbi::V26B123G15S.fs(), &r, &p, &u, &[0; 4], 7, 1 << 40, 1, 0x300, &geo2, &mut fw_, + &mut fq, + ); + let att = [uapi::drm_asahi_attachment { + pointer: g + 0x50000000, size: 128, ..Default::default() + }]; + encode::render_attachments_for(&mut fq[..], 1, FwAbi::V26B123G15S.fs().finalize, &att); + assert_eq!(u16::from_le_bytes(tw[0x748..0x74a].try_into().unwrap()), 74); + assert_eq!(r64(&tw, 0x760), p.tpc_gva); + assert_eq!(r32(&tw, ta::REGS + 52 * 12), 0x12099); + assert_eq!(r32(&tw, ta::REGS + 65 * 12), 0xa5a1); + assert_eq!(r64(&tw, ta::REGS + 65 * 12 + 4), 0x7f00400020); + assert_eq!(tq[ta::FINALIZE + 0x8d], 0); + assert_eq!(u16::from_le_bytes(fw_[0x788..0x78a].try_into().unwrap()), 82); + assert_eq!(r32(&fw_, 0x1c), 0x340); + assert_eq!( + (r32(&fw_, 0x48), r32(&fw_, 0x68), r32(&fw_, 0x6c)), + (0x88, u.isp_merge_upper_x, u.isp_merge_upper_y) + ); + assert_eq!(r32(&fw_, fs::REGS + 61 * 12), 0x120a1); + assert_eq!(r32(&fw_, fs::REGS + 77 * 12), 0xa5a9); + assert_eq!(r64(&fw_, fs::REGS + 77 * 12 + 4), 0x9f00400020); + assert_eq!(r64(&fq, 0x34), p.scene + 0x4c); + assert_eq!((r32(&fq, 0x1e4), r32(&fq, 0x230), r32(&fq, 0x234)), (0x80000003, 1, 3)); + assert_eq!(r32(&fq, 0x280), 8); + assert_eq!(fq[0x280 + 0xa4], 1); + assert_eq!(r64(&fq, 0x280 + 0xa5), p.fs_work + 0xc67); + assert_eq!((r32(&fq, 0x280 + 0xad), r32(&fq, 0x280 + 0xb4)), (0x71, 0x40000002)); + + // G15S 26B123 compute: 25 regs (+0x12091, no 0x10071), pre+0x1b80, 2-cluster context store. + let cr = 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, event: compute::EVENT, + }; + let cc = uapi::drm_asahi_cmd_compute { + cdm_ctrl_stream_base: g + 0x300000, cdm_ctrl_stream_end: g + 0x300200, + ..Default::default() + }; + let (mut cw, mut cq) = ([0xa5; compute::WORK_SIZE], [0xa5; compute::SEQ_SIZE]); + encode::encode_compute_for( + FwAbi::V26B123G15S.compute(), &cr, &cc, &[], &[0; 2], 1, 1, 1, &mut cw, &mut cq, + ).unwrap(); + assert_eq!(u16::from_le_bytes(cw[0x728..0x72a].try_into().unwrap()), 25); + assert_eq!(r64(&cw, compute::REGS + 2 * 12 + 4), cr.preempt_gva + 0x1b80); + assert_eq!(r32(&cw, compute::REGS + 8 * 12), 0x12091); + assert_eq!(r32(&cw, compute::REGS + 9 * 12), 0x101d9); + assert_eq!(r32(&cw, compute::REGS + 24 * 12), 0xa351); + assert_eq!((r64(&cw, 0x873), r64(&cw, 0x87b)), (0x31cc000, 0x2308000)); + assert_eq!( + (r64(&cq, 0x188), r64(&cq, 0x190), r64(&cq, 0x198), r64(&cq, 0x1a0)), + ( + cr.context_store_gva, + cr.context_store_gva + 0x1e400, + cr.context_store_gva + 0x3c800, + cr.context_store_gva + 0x3d800, + ) + ); +} + fn catalog() { // Handoff selection and what a 26B123 start still needs. assert!(FW_25G83.matches(1, &[UPPER, UPPER + 0x60000], &[1, 0])); @@ -451,5 +585,6 @@ fn main() { render(&out); compute_work(&out); queues(&out); + g15s_26b123(); 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()); } From 4ed0da96b08c9d9a604d7d6c2cd8dfdf1d5b544c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Wed, 25 Nov 2026 15:28:33 +1100 Subject: [PATCH 1252/1514] ci: stage the release kernel, modules and DTBs from the Arch package make pacman-pkg rebuilds and relinks the kernel (the build number goes from #1 to #2), so the standalone Image.gz and modules tarball were not the binaries in the Arch package, and the QEMU smoke run booted the former. When the Arch packages build, take Image.gz (decoded from the package's EFI zboot vmlinuz), the modules tree (with depmod run against the package's System.map), the DTBs, the config and System.map from the runtime and headers packages, so every asset and the smoke run use the binaries that ship. Without makepkg the previous direct path stays. Checked against the Arch packages of run 45429366862: the staged Image equals the zstd payload of the package's vmlinuz byte for byte; 5915 modules with modules.dep; 1629 DTBs. Signed-off-by: Ryan Murray --- .github/scripts/kernel-release-build.sh | 56 +++++++++++++------- .github/scripts/kernel-release-stage-arch.sh | 45 ++++++++++++++++ .github/workflows/kernel-release.yml | 1 + 3 files changed, 82 insertions(+), 20 deletions(-) create mode 100755 .github/scripts/kernel-release-stage-arch.sh diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh index 9d260a8e8d6aa7..c5798a5af9b144 100755 --- a/.github/scripts/kernel-release-build.sh +++ b/.github/scripts/kernel-release-build.sh @@ -77,32 +77,22 @@ echo "::group::build" mk Image.gz modules dtbs echo "::endgroup::" -KREL=$(cat "$O/include/config/kernel.release") -M=$O/modroot -rm -rf "$M" -mk INSTALL_MOD_PATH="$M" INSTALL_MOD_STRIP=1 modules_install -rm -f "$M/lib/modules/$KREL/build" "$M/lib/modules/$KREL/source" - -TAR=(tar --sort=name --mtime="$KBUILD_BUILD_TIMESTAMP" --owner=0 --group=0 --numeric-owner) -cp "$O/arch/arm64/boot/Image.gz" "$D/Image-$KREL.gz" -cp "$O/.config" "$D/config-$KREL" -cp "$O/System.map" "$D/System.map-$KREL" -"${TAR[@]}" --zstd -C "$M" -cf "$D/modules-$KREL.tar.zst" "lib/modules/$KREL" -"${TAR[@]}" --zstd -C "$O/arch/arm64/boot/dts" -cf "$D/dtbs-$KREL.tar.zst" \ - $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | sort) -cp "$O/certs/signing_key.x509" "$D/module-signing-cert-$KREL.der" -git -C "$S" rev-parse HEAD > "$D/source.commit" -echo "$KREL" > "$D/kernel.release" -echo "modules: $(find "$M/lib/modules/$KREL" -name '*.ko*' | wc -l)" -echo "dtbs: $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | wc -l)" - +ARCH_RUNTIME= echo "::group::pacman-pkg" if command -v makepkg >/dev/null; then rm -f "$O"/*.pkg.tar.* # Debian/Ubuntu's makepkg.conf defaults to .pkg.tar.gz. if PKGEXT=.pkg.tar.zst mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ MAKEPKGOPTS="--nodeps --noconfirm" pacman-pkg; then - cp "$O"/*.pkg.tar.zst "$D/" + runtimes=("$O"/"$PKGBASE"-[0-9]*.pkg.tar.zst) + headers=("$O"/"$PKGBASE"-headers-[0-9]*.pkg.tar.zst) + if [[ ${#runtimes[@]} -ne 1 || ! -f ${runtimes[0]} || + ${#headers[@]} -ne 1 || ! -f ${headers[0]} ]]; then + echo "::error::expected one Arch runtime and one headers package"; exit 1 + fi + ARCH_RUNTIME=${runtimes[0]} + ARCH_HEADERS=${headers[0]} + cp "$ARCH_RUNTIME" "$ARCH_HEADERS" "$D/" else echo "::warning::make pacman-pkg failed; release ships without the Arch package" fi @@ -111,6 +101,32 @@ else fi echo "::endgroup::" +KREL=$(cat "$O/include/config/kernel.release") +if [[ -n $ARCH_RUNTIME ]]; then + member="usr/lib/modules/$KREL/build" + tar --zstd -xOf "$ARCH_HEADERS" "$member/.config" > "$D/config-$KREL" + tar --zstd -xOf "$ARCH_HEADERS" "$member/System.map" > "$D/System.map-$KREL" + bash "$S/.github/scripts/kernel-release-stage-arch.sh" \ + "$ARCH_RUNTIME" "$KREL" "$D/System.map-$KREL" "$D" +else + M=$O/modroot + rm -rf "$M" + mk INSTALL_MOD_PATH="$M" INSTALL_MOD_STRIP=1 modules_install + rm -f "$M/lib/modules/$KREL/build" "$M/lib/modules/$KREL/source" + + TAR=(tar --sort=name --mtime="$KBUILD_BUILD_TIMESTAMP" --owner=0 --group=0 --numeric-owner) + cp "$O/arch/arm64/boot/Image.gz" "$D/Image-$KREL.gz" + cp "$O/.config" "$D/config-$KREL" + cp "$O/System.map" "$D/System.map-$KREL" + "${TAR[@]}" --zstd -C "$M" -cf "$D/modules-$KREL.tar.zst" "lib/modules/$KREL" + "${TAR[@]}" --zstd -C "$O/arch/arm64/boot/dts" -cf "$D/dtbs-$KREL.tar.zst" \ + $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | sort) +fi +cp "$O/certs/signing_key.x509" "$D/module-signing-cert-$KREL.der" +git -C "$S" rev-parse HEAD > "$D/source.commit" +echo "$KREL" > "$D/kernel.release" +echo "dtbs: $(cd "$O/arch/arm64/boot/dts" && find . -name '*.dtb' | wc -l)" + # The private signing key stays on the builder for this run only. rm -f "$O/certs/signing_key.pem" for f in "$D"/*.tar.* ; do diff --git a/.github/scripts/kernel-release-stage-arch.sh b/.github/scripts/kernel-release-stage-arch.sh new file mode 100755 index 00000000000000..c64836bf28bb1f --- /dev/null +++ b/.github/scripts/kernel-release-stage-arch.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0-only +# Stage standalone release artifacts from the Arch runtime package. + +set -euo pipefail + +package=$(realpath "$1") +release=$2 +system_map=$(realpath "$3") +output=$(realpath "$4") +stage=$(mktemp -d "$output/.arch-runtime.XXXXXX") +trap 'rm -rf -- "$stage"' EXIT + +member="usr/lib/modules/$release" +tar --no-same-owner --zstd -xf "$package" -C "$stage" "$member" +mkdir -p "$stage/lib/modules" +mv "$stage/$member" "$stage/lib/modules/" +runtime="$stage/lib/modules/$release" +mv "$runtime/dtb" "$stage/dtb" +python3 - "$runtime/vmlinuz" <<'PY' | gzip -n > "$output/Image-$release.gz" +import gzip +from pathlib import Path +import struct +import subprocess +import sys + +image = Path(sys.argv[1]).read_bytes() +if image.startswith(b"\x1f\x8b"): + image = gzip.decompress(image) +elif image[:2] == b"MZ" and image[4:8] == b"zimg": + offset, length = struct.unpack_from(" Date: Fri, 20 Nov 2026 19:25:09 -0600 Subject: [PATCH 1253/1514] wifi: apple: centauri: restart a stopped N1 firmware without a reboot On J813 the N1 firmware can stop while the machine is awake. A background scan sees the Alpha execution stage leave 2 and ends with -EIO, and every later command finds the command ring full. Nothing brought Wi-Fi back short of a reboot: PERST# alone, through the existing port cycle, leaves the firmware running. Restart the chip from the driver: - Release btcentauri and free the firmware's buffers. - Remove functions 1 and 2. The reset returns the chip to its single-function ROM personality, and a read through a stale function's BAR afterwards hangs the fabric. - Cycle the port with the N1's warm reset, given while the port is down. The chip comes back in stage 0. - Run the probe's boot steps, then attach the Beta function again. The warm reset comes from the root port's DT node, with the properties and parsing the T6050 boards already use (bindings/pci/apple,pcie.yaml): apple,function-warm-reset names the SMC and the key (the ADT's pci-bridge0 function-warm_reset), apple,warm-reset-writes the writes. A board restarts only when its root port has both and its port cycle is known; without them the driver never resets the chip. J813 gets them: key 'bpli', the same key and argument as the T6050 boards, with the T6050 writes. The Wi-Fi code reports the signs where it already sees them: the scan loop's and command_control()'s stage checks, a full command ring and a command timeout. A report queues a check 2 s later on an ordered, freezable workqueue, which restarts the chip only if the firmware is still stopped and the transport is not paused for a system sleep. At most three restarts in 30 minutes. There is no runtime switch; a board without the DT properties doesn't restart. debugfs rom_boot 4 restarts by hand, 5 and 6 test the fault path as a stopped firmware and as a fault that clears. The status file now reads under boot_lock, so no BAR read lands in a restart's port cycle. The driver now depends on MFD_MACSMC. Known limit, shared with the debugfs boot steps: removing function 0 under the PCI rescan lock (sysfs remove, host unbind) while a restart runs deadlocks. Signed-off-by: Kyle Arrington Signed-off-by: Nick --- .../bindings/net/wireless/apple,centauri.yaml | 5 + arch/arm64/boot/dts/apple/t8142-j813.dts | 7 + drivers/net/wireless/apple/Kconfig | 1 + .../net/wireless/apple/centauri/centauri.h | 15 +- .../wireless/apple/centauri/centauri_ipc.c | 8 +- .../wireless/apple/centauri/centauri_pci.c | 167 +++++++++++++++++- .../wireless/apple/centauri/centauri_port.c | 100 ++++++++++- .../wireless/apple/centauri/centauri_wifi.c | 26 ++- 8 files changed, 320 insertions(+), 9 deletions(-) diff --git a/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml b/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml index 8d226eec130917..7f064886f055f2 100644 --- a/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml +++ b/Documentation/devicetree/bindings/net/wireless/apple,centauri.yaml @@ -24,6 +24,11 @@ description: | native driver selects personalized firmware and transport data from its root-board match table rather than the T6050 wire-protocol properties. + On T8142 the root port above function zero may describe the N1's warm + reset with apple,function-warm-reset and apple,warm-reset-writes, as in + pci/apple,pcie.yaml. With both, the native driver restarts a firmware + that stopped; without them it never resets the chip. + properties: compatible: oneOf: diff --git a/arch/arm64/boot/dts/apple/t8142-j813.dts b/arch/arm64/boot/dts/apple/t8142-j813.dts index 5260a5eed2ab7c..b4cc280fc9ef7e 100644 --- a/arch/arm64/boot/dts/apple/t8142-j813.dts +++ b/arch/arm64/boot/dts/apple/t8142-j813.dts @@ -170,6 +170,13 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset: the ADT's pci-bridge0 function-warm_reset (the SMC, key + * 'bpli', the same key and argument as on the T6050 boards) and the T6050 writes. + * The N1 driver restarts a stopped firmware with it. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; n1_control: control@0,0 { compatible = "apple,t8142-centauri-control", "pci106b,1900"; diff --git a/drivers/net/wireless/apple/Kconfig b/drivers/net/wireless/apple/Kconfig index d9b13a9785de26..e7d24b6e7a52ee 100644 --- a/drivers/net/wireless/apple/Kconfig +++ b/drivers/net/wireless/apple/Kconfig @@ -10,6 +10,7 @@ config APPLE_CENTAURI tristate "Apple N1 Centauri experimental J813 Wi-Fi" depends on ARCH_APPLE || COMPILE_TEST depends on PCI && CFG80211 && DEBUG_FS + depends on MFD_MACSMC select FW_LOADER help Experimental Apple N1 PCIe and ACIPC Wi-Fi support for the J813 diff --git a/drivers/net/wireless/apple/centauri/centauri.h b/drivers/net/wireless/apple/centauri/centauri.h index fa937c1c4e2e3b..167539595226c7 100644 --- a/drivers/net/wireless/apple/centauri/centauri.h +++ b/drivers/net/wireless/apple/centauri/centauri.h @@ -6,6 +6,7 @@ #include #include #include +#include #define CEN_ALPHA_SCRATCH_OFFSET SZ_8M #define CEN_ALPHA_SCRATCH_SIZE (5 * SZ_1M) @@ -23,7 +24,7 @@ struct centauri { void __iomem *bar; resource_size_t size; u32 stage_offset; - struct dentry *debug; + struct dentry *debug, *crash_file; struct mutex boot_lock; void *firmware, *descriptor, *msi_page; dma_addr_t firmware_dma, descriptor_dma, msi_dma; @@ -35,6 +36,13 @@ struct centauri { bool link_ready; struct centauri_ipc *ipc; struct centauri_wifi *wifi; + /* Restart of a stopped firmware: requested by the Wi-Fi code, confirmed and run here */ + struct delayed_work recover_work; + unsigned long recover_at[3]; + bool removing; + bool recover_gave_up; /* restart limit reached: requests are ignored */ + bool warm_reset; /* the root port describes the N1's warm reset: restart on a stop */ + bool inject_stall; /* debugfs test: the next check finds the firmware stopped */ }; /* One row per machine with an N1: the FTAB file name, the word written to BAR+0x807c, @@ -92,7 +100,8 @@ static inline const struct centauri_board *centauri_board(void) return NULL; } -int centauri_port_cycle(struct pci_dev *pdev); +int centauri_port_cycle(struct pci_dev *pdev, bool reset_chip); +bool centauri_warm_reset_described(struct pci_dev *pdev); int centauri_start_ipc(struct centauri *c); void centauri_free_ipc(struct centauri *c); int centauri_alpha_resources(struct centauri *c, struct cen_alpha_resources *resources); @@ -102,4 +111,6 @@ void centauri_wifi_unregister(struct centauri *c); int centauri_wifi_suspend(struct centauri *c); int centauri_wifi_resume(struct centauri *c); void centauri_wifi_kick(struct centauri *c); +bool centauri_wifi_stalled(struct centauri *c); +void centauri_recovery_request(struct centauri *c, const char *why); #endif diff --git a/drivers/net/wireless/apple/centauri/centauri_ipc.c b/drivers/net/wireless/apple/centauri/centauri_ipc.c index 8d117989cd7602..a94ff01dc440bd 100644 --- a/drivers/net/wireless/apple/centauri/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/centauri_ipc.c @@ -169,7 +169,13 @@ static int secondary_init(struct centauri *c) pci_write_config_dword(c->pdev, 0xf8c, upper_32_bits(c->ipc->secondary->dma)); pci_write_config_dword(c->pdev, 0xf90, required); dev_info(&c->pdev->dev, "secondary memory: seed=%u required=%u\n", length, required); - debugfs_create_file("firmware_crash", 0400, c->debug, c, &firmware_crash_fops); + /* + * Created once and kept across restarts: its reader looks up c->ipc under boot_lock, + * and removing it here, under boot_lock, would wait for a reader blocked on that lock. + */ + if (!c->crash_file) + c->crash_file = debugfs_create_file("firmware_crash", 0400, c->debug, c, + &firmware_crash_fops); return 0; } diff --git a/drivers/net/wireless/apple/centauri/centauri_pci.c b/drivers/net/wireless/apple/centauri/centauri_pci.c index 598671387565a8..ad3ff5d538d213 100644 --- a/drivers/net/wireless/apple/centauri/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/centauri_pci.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "centauri.h" @@ -28,6 +29,8 @@ static int centauri_status_show(struct seq_file *s, void *unused) { struct centauri *c = s->private; + /* A restart cycles the link: no BAR read while it runs */ + mutex_lock(&c->boot_lock); seq_printf(s, "pci=%s vendor=%04x device=%04x\n", pci_name(c->pdev), c->pdev->vendor, c->pdev->device); if (c->link_ready) @@ -38,6 +41,7 @@ static int centauri_status_show(struct seq_file *s, void *unused) seq_printf(s, "transport=hardware-pci firmware_boot=%s image_response=%#x wifi=%s\n", c->boot_attempted ? "attempted" : "not-started", c->image_response, READ_ONCE(c->wifi) ? "registered" : "not-owned-by-this-function"); + mutex_unlock(&c->boot_lock); return 0; } DEFINE_SHOW_ATTRIBUTE(centauri_status); @@ -156,6 +160,145 @@ static int centauri_rom_boot(struct centauri *c) return ret; } +/* + * Restart the N1 from a running or stopped firmware, without the bootloader: release + * everything the firmware could write to, then a port cycle with the SMC warm reset + * (PERST# alone leaves the firmware running), which leaves the chip in its ROM (stage 0), + * then the boot steps 1-3 as at probe. btcentauri is released first: it drives function 2 + * over the IPC that is freed here. + * + * Not safe against function 0 being removed under the PCI rescan lock (sysfs remove, host + * unbind, hot unplug) while a restart runs: remove waits for the restart, which waits for the + * rescan lock. The debugfs boot steps have the same limit. + */ +static int centauri_recover(struct centauri *c) +{ + struct device *dev = &c->pdev->dev; + u32 stage = readl(c->bar + 0x8000); + struct pci_dev *beta; + int ret, i; + + if (!c->warm_reset) + return -EOPNOTSUPP; + if (!c->link_ready || PCI_FUNC(c->pdev->devfn)) + return -EBUSY; + dev_info(dev, "recovery: stage %#x, releasing the firmware's buffers\n", stage); + beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); + if (beta) + device_release_driver(&beta->dev); + pci_dev_put(beta); + centauri_free_boot(c); + /* + * The warm reset puts the chip back in its single-function ROM personality and wipes + * functions 1 and 2. Remove them now; the IPC start's rescan adds them again, as at + * probe. A stale function's BAR read after the reset hangs the fabric. + */ + pci_lock_rescan_remove(); + for (i = 2; i >= 1; i--) { + struct pci_dev *fn = pci_get_slot(c->pdev->bus, + PCI_DEVFN(PCI_SLOT(c->pdev->devfn), i)); + + if (fn) + pci_stop_and_remove_bus_device(fn); + pci_dev_put(fn); + } + pci_unlock_rescan_remove(); + c->boot_attempted = false; + c->image_response = 0; + c->link_ready = false; + ret = centauri_port_cycle(c->pdev, true); + if (ret) { + dev_err(dev, "recovery: reset port cycle failed: %d\n", ret); + return ret; + } + c->link_ready = true; + stage = readl(c->bar + 0x8000); + dev_info(dev, "recovery: stage %#x after the warm reset\n", stage); + if (stage != 0) + return -EIO; + ret = centauri_rom_boot(c); + if (ret) { + dev_err(dev, "recovery: ROM boot failed: %d\n", ret); + return ret; + } + msleep(2000); + c->link_ready = false; + ret = centauri_port_cycle(c->pdev, false); + if (ret) { + dev_err(dev, "recovery: boot port cycle failed: %d\n", ret); + return ret; + } + c->link_ready = true; + dev_info(dev, "recovery: post-reset execution stage=%#x\n", readl(c->bar + 0x8000)); + msleep(2000); + ret = centauri_start_ipc(c); + dev_info(dev, "recovery: IPC start %d\n", ret); + return ret; +} + +/* Ordered and freezable: a restart never runs during a system sleep or beside another one. */ +static struct workqueue_struct *centauri_wq; + +/* + * The Wi-Fi code saw a sign of a stopped firmware: an Alpha execution stage other than 2, + * a command ring the firmware no longer drains, or a command timeout. The worker looks + * again 2 s later and restarts the chip only if the firmware is still stopped. + */ +void centauri_recovery_request(struct centauri *c, const char *why) +{ + if (!c->warm_reset || READ_ONCE(c->removing) || READ_ONCE(c->recover_gave_up)) + return; + if (queue_delayed_work(centauri_wq, &c->recover_work, 2 * HZ)) + dev_warn(&c->pdev->dev, "firmware fault (%s); checking again in 2 s\n", why); +} + +static void centauri_recover_worker(struct work_struct *work) +{ + struct centauri *c = container_of(to_delayed_work(work), struct centauri, recover_work); + struct device *dev = &c->pdev->dev; + struct pci_dev *beta; + unsigned long now = jiffies; + int ret; + + mutex_lock(&c->boot_lock); + if (READ_ONCE(c->removing) || !c->ipc) { + mutex_unlock(&c->boot_lock); + return; + } + if (!xchg(&c->inject_stall, false) && !centauri_wifi_stalled(c)) { + mutex_unlock(&c->boot_lock); + dev_info(dev, "firmware fault cleared; no restart\n"); + return; + } + /* Three restarts in 30 minutes: the chip is left down rather than reset in a loop. */ + if (c->recover_at[0] && time_before(now, c->recover_at[0] + 30 * 60 * HZ)) { + WRITE_ONCE(c->recover_gave_up, true); + mutex_unlock(&c->boot_lock); + dev_err(dev, "firmware stopped again after 3 restarts in 30 min; leaving Wi-Fi down until the driver is reloaded\n"); + return; + } + memmove(c->recover_at, c->recover_at + 1, sizeof(c->recover_at) - sizeof(c->recover_at[0])); + c->recover_at[ARRAY_SIZE(c->recover_at) - 1] = now; + dev_warn(dev, "firmware stopped; restarting the N1\n"); + ret = centauri_recover(c); + mutex_unlock(&c->boot_lock); + if (ret) { + dev_err(dev, "restart failed: %d\n", ret); + return; + } + /* + * The IPC start's rescan added the Beta function before its firmware ran, so + * btcentauri refused it then. Attach it now, outside the rescan lock. + */ + beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); + if (beta && !beta->dev.driver) + dev_info(dev, "restarted; Bluetooth function attach: %d\n", + device_attach(&beta->dev)); + else + dev_info(dev, "restarted\n"); + pci_dev_put(beta); +} + static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { @@ -163,18 +306,25 @@ static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, u32 value; int ret = kstrtou32_from_user(buffer, count, 0, &value); - if (ret || value < 1 || value > 3) + if (ret || value < 1 || value > 6) return ret ?: -EINVAL; mutex_lock(&c->boot_lock); if (value == 1) { ret = centauri_rom_boot(c); } else if (value == 3) { ret = centauri_start_ipc(c); + } else if (value == 4) { + ret = centauri_recover(c); + } else if (value == 5 || value == 6) { + /* Test the fault path: 5 as a stopped firmware, 6 as a fault that clears. */ + WRITE_ONCE(c->inject_stall, value == 5); + centauri_recovery_request(c, value == 5 ? "debugfs: stopped" : "debugfs: spurious"); + ret = 0; } else if (!c->firmware || !c->link_ready || readl(c->bar + 0x8000) != 4) { ret = -EBUSY; } else { c->link_ready = false; - ret = centauri_port_cycle(c->pdev); + ret = centauri_port_cycle(c->pdev, false); if (!ret) { c->link_ready = true; dev_info(&c->pdev->dev, "post-reset execution stage=%#x\n", @@ -210,6 +360,8 @@ static int centauri_probe(struct pci_dev *pdev, const struct pci_device_id *id) c->pdev = pdev; c->link_ready = true; mutex_init(&c->boot_lock); + INIT_DELAYED_WORK(&c->recover_work, centauri_recover_worker); + c->warm_reset = centauri_warm_reset_described(pdev); c->stage_offset = id->driver_data; ret = pcim_enable_device(pdev); if (ret) @@ -246,6 +398,9 @@ static void centauri_remove(struct pci_dev *pdev) { struct centauri *c = pci_get_drvdata(pdev); + /* Disabled, not only cancelled: a request racing this remove can no longer queue it */ + WRITE_ONCE(c->removing, true); + disable_delayed_work_sync(&c->recover_work); centauri_wifi_unregister(c); debugfs_remove_recursive(c->debug); centauri_free_boot(c); @@ -306,10 +461,15 @@ static int __init centauri_init(void) { int ret; + centauri_wq = alloc_ordered_workqueue("apple_centauri", WQ_FREEZABLE); + if (!centauri_wq) + return -ENOMEM; centauri_debug = debugfs_create_dir("apple_centauri", NULL); ret = pci_register_driver(¢auri_driver); - if (ret) + if (ret) { debugfs_remove_recursive(centauri_debug); + destroy_workqueue(centauri_wq); + } return ret; } @@ -317,6 +477,7 @@ static void __exit centauri_exit(void) { pci_unregister_driver(¢auri_driver); debugfs_remove_recursive(centauri_debug); + destroy_workqueue(centauri_wq); } module_init(centauri_init); module_exit(centauri_exit); diff --git a/drivers/net/wireless/apple/centauri/centauri_port.c b/drivers/net/wireless/apple/centauri/centauri_port.c index 59eadc3f8521c0..ba54ac5838dad8 100644 --- a/drivers/net/wireless/apple/centauri/centauri_port.c +++ b/drivers/net/wireless/apple/centauri/centauri_port.c @@ -11,7 +11,10 @@ #include #include #include +#include +#include #include +#include #include "centauri.h" static void update(void __iomem *base, u32 offset, u32 clear, u32 set) @@ -26,7 +29,100 @@ static bool wait_bits(void __iomem *address, u32 mask, u32 wanted, u32 us) return !readl_poll_timeout(address, value, (value & mask) == wanted, 100, us); } -int centauri_port_cycle(struct pci_dev *pdev) +#define CEN_WARM_WRITES_MAX 4 + +/* + * The N1's warm reset, as the root port describes it (bindings/pci/apple,pcie.yaml, as on the + * T6050 boards): "apple,function-warm-reset" names the SMC and the key (the ADT's pci-bridge0 + * function-warm_reset), "apple,warm-reset-writes" the writes: the key's value, its bytes from + * the cell's most significant down, and the wait after it in microseconds. Reads them into + * @writes and returns how many, with the SMC's device (a reference) in *smc_pdev, or an error. + */ +static int warm_reset_parse(struct pci_dev *pdev, struct platform_device **smc_pdev, u32 *key, + u32 writes[2 * CEN_WARM_WRITES_MAX]) +{ + struct pci_dev *bridge = pdev->bus->self; + struct device_node *np = bridge ? pci_device_to_OF_node(bridge) : NULL; + struct of_phandle_args fn; + int count, i; + + *smc_pdev = NULL; + if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !np || + of_parse_phandle_with_fixed_args(np, "apple,function-warm-reset", 2, 0, &fn)) + return -ENODEV; + *smc_pdev = of_find_device_by_node(fn.np); + of_node_put(fn.np); + if (!*smc_pdev) + return -ENODEV; + *key = fn.args[0]; + count = of_property_count_u32_elems(np, "apple,warm-reset-writes"); + if (count < 2 || count % 2 || count > 2 * CEN_WARM_WRITES_MAX || + of_property_read_u32_array(np, "apple,warm-reset-writes", writes, count)) + goto bad; + for (i = 1; i < count; i += 2) + if (writes[i] > 100 * USEC_PER_MSEC) + goto bad; + return count / 2; +bad: + put_device(&(*smc_pdev)->dev); + *smc_pdev = NULL; + return -EINVAL; +} + +/* + * The root port describes a warm reset, and centauri_port_cycle() can cycle this port: only + * then does the driver restart a stopped N1, so a restart never tears the functions down on a + * board whose port cycle would refuse. + */ +bool centauri_warm_reset_described(struct pci_dev *pdev) +{ + const struct centauri_board *board = centauri_board(); + struct pci_dev *bridge = pdev->bus->self; + u32 key, writes[2 * CEN_WARM_WRITES_MAX]; + struct platform_device *smc_pdev; + + if (!board || !board->port || !bridge || bridge->vendor != PCI_VENDOR_ID_APPLE || + (board->bridge_id && bridge->device != board->bridge_id)) + return false; + if (warm_reset_parse(pdev, &smc_pdev, &key, writes) <= 0) + return false; + put_device(&smc_pdev->dev); + return true; +} + +/* + * Given while the port is down and not set up: the link then trains a chip that was just + * reset. PERST# alone leaves the firmware running. + */ +static int warm_reset(struct pci_dev *pdev) +{ + u32 key, writes[2 * CEN_WARM_WRITES_MAX]; + struct platform_device *smc_pdev; + struct apple_smc *smc; + int count, i, ret = 0; + + count = warm_reset_parse(pdev, &smc_pdev, &key, writes); + if (count <= 0) { + ret = count ?: -ENODEV; + goto out; + } + smc = platform_get_drvdata(smc_pdev); + if (!smc) + ret = -ENODEV; + for (i = 0; i < count && !ret; i++) { + __be32 value = cpu_to_be32(writes[2 * i]); + + ret = apple_smc_write(smc, key, &value, sizeof(value)); + if (!ret) + fsleep(writes[2 * i + 1]); + } + put_device(&smc_pdev->dev); +out: + dev_info(&pdev->dev, "warm reset through the SMC: %d\n", ret); + return ret; +} + +int centauri_port_cycle(struct pci_dev *pdev, bool reset_chip) { static const u32 reset[][2] = { {0x88, 0x110}, {0x100, ~0U}, {0x148, ~0U}, {0x210, ~0U}, @@ -141,6 +237,8 @@ int centauri_port_cycle(struct pci_dev *pdev) writel(0, port + 0x3800 + 4 * i); for (i = 0; i < ARRAY_SIZE(tune); i++) writel(tune[i][1], port + tune[i][0]); + if (reset_chip) + warm_reset(pdev); update(port, 0x800, 0, 1); udelay(10); update(phy, 0, 0, 1); diff --git a/drivers/net/wireless/apple/centauri/centauri_wifi.c b/drivers/net/wireless/apple/centauri/centauri_wifi.c index de0d4d872932a0..646615027625d5 100644 --- a/drivers/net/wireless/apple/centauri/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/centauri_wifi.c @@ -745,8 +745,10 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo return -EBUSY; if (size + 24 > BUFFER_SIZE) return -EMSGSIZE; - if ((slot + 1) % ring_size[1] == index_read(wifi, 1, 1)) + if ((slot + 1) % ring_size[1] == index_read(wifi, 1, 1)) { + centauri_recovery_request(wifi->control, "command ring full"); return -ENOSPC; + } packet = wifi->a.window + TX_BUFFER + slot * BUFFER_SIZE; memset(packet, 0, 24 + size); put_unaligned_le16(24 + size, packet + 0x10); @@ -766,8 +768,10 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo writel(1, wifi->a.bar + 0x1004); do { drain_control(wifi, pm_command); - if (readl(wifi->a.bar + 8) != 2) + if (readl(wifi->a.bar + 8) != 2) { + centauri_recovery_request(wifi->control, "command: Alpha stage"); return -EIO; + } /* Bit 30 is more-data-pending, not part of the command identity. * Scan/connect replies set it before their later completion event. */ @@ -782,9 +786,26 @@ static int command_control(struct centauri_wifi *wifi, u32 id, const void *paylo usleep_range(500, 1000); } while (time_before(jiffies, deadline)); dev_err(&wifi->control->pdev->dev, "Wi-Fi command %#x timed out (rx=%u)\n", id, wifi->rx_seen[2]); + centauri_recovery_request(wifi->control, "command timeout"); return -ETIMEDOUT; } +/* + * The firmware has stopped: Alpha left execution stage 2, or the command ring stays full + * (a running firmware drains each command before the next is queued). Not while the + * transport is paused for a system sleep. + */ +bool centauri_wifi_stalled(struct centauri *c) +{ + struct centauri_wifi *wifi = c->wifi; + + if (!wifi || READ_ONCE(wifi->transport_paused) || READ_ONCE(wifi->stopping)) + return false; + if (readl(wifi->a.bar + 8) != 2) + return true; + return (READ_ONCE(wifi->command_head) + 1) % ring_size[1] == index_read(wifi, 1, 1); +} + static int command(struct centauri_wifi *wifi, u32 id, const void *payload, size_t size) { return command_control(wifi, id, payload, size, false); @@ -955,6 +976,7 @@ static void scan_worker(struct work_struct *work) do { drain(wifi); if (readl(wifi->a.bar + 8) != 2) { + centauri_recovery_request(wifi->control, "scan: Alpha stage"); ret = -EIO; break; } From bfd2a53eb93d14b17485692be3d23b3bb97561eb Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:34:59 -0500 Subject: [PATCH 1254/1514] selftests: apple: atc-t8132-usb3: stub dwc3_apple_idle_rpm Commit 0d8e6bde9b28 ("usb: dwc3: apple: select idle runtime PM by DT power domains, not a SoC list", merged in #2299) replaced the inline SoC check in dwc3_apple_probe() with a call to dwc3_apple_idle_rpm(dev->of_node). atc-t8132-usb3.py extracts the early dwc3_apple_probe() prefix into its usb-native-shutdown host harness and stubs out probe helpers. Add the matching dwc3_apple_idle_rpm() stub so the host test compiles and passes again on main. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- tools/testing/selftests/drivers/apple/atc-t8132-usb3.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index dfa3d7aad45f52..8adcbb6159799a 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -737,6 +737,7 @@ def main(): static void mutex_init(int *p) { *p=0; } static bool dwc3_apple_has_fixed_hub(struct device *d,unsigned *port) { (void)d;(void)port;return false; } static bool dwc3_apple_host_only(struct device *d) { (void)d;return false; } +static bool dwc3_apple_idle_rpm(const char *np) { (void)np;return false; } static bool device_property_read_bool(struct device *d,const char *name) { (void)d;(void)name;return false; } static void spin_lock_init(int *p) { *p=0; } static void publish_owner(struct platform_device *pdev,struct dwc3_apple *appledwc) From cd47c16c4edb21cc9d54db2236772965cc0b0eaa Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 23:35:56 -0500 Subject: [PATCH 1255/1514] dt-checks: document disk-boot and subtract in-tree /chosen bindings Upstream dtschema's chosen.yaml sets additionalProperties: false, so dt-validate still reports every in-tree /chosen property (even those documented under Documentation/devicetree/bindings/chosen/*.yaml as in PR #3106) as not matching any regex in chosen.yaml. Adding another documented /chosen property (such as linux-enablement-mac,dapf-halted-handoff in #2745 for t8132-j715.dtb) changes the quoted property list in that warning line, causing apple-dt-check.sh to fail with a false positive. Fix this without shadowing upstream chosen.yaml: - Document linux-enablement-mac,disk-boot (used in t8132-jxxx.dtsi) in Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml. - In scripts/dtc/apple-dt-check.sh, parse properties documented under Documentation/devicetree/bindings/chosen/*.yaml for each checked revision and subtract only those documented property names from 'chosen: ... do(es) not match any of the regexes:' lines. Lines are dropped only when every listed property is documented in bindings/chosen/*.yaml. Any undocumented /chosen property remains reported (with singular/plural verb normalized), and all non-/chosen warnings and schema type/value checks continue to fail as before. Signed-off-by: Diljit Singh --- .../linux-enablement-mac,disk-boot.yaml | 35 +++++++++++ scripts/dtc/apple-dt-check.sh | 62 +++++++++++++++++-- 2 files changed, 93 insertions(+), 4 deletions(-) create mode 100644 Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml diff --git a/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml new file mode 100644 index 00000000000000..dd6b2669c689b9 --- /dev/null +++ b/Documentation/devicetree/bindings/chosen/linux-enablement-mac,disk-boot.yaml @@ -0,0 +1,35 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/chosen/linux-enablement-mac,disk-boot.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Apple T8132 disk-boot /chosen flag + +maintainers: + - Diljit Singh + +description: + Boolean flag in /chosen carried by Apple T8132 board device trees to + indicate that the board tree targets normal disk-boot hand-off from + the bootloader. + +select: + properties: + $nodename: + const: chosen + required: + - $nodename + +properties: + $nodename: + const: chosen + + linux-enablement-mac,disk-boot: + type: boolean + description: + Indicates that the board device tree targets disk-boot hand-off + on Apple T8132 systems. + +additionalProperties: true +... diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index 77772810f4295e..398a147bf6cac3 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -4,14 +4,67 @@ # and fail when HEAD has a warning BASE does not. Also runs dt_binding_check on every binding HEAD # changes. Phandle values in the messages are masked, so renumbering is not a new warning, and so # is the pattern list of a "does not match any of the regexes" message, which grows with every -# vendor prefix the bindings add. A firmware-profile variant (a .dts that includes another board's -# .dts, such as t8122-j613-25g83) is reported under its base board's name, so the base's existing -# warnings are not new warnings of the variant; anything the variant adds still is. -# Needs dtschema (dt-validate), clang/lld (LLVM=1), flex, bison. Prints a summary. +# vendor prefix the bindings add. Upstream dtschema's chosen.yaml sets additionalProperties: false, +# so properties documented in in-tree bindings/chosen/*.yaml are subtracted from "chosen: ... +# do(es) not match any of the regexes:" lines while preserving warnings for any undocumented +# properties and all schema type/value checks. A firmware-profile variant (a .dts that includes +# another board's .dts, such as t8122-j613-25g83) is reported under its base board's name, so the +# base's existing warnings are not new warnings of the variant; anything the variant adds still is. +# Needs dtschema (dt-validate), clang/lld (LLVM=1), flex, bison, python3. Prints a summary. set -u BASE=$1 HEAD=$2 W=$3 export ARCH=arm64 LLVM=1 mkdir -p "$W" +filter_documented_chosen() { # chosen_bindings_dir + python3 -c ' +import glob, os, re, sys + +def load_yaml(path): + try: + import yaml + with open(path, encoding="utf-8") as f: + return yaml.safe_load(f) + except ImportError: + from ruamel.yaml import YAML + with open(path, encoding="utf-8") as f: + return YAML(typ="safe").load(f) + +chosen_dir = sys.argv[1] +documented = set() +for path in sorted(glob.glob(os.path.join(chosen_dir, "*.yaml"))): + doc = load_yaml(path) + if not isinstance(doc, dict): + continue + props = doc.get("properties") + if not isinstance(props, dict): + continue + for key, val in props.items(): + if isinstance(key, str) and not key.startswith("$") and val is not False: + documented.add(key) + +pat = re.compile( + r"^(?P[^\n]*\.dtb: chosen: )" + r"(?P\x27[^\x27]+\x27(?:, \x27[^\x27]+\x27)*)" + r" (?:does|do) not match any of the regexes:(?P.*)$" +) + +for raw in sys.stdin: + line = raw.rstrip("\n") + m = pat.match(line) + if not m: + sys.stdout.write(raw) + continue + props = re.findall(r"\x27([^\x27]+)\x27", m.group("props")) + remaining = [p for p in props if p not in documented] + if not remaining: + continue + verb = "does" if len(remaining) == 1 else "do" + joined = ", ".join(f"\x27{p}\x27" for p in remaining) + prefix = m.group("prefix") + tail = m.group("tail") + sys.stdout.write(f"{prefix}{joined} {verb} not match any of the regexes:{tail}\n") +' "$1" +} warnings() { # rev tag local t=$W/src-$2 o=$W/out-$2 rm -f "$W/$2.warn" @@ -28,6 +81,7 @@ warnings() { # rev tag sed -E "s#$t/##g; s#$o/##g" | sed -E "s#arch/arm64/boot/dts/##; $variants" | sed -E 's#^apple/#arch/arm64/boot/dts/apple/#' | perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | + filter_documented_chosen "$t/Documentation/devicetree/bindings/chosen" | sort -u > "$W/$2.warn" echo "$2: make rc=$rc, $(wc -l < "$W/$2.warn") warning lines, $(echo $dtbs | wc -w) DTBs" return $rc From c28ac9cc500adaccac9bc7df668e44d33e1ba542 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 07:36:07 +0300 Subject: [PATCH 1256/1514] mfd: macsmc: Parse and give a PCIe endpoint's warm reset A PCIe root port names its endpoint's warm reset with "apple,function-warm-reset" (the SMC and the key) and "apple,warm-reset-writes" (each value and the wait after it). The T6050 host reads them in pcie-apple, and the N1 restart on T8142 needs the same: a second copy of the parser would drift from the first. Add apple_smc_warm_reset_parse(), apple_smc_warm_reset_put() and apple_smc_warm_reset() to the SMC driver, and use them in the T6050 host. The host's checks and messages are unchanged: at most four writes, no wait above 100 ms, a device link to the SMC for the noirq write, and no reset without both properties. Signed-off-by: Nick --- drivers/mfd/macsmc.c | 64 +++++++++++++++++++++++++++ drivers/pci/controller/pcie-apple.c | 68 +++++------------------------ include/linux/mfd/macsmc.h | 49 +++++++++++++++++++++ 3 files changed, 125 insertions(+), 56 deletions(-) diff --git a/drivers/mfd/macsmc.c b/drivers/mfd/macsmc.c index 35f86f9fe00273..cf1bbdab1889ef 100644 --- a/drivers/mfd/macsmc.c +++ b/drivers/mfd/macsmc.c @@ -913,6 +913,70 @@ int apple_smc_write_noirq(struct apple_smc *smc, smc_key key, const void *buf, s } EXPORT_SYMBOL_GPL(apple_smc_write_noirq); +int apple_smc_warm_reset_parse(struct device_node *np, struct apple_smc_warm_reset *wr) +{ + struct of_phandle_args fn; + int count, i; + + memset(wr, 0, sizeof(*wr)); + if (!np || of_parse_phandle_with_fixed_args(np, "apple,function-warm-reset", 2, 0, &fn)) + return -ENODEV; + wr->smc = of_find_device_by_node(fn.np); + of_node_put(fn.np); + if (!wr->smc) + return -ENODEV; + count = of_property_count_u32_elems(np, "apple,warm-reset-writes"); + if (count < 2 || count % 2 || count > ARRAY_SIZE(wr->writes) || + of_property_read_u32_array(np, "apple,warm-reset-writes", wr->writes, count)) + goto bad; + for (i = 1; i < count; i += 2) + if (wr->writes[i] > 100 * USEC_PER_MSEC) + goto bad; + wr->key = fn.args[0]; + wr->count = count / 2; + return 0; +bad: + apple_smc_warm_reset_put(wr); + return -EINVAL; +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset_parse); + +void apple_smc_warm_reset_put(struct apple_smc_warm_reset *wr) +{ + if (wr->smc) + put_device(&wr->smc->dev); + memset(wr, 0, sizeof(*wr)); +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset_put); + +int apple_smc_warm_reset(const struct apple_smc_warm_reset *wr, bool noirq) +{ + struct apple_smc *smc = wr->smc ? platform_get_drvdata(wr->smc) : NULL; + unsigned int i; + int ret = 0; + + if (!smc || !wr->count) + return -ENODEV; + for (i = 0; i < wr->count && !ret; i++) { + __be32 value = cpu_to_be32(wr->writes[2 * i]); + u32 wait = wr->writes[2 * i + 1]; + + if (noirq) { + ret = apple_smc_write_noirq(smc, wr->key, &value, sizeof(value)); + if (!ret) { + mdelay(wait / USEC_PER_MSEC); + udelay(wait % USEC_PER_MSEC); + } + } else { + ret = apple_smc_write(smc, wr->key, &value, sizeof(value)); + if (!ret) + fsleep(wait); + } + } + return ret; +} +EXPORT_SYMBOL_GPL(apple_smc_warm_reset); + static void apple_smc_write_mbse(struct apple_smc *smc, smc_key value) { int ret; diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 824b94d04caa7a..7d139eab8c4528 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -565,7 +565,6 @@ struct apple_pcie_pd { struct apple_radio_sleep; -#define APPLE_PCIE_T6050_WARM_WRITES 4 struct apple_pcie { struct mutex lock; @@ -588,10 +587,7 @@ struct apple_pcie { /* Those ports back, and their functions looked for, once the resume is over */ struct work_struct t6050_unpark_work; /* The endpoint's warm reset, given by this host while the port is down */ - struct platform_device *t6050_smc; - u32 t6050_warm_key; - u32 t6050_warm_writes[2 * APPLE_PCIE_T6050_WARM_WRITES]; - unsigned int t6050_warm_count; + struct apple_smc_warm_reset t6050_warm; bool t6050_warm_done; /* When this wake's bring-up of that port had the link up and its 100 ms over; 0 before */ ktime_t t6050_link_up; @@ -5546,35 +5542,14 @@ static int apple_pcie_t6050_pm_notify(struct notifier_block *nb, unsigned long a static void apple_pcie_t6050_warm_reset_probe(struct platform_device *pdev, struct apple_pcie *pcie, struct apple_pcie_port *port) { - struct of_phandle_args fn; - int count, i; - if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || - of_parse_phandle_with_fixed_args(port->np, "apple,function-warm-reset", 2, 0, &fn)) - return; - pcie->t6050_smc = of_find_device_by_node(fn.np); - of_node_put(fn.np); - if (!pcie->t6050_smc) + apple_smc_warm_reset_parse(port->np, &pcie->t6050_warm)) return; - count = of_property_count_u32_elems(port->np, "apple,warm-reset-writes"); - if (count < 2 || count % 2 || count > ARRAY_SIZE(pcie->t6050_warm_writes) || - of_property_read_u32_array(port->np, "apple,warm-reset-writes", - pcie->t6050_warm_writes, count)) - goto drop; - for (i = 1; i < count; i += 2) - if (pcie->t6050_warm_writes[i] > 100 * USEC_PER_MSEC) - goto drop; /* The SMC's noirq resume comes before this host's: the reset is written from there */ - if (!device_link_add(&pdev->dev, &pcie->t6050_smc->dev, DL_FLAG_STATELESS)) { + if (!device_link_add(&pdev->dev, &pcie->t6050_warm.smc->dev, DL_FLAG_STATELESS)) { dev_warn(&pdev->dev, "no warm reset after a sleep: no link to the SMC\n"); - goto drop; + apple_smc_warm_reset_put(&pcie->t6050_warm); } - pcie->t6050_warm_key = fn.args[0]; - pcie->t6050_warm_count = count / 2; - return; -drop: - put_device(&pcie->t6050_smc->dev); - pcie->t6050_smc = NULL; } /* @@ -5585,34 +5560,15 @@ static void apple_pcie_t6050_warm_reset_probe(struct platform_device *pdev, stru */ static int apple_pcie_t6050_warm_reset(struct apple_pcie *pcie, bool noirq) { - struct apple_smc *smc; - unsigned int i; - int ret = 0; + int ret; pcie->t6050_warm_done = false; - if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !pcie->t6050_warm_count) + if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !pcie->t6050_warm.count) return -ENODEV; - smc = platform_get_drvdata(pcie->t6050_smc); - if (!smc) { + ret = apple_smc_warm_reset(&pcie->t6050_warm, noirq); + if (ret == -ENODEV) { dev_warn(pcie->dev, "no warm reset: the SMC isn't bound\n"); - return -ENODEV; - } - for (i = 0; i < pcie->t6050_warm_count && !ret; i++) { - __be32 value = cpu_to_be32(pcie->t6050_warm_writes[2 * i]); - u32 wait = pcie->t6050_warm_writes[2 * i + 1]; - smc_key key = pcie->t6050_warm_key; - - if (noirq) { - ret = apple_smc_write_noirq(smc, key, &value, sizeof(value)); - if (!ret) { - mdelay(wait / USEC_PER_MSEC); - udelay(wait % USEC_PER_MSEC); - } - } else { - ret = apple_smc_write(smc, key, &value, sizeof(value)); - if (!ret) - fsleep(wait); - } + return ret; } pcie->t6050_warm_done = !ret; if (ret) @@ -5811,7 +5767,7 @@ void apple_pcie_t6050_sleep_reset(struct pci_dev *bridge) { struct apple_pcie *pcie = apple_pcie_t6050_from_bridge(bridge); - if (pcie && pcie->t6050_warm_count) { + if (pcie && pcie->t6050_warm.count) { pcie->t6050_keep_alive = false; pcie->t6050_reset_before_sleep = true; } @@ -5876,7 +5832,7 @@ int apple_pcie_t6050_port_recycle(struct pci_dev *bridge) if (!pcie) return -ENODEV; - if (!pcie->t6050_warm_count || pcie->t6050_lost || READ_ONCE(pcie->t6050_down)) + if (!pcie->t6050_warm.count || pcie->t6050_lost || READ_ONCE(pcie->t6050_down)) return -EBUSY; pci_save_state(bridge); ret = apple_pcie_t6050_sleep_down(pcie); @@ -7645,7 +7601,7 @@ static int apple_pcie_resume_noirq(struct device *dev) /* Up, and reset unless kept alive: nothing takes it down again */ pcie->t6050_woke = !READ_ONCE(pcie->t6050_down) && !pcie->t6050_lost && (!warm_reset || pcie->t6050_warm_done || - !pcie->t6050_warm_count); + !pcie->t6050_warm.count); list_for_each_entry(port, &pcie->ports, entry) if (pcie->t6050_parked & BIT(port->idx)) dev_dbg(dev, "port %d at the wake: parked since before the sleep, power off, PERST# low, no functions, root port %s, DART %s; %s\n", diff --git a/include/linux/mfd/macsmc.h b/include/linux/mfd/macsmc.h index 5afcf707a7c313..47d4bc7c9b35df 100644 --- a/include/linux/mfd/macsmc.h +++ b/include/linux/mfd/macsmc.h @@ -223,6 +223,55 @@ int apple_smc_write(struct apple_smc *smc, smc_key key, const void *buf, size_t */ int apple_smc_write_noirq(struct apple_smc *smc, smc_key key, const void *buf, size_t size); +struct device_node; +struct platform_device; + +#define APPLE_SMC_WARM_RESET_WRITES 4 + +/** + * struct apple_smc_warm_reset - a PCIe endpoint's reset through an SMC key + * @smc: the SMC's device (a reference, dropped by apple_smc_warm_reset_put()) + * @key: the key to write + * @count: how many writes + * @writes: per write, the key's value (its bytes from the cell's most significant down) + * and the wait after it in microseconds + * + * Read from a PCIe root port's "apple,function-warm-reset" and "apple,warm-reset-writes" + * (bindings/pci/apple,pcie.yaml). + */ +struct apple_smc_warm_reset { + struct platform_device *smc; + smc_key key; + unsigned int count; + u32 writes[2 * APPLE_SMC_WARM_RESET_WRITES]; +}; + +/** + * apple_smc_warm_reset_parse - read a root port's warm reset + * @np: the root port's node + * @wr: filled in on success + * + * Return: Zero on success, -ENODEV when the port describes none or its SMC has no device, + * -EINVAL when the writes are malformed. + */ +int apple_smc_warm_reset_parse(struct device_node *np, struct apple_smc_warm_reset *wr); + +/** + * apple_smc_warm_reset_put - drop the reference apple_smc_warm_reset_parse() took + * @wr: the parsed reset; cleared + */ +void apple_smc_warm_reset_put(struct apple_smc_warm_reset *wr); + +/** + * apple_smc_warm_reset - give a parsed warm reset + * @wr: the parsed reset + * @noirq: from another device's noirq callbacks: the replies are polled for and the waits + * busy-wait, as for apple_smc_write_noirq() + * + * Return: Zero on success, -ENODEV when the SMC isn't bound, or the first write's error. + */ +int apple_smc_warm_reset(const struct apple_smc_warm_reset *wr, bool noirq); + /** * apple_smc_enter_atomic - Enter atomic mode to be able to use apple_smc_write_atomic * @smc: Pointer to apple_smc struct From 642bc8a67049fe575911b10e2facaeb74112bd46 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 07:36:07 +0300 Subject: [PATCH 1257/1514] wifi: apple: centauri: wait for the restart's stages, and retry a failed restart Review of the N1 restart: - The restart slept 2 s after the ROM boot and 2 s after the second port cycle. The ROM boot already returns once the image is loaded (stage 4), as the boot step does, and the boot steps run the port cycle right after it, so the first wait goes. After the port cycle the IPC start needs stage 1: poll for it, for at most 5 s, and fail with the stage it read otherwise. - The warm reset's result was dropped. centauri_port_cycle() now takes where to store it, brings the link up either way, and returns the link's result, so the restart can tell a refused reset (link up: try again) from a lost link (nothing more to do). - A failed restart left Wi-Fi down with no further attempt. With the link up, the worker tries again 10 s later, within the same limit of three restarts in 30 minutes. With the link down it says so and stops. - The warm reset is read with the SMC driver's parser, shared with the T6050 host, instead of a copy. Signed-off-by: Nick --- .../net/wireless/apple/centauri/centauri.h | 3 +- .../wireless/apple/centauri/centauri_pci.c | 38 ++++++--- .../wireless/apple/centauri/centauri_port.c | 78 +++++-------------- 3 files changed, 51 insertions(+), 68 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/centauri.h b/drivers/net/wireless/apple/centauri/centauri.h index 167539595226c7..e24614ab66aab5 100644 --- a/drivers/net/wireless/apple/centauri/centauri.h +++ b/drivers/net/wireless/apple/centauri/centauri.h @@ -41,6 +41,7 @@ struct centauri { unsigned long recover_at[3]; bool removing; bool recover_gave_up; /* restart limit reached: requests are ignored */ + bool restart_failed; /* the last restart failed with the link up: try again */ bool warm_reset; /* the root port describes the N1's warm reset: restart on a stop */ bool inject_stall; /* debugfs test: the next check finds the firmware stopped */ }; @@ -100,7 +101,7 @@ static inline const struct centauri_board *centauri_board(void) return NULL; } -int centauri_port_cycle(struct pci_dev *pdev, bool reset_chip); +int centauri_port_cycle(struct pci_dev *pdev, int *reset_ret); bool centauri_warm_reset_described(struct pci_dev *pdev); int centauri_start_ipc(struct centauri *c); void centauri_free_ipc(struct centauri *c); diff --git a/drivers/net/wireless/apple/centauri/centauri_pci.c b/drivers/net/wireless/apple/centauri/centauri_pci.c index ad3ff5d538d213..332d9040170b71 100644 --- a/drivers/net/wireless/apple/centauri/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/centauri_pci.c @@ -176,7 +176,7 @@ static int centauri_recover(struct centauri *c) struct device *dev = &c->pdev->dev; u32 stage = readl(c->bar + 0x8000); struct pci_dev *beta; - int ret, i; + int ret, reset_ret, i; if (!c->warm_reset) return -EOPNOTSUPP; @@ -206,31 +206,39 @@ static int centauri_recover(struct centauri *c) c->boot_attempted = false; c->image_response = 0; c->link_ready = false; - ret = centauri_port_cycle(c->pdev, true); + ret = centauri_port_cycle(c->pdev, &reset_ret); if (ret) { dev_err(dev, "recovery: reset port cycle failed: %d\n", ret); return ret; } c->link_ready = true; + if (reset_ret) { + dev_err(dev, "recovery: warm reset failed: %d\n", reset_ret); + return reset_ret; + } stage = readl(c->bar + 0x8000); dev_info(dev, "recovery: stage %#x after the warm reset\n", stage); if (stage != 0) return -EIO; + /* Returns once the ROM reports the image loaded (stage 4), as the boot step does. */ ret = centauri_rom_boot(c); if (ret) { dev_err(dev, "recovery: ROM boot failed: %d\n", ret); return ret; } - msleep(2000); c->link_ready = false; - ret = centauri_port_cycle(c->pdev, false); + ret = centauri_port_cycle(c->pdev, NULL); if (ret) { dev_err(dev, "recovery: boot port cycle failed: %d\n", ret); return ret; } c->link_ready = true; - dev_info(dev, "recovery: post-reset execution stage=%#x\n", readl(c->bar + 0x8000)); - msleep(2000); + /* The IPC start needs the image's first stage (1) after the port cycle. */ + ret = readl_poll_timeout(c->bar + 0x8000, stage, stage == 1, 20 * USEC_PER_MSEC, + 5 * USEC_PER_SEC); + dev_info(dev, "recovery: post-reset execution stage=%#x\n", stage); + if (ret) + return ret; ret = centauri_start_ipc(c); dev_info(dev, "recovery: IPC start %d\n", ret); return ret; @@ -261,11 +269,11 @@ static void centauri_recover_worker(struct work_struct *work) int ret; mutex_lock(&c->boot_lock); - if (READ_ONCE(c->removing) || !c->ipc) { + if (READ_ONCE(c->removing) || (!c->ipc && !c->restart_failed)) { mutex_unlock(&c->boot_lock); return; } - if (!xchg(&c->inject_stall, false) && !centauri_wifi_stalled(c)) { + if (!xchg(&c->inject_stall, false) && !c->restart_failed && !centauri_wifi_stalled(c)) { mutex_unlock(&c->boot_lock); dev_info(dev, "firmware fault cleared; no restart\n"); return; @@ -281,9 +289,19 @@ static void centauri_recover_worker(struct work_struct *work) c->recover_at[ARRAY_SIZE(c->recover_at) - 1] = now; dev_warn(dev, "firmware stopped; restarting the N1\n"); ret = centauri_recover(c); + /* With the link up the chip can be reset again; without it nothing more can be done. */ + c->restart_failed = ret && c->link_ready; mutex_unlock(&c->boot_lock); + if (ret && !c->restart_failed) { + dev_err(dev, "restart failed: %d, and the link is down; Wi-Fi stays down until a reboot\n", + ret); + return; + } if (ret) { - dev_err(dev, "restart failed: %d\n", ret); + /* Counts against the same limit: at most three attempts in 30 minutes. */ + dev_err(dev, "restart failed: %d; trying again in 10 s\n", ret); + if (!READ_ONCE(c->removing)) + queue_delayed_work(centauri_wq, &c->recover_work, 10 * HZ); return; } /* @@ -324,7 +342,7 @@ static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, ret = -EBUSY; } else { c->link_ready = false; - ret = centauri_port_cycle(c->pdev, false); + ret = centauri_port_cycle(c->pdev, NULL); if (!ret) { c->link_ready = true; dev_info(&c->pdev->dev, "post-reset execution stage=%#x\n", diff --git a/drivers/net/wireless/apple/centauri/centauri_port.c b/drivers/net/wireless/apple/centauri/centauri_port.c index ba54ac5838dad8..55964946895e7b 100644 --- a/drivers/net/wireless/apple/centauri/centauri_port.c +++ b/drivers/net/wireless/apple/centauri/centauri_port.c @@ -29,44 +29,18 @@ static bool wait_bits(void __iomem *address, u32 mask, u32 wanted, u32 us) return !readl_poll_timeout(address, value, (value & mask) == wanted, 100, us); } -#define CEN_WARM_WRITES_MAX 4 - /* * The N1's warm reset, as the root port describes it (bindings/pci/apple,pcie.yaml, as on the * T6050 boards): "apple,function-warm-reset" names the SMC and the key (the ADT's pci-bridge0 - * function-warm_reset), "apple,warm-reset-writes" the writes: the key's value, its bytes from - * the cell's most significant down, and the wait after it in microseconds. Reads them into - * @writes and returns how many, with the SMC's device (a reference) in *smc_pdev, or an error. + * function-warm_reset), "apple,warm-reset-writes" the writes. */ -static int warm_reset_parse(struct pci_dev *pdev, struct platform_device **smc_pdev, u32 *key, - u32 writes[2 * CEN_WARM_WRITES_MAX]) +static int warm_reset_parse(struct pci_dev *pdev, struct apple_smc_warm_reset *wr) { struct pci_dev *bridge = pdev->bus->self; - struct device_node *np = bridge ? pci_device_to_OF_node(bridge) : NULL; - struct of_phandle_args fn; - int count, i; - *smc_pdev = NULL; - if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !np || - of_parse_phandle_with_fixed_args(np, "apple,function-warm-reset", 2, 0, &fn)) - return -ENODEV; - *smc_pdev = of_find_device_by_node(fn.np); - of_node_put(fn.np); - if (!*smc_pdev) + if (!IS_REACHABLE(CONFIG_MFD_MACSMC) || !bridge) return -ENODEV; - *key = fn.args[0]; - count = of_property_count_u32_elems(np, "apple,warm-reset-writes"); - if (count < 2 || count % 2 || count > 2 * CEN_WARM_WRITES_MAX || - of_property_read_u32_array(np, "apple,warm-reset-writes", writes, count)) - goto bad; - for (i = 1; i < count; i += 2) - if (writes[i] > 100 * USEC_PER_MSEC) - goto bad; - return count / 2; -bad: - put_device(&(*smc_pdev)->dev); - *smc_pdev = NULL; - return -EINVAL; + return apple_smc_warm_reset_parse(pci_device_to_OF_node(bridge), wr); } /* @@ -78,15 +52,14 @@ bool centauri_warm_reset_described(struct pci_dev *pdev) { const struct centauri_board *board = centauri_board(); struct pci_dev *bridge = pdev->bus->self; - u32 key, writes[2 * CEN_WARM_WRITES_MAX]; - struct platform_device *smc_pdev; + struct apple_smc_warm_reset wr; if (!board || !board->port || !bridge || bridge->vendor != PCI_VENDOR_ID_APPLE || (board->bridge_id && bridge->device != board->bridge_id)) return false; - if (warm_reset_parse(pdev, &smc_pdev, &key, writes) <= 0) + if (warm_reset_parse(pdev, &wr)) return false; - put_device(&smc_pdev->dev); + apple_smc_warm_reset_put(&wr); return true; } @@ -96,33 +69,24 @@ bool centauri_warm_reset_described(struct pci_dev *pdev) */ static int warm_reset(struct pci_dev *pdev) { - u32 key, writes[2 * CEN_WARM_WRITES_MAX]; - struct platform_device *smc_pdev; - struct apple_smc *smc; - int count, i, ret = 0; + struct apple_smc_warm_reset wr; + int ret; - count = warm_reset_parse(pdev, &smc_pdev, &key, writes); - if (count <= 0) { - ret = count ?: -ENODEV; - goto out; + ret = warm_reset_parse(pdev, &wr); + if (!ret) { + ret = apple_smc_warm_reset(&wr, false); + apple_smc_warm_reset_put(&wr); } - smc = platform_get_drvdata(smc_pdev); - if (!smc) - ret = -ENODEV; - for (i = 0; i < count && !ret; i++) { - __be32 value = cpu_to_be32(writes[2 * i]); - - ret = apple_smc_write(smc, key, &value, sizeof(value)); - if (!ret) - fsleep(writes[2 * i + 1]); - } - put_device(&smc_pdev->dev); -out: dev_info(&pdev->dev, "warm reset through the SMC: %d\n", ret); return ret; } -int centauri_port_cycle(struct pci_dev *pdev, bool reset_chip) +/* + * Take the N1's port down and train it again. With @reset_ret, the N1 is warm reset while + * the port is down and the reset's result is stored there; the link comes up either way. + * Returns the link's result. + */ +int centauri_port_cycle(struct pci_dev *pdev, int *reset_ret) { static const u32 reset[][2] = { {0x88, 0x110}, {0x100, ~0U}, {0x148, ~0U}, {0x210, ~0U}, @@ -237,8 +201,8 @@ int centauri_port_cycle(struct pci_dev *pdev, bool reset_chip) writel(0, port + 0x3800 + 4 * i); for (i = 0; i < ARRAY_SIZE(tune); i++) writel(tune[i][1], port + tune[i][0]); - if (reset_chip) - warm_reset(pdev); + if (reset_ret) + *reset_ret = warm_reset(pdev); update(port, 0x800, 0, 1); udelay(10); update(phy, 0, 0, 1); From 740aba2ae3427ec661a1dbc064847c096e8145bb Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 24 Nov 2026 22:07:23 +0300 Subject: [PATCH 1258/1514] arm64: dts: apple: t8142-j815: Describe the N1 warm reset, as on J813 The J815 ADT gives pci-bridge0 the same function-warm_reset as J813 (SMC key bpli, argument 0x1000000), so the N1 driver can restart a stopped firmware here too instead of leaving Wi-Fi and Bluetooth down until a reboot. Without these properties centauri_recovery_request() returns early and debugfs rom_boot 4/5 do nothing on this board. Signed-off-by: Nick --- arch/arm64/boot/dts/apple/t8142-j815.dts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index 82e73d6dafc2b9..ac142ba30a6411 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -268,6 +268,12 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset, as on J813: the J815 ADT's pci-bridge0 + * function-warm_reset names the same SMC key 'bpli' and argument. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; n1_control: control@0,0 { compatible = "apple,t8142-centauri-control", "pci106b,1900"; From 227c89b69b65094ce1354caf79971d069114f877 Mon Sep 17 00:00:00 2001 From: Nick Date: Tue, 24 Nov 2026 22:51:48 +0300 Subject: [PATCH 1259/1514] wifi: apple: centauri: attach Bluetooth once Beta's firmware runs Function 2 (Bluetooth) appears with the IPC start's bus rescan, before Beta's firmware runs, so btcentauri cannot take it then. Only the restart path attached it afterwards; on a cold boot nothing in the kernel did and hci0 came up only when a userspace script reloaded btcentauri (51 s after boot on J815 boot feb7dfb0, against ~15 s for Wi-Fi). After the IPC start step and after a restart, wait up to 10 s for Beta's firmware (exec stage 2, IPC unowned: the state btcentauri checks), then attach the function. The restart path's immediate attach could race the same firmware start; it now uses the same helper. btcentauri's early probe was logged as two errors on every boot; the state is expected, so log it at info level and return -ENXIO, which the driver core does not report as a failed probe. Signed-off-by: Nick --- drivers/bluetooth/btcentauri.c | 13 +++-- .../net/wireless/apple/centauri/centauri.h | 1 + .../wireless/apple/centauri/centauri_ipc.c | 11 ++++ .../wireless/apple/centauri/centauri_pci.c | 57 +++++++++++++++---- 4 files changed, 66 insertions(+), 16 deletions(-) diff --git a/drivers/bluetooth/btcentauri.c b/drivers/bluetooth/btcentauri.c index 7ae66124aa7ce2..f51f787753c82a 100644 --- a/drivers/bluetooth/btcentauri.c +++ b/drivers/bluetooth/btcentauri.c @@ -1040,10 +1040,15 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (ret) return ret; bt->bar = pcim_iomap_table(pdev)[0]; - if (readl(bt->bar + 0x18) != 2 || readl(bt->bar) != 0) - return dev_err_probe(&pdev->dev, -EBUSY, - "Beta requires running firmware and unowned IPC (exec=%u ipc=%u)\n", - readl(bt->bar + 0x18), readl(bt->bar)); + /* + * The function appears with the N1's IPC start, before Beta's firmware runs. + * apple_centauri attaches it again once that firmware is up. + */ + if (readl(bt->bar + 0x18) != 2 || readl(bt->bar) != 0) { + dev_info(&pdev->dev, "waiting for Beta's firmware (exec=%u ipc=%u)\n", + readl(bt->bar + 0x18), readl(bt->bar)); + return -ENXIO; + } ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(40)); if (ret) return ret; diff --git a/drivers/net/wireless/apple/centauri/centauri.h b/drivers/net/wireless/apple/centauri/centauri.h index e24614ab66aab5..17abbfb8352f29 100644 --- a/drivers/net/wireless/apple/centauri/centauri.h +++ b/drivers/net/wireless/apple/centauri/centauri.h @@ -104,6 +104,7 @@ static inline const struct centauri_board *centauri_board(void) int centauri_port_cycle(struct pci_dev *pdev, int *reset_ret); bool centauri_warm_reset_described(struct pci_dev *pdev); int centauri_start_ipc(struct centauri *c); +bool centauri_beta_running(struct centauri *c); void centauri_free_ipc(struct centauri *c); int centauri_alpha_resources(struct centauri *c, struct cen_alpha_resources *resources); int centauri_alpha_log_buffer(struct centauri *c, void **cpu, dma_addr_t *dma, size_t *size); diff --git a/drivers/net/wireless/apple/centauri/centauri_ipc.c b/drivers/net/wireless/apple/centauri/centauri_ipc.c index a94ff01dc440bd..d657e6a4b53747 100644 --- a/drivers/net/wireless/apple/centauri/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/centauri_ipc.c @@ -552,6 +552,17 @@ int centauri_start_ipc(struct centauri *c) return ret; } +/* + * Whether Beta's (Bluetooth's) firmware runs with its IPC still unowned: the state + * btcentauri needs to take function 2. Called with the boot lock held. + */ +bool centauri_beta_running(struct centauri *c) +{ + void __iomem *bar = c->ipc ? c->ipc->bar[2] : NULL; + + return bar && readl(bar + 0x18) == 2 && !readl(bar); +} + void centauri_free_ipc(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; diff --git a/drivers/net/wireless/apple/centauri/centauri_pci.c b/drivers/net/wireless/apple/centauri/centauri_pci.c index 332d9040170b71..67d3a7884759f6 100644 --- a/drivers/net/wireless/apple/centauri/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/centauri_pci.c @@ -260,11 +260,46 @@ void centauri_recovery_request(struct centauri *c, const char *why) dev_warn(&c->pdev->dev, "firmware fault (%s); checking again in 2 s\n", why); } +static bool centauri_beta_up(struct centauri *c) +{ + bool up; + + mutex_lock(&c->boot_lock); + up = READ_ONCE(c->removing) || centauri_beta_running(c); + mutex_unlock(&c->boot_lock); + return up; +} + +/* + * The IPC start's rescan adds the Beta (Bluetooth) function before Beta's firmware runs, + * so btcentauri cannot take it then. Wait for that firmware and attach the function. + * Called without the boot lock and outside the PCI rescan lock. Returns 1 when + * function 2 has a driver, 0 when none took it, or a negative error. + */ +static int centauri_attach_beta(struct centauri *c) +{ + struct pci_dev *beta; + bool up; + int ret; + + beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); + if (!beta) + return -ENODEV; + ret = 1; + if (!READ_ONCE(beta->dev.driver)) { + ret = read_poll_timeout(centauri_beta_up, up, up, 20 * USEC_PER_MSEC, + 10 * USEC_PER_SEC, false, c); + if (!ret) + ret = READ_ONCE(c->removing) ? -ENODEV : device_attach(&beta->dev); + } + pci_dev_put(beta); + return ret; +} + static void centauri_recover_worker(struct work_struct *work) { struct centauri *c = container_of(to_delayed_work(work), struct centauri, recover_work); struct device *dev = &c->pdev->dev; - struct pci_dev *beta; unsigned long now = jiffies; int ret; @@ -304,17 +339,7 @@ static void centauri_recover_worker(struct work_struct *work) queue_delayed_work(centauri_wq, &c->recover_work, 10 * HZ); return; } - /* - * The IPC start's rescan added the Beta function before its firmware ran, so - * btcentauri refused it then. Attach it now, outside the rescan lock. - */ - beta = pci_get_slot(c->pdev->bus, PCI_DEVFN(PCI_SLOT(c->pdev->devfn), 2)); - if (beta && !beta->dev.driver) - dev_info(dev, "restarted; Bluetooth function attach: %d\n", - device_attach(&beta->dev)); - else - dev_info(dev, "restarted\n"); - pci_dev_put(beta); + dev_info(dev, "restarted; Bluetooth function attach: %d\n", centauri_attach_beta(c)); } static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, @@ -350,6 +375,14 @@ static ssize_t centauri_boot_write(struct file *file, const char __user *buffer, } } mutex_unlock(&c->boot_lock); + if (value == 3 && !ret) { + int attached = centauri_attach_beta(c); + + if (attached == 1) + dev_info(&c->pdev->dev, "Bluetooth function attached\n"); + else + dev_warn(&c->pdev->dev, "Bluetooth function not attached: %d\n", attached); + } return ret ?: count; } From 1a272cebf27410bf936f20d80115ef82b0d14d0b Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 07:38:14 +0300 Subject: [PATCH 1260/1514] Bluetooth: btcentauri: Deliver ACL data by default The T8142 Beta transport already carries ACL data: BR/EDR on rings 2 and 8, LE on rings 4 and 10. Delivery was opt-in (enable_acl), and it needed arm_auxiliary_rings, which opens every auxiliary ring and allocates a 1 MiB private capture of what they receive. Without both, hci0 comes up and scans, but no device can connect: pairing, HID and audio all need ACL. Turn ACL delivery on by default and arm only the two ACL rings for it. The other auxiliary rings and the capture move behind a new diagnostic_capture parameter; the frames on them are not delivered either way. enable_acl=0 still gives the command and event transport alone. Signed-off-by: Nick --- drivers/bluetooth/btcentauri.c | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/drivers/bluetooth/btcentauri.c b/drivers/bluetooth/btcentauri.c index 7ae66124aa7ce2..c33b8a616e87db 100644 --- a/drivers/bluetooth/btcentauri.c +++ b/drivers/bluetooth/btcentauri.c @@ -49,9 +49,13 @@ static bool arm_le_data_rings = true; module_param(arm_le_data_rings, bool, 0444); MODULE_PARM_DESC(arm_le_data_rings, "Arm native Beta LE rings for radio bring-up"); -static bool arm_auxiliary_rings; +static bool arm_auxiliary_rings = true; module_param(arm_auxiliary_rings, bool, 0444); -MODULE_PARM_DESC(arm_auxiliary_rings, "Diagnostic: arm remaining native Beta resources and capture received frames privately"); +MODULE_PARM_DESC(arm_auxiliary_rings, "Arm Beta's ACL data rings"); + +static bool diagnostic_capture; +module_param(diagnostic_capture, bool, 0444); +MODULE_PARM_DESC(diagnostic_capture, "Diagnostic: arm every auxiliary ring and capture received frames privately; requires the auxiliary rings"); static bool native_startup; module_param(native_startup, bool, 0444); @@ -73,7 +77,7 @@ static bool accept_list; module_param(accept_list, bool, 0444); MODULE_PARM_DESC(accept_list, "Let the controller filter LE scans by its accept list (off: report its size as 0, the host filters)"); -static bool enable_acl; +static bool enable_acl = true; module_param(enable_acl, bool, 0444); MODULE_PARM_DESC(enable_acl, "Experimental ACL data delivery; requires LE and auxiliary rings"); @@ -90,8 +94,8 @@ struct cen_aux_spec { bool receive; }; -/* Host native Beta inventory; each resource is opt-in until target-qualified. - * HCI and LE rings remain in their existing, separately qualified arenas. +/* Beta's auxiliary rings. Only the ACL rings (2 and 8) are armed by default; the + * others only with diagnostic_capture. HCI and LE rings have their own arenas. */ static const struct cen_aux_spec cen_aux_specs[] = { { 2, 9, 2592, false }, /* ACL TX */ @@ -110,6 +114,7 @@ static const struct cen_aux_spec cen_aux_specs[] = { struct cen_aux_state { u32 offset, packets; u16 head, post; + bool opened; }; struct cen_bt { @@ -318,11 +323,14 @@ static int cen_aux_start(struct cen_bt *bt) return -ENOSPC; state->offset = offset; offset = ALIGN(offset + length, SZ_4K); + if (!diagnostic_capture && spec->id != 2 && spec->id != 8) + continue; ret = cen_open_ring(bt, spec->id, spec->slots, state->offset, spec->footer); if (ret) { dev_err(&bt->pdev->dev, "Auxiliary ring %u open failed: %d\n", spec->id, ret); return ret; } + state->opened = true; if (!spec->receive) continue; for (slot = 0; slot < spec->slots - 1; slot++) @@ -343,7 +351,7 @@ static int cen_aux_drain(struct cen_bt *bt, bool repost) u16 tail; int budget = spec->slots; - if (!spec->receive) + if (!state->opened || !spec->receive) continue; tail = cen_tail(bt, spec->id); if (tail >= spec->slots) @@ -951,7 +959,7 @@ static int cen_status_show(struct seq_file *s, void *unused) bt->capture_used, bt->capture_records, bt->capture_dropped); if (arm_auxiliary_rings) for (i = 0; i < ARRAY_SIZE(cen_aux_specs); i++) - if (cen_aux_specs[i].receive) + if (cen_aux_specs[i].receive && bt->aux[i].opened) seq_printf(s, "aux_rx ring=%u packets=%u consumed=%u device_tail=%u\n", cen_aux_specs[i].id, bt->aux[i].packets, bt->aux[i].head, cen_tail(bt, cen_aux_specs[i].id)); @@ -1028,6 +1036,8 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) skb_queue_head_init(&bt->le_txq); if (enable_acl && (!arm_le_data_rings || !arm_auxiliary_rings)) return -EINVAL; + if (diagnostic_capture && !arm_auxiliary_rings) + return -EINVAL; if (native_hrb && (!native_startup || !enable_acl)) return -EINVAL; INIT_DELAYED_WORK(&bt->poll, cen_poll); @@ -1051,7 +1061,7 @@ static int cen_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (!bt->arena) return -ENOMEM; memset(bt->arena, 0, CEN_ARENA_SIZE); - if (arm_auxiliary_rings) { + if (diagnostic_capture) { bt->capture = kvzalloc(CEN_CAPTURE_SIZE, GFP_KERNEL); if (!bt->capture) { ret = -ENOMEM; From 179870860f0b90885f001595d9ec28eda17477c2 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:52:00 -0500 Subject: [PATCH 1261/1514] drm/asahi: derive thermal-zone limits from machine trips and read host-block before zeroing Remove hardcoded thermal-zone trip temperatures from the G16/G15S thermal-zone backstop and read passive/active/hot/critical trip limits from the kernel thermal zone via thermal_zone_for_each_trip(), failing closed at S1 whenever the machine provides no valid trip limits. Track a monotonic poller sequence counter in asahi_g16_cooling so repeated reads of a single cached temperature cannot satisfy the 10-reading startup confirmation; confirmation now requires 10 distinct fresh sensor polls. Perform a read before zeroing each host-block control register in publish_host_block() and document the G15S host-block control offsets cleanly. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/glue.c | 142 ++++++++++- drivers/gpu/drm/asahi/g16/hw.rs | 3 + drivers/gpu/drm/asahi/g16/power.rs | 27 ++ drivers/gpu/drm/asahi/g16/power/policy.rs | 297 +++++++++++++++++----- drivers/gpu/drm/asahi/g16/regs.rs | 5 +- 5 files changed, 404 insertions(+), 70 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 882e2657bf098a..bf20149d6c84dc 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -46,7 +46,6 @@ bool asahi_g16_dma_unsupported(struct device *dev); */ #define ASAHI_G16_ZONE_POLL_FAST_MS 250 #define ASAHI_G16_ZONE_POLL_IDLE_MS 1000 -#define ASAHI_G16_ZONE_HOT_POLL_MC 75000 #define ASAHI_G16_ZONE_STALE_NS 3000000000ULL static const char * const asahi_g16_die_zones[] = { @@ -54,6 +53,15 @@ static const char * const asahi_g16_die_zones[] = { "apple_pmp_hotspot", }; +struct asahi_g16_zone_trips { + long release_mc; + long hot_mc; + long critical_mc; + long max_passive_mc; + bool have_hot; + bool have_critical; +}; + struct asahi_g16_cooling { atomic_t state; struct apple_pmp_gpu *pmp; @@ -68,16 +76,23 @@ struct asahi_g16_cooling { struct delayed_work zone_poll; atomic_t zone_active; atomic_t stopping; + u64 zone_seq; u64 zone_ns; long zone_mc; + long zone_release_mc; + long zone_hot_mc; + long zone_critical_mc; + bool zone_limits_valid; int zone_err; }; struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev); void asahi_g16_cooling_unregister(struct asahi_g16_cooling *cooling); int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool idle, - long *temperature, u32 *governor, u32 *power, - u32 *backstop); + long *temperature, u32 *governor, u32 *power, + u32 *backstop, u64 *zone_seq, long *release_mc, + long *hot_mc, long *critical_mc, + bool *limits_valid); int asahi_g16_clpc_gpu_get(struct device *dev, struct apple_clpc_gpu **out); void asahi_g16_clpc_gpu_set_active(struct apple_clpc_gpu *gpu, bool active); void asahi_g16_clpc_gpu_put(struct apple_clpc_gpu *gpu); @@ -115,13 +130,79 @@ static const struct thermal_cooling_device_ops asahi_g16_cooling_ops = { .set_cur_state = asahi_g16_cooling_set, }; +static int asahi_g16_zone_trip_cb(struct thermal_trip *trip, void *data) +{ + struct asahi_g16_zone_trips *t = data; + long temp = trip->temperature; + long hyst = trip->hysteresis; + + if (temp == THERMAL_TEMP_INVALID || temp <= 0) + return 0; + + switch (trip->type) { + case THERMAL_TRIP_PASSIVE: + if (temp > t->max_passive_mc) + t->max_passive_mc = temp; + fallthrough; + case THERMAL_TRIP_ACTIVE: + if (!t->have_hot || temp < t->hot_mc) { + t->hot_mc = temp; + t->release_mc = (hyst >= 0 && hyst < temp) ? + temp - hyst : 0; + t->have_hot = true; + } + break; + case THERMAL_TRIP_HOT: + case THERMAL_TRIP_CRITICAL: + if (!t->have_critical || temp < t->critical_mc) { + t->critical_mc = temp; + t->have_critical = true; + } + break; + default: + break; + } + return 0; +} + +static bool asahi_g16_zone_read_limits(const char *name, long *release_mc, + long *hot_mc, long *critical_mc) +{ + struct asahi_g16_zone_trips trips = {}; + struct thermal_zone_device *tz; + + tz = thermal_zone_get_zone_by_name(name); + if (IS_ERR(tz)) + return false; + if (thermal_zone_for_each_trip(tz, asahi_g16_zone_trip_cb, &trips)) + return false; + if (!trips.have_critical && trips.have_hot && + trips.max_passive_mc > trips.hot_mc) { + trips.critical_mc = trips.max_passive_mc; + trips.have_critical = true; + } + if (!trips.have_hot || !trips.have_critical || + trips.release_mc <= 0 || trips.release_mc > trips.hot_mc || + trips.critical_mc <= trips.hot_mc) + return false; + + *release_mc = trips.release_mc; + *hot_mc = trips.hot_mc; + *critical_mc = trips.critical_mc; + return true; +} + static void asahi_g16_zone_poll_fn(struct work_struct *work) { struct asahi_g16_cooling *cooling = container_of(to_delayed_work(work), struct asahi_g16_cooling, zone_poll); long hottest = 0; + long release_mc = 0; + long hot_mc = 0; + long critical_mc = 0; bool found = false; + bool limits_valid = false; int ret = -ENODEV; unsigned int i; unsigned int delay_ms; @@ -130,6 +211,7 @@ static void asahi_g16_zone_poll_fn(struct work_struct *work) return; for (i = 0; i < ARRAY_SIZE(asahi_g16_die_zones); i++) { + long z_rel = 0, z_hot = 0, z_crit = 0; int temp = 0; int err = thermal_zone_get_temp_by_name(asahi_g16_die_zones[i], &temp); @@ -138,26 +220,50 @@ static void asahi_g16_zone_poll_fn(struct work_struct *work) if (!found || temp > hottest) hottest = temp; found = true; + + if (asahi_g16_zone_read_limits(asahi_g16_die_zones[i], + &z_rel, &z_hot, + &z_crit)) { + if (!limits_valid) { + release_mc = z_rel; + hot_mc = z_hot; + critical_mc = z_crit; + limits_valid = true; + } else { + release_mc = min(release_mc, z_rel); + hot_mc = min(hot_mc, z_hot); + critical_mc = min(critical_mc, z_crit); + } + } } else if (err != -ENODEV) { ret = err; found = false; + limits_valid = false; break; } } if (found) ret = 0; + if (!found || !limits_valid || release_mc <= 0 || + release_mc > hot_mc || critical_mc <= hot_mc) + limits_valid = false; spin_lock(&cooling->zone_lock); + cooling->zone_seq++; cooling->zone_ns = ktime_get_ns(); cooling->zone_mc = found ? hottest : 0; + cooling->zone_release_mc = limits_valid ? release_mc : 0; + cooling->zone_hot_mc = limits_valid ? hot_mc : 0; + cooling->zone_critical_mc = limits_valid ? critical_mc : 0; + cooling->zone_limits_valid = limits_valid; cooling->zone_err = ret; spin_unlock(&cooling->zone_lock); if (atomic_read(&cooling->stopping)) return; - delay_ms = (ret || atomic_read(&cooling->zone_active) || - hottest >= ASAHI_G16_ZONE_HOT_POLL_MC) ? + delay_ms = (ret || !limits_valid || atomic_read(&cooling->zone_active) || + hottest >= release_mc) ? ASAHI_G16_ZONE_POLL_FAST_MS : ASAHI_G16_ZONE_POLL_IDLE_MS; queue_delayed_work(system_freezable_wq, &cooling->zone_poll, @@ -235,24 +341,38 @@ bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling) * fail closed whenever no fresh reading is available. */ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool idle, - long *temperature, u32 *governor, u32 *power, - u32 *backstop) + long *temperature, u32 *governor, u32 *power, + u32 *backstop, u64 *zone_seq, long *release_mc, + long *hot_mc, long *critical_mc, + bool *limits_valid) { int ret; *temperature = 0; + *zone_seq = 0; + *release_mc = 0; + *hot_mc = 0; + *critical_mc = 0; + *limits_valid = false; if (!cooling->pmp_node) { - u64 zone_ns; - long zone_mc; + u64 seq, zone_ns; + long zone_mc, rel, hot, crit; + bool valid; int zone_err; atomic_set(&cooling->zone_active, !idle); spin_lock(&cooling->zone_lock); + seq = cooling->zone_seq; zone_ns = cooling->zone_ns; zone_mc = cooling->zone_mc; + rel = cooling->zone_release_mc; + hot = cooling->zone_hot_mc; + crit = cooling->zone_critical_mc; + valid = cooling->zone_limits_valid; zone_err = cooling->zone_err; spin_unlock(&cooling->zone_lock); + *zone_seq = seq; if (!zone_ns) ret = -ENODATA; else if (zone_err) @@ -261,6 +381,10 @@ int asahi_g16_cooling_sample(struct asahi_g16_cooling *cooling, u64 now, bool id ret = -ETIMEDOUT; else { *temperature = zone_mc; + *release_mc = rel; + *hot_mc = hot; + *critical_mc = crit; + *limits_valid = valid; ret = 0; } *governor = atomic_read(&cooling->state); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 908297e82e417d..6ef83987bb29e0 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -340,6 +340,9 @@ pub(crate) mod t6030 { power_offset: 0x110, fault_banks: 2, axi2af: false, + // Host-block control words zeroed read-before-write at cold 26B123 startup: + // +0x0000 is the host device-control generation word; +0x1808 and +0x3010 are the + // per-pipe host-block control words cleared before endpoints 0x20/0x21 start. host_block_zero_order: &[0, 0x1808, 0x3010], host_block_ready: false, deep_sleep: false, diff --git a/drivers/gpu/drm/asahi/g16/power.rs b/drivers/gpu/drm/asahi/g16/power.rs index bed5e2432fcf4d..e476ccb497bb22 100644 --- a/drivers/gpu/drm/asahi/g16/power.rs +++ b/drivers/gpu/drm/asahi/g16/power.rs @@ -50,6 +50,11 @@ extern "C" { governor: *mut u32, power: *mut u32, backstop: *mut u32, + zone_seq: *mut u64, + release_mc: *mut core::ffi::c_long, + hot_mc: *mut core::ffi::c_long, + critical_mc: *mut core::ffi::c_long, + limits_valid: *mut bool, ) -> i32; } @@ -87,6 +92,11 @@ impl Cooling { fn sample(&mut self, now: u64, idle: bool, power: &mut Sample) -> Result { let mut mc: core::ffi::c_long = 0; + let mut seq: u64 = 0; + let mut release_mc: core::ffi::c_long = 0; + let mut hot_mc: core::ffi::c_long = 0; + let mut critical_mc: core::ffi::c_long = 0; + let mut limits_valid = false; // SAFETY: The C allocation and PMP phandle outlive this call, all output // pointers are valid, and the caller holds the GPU device mutex. let ret = unsafe { @@ -98,9 +108,20 @@ impl Cooling { &mut power.governor, &mut power.budget, &mut power.backstop, + &mut seq, + &mut release_mc, + &mut hot_mc, + &mut critical_mc, + &mut limits_valid, ) }; power.temperature_mc = mc as i64; + power.zone_seq = seq; + power.zone_limits = limits_valid.then_some(policy::ZoneLimits { + release_mc: release_mc as i64, + hot_mc: hot_mc as i64, + critical_mc: critical_mc as i64, + }); kernel::error::to_result(ret) } } @@ -119,6 +140,8 @@ struct Sample { governor: u32, budget: u32, backstop: u32, + zone_seq: u64, + zone_limits: Option, } /// DT-selected memory-demand provider (`apple,clpc`), or none. Its @@ -204,6 +227,8 @@ impl Power { governor: pmp_initial, budget: pmp_initial, backstop: COOLING_MAX, + zone_seq: 0, + zone_limits: None, }, last_sample_ns: None, top: TOP_DEFAULT, @@ -271,7 +296,9 @@ impl Power { if !self.cooling.is_pmp { self.zone_backstop.sample( now, + self.sample.zone_seq, self.sample.temperature_mc, + self.sample.zone_limits, self.sensor_error.is_some(), ); self.zone_backstop.observe(now, self.sample.governor); diff --git a/drivers/gpu/drm/asahi/g16/power/policy.rs b/drivers/gpu/drm/asahi/g16/power/policy.rs index 53310885d53ed8..f901963045023b 100644 --- a/drivers/gpu/drm/asahi/g16/power/policy.rs +++ b/drivers/gpu/drm/asahi/g16/power/policy.rs @@ -304,41 +304,57 @@ impl Governor { } } -/// Plausible SoC die temperature range (millidegrees Celsius) for thermal-zone cooling. -pub(crate) const ZONE_PLAUSIBLE_MIN_MC: i64 = 10_000; -pub(crate) const ZONE_PLAUSIBLE_MAX_MC: i64 = 125_000; -/// Thermal-zone cooling thresholds (millidegrees Celsius) for SoCs without an `apple,pmp` -/// telemetry bridge. Kept conservative relative to the GPU die target because SMC die -/// sensors can read cooler than the hottest GPU spot. -pub(crate) const ZONE_RELEASE_MC: i64 = 75_000; -pub(crate) const ZONE_HOT_MC: i64 = 80_000; -pub(crate) const ZONE_STEP_MC: i64 = 2_000; -pub(crate) const ZONE_FULL_COOLING_MC: i64 = ZONE_HOT_MC + (COOLING_MAX as i64 - 1) * ZONE_STEP_MC; -/// Startup/fault confirmation cadence (20 ms x 10 = 200 ms) and gradual release step. +/// Startup/fault confirmation cadence (minimum spacing across 10 distinct sensor polls) +/// and gradual cooling-release step interval. pub(crate) const ZONE_CONFIRM_NS: u64 = 20_000_000; pub(crate) const ZONE_CONFIRM_READS: u32 = 10; pub(crate) const ZONE_RELEASE_NS: u64 = 200_000_000; -/// Cooling level for a measured thermal-zone die temperature: 0 below 80 C, 1..=7 from -/// 80..94 C in 2 C steps, and [`COOLING_MAX`] at or above 94 C. -pub(crate) fn zone_heat_level(mc: i64) -> u32 { - if mc < ZONE_HOT_MC { +/// Machine-supplied thermal-zone trip limits (millidegrees Celsius) read from the kernel +/// thermal zone (`passive`/`active` trip with hysteresis, and `hot`/`critical` trip). +/// If the machine provides no valid limits, [`ZoneBackstop`] fails closed at [`COOLING_MAX`] (S1). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct ZoneLimits { + pub(crate) release_mc: i64, + pub(crate) hot_mc: i64, + pub(crate) critical_mc: i64, +} + +impl ZoneLimits { + pub(crate) const fn is_valid(&self) -> bool { + self.release_mc > 0 && self.release_mc <= self.hot_mc && self.critical_mc > self.hot_mc + } +} + +/// Cooling level for a measured thermal-zone die temperature against machine-supplied trip +/// limits: 0 below `hot_mc`, 1..=7 linearly across `hot_mc..critical_mc`, and [`COOLING_MAX`] +/// at or above `critical_mc` (or whenever `limits` are invalid). +pub(crate) fn zone_heat_level(mc: i64, limits: ZoneLimits) -> u32 { + if !limits.is_valid() { + return COOLING_MAX; + } + if mc < limits.hot_mc { 0 - } else if mc >= ZONE_FULL_COOLING_MC { + } else if mc >= limits.critical_mc { COOLING_MAX } else { - (((mc - ZONE_HOT_MC) / ZONE_STEP_MC) as u32 + 1).min(COOLING_MAX) + let span = limits.critical_mc - limits.hot_mc; + let delta = mc - limits.hot_mc; + let steps = (COOLING_MAX - 1) as i64; + (((delta * steps) / span) as u32 + 1).min(COOLING_MAX) } } /// Fail-closed thermal backstop driven by kernel SoC die thermal zones when a GPU DT node -/// has no `apple,pmp` telemetry bridge. Starts at [`COOLING_MAX`] (S1), requires 200 ms of -/// valid cool readings before stepping down gradually, and immediately clamps back to -/// [`COOLING_MAX`] on missing, stale, implausible, or critical readings. +/// has no `apple,pmp` telemetry bridge. Starts at [`COOLING_MAX`] (S1), requires +/// [`ZONE_CONFIRM_READS`] distinct fresh sensor polls with valid machine-supplied trip limits +/// before stepping down gradually, and immediately clamps back to [`COOLING_MAX`] on missing, +/// stale, unconfigured, or critical readings. pub(crate) struct ZoneBackstop { level: u32, hard: bool, good_reads: u32, + last_seq: u64, good_ns: u64, release_ns: u64, } @@ -349,6 +365,7 @@ impl ZoneBackstop { level: COOLING_MAX, hard: true, good_reads: 0, + last_seq: 0, good_ns: 0, release_ns: 0, } @@ -358,23 +375,46 @@ impl ZoneBackstop { self.level } - /// Incorporates one sampled temperature (millidegrees Celsius) or sensor error at `now`. - pub(crate) fn sample(&mut self, now: u64, mc: i64, error: bool) -> u32 { - if error - || !(ZONE_PLAUSIBLE_MIN_MC..=ZONE_PLAUSIBLE_MAX_MC).contains(&mc) - || mc >= ZONE_FULL_COOLING_MC - { + /// Incorporates one sampled temperature (millidegrees Celsius), poller sequence `seq`, + /// machine-supplied `limits`, or sensor `error` at `now`. + pub(crate) fn sample( + &mut self, + now: u64, + seq: u64, + mc: i64, + limits: Option, + error: bool, + ) -> u32 { + let Some(limits) = limits.filter(ZoneLimits::is_valid) else { + self.level = COOLING_MAX; + self.hard = true; + self.good_reads = 0; + if seq != 0 { + self.last_seq = seq; + } + self.good_ns = now; + self.release_ns = now; + return self.level; + }; + + if error || seq == 0 || mc <= 0 || mc >= limits.critical_mc { self.level = COOLING_MAX; self.hard = true; self.good_reads = 0; + if seq != 0 { + self.last_seq = seq; + } self.good_ns = now; self.release_ns = now; return self.level; } + let fresh = seq != self.last_seq; if self.hard { - if mc < ZONE_HOT_MC { - if self.good_reads == 0 || now.wrapping_sub(self.good_ns) >= ZONE_CONFIRM_NS { + if mc < limits.hot_mc { + let due = self.good_reads == 0 || now.wrapping_sub(self.good_ns) >= ZONE_CONFIRM_NS; + if fresh && due { + self.last_seq = seq; self.good_ns = now; self.good_reads = self.good_reads.saturating_add(1).min(ZONE_CONFIRM_READS); } @@ -382,6 +422,7 @@ impl ZoneBackstop { self.hard = false; } } else { + self.last_seq = seq; self.good_reads = 0; self.good_ns = now; } @@ -391,14 +432,20 @@ impl ZoneBackstop { } } - let target = zone_heat_level(mc); + if fresh { + self.last_seq = seq; + } + let target = zone_heat_level(mc, limits); if target > self.level { self.level = target; self.release_ns = now; - } else if mc < ZONE_RELEASE_MC && now.wrapping_sub(self.release_ns) >= ZONE_RELEASE_NS { + } else if fresh + && mc < limits.release_mc + && now.wrapping_sub(self.release_ns) >= ZONE_RELEASE_NS + { self.level = self.level.saturating_sub(1); self.release_ns = now; - } else if mc >= ZONE_RELEASE_MC { + } else if mc >= limits.release_mc { self.release_ns = now; } self.level @@ -779,68 +826,200 @@ mod tests { #[test] fn zone_backstop_starts_fail_closed_releases_gradually_and_clamps_on_heat_or_fault() { + let limits = ZoneLimits { + release_mc: 75_000, + hot_mc: 80_000, + critical_mc: 94_000, + }; let mut z = ZoneBackstop::new(); assert_eq!(z.level(), COOLING_MAX); assert_eq!(cooling_ceiling(8, z.level()), 1); - // Missing or implausible sensors keep the GPU clamped at S1 forever. - for i in 0..20u64 { - assert_eq!(z.sample(T + i * ZONE_CONFIRM_NS, 0, true), COOLING_MAX); + // Missing or invalid machine trip limits keep the GPU clamped at S1 forever. + for i in 1..=20u64 { + assert_eq!( + z.sample(T + i * ZONE_CONFIRM_NS, i, 55_000, None, false), + COOLING_MAX + ); } - assert_eq!(z.sample(T + 1_000_000_000, 9_999, false), COOLING_MAX); - assert_eq!(z.sample(T + 1_020_000_000, 125_001, false), COOLING_MAX); + let bad_limits = ZoneLimits { + release_mc: 80_000, + hot_mc: 80_000, + critical_mc: 80_000, + }; + assert_eq!( + z.sample(T + 500_000_000, 21, 55_000, Some(bad_limits), false), + COOLING_MAX + ); - // Repeated calls at the same timestamp cannot accelerate startup confirmation. + // Sensor errors or non-positive readings keep the GPU clamped at S1. + assert_eq!( + z.sample(T + 1_000_000_000, 22, 0, Some(limits), true), + COOLING_MAX + ); + assert_eq!( + z.sample(T + 1_020_000_000, 23, 0, Some(limits), false), + COOLING_MAX + ); + + // Repeated reads of a single cached temperature (unchanged seq) CANNOT satisfy + // startup confirmation even as timestamps advance past 10 * ZONE_CONFIRM_NS. let base = T + 2_000_000_000; - for _ in 0..100 { - assert_eq!(z.sample(base, 55_000, false), COOLING_MAX); + let cached_seq = 100u64; + for step in 0..50u64 { + assert_eq!( + z.sample( + base + step * ZONE_CONFIRM_NS, + cached_seq, + 55_000, + Some(limits), + false + ), + COOLING_MAX + ); } + // Advancing past release interval with the same cached seq still stays at S1. + assert_eq!( + z.sample( + base + 60 * ZONE_CONFIRM_NS + ZONE_RELEASE_NS, + cached_seq, + 55_000, + Some(limits), + false + ), + COOLING_MAX + ); + + // 9 more distinct fresh sensor polls complete the 10-poll startup confirmation. + let fresh_base = base + 60 * ZONE_CONFIRM_NS + 2 * ZONE_RELEASE_NS; for step in 1..ZONE_CONFIRM_READS as u64 { assert_eq!( - z.sample(base + step * ZONE_CONFIRM_NS, 55_000, false), + z.sample( + fresh_base + step * ZONE_CONFIRM_NS, + cached_seq + step, + 55_000, + Some(limits), + false + ), COOLING_MAX ); } - // Gradual release: one cooling level every 200 ms below 75 C. - let confirmed = base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + // Gradual release: one cooling level per fresh poll every 200 ms below release_mc. + let confirmed = fresh_base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + let mut seq = cached_seq + ZONE_CONFIRM_READS as u64; assert_eq!( - z.sample(confirmed + ZONE_RELEASE_NS - 1, 55_000, false), + z.sample(confirmed + ZONE_RELEASE_NS - 1, seq, 55_000, Some(limits), false), COOLING_MAX ); for step in 1..=COOLING_MAX as u64 { + seq += 1; assert_eq!( - z.sample(confirmed + step * ZONE_RELEASE_NS, 55_000, false), + z.sample( + confirmed + step * ZONE_RELEASE_NS, + seq, + 55_000, + Some(limits), + false + ), COOLING_MAX - step as u32 ); } assert_eq!(z.level(), 0); assert_eq!(cooling_ceiling(8, z.level()), 8); - // Progressive heat throttling from 80 C..94 C, immediate hard clamp at >= 94 C. + // Progressive heat throttling across hot_mc..critical_mc, hard clamp at >= critical_mc. let hot_t = confirmed + 10 * ZONE_RELEASE_NS; - assert_eq!(z.sample(hot_t, 79_999, false), 0); - assert_eq!(z.sample(hot_t + 10_000_000, 80_000, false), 1); - assert_eq!(z.sample(hot_t + 20_000_000, 86_000, false), 4); - // Holding between 75 C and 80 C does not release cooling. - assert_eq!(z.sample(hot_t + 500_000_000, 75_000, false), 4); - assert_eq!(z.sample(hot_t + 1_000_000_000, 79_000, false), 4); + seq += 1; + assert_eq!(z.sample(hot_t, seq, 79_999, Some(limits), false), 0); + seq += 1; + assert_eq!(z.sample(hot_t + 10_000_000, seq, 80_000, Some(limits), false), 1); + seq += 1; + assert_eq!(z.sample(hot_t + 20_000_000, seq, 86_000, Some(limits), false), 4); + // Holding between release_mc and hot_mc does not release cooling. + seq += 1; + assert_eq!( + z.sample(hot_t + 500_000_000, seq, 75_000, Some(limits), false), + 4 + ); + seq += 1; + assert_eq!( + z.sample(hot_t + 1_000_000_000, seq, 79_000, Some(limits), false), + 4 + ); // Critical heat immediately returns to hard COOLING_MAX (S1). - assert_eq!(z.sample(hot_t + 1_010_000_000, ZONE_FULL_COOLING_MC, false), COOLING_MAX); + seq += 1; + assert_eq!( + z.sample( + hot_t + 1_010_000_000, + seq, + limits.critical_mc, + Some(limits), + false + ), + COOLING_MAX + ); assert_eq!(cooling_ceiling(8, z.level()), 1); - // Governor observation is retained in the release envelope. + // Different machine-supplied trip limits govern dynamically without code constants. + let higher_limits = ZoneLimits { + release_mc: 85_000, + hot_mc: 90_000, + critical_mc: 104_000, + }; let mut z2 = ZoneBackstop::new(); - for step in 0..ZONE_CONFIRM_READS as u64 { - z2.sample(base + step * ZONE_CONFIRM_NS, 50_000, false); + for step in 1..=ZONE_CONFIRM_READS as u64 { + z2.sample( + base + step * ZONE_CONFIRM_NS, + step, + 84_000, + Some(higher_limits), + false, + ); } - let c2 = base + (ZONE_CONFIRM_READS as u64 - 1) * ZONE_CONFIRM_NS; + let c2 = base + (ZONE_CONFIRM_READS as u64) * ZONE_CONFIRM_NS; for step in 1..=COOLING_MAX as u64 { - z2.sample(c2 + step * ZONE_RELEASE_NS, 50_000, false); + z2.sample( + c2 + step * ZONE_RELEASE_NS, + ZONE_CONFIRM_READS as u64 + step, + 84_000, + Some(higher_limits), + false, + ); } assert_eq!(z2.level(), 0); + // 89 C is still below higher_limits.hot_mc (90 C). + assert_eq!( + z2.sample( + c2 + 9 * ZONE_RELEASE_NS, + 100, + 89_000, + Some(higher_limits), + false + ), + 0 + ); + // Governor observation is retained in the release envelope. z2.observe(c2 + 9 * ZONE_RELEASE_NS, 5); assert_eq!(z2.level(), 5); - assert_eq!(z2.sample(c2 + 9 * ZONE_RELEASE_NS + 1, 50_000, false), 5); - assert_eq!(z2.sample(c2 + 10 * ZONE_RELEASE_NS, 50_000, false), 4); + assert_eq!( + z2.sample( + c2 + 9 * ZONE_RELEASE_NS + 1, + 101, + 84_000, + Some(higher_limits), + false + ), + 5 + ); + assert_eq!( + z2.sample( + c2 + 10 * ZONE_RELEASE_NS, + 102, + 84_000, + Some(higher_limits), + false + ), + 4 + ); } } diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index 8ef5eeb106b7d5..7c0c4628ae4d01 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -319,12 +319,13 @@ impl Regs { Ok(()) } - /// 26B123 after AP power-on and before the GPU endpoints start: zeroes the host block, - /// and on G16G reads the scratch word and raises the ready word. + /// 26B123 after AP power-on and before the GPU endpoints start: reads then zeroes each + /// host-block control word, and on G16G reads the scratch word and raises the ready word. pub(crate) fn publish_host_block(&self, cfg: &super::Config) -> Result> { use super::hw::start_27_2 as s; let g = self.generation.io(); for &offset in cfg.host_block_zero_order { + let _ = g.try_read32(offset)?; g.try_write32(0, offset)?; } let probe = if cfg.host_block_ready { From 6799ef46c137770b3fcffa706cc99343f37fdae3 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:54:19 -0500 Subject: [PATCH 1262/1514] dt-bindings: apple: aop: scope aop-audio select to primary compatibles and add T603x motion Match apple,aop-audio.yaml select on the primary compatible rather than contains so T6041 and T8132 audio nodes (which carry apple,t6030-aop-audio as a fallback and are validated by apple,t6041-aop-audio.yaml) are not mis-selected, and include apple,t6000-aop-audio and apple,t8103-aop-audio in apple,aop-audio.yaml. Add apple,t6030-aop-{accel,gyro} and apple,t6031-aop-{accel,gyro} compatibles to apple,aop-motion.yaml. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .../bindings/iio/imu/apple,aop-motion.yaml | 4 ++++ .../bindings/sound/apple,aop-audio.yaml | 21 ++++++++++++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml b/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml index 2fe2474ee0987d..b682b877c3d7fe 100644 --- a/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml +++ b/Documentation/devicetree/bindings/iio/imu/apple,aop-motion.yaml @@ -26,6 +26,8 @@ properties: - items: - enum: - apple,t6000-aop-accel + - apple,t6030-aop-accel + - apple,t6031-aop-accel - apple,t6041-aop-accel - apple,t8112-aop-accel - apple,t8132-aop-accel @@ -33,6 +35,8 @@ properties: - items: - enum: - apple,t6000-aop-gyro + - apple,t6030-aop-gyro + - apple,t6031-aop-gyro - apple,t6041-aop-gyro - apple,t8112-aop-gyro - apple,t8132-aop-gyro diff --git a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml index 952fa583d183f1..5da4e92e751279 100644 --- a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml @@ -14,16 +14,21 @@ description: | calibration handoff determine its availability. It has no independent application-processor register window or interrupt. +# Match on the first compatible only: T6041 and T8132 also list +# apple,t6030-aop-audio as a fallback and are validated by +# apple,t6041-aop-audio.yaml. select: properties: compatible: - contains: - enum: - - apple,t6020-aop-audio - - apple,t6030-aop-audio - - apple,t6031-aop-audio - - apple,t8112-aop-audio - - apple,t8122-aop-audio + items: + - enum: + - apple,t6000-aop-audio + - apple,t6020-aop-audio + - apple,t6030-aop-audio + - apple,t6031-aop-audio + - apple,t8103-aop-audio + - apple,t8112-aop-audio + - apple,t8122-aop-audio required: - compatible @@ -32,7 +37,9 @@ properties: oneOf: - items: - enum: + - apple,t6000-aop-audio - apple,t6020-aop-audio + - apple,t8103-aop-audio - apple,t8112-aop-audio - const: apple,aop-audio - const: apple,t6030-aop-audio From 7879c0947f8041307bce285cf956306b2a945555 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:59:49 -0500 Subject: [PATCH 1263/1514] drm/apple: enforce v27 pins terminally and configure panels by DT capability Keep explicit match-data pins (T6050, T8142, T8132 M4, T8140 H17P) and image-UUID pins (T6041, T8122) ahead of generic dcp_firmware_27() admission in dcp_check_firmware_version(), making T8122 wrong or missing 27.2 UUIDs and internal T8142 unknown 27.x builds terminal refusals rather than taking generic firmware-27 or H17P. Configure firmware-27 internal panels from DT capabilities instead of SoC allowlists: verify available child routes inside typec-routes, derive firmware DMA width from the DCP DART apple,dma-range aperture when match data does not already set one (keeping DART-derived DMA widths on external profiles and only falling back when no aperture is supplied), exempt firmware-27 from the legacy apple,bw-scratch check, and restrict the single-clock disp0 fallback to internal-panel-only DCPs with exactly one unnamed clock so non-panel paths never fabricate clocks. Factor apple_t8122_dcpext_v27_2_for_internal() in include/linux/soc/apple/display.h and add KUnit coverage for T8122 internal/external, T6041 internal/external, T8142 (DCP_FIRMWARE_H17P on 26.6), T8132 pin precedence, terminal refusals, and typec-routes child availability. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp-firmware-test.c | 185 ++++++++++++++++++++++ drivers/gpu/drm/apple/dcp.c | 177 ++++++++++++++------- include/linux/soc/apple/display.h | 19 ++- 3 files changed, 316 insertions(+), 65 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-firmware-test.c b/drivers/gpu/drm/apple/dcp-firmware-test.c index b0990bb1c0f682..9a51e23fb6b7fc 100644 --- a/drivers/gpu/drm/apple/dcp-firmware-test.c +++ b/drivers/gpu/drm/apple/dcp-firmware-test.c @@ -100,10 +100,195 @@ static void dcp_firmware_27_empty_clock_table(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp_firmware_clocks_v27(dcp), -EINVAL); } +/* + * Explicit match-data and image-UUID pins stay ahead of generic firmware-27 + * admission: T8122 wrong/missing 27.2 UUIDs and internal T8142 unknown 27.x + * builds are terminally refused rather than using generic v27 or H17P, + * while generic refmac DCPs (T6030, T8112) take firmware 27 on complete 27.x + * method tables and refuse incomplete ones. + */ +static void dcp_firmware_27_pin_precedence(struct kunit *test) +{ + static const char t6030[] = "apple,t6030-dcp"; + static const char t6041[] = "apple,t6041-dcp\0apple,dcp"; + static const char t6041_ext[] = "apple,t6041-dcpext\0apple,dcpext"; + static const char t8122[] = "apple,t8122-dcp\0apple,dcp"; + static const char t8122_ext[] = "apple,t8122-dcpext\0apple,dcpext"; + static const char t8142[] = "apple,t8142-dcp"; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) + static const char t8132[] = "apple,t8132-dcp"; +#endif + static const char bad_uuid[] = "00000000-0000-0000-0000-000000000000"; + __be32 compat_26_6[] = { cpu_to_be32(26), cpu_to_be32(6), cpu_to_be32(2) }; + __be32 compat_27_0[] = { cpu_to_be32(27), 0, 0 }; + __be32 compat_27_1[] = { cpu_to_be32(27), cpu_to_be32(1), 0 }; + __be32 compat_27_2[] = { cpu_to_be32(27), cpu_to_be32(2), 0 }; + __be32 compat_27_3[] = { cpu_to_be32(27), cpu_to_be32(3), 0 }; + struct property props[] = { + { .name = "apple,firmware-compat", .length = sizeof(compat_27_2), + .value = compat_27_2, .next = &props[1] }, + { .name = "apple,firmware-version", .length = sizeof(compat_27_2), + .value = compat_27_2, .next = &props[2] }, + { .name = "apple,firmware-uuid", .length = sizeof(bad_uuid), + .value = (void *)bad_uuid, .next = &props[3] }, + { .name = "compatible", .length = sizeof(t6030), + .value = (void *)t6030 }, + }; + struct property ext_props[] = { + { .name = "apple,firmware-compat", .length = sizeof(compat_27_2), + .value = compat_27_2, .next = &ext_props[1] }, + { .name = "apple,firmware-version", .length = sizeof(compat_27_2), + .value = compat_27_2, .next = &ext_props[2] }, + { .name = "compatible", .length = sizeof(t8122_ext), + .value = (void *)t8122_ext }, + }; + struct device_node node = { .properties = props }; + struct device_node ext_node = { .properties = ext_props }; + struct device dev = { + .init_name = "dcp-firmware-test", + .of_node = &node, + .driver = &apple_platform_driver.driver, + }; + + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + + props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + props[0].value = compat_27_2; + + /* T6041 internal and external UUID pins remain enforced on 27.2. */ + props[3].length = sizeof(t6041); + props[3].value = (void *)t6041; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + + props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + + props[3].length = sizeof(t6041_ext); + props[3].value = (void *)t6041_ext; + props[2].length = sizeof(bad_uuid); + props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + + props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + + props[2].name = "apple,firmware-uuid"; + props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + + /* T8122 wrong or missing 27.2 UUID is terminally refused (never takes generic v27). */ + props[3].length = sizeof(t8122); + props[3].value = (void *)t8122; + props[2].name = "apple,firmware-uuid"; + props[2].length = sizeof(bad_uuid); + props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + + props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + + props[2].name = "apple,firmware-uuid"; + props[2].length = sizeof(APPLE_T8122_DCP_26B123_UUID); + props[2].value = (void *)APPLE_T8122_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + KUNIT_EXPECT_TRUE(test, + apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + + /* T8122 external with mismatched version is terminally refused regardless of live tree. */ + ext_props[1].value = compat_27_0; + KUNIT_EXPECT_FALSE(test, + apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + dev.of_node = &ext_node; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + ext_props[1].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + apple_t8122_dcpext_v27_2(&ext_node) ? + DCP_FIRMWARE_V_27_0 : DCP_FIRMWARE_UNKNOWN); + dev.of_node = &node; + + /* Internal T8142: known 27.x takes v27, unknown 27.x is refused (never takes H17P). */ + props[3].length = sizeof(t8142); + props[3].value = (void *)t8142; + props[0].value = compat_27_0; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + props[0].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_V_27_0); + props[0].value = compat_27_1; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_UNKNOWN); + props[0].value = compat_26_6; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_H17P); + props[0].value = compat_27_2; + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) + /* T8132 keeps its M4 match-data pin on 27.2. */ + props[3].length = sizeof(t8132); + props[3].value = (void *)t8132; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + DCP_FIRMWARE_M4); +#endif +} + +static void dcp_typec_routes_available_children(struct kunit *test) +{ + static const char disabled[] = "disabled"; + static const char okay[] = "okay"; + struct property child_status = { + .name = "status", .length = sizeof(disabled), .value = (void *)disabled, + }; + struct device_node child = { + .name = "route", .full_name = "route@0", .properties = &child_status, + }; + struct device_node routes = { + .name = "typec-routes", .full_name = "typec-routes", + }; + struct device_node parent = { + .name = "dcp", .full_name = "dcp", .child = &routes, + }; + + /* Empty typec-routes container has no available route children. */ + KUNIT_EXPECT_FALSE(test, dcp_has_available_typec_routes(&parent)); + + /* Container with only disabled child routes has no available routes. */ + routes.child = &child; + KUNIT_EXPECT_FALSE(test, dcp_has_available_typec_routes(&parent)); + + /* Available child route activates Type-C route detection. */ + child_status.length = sizeof(okay); + child_status.value = (void *)okay; + KUNIT_EXPECT_TRUE(test, dcp_has_available_typec_routes(&parent)); +} + static struct kunit_case dcp_firmware_cases[] = { KUNIT_CASE(dcp_firmware_13_5_compat), KUNIT_CASE(dcp_firmware_27_method_admission), KUNIT_CASE(dcp_firmware_27_empty_clock_table), + KUNIT_CASE(dcp_firmware_27_pin_precedence), + KUNIT_CASE(dcp_typec_routes_available_children), {} }; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 1c68499311d27a..0db75e9b222172 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6264,34 +6264,9 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) int ret; /* - * T8142 (J813) on macOS 27.0: the H17P interface written for its 26.x - * firmware makes the 27.0 DCP firmware panic right after the first - * hotplug ("ap_link: callback failed with: 0x5"). It runs the T6050's - * firmware-27 generation, and so does 27.2, with the 27.2 method table. + * T6050 and T8142 dcpext were introduced on firmware 27 and have no + * older interface. */ - if (of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) { - ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - if (ret >= 0 && (!strcmp(compat_str, "27.0.0") || - !strcmp(compat_str, "27.2.0"))) - return DCP_FIRMWARE_V_27_0; - } - - /* - * The T8122 (M3 MacBook Air) internal DCP on the 27.2 (26B123) image - * runs the firmware-27 backend with the 27.2 table, as the T6041's - * 27.2 internal DCP does. Its 14.x image keeps the native 14.7 path - * and the 25G83 profile its own, below. - */ - if (apple_t8122_dcp_v27_2(dev->of_node)) { - /* Checked by apple_t8122_dcp_v27_2(). */ - dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - return dcp_v27_method_table(dev, compat_str); - } - - if (dcp_firmware_27(dev, &version)) - return version; - - /* The T6050 was introduced on firmware 27 and has no older interface. */ if (hw->firmware_compat == DCP_FIRMWARE_V_27_0) { ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { @@ -6302,8 +6277,20 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) } /* - * SoCs introduced with H17-generation firmware pin its interface; the - * loader may not recognise their boot firmware version. + * T8142 (J813) on firmware 27 or later: the H17P interface written for + * its 26.x firmware makes 27.x firmware panic right after the first + * hotplug ("ap_link: callback failed with: 0x5"). Keep ahead of its + * H17P match-data pin so known 27.x builds take the common firmware-27 + * backend and unknown 27.x builds are terminally refused. + */ + if (of_device_is_compatible(dev->of_node, "apple,t8142-dcp") && + dcp_firmware_27(dev, &version)) + return version; + + /* + * SoCs introduced with M4 or H17-generation firmware pin their + * interface; keep explicit match-data pins ahead of the generic + * firmware-27 rule below so T8132/T8140 stay on their pinned backend. */ if (hw->firmware_compat != DCP_FIRMWARE_UNKNOWN) return hw->firmware_compat; @@ -6315,7 +6302,8 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) * T6041 (M4 Pro/Max) uses its desktop IOMFB instance on 26.5.2 and * 26.6.2 firmware, where boot firmware and compatibility versions must * match. The pinned 27.2 (26B123) T6041 DCP image uses the firmware-27 - * backend on internal and external display processors. + * backend on internal and external display processors. Keep ahead of + * dcp_firmware_27() so the T6041 image UUID pin remains enforced. */ if (of_device_is_compatible(dev->of_node, "apple,t6041-dcp") || of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) { @@ -6334,6 +6322,25 @@ static enum dcp_firmware_version dcp_check_firmware_version(struct device *dev) return DCP_FIRMWARE_UNKNOWN; } + /* + * T8122 (M3 MacBook Air) internal and external DCPs pin the 27.2 + * (26B123) image UUID on firmware 27.x: any wrong or missing UUID on a + * firmware 27+ build is terminally refused rather than falling through + * to generic firmware-27 or legacy 14.x selection. + */ + if ((of_device_is_compatible(dev->of_node, "apple,t8122-dcp") || + of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) && + dcp_firmware_27(dev, &version)) { + if (apple_t8122_dcp_v27_2(dev->of_node) || + apple_t8122_dcpext_v27_2(dev->of_node)) + return version; + dev_err(dev, "T8122 display not started: unpinned 27.x DCP firmware UUID\n"); + return DCP_FIRMWARE_UNKNOWN; + } + + if (dcp_firmware_27(dev, &version)) + return version; + ret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); if (ret < 0) { dev_err(dev, "Could not read 'apple,firmware-compat': %d\n", ret); @@ -6528,6 +6535,56 @@ VISIBLE_IF_KUNIT void dcp_enable_typec_work(struct apple_dcp *dcp) } } +static bool dcp_has_available_typec_routes(struct device_node *np) +{ + struct device_node *routes, *child; + bool avail = false; + + routes = of_get_child_by_name(np, "typec-routes"); + if (!routes) + return false; + if (of_device_is_available(routes)) { + for_each_available_child_of_node(routes, child) { + of_node_put(child); + avail = true; + break; + } + } + of_node_put(routes); + return avail; +} + +static bool dcp_is_internal_panel_only(const struct apple_dcp *dcp) +{ + struct device_node *np = dcp->dev->of_node; + + return dcp->panel_identity && !dcp->dcpext && + !of_property_present(np, "phys") && + !dcp_has_available_typec_routes(np); +} + +static u8 dcp_dart_dma_bits(struct device_node *np) +{ + struct of_phandle_args args; + u32 range[4]; + u64 base, size, end; + int ret; + + ret = of_parse_phandle_with_args(np, "iommus", "#iommu-cells", 0, &args); + if (ret) + return 0; + ret = of_property_read_u32_array(args.np, "apple,dma-range", range, 4); + of_node_put(args.np); + if (ret) + return 0; + base = ((u64)range[0] << 32) | range[1]; + size = ((u64)range[2] << 32) | range[3]; + if (!size || base + size < base) + return 0; + end = base + size - 1; + return clamp_t(u8, fls64(end), 32, 48); +} + /* * The provider clocks firmware 27 asks for by index (getClockFrequency): * apple,clock-ids, published by the boot loader from the ADT. @@ -6538,24 +6595,20 @@ static int dcp_firmware_clocks_v27(struct apple_dcp *dcp) int clocks, index, ret; /* - * T6041 device trees carry the single 712 MHz disp0 clock unless the - * boot loader publishes the two /arm-io/disp0 provider clocks - * (376 at 712 MHz and 460 at 0 Hz). Expose the same two-entry table - * when apple,clock-ids is absent so getClockFrequency(0/1) matches. - */ - /* - * The T8122 /arm-io/disp0 names the same pair (345 at 712 MHz, the - * device tree's disp0 clock, and 416 at 0 Hz). + * Internal panels whose device tree carries only the single unnamed + * disp0 clock without apple,clock-ids (T6041, T8122, T6030, T6031, + * T8112): expose the two-entry [disp0, 0 Hz] table so + * getClockFrequency(0/1) matches /arm-io/disp0. Non-panel paths or + * nodes without a single unnamed clock still require apple,clock-ids. */ if (!of_property_present(dev->of_node, "apple,clock-ids") && - (of_device_is_compatible(dev->of_node, "apple,t6041-dcp") || - of_device_is_compatible(dev->of_node, "apple,t8122-dcp"))) { - struct clk *clk = devm_clk_get_optional(dev, NULL); + dcp_is_internal_panel_only(dcp) && + !of_property_present(dev->of_node, "clock-names") && + of_count_phandle_with_args(dev->of_node, "clocks", "#clock-cells") == 1) { + struct clk *clk = devm_clk_get(dev, NULL); if (IS_ERR(clk)) return PTR_ERR(clk); - if (!clk) - return 0; dcp->firmware_clocks = devm_kcalloc(dev, 2, sizeof(*dcp->firmware_clocks), GFP_KERNEL); @@ -7924,6 +7977,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) */ if (fw_compat != DCP_FIRMWARE_V_14_7 && fw_compat != DCP_FIRMWARE_V_26_6 && + fw_compat != DCP_FIRMWARE_V_27_0 && fw_compat != DCP_FIRMWARE_M4 && !of_property_present(dev->of_node, "apple,bw-scratch") && !hw->firmware_clock) @@ -8059,27 +8113,26 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) * does not adopt. (The T8140 dcpext, whose match data does not adopt, is * refused above on anything but 26.6.2.) */ - if (fw_compat == DCP_FIRMWARE_V_27_0) - dcp->hw.adopt_live_session = true; - /* - * T6041 internal panel on firmware 27 adopts the running DCP session - * with 41-bit firmware DMA addressing and no DPTX port services, - * matching the H17-generation internal-panel profile. - */ - if (fw_compat == DCP_FIRMWARE_V_27_0 && - of_device_is_compatible(dev->of_node, "apple,t6041-dcp")) { - dcp->hw.firmware_dma_bits = 41; - dcp->hw.num_dptx_ports = 0; + if (fw_compat == DCP_FIRMWARE_V_27_0) { dcp->hw.adopt_live_session = true; + /* + * Derive firmware DMA width from the DCP DART aperture when + * match data does not already pin a hardware profile width. + */ + if (!dcp->hw.firmware_dma_bits) { + u8 dma_bits = dcp_dart_dma_bits(dev->of_node); + + if (dma_bits) + dcp->hw.firmware_dma_bits = dma_bits; + } } /* - * The same for the T8122 internal panel on firmware 27: its DART - * window is 0x100_0000_0000 + 64 GiB, and dcpext drives the external - * ports. + * Internal laptop panels on firmware 27 (an internal DCP with a panel + * child and no external DPTX/Type-C routes): the boot loader hands the + * panel over running and it has no DP port. */ if (fw_compat == DCP_FIRMWARE_V_27_0 && - of_device_is_compatible(dev->of_node, "apple,t8122-dcp")) { - dcp->hw.firmware_dma_bits = 41; + dcp_is_internal_panel_only(dcp)) { dcp->hw.num_dptx_ports = 0; dcp->hw.adopt_live_session = true; } @@ -8093,14 +8146,16 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) */ if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) { - dcp->hw.firmware_dma_bits = 41; + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = 41; dcp->hw.num_dptx_ports = 2; dcp->hw.fw_14_7_endpoints = false; dcp->hw.adopt_live_session = false; } if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t6041-dcpext")) { - dcp->hw.firmware_dma_bits = 41; + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = 41; dcp->hw.num_dptx_ports = 2; dcp->hw.adopt_live_session = true; dcp->hw.sink_metadata_edid = true; diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index c0ae42df744cd5..86a12be7bc1c90 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -93,11 +93,11 @@ static inline bool apple_t8122_dcp_v27_2(const struct device_node *np) * DCP's region). So it qualifies when both of its own are 27.2.0 and the * internal DCP was handed over on the 27.2 image. */ -static inline bool apple_t8122_dcpext_v27_2(const struct device_node *np) +static inline bool +apple_t8122_dcpext_v27_2_for_internal(const struct device_node *np, + const struct device_node *internal_dcp) { - struct device_node *dcp; u32 fw[3], compat[3]; - bool internal; if (!np || !of_device_is_compatible(np, "apple,t8122-dcpext") || of_property_count_u32_elems(np, "apple,firmware-version") != 3 || @@ -108,8 +108,19 @@ static inline bool apple_t8122_dcpext_v27_2(const struct device_node *np) compat[0] != 27 || compat[1] != 2 || compat[2] != 0) return false; + return apple_t8122_dcp_v27_2(internal_dcp); +} + +static inline bool apple_t8122_dcpext_v27_2(const struct device_node *np) +{ + struct device_node *dcp; + bool internal; + + if (!np || !of_device_is_compatible(np, "apple,t8122-dcpext")) + return false; + dcp = of_find_compatible_node(NULL, NULL, "apple,t8122-dcp"); - internal = apple_t8122_dcp_v27_2(dcp); + internal = apple_t8122_dcpext_v27_2_for_internal(np, dcp); of_node_put(dcp); return internal; } From 4bf7a40b52f7c6aca41b31c61f4af3263da2886e Mon Sep 17 00:00:00 2001 From: nekolyanich Date: Sun, 11 Oct 2026 18:01:28 +0300 Subject: [PATCH 1264/1514] drm: apple: audio: ask for up to 256 KiB of audio elements, as macOS When the audio elements do not fit the buffer of the get_elements call, DCP returns them cut off at the buffer's end and reports a used size of 0. A Samsung TV behind a USB-C to HDMI adapter has 17312 bytes of elements, so with the 16 KiB the legacy path asked for, everything past 16 KiB was lost. macOS 13 asks for up to 256 KiB (max_size 0x40000 in the request, 0x43a0 used in the reply for this TV), as the native 14.7 path already does: use that capacity on every firmware. The native path no longer needs a second buffer of its own. Allocate the elements buffer and the call buffers with kvzalloc(), including the ones in afk_service_call_timeout_len() and afk_service_call_with_reply_len(), which every AFK service call goes through; they are only copied into the DMA buffers. Fixes: cb24343242a7 ("gpu: drm: apple: Add DCP audio driver") Link: https://github.com/aurora-silicon/linux/pull/276 Signed-off-by: nekolyanich Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk.c | 8 +++--- drivers/gpu/drm/apple/audio.c | 53 ++++++++++++++++++----------------- drivers/gpu/drm/apple/av.c | 4 +-- 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 096d1685ae03b5..17b39eff37a377 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -3575,7 +3575,7 @@ int afk_service_call_timeout_len(struct apple_epic_service *service, u16 group, if (!service) return -ENODEV; - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; @@ -3645,7 +3645,7 @@ int afk_service_call_timeout_len(struct apple_epic_service *service, u16 group, } out: - kfree(bfr); + kvfree(bfr); return ret; } @@ -3683,7 +3683,7 @@ int afk_service_call_with_reply_len(struct apple_epic_service *service, &bfr_len) || bfr_len > U32_MAX) return -EOVERFLOW; - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; @@ -3728,7 +3728,7 @@ int afk_service_call_with_reply_len(struct apple_epic_service *service, } out: - kfree(bfr); + kvfree(bfr); return ret; } diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index f4db111e675858..513be60ef3d6fd 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -21,6 +21,8 @@ #include #include #include +#include +#include #include #include #include @@ -37,11 +39,15 @@ #include "audio.h" #include "parser.h" -#define DCPAUD_ELEMENTS_MAXSIZE 16384 +/* + * The element catalog capacity, on every firmware. Elements that do not + * fit come back cut off at the buffer's end with a used size of 0: a TV + * behind a USB-C to HDMI adapter has 17312 bytes of them. macOS 13 asks + * for up to 256 KiB. + */ +#define DCPAUD_ELEMENTS_MAXSIZE SZ_256K #define DCPAUD_PRODUCTATTRS_MAXSIZE 1024 #define DCPAUD_ELD_SIZE MAX_ELD_BYTES -/* The native element catalog capacity (14.7 external role). */ -#define DCPAUD_ELEMENTS_V14_7 SZ_256K /* * SIO takes one of its 64 descriptor slots per period, shared by all its @@ -145,11 +151,6 @@ static inline bool dcpaud_native_link(struct dcp_audio *dcpaud) #endif } -static inline size_t dcpaud_elements_size(struct dcp_audio *dcpaud) -{ - return dcpaud_native_link(dcpaud) ? DCPAUD_ELEMENTS_V14_7 : DCPAUD_ELEMENTS_MAXSIZE; -} - static const struct snd_pcm_hardware dcp_pcm_hw = { .info = SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_INTERLEAVED, @@ -198,7 +199,7 @@ static int dcpaud_read_remote_info(struct dcp_audio *dcpaud) int ret; ret = dcp_audiosrv_get_elements(dcpaud->dcp_dev, dcpaud->elements, - dcpaud_elements_size(dcpaud)); + DCPAUD_ELEMENTS_MAXSIZE); if (ret < 0) return ret; @@ -255,7 +256,7 @@ static void dcpaud_consult_elements(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) .v14_7_audio = dcpaud->native_link, @@ -304,7 +305,7 @@ static int dcpaud_select_cookie(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) .v14_7_audio = dcpaud->native_link, @@ -861,7 +862,7 @@ static int dcpaud_pin_rate_format(struct dcp_audio *dcpaud, struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, .v14_7_audio = dcpaud->native_link, }; @@ -1384,7 +1385,7 @@ static int dcpaud_select_default_cookie(struct dcp_audio *dcpaud) struct dcp_parse_ctx elements = { .dcp = dev_get_drvdata(dcpaud->dcp_dev), .blob = dcpaud->elements + 4, - .len = dcpaud_elements_size(dcpaud) - 4, + .len = DCPAUD_ELEMENTS_MAXSIZE - 4, .pos = 0, .v14_7_audio = dcpaud->native_link, }; @@ -2010,16 +2011,9 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dcpaud->dcp_dev = &dcp_pdev->dev; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - /* Native external roles share the link lifecycle and element catalog. */ - if (dcp_audiosrv_native_link(dcpaud->dcp_dev)) { - void *elements = devm_kzalloc(dev, DCPAUD_ELEMENTS_V14_7, GFP_KERNEL); - - if (!elements) - goto rpm_put; - devm_kfree(dev, dcpaud->elements); - dcpaud->elements = elements; + /* Native external roles share the link lifecycle. */ + if (dcp_audiosrv_native_link(dcpaud->dcp_dev)) dcpaud->native_link = true; - } #endif dma_pdev = of_find_device_by_node(dma_spec.np); @@ -2042,7 +2036,7 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) dcpaud_expose_debugfs_blob(dcpaud, "selected_cookie", &dcpaud->selected_cookie, sizeof(dcpaud->selected_cookie)); dcpaud_expose_debugfs_blob(dcpaud, "elements", dcpaud->elements, - dcpaud_elements_size(dcpaud)); + DCPAUD_ELEMENTS_MAXSIZE); dcpaud_expose_debugfs_blob(dcpaud, "product_attrs", dcpaud->productattrs, DCPAUD_PRODUCTATTRS_MAXSIZE); } @@ -2094,18 +2088,27 @@ static const struct component_ops dcpaud_comp_ops = { .unbind = dcpaud_comp_unbind, }; +static void dcpaud_free_elements(void *elements) +{ + kvfree(elements); +} + static int dcpaud_probe(struct platform_device *pdev) { struct dcp_audio *dcpaud; + int ret; dcpaud = devm_kzalloc(&pdev->dev, sizeof(*dcpaud), GFP_KERNEL); if (!dcpaud) return -ENOMEM; - dcpaud->elements = devm_kzalloc(&pdev->dev, DCPAUD_ELEMENTS_MAXSIZE, - GFP_KERNEL); + dcpaud->elements = kvzalloc(DCPAUD_ELEMENTS_MAXSIZE, GFP_KERNEL); if (!dcpaud->elements) return -ENOMEM; + ret = devm_add_action_or_reset(&pdev->dev, dcpaud_free_elements, + dcpaud->elements); + if (ret) + return ret; dcpaud->productattrs = devm_kzalloc(&pdev->dev, DCPAUD_PRODUCTATTRS_MAXSIZE, GFP_KERNEL); diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index f685bce973e5a0..13b9af7b13969b 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -659,12 +659,12 @@ dcp_audiosrv_osobject_call(struct apple_epic_service *service, u16 group, static_assert(sizeof(*hdr) == 48); size_t received = 0, used; size_t bfr_len = output_maxsize + sizeof(*hdr); - void *bfr __free(kfree) = NULL; + void *bfr __free(kvfree) = NULL; int ret; KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_osobject_call, service, group, command, output, output_maxsize, output_size); - bfr = kzalloc(bfr_len, GFP_KERNEL); + bfr = kvzalloc(bfr_len, GFP_KERNEL); if (!bfr) return -ENOMEM; From e93f1ed082dba6c0d6400e87f14cbecaccf709b2 Mon Sep 17 00:00:00 2001 From: nekolyanich Date: Sun, 11 Oct 2026 18:01:42 +0300 Subject: [PATCH 1265/1514] drm: apple: audio: drop the runtime PM reference only after the DMA stopped Trigger STOP put the runtime PM reference right after starting the asynchronous DMA terminate. Without autosuspend that suspends the device at once and powers its domain (ps_dpa1/ps_dpa2) down while SIO may still run DMA towards the DPA. SIO then crashed with "Shim DMA unavailable" and the TERMINATE timed out after it, taking DP audio on all outputs down until a reboot. On an M2 Pro with two DP sinks an earlier version of this change on a downstream tree took it from 4 of 4 boots to none in 11. Put the reference in sync_stop, after snd_dmaengine_pcm_sync_stop() waited for the terminate. ALSA calls sync_stop at the next hw_params, prepare or hw_free, at close, at system suspend and at disconnect, not right after the STOP, so after a drain, an xrun or a stop with the stream left open the DPA stays powered until then. Waiting inside trigger would also work (the PCM is nonatomic), but sync_stop is the hook ALSA has for it, as in the AOP audio driver. The stream remembers whether it holds the reference. sync_stop runs outside the stream lock: test and clear it under the lock. START takes the reference only once, since a START can follow a failed one before sync_stop ran. A stream that plays into the void without a sink holds none, as before. Fixes: f25cb501c5fc ("drm: apple: audio: Implement runtime PM support") Link: https://github.com/aurora-silicon/linux/pull/276 Signed-off-by: nekolyanich Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 513be60ef3d6fd..ec690d674e4183 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -106,6 +106,8 @@ struct dcp_audio { ktime_t void_start; u64 void_periods; struct delayed_work void_work; + /* The stream holds a runtime PM reference, put in sync_stop; stream lock */ + bool pm_held; void *elements; void *productattrs; @@ -730,7 +732,11 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) if (dcpaud->open_unplugged || !dcpaud_connection_up(dcpaud)) return dcpaud_void_start(substream); - WARN_ON(pm_runtime_get_sync(dcpaud->dev) < 0); + /* A START can follow a failed one before sync_stop ran */ + if (!dcpaud->pm_held) { + WARN_ON(pm_runtime_get_sync(dcpaud->dev) < 0); + dcpaud->pm_held = true; + } ret = dcp_audiosrv_startlink(dcpaud->dcp_dev, &dcpaud->selected_cookie); if (ret < 0) @@ -763,9 +769,8 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: + /* The runtime PM reference goes in sync_stop */ ret = dcp_audiosrv_stoplink(dcpaud->dcp_dev); - pm_runtime_mark_last_busy(dcpaud->dev); - __pm_runtime_put_autosuspend(dcpaud->dev); if (ret < 0) return ret; break; @@ -775,14 +780,32 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) } /* - * ALSA calls this once a stream has stopped, outside the stream lock, before - * the next hw_params, prepare or hw_free and at close. + * ALSA calls this once a stream has stopped (STOP, SUSPEND, or the STOP that + * undoes a failed START), outside the stream lock, before the next + * hw_params, prepare or hw_free, at close, at system suspend and at + * disconnect. The DMA terminate STOP started is asynchronous: putting the + * runtime PM reference in STOP powered the DPA's domain (ps_dpa*) down while + * SIO still ran DMA towards it, and SIO crashed ("Shim DMA unavailable", the + * TERMINATE timing out after it), taking DP audio down on every output until + * a reboot. Wait for the terminate first. */ static int dcp_pcm_sync_stop(struct snd_pcm_substream *substream) { struct dcp_audio *dcpaud = substream->pcm->private_data; + bool held; cancel_delayed_work_sync(&dcpaud->void_work); + snd_dmaengine_pcm_sync_stop(substream); + + snd_pcm_stream_lock_irq(substream); + held = dcpaud->pm_held; + dcpaud->pm_held = false; + snd_pcm_stream_unlock_irq(substream); + + if (held) { + pm_runtime_mark_last_busy(dcpaud->dev); + __pm_runtime_put_autosuspend(dcpaud->dev); + } return 0; } From 0d7dd16d8eed2aca5e8a5afc98843fa95599878a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 13 Nov 2026 00:41:28 +1100 Subject: [PATCH 1266/1514] drm: apple: audio: test the legacy stream's PM reference and element capacity KUnit cases for the legacy (pre-14.7) audio service: a stopped or suspended stream keeps its runtime PM reference until sync_stop has waited for the DMA terminate, a failed START and a retried one before sync_stop leave one reference, a stream without a sink takes none, and the element catalog is asked for with 256 KiB so that a 17312 byte catalog arrives whole. The audio service's link and catalog calls get static stubs for this. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio-legacy-test.c | 302 ++++++++++++++++++++++ drivers/gpu/drm/apple/audio.c | 1 + drivers/gpu/drm/apple/av.c | 28 +- 3 files changed, 323 insertions(+), 8 deletions(-) create mode 100644 drivers/gpu/drm/apple/audio-legacy-test.c diff --git a/drivers/gpu/drm/apple/audio-legacy-test.c b/drivers/gpu/drm/apple/audio-legacy-test.c new file mode 100644 index 00000000000000..fb082c244ee2b4 --- /dev/null +++ b/drivers/gpu/drm/apple/audio-legacy-test.c @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by audio.c: on the legacy (pre-14.7) audio service a stopped + * stream keeps its runtime PM reference until sync_stop has waited for the + * DMA terminate, a failed START leaves exactly one reference to put, and the + * element catalog is asked for with the full 256 KiB capacity. + * The production trigger and sync_stop run; the audio service's link calls + * and the DMA channel are stubbed. + */ +#include +#include +#include + +struct dcpaud_legacy_test { + struct dma_device dma; + struct dma_chan channel; + struct dma_async_tx_descriptor desc; + char sequence[32]; + unsigned int nsequence; + /* The runtime PM usage count when the terminate was waited for */ + int usage_at_drain; + int startlink_err; + size_t elements_asked; + size_t catalog; + struct device *dev; +}; + +static struct dcpaud_legacy_test *dcpaud_legacy_current; + +static void dcpaud_legacy_record(char step) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + if (t->nsequence < sizeof(t->sequence) - 1) + t->sequence[t->nsequence++] = step; +} + +static int dcpaud_legacy_terminate(struct dma_chan *chan) +{ + dcpaud_legacy_record('X'); + return 0; +} + +static void dcpaud_legacy_drain(struct dma_chan *chan) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + t->usage_at_drain = atomic_read(&t->dev->power.usage_count); + dcpaud_legacy_record('D'); +} + +static dma_cookie_t dcpaud_legacy_submit(struct dma_async_tx_descriptor *tx) +{ + return 1; +} + +static struct dma_async_tx_descriptor * +dcpaud_legacy_prep(struct dma_chan *chan, dma_addr_t buf, size_t len, size_t period, + enum dma_transfer_direction dir, unsigned long flags) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + dcpaud_legacy_record('Q'); + t->desc.chan = chan; + t->desc.tx_submit = dcpaud_legacy_submit; + return &t->desc; +} + +static void dcpaud_legacy_issue(struct dma_chan *chan) +{ +} + +static enum dma_status dcpaud_legacy_status(struct dma_chan *chan, dma_cookie_t cookie, + struct dma_tx_state *state) +{ + return DMA_COMPLETE; +} + +static int dcpaud_legacy_startlink(struct device *dev, struct dcp_sound_cookie *cookie) +{ + dcpaud_legacy_record('T'); + return dcpaud_legacy_current->startlink_err; +} + +static int dcpaud_legacy_stoplink(struct device *dev) +{ + dcpaud_legacy_record('S'); + return 0; +} + +static void dcpaud_legacy_rpm_disable(void *data) +{ + pm_runtime_disable(data); +} + +static void dcpaud_legacy_close(void *data) +{ + snd_dmaengine_pcm_close(data); +} + +/* A legacy service instance with a sink, and a configured stream on it */ +static struct snd_pcm_substream *dcpaud_legacy_setup(struct kunit *test, + struct dcp_audio **audio) +{ + struct dcpaud_legacy_test *t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + struct dcp_audio *dcpaud = kunit_kzalloc(test, sizeof(*dcpaud), GFP_KERNEL); + struct snd_pcm_substream *sub = kunit_kzalloc(test, sizeof(*sub), GFP_KERNEL); + struct snd_pcm_runtime *runtime = kunit_kzalloc(test, sizeof(*runtime), GFP_KERNEL); + struct snd_pcm *pcm = kunit_kzalloc(test, sizeof(*pcm), GFP_KERNEL); + struct platform_device *pdev; + + KUNIT_ASSERT_NOT_NULL(test, t); + KUNIT_ASSERT_NOT_NULL(test, dcpaud); + KUNIT_ASSERT_NOT_NULL(test, sub); + KUNIT_ASSERT_NOT_NULL(test, runtime); + KUNIT_ASSERT_NOT_NULL(test, pcm); + pdev = kunit_platform_device_alloc(test, "dcpaud-legacy", PLATFORM_DEVID_AUTO); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pdev); + platform_set_drvdata(pdev, dcpaud); + dcpaud->dev = &pdev->dev; + dcpaud->dcp_dev = &pdev->dev; + mutex_init(&dcpaud->data_lock); + INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); + dcpaud->connected = true; + dcpaud->substream = sub; + + /* Runtime PM on, without callbacks: only the usage count matters */ + pm_runtime_no_callbacks(dcpaud->dev); + pm_runtime_enable(dcpaud->dev); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_rpm_disable, + dcpaud->dev), 0); + + dcpaud_legacy_current = t; + t->dev = dcpaud->dev; + t->usage_at_drain = -1; + t->channel.device = &t->dma; + t->dma.device_terminate_all = dcpaud_legacy_terminate; + t->dma.device_synchronize = dcpaud_legacy_drain; + t->dma.device_tx_status = dcpaud_legacy_status; + t->dma.device_prep_dma_cyclic = dcpaud_legacy_prep; + t->dma.device_issue_pending = dcpaud_legacy_issue; + kunit_activate_static_stub(test, dcp_audiosrv_startlink, dcpaud_legacy_startlink); + kunit_activate_static_stub(test, dcp_audiosrv_stoplink, dcpaud_legacy_stoplink); + + pcm->private_data = dcpaud; + pcm->nonatomic = true; + sub->pcm = pcm; + sub->runtime = runtime; + mutex_init(&sub->self_group.mutex); + spin_lock_init(&sub->self_group.lock); + sub->group = &sub->self_group; + runtime->frame_bits = 64; + runtime->rate = 48000; + runtime->buffer_size = 8192; + runtime->period_size = 512; + KUNIT_ASSERT_EQ(test, snd_dmaengine_pcm_open(sub, &t->channel), 0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_close, sub), 0); + + *audio = dcpaud; + return sub; +} + +static int dcpaud_legacy_usage(struct dcp_audio *dcpaud) +{ + return atomic_read(&dcpaud->dev->power.usage_count); +} + +static void dcpaud_legacy_stop_waits_for_dma(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* The terminate is only started: the DPA stays powered */ + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXS"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* The reference goes once the terminate was waited for */ + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->usage_at_drain, 1); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); + KUNIT_EXPECT_FALSE(test, audio->pm_held); + + /* A second sync_stop (close after prepare) has nothing to put */ + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_suspend_waits_for_dma(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_SUSPEND), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->usage_at_drain, 1); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_failed_start(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + /* START fails at the link; ALSA undoes it with a STOP */ + dcpaud_legacy_current->startlink_err = -EIO; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), -EIO); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + + /* Retried before sync_stop ran: still one reference */ + dcpaud_legacy_current->startlink_err = 0; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 1); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TXSTQXSD"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static void dcpaud_legacy_void_takes_no_reference(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + /* No sink: the stream plays into the void; a 10 s period never elapses here */ + audio->open_unplugged = true; + sub->runtime->period_size = 480000; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_TRUE(test, audio->void_running); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "D"); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +static int dcpaud_legacy_get_elements(struct device *dev, void *elements, size_t maxsize) +{ + struct dcpaud_legacy_test *t = dcpaud_legacy_current; + + t->elements_asked = maxsize; + /* What the service returns: cut off at the buffer's end */ + memset(elements, 0xa5, min(t->catalog, maxsize)); + return 0; +} + +static int dcpaud_legacy_get_attrs(struct device *dev, void *attrs, size_t maxsize) +{ + return 0; +} + +static void dcpaud_legacy_free(void *data) +{ + kvfree(data); +} + +static void dcpaud_legacy_elements_capacity(struct kunit *test) +{ + struct dcp_audio *audio; + u8 *elements; + + dcpaud_legacy_setup(test, &audio); + elements = kvzalloc(DCPAUD_ELEMENTS_MAXSIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, elements); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dcpaud_legacy_free, elements), 0); + audio->elements = elements; + audio->productattrs = kunit_kzalloc(test, DCPAUD_PRODUCTATTRS_MAXSIZE, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, audio->productattrs); + kunit_activate_static_stub(test, dcp_audiosrv_get_elements, dcpaud_legacy_get_elements); + kunit_activate_static_stub(test, dcp_audiosrv_get_product_attrs, dcpaud_legacy_get_attrs); + + /* A TV behind a USB-C to HDMI adapter: 17312 bytes of elements */ + dcpaud_legacy_current->catalog = 17312; + KUNIT_ASSERT_FALSE(test, dcpaud_native_link(audio)); + KUNIT_ASSERT_EQ(test, dcpaud_read_remote_info(audio), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_current->elements_asked, (size_t)SZ_256K); + KUNIT_EXPECT_EQ(test, elements[17311], 0xa5); + KUNIT_EXPECT_EQ(test, elements[17312], 0); +} + +static struct kunit_case dcpaud_legacy_cases[] = { + KUNIT_CASE(dcpaud_legacy_stop_waits_for_dma), + KUNIT_CASE(dcpaud_legacy_suspend_waits_for_dma), + KUNIT_CASE(dcpaud_legacy_failed_start), + KUNIT_CASE(dcpaud_legacy_void_takes_no_reference), + KUNIT_CASE(dcpaud_legacy_elements_capacity), + {} +}; + +static struct kunit_suite dcpaud_legacy_suite = { + .name = "apple-dcpaud-legacy", + .test_cases = dcpaud_legacy_cases, +}; + +kunit_test_suite(dcpaud_legacy_suite); diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index ec690d674e4183..d425e0fe88b9fa 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -2288,6 +2288,7 @@ void dcp_audio_unregister(void) #if IS_ENABLED(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) #include "audio-no-sio-test.c" +#include "audio-legacy-test.c" #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) #include "audio-link-test.c" #endif diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index 13b9af7b13969b..bcc5743aae256b 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -266,10 +266,13 @@ int dcp_audiosrv_prepare(struct device *dev, struct dcp_sound_cookie *cookie) int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_startlink, dev, cookie); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; down_write(&asrv->srv_rwsem); ret = afk_service_call(asrv->srv, 0, asrv->cmds.start_link, cookie, sizeof(*cookie), 64 - sizeof(*cookie), NULL, 0, @@ -281,10 +284,13 @@ int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie) int dcp_audiosrv_stoplink(struct device *dev) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_stoplink, dev); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; down_write(&asrv->srv_rwsem); ret = afk_service_call(asrv->srv, 0, asrv->cmds.stop_link, NULL, 0, 64, NULL, 0, 64); @@ -728,13 +734,16 @@ static bool av_elements_need_more(int ret, size_t size, size_t cap, bool empty) int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; struct apple_epic_service *srv; size_t size = 0, cap; bool compact, empty; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_get_elements, dev, elements, maxsize); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; if (!asrv) return -ENODEV; scoped_guard(rwsem_read, &asrv->srv_rwsem) @@ -782,12 +791,15 @@ int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize int dcp_audiosrv_get_product_attrs(struct device *dev, void *attrs, size_t maxsize) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; struct apple_epic_service *srv; size_t size; int ret; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_get_product_attrs, dev, attrs, maxsize); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; if (!asrv) return -ENODEV; scoped_guard(rwsem_read, &asrv->srv_rwsem) From d0c923a3b25f08f95084cc64815f9cf3696353cd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 13 Nov 2026 01:35:40 +1100 Subject: [PATCH 1267/1514] selftests: apple-dcp, apple-afkv2: kvzalloc() and kvfree() for the call buffers The AFK service call and audio osobject call buffers now come from kvzalloc(); give the host harnesses that compile those functions the same calloc()/free() shims they have for kzalloc(). Signed-off-by: Ryan Murray --- tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py | 2 ++ tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py | 2 ++ .../selftests/drivers/gpu/apple-afkv2/extract-service.py | 2 ++ tools/testing/selftests/drivers/gpu/apple-dcp/audio.py | 2 +- 4 files changed, 7 insertions(+), 1 deletion(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py index bcced2f684cfa5..54485550122637 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-edid.py @@ -27,6 +27,8 @@ def function(name): #include "epic/dpavserv-edid.h" #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define cpu_to_le64(x) (x) #define le64_to_cpu(x) (x) #define READ_ONCE(x) (x) diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py index bdfd0f2325ba52..ea3915f0de720c 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-hpd.py @@ -36,6 +36,8 @@ def function(source, name): typedef u32 __le32; #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define kfree(p) free(p) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py index 19381f919d7e85..4c0164dce1aefc 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-service.py @@ -24,6 +24,8 @@ #define GFP_KERNEL 0 #define kzalloc(n,f) calloc(1,n) #define kfree(p) free(p) +#define kvzalloc(n,f) calloc(1,n) +#define kvfree(p) free(p) #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) #define cpu_to_le16(x) (x) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py index 25524680b7ea54..d1d6e9f57c3e68 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/audio.py @@ -24,7 +24,7 @@ def reply_bounds(root): #define GFP_KERNEL 0 static void free_buffer(void *p) {free(*(void **)p);} #define __free(x) __attribute__((cleanup(free_buffer))) -static void *kzalloc(size_t n, int flags) {(void)flags;return calloc(1,n);} +static void *kvzalloc(size_t n, int flags) {(void)flags;return calloc(1,n);} #define cpu_to_le64(x) (x) #define le64_to_cpu(x) (x) struct apple_dcp_afkep {bool compact;}; From 6d5ec4dd45a5b63f9c891425b09fa49acdaeadc6 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 08:14:56 +0300 Subject: [PATCH 1268/1514] arm64: dts: apple: t8142-j815: Give the SEP its power domains The SEP driver stages its sleep request for the commit on the SEP's PMGR word, which it finds through the node's first power domain. The J815 node named none, so every deep sleep was refused with "irreversible request could not be staged (ENOENT)". Describe the GPIO (+0x120) and SEP (+0xc00) words from the J815 ADT, both always on, and name them on the SEP node, as J813 does. Signed-off-by: Nick --- arch/arm64/boot/dts/apple/t8142-j815.dts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8142-j815.dts b/arch/arm64/boot/dts/apple/t8142-j815.dts index 82e73d6dafc2b9..ebb6a5270f0f69 100644 --- a/arch/arm64/boot/dts/apple/t8142-j815.dts +++ b/arch/arm64/boot/dts/apple/t8142-j815.dts @@ -358,6 +358,29 @@ * init (drivers/soc/apple/dt.rs). */ &pmgr { + /* + * From the J815 ADT, as on J813: GPIO at +0x120 and SEP at +0xc00, both + * always on (the enclave gates its own domain). The SEP driver stages its + * sleep request on the SEP word, so the node has to name it. + */ + ps_gpio: power-controller@120 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0x120 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "gpio"; + apple,always-on; + }; + + ps_sep: power-controller@c00 { + compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; + reg = <0xc00 4>; + #power-domain-cells = <0>; + #reset-cells = <0>; + label = "sep"; + apple,always-on; + }; + ps_spi2: power-controller@440 { compatible = "apple,t8142-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x440 4>; @@ -375,6 +398,7 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; From 76bf36c593124c7b5bf13e092a62b7f66e911f7c Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 08:27:42 +0300 Subject: [PATCH 1269/1514] Bluetooth: btcentauri: Quiesce Beta for sleep on every N1 board Suspend sent Beta the ACIPC host-sleep request only on apple,j813. J815 has the same N1 behind the same PCI functions, so it went into deep sleep with Beta never told: after the wake the transport read exec=3 and stopped, and every HCI command failed with -ENETDOWN until a reboot. Send the request wherever the IPC is up and Beta's firmware runs, as the Alpha side does since "wifi: apple: centauri: Quiesce Alpha for sleep on every N1 board". A firmware that isn't running has nothing to quiesce, and resume still only undoes a request suspend sent. Fixes: 507c53d46cf2 ("Bluetooth: btcentauri: quiesce the J813 transport across deep sleep") Signed-off-by: Nick --- drivers/bluetooth/btcentauri.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/bluetooth/btcentauri.c b/drivers/bluetooth/btcentauri.c index 7ae66124aa7ce2..4a5b9f33400591 100644 --- a/drivers/bluetooth/btcentauri.c +++ b/drivers/bluetooth/btcentauri.c @@ -1170,7 +1170,13 @@ static int cen_suspend(struct device *dev) bt->transport_paused = true; mutex_unlock(&bt->lock); cancel_delayed_work_sync(&bt->poll); - if (of_machine_is_compatible("apple,j813") && bt->ipc_requested) { + /* + * Tell Beta's firmware the host is going to sleep on every N1 board, as + * Alpha does. Only a running firmware can take the request; one that + * isn't running has nothing to quiesce. + */ + if (bt->ipc_requested && readl(bt->bar + 0x18) == 2 && + readl(bt->bar) == 2) { bt->transport_sleep_sent = true; ret = cen_transport_state(bt, true); if (ret) From 8b007a40c27be195ba626d21ca98023007417d87 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:17:02 -0500 Subject: [PATCH 1270/1514] thermal: sample temperature and trips from the same zone Acquire a device reference under the registry lock and hold it until both the temperature read and trip walk finish. This pairs the reading with limits from the same registered zone even when names are reused. Require usable limits from each contributing zone in the GPU poller. A zone without usable trips invalidates the combined limits and keeps the GPU cooling backstop active. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/glue.c | 70 +++++++++++++------------------- drivers/thermal/thermal_core.c | 18 ++++++-- include/linux/thermal.h | 10 +++++ 3 files changed, 53 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index bf20149d6c84dc..1ccb41d0fc8039 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -165,31 +165,16 @@ static int asahi_g16_zone_trip_cb(struct thermal_trip *trip, void *data) return 0; } -static bool asahi_g16_zone_read_limits(const char *name, long *release_mc, - long *hot_mc, long *critical_mc) +static bool asahi_g16_zone_limits_valid(struct asahi_g16_zone_trips *trips) { - struct asahi_g16_zone_trips trips = {}; - struct thermal_zone_device *tz; - - tz = thermal_zone_get_zone_by_name(name); - if (IS_ERR(tz)) - return false; - if (thermal_zone_for_each_trip(tz, asahi_g16_zone_trip_cb, &trips)) - return false; - if (!trips.have_critical && trips.have_hot && - trips.max_passive_mc > trips.hot_mc) { - trips.critical_mc = trips.max_passive_mc; - trips.have_critical = true; + if (!trips->have_critical && trips->have_hot && + trips->max_passive_mc > trips->hot_mc) { + trips->critical_mc = trips->max_passive_mc; + trips->have_critical = true; } - if (!trips.have_hot || !trips.have_critical || - trips.release_mc <= 0 || trips.release_mc > trips.hot_mc || - trips.critical_mc <= trips.hot_mc) - return false; - - *release_mc = trips.release_mc; - *hot_mc = trips.hot_mc; - *critical_mc = trips.critical_mc; - return true; + return trips->have_hot && trips->have_critical && + trips->release_mc > 0 && trips->release_mc <= trips->hot_mc && + trips->critical_mc > trips->hot_mc; } static void asahi_g16_zone_poll_fn(struct work_struct *work) @@ -202,7 +187,8 @@ static void asahi_g16_zone_poll_fn(struct work_struct *work) long hot_mc = 0; long critical_mc = 0; bool found = false; - bool limits_valid = false; + bool have_limits = false; + bool limits_valid = true; int ret = -ENODEV; unsigned int i; unsigned int delay_ms; @@ -211,29 +197,29 @@ static void asahi_g16_zone_poll_fn(struct work_struct *work) return; for (i = 0; i < ARRAY_SIZE(asahi_g16_die_zones); i++) { - long z_rel = 0, z_hot = 0, z_crit = 0; - int temp = 0; - int err = thermal_zone_get_temp_by_name(asahi_g16_die_zones[i], - &temp); + struct asahi_g16_zone_trips trips = {}; + int temp, err; + + err = thermal_zone_get_temp_and_trips(asahi_g16_die_zones[i], + &temp, asahi_g16_zone_trip_cb, + &trips); if (!err) { if (!found || temp > hottest) hottest = temp; found = true; - if (asahi_g16_zone_read_limits(asahi_g16_die_zones[i], - &z_rel, &z_hot, - &z_crit)) { - if (!limits_valid) { - release_mc = z_rel; - hot_mc = z_hot; - critical_mc = z_crit; - limits_valid = true; - } else { - release_mc = min(release_mc, z_rel); - hot_mc = min(hot_mc, z_hot); - critical_mc = min(critical_mc, z_crit); - } + if (!asahi_g16_zone_limits_valid(&trips)) { + limits_valid = false; + } else if (!have_limits) { + release_mc = trips.release_mc; + hot_mc = trips.hot_mc; + critical_mc = trips.critical_mc; + have_limits = true; + } else { + release_mc = min(release_mc, trips.release_mc); + hot_mc = min(hot_mc, trips.hot_mc); + critical_mc = min(critical_mc, trips.critical_mc); } } else if (err != -ENODEV) { ret = err; @@ -244,7 +230,7 @@ static void asahi_g16_zone_poll_fn(struct work_struct *work) } if (found) ret = 0; - if (!found || !limits_valid || release_mc <= 0 || + if (!found || !have_limits || !limits_valid || release_mc <= 0 || release_mc > hot_mc || critical_mc <= hot_mc) limits_valid = false; diff --git a/drivers/thermal/thermal_core.c b/drivers/thermal/thermal_core.c index 1bd642179e4fd3..77481eea5436e0 100644 --- a/drivers/thermal/thermal_core.c +++ b/drivers/thermal/thermal_core.c @@ -1726,9 +1726,11 @@ struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name) EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name); /** - * thermal_zone_get_temp_by_name() - sample a uniquely named registered zone + * thermal_zone_get_temp_and_trips() - sample a uniquely named registered zone * @name: thermal zone name * @temp: destination for the temperature in millidegrees Celsius + * @cb: optional callback for each trip of the sampled zone, under the zone lock + * @data: private data passed to @cb * * Acquire the zone device reference under the registry lock, as in * thermal_zone_get_by_id(). Removal waits for device references before freeing @@ -1736,9 +1738,11 @@ EXPORT_SYMBOL_GPL(thermal_zone_get_zone_by_name); * No borrowed thermal-zone pointer escapes to the caller. * * Return: 0 on success, -EINVAL for invalid arguments, -ENODEV for no match, - * -EEXIST for duplicate names, or the temperature read error. + * -EEXIST for duplicate names, or the error from the temperature read or trip callback. */ -int thermal_zone_get_temp_by_name(const char *name, int *temp) +int thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data) { struct thermal_zone_device *pos, *zone = NULL; int ret; @@ -1762,9 +1766,17 @@ int thermal_zone_get_temp_by_name(const char *name, int *temp) } ret = thermal_zone_get_temp(zone, temp); + if (!ret && cb) + ret = thermal_zone_for_each_trip(zone, cb, data); put_device(&zone->device); return ret; } +EXPORT_SYMBOL_GPL(thermal_zone_get_temp_and_trips); + +int thermal_zone_get_temp_by_name(const char *name, int *temp) +{ + return thermal_zone_get_temp_and_trips(name, temp, NULL, NULL); +} EXPORT_SYMBOL_GPL(thermal_zone_get_temp_by_name); static void thermal_zone_device_resume(struct work_struct *work) diff --git a/include/linux/thermal.h b/include/linux/thermal.h index 426dc182924065..9f603074c3b438 100644 --- a/include/linux/thermal.h +++ b/include/linux/thermal.h @@ -314,6 +314,9 @@ void thermal_cooling_device_unregister(struct thermal_cooling_device *); struct thermal_zone_device *thermal_zone_get_zone_by_name(const char *name); int thermal_zone_get_temp(struct thermal_zone_device *tz, int *temp); int thermal_zone_get_temp_by_name(const char *name, int *temp); +int thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data); int thermal_zone_get_slope(struct thermal_zone_device *tz); int thermal_zone_get_offset(struct thermal_zone_device *tz); bool thermal_trip_is_bound_to_cdev(struct thermal_zone_device *tz, @@ -371,6 +374,13 @@ static inline int thermal_zone_get_temp( { return -ENODEV; } static inline int thermal_zone_get_temp_by_name(const char *name, int *temp) { return -ENODEV; } +static inline int +thermal_zone_get_temp_and_trips(const char *name, int *temp, + int (*cb)(struct thermal_trip *, void *), + void *data) +{ + return -ENODEV; +} static inline int thermal_zone_get_slope( struct thermal_zone_device *tz) { return -ENODEV; } From 8c4b0e9dc04157e50eb57a3529a83614c3d61f14 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:42:25 -0500 Subject: [PATCH 1271/1514] drm/asahi: select GPU DVFS rows from the ADT table shape Use the source state count to select candidate index mappings and validate the paired frequencies and voltages before encoding the rows. The hardware descriptor no longer needs to specify a table layout. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/board.rs | 29 ++++----------- drivers/gpu/drm/asahi/g16/board/data.rs | 37 +++++-------------- drivers/gpu/drm/asahi/g16/hw.rs | 5 +-- drivers/gpu/drm/asahi/g16/initdata.rs | 2 +- .../drivers/gpu/asahi-m4/test-perf.py | 14 ++++--- 5 files changed, 27 insertions(+), 60 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/board.rs b/drivers/gpu/drm/asahi/g16/board.rs index 1d631276ac1fee..56798b017f5a9a 100644 --- a/drivers/gpu/drm/asahi/g16/board.rs +++ b/drivers/gpu/drm/asahi/g16/board.rs @@ -1,10 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! M4 board admission for the qualified firmware graph. -//! -//! 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. +//! Qualify firmware DVFS rows using this machine's preserved original ADT. pub(crate) mod data; @@ -16,23 +12,14 @@ use kernel::{device, prelude::*}; /// 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, - source_layout: data::SourceLayout, -) -> Result { - let (performance, layout) = - data::select_for(&adt.performance, source_layout).map_err(|error| { - dev_err!( - dev, - "M4 original ADT performance layout rejected: {:?}\n", - error - ); - EINVAL - })?; +pub(crate) fn qualify(dev: &device::Device, adt: &GpuAdt) -> Result { + let (performance, layout) = data::select_named(&adt.performance).map_err(|error| { + dev_err!(dev, "GPU original ADT performance layout rejected: {:?}\n", error); + EINVAL + })?; dev_info!( dev, - "M4 ADT DVFS: {} source states -> {} firmware rows ({} layout), top {} MHz\n", + "GPU ADT DVFS: {} source states -> {} firmware rows ({} layout), top {} MHz\n", adt.performance.count, performance.count, layout, @@ -41,7 +28,7 @@ pub(crate) fn qualify( for i in 0..performance.count { dev_info!( dev, - "M4 ADT DVFS S{}: main={} MHz auxiliary={} MHz core={} mV SRAM={} mV\n", + "GPU ADT DVFS S{}: main={} MHz auxiliary={} MHz core={} mV SRAM={} mV\n", i, performance.frequency[i], performance.auxiliary[i], diff --git a/drivers/gpu/drm/asahi/g16/board/data.rs b/drivers/gpu/drm/asahi/g16/board/data.rs index ee203adbc736ab..12dc2884263fc2 100644 --- a/drivers/gpu/drm/asahi/g16/board/data.rs +++ b/drivers/gpu/drm/asahi/g16/board/data.rs @@ -1,18 +1,8 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT -//! Qualified selections of the original ADT's sixteen performance states for 25G83. +//! Select firmware DVFS rows from this machine's ADT performance states. //! -//! 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; - -#[derive(Clone, Copy)] -pub(crate) enum SourceLayout { - T8132, - T6030, -} +//! Each row pairs a main and an auxiliary frequency at a shared voltage. /// One qualified mapping of the ADT states onto the first `rows` firmware rows. pub(crate) struct Layout { @@ -45,9 +35,9 @@ pub(crate) const LAYOUTS: [Layout; 2] = [ }, ]; -// Three low states, then five equal-voltage pairs. The equal frequency at source +// Four low states, then five equal-voltage pairs. The equal frequency at source // states 9 and 10 belongs to two voltage bins and is kept in both rows. -const T6030_LAYOUT: Layout = Layout { +const NINE_ROW_LAYOUT: Layout = Layout { name: "9-row", rows: 9, main: [0, 1, 2, 3, 5, 7, 9, 11, 13, 0, 0], @@ -66,23 +56,14 @@ pub(crate) fn select( /// 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> { - select_for(source, SourceLayout::T8132) -} - -/// Selects firmware rows using the qualified layout for this SoC. -pub(crate) fn select_for( - source: &super::super::adt::perf::Source, - layout: SourceLayout, ) -> core::result::Result<(Performance, &'static str), super::super::adt::perf::Error> { use super::super::adt::perf::Error; - let (count, layouts) = match layout { - SourceLayout::T8132 => (SOURCE_STATES, LAYOUTS.as_slice()), - SourceLayout::T6030 => (14, core::slice::from_ref(&T6030_LAYOUT)), + + let layouts = match source.count { + 14 => core::slice::from_ref(&NINE_ROW_LAYOUT), + 16 => LAYOUTS.as_slice(), + _ => return Err(Error::Shape), }; - if source.count != count { - return Err(Error::Shape); - } for layout in layouts { match select_layout(source, layout) { Err(Error::Shape) => continue, diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 6ef83987bb29e0..ff94d70162529b 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -42,7 +42,6 @@ pub(crate) struct Config { pub(crate) hw_ids: &'static [HwId], /// Compatible of the original ADT SGX node. pub(crate) adt_compatible: &'static [u8], - pub(crate) source_layout: super::board::data::SourceLayout, /// Qualified boot-loader handoffs. pub(crate) layouts: &'static [&'static FwLayout], /// Qualified firmware builds. @@ -92,7 +91,6 @@ pub(crate) mod t8132 { counts: 0x0011010a, }], adt_compatible: b"gpu,t8132", - source_layout: super::super::board::data::SourceLayout::T8132, layouts: &[&FW_25G83, &FW_26B123], firmware: &[ FirmwareBuild { @@ -303,7 +301,7 @@ pub(crate) mod t8132 { /// T6030 (G15S), qualified with the b000 image loaded on J516s. pub(crate) mod t6030 { - use super::super::{board::data::SourceLayout, fw::initdata}; + use super::super::fw::initdata; use super::{Config, FirmwareBuild, FwLayout, HwId, Scratch, FW_26B123, HOST_BLOCK, UPPER}; pub(crate) const CONFIG: Config = Config { @@ -321,7 +319,6 @@ pub(crate) mod t6030 { counts: 0x00110209, }], adt_compatible: b"gpu,t6030", - source_layout: SourceLayout::T6030, layouts: &[&LAYOUT], firmware: &[FirmwareBuild { name: "Apple GFX 26B123 G15S (build b000, iBoot-filled ranges zeroed)", diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 27555241f40cef..0fedb4d9d0f8bd 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -107,7 +107,7 @@ pub(crate) fn build( ) -> Result<(InitData, Channels, u32)> { let abi = adt.layout.abi; let layout = adt.layout.initdata; - let performance = board::qualify(dev, adt, cfg.source_layout)?; + let performance = board::qualify(dev, adt)?; // The top row of the qualified table, excluding the off state. let ceiling = performance.count as u32 - 1; let rows = performance.count as u32; 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 b696ece088d2f3..50785414007938 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-perf.py @@ -159,12 +159,14 @@ def node(props, children=()): } #[test] fn g15s_power_config_uses_the_encoded_ceiling_and_machine_adt_limiter() { - let mut performance = tables(); - performance.count = 9; - performance.frequency[9..].fill(0); - performance.auxiliary[9..].fill(0); - performance.voltage[9..].fill(0); - performance.sram[9..].fill(0); + let mut sgx = source(); + sgx.count = 14; + let (performance, shape) = data::select_named(&sgx).unwrap(); + assert_eq!((performance.count, shape), (9, "9-row")); + assert_eq!(performance.frequency[8], sgx.frequency_mhz[13]); + assert_eq!(performance.auxiliary[8], sgx.frequency_mhz[12]); + sgx.core_mv[12] += 1; + assert_eq!(data::select(&sgx), Err(perf::Error::Shape)); let layout = &wire::G15S_26B123; let mut input = input(performance); From 6b91bfb1ee33e3f1e22fcc28dbe7600bf40571ee Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 00:42:52 -0500 Subject: [PATCH 1272/1514] dt-checks: scope /chosen filtering to chosen.yaml and fail on filter errors Fix two review issues in scripts/dtc/apple-dt-check.sh: 1. Check filter_documented_chosen (and the warning extraction pipeline) exit status explicitly for both BASE and HEAD before comparing warning lists. Previously a failing filter (for example when neither PyYAML nor ruamel.yaml is available) exited non-zero inside the pipeline while sort wrote an empty warning file and warnings() returned make's exit status, silently dropping HEAD warnings with exit status 0. Fail immediately with a clear stderr message on any filter failure, while cleaning up the BASE worktree via an EXIT trap. 2. Run filter_documented_chosen on the raw CHECK_DTBS log (with make -Otarget to prevent parallel interleaving) before grep/perl strip 'from schema $id:' and regex tails, and subtract bindings/chosen/*.yaml properties only when the warning carries upstream chosen.yaml's exact schema ID (http://devicetree.org/schemas/chosen.yaml#). Warnings from any other schema ID or with no schema ID are left untouched. Signed-off-by: Diljit Singh --- scripts/dtc/apple-dt-check.sh | 139 +++++++++++++++++++++++++++------- 1 file changed, 113 insertions(+), 26 deletions(-) diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index 398a147bf6cac3..d6f30d6b440e5b 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -6,10 +6,11 @@ # is the pattern list of a "does not match any of the regexes" message, which grows with every # vendor prefix the bindings add. Upstream dtschema's chosen.yaml sets additionalProperties: false, # so properties documented in in-tree bindings/chosen/*.yaml are subtracted from "chosen: ... -# do(es) not match any of the regexes:" lines while preserving warnings for any undocumented -# properties and all schema type/value checks. A firmware-profile variant (a .dts that includes -# another board's .dts, such as t8122-j613-25g83) is reported under its base board's name, so the -# base's existing warnings are not new warnings of the variant; anything the variant adds still is. +# do(es) not match any of the regexes:" lines emitted by http://devicetree.org/schemas/chosen.yaml# +# while preserving warnings from any other schema, warnings for any undocumented properties, and +# all schema type/value checks. A firmware-profile variant (a .dts that includes another board's +# .dts, such as t8122-j613-25g83) is reported under its base board's name, so the base's existing +# warnings are not new warnings of the variant; anything the variant adds still is. # Needs dtschema (dt-validate), clang/lld (LLVM=1), flex, bison, python3. Prints a summary. set -u BASE=$1 HEAD=$2 W=$3 @@ -19,20 +20,31 @@ filter_documented_chosen() { # chosen_bindings_dir python3 -c ' import glob, os, re, sys -def load_yaml(path): +CHOSEN_SCHEMA_ID = "http://devicetree.org/schemas/chosen.yaml#" + +def get_yaml_loader(): try: import yaml - with open(path, encoding="utf-8") as f: - return yaml.safe_load(f) + return yaml.safe_load except ImportError: + pass + try: from ruamel.yaml import YAML - with open(path, encoding="utf-8") as f: - return YAML(typ="safe").load(f) + loader = YAML(typ="safe") + return loader.load + except ImportError: + sys.stderr.write( + "apple-dt-check.sh: neither PyYAML nor ruamel.yaml is available " + "to parse bindings/chosen/*.yaml\n" + ) + sys.exit(1) +load_yaml = get_yaml_loader() chosen_dir = sys.argv[1] documented = set() for path in sorted(glob.glob(os.path.join(chosen_dir, "*.yaml"))): - doc = load_yaml(path) + with open(path, encoding="utf-8") as f: + doc = load_yaml(f) if not isinstance(doc, dict): continue props = doc.get("properties") @@ -43,17 +55,51 @@ for path in sorted(glob.glob(os.path.join(chosen_dir, "*.yaml"))): documented.add(key) pat = re.compile( - r"^(?P[^\n]*\.dtb: chosen: )" + r"^(?P[^\s\n][^\n]*\.dtb: chosen: )" r"(?P\x27[^\x27]+\x27(?:, \x27[^\x27]+\x27)*)" r" (?:does|do) not match any of the regexes:(?P.*)$" ) +inline_schema_re = re.compile(r"\s+from schema \$id:\s*(\S+)\s*$") +hint_line_re = re.compile(r"^[ \t]+hint: ") +schema_line_re = re.compile(r"^[ \t]+from schema \$id:\s*(\S+)\s*$") -for raw in sys.stdin: - line = raw.rstrip("\n") +lines = sys.stdin.readlines() +i = 0 +n = len(lines) +while i < n: + raw = lines[i] + line = raw.rstrip("\r\n") m = pat.match(line) if not m: sys.stdout.write(raw) + i += 1 + continue + + cont = [] + schema_id = None + m_inline = inline_schema_re.search(m.group("tail")) + if m_inline: + schema_id = m_inline.group(1) + i += 1 + else: + j = i + 1 + while j < n and hint_line_re.match(lines[j]): + cont.append(lines[j]) + j += 1 + if j < n: + m_schema = schema_line_re.match(lines[j].rstrip("\r\n")) + if m_schema: + schema_id = m_schema.group(1) + cont.append(lines[j]) + j += 1 + i = j + + if schema_id != CHOSEN_SCHEMA_ID: + sys.stdout.write(raw) + for c in cont: + sys.stdout.write(c) continue + props = re.findall(r"\x27([^\x27]+)\x27", m.group("props")) remaining = [p for p in props if p not in documented] if not remaining: @@ -63,38 +109,80 @@ for raw in sys.stdin: prefix = m.group("prefix") tail = m.group("tail") sys.stdout.write(f"{prefix}{joined} {verb} not match any of the regexes:{tail}\n") + for c in cont: + sys.stdout.write(c) ' "$1" } -warnings() { # rev tag - local t=$W/src-$2 o=$W/out-$2 - rm -f "$W/$2.warn" - git worktree add -q --detach "$t" "$1" || return 1 - make -s -C "$t" O="$o" defconfig >/dev/null || return 1 - local dtbs; dtbs=$(cd "$t/arch/arm64/boot/dts" && ls apple/*.dts | sed 's/dts$/dtb/') - make -C "$t" O="$o" -j"$(nproc)" CHECK_DTBS=y $dtbs > "$W/$2.log" 2>&1 - local rc=$? +extract_warnings() { # src_dir out_dir log_file out_warn tag + local t=$1 o=$2 log=$3 out=$4 tag=$5 + local filtered=$W/$tag.filtered.log + rm -f "$filtered" "$out" + if ! filter_documented_chosen "$t/Documentation/devicetree/bindings/chosen" < "$log" > "$filtered"; then + rm -f "$filtered" "$out" + echo "apple-dt-check.sh: $tag: failed to filter documented /chosen warnings" >&2 + filter_failed=1 + return 1 + fi local variants; variants=$(cd "$t/arch/arm64/boot/dts" && grep -l '^#include "[^"]*\.dts"' apple/*.dts 2>/dev/null | while read -r v; do sed -nE 's#^\#include "([^"]*)\.dts".*#s|^'"${v%.dts}"'\\.dtb: |apple/\1.dtb: |;#p' "$v" | head -1 done) - grep -E '\.dtb: |[Ww]arning|rror' "$W/$2.log" | grep -v '^ ' | + grep -E '\.dtb: |[Ww]arning|rror' "$filtered" | grep -v '^ ' | sed -E "s#$t/##g; s#$o/##g" | sed -E "s#arch/arm64/boot/dts/##; $variants" | sed -E 's#^apple/#arch/arm64/boot/dts/apple/#' | perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | - filter_documented_chosen "$t/Documentation/devicetree/bindings/chosen" | - sort -u > "$W/$2.warn" + sort -u > "$out" + local ps=("${PIPESTATUS[@]}") + if [ "${ps[0]}" -gt 1 ] || [ "${ps[1]}" -gt 1 ] || [ "${ps[2]}" -ne 0 ] || [ "${ps[3]}" -ne 0 ] || [ "${ps[4]}" -ne 0 ] || [ "${ps[5]}" -ne 0 ] || [ "${ps[6]}" -ne 0 ]; then + rm -f "$out" + echo "apple-dt-check.sh: $tag: warning extraction pipeline failed (status: ${ps[*]})" >&2 + filter_failed=1 + return 1 + fi +} +warnings() { # rev tag + local t=$W/src-$2 o=$W/out-$2 + filter_failed=0 + rm -f "$W/$2.warn" "$W/$2.filtered.log" + git worktree add -q --detach "$t" "$1" || return 1 + make -s -C "$t" O="$o" defconfig >/dev/null || return 1 + local dtbs; dtbs=$(cd "$t/arch/arm64/boot/dts" && ls apple/*.dts | sed 's/dts$/dtb/') + make -C "$t" O="$o" -j"$(nproc)" -Otarget CHECK_DTBS=y $dtbs > "$W/$2.log" 2>&1 + local rc=$? + extract_warnings "$t" "$o" "$W/$2.log" "$W/$2.warn" "$2" || return 1 echo "$2: make rc=$rc, $(wc -l < "$W/$2.warn") warning lines, $(echo $dtbs | wc -w) DTBs" return $rc } +cleanup() { + git worktree remove --force "$W/src-base" 2>/dev/null || true +} +trap cleanup EXIT fail=0 -warnings "$BASE" base || echo "base build failed (its warnings still count)" +filter_failed=0 +warnings "$BASE" base; brc=$? +if [ "$filter_failed" -ne 0 ]; then + echo "apple-dt-check.sh: BASE $BASE warning filtering failed" >&2 + exit 1 +fi +if [ "$brc" -ne 0 ]; then + echo "base build failed (its warnings still count)" +fi if [ ! -f "$W/base.warn" ]; then # No list to compare against: every HEAD warning counts as new. echo "BASE $BASE could not be checked out or configured" : > "$W/base.warn" fail=1 fi +filter_failed=0 warnings "$HEAD" head; hrc=$? +if [ "$filter_failed" -ne 0 ]; then + echo "apple-dt-check.sh: HEAD $HEAD warning filtering failed" >&2 + exit 1 +fi +if [ ! -f "$W/head.warn" ]; then + echo "apple-dt-check.sh: HEAD $HEAD could not be checked out or configured" >&2 + exit 1 +fi comm -13 "$W/base.warn" "$W/head.warn" > "$W/new.warn" comm -23 "$W/base.warn" "$W/head.warn" > "$W/gone.warn" echo "new warnings: $(wc -l < "$W/new.warn"), removed: $(wc -l < "$W/gone.warn")" @@ -109,5 +197,4 @@ for f in $b; do echo "--- binding check failed: $f"; cat "$W/binding.log"; fail=1 fi done -git worktree remove --force "$W/src-base" 2>/dev/null; true exit $fail From 1cbb26c58017d4dc3b5efb58007c4e44960f6297 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:12:36 -0500 Subject: [PATCH 1273/1514] dt-bindings: sound: apple,aop-audio: select fallback lists Match the first compatible in one- or two-entry lists. Give the selector an explicit upper bound so schema processing does not infer a single item from the primary-compatible constraint. T6041 and T8132 remain covered by their own binding. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- Documentation/devicetree/bindings/sound/apple,aop-audio.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml index 5da4e92e751279..6298b45288103a 100644 --- a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml @@ -20,6 +20,8 @@ description: | select: properties: compatible: + minItems: 1 + maxItems: 2 items: - enum: - apple,t6000-aop-audio @@ -29,6 +31,7 @@ select: - apple,t8103-aop-audio - apple,t8112-aop-audio - apple,t8122-aop-audio + additionalItems: true required: - compatible From 2737d4be66618291a785aedf0c0953fa4e17d039 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:49:53 -0500 Subject: [PATCH 1274/1514] arm64: dts: apple: wire the T6030 DCP bandwidth scratch slot The internal display uses slot 1 in the PMGR bandwidth window for bandwidth requests on firmware 27.2. Point the DCP at that slot in disp-5 so the driver can resolve the scratch register. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6030-dcp.dtsi | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi index c2324b1083a616..511ebabee55b3d 100644 --- a/arch/arm64/boot/dts/apple/t6030-dcp.dtsi +++ b/arch/arm64/boot/dts/apple/t6030-dcp.dtsi @@ -87,6 +87,8 @@ <0x2 0x8e850000 0x0 0x4000>; power-domains = <&ps_disp_cpu>; clocks = <&clk_disp0>; + /* Display bandwidth request slot in the disp-5 window. */ + apple,bw-scratch = <&pmgr_dcp 0 5 0x988>; #address-cells = <2>; #size-cells = <2>; ranges; @@ -97,6 +99,12 @@ }; }; + pmgr_dcp: power-management@3503d0000 { + reg = <0x3 0x503d0000 0x0 0x4000>; + reg-names = "dcp-fw-pmgr"; + #apple,bw-scratch-cells = <3>; + }; + dcpext_dart: iommu@2d130c000 { compatible = "apple,t6030-dart", "apple,t8110-dart"; reg = <0x2 0xd130c000 0x0 0x4000>; From a54d9f2deca62e22c1f628a91e1d9a923eb0811a Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:53:38 -0500 Subject: [PATCH 1275/1514] drm/asahi: honor G15S root, channel and buffer layouts Check the post-start UAT links against the qualified table offset and attributes for each ABI. Read submit completion from the consumer cursor on rings with a producer header. Device-control rings retain their separate completion word. Accept empty shader-context scratch reservations on hardware without render scratch slots. Keep the hardware descriptor available to the running backend. Encode the parameter-buffer slot ID once on G15S so that the adjacent bank selector stays zero for nonzero slot IDs. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/channel.rs | 7 +++- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 16 +++++---- drivers/gpu/drm/asahi/g16/hw.rs | 15 ++++++++ drivers/gpu/drm/asahi/g16/mod.rs | 6 +++- drivers/gpu/drm/asahi/g16/queue.rs | 19 ++++++----- drivers/gpu/drm/asahi/g16/uat.rs | 7 ++-- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 34 +++++++++++++++++-- .../drivers/gpu/asahi-m4/test-abi-26b123.py | 3 ++ .../drivers/gpu/asahi-m4/test-ray-tracing.py | 33 +++++++++++++++++- .../selftests/drivers/gpu/asahi-m4/test-vm.py | 33 ++++++++++++++++-- 10 files changed, 148 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index c2ee881cac26a6..22c792c1135534 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -61,7 +61,12 @@ impl Ring { /// The completion index in the channel's state block. pub(crate) fn completion(&self) -> Result { - self.state.r32(self.completion) + // Submit rings with a producer header retire at the consumer's read cursor. + if self.header != 0 { + self.read() + } else { + self.state.r32(self.completion) + } } /// The producer's write index, either in state or at the start of the ring. diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index 4dc6483ffc5462..06438c04136d4b 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -51,8 +51,10 @@ pub(crate) mod pb_manager { /// shifted `-4` bytes from `ID_A` onward). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Layout { + /// Primary parameter-buffer slot ID offset (`parameter_id` / PBID). pub(crate) id_a: usize, - pub(crate) id_b: usize, + /// Secondary slot ID offset, when the record carries a second copy. + pub(crate) id_b: Option, pub(crate) page_list_fw: usize, pub(crate) page_list: usize, pub(crate) page_list_bytes: usize, @@ -70,7 +72,7 @@ pub(crate) mod pb_manager { pub(crate) const V25G83: Layout = Layout { id_a: ID_A, - id_b: ID_B, + id_b: Some(ID_B), page_list_fw: PAGE_LIST_FW, page_list: PAGE_LIST, page_list_bytes: PAGE_LIST_BYTES, @@ -86,12 +88,10 @@ pub(crate) mod pb_manager { max_pages_b: MAX_PAGES_B, }; - /// G15S 26B123 PB manager (`0x90`-byte firmware record invalidated by TA and InitBM): - /// `id_a` at `+0x08`, `id_b` at `+0x0c`, `page_list_fw` at `+0x1c`, `blocks` at `+0x38`, - /// `block_ctl` at `+0x48`, `counter` at `+0x60`. + /// G15S 26B123 uses one slot ID. The adjacent bank selector stays zero. pub(crate) const V26B123_G15S: Layout = Layout { id_a: 0x08, - id_b: 0x0c, + id_b: None, page_list_fw: 0x1c, page_list: 0x24, page_list_bytes: 0x2c, @@ -184,7 +184,9 @@ pub(crate) fn pb_manager_image_for( let pages = blocks * PAGES_PER_BLOCK; let mut m = [0; pb_manager::SIZE]; put32(&mut m, layout.id_a, id); - put32(&mut m, layout.id_b, id); + if let Some(id_b) = layout.id_b { + put32(&mut m, id_b, id); + } put64(&mut m, layout.page_list_fw, pages_fw); put64(&mut m, layout.page_list, pages_gpu); put32(&mut m, layout.page_list_bytes, PAGE_LIST_SIZE as u32); diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index ff94d70162529b..194e5dcd4a0b04 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -62,6 +62,8 @@ pub(crate) struct Config { pub(crate) host_block_ready: bool, /// Whether the TVM gate and firmware warm restart are supported. pub(crate) deep_sleep: bool, + /// Whether render work accepts scratch for ray queries. + pub(crate) supports_render_scs: bool, /// Whether FS->compute cross-engine barriers require `BarrierType::Hold` (type 1), as on G15. pub(crate) cross_engine_hold: bool, } @@ -189,6 +191,7 @@ pub(crate) mod t8132 { host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, host_block_ready: true, deep_sleep: true, + supports_render_scs: true, cross_engine_hold: false, }; @@ -343,6 +346,7 @@ pub(crate) mod t6030 { host_block_zero_order: &[0, 0x1808, 0x3010], host_block_ready: false, deep_sleep: false, + supports_render_scs: false, cross_engine_hold: true, }; @@ -443,6 +447,17 @@ pub(crate) enum FwAbi { V26B123G15S, } +impl FwAbi { + /// Offset of the table installed in root[1] after startup, and the + /// descriptor attributes the firmware uses for it and the shared L2. + pub(crate) const fn live_root_table(self) -> (u64, u64) { + match self { + Self::V25G83 | Self::V26B123 => (4 * PAGE, 0x00200000000004cb), + Self::V26B123G15S => (3 * PAGE, 0x403), + } + } +} + /// How the firmware's MMIO register table in loaded DATA is filled. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum LoaderTable { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index d76460c07cc21a..466db56ef84cf7 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -563,6 +563,8 @@ impl Shared { /// be stopped, so dropping this structure leaks the firmware-visible parts on purpose /// ([`Gpu::retain`]). pub(crate) struct Firmware { + /// Static hardware configuration for this GPU instance. + pub(crate) cfg: &'static hw::Config, /// RTKit, MMIO, regions, the adopted UAT and the host window. pub(crate) session: boot::Session, /// The initdata graph and its live words (Globals, Control, HardwareData, ...). @@ -693,7 +695,7 @@ impl Gpu { let uat = booted.session.uat(); 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 firmware = Firmware::start_backend(dev, cfg, 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). @@ -735,6 +737,7 @@ impl Firmware { #[inline(never)] fn start_backend( dev: &AsahiDrmDevice, + cfg: &'static hw::Config, mut booted: KBox, shared: &Arc, mut power: power::Power, @@ -779,6 +782,7 @@ impl Firmware { } = KBox::into_inner(booted); let mut firmware = slot .write_init(init!(Firmware { + cfg, session, init, private_factory, diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 54d2503b965ed5..7fadc1a3af5d74 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -179,9 +179,8 @@ pub(crate) struct Queue { timeline: Arc, /// Enabled GPU cores, which SCS memory is sized for. active_cores: u32, - /// Cluster count and GPU generation for stream admission. - num_clusters: u32, - gpu_generation: u32, + /// Hardware capabilities for stream admission and scratch reservations. + cfg: &'static hw::Config, /// Reserved render scratch pages per stage (`render_scs_layout`). render_scs: [u16; 2], // Last field: all preceding fields (especially scheduler) drop before capacity returns. @@ -246,8 +245,7 @@ impl Queue { shared: gpu.shared.clone(), timeline, active_cores: gpu.id.core_masks.iter().map(|mask| mask.count_ones()).sum(), - num_clusters: gpu.cfg.num_clusters, - gpu_generation: gpu.cfg.gpu_generation, + cfg: gpu.cfg, render_scs: [0; 2], _credit: credit, }) @@ -265,12 +263,12 @@ impl Queue { if sync_count > command::MAX_SYNCS { return Err(EINVAL); } - let parsed = if self.gpu_generation < 16 { + let parsed = if self.cfg.gpu_generation < 16 { command::parse_stream_for( bytes, params::early_tiling(), - self.num_clusters, - self.gpu_generation, + self.cfg.num_clusters, + self.cfg.gpu_generation, )? } else { command::parse_stream(bytes, params::early_tiling())? @@ -370,7 +368,10 @@ impl crate::queue::Queue for Queue { /// A render's UMA pool serves both stages of one render at a time, so their extra pages add /// up ([`super::rt::required_seeds`]). fn reserve_render_scs(&mut self, layouts: [u64; 2]) -> Result { - if self.gpu_generation < 16 { + if !self.cfg.supports_render_scs { + if layouts == [0; 2] { + return Ok(()); + } return Err(Error::from_errno(-(kernel::bindings::EOPNOTSUPP as i32))); } if self.accepted != [0; 2] { diff --git a/drivers/gpu/drm/asahi/g16/uat.rs b/drivers/gpu/drm/asahi/g16/uat.rs index b49944399e8a4d..e43e453819281d 100644 --- a/drivers/gpu/drm/asahi/g16/uat.rs +++ b/drivers/gpu/drm/asahi/g16/uat.rs @@ -181,6 +181,7 @@ pub(crate) struct Window { /// Observed firmware-owned root words; only the exact qualified forward transition is /// accepted after RUN, never a rollback or an unrelated physical table. firmware_root: [u64; 2], + abi: hw::FwAbi, text_pa: u64, data_pa: u64, /// The leaves the boot loader builds in this firmware's page tables (none for a firmware @@ -202,6 +203,7 @@ impl Window { snapshot: KVec::from_elem(0u64, ENTRIES, GFP_KERNEL)?, published: false, firmware_root: [0; 2], + abi: adt.layout.abi, text_pa: adt.text.start, data_pa: adt.data.start, // Admission refuses a layout with either unknown; never guess them here. @@ -453,6 +455,7 @@ impl Window { /// Confirms the shared root still names the driver's reserved L2 and only recognizes /// the qualified firmware-owned forward transitions in root[0..1]. fn verify_root(&mut self) -> Result { + let (table_offset, attributes) = self.abi.live_root_table(); for index in 0..2 { let observed = self.root.io().try_read64(index * 8)?; if observed == self.firmware_root[index] { @@ -461,7 +464,7 @@ impl Window { let expected = if index == 0 { (self.root.phys() + hw::PAGE) | 0x403 } else { - (self.root.phys() + 0x10000) | 0x00200000000004cb + (self.root.phys() + table_offset) | attributes }; if self.firmware_root[index] != 0 || observed != expected { return Err(EIO); @@ -469,7 +472,7 @@ impl Window { self.firmware_root[index] = observed; } let root = self.root.io().try_read64(WINDOW_INDEX * 8)?; - if root != self.shared_l2.phys() | 3 && root != self.shared_l2.phys() | 0x00200000000004cb { + if root != self.shared_l2.phys() | 3 && root != self.shared_l2.phys() | attributes { return Err(EIO); } Ok(()) 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 aacb13fc69b2a3..f9fe14e89f8c9c 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 @@ -301,10 +301,32 @@ fn queues(out: &std::path::Path) { std::fs::write(out.join("queue.bin"), all).unwrap(); } +mod ring_test { + use super::fw::{channels::STATE_READ, initdata::TxLayout}; + use std::sync::Arc; + + type Result = std::result::Result; + pub(crate) struct FwObject([u32; 5]); + impl FwObject { + fn r32(&self, offset: usize) -> Result { + self.0.get(offset / 4).copied().ok_or(()) + } + } + @RING@ + + pub(super) fn check(tx: TxLayout, submit: u32, control: u32) { + let state = Arc::new(FwObject([2, 0, 5, 0, 7])); + for (is_control, expected) in [(false, submit), (true, control)] { + let ring = Ring::new(state.clone(), state.clone(), tx, is_control); + assert_eq!(ring.completion(), Ok(expected)); + } + } +} + fn g15s_26b123() { let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; - // PB manager: G15S 26B123 shifts every field -4 bytes vs G16G. + // The word after the slot ID selects the hardware bank. let pb = fw::buffer::pb_manager_image_for( FwAbi::V26B123G15S.pb_manager(), 3, @@ -315,7 +337,7 @@ fn g15s_26b123() { f + 0x700000, 512, ); - assert_eq!((r32(&pb, 0x08), r32(&pb, 0x0c)), (3, 3)); + assert_eq!((r32(&pb, 0x08), r32(&pb, 0x0c)), (3, 0)); assert_eq!(r64(&pb, 0x1c), f + 0x400000); assert_eq!(r64(&pb, 0x24), g + 0x701a040000); assert_eq!( @@ -585,6 +607,14 @@ fn main() { render(&out); compute_work(&out); queues(&out); + for layout in backend_hw::t8132::CONFIG.layouts { + ring_test::check(layout.initdata.tx, 7, 7); + let pb = fw::buffer::pb_manager_image_for(layout.abi.pb_manager(), 3, 0, 0, 0, 0, 0, 1); + assert_eq!((r32(&pb, 0x0c), r32(&pb, 0x10)), (3, 3)); + } + assert!(backend_hw::t8132::CONFIG.supports_render_scs); + assert!(!backend_hw::t6030::CONFIG.supports_render_scs); + ring_test::check(wire::G15S_26B123.tx, 2, 5); g15s_26b123(); 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/test-abi-26b123.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-abi-26b123.py index a5765e8c4546de..839fccfaa58be1 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 @@ -200,6 +200,9 @@ def main(): first = identity.index('pub(crate) struct FirmwareBuild {') source = (HERE / 'check-abi-26b123.rs').read_text().replace('@KERNEL@', str(root)) source = source.replace('@FWID_BUILD@', identity[first:identity.index('\n}', first) + 2]) + channel = (root / 'drivers/gpu/drm/asahi/g16/channel.rs').read_text() + ring = channel[channel.index('pub(crate) struct Ring {'):channel.index(' /// The producer')] + source = source.replace('@RING@', ring + '}') harness = out / 'check-abi-26b123.rs' harness.write_text(source) binary = out / 'check-abi-26b123' diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py index bfc62d7c4c9ef5..dcb1e18100c0fd 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -79,6 +79,7 @@ def block(text, declaration): engine = (BACKEND / 'engine.rs').read_text() admission = '\n'.join(function(command, name) for name in ['check_intersection', 'check_render_ray', 'check_compute_ray']) +reserve = function((BACKEND / 'queue.rs').read_text(), 'reserve_render_scs') conversion = '\n'.join(function(engine, name) for name in ['compute_rt', 'stage_rt']) # The client address map, which bounds SCS pools (SCS_POOL_WINDOW). client = block((BACKEND / 'hw.rs').read_text(), 'pub(crate) mod client {') @@ -147,6 +148,36 @@ def block(text, declaration): } } struct Context<'a> { vm: &'a mmu::Vm, usc_base: u64, active_cores: u32, render_scs: [u16; 2] } +mod queue_test { + use super::*; + struct Config { supports_render_scs: bool } + struct Queue { cfg: Config, accepted: [u64; 2], active_cores: u32, render_scs: [u16; 2] } + const EBUSY: i32 = -16; + struct Error; + impl Error { fn from_errno(code: i32) -> i32 { code } } + impl Queue { @RESERVE@ } + + #[test] + fn reserve_scratch() { + let mut q = Queue { + cfg: Config { supports_render_scs: false }, + accepted: [0; 2], active_cores: 10, render_scs: [0; 2], + }; + let (layout, pages) = LAYOUTS[0]; + assert_eq!(q.reserve_render_scs([0, 0]), Ok(())); + for request in [[layout, 0], [0, layout]] { + assert_eq!(q.reserve_render_scs(request), Err(-95)); + assert_eq!(q.render_scs, [0, 0]); + } + q.cfg.supports_render_scs = true; + assert_eq!(q.reserve_render_scs([layout, 0]), Ok(())); + assert_eq!(q.render_scs, [pages, 0]); + q.accepted = [1, 0]; + assert_eq!(q.reserve_render_scs([0, 0]), Err(EBUSY)); + assert_eq!(q.render_scs, [pages, 0]); + } +} +pub mod bindings { pub const EOPNOTSUPP: u32 = 95; } @ADMISSION@ @CONVERSION@ type KBox = Box; @@ -577,7 +608,7 @@ def block(text, declaration): (staged / 'encode.rs').write_text(encode_source + gates) source = harness for key, value in {'@FLAT@': str(FLAT), '@ADMISSION@': admission, '@CONVERSION@': conversion, - '@LONG@': long, '@CLIENT@': client}.items(): + '@RESERVE@': reserve, '@LONG@': long, '@CLIENT@': client}.items(): source = source.replace(key, value) source = source.replace('#[path = "@BACKEND@/encode.rs"]', '#[path = "' + str(staged / 'encode.rs') + '"]') source = source.replace('@BACKEND@', str(BACKEND)) 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 7553c91f4ffc8f..0c859eca42aa71 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm.py @@ -26,6 +26,8 @@ def body(source, marker): 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) enum FwAbi {'), + body(hw, 'impl FwAbi {'), 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() @@ -89,8 +91,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,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}}} +struct Window{abi:hw::FwAbi,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{abi:hw::FwAbi::V25G83,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''' } @@ -117,9 +119,36 @@ 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();} } +fn live_root_tests() { + for abi in [hw::FwAbi::V25G83, hw::FwAbi::V26B123, hw::FwAbi::V26B123G15S] { + let mut w = Window::blank(); + w.abi = abi; + let compact = abi == hw::FwAbi::V26B123G15S; + let g15_table = (w.root.pa + 3 * hw::PAGE) | 0x403; + let g16_table = (w.root.pa + 4 * hw::PAGE) | 0x00200000000004cb; + let (table, other) = if compact { (g15_table, g16_table) } else { (g16_table, g15_table) }; + w.root.try_write64(w.shared_l2.pa | 3, 16).unwrap(); + w.root.try_write64(other, 8).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(table, 8).unwrap(); + w.verify_root().unwrap(); + let flags = if compact { 0x403 } else { 0x00200000000004cb }; + let wrong_flags = if compact { 0x00200000000004cb } else { 0x403 }; + w.root.try_write64(w.shared_l2.pa | wrong_flags, 16).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(w.shared_l2.pa | flags, 16).unwrap(); + w.verify_root().unwrap(); + w.root.try_write64((w.shared_l2.pa + hw::PAGE) | flags, 16).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + w.root.try_write64(w.shared_l2.pa | flags, 16).unwrap(); + w.root.try_write64(0, 8).unwrap(); + assert_eq!(w.verify_root(), Err(EIO)); + } +} // 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(){ + live_root_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()); From 822a1dd7369c6594f05fe3f31bb43385ba721727 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 08:56:56 +0300 Subject: [PATCH 1276/1514] selftests: apple: centauri-scan: stub centauri_recovery_request The scan worker now asks for a recovery when Alpha leaves its running stage (from main). The host model of the worker has no recovery path, so give it a counting stub and keep the scan tests building. Signed-off-by: Nick --- tools/asahi/centauri-scan-tests.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/asahi/centauri-scan-tests.py b/tools/asahi/centauri-scan-tests.py index cb41035cf500bc..a095cb79c2b057 100755 --- a/tools/asahi/centauri-scan-tests.py +++ b/tools/asahi/centauri-scan-tests.py @@ -394,6 +394,11 @@ def extract_fn(source, name): static void mutex_lock(int *l) { assert(!*l); *l = 1; } static void mutex_unlock(int *l) { assert(*l); *l = 0; } static u32 readl(void *addr) { (void)addr; return bar_state; } +static unsigned int recovery_requests; +static void centauri_recovery_request(struct centauri *c, const char *why) +{ + (void)c; (void)why; recovery_requests++; +} static size_t build_scan(struct centauri_wifi *w, unsigned int c, u8 *b) { (void)w; (void)c; (void)b; From 3928d792a14534a05e77065cd8a8c9f8a0650c77 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 01:28:32 -0500 Subject: [PATCH 1277/1514] sched/fair: enable FORK_LOCAL by default and scan LLC from its first CPU Scanning the local LLC round-robin from cpu + 1 spreads sequential fork/exec loops across every core in a cluster, diluting per-CPU PELT utilization under schedutil and dropping cluster frequency during posix_spawn benchmarks. Scanning from the first CPU of the LLC keeps a sequential parent/child pair warm on two cores while still filling the remaining idle cores during concurrent fan-out. Enable FORK_LOCAL by default so new threads and processes start in the creator's LLC on a default boot without a debugfs toggle. Signed-off-by: Satya Benson --- kernel/sched/fair.c | 2 +- kernel/sched/features.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 98dcd6d33d15d4..95eb408358bb67 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -10018,7 +10018,7 @@ static int fork_local_idle_cpu(struct sched_domain *sd, if (!llc_sd || !(llc_sd->flags & SD_BALANCE_FORK)) return -1; - for_each_cpu_wrap(i, sched_domain_span(llc_sd), cpu + 1) { + for_each_cpu(i, sched_domain_span(llc_sd)) { if (i == cpu || !cpumask_test_cpu(i, sched_domain_span(sd)) || !cpumask_test_cpu(i, p->cpus_ptr)) continue; diff --git a/kernel/sched/features.h b/kernel/sched/features.h index 71afc624b09b58..a6def9a19c001e 100644 --- a/kernel/sched/features.h +++ b/kernel/sched/features.h @@ -106,7 +106,7 @@ SCHED_FEAT(WAKE_SHORT_LOCAL, true) * cache with the task creating it, before looking further. See * fork_local_idle_cpu(). */ -SCHED_FEAT(FORK_LOCAL, false) +SCHED_FEAT(FORK_LOCAL, true) /* * Issue a WARN when we do multiple update_rq_clock() calls From 7802e9de5983f950800ef870e599d5195203b368 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:44:49 -0500 Subject: [PATCH 1278/1514] dt-bindings: sound: apple,aop-audio: document apple,no-beamforming Document the boolean apple,no-beamforming property already read by sound/soc/apple/aop_audio.rs and used by t8103-j456.dts and t8103-j457.dts, which are now matched by the updated two-entry compatible selector. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- Documentation/devicetree/bindings/sound/apple,aop-audio.yaml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml index 6298b45288103a..2247c81c9eb60b 100644 --- a/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml +++ b/Documentation/devicetree/bindings/sound/apple,aop-audio.yaml @@ -66,6 +66,10 @@ properties: $ref: /schemas/types.yaml#/definitions/string description: Machine family used for the sound card identity. + apple,no-beamforming: + type: boolean + description: Disable microphone array beamforming on boards without it. + required: - compatible - dmas From 50bc7fab53cbaa6948a48e321c76bd8bbdb09122 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 09:58:44 +0300 Subject: [PATCH 1279/1514] soc: apple: sleep: T8142: no timed wake by default apple_sleep.t8142_wake_s defaulted to 30, so every T8142 deep sleep set the PMU's RTC compare 30 s after the commit and woke itself: a closed lid or a menu suspend came back after half a minute. The timer is a test knob (the sleep tests set it themselves), and with it at 0 the PMU keeps its own compare and the sleep lasts until a key, the trackpad, the lid or the power button. Default it to 0. apple_sleep.t8142_wake_s=N still asks for a timed wake. Signed-off-by: Nick --- drivers/soc/apple/sleep.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 7f93efef9ec5a0..310f67083f2134 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -8750,16 +8750,18 @@ static void t8142_lower_io(struct apple_sleep *s) * read RTC_CTL, 0x43 if it had fired, the 4-byte compare at 0x2008, 0x200e <- 0, RTC_CTL <- * 0x41. T6050's post-timer step at the same addresses (apple,pmu-alarm-rearm 0x43 0x41). The * opcode carries the byte count (his follow-up fix). The compare and the counter are read here, - * before the cores' window, with the notes; the compare is now + apple_sleep.t8142_wake_s - * (0 keeps the PMU's own), which is also a wake source: J815 has no RTC device under Linux. + * before the cores' window, with the notes. The compare stays the PMU's own unless + * apple_sleep.t8142_wake_s asks for a timed wake that many seconds after the commit (a test + * knob: J815 has no RTC device under Linux, so nothing else arms one). By default a sleep + * lasts until a key, the trackpad, the lid or the power button wakes it. * J813 still resets with it (PMU took all four commands), so this is parity, not the fix. */ static bool sleep_pmu_alarm = true; module_param_named(pmu_alarm, sleep_pmu_alarm, bool, 0644); MODULE_PARM_DESC(pmu_alarm, "T8142: send the PMU's RTC alarm after the S2R timer, as macOS does (default Y)"); -static unsigned int t8142_wake_s = 30; +static unsigned int t8142_wake_s; module_param(t8142_wake_s, uint, 0644); -MODULE_PARM_DESC(t8142_wake_s, "T8142: the PMU RTC alarm this many s after the commit (0: keep the PMU's)"); +MODULE_PARM_DESC(t8142_wake_s, "T8142 test: wake this many s after the commit (default 0: no timed wake, the PMU's compare stays)"); static u8 t8142_alarm[4]; static bool t8142_alarm_ok; static int t8142_post_ret = -ENODATA; From e7cdc52b560607e152a731adc4ef8424a414c653 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Tue, 17 Nov 2026 21:00:42 +0000 Subject: [PATCH 1280/1514] arm64: dts: apple: t6041-j616c: system power state for the port controllers macOS tells the USB-C port controllers the system power state (SSPS), S3 before a sleep and S0 after it. The tipd driver does the same around a firmware-driven suspend for a controller with apple,sleep-ssps, as the J700, J714s, J716c and J813/J815 have. Give it to the J616c's four SN201202x controllers: hpm0, hpm1, hpm2 and MagSafe's hpm5. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041-j616c.dts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index ccdd779a5e5807..65fce9f16c7491 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -169,3 +169,21 @@ &scaler1 { status = "okay"; }; + +/* The port controllers take system power state S3 for a firmware suspend, as macOS sends it. */ +&hpm0 { + apple,sleep-ssps; +}; + +&hpm1 { + apple,sleep-ssps; +}; + +&hpm2 { + apple,sleep-ssps; +}; + +/* MagSafe's controller follows the sleep too. */ +&hpm5 { + apple,sleep-ssps; +}; From 15841a22b2de928a71407416579ac79fb872b168 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:12:38 -0500 Subject: [PATCH 1281/1514] selftests: apple-dcp: exercise full v27 firmware admission The T6041 host test omits helpers now needed by the firmware selector. The T8122 dcpext test omits the new internal-image helper and extracts the legacy branch, which valid 27.2 firmware returns before reaching. Use the complete selector and its firmware-27 dependencies in both tests. Verify that the pinned images are admitted, that bad UUIDs and builds are refused before any fallback, and that legacy firmware still selects its corresponding backend. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .../selftests/drivers/gpu/apple-dcp/boot.py | 181 +++++++++--------- .../selftests/drivers/gpu/apple-dcp/run.py | 2 +- 2 files changed, 90 insertions(+), 93 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 28533a70b2292b..e6ff1f887d88d2 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -196,25 +196,41 @@ def syslog(root): ''' -def _v27_prelude(root, helpers): - """Host stand-ins for the OF and DCP calls, then the production display.h - helpers named in @helpers, the firmware-27 method tables and - dcp_v27_method_table().""" +def _v27_prelude(root): + """Host stand-ins for OF and legacy board checks, then the live selector.""" display_h = (root / 'include/linux/soc/apple/display.h').read_text() uuid_defines = [line for line in display_h.splitlines() if line.startswith(('#define APPLE_T6041_DCP_26B123_UUID ', '#define APPLE_T8122_DCP_26B123_UUID '))] assert len(uuid_defines) == 2 - helper = '\n'.join((*uuid_defines, *( - block(display_h, 'static inline bool ' + name + '(') for name in helpers))) + helpers = ('static inline bool apple_dcp_image_v27_2(', + 'static inline bool apple_t6041_dcp_any_v27_2(', + 'static inline bool apple_t6041_dcp_v27_2(', + 'static inline bool apple_t6041_dcpext_v27_2(', + 'static inline bool apple_t8122_dcp_v27_2(', + 'static inline bool\napple_t8122_dcpext_v27_2_for_internal(', + 'static inline bool apple_t8122_dcpext_v27_2(') + helper = '\n'.join((*uuid_defines, *(block(display_h, marker) for marker in helpers))) iomfb_h = (root / 'drivers/gpu/drm/apple/iomfb.h').read_text() methods_decl = iomfb_h[iomfb_h.index('enum dcpep_method {'): iomfb_h.index('#define IOMFB_MAX_CB')] v27_c = (root / 'drivers/gpu/drm/apple/iomfb_v27.c').read_text() v27_tables = v27_c[v27_c.index('static const struct dcp_method_entry dcp_methods_27_0'): v27_c.index('/* The template\'s calls resolve through')] - dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() - method_table = block(dcp_c, 'static enum dcp_firmware_version dcp_v27_method_table(') + apple = root / 'drivers/gpu/drm/apple' + dcp_c = (apple / 'dcp.c').read_text() + version_defs = '\n'.join(line for line in dcp_c.splitlines() + if line.startswith('#define DCP_FW_VERSION_')) + version_enum = block((apple / 'version_utils.h').read_text(), + 'enum dcp_firmware_version {') + ';' + admission_enum = block((apple / 'dcp.h').read_text(), 'enum dcp_v27_admission {') + ';' + selector = '\n'.join(block(dcp_c, marker) for marker in ( + 'static int dcp_read_fw_version(', + 'static enum dcp_firmware_version dcp_v27_method_table(', + 'enum dcp_v27_admission dcp_v27_admission(', + 'static bool dcp_firmware_27(', + 'static enum dcp_firmware_version dcp_check_firmware_version(', + )) return r''' #include #include @@ -224,20 +240,16 @@ def _v27_prelude(root, helpers): #include #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) typedef uint32_t u32; -enum dcp_firmware_version { - DCP_FIRMWARE_UNKNOWN, - DCP_FIRMWARE_V_26_6_DESKTOP, - DCP_FIRMWARE_V_27_0, -}; +''' + version_defs + '\n' + version_enum + '\n' + admission_enum + r''' struct dcp_v14_board; struct apple_dcp_hw_data { enum dcp_firmware_version firmware_compat; }; struct device_node { const char *compatible; const char *uuid; int uuid_count; - u32 fw[3]; + u32 fw[DCP_FW_VERSION_MAX_LEN]; int fw_cells; - u32 compat[3]; + u32 compat[DCP_FW_VERSION_MAX_LEN]; int compat_cells; }; struct device { @@ -248,11 +260,11 @@ def _v27_prelude(root, helpers): { return np && np->compatible && !strcmp(np->compatible, s); } -/* The tree's display processors, for of_find_compatible_node(); unused by some units. */ +/* The tree's display processors, for of_find_compatible_node(). */ static struct device_node *of_nodes[2]; static int of_node_refs; -__attribute__((unused)) static struct device_node *of_find_compatible_node(struct device_node *from, - const char *type, const char *s) +static struct device_node *of_find_compatible_node(struct device_node *from, + const char *type, const char *s) { assert(!from && !type); for (unsigned i = 0; i < 2; i++) @@ -262,7 +274,7 @@ def _v27_prelude(root, helpers): } return NULL; } -__attribute__((unused)) static void of_node_put(struct device_node *np) +static void of_node_put(struct device_node *np) { if (np) assert(of_node_refs-- > 0); @@ -290,29 +302,30 @@ def _v27_prelude(root, helpers): return np->compat_cells; return -1; } -static int of_property_read_u32_array(const struct device_node *np, const char *name, u32 *out, size_t n) +static int of_property_read_variable_u32_array(const struct device_node *np, const char *name, + u32 *out, int min, int max) { + int cells = of_property_count_u32_elems(np, name); const u32 *src; - int cells; - if (!np || n != 3) - return -1; - if (!strcmp(name, "apple,firmware-version")) { - src = np->fw; - cells = np->fw_cells; - } else if (!strcmp(name, "apple,firmware-compat")) { - src = np->compat; - cells = np->compat_cells; - } else { - return -1; - } - if (cells != 3) - return -1; - memcpy(out, src, 3 * sizeof(u32)); - return 0; + + if (cells < min || cells > max) + return -EINVAL; + src = !strcmp(name, "apple,firmware-version") ? np->fw : np->compat; + memcpy(out, src, cells * sizeof(*out)); + return cells; +} +static int of_property_read_u32_array(const struct device_node *np, const char *name, u32 *out, int n) +{ + int ret = of_property_read_variable_u32_array(np, name, out, n, n); + + return ret < 0 ? ret : 0; } -#define DCP_FW_VERSION_STR_LEN 32 +#define scnprintf snprintf +#define strscpy(dst, src, size) snprintf((dst), (size), "%s", (src)) #define GFP_KERNEL 0 -#define dev_err(...) ((void)0) +#define dev_warn(...) ((void)0) +#define IS_ERR(ptr) false +static void dev_err(struct device *dev, const char *format, ...) {} static void *devm_kmemdup(struct device *dev, const void *src, size_t len, unsigned int gfp) { (void)dev; (void)src; (void)len; (void)gfp; @@ -322,29 +335,29 @@ def _v27_prelude(root, helpers): { return dev->hw; } -static int dcp_read_fw_version(struct device *dev, const char *name, char *out) +/* No internal board profile is present in these fixtures. */ +static bool of_property_present(struct device_node *np, const char *name) { - u32 v[3]; - if (of_property_count_u32_elems(dev->of_node, name) != 3 || - of_property_read_u32_array(dev->of_node, name, v, 3)) - return -1; - snprintf(out, DCP_FW_VERSION_STR_LEN, "%u.%u.%u", v[0], v[1], v[2]); - return 3; + assert(!strcmp(name, "apple,j613-25g83-profile")); + return false; +} +static bool apple_t8122_25g83_board(void) { return false; } +static int of_property_read_u32(struct device_node *np, const char *name, u32 *out) +{ + return -ENOENT; } -''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + method_table + '\n' +static const struct dcp_v14_board *iomfb_v14_7_board(struct device *dev) { return NULL; } +static const char *iomfb_v14_7_board_name(const struct dcp_v14_board *board) { return ""; } +static bool ext26; +static bool dcp_ext26_admitted(struct device_node *np) { return ext26; } +''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + selector + '\n' def t6041_v27_admission(root): - dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() - selector_full = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') - cutoff = '\n\tret = dcp_read_fw_version(dev, "apple,firmware-compat", compat_str);\n\tif (ret < 0)' - selector = selector_full[:selector_full.index(cutoff)] + '\n\t(void)v14_board;\n\treturn DCP_FIRMWARE_UNKNOWN;\n}\n' - return _v27_prelude(root, ('apple_dcp_image_v27_2', - 'apple_t6041_dcp_any_v27_2', 'apple_t6041_dcp_v27_2', - 'apple_t6041_dcpext_v27_2', 'apple_t8122_dcp_v27_2')) + selector + r''' + return _v27_prelude(root) + r''' static struct device_node node; -static struct apple_dcp_hw_data hw_t6041; -static struct device dev = { .of_node = &node, .hw = &hw_t6041 }; +static const struct apple_dcp_hw_data hw; +static struct device dev = { .of_node = &node, .hw = &hw }; static void reset_t6041_26b123(bool ext) { @@ -387,10 +400,14 @@ def t6041_v27_admission(root): assert(apple_t6041_dcpext_v27_2(&node)); assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); - for (unsigned ext = 0; ext < 2; ext++) { - /* Reject non-T6041 DCP compatibles. */ - reset_t6041_26b123(ext); node.compatible = "apple,t6031-dcp"; expect_rejected(); + /* A different SoC follows generic admission, without the T6041 UUID pin. */ + node.compatible = "apple,t6031-dcp"; + node.uuid_count = 0; + assert(!apple_t6041_dcp_v27_2(&node)); + assert(!apple_t6041_dcpext_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_27_0); + for (unsigned ext = 0; ext < 2; ext++) { /* Reject missing, multi-string, or non-26B123 firmware UUIDs (including 26B131). */ reset_t6041_26b123(ext); node.uuid_count = 0; expect_rejected(); reset_t6041_26b123(ext); node.uuid_count = 2; expect_rejected(); @@ -419,11 +436,9 @@ def t6041_v27_admission(root): } /* * The M3 Air's (T8122) internal DCP handed over with its 27.2 image runs - * the 27.2 table, on any T8122 board; its dcpext, another image, its - * 14.x image and other releases do not. + * the 27.2 table. The external processor needs the internal handoff, + * other firmware-27 images are refused and 14.7 stays on a legacy ABI. */ - static struct apple_dcp_hw_data hw_t8122; - dev.hw = &hw_t8122; reset_t6041_26b123(false); node.compatible = "apple,t8122-dcp"; node.uuid = APPLE_T8122_DCP_26B123_UUID; @@ -439,53 +454,33 @@ def t6041_v27_admission(root): assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid = APPLE_T8122_DCP_26B123_UUID; node.uuid_count = 0; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid_count = 2; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.uuid_count = 1; node.fw[0] = 14; node.fw[1] = 7; node.fw[2] = 0; node.compat[0] = 14; node.compat[1] = 7; node.compat[2] = 0; assert(!apple_t8122_dcp_v27_2(&node)); - assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_V_14_7_TEMPLATE); node.fw[0] = 27; node.fw[1] = 2; node.fw[2] = 1; node.compat[0] = 27; node.compat[1] = 2; node.compat[2] = 1; assert(!apple_t8122_dcp_v27_2(&node)); + assert(dcp_check_firmware_version(&dev) == DCP_FIRMWARE_UNKNOWN); node.fw[2] = 0; node.compat[2] = 0; assert(apple_t8122_dcp_v27_2(&node)); - dev.hw = &hw_t6041; puts("PASS T6041 26B123 v27.2 internal/external admission, refusal controls, and desktop 26.x preservation"); - puts("PASS T8122 internal DCP on its 27.2 image alone runs the 27.2 table"); + puts("PASS T8122 internal DCP needs its 27.2 image for the 27.2 table"); return 0; } ''' def t8122_dcpext_v27_admission(root): - """apple_t8122_dcpext_v27_2() and the apple,t8122-dcpext arm of - dcp_check_firmware_version(), both as the tree has them.""" - dcp_c = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() - selector = block(dcp_c, 'static enum dcp_firmware_version dcp_check_firmware_version(') - arm = block(selector, selector.index( - 'if (of_device_is_compatible(dev->of_node, "apple,t8122-dcpext")) {')) - unit = _v27_prelude(root, ('apple_dcp_image_v27_2', 'apple_t8122_dcp_v27_2', - 'apple_t8122_dcpext_v27_2')) - # The arm runs with the firmware-compat the selector read before it. - return r''' -#define DCP_FIRMWARE_H17P 0x17 -#define DCP_FIRMWARE_V_14_7_TEMPLATE 0x147 -''' + unit + r''' -static bool ext26; -static bool dcp_ext26_admitted(struct device_node *np) { (void)np; return ext26; } -static enum dcp_firmware_version t8122_dcpext_arm(struct device *dev) -{ - char compat_str[DCP_FW_VERSION_STR_LEN] = ""; - - dcp_read_fw_version(dev, "apple,firmware-compat", compat_str); - ''' + arm + r''' - return DCP_FIRMWARE_UNKNOWN; -} - + return _v27_prelude(root) + r''' static struct device_node dcp, dcpext; -static struct device dev = { .of_node = &dcpext }; +static const struct apple_dcp_hw_data hw; +static struct device dev = { .of_node = &dcpext, .hw = &hw }; static void set(u32 *v, u32 a, u32 b, u32 c) { v[0] = a; v[1] = b; v[2] = c; } @@ -509,7 +504,7 @@ def t8122_dcpext_v27_admission(root): static void expect(bool v27_2, enum dcp_firmware_version want) { assert(apple_t8122_dcpext_v27_2(&dcpext) == v27_2); - assert(t8122_dcpext_arm(&dev) == want); + assert(dcp_check_firmware_version(&dev) == want); assert(!of_node_refs); } @@ -546,14 +541,16 @@ def t8122_dcpext_v27_admission(root): expect(false, DCP_FIRMWARE_UNKNOWN); reset(); dcpext.fw_cells = 0; expect(false, DCP_FIRMWARE_UNKNOWN); reset(); dcpext.compat_cells = 4; expect(false, DCP_FIRMWARE_UNKNOWN); + /* A 27.x refusal is terminal even if the legacy gate would admit it. */ + reset(); ext26 = true; dcp.uuid_count = 0; expect(false, DCP_FIRMWARE_UNKNOWN); puts("PASS T8122 dcpext 27.2 refuses other or malformed versions"); /* The 14.7 template and the native 26.x path are as before. */ reset(); set(dcpext.fw, 14, 7, 0); set(dcpext.compat, 14, 7, 0); expect(false, DCP_FIRMWARE_V_14_7_TEMPLATE); - reset(); ext26 = true; expect(true, DCP_FIRMWARE_H17P); reset(); set(dcpext.fw, 26, 6, 2); set(dcpext.compat, 26, 6, 2); expect(false, DCP_FIRMWARE_UNKNOWN); + ext26 = true; expect(false, DCP_FIRMWARE_H17P); puts("PASS T8122 dcpext 14.7.0 keeps the template, native 26.x keeps H17P"); return 0; } diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index f62924a6d8443b..7dd5ba9affd9b4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -93,7 +93,7 @@ def main(): ('boot', 'oslog-events', boot.oslog, ((),), ()), ('boot', 'syslog-policy', boot.syslog, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), - ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ('-Wno-unused-function',)), + ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ()), ('boot', 'v27-tag-translation', boot.v27_tag_translation, ((),), ()), ('edid', 'dpavserv-start', edid.startup, ((),), ()), ('edid', 'service-rebind', edid.rebind, ((),), ()), From 36f28ca991c18ead2f999ce3e38696026672da67 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:32:09 -0500 Subject: [PATCH 1282/1514] drm/asahi: g16: use zone telemetry when the apple,pmp node is disabled A GPU node may link to a PMP instance whose DT status is "disabled". That device never probes, so apple_pmp_gpu_get() keeps returning -EPROBE_DEFER and the GPU stays in deferred probe forever, reported as "(reason unknown)". Treat an unavailable apple,pmp node like an absent one and drive the fail-closed thermal-zone backstop instead. When an available PMP node has not probed yet, keep deferring, but record the reason with dev_err_probe() so it shows up in devices_deferred. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g16/glue.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 1ccb41d0fc8039..710a2601ce8945 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -269,18 +269,26 @@ struct asahi_g16_cooling *asahi_g16_cooling_register(struct device *dev) INIT_DELAYED_WORK(&cooling->zone_poll, asahi_g16_zone_poll_fn); cooling->zone_err = -ENODATA; cooling->pmp_node = of_parse_phandle(dev->of_node, "apple,pmp", 0); + /* A disabled PMP node never probes, so it provides no telemetry. */ + if (cooling->pmp_node && !of_device_is_available(cooling->pmp_node)) { + of_node_put(cooling->pmp_node); + cooling->pmp_node = NULL; + } if (cooling->pmp_node) { atomic_set(&cooling->state, 8); cooling->pmp = apple_pmp_gpu_get(dev); if (IS_ERR(cooling->pmp)) { - ret = PTR_ERR(cooling->pmp); + ret = dev_err_probe(dev, PTR_ERR(cooling->pmp), + "PMP telemetry from %pOF unavailable\n", + cooling->pmp_node); goto put_node; } } else { /* - * Without an apple,pmp supplier, thermal-zone telemetry drives - * the fail-closed backstop (starting at maximum cooling) while - * the cooling device remains available to thermal policy. + * Without an available apple,pmp supplier, thermal-zone + * telemetry drives the fail-closed backstop (starting at maximum + * cooling) while the cooling device remains available to thermal + * policy. */ atomic_set(&cooling->state, 0); } From 2fcf03ccec624d85a90aafc03f2714c826ce829c Mon Sep 17 00:00:00 2001 From: Kazuhide Takahashi Date: Wed, 25 Nov 2026 07:48:24 +0000 Subject: [PATCH 1283/1514] Bluetooth: hci_bcm4377: cap the ACL MTU at what the ACL ring takes The host-to-controller ACL ring is set up with a mapped payload of MAX_ACL_PAYLOAD_SIZE (HCI_MAX_ACL_SIZE of data plus the header), and bcm4377_enqueue() refuses anything larger. The core fragments outgoing ACL data to the MTU the controller reports in Read Buffer Size, which the driver doesn't limit. On a 15-inch M4 MacBook Air (J715) the controller reports an ACL MTU of 2586, so every fragment above 1028 bytes is dropped: hci_bcm4377 0000:01:00.1: payload len 1451 is too large for ring 5 (max is 0 or 1032) Bluetooth: hci0: sending frame failed (-22) Small traffic gets through, but anything that sends full-size fragments breaks. Over Bluetooth tethering (BNEP), HTTPS transfers stall and fail, and the ACL link can stall until it is killed. Cap acl_mtu and le_mtu at HCI_MAX_ACL_SIZE in post_init, which runs after the init sequence has read the buffer sizes and before any connection. Sending fragments smaller than the controller allows is always valid. A controller that reports 1024 or less, like the M1's (1021), is unaffected. Signed-off-by: Kazuhide Takahashi --- drivers/bluetooth/hci_bcm4377.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 97fb480ed995cf..9e0a5f1ac1637e 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -1960,12 +1960,40 @@ static int bcm4377_hci_set_bdaddr(struct hci_dev *hdev, const bdaddr_t *bdaddr) return 0; } +/* + * The ACL transfer ring takes at most MAX_ACL_PAYLOAD_SIZE bytes per entry + * (HCI_MAX_ACL_SIZE of data), and bcm4377_enqueue() refuses anything larger. + * The core fragments ACL data to the MTUs the controller reports, so a + * controller that reports more than the ring takes would have every larger + * fragment dropped. Fragment to what the ring takes instead. + */ +static void bcm4377_clamp_acl_mtu(struct hci_dev *hdev) +{ + struct bcm4377_data *bcm4377 = hci_get_drvdata(hdev); + + if (hdev->acl_mtu > HCI_MAX_ACL_SIZE) { + dev_info(&bcm4377->pdev->dev, + "controller ACL MTU %u exceeds the ACL ring's %u, using %u\n", + hdev->acl_mtu, HCI_MAX_ACL_SIZE, HCI_MAX_ACL_SIZE); + hdev->acl_mtu = HCI_MAX_ACL_SIZE; + } + + if (hdev->le_mtu > HCI_MAX_ACL_SIZE) { + dev_info(&bcm4377->pdev->dev, + "controller LE MTU %u exceeds the ACL ring's %u, using %u\n", + hdev->le_mtu, HCI_MAX_ACL_SIZE, HCI_MAX_ACL_SIZE); + hdev->le_mtu = HCI_MAX_ACL_SIZE; + } +} + static int bcm4377_hci_post_init(struct hci_dev *hdev) { struct bcm4377_data *bcm4377 = hci_get_drvdata(hdev); const bdaddr_t *bda = NULL; int ret; + bcm4377_clamp_acl_mtu(hdev); + if (!bcm4377->cal_needed) return 0; From b462beb2bf528d973a2e551e2240e1bb230e8312 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:51:14 -0500 Subject: [PATCH 1284/1514] soc: apple: aop: add T8122 sleep endpoints Stop T8122's twelve AFK endpoints before deep sleep and restart them on resume, both when the bootloader provides firmware memory regions and on the fallback without them. Signed-off-by: Satya Benson --- drivers/soc/apple/aop.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/aop.rs b/drivers/soc/apple/aop.rs index 89849f775d5c74..615e965e4d9f8f 100644 --- a/drivers/soc/apple/aop.rs +++ b/drivers/soc/apple/aop.rs @@ -3196,12 +3196,19 @@ const HW_CFG_T6041: AopHwConfig = AopHwConfig { /// the DART's DAPF programmed and its windows reserved alongside the firmware /// segments. const HW_CFG_T8132: AopHwConfig = HW_CFG_T6040; +/// T8122 fallback when the bootloader supplies no firmware `memory-region`: +/// keeps the T6020 boot path while still stopping the T8122 sleep endpoints. +const HW_CFG_T8122_NO_FW_REGIONS: AopHwConfig = AopHwConfig { + sleep_endpoints: &[0x2b, 0x2a, 0x25, 0x27, 0x20, 0x23, 0x29, 0x24, 0x21, 0x28, 0x26, 0x22], + ..HW_CFG_T6020 +}; /// T8122 (M3): as T6040. iBoot leaves the AOP halted with its external code, /// data and log in DRAM, which the bootloader reserves in `memory-region`; /// the 27.2 firmware reads its `__EDATA` base from `ED0p`. A bootloader that /// reserves none leaves it to start as `apple,t6020-aop`, as before. const HW_CFG_T8122: AopHwConfig = AopHwConfig { - without_fw_regions: Some(&HW_CFG_T6020), + sleep_endpoints: &[0x2b, 0x2a, 0x25, 0x27, 0x20, 0x23, 0x29, 0x24, 0x21, 0x28, 0x26, 0x22], + without_fw_regions: Some(&HW_CFG_T8122_NO_FW_REGIONS), ..HW_CFG_T6040 }; /// T8140: the firmware is started with the boot arguments the bootloader From 2b5a5aedd258dea705bbe68c5d4ec5927586f28f Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:51:14 -0500 Subject: [PATCH 1285/1514] soc: apple: pmp: add T8122 SRAM backup config Match "apple,t8122-pmp-v2" with T8122's SRAM __DATA backup window (offset 0x36000, size 0x47000), allowing a device-tree apple,sram-keep property to override it when supplied by the bootloader. Signed-off-by: Satya Benson --- drivers/soc/apple/pmp.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/drivers/soc/apple/pmp.rs b/drivers/soc/apple/pmp.rs index c8b9219e51c019..9bff46da17cd21 100644 --- a/drivers/soc/apple/pmp.rs +++ b/drivers/soc/apple/pmp.rs @@ -1020,6 +1020,14 @@ const HW_CFG_T6050: PmpHwConfig = PmpHwConfig { confirm_ioreg_len: false, }; +/// T8122: the sleep engine reloads `__TEXT` from DRAM at the wake, and only `__DATA` +/// (the ADT's second segment, offset 0x36000, size 0x47000) has to be kept. When the +/// boot loader supplies `apple,sram-keep`, both offset and size come from the DT instead. +const HW_CFG_T8122: PmpHwConfig = PmpHwConfig { + sram_backup: Some((0x36000, 0x47000)), + ..HW_CFG_DEFAULT +}; + /// T8132: over a sleep only the ADT's second segment (0x68000 bytes, starting at 0x3c000 on /// 26.6.2/25G83 and 0x3d000 on 27.2/26B123 per ADT `segment-ranges` and SRAM header word 0x234) /// needs to be kept. When the boot loader supplies `apple,sram-keep`, both offset and size come @@ -1045,6 +1053,7 @@ kernel::of_device_table!( OF_TABLE, ::IdInfo, [ + (of::DeviceId::new(c"apple,t8122-pmp-v2"), &HW_CFG_T8122), (of::DeviceId::new(c"apple,t8132-pmp-v2"), &HW_CFG_T8132), (of::DeviceId::new(c"apple,t8140-pmp-v2"), &HW_CFG_T8140), (of::DeviceId::new(c"apple,t8142-pmp-v2"), &HW_CFG_T8142), From e5d8dc3958c9860f538468eb3f3f24c17e67fcde Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:51:14 -0500 Subject: [PATCH 1286/1514] soc: apple: mcc: support T8122 two-cluster SLC write-back for deep sleep Match "apple,t8122-mcc" with the retained two-plane path so T8122 disables SLC allocation on suspend and restores it after deep sleep wake. Signed-off-by: Satya Benson --- drivers/soc/apple/mcc.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/drivers/soc/apple/mcc.c b/drivers/soc/apple/mcc.c index 8bcdfc740eeaac..d962b9f0de3285 100644 --- a/drivers/soc/apple/mcc.c +++ b/drivers/soc/apple/mcc.c @@ -377,7 +377,8 @@ static int apple_mcc_probe(struct platform_device *pdev) INIT_LIST_HEAD(&mcc->boot_dma.link); mcc->boot_dma.dev = dev; mcc->boot_dma.lost = apple_mcc_boot_dma_lost; - mcc->retained = of_device_is_compatible(dev->of_node, "apple,t8132-mcc"); + mcc->retained = of_device_is_compatible(dev->of_node, "apple,t8122-mcc") || + of_device_is_compatible(dev->of_node, "apple,t8132-mcc"); mcc->ways_off = of_device_is_compatible(dev->of_node, "apple,t8142-mcc"); while (platform_get_resource(pdev, IORESOURCE_MEM, mcc->nr_planes)) { struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, mcc->nr_planes); @@ -538,6 +539,7 @@ static const struct dev_pm_ops apple_mcc_pm_ops = { }; static const struct of_device_id apple_mcc_of_match[] = { + { .compatible = "apple,t8122-mcc" }, { .compatible = "apple,t8132-mcc" }, { .compatible = "apple,t8140-mcc" }, { .compatible = "apple,t8142-mcc" }, From 8677cbde1ddcc1efb3777bebbbfbf055767113e6 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:12:18 -0500 Subject: [PATCH 1287/1514] drm/asahi: g17: avoid publication contagion and host drains on timestamp overlap Commit 086a909dc8c6 ("drm/asahi: overlap cross-engine commands with timestamped producers on G17") exposed ordered host publications on every overlapping timestamp-free command and forced timestamp-writing renders and NO_QUERY_ACCESS computes to wait on the host for any covered publication. Two effects serialized pipelined workloads that emit per-frame timestamps: 1. A timestamp-free Publication never cleared its pending state after all predecessors published cleanly, so every later command in the frame chained behind it and kept fences.publication populated even long after the original timestamped command completed. Any subsequent query-accessing compute or timestamp-writing render then added host completion waits on the entire frontier and drained both engines to zero in flight. 2. Timestamp-writing renders and NO_QUERY_ACCESS computes perform all host-ordered timestamp writes inside Publication::publish() once a chained render's firmware fragment-end timestamp window is disabled, so stalling them on the host behind covered publications was unnecessary. Fix both while preserving ordered timestamp publication and deferred producer error propagation: - Track has_outputs and an atomic pending flag on Publication. When a timestamp-free Publication's predecessors all publish Ok(()), clear pending and immediately release any downstream Publication successors without waiting for its own GPU retirement. Publications that fail before settling (or carry outputs) keep pending set so deferred errors continue to propagate; a settled timestamp-free publication whose own GPU work fails later relies on retirement-time producer checks and VM failure state, matching commands without a publication. - Add Destinations::disable_window() and disable the firmware fragment-end timestamp window on any render chained behind pending host predecessors, so its timestamps are written strictly on the host in publication order. - Restrict host completion waits in EnqueueOrdering::build() to query-accessing compute commands, while still adding already-signalled error fences (status < 0) on both same-engine paths when a covered entry failed between frontier pruning and ordering. Renders and NO_QUERY_ACCESS computes overlap pending publications in firmware and chain ordered publication. - Check Publication::is_pending() in has_pending_publication() and input_sources() so settled timestamp-free commands do not block cross-queue firmware barriers. - Extend asahi_g17_timestamp_window, asahi_g17_publication_order, and asahi_g17_cross_engine_timestamps KUnit tests to cover window disabling, clean upstream settlement, settled-then-failed propagation, chained timestamped overlap in both directions, and query-access host waits. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/completion.rs | 45 ++- .../drm/asahi/g17/completion/publication.rs | 158 ++++++++- drivers/gpu/drm/asahi/g17/queue/mod.rs | 315 +++++++++++++----- 3 files changed, 412 insertions(+), 106 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index ce2b4595c39615..794095f26f3ac1 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -128,9 +128,12 @@ const fn window_slot(index: usize) -> bool { /// one releases only a buffer reference; the buffer defers its own mapping release. pub(crate) struct Destinations { stamps: [Option; 4], - /// A render: the firmware gets its fragment end destination through the window. A compute - /// command's only stamp pair stays kernel-private (recovery trusts it). - render: bool, + /// A render whose fragment end destination may be written directly by + /// firmware through the timestamp window. Cleared when ordered behind + /// pending host timestamp predecessors so firmware cannot race with their + /// deferred host writes or bypass an inherited error. A compute command's + /// only stamp pair stays kernel-private (recovery trusts it). + allow_window: bool, /// The firmware was handed window destinations ([`Self::window_vas`]). handed: AtomicBool, } @@ -150,15 +153,19 @@ impl Destinations { } Ok(Self { stamps: destinations, - render: timestamps.len() == 2, + allow_window: timestamps.len() == 2, handed: AtomicBool::new(false), }) } + pub(crate) fn disable_window(&mut self) { + self.allow_window = false; + } + /// Window addresses for a render's vertex and fragment start/end destinations: the fragment /// end's if it is mapped in the window, 0 for the others. fn window_vas(&self) -> [u64; 4] { - if !self.render || WINDOW_MISSES.load(Ordering::Relaxed) >= WINDOW_GIVE_UP { + if !self.allow_window || WINDOW_MISSES.load(Ordering::Relaxed) >= WINDOW_GIVE_UP { return [0; 4]; } let vas: [u64; 4] = core::array::from_fn(|i| { @@ -179,11 +186,16 @@ impl Destinations { pub(super) fn empty() -> Self { Self { stamps: core::array::from_fn(|_| None), - render: false, + allow_window: false, handed: AtomicBool::new(false), } } + #[cfg(CONFIG_KUNIT = "y")] + pub(super) fn allows_window(&self) -> bool { + self.allow_window + } + fn iter(&self) -> core::slice::Iter<'_, Option> { self.stamps.iter() } @@ -243,7 +255,7 @@ impl HostOutput { ) -> Result { if host_predecessors || has_outputs { Ok(Self(HostOutputKind::Ordered(Publication::new( - output, status, + output, status, has_outputs, )?))) } else { Ok(Self(HostOutputKind::Immediate(output))) @@ -476,7 +488,7 @@ impl Completion { context: &Arc, member: Member, vm_job: mmu::VmJobGuard, - destinations: Destinations, + mut destinations: Destinations, compute: bool, host_predecessors: bool, feed: Option>, @@ -485,6 +497,9 @@ impl Completion { ) -> Result> { let fence = fence::independent(contexts)?; let has_outputs = destinations.has_outputs(); + if host_predecessors { + destinations.disable_window(); + } let terminal = if host_predecessors { Some(fence::independent(contexts)?) } else { @@ -1046,4 +1061,18 @@ mod window_tests { assert_eq!(ticks_to_ns(24), 1_000); assert_eq!(ticks_to_ns(24_000_025), 1_000_001_041); } + + #[test] + fn disable_window_clears_allow_window_and_leaves_handed_false() { + let mut dest = Destinations { + stamps: core::array::from_fn(|_| None), + allow_window: true, + handed: AtomicBool::new(false), + }; + assert!(dest.allows_window()); + dest.disable_window(); + assert!(!dest.allows_window()); + assert_eq!(dest.window_vas(), [0; 4]); + assert!(!dest.handed.load(Ordering::Acquire)); + } } diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 161a051dc9540a..e91cd7203b8035 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -9,6 +9,7 @@ use super::Output; use crate::g17::{dependency::PRODUCER_FAILED, status::VmStatus}; +use core::sync::atomic::{AtomicBool, Ordering}; use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; type Links = Option>; @@ -28,6 +29,9 @@ struct State { predecessor_error: Option, claimed: bool, published: Option, + // All predecessors published cleanly while this timestamp-free publication + // still has no result of its own; successors have already been released. + upstream_released: bool, successors: Links, } @@ -49,16 +53,27 @@ impl State { pub(crate) struct Publication { output: Output, status: Arc, + has_outputs: bool, + // True while this publication may still write host timestamps or deliver a + // deferred predecessor error. Cleared only once no host write or error + // remains, and never set again. + pending: AtomicBool, #[pin] state: Mutex, } impl Publication { - pub(super) fn new(output: Output, status: Arc) -> Result> { + pub(super) fn new( + output: Output, + status: Arc, + has_outputs: bool, + ) -> Result> { Arc::pin_init( pin_init!(Self { output, status, + has_outputs, + pending: AtomicBool::new(true), state <- new_mutex!(State { // Acceptance installs all links before releasing this sentinel. remaining: 1, @@ -66,6 +81,7 @@ impl Publication { predecessor_error: None, claimed: false, published: None, + upstream_released: false, successors: None, }, "G17 host timestamp publication"), }), @@ -77,6 +93,12 @@ impl Publication { &self.output } + /// Whether this publication still has an unpublished host timestamp write + /// or an unresolved or failed predecessor chain. + pub(crate) fn is_pending(&self) -> bool { + self.pending.load(Ordering::Acquire) + } + /// One terminal result, offered separately from its physical-retirement proof. pub(crate) fn finish(&self, result: Result<[u64; 4]>) { let ready = { @@ -107,6 +129,9 @@ impl Publication { // A late link is acknowledged only after timestamp writes, the public // fence and aggregate membership have all been published off this lock. state.published = Some(result); + if result.is_ok() { + self.pending.store(false, Ordering::Release); + } state.successors.take() }; let mut next = links.as_mut(); @@ -118,31 +143,56 @@ impl Publication { } fn predecessor_done(&self, result: Result) -> Links { - let ready = { + let (ready, settled) = { let mut state = self.state.lock(); debug_assert!(state.remaining != 0); if result.is_err() && state.predecessor_error.is_none() { state.predecessor_error = Some(PRODUCER_FAILED); } state.remaining -= 1; - state.claim() + if let Some(ready) = state.claim() { + (Some(ready), None) + } else if state.remaining == 0 + && !self.has_outputs + && state.predecessor_error.is_none() + && !state.upstream_released + { + // Every predecessor published cleanly and this command writes + // no host timestamps, so downstream commands need not wait on + // or chain behind its GPU execution. + state.upstream_released = true; + self.pending.store(false, Ordering::Release); + (None, state.successors.take()) + } else { + (None, None) + } }; - ready.and_then(|result| self.publish(result)) + if let Some(result) = ready { + return self.publish(result); + } + let mut links = settled; + let mut next = links.as_mut(); + while let Some(link) = next { + link.result = Ok(()); + next = link.next.as_mut(); + } + links } fn add_successor(&self, mut link: KBox) { - let published = { + let immediate = { let mut state = self.state.lock(); - match state.published { - Some(result) => result, - None => { - link.next = state.successors.take(); - state.successors = Some(link); - return; - } + if let Some(result) = state.published { + result + } else if state.upstream_released { + Ok(()) + } else { + link.next = state.successors.take(); + state.successors = Some(link); + return; } }; - Self::drain(link.target.predecessor_done(published)); + Self::drain(link.target.predecessor_done(immediate)); } /// Iterative depth-first notification, O(nodes + links), with no stack growth. @@ -213,6 +263,7 @@ impl Publication { pub(crate) fn test_pair( contexts: &kernel::dma_fence::FenceContexts, status: &Arc, + has_outputs: bool, ) -> Result<(Arc, kernel::dma_fence::Fence)> { let fence = crate::g17::fence::independent(contexts)?; let handle = kernel::dma_fence::Fence::from_fence(&fence); @@ -221,7 +272,7 @@ impl Publication { member: crate::g17::fence::Aggregate::test_member(contexts)?, destinations: super::Destinations::empty(), }; - Ok((Self::new(output, status.clone())?, handle)) + Ok((Self::new(output, status.clone(), has_outputs)?, handle)) } } @@ -240,6 +291,7 @@ mod tests { fn make_pub( contexts: &FenceContexts, status: &Arc, + has_outputs: bool, ) -> (Arc, Fence) { let fence = independent(contexts).unwrap(); let handle = Fence::from_fence(&fence); @@ -248,16 +300,16 @@ mod tests { member: Aggregate::test_member(contexts).unwrap(), destinations: Destinations::empty(), }; - (Publication::new(output, status.clone()).unwrap(), handle) + (Publication::new(output, status.clone(), has_outputs).unwrap(), handle) } #[test] fn consumer_retiring_before_delayed_producer_failure_inherits_error() { let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap(); let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); - let (producer, prod_fence) = make_pub(&contexts, &status); - let (consumer, cons_fence) = make_pub(&contexts, &status); - let (downstream, down_fence) = make_pub(&contexts, &status); + let (producer, prod_fence) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (downstream, down_fence) = make_pub(&contexts, &status, false); Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); @@ -275,5 +327,75 @@ mod tests { assert_eq!(fence_status(&prod_fence), EIO.to_errno()); assert_eq!(fence_status(&cons_fence), PRODUCER_FAILED.to_errno()); assert_eq!(fence_status(&down_fence), PRODUCER_FAILED.to_errno()); + assert!(producer.is_pending()); + assert!(consumer.is_pending()); + assert!(downstream.is_pending()); + } + + #[test] + fn clean_producer_settles_timestamp_free_chain_while_in_flight() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_settle"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, prod_fence) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (downstream, down_fence) = make_pub(&contexts, &status, false); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(downstream.clone(), core::iter::once(&consumer)).unwrap().activate(); + + assert!(producer.is_pending()); + assert!(consumer.is_pending()); + assert!(downstream.is_pending()); + + // Producer completes cleanly while consumer and downstream are still + // executing on the GPU: both timestamp-free publications settle at once + // without signalling their own completion fences early. + producer.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&prod_fence) > 0); + assert!(!producer.is_pending()); + assert!(!consumer.is_pending()); + assert!(!downstream.is_pending()); + assert_eq!(fence_status(&cons_fence), 0); + assert_eq!(fence_status(&down_fence), 0); + + // Downstream finishing before consumer still publishes immediately. + downstream.finish(Ok([5, 6, 0, 0])); + assert!(fence_status(&down_fence) > 0); + assert_eq!(fence_status(&cons_fence), 0); + + consumer.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&cons_fence) > 0); + } + + #[test] + fn settled_publication_failing_later_delivers_error_to_late_successor() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_settle_err"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, _) = make_pub(&contexts, &status, true); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let (early, early_fence) = make_pub(&contexts, &status, false); + + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap().activate(); + Prepared::new(early.clone(), core::iter::once(&consumer)).unwrap().activate(); + + producer.finish(Ok([1, 2, 0, 0])); + assert!(!consumer.is_pending()); + assert!(!early.is_pending()); + + // Consumer's own GPU execution later fails: early successor was already + // released at settlement, while a late successor added after publish + // observes consumer's error. + consumer.finish(Err(EIO)); + assert_eq!(fence_status(&cons_fence), EIO.to_errno()); + + early.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&early_fence) > 0); + + let (late, late_fence) = make_pub(&contexts, &status, false); + Prepared::new(late.clone(), core::iter::once(&consumer)).unwrap().activate(); + late.finish(Ok([5, 6, 0, 0])); + assert_eq!(fence_status(&late_fence), PRODUCER_FAILED.to_errno()); } } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 1c64f3839ae22d..9079ed471ed6da 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -203,7 +203,7 @@ impl Queue { self.frontiers.iter().enumerate().any(|(index, frontier)| { frontier.iter().any(|(sequence, fences)| { Order::contains(order.wait_through[index], *sequence) - && fences.publication.is_some() + && fences.publication.as_ref().is_some_and(|p| p.is_pending()) && fences.status() <= 0 }) }) @@ -265,7 +265,8 @@ impl Queue { }) && self.frontiers[1].iter().all(|(sequence, fences)| { !Order::contains(order.wait_through[1], *sequence) - || (fences.ready.raw() != fences.completed.raw() && fences.publication.is_none()) + || (fences.ready.raw() != fences.completed.raw() + && !fences.publication.as_ref().is_some_and(|p| p.is_pending())) || fences.status() > 0 }) && self.failures.iter_mut().enumerate().all(|(index, failure)| { @@ -294,7 +295,6 @@ impl Queue { order, engine, host_waits, - has_outputs, query_access, )?; let completion = Completion::new( @@ -635,52 +635,51 @@ impl Drop for Queue { /// Whether a cross-engine consumer must wait on the host for a covered /// producer's completion fence before scheduling. +/// +/// Only query-accessing compute commands can read or reset timestamp words on +/// the GPU. Timestamp-writing renders (whose firmware timestamp window is +/// disabled whenever chained behind predecessors) and `NO_QUERY_ACCESS` compute +/// commands write all timestamps on the host inside ordered +/// [`Publication::publish`], so they overlap in firmware and chain publication +/// instead of draining the GPU. const fn cross_engine_wait_completed( host_waits: bool, - has_outputs: bool, engine: Engine, query_access: bool, - has_publication: bool, + has_pending_publication: bool, ) -> bool { if host_waits { return true; } - if !has_publication { - return false; - } - has_outputs || (matches!(engine, Engine::Compute) && query_access) + has_pending_publication && matches!(engine, Engine::Compute) && query_access } /// Whether a cross-engine consumer overlaps execution with a producer that has -/// ordered host publication and therefore chains its completion behind it. +/// pending ordered host publication and therefore chains its completion behind it. const fn cross_engine_chain_publication( host_waits: bool, - has_outputs: bool, engine: Engine, query_access: bool, ) -> bool { - !host_waits && !has_outputs && !(matches!(engine, Engine::Compute) && query_access) + !host_waits && !(matches!(engine, Engine::Compute) && query_access) } /// Whether a same-engine consumer must wait on the host for covered same-engine -/// predecessors that have ordered host publication: query-accessing compute may -/// read or write, on the GPU, query words whose host publication is still -/// pending, and timestamp-writing renders can write their fragment-end -/// timestamp window on the GPU before a transitive cross-engine producer -/// finishes its deferred host write or error publication. -const fn same_engine_wait_completed( - engine: Engine, - has_outputs: bool, - query_access: bool, -) -> bool { - (matches!(engine, Engine::Compute) && query_access) - || (matches!(engine, Engine::Render) && has_outputs) +/// predecessors with pending ordered host publication: query-accessing compute +/// may read or reset query words on the GPU whose host publication is still +/// pending. Timestamp-writing renders disable their firmware timestamp window +/// when chained behind predecessors and write on the host in publication order. +const fn same_engine_wait_completed(engine: Engine, query_access: bool) -> bool { + matches!(engine, Engine::Compute) && query_access } trait FrontierEntry { fn status(&self) -> i32; fn ready_is_completed(&self) -> bool; fn publication(&self) -> Option<&Arc>; + fn pending_publication(&self) -> Option<&Arc> { + self.publication().filter(|publication| publication.is_pending()) + } fn completed(&self) -> &Fence; fn scheduled(&self) -> &Fence; } @@ -720,7 +719,6 @@ impl<'a> EnqueueOrdering<'a> { order: Order, engine: Engine, host_waits: bool, - has_outputs: bool, query_access: bool, ) -> Result { let index = engine.index(); @@ -744,22 +742,28 @@ impl<'a> EnqueueOrdering<'a> { &[] }; - let same_wait = same_engine_wait_completed(engine, has_outputs, query_access); + let same_wait = same_engine_wait_completed(engine, query_access); let same_chain = !same_wait; - let cross_chain = - cross_engine_chain_publication(host_waits, has_outputs, engine, query_access); - - // Retain covered failed publications (`status() <= 0`, not only `== 0`) - // that survived `prune_frontier()`: if a predecessor's deferred error - // published between pruning and link selection, `add_successor()` still - // delivers that failure immediately instead of letting the successor - // signal success. + let cross_chain = cross_engine_chain_publication(host_waits, engine, query_access); + + // Retain covered pending or failed publications (`status() <= 0`, not + // only `== 0`) that survived `prune_frontier()`: if a predecessor's + // deferred error published between pruning and link selection, + // `add_successor()` still delivers that failure immediately instead of + // letting the successor signal success. let mut predecessors = KVec::new(); + let mut host = KVec::new(); + let mut firmware = KVec::new(); if same_chain { for (_, entry) in same_covered { - if entry.status() <= 0 { - if let Some(publication) = entry.publication() { + let status = entry.status(); + if status <= 0 { + if let Some(publication) = entry.pending_publication() { predecessors.push(publication, GFP_KERNEL)?; + } else if status < 0 { + // Failed after `prune_frontier()` without an active + // publication: keep its already-signalled error fence. + host.push(entry.completed().clone(), GFP_KERNEL)?; } } } @@ -767,19 +771,19 @@ impl<'a> EnqueueOrdering<'a> { if cross_chain { for (_, entry) in other_covered { if entry.status() <= 0 { - if let Some(publication) = entry.publication() { + if let Some(publication) = entry.pending_publication() { predecessors.push(publication, GFP_KERNEL)?; } } } } - let mut host = KVec::new(); - let mut firmware = KVec::new(); if same_wait { for (_, entry) in same_covered { - if entry.status() <= 0 - && (entry.ready_is_completed() || entry.publication().is_some()) + let status = entry.status(); + if status < 0 + || (status == 0 + && (entry.ready_is_completed() || entry.pending_publication().is_some())) { host.push(entry.completed().clone(), GFP_KERNEL)?; } @@ -795,10 +799,9 @@ impl<'a> EnqueueOrdering<'a> { } if cross_engine_wait_completed( host_waits, - has_outputs, engine, query_access, - entry.publication().is_some(), + entry.pending_publication().is_some(), ) { host.push(entry.completed().clone(), GFP_KERNEL)?; } else { @@ -856,12 +859,13 @@ mod tests { fn test_entry( contexts: &FenceContexts, status: &Arc, - with_pub: bool, + pub_outputs: Option, ) -> (TestEntry, Option>) { let ready = Fence::from_fence(&independent(contexts).unwrap()); let scheduled = Fence::from_fence(&independent(contexts).unwrap()); - if with_pub { - let (publication, completed) = Publication::test_pair(contexts, status).unwrap(); + if let Some(has_outputs) = pub_outputs { + let (publication, completed) = + Publication::test_pair(contexts, status, has_outputs).unwrap(); ( TestEntry { ready, @@ -886,12 +890,12 @@ mod tests { } #[test] - fn transitive_render_window_waits_for_intermediate_completion() { + fn transitive_render_chains_publication_without_host_wait() { let contexts = FenceContexts::new(1, c_str!("asahi_q_ts_test"), TEST_KEY).unwrap(); let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); - // Compute A writes a timestamp (has ordered host publication). - let (comp_a, pub_a) = test_entry(&contexts, &status, true); + // Compute A writes a timestamp (has pending ordered host publication). + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); let pub_a = pub_a.unwrap(); PreparedPublication::new(pub_a.clone(), core::iter::empty()) .unwrap() @@ -911,7 +915,6 @@ mod tests { order_b, Engine::Render, false, - false, true, ) .unwrap(); @@ -919,17 +922,17 @@ mod tests { assert_eq!(plan_b.firmware_waits.len(), 1); assert_eq!(plan_b.predecessors.len(), 1); - let (rend_b, pub_b) = test_entry(&contexts, &status, true); + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); let pub_b = pub_b.unwrap(); - let rend_b_completed = rend_b.completed.raw(); PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter().copied()) .unwrap() .activate(); let render_frontier = [(1u64, rend_b)]; - // Render C writes a timestamp (may use fragment-end window) and covers - // only Render B: must host-wait on B's completion fence so C cannot - // write the slot or bypass A's error before A publishes through B. + // Render C writes a timestamp and covers only Render B: chains its + // publication behind B (disabling its firmware window in Completion::new) + // instead of stalling on the host, so C still cannot publish or write + // timestamps before A publishes through B. let order_c = Order { sequence: 2, wait_through: [Some(1), None], @@ -942,16 +945,23 @@ mod tests { Engine::Render, false, true, - true, ) .unwrap(); - assert_eq!(plan_c.host_waits.len(), 1); - assert_eq!(plan_c.host_waits[0].raw(), rend_b_completed); + assert!(plan_c.host_waits.is_empty()); assert!(plan_c.firmware_waits.is_empty()); - assert!(plan_c.predecessors.is_empty()); + assert_eq!(plan_c.predecessors.len(), 1); + + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, true).unwrap(); + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + .unwrap() + .activate(); - pub_a.finish(Ok([1, 2, 0, 0])); pub_b.finish(Ok([3, 4, 0, 0])); + pub_c.finish(Ok([5, 6, 0, 0])); + assert_eq!(fence_status(&fence_c), 0); + + pub_a.finish(Err(EIO)); + assert!(fence_status(&fence_c) < 0); } #[test] @@ -959,13 +969,13 @@ mod tests { let contexts = FenceContexts::new(1, c_str!("asahi_q_fail_test"), TEST_KEY).unwrap(); let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); - let (comp_a, pub_a) = test_entry(&contexts, &status, true); + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); let pub_a = pub_a.unwrap(); PreparedPublication::new(pub_a.clone(), core::iter::empty()) .unwrap() .activate(); - let (rend_b, pub_b) = test_entry(&contexts, &status, true); + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); let pub_b = pub_b.unwrap(); PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) .unwrap() @@ -994,13 +1004,12 @@ mod tests { order_c, Engine::Render, false, - false, true, ) .unwrap(); assert_eq!(plan_c.predecessors.len(), 1); - let (pub_c, fence_c) = Publication::test_pair(&contexts, &status).unwrap(); + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, false).unwrap(); PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) .unwrap() .activate(); @@ -1009,19 +1018,21 @@ mod tests { } #[test] - fn shared_timestamp_slot_keeps_host_wait_in_both_directions() { + fn query_access_waits_while_timestamped_overlap_chains_in_both_directions() { let contexts = FenceContexts::new(1, c_str!("asahi_q_dir_test"), TEST_KEY).unwrap(); let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); - let (rend_a, pub_ra) = test_entry(&contexts, &status, true); + let (rend_a, pub_ra) = test_entry(&contexts, &status, Some(true)); let pub_ra = pub_ra.unwrap(); PreparedPublication::new(pub_ra.clone(), core::iter::empty()) .unwrap() .activate(); + let rend_a_scheduled = rend_a.scheduled.raw(); let rend_a_completed = rend_a.completed.raw(); let render_frontier = [(1u64, rend_a)]; - // Render(ts) -> NO_QUERY_ACCESS Compute writing timestamps. + // Render(ts) -> NO_QUERY_ACCESS Compute: overlaps in firmware and chains + // ordered host publication instead of stalling on the host. let plan_rc = EnqueueOrdering::build( &[] as &[(u64, TestEntry)], &render_frontier, @@ -1032,23 +1043,43 @@ mod tests { }, Engine::Compute, false, - true, false, ) .unwrap(); - assert_eq!(plan_rc.host_waits.len(), 1); - assert_eq!(plan_rc.host_waits[0].raw(), rend_a_completed); - assert!(plan_rc.firmware_waits.is_empty()); + assert!(plan_rc.host_waits.is_empty()); + assert_eq!(plan_rc.firmware_waits.len(), 1); + assert_eq!(plan_rc.firmware_waits[0].0.raw(), rend_a_scheduled); + assert_eq!(plan_rc.firmware_waits[0].1.raw(), rend_a_completed); + assert_eq!(plan_rc.predecessors.len(), 1); + + // Render(ts) -> query-accessing Compute: must host-wait until A publishes. + let plan_rc_query = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &render_frontier, + Order { + sequence: 1, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert_eq!(plan_rc_query.host_waits.len(), 1); + assert_eq!(plan_rc_query.host_waits[0].raw(), rend_a_completed); + assert!(plan_rc_query.firmware_waits.is_empty()); - let (comp_a, pub_ca) = test_entry(&contexts, &status, true); + let (comp_a, pub_ca) = test_entry(&contexts, &status, Some(true)); let pub_ca = pub_ca.unwrap(); PreparedPublication::new(pub_ca.clone(), core::iter::empty()) .unwrap() .activate(); + let comp_a_scheduled = comp_a.scheduled.raw(); let comp_a_completed = comp_a.completed.raw(); let compute_frontier = [(1u64, comp_a)]; - // Compute(ts) -> Render writing timestamps (including fragment-end window). + // Compute(ts) -> Render: overlaps in firmware and chains publication. let plan_cr = EnqueueOrdering::build( &[] as &[(u64, TestEntry)], &compute_frontier, @@ -1060,17 +1091,143 @@ mod tests { Engine::Render, false, true, - true, ) .unwrap(); - assert_eq!(plan_cr.host_waits.len(), 1); - assert_eq!(plan_cr.host_waits[0].raw(), comp_a_completed); - assert!(plan_cr.firmware_waits.is_empty()); + assert!(plan_cr.host_waits.is_empty()); + assert_eq!(plan_cr.firmware_waits.len(), 1); + assert_eq!(plan_cr.firmware_waits[0].0.raw(), comp_a_scheduled); + assert_eq!(plan_cr.firmware_waits[0].1.raw(), comp_a_completed); + assert_eq!(plan_cr.predecessors.len(), 1); pub_ra.finish(Ok([1, 2, 0, 0])); pub_ca.finish(Ok([3, 4, 0, 0])); } + #[test] + fn settled_timestamp_free_publication_drops_contagion_and_host_waits() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_settle"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (comp_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // While Render A is still pending, query-accessing Compute C must host-wait on B. + let comp_b_completed = comp_b.completed.raw(); + let compute_frontier = [(1u64, comp_b)]; + let plan_before = EnqueueOrdering::build( + &compute_frontier, + &[] as &[(u64, TestEntry)], + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert_eq!(plan_before.host_waits.len(), 1); + assert_eq!(plan_before.host_waits[0].raw(), comp_b_completed); + + // Once Render A finishes cleanly, Compute B settles while still in flight: + // neither a query-accessing Compute nor a cross-engine Render waits or + // chains behind B. + pub_a.finish(Ok([1, 2, 0, 0])); + assert_eq!(rend_a.status(), 1); + assert_eq!(compute_frontier[0].1.status(), 0); + assert!(!pub_b.is_pending()); + + let plan_query = EnqueueOrdering::build( + &compute_frontier, + &[] as &[(u64, TestEntry)], + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Compute, + false, + true, + ) + .unwrap(); + assert!(plan_query.host_waits.is_empty()); + assert!(plan_query.predecessors.is_empty()); + + let plan_render = EnqueueOrdering::build( + &[] as &[(u64, TestEntry)], + &compute_frontier, + Order { + sequence: 2, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_render.host_waits.is_empty()); + assert_eq!(plan_render.firmware_waits.len(), 1); + assert!(plan_render.predecessors.is_empty()); + + pub_b.finish(Ok([3, 4, 0, 0])); + } + + #[test] + fn failed_settled_same_engine_entry_adds_host_wait() { + let contexts = FenceContexts::new(1, c_str!("asahi_q_settled_err"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + + let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + let rend_b_completed = rend_b.completed.raw(); + PreparedPublication::new(pub_b.clone(), core::iter::once(&pub_a)) + .unwrap() + .activate(); + + // Render A completes cleanly, settling Render B; then Render B fails in + // hardware after frontier pruning. + pub_a.finish(Ok([1, 2, 0, 0])); + assert!(!pub_b.is_pending()); + pub_b.finish(Err(EIO)); + assert!(rend_b.status() < 0); + assert_eq!(rend_a.status(), 1); + + let render_frontier = [(1u64, rend_b)]; + let plan_c = EnqueueOrdering::build( + &render_frontier, + &[] as &[(u64, TestEntry)], + Order { + sequence: 2, + wait_through: [Some(1), None], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_c.predecessors.is_empty()); + assert_eq!(plan_c.host_waits.len(), 1); + assert_eq!(plan_c.host_waits[0].raw(), rend_b_completed); + } + #[test] fn compute_with_outputs_and_no_predecessors_publishes_on_finish() { let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_pub"), TEST_KEY).unwrap(); @@ -1086,7 +1243,6 @@ mod tests { }, Engine::Compute, false, - true, false, ) .unwrap(); @@ -1122,7 +1278,7 @@ mod tests { let contexts = FenceContexts::new(1, c_str!("asahi_q_comp_chain"), TEST_KEY).unwrap(); let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); - let (rend_a, pub_a) = test_entry(&contexts, &status, true); + let (rend_a, pub_a) = test_entry(&contexts, &status, Some(true)); let pub_a = pub_a.unwrap(); PreparedPublication::new(pub_a.clone(), core::iter::empty()) .unwrap() @@ -1144,7 +1300,6 @@ mod tests { Engine::Compute, false, false, - false, ) .unwrap(); assert!(plan_b.host_waits.is_empty()); From eca0efdd874860b0b1c4a97d06671ba5b704a023 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:54:18 -0500 Subject: [PATCH 1288/1514] nvme: apple: support T8122 ANS warm sleep and restart Add an apple_nvme_t8122_hw profile matched on "apple,t8122-nvme-ans2" with warm_sleep enabled. On firmware-driven suspend-to-RAM, warm-idle ANS via apple_rtkit_idle() and clear CPU_CONTROL instead of tearing down RTKit. On resume, restore GPIO pins, replay SART entries, and warm-restart ANS via apple_rtkit_sleep_return_start() before disabling any retained controller state and rebuilding the NVMe queues. Also replay SART after a pre-M4 PMGR reset deassert where ANS and SART share a reset line. Signed-off-by: Satya Benson --- drivers/nvme/host/apple.c | 89 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 3 deletions(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index b33e64ae38bd87..1320be0b1f8149 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -236,6 +236,8 @@ struct apple_nvme_hw { u32 sleep_shn; /* The ANS is never reset through PMGR here, so no reset is named. */ bool reset_optional; + /* Pre-M4 controller that warm-idles and warm-restarts across deep sleep. */ + bool warm_sleep; bool secure_reg_layout; /* Also send the NVMe shutdown notification (CC.SHN) on removal. */ bool shutdown_notify; @@ -275,6 +277,7 @@ struct apple_nvme { bool sleep_restarting; ktime_t sleep_run_time; bool sleep_registered; + bool t8122_warm_sleep; unsigned long recovery_flags; void __iomem *mmio_coproc; @@ -1897,6 +1900,7 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) container_of(work, struct apple_nvme, ctrl.reset_work); enum nvme_ctrl_state state = nvme_ctrl_state(&anv->ctrl); bool inherited = !anv->owns_rtkit; + bool warm_restarted = false; if (anv->hw->needs_ioq_registers) { mutex_lock(&anv->disable_lock); @@ -2003,6 +2007,11 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) goto out; goto rtkit_ready; } + if (READ_ONCE(anv->sleep_restarted)) { + WRITE_ONCE(anv->sleep_restarted, false); + warm_restarted = true; + goto rtkit_ready; + } /* reset the controller if it is enabled */ if (anv->ctrl.ctrl_config & NVME_CC_ENABLE) apple_nvme_disable_legacy(anv, false); @@ -2049,6 +2058,14 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) if (ret) goto out; + /* + * T8122 shares the ANS reset with SART: replay saved SART + * entries after deasserting reset before starting ANS (no-op + * on cold boot when replay_valid is false). + */ + if (anv->sart) + apple_sart_replay(anv->sart); + writel(APPLE_ANS_COPROC_CPU_CONTROL_RUN, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); @@ -2088,12 +2105,14 @@ static void apple_nvme_reset_work_impl(struct work_struct *work) * queues. Woken this way, it would ignore the queue registers below, * which may only change while CC.EN is clear. Disable it first. */ - if (inherited && !anv->hw->needs_ioq_registers) { + if ((inherited || warm_restarted) && !anv->hw->needs_ioq_registers) { anv->ctrl.cap = readq(anv->mmio_nvme + NVME_REG_CAP); anv->ctrl.ctrl_config = readl(anv->mmio_nvme + NVME_REG_CC); if (anv->ctrl.ctrl_config & NVME_CC_ENABLE) { dev_info(anv->dev, - "controller handed over enabled, disabling it\n"); + "controller %s enabled, disabling it\n", + warm_restarted ? "retained after warm restart" : + "handed over"); ret = nvme_disable_ctrl(&anv->ctrl, false); if (ret) goto out; @@ -3137,6 +3156,39 @@ static void apple_nvme_shutdown(struct platform_device *pdev) * macOS. The wait for on doesn't: macOS rings the SEP a few ms after ANS's HELLO, before ANS * reports on, so the reset work waits, after the SEP's own resume has had its turn. */ +static void apple_nvme_t8122_warm_resume(struct apple_nvme *anv) +{ + void __iomem *control = anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL; + bool via_fw = pm_resume_via_firmware(); + int ret; + + if (!xchg(&anv->t8122_warm_sleep, false)) + return; + + if (via_fw) { + apple_sleep_restore_pins(); + if (anv->sart) + apple_sart_replay(anv->sart); + } + apple_rtkit_set_warm_epmap_mask(anv->rtk, BIT(0)); + anv->sleep_run_time = ktime_get(); + if (via_fw) { + ret = apple_rtkit_sleep_return_start(anv->rtk, control); + } else { + ret = apple_rtkit_warm_restart(anv->rtk); + if (!ret) + writel(readl(control) | APPLE_ANS_COPROC_CPU_CONTROL_RUN, + control); + } + if (ret) { + dev_err(anv->dev, "ANS warm restart failed (via_fw=%d): %d\n", + via_fw, ret); + anv->sleep_failed = true; + } else { + WRITE_ONCE(anv->sleep_restarting, true); + } +} + static int apple_nvme_resume_early(struct device *dev) { struct apple_nvme *anv = dev_get_drvdata(dev); @@ -3147,7 +3199,11 @@ static int apple_nvme_resume_early(struct device *dev) READ_ONCE(anv->m5.phase) != APPLE_M5_ANS_LIVE) return apple_nvme_m5_resume_early(anv); - if (!anv->hw->needs_ioq_registers || !anv->suspended || !anv->sleep_idled) + if (!anv->hw->needs_ioq_registers) { + apple_nvme_t8122_warm_resume(anv); + return 0; + } + if (!anv->suspended || !anv->sleep_idled) return 0; anv->sleep_idled = false; if (anv->sleep_stop) @@ -3232,6 +3288,11 @@ static int apple_nvme_resume(struct device *dev) WRITE_ONCE(anv->suspended, false); return nvme_try_sched_reset(&anv->ctrl); } + apple_nvme_t8122_warm_resume(anv); + if (READ_ONCE(anv->sleep_failed)) { + dev_crit(dev, "holding all I/O: ANS is down after the sleep, reboot to recover\n"); + return 0; + } return nvme_reset_ctrl(&anv->ctrl); } @@ -3392,6 +3453,20 @@ static int apple_nvme_suspend(struct device *dev) } if (apple_rtkit_is_running(anv->rtk)) { + if (anv->hw->warm_sleep && + pm_suspend_target_state == PM_SUSPEND_MEM && + pm_suspend_via_firmware()) { + anv->sleep_failed = false; + anv->sleep_restarted = false; + ret = apple_rtkit_idle(anv->rtk); + if (ret) { + dev_err(dev, "ANS warm idle failed: %d\n", ret); + return ret; + } + writel(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); + WRITE_ONCE(anv->t8122_warm_sleep, true); + return 0; + } ret = apple_rtkit_shutdown(anv->rtk); writel(0, anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL); @@ -3417,6 +3492,13 @@ static const struct apple_nvme_hw apple_nvme_t8103_hw = { .max_queue_depth = 64, }; +static const struct apple_nvme_hw apple_nvme_t8122_hw = { + .has_lsq_nvmmu = true, + .has_queue_count = true, + .warm_sleep = true, + .max_queue_depth = 64, +}; + /* * The post-M4 (T8132 and later) I/O queue setup follows Yureka Lilian's T8132 * support in m1n1 (commit 53f8ee9b54ba, "nvme: support T8132"). @@ -3528,6 +3610,7 @@ static const struct of_device_id apple_nvme_of_match[] = { { .compatible = "apple,t6050-nvme-ans2", .data = &apple_nvme_t6050_hw }, { .compatible = "apple,t8015-nvme-ans2", .data = &apple_nvme_t8015_hw }, { .compatible = "apple,t8103-nvme-ans2", .data = &apple_nvme_t8103_hw }, + { .compatible = "apple,t8122-nvme-ans2", .data = &apple_nvme_t8122_hw }, { .compatible = "apple,t8132-nvme-ans2", .data = &apple_nvme_t8132_hw }, { .compatible = "apple,t8140-nvme-ans2", .data = &apple_nvme_t8140_hw }, { .compatible = "apple,t8142-nvme-ans2", .data = &apple_nvme_t8142_hw }, From f7f2a1db0494c28171a2c4ecfd7d37059092a51a Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:54:29 -0500 Subject: [PATCH 1289/1514] drm/apple: iomfb 26.6: answer power-down callbacks Answer the callbacks the 26.6 DCP firmware sends when the display is powered down during suspend-to-RAM: D(2) (will_power_off_signal) and D(592) (swap_complete_intent_gated) as no-ops, D(572) (powerUpDART) via dcp_s2r_dart_power() with success, and D(209) (get_calendar_time_ms). Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/iomfb_v26_6.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.c b/drivers/gpu/drm/apple/iomfb_v26_6.c index 95128654acf305..081b4d69ceb77f 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6.c @@ -554,6 +554,24 @@ static int dcp_v26_callback(void *cookie, u32 tag, } if (tag == D(576) && SHAPE(4, 0)) return 0; + /* + * Callbacks the firmware sends when the display is powered down (A473, observed in + * macOS's panel-off and in Linux's sleep calls), answered as the H17P and M4 drivers + * answer them: a no-op (D2), swap_complete_intent_gated (D592, a no-op), + * powerUpDART (D572, success) and get_calendar_time_ms (D209). + */ + if ((tag == D(2) && SHAPE(0, 0)) || (tag == D(592) && SHAPE(20, 0))) + return 0; + if (tag == D(572) && SHAPE(4, 4)) { + if (v26->dcp) + dcp_s2r_dart_power(v26->dcp, get_unaligned_le32(in)); + memset(out, 0, 4); + return 0; + } + if (tag == D(209) && SHAPE(0, 8)) { + put_unaligned_le64(ktime_get_real_ns() / NSEC_PER_MSEC, out); + return 0; + } if (tag == D(300) && SHAPE(16, 0)) { dcp_v26_publish(v26, in); return 0; From 76bf29e8d83cd6b90b13327b97c1b6619dd488c1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:54:30 -0500 Subject: [PATCH 1290/1514] dt-bindings: soc: apple: sleep: add apple,t8122-sleep Document the apple,t8122-sleep compatible and its 21 named register windows covering PMGR power state, CPU powergate/cluster controls, sleep commit, watchdog, SPMI, wake sources, MCC channels, and APCIE shared/port0 blocks. Signed-off-by: Satya Benson --- .../bindings/soc/apple/apple,t8140-sleep.yaml | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml index 25228d7c80251c..bb1c214d5e072a 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,t8140-sleep.yaml @@ -19,16 +19,17 @@ description: | properties: compatible: enum: + - apple,t8122-sleep - apple,t8132-sleep - apple,t8140-sleep - apple,t8142-sleep reg: - minItems: 25 + minItems: 21 maxItems: 41 reg-names: - minItems: 25 + minItems: 21 maxItems: 41 apple,wake-enable: @@ -105,6 +106,41 @@ required: - apple,display-coprocessors allOf: + - if: + properties: + compatible: + contains: + const: apple,t8122-sleep + then: + required: + - apple,wake-enable + properties: + reg: + minItems: 21 + maxItems: 21 + reg-names: + items: + - const: ps + - const: pwrgate + - const: cpu-start + - const: cllt + - const: cluster + - const: commit + - const: wdt + - const: spmi + - const: spmi-hpm + - const: wake + - const: ps-aon + - const: mcc-a + - const: mcc-b + - const: mcc-c + - const: mcc-d + - const: apcie-axi + - const: apcie-rc + - const: apcie-clkgen + - const: apcie-phy + - const: apcie-phy-ip + - const: apcie-port0 - if: properties: compatible: From b43e2b08a1ef5dbf7ed5aace0ad8a8c2a26d54bb Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:58:18 -0500 Subject: [PATCH 1291/1514] soc: apple: sleep: add T8122 deep sleep and resume Add the apple,t8122-sleep profile and SoC callbacks to the shared Apple system sleep driver, guarded behind apple_sleep.deep=1 and apple_sleep.untested_commit=1 while untested across all T8122 boards: - Extend the shared sleep core with per-SoC el1_wfi, no_wd2, debug_cut_after_stops, no_pmu_notes, display_no_restart, wake_required, and dry-run support (apple_sleep_dry_run()) for early_context SoCs. - Implement T8122 entry/wake in sleep-t8122.h: map all 21 register windows from DT (including MCC channels and APCIE blocks), clear HID4/EHID4 DISABLE_DC_MVA and DISABLE_DC_SW_L2 around the full PoP/PoC and L1/L2 cache clean, power down and restore APCIE PHY/port0, step down MCC channels, and arm CYC_OVRD WFI mode 3 and DEEP_SLEEP_ENABLE before dropping to EL1 deep WFI. - Register apple,t8122-sleep in sleep-test.c KUnit coverage. Signed-off-by: Satya Benson --- drivers/soc/apple/sleep-t8122.h | 1256 +++++++++++++++++++++++++++++++ drivers/soc/apple/sleep-test.c | 4 +- drivers/soc/apple/sleep.c | 182 ++++- include/linux/soc/apple/sleep.h | 8 + 4 files changed, 1423 insertions(+), 27 deletions(-) create mode 100644 drivers/soc/apple/sleep-t8122.h diff --git a/drivers/soc/apple/sleep-t8122.h b/drivers/soc/apple/sleep-t8122.h new file mode 100644 index 00000000000000..957b4fc4b77444 --- /dev/null +++ b/drivers/soc/apple/sleep-t8122.h @@ -0,0 +1,1256 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * T8122 (Apple M3) system suspend-to-RAM support. + * + * Implements the T8122 sleep register map, display/APCIE/ATC/MCC shutdown and + * wake sequences, HID4/EHID4-unblocked PoP/PoC cache clean before deep sleep, + * and CYC_OVRD mode-3 EL1 deep WFI arming. + */ + +#define T8122_PS_GPIO 0x120 +#define T8122_PS_DISP_SYS 0x1d8 +#define T8122_PS_GFX 0x1e0 +#define T8122_PS_DISP_FE 0x208 +#define T8122_PS_SIO_CPU 0x210 +#define T8122_PS_APCIE 0x3f0 +#define T8122_PS_ANS 0x3f8 +#define T8122_PS_ATC0_COMMON 0x400 +#define T8122_PS_ATC1_COMMON 0x408 +#define T8122_PS_APCIE_GP 0x440 +#define T8122_PS_APCIE_ST 0x448 +#define T8122_PS_APCIE_PHY_SW 0x4a0 +#define T8122_PS_SEP 0xc00 +#define T8122_PS_DISP_CPU 0x10000 + +#define T8122_PS_AUTO_IDLE 0x1400000f + +#define T8122_AON_ATC0_USB_AON 0xb0 +#define T8122_AON_ATC1_USB_AON 0xb8 +#define T8122_AON_ATC0_USB 0xc0 +#define T8122_AON_ATC1_USB 0xc8 + +#define T8122_APCIE_PHY_CTRL_RESET BIT(7) +#define T8122_APCIE_PHY_CTRL_UP BIT(9) + +#define T8122_PWRGATE_E 0x80 +#define T8122_PWRGATE_P 0x88 +#define T8122_PWRGATE_DISP_A 0xcac +#define T8122_PWRGATE_DISP_B 0xcd0 +#define T8122_PWRGATE_DISP_C 0xcf0 + +#define T8122_CLUSTER_E 0x0 +#define T8122_CLUSTER_P 0x4 +#define T8122_CLLT_CTL 0x0 +#define T8122_CLLT_LAST 0x24 + +#define T8122_SYS_HID4 sys_reg(3, 0, 15, 4, 0) +#define T8122_SYS_EHID4 sys_reg(3, 0, 15, 4, 1) +#define T8122_HID4_DISABLE_DC_MVA BIT_ULL(11) +#define T8122_HID4_DISABLE_DC_SW_L2 BIT_ULL(44) +#define T8122_HID4_DC_MASK (T8122_HID4_DISABLE_DC_MVA | T8122_HID4_DISABLE_DC_SW_L2) +#define T8122_MPIDR_P_CORE BIT_ULL(16) + +#define T8122_SYS_CYC_OVRD sys_reg(3, 5, 15, 5, 0) +#define T8122_CYC_WFI_MODE GENMASK_ULL(25, 24) + +/* Every PMGR power-state word in the T8122 device tree. */ +static const u32 t8122_ps_all[] = { + 0x100, 0x108, 0x110, 0x118, 0x120, 0x128, 0x130, 0x138, 0x140, 0x148, + 0x150, 0x158, 0x160, 0x168, 0x170, 0x178, 0x180, 0x188, 0x190, 0x198, + 0x1a8, 0x1b0, 0x1b8, 0x1d8, 0x1e0, 0x1e8, 0x1f0, 0x200, 0x208, 0x210, + 0x218, 0x220, 0x228, 0x230, 0x238, 0x240, 0x248, 0x250, 0x258, 0x260, + 0x268, 0x270, 0x278, 0x280, 0x288, 0x290, 0x298, 0x2a0, 0x2a8, 0x2b0, + 0x2b8, 0x2c0, 0x2c8, 0x2d0, 0x2d8, 0x2e0, 0x2e8, 0x2f0, 0x2f8, 0x300, + 0x308, 0x310, 0x318, 0x330, 0x338, 0x340, 0x348, 0x358, 0x360, 0x368, + 0x370, 0x378, 0x380, 0x388, 0x390, 0x398, 0x3a0, 0x3a8, 0x3b0, 0x3b8, + 0x3c0, 0x3f0, 0x3f8, 0x400, 0x408, 0x410, 0x418, 0x420, 0x428, 0x430, + 0x438, 0x440, 0x448, 0x450, 0x458, 0x460, 0x468, 0x470, 0x478, 0x480, + 0x488, 0x490, 0x498, 0x4a0, 0x4a8, 0x4b0, 0x4b8, 0x4c0, 0xc00, 0x4000, + 0x4008, 0x4010, 0x4018, 0x4020, 0x4028, 0x4030, 0x4038, 0x4040, 0x4048, 0x4050, + 0x4058, 0x4060, 0x8000, 0x8008, 0x8010, 0x8018, 0x8020, 0x10000, +}; + +/* + * On at macOS's commit and off once Linux's drivers have suspended: + * DWI, GPIO, SOC_RC, SPI_P, UART_P, AUDIO_P, UART_N, UART0. Parents first. + */ +static const u32 t8122_ps_macos_on[] = { + 0x118, 0x120, 0x168, 0x278, 0x280, 0x288, 0x2d0, 0x2d8, +}; + +/* Off at macOS's commit and left clock-gated by the bootloader. */ +static const u32 t8122_ps_macos_off[] = { + 0x108, 0x138, 0x140, 0x148, 0x150, 0x158, 0x178, 0x228, 0x258, 0x260, + 0x268, 0x270, 0x2f8, 0x300, 0x308, 0x378, 0x380, 0x388, 0x390, 0x3b8, +}; + +static const u32 t8122_ps_aon_all[] = { + 0x0, 0x58, 0x60, 0x68, 0x70, 0x78, 0x80, 0x88, + 0x90, 0x98, 0xa0, 0xa8, 0xb0, 0xb8, 0xc0, 0xc8, +}; + +static const u32 t8122_ps_wake_order[] = { + 0xc00, 0x100, 0x110, 0x118, 0x120, 0x128, 0x130, 0x3f0, + 0x3f8, 0x440, 0x448, 0x450, 0x458, 0x4a0, 0x400, 0x408, +}; + +static const u32 t8122_ps_aon_wake_order[] = { 0x90 }; + +static const struct apple_sleep_word t8122_stray[] = { + { "isp_sys", 0x1e8 }, { "i2c1", 0x238 }, { "i2c2", 0x240 }, { "i2c3", 0x248 }, + { "spi2", 0x2a8 }, { "qspi", 0x2c8 }, { "sio_cpu", 0x210 }, { "apcie_phy_sw", 0x4a0 }, +}; + +static struct { + void __iomem *hpm_notify; + void __iomem *mcc[4]; + void __iomem *apcie_axi; + void __iomem *apcie_rc; + void __iomem *apcie_clkgen; + void __iomem *apcie_phy; + void __iomem *apcie_phy_ip; + void __iomem *apcie_port0; + u32 notify_saved[2]; + bool notify_staged; + bool matched; +} t8122; + +static __always_inline bool t8122_is_pcore(void) +{ + return !!(read_sysreg(mpidr_el1) & T8122_MPIDR_P_CORE); +} + +static __always_inline u64 t8122_read_hid4(bool pcore) +{ + return pcore ? read_sysreg_s(T8122_SYS_HID4) + : read_sysreg_s(T8122_SYS_EHID4); +} + +static __always_inline void t8122_write_hid4(bool pcore, u64 val) +{ + if (pcore) + write_sysreg_s(val, T8122_SYS_HID4); + else + write_sysreg_s(val, T8122_SYS_EHID4); + isb(); +} + +/* + * Clean [start, end) past T8122's L2 into SLC/DRAM via clean-only dc cvadp + * (FEAT_DPB2) or dc cvap (FEAT_DPB). Must run with HID4/EHID4 DISABLE_DC_MVA + * cleared so the maintenance instructions are not ignored as NOPs. + */ +static __always_inline void t8122_clean_range_slc(unsigned long start, unsigned long end) +{ + unsigned long line = 4UL << ((read_sysreg(ctr_el0) >> 16) & 0xf); + unsigned int dpb = read_sysreg(id_aa64isar1_el1) & 0xf; + unsigned long addr = start & ~(line - 1); + + if (dpb >= 2) { + for (; addr < end; addr += line) + asm volatile("sys #3, c7, c13, #1, %0" : : "r"(addr) : "memory"); + } else if (dpb >= 1) { + for (; addr < end; addr += line) + asm volatile("sys #3, c7, c12, #1, %0" : : "r"(addr) : "memory"); + } else { + for (; addr < end; addr += line) + asm volatile("dc civac, %0" : : "r"(addr) : "memory"); + } + dsb(sy); +} + +/* + * Register-only dc csw across all implemented data/unified cache levels + * (L1 + L2 on T8122). Must run with HID4/EHID4 DISABLE_DC_SW_L2 cleared and + * zero stack writes so L1/L2 stay clean through dsb(sy). + */ +static __always_inline void t8122_dcache_clean_all_levels(void) +{ + u64 r_clidr, r_ccidx, r_lvl, r_ctype, r_ccsidr, r_lshift; + u64 r_way, r_mset, r_wshift, r_set, r_tmp; + + asm volatile( + "dsb sy\n\t" + "mrs %[clidr], clidr_el1\n\t" + "mrs %[ccidx], id_aa64mmfr2_el1\n\t" + "ubfx %[ccidx], %[ccidx], #20, #4\n\t" + "mov %[lvl], #0\n\t" + "1:\n\t" + "cmp %[lvl], #7\n\t" + "b.hs 5f\n\t" + "add %[tmp], %[lvl], %[lvl], lsl #1\n\t" + "lsr %[ctype], %[clidr], %[tmp]\n\t" + "and %[ctype], %[ctype], #7\n\t" + "cbz %[ctype], 5f\n\t" + "cmp %[ctype], #2\n\t" + "b.lo 4f\n\t" + "cmp %[ctype], #4\n\t" + "b.hi 4f\n\t" + "lsl %[tmp], %[lvl], #1\n\t" + "msr csselr_el1, %[tmp]\n\t" + "isb\n\t" + "mrs %[ccsidr], ccsidr_el1\n\t" + "and %[lshift], %[ccsidr], #7\n\t" + "add %[lshift], %[lshift], #4\n\t" + "cbnz %[ccidx], 20f\n\t" + "ubfx %[way], %[ccsidr], #3, #10\n\t" + "ubfx %[mset], %[ccsidr], #13, #15\n\t" + "b 21f\n\t" + "20:\n\t" + "ubfx %[way], %[ccsidr], #3, #21\n\t" + "ubfx %[mset], %[ccsidr], #32, #24\n\t" + "21:\n\t" + "clz %w[wshift], %w[way]\n\t" + "2:\n\t" + "mov %[set], %[mset]\n\t" + "lsl %[ctype], %[way], %[wshift]\n\t" + "orr %[ctype], %[ctype], %[lvl], lsl #1\n\t" + "3:\n\t" + "lsl %[tmp], %[set], %[lshift]\n\t" + "orr %[tmp], %[ctype], %[tmp]\n\t" + "dc csw, %[tmp]\n\t" + "subs %[set], %[set], #1\n\t" + "b.ge 3b\n\t" + "subs %[way], %[way], #1\n\t" + "b.ge 2b\n\t" + "dsb sy\n\t" + "4:\n\t" + "add %[lvl], %[lvl], #1\n\t" + "b 1b\n\t" + "5:\n\t" + "msr csselr_el1, xzr\n\t" + "dsb sy\n\t" + "isb\n\t" + : [clidr] "=&r"(r_clidr), + [ccidx] "=&r"(r_ccidx), + [lvl] "=&r"(r_lvl), + [ctype] "=&r"(r_ctype), + [ccsidr] "=&r"(r_ccsidr), + [lshift] "=&r"(r_lshift), + [way] "=&r"(r_way), + [mset] "=&r"(r_mset), + [wshift] "=&r"(r_wshift), + [set] "=&r"(r_set), + [tmp] "=&r"(r_tmp) + : + : "cc", "memory"); +} + +static bool t8122_linear_va_valid(unsigned long addr) +{ + pgd_t *pgdp = pgd_offset_k(addr); + pgd_t pgd = READ_ONCE(*pgdp); + p4d_t *p4dp, p4d; + pud_t *pudp, pud; + pmd_t *pmdp, pmd; + pte_t *ptep; + + if (pgd_none(pgd) || pgd_bad(pgd)) + return false; + p4dp = p4d_offset(pgdp, addr); + p4d = READ_ONCE(*p4dp); + if (p4d_none(p4d) || p4d_bad(p4d)) + return false; + pudp = pud_offset(p4dp, addr); + pud = READ_ONCE(*pudp); + if (pud_none(pud)) + return false; + if (pud_leaf(pud)) + return pud_valid(pud); + if (pud_bad(pud)) + return false; + pmdp = pmd_offset(pudp, addr); + pmd = READ_ONCE(*pmdp); + if (pmd_none(pmd)) + return false; + if (pmd_leaf(pmd)) + return pmd_valid(pmd); + if (pmd_bad(pmd)) + return false; + ptep = pte_offset_kernel(pmdp, addr); + return ptep && pte_valid(READ_ONCE(*ptep)); +} + +static void t8122_clean_used_ram(void) +{ + struct memblock_region *reg; + + for_each_mem_region(reg) { + unsigned long pfn, end_pfn; + unsigned long run_start = 0, run_end = 0; + + if (memblock_is_nomap(reg)) + continue; + pfn = PFN_UP(reg->base); + end_pfn = PFN_DOWN(reg->base + reg->size); + while (pfn < end_pfn) { + struct page *page; + unsigned long va; + + if (!pfn_valid(pfn)) { + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + continue; + } + page = pfn_to_page(pfn); + if (PageBuddy(page)) { + unsigned long order = page_private(page); + unsigned long nr = 1; + + if (order <= MAX_PAGE_ORDER && + !(pfn & ((1UL << order) - 1))) + nr = 1UL << order; + if (nr > end_pfn - pfn) + nr = end_pfn - pfn; + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn += nr; + continue; + } + if (PageOffline(page)) { + if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + continue; + } + va = (unsigned long)page_address(page); + if (va && t8122_linear_va_valid(va)) { + if (run_start && va == run_end) { + run_end += PAGE_SIZE; + } else { + if (run_start) + t8122_clean_range_slc(run_start, run_end); + run_start = va; + run_end = va + PAGE_SIZE; + } + } else if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + pfn++; + } + if (run_start) + t8122_clean_range_slc(run_start, run_end); + } + dsb(sy); +} + +/* + * Clean the mapped kernel image (_text.._end). Under CTR_EL0.IDC=1 and + * rodata=full, patched text/rodata aliases are unmapped in the linear map and + * must be cleaned via kernel VAs so DRAM matches patched code on wake. + */ +static void t8122_clean_kernel_image(void) +{ + unsigned long start = (unsigned long)_text & PAGE_MASK; + unsigned long end = PAGE_ALIGN((unsigned long)_end); + unsigned long va, run_start = 0, run_end = 0; + + for (va = start; va < end; va += PAGE_SIZE) { + if (t8122_linear_va_valid(va)) { + if (run_start && va == run_end) { + run_end += PAGE_SIZE; + } else { + if (run_start) + t8122_clean_range_slc(run_start, run_end); + run_start = va; + run_end = va + PAGE_SIZE; + } + } else if (run_start) { + t8122_clean_range_slc(run_start, run_end); + run_start = 0; + } + } + if (run_start) + t8122_clean_range_slc(run_start, run_end); + dsb(sy); +} + +static void t8122_clean_percpu_slc(void) +{ + unsigned int cpu; + + for_each_possible_cpu(cpu) { + unsigned long area = (unsigned long)__per_cpu_start + per_cpu_offset(cpu); + + t8122_clean_range_slc(area, area + (__per_cpu_end - __per_cpu_start)); + } +} + +static void t8122_clean_all_kptables(void) +{ + unsigned int i, j, k, l; + pgd_t *pgd_base = swapper_pg_dir; + + t8122_clean_range_slc((unsigned long)pgd_base, + (unsigned long)pgd_base + PAGE_SIZE); + for (i = 0; i < PTRS_PER_PGD; i++) { + pgd_t pgd = READ_ONCE(pgd_base[i]); + p4d_t *p4d_base; + + if (pgd_none(pgd) || pgd_bad(pgd) || pgd_leaf(pgd)) + continue; + p4d_base = p4d_offset(&pgd_base[i], 0); + if ((unsigned long)p4d_base != (unsigned long)&pgd_base[i]) + t8122_clean_range_slc((unsigned long)p4d_base, + (unsigned long)p4d_base + PAGE_SIZE); + for (j = 0; j < PTRS_PER_P4D; j++) { + p4d_t p4d = READ_ONCE(p4d_base[j]); + pud_t *pud_base; + + if (p4d_none(p4d) || p4d_bad(p4d) || p4d_leaf(p4d)) + continue; + pud_base = pud_offset(&p4d_base[j], 0); + if ((unsigned long)pud_base != (unsigned long)&p4d_base[j]) + t8122_clean_range_slc((unsigned long)pud_base, + (unsigned long)pud_base + PAGE_SIZE); + for (k = 0; k < PTRS_PER_PUD; k++) { + pud_t pud = READ_ONCE(pud_base[k]); + pmd_t *pmd_base; + + if (pud_none(pud) || pud_bad(pud) || pud_leaf(pud)) + continue; + pmd_base = pmd_offset(&pud_base[k], 0); + if ((unsigned long)pmd_base != (unsigned long)&pud_base[k]) + t8122_clean_range_slc((unsigned long)pmd_base, + (unsigned long)pmd_base + PAGE_SIZE); + for (l = 0; l < PTRS_PER_PMD; l++) { + pmd_t pmd = READ_ONCE(pmd_base[l]); + pte_t *pte_base; + + if (pmd_none(pmd) || pmd_bad(pmd) || pmd_leaf(pmd)) + continue; + pte_base = pte_offset_kernel(&pmd_base[l], 0); + if (pte_base) + t8122_clean_range_slc((unsigned long)pte_base, + (unsigned long)pte_base + PAGE_SIZE); + } + } + } + } + dsb(sy); +} + +static void t8122_clean_va_ptables(unsigned long start, unsigned long len) +{ + unsigned long addr = start & PAGE_MASK; + unsigned long end = PAGE_ALIGN(start + len); + + for (; addr < end; addr += PAGE_SIZE) { + pgd_t *pgdp = pgd_offset_k(addr); + p4d_t *p4dp; + pud_t *pudp; + pmd_t *pmdp; + pte_t *ptep; + + t8122_clean_range_slc((unsigned long)pgdp & PAGE_MASK, + ((unsigned long)pgdp & PAGE_MASK) + PAGE_SIZE); + if (pgd_none(*pgdp) || pgd_bad(*pgdp)) + continue; + p4dp = p4d_offset(pgdp, addr); + if ((unsigned long)p4dp != (unsigned long)pgdp) + t8122_clean_range_slc((unsigned long)p4dp & PAGE_MASK, + ((unsigned long)p4dp & PAGE_MASK) + PAGE_SIZE); + if (p4d_none(*p4dp) || p4d_bad(*p4dp)) + continue; + pudp = pud_offset(p4dp, addr); + t8122_clean_range_slc((unsigned long)pudp & PAGE_MASK, + ((unsigned long)pudp & PAGE_MASK) + PAGE_SIZE); + if (pud_none(*pudp) || pud_bad(*pudp) || pud_leaf(*pudp)) + continue; + pmdp = pmd_offset(pudp, addr); + t8122_clean_range_slc((unsigned long)pmdp & PAGE_MASK, + ((unsigned long)pmdp & PAGE_MASK) + PAGE_SIZE); + if (pmd_none(*pmdp) || pmd_bad(*pmdp) || pmd_leaf(*pmdp)) + continue; + ptep = pte_offset_kernel(pmdp, addr); + if (ptep) + t8122_clean_range_slc((unsigned long)ptep & PAGE_MASK, + ((unsigned long)ptep & PAGE_MASK) + PAGE_SIZE); + } +} + +static void t8122_clean_state_poc(struct apple_sleep *s) +{ + unsigned int i, stash_n = mpidr_hash_size(); + + t8122_clean_range_slc((unsigned long)swapper_pg_dir, + (unsigned long)swapper_pg_dir + PAGE_SIZE); + t8122_clean_range_slc((unsigned long)idmap_pg_dir, + (unsigned long)idmap_pg_dir + 3 * PAGE_SIZE); + t8122_clean_va_ptables((unsigned long)current, sizeof(*current)); + t8122_clean_va_ptables((unsigned long)task_stack_page(current), THREAD_SIZE); + t8122_clean_va_ptables((unsigned long)s, sizeof(*s)); + t8122_clean_va_ptables((unsigned long)&t8122, sizeof(t8122)); + if (sleep_save_stash) { + unsigned long base = (unsigned long)sleep_save_stash; + + t8122_clean_va_ptables(base, stash_n * sizeof(*sleep_save_stash)); + t8122_clean_range_slc(base, base + stash_n * sizeof(*sleep_save_stash)); + for (i = 0; i < stash_n; i++) { + unsigned long entry = READ_ONCE(sleep_save_stash[i]); + + if (entry) { + t8122_clean_va_ptables(entry, sizeof(struct sleep_stack_data)); + t8122_clean_range_slc(entry, entry + sizeof(struct sleep_stack_data)); + } + } + } + t8122_clean_range_slc((unsigned long)&mpidr_hash, + (unsigned long)(&mpidr_hash + 1)); + t8122_clean_range_slc((unsigned long)&sleep_save_stash, + (unsigned long)(&sleep_save_stash + 1)); + t8122_clean_range_slc((unsigned long)s, (unsigned long)(s + 1)); + t8122_clean_range_slc((unsigned long)&t8122, (unsigned long)(&t8122 + 1)); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, (unsigned long)(s->mbox + 1)); + if (s->ps_commit && s->soc->ps_all.count) + t8122_clean_range_slc((unsigned long)s->ps_commit, + (unsigned long)(s->ps_commit + s->soc->ps_all.count)); + if (s->ps_aon_commit && s->soc->ps_aon_all.count) + t8122_clean_range_slc((unsigned long)s->ps_aon_commit, + (unsigned long)(s->ps_aon_commit + s->soc->ps_aon_all.count)); + if (s->ps_on_saved && s->soc->ps_macos_on.count) + t8122_clean_range_slc((unsigned long)s->ps_on_saved, + (unsigned long)(s->ps_on_saved + s->soc->ps_macos_on.count)); + if (s->ps_off_saved && s->soc->ps_macos_off.count) + t8122_clean_range_slc((unsigned long)s->ps_off_saved, + (unsigned long)(s->ps_off_saved + s->soc->ps_macos_off.count)); + if (s->pins_saved && s->npins) + t8122_clean_range_slc((unsigned long)s->pins_saved, + (unsigned long)(s->pins_saved + s->npins)); + t8122_clean_range_slc((unsigned long)current, + (unsigned long)current + sizeof(*current)); + t8122_clean_range_slc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); + dsb(sy); +} + +static void __iomem *t8122_map(struct apple_sleep *s, const char *name, struct resource *out) +{ + struct device_node *np = s->dev->of_node; + struct resource res; + void __iomem *base; + int index; + + index = of_property_match_string(np, "reg-names", name); + if (index < 0) + return IOMEM_ERR_PTR(index); + if (of_address_to_resource(np, index, &res)) + return IOMEM_ERR_PTR(-EINVAL); + /* Never unmapped: the driver has no unbind, as the common map. */ + base = ioremap_np(res.start, resource_size(&res)); + if (!base) + return IOMEM_ERR_PTR(-ENOMEM); + if (out) + *out = res; + + return base; +} + +static int t8122_sleep_map_regs(struct apple_sleep *s) +{ + static const struct { + const char *name; + size_t offset; + } regs[] = { + { "pwrgate", offsetof(struct apple_sleep, pwrgate) }, + { "cpu-start", offsetof(struct apple_sleep, cpu_start) }, + { "cllt", offsetof(struct apple_sleep, cllt) }, + { "cluster", offsetof(struct apple_sleep, cluster) }, + { "commit", offsetof(struct apple_sleep, commit) }, + { "wdt", offsetof(struct apple_sleep, wdt) }, + { "spmi", offsetof(struct apple_sleep, spmi) }, + { "wake", offsetof(struct apple_sleep, wake) }, + }; + static const char *const mcc_names[4] = { "mcc-a", "mcc-b", "mcc-c", "mcc-d" }; + unsigned int i; + bool pcore; + u64 hid4_orig; + int ret; + + s->ps = t8122_map(s, "ps", &s->ps_res); + if (IS_ERR(s->ps)) + return dev_err_probe(s->dev, PTR_ERR(s->ps), "no ps registers\n"); + for (i = 0; i < ARRAY_SIZE(regs); i++) { + void __iomem **field = (void __iomem **)((u8 *)s + regs[i].offset); + + *field = t8122_map(s, regs[i].name, NULL); + if (IS_ERR(*field)) + return dev_err_probe(s->dev, PTR_ERR(*field), "no %s registers\n", + regs[i].name); + } + t8122.hpm_notify = t8122_map(s, "spmi-hpm", NULL); + if (IS_ERR(t8122.hpm_notify)) + return dev_err_probe(s->dev, PTR_ERR(t8122.hpm_notify), "no spmi-hpm registers\n"); + + s->ps_aon = t8122_map(s, "ps-aon", NULL); + if (IS_ERR(s->ps_aon)) { + dev_warn(s->dev, "no ps-aon registers: USB/debug domains will not be lowered\n"); + s->ps_aon = NULL; + } + + ret = apple_sleep_read_wake_sources(s); + if (ret) + return ret; + + for (i = 0; i < ARRAY_SIZE(mcc_names); i++) { + t8122.mcc[i] = t8122_map(s, mcc_names[i], NULL); + if (IS_ERR(t8122.mcc[i])) { + dev_warn(s->dev, "no %s registers: MCC channel step-down unavailable\n", + mcc_names[i]); + t8122.mcc[i] = NULL; + } + } + + { + static const struct { + const char *name; + void __iomem **slot; + } apcie_regs[] = { + { "apcie-axi", &t8122.apcie_axi }, + { "apcie-rc", &t8122.apcie_rc }, + { "apcie-clkgen", &t8122.apcie_clkgen }, + { "apcie-phy", &t8122.apcie_phy }, + { "apcie-phy-ip", &t8122.apcie_phy_ip }, + { "apcie-port0", &t8122.apcie_port0 }, + }; + + for (i = 0; i < ARRAY_SIZE(apcie_regs); i++) { + *apcie_regs[i].slot = t8122_map(s, apcie_regs[i].name, NULL); + if (IS_ERR(*apcie_regs[i].slot)) + return dev_err_probe(s->dev, PTR_ERR(*apcie_regs[i].slot), + "no %s registers\n", apcie_regs[i].name); + } + } + + /* Ensure the EL1 deep-WFI stub is clean in DRAM before secondary cores jump to it. */ + pcore = t8122_is_pcore(); + hid4_orig = t8122_read_hid4(pcore); + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DISABLE_DC_MVA); + t8122_clean_range_slc((unsigned long)t8142_el1_wfi_stub, + (unsigned long)t8142_el1_wfi_stub_end); + t8122_write_hid4(pcore, hid4_orig); + + s->driver_down = devm_bitmap_zalloc(s->dev, resource_size(&s->ps_res) / 4, GFP_KERNEL); + if (!s->driver_down) + return -ENOMEM; + if (apple_sleep_alloc_books(s)) + return -ENOMEM; + + return 0; +} + +static void t8122_ps_lower_if_on(struct apple_sleep *s, u32 off, u32 first, u32 second) +{ + if (!FIELD_GET(PS_ACTUAL, readl(s->ps + off))) + return; + if (first) + writel(first, s->ps + off); + writel(second, s->ps + off); +} + +static int t8122_sleep_display_off(struct apple_sleep *s) +{ + u64 start, hz = arch_timer_get_cntfrq(); + bool off = false; + + if (FIELD_GET(PS_ACTUAL, readl(s->ps + T8122_PS_DISP_CPU))) { + writel(0x0f0000ff, s->ps + T8122_PS_DISP_CPU); + writel(3, s->pwrgate + T8122_PWRGATE_DISP_A); + writel(0, s->pwrgate + T8122_PWRGATE_DISP_B); + writel(0, s->pwrgate + T8122_PWRGATE_DISP_C); + writel(0x0f0003f0, s->ps + T8122_PS_DISP_CPU); + } + t8122_ps_lower_if_on(s, T8122_PS_DISP_FE, 0, 0x23f0); + t8122_ps_lower_if_on(s, T8122_PS_DISP_SYS, 0, 0x23f0); + + start = read_sysreg(cntvct_el0); + while (read_sysreg(cntvct_el0) - start < hz / 10) { + if (!FIELD_GET(PS_ACTUAL, readl(s->ps + T8122_PS_DISP_CPU))) { + off = true; + break; + } + cpu_relax(); + } + if (!off) { + dev_err(s->dev, "refused: DISP_CPU stayed on: %#x\n", + readl(s->ps + T8122_PS_DISP_CPU)); + return -EBUSY; + } + + return 0; +} + +static void t8122_sleep_match(struct apple_sleep *s) +{ + const struct apple_sleep_soc *soc = s->soc; + int i; + + t8122.matched = true; + for (i = 0; i < soc->ps_macos_on.count; i++) { + u32 offset = soc->ps_macos_on.offset[i]; + + s->ps_on_saved[i] = readl(s->ps + offset); + if (FIELD_GET(PS_ACTUAL, s->ps_on_saved[i]) == 0xf) + continue; + sleep_ps_raise_start(s, offset); + } + for (i = 0; i < soc->ps_macos_off.count; i++) { + u32 offset = soc->ps_macos_off.offset[i]; + + s->ps_off_saved[i] = readl(s->ps + offset); + if (!sleep_ps_on(s, offset)) + continue; + sleep_ps_lower(s, offset); + } + for (i = 0; i < soc->ps_macos_off.count; i++) + sleep_ps_wait_off(s, soc->ps_macos_off.offset[i]); +} + +static void t8122_sleep_match_undo(struct apple_sleep *s) +{ + const struct apple_sleep_soc *soc = s->soc; + int i; + + if (!t8122.matched) + return; + t8122.matched = false; + if (s->returned) + return; + for (i = soc->ps_macos_off.count - 1; i >= 0; i--) + if (FIELD_GET(PS_ACTUAL, s->ps_off_saved[i])) + sleep_ps_raise(s, soc->ps_macos_off.offset[i]); + for (i = soc->ps_macos_on.count - 1; i >= 0; i--) { + u32 val = s->ps_on_saved[i]; + + if (!FIELD_GET(PS_ACTUAL, val)) + sleep_ps_lower(s, soc->ps_macos_on.offset[i]); + else if (FIELD_GET(PS_ACTUAL, val) != 0xf) + writel(val & ~PS_FLAGS, s->ps + soc->ps_macos_on.offset[i]); + } +} + +static void t8122_apcie_down(struct apple_sleep *s) +{ + void __iomem *axi600, *clk, *ctrl, *run, *phy0, *port0; + u32 val, b_phy0; + int ret; + + if (!t8122.apcie_axi || !t8122.apcie_clkgen || !t8122.apcie_phy || + !t8122.apcie_phy_ip || !t8122.apcie_port0) + return; + + ret = sleep_ps_raise_start(s, T8122_PS_APCIE); + ret |= sleep_ps_raise_start(s, T8122_PS_ANS); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_GP); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_ST); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_PHY_SW); + if (ret) { + dev_warn(s->dev, "APCIE power-down raise failed: %d\n", ret); + return; + } + + axi600 = t8122.apcie_axi + 0x600; + clk = t8122.apcie_clkgen + APCIE_CLK_CTRL; + ctrl = t8122.apcie_phy + APCIE_PHY_CTRL; + run = t8122.apcie_phy + APCIE_PHY_RUN; + phy0 = t8122.apcie_phy + 0xc000; + port0 = t8122.apcie_port0; + + /* Port 0 PHY + PERST shutdown */ + b_phy0 = readl(phy0); + if (b_phy0 & 0xc0000603U) { + writel(b_phy0 & ~0xc0000000U, phy0); + writel(readl(axi600) & ~BIT(16), axi600); + writel(readl(port0 + 0x13c) | 0x100, port0 + 0x13c); + writel(0, port0 + APCIE_PORT_PERST); + writel(readl(port0 + 0x13c) & ~0x100, port0 + 0x13c); + writel(readl(phy0) & ~BIT(10), phy0); + writel(readl(phy0) & ~BIT(9), phy0); + writel(readl(phy0) | BIT(4), phy0); + writel(readl(phy0) & ~BIT(0), phy0); + readl_poll_timeout_atomic(phy0, val, !(val & BIT(2)), 1, APCIE_POLL_US); + writel(readl(phy0) & ~BIT(1), phy0); + readl_poll_timeout_atomic(phy0, val, !(val & BIT(3)), 1, APCIE_POLL_US); + writel(readl(port0 + APCIE_PORT_APPCLK) & ~BIT(0), port0 + APCIE_PORT_APPCLK); + writel(readl(axi600) | BIT(16), axi600); + } + + /* Common PHY + PHY IP + AXI + CIO3PLL shutdown */ + writel(readl(t8122.apcie_phy_ip + 0x6c) & ~0xcU, t8122.apcie_phy_ip + 0x6c); + writel(readl(t8122.apcie_phy_ip + 0x7c) | 0x0f000000U, t8122.apcie_phy_ip + 0x7c); + writel(readl(ctrl) | T8122_APCIE_PHY_CTRL_RESET, ctrl); + writel(readl(ctrl) & ~APCIE_PHY_CTRL_CLK1REQ, ctrl); + readl_poll_timeout_atomic(ctrl, val, !(val & APCIE_PHY_CTRL_CLK1ACK), 1, APCIE_POLL_US); + writel(readl(ctrl) & ~APCIE_PHY_CTRL_CLK0REQ, ctrl); + readl_poll_timeout_atomic(ctrl, val, !(val & APCIE_PHY_CTRL_CLK0ACK), 1, APCIE_POLL_US); + writel(readl(run) & ~APCIE_PHY_RUN_EN2, run); + writel(readl(run) & ~APCIE_PHY_RUN_EN, run); + writel(readl(axi600) & ~BIT(16), axi600); + writel(readl(clk) & ~APCIE_CLK_RUN, clk); + writel(readl(clk) | APCIE_CLK_OFF, clk); + writel(readl(clk) & ~APCIE_GEN4_CLK_EN, clk); + readl_poll_timeout_atomic(clk, val, !(val & APCIE_CLK_BUSY), 1, APCIE_POLL_US); + writel(readl(clk) | APCIE_CLK_OFF2, clk); + + writel(T8122_PS_AUTO_IDLE, s->ps + T8122_PS_APCIE_PHY_SW); + readl_poll_timeout_atomic(s->ps + T8122_PS_APCIE_PHY_SW, val, + FIELD_GET(PS_ACTUAL, val) == 4, 1, 5000); + sleep_ps_raise_finish(s, T8122_PS_APCIE); + sleep_ps_raise_finish(s, T8122_PS_ANS); + sleep_ps_raise_finish(s, T8122_PS_APCIE_GP); + sleep_ps_raise_finish(s, T8122_PS_APCIE_ST); +} + +static void t8122_sleep_prepare_regs(struct apple_sleep *s) +{ + t8122_sleep_match(s); + t8122_apcie_down(s); + apple_sleep_pmu_write(s->spmi, s->soc->pmu_usid, + s->soc->pmu_sleep_reg, s->soc->pmu_sleep_val); + t8122.notify_saved[0] = readl(s->spmi + SPMI_NOTIFY_ENABLE); + t8122.notify_saved[1] = readl(t8122.hpm_notify + SPMI_NOTIFY_ENABLE); + t8122.notify_staged = true; + writel(s->soc->spmi_notify_sleep, s->spmi + SPMI_NOTIFY_ENABLE); + writel(s->soc->spmi_notify_sleep, t8122.hpm_notify + SPMI_NOTIFY_ENABLE); +} + +static void t8122_sleep_undo_regs(struct apple_sleep *s) +{ + t8122_sleep_match_undo(s); + if (!t8122.notify_staged) + return; + writel(t8122.notify_saved[0], s->spmi + SPMI_NOTIFY_ENABLE); + writel(t8122.notify_saved[1], t8122.hpm_notify + SPMI_NOTIFY_ENABLE); + t8122.notify_staged = false; +} + +static void t8122_aon_lower(struct apple_sleep *s, u32 off) +{ + u32 val = readl(s->ps_aon + off); + + if (val & PS_AUTO_ENABLE) { + val &= ~(PS_AUTO_ENABLE | PS_FLAGS); + writel(val, s->ps_aon + off); + } + writel((val & ~PS_TARGET) | PS_FLAGS, s->ps_aon + off); +} + +static void t8122_sleep_atc_off(struct apple_sleep *s) +{ + static const struct { + u32 usb, usb_aon, common; + } port[] = { + { T8122_AON_ATC0_USB, T8122_AON_ATC0_USB_AON, T8122_PS_ATC0_COMMON }, + { T8122_AON_ATC1_USB, T8122_AON_ATC1_USB_AON, T8122_PS_ATC1_COMMON }, + }; + unsigned int i; + + if (!s->ps_aon) + return; + for (i = 0; i < ARRAY_SIZE(port); i++) { + t8122_aon_lower(s, port[i].usb); + t8122_aon_lower(s, port[i].usb_aon); + sleep_ps_lower(s, port[i].common); + sleep_ps_wait_off(s, port[i].common); + } +} + +/* + * Step down T8122 MCC channel enable/stage registers after SLC write-back + * (handled by drivers/soc/apple/mcc.c in suspend_noirq) and CPU cache clean. + */ +static const struct { u8 page; u16 off; bool wide; } t8122_mcc_words[] = { + { 2, 0x000, true }, { 0, 0x000, true }, { 1, 0x000, true }, { 2, 0x800, true }, + { 0, 0x800, true }, { 1, 0x800, true }, { 3, 0x584, false }, { 3, 0x588, false }, +}; +static const char t8122_mcc_order[] = + "ABABABABABABAAAAAAAAABABABAABABABABABABABACACCCCCCCCCCCCCCCDDDEDEDFDFDDGGGGGGGGGHH"; + +static void t8122_mcc_channel_stop(void) +{ + unsigned int i; + + if (!t8122.mcc[0] || !t8122.mcc[1] || !t8122.mcc[2] || !t8122.mcc[3]) + return; + for (i = 0; t8122_mcc_order[i]; i++) { + unsigned int w = t8122_mcc_order[i] - 'A'; + void __iomem *reg = t8122.mcc[t8122_mcc_words[w].page] + t8122_mcc_words[w].off; + + if (t8122_mcc_words[w].wide) { + u64 q = readq(reg); + + if (q) + writeq(q & (q - 1), reg); + } else { + u32 l = readl(reg); + + if (l) + writel(l & (l - 1), reg); + } + } +} + +static void t8122_sleep_commit_regs(struct apple_sleep *s) +{ + bool pcore; + u64 hid4_orig; + + sleep_ps_save(s); + t8122_sleep_atc_off(s); + writel(0, s->wdt + WDT_WD0_CTL); + + /* + * Mask and save AIC state before the full cache clean so the saved + * interrupt masks reach DRAM before the clusters power off. + */ + aic_sleep_mask_all(); + + if (s->mbox) { + s->resumes_before = READ_ONCE(s->mbox->resumes); + WRITE_ONCE(s->mbox->resume_pa, __pa_symbol(s->soc->ops->resume)); + } + + pcore = t8122_is_pcore(); + hid4_orig = t8122_read_hid4(pcore); + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DC_MASK); + t8122_clean_used_ram(); + t8122_clean_kernel_image(); + t8122_clean_percpu_slc(); + t8122_clean_all_kptables(); + t8122_clean_state_poc(s); + t8122_dcache_clean_all_levels(); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, + (unsigned long)(s->mbox + 1)); + t8122_clean_range_slc((unsigned long)current, + (unsigned long)current + sizeof(*current)); + t8122_clean_range_slc((unsigned long)task_stack_page(current), + (unsigned long)task_stack_page(current) + THREAD_SIZE); + dsb(sy); + t8122_write_hid4(pcore, hid4_orig); + + t8122_mcc_channel_stop(); + + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_E); + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_P); + writel(0, s->cluster + T8122_CLUSTER_E); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntp_ctl_el0); + write_sysreg(ARCH_TIMER_CTRL_IT_MASK, cntv_ctl_el0); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_ENABLE); + writel(0, s->cluster + T8122_CLUSTER_P); + writel(0x2500, s->cllt + T8122_CLLT_CTL); + writel(0, s->cllt + T8122_CLLT_CTL); + writel(0x1c17, s->cllt + T8122_CLLT_LAST); +} + +/* + * Common apple_sleep_commit() writes s->mbox->resume_pa and calls + * dcache_clean_poc() right before pre_commit, which is a NOP on T8122 while + * HID4.DISABLE_DC_MVA is set. Clean s->mbox and s with DISABLE_DC_MVA cleared. + */ +static void t8122_sleep_pre_commit(struct apple_sleep *s) +{ + bool pcore = t8122_is_pcore(); + u64 hid4_orig = t8122_read_hid4(pcore); + + t8122_write_hid4(pcore, hid4_orig & ~T8122_HID4_DISABLE_DC_MVA); + if (s->mbox) + t8122_clean_range_slc((unsigned long)s->mbox, + (unsigned long)(s->mbox + 1)); + t8122_clean_range_slc((unsigned long)s, (unsigned long)(s + 1)); + dsb(sy); + t8122_write_hid4(pcore, hid4_orig); +} + +/* AIC was already masked and saved before the cache clean in commit_regs. */ +static void t8122_aic_mask_noop(void) +{ +} + +static void t8122_deep_wfi_arm(void) +{ + sysreg_clear_set_s(T8122_SYS_CYC_OVRD, 0, T8122_CYC_WFI_MODE); + isb(); + sysreg_clear_set_s(SYS_APL_DEEP_SLEEP, 0, DEEP_SLEEP_ENABLE); + isb(); + if (is_kernel_in_hyp_mode()) { + dsb(sy); + t8142_el1_wfi(); + } +} + +static int t8122_raise_apcie(struct apple_sleep *s) +{ + static const struct { u32 off, val; } axi[] = { + { 0x0034, 0x0000ffff }, { 0x0038, 0x0000ffff }, { 0x0000, 0x00000211 }, + { 0x000c, 0x00016800 }, { 0x0010, 0x0000b400 }, { 0x0108, 0x00100031 }, + { 0x010c, 0x00016800 }, { 0x0110, 0x0000b400 }, { 0x0600, 0xc0010001 }, + { 0x0c00, 0x01ffffff }, { 0x0d48, 0x00200000 }, { 0x0e58, 0x00800010 }, + { 0x1000, 0x00000101 }, + }; + static const struct { u32 off, val; } cio3pll[] = { + { 0x2200, 0x00081f55 }, { 0x2224, 0x00000818 }, { 0x2228, 0x00000b18 }, + { 0x224c, 0x1f800096 }, { 0x22e4, 0x01024201 }, { 0x22fc, 0x030b40b4 }, + }; + static const struct { u32 off, val; } phy_ip[] = { + { 0x0028, 0x00800800 }, { 0x006c, 0x0000004c }, { 0x0080, 0x80010001 }, { 0x0094, 0x00000001 }, + { 0x1204, 0x0000004c }, { 0x1000, 0x2a2383c8 }, { 0x102c, 0x04454447 }, { 0x5080, 0x294d8190 }, + { 0x5088, 0x00560800 }, { 0x508c, 0x294d8190 }, { 0x5094, 0x00060800 }, { 0x50a0, 0x00554800 }, + { 0x50ac, 0x00554800 }, { 0x50b8, 0x00554800 }, { 0x5200, 0x0008155e }, { 0x5224, 0x00000818 }, + { 0x5240, 0x04010f69 }, { 0x52b0, 0x10300811 }, { 0x52fc, 0x03078078 }, { 0x531c, 0x00000002 }, + { 0x608c, 0x65918280 }, { 0x6224, 0x00000818 }, { 0x6228, 0x00000b18 }, { 0x6230, 0x0001e80f }, + { 0x624c, 0x1f80009d }, { 0xa000, 0x080001aa }, { 0xa008, 0x0000000a }, { 0xa00c, 0x0000000a }, + { 0xa010, 0x0000000a }, { 0xa014, 0x0000000a }, { 0xa038, 0x00000271 }, { 0xa040, 0x000000c8 }, + { 0xa04c, 0x00000bff }, { 0xa050, 0x00000001 }, { 0xa068, 0x00000c41 }, { 0xa070, 0x55b00820 }, + { 0xa084, 0x3e8f4240 }, { 0xa088, 0x00000fff }, { 0xa10c, 0x000f4240 }, { 0xa11c, 0x000f30dc }, + { 0xa178, 0x00300000 }, { 0xa0c0, 0x14e051f8 }, { 0xa1a4, 0x00000901 }, { 0xa1b0, 0x00000000 }, + { 0xa1b8, 0x00000000 }, { 0xa1e8, 0x00100000 }, { 0x903c, 0x018c3509 }, { 0x90d8, 0x0102068d }, + { 0x90dc, 0x12004408 }, { 0x91e0, 0x00002008 }, { 0x9288, 0x0801172a }, { 0x9280, 0xcccccccc }, + { 0x9000, 0x1e000000 }, { 0x9280, 0xccc8ccc1 }, { 0x928c, 0x00000003 }, { 0xb02c, 0x01980062 }, + { 0xb098, 0x05028000 }, { 0xc01c, 0x000006a1 }, { 0xc080, 0x540c6831 }, { 0xc08c, 0x10be0c1f }, + { 0xc0a0, 0x021a1780 }, { 0xc0ec, 0x00000000 }, { 0xd008, 0x0000000c }, { 0xd014, 0x04840408 }, + }; + void __iomem *ctrl, *run, *ready, *common; + unsigned int i; + u32 val; + int ret; + + if (!t8122.apcie_axi || !t8122.apcie_rc || !t8122.apcie_clkgen || + !t8122.apcie_phy || !t8122.apcie_phy_ip) + return -ENODEV; + + ret = sleep_ps_raise_start(s, T8122_PS_APCIE); + ret |= sleep_ps_raise_start(s, T8122_PS_ANS); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_GP); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_ST); + ret |= sleep_ps_raise_start(s, T8122_PS_APCIE_PHY_SW); + if (ret) + return ret; + + for (i = 0; i < ARRAY_SIZE(axi); i++) + writel(axi[i].val, t8122.apcie_axi + axi[i].off); + + writel(0, t8122.apcie_rc + APCIE_RC_ZERO); + + writel(0x239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + writel(0x80000030, t8122.apcie_clkgen + APCIE_CLK_START); + writel(0x80000239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + ret = readl_poll_timeout_atomic(t8122.apcie_clkgen + APCIE_CLK_CTRL, val, + !(val & APCIE_CLK_BUSY), 1, APCIE_POLL_US); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(cio3pll); i++) + writel(cio3pll[i].val, t8122.apcie_clkgen + cio3pll[i].off); + writel(0x239, t8122.apcie_clkgen + APCIE_CLK_CTRL); + + ctrl = t8122.apcie_phy + APCIE_PHY_CTRL; + run = t8122.apcie_phy + APCIE_PHY_RUN; + ready = t8122.apcie_phy + APCIE_PHY_READY; + common = t8122.apcie_phy + APCIE_PHY_COMMON; + + writel(0x03010030, t8122.apcie_phy + 0x800c); + writel(0x0400c030, t8122.apcie_phy + 0x8010); + writel(readl(ctrl) | APCIE_PHY_CTRL_CLK0REQ, ctrl); + ret = readl_poll_timeout_atomic(ctrl, val, val & APCIE_PHY_CTRL_CLK0ACK, 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(ctrl) | APCIE_PHY_CTRL_CLK1REQ, ctrl); + ret = readl_poll_timeout_atomic(ctrl, val, val & APCIE_PHY_CTRL_CLK1ACK, 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(ctrl) & ~T8122_APCIE_PHY_CTRL_RESET, ctrl); + writel(readl(run) | APCIE_PHY_RUN_EN, run); + + for (i = 0; i < ARRAY_SIZE(phy_ip); i++) + writel(phy_ip[i].val, t8122.apcie_phy_ip + phy_ip[i].off); + + writel(readl(run) | APCIE_PHY_RUN_EN2, run); + ret = readl_poll_timeout_atomic(ready, val, val & BIT(0), 1, APCIE_POLL_US); + if (ret) + return ret; + writel(readl(common) | BIT(0), common); + writel(readl(ctrl) | T8122_APCIE_PHY_CTRL_UP, ctrl); + + writel(0x140, t8122.apcie_rc + APCIE_RC_READY_CFG); + writel(1, t8122.apcie_rc + APCIE_RC_READY_START); + return readl_poll_timeout_atomic(t8122.apcie_rc + APCIE_RC_READY_STAT, val, + val & BIT(0), 1, APCIE_POLL_US); +} + +static void t8122_port0_wake(struct apple_sleep *s) +{ + static const struct { u32 off, val; } port0_init[] = { + { 0x088, 0x00000110 }, { 0x100, 0xffffffff }, { 0x148, 0xffffffff }, + { 0x210, 0xffffffff }, { 0x080, 0x00000000 }, { 0x084, 0x00000000 }, + { 0x104, 0xfffffff0 }, { 0x124, 0x00000100 }, { 0x16c, 0x00000000 }, + { 0x13c, 0x00000010 }, { 0x800, 0x00100100 }, { 0x808, 0x001000ff }, + { 0x82c, 0x00000000 }, { 0x130, 0x03000000 }, { 0x140, 0x00000010 }, + { 0x144, 0x00253770 }, { 0x21c, 0x00000000 }, { 0x834, 0x00000000 }, + { 0x83c, 0x00000000 }, { 0x140, 0x00000011 }, { 0x8a4, 0x00002020 }, + }; + void __iomem *port = t8122.apcie_port0; + unsigned int i; + u32 val; + + writel(readl(t8122.apcie_axi + 0x600) & ~BIT(16), t8122.apcie_axi + 0x600); + + for (i = 0; i < ARRAY_SIZE(port0_init); i++) + writel(port0_init[i].val, port + port0_init[i].off); + + writel(0x00100101, port + APCIE_PORT_APPCLK); + writel(1, port + APCIE_PORT_PERST); + readl_poll_timeout_atomic(port + 0x804, val, val & BIT(0), 1, APCIE_POLL_US); + writel(0x00100001, port + APCIE_PORT_APPCLK); + writel(3, port + 0x4020); + + writel(readl(t8122.apcie_axi + 0x600) | BIT(16), t8122.apcie_axi + 0x600); + + sleep_apcie_port_clock(port, t8122.apcie_phy + 0xc000); +} + +static void t8122_sleep_wake(struct apple_sleep *s) +{ + u32 val; + + writel(CLUSTER_ON, s->cluster + T8122_CLUSTER_E); + s->cluster_e_ret = readl_poll_timeout_atomic(s->cluster + T8122_CLUSTER_E, val, + val & CLUSTER_E_READY, 1, + CLUSTER_TIMEOUT_US); + writel(CLUSTER_ON, s->cluster + T8122_CLUSTER_P); + + writel(PWRGATE_ON, s->pwrgate + s->soc->pwrgate_wake[0]); + writel(PWRGATE_ON, s->pwrgate + s->soc->pwrgate_wake[1]); + + if (s->ps_aon) + sleep_ps_rewake(s); + /* Ensure GPIO domain is on before apple_sleep_restore_pins(). */ + sleep_ps_raise(s, T8122_PS_GPIO); + s->pins_lost = s->pins_saved_valid; + + if (t8122.apcie_axi) { + if (!t8122_raise_apcie(s) && t8122.apcie_port0 && t8122.apcie_phy) + t8122_port0_wake(s); + sleep_ps_raise_finish(s, T8122_PS_APCIE); + sleep_ps_raise_finish(s, T8122_PS_ANS); + sleep_ps_raise_finish(s, T8122_PS_APCIE_GP); + sleep_ps_raise_finish(s, T8122_PS_APCIE_ST); + sleep_ps_raise_finish(s, T8122_PS_APCIE_PHY_SW); + } + + val = readl(s->ps + T8122_PS_SEP); + if (val & PS_DEV_DISABLE) + writel(val & ~PS_DEV_DISABLE, s->ps + T8122_PS_SEP); + + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_E); + writel(PWRGATE_ON, s->pwrgate + T8122_PWRGATE_P); +} + +static const struct apple_sleep_gate_coproc t8122_gate_coprocs[] = { + { "/soc/dcp@28ec00000", true, T8122_PS_DISP_CPU }, + { "/soc/pmp@2d0500000", true }, + { "/soc/gpu@292400000", true, T8122_PS_GFX }, + { "/soc/sep@29e400000" }, + { "/soc/nvme@30dcc0000" }, + { "/soc/smc@2ec400000" }, +}; + +static const struct apple_sleep_wake_name t8122_wake_names[] = { + { 3, "AOP.CPUWakeupAP" }, { 12, "AOP.GPIO.IRQ6" }, { 51, "AOP.OutboxNotEmpty" }, + { 74, "AOP.SPMI0.SW3" }, { 83, "AOP.SPMI1.SW3" }, { 87, "ATC0.CIOWakeup" }, + { 88, "ATC0.USBWakeup" }, { 89, "ATC1.CIOWakeup" }, { 90, "ATC1.USBWakeup" }, + { 100, "MTP.DOCK.CHANNELS.AP0.IRQ" }, { 107, "MTP.GPIO.IRQ4" }, { 109, "MTP.GPIO.IRQ6" }, + { 128, "NUB.APWakeupTime" }, { 129, "NUB.APWatchdog" }, { 143, "NUB.GPIO.IRQ6" }, + { 155, "NUB.SPMI0.SW3" }, { 165, "NUB.SPMI1.SW3" }, { 179, "NUB.WakeupAP" }, + { 184, "SMC.CPUWakeupAP" }, { 208, "SMC.OutboxNotEmpty" }, +}; + +static const u32 t8122_wake_required[] = { 155 }; + +static int t8122_sleep_cpu_prepare(u64 mpidr) +{ + return 0; +} + +static void t8122_sleep_cpu_restore(u64 mpidr) +{ +} + +static const struct apple_sleep_ops t8122_sleep_ops = { + .deep_wfi_arm = t8122_deep_wfi_arm, + .resume = cpu_resume, + .aic_mask_all = t8122_aic_mask_noop, + .aic_ack = aic_sleep_ack, + .aic_restore = aic_sleep_restore, + .map_regs = t8122_sleep_map_regs, + .display_off = t8122_sleep_display_off, + .prepare_regs = t8122_sleep_prepare_regs, + .undo_regs = t8122_sleep_undo_regs, + .commit_regs = t8122_sleep_commit_regs, + .pre_commit = t8122_sleep_pre_commit, + .wake = t8122_sleep_wake, + .cpu_prepare = t8122_sleep_cpu_prepare, + .cpu_restore = t8122_sleep_cpu_restore, +}; + +static const struct apple_sleep_soc t8122_sleep_soc = { + .ops = &t8122_sleep_ops, + .untested = true, + .pen_deep = true, + .el1_wfi = true, + .no_pmu_notes = true, + .display_no_restart = true, + .early_context = true, + .stray = t8122_stray, + .nstray = ARRAY_SIZE(t8122_stray), + .wake_mask = 0x08, + .wake_status = 0x24, + .wake_words = 7, + .wake_last_word = GENMASK(16, 0), + .wake_names = t8122_wake_names, + .nwake_names = ARRAY_SIZE(t8122_wake_names), + .no_wd2 = true, + .early_cpu_wfi = true, + .debug_cut_after_stops = true, + .boot_mpidr = 0x10100, + .cpu_count = 8, + .wake_required = t8122_wake_required, + .nwake_required = ARRAY_SIZE(t8122_wake_required), + .boot_wfi_delay_ms = 2, + .ndisp = 1, + .nmcc = 4, + .cluster_cpu = { T8122_CLUSTER_E, T8122_CLUSTER_P }, + .ncluster_cpu = 2, + .cpu_clusters = 2, + .cpu_cores_per_cluster = 4, + .cpu_start_stride = 4, + .pwrgate_wake = { 0x000, 0x040 }, + .pwrgate_cpm = { T8122_PWRGATE_E, T8122_PWRGATE_P }, + .pmu_usid = 0xe, + .pmu_sleep_reg = 0xf701, + .pmu_sleep_val = 0x50, + .spmi_notify_sleep = 0x2000001, + .ps_aon_debug_switch = 0xa8, + .ps = { + .disp = { { T8122_PS_DISP_CPU, T8122_PS_DISP_FE, T8122_PS_DISP_SYS } }, + .sep = T8122_PS_SEP, + .ans = T8122_PS_ANS, + .apcie_sys_gp = T8122_PS_ANS, + }, + .ps_all = SLEEP_WORDS(t8122_ps_all), + .ps_aon_all = SLEEP_WORDS(t8122_ps_aon_all), + .ps_wake_order = SLEEP_WORDS(t8122_ps_wake_order), + .ps_aon_wake_order = SLEEP_WORDS(t8122_ps_aon_wake_order), + .ps_macos_on = SLEEP_WORDS(t8122_ps_macos_on), + .ps_macos_off = SLEEP_WORDS(t8122_ps_macos_off), + .gate_coprocs = t8122_gate_coprocs, + .ngate_coprocs = ARRAY_SIZE(t8122_gate_coprocs), +}; diff --git a/drivers/soc/apple/sleep-test.c b/drivers/soc/apple/sleep-test.c index 56df6219d56776..5cafa2300b02a3 100644 --- a/drivers/soc/apple/sleep-test.c +++ b/drivers/soc/apple/sleep-test.c @@ -12,6 +12,7 @@ static const char *const apple_sleep_test_profiles[] = { "apple,t8142-sleep", "apple,t6050-sleep", "apple,t6050-j716c-sleep", + "apple,t8122-sleep", }; static bool apple_sleep_test_has(const struct apple_sleep_words *all, u32 offset) @@ -59,7 +60,8 @@ static void apple_sleep_test_known_profiles(struct kunit *test) KUNIT_EXPECT_NOT_NULL_MSG(test, id->data, "%s has no data", id->compatible); KUNIT_ASSERT_LT(test, n, ARRAY_SIZE(apple_sleep_test_profiles)); KUNIT_EXPECT_STREQ(test, id->compatible, apple_sleep_test_profiles[n]); - if (!strcmp(id->compatible, "apple,t8142-sleep")) { + if (!strcmp(id->compatible, "apple,t8142-sleep") || + !strcmp(id->compatible, "apple,t8122-sleep")) { const struct apple_sleep_soc *soc = id->data; KUNIT_ASSERT_NOT_NULL(test, soc); diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 7f93efef9ec5a0..dc2fc2151b2c02 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -52,6 +52,8 @@ #include #include #include +#include +#include #include #include #include @@ -86,6 +88,7 @@ #include #include #include +#include #include #include #include @@ -666,6 +669,19 @@ struct apple_sleep_soc { bool early_context; /* The SoC's operations arm and read its wake sources: none of the common wake words */ bool own_wake; + /* Secondary and boot cores drop to EL1 with MMU off for their final deep WFI. */ + bool el1_wfi; + /* WD2 is not this SoC's measured sleep safety net. */ + bool no_wd2; + /* Keep the debug link until the coprocessors have stopped. */ + bool debug_cut_after_stops; + /* The PMU scratch the step notes are written to is unmeasured on this SoC: none are. */ + bool no_pmu_notes; + /* + * The first display's driver stops its coprocessor cold for a sleep and can't restart + * it. A dry run leaves it running and doesn't count it among the refusals. + */ + bool display_no_restart; bool strict_gate_inventory; /* * No PMP runs and its report is disabled: the PTD entries the commit drops have no @@ -773,6 +789,12 @@ struct apple_sleep_soc { unsigned int nwake_names; /* The sources in the wake block's last word */ u32 wake_last_word; + /* + * Sources the tree's apple,wake-enable must name, or the sleep is refused: the ones a + * timed wake arrives on, so a sleep can't be entered that only a person can end. + */ + const u32 *wake_required; + unsigned int nwake_required; /* The encoders' system power words: their domains need the AVE complex up */ const u32 *ave_domains; unsigned int nave_domains; @@ -1014,6 +1036,8 @@ struct apple_sleep { /* This wake came back down the deep path, not the DRAM-kept one. */ bool deep_ran; bool regs_staged, wake_masks_saved, entry_prepared, entry_committed; + /* An untested SoC's sleep that stops before the commit, as .begin found the switch. */ + bool dry_run; u64 smc_idle_sent, smc_idle_ack, timer_at; struct { struct device *dev; @@ -1142,6 +1166,18 @@ module_param_named(untested_commit, sleep_untested_commit, bool, 0644); MODULE_PARM_DESC(untested_commit, "Untested SoC: let a deep sleep through to the commit (else a dry run that refuses)"); +/* + * Whether this sleep is an untested SoC's dry run. An early_context SoC's drivers ask the same + * answer in their .suspend, so it is the one .begin latched: the switch can't change under a + * sleep. The common entry reads the switch where it stops, as before. + */ +static bool apple_sleep_dry(const struct apple_sleep *s) +{ + if (!s->soc->untested) + return false; + return s->soc->early_context ? s->dry_run : !READ_ONCE(sleep_untested_commit); +} + /* * Untested SoCs: each step of a sleep in PMU scratch, readable after a reset. J815's ADT * pmu-main info-scrpad is 0x8000 + 0x2800; aurora-silicon/linux#1664 (T6041) notes its steps @@ -1668,6 +1704,15 @@ bool apple_sleep_commit_stops_coprocs(void) } EXPORT_SYMBOL_GPL(apple_sleep_commit_stops_coprocs); +/* This firmware sleep stops before its commit: a driver must stop nothing it can't restart. */ +bool apple_sleep_dry_run(void) +{ + struct apple_sleep *s = READ_ONCE(apple_sleep); + + return s && pm_suspend_via_firmware() && apple_sleep_dry(s); +} +EXPORT_SYMBOL_GPL(apple_sleep_dry_run); + /* * The last thing that can fail on the way to the commit: no CPU but this one is up and * interrupts are off, so no lock can be held. A coprocessor stopped here comes back only @@ -3358,6 +3403,10 @@ static bool apple_sleep_gate_failed(struct apple_sleep *s) /* Idled below full power, or stopped: its registers read only at full power. */ if (g->asc && g->ps && !sleep_asc_running(s, g->ps, g->asc)) continue; + /* Left running by a dry run, see apple_sleep_refuse(). */ + if (s->soc->display_no_restart && s->display[0].np && g->np == s->display[0].np && + apple_sleep_dry(s)) + continue; if (g->asc && g->ps && (g->allow_unstarted || s->soc->regions)) dev_err(s->dev, "%s didn't stop: control %#x\n", g->name, readl(g->asc + ASC_CPU_CONTROL)); @@ -3422,6 +3471,24 @@ static void sleep_wake_masks(struct apple_sleep *s, u32 *val) sleep_wake_unmask(s, val, s->wake_enable[i]); } +/* Every source the SoC requires is among the tree's. A SoC that requires none admits any. */ +static bool apple_sleep_wake_admitted(const struct apple_sleep_soc *soc, const u32 *enabled, + int count) +{ + unsigned int i; + int j; + + for (i = 0; i < soc->nwake_required; i++) { + for (j = 0; j < count; j++) + if (enabled[j] == soc->wake_required[i]) + break; + if (j >= count) + return false; + } + + return true; +} + /* The last checks, then the stray words lowered: what has stopped may not return until a wake. */ static int apple_sleep_refuse(struct apple_sleep *s) { @@ -3465,6 +3532,15 @@ static int apple_sleep_refuse(struct apple_sleep *s) dev_err(s->dev, "refused: no wake source enabled in the device tree\n"); refused = true; } + if (!apple_sleep_wake_admitted(s->soc, s->wake_enable, s->wake_enable_count)) { + dev_err(s->dev, "refused: the device tree doesn't enable the timed wake's source\n"); + refused = true; + } + /* A required source can be neither armed nor read back without its block. */ + if (s->soc->nwake_required && !s->wake) { + dev_err(s->dev, "refused: the wake block isn't mapped\n"); + refused = true; + } sleep_note(s, 0x21); /* Its first config access after the power loss would hang on the untrained link. */ @@ -3518,6 +3594,11 @@ static int apple_sleep_refuse(struct apple_sleep *s) } if (s->display[i].bound && sleep_asc_running(s, ps, s->display[i].asc) && (!apple_sleep_v27_late() || sleep_v27_final_check(i))) { + /* Only a sleep that commits has its driver stop it: there is no restart. */ + if (i == 0 && s->soc->display_no_restart && apple_sleep_dry(s)) { + dev_info(s->dev, "dry run: the display coprocessor is left running; a sleep that commits stops it cold, until a reboot\n"); + continue; + } dev_err(s->dev, "refused: a bound display coprocessor is still running\n"); refused = true; } @@ -3532,7 +3613,7 @@ static int apple_sleep_refuse(struct apple_sleep *s) sleep_note(s, 0x28); /* A dry run, which stops right after this, writes no power word (as in b27). */ - return apple_sleep_lower_stray(s, s->soc->untested && !READ_ONCE(sleep_untested_commit)); + return apple_sleep_lower_stray(s, apple_sleep_dry(s)); } static void sleep_wake_arm(struct apple_sleep *s) @@ -3817,7 +3898,8 @@ static int sleep_hpm_sleep(struct apple_sleep *s) */ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) { - ktime_t start = ktime_get(); + /* The raw counter: the late cut runs with timekeeping suspended. */ + u64 start = read_sysreg(cntvct_el0), hz = arch_timer_get_cntfrq(); bool wake = true, up; u32 val = 0; int ms, ret; @@ -3830,7 +3912,7 @@ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) *gone_ms = -1; mdelay(HPM_RESET_FIRST_MS); for (;;) { - ms = ktime_ms_delta(ktime_get(), start); + ms = div64_u64((read_sysreg(cntvct_el0) - start) * 1000, hz); if (ms >= HPM_CONTRACT_MS) return -ETIMEDOUT; ret = wake ? sleep_hpm_cmd(s, SPMI_OP_WAKEUP, 0, NULL, NULL) : 0; @@ -3852,7 +3934,7 @@ static int sleep_hpm_wait_contract(struct apple_sleep *s, int *gone_ms) /* A live debug link holds the debug switch domain on. */ static bool sleep_debug_link_up(struct apple_sleep *s) { - return s->hpm_spmi && + return s->hpm_spmi && s->ps_aon && FIELD_GET(PS_ACTUAL, readl(s->ps_aon + s->soc->ps_aon_debug_switch)); } @@ -3876,7 +3958,9 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) if (!sleep_debug_link_up(s)) return false; - dev_info(s->dev, "debug link: cutting it for the sleep\n"); + /* The late cut prints nothing after it: the console is the link. */ + dev_info(s->dev, "debug link: cutting it for the sleep%s\n", + s->soc->debug_cut_after_stops ? ", after the coprocessor stops" : ""); enable = readl(s->hpm_spmi + SPMI_NOTIFY_ENABLE); writel(enable & ~SPMI_NOTIFY_REPLY, s->hpm_spmi + SPMI_NOTIFY_ENABLE); /* A reset that the partner doesn't come back from is done again. */ @@ -3891,11 +3975,13 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) WRITE_ONCE(sleep_debug_link_cut, true); ms = sleep_hpm_wait_contract(s, &gone); if (ms >= 0) { - dev_info(s->dev, "debug link: contract back %d ms after reset %d (gone at %d ms)\n", - ms, i, gone); + if (!s->soc->debug_cut_after_stops) + dev_info(s->dev, "debug link: contract back %d ms after reset %d (gone at %d ms)\n", + ms, i, gone); break; } - dev_warn(s->dev, "debug link: no contract with the partner after reset %d\n", i); + if (!s->soc->debug_cut_after_stops) + dev_warn(s->dev, "debug link: no contract with the partner after reset %d\n", i); } if (!ret) ret = sleep_hpm_sleep(s); @@ -3908,7 +3994,12 @@ static bool apple_sleep_usb_down(struct apple_sleep *s) bool apple_sleep_debug_link_cut(void) { - return apple_sleep ? apple_sleep_usb_down(apple_sleep) : false; + struct apple_sleep *s = apple_sleep; + + /* The entry cuts it itself, after its stops. */ + if (!s || s->soc->debug_cut_after_stops) + return false; + return apple_sleep_usb_down(s); } EXPORT_SYMBOL_GPL(apple_sleep_debug_link_cut); @@ -3916,7 +4007,7 @@ bool apple_sleep_debug_link_up(void) { struct apple_sleep *s = apple_sleep; - return s && !s->usb_down_ran && sleep_debug_link_up(s); + return s && !s->soc->debug_cut_after_stops && !s->usb_down_ran && sleep_debug_link_up(s); } EXPORT_SYMBOL_GPL(apple_sleep_debug_link_up); @@ -5055,7 +5146,8 @@ static void sleep_spmi_sources_report(struct apple_sleep *s) static bool sleep_notes_on(struct apple_sleep *s) { - return s && s->spmi && s->soc->untested && READ_ONCE(sleep_pmu_notes); + return s && s->spmi && s->soc->untested && !s->soc->no_pmu_notes && + READ_ONCE(sleep_pmu_notes); } /* @@ -5626,8 +5718,8 @@ static int apple_sleep_commit(unsigned long unused) early = s->soc->early_cpu_wfi && READ_ONCE(sleep_early_wfi); if (early) { /* Released before the stop: each core goes from its stop bit to its deep WFI. */ - spin_table_pen_deep_el1(s->soc->ops->deep_wfi_arm == t8142_deep_wfi_arm && - is_kernel_in_hyp_mode() && READ_ONCE(sleep_el1_wfi) >= 2); + spin_table_pen_deep_el1(s->soc->pen_deep && is_kernel_in_hyp_mode() && + (s->soc->el1_wfi || READ_ONCE(sleep_el1_wfi) >= 2)); spin_table_release_stopped(); } s->cpus_stop_ret = spin_table_stop_parked(); @@ -5669,8 +5761,8 @@ static int apple_sleep_commit(unsigned long unused) /* Each core's deep WFI comes after the commit, this one last. No SPMI from here on. */ if (!early) { - spin_table_pen_deep_el1(s->soc->ops->deep_wfi_arm == t8142_deep_wfi_arm && - is_kernel_in_hyp_mode() && READ_ONCE(sleep_el1_wfi) >= 2); + spin_table_pen_deep_el1(s->soc->pen_deep && is_kernel_in_hyp_mode() && + (s->soc->el1_wfi || READ_ONCE(sleep_el1_wfi) >= 2)); spin_table_release_stopped(); } if (s->soc->boot_wfi_delay_ms) @@ -6145,6 +6237,31 @@ static void apple_sleep_display_then_gpu(struct apple_sleep *s) apple_sleep_coprocs_stop(s, true); } +/* + * An untested SoC with early_context stops here unless asked, as the common entry does: the + * refusals have run and passed, no stray word was lowered, and no core is held, no display + * word lowered, no SMC notice sent from here and nothing stopped. What is left that can refuse + * without changing anything runs too, so the dry run reports it: each coprocessor's own last + * check and the SoC's final check. + */ +static int apple_sleep_enter_dry(struct apple_sleep *s) +{ + int ret = apple_sleep_coprocs_check(s); + + if (!ret && s->soc->ops->final_check) + ret = s->soc->ops->final_check(s); + if (!ret && pm_wakeup_pending()) + ret = -EBUSY; + apple_sleep_stray_restore(s); + if (ret) { + dev_info(s->dev, "dry run: refused at the last checks: %d\n", ret); + return ret; + } + dev_info(s->dev, + "dry run: every check passed; refusing before the first stop and the commit (untested SoC, apple_sleep.untested_commit=1 lets it through)\n"); + return -EAGAIN; +} + /* * The entry of a SoC with early_context, called with the boot core's context saved. All * returning checks precede enclave/final-stop. @@ -6165,6 +6282,8 @@ static int apple_sleep_enter_prepare(struct apple_sleep *s) ret = apple_sleep_refuse(s); if (ret) return ret; + if (apple_sleep_dry(s)) + return apple_sleep_enter_dry(s); ret = apple_sleep_cpus_hold(s); if (!ret) { step = "display prepare"; @@ -6670,6 +6789,8 @@ static int apple_sleep_begin(suspend_state_t state) if (ret) return ret; + apple_sleep->dry_run = apple_sleep->soc->untested && !READ_ONCE(sleep_untested_commit); + if (apple_sleep->soc->ops->begin) { ret = apple_sleep->soc->ops->begin(apple_sleep); if (ret) @@ -6682,7 +6803,7 @@ static int apple_sleep_begin(suspend_state_t state) apple_sleep->smc_woke_alone = false; sleep_pins_save(apple_sleep); } - { + if (!apple_sleep->soc->no_wd2) { unsigned long flags; spin_lock_irqsave(&apple_sleep_wdt_lock, flags); @@ -6706,7 +6827,7 @@ static void apple_sleep_end(void) /* Nothing left by now after a wake; the platform wake takes it */ if (pm_suspend_via_firmware() && apple_sleep->soc->ops->pmu_wake) apple_sleep->soc->ops->pmu_wake(apple_sleep); - if (pm_suspend_via_firmware()) + if (pm_suspend_via_firmware() && !apple_sleep->soc->no_wd2) apple_sleep_wdt_end(apple_sleep->wdt); } @@ -7168,7 +7289,8 @@ static const struct platform_suspend_ops apple_sleep_ops = { /* For a SoC with early_context: the same, with the scopes its entry needs held */ static const struct platform_suspend_ops apple_sleep_early_ops = { - .valid = suspend_valid_only_mem, + /* An untested SoC's deep sleep is offered only with apple_sleep.deep=1. */ + .valid = apple_sleep_valid, .begin = apple_sleep_begin, .prepare = apple_sleep_prepare, .prepare_late = apple_sleep_late_scope_begin, @@ -8119,6 +8241,9 @@ static int apple_sleep_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "cannot control CPU power\n"); if (s->soc->pen_deep) spin_table_pen_deep_arm(true); + if (s->soc->el1_wfi) + dcache_clean_poc((unsigned long)t8142_el1_wfi_stub, + (unsigned long)t8142_el1_wfi_stub_end); /* Last: the exported helpers take it as a probed driver, and a failure frees s. */ apple_sleep = s; @@ -8139,13 +8264,15 @@ static int apple_sleep_probe(struct platform_device *pdev) READ_ONCE(sleep_el1_wfi) >= 2 ? "EL1 on every core" : "EL1 on the boot core", &(phys_addr_t){ __pa_symbol(t8142_el1_wfi_stub) }); } - dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", - readl(s->pwrgate + s->soc->pwrgate_wake[0]), - readl(s->pwrgate + s->soc->pwrgate_wake[1]), - readl(s->pwrgate + s->soc->pwrgate_cpm[0]), - readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), - readl(s->cluster + s->soc->cluster_cpu[0]), - readl(s->cluster + s->soc->cluster_cpu[1])); + /* The common layout's words: a SoC with its own map names none of them. */ + if (!s->soc->ops->map_regs) + dev_info(dev, "probe: pwrgate wake %#x %#x cpm %#x %#x, commit %#x, clusters %#x %#x\n", + readl(s->pwrgate + s->soc->pwrgate_wake[0]), + readl(s->pwrgate + s->soc->pwrgate_wake[1]), + readl(s->pwrgate + s->soc->pwrgate_cpm[0]), + readl(s->pwrgate + s->soc->pwrgate_cpm[1]), readl(s->commit), + readl(s->cluster + s->soc->cluster_cpu[0]), + readl(s->cluster + s->soc->cluster_cpu[1])); dev_warn(dev, "sleep data derived for this SoC, untested: deep sleep is %s, and %s\n", READ_ONCE(sleep_deep) ? "offered (apple_sleep.deep=1)" : "off (apple_sleep.deep=1 offers it)", READ_ONCE(sleep_untested_commit) ? "the commit is allowed" : @@ -9849,10 +9976,12 @@ static const struct apple_sleep_soc t8142_sleep_soc = { .wake_last_word = GENMASK(11, 0), }; +#include "sleep-t8122.h" + /* * Qualified profiles expose system sleep. Inventory-only profiles match for a * precise refusal and cannot reach hardware preparation or suspend_set_ops(). - * T8142 remains opt-in and requires its separate physical-commit gate. + * T8142 and T8122 remain opt-in and require their separate physical-commit gate. */ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8140-sleep", .data = &t8140_sleep_soc }, @@ -9860,6 +9989,7 @@ static const struct of_device_id apple_sleep_of_match[] = { { .compatible = "apple,t8142-sleep", .data = &t8142_sleep_soc }, { .compatible = "apple,t6050-sleep", .data = &t6050_sleep_soc }, { .compatible = "apple,t6050-j716c-sleep", .data = &t6050_j716c_sleep_soc }, + { .compatible = "apple,t8122-sleep", .data = &t8122_sleep_soc }, { } }; diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index d2642a9c8ffb43..aea4996a464b1d 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -150,6 +150,9 @@ bool apple_sleep_coproc_stopped(struct device *dev); */ bool apple_sleep_commit_stops_coprocs(void); +/* This firmware sleep stops before its commit: a driver must stop nothing it can't restart. */ +bool apple_sleep_dry_run(void); + /* * Untested SoCs: a coprocessor's last stop notes its own step in PMU scratch (kept across a * WD2 reset), next to the sleep driver's step and the coprocessor's slot. @@ -402,6 +405,11 @@ static inline bool apple_sleep_commit_stops_coprocs(void) return false; } +static inline bool apple_sleep_dry_run(void) +{ + return false; +} + static inline void apple_sleep_usb_set_asleep(bool asleep) { } From 0a2d813aa04e257417b7a5fff31c387056451a09 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:58:18 -0500 Subject: [PATCH 1292/1514] drm/apple: iomfb 26.6: cold-stop DCP for firmware-driven sleep When firmware-driven deep sleep will cut display power on an internal 26.6 DCP session (and the sleep is not a dry run), send the firmware's panel-off and sleep-entry RPC sequences, request RTKit AP/IOP idle, and halt the coprocessor so display power domains can turn off cleanly. Ignore further flushes and resume calls while cold-stopped. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp.c | 45 +++++++++++++++- drivers/gpu/drm/apple/iomfb_v26_6.c | 81 +++++++++++++++++++++++++++- drivers/gpu/drm/apple/iomfb_v26_6.h | 4 ++ 4 files changed, 130 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index cb77aa8eabd5a1..5c7d6a7229aaff 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -941,6 +941,8 @@ struct apple_dcp { struct delayed_work secure_poll_wq; /* Stopped and not restarted, which outlives a suspend that gets refused. */ bool s2r_fw_down; + /* Stopped cold for firmware-driven sleep, with no restart until reboot. */ + bool sleep_cold_stopped; /* * Its last system suspend left the firmware running and its domains on * (wakeup path), see dcp_sleep_keeps_firmware(). Cleared by the next diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4e48c4574624f2..f6b8edddc0f383 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -10428,11 +10428,25 @@ static void dcp_dpms_power_off(struct apple_dcp *dcp) __dcp_dpms_power_off(dcp); } +/* + * Internal 26.6 DCP firmware stops cold when firmware-driven deep sleep will + * cut display power, because there is no cold-restart path for it yet. In a + * sleep dry run the coprocessor is left running and takes the ordinary suspend + * path instead. + */ +static bool dcp_sleep_owned(struct apple_dcp *dcp) +{ + return IS_ENABLED(CONFIG_APPLE_SOC_SLEEP) && dcp->fw_compat == DCP_FIRMWARE_V_26_6 && + !dcp->external && apple_sleep_commit_stops_coprocs() && !apple_sleep_dry_run(); +} + bool dcp_s2r_firmware_stopped(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return READ_ONCE(dcp->s2r_fw_down); + /* Whichever of this and the display subsystem suspends first: nothing commits to it. */ + return READ_ONCE(dcp->s2r_fw_down) || READ_ONCE(dcp->sleep_cold_stopped) || + (pm_suspend_via_firmware() && dcp_sleep_owned(dcp)); } #include "dcp-v27-sleep.inc" @@ -10551,6 +10565,31 @@ static int dcp_platform_suspend(struct device *dev) if (pm_suspend_via_firmware() && dcp_v27_sleep_selected(dcp)) return dcp_v27_sleep_suspend(dcp); + if (READ_ONCE(dcp->sleep_cold_stopped)) + return 0; + if (pm_suspend_via_firmware() && dcp_sleep_owned(dcp)) { + u32 control = readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL); + struct apple_rtkit *rtk = dcp->rtk ?: dcp_v26_rtkit(dcp); + + dev_warn(dev, "display coprocessor stopped cold for sleep (control %#x); panel stays off until reboot\n", + control); + WRITE_ONCE(dcp->quiescing, true); + /* + * Run the 26.6 firmware's panel-off and sleep-entry calls, then + * request RTKit AP and IOP idle before halting the coprocessor. + */ + dcp_v26_sleep_calls(dcp, 2); + if (!IS_ERR_OR_NULL(rtk)) { + int ret = apple_rtkit_idle_with(rtk, dcp_secure_port_idle, dcp); + + if (ret) + dev_warn(dev, "RTKit idle before cold stop failed: %d\n", ret); + } + WRITE_ONCE(dcp->sleep_cold_stopped, true); + dcp_s2r_cpu_stop(dcp); + return 0; + } + /* * J813 uses the same qualified stop as DPMS off. Probe already gates * its derived power layout on appledrm.s2r_untested; without this @@ -10722,6 +10761,10 @@ static int dcp_platform_resume(struct device *dev) if (dcp_v27_sleep_selected(dcp) && READ_ONCE(dcp->sleep_v27_closed)) return dcp_v27_sleep_resume(dcp); + /* Stopped cold, with no restart path until reboot. */ + if (READ_ONCE(dcp->sleep_cold_stopped)) + return 0; + if (dcp->s2r_stopped) return dcp_s2r_resume(dcp); diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.c b/drivers/gpu/drm/apple/iomfb_v26_6.c index 081b4d69ceb77f..2f0b1ffa1ae085 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.c +++ b/drivers/gpu/drm/apple/iomfb_v26_6.c @@ -1792,7 +1792,8 @@ void iomfb_v26_6_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, p = crtc->primary->state; fb = p && p->visible ? p->fb : NULL; dcp->swap_start = ktime_get(); - if (!dcp->v26 || !dcp_v26_present(dcp->v26, fb, dcp->notch_height, &presented, cs)) { + if (READ_ONCE(dcp->sleep_cold_stopped) || !dcp->v26 || + !dcp_v26_present(dcp->v26, fb, dcp->notch_height, &presented, cs)) { dcp_v26_cancel_event(dcp); return; } @@ -1946,3 +1947,81 @@ void iomfb_v26_6_poweroff(struct apple_dcp *dcp) dcp_v26_present(dcp->v26, NULL, 0, NULL, NULL); } } + +/* + * Calls the 26.6 firmware receives from macOS before a system sleep, in the order and + * with the inputs observed on its mailbox and RPC memory. + * The panel-off group: A414 (8 zero bytes; reply 1), A478 (reply 1) twice, A476(1), + * A478, A412 (reply 1), A473 (16 zero bytes; reply 8 zero bytes), A500 (0, 0). + * The sleep-entry group: A478, A476(1), A473 (bytes 8, 11 and 12 set to 1), A115 + * (reply 0), A500 (0, 1). @groups: 1 sends the sleep-entry group only, 2 sends the + * panel-off group first, then the sleep-entry group. Every reply is compared with + * the expected firmware reply; a mismatch returns -EPROTO. + */ +static int dcp_v26_sleep_call(struct apple_dcp_v26 *v26, u32 tag, const void *in, u32 in_size, + const void *want, u32 want_size, bool *same) +{ + u8 out[8] = {}; + int ret; + + ret = dcp_v26_call(v26, tag, in, in_size, want_size ? out : NULL, want_size, 0); + if (!ret && want_size && memcmp(out, want, want_size)) { + dev_warn(v26->dev, "sleep call %#x reply %*ph, expected %*ph\n", tag, want_size, + out, want_size, want); + *same = false; + } + return ret; +} + +int dcp_v26_sleep_calls(struct apple_dcp *dcp, int groups) +{ + static const u8 zero16[16], one[4] = { 1 }, one8[8] = { 1 }; + static const u8 a473_entry[16] = { [8] = 1, [11] = 1, [12] = 1 }; + static const u8 a500_off[4] = { 0, 0 }, a500_entry[4] = { 0, 1 }; + struct apple_dcp_v26 *v26 = dcp->v26; + bool same = true; + int ret = 0; + + if (!v26 || !v26->started) + return -ENODEV; + mutex_lock(&v26->lock); + if (groups >= 2) { + ret = dcp_v26_sleep_call(v26, A(414), zero16, 8, one8, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(476), one, 4, NULL, 0, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(412), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(473), zero16, 16, zero16, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(500), a500_off, 4, NULL, 0, &same); + dev_dbg(v26->dev, "panel-off calls before sleep: %d\n", ret); + } + if (!ret) + ret = dcp_v26_sleep_call(v26, A(478), NULL, 0, one, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(476), one, 4, NULL, 0, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(473), a473_entry, 16, zero16, 8, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(115), NULL, 0, zero16, 4, &same); + if (!ret) + ret = dcp_v26_sleep_call(v26, A(500), a500_entry, 4, NULL, 0, &same); + mutex_unlock(&v26->lock); + if (!ret && !same) + ret = -EPROTO; + dev_dbg(v26->dev, "sleep calls (groups %d): %d, replies %s expected\n", groups, ret, + same ? "matched" : "differed from"); + return ret; +} + +struct apple_rtkit *dcp_v26_rtkit(struct apple_dcp *dcp) +{ + return dcp->v26 ? dcp->v26->rtk : NULL; +} diff --git a/drivers/gpu/drm/apple/iomfb_v26_6.h b/drivers/gpu/drm/apple/iomfb_v26_6.h index 2831ee2f793458..1b856a09eb21f9 100644 --- a/drivers/gpu/drm/apple/iomfb_v26_6.h +++ b/drivers/gpu/drm/apple/iomfb_v26_6.h @@ -11,6 +11,7 @@ #include struct apple_dcp; +struct apple_rtkit; struct apple_dcp_v26; struct dcp_v26_board; struct device; @@ -51,5 +52,8 @@ void iomfb_v26_6_flush(struct apple_dcp *dcp, struct drm_crtc *crtc, struct drm_atomic_commit *state); void iomfb_v26_6_poweron(struct apple_dcp *dcp); void iomfb_v26_6_poweroff(struct apple_dcp *dcp); +/* Pre-sleep shutdown calls and the session's RTKit for firmware-driven sleep. */ +int dcp_v26_sleep_calls(struct apple_dcp *dcp, int groups); +struct apple_rtkit *dcp_v26_rtkit(struct apple_dcp *dcp); #endif /* __APPLE_IOMFB_V26_6_H__ */ From 9bf498ce08d78ecff831b74be90504d34b0160da Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 02:58:40 -0500 Subject: [PATCH 1293/1514] arm64: dts: apple: t8122: describe sleep controller and two-cluster MCC Update the T8122 memory-controller node to memory-controller@220000000 with its two SLC cluster multicast apertures, add the disabled apple,t8122-sleep node with all 21 register windows to t8122.dtsi, and enable both nodes in the shared t8122-j613-j615.dtsi board description. Signed-off-by: Satya Benson --- .../arm64/boot/dts/apple/t8122-j613-j615.dtsi | 10 ++++++ .../boot/dts/apple/t8122-peripherals.dtsi | 7 ++-- arch/arm64/boot/dts/apple/t8122.dtsi | 36 +++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi index f891967d74d041..98df2180607c00 100644 --- a/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-j613-j615.dtsi @@ -503,3 +503,13 @@ }; }; }; + +&mcc { + apple,boot-dma-devices = <&pmp>; + status = "okay"; +}; + +&sleep { + apple,debug-port = <&hpm0>; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi index cfeb98ce06c76f..b740469f7578a8 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripherals.dtsi @@ -282,12 +282,9 @@ status = "disabled"; }; - mcc: memory-controller@2d03c0000 { + mcc: memory-controller@220000000 { compatible = "apple,t8122-mcc", "apple,mcc"; - reg = <0x2 0xd03c0000 0x0 0x20000>, - <0x2 0xd0478000 0x0 0x149c>, - <0x2 0xd0780000 0x0 0x4000>, - <0x2 0x20000000 0x0 0x2000000>, + reg = <0x2 0x20000000 0x0 0x2000000>, <0x2 0x22000000 0x0 0x2000000>; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t8122.dtsi b/arch/arm64/boot/dts/apple/t8122.dtsi index ad7382ac89ea41..c3e777c9ff688f 100644 --- a/arch/arm64/boot/dts/apple/t8122.dtsi +++ b/arch/arm64/boot/dts/apple/t8122.dtsi @@ -558,6 +558,7 @@ mboxes = <&sep_mbox>; mbox-names = "mbox"; iommus = <&sep_dart 0>; + power-domains = <&ps_sep>, <&ps_gpio>; status = "disabled"; }; @@ -893,6 +894,41 @@ /* child nodes are added in t8122-pmgr.dtsi */ }; + sleep: sleep-controller@2d0700000 { + compatible = "apple,t8122-sleep"; + reg = <0x2 0xd0700000 0x0 0x14000>, + <0x2 0xd0724000 0x0 0x4000>, + <0x2 0xd0734000 0x0 0x10>, + <0x2 0xd0768000 0x0 0x40>, + <0x2 0xd0780000 0x0 0x8>, + <0x2 0xe42d4000 0x0 0x4>, + <0x2 0xe42b0000 0x0 0x30>, + <0x2 0xe4714000 0x0 0x100>, + <0x2 0xe4908000 0x0 0x100>, + <0x2 0xe4004000 0x0 0x48>, + <0x2 0xe4280000 0x0 0x4000>, + <0x2 0x20024000 0x0 0x1000>, + <0x2 0x20064000 0x0 0x1000>, + <0x2 0x20158000 0x0 0x1000>, + <0x2 0x20400000 0x0 0x1000>, + <0x5 0x9c000000 0x0 0x2000>, + <0x5 0x91000000 0x0 0x1000>, + <0x5 0x9e088000 0x0 0x3000>, + <0x5 0x9e000000 0x0 0x10000>, + <0x5 0x9e040000 0x0 0x10000>, + <0x5 0x94008000 0x0 0x5000>; + reg-names = "ps", "pwrgate", "cpu-start", "cllt", + "cluster", "commit", "wdt", "spmi", + "spmi-hpm", "wake", "ps-aon", + "mcc-a", "mcc-b", "mcc-c", "mcc-d", + "apcie-axi", "apcie-rc", "apcie-clkgen", + "apcie-phy", "apcie-phy-ip", "apcie-port0"; + apple,wake-enable = <155>; + apple,display-coprocessors = <&dcp>; + apple,pinctrl = <&pinctrl_ap>; + status = "disabled"; + }; + pmp_mbox: mbox@2d0c08000 { compatible = "apple,t8122-asc-mailbox", "apple,asc-mailbox-v4"; reg = <0x2 0xd0c08000 0x0 0x4000>; From 0a2532804408ccd79ddbcfffaf167a9f5adcfd76 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 08:47:30 +0000 Subject: [PATCH 1294/1514] dt-bindings: soc: apple,cluster-pwrgate: add T6041 T6041 has the per-core PMGR power-gate enable page at 0x50282c000 where the boot loader leaves the boot core's word clear, preventing it and its cluster from power-gating in WFI. Add the T6041 compatible and note T6041 and T8142 in the binding description. Signed-off-by: AxxzyWasTaken --- .../bindings/soc/apple/apple,cluster-pwrgate.yaml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml b/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml index 43539cc51a6a37..9c48556c7d68d3 100644 --- a/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml +++ b/Documentation/devicetree/bindings/soc/apple/apple,cluster-pwrgate.yaml @@ -11,15 +11,16 @@ maintainers: description: | PMGR words whose top bit lets a CPU power down in WFI: one per cluster on - T8132 and T8140, one per core on T6050. A core that PMGR powers on comes up - allowed to, but the boot CPU was started by the boot ROM and only follows its - word, which the boot loader may leave clear. The words are set early in boot, - in the order listed. + T8132, T8140 and T8142, one per core on T6041 and T6050. A core that PMGR + powers on comes up allowed to, but the boot CPU was started by the boot ROM + and only follows its word, which the boot loader may leave clear. The words + are set early in boot, in the order listed. properties: compatible: items: - enum: + - apple,t6041-cluster-pwrgate - apple,t6050-cluster-pwrgate - apple,t8132-cluster-pwrgate - apple,t8140-cluster-pwrgate From b7c843bc90a21711f783a7734d490923621d2759 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 08:47:30 +0000 Subject: [PATCH 1295/1514] arm64: dts: apple: t6041: add CPU cluster power-gate enables Add the cluster_pwrgate node to t6041.dtsi for the E core 0 (0x50282c000) and P0 core 0 / boot core (0x50282c040) power-gate enable words, matching the two wake gates restored by t6041-sleep. Setting bit 31 early in boot lets the boot core and P0 cluster power-gate in WFI without depending on the boot loader. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6041.dtsi | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index a4dfb2d600c9f8..1d280a55ad4082 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -494,6 +494,19 @@ #size-cells = <1>; }; + /* + * The CPU power-gate enables, in /arm-io/pmgr at 0x50282c000, one word + * per core: E core 0 at +0x0 and P0 core 0 (the boot core) at +0x40, + * matching the two wake gates t6041-sleep restores on resume. iBoot + * leaves the boot core's word clear, so P0 never powers down in WFI + * unless set early in boot. + */ + cluster_pwrgate: power-gate@50282c000 { + compatible = "apple,t6041-cluster-pwrgate", "apple,cluster-pwrgate"; + reg = <0x5 0x0282c000 0x0 0x4>, + <0x5 0x0282c040 0x0 0x4>; + }; + /* * Suspend-to-RAM at EL2 through aura's S2R mailbox; without the mailbox * it stays out. Stays disabled at the SoC level so boards without From fba4ec5680bfb4f95a3f84adf57538f9d9a97e4d Mon Sep 17 00:00:00 2001 From: Jos Dehaes Date: Tue, 17 Nov 2026 11:11:18 +0100 Subject: [PATCH 1296/1514] PCI: apple: put a function back in D0 before restoring it after S2R After a real sleep the host trains a conventional port again in its own resume, but the PCI core's noirq power-up of the functions behind it ran earlier, with the link still down ("Unable to change power state from D3hot to D0, device inaccessible"), and left current_state at D3hot. The GL9755 SD reader's resume then frees and allocates its MSI vector, which the MSI core refuses for a device that is not in D0: "enable PCI MSI failed, error=-22", and from then on every command times out. On the J614c the dead reader also blocks the next suspend (its command timeouts keep a freezable workqueue busy, "Device or resource busy") and hangs the kernel's final reboot step until the hardware watchdog resets the machine. The port reset brought the function up in D0: record that with pci_set_power_state() before its saved state is loaded back. Signed-off-by: Jos Dehaes --- drivers/pci/controller/pcie-apple.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 824b94d04caa7a..322d3c7e02db3c 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -7918,6 +7918,12 @@ static int apple_pcie_resume(struct device *dev) port = apple_pcie_get_port(fn->pdev); if (!port || !port->hib_cold) continue; + /* + * The PCI core's noirq power-up ran with the link down and left the function + * marked D3: the reset brought it up in D0, so record that before the + * restore, or its driver's resume can't enable MSI again (-EINVAL). + */ + pci_set_power_state(fn->pdev, PCI_D0); if (pci_load_saved_state(fn->pdev, fn->state)) pci_warn(fn->pdev, "S2R: saved configuration not taken back\n"); else From 030b3844c926fad13af1876fc70228455b1228d4 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:06:00 -0500 Subject: [PATCH 1297/1514] drm/apple: require a bootloader handoff for generic v27 DCP adoption Firmware 27 and a panel child describe the interface and port layout. They can also be present on a cold DCP. Inferring a running session from either makes the driver refuse to start that processor. Keep the RTKit session handoff check. For firmware 27, also accept the single-cell marker that the bootloader sets to 1 on an internal DCP after validating the running processor and its DARTs. Select the marker from the DCP match data. This lets the J516s keep its iBoot display without implying that the bootloader already negotiated RTKit. Derive DMA width and panel port count independently. Exercise marked and cold probes across the four internal profiles, including zero and foreign markers. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp.c | 64 ++++++------- .../selftests/drivers/gpu/apple-dcp/boot.py | 92 +++++++++++++++++++ .../selftests/drivers/gpu/apple-dcp/run.py | 1 + 4 files changed, 124 insertions(+), 35 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index cb77aa8eabd5a1..24dbe1812727e1 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -322,6 +322,8 @@ struct apple_dcp_hw_data { * standard RTKit wake instead of starting or restarting the ASC. */ bool adopt_live_session; + /* Bootloader property marking this DCP as running under iBoot. */ + const char *iboot_handoff; enum dcp_firmware_version firmware_compat; /* Firmware-visible clock aperture, independent of the AP PMGR window. */ const struct resource *firmware_clock; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 0db75e9b222172..fa6a9f824ce9d1 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -6585,6 +6585,30 @@ static u8 dcp_dart_dma_bits(struct device_node *np) return clamp_t(u8, fls64(end), 32, 48); } +static void dcp_apply_dt_profile(struct apple_dcp *dcp) +{ + struct device_node *np = dcp->dev->of_node; + u32 running; + + if (of_property_present(np, "apple,rtkit-handoff")) + dcp->hw.adopt_live_session = true; + + if (dcp->fw_compat != DCP_FIRMWARE_V_27_0) + return; + + /* iBoot can leave the ASC running without negotiating RTKit. */ + if (dcp->hw.iboot_handoff && + of_property_read_variable_u32_array(np, dcp->hw.iboot_handoff, + &running, 1, 1) == 1 && + running == 1) + dcp->hw.adopt_live_session = true; + + if (!dcp->hw.firmware_dma_bits) + dcp->hw.firmware_dma_bits = dcp_dart_dma_bits(np); + if (dcp_is_internal_panel_only(dcp)) + dcp->hw.num_dptx_ports = 0; +} + /* * The provider clocks firmware 27 asks for by index (getClockFrequency): * apple,clock-ids, published by the boot loader from the ADT. @@ -8091,9 +8115,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (ret) return ret; dcp->hw = *(struct apple_dcp_hw_data *)of_device_get_match_data(dev); - /* A boot stage handed this DCP over running: keep its session. */ - if (of_property_present(dev->of_node, "apple,rtkit-handoff")) - dcp->hw.adopt_live_session = true; + dcp_apply_dt_profile(dcp); /* The link report: on the board it has run on (dcp_j714s_ext()). */ if (!dcp_j714s_ext(dev)) dcp->hw.link_report = false; @@ -8104,38 +8126,6 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) if (fw_compat == DCP_FIRMWARE_V_27_0 && of_device_is_compatible(dev->of_node, "apple,t8142-dcp")) dcp->hw.iomfb_method_profile = DCP_IOMFB_METHODS_DEFAULT; - /* - * Every processor on firmware 27 inherits the live session the boot - * loader handed over. Its match data keeps the per-SoC port count, - * tunnel-flow flag and DART resources; only the session adoption follows - * the firmware. The per-SoC firmware-27 profiles below come after it and - * may override it: the T8122 dcpext, which the loader leaves unpowered, - * does not adopt. (The T8140 dcpext, whose match data does not adopt, is - * refused above on anything but 26.6.2.) - */ - if (fw_compat == DCP_FIRMWARE_V_27_0) { - dcp->hw.adopt_live_session = true; - /* - * Derive firmware DMA width from the DCP DART aperture when - * match data does not already pin a hardware profile width. - */ - if (!dcp->hw.firmware_dma_bits) { - u8 dma_bits = dcp_dart_dma_bits(dev->of_node); - - if (dma_bits) - dcp->hw.firmware_dma_bits = dma_bits; - } - } - /* - * Internal laptop panels on firmware 27 (an internal DCP with a panel - * child and no external DPTX/Type-C routes): the boot loader hands the - * panel over running and it has no DP port. - */ - if (fw_compat == DCP_FIRMWARE_V_27_0 && - dcp_is_internal_panel_only(dcp)) { - dcp->hw.num_dptx_ports = 0; - dcp->hw.adopt_live_session = true; - } /* * The T8122 external processor on firmware 27: the boot loader leaves * it unpowered (its DISPEXT domains are off at handoff), so Linux @@ -10981,15 +10971,18 @@ static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { }; static const struct apple_dcp_hw_data apple_dcp_hw_t6030 = { + .iboot_handoff = "apple,t6030-handoff", .num_dptx_ports = 1, }; static const struct apple_dcp_hw_data apple_dcp_hw_t8122 = { + .iboot_handoff = "apple,t8122-handoff", .num_dptx_ports = 2, }; /* The internal panel only, through the 14.x IOMFB, as on T6030. */ static const struct apple_dcp_hw_data apple_dcp_hw_t6031 = { + .iboot_handoff = "apple,t6031-handoff", .num_dptx_ports = 1, }; @@ -11022,6 +11015,7 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8132_dcpext = { /* T6041 (M4 Pro/Max), desktop 26.6 firmware */ static const struct apple_dcp_hw_data apple_dcp_hw_t6041 = { + .iboot_handoff = "apple,t6041-handoff", .num_dptx_ports = 2, }; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index e6ff1f887d88d2..74a7a11da1940e 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -353,6 +353,98 @@ def _v27_prelude(root): ''' + helper + '\n' + methods_decl + '\n' + v27_tables + '\n' + selector + '\n' +def v27_panel_handoff(root): + source = (root / 'drivers/gpu/drm/apple/dcp.c').read_text() + profiles = ('t6030', 't8122', 't6031', 't6041') + match = '\n'.join(block(source, f'static const struct apple_dcp_hw_data apple_dcp_hw_{soc} =') + + ';' for soc in profiles) + profile = block(source, 'static void dcp_apply_dt_profile(') + return r''' +#include +#include +#include +#include +typedef uint8_t u8; +typedef uint32_t u32; +enum { DCP_FIRMWARE_V_27_0 = 27 }; +struct device_node { + bool rtkit_handoff; + const char *marker; + u32 value; +}; +struct device { struct device_node *of_node; }; +struct apple_dcp_hw_data { + bool adopt_live_session; + const char *iboot_handoff; + unsigned num_dptx_ports; + u8 firmware_dma_bits; +}; +struct apple_dcp { + struct device *dev; + struct apple_dcp_hw_data hw; + int fw_compat; +}; +static bool of_property_present(struct device_node *np, const char *name) +{ + assert(!strcmp(name, "apple,rtkit-handoff")); + return np->rtkit_handoff; +} +static int of_property_read_variable_u32_array(struct device_node *np, const char *name, + u32 *value, int min, int max) +{ + assert(min == 1 && max == 1); + if (!np->marker || strcmp(name, np->marker)) + return -1; + *value = np->value; + return 1; +} +/* All probes see the same DART aperture and panel-only topology. */ +static u8 dcp_dart_dma_bits(struct device_node *np) { return 41; } +static bool dcp_is_internal_panel_only(struct apple_dcp *dcp) { return true; } +''' + match + '\n' + profile + r''' +static void check(struct apple_dcp_hw_data hw, struct device_node node, bool live) +{ + struct device dev = { .of_node = &node }; + struct apple_dcp dcp = { .dev = &dev, .hw = hw, .fw_compat = DCP_FIRMWARE_V_27_0 }; + + dcp_apply_dt_profile(&dcp); + assert(dcp.hw.adopt_live_session == live); + assert(dcp.hw.firmware_dma_bits == 41); + assert(dcp.hw.num_dptx_ports == 0); +} + +int main(void) +{ + const struct { + const struct apple_dcp_hw_data *hw; + const char *marker; + } panels[] = { + { &apple_dcp_hw_t6030, "apple,t6030-handoff" }, + { &apple_dcp_hw_t8122, "apple,t8122-handoff" }, + { &apple_dcp_hw_t6031, "apple,t6031-handoff" }, + { &apple_dcp_hw_t6041, "apple,t6041-handoff" }, + }; + + for (unsigned i = 0; i < sizeof(panels) / sizeof(panels[0]); i++) { + struct apple_dcp_hw_data hw = *panels[i].hw; + struct device_node node = {}; + + check(hw, node, false); + node.rtkit_handoff = true; + check(hw, node, true); + node.rtkit_handoff = false; + node.marker = panels[i].marker; + check(hw, node, false); + node.value = 1; + check(hw, node, true); + node.marker = panels[i ? 0 : 1].marker; + check(hw, node, false); + } + return 0; +} +''' + + def t6041_v27_admission(root): return _v27_prelude(root) + r''' static struct device_node node; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py index 7dd5ba9affd9b4..2d111c5bed9647 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/run.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/run.py @@ -92,6 +92,7 @@ def main(): ('m4', 'm4-panel-timing', m4.timing, ((),), ('-Wno-unused-function', '-Wno-unused-const-variable')), ('boot', 'oslog-events', boot.oslog, ((),), ()), ('boot', 'syslog-policy', boot.syslog, ((),), ()), + ('boot', 'v27-panel-handoff', boot.v27_panel_handoff, ((),), ()), ('boot', 't6041-v27-admission', boot.t6041_v27_admission, ((),), ()), ('boot', 't8122-dcpext-v27-admission', boot.t8122_dcpext_v27_admission, ((),), ()), ('boot', 'v27-tag-translation', boot.v27_tag_translation, ((),), ()), From 4becf74298599d4e210b91bc19074f5333f362c0 Mon Sep 17 00:00:00 2001 From: Jos Dehaes Date: Wed, 25 Nov 2026 09:37:29 +0100 Subject: [PATCH 1298/1514] drm/apple: T6041 S2R: no second power-off for a display DPMS already turned off A lid close blanks the internal panel before the sleep: the desktop's DPMS off runs set_power_state(0) on the internal DCP, and its D572(0) comes then, while s2r_active is clear. The S2R display stop then sent a second set_power_state(0), which gets no D572, and failed the suspend: apple-dcp 402e00000.dcp: no D572 after the power-off apple-drm display-subsystem: PM: failed to suspend: error -110 so on the J614c every lid sleep was refused, and systemd retried every 30 s while the lid stayed closed. rtcwake with the panel lit was not affected. Remember that the firmware confirmed the scanout stop of a power-off (pipe_off), until the next power-on starts. When the S2R stop finds the pipe already off, skip the second power-off and its D572 wait, and turn the display DART's streams off as that D572(0) would have. If the stop fails later, the unwind turns them on again. Fixes: 4af660c74e44 ("drm/apple: T6041 S2R display stop and warm restart") Signed-off-by: Jos Dehaes --- drivers/gpu/drm/apple/dcp-internal.h | 5 ++++ drivers/gpu/drm/apple/dcp.c | 41 +++++++++++++++++++------- drivers/gpu/drm/apple/iomfb_template.c | 7 +++-- 3 files changed, 40 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index cb77aa8eabd5a1..c141dea63e21e3 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -928,6 +928,11 @@ struct apple_dcp { bool s2r_stopped; /* DPMS off stopped the firmware and lowered the domains; DPMS on brings them back. */ bool dpms_powered_off; + /* + * The firmware confirmed the scanout stop of a set_power_state(0) and no power-on has + * started since: its D572(0) has come and gone, and a second set_power_state(0) gets none. + */ + bool pipe_off; /* Refused its idle with the display off: the firmware still runs, the display is dark. */ bool s2r_refused_off; /* The firmware's secure mailbox, where it has one. */ diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4e48c4574624f2..df54c7d1246073 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -11041,6 +11041,8 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) struct task_struct *poller; bool keep_set = false; bool powered_off = false; + /* The display DART's streams turned off here, not by a D572(0). */ + bool streams_off = false; bool idle_attempted = false; bool idle; u32 ctrl, status; @@ -11094,18 +11096,35 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * (axi_rd_err, 11 Nov). Without D572(0) abort sleep instead of tearing down domains * while scanning out. */ - reinit_completion(&dcp->s2r_dart_done); - WRITE_ONCE(dcp->s2r_active, true); - _dcp_poweroff(dcp); - powered_off = true; - if (!wait_for_completion_timeout(&dcp->s2r_dart_done, - msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) { + /* + * A DPMS off before the sleep (the desktop blanking on a lid close) already ran + * set_power_state(0), and its scanout stop was confirmed: its D572(0) came then, + * while s2r_active was clear, and a second set_power_state(0) gets none. Turn the + * display DART's streams off as that D572(0) would have; the pipe no longer scans + * out. + */ + if (READ_ONCE(dcp->pipe_off)) { + dev_info(dev, "display already off: no second power-off\n"); + if (dcp->s2r_disp_dart) { + apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, false, false); + streams_off = true; + } + } else { + unsigned long d572 = msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS); + + reinit_completion(&dcp->s2r_dart_done); + WRITE_ONCE(dcp->s2r_active, true); + _dcp_poweroff(dcp); + powered_off = true; + if (!wait_for_completion_timeout(&dcp->s2r_dart_done, d572)) { + WRITE_ONCE(dcp->s2r_active, false); + dev_err(dev, "no D572 after the power-off\n"); + ret = -ETIMEDOUT; + goto err_unwind; + } WRITE_ONCE(dcp->s2r_active, false); - dev_err(dev, "no D572 after the power-off\n"); - ret = -ETIMEDOUT; - goto err_unwind; } - WRITE_ONCE(dcp->s2r_active, false); if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { dev_err(dev, "display calls still in flight after the power-off\n"); ret = -ETIMEDOUT; @@ -11205,7 +11224,7 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, false); } - if (powered_off && dcp->s2r_disp_dart) + if ((powered_off || streams_off) && dcp->s2r_disp_dart) apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true, false); } diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 88c303630aae00..7fa70dc175ff61 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -2573,6 +2573,7 @@ void DCP_FW_NAME(iomfb_poweron)(struct apple_dcp *dcp) u32 handle; #endif dev_info(dcp->dev, "dcp_poweron() starting\n"); + WRITE_ONCE(dcp->pipe_off, false); #if DCP_FW_H17(DCP_FW_VER) if (dcp_is_ext26(dcp)) return; /* Native26 publishes A473 only after a successful A413. */ @@ -3004,10 +3005,12 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) dev_dbg(dcp->dev, "setPowerState(0) finished with %d ms to spare", jiffies_to_msecs(ret)); - if (dcp_power_stop_confirmed(poff_cookie)) + if (dcp_power_stop_confirmed(poff_cookie)) { dcp_release_all_retained_framebuffers(dcp); - else + WRITE_ONCE(dcp->pipe_off, true); + } else { dev_warn(dcp->dev, "scanout stop was not confirmed\n"); + } } kref_put(&poff_cookie->refcount, release_wait_cookie); From 79bbbb3580ec08d4aae044f028754fa1460a86c6 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 04:13:44 -0500 Subject: [PATCH 1299/1514] usb: dwc3: apple: defer host USB3 PHY routing until xHCI reset completes dwc3_apple_set_role() currently enables SUSPHY and calls phy_set_mode(usb3_phy, PHY_MODE_USB_HOST) before dwc3_host_init(). Routing the PIPE mux from the dummy producer to the live USB3 PHY before xhci_plat_probe() runs allows the SuperSpeed link to start Rx.Detect / Polling.LFPS immediately, and xhci_reset() (USBCMD.HCRST) then hits milliseconds later in the middle of that handshake. With a quiet console (dmesg -n 5), HCRST lands inside the partner's initial LFPS window often enough to leave downstream SuperSpeed hubs (such as the Dell S2725QC's 0bda:0409 hub on DP alt mode) wedged with PORTSC stuck at 0x0a0002b0 (PR=1, PLS=Rx.Detect) and no receiver termination, triggering a Type-C DISC replug that drops DP HPD and restarts the external display. Even on wakes that survive HCRST, link training stalls ~100 ms before retrying Polling instead of completing on the first handshake. Leave host-mode USB3 PHY routing to xHCI's shared SuperSpeed root hub (usb_add_hcd() on xhci->shared_hcd), mirroring how USB2 host mode is already left to the primary root hub. Keep SUSPHY clear while usb_add_hcd(primary) executes xhci_reset() on the dummy PIPE producer; dwc3_xhci_plat_start() enables SUSPHY once HCRST completes and before usb_add_hcd(shared) calls phy_set_mode(usb3_phy, PHY_MODE_USB_HOST) and xhci_run() starts the controller. Add a post_usb3_host_start glue hook in dwc3_xhci_plat_start() so controllers that must keep their USB3 PHY out of P3 (T8132/T8142) still disable U3 SUSPHY right after the shared HCD finishes routing the PIPE, including when xhci-plat is loaded as a module. Preserve pre-xHCI routing for gadget mode and for T6040, which pulses GUSB3PIPECTL.PHYSOFTRST before xHCI starts. Extend dwc3-apple-state-test and atc-t8132-usb3 (with a negative control) to cover the deferred host USB3 routing policy. Signed-off-by: Diljit Singh --- drivers/usb/dwc3/core.h | 3 + drivers/usb/dwc3/dwc3-apple-state-test.c | 35 +++++++++ drivers/usb/dwc3/dwc3-apple-state.h | 33 ++++++++ drivers/usb/dwc3/dwc3-apple.c | 72 +++++++++++++----- drivers/usb/dwc3/host.c | 12 +-- .../selftests/drivers/apple/atc-t8132-usb3.py | 76 ++++++++++++++----- 6 files changed, 186 insertions(+), 45 deletions(-) diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index 7821ccb4686e53..18726d8d4a8c74 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -1004,11 +1004,14 @@ struct dwc3_scratchpad_array { * @pre_run_stop: Notify run stop enable/disable information to glue * @pre_host_resume: Before xHCI touches the core at a system resume; an error keeps it away, * and a positive value says the core lost its state and was set up again + * @post_usb3_host_start: After xHCI's SuperSpeed root hub has configured the USB3 PHY, + * before xhci_run() starts the host controller */ struct dwc3_glue_ops { void (*pre_set_role)(struct dwc3 *dwc, enum usb_role role); void (*pre_run_stop)(struct dwc3 *dwc, bool is_on); int (*pre_host_resume)(struct dwc3 *dwc); + void (*post_usb3_host_start)(struct dwc3 *dwc); }; /** diff --git a/drivers/usb/dwc3/dwc3-apple-state-test.c b/drivers/usb/dwc3/dwc3-apple-state-test.c index 69abb0f32653ff..db43ac587ebdef 100644 --- a/drivers/usb/dwc3/dwc3-apple-state-test.c +++ b/drivers/usb/dwc3/dwc3-apple-state-test.c @@ -46,11 +46,46 @@ static void dwc3_apple_role_during_sleep_test(struct kunit *test) KUNIT_EXPECT_EQ(test, dwc3_apple_state_for_role(USB_ROLE_NONE), DWC3_APPLE_NO_CABLE); } +/* Host mode leaves USB3 PHY routing to xHCI's shared root hub unless a pre-xHCI reset runs. */ +static void dwc3_apple_usb3_host_left_to_xhci_test(struct kunit *test) +{ + enum phy_mode mode = PHY_MODE_USB_HOST; + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_HOST, false, &mode), 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_INVALID); + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_HOST, true, &mode), 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_USB_HOST); +} + +/* Device mode routes the USB3 PHY before gadget init; non-roles are rejected. */ +static void dwc3_apple_usb3_device_and_non_role_test(struct kunit *test) +{ + static const enum dwc3_apple_state states[] = { + DWC3_APPLE_PROBE_PENDING, DWC3_APPLE_NO_CABLE, + }; + enum phy_mode mode = PHY_MODE_INVALID; + int i; + + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(DWC3_APPLE_DEVICE, false, &mode), + 0); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_USB_DEVICE); + + for (i = 0; i < ARRAY_SIZE(states); i++) { + mode = PHY_MODE_USB_HOST; + KUNIT_EXPECT_EQ(test, dwc3_apple_usb3_mode_before_start(states[i], false, &mode), + -EINVAL); + KUNIT_EXPECT_EQ(test, mode, PHY_MODE_INVALID); + } +} + static struct kunit_case dwc3_apple_state_test_cases[] = { KUNIT_CASE(dwc3_apple_host_left_to_xhci_test), KUNIT_CASE(dwc3_apple_device_selected_before_reset_test), KUNIT_CASE(dwc3_apple_non_role_test), KUNIT_CASE(dwc3_apple_role_during_sleep_test), + KUNIT_CASE(dwc3_apple_usb3_host_left_to_xhci_test), + KUNIT_CASE(dwc3_apple_usb3_device_and_non_role_test), {} }; diff --git a/drivers/usb/dwc3/dwc3-apple-state.h b/drivers/usb/dwc3/dwc3-apple-state.h index bb8d827fdec4c5..bdaf181907fea4 100644 --- a/drivers/usb/dwc3/dwc3-apple-state.h +++ b/drivers/usb/dwc3/dwc3-apple-state.h @@ -48,6 +48,39 @@ static inline int dwc3_apple_usb2_mode_before_reset(enum dwc3_apple_state target } } +/** + * dwc3_apple_usb3_mode_before_start() - USB3 PHY mode to select before xHCI or gadget starts + * @target: the state the controller is brought up in + * @pipe_reset_before_host: true if the controller pulses PHYSOFTRST before xHCI starts + * @mode: set to the mode to select, or to PHY_MODE_INVALID to leave host routing to xHCI + * + * Device mode has no xHCI root hub to select it later, so it routes the USB3 PHY before + * dwc3_gadget_init(). Host mode leaves USB3 PHY routing to xHCI's SuperSpeed root hub + * (usb_add_hcd() on the shared HCD), which runs after xhci_reset() (USBCMD.HCRST) has + * completed on the dummy PIPE producer and dwc3_xhci_plat_start() has enabled SUSPHY. + * Routing the live USB3 PHY before dwc3_host_init() exposes an ongoing SuperSpeed link + * handshake to HCRST and can leave a partner hub stuck in Rx.Detect. Controllers that must + * pulse GUSB3PIPECTL.PHYSOFTRST before xHCI starts still route the PHY beforehand. + * + * Return: 0, or -EINVAL if @target is not DWC3_APPLE_HOST or DWC3_APPLE_DEVICE. + */ +static inline int dwc3_apple_usb3_mode_before_start(enum dwc3_apple_state target, + bool pipe_reset_before_host, + enum phy_mode *mode) +{ + switch (target) { + case DWC3_APPLE_HOST: + *mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID; + return 0; + case DWC3_APPLE_DEVICE: + *mode = PHY_MODE_USB_DEVICE; + return 0; + default: + *mode = PHY_MODE_INVALID; + return -EINVAL; + } +} + /** * dwc3_apple_state_for_role() - state a role asks for while the core is stopped for sleep * @role: the role asked for diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index b822637b83f3f6..fc409f7781cbf1 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -651,8 +651,28 @@ static int dwc3_apple_pre_host_resume(struct dwc3 *dwc) return ret; } +static void dwc3_apple_post_usb3_host_start(struct dwc3 *dwc) +{ + struct dwc3_apple *appledwc = to_dwc3_apple(dwc); + + if (!appledwc->usb3_phy) + return; + + /* + * These PHYs do not bring a SuperSpeed link back from U3 once + * the core has suspended them: keep them out of P3 from here on, + * once xHCI's shared HCD has finished routing the USB3 PIPE. + */ + if (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || + of_device_is_compatible(appledwc->dev->of_node, "apple,t8142-dwc3")) { + dwc->dis_u3_susphy_quirk = true; + dwc3_enable_susphy(dwc, true); + } +} + static const struct dwc3_glue_ops dwc3_apple_glue_ops = { .pre_host_resume = dwc3_apple_pre_host_resume, + .post_usb3_host_start = dwc3_apple_post_usb3_host_start, }; static bool dwc3_apple_host_before_core_init(struct dwc3_apple *appledwc, @@ -945,30 +965,50 @@ static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *appledwc) msleep(100); } -/* Select the role in the core and route the USB3 PHY, before xhci or the gadget is started */ +/* + * Select the role in the core and route the USB3 PHY when it is not left to + * xHCI's shared SuperSpeed root hub. + */ static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_state state) { bool host = state == DWC3_APPLE_HOST; + bool pipe_reset = host && appledwc->usb3_phy && + of_device_is_compatible(appledwc->dev->of_node, "apple,t6040-dwc3"); + enum phy_mode mode; int ret; lockdep_assert_held(&appledwc->lock); + ret = dwc3_apple_usb3_mode_before_start(state, pipe_reset, &mode); + if (ret) + return ret; + appledwc->dwc.dr_mode = host ? USB_DR_MODE_HOST : USB_DR_MODE_PERIPHERAL; dwc3_apple_set_ptrcap(appledwc, host ? DWC3_GCTL_PRTCAP_HOST : DWC3_GCTL_PRTCAP_DEVICE); + appledwc->dwc.dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; + if (mode == PHY_MODE_INVALID) { + /* + * Keep SUSPHY clear through xHCI's HCRST on the dummy PIPE; + * dwc3_xhci_plat_start() enables SUSPHY after HCRST completes, + * before the shared HCD routes the USB3 PHY. + */ + dwc3_enable_susphy(&appledwc->dwc, false); + return 0; + } + /* - * This platform requires SUSPHY to be enabled here already in order to properly - * configure the PHY and switch dwc3's PIPE interface to USB3 PHY. The USB2 PHY's - * device mode and the T8132 host role were selected in dwc3_apple_core_start(); - * other host roles are selected by the xHCI root hub as it starts. + * Device mode and T6040 (which pulses PHYSOFTRST before xHCI starts) + * need SUSPHY enabled here so the PHY can lock and switch the PIPE + * handler before starting the gadget or host. */ - appledwc->dwc.dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; dwc3_enable_susphy(&appledwc->dwc, true); - ret = phy_set_mode(appledwc->usb3_phy, host ? PHY_MODE_USB_HOST : PHY_MODE_USB_DEVICE); + ret = phy_set_mode(appledwc->usb3_phy, mode); if (ret) { /* - * A failed T8132 BIST or PIPE handoff must not start xHCI. Neither must a failed - * T6050 one: that PHY reports a port left on USB2 (four DisplayPort lanes) as - * success, and its errors leave the PIPE without a known producer. + * A failed T8132 BIST or PIPE handoff must not start gadget mode. + * Neither must a failed T6050 one: that PHY reports a port left on + * USB2 (four DisplayPort lanes) as success, and its errors leave + * the PIPE without a known producer. */ if (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || of_device_is_compatible(appledwc->dev->of_node, "apple,t6050-dwc3")) { @@ -976,17 +1016,7 @@ static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_stat return ret; } dev_warn(appledwc->dev, "USB3 PHY setup failed, USB2 only, err=%d\n", ret); - } else if (host && appledwc->usb3_phy && - (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || - of_device_is_compatible(appledwc->dev->of_node, "apple,t8142-dwc3"))) { - /* - * These PHYs do not bring a SuperSpeed link back from U3 once - * the core has suspended them: keep them out of P3 from here on. - */ - appledwc->dwc.dis_u3_susphy_quirk = true; - dwc3_enable_susphy(&appledwc->dwc, true); - } else if (appledwc->usb3_phy && - of_device_is_compatible(appledwc->dev->of_node, "apple,t6040-dwc3")) { + } else if (pipe_reset) { dwc3_apple_usb3_pipe_reset(appledwc); } return 0; diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index 652942d3f6f4f9..df8cff0b704546 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -67,14 +67,14 @@ static void dwc3_power_off_all_roothub_ports(struct dwc3 *dwc) static void dwc3_xhci_plat_start(struct usb_hcd *hcd) { - struct platform_device *pdev; - struct dwc3 *dwc; + struct platform_device *pdev = to_platform_device(hcd->self.controller); + struct dwc3 *dwc = dev_get_drvdata(pdev->dev.parent); - if (!usb_hcd_is_primary_hcd(hcd)) + if (!usb_hcd_is_primary_hcd(hcd)) { + if (dwc->glue_ops && dwc->glue_ops->post_usb3_host_start) + dwc->glue_ops->post_usb3_host_start(dwc); return; - - pdev = to_platform_device(hcd->self.controller); - dwc = dev_get_drvdata(pdev->dev.parent); + } dwc3_enable_susphy(dwc, true); } diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index 8adcbb6159799a..8abaae8d46a4dc 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -367,6 +367,7 @@ def main(): role_program = r''' #include #include +#include #include #include #include @@ -378,50 +379,89 @@ def main(): #define USB_DR_MODE_PERIPHERAL 2 #define DWC3_GCTL_PRTCAP_HOST 1 #define DWC3_GCTL_PRTCAP_DEVICE 2 -enum phy_mode { PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE }; +#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) +enum phy_mode { PHY_MODE_INVALID, PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE }; struct device { const char *of_node; }; struct dwc3 { int dr_mode, current_dr_role; bool dis_u3_susphy_quirk; }; struct dwc3_apple { struct dwc3 dwc; struct device *dev; void *usb2_phy, *usb3_phy; int lock, state; bool dt_dis_u3_susphy, host_only, sleep_ddr; }; -static int phy_error, host_calls, gadget_calls, stops, syscore; +#define to_dwc3_apple(d) container_of((d), struct dwc3_apple, dwc) +static int phy_error, phy_calls, pre_host_phy_calls, host_calls, gadget_calls, stops, syscore, pipe_resets; +static bool susphy_on; static bool of_device_is_compatible(const char *node, const char *name) { return !strcmp(node,name); } -static int phy_set_mode(void *phy, int mode) { (void)phy; (void)mode; return phy_error; } +static int phy_set_mode(void *phy, int mode) { + (void)phy; (void)mode; + assert(susphy_on); + phy_calls++; + return phy_error; +} static void dwc3_apple_set_ptrcap(struct dwc3_apple *a, int cap) { (void)a; (void)cap; } -static void dwc3_enable_susphy(struct dwc3 *d, bool on) { (void)d; assert(on); } -static int dwc3_host_init(struct dwc3 *d) { (void)d; host_calls++; return 0; } +static void dwc3_enable_susphy(struct dwc3 *d, bool on) { susphy_on = on && !d->dis_u3_susphy_quirk; } static int dwc3_gadget_init(struct dwc3 *d) { (void)d; gadget_calls++; return 0; } static int phy_reset(void *phy) { (void)phy; return 0; } static void dwc3_host_exit(struct dwc3 *d) { (void)d; assert(0); } static void apple_sleep_usb_slp_ddr(bool on) { (void)on; assert(0); } -static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; assert(0); } -''' + enum(states, "dwc3_apple_state") + r''' +static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; pipe_resets++; } +''' + enum(states, "dwc3_apple_state") + function(states, "dwc3_apple_usb3_mode_before_start") + r''' static int dwc3_apple_core_start(struct dwc3_apple *a, enum dwc3_apple_state s) { (void)a; (void)s; return 0; } static int dwc3_apple_core_stop(struct dwc3_apple *a) { (void)a; stops++; return 0; } static void dwc3_apple_syscore(struct dwc3_apple *a, bool on) { (void)a; assert(on); syscore++; } +''' + function(dwc, "dwc3_apple_post_usb3_host_start") + r''' +/* Model xhci_plat_probe(): HCRST on dummy PIPE, primary plat_start enables SUSPHY, shared HCD routes USB3. */ +static int dwc3_host_init(struct dwc3 *d) +{ + struct dwc3_apple *a = to_dwc3_apple(d); + int ret; + + pre_host_phy_calls = phy_calls; + host_calls++; + if (!of_device_is_compatible(a->dev->of_node, "apple,t6040-dwc3")) { + assert(!susphy_on); + assert(!phy_calls); + } + dwc3_enable_susphy(d, true); + if (a->usb3_phy && !phy_calls) { + ret = phy_set_mode(a->usb3_phy, PHY_MODE_USB_HOST); + if (ret) + return ret; + } + dwc3_apple_post_usb3_host_start(d); + return 0; +} ''' + function(dwc, "dwc3_apple_set_role") + function(dwc, "dwc3_apple_init") + r''' int main(void) { struct device dev = { "apple,t8132-dwc3" }; struct dwc3_apple a = { .dev=&dev, .usb3_phy=&dev, .state=DWC3_APPLE_NO_CABLE }; - phy_error=-ETIMEDOUT; + phy_error=-ETIMEDOUT; phy_calls=0; assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ETIMEDOUT); - assert(!host_calls && !gadget_calls && stops==1 && a.state==DWC3_APPLE_NO_CABLE); - phy_error=-EOPNOTSUPP; + assert(host_calls==1 && !pre_host_phy_calls && phy_calls==1 && !gadget_calls && stops==1 && a.state==DWC3_APPLE_NO_CABLE); + phy_error=-EOPNOTSUPP; phy_calls=0; assert(dwc3_apple_init(&a,DWC3_APPLE_DEVICE)==-EOPNOTSUPP); - assert(!gadget_calls && stops==2); - phy_error=0; + assert(!gadget_calls && stops==2 && phy_calls==1); + phy_error=0; phy_calls=0; assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST)); - assert(host_calls==1 && a.state==DWC3_APPLE_HOST && syscore==1); - /* A T8132 host keeps its USB3 PHY out of P3. */ - assert(a.dwc.dis_u3_susphy_quirk); - dev.of_node="apple,t8103-dwc3"; phy_error=-ETIMEDOUT; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==2 && syscore==2); + assert(host_calls==2 && !pre_host_phy_calls && phy_calls==1 && a.state==DWC3_APPLE_HOST && syscore==1); + /* A T8132 host keeps its USB3 PHY out of P3 once shared HCD routing completes. */ + assert(a.dwc.dis_u3_susphy_quirk && !susphy_on); + dev.of_node="apple,t6050-dwc3"; phy_error=0; phy_calls=0; + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==3 && !pre_host_phy_calls && phy_calls==1 && syscore==2); + assert(!a.dwc.dis_u3_susphy_quirk && susphy_on); + dev.of_node="apple,t6040-dwc3"; phy_error=0; phy_calls=0; + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==4 && pre_host_phy_calls==1 && pipe_resets==1 && syscore==3); + dev.of_node="apple,t8103-dwc3"; phy_error=-ETIMEDOUT; phy_calls=0; + assert(!dwc3_apple_init(&a,DWC3_APPLE_DEVICE) && gadget_calls==1 && syscore==4); assert(!a.dwc.dis_u3_susphy_quirk); - puts("ok 7 - T8132 PHY failures stop before xHCI, older fallback preserved"); + puts("ok 7 - USB3 host routing deferred past HCRST, T8132/T6050/T6040/device policies preserved"); return 0; } ''' run(Path(directory), "dwc3-t8132", role_program) + early_usb3 = role_program.replace( + "*mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID;", + "*mode = PHY_MODE_USB_HOST;", 1) + assert early_usb3 != role_program + run(Path(directory), "dwc3-usb3-before-host-negative-control", early_usb3, expect_failure=True) permissive = program.replace( "(!atcphy->host_active || pm_suspend_target_state != PM_SUSPEND_TO_IDLE)", "false", 1) assert permissive != program From ecbbfa81bfc95bc5534bffc039f1bc4f891e97ae Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Mon, 23 Nov 2026 08:31:22 -0300 Subject: [PATCH 1300/1514] arm64: dts: apple: t6041-j575c: give the port controllers their LOCK key The tipd driver renegotiates the connection that a J575c port inherits from the boot chain (apple,reset-inherited-usb2-connection). The DISC command it sends for that needs the controller unlocked by LOCK with the board's key, the board number reversed. The driver keeps that key in a table of machines. Describe it on the three ports that are renegotiated, with the binding's apple,debug-lock-key, so the driver can take it from there instead of its table. The key is the one the driver uses today ("575J"). Elsewhere the driver reads the property for a debug link that a sleep cut (these ports have none), for the boot power state's HChk and USBw (the J575c ports are in S0 already at the probe), and for the post-sleep replug of a T6050 host. None of that runs on these ports. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi | 1 + arch/arm64/boot/dts/apple/t6041-j575c.dts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi b/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi index 3971e75915e90c..1fe04fb9e6212f 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j575c-atc3.dtsi @@ -117,6 +117,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec3: connector { compatible = "usb-c-connector"; diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 06ee0da56448f5..91da674fc549ad 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1449,6 +1449,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec1: connector { compatible = "usb-c-connector"; @@ -1481,6 +1482,7 @@ apple,event-irq-in-sleep; /* Retimer set up before Linux keeps SuperSpeed down until replugged. */ apple,reset-inherited-usb2-connection; + apple,debug-lock-key = "575J"; typec2: connector { compatible = "usb-c-connector"; From 2375501aa80ab09d7439a30585e6c0382346353b Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Mon, 23 Nov 2026 08:31:51 -0300 Subject: [PATCH 1301/1514] usb: typec: tipd: take the J575c's renegotiation key from the DT The renegotiation of an inherited connection took its LOCK key, and whether a failure fails the probe, from a table of machines (cd321x_inherited_boards[]). The J575c ports now carry their key in apple,debug-lock-key, which the partner replug already reads. Take the key from there when the port has one, and drop the J575c row. A port with its key in the DT is left as it was when the renegotiation fails, as the J575c row asked. The J716c keeps its row and its behaviour: its DT has no key yet, and a failure still fails its probe. A port with the property but no key either way keeps its connection as it is, with a warning, so a J575c booted with an older DT comes up as before the renegotiation instead of failing. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- drivers/usb/typec/tipd/core.c | 73 +++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 34 deletions(-) diff --git a/drivers/usb/typec/tipd/core.c b/drivers/usb/typec/tipd/core.c index b13054a905e03a..d9ece372d36a4a 100644 --- a/drivers/usb/typec/tipd/core.c +++ b/drivers/usb/typec/tipd/core.c @@ -3581,25 +3581,38 @@ static int cd321x_remove(struct tps6598x *tps) } /* - * Boards whose inherited boot connection must be renegotiated. The port - * controller key is the reversed target identifier. + * An SN201202x takes "DISC" unlocked with the key its DT gives it (apple,debug-lock-key, the board + * number reversed). + */ +static int tipd_replug_key(struct tps6598x *tps, u8 key[4]) +{ + const char *s; + + if (!device_is_compatible(tps->dev, "apple,sn201202x") || + device_property_read_string(tps->dev, "apple,debug-lock-key", &s) || strlen(s) != 4) + return -EOPNOTSUPP; + memcpy(key, s, 4); + return 0; +} + +/* + * A connection that was up before Linux keeps state from the boot chain: a USB2 repeater + * connection on the J716c boot port, or on the J575c a Type-C retimer set up before the host PHY + * ran, so SuperSpeed stays in RxDetect until the partner is replugged. The controller reports + * nothing that tells such a connection apart from one that trains, so every one is renegotiated. * - * J716c: the boot port keeps a USB2 repeater connection. - * J575c: a connection that was up before Linux keeps its Type-C retimer set up - * from before the host PHY ran, so SuperSpeed stays in RxDetect until the - * partner is replugged. Every such connection is renegotiated: the controller - * reports nothing that tells it apart from one whose SuperSpeed side trains. - * A failure leaves the port as it was (USB2 only) instead of failing the probe. + * The renegotiation's DISC takes the controller unlocked with the board's LOCK key, the board + * number reversed. A port whose DT gives it (apple,debug-lock-key) is left as it was if the + * renegotiation fails. The J716c's DT does not give it yet: its key is here, and a failure there + * fails the probe. */ struct cd321x_inherited_board { const char *compatible; u8 key[4]; - bool best_effort; }; static const struct cd321x_inherited_board cd321x_inherited_boards[] = { { .compatible = "apple,j716c", .key = { '6', '1', '7', 'J' } }, - { .compatible = "apple,j575c", .key = { '5', '7', '5', 'J' }, .best_effort = true }, }; static const struct cd321x_inherited_board *cd321x_inherited_board(void) @@ -3612,8 +3625,7 @@ static const struct cd321x_inherited_board *cd321x_inherited_board(void) return NULL; } -static int __cd321x_reset_inherited_connection(struct tps6598x *tps, - const struct cd321x_inherited_board *board, +static int __cd321x_reset_inherited_connection(struct tps6598x *tps, const u8 key[4], u32 *status) { static const u8 locked[4]; @@ -3626,8 +3638,7 @@ static int __cd321x_reset_inherited_connection(struct tps6598x *tps, return 0; /* All suppliers are available, but no USB or router session has started. */ - ret = tps6598x_exec_cmd(tps, "LOCK", sizeof(board->key), board->key, sizeof(result), - &result); + ret = tps6598x_exec_cmd(tps, "LOCK", 4, key, sizeof(result), &result); if (ret) return ret; if (result) { @@ -3670,6 +3681,8 @@ static int __cd321x_reset_inherited_connection(struct tps6598x *tps, static int cd321x_reset_inherited_connection(struct tps6598x *tps, u32 *status) { const struct cd321x_inherited_board *board; + bool best_effort = true; + u8 key[4]; int ret; if (!device_property_read_bool(tps->dev, "apple,reset-inherited-usb2-connection") || @@ -3677,12 +3690,19 @@ static int cd321x_reset_inherited_connection(struct tps6598x *tps, u32 *status) tps->dbma_at_probe || !(*status & TPS_STATUS_PLUG_PRESENT) || !TPS_STATUS_TO_TYPEC_DATAROLE(*status)) return 0; - board = cd321x_inherited_board(); - if (!board) - return 0; + if (tipd_replug_key(tps, key)) { + board = cd321x_inherited_board(); + if (!board) { + dev_warn(tps->dev, + "inherited connection not reinitialized: no apple,debug-lock-key\n"); + return 0; + } + memcpy(key, board->key, sizeof(key)); + best_effort = false; + } - ret = __cd321x_reset_inherited_connection(tps, board, status); - if (!ret || !board->best_effort) + ret = __cd321x_reset_inherited_connection(tps, key, status); + if (!ret || !best_effort) return ret; dev_warn(tps->dev, "inherited connection not reinitialized: %d\n", ret); @@ -3719,21 +3739,6 @@ static void tipd_port_list_del(struct tps6598x *tps) cancel_work_sync(&tps->replug_work); } -/* - * An SN201202x takes "DISC" unlocked with the key its DT gives it (apple,debug-lock-key, the board - * number reversed). - */ -static int tipd_replug_key(struct tps6598x *tps, u8 key[4]) -{ - const char *s; - - if (!device_is_compatible(tps->dev, "apple,sn201202x") || - device_property_read_string(tps->dev, "apple,debug-lock-key", &s) || strlen(s) != 4) - return -EOPNOTSUPP; - memcpy(key, s, 4); - return 0; -} - bool tipd_replug_supported(struct tps6598x *tps) { u8 key[4]; From bc7e15f1a8ac754385c5612d89819633d8d208b5 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 09:42:39 +0000 Subject: [PATCH 1302/1514] dt-bindings: media: apple,avd: note demand-gated perf power domain Clarify that the optional "perf" power domain may be demand-gated by the driver based on decode load rather than held on whenever the decoder is active. Signed-off-by: AxxzyWasTaken --- Documentation/devicetree/bindings/media/apple,avd.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/media/apple,avd.yaml b/Documentation/devicetree/bindings/media/apple,avd.yaml index 28944ad86ca1b7..03ea9c0a5078a4 100644 --- a/Documentation/devicetree/bindings/media/apple,avd.yaml +++ b/Documentation/devicetree/bindings/media/apple,avd.yaml @@ -131,7 +131,7 @@ allOf: minItems: 1 items: - description: decoder power state - - description: performance floor (PMC rail or PMP device level) held while decoding + - description: performance floor (PMC rail or PMP device level) engaged on demand during high-load decoding power-domain-names: minItems: 1 From 52d1efdec9d9d1f4f163991f9e0398e2fe1e432b Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 09:42:39 +0000 Subject: [PATCH 1303/1514] media: apple: avd: demand-gate the optional perf power domain Attaching all AVD power domains with PD_FLAG_DEV_LINK_ON links the optional "perf" floor domain (such as pmc_soc_max on T6040/T6041 or pmp_report_avd0 on T8140) directly to avd->dev's runtime PM state. That holds the SoC rail at VMAX during probe boot, stream drains, and every light decode frame even though single-stream 1080p30/60 decodes far faster than real time without the floor (+0.96-1.05 W on J616c). Link only the "core" power domain to avd->dev's runtime PM and attach the optional "perf" domain separately with its own 100 ms autosuspend delay, leaving it suspended until active decode demand requires it: - frames larger than 1080p (> 2.2 Mpx, so 1440p/4K/8K engage on the first frame without ramp-up latency), - sustained high aggregate pixel throughput (>= 180 Mpx/s over a 250 ms window, with 135 Mpx/s exit hysteresis), - multiple concurrent active streams (either simultaneously in flight or alternating within a window), or - queue backlog (>= 4 frames in flight). A 500 ms hold-down prevents floor thrashing across brief demand dips. Idle retirement releases the floor via autosuspend so inter-frame gaps on demanding streams stay seamless. Power-off, parking (after firmware shutdown and DMA blocking, including error paths), and teardown drop and suspend the floor synchronously. During system suspend, device_prepare() holds a runtime-PM usage count on the genpd virtual device so pm_runtime_suspend() returns -EAGAIN while pm_runtime_put_sync_suspend() drops AVD's reference, letting genpd power the perf domain off at noirq (child before parent), matching prior timing. Nodes without a "perf" domain take a lockless no-op fast path without acquiring queue_lock. Measured on J616c (T6041 M4 Max, 4-round live VA-API ABAB): - 1080p30 H.264 (-re): 6778.5 -> 5817.7 mW (-961 mW / -14.2%), pmc-soc-vmax stays off-0 - 1080p30 AV1 (-re): 6785.9 -> 5737.3 mW (-1049 mW / -15.5%), pmc-soc-vmax stays off-0 - 4K30 AV1 (-re) and dual concurrent 1080p: pmc-soc-vmax scales up automatically and releases back to off-0 within 2.5 s idle - Unthrottled max-speed decode: 0.50s vs 0.50s (1080p H.264) and 1.76-2.01s vs 1.76-2.01s (4K AV1), bit-exact MD5, 0 AVD/DART errors. Add KUnit coverage in apple-avd-pm for low-demand playback, >1080p immediate engagement, pixel-rate hysteresis, multi-stream/backlog triggers, backwards-clock and >= 2-window resets, failed floor acquisition, and synchronous suspend/park cleanup including failed recovery paths. Signed-off-by: AxxzyWasTaken --- drivers/media/platform/apple/avd/avd-drv.c | 77 ++-- .../media/platform/apple/avd/avd-pm-test.c | 328 +++++++++++++++++- drivers/media/platform/apple/avd/avd-pm.c | 255 +++++++++++++- drivers/media/platform/apple/avd/avd-pm.h | 37 ++ drivers/media/platform/apple/avd/avd-queue.c | 45 ++- drivers/media/platform/apple/avd/avd.h | 2 +- 6 files changed, 712 insertions(+), 32 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-drv.c b/drivers/media/platform/apple/avd/avd-drv.c index 6580b13eb0c348..7dfe9a9dac2458 100644 --- a/drivers/media/platform/apple/avd/avd-drv.c +++ b/drivers/media/platform/apple/avd/avd-drv.c @@ -667,6 +667,57 @@ static void avd_release_open_firmware(void *data) release_firmware(avd->fw); } +static int avd_attach_power_domains(struct avd_dev *avd) +{ + static const char *const core_pd_names[] = { "core" }; + static const struct dev_pm_domain_attach_data core_pd_data = { + .pd_names = core_pd_names, + .num_pd_names = ARRAY_SIZE(core_pd_names), + .pd_flags = PD_FLAG_DEV_LINK_ON, + }; + static const struct dev_pm_domain_attach_data all_pd_data = { + .pd_flags = PD_FLAG_DEV_LINK_ON, + }; + struct device_node *np = avd->dev->of_node; + int num_pds, perf_idx, ret; + + /* + * A node may list a second power domain, "perf": a PMC or PMP + * performance floor that raises the SoC rail while the decoder works. + * With more than one domain the core attaches none. Link only "core" + * to avd->dev's runtime PM so light streams do not hold the floor on + * every frame, and manage "perf" separately on demand in avd-pm.c. + */ + num_pds = of_count_phandle_with_args(np, "power-domains", + "#power-domain-cells"); + if (num_pds <= 1) + return 0; + + perf_idx = of_property_match_string(np, "power-domain-names", "perf"); + if (perf_idx >= 0 && + of_property_match_string(np, "power-domain-names", "core") >= 0) { + ret = devm_pm_domain_attach_list(avd->dev, &core_pd_data, + &avd->pd_list); + if (ret < 0) + return dev_err_probe(avd->dev, ret, + "failed to attach core power domain\n"); + + ret = avd_pm_attach_perf(avd, perf_idx); + if (ret) + return dev_err_probe(avd->dev, ret, + "failed to attach perf power domain\n"); + + return 0; + } + + ret = devm_pm_domain_attach_list(avd->dev, &all_pd_data, &avd->pd_list); + if (ret < 0) + return dev_err_probe(avd->dev, ret, + "failed to attach power domains\n"); + + return 0; +} + static int avd_probe(struct platform_device *pdev) { struct avd_dev *avd; @@ -695,25 +746,9 @@ static int avd_probe(struct platform_device *pdev) if (IS_ERR(avd->rstc)) return PTR_ERR(avd->rstc); - /* - * A node may list a second power domain, "perf": the PMC floor that - * holds the SoC rail at its performance level while the decoder works - * (decode runs at about half speed on the M4 Pro without it). With more - * than one domain the core attaches none, so attach them all with - * runtime PM device links: the floor is then held exactly while the - * decoder is runtime-active (frames in flight plus the autosuspend - * delay) and released when it idles, rests or is retired. - */ - if (of_count_phandle_with_args(pdev->dev.of_node, "power-domains", - "#power-domain-cells") > 1) { - static const struct dev_pm_domain_attach_data pd_data = { - .pd_flags = PD_FLAG_DEV_LINK_ON, - }; - - ret = devm_pm_domain_attach_list(avd->dev, &pd_data, &avd->pd_list); - if (ret < 0) - return dev_err_probe(avd->dev, ret, "failed to attach power domains\n"); - } + ret = avd_attach_power_domains(avd); + if (ret) + return ret; avd->code = devm_platform_ioremap_resource_byname(pdev, "code"); if (IS_ERR(avd->code)) @@ -769,8 +804,8 @@ static int avd_probe(struct platform_device *pdev) /* * The domain links were added active, but the decoder starts - * suspended: settle that before enabling runtime PM, so the floor is - * not held until the first decode has come and gone. + * suspended: settle that before enabling runtime PM, so the attached + * domains are not held until the first decode has come and gone. */ if (avd->pd_list) { ret = pm_runtime_set_suspended(avd->dev); diff --git a/drivers/media/platform/apple/avd/avd-pm-test.c b/drivers/media/platform/apple/avd/avd-pm-test.c index 36efb30e83c4b5..aea64efc5aac25 100644 --- a/drivers/media/platform/apple/avd/avd-pm-test.c +++ b/drivers/media/platform/apple/avd/avd-pm-test.c @@ -14,9 +14,16 @@ struct avd_pm_test { unsigned int step; unsigned int unmap_step; unsigned int boot_step; + unsigned int shutdown_step; unsigned int resubmit_step; + unsigned int perf_put_step; unsigned int shutdowns; unsigned int submissions; + unsigned int perf_gets; + unsigned int perf_puts; + unsigned int perf_sync_puts; + unsigned int perf_suspends; + int perf_get_error; int boot_error; int suspend_error; bool unmapped_active; @@ -27,6 +34,51 @@ static struct avd_pm_test *avd_pm_fixture(struct avd_dev *avd) return container_of(avd, struct avd_pm_test, avd); } +static u64 avd_pm_test_now_ns; + +static u64 avd_pm_test_clock(void) +{ + return avd_pm_test_now_ns; +} + +static int avd_pm_test_perf_get(struct avd_dev *avd) +{ + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + if (fixture->perf_get_error) + return fixture->perf_get_error; + fixture->perf_gets++; + return 0; +} + +static void avd_pm_test_perf_put(struct avd_dev *avd, bool sync) +{ + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + fixture->perf_put_step = ++fixture->step; + fixture->perf_puts++; + if (sync) + fixture->perf_sync_puts++; +} + +static void avd_pm_test_perf_suspend(struct avd_dev *avd) +{ + avd_pm_fixture(avd)->perf_suspends++; +} + +static const struct avd_pm_perf_ops avd_pm_test_perf_ops = { + .get = avd_pm_test_perf_get, + .put = avd_pm_test_perf_put, + .suspend = avd_pm_test_perf_suspend, +}; + +static void avd_pm_test_enable_perf(struct avd_dev *avd) +{ + avd_pm_test_now_ns = 1000ULL * NSEC_PER_MSEC; + avd->pm.clock_ns = avd_pm_test_clock; + avd->pm.perf_ops = &avd_pm_test_perf_ops; +} + static bool avd_pm_test_idle(struct avd_dev *avd) { struct avd_pm_test *fixture = avd_pm_fixture(avd); @@ -49,7 +101,10 @@ static int avd_pm_test_boot(struct avd_dev *avd) static void avd_pm_test_shutdown(struct avd_dev *avd) { - avd_pm_fixture(avd)->shutdowns++; + struct avd_pm_test *fixture = avd_pm_fixture(avd); + + fixture->shutdown_step = ++fixture->step; + fixture->shutdowns++; } static int avd_pm_test_suspend(struct avd_dev *avd) @@ -376,6 +431,270 @@ static void avd_pm_parked_resume_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd->pm.irq_enabled); } +static void avd_pm_perf_low_demand_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + unsigned int i; + + /* Without a "perf" domain every call is a no-op. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + avd_pm_perf_idle(avd); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); + + avd_pm_test_enable_perf(avd); + + /* Steady 1080p60 single-stream playback (~125 Mpx/s) stays off floor. */ + for (i = 0; i < 60; i++) { + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_perf_idle(avd); + avd_pm_test_now_ns += 16666667ULL; + } + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); +} + +static void avd_pm_perf_large_frame_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* 4K engages on the first frame and does not double-acquire while held. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + avd_pm_test_now_ns += 5ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 2, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* Idle releases asynchronously so inter-frame gaps reuse autosuspend. */ + avd_pm_perf_idle(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 0U); + + /* Power-off flushes any pending autosuspend timer synchronously. */ + KUNIT_ASSERT_EQ(test, avd_pm_power_off(avd), 0); + KUNIT_EXPECT_EQ(test, fixture->perf_suspends, 1U); + + /* 1440p also engages immediately; parking drops it synchronously. */ + avd->pm.dart_active = true; + avd_pm_perf_frame_start(avd, &stream_a, 2560, 1440, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + KUNIT_ASSERT_EQ(test, avd_pm_park(avd), 0); + KUNIT_EXPECT_LT(test, fixture->shutdown_step, fixture->perf_put_step); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); +} + +static void avd_pm_perf_rate_hysteresis_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + unsigned int i; + + avd_pm_test_enable_perf(avd); + + /* Unthrottled 1080p burst (>180 Mpx/s) engages perf mid-window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* Roll over into a 150 Mpx/s window (inside 135..180 Mpx/s hysteresis band). */ + avd_pm_test_now_ns += AVD_PERF_WINDOW_MS * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + for (i = 0; i < 17; i++) { + avd_pm_test_now_ns += 13ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + } + avd_pm_test_now_ns += 35ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + + /* Drop to 1080p30 (~63 Mpx/s): stays held through hold-down, then releases. */ + for (i = 0; i < 30; i++) { + avd_pm_test_now_ns += 33333333ULL; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + } + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); +} + +static void avd_pm_perf_concurrency_and_backlog_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a, stream_b; + + avd_pm_test_enable_perf(avd); + + /* Simultaneous multi-stream frames engage immediately. */ + avd_pm_perf_frame_start(avd, &stream_a, 1280, 720, 2, 2); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); + + /* Alternating streams on a 1-slot backend also trigger within a window. */ + avd_pm_test_now_ns += 1000ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1280, 720, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_test_now_ns += 16ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_b, 1280, 720, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + avd_pm_perf_suspend(avd); + + /* Queue backlog (>= AVD_PERF_INFLIGHT_HIGH) engages immediately. */ + avd_pm_test_now_ns += 1000ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, + AVD_PERF_INFLIGHT_HIGH - 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, + AVD_PERF_INFLIGHT_HIGH, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 3U); + avd_pm_perf_idle(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); +} + +static void avd_pm_perf_clock_and_gap_reset_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a, stream_b; + unsigned int i; + + avd_pm_test_enable_perf(avd); + + /* Engage high-rate and multi-stream demand inside one window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, (i & 1) ? &stream_b : &stream_a, + 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + + /* A gap >= 2 * window resets rate/multi state and releases on low load. */ + avd_pm_test_now_ns += 2ULL * AVD_PERF_WINDOW_MS * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + + /* Re-engage high demand, then jump the clock backwards mid-window. */ + for (i = 0; i < 24; i++) { + avd_pm_perf_frame_start(avd, (i & 1) ? &stream_b : &stream_a, + 1920, 1088, 1, 1); + avd_pm_test_now_ns += 3ULL * NSEC_PER_MSEC; + } + KUNIT_EXPECT_TRUE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 2U); + + avd_pm_test_now_ns = avd->pm.perf_window_start_ns - 50ULL * NSEC_PER_MSEC; + avd_pm_perf_frame_start(avd, &stream_a, 1920, 1088, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_rate_high); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_window_multi); + KUNIT_EXPECT_EQ(test, avd->pm.perf_hold_until_ns, 0ULL); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); +} + +static void avd_pm_perf_failed_park_and_recover_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + struct iommu_domain domain = {}; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* Early -EHOSTDOWN return from avd_pm_park() still drops perf_held. */ + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_park(avd), -EHOSTDOWN); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); + + /* Failed DART parking (-ENODEV) shuts down first, then drops perf_held. */ + avd->pm.dart_active = true; + avd->domain = &domain; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_recover(avd), -ENODEV); + KUNIT_EXPECT_EQ(test, fixture->shutdowns, 1U); + KUNIT_EXPECT_LT(test, fixture->shutdown_step, fixture->perf_put_step); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 2U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 2U); + + /* Failed recovery reboot re-parks without double-putting perf_held. */ + avd->domain = NULL; + fixture->boot_error = -ETIMEDOUT; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, avd_pm_recover(avd), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, fixture->shutdowns, 3U); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 3U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 3U); + KUNIT_EXPECT_EQ(test, fixture->perf_suspends, 1U); +} + +static void avd_pm_perf_error_handling_test(struct kunit *test) +{ + struct avd_pm_test *fixture = test->priv; + struct avd_dev *avd = &fixture->avd; + int stream_a; + + avd_pm_test_enable_perf(avd); + + /* Failed floor acquisition never sets perf_held or causes an unmatched put. */ + fixture->perf_get_error = -EIO; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 0U); + avd_pm_perf_idle(avd); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 0U); + + /* Recovery once floor acquisition succeeds again. */ + fixture->perf_get_error = 0; + avd_pm_perf_frame_start(avd, &stream_a, 3840, 2160, 1, 1); + KUNIT_EXPECT_TRUE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_gets, 1U); + avd_pm_perf_suspend(avd); + KUNIT_EXPECT_FALSE(test, avd->pm.perf_held); + KUNIT_EXPECT_EQ(test, fixture->perf_puts, 1U); + KUNIT_EXPECT_EQ(test, fixture->perf_sync_puts, 1U); +} + static void avd_pm_test_exit(struct kunit *test) { struct avd_pm_test *fixture = test->priv; @@ -396,6 +715,13 @@ static struct kunit_case avd_pm_test_cases[] = { KUNIT_CASE(avd_pm_recovery_dart_gate_test), KUNIT_CASE(avd_pm_recovery_boot_test), KUNIT_CASE(avd_pm_parked_resume_test), + KUNIT_CASE(avd_pm_perf_low_demand_test), + KUNIT_CASE(avd_pm_perf_large_frame_test), + KUNIT_CASE(avd_pm_perf_rate_hysteresis_test), + KUNIT_CASE(avd_pm_perf_concurrency_and_backlog_test), + KUNIT_CASE(avd_pm_perf_clock_and_gap_reset_test), + KUNIT_CASE(avd_pm_perf_failed_park_and_recover_test), + KUNIT_CASE(avd_pm_perf_error_handling_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-pm.c b/drivers/media/platform/apple/avd/avd-pm.c index 4b60ce60ea4e87..183e49d28859d2 100644 --- a/drivers/media/platform/apple/avd/avd-pm.c +++ b/drivers/media/platform/apple/avd/avd-pm.c @@ -2,8 +2,11 @@ #include #include #include +#include #include +#include #include +#include #include #include #include @@ -12,6 +15,11 @@ /* [C] Keep Linux's existing default until the idle-timer capture is available. */ #define AVD_AUTOSUSPEND_MS 100 +#define AVD_PERF_AUTOSUSPEND_MS 100 +#define AVD_PERF_WINDOW_NS (AVD_PERF_WINDOW_MS * NSEC_PER_MSEC) +#define AVD_PERF_WINDOW_ENTER_PIXELS \ + (AVD_PERF_ENTER_PX_PER_MS * AVD_PERF_WINDOW_MS) +#define AVD_PERF_HOLD_NS (AVD_PERF_HOLD_MS * NSEC_PER_MSEC) #define AVD_DRAIN_TIMEOUT_MS 5000 #define AVD_PIODMA_SRAM_BASE 0x24 @@ -182,10 +190,229 @@ const struct avd_queue_pm_ops avd_pm_queue_ops = { .resubmit = avd_pm_resubmit, }; +static int avd_pm_perf_get_pd(struct avd_dev *avd) +{ + return pm_runtime_resume_and_get(avd->pm.perf_dev); +} + +static void avd_pm_perf_put_pd(struct avd_dev *avd, bool sync) +{ + if (sync) { + pm_runtime_put_sync_suspend(avd->pm.perf_dev); + return; + } + pm_runtime_mark_last_busy(avd->pm.perf_dev); + pm_runtime_put_autosuspend(avd->pm.perf_dev); +} + +static void avd_pm_perf_suspend_pd(struct avd_dev *avd) +{ + pm_runtime_suspend(avd->pm.perf_dev); +} + +static const struct avd_pm_perf_ops avd_pm_perf_runtime_ops = { + .get = avd_pm_perf_get_pd, + .put = avd_pm_perf_put_pd, + .suspend = avd_pm_perf_suspend_pd, +}; + +static u64 avd_pm_clock_ns(struct avd_dev *avd) +{ + return avd->pm.clock_ns ? avd->pm.clock_ns() : ktime_get_ns(); +} + +static void avd_pm_perf_reset_demand(struct avd_pm *pm) +{ + pm->perf_rate_high = false; + pm->perf_window_valid = false; + pm->perf_window_multi = false; + pm->perf_window_stream = NULL; + pm->perf_window_start_ns = 0; + pm->perf_window_pixels = 0; + pm->perf_hold_until_ns = 0; +} + +static void avd_pm_detach_perf(void *data) +{ + struct avd_dev *avd = data; + struct device *perf_dev = avd->pm.perf_dev; + + if (!perf_dev) + return; + + avd_pm_perf_suspend(avd); + mutex_lock(&avd->pm.perf_lock); + WRITE_ONCE(avd->pm.perf_ops, NULL); + avd->pm.perf_dev = NULL; + mutex_unlock(&avd->pm.perf_lock); + pm_runtime_dont_use_autosuspend(perf_dev); + dev_pm_domain_detach(perf_dev, false); +} + +int avd_pm_attach_perf(struct avd_dev *avd, unsigned int index) +{ + struct device *perf_dev; + int ret; + + perf_dev = dev_pm_domain_attach_by_id(avd->dev, index); + if (IS_ERR(perf_dev)) + return PTR_ERR(perf_dev); + if (!perf_dev) + return 0; + + pm_runtime_set_autosuspend_delay(perf_dev, AVD_PERF_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(perf_dev); + + mutex_lock(&avd->pm.perf_lock); + avd->pm.perf_dev = perf_dev; + WRITE_ONCE(avd->pm.perf_ops, &avd_pm_perf_runtime_ops); + mutex_unlock(&avd->pm.perf_lock); + + ret = devm_add_action_or_reset(avd->dev, avd_pm_detach_perf, avd); + if (ret) + return ret; + + return 0; +} + +/* + * Engage the optional "perf" floor only when active decode demand requires it: + * frames larger than 1080p, multiple concurrent active streams, queue backlog, + * or sustained high pixel throughput with Schmitt-trigger hysteresis and a + * hold-down window to prevent floor thrashing. + */ +void avd_pm_perf_frame_start(struct avd_dev *avd, const void *stream_id, + u32 width, u32 height, unsigned int inflight, + unsigned int concurrent_streams) +{ + const struct avd_pm_perf_ops *ops; + struct avd_pm *pm = &avd->pm; + u64 frame_pixels = (u64)width * height; + u64 now_ns; + bool high_demand, need_perf; + + if (!READ_ONCE(pm->perf_ops)) + return; + + mutex_lock(&pm->perf_lock); + ops = pm->perf_ops; + if (!ops) + goto unlock; + + now_ns = avd_pm_clock_ns(avd); + + if (!pm->perf_window_valid || now_ns < pm->perf_window_start_ns) { + pm->perf_window_valid = true; + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + pm->perf_rate_high = false; + pm->perf_hold_until_ns = 0; + } else { + u64 dt_ns = now_ns - pm->perf_window_start_ns; + + if (dt_ns >= 2 * AVD_PERF_WINDOW_NS) { + pm->perf_rate_high = false; + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + } else if (dt_ns >= AVD_PERF_WINDOW_NS) { + u64 dt_ms = div_u64(dt_ns, NSEC_PER_MSEC); + u64 px_per_ms = div_u64(pm->perf_window_pixels, dt_ms); + + if (px_per_ms >= AVD_PERF_ENTER_PX_PER_MS) + pm->perf_rate_high = true; + else if (px_per_ms < AVD_PERF_EXIT_PX_PER_MS) + pm->perf_rate_high = false; + + pm->perf_window_start_ns = now_ns; + pm->perf_window_pixels = frame_pixels; + pm->perf_window_stream = stream_id; + pm->perf_window_multi = false; + } else { + pm->perf_window_pixels += frame_pixels; + if (pm->perf_window_stream && stream_id && + pm->perf_window_stream != stream_id) + pm->perf_window_multi = true; + else if (!pm->perf_window_stream) + pm->perf_window_stream = stream_id; + if (pm->perf_window_pixels >= AVD_PERF_WINDOW_ENTER_PIXELS) + pm->perf_rate_high = true; + } + } + + high_demand = frame_pixels > AVD_PERF_FRAME_PIXELS || + concurrent_streams > 1 || + pm->perf_window_multi || + inflight >= AVD_PERF_INFLIGHT_HIGH || + pm->perf_rate_high; + + if (high_demand) + pm->perf_hold_until_ns = now_ns + AVD_PERF_HOLD_NS; + + need_perf = high_demand || + (pm->perf_hold_until_ns && now_ns < pm->perf_hold_until_ns); + + if (need_perf) { + /* Best effort: decode still completes without the floor. */ + if (!pm->perf_held && ops->get(avd) >= 0) + pm->perf_held = true; + } else { + pm->perf_hold_until_ns = 0; + if (pm->perf_held) { + pm->perf_held = false; + ops->put(avd, false); + } + } + +unlock: + mutex_unlock(&pm->perf_lock); +} + +void avd_pm_perf_idle(struct avd_dev *avd) +{ + const struct avd_pm_perf_ops *ops; + + if (!READ_ONCE(avd->pm.perf_ops)) + return; + + mutex_lock(&avd->pm.perf_lock); + ops = avd->pm.perf_ops; + if (ops && avd->pm.perf_held) { + avd->pm.perf_held = false; + ops->put(avd, false); + } + mutex_unlock(&avd->pm.perf_lock); +} + +void avd_pm_perf_suspend(struct avd_dev *avd) +{ + const struct avd_pm_perf_ops *ops; + + if (!READ_ONCE(avd->pm.perf_ops)) + return; + + mutex_lock(&avd->pm.perf_lock); + ops = avd->pm.perf_ops; + avd_pm_perf_reset_demand(&avd->pm); + if (ops) { + if (avd->pm.perf_held) { + avd->pm.perf_held = false; + ops->put(avd, true); + } else if (ops->suspend) { + ops->suspend(avd); + } + } + mutex_unlock(&avd->pm.perf_lock); +} + void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, const struct avd_queue_pm_ops *queue) { mutex_init(&avd->pm.lock); + mutex_init(&avd->pm.perf_lock); INIT_LIST_HEAD(&avd->pm.deferred_unmaps); init_waitqueue_head(&avd->pm.idle_wait); avd->pm.dart_active = false; @@ -194,6 +421,11 @@ void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, mutex_init(&avd->pm.hw_lock); avd->pm.hw_on = false; avd->pm.irq_gen = 0; + avd->pm.perf_dev = NULL; + avd->pm.perf_ops = NULL; + avd->pm.perf_held = false; + avd->pm.clock_ns = NULL; + avd_pm_perf_reset_demand(&avd->pm); avd->backend = backend; avd->pm.queue = queue; } @@ -248,6 +480,7 @@ void avd_pm_disable(struct avd_dev *avd) pm_runtime_disable(avd->dev); /* Also close the host IRQ if the final hardware transition failed. */ avd_pm_disable_irq(avd); + avd_pm_perf_suspend(avd); /* No queue_mutex is held here: let a woken handler thread finish. */ if (avd->pm.irq >= 0) synchronize_irq(avd->pm.irq); @@ -293,27 +526,34 @@ int avd_pm_backend_resume(struct avd_dev *avd) /* Caller holds a runtime PM reference and queue_mutex. */ int avd_pm_park(struct avd_dev *avd) { - int ret; + int ret = 0; - if (!avd->pm.dart_active) + if (!avd->pm.dart_active) { + avd_pm_perf_suspend(avd); return -EHOSTDOWN; + } avd_pm_disable_irq(avd); dev_warn(avd->dev, "recover: stop firmware\n"); avd->backend->shutdown(avd); if (avd->domain && !avd->pm.dma_parked) { - if (!avd->empty_domain) - return -ENODEV; + if (!avd->empty_domain) { + ret = -ENODEV; + goto out_perf; + } dev_warn(avd->dev, "recover: block DMA\n"); ret = iommu_attach_device(avd->empty_domain, avd->dev); if (ret) { dev_err(avd->dev, "recover: DART empty attach failed: %d\n", ret); - return ret; + goto out_perf; } avd->pm.dma_parked = true; /* Outstanding transfers drain into faults before any reset/free. */ usleep_range(5000, 6000); } - return 0; +out_perf: + /* Drop the perf floor only after firmware shutdown and DMA parking. */ + avd_pm_perf_suspend(avd); + return ret; } int avd_pm_recover(struct avd_dev *avd) @@ -429,6 +669,7 @@ int avd_pm_power_off(struct avd_dev *avd) avd_pm_drain_unmaps(avd); avd->pm.dart_active = false; mutex_unlock(&avd->pm.lock); + avd_pm_perf_suspend(avd); return 0; } @@ -451,6 +692,8 @@ static int avd_system_suspend(struct device *dev) ret = avd->pm.queue->drain(avd); if (!ret) ret = pm_runtime_force_suspend(dev); + if (!ret) + avd_pm_perf_suspend(avd); if (ret) v4l2_m2m_resume(avd->m2m_dev); return ret; diff --git a/drivers/media/platform/apple/avd/avd-pm.h b/drivers/media/platform/apple/avd/avd-pm.h index 10e3a0ffbe9362..31c6e36301b483 100644 --- a/drivers/media/platform/apple/avd/avd-pm.h +++ b/drivers/media/platform/apple/avd/avd-pm.h @@ -8,8 +8,25 @@ #include "avd-queue.h" +#define AVD_PERF_FRAME_PIXELS 2200000ULL +#define AVD_PERF_WINDOW_MS 250ULL +#define AVD_PERF_ENTER_PX_PER_MS 180000ULL +#define AVD_PERF_EXIT_PX_PER_MS 135000ULL +#define AVD_PERF_HOLD_MS 500ULL +/* + * Tier-1 backends expose 15 FIFO slots (7 on tier-0) and single-stream 1080p + * players often decode-ahead 2-3 frames; engage on >= 4 frames in flight. + */ +#define AVD_PERF_INFLIGHT_HIGH 4U + struct avd_dma_release; +struct avd_pm_perf_ops { + int (*get)(struct avd_dev *avd); + void (*put)(struct avd_dev *avd, bool sync); + void (*suspend)(struct avd_dev *avd); +}; + struct avd_queue_pm_ops { /* Snapshot under the queue lock: all FREE, no context draining. */ bool (*idle)(struct avd_dev *avd); @@ -49,6 +66,20 @@ struct avd_pm { /* Protected by queue_lock; counts drain operations, not stopped streams. */ unsigned int draining; const struct avd_queue_pm_ops *queue; + /* Optional "perf" floor domain, engaged only under high decode demand. */ + struct device *perf_dev; + const struct avd_pm_perf_ops *perf_ops; + /* Serializes perf-floor demand state and votes. */ + struct mutex perf_lock; + bool perf_held; + bool perf_rate_high; + bool perf_window_valid; + bool perf_window_multi; + const void *perf_window_stream; + u64 perf_window_start_ns; + u64 perf_window_pixels; + u64 perf_hold_until_ns; + u64 (*clock_ns)(void); }; /* The caller holds the queue lock, including the draining-context count. */ @@ -56,6 +87,12 @@ bool avd_pm_can_suspend(const struct avd_frame *frames, unsigned int draining); void avd_pm_init(struct avd_dev *avd, const struct avd_backend_ops *backend, const struct avd_queue_pm_ops *queue); +int avd_pm_attach_perf(struct avd_dev *avd, unsigned int index); +void avd_pm_perf_frame_start(struct avd_dev *avd, const void *stream_id, + u32 width, u32 height, unsigned int inflight, + unsigned int concurrent_streams); +void avd_pm_perf_idle(struct avd_dev *avd); +void avd_pm_perf_suspend(struct avd_dev *avd); void avd_pm_enable(struct avd_dev *avd); int avd_pm_map_piodma(struct avd_dev *avd); void avd_pm_prepare_piodma(struct avd_dev *avd); diff --git a/drivers/media/platform/apple/avd/avd-queue.c b/drivers/media/platform/apple/avd/avd-queue.c index 22e40b631a5270..19ac0c17bf495a 100644 --- a/drivers/media/platform/apple/avd/avd-queue.c +++ b/drivers/media/platform/apple/avd/avd-queue.c @@ -106,7 +106,12 @@ static void avd_retire(struct avd_dev *avd) f->dst = NULL; f->state = AVD_FRAME_FREE; avd->inflight--; - spin_unlock_irqrestore(&avd->queue_lock, flags); + if (!avd->inflight) { + spin_unlock_irqrestore(&avd->queue_lock, flags); + avd_pm_perf_idle(avd); + } else { + spin_unlock_irqrestore(&avd->queue_lock, flags); + } avd_pm_queue_changed(avd); pm_runtime_mark_last_busy(avd->dev); pm_runtime_put_autosuspend(avd->dev); @@ -352,6 +357,30 @@ int avd_queue_ready(void *priv) return ready; } +static void avd_active_stream_stats(struct avd_dev *avd, unsigned int *inflight, + unsigned int *streams) +{ + struct avd_ctx *seen[AVD_MAX_FRAMES]; + unsigned int i, j, count = 0; + unsigned long flags; + + spin_lock_irqsave(&avd->queue_lock, flags); + *inflight = avd->inflight; + for (i = 0; i < AVD_MAX_FRAMES; i++) { + struct avd_ctx *ctx = avd->frames[i].ctx; + + if (avd->frames[i].state == AVD_FRAME_FREE || !ctx) + continue; + for (j = 0; j < count; j++) + if (seen[j] == ctx) + break; + if (j == count) + seen[count++] = ctx; + } + spin_unlock_irqrestore(&avd->queue_lock, flags); + *streams = count; +} + static void avd_queue_submit_work(struct work_struct *work) { struct avd_ctx *ctx = container_of(work, struct avd_ctx, submit_work); @@ -359,7 +388,7 @@ static void avd_queue_submit_work(struct work_struct *work) const struct avd_codec_frame_ops *ops = ctx->coded_fmt_desc->frame_ops; struct avd_frame *f = NULL; unsigned long flags; - unsigned int i; + unsigned int i, inflight, streams; int ret; mutex_lock(&avd->queue_mutex); @@ -491,7 +520,12 @@ static void avd_queue_submit_work(struct work_struct *work) f->state = AVD_FRAME_FREE; f->ctx = NULL; avd->inflight--; - spin_unlock_irqrestore(&avd->queue_lock, flags); + if (!avd->inflight) { + spin_unlock_irqrestore(&avd->queue_lock, flags); + avd_pm_perf_idle(avd); + } else { + spin_unlock_irqrestore(&avd->queue_lock, flags); + } avd_pm_queue_changed(avd); pm_runtime_mark_last_busy(avd->dev); pm_runtime_put_autosuspend(avd->dev); @@ -500,6 +534,11 @@ static void avd_queue_submit_work(struct work_struct *work) goto unlock; } v4l2_m2m_buf_copy_metadata(f->src, f->dst); + if (READ_ONCE(avd->pm.perf_ops)) { + avd_active_stream_stats(avd, &inflight, &streams); + avd_pm_perf_frame_start(avd, ctx, fmt_width(ctx), + fmt_height(ctx), inflight, streams); + } ret = avd_send_frame(avd, f); if (ret && ret != -EBUSY) { spin_lock_irqsave(&avd->queue_lock, flags); diff --git a/drivers/media/platform/apple/avd/avd.h b/drivers/media/platform/apple/avd/avd.h index 07b01c86fa6c70..6bd4b9e6dbc1ba 100644 --- a/drivers/media/platform/apple/avd/avd.h +++ b/drivers/media/platform/apple/avd/avd.h @@ -258,7 +258,7 @@ struct avd_dev { struct iommu_domain *domain; struct iommu_domain *empty_domain; - /* Core and perf-floor domains when the node lists more than one. */ + /* Power domains linked to runtime PM when the node lists more than one. */ struct dev_pm_domain_list *pd_list; struct mutex vdev_lock; From 04ce44a770432ca5e522a1ffa23b4270d6783b55 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Wed, 25 Nov 2026 07:11:22 -0300 Subject: [PATCH 1304/1514] arm64: dts: apple: t6041-j575c: enable both MSR scalers The J575c includes t6041-j614-j616-j575-scaler.dtsi but leaves both scalers, their DARTs and their power domains disabled. The J616c enables them. The J575c's ADT (macOS 27.2.1) has scaler0 and scaler1 (hardware-version 0x15, MSR21) and dart-scaler0/1 at the dtsi's addresses and interrupts (1547/1549, 1553/1555; DARTs 1548, 1554, streams 0 and 1), and its PMGR has MSR0 and MSR0_ASE_CORE at 0x470/0x478 and MSR1 and MSR1_ASE_CORE at 0x3b0/0x3b8 in group 1, as the dtsi has them. Enable them, with ps_fab5_soc, as the J616c does. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 06ee0da56448f5..61f312e2e3a9a4 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -2101,3 +2101,44 @@ &ps_qspi { status = "okay"; }; + +/* + * Both MSR scalers (scaler0, scaler1) and their DARTs, as on the J616c. The + * J575c's ADT has them at the addresses, interrupts and PMGR offsets of + * t6041-j614-j616-j575-scaler.dtsi. + */ +&ps_fab5_soc { + status = "okay"; +}; + +&ps_msr0 { + status = "okay"; +}; + +&ps_msr0_ase_core { + status = "okay"; +}; + +&scaler0_dart { + status = "okay"; +}; + +&scaler0 { + status = "okay"; +}; + +&ps_msr1 { + status = "okay"; +}; + +&ps_msr1_ase_core { + status = "okay"; +}; + +&scaler1_dart { + status = "okay"; +}; + +&scaler1 { + status = "okay"; +}; From 7360cf091732387b47ead044c85cf55f4ff99084 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Wed, 25 Nov 2026 07:11:22 -0300 Subject: [PATCH 1305/1514] arm64: dts: apple: t6041-j575c: enable the first ProRes engine (apr0) t6041.dtsi describes apr0 and its DART, and the J616c enables them. The J575c leaves them disabled. The J575c's ADT (macOS 27.2.1) has apr0 (core 0x301000000, wrapper 0x300000000, aux 0x3010c0000, IRQ 1960) and dart-apr0 (0x301020000, IRQ 1959, stream 1) at the t6041.dtsi values, and its PMGR has FAB1_SOC, SCODEC and SCODEC_STREAMING at 0x2d0, 0x328 and 0x330. Enable apr0, its DART and those power domains, as the J616c does. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 06ee0da56448f5..64dba9dbed156c 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1399,6 +1399,32 @@ status = "okay"; }; +/* + * First ProRes encoder (apr0) and its DART, as on the J616c. The J575c's ADT + * has apr0 and dart-apr0 at the t6041.dtsi addresses and interrupts. apr0 + * runs with SCODEC_STREAMING (and SCODEC) powered and uses the driver's + * built-in T6041 power-up rows. + */ +&ps_fab1_soc { + status = "okay"; +}; + +&ps_scodec { + status = "okay"; +}; + +&ps_scodec_streaming { + status = "okay"; +}; + +&apr0_dart { + status = "okay"; +}; + +&apr0 { + status = "okay"; +}; + /* * Three of the four back Thunderbolt ports, with the J773s's PD controllers * (nub-spmi-a0 0xc, 0xa and 0x8 for ATC0-2), as on the J616c. From 3fd56c264ff9b78e05f8ebcdc7256c1c126f0e04 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Wed, 25 Nov 2026 07:11:22 -0300 Subject: [PATCH 1306/1514] arm64: dts: apple: t6041-j575c: enable the Neural Engine The J575c includes the J616c's ANE reservations, which the loader fills from the ADT's ane0 segment-ranges, but leaves the ANE and its three DARTs disabled. The J614c and J616c enable them. The J575c's ADT (macOS 27.2.1) has ane0 (apple,t6041-ane on any T6041) with pre-loaded firmware (__TEXT;__DATA) and dart-ane0 at the t604x.dtsi addresses, and the loader already fills the reservations on this machine (ane-firmware-text@100009d8000). Enable the ANE and its DARTs. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- arch/arm64/boot/dts/apple/t6041-j575c.dts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 06ee0da56448f5..7bce2c10baf1aa 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -1378,6 +1378,27 @@ status = "okay"; }; +/* + * The Neural Engine and its three DARTs, as on the J614c/J616c. The J575c's + * ADT has ane0 with pre-loaded firmware (__TEXT;__DATA); the loader fills the + * reservations of t6041-j616c-ane.dtsi and the firmware IOVAs from it. + */ +&ane0_dart0 { + status = "okay"; +}; + +&ane0_dart1 { + status = "okay"; +}; + +&ane0_dart2 { + status = "okay"; +}; + +&ane { + status = "okay"; +}; + /* Both JPEG engines; they have no board wiring. */ &ps_jpg { status = "okay"; From 4af242cb1d743ab46a457f89817df5e1d6754d73 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 10:15:58 +0000 Subject: [PATCH 1307/1514] media: apple: avd: update host tests for demand-gated perf domain Update the AVD standalone host test fixtures for the demand-gated perf power domain hooks added to avd-queue.c and avd-pm.c: - dispatch-test.py: extract production avd_active_stream_stats() from avd-queue.c, add pm.perf_ops to struct avd_dev, add width/height fields and fmt_width()/fmt_height() helpers matching avd.h, stub avd_pm_perf_frame_start()/avd_pm_perf_idle(), and assert no-op fast path, multi-stream accounting, idle retirement, and held-slice idle transitions. - recovery-test.py: stub avd_pm_perf_suspend() and assert it is invoked on every park, recovery, failed attach/reset/boot, and power-off path after hardware IRQ shutdown. Signed-off-by: AxxzyWasTaken --- .../platform/apple/avd/tests/dispatch-test.py | 42 ++++++++++++++++++- .../platform/apple/avd/tests/recovery-test.py | 29 +++++++------ 2 files changed, 58 insertions(+), 13 deletions(-) diff --git a/drivers/media/platform/apple/avd/tests/dispatch-test.py b/drivers/media/platform/apple/avd/tests/dispatch-test.py index 4a46a45e141002..6bd1496fc19eff 100755 --- a/drivers/media/platform/apple/avd/tests/dispatch-test.py +++ b/drivers/media/platform/apple/avd/tests/dispatch-test.py @@ -92,6 +92,7 @@ const struct format *coded_fmt_desc; struct work_struct submit_work; bool draining,broken; unsigned int hw_errors,max_frames; enum avd_frame_dep next_dep; bool session_started; u64 session_generation; + u32 width,height; int ctrl_hdl; }; struct avd_variant { size_t fp_size; }; @@ -106,6 +107,7 @@ struct avd_ctx *deferred_ctx; struct avd_frame *building; unsigned int inflight; u64 frame_seq; bool compat_held,stopping,faulted; unsigned long rest_until,last_recover; unsigned int storm_count; + struct { const void *perf_ops; } pm; int queue_lock,queue_mutex,queue_work; void *dev,*m2m_dev; }; static struct avd_ctx *running; @@ -147,6 +149,20 @@ static void pm_runtime_mark_last_busy(void *d) { (void)d; } static void pm_runtime_put_autosuspend(void *d) { (void)d; assert(pm_refs);pm_refs--; } static void avd_pm_queue_changed(struct avd_dev *d) { (void)d; } +static unsigned int perf_starts,perf_idles; +static const void *last_perf_stream; +static u32 last_perf_width,last_perf_height; +static unsigned int last_perf_inflight,last_perf_streams; +static u32 fmt_width(struct avd_ctx *c) { return c->width ? c->width : 1920; } +static u32 fmt_height(struct avd_ctx *c) { return c->height ? c->height : 1080; } +static void avd_pm_perf_frame_start(struct avd_dev *d,const void *stream_id, + u32 width,u32 height,unsigned int inflight,unsigned int concurrent_streams) +{ + assert(d && d->pm.perf_ops); perf_starts++; + last_perf_stream=stream_id; last_perf_width=width; last_perf_height=height; + last_perf_inflight=inflight; last_perf_streams=concurrent_streams; +} +static void avd_pm_perf_idle(struct avd_dev *d) { assert(d && !d->inflight); perf_idles++; } static void mod_delayed_work(void *w,void *v,int t) { (void)w;(void)v;(void)t; } static int avd_buf_alloc(struct avd_dev *d,struct avd_buf *b,size_t n) { (void)d;(void)b;(void)n;return -ENOMEM; } static void *devm_kzalloc(void *d,size_t n,int f) { (void)d;(void)f;return calloc(1,n); } @@ -285,6 +301,28 @@ m[0].src=&src[18];m[0].dst=&dst[18];submit(&c[0]); assert(!running&&wakes==old_wakes+1&&irq_enables==1&&!d.rest_until&&!d.storm_count); complete(&d,&c[0],0);assert(!pm_refs); + /* Perf floor hooks stay silent without perf_ops and track streams when enabled. */ + assert(!perf_starts&&perf_idles); + { + static const int fake_perf_ops; + struct vb2_v4l2_buffer perf_src[3]={},perf_dst[3]={}; + unsigned int old_idles=perf_idles; + d.pm.perf_ops=&fake_perf_ops; + c[0].width=3840;c[0].height=2160;c[1].width=1920;c[1].height=1080; + m[0].src=&perf_src[0];m[0].dst=&perf_dst[0];submit(&c[0]); + assert(perf_starts==1&&last_perf_stream==&c[0]&&last_perf_width==3840&&last_perf_height==2160); + assert(last_perf_inflight==1&&last_perf_streams==1&&perf_idles==old_idles); + m[1].src=&perf_src[1];m[1].dst=&perf_dst[1];submit(&c[1]); + assert(perf_starts==2&&last_perf_stream==&c[1]&&last_perf_width==1920&&last_perf_height==1080); + assert(last_perf_inflight==2&&last_perf_streams==2&&perf_idles==old_idles); + complete(&d,&c[0],0);assert(perf_idles==old_idles); + complete(&d,&c[1],0);assert(perf_idles==old_idles+1&&!d.inflight&&!pm_refs); + perf_src[2].flags=V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF; + m[0].src=&perf_src[2];m[0].dst=&perf_dst[2];submit(&c[0]); + assert(perf_starts==2&&perf_idles==old_idles+2&&!d.inflight&&!pm_refs); + m[0].dst=NULL; + d.pm.perf_ops=NULL; + } /* A failed wake retires the decoder and never opens IRQs or posts a frame. */ d.rest_until=jiffies;wake_error=-EIO;m[0].src=&src[19];m[0].dst=&dst[19]; unsigned int old_sent=send_count;submit(&c[0]);assert(d.faulted&&irq_enables==1&&send_count==old_sent); @@ -413,7 +451,9 @@ def main(): function(CORE.read_text(), 'v4l2_m2m_buf_done_and_job_finish') + function(legacy, 'avd_job_finish_no_pm') + function(legacy, 'avd_job_finish') + function(source, 'avd_send_frame') + - function(source, 'avd_retire') + function(source, 'avd_queue_submit_work') + + function(source, 'avd_retire') + + function(source, 'avd_active_stream_stats') + + function(source, 'avd_queue_submit_work') + function(source, 'avd_frame_vp_complete') + function(source, 'avd_retire_vp') + function(source, 'avd_queue_ready') + VP_MAIN + MAIN.replace(' puts("PASS: production dispatch', ' check_vp_events();\n puts("PASS: production dispatch')) exe = out / 'dispatch-test' diff --git a/drivers/media/platform/apple/avd/tests/recovery-test.py b/drivers/media/platform/apple/avd/tests/recovery-test.py index 915707e1e63e41..e78070c2d1a76f 100755 --- a/drivers/media/platform/apple/avd/tests/recovery-test.py +++ b/drivers/media/platform/apple/avd/tests/recovery-test.py @@ -68,7 +68,7 @@ static unsigned long jiffies=100; static void *attached; static int reset_error,boot_error,attach_error; -static unsigned int resets,boots,attaches,detaches,shutdowns,resubmits,drains,irq_opens,irq_closes,step,block_step,reset_step; +static unsigned int resets,boots,attaches,detaches,shutdowns,resubmits,drains,irq_opens,irq_closes,perf_suspends,step,block_step,reset_step; static bool pm_runtime_suspended(void *dev) { (void)dev;return false; } static void disable_irq_nosync(int irq) { assert(irq==1);irq_closes++; } static void enable_irq(int irq) { assert(irq==1);assert(!d.pm.dma_parked);irq_opens++; } @@ -97,6 +97,11 @@ } static void resubmit(struct avd_dev *avd) { (void)avd;resubmits++; } static void avd_pm_drain_unmaps(struct avd_dev *avd) { assert(avd->pm.dart_active);drains++; } +static void avd_pm_perf_suspend(struct avd_dev *avd) { + assert(avd==&d); + if(avd->pm.dart_active) assert(!d.pm.hw_on&&!d.pm.irq_enabled); + perf_suspends++; +} ''' MAIN = r''' @@ -108,36 +113,36 @@ d=(struct avd_dev){.dev=&d,.domain=&domain_token,.empty_domain=&empty_token,.backend=&backend, .pm={.dart_active=true,.irq_enabled=true,.hw_on=true,.irq=1,.queue=&queue}}; attached=d.domain;reset_error=boot_error=attach_error=0; - resets=boots=attaches=detaches=shutdowns=resubmits=drains=irq_opens=irq_closes=step=0; + resets=boots=attaches=detaches=shutdowns=resubmits=drains=irq_opens=irq_closes=perf_suspends=step=0; } int main(void) { - init();assert(!avd_pm_recover(&d));assert(resets==1&&boots==1&&attaches==1&&detaches==1); + init();assert(!avd_pm_recover(&d));assert(resets==1&&boots==1&&attaches==1&&detaches==1&&perf_suspends==1); assert(!d.pm.dma_parked&&!d.pm.irq_enabled&&attached==d.domain); avd_pm_enable_irq(&d);assert(irq_opens==1); init(); d.variant = &no_recovery_reset; assert(avd_pm_recover(&d) == -EIO); - assert(attaches == 1 && !resets && !boots && !detaches); + assert(attaches == 1 && !resets && !boots && !detaches && perf_suspends == 1); assert(d.pm.dma_parked && !d.pm.irq_enabled && attached == d.empty_domain); init();reset_error=-EIO;d.frames[0].state=AVD_FRAME_SUBMITTED;avd_reset_queue(&d,-ETIMEDOUT); - assert(d.faulted&&resets==1&&!boots&&!detaches&&d.pm.dma_parked&&attached==d.empty_domain); + assert(d.faulted&&resets==1&&!boots&&!detaches&&d.pm.dma_parked&&attached==d.empty_domain&&perf_suspends==1); assert(d.frames[0].state==AVD_FRAME_DONE&&!d.pm.irq_enabled); d.frames[0].state=AVD_FRAME_FREE; assert(!avd_pm_power_off(&d)&&!avd_pm_power_on(&d)); - assert(!boots&&!resubmits&&!d.pm.irq_enabled&&attached==d.empty_domain); + assert(!boots&&!resubmits&&!d.pm.irq_enabled&&attached==d.empty_domain&&perf_suspends==2); init();boot_error=-ETIMEDOUT;avd_reset_queue(&d,-ETIMEDOUT); - assert(d.faulted&&resets==1&&boots==1&&attaches==2&&detaches==1&&d.pm.dma_parked); + assert(d.faulted&&resets==1&&boots==1&&attaches==2&&detaches==1&&d.pm.dma_parked&&perf_suspends==2); assert(attached==d.empty_domain&&!d.pm.irq_enabled); init();avd_reset_queue(&d,-EIO);avd_reset_queue(&d,-EIO);avd_reset_queue(&d,-EIO); - assert(resets==2&&boots==2&&attaches==3&&detaches==2&&!d.faulted&&d.rest_until); + assert(resets==2&&boots==2&&attaches==3&&detaches==2&&!d.faulted&&d.rest_until&&perf_suspends==3); assert(d.pm.dma_parked&&attached==d.empty_domain&&!d.pm.irq_enabled); unsigned int old_boots=boots,old_resets=resets; assert(!avd_pm_power_off(&d)&&!avd_pm_power_on(&d)); - assert(boots==old_boots&&resets==old_resets&&!resubmits&&!d.pm.irq_enabled); + assert(boots==old_boots&&resets==old_resets&&!resubmits&&!d.pm.irq_enabled&&perf_suspends==4); /* The expiry path (dispatch-test) calls recover under a PM reference. */ - jiffies=d.rest_until;assert(!avd_pm_recover(&d));assert(resets==3&&!d.pm.dma_parked); - init();attach_error=-EIO;assert(avd_pm_recover(&d)==-EIO);assert(!resets&&!boots&&!detaches); - init();d.pm.dart_active=false;assert(avd_pm_park(&d)==-EHOSTDOWN);assert(!shutdowns&&!resets&&!attaches); + jiffies=d.rest_until;assert(!avd_pm_recover(&d));assert(resets==3&&!d.pm.dma_parked&&perf_suspends==5); + init();attach_error=-EIO;assert(avd_pm_recover(&d)==-EIO);assert(!resets&&!boots&&!detaches&&perf_suspends==1); + init();d.pm.dart_active=false;assert(avd_pm_park(&d)==-EHOSTDOWN);assert(!shutdowns&&!resets&&!attaches&&perf_suspends==1); puts("PASS: production recovery/PM: park before reset, no-reset variant stays parked, failed reset/boot stays blocked, budget rests, parked resume never boots, expiry recovery"); } ''' From 99d5af56d79997d07e804db50415a0e26eb40441 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 05:20:00 -0500 Subject: [PATCH 1308/1514] drm/apple: dptx: skip ATC PHY lane check for fixed non-ATC-PHY outputs SET_ACTIVE_LANE_COUNT checks the requested lane count against dptx->lane_count and logs an error when the request exceeds it. Commit 7b0416bd0edb ("drm/apple: dptx: no PHY lane check for a DP tunnel on any SoC") exempted USB4 DP tunnels because they have no ATC PHY lanes to pre-validate and dptx->lane_count tracks the previous active lane count. Fixed non-ATC-PHY outputs (dcp->dptx_phy > 3, such as dedicated HDMI-A ports on desktop Apple Silicon SoCs) are in the same situation: lines 500-502 already accept their lane counts directly into dptx->lane_count and skip phy_configure() when dptx->atcphy is NULL. When DCP firmware issues SET_ACTIVE_LANE_COUNT(4) before GET_MAX_LANE_COUNT (while dptx->lane_count is still 0) or after dropping the link to fewer lanes, the driver logged a spurious error on every boot and relink: set_active_lane_count: unexpected lane count:4 phy: 0 Exempt dcp->dptx_phy > 3 from the ATC PHY unexpected-lane-count check so the guard matches the set_lanes acceptance condition immediately below, and add a host regression test covering fixed non-ATC-PHY, ATC PHY, USB4 tunnel, external H17P, and invalid lane-count cases. Signed-off-by: Satya Benson --- drivers/gpu/drm/apple/dptxep.c | 9 +- .../asahi/dptx-set-active-lane-count-tests.py | 405 ++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 3 files changed, 412 insertions(+), 4 deletions(-) create mode 100755 tools/asahi/dptx-set-active-lane-count-tests.py diff --git a/drivers/gpu/drm/apple/dptxep.c b/drivers/gpu/drm/apple/dptxep.c index 01d5f67c18b2b2..513514cd2cfb1e 100644 --- a/drivers/gpu/drm/apple/dptxep.c +++ b/drivers/gpu/drm/apple/dptxep.c @@ -482,11 +482,12 @@ static int dptxport_call_set_active_lane_count(struct apple_epic_service *servic ret = dptx_j700_validate_lanes(dptx, lane_count); if (ret) return ret; - } else if (dptx->lane_count < lane_count && !dcp_is_usb4_output(dcp)) { + } else if (dptx->lane_count < lane_count && !dcp_is_usb4_output(dcp) && + dcp->dptx_phy <= 3) { /* - * A DP tunnel has no PHY lanes to check, on any SoC: its lane - * count is the tunnel's, and lane_count holds the previous - * active one. + * A DP tunnel or a fixed non-ATC-PHY output (dptx_phy > 3) has + * no ATC PHY lanes to check: its lane count is accepted below, + * and lane_count holds the previous active one. */ dev_err(dcp->dev, "set_active_lane_count: unexpected lane " "count:%llu phy: %d\n", lane_count, dptx->lane_count); diff --git a/tools/asahi/dptx-set-active-lane-count-tests.py b/tools/asahi/dptx-set-active-lane-count-tests.py new file mode 100755 index 00000000000000..8f8c5317082a4b --- /dev/null +++ b/tools/asahi/dptx-set-active-lane-count-tests.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Active lane-count validation in dptxport_call_set_active_lane_count(). + +Builds the production dptxport_call_set_active_lane_count() from +drivers/gpu/drm/apple/dptxep.c and verifies that fixed non-ATC-PHY outputs +(dcp->dptx_phy > 3, such as HDMI-A ports without an ATC PHY) and USB4 DP +tunnels do not trigger the ATC PHY "unexpected lane count" error when +firmware sets lanes before a max-lane query or after a link-down, while +standard ATC PHY outputs (dptx_phy <= 3) still flag unexpected counts and +invalid lane counts are rejected for all outputs. + +--mutation names a change to the production source that the matrix must kill. +""" +import argparse +import subprocess +import sys +import tempfile +from pathlib import Path + +MUTATIONS = { + # Revert the fixed non-ATC-PHY (dptx_phy > 3) exemption. + 'drop-fixed-phy': ( + ' && !dcp_is_usb4_output(dcp) &&\n\t\t dcp->dptx_phy <= 3)', + ' && !dcp_is_usb4_output(dcp))', + ), + # Suppress the ATC PHY unexpected-lane-count check altogether. + 'skip-all-unexpected': ( + 'dptx->lane_count < lane_count', + '0', + ), +} + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--mutation', choices=sorted(MUTATIONS)) +args = parser.parse_args() + +root = Path(__file__).resolve().parents[2] +dptx_c = (root / 'drivers/gpu/drm/apple/dptxep.c').read_text() + + +def extract_function(source, marker): + start = source.index(marker) + opening = source.index('{', start) + end, depth = opening + 1, 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +fn_src = extract_function( + dptx_c, + 'static int dptxport_call_set_active_lane_count(', +) + +if args.mutation: + old, new = MUTATIONS[args.mutation] + assert fn_src.count(old) == 1, args.mutation + fn_src = fn_src.replace(old, new) + +program = r''' +#include +#include +#include +#include +#include + +typedef uint8_t u8; +typedef uint32_t u32; +typedef unsigned long long u64; +typedef uint32_t __le32; +typedef unsigned long long __le64; + +static inline u64 le64_to_cpu(__le64 v) { return (u64)v; } +static inline __le64 cpu_to_le64(u64 v) { return (__le64)v; } +static inline __le32 cpu_to_le32(u32 v) { return (__le32)v; } +static inline u32 le32_to_cpu(__le32 v) { return (u32)v; } + +struct completion { + unsigned int done; +}; + +struct phy { + int dummy; +}; + +union phy_configure_opts { + struct { + u32 lanes; + bool set_lanes; + } dp; +}; + +struct dptxport_apcall_set_active_lane_count { + __le32 retcode; + u8 _unk0[12]; + __le64 lane_count; + u8 _unk1[8]; +} __attribute__((packed)); + +struct apple_dcp { + void *dev; + u32 dptx_phy; + bool external_h17p; + bool usb4_output; + bool t8132_ext; +}; + +struct apple_dcp_afkep { + struct apple_dcp *dcp; +}; + +struct dptx_port { + struct phy *atcphy; + union phy_configure_opts phy_ops; + u32 lane_count; + struct completion linkcfg_completion; +}; + +struct apple_epic_service { + struct apple_dcp_afkep *ep; + struct dptx_port *cookie; +}; + +static int unexpected_err_calls; +static int invalid_err_calls; +static int other_err_calls; +static int phy_configure_calls; +static int phy_configure_ret; +static int h17p_validate_calls; +static int h17p_validate_ret; +static int hotplug_calls; + +static void record_err(const char *fmt, ...) +{ + if (strstr(fmt, "unexpected lane")) + unexpected_err_calls++; + else if (strstr(fmt, "invalid lane count")) + invalid_err_calls++; + else + other_err_calls++; +} + +#define dev_err(dev, fmt, ...) record_err(fmt, ##__VA_ARGS__) +#define dev_dbg(dev, fmt, ...) do { (void)(dev); } while (0) + +static bool dcp_is_external_h17p(struct apple_dcp *dcp) +{ + return dcp->external_h17p; +} + +static bool dcp_is_usb4_output(struct apple_dcp *dcp) +{ + return dcp->usb4_output; +} + +static bool dcp_is_t8132_ext(struct apple_dcp *dcp) +{ + return dcp->t8132_ext; +} + +static int dptx_j700_validate_lanes(struct dptx_port *dptx, u64 lane_count) +{ + (void)dptx; + (void)lane_count; + h17p_validate_calls++; + return h17p_validate_ret; +} + +static int phy_configure(struct phy *phy, union phy_configure_opts *opts) +{ + (void)phy; + (void)opts; + phy_configure_calls++; + return phy_configure_ret; +} + +static void t8132_ext_drm_hotplug(void *dev) +{ + (void)dev; + hotplug_calls++; +} + +static void complete(struct completion *c) +{ + c->done++; +} + +''' + fn_src + r''' + +static void reset_counters(void) +{ + unexpected_err_calls = 0; + invalid_err_calls = 0; + other_err_calls = 0; + phy_configure_calls = 0; + phy_configure_ret = 0; + h17p_validate_calls = 0; + h17p_validate_ret = 0; + hotplug_calls = 0; +} + +static int call_set_lanes(struct apple_epic_service *svc, u64 lanes, + struct dptxport_apcall_set_active_lane_count *reply) +{ + struct dptxport_apcall_set_active_lane_count req = { + .lane_count = cpu_to_le64(lanes), + }; + + memset(reply, 0, sizeof(*reply)); + return dptxport_call_set_active_lane_count(svc, &req, sizeof(req), + reply, sizeof(*reply)); +} + +int main(void) +{ + struct phy dummy_phy = { 0 }; + struct dptxport_apcall_set_active_lane_count reply; + unsigned int cases = 0; + + /* + * 1. Fixed non-ATC-PHY outputs (dptx_phy > 3, e.g. HDMI-A with phy 4 or 5): + * bringing up 4 lanes from initial 0, dropping to 0, raising to 2 and 4 + * must never log "unexpected lane count" and must update dptx->lane_count. + */ + for (u32 phy_idx = 4; phy_idx <= 5; phy_idx++) { + struct apple_dcp dcp = { .dptx_phy = phy_idx }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + const u64 seq[] = { 4, 0, 2, 4, 1, 4 }; + + for (size_t i = 0; i < sizeof(seq) / sizeof(seq[0]); i++) { + unsigned int prev_done = port.linkcfg_completion.done; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, seq[i], &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 0); + assert(other_err_calls == 0); + assert(phy_configure_calls == 0); + assert(hotplug_calls == 0); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == seq[i]); + assert(port.lane_count == seq[i]); + assert(port.linkcfg_completion.done == + prev_done + (seq[i] > 0 ? 1u : 0u)); + cases++; + } + } + + /* + * 2. Standard ATC PHY outputs (dptx_phy <= 3, non-USB4, non-H17P): + * requesting more lanes than dptx->lane_count must still emit the + * "unexpected lane count" error; requesting <= dptx->lane_count must not. + */ + for (u32 phy_idx = 0; phy_idx <= 3; phy_idx++) { + struct apple_dcp dcp = { .dptx_phy = phy_idx }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 1); + assert(invalid_err_calls == 0); + assert(phy_configure_calls == 0); + assert(port.lane_count == 0); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == 4); + cases++; + + port.lane_count = 4; + reset_counters(); + ret = call_set_lanes(&svc, 2, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 0); + assert(port.lane_count == 4); + assert(le32_to_cpu(reply.retcode) == 0); + assert(le64_to_cpu(reply.lane_count) == 2); + cases++; + } + + /* + * 3. USB4 DP tunnels on any dptx_phy (0..3): + * no "unexpected lane count" error, updates dptx->lane_count, skips + * phy_configure(), and triggers T8132 hotplug only on lane changes. + */ + { + struct apple_dcp dcp = { + .dptx_phy = 1, + .usb4_output = true, + .t8132_ext = true, + }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(phy_configure_calls == 0); + assert(hotplug_calls == 1); + assert(port.lane_count == 4); + cases++; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(hotplug_calls == 0); + assert(port.lane_count == 4); + cases++; + } + + /* + * 4. External H17P output: + * uses dptx_j700_validate_lanes() and configures ATC PHY when present. + */ + { + struct apple_dcp dcp = { .dptx_phy = 0, .external_h17p = true }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = &dummy_phy, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, 4, &reply); + assert(ret == 0); + assert(h17p_validate_calls == 1); + assert(unexpected_err_calls == 0); + assert(phy_configure_calls == 1); + assert(port.lane_count == 4); + cases++; + } + + /* + * 5. Invalid lane counts (3, 5, 8) are rejected even on dptx_phy > 3. + */ + { + struct apple_dcp dcp = { .dptx_phy = 4 }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 4 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + const u64 bad[] = { 3, 5, 8 }; + + for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + unsigned int prev_done = port.linkcfg_completion.done; + int ret; + + reset_counters(); + ret = call_set_lanes(&svc, bad[i], &reply); + assert(ret == 0); + assert(unexpected_err_calls == 0); + assert(invalid_err_calls == 1); + assert(le32_to_cpu(reply.retcode) == 1); + assert(le64_to_cpu(reply.lane_count) == 0); + assert(port.linkcfg_completion.done == prev_done); + cases++; + } + } + + /* + * 6. Truncated request or reply buffers fail with -1. + */ + { + struct apple_dcp dcp = { .dptx_phy = 4 }; + struct apple_dcp_afkep ep = { .dcp = &dcp }; + struct dptx_port port = { .atcphy = NULL, .lane_count = 0 }; + struct apple_epic_service svc = { .ep = &ep, .cookie = &port }; + struct dptxport_apcall_set_active_lane_count req = { 0 }; + + assert(dptxport_call_set_active_lane_count(&svc, &req, sizeof(req) - 1, + &reply, sizeof(reply)) == -1); + assert(dptxport_call_set_active_lane_count(&svc, &req, sizeof(req), + &reply, sizeof(reply) - 1) == -1); + cases += 2; + } + + printf("%u cases\n", cases); + return 0; +} +''' + +with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / 'test.c' + src.write_text(program) + exe = src.with_suffix('') + subprocess.run( + ['cc', '-Werror', '-Wall', '-Wno-unused-function', + '-fsanitize=address,undefined', str(src), '-o', str(exe)], + check=True, + ) + run = subprocess.run([str(exe)]) + if run.returncode: + sys.exit(f'FAIL: dptx set_active_lane_count matrix exited {run.returncode}') +print('PASS fixed non-ATC-PHY (dptx_phy > 3) and USB4 tunnels skip ATC PHY lane-count error; ATC PHY and invalid counts preserved') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 0d3fb7209e45cb..8fd40aece45a91 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -89,6 +89,8 @@ def mutations(flag, names, base, expect=KILL): 'dcp-v27-dptx-layout-tests.py': [([], PASS)] + mutations( '--mutation', ['ignore-advertisement', 'ignore-pinned', 'ignore-dcpext', 'ignore-typec-routes'], []), + 'dptx-set-active-lane-count-tests.py': [([], PASS)] + mutations( + '--mutation', ['drop-fixed-phy', 'skip-all-unexpected'], []), 'dcpext26-wire-tests.py': [([], PASS)], 'pmp-native26-tests.py': [([], PASS)], From 1aaeec28576975f8db9e6fadc857fd2a7f03f34c Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 10:22:12 +0000 Subject: [PATCH 1309/1514] dt-bindings: media: apple,avd: wrap perf domain description line Wrap the perf power-domain description in apple,avd.yaml to stay under the 110-character yamllint line-length limit enforced by dt-checks. Signed-off-by: AxxzyWasTaken --- Documentation/devicetree/bindings/media/apple,avd.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Documentation/devicetree/bindings/media/apple,avd.yaml b/Documentation/devicetree/bindings/media/apple,avd.yaml index 03ea9c0a5078a4..2df00bda8c33b5 100644 --- a/Documentation/devicetree/bindings/media/apple,avd.yaml +++ b/Documentation/devicetree/bindings/media/apple,avd.yaml @@ -131,7 +131,9 @@ allOf: minItems: 1 items: - description: decoder power state - - description: performance floor (PMC rail or PMP device level) engaged on demand during high-load decoding + - description: > + performance floor (PMC rail or PMP device level) engaged on + demand during high-load decoding power-domain-names: minItems: 1 From b15be7d699b0988b8e5989aeb1c67e69e696b6ba Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 05:24:27 -0500 Subject: [PATCH 1310/1514] drm/asahi: g17: wrap the submission state initializer to 100 columns Split the Submission::state initializer that "drm/asahi: g17: deduplicate sync-input chains and resolve M5 cross-QID sources directly" left at 111 columns, as checkpatch asks. No functional change. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/fence.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index 888202bed8d969..d47b4f2f88fd85 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -278,7 +278,10 @@ impl Submission { let vm_status = work.as_ref().map(|work| work.status().clone()); Arc::pin_init( pin_init!(Self { - state <- new_mutex!(State { work, ready: None, published: None }, "G17 submission work state"), + state <- new_mutex!( + State { work, ready: None, published: None }, + "G17 submission work state" + ), vm_status, remaining: AtomicU8::new(1), error: AtomicI32::new(0), From d60d7b9124022ee8c49ba2c533148cbcd108f3c5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 05:26:09 -0500 Subject: [PATCH 1311/1514] drm/asahi: g17: wrap the sibling compute lines to 100 columns Split the nine lines that "drm/asahi: g17: fan M5 Pro compute out to sibling channels for sustained heavy kicks" left past 100 columns, as checkpatch asks, and follow the one that g17-compute-owed-stamp-tests.py matches in its retire-unchecked mutation. No functional change. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 7 +++++-- drivers/gpu/drm/asahi/g17/queue/render.rs | 10 ++++++---- drivers/gpu/drm/asahi/g17/runtime.rs | 11 ++++++++--- drivers/gpu/drm/asahi/g17/runtime/compute_control.rs | 6 +++++- drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs | 8 +++++++- tools/asahi/g17-compute-owed-stamp-tests.py | 3 ++- 6 files changed, 33 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 3658d8b0811a5c..5b0eb70a6fec2c 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -762,7 +762,8 @@ impl Queue { #[expect( clippy::too_many_arguments, - reason = "A sibling compute queue takes the same physical graph inputs plus its channel identity." + reason = "A sibling compute queue takes the same physical graph inputs plus its channel \ + identity." )] pub(crate) fn new_channel( alloc: &Allocator<'_>, @@ -2152,7 +2153,9 @@ impl Queue { /// A recycled vacant sibling queue whose descriptor ring still awaits off-lock release /// before re-arming with fresh backing. pub(crate) fn take_recycled_ring(&mut self) -> Option { - if !self.recycled_pending() || self.pool_phase != PoolPhase::Vacant || self.graph.ring.is_none() + if !self.recycled_pending() + || self.pool_phase != PoolPhase::Vacant + || self.graph.ring.is_none() { return None; } diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index a3692605b4851c..2bf03c518a1966 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -677,10 +677,12 @@ impl Pair { struct RenderBarriers { tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], tiling_count: usize, - fragment: [KickDependency; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment: [KickDependency; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], - fragment_types: [u8; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment_types: [u8; + 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } /// The last fragment kick published on any pair, and the last one of a render with an API task @@ -749,8 +751,8 @@ fn render_barriers( let fragment_stage = fragment_stage || stage_prefixes; let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut tiling_count = 0; - let mut fragment_barriers = - [own_tiling; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_barriers = [own_tiling; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut fragment_types = diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 3790372db14963..3c85e7d73750f2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2569,8 +2569,9 @@ impl super::Firmware { } #[inline(never)] - fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, packet: Arc, - dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result + fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, + packet: Arc, dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch) -> Result { if self.recovery.pending() || super::recovery::Memory::recovery_state(&self.init)? != 0 { return Err(EAGAIN); @@ -3115,7 +3116,11 @@ impl Backend { /// [`compute::Queue::sustained`]). Every other command streams down the primary ring: short /// kicks run faster there than spread over several QIDs, and a semaphore hop between queues /// stays on one ring per queue. - fn fans_out(&self, packet: &super::job::Packet, primary_sustained: impl FnOnce() -> bool) -> bool { + fn fans_out( + &self, + packet: &super::job::Packet, + primary_sustained: impl FnOnce() -> bool, + ) -> bool { self.compute_channels > 1 && packet.order.wait_through[1].is_none() && packet.completion.sources().is_none() diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs index 4e0dfece644a6e..881caee85111e8 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs @@ -79,7 +79,11 @@ impl Backend { return Ok(Decision::Own); } firmware.scan_compute(None, deferred)?; - if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) { + if !firmware + .queues + .compute_for_packet(self.owner, packet) + .is_some_and(|queue| queue.retired_held(packet)) + { return Ok(Decision::Own); } static REPORTED: AtomicU32 = AtomicU32::new(0); diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index 55cd94b8b003f7..f00e07a848eb06 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -150,7 +150,13 @@ impl Firmware { require_visible, &mut dependencies, )?; - self.publish_compute_on(owner, Some(qid), packet.clone(), dependencies.as_slice(), deferred) + self.publish_compute_on( + owner, + Some(qid), + packet.clone(), + dependencies.as_slice(), + deferred, + ) })() }; let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) && (self.recovery.pending() diff --git a/tools/asahi/g17-compute-owed-stamp-tests.py b/tools/asahi/g17-compute-owed-stamp-tests.py index edca687c3989b4..76165e3cbbcd91 100644 --- a/tools/asahi/g17-compute-owed-stamp-tests.py +++ b/tools/asahi/g17-compute-owed-stamp-tests.py @@ -733,7 +733,8 @@ def fixture(): MUTATIONS = { 'own-finished': [('_ if own.finished => Decision::Retire,', '_ if own.finished => Decision::Own,')], 'no-retire-glue': [('verdict.decision = self.retire_on_record(firmware, packet, &mut deferred)?;', '')], - 'retire-unchecked': [('if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) {', + 'retire-unchecked': [('if !firmware\n .queues\n .compute_for_packet(self.owner, packet)\n' + ' .is_some_and(|queue| queue.retired_held(packet))\n {', 'if false {')], 'no-expiry': [('if observed_at == Some(STAMP_WAIT_EXPIRED) {', 'if false {')], 'no-step-past': [('Ok(Some(_)) | Err(EAGAIN) if owed => at += 1,', 'Ok(Some(_)) | Err(EAGAIN) if owed => break,'), From 038447c6a96c45c0d9bcc3fdbeb2aa31037f40ed Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 05:33:04 -0500 Subject: [PATCH 1312/1514] nvme: apple: skip T8122 warm sleep on dry runs and fall back on refused sleeps Do not warm-idle ANS when apple_sleep_dry_run() is active; take the standard apple_rtkit_shutdown() and cold PMGR reset path instead, matching suspend-to-idle. If a non-dry-run firmware sleep is refused before the commit (!pm_resume_via_firmware()), fall back to the cold PMGR reset path in apple_nvme_reset_work_impl() rather than attempting a warm restart without a power cycle or locking sleep_failed. Signed-off-by: Satya Benson --- drivers/nvme/host/apple.c | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/drivers/nvme/host/apple.c b/drivers/nvme/host/apple.c index 1320be0b1f8149..15c8eeba741472 100644 --- a/drivers/nvme/host/apple.c +++ b/drivers/nvme/host/apple.c @@ -3159,30 +3159,27 @@ static void apple_nvme_shutdown(struct platform_device *pdev) static void apple_nvme_t8122_warm_resume(struct apple_nvme *anv) { void __iomem *control = anv->mmio_coproc + APPLE_ANS_COPROC_CPU_CONTROL; - bool via_fw = pm_resume_via_firmware(); int ret; if (!xchg(&anv->t8122_warm_sleep, false)) return; - if (via_fw) { - apple_sleep_restore_pins(); - if (anv->sart) - apple_sart_replay(anv->sart); - } + /* + * A sleep refused before the commit left ANS powered, so a warm + * restart without a power cycle can hang; fall back to the cold PMGR + * reset path in apple_nvme_reset_work_impl(). + */ + if (!pm_resume_via_firmware()) + return; + + apple_sleep_restore_pins(); + if (anv->sart) + apple_sart_replay(anv->sart); apple_rtkit_set_warm_epmap_mask(anv->rtk, BIT(0)); anv->sleep_run_time = ktime_get(); - if (via_fw) { - ret = apple_rtkit_sleep_return_start(anv->rtk, control); - } else { - ret = apple_rtkit_warm_restart(anv->rtk); - if (!ret) - writel(readl(control) | APPLE_ANS_COPROC_CPU_CONTROL_RUN, - control); - } + ret = apple_rtkit_sleep_return_start(anv->rtk, control); if (ret) { - dev_err(anv->dev, "ANS warm restart failed (via_fw=%d): %d\n", - via_fw, ret); + dev_err(anv->dev, "ANS warm restart failed: %d\n", ret); anv->sleep_failed = true; } else { WRITE_ONCE(anv->sleep_restarting, true); @@ -3455,7 +3452,8 @@ static int apple_nvme_suspend(struct device *dev) if (apple_rtkit_is_running(anv->rtk)) { if (anv->hw->warm_sleep && pm_suspend_target_state == PM_SUSPEND_MEM && - pm_suspend_via_firmware()) { + pm_suspend_via_firmware() && + !apple_sleep_dry_run()) { anv->sleep_failed = false; anv->sleep_restarted = false; ret = apple_rtkit_idle(anv->rtk); From 05eb659c4a23e0b20c146f2b200a0d3f6d587e83 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 05:33:04 -0500 Subject: [PATCH 1313/1514] PCI: apple: hold conventional host domains across noirq suspend for firmware sleep Conventional Apple PCIe hosts that use apple_pcie_s2r_reinit() currently only call apple_pcie_hold_domains() during suspend-to-idle. On SoCs whose host power domain is not marked always-on (such as T8122 ps_apcie_gp/ps_apcie), genpd gates the host during suspend_noirq even for firmware-driven sleeps. If the sleep is a dry run or is refused before the commit (!pm_resume_via_firmware()), neither the SoC wake sequence nor apple_pcie_hib_restore_noirq()/apple_pcie_resume() runs, leaving the controller unprogrammed behind a down link. Hold the host's attached power domains across genpd suspend_noirq for firmware-driven sleeps as well, releasing them in apple_pcie_resume_noirq(). On an abandoned or dry-run sleep the controller and link stay intact; on a real committed sleep the SoC commit powers the block down and the wake path retrains it. Signed-off-by: Satya Benson --- drivers/pci/controller/pcie-apple.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 824b94d04caa7a..1d556e26828c82 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -7140,9 +7140,18 @@ static int apple_pcie_suspend_noirq(struct device *dev) return ret; } if (!pcie->hw->tunneled) { - if (apple_pcie_s2r_reinit(pcie) && pm_suspend_via_firmware()) + bool s2r_reinit = apple_pcie_s2r_reinit(pcie) && pm_suspend_via_firmware(); + + if (s2r_reinit) apple_pcie_hib_save(pcie); - if (pm_suspend_no_platform() && pcie->num_pds) + /* + * Keep the host's power domains on across genpd noirq suspend + * for s2idle and firmware sleeps: on an abandoned or dry-run + * firmware sleep the commit never runs, so gating the domain + * here would leave the controller unprogrammed with no wake + * sequence to reinitialize it. A real commit powers it down. + */ + if ((pm_suspend_no_platform() || s2r_reinit) && pcie->num_pds) return apple_pcie_hold_domains(pcie); return 0; } From 61af6c41476ac007883e92b8d42f6a2b8165ca30 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 05:35:12 -0500 Subject: [PATCH 1314/1514] drm/asahi: g17: drop the unused unlocked M5 history update "drm/asahi: g17: reduce M5 direct submit and event lock overhead" moved every caller of Port::note_m5_submission_history() to the variant that runs under a held m5_outer, which left the unlocked wrapper unused and the build warning that it is never used. Remove it and describe the locked variant on its own. No functional change. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/port.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index 879a227d9a36e9..aace069d8a2439 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -434,13 +434,8 @@ impl Port { self.regs.as_ref().ok_or(ENODEV)?.submit_m5_work_held(submission) } - /// Counts `submissions` in the M5 submission-history table without taking the device mutex. - pub(super) fn note_m5_submission_history(&self, submissions: u8) -> Result { - let mut geometry = self.m5_outer.lock(); - self.note_m5_submission_history_locked(&mut geometry, submissions) - } - - /// [`Self::note_m5_submission_history`] while the caller already holds `m5_outer`. + /// Counts `submissions` in the M5 submission-history table without taking the device mutex, + /// while the caller holds `m5_outer`. pub(super) fn note_m5_submission_history_locked( &self, geometry: &mut MutexGuard<'_, Option<(u32, u64, u64)>>, From 9e8f843d017cd4e0e5837cd5d9a4fa0fc3365520 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 11:13:12 +0000 Subject: [PATCH 1315/1514] arm64: dts: apple: t6041-j614c-j616c: move apple,sleep-ssps to shared dtsi Both the J614c and J616c share the four SN201202x port controllers (hpm0, hpm1, hpm2 and MagSafe's hpm5) defined in t6041-j614c-j616c.dtsi. Move apple,sleep-ssps from the J616c board file onto those shared controller nodes so both boards receive the same firmware-suspend SSPS handling without board-gating J616c. Signed-off-by: AxxzyWasTaken --- .../boot/dts/apple/t6041-j614c-j616c.dtsi | 4 ++++ arch/arm64/boot/dts/apple/t6041-j616c.dts | 18 ------------------ 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi index 95ead115f9eef9..b8197103686224 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi +++ b/arch/arm64/boot/dts/apple/t6041-j614c-j616c.dtsi @@ -1891,6 +1891,7 @@ <19 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec0: connector { compatible = "usb-c-connector"; @@ -1929,6 +1930,7 @@ <71 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; }; hpm1: usb-pd@a { @@ -1940,6 +1942,7 @@ <45 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec1: connector { compatible = "usb-c-connector"; @@ -1981,6 +1984,7 @@ <19 IRQ_TYPE_EDGE_RISING>; interrupt-names = "irq", "select", "sleep", "wake"; apple,event-irq-in-sleep; + apple,sleep-ssps; typec2: connector { compatible = "usb-c-connector"; diff --git a/arch/arm64/boot/dts/apple/t6041-j616c.dts b/arch/arm64/boot/dts/apple/t6041-j616c.dts index 65fce9f16c7491..ccdd779a5e5807 100644 --- a/arch/arm64/boot/dts/apple/t6041-j616c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j616c.dts @@ -169,21 +169,3 @@ &scaler1 { status = "okay"; }; - -/* The port controllers take system power state S3 for a firmware suspend, as macOS sends it. */ -&hpm0 { - apple,sleep-ssps; -}; - -&hpm1 { - apple,sleep-ssps; -}; - -&hpm2 { - apple,sleep-ssps; -}; - -/* MagSafe's controller follows the sleep too. */ -&hpm5 { - apple,sleep-ssps; -}; From cf3beec847e81b05fe9b7cc75caf6d5f29af58a6 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 11:07:43 +0000 Subject: [PATCH 1316/1514] accel/ane: h16: park an idle engine through runtime PM After boot bring-up the shared H16 backend keeps its five power domains (ane_sys, ane_cpu, ane_mpm, ane_td, ane_base) and three ANE DARTs powered until the next system sleep or reboot. On top of the backend's explicit references, the three DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE device links added by apple-dart hold the ANE IOMMUs active as long as the ANE platform device never runtime-suspends. Port the H17 runtime-PM idle-parking pattern to the H16 backend for every platform that cycles cold across sleep (sleep_cold && !sleep_warm: T6041/T6040, T8132, and T8122): - Enable runtime PM autosuspend (2000 ms default delay, tunable via power/autosuspend_delay_ms) on the bound platform device at probe, holding a reference until bring-up reaches the program stage (or releasing it on pre-RUN rollback). - In ane_h16_backend_runtime_suspend(), drain in-flight requests and close the session via ane_h16_session_sleep(true), verify no channel command is pending and autosuspend did not refresh, then call ane_h16_power_down() to drop the five power domains and explicit DART holds and leave the session parked. Returning 0 drops the DART device links so all three ANE IOMMUs save state and suspend, letting ane_sys power off too. - On the next request (ane_h16_session_wake()), resume the device: the PM core resumes the three DART suppliers first (restoring SID0 translations on ane_sys power-on), then ane_h16_backend_runtime_resume() cold-boots the engine from the verified preload DATA and replays all open programs behind their existing handles. If runtime PM was forbidden while a system sleep parked the engine, the wake path unparks it directly. - Hold a runtime PM reference across EXECUTE batches in ane_h16_busy() (guarded by rpm_busy so defensive power-down calls stay idempotent) and refresh last_busy on completion. - Keep a quarantined engine pinned on until reboot or hung_stop sleep recovery; guard runtime recovery work with pm_runtime_get_noresume() and pm_runtime_barrier(). - Handle system sleep cleanly whether active or already parked: PM_SUSPEND_PREPARE skips power-down when already parked, drops the device via pm_runtime_put_sync_suspend() when powered off, allows ane_h16_backend_suspend() backstop when engine_on is false, and PM_POST_SUSPEND keeps a non-quarantined engine parked until the next request. - Disable runtime PM cleanly on remove/unbind whether parked or active without waking the engine inside remove, double-powering down, or leaking supplier links. - Add KUnit coverage in ane_pm_test.c (real runtime-PM core + three DART device links + five domains, S2R while parked/active, and unbind) and ane_h16_program_test.c (idle park, deferred close, wake/replay across repeat runs, and S2R wake blocking). Signed-off-by: AxxzyWasTaken --- drivers/accel/ane/ane_fw_platform.c | 10 +- drivers/accel/ane/ane_fw_platform.h | 2 + drivers/accel/ane/ane_h16_backend.c | 532 +++++++++++++++++++---- drivers/accel/ane/ane_h16_program_test.c | 157 +++++++ drivers/accel/ane/ane_pm_test.c | 485 +++++++++++++++++++++ 5 files changed, 1090 insertions(+), 96 deletions(-) diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index 1963f6b6b10509..c3df3abf0a3945 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -706,13 +706,17 @@ int ane_fw_platform_resume(struct device *dev) return ane_h16_backend_resume(dev); } -/* Runtime PM callbacks: only the bound H17 device parks; H16 has none. */ +/* Runtime PM callbacks of the bound H16 or H17 device. */ int ane_fw_platform_runtime_suspend(struct device *dev) { - return ane_fw_staged_bound(dev) ? ane_fw_staged_runtime_suspend(dev) : 0; + if (ane_fw_staged_bound(dev)) + return ane_fw_staged_runtime_suspend(dev); + return ane_h16_backend_runtime_suspend(dev); } int ane_fw_platform_runtime_resume(struct device *dev) { - return ane_fw_staged_bound(dev) ? ane_fw_staged_runtime_resume(dev) : 0; + if (ane_fw_staged_bound(dev)) + return ane_fw_staged_runtime_resume(dev); + return ane_h16_backend_runtime_resume(dev); } diff --git a/drivers/accel/ane/ane_fw_platform.h b/drivers/accel/ane/ane_fw_platform.h index 4e7799273da539..bd553fe342e89b 100644 --- a/drivers/accel/ane/ane_fw_platform.h +++ b/drivers/accel/ane/ane_fw_platform.h @@ -205,5 +205,7 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat void ane_h16_backend_remove(struct platform_device *pdev); int ane_h16_backend_suspend(struct device *dev); int ane_h16_backend_resume(struct device *dev); +int ane_h16_backend_runtime_suspend(struct device *dev); +int ane_h16_backend_runtime_resume(struct device *dev); #endif /* __ANE_FW_PLATFORM_H__ */ diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c index be62b0e5c703e0..33197c1027ed1c 100644 --- a/drivers/accel/ane/ane_h16_backend.c +++ b/drivers/accel/ane/ane_h16_backend.c @@ -118,6 +118,14 @@ struct ane_h16_device { bool program_ready; /* Firmware suspended and the engine power gated for system sleep. */ bool slept; + /* Powered off at idle (or after system sleep) until the next request. */ + bool parked; + /* System sleep transition under way (PM_SUSPEND_PREPARE..PM_POST_SUSPEND). */ + bool in_sleep; + /* Runtime PM autosuspend enabled on h->dev, and our own holds on it. */ + bool rpm_enabled; + bool rpm_held; + bool rpm_busy; /* genpd's transitions of each of the five domains across a sleep. */ struct ane_h16_genpd { struct notifier_block nb; @@ -207,12 +215,53 @@ static void ane_h16_log(void *ctx, const char *item, u64 a, u64 b) dev_info(h->dev, "H16 %s %llx %llx\n", item, a, b); } +/* Engines that cycle cold across sleep park through runtime PM between requests. */ +static bool ane_h16_rpm(const struct ane_h16_device *h) +{ + return h->boot.soc->sleep_cold && !h->boot.soc->sleep_warm; +} + +/* + * The parked engine's autosuspend delay: a request that finds it parked waits + * for a cold boot from the preload and the replay of its programs (~10-18 ms). + * Two seconds keep that under 1% of a pause longer than the delay and prevent + * cycling power faster than every two seconds. power/autosuspend_delay_ms + * changes it; a negative value keeps the engine up until the next system sleep. + */ +#define ANE_H16_AUTOSUSPEND_MS 2000 + +static void ane_h16_rpm_pin(struct ane_h16_device *h) +{ + lockdep_assert_held(&ane_h16_lock); + if (h->rpm_enabled && h->engine_on && !h->rpm_held) { + pm_runtime_get_noresume(h->dev); + h->rpm_held = true; + } +} + +/* + * After bring-up: hand the device's runtime PM reference to autosuspend, which + * parks the engine once idle for ANE_H16_AUTOSUSPEND_MS. A quarantined engine + * keeps its reference. + */ +static void ane_h16_rpm_idle(struct ane_h16_device *h) +{ + lockdep_assert_held(&ane_h16_lock); + if (!h->rpm_enabled || !h->rpm_held || !h->program_ready || + h->boot.quarantined || h->session.quarantined) + return; + h->rpm_held = false; + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); +} + static void ane_h16_startup_fwlog(struct ane_h16_device *h); static void ane_h16_quarantine(void *ctx, int error) { struct ane_h16_device *h = ctx; + ane_h16_rpm_pin(h); if ((error == -ETIMEDOUT || error == -ESHUTDOWN) && h->boot.stage == ANE_H16_BOOT) ane_h16_startup_fwlog(h); @@ -340,8 +389,8 @@ static void ane_h16_power_down(struct ane_h16_device *h) pm_runtime_put_sync(h->dart[i]); for (i = h->powered; i-- > 0; ) pm_runtime_put_sync(h->power[i]); - h->engine_on = false; - dev_info(h->dev, "H16 ANE: powered down for system sleep\n"); + WRITE_ONCE(h->engine_on, false); + dev_info(h->dev, "H16 ANE: powered down\n"); } /* The five domains in order, then the DARTs (their resume restores SID0). */ @@ -360,7 +409,7 @@ static int ane_h16_power_up(struct ane_h16_device *h) if (ret < 0) goto dart; } - h->engine_on = true; + WRITE_ONCE(h->engine_on, true); return 0; dart: while (j--) @@ -478,8 +527,9 @@ static void ane_h16_genpd_record(struct ane_h16_device *h) * again. At runtime the ANE DARTs, which sit in it, hold it on, so it stays * on across a runtime power cycle of the other four. A firmware startup stall * on the J616s survives that, and is cleared once sys is off too, as it is in - * system sleep. The DARTs keep their SID0 state across it, as they do across - * system sleep (the ANE DART's suspend and resume neither save nor restore). + * system sleep. When sys powers off in runtime suspend or system sleep, the + * ANE DARTs suspend first and save/restore TTBR and TCR across the cycle; an + * isolated sys cycle leaves their SID0 state intact across the reset. */ static int ane_h16_sys_cycle(struct ane_h16_device *h) { @@ -593,15 +643,152 @@ static int ane_h16_boot_again(struct ane_h16_device *h, unsigned int *restarts, return ret; } -static int ane_h16_cold_boot(struct ane_h16_device *h) +static int ane_h16_cold_boot(struct ane_h16_device *h, unsigned int *restarts, + const char *what, const char *why, bool recover) { int ret; ret = ane_h16_power_cycle(h, false); if (ret) return ret; - return ane_h16_boot_again(h, &h->resume_restarts, "resume restart/budget", - "after system sleep", h->sleep_quarantined); + return ane_h16_boot_again(h, restarts, what, why, recover); +} + +/* + * Boot a parked engine from the preload, as after a cold system sleep, and + * replay every open program behind its handle. Caller holds ane_h16_lock. + */ +static void ane_h16_unpark(struct ane_h16_device *h) +{ + unsigned int restarts = 0; + u64 start; + int ret; + + lockdep_assert_held(&ane_h16_lock); + if (!h->parked || READ_ONCE(h->in_sleep)) + return; + start = ktime_get_ns(); + h->resume_ready_ns = 0; + h->resume_first_ns = 0; + h->resume_replayed = 0; + ret = ane_h16_cold_boot(h, &restarts, "wake restart/budget", + "on runtime wake", false); + WRITE_ONCE(h->parked, false); + WRITE_ONCE(h->session.parked, false); + if (ret) { + /* Power and mappings stay for diagnosis: quarantine pins the device. */ + ane_h16_quarantine(h, ret); + h->boot.quarantined = true; + h->session.quarantined = true; + } + ane_h16_session_sleep(&h->session, false); + dev_info(h->dev, "H16 ANE: up for a request%s in %llu ms, %u programs replayed, %u restarts\n", + ret ? " FAILED" : "", div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), + h->resume_replayed, restarts); +} + +/* + * A request for a parked engine: runtime PM resumes the device (and its + * DART suppliers) and its resume callback boots the engine. Called without + * ane_h16_lock, which the callback takes. + */ +static int ane_h16_session_wake(void *ctx) +{ + struct ane_h16_device *h = ctx; + int ret; + + if (!READ_ONCE(h->parked)) + return 0; + /* The system is going to sleep or coming back: PM_POST_SUSPEND wakes waiters. */ + if (READ_ONCE(h->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(h->dev); + if (ret < 0) + return ret; + /* + * Still parked: either the device never suspended (runtime PM forbidden + * or a negative autosuspend delay) and a system sleep parked the engine, + * or a system sleep began and prevented the resume callback from booting + * it. + */ + if (READ_ONCE(h->parked)) { + guard(mutex)(&ane_h16_lock); + ane_h16_unpark(h); + } + if (READ_ONCE(h->parked)) { + pm_runtime_put_sync_suspend(h->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + return READ_ONCE(h->session.quarantined) ? -EIO : 0; +} + +/* + * Runtime suspend after the autosuspend delay: drain in-flight requests, + * power down the five domains and explicit DART holds, and leave the session + * closed and parked. Returning 0 drops the DART device links so all three + * ANE IOMMUs and ANE_SYS power off until the next request. + */ +int ane_h16_backend_runtime_suspend(struct device *dev) +{ + struct ane_h16_device *h = dev_get_drvdata(dev); + + /* Powered off already (or pre-acquire): nothing to stop, no lock needed. */ + if (!h || !READ_ONCE(h->rpm_enabled) || !READ_ONCE(h->engine_on)) + return 0; + guard(mutex)(&ane_h16_lock); + if (!h->engine_on) + return 0; + /* Bringing up, quarantined, recovering, or in a system sleep. */ + if (!h->program_ready || READ_ONCE(h->in_sleep) || h->boot.quarantined || + READ_ONCE(h->session.quarantined) || READ_ONCE(h->recovering)) + return -EBUSY; + /* Closes admission, waits for requests in flight and releases gating. */ + ane_h16_session_sleep(&h->session, true); + /* Gate release quarantined it: leave recovery to ane_h16_hung(). */ + if (READ_ONCE(h->session.quarantined)) { + ane_h16_session_sleep(&h->session, false); + return -EBUSY; + } + /* + * An execute that raced the autosuspend boundary may have finished while + * draining and refreshed last_busy: wait out the new delay instead of + * parking right after it. + */ + if (pm_runtime_autosuspend_expiration(dev)) { + ane_h16_session_sleep(&h->session, false); + return -EBUSY; + } + for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { + if (h->boot.transport.pending[ch].active) { + /* Something is still pending on a ring: autosuspend tries later. */ + ane_h16_session_sleep(&h->session, false); + pm_runtime_mark_last_busy(dev); + return -EBUSY; + } + } + ane_h16_power_down(h); + WRITE_ONCE(h->parked, true); + WRITE_ONCE(h->session.parked, true); + wake_up_all(&h->session.wake); + dev_info(dev, "H16 ANE: idle: parked until the next request\n"); + return 0; +} + +/* Runtime resume for a request (ane_h16_session_wake()): boot the parked engine. */ +int ane_h16_backend_runtime_resume(struct device *dev) +{ + struct ane_h16_device *h = dev_get_drvdata(dev); + + /* Only a parked engine that serves programs is booted here. */ + if (!h || !READ_ONCE(h->rpm_enabled) || !READ_ONCE(h->program_ready) || + !READ_ONCE(h->parked)) + return 0; + guard(mutex)(&ane_h16_lock); + ane_h16_unpark(h); + /* A failed boot is the quarantine's to report: the device itself is up. */ + return 0; } /* @@ -646,15 +833,19 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) int ret; guard(mutex)(&ane_h16_lock); + /* Parked: already off, with nothing to stop. */ + if (h->parked) + return 0; for (unsigned int i = 0; i < ARRAY_SIZE(h->genpd); i++) { h->genpd[i].offs = 0; h->genpd[i].ons = 0; h->genpd[i].off_at = 0; h->genpd[i].off_ns = 0; } - h->sleep_quarantined = false; + WRITE_ONCE(h->sleep_quarantined, false); if (!h->program_ready || (h->boot.quarantined && !ane_t6021_hung_stop)) return -EBUSY; + ane_h16_session_sleep(&h->session, true); /* Without hung_stop a quarantined session stays so across the sleep. */ if (ane_t6021_hung_stop && (h->boot.quarantined || h->session.quarantined)) { unsigned int held; @@ -664,18 +855,20 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) * off under it, DARTs held until its domains are off, and boot * it cold on resume if every domain went off. */ - ane_h16_session_sleep(&h->session, true); if (h->engine_on) { held = ane_h16_hold_darts(h); ane_h16_power_down(h); ane_h16_release_darts(h, held); } - h->sleep_quarantined = true; + if (h->rpm_enabled && h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_noidle(h->dev); + } + WRITE_ONCE(h->sleep_quarantined, true); dev_info(h->dev, "H16 ANE: quarantined engine powered off for system sleep\n"); WRITE_ONCE(h->slept, true); return 0; } - ane_h16_session_sleep(&h->session, true); if (!h->boot.soc->sleep_warm) { /* Cold cycle: nothing in flight, then power off under the firmware. */ for (unsigned int ch = 0; ch < ANE_FW_CHANNELS; ch++) { @@ -704,57 +897,100 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) static void ane_h16_sleep_resume(struct ane_h16_device *h) { + bool rpm = READ_ONCE(h->rpm_enabled); + bool held = false; s64 ready, first; u64 start; int ret; - guard(mutex)(&ane_h16_lock); - if (!h->slept) - return; - start = ktime_get_ns(); - h->resume_ready_ns = 0; - h->resume_first_ns = 0; - h->resume_replayed = 0; - h->resume_cold = !h->boot.soc->sleep_warm || h->sleep_quarantined; - h->resume_restarts = 0; - if (h->sleep_quarantined && !ane_h16_slept_off(h)) { - /* Not proven off: the old firmware may still run. Keep it. */ - dev_err(h->dev, "H16 ANE: a domain of the quarantined engine never went off; kept quarantined\n"); - ret = ane_h16_power_up(h); - if (!ret) - ret = -EIO; - } else if (h->resume_cold) { - ret = ane_h16_cold_boot(h); - } else { - ret = ane_h16_warm_boot(h); + /* + * Normal runtime-PM sleep stays parked after wake until a request + * needs the engine. A quarantined engine being recovered by sleep + * needs the device active across its cold boot; take a reference + * outside ane_h16_lock so runtime resume cannot wait on the lock. + */ + if (rpm && READ_ONCE(h->slept) && READ_ONCE(h->sleep_quarantined) && + pm_runtime_resume_and_get(h->dev) >= 0) + held = true; + scoped_guard(mutex, &ane_h16_lock) { + if (!h->slept) + break; + if (rpm && !h->sleep_quarantined) { + WRITE_ONCE(h->slept, false); + WRITE_ONCE(h->parked, true); + WRITE_ONCE(h->session.parked, true); + ane_h16_genpd_record(h); + dev_info(h->dev, "H16 ANE: resume ok: parked until the next request\n"); + break; + } + start = ktime_get_ns(); + h->resume_ready_ns = 0; + h->resume_first_ns = 0; + h->resume_replayed = 0; + h->resume_cold = !h->boot.soc->sleep_warm || h->sleep_quarantined; + h->resume_restarts = 0; + if (h->sleep_quarantined && !ane_h16_slept_off(h)) { + /* Not proven off: the old firmware may still run. Keep it. */ + dev_err(h->dev, "H16 ANE: a domain of the quarantined engine never went off; kept quarantined\n"); + ret = ane_h16_power_up(h); + if (!ret) + ret = -EIO; + } else if (h->resume_cold) { + ret = ane_h16_cold_boot(h, &h->resume_restarts, "resume restart/budget", + "after system sleep", h->sleep_quarantined); + } else { + ret = ane_h16_warm_boot(h); + if (ret) { + dev_warn(h->dev, "H16 ANE: warm boot failed (%d); cold boot and program replay\n", + ret); + h->resume_cold = true; + ret = ane_h16_cold_boot(h, &h->resume_restarts, + "resume restart/budget", + "after system sleep", false); + } + } + WRITE_ONCE(h->slept, false); if (ret) { - dev_warn(h->dev, "H16 ANE: warm boot failed (%d); cold boot and program replay\n", - ret); - h->resume_cold = true; - ret = ane_h16_cold_boot(h); + /* Every mapping and backing stays for diagnosis. */ + ane_h16_quarantine(h, ret); + h->boot.quarantined = true; + h->session.quarantined = true; + } else if (h->sleep_quarantined) { + h->recoveries++; + dev_info(h->dev, "H16 ANE: quarantined engine recovered by system sleep\n"); } + WRITE_ONCE(h->sleep_quarantined, false); + ane_h16_session_sleep(&h->session, false); + ane_h16_genpd_record(h); + /* One line per wake; times from PM_POST_SUSPEND, which follows the thaw. */ + ready = h->resume_ready_ns ? + div_u64(h->resume_ready_ns - start, NSEC_PER_MSEC) : -1; + first = h->resume_first_ns ? + div_u64(h->resume_first_ns - start, NSEC_PER_MSEC) : -1; + dev_info(h->dev, + "H16 ANE: resume %s: %s, firmware ready %lld ms, first program ready %lld ms, node reopened %llu ms, %u programs replayed, %u restarts\n", + ret ? "FAILED" : "ok", h->resume_cold ? "cold" : "warm", ready, first, + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed, + h->resume_restarts); } - WRITE_ONCE(h->slept, false); - if (ret) { - /* Every mapping and backing stays for diagnosis. */ - ane_h16_quarantine(h, ret); - h->boot.quarantined = true; - h->session.quarantined = true; - } else if (h->sleep_quarantined) { - h->recoveries++; - dev_info(h->dev, "H16 ANE: quarantined engine recovered by system sleep\n"); + if (held) { + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); } - h->sleep_quarantined = false; - ane_h16_session_sleep(&h->session, false); - ane_h16_genpd_record(h); - /* One line per wake; times from PM_POST_SUSPEND, which follows the thaw. */ - ready = h->resume_ready_ns ? div_u64(h->resume_ready_ns - start, NSEC_PER_MSEC) : -1; - first = h->resume_first_ns ? div_u64(h->resume_first_ns - start, NSEC_PER_MSEC) : -1; - dev_info(h->dev, - "H16 ANE: resume %s: %s, firmware ready %lld ms, first program ready %lld ms, node reopened %llu ms, %u programs replayed, %u restarts\n", - ret ? "FAILED" : "ok", h->resume_cold ? "cold" : "warm", ready, first, - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed, - h->resume_restarts); +} + +/* + * Clear the sleep gates on PM_POST_SUSPEND or when PM_SUSPEND_PREPARE refuses + * a transition (the PM core does not send PM_POST_SUSPEND to the refusing + * notifier). + */ +static void ane_h16_sleep_unblock(struct ane_h16_device *h) +{ + WRITE_ONCE(h->in_sleep, false); + WRITE_ONCE(h->session.wake_blocked, false); + WRITE_ONCE(h->recover_blocked, false); + if (READ_ONCE(h->program_ready)) + wake_up_all(&h->session.wake); } static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void *unused) @@ -777,16 +1013,39 @@ static int ane_h16_pm_event(struct notifier_block *nb, unsigned long event, void } if (event == PM_POST_SUSPEND) { ane_h16_sleep_resume(h); - WRITE_ONCE(h->recover_blocked, false); + ane_h16_sleep_unblock(h); return NOTIFY_DONE; } if (event == PM_SUSPEND_PREPARE && pinned) { + struct device *dev = h->dev; + bool rpm = READ_ONCE(h->rpm_enabled); + int ret; + + WRITE_ONCE(h->in_sleep, true); + WRITE_ONCE(h->session.wake_blocked, true); /* A recovery under way finishes first; sleep handles later ones. */ WRITE_ONCE(h->recover_blocked, true); flush_work(&h->recover); - if (!ane_h16_sleep_prepare(h)) + /* + * No idle park from here on: the sleep takes the engine down + * itself. A park that already began finishes first (the sleep + * waits for ane_h16_lock and finds the engine parked). + */ + if (rpm) + pm_runtime_get_noresume(dev); + ret = ane_h16_sleep_prepare(h); + if (rpm) { + if (!ret && !READ_ONCE(h->engine_on)) { + /* Off now: suspend so the DART links drop too. */ + pm_runtime_put_sync_suspend(dev); + } else { + pm_runtime_mark_last_busy(dev); + pm_runtime_put_autosuspend(dev); + } + } + if (!ret) return NOTIFY_DONE; - WRITE_ONCE(h->recover_blocked, false); + ane_h16_sleep_unblock(h); dev_warn_once(h->dev, ANE_FW_SLEEP_REFUSED); return NOTIFY_BAD; } @@ -828,7 +1087,8 @@ int ane_h16_backend_suspend(struct device *dev) { struct ane_h16_device *h = dev_get_drvdata(dev); /* Running firmware that the notifier did not suspend: refuse. */ - bool running = h && READ_ONCE(h->pinned) && !READ_ONCE(h->slept); + bool running = h && READ_ONCE(h->pinned) && READ_ONCE(h->engine_on) && + !READ_ONCE(h->slept); if (running) dev_warn_once(dev, ANE_FW_SLEEP_REFUSED); @@ -1501,32 +1761,57 @@ static void ane_h16_recover_work(struct work_struct *work) [ANE_T6021_RESTART_DONE] = "done", }; enum ane_t6021_restart_stage stage; + bool rpm = READ_ONCE(h->rpm_enabled), held = false, reschedule = false; u64 start = ktime_get_ns(); int ret; - guard(mutex)(&ane_h16_lock); - if (READ_ONCE(h->recover_blocked) || h->slept || !h->program_ready || - h->boot.quarantined || !h->session.quarantined || !ane_t6021_hung_stop) { + /* + * Keep runtime PM from starting a park and wait for any park in flight + * before taking ane_h16_lock. + */ + if (rpm) { + pm_runtime_get_noresume(h->dev); + pm_runtime_barrier(h->dev); + held = true; + } + scoped_guard(mutex, &ane_h16_lock) { + if (READ_ONCE(h->recover_blocked) || h->slept || h->parked || + !h->program_ready || h->boot.quarantined || + !h->session.quarantined || !ane_t6021_hung_stop) { + reschedule = h->program_ready && !h->parked && !h->slept && + !READ_ONCE(h->in_sleep) && !h->boot.quarantined && + !h->session.quarantined; + WRITE_ONCE(h->recovering, false); + break; + } + ane_h16_session_sleep(&h->session, true); + h->resume_replayed = 0; + h->resume_first_ns = 0; + ret = ane_t6021_restart_run(&ane_h16_restart_ops, h, false, &stage); + if (ret) { + h->recover_failures++; + dev_err(h->dev, + "H16 ANE: recovery after a hung request failed at the %s, error %d; quarantined until the next system sleep\n", + stages[stage], ret); + } else { + h->recoveries++; + reschedule = true; + dev_info(h->dev, + "H16 ANE: firmware recovered after a hung request in %llu ms, %u programs replayed\n", + div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), + h->resume_replayed); + } + ane_h16_session_sleep(&h->session, false); WRITE_ONCE(h->recovering, false); - return; } - ane_h16_session_sleep(&h->session, true); - h->resume_replayed = 0; - h->resume_first_ns = 0; - ret = ane_t6021_restart_run(&ane_h16_restart_ops, h, false, &stage); - if (ret) { - h->recover_failures++; - dev_err(h->dev, - "H16 ANE: recovery after a hung request failed at the %s, error %d; quarantined until the next system sleep\n", - stages[stage], ret); - } else { - h->recoveries++; - dev_info(h->dev, - "H16 ANE: firmware recovered after a hung request in %llu ms, %u programs replayed\n", - div_u64(ktime_get_ns() - start, NSEC_PER_MSEC), h->resume_replayed); + if (held) { + if (reschedule) { + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + } else { + pm_runtime_put_noidle(h->dev); + } } - ane_h16_session_sleep(&h->session, false); - WRITE_ONCE(h->recovering, false); } /* Session ops->hung: may run under the session lock, so only queue. */ @@ -1546,6 +1831,7 @@ static const struct ane_h16_session_ops ane_h16_session_ops = { .unmap = ane_h16_program_unmap, .log = ane_h16_log, .busy = ane_h16_busy, + .wake = ane_h16_session_wake, .hung = ane_h16_hung, }; @@ -1628,6 +1914,7 @@ static void ane_h16_release(struct ane_h16_device *h) pm_runtime_put_sync(pd); dev_pm_domain_detach(pd, true); } + WRITE_ONCE(h->engine_on, false); h->acquired = false; vfree(h->pristine_data); h->pristine_data = NULL; @@ -1678,6 +1965,17 @@ static void ane_h16_busy(void *ctx, bool busy) struct ane_h16_device *h = ctx; apple_clpc_ane_set_active(h->clpc, busy); + /* Under the session lock: no callback runs here, the park drains first. */ + if (READ_ONCE(h->rpm_enabled)) { + if (busy && !h->rpm_busy) { + pm_runtime_get_noresume(h->dev); + h->rpm_busy = true; + } else if (!busy && h->rpm_busy) { + h->rpm_busy = false; + pm_runtime_mark_last_busy(h->dev); + pm_runtime_put_autosuspend(h->dev); + } + } if (!h->perf) return; if (busy) { @@ -1798,7 +2096,7 @@ static int ane_h16_acquire(struct platform_device *pdev, struct ane_h16_device * if (ret < 0) return ret; h->darts_powered++; - h->engine_on = h->darts_powered == ARRAY_SIZE(h->dart); + WRITE_ONCE(h->engine_on, h->darts_powered == ARRAY_SIZE(h->dart)); h->window[ANE_H16_DART0 + i] = ioremap_np(r.start, resource_size(&r)); if (!h->window[ANE_H16_DART0 + i]) return -ENOMEM; @@ -1930,7 +2228,7 @@ static int ane_h16_program_stage(struct ane_h16_device *h) ret); return ret; } - h->program_ready = true; + WRITE_ONCE(h->program_ready, true); ane_h16_irq_wait_set(h, true); dev_info(h->dev, "H16 stage 5 program window %llx..%llx%s\n", h->program_start, h->program_end - 1, h->clpc ? ", CLPC input attached" : ""); @@ -1979,6 +2277,7 @@ static int ane_h16_advance(struct ane_h16_device *h, enum ane_h16_stage stage) h->refused = true; return ret; } + ane_h16_rpm_idle(h); } dev_info(h->dev, "H16 stage %s complete%s\n", ane_h16_stage_name(stage), h->boot.ran ? "; held until reboot" : ""); @@ -1988,6 +2287,10 @@ static int ane_h16_advance(struct ane_h16_device *h, enum ane_h16_stage stage) ane_h16_stage_name(stage), ret); h->refused = true; ane_h16_release(h); + if (h->rpm_enabled && h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_sync_suspend(h->dev); + } return ret; } @@ -2214,19 +2517,36 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat ret = register_pm_notifier(&h->pm_notifier); if (ret) { dev_err(h->dev, "H16 PM notifier refused, error %d\n", ret); - debugfs_remove_recursive(h->debugfs); - mutex_lock(&ane_h16_lock); - if (!--ane_h16_debugfs_users) { - debugfs_remove_recursive(ane_h16_debugfs); - ane_h16_debugfs = NULL; + goto err_notifier; + } + if (ane_h16_rpm(h)) { + ret = pm_runtime_set_active(h->dev); + if (ret) { + dev_err(h->dev, "H16 runtime PM activation refused, error %d\n", ret); + unregister_pm_notifier(&h->pm_notifier); + goto err_notifier; } - mutex_unlock(&ane_h16_lock); - platform_set_drvdata(pdev, NULL); - kfree(h); - return ret; + pm_runtime_get_noresume(h->dev); + h->rpm_held = true; + pm_runtime_set_autosuspend_delay(h->dev, ANE_H16_AUTOSUSPEND_MS); + pm_runtime_use_autosuspend(h->dev); + WRITE_ONCE(h->rpm_enabled, true); + pm_runtime_enable(h->dev); } schedule_work(&h->start); return 0; +err_notifier: + debugfs_remove_recursive(h->debugfs); + mutex_lock(&ane_h16_lock); + if (!--ane_h16_debugfs_users) { + debugfs_remove_recursive(ane_h16_debugfs); + ane_h16_debugfs = NULL; + } + mutex_unlock(&ane_h16_lock); + platform_set_drvdata(pdev, NULL); + drm_mm_takedown(&h->program_window); + kfree(h); + return ret; free: dev_err(h->dev, "H16 DT description refused, error %d\n", ret); drm_mm_takedown(&h->program_window); @@ -2239,26 +2559,48 @@ int ane_h16_backend_probe(struct platform_device *pdev, const struct ane_fw_plat void ane_h16_backend_remove(struct platform_device *pdev) { struct ane_h16_device *h = platform_get_drvdata(pdev); - bool keep; + bool keep, rpm_was_enabled; if (!h) return; /* Waits for the boot bring-up and any stage write in progress. */ cancel_work_sync(&h->start); cancel_work_sync(&h->recover); - if (h->program_ready) { + if (READ_ONCE(h->program_ready)) { cancel_delayed_work_sync(&h->session.gate_work); /* Return released exports; mapped ones stay with their mappings. */ flush_work(&h->session.export_work); } debugfs_remove_recursive(h->debugfs); + /* + * Stop runtime PM outside ane_h16_lock before touching state: waits for + * any in-flight park or wake callback and prevents new ones. A parked + * device stays suspended; an active device stays active. + */ + rpm_was_enabled = READ_ONCE(h->rpm_enabled); + if (rpm_was_enabled) { + pm_runtime_disable(h->dev); + pm_runtime_dont_use_autosuspend(h->dev); + } /* * Nothing can pin the device any more: the start work, the recovery * and the stage file are gone. An unpinned device drops its PM * notifier here, outside ane_h16_lock; a pinned one keeps it. */ - scoped_guard(mutex, &ane_h16_lock) + scoped_guard(mutex, &ane_h16_lock) { keep = h->boot.ran || h->pinned; + if (h->rpm_enabled) { + if (h->rpm_held) { + h->rpm_held = false; + pm_runtime_put_noidle(h->dev); + } + if (h->rpm_busy) { + h->rpm_busy = false; + pm_runtime_put_noidle(h->dev); + } + WRITE_ONCE(h->rpm_enabled, false); + } + } if (!keep) unregister_pm_notifier(&h->pm_notifier); mutex_lock(&ane_h16_lock); @@ -2272,7 +2614,11 @@ void ane_h16_backend_remove(struct platform_device *pdev) } else { ane_h16_release(h); drm_mm_takedown(&h->program_window); + platform_set_drvdata(pdev, NULL); kfree(h); } mutex_unlock(&ane_h16_lock); + /* Drop any remaining supplier device-link holds after pre-RUN rollback. */ + if (!keep && rpm_was_enabled) + pm_runtime_set_suspended(&pdev->dev); } diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index ad746c14c7fa8a..6a48bbf030e24e 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -80,6 +80,9 @@ struct prog_fw { /* ops->hung calls and the error of the last one. */ unsigned int hung; int hung_error; + /* ops->wake calls and replayed programs during runtime-PM unpark tests. */ + unsigned int wakes; + unsigned int wake_replayed; /* * Bytes mapped and not unmapped, ops->unmap calls, the most bytes a * nonzero window lets be mapped at once (-ENOSPC beyond), and the @@ -3565,6 +3568,158 @@ static void program_recover_gate_test(struct kunit *test) ane_h16_session_put(&f->s, p); } +static void fw_cold_boot(struct prog_fw *f); + +static int fw_rpm_wake(void *ctx) +{ + struct prog_fw *f = ctx; + u64 first = 0; + int ret; + + if (!READ_ONCE(f->s.parked)) + return 0; + if (READ_ONCE(f->s.wake_blocked)) + return -EAGAIN; + f->wakes++; + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ret = ane_h16_session_replay(&f->s, &f->wake_replayed, &first); + WRITE_ONCE(f->s.parked, false); + ane_h16_session_sleep(&f->s, false); + return ret; +} + +static const struct ane_h16_session_ops fw_session_ops_rpm = { + .map = fw_map, + .unmap = fw_unmap, + .log = fw_log, + .busy = fw_busy, + .sync = fw_sync, + .wake = fw_rpm_wake, + .hung = fw_hung, +}; + +/* + * H16 runtime-PM idle park + wake/replay across repeat add128 runs: + * closing a program while parked defers teardown without unmapping, waking + * cold-boots and replays still-open programs behind their handles, releases + * deferred closes once back up, and runs repeat EXECUTEs with zero faults. + */ +static void program_rpm_park_wake_replay_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *a = NULL, *b = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + u8 *exec = kunit_kzalloc(test, sizeof(f->exec), GFP_KERNEL); + size_t exec_length; + unsigned int round; + u32 prog_id; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + KUNIT_ASSERT_NOT_NULL(test, exec); + mutex_init(lock); + f->s.lock = lock; + f->s.ops = &fw_session_ops_rpm; + f->strict = true; + + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &a), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &b), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + mutex_unlock(lock); + memcpy(exec, f->exec, sizeof(f->exec)); + exec_length = f->exec_length; + KUNIT_EXPECT_EQ(test, f->busy_on, 1U); + KUNIT_EXPECT_EQ(test, f->busy_off, 1U); + KUNIT_EXPECT_EQ(test, f->busy_depth, 0); + + /* First park: close b while parked (deferred, no unmap while parked). */ + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + mutex_lock(lock); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, b), -EINPROGRESS); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, f->unmaps, 0U); + + /* Two park/wake cycles running the same add128 handle cleanly. */ + for (round = 1; round <= 2; round++) { + prog_id = a->key.program; + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, f->wakes, round); + KUNIT_EXPECT_EQ(test, f->wake_replayed, 1U); + KUNIT_EXPECT_FALSE(test, f->s.parked); + KUNIT_EXPECT_EQ(test, a->key.program, prog_id + 0x10); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + mutex_unlock(lock); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(f->exec + 0x30), + ANE_H16_EXECUTE_FLAG_QUEUED); + KUNIT_EXPECT_EQ(test, f->exec_length, exec_length); + KUNIT_EXPECT_EQ(test, memcmp(f->exec + 0x34, exec + 0x34, + exec_length - 0x34), 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + if (round == 1) { + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + } + } + + KUNIT_EXPECT_EQ(test, f->busy_on, 3U); + KUNIT_EXPECT_EQ(test, f->busy_off, 3U); + mutex_lock(lock); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, a), 0); + mutex_unlock(lock); + ane_h16_session_put(&f->s, a); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); +} + +/* + * System sleep while already parked blocks ops->wake (-EAGAIN) without + * booting; after PM_POST_SUSPEND unblocks it, the next request wakes and + * replays the open program cleanly. + */ +static void program_rpm_s2r_while_parked_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.lock = lock; + f->s.ops = &fw_session_ops_rpm; + f->strict = true; + + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + mutex_unlock(lock); + + /* Idle park, then S2R starts while parked. */ + ane_h16_session_sleep(&f->s, true); + WRITE_ONCE(f->s.parked, true); + WRITE_ONCE(f->s.wake_blocked, true); + + /* O_NONBLOCK sees -EAGAIN and never wakes the engine during sleep. */ + KUNIT_EXPECT_EQ(test, ane_h16_session_enter(&f->s, true), -EAGAIN); + KUNIT_EXPECT_EQ(test, f->wakes, 0U); + KUNIT_EXPECT_TRUE(test, f->s.parked); + KUNIT_EXPECT_TRUE(test, f->s.asleep); + + /* PM_POST_SUSPEND unblocks wake; next request wakes and replays p. */ + WRITE_ONCE(f->s.wake_blocked, false); + wake_up_all(&f->s.wake); + KUNIT_ASSERT_EQ(test, ane_h16_session_enter(&f->s, false), 0); + KUNIT_EXPECT_EQ(test, f->wakes, 1U); + KUNIT_EXPECT_EQ(test, f->wake_replayed, 1U); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_close(&f->s, p), 0); + mutex_unlock(lock); + ane_h16_session_put(&f->s, p); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); +} + static struct kunit_case program_cases[] = { KUNIT_CASE_SLOW(program_pool_rewind_test), KUNIT_CASE_SLOW(program_pool_resident_test), @@ -3595,6 +3750,8 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_sleep_gate_test), KUNIT_CASE(program_sleep_gate_quarantine_test), KUNIT_CASE(program_recover_gate_test), + KUNIT_CASE(program_rpm_park_wake_replay_test), + KUNIT_CASE(program_rpm_s2r_while_parked_test), KUNIT_CASE(program_sleep_keeps_program_test), KUNIT_CASE(program_sleep_restart_test), KUNIT_CASE(program_sleep_restart_deferred_test), diff --git a/drivers/accel/ane/ane_pm_test.c b/drivers/accel/ane/ane_pm_test.c index 5c372a2a730113..d01117e09ad292 100644 --- a/drivers/accel/ane/ane_pm_test.c +++ b/drivers/accel/ane/ane_pm_test.c @@ -1,9 +1,12 @@ // SPDX-License-Identifier: GPL-2.0-only OR MIT /* Exercise recovery against the real runtime-PM and device-link core. */ #include +#include #include +#include #include +#include "ane_fw_sleep.h" #include "ane_pm.h" struct ane_pm_test_dev { @@ -228,6 +231,484 @@ static void ane_pm_cycle_resume_error_test(struct kunit *test) pm_runtime_put_noidle(ctx.consumer); } +/* + * Exercise the H16 runtime-PM idle-park, wake, system-sleep and unbind model + * against the real Linux runtime-PM and device-link core: one consumer device + * linked to three DART suppliers (DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE) + * plus five attached power-domain devices. + */ +struct ane_h16_rpm_sim { + struct device dev; + struct device *power[5]; + struct device *dart[3]; + struct device_link *links[3]; + /* Serializes simulated power-state and park transitions. */ + struct mutex lock; + bool engine_on; + bool program_ready; + bool parked; + bool slept; + bool in_sleep; + bool pinned; + bool rpm_enabled; + bool rpm_held; + bool rpm_busy; + unsigned int power_downs; + unsigned int power_ups; + unsigned int parks; + unsigned int unparks; + bool dart_active_at_resume; +}; + +static void h16_sim_power_down(struct ane_h16_rpm_sim *s) +{ + int i; + + for (i = ARRAY_SIZE(s->dart); i-- > 0; ) + pm_runtime_put_sync(s->dart[i]); + for (i = ARRAY_SIZE(s->power); i-- > 0; ) + pm_runtime_put_sync(s->power[i]); + WRITE_ONCE(s->engine_on, false); + s->power_downs++; +} + +static int h16_sim_power_up(struct ane_h16_rpm_sim *s) +{ + int i, j, ret; + + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + ret = pm_runtime_resume_and_get(s->power[i]); + if (ret < 0) + goto err_power; + } + for (j = 0; j < ARRAY_SIZE(s->dart); j++) { + ret = pm_runtime_resume_and_get(s->dart[j]); + if (ret < 0) + goto err_dart; + } + WRITE_ONCE(s->engine_on, true); + s->power_ups++; + return 0; +err_dart: + while (j--) + pm_runtime_put_sync(s->dart[j]); +err_power: + while (i--) + pm_runtime_put_sync(s->power[i]); + return ret; +} + +static void h16_sim_unpark(struct ane_h16_rpm_sim *s) +{ + lockdep_assert_held(&s->lock); + if (!s->parked || READ_ONCE(s->in_sleep)) + return; + if (!h16_sim_power_up(s)) + s->unparks++; + WRITE_ONCE(s->parked, false); +} + +static int h16_sim_runtime_suspend(struct device *dev) +{ + struct ane_h16_rpm_sim *s = container_of(dev, struct ane_h16_rpm_sim, dev); + + if (!READ_ONCE(s->rpm_enabled) || !READ_ONCE(s->engine_on)) + return 0; + mutex_lock(&s->lock); + if (!s->engine_on) { + mutex_unlock(&s->lock); + return 0; + } + if (!s->program_ready || READ_ONCE(s->in_sleep)) { + mutex_unlock(&s->lock); + return -EBUSY; + } + if (pm_runtime_autosuspend_expiration(dev)) { + mutex_unlock(&s->lock); + return -EBUSY; + } + h16_sim_power_down(s); + WRITE_ONCE(s->parked, true); + s->parks++; + mutex_unlock(&s->lock); + return 0; +} + +static int h16_sim_runtime_resume(struct device *dev) +{ + struct ane_h16_rpm_sim *s = container_of(dev, struct ane_h16_rpm_sim, dev); + bool all_darts_active = true; + int i; + + for (i = 0; i < ARRAY_SIZE(s->dart); i++) + all_darts_active &= pm_runtime_active(s->dart[i]); + s->dart_active_at_resume = all_darts_active; + + if (!READ_ONCE(s->rpm_enabled) || !READ_ONCE(s->program_ready) || + !READ_ONCE(s->parked)) + return 0; + mutex_lock(&s->lock); + h16_sim_unpark(s); + mutex_unlock(&s->lock); + return 0; +} + +static const struct dev_pm_ops h16_sim_pm_ops = { + .runtime_suspend = h16_sim_runtime_suspend, + .runtime_resume = h16_sim_runtime_resume, +}; + +static const struct device_type h16_sim_type = { + .pm = &h16_sim_pm_ops, +}; + +static void h16_sim_release(struct device *dev) +{ + kfree(container_of(dev, struct ane_h16_rpm_sim, dev)); +} + +static void h16_sim_unregister(void *data) +{ + struct ane_h16_rpm_sim *s = data; + + device_unregister(&s->dev); +} + +static void h16_sim_power_cleanup(void *data) +{ + struct ane_h16_rpm_sim *s = data; + + if (READ_ONCE(s->rpm_enabled)) { + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + if (s->rpm_held) { + s->rpm_held = false; + pm_runtime_put_noidle(&s->dev); + } + if (s->rpm_busy) { + s->rpm_busy = false; + pm_runtime_put_noidle(&s->dev); + } + WRITE_ONCE(s->rpm_enabled, false); + } + if (READ_ONCE(s->engine_on)) + h16_sim_power_down(s); + pm_runtime_set_suspended(&s->dev); +} + +static struct ane_h16_rpm_sim *h16_sim_create(struct kunit *test, int delay_ms) +{ + static const char * const pd_names[] = { + "h16-ane-sys", "h16-ane-cpu", "h16-ane-mpm", + "h16-ane-td", "h16-ane-base", + }; + static const char * const dart_names[] = { + "h16-ane-dart0", "h16-ane-dart1", "h16-ane-dart2", + }; + struct ane_h16_rpm_sim *s; + int i, ret; + + s = kzalloc_obj(*s); + if (!s) + return NULL; + mutex_init(&s->lock); + device_initialize(&s->dev); + s->dev.release = h16_sim_release; + s->dev.type = &h16_sim_type; + ret = dev_set_name(&s->dev, "h16-ane-rpm-consumer"); + if (!ret) + ret = device_add(&s->dev); + if (ret) { + put_device(&s->dev); + return NULL; + } + if (kunit_add_action_or_reset(test, h16_sim_unregister, s)) + return NULL; + + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + s->power[i] = ane_pm_test_register(test, pd_names[i]); + if (!s->power[i]) + return NULL; + } + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + s->dart[i] = ane_pm_test_register(test, dart_names[i]); + if (!s->dart[i]) + return NULL; + /* Matches apple_dart_probe_device() supplier links. */ + s->links[i] = device_link_add(&s->dev, s->dart[i], + DL_FLAG_STATELESS | + DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!s->links[i]) + return NULL; + if (kunit_add_action_or_reset(test, ane_pm_test_unlink, s->links[i])) + return NULL; + } + /* LIFO: drop power and disable runtime PM before links/suppliers go. */ + if (kunit_add_action_or_reset(test, h16_sim_power_cleanup, s)) + return NULL; + KUNIT_ASSERT_EQ(test, pm_runtime_set_active(&s->dev), 0); + pm_runtime_get_noresume(&s->dev); + s->rpm_held = true; + pm_runtime_set_autosuspend_delay(&s->dev, delay_ms); + pm_runtime_use_autosuspend(&s->dev); + WRITE_ONCE(s->rpm_enabled, true); + pm_runtime_enable(&s->dev); + + KUNIT_ASSERT_EQ(test, h16_sim_power_up(s), 0); + /* First boot power-up is not counted as an unpark/wake power-up. */ + s->power_ups = 0; + s->pinned = true; + WRITE_ONCE(s->program_ready, true); + return s; +} + +static void h16_sim_wait_darts_suspended(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i, tries; + + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + for (tries = 0; tries < 40 && !pm_runtime_suspended(s->dart[i]); tries++) + usleep_range(10000, 15000); + } +} + +static void h16_sim_wait_suspended(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i; + + for (i = 0; i < 40 && !pm_runtime_suspended(&s->dev); i++) + usleep_range(10000, 15000); + pm_runtime_barrier(&s->dev); + KUNIT_ASSERT_TRUE(test, pm_runtime_suspended(&s->dev)); + h16_sim_wait_darts_suspended(test, s); +} + +static void h16_sim_expect_all_off(struct kunit *test, struct ane_h16_rpm_sim *s) +{ + int i; + + KUNIT_EXPECT_TRUE(test, pm_runtime_status_suspended(&s->dev)); + KUNIT_EXPECT_EQ(test, atomic_read(&s->dev.power.usage_count), 0); + for (i = 0; i < ARRAY_SIZE(s->dart); i++) { + KUNIT_EXPECT_TRUE(test, pm_runtime_suspended(s->dart[i])); + KUNIT_EXPECT_EQ(test, atomic_read(&s->dart[i]->power.usage_count), 0); + } + for (i = 0; i < ARRAY_SIZE(s->power); i++) { + KUNIT_EXPECT_TRUE(test, pm_runtime_suspended(s->power[i])); + KUNIT_EXPECT_EQ(test, atomic_read(&s->power[i]->power.usage_count), 0); + } +} + +static int h16_sim_session_wake(struct ane_h16_rpm_sim *s) +{ + int ret; + + if (!READ_ONCE(s->parked)) + return 0; + if (READ_ONCE(s->in_sleep)) + return -EAGAIN; + ret = pm_runtime_resume_and_get(&s->dev); + if (ret < 0) + return ret; + if (READ_ONCE(s->parked)) { + mutex_lock(&s->lock); + h16_sim_unpark(s); + mutex_unlock(&s->lock); + } + if (READ_ONCE(s->parked)) { + pm_runtime_put_sync_suspend(&s->dev); + return -EAGAIN; + } + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + return 0; +} + +/* + * Idle autosuspend parks H16: all five power domains and all three DART + * suppliers drop to suspended with usage_count == 0. Waking resumes the + * DART suppliers before the consumer callback powers the five domains up. + */ +static void ane_pm_h16_idle_park_wake_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 80); + int i; + + KUNIT_ASSERT_NOT_NULL(test, s); + + /* Hand off boot hold to autosuspend. */ + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + + /* Simulate an EXECUTE busy hold blocking suspend while in flight. */ + pm_runtime_get_noresume(&s->dev); + s->rpm_busy = true; + msleep(120); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(&s->dev)); + KUNIT_EXPECT_FALSE(test, s->parked); + + /* End EXECUTE: autosuspend parks consumer, 5 domains and 3 DARTs. */ + s->rpm_busy = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_EXPECT_TRUE(test, s->parked); + KUNIT_EXPECT_FALSE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->parks, 1U); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + h16_sim_expect_all_off(test, s); + + /* Wake for a request: DARTs resume first, then 5 domains power up. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_TRUE(test, s->dart_active_at_resume); + KUNIT_EXPECT_FALSE(test, s->parked); + KUNIT_EXPECT_TRUE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->unparks, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 1U); + for (i = 0; i < ARRAY_SIZE(s->power); i++) + KUNIT_EXPECT_TRUE(test, pm_runtime_active(s->power[i])); + for (i = 0; i < ARRAY_SIZE(s->dart); i++) + KUNIT_EXPECT_TRUE(test, pm_runtime_active(s->dart[i])); + + /* Second idle park + wake cycle stays clean and balanced. */ + h16_sim_wait_suspended(test, s); + KUNIT_EXPECT_EQ(test, s->parks, 2U); + KUNIT_EXPECT_EQ(test, s->power_downs, 2U); + h16_sim_expect_all_off(test, s); + + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_EQ(test, s->unparks, 2U); + KUNIT_EXPECT_EQ(test, s->power_ups, 2U); + KUNIT_EXPECT_TRUE(test, s->engine_on); +} + +/* + * System S2R while already parked does no double power_down or double + * power_up and passes the device-suspend backstop. S2R while active powers + * down once, suspends the DARTs, and stays parked on resume (including the + * pm_runtime_forbid fallback wake path). + */ +static void ane_pm_h16_s2r_while_parked_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 80); + bool running; + + KUNIT_ASSERT_NOT_NULL(test, s); + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_ASSERT_EQ(test, s->power_downs, 1U); + + /* S2R prepare while already parked: no second power_down. */ + WRITE_ONCE(s->in_sleep, true); + pm_runtime_get_noresume(&s->dev); + mutex_lock(&s->lock); + if (!s->parked) { + h16_sim_power_down(s); + WRITE_ONCE(s->slept, true); + } + mutex_unlock(&s->lock); + pm_runtime_put_sync_suspend(&s->dev); + + /* Device-suspend backstop must allow sleep while parked. */ + running = s->pinned && READ_ONCE(s->engine_on) && !READ_ONCE(s->slept); + KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(running), 0); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + KUNIT_EXPECT_FALSE(test, s->slept); + /* Requests during S2R get -EAGAIN without booting. */ + KUNIT_EXPECT_EQ(test, h16_sim_session_wake(s), -EAGAIN); + + /* S2R resume while parked: no power_up, stays parked. */ + WRITE_ONCE(s->in_sleep, false); + KUNIT_EXPECT_EQ(test, s->power_ups, 0U); + KUNIT_EXPECT_TRUE(test, s->parked); + h16_sim_expect_all_off(test, s); + + /* First request after S2R wakes cleanly. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_EQ(test, s->unparks, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 1U); + + /* Now S2R while active with runtime PM forbidden (power/control=on). */ + pm_runtime_forbid(&s->dev); + WRITE_ONCE(s->in_sleep, true); + pm_runtime_get_noresume(&s->dev); + mutex_lock(&s->lock); + h16_sim_power_down(s); + WRITE_ONCE(s->slept, true); + mutex_unlock(&s->lock); + pm_runtime_put_sync_suspend(&s->dev); + running = s->pinned && READ_ONCE(s->engine_on) && !READ_ONCE(s->slept); + KUNIT_EXPECT_EQ(test, ane_fw_sleep_backstop(running), 0); + KUNIT_EXPECT_EQ(test, s->power_downs, 2U); + + /* PM_POST_SUSPEND parks the engine; consumer stayed RPM_ACTIVE (forbidden). */ + mutex_lock(&s->lock); + WRITE_ONCE(s->slept, false); + WRITE_ONCE(s->parked, true); + mutex_unlock(&s->lock); + WRITE_ONCE(s->in_sleep, false); + KUNIT_EXPECT_TRUE(test, pm_runtime_active(&s->dev)); + KUNIT_EXPECT_TRUE(test, s->parked); + + /* Fallback unpark path in session_wake boots when RPM never suspended. */ + KUNIT_ASSERT_EQ(test, h16_sim_session_wake(s), 0); + KUNIT_EXPECT_FALSE(test, s->parked); + KUNIT_EXPECT_TRUE(test, s->engine_on); + KUNIT_EXPECT_EQ(test, s->unparks, 2U); + KUNIT_EXPECT_EQ(test, s->power_ups, 2U); + pm_runtime_allow(&s->dev); +} + +/* + * Unbind/remove while parked disables runtime PM without waking the engine or + * double-powering down. + */ +static void ane_pm_h16_unbind_while_parked_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 20); + + KUNIT_ASSERT_NOT_NULL(test, s); + s->rpm_held = false; + pm_runtime_mark_last_busy(&s->dev); + pm_runtime_put_autosuspend(&s->dev); + h16_sim_wait_suspended(test, s); + KUNIT_ASSERT_EQ(test, s->power_downs, 1U); + KUNIT_ASSERT_EQ(test, s->unparks, 0U); + + /* Remove while parked: stays suspended, no wake or double power-down. */ + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + WRITE_ONCE(s->rpm_enabled, false); + KUNIT_EXPECT_EQ(test, s->power_downs, 1U); + KUNIT_EXPECT_EQ(test, s->power_ups, 0U); + KUNIT_EXPECT_EQ(test, s->unparks, 0U); + h16_sim_expect_all_off(test, s); +} + +/* + * Pre-RUN unbind/rollback while active drops the device hold, powers down + * the five domains and three DARTs, and releases the supplier device links. + */ +static void ane_pm_h16_unbind_rollback_test(struct kunit *test) +{ + struct ane_h16_rpm_sim *s = h16_sim_create(test, 20); + + KUNIT_ASSERT_NOT_NULL(test, s); + pm_runtime_disable(&s->dev); + pm_runtime_dont_use_autosuspend(&s->dev); + s->rpm_held = false; + pm_runtime_put_noidle(&s->dev); + WRITE_ONCE(s->rpm_enabled, false); + h16_sim_power_down(s); + KUNIT_EXPECT_EQ(test, pm_runtime_set_suspended(&s->dev), 0); + h16_sim_wait_darts_suspended(test, s); + h16_sim_expect_all_off(test, s); +} + static struct kunit_case ane_pm_test_cases[] = { KUNIT_CASE(ane_pm_cycle_domains_test), KUNIT_CASE(ane_pm_cycle_single_test), @@ -235,6 +716,10 @@ static struct kunit_case ane_pm_test_cases[] = { KUNIT_CASE(ane_pm_cycle_supplier_error_test), KUNIT_CASE(ane_pm_cycle_verify_error_test), KUNIT_CASE(ane_pm_cycle_resume_error_test), + KUNIT_CASE(ane_pm_h16_idle_park_wake_test), + KUNIT_CASE(ane_pm_h16_s2r_while_parked_test), + KUNIT_CASE(ane_pm_h16_unbind_while_parked_test), + KUNIT_CASE(ane_pm_h16_unbind_rollback_test), {} }; From 9f8edbe0515e0a43fe45b210a74eb776ee0e14b3 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Wed, 25 Nov 2026 11:25:54 +0000 Subject: [PATCH 1317/1514] selftests: match J615 display tests by the panel node Signed-off-by: Eric Juta --- tools/asahi/dcp14-panel-tests.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tools/asahi/dcp14-panel-tests.py b/tools/asahi/dcp14-panel-tests.py index 353996cca34047..8238ce559ebe69 100755 --- a/tools/asahi/dcp14-panel-tests.py +++ b/tools/asahi/dcp14-panel-tests.py @@ -80,7 +80,12 @@ #ifdef OLD assert(IS_ERR(b));puts("old J615 board selection rejects: PASS");return 0; #else - assert(!IS_ERR(b) && b && b->panel_width==2880 && b->panel_height==1864); + assert(IS_ERR(b)); + panel.compatible="apple,panel-j615"; + b=iomfb_v14_7_board(&dev); + assert(!IS_ERR(b) && b && b->panel_width==2880 && b->panel_height==1864 && b->panel_nits); + machine="apple,other";assert(iomfb_v14_7_board(&dev)==b); + panel.compatible=NULL; assert(!strcmp(b->firmware_uuid,"90F849E1-B422-367E-B389-50246F8DEC47")); assert(!strcmp(b->handoff,"apple,t8122-handoff") && !b->promotion); image_uuid=b->firmware_uuid;assert(probe_gate(&dev,b)==0); @@ -110,7 +115,7 @@ assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964&&q.notch_rows==74); height=1964;notch=0;assert(dcp_v14_geometry(&q)==0&&q.panel_height==1964); width=2560;height=1600;stride=width*4;notch=64;assert(dcp_v14_geometry(&q)==-EINVAL);} - /* The Airs keep their machine records whatever the panel node says. */ + /* J613 keeps its machine record; J615 and J504 match the panel. */ machine="apple,j613";assert(iomfb_v14_7_board(&dev)==j); /* Other T8122 Macs (J433/J434 iMacs, no J504 panel) have no record. */ panel.compatible=NULL; From 0b3e63b43db89691f84f46a890f6426c527abc92 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Wed, 25 Nov 2026 11:26:32 +0000 Subject: [PATCH 1318/1514] drm/apple: keep enabled J615 out of the negative backlight fixture Signed-off-by: Eric Juta --- drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index aaf549ecd8ec31..c40b147aeb3c20 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -384,7 +384,7 @@ static bool v14_bl_queued(struct apple_dcp_v14 *v14) static void v14_bl_other_boards_untouched(struct kunit *test) { const struct dcp_v14_board *boards[] = { - &dcp_v14_board_j615, &dcp_v14_board_j514c, + &dcp_v14_board_j514c, }; struct dcp_backlight_present present; unsigned int i; From 52bc662b3fde6fc5858fbe7308c72b3ac7e69400 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Wed, 25 Nov 2026 11:27:05 +0000 Subject: [PATCH 1319/1514] drm/apple: describe the remaining negative backlight case Signed-off-by: Eric Juta --- drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c index c40b147aeb3c20..3eea1558792fec 100644 --- a/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c +++ b/drivers/gpu/drm/apple/iomfb_v14_7_backlight_test.c @@ -378,7 +378,7 @@ static bool v14_bl_queued(struct apple_dcp_v14 *v14) } /* - * The production paths on J615 and J514C: no policy is consulted, no + * The production paths on J514C: no policy is consulted, no * level is encoded, the work does nothing, sleep leaves the gate alone. */ static void v14_bl_other_boards_untouched(struct kunit *test) From 07b2169d79d8e0d788635f50dc6098c49d72312d Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Wed, 25 Nov 2026 11:27:33 +0000 Subject: [PATCH 1320/1514] soc: apple: select T8122 display DART ownership only from DT Do not let a boot parameter force sharing on a DT that prohibits sharing. Keep the display DART choice independent of the command line. Signed-off-by: Eric Juta --- drivers/soc/apple/display-gate-test.c | 27 --------------------------- drivers/soc/apple/display-gate.c | 21 --------------------- 2 files changed, 48 deletions(-) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index 2f4e64caaeb899..b482e059f8099d 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -155,7 +155,6 @@ static int gt_fixture_t6041 __initdata = -1; static int gt_live_soc __initdata = -1; struct gate_test { - int dcpext_disp_dart; /* apple_t8122_display.dcpext_disp_dart, as booted */ const struct gt_soc *s; struct of_changeset cs; /* this case's own edits to the test tree */ bool requested, t6031_requested; @@ -415,8 +414,6 @@ static int __init gt_init(struct kunit *test, const struct gt_soc *s) return -ENOMEM; test->priv = t; t->s = s; - t->dcpext_disp_dart = gate_t8122_dcpext_disp_dart; - gate_t8122_dcpext_disp_dart = -1; t->pmp_uuid = s->pmp_uuid; /* As the boot left them: the test kernel's command line sets neither. */ t->requested = gate_requested; @@ -462,7 +459,6 @@ static void __init gt_exit(struct kunit *test) gate_cs_free(gate_t8122_dcpext_cs); gate_t8122_dcpext_cs = NULL; } - gate_t8122_dcpext_disp_dart = t->dcpext_disp_dart; /* The gate leaves its changes applied only when it enabled the display. */ if (gate_pmp_ovcs) { of_changeset_revert(&gate_pmp_cs); @@ -1100,27 +1096,6 @@ static void __init gate_t8122_dcpext_board_no_fbdma(struct kunit *test) gt_expect_dcpext(test, false, NULL); } -/* =0 keeps the DART out on a board that would share. */ -static void __init gate_t8122_dcpext_forced_unshared(struct kunit *test) -{ - gt_require_display_driver(test); - gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); - KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_disp_dart_setup("0"), 0); - gt_run(test); - gt_expect_dcpext_mode(test, true, false, NULL); -} - -/* =1 shares on a board that mirrors, and disables its fbdma child. */ -static void __init gate_t8122_dcpext_forced_shared(struct kunit *test) -{ - gt_require_display_driver(test); - gt_t8122_dcpext_firmware(test, gt_v14_7, gt_v14_7); - gt_add_bool(test, GT_T8122_DCPEXT, "apple,no-shared-display-dart"); - KUNIT_ASSERT_EQ(test, gate_t8122_dcpext_disp_dart_setup("1"), 0); - gt_run(test); - gt_expect_dcpext_mode(test, true, true, NULL); -} - /* On 27.2 with apple,no-shared-display-dart, DARTs get the panel window and fbdma stays on. */ static void __init gate_t8122_dcpext_v27_2_mirrors(struct kunit *test) { @@ -1314,8 +1289,6 @@ static struct kunit_case gate_t8122_cases[] __refdata = { KUNIT_CASE(gate_t8122_dcpext_other_marker), KUNIT_CASE(gate_t8122_dcpext_board_mirrors), KUNIT_CASE(gate_t8122_dcpext_board_no_fbdma), - KUNIT_CASE(gate_t8122_dcpext_forced_unshared), - KUNIT_CASE(gate_t8122_dcpext_forced_shared), KUNIT_CASE(gate_t8122_dcpext_v27_2), KUNIT_CASE(gate_t8122_dcpext_v27_2_mirrors), KUNIT_CASE(gate_t8122_dcpext_v27_2_internal_v14), diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index ed310557cde2c8..51fb056ab38684 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -1837,25 +1837,6 @@ static int __init gate_t8122_dcpext_setup(char *arg) } early_param("apple_t8122_display.dcpext", gate_t8122_dcpext_setup); -/* - * Whether the external display DART joins the display subsystem's domain: - * -1 lets the board device tree decide (apple,no-shared-display-dart keeps - * it out and mirrors framebuffers through the fbdma child instead); 0 and 1 - * override the board default. - */ -static int gate_t8122_dcpext_disp_dart __initdata = -1; - -static int __init gate_t8122_dcpext_disp_dart_setup(char *arg) -{ - bool share; - int ret = kstrtobool(arg, &share); - - if (!ret) - gate_t8122_dcpext_disp_dart = share; - return ret; -} -early_param("apple_t8122_display.dcpext_disp_dart", gate_t8122_dcpext_disp_dart_setup); - /* The most display crossbars a T8122 dcpext's routes switch: ATC0's and ATC1's. */ #define GATE_T8122_XBARS 2 @@ -1962,8 +1943,6 @@ static int __init gate_t8122_dcpext_alias(struct of_changeset *cs, static int __init gate_t8122_dcpext_shares_dart(struct device_node *np, struct device_node *fbdma) { - if (gate_t8122_dcpext_disp_dart >= 0) - return gate_t8122_dcpext_disp_dart; if (!of_property_read_bool(np, "apple,no-shared-display-dart")) return 1; return fbdma ? 0 : -ENODEV; From d1213c5fa733867ca22fc0717d228e0e780dc231 Mon Sep 17 00:00:00 2001 From: Eric Juta Date: Wed, 25 Nov 2026 11:27:34 +0000 Subject: [PATCH 1321/1514] drm/apple: do not submit scanout without a framebuffer mirror If the described fbdma child cannot attach, let the failsafe external pipe give up without disturbing the panel. On mapping failure, submit the plane as disabled instead of passing an untranslated DVA to firmware. Keep the GEM mirror teardown order unchanged. Signed-off-by: Eric Juta --- drivers/gpu/drm/apple/dcp.c | 45 ++++++++++++++------------ drivers/gpu/drm/apple/dcp.h | 2 +- drivers/gpu/drm/apple/iomfb_template.c | 7 ++-- 3 files changed, 29 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 07fa4c2859d0ac..797de683e93a24 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5755,37 +5755,34 @@ static void dcp_release_piodma_iommu_dev(struct apple_dcp *dcp) * it shares that DART with the display subsystem instead, whose domain then * already maps every framebuffer there. */ -static void dcp_create_fbdma_dev(struct apple_dcp *dcp) +static int dcp_create_fbdma_dev(struct apple_dcp *dcp) { - struct device_node *node; + struct device_node *node __free(device_node) = NULL; struct iommu_domain *dom; int ret; if (!dcp->ext_failsafe || dcp->fbdma) - return; + return 0; node = of_get_available_child_by_name(dcp->dev->of_node, "fbdma"); if (!node) - return; + return 0; dcp->fbdma = of_platform_device_create(node, NULL, dcp->dev); - if (!dcp->fbdma) { - dev_warn(dcp->dev, "fbdma: could not create %pOF\n", node); - goto out; - } + if (!dcp->fbdma) + return dev_err_probe(dcp->dev, -ENODEV, "fbdma: could not create %pOF\n", node); ret = dma_set_mask_and_coherent(&dcp->fbdma->dev, DMA_BIT_MASK(42)); if (!ret) ret = of_dma_configure(&dcp->fbdma->dev, node, true); dom = ret ? NULL : iommu_get_domain_for_dev(&dcp->fbdma->dev); if (IS_ERR_OR_NULL(dom)) { - dev_warn(dcp->dev, "fbdma: no IOMMU domain (%d)\n", ret); + ret = ret ?: PTR_ERR_OR_ZERO(dom) ?: -ENODEV; of_platform_device_destroy(&dcp->fbdma->dev, NULL); dcp->fbdma = NULL; - goto out; + return dev_err_probe(dcp->dev, ret, "fbdma: no IOMMU domain\n"); } scoped_guard(mutex, &dcp->fb_mirror_lock) WRITE_ONCE(dcp->fb_dom, dom); dev_info(dcp->dev, "fbdma: framebuffers mirrored through %pOF\n", node); -out: - of_node_put(node); + return 0; } /* @@ -5838,23 +5835,25 @@ static int dcp_fb_mirror_range(struct apple_dcp *dcp, struct iommu_domain *src, * mapping lasts as long as its object and its DVA do: dcp_fb_unmirror() * removes it when the object is freed. */ -void dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb) +int dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb) { struct iommu_domain *src; unsigned int i; - if (!fb || !READ_ONCE(dcp->fb_dom)) - return; + if (!READ_ONCE(dcp->fb_dom)) + return 0; src = iommu_get_domain_for_dev(drm_dev_dma_dev(fb->dev)); guard(mutex)(&dcp->fb_mirror_lock); if (!dcp->fb_dom || IS_ERR_OR_NULL(src)) - return; + return -ENODEV; for (i = 0; i < fb->format->num_planes; i++) { struct drm_gem_dma_object *obj = drm_fb_dma_get_gem_obj(fb, i); unsigned long index = (unsigned long)obj; int ret; - if (!obj || xa_load(&dcp->fb_mirrors, index)) + if (!obj) + return -EINVAL; + if (xa_load(&dcp->fb_mirrors, index)) continue; ret = dcp_fb_mirror_range(dcp, src, obj->dma_addr, obj->base.size); if (!ret) { @@ -5863,12 +5862,15 @@ void dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb) if (ret) iommu_unmap(dcp->fb_dom, obj->dma_addr, obj->base.size); } - if (ret) + if (ret) { dev_warn_ratelimited(dcp->dev, "fbdma: %pad (%zu bytes, %s) not mirrored: %d\n", &obj->dma_addr, obj->base.size, obj->sgt ? "imported" : "native", ret); + return ret; + } } + return 0; } /* @obj is being freed: the external pipe must not read its pages any more. */ @@ -5880,7 +5882,7 @@ void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *ob if (!pdev) return; dcp = platform_get_drvdata(pdev); - if (!dcp) + if (!dcp || !READ_ONCE(dcp->fb_dom)) return; guard(mutex)(&dcp->fb_mirror_lock); entry = xa_erase(&dcp->fb_mirrors, (unsigned long)obj); @@ -7079,11 +7081,12 @@ static int dcp_comp_bind_pipe(struct device *dev, struct device *main, void *dat } ret = dcp_create_piodma_iommu_dev(dcp); - if (!ret) - dcp_create_fbdma_dev(dcp); if (ret) return dev_err_probe(dev, ret, "Failed to create PIODMA iommu child device\n"); + ret = dcp_create_fbdma_dev(dcp); + if (ret) + goto err_piodma; if (!dcp->iommu_dom) { ret = dev_err_probe(dev, -EPROBE_DEFER, "PIODMA iommu domain is unavailable\n"); diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index 2437a188d095b8..33369bbb5dc88f 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -114,7 +114,7 @@ void dcp_retain_framebuffer(struct platform_device *pdev, struct dcp_fb_reference *entry); void dcp_arm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); void dcp_unarm_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); -void dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb); +int dcp_fb_mirror(struct apple_dcp *dcp, struct drm_framebuffer *fb); struct drm_gem_dma_object; void dcp_fb_unmirror(struct platform_device *pdev, struct drm_gem_dma_object *obj); void dcp_release_retained_framebuffers(struct apple_dcp *dcp, u32 swap_id); diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 4e3758022fb726..d5d183e0be10e7 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -4598,9 +4598,11 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru l = apl_plane->iomfb_surf; req->swap.swap_enabled |= BIT(l); - if (!new_state->fb || !new_state->visible) { + if (!new_state->fb || !new_state->visible) + continue; + /* Never submit a surface with no translation in the scanout DART. */ + if (dcp_fb_mirror(dcp, new_state->fb)) continue; - } req->surf_null[l] = false; has_surface = 1; @@ -4614,7 +4616,6 @@ void DCP_FW_NAME(iomfb_flush)(struct apple_dcp *dcp, struct drm_crtc *crtc, stru if (dcp->notch_height > 0) req->swap.dst_rect[l].y += dcp->notch_height; - dcp_fb_mirror(dcp, new_state->fb); req->surf_iova[l] = apple_state->iova; req->surf[l].base = apple_state->surf; #if DCP_FW_H17(DCP_FW_VER) From 64ec32d188442e2e14953dbe048f67a02bac0d47 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 12:00:55 +0000 Subject: [PATCH 1322/1514] phy: apple: t6040: stop the RTKit transport after probe check t6040_usb3_probe() calls apple_rtkit_init() to confirm that the PHY coprocessor mailbox has probed (or defer with -EPROBE_DEFER), then leaves the RTKit session open until the first USB3/CIO detach calls t6040_usb3_firmware_power_down(). Because apple_rtkit_init() starts the mailbox (apple_mbox_start() -> pm_runtime_resume_and_get()), every idle USB-C port pins its mailbox active and keeps ps_atcN_phymxwrap and ps_atcN_common powered on from boot until the first detach. Stop the RTKit transport right after registering the devm cleanup action. -EPROBE_DEFER is still returned before teardown, the cleanup callback is already a no-op when tphy->rtk is NULL, fixed DP-only atcphy3 returns early without orientation-switch, and the first USB3 or CIO attach restarts the transport in t6040_usb3_cpu_start(). Signed-off-by: AxxzyWasTaken --- drivers/phy/apple/t6040-usb2.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/drivers/phy/apple/t6040-usb2.c b/drivers/phy/apple/t6040-usb2.c index 5a0546da5b78f6..66e41fe9ab252b 100644 --- a/drivers/phy/apple/t6040-usb2.c +++ b/drivers/phy/apple/t6040-usb2.c @@ -2662,6 +2662,12 @@ static int t6040_usb3_probe(struct t6040_usb2_phy *tphy, struct platform_device ret = devm_add_action_or_reset(dev, t6040_rtkit_cleanup, tphy); if (ret) return ret; + /* + * Stop the transport after verifying the mailbox so it drops its + * runtime-PM reference while the port is idle; the first attach + * starts it again in t6040_usb3_cpu_start(). + */ + t6040_rtkit_stop_transport(tphy); ret = t6040_debugfs_init(tphy); if (ret) From 5a86f018f9d78a503d1ac93b9841d70e0f37de2b Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:21:50 -0500 Subject: [PATCH 1323/1514] drm/apple: allocate dcp_firmware_27_pin_precedence fixture with kunit_kzalloc Keep the mock device, device nodes, and property arrays off the stack in dcp_firmware_27_pin_precedence() so arm64 GCC builds with CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST enabled stay well under the 2,048-byte frame-size limit (272 bytes vs 2,144 bytes). Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp-firmware-test.c | 195 +++++++++++++--------- 1 file changed, 113 insertions(+), 82 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-firmware-test.c b/drivers/gpu/drm/apple/dcp-firmware-test.c index 9a51e23fb6b7fc..1b411f88c84f78 100644 --- a/drivers/gpu/drm/apple/dcp-firmware-test.c +++ b/drivers/gpu/drm/apple/dcp-firmware-test.c @@ -124,131 +124,162 @@ static void dcp_firmware_27_pin_precedence(struct kunit *test) __be32 compat_27_1[] = { cpu_to_be32(27), cpu_to_be32(1), 0 }; __be32 compat_27_2[] = { cpu_to_be32(27), cpu_to_be32(2), 0 }; __be32 compat_27_3[] = { cpu_to_be32(27), cpu_to_be32(3), 0 }; - struct property props[] = { - { .name = "apple,firmware-compat", .length = sizeof(compat_27_2), - .value = compat_27_2, .next = &props[1] }, - { .name = "apple,firmware-version", .length = sizeof(compat_27_2), - .value = compat_27_2, .next = &props[2] }, - { .name = "apple,firmware-uuid", .length = sizeof(bad_uuid), - .value = (void *)bad_uuid, .next = &props[3] }, - { .name = "compatible", .length = sizeof(t6030), - .value = (void *)t6030 }, + struct dcp_pin_precedence_fixture { + struct property props[4]; + struct property ext_props[3]; + struct device_node node; + struct device_node ext_node; + struct device dev; + } *fx; + + fx = kunit_kzalloc(test, sizeof(*fx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, fx); + + fx->props[0] = (struct property) { + .name = "apple,firmware-compat", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->props[1], }; - struct property ext_props[] = { - { .name = "apple,firmware-compat", .length = sizeof(compat_27_2), - .value = compat_27_2, .next = &ext_props[1] }, - { .name = "apple,firmware-version", .length = sizeof(compat_27_2), - .value = compat_27_2, .next = &ext_props[2] }, - { .name = "compatible", .length = sizeof(t8122_ext), - .value = (void *)t8122_ext }, + fx->props[1] = (struct property) { + .name = "apple,firmware-version", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->props[2], }; - struct device_node node = { .properties = props }; - struct device_node ext_node = { .properties = ext_props }; - struct device dev = { - .init_name = "dcp-firmware-test", - .of_node = &node, - .driver = &apple_platform_driver.driver, + fx->props[2] = (struct property) { + .name = "apple,firmware-uuid", + .length = sizeof(bad_uuid), + .value = (void *)bad_uuid, + .next = &fx->props[3], + }; + fx->props[3] = (struct property) { + .name = "compatible", + .length = sizeof(t6030), + .value = (void *)t6030, + }; + fx->ext_props[0] = (struct property) { + .name = "apple,firmware-compat", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->ext_props[1], + }; + fx->ext_props[1] = (struct property) { + .name = "apple,firmware-version", + .length = sizeof(compat_27_2), + .value = compat_27_2, + .next = &fx->ext_props[2], + }; + fx->ext_props[2] = (struct property) { + .name = "compatible", + .length = sizeof(t8122_ext), + .value = (void *)t8122_ext, }; + fx->node.properties = fx->props; + fx->ext_node.properties = fx->ext_props; + fx->dev.init_name = "dcp-firmware-test"; + fx->dev.of_node = &fx->node; + fx->dev.driver = &apple_platform_driver.driver; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); - props[0].value = compat_27_3; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[0].value = compat_27_2; + fx->props[0].value = compat_27_2; /* T6041 internal and external UUID pins remain enforced on 27.2. */ - props[3].length = sizeof(t6041); - props[3].value = (void *)t6041; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[3].length = sizeof(t6041); + fx->props[3].value = (void *)t6041; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); - props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); - props[3].length = sizeof(t6041_ext); - props[3].value = (void *)t6041_ext; - props[2].length = sizeof(bad_uuid); - props[2].value = (void *)bad_uuid; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[3].length = sizeof(t6041_ext); + fx->props[3].value = (void *)t6041_ext; + fx->props[2].length = sizeof(bad_uuid); + fx->props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[2].name = "apple,unrelated"; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[2].name = "apple,firmware-uuid"; - props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); - props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(APPLE_T6041_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T6041_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); /* T8122 wrong or missing 27.2 UUID is terminally refused (never takes generic v27). */ - props[3].length = sizeof(t8122); - props[3].value = (void *)t8122; - props[2].name = "apple,firmware-uuid"; - props[2].length = sizeof(bad_uuid); - props[2].value = (void *)bad_uuid; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[3].length = sizeof(t8122); + fx->props[3].value = (void *)t8122; + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(bad_uuid); + fx->props[2].value = (void *)bad_uuid; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); KUNIT_EXPECT_FALSE(test, - apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); - props[2].name = "apple,unrelated"; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[2].name = "apple,unrelated"; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); KUNIT_EXPECT_FALSE(test, - apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); - props[2].name = "apple,firmware-uuid"; - props[2].length = sizeof(APPLE_T8122_DCP_26B123_UUID); - props[2].value = (void *)APPLE_T8122_DCP_26B123_UUID; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[2].name = "apple,firmware-uuid"; + fx->props[2].length = sizeof(APPLE_T8122_DCP_26B123_UUID); + fx->props[2].value = (void *)APPLE_T8122_DCP_26B123_UUID; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); KUNIT_EXPECT_TRUE(test, - apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); /* T8122 external with mismatched version is terminally refused regardless of live tree. */ - ext_props[1].value = compat_27_0; + fx->ext_props[1].value = compat_27_0; KUNIT_EXPECT_FALSE(test, - apple_t8122_dcpext_v27_2_for_internal(&ext_node, &node)); - dev.of_node = &ext_node; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + apple_t8122_dcpext_v27_2_for_internal(&fx->ext_node, &fx->node)); + fx->dev.of_node = &fx->ext_node; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - ext_props[1].value = compat_27_2; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), - apple_t8122_dcpext_v27_2(&ext_node) ? + fx->ext_props[1].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), + apple_t8122_dcpext_v27_2(&fx->ext_node) ? DCP_FIRMWARE_V_27_0 : DCP_FIRMWARE_UNKNOWN); - dev.of_node = &node; + fx->dev.of_node = &fx->node; /* Internal T8142: known 27.x takes v27, unknown 27.x is refused (never takes H17P). */ - props[3].length = sizeof(t8142); - props[3].value = (void *)t8142; - props[0].value = compat_27_0; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[3].length = sizeof(t8142); + fx->props[3].value = (void *)t8142; + fx->props[0].value = compat_27_0; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); - props[0].value = compat_27_2; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[0].value = compat_27_2; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_V_27_0); - props[0].value = compat_27_1; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[0].value = compat_27_1; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[0].value = compat_27_3; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[0].value = compat_27_3; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_UNKNOWN); - props[0].value = compat_26_6; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[0].value = compat_26_6; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_H17P); - props[0].value = compat_27_2; + fx->props[0].value = compat_27_2; #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T8132) /* T8132 keeps its M4 match-data pin on 27.2. */ - props[3].length = sizeof(t8132); - props[3].value = (void *)t8132; - KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&dev), + fx->props[3].length = sizeof(t8132); + fx->props[3].value = (void *)t8132; + KUNIT_EXPECT_EQ(test, dcp_check_firmware_version(&fx->dev), DCP_FIRMWARE_M4); #endif } From 9284d2ca9a0919f7f43dc4101b61672c0f61f8d9 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 12:00:16 +0000 Subject: [PATCH 1324/1514] arm64: dts: apple: t604x: allow ps_aes to power off when idle The Apple SIO AES driver (drivers/crypto/apple-aes.c) already implements runtime PM with 50 ms autosuspend, re-initializes the command FIFO and control registers on every request, and uses pm_runtime_force_suspend/ resume across system sleep. Its IOMMU (sio_dart) sits in the parent ps_sio domain and ps_aes has no child domains or other consumers. On T6041, ps_aes is also listed in apple,sleep-keep-on-domains (t6041.dtsi), so t6041-sleep.c raises it at sleep commit and t6041_ps_restore() returns it to its saved off state on wake. Drop the obsolete apple,always-on property from ps_aes on T6040 and T6041, matching T8122, T6030, and T8132, so the AES power domain can power off when idle. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t6040-pmgr.dtsi | 1 - arch/arm64/boot/dts/apple/t6041.dtsi | 1 - 2 files changed, 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi index 75650445572b10..835eae406f1e86 100644 --- a/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t6040-pmgr.dtsi @@ -106,7 +106,6 @@ #reset-cells = <0>; label = "aes"; power-domains = <&ps_sio>; - apple,always-on; status = "disabled"; }; diff --git a/arch/arm64/boot/dts/apple/t6041.dtsi b/arch/arm64/boot/dts/apple/t6041.dtsi index a4dfb2d600c9f8..38c0fc872c3728 100644 --- a/arch/arm64/boot/dts/apple/t6041.dtsi +++ b/arch/arm64/boot/dts/apple/t6041.dtsi @@ -675,7 +675,6 @@ #reset-cells = <0>; label = "aes"; power-domains = <&ps_sio>; - apple,always-on; status = "disabled"; }; }; From 5e1c035095b137a13383aafd267a8f3ea203fee7 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 12:00:55 +0000 Subject: [PATCH 1325/1514] drm/apple: dcp-fabric: route T6041 DP IN tunnels on activation A display crossbar with runtime PM enabled leaves its ATC USB power domain off until an output is selected, so apple_dpxbar_tunnel_select_source() returns -EOPNOTSUPP while unselected. On T6040/T6041, dcp_t602x_tunnel_route() did not match apple,t6041-display-crossbar, so dcp_tunnel_dpin_activate() skipped mux_control_try_select() before DCP probed AUX, leaving non-zero sources (dcpext1/dcpext2) and tiled DP IN 1 (unit == 1) unrouted when crossbar runtime PM is enabled. Include apple,t6041-display-crossbar in dcp_t602x_tunnel_route() and select dcp->split.xbar on activation for unit == 1 on T6041 so dcp_tunnel_dpin_activate() routes the DP IN output (and holds its crossbar power domain) before AUX negotiation while keeping link clocks off until dcp_tunnel_crossbar_up() / dcp_tunnel_split_up_locked(), matching T6030, T8132, and T8142. Also enable link clocks after a first select in dcp_tunnel_split_up_locked() on T6041, treat -EOPNOTSUPP from dcp_dpxbar_preselect() as already idle if a T6041 tunnel is deactivated before activation selects the mux, and stub dcp_xbar_t6041() in the apple-dcp host transaction selftest. Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/apple/dcp-fabric.c | 51 ++++++++++++++----- .../drivers/gpu/apple-dcp/transaction.py | 3 +- 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-fabric.c b/drivers/gpu/drm/apple/dcp-fabric.c index 148dd101094d02..2a0bcdf1073209 100644 --- a/drivers/gpu/drm/apple/dcp-fabric.c +++ b/drivers/gpu/drm/apple/dcp-fabric.c @@ -564,6 +564,7 @@ static int dcp_typec_route_activate(struct apple_dcp_typec_route *route, static int dcp_typec_route_deactivate(struct apple_dcp_typec_route *route); static int dcp_dpxbar_preselect(struct mux_control *mux, int state); static bool dcp_xbar_t8142(struct mux_control *mux); +static bool dcp_xbar_t6041(struct mux_control *mux); static int dcp_dpxbar_tunnel_select_source(struct mux_control *mux, int state) { @@ -843,11 +844,13 @@ static int dcp_typec_route_deactivate(struct apple_dcp_typec_route *route) } else { ret = dcp_dpxbar_preselect(route->active_xbar, MUX_IDLE_DISCONNECT); /* - * The T8142-layout crossbar writes an output only when it - * is selected: one never selected is idle already. + * The T8142-layout and runtime-PM T6041 + * crossbars write an output only when it is + * selected: one never selected is idle already. */ if (ret == -EOPNOTSUPP && (dcp_xbar_t8142(route->active_xbar) || + dcp_xbar_t6041(route->active_xbar) || dcp_typec_route_no_dp_alt(route))) ret = 0; } @@ -2296,17 +2299,27 @@ static bool dcp_xbar_t8142(struct mux_control *mux) "apple,t8142-display-crossbar"); } +/* The T6041-layout crossbar (one per ATC on T6040/T6041) */ +static bool dcp_xbar_t6041(struct mux_control *mux) +{ + return mux && of_device_is_compatible(mux->chip->dev.parent->of_node, + "apple,t6041-display-crossbar"); +} + /* * Tunnel routes whose crossbar must point the DP IN output at its pipeline * before the firmware uses AUX through it, i.e. from DCP's Activate: the T6030 - * 14.7 pipeline on its T602X crossbar (other T602X tunnels keep their order) - * and firmware 27 on the T8142-layout crossbar. Selecting routes the output - * only; its clocks follow the link. + * 14.7 pipeline on its T602X crossbar (other T602X tunnels keep their order), + * the T6041 crossbar on every firmware (its runtime-PM path only writes the + * mux while selected), and firmware 27 on the T8142-layout crossbar. Selecting + * routes the output only; its clocks follow the link. */ static bool dcp_t602x_tunnel_route(struct apple_dcp_typec_route *route) { if (!route || !route->tunnel || !route->active_xbar) return false; + if (dcp_xbar_t6041(route->active_xbar)) + return true; if (route->dcp->fw_compat == DCP_FIRMWARE_V_27_0) return dcp_xbar_t8142(route->active_xbar); return route->dcp->fw_compat == DCP_FIRMWARE_V_14_7 && @@ -2417,6 +2430,12 @@ static int dcp_tunnel_split_up_locked(struct apple_dcp *dcp) ret = mux_control_try_select(dcp->split.xbar, dcp->split.mux_state); if (!ret) dcp->split.xbar_up = true; + /* + * T6041 DP IN selection reserves and routes the mux only, so + * the first link up also enables the connection clocks. + */ + if (!ret && dcp_xbar_t6041(dcp->split.xbar)) + ret = dcp_dpxbar_link(dcp->split.xbar, true); } else { ret = dcp_dpxbar_link(dcp->split.xbar, true); } @@ -2555,15 +2574,13 @@ int dcp_tunnel_crossbar_up(struct apple_dcp *dcp, u32 unit) if (!ret) route->xbar_up = true; /* - * T602X DP IN selection reserves and routes the mux only, so the - * first link up also enables the connection. The T6041 crossbar - * (M4 Pro/Max) takes the same T6030 flow on every firmware: without - * this its clocks stay off until a retrain, and a mode set that - * keeps the trained link (5K on 26.6) never gets any video. + * T602X, T6041 and T8142 DP IN selection reserves and routes + * the mux only, so the first link up also enables the + * connection: without this its clocks stay off until a + * retrain, and a mode set that keeps the trained link (5K on + * 26.6) never gets any video. */ - if (!ret && (dcp_t602x_tunnel_route(route) || - of_device_is_compatible(route->active_xbar->chip->dev.parent->of_node, - "apple,t6041-display-crossbar"))) { + if (!ret && dcp_t602x_tunnel_route(route)) { ret = dcp_tunnel_xbar_configure(route); if (!ret) ret = dcp_dpxbar_link(route->active_xbar, true); @@ -2857,6 +2874,14 @@ int dcp_tunnel_dpin_activate(struct apple_dcp *dcp, u32 unit, bool active) if (unit) { if (!dcp->split.active || !dcp->split.generation || !dcp->split.set_active) return 0; + if (active && dcp_xbar_t6041(dcp->split.xbar) && + !dcp->split.xbar_up) { + ret = mux_control_try_select(dcp->split.xbar, + dcp->split.mux_state); + if (ret) + return ret; + dcp->split.xbar_up = true; + } return dcp->split.set_active(dcp->split.binding, active); } /* Route the upstream engine before firmware begins AUX negotiation. diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py index 1375b2683f4a44..7e980849060811 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/transaction.py @@ -104,8 +104,9 @@ def check(name, unit, cases=((),), negative=False, flags=()): static int dcp_dptx_connect_oob(void *dev,unsigned n) { (void)dev;(void)n;connect_calls++;display.external_cable=true;display.dptxport[0].connected=true;display.typec_cable_connected=true;connector.connected=true;return 0; } static void dcp_retrain_oob(struct connector *c) { (void)c; } static bool dcp_typec_sink_relink(struct apple_dcp *d) { (void)d;return false; } - /* An M1/M2 crossbar is not the T8142 layout, and an M1/M2 port has no fixed-CRTC connectors. */ + /* An M1/M2 crossbar is not the T8142 or T6041 layout, and an M1/M2 port has no fixed-CRTC connectors. */ static bool dcp_xbar_t8142(struct mux_control *m) { (void)m;return false; } + static bool dcp_xbar_t6041(struct mux_control *m) { (void)m;return false; } static bool dcp_typec_fixed_crtcs(void) { return false; } /* Deactivation retires queued DP IN events and drains their work. */ static int tb_event_cancels; From d335804477dd724c8ded2e04e8a6693f3cfcb7e1 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 12:00:56 +0000 Subject: [PATCH 1326/1514] mux: apple-display-crossbar: enable runtime PM on T6041 crossbars Enable runtime PM on apple_dpxbar_hw_t6041, matching apple_dpxbar_hw_t8132, so the display crossbar only holds its ps_atcN_usb power domain while an output is selected. Probe touches no registers (no_tunable is set), link up/down and system resume skip every unselected output (selected_dispext[i] < 0), and T6041 DP IN tunnels now select the mux in dcp_tunnel_dpin_activate() rather than relying on apple_dpxbar_tunnel_select_source() while suspended. Signed-off-by: AxxzyWasTaken --- drivers/mux/apple-display-crossbar.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/mux/apple-display-crossbar.c b/drivers/mux/apple-display-crossbar.c index 12e1f8a1cf7891..7740922e7f316e 100644 --- a/drivers/mux/apple-display-crossbar.c +++ b/drivers/mux/apple-display-crossbar.c @@ -1457,6 +1457,8 @@ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6020 = { * compact register map and flow: the status mirrors at 0x804/0x810/0x81c * follow 0x004/0x014/0x024 and 0x808/0x818 follow 0x00c/0x020, as on T6030. * The ADT lists nine UFP endpoints (dispext0-3, scodec0 and the DP IN ports). + * The ATC USB domain switches off at runtime, so it is only held while an + * output is selected; probe touches no register. */ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6041 = { .n_mux = MUX_MAX, @@ -1465,6 +1467,7 @@ static const struct apple_dpxbar_hw apple_dpxbar_hw_t6041 = { .t6030_flow = true, .no_tunable = true, .t604x_dpin_atc = true, + .runtime_pm = true, }; /* From 6945ee77e72faaf47556d417851b62e81315e94f Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:39:47 -0500 Subject: [PATCH 1327/1514] drm/asahi: g16: select display supplier from match data via shared DT link Replace the hardcoded T6030-versus-T8132 split in asahi_g16_display_prepare() with match-data-driven supplier selection: - Add apple_drm_link_device(consumer, display_node) in apple_drv.c, reusing the existing display publication mutex and device-link lifetime management for any published Apple DRM display subsystem matched by exact DT node. - Add display_compatible to g16::hw::Config (t8132 and t6030 rows) and pass it from g16::boot::admit() to asahi_g16_display_prepare(), so new hardware rows configure their display supplier without adding probe branches. - Extend tools/asahi/g15-display-order-tests.py to cover a third hardware row and exact-node publication/linking mutants while keeping all existing absent, disabled, deferred, ready, and withdrawal checks. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/apple/apple_drv.c | 71 +++++++++++++++++++ drivers/gpu/drm/asahi/g16/boot.rs | 18 +++-- drivers/gpu/drm/asahi/g16/glue.c | 18 +++-- drivers/gpu/drm/asahi/g16/glue.h | 2 + drivers/gpu/drm/asahi/g16/hw.rs | 4 ++ include/linux/soc/apple/display.h | 2 + tools/asahi/g15-display-order-tests.py | 97 +++++++++++++++++++------- 7 files changed, 172 insertions(+), 40 deletions(-) diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 58957e679b3926..906dcd3b1e0012 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -126,6 +126,8 @@ static DEFINE_MUTEX(apple_g15_display_lock); static struct device *apple_t6030_display; static struct device *apple_t6031_display; static struct device *apple_t8132_display; +#define APPLE_DRM_PUBLISHED_MAX 8 +static struct device *apple_drm_published[APPLE_DRM_PUBLISHED_MAX]; /* The publication slot of a G15/G16 SoC's internal display subsystem, or NULL. */ static struct device **apple_g15_display_slot(struct device *dev) @@ -209,6 +211,67 @@ int apple_drm_t8132_link_device(struct device *consumer) } EXPORT_SYMBOL_GPL(apple_drm_t8132_link_device); +static int apple_drm_display_publish(struct device *dev) +{ + int free_slot = -1; + int i; + + if (!dev->of_node) + return 0; + guard(mutex)(&apple_g15_display_lock); + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] == dev) + return 0; + if (apple_drm_published[i] && + apple_drm_published[i]->of_node == dev->of_node) + return -EBUSY; + if (!apple_drm_published[i] && free_slot < 0) + free_slot = i; + } + if (free_slot < 0) + return -ENOSPC; + apple_drm_published[free_slot] = get_device(dev); + return 0; +} + +static void apple_drm_display_withdraw(struct device *dev) +{ + struct device *old = NULL; + int i; + + scoped_guard(mutex, &apple_g15_display_lock) { + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] == dev) { + old = apple_drm_published[i]; + apple_drm_published[i] = NULL; + break; + } + } + } + put_device(old); +} + +int apple_drm_link_device(struct device *consumer, + const struct device_node *display_node) +{ + struct device_link *link; + int i; + + if (!consumer || !consumer->of_node || !display_node) + return -EINVAL; + guard(mutex)(&apple_g15_display_lock); + for (i = 0; i < ARRAY_SIZE(apple_drm_published); i++) { + if (apple_drm_published[i] && + apple_drm_published[i]->of_node == display_node) { + link = device_link_add(consumer, apple_drm_published[i], + DL_FLAG_AUTOREMOVE_CONSUMER); + return link ? 0 : -EINVAL; + } + } + return -EPROBE_DEFER; +} +EXPORT_SYMBOL_GPL(apple_drm_link_device); + DEFINE_DRM_GEM_DMA_FOPS(apple_fops); #define DART_PAGE_SIZE 16384 @@ -2102,6 +2165,13 @@ static int apple_drm_init(struct device *dev) drm_dev_unregister(&apple->drm); goto err_unbind; } + ret = apple_drm_display_publish(dev); + if (ret) { + apple_g15_display_withdraw(dev); + t8132_ext_drm_fini(&apple->drm); + drm_dev_unregister(&apple->drm); + goto err_unbind; + } mutex_lock(&apple_drm_pm_lock); list_add_tail(&apple->pm_node, &apple_drm_pm_list); @@ -2124,6 +2194,7 @@ static void apple_drm_uninit(struct device *dev) { struct apple_drm_private *apple = dev_get_drvdata(dev); + apple_drm_display_withdraw(dev); apple_g15_display_withdraw(dev); /* An aborted takeover leaves its DCPs running until the reboot. */ diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index eac8b29a6ed05e..e4d1e8562d2d45 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -44,7 +44,10 @@ 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_display_prepare( + dev: *mut core::ffi::c_void, + display_compat: *const core::ffi::c_char, + ) -> core::ffi::c_int; 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; @@ -70,9 +73,14 @@ pub(crate) mod glue { } /// Links the GPU to the published native display, or defers until it is. - pub(crate) fn display_prepare(dev: &device::Device) -> Result { - // SAFETY: `dev` is the bound GPU device; the helper only adds a device link. - kernel::error::to_result(unsafe { asahi_g16_display_prepare(dev.as_raw().cast()) }) + pub(crate) fn display_prepare(dev: &device::Device, display_compatible: &[u8]) -> Result { + let Ok(cstr) = core::ffi::CStr::from_bytes_with_nul(display_compatible) else { + return Err(EINVAL); + }; + // SAFETY: `dev` is the bound GPU device; `cstr` is NUL-terminated. + kernel::error::to_result(unsafe { + asahi_g16_display_prepare(dev.as_raw().cast(), cstr.as_ptr().cast()) + }) } /// The system counter frequency in Hz, as the boot loader programmed it. @@ -631,7 +639,7 @@ pub(crate) fn admit( return Err(err); } } - glue::display_prepare(dev).inspect_err(|e| { + glue::display_prepare(dev, cfg.display_compatible).inspect_err(|e| { if *e != EPROBE_DEFER { dev_err!(dev, "native display not admitted: {:?}\n", e); } diff --git a/drivers/gpu/drm/asahi/g16/glue.c b/drivers/gpu/drm/asahi/g16/glue.c index 710a2601ce8945..583dbc61d78f8d 100644 --- a/drivers/gpu/drm/asahi/g16/glue.c +++ b/drivers/gpu/drm/asahi/g16/glue.c @@ -33,7 +33,6 @@ #include "glue.h" bool asahi_g16_board(void); -int asahi_g16_display_prepare(struct device *dev); int asahi_g16_hold_power(struct device *dev); bool asahi_g16_ram_disjoint(u64 start, u64 size); void __iomem *asahi_g16_ioremap_wc(u64 start, size_t size); @@ -463,26 +462,25 @@ u32 asahi_g16_timebase_hz(void) * without one (no internal panel, or none qualified) starts on the boot * framebuffer. */ -int asahi_g16_display_prepare(struct device *dev) +int asahi_g16_display_prepare(struct device *dev, const char *display_compat) { - bool t6030 = of_device_is_compatible(dev->of_node, "apple,agx-t6030"); struct device_node *np; bool handed_over; int ret; - np = of_find_compatible_node(NULL, NULL, - t6030 ? "apple,t6030-display-subsystem" : - "apple,t8132-display-subsystem"); + if (!display_compat || !*display_compat) + return -EINVAL; + np = of_find_compatible_node(NULL, NULL, display_compat); handed_over = np && of_device_is_available(np); - of_node_put(np); if (!handed_over) { + of_node_put(np); dev_info_once(dev, "G16: no native display this boot; starting on the boot framebuffer\n"); return 0; } - ret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev); + ret = apple_drm_link_device(dev, np); + of_node_put(np); if (ret == -EPROBE_DEFER) - dev_info_once(dev, "G16: waiting for the %s native display to register\n", - t6030 ? "T6030" : "T8132"); + dev_info_once(dev, "G16: waiting for %s to register\n", display_compat); return ret; } diff --git a/drivers/gpu/drm/asahi/g16/glue.h b/drivers/gpu/drm/asahi/g16/glue.h index dd60a837903b83..c5cd057ef405ea 100644 --- a/drivers/gpu/drm/asahi/g16/glue.h +++ b/drivers/gpu/drm/asahi/g16/glue.h @@ -3,8 +3,10 @@ #define _ASAHI_G16_GLUE_H struct asahi_g16_cooling; +struct device; u32 asahi_g16_timebase_hz(void); bool asahi_g16_cooling_has_pmp(const struct asahi_g16_cooling *cooling); +int asahi_g16_display_prepare(struct device *dev, const char *display_compat); #endif /* _ASAHI_G16_GLUE_H */ diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 194e5dcd4a0b04..14567a7501016e 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -42,6 +42,8 @@ pub(crate) struct Config { pub(crate) hw_ids: &'static [HwId], /// Compatible of the original ADT SGX node. pub(crate) adt_compatible: &'static [u8], + /// NUL-terminated compatible of the native display subsystem supplier. + pub(crate) display_compatible: &'static [u8], /// Qualified boot-loader handoffs. pub(crate) layouts: &'static [&'static FwLayout], /// Qualified firmware builds. @@ -93,6 +95,7 @@ pub(crate) mod t8132 { counts: 0x0011010a, }], adt_compatible: b"gpu,t8132", + display_compatible: b"apple,t8132-display-subsystem\0", layouts: &[&FW_25G83, &FW_26B123], firmware: &[ FirmwareBuild { @@ -322,6 +325,7 @@ pub(crate) mod t6030 { counts: 0x00110209, }], adt_compatible: b"gpu,t6030", + display_compatible: b"apple,t6030-display-subsystem\0", layouts: &[&LAYOUT], firmware: &[FirmwareBuild { name: "Apple GFX 26B123 G15S (build b000, iBoot-filled ranges zeroed)", diff --git a/include/linux/soc/apple/display.h b/include/linux/soc/apple/display.h index c0ae42df744cd5..66dadb487cebc7 100644 --- a/include/linux/soc/apple/display.h +++ b/include/linux/soc/apple/display.h @@ -11,6 +11,8 @@ struct device; /* Initial native display admission, before starting retained GPU firmware. */ +int apple_drm_link_device(struct device *consumer, + const struct device_node *display_node); int apple_drm_t6030_link_device(struct device *consumer); int apple_drm_t6031_link_device(struct device *consumer); int apple_drm_t8132_link_device(struct device *consumer); diff --git a/tools/asahi/g15-display-order-tests.py b/tools/asahi/g15-display-order-tests.py index f72fca0cde9d52..cd4323903e76ab 100644 --- a/tools/asahi/g15-display-order-tests.py +++ b/tools/asahi/g15-display-order-tests.py @@ -42,8 +42,10 @@ def c_source(root): if line in ("static DEFINE_MUTEX(apple_g15_display_lock);", "static struct device *apple_t6030_display;", "static struct device *apple_t6031_display;", - "static struct device *apple_t8132_display;")] - assert len(state) == 4, f"publication state not found: {state}" + "static struct device *apple_t8132_display;", + "#define APPLE_DRM_PUBLISHED_MAX 8", + "static struct device *apple_drm_published[APPLE_DRM_PUBLISHED_MAX];")] + assert len(state) == 6, f"publication state not found: {state}" bodies = [item(apple, marker) for marker in ( "\nstatic struct device **apple_g15_display_slot(struct device *dev)\n{", "\nstatic int apple_g15_display_publish(struct device *dev)\n{", @@ -52,9 +54,12 @@ def c_source(root): "\nint apple_drm_t6030_link_device(struct device *consumer)\n{", "\nint apple_drm_t6031_link_device(struct device *consumer)\n{", "\nint apple_drm_t8132_link_device(struct device *consumer)\n{", + "\nstatic int apple_drm_display_publish(struct device *dev)\n{", + "\nstatic void apple_drm_display_withdraw(struct device *dev)\n{", + "\nint apple_drm_link_device(", )] bodies.append(item(glue, "\nint asahi_g15_display_prepare(struct device *dev)\n{")) - bodies.append(item(glue16, "\nint asahi_g16_display_prepare(struct device *dev)\n{")) + bodies.append(item(glue16, "\nint asahi_g16_display_prepare(struct device *dev, const char *display_compat)\n{")) return "\n".join(state) + "\n\n" + "\n\n".join(bodies) + "\n" @@ -68,8 +73,10 @@ def c_source(root): #define ENODEV 19 #define EBUSY 16 #define EINVAL 22 +#define ENOSPC 28 #define EPROBE_DEFER 517 #define DL_FLAG_AUTOREMOVE_CONSUMER 1u +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define EXPORT_SYMBOL_GPL(sym) extern int sym##_exported struct device_node { const char *compatible; bool available; int refs; }; @@ -131,14 +138,16 @@ def c_source(root): #define CHECK(c) do { if (!(c)) { fprintf(stderr, "%s:%d: %s\n", scenario, __LINE__, #c); exit(1); } } while (0) static struct device_node gpu31 = { "apple,agx-t6031", true }, gpu30 = { "apple,agx-t6030", true }; -static struct device_node gpu8132 = { "apple,agx-t8132", true }; +static struct device_node gpu8132 = { "apple,agx-t8132", true }, gpu8122 = { "apple,agx-t8122", true }; static struct device_node disp8132 = { "apple,t8132-display-subsystem", false }; +static struct device_node disp8122 = { "apple,t8122-display-subsystem", false }; static struct device_node disp31 = { "apple,t6031-display-subsystem", false }; static struct device_node disp30 = { "apple,t6030-display-subsystem", true }; static struct device_node other = { "apple,display-subsystem", true }; static struct device g31 = { &gpu31 }, g30 = { &gpu30 }, none = { NULL }; static struct device d31 = { &disp31 }, d31b = { &disp31 }, d30 = { &disp30 }, dother = { &other }; static struct device g8132 = { &gpu8132 }, d8132 = { &disp8132 }; +static struct device g8122 = { &gpu8122 }, d8122 = { &disp8122 }, d8122b = { &disp8122 }; static void machine(const char *soc, const char *board) { @@ -155,9 +164,11 @@ def c_source(root): static int link30(struct device *dev) { int ret = apple_drm_t6030_link_device(dev); clean(); return ret; } static int link31(struct device *dev) { int ret = apple_drm_t6031_link_device(dev); clean(); return ret; } static int link8132(struct device *dev) { int ret = apple_drm_t8132_link_device(dev); clean(); return ret; } -static int prepare16(struct device *dev) { int ret = asahi_g16_display_prepare(dev); clean(); return ret; } +static int prepare16(struct device *dev, const char *compat) { int ret = asahi_g16_display_prepare(dev, compat); clean(); return ret; } static int publish(struct device *dev) { int ret = apple_g15_display_publish(dev); clean(); return ret; } static void withdraw(struct device *dev) { apple_g15_display_withdraw(dev); clean(); } +static int publish_drm(struct device *dev) { int ret = apple_drm_display_publish(dev); clean(); return ret; } +static void withdraw_drm(struct device *dev) { apple_drm_display_withdraw(dev); clean(); } int main(int argc, char **argv) { @@ -219,40 +230,73 @@ def c_source(root): } else if (!strcmp(scenario, "g16-t6030")) { machine("apple,t6030", "apple,j516s"); disp30.available = false; - CHECK(prepare16(&g30) == 0 && links_made == 0); + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 0); nodes[2] = NULL; - CHECK(prepare16(&g30) == 0 && links_made == 0); + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 0); nodes[2] = &disp30; disp30.available = true; - CHECK(prepare16(&g30) == -EPROBE_DEFER && links_made == 0); - CHECK(publish(&d30) == 0); - CHECK(prepare16(&g30) == 0 && links_made == 1 && last_link.supplier == &d30); - withdraw(&d30); - CHECK(prepare16(&g30) == -EPROBE_DEFER); + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == -EPROBE_DEFER && links_made == 0); + CHECK(publish_drm(&d30) == 0 && d30.refs == 1); + CHECK(prepare16(&g30, "apple,t6030-display-subsystem") == 0 && links_made == 1 && last_link.supplier == &d30); + withdraw_drm(&d30); + CHECK(d30.refs == 0 && prepare16(&g30, "apple,t6030-display-subsystem") == -EPROBE_DEFER); } else if (!strcmp(scenario, "t8132")) { /* No handed-over display: G16 starts on the boot framebuffer, said once. */ machine("apple,t8132", "apple,j713"); nodes[0] = &gpu8132; nodes[1] = &disp8132; - CHECK(prepare16(&g8132) == 0 && infos == 1 && links_made == 0); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && infos == 1 && links_made == 0); nodes[1] = NULL; - CHECK(prepare16(&g8132) == 0 && infos == 1 && links_made == 0); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && infos == 1 && links_made == 0); nodes[1] = &disp8132; /* A handed-over display: wait for its own publication, said once, then link. */ disp8132.available = true; - CHECK(prepare16(&g8132) == -EPROBE_DEFER && infos == 2 && links_made == 0); - CHECK(publish(&d31) == 0 && prepare16(&g8132) == -EPROBE_DEFER && links_made == 0); - withdraw(&d31); - CHECK(publish(&d8132) == 0 && d8132.refs == 1); - CHECK(prepare16(&g8132) == 0 && links_made == 1); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER && infos == 2 && links_made == 0); + CHECK(publish_drm(&d31) == 0 && prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER && links_made == 0); + withdraw_drm(&d31); + CHECK(publish_drm(&d8132) == 0 && d8132.refs == 1); + CHECK(prepare16(&g8132, "apple,t8132-display-subsystem") == 0 && links_made == 1); CHECK(last_link.consumer == &g8132 && last_link.supplier == &d8132 && last_link.flags == DL_FLAG_AUTOREMOVE_CONSUMER); + CHECK(publish(&d31) == 0 && link8132(&g8132) == -EPROBE_DEFER && links_made == 1); + withdraw(&d31); + CHECK(publish(&d8132) == 0 && d8132.refs == 2); + CHECK(link8132(&g8132) == 0 && links_made == 2 && last_link.supplier == &d8132); CHECK(link8132(&g31) == -ENODEV && link8132(&none) == -ENODEV); + withdraw_drm(&d8132); + CHECK(d8132.refs == 1 && prepare16(&g8132, "apple,t8132-display-subsystem") == -EPROBE_DEFER); withdraw(&d8132); - CHECK(d8132.refs == 0 && prepare16(&g8132) == -EPROBE_DEFER); + CHECK(d8132.refs == 0 && link8132(&g8132) == -EPROBE_DEFER); CHECK(publish(&d8132) == 0); machine("apple,t6031", "apple,j516c"); - CHECK(link8132(&g8132) == -ENODEV && prepare16(&g8132) == -ENODEV && links_made == 1); + CHECK(link8132(&g8132) == -ENODEV && links_made == 2); + } else if (!strcmp(scenario, "g16-other-row")) { + /* Another hardware row selects its display supplier from match data without probing branches. */ + machine("apple,t8122", "apple,j615"); + nodes[0] = &gpu8122; + nodes[1] = &disp8122; + CHECK(prepare16(&g8122, NULL) == -EINVAL && prepare16(&g8122, "") == -EINVAL); + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && infos == 1 && links_made == 0); + nodes[1] = NULL; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && infos == 1 && links_made == 0); + nodes[1] = &disp8122; + disp8122.available = true; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER && infos == 2 && links_made == 0); + CHECK(publish_drm(&d8132) == 0 && prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER && links_made == 0); + CHECK(publish_drm(&d8122) == 0 && d8122.refs == 1); + CHECK(publish_drm(&d8122) == 0 && d8122.refs == 1); + CHECK(publish_drm(&d8122b) == -EBUSY && d8122b.refs == 0); + withdraw_drm(&d8122b); + CHECK(prepare16(&none, "apple,t8122-display-subsystem") == -EINVAL && links_made == 0); + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == 0 && links_made == 1); + CHECK(last_link.consumer == &g8122 && last_link.supplier == &d8122 && + last_link.flags == DL_FLAG_AUTOREMOVE_CONSUMER); + link_fail = 1; + CHECK(prepare16(&g8122, "apple,t8122-display-subsystem") == -EINVAL); + link_fail = 0; + withdraw_drm(&d8122); + CHECK(d8122.refs == 0 && prepare16(&g8122, "apple,t8122-display-subsystem") == -EPROBE_DEFER); + withdraw_drm(&d8132); } else { CHECK(!"unknown scenario"); } @@ -260,7 +304,7 @@ def c_source(root): } ''' -C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "g16-t6030", "t8132"] +C_SCENARIOS = ["disabled", "absent", "pending", "ready", "isolation", "foreign", "t6030", "g16-t6030", "t8132", "g16-other-row"] C_MUTANTS = { "unpublished-succeeds": ("if (!*display)\n\t\treturn -EPROBE_DEFER;", "if (!*display)\n\t\treturn 0;"), @@ -271,8 +315,10 @@ def c_source(root): "t8132-reads-t6031-slot": ("&apple_t8132_display);", "&apple_t6031_display);"), "t8132-published-as-t6031": ("return &apple_t8132_display;", "return &apple_t6031_display;"), "g16-ignores-handed-over-display": ("handed_over = np && of_device_is_available(np);", "handed_over = false;"), - "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev);", - "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = t6030 ? apple_drm_t6030_link_device(dev) : apple_drm_t8132_link_device(dev);"), + "g16-waits-without-display": ("\t\treturn 0;\n\t}\n\tret = apple_drm_link_device(dev, np);", + "\t\treturn -EPROBE_DEFER;\n\t}\n\tret = apple_drm_link_device(dev, np);"), + "drm-link-unpublished-succeeds": ("\t\t}\n\t}\n\treturn -EPROBE_DEFER;", "\t\t}\n\t}\n\treturn 0;"), + "drm-link-wrong-node": ("apple_drm_published[i]->of_node == display_node", "apple_drm_published[i]->of_node != NULL"), "no-machine-check": ("!of_machine_is_compatible(machine) ||", ""), "withdraw-keeps-display": ("*slot = NULL;", ";"), "publish-without-reference": ("*slot = get_device(dev);", "*slot = dev;"), @@ -474,9 +520,10 @@ def static_checks(root): assert compat.findall(autoload) == ["apple,agx-t6030", "apple,agx-t6031"], "autoload table" assert compat.findall(matched) == ["apple,agx-t6030", "apple,agx-t6031"], "match table" init = item(apple, "\nstatic int apple_drm_init(struct device *dev)\n{") - order = [init.index(s) for s in ("drm_dev_register(", "drm_client_setup_with_fourcc(", "apple_g15_display_publish(dev)")] + order = [init.index(s) for s in ("drm_dev_register(", "drm_client_setup_with_fourcc(", "apple_g15_display_publish(dev)", "apple_drm_display_publish(dev)")] assert order == sorted(order), "publication must follow DRM registration and client setup" uninit = item(apple, "\nstatic void apple_drm_uninit(struct device *dev)\n{") + assert uninit.index("apple_drm_display_withdraw(dev)") < uninit.index("component_unbind_all("), "withdraw before unbind" assert uninit.index("apple_g15_display_withdraw(dev)") < uninit.index("component_unbind_all("), "withdraw before unbind" assert "apple_t6030_display_publish" not in apple and "apple_t6030_display_withdraw" not in apple pmp = item(glue, "\nint asahi_g15_pmp_prepare(struct device *dev)\n{") From 40f74425e1a92ab6d7684113b518933c461c0c31 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 07:42:06 -0500 Subject: [PATCH 1328/1514] usb: dwc3: apple: route the host USB3 PHY from xHCI's SuperSpeed setup Leaving the host USB3 PHY routing to usb_add_hcd() on xHCI's shared HCD moved it into xhci_plat_probe(), whose result platform_device_add() does not report. A failed routing tore down both root hubs while dwc3_host_init() returned 0: dwc3_apple_init() then recorded a host with no bound xHCI, skipped dwc3_apple_core_stop(), voted USB_SLP_DDR, and an -ENOLINK after a sleep no longer reached dwc3_apple_start_after_sleep(). On older Type-C ports, a USB3 PHY error took the USB2 root hub down with it instead of leaving the port on USB2. The T8132/T8142 P3 quirk also ran from a probe that a modular or asynchronous xhci-plat may run outside the glue lock. Keep the USB3 PHY off the SuperSpeed root hub instead: let a shared HCD skip its PHYs when it asks for it, and let xhci-plat ask for that when the platform glue sets up the USB3 PHY itself. dwc3 asks for it when its glue has a usb3_host_route op, which replaces post_usb3_host_start and runs from xHCI's init_quirk for the shared HCD: after xhci_reset() and dwc3_xhci_plat_start(), before xhci_run(), the same point the routing ran at before. Its error fails the probe before the controller runs. In the Apple glue, that op routes with the error policy dwc3_apple_set_role() had: T8132 and T6050 failures stop the host, other ports warn and run USB2 only with both root hubs up. It acts only in the task that runs dwc3_apple_host_start() under the glue lock. dwc3_apple_host_start() binds xHCI itself when the driver core left the probe asynchronous, does not probe again once the PIPE has moved, and returns the routing's result, so that dwc3_apple_init() stops the core on any failure. Model platform_device_add() and xhci_plat_probe() in atc-t8132-usb3 the way they behave, with T8132 -ETIMEDOUT, T6050 -EIO and -ENOLINK, the T8103 USB2-only fallback, asynchronous and late probes, and negative controls for routing before xhci_reset(), routing from the root hub, a lost error, a probe repeated on the live PIPE and a probe outside the glue lock. Signed-off-by: Diljit Singh --- drivers/usb/core/hcd.c | 8 +- drivers/usb/dwc3/core.h | 7 +- drivers/usb/dwc3/dwc3-apple-state.h | 11 +- drivers/usb/dwc3/dwc3-apple.c | 177 ++++++++---- drivers/usb/dwc3/host.c | 34 ++- drivers/usb/host/xhci-plat.c | 2 + drivers/usb/host/xhci-plat.h | 2 + tools/asahi/neo-stability-tests.py | 2 + .../selftests/drivers/apple/atc-t8132-usb3.py | 266 +++++++++++++++--- .../drivers/gpu/apple-dcp/dwc3/mocks.c | 6 + 10 files changed, 397 insertions(+), 118 deletions(-) diff --git a/drivers/usb/core/hcd.c b/drivers/usb/core/hcd.c index 0ea6a9a729bc52..7a96c9f01ed56c 100644 --- a/drivers/usb/core/hcd.c +++ b/drivers/usb/core/hcd.c @@ -2814,10 +2814,10 @@ int usb_add_hcd(struct usb_hcd *hcd, struct usb_hcd *shared_hcd; int skip_phy_initialization; - if (usb_hcd_is_primary_hcd(hcd)) - skip_phy_initialization = hcd->skip_phy_initialization; - else - skip_phy_initialization = hcd->primary_hcd->skip_phy_initialization; + /* A shared HCD skips its PHYs when it or its primary HCD asks for it. */ + skip_phy_initialization = hcd->skip_phy_initialization; + if (!usb_hcd_is_primary_hcd(hcd)) + skip_phy_initialization |= hcd->primary_hcd->skip_phy_initialization; if (!skip_phy_initialization) { if (usb_hcd_is_primary_hcd(hcd)) { diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index 18726d8d4a8c74..2b665349277ec4 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -1004,14 +1004,15 @@ struct dwc3_scratchpad_array { * @pre_run_stop: Notify run stop enable/disable information to glue * @pre_host_resume: Before xHCI touches the core at a system resume; an error keeps it away, * and a positive value says the core lost its state and was set up again - * @post_usb3_host_start: After xHCI's SuperSpeed root hub has configured the USB3 PHY, - * before xhci_run() starts the host controller + * @usb3_host_route: Sets up the USB3 PHY for xHCI's SuperSpeed root hub, which then leaves + * that PHY alone; runs after xhci_reset(), before xhci_run() starts the + * host controller, and an error fails xHCI's probe */ struct dwc3_glue_ops { void (*pre_set_role)(struct dwc3 *dwc, enum usb_role role); void (*pre_run_stop)(struct dwc3 *dwc, bool is_on); int (*pre_host_resume)(struct dwc3 *dwc); - void (*post_usb3_host_start)(struct dwc3 *dwc); + int (*usb3_host_route)(struct dwc3 *dwc); }; /** diff --git a/drivers/usb/dwc3/dwc3-apple-state.h b/drivers/usb/dwc3/dwc3-apple-state.h index bdaf181907fea4..50cb05550bc006 100644 --- a/drivers/usb/dwc3/dwc3-apple-state.h +++ b/drivers/usb/dwc3/dwc3-apple-state.h @@ -52,13 +52,12 @@ static inline int dwc3_apple_usb2_mode_before_reset(enum dwc3_apple_state target * dwc3_apple_usb3_mode_before_start() - USB3 PHY mode to select before xHCI or gadget starts * @target: the state the controller is brought up in * @pipe_reset_before_host: true if the controller pulses PHYSOFTRST before xHCI starts - * @mode: set to the mode to select, or to PHY_MODE_INVALID to leave host routing to xHCI + * @mode: set to the mode to select, or to PHY_MODE_INVALID to route a host once xHCI has reset * - * Device mode has no xHCI root hub to select it later, so it routes the USB3 PHY before - * dwc3_gadget_init(). Host mode leaves USB3 PHY routing to xHCI's SuperSpeed root hub - * (usb_add_hcd() on the shared HCD), which runs after xhci_reset() (USBCMD.HCRST) has - * completed on the dummy PIPE producer and dwc3_xhci_plat_start() has enabled SUSPHY. - * Routing the live USB3 PHY before dwc3_host_init() exposes an ongoing SuperSpeed link + * Device mode routes the USB3 PHY before dwc3_gadget_init(). Host mode routes it while xHCI + * sets up its SuperSpeed root hub, after xhci_reset() (USBCMD.HCRST) has completed on the + * dummy PIPE producer and dwc3_xhci_plat_start() has enabled SUSPHY, and before xhci_run(): + * routing the live USB3 PHY before dwc3_host_init() exposes an ongoing SuperSpeed link * handshake to HCRST and can leave a partner hub stuck in Rx.Detect. Controllers that must * pulse GUSB3PIPECTL.PHYSOFTRST before xHCI starts still route the PHY beforehand. * diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index fc409f7781cbf1..c97f40b0aa9890 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -193,6 +194,14 @@ struct dwc3_apple { bool pre_core_rpm; bool dt_dis_u3_susphy; bool sleep_ddr; + /* + * A host's USB3 PHY is routed from xHCI's probe, see dwc3_apple_usb3_host_route(): the + * task that runs that probe under the glue lock, whether the routing is still owed, and + * its result (-EINPROGRESS until the SuperSpeed root hub was set up). + */ + struct task_struct *host_start_task; + bool usb3_host_owed; + int usb3_host_ret; struct notifier_block pm_nb; /* Kept through a deep sleep, with the PHY's hibernation, and the GUID it had. */ bool sleep_in_place; @@ -651,28 +660,11 @@ static int dwc3_apple_pre_host_resume(struct dwc3 *dwc) return ret; } -static void dwc3_apple_post_usb3_host_start(struct dwc3 *dwc) -{ - struct dwc3_apple *appledwc = to_dwc3_apple(dwc); - - if (!appledwc->usb3_phy) - return; - - /* - * These PHYs do not bring a SuperSpeed link back from U3 once - * the core has suspended them: keep them out of P3 from here on, - * once xHCI's shared HCD has finished routing the USB3 PIPE. - */ - if (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || - of_device_is_compatible(appledwc->dev->of_node, "apple,t8142-dwc3")) { - dwc->dis_u3_susphy_quirk = true; - dwc3_enable_susphy(dwc, true); - } -} +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc); static const struct dwc3_glue_ops dwc3_apple_glue_ops = { .pre_host_resume = dwc3_apple_pre_host_resume, - .post_usb3_host_start = dwc3_apple_post_usb3_host_start, + .usb3_host_route = dwc3_apple_usb3_host_route, }; static bool dwc3_apple_host_before_core_init(struct dwc3_apple *appledwc, @@ -966,8 +958,48 @@ static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *appledwc) } /* - * Select the role in the core and route the USB3 PHY when it is not left to - * xHCI's shared SuperSpeed root hub. + * Route the USB3 PHY for the role. This platform requires SUSPHY to be enabled already in order + * to properly configure the PHY and switch dwc3's PIPE interface to the USB3 PHY. + */ +static int dwc3_apple_route_usb3(struct dwc3_apple *appledwc, enum phy_mode mode) +{ + bool host = mode == PHY_MODE_USB_HOST; + int ret; + + lockdep_assert_held(&appledwc->lock); + + ret = phy_set_mode(appledwc->usb3_phy, mode); + if (ret) { + /* + * A failed T8132 BIST or PIPE handoff must not start xHCI. Neither must a failed + * T6050 one: that PHY reports a port left on USB2 (four DisplayPort lanes) as + * success, and its errors leave the PIPE without a known producer. + */ + if (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || + of_device_is_compatible(appledwc->dev->of_node, "apple,t6050-dwc3")) { + dev_err(appledwc->dev, "USB3 PHY setup failed, err=%d\n", ret); + return ret; + } + dev_warn(appledwc->dev, "USB3 PHY setup failed, USB2 only, err=%d\n", ret); + } else if (host && appledwc->usb3_phy && + (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || + of_device_is_compatible(appledwc->dev->of_node, "apple,t8142-dwc3"))) { + /* + * These PHYs do not bring a SuperSpeed link back from U3 once + * the core has suspended them: keep them out of P3 from here on. + */ + appledwc->dwc.dis_u3_susphy_quirk = true; + dwc3_enable_susphy(&appledwc->dwc, true); + } else if (host && appledwc->usb3_phy && + of_device_is_compatible(appledwc->dev->of_node, "apple,t6040-dwc3")) { + dwc3_apple_usb3_pipe_reset(appledwc); + } + return 0; +} + +/* + * Select the role in the core, and route the USB3 PHY before the gadget or xHCI starts unless + * dwc3_apple_usb3_mode_before_start() leaves a host's routing to dwc3_apple_usb3_host_route(). */ static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_state state) { @@ -986,40 +1018,83 @@ static int dwc3_apple_set_role(struct dwc3_apple *appledwc, enum dwc3_apple_stat appledwc->dwc.dr_mode = host ? USB_DR_MODE_HOST : USB_DR_MODE_PERIPHERAL; dwc3_apple_set_ptrcap(appledwc, host ? DWC3_GCTL_PRTCAP_HOST : DWC3_GCTL_PRTCAP_DEVICE); appledwc->dwc.dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; - if (mode == PHY_MODE_INVALID) { - /* - * Keep SUSPHY clear through xHCI's HCRST on the dummy PIPE; - * dwc3_xhci_plat_start() enables SUSPHY after HCRST completes, - * before the shared HCD routes the USB3 PHY. - */ - dwc3_enable_susphy(&appledwc->dwc, false); + /* + * A routing left to xHCI keeps SUSPHY clear through xhci_reset() on the dummy PIPE: + * dwc3_xhci_plat_start() enables it once that reset has completed. + */ + appledwc->usb3_host_owed = host && mode == PHY_MODE_INVALID; + dwc3_enable_susphy(&appledwc->dwc, !appledwc->usb3_host_owed); + if (appledwc->usb3_host_owed) return 0; + + return dwc3_apple_route_usb3(appledwc, mode); +} + +/* + * Runs from xHCI's probe as its SuperSpeed root hub is set up: after xhci_reset() (USBCMD.HCRST) + * has completed on the dummy PIPE, with SUSPHY enabled, and before xhci_run() starts the + * controller. The root hub leaves the USB3 PHY alone (see dwc3_host_init()), so routing the + * live PIPE here cannot expose a SuperSpeed link handshake to that reset, and an error both + * stops xHCI before it starts and reaches dwc3_apple_host_start(). Only the probe that + * dwc3_apple_host_start() runs under the glue lock routes; any other one, such as a probe + * the driver core ran asynchronously, is refused, and dwc3_apple_host_start() probes again. + */ +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc) +{ + struct dwc3_apple *appledwc = to_dwc3_apple(dwc); + + if (READ_ONCE(appledwc->host_start_task) != current) + return -EBUSY; + + lockdep_assert_held(&appledwc->lock); + appledwc->usb3_host_ret = 0; + if (appledwc->usb3_host_owed) + appledwc->usb3_host_ret = dwc3_apple_route_usb3(appledwc, PHY_MODE_USB_HOST); + appledwc->usb3_host_owed = false; + + return appledwc->usb3_host_ret; +} + +/* + * Start xHCI, with its USB3 PHY routed. dwc3_host_init() does not report a failed xHCI probe + * (platform_device_add() ignores it), and the driver core may have left that probe to run + * asynchronously, or to a driver not registered yet: bind it here, so that the routing's + * result is known and nothing routes the PIPE later without the glue lock. A probe that has + * routed it is not repeated, as its xhci_reset() would then run on the live PIPE. + */ +static int dwc3_apple_host_start(struct dwc3_apple *appledwc) +{ + struct dwc3 *dwc = &appledwc->dwc; + bool bound = false; + int ret; + + lockdep_assert_held(&appledwc->lock); + + appledwc->usb3_host_ret = -EINPROGRESS; + WRITE_ONCE(appledwc->host_start_task, current); + ret = dwc3_host_init(dwc); + if (!ret) { + scoped_guard(device, &dwc->xhci->dev) + bound = device_is_bound(&dwc->xhci->dev); + if (!bound && appledwc->usb3_host_ret == -EINPROGRESS) + bound = device_attach(&dwc->xhci->dev) > 0; } + WRITE_ONCE(appledwc->host_start_task, NULL); + if (ret) + return ret; - /* - * Device mode and T6040 (which pulses PHYSOFTRST before xHCI starts) - * need SUSPHY enabled here so the PHY can lock and switch the PIPE - * handler before starting the gadget or host. - */ - dwc3_enable_susphy(&appledwc->dwc, true); - ret = phy_set_mode(appledwc->usb3_phy, mode); + ret = appledwc->usb3_host_ret; + /* No SuperSpeed root hub was set up: xHCI has none, or no driver has bound it yet. */ + if (ret == -EINPROGRESS) + ret = bound ? 0 : -EPROBE_DEFER; + else if (!ret && !bound) + ret = -ENODEV; if (ret) { - /* - * A failed T8132 BIST or PIPE handoff must not start gadget mode. - * Neither must a failed T6050 one: that PHY reports a port left on - * USB2 (four DisplayPort lanes) as success, and its errors leave - * the PIPE without a known producer. - */ - if (of_device_is_compatible(appledwc->dev->of_node, "apple,t8132-dwc3") || - of_device_is_compatible(appledwc->dev->of_node, "apple,t6050-dwc3")) { - dev_err(appledwc->dev, "USB3 PHY setup failed, err=%d\n", ret); - return ret; - } - dev_warn(appledwc->dev, "USB3 PHY setup failed, USB2 only, err=%d\n", ret); - } else if (pipe_reset) { - dwc3_apple_usb3_pipe_reset(appledwc); + /* dwc3_host_exit() lets the USB3 PHY into P3 for the PIPE handback */ + dwc->dis_u3_susphy_quirk = appledwc->dt_dis_u3_susphy; + dwc3_host_exit(dwc); } - return 0; + return ret; } /* @@ -1062,7 +1137,7 @@ static int dwc3_apple_init(struct dwc3_apple *appledwc, enum dwc3_apple_state st switch (state) { case DWC3_APPLE_HOST: - ret = dwc3_host_init(&appledwc->dwc); + ret = dwc3_apple_host_start(appledwc); if (ret) { dev_err(appledwc->dev, "Failed to initialize host, ret=%d\n", ret); goto core_exit; diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c index df8cff0b704546..358ce65772aa7a 100644 --- a/drivers/usb/dwc3/host.c +++ b/drivers/usb/dwc3/host.c @@ -67,18 +67,33 @@ static void dwc3_power_off_all_roothub_ports(struct dwc3 *dwc) static void dwc3_xhci_plat_start(struct usb_hcd *hcd) { - struct platform_device *pdev = to_platform_device(hcd->self.controller); - struct dwc3 *dwc = dev_get_drvdata(pdev->dev.parent); + struct platform_device *pdev; + struct dwc3 *dwc; - if (!usb_hcd_is_primary_hcd(hcd)) { - if (dwc->glue_ops && dwc->glue_ops->post_usb3_host_start) - dwc->glue_ops->post_usb3_host_start(dwc); + if (!usb_hcd_is_primary_hcd(hcd)) return; - } + + pdev = to_platform_device(hcd->self.controller); + dwc = dev_get_drvdata(pdev->dev.parent); dwc3_enable_susphy(dwc, true); } +/* + * The SuperSpeed root hub is set up after xhci_reset() and dwc3_xhci_plat_start() on the + * primary HCD, and before xhci_run() starts the controller. + */ +static int dwc3_xhci_plat_init_quirk(struct usb_hcd *hcd) +{ + struct platform_device *pdev = to_platform_device(hcd->self.controller); + struct dwc3 *dwc = dev_get_drvdata(pdev->dev.parent); + + if (usb_hcd_is_primary_hcd(hcd) || !dwc->glue_ops || !dwc->glue_ops->usb3_host_route) + return 0; + + return dwc->glue_ops->usb3_host_route(dwc); +} + static int dwc3_xhci_plat_resume_quirk(struct usb_hcd *hcd) { struct platform_device *pdev = to_platform_device(hcd->self.controller); @@ -92,6 +107,7 @@ static int dwc3_xhci_plat_resume_quirk(struct usb_hcd *hcd) static const struct xhci_plat_priv dwc3_xhci_plat_quirk = { .plat_start = dwc3_xhci_plat_start, + .init_quirk = dwc3_xhci_plat_init_quirk, .resume_quirk = dwc3_xhci_plat_resume_quirk, }; @@ -190,6 +206,7 @@ EXPORT_SYMBOL_IF_KUNIT(dwc3_host_xhci_properties); int dwc3_host_init(struct dwc3 *dwc) { struct property_entry props[DWC3_XHCI_MAX_PROPERTIES + 1]; + struct xhci_plat_priv priv = dwc3_xhci_plat_quirk; struct platform_device *xhci; int ret, irq; int prop_idx = 0; @@ -231,8 +248,9 @@ int dwc3_host_init(struct dwc3 *dwc) } } - ret = platform_device_add_data(xhci, &dwc3_xhci_plat_quirk, - sizeof(struct xhci_plat_priv)); + /* A glue that sets up the USB3 PHY itself keeps it off the SuperSpeed root hub. */ + priv.skip_usb3_phy_init = dwc->glue_ops && dwc->glue_ops->usb3_host_route; + ret = platform_device_add_data(xhci, &priv, sizeof(priv)); if (ret) goto err; diff --git a/drivers/usb/host/xhci-plat.c b/drivers/usb/host/xhci-plat.c index 5ded59ac0f54de..0f891d99527f6a 100644 --- a/drivers/usb/host/xhci-plat.c +++ b/drivers/usb/host/xhci-plat.c @@ -365,6 +365,8 @@ int xhci_plat_probe(struct platform_device *pdev, struct device *sysdev, const s } xhci->shared_hcd->tpl_support = hcd->tpl_support; + if (priv && priv->skip_usb3_phy_init) + xhci->shared_hcd->skip_phy_initialization = 1; } usb3_hcd = xhci_get_usb3_hcd(xhci); diff --git a/drivers/usb/host/xhci-plat.h b/drivers/usb/host/xhci-plat.h index 0c4affdb5236d0..6ddee6b064f922 100644 --- a/drivers/usb/host/xhci-plat.h +++ b/drivers/usb/host/xhci-plat.h @@ -17,6 +17,8 @@ struct xhci_plat_priv { unsigned long long quirks; bool power_lost; unsigned sideband_at_suspend:1; + /* The platform glue sets up the USB3 PHY: the SuperSpeed root hub leaves it alone. */ + unsigned skip_usb3_phy_init:1; void (*plat_start)(struct usb_hcd *); int (*init_quirk)(struct usb_hcd *); int (*suspend_quirk)(struct usb_hcd *); diff --git a/tools/asahi/neo-stability-tests.py b/tools/asahi/neo-stability-tests.py index 34339436597466..530417adfd5c00 100644 --- a/tools/asahi/neo-stability-tests.py +++ b/tools/asahi/neo-stability-tests.py @@ -91,6 +91,8 @@ def function(source, name): static void pm_runtime_mark_last_busy(struct device*d){} static void pm_runtime_put_autosuspend(struct device*d){rpm_puts++;} static int dwc3_host_init(struct dwc3*d){return host_error;} +/* The xHCI start and its USB3 routing; atc-t8132-usb3 models them. */ +static int dwc3_apple_host_start(struct dwc3_apple*a){return dwc3_host_init(&a->dwc);} static int dwc3_gadget_init(struct dwc3*d){return gadget_error;} static void dwc3_host_exit(struct dwc3*d){role_exits++;} static void dwc3_gadget_exit(struct dwc3*d){role_exits++;} diff --git a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py index 8abaae8d46a4dc..0c0883ef8dcb53 100755 --- a/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py +++ b/tools/testing/selftests/drivers/apple/atc-t8132-usb3.py @@ -43,16 +43,19 @@ def defines(source): return "".join(result) -def run(tmp, name, program, expect_failure=False): +def run(tmp, name, program, expect_failure=False, expect=None): path = tmp / (name + ".c") path.write_text(program) binary = tmp / name subprocess.run(["cc", "-std=gnu11", "-Wall", "-Werror", "-Wno-unused-function", str(path), "-o", str(binary)], check=True) - result = subprocess.run([str(binary)], capture_output=expect_failure) + result = subprocess.run([str(binary)], capture_output=expect_failure, text=True) if expect_failure: if result.returncode == 0: raise RuntimeError(f"negative control passed: {name}") + # A control must fail on the check it is for, not on another one. + if expect and expect not in result.stderr: + raise RuntimeError(f"negative control failed elsewhere: {name}: {result.stderr.strip()}") else: result.check_returncode() @@ -371,47 +374,104 @@ def main(): #include #include #include -#define lockdep_assert_held(x) ((void)0) #define dev_warn(...) ((void)0) #define dev_err(...) ((void)0) +#define dev_info(...) ((void)0) #define WARN_ON_ONCE(x) ((void)(x)) +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +#define EPROBE_DEFER 517 +#define scoped_guard(type, lock) #define USB_DR_MODE_HOST 1 #define USB_DR_MODE_PERIPHERAL 2 #define DWC3_GCTL_PRTCAP_HOST 1 #define DWC3_GCTL_PRTCAP_DEVICE 2 #define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) enum phy_mode { PHY_MODE_INVALID, PHY_MODE_USB_HOST, PHY_MODE_USB_DEVICE }; -struct device { const char *of_node; }; -struct dwc3 { int dr_mode, current_dr_role; bool dis_u3_susphy_quirk; }; -struct dwc3_apple { struct dwc3 dwc; struct device *dev; void *usb2_phy, *usb3_phy; int lock, state; - bool dt_dis_u3_susphy, host_only, sleep_ddr; }; +/* The task running the code: the glue's, or another one probing xHCI. */ +struct task_struct { int id; }; +static struct task_struct glue_task, other_task, *current_task = &glue_task, *lock_owner; +#define current current_task +#define lockdep_assert_held(x) assert(lock_owner == current) +struct device { const char *of_node; bool registered, bound; }; +struct platform_device { struct device dev; }; +struct dwc3 { int dr_mode, current_dr_role; bool dis_u3_susphy_quirk; struct platform_device *xhci; }; +struct dwc3_apple { struct dwc3 dwc; struct device *dev; void *usb2_phy, *usb3_phy, *role_sw; int lock, state; + bool dt_dis_u3_susphy, host_only, sleep_ddr, fixed_hub, sleep_phy_wait, sleep_phy_pending; + struct task_struct *host_start_task; bool usb3_host_owed; int usb3_host_ret; }; #define to_dwc3_apple(d) container_of((d), struct dwc3_apple, dwc) -static int phy_error, phy_calls, pre_host_phy_calls, host_calls, gadget_calls, stops, syscore, pipe_resets; +static struct platform_device xhci_pdev; +/* The xHCI model: its probe's progress, and what the PIPE and the controller do meanwhile. */ +static bool driver_registered = true, async_probe, async_race, hcrst_done, running, pipe_live, pipe_reset; +static int phy_error, phy_calls, pre_host_phy_calls, probes, refused, host_calls, host_exits, gadget_calls; +static int stops, syscore, pipe_resets, slp_votes, late_error; static bool susphy_on; +/* The SuperSpeed root hub leaves the USB3 PHY to the glue, see dwc3_host_init(). */ +static const bool skip_usb3_phy_init = true; static bool of_device_is_compatible(const char *node, const char *name) { return !strcmp(node,name); } static int phy_set_mode(void *phy, int mode) { - (void)phy; (void)mode; + (void)phy; assert(susphy_on); + /* A host's PIPE moves only after xHCI's reset and before it runs, under the glue lock. */ + if (mode == PHY_MODE_USB_HOST && xhci_pdev.dev.registered) + assert(hcrst_done && !running && lock_owner == current); phy_calls++; + pipe_live = !phy_error; return phy_error; } static void dwc3_apple_set_ptrcap(struct dwc3_apple *a, int cap) { (void)a; (void)cap; } static void dwc3_enable_susphy(struct dwc3 *d, bool on) { susphy_on = on && !d->dis_u3_susphy_quirk; } static int dwc3_gadget_init(struct dwc3 *d) { (void)d; gadget_calls++; return 0; } static int phy_reset(void *phy) { (void)phy; return 0; } -static void dwc3_host_exit(struct dwc3 *d) { (void)d; assert(0); } -static void apple_sleep_usb_slp_ddr(bool on) { (void)on; assert(0); } -static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; pipe_resets++; } +static void apple_sleep_usb_slp_ddr(bool on) { slp_votes += on ? 1 : -1; } +/* T6040 resets the PIPE it routed before xHCI starts, see dwc3_apple_usb3_mode_before_start(). */ +static void dwc3_apple_usb3_pipe_reset(struct dwc3_apple *a) { (void)a; pipe_resets++; pipe_reset = true; } +static bool dwc3_apple_sleep_board(void) { return true; } +static void dwc3_apple_check_hub_later(struct dwc3_apple *a) { (void)a; } ''' + enum(states, "dwc3_apple_state") + function(states, "dwc3_apple_usb3_mode_before_start") + r''' static int dwc3_apple_core_start(struct dwc3_apple *a, enum dwc3_apple_state s) { (void)a; (void)s; return 0; } static int dwc3_apple_core_stop(struct dwc3_apple *a) { (void)a; stops++; return 0; } static void dwc3_apple_syscore(struct dwc3_apple *a, bool on) { (void)a; assert(on); syscore++; } -''' + function(dwc, "dwc3_apple_post_usb3_host_start") + r''' -/* Model xhci_plat_probe(): HCRST on dummy PIPE, primary plat_start enables SUSPHY, shared HCD routes USB3. */ +static int dwc3_apple_usb3_host_route(struct dwc3 *dwc); +static struct dwc3 *xhci_parent; +/* + * xhci_plat_probe(): usb_add_hcd() on the primary HCD runs xhci_reset() (HCRST), which must not + * meet a live PIPE, and dwc3_xhci_plat_start() enables SUSPHY. usb_add_hcd() on the shared HCD + * then sets up its PHYs unless told to skip them, and runs dwc3_xhci_plat_init_quirk() before + * xhci_run(). Any failure tears both HCDs down, and the probe fails. + */ +static int xhci_plat_probe(void) +{ + int ret = 0; + + probes++; + assert(!pipe_live || pipe_reset); + hcrst_done = true; + dwc3_enable_susphy(xhci_parent, true); + if (!skip_usb3_phy_init) { + ret = phy_set_mode(to_dwc3_apple(xhci_parent)->usb3_phy, PHY_MODE_USB_HOST); + if (ret) + goto fail; + } + ret = dwc3_apple_usb3_host_route(xhci_parent); + if (ret == -EBUSY) + refused++; + if (!ret) + ret = late_error; + if (ret) + goto fail; + running = true; + xhci_pdev.dev.bound = true; + return 0; +fail: + /* xhci_stop() resets the controller on the teardown, wherever the PIPE is. */ + hcrst_done = false; + return ret; +} +/* platform_device_add(): its probe's result does not reach the caller. */ static int dwc3_host_init(struct dwc3 *d) { struct dwc3_apple *a = to_dwc3_apple(d); - int ret; pre_host_phy_calls = phy_calls; host_calls++; @@ -419,49 +479,163 @@ def main(): assert(!susphy_on); assert(!phy_calls); } - dwc3_enable_susphy(d, true); - if (a->usb3_phy && !phy_calls) { - ret = phy_set_mode(a->usb3_phy, PHY_MODE_USB_HOST); - if (ret) - return ret; - } - dwc3_apple_post_usb3_host_start(d); + memset(&xhci_pdev, 0, sizeof(xhci_pdev)); + xhci_pdev.dev.registered = true; + xhci_parent = d; + d->xhci = &xhci_pdev; + hcrst_done = running = false; + if (driver_registered && !async_probe) + (void)xhci_plat_probe(); return 0; } -''' + function(dwc, "dwc3_apple_set_role") + function(dwc, "dwc3_apple_init") + r''' +static bool device_is_bound(struct device *dev) { return dev->bound; } +/* device_attach(): an asynchronous probe may run first, in its own task, then this one binds. */ +static int device_attach(struct device *dev) +{ + if (dev->bound) + return 1; + if (!driver_registered) + return 0; + if (async_race) { + current_task = &other_task; + (void)xhci_plat_probe(); + current_task = &glue_task; + } + return xhci_plat_probe() ? 0 : 1; +} +static void dwc3_host_exit(struct dwc3 *d) +{ + assert(d->xhci == &xhci_pdev && xhci_pdev.dev.registered); + host_exits++; + xhci_pdev.dev.registered = xhci_pdev.dev.bound = false; + running = hcrst_done = pipe_live = false; + d->xhci = NULL; +} +''' + "".join(function(dwc, name) for name in ( + "dwc3_apple_route_usb3", "dwc3_apple_set_role", "dwc3_apple_usb3_host_route", + "dwc3_apple_host_start", "dwc3_apple_init", "dwc3_apple_start_after_sleep")) + r''' +static void reset(struct dwc3_apple *a, const char *node, int error) +{ + a->dev->of_node = node; + a->state = DWC3_APPLE_NO_CABLE; + a->dwc.dis_u3_susphy_quirk = false; + phy_error = error; + phy_calls = pre_host_phy_calls = probes = refused = host_exits = 0; + pipe_live = running = hcrst_done = pipe_reset = false; + driver_registered = true; + async_probe = async_race = false; + late_error = 0; +} +/* A host that started: xHCI bound and running, both root hubs up. */ +static void started(struct dwc3_apple *a) +{ + assert(a->state == DWC3_APPLE_HOST && xhci_pdev.dev.bound && running && !host_exits); + a->state = DWC3_APPLE_NO_CABLE; + xhci_pdev.dev.registered = xhci_pdev.dev.bound = false; +} +/* A host that did not: no xHCI left behind, the core stopped, no host state recorded. */ +static void stopped(struct dwc3_apple *a, int s) +{ + assert(stops == s && host_exits == 1 && !xhci_pdev.dev.registered && !running); + assert(a->state == DWC3_APPLE_NO_CABLE && a->dwc.xhci == NULL); +} int main(void) { struct device dev = { "apple,t8132-dwc3" }; - struct dwc3_apple a = { .dev=&dev, .usb3_phy=&dev, .state=DWC3_APPLE_NO_CABLE }; - phy_error=-ETIMEDOUT; phy_calls=0; - assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ETIMEDOUT); - assert(host_calls==1 && !pre_host_phy_calls && phy_calls==1 && !gadget_calls && stops==1 && a.state==DWC3_APPLE_NO_CABLE); - phy_error=-EOPNOTSUPP; phy_calls=0; - assert(dwc3_apple_init(&a,DWC3_APPLE_DEVICE)==-EOPNOTSUPP); - assert(!gadget_calls && stops==2 && phy_calls==1); - phy_error=0; phy_calls=0; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST)); - assert(host_calls==2 && !pre_host_phy_calls && phy_calls==1 && a.state==DWC3_APPLE_HOST && syscore==1); - /* A T8132 host keeps its USB3 PHY out of P3 once shared HCD routing completes. */ + struct dwc3_apple a = { .dev=&dev, .usb3_phy=&dev, .role_sw=&dev, .state=DWC3_APPLE_NO_CABLE }; + int s = 0, cores = 0; + + lock_owner = &glue_task; + /* T8132: routed once, after HCRST, out of P3 before xHCI runs. */ + reset(&a, "apple,t8132-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(probes==1 && phy_calls==1 && !pre_host_phy_calls); assert(a.dwc.dis_u3_susphy_quirk && !susphy_on); - dev.of_node="apple,t6050-dwc3"; phy_error=0; phy_calls=0; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==3 && !pre_host_phy_calls && phy_calls==1 && syscore==2); + started(&a); + /* T6050 keeps SUSPHY. */ + reset(&a, "apple,t6050-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores && phy_calls==1); assert(!a.dwc.dis_u3_susphy_quirk && susphy_on); - dev.of_node="apple,t6040-dwc3"; phy_error=0; phy_calls=0; - assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && host_calls==4 && pre_host_phy_calls==1 && pipe_resets==1 && syscore==3); - dev.of_node="apple,t8103-dwc3"; phy_error=-ETIMEDOUT; phy_calls=0; - assert(!dwc3_apple_init(&a,DWC3_APPLE_DEVICE) && gadget_calls==1 && syscore==4); + started(&a); + /* T6040 routes and resets its PIPE before xHCI, which then leaves it alone. */ + reset(&a, "apple,t6040-dwc3", 0); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(pre_host_phy_calls==1 && phy_calls==1 && pipe_resets==1); + started(&a); + /* Older Type-C ports: a USB3 failure leaves both root hubs up, USB2 only. */ + reset(&a, "apple,t8103-dwc3", -ETIMEDOUT); + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores && stops==s); + assert(probes==1 && phy_calls==1 && !pipe_live && !a.dwc.dis_u3_susphy_quirk); + started(&a); + /* T8132: a BIST timeout fails xHCI before it runs and reaches dwc3_apple_init(). */ + reset(&a, "apple,t8132-dwc3", -ETIMEDOUT); + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ETIMEDOUT); + stopped(&a, ++s); + assert(probes==1 && phy_calls==1 && !pre_host_phy_calls && syscore==cores && !slp_votes); + /* T6050: a PIPE fault the same way. */ + reset(&a, "apple,t6050-dwc3", -EIO); a.sleep_ddr=true; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-EIO); + stopped(&a, ++s); + assert(probes==1 && phy_calls==1 && syscore==cores && !slp_votes); + /* T6050 after a sleep: a PHY not started yet leaves the start to the role switch. */ + reset(&a, "apple,t6050-dwc3", -ENOLINK); + assert(!dwc3_apple_start_after_sleep(&a,DWC3_APPLE_HOST)); + stopped(&a, ++s); + assert(a.sleep_phy_pending && !a.sleep_phy_wait && syscore==cores && !slp_votes); + a.sleep_phy_pending=false; a.sleep_ddr=false; + /* An asynchronous probe from another task is refused; the glue's own one routes. */ + reset(&a, "apple,t6050-dwc3", 0); async_probe=async_race=true; + assert(!dwc3_apple_init(&a,DWC3_APPLE_HOST) && syscore==++cores); + assert(probes==2 && refused==1 && phy_calls==1); + started(&a); + /* No xHCI driver yet: nothing routes the PIPE, and the probe is deferred. */ + reset(&a, "apple,t6050-dwc3", 0); driver_registered=false; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-EPROBE_DEFER); + stopped(&a, ++s); + assert(!probes && !phy_calls); + /* xHCI failing after the PIPE moved is not probed again on the live PIPE. */ + reset(&a, "apple,t6050-dwc3", 0); late_error=-ENOMEM; + assert(dwc3_apple_init(&a,DWC3_APPLE_HOST)==-ENODEV); + stopped(&a, ++s); + assert(probes==1 && phy_calls==1); + /* A probe outside a host start, such as a rebind, is refused and routes nothing. */ + reset(&a, "apple,t6050-dwc3", 0); xhci_pdev.dev.registered=true; xhci_parent=&a.dwc; + current_task=&other_task; hcrst_done=false; + assert(xhci_plat_probe()==-EBUSY && !phy_calls && refused==1); + current_task=&glue_task; xhci_pdev.dev.registered=false; + /* Device mode routes before the gadget: T8132 refuses a failure, older ports warn. */ + reset(&a, "apple,t8132-dwc3", -EOPNOTSUPP); + assert(dwc3_apple_init(&a,DWC3_APPLE_DEVICE)==-EOPNOTSUPP); + assert(!gadget_calls && stops==++s && phy_calls==1); + reset(&a, "apple,t8103-dwc3", -ETIMEDOUT); + assert(!dwc3_apple_init(&a,DWC3_APPLE_DEVICE) && gadget_calls==1 && syscore==++cores); assert(!a.dwc.dis_u3_susphy_quirk); - puts("ok 7 - USB3 host routing deferred past HCRST, T8132/T6050/T6040/device policies preserved"); + puts("ok 7 - USB3 host routed between HCRST and xHCI start, errors reach dwc3_apple_init, USB2-only fallback"); return 0; } ''' run(Path(directory), "dwc3-t8132", role_program) - early_usb3 = role_program.replace( - "*mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID;", - "*mode = PHY_MODE_USB_HOST;", 1) - assert early_usb3 != role_program - run(Path(directory), "dwc3-usb3-before-host-negative-control", early_usb3, expect_failure=True) + controls = { + # The PIPE routed before dwc3_host_init() would meet xhci_reset(). + "dwc3-usb3-before-host": ("*mode = pipe_reset_before_host ? PHY_MODE_USB_HOST : PHY_MODE_INVALID;", + "*mode = PHY_MODE_USB_HOST;", "dwc3_host_init: Assertion"), + # The SuperSpeed root hub routing the PHY too, as its failure tears USB2 down. + "dwc3-usb3-root-hub": ("static const bool skip_usb3_phy_init = true;", + "static const bool skip_usb3_phy_init = false;", "phy_calls==1"), + # A routing failure that no longer reaches dwc3_apple_init(). + "dwc3-usb3-error-lost": ("\tret = appledwc->usb3_host_ret;\n", "\tret = 0;\n", "==-ETIMEDOUT"), + # A probe repeated after the PIPE moved, whose xhci_reset() then meets the live PIPE. + "dwc3-usb3-reprobe-live": ("if (!bound && appledwc->usb3_host_ret == -EINPROGRESS)", + "if (!bound && (appledwc->usb3_host_ret == -EINPROGRESS || !appledwc->usb3_host_ret))", + "xhci_plat_probe: Assertion `!pipe_live"), + # An asynchronous probe that routes without the glue lock. + "dwc3-usb3-foreign-task": ("if (READ_ONCE(appledwc->host_start_task) != current)", + "if (!READ_ONCE(appledwc->host_start_task))", "lock_owner == current"), + } + for name, (old, new, expect) in controls.items(): + control = role_program.replace(old, new, 1) + assert control != role_program, name + run(Path(directory), name + "-negative-control", control, expect_failure=True, expect=expect) permissive = program.replace( "(!atcphy->host_active || pm_suspend_target_state != PM_SUSPEND_TO_IDLE)", "false", 1) assert permissive != program diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c index dd3cb7476f43bb..cf5bd8de5c337b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/dwc3/mocks.c @@ -405,6 +405,12 @@ static int dwc3_host_init(struct dwc3 *d) } return host_init_error; } + +/* The xHCI start and its USB3 routing; atc-t8132-usb3 models them. */ +static int dwc3_apple_host_start(struct dwc3_apple *a) +{ + return dwc3_host_init(&a->dwc); +} static int dwc3_gadget_init(struct dwc3 *d) { (void)d; From 5143298ac33f7c7dcea78fead169e501d5a513ae Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Wed, 25 Nov 2026 12:00:56 +0000 Subject: [PATCH 1329/1514] arm64: dts: apple: t604x-pmgr: allow idle ATC0-2 common domains to power off Drop the obsolete apple,always-on property from ps_atc0_common, ps_atc1_common, and ps_atc2_common so idle USB-C ATC controllers can power off. Boot-time attachment of a firmware-active ps_atcN_usb child under a powered-off ps_atcN_common parent is now handled by apple_pmgr_ps_hold_parents() in drivers/pmdomain/apple/pmgr-pwrstate.c, so the old always-on workaround comment is no longer needed. All enabled consumers under ps_atc0..2_common across T6040 and T6041 boards (dwc3, atcphy, its mailbox, DARTs, the display crossbar, and USB4/CIO where enabled on J614s/J616s; USB4/CIO nodes are absent on J614c/J616c/J575c and disabled on J773s) manage runtime PM, ps_atc0..2_usb_aon remain always-on for wake and Type-C detection, and ps_atc0..2_common_dp carry apple,sleep-wakeup-path which keeps their parent domains up via genpd subdomain refcounting whenever a PHY coprocessor stays running across s2idle. Keep ps_atc3_common always-on in t604x-extdisp.dtsi for fixed HDMI. Signed-off-by: AxxzyWasTaken --- arch/arm64/boot/dts/apple/t604x-pmgr.dtsi | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi index daa6811c841116..3104e3a8374d31 100644 --- a/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-pmgr.dtsi @@ -350,14 +350,17 @@ }; &pmgr_aux { - /* Always on: the firmware leaves ATCn_USB on below it, and genpd refuses an active child under a parent it would turn off. */ + /* + * All USB-C ATC0-2 consumers (dwc3, atcphy, mailbox, DARTs, display + * crossbar, and USB4/CIO where enabled) manage runtime PM; + * ps_atc0..2_usb_aon stay always-on for wake and Type-C detection. + */ ps_atc0_common: power-controller@390 { compatible = "apple,t6041-pmgr-pwrstate", "apple,t8103-pmgr-pwrstate"; reg = <0x390 4>; #power-domain-cells = <0>; #reset-cells = <0>; label = "atc0_common"; - apple,always-on; }; ps_atc1_common: power-controller@3b8 { @@ -366,7 +369,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc1_common"; - apple,always-on; }; ps_atc2_common: power-controller@3e0 { @@ -375,7 +377,6 @@ #power-domain-cells = <0>; #reset-cells = <0>; label = "atc2_common"; - apple,always-on; }; }; From 12900893333d50de284448c249817e7a6409621d Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Wed, 25 Nov 2026 08:08:25 -0500 Subject: [PATCH 1330/1514] thunderbolt: apple: tear down T8122 ACIO routers for deep sleep T8122 (M3) advertises "apple,t8122-usb4-acio", "apple,t8103-usb4-acio" in device tree, but had no match entry of its own in apple_acio_match[] and fell back to apple_cio_t8103_hw. Unlike T8103, T8122 deep sleep removes the CIO power domains and shares the ATC PHY with DWC3. Leaving a live USB4 router (such as a host-to-host XDomain) powered through noirq suspend with mem_sleep=deep hung the system in pm_test=platform before sleep entry on J615, while tearing the port down in PM_SUSPEND_PREPARE allowed platform, processors, core, and Phase 1 dry-run suspend/resume to complete cleanly. Add apple_cio_t8122_hw with sleep_removes_domains, restart_on_wake, and phy_shared_with_dwc3 alongside apple_dpin_m1, matching the T8142 flag design: mem_sleep=deep + mem tears down a connected router ahead of DWC3's PM notifier and requests fresh cable state immediately on wake, while default s2idle and freeze leave the port up unchanged. Extend tools/asahi/pciec-policy-tests.py to cover T8122 ACIO matching, deep-sleep vs s2idle/freeze gating, DWC3 notifier ordering, and negative controls. Signed-off-by: Satya Benson --- drivers/thunderbolt/apple.c | 18 +++ tools/asahi/pciec-policy-tests.py | 176 ++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 760369ea2a7562..f66c192a2ae3e3 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -192,6 +192,20 @@ static const struct apple_cio_hw apple_cio_t8103_hw = { .dp = &apple_dpin_m1, }; +/* + * T8122 shares the T8103 ACIO register layout and DP IN policy, while deep + * sleep removes the CIO power domains and shares the ATC PHY with DWC3. Tear + * down a connected router before tasks freeze (ahead of DWC3's PM notifier) + * and request fresh cable state immediately on wake; s2idle and freeze leave + * the port up. + */ +static const struct apple_cio_hw apple_cio_t8122_hw = { + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, + .dp = &apple_dpin_m1, +}; + static const struct apple_cio_hw apple_cio_t6020_hw = { .dp = &apple_dpin_m2, }; @@ -4896,6 +4910,10 @@ static const struct of_device_id apple_acio_match[] = { .compatible = "apple,t6030-usb4-acio", .data = &apple_cio_t6030_hw, }, + { + .compatible = "apple,t8122-usb4-acio", + .data = &apple_cio_t8122_hw, + }, { .compatible = "apple,t6020-usb4-acio", .data = &apple_cio_t6020_hw, diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index eb05f79c905010..3e753abfdba22f 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -670,6 +670,181 @@ def test_pm_order(out, acio): print('PASS negative control:', name) +T8122_SLEEP_FIXTURE = r''' +#include +#include +#include +#include +#include +struct apple_dpin_policy { int unused; }; +static const struct apple_dpin_policy apple_dpin_m1; +struct apple_cio_hw { + bool sleep_removes_domains; + bool restart_on_wake; + bool phy_shared_with_dwc3; + const struct apple_dpin_policy *dp; +}; +struct notifier_block { int (*notifier_call)(void); int priority; }; +struct apple_cio { const struct apple_cio_hw *hw; struct notifier_block pm_notifier; }; +struct dwc3_apple { struct notifier_block pm_nb; }; +struct match_entry { const char *compatible; const struct apple_cio_hw *data; }; +static bool default_s2idle, no_platform; +static bool pm_suspend_default_s2idle(void) { return default_s2idle; } +static bool pm_suspend_no_platform(void) { return no_platform; } +/* PRODUCTION_HW */ +static const struct match_entry match_table[] = { +/* MATCH_ENTRIES */ + { NULL, NULL }, +}; +/* PRODUCTION_FN */ +static const struct apple_cio_hw *match_of(const char *const *compat) +{ + for (size_t i = 0; compat[i]; i++) + for (size_t j = 0; match_table[j].compatible; j++) + if (!strcmp(compat[i], match_table[j].compatible)) + return match_table[j].data; + return NULL; +} +static struct notifier_block *chain[2]; +static int count; +static bool phy_off, pci_off; +static int register_pm_notifier(struct notifier_block *nb) +{ + int i = count++; + assert(count <= 2); + while (i && chain[i - 1]->priority < nb->priority) { + chain[i] = chain[i - 1]; + i--; + } + chain[i] = nb; + return 0; +} +static int apple_cio_pm_notify(void) +{ + assert(!phy_off); + pci_off = true; + return 0; +} +static int dwc3_apple_pm_notify(void) +{ + assert(pci_off); + phy_off = true; + return 0; +} +static void add_cio(struct apple_cio *acio) +{ + /* ACIO_REGISTRATION */ +} +static void add_dwc(struct dwc3_apple *appledwc) +{ + int ret; + /* DWC_REGISTRATION */ + assert(!ret); +} +int main(void) +{ + static const char *const t8122_compat[] = { + "apple,t8122-usb4-acio", "apple,t8103-usb4-acio", NULL + }; + static const char *const t8103_compat[] = { + "apple,t8103-usb4-acio", NULL + }; + const struct apple_cio_hw *t8122 = match_of(t8122_compat); + const struct apple_cio_hw *t8103 = match_of(t8103_compat); + assert(t8122 == &apple_cio_t8122_hw); + assert(t8103 == &apple_cio_t8103_hw); + assert(t8122->sleep_removes_domains); + assert(t8122->restart_on_wake); + assert(t8122->phy_shared_with_dwc3); + assert(t8122->dp == &apple_dpin_m1); + + struct apple_cio acio_t8122 = { .hw = t8122 }; + struct apple_cio acio_t8103 = { .hw = t8103 }; + + /* mem_sleep=deep + mem tears down T8122 ACIO, leaves T8103 unchanged. */ + default_s2idle = false; + no_platform = false; + assert(apple_cio_sleep_removes_domains(&acio_t8122)); + assert(!apple_cio_sleep_removes_domains(&acio_t8103)); + + /* s2idle keeps the port up. */ + default_s2idle = true; + no_platform = false; + assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + + /* freeze keeps the port up even when mem_sleep=deep is the default. */ + default_s2idle = false; + no_platform = true; + assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + + /* Shared ATC PHY: ACIO PM notifier must run before DWC3's. */ + struct dwc3_apple dwc = { 0 }; + add_dwc(&dwc); + add_cio(&acio_t8122); + for (int i = 0; i < count; i++) + assert(!chain[i]->notifier_call()); + assert(pci_off && phy_off); + + puts("PASS: T8122 ACIO deep-sleep teardown, freeze/s2idle preservation, and DWC3 PM order"); + return 0; +} +''' + + +def test_t8122_cio_sleep(out, acio): + dwc = (ROOT / 'drivers/usb/dwc3/dwc3-apple.c').read_text() + hw_defs = [] + for sym in ('apple_cio_t8103_hw', 'apple_cio_t8122_hw'): + m = re.search(r'^static const struct apple_cio_hw ' + sym + + r' = \{.*?\n\};', acio, re.M | re.S) + assert m, sym + hw_defs.append(m.group()) + match_block = re.search( + r'static const struct of_device_id apple_acio_match\[\] = \{.*?\n\};', + acio, re.S) + assert match_block + entries = re.findall( + r'\.compatible\s*=\s*"([^"]+)"\s*,\s*\.data\s*=\s*(&apple_cio_\w+_hw)', + match_block.group()) + match_lines = [f' {{ "{c}", {d} }},' for c, d in entries + if c in ('apple,t8122-usb4-acio', 'apple,t8103-usb4-acio')] + assert len(match_lines) == 2, match_lines + code = T8122_SLEEP_FIXTURE + code = code.replace('/* PRODUCTION_HW */', '\n'.join(hw_defs)) + code = code.replace('/* MATCH_ENTRIES */', '\n'.join(match_lines)) + code = code.replace('/* PRODUCTION_FN */', + function(acio, 'apple_cio_sleep_removes_domains')) + code = code.replace('/* ACIO_REGISTRATION */', pm_registration( + acio, 'acio->pm_notifier.notifier_call = apple_cio_pm_notify;', + 'register_pm_notifier(&acio->pm_notifier);')) + code = code.replace('/* DWC_REGISTRATION */', pm_registration( + dwc, 'appledwc->pm_nb.notifier_call = dwc3_apple_pm_notify;', + 'ret = register_pm_notifier(&appledwc->pm_nb);')) + muts = { + 't8122-drop-match': (' { "apple,t8122-usb4-acio", &apple_cio_t8122_hw },', ''), + 't8122-drop-sleep-removes-domains': ('\t.sleep_removes_domains = true,\n', ''), + 't8122-drop-phy-shared': ('\t.phy_shared_with_dwc3 = true,\n', ''), + } + cases = {'t8122-cio-sleep': code} + for name, (old, new) in muts.items(): + assert code.count(old) == 1, name + cases[name] = code.replace(old, new) + for name, body in cases.items(): + source, binary = out / (name + '.c'), out / name + source.write_text(body) + subprocess.run(['cc', '-std=gnu11', '-Wall', '-Wextra', '-Werror', + str(source), '-o', str(binary)], check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True) + (out / (name + '.log')).write_text(run.stdout + run.stderr) + if name == 't8122-cio-sleep': + assert run.returncode == 0, run.stderr + print(run.stdout, end='') + else: + assert run.returncode < 0 and 'Assertion' in run.stderr, ( + name, run.returncode, run.stderr) + print('PASS negative control:', name) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=Path) @@ -743,6 +918,7 @@ def main(): out = args.out or Path(tmp) out.mkdir(parents=True, exist_ok=True) test_pm_order(out, acio) + test_t8122_cio_sleep(out, acio) cases = { 'production': code, 'm2-fallback': code.replace( From 785dec503145b8439283a8b901a653094235b8a6 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:21:26 -0500 Subject: [PATCH 1331/1514] tools/asahi: bcm4377-resume: extract bcm4377_clamp_acl_mtu Commit 2fcf03ccec62 ("Bluetooth: hci_bcm4377: cap the ACL MTU at what the ACL ring takes") added a bcm4377_clamp_acl_mtu() call inside bcm4377_hci_post_init(). Extract bcm4377_clamp_acl_mtu() in bcm4377-resume-tests.py and provide HCI_MAX_ACL_SIZE plus hci_dev acl_mtu/le_mtu fields in fixture.h so the host test compiles and links again. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- tools/asahi/bcm4377-resume-tests.py | 2 +- tools/asahi/bcm4377-resume/fixture.h | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/asahi/bcm4377-resume-tests.py b/tools/asahi/bcm4377-resume-tests.py index f8dfa488d50790..e415dc0a76350e 100755 --- a/tools/asahi/bcm4377-resume-tests.py +++ b/tools/asahi/bcm4377-resume-tests.py @@ -12,7 +12,7 @@ def extract(s,n): while depth:depth+=(s[b]=='{')-(s[b]=='}');b+=1 return s[m.start():b]+'\n' s=(r/'drivers/bluetooth/hci_bcm4377.c').read_text();core=(r/'net/bluetooth/hci_sync.c').read_text();core_hci=(r/'net/bluetooth/hci_core.c').read_text() -names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_suspend','bcm4377_resume'] +names=['bcm4377_setup_retry_allowed','bcm4377_queue_setup_retry','bcm4377_setup_retry_work','bcm4377_resume_recovery_supported','bcm4377_resume_recovery_allowed','bcm4377_resume_recovery_invalidate','bcm4377_resume_recovery_sync','bcm4377_resume_recovery_destroy','bcm4377_resume_recovery_work','bcm4377_hci_timeout','bcm4377_resume_recovery_stop','bcm4377_hci_open','bcm4377_hci_close','bcm4377_hci_setup_once','bcm4377_hci_setup','bcm4377_clamp_acl_mtu','bcm4377_hci_post_init','bcm4377_hci_unregister_dev','bcm4377_sleep_finish','bcm4377_suspend','bcm4377_resume'] bodies={n:extract(s,n) for n in names};shared=[] if a.old_ref: old=subprocess.check_output(['git','show',a.old_ref+':drivers/bluetooth/hci_bcm4377.c'],cwd=r,text=True) diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index cb47a5d7ae3b78..7c053b3012ff68 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -23,6 +23,7 @@ #define HCI_SETUP 1 #define HCI_AUTO_OFF 2 #define HCI_UNREGISTER 4 +#define HCI_MAX_ACL_SIZE 1024 #define HCI_USER_CHANNEL 8 #define HCI_RUNNING 16 #define HCI_UP 32 @@ -45,7 +46,7 @@ static void bacpy(bdaddr_t *a,const bdaddr_t *b) { *a=*b; } static int bacmp(const bdaddr_t *a,const bdaddr_t *b) { return memcmp(a,b,6); } struct bcm4377_data; struct firmware { const unsigned char *data; int size; }; -struct hci_dev { struct bcm4377_data *data; unsigned int flags; void *req_workqueue,*workqueue; struct work_struct power_on,cmd_sync_work,cmd_work; struct delayed_work cmd_timer,ncmd_timer; int req_lock,cmd_cnt,suspend_state,wake_reason,wake_addr_type; bdaddr_t wake_addr; int *req_skb; void (*reset)(struct hci_dev*); bdaddr_t setup_addr,public_addr,bdaddr; }; +struct hci_dev { struct bcm4377_data *data; unsigned int flags; unsigned short acl_mtu,le_mtu; void *req_workqueue,*workqueue; struct work_struct power_on,cmd_sync_work,cmd_work; struct delayed_work cmd_timer,ncmd_timer; int req_lock,cmd_cnt,suspend_state,wake_reason,wake_addr_type; bdaddr_t wake_addr; int *req_skb; void (*reset)(struct hci_dev*); bdaddr_t setup_addr,public_addr,bdaddr; }; struct ring { bool enabled; }; struct pci_dev { int irq, dev; From 519feff53032b15c09b590d8c5008aa5cc7391c8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:30:42 +1100 Subject: [PATCH 1332/1514] drm/apple: stop an external firmware-27 pipe on DPMS off On firmware-27 interfaces iomfb_poweroff() returned before the clear swap and setPowerState(0) unless the pipe uses the H17G method profile, because H17P has no known safe pipe-off for its panel. Every other firmware-27 pipe that reaches it is external: a panel pipe takes the soft DPMS path in dcp_poweroff() and a retained external pipe has its own stop. Those pipes then kept scanning out the last frame after DPMS off. On a Mac mini (M2, 27.2 firmware) the HDMI monitor kept showing the last desktop frame with both CRTCs disabled, and the USB-C monitor only went dark because its synthetic HPD was dropped. Keep the early return for panel pipes only, and give an external pipe the clear swap and power-off sequence the H17G pipe already uses. The choice follows whether the DCP drives a panel (dcp_has_panel()), not the SoC or firmware version. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_template.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index 88c303630aae00..fd23281c4b6bbc 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -2902,8 +2902,13 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) #endif #if DCP_FW_H17(DCP_FW_VER) - /* H17P has no known safe pipe-off or surface-free transition. */ - if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) + /* + * H17P has no known safe pipe-off or surface-free transition for + * its panel. An external pipe stops like the H17G one: otherwise + * DPMS off leaves it scanning out the last frame. + */ + if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G && + dcp_has_panel(dcp)) return; #endif @@ -2925,7 +2930,8 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) kref_get(&cookie->refcount); #if DCP_FW_H17(DCP_FW_VER) - if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G) + if (dcp->hw.iomfb_method_profile == DCP_IOMFB_METHODS_H17G || + !dcp_has_panel(dcp)) dcp_prepare_clear_swap(dcp, swap); #else #if DCP_FW_DESKTOP_26(DCP_FW_VER) From 591e789022dfe68e95327fedaf862e32ffaf4830 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:34:00 +1100 Subject: [PATCH 1333/1514] drm/asahi: g16: add T8122 G15G on firmware 26B123 as data rows Run the M3 (T8122, G15G) GPU on the macOS 27.2 firmware (26B123) through the shared g16 backend, as #3132 does for T6030 G15S. The T8122 values come from the m3 27.2 series (linux#2781): - one firmware build row: the C0 TEXT digest measured on the J615, normalized by zeroing the GKTS and ECAP entropy values at 0x60f60 and 0x61043, which is the g16 normalization with no boot-filled ranges; - one handoff layout: TEXT 0x64000, fw-data 0xbc000 (DATA 0xb4000 plus the 0x8000 shared read-only tail), third segment at UPPER + 0x118000, handoff version 2; - the G15G InitData layout: the G16G 26B123 objects and positions with this image's version word (0x...039404b8), the T8122 register blocks, the empty-slot write modes, two extra performance words (+0x2f34, +0x6ac8) and the shared3 state word (+0x62b4), which gets the number of performance rows taken from the machine's ADT; - the GPU identity under masks (family 7, variant 2, revision 0x20, one die and one cluster), the ps_gfx offset 0x1e0, one cluster of ten core slots, no AXI2AF writes, no PMP vote. Selection is match data only. The apple,agx-t8122 row names the handoff marker aura publishes on this SoC (apple,m3-handoff-version) and the firmware-compat values it owns (<27 2 0>). The g16 driver probes the node only when the handoff describes the G15G layout and firmware-compat is 27.2, and the m3 probe steps aside in exactly that case, so the m3 14.8.3 and 26.6.2 paths are unchanged. T8132 and T6030 keep their exact identity words and handoff property. Power and thermal follow the shared backend: the DVFS rows, power sampling and limiter words come from the machine's ADT and the thermal limits from its thermal-zone trips. No power budget or FastDie temperature is carried over from the m3 series; the POWER object stays zero, as on G16G and G15S. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/driver.rs | 9 +- drivers/gpu/drm/asahi/g16/adt.rs | 39 +++++--- drivers/gpu/drm/asahi/g16/boot.rs | 6 +- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 66 +++++++++++++ drivers/gpu/drm/asahi/g16/hw.rs | 112 +++++++++++++++++++++++ drivers/gpu/drm/asahi/g16/mod.rs | 25 +++-- 6 files changed, 234 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 163764c1504ebb..c8e3f6d6722ad1 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -387,7 +387,14 @@ impl platform::Driver for AsahiPlatformDriver { } ProbeConfig::G17M5 => return AsahiPlatformDriver::probe_g17_m5(pdev), #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] - ProbeConfig::M3(crate::m3::Chip::T8122) => return AsahiPlatformDriver::probe_t8122(pdev), + ProbeConfig::M3(crate::m3::Chip::T8122) => { + // The shared G16 backend owns the handoffs its T8122 row describes (27.2). + #[cfg(CONFIG_DRM_ASAHI_G16)] + if crate::g16::claims(pdev.as_ref(), &crate::g16::hw::t8122::CONFIG) { + return Err(ENODEV); + } + return AsahiPlatformDriver::probe_t8122(pdev); + } ProbeConfig::M3(chip) => return Err(crate::m3::refuse_probe(pdev, *chip)), #[cfg(CONFIG_DRM_ASAHI_M5)] ProbeConfig::M5 => return AsahiPlatformDriver::probe_m5(pdev), diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 03eb49322ca8f9..383bfad621b244 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -122,19 +122,36 @@ fn performance_source(regions: &[Range]) -> Result<(KVVec, u64)> { /// Whether the boot loader selected this backend. Presence is enough to route probe; /// admission independently validates the property and the complete handoff. -pub(super) fn has_handoff(dev: &device::Device) -> bool { - dev.of_node().is_some_and(|node| { - !matches!( - node.get_opt_property::(c_str!("apple,g16-handoff-version")), - Ok(None) - ) - }) +pub(super) fn has_handoff(dev: &device::Device, cfg: &Config) -> bool { + dev.of_node() + .is_some_and(|node| !matches!(node.get_opt_property::(cfg.handoff_property), Ok(None))) +} + +/// Whether this backend owns `dev` under `cfg`: the handoff marker is present and, where `cfg` +/// names `firmware_compat` values, the handoff also describes one of its layouts and +/// `apple,firmware-compat` is one of those values. A compatible that another backend also +/// serves (`needs_handoff_marker`) is probed only then. +pub(crate) fn claims(dev: &device::Device, cfg: &Config) -> bool { + if !has_handoff(dev, cfg) { + return false; + } + if cfg.firmware_compat.is_empty() { + return true; + } + if layout(dev, cfg).is_none() { + return false; + } + let Some(node) = dev.of_node() else { + return false; + }; + let compat: Result> = node.get_property(c_str!("apple,firmware-compat")); + compat.is_ok_and(|compat| cfg.firmware_compat.iter().any(|c| compat.as_slice() == c)) } /// The boot loader's handoff for the loaded firmware: its version, segment VAs and flags. -fn handoff(dev: &device::Device) -> Result<(u32, KVec, KVec)> { +fn handoff(dev: &device::Device, cfg: &Config) -> 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 version: u32 = node.get_property(cfg.handoff_property)?; 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)) @@ -142,7 +159,7 @@ fn handoff(dev: &device::Device) -> Result<(u32, KVec, KVec)> { /// The firmware layout the boot loader's handoff describes, if it describes a known one. pub(crate) fn layout(dev: &device::Device, cfg: &Config) -> Option<&'static hw::FwLayout> { - let (version, vas, flags) = handoff(dev).ok()?; + let (version, vas, flags) = handoff(dev, cfg).ok()?; cfg.layouts .iter() .copied() @@ -153,7 +170,7 @@ pub(crate) fn layout(dev: &device::Device, cfg: &Config) -> Option<&'static hw:: #[inline(never)] pub(crate) fn read(dev: &device::Device, cfg: &Config) -> Result> { let node = dev.of_node().ok_or(EINVAL)?; - let (version, vas, flags) = handoff(dev)?; + let (version, vas, flags) = handoff(dev, cfg)?; let names: KVec = node.get_property(c_str!("memory-region-names"))?; let phandles: KVec = node.get_property(c_str!("memory-region"))?; let layout = cfg diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index e4d1e8562d2d45..5864452f42fa33 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -1013,11 +1013,7 @@ pub(crate) fn start( id.counts, id.cores ); - if !cfg - .hw_ids - .iter() - .any(|h| h.version == id.version && h.counts == id.counts) - { + if !cfg.hw_ids.iter().any(|h| h.matches(id.version, id.counts)) { dev_err!( d, "unsupported GPU hardware: version {:#x} counts {:#x}\n", diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 294fffcc8a5171..25dc15da5525ca 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -189,6 +189,9 @@ pub(crate) struct Layout { /// ADT (`clpc` low-peak limiter properties and `sgx` sample period), where the build has /// them. pub(crate) power_limiter: Option, + /// POWER_PERFORMANCE u32 that must lie above every performance-state index, where the build + /// has one: the number of performance rows is written there. + pub(crate) state_bound: Option, } /// POWER_PERFORMANCE offsets of the words derived from the GPU power sample period and @@ -345,6 +348,7 @@ pub(crate) const V25G83: Layout = Layout { power_policy: &[], power_sampling: None, power_limiter: None, + state_bound: None, }; /// The 26B123 InitData ABI: the same 31 objects and pointers, with @@ -437,6 +441,7 @@ pub(crate) const V26B123: Layout = Layout { filter_tc_ms: 0xad8, filter_tc_clks: 0xae0, }), + state_bound: None, }; /// G15S 26B123 keeps the protocol layouts and ADT-derived power sampling/limiter encoding while @@ -468,6 +473,58 @@ pub(crate) const G15S_26B123: Layout = Layout { ..V26B123 }; +/// G15G (T8122 C0) 26B123: the G16G 26B123 objects, register-map positions and protocol, with +/// the InitData version this image accepts (measured on the J615, linux#2781: the G16G version, +/// 0x0391, 0x0393 and 0x0395 in the differing field fault right after the root), the T8122 +/// register blocks, and the words the m3 27.2 runtime adds to the performance object. +pub(crate) const G15G_26B123: Layout = Layout { + name: "26B123 G15G", + version: 0x0c8a836f039404b8, + loaders: &G15G_LOADERS, + // 26.6.2 slots 2, 5-7, 30, 33, 34, 37, 38 and 41-43 carry write mode 2 while empty + // (`m3_mmio_26::empty_mode`); at their 26B123 positions (`slots_26b123`). + empty_loader_modes: (1 << 2) | (7 << 5) | (1 << 35) | (3 << 38) | (3 << 42) | (7 << 46), + // Two words this InitData family adds, 1 each as the G14 27.2 path sets them, next to the + // four power-up words (linux#2781 `relocate_26b123`). + power_policy: &[ + (0x9c, 1), + (0xa0, 1), + (0xa4, 1), + (0xa8, 1), + (0x2f34, 1), + (0x6ac8, 1), + ], + // The shared3 block's state word (+0x62ac + 8): with the block all zero the G15G firmware + // never takes the first device-control records. + state_bound: Some(0x62b4), + ..V26B123 +}; + +/// The T8122 register blocks behind each logical 26.6.2 slot (`m3_mmio_26::area` with the +/// T8122 blocks of `m3_adt_config::T8122_IO_MAPPINGS`). +const G15G_LOADERS: [Loader; LOADER_COUNT] = { + const SGX: u64 = 0x290000000; + let mut out = [EMPTY; LOADER_COUNT]; + out[0] = mmio(0x2d1014000, 0x4000, 0, 2); + // The memory cache, two banks, as on T8132. + out[3] = LOADERS[3]; + out[9] = mmio(0x2d03d0000, 0x1000, 0, 2); + out[10] = mmio(0x2d03c0000, 0x2000, 0, 0); + out[12] = mmio(0x31145c000, 0x4000, 0, 2); + out[14] = mmio(0x2d0280000, 0x8000, 0, 0); + out[17] = mmio(SGX, 0x20000, 0, 2); + out[26] = mmio(SGX + 0xd04000, 0x8000, 0xd04000, 2); + out[27] = mmio(SGX + 0xd0d000, 0x1000, 0xd0d000, 2); + out[28] = mmio(SGX + 0xd50000, 0x8000, 0xd50000, 2); + out[29] = mmio(SGX + 0xd10000, 0x4000, 0xd10000, 2); + out[31] = mmio(SGX + 0xd40000, 0x4000, 0xd40000, 2); + out[32] = mmio(SGX + 0xd60000, 0x8000, 0xd60000, 2); + out[35] = mmio(SGX + 0xe00000, 0x4000, 0xe00000, 2); + out[39] = mmio(SGX + 0xe08000, 0x8000, 0, 2); + out[40] = mmio(SGX + 0xe1c000, 0x4000, 0xe1c000, 2); + out +}; + const fn slots_g15s() -> [Option; LOADER_COUNT] { let mut slots = slots_26b123(); // The final two named registers use G15S-specific slots. Slot 41 (G16G's @@ -811,6 +868,12 @@ const fn retention_fits(layout: &Layout) -> bool { } } const _: () = assert!(layout_fits(&V25G83) && layout_fits(&V26B123) && layout_fits(&G15S_26B123)); +const _: () = assert!(layout_fits(&G15G_26B123)); +const _: () = assert!(match G15G_26B123.state_bound { + Some(at) => + power_slot_clear(&G15G_26B123, at) && power_policy_overlaps(G15G_26B123.power_policy, at), + None => false, +}); /// One logical loader record, including its page offset and exact PTE class. #[derive(Clone, Copy, Debug)] @@ -1564,6 +1627,9 @@ pub(crate) fn encode_for( for &(at, value) in layout.power_policy { put32(p, at, value)?; } + if let Some(at) = layout.state_bound { + put32(p, at, input.performance.count as u32)?; + } if let (Some(sampling), Some((period, samples))) = (layout.power_sampling, sampling_values) { for &at in sampling.period { put32(p, at, period)?; diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 14567a7501016e..e4580cc0d27a13 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -16,6 +16,25 @@ pub(crate) struct HwId { pub(crate) version: u32, /// SGX layout word (`sgx + 0xd04010`). pub(crate) counts: u32, + /// Bits of `version` and `counts` that must match; the others are not qualified. + pub(crate) version_mask: u32, + pub(crate) counts_mask: u32, +} + +impl HwId { + /// Mask both words exactly; rows give their values with `..HwId::EXACT`. + pub(crate) const EXACT: HwId = HwId { + version: 0, + counts: 0, + version_mask: u32::MAX, + counts_mask: u32::MAX, + }; + + /// Whether the identification registers read `version` and `counts`. + pub(crate) const fn matches(&self, version: u32, counts: u32) -> bool { + (version ^ self.version) & self.version_mask == 0 + && (counts ^ self.counts) & self.counts_mask == 0 + } } pub(crate) use crate::fwid::FirmwareBuild; @@ -50,6 +69,11 @@ pub(crate) struct Config { pub(crate) firmware: &'static [FirmwareBuild], /// Whether this compatible also has a legacy driver. pub(crate) needs_handoff_marker: bool, + /// GPU node property holding the boot loader's handoff version (the handoff marker). + pub(crate) handoff_property: &'static core::ffi::CStr, + /// `apple,firmware-compat` values this backend owns on a compatible that another backend + /// also serves; empty when the handoff layout alone selects the backend. + pub(crate) firmware_compat: &'static [[u32; 3]], /// T8132 retains the PMP bridge even on firmware that does not send an AGX vote. pub(crate) prepare_pmp: bool, /// PMGR register offset of the GFX domain. @@ -93,6 +117,7 @@ pub(crate) mod t8132 { hw_ids: &[HwId { version: 0x0a021100, counts: 0x0011010a, + ..HwId::EXACT }], adt_compatible: b"gpu,t8132", display_compatible: b"apple,t8132-display-subsystem\0", @@ -187,6 +212,8 @@ pub(crate) mod t8132 { }, ], needs_handoff_marker: false, + handoff_property: super::G16_HANDOFF_PROPERTY, + firmware_compat: &[], prepare_pmp: true, power_offset: 0x250, fault_banks: 8, @@ -323,6 +350,7 @@ pub(crate) mod t6030 { hw_ids: &[HwId { version: 0x07031100, counts: 0x00110209, + ..HwId::EXACT }], adt_compatible: b"gpu,t6030", display_compatible: b"apple,t6030-display-subsystem\0", @@ -340,6 +368,8 @@ pub(crate) mod t6030 { ], }], needs_handoff_marker: true, + handoff_property: super::G16_HANDOFF_PROPERTY, + firmware_compat: &[], prepare_pmp: false, power_offset: 0x110, fault_banks: 2, @@ -426,6 +456,88 @@ pub(crate) mod t6030 { ]; } +/// The handoff marker aura publishes for the T8132 and T6030 GPUs. +pub(crate) const G16_HANDOFF_PROPERTY: &core::ffi::CStr = c"apple,g16-handoff-version"; + +/// T8122 (G15G), qualified with the C0 image the macOS 27.2 boot chain loads (26B123). +/// +/// The same compatible is served by the `m3` runtime for the 14.8.3 and 26.6.2 firmware, so this +/// row owns a device only when its `firmware-compat` is 27.2 and the handoff describes [`LAYOUT`] +/// ([`Config::firmware_compat`], `adt::claims`). Aura names the handoff version +/// `apple,m3-handoff-version` on this SoC (aura#448/#455). +pub(crate) mod t8122 { + use super::super::fw::initdata; + use super::{Config, FirmwareBuild, FwLayout, HwId, FW_26B123, UPPER}; + + pub(crate) const CONFIG: Config = Config { + chip_id: 0x8122, + gpu_generation: 15, + gpu_hal_generation: kernel::uapi::drm_asahi_gpu_hal_generation_DRM_ASAHI_GPU_HAL_LEGACY, + gpu_variant: crate::hw::GpuVariant::G, + // C0 (`crate::hw::GpuRevision::C0`), as the m3 runtime reports it. + gpu_revision: 0x20, + uat_ias: 42, + uat_oas: 42, + // One cluster of ten core slots; eight or ten are enabled. + num_clusters: 1, + num_cores_per_cluster: 10, + // Family 7, variant 2 (G15G), revision 0x20; one die and one cluster. The other bits + // of the two words are not qualified (`m3_soc::T8122.id`). + hw_ids: &[HwId { + version: 0x07022000, + counts: 0x00010100, + version_mask: 0xffffff00, + counts_mask: 0x000fff00, + }], + adt_compatible: b"gpu,t8122", + display_compatible: b"apple,t8122-display-subsystem\0", + layouts: &[&LAYOUT], + firmware: &[FirmwareBuild { + // GKTS/ECAP-normalized loaded TEXT, measured on the J615 over three boots + // (linux#2781, `m3_firmware::T8122_IMAGES_27`): only the two entropy values are + // zeroed, which is this backend's normalization with no boot-filled ranges. + name: "Apple GFX 26B123 G15G (C0, entropy zeroed)", + text_size: LAYOUT.text_size, + data_size: LAYOUT.data_size, + entropy: &[[0x60f60, 0x61043]], + boot_filled: &[], + text_sha256: [ + 0x74, 0x06, 0xa5, 0x68, 0x34, 0x28, 0x37, 0xa7, 0x9f, 0x22, 0xc0, 0x3f, 0x7d, 0x45, + 0x7f, 0x9f, 0x9d, 0x3e, 0x08, 0x8c, 0x4b, 0x78, 0xd7, 0x83, 0xe2, 0xdc, 0xad, 0x76, + 0x71, 0x6f, 0x16, 0xf5, + ], + }], + needs_handoff_marker: true, + handoff_property: c"apple,m3-handoff-version", + firmware_compat: &[[27, 2, 0]], + // The 27.2 start sends no PMP vote. + prepare_pmp: false, + // `ps_gfx` in t8122-pmgr.dtsi. + power_offset: 0x1e0, + fault_banks: 1, + // The m3 27.2 start on the J615 writes no GFXCAXI2AF enables (no slot 22 either). + axi2af: false, + host_block_zero_order: &super::start_27_2::HOST_BLOCK_ZERO_ORDER, + host_block_ready: true, + deep_sleep: false, + supports_render_scs: false, + cross_engine_hold: true, + }; + + /// 26B123 G15G: __TEXT 0x64000 as on G16G, __DATA 0xb4000 and the 0x8000 __DATA_SHARED_RO + /// tail, so the third segment is at UPPER + 0x118000 (aura's version-2 handoff). + pub(crate) const LAYOUT: FwLayout = FwLayout { + name: "26B123 G15G", + segment_vas: &[UPPER, UPPER + 0x64000, UPPER + 0x118000], + data_size: 0xbc000, + initdata: &initdata::G15G_26B123, + // Not known for this firmware; the host keeps reading GPU registers while it runs, as + // the m3 runtime does. + powered: None, + ..FW_26B123 + }; +} + /// Which part of the loaded image a firmware page-table leaf maps. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum Segment { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 466db56ef84cf7..184a3faee6927d 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 -//! Classic GPU support for T8132 G16G (25G83 and 26B123) and T6030 G15S (26B123). +//! Classic GPU support for T8132 G16G (25G83 and 26B123), T6030 G15S (26B123) and T8122 G15G +//! (26B123). //! //! Classic firmware uses one ring per engine (TA, FS, compute) and expresses ordering through //! in-ring barrier records that wait on another queue's stamp, unlike the G17 kick-ring/QID @@ -14,9 +15,10 @@ //! //! # Plugging into the shared driver //! -//! - [`Driver`] matches `apple,agx-t8132` and `apple,agx-t6030`. T6030 selects this backend -//! through the boot loader's handoff marker. Probe links a handed-over native display and, on -//! T8132, the PMP supplier before booting firmware. It calls +//! - [`Driver`] matches `apple,agx-t8132`, `apple,agx-t6030` and `apple,agx-t8122`. T6030 and +//! T8122 select this backend through the boot loader's handoff (marker, layout and, on +//! T8122, `apple,firmware-compat` 27.2; see [`adt::claims`]). Probe links a handed-over +//! native display and, on T8132, the PMP supplier before booting firmware. It calls //! [`crate::driver::AsahiPlatformDriver::probe_g16`]. //! - [`Gpu`] implements [`crate::gpu::Gpu`]: GET_PARAMS identity, VM creation (`new_vm`), //! queues (`new_queue`, see [`queue`]) and timestamp buffers. @@ -101,7 +103,7 @@ pub(crate) const DRIVER_NAME: &CStr = c_str!("aurora-g16"); pub(crate) use hw::Config; /// OF match table of the G16 platform driver. -const OF_TABLE: kernel::device_id::IdArray = +const OF_TABLE: kernel::device_id::IdArray = kernel::device_id::IdArray::new([ ( of::DeviceId::new(c_str!("apple,agx-t8132")), @@ -111,6 +113,10 @@ const OF_TABLE: kernel::device_id::IdArray = of::DeviceId::new(c_str!("apple,agx-t6030")), &&hw::t6030::CONFIG, ), + ( + of::DeviceId::new(c_str!("apple,agx-t8122")), + &&hw::t8122::CONFIG, + ), ]); // Probe admission waits for the PMP supplier and the native display before @@ -121,9 +127,16 @@ kernel::of_device_table!( [ of::DeviceId::new(c_str!("apple,agx-t8132")), of::DeviceId::new(c_str!("apple,agx-t6030")), + of::DeviceId::new(c_str!("apple,agx-t8122")), ] ); +/// Whether this backend owns `dev` under the configuration of its compatible, so that another +/// backend serving the same compatible steps aside. +pub(crate) fn claims(dev: &device::Device, cfg: &Config) -> bool { + adt::claims(dev, cfg) +} + /// The G16 platform driver: the shared [`AsahiPlatformDriver`] probed through /// [`AsahiPlatformDriver::probe_g16`]. /// @@ -151,7 +164,7 @@ impl platform::Driver for Driver { info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let cfg = *info.ok_or(ENODEV)?; - if cfg.needs_handoff_marker && !adt::has_handoff(pdev.as_ref()) { + if cfg.needs_handoff_marker && !adt::claims(pdev.as_ref(), cfg) { return Err(ENODEV); } dev_info!(pdev.as_ref(), "G16: probing\n"); From df36284f753bcf69c83ca964d0ba84ae45438c79 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 08:42:17 -0500 Subject: [PATCH 1334/1514] drm/asahi: g17: collect given-up compute channels without allocating under the lock rollback_unpublished_compute() and drain_compute_siblings() take compute queues out of the registry under the device mutex. The empty entry keeps the QID until finish_uninstalled_compute() drops the queue off-lock and cancels its reservation. Both collected the queues, and the rollback its displaced bindings, into empty KVecs while holding the mutex. A failed push dropped the queue or binding under the mutex and skipped the cancellation. The empty entry then stayed for good, and reserve_compute_channel() refused its owner with EINVAL from then on. The drain also lost the queues it had already taken when a later sibling was still busy (EAGAIN), and the rollback lost them when a later channel's rollback failed. An owner holds at most COMPUTE_CHANNELS_MAX channels, so collect into fixed per-channel arrays that the caller owns: nothing is allocated under the mutex, a channel is refused before it changes if it would have no place, and after a failure the caller still has everything taken before it. The caller drops the displaced bindings and finishes every taken queue after releasing the mutex, and goes on past a failed cancellation. The rollback loop moves into the registry beside the drain, so no early return can skip that. Also remove Registry::compute_mut(), which has no caller left in this series and was the driver's only g17 dead-code warning. The new g17-compute-retired-tests host test runs the production rollback, drain, finish and reservation code for an owner with all three channels, including a failing rollback, a busy sibling and a failing cancellation. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/runtime.rs | 90 +++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 44 +- .../g17-compute-growth-deadline-tests.py | 10 +- tools/asahi/g17-compute-retired-tests.py | 471 ++++++++++++++++++ tools/asahi/g17-m5-sibling-compute-tests.py | 15 +- tools/asahi/run-host-tests.py | 4 + 6 files changed, 576 insertions(+), 58 deletions(-) create mode 100755 tools/asahi/g17-compute-retired-tests.py diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 3c85e7d73750f2..d88964fbcd92bd 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -72,6 +72,16 @@ struct ComputeEntry { queue: ComputeSlot, } +/// A compute queue taken out of the registry under the device mutex. Its empty entry keeps the +/// reservation's QID until [`Backend::finish_uninstalled_compute`] drops the queue (and its +/// aliases) after that mutex is released and then cancels the reservation. +type Uninstalled = (ComputeReservation, KBox); + +/// One place per compute channel of an owner. An owner holds at most `COMPUTE_CHANNELS_MAX` +/// channels, so what its channels give up under the device mutex is kept here without +/// allocating there, and is dropped or finished only after that mutex is released. +type PerChannel = [Option; super::pairs::COMPUTE_CHANNELS_MAX]; + /// A physical compute queue behind its own lock. Publication into a bound queue takes only /// this lock; device-mutex holders take it to observe or change the queue (device mutex -> /// cell). A logical queue may keep the cell after the registry gave the queue up: the cell is @@ -343,10 +353,6 @@ impl Registry { .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) } - pub(super) fn compute_mut(&mut self, owner: u64) -> Option> { - self.compute(owner) - } - pub(super) fn compute_for_packet( &self, owner: u64, @@ -1144,13 +1150,15 @@ impl Registry { } /// Releases idle sibling channels of `owner` before primary pool growth. Returns `Err(EAGAIN)` - /// while any sibling still has active, replaying or configuring work, and returns any - /// unpublished sibling queues for off-lock alias drop and QID cancellation. + /// while any sibling still has active, replaying or configuring work. Each unpublished + /// sibling queue goes to `retired`, which starts empty, for off-lock alias drop and QID + /// cancellation; on failure it still holds every queue taken before it. fn drain_compute_siblings( &mut self, owner: u64, - ) -> Result)>> { - let mut retired = KVec::new(); + retired: &mut PerChannel, + ) -> Result { + let mut channel = 0; for slot in 0..self.compute.len() { let is_sibling = self.compute[slot] .as_ref() @@ -1168,15 +1176,58 @@ impl Registry { if busy { return Err(EAGAIN); } + // Refuse before releasing a channel whose queue would have no place in `retired`. + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; let entry = self.compute[slot].as_mut().ok_or(EIO)?; let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; if unpublished { - if let Some(queue) = entry.queue.take() { - retired.push((entry.reservation, queue), GFP_KERNEL)?; + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); + } + } + Ok(()) + } + + /// Rolls back `owner`'s unpublished bindings to `context` on every channel, siblings before + /// the primary for deterministic teardown. Each displaced binding goes to `bindings` and each + /// cancelled queue to `retired`, both starting empty, for the caller to drop (and finish) + /// after releasing the device mutex; on failure they still hold everything taken before it. + fn rollback_unpublished_compute( + &mut self, + owner: u64, + context: &Arc, + retired: &mut PerChannel, + bindings: &mut PerChannel, + ) -> Result { + let mut channel = 0; + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + // Refuse before rolling back a channel whose binding or queue would have no place. + let binding = bindings.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let (cancel, replaced) = entry + .queue + .as_deref_mut() + .ok_or(EIO)? + .rollback_unpublished(owner, context)?; + *binding = replaced; + if cancel { + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); } } } - Ok(retired) + Ok(()) } pub(super) fn release_compute(&mut self, owner: u64) -> Result { @@ -1663,6 +1714,15 @@ impl Backend { Ok(()) } + /// Finishes every queue in `retired` as [`Self::finish_uninstalled_compute`] finishes one, + /// going on past a failure so no other reservation stays behind; returns the first failure. + fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result { + retired.iter_mut().fold(Ok(()), |result, item| { + let finished = self.finish_uninstalled_compute(item.take()); + result.and(finished) + }) + } + fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; { @@ -1694,7 +1754,7 @@ impl Backend { // Growth waits for this queue's retirement and for firmware to consume the pool // release; both are progress the event worker reports. let observed = self.shared.progress.observe(); - let mut retired_siblings = KVec::new(); + let mut retired_siblings: PerChannel = Default::default(); let result = (|| { let mut state = self.shared.state.lock(); admission.check()?; @@ -1704,7 +1764,7 @@ impl Backend { firmware.scan_compute(None, &mut deferred)?; // Release sibling channels before growing the primary channel so undersized // sibling pools are detached and later re-acquired at the grown capacity. - retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?; + firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?; let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { @@ -1719,9 +1779,7 @@ impl Backend { } queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) })(); - for item in retired_siblings { - self.finish_uninstalled_compute(Some(item))?; - } + self.finish_retired_compute(&mut retired_siblings)?; deferred.finish(); match result { Ok(old) => { drop(old); return Ok(()); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index ff0f4e897123d4..b3f54f9f45060a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -2,10 +2,11 @@ //! Scheduler callbacks and the off-lock fence boundary of a logical queue. -use super::{Backend, DeferredBatch}; +use super::{Backend, DeferredBatch, PerChannel, Uninstalled}; use crate::g17::{ completion::Deferred, job::{self, Engine, Packet}, + queue::compute::Binding, }; use core::sync::atomic::Ordering; use kernel::{dma_fence::{Fence, RawDmaFence}, drm::sched, prelude::*, sync::Arc}; @@ -35,47 +36,20 @@ impl Backend { // fresh epoch through alias destruction so recovery can join this work. loop { let lease = self.shared.preparations.enter(false)?; - let mut retired = KVec::new(); - let mut bindings = KVec::new(); + let mut retired: PerChannel = Default::default(); + let mut bindings: PerChannel = Default::default(); let mut state = self.shared.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; if !lease.is_current() { drop(state); drop(lease); continue; } - // Roll back sibling channels before the primary channel for deterministic teardown. - for primary_pass in [false, true] { - for index in 0..firmware.queues.compute.len() { - let matches = firmware.queues.compute[index] - .as_ref() - .and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| { - queue.owner() == Some(self.owner) && queue.is_primary() == primary_pass - }); - if !matches { - continue; - } - let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; - let (cancel, replaced) = entry - .queue - .as_deref_mut() - .ok_or(EIO)? - .rollback_unpublished(self.owner, &self.context)?; - if let Some(replaced) = replaced { - let _ = bindings.push(replaced, GFP_KERNEL); - } - if cancel { - if let Some(queue) = entry.queue.take() { - let _ = retired.push((entry.reservation, queue), GFP_KERNEL); - } - } - } - } + let result = firmware.queues.rollback_unpublished_compute( + self.owner, &self.context, &mut retired, &mut bindings); drop(state); + // Off-lock, and after a failure too: no cancelled queue's reservation stays behind. drop(bindings); - for item in retired { - self.finish_uninstalled_compute(Some(item))?; - } + let finished = self.finish_retired_compute(&mut retired); self.shared.channels.notify(); self.shared.queue_events(); - return Ok(()); + return result.and(finished); } } diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index d79d784b7578fe..7ed4ca5c95277c 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -32,7 +32,11 @@ def fixture(): admission = ('#[derive(Clone,Copy,Debug,PartialEq)]\n' + item(prep, 'pub(super) enum AdmissionWait').replace('pub(super) ', '') + '\n' + next(line for line in prep.splitlines() if 'const ADMISSION_WAITS:' in line).replace('pub(super) ', '') + '\n' + admission) - methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(']) + methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(', + ' fn finish_retired_compute(']) + # The per-channel places growth hands drained siblings over in. + aliases = '\n'.join(next(line for line in runtime.splitlines() if line.startswith(prefix)) + for prefix in ('type Uninstalled =', 'type PerChannel =')).replace('super::pairs::', '') methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::freelist::Pages', 'Pages') .replace('super::freelist::ComputeCapacity', 'ComputeCapacity')) return r''' @@ -75,6 +79,8 @@ def fixture(): impl Drop for Pages{fn drop(&mut self){PAGES.store(false,Ordering::SeqCst);}} impl Drop for Alias{fn drop(&mut self){ALIAS.store(false,Ordering::SeqCst);}} mod compute{pub(crate) use crate::Queue;} +const COMPUTE_CHANNELS_MAX:usize=3; +''' + aliases + r''' struct Queue{fresh:bool} impl Queue{ fn owner(&self)->Option{Some(1)} @@ -92,7 +98,7 @@ def fixture(): fn compute(&self,_:u64)->Option<&Queue>{self.compute[0].as_ref().unwrap().queue.as_deref()} fn compute_mut(&mut self,_:u64)->Option<&mut Queue>{self.compute[0].as_mut().unwrap().queue.as_deref_mut()} fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} - fn drain_compute_siblings(&mut self,_:u64)->Result)>>{Ok(Vec::new())} + fn drain_compute_siblings(&mut self,_:u64,_:&mut PerChannel)->Result{Ok(())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} diff --git a/tools/asahi/g17-compute-retired-tests.py b/tools/asahi/g17-compute-retired-tests.py new file mode 100755 index 00000000000000..900fdee4c47b4b --- /dev/null +++ b/tools/asahi/g17-compute-retired-tests.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: compute channels given up under the device mutex never leak a reservation. + +A logical compute queue holds up to `COMPUTE_CHANNELS_MAX` channels. When an +unpublished compute packet fails, `Backend::rollback_unpublished_compute()` +rolls back every channel of the owner, and before primary pool growth +`Registry::drain_compute_siblings()` releases every idle sibling. Both take +queues out of the registry under the device mutex. Each taken queue keeps an +empty registry entry, and so its QID, until it is dropped off-lock and its +reservation is cancelled (`finish_uninstalled_compute()`). An entry left empty +for good locks its owner out: `reserve_compute_channel()` refuses that owner +with `EINVAL`. + +This test compiles, against host stubs, the production code from +drivers/gpu/drm/asahi/g17/runtime.rs (`Registry::drain_compute_siblings()`, +`Registry::rollback_unpublished_compute()`, `Registry::reserve_compute_channel()`, +`Registry::reserved()`, `Registry::cancel_compute()`, +`Backend::finish_uninstalled_compute()`, `Backend::finish_retired_compute()`) +and from runtime/backend.rs (`Backend::rollback_unpublished_compute()`). It +checks, for an owner with all `COMPUTE_CHANNELS_MAX` channels, that: + +- nothing a channel gives up (queue or displaced binding) is dropped while the + device mutex is held; +- every cancelled or drained queue has its reservation cancelled, so the owner + can reserve channels again; +- this also holds when a later channel fails its rollback or is still busy in + the drain (`EAGAIN`), and when finishing one queue fails; +- an owner with more channels than places is refused before any extra channel + changes. + +Each mutation drops one part of that and must fail an assertion. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def line(source, prefix): + found = [text for text in source.splitlines() if text.startswith(prefix)] + assert len(found) == 1, prefix + return found[0] + + +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def build_harness(mutation=None): + runtime = (G17 / 'runtime.rs').read_text() + backend = (G17 / 'runtime/backend.rs').read_text() + max_line = line((G17 / 'pairs.rs').read_text(), 'pub(crate) const COMPUTE_CHANNELS_MAX: usize') + + aliases = '\n'.join([ + line(runtime, 'type Uninstalled ='), + line(runtime, 'type PerChannel ='), + ]).replace('super::pairs::', '') + drain = item(runtime, ' fn drain_compute_siblings(') + rollback = item(runtime, ' fn rollback_unpublished_compute(\n') + reserve = item(runtime, ' pub(super) fn reserve_compute_channel(') + reserved = item(runtime, ' fn reserved(&mut self, reservation: ComputeReservation)') + cancel = item(runtime, ' pub(super) fn cancel_compute(') + finish_one = item(runtime, ' fn finish_uninstalled_compute(') + finish_all = item(runtime, ' fn finish_retired_compute(') + backend_rollback = item(backend, ' fn rollback_unpublished_compute(&self)') + + if mutation == 'queue-under-lock': + # A cancelled queue is dropped where it is taken, as when a push into an empty KVec failed. + rollback = replace_once(rollback, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'binding-under-lock': + rollback = replace_once(rollback, '*binding = replaced;', 'drop(replaced);') + elif mutation == 'drain-under-lock': + drain = replace_once(drain, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'drain-local-on-eagain': + # The old shape: collect locally and hand the queues over only on success. + drain = replace_once(drain, 'retired: &mut PerChannel,', 'outer: &mut PerChannel,') + drain = replace_once(drain, ' let mut channel = 0;\n', + ' let mut local: PerChannel = Default::default();\n' + ' let retired = &mut local;\n' + ' let mut channel = 0;\n') + drain = drain[:drain.rindex('Ok(())')] + 'core::mem::swap(outer, retired);\n Ok(())\n }' + elif mutation == 'finish-stops-at-error': + finish_all = ( + ' fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result {\n' + ' for item in retired.iter_mut() {\n' + ' self.finish_uninstalled_compute(item.take())?;\n' + ' }\n' + ' Ok(())\n' + ' }') + elif mutation == 'early-return-skips-finish': + backend_rollback = replace_once(backend_rollback, 'let result = firmware.queues', 'let result: Result = Ok(()); firmware.queues') + backend_rollback = replace_once(backend_rollback, '&mut retired, &mut bindings);', '&mut retired, &mut bindings)?;') + elif mutation == 'overwrite-full': + rollback = replace_once(rollback, 'bindings.get_mut(channel)', 'bindings.get_mut(channel % COMPUTE_CHANNELS_MAX)') + rollback = replace_once(rollback, 'retired.get_mut(channel).filter(|place| place.is_none())', + 'retired.get_mut(channel % COMPUTE_CHANNELS_MAX)') + + reserve = reserve.replace('crate::g17::capacity::', 'capacity::') + reserve, cancel = (text.replace('pub(super) ', '') for text in (reserve, cancel)) + + return r''' +#![allow(dead_code)] +use std::cell::{Cell, RefCell, RefMut}; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +type Error = i32; +type Result = core::result::Result; +type KBox = Box; +type KVec = Vec; +const EIO: Error = -5; +const ENODEV: Error = -19; +const EINVAL: Error = -22; +const EAGAIN: Error = -11; +const ENOSPC: Error = -28; +const FIRST_COMPUTE_QID: u8 = 8; +''' + max_line.replace('pub(crate) ', '') + r''' + +thread_local! { + static LOCKED: Cell = const { Cell::new(false) }; + static LOG: RefCell> = const { RefCell::new(Vec::new()) }; +} +fn locked() -> bool { LOCKED.with(Cell::get) } +fn log(text: String) { LOG.with(|log| log.borrow_mut().push(text)); } +fn take_log() -> Vec { LOG.with(|log| core::mem::take(&mut *log.borrow_mut())) } + +mod capacity { + pub(super) enum Site { ComputeSlots } + pub(super) fn refused(_: Site) -> i32 { super::ENOSPC } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +struct Id { qid: u8, generation: u32 } +impl Id { fn qid(&self) -> u8 { self.qid } } +#[derive(Clone, Copy)] +enum DataMaster { Compute } + +struct Context; + +/// A displaced binding: its aliases must be torn down off the device mutex. +struct Binding(u8); +impl Drop for Binding { + fn drop(&mut self) { + assert!(!locked(), "binding of qid {} dropped under the device mutex", self.0); + log(format!("binding {}", self.0)); + } +} +mod compute { pub(super) use super::{Binding, Queue}; } + +#[derive(Clone, Copy, PartialEq)] +enum Rollback { Cancel, Displace, Keep, Fail } + +struct Queue { + qid: u8, + owner: Option, + primary: bool, + active: u32, + rollback: Rollback, + unpublished: bool, +} +impl Queue { + fn owner(&self) -> Option { self.owner } + fn is_primary(&self) -> bool { self.primary } + fn active_len(&self) -> u32 { self.active } + fn has_replays(&self) -> bool { false } + fn configuring(&self) -> bool { false } + fn release_owner(&mut self) -> Result { + self.owner = None; + Ok(self.unpublished) + } + fn rollback_unpublished(&mut self, owner: u64, _: &Arc) -> Result<(bool, Option)> { + assert_eq!(self.owner, Some(owner)); + log(format!("rollback {}", self.qid)); + match self.rollback { + Rollback::Cancel => { self.owner = None; Ok((true, None)) } + Rollback::Displace => Ok((false, Some(Binding(self.qid)))), + Rollback::Keep => Ok((false, None)), + Rollback::Fail => Err(EIO), + } + } +} +impl Drop for Queue { + fn drop(&mut self) { + assert!(!locked(), "queue {} dropped under the device mutex", self.qid); + log(format!("drop {}", self.qid)); + } +} + +/// Stands in for the cell-locked slot: a guard for the installed queue, or none. +struct ComputeSlot(RefCell>>); +impl ComputeSlot { + fn new() -> Result { Ok(Self(RefCell::new(None))) } + fn with(queue: Queue) -> Self { Self(RefCell::new(Some(Box::new(queue)))) } + fn as_deref(&self) -> Option> { + RefMut::filter_map(self.0.borrow_mut(), |queue| queue.as_deref_mut()).ok() + } + fn as_deref_mut(&mut self) -> Option> { self.as_deref() } + fn is_some(&self) -> bool { self.0.borrow().is_some() } + fn is_none(&self) -> bool { !self.is_some() } + fn take(&mut self) -> Option> { self.0.borrow_mut().take() } +} + +#[derive(Clone, Copy)] +struct ComputeReservation { slot: usize, id: Id, owner: u64 } +struct ComputeEntry { reservation: ComputeReservation, queue: ComputeSlot } +''' + aliases + r''' + +struct Identities(u64); +impl Identities { + fn reserve(&mut self, count: u64) -> Result> { + let start = self.0; + self.0 += count; + Ok(start..self.0) + } +} +struct Qids { next: u8, cancelled: Vec, refuse: Option } +impl Qids { + fn reserve_for(&mut self, _: u64, _: DataMaster, _: Option, _: usize) -> Result { + self.next += 1; + Ok(Id { qid: self.next, generation: 1 }) + } + fn render_pair_fits(&self) -> bool { true } + fn render_pair_capacity(&self) -> usize { 4 } + fn cancel_unpublished(&mut self, id: Id) -> Result { + if self.refuse == Some(id.qid) { return Err(EIO); } + self.cancelled.push(id.qid); + Ok(()) + } +} +struct Admission; +impl Admission { + fn reserve_compute_with_budget( + &self, _: u64, _: u64, reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, + ) -> Result { + reserve(0).map(|(id, _, _)| id) + } +} + +struct Registry { + compute: KVec>, + identities: Identities, + qids: Qids, + admission: Admission, +} +impl Registry { + fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { Ok((0, 0)) } + fn compute_admission_error(&self, error: Error) -> Error { + if error == ENOSPC { EAGAIN } else { error } + } + fn note_build_room(&mut self) {} +''' + '\n'.join([drain, rollback, reserve, reserved, cancel]) + r''' +} + +struct Firmware { queues: Registry } +struct Guard<'a>(RefMut<'a, Option>>); +impl Deref for Guard<'_> { + type Target = Option>; + fn deref(&self) -> &Self::Target { &self.0 } +} +impl DerefMut for Guard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } +} +impl Drop for Guard<'_> { + fn drop(&mut self) { LOCKED.with(|locked| locked.set(false)); } +} +struct State(RefCell>>); +impl State { + fn lock(&self) -> Guard<'_> { + assert!(!locked(), "device mutex taken twice"); + LOCKED.with(|locked| locked.set(true)); + Guard(self.0.borrow_mut()) + } +} +struct Lease; +impl Lease { fn is_current(&self) -> bool { true } } +struct Preparations; +impl Preparations { fn enter(&self, _: bool) -> Result { Ok(Lease) } } +struct Channels(Cell); +impl Channels { fn notify(&self) { self.0.set(self.0.get() + 1); } } +struct Shared { preparations: Preparations, state: State, channels: Channels } +impl Shared { fn queue_events(&self) {} } +struct Backend { owner: u64, context: Arc, shared: Shared } +impl Backend { +''' + '\n'.join([finish_one, finish_all, backend_rollback]) + r''' +} + +const OWNER: u64 = 1; + +/// The owner's channels in slots 0..: primary first, then siblings; slot `free` stays empty. +fn backend(channels: &[(Rollback, u32, bool)]) -> Backend { + let mut compute: KVec> = Vec::new(); + for (slot, &(rollback, active, unpublished)) in channels.iter().enumerate() { + let qid = 10 + slot as u8; + compute.push(Some(ComputeEntry { + reservation: ComputeReservation { slot, id: Id { qid, generation: 1 }, owner: OWNER }, + queue: ComputeSlot::with(Queue { + qid, owner: Some(OWNER), primary: slot == 0, active, rollback, unpublished, + }), + })); + } + for _ in 0..4 { + compute.push(None); + } + let queues = Registry { + compute, + identities: Identities(100), + qids: Qids { next: 40, cancelled: Vec::new(), refuse: None }, + admission: Admission, + }; + Backend { + owner: OWNER, + context: Arc::new(Context), + shared: Shared { + preparations: Preparations, + state: State(RefCell::new(Some(Box::new(Firmware { queues })))), + channels: Channels(Cell::new(0)), + }, + } +} + +fn installed(b: &Backend) -> Vec { + let state = b.shared.state.0.borrow(); + let queues = &state.as_ref().unwrap().queues; + queues.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref().map(|queue| queue.qid)).collect() +} + +fn empty_entries(b: &Backend) -> usize { + let state = b.shared.state.0.borrow(); + state.as_ref().unwrap().queues.compute.iter().flatten().filter(|entry| entry.queue.is_none()).count() +} + +fn cancelled(b: &Backend) -> Vec { + b.shared.state.0.borrow().as_ref().unwrap().queues.qids.cancelled.clone() +} + +/// The owner is not locked out: the production reservation grants it a channel again. +fn reserves_again(b: &Backend) { + let mut state = b.shared.state.0.borrow_mut(); + let queues = &mut state.as_mut().unwrap().queues; + let reservation = queues.reserve_compute_channel(OWNER, COMPUTE_CHANNELS_MAX as u8); + assert!(reservation.is_ok(), "owner locked out of reserve_compute_channel: {:?}", reservation.err()); + queues.cancel_compute(reservation.unwrap()).unwrap(); +} + +fn drain(b: &Backend) -> Result { + let mut retired: PerChannel = Default::default(); + let result = { + let mut state = b.shared.state.lock(); + let firmware = state.as_deref_mut().unwrap(); + firmware.queues.drain_compute_siblings(OWNER, &mut retired) + }; + let finished = b.finish_retired_compute(&mut retired); + assert!(retired.iter().all(Option::is_none), "drained queue left unfinished"); + result.and(finished) +} + +fn main() { + use Rollback::*; + assert_eq!(COMPUTE_CHANNELS_MAX, 3, "this test models three channels per owner"); + + // 1. Rollback cancels all three channels: siblings first, every reservation cancelled. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [11, 12, 10]); + assert!(installed(&b).is_empty() && empty_entries(&b) == 0, "rolled-back channel left in the registry"); + reserves_again(&b); + + // 2. Displaced bindings on all three channels are dropped off-lock; the queues stay. + let b = backend(&[(Displace, 0, false), (Displace, 0, false), (Displace, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "binding 11", "binding 12", "binding 10"]); + assert_eq!(installed(&b), [10, 11, 12]); + assert!(cancelled(&b).is_empty()); + + // 3. A later channel fails its rollback: the channels taken before it are still finished. + let b = backend(&[(Keep, 0, false), (Cancel, 0, false), (Fail, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "a failed rollback left an empty entry holding its QID"); + + // 4. The drain releases both idle siblings and finishes both; the primary stays. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 0, true)]); + drain(&b).unwrap(); + assert_eq!(take_log(), ["drop 11", "drop 12"]); + assert_eq!(cancelled(&b), [11, 12]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + reserves_again(&b); + + // 5. A busy later sibling stops the drain (EAGAIN), and the sibling taken before it is + // still finished, so the owner is not locked out. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 1, true)]); + assert_eq!(drain(&b), Err(EAGAIN)); + assert_eq!(take_log(), ["drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "EAGAIN left a drained sibling's entry empty"); + reserves_again(&b); + + // 6. Finishing goes on past a failed cancellation: the others' reservations still go. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.shared.state.0.borrow_mut().as_mut().unwrap().queues.qids.refuse = Some(11); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [12, 10], "a failed cancellation stopped the others"); + + // 7. More channels than places (beyond the per-owner bound): refused before the extra + // channel changes; the three taken are finished and the extra one stays installed. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 13", "drop 11", "drop 12", "drop 13"]); + assert_eq!(cancelled(&b), [11, 12, 13]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + + println!("PASS g17-compute-retired: no reservation leaks across rollback and sibling drain"); +} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=[ + 'queue-under-lock', 'binding-under-lock', 'drain-under-lock', 'drain-local-on-eagain', + 'finish-stops-at-error', 'early-return-skips-finish', 'overwrite-full', + ]) + args = parser.parse_args() + source = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-retired-') as tmp: + rs = Path(tmp) / 'test.rs' + exe = Path(tmp) / 'test' + rs.write_text(source) + build = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if build.returncode != 0: + sys.stderr.write(build.stderr) + return build.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 894d87bffca89b..84f2ce51675aa1 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -92,7 +92,8 @@ def build_harness(mutation=None): release_fn = item(runtime_src, 'pub(super) fn release_compute(') ack_exit_fn = item(exit_src, 'pub(super) fn acknowledge_compute_exit(') pub_exit_fn = item(exit_src, 'fn publish_compute_exit(') - rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(') + rollback_fn = item(runtime_src, 'fn rollback_unpublished_compute(\n') + backend_rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(&self)') grow_fn = item(runtime_src, 'fn grow_compute(') drain_sib_fn = item(runtime_src, 'fn drain_compute_siblings(') direct_fn = item(runtime_src, 'fn compute_direct(') @@ -203,7 +204,12 @@ def build_harness(mutation=None): rollback_fn, 'for primary_pass in [false, true]', 'queue.is_primary() == primary_pass', - '.rollback_unpublished(self.owner, &self.context)?', + '.rollback_unpublished(owner, context)?', + ) and ordered_ok( + backend_rollback_fn, + 'firmware.queues.rollback_unpublished_compute(', + 'drop(state);', + 'self.finish_retired_compute(&mut retired)', ) grow_releases_siblings_ok = ( ordered_ok( @@ -216,10 +222,9 @@ def build_harness(mutation=None): ) and ordered_ok( grow_fn, - 'retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?;', + 'firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?;', 'firmware.queues.compute_primary(self.owner)', - 'for item in retired_siblings {', - 'self.finish_uninstalled_compute(Some(item))?;', + 'self.finish_retired_compute(&mut retired_siblings)?;', ) ) exit_propagates_ok = ordered_ok( diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 055db828b15f1e..e9d4592d9ed7bc 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -271,6 +271,10 @@ def mutations(flag, names, base, expect=KILL): 'count-owed-twice'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], + 'g17-compute-retired-tests.py': [([], PASS)] + + mutations('--mutation', ('queue-under-lock', 'binding-under-lock', 'drain-under-lock', + 'drain-local-on-eagain', 'finish-stops-at-error', + 'early-return-skips-finish', 'overwrite-full'), []), 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), From e6b3e36fdbb87996fd835ed592d3270d475a5c57 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:42:52 +1100 Subject: [PATCH 1335/1514] arm64: dts: apple: retain the T8132 chosen flag The existing DT check compares the complete warning for the unmatched chosen properties. Keep disk-boot until those properties have schema coverage and leave the byte-identical duplicate M1 USB4 alias removal in this series. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-jxxx.dtsi | 1 + 1 file changed, 1 insertion(+) diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index f471c65f7c413d..03a129758b10b9 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -39,6 +39,7 @@ stdout-path = "serial0"; + linux-enablement-mac,disk-boot; linux-enablement-mac,dapf-handoff = "/arm-io/aop", "/arm-io/pmp"; linux-enablement-mac,dapf-power-on-handoff = "/arm-io/pmp"; From 7fc61f14b0b560109720dba5e511b105c9d28451 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:43:54 +1100 Subject: [PATCH 1336/1514] Bluetooth: mt7932: look for version-independent firmware names first The Bluetooth images and the PTX carry their version in their file names, so a firmware update renames them and the driver no longer finds the new files. Ask first for mediatek/mt7932/bt-b0.bin, bt-b1.bin and bt-ptb.ptx, which user space can point at the newest image of each kind, and fall back to the versioned names when they are not there. A file that exists but fails the image trailer, size or PTX checks also falls back to the next name, so a bad version-independent file cannot stop Bluetooth when the versioned file would work. Signed-off-by: Ryan Murray --- drivers/bluetooth/mt7932_bt_pcie.c | 106 ++++++++++++++++++++++------- 1 file changed, 81 insertions(+), 25 deletions(-) diff --git a/drivers/bluetooth/mt7932_bt_pcie.c b/drivers/bluetooth/mt7932_bt_pcie.c index 0882703177b90a..cc01adea054fa5 100644 --- a/drivers/bluetooth/mt7932_bt_pcie.c +++ b/drivers/bluetooth/mt7932_bt_pcie.c @@ -69,6 +69,15 @@ /* How long a wake reason may take to arrive once the transport is back. */ #define BT7932_WAKE_REASON_MS 200 +/* + * The firmware files carry their version in their names, and a firmware + * update renames them. User space can install the newest image of each kind + * under a name that does not change; look for that first, then for the + * versioned names. + */ +#define BT7932_FW_B0_STABLE "mediatek/mt7932/bt-b0.bin" +#define BT7932_FW_B1_STABLE "mediatek/mt7932/bt-b1.bin" +#define BT7932_PTX_STABLE "mediatek/mt7932/bt-ptb.ptx" #define BT7932_FW_B0 "mediatek/MT7932B0_OS_TypeB_0.1.44.0_241001003711.bin" #define BT7932_FW_B1 "mediatek/MT7932B1_OS_TypeB_2.0.177.0_260706180356.bin" #define BT7932_FW_B1_FALLBACK "mediatek/MT7932B1_OS_TypeB_0.1.133.0_260128190103.bin" @@ -401,31 +410,76 @@ static int bt7932_validate_ptx(const u8 *data, size_t size) return next == size ? 0 : -EINVAL; } +static int bt7932_validate_image(const u8 *data, size_t size) +{ + if (size <= 32 || size - 32 > U32_MAX - 3) + return -EINVAL; + if (memcmp(data + size - 32 + 16, "ALPS\x8a\x10\x8a\x10", 8)) + return -EINVAL; + return 0; +} + +static const char *const bt7932_b0_names[] = { + BT7932_FW_B0_STABLE, BT7932_FW_B0, +}; + +static const char *const bt7932_b1_names[] = { + BT7932_FW_B1_STABLE, BT7932_FW_B1, BT7932_FW_B1_FALLBACK, +}; + +static const char *const bt7932_ptx_names[] = { + BT7932_PTX_STABLE, BT7932_PTX, +}; + +/* + * Load the first of @names that exists and passes @validate. A file that is + * missing or fails validation moves on to the next name, so a bad + * version-independent file cannot hide a good versioned one. Only the last + * name warns when it is missing. + */ +static int bt7932_request_valid(struct bt7932 *bt, const struct firmware **fw, + const char *const *names, size_t count, + int (*validate)(const u8 *data, size_t size)) +{ + struct device *dev = &bt->pdev->dev; + int ret = -ENOENT; + size_t i; + + for (i = 0; i < count; i++) { + if (i + 1 < count) + ret = firmware_request_nowarn(fw, names[i], dev); + else + ret = request_firmware(fw, names[i], dev); + if (ret == -ENOENT) + continue; + if (ret) + return ret; + ret = validate((*fw)->data, (*fw)->size); + if (!ret) + return 0; + dev_warn(dev, "%s is not usable (%d)\n", names[i], ret); + release_firmware(*fw); + *fw = NULL; + } + return ret; +} + static int bt7932_read_inputs(struct bt7932 *bt) { const struct firmware *fw; - const u8 *trailer; u64 last; int i, ret; - if (!bt->rom) { - ret = request_firmware(&fw, BT7932_FW_B0, &bt->pdev->dev); - } else { - ret = firmware_request_nowarn(&fw, BT7932_FW_B1, &bt->pdev->dev); - if (ret == -ENOENT) - ret = request_firmware(&fw, BT7932_FW_B1_FALLBACK, &bt->pdev->dev); - } + if (!bt->rom) + ret = bt7932_request_valid(bt, &fw, bt7932_b0_names, + ARRAY_SIZE(bt7932_b0_names), + bt7932_validate_image); + else + ret = bt7932_request_valid(bt, &fw, bt7932_b1_names, + ARRAY_SIZE(bt7932_b1_names), + bt7932_validate_image); if (ret) return ret; - if (fw->size <= 32 || fw->size - 32 > U32_MAX - 3) { - ret = -EINVAL; - goto release_image; - } - trailer = fw->data + fw->size - 32; - if (memcmp(trailer + 16, "ALPS\x8a\x10\x8a\x10", 8)) { - ret = -EINVAL; - goto release_image; - } bt->image_body = fw->size - 32; bt->image_size = ALIGN(bt->image_body, 4); bt->image = dma_alloc_coherent(&bt->pdev->dev, bt->image_size, @@ -459,16 +513,15 @@ static int bt7932_read_inputs(struct bt7932 *bt) release_firmware(fw); if (ret) return ret; - ret = request_firmware(&fw, BT7932_PTX, &bt->pdev->dev); + ret = bt7932_request_valid(bt, &fw, bt7932_ptx_names, + ARRAY_SIZE(bt7932_ptx_names), + bt7932_validate_ptx); if (ret) return ret; - ret = bt7932_validate_ptx(fw->data, fw->size); - if (!ret) { - bt->ptx_size = fw->size; - bt->ptx = kmemdup(fw->data, fw->size, GFP_KERNEL); - if (!bt->ptx) - ret = -ENOMEM; - } + bt->ptx_size = fw->size; + bt->ptx = kmemdup(fw->data, fw->size, GFP_KERNEL); + if (!bt->ptx) + ret = -ENOMEM; release_firmware(fw); if (ret) return ret; @@ -1988,6 +2041,9 @@ module_pci_driver(bt7932_driver); MODULE_DESCRIPTION("MediaTek MT7932 Bluetooth PCIe transport for the Apple MacBook Neo"); MODULE_LICENSE("GPL"); +MODULE_FIRMWARE(BT7932_FW_B0_STABLE); +MODULE_FIRMWARE(BT7932_FW_B1_STABLE); +MODULE_FIRMWARE(BT7932_PTX_STABLE); MODULE_FIRMWARE(BT7932_FW_B0); MODULE_FIRMWARE(BT7932_FW_B1); MODULE_FIRMWARE(BT7932_FW_B1_FALLBACK); From 44282911e4a48fd6ba0753cdf6f79f5e977b9ae0 Mon Sep 17 00:00:00 2001 From: Bartosz Nitka Date: Thu, 19 Nov 2026 13:58:59 +0100 Subject: [PATCH 1337/1514] accel/ane: h16: take a program's process pool before LOAD Every CREATE makes the H16/H17 firmware ask for a 2 MiB EXPP process pool by SHAREDMALLOC, and it answers the CREATE only once that request was served. A request the host cannot serve, for lack of memory or of the 12 MiB shared quota, is never answered: the transport fails, the CREATE is lost, and the session is quarantined, taking every other loaded program with it. The host knows the request is coming, so take the pool first: before a LOAD (and a replay), make sure a retired EXPP allocation is there, allocating one now and keeping it retired if not. The firmware's request then reuses it as it reuses any pool given back by FREE. With no memory or no quota the LOAD now fails with -ENOMEM or -ENOSPC before any traffic, the engine stays up and every other program keeps running. A FREE of a torn-down program's pool that is still posted is served first, and the reservation tried once more. The firmware's request still goes through the same checks; a request the host did not foresee and cannot serve fails the transport as before. KUnit: past the quota a LOAD fails with -ENOSPC and no command sent, the other programs keep running and a closed program's pool serves the next LOAD; no memory gives -ENOMEM the same way; a FREE posted after the settle is served by the next LOAD; and at the transport level a reserved allocation serves its request without an allocation and a refused reservation leaves the transport working. The fake firmware now asks for the pool during CREATE and frees it after UNLOAD. [ported from niteria/linux 1e518c576e74 (ane/h17-cma-enomem), which has no Signed-off-by; onto the per-program command records: the replay takes the pool before its record instead of after an arena room check] Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_transport.h | 94 ++++++--- drivers/accel/ane/ane_fw_transport_test.c | 62 ++++++ drivers/accel/ane/ane_h16_program.c | 34 ++++ drivers/accel/ane/ane_h16_program_test.c | 224 +++++++++++++++++++++- 4 files changed, 385 insertions(+), 29 deletions(-) diff --git a/drivers/accel/ane/ane_fw_transport.h b/drivers/accel/ane/ane_fw_transport.h index bb166d37f15543..33d3467feb218c 100644 --- a/drivers/accel/ane/ane_fw_transport.h +++ b/drivers/accel/ane/ane_fw_transport.h @@ -723,7 +723,9 @@ ane_fw_transport_free(struct ane_fw_transport *t, void *slot, u64 dva, u64 bytes * firmware frees it after UNLOAD (often only during a later program), but the * backing stays mapped until reset: without reuse the 12 MiB quota ran out at * the sixth program of a boot. Only memory the firmware itself gave back by - * FREE is served again, and only for the same tag and size. + * FREE, or that the host reserved for the request + * (ane_fw_transport_shared_reserve()), is served again, and only for the + * same tag and size. */ static inline unsigned int ane_fw_shared_reusable(const struct ane_fw_transport *t, size_t size, u64 tag) @@ -737,11 +739,73 @@ ane_fw_shared_reusable(const struct ane_fw_transport *t, size_t size, u64 tag) return t->shared_count; } +/* + * A new shared allocation of size bytes under tag, within the host's caps + * (ANE_FW_SHARED_MAX entries, ANE_FW_SHARED_TOTAL bytes): its index, live. + */ +static inline int ane_fw_shared_add(struct ane_fw_transport *t, size_t size, u64 tag, + unsigned int *index) +{ + struct ane_fw_surface s = {}; + unsigned int i; + int ret; + + if (t->shared_count == ANE_FW_SHARED_MAX || size > ANE_FW_SHARED_TOTAL - + t->shared_bytes) + return -ENOSPC; + ret = t->ops->alloc(t->ctx, size, tag, &s); + if (ret) + return ret; + if (!ane_fw_surface_valid(&s) || !IS_ALIGNED(s.dva, SZ_16K) || + s.size != size || ane_fw_surfaces_overlap(&s, &t->ipc) || + ane_fw_surfaces_overlap(&s, &t->pool)) + return -EPROTO; + for (i = 0; i < t->shared_count; i++) + if (ane_fw_surfaces_overlap(&s, &t->shared[i])) + return -EPROTO; + *index = t->shared_count; + t->shared_tags[t->shared_count] = tag; + t->shared_retired[t->shared_count] = false; + t->shared[t->shared_count++] = s; + t->shared_bytes += size; + return 0; +} + +/* + * Make sure a later SHAREDMALLOC request of size bytes under tag is served + * from memory the host already has: a retired allocation of that tag and + * size, or a new one made now and kept retired for it. The firmware waits + * for the answer to every request, with its shared-memory lock held, and a + * request the host cannot serve is never answered: the command behind it + * stalls and only a power cycle recovers the engine. A request the host + * knows is coming is therefore taken before the command that causes it, so + * running out of memory or quota (-ENOMEM, -ENOSPC) refuses that command + * before the firmware sees it. + */ +static inline int ane_fw_transport_shared_reserve(struct ane_fw_transport *t, size_t size, + u32 tag) +{ + unsigned int i; + int ret; + + if (t->error) + return t->error; + if (!size || !IS_ALIGNED(size, SZ_16K)) + return -EINVAL; + if (ane_fw_shared_reusable(t, size, tag) < t->shared_count) + return 0; + ret = ane_fw_shared_add(t, size, tag, &i); + if (ret) + return ret; + t->shared_retired[i] = true; + ane_fw_shared_note(t, "reserve", i); + return 0; +} + static inline int ane_fw_transport_irq(struct ane_fw_transport *t, u32 *pending); static inline int ane_fw_transport_shared(struct ane_fw_transport *t) { - struct ane_fw_surface s = {}; u64 word0, word1, word2; size_t size; unsigned int i; @@ -801,33 +865,13 @@ static inline int ane_fw_transport_shared(struct ane_fw_transport *t) ane_fw_shared_note(t, "reuse", i); return 0; } - if (t->shared_count == ANE_FW_SHARED_MAX || size > ANE_FW_SHARED_TOTAL - - t->shared_bytes) { - ret = -ENOSPC; - goto refused; - } - ret = t->ops->alloc(t->ctx, size, word2, &s); + ret = ane_fw_shared_add(t, size, word2, &i); if (ret) goto refused; - if (!ane_fw_surface_valid(&s) || !IS_ALIGNED(s.dva, SZ_16K) || - s.size != size || ane_fw_surfaces_overlap(&s, &t->ipc) || - ane_fw_surfaces_overlap(&s, &t->pool)) { - ret = -EPROTO; - goto refused; - } - for (i = 0; i < t->shared_count; i++) { - if (ane_fw_surfaces_overlap(&s, &t->shared[i])) { - ret = -EPROTO; - goto refused; - } - } - t->shared_tags[t->shared_count] = word2; - t->shared[t->shared_count++] = s; - t->shared_bytes += size; t->ops->store64(t->ctx, p + 8, 0); - t->ops->store64(t->ctx, p + 16, t->shared_count); + t->ops->store64(t->ctx, p + 16, i + 1); t->ops->write_barrier(t->ctx); - t->ops->store64(t->ctx, p, s.dva | 1); + t->ops->store64(t->ctx, p, t->shared[i].dva | 1); t->ops->write_barrier(t->ctx); ane_fw_transport_doorbell(t, ANE_FW_SHAREDMALLOC); ane_fw_transport_advance(t, ANE_FW_SHAREDMALLOC); diff --git a/drivers/accel/ane/ane_fw_transport_test.c b/drivers/accel/ane/ane_fw_transport_test.c index c38415ada6c6b6..75849a914336f9 100644 --- a/drivers/accel/ane/ane_fw_transport_test.c +++ b/drivers/accel/ane/ane_fw_transport_test.c @@ -1186,6 +1186,67 @@ static void ane_transport_pool_no_free_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_fw_transport_shared(&f->t), -ENOSPC); } +/* + * A reserved allocation is kept retired and serves the request it was made + * for, with no allocation then; a full quota or no memory refuses the + * reservation without failing the transport or touching the ring. + */ +static void ane_transport_shared_reserve_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + unsigned int i; + u64 dva; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, 1, ANE_FW_SHARED_EXPP), + -EINVAL); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + KUNIT_EXPECT_TRUE(test, f->t.shared_retired[0]); + dva = f->t.shared[0].dva; + /* Already there: no second allocation. */ + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + ane_test_shared_request(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); + KUNIT_EXPECT_FALSE(test, f->t.shared_retired[0]); + KUNIT_EXPECT_EQ(test, ane_test_load(f, ane_test_slot(f, ANE_FW_SHAREDMALLOC) - + ANE_FW_SLOT_SIZE), dva | 1); + + /* No memory: refused, and nothing recorded. */ + f->alloc_error = -ENOMEM; + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -ENOMEM); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 1U); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + f->alloc_error = 0; + f->allocs = 1; + + /* Fill the quota with live pools; one more is refused cleanly. */ + for (i = 1; i < ANE_FW_SHARED_TOTAL / SZ_2M; i++) { + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, + ANE_FW_SHARED_EXPP), 0); + ane_test_shared_request(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + } + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -ENOSPC); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + KUNIT_EXPECT_EQ(test, f->refusals, 0U); + + /* A FREE gives one back, which serves the next reservation. */ + f->t.native_free = true; + ane_test_shared_request(f, dva, 0, 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + 0); + KUNIT_EXPECT_EQ(test, f->allocs, (unsigned int)(ANE_FW_SHARED_TOTAL / SZ_2M)); + KUNIT_EXPECT_EQ(test, f->t.error, 0); +} + /* A FREE posted after UNLOAD is answered by the settle loop. */ static void ane_transport_settle_test(struct kunit *test) { @@ -1550,6 +1611,7 @@ static struct kunit_case ane_transport_cases[] = { KUNIT_CASE(ane_transport_pool_reuse_test), KUNIT_CASE(ane_transport_pool_reuse_native_test), KUNIT_CASE(ane_transport_pool_no_free_test), + KUNIT_CASE(ane_transport_shared_reserve_test), KUNIT_CASE(ane_transport_settle_test), KUNIT_CASE(ane_transport_carry_shared_test), KUNIT_CASE(ane_transport_mode_stop_test), diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index c835fab0f1076b..cff8708460a2d1 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -654,6 +654,34 @@ static int h16_pool_room(struct ane_h16_session *s, const size_t *lengths, return 0; } +/* + * Every CREATE makes the firmware ask for a 2 MiB EXPP process pool by + * SHAREDMALLOC and wait for it before it answers; a pool it could not get + * leaves the CREATE stalled and the engine quarantined, and with it every + * other program of the session. Take the pool before LOAD instead + * (ane_fw_transport_shared_reserve()), so that without memory or quota the + * LOAD fails cleanly, before any traffic. A FREE of a torn-down program's + * pool may still be posted (it can come after the post-UNLOAD settle): + * serve it and try once more before giving up. + */ +static int h16_process_pool(struct ane_h16_session *s) +{ + int ret = ane_fw_transport_shared_reserve(s->transport, SZ_2M, ANE_FW_SHARED_EXPP); + + if (ret == -ENOSPC) { + ret = ane_fw_transport_settle(s->transport, s->settle_ns, + max(s->settle_ns, ANE_H16_SETTLE_LIMIT_NS)); + if (ret < 0) + return h16_fail(s, ret); + ret = ane_fw_transport_shared_reserve(s->transport, SZ_2M, + ANE_FW_SHARED_EXPP); + } + if (ret) + s->ops->log(s->ctx, "LOAD: no process pool", (u64)-ret, + s->transport->shared_bytes); + return ret; +} + /* * Outside a request batch, the commands published since mark were all * acknowledged and the firmware keeps no pointer into them: give their @@ -1124,6 +1152,9 @@ int ane_h16_session_load(struct ane_h16_session *s, if (ret) return ret; ret = h16_load_room(s); + if (ret) + return ret; + ret = h16_process_pool(s); if (ret) return ret; p = kzalloc_obj(*p); @@ -2097,6 +2128,9 @@ static int h16_replay(struct ane_h16_session *s, struct ane_h16_program *p) unsigned int i; int ret; + ret = h16_process_pool(s); + if (ret) + return ret; command = kzalloc(ANE_H16_CREATE_SIZE, GFP_KERNEL); if (!command) return -ENOMEM; diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index ad746c14c7fa8a..e701137da28948 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -16,6 +16,8 @@ #define FW_IPC_DVA 0x100003d0000ULL #define FW_POOL_DVA 0x10000384000ULL #define FW_MAP_DVA 0x10001f00000ULL +/* Shared (SHAREDMALLOC) allocations, far above the program mappings. */ +#define FW_SHARED_DVA 0x10010000000ULL #define FW_RING_SLOTS 8 #define FW_REPORTS 0x8000 @@ -87,6 +89,22 @@ struct prog_fw { */ u64 live, window; unsigned int unmaps, map_fail_at; + /* + * SHAREDMALLOC: with expp, CREATE asks for a 2 MiB EXPP pool and is + * answered only once the host served it, and UNLOAD frees the pool + * again, as the H16/H17 firmware does. irq holds the pending + * notification bits; allocs counts ops->alloc calls, alloc_fail + * makes them fail with -ENOMEM. + */ + bool expp, alloc_fail; + u32 irq; + u64 shared_dva; + unsigned int allocs; + /* The CREATE waiting for its pool, by IO slot; its program ID. */ + u8 *create_slot; + u64 create_length, create_dva; + u32 create_program; + u64 expp_dva[32]; }; static u64 fw_load(void *ctx, const void *p) @@ -105,7 +123,9 @@ static void fw_barrier(void *ctx) static u32 fw_read32(void *ctx, u32 reg) { - return 0; + struct prog_fw *f = ctx; + + return reg == f->soc.irq_status ? f->irq : 0; } static u8 *fw_slot(struct prog_fw *f, unsigned int ch) @@ -118,6 +138,17 @@ static void fw_advance(struct prog_fw *f, unsigned int ch) f->head[ch] = (f->head[ch] + 1) % f->t.channels[ch].slots; } +/* A SHAREDMALLOC request in the firmware's next slot, notified. */ +static void fw_shared_post(struct prog_fw *f, u64 word0, u64 bytes, u64 tag) +{ + u8 *slot = fw_slot(f, ANE_FW_SHAREDMALLOC); + + put_unaligned_le64(bytes, slot + 8); + put_unaligned_le64(tag, slot + 16); + put_unaligned_le64(word0, slot); + f->irq |= BIT(ANE_FW_SHAREDMALLOC); +} + static void fw_report(struct prog_fw *f, u64 uuid, u32 program, u32 process, u32 state) { u32 offset = FW_REPORTS + (f->reports++ % 16) * 0x60; @@ -232,8 +263,16 @@ static void fw_command(struct prog_fw *f, unsigned int ch) cmd + ANE_H16_LOAD_ID_OFFSET); break; case ANE_H16_UNLOAD_PROGRAM: - if (get_unaligned_le32(cmd + 8) - f->program < 32) - f->programs_live &= ~BIT(get_unaligned_le32(cmd + 8) - f->program); + if (get_unaligned_le32(cmd + 8) - f->program < 32) { + u32 i = get_unaligned_le32(cmd + 8) - f->program; + + f->programs_live &= ~BIT(i); + /* The pool comes back by FREE, after the UNLOAD reply. */ + if (f->expp && f->expp_dva[i]) { + fw_shared_post(f, f->expp_dva[i], 0, 0); + f->expp_dva[i] = 0; + } + } break; case ANE_H16_TERMINATE_PROCESS: if (get_unaligned_le32(cmd + 0xc) - f->process < 32) @@ -244,6 +283,16 @@ static void fw_command(struct prog_fw *f, unsigned int ch) put_unaligned_le32(fw_take_id(&f->processes_live, f->process), cmd + 0xc); if (f->mode == FW_CREATE_BODY) cmd[0x100] = 1; + if (f->expp) { + /* No reply until the host served the process pool. */ + f->create_slot = slot; + f->create_length = length; + f->create_dva = dva; + f->create_program = get_unaligned_le32(cmd + 8); + fw_shared_post(f, 0, SZ_2M, ANE_FW_SHARED_EXPP); + fw_advance(f, ch); + return; + } break; case ANE_H16_EXECUTE: f->exec_length = min_t(size_t, length, sizeof(f->exec)); @@ -258,12 +307,35 @@ static void fw_command(struct prog_fw *f, unsigned int ch) fw_execute(f, cmd); } +/* The host answered the SHAREDMALLOC slot; a CREATE waiting for it completes. */ +static void fw_shared_answered(struct prog_fw *f) +{ + u8 *slot = fw_slot(f, ANE_FW_SHAREDMALLOC); + u64 word0 = get_unaligned_le64(slot); + + if (!(word0 & 1)) + return; + fw_advance(f, ANE_FW_SHAREDMALLOC); + if (word0 == 1 || !f->create_slot) + return; + if (f->create_program - f->program < 32) + f->expp_dva[f->create_program - f->program] = word0 & ~1ULL; + put_unaligned_le64(f->create_length, f->create_slot + 8); + put_unaligned_le64(0, f->create_slot + 16); + put_unaligned_le64(f->create_dva | 1, f->create_slot); + f->create_slot = NULL; +} + static void fw_write32(void *ctx, u32 reg, u32 value) { struct prog_fw *f = ctx; + if (reg == f->soc.irq_ack) + f->irq &= ~value; if (reg != f->soc.doorbell) return; + if (value & BIT(ANE_FW_SHAREDMALLOC)) + fw_shared_answered(f); /* Commands take doorbell_ns to answer; returning report slots is free. */ if (value & (BIT(ANE_FW_IO) | BIT(ANE_FW_DATA_CHAIN))) f->now += f->doorbell_ns; @@ -294,9 +366,22 @@ static void fw_relax(void *ctx, u64 waited_ns) } } +static void *fw_zalloc(struct kunit *test, size_t size); + static int fw_alloc(void *ctx, size_t size, u32 tag, struct ane_fw_surface *s) { - return -ENOMEM; + struct prog_fw *f = ctx; + + f->allocs++; + if (f->alloc_fail) + return -ENOMEM; + *s = (struct ane_fw_surface) { + .cpu = fw_zalloc(f->test, size), .dva = f->shared_dva, .size = size, + }; + if (!s->cpu) + return -ENOMEM; + f->shared_dva += size; + return 0; } static void fw_refused(void *ctx, u64 w0, u64 w1, u64 w2, int error) @@ -481,6 +566,7 @@ static struct prog_fw *fw_create_family(struct kunit *test, unsigned int family) put_unaligned_le64(f->ipc.dva + 0x800 + i * 0x200, p + 0x50); } f->next_dva = FW_MAP_DVA; + f->shared_dva = FW_SHARED_DVA; f->program = 0x11; f->process = 0; if (ane_fw_transport_init(&f->t, &f->soc, &fw_ops, f, f->ipc, f->pool, SZ_16K, @@ -3565,6 +3651,133 @@ static void program_recover_gate_test(struct kunit *test) ane_h16_session_put(&f->s, p); } +/* As the firmware does at boot: a small shared allocation of its own. */ +static void fw_boot_allocations(struct kunit *test, struct prog_fw *f) +{ + fw_shared_post(f, 0, SZ_16K, 0x43434d44); + KUNIT_ASSERT_EQ(test, ane_fw_transport_irq(&f->t, &(u32){ 0 }), 0); + KUNIT_ASSERT_EQ(test, ane_fw_transport_shared(&f->t), 0); +} + +/* + * Every live program holds a 2 MiB EXPP process pool, which the firmware + * asks for during CREATE and waits for. Six programs at once on the Neo + * went past the 12 MiB shared quota: the pool was refused, the CREATE + * stalled, and the quarantine took the five other programs with it. Now + * the LOAD past the quota fails with -ENOSPC before any traffic, the + * engine stays up, the other programs keep running, and a closed + * program's pool serves the next LOAD. + */ +static void program_process_pool_quota_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p[ANE_FW_SHARED_TOTAL / SZ_2M + 1] = {}, *q = NULL; + unsigned int i, n = 0, count, allocs; + int ret; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + fw_boot_allocations(test, f); + while (n < ARRAY_SIZE(p)) { + count = f->count; + ret = fw_load_program(f, &p[n]); + if (ret) + break; + KUNIT_EXPECT_EQ(test, f->count, count + 2); + n++; + } + /* 16 KiB of the quota is the firmware's: room for one pool less. */ + KUNIT_EXPECT_EQ(test, n, (unsigned int)(ANE_FW_SHARED_TOTAL / SZ_2M - 1)); + KUNIT_EXPECT_EQ(test, ret, -ENOSPC); + KUNIT_EXPECT_PTR_EQ(test, p[n], NULL); + KUNIT_EXPECT_EQ(test, f->count, count); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); + KUNIT_EXPECT_EQ(test, f->t.error, 0); + for (i = 0; i < n; i++) + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p[i]), 0); + + /* The FREE after UNLOAD makes the pool serve the next LOAD. */ + allocs = f->allocs; + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[0]), 0); + ane_h16_session_put(&f->s, p[0]); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &q), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, q), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, q), 0); + ane_h16_session_put(&f->s, q); + for (i = 1; i < n; i++) { + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[i]), 0); + ane_h16_session_put(&f->s, p[i]); + } + /* Load and close cycles take no new pool. */ + for (i = 0; i < 20; i++) + KUNIT_ASSERT_EQ(test, fw_cycle(f), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + +/* No memory for the pool: -ENOMEM before any traffic, and the next LOAD works. */ +static void program_process_pool_nomem_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *a = NULL, *b = NULL; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &a), 0); + KUNIT_EXPECT_EQ(test, f->count, 2U); + f->alloc_fail = true; + KUNIT_EXPECT_EQ(test, fw_load_program(f, &b), -ENOMEM); + KUNIT_EXPECT_PTR_EQ(test, b, NULL); + KUNIT_EXPECT_EQ(test, f->count, 2U); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + f->alloc_fail = false; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &b), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, b), 0); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, a), 0); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 2U); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + +/* + * A FREE the firmware posts only after the post-UNLOAD settle: at the quota + * the LOAD serves it and takes that pool instead of failing. + */ +static void program_process_pool_late_free_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p[ANE_FW_SHARED_TOTAL / SZ_2M] = {}, *q = NULL; + unsigned int i, allocs; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + for (i = 0; i < ARRAY_SIZE(p); i++) + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p[i]), 0); + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, (size_t)ANE_FW_SHARED_TOTAL); + /* Torn down, with the FREE held back past the settle. */ + f->expp = false; + KUNIT_ASSERT_EQ(test, ane_h16_session_close(&f->s, p[0]), 0); + ane_h16_session_put(&f->s, p[0]); + f->expp = true; + fw_shared_post(f, f->expp_dva[0], 0, 0); + f->expp_dva[0] = 0; + allocs = f->allocs; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &q), 0); + KUNIT_EXPECT_EQ(test, f->allocs, allocs); + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, q), 0); + KUNIT_EXPECT_FALSE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 0U); +} + static struct kunit_case program_cases[] = { KUNIT_CASE_SLOW(program_pool_rewind_test), KUNIT_CASE_SLOW(program_pool_resident_test), @@ -3627,6 +3840,9 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_h17_sections_test), KUNIT_CASE(program_h17_mobilenet_test), KUNIT_CASE(program_h17_switch_test), + KUNIT_CASE(program_process_pool_quota_test), + KUNIT_CASE(program_process_pool_nomem_test), + KUNIT_CASE(program_process_pool_late_free_test), {} }; From 2365f95fd33620854ee728077975f8b1fa0ab22e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:47:33 +1100 Subject: [PATCH 1338/1514] accel/ane: fail the transport when a reserved shared pool is invalid A shared allocation the backend hands back for a firmware request is checked (16 KiB aligned DVA, exact size, no overlap with the IPC area, the command pool or another allocation), and one that fails the check fails the transport. The same check runs when a LOAD reserves its process pool ahead of the request, but there it only returned -EPROTO: the backend's mapping is not recorded, so every later LOAD made and dropped another 2 MiB mapping that the backend keeps until teardown. Fail the transport there as well, and quarantine the session when a reservation finds the transport failed, as the request path does. KUnit: a misaligned backend surface fails the reservation with -EPROTO, fails the transport, records nothing, and a second reservation does not allocate again. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_transport.h | 7 +++++++ drivers/accel/ane/ane_fw_transport_test.c | 21 +++++++++++++++++++++ drivers/accel/ane/ane_h16_program.c | 2 ++ 3 files changed, 30 insertions(+) diff --git a/drivers/accel/ane/ane_fw_transport.h b/drivers/accel/ane/ane_fw_transport.h index 33d3467feb218c..b4e834d04eb0f0 100644 --- a/drivers/accel/ane/ane_fw_transport.h +++ b/drivers/accel/ane/ane_fw_transport.h @@ -795,6 +795,13 @@ static inline int ane_fw_transport_shared_reserve(struct ane_fw_transport *t, si if (ane_fw_shared_reusable(t, size, tag) < t->shared_count) return 0; ret = ane_fw_shared_add(t, size, tag, &i); + /* + * An invalid surface from the backend is a host error, as it is for a + * request (ane_fw_transport_shared()): its mapping is not recorded, so + * retrying would map another one at every LOAD. + */ + if (ret == -EPROTO) + return ane_fw_transport_fail(t, ret); if (ret) return ret; t->shared_retired[i] = true; diff --git a/drivers/accel/ane/ane_fw_transport_test.c b/drivers/accel/ane/ane_fw_transport_test.c index 75849a914336f9..207a7e27f8fb58 100644 --- a/drivers/accel/ane/ane_fw_transport_test.c +++ b/drivers/accel/ane/ane_fw_transport_test.c @@ -1247,6 +1247,26 @@ static void ane_transport_shared_reserve_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->t.error, 0); } +/* + * A backend surface that fails validation fails the transport, as it does for + * a request, so a later LOAD does not map another one. + */ +static void ane_transport_shared_reserve_invalid_test(struct kunit *test) +{ + struct ane_transport_test *f = test->priv; + + KUNIT_ASSERT_EQ(test, ane_fw_transport_arm(&f->t), 0); + f->alloc_bad = 1; + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -EPROTO); + KUNIT_EXPECT_EQ(test, f->t.error, -EPROTO); + KUNIT_EXPECT_EQ(test, f->t.shared_count, 0U); + KUNIT_EXPECT_EQ(test, f->t.shared_bytes, 0UL); + KUNIT_EXPECT_EQ(test, ane_fw_transport_shared_reserve(&f->t, SZ_2M, ANE_FW_SHARED_EXPP), + -EPROTO); + KUNIT_EXPECT_EQ(test, f->allocs, 1U); +} + /* A FREE posted after UNLOAD is answered by the settle loop. */ static void ane_transport_settle_test(struct kunit *test) { @@ -1612,6 +1632,7 @@ static struct kunit_case ane_transport_cases[] = { KUNIT_CASE(ane_transport_pool_reuse_native_test), KUNIT_CASE(ane_transport_pool_no_free_test), KUNIT_CASE(ane_transport_shared_reserve_test), + KUNIT_CASE(ane_transport_shared_reserve_invalid_test), KUNIT_CASE(ane_transport_settle_test), KUNIT_CASE(ane_transport_carry_shared_test), KUNIT_CASE(ane_transport_mode_stop_test), diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index cff8708460a2d1..03e45b5e349250 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -676,6 +676,8 @@ static int h16_process_pool(struct ane_h16_session *s) ret = ane_fw_transport_shared_reserve(s->transport, SZ_2M, ANE_FW_SHARED_EXPP); } + if (ret && s->transport->error) + return h16_fail(s, ret); if (ret) s->ops->log(s->ctx, "LOAD: no process pool", (u64)-ret, s->transport->shared_bytes); From ffc9e90a9513078cf26df958a0bb2eaa3d7496be Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:45:33 +1100 Subject: [PATCH 1339/1514] soc: apple: rtkit: keep the crashlog host tests buildable The standalone crashlog tests compile the production parser without kernel Kconfig helpers. Guard the included test by its boolean Kconfig symbol directly. Signed-off-by: Ryan Murray --- drivers/soc/apple/rtkit-crashlog.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/soc/apple/rtkit-crashlog.c b/drivers/soc/apple/rtkit-crashlog.c index 47335bf11c493a..f12a3f6fda8549 100644 --- a/drivers/soc/apple/rtkit-crashlog.c +++ b/drivers/soc/apple/rtkit-crashlog.c @@ -493,6 +493,6 @@ void apple_rtkit_crashlog_dump(struct apple_rtkit *rtk, u8 *bfr, size_t size) "RTKit: End of crashlog reached but no footer present"); } -#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#ifdef CONFIG_APPLE_RTKIT_KUNIT_TEST #include "rtkit-crashlog-test.c" #endif From eaa0b0c12f6789a8d21dbd7765cbbeff95fb71ad Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:50:54 +1100 Subject: [PATCH 1340/1514] accel/ane: h16: quarantine the session when a replay fails early ane_h16_session_replay() documents that a failed replay quarantines the session, but h16_replay() returns before h16_fail() when taking the process pool fails (-ENOSPC, -ENOMEM), when the command buffer cannot be allocated, or when no firmware record is free. The caller then logs "PROGRAM REPLAY FAILED" and the backend reports the session quarantined while s->quarantined stays false, so requests reach firmware whose state is uncertain. Quarantine in ane_h16_session_replay() for any replay error. h16_fail() keeps the first error and reports the hang once, so a replay that already failed the transport is unchanged. KUnit: a replay that cannot take its process pool fails with -ENOMEM, replays nothing and quarantines the session, reported once. Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_h16_program.c | 2 +- drivers/accel/ane/ane_h16_program_test.c | 37 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index 03e45b5e349250..a4d65e98d8bd0d 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -2196,7 +2196,7 @@ int ane_h16_session_replay(struct ane_h16_session *s, unsigned int *replayed, ret = h16_replay(s, p); if (ret) { s->ops->log(s->ctx, "PROGRAM REPLAY FAILED", p->key.program, (u64)-ret); - return ret; + return h16_fail(s, ret); } if (!(*replayed)++) *first_ns = h16_now(s); diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index e701137da28948..ddde540bcfc28f 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -3778,6 +3778,42 @@ static void program_process_pool_late_free_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->hung, 0U); } +/* + * A replay that cannot take its process pool (no memory) fails, and the + * session is quarantined as for any other failed replay. + */ +static void program_process_pool_replay_nomem_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + struct mutex *lock = kunit_kzalloc(test, sizeof(*lock), GFP_KERNEL); + unsigned int replayed; + u64 first; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_NOT_NULL(test, lock); + mutex_init(lock); + f->s.ops = &fw_session_ops_hung; + f->t.native_free = true; + f->expp = true; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + + f->s.lock = lock; + ane_h16_session_sleep(&f->s, true); + fw_cold_boot(f); + ane_h16_session_restart(&f->s); + ane_h16_session_recovered(&f->s); + f->alloc_fail = true; + KUNIT_EXPECT_EQ(test, ane_h16_session_replay(&f->s, &replayed, &first), -ENOMEM); + KUNIT_EXPECT_EQ(test, replayed, 0U); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, f->hung, 1U); + f->alloc_fail = false; + ane_h16_session_sleep(&f->s, false); + f->s.lock = NULL; + cancel_delayed_work_sync(&f->s.gate_work); +} + static struct kunit_case program_cases[] = { KUNIT_CASE_SLOW(program_pool_rewind_test), KUNIT_CASE_SLOW(program_pool_resident_test), @@ -3843,6 +3879,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_process_pool_quota_test), KUNIT_CASE(program_process_pool_nomem_test), KUNIT_CASE(program_process_pool_late_free_test), + KUNIT_CASE(program_process_pool_replay_nomem_test), {} }; From cca33dad24f3c7a9e04b9de7a5b14b65698e2d84 Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Mon, 9 Nov 2026 09:28:42 +1100 Subject: [PATCH 1341/1514] media: apple: add ProRes decode-v0 node Add a compatible-gated stateful decoder alongside the existing encoder. Validate complete ProRes frames and pack the 0x100-byte non-RAW descriptor. Share the APR ring with generation-aware variable-size accounting. Snapshot completion diagnostics before the W1C/tail handoff. Preserve reset-based timeout recovery. Cover descriptor layout, parser bounds, and mixed ring wrap with KUnit. Signed-off-by: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> --- drivers/media/platform/apple/prores/Kconfig | 15 +- .../platform/apple/prores/apple-prores-desc.c | 202 ++++++++- .../platform/apple/prores/apple-prores-drv.c | 404 +++++++++++++++--- .../platform/apple/prores/apple-prores-test.c | 152 ++++++- .../platform/apple/prores/apple-prores.h | 60 ++- 5 files changed, 768 insertions(+), 65 deletions(-) diff --git a/drivers/media/platform/apple/prores/Kconfig b/drivers/media/platform/apple/prores/Kconfig index 27ffadcfcad5f9..ce2f49498cebc2 100644 --- a/drivers/media/platform/apple/prores/Kconfig +++ b/drivers/media/platform/apple/prores/Kconfig @@ -1,31 +1,32 @@ # SPDX-License-Identifier: GPL-2.0-only config VIDEO_APPLE_PRORES - tristate "Apple Silicon ProRes encoder" + tristate "Apple Silicon ProRes codec" depends on VIDEO_DEV depends on ARCH_APPLE || (COMPILE_TEST && 64BIT) depends on OF && IOMMU_API && PM select V4L2_MEM2MEM_DEV select VIDEOBUF2_DMA_CONTIG help - V4L2 memory-to-memory driver for the ProRes encoder engine (APR) + V4L2 memory-to-memory driver for the ProRes codec engine (APR) in Apple M1 Pro (T6000), M4 (T8132), M4 Pro (T6041), M5 (T8142), M5 Pro/Max (T6050) and A18 Pro (T8140) SoCs. On T6041, T8142 and T6050 a per-machine apple/prores--init.bin takes the place of the built-in initialization rows; T8132 has no built-in rows and binds only with apple/prores-t8132-init.bin. It encodes 8 and 16 bit 4:2:2 and 4:4:4 frames to ProRes 422 Proxy, LT, 422, HQ, - 4444 and 4444 XQ. + 4444 and 4444 XQ, and on engines with the decode descriptor + (T6000, T8140) also decodes those profiles. To compile this driver as a module, choose M here: the module will be called apple-prores. config VIDEO_APPLE_PRORES_KUNIT_TEST - tristate "KUnit tests for the Apple ProRes encoder" if !KUNIT_ALL_TESTS + tristate "KUnit tests for the Apple ProRes codec" if !KUNIT_ALL_TESTS depends on KUNIT && VIDEO_APPLE_PRORES default KUNIT_ALL_TESTS help Check the APRI firmware parser, quantisation tables, DC scale table, - and job descriptors. APRI fixtures are wholly synthetic and contain - no vendor initialization values. The parser cases cover the complete - container shape and every row constraint. No hardware is needed. + encode/decode job descriptors, ProRes frame parser and ring + accounting. APRI fixtures are wholly synthetic and contain no vendor + initialization values. No hardware is needed. diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 82abe6acce3f9b..f6757774a90aa0 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -333,7 +334,7 @@ static int apr_build_desc_common(const struct apr_frame *f, u8 *desc) is444 != apr_profile_is_444(f->profile)) return -EINVAL; if (!f->width || !f->height || f->width > U16_MAX || f->height > U16_MAX || - f->width & 1) + (!is444 && f->width & 1)) return -EINVAL; min_luma = f->width * (deep ? 2 : 1); min_chroma = min_luma * (is444 ? 2 : 1); @@ -473,6 +474,205 @@ int apr_build_desc_v0(const struct apr_frame *f, u8 *desc) } EXPORT_SYMBOL_IF_KUNIT(apr_build_desc_v0); +/* Non-RAW decode descriptor version 0 (T6000 and T8140). */ +#define DD_COMMAND 0x000 +#define DD_COMMAND_BFF BIT(14) +#define DD_COMMAND_IRQ BIT(12) +#define DD_COMMAND_COLOR (2 << 8) +#define DD_COMMAND_CHROMA_422 (2 << 2) +#define DD_COMMAND_CHROMA_444 (3 << 2) +#define DD_COMMAND_DEPTH_16 3 +#define DD_COMMAND_EXT 0x004 +#define DD_INPUT 0x008 +#define DD_INPUT_X 0x010 +#define DD_INPUT_Y 0x012 +#define DD_INPUT_WIDTH 0x014 +#define DD_INPUT_HEIGHT 0x016 +#define DD_OUTPUT_X 0x018 +#define DD_OUTPUT_Y 0x01a +#define DD_OUTPUT_WIDTH 0x01c +#define DD_OUTPUT_HEIGHT 0x01e +#define DD_LUMA_STRIDE 0x020 +#define DD_CHROMA_STRIDE 0x022 +#define DD_ALPHA_STRIDE 0x024 +#define DD_LUMA 0x028 +#define DD_LUMA_METADATA 0x030 +#define DD_CHROMA 0x038 +#define DD_CHROMA_METADATA 0x040 +#define DD_ALPHA 0x048 +#define DD_ALPHA_METADATA 0x050 +#define DD_CRC_CONTROL 0x090 + +int apr_build_decode_desc(const struct apr_decode_frame *f, u8 *desc) +{ + bool is444 = apr_input_is_444(f->output); + bool deep = f->output == APR_INPUT_422_16 || + f->output == APR_INPUT_444_16; + u32 min_luma, min_chroma, command; + + if ((unsigned int)f->output > APR_INPUT_444_16 || !f->width || + !f->height || f->width > U16_MAX || f->height > U16_MAX || + (!is444 && f->width & 1)) + return -EINVAL; + min_luma = f->width * (deep ? 2 : 1); + min_chroma = min_luma * (is444 ? 2 : 1); + if (f->luma_stride % 64 || f->chroma_stride % 64 || + f->luma_stride < min_luma || f->chroma_stride < min_chroma || + f->luma_stride / 64 > U16_MAX || + f->chroma_stride / 64 > U16_MAX || !f->input || !f->luma || + !f->chroma) + return -EINVAL; + + memset(desc, 0, APR_DECODE_DESC_BYTES); + command = (u32)f->job_id << 16 | DD_COMMAND_IRQ | DD_COMMAND_COLOR | + (is444 ? DD_COMMAND_CHROMA_444 : DD_COMMAND_CHROMA_422); + if (deep) + command |= DD_COMMAND_DEPTH_16; + if (f->bottom_field_first) + command |= DD_COMMAND_BFF; + put_unaligned_le32(command, desc + DD_COMMAND); + put_unaligned_le32(0, desc + DD_COMMAND_EXT); + put_unaligned_le64(f->input, desc + DD_INPUT); + put_unaligned_le16(0, desc + DD_INPUT_X); + put_unaligned_le16(0, desc + DD_INPUT_Y); + put_unaligned_le16(f->width, desc + DD_INPUT_WIDTH); + put_unaligned_le16(f->height, desc + DD_INPUT_HEIGHT); + put_unaligned_le16(0, desc + DD_OUTPUT_X); + put_unaligned_le16(0, desc + DD_OUTPUT_Y); + put_unaligned_le16(f->width, desc + DD_OUTPUT_WIDTH); + put_unaligned_le16(f->height, desc + DD_OUTPUT_HEIGHT); + put_unaligned_le16(f->luma_stride / 64, desc + DD_LUMA_STRIDE); + put_unaligned_le16(f->chroma_stride / 64, desc + DD_CHROMA_STRIDE); + put_unaligned_le16(0, desc + DD_ALPHA_STRIDE); + put_unaligned_le64(f->luma, desc + DD_LUMA); + put_unaligned_le64(0, desc + DD_LUMA_METADATA); + put_unaligned_le64(f->chroma, desc + DD_CHROMA); + put_unaligned_le64(0, desc + DD_CHROMA_METADATA); + put_unaligned_le64(0, desc + DD_ALPHA); + put_unaligned_le64(0, desc + DD_ALPHA_METADATA); + put_unaligned_le32(3, desc + DD_CRC_CONTROL); + return 0; +} +EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); + +static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, + u32 height, bool interlaced, u32 max_slices, + u32 *picture_size, u32 *slices) +{ + u32 header, size, table_bytes, data_bytes = 0, min_size; + u32 log2_slice, field_height, i; + + if (bytes < 8) + return -EINVAL; + header = data[0] >> 3; + size = get_unaligned_be32(data + 1); + log2_slice = data[7] >> 4; + if (header < 8 || header > size || size > bytes || log2_slice > 3 || + (data[7] & 0xf)) + return -EINVAL; + field_height = interlaced ? DIV_ROUND_UP(height, 2) : height; + *slices = apr_slice_count(width, field_height, log2_slice); + if (*slices < 9 || *slices > max_slices || + check_mul_overflow(*slices, 2U, &table_bytes) || + check_add_overflow(header, table_bytes, &min_size) || + min_size > size) + return -EINVAL; + for (i = 0; i < *slices; i++) { + u32 slice = get_unaligned_be16(data + header + 2 * i); + + if (slice < 6 || check_add_overflow(data_bytes, slice, &data_bytes)) + return -EINVAL; + } + if (data_bytes > size - min_size) + return -EINVAL; + *picture_size = size; + return 0; +} + +int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info) +{ + const u8 *header; + u32 frame_size, header_size, min_header, offset; + u64 pixels; + unsigned int i; + int ret; + + if (!data || !info || bytes < 28 || bytes > U32_MAX) + return -EINVAL; + frame_size = get_unaligned_be32(data); + if (frame_size != bytes || memcmp(data + 4, "icpf", 4)) + return -EINVAL; + header = data + 8; + header_size = get_unaligned_be16(header); + if (header_size < 20 || header_size > frame_size - 8 || + get_unaligned_be16(header + 2) > 1) + return -EINVAL; + min_header = 20 + 64 * hweight8(header[19] & 3); + if (header_size < min_header) + return -EINVAL; + + memset(info, 0, sizeof(*info)); + info->frame_size = frame_size; + info->width = get_unaligned_be16(header + 8); + info->height = get_unaligned_be16(header + 10); + info->chroma = header[12] >> 6; + info->frame_type = (header[12] >> 2) & 3; + info->alpha = header[17] & 0xf; + info->primaries = header[14]; + info->transfer = header[15]; + info->matrix = header[16]; + pixels = (u64)info->width * info->height; + if (info->width < 16 || info->height < 16 || pixels > 0x10000000 || + (info->chroma != 2 && info->chroma != 3) || info->frame_type > 2 || + (info->chroma == 2 && info->width & 1) || info->alpha > 2 || + (info->alpha && info->chroma != 3)) + return -EINVAL; + info->pictures = info->frame_type ? 2 : 1; + offset = 8 + header_size; + for (i = 0; i < info->pictures; i++) { + if (offset > frame_size) + return -EINVAL; + info->picture_offset[i] = offset; + ret = apr_parse_picture(data + offset, frame_size - offset, + info->width, info->height, + info->pictures == 2, + i ? 16384 : 262144, + &info->picture_size[i], &info->slices[i]); + if (ret) + return ret; + if (check_add_overflow(offset, info->picture_size[i], &offset)) + return -EINVAL; + } + return offset == frame_size ? 0 : -EINVAL; +} +EXPORT_SYMBOL_IF_KUNIT(apr_parse_frame); + +u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes) +{ + u32 offset = ptr & APR_RING_OFFSET_MASK; + u32 generation = ptr & APR_RING_GENERATION; + + offset += bytes; + if (offset >= ring_bytes) { + offset -= ring_bytes; + generation ^= APR_RING_GENERATION; + } + return generation | offset; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_advance); + +void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, + u32 desc_bytes) +{ + u32 offset = ptr & APR_RING_OFFSET_MASK; + u32 first = min(desc_bytes, ring_bytes - offset); + + memcpy(ring + offset, desc, first); + if (first != desc_bytes) + memcpy(ring, desc + first, desc_bytes - first); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_write); + /* * A finished frame starts with its big-endian length, which counts the whole * frame, followed by the 'icpf' frame identifier. diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index f75dd6d5b3d2a5..5b31bef6a2802d 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1,11 +1,12 @@ // SPDX-License-Identifier: GPL-2.0-only /* - * Apple ProRes (APR) V4L2 memory-to-memory encoder. + * Apple ProRes (APR) V4L2 memory-to-memory codec. * * One job runs at a time. The driver writes a descriptor into a 128 KiB DMA * ring, advances the producer head and waits for the completion interrupt. - * Raw frames come in on the OUTPUT queue as semi-planar 4:2:2 or 4:4:4 (8 or - * 16 bits per sample) and complete ProRes frames go out on CAPTURE. + * The encoder consumes semi-planar 4:2:2 or 4:4:4 frames and produces one + * complete ProRes frame per buffer. The decoder exposes a second stateful + * node with the queue directions reversed and linear color output. * * Based on Acelogic's J700 ProRes diagnostic, which first encoded on this * engine under Linux, and on the m1n1 proxyclient ProRes experiment (MIT). @@ -44,8 +45,9 @@ #define APR_NAME "apple-prores" #define APR_MIN_W 16 #define APR_MIN_H 16 -#define APR_MAX_W 8192 -#define APR_MAX_H 8192 +#define APR_MAX_W U16_MAX +#define APR_MAX_H U16_MAX +#define APR_MAX_PIXELS 0x10000000 #define APR_TIMEOUT_MS 1000 #define APR_POLL_MS 4 #define APR_AUTOSUSPEND_MS 500 @@ -974,6 +976,7 @@ static_assert(ARRAY_SIZE(apr_t8142_wrapper_tunables) == APRI_T8142_WRAPPER_COUNT /* Selected only by the DT compatible, before mapping any resources. */ struct apr_variant { int (*build_desc)(const struct apr_frame *f, u8 *desc); + bool has_decoder; struct apr_stats_regs stats[2]; const struct apr_tunable *engine_tunables; size_t num_engine_tunables; @@ -997,6 +1000,7 @@ struct apr_variant { static const struct apr_variant apr_t8140 = { .build_desc = apr_build_desc, + .has_decoder = true, .stats = { { APR_REG_STATS0_LO, APR_REG_STATS0_HI, APR_REG_STATS0_SIZE }, { APR_REG_STATS1_LO, APR_REG_STATS1_HI, APR_REG_STATS1_SIZE }, @@ -1009,11 +1013,12 @@ static const struct apr_variant apr_t8140 = { .num_regs = 2, .num_irqs = 2, .ring_bytes = APR_RING_BYTES, - .desc_bytes = APR_DESC_BYTES, + .desc_bytes = APR_ENCODE_DESC_BYTES, }; static const struct apr_variant apr_t6000 = { .build_desc = apr_build_desc_v0, + .has_decoder = true, .stats = { { 0x278, 0x27c, 0x280 }, { 0x358, 0x35c, 0x360 } }, .engine_tunables = apr_t6000_engine_tunables, .num_engine_tunables = ARRAY_SIZE(apr_t6000_engine_tunables), @@ -1021,7 +1026,7 @@ static const struct apr_variant apr_t6000 = { .num_regs = 2, .num_irqs = 1, .ring_bytes = APR_RING_BYTES, - .desc_bytes = APR_DESC_BYTES, + .desc_bytes = APR_ENCODE_DESC_BYTES, }; static const struct apr_variant apr_t6041 = { @@ -1125,7 +1130,8 @@ struct apr_dev { int irq[2]; struct v4l2_device v4l2_dev; - struct video_device vdev; + struct video_device enc_vdev; + struct video_device dec_vdev; struct v4l2_m2m_dev *m2m_dev; struct mutex vdev_lock; /* serialises ioctls and queue state */ @@ -1154,6 +1160,10 @@ struct apr_ctx { struct v4l2_pix_format_mplane src_fmt; struct v4l2_pix_format_mplane dst_fmt; const struct apr_fmt *raw; + bool decode; + bool source_valid; + bool decode_444; + bool cancelled; enum apr_profile stream_profile; /* fixed while OUTPUT streams */ u32 sequence; }; @@ -1314,6 +1324,57 @@ static void apr_fill_frame(struct apr_ctx *ctx, struct vb2_v4l2_buffer *src, }; } +static int apr_parse_src(struct vb2_v4l2_buffer *src, + struct apr_prores_info *info) +{ + struct vb2_buffer *vb = &src->vb2_buf; + u32 payload = vb2_get_plane_payload(vb, 0); + u32 offset = vb->planes[0].data_offset; + u8 *data = vb2_plane_vaddr(vb, 0); + + if (!data || offset > payload) + return -EINVAL; + return apr_parse_frame(data + offset, payload - offset, info); +} + +static int apr_fill_decode_frame(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *src, + struct vb2_v4l2_buffer *dst, + struct apr_decode_frame *f) +{ + const struct v4l2_pix_format_mplane *d = &ctx->dst_fmt; + struct apr_prores_info info; + dma_addr_t output; + u32 luma_stride; + int ret; + + ret = apr_parse_src(src, &info); + if (ret) + return ret; + /* The non-RAW descriptor accepts one picture; field repacking is later. */ + if (info.pictures != 1) + return -EOPNOTSUPP; + if (info.width != d->width || info.height != d->height || + info.chroma == 3 != ctx->raw->is444) + return -EINVAL; + + luma_stride = d->plane_fmt[0].bytesperline; + output = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0); + *f = (struct apr_decode_frame){ + .width = info.width, + .height = info.height, + .output = ctx->raw->input, + .luma_stride = luma_stride, + .chroma_stride = luma_stride * (ctx->raw->is444 ? 2 : 1), + .input = vb2_dma_contig_plane_dma_addr(&src->vb2_buf, 0) + + src->vb2_buf.planes[0].data_offset, + .luma = output, + .chroma = output + (u64)luma_stride * d->height, + .job_id = ctx->sequence, + }; + return 0; +} + static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) { struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; @@ -1325,7 +1386,7 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) if (WARN_ON(!src || !dst)) goto out; - if (!err) { + if (!err && !ctx->decode) { u8 *out = vb2_plane_vaddr(&dst->vb2_buf, 0); /* The engine wrote the frame through the DART; see it now. */ @@ -1335,6 +1396,11 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) if (err) dev_err_ratelimited(apr->dev, "engine returned no frame\n"); } + if (!err && ctx->decode) { + /* The ACK and tail read complete before output ownership returns. */ + dma_rmb(); + bytes = ctx->dst_fmt.plane_fmt[0].sizeimage; + } vb2_set_plane_payload(&dst->vb2_buf, 0, err ? 0 : bytes); v4l2_m2m_buf_copy_metadata(src, dst); dst->sequence = ctx->sequence++; @@ -1361,23 +1427,37 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) static struct apr_ctx *apr_take_done(struct apr_dev *apr, int *err) { struct apr_ctx *ctx = apr->active; - u32 status, tail; + u32 status, tail, st0, st1, st2; + u32 detail[6]; if (!ctx) return NULL; status = apr_read(apr, APR_REG_IRQ_STATUS); - if (!status) + if (!(status & (APR_IRQ_DONE | APR_IRQ_ERROR))) return NULL; + st0 = apr_read(apr, APR_REG_ST0); + st1 = apr_read(apr, APR_REG_ST1); + st2 = apr_read(apr, APR_REG_ST2); + detail[0] = apr_read(apr, APR_REG_DETAIL0); + detail[1] = apr_read(apr, APR_REG_DETAIL1_LO); + detail[2] = apr_read(apr, APR_REG_DETAIL1_HI); + detail[3] = apr_read(apr, APR_REG_DETAIL2_LO); + detail[4] = apr_read(apr, APR_REG_DETAIL2_HI); + detail[5] = apr_read(apr, APR_REG_DETAIL3); apr_write(apr, APR_REG_IRQ_STATUS, status); + /* The tail read flushes the posted W1C before buffers are released. */ tail = apr_read(apr, APR_REG_RING_TAIL) & APR_RING_PTR_MASK; *err = 0; - if (status != APR_IRQ_DONE || tail != apr->head) { + if (!(status & APR_IRQ_DONE) || status & APR_IRQ_ERROR || tail != apr->head) { dev_err_ratelimited(apr->dev, - "job failed: status %#x tail %#x head %#x st %#x/%#x\n", - status, tail, apr->head, - apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); + "job failed: irq %#x tail %#x head %#x st %#x/%#x/%#x detail %#x/%#x/%#x/%#x/%#x/%#x\n", + status, tail, apr->head, st0, st1, st2, + detail[0], detail[1], detail[2], detail[3], + detail[4], detail[5]); *err = -EIO; } + if (ctx->cancelled) + *err = -ECANCELED; apr->active = NULL; return ctx; } @@ -1452,6 +1532,9 @@ static void apr_device_run(void *priv) struct apr_dev *apr = ctx->apr; struct vb2_v4l2_buffer *src, *dst; struct apr_frame f; + struct apr_decode_frame decode; + u8 desc[APR_ENCODE_DESC_BYTES]; + u32 desc_bytes; unsigned long flags; void *out; int ret; @@ -1465,14 +1548,24 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, ret); return; } - apr_fill_frame(ctx, src, dst, &f); - /* Mark the output invalid so a frame the engine never wrote is caught. */ - out = vb2_plane_vaddr(&dst->vb2_buf, 0); - if (!out) { - apr_finish_job(apr, ctx, -EINVAL); + if (ctx->decode) { + ret = apr_fill_decode_frame(ctx, src, dst, &decode); + desc_bytes = APR_DECODE_DESC_BYTES; + } else { + apr_fill_frame(ctx, src, dst, &f); + ret = 0; + desc_bytes = apr->variant->desc_bytes; + /* Mark output invalid so a frame the engine never wrote is caught. */ + out = vb2_plane_vaddr(&dst->vb2_buf, 0); + if (!out) + ret = -EINVAL; + else + memset(out, 0, 8); + } + if (ret) { + apr_finish_job(apr, ctx, ret); return; } - memset(out, 0, 8); spin_lock_irqsave(&apr->hw_lock, flags); if (apr->broken) { @@ -1480,21 +1573,21 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, -EIO); return; } - /* - * The engine's ring wrap protocol is not known, so start again at the - * beginning of the ring instead of wrapping. The engine is idle here. - */ - if (!apr->ring_ready || - apr->head + apr->variant->desc_bytes > apr->variant->ring_bytes) + if (!apr->ring_ready) apr_hw_init(apr); - ret = apr->variant->build_desc(&f, apr->ring + apr->head); + ret = ctx->decode ? apr_build_decode_desc(&decode, desc) : + apr->variant->build_desc(&f, desc); if (ret) { spin_unlock_irqrestore(&apr->hw_lock, flags); apr_finish_job(apr, ctx, ret); return; } - apr->head += apr->variant->desc_bytes; + apr_ring_write(apr->ring, apr->variant->ring_bytes, apr->head, + desc, desc_bytes); + apr->head = apr_ring_advance(apr->head, desc_bytes, + apr->variant->ring_bytes); apr->active = ctx; + ctx->cancelled = false; apr->started = jiffies; /* Descriptor and buffers must be visible before the head moves. */ dma_wmb(); @@ -1503,8 +1596,39 @@ static void apr_device_run(void *priv) schedule_delayed_work(&apr->watchdog, msecs_to_jiffies(APR_POLL_MS)); } +static int apr_job_ready(void *priv) +{ + struct apr_ctx *ctx = priv; + struct vb2_v4l2_buffer *src; + struct apr_prores_info info; + + if (!ctx->decode) + return 1; + src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); + if (!src || apr_parse_src(src, &info)) + return 1; + return info.width == ctx->dst_fmt.width && + info.height == ctx->dst_fmt.height && + (info.chroma == 3) == ctx->raw->is444; +} + +static void apr_job_abort(void *priv) +{ + struct apr_ctx *ctx = priv; + struct apr_dev *apr = ctx->apr; + unsigned long flags; + + /* There is no decode- or encode-specific cancellation opcode. */ + spin_lock_irqsave(&apr->hw_lock, flags); + if (apr->active == ctx) + ctx->cancelled = true; + spin_unlock_irqrestore(&apr->hw_lock, flags); +} + static const struct v4l2_m2m_ops apr_m2m_ops = { .device_run = apr_device_run, + .job_ready = apr_job_ready, + .job_abort = apr_job_abort, }; /* ---- formats ----------------------------------------------------------- */ @@ -1526,12 +1650,22 @@ static const struct apr_fmt *apr_find_raw(u32 fourcc) */ static void apr_fill_raw(struct v4l2_pix_format_mplane *pix, const struct apr_fmt *fmt) { - u32 width = clamp_t(u32, ALIGN(pix->width, 2), APR_MIN_W, APR_MAX_W); + u32 width = clamp_t(u32, pix->width, APR_MIN_W, APR_MAX_W); u32 height = clamp_t(u32, pix->height, APR_MIN_H, APR_MAX_H); - u32 min_stride = ALIGN(width * fmt->bytes, 64); - u32 stride = ALIGN(pix->plane_fmt[0].bytesperline, 64); + u32 stride_align; + u32 min_stride; + u32 stride; u32 cstride; + if (!fmt->is444) + width = min_t(u32, ALIGN(width, 2), APR_MAX_W - 1); + if ((u64)width * height > APR_MAX_PIXELS) + height = APR_MAX_PIXELS / width; + /* An odd row count needs a 128-byte stride to align plane 1. */ + stride_align = height & 1 ? 128 : 64; + min_stride = ALIGN(width * fmt->bytes, stride_align); + stride = ALIGN(pix->plane_fmt[0].bytesperline, stride_align); + /* Accept padding up to one extra row width, as other drivers do. */ if (stride < min_stride || stride > 2 * min_stride) stride = min_stride; @@ -1566,25 +1700,62 @@ static void apr_fill_coded(struct v4l2_pix_format_mplane *dst, dst->plane_fmt[0].sizeimage = apr_coded_size(src->width, src->height, is444); } +static void apr_fill_decode_coded(struct v4l2_pix_format_mplane *pix) +{ + u32 size = pix->plane_fmt[0].sizeimage; + + pix->width = clamp_t(u32, pix->width, APR_MIN_W, APR_MAX_W); + pix->height = clamp_t(u32, pix->height, APR_MIN_H, APR_MAX_H); + if ((u64)pix->width * pix->height > APR_MAX_PIXELS) + pix->height = APR_MAX_PIXELS / pix->width; + pix->pixelformat = V4L2_PIX_FMT_PRORES; + pix->field = V4L2_FIELD_NONE; + pix->num_planes = 1; + pix->flags = 0; + memset(pix->reserved, 0, sizeof(pix->reserved)); + memset(pix->plane_fmt, 0, sizeof(pix->plane_fmt)); + pix->plane_fmt[0].sizeimage = clamp_t(u32, size, SZ_4K, SZ_256M); +} + static void apr_reset_fmts(struct apr_ctx *ctx) { - ctx->raw = &apr_raw_fmts[0]; + ctx->raw = ctx->decode ? &apr_raw_fmts[1] : &apr_raw_fmts[0]; memset(&ctx->src_fmt, 0, sizeof(ctx->src_fmt)); ctx->src_fmt.width = 1920; ctx->src_fmt.height = 1080; - apr_fill_raw(&ctx->src_fmt, ctx->raw); - apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); + if (ctx->decode) { + ctx->src_fmt.plane_fmt[0].sizeimage = + apr_coded_size(1920, 1080, false); + apr_fill_decode_coded(&ctx->src_fmt); + ctx->dst_fmt = ctx->src_fmt; + apr_fill_raw(&ctx->dst_fmt, ctx->raw); + } else { + apr_fill_raw(&ctx->src_fmt, ctx->raw); + apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); + } } static int apr_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + strscpy(cap->driver, APR_NAME, sizeof(cap->driver)); - strscpy(cap->card, "Apple ProRes encoder", sizeof(cap->card)); + strscpy(cap->card, ctx->decode ? "Apple ProRes decoder" : + "Apple ProRes encoder", sizeof(cap->card)); return 0; } static int apr_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + + if (ctx->decode) { + if (f->index) + return -EINVAL; + f->pixelformat = V4L2_PIX_FMT_PRORES; + f->flags = V4L2_FMT_FLAG_COMPRESSED; + return 0; + } if (f->index >= ARRAY_SIZE(apr_raw_fmts)) return -EINVAL; f->pixelformat = apr_raw_fmts[f->index].fourcc; @@ -1593,6 +1764,14 @@ static int apr_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc * static int apr_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); + + if (ctx->decode) { + if (f->index >= ARRAY_SIZE(apr_raw_fmts)) + return -EINVAL; + f->pixelformat = apr_raw_fmts[f->index].fourcc; + return 0; + } if (f->index) return -EINVAL; f->pixelformat = V4L2_PIX_FMT_PRORES; @@ -1603,12 +1782,15 @@ static int apr_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc * static int apr_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { + const struct apr_fmt *fmt = apr_find_raw(fs->pixel_format); + if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_PRORES && - !apr_find_raw(fs->pixel_format))) + !fmt)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; fs->stepwise = (struct v4l2_frmsize_stepwise){ - APR_MIN_W, APR_MAX_W, 2, APR_MIN_H, APR_MAX_H, 1, + APR_MIN_W, APR_MAX_W, fmt && !fmt->is444 ? 2 : 1, + APR_MIN_H, APR_MAX_H, 1, }; return 0; } @@ -1627,8 +1809,13 @@ static int apr_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) static int apr_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { + struct apr_ctx *ctx = apr_file_to_ctx(file); const struct apr_fmt *fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); + if (ctx->decode) { + apr_fill_decode_coded(&f->fmt.pix_mp); + return 0; + } apr_fill_raw(&f->fmt.pix_mp, fmt ?: &apr_raw_fmts[0]); return 0; } @@ -1637,7 +1824,17 @@ static int apr_try_fmt_out(struct file *file, void *priv, struct v4l2_format *f) static int apr_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { struct apr_ctx *ctx = apr_file_to_ctx(file); - + const struct apr_fmt *fmt; + + if (ctx->decode) { + fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); + if (!fmt || (ctx->source_valid && fmt->is444 != ctx->decode_444)) + fmt = &apr_raw_fmts[ctx->decode_444 ? 3 : 1]; + f->fmt.pix_mp.width = ctx->src_fmt.width; + f->fmt.pix_mp.height = ctx->src_fmt.height; + apr_fill_raw(&f->fmt.pix_mp, fmt); + return 0; + } apr_fill_coded(&f->fmt.pix_mp, &ctx->src_fmt, ctx->raw->is444); return 0; } @@ -1652,6 +1849,8 @@ static int apr_s_fmt_out(struct file *file, void *priv, struct v4l2_format *f) return -EBUSY; apr_try_fmt_out(file, priv, f); ctx->src_fmt = f->fmt.pix_mp; + if (ctx->decode) + return 0; ctx->raw = apr_find_raw(ctx->src_fmt.pixelformat); apr_fill_coded(&ctx->dst_fmt, &ctx->src_fmt, ctx->raw->is444); /* Keep the profile consistent with the chroma format. */ @@ -1670,6 +1869,8 @@ static int apr_s_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) return -EBUSY; apr_try_fmt_cap(file, priv, f); ctx->dst_fmt = f->fmt.pix_mp; + if (ctx->decode) + ctx->raw = apr_find_raw(ctx->dst_fmt.pixelformat); return 0; } @@ -1677,6 +1878,8 @@ static int apr_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subsc { if (sub->type == V4L2_EVENT_EOS) return v4l2_event_subscribe(fh, sub, 0, NULL); + if (sub->type == V4L2_EVENT_SOURCE_CHANGE) + return v4l2_src_change_event_subscribe(fh, sub); return v4l2_ctrl_subscribe_event(fh, sub); } @@ -1709,6 +1912,35 @@ static const struct v4l2_ioctl_ops apr_ioctl_ops = { .vidioc_unsubscribe_event = v4l2_event_unsubscribe, }; +static const struct v4l2_ioctl_ops apr_decoder_ioctl_ops = { + .vidioc_querycap = apr_querycap, + .vidioc_enum_fmt_vid_out = apr_enum_fmt_out, + .vidioc_enum_fmt_vid_cap = apr_enum_fmt_cap, + .vidioc_enum_framesizes = apr_enum_framesizes, + .vidioc_g_fmt_vid_out_mplane = apr_g_fmt_out, + .vidioc_g_fmt_vid_cap_mplane = apr_g_fmt_cap, + .vidioc_try_fmt_vid_out_mplane = apr_try_fmt_out, + .vidioc_try_fmt_vid_cap_mplane = apr_try_fmt_cap, + .vidioc_s_fmt_vid_out_mplane = apr_s_fmt_out, + .vidioc_s_fmt_vid_cap_mplane = apr_s_fmt_cap, + + .vidioc_reqbufs = v4l2_m2m_ioctl_reqbufs, + .vidioc_querybuf = v4l2_m2m_ioctl_querybuf, + .vidioc_qbuf = v4l2_m2m_ioctl_qbuf, + .vidioc_dqbuf = v4l2_m2m_ioctl_dqbuf, + .vidioc_prepare_buf = v4l2_m2m_ioctl_prepare_buf, + .vidioc_create_bufs = v4l2_m2m_ioctl_create_bufs, + .vidioc_expbuf = v4l2_m2m_ioctl_expbuf, + .vidioc_streamon = v4l2_m2m_ioctl_streamon, + .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, + + .vidioc_try_decoder_cmd = v4l2_m2m_ioctl_try_decoder_cmd, + .vidioc_decoder_cmd = v4l2_m2m_ioctl_decoder_cmd, + + .vidioc_subscribe_event = apr_subscribe_event, + .vidioc_unsubscribe_event = v4l2_event_unsubscribe, +}; + /* ---- queues ------------------------------------------------------------ */ static struct v4l2_pix_format_mplane *apr_q_fmt(struct apr_ctx *ctx, u32 type) @@ -1738,19 +1970,69 @@ static int apr_buf_prepare(struct vb2_buffer *vb) if (vb2_plane_size(vb, 0) < size) return -EINVAL; if (V4L2_TYPE_IS_OUTPUT(vb->type)) { - /* The engine always reads the whole padded surface. */ - vb2_set_plane_payload(vb, 0, size); + if (ctx->decode) { + u32 payload = vb2_get_plane_payload(vb, 0); + + if (payload < 28 || vb->planes[0].data_offset > payload) + return -EINVAL; + } else { + /* The encoder always reads the whole padded surface. */ + vb2_set_plane_payload(vb, 0, size); + } } else { vb2_set_plane_payload(vb, 0, 0); } return 0; } +static void apr_decode_source_change(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *vbuf) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_prores_info info; + bool changed; + unsigned int i; + + if (apr_parse_src(vbuf, &info)) + return; + changed = !ctx->source_valid || ctx->src_fmt.width != info.width || + ctx->src_fmt.height != info.height || + ctx->decode_444 != (info.chroma == 3); + if (!changed) + return; + ctx->source_valid = true; + ctx->decode_444 = info.chroma == 3; + ctx->src_fmt.width = info.width; + ctx->src_fmt.height = info.height; + if (!vb2_is_busy(v4l2_m2m_get_dst_vq(m2m))) { + for (i = 0; i < ARRAY_SIZE(apr_raw_fmts); i++) { + if (apr_raw_fmts[i].is444 == ctx->decode_444 && + apr_raw_fmts[i].bytes == ctx->raw->bytes) { + ctx->raw = &apr_raw_fmts[i]; + break; + } + } + ctx->dst_fmt.width = info.width; + ctx->dst_fmt.height = info.height; + apr_fill_raw(&ctx->dst_fmt, ctx->raw); + } + { + const struct v4l2_event event = { + .type = V4L2_EVENT_SOURCE_CHANGE, + .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, + }; + + v4l2_event_queue_fh(&ctx->fh, &event); + } +} + static void apr_buf_queue(struct vb2_buffer *vb) { struct apr_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb); + if (ctx->decode && V4L2_TYPE_IS_OUTPUT(vb->type)) + apr_decode_source_change(ctx, vbuf); if (!V4L2_TYPE_IS_OUTPUT(vb->type) && vb2_is_streaming(vb->vb2_queue) && v4l2_m2m_dst_buf_is_last(ctx->fh.m2m_ctx)) { @@ -1766,7 +2048,7 @@ static int apr_start_streaming(struct vb2_queue *q, unsigned int count) { struct apr_ctx *ctx = vb2_get_drv_priv(q); - if (V4L2_TYPE_IS_OUTPUT(q->type)) { + if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->decode) { if (ctx->raw->is444 != apr_profile_is_444(v4l2_ctrl_g_ctrl(ctx->profile))) { struct vb2_v4l2_buffer *vbuf; @@ -1796,7 +2078,7 @@ static void apr_stop_streaming(struct vb2_queue *q) v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); } v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, q); - if (V4L2_TYPE_IS_OUTPUT(q->type)) + if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->decode) v4l2_ctrl_grab(ctx->profile, false); if (V4L2_TYPE_IS_OUTPUT(q->type) && v4l2_m2m_has_stopped(ctx->fh.m2m_ctx)) { static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; @@ -1859,7 +2141,11 @@ static int apr_init_ctrls(struct apr_ctx *ctx) { struct v4l2_ctrl_handler *hdl = &ctx->hdl; - v4l2_ctrl_handler_init(hdl, 1); + v4l2_ctrl_handler_init(hdl, ctx->decode ? 0 : 1); + if (ctx->decode) { + ctx->fh.ctrl_handler = hdl; + return 0; + } /* The profile must match the raw format's chroma; checked at STREAMON. */ ctx->profile = v4l2_ctrl_new_std_menu(hdl, &apr_ctrl_ops, V4L2_CID_MPEG_VIDEO_PRORES_PROFILE, @@ -1885,6 +2171,7 @@ static int apr_open(struct file *file) if (!ctx) return -ENOMEM; ctx->apr = apr; + ctx->decode = video_devdata(file) == &apr->dec_vdev; apr_reset_fmts(ctx); v4l2_fh_init(&ctx->fh, video_devdata(file)); ret = apr_init_ctrls(ctx); @@ -2151,10 +2438,10 @@ static int apr_probe(struct platform_device *pdev) return dev_err_probe(dev, -EINVAL, "statistics area larger than %zu bytes\n", apr->stats_size); } - dev_info(dev, "ProRes encoder, id %#x\n", apr_read(apr, APR_REG_ID)); + dev_info(dev, "ProRes codec, id %#x\n", apr_read(apr, APR_REG_ID)); pm_runtime_put_autosuspend(dev); - vdev = &apr->vdev; + vdev = &apr->enc_vdev; strscpy(vdev->name, APR_NAME, sizeof(vdev->name)); vdev->fops = &apr_fops; vdev->ioctl_ops = &apr_ioctl_ops; @@ -2164,14 +2451,33 @@ static int apr_probe(struct platform_device *pdev) vdev->vfl_dir = VFL_DIR_M2M; vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; video_set_drvdata(vdev, apr); - return video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + ret = video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + if (ret || !apr->variant->has_decoder) + return ret; + + vdev = &apr->dec_vdev; + strscpy(vdev->name, APR_NAME "-decode", sizeof(vdev->name)); + vdev->fops = &apr_fops; + vdev->ioctl_ops = &apr_decoder_ioctl_ops; + vdev->release = video_device_release_empty; + vdev->lock = &apr->vdev_lock; + vdev->v4l2_dev = &apr->v4l2_dev; + vdev->vfl_dir = VFL_DIR_M2M; + vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; + video_set_drvdata(vdev, apr); + ret = video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); + if (ret) + video_unregister_device(&apr->enc_vdev); + return ret; } static void apr_remove(struct platform_device *pdev) { struct apr_dev *apr = platform_get_drvdata(pdev); - video_unregister_device(&apr->vdev); + if (apr->variant->has_decoder) + video_unregister_device(&apr->dec_vdev); + video_unregister_device(&apr->enc_vdev); } static const struct of_device_id apr_of_match[] = { @@ -2196,7 +2502,7 @@ static struct platform_driver apr_driver = { }; module_platform_driver(apr_driver); -MODULE_DESCRIPTION("Apple ProRes encoder"); +MODULE_DESCRIPTION("Apple ProRes codec"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE(APRI_T6041_FIRMWARE_NAME); MODULE_FIRMWARE(APRI_T6050_FIRMWARE_NAME); diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index 7e6fdd60199f8f..484bbc6a3a6da1 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -605,6 +605,152 @@ static void apr_test_apri_row_rejects(struct kunit *test) apr_test_apri_rows_reject(test, APRI_SYSTEM_BLOCK, 0, 8, 0x100); } +static void apr_test_decode_desc(struct kunit *test) +{ + struct apr_decode_frame f = { + .width = 320, .height = 240, .output = APR_INPUT_422_16, + .luma_stride = 640, .chroma_stride = 640, + .input = 0x10000100000ULL, .luma = 0x10000200000ULL, + .chroma = 0x10000300000ULL, .job_id = 0x1234, + }; + u8 *d = kunit_kmalloc(test, APR_DECODE_DESC_BYTES + 1, GFP_KERNEL); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, d); + memset(d, 0xa5, APR_DECODE_DESC_BYTES + 1); + KUNIT_ASSERT_EQ(test, apr_build_decode_desc(&f, d), 0); + KUNIT_EXPECT_EQ(test, d[APR_DECODE_DESC_BYTES], 0xa5); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d), 0x1234120b); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d + 4), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 8), f.input); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x14), 320); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x16), 240); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x1c), 320); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x1e), 240); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x20), 10); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x22), 10); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x28), f.luma); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x30), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x38), f.chroma); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x40), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(d + 0x48), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d + 0x90), 3); + for (i = 0x94; i < APR_DECODE_DESC_BYTES; i++) + KUNIT_EXPECT_EQ_MSG(test, d[i], 0, "reserved byte %#x", i); + + f.output = APR_INPUT_444_16; + f.chroma_stride = 1280; + f.bottom_field_first = true; + KUNIT_ASSERT_EQ(test, apr_build_decode_desc(&f, d), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(d), 0x1234520f); + KUNIT_EXPECT_EQ(test, get_unaligned_le16(d + 0x22), 20); + f.luma_stride = 600; + KUNIT_EXPECT_EQ(test, apr_build_decode_desc(&f, d), -EINVAL); +} + +static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes) +{ + u32 slices = interlaced ? 24 : 45; + u32 picture_size = 8 + 2 * slices + 6 * slices; + u32 pictures = interlaced ? 2 : 1; + u32 frame_size = 28 + pictures * picture_size; + u8 *frame = kunit_kzalloc(test, frame_size, GFP_KERNEL); + u32 offset = 28; + unsigned int i, p; + + if (!frame) + return NULL; + put_unaligned_be32(frame_size, frame); + memcpy(frame + 4, "icpf", 4); + put_unaligned_be16(20, frame + 8); + put_unaligned_be16(0, frame + 10); + memcpy(frame + 12, "kunt", 4); + put_unaligned_be16(320, frame + 16); + put_unaligned_be16(240, frame + 18); + frame[20] = 2 << 6 | (interlaced ? 1 << 2 : 0); + frame[22] = 1; + frame[23] = 1; + frame[24] = 1; + for (p = 0; p < pictures; p++) { + u8 *picture = frame + offset; + + picture[0] = 8 << 3; + put_unaligned_be32(picture_size, picture + 1); + put_unaligned_be16(slices, picture + 5); + picture[7] = 3 << 4; + for (i = 0; i < slices; i++) + put_unaligned_be16(6, picture + 8 + 2 * i); + offset += picture_size; + } + *bytes = frame_size; + return frame; +} + +static void apr_test_parse_frame(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream(test, false, &bytes); + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.frame_size, (u32)bytes); + KUNIT_EXPECT_EQ(test, info.width, 320U); + KUNIT_EXPECT_EQ(test, info.height, 240U); + KUNIT_EXPECT_EQ(test, info.chroma, (u8)2); + KUNIT_EXPECT_EQ(test, info.pictures, (u8)1); + KUNIT_EXPECT_EQ(test, info.slices[0], 45U); + KUNIT_EXPECT_EQ(test, info.picture_offset[0], 28U); + + put_unaligned_be32(bytes - 1, frame); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be32(bytes, frame); + frame[4] = 'x'; + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); +} + +static void apr_test_parse_interlaced(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream(test, true, &bytes); + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.frame_type, (u8)1); + KUNIT_EXPECT_EQ(test, info.pictures, (u8)2); + KUNIT_EXPECT_EQ(test, info.slices[0], 24U); + KUNIT_EXPECT_EQ(test, info.slices[1], 24U); + KUNIT_EXPECT_EQ(test, info.picture_offset[1], + info.picture_offset[0] + info.picture_size[0]); +} + +static void apr_test_ring_accounting(struct kunit *test) +{ + u8 *ring = kunit_kzalloc(test, APR_RING_BYTES, GFP_KERNEL); + u8 *desc = kunit_kmalloc(test, APR_ENCODE_DESC_BYTES, GFP_KERNEL); + u32 ptr = APR_RING_BYTES - 0x100; + u32 next; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, ring); + KUNIT_ASSERT_NOT_NULL(test, desc); + next = apr_ring_advance(0, APR_DECODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x100U); + next = apr_ring_advance(0x100, APR_ENCODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x280U); + next = apr_ring_advance(ptr, APR_ENCODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, APR_RING_GENERATION | 0x80U); + next = apr_ring_advance(APR_RING_GENERATION | APR_RING_BYTES - 0x80, + APR_DECODE_DESC_BYTES, APR_RING_BYTES); + KUNIT_EXPECT_EQ(test, next, 0x80U); + for (i = 0; i < APR_ENCODE_DESC_BYTES; i++) + desc[i] = i; + apr_ring_write(ring, APR_RING_BYTES, ptr, desc, APR_ENCODE_DESC_BYTES); + KUNIT_EXPECT_MEMEQ(test, ring + ptr, desc, 0x100); + KUNIT_EXPECT_MEMEQ(test, ring, desc + 0x100, 0x80); +} + static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_qmat_regs), KUNIT_CASE(apr_test_dc_scale), @@ -624,6 +770,10 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_apri_header_rejects), KUNIT_CASE(apr_test_apri_shape_rejects), KUNIT_CASE(apr_test_apri_row_rejects), + KUNIT_CASE(apr_test_decode_desc), + KUNIT_CASE(apr_test_parse_frame), + KUNIT_CASE(apr_test_parse_interlaced), + KUNIT_CASE(apr_test_ring_accounting), {} }; @@ -633,6 +783,6 @@ static struct kunit_suite apr_test_suite = { }; kunit_test_suite(apr_test_suite); -MODULE_DESCRIPTION("KUnit tests for the Apple ProRes encoder"); +MODULE_DESCRIPTION("KUnit tests for the Apple ProRes codec"); MODULE_LICENSE("GPL"); MODULE_IMPORT_NS("EXPORTED_FOR_KUNIT_TESTING"); diff --git a/drivers/media/platform/apple/prores/apple-prores.h b/drivers/media/platform/apple/prores/apple-prores.h index 67bf19c93370cd..60a99979db4ce1 100644 --- a/drivers/media/platform/apple/prores/apple-prores.h +++ b/drivers/media/platform/apple/prores/apple-prores.h @@ -1,11 +1,11 @@ /* SPDX-License-Identifier: GPL-2.0-only */ /* - * Apple ProRes (APR) encoder: register map and job descriptor. + * Apple ProRes (APR) codec: register map and job descriptors. * - * The APR is a register-driven engine with no firmware. Jobs are fixed-size - * descriptors placed in a DMA ring; the driver installs the ring, advances a - * producer head and the engine reports completion through a status register - * and a consumer tail. + * The APR is a register-driven engine with no firmware. Jobs are typed, + * variable-size descriptors placed in a DMA ring; the driver installs the + * ring, advances a producer head and the engine reports completion through a + * status register and a consumer tail. * * Register names and descriptor fields follow the m1n1 proxyclient ProRes * experiment (MIT), proxyclient/m1n1/hw/prores.py and @@ -29,12 +29,21 @@ #define APR_IRQ_ERROR BIT(1) #define APR_REG_ST0 0x0014 #define APR_REG_ST1 0x0018 +#define APR_REG_ST2 0x001c +#define APR_REG_DETAIL0 0x003c +#define APR_REG_DETAIL1_LO 0x0040 +#define APR_REG_DETAIL1_HI 0x0044 +#define APR_REG_DETAIL2_LO 0x0048 +#define APR_REG_DETAIL2_HI 0x0050 +#define APR_REG_DETAIL3 0x0054 #define APR_REG_RING_SIZE 0x0100 #define APR_REG_RING_LO 0x0104 #define APR_REG_RING_HI 0x0108 #define APR_REG_RING_HEAD 0x010c #define APR_REG_RING_TAIL 0x0110 -#define APR_RING_PTR_MASK GENMASK(23, 0) +#define APR_RING_OFFSET_MASK GENMASK(23, 0) +#define APR_RING_GENERATION BIT(24) +#define APR_RING_PTR_MASK GENMASK(24, 0) /* One statistics area, given to two consumers; their capacity reads back. */ #define APR_REG_STATS0_LO 0x038c #define APR_REG_STATS0_HI 0x0390 @@ -51,7 +60,10 @@ #define APR_DC_SCALE_ENTRIES 112 #define APR_RING_BYTES SZ_128K -#define APR_DESC_BYTES 0x180 +#define APR_ENCODE_DESC_BYTES 0x180 +#define APR_DECODE_DESC_BYTES 0x100 +/* Kept for the encode descriptor tests and callers. */ +#define APR_DESC_BYTES APR_ENCODE_DESC_BYTES #define APRI_T6041_FIRMWARE_NAME "apple/prores-t6041-init.bin" #define APRI_T6041_FIRMWARE_SIZE 2728 @@ -158,6 +170,35 @@ struct apr_frame { u8 matrix; }; +struct apr_decode_frame { + u32 width; + u32 height; + enum apr_input output; + u32 luma_stride; /* bytes, multiple of 64 */ + u32 chroma_stride; /* bytes, multiple of 64 */ + u64 input; + u64 luma; + u64 chroma; + u16 job_id; + bool bottom_field_first; +}; + +struct apr_prores_info { + u32 frame_size; + u32 width; + u32 height; + u32 slices[2]; + u32 picture_offset[2]; + u32 picture_size[2]; + u8 pictures; + u8 chroma; + u8 frame_type; + u8 alpha; + u8 primaries; + u8 transfer; + u8 matrix; +}; + /* Matrices are 8x8 in raster order, as carried in the ProRes frame header. */ extern const u8 *const apr_qmat_luma[APR_QTABLES]; extern const u8 *const apr_qmat_chroma[APR_QTABLES]; @@ -172,6 +213,8 @@ void apr_frame_budget(enum apr_profile profile, u32 width, u32 height, u32 apr_slice_count(u32 width, u32 height, u32 log2_slice); int apr_build_desc(const struct apr_frame *f, u8 *desc); int apr_build_desc_v0(const struct apr_frame *f, u8 *desc); +int apr_build_decode_desc(const struct apr_decode_frame *f, u8 *desc); +int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info); int apr_check_output(const u8 *out, size_t capacity, u32 *frame_bytes); extern const struct apri_layout apri_t6041; extern const struct apri_layout apri_t6050; @@ -185,5 +228,8 @@ static inline int apr_parse_t6041_init(const u8 *data, size_t size, { return apr_parse_init(&apri_t6041, data, size, init); } +u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes); +void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, + u32 desc_bytes); #endif From 3a4ea6cab78fbc0434c0147853ded89fa0d5b66f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:41:01 +1100 Subject: [PATCH 1342/1514] media: apple: prores: give every APR engine a decoder node Apple lists each ProRes engine in its SoCs as a ProRes encode and decode engine, and the decode descriptor runs on the same ring as the encoder's. The decoder node was registered only on the T6000 and T8140 variants. Register it for every compatible the driver binds (T6041 and T6050 as well) and drop the per-variant flag. Signed-off-by: Ryan Murray --- .../media/platform/apple/prores/apple-prores-drv.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 5b31bef6a2802d..c92b7257fd5020 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -976,7 +976,6 @@ static_assert(ARRAY_SIZE(apr_t8142_wrapper_tunables) == APRI_T8142_WRAPPER_COUNT /* Selected only by the DT compatible, before mapping any resources. */ struct apr_variant { int (*build_desc)(const struct apr_frame *f, u8 *desc); - bool has_decoder; struct apr_stats_regs stats[2]; const struct apr_tunable *engine_tunables; size_t num_engine_tunables; @@ -1000,7 +999,6 @@ struct apr_variant { static const struct apr_variant apr_t8140 = { .build_desc = apr_build_desc, - .has_decoder = true, .stats = { { APR_REG_STATS0_LO, APR_REG_STATS0_HI, APR_REG_STATS0_SIZE }, { APR_REG_STATS1_LO, APR_REG_STATS1_HI, APR_REG_STATS1_SIZE }, @@ -1018,7 +1016,6 @@ static const struct apr_variant apr_t8140 = { static const struct apr_variant apr_t6000 = { .build_desc = apr_build_desc_v0, - .has_decoder = true, .stats = { { 0x278, 0x27c, 0x280 }, { 0x358, 0x35c, 0x360 } }, .engine_tunables = apr_t6000_engine_tunables, .num_engine_tunables = ARRAY_SIZE(apr_t6000_engine_tunables), @@ -2452,9 +2449,13 @@ static int apr_probe(struct platform_device *pdev) vdev->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING; video_set_drvdata(vdev, apr); ret = video_register_device(vdev, VFL_TYPE_VIDEO, APPLE_M2M_VIDEO_NR); - if (ret || !apr->variant->has_decoder) + if (ret) return ret; + /* + * Every APR engine is a ProRes encode and decode engine (the decode + * descriptor shares the encoder's ring), so each one gets a decoder node. + */ vdev = &apr->dec_vdev; strscpy(vdev->name, APR_NAME "-decode", sizeof(vdev->name)); vdev->fops = &apr_fops; @@ -2475,8 +2476,7 @@ static void apr_remove(struct platform_device *pdev) { struct apr_dev *apr = platform_get_drvdata(pdev); - if (apr->variant->has_decoder) - video_unregister_device(&apr->dec_vdev); + video_unregister_device(&apr->dec_vdev); video_unregister_device(&apr->enc_vdev); } From 0aed742014e1de5688d450709a523bf01953d0b8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 04:37:54 +1100 Subject: [PATCH 1343/1514] media: apple: prores: parse each decoder source frame once The decoder parsed a source frame three times per job: in buf_queue for the source-change check, in job_ready and in device_run. Each parse walks the whole slice-size table (1020 entries for a 1080p frame, 4080 at 2160p) with 16-bit loads from the vb2 dma-contig mapping, which is uncached because the engine is not DMA-coherent, so every entry is a round trip to memory. job_ready also runs in atomic context, from v4l2_m2m_job_finish() in the completion interrupt. With one job in the ring this time sits between the interrupt and the next job. On an M1 Pro (T6000), function_graph shows 76 us per parse of a 1080p ProRes 422 HQ frame and 304 us at 2160p, three times per frame, and the engine idles 100 us (1080p) and 331 us (2160p) between jobs. Parse the frame once, in buf_prepare, and keep the result with the buffer. A frame that does not parse still fails its own job rather than QBUF, as before. Copy the slice table in 256-byte blocks and check the copy, so the CPU reads it with wide loads: one parse now takes 9 us at 1080p and 61 us at 2160p, and the gap between jobs is 3-5 us. Decode throughput on the M1 Pro, depth 1, same clips, output unchanged byte for byte: 1080p 422 HQ 1870 -> 2780 fps, 2160p 422 HQ 495 -> 765 fps, 1080p 4444 1470 -> 1880 fps. Add a KUnit case with a 1080p table that spans several blocks, with a bad entry in the first full and the last partial block. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 24 ++++++++--- .../platform/apple/prores/apple-prores-drv.c | 40 +++++++++++++---- .../platform/apple/prores/apple-prores-test.c | 43 +++++++++++++++++-- 3 files changed, 89 insertions(+), 18 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index f6757774a90aa0..e13b98014f8b06 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -555,6 +555,9 @@ int apr_build_decode_desc(const struct apr_decode_frame *f, u8 *desc) } EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); +/* Slice-size entries copied per block; 256 bytes of stack. */ +#define APR_SLICE_CHUNK 128 + static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, u32 height, bool interlaced, u32 max_slices, u32 *picture_size, u32 *slices) @@ -577,11 +580,22 @@ static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, check_add_overflow(header, table_bytes, &min_size) || min_size > size) return -EINVAL; - for (i = 0; i < *slices; i++) { - u32 slice = get_unaligned_be16(data + header + 2 * i); - - if (slice < 6 || check_add_overflow(data_bytes, slice, &data_bytes)) - return -EINVAL; + /* + * The decoder's source buffers are mapped uncached, where each load is + * a fabric round trip: copy the table in blocks, then walk the copy. + */ + for (i = 0; i < *slices; i += APR_SLICE_CHUNK) { + __be16 chunk[APR_SLICE_CHUNK]; + u32 n = min(*slices - i, (u32)APR_SLICE_CHUNK), j; + + memcpy(chunk, data + header + 2 * i, 2 * n); + for (j = 0; j < n; j++) { + u32 slice = be16_to_cpu(chunk[j]); + + if (slice < 6 || + check_add_overflow(data_bytes, slice, &data_bytes)) + return -EINVAL; + } } if (data_bytes > size - min_size) return -EINVAL; diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index c92b7257fd5020..a6d053cc5abfe4 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1111,6 +1111,23 @@ static const struct apr_variant apr_t8142 = { .apri = &apri_t8142, }; +/* + * A source buffer of the decoder. The frame is parsed once, when it is + * queued; job_ready, the source-change check and device_run then use the + * cached result instead of walking the slice table of the (uncached) buffer + * again each time. + */ +struct apr_buf { + struct v4l2_m2m_buffer m2m; /* first: vb2 and m2m embed this */ + struct apr_prores_info info; + int parse_err; +}; + +static struct apr_buf *to_apr_buf(struct vb2_v4l2_buffer *vbuf) +{ + return container_of(vbuf, struct apr_buf, m2m.vb); +} + struct apr_dev { const struct apr_variant *variant; struct device *dev; @@ -1324,14 +1341,12 @@ static void apr_fill_frame(struct apr_ctx *ctx, struct vb2_v4l2_buffer *src, static int apr_parse_src(struct vb2_v4l2_buffer *src, struct apr_prores_info *info) { - struct vb2_buffer *vb = &src->vb2_buf; - u32 payload = vb2_get_plane_payload(vb, 0); - u32 offset = vb->planes[0].data_offset; - u8 *data = vb2_plane_vaddr(vb, 0); + struct apr_buf *buf = to_apr_buf(src); - if (!data || offset > payload) - return -EINVAL; - return apr_parse_frame(data + offset, payload - offset, info); + if (buf->parse_err) + return buf->parse_err; + *info = buf->info; + return 0; } static int apr_fill_decode_frame(struct apr_ctx *ctx, @@ -1968,10 +1983,17 @@ static int apr_buf_prepare(struct vb2_buffer *vb) return -EINVAL; if (V4L2_TYPE_IS_OUTPUT(vb->type)) { if (ctx->decode) { + struct apr_buf *buf = to_apr_buf(to_vb2_v4l2_buffer(vb)); u32 payload = vb2_get_plane_payload(vb, 0); + u32 offset = vb->planes[0].data_offset; + u8 *data = vb2_plane_vaddr(vb, 0); - if (payload < 28 || vb->planes[0].data_offset > payload) + if (payload < 28 || offset > payload) return -EINVAL; + /* A frame that does not parse fails its job, not QBUF. */ + buf->parse_err = data ? + apr_parse_frame(data + offset, payload - offset, + &buf->info) : -EINVAL; } else { /* The encoder always reads the whole padded surface. */ vb2_set_plane_payload(vb, 0, size); @@ -2100,7 +2122,7 @@ static int apr_queue_init(void *priv, struct vb2_queue *src, struct vb2_queue *d src->type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; src->io_modes = VB2_MMAP | VB2_DMABUF; src->drv_priv = ctx; - src->buf_struct_size = sizeof(struct v4l2_m2m_buffer); + src->buf_struct_size = sizeof(struct apr_buf); src->ops = &apr_qops; src->mem_ops = &vb2_dma_contig_memops; src->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_COPY; diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index 484bbc6a3a6da1..a640c74b37f61e 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -648,9 +648,11 @@ static void apr_test_decode_desc(struct kunit *test) KUNIT_EXPECT_EQ(test, apr_build_decode_desc(&f, d), -EINVAL); } -static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes) +static u8 *apr_test_bitstream_size(struct kunit *test, u32 width, u32 height, + bool interlaced, size_t *bytes) { - u32 slices = interlaced ? 24 : 45; + u32 slices = apr_slice_count(width, interlaced ? + DIV_ROUND_UP(height, 2) : height, 3); u32 picture_size = 8 + 2 * slices + 6 * slices; u32 pictures = interlaced ? 2 : 1; u32 frame_size = 28 + pictures * picture_size; @@ -665,8 +667,8 @@ static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes put_unaligned_be16(20, frame + 8); put_unaligned_be16(0, frame + 10); memcpy(frame + 12, "kunt", 4); - put_unaligned_be16(320, frame + 16); - put_unaligned_be16(240, frame + 18); + put_unaligned_be16(width, frame + 16); + put_unaligned_be16(height, frame + 18); frame[20] = 2 << 6 | (interlaced ? 1 << 2 : 0); frame[22] = 1; frame[23] = 1; @@ -686,6 +688,11 @@ static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes return frame; } +static u8 *apr_test_bitstream(struct kunit *test, bool interlaced, size_t *bytes) +{ + return apr_test_bitstream_size(test, 320, 240, interlaced, bytes); +} + static void apr_test_parse_frame(struct kunit *test) { struct apr_prores_info info; @@ -725,6 +732,33 @@ static void apr_test_parse_interlaced(struct kunit *test) info.picture_offset[0] + info.picture_size[0]); } +/* 1080p has 1020 slices: the table is read in several blocks. */ +static void apr_test_parse_many_slices(struct kunit *test) +{ + struct apr_prores_info info; + size_t bytes; + u8 *frame = apr_test_bitstream_size(test, 1920, 1080, false, &bytes); + u8 *table; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.slices[0], 1020U); + table = frame + 28 + 8; + /* A bad size in the last, partial block is still found. */ + put_unaligned_be16(5, table + 2 * 1019); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 1019); + /* So is one just past the first block. */ + put_unaligned_be16(0, table + 2 * 128); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 128); + /* And slices that together overrun the picture. */ + put_unaligned_be16(7, table + 2 * 500); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), -EINVAL); + put_unaligned_be16(6, table + 2 * 500); + KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); +} + static void apr_test_ring_accounting(struct kunit *test) { u8 *ring = kunit_kzalloc(test, APR_RING_BYTES, GFP_KERNEL); @@ -773,6 +807,7 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_decode_desc), KUNIT_CASE(apr_test_parse_frame), KUNIT_CASE(apr_test_parse_interlaced), + KUNIT_CASE(apr_test_parse_many_slices), KUNIT_CASE(apr_test_ring_accounting), {} }; From 7e1e65b22f0a583dfa1cbb197c19c8c55f0ee1e3 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 03:15:40 +1100 Subject: [PATCH 1344/1514] media: apple: prores: keep up to eight jobs in the ring The engine works through a producer/consumer descriptor ring, but the driver kept one job in it: v4l2-m2m runs one job at a time and the job only finished at its completion interrupt. On an M1 Pro, VideoToolbox decodes the same clips about 2.6 times faster on the same engine, and between two of our jobs the engine sits idle for the interrupt and the workqueue round trip to the next device_run (100 us per 1080p frame). Publish a job's descriptor, move its buffers off the m2m queues into a per-device FIFO tagged with the ring pointer past the descriptor, and finish the m2m job at once so the next one is prepared while the engine works. Up to APR_MAX_INFLIGHT (8) jobs sit in the ring; when it is full the m2m job stays running until a completion makes room, so device_run is only entered with room for one more descriptor. The interrupt reads the tail and completes, in ring order, every job the tail has passed. DONE and ERROR are latched per engine, so an ERROR fails every job in the ring at that moment. A ring that stops moving for a second fails all of its jobs and resets the engine as before; device_run waits for that reset. stop_streaming, suspend and a STOP command with an empty OUTPUT queue wait for the context's jobs in the ring; job_abort marks only that context's jobs cancelled, since encoder and decoder share the ring. Encode stays at one job in the ring: every encode job uses the one shared statistics area and encode already runs at macOS speed. Add KUnit cases for the ring distance, free space, tail validation and in-order retirement across the ring wrap, and for the FIFO limits. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 57 +++ .../platform/apple/prores/apple-prores-drv.c | 421 ++++++++++++++---- .../platform/apple/prores/apple-prores-test.c | 97 ++++ .../platform/apple/prores/apple-prores.h | 20 + 4 files changed, 517 insertions(+), 78 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index e13b98014f8b06..8844574081bf9b 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -675,6 +675,63 @@ u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes) } EXPORT_SYMBOL_IF_KUNIT(apr_ring_advance); +/* + * Ring pointers carry a generation bit above the offset, so a pointer names + * one of 2 * ring_bytes positions and a full ring differs from an empty one. + */ +static u32 apr_ring_pos(u32 ptr, u32 ring_bytes) +{ + return (ptr & APR_RING_OFFSET_MASK) + + (ptr & APR_RING_GENERATION ? ring_bytes : 0); +} + +/* Bytes from @from forward to @to. */ +u32 apr_ring_distance(u32 from, u32 to, u32 ring_bytes) +{ + u32 span = 2 * ring_bytes; + + return (apr_ring_pos(to, ring_bytes) + span - + apr_ring_pos(from, ring_bytes)) % span; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_distance); + +/* Bytes the producer may still write; @done is what the engine consumed. */ +u32 apr_ring_free(u32 done, u32 head, u32 ring_bytes) +{ + u32 used = apr_ring_distance(done, head, ring_bytes); + + return used < ring_bytes ? ring_bytes - used : 0; +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_free); + +/* + * Has the consumer @tail moved past the descriptor that ends at @end? @done + * is the start of the oldest descriptor still owned by the engine. + */ +bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes) +{ + return apr_ring_distance(done, end, ring_bytes) <= + apr_ring_distance(done, tail, ring_bytes); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_passed); + +/* A tail the engine reports must lie between what it consumed and the head. */ +bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes) +{ + return !(tail & ~APR_RING_PTR_MASK) && + (tail & APR_RING_OFFSET_MASK) < ring_bytes && + apr_ring_distance(done, tail, ring_bytes) <= + apr_ring_distance(done, head, ring_bytes); +} +EXPORT_SYMBOL_IF_KUNIT(apr_ring_tail_valid); + +/* No further job may enter the ring with @jobs in it, @encodes of them encodes. */ +bool apr_jobs_full(unsigned int jobs, unsigned int encodes) +{ + return jobs >= APR_MAX_INFLIGHT || encodes >= APR_ENCODE_MAX_INFLIGHT; +} +EXPORT_SYMBOL_IF_KUNIT(apr_jobs_full); + void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, u32 desc_bytes) { diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index a6d053cc5abfe4..58614891cfa165 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -2,8 +2,12 @@ /* * Apple ProRes (APR) V4L2 memory-to-memory codec. * - * One job runs at a time. The driver writes a descriptor into a 128 KiB DMA - * ring, advances the producer head and waits for the completion interrupt. + * The driver writes job descriptors into a 128 KiB DMA ring and advances the + * producer head; the engine works through the ring and reports progress with + * a consumer tail and a completion interrupt. Up to APR_MAX_INFLIGHT jobs sit + * in the ring at once: a job's buffers leave the m2m queues when its + * descriptor is published, so v4l2-m2m can run the next job while the engine + * is busy, and they complete in ring order once the tail passes them. * The encoder consumes semi-planar 4:2:2 or 4:4:4 frames and produces one * complete ProRes frame per buffer. The decoder exposes a second stateful * node with the queue directions reversed and linear color output. @@ -11,6 +15,7 @@ * Based on Acelogic's J700 ProRes diagnostic, which first encoded on this * engine under Linux, and on the m1n1 proxyclient ProRes experiment (MIT). */ +#include #include #include #include @@ -29,6 +34,7 @@ #include #include #include +#include #include #include @@ -1111,6 +1117,8 @@ static const struct apr_variant apr_t8142 = { .apri = &apri_t8142, }; +struct apr_ctx; + /* * A source buffer of the decoder. The frame is parsed once, when it is * queued; job_ready, the source-change check and device_run then use the @@ -1128,6 +1136,17 @@ static struct apr_buf *to_apr_buf(struct vb2_v4l2_buffer *vbuf) return container_of(vbuf, struct apr_buf, m2m.vb); } +/* A job in the ring; its buffers left the m2m queues when it was published. */ +struct apr_job { + struct apr_ctx *ctx; + struct vb2_v4l2_buffer *src; + struct vb2_v4l2_buffer *dst; + u32 end; /* ring pointer just past its descriptor */ + u32 sequence; + u32 bytes; /* decoded payload */ + int err; /* forced result: engine error or cancellation */ +}; + struct apr_dev { const struct apr_variant *variant; struct device *dev; @@ -1158,12 +1177,22 @@ struct apr_dev { size_t stats_size; spinlock_t hw_lock; /* protects the fields below */ - struct apr_ctx *active; /* job in the engine, or NULL */ + struct apr_job jobs[APR_MAX_INFLIGHT]; /* in ring order */ + unsigned int job_first; /* oldest job in jobs[] */ + unsigned int njobs; /* jobs the engine owns */ + unsigned int nencodes; /* encode jobs among them */ + struct apr_ctx *held; /* m2m job left running while the ring is full */ u32 head; /* next free ring offset */ + u32 done; /* the engine has consumed the ring up to here */ bool ring_ready; /* engine registers programmed since power-up */ bool broken; /* timed out with no way to reset */ - unsigned long started; /* jiffies at submission */ + bool hung; /* ring state is inconsistent, reset now */ + bool resetting; /* the watchdog is resetting the engine */ + unsigned long progress; /* jiffies of the last start or completion */ struct delayed_work watchdog; + + atomic_t outstanding; /* jobs not yet given back to vb2 */ + wait_queue_head_t idle_wq; /* woken when jobs are given back */ }; struct apr_ctx { @@ -1177,7 +1206,7 @@ struct apr_ctx { bool decode; bool source_valid; bool decode_444; - bool cancelled; + atomic_t inflight; /* jobs in the ring not yet given back to vb2 */ enum apr_profile stream_profile; /* fixed while OUTPUT streams */ u32 sequence; }; @@ -1258,6 +1287,7 @@ static void apr_hw_init(struct apr_dev *apr) /* Order the setup before any descriptor publication. */ wmb(); apr->head = 0; + apr->done = 0; apr->ring_ready = true; } @@ -1387,17 +1417,18 @@ static int apr_fill_decode_frame(struct apr_ctx *ctx, return 0; } -static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) +/* + * Give a job's buffers back to vb2. Safe in interrupt context. Not inlined, + * so ftrace can time completions against apr_device_run and apr_irq. + */ +static noinline void apr_complete(struct apr_dev *apr, struct apr_job *job) { + struct apr_ctx *ctx = job->ctx; struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; - struct vb2_v4l2_buffer *src, *dst; + struct vb2_v4l2_buffer *src = job->src, *dst = job->dst; + int err = job->err; u32 bytes = 0; - src = v4l2_m2m_src_buf_remove(m2m); - dst = v4l2_m2m_dst_buf_remove(m2m); - if (WARN_ON(!src || !dst)) - goto out; - if (!err && !ctx->decode) { u8 *out = vb2_plane_vaddr(&dst->vb2_buf, 0); @@ -1411,11 +1442,11 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) if (!err && ctx->decode) { /* The ACK and tail read complete before output ownership returns. */ dma_rmb(); - bytes = ctx->dst_fmt.plane_fmt[0].sizeimage; + bytes = job->bytes; } vb2_set_plane_payload(&dst->vb2_buf, 0, err ? 0 : bytes); v4l2_m2m_buf_copy_metadata(src, dst); - dst->sequence = ctx->sequence++; + dst->sequence = job->sequence; dst->flags |= V4L2_BUF_FLAG_KEYFRAME; if (v4l2_m2m_is_last_draining_src_buf(m2m, src)) { static const struct v4l2_event eos = { .type = V4L2_EVENT_EOS }; @@ -1426,27 +1457,72 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) } v4l2_m2m_buf_done(src, err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); v4l2_m2m_buf_done(dst, err ? VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE); -out: +} + +/* + * Give back jobs taken off the ring, in ring order. A context may be freed + * as soon as its in-flight count drops, so it is not touched after that. + */ +static void apr_retire(struct apr_dev *apr, struct apr_job *jobs, + unsigned int n) +{ + unsigned int i; + + for (i = 0; i < n; i++) { + apr_complete(apr, &jobs[i]); + pm_runtime_mark_last_busy(apr->dev); + pm_runtime_put_autosuspend(apr->dev); + atomic_dec(&jobs[i].ctx->inflight); + atomic_dec(&apr->outstanding); + } + if (n) + wake_up_all(&apr->idle_wq); +} + +/* Fail the current m2m job before its descriptor reached the ring. */ +static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_job job = { + .ctx = ctx, + .err = err, + .sequence = ctx->sequence++, + }; + + job.src = v4l2_m2m_src_buf_remove(m2m); + job.dst = v4l2_m2m_dst_buf_remove(m2m); + if (!WARN_ON(!job.src || !job.dst)) + apr_complete(apr, &job); pm_runtime_mark_last_busy(apr->dev); pm_runtime_put_autosuspend(apr->dev); v4l2_m2m_job_finish(apr->m2m_dev, m2m); } /* - * Claim the active job if the engine has finished it. Returns the context to - * finish, or NULL. Called with hw_lock held. + * Move the jobs the engine has finished, oldest first, to @out (room for + * APR_MAX_INFLIGHT). Returns false if the engine raised nothing. Called with + * hw_lock held and the engine powered. + * + * DONE and ERROR are latched per engine, not per descriptor: the status and + * detail registers do not say which descriptor failed. An ERROR therefore + * fails every job in the ring at that moment; the engine keeps running and + * the watchdog resets it if the tail stops moving. Several descriptors may + * finish behind one interrupt, and a DONE may arrive for a job already taken + * here on the tail alone; both are fine. */ -static struct apr_ctx *apr_take_done(struct apr_dev *apr, int *err) +static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, + unsigned int *n) { - struct apr_ctx *ctx = apr->active; + u32 ring_bytes = apr->variant->ring_bytes; u32 status, tail, st0, st1, st2; u32 detail[6]; + unsigned int i; - if (!ctx) - return NULL; + *n = 0; status = apr_read(apr, APR_REG_IRQ_STATUS); if (!(status & (APR_IRQ_DONE | APR_IRQ_ERROR))) - return NULL; + return false; + /* Snapshot before the W1C, as for a single job. */ st0 = apr_read(apr, APR_REG_ST0); st1 = apr_read(apr, APR_REG_ST1); st2 = apr_read(apr, APR_REG_ST2); @@ -1456,78 +1532,143 @@ static struct apr_ctx *apr_take_done(struct apr_dev *apr, int *err) detail[3] = apr_read(apr, APR_REG_DETAIL2_LO); detail[4] = apr_read(apr, APR_REG_DETAIL2_HI); detail[5] = apr_read(apr, APR_REG_DETAIL3); + if (status & APR_IRQ_ERROR) { + dev_err_ratelimited(apr->dev, + "job failed: irq %#x head %#x done %#x jobs %u st %#x/%#x/%#x detail %#x/%#x/%#x/%#x/%#x/%#x\n", + status, apr->head, apr->done, apr->njobs, + st0, st1, st2, detail[0], detail[1], detail[2], + detail[3], detail[4], detail[5]); + for (i = 0; i < apr->njobs; i++) { + struct apr_job *job = &apr->jobs[(apr->job_first + i) % + APR_MAX_INFLIGHT]; + + if (!job->err) + job->err = -EIO; + } + } apr_write(apr, APR_REG_IRQ_STATUS, status); /* The tail read flushes the posted W1C before buffers are released. */ tail = apr_read(apr, APR_REG_RING_TAIL) & APR_RING_PTR_MASK; - *err = 0; - if (!(status & APR_IRQ_DONE) || status & APR_IRQ_ERROR || tail != apr->head) { - dev_err_ratelimited(apr->dev, - "job failed: irq %#x tail %#x head %#x st %#x/%#x/%#x detail %#x/%#x/%#x/%#x/%#x/%#x\n", - status, tail, apr->head, st0, st1, st2, - detail[0], detail[1], detail[2], detail[3], - detail[4], detail[5]); - *err = -EIO; + if (!apr_ring_tail_valid(apr->done, tail, apr->head, ring_bytes)) { + dev_err_ratelimited(apr->dev, "tail %#x outside %#x..%#x\n", + tail, apr->done, apr->head); + apr->hung = true; + return true; + } + while (apr->njobs) { + struct apr_job *job = &apr->jobs[apr->job_first]; + + if (!apr_ring_passed(apr->done, job->end, tail, ring_bytes)) + break; + out[(*n)++] = *job; + apr->done = job->end; + apr->job_first = (apr->job_first + 1) % APR_MAX_INFLIGHT; + apr->njobs--; + if (!job->ctx->decode) + apr->nencodes--; } - if (ctx->cancelled) - *err = -ECANCELED; - apr->active = NULL; + if (*n) + apr->progress = jiffies; + return true; +} + +/* + * The m2m job left running because the ring was full may finish once there + * is room again. Called with hw_lock held; the caller finishes it unlocked. + */ +static struct apr_ctx *apr_take_held(struct apr_dev *apr) +{ + struct apr_ctx *ctx = apr->held; + + if (!ctx || apr_jobs_full(apr->njobs, apr->nencodes)) + return NULL; + apr->held = NULL; return ctx; } static irqreturn_t apr_irq(int irq, void *data) { struct apr_dev *apr = data; - struct apr_ctx *ctx; - int err = 0; + struct apr_job done[APR_MAX_INFLIGHT]; + struct apr_ctx *held = NULL; + unsigned int n = 0; + bool handled = false, hung; spin_lock(&apr->hw_lock); - ctx = apr_take_done(apr, &err); + /* Registers are only reachable while the engine is powered. */ + if (apr->ring_ready) + handled = apr_take_done(apr, done, &n); + held = apr_take_held(apr); + hung = apr->hung; + if (!apr->njobs) + cancel_delayed_work(&apr->watchdog); spin_unlock(&apr->hw_lock); - if (!ctx) - return IRQ_NONE; - cancel_delayed_work(&apr->watchdog); - apr_finish_job(apr, ctx, err); - return IRQ_HANDLED; + if (hung) + mod_delayed_work(system_wq, &apr->watchdog, 0); + apr_retire(apr, done, n); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); + return handled ? IRQ_HANDLED : IRQ_NONE; } /* - * Backstop for a lost interrupt and for hangs. A hung engine is reset - * through its power domain and reprogrammed; without a reset line the - * device refuses further jobs rather than reuse memory it may still own. + * Backstop for a lost interrupt and for hangs. A ring that stops moving for + * APR_TIMEOUT_MS fails every job in it. A hung engine is reset through its + * power domain and reprogrammed; without a reset line the device refuses + * further jobs rather than reuse memory it may still own. */ static void apr_watchdog(struct work_struct *work) { struct apr_dev *apr = container_of(work, struct apr_dev, watchdog.work); - struct apr_ctx *ctx; + struct apr_job done[APR_MAX_INFLIGHT]; + struct apr_ctx *held; unsigned long flags; - int err = 0; + unsigned int n = 0; spin_lock_irqsave(&apr->hw_lock, flags); - ctx = apr_take_done(apr, &err); - if (ctx) { + if (!apr->njobs) { spin_unlock_irqrestore(&apr->hw_lock, flags); - dev_warn_once(apr->dev, "completion found without an interrupt\n"); - apr_finish_job(apr, ctx, err); return; } - ctx = apr->active; - if (!ctx) { + if (apr->ring_ready && apr_take_done(apr, done, &n) && n) + dev_warn_once(apr->dev, "completion found without an interrupt\n"); + if (!apr->hung && (!apr->njobs || + time_before(jiffies, apr->progress + + msecs_to_jiffies(APR_TIMEOUT_MS)))) { + held = apr_take_held(apr); + if (apr->njobs) + schedule_delayed_work(&apr->watchdog, + msecs_to_jiffies(APR_POLL_MS)); spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_retire(apr, done, n); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); return; } - if (time_before(jiffies, apr->started + msecs_to_jiffies(APR_TIMEOUT_MS))) { - spin_unlock_irqrestore(&apr->hw_lock, flags); - schedule_delayed_work(&apr->watchdog, msecs_to_jiffies(APR_POLL_MS)); - return; + dev_err(apr->dev, "%s: head %#x done %#x tail %#x jobs %u st %#x/%#x\n", + apr->hung ? "ring state invalid" : "job timed out", + apr->head, apr->done, apr_read(apr, APR_REG_RING_TAIL), + apr->njobs, apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); + /* Every job still in the ring fails; the engine may own none of them. */ + while (apr->njobs) { + struct apr_job *job = &apr->jobs[apr->job_first]; + + done[n] = *job; + if (!done[n].err) + done[n].err = -ETIMEDOUT; + n++; + apr->job_first = (apr->job_first + 1) % APR_MAX_INFLIGHT; + apr->njobs--; } - dev_err(apr->dev, "job timed out: head %#x tail %#x st %#x/%#x\n", - apr->head, apr_read(apr, APR_REG_RING_TAIL), - apr_read(apr, APR_REG_ST0), apr_read(apr, APR_REG_ST1)); - apr->active = NULL; + apr->nencodes = 0; + apr->hung = false; + held = apr->held; + apr->held = NULL; apr_write(apr, APR_REG_IRQ_ENABLE, 0); apr_write(apr, APR_REG_MODE, APR_MODE_OFF); apr->ring_ready = false; - /* No new job can start until this one is finished below. */ + /* device_run waits until the reset below is over. */ + apr->resetting = true; spin_unlock_irqrestore(&apr->hw_lock, flags); if (!apr->reset || reset_control_reset(apr->reset)) { dev_err(apr->dev, "engine cannot be reset, refusing further jobs\n"); @@ -1535,24 +1676,41 @@ static void apr_watchdog(struct work_struct *work) apr->broken = true; spin_unlock_irqrestore(&apr->hw_lock, flags); } - apr_finish_job(apr, ctx, -ETIMEDOUT); + spin_lock_irqsave(&apr->hw_lock, flags); + apr->resetting = false; + spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_retire(apr, done, n); + /* apr_retire() woke idle_wq only if there was a job to give back. */ + wake_up_all(&apr->idle_wq); + if (held) + v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); } +/* + * Publish one job and, while the ring has room for another, finish the m2m + * job at once so the next one is prepared while the engine works. When the + * ring is full the m2m job stays running until a completion makes room, so + * device_run is only entered with room for one more descriptor. + */ static void apr_device_run(void *priv) { struct apr_ctx *ctx = priv; struct apr_dev *apr = ctx->apr; + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + u32 ring_bytes = apr->variant->ring_bytes; struct vb2_v4l2_buffer *src, *dst; struct apr_frame f; struct apr_decode_frame decode; + struct apr_job *job; u8 desc[APR_ENCODE_DESC_BYTES]; u32 desc_bytes; unsigned long flags; + bool hold; void *out; int ret; - src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); - dst = v4l2_m2m_next_dst_buf(ctx->fh.m2m_ctx); + src = v4l2_m2m_next_src_buf(m2m); + dst = v4l2_m2m_next_dst_buf(m2m); ret = pm_runtime_resume_and_get(apr->dev); if (ret < 0) { @@ -1580,13 +1738,24 @@ static void apr_device_run(void *priv) } spin_lock_irqsave(&apr->hw_lock, flags); + while (apr->resetting) { + spin_unlock_irqrestore(&apr->hw_lock, flags); + wait_event(apr->idle_wq, !READ_ONCE(apr->resetting)); + spin_lock_irqsave(&apr->hw_lock, flags); + } if (apr->broken) { spin_unlock_irqrestore(&apr->hw_lock, flags); apr_finish_job(apr, ctx, -EIO); return; } - if (!apr->ring_ready) + if (!apr->ring_ready && !WARN_ON(apr->njobs)) apr_hw_init(apr); + if (WARN_ON(apr_jobs_full(apr->njobs, apr->nencodes) || + apr_ring_free(apr->done, apr->head, ring_bytes) <= desc_bytes)) { + spin_unlock_irqrestore(&apr->hw_lock, flags); + apr_finish_job(apr, ctx, -EBUSY); + return; + } ret = ctx->decode ? apr_build_decode_desc(&decode, desc) : apr->variant->build_desc(&f, desc); if (ret) { @@ -1594,18 +1763,35 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, ret); return; } - apr_ring_write(apr->ring, apr->variant->ring_bytes, apr->head, - desc, desc_bytes); - apr->head = apr_ring_advance(apr->head, desc_bytes, - apr->variant->ring_bytes); - apr->active = ctx; - ctx->cancelled = false; - apr->started = jiffies; + apr_ring_write(apr->ring, ring_bytes, apr->head, desc, desc_bytes); + apr->head = apr_ring_advance(apr->head, desc_bytes, ring_bytes); + job = &apr->jobs[(apr->job_first + apr->njobs) % APR_MAX_INFLIGHT]; + *job = (struct apr_job){ + .ctx = ctx, + .src = v4l2_m2m_src_buf_remove(m2m), + .dst = v4l2_m2m_dst_buf_remove(m2m), + .end = apr->head, + .sequence = ctx->sequence++, + .bytes = ctx->dst_fmt.plane_fmt[0].sizeimage, + }; + WARN_ON(job->src != src || job->dst != dst); + if (!apr->njobs) + apr->progress = jiffies; + apr->njobs++; + if (!ctx->decode) + apr->nencodes++; + atomic_inc(&ctx->inflight); + atomic_inc(&apr->outstanding); /* Descriptor and buffers must be visible before the head moves. */ dma_wmb(); writel(apr->head, apr->regs + APR_REG_RING_HEAD); - spin_unlock_irqrestore(&apr->hw_lock, flags); + hold = apr_jobs_full(apr->njobs, apr->nencodes); + if (hold) + apr->held = ctx; schedule_delayed_work(&apr->watchdog, msecs_to_jiffies(APR_POLL_MS)); + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (!hold) + v4l2_m2m_job_finish(apr->m2m_dev, m2m); } static int apr_job_ready(void *priv) @@ -1630,10 +1816,21 @@ static void apr_job_abort(void *priv) struct apr_dev *apr = ctx->apr; unsigned long flags; - /* There is no decode- or encode-specific cancellation opcode. */ + unsigned int i; + + /* + * There is no cancellation opcode: the context's jobs still run to the + * end of the ring and only report cancelled. stop_streaming waits for + * them; other contexts' jobs in the same ring are not touched. + */ spin_lock_irqsave(&apr->hw_lock, flags); - if (apr->active == ctx) - ctx->cancelled = true; + for (i = 0; i < apr->njobs; i++) { + struct apr_job *job = &apr->jobs[(apr->job_first + i) % + APR_MAX_INFLIGHT]; + + if (job->ctx == ctx) + job->err = -ECANCELED; + } spin_unlock_irqrestore(&apr->hw_lock, flags); } @@ -1895,6 +2092,63 @@ static int apr_subscribe_event(struct v4l2_fh *fh, const struct v4l2_event_subsc return v4l2_ctrl_subscribe_event(fh, sub); } +/* + * A STOP with no OUTPUT buffer left in the m2m queue makes the m2m helper + * mark the next CAPTURE buffer LAST at once. With this context's jobs still + * in the ring their frames would follow that LAST buffer, so wait for them + * first. The check and the helper run under hw_lock: device_run moves a + * job's buffers into the ring under the same lock, so the helper sees the + * last OUTPUT buffer either queued or already given back. + */ +static int apr_stop_cmd(struct file *file, struct apr_ctx *ctx, void *cmd) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + unsigned long flags; + int ret; + + for (;;) { + spin_lock_irqsave(&apr->hw_lock, flags); + if (v4l2_m2m_num_src_bufs_ready(m2m) || + !atomic_read(&ctx->inflight)) + break; + spin_unlock_irqrestore(&apr->hw_lock, flags); + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + } + ret = ctx->decode ? v4l2_m2m_decoder_cmd(file, m2m, cmd) : + v4l2_m2m_encoder_cmd(file, m2m, cmd); + spin_unlock_irqrestore(&apr->hw_lock, flags); + return ret; +} + +static int apr_encoder_cmd(struct file *file, void *priv, + struct v4l2_encoder_cmd *ec) +{ + struct apr_ctx *ctx = apr_file_to_ctx(file); + int ret; + + ret = v4l2_m2m_ioctl_try_encoder_cmd(file, priv, ec); + if (ret) + return ret; + if (ec->cmd == V4L2_ENC_CMD_STOP) + return apr_stop_cmd(file, ctx, ec); + return v4l2_m2m_ioctl_encoder_cmd(file, priv, ec); +} + +static int apr_decoder_cmd(struct file *file, void *priv, + struct v4l2_decoder_cmd *dc) +{ + struct apr_ctx *ctx = apr_file_to_ctx(file); + int ret; + + ret = v4l2_m2m_ioctl_try_decoder_cmd(file, priv, dc); + if (ret) + return ret; + if (dc->cmd == V4L2_DEC_CMD_STOP) + return apr_stop_cmd(file, ctx, dc); + return v4l2_m2m_ioctl_decoder_cmd(file, priv, dc); +} + static const struct v4l2_ioctl_ops apr_ioctl_ops = { .vidioc_querycap = apr_querycap, .vidioc_enum_fmt_vid_out = apr_enum_fmt_out, @@ -1918,7 +2172,7 @@ static const struct v4l2_ioctl_ops apr_ioctl_ops = { .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_try_encoder_cmd = v4l2_m2m_ioctl_try_encoder_cmd, - .vidioc_encoder_cmd = v4l2_m2m_ioctl_encoder_cmd, + .vidioc_encoder_cmd = apr_encoder_cmd, .vidioc_subscribe_event = apr_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, @@ -1947,7 +2201,7 @@ static const struct v4l2_ioctl_ops apr_decoder_ioctl_ops = { .vidioc_streamoff = v4l2_m2m_ioctl_streamoff, .vidioc_try_decoder_cmd = v4l2_m2m_ioctl_try_decoder_cmd, - .vidioc_decoder_cmd = v4l2_m2m_ioctl_decoder_cmd, + .vidioc_decoder_cmd = apr_decoder_cmd, .vidioc_subscribe_event = apr_subscribe_event, .vidioc_unsubscribe_event = v4l2_event_unsubscribe, @@ -2088,6 +2342,12 @@ static void apr_stop_streaming(struct vb2_queue *q) struct apr_ctx *ctx = vb2_get_drv_priv(q); struct vb2_v4l2_buffer *vbuf; + /* + * The engine still owns this context's jobs in the ring. The m2m core + * cancelled the job being prepared; wait for the ring ones, which the + * watchdog completes or fails within APR_TIMEOUT_MS of no progress. + */ + wait_event(ctx->apr->idle_wq, !atomic_read(&ctx->inflight)); for (;;) { vbuf = V4L2_TYPE_IS_OUTPUT(q->type) ? v4l2_m2m_src_buf_remove(ctx->fh.m2m_ctx) : @@ -2260,6 +2520,8 @@ static int apr_suspend(struct device *dev) struct apr_dev *apr = dev_get_drvdata(dev); v4l2_m2m_suspend(apr->m2m_dev); + /* No new job starts now; let the ring drain. */ + wait_event(apr->idle_wq, !atomic_read(&apr->outstanding)); return pm_runtime_force_suspend(dev); } @@ -2368,6 +2630,9 @@ static int apr_probe(struct platform_device *pdev) mutex_init(&apr->vdev_lock); spin_lock_init(&apr->hw_lock); INIT_DELAYED_WORK(&apr->watchdog, apr_watchdog); + init_waitqueue_head(&apr->idle_wq); + /* The ring always has room for every job the driver keeps in flight. */ + BUILD_BUG_ON(APR_MAX_INFLIGHT * APR_ENCODE_DESC_BYTES >= APR_RING_BYTES); platform_set_drvdata(pdev, apr); for (i = 0; i < apr->variant->num_regs; i++) { diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index a640c74b37f61e..8133663a33014d 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -785,6 +785,100 @@ static void apr_test_ring_accounting(struct kunit *test) KUNIT_EXPECT_MEMEQ(test, ring, desc + 0x100, 0x80); } +static void apr_test_ring_space(struct kunit *test) +{ + const u32 r = APR_RING_BYTES, g = APR_RING_GENERATION; + + KUNIT_EXPECT_EQ(test, apr_ring_distance(0, 0x100, r), 0x100U); + KUNIT_EXPECT_EQ(test, apr_ring_distance(0x100, 0x100, r), 0U); + /* Across the end of the ring, in either generation. */ + KUNIT_EXPECT_EQ(test, apr_ring_distance(r - 0x80, g | 0x80, r), 0x100U); + KUNIT_EXPECT_EQ(test, apr_ring_distance(g | (r - 0x80), 0x80, r), 0x100U); + /* Same offset, other generation: a whole ring apart. */ + KUNIT_EXPECT_EQ(test, apr_ring_distance(0x100, g | 0x100, r), r); + + KUNIT_EXPECT_EQ(test, apr_ring_free(0, 0, r), r); + KUNIT_EXPECT_EQ(test, apr_ring_free(0, 0x800, r), r - 0x800); + KUNIT_EXPECT_EQ(test, apr_ring_free(r - 0x80, g | 0x80, r), r - 0x100); + KUNIT_EXPECT_EQ(test, apr_ring_free(g | 0x100, 0x100, r), 0U); + /* The deepest ring the driver builds still has room. */ + KUNIT_EXPECT_GT(test, apr_ring_free(0, APR_MAX_INFLIGHT * + APR_ENCODE_DESC_BYTES, r), + (u32)APR_ENCODE_DESC_BYTES); +} + +static void apr_test_ring_tail(struct kunit *test) +{ + const u32 r = APR_RING_BYTES, g = APR_RING_GENERATION; + + KUNIT_EXPECT_TRUE(test, apr_ring_passed(0, 0x100, 0x100, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(0, 0x100, 0x300, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(0, 0x100, 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(0, 0x100, 0, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(r - 0x80, g | 0x80, g | 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(r - 0x80, g | 0x80, r - 0x40, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_passed(g | (r - 0x80), 0x80, 0x40, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_passed(g | (r - 0x80), 0x80, 0x80, r)); + + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x100, 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x400, 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(0x100, 0x280, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, 0x500, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, 0x80, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0x100, g | 0x200, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0, r, 0x400, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(0, BIT(25), 0x400, r)); + KUNIT_EXPECT_TRUE(test, apr_ring_tail_valid(r - 0x80, g | 0x40, g | 0x80, r)); + KUNIT_EXPECT_FALSE(test, apr_ring_tail_valid(r - 0x80, 0x40, g | 0x80, r)); +} + +static void apr_test_inflight(struct kunit *test) +{ + const u32 r = APR_RING_BYTES; + u32 ends[APR_MAX_INFLIGHT], done, head, tail; + unsigned int i, retired; + + KUNIT_EXPECT_FALSE(test, apr_jobs_full(0, 0)); + KUNIT_EXPECT_FALSE(test, apr_jobs_full(APR_MAX_INFLIGHT - 1, 0)); + KUNIT_EXPECT_TRUE(test, apr_jobs_full(APR_MAX_INFLIGHT, 0)); + /* Encode stays alone at the end of the ring. */ + KUNIT_EXPECT_TRUE(test, apr_jobs_full(1, 1)); + KUNIT_EXPECT_TRUE(test, apr_jobs_full(3, 1)); + + /* A full ring of decode jobs straddling the wrap, retired in order. */ + done = r - 3 * APR_DECODE_DESC_BYTES - 0x80; + head = done; + for (i = 0; i < APR_MAX_INFLIGHT; i++) { + KUNIT_ASSERT_GT(test, apr_ring_free(done, head, r), + (u32)APR_DECODE_DESC_BYTES); + head = apr_ring_advance(head, APR_DECODE_DESC_BYTES, r); + ends[i] = head; + } + KUNIT_EXPECT_EQ(test, apr_ring_distance(done, head, r), + (u32)(APR_MAX_INFLIGHT * APR_DECODE_DESC_BYTES)); + /* The tail stops inside the fifth descriptor: four jobs are done. */ + tail = apr_ring_advance(ends[3], 0x40, r); + KUNIT_ASSERT_TRUE(test, apr_ring_tail_valid(done, tail, head, r)); + for (retired = 0; retired < APR_MAX_INFLIGHT; retired++) { + if (!apr_ring_passed(done, ends[retired], tail, r)) + break; + done = ends[retired]; + } + KUNIT_EXPECT_EQ(test, retired, 4U); + KUNIT_EXPECT_EQ(test, done, ends[3]); + /* Then the engine drains the ring. */ + tail = head; + KUNIT_ASSERT_TRUE(test, apr_ring_tail_valid(done, tail, head, r)); + for (; retired < APR_MAX_INFLIGHT; retired++) { + if (!apr_ring_passed(done, ends[retired], tail, r)) + break; + done = ends[retired]; + } + KUNIT_EXPECT_EQ(test, retired, (unsigned int)APR_MAX_INFLIGHT); + KUNIT_EXPECT_EQ(test, done, head); + KUNIT_EXPECT_EQ(test, apr_ring_free(done, head, r), r); +} + static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_qmat_regs), KUNIT_CASE(apr_test_dc_scale), @@ -809,6 +903,9 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_parse_interlaced), KUNIT_CASE(apr_test_parse_many_slices), KUNIT_CASE(apr_test_ring_accounting), + KUNIT_CASE(apr_test_ring_space), + KUNIT_CASE(apr_test_ring_tail), + KUNIT_CASE(apr_test_inflight), {} }; diff --git a/drivers/media/platform/apple/prores/apple-prores.h b/drivers/media/platform/apple/prores/apple-prores.h index 60a99979db4ce1..758524513c89ff 100644 --- a/drivers/media/platform/apple/prores/apple-prores.h +++ b/drivers/media/platform/apple/prores/apple-prores.h @@ -65,6 +65,21 @@ /* Kept for the encode descriptor tests and callers. */ #define APR_DESC_BYTES APR_ENCODE_DESC_BYTES +/* + * Jobs the driver keeps in the ring at once. The ring itself holds hundreds + * of descriptors; the limit bounds the buffers and runtime-PM references a + * timeout has to fail and the latency of a stream-off. Eight covers the + * decode gap to VideoToolbox (several frames outstanding) with slack for the + * scheduling delay between jobs. + */ +#define APR_MAX_INFLIGHT 8 +/* + * Encode stays at one job in the ring: every encode job uses the one shared + * statistics area, and nothing public shows that two encodes may overlap in + * it. Encode already runs at macOS speed with one job outstanding. + */ +#define APR_ENCODE_MAX_INFLIGHT 1 + #define APRI_T6041_FIRMWARE_NAME "apple/prores-t6041-init.bin" #define APRI_T6041_FIRMWARE_SIZE 2728 #define APRI_T6050_FIRMWARE_NAME "apple/prores-t6050-init.bin" @@ -229,6 +244,11 @@ static inline int apr_parse_t6041_init(const u8 *data, size_t size, return apr_parse_init(&apri_t6041, data, size, init); } u32 apr_ring_advance(u32 ptr, u32 bytes, u32 ring_bytes); +u32 apr_ring_distance(u32 from, u32 to, u32 ring_bytes); +u32 apr_ring_free(u32 done, u32 head, u32 ring_bytes); +bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes); +bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes); +bool apr_jobs_full(unsigned int jobs, unsigned int encodes); void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, u32 desc_bytes); From c86af3b4b882881fcd924915898f030d960dbe3d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 08:24:16 +1100 Subject: [PATCH 1345/1514] media: apple: prores: retire decode jobs on the engine's finished-job id With several decode jobs in the ring, the driver gave a job's buffers back once the consumer tail had passed its descriptor. The tail moves when the engine fetches a descriptor, not when the frame is written, so buffers went back to vb2 while the engine still wrote them: wrong output on 4:4:4 clips and DART faults at the end of a run. The engine reports the id of the last decode job it has finished in the upper half of ST1; the decode command word already carries a 16-bit id. Give decode jobs device-wide ids that skip 0 (ST1 reads 0 after a reset), read ST1 after the status clear, and retire decode jobs in ring order once their id is reported finished. An encode descriptor carries no id, so an encode only enters an empty ring and completes on its interrupt, as before. On an M1 Pro (T6000) with eight jobs in the ring every clip decodes to the same bytes as with one job, with no DART faults; 1080p 422 HQ goes from about 2730 to 2920 fps, 4K 422 HQ from 761 to 775 fps. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 22 ++++++++++++ .../platform/apple/prores/apple-prores-drv.c | 34 +++++++++++++++---- .../platform/apple/prores/apple-prores-test.c | 16 +++++++++ .../platform/apple/prores/apple-prores.h | 4 +++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 8844574081bf9b..020a641ce95238 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -725,6 +725,28 @@ bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes) } EXPORT_SYMBOL_IF_KUNIT(apr_ring_tail_valid); +/* + * Decode job ids are device-wide and never 0: the engine reports the id of + * the last job it finished, and that report reads 0 after a reset, before + * any job has run. + */ +u16 apr_next_job_id(u16 id) +{ + return id == U16_MAX ? 1 : id + 1; +} +EXPORT_SYMBOL_IF_KUNIT(apr_next_job_id); + +/* + * Has the engine finished job @id, given the last finished id @done_id? + * Jobs finish in ring order and far fewer than 2^15 are ever outstanding, + * so the signed distance decides, across the wrap as well. + */ +bool apr_job_id_done(u16 done_id, u16 id) +{ + return (u16)(done_id - id) < 0x8000; +} +EXPORT_SYMBOL_IF_KUNIT(apr_job_id_done); + /* No further job may enter the ring with @jobs in it, @encodes of them encodes. */ bool apr_jobs_full(unsigned int jobs, unsigned int encodes) { diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 58614891cfa165..53eb9d7dc64918 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -4,10 +4,14 @@ * * The driver writes job descriptors into a 128 KiB DMA ring and advances the * producer head; the engine works through the ring and reports progress with - * a consumer tail and a completion interrupt. Up to APR_MAX_INFLIGHT jobs sit - * in the ring at once: a job's buffers leave the m2m queues when its + * a consumer tail and a completion interrupt. Up to APR_MAX_INFLIGHT decode + * jobs sit in the ring at once: a job's buffers leave the m2m queues when its * descriptor is published, so v4l2-m2m can run the next job while the engine - * is busy, and they complete in ring order once the tail passes them. + * is busy. The tail moves when the engine fetches a descriptor, not when it + * has finished the frame, so decode jobs complete in ring order once the + * engine reports their job id as finished in ST1. An encode descriptor + * carries no job id: it only enters an empty ring and completes on its + * interrupt, as a lone job. * The encoder consumes semi-planar 4:2:2 or 4:4:4 frames and produces one * complete ProRes frame per buffer. The decoder exposes a second stateful * node with the queue directions reversed and linear color output. @@ -16,6 +20,7 @@ * engine under Linux, and on the m1n1 proxyclient ProRes experiment (MIT). */ #include +#include #include #include #include @@ -1142,6 +1147,7 @@ struct apr_job { struct vb2_v4l2_buffer *src; struct vb2_v4l2_buffer *dst; u32 end; /* ring pointer just past its descriptor */ + u16 id; /* decode job id in the descriptor */ u32 sequence; u32 bytes; /* decoded payload */ int err; /* forced result: engine error or cancellation */ @@ -1184,6 +1190,7 @@ struct apr_dev { struct apr_ctx *held; /* m2m job left running while the ring is full */ u32 head; /* next free ring offset */ u32 done; /* the engine has consumed the ring up to here */ + u16 next_id; /* id for the next decode job, never 0 */ bool ring_ready; /* engine registers programmed since power-up */ bool broken; /* timed out with no way to reset */ bool hung; /* ring state is inconsistent, reset now */ @@ -1287,6 +1294,7 @@ static void apr_hw_init(struct apr_dev *apr) /* Order the setup before any descriptor publication. */ wmb(); apr->head = 0; + apr->next_id = 1; apr->done = 0; apr->ring_ready = true; } @@ -1412,7 +1420,6 @@ static int apr_fill_decode_frame(struct apr_ctx *ctx, src->vb2_buf.planes[0].data_offset, .luma = output, .chroma = output + (u64)luma_stride * d->height, - .job_id = ctx->sequence, }; return 0; } @@ -1517,6 +1524,7 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, u32 status, tail, st0, st1, st2; u32 detail[6]; unsigned int i; + u16 done_id; *n = 0; status = apr_read(apr, APR_REG_IRQ_STATUS); @@ -1555,10 +1563,15 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, apr->hung = true; return true; } + /* Read after the W1C: a job finishing later raises DONE again. */ + done_id = FIELD_GET(APR_ST1_DONE_ID, apr_read(apr, APR_REG_ST1)); while (apr->njobs) { struct apr_job *job = &apr->jobs[apr->job_first]; - if (!apr_ring_passed(apr->done, job->end, tail, ring_bytes)) + if (job->ctx->decode ? + !apr_job_id_done(done_id, job->id) : + !(status & (APR_IRQ_DONE | APR_IRQ_ERROR)) || + !apr_ring_passed(apr->done, job->end, tail, ring_bytes)) break; out[(*n)++] = *job; apr->done = job->end; @@ -1738,9 +1751,11 @@ static void apr_device_run(void *priv) } spin_lock_irqsave(&apr->hw_lock, flags); - while (apr->resetting) { + /* An encode has no job id, so it only runs alone in the ring. */ + while (apr->resetting || (!ctx->decode && apr->njobs)) { spin_unlock_irqrestore(&apr->hw_lock, flags); - wait_event(apr->idle_wq, !READ_ONCE(apr->resetting)); + wait_event(apr->idle_wq, !READ_ONCE(apr->resetting) && + (ctx->decode || !READ_ONCE(apr->njobs))); spin_lock_irqsave(&apr->hw_lock, flags); } if (apr->broken) { @@ -1756,6 +1771,8 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, -EBUSY); return; } + if (ctx->decode) + decode.job_id = apr->next_id; ret = ctx->decode ? apr_build_decode_desc(&decode, desc) : apr->variant->build_desc(&f, desc); if (ret) { @@ -1771,6 +1788,7 @@ static void apr_device_run(void *priv) .src = v4l2_m2m_src_buf_remove(m2m), .dst = v4l2_m2m_dst_buf_remove(m2m), .end = apr->head, + .id = ctx->decode ? apr->next_id : 0, .sequence = ctx->sequence++, .bytes = ctx->dst_fmt.plane_fmt[0].sizeimage, }; @@ -1780,6 +1798,8 @@ static void apr_device_run(void *priv) apr->njobs++; if (!ctx->decode) apr->nencodes++; + if (ctx->decode) + apr->next_id = apr_next_job_id(apr->next_id); atomic_inc(&ctx->inflight); atomic_inc(&apr->outstanding); /* Descriptor and buffers must be visible before the head moves. */ diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index 8133663a33014d..f87fe595cc56a1 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -879,6 +879,21 @@ static void apr_test_inflight(struct kunit *test) KUNIT_EXPECT_EQ(test, apr_ring_free(done, head, r), r); } +static void apr_test_job_id(struct kunit *test) +{ + /* Ids are never 0, which ST1 reads after a reset. */ + KUNIT_EXPECT_EQ(test, apr_next_job_id(1), 2); + KUNIT_EXPECT_EQ(test, apr_next_job_id(U16_MAX), 1); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(0, 1)); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(1, 1)); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(5, 3)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(3, 5)); + /* Across the wrap: 65535 finishes before 1 and 2. */ + KUNIT_EXPECT_TRUE(test, apr_job_id_done(1, U16_MAX)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX, 1)); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX - 1, 2)); +} + static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_qmat_regs), KUNIT_CASE(apr_test_dc_scale), @@ -906,6 +921,7 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_ring_space), KUNIT_CASE(apr_test_ring_tail), KUNIT_CASE(apr_test_inflight), + KUNIT_CASE(apr_test_job_id), {} }; diff --git a/drivers/media/platform/apple/prores/apple-prores.h b/drivers/media/platform/apple/prores/apple-prores.h index 758524513c89ff..2151f000ac8a10 100644 --- a/drivers/media/platform/apple/prores/apple-prores.h +++ b/drivers/media/platform/apple/prores/apple-prores.h @@ -29,6 +29,8 @@ #define APR_IRQ_ERROR BIT(1) #define APR_REG_ST0 0x0014 #define APR_REG_ST1 0x0018 +/* Job id of the last descriptor the engine has finished (decode command 31:16). */ +#define APR_ST1_DONE_ID GENMASK(31, 16) #define APR_REG_ST2 0x001c #define APR_REG_DETAIL0 0x003c #define APR_REG_DETAIL1_LO 0x0040 @@ -248,6 +250,8 @@ u32 apr_ring_distance(u32 from, u32 to, u32 ring_bytes); u32 apr_ring_free(u32 done, u32 head, u32 ring_bytes); bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes); bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes); +u16 apr_next_job_id(u16 id); +bool apr_job_id_done(u16 done_id, u16 id); bool apr_jobs_full(unsigned int jobs, unsigned int encodes); void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, u32 desc_bytes); From c74cf06a20a09703b22a4fe394cc731996825376 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 14:30:01 +1100 Subject: [PATCH 1346/1514] media: apple: prores: never give back a buffer the engine may still use Several paths could still hand buffers back while the engine owned them or would use them: - A DONE or ERROR latched after the last job was retired by id stayed set. An encode published into the then empty ring was taken for finished on it, because the tail passes an encode as soon as it is fetched. The engine is idle while the ring is empty, so clear both status bits before publishing into an empty ring. - ST1 = 0 counted as "finished" for every id in 0x8001..0xffff, and an id not issued yet retired the whole ring. 0 now means no progress, and an id at or after the next one to issue marks the ring hung, so the watchdog resets the engine before any buffer goes back. - A job that fails before it reaches the ring (a frame that does not parse, an interlaced frame) completed at once, ahead of up to seven earlier frames of the same context. As the drain's last source buffer it sent LAST and EOS first and the frames still in the ring were lost. It now waits until the context's jobs in the ring are given back. - apr_finish_job() removed the source and destination buffers outside hw_lock, so a STOP could see the destination half moved. Move both under the lock, as device_run does. Also correct the watchdog comments (it fires when no job finishes, not when the tail stops) and the ring test comment. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 16 +++++ .../platform/apple/prores/apple-prores-drv.c | 52 +++++++++++++--- .../platform/apple/prores/apple-prores-test.c | 60 ++++++++++++++++++- .../platform/apple/prores/apple-prores.h | 8 +++ 4 files changed, 126 insertions(+), 10 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 020a641ce95238..3ab8e6ca73dd39 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -747,6 +747,22 @@ bool apr_job_id_done(u16 done_id, u16 id) } EXPORT_SYMBOL_IF_KUNIT(apr_job_id_done); +/* + * Classify @done_id, the last finished id ST1 reports, against @next_id, the + * id the next decode job gets. 0 is what ST1 reads before any job finished + * since the reset. Ids from @next_id on, half the id space, are not issued + * yet; the other half are issued ids, finished or still in the ring. + */ +enum apr_done_id apr_job_id_check(u16 done_id, u16 next_id) +{ + if (!done_id) + return APR_DONE_ID_NONE; + if (apr_job_id_done(done_id, next_id)) + return APR_DONE_ID_FUTURE; + return APR_DONE_ID_ISSUED; +} +EXPORT_SYMBOL_IF_KUNIT(apr_job_id_check); + /* No further job may enter the ring with @jobs in it, @encodes of them encodes. */ bool apr_jobs_full(unsigned int jobs, unsigned int encodes) { diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 53eb9d7dc64918..c03fbb8a8d6c3b 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1471,7 +1471,7 @@ static noinline void apr_complete(struct apr_dev *apr, struct apr_job *job) * as soon as its in-flight count drops, so it is not touched after that. */ static void apr_retire(struct apr_dev *apr, struct apr_job *jobs, - unsigned int n) + unsigned int n) { unsigned int i; @@ -1486,18 +1486,28 @@ static void apr_retire(struct apr_dev *apr, struct apr_job *jobs, wake_up_all(&apr->idle_wq); } -/* Fail the current m2m job before its descriptor reached the ring. */ +/* + * Fail the current m2m job before its descriptor reached the ring. Earlier + * jobs of the context may still be in the ring: they are given back first, + * so this one cannot overtake them. That matters most when it is the drain's + * last source buffer, whose LAST flag and EOS end the stream. Sleeps. + */ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) { struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; struct apr_job job = { .ctx = ctx, .err = err, - .sequence = ctx->sequence++, }; + unsigned long flags; + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + /* Buffers move under hw_lock, which apr_stop_cmd() relies on. */ + spin_lock_irqsave(&apr->hw_lock, flags); + job.sequence = ctx->sequence++; job.src = v4l2_m2m_src_buf_remove(m2m); job.dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); if (!WARN_ON(!job.src || !job.dst)) apr_complete(apr, &job); pm_runtime_mark_last_busy(apr->dev); @@ -1513,9 +1523,17 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) * DONE and ERROR are latched per engine, not per descriptor: the status and * detail registers do not say which descriptor failed. An ERROR therefore * fails every job in the ring at that moment; the engine keeps running and - * the watchdog resets it if the tail stops moving. Several descriptors may - * finish behind one interrupt, and a DONE may arrive for a job already taken - * here on the tail alone; both are fine. + * the watchdog resets it if no job finishes for APR_TIMEOUT_MS. Several + * descriptors may finish behind one interrupt. + * + * A decode job is finished once ST1 reports its id. ST1 reads 0 before any + * job finished since the reset, which is no progress; an id the driver has + * not issued yet means the engine and the ring disagree, so the ring is + * declared hung and the watchdog resets the engine before any buffer goes + * back. An encode has no id and retires on DONE once the tail passed it. + * A DONE still latched after the last job was taken here would make a new + * encode look finished as soon as it is fetched, so device_run clears the + * status before it publishes into an empty ring. */ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, unsigned int *n) @@ -1523,6 +1541,7 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, u32 ring_bytes = apr->variant->ring_bytes; u32 status, tail, st0, st1, st2; u32 detail[6]; + enum apr_done_id state; unsigned int i; u16 done_id; @@ -1565,10 +1584,18 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, } /* Read after the W1C: a job finishing later raises DONE again. */ done_id = FIELD_GET(APR_ST1_DONE_ID, apr_read(apr, APR_REG_ST1)); + state = apr_job_id_check(done_id, apr->next_id); + if (state == APR_DONE_ID_FUTURE && apr->njobs > apr->nencodes) { + dev_err_ratelimited(apr->dev, "finished id %#x not issued yet, next %#x\n", + done_id, apr->next_id); + apr->hung = true; + return true; + } while (apr->njobs) { struct apr_job *job = &apr->jobs[apr->job_first]; if (job->ctx->decode ? + state != APR_DONE_ID_ISSUED || !apr_job_id_done(done_id, job->id) : !(status & (APR_IRQ_DONE | APR_IRQ_ERROR)) || !apr_ring_passed(apr->done, job->end, tail, ring_bytes)) @@ -1625,8 +1652,8 @@ static irqreturn_t apr_irq(int irq, void *data) } /* - * Backstop for a lost interrupt and for hangs. A ring that stops moving for - * APR_TIMEOUT_MS fails every job in it. A hung engine is reset through its + * Backstop for a lost interrupt and for hangs. When no job finishes for + * APR_TIMEOUT_MS, every job in the ring fails. A hung engine is reset through its * power domain and reprogrammed; without a reset line the device refuses * further jobs rather than reuse memory it may still own. */ @@ -1780,6 +1807,14 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, ret); return; } + /* + * With the ring empty the engine is idle, so a DONE or ERROR still + * latched belongs to a job already given back. Clear it before this + * job can be taken for finished on it. The clear reaches the engine + * before the head write below. + */ + if (!apr->njobs) + apr_write(apr, APR_REG_IRQ_STATUS, APR_IRQ_DONE | APR_IRQ_ERROR); apr_ring_write(apr->ring, ring_bytes, apr->head, desc, desc_bytes); apr->head = apr_ring_advance(apr->head, desc_bytes, ring_bytes); job = &apr->jobs[(apr->job_first + apr->njobs) % APR_MAX_INFLIGHT]; @@ -1835,7 +1870,6 @@ static void apr_job_abort(void *priv) struct apr_ctx *ctx = priv; struct apr_dev *apr = ctx->apr; unsigned long flags; - unsigned int i; /* diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index f87fe595cc56a1..53dc5c0abfd99c 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -845,7 +845,11 @@ static void apr_test_inflight(struct kunit *test) KUNIT_EXPECT_TRUE(test, apr_jobs_full(1, 1)); KUNIT_EXPECT_TRUE(test, apr_jobs_full(3, 1)); - /* A full ring of decode jobs straddling the wrap, retired in order. */ + /* + * Ring space and tail arithmetic for a full ring straddling the wrap. + * Only the lone encode retires on the tail; decode jobs retire on + * their ids (apr_test_job_id). + */ done = r - 3 * APR_DECODE_DESC_BYTES - 0x80; head = done; for (i = 0; i < APR_MAX_INFLIGHT; i++) { @@ -892,6 +896,60 @@ static void apr_test_job_id(struct kunit *test) KUNIT_EXPECT_TRUE(test, apr_job_id_done(1, U16_MAX)); KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX, 1)); KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX - 1, 2)); + + /* ST1 = 0 is no progress, never "everything in 0x8001..0xffff done". */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(0, 9), APR_DONE_ID_NONE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0, 0x8005), APR_DONE_ID_NONE); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(0, 0x8001)); + /* Ids 1..8 outstanding: ids already issued, finished or not. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(1, 9), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_EQ(test, apr_job_id_check(8, 9), APR_DONE_ID_ISSUED); + /* The other half of the id space reads as old ids: nothing retires. */ + for (u32 d = 0x8009; d <= U16_MAX; d += 0x7ff) { + KUNIT_EXPECT_EQ(test, apr_job_id_check(d, 9), APR_DONE_ID_ISSUED); + for (u16 id = 1; id < 9; id++) + KUNIT_EXPECT_FALSE(test, apr_job_id_done(d, id)); + } + KUNIT_EXPECT_EQ(test, apr_job_id_check(U16_MAX, 9), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_FALSE(test, apr_job_id_done(U16_MAX, 1)); + /* An id not issued yet: the ring is hung, nothing retires. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(9, 9), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(10, 9), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8008, 9), APR_DONE_ID_FUTURE); + /* First job after a reset: id 1 not issued until next_id moves on. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(1, 1), APR_DONE_ID_FUTURE); + + /* Eight jobs across the wrap: 0xfffc..0xffff, then 1..4 (0 skipped). */ + { + u16 ids[APR_MAX_INFLIGHT], next = 0xfffc; + unsigned int i, retired = 0; + + for (i = 0; i < APR_MAX_INFLIGHT; i++) { + ids[i] = next; + next = apr_next_job_id(next); + } + KUNIT_EXPECT_EQ(test, ids[4], 1); + KUNIT_EXPECT_EQ(test, next, 5); + /* ST1 skips ahead to 2: six jobs finished, in ring order. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(2, next), APR_DONE_ID_ISSUED); + while (retired < APR_MAX_INFLIGHT && + apr_job_id_done(2, ids[retired])) + retired++; + KUNIT_EXPECT_EQ(test, retired, 6U); + /* The same id again retires nothing more. */ + while (retired < APR_MAX_INFLIGHT && + apr_job_id_done(2, ids[retired])) + retired++; + KUNIT_EXPECT_EQ(test, retired, 6U); + /* A stale id from before the wrap retires nothing more either. */ + KUNIT_EXPECT_FALSE(test, apr_job_id_done(0xfffe, ids[6])); + KUNIT_EXPECT_EQ(test, apr_job_id_check(4, next), APR_DONE_ID_ISSUED); + KUNIT_EXPECT_TRUE(test, apr_job_id_done(4, ids[7])); + /* 5 = next_id: not issued, hung. */ + KUNIT_EXPECT_EQ(test, apr_job_id_check(5, next), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8004, next), APR_DONE_ID_FUTURE); + KUNIT_EXPECT_EQ(test, apr_job_id_check(0x8005, next), APR_DONE_ID_ISSUED); + } } static struct kunit_case apr_test_cases[] = { diff --git a/drivers/media/platform/apple/prores/apple-prores.h b/drivers/media/platform/apple/prores/apple-prores.h index 2151f000ac8a10..58808ed515c550 100644 --- a/drivers/media/platform/apple/prores/apple-prores.h +++ b/drivers/media/platform/apple/prores/apple-prores.h @@ -252,6 +252,14 @@ bool apr_ring_passed(u32 done, u32 end, u32 tail, u32 ring_bytes); bool apr_ring_tail_valid(u32 done, u32 tail, u32 head, u32 ring_bytes); u16 apr_next_job_id(u16 id); bool apr_job_id_done(u16 done_id, u16 id); + +enum apr_done_id { + APR_DONE_ID_NONE, /* nothing finished since the reset */ + APR_DONE_ID_ISSUED, /* an id the driver issued */ + APR_DONE_ID_FUTURE, /* an id not issued yet: the ring is hung */ +}; + +enum apr_done_id apr_job_id_check(u16 done_id, u16 next_id); bool apr_jobs_full(unsigned int jobs, unsigned int encodes); void apr_ring_write(u8 *ring, u32 ring_bytes, u32 ptr, const u8 *desc, u32 desc_bytes); From 26d5dbb5ef248c2c57157bb6cef70d91c1a7671d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 14:33:39 +1100 Subject: [PATCH 1347/1514] media: apple: prores: bound slice headers and the slice count The decode descriptor has no input length, so the engine reads as far as the frame's own sizes take it. apr_parse_frame() already holds the frame size, frame and picture header sizes, picture sizes, slice table and slice sizes to the payload, but two in-band fields the engine may also follow were never checked: - the picture header's slice count, which could ask for more slice table entries than the picture geometry gives; - each slice header, whose coded Y and Cb sizes (and Cr size, with alpha) could run past the end of the slice and so, for the last slice, past the buffer. Accept a slice count of 0, which our encoder writes, or the count the geometry gives. Require every slice header to fit its slice (8 bytes with alpha, where the Cr size is explicit, 6 otherwise) and its coded component sizes to fit the rest of the slice. Every ffmpeg-made test clip and every frame from the hardware encoder passes these checks. Read each slice size once so that the parse itself stays inside the payload even if userspace rewrites the buffer while it runs. Give the KUnit fixture valid 6-byte slice headers. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 43 ++++++++++++++----- .../platform/apple/prores/apple-prores-test.c | 5 ++- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 3ab8e6ca73dd39..c0f2015945c922 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -558,23 +558,34 @@ EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); /* Slice-size entries copied per block; 256 bytes of stack. */ #define APR_SLICE_CHUNK 128 +/* + * The decode descriptor carries no input length: the engine follows the + * frame's own sizes. Every size it consumes must therefore be checked against + * the payload here, before the engine is programmed. Each field is read once + * into a local so that the parse itself stays in bounds even if the buffer + * changes under it. + */ static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, - u32 height, bool interlaced, u32 max_slices, - u32 *picture_size, u32 *slices) + u32 height, bool interlaced, bool alpha, + u32 max_slices, u32 *picture_size, u32 *slices) { - u32 header, size, table_bytes, data_bytes = 0, min_size; - u32 log2_slice, field_height, i; + u32 header, size, table_bytes, pos, min_size, coded, count; + u32 log2_slice, field_height, slice_header, i; if (bytes < 8) return -EINVAL; header = data[0] >> 3; size = get_unaligned_be32(data + 1); + count = get_unaligned_be16(data + 5); log2_slice = data[7] >> 4; if (header < 8 || header > size || size > bytes || log2_slice > 3 || (data[7] & 0xf)) return -EINVAL; field_height = interlaced ? DIV_ROUND_UP(height, 2) : height; *slices = apr_slice_count(width, field_height, log2_slice); + /* Our encoder writes 0 here; anything else must match the geometry. */ + if (count && count != *slices) + return -EINVAL; if (*slices < 9 || *slices > max_slices || check_mul_overflow(*slices, 2U, &table_bytes) || check_add_overflow(header, table_bytes, &min_size) || @@ -583,22 +594,34 @@ static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, /* * The decoder's source buffers are mapped uncached, where each load is * a fabric round trip: copy the table in blocks, then walk the copy. + * A slice header gives the coded Y and Cb sizes, and the Cr size too + * when the frame has alpha; the rest of the slice is Cr (or alpha). */ + slice_header = alpha ? 8 : 6; + pos = min_size; for (i = 0; i < *slices; i += APR_SLICE_CHUNK) { __be16 chunk[APR_SLICE_CHUNK]; u32 n = min(*slices - i, (u32)APR_SLICE_CHUNK), j; memcpy(chunk, data + header + 2 * i, 2 * n); for (j = 0; j < n; j++) { - u32 slice = be16_to_cpu(chunk[j]); + u32 slice = be16_to_cpu(chunk[j]), hdr; + u8 sh[8]; - if (slice < 6 || - check_add_overflow(data_bytes, slice, &data_bytes)) + if (slice < slice_header || slice > size - pos) return -EINVAL; + memcpy(sh, data + pos, slice_header); + hdr = sh[0] >> 3; + coded = get_unaligned_be16(sh + 2) + + get_unaligned_be16(sh + 4); + if (alpha) + coded += get_unaligned_be16(sh + 6); + if (hdr < slice_header || hdr > slice || + coded > slice - hdr) + return -EINVAL; + pos += slice; } } - if (data_bytes > size - min_size) - return -EINVAL; *picture_size = size; return 0; } @@ -649,7 +672,7 @@ int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info) info->picture_offset[i] = offset; ret = apr_parse_picture(data + offset, frame_size - offset, info->width, info->height, - info->pictures == 2, + info->pictures == 2, info->alpha, i ? 16384 : 262144, &info->picture_size[i], &info->slices[i]); if (ret) diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index 53dc5c0abfd99c..b3b1216241a297 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -680,8 +680,11 @@ static u8 *apr_test_bitstream_size(struct kunit *test, u32 width, u32 height, put_unaligned_be32(picture_size, picture + 1); put_unaligned_be16(slices, picture + 5); picture[7] = 3 << 4; - for (i = 0; i < slices; i++) + for (i = 0; i < slices; i++) { put_unaligned_be16(6, picture + 8 + 2 * i); + /* A 6-byte slice header with empty Y and Cb data. */ + picture[8 + 2 * slices + 6 * i] = 6 << 3; + } offset += picture_size; } *bytes = frame_size; From 05cb72873182f579847f0b2545997139e82edd07 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 14:33:40 +1100 Subject: [PATCH 1348/1514] media: apple: prores: test decoder frames that point past their buffer The decode descriptor carries no input length, so a frame must not get past apr_parse_frame() if any size the engine follows points beyond the queued payload. Add KUnit cases for frames that do: a picture size 1 byte, 64 KiB and 4 GiB past the buffer; a frame size larger than bytesused; a payload truncated by one byte; a frame header past the frame; a slice table ending past the picture; a slice count asking for more table entries; slice sizes summing one byte past the picture; slice headers whose coded sizes run past their slice; and a bottom-field picture or slice past the buffer. The exact-fit frame and one that ends on the boundary byte are accepted. Each frame is parsed from an allocation exactly as long as the payload, so with KASAN an over-read in the parser is reported as well. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-test.c | 260 ++++++++++++++++++ 1 file changed, 260 insertions(+) diff --git a/drivers/media/platform/apple/prores/apple-prores-test.c b/drivers/media/platform/apple/prores/apple-prores-test.c index b3b1216241a297..b2f1f22c75d82c 100644 --- a/drivers/media/platform/apple/prores/apple-prores-test.c +++ b/drivers/media/platform/apple/prores/apple-prores-test.c @@ -762,6 +762,258 @@ static void apr_test_parse_many_slices(struct kunit *test) KUNIT_EXPECT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); } +/* + * The decode descriptor has no input length, so the engine reads as far as the + * frame's own sizes say. Each of these frames points past its payload and + * must be rejected before a descriptor is built. Every frame is parsed from an + * allocation exactly as long as the payload, so an over-read is a KASAN error. + * + * Progressive fixture: frame header at 8, picture at 28 (8-byte header, + * 45-entry slice table, 45 slices of 6 bytes), 396 bytes in all. + */ +#define APR_TP_PIC 28U +#define APR_TP_SLICES 45U +#define APR_TP_TABLE (APR_TP_PIC + 8) +#define APR_TP_DATA (APR_TP_TABLE + 2 * APR_TP_SLICES) +#define APR_TP_SIZE (8 + 8 * APR_TP_SLICES) +#define APR_TP_BYTES (APR_TP_PIC + APR_TP_SIZE) + +/* Parse the first @bytes of @frame from a buffer exactly that long. */ +static int apr_test_parse_at(struct kunit *test, const u8 *frame, size_t bytes) +{ + struct apr_prores_info info; + u8 *copy = kunit_kmalloc(test, bytes, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, copy); + memcpy(copy, frame, bytes); + return apr_parse_frame(copy, bytes, &info); +} + +/* A progressive fixture with @extra zero bytes of room after it. */ +static u8 *apr_test_room(struct kunit *test, size_t extra, size_t *bytes) +{ + u8 *frame = apr_test_bitstream(test, false, bytes); + u8 *room; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, *bytes, (size_t)APR_TP_BYTES); + room = kunit_kzalloc(test, *bytes + extra, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, room); + memcpy(room, frame, *bytes); + return room; +} + +static void apr_test_oob_exact_fit(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 1, &bytes); + struct apr_prores_info info; + u8 *last = frame + APR_TP_TABLE + 2 * (APR_TP_SLICES - 1); + + /* Header, table and slices fill the picture and the frame exactly. */ + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + KUNIT_EXPECT_EQ(test, info.picture_offset[0] + info.picture_size[0], + info.frame_size); + KUNIT_EXPECT_EQ(test, info.picture_size[0], APR_TP_SIZE); + + /* One more byte in the last slice, the picture and the frame fits too. */ + put_unaligned_be16(7, last); + put_unaligned_be32(APR_TP_SIZE + 1, frame + APR_TP_PIC + 1); + put_unaligned_be32(APR_TP_BYTES + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), 0); + + /* An encoder may leave the deprecated slice count at 0. */ + put_unaligned_be16(0, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), 0); +} + +static void apr_test_oob_frame_size(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 4096, &bytes); + + /* The frame claims more bytes than were queued. */ + put_unaligned_be32(bytes + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(bytes + 4096, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* bytesused one short of an otherwise valid frame. */ + put_unaligned_be32(bytes, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes - 1), -EINVAL); + + /* Truncated by one byte with the frame size rewritten to match. */ + put_unaligned_be32(bytes - 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes - 1), -EINVAL); + + /* Shorter than any frame header. */ + put_unaligned_be32(27, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, 27), -EINVAL); +} + +static void apr_test_oob_frame_header(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + + /* Frame header one byte past the frame, then filling it entirely. */ + put_unaligned_be16(bytes - 8 + 1, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(bytes - 8, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, frame + 8); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Quantisation matrices flagged but not inside the frame header. */ + put_unaligned_be16(20, frame + 8); + frame[8 + 19] = 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + frame[8 + 19] = 0; + + /* Picture header shorter than its fixed fields. */ + frame[APR_TP_PIC] = 7 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_picture_size(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *size = frame + APR_TP_PIC + 1; + + /* The picture runs one byte, 64 KiB and 4 GiB past the payload. */ + put_unaligned_be32(APR_TP_SIZE + 1, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(APR_TP_SIZE + SZ_64K, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Its slices must fit a picture one byte shorter. */ + put_unaligned_be32(APR_TP_SIZE - 1, size); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* Pictures must account for every byte of the frame. */ + frame = apr_test_room(test, 1, &bytes); + put_unaligned_be32(bytes + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes + 1), -EINVAL); +} + +static void apr_test_oob_slice_table(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u32 table_end = 8 + 2 * APR_TP_SLICES; + + /* The slice table ends one byte past the picture (and the frame). */ + put_unaligned_be32(table_end - 1, frame + APR_TP_PIC + 1); + put_unaligned_be32(APR_TP_PIC + table_end - 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, APR_TP_PIC + table_end - 1), + -EINVAL); + + /* The in-band slice count asks for one more table entry. */ + frame = apr_test_room(test, 0, &bytes); + put_unaligned_be16(APR_TP_SLICES + 1, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, frame + APR_TP_PIC + 5); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* + * Smaller slices mean more of them (75 at 320x240): the table the + * engine walks grows with log2_slice even with no in-band count. + */ + put_unaligned_be16(0, frame + APR_TP_PIC + 5); + frame[APR_TP_PIC + 7] = 2 << 4; + KUNIT_EXPECT_EQ(test, apr_slice_count(320, 240, 2), 75U); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_slice_sizes(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *table = frame + APR_TP_TABLE; + + /* The last slice ends one byte past the picture and the payload. */ + put_unaligned_be16(7, table + 2 * (APR_TP_SLICES - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(U16_MAX, table + 2 * (APR_TP_SLICES - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* A large early slice pushes every later one past the end. */ + put_unaligned_be16(6, table + 2 * (APR_TP_SLICES - 1)); + put_unaligned_be16(U16_MAX, table); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + + /* A slice too short for its own header. */ + put_unaligned_be16(5, table); + put_unaligned_be16(7, table + 2); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_slice_headers(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_room(test, 0, &bytes); + u8 *last = frame + APR_TP_DATA + 6 * (APR_TP_SLICES - 1); + + /* Coded Y and Cb data run one byte past the last slice. */ + put_unaligned_be16(1, last + 2); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(0, last + 2); + put_unaligned_be16(U16_MAX, last + 4); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(0, last + 4); + + /* A slice header longer than the slice. */ + last[0] = 7 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + last[0] = 6 << 3; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), 0); + + /* With alpha the Cr size is in the header too: 6 bytes is too short. */ + frame[8 + 12] = 3 << 6; + frame[8 + 17] = 1; + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + +static void apr_test_oob_second_field(struct kunit *test) +{ + size_t bytes; + u8 *frame = apr_test_bitstream(test, true, &bytes); + struct apr_prores_info info; + u32 second; + + KUNIT_ASSERT_NOT_NULL(test, frame); + KUNIT_ASSERT_EQ(test, apr_parse_frame(frame, bytes, &info), 0); + second = info.picture_offset[1]; + + /* The bottom field runs one byte past the payload. */ + put_unaligned_be32(info.picture_size[1] + 1, frame + second + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(U32_MAX, frame + second + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be32(info.picture_size[1], frame + second + 1); + + /* Its last slice ends one byte past the payload. */ + put_unaligned_be16(7, frame + second + 8 + 2 * (info.slices[1] - 1)); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); + put_unaligned_be16(6, frame + second + 8 + 2 * (info.slices[1] - 1)); + + /* The frame stops one byte into, and right at, the bottom field. */ + put_unaligned_be32(second + 1, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, second + 1), -EINVAL); + put_unaligned_be32(second, frame); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, second), -EINVAL); + put_unaligned_be32(bytes, frame); + + /* The top field grows by a byte, so the bottom one is misplaced. */ + put_unaligned_be32(info.picture_size[0] + 1, frame + info.picture_offset[0] + 1); + KUNIT_EXPECT_EQ(test, apr_test_parse_at(test, frame, bytes), -EINVAL); +} + static void apr_test_ring_accounting(struct kunit *test) { u8 *ring = kunit_kzalloc(test, APR_RING_BYTES, GFP_KERNEL); @@ -978,6 +1230,14 @@ static struct kunit_case apr_test_cases[] = { KUNIT_CASE(apr_test_parse_frame), KUNIT_CASE(apr_test_parse_interlaced), KUNIT_CASE(apr_test_parse_many_slices), + KUNIT_CASE(apr_test_oob_exact_fit), + KUNIT_CASE(apr_test_oob_frame_size), + KUNIT_CASE(apr_test_oob_frame_header), + KUNIT_CASE(apr_test_oob_picture_size), + KUNIT_CASE(apr_test_oob_slice_table), + KUNIT_CASE(apr_test_oob_slice_sizes), + KUNIT_CASE(apr_test_oob_slice_headers), + KUNIT_CASE(apr_test_oob_second_field), KUNIT_CASE(apr_test_ring_accounting), KUNIT_CASE(apr_test_ring_space), KUNIT_CASE(apr_test_ring_tail), From 4133514106e46c55fb5eb5abcc18c053d3ece1f4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 20 Nov 2026 23:53:52 +1100 Subject: [PATCH 1349/1514] media: apple: prores: mark the decoder's coded format DYN_RESOLUTION The decoder sends V4L2_EVENT_SOURCE_CHANGE when the stream's size or chroma changes, but its OUTPUT format description only carried V4L2_FMT_FLAG_COMPRESSED. The uAPI defines V4L2_FMT_FLAG_DYN_RESOLUTION for a stateful decoder that does this. Without the flag, GStreamer's v4l2 decoder sets up the CAPTURE queue before the first event and then takes that event as a mid-stream resolution change. It mistakes the real end-of-stream LAST buffer for the end of that change and waits forever, so every v4l2proresdec pipeline hangs at EOS even though its output is complete. FFmpeg does not look at the flag. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/prores/apple-prores-drv.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index c03fbb8a8d6c3b..2c6d2b2ec7f07f 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -2016,7 +2016,8 @@ static int apr_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc * if (f->index) return -EINVAL; f->pixelformat = V4L2_PIX_FMT_PRORES; - f->flags = V4L2_FMT_FLAG_COMPRESSED; + /* Size and chroma changes are reported with SOURCE_CHANGE. */ + f->flags = V4L2_FMT_FLAG_COMPRESSED | V4L2_FMT_FLAG_DYN_RESOLUTION; return 0; } if (f->index >= ARRAY_SIZE(apr_raw_fmts)) From 2d4490f07d1e6c73bd85c3971a19cd70e8a47844 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:22:29 +1100 Subject: [PATCH 1350/1514] media: apple: prores: take nothing off a hung ring before the reset When apr_take_done() finds a tail outside the ring or a finished id that was never issued, it marks the ring hung and queues the watchdog, which fails every job and resets the engine before their buffers go back. Four paths broke that order: - the engine interrupt stayed enabled, and apr_take_done() did not check the flag, so a second interrupt before the watchdog ran retired jobs by the untrusted ST1 id and handed their buffers back to vb2 while the engine might still use them; - the watchdog itself called apr_take_done() on a hung ring; - if that left the ring empty, the watchdog returned early, skipping the reset and leaving the flag set for the next job; - device_run only waited for a reset in progress, so a job could be published into the hung ring before the watchdog took the lock. Mask the engine interrupt when the ring is declared hung, take no completions while it is, and have the watchdog reset a hung ring even when no job is left in it. device_run now waits until the ring is neither hung nor being reset. A runtime suspend powers the engine off, which resets it, so it clears the flag too. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-drv.c | 51 ++++++++++++++----- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 2c6d2b2ec7f07f..e5e7cc71aa0f18 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1515,6 +1515,16 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) v4l2_m2m_job_finish(apr->m2m_dev, m2m); } +/* + * The ring state is inconsistent: no completion may be trusted until the + * watchdog has reset the engine. Called with hw_lock held. + */ +static void apr_set_hung(struct apr_dev *apr) +{ + apr->hung = true; + apr_write(apr, APR_REG_IRQ_ENABLE, 0); +} + /* * Move the jobs the engine has finished, oldest first, to @out (room for * APR_MAX_INFLIGHT). Returns false if the engine raised nothing. Called with @@ -1530,7 +1540,9 @@ static void apr_finish_job(struct apr_dev *apr, struct apr_ctx *ctx, int err) * job finished since the reset, which is no progress; an id the driver has * not issued yet means the engine and the ring disagree, so the ring is * declared hung and the watchdog resets the engine before any buffer goes - * back. An encode has no id and retires on DONE once the tail passed it. + * back. From then on nothing is taken off the ring here: the engine's + * interrupt is masked, and the watchdog fails every job after the reset. + * An encode has no id and retires on DONE once the tail passed it. * A DONE still latched after the last job was taken here would make a new * encode look finished as soon as it is fetched, so device_run clears the * status before it publishes into an empty ring. @@ -1546,6 +1558,8 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, u16 done_id; *n = 0; + if (apr->hung) + return false; status = apr_read(apr, APR_REG_IRQ_STATUS); if (!(status & (APR_IRQ_DONE | APR_IRQ_ERROR))) return false; @@ -1579,7 +1593,7 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, if (!apr_ring_tail_valid(apr->done, tail, apr->head, ring_bytes)) { dev_err_ratelimited(apr->dev, "tail %#x outside %#x..%#x\n", tail, apr->done, apr->head); - apr->hung = true; + apr_set_hung(apr); return true; } /* Read after the W1C: a job finishing later raises DONE again. */ @@ -1588,7 +1602,7 @@ static bool apr_take_done(struct apr_dev *apr, struct apr_job *out, if (state == APR_DONE_ID_FUTURE && apr->njobs > apr->nencodes) { dev_err_ratelimited(apr->dev, "finished id %#x not issued yet, next %#x\n", done_id, apr->next_id); - apr->hung = true; + apr_set_hung(apr); return true; } while (apr->njobs) { @@ -1635,12 +1649,15 @@ static irqreturn_t apr_irq(int irq, void *data) bool handled = false, hung; spin_lock(&apr->hw_lock); - /* Registers are only reachable while the engine is powered. */ + /* + * Registers are only reachable while the engine is powered. A hung + * ring masked the interrupt; one already in flight is ours. + */ if (apr->ring_ready) - handled = apr_take_done(apr, done, &n); + handled = apr_take_done(apr, done, &n) || apr->hung; held = apr_take_held(apr); hung = apr->hung; - if (!apr->njobs) + if (!apr->njobs && !hung) cancel_delayed_work(&apr->watchdog); spin_unlock(&apr->hw_lock); if (hung) @@ -1666,11 +1683,12 @@ static void apr_watchdog(struct work_struct *work) unsigned int n = 0; spin_lock_irqsave(&apr->hw_lock, flags); - if (!apr->njobs) { + /* A hung ring is reset even when no job is left in it. */ + if (!apr->njobs && !apr->hung) { spin_unlock_irqrestore(&apr->hw_lock, flags); return; } - if (apr->ring_ready && apr_take_done(apr, done, &n) && n) + if (!apr->hung && apr->ring_ready && apr_take_done(apr, done, &n) && n) dev_warn_once(apr->dev, "completion found without an interrupt\n"); if (!apr->hung && (!apr->njobs || time_before(jiffies, apr->progress + @@ -1778,10 +1796,15 @@ static void apr_device_run(void *priv) } spin_lock_irqsave(&apr->hw_lock, flags); - /* An encode has no job id, so it only runs alone in the ring. */ - while (apr->resetting || (!ctx->decode && apr->njobs)) { + /* + * Nothing enters a hung ring or one being reset; the watchdog clears + * both and wakes idle_wq. An encode has no job id, so it only runs + * alone in the ring. + */ + while (apr->hung || apr->resetting || (!ctx->decode && apr->njobs)) { spin_unlock_irqrestore(&apr->hw_lock, flags); - wait_event(apr->idle_wq, !READ_ONCE(apr->resetting) && + wait_event(apr->idle_wq, !READ_ONCE(apr->hung) && + !READ_ONCE(apr->resetting) && (ctx->decode || !READ_ONCE(apr->njobs))); spin_lock_irqsave(&apr->hw_lock, flags); } @@ -2558,9 +2581,13 @@ static int apr_runtime_suspend(struct device *dev) struct apr_dev *apr = dev_get_drvdata(dev); unsigned long flags; - /* Registers do not survive the power domain going off. */ + /* + * Registers do not survive the power domain going off, which resets + * the engine: a ring found hung with no job left needs nothing more. + */ spin_lock_irqsave(&apr->hw_lock, flags); apr->ring_ready = false; + apr->hung = false; spin_unlock_irqrestore(&apr->hw_lock, flags); return 0; } From 4f35f94059f54cc7a34a61bc8a65eceb89b86a68 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:23:47 +1100 Subject: [PATCH 1351/1514] media: apple: prores: decode from a driver-owned copy of each frame The decode descriptor has no input length: the engine follows the frame's in-band sizes (frame and picture size, the slice table and each slice header). Those sizes were checked once, in buf_prepare, on the OUTPUT buffer itself, which userspace can still write while the buffer is queued and while the job sits in the ring, up to eight jobs deep: it is an MMAP buffer or a DMABUF another process may hold. Rewriting a size after QBUF let the engine read up to several GiB past the buffer's IOVA. Every context of both nodes shares the engine's DART, so that read could land in another context's buffers, such as another user's encode source frames, and decode them into the attacker's CAPTURE buffer, or fault on an unmapped IOVA and reset the engine under every other context's jobs. Give each slot of the job FIFO a driver-owned source copy. device_run copies the frame into the copy of the slot its job will take, parses that copy and points DD_INPUT at it; the engine never reads the OUTPUT buffer. Only device_run, which v4l2-m2m runs one at a time and only with room in the FIFO, fills a copy, and the engine is done with a slot's copy once its job is taken off the ring or the engine is reset. The copies are cached non-contiguous DMA allocations, so the parse runs on cached memory, with a quarter of headroom so a stream rarely reallocates them; they are freed when the engine runtime-suspends. At most APR_MAX_INFLIGHT copies exist per engine. The parse at QBUF stays, for the source-change check and to fail a malformed frame early; a frame changed after QBUF so that it no longer parses fails its own job. device_run also checks that the CAPTURE buffer is large enough for the current format. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-desc.c | 7 +- .../platform/apple/prores/apple-prores-drv.c | 115 ++++++++++++++++-- 2 files changed, 112 insertions(+), 10 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index c0f2015945c922..45ef3a3e3210bf 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -561,9 +561,10 @@ EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); /* * The decode descriptor carries no input length: the engine follows the * frame's own sizes. Every size it consumes must therefore be checked against - * the payload here, before the engine is programmed. Each field is read once - * into a local so that the parse itself stays in bounds even if the buffer - * changes under it. + * the payload here, before the engine is programmed, and on a copy userspace + * cannot write (see apr_fill_decode_frame()). Each field is read once into a + * local, so that a parse of a buffer that changes under it, as at QBUF, still + * stays in bounds. */ static int apr_parse_picture(const u8 *data, u32 bytes, u32 width, u32 height, bool interlaced, bool alpha, diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index e5e7cc71aa0f18..363aeaf9594f45 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -1126,9 +1127,9 @@ struct apr_ctx; /* * A source buffer of the decoder. The frame is parsed once, when it is - * queued; job_ready, the source-change check and device_run then use the - * cached result instead of walking the slice table of the (uncached) buffer - * again each time. + * queued, for the source-change check and to fail a malformed frame early. + * The engine never reads this buffer: userspace may still write it, so + * device_run copies the frame and parses and programs the copy. */ struct apr_buf { struct v4l2_m2m_buffer m2m; /* first: vb2 and m2m embed this */ @@ -1141,6 +1142,18 @@ static struct apr_buf *to_apr_buf(struct vb2_v4l2_buffer *vbuf) return container_of(vbuf, struct apr_buf, m2m.vb); } +/* + * A driver-owned copy of one decoder source frame, the only input the engine + * reads. The decode descriptor has no input length: the engine follows the + * frame's in-band sizes, which are checked on this copy, out of userspace's + * reach, before the descriptor points at it. + */ +struct apr_bounce { + struct sg_table *sgt; + void *vaddr; + size_t size; +}; + /* A job in the ring; its buffers left the m2m queues when it was published. */ struct apr_job { struct apr_ctx *ctx; @@ -1184,6 +1197,13 @@ struct apr_dev { spinlock_t hw_lock; /* protects the fields below */ struct apr_job jobs[APR_MAX_INFLIGHT]; /* in ring order */ + /* + * Source copy of the decode job in the jobs[] slot of the same index. + * Not under hw_lock: only device_run, which m2m runs one at a time, + * fills the next free slot's copy, and completions free slots in order + * without changing which slot is next. + */ + struct apr_bounce bounce[APR_MAX_INFLIGHT]; unsigned int job_first; /* oldest job in jobs[] */ unsigned int njobs; /* jobs the engine owns */ unsigned int nencodes; /* encode jobs among them */ @@ -1387,18 +1407,89 @@ static int apr_parse_src(struct vb2_v4l2_buffer *src, return 0; } +static void apr_bounce_free(struct apr_dev *apr, struct apr_bounce *b) +{ + if (!b->sgt) + return; + dma_vunmap_noncontiguous(apr->dev, b->vaddr); + dma_free_noncontiguous(apr->dev, b->size, b->sgt, DMA_TO_DEVICE); + *b = (struct apr_bounce){}; +} + +/* Called once no job is in the ring, from runtime suspend and removal. */ +static void apr_bounce_free_all(struct apr_dev *apr) +{ + unsigned int i; + + for (i = 0; i < APR_MAX_INFLIGHT; i++) + apr_bounce_free(apr, &apr->bounce[i]); +} + +/* + * Make @b hold at least @bytes. Frame sizes vary within a stream, so a copy + * that grows keeps a quarter in hand and is rarely reallocated. CPU access + * is cached; the engine sees one IOVA range through its DART. + */ +static int apr_bounce_reserve(struct apr_dev *apr, struct apr_bounce *b, + size_t bytes) +{ + size_t size; + + if (b->size >= bytes) + return 0; + apr_bounce_free(apr, b); + size = PAGE_ALIGN(max_t(size_t, SZ_1M, bytes + bytes / 4)); + b->sgt = dma_alloc_noncontiguous(apr->dev, size, DMA_TO_DEVICE, + GFP_KERNEL, 0); + if (!b->sgt) + return -ENOMEM; + b->size = size; + b->vaddr = dma_vmap_noncontiguous(apr->dev, size, b->sgt); + if (!b->vaddr || b->sgt->nents != 1) { + if (b->vaddr) + dma_vunmap_noncontiguous(apr->dev, b->vaddr); + dma_free_noncontiguous(apr->dev, size, b->sgt, DMA_TO_DEVICE); + *b = (struct apr_bounce){}; + return -ENOMEM; + } + return 0; +} + +/* + * Copy @src's frame into @b, parse the copy and describe a decode of it. + * Userspace keeps write access to @src while it is queued, so the sizes + * checked when it was queued are only a hint: everything the engine follows + * comes from the copy, which nothing but the engine reads from now on. + */ static int apr_fill_decode_frame(struct apr_ctx *ctx, struct vb2_v4l2_buffer *src, struct vb2_v4l2_buffer *dst, + struct apr_bounce *b, struct apr_decode_frame *f) { const struct v4l2_pix_format_mplane *d = &ctx->dst_fmt; + struct apr_dev *apr = ctx->apr; struct apr_prores_info info; + u32 offset = src->vb2_buf.planes[0].data_offset; + u32 payload = vb2_get_plane_payload(&src->vb2_buf, 0); dma_addr_t output; u32 luma_stride; + u8 *data; int ret; - ret = apr_parse_src(src, &info); + ret = to_apr_buf(src)->parse_err; + if (ret) + return ret; + if (vb2_plane_size(&dst->vb2_buf, 0) < d->plane_fmt[0].sizeimage) + return -EINVAL; + data = vb2_plane_vaddr(&src->vb2_buf, 0); + if (!data || offset > payload) + return -EINVAL; + ret = apr_bounce_reserve(apr, b, payload - offset); + if (ret) + return ret; + memcpy(b->vaddr, data + offset, payload - offset); + ret = apr_parse_frame(b->vaddr, payload - offset, &info); if (ret) return ret; /* The non-RAW descriptor accepts one picture; field repacking is later. */ @@ -1407,6 +1498,7 @@ static int apr_fill_decode_frame(struct apr_ctx *ctx, if (info.width != d->width || info.height != d->height || info.chroma == 3 != ctx->raw->is444) return -EINVAL; + dma_sync_sgtable_for_device(apr->dev, b->sgt, DMA_TO_DEVICE); luma_stride = d->plane_fmt[0].bytesperline; output = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0); @@ -1416,8 +1508,7 @@ static int apr_fill_decode_frame(struct apr_ctx *ctx, .output = ctx->raw->input, .luma_stride = luma_stride, .chroma_stride = luma_stride * (ctx->raw->is444 ? 2 : 1), - .input = vb2_dma_contig_plane_dma_addr(&src->vb2_buf, 0) + - src->vb2_buf.planes[0].data_offset, + .input = sg_dma_address(b->sgt->sgl), .luma = output, .chroma = output + (u64)luma_stride * d->height, }; @@ -1763,6 +1854,7 @@ static void apr_device_run(void *priv) u8 desc[APR_ENCODE_DESC_BYTES]; u32 desc_bytes; unsigned long flags; + unsigned int slot; bool hold; void *out; int ret; @@ -1776,8 +1868,13 @@ static void apr_device_run(void *priv) apr_finish_job(apr, ctx, ret); return; } + /* device_run is entered with room in jobs[]; see apr_dev.bounce. */ + spin_lock_irqsave(&apr->hw_lock, flags); + slot = (apr->job_first + apr->njobs) % APR_MAX_INFLIGHT; + spin_unlock_irqrestore(&apr->hw_lock, flags); if (ctx->decode) { - ret = apr_fill_decode_frame(ctx, src, dst, &decode); + ret = apr_fill_decode_frame(ctx, src, dst, &apr->bounce[slot], + &decode); desc_bytes = APR_DECODE_DESC_BYTES; } else { apr_fill_frame(ctx, src, dst, &f); @@ -1841,6 +1938,7 @@ static void apr_device_run(void *priv) apr_ring_write(apr->ring, ring_bytes, apr->head, desc, desc_bytes); apr->head = apr_ring_advance(apr->head, desc_bytes, ring_bytes); job = &apr->jobs[(apr->job_first + apr->njobs) % APR_MAX_INFLIGHT]; + WARN_ON(job != &apr->jobs[slot]); *job = (struct apr_job){ .ctx = ctx, .src = v4l2_m2m_src_buf_remove(m2m), @@ -2589,6 +2687,8 @@ static int apr_runtime_suspend(struct device *dev) apr->ring_ready = false; apr->hung = false; spin_unlock_irqrestore(&apr->hw_lock, flags); + /* Every job holds a runtime PM reference, so no copy is in use. */ + apr_bounce_free_all(apr); return 0; } @@ -2632,6 +2732,7 @@ static void apr_cleanup(void *data) if (apr->m2m_dev) v4l2_m2m_release(apr->m2m_dev); v4l2_device_unregister(&apr->v4l2_dev); + apr_bounce_free_all(apr); } /* From b578773c8eb27b0ea1fd3fe8d884e4c8f619a93f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:25:38 +1100 Subject: [PATCH 1352/1514] media: apple: prores: follow the stateful decoder's resolution change The decoder advertises V4L2_FMT_FLAG_DYN_RESOLUTION, but a frame of a new size queued while CAPTURE was set up raised SOURCE_CHANGE at QBUF time, before decode reached it, left the CAPTURE format at the old size while CAPTURE was busy, and never marked the last old-size CAPTURE buffer LAST. job_ready just stalled on the new frame. A client following the stateful decoder sequence (drain to LAST, STREAMOFF and G_FMT on CAPTURE) waited for a LAST that never came, or read the old format back. Handle a change where Documentation/userspace-api/media/v4l/dev-decoder.rst puts it, in device_run when decode reaches the frame: give back every earlier frame of the context, switch the OUTPUT and CAPTURE formats to the new geometry, queue SOURCE_CHANGE, and return the next CAPTURE buffer empty with LAST. The new frame stays first on OUTPUT and no job runs until CAPTURE is restarted or a START command resumes decoding; START now also clears vb2's LAST-dequeued state, so DQBUF works again after it. The formats change under hw_lock, which G_FMT and TRY_FMT take, as device_run does not hold vdev_lock. Before CAPTURE streams, the next frame to decode still sets the formats at QBUF, now including the CAPTURE format while CAPTURE buffers exist: device_run refuses a CAPTURE buffer smaller than the format needs. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-drv.c | 198 ++++++++++++------ 1 file changed, 139 insertions(+), 59 deletions(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 363aeaf9594f45..26381be02dc5c6 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1233,6 +1233,8 @@ struct apr_ctx { bool decode; bool source_valid; bool decode_444; + /* LAST went out for a resolution change: wait for CAPTURE to restart. */ + bool drc_pending; atomic_t inflight; /* jobs in the ring not yet given back to vb2 */ enum apr_profile stream_profile; /* fixed while OUTPUT streams */ u32 sequence; @@ -1396,17 +1398,6 @@ static void apr_fill_frame(struct apr_ctx *ctx, struct vb2_v4l2_buffer *src, }; } -static int apr_parse_src(struct vb2_v4l2_buffer *src, - struct apr_prores_info *info) -{ - struct apr_buf *buf = to_apr_buf(src); - - if (buf->parse_err) - return buf->parse_err; - *info = buf->info; - return 0; -} - static void apr_bounce_free(struct apr_dev *apr, struct apr_bounce *b) { if (!b->sgt) @@ -1835,6 +1826,58 @@ static void apr_watchdog(struct work_struct *work) v4l2_m2m_job_finish(apr->m2m_dev, held->fh.m2m_ctx); } +static const struct v4l2_event apr_source_change = { + .type = V4L2_EVENT_SOURCE_CHANGE, + .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, +}; + +static void apr_decode_set_source(struct apr_ctx *ctx, + const struct apr_prores_info *info); + +/* Does a parsed source frame need other CAPTURE buffers than the format's? */ +static bool apr_decode_differs(const struct apr_ctx *ctx, + const struct apr_prores_info *info) +{ + return info->width != ctx->dst_fmt.width || + info->height != ctx->dst_fmt.height || + (info->chroma == 3) != ctx->raw->is444; +} + +/* + * Decode reached a frame whose geometry differs from the CAPTURE format: + * the stateful decoder's dynamic resolution change. Every frame from before + * it is given back first; the next CAPTURE buffer then goes back empty with + * LAST, the formats switch to the new geometry and SOURCE_CHANGE is queued. + * The frame stays first on OUTPUT, and no job runs until CAPTURE is + * restarted (STREAMOFF and STREAMON) or a START command resumes decoding. + * Called from device_run; sleeps. + */ +static void apr_decode_resolution_change(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *src) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + struct vb2_v4l2_buffer *dst; + unsigned long flags; + + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + /* Formats change under hw_lock for the G_FMT and TRY_FMT readers. */ + spin_lock_irqsave(&apr->hw_lock, flags); + apr_decode_set_source(ctx, &to_apr_buf(src)->info); + WRITE_ONCE(ctx->drc_pending, true); + dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); + /* A query after the event sees the new format. */ + v4l2_event_queue_fh(&ctx->fh, &apr_source_change); + if (!WARN_ON(!dst)) { + vb2_set_plane_payload(&dst->vb2_buf, 0, 0); + dst->field = V4L2_FIELD_NONE; + dst->flags |= V4L2_BUF_FLAG_LAST; + v4l2_m2m_buf_done(dst, VB2_BUF_STATE_DONE); + } + v4l2_m2m_job_finish(apr->m2m_dev, m2m); +} + /* * Publish one job and, while the ring has room for another, finish the m2m * job at once so the next one is prepared while the engine works. When the @@ -1861,6 +1904,11 @@ static void apr_device_run(void *priv) src = v4l2_m2m_next_src_buf(m2m); dst = v4l2_m2m_next_dst_buf(m2m); + if (ctx->decode && !to_apr_buf(src)->parse_err && + apr_decode_differs(ctx, &to_apr_buf(src)->info)) { + apr_decode_resolution_change(ctx, src); + return; + } ret = pm_runtime_resume_and_get(apr->dev); if (ret < 0) { @@ -1970,20 +2018,12 @@ static void apr_device_run(void *priv) v4l2_m2m_job_finish(apr->m2m_dev, m2m); } +/* A frame of another geometry is device_run's resolution change. */ static int apr_job_ready(void *priv) { struct apr_ctx *ctx = priv; - struct vb2_v4l2_buffer *src; - struct apr_prores_info info; - if (!ctx->decode) - return 1; - src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); - if (!src || apr_parse_src(src, &info)) - return 1; - return info.width == ctx->dst_fmt.width && - info.height == ctx->dst_fmt.height && - (info.chroma == 3) == ctx->raw->is444; + return !READ_ONCE(ctx->drc_pending); } static void apr_job_abort(void *priv) @@ -2180,15 +2220,29 @@ static int apr_enum_framesizes(struct file *file, void *priv, return 0; } +/* + * A decoder's resolution change rewrites the formats from device_run, which + * does not hold vdev_lock; it holds hw_lock. + */ static int apr_g_fmt_out(struct file *file, void *priv, struct v4l2_format *f) { - f->fmt.pix_mp = apr_file_to_ctx(file)->src_fmt; + struct apr_ctx *ctx = apr_file_to_ctx(file); + unsigned long flags; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + f->fmt.pix_mp = ctx->src_fmt; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); return 0; } static int apr_g_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) { - f->fmt.pix_mp = apr_file_to_ctx(file)->dst_fmt; + struct apr_ctx *ctx = apr_file_to_ctx(file); + unsigned long flags; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + f->fmt.pix_mp = ctx->dst_fmt; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); return 0; } @@ -2212,11 +2266,18 @@ static int apr_try_fmt_cap(struct file *file, void *priv, struct v4l2_format *f) const struct apr_fmt *fmt; if (ctx->decode) { - fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); - if (!fmt || (ctx->source_valid && fmt->is444 != ctx->decode_444)) - fmt = &apr_raw_fmts[ctx->decode_444 ? 3 : 1]; + unsigned long flags; + bool valid, is444; + + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + valid = ctx->source_valid; + is444 = ctx->decode_444; f->fmt.pix_mp.width = ctx->src_fmt.width; f->fmt.pix_mp.height = ctx->src_fmt.height; + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); + fmt = apr_find_raw(f->fmt.pix_mp.pixelformat); + if (!fmt || (valid && fmt->is444 != is444)) + fmt = &apr_raw_fmts[is444 ? 3 : 1]; apr_fill_raw(&f->fmt.pix_mp, fmt); return 0; } @@ -2322,7 +2383,14 @@ static int apr_decoder_cmd(struct file *file, void *priv, return ret; if (dc->cmd == V4L2_DEC_CMD_STOP) return apr_stop_cmd(file, ctx, dc); - return v4l2_m2m_ioctl_decoder_cmd(file, priv, dc); + ret = v4l2_m2m_ioctl_decoder_cmd(file, priv, dc); + if (ret) + return ret; + /* START resumes after a drain or a resolution change. */ + WRITE_ONCE(ctx->drc_pending, false); + vb2_clear_last_buffer_dequeued(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx)); + v4l2_m2m_try_schedule(ctx->fh.m2m_ctx); + return 0; } static const struct v4l2_ioctl_ops apr_ioctl_ops = { @@ -2434,45 +2502,54 @@ static int apr_buf_prepare(struct vb2_buffer *vb) return 0; } -static void apr_decode_source_change(struct apr_ctx *ctx, - struct vb2_v4l2_buffer *vbuf) +/* Make a parsed frame's geometry the stream's. Called with hw_lock held. */ +static void apr_decode_set_source(struct apr_ctx *ctx, + const struct apr_prores_info *info) { - struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; - struct apr_prores_info info; - bool changed; unsigned int i; - if (apr_parse_src(vbuf, &info)) - return; - changed = !ctx->source_valid || ctx->src_fmt.width != info.width || - ctx->src_fmt.height != info.height || - ctx->decode_444 != (info.chroma == 3); - if (!changed) - return; ctx->source_valid = true; - ctx->decode_444 = info.chroma == 3; - ctx->src_fmt.width = info.width; - ctx->src_fmt.height = info.height; - if (!vb2_is_busy(v4l2_m2m_get_dst_vq(m2m))) { - for (i = 0; i < ARRAY_SIZE(apr_raw_fmts); i++) { - if (apr_raw_fmts[i].is444 == ctx->decode_444 && - apr_raw_fmts[i].bytes == ctx->raw->bytes) { - ctx->raw = &apr_raw_fmts[i]; - break; - } + ctx->decode_444 = info->chroma == 3; + ctx->src_fmt.width = info->width; + ctx->src_fmt.height = info->height; + for (i = 0; i < ARRAY_SIZE(apr_raw_fmts); i++) { + if (apr_raw_fmts[i].is444 == ctx->decode_444 && + apr_raw_fmts[i].bytes == ctx->raw->bytes) { + ctx->raw = &apr_raw_fmts[i]; + break; } - ctx->dst_fmt.width = info.width; - ctx->dst_fmt.height = info.height; - apr_fill_raw(&ctx->dst_fmt, ctx->raw); } - { - const struct v4l2_event event = { - .type = V4L2_EVENT_SOURCE_CHANGE, - .u.src_change.changes = V4L2_EVENT_SRC_CH_RESOLUTION, - }; + /* A new geometry starts from the minimum stride. */ + if (ctx->dst_fmt.width != info->width || + ctx->dst_fmt.height != info->height) + ctx->dst_fmt.plane_fmt[0].bytesperline = 0; + ctx->dst_fmt.width = info->width; + ctx->dst_fmt.height = info->height; + apr_fill_raw(&ctx->dst_fmt, ctx->raw); +} - v4l2_event_queue_fh(&ctx->fh, &event); - } +/* + * Before CAPTURE streams, the next frame to decode sets the formats, and a + * new geometry is reported at once (initial setup, or a change while CAPTURE + * is stopped). While CAPTURE streams, device_run handles a change when + * decode reaches the frame, after the frames queued before it. + */ +static void apr_decode_source_change(struct apr_ctx *ctx, + struct vb2_v4l2_buffer *vbuf) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_buf *buf = to_apr_buf(vbuf); + unsigned long flags; + + if (buf->parse_err || vb2_is_streaming(v4l2_m2m_get_dst_vq(m2m))) + return; + if (ctx->source_valid && (v4l2_m2m_num_src_bufs_ready(m2m) || + !apr_decode_differs(ctx, &buf->info))) + return; + spin_lock_irqsave(&ctx->apr->hw_lock, flags); + apr_decode_set_source(ctx, &buf->info); + spin_unlock_irqrestore(&ctx->apr->hw_lock, flags); + v4l2_event_queue_fh(&ctx->fh, &apr_source_change); } static void apr_buf_queue(struct vb2_buffer *vb) @@ -2532,6 +2609,9 @@ static void apr_stop_streaming(struct vb2_queue *q) break; v4l2_m2m_buf_done(vbuf, VB2_BUF_STATE_ERROR); } + /* Restarting CAPTURE ends a resolution change. */ + if (!V4L2_TYPE_IS_OUTPUT(q->type)) + WRITE_ONCE(ctx->drc_pending, false); v4l2_m2m_update_stop_streaming_state(ctx->fh.m2m_ctx, q); if (V4L2_TYPE_IS_OUTPUT(q->type) && !ctx->decode) v4l2_ctrl_grab(ctx->profile, false); From faceb796a9f9301c93a0e322cb4071a7e4a94d61 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 02:26:06 +1100 Subject: [PATCH 1353/1514] media: apple: prores: say decode runs on every engine, one slice bound Kconfig and the decode descriptor comment still said decode exists only on T6000 and T8140, but every APR variant has had a decoder node since "media: apple: prores: give every APR engine a decoder node". The frame parser bounded the second field of an interlaced frame to 16384 slices and the first to 262144, with no reason given: both fields have the same geometry. Use one named bound for both. Interlaced frames are still refused before a descriptor is built, so nothing decodes differently. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/prores/Kconfig | 3 +-- .../media/platform/apple/prores/apple-prores-desc.c | 11 ++++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/drivers/media/platform/apple/prores/Kconfig b/drivers/media/platform/apple/prores/Kconfig index ce2f49498cebc2..f600080612f276 100644 --- a/drivers/media/platform/apple/prores/Kconfig +++ b/drivers/media/platform/apple/prores/Kconfig @@ -15,8 +15,7 @@ config VIDEO_APPLE_PRORES the built-in initialization rows; T8132 has no built-in rows and binds only with apple/prores-t8132-init.bin. It encodes 8 and 16 bit 4:2:2 and 4:4:4 frames to ProRes 422 Proxy, LT, 422, HQ, - 4444 and 4444 XQ, and on engines with the decode descriptor - (T6000, T8140) also decodes those profiles. + 4444 and 4444 XQ, and decodes those profiles, on every engine. To compile this driver as a module, choose M here: the module will be called apple-prores. diff --git a/drivers/media/platform/apple/prores/apple-prores-desc.c b/drivers/media/platform/apple/prores/apple-prores-desc.c index 45ef3a3e3210bf..f73923e5848069 100644 --- a/drivers/media/platform/apple/prores/apple-prores-desc.c +++ b/drivers/media/platform/apple/prores/apple-prores-desc.c @@ -474,7 +474,7 @@ int apr_build_desc_v0(const struct apr_frame *f, u8 *desc) } EXPORT_SYMBOL_IF_KUNIT(apr_build_desc_v0); -/* Non-RAW decode descriptor version 0 (T6000 and T8140). */ +/* Non-RAW decode descriptor version 0, used on every APR variant. */ #define DD_COMMAND 0x000 #define DD_COMMAND_BFF BIT(14) #define DD_COMMAND_IRQ BIT(12) @@ -557,6 +557,11 @@ EXPORT_SYMBOL_IF_KUNIT(apr_build_decode_desc); /* Slice-size entries copied per block; 256 bytes of stack. */ #define APR_SLICE_CHUNK 128 +/* + * Slices per picture, which bounds the CPU walk of the slice table. Both + * fields of an interlaced frame have the same geometry and the same bound. + */ +#define APR_MAX_SLICES 262144 /* * The decode descriptor carries no input length: the engine follows the @@ -674,8 +679,8 @@ int apr_parse_frame(const u8 *data, size_t bytes, struct apr_prores_info *info) ret = apr_parse_picture(data + offset, frame_size - offset, info->width, info->height, info->pictures == 2, info->alpha, - i ? 16384 : 262144, - &info->picture_size[i], &info->slices[i]); + APR_MAX_SLICES, &info->picture_size[i], + &info->slices[i]); if (ret) return ret; if (check_add_overflow(offset, info->picture_size[i], &offset)) From b5cc5906a9559bf88d8db47404ae0aa2c19fd7d8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 03:34:25 +1100 Subject: [PATCH 1354/1514] media: apple: prores: queue old CAPTURE buffers across a resolution change At a resolution change device_run switches the CAPTURE format before the client has seen SOURCE_CHANGE; the client is still dequeuing the last old-size frames and queues their buffers again. buf_prepare checked every CAPTURE buffer against the current format, so on a change to a larger size that QBUF failed with -EINVAL. dev-decoder.rst has the client queue those buffers as usual; one of them carries the change's LAST flag. On a Neo (T8140) a 1080p to 2160p and a 4:2:2 to 4:4:4 change failed this way; the downsizing changes passed only because the old buffers were large enough. Do not check a decoder's CAPTURE buffers against the current format at QBUF: queue_setup sized each for the format of its time. device_run gives back a buffer too small for the current format with ERROR and no payload, after the context's frames in the ring, and keeps the source frame queued for one that fits, instead of failing the frame. Signed-off-by: Ryan Murray --- .../platform/apple/prores/apple-prores-drv.c | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/prores/apple-prores-drv.c b/drivers/media/platform/apple/prores/apple-prores-drv.c index 26381be02dc5c6..76ee4183c0124a 100644 --- a/drivers/media/platform/apple/prores/apple-prores-drv.c +++ b/drivers/media/platform/apple/prores/apple-prores-drv.c @@ -1878,6 +1878,31 @@ static void apr_decode_resolution_change(struct apr_ctx *ctx, v4l2_m2m_job_finish(apr->m2m_dev, m2m); } +/* + * The next CAPTURE buffer predates a resolution change and cannot hold a + * frame of the current format: give it back with ERROR and no payload, + * after the context's frames in the ring, and leave the source frame queued + * for a buffer that fits. Called from device_run; sleeps. + */ +static void apr_decode_small_dst(struct apr_ctx *ctx) +{ + struct v4l2_m2m_ctx *m2m = ctx->fh.m2m_ctx; + struct apr_dev *apr = ctx->apr; + struct vb2_v4l2_buffer *dst; + unsigned long flags; + + wait_event(apr->idle_wq, !atomic_read(&ctx->inflight)); + spin_lock_irqsave(&apr->hw_lock, flags); + dst = v4l2_m2m_dst_buf_remove(m2m); + spin_unlock_irqrestore(&apr->hw_lock, flags); + if (!WARN_ON(!dst)) { + vb2_set_plane_payload(&dst->vb2_buf, 0, 0); + dst->field = V4L2_FIELD_NONE; + v4l2_m2m_buf_done(dst, VB2_BUF_STATE_ERROR); + } + v4l2_m2m_job_finish(apr->m2m_dev, m2m); +} + /* * Publish one job and, while the ring has room for another, finish the m2m * job at once so the next one is prepared while the engine works. When the @@ -1909,6 +1934,11 @@ static void apr_device_run(void *priv) apr_decode_resolution_change(ctx, src); return; } + if (ctx->decode && vb2_plane_size(&dst->vb2_buf, 0) < + ctx->dst_fmt.plane_fmt[0].sizeimage) { + apr_decode_small_dst(ctx); + return; + } ret = pm_runtime_resume_and_get(apr->dev); if (ret < 0) { @@ -2477,7 +2507,15 @@ static int apr_buf_prepare(struct vb2_buffer *vb) struct apr_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue); u32 size = apr_q_fmt(ctx, vb->type)->plane_fmt[0].sizeimage; - if (vb2_plane_size(vb, 0) < size) + /* + * A decoder's CAPTURE format may grow at a resolution change before + * the client has seen SOURCE_CHANGE, and the old buffers must still + * queue: the LAST buffer of the change is one of them. queue_setup + * sized them for the format of their time; device_run gives back one + * too small for the current format instead of decoding into it. + */ + if (vb2_plane_size(vb, 0) < size && + !(ctx->decode && !V4L2_TYPE_IS_OUTPUT(vb->type))) return -EINVAL; if (V4L2_TYPE_IS_OUTPUT(vb->type)) { if (ctx->decode) { From b56f3d399f8643d1f39886c85dea24bc2f3d205e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 01:36:32 +1100 Subject: [PATCH 1355/1514] drm/asahi: give the G14 27.2 firmware its power data and run the full GPU range Since #3091 the G14 GPU on firmware 27.2 has been capped at its first operating point (444 MHz): at the higher states the firmware stalled compute work under load (fetched > retired, no fault) and held the top voltage even when idle. The 27.2 builder left most of the firmware's power data zero. The 27.2 records keep that data in the 13.5 layout, and this driver already builds all of it for the 13.5 InitData: - Globals: HwDataShared1 at +0xec and HwDataShared2 at +0x1b4, which includes the G14 curves computed from each operating point's frequency and voltage. - Power record: the average-power filter at +0x10..+0x20 and HwDataShared3 at +0x4f0. - Hardware data: the 13.5 HwDataB words from the power sample period to the fragment count, at the chip id's distance (power sample period at +0xff4, fragment count at +0x10a4); the SRAM power coefficient of each operating point (sram_k); the identity state index map. Drop the second MHz series at +0x1924, which is not part of the block. - Globals +0x9b8/+0x9bc/+0x9c0, the compute back-off words that the M3 and M4 27.2 runtimes also set. Copy these values from the 13.5 InitData: same builders, same chip configuration and DT operating points, with no new constants. offset_of checks tie each destination to the 13.5 structures. With the data in place, publish the ceiling at Globals +0x98, as +0x88 and +0x8c already do. The firmware then governs the whole range itself: the rail follows the load (about 0.68-0.82 V instead of a fixed 0.94 V). Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 8 +- drivers/gpu/drm/asahi/gpu/v27_2.rs | 145 +++++++++++++++++++++++-- 2 files changed, 142 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index ab5c322a27a7b6..313607d3a6c702 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -76,15 +76,19 @@ impl GrowRequest { /// them (`m3_power_26`, `g16/fw/initdata`), with the 13.5 names: 0x24 relaxed compute kill /// timeout (ms), 0x78 command submission enabled, 0x998/0x99c/0x9a0 progress-check intervals /// of 3D/TA/compute (firmware polls), 0x9c8 compute context-switch timeout (ms), 0x9cc compute -/// kill timeout (ms), 0xe28. Left zero, the firmware's progress recovery (armed in HwDataB) +/// kill timeout (ms), 0x9b8/0x9bc/0x9c0 the compute back-off words (0x9bc is the G15 layout's +/// `cdm_backoff_timeout`), 0xe28. Left zero, the firmware's progress recovery (armed in HwDataB) /// times out TA and compute work that runs past a poll within a second or two. The TA interval /// is the 100 polls the M3 runtime uses for long vertex loops (`m3_config`), not 10. -pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 8] = [ +pub(crate) const GLOBALS_PROGRESS: [(usize, u32); 11] = [ (0x24, 3000), (0x78, 1), (0x998, 40), (0x99c, 100), (0x9a0, 250), + (0x9b8, 2), + (0x9bc, 40), + (0x9c0, 5), (0x9c8, 40), (0x9cc, 50), (0xe28, 3), diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 6c141adf218078..fc1514c61a8e44 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -42,9 +42,38 @@ const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; -/// Upper performance-state cap, in hundredths, at globals +0x98: the first state above idle. -/// Only this cap has run on hardware. -const STATE_CAP: u32 = 100; +/// Globals offsets of the 13.5 shared power tables (HwDataShared1 and HwDataShared2): the 27.2 +/// Globals carries them at these places, laid out field for field as in the 13.5 InitData. +const GLOBALS_SHARED1: usize = 0xec; +const GLOBALS_SHARED2: usize = 0x1b4; +const SHARED1_BYTES: usize = 0xa8; +const SHARED2_BYTES: usize = 0x510; +/// Power-record offset of the 13.5 HwDataShared3 (0x50 bytes). +const POWER_SHARED3: usize = 0x4f0; +const _: () = { + assert!(core::mem::size_of::() == SHARED1_BYTES); + assert!(core::mem::size_of::() == SHARED2_BYTES); + assert!(GLOBALS_SHARED1 + SHARED1_BYTES <= GLOBALS_SHARED2); + assert!(GLOBALS_SHARED2 + SHARED2_BYTES <= g14_v27_2_abi::GLOBALS_BYTES); + // The offsets put_shared1/put_shared2/put_curve write. + use core::mem::offset_of; + use fw::initdata::raw::{HwDataShared1 as S1, HwDataShared2 as S2, HwDataShared2Curve as C, + HwDataShared2G14 as G}; + assert!(offset_of!(S1, unk_44) == 0x40 && offset_of!(S1, unk_a4) == 0xa0 && offset_of!(S1, unk_a8) == 0xa4); + assert!(offset_of!(S2, unk_28) == 0x28 && offset_of!(S2, g14) == 0x38 && offset_of!(S2, unk_500) == 0x500); + assert!(offset_of!(G, unk_14) == 0x14 && offset_of!(G, unk_18) == 0x18); + assert!(offset_of!(G, curve1) == 0x38 && offset_of!(G, curve2) == 0x280); + assert!(offset_of!(C, t1) == 8 && offset_of!(C, t2) == 0x28 && offset_of!(C, t3) == 0x48); + assert!(core::mem::size_of::() == 0x248); + // The 13.5 HwDataB words copied at the chip id's distance land where the 27.2 block has + // them (power sample period +0xff4, fragment count +0x10a4). + use fw::initdata::raw::{HwDataBG14V13_5 as B13, HwDataBG14V27_2 as B27}; + assert!(offset_of!(B13, power_sample_period) + offset_of!(B27, chip_id) - offset_of!(B13, chip_id) == 0xff4); + assert!(offset_of!(B13, num_frags) + offset_of!(B27, chip_id) - offset_of!(B13, chip_id) == 0x10a4); + use fw::initdata::raw::HwDataShared3 as S3; + assert!(core::mem::size_of::() == 0x50 && offset_of!(S3, table) == 0xc && offset_of!(S3, unk_4c) == 0x4c); + assert!(POWER_SHARED3 + 0x50 <= 0x6a0); +}; /// Board facts the root needs, read from the device tree at probe. pub(crate) struct BoardV27_2 { @@ -89,6 +118,64 @@ fn put32(b: &mut [u8], at: usize, v: u32) { b[at..at + 4].copy_from_slice(&v.to_le_bytes()); } +/// The 13.5 HwDataShared1, field for field. +fn put_shared1(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared1) { + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 4 * i, *v as u32); + } + b[at + 0x40..at + 0xa0].copy_from_slice(&(*s.unk_44)[..]); + put32(b, at + 0xa0, s.unk_a4); + put32(b, at + 0xa4, s.unk_a8); +} + +/// The 13.5 HwDataShared2 curve, field for field. +fn put_curve(b: &mut [u8], at: usize, c: &fw::initdata::raw::HwDataShared2Curve) { + put32(b, at, c.unk_0); + put32(b, at + 4, c.unk_4); + for (i, v) in c.t1.iter().enumerate() { + b[at + 8 + 2 * i..at + 10 + 2 * i].copy_from_slice(&v.to_le_bytes()); + } + for (i, v) in c.t2.iter().enumerate() { + b[at + 0x28 + 2 * i..at + 0x2a + 2 * i].copy_from_slice(&v.to_le_bytes()); + } + for (row, values) in c.t3.iter().enumerate() { + for (i, v) in values.iter().enumerate() { + put32(b, at + 0x48 + 0x40 * row + 4 * i, *v as u32); + } + } +} + +/// The 13.5 HwDataShared3, field for field. +fn put_shared3(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared3) { + for (i, v) in [s.unk_0, s.unk_4, s.unk_8].into_iter().enumerate() { + put32(b, at + 4 * i, v); + } + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 0xc + 4 * i, *v); + } + put32(b, at + 0x4c, s.unk_4c); +} + +/// The 13.5 HwDataShared2, field for field (G14 curves included). +fn put_shared2(b: &mut [u8], at: usize, s: &fw::initdata::raw::HwDataShared2) { + for (i, v) in s.table.iter().enumerate() { + put32(b, at + 4 * i, *v as u32); + } + b[at + 0x28..at + 0x38].copy_from_slice(&(*s.unk_28)[..]); + for (i, v) in s.g14.unk_0.iter().enumerate() { + put32(b, at + 0x38 + 4 * i, *v); + } + put32(b, at + 0x4c, s.g14.unk_14); + for (i, v) in s.g14.unk_18.iter().enumerate() { + put32(b, at + 0x50 + 4 * i, *v); + } + put_curve(b, at + 0x70, &s.g14.curve1); + put_curve(b, at + 0x2b8, &s.g14.curve2); + for (i, v) in [s.unk_500, s.unk_504, s.unk_508, s.unk_50c].into_iter().enumerate() { + put32(b, at + 0x500 + 4 * i, v); + } +} + fn put64(b: &mut [u8], at: usize, v: u64) { b[at..at + 8].copy_from_slice(&v.to_le_bytes()); } @@ -965,6 +1052,23 @@ impl RootV27_2 { for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c].into_iter().enumerate() { put32(hw, chip + 4 * i, word); } + // From the power sample period to the fragment count, the 27.2 block keeps the 13.5 + // HwDataB words in order, at the chip id's distance: the firmware's power sampling + // period, the cache-flush and feature enables and the fragment count. + use core::mem::offset_of; + type Old = fw::initdata::raw::HwDataBG14V13_5; + let shift = chip - offset_of!(Old, chip_id); + for (at, value) in [ + (offset_of!(Old, power_sample_period), old.power_sample_period), + (offset_of!(Old, unk_49c), old.unk_49c), (offset_of!(Old, unk_4a0), old.unk_4a0), + (offset_of!(Old, unk_4a4), old.unk_4a4), (offset_of!(Old, unk_4c0), old.unk_4c0), + (offset_of!(Old, unk_4f0), old.unk_4f0), (offset_of!(Old, unk_4f4), old.unk_4f4), + (offset_of!(Old, unk_504), old.unk_504), (offset_of!(Old, unk_524), old.unk_524), + (offset_of!(Old, unk_534), old.unk_534), (offset_of!(Old, num_frags), old.num_frags), + ] { + put32(hw, at + shift, value); + } + put64(hw, offset_of!(Old, unk_4e0) + shift, old.unk_4e0.0); }); // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), @@ -987,8 +1091,10 @@ impl RootV27_2 { } put64(hw, 0x267c, u64::from(*core_mask)); put32(hw, 0x2684, id.total_active_cores); - // Operating points: power above the lowest state, and frequency above the base state, - // as percentages; MHz and the per-lane core and SRAM voltages. + // Operating points, in the 13.5 HwDataB order the 27.2 block keeps: power above the + // lowest state and frequency above the base state as f32 percentages, MHz, the per-lane + // core and SRAM voltages, the chip's SRAM power coefficient per state and the identity + // state index map. let top = states.len() - 1; if old_max_pstate(base)? as usize != top { return Err(EINVAL); } let baseline = states[0].pwr_mw; @@ -1012,15 +1118,17 @@ impl RootV27_2 { return Err(EINVAL); } let mhz = state.freq_hz / 1_000_000; - for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { - put32(hw, series + i * 4, mhz); - } + put32(hw, abi::COMMON26_HW_PERF_FREQUENCY + i * 4, mhz); + put32(hw, abi::COMMON26_HW_PERF_SCALE + i * 4, cfg.sram_k.to_bits()); for lane in 0..abi::COMMON26_HW_PERF_LANES { let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE + lane * 4; put32(hw, abi::COMMON26_HW_PERF_CORE_VOLTAGE + row, *mv); put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); } } + for index in 0..abi::COMMON26_HW_PERF_ROWS { + put32(hw, abi::COMMON26_HW_PERF_INDEX_MAP + index * 4, index as u32); + } crate::pgtable::clean_poc(hw.as_ptr(), hw.len()); put64(bytes, 0, hardware.gpu_va().get()); channels.push(hardware, GFP_KERNEL)?; @@ -1083,9 +1191,16 @@ impl RootV27_2 { data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); } let ceiling = pwr.perf_max_pstate * 100; - for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, STATE_CAP)] { + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling)] { put32(data, at, value); } + // The shared power tables the 13.5 InitData built from the chip configuration and + // the DT operating points (the G14 curves scale with each state's frequency and + // voltage). Left zero, the firmware runs the upper states without them. + base.hwdata_a.with(|a, _| { + put_shared1(data, GLOBALS_SHARED1, &a.hws1); + put_shared2(data, GLOBALS_SHARED2, &a.hws2); + }); put32(data, 0x6e, 1); // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. for (at, value) in g14_v27_2_abi::GLOBALS_PROGRESS { @@ -1117,6 +1232,18 @@ impl RootV27_2 { for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { put32(data, at, value); } + // The average-power filter and the third shared power table, as the 13.5 Globals + // carries them (built from the DT power values and the chip configuration). + graph.initdata.globals.with(|g, _| { + for (at, value) in [ + (0x10, g.avg_power_filter_tc_periods), (0x14, g.avg_power_ki_dt.to_bits()), + (0x18, g.avg_power_kp.to_bits()), (0x1c, g.avg_power_min_duty_cycle), + (0x20, g.avg_power_target_filter_tc), + ] { + put32(data, at, value); + } + put_shared3(data, POWER_SHARED3, &g.hws3); + }); let initial = controller.as_slice(); for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { From 5cdc59964af00fbf557ab95d35be532ff67fa1f9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 02:03:01 +1100 Subject: [PATCH 1356/1514] drm/asahi: g16: accept the boot loader's pagetables-l2 alias of shared-l2 A boot loader that also serves the older M3 runtime lists the shared L2 page-table reservation twice on the GPU node: first as "pagetables-l2", then as "shared-l2" in the canonical six. On the 15-inch M3 Air both names reference the same phandle, so it is one reservation under two names, but the exact six-entry check refused the whole handoff. Accept the seven-entry form only when the leading entry is named "pagetables-l2" and references the same reservation as "shared-l2". A second or unknown reservation still refuses the contract, and the six canonical regions are looked up and validated by name as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/adt.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index 383bfad621b244..b33a037f2e969b 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -187,12 +187,26 @@ pub(crate) fn read(dev: &device::Device, cfg: &Config) -> Result> { ); return Err(EINVAL); }; - if phandles.len() != 6 - || names.as_slice() != b"ttbs\0pagetables\0handoff\0shared-l2\0fw-text\0fw-data\0" - { + const CANONICAL: &[u8] = b"ttbs\0pagetables\0handoff\0shared-l2\0fw-text\0fw-data\0"; + // A boot loader that also serves the older M3 runtime names the shared L2 table a second + // time, first, as "pagetables-l2". Accept that entry only as an alias: it must reference + // the very reservation "shared-l2" references. Anything else (a second or unknown + // reservation) keeps the contract refused. The six canonical regions are then looked up + // and validated by name below, exactly as without the alias. + const L2_ALIAS: &[u8] = b"pagetables-l2\0"; + let canonical = phandles.len() == 6 && names.as_slice() == CANONICAL; + let aliased = phandles.len() == 7 + && names.as_slice().len() == L2_ALIAS.len() + CANONICAL.len() + && names.as_slice().starts_with(L2_ALIAS) + && &names.as_slice()[L2_ALIAS.len()..] == CANONICAL + && phandles[0] == phandles[4]; + if !canonical && !aliased { dev_err!(dev, "G16: unsupported boot-loader handoff contract\n"); return Err(EINVAL); } + if aliased { + dev_info!(dev, "G16: pagetables-l2 is an alias of shared-l2 (same reservation)\n"); + } let names = [ c_str!("ttbs"), c_str!("pagetables"), From 13e413b6a5d3c78875cad3bce1bb25df0605d5ce Mon Sep 17 00:00:00 2001 From: Jos Dehaes Date: Wed, 25 Nov 2026 16:07:26 +0100 Subject: [PATCH 1357/1514] arm64: dts: apple: t6041-j614c: enable SIO AES and AON PTD battery record Enable the SIO AES engine (software keys only) and the AON PTD battery telemetry record on the 14-inch M4 Max MacBook Pro (J614c), as the J616c already does. The J614c ADT /arm-io/aon-ptd ptd_data_table carries the same battery record as the J616c: "IFtb", layout version 1, slots 0x12..0x15. Signed-off-by: Jos Dehaes --- arch/arm64/boot/dts/apple/t6041-j614c.dts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6041-j614c.dts b/arch/arm64/boot/dts/apple/t6041-j614c.dts index 6deb66068c70be..d35e9b7e3808f8 100644 --- a/arch/arm64/boot/dts/apple/t6041-j614c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j614c.dts @@ -96,3 +96,21 @@ &mesa { firmware-name = "apple/mesacal-j614c.bin", "apple/msrk-j614c.bin"; }; + +/* + * ADT /arm-io/aon-ptd ptd_data_table: the battery record ("IFtb", layout 1, + * slots 0x12-0x15). Only its peek aperture is read. + */ +&aon_ptd { + apple,battery-record = <0x49467462 1 0x12 4>; + status = "okay"; +}; + +/* SIO AES engine, software keys only. */ +&ps_aes { + status = "okay"; +}; + +&aes { + status = "okay"; +}; From 264f9dcb7d98e10ef69838e5ed51fe2f894a588a Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 22:23:01 +0700 Subject: [PATCH 1358/1514] media: apple: jpeg: encode 4:2:2, 4:4:4 and greyscale on T6050 The T6050 encoder was driven for 4:2:0 only. Its job takes the subsampling in four places: the codec and pixel-mode registers, the MCU and per-plane tile geometry, and the JPEG IO flags (the frame header's sampling factors). Describe each subsampling as one table entry and offer NV16, NV24 and GREY besides NV12 on the encoder. The 4:2:2, 4:4:4 and greyscale entries were found by sweeping those fields on the J815 (T8142) and checking each output: the JPEG decodes with the expected sampling factors, at 640x480, 642x482, 1366x766 and 1920x1080, with 42.8 to 47.5 dB PSNR against the source frame. Signed-off-by: Nick --- .../platform/apple/jpeg/apple-jpeg-drv.c | 62 ++++++--- .../media/platform/apple/jpeg/apple-jpeg-hw.c | 125 ++++++++++++++---- .../media/platform/apple/jpeg/apple-jpeg-hw.h | 66 ++++++--- .../platform/apple/jpeg/apple-jpeg-test.c | 35 +++-- 4 files changed, 213 insertions(+), 75 deletions(-) diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c index 8dc8aa933c6136..cc4ece953fb218 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c @@ -2,7 +2,8 @@ /* * Apple Silicon JPEG encoder, V4L2 memory-to-memory. * - * Takes full-range YUV in one buffer (NV12 for 4:2:0, NV16 for 4:2:2) and + * Takes full-range YUV in one buffer (NV12 for 4:2:0, NV16 for 4:2:2; NV24 + * for 4:4:4 and GREY where the engine's job layout has them) and * produces baseline JPEG with the standard Huffman tables. One job runs at * a time; the engine is reset before each job and the completion interrupt * ends it. Register layout: see apple-jpeg-hw.h. @@ -227,6 +228,21 @@ static void aj_watchdog(struct work_struct *work) } } +/* The raw formats, in apple_jpeg_subsampling order. */ +static const u32 aj_raw_fmts[] = { + V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_NV16, V4L2_PIX_FMT_NV24, V4L2_PIX_FMT_GREY, +}; + +/* The subsampling of a raw format this engine takes; 4:2:0 for any other. */ +static enum apple_jpeg_subsampling aj_subsampling(const struct apple_jpeg *jpeg, u32 fourcc) +{ + for (unsigned int s = 0; s < ARRAY_SIZE(aj_raw_fmts); s++) + if (aj_raw_fmts[s] == fourcc && + apple_jpeg_has_subsampling(jpeg->variant->layout, s)) + return s; + return AJ_SUBSAMPLING_420; +} + static void aj_device_run(void *priv) { struct apple_jpeg_ctx *ctx = priv; @@ -235,8 +251,8 @@ static void aj_device_run(void *priv) struct apple_jpeg_layout layout; struct apple_jpeg_job job; unsigned long flags; + enum apple_jpeg_subsampling ss; dma_addr_t y; - bool is422; int n, ret; src = v4l2_m2m_next_src_buf(ctx->fh.m2m_ctx); @@ -249,16 +265,17 @@ static void aj_device_run(void *priv) } y = vb2_dma_contig_plane_dma_addr(&src->vb2_buf, 0); - is422 = ctx->src.pixelformat == V4L2_PIX_FMT_NV16; - apple_jpeg_raw_layout(ctx->src.width, ctx->src.height, is422, &layout); + ss = aj_subsampling(jpeg, ctx->src.pixelformat); + apple_jpeg_raw_layout(ctx->src.width, ctx->src.height, ss, &layout); job = (struct apple_jpeg_job){ .width = ctx->src.width, .height = ctx->src.height, - .is422 = is422, + .subsampling = ss, .luma_stride = layout.bytesperline, - .chroma_stride = layout.bytesperline, + .chroma_stride = layout.chroma_stride, .luma = y, - .chroma = y + layout.chroma_offset, + /* GREY has no chroma plane: point plane 1 at the luma. */ + .chroma = ss == AJ_SUBSAMPLING_GREY ? y : y + layout.chroma_offset, /* The engine's single input bound: the end of the negotiated surface. */ .input_end = y + layout.sizeimage - 1, .output = vb2_dma_contig_plane_dma_addr(&dst->vb2_buf, 0), @@ -328,14 +345,13 @@ static void aj_fill_colorimetry(struct v4l2_pix_format_mplane *pix) /* Raw input: Y rows then interleaved CbCr rows in one buffer. */ static void aj_fill_raw(const struct apple_jpeg *jpeg, struct v4l2_pix_format_mplane *pix) { - bool is422 = pix->pixelformat == V4L2_PIX_FMT_NV16 && - apple_jpeg_has_422(jpeg->variant->layout); + enum apple_jpeg_subsampling ss = aj_subsampling(jpeg, pix->pixelformat); u32 w = clamp_t(u32, ALIGN(pix->width, 2), AJ_MIN_SIZE, AJ_MAX_SIZE); u32 h = clamp_t(u32, pix->height, AJ_MIN_SIZE, AJ_MAX_SIZE); struct apple_jpeg_layout layout; - apple_jpeg_raw_layout(w, h, is422, &layout); - pix->pixelformat = is422 ? V4L2_PIX_FMT_NV16 : V4L2_PIX_FMT_NV12; + apple_jpeg_raw_layout(w, h, ss, &layout); + pix->pixelformat = aj_raw_fmts[ss]; pix->width = w; pix->height = h; pix->field = V4L2_FIELD_NONE; @@ -373,13 +389,18 @@ static int aj_querycap(struct file *file, void *priv, struct v4l2_capability *ca static int aj_enum_fmt_out(struct file *file, void *priv, struct v4l2_fmtdesc *f) { - static const u32 fmts[] = { V4L2_PIX_FMT_NV12, V4L2_PIX_FMT_NV16 }; const struct apple_jpeg *jpeg = aj_file_to_ctx(file)->jpeg; - - if (f->index >= (apple_jpeg_has_422(jpeg->variant->layout) ? ARRAY_SIZE(fmts) : 1)) - return -EINVAL; - f->pixelformat = fmts[f->index]; - return 0; + unsigned int n = 0; + + for (unsigned int s = 0; s < ARRAY_SIZE(aj_raw_fmts); s++) { + if (!apple_jpeg_has_subsampling(jpeg->variant->layout, s)) + continue; + if (n++ == f->index) { + f->pixelformat = aj_raw_fmts[s]; + return 0; + } + } + return -EINVAL; } static int aj_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) @@ -394,11 +415,10 @@ static int aj_enum_fmt_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f static int aj_enum_framesizes(struct file *file, void *priv, struct v4l2_frmsizeenum *fs) { const struct apple_jpeg *jpeg = aj_file_to_ctx(file)->jpeg; - bool nv16 = apple_jpeg_has_422(jpeg->variant->layout); + bool raw = aj_subsampling(jpeg, fs->pixel_format) != AJ_SUBSAMPLING_420 || + fs->pixel_format == V4L2_PIX_FMT_NV12; - if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_JPEG && - fs->pixel_format != V4L2_PIX_FMT_NV12 && - (fs->pixel_format != V4L2_PIX_FMT_NV16 || !nv16))) + if (fs->index || (fs->pixel_format != V4L2_PIX_FMT_JPEG && !raw)) return -EINVAL; fs->type = V4L2_FRMSIZE_TYPE_STEPWISE; fs->stepwise = (struct v4l2_frmsize_stepwise){ diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c index 4746b480449c6c..0c0f85d323f3a8 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.c @@ -649,10 +649,62 @@ int apple_jpeg_defaults(const struct apple_jpeg_reg_layout *layout, bool encode, EXPORT_SYMBOL_IF_KUNIT(apple_jpeg_defaults); /* - * The T6050 sequence, in AppleJPEGDriver's order (per the macOS register - * trace). Unlike the earlier revisions it has no plane size or pipe limit - * registers, takes 16-bit quantisation tables and two-bit Huffman table - * selectors, and needs 0x08c, 0x334 and IO flag bit 7. Only 4:2:0 is known. + * T6050 per-subsampling programming. The engine reads the input in MCUs: + * each plane's tile is its share of one MCU, in 8-byte columns and rows + * (plane 1 holds interleaved CbCr, so a 4:4:4 chroma tile is twice as wide + * as the luma one). The IO flags take the JPEG's own subsampling code, + * which sets the frame header's sampling factors. + * + * Every entry was checked on the J815 (T8142): the engine's JPEG decodes + * with the expected sampling factors at 640x480, 642x482, 1366x766 and + * 1920x1080, 42.8-47.5 dB PSNR against the source frame. + */ +struct aj_t6050_mode { + u8 codec; + u8 px_mode; + u8 io; + u8 mcu_w, mcu_h; + u8 tile0_w, tile0_h; + u8 tile1_w, tile1_h; /* 0: no plane 1 */ + u8 enc_ctrl; +}; + +static const struct aj_t6050_mode aj_t6050_modes[] = { + [AJ_SUBSAMPLING_420] = { + .codec = AJ_CODEC_420, .px_mode = AJ_CODEC_420, .io = AJ_IO_FLAGS_420, + .mcu_w = 16, .mcu_h = 16, .tile0_w = 2, .tile0_h = 16, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_422] = { + .codec = AJ_CODEC_422, .px_mode = AJ_CODEC_422, .io = AJ_IO_FLAGS_422, + .mcu_w = 16, .mcu_h = 8, .tile0_w = 2, .tile0_h = 8, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_444] = { + .codec = AJ_CODEC_444, .px_mode = AJ_CODEC_444, .io = AJ_IO_FLAGS_444, + .mcu_w = 8, .mcu_h = 8, .tile0_w = 1, .tile0_h = 8, .tile1_w = 2, .tile1_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, + [AJ_SUBSAMPLING_GREY] = { + .codec = AJ_CODEC_GREY, .px_mode = AJ_CODEC_GREY, .io = AJ_IO_FLAGS_GREY, + .mcu_w = 8, .mcu_h = 8, .tile0_w = 1, .tile0_h = 8, + .enc_ctrl = AJ_T6050_ENC_CTRL_ENCODE, + }, +}; + +bool apple_jpeg_has_subsampling(const struct apple_jpeg_reg_layout *layout, + enum apple_jpeg_subsampling s) +{ + if (!layout->t6050_job) + return s <= AJ_SUBSAMPLING_422; + return s < ARRAY_SIZE(aj_t6050_modes); +} +EXPORT_SYMBOL_IF_KUNIT(apple_jpeg_has_subsampling); + +/* + * The T6050 job. Unlike the earlier revisions it has no plane size or pipe + * limit registers, takes 16-bit quantisation tables and two-bit Huffman + * table selectors, and needs 0x08c, 0x334 and IO flag bit 7. */ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout *layout, const struct apple_jpeg_job *job, u64 output_end) @@ -669,10 +721,12 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout job->luma, job->chroma, job->input_end, job->output, job->output, output_end, }; u32 width = job->width, height = job->height; + const struct aj_t6050_mode *m; u8 q[2][64]; - if (job->is422) - return -EOPNOTSUPP; + if (job->subsampling >= ARRAY_SIZE(aj_t6050_modes)) + return -EINVAL; + m = &aj_t6050_modes[job->subsampling]; aj_put(l, AJ_MODE, AJ_MODE_SETUP); aj_put(l, AJ_MAIN_RUN, 0); @@ -682,19 +736,21 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout aj_put(l, AJ_ENCODE_ENABLE, 1); aj_put(l, AJ_CODEC_MODE, 1); aj_put(l, AJ_DECODE_ENABLE, 0); - aj_put(l, AJ_CODEC, AJ_CODEC_420); + aj_put(l, AJ_CODEC, m->codec); aj_put(l, layout->image_width, width); aj_put(l, layout->image_height, height); - aj_put(l, AJ_T6050_PX_MODE, AJ_CODEC_420); - aj_put(l, AJ_PX_USE_PLANE1, 1); + aj_put(l, AJ_T6050_PX_MODE, m->px_mode); + aj_put(l, AJ_PX_USE_PLANE1, !!m->tile1_w); aj_put(l, layout->timeout, apple_jpeg_timeout(width, height)); - aj_put(l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, 16)); - aj_put(l, AJ_PX_MCUS_H, DIV_ROUND_UP(height, 16)); - aj_put(l, AJ_PX_PLANE0_TILE_H, 2); - aj_put(l, AJ_PX_PLANE0_TILE_V, 16); - aj_put(l, AJ_PX_PLANE1_TILE_H, 2); - aj_put(l, AJ_PX_PLANE1_TILE_V, 8); - aj_put(l, AJ_T6050_ENC_CTRL, AJ_T6050_ENC_CTRL_ENCODE); + aj_put(l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, m->mcu_w)); + aj_put(l, AJ_PX_MCUS_H, DIV_ROUND_UP(height, m->mcu_h)); + aj_put(l, AJ_PX_PLANE0_TILE_H, m->tile0_w); + aj_put(l, AJ_PX_PLANE0_TILE_V, m->tile0_h); + if (m->tile1_w) { + aj_put(l, AJ_PX_PLANE1_TILE_H, m->tile1_w); + aj_put(l, AJ_PX_PLANE1_TILE_V, m->tile1_h); + } + aj_put(l, AJ_T6050_ENC_CTRL, m->enc_ctrl); /* Two planes, Y then interleaved Cb, Cr. */ aj_put(l, layout->encode_format, AJ_PIXEL_FORMAT_YUV_PLANES); @@ -714,7 +770,7 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout aj_put(l, AJ_T6050_PRE_ENCODE, 0); aj_put(l, AJ_MODE, AJ_MODE_ENCODE); - aj_put(l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | AJ_IO_FLAGS_420); + aj_put(l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | m->io); aj_put(l, AJ_JPEG_WIDTH, width); aj_put(l, AJ_JPEG_HEIGHT, height); aj_put(l, AJ_RST_INTERVAL, job->restart_interval); @@ -733,16 +789,19 @@ static int aj_build_t6050(struct aj_list *l, const struct apple_jpeg_reg_layout } /* - * Every register write of one baseline encode of two-plane (NV12 or NV16) - * full-range input, in order, ending with the start command. + * Every register write of one baseline encode of full-range input (NV12 or + * NV16; with the T6050 job layout also NV24 and GREY), in order, ending with + * the start command. */ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, const struct apple_jpeg_job *job, struct apple_jpeg_write *w, unsigned int max) { u32 width = job->width, height = job->height; - u32 mcu_h = job->is422 ? 8 : 16; - u32 crows = job->is422 ? height : DIV_ROUND_UP(height, 2); + bool is422 = job->subsampling == AJ_SUBSAMPLING_422; + u32 mcu_h = apple_jpeg_mcu_rows(job->subsampling); + u32 crows = is422 ? height : DIV_ROUND_UP(height, 2); + u32 min_cstride; struct aj_list l = { .w = w, .max = max }; u8 luma[64], chroma[64]; u64 output_end, addr_mask = DMA_BIT_MASK(layout->dma_addr_bits); @@ -750,7 +809,21 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, if (!width || !height || width > U16_MAX || height > U16_MAX) return -EINVAL; - if (job->luma_stride < width || job->chroma_stride < ALIGN(width, 2)) + if (!apple_jpeg_has_subsampling(layout, job->subsampling) || + job->subsampling > AJ_SUBSAMPLING_GREY) + return -EOPNOTSUPP; + switch (job->subsampling) { + case AJ_SUBSAMPLING_444: + min_cstride = 2 * width; + break; + case AJ_SUBSAMPLING_GREY: + min_cstride = 0; + break; + default: + min_cstride = ALIGN(width, 2); + break; + } + if (job->luma_stride < width || job->chroma_stride < min_cstride) return -EINVAL; if ((job->luma | job->chroma) & 3 || job->output & 31 || !job->output_size) return -EINVAL; @@ -779,7 +852,7 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put(&l, AJ_ENCODE_ENABLE, 1); aj_put(&l, AJ_CODEC_MODE, 1); aj_put(&l, AJ_DECODE_ENABLE, 0); - aj_put(&l, AJ_CODEC, job->is422 ? AJ_CODEC_422 : AJ_CODEC_420); + aj_put(&l, AJ_CODEC, is422 ? AJ_CODEC_422 : AJ_CODEC_420); aj_put(&l, AJ_PX_USE_PLANE1, 1); aj_put(&l, AJ_PX_MCUS_W, DIV_ROUND_UP(width, 16)); @@ -804,8 +877,8 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put_addr(&l, layout, layout->output_start0, job->output); aj_put_addr(&l, layout, layout->output_start1, job->output); aj_put_addr(&l, layout, layout->output_end, output_end); - aj_put(&l, layout->pipe_limit0, job->is422 ? 8 : 3); - aj_put(&l, layout->pipe_limit1, job->is422 ? 2 : 1); + aj_put(&l, layout->pipe_limit0, is422 ? 8 : 3); + aj_put(&l, layout->pipe_limit1, is422 ? 2 : 1); /* Two planes, Y then interleaved Cb, Cr; no colour conversion. */ aj_put(&l, layout->encode_format, AJ_PIXEL_FORMAT_YUV_PLANES); @@ -821,7 +894,7 @@ int apple_jpeg_build_job(const struct apple_jpeg_reg_layout *layout, aj_put(&l, AJ_MODE, AJ_MODE_ENCODE); aj_put(&l, AJ_JPEG_IO_FLAGS, AJ_IO_FLAGS_ORDER | - (job->is422 ? AJ_IO_FLAGS_422 : AJ_IO_FLAGS_420)); + (is422 ? AJ_IO_FLAGS_422 : AJ_IO_FLAGS_420)); aj_put(&l, AJ_JPEG_WIDTH, width); aj_put(&l, AJ_JPEG_HEIGHT, height); aj_put(&l, AJ_RST_INTERVAL, job->restart_interval); diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h index 429d25086d281e..8b83b309ad7cab 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-hw.h @@ -36,6 +36,8 @@ #define AJ_CODEC 0x028 #define AJ_CODEC_422 1 #define AJ_CODEC_420 3 +#define AJ_CODEC_444 0 +#define AJ_CODEC_GREY 4 #define AJ_CODEC_MODE 0x02c /* 1 encode */ #define AJ_DECODE_ENABLE 0x034 #define AJ_ENCODE_ENABLE 0x038 @@ -52,7 +54,7 @@ #define AJ_PX_PLANE1_TILE_H 0x080 #define AJ_PX_PLANE1_TILE_V 0x084 #define AJ_PX_PLANE1_STRIDE 0x088 -#define AJ_T6050_PX_MODE 0x08c /* T6050: the CODEC value for 4:2:0 */ +#define AJ_T6050_PX_MODE 0x08c /* T6050: the input's chroma layout */ #define AJ_PIXEL_FORMAT_YUV_PLANES 4 #define AJ_T6050_PRE_ENCODE 0x1dc /* T6050: cleared before MODE_ENCODE */ #define AJ_T6050_ENC_CTRL 0x334 @@ -61,6 +63,8 @@ #define AJ_IO_FLAGS_ORDER (BIT(4) | BIT(5)) #define AJ_IO_FLAGS_422 1 #define AJ_IO_FLAGS_420 2 +#define AJ_IO_FLAGS_444 0 +#define AJ_IO_FLAGS_GREY 3 #define AJ_IO_FLAGS_T6050 BIT(7) #define AJ_COMMAND 0x1004 #define AJ_QTBL_SEL 0x100c @@ -139,10 +143,21 @@ extern const struct apple_jpeg_variant apple_jpeg_t8112; extern const struct apple_jpeg_variant apple_jpeg_t8122; extern const struct apple_jpeg_variant apple_jpeg_t8140; -/* T6050's 4:2:2 job programming is not known yet. */ -static inline bool apple_jpeg_has_422(const struct apple_jpeg_reg_layout *layout) +/* Chroma subsampling of the raw input, which the JPEG keeps. */ +enum apple_jpeg_subsampling { + AJ_SUBSAMPLING_420, /* NV12 */ + AJ_SUBSAMPLING_422, /* NV16 */ + AJ_SUBSAMPLING_444, /* NV24, T6050 job layout only */ + AJ_SUBSAMPLING_GREY, /* GREY, T6050 job layout only */ +}; + +bool apple_jpeg_has_subsampling(const struct apple_jpeg_reg_layout *layout, + enum apple_jpeg_subsampling s); + +/* MCU height: 16 rows for 4:2:0, 8 for the others. */ +static inline u32 apple_jpeg_mcu_rows(enum apple_jpeg_subsampling s) { - return !layout->t6050_job; + return s == AJ_SUBSAMPLING_420 ? 16 : 8; } static inline bool @@ -156,7 +171,7 @@ apple_jpeg_hwrev_supported(const struct apple_jpeg_variant *variant, u32 hwrev) struct apple_jpeg_job { u32 width; u32 height; - bool is422; /* NV16: 4:2:2; NV12: 4:2:0 */ + enum apple_jpeg_subsampling subsampling; u32 luma_stride; u32 chroma_stride; u64 luma; @@ -169,28 +184,49 @@ struct apple_jpeg_job { }; /* - * Raw input: one buffer, the luma rows, then the interleaved CbCr rows at - * the same stride (V4L2 NV12/NV16). The engine prefetches its input up to - * AJ_INPUT_END, so both planes must sit in one buffer that ends there: with - * separate plane buffers it read past the end of whichever plane lies lower - * and faulted. It also fetches whole MCU rows (16 for 4:2:0, 8 for 4:2:2); - * the luma overrun lands in the chroma rows, and the buffer carries the - * chroma rows up to the MCU boundary after the visible ones. + * Raw input: one buffer, the luma rows, then the interleaved CbCr rows + * (V4L2 NV12/NV16/NV24; GREY has no chroma). The CbCr rows have the luma + * stride, twice it for NV24, whose chroma is full width. The engine + * prefetches its input up to AJ_INPUT_END, so both planes must sit in one + * buffer that ends there: with separate plane buffers it read past the end + * of whichever plane lies lower and faulted. It also fetches whole MCU rows + * (16 for 4:2:0, 8 otherwise); the luma overrun lands in the chroma rows, and + * the buffer carries the chroma rows up to the MCU boundary after the + * visible ones. Without chroma, the luma rows themselves are padded to it. */ struct apple_jpeg_layout { u32 bytesperline; + u32 chroma_stride; u32 chroma_offset; u32 sizeimage; }; -static inline void apple_jpeg_raw_layout(u32 width, u32 height, bool is422, +static inline void apple_jpeg_raw_layout(u32 width, u32 height, + enum apple_jpeg_subsampling s, struct apple_jpeg_layout *l) { - u32 rows = ALIGN(height, is422 ? 8 : 16); + u32 rows = ALIGN(height, apple_jpeg_mcu_rows(s)); l->bytesperline = ALIGN(width, 16); l->chroma_offset = l->bytesperline * height; - l->sizeimage = l->chroma_offset + l->bytesperline * (is422 ? rows : rows / 2); + switch (s) { + case AJ_SUBSAMPLING_420: + l->chroma_stride = l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * (rows / 2); + break; + case AJ_SUBSAMPLING_422: + l->chroma_stride = l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * rows; + break; + case AJ_SUBSAMPLING_444: + l->chroma_stride = 2 * l->bytesperline; + l->sizeimage = l->chroma_offset + l->chroma_stride * rows; + break; + default: + l->chroma_stride = 0; + l->sizeimage = l->bytesperline * rows; + break; + } } /* A kept CAPTURE size above the worst case is honoured up to this. */ diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c index 7f325d331ec44a..e94da7bc415aa6 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c @@ -115,7 +115,7 @@ static void apple_jpeg_job_422_test(struct kunit *test) int n; KUNIT_ASSERT_NOT_NULL(test, w); - job.is422 = true; + job.subsampling = AJ_SUBSAMPLING_422; job.width = 641; /* odd width: chroma rounds up */ job.luma_stride = 656; job.chroma_stride = 656; @@ -250,8 +250,13 @@ static void apple_jpeg_t6050_layout_test(struct kunit *test) KUNIT_EXPECT_EQ(test, w[6].value, 8); KUNIT_EXPECT_EQ(test, w[11].value, 16); KUNIT_EXPECT_EQ(test, apple_jpeg_dma_ids(l, 0, w, 11), -ENOSPC); - KUNIT_EXPECT_FALSE(test, apple_jpeg_has_422(l)); - KUNIT_EXPECT_TRUE(test, apple_jpeg_has_422(wide)); + /* Until the engine probe confirms them, T6050 offers 4:2:0 only. */ + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_420)); + KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_422)); + KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_444)); + KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_GREY)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_422)); + KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_444)); } /* The first write to @offset at or after @from, or -1. */ @@ -315,7 +320,7 @@ static void apple_jpeg_t6050_job_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1)), 0x00110012); KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1) + 0x7c), 0x00630063); - job.is422 = true; + job.subsampling = AJ_SUBSAMPLING_422; KUNIT_EXPECT_EQ(test, apple_jpeg_build_job(l, &job, w, APPLE_JPEG_MAX_WRITES), -EOPNOTSUPP); } @@ -361,7 +366,7 @@ static void apple_jpeg_legacy_job_test(struct kunit *test) job.input_end = 0x4ffff8; job.output = 0x1000000; for (unsigned int is422 = 0; is422 < 2; is422++) { - job.is422 = is422; + job.subsampling = is422 ? AJ_SUBSAMPLING_422 : AJ_SUBSAMPLING_420; n = apple_jpeg_build_job(apple_jpeg_t6000.layout, &job, w, APPLE_JPEG_MAX_WRITES); KUNIT_ASSERT_GT(test, n, 0); @@ -519,23 +524,27 @@ static void apple_jpeg_raw_layout_test(struct kunit *test) { static const struct { u32 w, h; - bool is422; + enum apple_jpeg_subsampling s; u32 bpl, chroma, size; } cases[] = { - { 1920, 1080, false, 1920, 1920 * 1080, 1920 * (1080 + 544) }, - { 1280, 720, false, 1280, 1280 * 720, 1280 * (720 + 360) }, - { 640, 480, false, 640, 640 * 480, 640 * (480 + 240) }, - { 3840, 2160, false, 3840, 3840 * 2160, 3840 * (2160 + 1080) }, + { 1920, 1080, AJ_SUBSAMPLING_420, 1920, 1920 * 1080, 1920 * (1080 + 544) }, + { 1280, 720, AJ_SUBSAMPLING_420, 1280, 1280 * 720, 1280 * (720 + 360) }, + { 640, 480, AJ_SUBSAMPLING_420, 640, 640 * 480, 640 * (480 + 240) }, + { 3840, 2160, AJ_SUBSAMPLING_420, 3840, 3840 * 2160, 3840 * (2160 + 1080) }, /* Odd height and a width that pads the stride to 16. */ - { 642, 481, false, 656, 656 * 481, 656 * (481 + 248) }, + { 642, 481, AJ_SUBSAMPLING_420, 656, 656 * 481, 656 * (481 + 248) }, /* 4:2:2 MCUs are 8 rows high and chroma has every row. */ - { 1920, 1084, true, 1920, 1920 * 1084, 1920 * (1084 + 1088) }, + { 1920, 1084, AJ_SUBSAMPLING_422, 1920, 1920 * 1084, 1920 * (1084 + 1088) }, + /* 4:4:4: full-width interleaved chroma, twice the luma stride. */ + { 640, 480, AJ_SUBSAMPLING_444, 640, 640 * 480, 640 * 480 + 1280 * 480 }, + /* GREY: the luma rows alone, padded to the 8-row MCU. */ + { 640, 481, AJ_SUBSAMPLING_GREY, 640, 640 * 481, 640 * 488 }, }; for (unsigned int i = 0; i < ARRAY_SIZE(cases); i++) { struct apple_jpeg_layout l; - apple_jpeg_raw_layout(cases[i].w, cases[i].h, cases[i].is422, &l); + apple_jpeg_raw_layout(cases[i].w, cases[i].h, cases[i].s, &l); KUNIT_EXPECT_EQ(test, l.bytesperline, cases[i].bpl); KUNIT_EXPECT_EQ(test, l.chroma_offset, cases[i].chroma); KUNIT_EXPECT_EQ(test, l.sizeimage, cases[i].size); From 62e450ef8d16b0f1cd4eabbc8b007506639bac92 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 07:17:55 -0500 Subject: [PATCH 1359/1514] drm/asahi: g16: pool disjoint per-VM compute workqueues Keep cross-VM non-SCS compute dispatches on disjoint firmware compute workqueues (graph.compute[0..COMPUTE_PIPES], COMPUTE_PIPES = 8, events 15..=22) so two different VMs/ASIDs are never queued into the same active qinfo. Previously, mixing multiple VMs in a shared compute workqueue forced a full engine drain on every cross-VM compute switch (DrainCross), leaving pipeline depth at zero on multi-process compute workloads. With a pool of 8 leaseable compute workqueues (capped at MAX_VM_COMPUTE_PIPES = 2 per VM to preserve render barrier ring bounds) and warm per-VM pipe affinity, concurrent clients execute on separate workqueues without cross-VM engine drains while preserving cross-VM render/compute drains and SCS/RT compute isolation. Latch shared Channel::Compute read/completion proofs onto active compute flights before the 256-entry submit ring can lap them, track compute administrative deadlines and warnings per compute pipe so progress on one pipe cannot mask a stall on another, and drain one compatible pipe for handoff when a waiting job (such as a base-only VM limited to pipe 0) has no eligible pipe while other pipes continue dispatching. Update the M4 host selftest harnesses for the 8-pipe compute workqueue pool, per-pipe deadlines, channel-wrap latching, and handoff semantics. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 566 ++++++++++++++---- drivers/gpu/drm/asahi/g16/event.rs | 47 +- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 12 +- drivers/gpu/drm/asahi/g16/graph.rs | 18 +- drivers/gpu/drm/asahi/g16/hw.rs | 14 +- drivers/gpu/drm/asahi/g16/mod.rs | 7 +- drivers/gpu/drm/asahi/g16/poll.rs | 155 +++-- drivers/gpu/drm/asahi/g16/recovery.rs | 128 ++-- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 54 +- drivers/gpu/drm/asahi/g16/slots.rs | 55 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 56 +- .../gpu/asahi-m4/test-progress-wrap.py | 91 ++- .../drivers/gpu/asahi-m4/test-publication.py | 427 ++++++++----- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 85 ++- 14 files changed, 1199 insertions(+), 516 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 0c85e94fd77cd7..69b5c78fe75c1b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -307,6 +307,9 @@ pub(crate) struct Flight { pub(crate) fs_start: u32, /// Channel producers (TA, FS, compute) after the prefix's records. pub(crate) rec: [u32; 3], + /// Whether `Channel::Compute` read and completion cursors already passed `rec[2]` before + /// the shared submit ring could wrap past this flight. + pub(crate) chan_settled: bool, /// Compute member j's FW stamp target, the FS target it waits on directly (0: none), and /// its private UMA counter value after publication. pub(crate) cstamp: [u32; sizes::COMPUTE_SLOTS], @@ -368,6 +371,7 @@ impl Flight { ta_start: 0, fs_start: 0, rec: [0; 3], + chan_settled: false, cstamp: [0; sizes::COMPUTE_SLOTS], cwait: [0; sizes::COMPUTE_SLOTS], csubmitted: [0; sizes::COMPUTE_SLOTS], @@ -434,7 +438,7 @@ pub(crate) enum HoldCause { DrainFailed, /// A cold `InitBM` render is in flight. DrainInitbm, - /// Compute behind any flight of another VM, render behind compute of another VM, or an + /// Compute behind render of another VM, render behind compute of another VM, or an /// SCS compute conflict. DrainCross, /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. @@ -640,6 +644,14 @@ pub(crate) struct Engine { /// The compute pipes / render queues were registered by a first record (`new_queue`). pub(crate) queue_registered: [bool; sizes::COMPUTE_PIPES], pub(crate) next_compute_pipe: u8, + /// Last VM id that published onto each compute pipe (warm per-VM `qinfo` affinity). + pub(crate) pipe_last_vm: [Option; sizes::COMPUTE_PIPES], + /// Monotonic last-use counter per compute pipe for LRU idle-pipe selection. + pub(crate) pipe_last_used: [u64; sizes::COMPUTE_PIPES], + pub(crate) pipe_use_seq: u64, + /// Transient bitmask of compute pipes being drained for handoff to a waiting job that has + /// no eligible pipe (e.g. a base-only VM limited to pipe 0). + pub(crate) handoff_avoid_pipes: u32, pub(crate) render_registered: bool, pub(crate) ta_registered: bool, /// A ready prefix waits only for a record's consumption: repoll sooner. @@ -662,9 +674,9 @@ pub(crate) struct Engine { /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, - /// Progress tracking of the oldest compute pipe 0/1 and render flights. - pub(crate) progress_flight: [u64; 3], - pub(crate) progress: [Option; 4], + /// Progress tracking of the oldest compute pipes `0..COMPUTE_PIPES` and render flights. + pub(crate) progress_flight: [u64; sizes::COMPUTE_PIPES + 1], + pub(crate) progress: [Option; sizes::COMPUTE_PIPES + 2], /// Boxed with [`Self::prof`]: `Firmware` is built on the probe's stack. pub(crate) stats: KBox, /// Phase timers (debug_flags bit 49). @@ -700,6 +712,10 @@ impl Engine { stage_seen: 0, queue_registered: [false; sizes::COMPUTE_PIPES], next_compute_pipe: 0, + pipe_last_vm: [None; sizes::COMPUTE_PIPES], + pipe_last_used: [0; sizes::COMPUTE_PIPES], + pipe_use_seq: 0, + handoff_avoid_pipes: 0, render_registered: false, ta_registered: false, chan_wait: false, @@ -709,8 +725,8 @@ impl Engine { housekeeping_owed: false, held_wait: false, coalesce_deadline_ns: 0, - progress_flight: [0; 3], - progress: [None; 4], + progress_flight: [0; sizes::COMPUTE_PIPES + 1], + progress: [None; sizes::COMPUTE_PIPES + 2], stats: KBox::zeroed(GFP_KERNEL)?, prof: KBox::zeroed(GFP_KERNEL)?, debugfs: None, @@ -866,13 +882,14 @@ impl Firmware { /// The single in-order Finalize frontier for each held M4 event. These cells are never /// reset after first publication, including across client VM switches and recovery. - pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 4]> { - Ok([ - self.graph.render.fw_stamp[0].r32(0)?, - self.graph.render.fw_stamp[1].r32(0)?, - self.graph.compute[0].fw_stamp.r32(0)?, - self.graph.compute[1].fw_stamp.r32(0)?, - ]) + pub(crate) fn recovery_snapshot(&self) -> Result<[u32; 2 + sizes::COMPUTE_PIPES]> { + let mut stage = [0u32; 2 + sizes::COMPUTE_PIPES]; + stage[0] = self.graph.render.fw_stamp[0].r32(0)?; + stage[1] = self.graph.render.fw_stamp[1].r32(0)?; + for (p, compute) in self.graph.compute.iter().enumerate() { + stage[2 + p] = compute.fw_stamp.r32(0)?; + } + Ok(stage) } /// Authenticate one firmware affected-work snapshot entry against its retained owner. @@ -882,7 +899,7 @@ impl Firmware { flags: u32, event: u32, target: u32, - stage: [u32; 4], + stage: [u32; 2 + sizes::COMPUTE_PIPES], ) -> Result { if flags & 1 != 0 && self.recovery.last_retired.contains(event, target) { // A notification may follow the full receipt. It names the retained old @@ -890,21 +907,12 @@ impl Firmware { return Ok(()); } // The named owner: the oldest flight, or with compute/render queued behind it a later one. + let compute_pipe = work::compute::pipe_of_event(event); let f = self .engine .flights .iter_mut() .find(|f| match event { - 15 => { - f.computes != 0 - && f.compute_pipe == 0 - && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) - } - 16 => { - f.computes != 0 - && f.compute_pipe == 1 - && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) - } 0x70 => { f.renders != 0 && f.r_ta_stamp[..(f.renders as usize).min(f.r_ta_stamp.len())] @@ -915,7 +923,11 @@ impl Firmware { && f.r_fs_stamp[..(f.renders as usize).min(f.r_fs_stamp.len())] .contains(&target) } - _ => false, + _ => compute_pipe.is_some_and(|pipe| { + f.computes != 0 + && f.compute_pipe as usize == pipe + && f.cstamp[..(f.computes as usize).min(f.cstamp.len())].contains(&target) + }), }) .ok_or(ENOENT)?; if flags & 1 == 0 { @@ -953,7 +965,7 @@ impl Firmware { /// in the snapshot. Keep it until either its full receipt or its passed-abort proof. pub(crate) fn recovery_prepare_suspects( &mut self, - stage: [u32; 4], + stage: [u32; 2 + sizes::COMPUTE_PIPES], _event: u32, fault_asid: Option, ) -> Result { @@ -1058,11 +1070,13 @@ impl Firmware { self.engine.slot_wait = false; self.engine.ta_wave_wait = false; self.engine.held_wait = false; + self.engine.handoff_avoid_pipes = 0; self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() { + self.engine.handoff_avoid_pipes = 0; let Some(index) = self.engine.pick() else { break; }; @@ -1083,6 +1097,13 @@ impl Firmware { self.note_hold(&job, true, 0); break; } + // If the selected head waiter has no eligible compute pipe (e.g. a base-only + // VM limited to pipe 0 while an incumbent refills pipe 0, or a 9th VM when all + // pipes are occupied), let one compatible pipe drain for handoff while other + // pipes continue dispatching. + self.engine.handoff_avoid_pipes = self + .compute_handoff_pipe(&job) + .map_or(0, |pipe| 1u32 << pipe); let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); let ta_wave_paused = ta_val >= self.active_ta_wave_cap(); let mut alt: Option = None; @@ -1152,6 +1173,7 @@ impl Firmware { match alt { Some(i) => job = self.engine.pending[i].clone(), None => { + self.engine.handoff_avoid_pipes = 0; self.engine.slot_wait = self .engine .pending @@ -1249,7 +1271,10 @@ impl Firmware { } match job.check_command_dependencies(job.progress.sent()) { Ok(()) => {} - Err(e) if e == EAGAIN => break, + Err(e) if e == EAGAIN => { + self.engine.handoff_avoid_pipes = 0; + break; + } Err(e) => { self.engine.unpend(&job); let _ = job.mark_terminal_retired(); @@ -1257,7 +1282,9 @@ impl Firmware { continue; } } - match self.publish_prefix(&job, done, &mut pending_rings) { + let pub_res = self.publish_prefix(&job, done, &mut pending_rings); + self.engine.handoff_avoid_pipes = 0; + match pub_res { Ok(()) => { self.engine.turn += 1; job.queue.turn.store(self.engine.turn, Ordering::Relaxed); @@ -1402,7 +1429,7 @@ impl Firmware { || f.recovery_suspect || f.initbm || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) - || ((is_compute || (is_render && f.computes != 0)) + || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) || (is_render && !self.render_can_pipeline(job)) @@ -1497,15 +1524,16 @@ impl Firmware { return true; } match command(job, sent) { - Some(Command::Compute(_)) => { + Some(Command::Compute(c)) => { let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); + let scs = job.resources.compute_scs() || c.is_rt(); compute_count > 0 && !self.slots.compute_exhausted() && (compute_count >= params::compute_flights() || job .resources .compute_slot_mask() - .is_ok_and(|mask| !self.slots.compute_available_in_mask(mask))) + .is_ok_and(|mask| !self.has_compute_pipe_for_vm(&job.vm, mask, scs))) } Some(Command::Render(_)) => { let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); @@ -1607,10 +1635,10 @@ impl Firmware { /// dispatch from one client cannot starve another client's fragment shading into a /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. - /// - Compute never runs beside compute of another VM, on either pipe: with several clients - /// dispatching barrier-free compute, the overlapped dispatches occasionally lost their - /// results without a fault (loads read zero, readbacks came back empty or partial), - /// which one client alone never does. G15 runs one VM at a time for the same reason. + /// - Cross-VM non-SCS compute runs concurrently across disjoint per-VM firmware workqueues + /// (`graph.compute[0..COMPUTE_PIPES]`): two different VMs/ASIDs are never queued into the + /// same in-flight `qinfo`, avoiding cross-VM engine drains without sharing an active + /// workqueue ring. SCS/RT compute still drains against non-SCS or other-VM compute. fn can_queue_behind(&self, job: &Arc) -> bool { let mut ta_pending = None; self.can_queue_behind_with_ta(job, &mut ta_pending) @@ -1677,14 +1705,17 @@ impl Firmware { }) }) })); - let cross_vm = e.flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &job.vm)); + let cross_vm_render = e + .flights + .iter() + .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); let scs = job.resources.compute_scs() || c.is_rt(); let scs_conflict = e .flights .iter() .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); - !cross_vm + !cross_vm_render && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() @@ -1693,7 +1724,7 @@ impl Firmware { && job .resources .compute_slot_mask() - .is_ok_and(|mask| self.slots.compute_available_in_mask(mask)) + .is_ok_and(|mask| self.has_compute_pipe_for_vm(&job.vm, mask, scs)) } Some(Command::Render(r)) => { let cross_vm_compute = e @@ -1822,8 +1853,16 @@ impl Firmware { let Ok(slot_mask) = head.resources.compute_slot_mask() else { return false; }; - let pipe = - self.choose_compute_pipe(&head.queue, [None, None], slot_mask, false, false); + let Some(pipe) = self.choose_compute_pipe( + &head.queue, + &head.vm, + [None; sizes::COMPUTE_PIPES], + slot_mask, + false, + false, + ) else { + return false; + }; let free_c = self.slots.free_compute_in_mask_for_pipe(slot_mask, pipe) as usize; let cap = super::hw::sizes::COALESCE_MAX_CMDS .min(free_c) @@ -2219,79 +2258,306 @@ impl Firmware { }) } - /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command: - /// - Base-only/SCS VMs (bits strictly in `0..PIPE1_COMPUTE_START`) or states where pipe 1 - /// has no available unit in `slot_mask` stay on pipe 0 so `0..PIPE1_COMPUTE_START` never - /// split across two pipes. - /// - If the command waits only on one pipe, reuse that pipe (in-order ring, zero `c2c` - /// barrier). - /// - If barrier-free (`[None, None]`), `!heavy_compute`, and `queue` already has an active + /// When a ready compute job cannot queue behind active flights because every compatible + /// compute pipe is currently occupied by another VM (for example a base-only VM limited to + /// pipe 0, or a 9th VM when all 8 pipes are occupied), pick one compatible occupied pipe to + /// drain for handoff while other pipes continue dispatching. + fn compute_handoff_pipe(&self, job: &Arc) -> Option { + let sent = job.progress.sent(); + let Some(Command::Compute(c)) = command(job, sent) else { + return None; + }; + if job.vm.status.get() != 0 + || self.slots.compute_exhausted() + || job.check_command_dependencies(sent).is_err() + { + return None; + } + let Ok(slot_mask) = job.resources.compute_slot_mask() else { + return None; + }; + let scs = job.resources.compute_scs() || c.is_rt(); + if self.has_compute_pipe_for_vm(&job.vm, slot_mask, scs) { + return None; + } + let mut other_load = [0usize; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 && !Arc::ptr_eq(&fl.job.vm, &job.vm) { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + other_load[p] += fl.computes as usize; + } + } + let limit = if scs { 1 } else { sizes::COMPUTE_PIPES }; + let mut best: Option<(usize, usize)> = None; + for (p, &load) in other_load.iter().enumerate().take(limit) { + if load == 0 { + continue; + } + let allowed = if p == 0 { + slot_mask + } else { + slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + }; + if allowed == 0 || self.slots.compute_exhausted_in_mask(allowed) { + continue; + } + if best.is_none_or(|(_, prev)| load < prev) { + best = Some((p, load)); + } + } + best.map(|(p, _)| p) + } + + /// Whether `vm` can acquire a compute pipe (`0..COMPUTE_PIPES`) without sharing an active + /// `qinfo` with another VM, exceeding `MAX_VM_COMPUTE_PIPES`, using a pipe draining for + /// handoff, or lacking an available unit in `slot_mask`. + fn has_compute_pipe_for_vm( + &self, + vm: &Arc, + slot_mask: u32, + rt_compute: bool, + ) -> bool { + let avoid = self.engine.handoff_avoid_pipes; + let mut active_same = [false; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + let mut any_rt = rt_compute; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] = true; + } else { + active_other[p] = true; + } + any_rt |= fl.rt_compute; + } + } + if any_rt { + return (avoid & 1) == 0 + && !active_other[0] + && self.slots.compute_available_in_mask_for_pipe(slot_mask, 0); + } + let vm_active_pipes = active_same.iter().filter(|&&a| a).count(); + for p in 0..sizes::COMPUTE_PIPES { + if (avoid & (1u32 << p)) != 0 || active_other[p] { + continue; + } + if !active_same[p] && vm_active_pipes >= sizes::MAX_VM_COMPUTE_PIPES { + continue; + } + if self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + return true; + } + } + false + } + + /// Minimum active compute count on another pipe eligible for `vm` besides `pipe`, used to + /// balance heavy barrier-free compute across up to `MAX_VM_COMPUTE_PIPES` pipes of `vm`. + fn other_vm_compute_pipe_load( + &self, + vm: &Arc, + pipe: usize, + slot_mask: u32, + ) -> Option { + let mut active_same = [0usize; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] += fl.computes as usize; + } else { + active_other[p] = true; + } + } + } + let vm_active_pipes = active_same.iter().filter(|&&n| n != 0).count(); + let mut best: Option = None; + for p in 0..sizes::COMPUTE_PIPES { + if p == pipe || active_other[p] { + continue; + } + if active_same[p] == 0 && vm_active_pipes >= sizes::MAX_VM_COMPUTE_PIPES { + continue; + } + if !self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { + continue; + } + best = Some(match best { + Some(prev) => prev.min(active_same[p]), + None => active_same[p], + }); + } + best + } + + /// Chooses which compute pipe (`0..COMPUTE_PIPES`) executes the next compute command + /// without ever mixing two different VMs/ASIDs inside one active `qinfo`: + /// - RT/SCS compute (or any flight while RT/SCS compute is active) stays on pipe 0. + /// - If the command waits only on one pipe of its own VM, reuse that pipe (in-order ring, + /// zero `c2c` barrier). + /// - If barrier-free (`waits` all `None`), `!heavy_compute`, and `queue` already has an active /// compute flight on a single pipe with free units, keep that light queue pipe-affine so /// consecutive horizon submits fold onto one workqueue without splitting across pipes. - /// - Otherwise (heavy compute streams, other queues, cross-VM compute, or waiting on both - /// pipes `[Some, Some]`), pick the pipe with fewer active compute commands, breaking ties - /// by `next_compute_pipe`. + /// - Otherwise, lease an idle pipe (preferring `vm`'s warm-affine `pipe_last_vm`, then never- + /// used, then LRU, preferring secondary pipes `1..COMPUTE_PIPES` for fresh/LRU picks so + /// pipe 0 stays free for base-only/SCS VMs) up to `MAX_VM_COMPUTE_PIPES` active pipes per + /// VM, or pick `vm`'s active eligible pipe with fewest commands in flight. + /// - Returns `None` when every eligible pipe is currently active for another VM or has no + /// available compute unit. fn choose_compute_pipe( &self, queue: &Arc, + vm: &Arc, waits: [Option; sizes::COMPUTE_PIPES], slot_mask: u32, rt_compute: bool, heavy_compute: bool, - ) -> usize { - if rt_compute - || self - .engine - .flights - .iter() - .any(|fl| fl.computes != 0 && fl.rt_compute) - || !self.slots.compute_available_in_mask_for_pipe(slot_mask, 1) - { - return 0; + ) -> Option { + let mut active_same = [0usize; sizes::COMPUTE_PIPES]; + let mut active_other = [false; sizes::COMPUTE_PIPES]; + let mut any_rt = rt_compute; + for fl in &self.engine.flights { + if fl.computes != 0 { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + if Arc::ptr_eq(&fl.job.vm, vm) { + active_same[p] += fl.computes as usize; + } else { + active_other[p] = true; + } + any_rt |= fl.rt_compute; + } } - match waits { - [Some(_), None] => return 0, - [None, Some(_)] => return 1, - [None, None] if !heavy_compute => { - let mut q_pipe: Option = None; - for fl in &self.engine.flights { - if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { - let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); - match q_pipe { - None => q_pipe = Some(p), - Some(prev) if prev == p => {} - Some(_) => { - q_pipe = None; - break; - } + let avoid = self.engine.handoff_avoid_pipes; + let vm_active_pipes = active_same.iter().filter(|&&n| n != 0).count(); + let pipe_ok = |p: usize| -> bool { + (avoid & (1u32 << p)) == 0 + && !active_other[p] + && (active_same[p] != 0 || vm_active_pipes < sizes::MAX_VM_COMPUTE_PIPES) + && self.slots.compute_available_in_mask_for_pipe(slot_mask, p) + }; + if any_rt { + return pipe_ok(0).then_some(0); + } + let mut wait_pipe: Option = None; + let mut wait_count = 0usize; + for (p, w) in waits.iter().enumerate() { + if w.is_some() { + wait_pipe = Some(p); + wait_count += 1; + } + } + if wait_count == 1 { + if let Some(p) = wait_pipe { + if pipe_ok(p) { + return Some(p); + } + } + } + if wait_count == 0 && !heavy_compute { + let mut q_pipe: Option = None; + for fl in &self.engine.flights { + if fl.computes != 0 && Arc::ptr_eq(&fl.job.queue, queue) { + let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); + match q_pipe { + None => q_pipe = Some(p), + Some(prev) if prev == p => {} + Some(_) => { + q_pipe = None; + break; } } } - if let Some(p) = q_pipe { - if self.slots.compute_available_in_mask_for_pipe(slot_mask, p) { - return p; - } + } + if let Some(p) = q_pipe { + if pipe_ok(p) { + return Some(p); } } - [None, None] | [Some(_), Some(_)] => {} - } - if !self.slots.compute_available_in_mask_for_pipe(slot_mask, 0) { - return 1; } - let mut active = [0usize; sizes::COMPUTE_PIPES]; - for fl in &self.engine.flights { - if fl.computes != 0 { - let p = (fl.compute_pipe as usize).min(sizes::COMPUTE_PIPES - 1); - active[p] += fl.computes as usize; + let pick_idle = |prefer_secondary: bool| -> Option { + // 1. Warm VM-affine idle pipe (keeps the same VM on the same `qinfo`). + for p in 0..sizes::COMPUTE_PIPES { + if active_same[p] == 0 + && pipe_ok(p) + && self.engine.pipe_last_vm[p] == Some(vm.id) + { + return Some(p); + } + } + // 2. Never-used idle pipe, preferring secondary pipes for extension-capable VMs so + // pipe 0 remains immediately available to base-only and SCS VMs. + let mut order = [0usize; sizes::COMPUTE_PIPES]; + if prefer_secondary { + for i in 0..(sizes::COMPUTE_PIPES - 1) { + order[i] = i + 1; + } + order[sizes::COMPUTE_PIPES - 1] = 0; + } else { + for (i, slot) in order.iter_mut().enumerate() { + *slot = i; + } + } + for &p in &order { + if active_same[p] == 0 && pipe_ok(p) && self.engine.pipe_last_vm[p].is_none() { + return Some(p); + } + } + // 3. Least-recently-used idle pipe, preferring secondary pipes when `prefer_secondary` + // is set so pipe 0 remains available to base-only and SCS VMs. + if prefer_secondary { + let mut best_sec: Option<(usize, u64)> = None; + for p in 1..sizes::COMPUTE_PIPES { + if active_same[p] == 0 && pipe_ok(p) { + let used = self.engine.pipe_last_used[p]; + if best_sec.is_none_or(|(_, prev)| used < prev) { + best_sec = Some((p, used)); + } + } + } + if let Some((p, _)) = best_sec { + return Some(p); + } + if active_same[0] == 0 && pipe_ok(0) { + return Some(0); + } + } else { + let mut best: Option<(usize, u64)> = None; + for p in 0..sizes::COMPUTE_PIPES { + if active_same[p] == 0 && pipe_ok(p) { + let used = self.engine.pipe_last_used[p]; + if best.is_none_or(|(_, prev)| used < prev) { + best = Some((p, used)); + } + } + } + if let Some((p, _)) = best { + return Some(p); + } + } + None + }; + let has_secondary = (slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1)) != 0; + let prefer_secondary = has_secondary && active_other.iter().any(|&a| a); + if vm_active_pipes < sizes::MAX_VM_COMPUTE_PIPES { + if let Some(p) = pick_idle(prefer_secondary) { + return Some(p); } } - if active[0] < active[1] { - 0 - } else if active[1] < active[0] { - 1 - } else { - (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES + // Reuse this VM's least-loaded eligible active pipe, breaking ties by `next_compute_pipe`. + let start = (self.engine.next_compute_pipe as usize) % sizes::COMPUTE_PIPES; + let mut best: Option<(usize, usize)> = None; + for i in 0..sizes::COMPUTE_PIPES { + let p = (start + i) % sizes::COMPUTE_PIPES; + if active_same[p] != 0 && pipe_ok(p) { + let load = active_same[p]; + if best.is_none_or(|(_, prev)| load < prev) { + best = Some((p, load)); + } + } } + best.map(|(p, _)| p) } /// Whether some of `job`'s commands were published: such a job is retained after a @@ -2518,11 +2784,18 @@ impl Firmware { .and_then(|o| o.wait_through[super::command::COMPUTE]), )?; let heavy = self.compute_queue_is_heavy(&job.queue, now_ns()); - ( - self.choose_compute_pipe(&job.queue, waits, slot_mask, rt_compute, heavy), + let Some(pipe) = self.choose_compute_pipe( + &job.queue, + &job.vm, waits, + slot_mask, + rt_compute, heavy, - ) + ) else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; + (pipe, waits, heavy) }; let pipe_behind = !render && self @@ -2530,13 +2803,27 @@ impl Firmware { .flights .iter() .any(|fl| fl.computes != 0 && fl.compute_pipe as usize == compute_pipe); + if !render && class_behind { + self.latch_compute_channel_receipts()?; + } for &channel in channels { let pipe = self.channels.channel(channel); let producer = self.channels.producer(channel); let busy = if class_behind { - // Behind in-flight commands on this class: post after their unconsumed records. + // Behind in-flight commands on this class: post after their unconsumed records + // and never lap an unsettled compute flight's shared submit-channel record. + let wrap_bound = channel == Channel::Compute + && self.engine.flights.iter().any(|fl| { + fl.computes != 0 + && !fl.chan_settled + && producer + .wrapping_sub((fl.rec[2] + RING_SLOTS - 1) % RING_SLOTS) + % RING_SLOTS + >= RING_SLOTS - 2 + }); pipe.write()? != producer || producer.wrapping_sub(pipe.read()?) % RING_SLOTS >= sizes::AHEAD_RECORDS + || wrap_bound } else { pipe.read()? != producer || pipe.completion()? != producer @@ -2598,10 +2885,12 @@ impl Firmware { return Err(EAGAIN); } } else if !render && pipe_behind { - // Room for optional fs2c + cross-pipe c2c barriers plus compute work entry. + // Room for optional fs2c + up to COMPUTE_PIPES-1 cross-pipe barriers + compute work. + let min_free = 2 + sizes::COMPUTE_PIPES as u32; c_read = self.graph.compute[compute_pipe].qstate.r32(qstate::READ)?; if c_read >= 256 - || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP >= sizes::QUEUE_CAP - 4 + || prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP + >= sizes::QUEUE_CAP - min_free { self.engine.slot_wait = true; return Err(EAGAIN); @@ -2639,16 +2928,22 @@ impl Firmware { active_pipe[p] += fl.computes as usize; } } - let active_computes = active_pipe[0] + active_pipe[1]; - // Keep heavy barrier-free compute balanced across both CDM pipes while light + let active_computes: usize = active_pipe.iter().sum(); + // Keep heavy barrier-free compute balanced across this VM's CDM pipes while light // single-queue compute streams stay pipe-affine and fold freely into one batch. let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES] { - active_pipe[1 - compute_pipe].saturating_sub(active_pipe[compute_pipe] + 1) + match self.other_vm_compute_pipe_load(&job.vm, compute_pipe, slot_mask) { + Some(other_load) => { + other_load.saturating_sub(active_pipe[compute_pipe] + 1) + } + None => usize::MAX, + } } else { usize::MAX }; let used = prefix.c_head.wrapping_sub(c_read) % sizes::QUEUE_CAP; - let ring_more = (sizes::QUEUE_CAP.saturating_sub(4)).saturating_sub(used) as usize; + let ring_more = (sizes::QUEUE_CAP.saturating_sub(2 + sizes::COMPUTE_PIPES as u32)) + .saturating_sub(used) as usize; let mut more_slots = free_c .min(params::compute_flights().saturating_sub(active_computes + 1)) .min(sizes::COMPUTE_SLOTS.saturating_sub(1)) @@ -3232,20 +3527,23 @@ impl Firmware { self.engine.target[compute_pipe] = f.target; self.engine.head[compute_pipe] = f.head; self.engine.queue_registered[compute_pipe] = true; - self.engine.next_compute_pipe = (compute_pipe as u8) ^ 1; + self.engine.pipe_use_seq = self.engine.pipe_use_seq.wrapping_add(1); + self.engine.pipe_last_vm[compute_pipe] = Some(job.vm.id); + self.engine.pipe_last_used[compute_pipe] = self.engine.pipe_use_seq; + self.engine.next_compute_pipe = ((compute_pipe + 1) % sizes::COMPUTE_PIPES) as u8; } self.engine.events = self.events.compute_events; self.engine.stage_seen = self.events.stage_events; f.behind = behind; self.stat_publish(f); - if !class_behind { - // First in-flight command on this class starts about now; commands queued behind - // their own class keep that class's oldest deadline without renewing the other. - if render { + // First in-flight command on this render class or compute pipe starts about now; + // commands queued behind the same class/pipe keep its oldest deadline. + if render { + if !class_behind { self.renew_render_deadline(); - } else { - self.renew_compute_deadline(); } + } else if !pipe_behind { + self.renew_compute_pipe_deadline(compute_pipe); } job.progress.set_sent(end); for k in index..end { @@ -3315,7 +3613,6 @@ impl Firmware { return Err(EAGAIN); } let pipe = pf.compute_pipe; - let other = 1 - pipe; let n = super::recovery::logic::next_ordinal(pf.n).ok_or(EOVERFLOW)?; let pipe_n = super::recovery::logic::next_ordinal(pf.pipe_n).ok_or(EOVERFLOW)?; let target = encode::stamp(pipe_n); @@ -3434,22 +3731,28 @@ impl Firmware { } else { None }; - let c2c_bar = if let Some(wait_c) = c_waits[other] { - let producer_initbm = wait_c.initbm || self.engine.flights.iter().any(|fl| fl.initbm); - let bar_type = cross_engine_barrier_type(producer_initbm, false); - let bar = encode::barrier( - self.graph.compute[other].fw_stamp.va, - wait_c.stamp, - work::compute::EVENTS[other], - target, - 0, - bar_type, - ); - s.barrier.write(work::barrier::SIZE, &bar)?; - true - } else { - false - }; + let mut c2c_mask = 0u32; + for (p_idx, wait_opt) in c_waits.iter().enumerate() { + if p_idx == pipe { + continue; + } + if let Some(wait_c) = *wait_opt { + let producer_initbm = + wait_c.initbm || self.engine.flights.iter().any(|fl| fl.initbm); + let bar_type = cross_engine_barrier_type(producer_initbm, false); + let bar = encode::barrier( + self.graph.compute[p_idx].fw_stamp.va, + wait_c.stamp, + work::compute::EVENTS[p_idx], + target, + 0, + bar_type, + ); + let off = (1 + p_idx) * work::barrier::SIZE; + s.barrier.write(off, &bar)?; + c2c_mask |= 1u32 << p_idx; + } + } f.uma_submitted = submitted; f.csubmitted[member] = submitted; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); @@ -3465,10 +3768,13 @@ impl Firmware { } else { f.cwait[member] = 0; } - if c2c_bar { + let mut rem = c2c_mask; + while rem != 0 { + let p_idx = rem.trailing_zeros() as usize; + rem &= rem - 1; g.ring.w64( 8 * pf.c_head as usize, - s.barrier.va + work::barrier::SIZE as u64, + s.barrier.va + ((1 + p_idx) * work::barrier::SIZE) as u64, )?; pf.c_head = (pf.c_head + 1) % sizes::QUEUE_CAP; } diff --git a/drivers/gpu/drm/asahi/g16/event.rs b/drivers/gpu/drm/asahi/g16/event.rs index d2f1463e7d21a0..fa46695cb87684 100644 --- a/drivers/gpu/drm/asahi/g16/event.rs +++ b/drivers/gpu/drm/asahi/g16/event.rs @@ -10,11 +10,15 @@ use kernel::{bindings, device, prelude::*}; use super::channel::Ring; use super::fw::channels::{RING_SLOTS, STATE_READ, STATE_WRITE}; -use super::hw::rings; +use super::fw::work::compute; +use super::hw::{rings, sizes}; use super::regs::{mb, rmb, wmb}; pub(crate) const RECORD_WORDS: usize = 18; -pub(crate) const STAGE_EVENTS: [u32; 4] = [0x70, 0x71, 15, 16]; +pub(crate) const STAGE_COUNT: usize = 2 + sizes::COMPUTE_PIPES; +const COMPUTE_EVENT_MASK: u32 = ((1u32 << sizes::COMPUTE_PIPES) - 1) << compute::EVENT; +const _: () = assert!(compute::EVENTS.len() == sizes::COMPUTE_PIPES); +const _: () = assert!(compute::EVENT as usize + sizes::COMPUTE_PIPES <= 32); /// Retained only for the allocator's pending-growth container. M4 does not /// interpret a G15 type-7 record as an allocator request. pub(crate) const GROW_QUEUE: usize = 8; @@ -45,7 +49,7 @@ pub(crate) struct Events { /// First notification of the pending recovery, for its absolute deadline. pub(crate) recovery_started_ns: Option, pub(crate) channel_errors: u32, - pub(crate) event_ns: [u64; 4], + pub(crate) event_ns: [u64; STAGE_COUNT], pub(crate) grow: KVec<[u32; 14]>, #[allow(dead_code)] pub(crate) grow_lost: u32, @@ -63,7 +67,7 @@ impl Events { last_statistics: None, recovery_started_ns: None, channel_errors: 0, - event_ns: [0; 4], + event_ns: [0; STAGE_COUNT], grow: KVec::new(), grow_lost: 0, } @@ -124,8 +128,8 @@ impl Events { }; match kind { 1 => { - // Type 1 carries 128 completion bits across words 1..=4; STAGE_EVENTS - // ([0x70, 0x71, 15, 16]) inspects word 1 (compute 15/16) and word 4 (TA/FS). + // Type 1 carries 128 completion bits across words 1..=4; compute pipe events + // (15..15+COMPUTE_PIPES) live in word 1 and TA/FS (0x70/0x71) live in word 4. let (w1, w4) = match ring.ring.r32(base + 4).and_then(|w1| { Ok((w1, ring.ring.r32(base + 16)?)) }) { @@ -137,22 +141,23 @@ impl Events { return Err(err); } }; - for (stage, event) in STAGE_EVENTS.iter().enumerate() { - let bits = match 1 + *event as usize / 32 { - 1 => w1, - 4 => w4, - _ => continue, - }; - if bits & (1u32 << (*event % 32)) == 0 { - continue; - } - self.event_ns[stage] = now; + if w4 & (1u32 << (0x70 % 32)) != 0 { + self.event_ns[0] = now; self.stage_events = self.stage_events.wrapping_add(1); - if stage == 1 { - self.fs_events = self.fs_events.wrapping_add(1); - } else if stage >= 2 { - self.compute_events = self.compute_events.wrapping_add(1); - } + } + if w4 & (1u32 << (0x71 % 32)) != 0 { + self.event_ns[1] = now; + self.stage_events = self.stage_events.wrapping_add(1); + self.fs_events = self.fs_events.wrapping_add(1); + } + let mut cbits = w1 & COMPUTE_EVENT_MASK; + while cbits != 0 { + let bit = cbits.trailing_zeros(); + cbits &= cbits - 1; + let pipe = (bit - compute::EVENT) as usize; + self.event_ns[2 + pipe] = now; + self.stage_events = self.stage_events.wrapping_add(1); + self.compute_events = self.compute_events.wrapping_add(1); } } 4 => { diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index 85daf5876aec3b..8954dcaa8981c6 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -43,7 +43,17 @@ pub(crate) const PAGE_LIST_SIZE: usize = 0x4000; pub(crate) const START_SCS: usize = 0x40; pub(crate) const EVENT: u32 = 15; /// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. -pub(crate) const EVENTS: [u32; 2] = [EVENT, 16]; +/// All events reside in type-1 event word 1 (`15..32`) so event draining reads only words 1 and 4. +pub(crate) const EVENTS: [u32; 8] = [EVENT, 16, 17, 18, 19, 20, 21, 22]; + +/// Resolves a firmware compute completion event back to its compute pipe index (`0..EVENTS.len()`). +pub(crate) const fn pipe_of_event(event: u32) -> Option { + if event >= EVENT && (event - EVENT) < EVENTS.len() as u32 { + Some((event - EVENT) as usize) + } else { + None + } +} /// The binding generation. pub(crate) const GENERATION: usize = 0x88b; diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index f5c3e8debcab16..8120f0adf5ba87 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -360,13 +360,13 @@ impl RenderGraph { /// the firmware-cached work rings from a probe-time device-lifetime /// [`Factory::persistent_objects_probe`] pool. pub(crate) struct GraphSession { - compute: [ComputeGraphSession; sizes::COMPUTE_PIPES], + compute: KVec, render: RenderGraphSession, } pub(crate) struct Graphs { pub(crate) dev: ARef, - pub(crate) compute: [ComputeGraph; sizes::COMPUTE_PIPES], + pub(crate) compute: KVec, pub(crate) render: RenderGraph, /// Owns the firmware-cached work rings for the device lifetime (never dropped). _ring_objects: core::mem::ManuallyDrop, @@ -377,10 +377,10 @@ impl Graphs { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. let sched_ctx = alloc(o, sched_ctx::SIZE, Class::Fw, None, 0, false)?; - let compute = [ - ComputeGraphSession::new(o, sched_ctx.clone())?, - ComputeGraphSession::new(o, sched_ctx.clone())?, - ]; + let mut compute = KVec::with_capacity(sizes::COMPUTE_PIPES, GFP_KERNEL)?; + for _ in 0..sizes::COMPUTE_PIPES { + compute.push(ComputeGraphSession::new(o, sched_ctx.clone())?, GFP_KERNEL)?; + } let render = RenderGraphSession::new(o, sched_ctx)?; Ok(GraphSession { compute, render }) } @@ -393,8 +393,10 @@ impl Graphs { ) -> Result { // Never dropped even on partial failure: ASC-cached mappings have no qualified teardown. let mut ring_objects = core::mem::ManuallyDrop::new(factory.persistent_objects_probe()); - let [c0, c1] = session.compute; - let compute = [c0.finish(&mut ring_objects)?, c1.finish(&mut ring_objects)?]; + let mut compute = KVec::with_capacity(sizes::COMPUTE_PIPES, GFP_KERNEL)?; + for c in session.compute { + compute.push(c.finish(&mut ring_objects)?, GFP_KERNEL)?; + } let render = session.render.finish(&mut ring_objects)?; ring_objects.finish_private()?; Ok(Self { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 4cd4ad02d8f35c..78dd943c5c4de7 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -748,7 +748,19 @@ pub(crate) mod sizes { pub(crate) const FREELIST_SEED: u32 = 8192; pub(crate) const QUEUE_CAP: u32 = 256; /// Independent firmware compute workqueue pipes sharing `Channel::Compute` and `sched_ctx`. - pub(crate) const COMPUTE_PIPES: usize = 2; + /// Each pipe owns a disjoint `ComputeGraph` (`qinfo`, work ring, `qstate`, `fw_stamp`, + /// `notifier`, `threshold`, `job_list`) and completion event (`work::compute::EVENTS`) so + /// concurrent compute VMs lease disjoint workqueues instead of mixing ASIDs in one active + /// `qinfo`. Pipe 0 exclusively owns `0..PIPE1_COMPUTE_START` for base-only and SCS VMs; + /// secondary pipes `1..COMPUTE_PIPES` share `PIPE1_COMPUTE_START..COMPUTE_UNITS` (18 units + /// for 7 secondary pipes, leaving 11 active units beyond the 7 undisplaced retired leases). + pub(crate) const COMPUTE_PIPES: usize = 8; + /// Maximum concurrent compute pipes one VM may occupy at once, preserving the render + /// ring-entry bound (`MAX_RENDER_RING_ENTRIES = 5`) since cross-VM render/compute drains. + pub(crate) const MAX_VM_COMPUTE_PIPES: usize = 2; + const _: () = assert!(COMPUTE_PIPES >= 2 && COMPUTE_PIPES <= 16); + const _: () = assert!(MAX_VM_COMPUTE_PIPES >= 2 && MAX_VM_COMPUTE_PIPES <= COMPUTE_PIPES); + const _: () = assert!(COMPUTE_UNITS - PIPE1_COMPUTE_START >= (COMPUTE_PIPES - 1) * 2); /// Compute units claimable in one batched compute prefix (matches `COMPUTE_UNITS`). pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base physical PB/UMA allocator slots allocated per VM on first render. diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 0a647cbbd2cb5f..ab2c72c68a129d 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -760,14 +760,15 @@ impl Firmware { let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; + let recovery = recovery::Recovery::new()?; let render_cmds = resources::RenderCmds::new()?; let compute_cmds = resources::ComputeCmds::new()?; let private_factory = booted.objects.private_factory(render_cmds, compute_cmds); let graph = graph::Graphs::finish(dev, graph_session, &private_factory)?; let slot = KBox::::new_uninit(GFP_KERNEL)?; - Ok((graph, private_factory, slots, pools, vms, engine, slot)) + Ok((graph, private_factory, slots, pools, vms, engine, recovery, slot)) })(); - let (graph, private_factory, slots, pools, vms, engine, slot) = match backend { + let (graph, private_factory, slots, pools, vms, engine, recovery, slot) = match backend { Ok(backend) => backend, Err(error) => { dev_err!( @@ -798,7 +799,7 @@ impl Firmware { graph, slots, engine, - recovery: recovery::Recovery::new(), + recovery, power, pools, vms, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index edb67cb71d1f0a..cac1bca48a326f 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -623,9 +623,7 @@ 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`. 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)); - dh <= dc && dc <= dt + super::recovery::logic::ring_passed(c, b, h, t, m) } impl Firmware { @@ -924,9 +922,6 @@ impl Firmware { render_behind = true; } } - if compute_behind[0] && compute_behind[1] && render_behind { - break; - } } rmb(); for p in 0..super::hw::sizes::COMPUTE_PIPES { @@ -1098,15 +1093,58 @@ impl Firmware { } let pipe = self.channels.channel(channel); if passed { + let read = pipe.read()?; + let comp = pipe.completion()?; + if read >= slots || comp >= slots { + return Ok(false); + } let first = (record + slots - 1) % slots; let producer = self.channels.producer(channel); - Ok(ring_passed(pipe.read()?, first, record, producer, slots) - && ring_passed(pipe.completion()?, first, record, producer, slots)) + Ok(ring_passed(read, first, record, producer, slots) + && ring_passed(comp, first, record, producer, slots)) } else { Ok(pipe.read()? == record && pipe.completion()? == record && pipe.write()? == record) } } + /// Latches `Channel::Compute` read and completion proofs onto active compute flights before + /// the shared submit ring can lap them, so a long flight on one compute pipe stays retirable + /// even after other pipes wrap the 256-entry submit channel. + pub(crate) fn latch_compute_channel_receipts(&mut self) -> Result { + if !self + .engine + .flights + .iter() + .any(|f| f.computes != 0 && !f.chan_settled) + { + return Ok(()); + } + let slots = super::fw::channels::RING_SLOTS; + let pipe = self.channels.channel(Channel::Compute); + let read = pipe.read()?; + let comp = pipe.completion()?; + if read >= slots || comp >= slots { + return Ok(()); + } + let producer = self.channels.producer(Channel::Compute); + for f in self.engine.flights.iter_mut() { + if f.computes == 0 || f.chan_settled { + continue; + } + let record = f.rec[2]; + if record >= slots { + return Err(EINVAL); + } + let first = (record + slots - 1) % slots; + if ring_passed(read, first, record, producer, slots) + && ring_passed(comp, first, record, producer, slots) + { + f.chan_settled = true; + } + } + Ok(()) + } + /// 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( @@ -1172,7 +1210,7 @@ impl Firmware { ) -> Result> { let mut compute_idx = [None; super::hw::sizes::COMPUTE_PIPES]; let mut render_idx = None; - if check_compute[0] || check_compute[1] || *check_render { + if check_compute.iter().any(|&c| c) || *check_render { for (i, f) in self.engine.flights.iter().enumerate() { if f.computes != 0 { let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); @@ -1183,12 +1221,6 @@ impl Firmware { if *check_render && render_idx.is_none() && f.renders != 0 { render_idx = Some(i); } - if (!check_compute[0] || compute_idx[0].is_some()) - && (!check_compute[1] || compute_idx[1].is_some()) - && (!*check_render || render_idx.is_some()) - { - break; - } } } for p in 0..super::hw::sizes::COMPUTE_PIPES { @@ -1259,7 +1291,8 @@ impl Firmware { let tail = self.engine.target[pipe]; if !stamp_reached(g.fw_stamp.r32(0)?, f.target, tail) || !self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? - || !self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)? + || !(f.chan_settled + || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) { return Ok(Retirement::Pending); } @@ -1271,7 +1304,8 @@ impl Firmware { } else { if g.fw_stamp.r32(0)? != f.target || !self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? - || !self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)? + || !(f.chan_settled + || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) { return Ok(Retirement::Pending); } @@ -1517,8 +1551,12 @@ impl Firmware { } if f.renders != 0 { for m in 0..(f.renders as usize).min(f.r_ta_stamp.len()) { - self.recovery.last_retired.push(2, f.r_ta_stamp[m]); - self.recovery.last_retired.push(3, f.r_fs_stamp[m]); + self.recovery + .last_retired + .push(super::hw::sizes::COMPUTE_PIPES, f.r_ta_stamp[m]); + self.recovery + .last_retired + .push(super::hw::sizes::COMPUTE_PIPES + 1, f.r_fs_stamp[m]); } let committed = f.pb.as_ref().ok_or(EINVAL).and_then(|epoch| { self.pools.retire_flight( @@ -1637,12 +1675,13 @@ impl Firmware { self.power.utilization.idle(self.engine.stats.idle_from_ns); self.power.report_work(false); } - // The next prefix on the retired flight's class(es) starts executing about now. + // The next prefix on the retired flight's pipe/class starts executing about now. if f.renders != 0 { self.renew_render_deadline(); } if f.computes != 0 { - self.renew_compute_deadline(); + let pipe = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + self.renew_compute_pipe_deadline(pipe); } let job = f.job.clone(); let p = &job.progress; @@ -1754,7 +1793,7 @@ impl Firmware { } } - /// Progress of the oldest compute pipe 0/1 and oldest render flights: a FW stamp of a pipe on + /// Progress of the oldest compute pipes and oldest render flights: a FW stamp of a pipe on /// which its oldest flight still has unreached work moved since the last poll. Renews the /// deadline; the first call for a flight only records its position. /// [`Self::check_hangs`] calls it while no firmware recovery notification is pending. @@ -1762,13 +1801,13 @@ impl Firmware { if self.engine.flights.is_empty() { return; } + const CP: usize = super::hw::sizes::COMPUTE_PIPES; let (g, r, e) = (&self.graph.compute, &self.graph.render, &self.engine); - let mut fc: [Option<&Flight>; super::hw::sizes::COMPUTE_PIPES] = - [None; super::hw::sizes::COMPUTE_PIPES]; + let mut fc: [Option<&Flight>; CP] = [None; CP]; let mut fr = None; for f in e.flights.iter() { if f.computes != 0 { - let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + let p = (f.compute_pipe as usize).min(CP - 1); if fc[p].is_none() { fc[p] = Some(f); } @@ -1776,42 +1815,52 @@ impl Firmware { if fr.is_none() && f.renders != 0 { fr = Some(f); } - if fc[0].is_some() && fc[1].is_some() && fr.is_some() { - break; - } } // None denotes an inactive/reached stage. A real unreached stamp may be zero // immediately after native wrap and must remain distinguishable from completion. let pending = |observed, own, tail| (!stamp_reached(observed, own, tail)).then_some(observed); - let mut c = [None; super::hw::sizes::COMPUTE_PIPES]; - let (mut ta, mut fs) = (None, None); - let mut published = [0u64; 3]; - for p in 0..super::hw::sizes::COMPUTE_PIPES { + let mut next_progress = [None; CP + 2]; + let mut published = [0u64; CP + 1]; + for p in 0..CP { if let Some(f) = fc[p] { - c[p] = pending(g[p].fw_stamp.r32(0).unwrap_or(0), f.target, e.target[p]); + next_progress[p] = pending( + g[p].fw_stamp.r32(0).unwrap_or(0), + f.target, + e.target[p], + ); published[p] = f.published_ns; } } if let Some(fr) = fr { - ta = pending(r.fw_stamp[0].r32(0).unwrap_or(0), fr.ta_target, e.ta_target); - fs = pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); - published[2] = fr.published_ns; + next_progress[CP] = pending( + r.fw_stamp[0].r32(0).unwrap_or(0), + fr.ta_target, + e.ta_target, + ); + next_progress[CP + 1] = + pending(r.fw_stamp[1].r32(0).unwrap_or(0), fr.fs_target, e.fs_target); + published[CP] = fr.published_ns; + } + let mut compute_moved = [false; CP]; + for p in 0..CP { + compute_moved[p] = fc[p].is_some() + && e.progress_flight[p] == published[p] + && next_progress[p] != e.progress[p]; } - let compute_moved = (0..super::hw::sizes::COMPUTE_PIPES).any(|p| { - fc[p].is_some() && e.progress_flight[p] == published[p] && c[p] != e.progress[p] - }); let render_moved = fr.is_some() - && e.progress_flight[2] == published[2] - && [ta, fs] != [e.progress[2], e.progress[3]]; - if compute_moved { - self.renew_compute_deadline(); + && e.progress_flight[CP] == published[CP] + && [next_progress[CP], next_progress[CP + 1]] != [e.progress[CP], e.progress[CP + 1]]; + for (p, moved) in compute_moved.into_iter().enumerate() { + if moved { + self.renew_compute_pipe_deadline(p); + } } if render_moved { self.renew_render_deadline(); } self.engine.progress_flight = published; - self.engine.progress = [c[0], c[1], ta, fs]; + self.engine.progress = next_progress; } /// The device mutex still excludes slot reuse after owner-ledger retirement. Read the @@ -2007,16 +2056,16 @@ impl Firmware { if hi > lo { s.span_ticks = s.span_ticks.saturating_add(hi - lo); } - for b in 0..4 { - let t = self.events.event_ns[b]; - let skip = match b { - 2 => f.computes == 0 || f.compute_pipe != 0, - 3 => f.computes == 0 || f.compute_pipe != 1, - _ => f.renders == 0, - }; - if skip { - continue; + if f.renders != 0 { + for b in 0..2 { + let t = self.events.event_ns[b]; + first = first.min(t); + last = last.max(t); } + } + if f.computes != 0 { + let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); + let t = self.events.event_ns[2 + p]; first = first.min(t); last = last.max(t); } diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 45b68f3b08928e..13969c3b46ba8f 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -50,15 +50,22 @@ pub(crate) fn push_completion(done: &mut Completions, job: &Arc, result: Re done.push(job, result); } +const _: () = assert!(logic::RETIRED_COMPUTE_PIPES == super::hw::sizes::COMPUTE_PIPES); + pub(crate) struct Recovery { - /// Per-class host deadlines, ordinary and long-job ([`logic::Deadlines`]). + /// Render host deadlines, ordinary and long-job ([`logic::Deadlines`]). pub(crate) deadlines: logic::Deadlines, - /// Per-class (render, compute) long-command warning deadlines; diagnostic only. + /// Per-compute-pipe host deadlines, ordinary and long-job, so progress on one pipe + /// cannot mask a stalled flight on another compute pipe. + pub(crate) compute_deadlines: [logic::Deadlines; super::hw::sizes::COMPUTE_PIPES], + /// Render long-command warning deadline; diagnostic only. warning_deadline_ns: [u64; 2], + /// Per-compute-pipe long-command warning deadlines; diagnostic only. + compute_warning_deadline_ns: [u64; super::hw::sizes::COMPUTE_PIPES], pub(crate) long_commands: u64, pub(crate) publication_wait_deadline: Option, - /// Recently retired compute pipe 0/1 and TA/FS stamps, for late recovery snapshots. - pub(crate) last_retired: logic::RetiredStamps, + /// Recently retired compute pipe and TA/FS stamps, heap-boxed off the probe stack. + pub(crate) last_retired: KBox, /// Queue engine order: render, compute. A quarantined/exhausted class stays offline. pub(crate) unavailable: [Option; 2], pub(crate) errors_seen: u32, @@ -78,13 +85,19 @@ pub(crate) struct Recovery { } impl Recovery { - pub(crate) fn new() -> Self { - Self { + pub(crate) fn new() -> Result { + let mut retired = KBox::::new_uninit(GFP_KERNEL)?; + logic::RetiredStamps::init_zero(&mut *retired); + // SAFETY: `init_zero` initialized the entire `RetiredStamps` in place. + let last_retired = unsafe { retired.assume_init() }; + Ok(Self { deadlines: logic::Deadlines::EXPIRED, + compute_deadlines: [logic::Deadlines::EXPIRED; super::hw::sizes::COMPUTE_PIPES], warning_deadline_ns: [u64::MAX; 2], + compute_warning_deadline_ns: [u64::MAX; super::hw::sizes::COMPUTE_PIPES], long_commands: 0, publication_wait_deadline: None, - last_retired: logic::RetiredStamps::new(), + last_retired, unavailable: [None; 2], errors_seen: 0, statistics_seen: 0, @@ -98,7 +111,7 @@ impl Recovery { window_count: 0, running: false, fwlog_remaining: super::channel::RECOVERY_FWLOG_CAP, - } + }) } pub(crate) fn failed(&self) -> Option { @@ -124,13 +137,19 @@ impl Firmware { now.saturating_add(5_000_000_000); } - pub(crate) fn renew_compute_deadline(&mut self) { + pub(crate) fn renew_compute_pipe_deadline(&mut self, pipe: usize) { + let pipe = pipe.min(super::hw::sizes::COMPUTE_PIPES - 1); let now = now_ns(); let renewed = logic::Deadlines::renew(now, 0, params::compute_deadline_ms()); - self.recovery.deadlines.compute = renewed.compute; - self.recovery.deadlines.long_compute = renewed.long_compute; - self.recovery.warning_deadline_ns[super::command::COMPUTE] = - now.saturating_add(5_000_000_000); + self.recovery.compute_deadlines[pipe].compute = renewed.compute; + self.recovery.compute_deadlines[pipe].long_compute = renewed.long_compute; + self.recovery.compute_warning_deadline_ns[pipe] = now.saturating_add(5_000_000_000); + } + + pub(crate) fn renew_compute_deadline(&mut self) { + for pipe in 0..super::hw::sizes::COMPUTE_PIPES { + self.renew_compute_pipe_deadline(pipe); + } } pub(crate) fn renew_deadlines(&mut self) { @@ -202,24 +221,28 @@ impl Firmware { return Err(EIO); } if !self.engine.flights.is_empty() { + const CP: usize = super::hw::sizes::COMPUTE_PIPES; self.progress(); let now = now_ns(); - let has_render = self.engine.flights.iter().any(|flight| flight.renders != 0); - let has_compute = self - .engine - .flights - .iter() - .any(|flight| flight.computes != 0); - let has_long_render = self - .engine - .flights - .iter() - .any(|flight| flight.renders != 0 && flight.job.long()); - let has_long_compute = self - .engine - .flights - .iter() - .any(|flight| flight.computes != 0 && flight.job.long()); + let mut has_render = false; + let mut has_long_render = false; + let mut has_compute = [false; CP]; + let mut has_long_compute = [false; CP]; + for flight in &self.engine.flights { + if flight.renders != 0 { + has_render = true; + if flight.job.long() { + has_long_render = true; + } + } + if flight.computes != 0 { + let p = (flight.compute_pipe as usize).min(CP - 1); + if !has_compute[p] { + has_compute[p] = true; + has_long_compute[p] = flight.job.long(); + } + } + } if has_render && logic::expired( now, @@ -233,25 +256,29 @@ impl Firmware { "M4 GPU render command has no completion-stamp progress for 5s; execution may still be active\n" ); } - if has_compute - && logic::expired( - now, - self.recovery.warning_deadline_ns[super::command::COMPUTE], - ) - { - self.recovery.warning_deadline_ns[super::command::COMPUTE] = u64::MAX; - self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); - dev_warn!( - self.dev(), - "M4 GPU compute command has no completion-stamp progress for 5s; execution may still be active\n" - ); + let mut compute_expired = false; + for p in 0..CP { + if !has_compute[p] { + continue; + } + if logic::expired(now, self.recovery.compute_warning_deadline_ns[p]) { + self.recovery.compute_warning_deadline_ns[p] = u64::MAX; + self.recovery.long_commands = self.recovery.long_commands.saturating_add(1); + dev_warn!( + self.dev(), + "M4 GPU compute pipe {} command has no completion-stamp progress for 5s; execution may still be active\n", + p + ); + } + let pipe_deadline = self.recovery.compute_deadlines[p] + .select(true, has_long_compute[p]); + if logic::expired(now, pipe_deadline) { + compute_expired = true; + } } // Ray traversal and AS builds: every flight of such a job (`Job::long`). let render_deadline = self.recovery.deadlines.select(false, has_long_render); - let compute_deadline = self.recovery.deadlines.select(true, has_long_compute); - if (has_render && logic::expired(now, render_deadline)) - || (has_compute && logic::expired(now, compute_deadline)) - { + if (has_render && logic::expired(now, render_deadline)) || compute_expired { dev_err!( self.dev(), "M4 GPU administrative command deadline exceeded without firmware recovery; retaining owners and fail-stop (not proof of quiescence)\n" @@ -406,7 +433,12 @@ impl Firmware { /// 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; 4], event: u32, asid: Option) -> Result { + fn mark_recovery( + &mut self, + stage: [u32; 2 + super::hw::sizes::COMPUTE_PIPES], + event: u32, + asid: Option, + ) -> Result { let data = self.init.firmware_data(); for i in 0..data.snapshot_entries { let offset = data.snapshot + i * 8; @@ -505,7 +537,9 @@ impl Firmware { if logic::expired(now, deadline) { let _ = self.drain_auxiliary_rings(); // Which side stalled, and whether tiling or fragment work was left behind. - let stage = self.recovery_snapshot().unwrap_or_default(); + let stage = self + .recovery_snapshot() + .unwrap_or([0; 2 + super::hw::sizes::COMPUTE_PIPES]); dev_err!( self.dev(), "M4 GPU recovery exceeded 1000 ms: {} (phase {}, TA {:#x}/{:#x}, FS {:#x}/{:#x}, {} flights)\n", diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index 7efb44a8359da0..a205d213bd2214 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -19,6 +19,9 @@ pub(crate) const fn stamp_reached(obs: u32, own: u32, tail: u32) -> bool { /// `CONFIG_RUST_OVERFLOW_CHECKS`). #[allow(dead_code)] pub(crate) const fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { + if m == 0 || c >= m || b >= m || h >= m || t >= m { + return false; + } let dc = c.wrapping_add(m).wrapping_sub(b) % m; let dh = h.wrapping_add(m).wrapping_sub(b) % m; let dt = t.wrapping_add(m).wrapping_sub(b) % m; @@ -155,28 +158,41 @@ impl SnapshotEntry { /// Bounded per-stage history of recently retired firmware stamps. pub(crate) const RETIRED_STAMPS_CAP: usize = 64; +/// Number of compute pipes tracked by [`RetiredStamps`] (matches `hw::sizes::COMPUTE_PIPES`). +pub(crate) const RETIRED_COMPUTE_PIPES: usize = 8; +/// Total retired-stamp stages: compute pipes `0..RETIRED_COMPUTE_PIPES`, TA, FS. +pub(crate) const RETIRED_STAGES: usize = RETIRED_COMPUTE_PIPES + 2; -/// Bounded per-stage ring of recently retired compute pipe 0/1 and TA/FS firmware stamps +/// Bounded per-stage ring of recently retired compute pipe and TA/FS firmware stamps /// so a late recovery snapshot arriving after pipelined retirement resolves any recently /// retired member, not only the single newest flight. #[derive(Clone, Debug)] pub(crate) struct RetiredStamps { - stamps: [[u32; RETIRED_STAMPS_CAP]; 4], - len: [u8; 4], - next: [u8; 4], + stamps: [[u32; RETIRED_STAMPS_CAP]; RETIRED_STAGES], + len: [u8; RETIRED_STAGES], + next: [u8; RETIRED_STAGES], } impl RetiredStamps { pub(crate) const fn new() -> Self { Self { - stamps: [[0; RETIRED_STAMPS_CAP]; 4], - len: [0; 4], - next: [0; 4], + stamps: [[0; RETIRED_STAMPS_CAP]; RETIRED_STAGES], + len: [0; RETIRED_STAGES], + next: [0; RETIRED_STAGES], } } + /// Initializes an uninitialized heap slot to the empty zero state without materializing a + /// multi-kilobyte temporary on the caller's stack. + #[allow(dead_code)] + pub(crate) fn init_zero(slot: &mut core::mem::MaybeUninit) { + // SAFETY: All fields of `RetiredStamps` are integer arrays for which all-zeroes is valid + // and identical to `RetiredStamps::new()`. + unsafe { core::ptr::write_bytes(slot.as_mut_ptr(), 0, 1) }; + } + pub(crate) fn push(&mut self, stage: usize, target: u32) { - if stage >= 4 { + if stage >= RETIRED_STAGES { return; } let idx = self.next[stage] as usize; @@ -189,10 +205,9 @@ impl RetiredStamps { pub(crate) fn contains(&self, event: u32, target: u32) -> bool { let stage = match event { - 15 => 0, - 16 => 1, - 0x70 => 2, - 0x71 => 3, + e if (15..15 + RETIRED_COMPUTE_PIPES as u32).contains(&e) => (e - 15) as usize, + 0x70 => RETIRED_COMPUTE_PIPES, + 0x71 => RETIRED_COMPUTE_PIPES + 1, _ => return false, }; let len = self.len[stage] as usize; @@ -307,9 +322,16 @@ mod tests { assert!(!retired.contains(0x70, 0)); retired.push(0, 0x100); retired.push(1, 0x300); - retired.push(2, 0); - retired.push(3, 0x200); - for (event, target) in [(15, 0x100), (16, 0x300), (0x70, 0), (0x71, 0x200)] { + retired.push(RETIRED_COMPUTE_PIPES - 1, 0x700); + retired.push(RETIRED_COMPUTE_PIPES, 0); + retired.push(RETIRED_COMPUTE_PIPES + 1, 0x200); + for (event, target) in [ + (15, 0x100), + (16, 0x300), + (15 + RETIRED_COMPUTE_PIPES as u32 - 1, 0x700), + (0x70, 0), + (0x71, 0x200), + ] { assert!(retired.contains(event, target)); assert!(!retired.contains(event, target.wrapping_add(0x100))); } @@ -472,6 +494,8 @@ mod tests { assert!(stamp_reached(0x100, 0xffff_ff00, 0x200)); assert!(ring_passed(2, 0xfe, 1, 5, 256)); assert!(!ring_passed(0xff, 0xfe, 1, 5, 256)); + assert!(!ring_passed(256, 0, 1, 2, 256)); + assert!(!ring_passed(257, 0, 1, 2, 256)); assert!(!ring_passed(u32::MAX, 0, 1, 5, 256)); } } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 1d48b4cd996d4a..aa8f5ee3b6e4d3 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -37,10 +37,10 @@ impl UnitCmds { let coherent = Class::FwCoherent; Ok(Self { seq: alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?, - // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. + // Holds fs2c (+0x00) and per-pipe c2c (+(1 + pipe) * barrier::SIZE) barriers in 1 page. barrier: alloc( o, - barrier::SIZE * sizes::COMPUTE_PIPES, + barrier::SIZE * (1 + sizes::COMPUTE_PIPES), coherent, None, 0, @@ -50,6 +50,8 @@ impl UnitCmds { } } +const _: () = assert!(barrier::SIZE * (1 + sizes::COMPUTE_PIPES) <= super::hw::PAGE as usize); + /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. pub(crate) struct ComputeSlot { pub(crate) its: Arc, @@ -1392,40 +1394,51 @@ impl Slots { } let n = sizes::COMPUTE_UNITS; let base_cursor = (self.cursor as usize) % n; + let p0_mask = (1u32 << sizes::PIPE1_COMPUTE_START) - 1; + // On pipe 0, prefer pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) before spilling + // into secondary-pipe units (`PIPE1_COMPUTE_START..COMPUTE_UNITS`) so concurrent + // secondary pipes keep maximum unit headroom. + let tiers: [u32; 2] = if pipe == 0 { + [allowed & p0_mask, allowed & !p0_mask] + } else { + [allowed, 0] + }; let mut chosen = None; if let Some(id) = vm_id { - for i in 0..n { - let k = (base_cursor + i) % n; - if (allowed & (1u32 << k)) != 0 - && !self.compute.scrub_full[k] - && self.compute.owner[k] - .as_ref() - .is_some_and(|prev| prev.id == id) - && self.compute.lifetime.claim(k) - { - chosen = Some(k); - break; + // 1. Reuse a warm unit already owned by `vm_id` (preferring pipe-0-exclusive units). + 'warm: for tier in tiers { + if tier == 0 { + continue; } - } - if chosen.is_none() { for i in 0..n { let k = (base_cursor + i) % n; - if (allowed & (1u32 << k)) != 0 + if (tier & (1u32 << k)) != 0 + && !self.compute.scrub_full[k] + && self.compute.owner[k] + .as_ref() + .is_some_and(|prev| prev.id == id) + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break 'search; + } + } + for i in 0..n { + let k = (base_cursor + i) % n; + if (tier & (1u32 << k)) != 0 && self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { chosen = Some(k); - break; + break 'search; } } } - } - if chosen.is_none() { for i in 0..n { let k = (base_cursor + i) % n; - if (allowed & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { + if (tier & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { chosen = Some(k); - break; + break 'search; } } } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 8cdeb175dac37b..227ba811a0bdc4 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -68,7 +68,7 @@ def item(declaration, text=source): pub const TA_WAVE_PASSES: usize = 4; pub const TA_WAVE_PASSES_LIGHT: usize = 8; pub const TA_WAVE_REFILL_HEADROOM: usize = 2; - pub const COMPUTE_PIPES: usize = 2; + pub const COMPUTE_PIPES: usize = 8; pub const COALESCE_WINDOW_US: u32 = 18; } } @@ -129,7 +129,7 @@ def item(declaration, text=source): fw_stamp: [Cell32; 2], } struct Graph { - compute: [ComputeGraph; 2], + compute: [ComputeGraph; hw::sizes::COMPUTE_PIPES], render: RenderGraph, } @@ -157,7 +157,7 @@ def item(declaration, text=source): shared: Option>, flights: Vec, pending: Vec>, - target: [u32; 2], + target: [u32; hw::sizes::COMPUTE_PIPES], fs_target: u32, chan_wait: bool, slot_wait: bool, @@ -349,14 +349,9 @@ def item(declaration, text=source): session: Session, objects: Objects, graph: Graph { - compute: [ - ComputeGraph { - fw_stamp: Cell32::new(0), - }, - ComputeGraph { - fw_stamp: Cell32::new(0), - }, - ], + compute: core::array::from_fn(|_| ComputeGraph { + fw_stamp: Cell32::new(0), + }), render: RenderGraph { fw_stamp: [Cell32::new(0), Cell32::new(0)], }, @@ -365,7 +360,7 @@ def item(declaration, text=source): shared: None, flights: vec![], pending: vec![], - target: [0; 2], + target: [0; hw::sizes::COMPUTE_PIPES], fs_target: 0, chan_wait: false, slot_wait: false, @@ -894,7 +889,8 @@ def item(declaration, text=source): target: 0x100, fs_target: 0, }); - fw2.engine.target = [0x200, 0x100]; + fw2.engine.target[0] = 0x200; + fw2.engine.target[1] = 0x100; fw2.graph.compute[0].fw_stamp.set(0x100); fw2.graph.compute[1].fw_stamp.set(0x100); assert!(fw2.oldest_stamp_reached()); @@ -1282,7 +1278,12 @@ def item(declaration, text=source): const STATE_WRITE: usize = 0x40; const RING_SLOTS: u32 = 128; const RECORD_WORDS: usize = 18; - const STAGE_EVENTS: [u32; 4] = [0x70, 0x71, 15, 16]; + const COMPUTE_PIPES: usize = 8; + const STAGE_COUNT: usize = 2 + COMPUTE_PIPES; + mod compute { + pub const EVENT: u32 = 15; + } + const COMPUTE_EVENT_MASK: u32 = ((1u32 << COMPUTE_PIPES) - 1) << compute::EVENT; mod rings { pub const EVENT_RECORD: usize = 0x48; } @@ -1370,7 +1371,7 @@ def item(declaration, text=source): ta_events: u32, fs_events: u32, compute_events: u32, - event_ns: [u64; 4], + event_ns: [u64; STAGE_COUNT], errors: u32, channel_errors: u32, recovery_started_ns: Option, @@ -1404,8 +1405,9 @@ def item(declaration, text=source): #[test] fn event_drain_batches_state_read_and_minimizes_wc_reads() { let ring = Ring::new(); - // 4 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), - // Compute pipe 0 (15 -> word 1 bit 15), Compute pipe 1 (16 -> word 1 bit 16). + // 5 consecutive type-1 stage events: TA (0x70 -> word 4 bit 16), FS (0x71 -> word 4 bit 17), + // Compute pipe 0 (15 -> word 1 bit 15), Compute pipe 1 (16 -> word 1 bit 16), + // and Compute pipe 7 (22 -> word 1 bit 22, event_ns[9]). let mut r0 = [0u32; RECORD_WORDS]; r0[0] = 1; r0[4] = 1 << 16; @@ -1418,25 +1420,31 @@ def item(declaration, text=source): let mut r3 = [0u32; RECORD_WORDS]; r3[0] = 1; r3[1] = 1 << 16; + let mut r4 = [0u32; RECORD_WORDS]; + r4[0] = 1; + r4[1] = 1 << 22; ring.put_record(0, &r0); ring.put_record(1, &r1); ring.put_record(2, &r2); ring.put_record(3, &r3); - ring.set_indices(0, 4); + ring.put_record(4, &r4); + ring.set_indices(0, 5); let mut ev = Events::default(); ev.drain(&device::Device, &ring).unwrap(); assert_eq!(ev.event_ns[0], 12345); + assert_eq!(ev.event_ns[1], 12345); assert_eq!(ev.event_ns[2], 12345); assert_eq!(ev.event_ns[3], 12345); + assert_eq!(ev.event_ns[9], 12345); assert_eq!(ev.fs_events, 1); - assert_eq!(ev.compute_events, 2); - assert_eq!(ev.stage_events, 4); - assert_eq!(ring.read_idx(), 4); - // Exactly ONE STATE_READ write for all 4 records! + assert_eq!(ev.compute_events, 3); + assert_eq!(ev.stage_events, 5); + assert_eq!(ring.read_idx(), 5); + // Exactly ONE STATE_READ write for all 5 records! assert_eq!(ring.state.writes.get(), 1); - // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 12 reads (not 72)! - assert_eq!(ring.ring.reads.get(), 12); + // Exactly 3 WC reads per type-1 record (kind, word 1, word 4) = 15 reads (not 90)! + assert_eq!(ring.ring.reads.get(), 15); } #[test] diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index 8cc61598bf6171..19ebbe49508af7 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -9,7 +9,7 @@ def function(text,name): marker=text.index('fn '+name+'(');start=text.rfind('\n',0,marker)+1;at=text.index('{',marker);depth,end=1,at+1 while depth:depth+=(text[end]=='{')-(text[end]=='}');end+=1 return text[start:end] -option='progress: [Option; 4]' in engine +option='progress: [Option; sizes::COMPUTE_PIPES + 2]' in engine harness=r''' #![allow(dead_code)] use std::cell::Cell; @@ -18,7 +18,7 @@ def function(text,name): #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EIO:Error=Error(5);const ETIMEDOUT:Error=Error(110); type Result=core::result::Result; -mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=2;}} +mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=8;}} mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} mod params{ pub fn recovery()->bool{true} @@ -31,14 +31,14 @@ def function(text,name): macro_rules! dev_warn{($($tt:tt)*)=>{};} macro_rules! dev_err{($($tt:tt)*)=>{};} struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} -struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;2],render:Render} +struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:Render} struct Job{long:bool} impl Job{fn long(&self)->bool{self.long}} struct Flight{job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} -struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,progress_flight:[u64;3],progress:[__TYPE__;4]} +struct Engine{flights:Vec,target:[u32;hw::sizes::COMPUTE_PIPES],ta_target:u32,fs_target:u32,progress_flight:[u64;hw::sizes::COMPUTE_PIPES+1],progress:[__TYPE__;hw::sizes::COMPUTE_PIPES+2]} impl Engine{fn oldest(&self)->Option<&Flight>{self.flights.first()}} -struct Recovery{deadlines:logic::Deadlines,warning_deadline_ns:[u64;2],long_commands:u64,receipt_fault:bool,failed:Option} -struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,fail_stops:Vec} +struct Recovery{deadlines:logic::Deadlines,compute_deadlines:[logic::Deadlines;hw::sizes::COMPUTE_PIPES],warning_deadline_ns:[u64;2],compute_warning_deadline_ns:[u64;hw::sizes::COMPUTE_PIPES],long_commands:u64,receipt_fault:bool,failed:Option} +struct Firmware{graph:Graph,engine:Engine,recovery:Recovery,render_renewed:u32,compute_renewed:u32,pipe_renewed:[u32;hw::sizes::COMPUTE_PIPES],fail_stops:Vec} impl Firmware{ fn dev(&self){} fn transport_error(&self)->Option{None} @@ -53,25 +53,33 @@ def function(text,name): self.recovery.warning_deadline_ns[command::RENDER]=now.saturating_add(5_000_000_000); self.render_renewed+=1; } - fn renew_compute_deadline(&mut self){ + fn renew_compute_pipe_deadline(&mut self,pipe:usize){ + let pipe=pipe.min(hw::sizes::COMPUTE_PIPES-1); let now=now_ns(); let renewed=logic::Deadlines::renew(now,0,params::compute_deadline_ms()); - self.recovery.deadlines.compute=renewed.compute; - self.recovery.deadlines.long_compute=renewed.long_compute; - self.recovery.warning_deadline_ns[command::COMPUTE]=now.saturating_add(5_000_000_000); + self.recovery.compute_deadlines[pipe].compute=renewed.compute; + self.recovery.compute_deadlines[pipe].long_compute=renewed.long_compute; + self.recovery.compute_warning_deadline_ns[pipe]=now.saturating_add(5_000_000_000); + self.pipe_renewed[pipe]+=1; self.compute_renewed+=1; } + fn renew_compute_deadline(&mut self){ + for pipe in 0..hw::sizes::COMPUTE_PIPES{ + self.renew_compute_pipe_deadline(pipe); + } + } __PROGRESS__ __CHECK_HANGS__ } type Completions=(); fn firmware(render:bool,target:u32,previous:u32)->Firmware{ set_now_ns(1_000_000_000); - let mut f=Firmware{graph:Graph{compute:[Compute{fw_stamp:Object(Cell::new(previous))},Compute{fw_stamp:Object(Cell::new(previous))}],render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, - engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:[target,0],ta_target:target,fs_target:target,progress_flight:[0;3],progress:[__ZERO__;4]}, - recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,warning_deadline_ns:[u64::MAX;2],long_commands:0,receipt_fault:false,failed:None}, - render_renewed:0,compute_renewed:0,fail_stops:vec![]}; - f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f + let mut t=[0u32;hw::sizes::COMPUTE_PIPES];t[0]=target; + let mut f=Firmware{graph:Graph{compute:core::array::from_fn(|_|Compute{fw_stamp:Object(Cell::new(previous))}),render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, + engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:t,ta_target:target,fs_target:target,progress_flight:[0;hw::sizes::COMPUTE_PIPES+1],progress:[__ZERO__;hw::sizes::COMPUTE_PIPES+2]}, + recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,compute_deadlines:[logic::Deadlines::EXPIRED;hw::sizes::COMPUTE_PIPES],warning_deadline_ns:[u64::MAX;2],compute_warning_deadline_ns:[u64::MAX;hw::sizes::COMPUTE_PIPES],long_commands:0,receipt_fault:false,failed:None}, + render_renewed:0,compute_renewed:0,pipe_renewed:[0;hw::sizes::COMPUTE_PIPES],fail_stops:vec![]}; + f.renew_render_deadline();f.renew_compute_deadline();f.render_renewed=0;f.compute_renewed=0;f.pipe_renewed=[0;hw::sizes::COMPUTE_PIPES];f } #[test]fn pending_native_zero_and_reached_are_distinct_progress_states(){ let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.compute_renewed,0);f.progress();assert_eq!(f.compute_renewed,0); @@ -104,7 +112,7 @@ def function(text,name): #[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ let mut f=firmware(false,0x200,0x100); f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:1,renders:0,target:0x200,ta_target:0,fs_target:0,published_ns:2}); - f.engine.target=[0x200,0x200]; + f.engine.target[0]=0x200;f.engine.target[1]=0x200; f.progress();assert_eq!(f.compute_renewed,0); // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. f.graph.compute[1].fw_stamp.0.set(0x200); @@ -167,7 +175,56 @@ def function(text,name): } } } -'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress').replace('super::hw::','hw::')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') +#[test]fn stuck_compute_pipe_times_out_while_other_compute_pipe_advances_and_retires(){ + // Pipe 0 has a normal flight stuck at 0x100 (5s deadline); pipe 1 runs a long job that + // keeps advancing and retiring every 2s across 6s. Pipe 1 progress/retirement must never + // renew pipe 0's deadline or grant pipe 0 the 10s long-job allowance. + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:true},computes:1,compute_pipe:1,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[1]=0x300; + let mut done=(); + assert_eq!(f.check_hangs(&mut done),Ok(())); + for step in 1u64..=3 { + set_now_ns(1_000_000_000 + step * 2_000_000_000); + let next_target = 0x300 + (step as u32) * 0x100; + f.graph.compute[1].fw_stamp.0.set(next_target - 0x100); + f.engine.flights[1].target = next_target; + f.engine.flights[1].published_ns = 2 + step; + f.engine.target[1] = next_target; + f.renew_compute_pipe_deadline(1); + let res = f.check_hangs(&mut done); + if step < 3 { + assert_eq!(res, Ok(()), "pipe 0 deadline (5s) not yet expired at step {step}"); + assert_eq!(f.pipe_renewed[0], 0, "pipe 1 activity must never renew pipe 0 deadline"); + assert!(f.pipe_renewed[1] > 0); + } else { + assert_eq!(res, Err(ETIMEDOUT), "stuck pipe 0 must fail-stop at 6s despite active long pipe 1"); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + } + } +} +#[test]fn younger_long_job_on_same_compute_pipe_does_not_extend_stalled_normal_head(){ + // Pipe 0 has a normal flight at index 0 (5s deadline) and a younger long flight at index 1 + // on the same pipe (10s allowance). Only the oldest active flight on a pipe selects its + // deadline, so the stalled normal head still times out at 6s instead of inheriting 10s. + let mut f=firmware(false,0x200,0x100); + f.engine.flights.push(Flight{job:Job{long:true},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + f.engine.target[0]=0x300; + let mut done=(); + set_now_ns(1_000_000_000 + 6_000_000_000); + assert_eq!(f.check_hangs(&mut done), Err(ETIMEDOUT)); + assert_eq!(f.fail_stops, [ETIMEDOUT]); + // Conversely, when the oldest flight on pipe 0 IS a long job and a younger normal job is + // queued behind it on the same pipe, pipe 0 keeps its 10s long-job allowance at 6s. + let mut fl=firmware(false,0x200,0x100); + fl.engine.flights[0].job.long=true; + fl.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); + fl.engine.target[0]=0x300; + set_now_ns(1_000_000_000 + 6_000_000_000); + assert_eq!(fl.check_hangs(&mut done), Ok(())); + assert!(fl.fail_stops.is_empty()); +} +'''.replace('__LOGIC__',str(backend/'recovery/logic.rs')).replace('__PROGRESS__',function(source,'progress').replace('super::hw::','hw::')).replace('__CHECK_HANGS__',function(recovery_src,'check_hangs').replace('super::command::','command::').replace('super::hw::','hw::')).replace('__TYPE__','Option' if option else 'u32').replace('__ZERO__','None' if option else '0') unit=out/'progress-wrap.rs';unit.write_text(harness);log='' for command in [rustc()+['--edition=2021','--test',str(unit),'-o',str(out/'progress-wrap')],[str(out/'progress-wrap'),'--nocapture']]: result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True);log+=result.stdout;print(result.stdout,end='');(out/'progress-wrap.log').write_text(log) 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 73dbb31f2a6684..2e21f8ff29191d 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -103,7 +103,7 @@ def item(declaration): const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true }; #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} -struct Vm { status:Status, slot:u32 } +struct Vm { id:u64, status:Status, slot:u32 } struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64, compute_ewma_us:AtomicU32 } impl Queue { fn new(turn:u64, priority:u32)->Arc{ @@ -124,7 +124,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)}fn compute_slot_mask(&self)->Result{Ok(0b11)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(24)}fn compute_slot_mask(&self)->Result{Ok((1u32 << 24) - 1)}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -141,7 +141,7 @@ def item(declaration): struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,coalesce_deadline_ns:u64} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -187,7 +187,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=8; pub const MAX_VM_COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -232,6 +232,7 @@ def item(declaration): impl Firmware { fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} + fn compute_handoff_pipe(&self,_job:&Arc)->Option{None} __NEEDS_ENGINE_DRAIN__ __RENDER_CAN_PIPELINE__ __HOLD_CAUSE_FN__ @@ -301,7 +302,7 @@ def item(declaration): __PUBLISH__ __PUBLISH_CHECKED__ } -fn mk_vm(slot:u32)->Arc{Arc::new(Vm{status:Status(AtomicU32::new(0)),slot})} +fn mk_vm(slot:u32)->Arc{Arc::new(Vm{id:u64::from(slot),status:Status(AtomicU32::new(0)),slot})} fn job_on_vm_mode(id:u32,vm:Arc,render:bool,heavy:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, queue:Queue::new(0,0), @@ -316,7 +317,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},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,slot_wait:false,ta_wave_wait:false,held_wait:false,coalesce_deadline_ns:0}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_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,allow_behind:false,block_render_behind:false,block_compute_behind:false, @@ -589,7 +590,7 @@ def item(declaration): assert_eq!(fw.attempted,[11]); assert_eq!(fw.engine.stats.hold[0],0); - // Cross-VM compute drains behind another VM's active compute (no cross-VM C<->C overlap). + // Cross-VM non-SCS compute queues behind another VM's active compute on a disjoint pipe. let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); @@ -598,8 +599,8 @@ def item(declaration): fc.engine.flights.push(flc); fc.allow_behind=true; assert_eq!(fc.publish_checked(&mut done),Ok(())); - assert!(fc.attempted.is_empty()); - assert_eq!(fc.engine.stats.hold[0],1); + assert_eq!(fc.attempted,[13]); + assert_eq!(fc.engine.stats.hold[0],0); // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); @@ -844,10 +845,11 @@ def item(declaration): struct QueueBehindGraph{render:QueueBehindRenderGraph} impl QueueBehindGraph{fn new()->Self{Self{render:QueueBehindRenderGraph{fw_stamp:[QueueBehindStamp::new(0),QueueBehindStamp::new(0)]}}}} struct QueueBehindFlight{job:Arc,group:Vec>,first:usize,count:usize,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,heavy_render:bool,published_ns:u64,target:u32,cstamp:[u32;16],r_ta_stamp:[u32;16],r_fs_stamp:[u32;16],fs_target:u32,initbm:bool,has_timestamps:bool,doomed:bool,recovery_suspect:bool} -struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,flights:Vec} +struct QueueBehindEngine{ordinal:u64,draw:u64,ta_target:u32,next_compute_pipe:u8,pipe_last_vm:[Option;hw::sizes::COMPUTE_PIPES],pipe_last_used:[u64;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:u32,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 compute_exhausted_in_mask(&self,mask:u32)->bool{self.compute_exhausted||mask==0} fn render_exhausted(&self)->bool{self.render_exhausted} fn compute_available(&self,_n:usize)->bool{self.compute_available} fn compute_available_in_mask(&self,_mask:u32)->bool{self.compute_available} @@ -915,11 +917,13 @@ def item(declaration): __CROSS_ENGINE_WAIT__ __WAIT_COMPUTE_STAMPS_FOR__ __COMPUTE_QUEUE_IS_HEAVY__ + __COMPUTE_HANDOFF_PIPE__ + __HAS_COMPUTE_PIPE_FOR_VM__ __CHOOSE_COMPUTE_PIPE__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,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)}, @@ -933,14 +937,14 @@ def item(declaration): let j_render=mk(4,vm1.clone(),q1.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:j1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&j2)); - // Cross-VM compute drains behind another VM's compute as behind its render. - assert!(!p.can_queue_behind(&j_other_vm)); - assert!(p.needs_engine_drain(&j_other_vm)); + // Cross-VM non-SCS compute queues on a disjoint compute pipe without draining. + assert!(p.can_queue_behind(&j_other_vm)); + assert!(!p.needs_engine_drain(&j_other_vm)); assert!(p.can_queue_behind(&j_render)); p.engine.flights[0].doomed=true; assert!(!p.can_queue_behind(&j2)); @@ -964,8 +968,8 @@ def item(declaration): // gpubench compute.long: a ray-query lane (vm1) beside a long-ALU lane (vm2). The // ray-query dispatch was reported complete with its results unwritten whenever the // other lane's compute ran with it, and its stores then faulted in its closed VM. - 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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,rt:bool|Arc::new(QueueBehindJob{ @@ -982,7 +986,7 @@ def item(declaration): let rq_vm2=mk(5,vm2.clone(),q2.clone(),true); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![flight(rq.clone(),true,0)]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![flight(rq.clone(),true,0)]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -994,14 +998,14 @@ def item(declaration): assert!(!p.can_queue_behind(j)); assert!(p.needs_engine_drain(j)); } - // SCS compute does not start beside non-SCS compute on either pipe, and no compute - // starts beside another VM's compute. + // SCS compute does not start beside non-SCS compute on any pipe; non-SCS cross-VM + // compute runs concurrently on disjoint compute pipes without draining. for pipe in [0u8,1] { p.engine.flights=vec![flight(alu.clone(),false,pipe)]; assert!(!p.can_queue_behind(&rq)); assert!(p.needs_engine_drain(&rq)); - assert!(!p.can_queue_behind(&rq_post)); - assert!(p.needs_engine_drain(&rq_post)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); p.engine.flights=vec![flight(rq_post.clone(),false,pipe)]; assert!(!p.can_queue_behind(&rq)); assert!(p.needs_engine_drain(&rq)); @@ -1017,11 +1021,11 @@ def item(declaration): p.engine.flights=vec![flight(rq_post.clone(),false,0)]; assert!(p.can_queue_behind(&rq_post)); assert!(!p.needs_engine_drain(&rq_post)); - assert!(!p.can_queue_behind(&alu)); - assert!(p.needs_engine_drain(&alu)); + assert!(p.can_queue_behind(&alu)); + assert!(!p.needs_engine_drain(&alu)); } #[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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,wait_cdm:Option|Arc::new(QueueBehindJob{ @@ -1038,7 +1042,7 @@ def item(declaration): let other_queue=mk(2,q2.clone(),true,None,Some(1)); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:timed,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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,block_pipeline_vm:None}, }; @@ -1056,7 +1060,7 @@ def item(declaration): }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:timed_render,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -1065,8 +1069,8 @@ def item(declaration): assert!(pr.can_queue_behind(&mk(2,q1.clone(),true,None,None))); } #[test]fn render_queues_behind_same_vm_and_coexists_with_compute_while_blocking_initbm(){ - 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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1080,7 +1084,7 @@ def item(declaration): let c1=mk(4,vm1.clone(),false); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200,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,block_pipeline_vm:None}, }; @@ -1109,8 +1113,8 @@ def item(declaration): assert!(!p.can_queue_behind(&c1)); } #[test]fn cross_vm_render_compute_overlap_matrix(){ - 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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ @@ -1130,7 +1134,7 @@ def item(declaration): }; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![mk_flight(vm1_r.clone(),0,1)]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; @@ -1139,11 +1143,12 @@ def item(declaration): assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); - // Active VM1 Compute: same-VM R & C allowed; cross-VM C and R blocked + drain. + // Active VM1 Compute: same-VM R & C allowed; cross-VM non-SCS C allowed on a disjoint + // pipe; cross-VM R blocked + drains. p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); - assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; @@ -1151,7 +1156,7 @@ def item(declaration): assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); } #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ @@ -1168,7 +1173,7 @@ def item(declaration): let c_other_q=mk(5,q2.clone(),false,1,[None,None]); let p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ QueueBehindFlight{job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x500;a},fs_target:0x500,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, QueueBehindFlight{job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x700,cstamp:{let mut a=[0;16];a[0]=0x700;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false}, ]}, @@ -1205,7 +1210,7 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let pm=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + engine:QueueBehindEngine{ordinal:3,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ QueueBehindFlight{job:multi_c,group:vec![],first:0,count:3,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target: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}, @@ -1224,7 +1229,7 @@ def item(declaration): assert_eq!(cross_engine_barrier_type(true, true), BarrierType::Hold); // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,0); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1238,7 +1243,7 @@ def item(declaration): let r_after_r=mk(3,true,2,[Some(1),None]); let host=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:r_initbm,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0, cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x900;a},fs_target:0x900, initbm:true,has_timestamps:false,doomed:false,recovery_suspect:false, @@ -1265,7 +1270,7 @@ def item(declaration): assert_eq!(fw2.session.transports.load(Ordering::Relaxed),1); } #[test]fn multi_queue_concurrent_compute_and_render_on_same_vm(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q_comp=Queue::new(0,2); let q_rend=Queue::new(0,2); let c_job=Arc::new(QueueBehindJob{ @@ -1284,7 +1289,7 @@ def item(declaration): }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:1,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:c_job.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100,cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1303,7 +1308,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&c_job,0,command::RENDER),Ok(None)); } #[test]fn cross_engine_wait_and_compute_flight_cap_account_for_batched_horizon_members(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1322,7 +1327,7 @@ def item(declaration): cstamp[0]=0x100;cstamp[1]=0x200;cstamp[2]=0x300; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:3,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:c1,group:vec![c2,c3],first:0,count:1,computes:3,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x300,cstamp,r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1337,7 +1342,7 @@ def item(declaration): assert!(!p.can_queue_behind(&c4)); } #[test]fn multi_pass_render_flight_wait_stamp_and_render_cap(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); let multi=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), @@ -1362,7 +1367,7 @@ def item(declaration): r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:0,draw:3,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:multi.clone(),group:vec![],first:0,count:3,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:r_fs,fs_target:0x300, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, }]}, @@ -1415,7 +1420,7 @@ def item(declaration): assert!(!p.can_queue_behind(&next_r)); } #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); let mk=|id:u32,heavy:bool|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1433,7 +1438,7 @@ def item(declaration): } let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:0,draw:8,ta_target:0x800,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:r_live,group:vec![],first:0,count:8,computes:0,renders:3,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], r_ta_stamp:r_ta,r_fs_stamp:r_ta,fs_target:0x800, initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, @@ -1472,8 +1477,8 @@ def item(declaration): assert!(p.can_queue_behind(&next_heavy)); } #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ - 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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(), @@ -1489,7 +1494,7 @@ def item(declaration): let c_ts_wait=mk(5,vm1.clone(),false,Ok(()),true,[Some(1),None]); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![QueueBehindFlight{ + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![QueueBehindFlight{ job:r_live,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0,cstamp:[0;16], r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x100;a},fs_target:0x100, initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, @@ -1544,18 +1549,25 @@ def item(declaration): #[test]fn staged_render_barriers_split_ta_and_fs_compute_and_render_waits(){ const FRAG: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS; const STAGED: u32 = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; - const NO_C: [[Option; 2]; 2] = [[None; 2]; 2]; + const NO_C1: [Option; sizes::COMPUTE_PIPES] = [None; sizes::COMPUTE_PIPES]; + const NO_C: [[Option; sizes::COMPUTE_PIPES]; 2] = [NO_C1; 2]; + let c8 = |a: Option, b: Option| -> [Option; sizes::COMPUTE_PIPES] { + let mut arr = [None; sizes::COMPUTE_PIPES]; + arr[0] = a; + arr[1] = b; + arr + }; // 1. Cold InitBM / empty render pipe (`class_behind = false`): zero render barriers, // compute->FS-only wait routes directly to fs_compute_barrier. assert_eq!( - plan_render_barriers(STAGED, false, true, 0, None, None, [[None, None], [Some(0x700), None]], false), + plan_render_barriers(STAGED, false, true, 0, None, None, [NO_C1, c8(Some(0x700), None)], false), RenderBarrierPlan { early: false, ta_prev_wait: false, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [Some(0x700), None], + ta_compute_wait: NO_C1, + fs_compute_wait: c8(Some(0x700), None), } ); // 2. Independent multi-pass render (`fs_wait_render = None`, e.g. compress.bw array / @@ -1570,8 +1582,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); } @@ -1585,7 +1597,7 @@ def item(declaration): 0x200, Some(0x200), None, - [[Some(0x700), None], [Some(0x700), None]], + [c8(Some(0x700), None), c8(Some(0x700), None)], false, ), RenderBarrierPlan { @@ -1593,8 +1605,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: [Some(0x700), None], - fs_compute_wait: [None, None], + ta_compute_wait: c8(Some(0x700), None), + fs_compute_wait: NO_C1, } ); // 4. Different compute targets on TA (0x600) vs FS (0x700) with no FS render dep: @@ -1607,7 +1619,7 @@ def item(declaration): 0x200, None, None, - [[Some(0x600), None], [Some(0x700), None]], + [c8(Some(0x600), None), c8(Some(0x700), None)], false, ), RenderBarrierPlan { @@ -1615,8 +1627,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: [Some(0x600), None], - fs_compute_wait: [Some(0x700), None], + ta_compute_wait: c8(Some(0x600), None), + fs_compute_wait: c8(Some(0x700), None), } ); // 4b. Two-pipe compute waits deduplicate per pipe independently: pipe 0 shared by TA+FS @@ -1629,7 +1641,7 @@ def item(declaration): 0x200, None, None, - [[Some(0x600), None], [Some(0x600), Some(0x700)]], + [c8(Some(0x600), None), c8(Some(0x600), Some(0x700))], false, ), RenderBarrierPlan { @@ -1637,8 +1649,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: None, - ta_compute_wait: [Some(0x600), None], - fs_compute_wait: [None, Some(0x700)], + ta_compute_wait: c8(Some(0x600), None), + fs_compute_wait: c8(None, Some(0x700)), } ); // 5. Staged render whose TA waits on an older in-flight FS (0x100 != prev_fs 0x200) @@ -1659,8 +1671,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: Some(0x200), - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 6. Staged render where TA and FS wait on the same older in-flight FS (0x100): @@ -1682,8 +1694,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 7. Staged render whose TA explicitly waits on the newest in-flight FS (0x200 == prev_fs): @@ -1705,8 +1717,8 @@ def item(declaration): ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 8. Dependent FRAGMENT_BARRIERS render (e.g. render.postfx): TA runs early with @@ -1719,7 +1731,7 @@ def item(declaration): 0x200, Some(0x200), None, - [[Some(0x700), None], [Some(0x700), None]], + [c8(Some(0x700), None), c8(Some(0x700), None)], false, ), RenderBarrierPlan { @@ -1727,8 +1739,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: [Some(0x700), None], - fs_compute_wait: [None, None], + ta_compute_wait: c8(Some(0x700), None), + fs_compute_wait: NO_C1, } ); // 9. Legacy dependent render (flags = 0, fs_wait_render = Some(0x200)): @@ -1740,8 +1752,8 @@ def item(declaration): ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 10. Legacy dependent render waiting on an older FS (0x100 != prev_fs 0x200): @@ -1753,8 +1765,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 11. Conservative `early_tiling = false` serializes TA behind prev_fs even when @@ -1766,8 +1778,8 @@ def item(declaration): ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 12. Cross-VM warm render behind another VM's render (`cross_vm_prev = true`, no @@ -1781,8 +1793,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: None, fs_render_wait: Some(0x200), - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); } @@ -1796,8 +1808,8 @@ def item(declaration): ta_prev_wait: true, ta_fs_wait: Some(0x100), fs_render_wait: Some(0x200), - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); // 14. Cross-VM with `early_tiling = false`: TA already waits on prev_fs, so fs_dep @@ -1809,14 +1821,14 @@ def item(declaration): ta_prev_wait: false, ta_fs_wait: Some(0x200), fs_render_wait: None, - ta_compute_wait: [None, None], - fs_compute_wait: [None, None], + ta_compute_wait: NO_C1, + fs_compute_wait: NO_C1, } ); } #[test]fn two_pipe_concurrent_compute_dispatch_and_fw_timestamp_safety(){ - 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 vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); let q1=Queue::new(0,2); let q2=Queue::new(0,2); let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ @@ -1832,12 +1844,13 @@ def item(declaration): let q3=Queue::new(0,2); let mut host=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![]}, + engine:QueueBehindEngine{ordinal:0,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![]}, slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; - // Empty engine uses next_compute_pipe (0). - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); + // Empty engine starts on pipe 0. + let no_w = [None; sizes::COMPUTE_PIPES]; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); host.engine.flights.push(QueueBehindFlight{ job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, @@ -1860,41 +1873,98 @@ def item(declaration): q1.compute_ewma_us.store(0, Ordering::Relaxed); // Light single-queue barrier-free compute stays affine to its active pipe (pipe 0), // while heavy single-queue compute and a second independent queue balance onto idle pipe 1. - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); - // RT/SCS compute stays pinned to pipe 0 even for another queue or heavy compute. - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, true, true), 0); - // A 2-unit base-only or SCS VM (bits < PIPE1_COMPUTE_START) stays pinned to pipe 0. - assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b11, false, true), 0); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], 0b110, false, true), 0); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(1)); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Cross-VM compute leases its own disjoint pipe (never shares VM1's active pipe 0). + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Base-only VM2 (only units 0..2, cannot use secondary pipes) waits when pipe 0 is busy by VM1. + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); + assert!(!host.has_compute_pipe_for_vm(&vm2, 0b11, false)); + // RT/SCS compute on same VM stays pinned to pipe 0; other VM RT returns None while pipe 0 busy. + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, true, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, true, true), None); + // A 2-unit base-only or SCS same-VM stays pinned to pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b11, false, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b110, false, true), Some(0)); assert!(host.can_queue_behind(&c2)); - // Add second concurrent flight on pipe 1 from q2: both pipes active, - // q1 stays affine to pipe 0, q2 stays affine to pipe 1, and a third queue q3 - // tie-breaks by next_compute_pipe. + // Add second concurrent flight on pipe 1 from VM2 (q2): VM1 stays on pipe 0 (or expands to + // pipe 2 for heavy compute, capped at MAX_VM_COMPUTE_PIPES=2), VM2 stays on pipe 1. host.engine.flights.push(QueueBehindFlight{ job:c_vm2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:1,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, false), 0); - assert_eq!(host.choose_compute_pipe(&q2, [None, None], (1u32 << 24) - 1, false, false), 1); - host.engine.next_compute_pipe=1; - assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 1); - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 1); - host.engine.next_compute_pipe=0; - assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); - assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); - // No compute queues beside another VM's compute flight, on either pipe. - assert!(!host.can_queue_behind(&c_vm2)); - assert!(!host.can_queue_behind(&c2)); - // Same-VM compute still pipelines without draining. - host.engine.flights.pop(); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Heavy VM1 picks idle pipe 2 (never VM2's active pipe 1). + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); + assert_eq!(host.choose_compute_pipe(&q3, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(2)); + // Once VM1 has 2 active pipes (0 and 2), MAX_VM_COMPUTE_PIPES=2 keeps VM1 on {0, 2}. + host.engine.flights.push(QueueBehindFlight{ + job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:2,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + host.engine.next_compute_pipe = 2; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); + host.engine.next_compute_pipe = 0; + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(0)); + // Cross-VM non-SCS compute queues on disjoint pipes without draining. + assert!(host.can_queue_behind(&c_vm2)); assert!(host.can_queue_behind(&c2)); + // When all COMPUTE_PIPES are occupied by distinct VMs, a 9th VM has no free pipe. + host.engine.flights.clear(); + for p in 0..sizes::COMPUTE_PIPES { + let vp = mk_vm((p + 10) as u32); + let qp = Queue::new(0, 2); + let jp = mk((p + 10) as u32, vp, qp, 1); + host.engine.flights.push(QueueBehindFlight{ + job:jp,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:p as u8,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + } assert!(!host.can_queue_behind(&c_vm2)); + assert!(host.blocked_on_slot_headroom(&c_vm2)); + assert!(!host.needs_engine_drain(&c_vm2)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), None); + // Starvation handoff: when all 8 pipes are occupied by other VMs, compute_handoff_pipe + // picks one compatible pipe (0) to drain so the remaining 7 pipes keep dispatching while + // pipe 0 drains for the waiting 9th VM. + assert_eq!(host.compute_handoff_pipe(&c_vm2), Some(0)); + host.engine.handoff_avoid_pipes = 1u32 << 0; + let vm10 = host.engine.flights[0].job.vm.clone(); + let q10 = host.engine.flights[0].job.queue.clone(); + let vm11 = host.engine.flights[1].job.vm.clone(); + let q11 = host.engine.flights[1].job.queue.clone(); + // Pipe 0 incumbent stops refilling pipe 0 while pipe 1 incumbent keeps dispatching on pipe 1. + assert_eq!(host.choose_compute_pipe(&q10, &vm10, no_w, (1u32 << 24) - 1, false, false), None); + assert_eq!(host.choose_compute_pipe(&q11, &vm11, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // Base-only VM2 (only units 0..2, limited to pipe 0) waiting while extension VM1 refills + // pipe 0: avoiding pipe 0 moves VM1 onto pipe 1 while pipe 0 drains, then VM2 gets pipe 0! + host.engine.handoff_avoid_pipes = 0; + host.engine.flights.clear(); + host.engine.flights.push(QueueBehindFlight{ + job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:1_000_000,target:0x100, + cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, + has_timestamps:false,doomed:false,recovery_suspect:false, + }); + // Base-only mask 0b11 cannot use pipes 1..7, so VM2 has no pipe while VM1 holds pipe 0. + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); + host.engine.handoff_avoid_pipes = 1u32 << 0; + // Extension VM1 continues dispatching on secondary pipe 1 instead of refilling pipe 0. + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + // A base-only VM1 incumbent stops refilling pipe 0 so pipe 0 drains for handoff. + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, 0b11, false, false), None); + assert!(!host.has_compute_pipe_for_vm(&vm1, 0b11, false)); + // Once pipe 0 drains (VM1 moved to pipe 1), clearing handoff_avoid_pipes gives VM2 pipe 0. + host.engine.flights[0].compute_pipe = 1; + host.engine.handoff_avoid_pipes = 0; + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), Some(0)); } #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1909,7 +1979,7 @@ def item(declaration): let c4=mk(4,4,Some(2)); let mut host=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,flights:vec![ + engine:QueueBehindEngine{ordinal:2,draw:0,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ QueueBehindFlight{ job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, @@ -1924,18 +1994,22 @@ def item(declaration): slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; - // Barrier-free compute resolves [None, None]. - assert_eq!(host.wait_compute_stamps_for(&c3, None), Ok([None, None])); - // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None] and reuses pipe 0 (zero c2c barrier). + // Barrier-free compute resolves all None. + let mut exp1 = [None; sizes::COMPUTE_PIPES]; + exp1[0] = Some(WaitTarget{stamp:0x100,initbm:false}); + let mut exp2 = exp1; + exp2[1] = Some(WaitTarget{stamp:0x200,initbm:false}); + assert_eq!(host.wait_compute_stamps_for(&c3, None), Ok([None; sizes::COMPUTE_PIPES])); + // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None..] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); - assert_eq!(w1, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(&q1, w1, (1u32 << 24) - 1, false, true), 0); + assert_eq!(w1, exp1); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w1, (1u32 << 24) - 1, false, true), Some(0)); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); - assert_eq!(w2, [Some(WaitTarget{stamp:0x100,initbm:false}), Some(WaitTarget{stamp:0x200,initbm:false})]); - assert_eq!(host.choose_compute_pipe(&q1, w2, (1u32 << 24) - 1, false, false), 0); + assert_eq!(w2, exp2); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2, (1u32 << 24) - 1, false, false), Some(0)); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -1945,15 +2019,15 @@ def item(declaration): q1.compute_ooo.store(1u64 << 0, Ordering::Release); assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); - assert_eq!(w2_ooo, [Some(WaitTarget{stamp:0x100,initbm:false}), None]); - assert_eq!(host.choose_compute_pipe(&q1, w2_ooo, (1u32 << 24) - 1, false, true), 0); - // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns [None, None]. + assert_eq!(w2_ooo, exp1); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2_ooo, (1u32 << 24) - 1, false, true), Some(0)); + // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns all None. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); - assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None, None])); + assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None; sizes::COMPUTE_PIPES])); } #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ - let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); let q1=Queue::new(0,2); let q2=Queue::new(0,2); let c1=Arc::new(QueueBehindJob{ @@ -1988,7 +2062,7 @@ def item(declaration): }); let host=QueueBehindHost{ graph:QueueBehindGraph::new(), - engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![ QueueBehindFlight{ job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0,target:0x100, cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, @@ -2004,9 +2078,11 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). + let mut exp_cw = [None; sizes::COMPUTE_PIPES]; + exp_cw[0] = Some(WaitTarget{stamp:0x100,initbm:false}); let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); - assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); - assert_eq!(host.choose_compute_pipe(&q2,cw,(1u32<<24)-1,false,false),0); + assert_eq!(cw,exp_cw); + assert_eq!(host.choose_compute_pipe(&q2,&vm1,cw,(1u32<<24)-1,false,false),Some(0)); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2016,7 +2092,7 @@ def item(declaration): // Once q1 retires, fw_waits resolves to no barriers. q1.completed[command::COMPUTE].store(1,Ordering::Release); q1.completed[command::RENDER].store(1,Ordering::Release); - assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None,None])); + assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None;sizes::COMPUTE_PIPES])); assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(None)); } } @@ -2354,7 +2430,18 @@ def item(declaration): mod poll { pub fn stamp_reached(obs: u32, own: u32, _tail: u32) -> bool { obs >= own } } - mod work { pub mod ta { pub const TPC_BYTES: usize = 0; } } + mod work { + pub mod ta { pub const TPC_BYTES: usize = 0; } + pub mod compute { + pub const fn pipe_of_event(event: u32) -> Option { + if event >= 15 && event < 15 + super::super::sizes::COMPUTE_PIPES as u32 { + Some((event - 15) as usize) + } else { + None + } + } + } + } fn wmb() {} struct PassBuf { size: usize, @@ -2396,9 +2483,17 @@ def item(declaration): gate_passed_ns: Option, unsettled_polls: u32, } - struct RecEngine { flights: Vec, target: [u32; 2], ta_target: u32, fs_target: u32 } + struct RecEngine { flights: Vec, target: [u32; sizes::COMPUTE_PIPES], ta_target: u32, fs_target: u32 } struct RecState { last_retired: recovery::logic::RetiredStamps } struct RecFirmware { engine: RecEngine, recovery: RecState } + fn st(ta: u32, fs: u32, c0: u32, c1: u32) -> [u32; 2 + sizes::COMPUTE_PIPES] { + let mut s = [0u32; 2 + sizes::COMPUTE_PIPES]; + s[0] = ta; + s[1] = fs; + s[2] = c0; + s[3] = c1; + s + } impl RecFirmware { __RECOVERY_PREPARE__ __RECOVERY_PREPARE_SUSPECTS__ @@ -2409,6 +2504,8 @@ def item(declaration): cstamp[0] = 0x100; cstamp[1] = 0x200; cstamp[2] = 0x300; + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x300; let mut fw = RecFirmware { engine: RecEngine { flights: vec![RecFlight { @@ -2429,16 +2526,16 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], - target: [0x300, 0], + target, ta_target: 0, fs_target: 0, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; - assert_eq!(fw.recovery_prepare(1, 15, 0x200, [0, 0, 0x100, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15, 0x200, st(0, 0, 0x100, 0)), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(fw.engine.flights[0].recovery_suspect); - assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0x100, 0]), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, st(0, 0, 0x100, 0)), Err(ENOENT)); } #[test] fn recovery_prepare_matches_interior_render_stamps_and_cleans_only_unfinished_tpc() { @@ -2477,7 +2574,7 @@ def item(declaration): gate_passed_ns: None, unsettled_polls: 0, }], - target: [0, 0], + target: [0; sizes::COMPUTE_PIPES], ta_target: 0x300, fs_target: 0x300, }, @@ -2485,14 +2582,14 @@ def item(declaration): }; // Pass 0 TA finished (stage[0] == 0x100); interior TA target 0x200 matches and cleans // TPC only for unfinished passes 1 and 2. - assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, [0x100, 0, 0, 0]), Ok(())); + assert_eq!(fw.recovery_prepare(9, 0x70, 0x200, st(0x100, 0, 0, 0)), Ok(())); assert!(fw.engine.flights[0].doomed); assert_eq!(fw.engine.flights[0].job.resources.passes[0].tpc.cleared.get(), 0); assert_eq!(fw.engine.flights[0].job.resources.passes[1].tpc.cleared.get(), 0x2000); assert_eq!(fw.engine.flights[0].job.resources.passes[2].tpc.cleared.get(), 0x3000); // Interior FS target 0x200 also matches; unrelated target 0x400 returns ENOENT. - assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, [0x300, 0x100, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, [0x300, 0x100, 0, 0]), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x200, st(0x300, 0x100, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x400, st(0x300, 0x100, 0, 0)), Err(ENOENT)); } #[test] fn cross_vm_recovery_prepare_isolates_blame_to_faulting_vm() { @@ -2501,6 +2598,8 @@ def item(declaration): r_ta[0] = 0x100; r_fs[0] = 0x100; let mut cstamp = [0u32; 16]; cstamp[0] = 0x500; + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x500; let mut fw = RecFirmware { engine: RecEngine { flights: vec![ @@ -2541,15 +2640,15 @@ def item(declaration): unsettled_polls: 0, }, ], - target: [0x500, 0], + target, ta_target: 0x100, fs_target: 0x100, }, recovery: RecState { last_retired: recovery::logic::RetiredStamps::new() }, }; // VM 1 (ASID 1) faults on FS 0x100 while VM 2 (ASID 2) has co-resident compute 0x500. - assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x100, 0, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare_suspects([0x100, 0, 0, 0], 0x71, Some(1)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, st(0x100, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0x100, 0, 0, 0), 0x71, Some(1)), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(fw.engine.flights[0].recovery_suspect); // VM 2's co-resident compute is suspect-only (checked via hardware ITS ticks), NEVER doomed! @@ -2582,8 +2681,8 @@ def item(declaration): }; fw.engine.ta_target = 0x200; fw.engine.fs_target = 0x200; - assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, [0x200, 0, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare_suspects([0x200, 0, 0, 0], 0x71, Some(1)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 0x71, 0x100, st(0x200, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0x200, 0, 0, 0), 0x71, Some(1)), Ok(())); assert!(fw.engine.flights[0].doomed); assert!(!fw.engine.flights[1].doomed); assert!(fw.engine.flights[1].recovery_suspect); @@ -2598,6 +2697,10 @@ def item(declaration): let mut last_retired = recovery::logic::RetiredStamps::new(); last_retired.push(0, 0x300); last_retired.push(1, 0x400); + last_retired.push(sizes::COMPUTE_PIPES - 1, 0x700); + let mut target = [0u32; sizes::COMPUTE_PIPES]; + target[0] = 0x100; + target[1] = 0x100; let mut fw = RecFirmware { engine: RecEngine { flights: vec![ @@ -2638,14 +2741,14 @@ def item(declaration): unsettled_polls: 0, }, ], - target: [0x100, 0x100], + target, ta_target: 0, fs_target: 0, }, recovery: RecState { last_retired }, }; - assert_eq!(fw.recovery_prepare(1, 16, 0x100, [0, 0, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare_suspects([0, 0, 0, 0], 16, Some(2)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 16, 0x100, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0, 0, 0, 0), 16, Some(2)), Ok(())); assert!(!fw.engine.flights[0].doomed); assert!(fw.engine.flights[0].recovery_suspect); assert!(fw.engine.flights[1].doomed); @@ -2656,20 +2759,22 @@ def item(declaration): fw.engine.flights[0].recovery_suspect = false; fw.engine.flights[1].recovery_suspect = false; fw.engine.flights[1].doomed = false; - assert_eq!(fw.recovery_prepare_suspects([0, 0, 0x100, 0], 16, Some(2)), Ok(())); + assert_eq!(fw.recovery_prepare_suspects(st(0, 0, 0x100, 0), 16, Some(2)), Ok(())); assert!(!fw.engine.flights[0].recovery_suspect); assert!(fw.engine.flights[1].recovery_suspect); assert!(fw.engine.flights[1].doomed); - // last_retired_target distinguishes event 15 (slot 0) from event 16 (slot 1). - assert_eq!(fw.recovery_prepare(1, 15, 0x300, [0, 0, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare(1, 16, 0x400, [0, 0, 0, 0]), Ok(())); - assert_eq!(fw.recovery_prepare(1, 15, 0x400, [0, 0, 0, 0]), Err(ENOENT)); - assert_eq!(fw.recovery_prepare(1, 16, 0x300, [0, 0, 0, 0]), Err(ENOENT)); + // last_retired_target distinguishes event 15 (slot 0), event 16 (slot 1), and event 22 (slot 7). + assert_eq!(fw.recovery_prepare(1, 15, 0x300, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 16, 0x400, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15 + sizes::COMPUTE_PIPES as u32 - 1, 0x700, st(0, 0, 0, 0)), Ok(())); + assert_eq!(fw.recovery_prepare(1, 15, 0x400, st(0, 0, 0, 0)), Err(ENOENT)); + assert_eq!(fw.recovery_prepare(1, 16, 0x300, st(0, 0, 0, 0)), Err(ENOENT)); } } mod busy_coalesce_scope { use super::{Arc, AtomicBool, AtomicU32, Command, ComputeCommand, Order, Ordering, Progress, Queue, Recovery, RenderCommand, Result, Status, Vm}; + use crate::hw::sizes; mod params { pub fn compute_flights() -> usize { 23 } pub fn render_flights() -> usize { 47 } @@ -2748,7 +2853,7 @@ def item(declaration): } impl Host { fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } - fn choose_compute_pipe(&self, _q: &Arc, _w: [Option<()>; 2], _m: u32, _rt: bool, _heavy: bool) -> usize { 0 } + fn choose_compute_pipe(&self, _q: &Arc, _vm: &Arc, _w: [Option<()>; crate::hw::sizes::COMPUTE_PIPES], _m: u32, _rt: bool, _heavy: bool) -> Option { Some(0) } fn ta_pending_passes(&self) -> usize { self.ta_pending } __COMPUTE_QUEUE_IS_HEAVY__ __TA_WAVE_CAP_FOR__ @@ -2773,7 +2878,7 @@ def item(declaration): } #[test] fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { - let vm1 = Arc::new(Vm { status: Status(AtomicU32::new(0)), slot: 1 }); + let vm1 = Arc::new(Vm { id: 1, status: Status(AtomicU32::new(0)), slot: 1 }); let q1 = Queue::new(0, 2); let q2 = Queue::new(0, 2); let c1 = mk_job(&vm1, &q1, false, 1, [None, None]); @@ -2941,6 +3046,8 @@ def item(declaration): '__CROSS_ENGINE_WAIT__': 'fn cross_engine_wait(', '__WAIT_COMPUTE_STAMPS_FOR__': 'fn wait_compute_stamps_for(', '__COMPUTE_QUEUE_IS_HEAVY__': 'fn compute_queue_is_heavy(', + '__COMPUTE_HANDOFF_PIPE__': 'fn compute_handoff_pipe(', + '__HAS_COMPUTE_PIPE_FOR_VM__': 'fn has_compute_pipe_for_vm(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', '__WAIT_TARGET__': 'struct WaitTarget {', 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 827a3e885c8525..ad0bfd3a31f0c2 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 @@ -28,7 +28,7 @@ def function(text, name): #[path="__LOGIC__"]mod logic; use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } -mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 2; } } +mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 8; } } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} impl Object { @@ -43,13 +43,13 @@ def function(text, name): mod compute {pub const DESCRIPTOR_COMPLETED:usize=0;pub const DESCRIPTOR_COUNTER:usize=8;} #[derive(Default)]struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} struct RGraph{fw_stamp:[Object;2],qstate:[Object;2],qinfo:[Object;2],notifier:Object} -struct Graph{compute:[CGraph;2],render:RGraph} +struct Graph{compute:[CGraph;hw::sizes::COMPUTE_PIPES],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)}fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)}fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)}fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)}} struct Claims{slot:[u32;16],slot_count:u32,pass:[u32;4]} -struct Flight{computes:u32,renders:u32,compute_pipe:u8,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,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} -struct Engine{flights:Vec,target:[u32;2],ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} +struct Flight{computes:u32,renders:u32,compute_pipe:u8,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],chan_settled:bool,pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} +struct Engine{flights:Vec,target:[u32;hw::sizes::COMPUTE_PIPES],ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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} @@ -80,10 +80,11 @@ def function(text, name): } fn firmware(render:bool,ordinal:u64)->Firmware{ let target=encode::stamp(ordinal); + let mut target_arr=[0u32;hw::sizes::COMPUTE_PIPES];target_arr[0]=target; let mut f=Firmware{ - graph:Graph{compute:[CGraph::default(),CGraph::default()], + graph:Graph{compute:core::array::from_fn(|_|CGraph::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),compute_pipe:0,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;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:[target,0],ta_target:target,fs_target:target,retired_ticks:[0;4]}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),compute_pipe:0,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;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],chan_settled:false,pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:target_arr,ta_target:target,fs_target:target,retired_ticks:[0;4]}, 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,completed:2},channels:TopChannels{compute_producer:1},queue_passed:true,last_chan_passed:Cell::new(None), }; @@ -292,7 +293,7 @@ def function(text, name): fmix.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(41))); fmix.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(41))); fmix.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); - let (mut check_c,mut check_r)=([true;2],true); + let (mut check_c,mut check_r)=([true;hw::sizes::COMPUTE_PIPES],true); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); assert!(!check_c[0] && !check_c[1] && check_r); fmix.engine.flights.remove(1); @@ -428,7 +429,7 @@ def function(text, name): c1.compute_pipe=1; c1.rec[2]=2; f.engine.flights.push(c1); - f.engine.target=[encode::stamp(10),encode::stamp(11)]; + f.engine.target[0]=encode::stamp(10);f.engine.target[1]=encode::stamp(11); f.channels.compute_producer=2; f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(9))); f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(11))); @@ -468,7 +469,7 @@ def function(text, name): innocent.job.resources.compute[0].its.set(8,530); f.engine.flights.push(innocent); - f.engine.target=[encode::stamp(40),encode::stamp(41)]; + f.engine.target[0]=encode::stamp(40);f.engine.target[1]=encode::stamp(41); f.channels.compute_producer=2; f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(40))); f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(40))); @@ -536,8 +537,8 @@ def function(text, name): } fn producer(&self, ch: Channel) -> u32 { self.channel(ch).write } } - struct Engine { head: [u32; 2], ta_head: u32, fs_head: u32 } - struct Flight { compute_pipe: u8, c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3] } + struct Engine { head: [u32; hw::sizes::COMPUTE_PIPES], ta_head: u32, fs_head: u32, flights: Vec } + struct Flight { computes: u32, compute_pipe: u8, c_start: u32, head: u32, ta_start: u32, ta_head: u32, fs_start: u32, fs_head: u32, rec: [u32; 3], chan_settled: bool } struct Firmware { init: Init, channels: Channels, engine: Engine } mod inner { use super::*; @@ -545,6 +546,7 @@ def function(text, name): __QUEUE_RING_RECEIPT__ __QUEUE_RING_PASSED__ __CHANNEL_RECEIPT__ + __LATCH_COMPUTE_CHANNEL_RECEIPTS__ __QUEUE_RECEIPT__ __QUEUE_PASSED__ } @@ -559,7 +561,7 @@ def function(text, name): ta: Pipe { read: 7, completion: 7, write: 7 }, fs: Pipe { read: 9, completion: 9, write: 9 }, }, - engine: Engine { head: [10, 12], ta_head: 20, fs_head: 30 }, + engine: Engine { head: { let mut h = [0u32; hw::sizes::COMPUTE_PIPES]; h[0] = 10; h[1] = 12; h }, ta_head: 20, fs_head: 30, flights: vec![] }, }; let mut state = Object::default(); let mut info = Object::default(); @@ -594,7 +596,7 @@ def function(text, name): assert_eq!(fw.queue_ring_receipt(&state, &info, 12), Ok(true)); assert_eq!(fw.channel_receipt(Channel::Compute, 5, false), Ok(false)); assert_eq!(fw.channel_receipt(Channel::Compute, 5, true), Ok(true)); - let f_p1 = Flight { compute_pipe: 1, c_start: 10, head: 11, ta_start: 0, ta_head: 1, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; + let f_p1 = Flight { computes: 1, compute_pipe: 1, c_start: 10, head: 11, ta_start: 0, ta_head: 1, fs_start: 0, fs_head: 1, rec: [1, 1, 5], chan_settled: false }; assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(true)); state.set(qstate::READ, 10); assert_eq!(fw.queue_ring_passed(Channel::Compute, &state, &info, &f_p1), Ok(false)); @@ -603,7 +605,7 @@ def function(text, name): // queue_passed with queued work behind flight (including wrap-around) never reads qinfo. fw.engine.ta_head = 2; fw.channels.ta = Pipe { read: 2, completion: 2, write: 3 }; - let f = Flight { compute_pipe: 0, c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5] }; + let f = Flight { computes: 0, compute_pipe: 0, c_start: 0, head: 10, ta_start: 254, ta_head: 0, fs_start: 0, fs_head: 1, rec: [1, 1, 5], chan_settled: false }; state.set(qstate::READ, 1); assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(true)); assert_eq!(info.reads.get(), 0); @@ -616,11 +618,64 @@ def function(text, name): assert_eq!(fw.queue_passed(Channel::Ta, &state, &info, &f), Ok(false)); assert_eq!(info.reads.get(), 0); } + #[test] + fn cross_pipe_channel_wrap_latches_receipt_before_producer_laps_flight() { + // Pipe 0 submits compute record 1 while pipe 1 submits and retires 255 records, + // stopping at producer=0, read=0, completion=0. Raw ring_passed(0, 0, 1, 0, 256) + // would be false forever, but latch_compute_channel_receipts proves record 1 before + // the 256-entry submit channel wraps. + let mut fw = Firmware { + init: Init { abi: Abi }, + channels: Channels { + compute: Pipe { read: 1, completion: 1, write: 1 }, + ta: Pipe { read: 0, completion: 0, write: 0 }, + fs: Pipe { read: 0, completion: 0, write: 0 }, + }, + engine: Engine { + head: [0u32; hw::sizes::COMPUTE_PIPES], + ta_head: 0, + fs_head: 0, + flights: vec![Flight { + computes: 1, + compute_pipe: 0, + c_start: 0, + head: 1, + ta_start: 0, + ta_head: 0, + fs_start: 0, + fs_head: 0, + rec: [0, 0, 1], + chan_settled: false, + }], + }, + }; + // While firmware has not completed record 1 yet, latch stays false. + fw.channels.compute = Pipe { read: 1, completion: 0, write: 2 }; + fw.latch_compute_channel_receipts().unwrap(); + assert!(!fw.engine.flights[0].chan_settled); + // Out-of-range firmware cursors (>= RING_SLOTS, e.g. 257 which wraps mod 256 to 1) + // must be rejected before modular comparison in both passed receipts and latching. + for (read, completion) in [(257, 257), (257, 2), (2, 257)] { + fw.channels.compute = Pipe { read, completion, write: 2 }; + assert_eq!(fw.channel_receipt(Channel::Compute, 1, true), Ok(false)); + fw.latch_compute_channel_receipts().unwrap(); + assert!(!fw.engine.flights[0].chan_settled); + } + // Once read and completion pass record 1 before wrap, latch becomes true. + fw.channels.compute = Pipe { read: 2, completion: 2, write: 2 }; + fw.latch_compute_channel_receipts().unwrap(); + assert!(fw.engine.flights[0].chan_settled); + // Even after pipe 1 submits 254 more records and stops at producer=0 (where raw + // channel_receipt(Compute, 1, true) returns false), the latched proof persists. + fw.channels.compute = Pipe { read: 0, completion: 0, write: 0 }; + assert_eq!(fw.channel_receipt(Channel::Compute, 1, true), Ok(false)); + assert!(fw.engine.flights[0].chan_settled); + } } } '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__LATCH_COMPUTE_CHANNEL_RECEIPTS__','poll.rs','latch_compute_channel_receipts'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: body = function((backend/path).read_text(),name) if token in ('__RETIRED_FLIGHT__', '__RETIRED_FLIGHT_CLASSES__', '__RETIRED_SNAPSHOT_AT__'): body = body.replace('super::hw::', 'hw::') From f66997b7c50351953d138f4ba6abd785d18efe02 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 07:26:00 -0500 Subject: [PATCH 1360/1514] drm/asahi: g16: cache compute work records in FwCoherent UnitCmds Move each hardware compute unit's 8 KiB work image into device-lifetime Class::FwCoherent UnitCmds (ASC-cached with cacheable host view and uncached GPU kernel-task lower alias cleaned to PoC on write), matching PassCmds ta_work/fs_work and macOS 26B123 per-queue command objects. Explicitly invalidate the cacheable CPU work_ticks lines to PoC (FwObject::sync_for_cpu) before reading firmware/GPU-written 26B123 work_ticks, retain partial UnitCmds allocations in PersistentUnitCmds so first-use allocation failures never leak or duplicate persistent mappings on retry, and validate retained manager::INDEX against r.uma_slot in validate_compute_descriptor before displaced in-place reuse. Separate the per-VM compute UMA manager descriptor into an uncached Class::Fw view paired with the submission counter inside ComputeSlot's VM-free uma_lease (matching pools::Allocator), initialized once with COMPUTE_EXCLUSION = 1 and validated in place on cross-VM/displaced reuse instead of copying into the work image. Update ComputeRefs with an optional descriptor_fw address (zero preserves the embedded offset for legacy fixtures), update retirement receipts in poll.rs, and update the M4 host selftests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/encode.rs | 4 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 56 ++++- drivers/gpu/drm/asahi/g16/engine.rs | 15 +- drivers/gpu/drm/asahi/g16/fw/buffer.rs | 18 ++ drivers/gpu/drm/asahi/g16/graph.rs | 1 + drivers/gpu/drm/asahi/g16/object.rs | 194 +++++++++++------- drivers/gpu/drm/asahi/g16/poll.rs | 13 +- drivers/gpu/drm/asahi/g16/resources.rs | 68 ++++-- drivers/gpu/drm/asahi/g16/slots.rs | 151 ++++++++++---- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 27 ++- .../drivers/gpu/asahi-m4/check-compute.rs | 2 +- .../drivers/gpu/asahi-m4/test-publication.py | 4 +- .../drivers/gpu/asahi-m4/test-ray-tracing.py | 2 +- .../drivers/gpu/asahi-m4/test-resources.py | 169 +++++++++++++-- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 24 +-- .../drivers/gpu/asahi-m4/test-timestamps.py | 14 +- 16 files changed, 561 insertions(+), 201 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index 5c91c50db28847..216dad4384c4d1 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -73,8 +73,8 @@ 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, encode_compute_for, encode_compute_rt, init_compute_pool, - preserve_compute_descriptor, ComputeEncodeError, ComputeRefs, ComputeRt, - COMPUTE_SCS_DRIVER_WORD, + preserve_compute_descriptor, validate_compute_descriptor, ComputeEncodeError, ComputeRefs, + ComputeRt, COMPUTE_SCS_DRIVER_WORD, }; /// Tiling geometry and register words of a render (accelerator count 2). diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 78c972ac4c9df8..b172f3e428fae9 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -38,6 +38,8 @@ pub(crate) struct ComputeRefs { pub(crate) work: u64, pub(crate) work_gva: u64, pub(crate) seq: u64, + /// Zero selects the embedded `work + DESCRIPTOR`; otherwise a separate firmware UMA manager. + pub(crate) descriptor_fw: u64, pub(crate) preempt_gva: u64, pub(crate) its: u64, pub(crate) stats_fw: u64, @@ -164,17 +166,17 @@ pub(crate) fn init_compute_pool( Ok(()) } -/// Restores the complete allocator descriptor into a newly encoded, unpublished work after -/// the engine has proved A retired, distinct B displaced A in the same UMA slot, and B retired. -/// Numeric checks here do not establish that ownership proof. The old descriptor's completion -/// counter must equal A's cumulative submission count. Pool/list/counter backing stays pinned; -/// only the work pointer and destination slot are rewritten. Returns the next private counter. -pub(crate) fn preserve_compute_descriptor( +fn validate_compute_descriptor_inner( r: &ComputeRefs, old: &[u8; compute::DESCRIPTOR_SIZE], submitted_before: u64, - w: &mut [u8; compute::WORK_SIZE], + check_index: bool, ) -> Result { + fn read32(b: &[u8], off: usize) -> u32 { + let mut v = [0; 4]; + v.copy_from_slice(&b[off..off + 4]); + u32::from_le_bytes(v) + } fn read64(b: &[u8], off: usize) -> u64 { let mut v = [0; 8]; v.copy_from_slice(&b[off..off + 8]); @@ -185,6 +187,7 @@ pub(crate) fn preserve_compute_descriptor( || r.submitted != submitted_before + 1 || r.uma_slot == 0 || r.uma_slot > 32 + || (check_index && read32(old, manager::INDEX) != r.uma_slot) || read64(old, manager::WORK) != r.work || read64(old, manager::FREELIST) != r.pool_state_gva || read64(old, manager::POOL_TABLE) != r.page_list_gva @@ -193,10 +196,37 @@ pub(crate) fn preserve_compute_descriptor( { return Err(ComputeEncodeError::Descriptor); } + Ok(submitted_before + 1) +} + +/// Validates an in-place retained compute UMA manager descriptor before reuse after displacement. +/// Numeric checks here do not establish ownership proof; the engine proves prior retirement and +/// distinct displacement first. Returns the next private submission counter. +pub(crate) fn validate_compute_descriptor( + r: &ComputeRefs, + old: &[u8; compute::DESCRIPTOR_SIZE], + submitted_before: u64, +) -> Result { + validate_compute_descriptor_inner(r, old, submitted_before, true) +} + +/// Restores the complete allocator descriptor into a newly encoded, unpublished work after +/// the engine has proved A retired, distinct B displaced A in the same UMA slot, and B retired. +/// Numeric checks here do not establish that ownership proof. The old descriptor's completion +/// counter must equal A's cumulative submission count. Pool/list/counter backing stays pinned; +/// only the work pointer and destination slot are rewritten. Returns the next private counter. +#[allow(dead_code)] +pub(crate) fn preserve_compute_descriptor( + r: &ComputeRefs, + old: &[u8; compute::DESCRIPTOR_SIZE], + submitted_before: u64, + w: &mut [u8; compute::WORK_SIZE], +) -> Result { + let next = validate_compute_descriptor_inner(r, old, submitted_before, false)?; w[compute::DESCRIPTOR..compute::DESCRIPTOR + compute::DESCRIPTOR_SIZE].copy_from_slice(old); put64(w, compute::DESCRIPTOR + manager::WORK, r.work); put32(w, compute::DESCRIPTOR + manager::INDEX, r.uma_slot); - Ok(submitted_before + 1) + Ok(next) } fn timestamp( @@ -306,6 +336,7 @@ pub(crate) fn encode_compute_rt( } if !fw(r.work, compute::WORK_SIZE as u64) || !fw(r.seq, compute::SEQ_SIZE as u64) + || (r.descriptor_fw != 0 && !fw(r.descriptor_fw, compute::DESCRIPTOR_SIZE as u64)) || !fw(r.qinfo, 0x24c0) || !fw(r.stats_fw, 0xe10) || !fw(r.auxiliary_fw, compute::AUX_SIZE as u64) @@ -456,7 +487,12 @@ pub(crate) fn encode_compute_rt( put64(w, 0x83c, r.its + 8); put64(w, 0x844, ts_va[0]); put64(w, 0x84c, ts_va[1]); - put64(w, 0x86a, r.work + compute::DESCRIPTOR as u64); + let descriptor_fw = if r.descriptor_fw == 0 { + r.work + compute::DESCRIPTOR as u64 + } else { + r.descriptor_fw + }; + put64(w, 0x86a, descriptor_fw); put8(w, 0x872, 1); put64(w, 0x873, 0x1588000); put64(w, 0x87b, 0xef8000); @@ -489,7 +525,7 @@ pub(crate) fn encode_compute_rt( put16(q, off + 0xe, 1); } put32(q, 0x158, att.len() as u32); - put64(q, 0x160, r.work + compute::DESCRIPTOR as u64); + put64(q, 0x160, descriptor_fw); put64(q, 0x178, r.auxiliary_gva); put64(q, 0x188, r.context_store_gva); put64(q, 0x190, r.context_store_gva + 0xf400); diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 69b5c78fe75c1b..e070873138f67a 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -3635,6 +3635,8 @@ impl Firmware { work_gva: s.work.lower_gva.ok_or(EINVAL)?, // Separate device-lifetime firmware-cached microsequence record for this unit index. seq: s.seq.va, + // Separate per-VM uncached UMA manager descriptor inside `s.uma_lease`. + descriptor_fw: s.descriptor.va, preempt_gva: s.preempt.gva.ok_or(EINVAL)?, its: s.its.va, stats_fw: self.init.compute_activity.va, @@ -3685,10 +3687,10 @@ impl Firmware { if full_work { if before != 0 { // Slots::claim_compute proved a different fully retired unit displaced this - // descriptor in the same hardware slot. Keep every firmware-mutated byte. + // descriptor in the same hardware slot. Validate the retained descriptor in place. let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; - s.work.read(work::compute::DESCRIPTOR, &mut descriptor)?; - if encode::preserve_compute_descriptor(&refs, &descriptor, before, w).is_err() { + s.descriptor.read(0, &mut descriptor)?; + if encode::validate_compute_descriptor(&refs, &descriptor, before).is_err() { // This is retained allocator identity/completion corruption, not a client // refusal. Keep the unit and its previous VM lease mapped forever; cancelling // preparation would make the corrupt descriptor available to another job. @@ -3697,13 +3699,12 @@ impl Firmware { return Err(EIO); } } - s.work.write(0, w)?; + s.work.write(0, &w[..work::compute::BODY_ACTIVE_END])?; } else { - // Clean same-VM reuse: DESCRIPTOR (0xe00..0xea0) was already authenticated on + // Clean same-VM reuse: `s.descriptor` stays intact in place and was authenticated on // retirement for this exact unit and VM, static NOTIFIER (0xc00..0xd18) and tail // (0xee0..0xf08) remain intact in place, and the live microsequence lives in - // firmware-cached `s.seq`. Skip the 160-byte WC read-back and embedded sequence copy, - // writing only the active head and body before `SEQ_EMBEDDED`. + // firmware-cached `s.seq`. Write only the active head and body before `SEQ_EMBEDDED`. s.work.write(0, &w[..work::compute::HEAD_ACTIVE_SIZE])?; s.work.write( work::compute::BODY_ACTIVE_START, diff --git a/drivers/gpu/drm/asahi/g16/fw/buffer.rs b/drivers/gpu/drm/asahi/g16/fw/buffer.rs index e0a7b43b677bf3..ba9edef9127da5 100644 --- a/drivers/gpu/drm/asahi/g16/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/g16/fw/buffer.rs @@ -152,6 +152,24 @@ pub(crate) fn uma_manager_image( m } +/// One retained M4 compute UMA descriptor (`COMPUTE_UMA_SLOT + hw_slot`), identical to +/// [`uma_manager_image`] with `COMPUTE_EXCLUSION = 1` and `work_fw` at offset 0. +pub(crate) fn compute_uma_manager_image( + work_fw: u64, + slot: u32, + state_gpu: u64, + list_gpu: u64, + counter_fw: u64, + seeds: u32, + records: u32, +) -> [u8; uma_manager::SIZE] { + let mut m = uma_manager_image( + work_fw, slot, state_gpu, list_gpu, counter_fw, seeds, records, + ); + put32(&mut m, super::graph::manager::COMPUTE_EXCLUSION, 1); + m +} + #[cfg(test)] mod tests { use super::*; diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 8120f0adf5ba87..b3eaa19d7ee441 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -92,6 +92,7 @@ pub(crate) fn alloc( /// Work lists belong to the kernel GPU task. Firmware prepares them through the upper /// mapping and hardware reads the existing lower address; applications get no alias. /// Preserve the established cache classes and wire addresses while separating ownership. +#[allow(dead_code)] pub(crate) fn alloc_work( objects: &mut Objects, size: usize, diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 080d21522921b6..cda6f6617e279e 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -48,12 +48,15 @@ pub(crate) enum Class { SharedCached, /// ASC-cached (AttrIndex 0) behind a cacheable host mapping: the leaf macOS 26B123 gives its /// per-queue command objects and the G13-G15 private-allocator contract (`PROT_FW_PRIV_RW` - /// behind `gem::new_kernel_object`). Only for command records the host writes before - /// publication and never reads back what the firmware writes, with no client alias, and only - /// from device-lifetime allocators ([`Factory::persistent_objects`]): an ASC-cached M4 - /// mapping has no qualified teardown, so its owner is never dropped. A kernel GPU task lower - /// alias stays uncached, as macOS maps its work items for the GPU; host stores to such an - /// object are cleaned to the point of coherency for it ([`FwObject::write`]). + /// behind `gem::new_kernel_object`). Only for device-lifetime command records with no client + /// alias ([`Factory::persistent_objects`]): an ASC-cached M4 mapping has no qualified + /// teardown, so its owner is never dropped. A kernel GPU task lower alias stays uncached, as + /// macOS maps its work items for the GPU; host stores to such an object are cleaned to the + /// point of coherency for it ([`FwObject::write`]). Host readback of any firmware- or + /// GPU-written field inside a `FwCoherent` record (such as 26B123 compute `work_ticks`) must + /// call [`FwObject::sync_for_cpu`] first to clean+invalidate the CPU lines to PoC; because + /// prior host stores were already cleaned to PoC before publication and no host store occurs + /// while in flight, clean+invalidate never overwrites firmware/GPU writes. FwCoherent, /// Firmware device mapping. #[allow(dead_code)] @@ -113,6 +116,9 @@ pub(crate) struct FwObject { /// Host stores go through a cacheable view the GPU reads through its uncached lower alias: /// each store is cleaned to the point of coherency. clean: bool, + /// Host CPU mapping is write-back cacheable (`Class::FwCoherent`): any post-publication CPU + /// readback of firmware- or GPU-written words must call [`Self::sync_for_cpu`] first. + cached_cpu: bool, } // SAFETY: The object only refers to kernel memory shared with the firmware; every host access @@ -162,6 +168,7 @@ impl FwObject { _parent: Some(object.clone()), limit: Some(size), clean: object.clean, + cached_cpu: object.cached_cpu, }, GFP_KERNEL, )?) @@ -175,6 +182,18 @@ impl FwObject { } } + /// Invalidates CPU cache lines covering `len` bytes at `offset` when this object uses a + /// cacheable host mapping (`Class::FwCoherent`), ensuring subsequent CPU reads observe + /// firmware- or GPU-written words (e.g. 26B123 compute `work_ticks`) after publication. + pub(crate) fn sync_for_cpu(&self, offset: usize, len: usize) -> Result { + let p = self.ptr(offset, len)?; + if self.cached_cpu { + crate::pgtable::clean_invalidate_poc(p, len); + crate::pgtable::poc_barrier(); + } + Ok(()) + } + /// Copies bytes into the object before it is published, or into host-owned words. pub(crate) fn write(&self, offset: usize, bytes: &[u8]) -> Result { let p = self.ptr(offset, bytes.len())?; @@ -577,15 +596,35 @@ impl Objects { { return Err(EINVAL); } - let private = self.private.as_ref().ok_or(EINVAL)?; let bytes = req .offset .checked_add(req.size) .and_then(|size| size.checked_add(hw::PAGE as usize - 1)) .ok_or(EOVERFLOW)? & !(hw::PAGE as usize - 1); + { + let private = self.private.as_ref().ok_or(EINVAL)?; + if client_range.is_some() { + if private.vm.is_none() { + return Err(EINVAL); + } + } else if let Some((gva, leaf)) = req.client { + if private.vm.is_none() { + return Err(EINVAL); + } + let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; + if gva < hw::client::CLIENT_APERTURE.start + || end > hw::client::CLIENT_APERTURE.end + || gva & (hw::PAGE - 1) != 0 + || leaf != pte::LEAF_NC && leaf != pte::LEAF_PB_LIST + { + return Err(EINVAL); + } + } + } self.retained.reserve(1, GFP_KERNEL)?; self.mappings.reserve(3, GFP_KERNEL)?; + let object_slot = UniqueArc::::new_uninit(GFP_KERNEL)?; // A firmware-cached record needs a cacheable host view of the same pages (the host and // firmware caches are coherent, as for G13-G15 private objects); every other private // class keeps its write-combined view. @@ -606,6 +645,7 @@ impl Objects { gem::prepare_new_object(&backing.gem, parent.as_ref())?; } let clean = req.class == Class::FwCoherent && req.lower.is_some(); + let cached_cpu = req.class == Class::FwCoherent; let cpu = if req.cpu { let vmap = backing.vmap()?; let pointer = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; @@ -619,17 +659,7 @@ impl Objects { } else { None }; - let firmware = self.uat.kernel_vm().map_in_range( - &backing.gem, - 0..bytes, - hw::PAGE, - private.firmware.clone(), - mmu::Prot::from_pte(req.class.pte()), - true, - )?; - let va = firmware.iova(); - self.mappings.push(firmware, GFP_KERNEL)?; - let lower_gva = if req.lower.is_some() { + let lower_mapping = if req.lower.is_some() { // No two live VMs share a context-0 work address. The self-check at 0x70ff... // and all fixed client aliases are outside this aperture. let lower = self.uat.kernel_lower_vm().map_in_range( @@ -640,77 +670,90 @@ impl Objects { mmu::Prot::from_pte(pte::LOWER), true, )?; - let address = lower.iova() + req.offset as u64; - self.mappings.push(lower, GFP_KERNEL)?; uat::clean_lower(&self.uat)?; - Some(address) + Some(lower) } else { None }; - let client_gva = if let Some(range) = client_range { - let vm = private.vm.as_ref().ok_or(EINVAL)?; - let mapping = vm.map_in_range( - &backing.gem, - 0..bytes, - hw::PAGE, - range, - mmu::Prot::from_pte(pte::LEAF_NC), - true, - )?; - let address = mapping.iova(); - self.mappings.push(mapping, GFP_KERNEL)?; - Some(address) - } else if let Some((gva, leaf)) = req.client { - let vm = private.vm.as_ref().ok_or(EINVAL)?; - let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; - if gva < hw::client::CLIENT_APERTURE.start - || end > hw::client::CLIENT_APERTURE.end - || gva & (hw::PAGE - 1) != 0 - || leaf != pte::LEAF_NC && leaf != pte::LEAF_PB_LIST - { - return Err(EINVAL); + let (client_mapping, client_gva) = { + let private = self.private.as_ref().ok_or(EINVAL)?; + if let Some(range) = client_range { + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = vm.map_in_range( + &backing.gem, + 0..bytes, + hw::PAGE, + range, + mmu::Prot::from_pte(pte::LEAF_NC), + true, + )?; + let address = mapping.iova(); + (Some(mapping), Some(address)) + } else if let Some((gva, leaf)) = req.client { + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = + vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?; + (Some(mapping), Some(gva)) + } else { + (None, None) } - self.mappings.push( - vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, - GFP_KERNEL, - )?; - Some(gva) - } else { - None }; - wmb(); - let private = self.private.as_mut().ok_or(EINVAL)?; - let end = va + bytes as u64; - private.pending = Some(match private.pending.take() { - Some(range) => range.start.min(va)..range.end.max(end), - None => va..end, - }); - let object = Arc::new( - FwObject { - va: va + req.offset as u64, - gva: client_gva.map(|gva| gva + req.offset as u64), - lower_gva, - size: req.size, - offset: req.offset, - bytes, - client_leaf: req.client.map_or(pte::LEAF_NC, |(_, leaf)| leaf), - cpu, - backing, - _parent: None, - limit: None, - clean, - }, - GFP_KERNEL, + let fw_range = self.private.as_ref().ok_or(EINVAL)?.firmware.clone(); + // Map the firmware aperture last: for `Class::FwCoherent` an ASC-cached mapping cannot + // be torn down on drop, so every fallible allocation, validation, and uncached alias + // must succeed before it is created. + let firmware = self.uat.kernel_vm().map_in_range( + &backing.gem, + 0..bytes, + hw::PAGE, + fw_range, + mmu::Prot::from_pte(req.class.pte()), + true, )?; - self.retained.push(object.clone(), GFP_KERNEL)?; + let va = firmware.iova(); + let lower_gva = lower_mapping.as_ref().map(|m| m.iova() + req.offset as u64); + let _ = self.mappings.push_within_capacity(firmware); + if let Some(lower) = lower_mapping { + let _ = self.mappings.push_within_capacity(lower); + } + if let Some(client) = client_mapping { + let _ = self.mappings.push_within_capacity(client); + } + wmb(); + if let Some(private) = self.private.as_mut() { + let end = va + bytes as u64; + private.pending = Some(match private.pending.take() { + Some(range) => range.start.min(va)..range.end.max(end), + None => va..end, + }); + } + let object = Arc::from(object_slot.write(FwObject { + va: va + req.offset as u64, + gva: client_gva.map(|gva| gva + req.offset as u64), + lower_gva, + size: req.size, + offset: req.offset, + bytes, + client_leaf: req.client.map_or(pte::LEAF_NC, |(_, leaf)| leaf), + cpu, + backing, + _parent: None, + limit: None, + clean, + cached_cpu, + })); + let _ = self.retained.push_within_capacity(object.clone()); self.pages += bytes / hw::PAGE as usize; Ok(object) } /// Publish a completed private arena in one shared-L2 transaction. pub(crate) fn finish_private(&mut self) -> Result { - if let Some(range) = self.private.as_mut().ok_or(EINVAL)?.pending.take() { + if let Some(range) = self.private.as_ref().ok_or(EINVAL)?.pending.clone() { self.window.lock().sync_range(&self.uat, range)?; + if let Some(private) = self.private.as_mut() { + private.pending = None; + } } Ok(()) } @@ -855,6 +898,7 @@ impl Objects { _parent: None, limit: None, clean: false, + cached_cpu: false, }) .into(); self.retained.push(object.clone(), GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index cac1bca48a326f..c767737ed560ef 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -33,8 +33,7 @@ use kernel::{ use super::channel::Channel; use super::engine::{complete, now_ns, rmb, Flight, Lap}; -use super::fw::graph::{notifier, notifier_page, qstate}; -use super::fw::work::compute; +use super::fw::graph::{manager, notifier, notifier_page, qstate}; use super::job::{self, Completions, Job}; use super::recovery::logic::{Retirement, ABORT_GRACE_NS}; use super::regs::EngineState; @@ -988,7 +987,8 @@ impl Firmware { /// 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. Check /// `work_ticks` first when the ABI defines them so 26B123 skips two always-zero WC reads - /// per command, falling back to ITS if `work_ticks` holds no interval. + /// per command, invalidating the cacheable `FwCoherent` work lines to PoC before reading + /// (`sync_for_cpu`), and falling back to ITS if `work_ticks` holds no interval. fn compute_ticks(&self, unit: &super::slots::ComputeSlot) -> Result<(u64, u64)> { Self::compute_ticks_with(self.init.abi.compute().work_ticks, unit) } @@ -999,6 +999,9 @@ impl Firmware { ) -> Result<(u64, u64)> { if let Some((start_off, end_off)) = work_ticks { let w = &unit.work; + let lo = start_off.min(end_off); + let hi = start_off.max(end_off).checked_add(8).ok_or(EINVAL)?; + w.sync_for_cpu(lo, hi - lo)?; // 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 { @@ -1322,8 +1325,8 @@ impl Firmware { let submitted = f.csubmitted[m]; if submitted == 0 || unit.counter.r64(0)? != submitted - || unit.work.r64(compute::DESCRIPTOR_COMPLETED)? != submitted - || unit.work.r64(compute::DESCRIPTOR_COUNTER)? != unit.counter.va + || unit.descriptor.r64(manager::COMPLETED)? != submitted + || unit.descriptor.r64(manager::COUNTER)? != unit.counter.va { full = false; break; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 56e87b15b8dad4..6b80ddcbf0570f 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -7,7 +7,7 @@ use super::{ command::Command, - object::{Factory, Objects}, + object::{Factory, FwObject, Objects}, pools::{PbEpoch, PoolSet}, slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, @@ -77,16 +77,20 @@ impl RenderCmds { } /// One hardware compute unit's device-lifetime command records and the allocator that maps -/// them. The allocator is never dropped for the same reason as [`PersistentPassCmds`]. +/// them. The allocator is never dropped for the same reason as [`PersistentPassCmds`]; partial +/// allocations are retained in place so a retry finishes without leaking or duplicating pages. struct PersistentUnitCmds { objects: core::mem::ManuallyDrop, - cmds: Option, + work: Option>, + seq: Option>, + barrier: Option>, + finished: bool, } -/// The firmware-cached compute command records (microsequence and barrier records) of every -/// hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until reboot. A -/// hardware compute unit is device-global and claimed by one flight at a time, so every VM's -/// [`ComputeSlot`] bound to hardware unit `k` shares its records, and closing a VM drops no +/// The firmware-cached compute command records (work image, microsequence, and barrier records) +/// of every hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until +/// reboot. A hardware compute unit is device-global and claimed by one flight at a time, so every +/// VM's [`ComputeSlot`] bound to hardware unit `k` shares its records, and closing a VM drops no /// firmware-cached mapping. #[pin_data] pub(crate) struct ComputeCmds { @@ -111,21 +115,38 @@ impl ComputeCmds { pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result { let mut sets = self.sets.lock(); let entry = sets.get_mut(k).ok_or(EINVAL)?; - if let Some(cmds) = entry.as_ref().and_then(|set| set.cmds.as_ref()) { - return Ok(cmds.clone()); + if entry.is_none() { + let slot = KBox::::new_uninit(GFP_KERNEL)?; + *entry = Some(KBox::write( + slot, + PersistentUnitCmds { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + work: None, + seq: None, + barrier: None, + finished: false, + }, + )); } - let mut set = KBox::new( - PersistentUnitCmds { - objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), - cmds: None, - }, - GFP_KERNEL, + let set: &mut PersistentUnitCmds = &mut **entry.as_mut().ok_or(EINVAL)?; + if set.finished { + if let (Some(work), Some(seq), Some(barrier)) = (&set.work, &set.seq, &set.barrier) { + return Ok(UnitCmds { + work: work.clone(), + seq: seq.clone(), + barrier: barrier.clone(), + }); + } + } + let cmds = UnitCmds::init_into( + &mut set.objects, + k as u64, + &mut set.work, + &mut set.seq, + &mut set.barrier, )?; - // From here on a failure leaks the allocator with whatever it mapped. - let cmds = UnitCmds::new(&mut set.objects)?; set.objects.finish_private()?; - set.cmds = Some(cmds.clone()); - *entry = Some(set); + set.finished = true; Ok(cmds) } } @@ -183,7 +204,14 @@ impl ComputeArena { ) -> Result> { let cmds = factory.compute_cmds(hw_slot)?; let mut objects = factory.objects(vm); - let unit = ComputeSlot::new_in(&mut objects, factory, local as u64, placement, &cmds)?; + let unit = ComputeSlot::new_in( + &mut objects, + factory, + local as u64, + hw_slot as u32, + placement, + &cmds, + )?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index aa8f5ee3b6e4d3..f938866ba2eb9c 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -12,40 +12,75 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; use super::encode::{Geometry, PassRefs}; +use super::fw::buffer; use super::fw::work::{barrier, compute, fs, ta}; -use super::graph::{alloc, alloc_work, Client}; -use super::hw::{client, sizes}; +use super::graph::{alloc, Client}; +use super::hw::{client, engine, sizes}; use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; -/// The compute command records of one hardware compute unit index (microsequence and barrier -/// records), shared by every VM's [`ComputeSlot`] bound to that hardware unit: the unit index -/// is device-global and claimed by one flight at a time. The host writes them before -/// publication and never reads back what the firmware writes, so they take the firmware-cached -/// [`Class::FwCoherent`] view macOS 26B123 gives its per-queue command objects, with no client -/// or lower alias. +/// The compute command records of one hardware compute unit index (work image, microsequence, and +/// barrier records), shared by every VM's [`ComputeSlot`] bound to that hardware unit: the unit +/// index is device-global and claimed by one flight at a time. The host writes them before +/// publication and they take the firmware-cached [`Class::FwCoherent`] view macOS 26B123 gives its +/// per-queue command objects; the work image keeps its uncached kernel GPU task lower alias and +/// cleans host stores to PoC for the GPU, matching [`PassCmds`]. #[derive(Clone)] pub(crate) struct UnitCmds { + pub(crate) work: Arc, pub(crate) seq: Arc, pub(crate) barrier: Arc, } impl UnitCmds { - /// Allocates one compute unit index's command records from a device-lifetime allocator + /// Allocates hardware compute unit `k`'s command records from a device-lifetime allocator /// ([`Factory::persistent_objects`]), which the caller never drops. - pub(crate) fn new(o: &mut Objects) -> Result { + #[allow(dead_code)] + pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + let (mut work, mut seq, mut barrier) = (None, None, None); + Self::init_into(o, k, &mut work, &mut seq, &mut barrier) + } + + /// Populates any missing persistent command records for hardware compute unit `k` into the + /// caller-owned slots so partial failure retains already-mapped `FwCoherent` records instead + /// of leaking or re-allocating them on retry. + pub(crate) fn init_into( + o: &mut Objects, + k: u64, + work: &mut Option>, + seq: &mut Option>, + barrier: &mut Option>, + ) -> Result { let coherent = Class::FwCoherent; - Ok(Self { - seq: alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?, + if work.is_none() { + *work = Some(o.alloc(super::object::Request { + size: compute::WORK_SIZE, + class: coherent, + placement: super::object::Placement::Anywhere, + offset: 0, + client: None, + lower: Some(client::WORK_PAGE + k * client::CWORK_STRIDE), + cpu: true, + })?); + } + if seq.is_none() { + *seq = Some(alloc(o, compute::SEQ_SIZE, coherent, None, 0, false)?); + } + if barrier.is_none() { // Holds fs2c (+0x00) and per-pipe c2c (+(1 + pipe) * barrier::SIZE) barriers in 1 page. - barrier: alloc( + *barrier = Some(alloc( o, barrier::SIZE * (1 + sizes::COMPUTE_PIPES), coherent, None, 0, false, - )?, + )?); + } + Ok(Self { + work: work.as_ref().ok_or(EINVAL)?.clone(), + seq: seq.as_ref().ok_or(EINVAL)?.clone(), + barrier: barrier.as_ref().ok_or(EINVAL)?.clone(), }) } } @@ -60,6 +95,7 @@ pub(crate) struct ComputeSlot { pub(crate) seq: Arc, #[allow(dead_code)] pub(crate) barrier: Arc, + pub(crate) descriptor: Arc, pub(crate) pool: Arc, pub(crate) pool_state: Arc, pub(crate) page_list: Arc, @@ -68,9 +104,8 @@ pub(crate) struct ComputeSlot { pub(crate) aux: Arc, /// Freelist entries of the unit's UMA pool, seeded once ([`init_uma_pool`]). pub(crate) seeds: u32, - /// VM-free firmware lease keeping `work` (containing the compute UMA manager at `+0xe00`) - /// and `counter` mapped in context-0 UAT until a later compute retirement overwrites - /// firmware `uma_mgr_table[1 + k]`. + /// VM-free firmware lease keeping this unit's `descriptor` and `counter` mapped in context-0 + /// UAT until a later compute retirement overwrites firmware `uma_mgr_table[1 + k]`. uma_lease: Arc, } @@ -107,13 +142,6 @@ impl Placement { Placement::Scs { .. } => self.pool(k) + self.pool_bytes() as u64, } } - fn work(self, k: u64) -> u64 { - let index = match self { - Placement::Base => k, - Placement::Scs { .. } => sizes::COMPUTE_UNITS as u64 + k, - }; - client::WORK_PAGE + index * client::CWORK_STRIDE - } /// Freelist entries of the unit's pool. pub(crate) fn seeds(self) -> u32 { match self { @@ -189,24 +217,29 @@ impl ComputeSlot { k: u64, cmds: &UnitCmds, ) -> Result { - Self::new_in(o, fw_factory, k, Placement::Base, cmds) + Self::new_in(o, fw_factory, k, k as u32, Placement::Base, cmds) } - /// Unit `k` at `placement`, around the device-lifetime command records `cmds` of its - /// hardware ledger slot. + /// Unit `k` at `placement` bound to hardware ledger slot `hw_slot`, around the device-lifetime + /// command records `cmds` of `hw_slot`. pub(crate) fn new_in( o: &mut Objects, fw_factory: &Factory, k: u64, + hw_slot: u32, placement: Placement, cmds: &UnitCmds, ) -> Result { placement.check()?; let sh = Class::Shared; let state = placement.state(k); + // Keep the per-VM UMA manager descriptor and submission counter in one VM-free Class::Fw + // page inside `uma_lease` (matching `pools::Allocator`) while `work`, `seq`, and `barrier` + // live in device-lifetime `Class::FwCoherent` `UnitCmds`. let mut fw = fw_factory.fw_objects(); - let work = alloc_work(&mut fw, 0x2000, placement.work(k), 0)?; - let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; + let uma_page = alloc(&mut fw, 0x200, Class::Fw, None, 0, false)?; + let descriptor = FwObject::view(&uma_page, 0, compute::DESCRIPTOR_SIZE)?; + let counter = FwObject::view(&uma_page, 0x100, 0x80)?; let uma_lease = FwLease::new(fw)?; let unit = Self { its: alloc(o, 16, sh, None, 0, false)?, @@ -218,9 +251,10 @@ impl ComputeSlot { 0, false, )?, - work, + work: cmds.work.clone(), seq: cmds.seq.clone(), barrier: cmds.barrier.clone(), + descriptor, pool: o.alloc(super::object::Request { size: placement.pool_bytes(), class: sh, @@ -272,10 +306,23 @@ impl ComputeSlot { unit.pool.gva.ok_or(EINVAL)?, unit.seeds, )?; + unit.descriptor.write( + 0, + &buffer::compute_uma_manager_image( + unit.work.va, + engine::COMPUTE_UMA_SLOT + hw_slot, + unit.pool_state.gva.ok_or(EINVAL)?, + unit.page_list.gva.ok_or(EINVAL)?, + unit.counter.va, + unit.seeds, + super::rt::freelist_records(unit.seeds), + ), + )?; Ok(unit) } - /// VM-free firmware lease keeping this unit's `work` and `counter` mapped in context-0 UAT. + /// VM-free firmware lease keeping this unit's `descriptor` and `counter` mapped in context-0 + /// UAT. pub(crate) fn uma_lease(&self) -> Arc { self.uma_lease.clone() } @@ -1420,27 +1467,43 @@ impl Slots { && self.compute.lifetime.claim(k) { chosen = Some(k); - break 'search; + break 'warm; + } + } + } + // 2. Claim an unowned unit before stealing another VM's warm unit. + if chosen.is_none() { + 'unowned: for tier in tiers { + if tier == 0 { + continue; + } + for i in 0..n { + let k = (base_cursor + i) % n; + if (tier & (1u32 << k)) != 0 + && self.compute.owner[k].is_none() + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break 'unowned; + } } } + } + } + // 3. Fall back to round-robin over any available unit (preferring pipe-0-exclusive). + if chosen.is_none() { + 'any: for tier in tiers { + if tier == 0 { + continue; + } for i in 0..n { let k = (base_cursor + i) % n; - if (tier & (1u32 << k)) != 0 - && self.compute.owner[k].is_none() - && self.compute.lifetime.claim(k) - { + if (tier & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { chosen = Some(k); - break 'search; + break 'any; } } } - for i in 0..n { - let k = (base_cursor + i) % n; - if (tier & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { - chosen = Some(k); - break 'search; - } - } } let Some(k) = chosen else { return Ok(None); 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 a9bdf0a390089d..5156d78eb60cfc 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 @@ -244,7 +244,7 @@ fn compute_work(out: &std::path::Path) { 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, + descriptor_fw: 0, 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, @@ -277,6 +277,31 @@ fn compute_work(out: &std::path::Path) { 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[..]); + // Separate uncached descriptor_fw: work+0x86a and seq+0x160 point to descriptor_fw, + // compute_uma_manager_image matches the embedded descriptor layout, and displaced-reuse + // validation checks manager::INDEX against r.uma_slot. + let r_sep = encode::ComputeRefs { descriptor_fw: f + 0x580000, ..r }; + let (mut w_sep, mut q_sep) = ([0xa5; compute::WORK_SIZE], [0xa5; compute::SEQ_SIZE]); + encode::encode_compute_for( + &compute::V26B123, &r_sep, &c, &att, &ts, 1, 1, 1, &mut w_sep, &mut q_sep, + ).unwrap(); + assert_eq!(r64(&w_sep, 0x86a), r_sep.descriptor_fw, "work descriptor pointer at +0x86a"); + assert_eq!(r64(&q_sep, 0x160), r_sep.descriptor_fw, "seq descriptor pointer at +0x160"); + let mut desc = fw::buffer::compute_uma_manager_image( + r_sep.work, r_sep.uma_slot, r_sep.pool_state_gva, r_sep.page_list_gva, + r_sep.counter_fw, 8192, fw::graph::manager::UNK_1C_VALUE, + ); + assert_eq!(&desc[..], &w[compute::DESCRIPTOR..compute::DESCRIPTOR + compute::DESCRIPTOR_SIZE]); + desc[fw::graph::manager::COMPLETED..fw::graph::manager::COMPLETED + 8] + .copy_from_slice(&(r_sep.submitted - 1).to_le_bytes()); + assert_eq!( + encode::validate_compute_descriptor(&r_sep, &desc, r_sep.submitted - 1), + Ok(r_sep.submitted), + ); + let mut bad_idx = desc; + bad_idx[fw::graph::manager::INDEX..fw::graph::manager::INDEX + 4] + .copy_from_slice(&(r_sep.uma_slot + 1).to_le_bytes()); + assert!(encode::validate_compute_descriptor(&r_sep, &bad_idx, r_sep.submitted - 1).is_err()); 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(); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs index e0099ee4862e6c..4ae5a991b17a49 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-compute.rs @@ -30,7 +30,7 @@ fn refs(variant:u64)->encode::ComputeRefs { let g=0x1000000000+variant*0x100000000; 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, + work:f+0x100000,work_gva:g+0x100000,seq:f+0x100900,descriptor_fw:0,preempt_gva:g+0x200000, its:if variant&2!=0{f+0x500040}else{f+0x1008c0},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, 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 2e21f8ff29191d..209ded86b57948 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -185,7 +185,7 @@ def item(declaration): pub struct ComputeRefs{pub invalid:bool} // Fault injection replaces the descriptor reader, while the actual production // containment branch below decides whether the unit becomes claimable again. - pub fn preserve_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64,_work:&mut[u8;8192])->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} + pub fn validate_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64)->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=8; pub const MAX_VM_COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} @@ -3032,7 +3032,7 @@ def item(declaration): '__HOLD_CAUSE_FN__': 'fn hold_cause(', '__NOTE_HOLD__': 'fn note_hold(', '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', - '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', + '__DESCRIPTOR_CONTAINMENT__': 'if encode::validate_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(', '__TA_PENDING_PASSES__': 'pub(crate) fn ta_pending_passes(', '__TA_WAVE_CAP_FOR__': 'fn ta_wave_cap_for(', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py index bfc62d7c4c9ef5..59712e02f8ab3a 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-ray-tracing.py @@ -191,7 +191,7 @@ def block(text, declaration): let f = 0xfffffc2000000000u64; let g = 0x1000000000u64; 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, + work: f + 0x100000, work_gva: g + 0x100000, seq: f + 0x100900, descriptor_fw: 0, preempt_gva: g + 0x200000, its: f + 0x1008c0, 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: 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 27cc9aab32d726..cb84603adc5560 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -41,13 +41,27 @@ def module(text, name): #[derive(Copy,Clone,Debug,Eq,PartialEq)] pub struct Error(i32); pub const EINVAL:Error=Error(22); pub const EAGAIN:Error=Error(11); pub const E2BIG:Error=Error(7); pub const EBUSY:Error=Error(16); pub const EOVERFLOW:Error=Error(75); pub const EIO:Error=Error(5); +pub const ENOMEM:Error=Error(12); pub const ETIMEDOUT:Error=Error(110);pub const ERESTARTSYS:Error=Error(512); pub const GFP_KERNEL:u32=0; pub type Result = std::result::Result; macro_rules! init { ($($tt:tt)*) => { $($tt)* }; } -pub mod prelude {pub use crate::{Result,KVec,KBox,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,ENOMEM,ETIMEDOUT,ERESTARTSYS};} +std::thread_local!{pub static FAIL_KBOX_UNINIT:std::cell::Cell=const{std::cell::Cell::new(false)};} pub struct KBox(Box); -implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} pub fn init(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} +implKBox{ + pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} + pub fn init(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} + pub fn new_uninit(_:u32)->Result>>{ + if FAIL_KBOX_UNINIT.with(|f|f.replace(false)){return Err(ENOMEM);} + Ok(KBox(Box::new(core::mem::MaybeUninit::uninit()))) + } + pub fn write(mut b:KBox>,x:T)->Self{ + b.0.write(x); + // SAFETY: `write` just initialized `b.0`. + Self(unsafe{Box::from_raw(Box::into_raw(b.0).cast::())}) + } +} 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); @@ -123,7 +137,32 @@ def module(text, name): } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} - pub struct Objects{pub objects:Vec>,pub persistent:bool} + pub struct Window { + pub fail_once: std::sync::atomic::AtomicBool, + pub calls: std::sync::atomic::AtomicUsize, + pub ranges: std::sync::Mutex>>, + } + impl Window { + pub fn new() -> Self { + Self { + fail_once: std::sync::atomic::AtomicBool::new(false), + calls: std::sync::atomic::AtomicUsize::new(0), + ranges: std::sync::Mutex::new(Vec::new()), + } + } + pub fn sync_range(&self, _uat: &(), range: core::ops::Range) -> Result { + self.calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.ranges.lock().unwrap().push(range); + if self.fail_once.swap(false, std::sync::atomic::Ordering::AcqRel) { + return Err(EIO); + } + Ok(()) + } + } + pub struct Private { + pub pending: Option>, + } + pub struct Objects{pub objects:Vec>,pub persistent:bool,pub uat:(),pub window:Arc>,pub private:Option} // Device-lifetime render and compute command records, per test thread (the production // tables are resources::RenderCmds and resources::ComputeCmds): one never-dropped // allocator owns them. @@ -139,15 +178,16 @@ def module(text, name): } pub fn test_unit_cmds(k:u64)->crate::g16::slots::UnitCmds{ if let Some(c)=UNIT_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} - let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::UnitCmds::new(p.get_or_insert_with(Objects::persistent)).unwrap()}); + let c=PERSISTENT.with(|p|{let mut p=p.borrow_mut();crate::g16::slots::UnitCmds::new(p.get_or_insert_with(Objects::persistent),k).unwrap()}); UNIT_CMDS.with(|p|p.borrow_mut().push((k,c.clone())));c } impl Objects{ - pub fn new()->Self{Self{objects:vec![],persistent:false}} - pub fn persistent()->Self{Self{objects:vec![],persistent:true}} - pub fn finish_private(&mut self)->Result{Ok(())} + pub fn new()->Self{Self::with_window(false,Arc::new(crate::sync::Mutex::new(Window::new()),0).unwrap())} + pub fn persistent()->Self{Self::with_window(true,Arc::new(crate::sync::Mutex::new(Window::new()),0).unwrap())} + pub fn with_window(persistent:bool,window:Arc>)->Self{Self{objects:vec![],persistent,uat:(),window,private:Some(Private{pending:None})}} + __FINISH_PRIVATE__ pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{if r.class==Class::FwCoherent&&(!self.persistent||r.client.is_some()){return Err(EINVAL);}let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;if let Some(p)=self.private.as_mut(){let end=va+bytes as u64;p.pending=Some(match p.pending.take(){Some(range)=>range.start.min(va)..range.end.max(end),None=>va..end});}self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -636,29 +676,33 @@ def module(text, name): let mut vm_b = Objects::new(); let f = g16::object::Factory; // Per-VM non-persistent allocator refuses UnitCmds (Class::FwCoherent). - assert!(matches!(UnitCmds::new(&mut vm_a), Err(EINVAL))); + assert!(matches!(UnitCmds::new(&mut vm_a, 3), Err(EINVAL))); // Normal VM unit 3 and an SCS VM local unit 0 bound to hardware slot 3 share slot 3's - // device-lifetime seq + barrier records; neither VM arena owns any FwCoherent object. + // device-lifetime work + seq + barrier records; neither VM arena owns any FwCoherent object. let ca = ComputeSlot::new(&mut vm_a, &f, 3, &g16::object::test_unit_cmds(3)).unwrap(); let cb = ComputeSlot::new_in( &mut vm_b, &f, 0, + 3, SlotPlacement::Scs { seeds: 8192 }, &g16::object::test_unit_cmds(3), ) .unwrap(); - let ra = [ca.seq.clone(), ca.barrier.clone()]; - let rb = [cb.seq.clone(), cb.barrier.clone()]; - for (x, y) in ra.iter().zip(rb.iter()) { + let ra = [ca.work.clone(), ca.seq.clone(), ca.barrier.clone()]; + let rb = [cb.work.clone(), cb.seq.clone(), cb.barrier.clone()]; + for (idx, (x, y)) in ra.iter().zip(rb.iter()).enumerate() { assert!(crate::sync::Arc::ptr_eq(x, y)); assert_eq!(x.class, Class::FwCoherent); - assert_eq!((x.gva, x.client_leaf, x.lower_gva), (None, None, None)); + assert_eq!((x.gva, x.client_leaf), (None, None)); + assert_eq!(x.lower_gva.is_some(), idx == 0); assert_eq!(x.va & 0x3fff, 0); } + assert_ne!(ca.work.va, ca.seq.va); assert_ne!(ca.seq.va, ca.barrier.va); - assert_eq!(ca.work.class, Class::Shared); - assert!(ca.work.lower_gva.is_some()); + assert_eq!(ca.descriptor.class, Class::Fw); + assert_eq!(cb.descriptor.class, Class::Fw); + assert_ne!(ca.descriptor.va, cb.descriptor.va); assert!(vm_a.objects.iter().chain(vm_b.objects.iter()).all(|o| o.class != Class::FwCoherent)); assert!(vm_a .objects @@ -667,19 +711,22 @@ def module(text, name): .all(|o| ra.iter().all(|r| !crate::sync::Arc::ptr_eq(o, r)))); // Distinct hardware slot gets distinct UnitCmds. let cc = ComputeSlot::new(&mut vm_b, &f, 4, &g16::object::test_unit_cmds(4)).unwrap(); + assert!(!crate::sync::Arc::ptr_eq(&cc.work, &ca.work)); assert!(!crate::sync::Arc::ptr_eq(&cc.seq, &ca.seq)); assert!(!crate::sync::Arc::ptr_eq(&cc.barrier, &ca.barrier)); // Closing VM a leaves slot 3's UnitCmds owned by the device-lifetime allocator. drop(ca); drop(vm_a); let again = g16::object::test_unit_cmds(3); - assert!(crate::sync::Arc::ptr_eq(&again.seq, &rb[0])); - assert!(crate::sync::Arc::ptr_eq(&again.barrier, &rb[1])); + assert!(crate::sync::Arc::ptr_eq(&again.work, &rb[0])); + assert!(crate::sync::Arc::ptr_eq(&again.seq, &rb[1])); + assert!(crate::sync::Arc::ptr_eq(&again.barrier, &rb[2])); g16::object::PERSISTENT.with(|p| { let p = p.borrow(); let owned = &p.as_ref().unwrap().objects; assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[0]))); assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[1]))); + assert!(owned.iter().any(|o| crate::sync::Arc::ptr_eq(o, &rb[2]))); assert!(owned.iter().all(|o| o.class == Class::FwCoherent)); }); // Work rings require a device-lifetime persistent allocator and never live in session o. @@ -722,7 +769,7 @@ def module(text, name): } #[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); - assert!(arena.compute.compute.iter().all(|s|s.work.class==g16::object::Class::Shared)); + assert!(arena.compute.compute.iter().all(|s|s.work.class==g16::object::Class::FwCoherent)); assert!(arena.render.passes.iter().all(|s|s.ta_work.class==g16::object::Class::FwCoherent&&s.fs_work.class==g16::object::Class::FwCoherent)); let work=arena.compute.compute.iter().map(|s|&s.work) .chain(arena.render.passes.iter().flat_map(|s|[&s.ta_work,&s.fs_work])); @@ -3314,6 +3361,82 @@ def module(text, name): assert!(!p.reclaim_closed()); } + mod compute_cmds_retry { + use crate::*; + use crate::sync::{Arc, Mutex}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use crate::g16::object::{FwObject, Objects, Window}; + use crate::g16::slots::UnitCmds; + pub(super) mod hw { + pub(crate) use crate::g16::hw::sizes; + } + pub struct Factory { + window: Arc>, + persistent_calls: AtomicUsize, + } + impl Factory { + pub fn persistent_objects(&self) -> Objects { + self.persistent_calls.fetch_add(1, Ordering::Relaxed); + Objects::with_window(true, self.window.clone()) + } + } + __PERSISTENT_UNIT_CMDS__ + __COMPUTE_CMDS_STRUCT__ + impl ComputeCmds { + pub(crate) fn new() -> Result> { + Arc::new( + Self { + sets: Mutex::new([const { None }; hw::sizes::COMPUTE_UNITS]), + }, + GFP_KERNEL, + ) + } + __COMPUTE_CMDS_GET__ + } + #[test] + fn failed_finish_private_retries_sync_and_failed_kbox_skips_persistent_objects() { + let window = Arc::new(Mutex::new(Window::new()), GFP_KERNEL).unwrap(); + window.lock().fail_once.store(true, Ordering::Release); + let factory = Factory { + window: window.clone(), + persistent_calls: AtomicUsize::new(0), + }; + let cmds = ComputeCmds::new().unwrap(); + + // KBox::new_uninit OOM must fail before calling factory.persistent_objects(). + crate::FAIL_KBOX_UNINIT.with(|f| f.set(true)); + assert_eq!(cmds.get(&factory, 0).err(), Some(ENOMEM)); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 0); + + // First real call allocates work/seq/barrier (3 objects) and fails sync_range once. + let before = crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()); + assert_eq!(cmds.get(&factory, 0).err(), Some(EIO)); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 1); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 3); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 1); + + // Retry must NOT re-allocate work/seq/barrier AND MUST retry sync_range on the + // preserved pending range before marking finished = true. + let first = cmds.get(&factory, 0).unwrap(); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 1); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 3); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + { + let w = window.lock(); + let ranges = w.ranges.lock().unwrap(); + assert_eq!(ranges.len(), 2); + assert_eq!(ranges[0], ranges[1]); + } + + // Third call hits finished fast-path without calling sync_range again. + let second = cmds.get(&factory, 0).unwrap(); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + assert!(Arc::ptr_eq(&first.work, &second.work)); + assert!(Arc::ptr_eq(&first.seq, &second.seq)); + assert!(Arc::ptr_eq(&first.barrier, &second.barrier)); + } + } + } ''' poll_source = (production/'poll.rs').read_text() @@ -3404,6 +3527,14 @@ def module(text, name): alloc_private_in_fn = item(object_source, 'fn alloc_private_in(') assert 'pub(crate) fn persistent_objects_probe(&self) -> Objects' in object_source, 'Factory must expose persistent_objects_probe for probe-time work rings' assert 'if self.probe {' in alloc_private_in_fn and 'self.dev.registration_guard().ok_or(ENODEV)?' in alloc_private_in_fn, 'alloc_private_in must gate as_bound() on self.probe and keep registration_guard() otherwise' +assert alloc_private_in_fn.index('UniqueArc::::new_uninit(GFP_KERNEL)?') < alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range('), 'alloc_private_in must pre-allocate UniqueArc before mapping firmware aperture' +assert alloc_private_in_fn.index('self.uat.kernel_lower_vm().map_in_range(') < alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range('), 'alloc_private_in must map uncached aliases before firmware aperture' +assert alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range(') < alloc_private_in_fn.index('self.mappings.push_within_capacity(firmware)'), 'alloc_private_in must commit mappings infallibly after firmware map' +source = (source + .replace('__FINISH_PRIVATE__', item(object_source, 'pub(crate) fn finish_private(')) + .replace('__PERSISTENT_UNIT_CMDS__', item(resources_source, 'struct PersistentUnitCmds {')) + .replace('__COMPUTE_CMDS_STRUCT__', item(resources_source, 'pub(crate) struct ComputeCmds {').replace('#[pin]\n', '').replace('super::hw::', 'hw::')) + .replace('__COMPUTE_CMDS_GET__', item(resources_source, 'pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result {'))) ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( 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 ad0bfd3a31f0c2..a06beb782943b1 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 @@ -40,7 +40,7 @@ def function(text, name): #[derive(Clone,Copy)]enum Channel{Compute,Ta,Fs} mod notifier_page {pub const COMPUTE_STAMP:usize=0;pub const COMPUTE_CONTEXT:usize=4;pub const TA_STAMP:usize=8;pub const FS_STAMP:usize=12;pub const FS_RECORD:usize=32;} mod notifier {pub const CONTEXT:usize=16;} -mod compute {pub const DESCRIPTOR_COMPLETED:usize=0;pub const DESCRIPTOR_COUNTER:usize=8;} +mod manager {pub const COUNTER:usize=0x4c;pub const COMPLETED:usize=0x54;} #[derive(Default)]struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object} struct RGraph{fw_stamp:[Object;2],qstate:[Object;2],qinfo:[Object;2],notifier:Object} struct Graph{compute:[CGraph;hw::sizes::COMPUTE_PIPES],render:RGraph} @@ -52,7 +52,7 @@ def function(text, name): struct Engine{flights:Vec,target:[u32;hw::sizes::COMPUTE_PIPES],ta_target:u32,fs_target:u32,retired_ticks:[u64;4]} 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 CUnit{counter:Object,descriptor:Object,its:Object,work:Object} struct RUnit{scene:Object} struct Scrub{compute:Vec,passes:Vec} struct Slots{scrub:Scrub} @@ -84,8 +84,8 @@ def function(text, name): let mut f=Firmware{ graph:Graph{compute:core::array::from_fn(|_|CGraph::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),compute_pipe:0,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;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],chan_settled:false,pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:target_arr,ta_target:target,fs_target:target,retired_ticks:[0;4]}, - slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, + engine:Engine{flights:vec![Flight{computes:u32::from(!render),renders:u32::from(render),compute_pipe:0,target,ta_target:target,fs_target:target,job:Job{vm:Vm{slot:2},resources:Resources{compute:vec![CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}],pools:Pools{full:true,completed:2}}},claims:Claims{slot:[0;16],slot_count:u32::from(!render),pass:[0;4]},head:1,ta_head:1,fs_head:1,rec:[1;3],chan_settled:false,pb_slot:0,uma_submitted:2,csubmitted:{let mut a=[0u64;16];if !render{a[0]=ordinal;}a},recovery_suspect:false,recovery_started_ns:0,gate_passed_ns:None,unsettled_polls:0,doomed:false}],target:target_arr,ta_target:target,fs_target:target,retired_ticks:[0;4]}, + slots:Slots{scrub:Scrub{compute:vec![CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}],passes:vec![RUnit{scene:Object::default()}]}}, pools:Pools{full:true,completed:2},channels:TopChannels{compute_producer:1},queue_passed:true,last_chan_passed:Cell::new(None), }; f.graph.compute[0].fw_stamp.set(0,u64::from(target)); @@ -93,8 +93,8 @@ def function(text, name): f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); f.engine.flights[0].job.resources.compute[0].counter.set(0,ordinal); f.engine.flights[0].job.resources.compute[0].its.set(0,100);f.engine.flights[0].job.resources.compute[0].its.set(8,101); - f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COMPLETED,ordinal); - f.engine.flights[0].job.resources.compute[0].work.set(compute::DESCRIPTOR_COUNTER,0x1234); + f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COMPLETED,ordinal); + f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COUNTER,0x1234); for stage in 0..2{f.graph.render.fw_stamp[stage].set(0,u64::from(target));} f.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(target)); f.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(target)); @@ -146,7 +146,7 @@ def function(text, name): f.graph.compute[0].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); + f.queue_passed=true;f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COMPLETED,n-1); assert_eq!(f.retired(),Ok(Retirement::Pending)); } } @@ -224,11 +224,11 @@ def function(text, name): #[test]fn multi_compute_horizon_requires_every_claimed_unit_receipt(){ let mut f=firmware(false,12); let mk_unit=|sub:u64,start:u64,end:u64|{ - let mut u=CUnit{counter:Object::default(),its:Object::default(),work:Object::default()}; + let mut u=CUnit{counter:Object::default(),descriptor:Object::default(),its:Object::default(),work:Object::default()}; u.counter.set(0,sub); u.its.set(0,start);u.its.set(8,end); - u.work.set(compute::DESCRIPTOR_COMPLETED,sub); - u.work.set(compute::DESCRIPTOR_COUNTER,0x1234); + u.descriptor.set(manager::COMPLETED,sub); + u.descriptor.set(manager::COUNTER,0x1234); u }; let fl=&mut f.engine.flights[0]; @@ -239,9 +239,9 @@ def function(text, name): fl.job.resources.compute=vec![mk_unit(10,100,110),mk_unit(11,110,120),mk_unit(12,120,130)]; assert_eq!(f.retired(),Ok(Retirement::Full)); // Missing interior unit completion keeps the whole batched flight pending. - f.engine.flights[0].job.resources.compute[1].work.set(compute::DESCRIPTOR_COMPLETED,10); + f.engine.flights[0].job.resources.compute[1].descriptor.set(manager::COMPLETED,10); assert_eq!(f.retired(),Ok(Retirement::Pending)); - f.engine.flights[0].job.resources.compute[1].work.set(compute::DESCRIPTOR_COMPLETED,11); + f.engine.flights[0].job.resources.compute[1].descriptor.set(manager::COMPLETED,11); // Missing tail unit ticks keeps the whole batched flight pending. f.engine.flights[0].job.resources.compute[2].its.set(8,0); 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 06b87ba9ef64bb..78b33c7ac32b33 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-timestamps.py @@ -168,6 +168,7 @@ def function(source, marker): pub vals: [u64; 4], pub r64_calls: std::cell::Cell, pub r32_calls: std::cell::Cell, + pub sync_calls: std::cell::Cell, } impl Cells { pub fn new(vals: [u64; 4]) -> Self { @@ -175,8 +176,13 @@ def function(source, marker): vals, r64_calls: std::cell::Cell::new(0), r32_calls: std::cell::Cell::new(0), + sync_calls: std::cell::Cell::new(0), } } + pub fn sync_for_cpu(&self, _offset: usize, _len: usize) -> Result { + self.sync_calls.set(self.sync_calls.get() + 1); + Ok(()) + } pub fn r64(&self, offset: usize) -> Result { self.r64_calls.set(self.r64_calls.get() + 1); match offset { @@ -322,7 +328,9 @@ def function(source, marker): fw.publish_timestamps(&flight,&claims).unwrap(); assert_eq!((c0.words[0].load(Ordering::Relaxed),c0.words[1].load(Ordering::Relaxed)),(expected(0x1_0000_0070),expected(0x1_0000_0090))); assert_eq!((c1.words[0].load(Ordering::Relaxed),c1.words[1].load(Ordering::Relaxed)),(expected(0x2_0000_0010),expected(0x2_0000_0040))); - // 26B123 work_ticks-first path must skip redundant ITS WC reads when work ticks are valid. + // 26B123 work_ticks-first path invalidates cacheable FwCoherent work lines and skips ITS WC reads. + assert_eq!(flight.job.resources.compute[0].work.sync_calls.get(), 1); + assert_eq!(flight.job.resources.compute[1].work.sync_calls.get(), 1); assert_eq!(flight.job.resources.compute[0].its.r64_calls.get(), 0); assert_eq!(flight.job.resources.compute[1].its.r64_calls.get(), 0); // When work_ticks holds no interval (0/0), fall back to ITS cleanly. @@ -331,8 +339,9 @@ def function(source, marker): work: Cells::new([0, 0, 0, 0]), }; assert_eq!(fw.compute_ticks(&fallback_unit), Ok((0x300, 0x400))); + assert_eq!(fallback_unit.work.sync_calls.get(), 1); assert_eq!(fallback_unit.its.r64_calls.get(), 2); - // 25G83 (work_ticks = None) reads ITS directly with zero work reads. + // 25G83 (work_ticks = None) reads ITS directly with zero work reads or syncs. let fw25 = firmware(); let unit25 = Compute { its: Cells::new([0x500, 0x600, 0, 0]), @@ -341,6 +350,7 @@ def function(source, marker): assert_eq!(fw25.compute_ticks(&unit25), Ok((0x500, 0x600))); assert_eq!(unit25.its.r64_calls.get(), 2); assert_eq!(unit25.work.r32_calls.get(), 0); + assert_eq!(unit25.work.sync_calls.get(), 0); } mod r64_scope { use super::{Result, EINVAL}; From 67390add04cbbc3e405020153a4540dbdc45d7f8 Mon Sep 17 00:00:00 2001 From: Nick Date: Wed, 25 Nov 2026 23:22:04 +0700 Subject: [PATCH 1361/1514] media: apple: jpeg: test the T6050 4:2:2, 4:4:4 and greyscale jobs The T6050 layout test still expected the job to offer 4:2:0 only, and the job test expected 4:2:2 to be refused. Expect every subsampling on T6050, and check each job's programming: the codec and pixel-mode registers, the MCU grid, the plane tiles, plane 1 off for greyscale, and the IO flags. Signed-off-by: Nick --- .../platform/apple/jpeg/apple-jpeg-test.c | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c index e94da7bc415aa6..87da054d7e2ae5 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-test.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-test.c @@ -250,11 +250,11 @@ static void apple_jpeg_t6050_layout_test(struct kunit *test) KUNIT_EXPECT_EQ(test, w[6].value, 8); KUNIT_EXPECT_EQ(test, w[11].value, 16); KUNIT_EXPECT_EQ(test, apple_jpeg_dma_ids(l, 0, w, 11), -ENOSPC); - /* Until the engine probe confirms them, T6050 offers 4:2:0 only. */ + /* The T6050 job takes every subsampling; the older ones 4:2:0 and 4:2:2. */ KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_420)); - KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_422)); - KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_444)); - KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_GREY)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_422)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_444)); + KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(l, AJ_SUBSAMPLING_GREY)); KUNIT_EXPECT_TRUE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_422)); KUNIT_EXPECT_FALSE(test, apple_jpeg_has_subsampling(wide, AJ_SUBSAMPLING_444)); } @@ -268,6 +268,16 @@ static int apple_jpeg_index(const struct apple_jpeg_write *w, int n, int from, u return -1; } +/* The T6050 programming of the subsamplings besides 4:2:0, as checked on a J815 */ +static const struct apple_jpeg_t6050_case { + enum apple_jpeg_subsampling subsampling; + u32 codec, io, mcu_w, mcu_h, tile0_w, tile1_w; +} apple_jpeg_t6050_cases[] = { + { AJ_SUBSAMPLING_422, AJ_CODEC_422, AJ_IO_FLAGS_422, 16, 8, 2, 2 }, + { AJ_SUBSAMPLING_444, AJ_CODEC_444, AJ_IO_FLAGS_444, 8, 8, 1, 2 }, + { AJ_SUBSAMPLING_GREY, AJ_CODEC_GREY, AJ_IO_FLAGS_GREY, 8, 8, 1, 0 }, +}; + /* T6050 jobs: macOS's sequence, with 16-bit tables and no plane size registers. */ static void apple_jpeg_t6050_job_test(struct kunit *test) { @@ -320,9 +330,30 @@ static void apple_jpeg_t6050_job_test(struct kunit *test) KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1)), 0x00110012); KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_QTBL16(1) + 0x7c), 0x00630063); - job.subsampling = AJ_SUBSAMPLING_422; - KUNIT_EXPECT_EQ(test, apple_jpeg_build_job(l, &job, w, APPLE_JPEG_MAX_WRITES), - -EOPNOTSUPP); + /* The other subsamplings: codec, chroma layout, MCU grid, tiles, header */ + for (unsigned int i = 0; i < ARRAY_SIZE(apple_jpeg_t6050_cases); i++) { + const struct apple_jpeg_t6050_case *c = &apple_jpeg_t6050_cases[i]; + + job.subsampling = c->subsampling; + /* NV24's chroma rows are full width: twice the luma stride */ + job.chroma_stride = c->subsampling == AJ_SUBSAMPLING_444 ? 2 * job.width : job.width; + n = apple_jpeg_build_job(l, &job, w, APPLE_JPEG_MAX_WRITES); + KUNIT_ASSERT_GT(test, n, 0); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_CODEC), c->codec); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_T6050_PX_MODE), c->codec); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_MCUS_W), + DIV_ROUND_UP(job.width, c->mcu_w)); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_MCUS_H), + DIV_ROUND_UP(job.height, c->mcu_h)); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_PLANE0_TILE_H), c->tile0_w); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_USE_PLANE1), !!c->tile1_w); + if (c->tile1_w) + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_PX_PLANE1_TILE_H), + c->tile1_w); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_JPEG_IO_FLAGS), + AJ_IO_FLAGS_T6050 | AJ_IO_FLAGS_ORDER | c->io); + KUNIT_EXPECT_EQ(test, apple_jpeg_last(w, n, AJ_T6050_ENC_CTRL), 0x35); + } } static void apple_jpeg_older_hwrev_test(struct kunit *test) From 76e07cfb616cd096dd7aa9db73047948ab6698bb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 03:27:58 +1100 Subject: [PATCH 1362/1514] drm/asahi: g16: encode a one-period low-peak limiter filter The low-peak (PPM) limiter's IIR filter spans the ADT's limiter time constant divided by the GPU power sample period. On the 15-inch M3 Air both are the same, so the filter spans one period, and encode_for refused it ("periods < 2"), which stopped the 27.2 start with EINVAL before the firmware ran. A one-period filter is valid: its pole is (1 - 1) / 1 = +0.0 and its gain 1 / 1 = +1.0, so each sample is taken as is. Accept periods >= 1 and keep the limiter on, with every input still from the machine's ADT. f32_bits() looped forever on a zero numerator; return +0.0 for it and pin both encodings with compile-time checks. Machines whose filter spans two or more periods encode exactly as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 25dc15da5525ca..79f85c96350e66 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -233,6 +233,10 @@ pub(crate) struct PowerLimiter { /// 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 { + // +0.0: a zero numerator never normalizes (`n < d` would loop forever). + if num == 0 { + return 0; + } let (mut n, mut d) = (num as u64, den as u64); let mut exponent: i32 = 0; while n >= 2 * d { @@ -256,6 +260,7 @@ pub(crate) const fn f32_bits(num: u32, den: u32) -> u32 { } 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); +const _: () = assert!(f32_bits(0, 1) == 0 && f32_bits(1, 1) == 0x3f80_0000); /// Where the RETENTION object (0x4000 zeroed bytes) is published. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1408,8 +1413,12 @@ pub(crate) fn encode_for( { return Err(()); } + // The low-peak IIR filter spans `periods` sample periods. One period (the ADT's + // limiter time constant equals its sample period, as on the 15-inch M3 Air) is a valid + // filter: a_neg = (1 - 1) / 1 = +0.0 and a = 1 / 1 = +1.0, i.e. each sample is taken + // as is. Only a time constant shorter than one period is refused. let periods = input.lowpeak_limiter_tc_ms / input.power_sample_period_ms; - if periods < 2 { + if periods < 1 { return Err(()); } let periods_x4 = periods.checked_mul(4).ok_or(())?; From 6ce1f16e3b3eb174bce7cf23a9b0c73614658f5e Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 11:39:11 -0500 Subject: [PATCH 1363/1514] selftests: asahi-m4: initialize descriptor_fw in g15s_26b123 ComputeRefs Initialize the optional descriptor_fw field to 0 in the g15s_26b123() ComputeRefs fixture added on main, matching compute_work() in check-abi-26b123.rs. Signed-off-by: Diljit Singh --- .../testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 cd0276e20e6642..a06623ffaa9f2e 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 @@ -450,7 +450,7 @@ fn g15s_26b123() { let cr = 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, + descriptor_fw: 0, 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, From dee9cd36cfffbc0e61009027eb00a60bdbaf37d4 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:15:46 -0500 Subject: [PATCH 1364/1514] soc: apple: sleep: t8103: allow GPU commit stop and save AGX fabric tunables Allow T8103 deep sleep when the GPU driver has registered a ready commit-time stop callback (apple_sleep_coproc_ready_node()). When ps_gfx is powered at commit time, save the seven boot-programmed AGX fabric tunable registers (0x205000000), drain bridges[0], and lower ps_gfx before stopping PMP so GFX powers down while PMP is still running. On wake, restore ps_gfx and the saved AGX fabric tunables before returning to the OS so the GPU firmware can warm-restart cleanly. Signed-off-by: Erik Bourget --- drivers/soc/apple/sleep-t8103.h | 54 ++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/drivers/soc/apple/sleep-t8103.h b/drivers/soc/apple/sleep-t8103.h index d9ffd8ae6e9d65..cdbb1b1ef67337 100644 --- a/drivers/soc/apple/sleep-t8103.h +++ b/drivers/soc/apple/sleep-t8103.h @@ -174,6 +174,10 @@ static const u32 t8103_acc_thrtl[] = { T8103_ACC_AMX_THRTL, T8103_ACC_LLC_THRTL, #define T8103_PMP_ACK_US 200000 #define T8103_PMP_IDLE_US 10000 +/* AGX fabric tunables programmed by the boot loader; lost when ps_gfx powers off. */ +#define T8103_AGX_FABRIC 0x205000000ULL +static const u32 t8103_agx_regs[] = { 0x30, 0x34, 0x400, 0x600, 0x738, 0x798, 0x800 }; + /* * CLK_PERF_DCS (T8103_DCS_PERF) holds the memory clock's performance state: target in bits 3:0, * busy in bit 31. Moving it by more than one state in a single write leaves memory unusable on @@ -233,6 +237,7 @@ static const u32 t8103_commit_off[] = { * nothing else raises them, and the DCP driver's power-up of DISP0 hangs without them. Put * back as the commit found them, pmp first. */ +#define T8103_COMMIT_OFF_GFX 0 #define T8103_COMMIT_OFF_PMP 10 #define T8103_COMMIT_OFF_RMX 9 @@ -365,6 +370,9 @@ static struct t8103_sleep { u8 slc_result, aic_result; void __iomem *pmp_asc, *pmp_mbox, *sio_asc, *sio_mbox; void __iomem *dcp_mbox, *dcpext_asc, *dcpext_mbox; + void __iomem *agx_fabric; + u32 agx_saved[ARRAY_SIZE(t8103_agx_regs)]; + bool agx_saved_valid; /* Each coprocessor's t8103_asc_stop() result */ u8 pmp_result, sio_result, dcp_result, dcpext_result; /* The t8103_commit_off and t8103_cg_commit_off words found or taken off */ @@ -743,6 +751,7 @@ static int t8103_sleep_map_regs(struct apple_sleep *s) t->dcpext_mbox = t8103_ioremap(s, T8103_DCPEXT_MBOX, 0x1000); for (i = 0; i < ARRAY_SIZE(t8103_bridges); i++) t->bridges[i] = t8103_ioremap(s, t8103_bridges[i].pa, 0x1000); + t->agx_fabric = t8103_ioremap(s, T8103_AGX_FABRIC, 0x1000); /* The commit word is the S2R timer, the clusters' words are in "ps". */ s->commit = s->ps_aon + T8103_S2R_TIMER; s->cluster = s->ps; @@ -829,8 +838,9 @@ static int t8103_sleep_check(struct apple_sleep *s) struct t8103_sleep *t = &t8103_sleep; unsigned int i, wanted = 0; - /* The GPU coprocessor doesn't survive the power cut, and it can't be started twice. */ - if (t->gpu && device_is_bound(&t->gpu->dev)) { + /* Refuse a bound GPU driver unless it registered a commit stop for warm restart. */ + if (t->gpu && device_is_bound(&t->gpu->dev) && + !apple_sleep_coproc_ready_node(t->gpu->dev.of_node)) { dev_err(s->dev, "refused: the GPU's driver is bound\n"); return -EBUSY; } @@ -1226,6 +1236,34 @@ static void t8103_pre_smc_down(struct apple_sleep *s) T8103_SEP_GATE_US); t->sep_ps = v; } + t->commit_off = 0; + t->commit_lowered = 0; + t->agx_saved_valid = false; + /* + * Lower GFX (and save its fabric tunables) before stopping PMP, matching macOS and + * newer SoCs where GFX powers off while PMP is still running. + */ + if (!sleep_ps_on(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) { + t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); + } else { + if (t->agx_fabric) { + for (i = 0; i < ARRAY_SIZE(t8103_agx_regs); i++) + t->agx_saved[i] = readl(t->agx_fabric + t8103_agx_regs[i]); + t->agx_saved_valid = true; + } + if (t->bridges[0]) { + writel(1, t->bridges[0] + T8103_BRIDGE_8014); + writel(1, t->bridges[0] + T8103_BRIDGE_82BC); + writel(2, t->bridges[0] + T8103_BRIDGE_82BC); + writel(4, t->bridges[0] + T8103_BRIDGE_82BC); + } + t->commit_saved[T8103_COMMIT_OFF_GFX] = + readl(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX]); + t->commit_lowered |= BIT(T8103_COMMIT_OFF_GFX); + sleep_ps_lower(s, t8103_commit_off[T8103_COMMIT_OFF_GFX]); + if (!sleep_ps_wait_off(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) + t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); + } t8103_pmp_stop(s); t->aon_commit_off = 0; for (i = 0; i < ARRAY_SIZE(t8103_aon_commit_off); i++) { @@ -1240,9 +1278,7 @@ static void t8103_pre_smc_down(struct apple_sleep *s) if (!readl_poll_timeout_atomic(reg, av, !FIELD_GET(PS_ACTUAL, av), 1, 10000)) t->aon_commit_off |= BIT(i); } - t->commit_off = 0; - t->commit_lowered = 0; - for (i = 0; i < ARRAY_SIZE(t8103_commit_off) - 1; i++) { + for (i = 1; i < ARRAY_SIZE(t8103_commit_off) - 1; i++) { unsigned int b; if (!sleep_ps_on(s, t8103_commit_off[i])) { @@ -1528,6 +1564,14 @@ static void t8103_sleep_wake(struct apple_sleep *s) if (t->commit_lowered & BIT(T8103_COMMIT_OFF_RMX)) sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_RMX], t->commit_saved[T8103_COMMIT_OFF_RMX]); + if (t->commit_lowered & BIT(T8103_COMMIT_OFF_GFX)) { + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX], + t->commit_saved[T8103_COMMIT_OFF_GFX]); + if (t->agx_saved_valid && t->agx_fabric) { + for (i = 0; i < ARRAY_SIZE(t8103_agx_regs); i++) + writel(t->agx_saved[i], t->agx_fabric + t8103_agx_regs[i]); + } + } t->commit_lowered = 0; for (i = ARRAY_SIZE(t8103_aon_commit_off); i > 0; i--) { unsigned int idx = i - 1; From 835b40a4a1cdeadcd9a1261d95a2d6c130ab9253 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:31:00 -0500 Subject: [PATCH 1365/1514] soc: apple: sleep: t8103: enforce GPU commit-stop and wake-restore gates Tighten error handling around the T8103 GPU deep-sleep commit and wake paths: - Export apple_sleep_coproc_wake_error() and record per-coprocessor wake errors (reset alongside stop_ret when readied). - In t8103_sleep_check(), refuse sleep when a bound GPU lacks either the AGX fabric or bridge[0] MMIO mapping. - In t8103_pre_smc_down(), treat a failed GPU commit stop (stop_ret != 0) or a timed-out GFX domain power-off past the point of no return as fatal instead of stopping PMP while GFX is still active. - In t8103_sleep_wake(), check both PMP and GFX sleep_ps_restore() results before touching AGX fabric registers and propagate any failure to the GPU coprocessor's wake_err. Signed-off-by: Erik Bourget --- drivers/soc/apple/sleep-t8103.h | 51 +++++++++++++++++++++++++-------- drivers/soc/apple/sleep.c | 13 +++++++++ include/linux/soc/apple/sleep.h | 8 ++++++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/drivers/soc/apple/sleep-t8103.h b/drivers/soc/apple/sleep-t8103.h index cdbb1b1ef67337..05db54012ab259 100644 --- a/drivers/soc/apple/sleep-t8103.h +++ b/drivers/soc/apple/sleep-t8103.h @@ -373,6 +373,7 @@ static struct t8103_sleep { void __iomem *agx_fabric; u32 agx_saved[ARRAY_SIZE(t8103_agx_regs)]; bool agx_saved_valid; + int gfx_wake_err; /* Each coprocessor's t8103_asc_stop() result */ u8 pmp_result, sio_result, dcp_result, dcpext_result; /* The t8103_commit_off and t8103_cg_commit_off words found or taken off */ @@ -825,6 +826,7 @@ static int t8103_sleep_begin(struct apple_sleep *s) t->mux_timeouts = 0; t->cluster_timeouts = 0; t->mux_wake_timeouts = 0; + t->gfx_wake_err = 0; memset(t->cluster_wake_ret, 0, sizeof(t->cluster_wake_ret)); t->aop_slp_ddr = t8103_aop_bound(); if (t->aop_slp_ddr) @@ -838,11 +840,16 @@ static int t8103_sleep_check(struct apple_sleep *s) struct t8103_sleep *t = &t8103_sleep; unsigned int i, wanted = 0; - /* Refuse a bound GPU driver unless it registered a commit stop for warm restart. */ - if (t->gpu && device_is_bound(&t->gpu->dev) && - !apple_sleep_coproc_ready_node(t->gpu->dev.of_node)) { - dev_err(s->dev, "refused: the GPU's driver is bound\n"); - return -EBUSY; + /* Refuse a bound GPU driver unless it registered a commit stop and registers are mapped. */ + if (t->gpu && device_is_bound(&t->gpu->dev)) { + if (!apple_sleep_coproc_ready_node(t->gpu->dev.of_node)) { + dev_err(s->dev, "refused: the GPU's driver is bound\n"); + return -EBUSY; + } + if (!t->agx_fabric || !t->bridges[0]) { + dev_err(s->dev, "refused: GPU fabric or bridge registers not mapped\n"); + return -ENODEV; + } } for (i = 0; i < T8103_WAKE_WORDS; i++) @@ -1239,6 +1246,12 @@ static void t8103_pre_smc_down(struct apple_sleep *s) t->commit_off = 0; t->commit_lowered = 0; t->agx_saved_valid = false; + if (t->gpu && device_is_bound(&t->gpu->dev)) { + struct apple_sleep_coproc *gc = apple_sleep_coproc_find(&t->gpu->dev); + + if (gc && gc->stop_ret) + panic("T8103 committed GPU stop failed: %d", gc->stop_ret); + } /* * Lower GFX (and save its fabric tunables) before stopping PMP, matching macOS and * newer SoCs where GFX powers off while PMP is still running. @@ -1261,8 +1274,9 @@ static void t8103_pre_smc_down(struct apple_sleep *s) readl(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX]); t->commit_lowered |= BIT(T8103_COMMIT_OFF_GFX); sleep_ps_lower(s, t8103_commit_off[T8103_COMMIT_OFF_GFX]); - if (!sleep_ps_wait_off(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) - t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); + if (sleep_ps_wait_off(s, t8103_commit_off[T8103_COMMIT_OFF_GFX])) + panic("T8103 committed GFX power-off timed out"); + t->commit_off |= BIT(T8103_COMMIT_OFF_GFX); } t8103_pmp_stop(s); t->aon_commit_off = 0; @@ -1471,6 +1485,7 @@ static void t8103_sleep_wake(struct apple_sleep *s) { struct t8103_sleep *t = &t8103_sleep; unsigned int i; + int pmp_ret = 0; u32 v; t8103_aic_ipi_restore(s); @@ -1559,18 +1574,27 @@ static void t8103_sleep_wake(struct apple_sleep *s) sleep_ps_restore(s->ps + t8103_commit_off[idx], 0xf); } if (t->commit_lowered & BIT(T8103_COMMIT_OFF_PMP)) - sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_PMP], - t->commit_saved[T8103_COMMIT_OFF_PMP]); + pmp_ret = sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_PMP], + t->commit_saved[T8103_COMMIT_OFF_PMP]); if (t->commit_lowered & BIT(T8103_COMMIT_OFF_RMX)) sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_RMX], t->commit_saved[T8103_COMMIT_OFF_RMX]); if (t->commit_lowered & BIT(T8103_COMMIT_OFF_GFX)) { - sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX], - t->commit_saved[T8103_COMMIT_OFF_GFX]); - if (t->agx_saved_valid && t->agx_fabric) { + int gfx_ret = pmp_ret ? pmp_ret : + sleep_ps_restore(s->ps + t8103_commit_off[T8103_COMMIT_OFF_GFX], + t->commit_saved[T8103_COMMIT_OFF_GFX]); + + if (!gfx_ret && t->agx_saved_valid && t->agx_fabric) { for (i = 0; i < ARRAY_SIZE(t8103_agx_regs); i++) writel(t->agx_saved[i], t->agx_fabric + t8103_agx_regs[i]); } + t->gfx_wake_err = gfx_ret; + if (gfx_ret && t->gpu) { + struct apple_sleep_coproc *gc = apple_sleep_coproc_find(&t->gpu->dev); + + if (gc) + gc->wake_err = gfx_ret; + } } t->commit_lowered = 0; for (i = ARRAY_SIZE(t8103_aon_commit_off); i > 0; i--) { @@ -1627,6 +1651,9 @@ static void t8103_sleep_finish(struct apple_sleep *s) if (t->mux_fixed) dev_info(s->dev, "T8103: clock muxes put back after the wake: %#llx\n", t->mux_fixed); + if (t->gfx_wake_err) + dev_err(s->dev, "T8103: GFX power restore failed after wake: %d\n", + t->gfx_wake_err); dev_info(s->dev, "T8103: wake status %08x %08x %08x %08x %08x, clusters %d %d, mux timeouts %u\n", s->wake_status[0], s->wake_status[1], s->wake_status[2], s->wake_status[3], s->wake_status[4], t->cluster_wake_ret[0], t->cluster_wake_ret[1], diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 320b2cecc43d3c..88f6fbd0f96571 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -377,6 +377,7 @@ static struct apple_sleep_coproc { bool stopped; u32 status; int stop_ret; + int wake_err; /* No ASC: its last stop takes it whole, power word @ps included, before the others. */ bool first; /* Between ANS and the others, whatever order they registered in. */ @@ -1650,6 +1651,8 @@ void apple_sleep_coproc_set_ready(struct device *dev, bool ready) return; c->ready = ready; c->stopped = false; + c->stop_ret = 0; + c->wake_err = 0; } EXPORT_SYMBOL_GPL(apple_sleep_coproc_set_ready); @@ -1663,6 +1666,16 @@ bool apple_sleep_coproc_stopped(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_coproc_stopped); +int apple_sleep_coproc_wake_error(struct device *dev) +{ + struct apple_sleep_coproc *c; + + guard(mutex)(&apple_sleep_coprocs_lock); + c = apple_sleep_coproc_find(dev); + return c ? c->wake_err : -ENODEV; +} +EXPORT_SYMBOL_GPL(apple_sleep_coproc_wake_error); + bool apple_sleep_commit_stops_coprocs(void) { return READ_ONCE(apple_sleep) && pm_suspend_via_firmware(); diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index bcaeffeb6832ab..0f0380daa0094e 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -111,6 +111,9 @@ void apple_sleep_coproc_set_early(struct device *dev); /* Whether the last step stopped it: after a refused sleep, false means it still runs. */ bool apple_sleep_coproc_stopped(struct device *dev); +/* Platform wake error for a stopped coprocessor (0 if its power domain and fabric restored). */ +int apple_sleep_coproc_wake_error(struct device *dev); + /* * Whether this sleep's commit stops the registered coprocessors. Then one that can't be * registered refuses the sleep: stopped any earlier, a later refusal would strand it. @@ -327,6 +330,11 @@ static inline bool apple_sleep_coproc_stopped(struct device *dev) return false; } +static inline int apple_sleep_coproc_wake_error(struct device *dev) +{ + return -ENODEV; +} + static inline void apple_sleep_note_sub(u8 step) {} static inline bool apple_sleep_commit_stops_coprocs(void) From 22073d0c4f7614ce6b195ce78054f3056501725b Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 11:32:48 -0500 Subject: [PATCH 1366/1514] soc: apple: sleep: t8103: enable NCO channels across sleep commit T8103's MCA audio power domains (ps_mca0..5) are externally clocked by NCO channels 0..4. When an ALSA stream closes, apple-mca disables its parent NCO clock, clearing CTRL_ENABLE. During suspend-to-RAM entry, the hardware sleep sequencer writes and polls ps_mca0..5, which hang busy without a running NCO clock and trigger a SoC reset. Map the NCO register block in the T8103 sleep profile, enable any disabled NCO channel before the sleep commit, and clear CTRL_ENABLE again on wake so clk-apple-nco's software state stays consistent. Signed-off-by: Erik Bourget --- drivers/soc/apple/sleep-t8103.h | 43 ++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/drivers/soc/apple/sleep-t8103.h b/drivers/soc/apple/sleep-t8103.h index 05db54012ab259..f30b4b6a088f6b 100644 --- a/drivers/soc/apple/sleep-t8103.h +++ b/drivers/soc/apple/sleep-t8103.h @@ -318,6 +318,17 @@ static const u32 t8103_cg_commit_off[] = { #define T8103_DCS_WQ_FLUSH 0xa30 #define T8103_DCS_FLUSH_US 330 +/* + * NCO channels 0..4 clock the externally-clocked MCA PMGR domains (ps_mca0..5). The SoC sleep + * entry sequence writes and polls those domains; if a channel's enable bit was cleared after + * an audio stream closed, the PMGR transition hangs busy and resets the SoC. Enable any + * disabled channel across the commit and turn it back off on wake. + */ +#define T8103_NCO 0x23b044000ULL +#define T8103_NCO_CHANS 5 +#define T8103_NCO_STRIDE 0x4000 +#define T8103_NCO_CTRL_EN BIT(31) + /* AIC: each CPU's IPI mask set at +0x5024 and its status at +0x5004, 0x80 per CPU */ #define T8103_AIC_CPU 0x23b105000ULL #define T8103_AIC_CPU_STRIDE 0x80 @@ -356,8 +367,9 @@ static const u32 t8103_aon_boot_auto[] = { }; static struct t8103_sleep { - void __iomem *mcc_bcast, *mcc_planes, *dcs, *aic_cpu; + void __iomem *mcc_bcast, *mcc_planes, *dcs, *aic_cpu, *nco; void __iomem *bridges[ARRAY_SIZE(t8103_bridges)]; + u8 nco_forced; /* The SoC clock muxes from T8103_MUX_SOC at the commit, and those the wake put back */ u32 mux_snap[40]; u64 mux_fixed; @@ -740,8 +752,10 @@ static int t8103_sleep_map_regs(struct apple_sleep *s) t->mcc_planes = t8103_ioremap(s, T8103_MCC_PLANES, T8103_MCC_NPLANES * T8103_MCC_STRIDE); t->dcs = t8103_ioremap(s, T8103_DCS_BASE, T8103_DCS_NCHAN * T8103_DCS_STRIDE); t->aic_cpu = t8103_ioremap(s, T8103_AIC_CPU, T8103_AIC_CPUS * T8103_AIC_CPU_STRIDE); - if (!t->mcc_bcast || !t->mcc_planes || !t->dcs || !t->aic_cpu) - return dev_err_probe(s->dev, -ENOMEM, "MCC, DCS or AIC CPU block not mapped\n"); + t->nco = t8103_ioremap(s, T8103_NCO, T8103_NCO_CHANS * T8103_NCO_STRIDE); + if (!t->mcc_bcast || !t->mcc_planes || !t->dcs || !t->aic_cpu || !t->nco) + return dev_err_probe(s->dev, -ENOMEM, + "MCC, DCS, AIC CPU or NCO block not mapped\n"); t->dcs_perf = t8103_ioremap(s, T8103_DCS_PERF, 4); t->pmp_asc = t8103_ioremap(s, T8103_PMP_ASC, 0x100); t->pmp_mbox = t8103_ioremap(s, T8103_PMP_MBOX, 0x1000); @@ -827,6 +841,7 @@ static int t8103_sleep_begin(struct apple_sleep *s) t->cluster_timeouts = 0; t->mux_wake_timeouts = 0; t->gfx_wake_err = 0; + t->nco_forced = 0; memset(t->cluster_wake_ret, 0, sizeof(t->cluster_wake_ret)); t->aop_slp_ddr = t8103_aop_bound(); if (t->aop_slp_ddr) @@ -1421,6 +1436,20 @@ static void t8103_sleep_commit_regs(struct apple_sleep *s) T8103_MUX_TIMEOUT_US)) t->mux_timeouts++; } + /* + * Externally-clocked MCA power domains (ps_mca0..5) hang BUSY in the sleep sequencer + * if their NCO channel is disabled. Enable any disabled channel for the commit. + */ + t->nco_forced = 0; + for (i = 0; i < T8103_NCO_CHANS; i++) { + void __iomem *reg = t->nco + i * T8103_NCO_STRIDE; + + v = readl(reg); + if (!(v & T8103_NCO_CTRL_EN)) { + writel(v | T8103_NCO_CTRL_EN, reg); + t->nco_forced |= BIT(i); + } + } for (i = 0; i < ARRAY_SIZE(t->mux_snap); i++) t->mux_snap[i] = readl(s->clk_mux + T8103_MUX_SOC + i * 4); /* E4: the CPU complexes' and voltage monitors' quiesce */ @@ -1544,6 +1573,14 @@ static void t8103_sleep_wake(struct apple_sleep *s) T8103_MUX_TIMEOUT_US)) t->mux_wake_timeouts++; } + /* Turn back off any NCO channel the commit enabled so clk-apple-nco state matches. */ + for (i = 0; i < T8103_NCO_CHANS; i++) { + void __iomem *reg = t->nco + i * T8103_NCO_STRIDE; + + if (t->nco_forced & BIT(i)) + writel(readl(reg) & ~T8103_NCO_CTRL_EN, reg); + } + t->nco_forced = 0; /* * A cluster's ACC answers only while the cluster is powered: after a real sleep both * were off until W3, and an access before that is an external abort. From e4a69b1508762e9a2140fdd155d45433d94034a5 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Tue, 24 Nov 2026 17:53:02 -0500 Subject: [PATCH 1367/1514] drm/asahi: enable T8103 (G13G) on GPU firmware 27.2 Extend the g14_v27_2 backend to support T8103 (G13G) on firmware 27.2 (26B131) on the default kernel command line: - Map ASC control and MMU fault-status registers with ioremap_np() to honor Apple SoC nonposted-mmio; a posted write to ASC_CPU_CONTROL resets T8103 immediately. - Add T8103 REGISTERS_V27_2 and WRITABLE_V27_2 register aperture tables (including PMP doorbell slot 2 and PMGR scratch / PMP telemetry slot 5) and route apple,agx-t8103 with apple,firmware-compat = <27 2 0> to probe_g14_v27_2(). - Build the G13G 27.2 HwDataB, globals, power, and calibrated thermal / DVFS controller from the 13.5 configuration and device tree (deriving SRAM voltages from apple,min-sram-microvolt when adt-perf-states-sram is absent, and omitting G14-only CRE and per-sensor coefficient tables). - Encode G13 vertex and fragment JobParameters1 layouts in g14_v27_2_render.rs and allow 3000 ms for the initial idle-policy handshake while G13G runs its first DVFS transition. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/driver.rs | 19 +- drivers/gpu/drm/asahi/g14_v27_2.rs | 10 +- drivers/gpu/drm/asahi/g14_v27_2_render.rs | 485 ++++++++++++---------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 275 ++++++++---- drivers/gpu/drm/asahi/hw/t8103.rs | 57 +++ 5 files changed, 531 insertions(+), 315 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 163764c1504ebb..0a44479f7b3c83 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -197,7 +197,7 @@ macro_rules! asahi_of_device_table { ), ( of::DeviceId::new(c"apple,agx-t8103"), - ProbeConfig::Legacy(&hw::t8103::HWCONFIG) + ProbeConfig::LegacyWithG14Handoff(&hw::t8103::HWCONFIG) ), ( of::DeviceId::new(c"apple,agx-t8112"), @@ -403,9 +403,14 @@ impl platform::Driver for AsahiPlatformDriver { // The loader advertises the supported wire layout independently of the image version. if has_g14_handoff && compat.as_slice() == [27, 2, 0] { #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] - return AsahiPlatformDriver::probe_g14_v27_2( - pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2, - ); + { + let (registers, writable) = match cfg.gpu_gen { + hw::GpuGen::G13 => (hw::t8103::REGISTERS_V27_2, hw::t8103::WRITABLE_V27_2), + hw::GpuGen::G14 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2), + _ => return Err(ENODEV), + }; + return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg, registers, writable); + } #[cfg(not(CONFIG_DRM_ASAHI_G14_V27_2))] return Err(ENODEV); } @@ -521,7 +526,11 @@ impl AsahiPlatformDriver { return Err(error); } }; - dev_info!(pdev.as_ref(), "G14 firmware 27.2 running; DRM device registered\n"); + dev_info!( + pdev.as_ref(), + "{:?} firmware 27.2 running; DRM device registered\n", + cfg.gpu_gen + ); Ok(AsahiPlatformDriverData { binding, _device: reg.device().into(), diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 5f18d886413dd0..a9b9477d05ee97 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -91,8 +91,10 @@ unsafe impl Sync for AscControl {} impl AscControl { fn new(phys: u64) -> Result { - // SAFETY: `phys` is the ASC register window of this platform device. - let ptr = unsafe { kernel::bindings::ioremap(phys, 0x4000) }; + // SAFETY: `phys` is the ASC register window of this platform device. Apple SoC fabrics + // require non-posted MMIO (`nonposted-mmio`); a posted write to ASC_CPU_CONTROL resets + // T8103 immediately. + let ptr = unsafe { kernel::bindings::ioremap_np(phys, 0x4000) }; if ptr.is_null() { return Err(ENOMEM); } Ok(Self(ptr.cast())) } @@ -138,7 +140,7 @@ impl FaultStatus { return Err(EINVAL); } // SAFETY: the page lies inside this platform device's SGX register window. - let page = unsafe { kernel::bindings::ioremap(sgx + base as u64, 0x1000) }; + let page = unsafe { kernel::bindings::ioremap_np(sgx + base as u64, 0x1000) }; if page.is_null() { return Err(ENOMEM); } Ok(Self { page: page.cast(), info: info - base, addr: addr.map(|a| a - base), g14x }) } @@ -276,7 +278,7 @@ fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Re fn set_idle_policy(root: &RootV27_2, peer: &mut Peer, allow_off: bool) -> Result { let (target, generation) = root.publish_idle_policy(allow_off)?; peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; - wait(root, 500, || Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation)) + wait(root, 3000, || Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation)) } /// Stops firmware that no runtime owns: allow power-off, then RTKit power-off, then the ASC diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index ecf9e43bc9d866..c389ab009a9b8c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -20,9 +20,13 @@ use kernel::{ }; type Rv = fw::vertex::raw::RunVertexG14V13_5<'static>; +type Rv13 = fw::vertex::raw::RunVertexG13V13_5<'static>; type Rf = fw::fragment::raw::RunFragmentG14V13_5<'static>; +type Rf13 = fw::fragment::raw::RunFragmentG13V13_5<'static>; type Meta = fw::job::raw::JobMeta; +const TILECTL_DISABLE_CLUSTERING: u32 = 1 << 0; + pub(crate) const INITBUF_AT: usize = 0xf00; pub(crate) const OWN_BARRIER_AT: usize = 0xf40; pub(crate) const OWN_BARRIER_SIZE: usize = 0x40; @@ -63,6 +67,9 @@ pub(crate) struct Prep { scene27: GpuArray, info_va: u64, usc: u64, + gpu_gen: crate::hw::GpuGen, + tiling_control: u32, + core_masks: [u32; 2], pub(crate) buffer_op: Option, } @@ -170,6 +177,13 @@ impl QueueRender { } else { None }; + let cfg = ::get_cfg(&self.graph); + let dyncfg = + ::get_dyncfg(&self.graph); + let core_masks = [ + *dyncfg.id.core_masks_packed.first().unwrap_or(&0), + *dyncfg.id.core_masks_packed.get(1).unwrap_or(&0), + ]; Ok(Prep { scene, aux_fb, @@ -177,6 +191,9 @@ impl QueueRender { scene27, info_va: binding.info.gpu_va().get(), usc, + gpu_gen: cfg.gpu_gen, + tiling_control: cfg.render.tiling_control | TILECTL_DISABLE_CLUSTERING, + core_masks, buffer_op, }) } @@ -288,7 +305,6 @@ pub(crate) fn encode_vertex( timestamps: [u64; 2], attachments: &Attachments, ) -> Result { - let jp1 = |field: usize| 0x38 + field - offset_of!(Rv, job_params1); let jp2 = |field: usize| 0x488 + field - offset_of!(Rv, job_params2); header(cmd, 0, c); let scene = &p.scene; @@ -307,87 +323,111 @@ pub(crate) fn encode_vertex( put64(cmd, 0x20, info_va); put64(cmd, 0x28, scene_va); put64(cmd, 0x30, scene.kernel_buffer_pointer().into()); - // JobParameters1 at 0x38, 13.5 G14 internal layout. - put64(cmd, jp1(offset_of!(Rv, job_params1.unk_0)), 0x200); - put32(cmd, jp1(offset_of!(Rv, job_params1.unk_8)), 0x1e3c_e508); - put32(cmd, jp1(offset_of!(Rv, job_params1.unk_c)), 0x1e3c_e508); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.tvb_tilemap)), - scene.tvb_tilemap_pointer().into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.tpc)), - scene.tpc_pointer().into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.tvb_heapmeta)), - scene - .tvb_heapmeta_pointer() - .or(0x8000_0000_0000_0000) - .into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.iogpu_unk_54)), - 0x3a_0012_006b_0003, - ); - put64(cmd, jp1(offset_of!(Rv, job_params1.iogpu_unk_56)), 1); - put32( - cmd, - jp1(offset_of!(Rv, job_params1.utile_config)), - utile_config, - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.ppp_multisamplectl)), - r.multisample_control, - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.tvb_layermeta)), - scene.tvb_layermeta_pointer().into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.preempt_buf1)), - scene.preempt_buf_1_pointer().into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.preempt_buf2)), - scene.preempt_buf_2_pointer().into(), - ); - put64(cmd, jp1(offset_of!(Rv, job_params1.unk_80)), 1); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.preempt_buf3)), - scene.preempt_buf_3_pointer().or(0x4_0000_0000_0000).into(), - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.vdm_ctrl_stream_base)), - r.vdm_base, - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.usc_exec_base_ta)), - p.usc, - ); - put64(cmd, jp1(offset_of!(Rv, job_params1.unk_f8)), 0x8c60); - put32( - cmd, - jp1(offset_of!(Rv, job_params1.helper_program)), - r.vertex_helper.binary, - ); - put64( - cmd, - jp1(offset_of!(Rv, job_params1.helper_arg)), - r.vertex_helper.data, - ); - put32(cmd, jp1(offset_of!(Rv, job_params1.unk_118)), 0x1c); + // JobParameters1 at 0x38, 13.5 G13 or G14 internal layout. + macro_rules! write_vtx_jp1 { + ($R:ty) => {{ + let jp1 = |field: usize| 0x38 + field - offset_of!($R, job_params1); + put64(cmd, jp1(offset_of!($R, job_params1.unk_0)), 0x200); + put32(cmd, jp1(offset_of!($R, job_params1.unk_8)), 0x1e3c_e508); + put32(cmd, jp1(offset_of!($R, job_params1.unk_c)), 0x1e3c_e508); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_tilemap)), + scene.tvb_tilemap_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tpc)), + scene.tpc_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_heapmeta)), + scene + .tvb_heapmeta_pointer() + .or(0x8000_0000_0000_0000) + .into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.iogpu_unk_54)), + 0x3a_0012_006b_0003, + ); + put64(cmd, jp1(offset_of!($R, job_params1.iogpu_unk_56)), 1); + put32( + cmd, + jp1(offset_of!($R, job_params1.utile_config)), + utile_config, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.ppp_multisamplectl)), + r.multisample_control, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.tvb_layermeta)), + scene.tvb_layermeta_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf1)), + scene.preempt_buf_1_pointer().into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf2)), + scene.preempt_buf_2_pointer().into(), + ); + put64(cmd, jp1(offset_of!($R, job_params1.unk_80)), 1); + put64( + cmd, + jp1(offset_of!($R, job_params1.preempt_buf3)), + scene.preempt_buf_3_pointer().or(0x4_0000_0000_0000).into(), + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.vdm_ctrl_stream_base)), + r.vdm_base, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.usc_exec_base_ta)), + p.usc, + ); + put64(cmd, jp1(offset_of!($R, job_params1.unk_f8)), 0x8c60); + put32( + cmd, + jp1(offset_of!($R, job_params1.helper_program)), + r.vertex_helper.binary, + ); + put64( + cmd, + jp1(offset_of!($R, job_params1.helper_arg)), + r.vertex_helper.data, + ); + put32(cmd, jp1(offset_of!($R, job_params1.unk_118)), 0x1c); + }}; + } + if p.gpu_gen == crate::hw::GpuGen::G13 { + write_vtx_jp1!(Rv13); + let jp1 = |field: usize| 0x38 + field - offset_of!(Rv13, job_params1); + let mask_off = jp1(offset_of!(Rv13, job_params1.core_mask)); + put32(cmd, mask_off, p.core_masks[0]); + put32(cmd, mask_off + 4, p.core_masks[1]); + put32( + cmd, + jp1(offset_of!(Rv13, job_params1.tiling_control)), + p.tiling_control, + ); + put64( + cmd, + jp1(offset_of!(Rv13, job_params1.unk_f0)), + 0x1c + u64::from(crate::util::align(p.tile.meta1_blocks, 4)), + ); + } else { + write_vtx_jp1!(Rv); + } // Tiling parameters at 0x3bc (13.5 block), + the new word at +0x30. { let at = 0x3bc; @@ -618,140 +658,150 @@ pub(crate) fn encode_fragment( w32(cmd, offset_of!(Rf, isp_merge_upper_x), r.merge_upper_x); w32(cmd, offset_of!(Rf, isp_merge_upper_y), r.merge_upper_y); w64(cmd, offset_of!(Rf, tile_count), u64::from(p.tile.tiles)); - // Job parameters 1. - w32(cmd, offset_of!(Rf, job_params1.utile_config), utile_config); - w64( - cmd, - offset_of!(Rf, job_params1.bg.rsrc_spec), - r.background.resource_spec, - ); - w64( - cmd, - offset_of!(Rf, job_params1.bg.address), - u64::from(r.background.usc), - ); - w64( - cmd, - offset_of!(Rf, job_params1.ppp_multisamplectl), - r.multisample_control, - ); - w64( - cmd, - offset_of!(Rf, job_params1.isp_scissor_base), - r.scissor_base, - ); - w64( - cmd, - offset_of!(Rf, job_params1.isp_dbias_base), - r.depth_bias_base, - ); - w64( - cmd, - offset_of!(Rf, job_params1.isp_oclqry_base), - r.occlusion_query_base, - ); - for base in [ - offset_of!(Rf, job_params1.aux_fb_info), - offset_of!(Rf, job_params3.aux_fb_info), - ] { - w32(cmd, base, isp_ctl); - w32(cmd, base + 8, u32::from(r.width)); - w32(cmd, base + 0xc, u32::from(r.height)); - w64(cmd, base + 0x10, 0x10_0000); + // Job parameters 1 (13.5 G13 or G14 internal layout). + let g13 = p.gpu_gen == crate::hw::GpuGen::G13; + macro_rules! write_frag_jp1 { + ($R:ty) => {{ + w32(cmd, offset_of!($R, job_params1.utile_config), utile_config); + w64( + cmd, + offset_of!($R, job_params1.bg.rsrc_spec), + r.background.resource_spec, + ); + w64( + cmd, + offset_of!($R, job_params1.bg.address), + u64::from(r.background.usc), + ); + w64( + cmd, + offset_of!($R, job_params1.ppp_multisamplectl), + r.multisample_control, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_scissor_base), + r.scissor_base, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_dbias_base), + r.depth_bias_base, + ); + w64( + cmd, + offset_of!($R, job_params1.isp_oclqry_base), + r.occlusion_query_base, + ); + for base in [ + offset_of!($R, job_params1.aux_fb_info), + offset_of!($R, job_params3.aux_fb_info), + ] { + w32(cmd, base, isp_ctl); + w32(cmd, base + 8, u32::from(r.width)); + w32(cmd, base + 0xc, u32::from(r.height)); + w64(cmd, base + 0x10, 0x10_0000); + } + w64( + cmd, + offset_of!($R, job_params1.isp_zls_pixels), + u64::from(r.depth_dimensions), + ); + w64(cmd, offset_of!($R, job_params1.zls_ctrl), r.zls_control); + for (o, v) in [ + (offset_of!($R, job_params1.z_load), r.depth.base), + (offset_of!($R, job_params1.z_store), r.depth.base), + (offset_of!($R, job_params1.s_load), r.stencil.base), + (offset_of!($R, job_params1.s_store), r.stencil.base), + ( + offset_of!($R, job_params1.z_load_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!($R, job_params1.z_store_stride), + u64::from(r.depth.stride), + ), + ( + offset_of!($R, job_params1.s_load_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!($R, job_params1.s_store_stride), + u64::from(r.stencil.stride), + ), + ( + offset_of!($R, job_params1.z_load_comp), + r.depth.compression_base, + ), + ( + offset_of!($R, job_params1.z_load_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!($R, job_params1.z_store_comp), + r.depth.compression_base, + ), + ( + offset_of!($R, job_params1.z_store_comp_stride), + u64::from(r.depth.compression_stride), + ), + ( + offset_of!($R, job_params1.s_load_comp), + r.stencil.compression_base, + ), + ( + offset_of!($R, job_params1.s_load_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!($R, job_params1.s_store_comp), + r.stencil.compression_base, + ), + ( + offset_of!($R, job_params1.s_store_comp_stride), + u64::from(r.stencil.compression_stride), + ), + ( + offset_of!($R, job_params1.tvb_tilemap), + scene.tvb_tilemap_pointer().into(), + ), + ( + offset_of!($R, job_params1.tvb_layermeta), + scene.tvb_layermeta_pointer().into(), + ), + ( + offset_of!($R, job_params1.mtile_stride_dwords), + (4 * rgn_size) << 24, + ), + ( + offset_of!($R, job_params1.tvb_heapmeta), + scene.tvb_heapmeta_pointer().into(), + ), + (offset_of!($R, job_params1.tile_config), tile_config), + (offset_of!($R, job_params1.aux_fb), p.aux_fb.gpu_va().get()), + (offset_of!($R, job_params1.usc_exec_base_isp), p.usc), + (offset_of!($R, job_params1.unk_140), 0x8c60), + ( + offset_of!($R, job_params1.helper_arg), + r.fragment_helper.data, + ), + (offset_of!($R, job_params1.unk_158), 0x1c), + ] { + w64(cmd, o, v); + } + w32( + cmd, + offset_of!($R, job_params1.helper_program), + r.fragment_helper.binary, + ); + }}; } - w64( - cmd, - offset_of!(Rf, job_params1.isp_zls_pixels), - u64::from(r.depth_dimensions), - ); - w64(cmd, offset_of!(Rf, job_params1.zls_ctrl), r.zls_control); - w64(cmd, offset_of!(Rf, job_params1.unk_58_g14_0), 0x404_0404); - for (o, v) in [ - (offset_of!(Rf, job_params1.z_load), r.depth.base), - (offset_of!(Rf, job_params1.z_store), r.depth.base), - (offset_of!(Rf, job_params1.s_load), r.stencil.base), - (offset_of!(Rf, job_params1.s_store), r.stencil.base), - ( - offset_of!(Rf, job_params1.z_load_stride), - u64::from(r.depth.stride), - ), - ( - offset_of!(Rf, job_params1.z_store_stride), - u64::from(r.depth.stride), - ), - ( - offset_of!(Rf, job_params1.s_load_stride), - u64::from(r.stencil.stride), - ), - ( - offset_of!(Rf, job_params1.s_store_stride), - u64::from(r.stencil.stride), - ), - ( - offset_of!(Rf, job_params1.z_load_comp), - r.depth.compression_base, - ), - ( - offset_of!(Rf, job_params1.z_load_comp_stride), - u64::from(r.depth.compression_stride), - ), - ( - offset_of!(Rf, job_params1.z_store_comp), - r.depth.compression_base, - ), - ( - offset_of!(Rf, job_params1.z_store_comp_stride), - u64::from(r.depth.compression_stride), - ), - ( - offset_of!(Rf, job_params1.s_load_comp), - r.stencil.compression_base, - ), - ( - offset_of!(Rf, job_params1.s_load_comp_stride), - u64::from(r.stencil.compression_stride), - ), - ( - offset_of!(Rf, job_params1.s_store_comp), - r.stencil.compression_base, - ), - ( - offset_of!(Rf, job_params1.s_store_comp_stride), - u64::from(r.stencil.compression_stride), - ), - ( - offset_of!(Rf, job_params1.tvb_tilemap), - scene.tvb_tilemap_pointer().into(), - ), - ( - offset_of!(Rf, job_params1.tvb_layermeta), - scene.tvb_layermeta_pointer().into(), - ), - ( - offset_of!(Rf, job_params1.mtile_stride_dwords), - (4 * rgn_size) << 24, - ), - ( - offset_of!(Rf, job_params1.tvb_heapmeta), - scene.tvb_heapmeta_pointer().into(), - ), - (offset_of!(Rf, job_params1.tile_config), tile_config), - (offset_of!(Rf, job_params1.aux_fb), p.aux_fb.gpu_va().get()), - (offset_of!(Rf, job_params1.usc_exec_base_isp), p.usc), - (offset_of!(Rf, job_params1.unk_140), 0x8c60), - ( - offset_of!(Rf, job_params1.helper_arg), - r.fragment_helper.data, - ), - (offset_of!(Rf, job_params1.unk_158), 0x1c), - ] { - w64(cmd, o, v); + if g13 { + write_frag_jp1!(Rf13); + } else { + write_frag_jp1!(Rf); + w64(cmd, offset_of!(Rf, job_params1.unk_58_g14_0), 0x404_0404); } - w32( - cmd, - offset_of!(Rf, job_params1.helper_program), - r.fragment_helper.binary, - ); // Job parameters 2, + the new JP2+0x44 = buffer slot (cmd+0x40c). w32( cmd, @@ -793,7 +843,7 @@ pub(crate) fn encode_fragment( w32( cmd, offset_of!(Rf, job_params2.isp_bgobjvals), - r.stencil_clear, + if g13 { r.stencil_clear | 0x400 } else { r.stencil_clear }, ); w32(cmd, offset_of!(Rf, job_params2.unk_3c), 1); w32( @@ -833,7 +883,10 @@ pub(crate) fn encode_fragment( u64::from(r.partial_background.usc), ), (offset_of!(Rf, job_params3.zls_ctrl), r.zls_control), - (offset_of!(Rf, job_params3.unk_290), 0x404_0404), + ( + offset_of!(Rf, job_params3.unk_290), + if g13 { 0 } else { 0x404_0404 }, + ), (offset_of!(Rf, job_params3.z_load), r.depth.base), ( offset_of!(Rf, job_params3.z_partial_stride), diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index fc1514c61a8e44..5ced17fb2b9c0f 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -927,12 +927,14 @@ impl RootV27_2 { /// Builds the root, the boot job and every record they name. pub(crate) fn build(graph: &Arc, board: &BoardV27_2) -> Result> { let cfg = graph.cfg; + let g13 = cfg.gpu_gen == hw::GpuGen::G13; let pwr = &graph.dyncfg.pwr; let states = &pwr.perf_states; let id = &graph.dyncfg.id; // Inputs the controller below is built from, all from the DT and the ID registers. let [core_mask] = id.core_masks.as_slice() else { return Err(EINVAL); }; - if !pwr.power_zones.is_empty() || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 + if (!g13 && !pwr.power_zones.is_empty()) || pwr.power_zones.len() > 5 + || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) || pwr.power_sample_period == 0 || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period @@ -942,7 +944,7 @@ impl RootV27_2 { || states.windows(2).any(|s| s[1].pwr_mw <= s[0].pwr_mw || s[1].freq_hz <= s[0].freq_hz) || pwr.perf_base_pstate == 0 || pwr.perf_base_pstate as usize >= states.len() || core_mask.count_ones() != id.total_active_cores || id.total_active_cores == 0 - || cfg.shared3_tab.len() != 16 + || (!g13 && cfg.shared3_tab.len() != 16) || board.copy_bytes == 0 || board.sgx_size < 0xe14000 { return Err(EINVAL); } @@ -951,8 +953,16 @@ impl RootV27_2 { if sensors == 0 || sensors >> 32 != 0 || cfg.fast_sensor_mask_alt[0] != sensors { return Err(EINVAL); } - // The SRAM voltage of each operating point, published by the loader from the ADT. + // The SRAM voltage of each operating point: published by the loader from the ADT on G14, + // or derived from apple,min-sram-microvolt on G13 where the ADT has no perf-states-sram. let sram_table = Self::sram_table(states.len())?; + if !g13 && sram_table.is_none() { + return Err(EINVAL); + } + let min_sram_mv = pwr.min_sram_microvolt / 1000; + if sram_table.is_none() && min_sram_mv == 0 { + return Err(EINVAL); + } let mut alloc = graph.alloc(); graph.event_manager.sync_initial_stamps(); @@ -1052,45 +1062,66 @@ impl RootV27_2 { for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c].into_iter().enumerate() { put32(hw, chip + 4 * i, word); } - // From the power sample period to the fragment count, the 27.2 block keeps the 13.5 - // HwDataB words in order, at the chip id's distance: the firmware's power sampling - // period, the cache-flush and feature enables and the fragment count. - use core::mem::offset_of; - type Old = fw::initdata::raw::HwDataBG14V13_5; - let shift = chip - offset_of!(Old, chip_id); - for (at, value) in [ - (offset_of!(Old, power_sample_period), old.power_sample_period), - (offset_of!(Old, unk_49c), old.unk_49c), (offset_of!(Old, unk_4a0), old.unk_4a0), - (offset_of!(Old, unk_4a4), old.unk_4a4), (offset_of!(Old, unk_4c0), old.unk_4c0), - (offset_of!(Old, unk_4f0), old.unk_4f0), (offset_of!(Old, unk_4f4), old.unk_4f4), - (offset_of!(Old, unk_504), old.unk_504), (offset_of!(Old, unk_524), old.unk_524), - (offset_of!(Old, unk_534), old.unk_534), (offset_of!(Old, num_frags), old.num_frags), - ] { - put32(hw, at + shift, value); + if !g13 { + // From the power sample period to the fragment count, the 27.2 block keeps the 13.5 + // HwDataB words in order, at the chip id's distance: the firmware's power sampling + // period, the cache-flush and feature enables and the fragment count. + use core::mem::offset_of; + type Old = fw::initdata::raw::HwDataBG14V13_5; + let shift = chip - offset_of!(Old, chip_id); + for (at, value) in [ + (offset_of!(Old, power_sample_period), old.power_sample_period), + (offset_of!(Old, unk_49c), old.unk_49c), (offset_of!(Old, unk_4a0), old.unk_4a0), + (offset_of!(Old, unk_4a4), old.unk_4a4), (offset_of!(Old, unk_4c0), old.unk_4c0), + (offset_of!(Old, unk_4f0), old.unk_4f0), (offset_of!(Old, unk_4f4), old.unk_4f4), + (offset_of!(Old, unk_504), old.unk_504), (offset_of!(Old, unk_524), old.unk_524), + (offset_of!(Old, unk_534), old.unk_534), (offset_of!(Old, num_frags), old.num_frags), + ] { + put32(hw, at + shift, value); + } + put64(hw, offset_of!(Old, unk_4e0) + shift, old.unk_4e0.0); } - put64(hw, offset_of!(Old, unk_4e0) + shift, old.unk_4e0.0); }); - // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. - for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), - (0xffc, 1), (0x2724, 1), (0x2754, 1), - (0xfc4, 1), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), - (0x109c, 0), (0x1064, 0), (0x2728, 0)] { - put32(hw, offset as usize, value); - } - // Per-engine kick masks. The firmware gives an engine a kick slot only for bits set - // here, so an engine whose mask is left zero is never scheduled. The tiler takes one - // bit per cluster; the fragment and compute engines take one bit per configured core. - let low_bits = |n: u32| if n < 32 { (1u32 << n) - 1 } else { u32::MAX }; - put32(hw, 0x2668, low_bits(id.num_clusters)); - for offset in [0x266c, 0x2670] { - put32(hw, offset, low_bits(id.total_active_cores)); - } - // Firmware-managed operating points, CRE and event-assisted operating-point completion. - for offset in [0xfc0, 0x26b8, 0x1054] { - put32(hw, offset, 1); + if g13 { + // Inline words for G13G (T8103) firmware 27.2.1 (26B131): derived from the 13.5 + // configuration and the chip's register capabilities (no CRE on T8103). + for (at, v) in [ + (0xfc0, 1u32), (0xfe4, 1), (0xff4, pwr.power_sample_period), (0x1000, 1), (0x1004, 1), + (0x1020, 0x1f), (0x1050, 1), (0x1054, 1), (0x1068, 0x31), (0x1088, 1), + (0x10a4, id.num_frags * id.num_clusters), (0x10a8, 1), + (0x10cc, 0), (0x10d0, 0), + (0x2664, cfg.max_num_gps), (0x2668, 3), (0x266c, 7), (0x2670, 7), + (0x267c, 0), (0x2680, 0), (0x2684, id.total_active_cores), + (0x268c, 1), (0x26a8, 0xe_0000), + (0x26b0, 1), (0x26b4, 1), (0x26b8, 0), (0x26c0, 1), (0x26c4, 1), + (0x277c, 0x1_0000), (0x2780, 0x1_0000), + ] { + put32(hw, at, v); + } + hw[0x26d0..0x2700].fill(0xff); + } else { + // Inline words the stock host producer fixes for a gpu,t8112 node without model-slow. + for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), + (0xffc, 1), (0x2724, 1), (0x2754, 1), + (0xfc4, 1), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), + (0x109c, 0), (0x1064, 0), (0x2728, 0)] { + put32(hw, offset as usize, value); + } + // Per-engine kick masks. The firmware gives an engine a kick slot only for bits set + // here, so an engine whose mask is left zero is never scheduled. The tiler takes one + // bit per cluster; the fragment and compute engines take one bit per configured core. + let low_bits = |n: u32| if n < 32 { (1u32 << n) - 1 } else { u32::MAX }; + put32(hw, 0x2668, low_bits(id.num_clusters)); + for offset in [0x266c, 0x2670] { + put32(hw, offset, low_bits(id.total_active_cores)); + } + // Firmware-managed operating points, CRE and event-assisted operating-point completion. + for offset in [0xfc0, 0x26b8, 0x1054] { + put32(hw, offset, 1); + } + put64(hw, 0x267c, u64::from(*core_mask)); + put32(hw, 0x2684, id.total_active_cores); } - put64(hw, 0x267c, u64::from(*core_mask)); - put32(hw, 0x2684, id.total_active_cores); // Operating points, in the 13.5 HwDataB order the 27.2 block keeps: power above the // lowest state and frequency above the base state as f32 percentages, MHz, the per-lane // core and SRAM voltages, the chip's SRAM power coefficient per state and the identity @@ -1112,18 +1143,26 @@ impl RootV27_2 { } for (i, state) in states.iter().enumerate() { let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; - let (freq, voltage) = sram_table[i * 8..i * 8 + 8].split_at(4); - let sram_mv = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); - if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || sram_mv < *mv || sram_mv == 0 { - return Err(EINVAL); - } + let sram_mv = if let Some(table) = sram_table.as_ref() { + let (freq, voltage) = table[i * 8..i * 8 + 8].split_at(4); + let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz || value < *mv || value == 0 { + return Err(EINVAL); + } + value + } else { + (*mv).max(min_sram_mv) + }; let mhz = state.freq_hz / 1_000_000; put32(hw, abi::COMMON26_HW_PERF_FREQUENCY + i * 4, mhz); put32(hw, abi::COMMON26_HW_PERF_SCALE + i * 4, cfg.sram_k.to_bits()); + let sram_lanes = if g13 { 1 } else { abi::COMMON26_HW_PERF_LANES }; for lane in 0..abi::COMMON26_HW_PERF_LANES { let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE + lane * 4; put32(hw, abi::COMMON26_HW_PERF_CORE_VOLTAGE + row, *mv); - put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); + if lane < sram_lanes { + put32(hw, abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row, sram_mv); + } } } for index in 0..abi::COMMON26_HW_PERF_ROWS { @@ -1190,21 +1229,40 @@ impl RootV27_2 { for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); } - let ceiling = pwr.perf_max_pstate * 100; - for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling)] { - put32(data, at, value); - } - // The shared power tables the 13.5 InitData built from the chip configuration and - // the DT operating points (the G14 curves scale with each state's frequency and - // voltage). Left zero, the firmware runs the upper states without them. - base.hwdata_a.with(|a, _| { - put_shared1(data, GLOBALS_SHARED1, &a.hws1); - put_shared2(data, GLOBALS_SHARED2, &a.hws2); - }); put32(data, 0x6e, 1); - // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. - for (at, value) in g14_v27_2_abi::GLOBALS_PROGRESS { - put32(data, at, value); + let ceiling = pwr.perf_max_pstate * 100; + if g13 { + for (at, value) in [ + (0x24, 3000u32), (0x30, 1), (0x38, 1), (0x40, 120), + (0x60, 0x1_0000), (0x64, 0x1_0000), (0x68, 0x3_0000), (0x78, 1), + (0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling), + (0x128, u32::MAX), (0x18c, 0xffff), (0x1b4, 0x800), (0x1b8, 0x1555), + (0x1d0, u32::MAX), (0x1e8, u32::MAX), (0x6bc, 0xc0_0007), + (0x7ec, 1), (0x7f0, 1), (0x7f4, 100), (0x7f8, 100), + (0x990, 400_000), (0x998, 40), (0x99c, 10), (0x9a0, 250), (0x9a4, 1), + (0x9b8, 2), (0x9bc, 40), (0x9c0, 5), (0x9c8, 40), (0x9cc, 50), + (0x9d0, 1), (0x9d8, 50), (0xe08, 250), (0xe28, 3), (0xe2c, 1), + ] { + put32(data, at, value); + } + data[0xec..0x128].fill(0xff); + data[0x1bc..0x1d0].fill(0xff); + data[0x1dc..0x1e8].fill(0xff); + } else { + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), (0x8c, ceiling), (0x98, ceiling)] { + put32(data, at, value); + } + // The shared power tables the 13.5 InitData built from the chip configuration and + // the DT operating points (the G14 curves scale with each state's frequency and + // voltage). Left zero, the firmware runs the upper states without them. + base.hwdata_a.with(|a, _| { + put_shared1(data, GLOBALS_SHARED1, &a.hws1); + put_shared2(data, GLOBALS_SHARED2, &a.hws2); + }); + // The firmware's progress checks and compute watchdog, as M3 and M4 27.2 set them. + for (at, value) in g14_v27_2_abi::GLOBALS_PROGRESS { + put32(data, at, value); + } } crate::pgtable::clean_poc(data.as_ptr(), data.len()); } @@ -1226,28 +1284,61 @@ impl RootV27_2 { owners.push(alloc.gpu.array_empty::(0x4000)?, GFP_KERNEL)?; let mut power = alloc.shared.array_empty::(0x6a0)?; { - // Cold mirrors of the controller's power and temperature-loop values. - let gains = base.hwdata_a.with(|a, _| (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); let data = power.as_mut_slice(); - for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { - put32(data, at, value); - } - // The average-power filter and the third shared power table, as the 13.5 Globals - // carries them (built from the DT power values and the chip configuration). - graph.initdata.globals.with(|g, _| { + if g13 { + let period = pwr.power_sample_period; + let dt = crate::float::F32::from(period) / crate::f32!(1000.0); + let zone = pwr.power_zones.first(); for (at, value) in [ - (0x10, g.avg_power_filter_tc_periods), (0x14, g.avg_power_ki_dt.to_bits()), - (0x18, g.avg_power_kp.to_bits()), (0x1c, g.avg_power_min_duty_cycle), - (0x20, g.avg_power_target_filter_tc), + (0x0c, 0u32), + (0x10, pwr.avg_power_filter_tc_ms / period), + (0x14, (pwr.avg_power_ki_only * dt).to_bits()), + (0x18, pwr.avg_power_kp.to_bits()), + (0x1c, pwr.avg_power_min_duty_cycle), + (0x20, pwr.avg_power_target_filter_tc), + (0x24, zone.map_or(0, |z| z.target)), + (0x28, zone.map_or(0, |z| z.target.saturating_sub(z.target_offset))), + (0x2c, zone.map_or(0, |z| z.filter_tc)), + (0xc8, cfg.da.unk_8cc), + (0xcc, 8000), + (0xd0, cfg.da.unk_87c as u32), + (0xd8, pwr.fast_die0_proportional_gain.to_bits()), + (0xdc, (pwr.fast_die0_integral_gain * dt).to_bits()), + (0xf0, 9900), (0xf4, 200), + (0x108, crate::f32!(100.0).to_bits()), (0x10c, crate::f32!(400.0).to_bits()), + (0x110, 200), + (0x12c, pwr.max_power_mw), + (0x130, pwr.ppm_kp.to_bits()), + (0x134, (pwr.ppm_ki * dt).to_bits()), + (0x5e0, 1), (0x5e4, 0x1b), + (0x624, crate::f32!(15.0).to_bits()), (0x628, crate::f32!(5.0).to_bits()), + (0x62c, 32), (0x630, pwr.perf_max_pstate * 100), (0x640, 500), (0x68c, 1), ] { put32(data, at, value); } - put_shared3(data, POWER_SHARED3, &g.hws3); - }); - let initial = controller.as_slice(); - for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), - (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { - data[dst..dst + 4].copy_from_slice(&initial[src..src + 4]); + } else { + // Cold mirrors of the controller's power and temperature-loop values. + let gains = base.hwdata_a.with(|a, _| (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); + for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { + put32(data, at, value); + } + // The average-power filter and the third shared power table, as the 13.5 Globals + // carries them (built from the DT power values and the chip configuration). + graph.initdata.globals.with(|g, _| { + for (at, value) in [ + (0x10, g.avg_power_filter_tc_periods), (0x14, g.avg_power_ki_dt.to_bits()), + (0x18, g.avg_power_kp.to_bits()), (0x1c, g.avg_power_min_duty_cycle), + (0x20, g.avg_power_target_filter_tc), + ] { + put32(data, at, value); + } + put_shared3(data, POWER_SHARED3, &g.hws3); + }); + let initial = controller.as_slice(); + for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), + (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { + data[dst..dst + 4].copy_from_slice(&initial[src..src + 4]); + } } crate::pgtable::clean_poc(data.as_ptr(), data.len()); } @@ -1294,8 +1385,8 @@ impl RootV27_2 { } /// The loader's `adt-perf-states-sram` table under `/chosen/aurora-gpu-resources/sgx` - /// (frequency and SRAM millivolts per state). - fn sram_table(states: usize) -> Result> { + /// (frequency and SRAM millivolts per state), if present. + fn sram_table(states: usize) -> Result>> { let chosen = kernel::of::chosen().ok_or(ENODEV)?; let is = |name: Option>, want: &[u8]| { name.as_deref().is_some_and(|n| n.strip_suffix(b"\0").unwrap_or(n) == want) @@ -1304,14 +1395,15 @@ impl RootV27_2 { if !is(parent.get_opt_property::>(c"name")?, b"aurora-gpu-resources") { continue; } for child in parent.children() { if is(child.get_opt_property::>(c"name")?, b"sgx") { - let table = child.get_opt_property::>(c"adt-perf-states-sram")? - .ok_or(ENODEV)?; + let Some(table) = child.get_opt_property::>(c"adt-perf-states-sram")? else { + return Ok(None); + }; if table.len() != states * 8 { return Err(EINVAL); } - return Ok(table); + return Ok(Some(table)); } } } - Err(EINVAL) + Ok(None) } /// The power and thermal controller (directory +0x485): the 13.5 calibrated values of the @@ -1354,16 +1446,19 @@ impl RootV27_2 { put32(policy, at, value); } // Per-sensor corrections from the chip's coefficient tables (13.5 unk_coef_a/unk_coef_b), - // indexed from the first fast-die sensor id. A sensor without a coefficient refuses. + // indexed from the first fast-die sensor id. G13 carries no per-sensor coefficient tables; + // on chips that do, a sensor without a coefficient refuses. const FIRST_SENSOR: usize = 7; - let coef_a = cfg.unk_coef_a.first().ok_or(EINVAL)?; - let coef_b = cfg.unk_coef_b.first().ok_or(EINVAL)?; - for (at, coef) in [(0x2320, coef_a), (0x2420, coef_a), (0x2f38, coef_b), (0x3038, coef_b)] { - for sid in (0..64usize).filter(|sid| sensors & (1u64 << sid) != 0) { - let value = sid.checked_sub(FIRST_SENSOR).and_then(|index| coef.get(index)) - .ok_or(EINVAL)?; - put32(policy, at + 4 * sid, value.to_bits()); + if let (Some(coef_a), Some(coef_b)) = (cfg.unk_coef_a.first(), cfg.unk_coef_b.first()) { + for (at, coef) in [(0x2320, coef_a), (0x2420, coef_a), (0x2f38, coef_b), (0x3038, coef_b)] { + for sid in (0..64usize).filter(|sid| sensors & (1u64 << sid) != 0) { + let value = sid.checked_sub(FIRST_SENSOR).and_then(|index| coef.get(index)) + .ok_or(EINVAL)?; + put32(policy, at + 4 * sid, value.to_bits()); + } } + } else if cfg.gpu_gen != hw::GpuGen::G13 { + return Err(EINVAL); } put64(policy, 0x2f28, sensors); put32(policy, 0x3ba8, 1); diff --git a/drivers/gpu/drm/asahi/hw/t8103.rs b/drivers/gpu/drm/asahi/hw/t8103.rs index a2a76600c0a3bb..261e51fbc4c83f 100644 --- a/drivers/gpu/drm/asahi/hw/t8103.rs +++ b/drivers/gpu/drm/asahi/hw/t8103.rs @@ -91,3 +91,60 @@ pub(crate) const HWCONFIG: super::HwConfig = HwConfig { sram_base: None, sram_size: None, }; + +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +const fn reg( + slot: usize, + base: RegisterBaseV27_2, + size: u32, + relative: u64, + install: Option, +) -> RegisterV27_2 { + RegisterV27_2 { + slot, + base, + size, + relative, + install, + } +} + +/// The firmware 27.2 register table for T8103 (G13G). Writable windows outside SGX and the +/// PMP/PMGR telemetry apertures (slots 2 and 5) are left unmapped. +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const REGISTERS_V27_2: &[RegisterV27_2] = { + use RegisterBaseV27_2::{Physical, Sgx}; + &[ + reg(0, Physical(0x23b104000), 0x4000, 0, None), // AIC software interrupt + reg(1, Physical(0x23b2e8000), 0x1000, 0, Some(0)), // Analog temperature controller + reg(2, Physical(0x23bc00000), 0x1000, 0, Some(0)), // PMP doorbell + reg(3, Physical(0x200004000), 0x50000, 0, None), // Memory cache + reg(5, Physical(0x23b738000), 0x1000, 0, Some(0)), // PMGR scratch / PMP telemetry + reg(12, Physical(0x26b45c000), 0x4000, 0, None), // ANE doorbell + reg(17, Sgx(0), 0x20000, 0, Some(0)), // GPU core + reg(31, Sgx(0xd04000), 0xc000, 0xd04000, Some(0)), // Fender configuration + reg(32, Sgx(0xd61000), 0x1000, 0xd61000, Some(0)), // GIFAF + reg(34, Sgx(0xd10000), 0x4000, 0xd10000, Some(0)), // CPMS + reg(37, Sgx(0xe10000), 0x1000, 0xe10000, Some(0)), // Fender scratch RAM + reg(38, Sgx(0xd18000), 0x4000, 0xd18000, Some(0)), // Fender clock/power + reg(40, Sgx(0xd00000), 0x4000, 0xd00000, Some(0)), // Fender multi-GPU configuration + reg(44, Sgx(0xd80000), 0x5000, 0, Some(0)), // Metrology sensors + ] +}; + +/// Slots of the T8103 27.2 register table whose stock mode is read-write (no slot 9 telemetry). +#[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] +pub(crate) const WRITABLE_V27_2: u64 = { + let mut mask = 0u64; + let mut slot = 0; + while slot < 60 { + if matches!( + slot, + 0 | 2 | 3 | 5..=8 | 12 | 17 | 25..=27 | 31..=40 | 42..=48 | 52..=55 | 58 + ) { + mask |= 1 << slot; + } + slot += 1; + } + mask +}; From 5a055fcec42786f85f2b31b286ae1a0e485536ea Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 12:03:21 -0500 Subject: [PATCH 1368/1514] selftests: asahi-m4: mock backend feature flags The shared feature_flags() now reads backend-specific feature bits. Return zero from the soft-faults mock so the host test can compile the shared implementation and check the G16 fault_control opt-out. Signed-off-by: Diljit Singh --- tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py index 0aa956ee2d8cde..38bcec27ce8879 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-uapi.py @@ -36,6 +36,7 @@ def item(text, declaration): } pub struct QueueLimits; trait Backend { + fn backend_feature_flags(&self) -> u64 { 0 } fn supports_vm_status(&self) -> bool { false } fn queue_limits(&self) -> Option { None } __SHARED__ From baf523ed93a3c70f3b263c24a48fcc0ddd452ffd Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:15:46 -0500 Subject: [PATCH 1369/1514] drm/asahi: g14_v27_2: populate the GPU power controller parameters RootV27_2::controller() seeded the power-controller output at +0xa48 to max_state and relocated pwr_min_duty_cycle to +0xa00, but left the power controller's own parameter block (+0x9c8..+0xa14) zero. While the GPU stays powered, +0xa48 keeps its initial max_state value. Once the GPU powers off for at least two 8 ms power-sample periods (such as across deep sleep or an idle power-off), the firmware's power-up replay recomputes +0xa48 from +0xa08, +0xa04, and the controller gains. With +0xa04 and +0xa08 zero, +0xa48 clamps to 0, driving the overall performance target (+0x50) to 0 (reason 1) and forcing the firmware into below-minimum-pstate duty-gating on an 8 ms cadence (~26x slowdown). Populate +0x9c8..+0xa14 from the board's calibrated 13.5 hwdata_a parameters (derived from device tree) and reject a zero pwr_filter_time_constant in RootV27_2::build(). Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/gpu/v27_2.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 5ced17fb2b9c0f..0a29bf2d36fc4f 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -937,6 +937,7 @@ impl RootV27_2 { || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) || pwr.power_sample_period == 0 + || pwr.pwr_filter_time_constant == 0 || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period || pwr.avg_power_filter_tc_ms < pwr.power_sample_period || pwr.avg_power_target_filter_tc == 0 @@ -1486,13 +1487,27 @@ impl RootV27_2 { // differ. No power zones. let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; let fields = base.hwdata_a.with(|a, _| [ - (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), + (0x50, 100), + // Power controller (reason 1): populated from the 13.5 calibrated values so long + // power-off replays (e.g. deep sleep or idle-off) keep the limiter calibrated. + (0x9c8, a.unk_64c), + (0x9d4, a.pwr_filter_a_neg.to_bits()), + (0x9dc, a.pwr_filter_a.to_bits()), + (0x9e4, a.pwr_integral_gain.to_bits()), + (0x9ec, a.pwr_integral_min_clamp.to_bits()), + (0x9f0, a.max_power_1.to_bits()), + (0x9f4, a.pwr_proportional_gain.to_bits()), + (0x9fc, a.pwr_pstate_related_k.to_bits()), + (0xa04, max_state), + (0xa08, a.max_pstate_scaled_2), + (0xa14, a.max_power_2), + (0xa48, max_state), + (0xa80, a.ppm_filter_tc_periods_x4), (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), - (0xa48, max_state), (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), From f03b064ad184c296f83269484ae80309b89c043e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:15:46 -0500 Subject: [PATCH 1370/1514] drm/asahi: g14_v27_2: support deep sleep warm restart Allow the G13/G14 firmware 27.2 backend to participate in firmware-driven deep sleep (S2R) via commit-time coprocessor stop and warm restart: - In driver.rs, pass pm_suspend_via_firmware() into backend.sleep_prepare() instead of unconditionally refusing deep sleep with -EBUSY. - In g14_v27_2.rs, map the Fender operating-point page alongside the ASC control page, drain pending work and worker queues during deep sleep prepare, switch the firmware idle policy to allow-off, and register a commit-time stop callback (apple_sleep_coproc_register_first) that runs apple_rtkit_sleep_idle_polled(), disables mailbox receive, and clears ASC_RUN only after all sleep refusals have passed. - In sleep_complete(), restore keep-powered if the sleep was refused before commit; after a real firmware-driven wake, warm-restart RTKit (apple_rtkit_warm_restart), re-assert ASC_RUN, re-boot RTKit, restore keep-powered, and wait for the Fender operating point to report powered. - In gpu/v27_2.rs, add PoC cache maintenance to drain() and firmware_running(), enable the G13 sleep/wake and RTKit power-callback inline words, remove the stale zeroing of +0x10cc/+0x10d0 that clobbered uat_ttb_base, add compile-time offset assertions before 0xfc0, and populate the warm-restart wake operands (+0x9c..+0xa8). Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/driver.rs | 9 +- drivers/gpu/drm/asahi/g14_v27_2.rs | 301 ++++++++++++++++++++++++++--- drivers/gpu/drm/asahi/gpu/v27_2.rs | 23 ++- 3 files changed, 298 insertions(+), 35 deletions(-) diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 0a44479f7b3c83..2483f4da0468b0 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -273,16 +273,11 @@ unsafe fn sleep_data<'a>(dev: *mut bindings::device) -> &'a AsahiPlatformDriverD unsafe extern "C" fn sleep_prepare(dev: *mut bindings::device) -> core::ffi::c_int { // SAFETY: Called by the PM core. let data = unsafe { sleep_data(dev) }; - // G14 on firmware 27.2: the firmware keeps running through suspend-to-idle, with nothing in - // flight; a sleep that powers the SoC down would lose it, and it has no cold restart, so that - // is refused. #[cfg(CONFIG_DRM_ASAHI_G14_V27_2)] if let Some(backend) = data.g14_v27_2.as_ref() { // SAFETY: Reads a global flag word. - if unsafe { bindings::pm_suspend_via_firmware() } { - return EBUSY.to_errno(); - } - return kernel::error::from_result(|| backend.sleep_prepare().map(|_| 0)); + let deep = unsafe { bindings::pm_suspend_via_firmware() }; + return kernel::error::from_result(|| backend.sleep_prepare(deep).map(|_| 0)); } // SAFETY: Reads a global flag word. if !unsafe { bindings::pm_suspend_via_firmware() } { diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index a9b9477d05ee97..3c28823479e7b4 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -48,6 +48,54 @@ const EP_DOORBELL: u8 = 0x21; const ASC_CPU_CONTROL: usize = 0x44; const ASC_RUN: u32 = 0x10; +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" { + fn apple_sleep_commit_stops_coprocs() -> bool; + fn apple_sleep_coproc_register_first( + dev: *mut core::ffi::c_void, + last_stop: Option core::ffi::c_int>, + data: *mut core::ffi::c_void, + ) -> core::ffi::c_int; + fn apple_sleep_coproc_set_ready(dev: *mut core::ffi::c_void, ready: bool); + fn apple_sleep_coproc_stopped(dev: *mut core::ffi::c_void) -> bool; + fn apple_sleep_coproc_unregister(dev: *mut core::ffi::c_void); +} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +struct CommitStop { + rtk: *mut kernel::bindings::apple_rtkit, + asc_ctl: *mut u8, + ran: bool, + idle_ret: core::ffi::c_int, + idle_us: u32, +} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +// SAFETY: Owned by `State` under `Runtime::state`; read and written in the commit callback with +// interrupts off on the single boot CPU. +unsafe impl Send for CommitStop {} + +#[cfg(CONFIG_APPLE_SOC_SLEEP)] +unsafe extern "C" fn g14_v27_2_commit_stop(data: *mut core::ffi::c_void) -> core::ffi::c_int { + // SAFETY: `data` points to the heap-allocated `CommitStop` owned by `State::commit_stop` + // until `sleep_complete` (or `stop`) unregisters this callback. + let c = unsafe { &mut *data.cast::() }; + c.ran = true; + // SAFETY: `rtk` and `asc_ctl` remain mapped and live for the boot; runs at commit time with + // interrupts off and all refusals behind it. + unsafe { + c.idle_ret = kernel::bindings::apple_rtkit_sleep_idle_polled( + c.rtk, + c.asc_ctl.cast(), + &mut c.idle_us, + ); + kernel::bindings::apple_rtkit_mailbox_recv_off(c.rtk); + let ctl = kernel::bindings::readl(c.asc_ctl.cast()); + kernel::bindings::writel(ctl & !ASC_RUN, c.asc_ctl.cast()); + } + c.idle_ret +} + /// Commands slower than this are a hang; the firmware state is then not trusted. const COMMAND_TIMEOUT_MS: i64 = 5000; /// How long `stop` lets published work retire before it fails what is left. @@ -82,21 +130,28 @@ impl FirmwareWait { } } -/// The ASC control page, kept mapped until the firmware is stopped. -pub(crate) struct AscControl(*mut u8); -// SAFETY: a device register page; accesses are single 32-bit MMIO operations. +/// The ASC control page and Fender operating-point page, kept mapped until the firmware is stopped. +pub(crate) struct AscControl(*mut u8, *mut u8); +// SAFETY: device register pages; accesses are single 32-bit MMIO operations. unsafe impl Send for AscControl {} // SAFETY: as above. unsafe impl Sync for AscControl {} impl AscControl { - fn new(phys: u64) -> Result { + fn new(phys: u64, sgx: u64) -> Result { // SAFETY: `phys` is the ASC register window of this platform device. Apple SoC fabrics // require non-posted MMIO (`nonposted-mmio`); a posted write to ASC_CPU_CONTROL resets // T8103 immediately. let ptr = unsafe { kernel::bindings::ioremap_np(phys, 0x4000) }; if ptr.is_null() { return Err(ENOMEM); } - Ok(Self(ptr.cast())) + // SAFETY: `sgx + 0xd01000` is the Fender operating-point register inside the SGX window. + let fender = unsafe { kernel::bindings::ioremap_np(sgx + 0xd01000, 0x1000) }; + if fender.is_null() { + // SAFETY: mapped above. + unsafe { kernel::bindings::iounmap(ptr) }; + return Err(ENOMEM); + } + Ok(Self(ptr.cast(), fender.cast())) } fn read(&self, at: usize) -> u32 { // SAFETY: `at` is a register offset inside the mapped page. @@ -106,6 +161,10 @@ impl AscControl { // SAFETY: as above. unsafe { kernel::bindings::writel(value, self.0.add(at).cast()) } } + fn fender(&self) -> u32 { + // SAFETY: mapped Fender register page. + unsafe { kernel::bindings::readl(self.1.cast()) } + } /// Clears the ASC run bit. fn halt(&self) { self.write(ASC_CPU_CONTROL, self.read(ASC_CPU_CONTROL) & !ASC_RUN); @@ -115,10 +174,18 @@ impl AscControl { impl Drop for AscControl { fn drop(&mut self) { // SAFETY: mapped in `new`, unmapped once. - unsafe { kernel::bindings::iounmap(self.0.cast()) } + unsafe { + kernel::bindings::iounmap(self.1.cast()); + kernel::bindings::iounmap(self.0.cast()); + } } } +/// Whether a Fender word says the GPU is powered: a nonzero index and no request pending. +fn gpu_powered(fender: u32) -> bool { + fender & 0x10 == 0 && fender & 0xf != 0 +} + /// The GPU MMU fault status, read when a command times out: a pending fault names the faulting /// address and unit, an empty status says the work stalled without a page fault. struct FaultStatus { @@ -193,14 +260,16 @@ impl Notify { /// Queues one service run if a runtime is attached. A run already queued covers this one. fn wake(&self) { if let Some(runtime) = self.runtime.lock().as_ref() { - let _ = runtime.queue.enqueue::, 0>(runtime.clone()); + if !runtime.deep_sleeping.load(Ordering::Acquire) { + let _ = runtime.queue.enqueue::, 0>(runtime.clone()); + } } } /// Queues a poll while attached. Detaching also fences off poll requests before teardown. fn retry(&self) { if let Some(runtime) = self.runtime.lock().as_ref() { - if runtime.healthy() { + if runtime.healthy() && !runtime.deep_sleeping.load(Ordering::Acquire) { let _ = runtime.queue.enqueue_delayed::, RETRY_WORK>( runtime.clone(), msecs_to_jiffies(RESOURCE_RETRY_MS), ); @@ -316,7 +385,8 @@ pub(crate) fn start<'a>( let dev: &device::Device = pdev.as_ref(); let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?; - let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?; + let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start(), sgx.start())?; let control = asc.read(ASC_CPU_CONTROL); if control & ASC_RUN != 0 { return Err(EBUSY); } let notify = Notify::new(dev)?; @@ -324,7 +394,6 @@ pub(crate) fn start<'a>( rtkit::RtKit::::new(dev, None, 0, notify.clone())?, GFP_KERNEL)?; let resources = crate::regs::Resources::new(pdev)?; - let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; let fault = FaultStatus::new(sgx.start(), cfg)?; let copy_bytes: u32 = dev.fwnode().ok_or(ENODEV)? .property_read(c"apple,coredump-copy-buffer").required_by(dev)?; @@ -452,6 +521,8 @@ struct State { accepting: bool, submitted: u64, retired: u64, + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + commit_stop: Option>, } impl State { @@ -498,6 +569,9 @@ pub(crate) struct Runtime { /// Set between [`Runtime::sleep_prepare`] and [`Runtime::sleep_complete`]: nothing is /// published across a system sleep. asleep: AtomicBool, + /// Set across a firmware-driven deep sleep once workers are drained and the commit stop + /// is armed; prevents workers from touching the stopped firmware or mailbox. + deep_sleeping: AtomicBool, notify: Arc, /// Runs the service. Only `Notify` queues on it, and `stop` drains it. queue: OwnedQueue, @@ -961,17 +1035,19 @@ impl Runtime { self.pump(state); } - /// Before a suspend-to-idle: holds new publications and lets published work retire, so the - /// sleep starts with nothing in flight. The firmware keeps running with its keep-powered - /// policy: its GPU power domain is kept through the sleep (`apple,sleep-retained`), and the - /// ASC, its memory and the root stay as they are. Refuses the sleep (EBUSY) if published work - /// does not retire within the stop drain time. + /// Before a system sleep: holds new publications and lets published work retire. /// - /// The firmware's own power-off handshake (idle policy allow-off, then keep-powered again - /// after the wake) is not used: on phellos the firmware crashed in the wake that followed it. - pub(crate) fn sleep_prepare(&self) -> Result { + /// For suspend-to-idle (`!deep`), the firmware keeps running with its keep-powered policy + /// (`apple,sleep-retained`). For a firmware-driven deep sleep (`deep`), workers are drained, + /// idle power-off is permitted, and a commit-time stop is registered with the SoC sleep + /// driver so the firmware is idled and halted only after all refusals have passed, then + /// warm-restarted in [`sleep_complete`]. + pub(crate) fn sleep_prepare(&self, deep: bool) -> Result { let mut guard = self.state.lock(); if !self.healthy() || guard.is_none() { return Ok(()); } + if self.deep_sleeping.load(Ordering::Acquire) { + return Err(EBUSY); + } // Hold publications first, then let what is published retire. User space is frozen by // now; only the scheduler's queued jobs can still arrive, and they wait in `pending`. self.asleep.store(true, Ordering::Release); @@ -980,9 +1056,7 @@ impl Runtime { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } if !state.running() { - dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", - state.submitted, state.retired, state.pending.len()); - return Ok(()); + break; } if remaining == 0 { dev_err!(self.dev, "GPU: sleep refused, {} compute commands and {} render pairs still running\n", @@ -996,13 +1070,184 @@ impl Runtime { _ => 0, }; } + if !deep { + if let Some(state) = Option::as_ref(&*guard) { + dev_info!(self.dev, "GPU held for sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + } + return Ok(()); + } + #[cfg(not(CONFIG_APPLE_SOC_SLEEP))] + { + if let Some(state) = Option::as_mut(&mut *guard) { + self.asleep.store(false, Ordering::Release); + self.pump(state); + } + return Err(EBUSY); + } + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + { + // SAFETY: Reads global sleep-driver availability and suspend mode. + if !unsafe { apple_sleep_commit_stops_coprocs() } { + if let Some(state) = Option::as_mut(&mut *guard) { + self.asleep.store(false, Ordering::Release); + self.pump(state); + } + return Err(EBUSY); + } + self.deep_sleeping.store(true, Ordering::Release); + drop(guard); + // Flush any queued retry or service work; `deep_sleeping` keeps new work out. + // SAFETY: `self.retry` is an initialized, pinned delayed work item. + unsafe { + let work = Work::raw_get(DelayedWork::raw_as_work(&self.retry)); + let delayed = kernel::container_of!(work, kernel::bindings::delayed_work, work); + kernel::bindings::flush_delayed_work(delayed); + } + self.queue.drain(); + + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { + self.deep_sleeping.store(false, Ordering::Release); + return Ok(()); + }; + if !self.healthy() || state.running() { + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(EBUSY); + } + if let Err(err) = set_idle_policy(&state.root, &mut state.peer, true) { + dev_err!(self.dev, "GPU: deep sleep refused, allow-off failed: {:?}\n", err); + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(err); + } + let _ = wait(&state.root, 200, || { + Ok(state.root.firmware_running()? == 0 || state.asc.fender() & 0xf == 0) + }); + // SAFETY: `ASC_CPU_CONTROL` lies within the mapped ASC page. + let asc_ctl = unsafe { state.asc.0.add(ASC_CPU_CONTROL) }; + let commit = match KBox::new(CommitStop { + rtk: state.peer.as_raw(), + asc_ctl, + ran: false, + idle_ret: 0, + idle_us: 0, + }, GFP_KERNEL) { + Ok(c) => c, + Err(err) => { + let _ = set_idle_policy(&state.root, &mut state.peer, false); + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(err.into()); + } + }; + state.commit_stop = Some(commit); + let data = state.commit_stop.as_deref_mut().map_or(core::ptr::null_mut(), |c| { + core::ptr::from_mut(c).cast::() + }); + // SAFETY: `dev` is the live GPU device; `data` points to `state.commit_stop` which + // remains allocated at the same address until unregistered in `sleep_complete`/`stop`. + let ret = unsafe { + apple_sleep_coproc_register_first( + self.dev.as_raw().cast(), + Some(g14_v27_2_commit_stop), + data, + ) + }; + if ret != 0 { + state.commit_stop = None; + let _ = set_idle_policy(&state.root, &mut state.peer, false); + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + self.pump(state); + return Err(Error::from_errno(ret)); + } + // SAFETY: `dev` was just registered above. + unsafe { apple_sleep_coproc_set_ready(self.dev.as_raw().cast(), true) }; + dev_info!(self.dev, "GPU prepared for deep sleep: submitted={} completed={} pending={}\n", + state.submitted, state.retired, state.pending.len()); + Ok(()) + } } - /// After the sleep: publishes the work held during it. + /// After the sleep: warm-restarts the firmware after a real deep sleep, then publishes held work. pub(crate) fn sleep_complete(&self) { let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + return; + }; + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + if let Some(commit) = state.commit_stop.take() { + // SAFETY: `dev` was registered in `sleep_prepare`. + let stopped = commit.ran + || unsafe { apple_sleep_coproc_stopped(self.dev.as_raw().cast()) }; + // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`. + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw().cast()) }; + // SAFETY: Reads a global flag word. + let real = unsafe { kernel::bindings::pm_resume_via_firmware() }; + if !stopped && !real { + dev_info!(self.dev, "GPU: deep sleep refused before commit; restoring keep-powered\n"); + if let Err(err) = set_idle_policy(&state.root, &mut state.peer, false) { + dev_err!(self.dev, "GPU: failed to restore keep-powered policy: {:?}\n", err); + self.fail_all(state, err); + } + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + state.waiting_unlink = None; + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + return; + } + if !real { + dev_warn!(self.dev, "GPU: sleep refused after commit stop; firmware stays stopped\n"); + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + self.fail_all(state, EIO); + return; + } + let started = Instant::::now(); + let ctl_before = state.asc.read(ASC_CPU_CONTROL); + let restart = (|| -> Result { + // SAFETY: `peer` is live and the firmware was stopped at the commit. + kernel::error::to_result(unsafe { + kernel::bindings::apple_rtkit_warm_restart(state.peer.as_raw()) + })?; + state.asc.write(ASC_CPU_CONTROL, ctl_before | ASC_RUN); + state.peer.as_mut().boot()?; + set_idle_policy(&state.root, &mut state.peer, false)?; + wait(&state.root, 500, || Ok(gpu_powered(state.asc.fender()))) + })(); + self.deep_sleeping.store(false, Ordering::Release); + self.asleep.store(false, Ordering::Release); + state.waiting_unlink = None; + state.waiting_control = None; + match restart { + Ok(()) => { + dev_info!(self.dev, "GPU firmware 27.2 back in {} us (commit idle={} {} us, pending={})\n", + started.elapsed().as_micros_ceil(), commit.idle_ret, commit.idle_us, + state.pending.len()); + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + } + Err(err) => { + dev_err!(self.dev, "GPU firmware 27.2 warm restart failed: {:?} (crashed={})\n", + err, state.peer.is_crashed()); + self.fail_all(state, err); + } + } + return; + } if !self.asleep.swap(false, Ordering::AcqRel) { return; } - let Some(state) = Option::as_mut(&mut *guard) else { return; }; dev_info!(self.dev, "GPU released after sleep: running={:?} pending={}\n", state.root.firmware_running(), state.pending.len()); state.waiting_unlink = None; @@ -1038,6 +1283,11 @@ impl Runtime { self.queue.drain(); let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + if state.commit_stop.take().is_some() { + // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`. + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw().cast()) }; + } self.fail_all(&mut state, ENODEV); let allowed = set_idle_policy(&state.root, &mut state.peer, true); let root = &state.root; @@ -1103,6 +1353,7 @@ impl Backend { graph: runtime_graph, healthy: AtomicBool::new(true), asleep: AtomicBool::new(false), + deep_sleeping: AtomicBool::new(false), notify: runtime_notify, queue, state <- new_mutex!(None, "g14_v27_2::Runtime::state"), @@ -1154,6 +1405,8 @@ impl Backend { accepting: true, submitted: 0, retired: 0, + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + commit_stop: None, }); // From here the firmware's messages run the service; one run consumes anything it // published before. @@ -1177,7 +1430,7 @@ impl Backend { } pub(crate) fn stop(&self) { self.runtime.stop(); } - pub(crate) fn sleep_prepare(&self) -> Result { self.runtime.sleep_prepare() } + pub(crate) fn sleep_prepare(&self, deep: bool) -> Result { self.runtime.sleep_prepare(deep) } pub(crate) fn sleep_complete(&self) { self.runtime.sleep_complete() } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 0a29bf2d36fc4f..0d1df040d11dc5 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -854,10 +854,13 @@ impl RootV27_2 { /// Drain the telemetry rings. The event ring is consumed separately after servicing each event. pub(crate) fn drain(&self) -> Result { let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { + crate::pgtable::clean_invalidate_poc(state.as_slice()[base..].as_ptr(), 0x30); + crate::pgtable::poc_barrier(); let write = Self::word(state, base + 0x20)?; let read = state.shared_index(base)?; if write < records && read.load(Ordering::Acquire) != write { read.store(write, Ordering::Release); + crate::pgtable::clean_poc(state.as_slice()[base..].as_ptr(), 4); crate::pgtable::poc_barrier(); } Ok(()) @@ -877,6 +880,8 @@ impl RootV27_2 { /// Shared status +0x10: nonzero while the firmware reports itself running. pub(crate) fn firmware_running(&self) -> Result { + crate::pgtable::clean_invalidate_poc(self.status.as_slice().as_ptr(), 0x20); + crate::pgtable::poc_barrier(); Self::word(&self.status, 0x10) } @@ -1044,6 +1049,8 @@ impl RootV27_2 { } register_mappings.push(page, GFP_KERNEL)?; } + const _: () = assert!(core::mem::offset_of!(Hw, coredump_copy_buffer_size) + 8 <= 0xfc0); + const _: () = assert!(core::mem::offset_of!(Hw, chip_id) + 16 <= 0xfc0); let dump = core::mem::offset_of!(Hw, coredump_copy_buffer_size); put64(hw, dump, u64::from(board.copy_bytes)); base.hwdata_b.with(|old, _| { @@ -1087,10 +1094,11 @@ impl RootV27_2 { // Inline words for G13G (T8103) firmware 27.2.1 (26B131): derived from the 13.5 // configuration and the chip's register capabilities (no CRE on T8103). for (at, v) in [ - (0xfc0, 1u32), (0xfe4, 1), (0xff4, pwr.power_sample_period), (0x1000, 1), (0x1004, 1), + // Sleep/wake handler and RTKit power callback enables matching G14. + (0xfc0, 1u32), (0xfc4, 1), (0xfd8, 1), (0xfdc, 1), (0xfe4, 1), (0xfec, 24000), + (0xff0, 1), (0xff4, pwr.power_sample_period), (0xffc, 1), (0x1000, 1), (0x1004, 1), (0x1020, 0x1f), (0x1050, 1), (0x1054, 1), (0x1068, 0x31), (0x1088, 1), (0x10a4, id.num_frags * id.num_clusters), (0x10a8, 1), - (0x10cc, 0), (0x10d0, 0), (0x2664, cfg.max_num_gps), (0x2668, 3), (0x266c, 7), (0x2670, 7), (0x267c, 0), (0x2680, 0), (0x2684, id.total_active_cores), (0x268c, 1), (0x26a8, 0xe_0000), @@ -1466,8 +1474,15 @@ impl RootV27_2 { for (word, value) in policy[0x62b8..0x62f8].chunks_exact_mut(4).zip(cfg.shared3_tab) { word.copy_from_slice(&value.to_le_bytes()); } - // Cold-wake operand: the board's base operating point. - put32(policy, 0xa4, pwr.perf_base_pstate); + // Warm-restart operands: base operating point and wake flags. + for (at, value) in [ + (0x9c, 1), + (0xa0, 1), + (0xa4, pwr.perf_base_pstate), + (0xa8, 1), + ] { + put32(policy, at, value); + } for (source, bits) in [ (4, pwr.pwr_sample_period_aic_clks), (8, pwr.pwr_sample_period_aic_clks), From 3bdddf1caa53de26221368e96911cd879cb8181a Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 12:07:37 -0500 Subject: [PATCH 1371/1514] soc: apple: sleep: export apple_sleep_coproc_wake_error() Track per-coprocessor platform wake errors on apple_sleep_coproc (reset alongside stop_ret when readied) and export apple_sleep_coproc_wake_error() so coprocessor drivers can check whether their power domain and fabric restored cleanly after a deep-sleep wake before touching MMIO or RTKit. Signed-off-by: Erik Bourget --- drivers/soc/apple/sleep.c | 13 +++++++++++++ include/linux/soc/apple/sleep.h | 8 ++++++++ 2 files changed, 21 insertions(+) diff --git a/drivers/soc/apple/sleep.c b/drivers/soc/apple/sleep.c index 7f93efef9ec5a0..8e877b6bbf7b16 100644 --- a/drivers/soc/apple/sleep.c +++ b/drivers/soc/apple/sleep.c @@ -377,6 +377,7 @@ static struct apple_sleep_coproc { bool stopped; u32 status; int stop_ret; + int wake_err; /* No ASC: its last stop takes it whole, power word @ps included, before the others. */ bool first; /* Between ANS and the others, whatever order they registered in. */ @@ -1640,6 +1641,8 @@ void apple_sleep_coproc_set_ready(struct device *dev, bool ready) return; c->ready = ready; c->stopped = false; + c->stop_ret = 0; + c->wake_err = 0; } EXPORT_SYMBOL_GPL(apple_sleep_coproc_set_ready); @@ -1653,6 +1656,16 @@ bool apple_sleep_coproc_stopped(struct device *dev) } EXPORT_SYMBOL_GPL(apple_sleep_coproc_stopped); +int apple_sleep_coproc_wake_error(struct device *dev) +{ + struct apple_sleep_coproc *c; + + guard(mutex)(&apple_sleep_coprocs_lock); + c = apple_sleep_coproc_find(dev); + return c ? c->wake_err : -ENODEV; +} +EXPORT_SYMBOL_GPL(apple_sleep_coproc_wake_error); + static bool apple_sleep_external_commit; void apple_sleep_set_commit_stops_coprocs(bool enable) diff --git a/include/linux/soc/apple/sleep.h b/include/linux/soc/apple/sleep.h index d2642a9c8ffb43..50eb9fb5e3eb30 100644 --- a/include/linux/soc/apple/sleep.h +++ b/include/linux/soc/apple/sleep.h @@ -144,6 +144,9 @@ void apple_sleep_coproc_set_early(struct device *dev); /* Whether the last step stopped it: after a refused sleep, false means it still runs. */ bool apple_sleep_coproc_stopped(struct device *dev); +/* Platform wake error for a stopped coprocessor (0 if its power domain and fabric restored). */ +int apple_sleep_coproc_wake_error(struct device *dev); + /* * Whether this sleep's commit stops the registered coprocessors. Then one that can't be * registered refuses the sleep: stopped any earlier, a later refusal would strand it. @@ -371,6 +374,11 @@ static inline bool apple_sleep_coproc_stopped(struct device *dev) return false; } +static inline int apple_sleep_coproc_wake_error(struct device *dev) +{ + return -ENODEV; +} + static inline void apple_sleep_note_sub(u8 step) {} static inline void apple_sleep_set_commit_stops_coprocs(bool enable) From 33239c32c0b3fb6fa4cc2138d3adfc3c55df59e1 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:31:00 -0500 Subject: [PATCH 1372/1514] drm/asahi: g14_v27_2: harden deep-sleep prepare, rollback, and DT power gating Address deep-sleep concurrency, rollback, and DT calibration invariants: - Track whether all four GPU power-controller tuning properties were explicitly supplied by the machine's DT/ADT (pwr_controller_from_dt) in PwrConfig::load(). Only populate the 27.2 power controller (+0x9c8..+0xa14) and allow deep sleep when those properties are present, avoiding fallback coefficients on boards whose DT omits them. - Synchronize deep_sleeping toggles under Notify::runtime's spinlock so no RTKit notification or retry can race queue.drain(). - Track whether an allow-off idle-policy record was published during sleep_prepare(), confirm keep-powered rollback before reopening submissions (failing the backend if rollback cannot be confirmed), and require Fender to report powered-off with no request pending (0x1f == 0) before arming commit stop. - In g14_v27_2_commit_stop(), return immediately without clearing ASC_RUN if RTKit idle fails. In sleep_complete(), check commit.idle_ret and apple_sleep_coproc_wake_error() before touching ASC or RTKit. - Hold CommitStop alive across apple_sleep_coproc_unregister() in stop(), use typed *mut bindings::device FFI prototypes, and remove redundant PoC cache maintenance on shared telemetry/status cursors in gpu/v27_2.rs. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g14_v27_2.rs | 165 +++++++++++++++++++++-------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 51 +++++---- drivers/gpu/drm/asahi/hw/mod.rs | 39 ++++++- 3 files changed, 182 insertions(+), 73 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 3c28823479e7b4..db87fd6de39ee0 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -52,13 +52,14 @@ const ASC_RUN: u32 = 0x10; unsafe extern "C" { fn apple_sleep_commit_stops_coprocs() -> bool; fn apple_sleep_coproc_register_first( - dev: *mut core::ffi::c_void, + dev: *mut kernel::bindings::device, last_stop: Option core::ffi::c_int>, data: *mut core::ffi::c_void, ) -> core::ffi::c_int; - fn apple_sleep_coproc_set_ready(dev: *mut core::ffi::c_void, ready: bool); - fn apple_sleep_coproc_stopped(dev: *mut core::ffi::c_void) -> bool; - fn apple_sleep_coproc_unregister(dev: *mut core::ffi::c_void); + fn apple_sleep_coproc_set_ready(dev: *mut kernel::bindings::device, ready: bool); + fn apple_sleep_coproc_stopped(dev: *mut kernel::bindings::device) -> bool; + fn apple_sleep_coproc_wake_error(dev: *mut kernel::bindings::device) -> core::ffi::c_int; + fn apple_sleep_coproc_unregister(dev: *mut kernel::bindings::device); } #[cfg(CONFIG_APPLE_SOC_SLEEP)] @@ -89,11 +90,14 @@ unsafe extern "C" fn g14_v27_2_commit_stop(data: *mut core::ffi::c_void) -> core c.asc_ctl.cast(), &mut c.idle_us, ); + if c.idle_ret != 0 { + return c.idle_ret; + } kernel::bindings::apple_rtkit_mailbox_recv_off(c.rtk); let ctl = kernel::bindings::readl(c.asc_ctl.cast()); kernel::bindings::writel(ctl & !ASC_RUN, c.asc_ctl.cast()); } - c.idle_ret + 0 } /// Commands slower than this are a hang; the firmware state is then not trusted. @@ -186,6 +190,11 @@ fn gpu_powered(fender: u32) -> bool { fender & 0x10 == 0 && fender & 0xf != 0 } +/// Whether a Fender word says the GPU is powered off: zero index and no request pending. +fn gpu_powered_off(fender: u32) -> bool { + fender & 0x1f == 0 +} + /// The GPU MMU fault status, read when a command times out: a pending fault names the faulting /// address and unit, an empty status says the work stalled without a page fault. struct FaultStatus { @@ -281,6 +290,14 @@ impl Notify { *self.runtime.lock() = Some(runtime); } + /// Toggles `deep_sleeping` under the same lock that guards `wake` and `retry`, so no + /// notification can race a queue drain after this returns with `deep == true`. + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + fn set_deep_sleeping(&self, runtime: &Runtime, deep: bool) { + let _guard = self.runtime.lock(); + runtime.deep_sleeping.store(deep, Ordering::Release); + } + /// After this returns, nothing queues service work. fn detach(&self) -> Option> { self.runtime.lock().take() @@ -342,12 +359,28 @@ fn wait(root: &RootV27_2, ms: i64, mut done: impl FnMut() -> Result) -> Re } } +/// Publishes an idle-policy record and waits until the firmware has consumed and +/// acknowledged it. On error, returns `(published, err)` where `published` is true if the +/// control record was already written to shared memory before the failure. +fn try_set_idle_policy( + root: &RootV27_2, + peer: &mut Peer, + allow_off: bool, +) -> core::result::Result<(), (bool, Error)> { + let (target, generation) = root.publish_idle_policy(allow_off).map_err(|e| (false, e))?; + peer.as_mut() + .send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK) + .map_err(|e| (true, e))?; + wait(root, 3000, || { + Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation) + }) + .map_err(|e| (true, e)) +} + /// Publishes an idle-policy record and waits until the firmware has consumed and /// acknowledged it. fn set_idle_policy(root: &RootV27_2, peer: &mut Peer, allow_off: bool) -> Result { - let (target, generation) = root.publish_idle_policy(allow_off)?; - peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK)?; - wait(root, 3000, || Ok(root.idle_progress()? == [target; 3] && root.idle_acknowledgement()? == generation)) + try_set_idle_policy(root, peer, allow_off).map_err(|(_, e)| e) } /// Stops firmware that no runtime owns: allow power-off, then RTKit power-off, then the ASC @@ -1035,6 +1068,33 @@ impl Runtime { self.pump(state); } + /// Rolls back a failed deep-sleep prepare. If an allow-off policy record was published, + /// keep-powered must be confirmed before reopening submissions; otherwise the backend is + /// failed rather than resuming with an unconfirmed idle policy. + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + fn abort_deep_prepare(&self, state: &mut State, policy_published: bool, err: Error) -> Error { + if policy_published { + if let Err(rb_err) = set_idle_policy(&state.root, &mut state.peer, false) { + dev_err!( + self.dev, + "GPU: deep sleep rollback failed to restore keep-powered: {:?}\n", + rb_err + ); + self.fail_all(state, rb_err); + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + return err; + } + } + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + if self.healthy() { + self.pump(state); + self.notify.wake(); + } + err + } + /// Before a system sleep: holds new publications and lets published work retire. /// /// For suspend-to-idle (`!deep`), the firmware keeps running with its keep-powered policy @@ -1087,15 +1147,18 @@ impl Runtime { } #[cfg(CONFIG_APPLE_SOC_SLEEP)] { + let has_pwr_controller = + Option::as_ref(&*guard).is_some_and(|s| s.root.has_pwr_controller()); // SAFETY: Reads global sleep-driver availability and suspend mode. - if !unsafe { apple_sleep_commit_stops_coprocs() } { + if !has_pwr_controller || !unsafe { apple_sleep_commit_stops_coprocs() } { if let Some(state) = Option::as_mut(&mut *guard) { self.asleep.store(false, Ordering::Release); self.pump(state); } return Err(EBUSY); } - self.deep_sleeping.store(true, Ordering::Release); + // Close Notify admission under its spinlock before dropping `state` and draining. + self.notify.set_deep_sleeping(self, true); drop(guard); // Flush any queued retry or service work; `deep_sleeping` keeps new work out. // SAFETY: `self.retry` is an initialized, pinned delayed work item. @@ -1108,25 +1171,25 @@ impl Runtime { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { - self.deep_sleeping.store(false, Ordering::Release); + self.notify.set_deep_sleeping(self, false); return Ok(()); }; if !self.healthy() || state.running() { - self.deep_sleeping.store(false, Ordering::Release); - self.asleep.store(false, Ordering::Release); - self.pump(state); - return Err(EBUSY); + return Err(self.abort_deep_prepare(state, false, EBUSY)); } - if let Err(err) = set_idle_policy(&state.root, &mut state.peer, true) { + if let Err((published, err)) = try_set_idle_policy(&state.root, &mut state.peer, true) { dev_err!(self.dev, "GPU: deep sleep refused, allow-off failed: {:?}\n", err); - self.deep_sleeping.store(false, Ordering::Release); - self.asleep.store(false, Ordering::Release); - self.pump(state); - return Err(err); + return Err(self.abort_deep_prepare(state, published, err)); + } + if let Err(err) = wait(&state.root, 500, || Ok(gpu_powered_off(state.asc.fender()))) { + dev_err!( + self.dev, + "GPU: deep sleep refused, GPU did not power off (fender={:#x}): {:?}\n", + state.asc.fender(), + err + ); + return Err(self.abort_deep_prepare(state, true, err)); } - let _ = wait(&state.root, 200, || { - Ok(state.root.firmware_running()? == 0 || state.asc.fender() & 0xf == 0) - }); // SAFETY: `ASC_CPU_CONTROL` lies within the mapped ASC page. let asc_ctl = unsafe { state.asc.0.add(ASC_CPU_CONTROL) }; let commit = match KBox::new(CommitStop { @@ -1137,13 +1200,7 @@ impl Runtime { idle_us: 0, }, GFP_KERNEL) { Ok(c) => c, - Err(err) => { - let _ = set_idle_policy(&state.root, &mut state.peer, false); - self.deep_sleeping.store(false, Ordering::Release); - self.asleep.store(false, Ordering::Release); - self.pump(state); - return Err(err.into()); - } + Err(err) => return Err(self.abort_deep_prepare(state, true, err.into())), }; state.commit_stop = Some(commit); let data = state.commit_stop.as_deref_mut().map_or(core::ptr::null_mut(), |c| { @@ -1153,21 +1210,17 @@ impl Runtime { // remains allocated at the same address until unregistered in `sleep_complete`/`stop`. let ret = unsafe { apple_sleep_coproc_register_first( - self.dev.as_raw().cast(), + self.dev.as_raw(), Some(g14_v27_2_commit_stop), data, ) }; if ret != 0 { state.commit_stop = None; - let _ = set_idle_policy(&state.root, &mut state.peer, false); - self.deep_sleeping.store(false, Ordering::Release); - self.asleep.store(false, Ordering::Release); - self.pump(state); - return Err(Error::from_errno(ret)); + return Err(self.abort_deep_prepare(state, true, Error::from_errno(ret))); } // SAFETY: `dev` was just registered above. - unsafe { apple_sleep_coproc_set_ready(self.dev.as_raw().cast(), true) }; + unsafe { apple_sleep_coproc_set_ready(self.dev.as_raw(), true) }; dev_info!(self.dev, "GPU prepared for deep sleep: submitted={} completed={} pending={}\n", state.submitted, state.retired, state.pending.len()); Ok(()) @@ -1178,17 +1231,21 @@ impl Runtime { pub(crate) fn sleep_complete(&self) { let mut guard = self.state.lock(); let Some(state) = Option::as_mut(&mut *guard) else { - self.deep_sleeping.store(false, Ordering::Release); + #[cfg(CONFIG_APPLE_SOC_SLEEP)] + self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); return; }; #[cfg(CONFIG_APPLE_SOC_SLEEP)] if let Some(commit) = state.commit_stop.take() { - // SAFETY: `dev` was registered in `sleep_prepare`. + // SAFETY: `dev` was registered in `sleep_prepare`; `commit` stays live until after + // `apple_sleep_coproc_unregister` completes. let stopped = commit.ran - || unsafe { apple_sleep_coproc_stopped(self.dev.as_raw().cast()) }; + || unsafe { apple_sleep_coproc_stopped(self.dev.as_raw()) }; + // SAFETY: `dev` is still registered until the unregister below. + let wake_err = unsafe { apple_sleep_coproc_wake_error(self.dev.as_raw()) }; // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`. - unsafe { apple_sleep_coproc_unregister(self.dev.as_raw().cast()) }; + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw()) }; // SAFETY: Reads a global flag word. let real = unsafe { kernel::bindings::pm_resume_via_firmware() }; if !stopped && !real { @@ -1197,7 +1254,7 @@ impl Runtime { dev_err!(self.dev, "GPU: failed to restore keep-powered policy: {:?}\n", err); self.fail_all(state, err); } - self.deep_sleeping.store(false, Ordering::Release); + self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); state.waiting_unlink = None; if self.healthy() { @@ -1208,7 +1265,19 @@ impl Runtime { } if !real { dev_warn!(self.dev, "GPU: sleep refused after commit stop; firmware stays stopped\n"); - self.deep_sleeping.store(false, Ordering::Release); + self.notify.set_deep_sleeping(self, false); + self.asleep.store(false, Ordering::Release); + self.fail_all(state, EIO); + return; + } + if commit.idle_ret != 0 || wake_err != 0 { + dev_err!( + self.dev, + "GPU: skipping warm restart after commit/wake error (idle_ret={} wake_err={})\n", + commit.idle_ret, + wake_err + ); + self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); self.fail_all(state, EIO); return; @@ -1225,7 +1294,7 @@ impl Runtime { set_idle_policy(&state.root, &mut state.peer, false)?; wait(&state.root, 500, || Ok(gpu_powered(state.asc.fender()))) })(); - self.deep_sleeping.store(false, Ordering::Release); + self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); state.waiting_unlink = None; state.waiting_control = None; @@ -1284,9 +1353,11 @@ impl Runtime { let mut guard = self.state.lock(); let Some(mut state) = guard.take() else { return; }; #[cfg(CONFIG_APPLE_SOC_SLEEP)] - if state.commit_stop.take().is_some() { - // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`. - unsafe { apple_sleep_coproc_unregister(self.dev.as_raw().cast()) }; + if let Some(_commit) = state.commit_stop.take() { + // SAFETY: Matches `apple_sleep_coproc_register_first` in `sleep_prepare`; PM + // unbind/shutdown does not run concurrently with the IRQ-off commit, and `_commit` + // stays alive until after unregister completes. + unsafe { apple_sleep_coproc_unregister(self.dev.as_raw()) }; } self.fail_all(&mut state, ENODEV); let allowed = set_idle_policy(&state.root, &mut state.peer, true); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 0d1df040d11dc5..d0d634805ecbcb 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -854,13 +854,10 @@ impl RootV27_2 { /// Drain the telemetry rings. The event ring is consumed separately after servicing each event. pub(crate) fn drain(&self) -> Result { let consume = |state: &fw::types::GpuArray, base: usize, records: u32| -> Result { - crate::pgtable::clean_invalidate_poc(state.as_slice()[base..].as_ptr(), 0x30); - crate::pgtable::poc_barrier(); let write = Self::word(state, base + 0x20)?; let read = state.shared_index(base)?; if write < records && read.load(Ordering::Acquire) != write { read.store(write, Ordering::Release); - crate::pgtable::clean_poc(state.as_slice()[base..].as_ptr(), 4); crate::pgtable::poc_barrier(); } Ok(()) @@ -880,11 +877,14 @@ impl RootV27_2 { /// Shared status +0x10: nonzero while the firmware reports itself running. pub(crate) fn firmware_running(&self) -> Result { - crate::pgtable::clean_invalidate_poc(self.status.as_slice().as_ptr(), 0x20); - crate::pgtable::poc_barrier(); Self::word(&self.status, 0x10) } + /// Whether the machine's DT/ADT supplied the GPU power-controller tuning parameters. + pub(crate) fn has_pwr_controller(&self) -> bool { + self.graph.dyncfg.pwr.pwr_controller_from_dt + } + /// Whether the firmware has installed its command handlers: it clears the installation /// request (+0x4c24), which the root sets, once powered initialization has copied them. /// Engine entries may be published only after that. @@ -942,7 +942,7 @@ impl RootV27_2 { || pwr.max_power_mw == 0 || pwr.max_power_mw > i32::MAX as u32 || states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) || pwr.power_sample_period == 0 - || pwr.pwr_filter_time_constant == 0 + || (pwr.pwr_controller_from_dt && pwr.pwr_filter_time_constant == 0) || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period || pwr.avg_power_filter_tc_ms < pwr.power_sample_period || pwr.avg_power_target_filter_tc == 0 @@ -1500,29 +1500,36 @@ impl RootV27_2 { } // The calibrated values of the 13.5 producer; only the layout and the peak length unit // differ. No power zones. + if pwr.pwr_controller_from_dt { + // Power controller (reason 1): populated only when the machine's DT/ADT supplied + // the tuning parameters, so long power-off replays (deep sleep or idle-off) keep + // the limiter calibrated without falling back to built-in coefficients. + let pwr_fields = base.hwdata_a.with(|a, _| [ + (0x9c8, a.unk_64c), + (0x9d4, a.pwr_filter_a_neg.to_bits()), + (0x9dc, a.pwr_filter_a.to_bits()), + (0x9e4, a.pwr_integral_gain.to_bits()), + (0x9ec, a.pwr_integral_min_clamp.to_bits()), + (0x9f0, a.max_power_1.to_bits()), + (0x9f4, a.pwr_proportional_gain.to_bits()), + (0x9fc, a.pwr_pstate_related_k.to_bits()), + (0xa04, max_state), + (0xa08, a.max_pstate_scaled_2), + (0xa14, a.max_power_2), + ]); + for (at, value) in pwr_fields { + put32(policy, at, value); + } + } let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; let fields = base.hwdata_a.with(|a, _| [ - (0x50, 100), - // Power controller (reason 1): populated from the 13.5 calibrated values so long - // power-off replays (e.g. deep sleep or idle-off) keep the limiter calibrated. - (0x9c8, a.unk_64c), - (0x9d4, a.pwr_filter_a_neg.to_bits()), - (0x9dc, a.pwr_filter_a.to_bits()), - (0x9e4, a.pwr_integral_gain.to_bits()), - (0x9ec, a.pwr_integral_min_clamp.to_bits()), - (0x9f0, a.max_power_1.to_bits()), - (0x9f4, a.pwr_proportional_gain.to_bits()), - (0x9fc, a.pwr_pstate_related_k.to_bits()), - (0xa04, max_state), - (0xa08, a.max_pstate_scaled_2), - (0xa14, a.max_power_2), - (0xa48, max_state), - (0xa80, a.ppm_filter_tc_periods_x4), + (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), + (0xa48, max_state), (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), diff --git a/drivers/gpu/drm/asahi/hw/mod.rs b/drivers/gpu/drm/asahi/hw/mod.rs index 934c52380c43db..67335112eef0bf 100644 --- a/drivers/gpu/drm/asahi/hw/mod.rs +++ b/drivers/gpu/drm/asahi/hw/mod.rs @@ -472,6 +472,8 @@ pub(crate) struct PwrConfig { pub(crate) ppm_ki: F32, /// PPM (?) filter PID proportional gain. pub(crate) ppm_kp: F32, + /// Whether the board's DT/ADT explicitly supplied all four power-controller parameters. + pub(crate) pwr_controller_from_dt: bool, /// Power consumption filter time constant (periods?) pub(crate) pwr_filter_time_constant: u32, /// Power consumption filter PID integral gain. @@ -618,6 +620,34 @@ impl PwrConfig { }; let power_sample_period: u32 = prop!("apple,power-sample-period"); + let pwr_filter_tc_opt: Option = node + .get_opt_property(c_str!("apple,pwr-filter-time-constant")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-filter-time-constant: {:?}\n", e); + e + })?; + let pwr_ki_opt: Option = node + .get_opt_property(c_str!("apple,pwr-integral-gain")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-integral-gain: {:?}\n", e); + e + })?; + let pwr_clamp_opt: Option = node + .get_opt_property(c_str!("apple,pwr-integral-min-clamp")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-integral-min-clamp: {:?}\n", e); + e + })?; + let pwr_kp_opt: Option = node + .get_opt_property(c_str!("apple,pwr-proportional-gain")) + .map_err(|e| { + dev_err!(dev, "Error reading property apple,pwr-proportional-gain: {:?}\n", e); + e + })?; + let pwr_controller_from_dt = pwr_filter_tc_opt.is_some() + && pwr_ki_opt.is_some() + && pwr_clamp_opt.is_some() + && pwr_kp_opt.is_some(); Ok(PwrConfig { core_leak_coef, @@ -662,11 +692,12 @@ impl PwrConfig { ppm_filter_time_constant_ms: prop!("apple,ppm-filter-time-constant-ms"), ppm_ki: prop!("apple,ppm-ki"), ppm_kp: prop!("apple,ppm-kp"), - pwr_filter_time_constant: prop!("apple,pwr-filter-time-constant", 313), - pwr_integral_gain: prop!("apple,pwr-integral-gain", f32!(0.0202129)), - pwr_integral_min_clamp: prop!("apple,pwr-integral-min-clamp", 0), + pwr_controller_from_dt, + pwr_filter_time_constant: pwr_filter_tc_opt.unwrap_or(313), + pwr_integral_gain: pwr_ki_opt.unwrap_or(f32!(0.0202129)), + pwr_integral_min_clamp: pwr_clamp_opt.unwrap_or(0), pwr_min_duty_cycle: prop!("apple,pwr-min-duty-cycle"), - pwr_proportional_gain: prop!("apple,pwr-proportional-gain", f32!(5.2831855)), + pwr_proportional_gain: pwr_kp_opt.unwrap_or(f32!(5.2831855)), pwr_sample_period_aic_clks: prop!( "apple,pwr-sample-period-aic-clks", cfg.base_clock_hz / 1000 * power_sample_period From 3577ce0e4885ca23f43b62087503b078b2fbee64 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 03:45:43 -0500 Subject: [PATCH 1373/1514] drm/asahi: g14_v27_2: skip hardware teardown after failed sleep or wake Persist hardware_unreachable in State when sleep_complete() sees a refused sleep after commit stop or a commit/wake error, and skip live RTKit and ASC MMIO operations in stop() while still retaining the firmware's page-table backing. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g14_v27_2.rs | 45 ++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index db87fd6de39ee0..e2962c75ee0436 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -49,6 +49,7 @@ const ASC_CPU_CONTROL: usize = 0x44; const ASC_RUN: u32 = 0x10; #[cfg(CONFIG_APPLE_SOC_SLEEP)] +#[allow(improper_ctypes)] unsafe extern "C" { fn apple_sleep_commit_stops_coprocs() -> bool; fn apple_sleep_coproc_register_first( @@ -554,6 +555,9 @@ struct State { accepting: bool, submitted: u64, retired: u64, + /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so + /// teardown skips live-hardware MMIO and RTKit operations. + hardware_unreachable: bool, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: Option>, } @@ -1265,6 +1269,7 @@ impl Runtime { } if !real { dev_warn!(self.dev, "GPU: sleep refused after commit stop; firmware stays stopped\n"); + state.hardware_unreachable = true; self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); self.fail_all(state, EIO); @@ -1277,6 +1282,7 @@ impl Runtime { commit.idle_ret, wake_err ); + state.hardware_unreachable = true; self.notify.set_deep_sleeping(self, false); self.asleep.store(false, Ordering::Release); self.fail_all(state, EIO); @@ -1360,20 +1366,30 @@ impl Runtime { unsafe { apple_sleep_coproc_unregister(self.dev.as_raw()) }; } self.fail_all(&mut state, ENODEV); - let allowed = set_idle_policy(&state.root, &mut state.peer, true); - let root = &state.root; - let _ = wait(root, 500, || Ok(root.firmware_running()? == 0)); - let running = root.firmware_running(); - let forced = (running != Ok(0)).then(|| { - // SAFETY: the RTKit instance is live and owned here. - kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) - }); - state.asc.halt(); - dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", - allowed, running, forced, state.submitted, state.retired, - self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped, state.deferred); - if running != Ok(0) && forced != Some(Ok(())) { - dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); + if state.hardware_unreachable { + dev_info!( + self.dev, + "GPU stopped: skipping hardware teardown after failed sleep/wake (submitted={} completed={} notifications={})\n", + state.submitted, + state.retired, + self.notify.messages.load(Ordering::Relaxed) + ); + } else { + let allowed = set_idle_policy(&state.root, &mut state.peer, true); + let root = &state.root; + let _ = wait(root, 500, || Ok(root.firmware_running()? == 0)); + let running = root.firmware_running(); + let forced = (running != Ok(0)).then(|| { + // SAFETY: the RTKit instance is live and owned here. + kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) }) + }); + state.asc.halt(); + dev_info!(self.dev, "GPU stopped: allow-off={:?} running={:?} forced-off={:?} submitted={} completed={} notifications={} late={} skipped-slots={} deferred-cursors={}\n", + allowed, running, forced, state.submitted, state.retired, + self.notify.messages.load(Ordering::Relaxed), state.late, state.skipped, state.deferred); + if running != Ok(0) && forced != Some(Ok(())) { + dev_err!(self.dev, "GPU firmware did not stop; a reset is required\n"); + } } // Keep everything the firmware could reach for the rest of the boot, halted or not: // its page tables still name these pages, and the boot handoff window that start() @@ -1476,6 +1492,7 @@ impl Backend { accepting: true, submitted: 0, retired: 0, + hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, }); From ef1c98566309db7a963ef6e38df8a77123ab6045 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 04:37:35 +1100 Subject: [PATCH 1374/1514] drm/asahi: g16: run T8122 G15G on the G15 family's 26B123 protocol After READY the 15-inch M3 Air's G15G firmware installs root[1] at the shared root + 3 pages with 0x403 attributes, the G15S convention, while the G16G protocol expects root + 4 pages with 0x2000000000004cb. The host's live-root check therefore refused the backend start with EIO right after READY. Use FwAbi::V26B123G15S for the G15G build: its live root table matches what this firmware writes, and with it the queue/resource graphs, the device-control channel and DRM registration all come up on the J615. InitData, scratch window and segment layout stay G15G's own. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/hw.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index e4580cc0d27a13..fbd206a7502594 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -531,6 +531,9 @@ pub(crate) mod t8122 { segment_vas: &[UPPER, UPPER + 0x64000, UPPER + 0x118000], data_size: 0xbc000, initdata: &initdata::G15G_26B123, + // The G15 family's 26B123 protocol: the J615 firmware installs root[1] at root + 3 + // pages with 0x403 attributes, the G15S convention, not G16G's. + abi: super::FwAbi::V26B123G15S, // Not known for this firmware; the host keeps reading GPU registers while it runs, as // the m3 runtime does. powered: None, From ad937dcfb227ed4ee394cb73fafdbc964d72fa8b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 04:53:30 +1100 Subject: [PATCH 1375/1514] drm/apple: leave an external pipe without a valid mode to the firmware The external pipe-off on firmware-27 interfaces ran whenever a CRTC was disabled. On a Mac mini (M2, 27.2 firmware) the desktop's CRTC disable at the login hand-over can land while the firmware describes the HDMI display again after a hotplug. The firmware then answers neither the clear swap nor setPowerState(0); both time out, the next power-on waits for power in vain, and the display stays dark. A firmware re-describe withdraws the mode first (mode_state.valid is false until a mode set completes), and nothing of ours scans out then. Leave such a pipe to the firmware and only stop a pipe that runs a mode we set. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/iomfb_template.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/iomfb_template.c b/drivers/gpu/drm/apple/iomfb_template.c index fd23281c4b6bbc..a8e995f3f41266 100644 --- a/drivers/gpu/drm/apple/iomfb_template.c +++ b/drivers/gpu/drm/apple/iomfb_template.c @@ -2907,9 +2907,22 @@ void DCP_FW_NAME(iomfb_poweroff)(struct apple_dcp *dcp) * its panel. An external pipe stops like the H17G one: otherwise * DPMS off leaves it scanning out the last frame. */ - if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G && - dcp_has_panel(dcp)) - return; + if (dcp->hw.iomfb_method_profile != DCP_IOMFB_METHODS_H17G) { + if (dcp_has_panel(dcp)) + return; + /* + * The firmware withdrew the mode (it is describing the display + * again after a hotplug, see dcp_mode_withdraw()): no scanout of + * ours is left to stop, and while it republishes the display it + * answers neither the clear swap nor setPowerState(0). Both then + * time out and leave the pipe unable to power on again. + */ + if (!READ_ONCE(dcp->mode_state.valid)) { + dev_dbg(dcp->dev, "%s: no valid mode, pipe left to the firmware\n", + __func__); + return; + } + } #endif #if DCP_FW_DESKTOP_26(DCP_FW_VER) From 7b54ee43d0bb3896852ffad35102b0411a8b9d06 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 13:04:50 -0500 Subject: [PATCH 1376/1514] PCI: apple: mask conventional port chained IRQ across firmware sleep Conventional Apple PCIe ports attach a chained interrupt handler at AIC, which suspend_device_irqs() does not mask. On T8103, the boot loader's post-sleep complex reinit does not write PORT_INTMSK, leaving all 32 port interrupt lines unmasked at hardware reset default when AIC resumes. An unmapped pending bit in PORT_INTSTAT then storms CPU0 through apple_port_irq_handler() until the hardware watchdog resets the machine. Mask and gate each port's chained interrupt in apple_pcie_hib_save(), re-enable it in apple_pcie_resume_noirq() if the sleep was refused before commit, and otherwise unmask it in apple_pcie_resume() after each port's interrupt mask and status have been restored (or masked on link recovery failure or idle ports). Signed-off-by: Erik Bourget --- drivers/pci/controller/pcie-apple.c | 40 ++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 322d3c7e02db3c..18012332042398 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -659,6 +659,7 @@ struct apple_pcie { unsigned long *bitmap; struct list_head ports; struct list_head hib_fns; + bool hib_saved; struct completion event; struct irq_fwspec fwspec; struct irq_domain *msi_domain; @@ -7674,8 +7675,16 @@ static int apple_pcie_resume_noirq(struct device *dev) return ret; } if (!pcie->hw->tunneled) { - if (apple_pcie_s2r_reinit(pcie) && pm_resume_via_firmware()) - apple_pcie_hib_restore_noirq(pcie, "S2R"); + if (pcie->hib_saved) { + if (pm_resume_via_firmware()) { + apple_pcie_hib_restore_noirq(pcie, "S2R"); + } else { + /* Refused before commit: registers are intact. */ + pcie->hib_saved = false; + list_for_each_entry(port, &pcie->ports, entry) + apple_pcie_port_enable_irq(port); + } + } return 0; } if (pcie->resume_failed) @@ -7770,6 +7779,13 @@ static void apple_pcie_hib_save(struct apple_pcie *pcie) mutex_lock(&pcie->lock); list_for_each_entry(port, &pcie->ports, entry) { + /* + * A chained port interrupt stays unmasked across suspend_device_irqs(). + * Mask and gate it before firmware sleep so a complex whose boot-time + * reinit leaves PORT_INTMSK clear cannot storm at AIC resume before + * apple_pcie_resume() masks and restores the port. + */ + apple_pcie_port_disable_irq(port); port->hib_link_up = apple_pcie_port_readl(port, PORT_LINKSTS) & PORT_LINKSTS_UP; port->hib_cold = false; port->saved_intmask = apple_pcie_port_readl(port, PORT_INTMSK); @@ -7777,6 +7793,7 @@ static void apple_pcie_hib_save(struct apple_pcie *pcie) port->saved_rid2sid[i] = apple_pcie_port_readl(port, port_rid2sid_offset(port, i)); } + pcie->hib_saved = true; mutex_unlock(&pcie->lock); } @@ -7895,22 +7912,37 @@ static int apple_pcie_resume(struct device *dev) struct apple_pcie_hib_fn *fn; int ret; - if (!apple_pcie_s2r_reinit(pcie) || !pm_resume_via_firmware()) + if (!pcie->hib_saved) + return 0; + pcie->hib_saved = false; + if (!apple_pcie_s2r_reinit(pcie) || !pm_resume_via_firmware()) { + list_for_each_entry(port, &pcie->ports, entry) + apple_pcie_port_enable_irq(port); return 0; + } list_for_each_entry(port, &pcie->ports, entry) { - if (!port->hib_link_up) + if (!port->hib_link_up) { + apple_pcie_port_writel(port, ~0, PORT_INTMSK); + apple_pcie_port_writel(port, ~0, PORT_INTSTAT); + apple_pcie_port_enable_irq(port); continue; + } if (!port->hib_cold) { apple_pcie_hib_rid2sid(pcie, port); + apple_pcie_port_enable_irq(port); continue; } ret = apple_pcie_hib_port_up(pcie, port); if (ret) { dev_err(dev, "S2R: %pOF link not back (%d), its functions stay unreachable\n", port->np, ret); + apple_pcie_port_writel(port, ~0, PORT_INTMSK); + apple_pcie_port_writel(port, ~0, PORT_INTSTAT); port->hib_cold = false; + apple_pcie_port_enable_irq(port); continue; } + apple_pcie_port_enable_irq(port); dev_info(dev, "S2R: %pOF link back, PWREN and PERST# cycled as at probe\n", port->np); } From 73c532b7f83022076b8d8e1f48e045a49f300b31 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 13:31:13 -0500 Subject: [PATCH 1377/1514] Bluetooth: hci_bcm4377: restore BAR0 windows and mark needs_reset on S2R power loss After a firmware-driven sleep on a conventional PCIe host, PERST# resets BCM4377/BCM4378's private BAR0 backplane windows to their hardware defaults (e.g. 0x19328000 on BCM4378). When bcm4377_resume() queues device_reprobe() without setting needs_reset or restoring the BAR0 windows, bcm4377_hci_close() during hci_unregister_dev() still attempts to destroy transfer rings by writing the BAR0 doorbell through the unconfigured window, faulting the PCIe/AXI bus on T8103. Set needs_reset and call bcm4377_init_cfg() before queueing the rebind so teardown skips ring destruction on dead firmware and any interim BAR0 access lands on valid backplane windows. Signed-off-by: Erik Bourget --- drivers/bluetooth/hci_bcm4377.c | 7 ++++++- tools/asahi/bcm4377-resume/fixture.h | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 9e0a5f1ac1637e..80c3f197263cfd 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -3250,11 +3250,16 @@ static int bcm4377_resume(struct device *dev) /* * A real sleep took the function's power: the firmware is gone, and every resume command * would only time out (two times 2 s inside the system resume, then the rebind anyway). - * Skip them and rebind from the work queue; probe boots the firmware from scratch. + * Restore the private BAR0 windows and mark needs_reset before queueing the rebind so + * neither hci_close() during device_reprobe() nor a stray frame can write BAR0 through + * unconfigured reset windows. Skip the resume commands and rebind from the work queue; + * probe boots the firmware from scratch. */ if (pm_resume_via_firmware() && !bcm4377->dma_window_base) { bcm4377->quiesced = false; bcm4377->resume_powered = false; + bcm4377->needs_reset = true; + bcm4377_init_cfg(bcm4377); WRITE_ONCE(bcm4377->setup_retry_blocked, false); bcm4377_queue_rebind(bcm4377, "power lost in the sleep"); return 0; diff --git a/tools/asahi/bcm4377-resume/fixture.h b/tools/asahi/bcm4377-resume/fixture.h index 7c053b3012ff68..ddd125e8764b3b 100644 --- a/tools/asahi/bcm4377-resume/fixture.h +++ b/tools/asahi/bcm4377-resume/fixture.h @@ -91,6 +91,7 @@ static int send_ptb(struct bcm4377_data *b,const struct firmware *f) { assert(f= static const struct firmware *bcm4377_request_blob(struct bcm4377_data *b,const char *suffix) { assert(!strcmp(suffix,"ptb"));return missing_blob?NULL:&fw; } static void release_firmware(const struct firmware *f) { assert(f==&fw); } static int bcm4377_check_bdaddr(struct bcm4377_data *b) { return 0; } +static int bcm4377_init_cfg(struct bcm4377_data *b) { (void)b; return 0; } static int bcm4377_destroy_transfer_ring(struct bcm4377_data *b,struct ring *r) { r->enabled=false;return close_error; } static int bcm4377_destroy_completion_ring(struct bcm4377_data *b,struct ring *r) { r->enabled=false;return close_error; } static int bcm4377_hci_set_bdaddr(struct hci_dev *h,const bdaddr_t *a) { addr_count++;if(addr_error)return addr_error;h->bdaddr=*a;return 0; } From 3025a8dcbf6625b2a98edf4faa8cadf4262efd6f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 12:53:14 -0500 Subject: [PATCH 1378/1514] drm/asahi: g17: keep firmware-mutable pooled state uncached On G17, Pool::allocate() converts the requested prefix of pooled firmware objects from MEMATTR_UNCACHED to MEMATTR_CACHED via set_fw_cached_prefix(), while the host accesses them through write-combined mappings. G17 firmware has no cache-flush protocol, and host CPU stores neither snoop nor invalidate dirty lines in the firmware coprocessor's private cache. When the firmware writes runtime state into a firmware-cached page and the host later overwrites fields on the same cache line, the firmware can read stale data from its cache and later evict the dirty line back to DRAM, reverting the host's update. On J716c (T6050), rebinding an idle compute queue to a new context through Graph::set_owner() left the firmware's dirty QueueRecord line intact: on subsequent mixed render/compute work, QueueRecord.job_list_va in DRAM reverted to the previous context's WorkHead, stranding shared WorkNodes with completed == submitted and a non-empty job list until the 2 s watchdog failed the client with VK_ERROR_DEVICE_LOST and quarantined the queues. The same dirty-line hazard applies to every pooled G17 object that both the firmware and the host write: - Compute queue graphs (QueueRecord rewritten on rebind, items ring rewritten on wrap). Because installed compute graphs live until firmware stop, allocate them directly as uncached KernelObjects, freeing Family::QueueState pool slots for render pairs. - Compute descriptor rings (M5 common firmware clears the accounting counter at +0xfac, and the host rewrites each slot every 32 kicks). - Render queue-state objects (QueueRecord rewritten on G17P rebind and work-slot bind, and zeroed on pool reuse everywhere). - Context work-state objects (WorkNode slots rewritten every 63 submissions and zeroed on pool reuse). - M5 context scheduler pages (zeroed and reinitialized on pool reuse). Allow Pool::allocate() with prefix == 0 to retain and fence an uncached mapping without calling set_fw_cached_prefix(), preserving control-ring fencing, A18 Pro ReturnMark tracking, retain_until_stop(), and O(1) VA reuse. Pass prefix == 0 for compute DescriptorRing, render QueueState, WorkState, and M5 Scheduler allocations, leave firmware-read-only render descriptors (which already fall back to uncached on M5 due to the 32-page conversion limit) and QueueConfig pools unchanged, add release barriers after QueueRecord owner rebinds, and cover prefix == 0 pool retention in tools/asahi/g17-object-fence-tests.py. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/context.rs | 13 +++-- drivers/gpu/drm/asahi/g17/object.rs | 16 ++++-- drivers/gpu/drm/asahi/g17/queue/compute.rs | 53 ++++++++++-------- .../gpu/drm/asahi/g17/queue/render/memory.rs | 7 ++- tools/asahi/g17-object-fence-tests.py | 54 ++++++++++++++++++- 5 files changed, 110 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 84b519795da736..6ec7713e690efe 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -166,9 +166,9 @@ impl WorkStorage { } } -/// A context's scheduler page. The M5 firmware caches its mapping, so on M5 it -/// comes from the retention pool and stays mapped until firmware stop; elsewhere -/// it is an ordinary allocation. +/// A context's scheduler page. On M5 it comes from the retention pool so its +/// VA stays mapped and fenced across releases (uncached, because both firmware +/// and host write it on reuse); elsewhere it is an ordinary allocation. pub(crate) enum SchedulerStorage { Ordinary(KernelObject), Retained(PooledObject), @@ -281,7 +281,7 @@ impl Context { alloc, Family::Scheduler, UAT_PGSZ, - UAT_PGSZ, + 0, kernel_prot, CpuMap::WriteCombined, )?) @@ -300,11 +300,14 @@ impl Context { fence(Ordering::SeqCst); let scheduler_generation = super::ids::OBJECTS.object()?; let scheduler = Arc::new(scheduler, GFP_KERNEL)?; + // Both firmware and host write work nodes (reused every 63 submissions + // and zeroed on pool reuse). Keep the whole work-state object uncached + // while retaining its VA and return mark in the pool. let mut object = pool.allocate( alloc, Family::WorkState, 2 * UAT_PGSZ, - UAT_PGSZ, + 0, kernel_prot, CpuMap::WriteCombined, )?; diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index de422808e8e668..09be46bb145a0d 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -700,15 +700,18 @@ impl Pool { ) } - /// Allocates or reuses a matching object. Capacity pressure leaves a fresh - /// mapping uncached, preserving allocation and submission concurrency. + /// Allocates or reuses a matching object. A non-zero `prefix` maps `[0..prefix)` + /// firmware-cached; `prefix == 0` keeps the whole mapping uncached (for objects + /// that both firmware and host write) while still retaining and fencing the VA + /// in the pool. Capacity pressure leaves a fresh mapping unpooled and uncached, + /// preserving allocation and submission concurrency. /// /// The firmware may still follow a previous owner's pointers into a returned object /// until it has processed that owner's release. Reuse takes the matching object /// returned longest ago once its fence is met (see `return_object`); a younger one is - /// reused only when the family has no room for a fresh cached object, because an - /// uncached one is unmapped as soon as its owner drops it. On the A18 Pro a work state is - /// never reused before its fence: with no room, a fresh one stays uncached instead. + /// reused only when the family has no room for a fresh pooled object, because an + /// unpooled one is unmapped as soon as its owner drops it. On the A18 Pro a work state is + /// never reused before its fence: with no room, a fresh one stays unpooled instead. pub(crate) fn allocate( self: &kernel::sync::Arc, alloc: &Allocator<'_>, @@ -808,6 +811,9 @@ impl Pool { if !reserved { return Ok(result); } + if prefix == 0 { + return Ok(result); + } let (proof, mutated) = match result.mapping.as_ref() { // SAFETY: The allocator just created the private mapping. No // pointer or alias has been published; its reserved lease retains diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index afc1ee221567ab..bd5732e9ac68d6 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -47,9 +47,9 @@ const CONFIG: usize = 0; const ANNOUNCE: usize = 0x800; const PREDECESSOR: usize = 0x400; const POINTERS: usize = 0x100; -/// Producer/consumer words live on their own uncached page after the graph, -/// which the firmware reads through a cached mapping (queue record, job-list -/// head and item ring), as native does. +/// Producer/consumer words live on their own page after the graph. The whole +/// graph stays uncached because both the firmware and host write the queue +/// record (on owner rebinds) and item ring. const CURSORS: usize = GRAPH_SIZE; const ITEMS: usize = 0x4000; const STAMP: usize = 0x300; @@ -106,18 +106,20 @@ pub(crate) struct DescriptorRing { } impl DescriptorRing { - /// Firmware reads every descriptor through a cached kernel mapping, as it - /// does for render. The pool keeps that mapping until processor stop; the - /// hardware reads the same pages through an uncached canonical low alias. - /// On M5 the kernel mapping, in the upper half every execution context - /// includes, is firmware-only. + /// Keep compute descriptors uncached while retaining their VA and fence in + /// the pool: M5 common firmware clears the descriptor's accounting counter + /// at `+0xfac`, and the host rewrites each slot every 32 kicks, so a + /// firmware-cached mapping carries the same dirty-line writeback hazard. + /// The hardware reads the same pages through an uncached canonical low + /// alias; on M5 the kernel mapping, in the upper half every execution + /// context includes, is firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( alloc, Family::Descriptor, size, - size, + 0, if alloc.uat.is_m5() { mmu::PROT_FW_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }, CpuMap::WriteCombined, )?; @@ -141,7 +143,7 @@ struct Graph { operand: KernelObject, support: KernelObject, m5_timestamps: Option>, - graph: PooledObject, + graph: KernelObject, context_low: Option, context_high: Option, /// Announcements, which stay uncached for the firmware. @@ -191,14 +193,14 @@ impl Graph { support.write(0x110, 0x50u32)?; support.write(mmu::UAT_PGSZ + 4, 1u32)?; } - let mut graph = objects.allocate( - alloc, - Family::QueueState, - GRAPH_SIZE + mmu::UAT_PGSZ, - GRAPH_SIZE, - prot, - cpu, - )?; + // Keep the compute graph uncached: the firmware writes runtime state + // into the queue record while the host rewrites its owner fields on + // rebind (`Graph::set_owner`) and wraps the item ring. Firmware-cached + // G17 mappings are non-coherent with host writes and cannot be flushed, + // so dirty firmware lines would revert host updates. An installed + // compute graph lives until firmware stop and does not need the reuse + // pool. + let mut graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; let graph_va = graph.gpu_va(); graph.initialize::(0, |view| { view.pointers = PointerBlock::new(&pointers)?; @@ -308,8 +310,16 @@ impl Graph { .cast::(); // SAFETY: The checked packed record stays mapped. The device mutex // and idle witness exclude access by another owner during this update. - return unsafe { (*pointer).set_compute_owner(context.work_head_va(), - context.scheduler_va(), context.owner_pid(), context.policy()) }; + unsafe { + (*pointer).set_compute_owner( + context.work_head_va(), + context.scheduler_va(), + context.owner_pid(), + context.policy(), + ) + }?; + fence(Ordering::Release); + return Ok(()); } let pointer = self .graph @@ -325,6 +335,7 @@ impl Graph { context.policy(), ) }; + fence(Ordering::Release); Ok(()) } @@ -2532,7 +2543,7 @@ impl Graph { (object, record_start(slot, offset, window, stride)?) } else { let start = record_start(0, offset, window, GRAPH_SIZE - 0x6800)?; - (&mut *self.graph, 0x6800 + start) + (&mut self.graph, 0x6800 + start) }; if core::mem::size_of::() > window { return Err(EINVAL); diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index 4cc04e2ac23e90..46f82879a95b71 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -145,11 +145,14 @@ impl Graph { context.vm(), TA_BYTES..TA_BYTES + FRAGMENT_BYTES, )?) }; + // Both firmware and host write queue records (in-place retargeting and + // work-slot binding on G17P, and zeroing on pool reuse everywhere). Keep + // the whole queue-state object uncached while retaining it in the pool. let mut queues = pool.allocate( alloc, Family::QueueState, GRAPH_SIZE, - 0x8000, + 0, prot, CpuMap::WriteCombined, )?; @@ -1062,6 +1065,7 @@ impl Memory { pointer.write_unaligned(value); } } + core::sync::atomic::fence(Ordering::Release); return Ok(()); } let offsets = qids.map(|qid| usize::from(qid) * size_of::()); @@ -1106,6 +1110,7 @@ impl Memory { } } } + core::sync::atomic::fence(Ordering::Release); Ok(()) } } diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index d9a5b417f03220..fe4eccf9e96e9d 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -148,7 +148,10 @@ def context_source(text): pub struct KernelMapping { pub iova: u64 } impl KernelMapping { pub fn iova(&self) -> u64 { self.iova } - pub unsafe fn set_fw_cached_prefix(&self, _prefix: usize) -> (crate::Result<[u64; 2]>, bool) { (Ok([0; 2]), true) } + pub unsafe fn set_fw_cached_prefix(&self, prefix: usize) -> (crate::Result<[u64; 2]>, bool) { + assert!(prefix > 0, "set_fw_cached_prefix must not be called for prefix == 0"); + (Ok([0; 2]), true) + } } } @@ -357,6 +360,54 @@ def context_source(text): ["unseen=", "released=", "strict="].map(|key| crate::count(&s, "workstate_returns", key)) } + /// Uncached pooled objects (`prefix == 0`) skip `set_fw_cached_prefix` while keeping + /// their pool lease, fence, return mark, reuse zeroing and retention until stop. + pub fn uncached_pooled() { + for after_release in [true, false] { + let next = Cell::new(1); + let alloc = Allocator { next: &next }; + let pool = Pool::new(after_release).unwrap(); + crate::forget_unmapped(); + crate::channel::set(5, 3); + + let mut ws = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert!(ws.lease.is_some(), "prefix == 0 keeps a pool lease"); + assert_eq!(ws.return_mark().is_some(), after_release); + ws.bytes_mut()[0] = 0x42; + let ws_id = ws.id; + if let Some(mark) = ws.return_mark() { + mark.expose(); + } + drop(ws); + assert!(!unmapped(ws_id), "prefix == 0 stays mapped on drop"); + assert_eq!(fence(&pool, Family::WorkState, ws_id), Some(6)); + + // Still behind fence: a fresh object is allocated instead of reusing ws_id. + let fresh = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert_ne!(fresh.id, ws_id); + drop(fresh); + + // Once the fence is met, ws_id is reused and zeroed. + crate::channel::set(6, 6); + let reused = pool.allocate(&alloc, Family::WorkState, WORK, 0, 0, CpuMap::WriteCombined).unwrap(); + assert_eq!(reused.id, ws_id, "prefix == 0 is reused once its fence is met"); + assert_eq!(reused.bytes[0], 0, "reused prefix == 0 object is zeroed"); + drop(reused); + + // retain_until_stop keeps an uncached pooled object mapped until firmware stop. + let mut kept = pool.allocate(&alloc, Family::QueueState, mmu::UAT_PGSZ, 0, 0, CpuMap::WriteCombined).unwrap(); + assert!(kept.lease.is_some()); + let kept_id = kept.id; + kept.retain_until_stop(&pool); + drop(kept); + assert!(!unmapped(kept_id)); + pool.stop_after_firmware(); + assert!(unmapped(kept_id)); + assert!(unmapped(ws_id)); + } + println!("uncached pooled: prefix == 0 skips firmware caching while keeping fencing, reuse and retention"); + } + /// Each return class decides the fence; reuse never waits on a met fence. pub fn return_classes() { let next = Cell::new(1); @@ -708,6 +759,7 @@ def context_source(text): } fn main() { + now::uncached_pooled(); now::return_classes(); now::full_family(); let (mut allocations, mut uncached, mut overruns) = (0, 0, 0); From 9a1540ca44538b6730c995cee44200d366a9f45b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 07:49:58 +1100 Subject: [PATCH 1379/1514] drm/asahi: g16: lay out G15G GLOBALS as the G15 family's 26B123 The 15-inch M3 Air (T8122 G15G) runs the G15 family's 26B123 InitData version, the same version as G15S, but its layout took G16G's GLOBALS runs. In this version the 25G83 words from +0xe28 on sit 5 bytes up, not 4, so the soft-fault word (25G83 +0xe28 = 3) landed one byte low and the firmware read 0 there. With soft faults off, an unmapped shader write faults the whole context instead of being dropped: Geekbench 6 Vulkan's Background Blur (resize_bilinear) wrote 29 KiB past an application buffer, the VM went into its sticky error state and the device was lost, on both linux#3163's head and main. The same workload passes on G16G (J713) and G16S (J616s), whose firmware default drops such writes. Use the G15S GLOBALS runs for G15G. The rest of the G15G layout is unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/fw/initdata.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/gpu/drm/asahi/g16/fw/initdata.rs b/drivers/gpu/drm/asahi/g16/fw/initdata.rs index 79f85c96350e66..ab15e9d40e53bd 100644 --- a/drivers/gpu/drm/asahi/g16/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/fw/initdata.rs @@ -502,6 +502,11 @@ pub(crate) const G15G_26B123: Layout = Layout { // The shared3 block's state word (+0x62ac + 8): with the block all zero the G15G firmware // never takes the first device-control records. state_bound: Some(0x62b4), + // GLOBALS as the G15 family's 26B123 InitData version lays it out (the same version as + // G15S): the words from 25G83 +0xe28 on sit 5 bytes up, not G16G's 4. With G16G's runs the + // soft-fault word (25G83 +0xe28 = 3) lands one byte low, the firmware reads 0 there and an + // unmapped shader write faults the context instead of being dropped. + globals: G15S_26B123.globals, ..V26B123 }; From bcdc74861256bab351862b41e9de6b6409c44e27 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 16:37:07 -0500 Subject: [PATCH 1380/1514] drm/apple: dcp: support T8103 DCPEXT DART register mapping and S2R Add an apple,t8103-dcpext match entry with map_reg_dart, s2r_ext, s2r_disp_dart_with_dcp, and DISPEXT0 power words (0x378/0x368), and add apple,display-power on t8103's dcpext node. Without map_reg_dart, firmware 27.2 faults on stream 0 writing disp-4 (0x23b3d0000) during its first external display power-down and crashes DCPEXT. Generalize the s2r_ext domain/power-word helpers to key on hw.s2r_layout and hw.s2r_ext instead of a SoC compatible check, restore disp_dart streams on s2r_ext_start when s2r_disp_dart_with_dcp is set, and gate firmware 27.0 s2r_ext on hw.s2r_untested so T8142 keeps its existing opt-in while T8103 works with the default command line. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103.dtsi | 1 + drivers/gpu/drm/apple/dcp.c | 51 +++++++++++++++++++++++----- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8103.dtsi b/arch/arm64/boot/dts/apple/t8103.dtsi index 6e420d4c5ffabf..02b06f1b2e6f6b 100644 --- a/arch/arm64/boot/dts/apple/t8103.dtsi +++ b/arch/arm64/boot/dts/apple/t8103.dtsi @@ -1653,6 +1653,7 @@ dcpext: dcp@271c00000 { compatible = "apple,t8103-dcpext", "apple,dcpext"; + apple,display-power = <&dcp_power>; mboxes = <&dcpext_mbox>; mbox-names = "mbox"; iommus = <&dcpext_dart 0 0x0 0x0 0x0 0xfc000000>; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index ec6a28333f3920..4815a51bbf12d8 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -9198,6 +9198,17 @@ static const struct dcp_s2r_layout dcp_s2r_t8103 = { .disp_streams = BIT(0) | BIT(4), }; +/* + * T8103's external display processor: DISPEXT0's CPU (0x378) and front end (0x368) + * power words, with the same DART stream layout as the internal DCP. + */ +static const struct dcp_s2r_layout dcp_s2r_t8103_ext = { + .disp_cpu = 0x378, + .disp_fe = 0x368, + .dcp_streams = BIT(0), + .disp_streams = BIT(0) | BIT(4), +}; + /* TEST: J813 external processors, ADT DISPEXT0/1 power words. */ static const struct dcp_s2r_layout dcp_s2r_t8142_ext[] = { { .disp_cpu = 0x428, .disp_fe = 0x418, .disp_sys = 0x308, @@ -9502,10 +9513,12 @@ static int dcp_s2r_stop_firmware(struct apple_dcp *dcp) */ static bool dcp_s2r_ext_capable(struct apple_dcp *dcp) { + if (!dcp->hw.s2r_ext || !of_property_present(dcp->dev->of_node, "apple,display-power")) + return false; if (dcp->fw_compat == DCP_FIRMWARE_V_27_0) - return dcp->hw.s2r_ext && s2r_untested && dcp->v27_methods && + return (!dcp->hw.s2r_untested || s2r_untested) && dcp->v27_methods && dcp->v27_methods[dcpep_unnamed_500].tag[0]; - return dcp->fw_compat == DCP_FIRMWARE_H17P && dcp->hw.s2r_ext; + return dcp->fw_compat == DCP_FIRMWARE_H17P; } /* @@ -9848,8 +9861,8 @@ static int dcp_s2r_domains_on(struct apple_dcp *dcp) val = readl(ps + l->disp_fe) & ~(GENMASK(9, 8) | GENMASK(3, 0)); writel(val | 0xf, ps + l->disp_fe); val = readl(ps + l->disp_cpu) & ~(GENMASK(9, 8) | GENMASK(3, 0) | BIT(28)); - if (dcp_s2r_is_t8142_ext(dcp)) { - /* Retain the CPU when idle, as in the measured J813 wake sequence. */ + if (dcp->hw.s2r_ext) { + /* Retain the external CPU when idle (apple,min-state = 4). */ val = (val & ~DCP_PS_MIN) | FIELD_PREP(DCP_PS_MIN, 4); writel(val, ps + l->disp_cpu); } @@ -9891,7 +9904,7 @@ static int dcp_s2r_ext_domains_on(struct apple_dcp *dcp) u32 val; int i, ret = -ENODEV; - if (dcp_s2r_is_t8142_ext(dcp)) + if (dcp->hw.s2r_layout) return dcp_s2r_domains_on(dcp); np = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); @@ -9962,14 +9975,22 @@ static int dcp_s2r_ext_start(struct apple_dcp *dcp, bool cycled) ret = dcp_s2r_ext_domains_on(dcp); if (ret) return ret; + /* Powered again: the invalidations held while it was dark run now. */ + if (dcp->s2r_disp_dart) + apple_dart_power_dark(dcp->s2r_disp_dart, false); /* After the domains, whose writes it would reject, the DART protects them again. */ apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, true, false); + /* Set up again before the firmware runs, which uses it right away. */ + if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, true, false); + if (ret) + return ret; + } if (!cycled) return apple_rtkit_sleep_return(dcp->rtk, control); - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, false); return apple_rtkit_power_cycled_return(dcp->rtk, control); } @@ -9988,7 +10009,7 @@ static int dcp_s2r_ext_domains_off(struct apple_dcp *dcp) int i, ret = -ENODEV; u32 val; - if (dcp_s2r_is_t8142_ext(dcp)) + if (dcp->hw.s2r_layout) return dcp_s2r_domains_off(dcp); np = of_parse_phandle(dcp->dev->of_node, "apple,display-power", 0); @@ -10047,7 +10068,7 @@ static bool dcp_s2r_ext_cpu_on(struct apple_dcp *dcp) of_node_put(np); if (!ps) return false; - on = FIELD_GET(GENMASK(7, 4), readl(ps + (dcp_s2r_is_t8142_ext(dcp) ? + on = FIELD_GET(GENMASK(7, 4), readl(ps + (dcp->hw.s2r_layout ? dcp_s2r_layout(dcp)->disp_cpu : 0x328))); iounmap(ps); @@ -11067,6 +11088,16 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8103 = { .s2r_disp_dart_with_dcp = true, }; +/* T8103's external DCP: maps register windows through its DART and stops/restarts across S2R */ +static const struct apple_dcp_hw_data apple_dcp_hw_t8103_dcpext = { + .num_dptx_ports = 2, + .s2r_ext = true, + .s2r_no_secure_port = true, + .s2r_layout = &dcp_s2r_t8103_ext, + .map_reg_dart = true, + .s2r_disp_dart_with_dcp = true, +}; + static const struct apple_dcp_hw_data apple_dcp_hw_dcp = { .num_dptx_ports = 0, }; @@ -11170,6 +11201,7 @@ static const struct apple_dcp_hw_data apple_dcp_hw_t8142_dcpext = { .dptx_controller = true, /* TEST: firmware 27.2 link release, gated by appledrm.s2r_untested. */ .s2r_ext = true, + .s2r_untested = true, .s2r_no_secure_port = true, .s2r_layout = &dcp_s2r_t8142_ext[0], }; @@ -11204,6 +11236,7 @@ static const struct of_device_id of_match[] = { { .compatible = "apple,t6020-dcp", .data = &apple_dcp_hw_t6020, }, { .compatible = "apple,t6020-dcpext", .data = &apple_dcp_hw_t6020_dcpext, }, { .compatible = "apple,t8103-dcp", .data = &apple_dcp_hw_t8103, }, + { .compatible = "apple,t8103-dcpext", .data = &apple_dcp_hw_t8103_dcpext, }, { .compatible = "apple,t8112-dcp", .data = &apple_dcp_hw_t8112, }, { .compatible = "apple,t8140-dcp", .data = &apple_dcp_hw_t8140, }, { .compatible = "apple,t8140-dcpext", .data = &apple_dcp_hw_t8140_external, }, From 834e5defedc682c954468eb5573e718846c110c2 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 16:37:07 -0500 Subject: [PATCH 1381/1514] thunderbolt: apple: tear down T8103 ACIO routers for deep sleep Like T8122, T8103 deep sleep cuts power to the CIO/ATC domains and shares the ATC PHY with DWC3. Set sleep_removes_domains, restart_on_wake, and phy_shared_with_dwc3 on apple_cio_t8103_hw so mem_sleep=deep tears down an attached router ahead of DWC3's PM notifier and requests fresh cable state on wake, while s2idle and freeze leave the port up unchanged. Update tools/asahi/pciec-policy-tests.py to cover T8103 alongside T8122. Signed-off-by: Erik Bourget --- drivers/thunderbolt/apple.c | 9 ++++++ tools/asahi/pciec-policy-tests.py | 50 +++++++++++++++++++++++-------- 2 files changed, 46 insertions(+), 13 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index f66c192a2ae3e3..6115871373557d 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -188,7 +188,16 @@ struct apple_cio_hw { const struct apple_dpin_policy *dp; }; +/* + * T8103 deep sleep removes the CIO power domains and shares the ATC PHY with + * DWC3. Tear down a connected router before tasks freeze (ahead of DWC3's PM + * notifier) and request fresh cable state immediately on wake; s2idle and + * freeze leave the port up. + */ static const struct apple_cio_hw apple_cio_t8103_hw = { + .sleep_removes_domains = true, + .restart_on_wake = true, + .phy_shared_with_dwc3 = true, .dp = &apple_dpin_m1, }; diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index 3e753abfdba22f..449d635c5122f5 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -677,7 +677,7 @@ def test_pm_order(out, acio): #include #include struct apple_dpin_policy { int unused; }; -static const struct apple_dpin_policy apple_dpin_m1; +static const struct apple_dpin_policy apple_dpin_m1, apple_dpin_m2; struct apple_cio_hw { bool sleep_removes_domains; bool restart_on_wake; @@ -749,33 +749,42 @@ def test_pm_order(out, acio): static const char *const t8103_compat[] = { "apple,t8103-usb4-acio", NULL }; + static const char *const t6020_compat[] = { + "apple,t6020-usb4-acio", "apple,t8103-usb4-acio", NULL + }; const struct apple_cio_hw *t8122 = match_of(t8122_compat); const struct apple_cio_hw *t8103 = match_of(t8103_compat); + const struct apple_cio_hw *t6020 = match_of(t6020_compat); assert(t8122 == &apple_cio_t8122_hw); assert(t8103 == &apple_cio_t8103_hw); - assert(t8122->sleep_removes_domains); - assert(t8122->restart_on_wake); - assert(t8122->phy_shared_with_dwc3); - assert(t8122->dp == &apple_dpin_m1); + assert(t6020 == &apple_cio_t6020_hw); + assert(t8122->sleep_removes_domains && t8103->sleep_removes_domains); + assert(t8122->restart_on_wake && t8103->restart_on_wake); + assert(t8122->phy_shared_with_dwc3 && t8103->phy_shared_with_dwc3); + assert(t8122->dp == &apple_dpin_m1 && t8103->dp == &apple_dpin_m1); struct apple_cio acio_t8122 = { .hw = t8122 }; struct apple_cio acio_t8103 = { .hw = t8103 }; + struct apple_cio acio_t6020 = { .hw = t6020 }; - /* mem_sleep=deep + mem tears down T8122 ACIO, leaves T8103 unchanged. */ + /* mem_sleep=deep + mem tears down T8103 and T8122 ACIO, leaves T6020 unchanged. */ default_s2idle = false; no_platform = false; assert(apple_cio_sleep_removes_domains(&acio_t8122)); - assert(!apple_cio_sleep_removes_domains(&acio_t8103)); + assert(apple_cio_sleep_removes_domains(&acio_t8103)); + assert(!apple_cio_sleep_removes_domains(&acio_t6020)); /* s2idle keeps the port up. */ default_s2idle = true; no_platform = false; assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + assert(!apple_cio_sleep_removes_domains(&acio_t8103)); /* freeze keeps the port up even when mem_sleep=deep is the default. */ default_s2idle = false; no_platform = true; assert(!apple_cio_sleep_removes_domains(&acio_t8122)); + assert(!apple_cio_sleep_removes_domains(&acio_t8103)); /* Shared ATC PHY: ACIO PM notifier must run before DWC3's. */ struct dwc3_apple dwc = { 0 }; @@ -785,7 +794,7 @@ def test_pm_order(out, acio): assert(!chain[i]->notifier_call()); assert(pci_off && phy_off); - puts("PASS: T8122 ACIO deep-sleep teardown, freeze/s2idle preservation, and DWC3 PM order"); + puts("PASS: T8103/T8122 ACIO deep-sleep teardown, freeze/s2idle preservation, and DWC3 PM order"); return 0; } ''' @@ -794,7 +803,7 @@ def test_pm_order(out, acio): def test_t8122_cio_sleep(out, acio): dwc = (ROOT / 'drivers/usb/dwc3/dwc3-apple.c').read_text() hw_defs = [] - for sym in ('apple_cio_t8103_hw', 'apple_cio_t8122_hw'): + for sym in ('apple_cio_t8103_hw', 'apple_cio_t8122_hw', 'apple_cio_t6020_hw'): m = re.search(r'^static const struct apple_cio_hw ' + sym + r' = \{.*?\n\};', acio, re.M | re.S) assert m, sym @@ -807,8 +816,9 @@ def test_t8122_cio_sleep(out, acio): r'\.compatible\s*=\s*"([^"]+)"\s*,\s*\.data\s*=\s*(&apple_cio_\w+_hw)', match_block.group()) match_lines = [f' {{ "{c}", {d} }},' for c, d in entries - if c in ('apple,t8122-usb4-acio', 'apple,t8103-usb4-acio')] - assert len(match_lines) == 2, match_lines + if c in ('apple,t8122-usb4-acio', 'apple,t6020-usb4-acio', + 'apple,t8103-usb4-acio')] + assert len(match_lines) == 3, match_lines code = T8122_SLEEP_FIXTURE code = code.replace('/* PRODUCTION_HW */', '\n'.join(hw_defs)) code = code.replace('/* MATCH_ENTRIES */', '\n'.join(match_lines)) @@ -822,8 +832,22 @@ def test_t8122_cio_sleep(out, acio): 'ret = register_pm_notifier(&appledwc->pm_nb);')) muts = { 't8122-drop-match': (' { "apple,t8122-usb4-acio", &apple_cio_t8122_hw },', ''), - 't8122-drop-sleep-removes-domains': ('\t.sleep_removes_domains = true,\n', ''), - 't8122-drop-phy-shared': ('\t.phy_shared_with_dwc3 = true,\n', ''), + 't8103-drop-sleep-removes-domains': ( + 'static const struct apple_cio_hw apple_cio_t8103_hw = {\n' + '\t.sleep_removes_domains = true,\n', + 'static const struct apple_cio_hw apple_cio_t8103_hw = {\n'), + 't8122-drop-sleep-removes-domains': ( + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n', + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n'), + 't8122-drop-phy-shared': ( + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n' + '\t.restart_on_wake = true,\n' + '\t.phy_shared_with_dwc3 = true,\n', + 'static const struct apple_cio_hw apple_cio_t8122_hw = {\n' + '\t.sleep_removes_domains = true,\n' + '\t.restart_on_wake = true,\n'), } cases = {'t8122-cio-sleep': code} for name, (old, new) in muts.items(): From 3e72a0ce5a9b72cbd1629579ea4b8ba4b4017a47 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 16:37:07 -0500 Subject: [PATCH 1382/1514] PCI: apple: allow orderly removal of igc behind a tunneled PCIe-C port igc_remove() unregisters its netdev and disables the PCI device without touching the PM notifier chain, so it is safe to remove during PM_SUSPEND_PREPARE when deep sleep powers down a USB4/Thunderbolt router (such as a CalDigit TS5 dock carrying an Intel I225-LMvP NIC). Signed-off-by: Erik Bourget --- drivers/pci/controller/pcie-apple.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/drivers/pci/controller/pcie-apple.c b/drivers/pci/controller/pcie-apple.c index 9f6be9afd1cf82..88be13b02f0e86 100644 --- a/drivers/pci/controller/pcie-apple.c +++ b/drivers/pci/controller/pcie-apple.c @@ -6286,7 +6286,8 @@ static int apple_pcie_tunnel_other_driver(struct pci_dev *pdev, void *data) { struct device_driver *drv = READ_ONCE(pdev->dev.driver); - if (!drv || !strcmp(drv->name, "nvme") || !strcmp(drv->name, "pcieport")) + if (!drv || !strcmp(drv->name, "nvme") || !strcmp(drv->name, "pcieport") || + !strcmp(drv->name, "igc")) return 0; *(const char **)data = drv->name; return 1; @@ -6300,13 +6301,14 @@ static int apple_pcie_tunnel_other_driver(struct pci_dev *pdev, void *data) * For a sleep that takes the tunnel's router down. Unlike apple_pcie_tunnel_quiesce(), which * marks the functions disconnected first (their drivers then treat them as gone), the * functions are removed while they still answer: an NVMe controller's driver stops its - * queues and gives the controller its normal shutdown, as at a power-off. Nothing is written + * queues and gives the controller its normal shutdown, as at a power-off, and igc + * unregisters its netdev cleanly without touching PM notifiers. Nothing is written * to a disk that has no opener. apple_pcie_tunnel_quiesce() then takes the ports down and * apple_pcie_tunnel_restore() enumerates the hierarchy again. * * Returns 0 when the hierarchy is removed (or was already), -EBUSY when a disk is open and - * @in_use_too is false, -EOPNOTSUPP when a function has a driver other than nvme or the PCIe - * port driver. Nothing is removed on an error. + * @in_use_too is false, -EOPNOTSUPP when a function has a driver other than nvme, igc, or + * the PCIe port driver. Nothing is removed on an error. */ int apple_pcie_tunnel_remove_orderly(struct device *dev, bool in_use_too) { From e1924d043f383511bc265ca8b62057557b233de1 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 16:37:07 -0500 Subject: [PATCH 1383/1514] iommu/apple-dart: allow PCIe-C tunnel state save/restore with non-locking tunables T8103 USB4 PCIe-C DARTs receive apple,tunable entries from the bootloader that do not set DART_T8020_CONFIG_LOCK. Check whether any tunable entry actually sets the lock bit instead of rejecting any non-NULL dart->tunables in apple_dart_save_tunnel_state() and apple_dart_restore_tunnel_state(), and reapply dart->tunables after apple_dart_hw_reset() on restore. Signed-off-by: Erik Bourget --- drivers/iommu/apple-dart.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index be7e5a7fa72162..0c152f4aac3696 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -6631,6 +6631,21 @@ int apple_dart_resume_commands(struct device *dev) } EXPORT_SYMBOL_GPL(apple_dart_resume_commands); +static bool apple_dart_tunables_lock(const struct apple_dart *dart) +{ + size_t i; + + if (!dart->tunables) + return false; + + for (i = 0; i < dart->tunables->sz; ++i) { + if (dart->tunables->values[i].offset == dart->hw->lock && + (dart->tunables->values[i].value & dart->hw->lock_bit)) + return true; + } + return false; +} + /* * System sleep has quiesced every downstream device. PCIe-C calls this * before stopping APPCLK because its domain reset also loses DART state, @@ -6642,7 +6657,7 @@ int apple_dart_save_tunnel_state(struct device *dev) unsigned int sid, idx; if (!dart || !dart->tunneled || dart->locked || - dart->hw->type != DART_T8020 || dart->tunables) + dart->hw->type != DART_T8020 || apple_dart_tunables_lock(dart)) return -EOPNOTSUPP; guard(spinlock_irqsave)(&dart->lock); @@ -6670,7 +6685,7 @@ int apple_dart_restore_tunnel_state(struct device *dev) int ret; if (!dart || !dart->tunneled || dart->locked || - dart->hw->type != DART_T8020 || dart->tunables) + dart->hw->type != DART_T8020 || apple_dart_tunables_lock(dart)) return -EOPNOTSUPP; if (!dart->tunnel_state_saved || READ_ONCE(dart->commands_gated)) return -EINVAL; @@ -6678,6 +6693,8 @@ int apple_dart_restore_tunnel_state(struct device *dev) ret = apple_dart_hw_reset(dart); if (ret) return ret; + if (dart->tunables) + apple_dart_apply_own_tunables(dart); for (sid = 0; sid < dart->num_streams; sid++) { for (idx = 0; idx < dart->hw->ttbr_count; idx++) From aefd301d304e438029235da6f49c83e9a0499b04 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 16:37:07 -0500 Subject: [PATCH 1384/1514] usb: dwc3: apple: declare pre-load softdep on xhci_plat_hcd dwc3_apple_host_start() binds xhci-hcd synchronously under appledwc->lock and returns -EPROBE_DEFER if no driver binds it before platform_device_add()/device_attach() returns. When CONFIG_USB_XHCI_PLATFORM=m, the first USB host plug-in after boot raced ahead of udev loading xhci-plat-hcd and failed with -517. Declare MODULE_SOFTDEP("pre: xhci_plat_hcd") so xhci-plat-hcd is loaded before dwc3-apple. Signed-off-by: Erik Bourget --- drivers/usb/dwc3/dwc3-apple.c | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/usb/dwc3/dwc3-apple.c b/drivers/usb/dwc3/dwc3-apple.c index c97f40b0aa9890..eb9aff615bcb4b 100644 --- a/drivers/usb/dwc3/dwc3-apple.c +++ b/drivers/usb/dwc3/dwc3-apple.c @@ -2369,3 +2369,4 @@ module_platform_driver(dwc3_apple_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("DesignWare DWC3 Apple Silicon Glue Driver"); +MODULE_SOFTDEP("pre: xhci_plat_hcd"); From 66622957ef131f323dc681e4c613967c5a216133 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 25 Nov 2026 04:37:04 -0300 Subject: [PATCH 1385/1514] wifi: brcmfmac: skip 500 ms down delay when not connected Both __brcmf_cfg80211_down() and brcmf_cfg80211_suspend() check BRCMF_VIF_STATUS_READY, call brcmf_link_down(), and then unconditionally sleep 500 ms via brcmf_delay(500) so wpa_supplicant can process the firmware DISASSOC event. When wpa_supplicant has already disconnected before bringing the interface down (as on every normal shutdown/reboot and suspend), BRCMF_VIF_STATUS_CONNECTED is already clear and brcmf_link_down() sends no WLC_DISASSOC to firmware, making the 500 ms sleep under rtnl_lock() pure delay. Return whether brcmf_link_down() actually sent WLC_DISASSOC and only sleep 500 ms when it did. Signed-off-by: Jonathan Goyvaerts --- .../broadcom/brcm80211/brcmfmac/cfg80211.c | 33 +++++++++++-------- tools/asahi/brcmf-suspend-tests.py | 2 +- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c index ede3f72e253882..157b54a776fd74 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c @@ -1681,12 +1681,13 @@ static int brcmf_set_pmk(struct brcmf_if *ifp, const u8 *pmk_data, u16 pmk_len) return brcmf_set_wsec(ifp, pmk_data, pmk_len, 0); } -static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, +static bool brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, bool locally_generated) { struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(vif->wdev.wiphy); struct brcmf_pub *drvr = cfg->pub; bool bus_up = drvr->bus_if->state == BRCMF_BUS_UP; + bool disassoc_sent = false; s32 err = 0; brcmf_dbg(TRACE, "Enter\n"); @@ -1699,6 +1700,8 @@ static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, if (err) bphy_err(drvr, "WLC_DISASSOC failed (%d)\n", err); + else + disassoc_sent = true; } if ((vif->wdev.iftype == NL80211_IFTYPE_STATION) || @@ -1717,6 +1720,7 @@ static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason, vif->profile.use_fwsup = BRCMF_PROFILE_FWSUP_NONE; } brcmf_dbg(TRACE, "Exit\n"); + return disassoc_sent; } static s32 brcmf_cfg80211_join_ibss(struct wiphy *wiphy, @@ -5287,12 +5291,13 @@ static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy, * disassociate from AP to save power while system is * in suspended state */ - brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED, true); - /* Make sure WPA_Supplicant receives all the event - * generated due to DISASSOC call to the fw to keep - * the state fw and WPA_Supplicant state consistent - */ - brcmf_delay(500); + if (brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED, true)) { + /* Make sure WPA_Supplicant receives all the event + * generated due to DISASSOC call to the fw to keep + * the state fw and WPA_Supplicant state consistent + */ + brcmf_delay(500); + } } /* Configure MPC */ brcmf_set_mpc(ifp, 1); @@ -9321,13 +9326,13 @@ static s32 __brcmf_cfg80211_down(struct brcmf_if *ifp) * from AP to save power */ if (check_vif_up(ifp->vif)) { - brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED, true); - - /* Make sure WPA_Supplicant receives all the event - generated due to DISASSOC call to the fw to keep - the state fw and WPA_Supplicant state consistent - */ - brcmf_delay(500); + if (brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED, true)) { + /* Make sure WPA_Supplicant receives all the events + * generated due to DISASSOC call to the fw to keep + * the fw and WPA_Supplicant state consistent. + */ + brcmf_delay(500); + } } brcmf_abort_scanning(cfg); diff --git a/tools/asahi/brcmf-suspend-tests.py b/tools/asahi/brcmf-suspend-tests.py index c66733209235b6..bccf1a63d40dd4 100644 --- a/tools/asahi/brcmf-suspend-tests.py +++ b/tools/asahi/brcmf-suspend-tests.py @@ -223,7 +223,7 @@ def function(source, name): static void brcmf_abort_scanning(struct brcmf_cfg80211_info *c) {(void)c;can_command();} static unsigned wowl_offs; static void brcmf_bus_wowl_config(struct brcmf_bus *b,bool e) {(void)b;if(!e)wowl_offs++;} -static void brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();} +static bool brcmf_link_down(struct brcmf_cfg80211_vif *v,int r,bool b) {(void)v;(void)r;(void)b;can_command();return true;} static void brcmf_delay(int t) {(void)t;} static void brcmf_set_mpc(struct brcmf_if *i,int v) {(void)i;(void)v;can_command();} static unsigned wowl_configs; From c72e93d2202c00c4afb5c02d4c2c411e006b0fb0 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 25 Nov 2026 04:37:06 -0300 Subject: [PATCH 1386/1514] soc: apple: sep: notify sysfs on diag/keystore and diag/touchid transitions Userspace helpers (aurora-sep-load, aurora-sep-ready) currently poll diag/keystore in a 100 ms sleep loop while waiting for SEP bring-up to finish (aurora-silicon/linux#2313). Cache kernfs_node references for diag/keystore and diag/touchid at sep_diag_register() time (released via devm_add_action_or_reset() before the attribute group is removed) and call kernfs_notify() on state transitions so userspace can wait via poll(POLLPRI | POLLERR) with zero polling delay. Signed-off-by: Jonathan Goyvaerts --- drivers/soc/apple/diag_shim.c | 83 +++++++++++++++++++--- tools/aurora-sep/tests/test_diag_sensor.py | 60 +++++++++++++++- 2 files changed, 130 insertions(+), 13 deletions(-) diff --git a/drivers/soc/apple/diag_shim.c b/drivers/soc/apple/diag_shim.c index 995abe149b0c50..51453c19297f0d 100644 --- a/drivers/soc/apple/diag_shim.c +++ b/drivers/soc/apple/diag_shim.c @@ -19,8 +19,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -118,8 +120,39 @@ static struct { atomic_t unhandled; atomic_t sleeps; atomic_t sleeping; + + struct kernfs_node *keystore_kn; + struct kernfs_node *touchid_kn; } sep_diag; +static DEFINE_SPINLOCK(sep_diag_kn_lock); + +static void sep_diag_put_kns(void *data) +{ + struct kernfs_node *keystore_kn, *touchid_kn; + unsigned long flags; + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + keystore_kn = sep_diag.keystore_kn; + touchid_kn = sep_diag.touchid_kn; + sep_diag.keystore_kn = NULL; + sep_diag.touchid_kn = NULL; + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); + + sysfs_put(keystore_kn); + sysfs_put(touchid_kn); +} + +static void sep_diag_notify_kn(struct kernfs_node **knp) +{ + unsigned long flags; + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + if (*knp) + kernfs_notify(*knp); + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); +} + /* Written once per probe, before pnon reads SEP_DIAG_PNON_READ. */ static u8 sep_diag_pnon_digest[SEP_DIAG_PNON_DIGEST_LEN]; @@ -735,6 +768,10 @@ static const struct attribute_group sep_diag_group = { int sep_diag_register(struct device *dev, const char *profile, size_t profile_len, bool cold, bool sepos13, bool xart) { + struct kernfs_node *diag_kn, *keystore_kn = NULL, *touchid_kn = NULL; + unsigned long flags; + int ret; + profile_len = min(profile_len, sizeof(sep_diag.profile) - 1); memcpy(sep_diag.profile, profile, profile_len); sep_diag.profile[profile_len] = '\0'; @@ -743,7 +780,23 @@ int sep_diag_register(struct device *dev, const char *profile, sep_diag.xart = xart; sep_diag.probe_ns = ktime_get_boottime_ns(); - return devm_device_add_group(dev, &sep_diag_group); + ret = devm_device_add_group(dev, &sep_diag_group); + if (ret) + return ret; + + diag_kn = sysfs_get_dirent(dev->kobj.sd, "diag"); + if (diag_kn) { + keystore_kn = sysfs_get_dirent(diag_kn, "keystore"); + touchid_kn = sysfs_get_dirent(diag_kn, "touchid"); + sysfs_put(diag_kn); + } + + spin_lock_irqsave(&sep_diag_kn_lock, flags); + sep_diag.keystore_kn = keystore_kn; + sep_diag.touchid_kn = touchid_kn; + spin_unlock_irqrestore(&sep_diag_kn_lock, flags); + + return devm_add_action_or_reset(dev, sep_diag_put_kns, NULL); } void sep_diag_set_attach(bool attached) @@ -867,7 +920,9 @@ void sep_diag_log_summary(struct device *dev) void sep_diag_set_keystore_open(void) { - atomic_set(&sep_diag.keystore, SEP_DIAG_KEYSTORE_OPEN); + if (atomic_xchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_OPEN) != + SEP_DIAG_KEYSTORE_OPEN) + sep_diag_notify_kn(&sep_diag.keystore_kn); } void sep_diag_set_keybag(int state) @@ -925,14 +980,18 @@ void sep_diag_set_sensor_result(unsigned int bind, bool online) */ void sep_diag_set_bio_published(void) { - atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, - SEP_DIAG_TOUCHID_PUBLISHED); + if (atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, + SEP_DIAG_TOUCHID_PUBLISHED) == + SEP_DIAG_TOUCHID_PENDING) + sep_diag_notify_kn(&sep_diag.touchid_kn); } void sep_diag_set_touchid(bool started) { - atomic_set(&sep_diag.touchid, - started ? SEP_DIAG_TOUCHID_STARTED : SEP_DIAG_TOUCHID_FAILED); + int state = started ? SEP_DIAG_TOUCHID_STARTED : SEP_DIAG_TOUCHID_FAILED; + + if (atomic_xchg(&sep_diag.touchid, state) != state) + sep_diag_notify_kn(&sep_diag.touchid_kn); } void sep_diag_set_sensor_attach(int state) @@ -978,13 +1037,17 @@ void sep_diag_set_xart(bool writable) void sep_diag_keystore_ended(void) { atomic64_cmpxchg(&sep_diag.ready_ns, 0, ktime_get_boottime_ns()); - atomic_cmpxchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_UNKNOWN, - SEP_DIAG_KEYSTORE_CLOSED); + if (atomic_cmpxchg(&sep_diag.keystore, SEP_DIAG_KEYSTORE_UNKNOWN, + SEP_DIAG_KEYSTORE_CLOSED) == + SEP_DIAG_KEYSTORE_UNKNOWN) + sep_diag_notify_kn(&sep_diag.keystore_kn); } void sep_diag_bringup_ended(void) { sep_diag_keystore_ended(); - atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, - SEP_DIAG_TOUCHID_UNAVAILABLE); + if (atomic_cmpxchg(&sep_diag.touchid, SEP_DIAG_TOUCHID_PENDING, + SEP_DIAG_TOUCHID_UNAVAILABLE) == + SEP_DIAG_TOUCHID_PENDING) + sep_diag_notify_kn(&sep_diag.touchid_kn); } diff --git a/tools/aurora-sep/tests/test_diag_sensor.py b/tools/aurora-sep/tests/test_diag_sensor.py index a8a6a114447891..86b564752c0d8a 100644 --- a/tools/aurora-sep/tests/test_diag_sensor.py +++ b/tools/aurora-sep/tests/test_diag_sensor.py @@ -94,10 +94,31 @@ return (u64)now.tv_sec * 1000000000ULL + now.tv_nsec; } static inline u64 div_u64(u64 value, u32 divisor) { return value / divisor; } +''', + 'linux/kernfs.h': r''' +#include +struct kernfs_node { + const char *name; + struct kernfs_node *const *children; + unsigned int notifies; +}; +static inline void kernfs_notify(struct kernfs_node *kn) +{ + if (kn) + kn->notifies++; +} +''', + 'linux/spinlock.h': r''' +typedef struct { int unused; } spinlock_t; +#define DEFINE_SPINLOCK(x) spinlock_t x +#define spin_lock_irqsave(lock, flags) do { (void)(lock); (flags) = 0; } while (0) +#define spin_unlock_irqrestore(lock, flags) do { (void)(lock); (void)(flags); } while (0) ''', 'linux/device.h': r''' #include -struct device { int unused; }; +struct kernfs_node; +struct kobject { struct kernfs_node *sd; }; +struct device { struct kobject kobj; }; #define dev_info(dev, ...) ((void)(dev)) struct attribute { const char *name; umode_t mode; }; struct device_attribute { @@ -118,11 +139,32 @@ registered_group = grp; return 0; } +static inline int devm_add_action_or_reset(struct device *dev, + void (*action)(void *), void *data) +{ + (void)dev; + (void)action; + (void)data; + return 0; +} ''', 'linux/sysfs.h': r''' +#include #include #include #include +#include +static inline struct kernfs_node *sysfs_get_dirent(struct kernfs_node *parent, + const char *name) +{ + if (!parent || !parent->children) + return NULL; + for (struct kernfs_node *const *c = parent->children; *c; c++) + if (!strcmp((*c)->name, name)) + return *c; + return NULL; +} +static inline void sysfs_put(struct kernfs_node *kn) { (void)kn; } static inline int sysfs_emit(char *buf, const char *fmt, ...) { va_list args; @@ -160,6 +202,7 @@ #include #include #include +#include #include #include "shim.h" @@ -215,7 +258,13 @@ int main(int argc, char **argv) { - struct device dev; + struct kernfs_node keystore_kn = { .name = "keystore" }; + struct kernfs_node touchid_kn = { .name = "touchid" }; + struct kernfs_node *const diag_children[] = { &keystore_kn, &touchid_kn, NULL }; + struct kernfs_node diag_kn = { .name = "diag", .children = diag_children }; + struct kernfs_node *const root_children[] = { &diag_kn, NULL }; + struct kernfs_node root_kn = { .name = "root", .children = root_children }; + struct device dev = { .kobj = { .sd = &root_kn } }; unsigned int bind, stale; /* The Neo: warm attach, xART writable, no guard. */ @@ -245,6 +294,10 @@ expect("attach", "sensor_attach", "attached"); expect("attach", "restore", "restored"); expect("attach", "touchid", "ready"); + if (touchid_kn.notifies != 2) { + printf("FAIL attach: touchid notifies is %u, want 2\n", touchid_kn.notifies); + failures++; + } if (argc > 1) dump(argv[1]); @@ -285,6 +338,7 @@ #include #include #include +#include #include #include "shim.h" @@ -310,7 +364,7 @@ /* argv: level list matching-at-probe refusals matching-after-refusal */ int main(int argc, char **argv) { - struct device dev; + struct device dev = { 0 }; int refusals = atoi(argv[4]); sep_diag_set_xart_guard(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); From a4f42a41076ece8cf39d99a3fe37bc5436646849 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 17:18:08 -0500 Subject: [PATCH 1387/1514] drm/asahi: g17: allow sibling render completion while direct prepare is lent Two physical render pairs bound to one logical context share a single free-list Lease. With direct render submission enabled on M5 (PR #2955) alongside two render pairs per owner, lend_render() prepares the shared pool lease and releases the device mutex while the lent pair builds and publishes off-lock. Previously Lease encoded preparation as a single scalar phase (LeasePhase::Preparing), so when the event worker retired a completed render on the sibling pair while the other pair was lent, Lease::complete_render() saw LeasePhase::Preparing, returned EINVAL, and stopped the GPU runtime (reproduced immediately by gpubench-vk render.light depth=8 on J716c). Track active preparations with a counter (preparing) and whether at least one render of the generation has published (published): - Lease::complete_render() admits completions while sibling preparations are lent, while still rejecting completions with EINVAL if no published render holds references above the reserved preparations. - Add Lease::cancel_prepare() and update Pools::rollback() to undo only the rolled-back preparation instead of restoring a pre-prepare snapshot, preserving any sibling completions or observed control-ring release witnesses that occurred while lent. - Add Firmware::rollback_render_pool() so a rollback that drops the last reference on an already-published generation immediately flushes its pending FreeListRelease (or queues events on EAGAIN). - Add KUnit coverage in freelist.rs and a host mutation test in tools/asahi/g17-freelist-lease-direct-tests.py. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g17/freelist.rs | 147 +++++++- drivers/gpu/drm/asahi/g17/runtime/render.rs | 23 ++ .../drm/asahi/g17/runtime/render/direct.rs | 6 +- .../gpu/drm/asahi/g17/runtime/render/pools.rs | 23 +- .../drm/asahi/g17/runtime/render/submit.rs | 3 +- .../asahi/g17-freelist-lease-direct-tests.py | 320 ++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 7 files changed, 504 insertions(+), 21 deletions(-) create mode 100755 tools/asahi/g17-freelist-lease-direct-tests.py diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index cf9e729dad36a9..017f6d03b2013c 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -1226,7 +1226,9 @@ pub(crate) struct Owner { #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum LeasePhase { - Preparing, + /// Active and/or preparing. `references == commands + preparing` with + /// `commands >= 2 * preparing`. When `references == 0`, `published` is + /// true and a final `FreeListRelease` is pending. Ready, /// No reference since the given time. The registration stays live so that /// the owner's next render reuses it without a control-ring release; the @@ -1249,6 +1251,8 @@ pub(crate) struct Lease { generation: u64, references: u32, commands: u32, + preparing: u32, + published: bool, phase: LeasePhase, previous_release: Option, } @@ -1264,7 +1268,9 @@ impl Lease { generation: 0, references: 3, commands: 2, - phase: LeasePhase::Preparing, + preparing: 1, + published: false, + phase: LeasePhase::Ready, previous_release: None, }); }; @@ -1287,6 +1293,7 @@ impl Lease { } let references = previous.references.checked_add(3).ok_or(EOVERFLOW)?; let commands = previous.commands.checked_add(2).ok_or(EOVERFLOW)?; + let preparing = previous.preparing.checked_add(1).ok_or(EOVERFLOW)?; Ok(Self { owner, generation: if overlapping { @@ -1296,7 +1303,9 @@ impl Lease { }, references, commands, - phase: LeasePhase::Preparing, + preparing, + published: overlapping && previous.published, + phase: LeasePhase::Ready, previous_release: previous.release_witness(), }) } @@ -1313,9 +1322,14 @@ impl Lease { LeasePhase::ReleaseSent(_) | LeasePhase::Released ) && self.references == 0 && self.commands == 0 + && self.preparing == 0 } pub(crate) fn released(&self) -> bool { - self.phase == LeasePhase::Released && self.previous_release.is_none() + self.phase == LeasePhase::Released + && self.previous_release.is_none() + && self.references == 0 + && self.commands == 0 + && self.preparing == 0 } pub(crate) fn release_witness(&self) -> Option { match self.phase { @@ -1326,13 +1340,47 @@ impl Lease { /// Publication retires preparation independently of the command references. pub(crate) fn retire_prepare(&mut self) -> Result { - if self.phase != LeasePhase::Preparing || self.references < 3 { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || self.preparing == 0 + || self.references < reserved_refs + || self.commands < reserved_cmds + { return Err(EINVAL); } + self.preparing -= 1; self.references -= 1; - self.phase = LeasePhase::Ready; + self.published = true; Ok(()) } + /// Rolls back one unpublished `acquire()` without disturbing sibling + /// completions or observed release witnesses that occurred meanwhile. + /// If the rolled-back preparation held the last reference on an already + /// published generation, its final release becomes pending. + pub(crate) fn cancel_prepare( + &mut self, + ) -> Result> { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || self.preparing == 0 + || self.references < reserved_refs + || self.commands < reserved_cmds + { + return Err(EINVAL); + } + self.preparing -= 1; + self.references -= 3; + self.commands -= 2; + if self.references == 0 && !self.published { + self.phase = match self.previous_release.take() { + Some(cursor) => LeasePhase::ReleaseSent(cursor), + None => LeasePhase::Released, + }; + } + Ok(self.pending_release()) + } /// Fixed prepopulated pools never submit an asynchronous growth request. /// An incoming growth completion therefore cannot name a live request. pub(crate) fn complete_grow( @@ -1348,7 +1396,13 @@ impl Lease { &mut self, linger: bool, ) -> Result> { - if self.phase != LeasePhase::Ready || self.references < 2 || self.commands < 2 { + let reserved_refs = self.preparing.checked_mul(3).ok_or(EINVAL)?; + let reserved_cmds = self.preparing.checked_mul(2).ok_or(EINVAL)?; + if self.phase != LeasePhase::Ready + || !self.published + || self.references < reserved_refs.saturating_add(2) + || self.commands < reserved_cmds.saturating_add(2) + { return Err(EINVAL); } self.references -= 2; @@ -1372,7 +1426,7 @@ impl Lease { } } pub(crate) fn pending_release(&self) -> Option { - (self.phase == LeasePhase::Ready && self.references == 0).then(|| { + (self.phase == LeasePhase::Ready && self.references == 0 && self.published).then(|| { super::fw::channels::FreeListRelease::new(self.generation, self.owner.buffer_slot) }) } @@ -1443,4 +1497,81 @@ mod capacity_tests { assert_eq!(ids.used(), 0); } } + + fn owner(slot: u32, serial: u64) -> Owner { + Owner { + serial, + epoch: 1, + buffer_slot: slot, + control_va: 0x1000, + ring_va: 0x2000, + cookie: 0x3000, + } + } + + #[test] + fn sibling_render_completes_while_direct_prepare_is_lent() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + // An unactivated preparation cannot complete as a render. + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + lease.retire_prepare().unwrap(); + + // Sibling pair lends the same pool off-lock. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + assert_eq!(lease.generation(), 0); + // Active sibling completes while the direct preparation is still lent. + assert!(lease.complete_render(false).unwrap().is_none()); + // No other published render remains until the lent preparation activates. + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + + lease.retire_prepare().unwrap(); + let release = lease.complete_render(false).unwrap(); + assert!(release.is_some()); + assert!(lease.pending_release().is_some()); + } + + #[test] + fn rollback_after_sibling_completion_exposes_pending_release() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + lease.retire_prepare().unwrap(); + + // Sibling prepares off-lock, active sibling retires, then preparation rolls back. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + assert!(lease.complete_render(false).unwrap().is_none()); + let release = lease.cancel_prepare().unwrap(); + assert!(release.is_some()); + assert!(lease.pending_release().is_some()); + lease.mark_release_sent(4).unwrap(); + assert!(lease.reacquirable()); + } + + #[test] + fn rollback_of_unpublished_generation_preserves_release_witness() { + let owner = owner(129, 1); + let mut lease = Lease::acquire(None, owner).unwrap(); + assert!(lease.cancel_prepare().unwrap().is_none()); + assert!(lease.released()); + assert!(lease.pending_release().is_none()); + + // Publish and send release at cursor 5, then reacquire and observe consumption + // before rolling back the unpublished successor. + lease = Lease::acquire(Some(&lease), owner).unwrap(); + lease.retire_prepare().unwrap(); + assert!(lease.complete_render(false).unwrap().is_some()); + lease.mark_release_sent(5).unwrap(); + + let mut unconsumed = Lease::acquire(Some(&lease), owner).unwrap(); + assert!(unconsumed.cancel_prepare().unwrap().is_none()); + assert!(unconsumed.reacquirable()); + assert!(!unconsumed.released()); + assert_eq!(unconsumed.release_witness(), Some(5)); + + let mut consumed = Lease::acquire(Some(&lease), owner).unwrap(); + consumed.observe_releases(6, 6).unwrap(); + assert!(consumed.cancel_prepare().unwrap().is_none()); + assert!(consumed.released()); + assert_eq!(consumed.release_witness(), None); + } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 49bb19ba89dbb9..97be852c019464 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -1184,6 +1184,29 @@ impl crate::g17::Firmware { }) } + /// Undoes an unpublished pool preparation and flushes any final release + /// exposed when sibling renders completed while the preparation was lent. + fn rollback_render_pool(&mut self, preparation: pools::Preparation) -> Result { + let pending = match self.queues.render.pools.rollback(preparation) { + Ok(pending) => pending, + Err(error) => { + self.primary.state.shared.lose_device_quietly(); + return Err(error); + } + }; + if pending { + match self.release_render_lists() { + Ok(()) => {} + Err(error) if error == EAGAIN => self.primary.state.shared.queue_events(), + Err(error) => { + self.primary.state.shared.lose_device_quietly(); + return Err(error); + } + } + } + Ok(()) + } + /// Events have already been consumed by the caller. Each healthy completion /// services its final pool release before examining the next retained job. fn retire_render_slot( diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 1d6a91a30924aa..47e4e7547afffa 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -276,8 +276,9 @@ impl crate::g17::Firmware { let pair = match self.queues.render.take_pair(slot, owner, packet) { Ok(pair) => pair, Err(error) => { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(buffer)?; + rollback?; return if error == EBUSY { Ok(None) } else { Err(error) }; } }; @@ -339,8 +340,9 @@ impl crate::g17::Firmware { if packet.is_published() { self.queues.render.entry_mut(slot)?.published = true; } else { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(loan.buffer)?; + rollback?; } Ok(()) } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs index 25d81a1976bba3..c3a66941cfbaec 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/pools.rs @@ -24,10 +24,10 @@ pub(super) struct Pools { leases: KVec>, } -/// Undo state cannot leave the device-locked publication transaction. Rollback -/// is permitted only before the packet exposes its first firmware reference. +/// Undo handle for one unpublished `prepare()` call. Rollback undoes only +/// this preparation's references, preserving any sibling completions or +/// control-ring release observations that occurred while lent. pub(super) struct Preparation { - previous: Option, slot: usize, pub(super) generation: u64, } @@ -96,11 +96,7 @@ impl Pools { } let generation = next.generation(); self.leases[slot] = Some(next); - Ok(Preparation { - previous, - slot, - generation, - }) + Ok(Preparation { slot, generation }) } /// Warming validates the incoming owner and stages its descriptor without @@ -170,8 +166,15 @@ impl Pools { lease.retire_prepare() } - pub(super) fn rollback(&mut self, preparation: Preparation) { - self.leases[preparation.slot] = preparation.previous; + /// Rolls back one unpublished preparation without disturbing sibling + /// completions or release observations that occurred while it was lent. + /// Returns whether a final release is now pending on this pool. + pub(super) fn rollback(&mut self, preparation: Preparation) -> Result { + let lease = self.leases[preparation.slot].as_mut().ok_or(EIO)?; + if lease.generation() != preparation.generation { + return Err(EIO); + } + Ok(lease.cancel_prepare()?.is_some()) } /// Preflight a paired retirement before QoS or PB reference accounting. diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 0954496803d9a7..f225d736daa056 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -841,7 +841,7 @@ impl crate::g17::Firmware { if packet.is_published() { self.queues.render.entry_mut(slot)?.published = true; } else if result.is_err() { - self.queues.render.pools.rollback(preparation); + let rollback = self.rollback_render_pool(preparation); self.queues.buffers.release(buffer_id)?; self.queues .render @@ -850,6 +850,7 @@ impl crate::g17::Firmware { .as_mut() .ok_or(EIO)? .discard_prepared(packet)?; + rollback?; } result } diff --git a/tools/asahi/g17-freelist-lease-direct-tests.py b/tools/asahi/g17-freelist-lease-direct-tests.py new file mode 100755 index 00000000000000..6e7f4104614f58 --- /dev/null +++ b/tools/asahi/g17-freelist-lease-direct-tests.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise production freelist Lease and rollback transitions under direct sibling loans. + +Compiles the production Owner, LeasePhase, Lease, control_consumed, +Pools::rollback, and Firmware::rollback_render_pool extracted from +drivers/gpu/drm/asahi/g17/ against host stubs. +""" +import argparse +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth = 1 + end = opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def check(cond, line, msg): + if not cond: + print(f'FAIL line {line}: {msg}', file=sys.stderr) + sys.exit(1) + + +def extract_code(mutation): + freelist = (ROOT / 'freelist.rs').read_text() + pools = (ROOT / 'runtime/render/pools.rs').read_text() + render = (ROOT / 'runtime/render.rs').read_text() + direct = (ROOT / 'runtime/render/direct.rs').read_text() + submit = (ROOT / 'runtime/render/submit.rs').read_text() + + check(direct.count('self.rollback_render_pool(preparation)') == 2, 43, + 'direct.rs must use rollback_render_pool at both rollback sites') + check(submit.count('self.rollback_render_pool(preparation)') == 1, 45, + 'submit.rs must use rollback_render_pool') + + owner = item(freelist, 'pub(crate) struct Owner') + phase = item(freelist, 'enum LeasePhase') + lease = item(freelist, 'pub(crate) struct Lease') + impl_lease = item(freelist, 'impl Lease {') + consumed = item(freelist, 'pub(crate) fn control_consumed(') + pools_rollback = item(pools, 'pub(super) fn rollback(').replace('pub(super) ', 'pub ') + fw_rollback = item(render, 'fn rollback_render_pool(').replace('pools::Preparation', 'Preparation') + + lease_code = '\n\n'.join([ + '#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n' + owner, + '#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n' + phase, + '#[derive(Copy, Clone, Debug)]\n' + lease, + impl_lease, + consumed, + ]) + lease_code = lease_code.replace('pub(crate) ', 'pub ') + lease_code = lease_code.replace('super::fw::channels::FreeListCompletion', 'FreeListCompletion') + lease_code = lease_code.replace('super::fw::channels::FreeListRelease', 'FreeListRelease') + lease_code = lease_code.replace('super::fw::channels::DEVICE_CONTROL_SLOTS', 'DEVICE_CONTROL_SLOTS') + lease_code = lease_code.replace('super::now_ns()', 'now_ns()') + + if mutation == 'reject-preparing-complete': + target = 'if self.phase != LeasePhase::Ready\n || !self.published' + replacement = 'if self.phase != LeasePhase::Ready\n || self.preparing != 0\n || !self.published' + check(target in lease_code, 71, 'vacuous mutation: reject-preparing-complete') + lease_code = lease_code.replace(target, replacement, 1) + elif mutation == 'snapshot-rollback': + target = 'Ok(lease.cancel_prepare()?.is_some())' + replacement = 'self.leases[preparation.slot] = preparation.snapshot; Ok(self.leases[preparation.slot].and_then(|l| l.pending_release()).is_some())' + check(target in pools_rollback, 76, 'vacuous mutation: snapshot-rollback') + pools_rollback = pools_rollback.replace(target, replacement, 1) + elif mutation == 'drop-pending-flush': + target = 'match self.release_render_lists()' + replacement = 'match Ok(())' + check(target in fw_rollback, 81, 'vacuous mutation: drop-pending-flush') + fw_rollback = fw_rollback.replace(target, replacement, 1) + elif mutation == 'drop-doorbell-loss': + target = 'self.primary.state.shared.lose_device_quietly();\n return Err(error);' + replacement = 'return Err(error);' + check(target in fw_rollback, 86, 'vacuous mutation: drop-doorbell-loss') + fw_rollback = fw_rollback.replace(target, replacement, 1) + + return lease_code, pools_rollback, fw_rollback + + +def build_harness(mutation): + lease_code, pools_rollback, fw_rollback = extract_code(mutation) + return f''' +#![allow(dead_code)] +type Error = i32; +type Result = std::result::Result; +const EINVAL: Error = -22; +const EIO: Error = -5; +const EAGAIN: Error = -11; +const EBUSY: Error = -16; +const ETIMEDOUT: Error = -110; +const EOVERFLOW: Error = -75; +const DEVICE_CONTROL_SLOTS: u32 = 256; + +#[derive(Copy, Clone, Debug)] +pub struct FreeListCompletion; + +// Match production FreeListRelease: intentionally does not derive PartialEq. +#[derive(Copy, Clone, Debug)] +pub struct FreeListRelease {{ + pub generation: u64, + pub buffer_slot: u32, +}} + +impl FreeListRelease {{ + pub fn new(generation: u64, buffer_slot: u32) -> Self {{ + Self {{ generation, buffer_slot }} + }} +}} + +fn now_ns() -> u64 {{ 1_000_000 }} + +{lease_code} + +struct Preparation {{ + slot: usize, + generation: u64, + snapshot: Option, +}} + +struct Pools {{ + leases: Vec>, +}} + +impl Pools {{ + fn new() -> Self {{ + Self {{ leases: vec![None; 256] }} + }} + fn prepare(&mut self, slot: usize, owner: Owner) -> Result {{ + let snapshot = self.leases[slot]; + let next = Lease::acquire(snapshot.as_ref(), owner)?; + let generation = next.generation(); + self.leases[slot] = Some(next); + Ok(Preparation {{ slot, generation, snapshot }}) + }} + {pools_rollback} +}} + +struct Shared {{ + events_queued: usize, + lost: bool, +}} +impl Shared {{ + fn queue_events(&mut self) {{ self.events_queued += 1; }} + fn lose_device_quietly(&mut self) {{ self.lost = true; }} +}} +struct PrimaryState {{ shared: Shared }} +struct Primary {{ state: PrimaryState }} +struct Render {{ pools: Pools }} +struct Queues {{ render: Render }} +struct Firmware {{ + queues: Queues, + primary: Primary, + release_calls: usize, + release_result: Result, +}} +impl Firmware {{ + fn new() -> Self {{ + Self {{ + queues: Queues {{ render: Render {{ pools: Pools::new() }} }}, + primary: Primary {{ state: PrimaryState {{ shared: Shared {{ events_queued: 0, lost: false }} }} }}, + release_calls: 0, + release_result: Ok(()), + }} + }} + fn release_render_lists(&mut self) -> Result {{ + self.release_calls += 1; + self.release_result + }} + {fw_rollback} +}} + +fn owner(slot: u32, serial: u64) -> Owner {{ + Owner {{ + serial, + epoch: 1, + buffer_slot: slot, + control_va: 0x1000, + ring_va: 0x2000, + cookie: 0x3000, + }} +}} + +fn main() {{ + let o = owner(129, 1); + + // 1. Sibling completion while direct preparation is lent off-lock. + let mut lease = Lease::acquire(None, o).unwrap(); + assert!(matches!(lease.complete_render(false), Err(EINVAL)), "unactivated prepare cannot complete"); + lease.retire_prepare().unwrap(); + + lease = Lease::acquire(Some(&lease), o).unwrap(); + assert_eq!(lease.generation(), 0); + assert!(lease.complete_render(false).expect("sibling must complete while direct prepare is lent").is_none()); + assert!(matches!(lease.complete_render(false), Err(EINVAL)), "no second published render yet"); + lease.retire_prepare().unwrap(); + let rel = lease.complete_render(false).unwrap().expect("final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + lease.mark_release_sent(3).unwrap(); + lease.observe_releases(3, 3).unwrap(); + assert!(lease.released()); + + // 2. Production Pools::rollback + Firmware::rollback_render_pool after sibling completion. + let mut fw = Firmware::new(); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + fw.rollback_render_pool(p1).unwrap(); + let rel = fw.queues.render.pools.leases[129].unwrap().pending_release().expect("rollback after sibling completion must expose final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + assert_eq!(fw.release_calls, 1, "rollback exposing final release must flush release_render_lists"); + assert!(!fw.primary.state.shared.lost); + + // 3. EAGAIN on release_render_lists queues events without losing device. + let mut fw = Firmware::new(); + fw.release_result = Err(EAGAIN); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + fw.rollback_render_pool(p1).unwrap(); + assert_eq!(fw.release_calls, 1); + assert_eq!(fw.primary.state.shared.events_queued, 1); + assert!(!fw.primary.state.shared.lost); + + // 4. Mailbox/transport error on release_render_lists loses the device so committed releases cannot strand. + let mut fw = Firmware::new(); + fw.release_result = Err(ETIMEDOUT); + let _p0 = fw.queues.render.pools.prepare(129, o).unwrap(); + fw.queues.render.pools.leases[129].as_mut().unwrap().retire_prepare().unwrap(); + let p1 = fw.queues.render.pools.prepare(129, o).unwrap(); + assert!(fw.queues.render.pools.leases[129].as_mut().unwrap().complete_render(false).unwrap().is_none()); + assert_eq!(fw.rollback_render_pool(p1), Err(ETIMEDOUT)); + assert!(fw.primary.state.shared.lost, "transport failure during rollback release must lose device"); + + // 5. Concurrent dual preparations with mixed activate/rollback and completions. + let mut lease = Lease::acquire(None, o).unwrap(); + lease.retire_prepare().unwrap(); + lease = Lease::acquire(Some(&lease), o).unwrap(); + lease = Lease::acquire(Some(&lease), o).unwrap(); + assert!(lease.complete_render(false).unwrap().is_none()); + assert!(matches!(lease.complete_render(false), Err(EINVAL))); + lease.retire_prepare().unwrap(); + assert!(lease.cancel_prepare().unwrap().is_none()); + let rel = lease.complete_render(false).unwrap().expect("final release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + + // 6. Rollback of unpublished fresh generation and reacquire over ReleaseSent. + let mut fresh = Lease::acquire(None, o).unwrap(); + assert!(fresh.cancel_prepare().unwrap().is_none()); + assert!(fresh.released()); + assert!(fresh.pending_release().is_none()); + + let mut sent = Lease::acquire(Some(&fresh), o).unwrap(); + sent.retire_prepare().unwrap(); + assert!(sent.complete_render(false).unwrap().is_some()); + sent.mark_release_sent(7).unwrap(); + + let mut unconsumed = Lease::acquire(Some(&sent), o).unwrap(); + assert!(unconsumed.cancel_prepare().unwrap().is_none()); + assert!(unconsumed.reacquirable()); + assert!(!unconsumed.released()); + assert_eq!(unconsumed.release_witness(), Some(7)); + + let mut consumed = Lease::acquire(Some(&sent), o).unwrap(); + consumed.observe_releases(8, 8).unwrap(); + assert!(consumed.cancel_prepare().unwrap().is_none()); + assert!(consumed.released()); + assert_eq!(consumed.release_witness(), None); + + // 7. Rollback after acquiring a lingering registration exposes its pending release. + let mut lingering = Lease::acquire(None, o).unwrap(); + lingering.retire_prepare().unwrap(); + assert!(lingering.complete_render(true).unwrap().is_none()); + assert!(lingering.lingering().is_some()); + let mut from_linger = Lease::acquire(Some(&lingering), o).unwrap(); + assert_eq!(from_linger.generation(), 0); + let rel = from_linger.cancel_prepare().unwrap().expect("linger rollback must release"); + assert_eq!((rel.generation, rel.buffer_slot), (0, 129)); + + println!("PASS freelist lease direct sibling completion, rollback release, doorbell loss, and witness preservation"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['reject-preparing-complete', 'snapshot-rollback', + 'drop-pending-flush', 'drop-doorbell-loss']) + args = parser.parse_args() + + code = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-freelist-lease-') as tmp: + src = Path(tmp) / 'test.rs' + binary = Path(tmp) / 'test' + src.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(src), '-o', str(binary)], check=True) + result = subprocess.run([str(binary)], capture_output=True, text=True) + if result.stdout: + print(result.stdout.strip()) + if result.stderr: + print(result.stderr.strip(), file=sys.stderr) + sys.exit(result.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 5c68f5e6e20d7c..91440e6642c8ef 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -293,6 +293,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-m5-effort-tests.py': [([], PASS)] + mutations('--mutation', ('m5-ignores-bound',), []), 'g17-firmware-selection-tests.py': [([], PASS)], + 'g17-freelist-lease-direct-tests.py': [([], PASS)] + + mutations('--mutation', ('reject-preparing-complete', 'snapshot-rollback', + 'drop-pending-flush', 'drop-doorbell-loss'), []), 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], 'g17-object-fence-tests.py': [([], PASS)] From 5f1321879f348f5c636f9b208ee816b29241b6a4 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 17:18:10 -0500 Subject: [PATCH 1388/1514] ASoC: apple: t8152-aop-audio: require verified pw0 before rearming sense ring Do not clear spkr running state or stop SenseRing DMA when a pw0 transition fails in spkr_stop_locked() (except on shutdown, which still releases DMA resources while keeping running set). On suspend, still stop and synchronize SenseRing DMA and record resume_run even when pw0 fails, because snd_soc_component_suspend() discards the callback error and proceeds with sleep. Track pw0_verified in SpkrState, clear it before every pwrd attempt so an unconfirmed pwrd failure forces a fresh verified pw0 before rearming, have resume_with_ring() verify pw0 via ensure_pw0() when running or unverified before rearming SenseRing, and fail closed in both resume_with_ring() and start_with_ring() if pw0 still fails so neither prepare nor resume can arm RX on a running or unverified serializer. Add KUnit coverage in spkr_state_requires_verified_pw0_before_rearm and spkr_state_suspend_pw0_failure_and_resume. Signed-off-by: Erik Bourget --- sound/soc/apple/t8152_aop_audio.rs | 566 ++++++++++++++++++++++++++--- 1 file changed, 511 insertions(+), 55 deletions(-) diff --git a/sound/soc/apple/t8152_aop_audio.rs b/sound/soc/apple/t8152_aop_audio.rs index 5fdd6e7e917efa..4180507b619fb8 100644 --- a/sound/soc/apple/t8152_aop_audio.rs +++ b/sound/soc/apple/t8152_aop_audio.rs @@ -239,9 +239,126 @@ impl Service { struct SpkrState { open: bool, running: bool, + /// True only after `pw0 ` has been verified and before any `pwrd` + /// transition attempt. `SenseRing` may only be armed while + /// `!running && pw0_verified`. + pw0_verified: bool, resume_run: bool, } +impl SpkrState { + const fn new() -> Self { + Self { + open: false, + running: false, + pw0_verified: false, + resume_run: false, + } + } + + fn ensure_pw0( + &mut self, + spkr_running: &AtomicFlag, + set_pw0: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || (self.open && !self.pw0_verified) { + self.pw0_verified = false; + set_pw0()?; + self.running = false; + self.pw0_verified = true; + spkr_running.store(false, Relaxed); + } + Ok(()) + } + + fn start_with_ring( + &mut self, + spkr_running: &AtomicFlag, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || !self.pw0_verified { + return Err(EIO); + } + ring_stop(); + ring_start()?; + self.pw0_verified = false; + if let Err(e) = set_pwrd() { + ring_stop(); + return Err(e); + } + self.running = true; + spkr_running.store(true, Relaxed); + Ok(()) + } + + fn stop( + &mut self, + spkr_running: &AtomicFlag, + has_ring: bool, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl FnOnce(), + ) -> Result<()> { + self.ensure_pw0(spkr_running, set_pw0)?; + if has_ring { + ring_stop(); + } + Ok(()) + } + + fn prepare_with_ring( + &mut self, + spkr_running: &AtomicFlag, + quiesce: impl FnOnce() -> Result<()>, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if self.running || !self.pw0_verified { + quiesce()?; + self.pw0_verified = false; + set_pw0()?; + self.running = false; + self.pw0_verified = true; + spkr_running.store(false, Relaxed); + } + self.start_with_ring(spkr_running, ring_stop, ring_start, set_pwrd) + } + + fn suspend( + &mut self, + spkr_running: &AtomicFlag, + has_ring: bool, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl FnOnce(), + ) -> Result<()> { + let was_running = self.running; + let res = self.ensure_pw0(spkr_running, set_pw0); + if has_ring { + ring_stop(); + } + self.resume_run = was_running; + res + } + + fn resume_with_ring( + &mut self, + spkr_running: &AtomicFlag, + set_pw0: impl FnOnce() -> Result<()>, + ring_stop: impl Fn(), + ring_start: impl FnOnce() -> Result<()>, + set_pwrd: impl FnOnce() -> Result<()>, + ) -> Result<()> { + if !mem::take(&mut self.resume_run) || !self.open { + return Ok(()); + } + self.ensure_pw0(spkr_running, set_pw0)?; + self.start_with_ring(spkr_running, ring_stop, ring_start, set_pwrd) + } +} + const SENSE_RATE: u64 = 48000; const NSEC_PER_SEC: u64 = 1_000_000_000; /// 2.5 ms periods (120 frames at 48 kHz), 32 of them: an 80 ms ring, delivered @@ -864,10 +981,12 @@ impl T8152AopAudio { /// since boot attaches `spkr` and raises `pw0 ` so the audio fabric is up /// without disturbing an already-running speaker stream. fn sense_startup(&self) -> Result<()> { - let st = self.spkr_state.lock(); + let mut st = self.spkr_state.lock(); self.attach(&self.spkr)?; if !st.running { + st.pw0_verified = false; self.set_power(&self.spkr, POWER_STATE_PW0)?; + st.pw0_verified = true; } Ok(()) } @@ -875,6 +994,7 @@ impl T8152AopAudio { fn spkr_startup(&self) -> Result<()> { let mut st = self.spkr_state.lock(); self.attach(&self.spkr)?; + st.pw0_verified = false; self.set_power(&self.spkr, POWER_STATE_PW0)?; if let Err(e) = self.mca_up() { let _ = self.set_power(&self.spkr, POWER_STATE_PW0); @@ -882,74 +1002,73 @@ impl T8152AopAudio { } st.open = true; st.running = false; + st.pw0_verified = true; st.resume_run = false; self.spkr.running.store(false, Relaxed); Ok(()) } - /// Arms the sense ring on the stopped serializer, then raises `pwrd`. - fn spkr_start_with_ring(&self, st: &mut SpkrState, ring: &SenseRing) -> Result<()> { - ring.stop(); - ring.start(&self.dev)?; - if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PWRD) { - ring.stop(); - return Err(e); - } - st.running = true; - self.spkr.running.store(true, Relaxed); - Ok(()) - } - /// Speaker prepare: when a sense ring is in use, every playback prepare /// starts a fresh serializer with the ring armed first so offset 0 is slot - /// 0 of a frame. If the serializer was still running (re-prepare after an - /// underrun or resume), `quiesce` mutes the amps before stopping the clock. + /// 0 of a frame. If the serializer was still running or its `pw0 ` state is + /// unconfirmed (re-prepare after an underrun, failed stop, or resume), + /// `quiesce` mutes the amps before stopping the clock. fn spkr_prepare(&self, quiesce: impl FnOnce() -> Result<()>) -> Result<()> { let mut st = self.spkr_state.lock(); let Some(ring) = &self.sense_ring else { if !st.running { + st.pw0_verified = false; self.set_power(&self.spkr, POWER_STATE_PWRD)?; st.running = true; self.spkr.running.store(true, Relaxed); } return Ok(()); }; - if st.running { - quiesce()?; - self.set_power(&self.spkr, POWER_STATE_PW0)?; - st.running = false; - self.spkr.running.store(false, Relaxed); + st.prepare_with_ring( + &self.spkr.running, + quiesce, + || self.set_power(&self.spkr, POWER_STATE_PW0), + || ring.stop(), + || ring.start(&self.dev), + || self.set_power(&self.spkr, POWER_STATE_PWRD), + ) + } + + fn spkr_pw0(&self) -> Result<()> { + if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PW0) { + dev_err!(self.dev, "spkr: pw0 failed: {:?}\n", e); + return Err(e); } - self.spkr_start_with_ring(&mut st, ring) + Ok(()) } - fn spkr_stop_locked(&self, st: &mut SpkrState) { - if st.running { - if let Err(e) = self.set_power(&self.spkr, POWER_STATE_PW0) { - dev_err!(self.dev, "spkr: pw0 failed: {:?}\n", e); - } - st.running = false; - self.spkr.running.store(false, Relaxed); - } - if let Some(ring) = &self.sense_ring { - ring.stop(); - } + fn spkr_stop_locked(&self, st: &mut SpkrState) -> Result<()> { + st.stop( + &self.spkr.running, + self.sense_ring.is_some(), + || self.spkr_pw0(), + || { + if let Some(ring) = &self.sense_ring { + ring.stop(); + } + }, + ) } - fn spkr_hw_free(&self) { + fn spkr_hw_free(&self) -> Result<()> { if self.sense_ring.is_none() { - return; + return Ok(()); } let mut st = self.spkr_state.lock(); - self.spkr_stop_locked(&mut st); + self.spkr_stop_locked(&mut st) } fn spkr_shutdown(&self) { { let mut st = self.spkr_state.lock(); + let _ = self.spkr_stop_locked(&mut st); st.open = false; st.resume_run = false; - self.spkr_stop_locked(&mut st); // Release the ring and its ADMAC channel while the fabric is still // powered (`pw0 `) and before the MCA leaves power down. if let Some(ring) = &self.sense_ring { @@ -959,13 +1078,12 @@ impl T8152AopAudio { self.mca_down(); } - fn spkr_suspend(&self) { - if self.sense_ring.is_none() { - return; - } + fn spkr_suspend(&self) -> Result<()> { + let Some(ring) = &self.sense_ring else { + return Ok(()); + }; let mut st = self.spkr_state.lock(); - st.resume_run = st.running; - self.spkr_stop_locked(&mut st); + st.suspend(&self.spkr.running, true, || self.spkr_pw0(), || ring.stop()) } fn spkr_resume(&self) -> Result<()> { @@ -973,10 +1091,13 @@ impl T8152AopAudio { return Ok(()); }; let mut st = self.spkr_state.lock(); - if !mem::take(&mut st.resume_run) || !st.open { - return Ok(()); - } - self.spkr_start_with_ring(&mut st, ring) + st.resume_with_ring( + &self.spkr.running, + || self.spkr_pw0(), + || ring.stop(), + || ring.start(&self.dev), + || self.set_power(&self.spkr, POWER_STATE_PWRD), + ) } /// `pwrd`: the firmware starts the serializer clocks and the stream. @@ -1684,7 +1805,9 @@ unsafe extern "C" fn be_hw_free( // SAFETY: by the caller's contract. if let Some((data, svc)) = unsafe { be_service(dai, substream) } { if ptr::eq(svc, &data.spkr) { - data.spkr_hw_free(); + if let Err(e) = data.spkr_hw_free() { + return e.to_errno(); + } } } 0 @@ -1712,8 +1835,10 @@ unsafe extern "C" fn be_shutdown( /// Called by ASoC on this driver's registered component. unsafe extern "C" fn asoc_suspend(component: *mut bindings::snd_soc_component) -> i32 { // SAFETY: by the caller's contract. - unsafe { component_data(component) }.spkr_suspend(); - 0 + match unsafe { component_data(component) }.spkr_suspend() { + Ok(()) => 0, + Err(e) => e.to_errno(), + } } /// # Safety @@ -2241,11 +2366,7 @@ impl platform::Driver for T8152AopAudioDriver { cout: Service::new(from_fourcc(b"cout"), "cout", true), cin: Service::new(from_fourcc(b"cin "), "cin", true), spkr: Service::new(from_fourcc(b"spkr"), "spkr", false), - spkr_state <- new_mutex!(SpkrState { - open: false, - running: false, - resume_run: false, - }), + spkr_state <- new_mutex!(SpkrState::new()), sense_ring, mca, cfg, @@ -2404,4 +2525,339 @@ mod tests { // Overflow in unread + pending + incoming fails closed assert!(!sense_ring_has_fe_space(1024, usize::MAX, 0, 1)); } + + #[test] + fn spkr_state_requires_verified_pw0_before_rearm() { + use core::cell::Cell; + + let spkr_running = AtomicFlag::new(false); + let ring_starts = Cell::new(0u32); + let ring_stops = Cell::new(0u32); + let pw0_calls = Cell::new(0u32); + let quiesce_calls = Cell::new(0u32); + + let mut st = SpkrState { + open: true, + running: false, + pw0_verified: true, + resume_run: false, + }; + + // Initial prepare arms ring and enters running (`pw0_verified` clears). + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(spkr_running.load(Relaxed)); + assert_eq!(ring_starts.get(), 1); + assert_eq!(pw0_calls.get(), 0); + + // If AOP rejects `pw0 ` on stop (`hw_free` / `suspend`), running stays + // true, `pw0_verified` stays false, and DMA is not stopped. + let stops_before = ring_stops.get(); + assert_eq!( + st.stop( + &spkr_running, + true, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(spkr_running.load(Relaxed)); + assert_eq!(ring_stops.get(), stops_before); + + // Next prepare fails closed if `pw0 ` still fails, without rearming RX. + assert_eq!( + st.prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ), + Err(EIO) + ); + assert_eq!(quiesce_calls.get(), 1); + assert_eq!(ring_starts.get(), 1); + assert!(st.running); + + // Even if `resume_run` were set while `pw0 ` is unverified and `pw0 ` + // still fails on resume, resume fails closed without arming RX. + st.resume_run = true; + assert_eq!( + st.resume_with_ring( + &spkr_running, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ), + Err(EIO) + ); + assert_eq!(ring_starts.get(), 1); + + // Once `pw0 ` succeeds, prepare verifies it and rearms the ring cleanly. + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_starts.get(), 2); + assert!(st.running); + + // Suspend with failed `pw0 ` stops RX and records restart intent so + // resume must verify `pw0 ` before rearming. + let stops_before = ring_stops.get(); + assert_eq!( + st.suspend( + &spkr_running, + true, + || Err(EIO), + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(ring_stops.get(), stops_before + 1); + assert!(st.resume_run); + assert!(st.running); + assert!(!st.pw0_verified); + + // Suspend with verified `pw0 ` stops DMA, then resume restarts cleanly + // without an extra `pw0 ` call. + assert!(st + .suspend( + &spkr_running, + true, + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + ) + .is_ok()); + assert!(!st.running); + assert!(st.pw0_verified); + assert!(st.resume_run); + assert!(st + .resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_starts.get(), 3); + assert!(st.running); + + // An unconfirmed `pwrd` transition clears `pw0_verified` so the next + // prepare re-verifies `pw0 ` before arming RX again. + assert!(st + .stop( + &spkr_running, + true, + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + ) + .is_ok()); + assert_eq!( + st.prepare_with_ring( + &spkr_running, + || Ok(()), + || Ok(()), + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Err(EIO), + ), + Err(EIO) + ); + assert!(!st.running); + assert!(!st.pw0_verified); + assert_eq!(ring_starts.get(), 4); + assert!(st + .prepare_with_ring( + &spkr_running, + || { + quiesce_calls.set(quiesce_calls.get() + 1); + Ok(()) + }, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || Ok(()), + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 2); + assert_eq!(ring_starts.get(), 5); + } + + #[test] + fn spkr_state_suspend_pw0_failure_and_resume() { + use core::cell::Cell; + + let spkr_running = AtomicFlag::new(true); + let ring_stops = Cell::new(0u32); + let ring_starts = Cell::new(0u32); + let pw0_calls = Cell::new(0u32); + let pwrd_calls = Cell::new(0u32); + + let mut st = SpkrState { + open: true, + running: true, + pw0_verified: false, + resume_run: false, + }; + + // Failed `pw0 ` during suspend still stops/synchronizes RX and records + // restart intent so resume verifies `pw0 ` before rearming. + assert_eq!( + st.suspend( + &spkr_running, + true, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 1); + assert_eq!(ring_stops.get(), 1); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(st.resume_run); + assert!(spkr_running.load(Relaxed)); + + // Resume fails closed without rearming RX if retry `pw0 ` still fails. + assert_eq!( + st.resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || { + pwrd_calls.set(pwrd_calls.get() + 1); + Ok(()) + }, + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 2); + assert_eq!(ring_starts.get(), 0); + assert_eq!(pwrd_calls.get(), 0); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(!st.resume_run); + assert!(spkr_running.load(Relaxed)); + + // Another suspend with `pw0 ` failing still stops RX and records intent; + // when retry `pw0 ` succeeds on resume, RX is cleanly rearmed before `pwrd`. + assert_eq!( + st.suspend( + &spkr_running, + true, + || { + pw0_calls.set(pw0_calls.get() + 1); + Err(EIO) + }, + || ring_stops.set(ring_stops.get() + 1), + ), + Err(EIO) + ); + assert_eq!(pw0_calls.get(), 3); + assert_eq!(ring_stops.get(), 2); + assert!(st.resume_run); + + assert!(st + .resume_with_ring( + &spkr_running, + || { + pw0_calls.set(pw0_calls.get() + 1); + Ok(()) + }, + || ring_stops.set(ring_stops.get() + 1), + || { + ring_starts.set(ring_starts.get() + 1); + Ok(()) + }, + || { + pwrd_calls.set(pwrd_calls.get() + 1); + Ok(()) + }, + ) + .is_ok()); + assert_eq!(pw0_calls.get(), 4); + assert_eq!(ring_stops.get(), 3); + assert_eq!(ring_starts.get(), 1); + assert_eq!(pwrd_calls.get(), 1); + assert!(st.running); + assert!(!st.pw0_verified); + assert!(!st.resume_run); + assert!(spkr_running.load(Relaxed)); + } } From ffe41dd9ce6449d8521039738c7da8fed155c5f0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 09:58:58 +1100 Subject: [PATCH 1389/1514] ci: kernel-release: handle a channel tag that does not exist yet The first edge release on main (run 45683031437) built and passed the QEMU smoke, then failed in 'Move the channel tag': for a missing tag 'gh api .../git/ref/tags/aurora-edge -q .object.sha' exits non-zero and prints the 404 body on stdout, '|| true' kept it, and the body became the old commit id in the compare URL. Keep only a 40-hex commit id from that lookup, in the publish step and in the plan step's last-nightly check (same pattern; the first nightly would have hit it). An empty old id makes the push lease expect no tag, so an API error on an existing tag still fails the push instead of moving the tag. Signed-off-by: Ryan Murray --- .github/workflows/kernel-release.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/kernel-release.yml b/.github/workflows/kernel-release.yml index 26383266ce00a8..e145e075336ef9 100644 --- a/.github/workflows/kernel-release.yml +++ b/.github/workflows/kernel-release.yml @@ -104,7 +104,9 @@ jobs: esac if [ "$channel" = nightly ]; then sha=$(gh api "repos/$REPO/git/ref/heads/main" -q .object.sha) - last=$(gh api "repos/$REPO/git/ref/tags/aurora-nightly" -q .object.sha 2>/dev/null || true) + # On a missing tag (the first nightly) gh api exits non-zero and + # prints the 404 body on stdout, so keep only a commit id. + last=$(gh api "repos/$REPO/git/ref/tags/aurora-nightly" -q .object.sha 2>/dev/null | grep -xE '[0-9a-f]{40}' || true) if [ "$EVENT" = schedule ] && [ "$last" = "$sha" ]; then echo "main is still at the last nightly ($sha); nothing to build" build=false @@ -324,7 +326,11 @@ jobs: # Channel tags are always addressed as refs/tags/, never by the # bare name, which may also be a branch. They only move forward: the # new commit must contain the tagged one (a rewritten main stops here). - old=$(gh api "repos/$GH_REPO/git/ref/tags/$tag" -q .object.sha 2>/dev/null || true) + # On a missing tag (a channel's first release) gh api exits non-zero + # and prints the 404 body on stdout, so keep only a commit id. Any + # other API error also leaves old empty; the lease below then expects + # no tag, so the push fails rather than moving an existing one. + old=$(gh api "repos/$GH_REPO/git/ref/tags/$tag" -q .object.sha 2>/dev/null | grep -xE '[0-9a-f]{40}' || true) if [ -n "$old" ]; then status=$(gh api "repos/$GH_REPO/compare/$old...$SHA" -q .status) case "$status" in From 944b9be10bc772ee35d5740114506a0c1a29bd98 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 08:38:31 +1100 Subject: [PATCH 1390/1514] drm/apple: afk: retire a superseded singleton AV service On the classic AV endpoint, DCP firmware 27.2 announces its DCPAVSimpleVideoInterface and DCPAVAudioInterface again on fresh channels every time the display comes back (DPMS on, wake, re-attach) and never closes the previous channels. The old instances stayed enabled, so their slots were never reclaimed. After eight attaches a Mac mini (M2) used all 16 service slots of the endpoint, logged "no reusable service slots" and lost monitor audio until reboot. The compact path already replaces such re-announced services in place (afk_compact_slot()). Do the same on the classic path for services that are singletons, one live instance per endpoint: an announcement on a new channel retires the previous instance, and its slot is reclaimed once its last user lets go. The successor's init takes over the service's state, as before. Firmware that closes the old channel first is unaffected: its instance is already torn down. Mark the classic AV video and audio interfaces as singletons, and add a KUnit test that re-announces them many more times than there are slots. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk-service-test.c | 70 +++++++++++++++++++ drivers/gpu/drm/apple/afk.c | 10 +++ drivers/gpu/drm/apple/afk.h | 28 ++++++++ drivers/gpu/drm/apple/av.c | 2 + .../selftests/drivers/gpu/apple-dcp/edid.py | 4 +- 5 files changed, 112 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/afk-service-test.c b/drivers/gpu/drm/apple/afk-service-test.c index 06db01a8f84d3f..ef0920a28dbe86 100644 --- a/drivers/gpu/drm/apple/afk-service-test.c +++ b/drivers/gpu/drm/apple/afk-service-test.c @@ -266,11 +266,81 @@ static void afk_service_declined_channel_test(struct kunit *test) KUNIT_EXPECT_TRUE(test, afk_service_retired(service, 3)); } +static const struct apple_epic_service_ops singleton_video_ops = { + .name = "singleton-video", + .reusable = true, + .singleton = true, +}; + +static const struct apple_epic_service_ops singleton_audio_ops = { + .name = "singleton-audio", + .reusable = true, + .singleton = true, +}; + +/* + * The firmware announces its AV video and audio interfaces again on fresh + * channels on every display attach and never closes the old ones. Announce + * them as the endpoint's receive path does: supersede, then take the first + * reclaimable slot. The superseded audio instance stays pinned by its owner + * until the successor's init drops it. + */ +static struct apple_epic_service * +afk_test_announce(struct apple_epic_service *slots, unsigned int nr, + const struct apple_epic_service_ops *ops, u32 channel) +{ + unsigned int i; + + for (i = 0; i < nr; i++) + afk_service_supersede(&slots[i], ops, channel); + for (i = 0; i < nr; i++) + if (afk_service_reinit(&slots[i], NULL, ops, channel)) + return &slots[i]; + return NULL; +} + +static void afk_service_singleton_reannounce_test(struct kunit *test) +{ + struct apple_epic_service *slots, *video, *audio, *owned = NULL; + const unsigned int nr = 4; + unsigned int i; + u32 channel = 5; + + slots = kunit_kcalloc(test, nr, sizeof(*slots), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, slots); + for (i = 0; i < nr; i++) + spin_lock_init(&slots[i].lock); + + /* Many more attaches than slots: the budget stays bounded. */ + for (i = 0; i < 4 * AFK_MAX_CHANNEL; i++, channel += 4) { + video = afk_test_announce(slots, nr, &singleton_video_ops, channel); + KUNIT_ASSERT_NOT_NULL(test, video); + KUNIT_EXPECT_TRUE(test, afk_service_matches(video, channel)); + audio = afk_test_announce(slots, nr, &singleton_audio_ops, channel + 2); + KUNIT_ASSERT_NOT_NULL(test, audio); + /* The audio owner pins the new instance and lets go of the old one. */ + KUNIT_ASSERT_PTR_EQ(test, afk_service_get(audio), audio); + if (owned) + afk_service_put(owned); + owned = audio; + } + + /* A different service is never superseded by a singleton announcement. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &singleton_video_ops, 1)); + /* Nor is the instance announced on the same channel. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &singleton_audio_ops, + owned->channel)); + /* Only singleton services are superseded. */ + KUNIT_EXPECT_FALSE(test, afk_service_supersede(owned, &reusable_ops, 1)); + afk_service_put(owned); +} + static struct kunit_case afk_service_cases[] = { KUNIT_CASE(afk_service_admission_test), KUNIT_CASE(dptx_service_identity_test), KUNIT_CASE(dptx_service_duplicate_close_test), KUNIT_CASE(afk_service_many_generations_test), + KUNIT_CASE(afk_service_singleton_reannounce_test), KUNIT_CASE(afk_service_reader_pin_test), KUNIT_CASE(afk_service_pending_reply_test), KUNIT_CASE(afk_service_completed_reader_test), diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 096d1685ae03b5..84532778e99980 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1885,6 +1885,16 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, goto free; } + for (ch_idx = 0; ch_idx < ep->num_channels; ch_idx++) { + struct apple_epic_service *old = &ep->services[ch_idx]; + + if (afk_service_supersede(old, ops, channel)) { + dev_info(ep->dcp->dev, + "AFK[ep:%02x]: %s on channel %u supersedes channel %u\n", + ep->endpoint, service_name, channel, old->channel); + afk_remove_service_debugfs(old); + } + } for (ch_idx = 0; ch_idx < AFK_MAX_CHANNEL; ch_idx++) { struct apple_epic_service *candidate = &ep->services[ch_idx]; diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index fef5067af705ec..4d8c41ccdae17d 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -258,6 +258,34 @@ static inline void afk_service_retire_channel(struct apple_epic_service *service spin_unlock_irqrestore(&service->lock, flags); } +/* + * A singleton service has one live instance per endpoint. The firmware + * announces it again on a fresh channel when the display is attached again, + * without closing the previous channel (as for compact services, see + * afk_compact_slot()). The announcement on @channel then supersedes + * @service: retire it, so that its slot is reclaimed once its last user + * lets go. The successor's init takes over the service's state. + */ +static inline bool afk_service_supersede(struct apple_epic_service *service, + const struct apple_epic_service_ops *ops, + u32 channel) +{ + unsigned long flags; + bool superseded; + + if (!ops->singleton) + return false; + spin_lock_irqsave(&service->lock, flags); + superseded = service->ops == ops && !service->torndown && + service->channel != channel; + if (superseded) { + service->enabled = false; + service->torndown = true; + } + spin_unlock_irqrestore(&service->lock, flags); + return superseded; +} + static inline bool afk_service_matches(struct apple_epic_service *service, u32 channel) { diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index f685bce973e5a0..f285070f33f3e6 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -1060,12 +1060,14 @@ static const struct apple_epic_service_ops avep_ops[] = { { .name = "DCPAVSimpleVideoInterface", .reusable = true, + .singleton = true, .init = av_interface_init, .teardown = av_interface_teardown, }, { .name = "DCPAVAudioInterface", .reusable = true, + .singleton = true, .init = av_audiosrv_init, .report = av_audiosrv_report, .teardown = av_audiosrv_teardown, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index db428743d7d12a..6fbf19d2a6329f 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -85,7 +85,7 @@ def function(file,signature): struct apple_dcp;struct apple_dcp_afkep;struct apple_epic_service; void afk_service_retry(struct apple_dcp_afkep *ep); /* open_later: a firmware 27 panel service that sends its own OPEN; none is here. */ -struct apple_epic_service_ops { char name[32];bool reusable,optional,open_later;void (*init)(struct apple_epic_service *,const char *,const char *,s64);int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);void (*teardown)(struct apple_epic_service *); }; +struct apple_epic_service_ops { char name[32];bool reusable,optional,open_later,singleton;void (*init)(struct apple_epic_service *,const char *,const char *,s64);int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);void (*teardown)(struct apple_epic_service *); }; struct epic_cmd_info { u16 tag;u8 type;size_t reply_length,reply_len;bool reply_len_valid;void *rxbuf,*txbuf;dma_addr_t rxbuf_dma,txbuf_dma;size_t rxlen,txlen;u32 retcode;bool done,free_on_ack;int *completion; }; struct apple_epic_service { struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops; @@ -183,7 +183,7 @@ def function(file,signature): function('epic/dpavservep.c','static void dcpavserv_teardown('),function('epic/dpavservep.c','void dpavservep_detach('), function('afk.c','static const struct apple_epic_service_ops *\nafk_match_service('), function('afk.c','static struct apple_epic_service *afk_epic_find_service('), - function('afk.h','static inline bool afk_service_retired('),function('afk.c','static bool afk_epic_channel_retired('), + function('afk.h','static inline bool afk_service_retired('),function('afk.h','static inline bool afk_service_supersede('),function('afk.c','static bool afk_epic_channel_retired('), function('afk.c','static void afk_discard_pending_open('),function('afk.c','static void afk_retry_service_init('),function('afk.c','static void afk_service_worker('),function('afk.c','static void afk_recv_handle_init('), function('epic/dpavservep.c','static int dcpdpserv_prepare('), function('epic/dpavservep.c','static void dcpdpserv_teardown('),function('afk.c','static void afk_recv_handle_teardown('), From 7baf07b4ae72225e7336bdf0a835f4e07f680d7b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 10:04:48 +1100 Subject: [PATCH 1391/1514] wifi: brcmfmac: pcie: save the config only where the reset restores it The watchdog reset saved the function's config space on every chip but restored it only when the reset also resets PCIe function 0 (chipcommon rev >= 65). On an older chip pdev->state_saved then stayed set from the probe, so the next D3 suspend skipped saving the live config and resume restored the probe-time copy. A failed save could also leave state_saved set. Save only on chips whose reset puts the config space back to defaults, check the result as the suspend paths in this file do, clear state_saved if the save failed, and restore only a state that was saved. Signed-off-by: Ryan Murray --- .../broadcom/brcm80211/brcmfmac/pcie.c | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c index f97aaf324db14e..19f244397e00ef 100644 --- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c +++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/pcie.c @@ -780,6 +780,7 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) BRCMF_PCIE_CFGREG_REG_BAR3_CONFIG }; bool fn_reset = false; + bool saved = false; u32 i; u32 val; u32 lsc; @@ -793,8 +794,21 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) * chip defaults: e.g. the resizable BAR 2 drops from the size the PCI * core assigned to 8 MiB. Save what the PCI core programmed, before * ASPM is turned off for the reset, so it can be put back afterwards. + * Older chips keep their config space, so save nothing there: a saved + * state left behind would stand in for the live one at the next + * suspend. */ - pci_save_state(devinfo->pdev); + core = brcmf_chip_get_chipcommon(devinfo->ci); + if (core->rev >= 65) { + int err = pci_save_state(devinfo->pdev); + + if (err) { + pci_err(devinfo->pdev, "failed to save PCI state: %d\n", err); + devinfo->pdev->state_saved = false; + } else { + saved = true; + } + } /* Disable ASPM */ brcmf_pcie_select_core(devinfo, BCMA_CORE_PCIE2); @@ -843,9 +857,9 @@ static void brcmf_pcie_reset_device(struct brcmf_pciedev_info *devinfo) * with the reset defaults while the core still holds the assigned * values, and the next pci_restore_state() (system resume) rewrites * them on a live, bus-mastering function: BAR 2 changes size under - * running firmware. + * running firmware. Only a state saved above is put back. */ - if (fn_reset) + if (fn_reset && saved) pci_restore_state(devinfo->pdev); core = brcmf_chip_get_core(devinfo->ci, BCMA_CORE_PCIE2); From 5938e9e5e9b63e58941ece4cf271f2b48c597e0e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 10:33:07 +1100 Subject: [PATCH 1392/1514] tools/asahi: dcpext26-startup-tests: model the singleton supersede afk_recv_handle_init() now supersedes the previous instance of a singleton service and drops its debugfs entry. Give the host model the ops flag, the helper and a debugfs stub, as the apple-dcp model has. Signed-off-by: Ryan Murray --- tools/asahi/dcpext26-startup-tests.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/asahi/dcpext26-startup-tests.py b/tools/asahi/dcpext26-startup-tests.py index c896fb37156669..6d2fba8014404f 100644 --- a/tools/asahi/dcpext26-startup-tests.py +++ b/tools/asahi/dcpext26-startup-tests.py @@ -91,7 +91,7 @@ def run(name,code,reject=False): #define MAX_PENDING_CMDS 16 struct dcp_parse_ctx {void *dcp;const void *blob;u32 pos,len;}; struct apple_epic_service;struct apple_dcp_afkep; -struct apple_epic_service_ops {const char *name;bool reusable,optional,open_later;int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);}; +struct apple_epic_service_ops {const char *name;bool reusable,optional,open_later,singleton;int (*prepare)(struct apple_epic_service *,const char *,const char *,s64);int (*revalidate)(struct apple_epic_service *,const char *,const char *,s64);void (*init)(struct apple_epic_service *,const char *,const char *,s64);void (*teardown)(struct apple_epic_service *);void (*init_props)(struct apple_epic_service *,s64,const void *,size_t);}; struct apple_epic_service {struct apple_dcp_afkep *ep;const struct apple_epic_service_ops *ops;bool enabled,torndown,pending_open,defer_start;unsigned users;int lock;u32 channel;void *cookie;const char *pending_name,*pending_class;s64 pending_unit;int cmd_map[1];}; struct dptx_port {struct apple_epic_service *service;s64 unit;bool enabled,connected;int enable_completion;}; struct apple_dcp {const void *push_out_prefill;bool native,ext26_services_open,v27_j714s,v27_sleep_transport,dcpext;int fw_compat,index,dptx_controller_ready;struct {unsigned num_dptx_ports;int iomfb_method_profile,firmware_compat;bool afk_announced_names;} hw;struct dptx_port dptxport[2];void *dev;struct apple_dcp_afkep *systemep,*ibootep,*dptx_controller_ep,*dcpavservep,*dptxep,*ext26_aux[3];}; @@ -108,6 +108,7 @@ def run(name,code,reject=False): static unsigned opened[256][16],queued,published; static int open_error; static void afk_populate_service_debugfs(struct apple_epic_service *s){} +static void afk_remove_service_debugfs(struct apple_epic_service *s){} static void afk_recv_handle_teardown(struct apple_dcp_afkep *e,u32 c){} static void afk_retry_service_init(struct apple_dcp_afkep *ep); void afk_service_retry(struct apple_dcp_afkep *ep); @@ -119,7 +120,7 @@ def run(name,code,reject=False): # Drop the audio-only helper region from the extracted prefix. identity=re.sub(r'#if IS_ENABLED\(CONFIG_DRM_APPLE_AUDIO\).*?#endif','',identity,flags=re.S) identity+=block(parser,'struct iterator {')+'\n'+fn(parser,'iterator_begin')+'\n'+fn(parser,'parse')+'\n'+fn(parser,'parse_epic_service_init')+'\n' -for name in ['afk_service_reclaimable','afk_service_reinit','afk_service_discard','afk_service_publish','afk_service_matches']: +for name in ['afk_service_reclaimable','afk_service_reinit','afk_service_discard','afk_service_publish','afk_service_matches','afk_service_supersede']: identity+=fn(h,name)+'\n' identity+=fn(dptx,'dptx_native_controllers_ready')+'\n'+fn(dptx,'dptx_native_controller_prepare')+'\n'+fn(dptx,'dptx_controller_service_init')+'\n' for name in ['afk_match_service','afk_epic_find_service','afk_discard_pending_open','afk_retry_service_init','afk_service_retry']: From cd4666bbd23e0c4ef9127464c482b93c95e4a510 Mon Sep 17 00:00:00 2001 From: Jeff Queisser Date: Wed, 25 Nov 2026 13:28:21 -0800 Subject: [PATCH 1393/1514] accel/ane: bound each H15/H16/H17 task's DMAs on its own words The DMA check also carried a register image across the tasks of a stream and, after each task, checked every base written so far against the geometry in force then. That models an engine that keeps the registers a task leaves out. The engine starts each task from the reset values: on the J775D's H17, a second task that leaves out the output base or a row stride runs with the reset value 0, and one that leaves out the widths does not run with the first task's. Valid programs rely on this: they may leave out any word that holds its reset value, even after an earlier task wrote another value there. So the carried image refused eight programs of the corpus below that stay inside their buffers. An L2-resident task that takes its input from L2 was checked against the earlier task's input base. A task that leaves a group count or a plane stride at its reset value was checked with the earlier task's value. Check each task on its own words over the reset values only. No base can reach a later task, because every DMA a task enables must have its base in that task. That rule now covers the coefficient DMA too, which only the carried image bounded, because lookup-table tasks set its lane configuration words without a base. Those lanes are idle: 0x20 in the low half (0x30020 and 0x50020 in the corpus). Any other non-zero lane word enables the DMA and needs the base. Before this, a one-task stream could enable the coefficient DMA without a base and nothing checked it. Walk the stream with the header words of the program's target. The DMA check had its own copy of the task framing, fixed at the nine header words of H16 and H17. H15 tasks have eight, so on an H15 stream it read each task's first record as a header word and the records after it out of step: a row stride written in that first record went unchecked, and the rest of the task could be hidden in what it read as L2 values. The structural gate, the HWX validator's relocation check and the DMA check each walked the framing in their own code. They now share one walk, ane_hx_task_frame(), and one record count, with the header words that the HWX target gives, which struct ane_h16_hwx now records for the DMA check. A word of the checked blocks written twice in one task must repeat its value, and a base its slot too. An H17 program writes source 2's base twice, unchanged. The check kept only the last write, so a first write could name any address or stride unchecked. No program in the corpus writes any other word twice. A configuration word relocated on the slot 4 custom BAR takes the custom BAR value, which the check does not see, so it must already enable its DMA. Zero, or an idle lane, could become a DMA the check saw as off. Every such word in the corpus enables its DMA. Refuse a zero width on an enabled input or output stream instead of reading it as one. A task without widths stalled the J775D's H17, and an H16 matmul without them computed its full 256-wide result, so the kernel cannot bound what a zero width moves. For the same reason a zero depth, group or output channel count is read as one only when its stride is zero, and a coefficient lane of size 0 is refused: at the end of its buffer, its offset passed with nothing to read. No program in the corpus has any of these. Over 224 programs built with mil-hwx-compiler, 222 pass. Two are refused: - The H16G chain example s_mm_256 reads its second output channel group 0x40000 bytes past its coefficient base, beyond the 0x20000-byte buffer the first task fills. The other matmul form of the same size strides 0x10000, where those coefficients are. Bit 2 of common word 0x3c, set only in this form, does not change the unit: the attention fixture's two coefficient DMAs with that bit set read exactly what an earlier task wrote. - The H16G fixture matmul_gelu_256 leaves its widths out. The other fixtures in the corpus include them. The corpus has no H15 program; the H15 framing is covered by KUnit. Signed-off-by: Jeff Queisser --- drivers/accel/ane/ane_h16_hwx.c | 38 +- drivers/accel/ane/ane_h16_hwx.h | 2 + drivers/accel/ane/ane_h16_program.c | 2 +- drivers/accel/ane/ane_h16_tasks.h | 351 ++++++++++------- drivers/accel/ane/ane_h16_tasks_test.c | 518 ++++++++++++++++++++----- 5 files changed, 657 insertions(+), 254 deletions(-) diff --git a/drivers/accel/ane/ane_h16_hwx.c b/drivers/accel/ane/ane_h16_hwx.c index c8b6dfeeadda1c..2c5d72671c738a 100644 --- a/drivers/accel/ane/ane_h16_hwx.c +++ b/drivers/accel/ane/ane_h16_hwx.c @@ -392,7 +392,8 @@ static int hwx_program(struct hwx_parser *p) if (!memcmp(c, expected, length)) { ret = ane_hx_task_stream_validate_hdr(p->bytes + info->text.offset, info->text.size, info->tasks, prologue, - t->header_words, &record_limit, &final_end); + info->task_header_words, &record_limit, + &final_end); /* This compiler hint need not equal the encoded record count. */ if (!ret && (!records || records > record_limit)) ret = -ENOEXEC; @@ -599,31 +600,23 @@ static int hwx_symbols(struct hwx_parser *p) static bool hwx_relocations_in_payload(const struct hwx_parser *p, unsigned long *sites) { const u8 *text = p->bytes + p->info.text.offset; - size_t pos = 16; + struct ane_hx_task t; + size_t pos = 16, record; + u32 count; + int ret; while (pos < p->info.text.size) { - u32 words = (get_unaligned_le32(text + pos) >> 16) & 0x7ff; - size_t end, record; - - if (!words) { - pos += 16; + ret = ane_hx_task_frame(text, p->info.text.size, pos, + p->info.task_header_words, &t); + if (ret < 0) + return false; + pos = t.next; + if (!ret) continue; + for (record = t.rec; record < t.end; record += 4 + count * 4) { + count = ane_hx_record_count(get_unaligned_le32(text + record)); + bitmap_clear(sites, record / 4 + 1, count); } - end = pos + words * 4; - record = pos + p->target->header_words * 4; - if ((get_unaligned_le32(text + pos + (p->target->header_words - 1) * 4) & 3) == 3) - record += 4; - while (record < end) { - u32 header = get_unaligned_le32(text + record); - u32 count = header & BIT(31) ? - 1 + hweight32((header >> 15) & 0xffff) : - 1 + ((header >> 15) & 0x3f); - - record += 4; - bitmap_clear(sites, record / 4, count); - record += count * 4; - } - pos = ALIGN(end, 16); } return bitmap_empty(sites, p->info.text.size / 4); } @@ -659,6 +652,7 @@ int ane_h16_hwx_validate(const void *bytes, size_t size, struct ane_h16_hwx *inf p->size = size; p->command_end = 32 + (size_t)length; p->info.subtype = target->subtype; + p->info.task_header_words = target->header_words; for (i = 0; i < count; i++) { u32 cmd, len; diff --git a/drivers/accel/ane/ane_h16_hwx.h b/drivers/accel/ane/ane_h16_hwx.h index 7b2fe402cad722..eb1022a8928ed5 100644 --- a/drivers/accel/ane/ane_h16_hwx.h +++ b/drivers/accel/ane/ane_h16_hwx.h @@ -54,6 +54,8 @@ struct ane_h16_hwx { struct ane_h16_hwx_section text, constants, kernel, scratch; /* Target; a backend accepts only its own engine's subtype. */ u32 subtype; + /* Fixed words per task of the target's task stream (ane_hx_task_frame()). */ + u32 task_header_words; struct ane_h16_hwx_surface surfaces[ANE_H16_SURFACES]; u32 surface_count; u32 tasks; diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index de6d90d4c64430..1d88691cfa0645 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -467,7 +467,7 @@ int ane_h16_operation_validate(const struct ane_h16_hwx_snapshot *snapshot, if (hwx->kernel.size && !kernel_bound) goto out; ret = ane_hx_task_stream_dma_validate((const u8 *)snapshot->bytes + hwx->text.offset, - hwx->text.size, bound); + hwx->text.size, hwx->task_header_words, bound); out: kfree(bound); return ret; diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h index bf49fb92ab558e..f4560e6eb64ff7 100644 --- a/drivers/accel/ane/ane_h16_tasks.h +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -36,62 +36,97 @@ static inline bool ane_h16_register_valid(u32 word) return false; } +/* Values after record header @h: a dense run, or one plus a scatter mask's bits. */ +static inline u32 ane_hx_record_count(u32 h) +{ + return h & BIT(31) ? 1 + hweight32((h >> 15) & 0xffff) : ((h >> 15) & 0x3f) + 1; +} + /* * A stream opens with a 16-byte frame: little-endian u32 @prologue, then * twelve reserved zero bytes. H15/H16/H17 programs share this framing with - * @header_words fixed words per task (8 on H15, 9 on H16 and H17). The last - * task may end at the end of the section; every other task is padded with - * zeros to 16 bytes. This structural gate does not replace container/tensor/ - * aperture validation. + * @header_words fixed words per task (8 on H15, 9 on H16 and H17, from the + * HWX target), the task's length in words in bits 16-26 of the first. Low + * bits 3 in the last fixed word add one more header word. The last task may + * end at the end of the section; every other task is padded with zeros to + * 16 bytes, and a 16-byte zero block may stand between tasks. + * + * ane_hx_task_frame() is the one walk of this framing: the structural gate, + * the relocation check of the HWX validator and the DMA bound all step + * through a stream with it, so they cannot disagree on where a task's + * records start. + */ +struct ane_hx_task { + size_t rec, end; /* the task's records */ + size_t next; /* the next task or zero block */ +}; + +/* + * Frame the task or zero block at @pos of a stream of @size bytes. Returns 1 + * for a task, 0 for a zero block (only @t->next is set) and -ENOEXEC for a + * frame that does not fit or is not padded with zeros. + */ +static inline int ane_hx_task_frame(const u8 *p, size_t size, size_t pos, + unsigned int header_words, struct ane_hx_task *t) +{ + u32 words; + + if (!header_words || pos > size || size - pos < 16) + return -ENOEXEC; + words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; + if (!words) { + t->next = pos + 16; + return memchr_inv(p + pos, 0, 16) ? -ENOEXEC : 0; + } + if (words < header_words || words > (size - pos) / 4) + return -ENOEXEC; + t->end = pos + words * 4; + if ((get_unaligned_le32(p + pos + (header_words - 1) * 4) & 3) == 3) + header_words++; + if (words < header_words) + return -ENOEXEC; + t->rec = pos + header_words * 4; + t->next = t->end == size ? size : ALIGN(t->end, 16); + if (t->next > size || memchr_inv(p + t->end, 0, t->next - t->end)) + return -ENOEXEC; + return 1; +} + +/* + * The structural gate over the framing above. Every record names registers + * of the H16 image. This gate does not replace container/tensor/aperture + * validation. */ static inline int ane_hx_task_stream_validate_hdr(const void *text, size_t size, u32 expected_tasks, - u32 prologue, unsigned int fixed_header_words, + u32 prologue, unsigned int header_words, u32 *record_limit, size_t *final_end) { const u8 *p = text; size_t pos = 16, last = 0; u32 tasks = 0, limit = 0; - if (!p || !expected_tasks || !fixed_header_words || size < 16 || - size > ANE_H16_TASK_MAX || (size & 3) || + if (!p || !expected_tasks || size < 16 || size > ANE_H16_TASK_MAX || (size & 3) || get_unaligned_le32(p) != prologue || memchr_inv(p + 4, 0, 12)) return -ENOEXEC; while (pos < size) { - u32 words, header_words = fixed_header_words; - size_t end, padded, rec; + struct ane_hx_task t; + int ret = ane_hx_task_frame(p, size, pos, header_words, &t); + size_t rec; - if (size - pos < 16) - return -ENOEXEC; - words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; - if (!words) { - if (memchr_inv(p + pos, 0, 16)) - return -ENOEXEC; - pos += 16; + if (ret < 0) + return ret; + pos = t.next; + if (!ret) continue; - } - if (words < fixed_header_words || words > (size - pos) / 4) - return -ENOEXEC; - end = pos + words * 4; - if ((get_unaligned_le32(p + pos + (fixed_header_words - 1) * 4) & 3) == 3) - header_words++; - if (words < header_words) - return -ENOEXEC; - rec = pos + header_words * 4; /* A record needs at least one header and one register value. */ - limit += (end - rec) / 8; - while (rec < end) { - u32 h = get_unaligned_le32(p + rec); - u32 base = h & 0x7fff; - u32 mask = (h >> 15) & 0xffff; - u32 count, i; + limit += (t.end - t.rec) / 8; + for (rec = t.rec; rec < t.end; ) { + u32 h = get_unaligned_le32(p + rec), count = ane_hx_record_count(h); + u32 base = h & 0x7fff, mask = (h >> 15) & 0xffff, i; rec += 4; - if (h & BIT(31)) - count = 1 + hweight32(mask); - else - count = ((h >> 15) & 0x3f) + 1; - if (count > (end - rec) / 4 || !ane_h16_register_valid(base)) + if (count > (t.end - rec) / 4 || !ane_h16_register_valid(base)) return -ENOEXEC; if (h & BIT(31)) { for (i = 0; i < 16; i++) @@ -105,11 +140,7 @@ ane_hx_task_stream_validate_hdr(const void *text, size_t size, u32 expected_task } rec += count * 4; } - padded = end == size ? end : ALIGN(end, 16); - if (padded > size || memchr_inv(p + end, 0, padded - end)) - return -ENOEXEC; - last = end; - pos = padded; + last = t.end; if (++tasks > expected_tasks) return -ENOEXEC; } @@ -198,6 +229,29 @@ static inline bool ane_hx_dma_config(u32 addr) (addr >= 0x5520 && addr <= 0x555c); } +/* + * Whether configuration word @w at @addr enables its DMA: any non-zero value + * except a coefficient lane's idle form, 0x20 in the low half, which + * lookup-table tasks write for the lanes they do not fetch. + */ +static inline bool ane_hx_dma_config_on(u32 addr, u32 w) +{ + return w && !(addr >= 0x5520 && addr <= 0x555c && (w & 0xffff) == 0x20); +} + +/* + * A count of @n steps @stride apart. Only a zero stride lets a zero count be + * read as one: the kernel cannot bound what a zero count moves when the + * engine steps by the stride. + */ +static inline int ane_hx_dma_count(u32 n, u32 stride, u64 *count) +{ + if (!n && stride) + return -ENOEXEC; + *count = max(1U, n); + return 0; +} + /* Byte address of value @i of the record with header @h. */ static inline u32 ane_hx_record_addr(u32 h, u32 i) { @@ -211,37 +265,35 @@ static inline u32 ane_hx_record_addr(u32 h, u32 i) return (base + bit + 1) * 4; } -static inline u32 ane_hx_record_count(u32 h) -{ - return h & BIT(31) ? 1 + hweight32((h >> 15) & 0xffff) : ((h >> 15) & 0x3f) + 1; -} - /* * Bytes an input or output DMA stream touches from its base: the last * element of the last row, plane, depth slice and group. Interleave k packs * k channels into each element, so a plane holds k channels (the measured * matmul staging writes 128 channels interleaved 8 as 16 planes of 2 KiB, its - * exact scratch). + * exact scratch). The row, plane, depth and group strides follow the base; + * a zero height, channel, depth or group count is one only with a zero + * stride (ane_hx_dma_count()). */ static inline int ane_hx_dma_tile(const u32 *img, u32 base, u64 *extent) { static const u8 bytes[] = { 1, 1, 2, 4 }; bool dst = base == 0x5108; u32 stride = base + 8, format = dst ? 0x5138 : base == 0x4d10 ? 0x4d68 : 0x4d6c; - u32 dim = dst ? 0x14 : 0x4, f = img[ane_hx_dma_index(format)]; - u64 k = max(1U, (f >> 24) & 0xf), n[5], sum, term; + u32 dim = dst ? 0x14 : 0x4, f = img[ane_hx_dma_index(format)], step; + u64 k = max(1U, (f >> 24) & 0xf), n, sum, term; unsigned int i; - for (i = 0; i < 4; i++) - n[i] = max(1U, img[ane_hx_dma_index(dim + 4 * i)]); - n[4] = max(1U, img[ane_hx_dma_index(0x24)]); - n[2] = DIV_ROUND_UP(n[2], k); - sum = n[0] * bytes[(f >> 12) & 3] * k; - for (i = 1; i < 5; i++) - if (check_mul_overflow(n[i] - 1, (u64)img[ane_hx_dma_index(stride + 4 * (i - 1))], - &term) || + sum = (u64)max(1U, img[ane_hx_dma_index(dim)]) * bytes[(f >> 12) & 3] * k; + for (i = 1; i < 5; i++) { + step = img[ane_hx_dma_index(stride + 4 * (i - 1))]; + if (ane_hx_dma_count(img[ane_hx_dma_index(i < 4 ? dim + 4 * i : 0x24)], step, &n)) + return -ENOEXEC; + if (i == 2) + n = DIV_ROUND_UP(n, k); + if (check_mul_overflow(n - 1, (u64)step, &term) || check_add_overflow(sum, term, &sum)) return -ENOEXEC; + } *extent = sum; return 0; } @@ -252,23 +304,30 @@ static inline int ane_hx_dma_tile(const u32 *img, u32 base, u64 *extent) * size 0x5504; an unset size is 64), then every group (stride 0x5518) and * every output channel group (stride 0x551c) after the first. An output * channel group is 16 << (common word 0x40 & 7) channels, 128 when that - * word is unset. + * word is unset. As with a zero width, a lane of size 0 is refused rather + * than read as nothing, and a zero group or channel count is one only with + * a zero stride. */ static inline int ane_hx_dma_kernel(const u32 *img, u64 *extent) { - u64 lanes = 0, groups, ocgs, term; + u32 group_stride = img[ane_hx_dma_index(0x5518)]; + u32 ocg_stride = img[ane_hx_dma_index(0x551c)]; + u64 lanes = 0, size, groups, ocgs, term; unsigned int i; - for (i = 0; i < 16; i++) - lanes = max(lanes, (u64)img[ane_hx_dma_index(0x5560 + 4 * i)] + - max(img[ane_hx_dma_index(0x55a0 + 4 * i)], - img[ane_hx_dma_index(0x5504)])); - groups = max(1U, img[ane_hx_dma_index(0x24)]) - 1; - ocgs = DIV_ROUND_UP((u64)max(1U, img[ane_hx_dma_index(0x1c)]), - 16U << (img[ane_hx_dma_index(0x40)] & 7)) - 1; - if (check_mul_overflow(groups, (u64)img[ane_hx_dma_index(0x5518)], &term) || + for (i = 0; i < 16; i++) { + size = max(img[ane_hx_dma_index(0x55a0 + 4 * i)], img[ane_hx_dma_index(0x5504)]); + if (!size) + return -ENOEXEC; + lanes = max(lanes, img[ane_hx_dma_index(0x5560 + 4 * i)] + size); + } + if (ane_hx_dma_count(img[ane_hx_dma_index(0x24)], group_stride, &groups) || + ane_hx_dma_count(img[ane_hx_dma_index(0x1c)], ocg_stride, &ocgs)) + return -ENOEXEC; + ocgs = DIV_ROUND_UP(ocgs, 16U << (img[ane_hx_dma_index(0x40)] & 7)); + if (check_mul_overflow(groups - 1, (u64)group_stride, &term) || check_add_overflow(lanes, term, &lanes) || - check_mul_overflow(ocgs, (u64)img[ane_hx_dma_index(0x551c)], &term) || + check_mul_overflow(ocgs - 1, (u64)ocg_stride, &term) || check_add_overflow(lanes, term, extent)) return -ENOEXEC; return 0; @@ -278,14 +337,25 @@ static inline int ane_hx_dma_kernel(const u32 *img, u64 *extent) static const u16 ane_hx_dma_base_addr[] = { 0x4d10, 0x4d28, 0x5108, 0x5510, 0x5618 }; #define ANE_HX_DMA_BASES ARRAY_SIZE(ane_hx_dma_base_addr) -/* A register image, and each base's slot and offset as last written into it. */ +/* + * One task's register image, the image words it wrote, and each base's slot + * and offset as it wrote them. + */ struct ane_hx_dma_state { u32 img[ANE_HX_DMA_WORDS]; + DECLARE_BITMAP(set, ANE_HX_DMA_WORDS); u64 offset[ANE_HX_DMA_BASES]; u8 slot[ANE_HX_DMA_BASES]; u8 written; /* bit b: base b was written */ }; +/* + * The reset values of the image: a task starts from them, and a program + * may leave out every word that holds its reset value. On the J775D's H17 a + * second task that leaves out the output base or a row stride runs with + * the reset value 0, and one that leaves out the widths does not run with + * the first task's. + */ static inline void ane_hx_dma_defaults(struct ane_hx_dma_state *st) { unsigned int i; @@ -317,7 +387,14 @@ static inline bool ane_hx_other_allowed(u32 addr) /* * Apply one task's records (bytes [rec, end) of @p) to @st, refusing the * header forms the task stream never uses. A relocated record covering a - * base's [lo, hi] pair sets that base's slot and offset. + * base's [lo, hi] pair sets that base's slot and offset. Any other + * relocation names the slot 4 custom BAR and takes its value + * (ane_h16_custom_bars()), which this check does not see, so the + * configuration word must already enable its DMA: that value must not be + * able to turn a DMA on. + * A word written twice in one task must repeat its value, and a base its + * slot too, so no earlier write names anything unchecked; H17 programs + * repeat source 2's base unchanged. */ static inline int ane_hx_dma_apply(const u8 *p, size_t rec, size_t end, struct ane_hx_dma_state *st) @@ -337,29 +414,40 @@ static inline int ane_hx_dma_apply(const u8 *p, size_t rec, size_t end, if (!(h & BIT(31)) && ((h & (BIT(21) | BIT(22) | BIT(30))) || (!reloc && slot))) return -ENOEXEC; if (reloc && count == 2 && ane_hx_dma_base(first) && !(first & 4)) { + u64 offset = get_unaligned_le32(p + rec) | + (u64)get_unaligned_le32(p + rec + 4) << 32; + for (b = 0; ane_hx_dma_base_addr[b] != first; b++) ; - st->offset[b] = get_unaligned_le32(p + rec) | - (u64)get_unaligned_le32(p + rec + 4) << 32; + if ((st->written & BIT(b)) && st->slot[b] != slot) + return -ENOEXEC; + st->offset[b] = offset; st->slot[b] = slot; st->written |= BIT(b); } else if (reloc) { if (slot != 4) return -ENOEXEC; for (i = 0; i < count; i++) - if (!ane_hx_dma_config(first + 4 * i)) + if (!ane_hx_dma_config(first + 4 * i) || + !ane_hx_dma_config_on(first + 4 * i, + get_unaligned_le32(p + rec + 4 * i))) return -ENOEXEC; } for (i = 0; i < count; i++) { u32 addr = ane_hx_record_addr(h, i); + u32 w = get_unaligned_le32(p + rec + 4 * i); if (!reloc && ane_hx_dma_base(addr)) return -ENOEXEC; index = ane_hx_dma_index(addr); - if (index >= 0) - st->img[index] = get_unaligned_le32(p + rec + 4 * i); - else if (get_unaligned_le32(p + rec + 4 * i) && !ane_hx_other_allowed(addr)) + if (index < 0) { + if (w && !ane_hx_other_allowed(addr)) + return -ENOEXEC; + continue; + } + if (test_and_set_bit(index, st->set) && st->img[index] != w) return -ENOEXEC; + st->img[index] = w; } rec += count * 4; } @@ -392,32 +480,39 @@ static inline int ane_hx_dma_image_check(const u32 *img) } /* - * What one task enables it must also locate: an input DMA source, the output - * DMA or the lookup table with a non-zero configuration needs its relocated - * base in the same task, and a height and channel count that are not zero. - * A zero width, depth or group count is read as one: the compiler writes 0 - * for them, and a zero width is in the 256 x 256 matmul that runs correctly - * on an M4 Pro. The coefficient DMA is not held to this: lookup-table tasks - * configure it without a base (see ane_hx_task_stream_dma_validate()). + * What one task enables it must also locate and size. Each DMA has its + * configuration words: source 1 0x4d00, source 2 0x4d04, the destination + * 0x5100, the 16 coefficient lanes 0x5520-0x555c and the lookup table's + * 0x5600-0x5614, which enable it as ane_hx_dma_config_on() says. An + * enabled DMA needs its relocated base in the same task, and an enabled + * input or output stream a width, height and channel count that are not + * zero. A zero width is not read as one: on the J775D's H17 a task without + * widths stalled the engine, and on H16 a matmul without them ran 256 wide. + * A zero depth or group count is one only with a zero stride, which every + * program that leaves them out has (ane_hx_dma_tile()). */ static inline int ane_hx_dma_enabled_check(const struct ane_hx_dma_state *st) { static const struct { u16 config, last, dim; u8 base; } dma[] = { { 0x4d00, 0x4d00, 0x4, 0 }, { 0x4d04, 0x4d04, 0x4, 1 }, - { 0x5100, 0x5100, 0x14, 2 }, { 0x5600, 0x5614, 0, 4 }, + { 0x5100, 0x5100, 0x14, 2 }, { 0x5520, 0x555c, 0, 3 }, + { 0x5600, 0x5614, 0, 4 }, }; unsigned int i; - u32 a, on; + bool on; + u32 a; for (i = 0; i < ARRAY_SIZE(dma); i++) { - for (a = dma[i].config, on = 0; a <= dma[i].last; a += 4) - on |= st->img[ane_hx_dma_index(a)]; + for (a = dma[i].config, on = false; a <= dma[i].last; a += 4) + if (ane_hx_dma_config_on(a, st->img[ane_hx_dma_index(a)])) + on = true; if (!on) continue; - if (!(st->written & BIT(dma[i].base)) || - (dma[i].dim && (!st->img[ane_hx_dma_index(dma[i].dim + 4)] || - !st->img[ane_hx_dma_index(dma[i].dim + 8)]))) + if (!(st->written & BIT(dma[i].base))) return -ENOEXEC; + for (a = dma[i].dim; dma[i].dim && a <= dma[i].dim + 8; a += 4) + if (!st->img[ane_hx_dma_index(a)]) + return -ENOEXEC; } return 0; } @@ -450,27 +545,25 @@ static inline int ane_hx_dma_fits(const struct ane_hx_dma_state *st, unsigned in } /* - * Bound every DMA base of an already validated stream. @bound[s] is the size - * of the buffer the operation section binds to BAR slot s, 0 when it binds - * none. A base must be a relocated [lo, hi] record on a bound slot, and its - * offset plus the extent of its transfer must stay inside that buffer. + * Bound every DMA base of an already validated stream with @header_words + * fixed words per task. @bound[s] is the size of the buffer the operation + * section binds to BAR slot s, 0 when it binds none. A base must be a + * relocated [lo, hi] record on a bound slot, and its offset plus the extent + * of its transfer must stay inside that buffer. * - * Whether the engine starts each task from its defaults or keeps registers - * from the task before is not known, so both readings are checked: - * - each task over the defaults: the bases it writes, with its own words, - * and every DMA it enables has its base in the task; - * - a running image over the whole stream, from the defaults: after each - * task, every base written so far, with the geometry in force then. This - * also bounds a coefficient DMA configured without a base of its own. - * Programs leave out words that hold the default even when an earlier task - * set another value; such a stream fits only the first reading and is - * refused. + * Each task is checked on its own words over the reset values, which is the + * state the engine runs it from (see ane_hx_dma_defaults()). A word a task + * leaves out holds its reset value, whatever an earlier task wrote there, + * and a DMA the task does not enable reads and writes nothing. No base can + * reach a later task either: every DMA a task enables has its base written + * in that task (ane_hx_dma_enabled_check()). */ static inline int -ane_hx_task_stream_dma_validate(const void *text, size_t size, +ane_hx_task_stream_dma_validate(const void *text, size_t size, unsigned int header_words, const u64 bound[ANE_HX_DMA_SLOTS]) { - struct ane_hx_dma_state *task, *run; + struct ane_hx_dma_state *task; + struct ane_hx_task t; const u8 *p = text; size_t pos = 16; unsigned int b; @@ -478,53 +571,27 @@ ane_hx_task_stream_dma_validate(const void *text, size_t size, if (!p || !bound || size < 16 || size > ANE_H16_TASK_MAX || (size & 3)) return -ENOEXEC; - task = kmalloc_array(2, sizeof(*task), GFP_KERNEL); + task = kmalloc_obj(*task); if (!task) return -ENOMEM; - run = task + 1; - ane_hx_dma_defaults(run); - while (!ret && pos < size) { - u32 words, header_words = 9; - size_t end, rec; - - if (size - pos < 16) { - ret = -ENOEXEC; + while (pos < size) { + ret = ane_hx_task_frame(p, size, pos, header_words, &t); + if (ret < 0) break; - } - words = (get_unaligned_le32(p + pos) >> 16) & 0x7ff; - if (!words) { - pos += 16; + pos = t.next; + if (!ret) continue; - } - if (words < 9 || words > (size - pos) / 4) { - ret = -ENOEXEC; - break; - } - end = pos + words * 4; - if ((get_unaligned_le32(p + pos + 8 * 4) & 3) == 3) - header_words++; - if (words < header_words) { - ret = -ENOEXEC; - break; - } - rec = pos + header_words * 4; ane_hx_dma_defaults(task); - ret = ane_hx_dma_apply(p, rec, end, task); + ret = ane_hx_dma_apply(p, t.rec, t.end, task); if (!ret) ret = ane_hx_dma_image_check(task->img); if (!ret) ret = ane_hx_dma_enabled_check(task); - if (!ret) - ret = ane_hx_dma_apply(p, rec, end, run); - if (!ret) - ret = ane_hx_dma_image_check(run->img); - for (b = 0; !ret && b < ANE_HX_DMA_BASES; b++) { + for (b = 0; !ret && b < ANE_HX_DMA_BASES; b++) if (task->written & BIT(b)) ret = ane_hx_dma_fits(task, b, bound); - if (!ret && (run->written & BIT(b))) - ret = ane_hx_dma_fits(run, b, bound); - } - pos = end == size ? end : ALIGN(end, 16); + if (ret) + break; } kfree(task); return ret; diff --git a/drivers/accel/ane/ane_h16_tasks_test.c b/drivers/accel/ane/ane_h16_tasks_test.c index a95932e4767704..5ca9a0d4f44c55 100644 --- a/drivers/accel/ane/ane_h16_tasks_test.c +++ b/drivers/accel/ane/ane_h16_tasks_test.c @@ -200,50 +200,50 @@ static void ane_hx_dma_bound_test(struct kunit *test) /* 15 rows of 0x40, 127 planes of 0x400 and one 32-byte row: exactly 128 KiB. */ size = dma_task(text, 0, 0); KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); size = dma_task(text, 0x40, 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); size = dma_task(text, 0, 0x20000); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); size = dma_task(text, 0, -0x70000); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); size = dma_task(text, -1, 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A larger buffer takes the same offset. */ bound[7] = 0x40000; size = dma_task(text, 0, 0x20000); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); /* A slot the operation section does not bind. */ bound[7] = 0; size = dma_task(text, 0, 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); bound[7] = 0x20000; /* A base without relocation, or relocated on the custom BAR slot. */ put_unaligned_le32(0x4d10 / 4 | 1 << 15, dma_record(text, 5)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(0x4d10 / 4 | 1 << 15 | BIT(29) | 4 << 23, dma_record(text, 5)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A relocated record that is not exactly the [lo, hi] pair. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x4d0c / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 5)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A scatter write of the hi word. */ size = dma_task(text, 0, 0); put_unaligned_le32(BIT(31) | BIT(15) | 0x5108 / 4, dma_record(text, 6)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A relocation on a stride, and an unused header bit. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(29) | 6 << 23, dma_record(text, 1)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(0x4d18 / 4 | 1 << 15 | BIT(30), dma_record(text, 1)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* One byte more of plane stride crosses a line past the end. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x401, dma_record(text, 1) + 8); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* Rows, planes and depth slices whose sum wraps 64 bits to 32 bytes. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x80000001, dma_record(text, 0) + 8); @@ -252,89 +252,175 @@ static void ane_hx_dma_bound_test(struct kunit *test) put_unaligned_le32(U32_MAX, dma_record(text, 1) + 4); put_unaligned_le32(U32_MAX, dma_record(text, 1) + 8); put_unaligned_le32(0x80000000, dma_record(text, 1) + 12); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A source 1 metadata address, which the bound does not model. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x4d40 / 4, dma_record(text, 2)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A wrap configuration beside the cache hint. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x4d08 / 4, dma_record(text, 2)); put_unaligned_le32(0x1ce, dma_record(text, 2) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(0xce, dma_record(text, 2) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); } +/* Record headers: @n dense words from @addr, and a relocated [lo, hi] pair on @slot. */ +#define DMA_REC(addr, n) ((addr) / 4 | ((n) - 1) << 15) +#define DMA_RELOC(addr, slot) (DMA_REC(addr, 2) | BIT(29) | (slot) << 23) + /* - * Two tasks from dma_task's records: the geometry records (dimensions, strides - * and formats, records 0-4) and the base records (records 5-7), each task - * given @first then @second of them (bit 0 geometry, bit 1 bases), with the - * source plane stride of the second task's geometry set to @plane. + * Parts of dma_task's one task, for streams of several tasks: its geometry + * (dimensions with @rows source rows, strides with @plane source plane + * stride, formats), its two bases (source 1 at @src, the destination at 0) + * and the source 1 configuration word that enables it. */ -static size_t dma_two(u8 *text, unsigned int first, unsigned int second, u32 plane) +enum { DMA_GEOMETRY = 1, DMA_BASES = 2, DMA_ENABLE = 4, DMA_EXTRA = 8 }; + +/* Append one task of @parts, then @n more words of @extra; returns the new end. */ +static size_t dma_append(u8 *text, size_t at, unsigned int parts, u32 rows, u32 plane, + u64 src, const u32 *extra, unsigned int n) { - static const unsigned int parts[2][2] = { - { 0, 28 * 4 - 9 * 4 }, { 28 * 4 - 9 * 4, 8 * 4 }, + const u32 geometry[] = { + DMA_REC(0x4, 7), 16, rows, 128, 0, 16, 16, 128, + DMA_REC(0x4d18, 3), 0x40, plane, 0, DMA_REC(0x4d68, 1), 0x1002031, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + }; + const u32 bases[] = { + DMA_RELOC(0x4d10, 6), lower_32_bits(src), upper_32_bits(src), + DMA_RELOC(0x5108, 7), 0, 0, }; - u8 full[256]; - size_t at = 16, task, rec = 16 + 9 * 4; - unsigned int t, k; + const u32 enable[] = { DMA_REC(0x4d00, 1) | BIT(29) | 4 << 23, 0x21 }; + const struct { unsigned int part; const u32 *w; unsigned int n; } part[] = { + { DMA_GEOMETRY, geometry, ARRAY_SIZE(geometry) }, + { DMA_BASES, bases, ARRAY_SIZE(bases) }, + { DMA_ENABLE, enable, ARRAY_SIZE(enable) }, + { DMA_EXTRA, extra, n }, + }; + size_t task = at; + unsigned int k, i; + + parts |= DMA_EXTRA; + memset(text + at, 0, 9 * 4); + at += 9 * 4; + for (k = 0; k < ARRAY_SIZE(part); k++) + for (i = 0; (parts & part[k].part) && i < part[k].n; i++, at += 4) + put_unaligned_le32(part[k].w[i], text + at); + put_unaligned_le32((at - task) / 4 << 16, text + task); + return ALIGN(at, 16); +} - dma_task(full, 0, 0); +/* A stream of one complete task from dma_append() with @n words of @extra. */ +static size_t dma_one(u8 *text, u32 plane, const u32 *extra, unsigned int n) +{ memset(text, 0, 512); - put_unaligned_le32(2, text); - for (t = 0; t < 2; t++) { - unsigned int want = t ? second : first; - - task = at; - memcpy(text + at, full + 16, 9 * 4); - at += 9 * 4; - for (k = 0; k < 2; k++) { - if (!(want & BIT(k))) - continue; - memcpy(text + at, full + rec + parts[k][0], parts[k][1]); - if (k == 0 && t == 1) - /* record 1 (source strides) starts 8 words in: row, plane, depth */ - put_unaligned_le32(plane, text + at + 8 * 4 + 8); - at += parts[k][1]; - } - put_unaligned_le32((at - task) / 4 << 16, text + task); - if (!t) - at = ALIGN(at, 16); - } - return at; + put_unaligned_le32(1, text); + return dma_append(text, 16, 7, 16, plane, 0, extra, n); +} + +/* A stream of two tasks, @first then @second, from dma_append(). */ +static size_t dma_two(u8 *text, unsigned int first, unsigned int second, u32 plane) +{ + size_t at; + + memset(text, 0, 512); + put_unaligned_le32(1, text); + at = dma_append(text, 16, first, 16, 0x400, 0, NULL, 0); + return dma_append(text, at, second, 16, plane, 0, NULL, 0); } /* - * Whether the engine keeps registers from one task to the next is not known, - * so a stream must fit both ways. Geometry in one task and bases in the next - * fits only per task when the geometry is too large; a base kept from an - * earlier task fits only per task when a later task enlarges its geometry. + * Each task runs from the reset values, so each is checked on its own words + * over them, and every DMA a task enables has its base in that task. A word + * a task leaves out holds its reset value, whatever an earlier task wrote. */ -static void ane_hx_dma_carry_test(struct kunit *test) +static void ane_hx_dma_reset_test(struct kunit *test) { u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + const u32 groups[] = { DMA_REC(0x24, 1), 2, DMA_REC(0x4d24, 1), 0x20000 }; + const u32 dst_only[] = { + DMA_REC(0x4, 7), 16, 32, 128, 0, 16, 16, 128, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + DMA_RELOC(0x5108, 7), 0, 0, + }; u8 text[512]; size_t size; /* Both tasks complete and in range. */ - size = dma_two(text, 3, 3, 0x400); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + size = dma_two(text, 7, 7, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* + * Task N: geometry with no base; task N+1: the bases and the enable + * alone, which enable source 1 with no size of its own. + */ + size = dma_two(text, DMA_GEOMETRY, DMA_BASES | DMA_ENABLE, 0x400); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* N+1 with larger planes and nothing enabled moves nothing: N's base does not reach it. */ + size = dma_two(text, 7, DMA_GEOMETRY, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* ... but enabling source 1 there without its base is refused, */ + size = dma_two(text, 7, DMA_GEOMETRY | DMA_ENABLE, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* ... and so is its base with those planes. */ + size = dma_two(text, 7, 7, 0x800); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + /* + * An L2-resident task: N+1 takes its input from L2 and writes only the + * destination, with 32 rows. Source 1 is not enabled in N+1, so N's + * source base is not read with N+1's rows (which would end past 128 KiB). + */ + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, NULL, 0); + size = dma_append(text, size, 0, 0, 0, 0, dst_only, ARRAY_SIZE(dst_only)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* - * Task N: geometry (and large planes) with no base; task N+1: the bases - * alone, which enable the source with no size of its own. + * A word left at its reset value after an earlier task set it: N reads + * two groups 128 KiB apart from a 256 KiB source; N+1 leaves the group + * count and stride out and reads one group from 128 KiB on. */ - size = dma_two(text, 3, 2, 0x400); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); - size = dma_two(text, 1, 2, 0x400); - put_unaligned_le32(0x800, text + 16 + 9 * 4 + 8 * 4 + 8); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); - /* The reverse: the bases kept from task N, larger planes in task N+1. */ - size = dma_two(text, 3, 1, 0x800); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); - size = dma_two(text, 3, 1, 0x400); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + bound[6] = 0x40000; + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, groups, ARRAY_SIZE(groups)); + size = dma_append(text, size, 7, 16, 0x400, 0x20000, NULL, 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* N+1 writing the two groups itself reaches 128 KiB past the source. */ + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, groups, ARRAY_SIZE(groups)); + size = dma_append(text, size, 7, 16, 0x400, 0x20000, groups, ARRAY_SIZE(groups)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * A base written twice in one task must repeat its slot and offset: an + * out-of-range first write followed by an in-range one is refused, as is + * a second write on another slot. H17 programs repeat 0x4d28 unchanged. + */ +static void ane_hx_dma_rewrite_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000, [8] = 0x20000 }; + u32 again[] = { DMA_RELOC(0x4d10, 6), 0, 0 }; + u8 text[512]; + size_t size; + + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0x20000, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + again[0] = DMA_RELOC(0x4d10, 8); + memset(text, 0, 512); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 7, 16, 0x400, 0, again, ARRAY_SIZE(again)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); } /* @@ -352,43 +438,55 @@ static void ane_hx_dma_strict_test(struct kunit *test) size = dma_task(text, 0, 0); put_unaligned_le32(0x5100 / 4, dma_record(text, 7)); put_unaligned_le32(0x1000021, dma_record(text, 7) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); /* ... with a zero channel count, */ put_unaligned_le32(0, dma_record(text, 0) + 28); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(128, dma_record(text, 0) + 28); /* ... and without its base: record 6 rewrites the destination strides instead. */ put_unaligned_le32(0x5110 / 4 | 1 << 15, dma_record(text, 6)); put_unaligned_le32(0x40, dma_record(text, 6) + 4); put_unaligned_le32(0x400, dma_record(text, 6) + 8); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* A zero channel count on an enabled source. */ size = dma_task(text, 0, 0); put_unaligned_le32(0, dma_record(text, 0) + 12); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); - /* A zero width reads as one. */ + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* + * A zero width on an enabled stream: the J775D's H17 stalled on one and + * an M4 Pro ran one 256 wide, so it is not read as one. + */ size = dma_task(text, 0, 0); put_unaligned_le32(0, dma_record(text, 0) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* The destination's width matters once the destination is enabled. */ + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 0) + 20); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(0x5100 / 4, dma_record(text, 7)); + put_unaligned_le32(0x1000021, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(16, dma_record(text, 0) + 20); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); /* An output channel group of 6, then 5: common word 0x40 in place of the source format. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x40 / 4, dma_record(text, 2)); put_unaligned_le32(6, dma_record(text, 2) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(5, dma_record(text, 2) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); /* A source format bit the compiler never sets. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x1002033, dma_record(text, 2) + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); /* 0x44d0, and a cache DMA word the compiler never writes, in place of the source format. */ size = dma_task(text, 0, 0); put_unaligned_le32(0x44d0 / 4, dma_record(text, 2)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(0x590c / 4, dma_record(text, 2)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); put_unaligned_le32(0x5904 / 4, dma_record(text, 2)); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); } /* @@ -407,12 +505,12 @@ static void ane_hx_dma_align_test(struct kunit *test) put_unaligned_le32(0, text + at + 8); at += 12; put_unaligned_le32((at - 16) / 4 << 16, text + 16); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); bound[6] = 128; - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), 0); /* Offset 0x41: the line at 0x40 through the one at 0x80. */ put_unaligned_le32(0x41, text + 16 + 9 * 4 + 4); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); } /* @@ -444,18 +542,254 @@ static void ane_hx_dma_kernel_test(struct kunit *test) #undef PUT put_unaligned_le32((at - 16) / 4 << 16, text + 16); KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at, 1), 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), 0); bound[8] = 0xfc0; - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at, 9, bound), -ENOEXEC); /* 3 at 0x40 is the default 128-channel group, 2 a 64-channel one: four groups. */ bound[8] = 0x1000; put_unaligned_le32(0x40 / 4, text + at); put_unaligned_le32(2, text + at + 4); put_unaligned_le32((at + 8 - 16) / 4 << 16, text + 16); KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, at + 8, 1), 0); - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, bound), -ENOEXEC); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, 9, bound), -ENOEXEC); bound[8] = 0x2000; - KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, bound), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, at + 8, 9, bound), 0); +} + +/* + * A matmul's coefficient DMA from slot 3: 16 lanes of 0x1000 bytes 0x1000 + * apart, 256 output channels in two groups of 128 (common word 0x40 unset) + * @ocgs apart, the lane configuration words set to @lane (none when 0) and + * the base written when @base. + */ +static size_t dma_kernel(u8 *text, u32 lane, bool base, u32 ocgs) +{ + size_t at = 16 + 9 * 4; + unsigned int i; + + memset(text, 0, 512); + put_unaligned_le32(1, text); +#define PUT(v) do { put_unaligned_le32(v, text + at); at += 4; } while (0) + PUT(DMA_REC(0x1c, 1)); + PUT(256); + PUT(DMA_REC(0x3c, 1)); + PUT(0x20200004); + PUT(DMA_REC(0x551c, 1)); + PUT(ocgs); + PUT(DMA_REC(0x5560, 32)); + for (i = 0; i < 16; i++) + PUT(i * 0x1000); + for (i = 0; i < 16; i++) + PUT(0x1000); + if (lane) { + /* Enabled lanes take the custom BAR value; idle ones are not relocated. */ + PUT(DMA_REC(0x5520, 16) | ((lane & 0xffff) == 0x20 ? 0 : BIT(29) | 4 << 23)); + for (i = 0; i < 16; i++) + PUT(lane); + } + if (base) { + PUT(DMA_RELOC(0x5510, 3)); + PUT(0); + PUT(0); + } +#undef PUT + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* + * The coefficient DMA is held to the same rule as the others: lanes that + * enable it need its base in the task. A lookup-table task writes its lanes + * idle (0x20 in the low half) and fetches nothing. The second + * output channel group of 128 x 256 fp16 coefficients starts 0x10000 into + * them; a group stride of 0x40000 reads 0x30000 past a 0x20000 buffer. + */ +static void ane_hx_dma_kernel_enable_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [3] = 0x20000 }; + u8 text[512]; + size_t size; + + size = dma_kernel(text, 0x10041, true, 0x10000); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_kernel(text, 0x10041, true, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Enabled lanes without a base. */ + size = dma_kernel(text, 0x10041, false, 0x10000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Idle lanes without a base fetch nothing; any other lane word enables the DMA. */ + size = dma_kernel(text, 0x50020, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_kernel(text, 0x50022, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_kernel(text, 0x50120, false, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* A base written beside idle lanes is still bounded. */ + size = dma_kernel(text, 0x50020, true, 0x40000); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + /* Idle lanes that take the custom BAR value could become enabled lanes. */ + size = dma_kernel(text, 0x50020, false, 0x10000); + put_unaligned_le32(get_unaligned_le32(text + size - 17 * 4) | BIT(29) | 4 << 23, + text + size - 17 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * Counts the bound cannot read as one, and a lane that reads nothing. In + * dma_kernel()'s task, 52, 60 and 68 hold the records of the output channel + * count, common word 0x3c and the output channel group stride; 80 + 4i + * holds lane i's offset and 144 + 4i its size. + */ +static void ane_hx_dma_kernel_count_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [3] = 0x20000 }; + u8 text[512]; + size_t size; + + /* No group count with a group stride, then two groups 0x1000 apart. */ + size = dma_kernel(text, 0x10041, true, 0x10000); + put_unaligned_le32(DMA_REC(0x5518, 1), text + 60); + put_unaligned_le32(0x1000, text + 64); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(DMA_REC(0x24, 1), text + 68); + put_unaligned_le32(2, text + 72); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* No output channel count with an output channel group stride. */ + size = dma_kernel(text, 0x10041, true, 0x10000); + put_unaligned_le32(0, text + 56); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_kernel(text, 0x10041, true, 0); + put_unaligned_le32(0, text + 56); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + /* A lane of size 0 at the end of the buffer, then one 0x5504 sizes. */ + size = dma_kernel(text, 0x10041, true, 0); + put_unaligned_le32(0x20000, text + 80 + 15 * 4); + put_unaligned_le32(0, text + 144 + 15 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(DMA_REC(0x5504, 1), text + 60); + put_unaligned_le32(0x80, text + 64); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x1f000, text + 80 + 15 * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* + * A zero depth or group count on a source or the destination is one only + * with a zero stride. dma_task()'s source has depth 0 and writes its depth + * stride at record 1 + 12. + */ +static void ane_hx_dma_count_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + static const u32 dst_depth[] = { DMA_REC(0x5118, 1), 0x400 }; + static const u32 dst_depths[] = { DMA_REC(0x5118, 1), 0x400, DMA_REC(0x20, 1), 1 }; + static const u32 src_group[] = { DMA_REC(0x4d24, 1), 0x20000 }; + static const u32 dst_group[] = { DMA_REC(0x511c, 1), 0x20000 }; + static const u32 src_groups[] = { DMA_REC(0x24, 1), 1, DMA_REC(0x4d24, 1), 0x20000 }; + u8 text[512]; + size_t size; + + size = dma_task(text, 0, 0); + put_unaligned_le32(0x400, dma_record(text, 1) + 12); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(1, dma_record(text, 0) + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(2, dma_record(text, 0) + 16); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + size = dma_one(text, 0x400, dst_depth, ARRAY_SIZE(dst_depth)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, dst_depths, ARRAY_SIZE(dst_depths)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_one(text, 0x400, src_group, ARRAY_SIZE(src_group)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, dst_group, ARRAY_SIZE(dst_group)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + size = dma_one(text, 0x400, src_groups, ARRAY_SIZE(src_groups)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); +} + +/* + * A word written twice in one task repeats its value: a plane stride that + * would end past the source, then one that would not, is refused. A + * configuration word on the custom BAR must already enable its DMA. + */ +static void ane_hx_dma_repeat_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + static const u32 plane[] = { DMA_REC(0x4d1c, 1), 0x400 }; + u8 text[512]; + size_t size; + + size = dma_one(text, 0x400, plane, ARRAY_SIZE(plane)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + size = dma_one(text, 0x800, plane, ARRAY_SIZE(plane)); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + + size = dma_task(text, 0, 0); + put_unaligned_le32(0, dma_record(text, 7) + 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + +/* + * One H15 task: eight header words (nine when @extra sets the last one's + * low bits), then a source 1 row stride of @row, three L2 records and + * dma_task()'s geometry, bases and enable. Read with nine header words, the + * row stride record would be a header word and the L2 records would hide + * it, so the stride goes unchecked. + */ +static size_t dma_h15(u8 *text, u32 row, bool extra) +{ + static const u32 tail[] = { + DMA_REC(0x4104, 1), DMA_REC(0x4108, 2), DMA_REC(0x410c, 1), 0, + DMA_REC(0x4, 7), 16, 16, 128, 0, 16, 16, 128, + DMA_REC(0x4d1c, 2), 0x400, 0, DMA_REC(0x4d68, 1), 0x1002031, + DMA_REC(0x5110, 2), 0x40, 0x400, DMA_REC(0x5138, 1), 0x1302031, + DMA_RELOC(0x4d10, 6), 0, 0, DMA_RELOC(0x5108, 7), 0, 0, + DMA_REC(0x4d00, 1) | BIT(29) | 4 << 23, 0x21, + }; + size_t at = 16 + 8 * 4; + unsigned int i; + + memset(text, 0, 256); + put_unaligned_le32(1, text); + if (extra) { + put_unaligned_le32(3, text + at - 4); + at += 4; + } + put_unaligned_le32(DMA_REC(0x4d18, 1), text + at); + put_unaligned_le32(row, text + at + 4); + at += 8; + for (i = 0; i < ARRAY_SIZE(tail); i++, at += 4) + put_unaligned_le32(tail[i], text + at); + put_unaligned_le32((at - 16) / 4 << 16, text + 16); + return at; +} + +/* The DMA bound walks a stream with its target's header words, as the structural gate does. */ +static void ane_hx_dma_h15_test(struct kunit *test) +{ + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x20000, [7] = 0x20000 }; + u8 text[256]; + size_t size; + bool extra; + + for (extra = false; ; extra = true) { + size = dma_h15(text, 0x40, extra); + KUNIT_ASSERT_EQ(test, ane_hx_task_stream_validate_hdr(text, size, 1, 1, 8, + NULL, NULL), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 8, bound), 0); + /* 15 rows of 0x1040 end past the source. */ + size = dma_h15(text, 0x1040, extra); + KUNIT_ASSERT_EQ(test, ane_hx_task_stream_validate_hdr(text, size, 1, 1, 8, + NULL, NULL), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 8, bound), + -ENOEXEC); + if (extra) + break; + } + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 0, bound), -ENOEXEC); } static struct kunit_case ane_h16_task_cases[] = { @@ -467,7 +801,13 @@ static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_relocation_test), KUNIT_CASE(ane_hx_dma_bound_test), KUNIT_CASE(ane_hx_dma_kernel_test), - KUNIT_CASE(ane_hx_dma_carry_test), + KUNIT_CASE(ane_hx_dma_kernel_enable_test), + KUNIT_CASE(ane_hx_dma_kernel_count_test), + KUNIT_CASE(ane_hx_dma_count_test), + KUNIT_CASE(ane_hx_dma_repeat_test), + KUNIT_CASE(ane_hx_dma_h15_test), + KUNIT_CASE(ane_hx_dma_reset_test), + KUNIT_CASE(ane_hx_dma_rewrite_test), KUNIT_CASE(ane_hx_dma_strict_test), KUNIT_CASE(ane_hx_dma_align_test), {} From bbd215282cce7288c5a01ab3d665ed96e602116c Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 19:15:25 -0500 Subject: [PATCH 1394/1514] thunderbolt: apple: sleep T8103 ACIO router before power-off and on reboot On T8103, powering off ps_atc*_cio while the ACIO host router firmware is still active (M3_STAT=0x01000000) triggers an immediate SoC reset. Similarly, rebooting with a started router leaves the router running while PCIe-C and DART shutdown callbacks tear down its devices, causing a panic in apple_dpin_irq_dispatch(). Add a sleep_router_on_stop hardware flag and enable it along with psd_power_cycle and stop_at_reboot on apple_cio_t8103_hw: - Put the host router into ACIO sleep via apple_nhi_cio_router_sleep() (M3_STAT=0x02000000) before removing NHI children. - Detach and flush the RTKit mailbox via apple_rtkit_mailbox_off() before freeing the RTKit instance. - Release and synchronously suspend ACIO power domains in reverse order. - Register the reboot notifier so a started router is stopped cleanly before reboot. Signed-off-by: Erik Bourget --- drivers/thunderbolt/apple.c | 46 ++++++++++++++++++++++++++++++- tools/asahi/pciec-policy-tests.py | 4 +++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 6115871373557d..694a310767ab15 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -176,6 +176,11 @@ struct apple_cio_hw { bool psd_power_cycle; /* Stop a started router before a reboot shuts its PCIe and DARTs down. */ bool stop_at_reboot; + /* + * Put the host router into ACIO sleep before powering off its domains, + * and detach the RTKit mailbox before freeing it. + */ + bool sleep_router_on_stop; /* Deep sleep removes the CIO domains, including an attached router. */ bool sleep_removes_domains; /* Start the router again at once after a wake. */ @@ -192,12 +197,16 @@ struct apple_cio_hw { * T8103 deep sleep removes the CIO power domains and shares the ATC PHY with * DWC3. Tear down a connected router before tasks freeze (ahead of DWC3's PM * notifier) and request fresh cable state immediately on wake; s2idle and - * freeze leave the port up. + * freeze leave the port up. Put the host router into ACIO sleep before + * powering off the CIO power domain, and stop a started router before reboot. */ static const struct apple_cio_hw apple_cio_t8103_hw = { .sleep_removes_domains = true, .restart_on_wake = true, .phy_shared_with_dwc3 = true, + .psd_power_cycle = true, + .stop_at_reboot = true, + .sleep_router_on_stop = true, .dp = &apple_dpin_m1, }; @@ -1544,6 +1553,7 @@ struct apple_nhi { }; static int apple_nhi_cio_bind(struct apple_nhi *anhi); +static int apple_nhi_cio_router_sleep(struct tb_nhi *nhi); static int apple_nhi_cio_prepare(struct apple_nhi *anhi); static int apple_nhi_cio_suspend(struct apple_nhi *anhi); static int apple_nhi_cio_resume(struct apple_nhi *anhi); @@ -3213,6 +3223,30 @@ static struct platform_device *apple_cio_find_pcie_tunnel(struct apple_cio *acio return pdev; } +static void apple_cio_sleep_router_for_stop(struct apple_cio *acio) +{ + struct platform_device *nhi_pdev; + struct apple_nhi *anhi; + int ret; + + lockdep_assert_held(&acio->lock); + nhi_pdev = READ_ONCE(acio->nhi_pdev); + if (!nhi_pdev) + return; + device_lock(&nhi_pdev->dev); + if (READ_ONCE(acio->nhi_pdev) == nhi_pdev) { + anhi = platform_get_drvdata(nhi_pdev); + if (anhi && anhi->tb && anhi->tb->root_switch) { + scoped_guard(mutex, &anhi->tb->lock) + ret = apple_nhi_cio_router_sleep(&anhi->nhi); + if (ret) + dev_warn(acio->dev, + "CIO router sleep before stop failed: %d\n", ret); + } + } + device_unlock(&nhi_pdev->dev); +} + static void apple_cio_remove_children(struct apple_cio *acio) { struct platform_device *nhi_pdev; @@ -3226,6 +3260,14 @@ static void apple_cio_remove_children(struct apple_cio *acio) */ apple_cio_stop_pcie_tunnel(acio); + /* + * Put the host router firmware into ACIO sleep before tearing down the + * NHI and powering off the CIO power domain. On T8103, dropping the + * CIO domain while the firmware is still active triggers a SoC reset. + */ + if (acio->hw->sleep_router_on_stop) + apple_cio_sleep_router_for_stop(acio); + /* * The NHI is the tunnel control plane. Stop it while the tunneled PCIe * host and DART are still accessible, before depopulation tears down the @@ -3427,6 +3469,8 @@ static void apple_cio_stop(struct apple_cio *acio) if (ret) dev_warn(acio->dev, "Failed to shutdown M3 RTKit, continuing ACIO shutdown anyway\n"); + if (acio->hw->sleep_router_on_stop) + apple_rtkit_mailbox_off(acio->rtk); apple_rtkit_free(acio->rtk); acio->rtk = NULL; apple_cio_cpu_halt(acio); diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index 449d635c5122f5..24cde8b617b01c 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -682,6 +682,9 @@ def test_pm_order(out, acio): bool sleep_removes_domains; bool restart_on_wake; bool phy_shared_with_dwc3; + bool psd_power_cycle; + bool stop_at_reboot; + bool sleep_router_on_stop; const struct apple_dpin_policy *dp; }; struct notifier_block { int (*notifier_call)(void); int priority; }; @@ -761,6 +764,7 @@ def test_pm_order(out, acio): assert(t8122->sleep_removes_domains && t8103->sleep_removes_domains); assert(t8122->restart_on_wake && t8103->restart_on_wake); assert(t8122->phy_shared_with_dwc3 && t8103->phy_shared_with_dwc3); + assert(t8103->psd_power_cycle && t8103->stop_at_reboot && t8103->sleep_router_on_stop); assert(t8122->dp == &apple_dpin_m1 && t8103->dp == &apple_dpin_m1); struct apple_cio acio_t8122 = { .hw = t8122 }; From dbb7b44b3d99bbc745699df9008a7f30d3e41d1f Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 19:15:25 -0500 Subject: [PATCH 1395/1514] phy: apple: atc: restore T8103 PHY and dummy PIPE state after deep sleep T8103 deep sleep powers off ps_atc*_common behind genpd's back, wiping the ATC PHY register state and clearing PIPEHANDLER_DUMMY_PHY_EN in PIPEHANDLER_NONSELECTED_OVERRIDE. Without restoring the tracked PHY mode on wake, restarting the ACIO router on an unconfigured PHY resets the SoC; without re-enabling the dummy PIPE backend when parking the PIPE, the subsequent USB4 PIPE handoff fails to lock and tunneled USB3 fails to enable. Add a sleep_drops_common flag to atcphy_hw and enable park_dummy_phy, restore_after_pd_off, and sleep_drops_common on atcphy_hw_t8103 so resume marks pd_was_off, re-enables the dummy PIPE when parking, and restores the tracked PHY mode before consumers restart. Signed-off-by: Erik Bourget --- drivers/phy/apple/atc.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/drivers/phy/apple/atc.c b/drivers/phy/apple/atc.c index 9e55427a76c664..4071204363379a 100644 --- a/drivers/phy/apple/atc.c +++ b/drivers/phy/apple/atc.c @@ -769,6 +769,9 @@ struct apple_atcphy; * sleep, or at runtime with @idle_power_off, which * resets the block; bring the tracked state back once * the domain is on again + * @sleep_drops_common: Deep sleep lowers the common power domain behind + * genpd's back, so resume must mark @pd_was_off even + * without a genpd power-off notification * @idle_power_off: Let an idle PHY runtime-suspend, so that its power domain * can also drop while the system runs, see atcphy_rpm_get(). * Only for PHYs without DisplayPort, whose phy ops and tunnel @@ -799,6 +802,7 @@ struct atcphy_hw { bool clear_boot_hold; bool pipe_lock_unacked; bool restore_after_pd_off; + bool sleep_drops_common; bool idle_power_off; }; @@ -8123,6 +8127,7 @@ static int atcphy_suspend_noirq(struct device *dev) static void atcphy_sleep_lost_common(struct apple_atcphy *atcphy) { if ((!atcphy->hw->has_t8140_dp && + !atcphy->hw->sleep_drops_common && !of_device_is_compatible(atcphy->np, "apple,t8142-atcphy")) || !atcphy->hw->restore_after_pd_off || !pm_resume_via_firmware()) return; @@ -8652,6 +8657,9 @@ static const struct atcphy_hw atcphy_hw_t8103 = { .pipe_mux_data = PIPEHANDLER_MUX_CTRL_DATA_T8103, .has_usb4 = true, .park_pipe_unlocked = true, + .park_dummy_phy = true, + .restore_after_pd_off = true, + .sleep_drops_common = true, }; static const struct atcphy_hw atcphy_hw_t8122 = { From ecbefcf376a89e9cbe83ad0baf5b173278a09b47 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 11:18:28 +1100 Subject: [PATCH 1396/1514] drm/apple: afk: retire a superseded singleton only after its successor is admitted afk_recv_handle_init() retired the live instance of a singleton service as soon as its replacement was announced, before the replacement had a slot. When no slot was reclaimable (every slot pinned by a user or waiting for a reply) or the replacement failed admission or its OPEN, the replacement was dropped while the previous instance was already disabled and retired. Its owner (the audio service) kept a reference to a service it could no longer use, and no successor's init ran to hand it a new one. Retire the previous instance only once the replacement holds its slot, has been admitted and opened, right before it is published and its init takes over. A rejected replacement now leaves the previous instance usable. Add a host scenario that runs the real announcement path with every other slot pinned: the rejected replacement leaves the previous instance enabled and owned, and an admitted one retires it. Order the KUnit announcement model the same way. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk-service-test.c | 19 +++++---- drivers/gpu/drm/apple/afk.c | 25 +++++++----- drivers/gpu/drm/apple/afk.h | 8 ++-- .../selftests/drivers/gpu/apple-dcp/edid.py | 40 +++++++++++++++++++ 4 files changed, 72 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/apple/afk-service-test.c b/drivers/gpu/drm/apple/afk-service-test.c index ef0920a28dbe86..2d9c51ad1a0318 100644 --- a/drivers/gpu/drm/apple/afk-service-test.c +++ b/drivers/gpu/drm/apple/afk-service-test.c @@ -281,22 +281,27 @@ static const struct apple_epic_service_ops singleton_audio_ops = { /* * The firmware announces its AV video and audio interfaces again on fresh * channels on every display attach and never closes the old ones. Announce - * them as the endpoint's receive path does: supersede, then take the first - * reclaimable slot. The superseded audio instance stays pinned by its owner + * them as the endpoint's receive path does: take the first reclaimable + * slot, then supersede the previous instance. The superseded audio instance stays pinned by its owner * until the successor's init drops it. */ static struct apple_epic_service * afk_test_announce(struct apple_epic_service *slots, unsigned int nr, const struct apple_epic_service_ops *ops, u32 channel) { + struct apple_epic_service *admitted = NULL; unsigned int i; - for (i = 0; i < nr; i++) - afk_service_supersede(&slots[i], ops, channel); - for (i = 0; i < nr; i++) + /* As afk_recv_handle_init(): admit first, then retire what it replaces. */ + for (i = 0; i < nr && !admitted; i++) if (afk_service_reinit(&slots[i], NULL, ops, channel)) - return &slots[i]; - return NULL; + admitted = &slots[i]; + if (!admitted) + return NULL; + for (i = 0; i < nr; i++) + if (&slots[i] != admitted) + afk_service_supersede(&slots[i], ops, channel); + return admitted; } static void afk_service_singleton_reannounce_test(struct kunit *test) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index fc34158368387b..bc918ba18b0dbe 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -1885,16 +1885,6 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, goto free; } - for (ch_idx = 0; ch_idx < ep->num_channels; ch_idx++) { - struct apple_epic_service *old = &ep->services[ch_idx]; - - if (afk_service_supersede(old, ops, channel)) { - dev_info(ep->dcp->dev, - "AFK[ep:%02x]: %s on channel %u supersedes channel %u\n", - ep->endpoint, service_name, channel, old->channel); - afk_remove_service_debugfs(old); - } - } for (ch_idx = 0; ch_idx < AFK_MAX_CHANNEL; ch_idx++) { struct apple_epic_service *candidate = &ep->services[ch_idx]; @@ -1959,6 +1949,21 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, goto free; } } + /* + * Only an admitted, opened successor retires the instance it + * replaces: a replacement rejected above (no slot, admission or OPEN + * failure) leaves the previous instance usable by its owner. + */ + for (ch_idx = 0; ch_idx < ep->num_channels; ch_idx++) { + struct apple_epic_service *old = &ep->services[ch_idx]; + + if (old != service && afk_service_supersede(old, ops, channel)) { + dev_info(ep->dcp->dev, + "AFK[ep:%02x]: %s on channel %u supersedes channel %u\n", + ep->endpoint, service_name, channel, old->channel); + afk_remove_service_debugfs(old); + } + } if (ops->prepare) afk_service_publish(service); if (ops->init_props) diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index 4d8c41ccdae17d..eddd22a96c4351 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -262,9 +262,11 @@ static inline void afk_service_retire_channel(struct apple_epic_service *service * A singleton service has one live instance per endpoint. The firmware * announces it again on a fresh channel when the display is attached again, * without closing the previous channel (as for compact services, see - * afk_compact_slot()). The announcement on @channel then supersedes - * @service: retire it, so that its slot is reclaimed once its last user - * lets go. The successor's init takes over the service's state. + * afk_compact_slot()). Once the instance announced on @channel has been + * admitted, it supersedes @service: retire it, so that its slot is + * reclaimed once its last user lets go. The successor's init takes over + * the service's state. Call this only after the successor holds its own + * slot; a rejected successor must leave @service usable. */ static inline bool afk_service_supersede(struct apple_epic_service *service, const struct apple_epic_service_ops *ops, diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 6fbf19d2a6329f..1a084131f69881 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -479,6 +479,45 @@ def function(file,signature): memset(ep.services,0,sizeof(ep.services));ep.num_channels=AFK_MAX_CHANNEL;ep.ops=announcement_ops; puts("PASS optional absence remains closed; required unsupported and genuine optional failures remain errors"); } +static struct apple_epic_service *singleton_owner; +/* As av_audiosrv_init(): the owner pins the new instance and lets go of the old one. */ +static void singleton_init(struct apple_epic_service *s,const char *n,const char *c,s64 u) +{ + struct apple_epic_service *old=singleton_owner; + singleton_owner=afk_service_get(s);assert(singleton_owner==s); + if(old) afk_service_put(old); +} +static int singleton_prepare(struct apple_epic_service *s,const char *n,const char *c,s64 u) { return 0; } +static void singleton_rejected_replacement(void) +{ + /* A classic AV singleton (no prepare): its replacement must not retire the + * instance it would replace before the replacement has a slot. */ + const struct apple_epic_service_ops single[]={{.name="dcpav-service-epic",.reusable=true,.singleton=true,.prepare=singleton_prepare,.init=singleton_init},{.name=""}}; + memset(ep.services,0,sizeof(ep.services));singleton_owner=NULL; + ep.ops=single;ep.match_epic_name=true;ep.num_channels=0;d.fw_compat=DCP_FIRMWARE_H17P; + announce(1,name,class,1);run_retries(); + struct apple_epic_service *a=singleton_owner; + assert(a && a->channel==1 && a->enabled && !a->torndown && a->users==1); + /* Every other slot is retired with a reply still owed: none is reclaimable. */ + for(unsigned i=0;iops=&single[0];o->torndown=true;o->enabled=false;o->channel=100+i;o->cmd_map[0]|=1; + } + ep.num_channels=AFK_MAX_CHANNEL;diagnostic_errors=0; + announce(5,name,class,5);run_retries(); + assert(diagnostic_errors>=1); + assert(singleton_owner==a && a->enabled && !a->torndown && a->users==1); + assert(afk_service_get(a)==a);afk_service_put(a); + /* A slot comes back: the replacement is admitted, and only then retires the previous instance. */ + ep.services[a==&ep.services[0]?1:0].cmd_map[0]&=~1UL; + announce(5,name,class,5);run_retries(); + assert(singleton_owner && singleton_owner!=a && singleton_owner->channel==5 && singleton_owner->enabled); + assert(a->torndown && !a->enabled && !a->users); + afk_service_put(singleton_owner);singleton_owner=NULL; + memset(ep.services,0,sizeof(ep.services));ep.num_channels=AFK_MAX_CHANNEL;ep.ops=announcement_ops; + puts("PASS a singleton replacement rejected for lack of a slot leaves the previous instance usable; an admitted one retires it"); +} int main(void) { d.hw.iomfb_method_profile=2;d.typec_cable_connected=true;d.typec_generation=1;d.nr_modes=1;d.connector=&con;d.dev=&d; @@ -555,6 +594,7 @@ def function(file,signature): assert(d.dcpavserv.service==pending && pending->users==1);dpavservep_detach(&d); assert(!pending->users && !d.hpd_mutex && !d.dcpavserv.lock); memset(&ep.services,0,sizeof(ep.services));ep.wire_v2=true;ep.endpoint=0x2a;d.hw.iomfb_method_profile=2; + singleton_rejected_replacement(); repeated_announcements(); deferred_announcements(); free(ep.command_tags);ep.command_tags=NULL; From 63f53f29d77165b2e3e91bfb72d9be71d21a3110 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 11:18:44 +1100 Subject: [PATCH 1397/1514] drm/apple: afk-service-test: rewrap the announcement model comment Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk-service-test.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/apple/afk-service-test.c b/drivers/gpu/drm/apple/afk-service-test.c index 2d9c51ad1a0318..fcd64cde1df663 100644 --- a/drivers/gpu/drm/apple/afk-service-test.c +++ b/drivers/gpu/drm/apple/afk-service-test.c @@ -282,8 +282,8 @@ static const struct apple_epic_service_ops singleton_audio_ops = { * The firmware announces its AV video and audio interfaces again on fresh * channels on every display attach and never closes the old ones. Announce * them as the endpoint's receive path does: take the first reclaimable - * slot, then supersede the previous instance. The superseded audio instance stays pinned by its owner - * until the successor's init drops it. + * slot, then supersede the previous instance. The superseded audio + * instance stays pinned by its owner until the successor's init drops it. */ static struct apple_epic_service * afk_test_announce(struct apple_epic_service *slots, unsigned int nr, From 0050f580cc54892302f38e458e609d1b793010e0 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:35:07 -0500 Subject: [PATCH 1398/1514] wifi: apple: centauri: t6050: drop const from the BSS keep helpers ieee80211_bss_get_elem() takes a non-const struct cfg80211_bss, so avoid_keep_bss() discards the qualifier when it passes its const bss. Clang treats that as an error, so main no longer builds with LLVM=1: centauri_wifi.c:308: passing 'const struct cfg80211_bss *' to parameter of type 'struct cfg80211_bss *' discards qualifiers The entries come from cfg80211_bss_iter() as non-const pointers, so keep them non-const through avoid_keep_set() and avoid_keep_bss(). No change in behaviour. Fixes: 47ef5125554a ("wifi: apple: centauri: t6050: unlink every avoided 6 GHz BSS, not only 16") Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c index e93a5bd0afa448..7e338ac938a8a1 100644 --- a/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c +++ b/drivers/net/wireless/apple/centauri/t6050/centauri_wifi.c @@ -295,7 +295,7 @@ struct avoid_find { /* Whether @bss is one to keep. Under cfg80211's BSS lock. */ static bool avoid_keep_bss(const struct avoid_find *find, - const struct cfg80211_bss *bss) + struct cfg80211_bss *bss) { const struct element *ssid; bool same; @@ -317,9 +317,9 @@ static bool avoid_keep_bss(const struct avoid_find *find, * its multiple-BSSID element, which cfg80211 unlinks together. */ static bool avoid_keep_set(const struct avoid_find *find, - const struct cfg80211_bss *bss) + struct cfg80211_bss *bss) { - const struct cfg80211_bss *set = bss->transmitted_bss ?: bss, *member; + struct cfg80211_bss *set = bss->transmitted_bss ?: bss, *member; if (avoid_keep_bss(find, set)) return true; From 9c3c459d84f09c06def9343339b01f232cbcf071 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 17:22:41 -0500 Subject: [PATCH 1399/1514] drm/asahi: g16: keep renders of a multisampling VM apart from other VMs Every VM's render passes go through the one firmware TA/FS queue pair. While passes of two VMs are both published there and one of the VMs renders multisampled, that VM's passes lose coverage: pixels or samples that should be covered come out uncovered or zero (CTS multisample min_sample_shading, alpha_to_coverage, z_export *_atc, mixed_count, standardsampleposition, and resolve_image whole_copy_before_resolving), and its fragment shaders can fault at VA 0 or stall the fragment stage. One VM alone never shows it, nor do VMs that render only single-sampled. Making the later pass's TA wait for the earlier pass's FS with ring barriers does not help: the two passes need not run at the same time, only be published together. Single-sampled passes of a multisampling VM are affected too, such as an attachmentless pass that reads its multisampled images as input attachments. Mark a VM once a multisampled pass of it becomes visible to the firmware, and hold a render while another VM's render flight has not retired if either VM is marked or the render itself is multisampled. Apply the same rule to every member the same-submit and cross-job render folds append, so a multisampled member never joins a prefix beside another VM's render. Renders of one VM, and of VMs that never render multisampled, still queue behind each other. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/command.rs | 5 + drivers/gpu/drm/asahi/g16/engine.rs | 50 ++- drivers/gpu/drm/asahi/g16/vm.rs | 17 +- .../drivers/gpu/asahi-m4/test-publication.py | 393 ++++++++++++++++-- 4 files changed, 431 insertions(+), 34 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 197d31e93fa0f6..50a11bf412b9f5 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -192,6 +192,11 @@ impl RenderCommand { pub(crate) fn is_heavy_ta(&self) -> bool { self.heavy_ta } + + /// Whether this render pass is multisampled. + pub(crate) fn is_multisampled(&self) -> bool { + self.cmd.samples > 1 + } } /// A validated compute command. diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 05a3e003fc7e68..fc08739e9e6710 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -175,6 +175,22 @@ fn scs_compute_conflict(f: &Flight, vm: &Arc, scs: bool) -> f.computes != 0 && (f.rt_compute != scs || (scs && !Arc::ptr_eq(&f.job.vm, vm))) } +/// Whether a render of `vm`, multisampled when `msaa`, must wait for render flight `f` to +/// retire before it is published. +/// +/// Every VM's render passes share the one firmware TA/FS queue pair. While passes of two VMs +/// are both published there and one of the VMs renders multisampled +/// (`VmStateInner::renders_msaa`), that VM's passes can lose coverage (uncovered or zero +/// pixels and samples, also in single-sampled passes that read its multisampled images) and +/// its fragment shaders can read VA 0. Ordering the two passes' TA and FS with ring barriers +/// does not prevent it; publishing one only after the other retired does. Passes of one VM, +/// and passes of VMs that never render multisampled, still share the queues. +fn msaa_render_conflict(f: &Flight, vm: &Arc, msaa: bool) -> bool { + f.renders != 0 + && !Arc::ptr_eq(&f.job.vm, vm) + && (msaa || vm.renders_msaa() || f.job.vm.renders_msaa()) +} + /// Resolved ring-barrier placement for one render pass (legacy, `FRAGMENT_BARRIERS`, or /// `DRM_ASAHI_RENDER_STAGE_PREFIXES`). #[derive(Copy, Clone, Debug, PartialEq, Eq)] @@ -349,6 +365,9 @@ pub(crate) struct Flight { pub(crate) rt_compute: bool, /// Whether this flight includes any heavy-TA render pass (multi-layer or large tilemap). pub(crate) heavy_render: bool, + /// Whether this flight includes a multisampled render pass; its VM is marked + /// (`VmStateInner::note_msaa_render`) once the flight becomes visible. + pub(crate) msaa: bool, } impl Flight { @@ -393,6 +412,7 @@ impl Flight { has_timestamps: false, rt_compute: false, heavy_render: false, + msaa: false, } } } @@ -438,8 +458,9 @@ pub(crate) enum HoldCause { DrainFailed, /// A cold `InitBM` render is in flight. DrainInitbm, - /// Compute behind render of another VM, render behind compute of another VM, or an - /// SCS compute conflict. + /// Compute behind render of another VM, render behind compute of another VM, an SCS + /// compute conflict, or a render beside another VM's render while one of the two VMs + /// renders multisampled. DrainCross, /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. DrainPb, @@ -1414,6 +1435,16 @@ impl Firmware { Ok(()) } + /// Whether render `r` of `vm` may be published beside the flights in flight + /// ([`msaa_render_conflict`]). Every member of a prefix is checked, not only its first. + fn msaa_member_allowed(&self, vm: &Arc, r: &RenderCommand) -> bool { + !self + .engine + .flights + .iter() + .any(|f| msaa_render_conflict(f, vm, r.is_multisampled())) + } + /// Whether `job` requires `self.engine.flights` to drain to empty before it can /// publish (so `alt`-class bypass must not keep refilling the engine ahead of it). fn needs_engine_drain(&self, job: &Arc) -> bool { @@ -1423,12 +1454,14 @@ impl Firmware { let is_rt_compute = is_compute && (job.resources.compute_scs() || matches!(cmd, Some(Command::Compute(c)) if c.is_rt())); + let is_msaa_render = matches!(cmd, Some(Command::Render(r)) if r.is_multisampled()); job.vm.status.get() != 0 || self.engine.flights.iter().any(|f| { f.doomed || f.recovery_suspect || f.initbm || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) + || (is_render && msaa_render_conflict(f, &job.vm, is_msaa_render)) || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) @@ -1731,9 +1764,11 @@ impl Firmware { .flights .iter() .any(|f| f.computes != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let msaa_conflict = !self.msaa_member_allowed(&job.vm, r); let render_count: usize = e.flights.iter().map(|f| f.renders as usize).sum(); let ta_cap = self.ta_wave_cap_for(r.is_heavy_ta()); !cross_vm_compute + && !msaa_conflict && render_count < params::render_flights() && *ta_pending.get_or_insert_with(|| self.ta_pending_passes()) < ta_cap && !self.slots.render_exhausted() @@ -3135,6 +3170,9 @@ impl Firmware { let Some(Command::Render(r2)) = command(job, end) else { break; }; + if !self.msaa_member_allowed(&job.vm, r2) { + break; + } if r2.is_heavy_ta() && !wave_heavy { if ta_pending_before + prefix.renders as usize + 1 > sizes::TA_WAVE_PASSES @@ -3289,6 +3327,10 @@ impl Firmware { precheck_ok = false; break; }; + if !self.msaa_member_allowed(&job.vm, r2) { + precheck_ok = false; + break; + } if r2.is_heavy_ta() { job_heavy = true; } @@ -3435,6 +3477,9 @@ impl Firmware { // 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; + if f.msaa { + job.vm.note_msaa_render(); + } let publication = (|| -> Result { if render { let a = f.pb_slot as usize; @@ -3960,6 +4005,7 @@ impl Firmware { }; f.has_timestamps |= !cmd.timestamp_outputs.is_empty(); f.heavy_render |= cmd.is_heavy_ta(); + f.msaa |= cmd.is_multisampled(); let p = resources.render_pass(k)?; let pass = p.refs(); let heap_bytes = if cmd.cmd.layers > 1 { 0x1000 } else { 0x200 }; diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 2e17f340b93395..b7a76ee776ec4e 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -28,7 +28,7 @@ //! alike. use core::ops::Range; -use core::sync::atomic::{AtomicU32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use kernel::{ drm::gem::BaseObject, new_mutex, @@ -134,6 +134,8 @@ pub(crate) struct VmStateInner { /// Private mappings are kept outside generic close's user GPUVA teardown. context_mappings: KVec, pub(crate) resources: Option>, + /// Set once a multisampled render pass of this VM becomes visible ([`Self::renders_msaa`]). + renders_msaa: AtomicBool, #[allow(dead_code)] pub(crate) live: Arc, } @@ -145,6 +147,18 @@ impl VmStateInner { .as_ref() .is_some_and(|cache| cache.renders_unpublished()) } + + /// Whether this VM has published a multisampled render pass. Its later passes can still + /// read multisampled images (an attachmentless pass reading them as input attachments is + /// single-sampled), so the property is the VM's from then on. + pub(crate) fn renders_msaa(&self) -> bool { + self.renders_msaa.load(Ordering::Relaxed) + } + + /// Records that a multisampled render pass of this VM became visible to the firmware. + pub(crate) fn note_msaa_render(&self) { + self.renders_msaa.store(true, Ordering::Relaxed); + } } impl Drop for VmStateInner { @@ -434,6 +448,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul vm: vm.clone(), context_mappings: mappings, resources: Some(resources), + renders_msaa: AtomicBool::new(false), live, }; let state = Arc::new(VmState(crate::cleanup::Deferred::new(inner)?), GFP_KERNEL)?; 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 209ded86b57948..373b2285d46690 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -53,6 +53,9 @@ def item(declaration): ), 'render_bar must be hoisted ahead of barrier emission' assert prefix_render_fn.count('render_bar,') == 5, prefix_render_fn assert 'p.prev_barrier.write(0, &prev)?;' in prefix_render_fn +# The VM mark waits for visibility: an unpublished prefix never marks its VM. +assert 'note_msaa_render' not in prefix_render_fn +assert 'f.msaa |= cmd.is_multisampled();' in prefix_render_fn assert 'p.ta_fs_barrier.write(0, &ta_fs)?;' in prefix_render_fn assert 'p.fs_dep.write(0, &dep)?;' in prefix_render_fn assert 'p.compute_barrier.write(off, &cbar)?;' in prefix_render_fn @@ -78,6 +81,18 @@ def item(declaration): assert 'DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2' in params_src publish_prefix_body_fn = item('fn publish_prefix_body(') assert 'self.graph.render.threshold.w32(0, prefix.draw as u32)?;' in publish_prefix_body_fn +_visible = publish_prefix_body_fn.index('*visible = true;') +assert publish_prefix_body_fn.count('job.vm.note_msaa_render();') == 1 +assert publish_prefix_body_fn.index('job.vm.note_msaa_render();') > _visible +# Both render fold paths check each member before claiming its pass slot. +_same = publish_prefix_body_fn.index('while more_renders > 0 && end < job.progress.count()') +_horizon = publish_prefix_body_fn.index('// Cross-job render horizon') +assert publish_prefix_body_fn.count('self.msaa_member_allowed(&job.vm, r2)') == 2 +_m1 = publish_prefix_body_fn.index('self.msaa_member_allowed(&job.vm, r2)', _same) +assert _m1 < publish_prefix_body_fn.index('pick_pass_in_for(', _same) < _horizon +_m2 = publish_prefix_body_fn.index('self.msaa_member_allowed(&job.vm, r2)', _horizon) +assert _m2 < publish_prefix_body_fn.index('pick_pass_in_for(', _horizon) +assert 'let msaa_conflict = !self.msaa_member_allowed(&job.vm, r);' in can_queue_behind_fn assert 'self.graph.render.threshold.w32(8, prefix.draw as u32)?;' in publish_prefix_body_fn assert 'earliest_unfinished_ta_draw' not in source and 'rearm_ta_threshold' not in source assert 'let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES]' in publish_prefix_body_fn, 'pipe_fold_cap must only apply to heavy barrier-free compute' @@ -97,13 +112,15 @@ def item(declaration): #[derive(Copy,Clone,Debug,PartialEq,Eq)]enum Channel { Ta = 0, Fs = 1, Compute = 2 } #[derive(Copy,Clone)]struct ComputeCommand { query_access: bool, rt: bool } impl ComputeCommand { fn is_rt(&self) -> bool { self.rt } } -#[derive(Copy,Clone)]struct RenderCommand { heavy_ta: bool } -impl RenderCommand { fn is_heavy_ta(&self) -> bool { self.heavy_ta } } -const R_LIGHT: RenderCommand = RenderCommand { heavy_ta: false }; -const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true }; +#[derive(Copy,Clone)]struct RenderCommand { heavy_ta: bool, msaa: bool } +impl RenderCommand { fn is_heavy_ta(&self) -> bool { self.heavy_ta } fn is_multisampled(&self) -> bool { self.msaa } } +const R_LIGHT: RenderCommand = RenderCommand { heavy_ta: false, msaa: false }; +const R_HEAVY: RenderCommand = RenderCommand { heavy_ta: true, msaa: false }; +const R_MSAA: RenderCommand = RenderCommand { heavy_ta: false, msaa: true }; #[derive(Copy,Clone)]enum Command { Compute(ComputeCommand), Render(RenderCommand) } struct Status(AtomicU32);impl Status{fn get(&self)->u32{self.0.load(Ordering::Relaxed)}} -struct Vm { id:u64, status:Status, slot:u32 } +struct Vm { id:u64, status:Status, slot:u32, msaa:AtomicBool } +impl Vm { fn renders_msaa(&self)->bool{self.msaa.load(Ordering::Relaxed)} fn note_msaa_render(&self){self.msaa.store(true,Ordering::Relaxed)} } struct Queue { turn:AtomicU64, priority:u32, completed:[AtomicU64;2], compute_ooo:AtomicU64, compute_ewma_us:AtomicU32 } impl Queue { fn new(turn:u64, priority:u32)->Arc{ @@ -141,6 +158,7 @@ def item(declaration): struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ +__MSAA_RENDER_CONFLICT__ struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64} impl Engine { __PICK__ @@ -302,12 +320,12 @@ def item(declaration): __PUBLISH__ __PUBLISH_CHECKED__ } -fn mk_vm(slot:u32)->Arc{Arc::new(Vm{id:u64::from(slot),status:Status(AtomicU32::new(0)),slot})} +fn mk_vm(slot:u32)->Arc{Arc::new(Vm{id:u64::from(slot),status:Status(AtomicU32::new(0)),slot,msaa:AtomicBool::new(false)})} fn job_on_vm_mode(id:u32,vm:Arc,render:bool,heavy:bool,sent:u32,dependency:Result)->Arc{ Arc::new(Job{id,vm, queue:Queue::new(0,0), progress:Progress{sent:AtomicU32::new(sent),count:sent+1,pending:AtomicBool::new(true)}, - commands:vec![if render{Command::Render(RenderCommand{heavy_ta:heavy})}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) + commands:vec![if render{Command::Render(RenderCommand{heavy_ta:heavy,msaa:false})}else{Command::Compute(ComputeCommand{query_access:true,rt:false})};sent as usize+1],dependency,terminal_marked:AtomicBool::new(false),resources:Resources}) } fn job_on_vm(id:u32,vm:Arc,render:bool,sent:u32,dependency:Result)->Arc{ job_on_vm_mode(id,vm,render,false,sent,dependency) @@ -904,6 +922,7 @@ def item(declaration): __RENDER_BARRIER_PLAN__ __PLAN_RENDER_BARRIERS__ __SCS_COMPUTE_CONFLICT__ + __MSAA_RENDER_CONFLICT__ impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ __RENDER_CAN_PIPELINE__ @@ -912,6 +931,7 @@ def item(declaration): __TA_WAVE_CAP_FOR__ __CAN_QUEUE_BEHIND__ __CAN_QUEUE_BEHIND_WITH_TA__ + __MSAA_MEMBER_ALLOWED__ __WAIT_STAMP_FOR_WITH__ __WAIT_STAMP_FOR__ __CROSS_ENGINE_WAIT__ @@ -922,8 +942,8 @@ def item(declaration): __CHOOSE_COMPUTE_PIPE__ } #[test]fn timed_compute_queues_behind_same_vm_and_coexists_with_render(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,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)}, @@ -968,8 +988,8 @@ def item(declaration): // gpubench compute.long: a ray-query lane (vm1) beside a long-ALU lane (vm2). The // ray-query dispatch was reported complete with its results unwritten whenever the // other lane's compute ran with it, and its stores then faulted in its closed VM. - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,rt:bool|Arc::new(QueueBehindJob{ @@ -1025,7 +1045,7 @@ def item(declaration): assert!(!p.needs_engine_drain(&alu)); } #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,query_access:bool,wait_vdm:Option,wait_cdm:Option|Arc::new(QueueBehindJob{ @@ -1069,8 +1089,8 @@ def item(declaration): assert!(pr.can_queue_behind(&mk(2,q1.clone(),true,None,None))); } #[test]fn render_queues_behind_same_vm_and_coexists_with_compute_while_blocking_initbm(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, @@ -1113,8 +1133,8 @@ def item(declaration): assert!(!p.can_queue_behind(&c1)); } #[test]fn cross_vm_render_compute_overlap_matrix(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,vm:Arc,queue:Arc,render:bool|Arc::new(QueueBehindJob{ @@ -1154,9 +1174,83 @@ def item(declaration): p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); + // Once a VM renders multisampled, none of its renders shares the TA/FS queues with + // another VM's render, in either order; its own renders still queue behind each other. + let mk_msaa=|id:u32,vm:Arc,queue:Arc|Arc::new(QueueBehindJob{ + id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_MSAA)], + order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let vm2_ms=mk_msaa(6,vm2.clone(),q2.clone()); + // Neither VM has rendered multisampled: only a multisampled render is held. + p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1)]; + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_ms) && p.needs_engine_drain(&vm2_ms)); + // VM1 has rendered multisampled: VM2's single-sampled render is held behind any VM1 + // render flight, VM1's own renders are not. + vm1.note_msaa_render(); + let vm1_ms=mk_msaa(5,vm1.clone(),q1.clone()); + assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm1_ms) && !p.needs_engine_drain(&vm1_ms)); + assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); + assert!(!p.can_queue_behind(&vm2_ms) && p.needs_engine_drain(&vm2_ms)); + // ...and VM1's single-sampled render is held behind any VM2 render flight. + p.engine.flights=vec![mk_flight(vm2_r.clone(),0,1)]; + assert!(!p.can_queue_behind(&vm1_r) && p.needs_engine_drain(&vm1_r)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + // Compute flights carry no render: the existing cross-VM compute rule applies. + p.engine.flights=vec![mk_flight(vm2_c.clone(),1,0)]; + assert!(!p.can_queue_behind(&vm1_ms) && p.needs_engine_drain(&vm1_ms)); + assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); + assert!(p.msaa_member_allowed(&vm1,&R_MSAA)); + } + #[test]fn render_fold_members_obey_cross_vm_msaa_rule(){ + // The same-submit fold and the cross-job horizon fold ask msaa_member_allowed() for + // every candidate member (source-order asserts above): a single-sampled lead of an + // unmarked VM may be admitted beside another VM's render, but a multisampled member + // after it splits the same-submit fold and declines the horizon fold. + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); + let q2=Queue::new(0,0); + let lead=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:Queue::new(0,0),progress:Progress{sent:AtomicU32::new(0),count:2,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT),Command::Render(R_MSAA)], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let other=Arc::new(QueueBehindJob{ + id:2,vm:vm2.clone(),queue:q2,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(R_LIGHT)], + order:Order{engine:command::RENDER,sequence:2,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let in_flight=QueueBehindFlight{ + job:other,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,rt_compute:false,heavy_render:false,published_ns:0, + target:0,cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a}, + fs_target:0x200,initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }; + let mut p=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,pipe_last_vm:[None;hw::sizes::COMPUTE_PIPES],pipe_last_used:[0;hw::sizes::COMPUTE_PIPES],handoff_avoid_pipes:0,flights:vec![in_flight]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // The lead (command 0) is admitted; the multisampled member (command 1) is refused. + assert!(p.can_queue_behind(&lead) && !p.needs_engine_drain(&lead)); + assert!(p.msaa_member_allowed(&vm1,&R_LIGHT)); + assert!(!p.msaa_member_allowed(&vm1,&R_MSAA)); + // Once VM2 is marked, no member of VM1 may join beside it. + vm2.note_msaa_render(); + assert!(!p.msaa_member_allowed(&vm1,&R_LIGHT)); + assert!(!p.can_queue_behind(&lead) && p.needs_engine_drain(&lead)); + // With nothing of another VM in flight every member may join. + p.engine.flights.clear(); + assert!(p.msaa_member_allowed(&vm1,&R_MSAA)); + assert!(!vm1.renders_msaa()); } #[test]fn cross_engine_wait_resolves_barriers_and_skips_no_barrier_or_retired(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let q2=Queue::new(0,0); let mk=|id:u32,queue:Arc,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ @@ -1229,7 +1323,7 @@ def item(declaration): assert_eq!(cross_engine_barrier_type(true, true), BarrierType::Hold); // Verify wait_stamp_for_with / cross_engine_wait propagate producer flight.initbm. - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1270,7 +1364,7 @@ def item(declaration): assert_eq!(fw2.session.transports.load(Ordering::Relaxed),1); } #[test]fn multi_queue_concurrent_compute_and_render_on_same_vm(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q_comp=Queue::new(0,2); let q_rend=Queue::new(0,2); let c_job=Arc::new(QueueBehindJob{ @@ -1308,7 +1402,7 @@ def item(declaration): assert_eq!(p.cross_engine_wait(&c_job,0,command::RENDER),Ok(None)); } #[test]fn cross_engine_wait_and_compute_flight_cap_account_for_batched_horizon_members(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let mk=|id:u32,render:bool,seq:u64,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -1342,7 +1436,7 @@ def item(declaration): assert!(!p.can_queue_behind(&c4)); } #[test]fn multi_pass_render_flight_wait_stamp_and_render_cap(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let multi=Arc::new(QueueBehindJob{ id:1,vm:vm1.clone(),queue:q1.clone(), @@ -1420,12 +1514,12 @@ def item(declaration): assert!(!p.can_queue_behind(&next_r)); } #[test]fn ta_pending_passes_paces_unfinished_ta_waves_without_throttling_finished_ta(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let mk=|id:u32,heavy:bool|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, - commands:vec![Command::Render(RenderCommand{heavy_ta:heavy})], + commands:vec![Command::Render(RenderCommand{heavy_ta:heavy,msaa:false})], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); @@ -1477,8 +1571,8 @@ def item(declaration): assert!(p.can_queue_behind(&next_heavy)); } #[test]fn slot_wait_arms_only_for_same_vm_slot_or_flight_headroom_blocks(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,0); let mk=|id:u32,vm:Arc,render:bool,dep:Result,query_access:bool,wait:[Option;2]|Arc::new(QueueBehindJob{ id,vm,queue:q1.clone(), @@ -1827,8 +1921,8 @@ def item(declaration): ); } #[test]fn two_pipe_concurrent_compute_dispatch_and_fw_timestamp_safety(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); - let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); + let vm2=Arc::new(Vm{id:2,status:Status(AtomicU32::new(0)),slot:2,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let q2=Queue::new(0,2); let mk=|id:u32,vm:Arc,queue:Arc,seq:u64|Arc::new(QueueBehindJob{ @@ -1964,7 +2058,7 @@ def item(declaration): assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), Some(0)); } #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let mk=|id:u32,seq:u64,wait_c:Option|Arc::new(QueueBehindJob{ id,vm:vm1.clone(),queue:q1.clone(), @@ -2027,7 +2121,7 @@ def item(declaration): assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None; sizes::COMPUTE_PIPES])); } #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ - let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1}); + let vm1=Arc::new(Vm{id:1,status:Status(AtomicU32::new(0)),slot:1,msaa:AtomicBool::new(false)}); let q1=Queue::new(0,2); let q2=Queue::new(0,2); let c1=Arc::new(QueueBehindJob{ @@ -2865,7 +2959,7 @@ def item(declaration): vm: vm.clone(), queue: q.clone(), progress: Progress { sent: AtomicU32::new(0), count: 1, pending: AtomicBool::new(true) }, - commands: vec![if render { Command::Render(RenderCommand { heavy_ta: heavy }) } else { Command::Compute(ComputeCommand { query_access: false, rt: false }) }], + commands: vec![if render { Command::Render(RenderCommand { heavy_ta: heavy, msaa: false }) } else { Command::Compute(ComputeCommand { query_access: false, rt: false }) }], orders: vec![Order { engine: if render { crate::command::RENDER } else { crate::command::COMPUTE }, sequence: seq, wait_through: wait }], fw_waits: vec![], resources: Resources { units: 24, scs: false }, @@ -2878,7 +2972,7 @@ def item(declaration): } #[test] fn busy_coalesce_holds_deep_single_queue_bursts_and_never_delays_shallow_or_other_queues() { - let vm1 = Arc::new(Vm { id: 1, status: Status(AtomicU32::new(0)), slot: 1 }); + let vm1 = Arc::new(Vm { id: 1, status: Status(AtomicU32::new(0)), slot: 1, msaa: AtomicBool::new(false) }); let q1 = Queue::new(0, 2); let q2 = Queue::new(0, 2); let c1 = mk_job(&vm1, &q1, false, 1, [None, None]); @@ -2971,8 +3065,243 @@ def item(declaration): assert_eq!(h.defer_busy_coalesce(605_000), None); } } +// Production fold loops and publication prologue of publish_prefix_body, verbatim, around mock +// slots, waits and prefix_render: what they accept, refuse and mark is production behaviour. +mod msaa_fold_scope { + use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + #[derive(Copy,Clone,Debug,PartialEq,Eq)] struct Error(i32); + const EINVAL: Error = Error(22); const EAGAIN: Error = Error(11); const EIO: Error = Error(5); + type Result = std::result::Result; + #[derive(Copy,Clone)] struct Gfp; const GFP_NOWAIT: Gfp = Gfp; + mod sizes { + pub const QUEUE_CAP: u32 = 256; pub const TA_WAVE_PASSES: usize = 4; pub const TA_WAVE_PASSES_LIGHT: usize = 8; + pub const HORIZON_JOBS: u32 = 8; pub const MAX_RENDER_RING_ENTRIES: usize = 5; + } + mod params { pub fn early_tiling() -> bool { true } } + #[allow(non_upper_case_globals)] + mod kernel { pub mod uapi { pub const drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES: u32 = 1 << 23; } } + mod super_vm { pub(super) type VmState = super::Vm; } + #[derive(Copy,Clone)] struct RenderCmd { flags: u32, samples: u16 } + #[derive(Copy,Clone)] struct RenderCommand { cmd: RenderCmd, heavy_ta: bool } + impl RenderCommand { + fn is_heavy_ta(&self) -> bool { self.heavy_ta } + __IS_MULTISAMPLED__ + } + const LIGHT: RenderCommand = RenderCommand { cmd: RenderCmd { flags: 0, samples: 1 }, heavy_ta: false }; + const MSAA: RenderCommand = RenderCommand { cmd: RenderCmd { flags: 0, samples: 4 }, heavy_ta: false }; + #[derive(Copy,Clone)] enum Command { Render(RenderCommand), #[allow(dead_code)] Compute } + struct Geometry; + impl Geometry { fn new_for(_c: &RenderCmd, _heap: u64, _clusters: u32, _generation: u32) -> Self { Geometry } } + struct Binding; impl Binding { fn mark_binding_published(&self) -> Result { Ok(()) } } + struct Vm { id: u64, renders_msaa: AtomicBool, vm: Binding } + impl Vm { + __RENDERS_MSAA__ + __NOTE_MSAA_RENDER__ + } + fn vm(id: u64) -> Arc { Arc::new(Vm { id, renders_msaa: AtomicBool::new(false), vm: Binding }) } + struct Queue; + #[derive(Copy,Clone)] struct Order { sequence: u64, wait_through: [Option; 2], ta_wait_through: [Option; 2] } + struct Progress { count: u32 } impl Progress { fn count(&self) -> u32 { self.count } } + struct Resources; + impl Resources { + fn render_scs(&self) -> bool { false } + fn pb_owner_arena(&self, _k: usize) -> u32 { 0 } + fn pb_uma_lease(&self, _k: usize) -> u32 { 0 } + } + struct Job { id: u32, vm: Arc, queue: Arc, commands: Vec, first_seq: u64, progress: Progress, resources: Resources } + impl Job { + fn long(&self) -> bool { false } + fn command_order(&self, k: u32) -> Option { + Some(Order { sequence: self.first_seq + u64::from(k), wait_through: [None, None], ta_wait_through: [None, None] }) + } + fn can_fold_render_cmd(&self, k: u32, seq: u64) -> bool { seq == self.first_seq + u64::from(k) } + fn can_fold_render_horizon_job(&self, first: u64) -> bool { first == self.first_seq } + } + fn job(id: u32, vm: &Arc, queue: &Arc, first_seq: u64, commands: &[RenderCommand]) -> Arc { + Arc::new(Job { id, vm: vm.clone(), queue: queue.clone(), commands: commands.iter().map(|r| Command::Render(*r)).collect(), + first_seq, progress: Progress { count: commands.len() as u32 }, resources: Resources }) + } + fn command(job: &Job, k: u32) -> Option<&Command> { job.commands.get(k as usize) } + struct Claims { pass: [u32; 48], pass_count: u32, pass_mask: u64 } + struct Group(Vec>); + impl Group { + fn len(&self) -> usize { self.0.len() } + fn reserve(&mut self, n: usize, _g: Gfp) -> std::result::Result<(), ()> { self.0.reserve(n); Ok(()) } + fn push_within_capacity(&mut self, j: Arc) -> std::result::Result<(), Arc> { self.0.push(j); Ok(()) } + } + struct Pb; impl Pb { fn check_assignment(&self, _k: usize) -> Result { Ok(()) } } + struct Flight { job: Arc, renders: u32, claims: Claims, count: usize, group: Group, msaa: bool, pb: Option, pb_slot: u32 } + fn flight(job: &Arc, renders: u32) -> Flight { + Flight { job: job.clone(), renders, claims: Claims { pass: [0; 48], pass_count: 1, pass_mask: 1 }, count: 1, + group: Group(vec![]), msaa: false, pb: Some(Pb), pb_slot: 0 } + } + __MSAA_RENDER_CONFLICT__ + struct Prefix { draw: u64, ta_head: u32, fs_head: u32, renders: u32 } + struct Cfg { num_clusters: u32, gpu_generation: u32 } + struct Slots { pass_busy: u64, publish_fails: bool } + impl Slots { + fn pick_pass_in_for(&self, _r: &Resources, _g: &Geometry, picked: u64, _vm: Option) -> Option { + (0..48).find(|k| (self.pass_busy | picked) & (1u64 << k) == 0) + } + fn verify_held(&self, _c: &Claims) -> Result { Ok(()) } + fn publish(&mut self, _c: &mut Claims) -> Result { if self.publish_fails { Err(EIO) } else { Ok(()) } } + } + struct Pools; impl Pools { fn hold_alloc(&mut self, _k: usize, _vm: &Arc, _a: u32, _l: u32) -> Result { Ok(()) } } + struct Engine { flights: Vec, pending: Vec> } + struct Host { cfg: Cfg, slots: Slots, pools: Pools, engine: Engine, prefixed: Vec<(u32, u32)> } + impl Host { + __MSAA_MEMBER_ALLOWED__ + fn recovery_pending(&self) -> Result { Ok(false) } + fn wait_compute_stamps_for(&self, _j: &Arc, _t: Option) -> Result { Ok(()) } + fn wait_stamp_for_with(&self, _j: &Arc, _c: usize, _t: Option, _f: Option<&Flight>) -> Result { Ok(()) } + #[allow(clippy::too_many_arguments)] + fn prefix_render(&mut self, job: &Arc, _r: &Resources, k: u32, cmd: &RenderCommand, _g: Geometry, + prefix: &mut Prefix, f: &mut Flight, _behind: bool, _class_behind: bool) -> Result { + self.prefixed.push((job.id, k)); + prefix.renders += 1; + prefix.draw += 1; + f.msaa |= cmd.is_multisampled(); + Ok(()) + } + /// The lead (command 0 of `job`) is already prefixed; returns the prefix's end command. + #[allow(unused_assignments, unused_variables, unused_mut)] + fn fold(&mut self, job: &Arc, f: &mut Flight, more: usize) -> Result { + let index = 0u32; + let mut end = 1u32; + let mut prefix = Prefix { draw: 1, ta_head: 0, fs_head: 0, renders: 1 }; + let (ta_read, fs_read) = (0u32, 0u32); + let (behind, class_behind) = (true, true); + let stage_prefix = kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_STAGE_PREFIXES; + let mut last_seq = job.command_order(index).map(|o| o.sequence); + let ta_pending_before = 0usize; + let mut wave_heavy = false; + let mut more_renders = more; + __SAME_SUBMIT_FOLD__ + __HORIZON_FOLD__ + f.renders = prefix.renders; + Ok(end) + } + fn publish_prologue(&mut self, job: &Arc, f: &mut Flight, visible: &mut bool, fail_after: bool) -> Result { + let render = true; + __PUBLICATION_PROLOGUE__ + if fail_after { return Err(EIO); } + Ok(()) + } + } + fn host(flights: Vec, pending: Vec>) -> Host { + Host { cfg: Cfg { num_clusters: 1, gpu_generation: 16 }, slots: Slots { pass_busy: 1, publish_fails: false }, pools: Pools, + engine: Engine { flights, pending }, prefixed: vec![] } + } + #[test] fn same_submit_fold_splits_before_a_multisampled_member_beside_another_vm() { + let (vm1, vm2, q1, q2) = (vm(1), vm(2), Arc::new(Queue), Arc::new(Queue)); + let lead = job(1, &vm1, &q1, 10, &[LIGHT, LIGHT, MSAA, LIGHT]); + let other = job(2, &vm2, &q2, 1, &[LIGHT]); + // Beside another VM's render: the single-sampled member joins, the prefix ends at the + // multisampled one (command 2), which waits for its own publication. + let mut h = host(vec![flight(&other, 1)], vec![]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(2)); + assert_eq!(h.prefixed, [(1, 1)]); + assert!(!f.msaa); + // Nothing of another VM in flight: the whole submit folds. + let mut h = host(vec![], vec![]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(4)); + assert_eq!(h.prefixed, [(1, 1), (1, 2), (1, 3)]); + assert!(f.msaa); + } + #[test] fn cross_job_fold_takes_a_whole_job_or_none_of_it_beside_another_vm() { + let (vm1, vm2, q1, q2) = (vm(1), vm(2), Arc::new(Queue), Arc::new(Queue)); + let lead = job(1, &vm1, &q1, 10, &[LIGHT]); + let other = job(2, &vm2, &q2, 1, &[LIGHT]); + // A single-sampled job folds beside another VM's render. + let light = job(3, &vm1, &q1, 11, &[LIGHT, LIGHT]); + let mut h = host(vec![flight(&other, 1)], vec![lead.clone(), light.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert_eq!(h.prefixed, [(3, 0), (3, 1)]); + assert_eq!(f.group.len(), 1); + assert_eq!(f.renders, 3); + // A job with a multisampled member is declined whole: none of its members is prefixed. + let mixed = job(4, &vm1, &q1, 11, &[LIGHT, MSAA]); + let mut h = host(vec![flight(&other, 1)], vec![lead.clone(), mixed.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert!(h.prefixed.is_empty()); + assert_eq!(f.group.len(), 0); + assert_eq!(f.renders, 1); + // Without another VM in flight the same job folds. + let mut h = host(vec![], vec![lead.clone(), mixed.clone()]); + let mut f = flight(&lead, 1); + assert_eq!(h.fold(&lead, &mut f, 8), Ok(1)); + assert_eq!(h.prefixed, [(4, 0), (4, 1)]); + assert!(f.msaa); + } + #[test] fn only_a_visible_multisampled_prefix_marks_its_vm() { + let q = Arc::new(Queue); + // Refused before visibility: unpublished, the VM stays unmarked. + let v = vm(1); + let j = job(1, &v, &q, 1, &[MSAA]); + let mut h = host(vec![], vec![]); + h.slots.publish_fails = true; + let (mut f, mut visible) = (flight(&j, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j, &mut f, &mut visible, false), Err(EIO)); + assert!(!visible && !v.renders_msaa()); + // Published: marked. + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j, &mut f, &mut visible, false), Ok(())); + assert!(visible && v.renders_msaa()); + // Visible, then failed (uncertain, may run): marked. + let v2 = vm(2); + let j2 = job(2, &v2, &q, 1, &[MSAA]); + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j2, 1), false); + f.msaa = true; + assert_eq!(h.publish_prologue(&j2, &mut f, &mut visible, true), Err(EIO)); + assert!(visible && v2.renders_msaa()); + // A published single-sampled prefix does not mark. + let v3 = vm(3); + let j3 = job(3, &v3, &q, 1, &[LIGHT]); + let mut h = host(vec![], vec![]); + let (mut f, mut visible) = (flight(&j3, 1), false); + assert_eq!(h.publish_prologue(&j3, &mut f, &mut visible, false), Ok(())); + assert!(visible && !v3.renders_msaa()); + let _ = (EAGAIN, EINVAL); + } +} + ''' harness = harness.replace('__LOGIC__', str(production.parent / 'recovery/logic.rs')) + +vm_src = (production.parent / 'vm.rs').read_text() +command_src = (production.parent / 'command.rs').read_text() +_same_fold = item('while more_renders > 0 && end < job.progress.count() {') +_horizon_fold = item('if end == job.progress.count() && more_renders > 0 {') +_prologue_start = source.index(' if self.recovery_pending()? {\n return Err(EAGAIN);\n }\n if render {\n f.pb.as_ref()') +_prologue_end = source.index(' let publication = (|| -> Result {', _prologue_start) +_prologue = source[_prologue_start:_prologue_end] +assert '*visible = true;' in _prologue and 'job.vm.note_msaa_render();' in _prologue +_scope_start = harness.index('mod msaa_fold_scope {') +_scope = harness[_scope_start:] +for token, text in { + '__SAME_SUBMIT_FOLD__': _same_fold, + '__HORIZON_FOLD__': _horizon_fold, + '__PUBLICATION_PROLOGUE__': _prologue, + '__IS_MULTISAMPLED__': item_in(command_src, 'pub(crate) fn is_multisampled('), + '__RENDERS_MSAA__': item_in(vm_src, 'pub(crate) fn renders_msaa('), + '__NOTE_MSAA_RENDER__': item_in(vm_src, 'pub(crate) fn note_msaa_render('), + '__MSAA_RENDER_CONFLICT__': item('fn msaa_render_conflict('), + '__MSAA_MEMBER_ALLOWED__': item('fn msaa_member_allowed('), +}.items(): + assert token in _scope, token + _scope = _scope.replace(token, text + .replace('super::recovery::', 'crate::recovery::') + .replace('super::command::', 'crate::command::') + .replace('super::vm::VmState', 'super_vm::VmState')) +harness = harness[:_scope_start] + _scope harness = harness.replace('__USAGE__', str(production.parent.parent / 'usage.rs')) harness = harness.replace('__FLIGHTS_LINE__', flights_line.strip()) harness = harness.replace('__MAX_QUEUES_LINE__', max_queues_line.strip()) @@ -3050,6 +3379,8 @@ def item(declaration): '__HAS_COMPUTE_PIPE_FOR_VM__': 'fn has_compute_pipe_for_vm(', '__CHOOSE_COMPUTE_PIPE__': 'fn choose_compute_pipe(', '__SCS_COMPUTE_CONFLICT__': 'fn scs_compute_conflict(', + '__MSAA_RENDER_CONFLICT__': 'fn msaa_render_conflict(', + '__MSAA_MEMBER_ALLOWED__': 'fn msaa_member_allowed(', '__WAIT_TARGET__': 'struct WaitTarget {', '__CROSS_ENGINE_BARRIER_TYPE__': 'const fn cross_engine_barrier_type(', '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', From f4ec0b785161caa56a99f2bba2fef6156cf084c1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 10:48:38 +1100 Subject: [PATCH 1400/1514] drm/asahi: keep a G14 27.2 pool command intact until its slot is reused twice On G14 firmware 27.2 the firmware keeps a pool slot on a list while it still has stamp stores queued for it. Each queued record names the retired command's JobMeta (stamp pointer, value, slot). A list pass that finds the slot's retirement cursor advanced unlinks the slot, which clears the word the driver reads as "registered", and only after that reads the records it still holds. The driver reused a slot as soon as it was retired and unregistered, and zeroed and re-encoded the command right away. When that happened while the firmware was still reading the old command's records, the firmware stored through a zero or half-written stamp pointer and faulted (RTKit data abort, FAR 0), and the device was lost. Sustained Vulkan compute (Geekbench 6) hit it within minutes once kernels were timed with Vulkan timestamps or the GPU ran at full clock, both of which raise the submission rate and keep the pool full. Give each slot two command buffers and use them in turn. A retired command stays intact while its slot's next command runs. Its buffer is rewritten only after the slot has been retired and unlinked once more, which the firmware does in a later pass than the one that read the old records. The slot's tracking, stream and retirement rules are unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 31 ++++++++++++++++++++++++++ drivers/gpu/drm/asahi/gpu/v27_2.rs | 18 +++++++++++---- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 313607d3a6c702..bb89a2ed6eeb8c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -146,11 +146,42 @@ pub(crate) fn encode_compute_timestamps(cmd: &mut [u8], cmd_va: u64, timestamps: user_timestamp_pointer(cmd_va + COMPUTE_USER_TIMESTAMPS as u64, timestamps) } +/// The command buffer a pool slot uses: each slot owns two, `2 * slot` and `2 * slot + 1`, +/// and alternates between them. The firmware may still read a retired command's JobMeta for +/// stamp stores it queued after it unlinked the slot, so a slot's next command must not +/// overwrite it. +pub(crate) fn pool_command(slot: usize, second: bool) -> usize { + 2 * slot + usize::from(second) +} + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { use super::*; + #[test] + fn a_slot_never_rewrites_the_command_it_used_last() { + const SLOTS: usize = 48; + let mut owner = [usize::MAX; 2 * SLOTS]; + let mut alternate = 0u64; + let mut last = [usize::MAX; SLOTS]; + for round in 0..5 { + for slot in 0..SLOTS { + alternate ^= 1 << slot; + let c = pool_command(slot, alternate & (1 << slot) != 0); + assert!(c < 2 * SLOTS); + // Two buffers per slot, never shared with another slot. + assert!(owner[c] == usize::MAX || owner[c] == slot); + owner[c] = slot; + // Consecutive uses of a slot take different buffers. + if round > 0 { + assert_ne!(c, last[slot]); + } + last[slot] = c; + } + } + } + #[test] fn head_wraps_and_keeps_one_entry_free() { assert_eq!(queue_head(8, 7, 7, 2), Ok(1)); diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index fc1514c61a8e44..ef33c1eea5ffeb 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -477,7 +477,10 @@ const COMMAND_STRIDE: usize = 0x1000; const STREAM_STRIDE: usize = 0x400; pub(crate) struct CommandPool { + /// Two command buffers per slot, used in turn (`g14_v27_2_abi::pool_command`). commands: fw::types::GpuArray, + /// Which of its two command buffers each slot used last, one bit per slot. + alternate: u64, streams: fw::types::GpuArray, tracking: fw::types::GpuArray, cursors: fw::types::GpuArray, @@ -487,7 +490,7 @@ pub(crate) struct CommandPool { impl CommandPool { pub(crate) fn new(alloc: &mut KernelAllocators, cfg: &'static hw::HwConfig) -> Result { - let commands = alloc.private.array_empty::(POOL_SLOTS * COMMAND_STRIDE)?; + let commands = alloc.private.array_empty::(2 * POOL_SLOTS * COMMAND_STRIDE)?; let streams = alloc.private.array_empty::(POOL_SLOTS * STREAM_STRIDE)?; let mut tracking = alloc.private.array_empty::(POOL_SLOTS * 0x100)?; // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. @@ -498,7 +501,8 @@ impl CommandPool { put64(chunk, 0, base + 0x40 * i as u64); } crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); - Ok(Self { commands, streams, tracking, cursors, stamps, preempt1: cfg.compute_preempt1_size as u64 }) + Ok(Self { commands, alternate: 0, streams, tracking, cursors, stamps, + preempt1: cfg.compute_preempt1_size as u64 }) } /// Builds slot `i` for `job` and returns the command's firmware VA. @@ -516,7 +520,13 @@ impl CommandPool { encode: impl FnOnce(&mut [u8], &mut [u8], crate::g14_v27_2_render::Common) -> Result, ) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } - let cmd_va = self.commands.gpu_va().get() + (i * COMMAND_STRIDE) as u64; + // The firmware may read a retired command's JobMeta after it has unlinked the slot + // (for the stamp stores it still has queued), so the next command of the slot goes + // to the slot's other buffer. A buffer is rewritten only after the slot has been + // retired and unlinked once more, which the firmware does in a later pass. + self.alternate ^= 1 << i; + let c = g14_v27_2_abi::pool_command(i, self.alternate & (1 << i) != 0); + let cmd_va = self.commands.gpu_va().get() + (c * COMMAND_STRIDE) as u64; let stream_va = self.streams.gpu_va().get() + (i * STREAM_STRIDE) as u64; let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; @@ -526,7 +536,7 @@ impl CommandPool { let stamps = &mut self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80]; stamps.fill(0); crate::pgtable::clean_poc(stamps.as_ptr(), stamps.len()); - let cmd = &mut self.commands.as_mut_slice()[i * COMMAND_STRIDE..(i + 1) * COMMAND_STRIDE]; + let cmd = &mut self.commands.as_mut_slice()[c * COMMAND_STRIDE..(c + 1) * COMMAND_STRIDE]; cmd.fill(0); let stream = &mut self.streams.as_mut_slice()[i * STREAM_STRIDE..(i + 1) * STREAM_STRIDE]; stream.fill(0); From 27e52f68bb19c24b665cc4557ff77cacc461868d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 13:24:08 +1100 Subject: [PATCH 1401/1514] drm/asahi: report G14 27.2 pool slot state when the pool stalls When no pool slot becomes free for the command timeout, print the busy and unacknowledged slot masks and, for every slot the firmware still lists or whose cursor differs from its record count, those three values. This is the information needed to tell a firmware that stopped retiring slots from a cursor the driver never advanced. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 11 ++++++++++- drivers/gpu/drm/asahi/gpu/v27_2.rs | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 68ee7faa50efc9..ed4c281443bbc8 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -666,7 +666,16 @@ impl Runtime { Ok(Some(slots)) => slots, Ok(None) => return, Err(err) => { - dev_err!(self.dev, "GPU: command pool stalled: {:?}\n", err); + dev_err!(self.dev, "GPU: command pool stalled: {:?} busy={:#x} unacked={:#x} inflight={} rendering={}\n", + err, state.busy, state.unacked, state.inflight.len(), state.rendering.is_some()); + for slot in 0..POOL_SLOTS { + if let Ok((count, cursor, linked)) = state.pool.describe(slot) { + if linked != 0 || count != cursor { + dev_err!(self.dev, "GPU: slot {}: records={} cursor={} linked={}\n", + slot, count, cursor, linked); + } + } + } self.fail_all(state, err); return; } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index ef33c1eea5ffeb..1759e7fb4262b0 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -570,6 +570,18 @@ impl CommandPool { Ok(true) } + /// Slot `i`'s record count (+0xc), its retirement cursor and whether the firmware still + /// holds it in the queue's tracking list (+0x94), for a stall report. + pub(crate) fn describe(&self, i: usize) -> Result<(u32, u32, u32)> { + if i >= POOL_SLOTS { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::clean_invalidate_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok((self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire), + self.cursors.shared_index(i * 0x40)?.load(Ordering::Acquire), + self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire))) + } + /// Whether the firmware still holds slot `i` in the queue's tracking list (+0x94). pub(crate) fn registered(&self, i: usize) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } From f7b9ee1d121daec95a0d49843e8d993d6e3faca2 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:36:53 -0500 Subject: [PATCH 1402/1514] media: apple: jpeg: arm the watchdog before starting a job aj_device_run() armed the job watchdog only after starting the engine and releasing hw_lock. A completion handled in between found no watchdog to cancel, and the one armed afterwards stayed pending. A later job's schedule_delayed_work() left that earlier expiry in place, so it fired early against whichever context was active by then. Arm the watchdog under hw_lock before the start command, with mod_delayed_work() so that every job gets its full timeout, and record the job's deadline so that an expiry already running for an earlier job leaves the current one alone. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .../media/platform/apple/jpeg/apple-jpeg-drv.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c index cc4ece953fb218..c2e4468e88aa4e 100644 --- a/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c +++ b/drivers/media/platform/apple/jpeg/apple-jpeg-drv.c @@ -55,6 +55,7 @@ struct apple_jpeg { struct apple_jpeg_ctx *active; bool broken; u32 status, int_status, bytes; + unsigned long deadline; /* when the active job times out, in jiffies */ struct delayed_work watchdog; struct apple_jpeg_write writes[APPLE_JPEG_MAX_WRITES]; }; @@ -215,7 +216,11 @@ static void aj_watchdog(struct work_struct *work) spin_lock_irqsave(&jpeg->hw_lock, flags); ctx = jpeg->active; - jpeg->active = NULL; + /* An expiry from an earlier job that was already running: not this job's. */ + if (ctx && time_before(jiffies, jpeg->deadline)) + ctx = NULL; + else + jpeg->active = NULL; if (ctx) { aj_write(jpeg, AJ_MAIN_RUN, 0); aj_write(jpeg, AJ_IRQ_MASK, 0); @@ -301,12 +306,19 @@ static void aj_device_run(void *priv) return; } jpeg->active = ctx; + /* + * Arm the watchdog before the start command, so that the completion + * cannot precede it, and give this job its full timeout even if an + * earlier job's expiry is still pending. + */ + jpeg->deadline = jiffies + msecs_to_jiffies(AJ_JOB_TIMEOUT_MS); + mod_delayed_work(system_percpu_wq, &jpeg->watchdog, + msecs_to_jiffies(AJ_JOB_TIMEOUT_MS)); /* Buffers must be visible before the start command, the last write. */ dma_wmb(); for (int i = 0; i < n; i++) writel(jpeg->writes[i].value, jpeg->regs + jpeg->writes[i].offset); spin_unlock_irqrestore(&jpeg->hw_lock, flags); - schedule_delayed_work(&jpeg->watchdog, msecs_to_jiffies(AJ_JOB_TIMEOUT_MS)); } static const struct v4l2_m2m_ops aj_m2m_ops = { From cc81bde6dd03983cc0d14dac4752bccfb75d9103 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 21:44:13 -0500 Subject: [PATCH 1403/1514] arm64: dts: apple: t8103: give every M1 board the sio alias The boot loader finds the SIO by its "sio" alias: it reserves the SIO firmware, hands over the firmware data and parameters from the ADT, and only then sets the node to "okay". Only the Mac mini (J274) had the alias, so on the MacBook Air (J313), MacBook Pro (J293) and iMacs (J456/J457) the SIO stayed disabled. Their dpaudio1 is enabled in t8103-jxxx.dtsi, but without the SIO it has no DMA device ("No DMA device"), so DisplayPort audio over USB-C never registered a card. Move the alias into t8103-jxxx.dtsi next to the dpaudio1 it serves, as t8112-jxxx.dtsi does. The SIO node itself stays disabled in the DTS; the boot loader enables it once its firmware is set up. Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103-j274.dts | 1 - arch/arm64/boot/dts/apple/t8103-jxxx.dtsi | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8103-j274.dts b/arch/arm64/boot/dts/apple/t8103-j274.dts index 11d55fa84da335..387873272d6991 100644 --- a/arch/arm64/boot/dts/apple/t8103-j274.dts +++ b/arch/arm64/boot/dts/apple/t8103-j274.dts @@ -19,7 +19,6 @@ aliases { ethernet0 = ðernet0; - sio = &sio; }; }; diff --git a/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi index 77485eb85b0b31..961f189cd78557 100644 --- a/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8103-jxxx.dtsi @@ -19,6 +19,7 @@ disp0-piodma = &disp0_piodma; serial0 = &serial0; serial2 = &serial2; + sio = &sio; wifi0 = &wifi0; atcphy0 = &atcphy0; atcphy1 = &atcphy1; From 0ed56efaa61558bc54e8fcf26e251752b2c9d952 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 21:49:58 -0500 Subject: [PATCH 1404/1514] drm/asahi: admit compute sampler heaps on G14 firmware 27.2 The G14 firmware 27.2 queues refused every compute command that names a sampler heap with ENOTSUPP ("M3 compute rejected: ... samplers=1024"), because the 27.2 compute command's sampler placement was not known. On these GPUs Borealis names its sampler heap on every compute command whose shaders sample through a sampler, so compute work that samples textures was dropped on the 27.2 firmware (the M2, and the M1 with its 27.2 support). The firmware loads the sampler heap, the sampler count and the sampler bound of every command type through one handler, keyed by the command type, into the data master's sampler state: TA command +0x558/+0x560/ +0x564, 3D command +0x8bc/+0x8c4/+0x8c8, compute command +0x284/+0x28c/ +0x290. The count and the bound are 11-bit fields. The render builders already write the TA and 3D words. In the compute command these are the 13.5 EncoderParams sampler words, 0x10 bytes further on, as the 3D command's are (13.5 +0x8ac, 27.2 +0x8bc), between the encoder mask (+0x270) and the JobMeta stamps (+0x298). Admit the sampler heap on compute for queues whose builders encode it (the G14 27.2 queues), as render already does. The common compute translator validates the heap (at most 1024 samplers, both fields set or both zero, 8-byte aligned, readable in the submitting VM). Carry it in the compute control to the 27.2 compute encoder, which writes the heap, the count, and the count plus one as the bound, as the 13.5 compute command does; a command without samplers keeps the words zero. The M3 queues still refuse compute sampler heaps. Signed-off-by: Erik Bourget --- drivers/gpu/drm/asahi/g14_v27_2.rs | 2 + drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 52 +++++++++++++++++++++++++ drivers/gpu/drm/asahi/gpu/v27_2.rs | 5 +++ drivers/gpu/drm/asahi/m3/agx_compute.rs | 6 +++ drivers/gpu/drm/asahi/m3/m3_submit.rs | 20 ++++++---- 5 files changed, 77 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 68ee7faa50efc9..154cca60b5590d 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -706,6 +706,8 @@ impl Runtime { preempt, timestamps: packet.timestamp_addresses(index), helper: control.helper, + sampler_heap: control.sampler_heap, + sampler_count: control.sampler_count, }; let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?; let submission = state.root.stage_compute(command)?; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 313607d3a6c702..101c339a90c631 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -138,6 +138,34 @@ pub(crate) fn encode_compute_helper(cmd: &mut [u8], binary: u32, data: u64, conf put32(cmd, COMPUTE_JOB_PARAMETERS1 + 0x50, config); } +/// Where the 27.2 compute command keeps its sampler heap (u64), sampler count and sampler bound: +/// the 13.5 EncoderParams sampler words, 0x10 bytes further on as in the 27.2 fragment command +/// (13.5 0x8ac, 27.2 0x8bc). The firmware loads the same three words of every command type +/// into the data master's sampler state (TA 0x558/0x560/0x564, 3D 0x8bc/0x8c4/0x8c8, compute +/// here), the count and the bound as 11-bit fields. +pub(crate) const COMPUTE_SAMPLER_HEAP: usize = 0x284; +pub(crate) const COMPUTE_SAMPLER_COUNT: usize = 0x28c; +pub(crate) const COMPUTE_SAMPLER_MAX: usize = 0x290; + +/// The sampler bound the 13.5 compute command stores next to the count: the count plus one, +/// or zero without samplers. +pub(crate) fn compute_sampler_max(count: u32) -> u32 { + if count == 0 { + 0 + } else { + count + 1 + } +} + +/// Writes the sampler heap of a zeroed 27.2 compute command. A command without samplers +/// (heap and count zero) keeps the words zero. The caller has validated the heap: at most +/// 1024 samplers, both fields set or both zero. +pub(crate) fn encode_compute_samplers(cmd: &mut [u8], heap: u64, count: u32) { + put64(cmd, COMPUTE_SAMPLER_HEAP, heap); + put32(cmd, COMPUTE_SAMPLER_COUNT, count); + put32(cmd, COMPUTE_SAMPLER_MAX, compute_sampler_max(count)); +} + /// Writes the user timestamp pair of a zeroed 27.2 compute command at `cmd_va` and returns the /// Timestamp operations' user word ([`user_timestamp_pointer`]). pub(crate) fn encode_compute_timestamps(cmd: &mut [u8], cmd_va: u64, timestamps: [u64; 2]) -> u64 { @@ -272,6 +300,30 @@ mod tests { } } + #[test] + fn the_compute_samplers_sit_between_the_encoder_mask_and_the_job_meta() { + let mut cmd = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_samplers(&mut cmd, 0x2d_fff4_4000, 1024); + let read64 = |at: usize| u64::from_le_bytes(cmd[at..at + 8].try_into().unwrap()); + let read32 = |at: usize| u32::from_le_bytes(cmd[at..at + 4].try_into().unwrap()); + assert_eq!( + (read64(0x284), read32(0x28c), read32(0x290)), + (0x2d_fff4_4000, 1024, 1025) + ); + // After the encoder mask (+0x270) and before the JobMeta stamps (+0x298), in no other + // word the compute encoder writes. + for (at, len) in [(0x284, 8), (0x28c, 4), (0x290, 4)] { + assert!(free(at, len)); + assert!(0x270 + 4 <= at && at + len <= 0x298); + } + // The firmware takes the count and the bound as 11-bit fields. + assert!(compute_sampler_max(1024) < 1 << 11); + + let mut none = [0u8; COMPUTE_COMMAND_BYTES]; + encode_compute_samplers(&mut none, 0, 0); + assert!(none.iter().all(|&b| b == 0)); + } + #[test] fn flush_stamps_follows_the_compute_job_meta_and_misses_the_user_pair() { // The JobMeta words the encoder writes end right before it: slot at +0x2b0. diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index fc1514c61a8e44..53e26ba16771df 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -112,6 +112,9 @@ pub(crate) struct ComputeJob { pub(crate) timestamps: [u64; 2], /// The helper program (scratch and stack setup), or zero. pub(crate) helper: crate::m3::agx_uapi::UapiHelperProgram, + /// The sampler heap and its sampler count, or zero. + pub(crate) sampler_heap: u64, + pub(crate) sampler_count: u32, } fn put32(b: &mut [u8], at: usize, v: u32) { @@ -217,6 +220,7 @@ fn encode_compute( put64(cmd, 0x334, timestamps + 0x20); let user = g14_v27_2_abi::encode_compute_timestamps(cmd, cmd_va, job.timestamps); g14_v27_2_abi::encode_compute_helper(cmd, job.helper.binary, job.helper.data, job.helper.config); + g14_v27_2_abi::encode_compute_samplers(cmd, job.sampler_heap, job.sampler_count); put32(stream, 0, 11); // 13.5 StartCompute.unk_28, at the same place in this layout (the 13.5 G14 path writes 1). @@ -455,6 +459,7 @@ impl BootJob { context: 0, sequence: 0, cdm_base: cdm, cdm_end: cdm + 8, usc_base: 0x11_0000_0000, preempt: self.client_va, timestamps: [0; 2], helper: crate::m3::agx_uapi::UapiHelperProgram { binary: 0, config: 0, data: 0 }, + sampler_heap: 0, sampler_count: 0, }; let (cmd_va, stream_va) = (self.command.gpu_va().get(), self.stream.gpu_va().get()); encode_compute(self.command.as_mut_slice(), cmd_va, self.stream.as_mut_slice(), stream_va, diff --git a/drivers/gpu/drm/asahi/m3/agx_compute.rs b/drivers/gpu/drm/asahi/m3/agx_compute.rs index 01c5354748a213..28c2cb592feb42 100644 --- a/drivers/gpu/drm/asahi/m3/agx_compute.rs +++ b/drivers/gpu/drm/asahi/m3/agx_compute.rs @@ -10,4 +10,10 @@ pub(crate) struct Control { /// (`m3_submit::Queue::samplers_and_helpers`). #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] pub helper: crate::m3::agx_uapi::UapiHelperProgram, + /// The sampler heap and its sampler count, both zero unless the queue's command builder + /// encodes them (`m3_submit::Queue::samplers_and_helpers`). + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub sampler_heap: u64, + #[cfg_attr(not(CONFIG_DRM_ASAHI_G14_V27_2), allow(dead_code))] + pub sampler_count: u32, } diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index c825f9492672f9..e56d4755e58ceb 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -319,9 +319,9 @@ pub(crate) struct Queue { /// for every sample count and layer count. Otherwise only the single-sample, /// single-layer compressed depth layout is admitted. zls_compression_all_layouts:bool, - /// Whether this queue's command builders encode the render sampler heap and the render and - /// compute helper programs, in the 13.5 places. Otherwise they are refused: the M3 26.x - /// commands stream their sampler state and carry no helper. + /// Whether this queue's command builders encode the render and compute sampler heaps and + /// helper programs, in the 13.5 places. Otherwise they are refused: the M3 26.x commands + /// stream their sampler state and carry no helper. samplers_and_helpers:bool, urgency:u8, } @@ -356,8 +356,9 @@ impl Queue { // compression words in every layout (g14_v27_2_render.rs). zls_compression_all_layouts:true, // Its render commands carry the sampler heap and both helper programs, and its - // compute command the 13.5 compute JobParameters1 with the helper - // (g14_v27_2_render.rs, gpu/v27_2.rs). + // compute command the 13.5 compute JobParameters1 with the helper and the sampler + // heap words the firmware loads for every command type (g14_v27_2_render.rs, + // g14_v27_2_abi.rs, gpu/v27_2.rs). samplers_and_helpers:true, urgency,preempt_alloc:Some((ualloc_priv,preempt_bytes)), render_queue: Some(render_queue)}) @@ -391,7 +392,7 @@ impl queue::Queue for Queue { // Other engines and helpers need their own M3 firmware translation. let wide=kernel::uapi::drm_asahi_compute_flags_DRM_ASAHI_COMPUTE_WIDE_VISIBILITY as u32; if payload.flags & !wide !=0 || (!self.wide_visibility && payload.flags & wide != 0) - || payload.sampler_count!=0 || payload.sampler_heap!=0 { + || (!self.samplers_and_helpers && (payload.sampler_count!=0 || payload.sampler_heap!=0)) { pr_err!("M3 compute rejected: flags={:#x} samplers={} heap={:#x} attachments={} timestamps={}/{}\n",payload.flags,payload.sampler_count,payload.sampler_heap,attachments.as_slice().len(),payload.timestamps.start.handle,payload.timestamps.end.handle); return Err(ENOTSUPP); } @@ -415,7 +416,7 @@ impl queue::Queue for Queue { let c=agx_uapi::translate_compute_command(payload,attachments, agx_uapi::QueueUscWindow{base:self.usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}, &AddressSpace(&self.vm)).map_err(|e| { - pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper); + pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?} samplers={} heap={:#x}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper,payload.sampler_count,payload.sampler_heap); EINVAL })?; // The launch check decodes the 26.x G15 CDM launch format; G14 streams differ. @@ -425,7 +426,10 @@ impl queue::Queue for Queue { } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; - commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc,helper}),GFP_KERNEL)?; + // The translator checked the heap: at most 1024 samplers, both fields set or both zero, + // 8-byte aligned and readable in this VM. Only a queue that encodes it admits one. + commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc,helper, + sampler_heap:c.sampler_heap,sampler_count:c.sampler_count}),GFP_KERNEL)?; } parser.finish().map_err(|_|EINVAL)?; let preempt=match &self.preempt_alloc { From ff817bf9845c3adda82db50706aa009b9f36444d Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Wed, 25 Nov 2026 21:52:38 -0500 Subject: [PATCH 1405/1514] thunderbolt: apple: keep the T8103 CIO domain up when the router does not sleep On T8103 the ACIO host router must be in ACIO sleep before ps_atc*_cio is powered off: dropping the domain with the router firmware still active resets the SoC. apple_cio_sleep_router_for_stop() logged a failed sleep request and apple_cio_stop() went on to remove the NHI and release the domains anyway. The request can fail before anything is sent to the router (no VSE capability, a failed config read or write) or after it (the controller never reports the sleep state). Return the sleep error and let each caller of apple_cio_stop() say what happens to a router that stays awake: - System sleep and cable changes keep the port up as it was: the NHI, the co-processor and the domains stay, PCIe-C admission reopens and a PCIe tunnel that was requested is restored, as after a tunnel teardown. The suspend notifier gets the error and refuses the sleep; the peer state recorded for the restart is committed only once the port is off. A refused unplug is retried on the next cable change. - A reboot or power-off removes the children but keeps the co-processor and the domains powered until the platform reset. - The unwind of a failed start and driver removal still power off: the start frees the co-processor, and removal detaches the domains with the device. A started port whose NHI is gone cannot send the request either, so that is reported as -ENODEV instead of being treated as asleep. Add a host test of apple_cio_stop() and apple_cio_remove_children() for each case, with negative controls, to pciec-policy-tests.py. Signed-off-by: Erik Bourget --- drivers/thunderbolt/apple.c | 148 ++++++++++++++++++++++++------ tools/asahi/pciec-policy-tests.py | 124 +++++++++++++++++++++++++ 2 files changed, 243 insertions(+), 29 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 694a310767ab15..6dd5422c7da210 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -2094,13 +2094,16 @@ static int apple_nhi_pci_tunnel_post_activate(struct tb_nhi *nhi) return 0; } -static void apple_cio_stop_pcie_tunnel(struct apple_cio *acio) +/* Returns whether a tunnel was requested, for apple_cio_reopen_pcie_tunnel(). */ +static bool apple_cio_stop_pcie_tunnel(struct apple_cio *acio) { + bool requested; int ret; /* Block new requests before draining work, without nesting tb->lock. */ mutex_lock(&acio->pcie_tunnel_lock); acio->pcie_tunnel_stopping = true; + requested = READ_ONCE(acio->pcie_tunnel_requested); WRITE_ONCE(acio->pcie_tunnel_requested, false); mutex_unlock(&acio->pcie_tunnel_lock); cancel_delayed_work_sync(&acio->pcie_tunnel_work); @@ -2112,6 +2115,24 @@ static void apple_cio_stop_pcie_tunnel(struct apple_cio *acio) if (ret) dev_warn(acio->dev, "failed to quiesce PCIe-C before NHI shutdown: %d\n", ret); + return requested; +} + +/* + * Undo apple_cio_stop_pcie_tunnel() for a port that stays up with its NHI: + * reopen admission and bring a requested tunnel's hierarchy back, as after + * a tunnel teardown (apple_cio_activate_pcie_tunnel_locked()). + */ +static void apple_cio_reopen_pcie_tunnel(struct apple_cio *acio, bool requested) +{ + guard(mutex)(&acio->pcie_tunnel_lock); + acio->pcie_tunnel_stopping = false; + if (requested) { + WRITE_ONCE(acio->pcie_tunnel_requested, true); + acio->pcie_bind_retries = APPLE_CIO_PCIE_BIND_RETRIES; + } + if (acio->pcie_quiesce_pending || READ_ONCE(acio->pcie_tunnel_requested)) + mod_delayed_work(system_freezable_wq, &acio->pcie_tunnel_work, 0); } #define APPLE_DP_AUX_POLL_MS 500 @@ -3223,33 +3244,60 @@ static struct platform_device *apple_cio_find_pcie_tunnel(struct apple_cio *acio return pdev; } -static void apple_cio_sleep_router_for_stop(struct apple_cio *acio) +/* + * Returns 0 once the host router is asleep, or when no router was started + * (the unwind of a start whose NHI never came up). A started port whose NHI + * is gone cannot send the request: that is an error too. + */ +static int apple_cio_sleep_router_for_stop(struct apple_cio *acio) { struct platform_device *nhi_pdev; struct apple_nhi *anhi; - int ret; + int ret = acio->current_cable_info ? -ENODEV : 0; lockdep_assert_held(&acio->lock); nhi_pdev = READ_ONCE(acio->nhi_pdev); if (!nhi_pdev) - return; + return ret; device_lock(&nhi_pdev->dev); if (READ_ONCE(acio->nhi_pdev) == nhi_pdev) { anhi = platform_get_drvdata(nhi_pdev); if (anhi && anhi->tb && anhi->tb->root_switch) { scoped_guard(mutex, &anhi->tb->lock) ret = apple_nhi_cio_router_sleep(&anhi->nhi); - if (ret) - dev_warn(acio->dev, - "CIO router sleep before stop failed: %d\n", ret); } } device_unlock(&nhi_pdev->dev); + if (ret) + dev_err(acio->dev, "CIO host router did not go to sleep: %d\n", ret); + return ret; } -static void apple_cio_remove_children(struct apple_cio *acio) +/* + * What a stop does when a host router that must sleep before its domains go + * off (sleep_router_on_stop) does not go to sleep. + */ +enum apple_cio_awake { + /* The port stays up as it was and the error is returned. */ + APPLE_CIO_AWAKE_KEEP, + /* + * The children go, the co-processor and its domains stay powered: a + * reboot or power-off, which the platform reset or power-off ends. + */ + APPLE_CIO_AWAKE_HOLD, + /* + * Power off anyway: a start's unwind frees the co-processor, and a + * removed device detaches its domains. + */ + APPLE_CIO_AWAKE_FORCE, +}; + +static int apple_cio_remove_children(struct apple_cio *acio, + enum apple_cio_awake awake) { struct platform_device *nhi_pdev; + bool pcie; + int ret = 0; lockdep_assert_held(&acio->lock); @@ -3258,15 +3306,22 @@ static void apple_cio_remove_children(struct apple_cio *acio) * across domain removal: it takes tb->lock, which tunnel callbacks hold * when they acquire pcie_tunnel_lock. */ - apple_cio_stop_pcie_tunnel(acio); + pcie = apple_cio_stop_pcie_tunnel(acio); /* * Put the host router firmware into ACIO sleep before tearing down the * NHI and powering off the CIO power domain. On T8103, dropping the * CIO domain while the firmware is still active triggers a SoC reset. + * If it does not sleep, a port that can stay up keeps everything: the + * NHI, PCIe-C admission and a tunnel that was requested come back. */ - if (acio->hw->sleep_router_on_stop) - apple_cio_sleep_router_for_stop(acio); + if (acio->hw->sleep_router_on_stop) { + ret = apple_cio_sleep_router_for_stop(acio); + if (ret && awake == APPLE_CIO_AWAKE_KEEP) { + apple_cio_reopen_pcie_tunnel(acio, pcie); + return ret; + } + } /* * The NHI is the tunnel control plane. Stop it while the tunneled PCIe @@ -3293,6 +3348,7 @@ static void apple_cio_remove_children(struct apple_cio *acio) acio->pcie_tunnel_populated = false; acio->pcie_quiesce_pending = false; } + return ret; } /* @@ -3450,19 +3506,35 @@ static void apple_cio_release_domains(struct apple_cio *acio) /** * apple_cio_stop - Stop and power down the ACIO complex * @acio: ACIO complex to stop + * @awake: what to do if the host router must sleep first and does not * * Remove the NHI and DART children before shutting down the co-processor and * dropping the power-domain links. The Type-C PHY must remain configured * until this function returns. The caller must hold @acio->lock. + * + * Return: 0 once the complex is off; else the router's sleep error, with + * the port still up (APPLE_CIO_AWAKE_KEEP) or only its children removed + * (APPLE_CIO_AWAKE_HOLD). */ -static void apple_cio_stop(struct apple_cio *acio) +static int apple_cio_stop(struct apple_cio *acio, enum apple_cio_awake awake) { int ret; lockdep_assert_held(&acio->lock); if (!acio->current_cable_info) - return; - apple_cio_remove_children(acio); + return 0; + ret = apple_cio_remove_children(acio, awake); + if (ret && awake == APPLE_CIO_AWAKE_KEEP) { + dev_err(acio->dev, "the port stays up with its domains powered\n"); + return ret; + } + if (ret && awake == APPLE_CIO_AWAKE_HOLD) { + dev_err(acio->dev, + "the co-processor and its domains stay powered until the reset\n"); + return ret; + } + if (ret) + dev_err(acio->dev, "powering off its domains with the router awake\n"); /* Try to shut down and power off the co-processor gracefully */ ret = apple_rtkit_poweroff(acio->rtk); @@ -3489,6 +3561,7 @@ static void apple_cio_stop(struct apple_cio *acio) acio->current_cable_info = 0; acio->resume_link_failed = false; acio->link_lost_restart = false; + return 0; } /* @@ -3733,7 +3806,8 @@ static int apple_cio_start(struct apple_cio *acio) return 0; err_depopulate: - apple_cio_remove_children(acio); + /* A router this start brought up with its NHI goes with the co-processor. */ + apple_cio_remove_children(acio, APPLE_CIO_AWAKE_FORCE); err_shutdown_rtkit: /* Ignore errors here since we're about to cut power to the entire block anyway */ apple_rtkit_poweroff(acio->rtk); @@ -4082,7 +4156,7 @@ static int apple_cio_tbt_switch_set(struct typec_thunderbolt_switch_dev *sw, "Invalid cable transition from 0x%x to 0x%x, shutting down instead\n", acio->current_cable_info, acio->target_cable_info); acio->target_cable_info = 0; - apple_cio_stop(acio); + apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); return -EINVAL; } @@ -4119,8 +4193,8 @@ static int apple_cio_tbt_switch_set(struct typec_thunderbolt_switch_dev *sw, return ret; } - apple_cio_stop(acio); - return 0; + /* A router that does not sleep keeps the port up until the next change. */ + return apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); } /* The T6050 firmware sleep, selected by the sleep driver's profile and mem_sleep. */ @@ -4219,8 +4293,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) { ktime_t start = ktime_get(), stop; const char *lstx = "not held"; - bool t6050; - int released; + bool t6050, peer_check, peer_wanted = false; + int released, ret; cancel_delayed_work_sync(&acio->resume_link_work); @@ -4246,8 +4320,8 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) struct platform_device *pcie; bool removes = apple_cio_sleep_removes_domains(acio); int mode = removes ? 1 : READ_ONCE(t6050_sleep_pcie); - int ret = 0; + ret = 0; /* * The T6050 firmware sleep takes the router's power whatever is behind * it. The tunnelled functions go first and in order, while the tunnel @@ -4275,16 +4349,30 @@ static int apple_cio_sleep_teardown(struct apple_cio *acio) dev_info(acio->dev, "powering off port for system sleep (cable info 0x%x)\n", acio->current_cable_info); t6050 = apple_cio_t6050_sleep(acio); - if (t6050 || apple_cio_sleep_removes_domains(acio)) { + peer_check = t6050 || apple_cio_sleep_removes_domains(acio); + if (peer_check) { u64 activity; /* With no NHI the answer is "yes": then nothing is expected back. */ - acio->sleep_peer_wanted = READ_ONCE(acio->nhi_pdev) && - apple_cio_has_peer(acio, &activity); - acio->link_lost_cycles = 0; + peer_wanted = READ_ONCE(acio->nhi_pdev) && + apple_cio_has_peer(acio, &activity); } stop = ktime_get(); - apple_cio_stop(acio); + /* + * A router that does not go to sleep keeps the port up, its PCIe + * hierarchy coming back, and the sleep is refused: deep sleep would + * take the domains down with it. + */ + ret = apple_cio_stop(acio, APPLE_CIO_AWAKE_KEEP); + if (ret) { + dev_err(acio->dev, "refusing system sleep: the port cannot be powered off (%d)\n", + ret); + return ret; + } + if (peer_check) { + acio->sleep_peer_wanted = peer_wanted; + acio->link_lost_cycles = 0; + } acio->sleep_phase = APPLE_CIO_SLEEP_CLOSED; WRITE_ONCE(acio->sleep_restart_owed, true); /* Its displays come back with the port's restart. */ @@ -4622,7 +4710,9 @@ static int apple_cio_pcie_notify(struct notifier_block *nb, * A reboot or power-off shuts the PCIe-C host and the router's and the * tunnel's DARTs down before this device, with the router still running * over them. Stop a started router first, as the port driver does for an - * unplugged cable, and refuse a new start from then on. + * unplugged cable, and refuse a new start from then on. A router that must + * sleep first and does not loses only its children: its domains stay + * powered until the reset or power-off. */ static int apple_cio_reboot_notify(struct notifier_block *nb, unsigned long action, void *data) @@ -4632,7 +4722,7 @@ static int apple_cio_reboot_notify(struct notifier_block *nb, unsigned long acti guard(mutex)(&acio->lock); acio->removing = true; if (acio->current_cable_info) - apple_cio_stop(acio); + apple_cio_stop(acio, APPLE_CIO_AWAKE_HOLD); return NOTIFY_DONE; } @@ -4935,7 +5025,7 @@ static void apple_cio_remove(struct platform_device *pdev) typec_thunderbolt_switch_unregister(acio->tbt_switch); guard(mutex)(&acio->lock); if (acio->current_cable_info) - apple_cio_stop(acio); + apple_cio_stop(acio, APPLE_CIO_AWAKE_FORCE); } diff --git a/tools/asahi/pciec-policy-tests.py b/tools/asahi/pciec-policy-tests.py index 24cde8b617b01c..7093382b9c10d8 100644 --- a/tools/asahi/pciec-policy-tests.py +++ b/tools/asahi/pciec-policy-tests.py @@ -873,6 +873,129 @@ def test_t8122_cio_sleep(out, acio): print('PASS negative control:', name) +CIO_STOP_FIXTURE = r''' +#include +#include +#include +#include +#define ENODEV 19 +#define EIO 5 +#define READ_ONCE(x) (x) +#define lockdep_assert_held(l) ((void)(l)) +#define scoped_guard(type, lock) if ((void)(lock), 1) +#define dev_err(dev, ...) ((void)(dev), errs++) +#define dev_warn(dev, ...) ((void)(dev)) +#define readl(addr) ((void)(addr), 0u) +#define APPLE_CIO_M3_CTRL 0 +#define APPLE_CIO_LSTX_CTRL_LEVEL 1u +struct device { int unused; }; +struct platform_device { struct device dev; }; +struct apple_cio_hw { bool sleep_router_on_stop; bool lstx_after_boot; }; +struct apple_cio { + const struct apple_cio_hw *hw; + int lock, pcie_tunnel_lock, dp_wq; + struct device *dev; + struct platform_device *nhi_pdev; + unsigned int current_cable_info, target_cable_info; + bool pcie_tunnel_populated, pcie_quiesce_pending; + bool resume_link_failed, link_lost_restart; + void *rtk; + char *rc_base; +}; +static int errs, sleep_ret, sleeps, reopens, destroyed, depopulated; +static int poweroffs, freed, released; +static bool apple_cio_stop_pcie_tunnel(struct apple_cio *acio) { (void)acio; return true; } +static int apple_cio_sleep_router_for_stop(struct apple_cio *acio) { (void)acio; sleeps++; return sleep_ret; } +static void apple_cio_reopen_pcie_tunnel(struct apple_cio *acio, bool pcie) { (void)acio; assert(pcie); reopens++; } +static void of_platform_device_destroy(struct device *dev, void *data) { (void)dev; (void)data; destroyed++; } +static void flush_workqueue(int wq) { (void)wq; } +static void of_platform_depopulate(struct device *dev) { (void)dev; depopulated++; } +static int apple_rtkit_poweroff(void *rtk) { (void)rtk; poweroffs++; return 0; } +static void apple_rtkit_mailbox_off(void *rtk) { (void)rtk; } +static void apple_rtkit_free(void *rtk) { (void)rtk; freed++; } +static void apple_cio_cpu_halt(struct apple_cio *acio) { (void)acio; } +static void apple_cio_lstx_hold(struct apple_cio *acio, bool high) { (void)acio; (void)high; } +static void apple_cio_test_log_guards(struct apple_cio *acio) { (void)acio; } +static void apple_cio_release_domains(struct apple_cio *acio) { (void)acio; released++; } +/* PRODUCTION */ +static struct device dev; +static struct platform_device nhi; +static int rtk; +static int stop(const struct apple_cio_hw *hw, int ret, enum apple_cio_awake awake, + struct apple_cio *acio) +{ + *acio = (struct apple_cio){ .hw = hw, .dev = &dev, .nhi_pdev = &nhi, + .current_cable_info = 0x51, .rtk = &rtk }; + errs = sleeps = reopens = destroyed = depopulated = poweroffs = freed = released = 0; + sleep_ret = ret; + return apple_cio_stop(acio, awake); +} +int main(void) +{ + static const struct apple_cio_hw sleeps_first = { .sleep_router_on_stop = true }; + static const struct apple_cio_hw plain = { 0 }; + struct apple_cio acio; + + /* A router that sleeps: the complex goes off whatever the caller. */ + for (int awake = APPLE_CIO_AWAKE_KEEP; awake <= APPLE_CIO_AWAKE_FORCE; awake++) { + assert(stop(&sleeps_first, 0, awake, &acio) == 0); + assert(sleeps == 1 && destroyed == 1 && depopulated == 1 && !reopens); + assert(poweroffs == 1 && freed == 1 && released == 1 && !acio.current_cable_info); + } + /* No sleep needed: unchanged. */ + assert(stop(&plain, -EIO, APPLE_CIO_AWAKE_KEEP, &acio) == 0); + assert(!sleeps && destroyed == 1 && released == 1 && !acio.current_cable_info); + + /* Sleep or cable change: the port stays up with its NHI and domains. */ + assert(stop(&sleeps_first, -EIO, APPLE_CIO_AWAKE_KEEP, &acio) == -EIO); + assert(reopens == 1 && !destroyed && !depopulated && !poweroffs && !freed && !released); + assert(acio.current_cable_info == 0x51 && acio.rtk == &rtk && errs); + + /* Reboot: the children go, the co-processor and the domains stay. */ + assert(stop(&sleeps_first, -ENODEV, APPLE_CIO_AWAKE_HOLD, &acio) == -ENODEV); + assert(!reopens && destroyed == 1 && depopulated == 1); + assert(!poweroffs && !freed && !released && acio.rtk == &rtk && errs); + + /* Removal: the device and its domains go. */ + assert(stop(&sleeps_first, -EIO, APPLE_CIO_AWAKE_FORCE, &acio) == 0); + assert(!reopens && destroyed == 1 && released == 1 && freed == 1 && errs); + + puts("PASS: ACIO stop keeps the port or its domains up for a router that does not sleep"); + return 0; +} +''' + + +def test_cio_stop(out, acio): + enum = re.search(r'^enum apple_cio_awake \{.*?\n\};', acio, re.M | re.S) + assert enum + production = '\n'.join((enum.group(), + function(acio, 'apple_cio_remove_children'), + function(acio, 'apple_cio_stop'))) + code = CIO_STOP_FIXTURE.replace('/* PRODUCTION */', production) + muts = { + 'cio-stop-ignore-sleep-error': ( + 'ret = apple_cio_sleep_router_for_stop(acio);\n' + '\t\tif (ret && awake == APPLE_CIO_AWAKE_KEEP) {', + 'ret = apple_cio_sleep_router_for_stop(acio);\n' + '\t\tif (false) {'), + 'cio-stop-no-reopen': ( + 'apple_cio_reopen_pcie_tunnel(acio, pcie);', '(void)pcie;'), + 'cio-stop-hold-powers-off': ( + 'if (ret && awake == APPLE_CIO_AWAKE_HOLD) {', 'if (false) {'), + 'cio-stop-keep-powers-off': ( + 'if (ret && awake == APPLE_CIO_AWAKE_KEEP) {\n' + '\t\tdev_err(acio->dev, "the port stays up', + 'if (false) {\n' + '\t\tdev_err(acio->dev, "the port stays up'), + } + cases = {'cio-stop-production': code} + for name, (old, new) in muts.items(): + assert code.count(old) == 1, name + cases[name] = code.replace(old, new) + run_cases(out, cases, extra_flags=('-Wextra', '-Wno-unused-parameter')) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('--out', type=Path) @@ -947,6 +1070,7 @@ def main(): out.mkdir(parents=True, exist_ok=True) test_pm_order(out, acio) test_t8122_cio_sleep(out, acio) + test_cio_stop(out, acio) cases = { 'production': code, 'm2-fallback': code.replace( From 890aa2614a21afbb8c5dd726039f8e1d42aa32fb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 14:06:49 +1100 Subject: [PATCH 1406/1514] drm/asahi: move a G14 27.2 pool slot to its other buffer only on publication Encoding a pool command flipped the slot's buffer bit at once. When the publication then failed (for example the in-flight allocation), the command never reached the firmware, but the next attempt on the slot selected the buffer of its last published command and cleared its JobMeta, with no retirement or unlink in between. Always encode into the slot's spare buffer without changing the bit, and flip it only after the command is published: right after the compute submission is published, and for a render pass after both submissions are published. A failed publication is retried in the same spare buffer. Reported-by: Diljit Singh Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 4 ++++ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 26 ++++++++++++++++++-------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 23 +++++++++++++++-------- 3 files changed, 37 insertions(+), 16 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index ed4c281443bbc8..7bde3c145f6eb7 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -724,6 +724,7 @@ impl Runtime { publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; packet.mark_published(); submission.publish(); + state.pool.mark_published(slot); state.last = stamp; state.sequence += 1; state.unacked &= !(1 << slot); @@ -784,6 +785,9 @@ impl Runtime { // Queue the fragment dependency before kicking the tiler that satisfies it. fs_post.publish(); ta_post.publish(); + for slot in slots { + state.pool.mark_published(slot); + } for slot in slots { state.busy |= 1 << slot; state.unacked &= !(1 << slot); diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index bb89a2ed6eeb8c..816539f3580b1f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -154,29 +154,39 @@ pub(crate) fn pool_command(slot: usize, second: bool) -> usize { 2 * slot + usize::from(second) } +/// Whether slot `slot`'s next command goes to its second buffer: the one it did not last +/// publish, given one bit per slot set when the last published command used the second. +/// Encoding does not change the bits, so a command that is encoded but never published is +/// replaced in the same spare buffer. +pub(crate) fn spare_buffer(published: u64, slot: usize) -> bool { + published & (1 << slot) == 0 +} + #[cfg_attr(not(test), kunit_tests(asahi_g14_fw_queues))] #[cfg_attr(test, allow(dead_code))] mod tests { use super::*; #[test] - fn a_slot_never_rewrites_the_command_it_used_last() { + fn a_slot_never_rewrites_the_command_it_published_last() { const SLOTS: usize = 48; let mut owner = [usize::MAX; 2 * SLOTS]; - let mut alternate = 0u64; + let mut published = 0u64; let mut last = [usize::MAX; SLOTS]; - for round in 0..5 { + for round in 0..6 { for slot in 0..SLOTS { - alternate ^= 1 << slot; - let c = pool_command(slot, alternate & (1 << slot) != 0); + let c = pool_command(slot, spare_buffer(published, slot)); assert!(c < 2 * SLOTS); // Two buffers per slot, never shared with another slot. assert!(owner[c] == usize::MAX || owner[c] == slot); owner[c] = slot; - // Consecutive uses of a slot take different buffers. - if round > 0 { - assert_ne!(c, last[slot]); + // Never the buffer the slot last published. + assert_ne!(c, last[slot]); + // Every third slot's publication fails once: the retry takes the same spare. + if (slot + round) % 3 == 0 { + assert_eq!(pool_command(slot, spare_buffer(published, slot)), c); } + published ^= 1 << slot; last[slot] = c; } } diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1759e7fb4262b0..4d16adc052a953 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -479,8 +479,8 @@ const STREAM_STRIDE: usize = 0x400; pub(crate) struct CommandPool { /// Two command buffers per slot, used in turn (`g14_v27_2_abi::pool_command`). commands: fw::types::GpuArray, - /// Which of its two command buffers each slot used last, one bit per slot. - alternate: u64, + /// Which of its two command buffers each slot last published, one bit per slot. + published: u64, streams: fw::types::GpuArray, tracking: fw::types::GpuArray, cursors: fw::types::GpuArray, @@ -501,7 +501,7 @@ impl CommandPool { put64(chunk, 0, base + 0x40 * i as u64); } crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); - Ok(Self { commands, alternate: 0, streams, tracking, cursors, stamps, + Ok(Self { commands, published: 0, streams, tracking, cursors, stamps, preempt1: cfg.compute_preempt1_size as u64 }) } @@ -521,11 +521,12 @@ impl CommandPool { ) -> Result { if i >= POOL_SLOTS { return Err(EINVAL); } // The firmware may read a retired command's JobMeta after it has unlinked the slot - // (for the stamp stores it still has queued), so the next command of the slot goes - // to the slot's other buffer. A buffer is rewritten only after the slot has been - // retired and unlinked once more, which the firmware does in a later pass. - self.alternate ^= 1 << i; - let c = g14_v27_2_abi::pool_command(i, self.alternate & (1 << i) != 0); + // (for the stamp stores it still has queued), so the slot's next command goes to its + // other buffer. A buffer is rewritten only after the slot has been retired and + // unlinked once more, which the firmware does in a later pass. Encoding always + // takes the spare; `published` moves it only once the firmware can see the command, + // so a publication that fails leaves the last published buffer alone. + let c = g14_v27_2_abi::pool_command(i, g14_v27_2_abi::spare_buffer(self.published, i)); let cmd_va = self.commands.gpu_va().get() + (c * COMMAND_STRIDE) as u64; let stream_va = self.streams.gpu_va().get() + (i * STREAM_STRIDE) as u64; let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; @@ -550,6 +551,12 @@ impl CommandPool { Ok(cmd_va) } + /// Slot `i`'s command, encoded in its spare buffer, is now visible to the firmware: the + /// next encode of the slot takes the other buffer. + pub(crate) fn mark_published(&mut self, i: usize) { + if i < POOL_SLOTS { self.published ^= 1 << i; } + } + /// Retirement: advance slot `i`'s cursor to the value the firmware recorded at /// tracking +0xc, so its retirement scan unlinks the slot from the queue's list. /// From 8f48bf8f1c2488d797af72a6a34bb44020d2e858 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:15 -0500 Subject: [PATCH 1407/1514] Bluetooth: hci_bcm4377: Bound completion ring polling Sample and validate the device producer index once per poll. Order the completion entry reads after that snapshot and limit the work to the ring capacity. Leave entries published later for the next interrupt. Exercise invalid indices, an empty ring, wraparound and producer progress during polling with the host test. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- MAINTAINERS | 1 + drivers/bluetooth/hci_bcm4377.c | 25 ++++--- tools/asahi/bcm4377-completion-tests.py | 96 +++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 10 deletions(-) create mode 100755 tools/asahi/bcm4377-completion-tests.py diff --git a/MAINTAINERS b/MAINTAINERS index 9027f2eb83928f..798e34ac61c303 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2786,6 +2786,7 @@ F: Documentation/power/apple-s2idle.rst F: arch/arm64/boot/dts/apple/ F: drivers/bluetooth/hci_bcm4377.c F: drivers/bluetooth/hci_bcm4377_test.c +F: tools/asahi/bcm4377-completion-tests.py F: tools/asahi/bcm4377-sleep-config-tests.* F: drivers/clk/clk-apple-nco.c F: drivers/cpufreq/apple-soc-cpufreq.c diff --git a/drivers/bluetooth/hci_bcm4377.c b/drivers/bluetooth/hci_bcm4377.c index 9e0a5f1ac1637e..f133a0257f4f47 100644 --- a/drivers/bluetooth/hci_bcm4377.c +++ b/drivers/bluetooth/hci_bcm4377.c @@ -875,26 +875,31 @@ static void bcm4377_handle_completion(struct bcm4377_data *bcm4377, static void bcm4377_poll_completion_ring(struct bcm4377_data *bcm4377, struct bcm4377_completion_ring *ring) { - u16 tail; __le16 *heads = bcm4377->ring_state->completion_ring_head; __le16 *tails = bcm4377->ring_state->completion_ring_tail; + u16 head, tail, i; if (!ring->enabled) return; + /* Sample the producer index after the interrupt status read. */ + dma_rmb(); + head = le16_to_cpu(READ_ONCE(heads[ring->ring_id])); + if (head >= ring->n_entries) { + dev_warn_ratelimited(&bcm4377->pdev->dev, + "invalid head %u for completion ring %u\n", + head, ring->ring_id); + return; + } + tail = le16_to_cpu(tails[ring->ring_id]); dev_dbg(&bcm4377->pdev->dev, "completion ring #%d: head: %d, tail: %d\n", ring->ring_id, - le16_to_cpu(heads[ring->ring_id]), tail); - - while (tail != le16_to_cpu(READ_ONCE(heads[ring->ring_id]))) { - /* - * ensure the CPU doesn't speculate through the comparison. - * otherwise it might already read the (empty) queue entry - * before the updated head has been loaded and checked. - */ - dma_rmb(); + head, tail); + /* Read the published entries after observing the device's head. */ + dma_rmb(); + for (i = 0; tail != head && i < ring->n_entries; i++) { bcm4377_handle_completion(bcm4377, ring, tail); tail = (tail + 1) % ring->n_entries; diff --git a/tools/asahi/bcm4377-completion-tests.py b/tools/asahi/bcm4377-completion-tests.py new file mode 100755 index 00000000000000..e38a2b35d8b37a --- /dev/null +++ b/tools/asahi/bcm4377-completion-tests.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Run the driver's completion poll against an in-memory producer.""" +from pathlib import Path +import subprocess +import tempfile + +DRIVER = Path(__file__).resolve().parents[2] / "drivers/bluetooth/hci_bcm4377.c" + +FIXTURE = r""" +#include +#include +#include +typedef uint16_t u16; +typedef uint16_t __le16; + +struct ring_state { + __le16 completion_ring_head[1], completion_ring_tail[1]; +}; +struct bcm4377_data { + struct ring_state *ring_state; +}; +struct bcm4377_completion_ring { + u16 ring_id, n_entries; + bool enabled; +}; + +#define READ_ONCE(x) (x) +#define dma_rmb() ((void)0) +#define le16_to_cpu(x) (x) +#define cpu_to_le16(x) (x) +#define dev_dbg(...) ((void)0) +#define dev_warn_ratelimited(...) ((void)0) + +static u16 slots[4]; +static unsigned int handled; +static bool advance_head; + +static void bcm4377_handle_completion(struct bcm4377_data *data, + struct bcm4377_completion_ring *ring, u16 tail) +{ + assert(handled < ring->n_entries); + slots[handled++] = tail; + if (advance_head) + data->ring_state->completion_ring_head[ring->ring_id] = 2; +} +""" + +CASES = r""" +int main(void) +{ + struct ring_state state = {}; + struct bcm4377_data data = { .ring_state = &state }; + struct bcm4377_completion_ring ring = { + .n_entries = sizeof(slots) / sizeof(slots[0]), .enabled = true, + }; + u16 invalid[] = { ring.n_entries, UINT16_MAX }; + u16 last = ring.n_entries - 1; + + state.completion_ring_tail[0] = last; + for (unsigned int i = 0; i < sizeof(invalid) / sizeof(invalid[0]); i++) { + state.completion_ring_head[0] = invalid[i]; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 0 && state.completion_ring_tail[0] == last); + } + + state.completion_ring_head[0] = last; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 0 && state.completion_ring_tail[0] == last); + + /* Wrap around. A completion added mid-poll belongs to the next poll. */ + state.completion_ring_head[0] = 1; + advance_head = true; + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 2 && slots[0] == last && slots[1] == 0); + assert(state.completion_ring_tail[0] == 1); + bcm4377_poll_completion_ring(&data, &ring); + assert(handled == 3 && slots[2] == 1 && state.completion_ring_tail[0] == 2); +} +""" + + +def main(): + source = DRIVER.read_text() + start = source.index("static void bcm4377_poll_completion_ring(") + end = source.index("\n}", start) + 2 + with tempfile.TemporaryDirectory() as directory: + binary = Path(directory) / "completion-test" + subprocess.run(["cc", "-std=gnu11", "-Wall", "-Wextra", "-Werror", + "-x", "c", "-", "-o", binary], check=True, + input=FIXTURE + source[start:end] + "\n" + CASES, text=True) + subprocess.run([binary], check=True, timeout=5) + + +if __name__ == "__main__": + main() From 1015e9c61f02fe095b0ff9b49d0a76214277004e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 14:22:42 +1100 Subject: [PATCH 1408/1514] drm/asahi: re-advance a listed G14 27.2 pool slot's cursor before skipping it The firmware keeps a pool slot listed until the slot's retirement cursor equals the number of records it counted for the slot. It can count another record for a retired slot after the driver advanced the cursor. The driver advanced it only once per retirement, so such a slot stayed listed for good. Under sustained load every slot ended up there and the pool stalled: "command pool stalled", with no slot busy or awaiting acknowledgement, and every slot listed with its record count one above its cursor. When the free-slot search finds a slot that is not busy but still listed, advance its cursor to the current count. The slot's last command is kept intact in its buffer, so the earlier unlink this allows is safe. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 7bde3c145f6eb7..5a59faa3be8131 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -627,6 +627,11 @@ impl Runtime { let slot = (state.next_slot + k) % POOL_SLOTS; if state.busy & (1 << slot) != 0 { continue; } if state.pool.registered(slot)? { + // The firmware can count another record for a retired slot after its cursor + // was advanced, and keeps the slot listed until the cursor matches again: + // advance it to the current count. The slot's last command stays intact in + // its buffer, so an early unlink is harmless. + state.pool.retire(slot)?; state.skipped += 1; continue; } From 8fd602ebb8b96c89a81cf63a757e8f71f9dba098 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 21:41:09 -0500 Subject: [PATCH 1409/1514] drm/asahi: g17: keep G17P work nodes and compute descriptors firmware-cached linux#3170 made every firmware-mutable pooled G17 object uncached after a J716c (T6050) compute queue record, rebound in place, had a dirty firmware line revert the host's owner fields. On the MacBook Neo (J700, A18 Pro) that made light submissions 20-30% slower, because the G17P firmware reads and updates these objects on every kick. In one boot, giving each family back its pre-linux#3170 cached prefix showed where the time goes (gpubench-vk, us per submission): family re-cached render.light queue d4 d8 d32 compute.light d4 none (main) 43.6 38.2 37.0 26.4 render queue records 41.9 36.3 34.6 26.5 work nodes 36.4 31.6 29.5 22.7 compute descriptors 43.9 38.2 36.5 24.5 compute graph 43.7 38.2 36.6 26.4 all of them (pre-linux#3170) 34.1 29.1 27.3 21.1 The host rewrites neither the work nodes nor the compute descriptors while the firmware may still be updating them: - It rewrites a work node only after WorkStorage::drained() has read the firmware's final completed count from memory, and zeroes a returned work state only once its pool fence is met. - It rewrites a compute descriptor slot only after the kick that last used it retired; at most DESCRIPTORS kicks are in flight. A test-only detector on J700 checked this while the full dEQP-VK.synchronization2.op.multi_queue.* family, render.light, compute.light and the compute CRCs ran. It read each work node back just before the host re-initialised it, and hashed each compute descriptor after the host wrote it and again just before the host rewrote it. With the cached mappings, across 1,151,688 node re-inits and 778,522 descriptor rewrites, no host-written word of a node was ever reverted. The firmware's stores to node lines 2-3 were already in memory at every re-init, and its stores near the end of a descriptor at 99.94% of rewrites: the same fractions as with the uncached mappings (1,007,416 and 700,934 checks). The CTS family passed 4266/0 in both modes. Objects the host rewrites in place while their queue may run keep linux#3170's uncached mappings everywhere: render queue records (retargeted, and bound to a work slot on every G17P render submission), the compute graph, and the M5 scheduler pages. M5 keeps all of linux#3170. On G17P, map the work-node page and the compute descriptor ring firmware-cached again, and pin the policy in tools/asahi/g17-object-fence-tests.py with four mutations. On origin/main 16da00248bc9, separate one-shot J700 boots, without and with this change: render.light queue d4/d8/d32 42.5/37.8/36.4 -> 35.9/31.2/29.4 us, queues d2/d4/d8 57.5/47.4/43.8 -> 52.5/42.2/38.4 us, compute.light d4 26.4 -> 21.3 us; the multi_queue CTS family 4266/0 three times, compute CRCs 5/5, offline Geekbench 6 Vulkan 8/8 with no validation errors, and no GPU fault, WARN or AVC. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/context.rs | 11 +++-- drivers/gpu/drm/asahi/g17/queue/compute.rs | 20 ++++---- tools/asahi/g17-object-fence-tests.py | 53 ++++++++++++++++++++++ tools/asahi/run-host-tests.py | 4 +- 4 files changed, 76 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 6e377d0f29a429..3ca44bf6a4df48 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -304,13 +304,18 @@ impl Context { let scheduler_generation = super::ids::OBJECTS.object()?; let scheduler = Arc::new(scheduler, GFP_KERNEL)?; // Both firmware and host write work nodes (reused every 63 submissions - // and zeroed on pool reuse). Keep the whole work-state object uncached - // while retaining its VA and return mark in the pool. + // and zeroed on pool reuse). M5 keeps the whole work-state object + // uncached. G17P maps the node page firmware-cached: the host rewrites + // a node only after `WorkStorage::drained` has read the firmware's + // final `completed` count from memory, and zeroes a returned object + // only once its pool fence is met, so it never rewrites a node the + // firmware is still updating. The counter page, which the host writes + // on every kick, stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, 2 * UAT_PGSZ, - 0, + if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }, kernel_prot, CpuMap::WriteCombined, )?; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index b439fdb0b8e36a..67c78957fb3643 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -106,20 +106,24 @@ pub(crate) struct DescriptorRing { } impl DescriptorRing { - /// Keep compute descriptors uncached while retaining their VA and fence in - /// the pool: M5 common firmware clears the descriptor's accounting counter - /// at `+0xfac`, and the host rewrites each slot every 32 kicks, so a - /// firmware-cached mapping carries the same dirty-line writeback hazard. - /// The hardware reads the same pages through an uncached canonical low - /// alias; on M5 the kernel mapping, in the upper half every execution - /// context includes, is firmware-only. + /// Both firmware and host write compute descriptors: the firmware updates + /// an accounting word near the end of each descriptor (`+0xfac` on M5), + /// and the host rewrites each slot every 32 kicks. M5 keeps them uncached + /// against the dirty-line writeback hazard of linux#3170, while retaining + /// their VA and fence in the pool. G17P maps them firmware-cached, as it + /// does render descriptors: the host rewrites a slot only after the kick + /// that last used it retired (at most `DESCRIPTORS` kicks are in flight), + /// by when that kick's accounting store is in memory. The hardware reads + /// the same pages through an uncached canonical low alias; on M5 the + /// kernel mapping, in the upper half every execution context includes, is + /// firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( alloc, Family::Descriptor, size, - 0, + if alloc.uat.is_m5() { 0 } else { size }, if alloc.uat.is_m5() { mmu::PROT_FW_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }, CpuMap::WriteCombined, )?; diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index fe4eccf9e96e9d..fc672d2e8ce279 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -17,6 +17,10 @@ match the pool before linux#1978 (BASE) on the same random operations. - Source rules: every accessor that hands the address to the firmware marks it, and only the release path of `retain_linked_work` marks it released. +- Cache policy (linux#3170 and its G17P follow-up): records the host rewrites + in place (render queue records, the compute graph, M5 scheduler pages) stay + uncached on every G17; work nodes and compute descriptors are uncached on M5 + and keep their firmware-cached prefix on G17P. `--mutation` applies one known-bad change to the compiled copy; the run must then fail. @@ -47,6 +51,14 @@ 'node-unmarked': ('context', ' self.context.expose_work();\n', ''), # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), + # M5 work nodes are firmware-cached again. + 'm5-cached-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', 'UAT_PGSZ'), + # M5 compute descriptors are firmware-cached again. + 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), + # Render queue records, which the host retargets in place, are firmware-cached again. + 'cached-queue-records': ('policy-memory', 'GRAPH_SIZE,\n 0,\n', 'GRAPH_SIZE,\n 0x8000,\n'), + # G17P work nodes lose their cached prefix (the linux#3170 light-submission cost). + 'uncached-g17p-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', '0'), } @@ -819,6 +831,32 @@ def source_rules(context, observation, tree): print('source: records and commands mark the work state; only a consumed empty-list release releases it') +def cache_policy(context, compute, memory): + """The firmware-cached prefix each pooled G17 object family gets. Returns the failures.""" + failures = [] + + def need(text, pattern, what): + if not re.search(pattern, text): + failures.append(what) + + # Work nodes: uncached on M5, the node page cached on G17P; the counter page stays uncached. + need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*' + r'if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ UAT_PGSZ \},', 'work nodes: M5 uncached, G17P node page cached') + # M5 scheduler pages, which are zeroed and reinitialised on reuse, stay uncached. + need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') + # Compute descriptors: uncached on M5, cached on G17P. + need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', + 'compute descriptors: M5 uncached, G17P cached') + # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. + need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', + 'compute graph uncached') + if 'Family::QueueState' in compute: + failures.append('compute graph not pooled') + # Render queue records, retargeted and bound to work slots in place, stay uncached. + need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*0,\s*prot,', 'render queue records uncached') + return failures + + def main(): ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) ap.add_argument('--mutation', choices=sorted(MUTATIONS)) @@ -832,6 +870,21 @@ def main(): check=True, capture_output=True, text=True).stdout source_rules(ctx, observation, DRIVER) + policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), + 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text()} + if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): + where, old, new = MUTATIONS[args.mutation] + policy[where[len('policy-'):]] = replace(policy[where[len('policy-'):]], old, new) + failures = cache_policy(policy['context'], policy['compute'], policy['memory']) + for failure in failures: + print(f'FAIL line 0: cache policy: {failure}') + if failures: + return 1 + print('cache policy: in-place rewritten records uncached everywhere; work nodes and compute descriptors ' + 'uncached on M5 and cached on G17P') + if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): + return 0 + now = pool_source(obj) pages, methods, node = context_source(ctx) if args.mutation: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 08fbb64334f06e..0414e805a433b0 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -349,7 +349,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-growth-tests.py': [([], PASS)], 'g17-object-fence-tests.py': [([], PASS)] + mutations('--mutation', ('overrun-work-states', 'unseen-strict', 'retain-not-sticky', - 'node-unmarked', 'no-release'), []), + 'node-unmarked', 'no-release', 'm5-cached-nodes', + 'm5-cached-descriptors', 'cached-queue-records', + 'uncached-g17p-nodes'), []), 'g17-owner-release-order-tests.py': [([], PASS)], 'g17-pool-release-tests.py': [([], PASS)], # no-drain-release is the old rule: only a lease ends a slot's quarantine. From a7b698f50a707db723188986ff655a9d49b2e2f0 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:32:57 -0500 Subject: [PATCH 1410/1514] selftests: asahi: Run the BCM4377 completion poll test Register the completion poll regression alongside the existing BCM4377 host tests so the standard runner discovers and executes it. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- tools/asahi/run-host-tests.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 20b5be0097ebf8..0c9eb59a4da05c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -160,6 +160,7 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('round-up', 'cpu-unaligned', 'seg-cpu-unaligned', 'seg-any-size', 'ref-index-upper', 'frame-width-unchecked'), out()), 'avd-codec-tail-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'bcm4377-completion-tests.py': [([], PASS)], # The old revision is the one before the J493 hardware-table ID match. 'bcm4377-id-tests.py': [(out() + ['--old-ref', '87ddae1397f6f70817cb57df76477a86bdf96424'], PASS)], # These mutations are caught inside the test, which then exits 0. From 2bd6229136e369b022be7643c72469596ec678f6 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:26 -0500 Subject: [PATCH 1411/1514] dt-bindings: hwmon: apple,smc-hwmon: add SoC die passive and hot trips Add apple,soc-die-passive-millicelsius and apple,soc-die-hot-millicelsius. They give the macsmc_soc_die thermal zone the machine's SoC die limits: the temperature from which in-kernel power consumers shed performance and the one at which they hold their lowest state. Each requires the other and apple,soc-die-keys. The hot trip only reports and never shuts the machine down. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- .../bindings/hwmon/apple,smc-hwmon.yaml | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml index d1224aa9f467fb..fe5e0e629458e9 100644 --- a/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml +++ b/Documentation/devicetree/bindings/hwmon/apple,smc-hwmon.yaml @@ -100,6 +100,23 @@ properties: from the machine's ADT or SMC rather than hardcoded in static board .dts files. + apple,soc-die-passive-millicelsius: + maxItems: 1 + description: + Passive trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone. In-kernel power consumers begin shedding performance at + this temperature. Taken from the machine's ADT. Requires + apple,soc-die-keys and apple,soc-die-hot-millicelsius. + + apple,soc-die-hot-millicelsius: + maxItems: 1 + description: + Hot trip temperature, in millidegrees Celsius, on the macsmc_soc_die + thermal zone. In-kernel power consumers hold their lowest performance + state at this temperature. Taken from the machine's ADT. Must be above + apple,soc-die-passive-millicelsius. The trip reports the event without + shutting the machine down. + apple,thermal-pressure-key: $ref: /schemas/types.yaml#/definitions/string pattern: "^[A-Za-z0-9]{4}$" @@ -199,6 +216,12 @@ dependentRequired: - apple,soc-die-keys - apple,soc-die-fan-trip-millicelsius - apple,soc-die-fan-hysteresis-millicelsius + apple,soc-die-passive-millicelsius: + - apple,soc-die-keys + - apple,soc-die-hot-millicelsius + apple,soc-die-hot-millicelsius: + - apple,soc-die-keys + - apple,soc-die-passive-millicelsius allOf: - if: From 8ee88973bb441dc1404ecc3806f6e56396d74a56 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:28 -0500 Subject: [PATCH 1412/1514] hwmon: macsmc: register the SoC die passive and hot trips The macsmc_soc_die zone is registered tripless unless the board describes hotspot fan assistance. Consumers that read the zone's trips then see no limits. The G16 backend's thermal-zone backstop, which drives the GPU ceiling when the GPU has no PMP telemetry, fails closed at its lowest state in that case. So the T6030 and T8122 GPUs never leave S1. Read apple,soc-die-passive-millicelsius and apple,soc-die-hot-millicelsius from the hwmon node, and register them as a passive and a hot trip on the zone, after the active fan-assistance trip when one is configured. Both must be present, and the hot trip must lie above the passive one, or neither is registered. The zone has no hot callback and no critical trip, so the hot trip never shuts the machine down. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- Documentation/hwmon/macsmc-hwmon.rst | 9 ++++ drivers/hwmon/macsmc-hwmon.c | 80 +++++++++++++++++++++++----- 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/Documentation/hwmon/macsmc-hwmon.rst b/Documentation/hwmon/macsmc-hwmon.rst index 2ce19711b42594..bb0c502514a50d 100644 --- a/Documentation/hwmon/macsmc-hwmon.rst +++ b/Documentation/hwmon/macsmc-hwmon.rst @@ -52,6 +52,15 @@ with that active trip and ``macsmc_hwmon_hotspot_assist_policy()`` exposes the thresholds and hold time to hotspot fan assistance. Without those properties from the Devicetree, hotspot fan assistance stays off. +When the Devicetree gives ``apple,soc-die-passive-millicelsius`` and +``apple,soc-die-hot-millicelsius``, ``macsmc_soc_die`` also carries a passive +trip and a hot trip at those temperatures. They describe the machine's SoC die +limits for in-kernel power consumers that read the zone's trips (the GPU +thermal backstop sheds performance from the passive trip and holds its lowest +state at the hot one). The hot trip only reports: the zone has no hot callback +and no critical trip, so it never shuts the machine down. Without both +properties the zone carries no passive or hot trip. + SoC die temperatures are described by the ``apple,soc-die-keys`` string list on the hwmon device node. The driver appends these temperature channels after the ``temperature-*`` children, in list order, with labels ``SoC die ``. diff --git a/drivers/hwmon/macsmc-hwmon.c b/drivers/hwmon/macsmc-hwmon.c index 8fde9c3a4b0822..e577f9f018499d 100644 --- a/drivers/hwmon/macsmc-hwmon.c +++ b/drivers/hwmon/macsmc-hwmon.c @@ -136,6 +136,10 @@ struct macsmc_hwmon { /* DT-supplied hotspot fan-assistance trip on macsmc_soc_die. */ struct macsmc_hwmon_fan_assist fan_assist; bool fan_assist_valid; + /* DT-supplied passive and hot trips on macsmc_soc_die. */ + int die_passive_mc; + int die_hot_mc; + bool die_limits_valid; /* CPU clusters (policy->cpu) whose higher states these zones own */ struct delayed_work cpu_owner_work; cpumask_t cpu_owned; @@ -777,6 +781,29 @@ static bool macsmc_hwmon_parse_fan_assist(const struct device_node *np, return true; } +/* + * Parse the DT-supplied SoC die limits for macsmc_soc_die: the temperature + * from which power consumers shed performance (passive trip) and the one at + * which they hold their lowest state (hot trip). Both are required, and the + * hot trip must lie above the passive one. + */ +static bool macsmc_hwmon_parse_die_limits(const struct device_node *np, + int *passive_mc, int *hot_mc) +{ + u32 passive, hot; + + if (!np || + of_property_read_u32(np, "apple,soc-die-passive-millicelsius", &passive) || + of_property_read_u32(np, "apple,soc-die-hot-millicelsius", &hot)) + return false; + if (!passive || hot <= passive || hot > MACSMC_DIE_MAX_MC) + return false; + + *passive_mc = (int)passive; + *hot_mc = (int)hot; + return true; +} + static bool macsmc_hwmon_node_hotspot_assist(const struct device_node *np, struct macsmc_hwmon_fan_assist *policy) { @@ -1541,11 +1568,12 @@ static void macsmc_hwmon_populate_fan_configs(u32 *configs, const struct macsmc_ /* * The SoC die temperature zone: the hottest of the SoC die temperature * sensors, for in-kernel users that limit SoC power by temperature (they look - * the zone up by name). It has no trip points and is not polled; each read - * queries every SoC die sensor. A read fails if any of them cannot be read or - * reads outside -40..150 degrees Celsius, so users never act on a partial or - * implausible view. A sensor below its no-data threshold is powered down and - * left out. + * the zone up by name). It is not polled; each read queries every SoC die + * sensor. Its trips come from the DT: the hotspot fan-assistance active trip + * and the SoC die passive and hot limits, each only when configured. A read + * fails if any of the sensors cannot be read or reads outside -40..150 degrees + * Celsius, so users never act on a partial or implausible view. A sensor below + * its no-data threshold is powered down and left out. */ #if IS_ENABLED(CONFIG_THERMAL) #define MACSMC_SOC_DIE_ZONE "macsmc_soc_die" @@ -1604,8 +1632,10 @@ static void macsmc_hwmon_die_unregister(void *data) static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) { + struct thermal_trip trips[3]; struct thermal_zone_device *tz; char keys[16 * 5] = ""; + unsigned int n_trips = 0; size_t len = 0; u32 i; @@ -1646,28 +1676,49 @@ static int macsmc_hwmon_die_register(struct macsmc_hwmon *hwmon) "cannot register the device tree SoC die zone (%pe)\n", tz); } - if (hwmon->fan_assist_valid) { - struct thermal_trip trip = { + if (hwmon->fan_assist_valid) + trips[n_trips++] = (struct thermal_trip) { .temperature = hwmon->fan_assist.trigger_mc, .hysteresis = hwmon->fan_assist.trigger_mc - hwmon->fan_assist.release_mc, .type = THERMAL_TRIP_ACTIVE, }; + /* + * The hot trip only reports: the zone has no hot callback, so nothing + * here shuts the machine down. Consumers that read the trips (the GPU + * thermal backstop) shed performance from the passive trip and hold + * their lowest state at the hot one. + */ + if (hwmon->die_limits_valid) { + trips[n_trips++] = (struct thermal_trip) { + .temperature = hwmon->die_passive_mc, + .type = THERMAL_TRIP_PASSIVE, + }; + trips[n_trips++] = (struct thermal_trip) { + .temperature = hwmon->die_hot_mc, + .type = THERMAL_TRIP_HOT, + }; + } + if (n_trips) tz = thermal_zone_device_register_with_trips(MACSMC_SOC_DIE_ZONE, - &trip, 1, hwmon, + trips, n_trips, hwmon, &macsmc_hwmon_die_ops, NULL, 0, 0); - } else { + else tz = thermal_tripless_zone_device_register(MACSMC_SOC_DIE_ZONE, hwmon, &macsmc_hwmon_die_ops, NULL); - } if (IS_ERR(tz)) { dev_warn(hwmon->dev, "cannot register the SoC die temperature zone (%pe)\n", tz); return 0; } - dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present)\n", - MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed); + if (hwmon->die_limits_valid) + dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present), passive %d mC, hot %d mC\n", + MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed, + hwmon->die_passive_mc, hwmon->die_hot_mc); + else + dev_info(hwmon->dev, "SoC die temperature zone %s: hottest of%s (%u of %u listed keys present)\n", + MACSMC_SOC_DIE_ZONE, keys, hwmon->die_count, hwmon->die_listed); return devm_add_action_or_reset(hwmon->dev, macsmc_hwmon_die_unregister, tz); } #else @@ -2067,6 +2118,11 @@ static int macsmc_hwmon_probe(struct platform_device *pdev) macsmc_hwmon_parse_fan_assist(hwmon->dev->of_node, &hwmon->fan_assist)) hwmon->fan_assist_valid = true; + if (hwmon->die_count && + macsmc_hwmon_parse_die_limits(hwmon->dev->of_node, &hwmon->die_passive_mc, + &hwmon->die_hot_mc)) + hwmon->die_limits_valid = true; + if (!hwmon->curr.count && !hwmon->fan.count && !hwmon->power.count && !hwmon->temp.count && !hwmon->volt.count && !hwmon->pressure.macsmc_key) { From c05e7009f834e306276057d6e1aee23643028582 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:29 -0500 Subject: [PATCH 1413/1514] arm64: dts: apple: t6030: give the SoC die zone its ADT limits The T6030 GPU has no PMP telemetry (its PMP node is disabled), so the G16 backend sets the GPU ceiling from the macsmc_soc_die zone's trips. The zone had none, so the backstop failed closed and held the G15S at S1, 338 MHz of its 1380 MHz table. Give the zone the machine's SoC die limits. The ADT's /arm-io/pmp/iop-pmp-nub describes the PMP's fast die control: fast-die-ctrl-ts-avg-temp holds the average die temperature at 100 C (0x640000, 16.16), and the fast-die-ctrl-loop target holds the hottest die sensor at 110 C (0x6e0000 in each of its EACC, PACC and ANE0 records). The J514s and J516s device trees of the 27.2 (26B123) IPSW carry the same values, so they go in the SoC dtsi: the passive trip at 100 C and the hot trip at 110 C. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t6030.dtsi | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6030.dtsi b/arch/arm64/boot/dts/apple/t6030.dtsi index ee1441a387dffe..953e45d650b009 100644 --- a/arch/arm64/boot/dts/apple/t6030.dtsi +++ b/arch/arm64/boot/dts/apple/t6030.dtsi @@ -2189,5 +2189,15 @@ apple,soc-die-keys = "Tf04", "Tf09", "Tf0A", "Tf0B", "Tf0D", "Tf0E", "Tf14", "Tf18", "Tf19", "Tf1A", "Tf24", "Tf25", "Tf2A", "Tf2B"; + /* + * SoC die limits from the ADT's /arm-io/pmp/iop-pmp-nub, the same in + * the J514s and J516s device trees: the PMP's fast die control holds + * the average die temperature at fast-die-ctrl-ts-avg-temp (100 C) + * and the hottest die sensor at the fast-die-ctrl-loop target (110 C). + * Power consumers shed performance from the first and hold their + * lowest state at the second. + */ + apple,soc-die-passive-millicelsius = <100000>; + apple,soc-die-hot-millicelsius = <110000>; apple,thermal-pressure-key = "mTPL"; }; From c42928cd0133225742d85f5bfae83a9f1a14d7b4 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:27:36 -0500 Subject: [PATCH 1414/1514] arm64: dts: apple: t8122: give the SoC die zone its ADT limits The T8122 GPU, like T6030's, has no PMP telemetry (its PMP node is disabled), so the G16 backend sets the G15G ceiling from the macsmc_soc_die zone's trips. The zone has none, so the backstop fails closed at S1. Give the zone the machine's SoC die limits. The ADT's /arm-io/pmp/iop-pmp-nub holds fast-die-ctrl-ts-avg-temp at 100 C (0x640000, 16.16) and the fast-die-ctrl-loop target at 110 C (0x6e0000). The J433, J434, J504, J613 and J615 device trees of the 27.2 (26B123) IPSW carry the same values, so they go in the SoC dtsi: the passive trip at 100 C and the hot trip at 110 C. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t8122.dtsi | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8122.dtsi b/arch/arm64/boot/dts/apple/t8122.dtsi index c3e777c9ff688f..b95470d118340f 100644 --- a/arch/arm64/boot/dts/apple/t8122.dtsi +++ b/arch/arm64/boot/dts/apple/t8122.dtsi @@ -1177,6 +1177,17 @@ apple,soc-die-keys = "Tg0D", "Tg0P", "Tg0X", "Tg0b", "Tg0j", "Tg0v", "Te05", "Te0P", "Tp05", "Tp0L", "Tp0b", "Tp0r"; + /* + * SoC die limits from the ADT's /arm-io/pmp/iop-pmp-nub, + * the same in the J433, J434, J504, J613 and J615 device + * trees: the PMP's fast die control holds the average die + * temperature at fast-die-ctrl-ts-avg-temp (100 C) and the + * hottest die sensor at the fast-die-ctrl-loop target + * (110 C). Power consumers shed performance from the first + * and hold their lowest state at the second. + */ + apple,soc-die-passive-millicelsius = <100000>; + apple,soc-die-hot-millicelsius = <110000>; apple,thermal-pressure-key = "mTPL"; /* CPU die temperatures, first: thermal zones index them. */ From ad85ffafca409c0988420c648f8cb3012509bbfb Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 18:25:18 +1100 Subject: [PATCH 1415/1514] ci: kernel-release: move the Arch package version with the source make pacman-pkg takes pkgrel from scripts/build-version, a local build counter, so every release build produced 7.3.0_aurora_edge-2: the edge packages at f3bfe500 and c4b7e839 have the same version and different contents, and pacman (vercmp 0) never upgrades from one to the other. Use the source commit's committer time in Unix seconds as the build number: export it as KBUILD_BUILD_VERSION (uname -v '#N') and seed .version so pacman-pkg's pkgrel is the same value. It grows with every new main commit (channel tags only move forward), a rebuild of the same commit gets the same version, and ten digits keep UTS_VERSION within its 64 bytes. An explicit KBUILD_BUILD_VERSION still wins. Signed-off-by: Ryan Murray --- .github/scripts/kernel-release-build.sh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/scripts/kernel-release-build.sh b/.github/scripts/kernel-release-build.sh index c5798a5af9b144..14ef7d4a80606e 100755 --- a/.github/scripts/kernel-release-build.sh +++ b/.github/scripts/kernel-release-build.sh @@ -26,6 +26,13 @@ JOBS=${JOBS:-$(nproc)} export ARCH=arm64 LLVM=1 export KBUILD_BUILD_USER=${KBUILD_BUILD_USER:-aurora} KBUILD_BUILD_HOST=${KBUILD_BUILD_HOST:-github} export KBUILD_BUILD_TIMESTAMP=${KBUILD_BUILD_TIMESTAMP:-$(git -C "$S" log -1 --format=%cD HEAD)} +# Build number (uname -v '#N') and Arch pkgrel: the source commit's +# committer time in Unix seconds, so every new main commit gets a higher +# package version than the last one (pacman never upgrades between equal +# versions) and a rebuild of the same commit gets the same one. Ten digits +# keep UTS_VERSION within its 64 bytes. +REVISION=${KBUILD_BUILD_VERSION:-$(git -C "$S" log -1 --format=%ct HEAD)} +export KBUILD_BUILD_VERSION=$REVISION mk() { make -C "$S" O="$O" LOCALVERSION="$LV" -j"$JOBS" "$@"; } @@ -81,6 +88,9 @@ ARCH_RUNTIME= echo "::group::pacman-pkg" if command -v makepkg >/dev/null; then rm -f "$O"/*.pkg.tar.* + # make pacman-pkg takes pkgrel from scripts/build-version, which + # prints .version + 1. + echo $((REVISION - 1)) > "$O/.version" # Debian/Ubuntu's makepkg.conf defaults to .pkg.tar.gz. if PKGEXT=.pkg.tar.zst mk PACMAN_PKGBASE="$PKGBASE" PACMAN_EXTRAPACKAGES=headers \ MAKEPKGOPTS="--nodeps --noconfirm" pacman-pkg; then From b4a1d57ac4b19e330b1f2dff69b361c618185ca2 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:28:29 -0500 Subject: [PATCH 1416/1514] tools: aurora-wake: Keep diagnostic output in a private directory The Bluetooth wake diagnostics run as root and wrote their evidence below /var/tmp/bt-wake, under directory names predictable to the second, taking over any existing directory with mkdir -p and writing through ordinary pathname redirections and tee. Another local user who owns that parent, or a leaf in it, could point those writes elsewhere. bt-wake-cycle.sh and bt-wake-power.sh now open their output directory with open_out(): a fresh mktemp -d directory by default, or, for -o, a new absolute path that must not exist yet and whose parents only root, the caller or the sticky bit let others change. The directory is created with mode 0700, checked to be private, and entered, and the scripts work inside it with noclobber set, so a renamed or replaced path cannot redirect later writes and no existing file is overwritten. Kernel attributes are written with >| on purpose. attended-bt-wake.sh works in a fresh private directory the same way, and bt-wake-emulated.sh copies the cycle script to, and collects its evidence from, a fresh directory on the target rather than a fixed shared one. aurora-wake-output-tests.py, run by run-host-tests.py, plants the old predictable paths with symlinked outputs and checks that nothing is written through them; that -o refuses relative, existing, symlinked and dangling paths and parents others can change; that writes after a swap stay in the held directory; and that the scripts keep to these rules. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- tools/asahi/aurora-wake-output-tests.py | 225 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + tools/aurora-wake/attended-bt-wake.sh | 14 +- tools/aurora-wake/bt-wake-cycle.sh | 103 ++++++++--- tools/aurora-wake/bt-wake-emulated.sh | 14 +- tools/aurora-wake/bt-wake-power.sh | 69 ++++++-- 6 files changed, 375 insertions(+), 51 deletions(-) create mode 100755 tools/asahi/aurora-wake-output-tests.py diff --git a/tools/asahi/aurora-wake-output-tests.py b/tools/asahi/aurora-wake-output-tests.py new file mode 100755 index 00000000000000..3e3db15fe8487b --- /dev/null +++ b/tools/asahi/aurora-wake-output-tests.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only +"""Host tests of where the tools/aurora-wake Bluetooth wake diagnostics write. + +They run as root, so their evidence must go to a directory they create for +themselves: open_out() in bt-wake-cycle.sh and bt-wake-power.sh. The tests +extract that function, as test-s2idle-rtc-regression.sh does for its kernel log +collection, and check that: +- the default directory is a fresh private one, so files planted under the old + predictable /var/tmp/bt-wake paths, symlinked to victims, are never written; +- -o refuses relative, existing, symlinked and dangling paths, and parents that + others can change, and creates a new private directory otherwise; +- a directory renamed and replaced by a symlink after open_out() still takes + every write, and noclobber refuses an existing file; +- no script still names a fixed /var/tmp/bt-wake path, writes a kernel + attribute without >| or pipes evidence through a truncating tee. + +Usage: aurora-wake-output-tests.py --out DIR +""" +import argparse +import os +import re +import stat +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +WAKE = ROOT / 'tools/aurora-wake' +SCRIPTS = ['bt-wake-cycle.sh', 'bt-wake-power.sh'] +ALL = SCRIPTS + ['attended-bt-wake.sh', 'bt-wake-emulated.sh'] +BEGIN = '# --- private output directory' +END = '# --- end of private output directory' + +failures = [] + + +def check(ok, what): + print(('ok: ' if ok else 'FAIL line {}: '.format(sys._getframe(1).f_lineno)) + what) + if not ok: + failures.append(what) + + +def section(name): + text = (WAKE / name).read_text() + start = text.find(BEGIN) + end = text.find(END, start) + if start < 0 or end < 0: + return None + return text[start:end + len(END)] + '\n' + + +def bash(lib, script, cwd): + """Run `script` in bash with open_out() defined; returns (rc, stdout).""" + p = subprocess.run(['bash', '-c', 'set -u\n. "$1"\n' + script, 'test', str(lib)], + cwd=cwd, capture_output=True, text=True) + return p.returncode, p.stdout + p.stderr + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--out', required=True, type=Path) + work = ap.parse_args().out.resolve() + work.mkdir(parents=True, exist_ok=True) + + libs = {name: section(name) for name in SCRIPTS} + for name, text in libs.items(): + check(text is not None, f'{name} has an open_out() section') + check(len(set(libs.values())) == 1, 'bt-wake-cycle.sh and bt-wake-power.sh share one open_out()') + if None not in libs.values(): + lib = work / 'open_out.sh' + lib.write_text(libs[SCRIPTS[0]]) + behaviour(lib, work) + static() + + if failures: + print(f'{len(failures)} check(s) failed', file=sys.stderr) + return 1 + print('all checks passed') + return 0 + + +def behaviour(lib, work): + + # The issue's attack on the old default: someone owns the shared parent + # and has planted timestamped leaves whose outputs are symlinks to + # victims. The default directory is now a fresh one beside them. + base = work / 'var-tmp' + base.mkdir() + os.chmod(base, 0o1777) + victims = work / 'victims' + victims.mkdir() + planted = base / 'bt-wake' + names = ['results.txt', 'before.txt', 'dmesg.txt', 'after.txt', 'verdict.txt', 'suspending', + 'rtcwake.txt', 'hci.btsnoop', 'bad-lines.txt', 'device.txt'] + for leaf in ['cycle-20261126-120000', 'power-20261126-120000', 'attended-120000']: + (planted / leaf).mkdir(parents=True) + for n in names: + victim = victims / f'{leaf}-{n}' + victim.write_text('ORIGINAL\n') + (planted / leaf / n).symlink_to(victim) + for prefix in ['bt-wake-cycle', 'bt-wake-power']: + rc, log = bash(lib, f'''open_out "" "{base}" {prefix} || exit 9 + echo "$out"; echo header > results.txt; echo row | tee -a results.txt > /dev/null + dmesg_text=x; echo "$dmesg_text" > dmesg.txt; : > hci.btsnoop + echo verdict > verdict.txt; pwd -P''', work) + lines = log.split() + check(rc == 0 and len(lines) == 2 and lines[0] == lines[1], f'{prefix}: default directory opened and entered') + if rc == 0: + made = Path(lines[0]) + check(made.parent == base and made.name.startswith(prefix + '.') and made.name != prefix + '.XXXXXXXX', + f'{prefix}: default directory is a fresh name under the base, not under bt-wake/') + mode = made.stat() + check(stat.S_IMODE(mode.st_mode) == 0o700 and mode.st_uid == os.getuid(), f'{prefix}: it is private') + check((made / 'results.txt').read_text() == 'header\nrow\n', f'{prefix}: evidence written inside it') + check(all(v.read_text() == 'ORIGINAL\n' for v in victims.iterdir()), 'no planted symlink target was written') + + # -o refusals: nothing may be created or written through these. + private = work / 'private' + private.mkdir(mode=0o700) + existing = private / 'existing' + existing.mkdir() + (private / 'link').symlink_to(existing) + (private / 'dangling').symlink_to(private / 'nowhere') + (private / 'file').write_text('ORIGINAL\n') + open_dir = work / 'open' + open_dir.mkdir() + os.chmod(open_dir, 0o777) + group_dir = work / 'group' + group_dir.mkdir() + os.chmod(group_dir, 0o775) + under_open = private / 'inner-open' + under_open.mkdir() + os.chmod(under_open, 0o757) + refused = { + 'relative path': 'relative/out', + 'existing directory': str(existing), + 'symlink to a directory': str(private / 'link'), + 'dangling symlink': str(private / 'dangling'), + 'existing file': str(private / 'file'), + 'missing parent': str(private / 'missing' / 'out'), + 'world-writable parent': str(open_dir / 'out'), + 'group-writable parent': str(group_dir / 'out'), + 'writable ancestor': str(under_open / 'deeper' / 'out'), + 'dot leaf': str(private) + '/.', + 'dot-dot leaf': str(private) + '/..', + } + (under_open / 'deeper').mkdir() + for what, path in refused.items(): + before = sorted(p.name for p in private.iterdir()) + rc, log = bash(lib, f'open_out "{path}" "{base}" x || exit 9; echo opened', work) + check(rc == 9 and 'opened' not in log, f'-o {what} is refused') + check(sorted(p.name for p in private.iterdir()) == before, f'-o {what} creates nothing') + check((private / 'file').read_text() == 'ORIGINAL\n' and not (private / 'nowhere').exists(), + '-o refusals wrote through nothing') + check(not (open_dir / 'out').exists() and not (group_dir / 'out').exists() + and not (under_open / 'deeper' / 'out').exists(), '-o below a writable parent or ancestor creates nothing') + + # -o accepted: a new leaf below a private parent, and below a sticky one. + sticky = work / 'sticky' + sticky.mkdir() + os.chmod(sticky, 0o1777) + for what, path in {'private parent': private / 'new', 'sticky parent': sticky / 'new'}.items(): + rc, log = bash(lib, f'open_out "{path}" "{base}" x || exit 9; pwd -P; echo e > evidence.txt', work) + check(rc == 0 and log.split() == [str(path)], f'-o below a {what} opens the new directory') + check(path.is_dir() and stat.S_IMODE(path.stat().st_mode) == 0o700 and (path / 'evidence.txt').exists(), + f'-o below a {what}: private, with the evidence inside') + + # A directory renamed and replaced after open_out(): the script keeps + # writing into the directory it holds, never through the replacement. + swap_victim = work / 'swap-victim' + swap_victim.mkdir() + target = private / 'swap' + rc, log = bash(lib, f'''open_out "{target}" "{base}" x || exit 9 + echo first > before.txt + mv -- "{target}" "{target}.moved" && ln -s "{swap_victim}" "{target}" + echo later > dmesg.txt; echo verdict > verdict.txt''', work) + check(rc == 0 and (Path(f'{target}.moved') / 'dmesg.txt').read_text() == 'later\n', + 'writes after a swap land in the held directory') + check(not any(swap_victim.iterdir()), 'nothing is written through the swapped-in symlink') + + # noclobber: an existing file is never truncated, kernel attributes use >|. + attr = work / 'attribute' + attr.write_text('enabled\n') + rc, log = bash(lib, f'''open_out "{private / 'clobber'}" "{base}" x || exit 9 + echo old > results.txt + if (echo new > results.txt) 2> /dev/null; then exit 8; fi + echo disabled >| "{attr}" + cat results.txt''', work) + check(rc == 0 and log.strip() == 'old', 'noclobber refuses to overwrite an existing evidence file') + check(attr.read_text() == 'disabled\n', '>| still writes a kernel attribute') + + +def static(): + """The scripts themselves.""" + for name in ALL: + text = (WAKE / name).read_text() + code = '\n'.join(line for line in text.splitlines() if not line.lstrip().startswith('#')) + check('/var/tmp/bt-wake/' not in code and not re.search(r'=/var/tmp/bt-wake\b', code), + f'{name}: no fixed /var/tmp/bt-wake path') + check(not re.search(r'(?|])>\s*"?(\$dev|/sys/)', code), + f'{name}: kernel attributes are written with >|') + check(not re.search(r'mkdir -p "\$out"', code) or name == 'bt-wake-emulated.sh', + f'{name}: the evidence directory is not taken over with mkdir -p') + # The emulated run's own tee writes the emulator's control file over ssh, + # not evidence on the target. + for name in SCRIPTS + ['attended-bt-wake.sh']: + code = (WAKE / name).read_text() + check(not re.search(r'\btee\s+(?!-a\b)', code), f'{name}: no truncating tee') + for name in SCRIPTS: + code = (WAKE / name).read_text() + check(re.search(r'^open_out "\$out" /var/tmp bt-wake-', code, re.M) is not None, + f'{name}: opens its evidence directory with open_out()') + rest = code[code.find(END):] if END in code else code + check('"$out/' not in rest, f'{name}: writes relative to the held directory, not through $out') + attended = (WAKE / 'attended-bt-wake.sh').read_text() + check('mktemp -d /var/tmp/bt-wake-attended.' in attended and 'set -C' in attended, + 'attended-bt-wake.sh: a fresh private directory with noclobber') + emulated = (WAKE / 'bt-wake-emulated.sh').read_text() + check('mktemp -d /var/tmp/bt-wake-run.' in emulated and 'rm -rf $d' not in emulated, + 'bt-wake-emulated.sh: the target copy and evidence go to a fresh directory') + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a3c33382e0fb11..fdad34b506fef2 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -58,6 +58,7 @@ def mutations(flag, names, base, expect=KILL): # test file -> [(arguments, expectation)]. '{out}' is a fresh directory. ASAHI_TESTS = { + 'aurora-wake-output-tests.py': [(out(), PASS)], 'dcpext26-crossbar-union-tests.py': [([], PASS), (['--drop-native26'], KILL), (['--drop-t8132'], KILL)], 'dcpext26-suspend-route-tests.py': [([], PASS), (['--native-parks'], KILL), (['--drop-h17p-park'], KILL)], 'j613-mux-order-tests.py': [([], PASS), (['--negative-control'], KILL), diff --git a/tools/aurora-wake/attended-bt-wake.sh b/tools/aurora-wake/attended-bt-wake.sh index f8afc8ac872699..2bcd7fcd857f8f 100755 --- a/tools/aurora-wake/attended-bt-wake.sh +++ b/tools/aurora-wake/attended-bt-wake.sh @@ -15,13 +15,17 @@ addr=${1:-} [[ $addr =~ ^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$ ]] || { echo "usage: $0 " >&2; exit 2; } here=$(dirname "$(readlink -f "$0")") -out=/var/tmp/bt-wake/attended-$(date +%H%M%S) -mkdir -p "$out" +# A fresh private directory, worked in with noclobber set, so that a planted +# or swapped path cannot redirect what root writes (as in bt-wake-cycle.sh). +out=$(mktemp -d /var/tmp/bt-wake-attended.XXXXXXXX) || + { echo "cannot create an output directory" >&2; exit 2; } +cd -- "$out" || exit 2 +set -C -bluetoothctl info "$addr" > "$out/device.txt" 2>&1 || +bluetoothctl info "$addr" > device.txt 2>&1 || { echo "$addr is not known to BlueZ" >&2; exit 2; } -grep -E "Name|Paired|WakeAllowed|Connected" "$out/device.txt" -grep -q "WakeAllowed: yes" "$out/device.txt" || +grep -E "Name|Paired|WakeAllowed|Connected" device.txt +grep -q "WakeAllowed: yes" device.txt || { echo "wake is not allowed: bluetoothctl wake $addr on" >&2; exit 2; } echo ">>> Press a key on the Bluetooth keyboard so that it connects (60 s)." diff --git a/tools/aurora-wake/bt-wake-cycle.sh b/tools/aurora-wake/bt-wake-cycle.sh index 2eb419b3458230..687cc7d7eb2a5f 100755 --- a/tools/aurora-wake/bt-wake-cycle.sh +++ b/tools/aurora-wake/bt-wake-cycle.sh @@ -8,15 +8,57 @@ # emulated keyboard on another machine) is expected to make a wake-enabled # Bluetooth HID device reconnect while the system sleeps. # -# Usage: bt-wake-cycle.sh -w on|off [-s backstop-secs] [-r rtc] [-a bdaddr] [-o outdir] +# Usage: bt-wake-cycle.sh -w on|off [-s backstop-secs] [-r rtc] [-a bdaddr] [-o new-dir] # -w on expect a Bluetooth wake well before the backstop # -w off expect no wake: the RTC ends the sleep # -a Bluetooth address that must be connected again after resume +# -o a new directory for the evidence (default: a fresh +# /var/tmp/bt-wake-cycle.* directory) # The file /suspending appears right before the system suspends. # Exit status: 0 PASS, 1 FAIL, 2 setup error. set -u +# --- private output directory +# The evidence goes to a directory this script creates for itself, mode 0700: +# a fresh one under $2 by default, or the absolute path $1 given with -o, which +# must not exist yet, below parents that only root, this user or the sticky bit +# let others change. The script then works inside it with noclobber set, so a +# planted or swapped path cannot redirect what it writes as root. +open_out() { # $1: -o path or empty, $2: base directory, $3: name prefix + local leaf parent p owner mode + if [ -z "$1" ]; then + out=$(mktemp -d "$2/$3.XXXXXXXX") || + { echo "cannot create an output directory in $2" >&2; return 1; } + else + [[ $1 == /* ]] || + { echo "the output directory must be an absolute path: $1" >&2; return 1; } + leaf=$(basename -- "$1") + case $leaf in . | .. | /) echo "not a new directory: $1" >&2; return 1 ;; esac + parent=$(readlink -e -- "$(dirname -- "$1")") || + { echo "the parent of $1 does not exist" >&2; return 1; } + p=$parent + while :; do + read -r owner mode < <(stat -c '%u %a' -- "$p") || return 1 + if { [ "$owner" != 0 ] && [ "$owner" != "$(id -u)" ]; } || + { ((8#$mode & 8#022)) && ! ((8#$mode & 8#1000)); }; then + echo "others can change $p; not writing below it" >&2 + return 1 + fi + [ "$p" = / ] && break + p=$(dirname -- "$p") + done + out=${parent%/}/$leaf + mkdir -m 700 -- "$out" 2> /dev/null || + { echo "the output directory must not exist yet: $1" >&2; return 1; } + fi + cd -- "$out" || return 1 + [ "$(stat -c '%u %a' .)" = "$(id -u) 700" ] || + { echo "$out is not a private directory" >&2; return 1; } + set -C +} +# --- end of private output directory + # The PMU RTC, which can wake the system: rtc0 on J700, rtc1 on others. pmu_rtc() { local name @@ -33,7 +75,7 @@ mode= secs=120 rtc=$(pmu_rtc) addr= -out=/var/tmp/bt-wake/cycle-$(date +%Y%m%d-%H%M%S) +out= bdf=0000:01:00.1 while getopts "w:s:r:a:o:" opt; do @@ -54,7 +96,7 @@ esac dev=/sys/bus/pci/devices/$bdf [ -f "$dev/power/wakeup" ] || { echo "$bdf has no power/wakeup" >&2; exit 2; } -mkdir -p "$out" +open_out "$out" /var/tmp bt-wake-cycle || exit 2 irq=$(awk -F: '/mt7932-bt/ { gsub(/ /, "", $1); print $1; exit }' /proc/interrupts) [ -n "$irq" ] || { echo "no mt7932-bt interrupt" >&2; exit 2; } # Recorded only: a PME would arrive on the root port's PME interrupt. @@ -67,12 +109,13 @@ bt_irqs() { } orig_wakeup=$(cat "$dev/power/wakeup") -restore() { echo "$orig_wakeup" > "$dev/power/wakeup"; } +# Kernel attributes are the only files written with >|, past noclobber. +restore() { echo "$orig_wakeup" >| "$dev/power/wakeup"; } trap restore EXIT -[ "$mode" = on ] && echo enabled > "$dev/power/wakeup" || echo disabled > "$dev/power/wakeup" +[ "$mode" = on ] && echo enabled >| "$dev/power/wakeup" || echo disabled >| "$dev/power/wakeup" -echo 'module mt7932_bt_pcie +p' > /sys/kernel/debug/dynamic_debug/control 2> /dev/null -echo 1 > /sys/power/pm_debug_messages +echo 'module mt7932_bt_pcie +p' >| /sys/kernel/debug/dynamic_debug/control 2> /dev/null +echo 1 >| /sys/power/pm_debug_messages { echo "mode=$mode secs=$secs rtc=$rtc addr=$addr irq=$irq" @@ -83,18 +126,19 @@ echo 1 > /sys/power/pm_debug_messages echo "bt_irqs=$(bt_irqs)" bluetoothctl show | grep -E "Powered|PowerState" [ -n "$addr" ] && bluetoothctl info "$addr" | grep -E "Name|Connected|WakeAllowed" -} > "$out/before.txt" 2>&1 +} > before.txt 2>&1 fail_before=$(cat /sys/power/suspend_stats/fail) dmesg -C # HCI trace of the whole cycle: what the host sent at suspend, what woke it. -btmon -w "$out/hci.btsnoop" > /dev/null 2>&1 & +# btmon creates the capture itself, in this private directory. +btmon -w hci.btsnoop > /dev/null 2>&1 & btmon_pid=$! sleep 1 sync -date +%s.%N > "$out/suspending" +date +%s.%N > suspending t0=$(date +%s.%N) -rtcwake -d "$rtc" -m freeze -s "$secs" > "$out/rtcwake.txt" 2>&1 +rtcwake -d "$rtc" -m freeze -s "$secs" > rtcwake.txt 2>&1 rc=$? t1=$(date +%s.%N) slept=$(awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.1f", b - a }') @@ -119,20 +163,20 @@ fi powered=$(bluetoothctl show | awk '/Powered:/ { print $2 }') kill "$btmon_pid" 2> /dev/null -dmesg > "$out/dmesg.txt" +dmesg > dmesg.txt { echo "rc=$rc slept=${slept}s pm_wakeup_irq=$wirq ($wsrc) bt_irq=$irq pme_irq=$pme" echo "bt_irqs_after=$irqs_after wakeup_count=$(cat "$dev/power/wakeup_count" 2>/dev/null)" echo "irq_wakeup_after=$(cat /sys/kernel/irq/"$irq"/wakeup 2>/dev/null)" echo "reconnect=$reconnect powered=$powered" - grep -E "mt7932|Bluetooth|hci0" "$out/dmesg.txt" | grep -vE "Timekeeping|s2idle" | tail -20 -} > "$out/after.txt" + grep -E "mt7932|Bluetooth|hci0" dmesg.txt | grep -vE "Timekeeping|s2idle" | tail -20 +} > after.txt reasons=() [ $rc = 0 ] || reasons+=("rtcwake exited $rc") [ "$(cat /sys/power/suspend_stats/fail)" = "$fail_before" ] || reasons+=("suspend_stats fail count rose") -grep -q "system sleep with wakeup armed" "$out/dmesg.txt" +grep -q "system sleep with wakeup armed" dmesg.txt armed=$? if [ "$mode" = on ]; then [ $armed = 0 ] || reasons+=("driver did not report wakeup armed") @@ -150,18 +194,21 @@ fi [ "$powered" = yes ] || reasons+=("controller not powered after resume") [ "$reconnect" != timeout ] || reasons+=("$addr did not reconnect within 30 s") bad='WARNING:|BUG:|Oops|Call trace:|terminal transport fault|failed to (suspend|resume)' -grep -E "$bad" "$out/dmesg.txt" > "$out/bad-lines.txt" -[ -s "$out/bad-lines.txt" ] && - reasons+=("kernel log errors: $(head -2 "$out/bad-lines.txt" | tr '\n' ' ')") +grep -E "$bad" dmesg.txt > bad-lines.txt +[ -s bad-lines.txt ] && + reasons+=("kernel log errors: $(head -2 bad-lines.txt | tr '\n' ' ')") -if [ ${#reasons[@]} = 0 ]; then - echo "VERDICT wake=$mode: PASS slept=${slept}s pm_wakeup_irq=$wirq ($wsrc)" \ - "reconnect=$reconnect" | tee "$out/verdict.txt" - status=0 -else - echo "VERDICT wake=$mode: FAIL slept=${slept}s pm_wakeup_irq=$wirq" | tee "$out/verdict.txt" - printf ' - %s\n' "${reasons[@]}" | tee -a "$out/verdict.txt" - status=1 -fi -echo "evidence: $out" | tee -a "$out/verdict.txt" +# The verdict file appears complete: bt-wake-emulated.sh waits for it. +{ + if [ ${#reasons[@]} = 0 ]; then + echo "VERDICT wake=$mode: PASS slept=${slept}s pm_wakeup_irq=$wirq ($wsrc)" \ + "reconnect=$reconnect" + else + echo "VERDICT wake=$mode: FAIL slept=${slept}s pm_wakeup_irq=$wirq" + printf ' - %s\n' "${reasons[@]}" + fi + echo "evidence: $out" +} > verdict.txt +cat verdict.txt +[ ${#reasons[@]} = 0 ] && status=0 || status=1 exit $status diff --git a/tools/aurora-wake/bt-wake-emulated.sh b/tools/aurora-wake/bt-wake-emulated.sh index 64689be5bd7155..8c5dac8ba3b2a7 100755 --- a/tools/aurora-wake/bt-wake-emulated.sh +++ b/tools/aurora-wake/bt-wake-emulated.sh @@ -38,7 +38,6 @@ read -r -a target_args <<< "${TARGET_SSH_ARGS:-}" tgt() { ssh "${ssh_opts[@]}" "${target_args[@]}" "$TARGET_SSH" "$@"; } box() { ssh "${ssh_opts[@]}" "$EMU_SSH" "$@"; } CTL=/run/hogkb/ctl -TGT_DIR=/var/tmp/bt-wake BACKSTOP=120 TRIGGER_AFTER=20 out=${OUT:-./bt-wake-run-$(date +%Y%m%d-%H%M%S)} @@ -81,9 +80,14 @@ pair) run) n=${2:-5} emu_start - tgt "mkdir -p $TGT_DIR" && - scp -q "${target_args[@]}" "$(dirname "$0")/bt-wake-cycle.sh" \ - "$TARGET_SSH:$TGT_DIR/" + # A fresh private directory on the target holds the copied script and + # every cycle's evidence, so nothing root runs or writes there can be + # planted or swapped by another user. + TGT_DIR=$(tgt "mktemp -d /var/tmp/bt-wake-run.XXXXXXXX") + [[ $TGT_DIR =~ ^/var/tmp/bt-wake-run\.[A-Za-z0-9]+$ ]] || + { echo "cannot create a directory on the target" >&2; exit 2; } + scp -q "${target_args[@]}" "$(dirname "$0")/bt-wake-cycle.sh" \ + "$TARGET_SSH:$TGT_DIR/" || exit 2 pass=0 plan=() for _ in $(seq 1 "$n"); do plan+=(on); done @@ -96,7 +100,7 @@ run) emu key 0x2c 30 sleep 8 say "cycle $k wake=$mode: suspending the target (backstop ${BACKSTOP}s)" - tgt "rm -rf $d; setsid nohup $TGT_DIR/bt-wake-cycle.sh -w $mode -s $BACKSTOP \ + tgt "setsid nohup $TGT_DIR/bt-wake-cycle.sh -w $mode -s $BACKSTOP \ -a $EMU_ADDR -o $d > $d.log 2>&1 < /dev/null &" for _ in $(seq 1 30); do tgt "test -f $d/suspending" 2> /dev/null && break diff --git a/tools/aurora-wake/bt-wake-power.sh b/tools/aurora-wake/bt-wake-power.sh index be6d1eb06c8f60..91e46188f5f649 100755 --- a/tools/aurora-wake/bt-wake-power.sh +++ b/tools/aurora-wake/bt-wake-power.sh @@ -7,8 +7,50 @@ # - Bluetooth MSIs and all interrupts taken across the sleep, # - how often the s2idle loop was re-entered (pm_debug "Timekeeping suspended"), # - the battery energy used, when running on battery (energy_now). -# Usage: bt-wake-power.sh [-s secs] [-n pairs] [-o outdir] +# Usage: bt-wake-power.sh [-s secs] [-n pairs] [-o new-dir] +# -o a new directory for the evidence (default: a fresh +# /var/tmp/bt-wake-power.* directory) set -u + +# --- private output directory +# The evidence goes to a directory this script creates for itself, mode 0700: +# a fresh one under $2 by default, or the absolute path $1 given with -o, which +# must not exist yet, below parents that only root, this user or the sticky bit +# let others change. The script then works inside it with noclobber set, so a +# planted or swapped path cannot redirect what it writes as root. +open_out() { # $1: -o path or empty, $2: base directory, $3: name prefix + local leaf parent p owner mode + if [ -z "$1" ]; then + out=$(mktemp -d "$2/$3.XXXXXXXX") || + { echo "cannot create an output directory in $2" >&2; return 1; } + else + [[ $1 == /* ]] || + { echo "the output directory must be an absolute path: $1" >&2; return 1; } + leaf=$(basename -- "$1") + case $leaf in . | .. | /) echo "not a new directory: $1" >&2; return 1 ;; esac + parent=$(readlink -e -- "$(dirname -- "$1")") || + { echo "the parent of $1 does not exist" >&2; return 1; } + p=$parent + while :; do + read -r owner mode < <(stat -c '%u %a' -- "$p") || return 1 + if { [ "$owner" != 0 ] && [ "$owner" != "$(id -u)" ]; } || + { ((8#$mode & 8#022)) && ! ((8#$mode & 8#1000)); }; then + echo "others can change $p; not writing below it" >&2 + return 1 + fi + [ "$p" = / ] && break + p=$(dirname -- "$p") + done + out=${parent%/}/$leaf + mkdir -m 700 -- "$out" 2> /dev/null || + { echo "the output directory must not exist yet: $1" >&2; return 1; } + fi + cd -- "$out" || return 1 + [ "$(stat -c '%u %a' .)" = "$(id -u) 700" ] || + { echo "$out is not a private directory" >&2; return 1; } + set -C +} +# --- end of private output directory # The PMU RTC, which can wake the system: rtc0 on J700, rtc1 on others. pmu_rtc() { local name @@ -22,7 +64,7 @@ pmu_rtc() { } secs=300 pairs=2 -out=/var/tmp/bt-wake/power-$(date +%Y%m%d-%H%M%S) +out= while getopts "s:n:o:" opt; do case $opt in s) secs=$OPTARG ;; n) pairs=$OPTARG ;; o) out=$OPTARG ;; *) exit 2 ;; esac done @@ -31,11 +73,12 @@ dev=/sys/bus/pci/devices/0000:01:00.1 bat=/sys/class/power_supply/macsmc-battery irq=$(awk -F: '/mt7932-bt/ { gsub(/ /, "", $1); print $1; exit }' /proc/interrupts) rtc=$(pmu_rtc) -mkdir -p "$out" +open_out "$out" /var/tmp bt-wake-power || exit 2 orig=$(cat "$dev/power/wakeup") -trap 'echo "$orig" > "$dev/power/wakeup"' EXIT -echo 1 > /sys/power/pm_debug_messages -echo 'module mt7932_bt_pcie +p' > /sys/kernel/debug/dynamic_debug/control 2> /dev/null +# Kernel attributes are the only files written with >|, past noclobber. +trap 'echo "$orig" >| "$dev/power/wakeup"' EXIT +echo 1 >| /sys/power/pm_debug_messages +echo 'module mt7932_bt_pcie +p' >| /sys/kernel/debug/dynamic_debug/control 2> /dev/null irq_sum() { # $1: irq number or "all" awk -v i="$1" '$1 ~ /^[0-9]+:$/ && (i == "all" || $1 == i ":") { @@ -43,11 +86,11 @@ irq_sum() { # $1: irq number or "all" } END { print s + 0 }' /proc/interrupts } -echo "mode secs slept bt_msis all_irqs s2idle_entries energy_mWh status armed" | - tee "$out/results.txt" +echo "mode secs slept bt_msis all_irqs s2idle_entries energy_mWh status armed" > results.txt +cat results.txt for p in $(seq 1 "$pairs"); do for mode in disabled enabled; do - echo "$mode" > "$dev/power/wakeup" + echo "$mode" >| "$dev/power/wakeup" dmesg -C b0=$(irq_sum "$irq") a0=$(irq_sum all) @@ -57,12 +100,12 @@ for p in $(seq 1 "$pairs"); do rtcwake -d "$rtc" -m freeze -s "$secs" > /dev/null 2>&1 t1=$(date +%s.%N) b1=$(irq_sum "$irq"); a1=$(irq_sum all); e1=$(cat "$bat/energy_now") - dmesg > "$out/dmesg-$p-$mode.txt" - entries=$(grep -c "Timekeeping suspended" "$out/dmesg-$p-$mode.txt") - armed=$(grep -c "system sleep with wakeup armed" "$out/dmesg-$p-$mode.txt") + dmesg > "dmesg-$p-$mode.txt" + entries=$(grep -c "Timekeeping suspended" "dmesg-$p-$mode.txt") + armed=$(grep -c "system sleep with wakeup armed" "dmesg-$p-$mode.txt") slept=$(awk -v a="$t0" -v b="$t1" 'BEGIN { printf "%.1f", b - a }') echo "$mode $secs $slept $((b1 - b0)) $((a1 - a0)) $entries" \ - "$(((e0 - e1) / 1000)) $st $armed" | tee -a "$out/results.txt" + "$(((e0 - e1) / 1000)) $st $armed" | tee -a results.txt sleep 20 done done From 3fd420c565bfdbd63f40fb60d5ffeae7e62b0fe5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 20:53:21 +1100 Subject: [PATCH 1417/1514] drm/apple: dpavservep: admit DCPDP13Service on the classic DPAV endpoint On firmware 27.x the M3 and M4 Airs' external display processors announce the EDID AV service, dcpav-service-epic with class DCPDP13Service, on the classic DPAV endpoint 0x28 with EPICUnit 0 and a dynamic interface-id (1 at boot, then 5, 9, 13, 17, 21 after each reconnect and resume). Endpoint 0x28 admits only the MCDP29xx converter classes, so the service is refused with -ENODEV and the connector has no EDID source: an empty EDID blob, no monitor name, no colorimetry or HDR metadata, and no ELD for DisplayPort audio. The generic classes were refused there because using them reset the M4 Air when the external processor released its link. That reset was the display DART being unmapped while DPMS had its domains off, fixed by "drm/apple: dcp: keep the display DART dark while DPMS has its domains off" (linux#2962). With it, the service no longer resets the J713 on link release. Admit DCPDP13Service on endpoint 0x28 with EPICUnit 0, as the converter classes are. AppleDCPDP2HDMI stays refused there, endpoint 0x2a keeps requiring unit == interface-id, and the generation, epoch and owner fences are unchanged. The host regression admits DCPDP13Service on 0x28 over interface-ids 1/5/9/13 and still refuses AppleDCPDP2HDMI there, unit == interface-id on 0x28, unit 0 on 0x2a, other endpoints, compartments and classes. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep.c | 9 +++++---- .../selftests/drivers/gpu/apple-dcp/edid.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep.c b/drivers/gpu/drm/apple/epic/dpavservep.c index 96bbac2cf72783..de678ef34b6756 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep.c +++ b/drivers/gpu/drm/apple/epic/dpavservep.c @@ -66,13 +66,14 @@ static bool dcpavserv_identity(struct apple_epic_service *service, const char *n * Firmware 27 names an MCDP29xx DP-to-HDMI converter's AV service after * its part (the M2 Mac mini's HDMI port, USB-C to HDMI adapters) and * announces it on the classic DPAV endpoint with EPICUnit 0; its - * interface-id (the channel) is dynamic across reconnects. The generic - * services stay refused there: using them resets the M4 Air when the - * external processor releases its link. + * interface-id (the channel) is dynamic across reconnects. The M3 and + * M4 Airs' external processors announce the generic DCPDP13Service + * there the same way. */ return service->ep->endpoint == DPAVSERV_ENDPOINT && unit == 0 && (!strcmp(class, "AppleDCPMCDP29XX") || - !strcmp(class, "AppleDCPMCDP2900")); + !strcmp(class, "AppleDCPMCDP2900") || + !strcmp(class, "DCPDP13Service")); } static bool dcpavserv_admission_current(struct apple_dcp *dcp, u64 generation) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py index 6fbf19d2a6329f..ca7357a0ddaa86 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/edid.py @@ -301,6 +301,22 @@ def function(file,signature): const char *forged[]={"DCPDP13ServiceExtra","dcpdp13service","AppleDCPDP2HDMIExtra","unrelated-provider"}; announce(13,name,forged[variant],13);assert(opens==before && !d.dcpavserv.service); } + /* + * AFKV2 on the classic DPAV endpoint: the M3/M4 Air external DCPs announce + * DCPDP13Service with EPICUnit 0 and a dynamic interface-id. Only that + * generic class (and the MCDP29xx converters) is admitted there. + */ + ep.endpoint=0x28; + assert(!prepare(1,1,name,native_class));assert(!prepare(5,5,name,native_class)); + assert(!prepare(0,0,name,native_class));assert(!prepare(65536,0,name,native_class)); + assert(!prepare(5,0,"dcpdp-service-epic",native_class));assert(!prepare(5,0,name,"unrelated-provider")); + for(u32 channel=1;channel<=13;channel+=4) { + struct apple_epic_service *s=prepare(channel,0,name,native_class); + assert(s && "EPICUnit-0 DCPDP13Service must be admitted");afk_service_discard(s); + assert(!prepare(channel,0,name,class) && "AppleDCPDP2HDMI stays refused on 0x28"); + } + ep.endpoint=0x2c;assert(!prepare(5,0,name,native_class));ep.endpoint=0x2a; + assert(!prepare(5,0,name,native_class)); /* H17P keeps unit == interface-id. */ assert(!prepare(13,13,name,NULL)); open_error=-EIO;announce(13,name,native_class,13);assert(opens==++before && !d.dcpavserv.service);open_error=0; for(unsigned int window=0;window<5;window++) { From 027c9476464dc3f1a70b91501e94925df427d3a8 Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:39:20 -0500 Subject: [PATCH 1418/1514] PCI: Mark devices below a device tree external-facing port untrusted The device tree binding defines "external-facing" on a port as: every bridge and endpoint downstream of it is external to the machine. pci_set_bus_of_node() still sets external_facing on such a port, but since commit 3b96b895127b ("PCI: Detect and trust built-in Thunderbolt chips") only arch_pci_dev_is_removable() marks the devices below it untrusted or removable, and that is implemented for x86 with ACPI only. On device tree systems, devices tunneled through a USB4 or Thunderbolt port are therefore treated as built in: iommu-dma maps their buffers in place instead of bouncing the unaligned ones, so with 16K IOMMU pages a device can reach the rest of each page around its buffers, and ATS stays allowed. Mark the devices directly below a port that the device tree marks external-facing untrusted and removable again, as before that commit. The ACPI exception for a built-in discrete controller below an ExternalFacingPort does not apply: the binding leaves no room for one. Fixes: 3b96b895127b ("PCI: Detect and trust built-in Thunderbolt chips") Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/pci/probe.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index c38a60df06d81d..d1bd1670841c9a 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1735,6 +1736,20 @@ static void set_pcie_cxl(struct pci_dev *dev) } +/* + * Every bridge and endpoint below a port that the device tree marks + * "external-facing" is external to the machine, as the binding defines it. + * Unlike an ACPI ExternalFacingPort (see arch_pci_dev_is_removable()), no + * built-in controller sits below such a port. + */ +static bool pci_dev_below_of_external_port(struct pci_dev *dev) +{ + struct pci_dev *parent = pci_upstream_bridge(dev); + + return parent && parent->external_facing && + of_property_read_bool(parent->dev.of_node, "external-facing"); +} + static void set_pcie_untrusted(struct pci_dev *dev) { struct pci_dev *parent = pci_upstream_bridge(dev); @@ -1750,7 +1765,7 @@ static void set_pcie_untrusted(struct pci_dev *dev) return; } - if (arch_pci_dev_is_removable(dev)) { + if (arch_pci_dev_is_removable(dev) || pci_dev_below_of_external_port(dev)) { pci_dbg(dev, "marking as untrusted\n"); dev->untrusted = true; } @@ -1778,7 +1793,7 @@ static void pci_set_removable(struct pci_dev *dev) return; } - if (arch_pci_dev_is_removable(dev)) { + if (arch_pci_dev_is_removable(dev) || pci_dev_below_of_external_port(dev)) { pci_dbg(dev, "marking as removable\n"); dev_set_removable(&dev->dev, DEVICE_REMOVABLE); } From 9fbe8105d6494de3b3c9be72a9d81dcafb2526e4 Mon Sep 17 00:00:00 2001 From: AxxzyWasTaken Date: Thu, 26 Nov 2026 07:59:08 +0000 Subject: [PATCH 1419/1514] drm/apple: drop in_atomic() from dcp_send_message() dcp_send_message() previously passed in_atomic() to apple_rtkit_send_message() on T6030 14.7 and native26 (ext26) firmwares to choose between sleeping and non-sleeping mailbox sends. in_atomic() is unreliable on non-preemptible kernels (!CONFIG_PREEMPT_COUNT), where holding a spinlock does not increment preempt_count and in_atomic() returns false even while a spinlock is held with interrupts disabled. Auditing all four dcp_send_message() call sites (iomfb_start_rtkit(), dcp_push_context(), dcp_ack(), and afk_send()) and every transitive caller shows that every external entry point is already in sleepable context (RTKit RX runs on an ordered workqueue, DCP audio sets pcm->nonatomic = true, HPD uses a threaded IRQ, and DRM commits run in process/workqueue context). However, two internal AFK paths called afk_send() while holding spinlocks: - afk_send_epic_token() held ep->lock across afk_send(), and afk_send_command_common() also held service->lock across afk_send_epic(). - afk_send_compact_fragment() held ep->lock across afk_send(), even though its caller already holds the endpoint TX mutex. On CONFIG_PREEMPT_COUNT=y kernels, that caused in_atomic() to return true on EPIC commands and DisplayPort handshake replies, forcing non-sleeping sends that can fail on a full shared mailbox FIFO. On !CONFIG_PREEMPT_COUNT kernels, it risked sleeping while holding ep->lock and service->lock with IRQs disabled. Fix both layers cleanly: - Generalize ep->compact_tx_lock to ep->tx_lock so TX ring writes and their matching mailbox doorbells stay serialized across afk_send_epic_token(), afk_send_compact(), and afk_v27_sleep_control() without holding ep->lock across afk_send(). Drain external TX senders in afk_quiesce() by taking and releasing ep->tx_lock after stopping is set and workqueues are destroyed. - Release service->lock in afk_send_command_common() once the command slot and completion are published, before calling afk_send_epic(). - Remove in_atomic() from dcp_send_message(), add might_sleep() to enforce its sleepable-context contract under CONFIG_DEBUG_ATOMIC_SLEEP, and unconditionally use sleeping sends on 14.7/ext26 while keeping atomic sends on other firmware paths. - Update the AFK/DCP host selftests to track ep->tx_lock in afk_quiesce() and assert that neither service->lock nor ep->lock is held when afk_send_epic() is called. Closes: https://github.com/aurora-silicon/linux/issues/2847 Signed-off-by: AxxzyWasTaken --- drivers/gpu/drm/apple/afk.c | 51 ++++++++++++++----- drivers/gpu/drm/apple/afk.h | 5 +- drivers/gpu/drm/apple/dcp.c | 12 +++-- drivers/gpu/drm/apple/dcp.h | 1 + .../drivers/gpu/apple-afkv2/extract-send.py | 5 +- .../drivers/gpu/apple-dcp/recovery.py | 2 + 6 files changed, 54 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index befc7ccc56ea97..820f873dc9477c 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -181,6 +181,9 @@ void afk_quiesce(struct apple_dcp_afkep *afkep) destroy_workqueue(afkep->tx_wq); afkep->tx_wq = NULL; } + /* Drain any external TX sender that passed stopping before it was set. */ + mutex_lock(&afkep->tx_lock); + mutex_unlock(&afkep->tx_lock); kvfree(afkep->compact_rx_data); afkep->compact_rx_data = NULL; for (i = 0; i < afkep->num_channels; i++) @@ -651,8 +654,11 @@ static int afk_send_compact_fragment(struct apple_dcp_afkep *ep, u16 intf_id, void *message; size_t message_size, advance; u32 rptr, wptr, old_wptr; + u64 doorbell; int ret = 0; + lockdep_assert_held(&ep->tx_lock); + if (!ep->txbfr.ready || !ep->txbfr.stride) return -EIO; @@ -734,10 +740,15 @@ static int afk_send_compact_fragment(struct apple_dcp_afkep *ep, u16 intf_id, dma_wmb(); WRITE_ONCE(*ep->txbfr.wptr, cpu_to_le32(wptr)); dma_wmb(); + doorbell = FIELD_PREP(RBEP_TYPE, RBEP_RECV) | + ((u64)(rptr & 0xffff) << 32) | + ((u64)(wptr & 0xffff) << 16) | (old_wptr & 0xffff); + spin_unlock_irqrestore(&ep->lock, flags); + /* The firmware's own client rings with RECV and both pointers. */ - afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_RECV) | - ((u64)(rptr & 0xffff) << 32) | - ((u64)(wptr & 0xffff) << 16) | (old_wptr & 0xffff)); + afk_send(ep, doorbell); + kfree(message); + return 0; out_unlock: spin_unlock_irqrestore(&ep->lock, flags); @@ -774,7 +785,7 @@ static int afk_send_compact(struct apple_dcp_afkep *ep, u16 intf_id, u8 type, if (payload_size) memcpy(sub + 1, payload, payload_size); - mutex_lock(&ep->compact_tx_lock); + mutex_lock(&ep->tx_lock); deadline = jiffies + msecs_to_jiffies(5000); while (offset < total) { chunk = min_t(size_t, total - offset, AFK_COMPACT_FRAGMENT_SIZE); @@ -802,7 +813,7 @@ static int afk_send_compact(struct apple_dcp_afkep *ep, u16 intf_id, u8 type, /* Never start a new header into an unfinished remote assembly. */ if (ret && offset) afk_compact_tx_desync(ep, ret); - mutex_unlock(&ep->compact_tx_lock); + mutex_unlock(&ep->tx_lock); kvfree(body); return ret; } @@ -1645,15 +1656,16 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ret = afk_v27_sleep_check(ep); if (ret) return ret; + mutex_lock(&ep->tx_lock); spin_lock_irqsave(&ep->lock, flags); /* A callback reply may have failed since the inventory check. */ if (ep->stopping || ep->sleep_poisoned || ep->sleep_waiting) { ret = -EBUSY; - goto out; + goto out_tx_unlock; } if (ep->sleep_closed == !open) { ret = -EALREADY; - goto out; + goto out_tx_unlock; } dma_rmb(); rptr = le32_to_cpu(READ_ONCE(*ep->txbfr.rptr)); @@ -1664,7 +1676,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ep->txbfr.bufsz % ep->txbfr.stride || ep->txbfr.bufsz - wptr < sizeof(*hdr)) { ret = -EPROTO; - goto out; + goto out_tx_unlock; } /* Use the existing dummy-header wrap format and keep one slot empty. */ next = ALIGN(wptr + sizeof(*hdr) + sizeof(payload), ep->txbfr.stride); @@ -1675,7 +1687,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) if ((wptr < rptr && next >= rptr) || (wptr >= rptr && next <= wptr && next >= rptr)) { ret = -EAGAIN; - goto out; + goto out_tx_unlock; } hdr = ep->txbfr.buf + wptr; hdr->magic = cpu_to_le32(QE_MAGIC); @@ -1701,6 +1713,7 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) FIELD_PREP(RBEP_TYPE, RBEP_RECV) | (u64)rptr << 32 | (u64)next << 16 | old, NULL, true); spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); if (!ret && !wait_for_completion_timeout(&ep->sleep_done, msecs_to_jiffies(250))) ret = -ETIMEDOUT; @@ -1709,9 +1722,13 @@ int afk_v27_sleep_control(struct apple_dcp_afkep *ep, bool open) ep->sleep_poisoned = true; ep->sleep_waiting = false; } - out: spin_unlock_irqrestore(&ep->lock, flags); return ret; + +out_tx_unlock: + spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); + return ret; } /* Pending identities are owned only by the ordered endpoint workqueue. */ @@ -3046,6 +3063,7 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, } } + mutex_lock(&ep->tx_lock); spin_lock_irqsave(&ep->lock, flags); if (READ_ONCE(ep->dcp->sleep_v27_closed) && ecat != EPIC_CAT_REPLY) { ret = -EBUSY; @@ -3231,12 +3249,17 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, /* Publish the completed entry before allowing the consumer to read it. */ dma_wmb(); *ep->txbfr.wptr = cpu_to_le32(wptr); + spin_unlock_irqrestore(&ep->lock, flags); + + /* Keep tx_lock held across the doorbell so ring writes stay ordered. */ afk_send(ep, FIELD_PREP(RBEP_TYPE, RBEP_SEND) | - FIELD_PREP(SEND_WPTR, wptr)); - ret = 0; + FIELD_PREP(SEND_WPTR, wptr)); + mutex_unlock(&ep->tx_lock); + return 0; out: spin_unlock_irqrestore(&ep->lock, flags); + mutex_unlock(&ep->tx_lock); return ret; } @@ -3276,7 +3299,7 @@ static u16 afk_command_tag(struct apple_epic_service *service, u8 slot) if (!ep->wire_v2) return ((service->cmd_tag++ & 0xff) << 8) | slot; - /* Send already nests the endpoint lock below the service lock. */ + /* Endpoint lock nests below the service lock. */ spin_lock_irqsave(&ep->lock, flags); tag = afkv2_command_id(ep->command_tags[service->channel]++, slot); spin_unlock_irqrestore(&ep->lock, flags); @@ -3474,6 +3497,7 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, service->cmds[idx].done = false; service->cmds[idx].completion = &completion; init_completion(&completion); + spin_unlock_irqrestore(&service->lock, flags); if (ep->inline_v2) { ret = afkv2_encode_inline_command(inline_command, @@ -3490,7 +3514,6 @@ static int afk_send_command_common(struct apple_epic_service *service, u8 type, } kfree(inline_command); inline_command = NULL; - spin_unlock_irqrestore(&service->lock, flags); if (ret) goto err_free_cmd; diff --git a/drivers/gpu/drm/apple/afk.h b/drivers/gpu/drm/apple/afk.h index 7f4e6cf4849c1f..e0b8d1cf3a12b8 100644 --- a/drivers/gpu/drm/apple/afk.h +++ b/drivers/gpu/drm/apple/afk.h @@ -582,6 +582,8 @@ struct apple_dcp_afkep { void *rx_scratch; spinlock_t lock; + /* Serializes TX ring writes and mailbox doorbells outside ep->lock. */ + struct mutex tx_lock; u16 qe_seq; bool stopping; /* lock: no new receive work after shutdown. */ @@ -605,7 +607,6 @@ struct apple_dcp_afkep { size_t compact_reply_bytes; /* Accepted RX and queued replies, until each worker has returned. */ atomic_t sleep_jobs; - struct mutex compact_tx_lock; struct afk_fragment_state compact_rx; void *compact_rx_data; @@ -636,10 +637,10 @@ static inline void afk_ep_init_state(struct apple_dcp_afkep *ep) u32 i; spin_lock_init(&ep->lock); + mutex_init(&ep->tx_lock); INIT_LIST_HEAD(&ep->compact_cmds); init_waitqueue_head(&ep->compact_orphan_wq); init_waitqueue_head(&ep->service_wq); - mutex_init(&ep->compact_tx_lock); init_completion(&ep->started); init_completion(&ep->stopped); init_completion(&ep->sleep_done); diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 4a696e8dc1b7ad..76fd8d034492a1 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2176,17 +2176,21 @@ void dcp_send_message(struct apple_dcp *dcp, u8 endpoint, u64 message) bool native_14_7 = dcp->fw_compat == DCP_FIRMWARE_V_14_7; int ret; + might_sleep(); + if (READ_ONCE(dcp->quiescing) || (dcp_is_ext26(dcp) && READ_ONCE(dcp->ext26_blocked))) return; trace_dcp_send_msg(dcp, endpoint, message); /* - * The adopted T6030 14.7 session shares this mailbox with the panel - * link. A non-sleeping send fails while that FIFO is full, and the - * DisplayPort handshake then waits for a reply that was never sent. + * The adopted T6030 14.7 and native26 (ext26) sessions share this + * mailbox with the panel link. A non-sleeping send fails while that + * FIFO is full, and the DisplayPort handshake then waits for a reply + * that was never sent. All callers are sleepable, so always use + * sleeping sends on 14.7/ext26 and keep atomic sends on other firmware. */ ret = apple_rtkit_send_message(dcp->rtk, endpoint, message, NULL, - (native_14_7 || dcp_is_ext26(dcp)) ? in_atomic() : true); + !(native_14_7 || dcp_is_ext26(dcp))); if (ret && dcp_is_ext26(dcp)) { WRITE_ONCE(dcp->crashed, true); dev_err(dcp->dev, "native26 mailbox send failed ep=%#x: %d\n", endpoint, ret); diff --git a/drivers/gpu/drm/apple/dcp.h b/drivers/gpu/drm/apple/dcp.h index f2745dde65580d..dae843ffbdcd08 100644 --- a/drivers/gpu/drm/apple/dcp.h +++ b/drivers/gpu/drm/apple/dcp.h @@ -153,6 +153,7 @@ void dcp_set_dimensions(struct apple_dcp *dcp, u64 generation); void dcp_panel_read_dimensions(struct apple_dcp *dcp, struct device_node *panel_np); void dcp_update_connector_dimensions(struct apple_dcp *dcp, struct drm_connector *connector); +/* Must be called from sleepable context; may sleep on 14.7/ext26 mailboxes. */ void dcp_send_message(struct apple_dcp *dcp, u8 endpoint, u64 message); int dcp_dptx_connect_oob(struct platform_device *pdev, u32 port); diff --git a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py index 191881806f58cb..65e51df3bfddc4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py +++ b/tools/testing/selftests/drivers/gpu/apple-afkv2/extract-send.py @@ -49,8 +49,8 @@ def function(pattern, what): #define kfree(p) free(p) #define READ_ONCE(x) (x) #define WRITE_ONCE(x,v) ((x)=(v)) -#define spin_lock_irqsave(l,f) ((void)(l),(f)=0) -#define spin_unlock_irqrestore(l,f) ((void)(l),(void)(f)) +#define spin_lock_irqsave(l,f) do { assert(!*(l)); *(l)=1; (f)=0; } while(0) +#define spin_unlock_irqrestore(l,f) do { assert(*(l)); *(l)=0; (void)(f); } while(0) #define dma_rmb() do {} while(0) #define dev_warn(...) do {} while(0) #define dev_err(...) do {} while(0) @@ -119,6 +119,7 @@ def function(pattern, what): static int afk_send_epic(struct apple_dcp_afkep *ep,u32 channel,u16 tag,int type,int category,u8 subtype,const void *payload,size_t length) { struct cmd_info *c=&active->cmds[0];struct afkv2_command parsed; + assert(!active->lock && !ep->lock); assert(channel==4 && type==3 && category==0x30 && subtype==0xc0); sends++; /* The payload-envelope mock bounds the command separately from its response. */ diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py index d9c1391897279e..67e9c39e824480 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/recovery.py @@ -360,6 +360,8 @@ def run(name,text,cases): } ''' af=(root/'drivers/gpu/drm/apple/afk.c').read_text() + if 'mutex_lock(&afkep->tx_lock);' in af: + queued=queued.replace('bool lock,stopping;','bool lock,tx_lock,stopping;',1) if 'atomic_inc(&ep->sleep_jobs);' in af: # The receive jobs a firmware sleep waits for; nothing here waits. anchor='struct apple_dcp_afkep { u8 *command_tags;int started,stopped;' From b54359a3dd679ac77dafc86fb24761ce2d6c2968 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 21:24:23 +1100 Subject: [PATCH 1420/1514] ci: apple-build: compile the Apple Wi-Fi drivers too Main stopped building with the fleet configuration after a merge left centauri_wifi.c passing a const struct cfg80211_bss to a non-const parameter (-Werror, fixed in #3179). The apple-build job already configures CONFIG_APPLE_CENTAURI_T6050_WIFI=y through asahi.config, but it never compiles drivers/net/wireless/apple/, and a change to that directory does not start the job. Compile drivers/net/wireless/apple/, require the option in the configured .config like the other Apple drivers, and run the job for changes under drivers/net/wireless/apple/. Signed-off-by: Ryan Murray --- .github/workflows/apple-build-kunit.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/apple-build-kunit.yml b/.github/workflows/apple-build-kunit.yml index 51354983d82206..c3b3e4d995e196 100644 --- a/.github/workflows/apple-build-kunit.yml +++ b/.github/workflows/apple-build-kunit.yml @@ -21,6 +21,7 @@ on: - 'drivers/iommu/**' - 'drivers/media/platform/apple/**' - 'drivers/mfd/**' + - 'drivers/net/wireless/apple/**' - 'drivers/nvme/host/**' - 'drivers/pci/controller/**' - 'drivers/power/**' @@ -48,6 +49,7 @@ on: - 'drivers/iommu/**' - 'drivers/media/platform/apple/**' - 'drivers/mfd/**' + - 'drivers/net/wireless/apple/**' - 'drivers/nvme/host/**' - 'drivers/pci/controller/**' - 'drivers/power/**' @@ -109,7 +111,7 @@ jobs: for opt in RUST=y DRM_ASAHI=m DRM_APPLE=m DRM_ACCEL_ANE=m VIDEO_APPLE_AVD=m \ NVME_APPLE=m APPLE_DART=y PCIE_APPLE=y USB4=m USB4_APPLE_SOC=m \ SPI_HID_APPLE_OF=m MFD_MACSMC=y MACSMC_POWER=m POWER_RESET_MACSMC=m \ - APPLE_SEP=m KSM=y MM_SUBPAGE=y; do + APPLE_SEP=m KSM=y MM_SUBPAGE=y APPLE_CENTAURI_T6050_WIFI=y; do grep -qx "CONFIG_$opt" .config || { echo "::error::CONFIG_$opt is not set"; exit 1; } done - name: Compile the Apple drivers @@ -123,6 +125,7 @@ jobs: drivers/iommu/ \ drivers/media/platform/apple/ \ drivers/mfd/ \ + drivers/net/wireless/apple/ \ drivers/nvme/host/ \ drivers/pci/controller/ \ drivers/power/ \ From d39ba2143dfff4ea677d017a8422155294c2cfe6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:06:25 +1100 Subject: [PATCH 1421/1514] drm/asahi: keep stopped G14 27.2 work owned until shutdown A command the firmware stopped in a recovery left its queue without a completion stamp. That proves queue progress, not that the GPU no longer reaches its memory, so its VM job guard must not be released. But quarantine() took the flight off rendering/inflight and forgot it. The packet then no longer counted as owned, and a later withdraw() from the scheduler's timeout or cancel path, or fail_all(), could release its guard and let the client's mappings change under the firmware. Track kept work in the runtime instead. blame() adds the packet to State::kept before anything is marked, and the stopped flights, with their VM binding and scene, go to State::kept_flights when they leave the queue. owns() now covers kept packets, so withdraw(), fail_all() and fail_publication() leave the guard alone. fail_doomed() asks only whether a queue still holds the packet. stop() already keeps the whole state for the boot. kept has QUARANTINE_LIMIT (31) places, allocated at start, so keeping a packet never allocates. Each kept packet pins its VM's user UAT context, so the limit is half of the 63 user contexts. Once it is reached, blame() fails and the recovery takes the fail-all path, which keeps all published work owned. The storm window limits the rate of recoveries but not the total, so a slow trickle of stopped work could otherwise use up every context. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 87 ++++++++++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 41 ++++++++++++ 2 files changed, 110 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 82916164955aa7..97aa78aa08466f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -533,13 +533,6 @@ fn latch_guilty(packet: &Packet, error: Error) { } } -/// Keeps a command the firmware stopped, and everything it owns (packet and VM job guard, VM -/// binding, scene), for the rest of the boot: see `Runtime::fail_doomed`. Bounded by the -/// recovery-storm window; the same as `stop` does for everything at shutdown. -fn quarantine(flight: T) { - core::mem::forget(flight); -} - struct Inflight { packet: Arc, last: bool, @@ -566,6 +559,14 @@ struct RenderFlight { doomed: Option, } +/// A command the firmware stopped, kept with everything it owns (VM binding, scene) after it +/// left its queue: see `Runtime::fail_doomed` and `Runtime::keep`. Held, never read. +#[allow(dead_code)] +enum Kept { + Compute(Inflight), + Render(RenderFlight), +} + struct State { peer: Peer, root: crate::fw::types::GpuObject, @@ -606,6 +607,12 @@ struct State { /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. recovery_window: u64, recovery_count: u32, + /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept + /// for the rest of the boot: the firmware may still reach that memory. Allocated with + /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. + kept: KVec>, + /// The stopped commands of those packets, once they left their queue. + kept_flights: KVec, /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so /// teardown skips live-hardware MMIO and RTKit operations. hardware_unreachable: bool, @@ -622,7 +629,9 @@ impl State { { last.publication_error = Some(err); } else { - packet.release_guard(); + if g14_v27_2_abi::guard_releasable(false, self.kept(packet)) { + packet.release_guard(); + } packet.finish(Err(err)); } } @@ -631,11 +640,22 @@ impl State { !self.inflight.is_empty() || self.rendering.is_some() } - fn owns(&self, packet: &Arc) -> bool { + /// Whether a queue holds any of the packet's commands. + fn live(&self, packet: &Arc) -> bool { self.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, packet)) || self.rendering.as_ref().is_some_and(|flight| Arc::ptr_eq(&flight.packet, packet)) } + /// Whether a recovery stopped a command of the packet: it stays owned for the boot. + fn kept(&self, packet: &Arc) -> bool { + self.kept.iter().any(|kept| Arc::ptr_eq(kept, packet)) + } + + /// Whether the runtime owns the packet's VM job guard (`g14_v27_2_abi::guard_releasable`). + fn owns(&self, packet: &Arc) -> bool { + !g14_v27_2_abi::guard_releasable(self.live(packet), self.kept(packet)) + } + fn pending(&self, packet: &Arc) -> bool { self.pending.iter().any(|(current, _)| Arc::ptr_eq(current, packet)) } @@ -1029,7 +1049,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); - quarantine(flight); + self.keep(state, Kept::Render(flight)); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -1058,11 +1078,12 @@ impl Runtime { /// A stopped command left its queue without a completion stamp: that proves queue progress, /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So /// its VM job guard is not released: the error completion quarantines it (no mapping - /// changes), and the caller keeps the flight that owns the packet, its VM binding and - /// scene for the rest of the boot (`quarantine`). Pool slots are reused only after the - /// firmware unregisters them (`free_slots`). + /// changes), the packet stays in `State::kept` (`blame`), and the caller keeps the flight + /// with its VM binding and scene (`keep`), all for the rest of the boot. Pool slots follow + /// the normal rule: reused only after the firmware unregisters them (`free_slots`), and + /// then in the slot's other buffer, so the stopped command stays intact. fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { - if state.owns(packet) { return; } + if state.live(packet) { return; } if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { let _ = state.pending.remove(i); } @@ -1071,12 +1092,38 @@ impl Runtime { packet.finish(Err(err)); } + /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest + /// of the boot. Its packet is already in `State::kept`, so ownership does not depend on + /// this allocation; if it fails, the flight is leaked instead, which keeps it as well. + fn keep(&self, state: &mut State, flight: Kept) { + if let Err(err) = state.kept_flights.push(flight, GFP_KERNEL) { + dev_warn!(self.dev, "GPU: no memory to track a stopped command ({:?}); leaking it\n", err); + } + } + + /// Adds the packet of stopped work to `State::kept` before anything is marked, so it stays + /// owned from here on. Err(EIO) once `g14_v27_2_abi::QUARANTINE_LIMIT` packets are kept: + /// the caller then fails all work, and published work stays owned. + fn reserve_kept(&self, state: &mut State, packet: &Arc) -> Result { + if state.kept(packet) { return Ok(()); } + if !g14_v27_2_abi::quarantine_fits(state.kept.len()) { + dev_err!(self.dev, "GPU: {} clients' stopped work kept this boot; not recovering more\n", + state.kept.len()); + return Err(EIO); + } + // Within the capacity allocated at start: never allocates. + state.kept.push_within_capacity(packet.clone()).map_err(|_| EIO) + } + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the /// published render pair, or the compute command with that completion stamp and the rest of /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { match work { Stopped::Render => { + let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); latch_guilty(&flight.packet, error); @@ -1087,6 +1134,7 @@ impl Runtime { Stopped::Compute(stamp) => { let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) .map(|f| f.packet.clone()) else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); @@ -1385,7 +1433,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); - quarantine(done); + self.keep(state, Kept::Compute(done)); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); @@ -1804,12 +1852,13 @@ impl Backend { } }; let (queue, last) = root.queue(); - let checked = (|| -> Result<(u32, u32)> { + let checked = (|| -> Result<(u32, u32, KVec>)> { let (head, retired) = root.progress()?; if head != retired { return Err(EBUSY); } - Ok((head, root.capacity()?)) + let kept = KVec::with_capacity(g14_v27_2_abi::QUARANTINE_LIMIT, GFP_KERNEL)?; + Ok((head, root.capacity()?, kept)) })(); - let (head, capacity) = match checked { + let (head, capacity, kept) = match checked { Ok(v) => v, Err(e) => { halt_unowned(dev, peer, root, asc, true); @@ -1843,6 +1892,8 @@ impl Backend { recoveries: 0, recovery_window: 0, recovery_count: 0, + kept, + kept_flights: KVec::new(), hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index ed044dd77880d1..e6afbaee74ce6f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -146,6 +146,25 @@ pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { } } +/// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, +/// and with it one user UAT context, and a render one also pins its scene. The limit is half +/// the user contexts, so innocent clients keep the rest. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Whether one more packet with stopped work fits next to the `kept` ones. When it does not, +/// the caller fails all work, and everything published stays owned. +pub(crate) const fn quarantine_fits(kept: usize) -> bool { + kept < QUARANTINE_LIMIT +} + +/// Whether a packet's VM job guard may be released, so its mappings may change. That needs +/// none of its commands in a queue (`live`) and no stopped command of it kept (`kept`). The +/// firmware may still reach a stopped command's memory, so a kept packet stays owned for the +/// rest of the boot, whoever asks: retirement, `withdraw` or `fail_all`. +pub(crate) const fn guard_releasable(live: bool, kept: bool) -> bool { + !live && !kept +} + /// Event ring record kinds. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum EventKind { @@ -472,6 +491,28 @@ mod tests { assert!(new_round(Some(u64::MAX), 0)); } + #[test] + fn a_withdrawn_stopped_packet_keeps_its_guard() { + // The scheduler withdraws a packet whose stopped command left the queue: it is no + // longer live, but it is kept, so its guard stays. + assert!(!guard_releasable(false, true)); + // Still in a queue, kept or not. + assert!(!guard_releasable(true, false)); + assert!(!guard_releasable(true, true)); + // Retired innocent work. + assert!(guard_releasable(false, false)); + } + + #[test] + fn kept_packets_are_bounded_per_boot() { + assert!(quarantine_fits(0)); + assert!(quarantine_fits(QUARANTINE_LIMIT - 1)); + assert!(!quarantine_fits(QUARANTINE_LIMIT)); + assert!(!quarantine_fits(usize::MAX)); + // Innocent clients keep at least half of the 63 user UAT contexts. + assert!(2 * QUARANTINE_LIMIT <= 63); + } + #[test] fn progress_words_fit_the_globals_and_leave_power_words_alone() { let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; From 5d3c9dc95779e0b57d903f6d019f845f8f265c46 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:09:55 +1100 Subject: [PATCH 1422/1514] drm/asahi: consume G14 27.2 recovery reports of rounds already answered The firmware posts a fault or timeout record on the event ring and then opens its recovery round (phase 1). The host can answer a round before it reads that record: a further round opened while stopped work drained, or a round the command timeout found at phase 1. The record then stays in the ring. The next service pass read it, waited 50 ms for a phase 1 that never came, and failed all work. One recovered fault could so take down every client a moment later. Keep a ledger of reports read and rounds answered (g14_v27_2_abi::RecoveryLedger). recover() returns Ok(false) when no round opens. The service then consumes a report whose round was already answered, with a warning, and keeps the fail-all only for a report that has no round. Records read in one pass count as one report, so a fault and a timeout for the same stop do not look like two. recover() also starts from the last generation answered, so a round the host already answered is never answered again. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 63 +++++++++++++------ drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 85 ++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 17 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 97aa78aa08466f..0b1b82976ebc04 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -607,6 +607,8 @@ struct State { /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. recovery_window: u64, recovery_count: u32, + /// Reports read and rounds answered: tells a stale report from a new one. + ledger: g14_v27_2_abi::RecoveryLedger, /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. @@ -1061,8 +1063,9 @@ impl Runtime { // The firmware stopped it and halted, but its event was not seen. Recovery // marks it and waits until it left both queues: retire it now, so its fence // is signalled and the queue behind it runs without waiting for another message. - self.recover(state, ETIMEDOUT, -1)?; - return self.retire_render(state); + if self.recover(state, ETIMEDOUT, -1)? { + return self.retire_render(state); + } } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -1193,11 +1196,13 @@ impl Runtime { /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped /// work then leaves its queue and fails only its own packet and VM; the next recoveries /// while it drains are answered the same way, a bounded number of times. Errors here fail - /// all work (the runtime is not trusted). - fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + /// all work (the runtime is not trusted). Ok(false) if the firmware opened no round within + /// PHASE1_WAIT_MS: the caller decides whether its report was stale. + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { state.root.log_timeout(&self.dev); let mut rounds = 0; - let mut previous = None; + // A round the host already answered must not be answered again. + let mut previous = state.ledger.last(); let began = Instant::::now(); loop { // The state lock is held throughout: keep the whole recovery, including a last round @@ -1207,9 +1212,9 @@ impl Runtime { return Err(ETIMEDOUT); } if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { - dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", - error, slot); - return Err(ETIMEDOUT); + // A further round starts at a phase 1 the drain saw: it cannot go missing. + if rounds > 0 { return Err(EPROTO); } + return Ok(false); } let now = ::ktime_get() as u64; if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { @@ -1279,6 +1284,7 @@ impl Runtime { return Err(ETIMEDOUT); } state.root.answer_recovery(0)?; + state.ledger.answered(generation); dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", generation, start.elapsed().as_millis(), entries); let start = Instant::::now(); @@ -1292,7 +1298,7 @@ impl Runtime { dev_err!(self.dev, "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", state.recoveries, start.elapsed().as_millis()); - return Ok(()); + return Ok(true); } if state.peer.is_crashed() { return Err(EIO); } // Phase 0 = still draining; 1 = a new recovery (a new generation is checked @@ -1342,6 +1348,8 @@ impl Runtime { } fn process_events(&self, state: &mut State) -> Result { + // A fault and a timeout read in one pass are one report (`RecoveryLedger`). + let mut reported = false; // Limit one pass to the ring capacity. Further arrivals notify the worker again. for _ in 0..256 { let Some((cursor, event)) = state.root.peek_event()? else { break; }; @@ -1373,11 +1381,13 @@ impl Runtime { FirmwareEvent::Timeout { slot } => { dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } } FirmwareEvent::Fault => { dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); state.fault.log(&self.dev); state.firmware_error.get_or_insert((EIO, -1)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } @@ -1402,10 +1412,25 @@ impl Runtime { return; } if let Some((error, slot)) = state.firmware_error.take() { - if let Err(err) = self.recover(state, error, slot) { - dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); - self.fail_all(state, err); - return; + match self.recover(state, error, slot) { + Ok(true) => {} + // The host answered this report's round before it read the report (a round + // opened while stopped work drained, or found at a command timeout). + Ok(false) if state.ledger.report_answered() => { + dev_warn!(self.dev, "GPU: firmware report {:?} (slot {}) is for recovery {:?}, already answered\n", + error, slot, state.ledger.last()); + } + Ok(false) => { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + self.fail_all(state, ETIMEDOUT); + return; + } + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } } } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } @@ -1450,11 +1475,14 @@ impl Runtime { state.queue_stamp(), expected, state.submitted, state.retired); if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { // The firmware stopped it and halted, but its event was not seen. - if let Err(err) = self.recover(state, ETIMEDOUT, -1) { - self.fail_all(state, err); - return; + match self.recover(state, ETIMEDOUT, -1) { + Ok(true) => continue, + Ok(false) => {} + Err(err) => { + self.fail_all(state, err); + return; + } } - continue; } state.root.log_timeout(&self.dev); state.fault.log(&self.dev); @@ -1892,6 +1920,7 @@ impl Backend { recoveries: 0, recovery_window: 0, recovery_count: 0, + ledger: g14_v27_2_abi::RecoveryLedger::default(), kept, kept_flights: KVec::new(), hardware_unreachable: false, diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index e6afbaee74ce6f..662f4fb137446f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -146,6 +146,51 @@ pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { } } +/// Tells a fault or timeout report on the event ring that needs a recovery from one whose round +/// the host already answered. +/// +/// The firmware posts the report, then opens the round (phase 1). The host can answer a round +/// before it reads its report: a further round opened while stopped work drains, or a round +/// found at a command timeout. That report is then still in the ring, and the next service pass +/// reads it after the firmware is back at phase 0. It must be consumed, not answered with a +/// wait for a phase 1 that never comes, which would fail all work. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct RecoveryLedger { + /// Service passes that read fault or timeout records. One pass counts once, so a fault and + /// a timeout posted for the same stop are one report. + reports: u64, + /// Rounds the host answered. + answered: u64, + /// Generation of the last round answered. + last: Option, +} + +impl RecoveryLedger { + /// A service pass read fault or timeout records. + pub(crate) fn report(&mut self) { + self.reports = self.reports.saturating_add(1); + } + + /// The host answered round `generation` (wrote phase 0). + pub(crate) fn answered(&mut self, generation: u64) { + self.answered = self.answered.saturating_add(1); + self.last = Some(generation); + } + + /// Generation of the last round answered: a round at phase 1 must carry another one + /// (`new_round`). + pub(crate) const fn last(&self) -> Option { + self.last + } + + /// With no new round open after a report: whether every report read so far has a round the + /// host already answered. Then the report is stale and is consumed. Otherwise the firmware + /// reported a stop without entering recovery. + pub(crate) const fn report_answered(&self) -> bool { + self.reports <= self.answered + } +} + /// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, /// and with it one user UAT context, and a render one also pins its scene. The limit is half /// the user contexts, so innocent clients keep the rest. @@ -491,6 +536,46 @@ mod tests { assert!(new_round(Some(u64::MAX), 0)); } + #[test] + fn a_report_read_before_its_round_is_answered_once() { + // Report, then its round: balanced, nothing left over. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + assert!(ledger.report_answered()); + assert_eq!(ledger.last(), Some(7)); + // A later report with no round open is a stop without recovery: not consumed. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_drain_round_is_consumed() { + // Round 7 from its report; round 8 opened while 7's work drained, answered before its + // report was read. Round 8's report then comes on the next pass, at phase 0. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + ledger.answered(8); + ledger.report(); + assert!(ledger.report_answered()); + // Round 8 is answered: phase 1 with generation 8 again is not a new round. + assert!(!new_round(ledger.last(), 8)); + assert!(new_round(ledger.last(), 9)); + // Its credit is spent: a further report without a round is not stale. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_timeout_round_is_consumed() { + // The command timeout found phase 1 and answered round 3 before the event was read. + let mut ledger = RecoveryLedger::default(); + ledger.answered(3); + ledger.report(); + assert!(ledger.report_answered()); + } + #[test] fn a_withdrawn_stopped_packet_keeps_its_guard() { // The scheduler withdraws a packet whose stopped command left the queue: it is no From a0b2c2e774b723bbe1583045fa139014b055af87 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:12:39 +1100 Subject: [PATCH 1423/1514] drm/asahi: log each G14 27.2 recovery round on one line A J473 row has to tell a firmware-reported stop from a silent hang. Up to now a round logged up to eight snapshot lines and a separate blame line, and the command timeout log had no recovery words at all. Each round now logs one warning with the error, the slot the event named, the last event ring kinds, the snapshot ({flags, target} in hex, the first four entries and the count), and the blamed client with its stamps (compute: the stopped command's stamp and the queue's current stamp; render: the tiler and fragment stamps). log_timeout() also prints the recovery generation, phase and snapshot, so every command timeout and recovery failure shows the control words at that moment. peek_event() now returns the raw kind word for the event history. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 72 +++++++++++++++++++++--------- drivers/gpu/drm/asahi/gpu/v27_2.rs | 29 ++++++++++-- 2 files changed, 78 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 0b1b82976ebc04..6ca2d2f4be948e 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -128,6 +128,8 @@ const RECOVERY_DRAIN_MS: i64 = 1000; /// Further recoveries answered while the stopped work drains (work behind it can time out in /// turn) before the runtime gives up. const FURTHER_RECOVERIES: u32 = 4; +/// Event ring record kinds kept for the logs of a timeout or a recovery. +const EVENT_HISTORY: usize = 8; /// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + /// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler /// job timeout. @@ -567,6 +569,13 @@ enum Kept { Render(RenderFlight), } +/// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps +/// (render: tiler and fragment; compute: the stopped command's and the queue's current one). +struct Blamed { + owner: crate::m3::m3_submit::Owner, + stamps: [u32; 2], +} + struct State { peer: Peer, root: crate::fw::types::GpuObject, @@ -609,6 +618,9 @@ struct State { recovery_count: u32, /// Reports read and rounds answered: tells a stale report from a new one. ledger: g14_v27_2_abi::RecoveryLedger, + /// Kind words of the last event ring records read, and how many were read in all. + events: [u32; EVENT_HISTORY], + events_read: u64, /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. @@ -638,6 +650,17 @@ impl State { } } + /// The kinds of the last event ring records read, oldest first, for a log line. + fn recent_events(&self) -> ([u32; EVENT_HISTORY], usize) { + let count = self.events_read.min(EVENT_HISTORY as u64) as usize; + let mut out = [0; EVENT_HISTORY]; + for (i, kind) in out.iter_mut().take(count).enumerate() { + let at = (self.events_read - count as u64 + i as u64) % EVENT_HISTORY as u64; + *kind = self.events[at as usize]; + } + (out, count) + } + fn running(&self) -> bool { !self.inflight.is_empty() || self.rendering.is_some() } @@ -1121,8 +1144,8 @@ impl Runtime { /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the /// published render pair, or the compute command with that completion stamp and the rest of /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. - fn blame(&self, state: &mut State, error: Error, slot: i32, work: Stopped) -> Result { - match work { + fn blame(&self, state: &mut State, error: Error, work: Stopped) -> Result { + let blamed = match work { Stopped::Render => { let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) else { return Err(EIO); }; @@ -1130,9 +1153,8 @@ impl Runtime { let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; flight.doomed = Some(error); latch_guilty(&flight.packet, error); - let owner = &flight.packet.owner; - dev_err!(self.dev, "GPU: stopped render of {}[{}] (slot {}, {:?})\n", - owner.process(), owner.pid, slot, error); + Blamed { owner: flight.packet.owner, + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } } Stopped::Compute(stamp) => { let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) @@ -1143,11 +1165,10 @@ impl Runtime { flight.doomed.get_or_insert(error); } latch_guilty(&packet, error); - dev_err!(self.dev, "GPU: stopped compute {:#x} of {}[{}] (slot {}, {:?})\n", - stamp, packet.owner.process(), packet.owner.pid, slot, error); + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()] } } - } - Ok(()) + }; + Ok(blamed) } /// Whether every command marked by `blame` has left its queue. @@ -1234,6 +1255,7 @@ impl Runtime { .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); let mut attribution = g14_v27_2_abi::Attribution::default(); let mut entries = 0; + let mut first = [(0u32, 0u32); 4]; let mut stopped_tiler = false; for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { let (flags, target) = state.root.recovery_entry(i)?; @@ -1245,20 +1267,26 @@ impl Runtime { attribution.add(entry.flags, entry.target, render, |stamp| { inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) }); - if entries <= 8 { - dev_err!(self.dev, - "GPU: recovery {} entry {}: flags {:#x} (event {:#x}) target {:#x}\n", - generation, i, entry.flags, entry.event, entry.target); - } + if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } } + let shown = &first[..entries.min(first.len())]; + let (events, seen) = state.recent_events(); // Every round is attributed: work behind the first stopped command can time out in // turn. Unnamed or ambiguous stopped work keeps the fail-stop. let Some(work) = attribution.result() else { - dev_err!(self.dev, "GPU: recovery {} names no single tracked command ({} entries)\n", - generation, entries); + dev_err!(self.dev, "GPU: recovery {} ({:?}, slot {}) names no single tracked command: snapshot ({} entries) {:x?}, events {:?}\n", + generation, error, slot, entries, shown, &events[..seen]); return Err(EIO); }; - self.blame(state, error, slot, work)?; + let blamed = self.blame(state, error, work)?; + let (what, second) = match work { + Stopped::Render => ("render, tiler", "fragment"), + Stopped::Compute(_) => ("compute", "queue at"), + }; + dev_warn!(self.dev, "GPU: recovery {} ({:?}, slot {}, events {:?}): snapshot ({} entries) {:x?}; stopped {} {:#x} ({} {:#x}) of {}[{}]\n", + generation, error, slot, &events[..seen], entries, shown, what, + blamed.stamps[0], second, blamed.stamps[1], + blamed.owner.process(), blamed.owner.pid); if stopped_tiler { if let Some(flight) = state.rendering.as_ref() { let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; @@ -1285,8 +1313,8 @@ impl Runtime { } state.root.answer_recovery(0)?; state.ledger.answered(generation); - dev_err!(self.dev, "GPU: recovery {} answered in {} ms ({} snapshot entries)\n", - generation, start.elapsed().as_millis(), entries); + dev_info!(self.dev, "GPU: recovery {} answered in {} ms\n", + generation, start.elapsed().as_millis()); let start = Instant::::now(); loop { let _ = state.root.drain(); @@ -1352,7 +1380,9 @@ impl Runtime { let mut reported = false; // Limit one pass to the ring capacity. Further arrivals notify the worker again. for _ in 0..256 { - let Some((cursor, event)) = state.root.peek_event()? else { break; }; + let Some((cursor, kind, event)) = state.root.peek_event()? else { break; }; + state.events[(state.events_read % EVENT_HISTORY as u64) as usize] = kind; + state.events_read += 1; match event { FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { let Some(reply) = state.root.reserve_control_reply()? else { @@ -1921,6 +1951,8 @@ impl Backend { recovery_window: 0, recovery_count: 0, ledger: g14_v27_2_abi::RecoveryLedger::default(), + events: [0; EVENT_HISTORY], + events_read: 0, kept, kept_flights: KVec::new(), hardware_unreachable: false, diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index 1b48e8cf661877..78046f9abb0728 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -738,6 +738,27 @@ impl RootV27_2 { for (name, queue) in ["tiler", "fragment"].into_iter().zip(&self.render_queues) { Self::log_queue(dev, name, &queue.positions, &queue.queue, &queue.event); } + let (generation, phase) = (self.halt_count(), self.recovery_phase()); + let (snapshot, entries) = self.recovery_snapshot(); + dev_err!(dev, "GPU: recovery generation={:?} phase={:?} snapshot ({} entries) {:x?}\n", + generation, phase, entries, &snapshot[..entries.min(snapshot.len())]); + } + + /// The first valid recovery snapshot entries, {flags, target} in hex, and how many valid + /// entries there are in all (the first invalid entry ends the snapshot). Logging only. + pub(crate) fn recovery_snapshot(&self) -> ([(u32, u32); 4], usize) { + let mut first = [(0, 0); 4]; + let mut entries = 0; + for i in 0..RECOVERY_SNAPSHOT_ENTRIES { + match self.recovery_entry(i) { + Ok((flags, target)) if flags & 1 != 0 => { + if let Some(slot) = first.get_mut(entries) { *slot = (flags, target); } + entries += 1; + } + _ => break, + } + } + (first, entries) } pub(crate) fn render_kick(dm: usize) -> u64 { @@ -850,7 +871,8 @@ impl RootV27_2 { && job.event.current_noncoherent().raw() == job.expected_stamp) } - pub(crate) fn peek_event(&self) -> Result> { + /// The record at the head of the event ring: its cursor, its raw kind word and its decoding. + pub(crate) fn peek_event(&self) -> Result> { use crate::m3::m3_channel_format::RECEIVE_BYTES; let state = &self.channels[2 * EVENT_RING]; let ring = &self.channels[2 * EVENT_RING + 1]; @@ -863,7 +885,8 @@ impl RootV27_2 { crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); crate::pgtable::poc_barrier(); let word = |offset| Self::word(ring, at + offset); - let event = match g14_v27_2_abi::event_kind(word(0)?) { + let kind = word(0)?; + let event = match g14_v27_2_abi::event_kind(kind) { EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, ])), @@ -874,7 +897,7 @@ impl RootV27_2 { EventKind::ChannelError => FirmwareEvent::ChannelError, EventKind::Notification => FirmwareEvent::Notification, }; - Ok(Some((read, event))) + Ok(Some((read, kind, event))) } /// Validates a byte range of the control object before it is sliced or cache-maintained. From 9303dd812506365e6495af0320be259ab031db70 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:16:00 +1100 Subject: [PATCH 1424/1514] drm/asahi: fail all G14 27.2 work on a command timeout only without a round The driver's 5 s command timeout is a backstop for the firmware's own recovery, but it still acted alone. The compute path answered a round open at phase 1 only when the front command was not blamed yet, and the render path only when the render was not stopped. Recovery also restarted the clocks of queued compute work but not of the render in flight. So a render that waited out a round for another client could reach the timeout and fail every client. Ask the firmware first, in both paths (g14_v27_2_abi:: command_timeout_action). With a round open, recover: the snapshot names the stopped command by stamp (stopped_compute(), which never names a retired command), only that client fails, and the others' work resumes after phase 0 with its clock restarted. Only with no round open, a silent hang, does the timeout still fail all work. It then logs the queue positions, the recovery generation, phase and snapshot, the MMU fault status, the last event ring kinds and the report and round counts, so a row tells a silent hang from a missed report. sleep_prepare() also refuses while the firmware has a round open, so no round crosses a system sleep. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 60 +++++++++++++++----- drivers/gpu/drm/asahi/g14_v27_2_abi.rs | 77 ++++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 6ca2d2f4be948e..b87e308af54fe9 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1082,16 +1082,18 @@ impl Runtime { } } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); - if state.root.recovery_phase()? == 1 && doomed.is_none() { - // The firmware stopped it and halted, but its event was not seen. Recovery - // marks it and waits until it left both queues: retire it now, so its fence - // is signalled and the queue behind it runs without waiting for another message. + if g14_v27_2_abi::command_timeout_action(state.root.recovery_phase()?) + == g14_v27_2_abi::TimeoutAction::Recover + { + // The firmware has a round open whose event was not seen. Recovery blames the + // work it stopped and waits until that left its queue. Then retire again, so a + // stopped render's fence is signalled and the queue behind it runs without + // waiting for another message; an innocent render got its clock restarted. if self.recover(state, ETIMEDOUT, -1)? { return self.retire_render(state); } } - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + self.log_silent_hang(state, "render"); return Err(ETIMEDOUT); } Ok(()) @@ -1157,8 +1159,9 @@ impl Runtime { stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } } Stopped::Compute(stamp) => { - let Some(packet) = state.inflight.iter().find(|f| f.stamp.raw() == stamp) - .map(|f| f.packet.clone()) else { return Err(EIO); }; + let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + let Some(packet) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| state.inflight[i].packet.clone()) else { return Err(EIO); }; self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { @@ -1171,6 +1174,19 @@ impl Runtime { Ok(blamed) } + /// The last resort of a command timeout: the firmware has no recovery round open, so it + /// reported nothing the host can answer. Logs what a row needs to tell a silent hang from a + /// missed report: queue positions and recovery words (`log_timeout`), the MMU fault status, + /// and the last event ring kinds with the report and round counts. + fn log_silent_hang(&self, state: &State, work: &str) { + state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); + let (events, seen) = state.recent_events(); + let (reports, answered) = state.ledger.counts(); + dev_err!(self.dev, "GPU: {} timed out with no recovery round open: last events {:?} ({} read), {} reports, {} rounds answered (last {:?}); failing all work\n", + work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); + } + /// Whether every command marked by `blame` has left its queue. fn doomed_retired(&self, state: &mut State) -> Result { if let Some(flight) = state.rendering.as_ref() { @@ -1265,7 +1281,8 @@ impl Runtime { let retired = state.retired_total; let inflight = &state.inflight; attribution.add(entry.flags, entry.target, render, |stamp| { - inflight.iter().any(|f| f.stamp.raw() == stamp && f.ordinal > retired) + let flights = inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + g14_v27_2_abi::stopped_compute(flights, retired, stamp).is_some() }); if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } } @@ -1323,6 +1340,7 @@ impl Runtime { // Work behind the stopped command waited out the recovery: restart its clocks. let now = Instant::now(); for flight in state.inflight.iter_mut() { flight.started = now; } + if let Some(flight) = state.rendering.as_mut() { flight.started = now; } dev_err!(self.dev, "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", state.recoveries, start.elapsed().as_millis()); @@ -1481,8 +1499,7 @@ impl Runtime { } while !state.inflight.is_empty() { let front = &state.inflight[0]; - let (ordinal, started, unblamed, expected) = - (front.ordinal, front.started, front.doomed.is_none(), front.stamp.raw()); + let (ordinal, started, expected) = (front.ordinal, front.started, front.stamp.raw()); if state.retired_total >= ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); @@ -1503,19 +1520,22 @@ impl Runtime { if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", state.queue_stamp(), expected, state.submitted, state.retired); - if unblamed && state.root.recovery_phase().unwrap_or(0) == 1 { - // The firmware stopped it and halted, but its event was not seen. + let phase = state.root.recovery_phase().unwrap_or(0); + if g14_v27_2_abi::command_timeout_action(phase) == g14_v27_2_abi::TimeoutAction::Recover { + // The firmware has a round open whose event was not seen. Recovery blames + // the command it names by stamp, which need not be this front one, and + // fails only that client; the others' work resumes after phase 0. match self.recover(state, ETIMEDOUT, -1) { Ok(true) => continue, Ok(false) => {} Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); self.fail_all(state, err); return; } } } - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + self.log_silent_hang(state, "compute"); self.fail_all(state, ETIMEDOUT); return; } @@ -1573,6 +1593,16 @@ impl Runtime { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } if !state.running() { + // No recovery round crosses a sleep: a round open now (the firmware stopped + // without anything of ours running) is answered by the service first. + let phase = state.root.recovery_phase().unwrap_or(0); + if phase != 0 { + dev_err!(self.dev, "GPU: sleep refused, firmware recovery phase {}\n", phase); + self.asleep.store(false, Ordering::Release); + self.pump(state); + self.notify.wake(); + return Err(EBUSY); + } break; } if remaining == 0 { diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 662f4fb137446f..96d4992845d68f 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -137,6 +137,39 @@ impl Attribution { } } +/// The published compute command a snapshot target names: the one, among commands the queue +/// has not retired (`ordinal > retired`), whose completion stamp is `stamp`. `flights` yields +/// each published command's (completion stamp, ordinal) in publication order. A command that +/// already retired is never blamed, even before the host has taken it off its list. +pub(crate) fn stopped_compute( + flights: impl IntoIterator, + retired: u64, + stamp: u32, +) -> Option { + flights.into_iter().position(|(s, ordinal)| s == stamp && ordinal > retired) +} + +/// What the host does when a command ran past the driver's command timeout. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TimeoutAction { + /// The firmware has a recovery round open (phase 1): answer it, which blames the work it + /// stopped by stamp and fails only that client. + Recover, + /// No round open: the firmware reported nothing and stopped nothing that the host can + /// answer (a silent hang), or the handshake is in a state the host does not own. Failing + /// all work is the last resort. + FailAll, +} + +/// The driver's command timeout is only a backstop for the firmware's own recovery: it fails +/// every client only when the firmware has no round open. +pub(crate) const fn command_timeout_action(phase: u32) -> TimeoutAction { + match phase { + 1 => TimeoutAction::Recover, + _ => TimeoutAction::FailAll, + } +} + /// A further recovery round while stopped work drains must carry a new generation; the same /// generation again means the host misread the handshake. pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { @@ -189,6 +222,11 @@ impl RecoveryLedger { pub(crate) const fn report_answered(&self) -> bool { self.reports <= self.answered } + + /// Reports read and rounds answered so far, for a log line. + pub(crate) const fn counts(&self) -> (u64, u64) { + (self.reports, self.answered) + } } /// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, @@ -576,6 +614,45 @@ mod tests { assert!(ledger.report_answered()); } + #[test] + fn a_timed_out_compute_is_blamed_by_stamp_and_spares_its_neighbours() { + // Compute list in publication order: (owner, completion stamp, ordinal). Client A's + // command completed and retired, but the host has not taken it off its list yet; B's + // command is the one the firmware timed out (event 4); C's command was published after + // it and waits behind it. + let flights = [('A', 0x7900u32, 1u64), ('B', 0x7a00, 2), ('C', 0x7b00, 3)]; + let retired = 1; + let unretired = |stamp| stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, stamp) + .is_some(); + // The J473 compute snapshot: one entry {0x7, next stamp of the stopped command}. + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, unretired); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + let stopped = stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7a00); + assert_eq!(stopped, Some(1)); + // blame() dooms every listed command of the stopped command's packet, and only those. + let guilty = flights[stopped.unwrap()].0; + let doomed: [bool; 3] = core::array::from_fn(|i| flights[i].0 == guilty); + assert_eq!(doomed, [false, true, false]); + // A target naming the retired front is not blamed on it. + assert_eq!(stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7900), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7900, None, unretired); + assert_eq!(a.result(), None); + } + + #[test] + fn the_command_timeout_fails_all_only_without_a_recovery_round() { + assert_eq!(command_timeout_action(1), TimeoutAction::Recover); + // Silent hang: no round open. + assert_eq!(command_timeout_action(0), TimeoutAction::FailAll); + // The host's own phases or anything else: the handshake is not the firmware's to + // continue, so the host does not answer it from a timeout. + for phase in [2, 3, 4, u32::MAX] { + assert_eq!(command_timeout_action(phase), TimeoutAction::FailAll); + } + } + #[test] fn a_withdrawn_stopped_packet_keeps_its_guard() { // The scheduler withdraws a packet whose stopped command left the queue: it is no From c49b2ded3a4ba6c90b149025b08bcdf614de732b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:21:22 +1100 Subject: [PATCH 1425/1514] drm/asahi: never drop a stopped G14 27.2 flight when keeping it fails Keeping a stopped flight used KVec::push(), which drops the value when the allocation fails. That would release the flight's VM binding and scene while the firmware may still reach them. Reserve the place first and leak the flight if that fails. Its packet is kept either way, so the client's guard stays. Keep compute and render flights in two lists instead of one enum. A RenderFlight is much larger than an Inflight, so the enum would have made every kept compute flight as large as a render one. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 37 +++++++++++++++--------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index b87e308af54fe9..ac78695a87d755 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -561,14 +561,6 @@ struct RenderFlight { doomed: Option, } -/// A command the firmware stopped, kept with everything it owns (VM binding, scene) after it -/// left its queue: see `Runtime::fail_doomed` and `Runtime::keep`. Held, never read. -#[allow(dead_code)] -enum Kept { - Compute(Inflight), - Render(RenderFlight), -} - /// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps /// (render: tiler and fragment; compute: the stopped command's and the queue's current one). struct Blamed { @@ -625,8 +617,10 @@ struct State { /// for the rest of the boot: the firmware may still reach that memory. Allocated with /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. kept: KVec>, - /// The stopped commands of those packets, once they left their queue. - kept_flights: KVec, + /// The stopped commands of those packets, with their VM binding and scene, once they left + /// their queue (`Runtime::keep`). Held, never read. + kept_compute: KVec, + kept_renders: KVec, /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so /// teardown skips live-hardware MMIO and RTKit operations. hardware_unreachable: bool, @@ -1074,7 +1068,7 @@ impl Runtime { } if let Some(err) = flight.doomed { self.fail_doomed(state, &flight.packet, err); - self.keep(state, Kept::Render(flight)); + self.keep(&mut state.kept_renders, flight); } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { @@ -1121,11 +1115,17 @@ impl Runtime { } /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest - /// of the boot. Its packet is already in `State::kept`, so ownership does not depend on - /// this allocation; if it fails, the flight is leaked instead, which keeps it as well. - fn keep(&self, state: &mut State, flight: Kept) { - if let Err(err) = state.kept_flights.push(flight, GFP_KERNEL) { - dev_warn!(self.dev, "GPU: no memory to track a stopped command ({:?}); leaking it\n", err); + /// of the boot (`State::kept_compute`, `kept_renders`). Its packet is already in + /// `State::kept`, so ownership does not depend on this allocation. If it fails, the flight + /// is leaked, which keeps it as well; it is never dropped. + fn keep(&self, list: &mut KVec, flight: T) { + if list.reserve(1, GFP_KERNEL).is_err() { + dev_warn!(self.dev, "GPU: no memory to track a stopped command; leaking it\n"); + core::mem::forget(flight); + return; + } + if let Err(kernel::alloc::kvec::PushError(flight)) = list.push_within_capacity(flight) { + core::mem::forget(flight); } } @@ -1505,7 +1505,7 @@ impl Runtime { self.retire_slot(state, done.slot); if let Some(err) = done.doomed { self.fail_doomed(state, &done.packet, err); - self.keep(state, Kept::Compute(done)); + self.keep(&mut state.kept_compute, done); } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); @@ -1984,7 +1984,8 @@ impl Backend { events: [0; EVENT_HISTORY], events_read: 0, kept, - kept_flights: KVec::new(), + kept_compute: KVec::new(), + kept_renders: KVec::new(), hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, From b38daf6cf1e6fc4116d60b302b014d8e4c5b0d45 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:57:01 +1100 Subject: [PATCH 1426/1514] drm/apple: dpavservep: KUnit: DCPDP13Service is admitted on endpoint 0x28 The identity KUnit table still expected the generic class to be refused on the classic DPAV endpoint. Admit DCPDP13Service with EPICUnit 0 there, up to interface-id 0xffff, as the previous commit does; AppleDCPDP2HDMI, unit == interface-id, channel 0, channels over u16, other classes and other MCDP parts stay refused. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/epic/dpavservep-identity-test.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c index 96a6003a88cbc7..584b37ccd4ff1c 100644 --- a/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c +++ b/drivers/gpu/drm/apple/epic/dpavservep-identity-test.c @@ -61,11 +61,12 @@ static const struct dpavid_case dpavid_cases[] = { "DCPDPService", 3, 3, false }, /* - * AFKV2 on the classic DPAV endpoint is refused: using the service there - * resets the M4 Air when the external processor releases its link. + * AFKV2 on the classic DPAV endpoint: the MCDP29xx converters and the + * M3/M4 Airs' generic DCPDP13Service, with EPICUnit 0 and a bounded + * dynamic interface-id. AppleDCPDP2HDMI and the other classes stay refused. */ { "v2 ep 0x28: DP13 unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, - "DCPDP13Service", 0, 7, false }, + "DCPDP13Service", 0, 7, true }, { "v2 ep 0x28: DP2HDMI unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "AppleDCPDP2HDMI", 0, 1, false }, { "v2 ep 0x28: MCDP29XX unit 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, @@ -77,7 +78,7 @@ static const struct dpavid_case dpavid_cases[] = { { "v2 ep 0x28: other MCDP part", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "AppleDCPMCDP2800", 0, 1, false }, { "v2 ep 0x28: unit 0, channel at u16 max", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, - "DCPDP13Service", 0, 0xffff, false }, + "DCPDP13Service", 0, 0xffff, true }, { "v2 ep 0x28: unit == channel", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, "DCPDP13Service", 7, 7, false }, { "v2 ep 0x28: channel 0", DPAVID_V2, DPAVSERV_ENDPOINT, DPAVID_NAME, From 5f66e6979d88059eee062f8dba841cc1126a8aca Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 07:14:31 -0500 Subject: [PATCH 1427/1514] soc: apple: display-gate: boot the J773g as main does when dcpext0 cannot be adopted On the J773g on macOS 27.2, the boot loader hands dcpext0 over running and enables the display subsystem and disp0's DART for it. The gate then enabled dcpext0's chain. But apple-dart keeps a locked DART's firmware roots only for T6041, T6050, T8140 and T8142 DARTs, not for a T8132 one. So dcpext0's firmware DART failed its probe (-EBUSY, with a WARNING in iommu_setup_default_domain()), and the DCP and its PHY never probed. The display subsystem never registered, and G16, which waits for a handed-over display before its first start, never probed either. The same Mac boots main with the GPU up on the boot framebuffer. - include/linux/soc/apple/dart.h: apple_dart_keeps_locked_roots() names the DART kinds whose locked firmware roots apple-dart keeps (fw_mirror). apple-dart.c takes its fw_mirror list from it, with no functional change. - The gate enables a T8132 fixed-DP chain only when both of its DARTs are of such a kind. On this tree no T8132 DART is, so the J773g HDMI chain stays off until apple-dart keeps a locked T8132 DART's roots. - When no chain is enabled on a headless T8132 (no internal DCP handed over on 27.2), nomodeset included, the gate disables what the boot loader enabled for the external processors: the display subsystem, and its DART unless the main DCP is enabled. With no display handed over, G16 starts on the boot framebuffer, as on main. - A boot where the loader published nothing for the dcpexts changes nothing. tools/asahi/t8132-display-gate-tests.py now also covers: - no handover: no change to any node, to disp0's iommus or to the log, with and without nomodeset; - the J773g's T8132 DARTs: the chain stays off, and the display and its DART go; - either DART of the chain alone not kept; - a laptop whose main DCP is handed over: its display is kept; - a headless tree with the main DCP enabled: the display goes, its DART stays. The existing refusal cases also check that the display goes. Signed-off-by: DjDeveloperr --- drivers/iommu/apple-dart.c | 5 +- drivers/soc/apple/display-gate.c | 91 +++++++++++- include/linux/soc/apple/dart.h | 15 ++ tools/asahi/t8132-display-gate-tests.py | 184 ++++++++++++++++++++++-- 4 files changed, 281 insertions(+), 14 deletions(-) diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index dc0b0a15d163ce..c630e5a248b159 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -6377,10 +6377,7 @@ static int apple_dart_probe(struct platform_device *pdev) * roots of its own (dart-dcpextN SID 23, dart-dispextN SIDs 0 and 16). */ dart->fw_mirror = dart->locked && !dart->fw_handoff && - (of_device_is_compatible(dev->of_node, "apple,t6041-dart") || - of_device_is_compatible(dev->of_node, "apple,t6050-dart") || - of_device_is_compatible(dev->of_node, "apple,t8140-dart") || - of_device_is_compatible(dev->of_node, "apple,t8142-dart")); + apple_dart_keeps_locked_roots(dev->of_node); /* * A T6040/T6041 MTP (apple,t6041-mtp on both) may arrive live after the * boot keyboard used it; its firmware cannot be restarted. Do not reset diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index dc63ff1734d34e..4aac37b50f9777 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -117,6 +117,7 @@ #include #include #include +#include #include #include #include @@ -3691,9 +3692,86 @@ static bool __init gate_t8132_fixed_dp_ready(struct device_node *nodes[T8132_HDM return false; } } + /* + * The processor runs on through the handover, behind DARTs the boot + * loader leaves locked: adopting it needs apple-dart to keep their + * firmware roots. Off that, the firmware DART's probe fails (-EBUSY on + * the J773g), the processor and its PHY never probe, and the display + * subsystem never binds. + */ + if (!apple_dart_keeps_locked_roots(nodes[T8132_HDMI_FW_DART]) || + !apple_dart_keeps_locked_roots(nodes[T8132_HDMI_DISP_DART])) { + staged_info("%pOF: the firmware roots of %pOF and %pOF are not kept, HDMI left off\n", + nodes[T8132_HDMI_DCP], nodes[T8132_HDMI_FW_DART], + nodes[T8132_HDMI_DISP_DART]); + return false; + } return true; } +/* + * A headless T8132 (no internal display processor handed over on 27.2) whose + * HDMI chain stays off: the display subsystem the boot loader enabled for it + * has no processor left to bind, since the main DCP is the M4 backend's on its + * firmware path only (apple_dcp_usable()). Left enabled it never registers, + * and the GPU, whose first start follows a handed-over display, waits for it + * for good. Disable it, as when the boot loader hands over no display: the + * boot framebuffer stays, and the GPU starts on it. Its DART (disp0's), which + * the boot loader enabled with it, goes too unless the main DCP, whose piodma + * also maps through it, is enabled. + */ +static void __init gate_t8132_display_off(void) +{ + struct device_node *display, *internal; + struct of_phandle_args args; + struct of_changeset *cs; + bool panel, internal_on; + int i, ret; + + display = of_find_node_by_path("disp0"); + if (!display) + display = of_find_compatible_node(NULL, NULL, gate_soc->display_compat); + if (!display || !of_device_is_compatible(display, gate_soc->display_compat) || + !of_device_is_available(display)) { + of_node_put(display); + return; + } + internal = of_find_node_by_path("dcp"); + if (!internal) + internal = of_find_compatible_node(NULL, NULL, gate_soc->dcp_compat); + panel = gate_t8132_dcp_v27_2(internal); + internal_on = of_device_is_available(internal); + of_node_put(internal); + if (panel) { + of_node_put(display); + return; + } + + cs = gate_cs_alloc(); + if (!cs) { + staged_err("%pOF: could not allocate changeset\n", display); + of_node_put(display); + return; + } + ret = of_changeset_update_prop_string(cs, display, "status", "disabled"); + for (i = 0; !ret && !internal_on && + !of_parse_phandle_with_args(display, "iommus", "#iommu-cells", i, &args); i++) { + if (of_device_is_available(args.np)) + ret = of_changeset_update_prop_string(cs, args.np, "status", "disabled"); + of_node_put(args.np); + } + if (!ret) + ret = of_changeset_apply(cs); + if (ret) { + gate_cs_free(cs); + staged_err("%pOF: could not disable it without HDMI: %d\n", display, ret); + } else { + staged_info("no HDMI chain and no internal display: %pOF disabled, boot framebuffer kept\n", + display); + } + of_node_put(display); +} + /* * T8132 on macOS 27.2 (off the M4 26.6.2 firmware path): any apple,t8132-dcpext * wired to a fixed DP PHY (phy-names = "dp-phy", e.g. the J773g HDMI port) @@ -3708,6 +3786,9 @@ static bool __init gate_t8132_fixed_dp_ready(struct device_node *nodes[T8132_HDM * is not handed over (a headless Mac mini), disp0's DART is left unprobed by * apple-dart and would hold the display subsystem's probe forever, so iommus * is replaced with dispext's DART instead. + * + * With no chain enabled (no handover, a refused one, or nomodeset), a headless + * T8132 boots as without this gate: see gate_t8132_display_off(). */ static void __init gate_t8132_run(void) { @@ -3715,12 +3796,15 @@ static void __init gate_t8132_run(void) struct device_node *nodes[T8132_HDMI_NR]; bool append_dart = false; bool display_checked = false; + bool enabled = false; unsigned int i; int phy_idx, ret; - if (IS_ENABLED(CONFIG_VIDEO) && video_firmware_drivers_only()) - return; staged_prefix = gate_soc->prefix; + if (IS_ENABLED(CONFIG_VIDEO) && video_firmware_drivers_only()) { + gate_t8132_display_off(); + return; + } for_each_compatible_node(dcp, NULL, "apple,t8132-dcpext") { struct of_changeset *cs; @@ -3793,10 +3877,13 @@ static void __init gate_t8132_run(void) append_dart ? "appended" : "on", nodes[T8132_HDMI_DISP_DART]); append_dart = true; + enabled = true; } gate_t8132_put_nodes(nodes); } of_node_put(display); + if (!enabled) + gate_t8132_display_off(); } /* Runs before of_platform_default_populate_init() at arch_initcall_sync. */ diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 3c46255efd6e56..15e7c256999e87 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -6,11 +6,26 @@ #include #include #include +#include #include struct device; struct device_node; +/* + * Whether apple-dart keeps the firmware's root slots of a DART of @np's kind + * that the boot loader leaves locked (fw_mirror). Only then can a coprocessor + * the boot loader leaves running behind such a DART be adopted: on the plain + * locked path its firmware loses the mappings it runs on. + */ +static inline bool apple_dart_keeps_locked_roots(const struct device_node *np) +{ + return of_device_is_compatible(np, "apple,t6041-dart") || + of_device_is_compatible(np, "apple,t6050-dart") || + of_device_is_compatible(np, "apple,t8140-dart") || + of_device_is_compatible(np, "apple,t8142-dart"); +} + /* Retained internal-display ownership is qualified only with a built-in * DART provider. Other consumers, including modular DART, keep the APIs below. */ diff --git a/tools/asahi/t8132-display-gate-tests.py b/tools/asahi/t8132-display-gate-tests.py index 9361b8a6008f50..01fb832783e505 100755 --- a/tools/asahi/t8132-display-gate-tests.py +++ b/tools/asahi/t8132-display-gate-tests.py @@ -35,6 +35,7 @@ def main(): gate_src = (ROOT / 'drivers/soc/apple/display-gate.c').read_text() disp_hdr = (ROOT / 'include/linux/soc/apple/display.h').read_text() t8132_hdr = (ROOT / 'include/linux/soc/apple/t8132.h').read_text() + dart_hdr = (ROOT / 'include/linux/soc/apple/dart.h').read_text() # Enforce at source level that T8132 fixed-DP gate matches the SoC, not a board name, # and carries no hard-coded board node paths. @@ -51,6 +52,7 @@ def main(): uuid_lines, extract_block(disp_hdr, r'^static inline bool apple_dcp_image_v27_2\('), extract_block(t8132_hdr, r'^static inline bool apple_t8132_dcpext_v27_2\('), + extract_block(dart_hdr, r'^static inline bool apple_dart_keeps_locked_roots\('), extract_block(gate_src, r'^static int gate_iommus_append\('), extract_block(gate_src, r'^static struct of_changeset \*__init gate_cs_alloc\('), extract_block(gate_src, r'^static void __init gate_cs_free\('), @@ -61,6 +63,7 @@ def main(): extract_block(gate_src, r'^static void __init gate_t8132_put_nodes\('), extract_block(gate_src, r'^static int __init gate_t8132_resolve_fixed_dp\('), extract_block(gate_src, r'^static bool __init gate_t8132_fixed_dp_ready\('), + extract_block(gate_src, r'^static void __init gate_t8132_display_off\('), extract_block(gate_src, r'^static void __init gate_t8132_run\('), ]) @@ -474,6 +477,13 @@ def main(): return 0; } ''' + helpers + r''' +/* + * A DART kind whose locked firmware roots apple-dart keeps + * (apple_dart_keeps_locked_roots()). The J773g's own, apple,t8132-dart, is not + * one in this tree: see j773g_darts(). + */ +#define KEPT_DART "apple,t6041-dart" + struct fixture { struct device_node display, disp0_dart, main_dcp; struct device_node phy, fw_dart, disp_dart, mbox, piodma, dcpext0; @@ -545,10 +555,12 @@ def main(): .path = "/soc/phy@999700000", .phandle = 20, .available = false, }; f->fw_dart = (struct device_node){ - .path = "/soc/iommu@999340000", .phandle = 21, .available = false, + .path = "/soc/iommu@999340000", .compatible = KEPT_DART, + .phandle = 21, .available = false, }; f->disp_dart = (struct device_node){ - .path = "/soc/iommu@999300000", .phandle = 22, .available = false, + .path = "/soc/iommu@999300000", .compatible = KEPT_DART, + .phandle = 22, .available = false, }; f->mbox = (struct device_node){ .path = "/soc/mailbox@999e08000", .phandle = 23, .available = false, @@ -606,6 +618,67 @@ def main(): register_node(&f->dcpext1); } +/* The J773g's dcpext0 DARTs, which this tree's apple-dart does not keep the locked roots of. */ +static void j773g_darts(struct fixture *f) +{ + f->fw_dart.compatible = "apple,t8132-dart"; + f->disp_dart.compatible = "apple,t8132-dart"; +} + +/* Stage 2 published nothing for the dcpexts: no image, placeholders, no display. */ +static void no_handover(struct fixture *f) +{ + struct device_node *dcps[] = { &f->dcpext0, &f->dcpext1 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(dcps); i++) { + dcps[i]->fw_uuid = NULL; + dcps[i]->fw_uuid_count = 0; + dcps[i]->fw_ver_cells = 0; + dcps[i]->fw_compat_cells = 0; + } + f->mem_text.available = f->mem_data.available = f->mem_heap.available = false; + f->display.available = false; +} + +struct snapshot { + bool available[MAX_NODES]; + int display_iommus; + struct device_node *display_iommu[4]; +}; + +static void take_snapshot(struct fixture *f, struct snapshot *snap) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + snap->available[i] = all_nodes[i]->available; + snap->display_iommus = f->display.iommu_count; + memcpy(snap->display_iommu, f->display.iommus, sizeof(snap->display_iommu)); +} + +static void expect_unchanged(struct fixture *f, const struct snapshot *snap) +{ + unsigned int i; + + for (i = 0; i < nr_nodes; i++) + assert(all_nodes[i]->available == snap->available[i]); + assert(f->display.iommu_count == snap->display_iommus); + assert(!memcmp(f->display.iommus, snap->display_iommu, sizeof(snap->display_iommu))); + assert(nr_applied_cs == 0); +} + +/* + * What the GPU sees (asahi_g16_display_prepare()): with the display subsystem + * disabled it starts on the boot framebuffer instead of waiting for it. + */ +static void expect_gpu_on_boot_framebuffer(struct fixture *f) +{ + assert(!of_device_is_available(&f->display)); + assert(!f->disp0_dart.available); + assert(f->display.iommu_count == 1 && f->display.iommus[0] == &f->disp0_dart); +} + static void expect_chain(struct fixture *f, bool enabled) { assert(f->phy.available == enabled); @@ -619,6 +692,7 @@ def main(): int main(void) { + struct snapshot snap; struct fixture f; /* 1. Headless T8132 (J773g-like): phandle-derived chain enabled; disp0 iommus replaced. */ @@ -649,38 +723,47 @@ def main(): assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp_dart); check_refs_zero(); + /* + * 4-7: a refused chain on a headless T8132 leaves the display subsystem the + * boot loader enabled, and its DART, disabled: the GPU starts on the boot + * framebuffer. + */ /* 4. Unapproved firmware UUID on dcpext0 -> chain stays disabled, disp0 unchanged. */ init_fixture(&f); + f.disp0_dart.available = true; f.dcpext0.fw_uuid = "00000000-0000-0000-0000-000000000000"; gate_t8132_run(); expect_chain(&f, false); - assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + expect_gpu_on_boot_framebuffer(&f); check_refs_zero(); /* 5. Placeholder (disabled) memory-region -> refused whole. */ init_fixture(&f); + f.disp0_dart.available = true; f.mem_heap.available = false; gate_t8132_run(); expect_chain(&f, false); - assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + expect_gpu_on_boot_framebuffer(&f); check_refs_zero(); /* 6. Missing phandle (e.g. no piodma child) -> refused whole. */ init_fixture(&f); + f.disp0_dart.available = true; f.dcpext0.piodma_child = NULL; gate_t8132_run(); expect_chain(&f, false); - assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + expect_gpu_on_boot_framebuffer(&f); check_refs_zero(); /* 7. Any chain node already enabled -> refused whole, DART not modified. */ init_fixture(&f); + f.disp0_dart.available = true; f.phy.available = true; gate_t8132_run(); assert(f.phy.available); assert(!f.fw_dart.available && !f.disp_dart.available && !f.mbox.available && !f.piodma.available && !f.dcpext0.available); - assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); + expect_gpu_on_boot_framebuffer(&f); check_refs_zero(); /* 8. Disabled display subsystem -> chain stays disabled. */ @@ -691,23 +774,108 @@ def main(): assert(f.display.iommu_count == 1 && f.display.iommus[0] == &f.disp0_dart); check_refs_zero(); - /* 9. Tree with no fixed dp-phy on any dcpext -> quiet no-op. */ + /* + * 9. No fixed dp-phy on any dcpext -> no chain, no error; the display + * subsystem has nothing to bind and goes. + */ init_fixture(&f); + f.disp0_dart.available = true; f.dcpext0.phy_names[0] = "typec1"; gate_t8132_run(); expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + assert(err_count == 0 && info_count == 1); + check_refs_zero(); + + /* 10. nomodeset -> no chain; drm/apple does not register, so neither does the display. */ + init_fixture(&f); + f.disp0_dart.available = true; + nomodeset = true; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* + * 11. No handover (Stage 2 published nothing for the dcpexts): no change + * from a tree without this gate. Nothing is enabled or disabled, disp0's + * iommus stay, and nothing is logged. + */ + init_fixture(&f); + no_handover(&f); + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); assert(err_count == 0 && info_count == 0); check_refs_zero(); - /* 10. nomodeset -> no-op. */ + /* 11b. The same with the J773g's DARTs, and under nomodeset. */ init_fixture(&f); + no_handover(&f); + j773g_darts(&f); + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); nomodeset = true; gate_t8132_run(); + expect_unchanged(&f, &snap); + check_refs_zero(); + + /* + * 12. The J773g on 27.2 with this tree: Stage 2 handed dcpext0 over and + * enabled the display subsystem and disp0's DART, but apple-dart keeps no + * locked roots of a T8132 DART. The chain stays off and the display goes, + * so the GPU starts on the boot framebuffer as without the handover. + */ + init_fixture(&f); + j773g_darts(&f); + f.disp0_dart.available = true; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + assert(err_count == 0); + check_refs_zero(); + + /* 13. Either DART of the chain alone not kept -> the same. */ + init_fixture(&f); + f.disp0_dart.available = true; + f.fw_dart.compatible = "apple,t8132-dart"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + init_fixture(&f); + f.disp0_dart.available = true; + f.disp_dart.compatible = "apple,t8132-dart"; + gate_t8132_run(); + expect_chain(&f, false); + expect_gpu_on_boot_framebuffer(&f); + check_refs_zero(); + + /* 14. Laptop: main DCP handed over on 27.2 -> its display subsystem and DART stay. */ + init_fixture(&f); + j773g_darts(&f); + set_v27_2(&f.main_dcp); + f.main_dcp.has_clock_ids = true; + f.main_dcp.available = true; + f.disp0_dart.available = true; + take_snapshot(&f, &snap); + gate_t8132_run(); + expect_unchanged(&f, &snap); + check_refs_zero(); + + /* 15. Headless, but the main DCP enabled: the display goes, disp0's DART (its piodma's) stays. */ + init_fixture(&f); + j773g_darts(&f); + f.main_dcp.available = true; + f.disp0_dart.available = true; + gate_t8132_run(); expect_chain(&f, false); + assert(!f.display.available && f.disp0_dart.available); check_refs_zero(); cleanup_applied(); puts("PASS T8132 fixed-DP display gate: phandle chain, replace vs append disp0 iommus, fail-closed controls"); + puts("PASS T8132 display gate: no handover or no kept DART roots boots as without the gate, GPU on the boot framebuffer"); return 0; } ''' From 2213f9815e3143a31323ba6deec9029cb003bc7f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 00:04:52 +1100 Subject: [PATCH 1428/1514] drm/asahi: drain only the G14 27.2 command the firmware stopped After a recovery round, the host waited for every command of the guilty packet to leave the queue within RECOVERY_DRAIN_MS. Only the command the snapshot named was stopped: the packet's later commands run normally. A hung client usually has several dispatches queued, and if one of them also runs past the drain budget, the round ended in "stopped work did not leave the queue" and failed every client, which is what the recovery is there to avoid. Wait for the stopped command only. The packet's later commands are already marked and are failed as they retire; if one of them hangs too, the firmware stops it in a round of its own. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index ac78695a87d755..0b9f120cc7def4 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -566,6 +566,9 @@ struct RenderFlight { struct Blamed { owner: crate::m3::m3_submit::Owner, stamps: [u32; 2], + /// The stopped compute command's queue ordinal: the drain waits for this command only. The + /// packet's later commands were not stopped and retire (failed) through the normal path. + stopped: Option, } struct State { @@ -1156,19 +1159,22 @@ impl Runtime { flight.doomed = Some(error); latch_guilty(&flight.packet, error); Blamed { owner: flight.packet.owner, - stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()] } + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()], + stopped: None } } Stopped::Compute(stamp) => { let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); - let Some(packet) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) - .map(|i| state.inflight[i].packet.clone()) else { return Err(EIO); }; + let Some((packet, stopped)) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| (state.inflight[i].packet.clone(), state.inflight[i].ordinal)) + else { return Err(EIO); }; self.reserve_kept(state, &packet)?; let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); for flight in state.inflight.iter_mut().filter(owned) { flight.doomed.get_or_insert(error); } latch_guilty(&packet, error); - Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()] } + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()], + stopped: Some(stopped) } } }; Ok(blamed) @@ -1187,16 +1193,17 @@ impl Runtime { work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); } - /// Whether every command marked by `blame` has left its queue. - fn doomed_retired(&self, state: &mut State) -> Result { + /// Whether the stopped work has left its queue: the render pair, or the compute command at + /// `stopped` (its packet's later commands run normally and are failed as they retire). + fn doomed_retired(&self, state: &mut State, stopped: Option) -> Result { if let Some(flight) = state.rendering.as_ref() { if flight.doomed.is_some() { return Ok(state.root.render_retired(TILER, flight.targets[TILER])? && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); } } - let Some(ordinal) = - state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal) + let Some(ordinal) = stopped.or_else(|| + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal)) else { return Ok(true); }; self.advance(state)?; Ok(state.retired_total >= ordinal) @@ -1335,7 +1342,7 @@ impl Runtime { let start = Instant::::now(); loop { let _ = state.root.drain(); - if self.doomed_retired(state)? { + if self.doomed_retired(state, blamed.stopped)? { state.recoveries += 1; // Work behind the stopped command waited out the recovery: restart its clocks. let now = Instant::now(); From fa824cfae0227f17d33e2ae151f0674f664f6d75 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 00:04:52 +1100 Subject: [PATCH 1429/1514] drm/asahi: forget G14 27.2 recovery rounds across a warm restart The recovery ledger keeps the last answered generation and refuses a round that repeats it. After a deep-sleep warm restart the firmware may count generations from its start again, so the first real round after wake could be refused with EPROTO and fail all work. No round can cross a sleep (sleep_prepare refuses while one is open), so start the ledger afresh once the firmware is back. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g14_v27_2.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index 0b9f120cc7def4..24a1b9c66e237c 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -1796,6 +1796,9 @@ impl Runtime { state.waiting_control = None; match restart { Ok(()) => { + // No round crosses a sleep (sleep_prepare refuses one), and the restarted + // firmware may count generations again from its start: forget old rounds. + state.ledger = g14_v27_2_abi::RecoveryLedger::default(); dev_info!(self.dev, "GPU firmware 27.2 back in {} us (commit idle={} {} us, pending={})\n", started.elapsed().as_micros_ceil(), commit.idle_ret, commit.idle_us, state.pending.len()); From da9a2c94b1ef3b24e66024d872c034e893500a5b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 22:59:22 +1100 Subject: [PATCH 1430/1514] drm/apple: watch the swaps of every external pipe An HDMI display behind a fixed port drops HPD while it wakes from standby after DPMS on. When that happens under a swap the firmware has accepted, the firmware never completes the swap. The swap watchdog retires such a present after a second and has the hotplug worker set the mode again, but it was only armed for Type-C outputs. On a fixed HDMI port the dropped present held the IOMFB queue until its ten second timeout. That timeout declares the coprocessor crashed, and dcp_crtc_mode_fixup() then refuses every mode, so the display stays dark until a reboot. A compositor that enables both outputs in one commit loses the other display as well. Arm the watchdog for every pipe without a built-in panel. The condition is the panel the hardware describes, so a Type-C route, a fixed HDMI port and any other external output are covered alike, and built-in panels keep their swaps unwatched as before. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp.c | 11 ++++- drivers/gpu/drm/apple/dcp_dropped_swap_test.c | 42 +++++++++++++++++++ .../drivers/gpu/apple-dcp/display.py | 10 ++++- 3 files changed, 60 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bd867d04bb072f..5e72a0dc79d9e6 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1736,7 +1736,16 @@ VISIBLE_IF_KUNIT void dcp_swap_watchdog(struct work_struct *work) void dcp_swap_watchdog_arm(struct apple_dcp *dcp) { - if (dcp_is_typec_output(dcp) || dcp_desktop_swap_watched(dcp)) { + /* + * Every external pipe can lose its sink under an accepted swap, not + * only a Type-C route: an HDMI display on a fixed port also drops HPD, + * for instance while it wakes from standby after DPMS on. Unwatched, + * the dropped present holds the IOMFB queue until its ten second + * timeout, which declares the coprocessor crashed, and the mode set + * that would bring the display back waits behind it. + */ + if (dcp_is_typec_output(dcp) || !dcp_has_panel(dcp) || + dcp_desktop_swap_watched(dcp)) { dcp->swap_watchdog_deadline = jiffies + msecs_to_jiffies(DCP_SWAP_WATCHDOG_MS); mod_delayed_work(system_dfl_wq, &dcp->swap_watchdog_wq, diff --git a/drivers/gpu/drm/apple/dcp_dropped_swap_test.c b/drivers/gpu/drm/apple/dcp_dropped_swap_test.c index dc5b145fab5285..473ca29bfaee4b 100644 --- a/drivers/gpu/drm/apple/dcp_dropped_swap_test.c +++ b/drivers/gpu/drm/apple/dcp_dropped_swap_test.c @@ -266,6 +266,46 @@ static void dropped_present_retired_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->mode_state.valid)); } +/* + * The same drop on an HDMI display behind a fixed port (no panel, no Type-C + * route): the J473's HDMI display drops HPD while it wakes from standby after + * DPMS on, under an accepted swap. The watchdog must retire that present too, + * instead of leaving it to the queue's ten second timeout, which declares the + * coprocessor crashed and refuses every later mode set. + */ +static void dropped_present_fixed_hdmi_test(struct kunit *test) +{ + struct dropped_test *t = dropped_test_external(test); + struct apple_dcp *dcp = &t->dcp; + + dcp->fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA; + KUNIT_ASSERT_FALSE(test, dcp_has_panel(dcp)); + + dropped_test_present(test, t, 0, &t->fb[1]); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&dcp->swap_watchdog_wq)); + KUNIT_EXPECT_EQ(test, iomfb_queue_settle(dcp, msecs_to_jiffies(2000)), 0); + KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->crashed)); + KUNIT_EXPECT_TRUE(test, t->present[0].released); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&dcp->iomfb.timeout)); + KUNIT_EXPECT_TRUE(test, dcp_present_was_retired_h17p(&dcp->present_state_h17p, + DROPPED_SWAP_ID)); + flush_delayed_work(&dcp->swap_watchdog_wq); + KUNIT_EXPECT_FALSE(test, READ_ONCE(dcp->mode_state.valid)); +} + +/* A built-in panel keeps its swaps unwatched, as before. */ +static void panel_swap_unwatched_test(struct kunit *test) +{ + struct dropped_test *t = dropped_test_external(test); + struct apple_dcp *dcp = &t->dcp; + + dcp->fixed_connector_type = DRM_MODE_CONNECTOR_eDP; + dcp->panel.width_mm = 300; + KUNIT_ASSERT_TRUE(test, dcp_has_panel(dcp)); + dcp_swap_watchdog_arm(dcp); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&dcp->swap_watchdog_wq)); +} + /* * The firmware might still read a dropped present: its framebuffers, and the * one it would have replaced, stay referenced until a later present @@ -546,6 +586,8 @@ static struct kunit_case dropped_swap_cases[] = { KUNIT_CASE(desktop_present_completion_test), KUNIT_CASE(takeover_adopt_watched_test), KUNIT_CASE(dropped_present_retired_test), + KUNIT_CASE(dropped_present_fixed_hdmi_test), + KUNIT_CASE(panel_swap_unwatched_test), KUNIT_CASE(dropped_present_buffers_test), KUNIT_CASE(completed_present_kept_test), KUNIT_CASE(stop_deferred_test), diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py index 66604bfdb7b3f7..e385105e186f53 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/display.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/display.py @@ -475,7 +475,7 @@ def watchdog(root): struct work_struct {unsigned unused;}; struct delayed_work {struct work_struct work;}; struct apple_dcp { - int fw_compat;bool vrr_enabled,typec; + int fw_compat;bool vrr_enabled,typec,panel; struct {u32 present_id;bool present_pending,vrr_failed,takeover_adopted,mode_live;} *desktop; struct {bool valid;} mode_state; struct delayed_work swap_watchdog_wq; @@ -494,12 +494,13 @@ def watchdog(root): static void dcp_drm_crtc_vblank(void *c) {vblanks++;} static void dcp_queue_hotplug(void *c) {hotplugs++;} static bool dcp_is_typec_output(struct apple_dcp *d) {return d->typec;} +static bool dcp_has_panel(struct apple_dcp *d) {return d->panel;} static void mod_delayed_work(void *q,struct delayed_work *w,unsigned long delay) {assert(delay==1000);scheduled++;} static void cancel_delayed_work(struct delayed_work *w) {cancelled++;} ''' + definitions + '\n' + helpers + '\n' + production + r''' int main(void) { - struct apple_dcp d={.fw_compat=5,.vrr_enabled=true,.mode_state={true},.connector=(void *)1}; + struct apple_dcp d={.fw_compat=5,.vrr_enabled=true,.panel=true,.mode_state={true},.connector=(void *)1}; __typeof__(*d.desktop) state={.present_id=42,.present_pending=true};d.desktop=&state; dcp_swap_watchdog_arm(&d);assert(scheduled==1 && d.swap_watchdog_deadline==1000); jiffies=999;dcp_swap_watchdog(&d.swap_watchdog_wq.work); @@ -535,6 +536,11 @@ def watchdog(root): jiffies=d.swap_watchdog_deadline;unsigned hp=hotplugs; dcp_swap_watchdog(&d.swap_watchdog_wq.work); assert(!state.takeover_adopted && !state.mode_live && !d.mode_state.valid && hotplugs==hp+1); + /* Any external pipe is watched, not only Type-C: a fixed HDMI port + * (no panel, no Type-C route, no watched desktop swap) arms too. */ + d.fw_compat=1;d.typec=false;d.vrr_enabled=false;state.takeover_adopted=false; + before=scheduled;dcp_swap_watchdog_arm(&d);assert(scheduled==before); + d.panel=false;dcp_swap_watchdog_arm(&d);assert(scheduled==before+1); return 0; } ''' From 83e327e49dad438f60b9435bf51fe1da4b58cff5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 01:06:39 +1100 Subject: [PATCH 1431/1514] soc: apple: sep: declare the HDCP 2.2 transmitter service interface Declare the in-kernel API through which the display driver drives HDCP 2.2 transmitter authentication on the Apple SEP (endpoint 0x0e). Only clear-text protocol fields (r_tx, cert_rx, r_rx, Ekpub(km)/stored km, H', pairing Ekh(km), r_n, L', Edkey(ks), r_iv, ReceiverID list, V'/V, stream type, M') cross this boundary; km, ks, kd and device keys never leave the enclave. Provide inline -ENODEV/false/no-op stubs when CONFIG_APPLE_SEP_HDCP_INTERFACE is disabled so display driver builds without CONFIG_APPLE_SEP link cleanly. Signed-off-by: Ryan Murray --- include/linux/apple-sep-hdcp.h | 221 +++++++++++++++++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 include/linux/apple-sep-hdcp.h diff --git a/include/linux/apple-sep-hdcp.h b/include/linux/apple-sep-hdcp.h new file mode 100644 index 00000000000000..e01766d858ffb1 --- /dev/null +++ b/include/linux/apple-sep-hdcp.h @@ -0,0 +1,221 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* + * Apple SEP HDCP 2.2 transmitter service, for the display driver. + * + * The SEP holds the transmitter's device keys and does every HDCP 2.2 + * cryptographic step itself. The display driver builds the protocol + * messages from the fields below and relays them to the receiver through + * DCP. Only fields that the HDCP 2.2 protocol sends in the clear cross this + * interface. No call returns or takes km, ks, kd or a device key. + * + * Every call runs on one HDCP interface channel of the SEP (the display + * node's "apple,hdcp-channels" value). A session is opened with + * apple_sep_hdcp_open() and ends with apple_sep_hdcp_close(). The SEP + * driver enforces the protocol order per channel, so a call out of order + * fails with -EPROTO before the SEP sees it. Bounded verification retries + * permitted by HDCP 2.2 (locality check L' and repeater stream M') leave + * the session open for retry while attempts remain; any other SEP error + * leaves the session failed until it is closed. If the SEP does not answer, + * every channel fails with -EIO until the SEP is reset. + * + * All calls may sleep. They return 0 or a negative errno: -ENODEV when no + * SEP driver is bound or the endpoint is absent, -EAGAIN when the SEP is + * still finishing bring-up or transiently gated for system sleep, -EINVAL + * for a bad argument, -EPROTO for a call out of order, -EACCES when the + * SEP rejects a verification (certificate, H', L', ReceiverID list, V', M'), + * -EIO when the SEP fails or does not answer. + */ +#ifndef _LINUX_APPLE_SEP_HDCP_H +#define _LINUX_APPLE_SEP_HDCP_H + +#include +#include +#include + +#define APPLE_SEP_HDCP_RTX_LEN 8 +#define APPLE_SEP_HDCP_RRX_LEN 8 +#define APPLE_SEP_HDCP_CAPS_LEN 3 +#define APPLE_SEP_HDCP_CERT_LEN 522 +#define APPLE_SEP_HDCP_EKPUB_KM_LEN 128 +#define APPLE_SEP_HDCP_EKH_KM_LEN 16 +#define APPLE_SEP_HDCP_M_LEN 16 +#define APPLE_SEP_HDCP_H_PRIME_LEN 32 +#define APPLE_SEP_HDCP_RN_LEN 8 +#define APPLE_SEP_HDCP_L_PRIME_LEN 32 +#define APPLE_SEP_HDCP_EDKEY_KS_LEN 16 +#define APPLE_SEP_HDCP_RIV_LEN 8 +#define APPLE_SEP_HDCP_RXINFO_LEN 2 +#define APPLE_SEP_HDCP_SEQ_NUM_LEN 3 +#define APPLE_SEP_HDCP_RECEIVER_ID_LEN 5 +#define APPLE_SEP_HDCP_MAX_DEVICES 31 +#define APPLE_SEP_HDCP_V_PRIME_LEN 16 +#define APPLE_SEP_HDCP_V_LEN 32 +#define APPLE_SEP_HDCP_M_PRIME_LEN 32 + +/* The km the SEP has stored for this receiver, as AKE_Stored_km carries it. */ +struct apple_sep_hdcp_stored_km { + u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]; + u8 m[APPLE_SEP_HDCP_M_LEN]; +}; + +#if IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) + +/* Session start: the SEP draws r_tx for AKE_Init. */ +int apple_sep_hdcp_open(u32 channel, u8 rtx[APPLE_SEP_HDCP_RTX_LEN]); + +/* + * AKE_Send_Cert and r_rx. The SEP checks the certificate signature. + * On return *stored is true and @km holds AKE_Stored_km's body when the SEP + * has paired with this receiver before; otherwise @ekpub_km holds + * AKE_No_Stored_km's body. + */ +int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]); + +/* AKE_Send_H_prime: the SEP checks H' over r_tx, RxCaps and TxCaps. */ +int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]); + +/* AKE_Send_Pairing_Info (first pairing only): the SEP stores km. */ +int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]); + +/* LC_Init: r_n from the SEP. */ +int apple_sep_hdcp_lc_init(u32 channel, u8 rn[APPLE_SEP_HDCP_RN_LEN]); + +/* LC_Send_L_prime: the SEP checks L'. */ +int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]); + +/* SKE_Send_Eks: the SEP returns Edkey(ks) and r_iv for the receiver. */ +int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]); + +/* + * RepeaterAuth_Send_ReceiverID_List: @ids holds @count Receiver IDs. The SEP + * checks V' and returns V; the transmitter sends its least significant + * 128 bits in RepeaterAuth_Send_Ack. + */ +int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]); + +/* + * RepeaterAuth_Stream_Manage / Stream_Ready for one stream: the SEP checks + * M' over StreamID_Type and seq_num_M. @type is 0 or 1. + */ +int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]); + +/* Authentication complete. The caller waits 200 ms before encryption. */ +int apple_sep_hdcp_finish(u32 channel); + +/* Link encryption on or off for this channel. */ +int apple_sep_hdcp_set_encryption(u32 channel, bool on); + +/* Ends the session from any state; safe to call when none is open. */ +void apple_sep_hdcp_close(u32 channel); + +/* True when a SEP driver with the HDCP service is bound and ready. */ +bool apple_sep_hdcp_available(void); + +#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */ + +static inline int apple_sep_hdcp_open(u32 channel, + u8 rtx[APPLE_SEP_HDCP_RTX_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, + struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_lc_init(u32 channel, + u8 rn[APPLE_SEP_HDCP_RN_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, + unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, + u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_finish(u32 channel) +{ + return -ENODEV; +} + +static inline int apple_sep_hdcp_set_encryption(u32 channel, bool on) +{ + return -ENODEV; +} + +static inline void apple_sep_hdcp_close(u32 channel) +{ +} + +static inline bool apple_sep_hdcp_available(void) +{ + return false; +} + +#endif /* IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */ + +#endif /* _LINUX_APPLE_SEP_HDCP_H */ From 8c39c0d0010fcfa537aa679a0169a26cfd687afe Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 01:07:06 +1100 Subject: [PATCH 1432/1514] soc: apple: sep: add the HDCP 2.2 transmitter client (ep 0x0e) Implement the Apple SEP HDCP 2.2 transmitter endpoint (0x0e, 'hdcp') in drivers/soc/apple/hdcp.rs and expose it to the display driver through the built-in C shim (hdcp_shim.c) backing include/linux/apple-sep-hdcp.h. - Validate the endpoint's discovery descriptor and OOL layout config word before use; allocate persistent 16 KiB inbound/outbound OOL buffers and retain registered buffers on remove(). - Enumerate the enclave's HDCP interface channels at runtime with commands 0x27 and 0x28 rather than hard-coding a per-SoC channel count. - Enforce the closed 26-command wire table and per-channel HDCP 2.2 state machine (first-time pairing, stored km, bounded locality-check and repeater stream-manage retries, repeater ReceiverID list and V'/V, finish, encryption on/off, teardown from any open state). - Synchronise outbound OOL reads with repoison/await-written, scrub buffers after each exchange, return -EAGAIN while SEP bring-up or sleep gating is active, and quarantine the endpoint until reset if a command goes unanswered. - Add Rust KUnit suite apple_sep_hdcp (13 cases), C KUnit suite apple_sep_hdcp_shim (6 cases), and host check test_hdcp_client.py wired into sep-source.yml. Signed-off-by: Ryan Murray --- .github/workflows/sep-source.yml | 3 + drivers/soc/apple/Kconfig | 7 + drivers/soc/apple/Makefile | 1 + drivers/soc/apple/hdcp.rs | 1914 ++++++++++++++++++++ drivers/soc/apple/hdcp_shim.c | 297 +++ drivers/soc/apple/hdcp_shim_test.c | 217 +++ drivers/soc/apple/sep.rs | 41 + drivers/soc/apple/shim.h | 27 + tools/aurora-sep/tests/test_hdcp_client.py | 54 + 9 files changed, 2561 insertions(+) create mode 100644 drivers/soc/apple/hdcp.rs create mode 100644 drivers/soc/apple/hdcp_shim.c create mode 100644 drivers/soc/apple/hdcp_shim_test.c create mode 100644 tools/aurora-sep/tests/test_hdcp_client.py diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index fd49f4b11c547c..92a1408c846a97 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -8,6 +8,7 @@ on: - 'tools/aurora-bindgen/**' - 'drivers/soc/apple/**' - 'drivers/pmdomain/apple/pmp-report.c' + - 'include/linux/apple-sep-hdcp.h' - 'include/uapi/linux/apple-sep.h' - 'tools/aurora-sep/**' - 'Kconfig' @@ -36,6 +37,7 @@ jobs: sparse-checkout-cone-mode: false sparse-checkout: | drivers/soc/apple/** + include/linux/apple-sep-hdcp.h include/uapi/linux/apple-sep.h tools/aurora-sep/** - name: Check biometric ioctl ABI sizes @@ -72,6 +74,7 @@ jobs: python3 -m unittest tools/aurora-sep/tests/test_policy_window.py -v python3 -m unittest tools/aurora-sep/tests/test_log_ratelimit.py -v python3 -m unittest tools/aurora-sep/tests/test_key_context_cleanup.py -v + python3 -m unittest tools/aurora-sep/tests/test_hdcp_client.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_packaging.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_sep_writes_always_on.py -v python3 -m unittest discover -s tools/aurora-sep/tests -p test_boot_locks.py -v diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index 2d1e29d1c7c734..00c137d065030e 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -318,6 +318,12 @@ config APPLE_AOP config APPLE_SEP_FV_INTERFACE bool +config APPLE_SEP_HDCP_INTERFACE + bool + help + The kernel interface through which the display driver runs HDCP 2.2 + authentication on the SEP. Selected by the SEP driver. + config APPLE_SEP tristate "Apple SEP (Secure Enclave Processor)" default m if ARCH_APPLE @@ -338,6 +344,7 @@ config APPLE_SEP select CRYPTO_GCM select CRYPTO_ECDH select APPLE_SEP_FV_INTERFACE + select APPLE_SEP_HDCP_INTERFACE select RUST_FW_LOADER_ABSTRACTIONS help Driver for the Apple SEP (Secure Enclave Processor) on Apple silicon. diff --git a/drivers/soc/apple/Makefile b/drivers/soc/apple/Makefile index b742973807afb1..216234e3aba5da 100644 --- a/drivers/soc/apple/Makefile +++ b/drivers/soc/apple/Makefile @@ -56,6 +56,7 @@ obj-$(CONFIG_APPLE_TUNABLE_KUNIT_TEST) += tunable-test.o obj-$(CONFIG_APPLE_AOP) += aop.o obj-$(CONFIG_APPLE_SEP_FV_INTERFACE) += fv_shim.o +obj-$(CONFIG_APPLE_SEP_HDCP_INTERFACE) += hdcp_shim.o obj-$(CONFIG_APPLE_SEP) += apple-sep.o apple-sep-y := sep.o hwrng_shim.o store_shim.o bio_shim.o sha_shim.o \ diff --git a/drivers/soc/apple/hdcp.rs b/drivers/soc/apple/hdcp.rs new file mode 100644 index 00000000000000..a6b67f19a43530 --- /dev/null +++ b/drivers/soc/apple/hdcp.rs @@ -0,0 +1,1914 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +// Copyright 2026 Ryan Murray + +//! The enclave's HDCP endpoint (`0x0e`): the HDCP 2.2 transmitter service. +//! +//! The AP runs the HDCP 2.2 transmitter protocol; the enclave holds the +//! transmitter's secrets and does every cryptographic step. The host gives +//! the enclave the fields the receiver sent and gets back the fields it must +//! send, one command at a time. Only fields that the protocol sends in the +//! clear cross the endpoint; km, ks and the device keys never do. +//! +//! ```text +//! TX 0x0000_0000_0000_270e query interface count +//! RX 0x0000_0009_0000_000e status 0, 9 interfaces +//! TX 0x0201_0000_0700_010e command 0x01, slot 7, argument 0x0201_0000 +//! RX 0x0000_0000_0000_000e status 0, no output +//! TX 0x0000_020a_0700_080e command 0x08, slot 7, 522 input bytes out of line +//! RX 0x0000_0000_0020_000e status 0, 32 output bytes out of line +//! ``` +//! +//! - Request: byte 1 is the command, byte 3 the slot (the HDCP interface +//! channel the session runs on). The upper word is the input length for a +//! command that takes input, otherwise its argument. +//! - Reply: byte 1 is the status, byte 2 the output length (except for +//! interface-count query `0x27`, whose upper word carries the count). A +//! reply carries no command or tag, so one request may be in flight on the +//! endpoint. Its second word is stale memory and is never read. +//! - Input is one flat segment at offset 0 of a persistent 16 KiB buffer; +//! output is at offset 0 of a second one. Both are registered once. +//! - Every input is a protocol field, or fields concatenated in the order the +//! HDCP 2.2 specification hashes them (H', V', M'). +//! +//! The command set is closed ([`SPECS`]) and a session sends it in protocol +//! order only ([`Session`]); anything else is refused before it reaches the +//! mailbox. The display driver reaches this through `hdcp_shim.c`. + +use super::*; +use crate::proto::*; +use kernel::prelude::*; +use kernel::soc::apple::mailbox::Message; + +pub(crate) const EP_HDCP: u8 = 0x0e; + +/// The endpoint's discovery name. +pub(crate) const HDCP_NAME: u32 = u32::from_be_bytes(*b"hdcp"); + +/// One enclave page, and each out-of-line buffer size. +pub(crate) const SEP_PAGE: usize = 0x4000; +pub(crate) const OOL_SIZE_HDCP: usize = SEP_PAGE; + +/// Maximum HDCP interface channels tracked per SEP; the actual count is +/// queried at runtime with command `0x27` (for example 9 on T8112, 15 on +/// T6040). +pub(crate) const MAX_CHANNELS: usize = 32; + +/// How long one command may take. The slowest, the RSA encryption of km, +/// takes about 90 ms. +pub(crate) const HDCP_TIMEOUT_MS: u32 = 1000; + +/// Locality check attempts per session (HDCP 2.2: at most 1024). +pub(crate) const LC_MAX_TRIES: u16 = 1024; + +/// Repeater stream-manage attempts per session (HDCP 2.2: initial + 1 retry). +pub(crate) const STREAM_MAX_TRIES: u8 = 2; + +/// Reply status of the stored-km query when no km is stored for the receiver. +pub(crate) const STATUS_NO_STORED_KM: u8 = 0x08; + +/// The arguments that ride in the upper word of a command without input. +/// Observed values; their byte meanings are not established. +pub(crate) const OPEN_ARG: u32 = (0x02 << 24) | (0x01 << 16); +pub(crate) const PREPARE_ARG: u32 = 0x02 << 16; +pub(crate) const FINISH_ARG: u32 = 0x01 << 16; +/// Command 0x21's argument: bit 16 set as encryption is turned on, clear as +/// it is turned off. +pub(crate) const ENCRYPTION_ON: u32 = 1 << 16; + +/// Per-channel descriptor size returned by command `0x28`. +pub(crate) const CHANNEL_INFO_LEN: usize = 8; + +/// HDCP 2.2 field sizes (public specification). +pub(crate) const RTX_LEN: usize = 8; +pub(crate) const RRX_LEN: usize = 8; +pub(crate) const RN_LEN: usize = 8; +pub(crate) const RIV_LEN: usize = 8; +pub(crate) const CERT_LEN: usize = 522; +pub(crate) const CAPS_LEN: usize = 3; +pub(crate) const H_PRIME_LEN: usize = 32; +pub(crate) const L_PRIME_LEN: usize = 32; +/// Ekh(km) and m, the body of AKE_Stored_km. +pub(crate) const STORED_KM_LEN: usize = 32; +pub(crate) const EKPUB_KM_LEN: usize = 128; +pub(crate) const EKH_KM_LEN: usize = 16; +pub(crate) const EKS_LEN: usize = 16; +pub(crate) const RECEIVER_ID_LEN: usize = 5; +pub(crate) const MAX_DEVICES: usize = 31; +pub(crate) const RXINFO_LEN: usize = 2; +pub(crate) const SEQ_NUM_LEN: usize = 3; +pub(crate) const V_PRIME_LEN: usize = 16; +pub(crate) const V_LEN: usize = 32; +pub(crate) const M_PRIME_LEN: usize = 32; +/// r_tx, then RxCaps, then TxCaps. +pub(crate) const H_CONTEXT_LEN: usize = RTX_LEN + 2 * CAPS_LEN; +/// Receiver ID list, RxInfo, seq_num_V. +pub(crate) const LIST_MIN: usize = RECEIVER_ID_LEN + RXINFO_LEN + SEQ_NUM_LEN; +pub(crate) const LIST_MAX: usize = MAX_DEVICES * RECEIVER_ID_LEN + RXINFO_LEN + SEQ_NUM_LEN; +/// StreamID, Type, seq_num_M. +pub(crate) const STREAM_LEN: usize = 2 + SEQ_NUM_LEN; + +/// Validates the endpoint's discovery buffer-layout word (min/max pages each +/// way, MSB to LSB: send_min, recv_min, send_max, recv_max). One page each +/// way must be permitted by the advertised range. +pub(crate) fn ool_sizes(word: u32) -> Option<(usize, usize)> { + let send_min = (word >> 24) as u8; + let recv_min = (word >> 16) as u8; + let send_max = (word >> 8) as u8; + let recv_max = word as u8; + if send_min == 0 || recv_min == 0 || send_min > 1 || recv_min > 1 { + return None; + } + if send_max < 1 || recv_max < 1 || send_min > send_max || recv_min > recv_max { + return None; + } + Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP)) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Command { + QueryChannels, + GetChannelInfo, + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + GetEkpubKm, + PutHContext, + PutHPrime, + PutPairing, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + PutReceiverList, + PutVPrime, + GetV, + PutStream, + PutMPrime, + Finish, + SetEncryption, + Close, +} + +/// What a command looks like on the wire. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Spec { + pub(crate) command: Command, + pub(crate) id: u8, + /// Input bytes out of line (the upper word then carries the length). + /// A command with a list takes any length from `input` to `input_max` + /// in whole entries; for the others the two are equal. + pub(crate) input: usize, + pub(crate) input_max: usize, + /// Output bytes out of line; a successful reply's byte 2 must say this. + pub(crate) output: usize, + /// The enclave checks something the receiver sent: a refusal means the + /// receiver failed authentication, not that the enclave failed. + pub(crate) verifies: bool, +} + +const fn spec(command: Command, id: u8, input: usize, output: usize) -> Spec { + Spec { + command, + id, + input, + input_max: input, + output, + verifies: false, + } +} + +const fn verify(command: Command, id: u8, input: usize) -> Spec { + Spec { + command, + id, + input, + input_max: input, + output: 0, + verifies: true, + } +} + +/// Every command the driver may send. +pub(crate) const SPECS: [Spec; 26] = [ + spec(Command::QueryChannels, 0x27, 0, 0), + spec(Command::GetChannelInfo, 0x28, 0, CHANNEL_INFO_LEN), + spec(Command::Open, 0x01, 0, 0), + spec(Command::Prepare, 0x26, 0, 0), + spec(Command::Start, 0x22, 0, 0), + spec(Command::GetRtx, 0x04, 0, RTX_LEN), + verify(Command::PutCert, 0x08, CERT_LEN), + spec(Command::PutRrx, 0x05, RRX_LEN, 0), + spec(Command::QueryStoredKm, 0x09, 0, STORED_KM_LEN), + spec(Command::GetEkpubKm, 0x0c, 0, EKPUB_KM_LEN), + spec(Command::PutHContext, 0x0e, H_CONTEXT_LEN, 0), + verify(Command::PutHPrime, 0x0f, H_PRIME_LEN), + spec(Command::PutPairing, 0x16, EKH_KM_LEN, 0), + spec(Command::GetRn, 0x18, 0, RN_LEN), + spec(Command::LcStart, 0x1a, 0, 0), + verify(Command::PutLPrime, 0x1c, L_PRIME_LEN), + spec(Command::GetEks, 0x10, 0, EKS_LEN), + spec(Command::GetRiv, 0x12, 0, RIV_LEN), + Spec { + command: Command::PutReceiverList, + id: 0x1d, + input: LIST_MIN, + input_max: LIST_MAX, + output: 0, + verifies: true, + }, + verify(Command::PutVPrime, 0x1f, V_PRIME_LEN), + spec(Command::GetV, 0x1e, 0, V_LEN), + spec(Command::PutStream, 0x23, STREAM_LEN, 0), + verify(Command::PutMPrime, 0x25, M_PRIME_LEN), + spec(Command::Finish, 0x20, 0, 0), + spec(Command::SetEncryption, 0x21, 0, 0), + spec(Command::Close, 0x02, 0, 0), +]; + +static_assert!(LIST_MAX <= OOL_SIZE_HDCP && CERT_LEN <= OOL_SIZE_HDCP); +static_assert!(EKPUB_KM_LEN <= u8::MAX as usize); +static_assert!(MAX_CHANNELS <= u8::MAX as usize); + +pub(crate) fn spec_of(command: Command) -> Spec { + let mut i = 0; + while i < SPECS.len() { + if SPECS[i].command == command { + return SPECS[i]; + } + i += 1; + } + unreachable!() +} + +/// The request word: command, slot and the upper word (input length or +/// argument). +pub(crate) const fn request_word(id: u8, slot: u8, upper: u32) -> Message { + Message { + msg0: (EP_HDCP as u64) + | ((id as u64) << MSG_TAG_SHIFT) + | ((slot as u64) << MSG_PARAM_SHIFT) + | ((upper as u64) << MSG_DATA_SHIFT), + msg1: 0, + } +} + +fn input_len_ok(s: &Spec, len: usize) -> bool { + if s.input == s.input_max { + return len == s.input; + } + // A list: whole Receiver IDs ahead of the fixed fields. + len >= s.input && len <= s.input_max && (len - s.input) % RECEIVER_ID_LEN == 0 +} + +/// Builds the request for `command` on `slot`. `arg` is used only by commands +/// without input, `input_len` only by those with it, and must fit the spec. +pub(crate) fn request(command: Command, slot: u8, arg: u32, input_len: usize) -> Result { + let s = spec_of(command); + if usize::from(slot) >= MAX_CHANNELS { + return Err(EINVAL); + } + if command == Command::QueryChannels && slot != 0 { + return Err(EINVAL); + } + let upper = if s.input != 0 { + if arg != 0 || !input_len_ok(&s, input_len) { + return Err(EINVAL); + } + input_len as u32 + } else { + if input_len != 0 { + return Err(EINVAL); + } + let allowed = match command { + Command::Open => arg == OPEN_ARG, + Command::Prepare => arg == PREPARE_ARG, + Command::Finish => arg == FINISH_ARG, + Command::SetEncryption => arg == 0 || arg == ENCRYPTION_ON, + _ => arg == 0, + }; + if !allowed { + return Err(EINVAL); + } + arg + }; + Ok(request_word(s.id, slot, upper)) +} + +/// What a reply says about the command in flight. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Outcome { + /// Status 0, with this many output bytes (the expected count). + Done(usize), + /// Status 0 for `QueryChannels`: the enclave offers this many channels. + ChannelCount(u8), + /// The stored-km query found no km for this receiver: pair first. + NotStored, + /// The enclave refused the command with this status. + Refused(u8), + /// Not a reply this command gets. + Malformed, + /// No answer in time: the endpoint is quarantined until the driver + /// rebinds, since a late reply would be taken for the next command's. + NoReply, +} + +/// Judges a reply to `command` by its first word only. +pub(crate) fn check_reply(command: Command, msg: &Message) -> Outcome { + let f = decode(msg); + let s = spec_of(command); + if f.ep != EP_HDCP || f.param != 0 { + return Outcome::Malformed; + } + if command == Command::QueryChannels { + return match f.tag { + 0 if f.ty == 0 && f.data_lo >= 1 && (f.data_lo as usize) <= MAX_CHANNELS => { + Outcome::ChannelCount(f.data_lo as u8) + } + 0 => Outcome::Malformed, + status => Outcome::Refused(status), + }; + } + if f.data_lo != 0 { + return Outcome::Malformed; + } + match f.tag { + 0 if usize::from(f.ty) == s.output => Outcome::Done(s.output), + 0 => Outcome::Malformed, + STATUS_NO_STORED_KM if command == Command::QueryStoredKm => Outcome::NotStored, + status => Outcome::Refused(status), + } +} + +/// The errno a failed command reports to the display driver. +pub(crate) fn errno(command: Command, outcome: Outcome) -> Option { + match outcome { + Outcome::Done(_) | Outcome::ChannelCount(_) | Outcome::NotStored => None, + Outcome::Refused(_) if spec_of(command).verifies => Some(EACCES), + _ => Some(EIO), + } +} + +/// One session on one slot: which command may go next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Session { + last: Option, + open: bool, + /// The stored-km query's answer, once asked. + stored: Option, + encrypting: bool, + failed: bool, + lc_tries: u16, + stream_tries: u8, + /// Set when the previous L' or M' verification was refused while retries + /// remain; allows only the corresponding retry (or teardown). + lc_retry: bool, + stream_retry: bool, + /// r_tx of this session, for the H' context. + pub(crate) rtx: [u8; RTX_LEN], +} + +impl Session { + pub(crate) const fn new() -> Session { + Session { + last: None, + open: false, + stored: None, + encrypting: false, + failed: false, + lc_tries: 0, + stream_tries: 0, + lc_retry: false, + stream_retry: false, + rtx: [0; RTX_LEN], + } + } + + /// The protocol order: `next` may follow `last`. + fn follows(&self, last: Command, next: Command) -> bool { + use Command::*; + if self.lc_retry { + return next == GetRn && self.lc_tries < LC_MAX_TRIES; + } + if self.stream_retry { + return next == PutStream && self.stream_tries < STREAM_MAX_TRIES; + } + let stored = self.stored == Some(true); + let fresh = self.stored == Some(false); + matches!( + (last, next), + (Open, Prepare) + | (Prepare, Start) + | (Start, GetRtx) + | (GetRtx, PutCert) + | (PutCert, PutRrx) + | (PutRrx, QueryStoredKm) + | (GetEkpubKm, PutHContext) + | (PutHContext, PutHPrime) + | (PutPairing, GetRn) + | (GetRn, LcStart) + | (LcStart, PutLPrime) + | (PutLPrime, GetEks) + | (GetEks, GetRiv) + | (GetRiv, PutReceiverList) + | (GetRiv, Finish) + | (PutReceiverList, PutVPrime) + | (PutVPrime, GetV) + | (GetV, PutStream) + | (PutStream, PutMPrime) + | (PutMPrime, Finish) + ) || match (last, next) { + (QueryStoredKm, GetEkpubKm) => fresh, + (QueryStoredKm, PutHContext) => stored, + (PutHPrime, PutPairing) => fresh, + (PutHPrime, GetRn) => stored, + // The receiver missed the locality check: try again with a new r_n. + (GetRn, GetRn) => self.lc_tries < LC_MAX_TRIES, + (Finish, SetEncryption) => true, + _ => false, + } + } + + /// Whether `command` may be sent now. + pub(crate) fn allows(&self, command: Command, arg: u32) -> bool { + if matches!(command, Command::QueryChannels | Command::GetChannelInfo) { + return false; + } + if !self.open { + return command == Command::Open; + } + match command { + Command::Open => false, + // Teardown: encryption off, then close, from any open state. + Command::SetEncryption if arg == 0 => true, + Command::Close => !self.encrypting, + _ if self.failed || self.encrypting => false, + Command::SetEncryption if arg != ENCRYPTION_ON => false, + _ => self.last.is_some_and(|last| self.follows(last, command)), + } + } + + /// Records the outcome of a command [`Session::allows`] let through; + /// `false` when the session cannot advance on this command. Anything other + /// than a bounded LC/stream verification retry fails the session so only + /// teardown is allowed after it. + pub(crate) fn record(&mut self, command: Command, arg: u32, outcome: Outcome) -> bool { + match outcome { + Outcome::Done(_) => { + if command == Command::QueryStoredKm { + self.stored = Some(true); + } + } + Outcome::NotStored if command == Command::QueryStoredKm => { + self.stored = Some(false); + } + Outcome::Refused(_) + if command == Command::PutLPrime && self.lc_tries < LC_MAX_TRIES => + { + self.lc_retry = true; + self.last = Some(command); + return false; + } + Outcome::Refused(_) + if command == Command::PutMPrime && self.stream_tries < STREAM_MAX_TRIES => + { + self.stream_retry = true; + self.last = Some(command); + return false; + } + _ => { + if command == Command::Close { + // The enclave refused to close, or never answered: + // nothing more goes to this slot from this session. + *self = Session::new(); + return false; + } + self.failed = true; + self.encrypting = false; + self.lc_retry = false; + self.stream_retry = false; + return false; + } + } + self.lc_retry = false; + self.stream_retry = false; + match command { + Command::Close => { + *self = Session::new(); + return true; + } + Command::Open => self.open = true, + Command::SetEncryption if arg == 0 => { + // No way back to encryption without a new session. + self.encrypting = false; + self.failed = true; + } + Command::SetEncryption => self.encrypting = true, + Command::GetRn => self.lc_tries += 1, + Command::PutStream => self.stream_tries += 1, + _ => {} + } + self.last = Some(command); + true + } + + /// Encryption is on: every step acknowledged, in order. + pub(crate) fn encrypting(&self) -> bool { + self.encrypting + } + + pub(crate) fn is_open(&self) -> bool { + self.open + } +} + +/// The endpoint: probed channel count, a session per slot, and whether it is +/// quarantined. +pub(crate) struct State { + pub(crate) channel_count: Option, + pub(crate) sessions: [Session; MAX_CHANNELS], + pub(crate) quarantined: bool, +} + +impl State { + pub(crate) const fn new() -> State { + State { + channel_count: None, + sessions: [Session::new(); MAX_CHANNELS], + quarantined: false, + } + } + + /// Channels known to the enclave once enumerated. + pub(crate) fn channels(&self) -> usize { + self.channel_count.map_or(0, usize::from) + } +} + +/// The single exchange the endpoint can have in flight. +pub(crate) struct Exchange { + waiting: bool, + generation: u64, + reply: Option, +} + +impl Exchange { + pub(crate) const fn new() -> Exchange { + Exchange { + waiting: false, + generation: 0, + reply: None, + } + } + + pub(crate) fn begin(&mut self) -> u64 { + self.generation = self.generation.wrapping_add(1); + self.waiting = true; + self.reply = None; + self.generation + } + + /// Takes `msg` as the answer if an exchange waits and has none yet. + pub(crate) fn answer(&mut self, msg: Message) -> bool { + if !self.waiting || self.reply.is_some() { + return false; + } + self.reply = Some(msg); + true + } + + pub(crate) fn take(&mut self) -> Option { + let reply = self.reply.take(); + if reply.is_some() { + self.waiting = false; + } + reply + } + + pub(crate) fn end(&mut self) { + self.waiting = false; + self.reply = None; + } +} + +/// The steps the display driver asks for (`enum sep_hdcp_step` in shim.h). +/// Each is a fixed run of commands; inputs and outputs are flat. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u32)] +pub(crate) enum Step { + /// out: r_tx. + Open = 0, + /// in: cert, r_rx. out: 1 + Ekh(km) + m (stored), or 0 + Ekpub(km). + AkeCert = 1, + /// in: RxCaps, TxCaps, H'. + HPrime = 2, + /// in: Ekh(km). + Pairing = 3, + /// out: r_n. + LcInit = 4, + /// in: L'. + LPrime = 5, + /// out: Edkey(ks), r_iv. + Ske = 6, + /// in: Receiver IDs, RxInfo, seq_num_V, V'. out: V. + ReceiverList = 7, + /// in: StreamID, Type, seq_num_M, M'. + Stream = 8, + Finish = 9, + EncryptionOn = 10, + EncryptionOff = 11, +} + +pub(crate) const AKE_CERT_IN: usize = CERT_LEN + RRX_LEN; +pub(crate) const AKE_CERT_OUT: usize = 1 + EKPUB_KM_LEN; +pub(crate) const H_PRIME_IN: usize = 2 * CAPS_LEN + H_PRIME_LEN; +pub(crate) const SKE_OUT: usize = EKS_LEN + RIV_LEN; +pub(crate) const STREAM_IN: usize = STREAM_LEN + M_PRIME_LEN; + +impl Step { + fn from_raw(raw: u32) -> Option { + Some(match raw { + 0 => Step::Open, + 1 => Step::AkeCert, + 2 => Step::HPrime, + 3 => Step::Pairing, + 4 => Step::LcInit, + 5 => Step::LPrime, + 6 => Step::Ske, + 7 => Step::ReceiverList, + 8 => Step::Stream, + 9 => Step::Finish, + 10 => Step::EncryptionOn, + 11 => Step::EncryptionOff, + _ => return None, + }) + } + + /// Whether `inp` and `out` have this step's sizes. + pub(crate) fn sizes_ok(self, inp: usize, out: usize) -> bool { + match self { + Step::Open => inp == 0 && out == RTX_LEN, + Step::AkeCert => inp == AKE_CERT_IN && out == AKE_CERT_OUT, + Step::HPrime => inp == H_PRIME_IN && out == 0, + Step::Pairing => inp == EKH_KM_LEN && out == 0, + Step::LcInit => inp == 0 && out == RN_LEN, + Step::LPrime => inp == L_PRIME_LEN && out == 0, + Step::Ske => inp == 0 && out == SKE_OUT, + Step::ReceiverList => { + inp >= V_PRIME_LEN + && input_len_ok(&spec_of(Command::PutReceiverList), inp - V_PRIME_LEN) + && out == V_LEN + } + Step::Stream => inp == STREAM_IN && out == 0, + Step::Finish | Step::EncryptionOn | Step::EncryptionOff => inp == 0 && out == 0, + } + } +} + +/// Runs commands against the HDCP endpoint; the SEP side or a test double. +pub(crate) trait Transport { + /// Sends `command` with `arg` and `input`; on [`Outcome::Done`] with + /// output, the output bytes are copied to `out` (exactly its length). + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result; + + /// Notified when the endpoint is quarantined after an unanswered command. + fn on_quarantine(&self, _slot: u8, _command: Command) {} +} + +/// Queries the enclave's HDCP interface count (`0x27`) and per-channel +/// descriptors (`0x28`), once per boot before any session opens. +pub(crate) fn enumerate(t: &T, state: &mut State) -> Result { + if state.quarantined { + return Err(EIO); + } + if let Some(count) = state.channel_count { + return Ok(count); + } + let outcome = match t.exchange(0, Command::QueryChannels, 0, &[], &mut []) { + Ok(o) => o, + Err(e) => return Err(e), + }; + if outcome == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(0, Command::QueryChannels); + return Err(EIO); + } + let Outcome::ChannelCount(count) = outcome else { + return Err(EIO); + }; + for slot in 0..count { + let mut info = [0u8; CHANNEL_INFO_LEN]; + let o = match t.exchange(slot, Command::GetChannelInfo, 0, &[], &mut info) { + Ok(o) => o, + Err(e) => return Err(e), + }; + if o == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(slot, Command::GetChannelInfo); + return Err(EIO); + } + if o != Outcome::Done(CHANNEL_INFO_LEN) || info[0] != slot { + return Err(EIO); + } + } + state.channel_count = Some(count); + Ok(count) +} + +/// Sends one session command on `slot` if the session allows it, and records +/// the outcome. +fn run( + t: &T, + state: &mut State, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], +) -> Result { + if state.quarantined { + return Err(EIO); + } + let i = usize::from(slot); + if i >= state.channels() { + return Err(EINVAL); + } + if !state.sessions[i].allows(command, arg) { + return Err(EPROTO); + } + if out.len() != spec_of(command).output { + return Err(EINVAL); + } + let outcome = match t.exchange(slot, command, arg, input, out) { + Ok(o) => o, + Err(e) => { + // Not sent (sleep gate, shutdown): if the session is already open, + // only teardown is safe afterwards. + if state.sessions[i].is_open() { + state.sessions[i].record(command, arg, Outcome::Malformed); + } + return Err(if e == EINVAL || e == EAGAIN || e == ENODEV { + e + } else { + EIO + }); + } + }; + if outcome == Outcome::NoReply { + state.quarantined = true; + t.on_quarantine(slot, command); + } + state.sessions[i].record(command, arg, outcome); + match errno(command, outcome) { + Some(e) => Err(e), + None => Ok(outcome), + } +} + +/// Runs one display-driver step on `slot`. +pub(crate) fn step( + t: &T, + state: &mut State, + slot: u8, + step: Step, + inp: &[u8], + out: &mut [u8], +) -> Result { + if !step.sizes_ok(inp.len(), out.len()) { + return Err(EINVAL); + } + let count = enumerate(t, state)?; + let i = usize::from(slot); + if i >= usize::from(count) { + return Err(EINVAL); + } + let was_open = state.sessions[i].is_open(); + let r = step_inner(t, state, slot, step, inp, out); + if r.is_err() { + out.fill(0); + // Only tear down a session that this Open call started; never clobber + // an already-open session when a duplicate Open fails with -EPROTO. + if step == Step::Open && !was_open && state.sessions[i].is_open() { + close(t, state, slot); + } + } + r +} + +fn step_inner( + t: &T, + state: &mut State, + slot: u8, + step: Step, + inp: &[u8], + out: &mut [u8], +) -> Result { + use Command::*; + let none: &mut [u8] = &mut []; + match step { + Step::Open => { + run(t, state, slot, Open, OPEN_ARG, &[], &mut [])?; + run(t, state, slot, Prepare, PREPARE_ARG, &[], &mut [])?; + run(t, state, slot, Start, 0, &[], &mut [])?; + run(t, state, slot, GetRtx, 0, &[], out)?; + state.sessions[usize::from(slot)].rtx.copy_from_slice(out); + } + Step::AkeCert => { + run(t, state, slot, PutCert, 0, &inp[..CERT_LEN], none)?; + run(t, state, slot, PutRrx, 0, &inp[CERT_LEN..], none)?; + let (flag, rest) = out.split_at_mut(1); + let o = run( + t, + state, + slot, + QueryStoredKm, + 0, + &[], + &mut rest[..STORED_KM_LEN], + )?; + if o == Outcome::NotStored { + rest[..STORED_KM_LEN].fill(0); + flag[0] = 0; + run(t, state, slot, GetEkpubKm, 0, &[], rest)?; + } else { + flag[0] = 1; + } + } + Step::HPrime => { + let mut ctx = [0u8; H_CONTEXT_LEN]; + ctx[..RTX_LEN].copy_from_slice(&state.sessions[usize::from(slot)].rtx); + ctx[RTX_LEN..].copy_from_slice(&inp[..2 * CAPS_LEN]); + run(t, state, slot, PutHContext, 0, &ctx, none)?; + run(t, state, slot, PutHPrime, 0, &inp[2 * CAPS_LEN..], none)?; + } + Step::Pairing => { + run(t, state, slot, PutPairing, 0, inp, none)?; + } + Step::LcInit => { + run(t, state, slot, GetRn, 0, &[], out)?; + } + Step::LPrime => { + run(t, state, slot, LcStart, 0, &[], none)?; + run(t, state, slot, PutLPrime, 0, inp, none)?; + } + Step::Ske => { + let (eks, riv) = out.split_at_mut(EKS_LEN); + run(t, state, slot, GetEks, 0, &[], eks)?; + run(t, state, slot, GetRiv, 0, &[], riv)?; + } + Step::ReceiverList => { + let (list, v_prime) = inp.split_at(inp.len() - V_PRIME_LEN); + run(t, state, slot, PutReceiverList, 0, list, none)?; + run(t, state, slot, PutVPrime, 0, v_prime, none)?; + run(t, state, slot, GetV, 0, &[], out)?; + } + Step::Stream => { + run(t, state, slot, PutStream, 0, &inp[..STREAM_LEN], none)?; + run(t, state, slot, PutMPrime, 0, &inp[STREAM_LEN..], none)?; + } + Step::Finish => { + run(t, state, slot, Finish, FINISH_ARG, &[], none)?; + } + Step::EncryptionOn => { + run(t, state, slot, SetEncryption, ENCRYPTION_ON, &[], none)?; + } + Step::EncryptionOff => { + run(t, state, slot, SetEncryption, 0, &[], none)?; + } + } + Ok(()) +} + +/// Ends the session on `slot` from any state: encryption off, then close. +/// The local session is reset whatever the enclave answers. +pub(crate) fn close(t: &T, state: &mut State, slot: u8) { + let i = usize::from(slot); + if i >= state.channels() || !state.sessions[i].is_open() { + return; + } + if !state.quarantined { + if state.sessions[i].encrypting() { + let _ = run(t, state, slot, Command::SetEncryption, 0, &[], &mut []); + } + if !state.quarantined { + let _ = run(t, state, slot, Command::Close, 0, &[], &mut []); + } + } + state.sessions[i] = Session::new(); +} + +/// The mailbox side. +struct Mailbox<'a>(&'a SepData); + +impl Transport for Mailbox<'_> { + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result { + let sep = self.0; + let msg = request(command, slot, arg, input.len())?; + if !input.is_empty() { + sep.ool_write(&sep.ool_hdcp, 0, input)?; + } + if !out.is_empty() { + // The last reply must not be taken for this one's. + sep.ool_repoison(&sep.ool_hdcp, 0, out.len()); + } + sep.hdcp_rx.lock().begin(); + if let Err(e) = sep.send(msg) { + sep.hdcp_rx.lock().end(); + sep.hdcp_scrub_buffers(input.len(), out.len()); + return Err(e); + } + let reply = match sep.hdcp_wait() { + Ok(Some(r)) => r, + Ok(None) => { + sep.hdcp_scrub_buffers(input.len(), 0); + return Ok(Outcome::NoReply); + } + Err(e) => { + sep.hdcp_scrub_buffers(input.len(), out.len()); + return Err(e); + } + }; + let outcome = check_reply(command, &reply); + let final_outcome = match outcome { + Outcome::Done(n) if n > 0 => { + if n != out.len() || !sep.ool_await_written(&sep.ool_hdcp, 0, n) { + Outcome::Malformed + } else { + match sep.ool_read(&sep.ool_hdcp, 0, n) { + Ok(bytes) => { + out.copy_from_slice(&bytes); + Outcome::Done(n) + } + Err(_) => Outcome::Malformed, + } + } + } + other => other, + }; + sep.hdcp_scrub_buffers(input.len(), out.len()); + Ok(final_outcome) + } + + fn on_quarantine(&self, slot: u8, command: Command) { + self.0.hdcp_quarantined.store(true, Release); + dev_err_ratelimited!( + self.0.dev, + "hdcp: no reply to command {:#04x} on channel {}; endpoint quarantined until reset\n", + spec_of(command).id, + slot + ); + } +} + +impl SepData { + /// Records the discovery messages of the endpoint. + pub(crate) fn hdcp_discovered(&self, f: &Fields) { + if f.param != EP_HDCP { + return; + } + match f.ty { + DISCOVER_TYPE_DESCRIPTOR => self.hdcp_named.store(f.data_lo == HDCP_NAME, Relaxed), + DISCOVER_TYPE_CONFIG => self.hdcp_layout.store(f.data_lo, Relaxed), + _ => {} + } + } + + pub(crate) fn hdcp_offered(&self) -> bool { + self.endpoint_present(EP_HDCP) + && self.hdcp_named.load(Relaxed) + && ool_sizes(self.hdcp_layout.load(Relaxed)).is_some() + } + + fn hdcp_ready_state(&self) -> Result { + if self.shutting_down.load(Relaxed) { + return Err(ENODEV); + } + if self.phase.load(Relaxed) != PHASE_READY { + return Err(EAGAIN); + } + if !self.hdcp_offered() { + return Err(ENODEV); + } + match self.sleep_gate() { + pm::SleepGate::Open => Ok(()), + pm::SleepGate::Lost => Err(EIO), + _ => Err(EAGAIN), + } + } + + fn hdcp_available(&self) -> bool { + self.hdcp_ready_state().is_ok() && !self.hdcp_quarantined.load(Acquire) + } + + fn hdcp_scrub_buffers(&self, in_len: usize, out_len: usize) { + let guard = self.ool_hdcp.lock(); + let Some(buffers) = guard.as_ref() else { + return; + }; + let in_n = in_len.min(buffers.allocated); + let out_n = out_len.min(buffers.allocated); + // SAFETY: the exchange is finished (or never sent) under `hdcp_state`; + // no concurrent host accessor touches these slices. + unsafe { + if in_n > 0 { + buffers.inbound.as_mut()[..in_n].fill(0); + } + if out_n > 0 { + buffers.outbound.as_mut()[..out_n].fill(OOL_POISON_OUTBOUND); + } + } + } + + /// Waits for the reply to the exchange in flight; `None` on timeout. + fn hdcp_wait(&self) -> Result> { + let mut remaining = time::msecs_to_jiffies(HDCP_TIMEOUT_MS); + let mut guard = self.hdcp_rx.lock(); + loop { + if self.shutting_down.load(Relaxed) { + guard.end(); + return Err(ENODEV); + } + if let Some(reply) = guard.take() { + return Ok(Some(reply)); + } + if remaining == 0 { + guard.end(); + return Ok(None); + } + // Uninterruptible, as the other reply waits. + match self.hdcp_wq.wait_timeout(&mut guard, remaining) { + CondVarTimeoutResult::Woken { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Signal { jiffies } => remaining = jiffies, + CondVarTimeoutResult::Timeout => remaining = 0, + } + } + } + + pub(crate) fn on_hdcp(&self, msg: Message) { + if self.hdcp_rx.lock().answer(msg) { + self.hdcp_wq.notify_all(); + } else if diag::unhandled() <= UNHANDLED_LOG_LIMIT { + dev_info_ratelimited!( + self.dev, + "hdcp: unexpected message (msg0 {:#018x})\n", + msg.msg0 + ); + } + } + + fn hdcp_ready(&self) -> Result { + self.hdcp_ready_state()?; + self.register_ool(&self.ool_hdcp).map_err(|e| { + if e == EAGAIN || e == ENODEV { + e + } else { + EIO + } + }) + } + + fn hdcp_step(&self, channel: u32, raw: u32, inp: &[u8], out: &mut [u8]) -> Result { + let slot = u8::try_from(channel).map_err(|_| EINVAL)?; + let step_id = Step::from_raw(raw).ok_or(EINVAL)?; + if let Err(e) = self.hdcp_ready() { + out.fill(0); + return Err(e); + } + let mut state = self.hdcp_state.lock(); + step(&Mailbox(self), &mut state, slot, step_id, inp, out) + } + + fn hdcp_close(&self, channel: u32) { + let Ok(slot) = u8::try_from(channel) else { + return; + }; + let mut state = self.hdcp_state.lock(); + close(&Mailbox(self), &mut state, slot); + } + + pub(crate) fn register_hdcp_kernel(&self) -> Result { + let context = core::ptr::from_ref(self).cast_mut().cast::(); + // SAFETY: `KERNEL_OPS` is static and `remove()` unregisters this + // pointer before the driver's `Arc` can be dropped. + kernel::error::to_result(unsafe { sep_hdcp_register(context, &KERNEL_OPS) }) + } + + pub(crate) fn unregister_hdcp_kernel(&self) { + let context = core::ptr::from_ref(self).cast_mut().cast::(); + // SAFETY: the pointer is the one passed to `sep_hdcp_register`. + unsafe { sep_hdcp_unregister(context) }; + } +} + +/// `struct sep_hdcp_ops` in shim.h. +#[repr(C)] +struct KernelOps { + available: unsafe extern "C" fn(*mut c_void) -> bool, + step: unsafe extern "C" fn(*mut c_void, u32, u32, *const u8, usize, *mut u8, usize) -> c_int, + close: unsafe extern "C" fn(*mut c_void, u32), +} + +extern "C" { + fn sep_hdcp_register(context: *mut c_void, ops: *const KernelOps) -> c_int; + fn sep_hdcp_unregister(context: *mut c_void); +} + +static KERNEL_OPS: KernelOps = KernelOps { + available: kernel_available, + step: kernel_step, + close: kernel_close, +}; + +/// # Safety +/// +/// `context` is the registered `SepData`; the shim holds its registration +/// lock, so it outlives the call. +unsafe extern "C" fn kernel_available(context: *mut c_void) -> bool { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + sep.hdcp_available() +} + +/// # Safety +/// +/// As [`kernel_available`]; `inp`/`out` are valid for their lengths (or the +/// length is 0) and do not overlap. +unsafe extern "C" fn kernel_step( + context: *mut c_void, + channel: u32, + step: u32, + inp: *const u8, + inp_len: usize, + out: *mut u8, + out_len: usize, +) -> c_int { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + let inp: &[u8] = if inp_len == 0 { + &[] + } else { + // SAFETY: see the function's safety section. + unsafe { core::slice::from_raw_parts(inp, inp_len) } + }; + let out: &mut [u8] = if out_len == 0 { + &mut [] + } else { + // SAFETY: see the function's safety section. + unsafe { core::slice::from_raw_parts_mut(out, out_len) } + }; + match sep.hdcp_step(channel, step, inp, out) { + Ok(()) => 0, + Err(e) => e.to_errno(), + } +} + +/// # Safety +/// +/// As [`kernel_available`]. +unsafe extern "C" fn kernel_close(context: *mut c_void, channel: u32) { + // SAFETY: see the function's safety section. + let sep = unsafe { &*context.cast::() }; + sep.hdcp_close(channel); +} + +#[cfg(CONFIG_APPLE_SEP_KUNIT_TEST)] +#[::kernel::macros::kunit_tests(apple_sep_hdcp)] +mod tests { + use super::*; + use core::cell::{Cell, RefCell}; + + // The request words of one first-pairing session to a repeater on slot 7, + // each with its reply word. The stored-km query answers status 0x08: no + // km stored. + const SLOT: u8 = 0x07; + const TRACE: [(Command, u32, usize, u64, u64); 23] = [ + ( + Command::Open, + OPEN_ARG, + 0, + 0x0201_0000_0700_010e, + 0x0000_0000_0000_000e, + ), + ( + Command::Prepare, + PREPARE_ARG, + 0, + 0x0002_0000_0700_260e, + 0x0000_0000_0000_000e, + ), + ( + Command::Start, + 0, + 0, + 0x0000_0000_0700_220e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetRtx, + 0, + 0, + 0x0000_0000_0700_040e, + 0x0000_0000_0008_000e, + ), + ( + Command::PutCert, + 0, + 522, + 0x0000_020a_0700_080e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutRrx, + 0, + 8, + 0x0000_0008_0700_050e, + 0x0000_0000_0000_000e, + ), + ( + Command::QueryStoredKm, + 0, + 0, + 0x0000_0000_0700_090e, + 0x0000_0000_0020_080e, + ), + ( + Command::GetEkpubKm, + 0, + 0, + 0x0000_0000_0700_0c0e, + 0x0000_0000_0080_000e, + ), + ( + Command::PutHContext, + 0, + 14, + 0x0000_000e_0700_0e0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutHPrime, + 0, + 32, + 0x0000_0020_0700_0f0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutPairing, + 0, + 16, + 0x0000_0010_0700_160e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetRn, + 0, + 0, + 0x0000_0000_0700_180e, + 0x0000_0000_0008_000e, + ), + ( + Command::LcStart, + 0, + 0, + 0x0000_0000_0700_1a0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutLPrime, + 0, + 32, + 0x0000_0020_0700_1c0e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetEks, + 0, + 0, + 0x0000_0000_0700_100e, + 0x0000_0000_0010_000e, + ), + ( + Command::GetRiv, + 0, + 0, + 0x0000_0000_0700_120e, + 0x0000_0000_0008_000e, + ), + ( + Command::PutReceiverList, + 0, + 10, + 0x0000_000a_0700_1d0e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutVPrime, + 0, + 16, + 0x0000_0010_0700_1f0e, + 0x0000_0000_0000_000e, + ), + ( + Command::GetV, + 0, + 0, + 0x0000_0000_0700_1e0e, + 0x0000_0000_0020_000e, + ), + ( + Command::PutStream, + 0, + 5, + 0x0000_0005_0700_230e, + 0x0000_0000_0000_000e, + ), + ( + Command::PutMPrime, + 0, + 32, + 0x0000_0020_0700_250e, + 0x0000_0000_0000_000e, + ), + ( + Command::Finish, + FINISH_ARG, + 0, + 0x0001_0000_0700_200e, + 0x0000_0000_0000_000e, + ), + ( + Command::SetEncryption, + ENCRYPTION_ON, + 0, + 0x0001_0000_0700_210e, + 0x0000_0000_0000_000e, + ), + ]; + // Display power-off: encryption off, then close. + const TRACE_OFF: [(Command, u64); 2] = [ + (Command::SetEncryption, 0x0000_0000_0700_210e), + (Command::Close, 0x0000_0000_0700_020e), + ]; + + fn reply(w: u64) -> Message { + // The second word is stale memory; it must not matter. + Message { + msg0: w, + msg1: 0x0bad_f00d, + } + } + + /// A transport that answers from a script of reply words and logs what + /// was sent. + struct Fake { + replies: RefCell>, + sent: RefCell>, + next: Cell, + quarantined: Cell, + } + + impl Fake { + fn new(replies: &[u64]) -> Fake { + let mut v = KVec::new(); + for r in replies { + v.push(*r, GFP_KERNEL).unwrap(); + } + Fake { + replies: RefCell::new(v), + sent: RefCell::new(KVec::new()), + next: Cell::new(0), + quarantined: Cell::new(false), + } + } + + fn sent(&self) -> KVec { + let mut v = KVec::new(); + for s in self.sent.borrow().iter() { + v.push(s.0, GFP_KERNEL).unwrap(); + } + v + } + } + + impl Transport for Fake { + fn exchange( + &self, + slot: u8, + command: Command, + arg: u32, + input: &[u8], + out: &mut [u8], + ) -> Result { + request(command, slot, arg, input.len())?; + self.sent + .borrow_mut() + .push((command, slot, arg, input.len()), GFP_KERNEL)?; + let i = self.next.get(); + self.next.set(i + 1); + let Some(&w) = self.replies.borrow().get(i) else { + return Ok(Outcome::NoReply); + }; + let o = check_reply(command, &reply(w)); + if let Outcome::Done(n) = o { + if n != out.len() { + return Ok(Outcome::Malformed); + } + if command == Command::GetChannelInfo { + out.fill(0); + out[0] = slot; + } else { + out.fill(0x5c); + } + } + Ok(o) + } + + fn on_quarantine(&self, _slot: u8, _command: Command) { + self.quarantined.set(true); + } + } + + const OK: u64 = 0x0000_0000_0000_000e; + + fn ok_for(c: Command) -> u64 { + OK | ((spec_of(c).output as u64) << 16) + } + + fn state_with_channels(n: u8) -> State { + let mut st = State::new(); + st.channel_count = Some(n); + st + } + + #[test] + fn the_requests_match_the_recording() { + assert_eq!( + request(Command::QueryChannels, 0, 0, 0).unwrap().msg0, + 0x0000_0000_0000_270e + ); + assert_eq!( + request(Command::GetChannelInfo, SLOT, 0, 0).unwrap().msg0, + 0x0000_0000_0700_280e + ); + assert!(request(Command::QueryChannels, 1, 0, 0).is_err()); + for &(c, arg, len, tx, _) in TRACE.iter() { + assert_eq!(request(c, SLOT, arg, len).unwrap().msg0, tx); + } + assert_eq!( + request(Command::SetEncryption, SLOT, 0, 0).unwrap().msg0, + TRACE_OFF[0].1 + ); + assert_eq!( + request(Command::Close, SLOT, 0, 0).unwrap().msg0, + TRACE_OFF[1].1 + ); + } + + #[test] + fn discovery_layout_and_channel_enumeration_follow_hardware() -> Result { + assert_eq!(ool_sizes(0x0101_0101), Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP))); + assert_eq!(ool_sizes(0x0101_0202), Some((OOL_SIZE_HDCP, OOL_SIZE_HDCP))); + assert_eq!(ool_sizes(0x0202_0202), None); + assert_eq!(ool_sizes(0), None); + + // Enclave advertises 9 channels (as on T8112); slot 8 succeeds, slot 9 fails. + let mut replies = KVec::new(); + replies.push(0x0000_0009_0000_000e, GFP_KERNEL)?; + for _ in 0..9 { + replies.push(ok_for(Command::GetChannelInfo), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = State::new(); + assert_eq!(enumerate(&t, &mut st)?, 9); + assert_eq!(st.channels(), 9); + // Second enumeration is cached (no further mailbox traffic). + assert_eq!(enumerate(&t, &mut st)?, 9); + assert_eq!(t.sent().len(), 10); + assert_eq!( + step(&t, &mut st, 9, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + assert_eq!(t.sent().len(), 10); + Ok(()) + } + + #[test] + fn the_recorded_session_runs_to_encryption_and_tears_down() { + let mut s = Session::new(); + for &(c, arg, _, _, rx) in TRACE.iter() { + assert!(s.allows(c, arg)); + let o = check_reply(c, &reply(rx)); + assert!(errno(c, o).is_none()); + assert!(s.record(c, arg, o)); + } + assert!(s.encrypting()); + assert!(!s.allows(Command::Close, 0)); + assert!(!s.allows(Command::GetRn, 0)); + assert!(s.allows(Command::SetEncryption, 0)); + assert!(s.record(Command::SetEncryption, 0, Outcome::Done(0))); + assert!(!s.encrypting()); + assert!(!s.allows(Command::SetEncryption, ENCRYPTION_ON)); + assert!(s.allows(Command::Close, 0)); + assert!(s.record(Command::Close, 0, Outcome::Done(0))); + assert!(!s.is_open()); + assert!(s.allows(Command::Open, OPEN_ARG)); + } + + #[test] + fn the_steps_send_the_first_pairing_repeater_order() -> Result { + let mut replies = KVec::new(); + for &(_, _, _, _, rx) in TRACE.iter() { + replies.push(rx, GFP_KERNEL)?; + } + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + let mut rtx = [0u8; RTX_LEN]; + step(&t, &mut st, SLOT, Step::Open, &[], &mut rtx)?; + let mut cert_out = [0u8; AKE_CERT_OUT]; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut cert_out, + )?; + assert_eq!(cert_out[0], 0); + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Pairing, &[3; EKH_KM_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN])?; + step(&t, &mut st, SLOT, Step::LPrime, &[4; L_PRIME_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::Ske, &[], &mut [0; SKE_OUT])?; + step( + &t, + &mut st, + SLOT, + Step::ReceiverList, + &[5; LIST_MIN + V_PRIME_LEN], + &mut [0; V_LEN], + )?; + step(&t, &mut st, SLOT, Step::Stream, &[6; STREAM_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Finish, &[], &mut [])?; + step(&t, &mut st, SLOT, Step::EncryptionOn, &[], &mut [])?; + assert!(st.sessions[SLOT as usize].encrypting()); + close(&t, &mut st, SLOT); + let sent = t.sent(); + assert_eq!(sent.len(), TRACE.len() + 2); + for (i, &(c, ..)) in TRACE.iter().enumerate() { + assert_eq!(sent[i], c); + } + assert_eq!(sent[TRACE.len()], Command::SetEncryption); + assert_eq!(sent[TRACE.len() + 1], Command::Close); + assert!(!st.sessions[SLOT as usize].is_open()); + Ok(()) + } + + #[test] + fn duplicate_open_does_not_clobber_active_session() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [Open, Prepare, Start, GetRtx] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + let sent_after_open = t.sent().len(); + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EPROTO) + ); + assert!(st.sessions[SLOT as usize].is_open()); + assert_eq!(t.sent().len(), sent_after_open); + Ok(()) + } + + #[test] + fn the_stored_km_path_skips_pairing() -> Result { + use Command::*; + let order = [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + PutHPrime, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + Finish, + SetEncryption, + ]; + let mut replies = KVec::new(); + for c in order.iter() { + replies.push(ok_for(*c), GFP_KERNEL)?; + } + let t = Fake::new(&replies); + let mut st = state_with_channels(15); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + let mut cert_out = [0u8; AKE_CERT_OUT]; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut cert_out, + )?; + assert_eq!(cert_out[0], 1); + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + // No pairing after a stored km. + assert_eq!( + step(&t, &mut st, SLOT, Step::Pairing, &[3; EKH_KM_LEN], &mut []), + Err(EPROTO) + ); + Ok(()) + } + + #[test] + fn out_of_order_and_bad_sizes_are_refused() { + let t = Fake::new(&[]); + let mut st = state_with_channels(15); + // Nothing before open; nothing reaches the transport. + assert_eq!( + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN]), + Err(EPROTO) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::EncryptionOn, &[], &mut []), + Err(EPROTO) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; 7]), + Err(EINVAL) + ); + assert_eq!( + step(&t, &mut st, 15, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + // A list of no Receiver ID, of 32, or of a partial one. + for n in [ + V_PRIME_LEN + 5, + V_PRIME_LEN + LIST_MAX + 5, + V_PRIME_LEN + LIST_MIN + 3, + ] { + assert!(!Step::ReceiverList.sizes_ok(n, V_LEN)); + } + assert!(Step::ReceiverList.sizes_ok(V_PRIME_LEN + LIST_MAX, V_LEN)); + assert!(t.sent().is_empty()); + assert!(request(Command::PutCert, SLOT, 0, 521).is_err()); + assert!(request(Command::Open, SLOT, 0, 0).is_err()); + assert!(request(Command::GetRtx, SLOT, 0, 8).is_err()); + assert!(request(Command::SetEncryption, SLOT, 3, 0).is_err()); + } + + #[test] + fn a_refused_verification_is_eacces_and_fails_the_session() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + ] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + // H' refused with some status. + replies.push(0x0000_0000_0000_030e, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(15); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut [0; AKE_CERT_OUT], + )?; + assert_eq!( + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut []), + Err(EACCES) + ); + assert_eq!( + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN]), + Err(EPROTO) + ); + close(&t, &mut st, SLOT); + assert_eq!(*t.sent().last().unwrap(), Close); + assert!(st.sessions[SLOT as usize].allows(Open, OPEN_ARG)); + // A refused non-verification command is EIO. + assert_eq!(errno(GetRtx, Outcome::Refused(1)), Some(EIO)); + assert_eq!(errno(PutMPrime, Outcome::Refused(1)), Some(EACCES)); + assert_eq!(errno(PutReceiverList, Outcome::Refused(1)), Some(EACCES)); + Ok(()) + } + + #[test] + fn stream_manage_allows_one_retry_after_refused_m_prime() -> Result { + use Command::*; + let mut replies = KVec::new(); + for c in [ + Open, + Prepare, + Start, + GetRtx, + PutCert, + PutRrx, + QueryStoredKm, + PutHContext, + PutHPrime, + GetRn, + LcStart, + PutLPrime, + GetEks, + GetRiv, + PutReceiverList, + PutVPrime, + GetV, + PutStream, + ] { + replies.push(ok_for(c), GFP_KERNEL)?; + } + // First M' refused, second attempt succeeds, then Finish succeeds. + replies.push(0x0000_0000_0000_030e, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + replies.push(OK, GFP_KERNEL)?; + let t = Fake::new(&replies); + let mut st = state_with_channels(9); + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN])?; + step( + &t, + &mut st, + SLOT, + Step::AkeCert, + &[1; AKE_CERT_IN], + &mut [0; AKE_CERT_OUT], + )?; + step(&t, &mut st, SLOT, Step::HPrime, &[2; H_PRIME_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::LcInit, &[], &mut [0; RN_LEN])?; + step(&t, &mut st, SLOT, Step::LPrime, &[4; L_PRIME_LEN], &mut [])?; + step(&t, &mut st, SLOT, Step::Ske, &[], &mut [0; SKE_OUT])?; + step( + &t, + &mut st, + SLOT, + Step::ReceiverList, + &[5; LIST_MIN + V_PRIME_LEN], + &mut [0; V_LEN], + )?; + assert_eq!( + step(&t, &mut st, SLOT, Step::Stream, &[6; STREAM_IN], &mut []), + Err(EACCES) + ); + // Finish is refused while retry is pending. + assert_eq!(step(&t, &mut st, SLOT, Step::Finish, &[], &mut []), Err(EPROTO)); + // Retry succeeds, then Finish proceeds. + step(&t, &mut st, SLOT, Step::Stream, &[7; STREAM_IN], &mut [])?; + step(&t, &mut st, SLOT, Step::Finish, &[], &mut [])?; + Ok(()) + } + + #[test] + fn replies_are_judged_by_status_and_length() { + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0009_0000_000e)), + Outcome::ChannelCount(9) + ); + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0000_0000_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::QueryChannels, &reply(0x0000_0021_0000_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::GetRtx, &reply(0x0000_0000_0010_000e)), + Outcome::Malformed + ); + assert_eq!( + check_reply(Command::GetEkpubKm, &reply(0x0000_0000_0080_000e)), + Outcome::Done(128) + ); + assert_eq!( + check_reply(Command::QueryStoredKm, &reply(0x0000_0000_0020_080e)), + Outcome::NotStored + ); + // Status 0x08 means "not stored" for the query only. + assert_eq!( + check_reply(Command::GetRn, &reply(0x0000_0000_0000_080e)), + Outcome::Refused(8) + ); + for w in [ + 0x0000_0000_0000_000fu64, + 0x0000_0000_0100_000e, + 0x0000_0001_0000_000e, + ] { + assert_eq!(check_reply(Command::Start, &reply(w)), Outcome::Malformed); + } + } + + #[test] + fn silence_quarantines_every_slot() -> Result { + let t = Fake::new(&[OK]); + let mut st = state_with_channels(15); + // Open answered, Prepare never: the whole endpoint stops. + assert_eq!( + step(&t, &mut st, SLOT, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EIO) + ); + assert!(st.quarantined); + assert!(t.quarantined.get()); + let n = t.sent().len(); + assert_eq!( + step(&t, &mut st, 5, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EIO) + ); + close(&t, &mut st, SLOT); + assert_eq!(t.sent().len(), n); + assert!(!st.sessions[SLOT as usize].is_open()); + Ok(()) + } + + #[test] + fn the_locality_check_may_be_retried_a_bounded_number_of_times() { + use Command::*; + let mut s = Session::new(); + for c in [Open, Prepare, Start, GetRtx, PutCert, PutRrx] { + let arg = match c { + Open => OPEN_ARG, + Prepare => PREPARE_ARG, + _ => 0, + }; + assert!(s.record(c, arg, Outcome::Done(spec_of(c).output))); + } + assert!(s.record(QueryStoredKm, 0, Outcome::Done(32))); + for c in [PutHContext, PutHPrime] { + assert!(s.allows(c, 0)); + assert!(s.record(c, 0, Outcome::Done(0))); + } + // Refused L' allows retrying GetRn while retries remain. + assert!(s.allows(GetRn, 0)); + assert!(s.record(GetRn, 0, Outcome::Done(8))); + assert!(s.allows(LcStart, 0)); + assert!(s.record(LcStart, 0, Outcome::Done(0))); + assert!(s.allows(PutLPrime, 0)); + assert!(!s.record(PutLPrime, 0, Outcome::Refused(1))); + assert!(!s.allows(GetEks, 0)); + for _ in 1..LC_MAX_TRIES { + assert!(s.allows(GetRn, 0)); + assert!(s.record(GetRn, 0, Outcome::Done(8))); + } + assert!(!s.allows(GetRn, 0)); + assert!(s.allows(LcStart, 0)); + assert!(s.record(LcStart, 0, Outcome::Done(0))); + // Refused L' after the last attempt fails the session. + assert!(!s.record(PutLPrime, 0, Outcome::Refused(1))); + assert!(!s.allows(GetRn, 0)); + assert!(!s.allows(GetEks, 0)); + assert!(s.allows(Close, 0)); + } + + #[test] + fn the_table_is_closed_and_fits_the_buffers() { + for (i, a) in SPECS.iter().enumerate() { + assert!(a.input_max <= OOL_SIZE_HDCP && a.output <= u8::MAX as usize); + for b in SPECS[i + 1..].iter() { + assert!(a.id != b.id && a.command != b.command); + } + } + } +} diff --git a/drivers/soc/apple/hdcp_shim.c b/drivers/soc/apple/hdcp_shim.c new file mode 100644 index 00000000000000..2c0d48eb1947c6 --- /dev/null +++ b/drivers/soc/apple/hdcp_shim.c @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The SEP HDCP 2.2 transmitter service for the display driver + * (include/linux/apple-sep-hdcp.h). The SEP driver registers its steps here; + * this file checks the arguments, flattens them in the order the SEP takes + * them and unpacks the results. It is built in, so the display driver links + * against it whether or not the SEP driver is loaded. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "shim.h" + +static DECLARE_RWSEM(apple_sep_hdcp_registration_lock); +static DEFINE_MUTEX(apple_sep_hdcp_call_lock); +static struct sep_hdcp_ops apple_sep_hdcp_ops; +static void *apple_sep_hdcp_context; + +int sep_hdcp_register(void *context, const struct sep_hdcp_ops *ops) +{ + int ret = 0; + + if (!context || !ops || !ops->available || !ops->step || !ops->close) + return -EINVAL; + + down_write(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) { + ret = -EBUSY; + } else { + apple_sep_hdcp_ops = *ops; + apple_sep_hdcp_context = context; + } + up_write(&apple_sep_hdcp_registration_lock); + return ret; +} +EXPORT_SYMBOL_GPL(sep_hdcp_register); + +void sep_hdcp_unregister(void *context) +{ + down_write(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context == context) { + apple_sep_hdcp_context = NULL; + memzero_explicit(&apple_sep_hdcp_ops, + sizeof(apple_sep_hdcp_ops)); + } + up_write(&apple_sep_hdcp_registration_lock); +} +EXPORT_SYMBOL_GPL(sep_hdcp_unregister); + +static int apple_sep_hdcp_step(u32 channel, enum sep_hdcp_step step, + const u8 *in, size_t in_len, u8 *out, + size_t out_len) +{ + int ret; + + down_read(&apple_sep_hdcp_registration_lock); + if (!apple_sep_hdcp_context) { + ret = -ENODEV; + goto out; + } + mutex_lock(&apple_sep_hdcp_call_lock); + ret = apple_sep_hdcp_ops.step(apple_sep_hdcp_context, channel, step, + in, in_len, out, out_len); + mutex_unlock(&apple_sep_hdcp_call_lock); +out: + up_read(&apple_sep_hdcp_registration_lock); + if (ret && out_len) + memzero_explicit(out, out_len); + return ret; +} + +bool apple_sep_hdcp_available(void) +{ + bool ret = false; + + down_read(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) + ret = apple_sep_hdcp_ops.available(apple_sep_hdcp_context); + up_read(&apple_sep_hdcp_registration_lock); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_available); + +int apple_sep_hdcp_open(u32 channel, u8 rtx[APPLE_SEP_HDCP_RTX_LEN]) +{ + if (!rtx) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_OPEN, NULL, 0, rtx, + APPLE_SEP_HDCP_RTX_LEN); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_open); + +#define AKE_CERT_IN (APPLE_SEP_HDCP_CERT_LEN + APPLE_SEP_HDCP_RRX_LEN) +#define AKE_CERT_OUT (1 + APPLE_SEP_HDCP_EKPUB_KM_LEN) + +int apple_sep_hdcp_ake_cert(u32 channel, + const u8 cert[APPLE_SEP_HDCP_CERT_LEN], + const u8 rrx[APPLE_SEP_HDCP_RRX_LEN], + bool *stored, struct apple_sep_hdcp_stored_km *km, + u8 ekpub_km[APPLE_SEP_HDCP_EKPUB_KM_LEN]) +{ + u8 *in, *out; + int ret; + + if (!cert || !rrx || !stored || !km || !ekpub_km) + return -EINVAL; + *stored = false; + memzero_explicit(km, sizeof(*km)); + memzero_explicit(ekpub_km, APPLE_SEP_HDCP_EKPUB_KM_LEN); + + in = kmalloc(AKE_CERT_IN + AKE_CERT_OUT, GFP_KERNEL); + if (!in) + return -ENOMEM; + out = in + AKE_CERT_IN; + memcpy(in, cert, APPLE_SEP_HDCP_CERT_LEN); + memcpy(in + APPLE_SEP_HDCP_CERT_LEN, rrx, APPLE_SEP_HDCP_RRX_LEN); + + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_AKE_CERT, in, + AKE_CERT_IN, out, AKE_CERT_OUT); + if (!ret) { + if (out[0]) { + *stored = true; + memcpy(km->ekh_km, out + 1, APPLE_SEP_HDCP_EKH_KM_LEN); + memcpy(km->m, out + 1 + APPLE_SEP_HDCP_EKH_KM_LEN, + APPLE_SEP_HDCP_M_LEN); + } else { + memcpy(ekpub_km, out + 1, APPLE_SEP_HDCP_EKPUB_KM_LEN); + } + } + kfree_sensitive(in); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_cert); + +int apple_sep_hdcp_ake_h_prime(u32 channel, + const u8 rxcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 txcaps[APPLE_SEP_HDCP_CAPS_LEN], + const u8 h_prime[APPLE_SEP_HDCP_H_PRIME_LEN]) +{ + u8 in[2 * APPLE_SEP_HDCP_CAPS_LEN + APPLE_SEP_HDCP_H_PRIME_LEN]; + int ret; + + if (!rxcaps || !txcaps || !h_prime) + return -EINVAL; + memcpy(in, rxcaps, APPLE_SEP_HDCP_CAPS_LEN); + memcpy(in + APPLE_SEP_HDCP_CAPS_LEN, txcaps, APPLE_SEP_HDCP_CAPS_LEN); + memcpy(in + 2 * APPLE_SEP_HDCP_CAPS_LEN, h_prime, + APPLE_SEP_HDCP_H_PRIME_LEN); + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_H_PRIME, in, + sizeof(in), NULL, 0); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_h_prime); + +int apple_sep_hdcp_ake_pairing(u32 channel, + const u8 ekh_km[APPLE_SEP_HDCP_EKH_KM_LEN]) +{ + if (!ekh_km) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_PAIRING, ekh_km, + APPLE_SEP_HDCP_EKH_KM_LEN, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ake_pairing); + +int apple_sep_hdcp_lc_init(u32 channel, u8 rn[APPLE_SEP_HDCP_RN_LEN]) +{ + if (!rn) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_LC_INIT, NULL, 0, rn, + APPLE_SEP_HDCP_RN_LEN); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_lc_init); + +int apple_sep_hdcp_lc_l_prime(u32 channel, + const u8 l_prime[APPLE_SEP_HDCP_L_PRIME_LEN]) +{ + if (!l_prime) + return -EINVAL; + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_L_PRIME, l_prime, + APPLE_SEP_HDCP_L_PRIME_LEN, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_lc_l_prime); + +int apple_sep_hdcp_ske(u32 channel, + u8 edkey_ks[APPLE_SEP_HDCP_EDKEY_KS_LEN], + u8 riv[APPLE_SEP_HDCP_RIV_LEN]) +{ + u8 out[APPLE_SEP_HDCP_EDKEY_KS_LEN + APPLE_SEP_HDCP_RIV_LEN]; + int ret; + + if (!edkey_ks || !riv) + return -EINVAL; + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_SKE, NULL, 0, out, + sizeof(out)); + memcpy(edkey_ks, out, APPLE_SEP_HDCP_EDKEY_KS_LEN); + memcpy(riv, out + APPLE_SEP_HDCP_EDKEY_KS_LEN, APPLE_SEP_HDCP_RIV_LEN); + memzero_explicit(out, sizeof(out)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_ske); + +#define LIST_IN_MAX (APPLE_SEP_HDCP_MAX_DEVICES * APPLE_SEP_HDCP_RECEIVER_ID_LEN + \ + APPLE_SEP_HDCP_RXINFO_LEN + APPLE_SEP_HDCP_SEQ_NUM_LEN + \ + APPLE_SEP_HDCP_V_PRIME_LEN) + +int apple_sep_hdcp_repeater_list(u32 channel, const u8 *ids, unsigned int count, + const u8 rxinfo[APPLE_SEP_HDCP_RXINFO_LEN], + const u8 seq_num_v[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 v_prime[APPLE_SEP_HDCP_V_PRIME_LEN], + u8 v[APPLE_SEP_HDCP_V_LEN]) +{ + u8 in[LIST_IN_MAX]; + size_t n; + int ret; + + if (!v) + return -EINVAL; + memzero_explicit(v, APPLE_SEP_HDCP_V_LEN); + if (!ids || !count || count > APPLE_SEP_HDCP_MAX_DEVICES || !rxinfo || + !seq_num_v || !v_prime) + return -EINVAL; + + /* The order V is computed over: the list, RxInfo, seq_num_V. */ + n = count * APPLE_SEP_HDCP_RECEIVER_ID_LEN; + memcpy(in, ids, n); + memcpy(in + n, rxinfo, APPLE_SEP_HDCP_RXINFO_LEN); + n += APPLE_SEP_HDCP_RXINFO_LEN; + memcpy(in + n, seq_num_v, APPLE_SEP_HDCP_SEQ_NUM_LEN); + n += APPLE_SEP_HDCP_SEQ_NUM_LEN; + memcpy(in + n, v_prime, APPLE_SEP_HDCP_V_PRIME_LEN); + n += APPLE_SEP_HDCP_V_PRIME_LEN; + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_RECEIVER_LIST, in, n, + v, APPLE_SEP_HDCP_V_LEN); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_repeater_list); + +int apple_sep_hdcp_repeater_stream(u32 channel, u8 stream_id, u8 type, + const u8 seq_num_m[APPLE_SEP_HDCP_SEQ_NUM_LEN], + const u8 m_prime[APPLE_SEP_HDCP_M_PRIME_LEN]) +{ + u8 in[2 + APPLE_SEP_HDCP_SEQ_NUM_LEN + APPLE_SEP_HDCP_M_PRIME_LEN]; + int ret; + + if (type > 1 || !seq_num_m || !m_prime) + return -EINVAL; + /* The order M is computed over: StreamID_Type, then seq_num_M. */ + in[0] = stream_id; + in[1] = type; + memcpy(in + 2, seq_num_m, APPLE_SEP_HDCP_SEQ_NUM_LEN); + memcpy(in + 2 + APPLE_SEP_HDCP_SEQ_NUM_LEN, m_prime, + APPLE_SEP_HDCP_M_PRIME_LEN); + ret = apple_sep_hdcp_step(channel, SEP_HDCP_STEP_STREAM, in, + sizeof(in), NULL, 0); + memzero_explicit(in, sizeof(in)); + return ret; +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_repeater_stream); + +int apple_sep_hdcp_finish(u32 channel) +{ + return apple_sep_hdcp_step(channel, SEP_HDCP_STEP_FINISH, NULL, 0, + NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_finish); + +int apple_sep_hdcp_set_encryption(u32 channel, bool on) +{ + return apple_sep_hdcp_step(channel, + on ? SEP_HDCP_STEP_ENCRYPTION_ON : + SEP_HDCP_STEP_ENCRYPTION_OFF, + NULL, 0, NULL, 0); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_set_encryption); + +void apple_sep_hdcp_close(u32 channel) +{ + down_read(&apple_sep_hdcp_registration_lock); + if (apple_sep_hdcp_context) { + mutex_lock(&apple_sep_hdcp_call_lock); + apple_sep_hdcp_ops.close(apple_sep_hdcp_context, channel); + mutex_unlock(&apple_sep_hdcp_call_lock); + } + up_read(&apple_sep_hdcp_registration_lock); +} +EXPORT_SYMBOL_GPL(apple_sep_hdcp_close); + +#if IS_BUILTIN(CONFIG_KUNIT) && IS_ENABLED(CONFIG_APPLE_SEP_KUNIT_TEST) +#include "hdcp_shim_test.c" +#endif diff --git a/drivers/soc/apple/hdcp_shim_test.c b/drivers/soc/apple/hdcp_shim_test.c new file mode 100644 index 00000000000000..def94210eaaa0c --- /dev/null +++ b/drivers/soc/apple/hdcp_shim_test.c @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the HDCP shim: argument checks, registration rules, the + * flat layouts handed to the SEP driver, and that outputs are zeroed on + * failure. Included from hdcp_shim.c. A stand-in SEP driver records each step. + */ +#include + +static struct { + u32 channel; + u32 step; + u8 in[256]; + size_t in_len; + size_t out_len; + int ret; + u8 fill; + int calls; + int closes; +} fake; + +static bool fake_available(void *context) +{ + return true; +} + +static int fake_step(void *context, u32 channel, u32 step, const u8 *in, + size_t in_len, u8 *out, size_t out_len) +{ + fake.calls++; + fake.channel = channel; + fake.step = step; + fake.in_len = in_len; + fake.out_len = out_len; + if (in_len <= sizeof(fake.in) && in_len) + memcpy(fake.in, in, in_len); + if (out_len) + memset(out, fake.fill, out_len); + return fake.ret; +} + +static void fake_close(void *context, u32 channel) +{ + fake.closes++; + fake.channel = channel; +} + +static const struct sep_hdcp_ops fake_ops = { + .available = fake_available, + .step = fake_step, + .close = fake_close, +}; + +static int fake_context; + +static int hdcp_shim_init(struct kunit *test) +{ + memset(&fake, 0, sizeof(fake)); + /* A real SEP driver owns the registration: leave it alone. */ + if (sep_hdcp_register(&fake_context, &fake_ops)) + kunit_skip(test, "a SEP driver is registered"); + return 0; +} + +static void hdcp_shim_exit(struct kunit *test) +{ + sep_hdcp_unregister(&fake_context); +} + +static void hdcp_shim_registration_rules(struct kunit *test) +{ + static int other_context; + struct sep_hdcp_ops incomplete = fake_ops; + + KUNIT_EXPECT_EQ(test, sep_hdcp_register(&other_context, &fake_ops), + -EBUSY); + KUNIT_EXPECT_EQ(test, sep_hdcp_register(NULL, &fake_ops), -EINVAL); + incomplete.close = NULL; + KUNIT_EXPECT_EQ(test, sep_hdcp_register(&other_context, &incomplete), + -EINVAL); + /* Unregistering the wrong context must leave the active one intact. */ + sep_hdcp_unregister(&other_context); + KUNIT_EXPECT_TRUE(test, apple_sep_hdcp_available()); +} + +static void hdcp_shim_unregistered_is_enodev(struct kunit *test) +{ + u8 rtx[APPLE_SEP_HDCP_RTX_LEN]; + + sep_hdcp_unregister(&fake_context); + memset(rtx, 0xee, sizeof(rtx)); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_open(3, rtx), -ENODEV); + KUNIT_EXPECT_TRUE(test, !memchr_inv(rtx, 0, sizeof(rtx))); + KUNIT_EXPECT_FALSE(test, apple_sep_hdcp_available()); + apple_sep_hdcp_close(3); + KUNIT_EXPECT_EQ(test, fake.calls + fake.closes, 0); +} + +static void hdcp_shim_ake_cert_unpacks_both_answers(struct kunit *test) +{ + static u8 cert[APPLE_SEP_HDCP_CERT_LEN]; + u8 rrx[APPLE_SEP_HDCP_RRX_LEN] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + u8 ekpub[APPLE_SEP_HDCP_EKPUB_KM_LEN]; + struct apple_sep_hdcp_stored_km km; + bool stored; + + /* The stand-in fills the whole output: flag 1 means a stored km. */ + fake.fill = 1; + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_AKE_CERT); + KUNIT_EXPECT_EQ(test, fake.channel, 7u); + KUNIT_EXPECT_EQ(test, fake.out_len, + (size_t)(1 + APPLE_SEP_HDCP_EKPUB_KM_LEN)); + KUNIT_EXPECT_TRUE(test, stored); + KUNIT_EXPECT_EQ(test, km.ekh_km[0], 1); + KUNIT_EXPECT_TRUE(test, !memchr_inv(ekpub, 0, sizeof(ekpub))); + + fake.fill = 0; + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), 0); + KUNIT_EXPECT_FALSE(test, stored); + KUNIT_EXPECT_TRUE(test, !memchr_inv(&km, 0, sizeof(km))); + + fake.fill = 0x77; + fake.ret = -EACCES; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_ake_cert(7, cert, rrx, &stored, + &km, ekpub), -EACCES); + KUNIT_EXPECT_FALSE(test, stored); + KUNIT_EXPECT_TRUE(test, !memchr_inv(&km, 0, sizeof(km))); + KUNIT_EXPECT_TRUE(test, !memchr_inv(ekpub, 0, sizeof(ekpub))); +} + +static void hdcp_shim_receiver_list_layout_and_bounds(struct kunit *test) +{ + u8 ids[2 * APPLE_SEP_HDCP_RECEIVER_ID_LEN] = { + 0x10, 0x11, 0x12, 0x13, 0x14, 0x20, 0x21, 0x22, 0x23, 0x24 + }; + u8 rxinfo[2] = { 0x02, 0x20 }, seq[3] = { 0, 0, 1 }; + u8 vp[APPLE_SEP_HDCP_V_PRIME_LEN], v[APPLE_SEP_HDCP_V_LEN]; + + memset(vp, 0xab, sizeof(vp)); + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 2, rxinfo, + seq, vp, v), 0); + KUNIT_EXPECT_EQ(test, fake.in_len, (size_t)(10 + 2 + 3 + 16)); + KUNIT_EXPECT_EQ(test, fake.in[5], 0x20); + KUNIT_EXPECT_EQ(test, fake.in[10], 0x02); + KUNIT_EXPECT_EQ(test, fake.in[14], 0x01); + KUNIT_EXPECT_EQ(test, fake.in[15], 0xab); + + fake.calls = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 0, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, ids, 32, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_list(1, NULL, 1, rxinfo, + seq, vp, v), -EINVAL); + KUNIT_EXPECT_EQ(test, fake.calls, 0); +} + +static void hdcp_shim_stream_layout_and_type(struct kunit *test) +{ + u8 seq[3] = { 0, 0, 2 }, mp[APPLE_SEP_HDCP_M_PRIME_LEN] = { 0x5a }; + + KUNIT_ASSERT_EQ(test, apple_sep_hdcp_repeater_stream(2, 0, 1, seq, mp), + 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_STREAM); + KUNIT_EXPECT_EQ(test, fake.in_len, (size_t)37); + KUNIT_EXPECT_EQ(test, fake.in[0], 0); + KUNIT_EXPECT_EQ(test, fake.in[1], 1); + KUNIT_EXPECT_EQ(test, fake.in[4], 2); + KUNIT_EXPECT_EQ(test, fake.in[5], 0x5a); + fake.calls = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_repeater_stream(2, 0, 2, seq, mp), + -EINVAL); + KUNIT_EXPECT_EQ(test, fake.calls, 0); +} + +static void hdcp_shim_errors_zero_outputs(struct kunit *test) +{ + u8 rn[APPLE_SEP_HDCP_RN_LEN], eks[APPLE_SEP_HDCP_EDKEY_KS_LEN]; + u8 riv[APPLE_SEP_HDCP_RIV_LEN]; + + fake.fill = 0x99; + fake.ret = -EIO; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_lc_init(0, rn), -EIO); + KUNIT_EXPECT_TRUE(test, !memchr_inv(rn, 0, sizeof(rn))); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_ske(0, eks, riv), -EIO); + KUNIT_EXPECT_TRUE(test, !memchr_inv(eks, 0, sizeof(eks))); + KUNIT_EXPECT_TRUE(test, !memchr_inv(riv, 0, sizeof(riv))); + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_open(0, NULL), -EINVAL); + + fake.ret = 0; + KUNIT_EXPECT_EQ(test, apple_sep_hdcp_set_encryption(4, false), 0); + KUNIT_EXPECT_EQ(test, fake.step, (u32)SEP_HDCP_STEP_ENCRYPTION_OFF); + apple_sep_hdcp_close(4); + KUNIT_EXPECT_EQ(test, fake.closes, 1); + KUNIT_EXPECT_TRUE(test, apple_sep_hdcp_available()); +} + +static struct kunit_case hdcp_shim_test_cases[] = { + KUNIT_CASE(hdcp_shim_registration_rules), + KUNIT_CASE(hdcp_shim_unregistered_is_enodev), + KUNIT_CASE(hdcp_shim_ake_cert_unpacks_both_answers), + KUNIT_CASE(hdcp_shim_receiver_list_layout_and_bounds), + KUNIT_CASE(hdcp_shim_stream_layout_and_type), + KUNIT_CASE(hdcp_shim_errors_zero_outputs), + {} +}; + +static struct kunit_suite hdcp_shim_test_suite = { + .name = "apple_sep_hdcp_shim", + .init = hdcp_shim_init, + .exit = hdcp_shim_exit, + .test_cases = hdcp_shim_test_cases, +}; + +kunit_test_suite(hdcp_shim_test_suite); diff --git a/drivers/soc/apple/sep.rs b/drivers/soc/apple/sep.rs index fc5302b33bdacd..2e45b04dd527b3 100644 --- a/drivers/soc/apple/sep.rs +++ b/drivers/soc/apple/sep.rs @@ -19,6 +19,7 @@ mod der; mod diag; mod dt; mod fv; +mod hdcp; mod hibe; mod hwrng; mod image; @@ -829,6 +830,21 @@ struct SepData { stac_layout: Atomic, stac_absent_logged: Atomic, + // The HDCP endpoint (see `hdcp`): its buffers, the sessions per slot + // (held for a whole step, so one exchange is in flight), the reply wait, + // discovery state, and quarantine flag. + #[pin] + ool_hdcp: Mutex>, + #[pin] + hdcp_state: Mutex, + #[pin] + hdcp_rx: Mutex, + #[pin] + hdcp_wq: CondVar, + hdcp_named: Atomic, + hdcp_layout: Atomic, + hdcp_quarantined: Atomic, + // The boot-policy endpoint (see `pnon`): its buffers, its one // exchange, and what discovery said about it. #[pin] @@ -1087,6 +1103,12 @@ impl SepData { stac::OOL_SIZE_STAC, (stac::OOL_SIZE_STAC, stac::OOL_SIZE_STAC), )?; + let ool_hdcp = Self::alloc_ool( + dev, + hdcp::EP_HDCP, + hdcp::OOL_SIZE_HDCP, + (hdcp::OOL_SIZE_HDCP, hdcp::OOL_SIZE_HDCP), + )?; // Sized from the endpoint's layout before it is registered. let ool_pnon = Self::alloc_ool(dev, pnon::EP_PNON, pnon::OOL_SIZE_PNON, (0, 0))?; let dma_ring = dma::Coherent::::zeroed_slice(dev, DMA_RING_SIZE, GFP_KERNEL)?; @@ -1251,6 +1273,13 @@ impl SepData { stac_named: Atomic::new(false), stac_layout: Atomic::new(0), stac_absent_logged: Atomic::new(false), + ool_hdcp <- new_mutex!(Some(ool_hdcp)), + hdcp_state <- new_mutex!(hdcp::State::new()), + hdcp_rx <- new_mutex!(hdcp::Exchange::new()), + hdcp_wq <- new_condvar!("SepData::hdcp_wq"), + hdcp_named: Atomic::new(false), + hdcp_layout: Atomic::new(0), + hdcp_quarantined: Atomic::new(false), ool_pnon <- new_mutex!(Some(ool_pnon)), pnon_rx <- new_mutex!(pnon::Exchange::new()), pnon_wq <- new_condvar!("SepData::pnon_wq"), @@ -3366,6 +3395,8 @@ impl SepData { stac::EP_STAC => self.on_stac(msg), + hdcp::EP_HDCP => self.on_hdcp(msg), + pnon::EP_PNON => self.on_pnon(msg), sse::EP_SSE => self.on_sse(msg), @@ -3420,6 +3451,7 @@ impl SepData { proto::DISCOVER_TYPE_DESCRIPTOR | proto::DISCOVER_TYPE_CONFIG => { let _ = table.slot(f.param); self.stac_discovered(&f); + self.hdcp_discovered(&f); self.pnon_discovered(&f); self.sse_discovered(&f); self.hibe_discovered(&f); @@ -3458,12 +3490,14 @@ impl SepData { self.sbio_wq.notify_all(); self.sks_wq.notify_all(); self.scrd_wq.notify_all(); + self.hdcp_wq.notify_all(); pm::unregister(); // Release any capture start still held for a resume that will not be // reported now. self.sleep_finished(); trusted::unregister(); self.unregister_fv_kernel(); + self.unregister_hdcp_kernel(); let dev = self.bio_dev.lock().take(); drop(dev); @@ -3515,6 +3549,7 @@ impl SepData { &self.ool_sks, &self.ool_scrd, &self.ool_stac, + &self.ool_hdcp, &self.ool_pnon, ] { if let Some(buffers) = slot.lock().take() { @@ -3828,6 +3863,12 @@ impl platform::Driver for SepDriver { } } + // The display driver's HDCP 2.2 transmitter service. Nothing is sent + // to the endpoint until the display driver starts a session. + if let Err(e) = data.register_hdcp_kernel() { + dev_warn_ratelimited!(dev, "hdcp: could not register the kernel API: {:?}\n", e); + } + if module_parameters::trusted_keys.value() != 0 { if let Err(e) = trusted::register(data.clone()) { dev_warn_ratelimited!(data.dev, "trusted-keys: registration failed ({:?})\n", e); diff --git a/drivers/soc/apple/shim.h b/drivers/soc/apple/shim.h index 456492d6e8afe3..86325f940adb56 100644 --- a/drivers/soc/apple/shim.h +++ b/drivers/soc/apple/shim.h @@ -307,6 +307,33 @@ unsigned int sep_tk_blob_len(const struct trusted_key_payload *p); void sep_tk_set_blob_len(struct trusted_key_payload *p, unsigned int n); +/* -- hdcp_shim.c ------------------------------------------------------- */ + +enum sep_hdcp_step { + SEP_HDCP_STEP_OPEN = 0, + SEP_HDCP_STEP_AKE_CERT = 1, + SEP_HDCP_STEP_H_PRIME = 2, + SEP_HDCP_STEP_PAIRING = 3, + SEP_HDCP_STEP_LC_INIT = 4, + SEP_HDCP_STEP_L_PRIME = 5, + SEP_HDCP_STEP_SKE = 6, + SEP_HDCP_STEP_RECEIVER_LIST = 7, + SEP_HDCP_STEP_STREAM = 8, + SEP_HDCP_STEP_FINISH = 9, + SEP_HDCP_STEP_ENCRYPTION_ON = 10, + SEP_HDCP_STEP_ENCRYPTION_OFF = 11, +}; + +struct sep_hdcp_ops { + bool (*available)(void *context); + int (*step)(void *context, u32 channel, u32 step, const u8 *in, + size_t in_len, u8 *out, size_t out_len); + void (*close)(void *context, u32 channel); +}; + +int sep_hdcp_register(void *context, const struct sep_hdcp_ops *ops); +void sep_hdcp_unregister(void *context); + /* Initrd attach and completion; sysfs removal drains the callback. */ bool sep_keystore_only(void); bool sep_keystore_user_bags(void); diff --git a/tools/aurora-sep/tests/test_hdcp_client.py b/tools/aurora-sep/tests/test_hdcp_client.py new file mode 100644 index 00000000000000..29f09f3f38a885 --- /dev/null +++ b/tools/aurora-sep/tests/test_hdcp_client.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""Host checks for the Apple SEP HDCP 2.2 transmitter client.""" +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[3] +APPLE = ROOT / "drivers/soc/apple" +HEADER = ROOT / "include/linux/apple-sep-hdcp.h" + + +class HdcpClientChecks(unittest.TestCase): + def test_header_has_disabled_stubs_for_every_declared_api(self): + text = HEADER.read_text() + self.assertIn("#if IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE)", text) + self.assertIn("#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */", text) + enabled, disabled = text.split( + "#else /* !IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE) */", 1 + ) + decl_re = re.compile(r"\b(apple_sep_hdcp_\w+)\s*\(") + enabled_fns = set(decl_re.findall(enabled)) + disabled_fns = set(decl_re.findall(disabled)) + self.assertGreaterEqual(len(enabled_fns), 13) + self.assertEqual(enabled_fns, disabled_fns) + + def test_sep_wires_hdcp_lifecycle_and_forgets_registered_ool(self): + sep = (APPLE / "sep.rs").read_text() + self.assertIn("mod hdcp;", sep) + self.assertIn("hdcp::EP_HDCP => self.on_hdcp(msg),", sep) + self.assertIn("self.hdcp_discovered(&f);", sep) + self.assertIn("data.register_hdcp_kernel()", sep) + self.assertIn("self.unregister_hdcp_kernel();", sep) + remove_fn = sep[sep.index("fn remove(&self)"):] + self.assertIn("self.hdcp_wq.notify_all();", remove_fn) + self.assertIn("&self.ool_hdcp,", remove_fn) + + def test_hdcp_uses_runtime_enumeration_and_ool_sync(self): + hdcp = (APPLE / "hdcp.rs").read_text() + self.assertIn("Command::QueryChannels", hdcp) + self.assertIn("Command::GetChannelInfo", hdcp) + self.assertIn("ool_repoison(&sep.ool_hdcp", hdcp) + self.assertIn("ool_await_written(&sep.ool_hdcp", hdcp) + self.assertIn("hdcp_scrub_buffers", hdcp) + self.assertIn("PHASE_READY", hdcp) + self.assertIn("pm::SleepGate::Open", hdcp) + + def test_shim_scrubs_buffers(self): + shim = (APPLE / "hdcp_shim.c").read_text() + self.assertIn("kfree_sensitive(in);", shim) + self.assertIn("memzero_explicit(", shim) + + +if __name__ == "__main__": + unittest.main() From 43a28f33c45c014695d9cf6936b71c715e591987 Mon Sep 17 00:00:00 2001 From: termg Date: Thu, 26 Nov 2026 14:05:05 +0000 Subject: [PATCH 1433/1514] dt-checks: compare undocumented properties one by one A "does not match any of the regexes" warning lists every undocumented property of a node on one line. When a change documents one of them, the line for that node changes, and the line diff counts the shorter list as a new warning although nothing was added: documenting apple,idleoff-standby-timer in apple,agx.yaml reports the t6021-j475c, t6022-j180d and t6022-j475d GPU nodes as new. Split such warnings into one line per property before the comparison, so only a property that HEAD adds is new. Run the script in the C locale: sort and comm must agree on the order, and in en_US.UTF-8 they do not for these lines. On linux#2093's head against main that gives 0 new and 8 removed instead of 3 new. Signed-off-by: termg --- scripts/dtc/apple-dt-check.sh | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index d6f30d6b440e5b..971a7dd8287d60 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -15,6 +15,8 @@ set -u BASE=$1 HEAD=$2 W=$3 export ARCH=arm64 LLVM=1 +# sort and comm must agree on the order: some UTF-8 locales collate these lines differently. +export LC_ALL=C mkdir -p "$W" filter_documented_chosen() { # chosen_bindings_dir python3 -c ' @@ -139,6 +141,29 @@ extract_warnings() { # src_dir out_dir log_file out_warn tag filter_failed=1 return 1 fi + # One line per undocumented property, so documenting one of a node's properties does not + # turn that node's remaining ones into a "new" warning. + python3 -c ' +import re, sys +pat = re.compile(r"^(.*?: )(\x27[^\x27]+\x27(?:, \x27[^\x27]+\x27)*) do(?:es)? not match any of the regexes:(.*)$") +for line in open(sys.argv[1]): + line = line.rstrip("\n") + m = pat.match(line) + if not m: + print(line) + continue + prefix, props, tail = m.groups() + for prop in re.findall(r"\x27[^\x27]+\x27", props): + print(prefix + prop + " does not match any of the regexes:" + tail) +' "$out" | sort -u > "$out.split" + local sp=("${PIPESTATUS[@]}") + if [ "${sp[0]}" -ne 0 ] || [ "${sp[1]}" -ne 0 ]; then + rm -f "$out" "$out.split" + echo "apple-dt-check.sh: $tag: splitting property warnings failed" >&2 + filter_failed=1 + return 1 + fi + mv "$out.split" "$out" } warnings() { # rev tag local t=$W/src-$2 o=$W/out-$2 From 1e5eebd9656d40c97ded224da4418f996b0b2bc4 Mon Sep 17 00:00:00 2001 From: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:27:26 -0500 Subject: [PATCH 1434/1514] drm/apple: refuse panel brightness once the display processor crashed A panel that presents its level in the swap gets a new level only with a present. Once the IOMFB queue has timed out and marked the processor crashed, every present is discarded, but brightness writes were still accepted and actual_brightness kept reporting the last requested level, so userspace saw a level change that never reached the panel. Fail both with -EIO while the processor is crashed, as the DAC fade and the deferred brightness present already stop there. The desktop panel host test checks that a crashed processor reports no level, refuses a write without changing the requested one, and takes the next write once it is no longer crashed. Signed-off-by: Rolando Trevino <122947376+rolotrealanis98@users.noreply.github.com> --- drivers/gpu/drm/apple/dcp_backlight.c | 6 ++++++ .../selftests/drivers/gpu/apple-dcp/desktop.py | 13 ++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/dcp_backlight.c b/drivers/gpu/drm/apple/dcp_backlight.c index 1019180517bed8..5746c318e54cd0 100644 --- a/drivers/gpu/drm/apple/dcp_backlight.c +++ b/drivers/gpu/drm/apple/dcp_backlight.c @@ -252,6 +252,9 @@ static int dcp_get_brightness(struct backlight_device *bd) if (READ_ONCE(dcp->quiescing)) return -ENODEV; + /* Nothing is presented any more: there is no level to report. */ + if (READ_ONCE(dcp->crashed)) + return -EIO; if (dcp_backlight_active(dcp) || dcp_backlight_desktop(dcp)) { /* @@ -885,6 +888,9 @@ static int dcp_set_brightness(struct backlight_device *bd) if (READ_ONCE(dcp->quiescing)) return -ENODEV; + /* A crashed processor discards every present, the level with it. */ + if (READ_ONCE(dcp->crashed)) + return -EIO; if (dcp_backlight_active(dcp) || dcp_backlight_desktop(dcp)) { struct dcp_backlight_state *state = &dcp->backlight.state; diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py index 1eb7f35674986c..6bbc105f111bd4 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py @@ -242,7 +242,7 @@ def brightness_takeover(root): struct backlight_properties {int type,brightness,max_brightness,scale,state;}; struct backlight_device {struct backlight_properties props;void *data;bool ops_lock;}; struct apple_dcp { - int fw_compat;bool quiescing; + int fw_compat;bool quiescing,crashed; struct {int iomfb_method_profile;} hw; struct {u32 maximum,nits,dac;bool update;struct backlight_device *bl_dev; u32 level,fade_from,fade_to;bool fading;unsigned long fade_start;int fade_work; @@ -351,6 +351,17 @@ def brightness_takeover(root): assert(dcp_get_brightness(&dac_bl)==0); dcp_backlight_presented(&dac,500); assert(dcp_get_brightness(&dac_bl)==500 && !dac.backlight.lock); + /* + * A crashed processor discards every present: no level is reported, and + * a new level is refused without changing the requested one. + */ + struct dcp_backlight_state before=d.backlight.state; + d.crashed=true;registered.props.brightness=200; + assert(dcp_get_brightness(®istered)==-EIO); + assert(dcp_set_brightness(®istered)==-EIO); + assert(!memcmp(&before,&d.backlight.state,sizeof(before)) && !d.backlight.lock); + d.crashed=false; + assert(!dcp_set_brightness(®istered) && d.backlight.state.target==200); return 0; } ''' From 1c4e83a177e2ae03e23fde995f18d63768a7f9d1 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 10:40:42 -0500 Subject: [PATCH 1435/1514] drm/asahi: advertise DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS When a render pass loads an attachment written by an earlier render pass, userspace previously waited on the earlier pass in both tiling and fragment halves out of concern that a partial render triggered by tiler-heap overflow could execute or store before the earlier render's fragment pass completed. Add DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS (bit 45) to advertise that every fragment pass of a render command, including partial renders triggered by tiler-heap overflow, starts only after the fragment work its fragment half is ordered after has completed. On G17, advertise the bit only where firmware drains outstanding fragment passes (variant.fragment_busy) and each logical render queue runs on a single physical render pair (pairs::per_owner() == 1). Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/mod.rs | 13 +++++++++++++ include/uapi/drm/asahi_drm.h | 12 ++++++++++++ 2 files changed, 25 insertions(+) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 68167f1740256b..f30bdc97d0b474 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1201,6 +1201,17 @@ fn compute_channel_features(channels: u8) -> u64 { } } +/// Whether the firmware keeps partial renders (tiler-heap overflow fragment passes) strictly +/// ordered behind earlier fragment work: advertised where `fragment_busy` drains an outstanding +/// fragment pass on the pair and each logical render queue uses a single physical render pair. +fn ordered_partial_renders_feature(fragment_busy: bool, render_pairs: u8) -> u64 { + if fragment_busy && render_pairs == 1 { + uapi::DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS as u64 + } else { + 0 + } +} + /// Event work item ID. const EVENT_WORK: u64 = 0; /// Short control/retirement polls do not wait behind the longer idle deadline. @@ -2895,6 +2906,8 @@ impl gpu::Gpu for Gpu { | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT | compute_channel_features(pairs::compute_channels_per_owner()); let variant = self.shared.variant; + params.features |= + ordered_partial_renders_feature(variant.fragment_busy, pairs::per_owner()); // The M5 command set has no AS-build flag: its validation refuses one. if !variant.m5_commands { params.features |= u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_BOUNDED_AS_BUILD); diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index ec3de5c4356886..dd79dfb569bdc1 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -593,6 +593,18 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS ((1ULL) << 44) +/* + * DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS: every fragment pass of a render + * command, including partial renders the firmware runs when the tiler heap + * fills, starts only after the fragment work its fragment half is ordered + * after has completed: the earlier fragment work of its physical queue and + * the renders named by its fragment barriers. Userspace may then order a + * render's attachment loads and stores against an earlier render with + * fragment-stage ordering alone, without a tiling-half wait. A feature bit + * like those of enum drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS ((1ULL) << 45) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 From c02408dec10fbbf05170532a1e0ace5da778639a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 03:20:05 +1100 Subject: [PATCH 1436/1514] soc: apple: sep: support sparse HDCP channel tables and log failed replies Command 0x28 (GetChannelInfo) is indexed by interface slot 0..count-1 from command 0x27, while info[0] carries the interface's actual HDCP channel ID. On T6040 the 14 interfaces advertise channel IDs 0..5 and 7..14 (skipping channel 6), so requiring info[0] == index rejected enumeration with -EIO on every attempt. Record the enumerated channel IDs in a bitmask so sparse channel sets are validated accurately against hardware-reported IDs, extend KUnit with a sparse-table case, and log unexpected reply words (status/length only, never payload bytes) plus OOL registration failures. Signed-off-by: Ryan Murray --- drivers/soc/apple/hdcp.rs | 141 ++++++++++++++++++++++++++++++-------- 1 file changed, 111 insertions(+), 30 deletions(-) diff --git a/drivers/soc/apple/hdcp.rs b/drivers/soc/apple/hdcp.rs index a6b67f19a43530..29d2aada55baca 100644 --- a/drivers/soc/apple/hdcp.rs +++ b/drivers/soc/apple/hdcp.rs @@ -526,10 +526,11 @@ impl Session { } } -/// The endpoint: probed channel count, a session per slot, and whether it is -/// quarantined. +/// The endpoint: probed channel bitmask, a session per slot, and whether it is +/// quarantined. Channel IDs returned by command `0x28` may be sparse (e.g. an +/// absent channel ID with higher channel IDs above the interface count). pub(crate) struct State { - pub(crate) channel_count: Option, + pub(crate) channel_mask: Option, pub(crate) sessions: [Session; MAX_CHANNELS], pub(crate) quarantined: bool, } @@ -537,15 +538,18 @@ pub(crate) struct State { impl State { pub(crate) const fn new() -> State { State { - channel_count: None, + channel_mask: None, sessions: [Session::new(); MAX_CHANNELS], quarantined: false, } } - /// Channels known to the enclave once enumerated. - pub(crate) fn channels(&self) -> usize { - self.channel_count.map_or(0, usize::from) + /// Whether `slot` is an enumerated HDCP channel on this enclave. + pub(crate) fn has_channel(&self, slot: u8) -> bool { + usize::from(slot) < MAX_CHANNELS + && self + .channel_mask + .is_some_and(|mask| (mask & (1u32 << slot)) != 0) } } @@ -686,14 +690,15 @@ pub(crate) trait Transport { fn on_quarantine(&self, _slot: u8, _command: Command) {} } -/// Queries the enclave's HDCP interface count (`0x27`) and per-channel -/// descriptors (`0x28`), once per boot before any session opens. -pub(crate) fn enumerate(t: &T, state: &mut State) -> Result { +/// Queries the enclave's HDCP interface count (`0x27`) and per-interface +/// descriptors (`0x28`), once per boot before any session opens. Returns the +/// bitmask of advertised channel IDs (`info[0]` per interface index). +pub(crate) fn enumerate(t: &T, state: &mut State) -> Result { if state.quarantined { return Err(EIO); } - if let Some(count) = state.channel_count { - return Ok(count); + if let Some(mask) = state.channel_mask { + return Ok(mask); } let outcome = match t.exchange(0, Command::QueryChannels, 0, &[], &mut []) { Ok(o) => o, @@ -707,23 +712,29 @@ pub(crate) fn enumerate(t: &T, state: &mut State) -> Result { let Outcome::ChannelCount(count) = outcome else { return Err(EIO); }; - for slot in 0..count { + let mut mask = 0u32; + for index in 0..count { let mut info = [0u8; CHANNEL_INFO_LEN]; - let o = match t.exchange(slot, Command::GetChannelInfo, 0, &[], &mut info) { + let o = match t.exchange(index, Command::GetChannelInfo, 0, &[], &mut info) { Ok(o) => o, Err(e) => return Err(e), }; if o == Outcome::NoReply { state.quarantined = true; - t.on_quarantine(slot, Command::GetChannelInfo); + t.on_quarantine(index, Command::GetChannelInfo); return Err(EIO); } - if o != Outcome::Done(CHANNEL_INFO_LEN) || info[0] != slot { + let ch = info[0]; + if o != Outcome::Done(CHANNEL_INFO_LEN) || usize::from(ch) >= MAX_CHANNELS { return Err(EIO); } + mask |= 1u32 << ch; } - state.channel_count = Some(count); - Ok(count) + if mask == 0 { + return Err(EIO); + } + state.channel_mask = Some(mask); + Ok(mask) } /// Sends one session command on `slot` if the session allows it, and records @@ -740,10 +751,10 @@ fn run( if state.quarantined { return Err(EIO); } - let i = usize::from(slot); - if i >= state.channels() { + if !state.has_channel(slot) { return Err(EINVAL); } + let i = usize::from(slot); if !state.sessions[i].allows(command, arg) { return Err(EPROTO); } @@ -788,11 +799,11 @@ pub(crate) fn step( if !step.sizes_ok(inp.len(), out.len()) { return Err(EINVAL); } - let count = enumerate(t, state)?; - let i = usize::from(slot); - if i >= usize::from(count) { + enumerate(t, state)?; + if !state.has_channel(slot) { return Err(EINVAL); } + let i = usize::from(slot); let was_open = state.sessions[i].is_open(); let r = step_inner(t, state, slot, step, inp, out); if r.is_err() { @@ -893,8 +904,11 @@ fn step_inner( /// Ends the session on `slot` from any state: encryption off, then close. /// The local session is reset whatever the enclave answers. pub(crate) fn close(t: &T, state: &mut State, slot: u8) { + if !state.has_channel(slot) { + return; + } let i = usize::from(slot); - if i >= state.channels() || !state.sessions[i].is_open() { + if !state.sessions[i].is_open() { return; } if !state.quarantined { @@ -963,6 +977,31 @@ impl Transport for Mailbox<'_> { } other => other, }; + // Log non-success replies using only the mailbox word (status/len), + // never any out-of-line payload bytes. + match final_outcome { + Outcome::Done(_) | Outcome::NotStored | Outcome::ChannelCount(_) => {} + Outcome::Refused(_) if spec_of(command).verifies => { + dev_dbg!( + sep.dev, + "hdcp: command {:#04x} channel {}: verification refused (reply {:#018x})\n", + spec_of(command).id, + slot, + reply.msg0 + ); + } + other => { + dev_warn_ratelimited!( + sep.dev, + "hdcp: command {:#04x} channel {}: {:?} (reply {:#018x}, expected {} out)\n", + spec_of(command).id, + slot, + other, + reply.msg0, + out.len() + ); + } + } sep.hdcp_scrub_buffers(input.len(), out.len()); Ok(final_outcome) } @@ -1077,6 +1116,11 @@ impl SepData { fn hdcp_ready(&self) -> Result { self.hdcp_ready_state()?; self.register_ool(&self.ool_hdcp).map_err(|e| { + dev_warn_ratelimited!( + self.dev, + "hdcp: out-of-line buffer registration failed ({:?})\n", + e + ); if e == EAGAIN || e == ENODEV { e } else { @@ -1380,6 +1424,7 @@ mod tests { /// was sent. struct Fake { replies: RefCell>, + channel_ids: RefCell>, sent: RefCell>, next: Cell, quarantined: Cell, @@ -1393,12 +1438,21 @@ mod tests { } Fake { replies: RefCell::new(v), + channel_ids: RefCell::new(KVec::new()), sent: RefCell::new(KVec::new()), next: Cell::new(0), quarantined: Cell::new(false), } } + fn with_channel_ids(replies: &[u64], ids: &[u8]) -> Fake { + let f = Fake::new(replies); + for &id in ids { + f.channel_ids.borrow_mut().push(id, GFP_KERNEL).unwrap(); + } + f + } + fn sent(&self) -> KVec { let mut v = KVec::new(); for s in self.sent.borrow().iter() { @@ -1433,7 +1487,8 @@ mod tests { } if command == Command::GetChannelInfo { out.fill(0); - out[0] = slot; + let ids = self.channel_ids.borrow(); + out[0] = ids.get(usize::from(slot)).copied().unwrap_or(slot); } else { out.fill(0x5c); } @@ -1454,7 +1509,7 @@ mod tests { fn state_with_channels(n: u8) -> State { let mut st = State::new(); - st.channel_count = Some(n); + st.channel_mask = Some((1u32 << n) - 1); st } @@ -1489,7 +1544,7 @@ mod tests { assert_eq!(ool_sizes(0x0202_0202), None); assert_eq!(ool_sizes(0), None); - // Enclave advertises 9 channels (as on T8112); slot 8 succeeds, slot 9 fails. + // Enclave advertises 9 contiguous channels (as on T8112); slot 8 ok, slot 9 EINVAL. let mut replies = KVec::new(); replies.push(0x0000_0009_0000_000e, GFP_KERNEL)?; for _ in 0..9 { @@ -1497,16 +1552,42 @@ mod tests { } let t = Fake::new(&replies); let mut st = State::new(); - assert_eq!(enumerate(&t, &mut st)?, 9); - assert_eq!(st.channels(), 9); + assert_eq!(enumerate(&t, &mut st)?, 0x1ff); + assert!(st.has_channel(8)); + assert!(!st.has_channel(9)); // Second enumeration is cached (no further mailbox traffic). - assert_eq!(enumerate(&t, &mut st)?, 9); + assert_eq!(enumerate(&t, &mut st)?, 0x1ff); assert_eq!(t.sent().len(), 10); assert_eq!( step(&t, &mut st, 9, Step::Open, &[], &mut [0; RTX_LEN]), Err(EINVAL) ); assert_eq!(t.sent().len(), 10); + + // Sparse channel table (14 interfaces: 0..=5 and 7..=14, skipping 6, + // as on T6040): channel 6 is refused, channels 7 and 14 are accepted. + let sparse_ids: [u8; 14] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]; + let mut sparse_replies = KVec::new(); + sparse_replies.push(0x0000_000e_0000_000e, GFP_KERNEL)?; + for _ in 0..14 { + sparse_replies.push(ok_for(Command::GetChannelInfo), GFP_KERNEL)?; + } + for c in [Command::Open, Command::Prepare, Command::Start, Command::GetRtx] { + sparse_replies.push(ok_for(c), GFP_KERNEL)?; + } + let ts = Fake::with_channel_ids(&sparse_replies, &sparse_ids); + let mut sts = State::new(); + let mask = enumerate(&ts, &mut sts)?; + assert!(!sts.has_channel(6)); + assert!(sts.has_channel(7)); + assert!(sts.has_channel(14)); + assert!(!sts.has_channel(15)); + assert_eq!(mask, 0x7fbf); + assert_eq!( + step(&ts, &mut sts, 6, Step::Open, &[], &mut [0; RTX_LEN]), + Err(EINVAL) + ); + step(&ts, &mut sts, 14, Step::Open, &[], &mut [0; RTX_LEN])?; Ok(()) } From 4d781f74b6e9ef46c5d8bcc0e27e056bef3e83e8 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 11:57:50 -0500 Subject: [PATCH 1437/1514] arm64: dts: apple: t8103-j313: the SMC's wake reasons Without apple,wake-reasons, macsmc numbers the J313's wake record with the T8140 table, which does not match this board: the lid is bit 8, not 10, the charger bit 9 and the radio bit 12, not 18 and 23, and the keyboard and trackpad's bit 21 has no name at all. So a wake for the lid alone is not seen as one, the radio's wake is looked for in the wrong bit, and the log names the wrong reasons or none. Describe the bits as the J313 ADT's smc-pmu node numbers them (event_name-bitN). Signed-off-by: Erik Bourget --- arch/arm64/boot/dts/apple/t8103-j313.dts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8103-j313.dts b/arch/arm64/boot/dts/apple/t8103-j313.dts index 671d7cd6e800d9..87e12d3e70680d 100644 --- a/arch/arm64/boot/dts/apple/t8103-j313.dts +++ b/arch/arm64/boot/dts/apple/t8103-j313.dts @@ -183,6 +183,14 @@ status = "okay"; }; +/* The SMC's wake reasons (ADT smc-pmu, event_name-bitN) */ +&smc { + apple,wake-reasons = <0 8 9 11 12 21 40 41 42 43 44 45 48>; + apple,wake-reason-names = "pwrbtn", "lid", "charger", "codec", "wifibt", + "trackpadkeyboard", "acattach", "acdetach", "USB-C_plug", + "USB2_plug", "USB2_wake", "aupo", "rtc"; +}; + /* The port controllers' system power state: S3 before a firmware-driven sleep, S0 after it */ &hpm0 { apple,sleep-ssps; From f923c3868957ac4476ab918be517078f8d54c77e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 04:16:59 +1100 Subject: [PATCH 1438/1514] drm/apple: audio: end a stream whose service instance was replaced The firmware publishes a successor of the DP audio service whenever the display link is set up again, also with the sink connected throughout. The successor comes up plugged, so the card sees no unplug and a running stream is not stopped. The link the stream started on went with the old instance: its DMA stops and the stream waits in RUNNING until the PCM is reopened. On the M2 Mac mini (firmware 27.2) this happens after every short system sleep. The HDMI monitor drops HPD for ~1.7 s as it wakes, and ~10.7 s after the resume the firmware announces DCPAVAudioInterface on a new channel. A stream started in between stops after ~1.5 s. Record the instance a stream's link starts on, read under the lock the start call takes the instance with. Each newly opened instance connects the card; a stream still running on an older instance then ends as an xrun, and userspace prepares it again on the successor. A stream playing into the void (no sink) has no link and is left alone. The instance comes from the service's own generation count, not from a firmware or board test. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio-legacy-test.c | 101 +++++++++++++++++++++- drivers/gpu/drm/apple/audio.c | 47 +++++++++- drivers/gpu/drm/apple/audio.h | 2 +- drivers/gpu/drm/apple/av.c | 16 +++- 4 files changed, 159 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/apple/audio-legacy-test.c b/drivers/gpu/drm/apple/audio-legacy-test.c index fb082c244ee2b4..99249c702a36d5 100644 --- a/drivers/gpu/drm/apple/audio-legacy-test.c +++ b/drivers/gpu/drm/apple/audio-legacy-test.c @@ -20,6 +20,8 @@ struct dcpaud_legacy_test { /* The runtime PM usage count when the terminate was waited for */ int usage_at_drain; int startlink_err; + /* The published service instance, as dcp_audiosrv_instance() reports it */ + u64 instance; size_t elements_asked; size_t catalog; struct device *dev; @@ -76,8 +78,10 @@ static enum dma_status dcpaud_legacy_status(struct dma_chan *chan, dma_cookie_t return DMA_COMPLETE; } -static int dcpaud_legacy_startlink(struct device *dev, struct dcp_sound_cookie *cookie) +static int dcpaud_legacy_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen) { + if (gen) + *gen = dcpaud_legacy_current->instance; dcpaud_legacy_record('T'); return dcpaud_legacy_current->startlink_err; } @@ -241,6 +245,96 @@ static void dcpaud_legacy_void_takes_no_reference(struct kunit *test) KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +static u64 dcpaud_legacy_instance(struct device *dev) +{ + return dcpaud_legacy_current->instance; +} + +/* A started stream, RUNNING as the PCM core has it, on service instance 5 */ +static struct snd_pcm_substream *dcpaud_legacy_running(struct kunit *test, + struct dcp_audio **audio) +{ + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, audio); + struct snd_pcm_runtime *runtime = sub->runtime; + + runtime->status = kunit_kzalloc(test, sizeof(*runtime->status), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, runtime->status); + init_waitqueue_head(&runtime->sleep); + init_waitqueue_head(&runtime->tsleep); + sub->ops = &dcp_playback_ops; + INIT_WORK(&(*audio)->replaced_work, dcpaud_replaced_work); + dcpaud_legacy_current->instance = 5; + kunit_activate_static_stub(test, dcp_audiosrv_instance, dcpaud_legacy_instance); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + runtime->state = SNDRV_PCM_STATE_RUNNING; + runtime->status->state = SNDRV_PCM_STATE_RUNNING; + return sub; +} + +/* + * The firmware published a successor of the service with the sink still + * connected: the stream's link went with the old instance. The connect that + * follows the successor's Open ends the stream as an xrun (DMA terminate and + * link stop, as on any STOP); sync_stop then puts the PM reference. + */ +static void dcpaud_legacy_replaced_instance_ends_stream(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_running(test, &audio); + + KUNIT_EXPECT_EQ(test, audio->start_gen, 5ULL); + dcpaud_legacy_current->instance = 6; + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_XRUN); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQXS"); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); + + /* Prepared again by userspace, the next START is the successor's */ + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + KUNIT_EXPECT_EQ(test, audio->start_gen, 6ULL); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); +} + +/* A connect with the stream's own instance still published leaves it playing */ +static void dcpaud_legacy_same_instance_keeps_stream(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_running(test, &audio); + + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_RUNNING); + KUNIT_EXPECT_STREQ(test, dcpaud_legacy_current->sequence, "TQ"); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); + KUNIT_EXPECT_EQ(test, dcpaud_legacy_usage(audio), 0); +} + +/* A stream playing into the void has no link to lose */ +static void dcpaud_legacy_replaced_instance_keeps_void(struct kunit *test) +{ + struct dcp_audio *audio; + struct snd_pcm_substream *sub = dcpaud_legacy_setup(test, &audio); + + sub->runtime->status = kunit_kzalloc(test, sizeof(*sub->runtime->status), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sub->runtime->status); + sub->ops = &dcp_playback_ops; + INIT_WORK(&audio->replaced_work, dcpaud_replaced_work); + kunit_activate_static_stub(test, dcp_audiosrv_instance, dcpaud_legacy_instance); + audio->open_unplugged = true; + sub->runtime->period_size = 480000; + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_START), 0); + sub->runtime->state = SNDRV_PCM_STATE_RUNNING; + dcpaud_legacy_current->instance = 6; + dcpaud_replaced_work(&audio->replaced_work); + KUNIT_EXPECT_EQ(test, (int)sub->runtime->state, (int)SNDRV_PCM_STATE_RUNNING); + KUNIT_ASSERT_EQ(test, dcp_pcm_trigger(sub, SNDRV_PCM_TRIGGER_STOP), 0); + KUNIT_ASSERT_EQ(test, dcp_pcm_sync_stop(sub), 0); +} +#endif + static int dcpaud_legacy_get_elements(struct device *dev, void *elements, size_t maxsize) { struct dcpaud_legacy_test *t = dcpaud_legacy_current; @@ -291,6 +385,11 @@ static struct kunit_case dcpaud_legacy_cases[] = { KUNIT_CASE(dcpaud_legacy_failed_start), KUNIT_CASE(dcpaud_legacy_void_takes_no_reference), KUNIT_CASE(dcpaud_legacy_elements_capacity), +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + KUNIT_CASE(dcpaud_legacy_replaced_instance_ends_stream), + KUNIT_CASE(dcpaud_legacy_same_instance_keeps_stream), + KUNIT_CASE(dcpaud_legacy_replaced_instance_keeps_void), +#endif {} }; diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index d425e0fe88b9fa..4f68fdce1c3905 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -108,6 +108,12 @@ struct dcp_audio { struct delayed_work void_work; /* The stream holds a runtime PM reference, put in sync_stop; stream lock */ bool pm_held; + /* The service instance the stream's link started on; stream lock */ + u64 start_gen; +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* Ends a stream on a replaced instance, see dcpaud_replaced_work() */ + struct work_struct replaced_work; +#endif void *elements; void *productattrs; @@ -738,7 +744,7 @@ static int dcp_pcm_trigger(struct snd_pcm_substream *substream, int cmd) dcpaud->pm_held = true; } ret = dcp_audiosrv_startlink(dcpaud->dcp_dev, - &dcpaud->selected_cookie); + &dcpaud->selected_cookie, &dcpaud->start_gen); if (ret < 0) return ret; break; @@ -1905,6 +1911,36 @@ static int dcpaud_init_snd_card(struct dcp_audio *dcpaud) return ret; } +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) +/* + * The firmware publishes a successor of the audio service while the display + * link is set up again, also with the sink connected throughout (after a + * wake, the monitor's HPD pulse). The successor comes up plugged, so the card + * sees no unplug; the link a running stream started on went with the old + * instance, its DMA stops and the stream would wait forever. It ends as an + * xrun instead, and userspace prepares it again on the successor. + */ +static void dcpaud_replaced_work(struct work_struct *work) +{ + struct dcp_audio *dcpaud = container_of(work, struct dcp_audio, replaced_work); + struct snd_pcm_substream *substream = dcpaud->substream; + + if (!substream || !dcpaud->dcp_dev) + return; + /* + * Under the stream lock (a mutex: the PCM is nonatomic), as START + * takes the instance under it: no START completes in between. + */ + snd_pcm_stream_lock_irq(substream); + if (substream->runtime && snd_pcm_running(substream) && !dcpaud->void_running && + dcpaud->start_gen != dcp_audiosrv_instance(dcpaud->dcp_dev)) { + dev_dbg(dcpaud->dev, "stream's link went with its service\n"); + snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN); + } + snd_pcm_stream_unlock_irq(substream); +} +#endif + void dcpaud_connect(struct platform_device *pdev, bool connected) { struct dcp_audio *dcpaud = platform_get_drvdata(pdev); @@ -1918,6 +1954,11 @@ void dcpaud_connect(struct platform_device *pdev, bool connected) mutex_lock(&dcpaud->data_lock); dcpaud_report_hotplug(dcpaud, connected, eld); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* A connect follows each newly opened instance; see dcpaud_replaced_work() */ + if (connected && !dcpaud->native_link && dcpaud->card) + schedule_work(&dcpaud->replaced_work); +#endif } /* @@ -2075,6 +2116,9 @@ static void dcpaud_comp_unbind(struct device *dev, struct device *main, { struct dcp_audio *dcpaud = dev_get_drvdata(dev); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + cancel_work_sync(&dcpaud->replaced_work); +#endif /* snd_card_free_when_closed() checks for NULL */ snd_card_free_when_closed(dcpaud->card); @@ -2143,6 +2187,7 @@ static int dcpaud_probe(struct platform_device *pdev) #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) mutex_init(&dcpaud->link_lock); INIT_WORK(&dcpaud->stale_work, dcpaud_stale_work); + INIT_WORK(&dcpaud->replaced_work, dcpaud_replaced_work); #endif INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); platform_set_drvdata(pdev, dcpaud); diff --git a/drivers/gpu/drm/apple/audio.h b/drivers/gpu/drm/apple/audio.h index 6d60750cc315ae..189abae53b073e 100644 --- a/drivers/gpu/drm/apple/audio.h +++ b/drivers/gpu/drm/apple/audio.h @@ -8,7 +8,7 @@ struct platform_device; struct dcp_sound_cookie; int dcp_audiosrv_prepare(struct device *dev, struct dcp_sound_cookie *cookie); -int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie); +int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen); int dcp_audiosrv_stoplink(struct device *dev); int dcp_audiosrv_unprepare(struct device *dev); int dcp_audiosrv_get_elements(struct device *dev, void *elements, size_t maxsize); diff --git a/drivers/gpu/drm/apple/av.c b/drivers/gpu/drm/apple/av.c index c147284af2402a..3496f5ccdfb50d 100644 --- a/drivers/gpu/drm/apple/av.c +++ b/drivers/gpu/drm/apple/av.c @@ -264,16 +264,21 @@ int dcp_audiosrv_prepare(struct device *dev, struct dcp_sound_cookie *cookie) return ret; } -int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie) +/* @gen: the instance the link starts on (dcp_audiosrv_instance()), or NULL */ +int dcp_audiosrv_startlink(struct device *dev, struct dcp_sound_cookie *cookie, u64 *gen) { struct apple_dcp *dcp; struct audiosrv_data *asrv; int ret; - KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_startlink, dev, cookie); + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_startlink, dev, cookie, gen); dcp = dev_get_drvdata(dev); asrv = dcp->audiosrv; down_write(&asrv->srv_rwsem); +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + if (gen) + *gen = asrv->gen; +#endif ret = afk_service_call(asrv->srv, 0, asrv->cmds.start_link, cookie, sizeof(*cookie), 64 - sizeof(*cookie), NULL, 0, 64); @@ -361,9 +366,12 @@ static int av_audiosrv_call(struct apple_epic_service *srv, u32 command, const v /* The audio service instance now published, as dcp_audiosrv_replaced() takes it. */ u64 dcp_audiosrv_instance(struct device *dev) { - struct apple_dcp *dcp = dev_get_drvdata(dev); - struct audiosrv_data *asrv = dcp->audiosrv; + struct apple_dcp *dcp; + struct audiosrv_data *asrv; + KUNIT_STATIC_STUB_REDIRECT(dcp_audiosrv_instance, dev); + dcp = dev_get_drvdata(dev); + asrv = dcp->audiosrv; if (!asrv) return 0; guard(rwsem_read)(&asrv->srv_rwsem); From 6125e3d724b0aa9b089151dd0f965121c032da9c Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 12:23:09 -0500 Subject: [PATCH 1439/1514] soc: apple: clpc: use per-CPU deferrable timers when idle on idle_on_time SoCs On idle_on_time SoCs with PMC sampling, replace the continuous 4 ms idle sampling timer while no floor vote is held with per-CPU pinned deferrable timers (minimum 2 jiffies step) whenever nohz_full is not enabled. Idle NO_HZ CPUs take zero CLPC wakeups while any busy CPU kicks active sampling once its tick resumes. Preserve any fresh client demand already queued on clpc->work when entering idle, serialize timer drain/re-arm with CPU hotplug and halt via a dedicated idle_lock (ordered inside cpuhp and sample_lock) and an idle_online_cpus mask so teardown never migrates a pinned timer and newly onlined CPUs start with a fresh baseline, and refresh the baseline on backwards or invalid idle deltas. Signed-off-by: Erik Bourget --- drivers/soc/apple/clpc.c | 256 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 248 insertions(+), 8 deletions(-) diff --git a/drivers/soc/apple/clpc.c b/drivers/soc/apple/clpc.c index 958ee2cf65a403..92766cebffce3e 100644 --- a/drivers/soc/apple/clpc.c +++ b/drivers/soc/apple/clpc.c @@ -20,10 +20,14 @@ * Copyright The Asahi Linux Contributors */ +#include +#include +#include #include #include #include #include +#include #include #include #include @@ -40,6 +44,8 @@ #include #include #include +#include +#include #include #include #include @@ -198,14 +204,29 @@ struct apple_clpc_ane { struct delayed_work *wake; }; +struct apple_clpc; + +struct apple_clpc_idle_timer { + struct timer_list timer; + struct apple_clpc *clpc; + u64 last_idle; + u64 last_wall; +}; + struct apple_clpc { struct device *dev; struct device *pmc; const struct apple_clpc_hw *hw; unsigned int agent; - /* Samples while a vote is held; idle_work defers to busy CPUs. */ + /* Samples while a vote is held; idle_work or per-CPU idle_timers defer to busy CPUs. */ struct delayed_work work; struct delayed_work idle_work; + struct apple_clpc_idle_timer __percpu *idle_timers; + struct mutex idle_lock; + cpumask_t idle_online_cpus; + struct hlist_node cpuhp_node; + bool cpuhp_added; + atomic_t idle_armed; struct mutex sample_lock; bool stopped; struct apple_clpc_cluster clusters[APPLE_CLPC_MAX_CLUSTERS]; @@ -681,6 +702,131 @@ static u32 apple_clpc_floor(struct apple_clpc *clpc, const unsigned int *state) return floor; } +static enum cpuhp_state apple_clpc_cpuhp_state; + +static unsigned long apple_clpc_idle_step(void) +{ + return max_t(unsigned long, msecs_to_jiffies(APPLE_CLPC_SAMPLE_MS), 2); +} + +static void apple_clpc_idle_timer_fn(struct timer_list *timer) +{ + struct apple_clpc_idle_timer *t = timer_container_of(t, timer, timer); + struct apple_clpc *clpc = t->clpc; + unsigned int cpu = smp_processor_id(); + unsigned long step = apple_clpc_idle_step(); + u64 wall, idle, dw, di; + + if (READ_ONCE(clpc->stopped) || !atomic_read(&clpc->idle_armed)) + return; + + idle = get_cpu_idle_time(cpu, &wall, 0); + if (wall < t->last_wall || idle < t->last_idle) { + t->last_wall = wall; + t->last_idle = idle; + mod_timer(&t->timer, jiffies + step); + return; + } + dw = wall - t->last_wall; + if (dw < APPLE_CLPC_SAMPLE_MS * 1000ULL) { + mod_timer(&t->timer, jiffies + step); + return; + } + di = idle - t->last_idle; + t->last_wall = wall; + t->last_idle = idle; + + /* + * A CPU that only woke briefly for an IRQ or short timer stayed mostly + * idle (or an out-of-order iowait/idle read yielded di > dw); re-arm + * its pinned deferrable timer without waking a kworker. + */ + if (di > dw || (dw - di) * 100 < dw * APPLE_CLPC_BUSY_PCT) { + mod_timer(&t->timer, jiffies + step); + return; + } + + if (atomic_cmpxchg(&clpc->idle_armed, 1, 0) == 1) + mod_delayed_work(system_freezable_power_efficient_wq, + &clpc->work, 0); +} + +static int apple_clpc_cpu_online(unsigned int cpu, struct hlist_node *node) +{ + struct apple_clpc *clpc = hlist_entry_safe(node, struct apple_clpc, + cpuhp_node); + struct apple_clpc_idle_timer *t; + + if (!clpc || !clpc->idle_timers) + return 0; + + guard(mutex)(&clpc->idle_lock); + cpumask_set_cpu(cpu, &clpc->idle_online_cpus); + if (READ_ONCE(clpc->stopped) || !atomic_read(&clpc->idle_armed)) + return 0; + + t = per_cpu_ptr(clpc->idle_timers, cpu); + timer_delete_sync(&t->timer); + t->last_idle = get_cpu_idle_time(cpu, &t->last_wall, 0); + t->timer.expires = jiffies + apple_clpc_idle_step(); + add_timer_on(&t->timer, cpu); + return 0; +} + +static int apple_clpc_cpu_down(unsigned int cpu, struct hlist_node *node) +{ + struct apple_clpc *clpc = hlist_entry_safe(node, struct apple_clpc, + cpuhp_node); + + if (!clpc || !clpc->idle_timers) + return 0; + + /* Delete before CPU teardown migrates the pinned timer elsewhere. */ + guard(mutex)(&clpc->idle_lock); + cpumask_clear_cpu(cpu, &clpc->idle_online_cpus); + timer_delete_sync(&per_cpu_ptr(clpc->idle_timers, cpu)->timer); + return 0; +} + +/* + * Arm a pinned deferrable timer on every online CPU. Idle CPUs stay asleep + * (TIMER_DEFERRABLE never sends an IPI or wakes a NO_HZ CPU), while any busy + * CPU runs the callback once its tick resumes and kicks active CLPC sampling. + */ +static void apple_clpc_arm_idle(struct apple_clpc *clpc) +{ + unsigned long expires = jiffies + apple_clpc_idle_step(); + unsigned int cpu; + + /* + * Serialize with CPU hotplug callbacks and halt via idle_lock (ordered + * strictly inside cpuhp and sample_lock) rather than taking + * cpus_read_lock() inside sample_lock. + */ + guard(mutex)(&clpc->idle_lock); + atomic_set(&clpc->idle_armed, 0); + smp_mb(); + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + timer_delete_sync(&t->timer); + } + + for_each_cpu(cpu, &clpc->idle_online_cpus) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + t->last_idle = get_cpu_idle_time(cpu, &t->last_wall, 0); + } + atomic_set(&clpc->idle_armed, 1); + smp_mb(); + for_each_cpu(cpu, &clpc->idle_online_cpus) { + struct apple_clpc_idle_timer *t = per_cpu_ptr(clpc->idle_timers, cpu); + + t->timer.expires = expires; + add_timer_on(&t->timer, cpu); + } +} + static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) { if (READ_ONCE(clpc->stopped)) @@ -704,9 +850,21 @@ static void apple_clpc_queue(struct apple_clpc *clpc, bool idle) /* * A held vote has to be sampled on time so that it drops once demand * stops; with no vote held, sampling can wait for a CPU that wakes up - * anyway rather than waking an idle one every period, unless the SoC - * samples on time (@idle_on_time). + * anyway rather than waking an idle one every period. On SoCs with + * @idle_on_time (and without nohz_full, which can stop ticks on busy + * CPUs), arm a per-CPU deferrable timer across online CPUs so an idle + * system takes zero CLPC wakeups. Preserve any fresh client demand + * already queued on clpc->work. */ + if (idle && clpc->idle_timers && !tick_nohz_full_enabled()) { + cancel_delayed_work(&clpc->idle_work); + if (delayed_work_pending(&clpc->work)) + return; + apple_clpc_arm_idle(clpc); + return; + } + + atomic_set(&clpc->idle_armed, 0); idle = idle && !clpc->hw->idle_on_time; /* A demand edge can queue work while the deferrable pass is pending. * Keep one sampling cadence once the serialized pass settles. @@ -1064,6 +1222,7 @@ static void apple_clpc_sample(struct apple_clpc *clpc) unsigned int i, rail; u32 reason = 0, floor = 0; + atomic_set(&clpc->idle_armed, 0); clpc->samples++; if (!cpumask_equal(clpc->covered, cpu_possible_mask) && (!clpc->has_pmc || time_after_eq(now, clpc->next_scan))) { @@ -1340,14 +1499,27 @@ static void apple_clpc_free_clusters(struct apple_clpc *clpc) /* Stop sampling and give the floor back, before suspend and on removal. */ static void apple_clpc_halt(struct apple_clpc *clpc) { - unsigned int rail, i; + unsigned int rail, i, cpu; /* - * Each pass queues one of the two works unless stopped. A pass that - * began before the flag was set can still queue the other work once, - * which the second round cancels. + * Each pass queues one of the two works (or arms per-CPU deferrable + * timers) unless stopped. Cancel any in-flight pass first, drain every + * per-CPU idle timer so none can re-queue work, then cancel once more. */ WRITE_ONCE(clpc->stopped, true); + atomic_set(&clpc->idle_armed, 0); + cancel_delayed_work_sync(&clpc->work); + cancel_delayed_work_sync(&clpc->idle_work); + if (clpc->idle_timers) { + scoped_guard(mutex, &clpc->idle_lock) { + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = + per_cpu_ptr(clpc->idle_timers, cpu); + + timer_delete_sync(&t->timer); + } + } + } for (i = 0; i < 2; i++) { cancel_delayed_work_sync(&clpc->work); cancel_delayed_work_sync(&clpc->idle_work); @@ -1382,6 +1554,13 @@ static void apple_clpc_stop(void *data) } apple_clpc_ane_detach(clpc->ane); debugfs_remove_recursive(clpc->debugfs); + WRITE_ONCE(clpc->stopped, true); + atomic_set(&clpc->idle_armed, 0); + if (clpc->cpuhp_added) { + cpuhp_state_remove_instance_nocalls(apple_clpc_cpuhp_state, + &clpc->cpuhp_node); + clpc->cpuhp_added = false; + } apple_clpc_halt(clpc); /* The SMC keeps this mode after the driver's profile state is gone. */ mutex_lock(&clpc->sample_lock); @@ -1839,8 +2018,36 @@ static int apple_clpc_probe(struct platform_device *pdev) apple_clpc_find_clusters(clpc); clpc->next_scan = jiffies + HZ; mutex_init(&clpc->sample_lock); + mutex_init(&clpc->idle_lock); + cpumask_clear(&clpc->idle_online_cpus); INIT_DELAYED_WORK(&clpc->work, apple_clpc_work); INIT_DEFERRABLE_WORK(&clpc->idle_work, apple_clpc_idle_work); + if (clpc->has_pmc && clpc->hw->idle_on_time) { + unsigned int cpu; + + clpc->idle_timers = devm_alloc_percpu(dev, struct apple_clpc_idle_timer); + if (!clpc->idle_timers) { + apple_clpc_free_clusters(clpc); + return -ENOMEM; + } + for_each_possible_cpu(cpu) { + struct apple_clpc_idle_timer *t = + per_cpu_ptr(clpc->idle_timers, cpu); + + t->clpc = clpc; + timer_setup(&t->timer, apple_clpc_idle_timer_fn, + TIMER_DEFERRABLE | TIMER_PINNED); + } + if (apple_clpc_cpuhp_state > 0) { + ret = cpuhp_state_add_instance(apple_clpc_cpuhp_state, + &clpc->cpuhp_node); + if (ret) { + apple_clpc_free_clusters(clpc); + return ret; + } + clpc->cpuhp_added = true; + } + } /* Sample at a cold publication only where that publication is the demand. * Dense counting needs no extra sample, and one taken as each frame of a * frame-paced client starts finds its CPUs busy and votes their fabric. @@ -1894,7 +2101,9 @@ static int apple_clpc_probe(struct platform_device *pdev) mutex_lock(&apple_clpc_clients_lock); platform_set_drvdata(pdev, clpc); mutex_unlock(&apple_clpc_clients_lock); + mutex_lock(&clpc->sample_lock); apple_clpc_queue(clpc, true); + mutex_unlock(&clpc->sample_lock); return 0; } @@ -1914,12 +2123,14 @@ static int apple_clpc_resume(struct device *dev) struct apple_clpc *clpc = dev_get_drvdata(dev); unsigned int cpu; + mutex_lock(&clpc->sample_lock); if (clpc->wall) for_each_possible_cpu(cpu) clpc->wall[cpu] = 0; clpc->power_next = jiffies; WRITE_ONCE(clpc->stopped, false); apple_clpc_queue(clpc, true); + mutex_unlock(&clpc->sample_lock); return 0; } @@ -2874,7 +3085,36 @@ static struct platform_driver apple_clpc_driver = { .pm = pm_sleep_ptr(&apple_clpc_pm_ops), }, }; -module_platform_driver(apple_clpc_driver); +static int __init apple_clpc_driver_init(void) +{ + int ret; + + ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, + "soc/apple/clpc:online", + apple_clpc_cpu_online, + apple_clpc_cpu_down); + if (ret < 0) + return ret; + apple_clpc_cpuhp_state = ret; + + ret = platform_driver_register(&apple_clpc_driver); + if (ret) { + cpuhp_remove_multi_state(apple_clpc_cpuhp_state); + apple_clpc_cpuhp_state = 0; + } + return ret; +} +module_init(apple_clpc_driver_init); + +static void __exit apple_clpc_driver_exit(void) +{ + platform_driver_unregister(&apple_clpc_driver); + if (apple_clpc_cpuhp_state > 0) { + cpuhp_remove_multi_state(apple_clpc_cpuhp_state); + apple_clpc_cpuhp_state = 0; + } +} +module_exit(apple_clpc_driver_exit); MODULE_DESCRIPTION("Apple SoC host performance controller floors"); MODULE_LICENSE("Dual MIT/GPL"); From 20df9351846a4cbe5d87477f2eba4e77a6999c4e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 12:23:09 -0500 Subject: [PATCH 1440/1514] accel/ane: enable T6050 cold sleep and idle power-off Allow the T6050 H17 ANE platform to enter cold sleep and power-gate ane-sys at idle once requests drain, matching the verified cold-boot resume path. Refuse runtime idle power-off when clean firmware stop is disabled so power is never cut without stopping firmware DMA. Signed-off-by: Erik Bourget --- drivers/accel/ane/ane_fw_cold.c | 7 ++++++- drivers/accel/ane/ane_fw_platform.c | 3 +++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 060de93b1e8368..7a0c40e521c6cd 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1554,8 +1554,13 @@ int ane_fw_staged_runtime_suspend(struct device *dev) return -EBUSY; } } + /* Do not cut power at runtime idle if clean firmware stop is disabled. */ + if (!ane_fw_clean_stop(b) || !b->pmu_base_set) { + ane_h16_session_sleep(&b->session, false); + return -EBUSY; + } b->in_rpm = true; - ret = ane_fw_clean_stop(b) ? ane_fw_firmware_stop(b) : 0; + ret = ane_fw_firmware_stop(b); if (!ret) ret = ane_fw_power_down(b); b->in_rpm = false; diff --git a/drivers/accel/ane/ane_fw_platform.c b/drivers/accel/ane/ane_fw_platform.c index c3df3abf0a3945..1ba2da0cce8c98 100644 --- a/drivers/accel/ane/ane_fw_platform.c +++ b/drivers/accel/ane/ane_fw_platform.c @@ -306,6 +306,9 @@ const struct ane_fw_platform ane_h17_platform = { .boot_qualified = true, \ .firmware_preloaded = true, \ .safe_reset = false, \ + /* Exclave mode at boot, cold sleep cycle and parked start. */ \ + .exclave_mode_stop = true, \ + .macos_sleep = true, \ .sleep_warm = false, \ .pmgr_sys = 0x3a8, \ .pmgr_cpu = 0x3c8, \ From 642ce6857f46c02849a04ebe1299c62e5b9f651d Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 13:54:56 -0500 Subject: [PATCH 1441/1514] nvmem: core: let a provider keep its sysfs file read-only A provider with a reg_write callback gets a writable whole-device sysfs file, nvmem. Its kernel consumers may need to write a few cells, but the file then lets root write anywhere in the device. read_only does not separate the two: it also stops the kernel's cell writes, and root can clear it through force_ro. Add nvmem_config.sysfs_read_only. The whole-device file of such a device has no write permission, and its write handler refuses writes whatever the file's mode or read_only say. force_ro is shown but cannot be stored, as it would only stop the kernel's cell writes. Kernel consumers write the device's cells as before. Signed-off-by: DjDeveloperr --- drivers/nvmem/core.c | 18 ++++++++++++++++-- drivers/nvmem/internals.h | 2 ++ include/linux/nvmem-provider.h | 4 ++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/drivers/nvmem/core.c b/drivers/nvmem/core.c index b4e5069d9e3802..bd5b53d317b223 100644 --- a/drivers/nvmem/core.c +++ b/drivers/nvmem/core.c @@ -204,8 +204,13 @@ static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct nvmem_device *nvmem = to_nvmem_device(dev); - int ret = kstrtobool(buf, &nvmem->read_only); + int ret; + + /* It would only govern the kernel's cell writes. */ + if (nvmem->sysfs_read_only) + return -EPERM; + ret = kstrtobool(buf, &nvmem->read_only); if (ret < 0) return ret; @@ -266,6 +271,10 @@ static ssize_t bin_attr_nvmem_write(struct file *filp, struct kobject *kobj, dev = kobj_to_dev(kobj); nvmem = to_nvmem_device(dev); + /* Whatever the file's mode, and whatever force_ro says */ + if (nvmem->sysfs_read_only) + return -EPERM; + if (!IS_ALIGNED(pos, nvmem->stride)) return -EINVAL; @@ -296,7 +305,7 @@ static umode_t nvmem_bin_attr_get_umode(struct nvmem_device *nvmem) if (!nvmem->root_only) mode |= 0044; - if (!nvmem->read_only) + if (!nvmem->read_only && !nvmem->sysfs_read_only) mode |= 0200; if (!ops->reg_write) @@ -345,6 +354,10 @@ static umode_t nvmem_attr_is_visible(struct kobject *kobj, if (attr == &dev_attr_force_ro.attr && !ops->reg_write) return 0; /* Attribute not visible */ + /* Shown, but it cannot make the device's file writable. */ + if (attr == &dev_attr_force_ro.attr && nvmem->sysfs_read_only) + return 0444; + return attr->mode; } @@ -945,6 +958,7 @@ struct nvmem_device *nvmem_register(const struct nvmem_config *config) nvmem->word_size = config->word_size ?: 1; nvmem->size = config->size; nvmem->root_only = config->root_only; + nvmem->sysfs_read_only = config->sysfs_read_only; nvmem->priv = config->priv; nvmem->type = config->type; nvmem->keepout = config->keepout; diff --git a/drivers/nvmem/internals.h b/drivers/nvmem/internals.h index 4e610deeaa7b3c..df8b25fd39369f 100644 --- a/drivers/nvmem/internals.h +++ b/drivers/nvmem/internals.h @@ -23,6 +23,8 @@ struct nvmem_device { size_t size; bool read_only; bool root_only; + /* See nvmem_config.sysfs_read_only */ + bool sysfs_read_only; int flags; enum nvmem_type type; struct bin_attribute eeprom; diff --git a/include/linux/nvmem-provider.h b/include/linux/nvmem-provider.h index 6063fe5b7784ac..c74e0fbb9d73ca 100644 --- a/include/linux/nvmem-provider.h +++ b/include/linux/nvmem-provider.h @@ -91,6 +91,9 @@ struct nvmem_cell_info { * @type: Type of the nvmem storage * @read_only: Device is read-only. * @root_only: Device is accessibly to root only. + * @sysfs_read_only: The device's whole-device sysfs file is read-only for + * good: force_ro cannot make it writable. Kernel consumers still + * write its cells. * @of_node: If given, this will be used instead of the parent's of_node. * @reg_read: Callback to read data; return zero if successful. * @reg_write: Callback to write data; return zero if successful. @@ -123,6 +126,7 @@ struct nvmem_config { enum nvmem_type type; bool read_only; bool root_only; + bool sysfs_read_only; bool ignore_wp; struct nvmem_layout *layout; struct device_node *of_node; From a1f36ffe3b9fb283b836420f9009a27f0819a2a1 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 13:54:57 -0500 Subject: [PATCH 1442/1514] nvmem: apple-spmi: keep the PMIC's sysfs file read-only The provider covers the PMIC's whole 64 KiB register space, and its kernel consumers (the RTC offset, the boot stage, the boot error and panic counts, the shutdown flag) write the cells the device tree declares. Its sysfs file was writable by root, which could so write any PMIC register. Register it with sysfs_read_only: root still reads the registers through sysfs, nobody writes them there, and the kernel writes the cells as before. Registration moves to a helper that the test uses. Add KUnit cases on a register map in memory, with the provider registered as the driver does: the sysfs file is 0400, refuses writes, also once read_only is cleared, and force_ro cannot be stored, while root still reads; and the kernel still writes a byte cell (the RTC offset) and a bit-field cell (the panic count beside the boot error count). With the provider registered as before, the first case fails: the file is 0600, a write reaches the register, and force_ro is writable. Signed-off-by: DjDeveloperr --- MAINTAINERS | 2 + drivers/nvmem/Kconfig | 10 ++ drivers/nvmem/apple-spmi-nvmem-test.c | 153 +++++++++++++++++++++ drivers/nvmem/apple-spmi-nvmem.c | 30 ++-- drivers/nvmem/apple-spmi-nvmem.kunitconfig | 7 + 5 files changed, 194 insertions(+), 8 deletions(-) create mode 100644 drivers/nvmem/apple-spmi-nvmem-test.c create mode 100644 drivers/nvmem/apple-spmi-nvmem.kunitconfig diff --git a/MAINTAINERS b/MAINTAINERS index 798e34ac61c303..3ea04e12de0eaa 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2814,7 +2814,9 @@ F: drivers/nfc/.kunitconfig F: drivers/nfc/apple-stockholm*.c F: drivers/nvme/host/apple.c F: drivers/nvmem/apple-efuses.c +F: drivers/nvmem/apple-spmi-nvmem-test.c F: drivers/nvmem/apple-spmi-nvmem.c +F: drivers/nvmem/apple-spmi-nvmem.kunitconfig F: drivers/phy/apple/ F: drivers/phy/apple/.kunitconfig.apple-atc F: drivers/pinctrl/pinctrl-apple-gpio.c diff --git a/drivers/nvmem/Kconfig b/drivers/nvmem/Kconfig index 99ce966756a800..0da6ce8f75c77c 100644 --- a/drivers/nvmem/Kconfig +++ b/drivers/nvmem/Kconfig @@ -174,6 +174,16 @@ config NVMEM_APPLE_SPMI This driver can also be built as a module. If so, the module will be called apple-nvmem-spmi. +config NVMEM_APPLE_SPMI_KUNIT_TEST + bool "KUnit tests for the Apple SPMI NVMEM driver" if !KUNIT_ALL_TESTS + depends on NVMEM_APPLE_SPMI=y && NVMEM_SYSFS && KUNIT=y + default KUNIT_ALL_TESTS + help + Check, on a register map in memory, that the PMIC's whole-device + sysfs file cannot be written, even with force_ro cleared, while + the kernel still writes its byte and bit-field cells. No Apple + hardware is needed. + config NVMEM_BCM_OCOTP tristate "Broadcom On-Chip OTP Controller support" depends on ARCH_BCM_IPROC || COMPILE_TEST diff --git a/drivers/nvmem/apple-spmi-nvmem-test.c b/drivers/nvmem/apple-spmi-nvmem-test.c new file mode 100644 index 00000000000000..1990e1f4562405 --- /dev/null +++ b/drivers/nvmem/apple-spmi-nvmem-test.c @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * Included by apple-spmi-nvmem.c: the provider as the driver registers it, on a + * register map in memory. Userspace cannot write the PMIC's registers through + * the whole-device sysfs file, whatever force_ro says, while the kernel still + * writes the cells its consumers declare. + */ +#include +#include +#include + +#include "internals.h" + +struct apple_spmi_nvmem_test { + u8 regs[0x10000]; +}; + +static int apple_spmi_nvmem_test_reg_read(void *context, unsigned int reg, unsigned int *val) +{ + struct apple_spmi_nvmem_test *t = context; + + *val = t->regs[reg]; + return 0; +} + +static int apple_spmi_nvmem_test_reg_write(void *context, unsigned int reg, unsigned int val) +{ + struct apple_spmi_nvmem_test *t = context; + + t->regs[reg] = val; + return 0; +} + +/* The driver's register layout (apple_spmi_regmap_config), on the array above */ +static const struct regmap_config apple_spmi_nvmem_test_regmap_config = { + .reg_bits = 16, + .val_bits = 8, + .max_register = 0xffff, + .reg_read = apple_spmi_nvmem_test_reg_read, + .reg_write = apple_spmi_nvmem_test_reg_write, +}; + +static struct nvmem_device *apple_spmi_nvmem_test_register(struct kunit *test, + struct apple_spmi_nvmem_test **regs) +{ + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + struct regmap *regmap; + struct device *dev; + + dev = kunit_device_register(test, "apple-spmi-nvmem-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + + regmap = devm_regmap_init(dev, NULL, t, &apple_spmi_nvmem_test_regmap_config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, regmap); + + nvmem = apple_spmi_nvmem_register(dev, regmap); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + *regs = t; + return nvmem; +} + +/* + * The whole-device file: root reads it, nobody writes it, not with read_only + * cleared either, and force_ro is shown but cannot be stored. + */ +static void apple_spmi_nvmem_sysfs_read_only_test(struct kunit *test) +{ + u8 offset[6] = { 1, 2, 3, 4, 5, 6 }, out[6] = {}; + const struct attribute_group *group; + const struct bin_attribute *raw; + struct device_attribute *force_ro; + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + struct kobject *kobj; + int i; + + nvmem = apple_spmi_nvmem_test_register(test, &t); + kobj = &nvmem->dev.kobj; + KUNIT_ASSERT_NOT_NULL(test, nvmem->dev.groups); + group = nvmem->dev.groups[0]; + raw = group->bin_attrs[0]; + KUNIT_ASSERT_STREQ(test, raw->attr.name, "nvmem"); + + KUNIT_EXPECT_EQ(test, group->is_bin_visible(kobj, raw, 0), (umode_t)0400); + + t->regs[0x2100] = 0x5a; + KUNIT_EXPECT_EQ(test, raw->write(NULL, kobj, raw, (char *)offset, 0x2100, sizeof(offset)), + (ssize_t)-EPERM); + KUNIT_EXPECT_EQ(test, t->regs[0x2100], 0x5a); + + for (i = 0; group->attrs[i]; i++) + if (!strcmp(group->attrs[i]->name, "force_ro")) + break; + KUNIT_ASSERT_NOT_NULL(test, group->attrs[i]); + KUNIT_EXPECT_EQ(test, group->is_visible(kobj, group->attrs[i], i), (umode_t)0444); + force_ro = container_of(group->attrs[i], struct device_attribute, attr); + KUNIT_EXPECT_EQ(test, force_ro->store(&nvmem->dev, force_ro, "0", 1), (ssize_t)-EPERM); + + /* As if read_only were cleared, by force_ro or otherwise */ + nvmem->read_only = false; + KUNIT_EXPECT_EQ(test, group->is_bin_visible(kobj, raw, 0), (umode_t)0400); + KUNIT_EXPECT_EQ(test, raw->write(NULL, kobj, raw, (char *)offset, 0x2100, sizeof(offset)), + (ssize_t)-EPERM); + KUNIT_EXPECT_EQ(test, t->regs[0x2100], 0x5a); + + KUNIT_EXPECT_EQ(test, raw->read(NULL, kobj, raw, (char *)out, 0x2100, sizeof(out)), + (ssize_t)sizeof(out)); + KUNIT_EXPECT_EQ(test, out[0], 0x5a); +} + +/* + * The kernel's consumers still write their cells: a byte cell (the RTC offset) + * and a bit-field cell sharing its byte (the panic count above the boot error + * count). + */ +static void apple_spmi_nvmem_cell_write_test(struct kunit *test) +{ + struct nvmem_cell_info rtc_offset = { + .name = "rtc-offset", .offset = 0x2100, .bytes = 6, + }; + struct nvmem_cell_info panic_count = { + .name = "panic-count", .offset = 0xf802, .bytes = 1, .bit_offset = 4, .nbits = 4, + }; + u8 offset[6] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }; + struct apple_spmi_nvmem_test *t; + struct nvmem_device *nvmem; + u8 count = 3; + + nvmem = apple_spmi_nvmem_test_register(test, &t); + + KUNIT_EXPECT_EQ(test, nvmem_device_cell_write(nvmem, &rtc_offset, offset), 6); + KUNIT_EXPECT_MEMEQ(test, &t->regs[0x2100], offset, sizeof(offset)); + + t->regs[0xf802] = 0x05; + KUNIT_EXPECT_EQ(test, nvmem_device_cell_write(nvmem, &panic_count, &count), 1); + KUNIT_EXPECT_EQ(test, t->regs[0xf802], 0x35); +} + +static struct kunit_case apple_spmi_nvmem_test_cases[] = { + KUNIT_CASE(apple_spmi_nvmem_sysfs_read_only_test), + KUNIT_CASE(apple_spmi_nvmem_cell_write_test), + {} +}; + +static struct kunit_suite apple_spmi_nvmem_test_suite = { + .name = "apple-spmi-nvmem", + .test_cases = apple_spmi_nvmem_test_cases, +}; + +kunit_test_suite(apple_spmi_nvmem_test_suite); diff --git a/drivers/nvmem/apple-spmi-nvmem.c b/drivers/nvmem/apple-spmi-nvmem.c index 6a270ccb9aca81..8c933bd83dd669 100644 --- a/drivers/nvmem/apple-spmi-nvmem.c +++ b/drivers/nvmem/apple-spmi-nvmem.c @@ -35,30 +35,40 @@ static int apple_spmi_nvmem_write(void *priv, unsigned int offset, void *val, return regmap_bulk_write(map, offset, val, bytes); } -static int apple_spmi_nvmem_probe(struct spmi_device *sdev) +/* + * The PMIC's register file. Its kernel consumers (the RTC, the reboot and boot + * state) write the cells the device tree declares; through sysfs, only root may + * read the registers, and nobody may write them. + */ +static struct nvmem_device *apple_spmi_nvmem_register(struct device *dev, struct regmap *regmap) { - struct regmap *regmap; - struct nvmem_device *provider; struct nvmem_config nvmem_cfg = { - .dev = &sdev->dev, + .dev = dev, .name = "spmi_nvmem", .id = NVMEM_DEVID_AUTO, .word_size = 1, .stride = 1, .size = 0xffff, - /* PMIC registers: only root may read them through sysfs. */ .root_only = true, + .sysfs_read_only = true, .reg_read = apple_spmi_nvmem_read, .reg_write = apple_spmi_nvmem_write, + .priv = regmap, }; + return devm_nvmem_register(dev, &nvmem_cfg); +} + +static int apple_spmi_nvmem_probe(struct spmi_device *sdev) +{ + struct regmap *regmap; + struct nvmem_device *provider; + regmap = devm_regmap_init_spmi_ext(sdev, &apple_spmi_regmap_config); if (IS_ERR(regmap)) return PTR_ERR(regmap); - nvmem_cfg.priv = regmap; - - provider = devm_nvmem_register(&sdev->dev, &nvmem_cfg); + provider = apple_spmi_nvmem_register(&sdev->dev, regmap); if (IS_ERR(provider)) return PTR_ERR(provider); if (!of_device_is_compatible(sdev->dev.of_node, "apple,baku-pmic") && @@ -91,3 +101,7 @@ module_spmi_driver(apple_spmi_nvmem_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_AUTHOR("Hector Martin "); MODULE_DESCRIPTION("Apple SPMI NVMEM driver"); + +#if IS_ENABLED(CONFIG_NVMEM_APPLE_SPMI_KUNIT_TEST) +#include "apple-spmi-nvmem-test.c" +#endif diff --git a/drivers/nvmem/apple-spmi-nvmem.kunitconfig b/drivers/nvmem/apple-spmi-nvmem.kunitconfig new file mode 100644 index 00000000000000..f6c1e1f3eef14f --- /dev/null +++ b/drivers/nvmem/apple-spmi-nvmem.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_SPMI=y +CONFIG_NVMEM=y +CONFIG_NVMEM_SYSFS=y +CONFIG_NVMEM_APPLE_SPMI=y +CONFIG_NVMEM_APPLE_SPMI_KUNIT_TEST=y From 9608a26ff3794c185ca3f55a5f3bbef15c9ac53e Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 13:54:57 -0500 Subject: [PATCH 1443/1514] ci: build drivers/nvmem and run the Apple SPMI NVMEM KUnit suite Compile drivers/nvmem in the Apple build job, run the apple-spmi-nvmem suite in the KUnit matrix, and start the workflow on drivers/nvmem changes. Signed-off-by: DjDeveloperr --- .github/workflows/apple-build-kunit.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/apple-build-kunit.yml b/.github/workflows/apple-build-kunit.yml index 51354983d82206..cfe9ef6364e509 100644 --- a/.github/workflows/apple-build-kunit.yml +++ b/.github/workflows/apple-build-kunit.yml @@ -22,6 +22,7 @@ on: - 'drivers/media/platform/apple/**' - 'drivers/mfd/**' - 'drivers/nvme/host/**' + - 'drivers/nvmem/**' - 'drivers/pci/controller/**' - 'drivers/power/**' - 'drivers/soc/apple/**' @@ -49,6 +50,7 @@ on: - 'drivers/media/platform/apple/**' - 'drivers/mfd/**' - 'drivers/nvme/host/**' + - 'drivers/nvmem/**' - 'drivers/pci/controller/**' - 'drivers/power/**' - 'drivers/soc/apple/**' @@ -124,6 +126,7 @@ jobs: drivers/media/platform/apple/ \ drivers/mfd/ \ drivers/nvme/host/ \ + drivers/nvmem/ \ drivers/pci/controller/ \ drivers/power/ \ drivers/soc/apple/ \ @@ -158,6 +161,7 @@ jobs: - { suite: scaler, kunitconfig: drivers/media/platform/apple/scaler/.kunitconfig } - { suite: macsmc, kunitconfig: drivers/mfd/macsmc.kunitconfig } - { suite: clpc, kunitconfig: drivers/soc/apple/clpc.kunitconfig } + - { suite: apple-spmi-nvmem, kunitconfig: drivers/nvmem/apple-spmi-nvmem.kunitconfig } - { suite: trusted-keys, kunitconfig: security/keys/trusted-keys/tests/.kunitconfig } steps: - uses: actions/checkout@v4 From cf92495c6359e9b7a5219b63839be252076a286f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 04:10:06 +1100 Subject: [PATCH 1444/1514] drm: apple: afk: send AFKv2 service reports with data An AFKv2 endpoint could send only payload-less open and close reports. The HDCP auth session takes the transmitter's progress as a standard service report with data (category report, subtype 0xc0, no flags). Allow that one form; everything else stays refused. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/afk.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index 50c0c10bd5ea72..cb72d998412956 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -3015,7 +3015,12 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, if (ep->wire_v2) { if (!channel || channel > U16_MAX || tag > U8_MAX || payload_len > SZ_1M) return -EINVAL; - if (ecat == EPIC_CAT_REPORT) { + if (ecat == EPIC_CAT_REPORT && stype == EPIC_SUBTYPE_STD_SERVICE) { + /* A service report with its data (an HDCP session's progress). */ + if (!payload_len) + return -EINVAL; + v2_category = AFKV2_REPORT; + } else if (ecat == EPIC_CAT_REPORT) { if ((stype != AFKV2_OPEN && stype != AFKV2_CLOSE) || payload_len) return -EOPNOTSUPP; v2_flags = 1; From 1acd4745f0e30b3d470b8f2ad84239568f656d61 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 06:19:51 +1100 Subject: [PATCH 1445/1514] drm: apple: add the HDCP 2.2 transmitter for DCP outputs The display coprocessor carries HDCP 2.2 to an external receiver and the SEP holds the transmitter's keys and does its cryptography. Add the transmitter that joins the two, without any runtime caller yet: - dcp-hdcp-wire.h: the DCP services' message layouts. The DP device service reads and writes the receiver's HDCP 2.2 registers (the DisplayPort HDCP 2.2 register map, also used behind an on-board DP to HDMI converter); an authentication session service per attempt calls the AP with the receiver's events and takes the transmitter's progress reports. - dcp-hdcp-tx.c: the HDCP 2.2 transmitter procedure on the apple-sep-hdcp.h service: AKE with stored km or first pairing, locality check with retries, SKE, repeater authentication (topology limits, seq_num_V, V), stream management with the content type and one M' retry, the 200 ms wait, then encryption. Receiver IDs go through drm_hdcp_check_ksvs_revoked(); a revoked ID or an unreadable SRM fails closed. Type 1 is refused when RxInfo reports an HDCP 1.x device or an HDCP 2.0 repeater downstream. The certificate is read after the 100 ms AKE_Send_Cert time and a Receiver ID without twenty ones fails the attempt. DCP turns RxStatus into session events; RxStatus is read only when an event is overdue, since a DisplayPort read clears those bits. - dcp-hdcp.h: the Content Protection policy (off, desired, authenticating, enabled), with back-off between failed attempts. Only fields the protocol sends in the clear pass between the transmitter and the SEP; km, ks and the device keys never leave the SEP. KUnit: apple-dcp-hdcp-wire, apple-dcp-hdcp-tx, apple-dcp-hdcp. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/Kconfig | 14 + drivers/gpu/drm/apple/Makefile | 3 + drivers/gpu/drm/apple/dcp-hdcp-test.c | 237 +++++++++ drivers/gpu/drm/apple/dcp-hdcp-tx-test.c | 581 +++++++++++++++++++++ drivers/gpu/drm/apple/dcp-hdcp-tx.c | 374 +++++++++++++ drivers/gpu/drm/apple/dcp-hdcp-tx.h | 115 ++++ drivers/gpu/drm/apple/dcp-hdcp-wire-test.c | 156 ++++++ drivers/gpu/drm/apple/dcp-hdcp-wire.h | 247 +++++++++ drivers/gpu/drm/apple/dcp-hdcp.h | 230 ++++++++ 9 files changed, 1957 insertions(+) create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-test.c create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx-test.c create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx.c create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx.h create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-wire-test.c create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-wire.h create mode 100644 drivers/gpu/drm/apple/dcp-hdcp.h diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 689171db4ebe0c..a3753e2481e542 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -36,6 +36,20 @@ config DRM_APPLE_CEC dcpav-cec-interface-epic service. Say Y here to expose a standard Linux /dev/cecX adapter bound to the built-in HDMI connector. +config DRM_APPLE_HDCP + bool "HDCP 2.2 content protection on external outputs" + default y + depends on DRM_APPLE + select DRM_DISPLAY_HELPER + select DRM_DISPLAY_HDCP_HELPER + help + Support the standard "Content Protection" and "HDCP Content Type" + connector properties on external DisplayPort, HDMI and USB-C + outputs. The SEP holds the transmitter's keys and does the HDCP 2.2 + cryptography; DCP carries the messages to the receiver. Sessions + run only with the appledrm.hdcp module parameter set and the SEP + HDCP service (APPLE_SEP_HDCP_INTERFACE) available. + config DRM_APPLE_AUDIO bool "DisplayPort/HDMI Audio support" default y diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index 6098e8efb7c597..c20e07e9edfcad 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -41,6 +41,7 @@ appledrm-y += epic/dpavservep.o appledrm-y += epic/panelavep.o appledrm-y += plane.o appledrm-y += dcp-indicator.o +appledrm-$(CONFIG_DRM_APPLE_HDCP) += dcp-hdcp-tx.o appledrm-$(CONFIG_TRACING) += trace.o @@ -50,6 +51,8 @@ obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk_test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_backlight_test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-indicator-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-announce-test.o +obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-hdcp-test.o +obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-hdcp-wire-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk-service-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_cec_test.o diff --git a/drivers/gpu/drm/apple/dcp-hdcp-test.c b/drivers/gpu/drm/apple/dcp-hdcp-test.c new file mode 100644 index 00000000000000..09650183487e7e --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-test.c @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +#include +#include + +#include "dcp-hdcp.h" + +static const unsigned long T0 = 1000; + +static struct dcp_hdcp_link bound(void) +{ + struct dcp_hdcp_link l = { .relay = true, .sep = true }; + + return l; +} + +static void hdcp_property_needs_all(struct kunit *test) +{ + KUNIT_EXPECT_TRUE(test, dcp_hdcp_attach_property(true, true, true)); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(false, true, true)); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(true, false, true)); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(true, true, false)); +} + +static void hdcp_unbound_declines(struct kunit *test) +{ + struct dcp_hdcp_link l = { }; + + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_DESIRED); + l.relay = true; + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); + /* Both sides bound: ask DCP for a session. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, true, T0), DCP_HDCP_KICK); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); +} + +static void hdcp_undesired_declines(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_UNDESIRED); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_KICK); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); + /* One session at a time. */ + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); +} + +static void hdcp_session_enables(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + dcp_hdcp_request(&l, true, 1, T0); + KUNIT_ASSERT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_DESIRED); + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_ENABLED); + KUNIT_EXPECT_EQ(test, l.type, 1); + + /* Userspace turns it off: teardown, UNDESIRED. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, false, 1, T0), + DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_UNDESIRED); + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, false, 1, T0), DCP_HDCP_NONE); +} + +static void hdcp_type_change_reauths(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + dcp_hdcp_auth_done(&l, 1, 0, T0); + /* Same type again: nothing. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); + /* Type 1 now: the running session goes, no backoff. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 1, T0), + DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); + KUNIT_EXPECT_EQ(test, l.failures, 0); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); + KUNIT_EXPECT_EQ(test, l.type, 1); +} + +static void hdcp_failure_backs_off(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + unsigned long t = T0; + unsigned int i; + + dcp_hdcp_request(&l, true, 0, t); + dcp_hdcp_open(&l, 1, t); + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, -EACCES, t), + DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); + /* DCP's next open is declined until the backoff is over. */ + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, t + 1)); + t += msecs_to_jiffies(DCP_HDCP_RETRY_MS); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, t)); + + /* Doubling, capped. */ + for (i = 2; i < 12; i++) { + dcp_hdcp_auth_done(&l, 1, -EACCES, t); + KUNIT_EXPECT_EQ(test, l.failures, i); + t = l.retry_at; + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, t)); + } + KUNIT_EXPECT_EQ(test, dcp_hdcp_backoff(20), + msecs_to_jiffies(DCP_HDCP_RETRY_MAX_MS)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_backoff(2), + msecs_to_jiffies(2 * DCP_HDCP_RETRY_MS)); + /* A success resets it. */ + dcp_hdcp_auth_done(&l, 1, 0, t); + KUNIT_EXPECT_EQ(test, l.failures, 0); +} + +static void hdcp_close_mid_auth(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + /* DCP gives up on an attempt (a receiver timeout): a failure. */ + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 1, T0), DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.failures, 1); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_DESIRED); + /* The attempt's late result changes nothing. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); + + /* Closing an enabled session (re-authentication) is no failure. */ + l = bound(); + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + dcp_hdcp_auth_done(&l, 1, 0, T0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 1, T0), DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.failures, 0); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); + /* A close for another generation is ignored. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 7, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_AUTH); +} + +static void hdcp_link_change_drops_enabled(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + dcp_hdcp_auth_done(&l, 1, 0, T0); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); + + /* Same generation: nothing. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_link_event(&l, 1, T0), DCP_HDCP_NONE); + /* Hotplug, DPMS, resume: back to DESIRED, no backoff. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_link_event(&l, 2, T0), DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_DESIRED); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 2, T0)); + /* A result from generation 1 is late. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_AUTH); + /* A link change clears an earlier backoff. */ + dcp_hdcp_auth_done(&l, 2, -EACCES, T0); + KUNIT_EXPECT_EQ(test, l.failures, 1); + dcp_hdcp_link_event(&l, 3, T0); + KUNIT_EXPECT_EQ(test, l.failures, 0); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 3, T0)); +} + +static void hdcp_unbind_drops(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + dcp_hdcp_auth_done(&l, 1, 0, T0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, false, T0), + DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, true, T0), DCP_HDCP_KICK); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); +} + +static void hdcp_sep_busy_holds(struct kunit *test) +{ + struct dcp_hdcp_link l = bound(); + unsigned long hold = msecs_to_jiffies(DCP_HDCP_RETRY_MS); + + dcp_hdcp_request(&l, true, 0, T0); + dcp_hdcp_open(&l, 1, T0); + /* The SEP is busy: DESIRED, no failure counted, a short hold. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, -EAGAIN, T0), + DCP_HDCP_TEARDOWN); + KUNIT_EXPECT_EQ(test, l.failures, 0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), + DRM_MODE_CONTENT_PROTECTION_DESIRED); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0 + hold - 1)); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0 + hold)); + dcp_hdcp_auth_done(&l, 1, 0, T0 + hold); + KUNIT_EXPECT_FALSE(test, l.hold); + KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); +} + +static struct kunit_case dcp_hdcp_cases[] = { + KUNIT_CASE(hdcp_property_needs_all), + KUNIT_CASE(hdcp_unbound_declines), + KUNIT_CASE(hdcp_undesired_declines), + KUNIT_CASE(hdcp_session_enables), + KUNIT_CASE(hdcp_type_change_reauths), + KUNIT_CASE(hdcp_failure_backs_off), + KUNIT_CASE(hdcp_close_mid_auth), + KUNIT_CASE(hdcp_link_change_drops_enabled), + KUNIT_CASE(hdcp_unbind_drops), + KUNIT_CASE(hdcp_sep_busy_holds), + { } +}; + +static struct kunit_suite dcp_hdcp_suite = { + .name = "apple-dcp-hdcp", + .test_cases = dcp_hdcp_cases, +}; +kunit_test_suite(dcp_hdcp_suite); + +MODULE_DESCRIPTION("KUnit tests for the Apple DCP HDCP policy"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c b/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c new file mode 100644 index 00000000000000..344adca03ea35d --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c @@ -0,0 +1,581 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +/* + * The transmitter procedure against a fake receiver (its HDCP 2.2 register + * map) and a fake SEP. Included from dcp-hdcp-tx.c. + */ + +#include + +#define FAKE_REG_BASE DP_HDCP_2_2_REG_RTX_OFFSET +#define FAKE_REG_SIZE 0x600 +#define FAKE_LOG 64 + +struct fake_write { + u32 addr; + size_t len; + u8 first; +}; + +struct fake { + struct kunit *test; + u8 regs[FAKE_REG_SIZE]; + + struct fake_write writes[FAKE_LOG]; + unsigned int nwrites; + enum dcp_hdcp_progress_code reports[FAKE_LOG]; + unsigned int nreports; + char sep[FAKE_LOG]; /* one letter per SEP call */ + unsigned int nsep; + unsigned int slept_ms; + + unsigned long events; /* BIT(op): DCP sends it */ + int cancel_op; /* -1, or the op whose wait is cancelled */ + bool stored; + int revoked_ids; /* returned by revoked() */ + unsigned int m_rejects; /* M' checks the SEP fails first */ + unsigned int l_rejects; /* L' checks the SEP fails first */ + bool sep_busy; /* the SEP is not available */ + bool encryption; + bool closed; + bool read_rxstatus; /* the TX read RxStatus */ +}; + +static int fake_read(void *ctx, u32 addr, void *buf, size_t len) +{ + struct fake *f = ctx; + + if (addr < FAKE_REG_BASE || addr + len > FAKE_REG_BASE + FAKE_REG_SIZE) + return -EIO; + if (addr == DP_HDCP_2_2_REG_RXSTATUS_OFFSET) + f->read_rxstatus = true; + memcpy(buf, f->regs + addr - FAKE_REG_BASE, len); + return 0; +} + +static int fake_write(void *ctx, u32 addr, const void *buf, size_t len) +{ + struct fake *f = ctx; + + if (addr < FAKE_REG_BASE || addr + len > FAKE_REG_BASE + FAKE_REG_SIZE) + return -EIO; + memcpy(f->regs + addr - FAKE_REG_BASE, buf, len); + if (f->nwrites < FAKE_LOG) + f->writes[f->nwrites++] = (struct fake_write){ addr, len, + ((u8 *)buf)[0] }; + return 0; +} + +static int fake_wait(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms) +{ + struct fake *f = ctx; + + if (f->cancel_op == op) + return -ECANCELED; + return (f->events & BIT(op)) ? 0 : -ETIMEDOUT; +} + +static void fake_report(void *ctx, enum dcp_hdcp_progress_code code, + bool active, bool repeater, bool encrypted) +{ + struct fake *f = ctx; + + if (f->nreports < FAKE_LOG) + f->reports[f->nreports++] = code; +} + +static int fake_revoked(void *ctx, u8 *ids, unsigned int count) +{ + return ((struct fake *)ctx)->revoked_ids; +} + +static void fake_sleep(void *ctx, unsigned int ms) +{ + ((struct fake *)ctx)->slept_ms += ms; +} + +static void sep_log(struct fake *f, char c) +{ + if (f->nsep < FAKE_LOG - 1) + f->sep[f->nsep++] = c; +} + +static int fake_sep_open(void *ctx, u32 ch, u8 *rtx) +{ + if (((struct fake *)ctx)->sep_busy) + return -EAGAIN; + sep_log(ctx, 'o'); + memset(rtx, 0xa1, HDCP_2_2_RTX_LEN); + return 0; +} + +static int fake_sep_ake_cert(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, + bool *stored, u8 *ekh_km_m, u8 *ekpub_km) +{ + struct fake *f = ctx; + + sep_log(f, 'c'); + *stored = f->stored; + memset(ekh_km_m, 0xb2, HDCP_2_2_E_KH_KM_M_LEN); + memset(ekpub_km, 0xc3, HDCP_2_2_E_KPUB_KM_LEN); + return 0; +} + +static int fake_sep_h_prime(void *ctx, u32 ch, const u8 *rxcaps, + const u8 *txcaps, const u8 *h_prime) +{ + struct fake *f = ctx; + + sep_log(f, 'h'); + /* H' covers RxCaps and TxCaps as the receiver sent and got them. */ + KUNIT_EXPECT_EQ(f->test, txcaps[0], HDCP_2_2_RX_CAPS_VERSION_VAL); + KUNIT_EXPECT_EQ(f->test, rxcaps[0], HDCP_2_2_RX_CAPS_VERSION_VAL); + return 0; +} + +static int fake_sep_pairing(void *ctx, u32 ch, const u8 *ekh_km) +{ + sep_log(ctx, 'p'); + return 0; +} + +static int fake_sep_lc_init(void *ctx, u32 ch, u8 *rn) +{ + sep_log(ctx, 'l'); + memset(rn, 0xd4, HDCP_2_2_RN_LEN); + return 0; +} + +static int fake_sep_l_prime(void *ctx, u32 ch, const u8 *l_prime) +{ + struct fake *f = ctx; + + sep_log(f, 'L'); + if (f->l_rejects) { + f->l_rejects--; + return -EACCES; + } + return 0; +} + +static int fake_sep_ske(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv) +{ + sep_log(ctx, 's'); + memset(edkey_ks, 0xe5, HDCP_2_2_E_DKEY_KS_LEN); + memset(riv, 0xf6, HDCP_2_2_RIV_LEN); + return 0; +} + +static int fake_sep_list(void *ctx, u32 ch, const u8 *ids, unsigned int count, + const u8 *rxinfo, const u8 *seq_num_v, + const u8 *v_prime, u8 *v) +{ + sep_log(ctx, 'r'); + memset(v, 0x11, HDCP_2_2_V_PRIME_HALF_LEN); + memset(v + HDCP_2_2_V_PRIME_HALF_LEN, 0x22, HDCP_2_2_V_PRIME_HALF_LEN); + return 0; +} + +static int fake_sep_stream(void *ctx, u32 ch, u8 stream_id, u8 type, + const u8 *seq_num_m, const u8 *m_prime) +{ + struct fake *f = ctx; + + sep_log(f, 'm'); + if (f->m_rejects) { + f->m_rejects--; + return -EACCES; + } + return 0; +} + +static int fake_sep_finish(void *ctx, u32 ch) +{ + sep_log(ctx, 'f'); + return 0; +} + +static int fake_sep_set_encryption(void *ctx, u32 ch, bool on) +{ + struct fake *f = ctx; + + sep_log(f, on ? 'E' : 'e'); + f->encryption = on; + return 0; +} + +static void fake_sep_close(void *ctx, u32 ch) +{ + struct fake *f = ctx; + + sep_log(f, 'x'); + f->closed = true; +} + +static const struct dcp_hdcp_tx_ops fake_ops = { + .read = fake_read, + .write = fake_write, + .wait = fake_wait, + .report = fake_report, + .revoked = fake_revoked, + .sleep = fake_sleep, + .sep_open = fake_sep_open, + .sep_ake_cert = fake_sep_ake_cert, + .sep_h_prime = fake_sep_h_prime, + .sep_pairing = fake_sep_pairing, + .sep_lc_init = fake_sep_lc_init, + .sep_l_prime = fake_sep_l_prime, + .sep_ske = fake_sep_ske, + .sep_repeater_list = fake_sep_list, + .sep_repeater_stream = fake_sep_stream, + .sep_finish = fake_sep_finish, + .sep_set_encryption = fake_sep_set_encryption, + .sep_close = fake_sep_close, +}; + +static u8 *reg(struct fake *f, u32 addr) +{ + return f->regs + addr - FAKE_REG_BASE; +} + +/* A receiver that does HDCP 2.2, a repeater or not. */ +static void fake_receiver(struct fake *f, bool repeater) +{ + u8 *caps = reg(f, DP_HDCP_2_2_REG_RX_CAPS_OFFSET); + + caps[0] = HDCP_2_2_RX_CAPS_VERSION_VAL; + caps[1] = 0; + caps[2] = BIT(1) | (repeater ? BIT(0) : 0); + memset(reg(f, DP_HDCP_2_2_REG_CERT_RX_OFFSET), 0x5a, + sizeof(struct hdcp2_cert_rx)); + f->events = BIT(DCP_HDCP_AUTH_H_PRIME) | BIT(DCP_HDCP_AUTH_PAIRING); + if (repeater) { + u8 *rxinfo = reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET); + + /* Depth 1, one device. */ + rxinfo[0] = 0x02; + rxinfo[1] = 0x10; + f->events |= BIT(DCP_HDCP_AUTH_LIST); + } +} + +static struct fake *fake_new(struct kunit *test, struct dcp_hdcp_tx *tx, + bool repeater, u8 type) +{ + struct fake *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, f); + f->test = test; + f->cancel_op = -1; + fake_receiver(f, repeater); + memset(tx, 0, sizeof(*tx)); + tx->ops = &fake_ops; + tx->ctx = f; + tx->channel = 7; + tx->type = type; + return f; +} + +static bool wrote(struct fake *f, u32 addr, size_t len) +{ + unsigned int i; + + for (i = 0; i < f->nwrites; i++) + if (f->writes[i].addr == addr && f->writes[i].len == len) + return true; + return false; +} + +static bool reported(struct fake *f, enum dcp_hdcp_progress_code code) +{ + unsigned int i; + + for (i = 0; i < f->nreports; i++) + if (f->reports[i] == code) + return true; + return false; +} + +static void tx_stored_km_type0(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + f->stored = true; + KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_STREQ(test, f->sep, "ochlLsfE"); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RTX_OFFSET, 8)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_TXCAPS_OFFSET, 3)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EKH_KM_WR_OFFSET, 32)); + KUNIT_EXPECT_FALSE(test, wrote(f, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, 128)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RN_OFFSET, 8)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EDKEY_KS_OFFSET, 16)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RIV_OFFSET, 8)); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, 1)); + KUNIT_EXPECT_EQ(test, *reg(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET), 0); + KUNIT_EXPECT_FALSE(test, reported(f, DCP_HDCP_PROGRESS_H_VERIFIED)); + KUNIT_EXPECT_EQ(test, f->reports[f->nreports - 1], + DCP_HDCP_PROGRESS_ENCRYPTED); + /* The cert after 100 ms, L' after 16 ms, encryption 200 ms after the keys. */ + KUNIT_EXPECT_EQ(test, f->slept_ms, HDCP_2_2_CERT_TIMEOUT_MS + + HDCP_2_2_DP_LPRIME_TIMEOUT_MS + + HDCP_2_2_DELAY_BEFORE_ENCRYPTION_EN); + KUNIT_EXPECT_TRUE(test, f->encryption); + KUNIT_EXPECT_FALSE(test, tx.repeater); + + dcp_hdcp_abort(&tx); + KUNIT_EXPECT_FALSE(test, f->encryption); + KUNIT_EXPECT_TRUE(test, f->closed); +} + +static void tx_first_pairing(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_STREQ(test, f->sep, "ochplLsfE"); + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, 128)); + KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_H_VERIFIED)); + + /* No pairing information: the attempt fails, nothing is encrypted. */ + f = fake_new(test, &tx, false, 0); + f->events &= ~BIT(DCP_HDCP_AUTH_PAIRING); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, f->encryption); +} + +static void tx_repeater_types(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f; + u8 *sm; + u8 type; + + for (type = 0; type <= 1; type++) { + f = fake_new(test, &tx, true, type); + f->stored = true; + KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_STREQ(test, f->sep, "ochlLsrmfE"); + KUNIT_EXPECT_TRUE(test, tx.repeater); + KUNIT_EXPECT_EQ(test, tx.device_count, 1); + KUNIT_EXPECT_EQ(test, tx.depth, 1); + /* The ack carries V's low half. */ + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_V_OFFSET, 16)); + KUNIT_EXPECT_EQ(test, *reg(f, DP_HDCP_2_2_REG_V_OFFSET), 0x22); + /* seq_num_M 0, k 1, stream 0 with the type asked for. */ + KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET, 7)); + sm = reg(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET); + KUNIT_EXPECT_EQ(test, get_unaligned_be24(sm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_be16(sm + 3), 1); + KUNIT_EXPECT_EQ(test, sm[5], 0); + KUNIT_EXPECT_EQ(test, sm[6], type); + KUNIT_EXPECT_EQ(test, tx.seq_num_m, 1); + KUNIT_EXPECT_FALSE(test, wrote(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, 1)); + KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_LIST_VERIFIED)); + KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_STREAM_READY)); + } +} + +static void tx_type1_refused_downstream_legacy(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f; + u8 legacy[] = { BIT(0), BIT(1) }; /* HDCP 1.x device, 2.0 repeater */ + int i; + + for (i = 0; i < ARRAY_SIZE(legacy); i++) { + f = fake_new(test, &tx, true, 1); + reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= legacy[i]; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPERM); + KUNIT_EXPECT_FALSE(test, f->encryption); + KUNIT_EXPECT_TRUE(test, tx.legacy_downstream); + dcp_hdcp_abort(&tx); + KUNIT_EXPECT_TRUE(test, f->closed); + /* Never asked to turn encryption off: it never went on. */ + KUNIT_EXPECT_EQ(test, f->sep[f->nsep - 1], 'x'); + + /* Type 0 goes through the same topology. */ + f = fake_new(test, &tx, true, 0); + reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= legacy[i]; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + } +} + +static void tx_topology_exceeded(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, true, 0); + + reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= BIT(3); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); + f = fake_new(test, &tx, true, 0); + reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= BIT(2); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); + /* A list that names no device. */ + f = fake_new(test, &tx, true, 0); + reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] = 0; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); + /* The first list of a session must carry seq_num_V 0. */ + f = fake_new(test, &tx, true, 0); + reg(f, DP_HDCP_2_2_REG_SEQ_NUM_V_OFFSET)[2] = 1; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPROTO); + KUNIT_EXPECT_FALSE(test, f->encryption); +} + +/* A certificate read too early or garbled never reaches the SEP. */ +static void tx_bad_receiver_id(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + memset(reg(f, DP_HDCP_2_2_REG_CERT_RX_OFFSET), 0xff, HDCP_2_2_RECEIVER_ID_LEN); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPROTO); + KUNIT_EXPECT_STREQ(test, tx.step, "check Receiver ID"); + KUNIT_EXPECT_FALSE(test, f->encryption); +} + +static void tx_revoked(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + /* The receiver's own ID: refused before the SEP sees the cert. */ + f->revoked_ids = 1; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPERM); + KUNIT_EXPECT_STREQ(test, f->sep, "o"); + + /* An SRM that cannot be read fails closed. */ + f = fake_new(test, &tx, false, 0); + f->revoked_ids = -EINVAL; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EINVAL); + KUNIT_EXPECT_FALSE(test, f->encryption); +} + +static void tx_timeout_and_rxstatus(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + f->stored = true; + f->events = 0; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, f->encryption); + + /* An overdue event, but RxStatus says H' is there. */ + f = fake_new(test, &tx, false, 0); + f->stored = true; + f->events = 0; + *reg(f, DP_HDCP_2_2_REG_RXSTATUS_OFFSET) = BIT(1); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + + /* An event on time: RxStatus is left to DCP. */ + f = fake_new(test, &tx, false, 0); + f->stored = true; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_FALSE(test, f->read_rxstatus); +} + +static void tx_close_mid_auth(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, true, 0); + + /* DCP closes while the ReceiverID list is awaited. */ + f->cancel_op = DCP_HDCP_AUTH_LIST; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ECANCELED); + KUNIT_EXPECT_FALSE(test, reported(f, DCP_HDCP_PROGRESS_LIST_VERIFIED)); + dcp_hdcp_abort(&tx); + KUNIT_EXPECT_TRUE(test, f->closed); + KUNIT_EXPECT_FALSE(test, f->encryption); + /* A second abort is harmless. */ + f->nsep = 0; + memset(f->sep, 0, sizeof(f->sep)); + dcp_hdcp_abort(&tx); + KUNIT_EXPECT_EQ(test, f->nsep, 0); +} + +static void tx_m_prime_retry(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, true, 1); + + f->m_rejects = 1; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_EQ(test, tx.seq_num_m, 2); + KUNIT_EXPECT_EQ(test, get_unaligned_be24(reg(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET)), 1); + + f = fake_new(test, &tx, true, 1); + f->m_rejects = 2; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EACCES); + KUNIT_EXPECT_FALSE(test, f->encryption); +} + +static void tx_not_capable(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + KUNIT_EXPECT_EQ(test, dcp_hdcp_capable(&tx), 1); + reg(f, DP_HDCP_2_2_REG_RX_CAPS_OFFSET)[2] = 0; + KUNIT_EXPECT_EQ(test, dcp_hdcp_capable(&tx), 0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ENODEV); + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&(struct dcp_hdcp_tx){ + .ops = &fake_ops, .ctx = f, .type = 2 }), + -EINVAL); + +} + +static void tx_l_prime_retry(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + /* Each retry starts with a fresh r_n. */ + f->stored = true; + f->l_rejects = DCP_HDCP_LC_TRIES - 1; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); + KUNIT_EXPECT_STREQ(test, f->sep, "ochlLlLlLsfE"); + + f = fake_new(test, &tx, false, 0); + f->stored = true; + f->l_rejects = DCP_HDCP_LC_TRIES; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EACCES); + KUNIT_EXPECT_STREQ(test, f->sep, "ochlLlLlL"); +} + +static void tx_sep_busy(struct kunit *test) +{ + struct dcp_hdcp_tx tx; + struct fake *f = fake_new(test, &tx, false, 0); + + f->sep_busy = true; + KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EAGAIN); + KUNIT_EXPECT_EQ(test, f->nwrites, 0); + dcp_hdcp_abort(&tx); + KUNIT_EXPECT_EQ(test, f->nsep, 0); +} + +static struct kunit_case dcp_hdcp_tx_cases[] = { + KUNIT_CASE(tx_stored_km_type0), + KUNIT_CASE(tx_first_pairing), + KUNIT_CASE(tx_repeater_types), + KUNIT_CASE(tx_type1_refused_downstream_legacy), + KUNIT_CASE(tx_topology_exceeded), + KUNIT_CASE(tx_revoked), + KUNIT_CASE(tx_bad_receiver_id), + KUNIT_CASE(tx_timeout_and_rxstatus), + KUNIT_CASE(tx_close_mid_auth), + KUNIT_CASE(tx_m_prime_retry), + KUNIT_CASE(tx_l_prime_retry), + KUNIT_CASE(tx_sep_busy), + KUNIT_CASE(tx_not_capable), + { } +}; + +static struct kunit_suite dcp_hdcp_tx_suite = { + .name = "apple-dcp-hdcp-tx", + .test_cases = dcp_hdcp_tx_cases, +}; +kunit_test_suite(dcp_hdcp_tx_suite); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx.c b/drivers/gpu/drm/apple/dcp-hdcp-tx.c new file mode 100644 index 00000000000000..222c0a74ab6d9a --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-tx.c @@ -0,0 +1,374 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +#include +#include +#include +#include +#include + +#include "dcp-hdcp-tx.h" + +/* Each step names itself, so a failed attempt says where it stopped. */ +#define TX_READ(tx, reg, buf, len) \ + ((tx)->step = "read " #reg, (tx)->ops->read((tx)->ctx, reg, buf, len)) +#define TX_WRITE(tx, reg, buf, len) \ + ((tx)->step = "write " #reg, (tx)->ops->write((tx)->ctx, reg, buf, len)) +#define TX_SEP(tx, fn) ((tx)->step = #fn, (tx)->ops->fn) + +static void tx_report(struct dcp_hdcp_tx *tx, enum dcp_hdcp_progress_code code, + bool encrypted) +{ + tx->ops->report(tx->ctx, code, true, tx->repeater, encrypted); +} + +/* + * Waits for a session event. DCP turns the receiver's RxStatus into these + * events, so RxStatus is read only once the event is overdue (spec time plus + * slack): a DisplayPort read clears the bits DCP waits for. Some paths (an + * on-board DP to HDMI converter) never raise the event although the receiver + * has the message ready. + */ +static int tx_wait(struct dcp_hdcp_tx *tx, enum dcp_hdcp_auth_op op, + unsigned int spec_ms) +{ + u8 status; + int ret; + + tx->step = "wait for DCP event"; + ret = tx->ops->wait(tx->ctx, op, spec_ms + DCP_HDCP_EVENT_SLACK_MS); + if (ret != -ETIMEDOUT) + return ret; + if (TX_READ(tx, DP_HDCP_2_2_REG_RXSTATUS_OFFSET, &status, 1)) + return -ETIMEDOUT; + switch (op) { + case DCP_HDCP_AUTH_H_PRIME: + return HDCP_2_2_DP_RXSTATUS_H_PRIME(status) ? 0 : -ETIMEDOUT; + case DCP_HDCP_AUTH_PAIRING: + return HDCP_2_2_DP_RXSTATUS_PAIRING(status) ? 0 : -ETIMEDOUT; + case DCP_HDCP_AUTH_LIST: + return HDCP_2_2_DP_RXSTATUS_READY(status) ? 0 : -ETIMEDOUT; + default: + return -ETIMEDOUT; + } +} + +/* Any revoked ID, or an SRM that cannot be read, fails the attempt. */ +static int tx_revocation(struct dcp_hdcp_tx *tx, u8 *ids, unsigned int count) +{ + int ret = tx->ops->revoked(tx->ctx, ids, count); + + if (ret > 0) + return -EPERM; + return ret; +} + +/* Twenty ones and twenty zeros, as every HDCP Receiver ID. */ +static bool dcp_hdcp_receiver_id_valid(const u8 *id) +{ + unsigned int i, ones = 0; + + for (i = 0; i < HDCP_2_2_RECEIVER_ID_LEN; i++) + ones += hweight8(id[i]); + return ones == 20; +} + +int dcp_hdcp_capable(struct dcp_hdcp_tx *tx) +{ + int ret = TX_READ(tx, DP_HDCP_2_2_REG_RX_CAPS_OFFSET, tx->rxcaps, + sizeof(tx->rxcaps)); + + if (ret) + return ret; + return dcp_hdcp_rxcaps_capable(tx->rxcaps); +} + +static int tx_ake(struct dcp_hdcp_tx *tx, bool *stored) +{ + u8 rtx[HDCP_2_2_RTX_LEN]; + u8 ekh_km_m[HDCP_2_2_E_KH_KM_M_LEN]; + u8 ekpub_km[HDCP_2_2_E_KPUB_KM_LEN]; + u8 h_prime[HDCP_2_2_H_PRIME_LEN]; + u8 ekh_km[HDCP_2_2_E_KH_KM_LEN]; + int ret; + + ret = TX_SEP(tx, sep_open)(tx->ctx, tx->channel, rtx); + if (ret) + return ret; + tx->sep_open = true; + + /* AKE_Init */ + tx->txcaps.version = HDCP_2_2_RX_CAPS_VERSION_VAL; + tx->txcaps.tx_cap_mask[0] = 0; + tx->txcaps.tx_cap_mask[1] = 0; + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RTX_OFFSET, rtx, sizeof(rtx)); + if (!ret) + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_TXCAPS_OFFSET, &tx->txcaps, + sizeof(tx->txcaps)); + if (ret) + return ret; + + /* AKE_Send_Cert: the receiver has 100 ms to make it readable. */ + tx->step = "wait for AKE_Send_Cert"; + tx->ops->sleep(tx->ctx, HDCP_2_2_CERT_TIMEOUT_MS); + ret = TX_READ(tx, DP_HDCP_2_2_REG_CERT_RX_OFFSET, &tx->cert, + sizeof(tx->cert)); + /* A Receiver ID has twenty ones and twenty zeros; anything else is a bad read. */ + if (!ret && !dcp_hdcp_receiver_id_valid(tx->cert.receiver_id)) { + tx->step = "check Receiver ID"; + ret = -EPROTO; + } + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_RRX_OFFSET, tx->rrx, + sizeof(tx->rrx)); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_RX_CAPS_OFFSET, tx->rxcaps, + sizeof(tx->rxcaps)); + if (ret) + return ret; + if (!dcp_hdcp_rxcaps_capable(tx->rxcaps)) + return -ENODEV; + tx->repeater = HDCP_2_2_RX_REPEATER(tx->rxcaps[2]); + ret = tx_revocation(tx, tx->cert.receiver_id, 1); + if (ret) + return ret; + ret = TX_SEP(tx, sep_ake_cert)(tx->ctx, tx->channel, (const u8 *)&tx->cert, + tx->rrx, stored, ekh_km_m, ekpub_km); + if (ret) + return ret; + + /* AKE_Stored_km (Ekh(km) then m, contiguous) or AKE_No_Stored_km */ + if (*stored) + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EKH_KM_WR_OFFSET, ekh_km_m, + sizeof(ekh_km_m)); + else + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, ekpub_km, + sizeof(ekpub_km)); + if (ret) + return ret; + tx_report(tx, DCP_HDCP_PROGRESS_KM_SENT, false); + + /* AKE_Send_H_prime */ + ret = tx_wait(tx, DCP_HDCP_AUTH_H_PRIME, + *stored ? HDCP_2_2_HPRIME_PAIRED_TIMEOUT_MS : + HDCP_2_2_HPRIME_NO_PAIRED_TIMEOUT_MS); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_HPRIME_OFFSET, h_prime, + sizeof(h_prime)); + if (!ret) + ret = TX_SEP(tx, sep_h_prime)(tx->ctx, tx->channel, tx->rxcaps, + (const u8 *)&tx->txcaps, h_prime); + if (ret) + return ret; + if (*stored) + return 0; + + /* AKE_Send_Pairing_Info */ + tx_report(tx, DCP_HDCP_PROGRESS_H_VERIFIED, false); + ret = tx_wait(tx, DCP_HDCP_AUTH_PAIRING, HDCP_2_2_PAIRING_TIMEOUT_MS); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_EKH_KM_RD_OFFSET, ekh_km, + sizeof(ekh_km)); + if (!ret) + ret = TX_SEP(tx, sep_pairing)(tx->ctx, tx->channel, ekh_km); + return ret; +} + +static int tx_lc_ske(struct dcp_hdcp_tx *tx) +{ + u8 rn[HDCP_2_2_RN_LEN]; + u8 l_prime[HDCP_2_2_L_PRIME_LEN]; + u8 edkey_ks[HDCP_2_2_E_DKEY_KS_LEN]; + u8 riv[HDCP_2_2_RIV_LEN]; + int attempt, ret; + + /* + * LC_Init, then LC_Send_L_prime once the receiver had its time. A + * wrong L' is retried with a fresh r_n, a bounded number of times. + */ + for (attempt = 0; attempt < DCP_HDCP_LC_TRIES; attempt++) { + ret = TX_SEP(tx, sep_lc_init)(tx->ctx, tx->channel, rn); + if (!ret) + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RN_OFFSET, rn, sizeof(rn)); + if (ret) + return ret; + tx->ops->sleep(tx->ctx, HDCP_2_2_DP_LPRIME_TIMEOUT_MS); + ret = TX_READ(tx, DP_HDCP_2_2_REG_LPRIME_OFFSET, l_prime, + sizeof(l_prime)); + if (!ret) + ret = TX_SEP(tx, sep_l_prime)(tx->ctx, tx->channel, l_prime); + if (ret != -EACCES) + break; + } + if (ret) + return ret; + + /* SKE_Send_Eks */ + ret = TX_SEP(tx, sep_ske)(tx->ctx, tx->channel, edkey_ks, riv); + if (!ret) + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EDKEY_KS_OFFSET, edkey_ks, + sizeof(edkey_ks)); + if (!ret) + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RIV_OFFSET, riv, sizeof(riv)); + if (!ret) + tx_report(tx, DCP_HDCP_PROGRESS_SKE_SENT, false); + return ret; +} + +static int tx_receiver_list(struct dcp_hdcp_tx *tx) +{ + u8 rxinfo[HDCP_2_2_RXINFO_LEN]; + u8 seq_num_v[HDCP_2_2_SEQ_NUM_LEN]; + u8 v_prime[HDCP_2_2_V_PRIME_HALF_LEN]; + u8 v[2 * HDCP_2_2_V_PRIME_HALF_LEN]; + unsigned int count; + int ret; + + ret = tx_wait(tx, DCP_HDCP_AUTH_LIST, HDCP_2_2_RECVID_LIST_TIMEOUT_MS); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_RXINFO_OFFSET, rxinfo, + sizeof(rxinfo)); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_SEQ_NUM_V_OFFSET, seq_num_v, + sizeof(seq_num_v)); + if (!ret) + ret = TX_READ(tx, DP_HDCP_2_2_REG_VPRIME_OFFSET, v_prime, + sizeof(v_prime)); + if (ret) + return ret; + + /* Topology: too many devices or levels downstream fails the attempt. */ + if (HDCP_2_2_MAX_CASCADE_EXCEEDED(rxinfo[1]) || + HDCP_2_2_MAX_DEVS_EXCEEDED(rxinfo[1])) + return -E2BIG; + count = (HDCP_2_2_DEV_COUNT_HI(rxinfo[0]) << 4) | + HDCP_2_2_DEV_COUNT_LO(rxinfo[1]); + if (!count || count > HDCP_2_2_MAX_DEVICE_COUNT) + return -E2BIG; + tx->device_count = count; + tx->depth = HDCP_2_2_DEPTH(rxinfo[0]); + tx->legacy_downstream = HDCP_2_2_HDCP1_DEVICE_CONNECTED(rxinfo[1]) || + HDCP_2_2_HDCP_2_0_REP_CONNECTED(rxinfo[1]); + /* The first list of a session carries seq_num_V 0. */ + if (get_unaligned_be24(seq_num_v)) + return -EPROTO; + + ret = TX_READ(tx, DP_HDCP_2_2_REG_RECV_ID_LIST_OFFSET, tx->ids, + count * HDCP_2_2_RECEIVER_ID_LEN); + if (ret) + return ret; + ret = tx_revocation(tx, tx->ids, count); + if (ret) + return ret; + ret = TX_SEP(tx, sep_repeater_list)(tx->ctx, tx->channel, tx->ids, count, + rxinfo, seq_num_v, v_prime, v); + if (ret) + return ret; + + /* RepeaterAuth_Send_Ack: the least significant 128 bits of V. */ + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_V_OFFSET, v + HDCP_2_2_V_PRIME_HALF_LEN, + HDCP_2_2_V_PRIME_HALF_LEN); + if (!ret) + tx_report(tx, DCP_HDCP_PROGRESS_LIST_VERIFIED, false); + return ret; +} + +/* + * RepeaterAuth_Stream_Manage for the one stream, then Stream_Ready. A wrong + * M' is retried once with the next seq_num_M, as the specification allows. + */ +static int tx_stream_manage(struct dcp_hdcp_tx *tx) +{ + u8 msg[HDCP_2_2_SEQ_NUM_LEN + 2 + sizeof(struct hdcp2_streamid_type)]; + u8 m_prime[HDCP_2_2_MPRIME_LEN]; + int attempt, ret = -EACCES; + + /* Type 1 must not reach an HDCP 1.x device or an HDCP 2.0 repeater. */ + if (tx->type && tx->legacy_downstream) + return -EPERM; + + for (attempt = 0; attempt < 2 && ret == -EACCES; attempt++) { + if (tx->seq_num_m > HDCP_2_2_SEQ_NUM_MAX) + return -ERANGE; + put_unaligned_be24(tx->seq_num_m, msg); + put_unaligned_be16(1, msg + HDCP_2_2_SEQ_NUM_LEN); + msg[HDCP_2_2_SEQ_NUM_LEN + 2] = 0; /* stream ID */ + msg[HDCP_2_2_SEQ_NUM_LEN + 3] = tx->type; + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET, msg, + sizeof(msg)); + if (ret) + return ret; + tx->ops->sleep(tx->ctx, HDCP_2_2_STREAM_READY_TIMEOUT_MS); + ret = TX_READ(tx, DP_HDCP_2_2_REG_MPRIME_OFFSET, m_prime, + sizeof(m_prime)); + if (ret) + return ret; + ret = TX_SEP(tx, sep_repeater_stream)(tx->ctx, tx->channel, 0, + tx->type, msg, m_prime); + tx->seq_num_m++; + } + if (!ret) + tx_report(tx, DCP_HDCP_PROGRESS_STREAM_READY, false); + return ret; +} + +int dcp_hdcp_authenticate(struct dcp_hdcp_tx *tx) +{ + bool stored = false; + int ret; + + tx->step = NULL; + if (tx->type > 1) + return -EINVAL; + tx->repeater = false; + tx->legacy_downstream = false; + tx->device_count = 0; + tx->depth = 0; + tx->seq_num_m = 0; + tx_report(tx, DCP_HDCP_PROGRESS_AKE, false); + + ret = tx_ake(tx, &stored); + if (ret) + return ret; + tx_report(tx, DCP_HDCP_PROGRESS_AKE_DONE, false); + ret = tx_lc_ske(tx); + if (ret) + return ret; + + if (tx->repeater) { + ret = tx_receiver_list(tx); + if (!ret) + ret = tx_stream_manage(tx); + } else { + ret = TX_WRITE(tx, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, &tx->type, + sizeof(tx->type)); + } + if (ret) + return ret; + + /* Encryption no sooner than 200 ms after SKE_Send_Eks. */ + ret = TX_SEP(tx, sep_finish)(tx->ctx, tx->channel); + if (ret) + return ret; + tx->ops->sleep(tx->ctx, HDCP_2_2_DELAY_BEFORE_ENCRYPTION_EN); + tx->encrypting = true; + ret = TX_SEP(tx, sep_set_encryption)(tx->ctx, tx->channel, true); + if (ret) + return ret; + tx_report(tx, DCP_HDCP_PROGRESS_ENCRYPTED, true); + return 0; +} + +void dcp_hdcp_abort(struct dcp_hdcp_tx *tx) +{ + if (tx->encrypting) + TX_SEP(tx, sep_set_encryption)(tx->ctx, tx->channel, false); + tx->encrypting = false; + if (tx->sep_open) + TX_SEP(tx, sep_close)(tx->ctx, tx->channel); + tx->sep_open = false; +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) +#include "dcp-hdcp-tx-test.c" +#endif diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx.h b/drivers/gpu/drm/apple/dcp-hdcp-tx.h new file mode 100644 index 00000000000000..f32189bb1556cb --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-tx.h @@ -0,0 +1,115 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2026 Ryan Murray */ +#ifndef __APPLE_DCP_HDCP_TX_H__ +#define __APPLE_DCP_HDCP_TX_H__ + +#include +#include +#include + +#include "dcp-hdcp-wire.h" + +/* + * One HDCP 2.2 transmitter authentication, as the AP runs it with the SEP + * doing the cryptography: every message is built from the fields the SEP + * returns and written to, or read from, the receiver's HDCP 2.2 registers + * through DCP. The procedure runs once DCP has opened a session and started + * it, and blocks: it waits for DCP's session events and sleeps where the + * specification asks for it. It never touches the display. + * + * DCP owns the receiver timeouts and closes an attempt that runs out of + * time; the waits below only guard against a session DCP forgets. + */ +#define DCP_HDCP_EVENT_SLACK_MS 500 +/* Locality check attempts, each with a fresh r_n. */ +#define DCP_HDCP_LC_TRIES 3 + +struct dcp_hdcp_tx_ops { + /* Receiver registers (DP_HDCP_2_2_REG_*). */ + int (*read)(void *ctx, u32 addr, void *buf, size_t len); + int (*write)(void *ctx, u32 addr, const void *buf, size_t len); + /* + * Waits up to @ms for session event @op. Returns 0 when it came, + * -ETIMEDOUT, or -ECANCELED when the session was closed or the + * protection is no longer wanted. + */ + int (*wait)(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms); + void (*report)(void *ctx, enum dcp_hdcp_progress_code code, + bool active, bool repeater, bool encrypted); + /* drm_hdcp_check_ksvs_revoked(): the count of revoked IDs, or <0. */ + int (*revoked)(void *ctx, u8 *ids, unsigned int count); + void (*sleep)(void *ctx, unsigned int ms); + + /* The SEP service, include/linux/apple-sep-hdcp.h. */ + int (*sep_open)(void *ctx, u32 ch, u8 *rtx); + int (*sep_ake_cert)(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, + bool *stored, u8 *ekh_km_m, u8 *ekpub_km); + int (*sep_h_prime)(void *ctx, u32 ch, const u8 *rxcaps, + const u8 *txcaps, const u8 *h_prime); + int (*sep_pairing)(void *ctx, u32 ch, const u8 *ekh_km); + int (*sep_lc_init)(void *ctx, u32 ch, u8 *rn); + int (*sep_l_prime)(void *ctx, u32 ch, const u8 *l_prime); + int (*sep_ske)(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv); + int (*sep_repeater_list)(void *ctx, u32 ch, const u8 *ids, + unsigned int count, const u8 *rxinfo, + const u8 *seq_num_v, const u8 *v_prime, u8 *v); + int (*sep_repeater_stream)(void *ctx, u32 ch, u8 stream_id, u8 type, + const u8 *seq_num_m, const u8 *m_prime); + int (*sep_finish)(void *ctx, u32 ch); + int (*sep_set_encryption)(void *ctx, u32 ch, bool on); + void (*sep_close)(void *ctx, u32 ch); +}; + +struct dcp_hdcp_tx { + const struct dcp_hdcp_tx_ops *ops; + void *ctx; + u32 channel; + /* The content type asked for: 0 or 1. */ + u8 type; + + /* Results, valid after dcp_hdcp_authenticate() returned 0. */ + bool repeater; + bool legacy_downstream; + unsigned int device_count; + unsigned int depth; + + /* Session state; @step names the last step tried. */ + const char *step; + bool sep_open; + bool encrypting; + u32 seq_num_m; + + /* Scratch: the messages of one attempt. */ + u8 rxcaps[HDCP_2_2_RXCAPS_LEN]; + struct hdcp2_tx_caps txcaps; + struct hdcp2_cert_rx cert; + u8 rrx[HDCP_2_2_RRX_LEN]; + u8 ids[HDCP_2_2_RECEIVER_IDS_MAX_LEN]; +}; + +/* The receiver says it does HDCP 2.2 over DP. */ +static inline bool dcp_hdcp_rxcaps_capable(const u8 *rxcaps) +{ + return rxcaps[0] == HDCP_2_2_RX_CAPS_VERSION_VAL && + HDCP_2_2_DP_HDCP_CAPABLE(rxcaps[2]); +} + +/* Reads RxCaps: 1 when the receiver can do HDCP 2.2, 0 when not, or <0. */ +int dcp_hdcp_capable(struct dcp_hdcp_tx *tx); + +/* + * Runs one authentication to encryption. On 0 the link is encrypted with + * tx->type; on failure the caller ends it with dcp_hdcp_abort(). -EAGAIN + * means the SEP was not available for now: no failure of the receiver. + */ +int dcp_hdcp_authenticate(struct dcp_hdcp_tx *tx); + +/* Encryption off and the SEP session closed; safe at any point. */ +void dcp_hdcp_abort(struct dcp_hdcp_tx *tx); + +/* + * The receiver's status on an encrypted link: 0 while it holds, -EAGAIN when + * it asks for re-authentication or reports a link integrity failure. + */ + +#endif /* __APPLE_DCP_HDCP_TX_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c b/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c new file mode 100644 index 00000000000000..2ca3e8c463dc10 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +#include +#include +#include + +#include "dcp-hdcp-wire.h" + +static void wire_read_encode(struct kunit *test) +{ + u8 body[DCP_HDCP_REG_ARGS_LEN + 522]; + + memset(body, 0xff, sizeof(body)); + KUNIT_ASSERT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), + DP_HDCP_2_2_REG_CERT_RX_OFFSET, + 522, DCP_HDCP_REG_TIMEOUT_MS), + (int)sizeof(body)); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body), 0x6900b); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 16), 522); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 32), 500); + KUNIT_EXPECT_EQ(test, body[4], 0); + KUNIT_EXPECT_EQ(test, body[sizeof(body) - 1], 0); + + /* No room, nothing, too much. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body) - 1, + 0x6900b, 522, 500), -EINVAL); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), + 0x69000, 0, 500), -EINVAL); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), + 0x69000, DCP_HDCP_REG_MAX + 1, + 500), -EINVAL); +} + +static void wire_read_check(struct kunit *test) +{ + u8 body[DCP_HDCP_REG_ARGS_LEN + 32]; + + dcp_hdcp_reg_read_encode(body, sizeof(body), DP_HDCP_2_2_REG_HPRIME_OFFSET, + 32, 500); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), + DP_HDCP_2_2_REG_HPRIME_OFFSET, + 32), 0); + /* Truncated: the data is not all there. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body) - 1, + DP_HDCP_2_2_REG_HPRIME_OFFSET, + 32), -EPROTO); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, 8, + DP_HDCP_2_2_REG_HPRIME_OFFSET, + 32), -EPROTO); + /* An answer for another register or another length. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), + DP_HDCP_2_2_REG_LPRIME_OFFSET, + 32), -EPROTO); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), + DP_HDCP_2_2_REG_HPRIME_OFFSET, + 16), -EPROTO); + /* An oversized ask is refused before any compare. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, SIZE_MAX, + DP_HDCP_2_2_REG_HPRIME_OFFSET, + DCP_HDCP_REG_MAX + 1), -EPROTO); +} + +static void wire_write(struct kunit *test) +{ + u8 body[DCP_HDCP_REG_ARGS_LEN + 8]; + u8 rtx[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + + KUNIT_ASSERT_EQ(test, dcp_hdcp_reg_write_encode(body, sizeof(body), + DP_HDCP_2_2_REG_RTX_OFFSET, + rtx, sizeof(rtx)), + (int)sizeof(body)); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 16), 0x69000); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 32), 8); + /* A write carries the AUX timeout too, at +48. */ + KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 48), DCP_HDCP_REG_TIMEOUT_MS); + KUNIT_EXPECT_MEMEQ(test, body + DCP_HDCP_REG_ARGS_LEN, rtx, sizeof(rtx)); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, sizeof(body), + 0x69000, 8), 0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, 63, 0x69000, 8), + -EPROTO); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, sizeof(body), + 0x69008, 8), -EPROTO); + KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_encode(body, sizeof(body) - 1, + 0x69000, rtx, 8), -EINVAL); +} + +static void wire_auth_reply(struct kunit *test) +{ + struct dcp_hdcp_word in = { .value = cpu_to_le32(0xffffffff) }; + struct dcp_hdcp_word out; + u8 small[8]; + + /* The open: the AP's answer says whether it takes the session. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, + sizeof(in), &out, sizeof(out), + true), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 1); + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, + sizeof(in), &out, sizeof(out), + false), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); + /* Others come back as they were. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_CONFIG, &in, + sizeof(in), &out, sizeof(out), + false), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0xffffffff); + /* A short open answer, another group, an unknown call. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, + sizeof(in), small, sizeof(small), + true), -EPROTO); + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(1, DCP_HDCP_AUTH_OPEN, &in, + sizeof(in), &out, sizeof(out), + true), -EOPNOTSUPP); + KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, 0x55, &in, sizeof(in), + &out, sizeof(out), true), + -EOPNOTSUPP); +} + +static void wire_report(struct kunit *test) +{ + struct dcp_hdcp_report r; + u8 *b = (u8 *)&r; + + dcp_hdcp_report_encode(&r, DCP_HDCP_PROGRESS_LIST_VERIFIED, true, true, + false); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 64), 0x78); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 16), 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 48), 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 32), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 0), 0); + dcp_hdcp_report_encode(&r, DCP_HDCP_PROGRESS_ENCRYPTED, true, false, true); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 64), 0x74); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 32), 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 0), 1); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 48), 0); +} + +static struct kunit_case dcp_hdcp_wire_cases[] = { + KUNIT_CASE(wire_read_encode), + KUNIT_CASE(wire_read_check), + KUNIT_CASE(wire_write), + KUNIT_CASE(wire_auth_reply), + KUNIT_CASE(wire_report), + { } +}; + +static struct kunit_suite dcp_hdcp_wire_suite = { + .name = "apple-dcp-hdcp-wire", + .test_cases = dcp_hdcp_wire_cases, +}; +kunit_test_suite(dcp_hdcp_wire_suite); + +MODULE_DESCRIPTION("KUnit tests for the Apple DCP HDCP service layouts"); +MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-wire.h b/drivers/gpu/drm/apple/dcp-hdcp-wire.h new file mode 100644 index 00000000000000..e3642647109243 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-wire.h @@ -0,0 +1,247 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2026 Ryan Murray */ +#ifndef __APPLE_DCP_HDCP_WIRE_H__ +#define __APPLE_DCP_HDCP_WIRE_H__ + +#include +#include +#include +#include +#include +#include + +/* + * The DCP services that carry HDCP 2.2, as standard EPIC service calls + * (struct epic_service_call, then the body described here): + * + * - The sink's DP device service ("dcpdp-device-epic") reads and writes the + * receiver's HDCP 2.2 registers, addressed as in the DisplayPort HDCP 2.2 + * register map (DP_HDCP_2_2_REG_*). DCP runs the AUX transaction. A + * built-in HDMI port behind an on-board DP to HDMI converter is reached + * the same way: the converter is the HDCP repeater. + * - The HDCP interface service ("dcpdptx-hdcp-interface"), one per port, + * takes the transmitter's capability once it is opened. + * - An authentication session service ("dcpdptx-hdcp-auth-session"), + * announced by DCP for each attempt, calls the AP with the session's + * events (open, start, H' ready, pairing ready, ReceiverID list ready, + * close) and takes progress reports. DCP owns the receiver timeouts: an + * attempt that runs out of time is closed by DCP and opened again. + * + * Every body field is a little-endian 32-bit word at a 16-byte stride. + */ + +/* Register access on the DP device service. */ +#define DCP_HDCP_REG_GROUP 1 +#define DCP_HDCP_REG_READ 6 +#define DCP_HDCP_REG_WRITE 7 +/* The register arguments, then the data. */ +#define DCP_HDCP_REG_ARGS_LEN 64 +/* The longest register block: the receiver certificate. */ +#define DCP_HDCP_REG_MAX 1024 +/* The timeout DCP applies to a register read or write on the AUX side. */ +#define DCP_HDCP_REG_TIMEOUT_MS 500 + +/* The device service's query, the first call of a session. */ +#define DCP_HDCP_DEV_GROUP 0 +#define DCP_HDCP_DEV_QUERY 4 +#define DCP_HDCP_DEV_QUERY_LEN 0x20 +/* Its counterpart when the session ends: DCP waits for it before power-down. */ +#define DCP_HDCP_DEV_END 5 +#define DCP_HDCP_DEV_END_LEN 0x10 +/* The device service's information call, once after it is opened. */ +#define DCP_HDCP_DEV_INFO 0xc +#define DCP_HDCP_DEV_INFO_LEN 0x50 + +/* The HDCP interface service's capability call. */ +#define DCP_HDCP_IF_GROUP 4 +#define DCP_HDCP_IF_CAPS 6 +#define DCP_HDCP_IF_CAPS_LEN 0x20 +#define DCP_HDCP_IF_CAPS_VALUE 3 + +/* The authentication session's calls to the AP (group 0). */ +enum dcp_hdcp_auth_op { + DCP_HDCP_AUTH_START = 0x0, + DCP_HDCP_AUTH_CONFIG = 0x1, + DCP_HDCP_AUTH_OPEN = 0x7, + DCP_HDCP_AUTH_CLOSE = 0x8, + DCP_HDCP_AUTH_H_PRIME = 0x9, /* H' is available */ + DCP_HDCP_AUTH_PAIRING = 0xa, /* pairing information is available */ + DCP_HDCP_AUTH_LIST = 0xb, /* the ReceiverID list is available */ +}; + +/* The AP's progress report on the session. */ +#define DCP_HDCP_REPORT_GROUP 2 +#define DCP_HDCP_REPORT_PROGRESS 6 +#define DCP_HDCP_REPORT_LEN 0x50 + +enum dcp_hdcp_progress_code { + DCP_HDCP_PROGRESS_IDLE = 0x65, /* opened, or closed again */ + DCP_HDCP_PROGRESS_STARTED = 0x66, + DCP_HDCP_PROGRESS_AKE = 0x69, /* AKE running */ + DCP_HDCP_PROGRESS_KM_SENT = 0x6c, + DCP_HDCP_PROGRESS_H_VERIFIED = 0x6d, /* pairing still to come */ + DCP_HDCP_PROGRESS_AKE_DONE = 0x70, + DCP_HDCP_PROGRESS_STREAM_READY = 0x72, + DCP_HDCP_PROGRESS_ENCRYPTED = 0x74, + DCP_HDCP_PROGRESS_SKE_SENT = 0x75, + DCP_HDCP_PROGRESS_LIST_VERIFIED = 0x78, +}; + +struct dcp_hdcp_reg_read { + __le32 addr; + __le32 rsvd0[3]; + __le32 len; + __le32 rsvd1[3]; + __le32 timeout_ms; + __le32 rsvd2[7]; +} __packed; +static_assert(sizeof(struct dcp_hdcp_reg_read) == DCP_HDCP_REG_ARGS_LEN); + +struct dcp_hdcp_reg_write { + __le32 rsvd0[4]; + __le32 addr; + __le32 rsvd1[3]; + __le32 len; + __le32 rsvd2[3]; + __le32 timeout_ms; + __le32 rsvd3[3]; +} __packed; +static_assert(sizeof(struct dcp_hdcp_reg_write) == DCP_HDCP_REG_ARGS_LEN); + +/* One word at offset 16: the interface capability, the open's acceptance. */ +struct dcp_hdcp_word { + __le32 rsvd0[4]; + __le32 value; + __le32 rsvd1[3]; +} __packed; +static_assert(sizeof(struct dcp_hdcp_word) == DCP_HDCP_IF_CAPS_LEN); + +struct dcp_hdcp_report { + __le32 authenticated; + __le32 rsvd0[3]; + __le32 active; + __le32 rsvd1[3]; + __le32 encrypted; + __le32 rsvd2[3]; + __le32 repeater; + __le32 rsvd3[3]; + __le32 code; + __le32 rsvd4[3]; +} __packed; +static_assert(sizeof(struct dcp_hdcp_report) == DCP_HDCP_REPORT_LEN); + +static inline bool dcp_hdcp_reg_len_ok(size_t len) +{ + return len && len <= DCP_HDCP_REG_MAX; +} + +/* A read request: the arguments, then @len zero bytes for the data. */ +static inline int dcp_hdcp_reg_read_encode(void *body, size_t room, u32 addr, + size_t len, u32 timeout_ms) +{ + struct dcp_hdcp_reg_read *a = body; + + if (!dcp_hdcp_reg_len_ok(len) || room < DCP_HDCP_REG_ARGS_LEN + len) + return -EINVAL; + memset(body, 0, DCP_HDCP_REG_ARGS_LEN + len); + a->addr = cpu_to_le32(addr); + a->len = cpu_to_le32(len); + a->timeout_ms = cpu_to_le32(timeout_ms); + return DCP_HDCP_REG_ARGS_LEN + len; +} + +/* + * A read answer: it must name the register block asked for and carry all of + * its bytes. On success the data starts at body + DCP_HDCP_REG_ARGS_LEN. + */ +static inline int dcp_hdcp_reg_read_check(const void *body, size_t received, + u32 addr, size_t len) +{ + const struct dcp_hdcp_reg_read *a = body; + + if (!dcp_hdcp_reg_len_ok(len) || received < DCP_HDCP_REG_ARGS_LEN + len) + return -EPROTO; + if (le32_to_cpu(a->addr) != addr || le32_to_cpu(a->len) != len) + return -EPROTO; + return 0; +} + +static inline int dcp_hdcp_reg_write_encode(void *body, size_t room, u32 addr, + const void *data, size_t len) +{ + struct dcp_hdcp_reg_write *a = body; + + if (!dcp_hdcp_reg_len_ok(len) || room < DCP_HDCP_REG_ARGS_LEN + len) + return -EINVAL; + memset(body, 0, DCP_HDCP_REG_ARGS_LEN); + a->addr = cpu_to_le32(addr); + a->len = cpu_to_le32(len); + a->timeout_ms = cpu_to_le32(DCP_HDCP_REG_TIMEOUT_MS); + memcpy(body + DCP_HDCP_REG_ARGS_LEN, data, len); + return DCP_HDCP_REG_ARGS_LEN + len; +} + +static inline int dcp_hdcp_reg_write_check(const void *body, size_t received, + u32 addr, size_t len) +{ + const struct dcp_hdcp_reg_write *a = body; + + if (received < DCP_HDCP_REG_ARGS_LEN) + return -EPROTO; + if (le32_to_cpu(a->addr) != addr || le32_to_cpu(a->len) != len) + return -EPROTO; + return 0; +} + +static inline bool dcp_hdcp_auth_op_known(u32 op) +{ + switch (op) { + case DCP_HDCP_AUTH_START: + case DCP_HDCP_AUTH_CONFIG: + case DCP_HDCP_AUTH_OPEN: + case DCP_HDCP_AUTH_CLOSE: + case DCP_HDCP_AUTH_H_PRIME: + case DCP_HDCP_AUTH_PAIRING: + case DCP_HDCP_AUTH_LIST: + return true; + default: + return false; + } +} + +/* + * The AP's answer to a session call: the call's body back, and for the open + * whether the AP takes the session (1) or not (0). + */ +static inline int dcp_hdcp_auth_reply(u16 group, u32 op, const void *data, + size_t size, void *reply, size_t room, + bool accept) +{ + if (group || !dcp_hdcp_auth_op_known(op)) + return -EOPNOTSUPP; + memset(reply, 0, room); + memcpy(reply, data, min(size, room)); + if (op == DCP_HDCP_AUTH_OPEN) { + struct dcp_hdcp_word *w = reply; + + if (room < sizeof(*w)) + return -EPROTO; + w->value = cpu_to_le32(accept); + } + return 0; +} + +static inline void dcp_hdcp_report_encode(struct dcp_hdcp_report *r, + enum dcp_hdcp_progress_code code, + bool active, bool repeater, + bool encrypted) +{ + memset(r, 0, sizeof(*r)); + r->code = cpu_to_le32(code); + r->active = cpu_to_le32(active); + r->repeater = cpu_to_le32(repeater); + r->encrypted = cpu_to_le32(encrypted); + r->authenticated = cpu_to_le32(encrypted); +} + +#endif /* __APPLE_DCP_HDCP_WIRE_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp.h b/drivers/gpu/drm/apple/dcp-hdcp.h new file mode 100644 index 00000000000000..536bf67966137c --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp.h @@ -0,0 +1,230 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2026 Ryan Murray */ +#ifndef __APPLE_DCP_HDCP_H__ +#define __APPLE_DCP_HDCP_H__ + +#include +#include +#include +#include +#include +#include +#include + +/* + * HDCP 2.2 on an external connector, as the AP runs it: the AP is the + * transmitter, the SEP holds its secrets and does the cryptography, and DCP + * carries the receiver's messages over the link (see dcp-hdcp-wire.h). The + * built-in panel never gets a receiver session, so this never applies to it. + * + * This file is the Content Protection policy, with no hardware behind it: + * + * - DCP opens an authentication session after the link comes up. The AP + * takes it only while protection is DESIRED, the SEP service and the DCP + * relay are bound and no backoff is pending; otherwise it declines. + * - ENABLED needs a complete authentication, the 200 ms wait and an + * acknowledged encryption enable, all in one session on one link + * generation. + * - A failure, a session DCP closes before the end, a new link generation, + * or the SEP service or relay going away drops the session to DESIRED and + * asks for teardown: encryption off and the SEP session closed. A late + * result from a session or generation that is gone is ignored. The display + * itself is never touched: a failed session leaves an unprotected, working + * output. + * - A changed content type re-authenticates; UNDESIRED tears down. + * - Retries back off: DCP_HDCP_RETRY_MS doubled per failure, capped at + * DCP_HDCP_RETRY_MAX_MS, reset by a success or a new link generation. + */ +#define DCP_HDCP_RETRY_MS 1000 +#define DCP_HDCP_RETRY_MAX_MS 60000 + +/* + * Message sizes, msg_id byte included, as the public structures define + * them. The register blocks DCP moves are these without the msg_id byte. + */ +static_assert(sizeof(struct hdcp2_ake_init) == 12); +static_assert(sizeof(struct hdcp2_ake_send_cert) == 534); +static_assert(sizeof(struct hdcp2_ake_stored_km) == 33); +static_assert(sizeof(struct hdcp2_ake_send_hprime) == 33); +static_assert(sizeof(struct hdcp2_lc_init) == 9); +static_assert(sizeof(struct hdcp2_lc_send_lprime) == 33); +static_assert(sizeof(struct hdcp2_ske_send_eks) == 25); + +enum dcp_hdcp_state { + DCP_HDCP_OFF, /* userspace does not want protection */ + DCP_HDCP_DESIRED, /* wanted; no session running */ + DCP_HDCP_AUTH, /* a session is running */ + DCP_HDCP_ENABLED, /* encryption on, acknowledged */ +}; + +enum dcp_hdcp_action { + DCP_HDCP_NONE, + DCP_HDCP_TEARDOWN, /* encryption off and close, display untouched */ + DCP_HDCP_KICK, /* ask DCP for a session */ +}; + +struct dcp_hdcp_link { + enum dcp_hdcp_state state; + u8 type; /* the content type asked for: 0 or 1 */ + u32 generation; /* link generation of the running session */ + unsigned long retry_at; + unsigned int failures; + bool hold; /* the SEP was busy: wait until retry_at */ + bool relay; /* the DCP relay is bound */ + bool sep; /* the SEP service is up */ +}; + +/* + * The property exists on an external connector whose display processor has + * an HDCP channel, with the SEP service built in. Whether a session can run + * is decided at runtime: until then the property stays DESIRED. + */ +static inline bool dcp_hdcp_attach_property(bool external, bool channel, bool sep) +{ + return external && channel && sep; +} + +static inline u64 dcp_hdcp_property(const struct dcp_hdcp_link *l) +{ + switch (l->state) { + case DCP_HDCP_OFF: + return DRM_MODE_CONTENT_PROTECTION_UNDESIRED; + case DCP_HDCP_ENABLED: + return DRM_MODE_CONTENT_PROTECTION_ENABLED; + default: + return DRM_MODE_CONTENT_PROTECTION_DESIRED; + } +} + +static inline unsigned long dcp_hdcp_backoff(unsigned int failures) +{ + unsigned long ms = DCP_HDCP_RETRY_MS; + + while (failures-- > 1 && ms < DCP_HDCP_RETRY_MAX_MS) + ms *= 2; + return msecs_to_jiffies(min_t(unsigned long, ms, DCP_HDCP_RETRY_MAX_MS)); +} + +/* A session may start now. */ +static inline bool dcp_hdcp_ready(const struct dcp_hdcp_link *l, + unsigned long now) +{ + return l->state == DCP_HDCP_DESIRED && l->relay && l->sep && + !((l->failures || l->hold) && time_before(now, l->retry_at)); +} + +/* Drops a session; teardown is owed if one was running. */ +static inline enum dcp_hdcp_action dcp_hdcp_drop(struct dcp_hdcp_link *l, + bool failed, unsigned long now) +{ + bool running = l->state == DCP_HDCP_AUTH || l->state == DCP_HDCP_ENABLED; + + if (l->state != DCP_HDCP_OFF) + l->state = DCP_HDCP_DESIRED; + if (failed) { + l->failures++; + l->retry_at = now + dcp_hdcp_backoff(l->failures); + } + return running ? DCP_HDCP_TEARDOWN : DCP_HDCP_NONE; +} + +/* + * Userspace set the property: @want is DESIRED (true) or UNDESIRED, @type + * the content type. + */ +static inline enum dcp_hdcp_action dcp_hdcp_request(struct dcp_hdcp_link *l, + bool want, u8 type, + unsigned long now) +{ + if (!want) { + enum dcp_hdcp_action a = dcp_hdcp_drop(l, false, now); + + l->state = DCP_HDCP_OFF; + return a; + } + if (l->state == DCP_HDCP_OFF) + l->state = DCP_HDCP_DESIRED; + if (type != l->type) { + l->type = type; + /* A running session protects the old type: start again. */ + if (dcp_hdcp_drop(l, false, now) == DCP_HDCP_TEARDOWN) + return DCP_HDCP_TEARDOWN; + } + return dcp_hdcp_ready(l, now) ? DCP_HDCP_KICK : DCP_HDCP_NONE; +} + +/* DCP opened a session on link generation @gen: true if the AP takes it. */ +static inline bool dcp_hdcp_open(struct dcp_hdcp_link *l, u32 gen, + unsigned long now) +{ + if (!dcp_hdcp_ready(l, now)) + return false; + l->state = DCP_HDCP_AUTH; + l->generation = gen; + return true; +} + +/* + * The session on generation @gen ended its authentication with @result: 0, + * -EAGAIN when the SEP was not available for now (retried after the first + * backoff step, not counted as a failure), or another error. + */ +static inline enum dcp_hdcp_action dcp_hdcp_auth_done(struct dcp_hdcp_link *l, + u32 gen, int result, + unsigned long now) +{ + /* A late result, from a session or generation that is gone. */ + if (l->state != DCP_HDCP_AUTH || gen != l->generation) + return DCP_HDCP_NONE; + if (result == -EAGAIN) { + l->hold = true; + l->retry_at = now + dcp_hdcp_backoff(1); + return dcp_hdcp_drop(l, false, now); + } + if (result) + return dcp_hdcp_drop(l, true, now); + l->state = DCP_HDCP_ENABLED; + l->failures = 0; + l->hold = false; + return DCP_HDCP_NONE; +} + +/* + * DCP closed the session, or the receiver asked for re-authentication: a + * session that had not finished failed; an enabled one is redone at once. + */ +static inline enum dcp_hdcp_action dcp_hdcp_closed(struct dcp_hdcp_link *l, + u32 gen, unsigned long now) +{ + if (gen != l->generation) + return DCP_HDCP_NONE; + if (l->state == DCP_HDCP_AUTH) + return dcp_hdcp_drop(l, true, now); + return dcp_hdcp_drop(l, false, now); +} + +/* The link retrained, went away or came back: it is now generation @gen. */ +static inline enum dcp_hdcp_action dcp_hdcp_link_event(struct dcp_hdcp_link *l, + u32 gen, unsigned long now) +{ + if (gen == l->generation) + return DCP_HDCP_NONE; + l->failures = 0; + l->hold = false; + l->generation = gen; + return dcp_hdcp_drop(l, false, now); +} + +/* The SEP service or the DCP relay came or went. */ +static inline enum dcp_hdcp_action dcp_hdcp_bind(struct dcp_hdcp_link *l, + bool relay, bool sep, + unsigned long now) +{ + l->relay = relay; + l->sep = sep; + if (relay && sep) + return dcp_hdcp_ready(l, now) ? DCP_HDCP_KICK : DCP_HDCP_NONE; + return dcp_hdcp_drop(l, false, now); +} + +#endif /* __APPLE_DCP_HDCP_H__ */ From 799a8e35c37397b4170705823a830f0402dbdafd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 06:20:02 +1100 Subject: [PATCH 1446/1514] drm: apple: run HDCP 2.2 on external outputs with Content Protection Expose the standard "Content Protection" and "HDCP Content Type" connector properties on external DisplayPort, HDMI and USB-C connectors (never on a built-in panel) and run the HDCP 2.2 transmitter over the DCP services: - Bind the DP device service and the HDCP interface and auth-session services by EPIC name, on the classic and the compact announcement paths alike (their provider classes are shared with other services). Start the DP device and HDCP interface endpoints when nothing else drives them. - Each auth session DCP announces gets a handler: DCP announces one per protocol version and closes each before it powers down. Sessions announced for HDCP 1.x are declined. - Take a session DCP opens only while protection is desired; answer every session call; report the transmitter's progress; pair the device service's session query with its end call when the session closes. - ENABLED only after the SEP's encryption enable and the final progress report. A failure, a session close, unplug, DPMS off, suspend or unbind turns encryption off, closes the SEP session and drops back to DESIRED; the picture is not touched. Re-authentication backs off from 1 s to 60 s. Link integrity stays with DCP, which closes the session on a re-authentication request or a link failure. - The SEP channel comes from the display node's "apple,hdcp-channels". DCP offers a session only when the link comes up, so a request made while no session is offered is served at the next link-up (DPMS, mode set, hotplug or resume). Off by default: appledrm.hdcp=1 enables it. KUnit: apple-dcp-hdcp-glue. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/Makefile | 2 +- drivers/gpu/drm/apple/afk.c | 27 +- drivers/gpu/drm/apple/apple_drv.c | 18 + drivers/gpu/drm/apple/connector.h | 9 + drivers/gpu/drm/apple/dcp-hdcp-drv.h | 76 ++ drivers/gpu/drm/apple/dcp-hdcp-glue-test.c | 139 +++ drivers/gpu/drm/apple/dcp-hdcp.c | 1118 ++++++++++++++++++++ drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp.c | 23 + drivers/gpu/drm/apple/iomfb.c | 4 + 10 files changed, 1408 insertions(+), 10 deletions(-) create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-drv.h create mode 100644 drivers/gpu/drm/apple/dcp-hdcp-glue-test.c create mode 100644 drivers/gpu/drm/apple/dcp-hdcp.c diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index c20e07e9edfcad..fa82d847891efe 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -41,7 +41,7 @@ appledrm-y += epic/dpavservep.o appledrm-y += epic/panelavep.o appledrm-y += plane.o appledrm-y += dcp-indicator.o -appledrm-$(CONFIG_DRM_APPLE_HDCP) += dcp-hdcp-tx.o +appledrm-$(CONFIG_DRM_APPLE_HDCP) += dcp-hdcp.o dcp-hdcp-tx.o appledrm-$(CONFIG_TRACING) += trace.o diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index cb72d998412956..b21d34ac8cef64 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -24,6 +24,7 @@ #include #include "afk.h" +#include "dcp-hdcp-drv.h" #include "afkv2-codec.h" #include "afk_reply.h" #include "trace.h" @@ -458,7 +459,7 @@ afk_match_service(struct apple_dcp_afkep *ep, const char *name) return ops; } - return NULL; + return dcp_hdcp_match_service(ep, name, false); } static struct apple_epic_service *afk_epic_find_service(struct apple_dcp_afkep *ep, @@ -830,6 +831,7 @@ afk_compact_match_service(struct apple_dcp_afkep *ep, const char *name) const struct apple_epic_service_ops *ops, *any = NULL; const char *service_name; size_t len; + bool cut; if (!name[0] || !ep->ops) return NULL; @@ -856,13 +858,14 @@ afk_compact_match_service(struct apple_dcp_afkep *ep, const char *name) } /* An announcement that filled its field may have lost its end. */ - if (strlen(name) < AFK_COMPACT_NAME_LEN - 1) - return any; - for (ops = ep->ops; ops->name[0]; ops++) - if (afk_compact_cut_of(ops, service_name)) - return ops; + cut = strlen(name) >= AFK_COMPACT_NAME_LEN - 1; + if (cut) + for (ops = ep->ops; ops->name[0]; ops++) + if (afk_compact_cut_of(ops, service_name)) + return ops; - return any; + /* The HDCP services, by name, wherever they are announced. */ + return dcp_hdcp_match_service(ep, service_name, cut) ?: any; } /* @@ -1901,9 +1904,15 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, } } - if (ep->match_epic_name) + /* + * The HDCP services go by their EPIC name: their provider classes are + * shared with other services (the DP device class also names the AV + * device, the interface class names the port controllers). + */ + ops = dcp_hdcp_match_service(ep, epic_name, false); + if (!ops && ep->match_epic_name) ops = afk_match_service(ep, epic_name); - else + else if (!ops) ops = afk_match_service(ep, service_name); if (dcp_is_ext26(ep->dcp)) dev_dbg(ep->dcp->dev, diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index f39238a60bb22d..2f7f86e5e0308d 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -54,6 +54,7 @@ #include "apple_resume.h" #include "dcp-hdr-metadata.h" #include "dcp.h" +#include "dcp-hdcp-drv.h" #include "plane.h" #include "iomfb_m4.h" #include "t8132_ext_drm.h" @@ -1035,6 +1036,8 @@ static void apple_atomic_commit_tail(struct drm_atomic_commit *state) DRM_PLANE_COMMIT_ACTIVE_ONLY); drm_atomic_helper_fake_vblank(state); drm_atomic_helper_commit_hw_done(state); + /* Content Protection requests go to the display processors' queues. */ + dcp_hdcp_commit(state); drm_atomic_helper_wait_for_flip_done(state->dev, state); apple_fail_lost_flips(state); drm_atomic_helper_cleanup_planes(state->dev, state); @@ -1150,6 +1153,7 @@ static int apple_connector_atomic_check(struct drm_connector *conn, const struct drm_property_blob *blob = new->hdr_output_metadata; struct drm_crtc_state *crtc_state; + dcp_hdcp_atomic_check(conn, state); if (blob && (blob->length != sizeof(struct hdr_output_metadata) || !dcp_hdr_is_type1(blob->data))) return -EINVAL; @@ -1356,6 +1360,9 @@ static int apple_connector_create(struct drm_device *drm, dcp_ext_color_props_supported(dcp)); if (ret) goto err_cleanup; + ret = dcp_hdcp_attach_connector(connector, &dcp, 1, connector_type); + if (ret) + goto err_cleanup; connector->base.polled = DRM_CONNECTOR_POLL_HPD; connector->connected = false; @@ -1718,6 +1725,17 @@ static int apple_probe_typec_ports(struct drm_device *drm, connector->connected = false; connector->dcp = NULL; + /* Content Protection where a pipeline that can drive the port has HDCP. */ + for (i = 0; i < num_dcp; i++) { + if (pipeline ? dcp[i] != pipeline : + !dcp_typec_port_has_candidate(port_idx, dcp[i])) + continue; + ret = dcp_hdcp_attach_connector(connector, &dcp[i], 1, + DRM_MODE_CONNECTOR_DisplayPort); + if (ret) + return ret; + } + /* * One encoder per connector, covering its allowed pipelines. * T6050 connectors each cover exactly one. Attaching several diff --git a/drivers/gpu/drm/apple/connector.h b/drivers/gpu/drm/apple/connector.h index 5d8c1674503fcf..ff01bb3b5cef46 100644 --- a/drivers/gpu/drm/apple/connector.h +++ b/drivers/gpu/drm/apple/connector.h @@ -89,6 +89,15 @@ struct apple_connector { * chosen one; -1 until then, and nothing is sent. */ int bl_level; + + /* + * Content Protection (dcp-hdcp-drv.h): the property is attached, and + * what the last commit asked for. Written by the commit tail, read by + * the display processor that drives the connector. + */ + bool hdcp_attached; + bool hdcp_want; + u8 hdcp_type; }; #define to_apple_connector(x) container_of(x, struct apple_connector, base) diff --git a/drivers/gpu/drm/apple/dcp-hdcp-drv.h b/drivers/gpu/drm/apple/dcp-hdcp-drv.h new file mode 100644 index 00000000000000..cf08236cbb5595 --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-drv.h @@ -0,0 +1,76 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +/* Copyright 2026 Ryan Murray */ +#ifndef __APPLE_DCP_HDCP_DRV_H__ +#define __APPLE_DCP_HDCP_DRV_H__ + +#include +#include + +struct apple_connector; +struct apple_dcp; +struct apple_dcp_afkep; +struct apple_epic_service_ops; +struct drm_atomic_commit; +struct drm_connector; +struct platform_device; + +/* + * HDCP 2.2 on the display processors' external outputs: the DCP services + * (dcp-hdcp-wire.h), the transmitter (dcp-hdcp-tx.h) and the Content + * Protection policy (dcp-hdcp.h), joined to the connector properties. + */ +/* Whether something already drives @endpoint (dcp.c). */ +bool dcp_endpoint_routed(struct apple_dcp *dcp, u8 endpoint); + +#if IS_ENABLED(CONFIG_DRM_APPLE_HDCP) +/* A display processor's HDCP state, if it has an HDCP channel; idempotent. */ +struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp); +void dcp_hdcp_fini(struct apple_dcp *dcp); +/* Starts the DP device and HDCP interface endpoints when no other path did. */ +void dcp_hdcp_start_endpoints(struct apple_dcp *dcp); +/* Routes the endpoints this file started. */ +struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, u32 endpoint); +/* The HDCP services, matched by name ahead of a catch-all. */ +const struct apple_epic_service_ops * +dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, + bool cut); +/* Hotplug, power off or on, suspend, a new route: a new link generation. */ +void dcp_hdcp_link_changed(struct apple_dcp *dcp); + +int dcp_hdcp_attach_connector(struct apple_connector *connector, + struct platform_device **dcps, unsigned int n, + int connector_type); +void dcp_hdcp_atomic_check(struct drm_connector *conn, + struct drm_atomic_commit *state); +void dcp_hdcp_commit(struct drm_atomic_commit *state); +#else +static inline struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) { return NULL; } +static inline void dcp_hdcp_fini(struct apple_dcp *dcp) { } +static inline void dcp_hdcp_start_endpoints(struct apple_dcp *dcp) { } +static inline struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, + u32 endpoint) +{ + return NULL; +} + +static inline const struct apple_epic_service_ops * +dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, + bool cut) +{ + return NULL; +} + +static inline void dcp_hdcp_link_changed(struct apple_dcp *dcp) { } +static inline int dcp_hdcp_attach_connector(struct apple_connector *connector, + struct platform_device **dcps, + unsigned int n, int connector_type) +{ + return 0; +} + +static inline void dcp_hdcp_atomic_check(struct drm_connector *conn, + struct drm_atomic_commit *state) { } +static inline void dcp_hdcp_commit(struct drm_atomic_commit *state) { } +#endif + +#endif /* __APPLE_DCP_HDCP_DRV_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c b/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c new file mode 100644 index 00000000000000..92dcf8e37da4fe --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c @@ -0,0 +1,139 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +/* The HDCP services' matching and the session's answers. Included from dcp-hdcp.c. */ + +#include + +struct glue_fixture { + struct apple_dcp dcp; + struct apple_dcp_afkep ep; + struct dcp_hdcp h; + struct apple_epic_service service; +}; + +static struct glue_fixture *glue_new(struct kunit *test, bool with_hdcp) +{ + struct glue_fixture *g = kunit_kzalloc(test, sizeof(*g), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, g); + g->ep.dcp = &g->dcp; + g->service.ep = &g->ep; + g->h.dcp = &g->dcp; + if (with_hdcp) + g->dcp.hdcp = &g->h; + return g; +} + +static void glue_match_by_name(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, true); + const struct apple_epic_service_ops *ops; + + ops = dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic:0", false); + KUNIT_ASSERT_NOT_NULL(test, ops); + KUNIT_EXPECT_PTR_EQ(test, (void *)ops->init, (void *)dcp_hdcp_relay_init); + ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-interface", false); + KUNIT_ASSERT_NOT_NULL(test, ops); + KUNIT_EXPECT_PTR_EQ(test, (void *)ops->init, (void *)dcp_hdcp_iface_init); + ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-auth-session", false); + KUNIT_ASSERT_NOT_NULL(test, ops); + KUNIT_EXPECT_PTR_EQ(test, (void *)ops->call_v2, (void *)dcp_hdcp_session_call); + + /* A cut long name matches only when the announcement filled its field. */ + KUNIT_EXPECT_NOT_NULL(test, dcp_hdcp_match_service(&g->ep, + "dcpdptx-hdcp-auth-sess", true)); + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, + "dcpdptx-hdcp-auth-sess", false)); + /* Other names, and a longer name that only starts the same. */ + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpav-device-epic", true)); + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epicx", false)); + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, NULL, false)); + + /* Without HDCP on this processor nothing is taken. */ + g = glue_new(test, false); + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic", false)); +} + +static void glue_session_without_hdcp_declines(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, false); + struct dcp_hdcp_word in = {}, out; + + KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_OPEN, + &in, sizeof(in), &out, sizeof(out)), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); + KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, 0x55, &in, + sizeof(in), &out, sizeof(out)), + -EOPNOTSUPP); +} + +/* A declined open in the slot of an earlier session leaves it not ours. */ +static void glue_declined_open_forgets_slot(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, true); + struct dcp_hdcp_word in = {}, out; + + mutex_init(&g->h.lock); + spin_lock_init(&g->h.svc_lock); + init_waitqueue_head(&g->h.ev_wq); + g->h.wq = alloc_ordered_workqueue("hdcp-test", 0); + KUNIT_ASSERT_NOT_NULL(test, g->h.wq); + INIT_WORK(&g->h.event_work, dcp_hdcp_event_work); + INIT_WORK(&g->h.teardown_work, dcp_hdcp_teardown_work); + INIT_WORK(&g->h.prop_work, dcp_hdcp_prop_work); + INIT_DELAYED_WORK(&g->h.kick_work, dcp_hdcp_kick_work); + g->h.session = &g->service; + + /* Nothing asks for protection here: the open is declined. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_OPEN, + &in, sizeof(in), &out, sizeof(out)), 0); + KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); + KUNIT_EXPECT_NULL(test, g->h.session); + /* Its later events are answered and not acted on. */ + KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_H_PRIME, + &in, sizeof(in), &out, sizeof(out)), 0); + KUNIT_EXPECT_EQ(test, g->h.ev_bits, 0); + KUNIT_EXPECT_EQ(test, g->h.q_head, 0); + flush_workqueue(g->h.wq); + destroy_workqueue(g->h.wq); +} + +/* Sessions announced for HDCP 1.x are recorded, never taken, and forgotten on teardown. */ +static void glue_hdcp1_session_declined(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, true); + struct apple_epic_service other = { .ep = &g->ep }; + const struct apple_epic_service_ops *ops; + + spin_lock_init(&g->h.svc_lock); + ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-auth-session", false); + KUNIT_ASSERT_NOT_NULL(test, ops); + /* Every announced session keeps its own handler. */ + KUNIT_EXPECT_FALSE(test, ops->singleton); + + ops->init(&g->service, "dcpdptx-hdcp-auth-session", "TxHDCP1Session", 0); + ops->init(&other, "dcpdptx-hdcp-auth-session", "TxHDCP2Session", 0); + KUNIT_EXPECT_TRUE(test, dcp_hdcp_is_hdcp1(&g->h, &g->service)); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &other)); + /* No class: taken for HDCP 2.2. */ + ops->init(&other, "dcpdptx-hdcp-auth-session", NULL, 0); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &other)); + + dcp_hdcp_session_teardown(&g->service); + KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &g->service)); +} + +static struct kunit_case dcp_hdcp_glue_cases[] = { + KUNIT_CASE(glue_match_by_name), + KUNIT_CASE(glue_session_without_hdcp_declines), + KUNIT_CASE(glue_declined_open_forgets_slot), + KUNIT_CASE(glue_hdcp1_session_declined), + { } +}; + +static struct kunit_suite dcp_hdcp_glue_suite = { + .name = "apple-dcp-hdcp-glue", + .test_cases = dcp_hdcp_glue_cases, +}; +kunit_test_suite(dcp_hdcp_glue_suite); diff --git a/drivers/gpu/drm/apple/dcp-hdcp.c b/drivers/gpu/drm/apple/dcp-hdcp.c new file mode 100644 index 00000000000000..1a6f4c1220b5da --- /dev/null +++ b/drivers/gpu/drm/apple/dcp-hdcp.c @@ -0,0 +1,1118 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* Copyright 2026 Ryan Murray */ + +/* + * HDCP 2.2 on the display processors' external outputs. + * + * DCP opens an authentication session after the link comes up and calls the + * AP with the session's events; the AP answers each at once and runs the + * transmitter (dcp-hdcp-tx.c) on its own ordered queue, with the SEP doing + * the cryptography (include/linux/apple-sep-hdcp.h) and the sink's DP device + * service moving the receiver's messages. The connector's Content + * Protection property follows the policy in dcp-hdcp.h. No key material is + * seen here: only the protocol fields the HDCP 2.2 messages carry in the + * clear. + * + * Off unless appledrm.hdcp=1: the property is not attached and DCP's + * sessions are declined, as before. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "afk.h" +#include "connector.h" +#include "dcp.h" +#include "dcp-hdcp.h" +#include "dcp-hdcp-drv.h" +#include "dcp-hdcp-tx.h" +#include "dcp-hdcp-wire.h" +#include "dcp-internal.h" + +static bool hdcp; +module_param(hdcp, bool, 0444); +MODULE_PARM_DESC(hdcp, "HDCP 2.2 on external outputs: attach Content Protection and take DCP's authentication sessions (needs the SEP HDCP service)"); + +/* How long a register access may take: DCP's AUX timeout, and some. */ +#define DCP_HDCP_CALL_MS (DCP_HDCP_REG_TIMEOUT_MS + 500) +/* Asking DCP for a session again, while one is wanted and none came. */ +#define DCP_HDCP_KICK_MS 5000 +#define DCP_HDCP_KICKS 6 +/* The receiver's status on an encrypted link. */ +#define DCP_HDCP_IFACES 4 +#define DCP_HDCP_QUEUE 16 + +struct dcp_hdcp_event { + u8 op; + struct apple_epic_service *service; +}; + +struct dcp_hdcp { + struct apple_dcp *dcp; + u32 channel; + + /* The policy, the link generation and the session's identity. */ + struct mutex lock; + struct dcp_hdcp_link link; + u32 gen; + u32 session_gen; + + /* Service pointers and session events, also touched from teardown. */ + spinlock_t svc_lock; + struct apple_epic_service *relay; + struct apple_epic_service *iface[DCP_HDCP_IFACES]; + struct apple_epic_service *session; + /* Sessions DCP announced for HDCP 1.x: declined, this is HDCP 2.2 only. */ + struct apple_epic_service *hdcp1[DCP_HDCP_IFACES]; + unsigned long ev_bits; + /* The device service was asked for a session (query) and not yet told it ended. */ + bool dev_begun; + bool closed; + bool cancel; + struct dcp_hdcp_event queue[DCP_HDCP_QUEUE]; + unsigned int q_head, q_tail; + wait_queue_head_t ev_wq; + + struct apple_dcp_afkep *dpdev_ep; + /* The HDCP interface endpoint, when this file started it. */ + struct apple_dcp_afkep *if_ep; + + struct workqueue_struct *wq; + struct work_struct event_work; + struct work_struct teardown_work; + struct work_struct prop_work; + struct work_struct relay_work; + struct delayed_work kick_work; + unsigned int kicks; + + struct dcp_hdcp_tx tx; +}; + +static struct dcp_hdcp *dcp_hdcp_of(struct apple_epic_service *service) +{ + return service && service->ep ? READ_ONCE(service->ep->dcp->hdcp) : NULL; +} + +/* Pins the service in @slot, NULL if there is none or it is gone. */ +static struct apple_epic_service *dcp_hdcp_pin(struct dcp_hdcp *h, + struct apple_epic_service **slot) +{ + struct apple_epic_service *service; + unsigned long flags; + + spin_lock_irqsave(&h->svc_lock, flags); + service = afk_service_get(*slot); + spin_unlock_irqrestore(&h->svc_lock, flags); + return service; +} + +/* The DP device service: register access. */ + +static int dcp_hdcp_reg_read(void *ctx, u32 addr, void *buf, size_t len) +{ + struct dcp_hdcp *h = ctx; + struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); + size_t received = 0; + void *body; + int n, ret; + + if (!service) + return -ENODEV; + body = kzalloc(DCP_HDCP_REG_ARGS_LEN + len, GFP_KERNEL); + if (!body) { + afk_service_put(service); + return -ENOMEM; + } + n = dcp_hdcp_reg_read_encode(body, DCP_HDCP_REG_ARGS_LEN + len, addr, + len, DCP_HDCP_REG_TIMEOUT_MS); + ret = n < 0 ? n : + afk_service_call_timeout_len(service, DCP_HDCP_REG_GROUP, + DCP_HDCP_REG_READ, body, n, 0, body, n, + 0, DCP_HDCP_CALL_MS, &received); + if (!ret) + ret = dcp_hdcp_reg_read_check(body, received, addr, len); + if (!ret) + memcpy(buf, body + DCP_HDCP_REG_ARGS_LEN, len); + kfree_sensitive(body); + afk_service_put(service); + return ret; +} + +static int dcp_hdcp_reg_write(void *ctx, u32 addr, const void *buf, size_t len) +{ + struct dcp_hdcp *h = ctx; + struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); + size_t received = 0; + void *body; + int n, ret; + + if (!service) + return -ENODEV; + body = kzalloc(DCP_HDCP_REG_ARGS_LEN + len, GFP_KERNEL); + if (!body) { + afk_service_put(service); + return -ENOMEM; + } + n = dcp_hdcp_reg_write_encode(body, DCP_HDCP_REG_ARGS_LEN + len, addr, + buf, len); + ret = n < 0 ? n : + afk_service_call_timeout_len(service, DCP_HDCP_REG_GROUP, + DCP_HDCP_REG_WRITE, body, n, 0, body, n, + 0, DCP_HDCP_CALL_MS, &received); + if (!ret) + ret = dcp_hdcp_reg_write_check(body, received, addr, len); + kfree_sensitive(body); + afk_service_put(service); + return ret; +} + +/* A call with a zero body whose answer is not needed. */ +static int dcp_hdcp_plain_call(struct apple_epic_service *service, u16 group, + u32 command, size_t len, u32 value) +{ + struct dcp_hdcp_word *w; + void *body = kzalloc(len, GFP_KERNEL); + int ret; + + if (!body) + return -ENOMEM; + if (value && len >= sizeof(*w)) { + w = body; + w->value = cpu_to_le32(value); + } + ret = afk_service_call_timeout(service, group, command, body, len, 0, + body, len, 0, DCP_HDCP_CALL_MS); + kfree(body); + return ret; +} + +/* The session service: events in, progress reports out. */ + +static void dcp_hdcp_report(void *ctx, enum dcp_hdcp_progress_code code, + bool active, bool repeater, bool encrypted) +{ + struct dcp_hdcp *h = ctx; + struct apple_epic_service *service = dcp_hdcp_pin(h, &h->session); + struct { + struct epic_service_call call; + struct dcp_hdcp_report report; + } __packed msg = {}; + int ret; + + if (!service) + return; + msg.call.group = cpu_to_le16(DCP_HDCP_REPORT_GROUP); + msg.call.command = cpu_to_le32(DCP_HDCP_REPORT_PROGRESS); + msg.call.data_len = cpu_to_le32(sizeof(msg.report)); + msg.call.magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC); + dcp_hdcp_report_encode(&msg.report, code, active, repeater, encrypted); + ret = afk_send_epic(service->ep, service->channel, 0, EPIC_TYPE_NOTIFY, + EPIC_CAT_REPORT, EPIC_SUBTYPE_STD_SERVICE, &msg, + sizeof(msg)); + if (ret) + dev_dbg(h->dcp->dev, "HDCP: progress %#x not reported: %d\n", + code, ret); + afk_service_put(service); +} + +static int dcp_hdcp_wait(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms) +{ + struct dcp_hdcp *h = ctx; + unsigned long flags; + bool got; + + wait_event_timeout(h->ev_wq, + test_bit(op, &h->ev_bits) || READ_ONCE(h->closed) || + READ_ONCE(h->cancel), msecs_to_jiffies(ms)); + spin_lock_irqsave(&h->svc_lock, flags); + if (h->closed || h->cancel) { + spin_unlock_irqrestore(&h->svc_lock, flags); + return -ECANCELED; + } + got = __test_and_clear_bit(op, &h->ev_bits); + spin_unlock_irqrestore(&h->svc_lock, flags); + return got ? 0 : -ETIMEDOUT; +} + +static int dcp_hdcp_revoked(void *ctx, u8 *ids, unsigned int count) +{ + struct dcp_hdcp *h = ctx; + struct apple_connector *connector = READ_ONCE(h->dcp->connector); + + if (!connector) + return -ENODEV; + return drm_hdcp_check_ksvs_revoked(connector->base.dev, ids, count); +} + +static void dcp_hdcp_sleep(void *ctx, unsigned int ms) +{ + msleep(ms); +} + +/* The SEP service. */ + +static int sep_open(void *ctx, u32 ch, u8 *rtx) +{ + return apple_sep_hdcp_open(ch, rtx); +} + +static int sep_ake_cert(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, + bool *stored, u8 *ekh_km_m, u8 *ekpub_km) +{ + struct apple_sep_hdcp_stored_km km; + int ret; + + static_assert(sizeof(km) == HDCP_2_2_E_KH_KM_M_LEN); + ret = apple_sep_hdcp_ake_cert(ch, cert, rrx, stored, &km, ekpub_km); + if (!ret && *stored) + memcpy(ekh_km_m, &km, sizeof(km)); + memzero_explicit(&km, sizeof(km)); + return ret; +} + +static int sep_h_prime(void *ctx, u32 ch, const u8 *rxcaps, const u8 *txcaps, + const u8 *h_prime) +{ + return apple_sep_hdcp_ake_h_prime(ch, rxcaps, txcaps, h_prime); +} + +static int sep_pairing(void *ctx, u32 ch, const u8 *ekh_km) +{ + return apple_sep_hdcp_ake_pairing(ch, ekh_km); +} + +static int sep_lc_init(void *ctx, u32 ch, u8 *rn) +{ + return apple_sep_hdcp_lc_init(ch, rn); +} + +static int sep_l_prime(void *ctx, u32 ch, const u8 *l_prime) +{ + return apple_sep_hdcp_lc_l_prime(ch, l_prime); +} + +static int sep_ske(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv) +{ + return apple_sep_hdcp_ske(ch, edkey_ks, riv); +} + +static int sep_repeater_list(void *ctx, u32 ch, const u8 *ids, + unsigned int count, const u8 *rxinfo, + const u8 *seq_num_v, const u8 *v_prime, u8 *v) +{ + return apple_sep_hdcp_repeater_list(ch, ids, count, rxinfo, seq_num_v, + v_prime, v); +} + +static int sep_repeater_stream(void *ctx, u32 ch, u8 stream_id, u8 type, + const u8 *seq_num_m, const u8 *m_prime) +{ + return apple_sep_hdcp_repeater_stream(ch, stream_id, type, seq_num_m, + m_prime); +} + +static int sep_finish(void *ctx, u32 ch) +{ + return apple_sep_hdcp_finish(ch); +} + +static int sep_set_encryption(void *ctx, u32 ch, bool on) +{ + return apple_sep_hdcp_set_encryption(ch, on); +} + +static void sep_close(void *ctx, u32 ch) +{ + apple_sep_hdcp_close(ch); +} + +static const struct dcp_hdcp_tx_ops dcp_hdcp_tx_ops = { + .read = dcp_hdcp_reg_read, + .write = dcp_hdcp_reg_write, + .wait = dcp_hdcp_wait, + .report = dcp_hdcp_report, + .revoked = dcp_hdcp_revoked, + .sleep = dcp_hdcp_sleep, + .sep_open = sep_open, + .sep_ake_cert = sep_ake_cert, + .sep_h_prime = sep_h_prime, + .sep_pairing = sep_pairing, + .sep_lc_init = sep_lc_init, + .sep_l_prime = sep_l_prime, + .sep_ske = sep_ske, + .sep_repeater_list = sep_repeater_list, + .sep_repeater_stream = sep_repeater_stream, + .sep_finish = sep_finish, + .sep_set_encryption = sep_set_encryption, + .sep_close = sep_close, +}; + +/* Policy glue. */ + +/* What the connector this processor drives asks for. */ +static void dcp_hdcp_want(struct dcp_hdcp *h, bool *want, u8 *type) +{ + struct apple_connector *connector = READ_ONCE(h->dcp->connector); + + *want = connector && READ_ONCE(connector->hdcp_attached) && + READ_ONCE(connector->hdcp_want); + *type = connector ? READ_ONCE(connector->hdcp_type) : 0; +} + +static void dcp_hdcp_apply(struct dcp_hdcp *h, enum dcp_hdcp_action action) +{ + unsigned long flags; + + if (action == DCP_HDCP_TEARDOWN) { + spin_lock_irqsave(&h->svc_lock, flags); + h->cancel = true; + spin_unlock_irqrestore(&h->svc_lock, flags); + wake_up_all(&h->ev_wq); + queue_work(h->wq, &h->teardown_work); + } else if (action == DCP_HDCP_KICK) { + h->kicks = 0; + mod_delayed_work(h->wq, &h->kick_work, 0); + } + queue_work(h->wq, &h->prop_work); +} + +/* The bound state of both sides, then what the connector asks for. */ +static void dcp_hdcp_sync_locked(struct dcp_hdcp *h) +{ + unsigned long now = jiffies; + enum dcp_hdcp_action a, b; + bool want, relay; + u8 type; + + relay = READ_ONCE(h->relay) != NULL; + a = dcp_hdcp_bind(&h->link, relay, apple_sep_hdcp_available(), now); + dcp_hdcp_want(h, &want, &type); + b = dcp_hdcp_request(&h->link, want, type, now); + dcp_hdcp_apply(h, a == DCP_HDCP_TEARDOWN ? a : b); +} + +static void dcp_hdcp_sync(struct dcp_hdcp *h) +{ + mutex_lock(&h->lock); + dcp_hdcp_sync_locked(h); + mutex_unlock(&h->lock); +} + +static void dcp_hdcp_prop_work(struct work_struct *work) +{ + struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, prop_work); + struct apple_connector *connector = READ_ONCE(h->dcp->connector); + struct drm_device *drm; + u64 value; + + if (!connector || !READ_ONCE(connector->hdcp_attached)) + return; + mutex_lock(&h->lock); + value = dcp_hdcp_property(&h->link); + mutex_unlock(&h->lock); + /* UNDESIRED is userspace's to set, never the driver's. */ + if (value == DRM_MODE_CONTENT_PROTECTION_UNDESIRED || + !READ_ONCE(connector->hdcp_want)) + return; + drm = connector->base.dev; + drm_modeset_lock(&drm->mode_config.connection_mutex, NULL); + if (READ_ONCE(connector->hdcp_want)) + drm_hdcp_update_content_protection(&connector->base, value); + drm_modeset_unlock(&drm->mode_config.connection_mutex); +} + +/* Asks DCP for a session through the HDCP interfaces, while one is wanted. */ +static void dcp_hdcp_kick_work(struct work_struct *work) +{ + struct dcp_hdcp *h = container_of(to_delayed_work(work), struct dcp_hdcp, + kick_work); + struct apple_epic_service *service; + bool ready; + int i; + + mutex_lock(&h->lock); + ready = dcp_hdcp_ready(&h->link, jiffies); + mutex_unlock(&h->lock); + if (!ready || h->kicks >= DCP_HDCP_KICKS) + return; + h->kicks++; + for (i = 0; i < DCP_HDCP_IFACES; i++) { + service = dcp_hdcp_pin(h, &h->iface[i]); + if (!service) + continue; + dcp_hdcp_plain_call(service, DCP_HDCP_IF_GROUP, DCP_HDCP_IF_CAPS, + DCP_HDCP_IF_CAPS_LEN, DCP_HDCP_IF_CAPS_VALUE); + afk_service_put(service); + } + queue_delayed_work(h->wq, &h->kick_work, msecs_to_jiffies(DCP_HDCP_KICK_MS)); +} + +/* Encryption off, the SEP session closed, DCP told; the picture stays. */ +/* Tells the DP device service the session it was asked for has ended. */ +static void dcp_hdcp_dev_end(struct dcp_hdcp *h) +{ + struct apple_epic_service *relay; + + if (!xchg(&h->dev_begun, false)) + return; + relay = dcp_hdcp_pin(h, &h->relay); + if (!relay) + return; + dcp_hdcp_plain_call(relay, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_END, + DCP_HDCP_DEV_END_LEN, 0); + afk_service_put(relay); +} + +static void dcp_hdcp_teardown_work(struct work_struct *work) +{ + struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, teardown_work); + bool was_open = h->tx.sep_open; + + dcp_hdcp_abort(&h->tx); + if (was_open) + dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); + dcp_hdcp_dev_end(h); +} + +/* One authentication, from DCP's start of the session to its result. */ +static void dcp_hdcp_run(struct dcp_hdcp *h) +{ + struct apple_epic_service *relay = dcp_hdcp_pin(h, &h->relay); + enum dcp_hdcp_action action; + u32 gen; + int ret; + + mutex_lock(&h->lock); + gen = h->session_gen; + h->tx.type = h->link.type; + /* Only a session the policy took, on its generation. */ + if (h->link.state != DCP_HDCP_AUTH || h->link.generation != gen) { + mutex_unlock(&h->lock); + afk_service_put(relay); + return; + } + mutex_unlock(&h->lock); + h->tx.ops = &dcp_hdcp_tx_ops; + h->tx.ctx = h; + h->tx.channel = h->channel; + + if (relay) { + /* The device service's query opens each session; dcp_hdcp_dev_end() closes it. */ + dcp_hdcp_dev_end(h); + if (!dcp_hdcp_plain_call(relay, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_QUERY, + DCP_HDCP_DEV_QUERY_LEN, 0)) + WRITE_ONCE(h->dev_begun, true); + afk_service_put(relay); + ret = dcp_hdcp_authenticate(&h->tx); + } else { + ret = -ENODEV; + } + if (ret) { + dev_info(h->dcp->dev, "HDCP: authentication failed at %s: %d\n", + h->tx.step ?: "start", ret); + dcp_hdcp_abort(&h->tx); + } else { + dev_info(h->dcp->dev, "HDCP: encrypted, type %u%s\n", h->tx.type, + h->tx.repeater ? " (repeater)" : ""); + } + mutex_lock(&h->lock); + action = dcp_hdcp_auth_done(&h->link, gen, ret, jiffies); + mutex_unlock(&h->lock); + /* The SEP session is already closed after a failure. */ + if (action != DCP_HDCP_TEARDOWN) + dcp_hdcp_apply(h, action); + else + queue_work(h->wq, &h->prop_work); +} + +static void dcp_hdcp_close(struct dcp_hdcp *h, struct apple_epic_service *service) +{ + unsigned long flags; + + dcp_hdcp_abort(&h->tx); + mutex_lock(&h->lock); + dcp_hdcp_closed(&h->link, h->session_gen, jiffies); + mutex_unlock(&h->lock); + /* The session goes back to idle on DCP's side. */ + if (service) + dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); + dcp_hdcp_dev_end(h); + spin_lock_irqsave(&h->svc_lock, flags); + if (h->session == service) + h->session = NULL; + spin_unlock_irqrestore(&h->svc_lock, flags); + queue_work(h->wq, &h->prop_work); +} + +static void dcp_hdcp_event_work(struct work_struct *work) +{ + struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, event_work); + struct dcp_hdcp_event ev; + unsigned long flags; + + for (;;) { + spin_lock_irqsave(&h->svc_lock, flags); + if (h->q_head == h->q_tail) { + spin_unlock_irqrestore(&h->svc_lock, flags); + return; + } + ev = h->queue[h->q_tail++ % DCP_HDCP_QUEUE]; + spin_unlock_irqrestore(&h->svc_lock, flags); + + switch (ev.op) { + case DCP_HDCP_AUTH_OPEN: + dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, + false); + break; + case DCP_HDCP_AUTH_START: + dcp_hdcp_report(h, DCP_HDCP_PROGRESS_STARTED, false, + false, false); + break; + case DCP_HDCP_AUTH_CONFIG: + dcp_hdcp_run(h); + break; + case DCP_HDCP_AUTH_CLOSE: + dcp_hdcp_close(h, ev.service); + break; + } + afk_service_put(ev.service); + } +} + +static void dcp_hdcp_queue(struct dcp_hdcp *h, struct apple_epic_service *service, + u8 op) +{ + struct apple_epic_service *pinned = afk_service_get(service); + unsigned long flags; + bool full; + + if (!pinned) + return; + spin_lock_irqsave(&h->svc_lock, flags); + full = h->q_head - h->q_tail >= DCP_HDCP_QUEUE; + if (!full) + h->queue[h->q_head++ % DCP_HDCP_QUEUE] = + (struct dcp_hdcp_event){ op, pinned }; + spin_unlock_irqrestore(&h->svc_lock, flags); + if (full) { + dev_warn_ratelimited(h->dcp->dev, "HDCP: session event %#x dropped\n", op); + afk_service_put(pinned); + return; + } + queue_work(h->wq, &h->event_work); +} + +/* Whether DCP announced @service as an HDCP 1.x session. */ +static bool dcp_hdcp_is_hdcp1(struct dcp_hdcp *h, struct apple_epic_service *service) +{ + unsigned long flags; + bool ret = false; + int i; + + spin_lock_irqsave(&h->svc_lock, flags); + for (i = 0; i < DCP_HDCP_IFACES; i++) + ret |= h->hdcp1[i] == service; + spin_unlock_irqrestore(&h->svc_lock, flags); + return ret; +} + +/* + * DCP announces one session per protocol version; the provider class says + * which, where the announcement carries one. A session without a class is + * taken for HDCP 2.2: the receiver registers it reads decide. + */ +static void dcp_hdcp_session_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + int i; + + if (!h || !class || !strstr(class, "HDCP1")) + return; + spin_lock_irqsave(&h->svc_lock, flags); + for (i = 0; i < DCP_HDCP_IFACES; i++) { + if (h->hdcp1[i] == service) + break; + if (!h->hdcp1[i]) { + h->hdcp1[i] = service; + break; + } + } + spin_unlock_irqrestore(&h->svc_lock, flags); + dev_dbg(h->dcp->dev, "HDCP: HDCP 1.x session announced, declined\n"); +} + +static int dcp_hdcp_session_call(struct apple_epic_service *service, u16 group, + u32 command, const void *data, size_t size, + void *reply, size_t room) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + bool accept = false, ours; + int ret; + + if (h && !group && command == DCP_HDCP_AUTH_OPEN) { + mutex_lock(&h->lock); + dcp_hdcp_sync_locked(h); + accept = !dcp_hdcp_is_hdcp1(h, service) && + dcp_hdcp_open(&h->link, h->gen, jiffies); + if (accept) + h->session_gen = h->gen; + mutex_unlock(&h->lock); + spin_lock_irqsave(&h->svc_lock, flags); + if (accept) { + h->session = service; + h->ev_bits = 0; + h->closed = false; + h->cancel = false; + } else if (h->session == service) { + /* The slot of an earlier session, declined this time. */ + h->session = NULL; + } + spin_unlock_irqrestore(&h->svc_lock, flags); + if (accept) + cancel_delayed_work(&h->kick_work); + } + ret = dcp_hdcp_auth_reply(group, command, data, size, reply, room, + accept); + if (ret == -EOPNOTSUPP && h && !group) { + /* Not a session step: answered and logged. */ + memset(reply, 0, room); + memcpy(reply, data, min(size, room)); + dev_dbg(h->dcp->dev, "HDCP: session call %#x\n", command); + return 0; + } + if (ret || !h) + return ret; + + spin_lock_irqsave(&h->svc_lock, flags); + ours = h->session == service; + switch (command) { + case DCP_HDCP_AUTH_H_PRIME: + case DCP_HDCP_AUTH_PAIRING: + case DCP_HDCP_AUTH_LIST: + if (ours) + __set_bit(command, &h->ev_bits); + break; + case DCP_HDCP_AUTH_CLOSE: + if (ours) + h->closed = true; + break; + } + spin_unlock_irqrestore(&h->svc_lock, flags); + wake_up_all(&h->ev_wq); + + if (ours && (command == DCP_HDCP_AUTH_OPEN || command == DCP_HDCP_AUTH_START || + command == DCP_HDCP_AUTH_CONFIG || command == DCP_HDCP_AUTH_CLOSE)) + dcp_hdcp_queue(h, service, command); + return 0; +} + +static void dcp_hdcp_session_teardown(struct apple_epic_service *service) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + bool ours; + int i; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + for (i = 0; i < DCP_HDCP_IFACES; i++) + if (h->hdcp1[i] == service) + h->hdcp1[i] = NULL; + ours = h->session == service; + if (ours) { + h->closed = true; + h->session = NULL; + } + spin_unlock_irqrestore(&h->svc_lock, flags); + if (ours) { + wake_up_all(&h->ev_wq); + dcp_hdcp_apply(h, DCP_HDCP_TEARDOWN); + } +} + +static void dcp_hdcp_relay_work(struct work_struct *work) +{ + struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, relay_work); + struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); + + if (!service) + return; + /* The device service's information call, once after it is opened. */ + dcp_hdcp_plain_call(service, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_INFO, + DCP_HDCP_DEV_INFO_LEN, 0); + afk_service_put(service); + dcp_hdcp_sync(h); +} + +static void dcp_hdcp_relay_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + h->relay = service; + spin_unlock_irqrestore(&h->svc_lock, flags); + dev_dbg(h->dcp->dev, "HDCP: DP device service on interface %u\n", + service->channel); + queue_work(h->wq, &h->relay_work); +} + +static void dcp_hdcp_relay_teardown(struct apple_epic_service *service) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + bool ours; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + ours = h->relay == service; + if (ours) + h->relay = NULL; + spin_unlock_irqrestore(&h->svc_lock, flags); + if (ours) + dcp_hdcp_apply(h, DCP_HDCP_TEARDOWN); +} + +static void dcp_hdcp_iface_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + int i; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + for (i = 0; i < DCP_HDCP_IFACES; i++) { + if (h->iface[i] == service) + break; + if (!h->iface[i]) { + h->iface[i] = service; + break; + } + } + spin_unlock_irqrestore(&h->svc_lock, flags); + /* The capability goes out once the interface is open, as the first kick. */ + h->kicks = 0; + mod_delayed_work(h->wq, &h->kick_work, 0); +} + +static void dcp_hdcp_iface_teardown(struct apple_epic_service *service) +{ + struct dcp_hdcp *h = dcp_hdcp_of(service); + unsigned long flags; + int i; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + for (i = 0; i < DCP_HDCP_IFACES; i++) + if (h->iface[i] == service) + h->iface[i] = NULL; + spin_unlock_irqrestore(&h->svc_lock, flags); +} + +static void dcp_hdcp_other_init(struct apple_epic_service *service, + const char *name, const char *class, s64 unit) +{ +} + +#define DCP_HDCP_RELAY_OPS { \ + .name = "dcpdp-device-epic", \ + .compact_full = "dcpdp-device-epic:0", \ + .singleton = true, \ + .init = dcp_hdcp_relay_init, \ + .teardown = dcp_hdcp_relay_teardown, \ +} + +static const struct apple_epic_service_ops dcp_hdcp_service_ops[] = { + DCP_HDCP_RELAY_OPS, + { + .name = "dcpdptx-hdcp-interface", + .init = dcp_hdcp_iface_init, + .teardown = dcp_hdcp_iface_teardown, + }, + { + .name = "dcpdptx-hdcp-auth-session", + .compact_full = "dcpdptx-hdcp-auth-session", + /* + * Not a singleton: DCP announces one session per protocol + * version and closes each before it powers down, so every + * one needs its handler to answer. + */ + .init = dcp_hdcp_session_init, + .call_v2 = dcp_hdcp_session_call, + .teardown = dcp_hdcp_session_teardown, + }, + {}, +}; + +/* The DP device endpoint when this file starts it: the sink's services. */ +static const struct apple_epic_service_ops dcp_hdcp_dpdev_ops[] = { + DCP_HDCP_RELAY_OPS, + { .name = "*", .init = dcp_hdcp_other_init }, + {}, +}; + +const struct apple_epic_service_ops * +dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, + bool cut) +{ + const struct apple_epic_service_ops *ops; + size_t len; + + if (!ep || !READ_ONCE(ep->dcp->hdcp) || !service_name) + return NULL; + for (ops = dcp_hdcp_service_ops; ops->name[0]; ops++) { + len = strlen(ops->name); + if (!strncmp(ops->name, service_name, len) && + (!service_name[len] || service_name[len] == ':')) + return ops; + if (cut && afk_compact_cut_of(ops, service_name)) + return ops; + } + return NULL; +} + +/* + * The endpoints that carry the HDCP interface services, by firmware: the + * first one advertised and not driven by anything else is started here. + */ +static const u8 dcp_hdcp_if_endpoints[] = { AV_AUDIO_ENDPOINT_DESKTOP, DPTX_HDCP_ENDPOINT }; + +static struct apple_dcp_afkep *dcp_hdcp_start_one(struct apple_dcp *dcp, u8 endpoint, + const struct apple_epic_service_ops *ops, + struct apple_dcp_afkep **slot, const char *what) +{ + struct apple_dcp_afkep *ep; + int ret; + + if (!apple_rtkit_has_endpoint(dcp->rtk, endpoint) || dcp_endpoint_routed(dcp, endpoint)) + return NULL; + ep = afk_init(dcp, endpoint, ops); + if (IS_ERR(ep)) { + dev_warn(dcp->dev, "HDCP: %s endpoint %#x not set up: %ld\n", what, + endpoint, PTR_ERR(ep)); + return NULL; + } + ep->debugfs_entry = dcp->ep_debugfs[endpoint - 0x20]; + /* Routed before the start: afk_start() waits for the firmware's answer. */ + WRITE_ONCE(*slot, ep); + ret = afk_start(ep); + if (ret) + dev_warn(dcp->dev, "HDCP: %s endpoint %#x not started: %d\n", what, + endpoint, ret); + else + dev_info(dcp->dev, "HDCP: started the %s endpoint %#x\n", what, endpoint); + return ep; +} + +void dcp_hdcp_start_endpoints(struct apple_dcp *dcp) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + int i; + + if (!h || IS_ERR_OR_NULL(dcp->rtk)) + return; + if (!h->dpdev_ep) + dcp_hdcp_start_one(dcp, DPDEV_ENDPOINT, dcp_hdcp_dpdev_ops, + &h->dpdev_ep, "DP device"); + for (i = 0; i < ARRAY_SIZE(dcp_hdcp_if_endpoints) && !h->if_ep; i++) + dcp_hdcp_start_one(dcp, dcp_hdcp_if_endpoints[i], dcp_hdcp_service_ops, + &h->if_ep, "HDCP interface"); +} + +struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, u32 endpoint) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + struct apple_dcp_afkep *ep; + + if (!h) + return NULL; + ep = READ_ONCE(h->dpdev_ep); + if (ep && ep->endpoint == endpoint) + return ep; + ep = READ_ONCE(h->if_ep); + return ep && ep->endpoint == endpoint ? ep : NULL; +} + +void dcp_hdcp_link_changed(struct apple_dcp *dcp) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + enum dcp_hdcp_action action; + + if (!h) + return; + mutex_lock(&h->lock); + h->gen++; + action = dcp_hdcp_link_event(&h->link, h->gen, jiffies); + mutex_unlock(&h->lock); + if (action == DCP_HDCP_TEARDOWN) + dcp_hdcp_apply(h, action); + dcp_hdcp_sync(h); +} + +static bool dcp_hdcp_channel(struct apple_dcp *dcp, u32 *channel) +{ + return !of_property_read_u32_index(dcp->dev->of_node, + "apple,hdcp-channels", 0, channel); +} + +static void dcp_hdcp_destroy_wq(void *data) +{ + destroy_workqueue(data); +} + +struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + u32 channel; + + if (h || !hdcp || dcp_has_panel(dcp) || !dcp_hdcp_channel(dcp, &channel)) + return h; + h = devm_kzalloc(dcp->dev, sizeof(*h), GFP_KERNEL); + if (!h) + return NULL; + h->dcp = dcp; + h->channel = channel; + mutex_init(&h->lock); + spin_lock_init(&h->svc_lock); + init_waitqueue_head(&h->ev_wq); + INIT_WORK(&h->event_work, dcp_hdcp_event_work); + INIT_WORK(&h->teardown_work, dcp_hdcp_teardown_work); + INIT_WORK(&h->prop_work, dcp_hdcp_prop_work); + INIT_WORK(&h->relay_work, dcp_hdcp_relay_work); + INIT_DELAYED_WORK(&h->kick_work, dcp_hdcp_kick_work); + h->wq = alloc_ordered_workqueue("apple-dcp-hdcp", WQ_FREEZABLE); + if (!h->wq) + return NULL; + if (devm_add_action_or_reset(dcp->dev, dcp_hdcp_destroy_wq, h->wq)) + return NULL; + h->tx.ops = &dcp_hdcp_tx_ops; + h->tx.ctx = h; + h->tx.channel = channel; + WRITE_ONCE(dcp->hdcp, h); + dev_info(dcp->dev, "HDCP: transmitter on SEP channel %u\n", channel); + return h; +} + +void dcp_hdcp_fini(struct apple_dcp *dcp) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + unsigned long flags; + + if (!h) + return; + spin_lock_irqsave(&h->svc_lock, flags); + h->cancel = true; + spin_unlock_irqrestore(&h->svc_lock, flags); + wake_up_all(&h->ev_wq); + cancel_delayed_work_sync(&h->kick_work); + flush_workqueue(h->wq); + dcp_hdcp_abort(&h->tx); +} + +/* DRM. */ + +int dcp_hdcp_attach_connector(struct apple_connector *connector, + struct platform_device **dcps, unsigned int n, + int connector_type) +{ + bool channel = false; + unsigned int i; + int ret; + + if (!hdcp || connector->hdcp_attached || + connector_type == DRM_MODE_CONNECTOR_eDP) + return 0; + for (i = 0; i < n; i++) { + struct apple_dcp *dcp = dcps[i] ? platform_get_drvdata(dcps[i]) : NULL; + + if (dcp && dcp_hdcp_init(dcp)) + channel = true; + } + if (!dcp_hdcp_attach_property(true, channel, + IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE))) + return 0; + ret = drm_connector_attach_content_protection_property(&connector->base, + true); + if (ret) + return ret; + connector->hdcp_attached = true; + return 0; +} + +void dcp_hdcp_atomic_check(struct drm_connector *conn, + struct drm_atomic_commit *state) +{ + struct drm_connector_state *old = drm_atomic_get_old_connector_state(state, conn); + struct drm_connector_state *new = drm_atomic_get_new_connector_state(state, conn); + struct drm_crtc_state *crtc_state; + + if (!to_apple_connector(conn)->hdcp_attached || !old || !new) + return; + /* A connector switched off keeps asking: DESIRED again when it is back. */ + if (!new->crtc) { + if (old->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) + new->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED; + return; + } + crtc_state = drm_atomic_get_new_crtc_state(state, new->crtc); + if (old->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED || + new->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED) + return; + /* A mode set or another type: protected again only after a new session. */ + if ((crtc_state && drm_atomic_crtc_needs_modeset(crtc_state)) || + old->hdcp_content_type != new->hdcp_content_type) + new->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED; +} + +void dcp_hdcp_commit(struct drm_atomic_commit *state) +{ + struct drm_connector_state *new; + struct drm_connector *conn; + int i; + + for_each_new_connector_in_state(state, conn, new, i) { + struct apple_connector *connector = to_apple_connector(conn); + struct platform_device *pdev = READ_ONCE(connector->dcp); + struct apple_dcp *dcp; + + if (!connector->hdcp_attached) + continue; + WRITE_ONCE(connector->hdcp_type, new->hdcp_content_type); + WRITE_ONCE(connector->hdcp_want, new->content_protection != + DRM_MODE_CONTENT_PROTECTION_UNDESIRED); + dcp = pdev ? platform_get_drvdata(pdev) : NULL; + if (dcp && READ_ONCE(dcp->hdcp)) + dcp_hdcp_sync(dcp->hdcp); + } +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) +#include "dcp-hdcp-glue-test.c" +#endif diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index fd561bc7358ccd..b3ba6616b8a72c 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1313,6 +1313,8 @@ struct apple_dcp { /* Internal panel identity; NULL without an internal panel. */ struct dcp_panel_identity *panel_identity; struct dcp_cec *cec; + /* HDCP 2.2 transmitter state, NULL without HDCP (dcp-hdcp.c). */ + struct dcp_hdcp *hdcp; }; /* A DCP driven through the firmware's iBoot interface alone. */ diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index bd867d04bb072f..716a26c59d2cee 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -72,6 +72,7 @@ #include #include "dcp-fabric-effects.h" #include "dcp-fabric.h" +#include "dcp-hdcp-drv.h" #include "dcp-hdmi.h" #include "dcp-syslog.h" #include "dcpext_scanout.h" @@ -1650,6 +1651,9 @@ static struct apple_dcp_afkep *dcp_afkep(struct apple_dcp *dcp, u8 endpoint) if (ep) return ep; } + /* The DP device endpoint HDCP started. */ + if (dcp_hdcp_route(dcp, endpoint)) + return dcp_hdcp_route(dcp, endpoint); /* DPAV 0x2a on H17P overlaps the legacy DPTX endpoint number. */ if (dcp->dcpavservep && endpoint == dcp->dcpavservep->endpoint) return dcp->dcpavservep; @@ -1669,6 +1673,12 @@ static struct apple_dcp_afkep *dcp_afkep(struct apple_dcp *dcp, u8 endpoint) } } +/* Whether something already drives @endpoint (HDCP starts only idle ones). */ +bool dcp_endpoint_routed(struct apple_dcp *dcp, u8 endpoint) +{ + return !!dcp_afkep(dcp, endpoint); +} + /* RX and the watchdog may race to finish one present, never both. */ bool dcp_desktop_present_complete(struct apple_dcp *dcp, u32 id) { @@ -4913,6 +4923,9 @@ int dcp_start(struct platform_device *pdev) } + /* Before any endpoint announces its services: they are matched by name. */ + dcp_hdcp_init(dcp); + /* Even if nothing starts, dcp_wait_ready() must find it initialised. */ init_completion(&dcp->start_done); init_completion(&dcp->s2r_dart_done); @@ -5064,6 +5077,7 @@ int dcp_start(struct platform_device *pdev) dcp_cec_register(dcp); } #endif + dcp_hdcp_start_endpoints(dcp); return ret; } @@ -5344,6 +5358,9 @@ void dcp_poweron(struct platform_device *pdev) unsigned long remaining; int ret; + /* A new link: DCP opens a new HDCP session once it is up. */ + dcp_hdcp_link_changed(dcp); + /* The takeover trial powered it on before the eviction. */ if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->desktop->trial_powered) { @@ -5527,6 +5544,9 @@ void dcp_poweroff(struct platform_device *pdev) bool display_gone = false; int ret; + /* DPMS off ends any HDCP session; the next power-on starts another. */ + dcp_hdcp_link_changed(dcp); + if (iomfb_is_m4(dcp)) { ret = dcp_backlight_dpms(dcp, false); if (!ret) @@ -7460,6 +7480,7 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v if (!dcp) return; + dcp_hdcp_fini(dcp); if (IS_ENABLED(CONFIG_APPLE_SOC_SLEEP)) apple_sleep_v27_unregister(dev); dcp_indicator_release(dcp); @@ -9913,6 +9934,8 @@ static int dcp_s2r_suspend(struct apple_dcp *dcp) bool was_off; int ret; + dcp_hdcp_link_changed(dcp); + /* * Not bound into the display subsystem (a component unbind released the RTKit * session): nothing of the firmware is this driver's to stop. diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index cbc093e132fc8a..a8c09cd8378cce 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -41,6 +41,7 @@ #include "cec.h" #include "dcp.h" #include "dcp-hdr-metadata.h" +#include "dcp-hdcp-drv.h" #include "dcp-internal.h" #include "iomfb.h" #include "iomfb_internal.h" @@ -1992,6 +1993,9 @@ void dcp_hotplug(struct work_struct *work) connector->connected, READ_ONCE(dcp->mode_state.valid), dcp->nr_modes); if (READ_ONCE(dcp->mode_state.valid)) dcp->tunnel_power_cycles = 0; + /* An unplugged sink ends its HDCP session; a new link brings another. */ + if (!READ_ONCE(connector->connected)) + dcp_hdcp_link_changed(dcp); scoped_guard(mutex, &connector->base.dev->mode_config.mutex) { if (READ_ONCE(connector->dcp) == pdev) From 37bd824f8dc8c5244e92959a07c76de9e96051b4 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 01:08:49 +1100 Subject: [PATCH 1447/1514] dt-bindings: display: apple,dcp: add apple,hdcp-channels The Secure Enclave HDCP interface channels assigned to a display coprocessor; the first is its external output's HDCP 2.2 transmitter. Signed-off-by: Ryan Murray --- .../devicetree/bindings/display/apple,dcp.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index 57616c37cda25a..eba0a74ce67833 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -387,6 +387,17 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: Display coprocessor index on multi-DCP systems. + apple,hdcp-channels: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 2 + items: + maximum: 14 + description: + The Secure Enclave's HDCP interface channels assigned to this display + coprocessor. The first is the HDCP 2.2 transmitter channel of its + external output. Absent when the coprocessor has no HDCP transmitter. + apple,sleep-host-stop: type: boolean description: From ccd3793b727003fb7d9d5368e6974274d3da1e4a Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 01:08:49 +1100 Subject: [PATCH 1448/1514] arm64: dts: apple: describe the display coprocessors' HDCP channels Fill in "apple,hdcp-channels" from the Apple Device Tree for t8112 (dcp 5/6, dcpext 7/8) and t604x (dcp 5/6, dcpext0 7/8, dcpext1 9/10). The t604x values come from a t6041 device tree; t6040 shares the layout. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t604x-extdisp.dtsi | 2 ++ arch/arm64/boot/dts/apple/t604x.dtsi | 1 + arch/arm64/boot/dts/apple/t8112.dtsi | 2 ++ 3 files changed, 5 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi b/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi index 3b60ac6afcb788..1cec4e06a66d70 100644 --- a/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi @@ -18,6 +18,7 @@ mboxes = <&dcpext0_mbox>; mbox-names = "mbox"; iommus = <&dcpext0_dart 23>; + apple,hdcp-channels = <7 8>; /* guessed: the internal DCP uses 0x20000, J700 DISPEXT0 is +0x8000 */ apple,bw-scratch = <&pmgr_dcp 0 4 0x28000>; /* firmware Disp_Index, the dual-pipe endpoint ID */ @@ -56,6 +57,7 @@ mboxes = <&dcpext1_mbox>; mbox-names = "mbox"; iommus = <&dcpext1_dart 23>; + apple,hdcp-channels = <9 10>; /* guessed, as dcpext0 */ apple,bw-scratch = <&pmgr_dcp 0 4 0x30000>; apple,dcp-endpoint = <2>; diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index b269473755b871..b67f4c3e10dd2c 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -667,6 +667,7 @@ mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 23>; + apple,hdcp-channels = <5 6>; apple,bw-scratch = <&pmgr_dcp 0 4 0x20000>; apple,iomfb-surfaces = <1 1 0 0>; /* the boot loader describes the piodma's regions with 2+2 cells */ diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index fd13d3c654e935..9d06d392525c15 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -793,6 +793,7 @@ mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 5 0x8 0x00000000 0x7 0xffff0000>; + apple,hdcp-channels = <5 6>; /* the ADT has 2 additional regs which seems to be unused */ reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; @@ -2007,6 +2008,7 @@ mboxes = <&dcpext_mbox>; mbox-names = "mbox"; iommus = <&dcpext_dart 5 0x8 0x00000000 0x7 0xffff0000>; + apple,hdcp-channels = <7 8>; phandle = <&dcpext>; /* the ADT has 2 additional regs which seems to be unused */ From 932b5216a2e68e2398813d6c1e42bbf414062a35 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 14:39:09 -0500 Subject: [PATCH 1449/1514] iommu/apple-dart: drain TLB flushes and fault IRQs when display DART goes dark When a display DART is marked display_dark before its power domain is lowered at runtime, a TLB flush that already passed the display_dark check or a shared fault IRQ handler can still reach DART MMIO after the domain powers off. Track active display TLB flush writers and dark-mode page-table sync writers under managed_lock, gate apple_dart_irq() on display_dark, drain in-flight writers, map TCR readers, and fault IRQs before returning from apple_dart_power_dark(..., true) and apple_dart_display_streams(..., false, ...), and drain dark writers while flushing any stale TLB updates before clearing display_dark or re-enabling streams. On a failed or incomplete reopen drain/flush, preserve display_dark and display_tlb_stale and return the error. Return an error from apple_dart_power_dark() and propagate errors from apple_dart_power_dark() and apple_dart_display_streams(..., true, ...) in all apple-dcp callers so power domains are never lowered after a drain failure and firmware is never restarted with stale DART state. Signed-off-by: Erik Bourget --- drivers/gpu/drm/apple/dcp-internal.h | 2 + drivers/gpu/drm/apple/dcp.c | 290 ++++++++++++++++++++------- drivers/iommu/apple-dart.c | 205 ++++++++++++++----- include/linux/soc/apple/dart.h | 5 +- 4 files changed, 377 insertions(+), 125 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 9ec6b6ba41a276..325e25351bbb15 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1010,7 +1010,9 @@ struct apple_dcp { bool s2r_power_on; bool s2r_power_oob; u8 s2r_step; + struct mutex s2r_dart_lock; /* serializes D572 DART callback with s2r_active */ struct completion s2r_dart_done; + int s2r_dart_err; struct completion s2r_hpd_done; bool sleep_host_stop; struct dcp_t6041_power t6041_power; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 59a2b3d198c6c9..fb1d0f7ac0f680 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -4939,6 +4939,7 @@ int dcp_start(struct platform_device *pdev) /* Even if nothing starts, dcp_wait_ready() must find it initialised. */ init_completion(&dcp->start_done); + mutex_init(&dcp->s2r_dart_lock); init_completion(&dcp->s2r_dart_done); if (dcp->fw_compat == DCP_FIRMWARE_V_26_6) return iomfb_v26_6_start(dcp); @@ -8518,6 +8519,7 @@ static int dcp_platform_probe_pipe(struct platform_device *pdev) of_property_read_u32(dev->of_node, "apple,dptx-phy", &dcp->dptx_phy); of_property_read_u32(dev->of_node, "apple,dptx-die", &dcp->dptx_die); dcp->fixed_dptx_phy = dcp->dptx_phy; + mutex_init(&dcp->s2r_dart_lock); init_completion(&dcp->s2r_dart_done); init_completion(&dcp->s2r_hpd_done); init_completion(&dcp->typec_iomfb_hpd_ready); @@ -9552,19 +9554,31 @@ static void dcp_s2r_find_darts(struct apple_dcp *dcp) } } +static void dcp_s2r_dart_end(struct apple_dcp *dcp) +{ + guard(mutex)(&dcp->s2r_dart_lock); + WRITE_ONCE(dcp->s2r_active, false); +} + void dcp_s2r_dart_power(struct apple_dcp *dcp, u32 on) { + int ret = 0; + if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP) dev_dbg(dcp->dev, "D572(%u) s2r_active=%u\n", on, READ_ONCE(dcp->s2r_active)); + guard(mutex)(&dcp->s2r_dart_lock); if (!READ_ONCE(dcp->s2r_active)) return; if (dcp->s2r_disp_dart) - apple_dart_display_streams(dcp->s2r_disp_dart, dcp_s2r_layout(dcp)->disp_streams, - on, false); - if (dcp->fw_compat != DCP_FIRMWARE_V_26_6_DESKTOP || !on) + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + dcp_s2r_layout(dcp)->disp_streams, + on, false); + if (ret) + WRITE_ONCE(dcp->s2r_dart_err, ret); + if (dcp->fw_compat != DCP_FIRMWARE_V_26_6_DESKTOP || !on || ret) complete(&dcp->s2r_dart_done); } @@ -9641,6 +9655,7 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) bool idle; int ret; + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); dcp_s2r_find_darts(dcp); WRITE_ONCE(dcp->s2r_active, true); @@ -9666,6 +9681,11 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) ret = -ETIMEDOUT; goto err; } + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) { + dev_err(dcp->dev, "display DART stream off failed on D572: %d\n", ret); + goto err; + } dev_dbg(dcp->dev, "display off: set_power_state(0) %lld ms, D572 %lld ms\n", power_ms, ktime_ms_delta(ktime_get(), start)); display_off = true; @@ -9718,13 +9738,13 @@ static int dcp_s2r_quiesce(struct apple_dcp *dcp, u32 *status) dev_dbg(dcp->dev, "firmware idle after %lld ms, status %#x\n", ktime_ms_delta(ktime_get(), start), *status); - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); dcp->s2r_refused_off = false; return 0; err: - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); dcp_s2r_put_darts(dcp); /* * Refused with the display off: leave the firmware running, never stop it under its @@ -10097,7 +10117,6 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) u32 val; int ret; - dcp->s2r_domains_up = false; ret = dcp_s2r_map_power(dcp, &ps, &pwrgate, &pmc); if (ret) goto out; @@ -10109,8 +10128,12 @@ static int dcp_s2r_domains_off(struct apple_dcp *dcp) * so on every firmware (27.2 reports 1 at the stop). Dark until the domains are * back, as for an external DCP. */ - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (ret) + goto out; + } + dcp->s2r_domains_up = false; if (pmc) dcp_pmc_set(dcp, pmc, false); val = readl(ps + l->disp_cpu); @@ -10282,13 +10305,18 @@ static int dcp_s2r_ext_start(struct apple_dcp *dcp, bool cycled) if (ret) return ret; /* After the domains, whose writes it would reject, the DART protects them again. */ - apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, true, - false); + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, + true, false); + if (ret) + return ret; if (!cycled) return apple_rtkit_sleep_return(dcp->rtk, control); - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (ret) + return ret; + } return apple_rtkit_power_cycled_return(dcp->rtk, control); } @@ -10323,8 +10351,11 @@ static int dcp_s2r_ext_domains_off(struct apple_dcp *dcp) * Its display DART goes off with DISPEXT0, and every framebuffer is mapped into it: a * map during the hold would reach its registers. Dark until the domains are back. */ - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, true); + if (ret) + goto out; + } dcp->s2r_domains_up = false; dcp_pmc_set(dcp, pmc, false); ret = 0; @@ -10428,13 +10459,20 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) if (ret) return ret; /* Powered again: the invalidations held while it was dark run now. */ - if (dcp->s2r_disp_dart) - apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (dcp->s2r_disp_dart) { + ret = apple_dart_power_dark(dcp->s2r_disp_dart, false); + if (ret) + return ret; + } /* After the domains, whose writes it would reject, the DART protects them again. */ - if (dcp->s2r_dcp_dart) - apple_dart_display_streams(dcp->s2r_dcp_dart, dcp_s2r_layout(dcp)->dcp_streams, - true, false); + if (dcp->s2r_dcp_dart) { + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, + dcp_s2r_layout(dcp)->dcp_streams, + true, false); + if (ret) + return ret; + } /* Set up again before the firmware runs, which uses it right away. */ if (dcp->hw.s2r_disp_dart_with_dcp && dcp->s2r_disp_dart) { ret = apple_dart_display_streams(dcp->s2r_disp_dart, @@ -10484,6 +10522,7 @@ static int dcp_s2r_warm_restart(struct apple_dcp *dcp) */ static int dcp_s2r_display_on(struct apple_dcp *dcp) { + bool done; int ret; ret = dcp_s2r_warm_restart(dcp); @@ -10492,6 +10531,7 @@ static int dcp_s2r_display_on(struct apple_dcp *dcp) return ret; } + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); @@ -10499,13 +10539,19 @@ static int dcp_s2r_display_on(struct apple_dcp *dcp) ret = dcp_s2r_power(dcp, true, true, true); if (ret) { dev_err(dcp->dev, "no reply to set_power_state(1): %d\n", ret); - goto out; + dcp_s2r_dart_end(dcp); + return ret; } - if (!wait_for_completion_timeout(&dcp->s2r_dart_done, - msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) + done = wait_for_completion_timeout(&dcp->s2r_dart_done, + msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS)); + dcp_s2r_dart_end(dcp); + if (!done && !completion_done(&dcp->s2r_dart_done)) { dev_warn(dcp->dev, "no D572 after set_power_state(1), scanout DART left off\n"); -out: - WRITE_ONCE(dcp->s2r_active, false); + return -ETIMEDOUT; + } + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) + dev_err(dcp->dev, "display DART stream on failed on D572: %d\n", ret); return ret; } @@ -10762,13 +10808,28 @@ static void dcp_s2r_light_running(struct apple_dcp *dcp) int ret; dcp_s2r_find_darts(dcp); + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); ret = dcp_s2r_power(dcp, true, true, true); - if (!ret && !wait_for_completion_timeout(&dcp->s2r_dart_done, - msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS))) - dev_warn(dcp->dev, "no D572 after set_power_state(1), scanout DART left off\n"); - WRITE_ONCE(dcp->s2r_active, false); + if (!ret) { + bool done = wait_for_completion_timeout(&dcp->s2r_dart_done, + msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS)); + + dcp_s2r_dart_end(dcp); + if (!done && !completion_done(&dcp->s2r_dart_done)) { + dev_warn(dcp->dev, + "no D572 after set_power_state(1), scanout DART left off\n"); + ret = -ETIMEDOUT; + } else { + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) + dev_err(dcp->dev, "display DART stream on failed on D572: %d\n", + ret); + } + } else { + dcp_s2r_dart_end(dcp); + } dcp_s2r_put_darts(dcp); if (ret) { WRITE_ONCE(dcp->crashed, true); @@ -10854,8 +10915,10 @@ static void dcp_s2r_prewarm_work(struct work_struct *work) if (ret) { /* Back as DPMS off left it, stopped and powered down: DPMS on starts it again. */ dcp_s2r_stop_failed_start(dcp); - dcp_s2r_stop_streams(dcp); - dcp_s2r_domains_off(dcp); + if (!dcp_s2r_stop_streams(dcp)) + dcp_s2r_domains_off(dcp); + else + WRITE_ONCE(dcp->crashed, true); dcp_s2r_put_darts(dcp); dev_warn(dcp->dev, "wake: firmware start failed, DPMS on tries again: %d\n", ret); return; @@ -11610,21 +11673,39 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * An external DCP stopped for an earlier sleep stays down, with its domains forced off by * the power word step: reading its registers again hung the second sleep of a boot (11 Nov). */ - if (external) { - /* Also one that was never running: the power word step took its domains down too. */ - if (READ_ONCE(dcp->ext_dead) || dcp->t6041_ext_seen) - return 0; - } + if (external && dcp->t6041_ext_seen) + return 0; if (!apple_rtkit_is_running(dcp->rtk)) { + ret = 0; if (external) { + if (dcp->coproc_reg && + (readl(dcp->coproc_reg + APPLE_DCP_COPROC_CPU_CONTROL) & + APPLE_DCP_COPROC_CPU_CONTROL_RUN)) { + dcp_s2r_cpu_stop(dcp); + ret = readl_poll_timeout(dcp->coproc_reg + + APPLE_DCP_COPROC_CPU_CONTROL, + ctrl, + !(ctrl & APPLE_DCP_COPROC_CPU_CONTROL_RUN), + 100, 10000); + if (ret) { + dev_err(dev, + "coprocessor RUN bit did not clear: control %#x\n", + ctrl); + return ret; + } + } dcp_s2r_find_darts(dcp); if (dcp->s2r_disp_dart) - apple_dart_display_streams(dcp->s2r_disp_dart, - DCP_S2R_DISP_STREAMS, false, true); - dcp->t6041_ext_seen = true; + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + false, true); + if (!ret && dcp->s2r_dcp_dart) + ret = dcp_s2r_stop_streams(dcp); + if (!ret) + dcp->t6041_ext_seen = true; } dcp_s2r_put_darts(dcp); - return 0; + return ret; } dcp_drain_for_sleep(dcp); cancel_delayed_work_sync(&dcp->swap_watchdog_wq); @@ -11661,24 +11742,33 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) if (READ_ONCE(dcp->pipe_off)) { dev_info(dev, "display already off: no second power-off\n"); if (dcp->s2r_disp_dart) { - apple_dart_display_streams(dcp->s2r_disp_dart, - DCP_S2R_DISP_STREAMS, false, false); streams_off = true; + ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + false, false); + if (ret) + goto err_unwind; } } else { unsigned long d572 = msecs_to_jiffies(DCP_S2R_D572_TIMEOUT_MS); + WRITE_ONCE(dcp->s2r_dart_err, 0); reinit_completion(&dcp->s2r_dart_done); WRITE_ONCE(dcp->s2r_active, true); _dcp_poweroff(dcp); powered_off = true; if (!wait_for_completion_timeout(&dcp->s2r_dart_done, d572)) { - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); dev_err(dev, "no D572 after the power-off\n"); ret = -ETIMEDOUT; goto err_unwind; } - WRITE_ONCE(dcp->s2r_active, false); + dcp_s2r_dart_end(dcp); + ret = READ_ONCE(dcp->s2r_dart_err); + if (ret) { + dev_err(dev, "display DART stream off failed on D572: %d\n", ret); + goto err_unwind; + } } if (read_poll_timeout(iomfb_channels_idle, idle, idle, 1000, 200000, false, dcp)) { dev_err(dev, "display calls still in flight after the power-off\n"); @@ -11726,7 +11816,6 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * data abort at 0xffffffff00000040 right after the first shmem_setup). */ if (external) { - dcp->t6041_ext_seen = true; ret = apple_rtkit_shutdown(dcp->rtk); if (ret) dev_warn(dev, "external coprocessor shutdown failed: %d\n", ret); @@ -11757,33 +11846,48 @@ static int dcp_t6041_stop_one(struct device *dev, void *data) * later unmap would flush a DART behind a dead block (11 Nov). * Marked dark, the flush only publishes to memory. */ + ret = 0; if (external && dcp->s2r_disp_dart) - apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, - false, true); - ret = dcp_s2r_stop_streams(dcp); + ret = apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, + false, true); + if (!ret) + ret = dcp_s2r_stop_streams(dcp); dcp_s2r_put_darts(dcp); if (ret) { dev_err(dev, "failed to stop DCP DART streams: %d\n", ret); return ret; } + if (external) + dcp->t6041_ext_seen = true; return 0; err_unwind: - if (!external) { - if (keep_set) { - if (dcp->s2r_disp_dart) - apple_dart_display_keep(dcp->s2r_disp_dart, - DCP_S2R_DISP_STREAMS, false); - if (dcp->s2r_dcp_dart) - apple_dart_display_keep(dcp->s2r_dcp_dart, - DCP_S2R_DCP_STREAMS, false); + { + int dart_ret = 0; + + if (!external) { + if (keep_set) { + if (dcp->s2r_disp_dart) + apple_dart_display_keep(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, false); + if (dcp->s2r_dcp_dart) + apple_dart_display_keep(dcp->s2r_dcp_dart, + DCP_S2R_DCP_STREAMS, false); + } + if ((powered_off || streams_off) && dcp->s2r_disp_dart) + dart_ret = apple_dart_display_streams(dcp->s2r_disp_dart, + DCP_S2R_DISP_STREAMS, + true, false); + } + dcp_s2r_put_darts(dcp); + if (dart_ret) { + dev_err(dev, "display DART restore after failed stop failed: %d\n", + dart_ret); + WRITE_ONCE(dcp->crashed, true); + return ret; } - if ((powered_off || streams_off) && dcp->s2r_disp_dart) - apple_dart_display_streams(dcp->s2r_disp_dart, - DCP_S2R_DISP_STREAMS, true, false); } - dcp_s2r_put_darts(dcp); iomfb_pause_presentation(dcp, false); if (idle_attempted) { int ap_ret = apple_rtkit_ap_power(dcp->rtk, true); @@ -12167,15 +12271,23 @@ static int dcp_t6041_start_one(struct device *dev, void *data) dev_warn(dev, "display child domains not on after the sleep: %#x\n", to); dcp_s2r_find_darts(dcp); + ret = 0; if (dcp->s2r_disp_dart) { apple_dart_display_keep(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, false); - apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, true, false); + ret = apple_dart_display_streams(dcp->s2r_disp_dart, DCP_S2R_DISP_STREAMS, + true, false); } - if (dcp->s2r_dcp_dart) { + if (!ret && dcp->s2r_dcp_dart) { apple_dart_display_keep(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, false); - apple_dart_display_streams(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, true, false); + ret = apple_dart_display_streams(dcp->s2r_dcp_dart, DCP_S2R_DCP_STREAMS, + true, false); } dcp_s2r_put_darts(dcp); + if (ret) { + dev_err(dev, "display DART stream restore after the sleep failed: %d\n", ret); + WRITE_ONCE(dcp->crashed, true); + return ret; + } WRITE_ONCE(dcp->crashed, false); WRITE_ONCE(dcp->ext_dead, false); @@ -12209,18 +12321,20 @@ static int dcp_t6041_start_one(struct device *dev, void *data) static bool dcp_t6041_down, dcp_t6041_words; -/* @np's first DART, dark if its driver is bound. */ -static void dcp_t6041_dart_dark(struct device_node *np) +/* @np's first DART, dark or lit if its driver is bound. */ +static int dcp_t6041_dart_dark(struct device_node *np, bool dark) { struct device_node *dart = np ? of_parse_phandle(np, "iommus", 0) : NULL; struct platform_device *pdev = dart ? of_find_device_by_node(dart) : NULL; + int ret = 0; of_node_put(dart); if (!pdev) - return; + return 0; if (device_is_bound(&pdev->dev)) - apple_dart_power_dark(&pdev->dev, true); + ret = apple_dart_power_dark(&pdev->dev, dark); put_device(&pdev->dev); + return ret; } /* @@ -12230,18 +12344,50 @@ static void dcp_t6041_dart_dark(struct device_node *np) * whose DCP never bound, which the display subsystem skips as unusable, is covered too, and so * is every chain a board enables, not only the first two. */ -static void dcp_t6041_ext_darts_dark(void) +static int dcp_t6041_ext_darts_dark(void) { - struct device_node *np, *piodma; + struct device_node *np, *piodma, *fail_np = NULL; + bool fail_on_dcp = false; + int ret = 0; for_each_compatible_node(np, NULL, "apple,t6041-dcpext") { if (!of_device_is_available(np)) continue; piodma = of_get_child_by_name(np, "piodma"); - dcp_t6041_dart_dark(piodma); + ret = dcp_t6041_dart_dark(piodma, true); + of_node_put(piodma); + if (ret) { + fail_np = np; + break; + } + ret = dcp_t6041_dart_dark(np, true); + if (ret) { + fail_np = np; + fail_on_dcp = true; + break; + } + } + if (!ret) + return 0; + for_each_compatible_node(np, NULL, "apple,t6041-dcpext") { + if (!of_device_is_available(np)) + continue; + if (np == fail_np) { + if (fail_on_dcp) { + piodma = of_get_child_by_name(np, "piodma"); + dcp_t6041_dart_dark(piodma, false); + of_node_put(piodma); + } + of_node_put(np); + break; + } + dcp_t6041_dart_dark(np, false); + piodma = of_get_child_by_name(np, "piodma"); + dcp_t6041_dart_dark(piodma, false); of_node_put(piodma); - dcp_t6041_dart_dark(np); } + of_node_put(fail_np); + return ret; } enum dcp_t6041_step { DCP_S2R_FW_STOP, DCP_S2R_WORDS_DOWN, DCP_S2R_START }; @@ -12268,8 +12414,10 @@ static int dcp_t6041_s2r_step(enum dcp_t6041_step step) if (step == DCP_S2R_WORDS_DOWN) { if (dcp_t6041_words || !dcp_t6041_down) return 0; + ret = dcp_t6041_ext_darts_dark(); + if (ret) + return ret; dcp_t6041_words = true; - dcp_t6041_ext_darts_dark(); for (i = 0; i < host->t6041_power.num_chains; i++) { ret = dcp_t6041_word_try(host->dev, &host->t6041_power, &host->t6041_power.chains[i]); diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index c630e5a248b159..56358be85390b6 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -404,6 +404,8 @@ struct apple_dart { */ bool display_dark; bool display_tlb_stale; + unsigned int display_writers; + unsigned int display_dark_writers; DECLARE_BITMAP(display_tcr_four, DART_MAX_STREAMS); /* T8020: its enabled streams and translations, saved at the display's power-down */ u32 display_enable; @@ -2966,6 +2968,9 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, * publishing the page table or powering another DART failed. */ for_each_stream_map(i, domain, map) { + unsigned long flags; + bool dark; + stream.dart = map->dart; for (j = 0; j < BITS_TO_LONGS(stream.dart->num_streams); j++) stream.sidmap[j] = atomic_long_read(&map->sidmap[j]); @@ -2975,10 +2980,21 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, * Its display is powered off: publish to memory only. With its streams off * nothing walks the tables, and the TLB is invalidated before they're on. */ - if (READ_ONCE(stream.dart->display_dark)) { + spin_lock_irqsave(&stream.dart->managed_lock, flags); + dark = stream.dart->display_dark; + if (dark) { + stream.dart->display_dark_writers++; + WRITE_ONCE(stream.dart->display_tlb_stale, true); + } else { + stream.dart->display_writers++; + } + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); + if (dark) { ret = stream.dart->locked ? apple_dart_hw_sync_locked(cfg, &stream, true) : 0; - WRITE_ONCE(stream.dart->display_tlb_stale, true); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_dark_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; continue; } @@ -2990,12 +3006,18 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, ret = stream.dart->locked ? apple_dart_hw_sync_locked(cfg, &stream, true) : 0; apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; continue; } ret = pm_runtime_resume_and_get(stream.dart->dev); if (ret < 0) { apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); dev_err_ratelimited(stream.dart->dev, "failed to power DART for TLB synchronization: %d\n", ret); err = err ?: ret; @@ -3026,6 +3048,9 @@ static int apple_dart_domain_flush_tlb_range(struct apple_dart_domain *domain, apple_dart_managed_quarantine(stream.dart); pm_runtime_put(stream.dart->dev); apple_dart_sleep_writer_put(stream.dart, gate); + spin_lock_irqsave(&stream.dart->managed_lock, flags); + stream.dart->display_writers--; + spin_unlock_irqrestore(&stream.dart->managed_lock, flags); err = err ?: ret; } return err; @@ -5344,11 +5369,13 @@ static irqreturn_t apple_dart_irq(int irq, void *dev) * faulting. Its line can be shared or still pending, so leave it alone; * apple_dart_host_power_off() waits for a handler already past this. */ - if (READ_ONCE(dart->commands_gated) || READ_ONCE(dart->host_off)) + if (READ_ONCE(dart->commands_gated) || READ_ONCE(dart->host_off) || + READ_ONCE(dart->display_dark)) return IRQ_NONE; if (pm_runtime_resume_and_get(dart->dev) < 0) return IRQ_NONE; - if (!READ_ONCE(dart->commands_gated) && !READ_ONCE(dart->host_off)) + if (!READ_ONCE(dart->commands_gated) && !READ_ONCE(dart->host_off) && + !READ_ONCE(dart->display_dark)) ret = dart->hw->irq_handler(irq, dev); pm_runtime_put(dart->dev); return ret; @@ -8231,6 +8258,101 @@ EXPORT_SYMBOL_GPL(apple_dart_gapf_ready); * power-up the translations saved at the power-down are written back when they were * lost and the DART is unlocked; lost and still locked, it stays off. */ +static int apple_dart_display_dark_exit(struct apple_dart *dart); + +/* + * Close admission to display DART MMIO and drain in-flight TLB flushes, map + * TCR readers, and fault IRQ handlers before the display domain powers down. + */ +static int apple_dart_display_dark_enter(struct apple_dart *dart) +{ + unsigned long flags; + unsigned int sid, tries; + bool entered = false; + + if (!READ_ONCE(dart->display_dark)) { + for (sid = 0; sid < dart->num_streams; sid++) + __assign_bit(sid, dart->display_tcr_four, + readl(dart->regs + DART_TCR(dart, sid)) & + dart->hw->tcr_4level); + spin_lock_irqsave(&dart->managed_lock, flags); + if (!dart->display_dark) { + WRITE_ONCE(dart->display_dark, true); + entered = true; + } + spin_unlock_irqrestore(&dart->managed_lock, flags); + } + + for (tries = 0; tries < 10000; tries++) { + bool busy; + + spin_lock_irqsave(&dart->managed_lock, flags); + busy = dart->display_writers != 0; + spin_unlock_irqrestore(&dart->managed_lock, flags); + if (!busy) + break; + usleep_range(10, 20); + } + if (tries == 10000) { + if (entered) + apple_dart_display_dark_exit(dart); + dev_err(dart->dev, "display DART TLB writers did not drain before power-down\n"); + return -EBUSY; + } + + /* Serialize with map paths reading DART_TCR under dart->lock. */ + spin_lock_irqsave(&dart->lock, flags); + spin_unlock_irqrestore(&dart->lock, flags); + + if (dart->irq > 0) + synchronize_irq(dart->irq); + return 0; +} + +static int apple_dart_display_dark_exit(struct apple_dart *dart) +{ + struct apple_dart_stream_map all = { .dart = dart }; + unsigned long flags; + unsigned int tries; + int ret; + + bitmap_fill(all.sidmap, dart->num_streams); + for (tries = 0; tries < 10000; tries++) { + bool stale = false; + + spin_lock_irqsave(&dart->managed_lock, flags); + if (!dart->display_dark) { + spin_unlock_irqrestore(&dart->managed_lock, flags); + return 0; + } + if (!dart->display_dark_writers) { + stale = READ_ONCE(dart->display_tlb_stale); + WRITE_ONCE(dart->display_tlb_stale, false); + if (!stale) { + WRITE_ONCE(dart->display_dark, false); + spin_unlock_irqrestore(&dart->managed_lock, flags); + return 0; + } + } + spin_unlock_irqrestore(&dart->managed_lock, flags); + if (stale) { + ret = dart->hw->invalidate_tlb(&all); + if (ret) { + spin_lock_irqsave(&dart->managed_lock, flags); + WRITE_ONCE(dart->display_tlb_stale, true); + spin_unlock_irqrestore(&dart->managed_lock, flags); + dev_err(dart->dev, "TLB invalidation at power-on failed: %d\n", + ret); + return ret; + } + continue; + } + usleep_range(10, 20); + } + dev_err(dart->dev, "display DART dark writers did not drain at power-on\n"); + return -EBUSY; +} + static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams, bool on, bool flush) { @@ -8254,6 +8376,8 @@ static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams ret = apple_dart_hw_reset(dart); if (ret && ret != -EBUSY) dev_warn(dart->dev, "reset at power-on: %d\n", ret); + /* Keep target streams disabled until dark drain and TLB flush succeed. */ + writel(readl(enable) & ~streams, enable); for (sid = 0; sid < dart->num_streams; sid++) { for (idx = 0; idx < dart->hw->ttbr_count; idx++) writel(dart->save_ttbr[sid][idx], @@ -8266,19 +8390,22 @@ static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams error = readl(dart->regs + DART_T8020_ERROR); if (error & DART_T8020_ERROR_FLAG) writel(error, dart->regs + DART_T8020_ERROR); + /* + * Drain dark page-table writers and invalidate the TLB before + * enabling streams or reopening DMA. + */ + scoped_guard(spinlock_irqsave, &dart->managed_lock) + WRITE_ONCE(dart->display_tlb_stale, true); + ret = apple_dart_display_dark_exit(dart); + if (ret) + return ret; if (dart->display_saved) writel(readl(enable) | (dart->display_enable & streams), enable); - /* Maps and unmaps while it was off left their invalidations to here. */ - bitmap_fill(map.sidmap, dart->num_streams); - if (dart->hw->invalidate_tlb(&map)) - dev_err(dart->dev, "TLB invalidation at power-on failed\n"); dart->host_off_slept = false; dart->display_saved = false; dart->sleep_flushed = false; - WRITE_ONCE(dart->display_tlb_stale, false); - WRITE_ONCE(dart->display_dark, false); WRITE_ONCE(dart->host_off, false); - return ret; + return 0; } /* @@ -8292,11 +8419,10 @@ static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams apple_dart_save_state(dart); dart->display_enable = readl(enable); dart->display_saved = true; - for (sid = 0; sid < dart->num_streams; sid++) - __assign_bit(sid, dart->display_tcr_four, - dart->save_tcr[sid] & dart->hw->tcr_4level); - WRITE_ONCE(dart->display_dark, true); } + ret = apple_dart_display_dark_enter(dart); + if (ret) + return ret; writel(readl(enable) & ~streams, enable); if (flush) { for_each_set_bit(sid, &bits, dart->num_streams) @@ -8388,15 +8514,9 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl apple_dart_gapf_protect(dart); dart->sleep_flushed = false; /* Maps or unmaps while it was dark left their invalidations here. */ - if (READ_ONCE(dart->display_tlb_stale)) { - struct apple_dart_stream_map all = { .dart = dart }; - - bitmap_fill(all.sidmap, dart->num_streams); - if (dart->hw->invalidate_tlb(&all)) - dev_err(dev, "TLB invalidation at power-on failed\n"); - WRITE_ONCE(dart->display_tlb_stale, false); - } - WRITE_ONCE(dart->display_dark, false); + ret = apple_dart_display_dark_exit(dart); + if (ret) + return ret; writel(0, dart->regs + 0x210); writel(0, dart->regs + 0x4060); writel(streams, dart->regs + DART_T8110_ENABLE_STREAMS); @@ -8406,13 +8526,9 @@ int apple_dart_display_streams(struct device *dev, u32 streams, bool on, bool fl if (flush && dart->sleep_flushed) return 0; - if (!READ_ONCE(dart->display_dark)) { - for (sid = 0; sid < dart->num_streams; sid++) - __assign_bit(sid, dart->display_tcr_four, - readl(dart->regs + DART_TCR(dart, sid)) & - dart->hw->tcr_4level); - WRITE_ONCE(dart->display_dark, true); - } + ret = apple_dart_display_dark_enter(dart); + if (ret) + return ret; writel(U32_MAX, dart->regs + 0x4060); writel(0, dart->regs + 0x4000); @@ -8444,30 +8560,15 @@ EXPORT_SYMBOL_GPL(apple_dart_display_streams); * into it: dark, maps reach memory only and their invalidations wait; lit, those run. Its * streams are left as they are. Call it dark while it's still powered. */ -void apple_dart_power_dark(struct device *dev, bool dark) +int apple_dart_power_dark(struct device *dev, bool dark) { struct apple_dart *dart = dev_get_drvdata(dev); - unsigned int sid; - - if (dark) { - if (READ_ONCE(dart->display_dark)) - return; - for (sid = 0; sid < dart->num_streams; sid++) - __assign_bit(sid, dart->display_tcr_four, - readl(dart->regs + DART_TCR(dart, sid)) & - dart->hw->tcr_4level); - WRITE_ONCE(dart->display_dark, true); - return; - } - if (READ_ONCE(dart->display_tlb_stale)) { - struct apple_dart_stream_map all = { .dart = dart }; - bitmap_fill(all.sidmap, dart->num_streams); - if (dart->hw->invalidate_tlb(&all)) - dev_err(dev, "TLB invalidation at power-on failed\n"); - WRITE_ONCE(dart->display_tlb_stale, false); - } - WRITE_ONCE(dart->display_dark, false); + if (!dart) + return -ENODEV; + if (dark) + return apple_dart_display_dark_enter(dart); + return apple_dart_display_dark_exit(dart); } EXPORT_SYMBOL_GPL(apple_dart_power_dark); diff --git a/include/linux/soc/apple/dart.h b/include/linux/soc/apple/dart.h index 15e7c256999e87..d636570c795a66 100644 --- a/include/linux/soc/apple/dart.h +++ b/include/linux/soc/apple/dart.h @@ -226,7 +226,7 @@ int apple_dart_display_keep(struct device *dev, u32 streams, bool save); /* A GAPF slice released before its coprocessor's CPU domain comes up after a wake. */ int apple_dart_gapf_ready(struct device *dev); /* A display DART whose domain goes off at runtime while others still map into it. */ -void apple_dart_power_dark(struct device *dev, bool dark); +int apple_dart_power_dark(struct device *dev, bool dark); /* A DART's state kept across its consumer's own power cycle, outside a system sleep. */ int apple_dart_m5_restore(struct device *dev, struct device *owner); /* T6050: a display coprocessor's DART around its restart, the display pipe's around its domain's. */ @@ -267,8 +267,9 @@ static inline int apple_dart_gapf_ready(struct device *dev) return 0; } -static inline void apple_dart_power_dark(struct device *dev, bool dark) +static inline int apple_dart_power_dark(struct device *dev, bool dark) { + return 0; } static inline int apple_dart_m5_restore(struct device *dev, struct device *owner) From a5e14b7862a0a356ac3b298221b9a51a5faf79ac Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 15:39:12 -0500 Subject: [PATCH 1450/1514] tools/asahi: update CLPC host-test stubs for per-CPU idle timers Mirror the new idle_armed, idle_timers, idle_lock, and cpuhp fields in the CLPC host-test harnesses and accept the extra pre-timer work cancel in apple_clpc_halt() while preserving the --old-ref control. Signed-off-by: Erik Bourget --- tools/asahi/clpc-gpu-demand-tests.py | 3 +++ tools/asahi/clpc-high-power-cleanup-tests.py | 23 +++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/tools/asahi/clpc-gpu-demand-tests.py b/tools/asahi/clpc-gpu-demand-tests.py index cb8acb4e4faa6f..6e2650f1fd95f5 100644 --- a/tools/asahi/clpc-gpu-demand-tests.py +++ b/tools/asahi/clpc-gpu-demand-tests.py @@ -256,6 +256,8 @@ def cells(name): typedef uint8_t u8; typedef uint32_t u32; typedef uint64_t u64; +typedef int atomic_t; +static void atomic_set(atomic_t *v, int i) { *v = i; } struct device; #define APPLE_CLPC_LEVELS 4 #define APPLE_CLPC_HOLD_MS 32 @@ -326,6 +328,7 @@ def cells(name): bool low_power; unsigned int low_power_khz; unsigned int low_power_mw; + atomic_t idle_armed; }; static unsigned long jiffies; static u64 ktime_get_mono_fast_ns(void) { return jiffies * 1000000ull; } diff --git a/tools/asahi/clpc-high-power-cleanup-tests.py b/tools/asahi/clpc-high-power-cleanup-tests.py index 6e5d9e480e9ff0..841289d9845e55 100755 --- a/tools/asahi/clpc-high-power-cleanup-tests.py +++ b/tools/asahi/clpc-high-power-cleanup-tests.py @@ -35,6 +35,16 @@ def function(source, name): #include #include typedef uint8_t u8; +typedef int atomic_t; +static void __attribute__((unused)) atomic_set(atomic_t *v, int i) { *v = i; } +struct hlist_node { int unused; }; +struct apple_clpc_idle_timer { int timer; }; +static int __attribute__((unused)) apple_clpc_cpuhp_state; +static void __attribute__((unused)) cpuhp_state_remove_instance_nocalls(int s, struct hlist_node *n) { (void)s; (void)n; } +static void __attribute__((unused)) timer_delete_sync(int *t) { (void)t; } +#define scoped_guard(kind, lock) for (int _once = (mutex_lock(lock), 1); _once; _once = (mutex_unlock(lock), 0)) +#define for_each_possible_cpu(cpu) for ((cpu) = 0; (cpu) < 1; (cpu)++) +#define per_cpu_ptr(ptr, cpu) (&(ptr)[cpu]) #define APPLE_CLPC_RAILS 2 #define FREQ_QOS_MIN_DEFAULT_VALUE 0 #define CPUFREQ_POLICY_NOTIFIER 1 @@ -63,9 +73,12 @@ def function(source, name): struct device_node *smc_np; struct apple_clpc_gpu *gpu; struct apple_clpc_ane *ane; - struct mutex sample_lock; + struct mutex sample_lock, idle_lock; struct delayed_work work, idle_work; - bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power; + struct apple_clpc_idle_timer *idle_timers; + struct hlist_node cpuhp_node; + atomic_t idle_armed; + bool has_pmc, stopped, high_power, high_power_sent, policy_nb_added, low_power, cpuhp_added; u8 high_power_seq; enum platform_profile_option profile; unsigned long power_next, ane_until; @@ -109,7 +122,7 @@ def function(source, name): } static void apple_pmc_floor_update(void *p, unsigned a, unsigned mask, unsigned saved) { (void)p; (void)a; (void)mask; (void)saved; - assert(cancels == 4 && !active->work.pending && !active->idle_work.pending); + assert(cancels >= 4 && !active->work.pending && !active->idle_work.pending); floor_restored = true; } static int freq_qos_update_request(struct freq_qos_request *q, int value) { @@ -138,7 +151,7 @@ def function(source, name): assert(s && key == SMC_KEY(zETM) && size == sizeof(last_record)); assert(active->sample_lock.held && !node_put && !freed); if (cleanup) { - assert(detached && debug_removed && floor_restored && cancels == 4); + assert(detached && debug_removed && floor_restored && cancels >= 4); assert(!active->dev->data && !active->gpu->wake && !active->ane->wake); assert(active->stopped && !notifier_removed && !qos_removed); assert(active->vote[0].state == 0 && active->vote[1].state == 0); @@ -182,7 +195,7 @@ def function(source, name): cleanup = true; apple_clpc_stop(&c); assert(freed && notifier_removed && qos_removed == 3); assert(!c.sample_lock.held && !apple_clpc_clients_lock.held); - assert(c.stopped && cancels == 4 && floor_restored && !dev.data); + assert(c.stopped && cancels >= 4 && floor_restored && !dev.data); } int main(void) { /* A real successful performance callback sets the qualified sent state. */ From eab8b5157340ebdeff874eb0a28b43b2e7c9aed3 Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Thu, 26 Nov 2026 16:25:02 -0500 Subject: [PATCH 1451/1514] iommu/apple-dart: update host test stubs for display dark writer tracking Update the standalone C harness stubs in apple-dart-range-tests.py, dart-sleep-writer-tests.py, and bcm4377-radio-sids.py for the managed_lock, display_writers, and display_dark_writers fields used by apple_dart_domain_flush_tlb_range(). Signed-off-by: Erik Bourget --- tools/asahi/apple-dart-range-tests.py | 4 +++- tools/asahi/dart-sleep-writer-tests.py | 4 ++-- tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/asahi/apple-dart-range-tests.py b/tools/asahi/apple-dart-range-tests.py index 8939de0a74e85b..f8c5d0f07d2175 100644 --- a/tools/asahi/apple-dart-range-tests.py +++ b/tools/asahi/apple-dart-range-tests.py @@ -38,6 +38,8 @@ def main(): #define dev_err_ratelimited(...) ((void)0) #define READ_ONCE(x) (x) #define WRITE_ONCE(x, v) ((x) = (v)) +#define spin_lock_irqsave(lock, flags) do { assert(!*(lock)); *(lock) = true; (flags) = 0; } while (0) +#define spin_unlock_irqrestore(lock, flags) do { assert(*(lock)); *(lock) = false; (void)(flags); } while (0) #define DART_T8110_TLB_CMD_OP_FLUSH_SID 1 struct io_pgtable_cfg { int unused; }; struct io_pgtable { struct io_pgtable_cfg cfg; }; @@ -45,7 +47,7 @@ def main(): struct apple_dart; struct apple_dart_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; struct apple_dart_hw { int (*invalidate_tlb)(struct apple_dart_stream_map *); bool gen3; }; -struct apple_dart { int num_streams, locked, version; bool fw_mirror, fw_handoff, managed_sids, display_dark, display_tlb_stale; void *dev; struct apple_dart_hw *hw; }; +struct apple_dart { int num_streams, locked, version; bool fw_mirror, fw_handoff, managed_sids, managed_lock, display_dark, display_tlb_stale; unsigned int display_writers, display_dark_writers; void *dev; struct apple_dart_hw *hw; }; struct apple_dart_atomic_stream_map { struct apple_dart *dart; unsigned long sidmap[1]; }; struct apple_dart_domain { void *pgtbl_ops; bool dcp; struct apple_dart_atomic_stream_map streams[2]; int count; diff --git a/tools/asahi/dart-sleep-writer-tests.py b/tools/asahi/dart-sleep-writer-tests.py index e07f0a68a386c4..4888e79e1bfe8a 100644 --- a/tools/asahi/dart-sleep-writer-tests.py +++ b/tools/asahi/dart-sleep-writer-tests.py @@ -52,8 +52,8 @@ def closed_branches_put(text): branches = closed_branches_put(driver) assert branches == 6, branches # Negative control: a branch that leaks its reference is caught. -leak = driver.replace("\t\t\tapple_dart_sleep_writer_put(stream.dart, gate);\n\t\t\terr = err ?: ret;\n\t\t\tcontinue;", - "\t\t\terr = err ?: ret;\n\t\t\tcontinue;", 1) +leak = driver.replace("\t\t\tapple_dart_sleep_writer_put(stream.dart, gate);\n\t\t\tspin_lock_irqsave(&stream.dart->managed_lock, flags);", + "\t\t\tspin_lock_irqsave(&stream.dart->managed_lock, flags);", 1) assert leak != driver try: closed_branches_put(leak) diff --git a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py index bf0ffb0b06e980..e9ab0f3826b9da 100755 --- a/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py +++ b/tools/testing/selftests/drivers/apple/bcm4377-radio-sids.py @@ -115,6 +115,7 @@ def main(): bool four_level, per_stream, tunneled, fw_mirror, fw_handoff; bool pending, preserve_display; bool isp_host, cold_ane, live_mtp, display_dark, display_tlb_stale; + unsigned int display_writers, display_dark_writers; bool cold_gen3, cold_gen3_pcie; u32 cold_gen3_sids; void *tunables; From efa194704a2919b0c01c4725a3161c2463d52aca Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 08:38:27 +1100 Subject: [PATCH 1452/1514] drm/apple: audio: queue the replaced-instance work only while bound The DCP unbinds after its DP audio component and may still connect the card meanwhile. Cancelling the work at unbind left it free to be queued again by such a connect, and the work then acted on the substream of a card being freed. Keep the work disabled outside a bound card: it starts disabled, is enabled once the card is registered, and is disabled (waiting for a running one) at unbind before the card is freed. A connect while it is disabled queues nothing. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/audio.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/apple/audio.c b/drivers/gpu/drm/apple/audio.c index 4f68fdce1c3905..d2333b9340b32e 100644 --- a/drivers/gpu/drm/apple/audio.c +++ b/drivers/gpu/drm/apple/audio.c @@ -113,6 +113,8 @@ struct dcp_audio { #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) /* Ends a stream on a replaced instance, see dcpaud_replaced_work() */ struct work_struct replaced_work; + /* replaced_work is enabled: the card is bound, see dcpaud_comp_unbind() */ + bool replaced_enabled; #endif void *elements; void *productattrs; @@ -2097,6 +2099,11 @@ static int dcpaud_comp_bind(struct device *dev, struct device *main, void *data) ret = dcpaud_init_snd_card(dcpaud); if (!ret) { +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* Connects may queue it from now on, with a card to act on. */ + enable_work(&dcpaud->replaced_work); + dcpaud->replaced_enabled = true; +#endif dcpaud_expose_debugfs_blob(dcpaud, "selected_cookie", &dcpaud->selected_cookie, sizeof(dcpaud->selected_cookie)); dcpaud_expose_debugfs_blob(dcpaud, "elements", dcpaud->elements, @@ -2117,7 +2124,15 @@ static void dcpaud_comp_unbind(struct device *dev, struct device *main, struct dcp_audio *dcpaud = dev_get_drvdata(dev); #if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) - cancel_work_sync(&dcpaud->replaced_work); + /* + * The DCP unbinds after its audio and may still connect: a connect + * from now on queues nothing, and a queued or running work ends + * before the card goes. + */ + if (dcpaud->replaced_enabled) { + disable_work_sync(&dcpaud->replaced_work); + dcpaud->replaced_enabled = false; + } #endif /* snd_card_free_when_closed() checks for NULL */ snd_card_free_when_closed(dcpaud->card); @@ -2188,6 +2203,8 @@ static int dcpaud_probe(struct platform_device *pdev) mutex_init(&dcpaud->link_lock); INIT_WORK(&dcpaud->stale_work, dcpaud_stale_work); INIT_WORK(&dcpaud->replaced_work, dcpaud_replaced_work); + /* Enabled once the card is bound, see dcpaud_comp_bind() */ + disable_work(&dcpaud->replaced_work); #endif INIT_DELAYED_WORK(&dcpaud->void_work, dcpaud_void_work); platform_set_drvdata(pdev, dcpaud); From 9915671b8e421fd854141f87e70ae2ea86524678 Mon Sep 17 00:00:00 2001 From: Fredrik Silfver <1684291+freber@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:43:01 +0100 Subject: [PATCH 1453/1514] arm64: dts: apple: t8122-j615: leave the trackpad power method to the driver Commit d5cc1f60ea32 pinned apple,power-method = <2> on the J615 multi-touch node because the 27.2 MTP firmware rejects the one-stage interface reset. A J615 on the 14.7 stub boots the same t8122-j615.dtb, and its firmware rejects the first two-stage command instead: dockchannel-hid 2fab28000.input: output report 0x40 to iface 0 (comm) failed with err 0xe00002c2 dchid_pm2_set_power() then returns -EIO, dchid_start_interface() fails and dchid_open() returns it, so every open of the multi-touch evdev node fails with EIO. The keyboard works and the trackpad does not. The same machine on the 14.7 stub brought the trackpad up with the method left at its default, power method 1. Commit 628343216 ("HID: dockchannel-hid: fall back to power method 2 when method 1 is rejected") has since made the pin unnecessary on 27.2. When the DT does not pin the method, the transport is not the ring and the node names an AFE reset line, a method 1 power-off rejected with 0xe00002c2 moves the interface to power method 2, including the path for a session handed over running. t8122-j613-j615.dtsi gives the J615 apple,afe-reset-gpios, so the 27.2 firmware still ends up on power method 2 and the 14.7 firmware keeps power method 1. Drop the pin. t8122-j615-25g83.dts keeps its own apple,power-method = <2>. Fixes: d5cc1f60ea32 ("arm64: dts: apple: t8122-j615: hand the MTP over running, two-stage trackpad power") Signed-off-by: Fredrik Silfver <1684291+freber@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t8122-j615.dts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index e14193bee84cbe..425edb7fdca622 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -174,8 +174,11 @@ &mtp_mt { firmware-name = "apple/tpmtfw-j615.bin"; - /* The 27.x trackpad firmware answers only the two-stage power command. */ - apple,power-method = <2>; + /* + * No apple,power-method: the 14.7 trackpad firmware takes only + * method 1 and the 27.x firmware only method 2. dockchannel-hid + * starts with method 1 and moves to method 2 when it is rejected. + */ }; /* The J615 MTP firmware cannot be restarted once quiesced: hand it over running. */ From 065ad624701a154d67304f81bb63494b870f469f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 19 Nov 2026 23:10:32 +1100 Subject: [PATCH 1454/1514] arm64: dts: apple: t6050: share the K boards' N1 and USB-C ports, add K114s and K116c The K114s and K116c had no USB, no Wi-Fi/Bluetooth and no PCIe: the shared t6050-k114-k116.dtsi disabled ATC1, nub-spmi-a0 and the PCIe host, and only the K114c and K116s described their N1 port and USB-C ports, each in its own copy. The boards' ADTs have the same apcie0 port 0 (registers, IRQ 1523, PERST# GPIO 80, N1 on dart-apcie0 streams 1-3), the same PD controllers (hpm1 at 0xa on nub-spmi-a0, hpm2 at 0xc on nub-spmi-a1, SN201202x) and the same atc-phy, usb-drd and dart-usb nodes on all four boards. So: - t6050-k114-k116.dtsi now describes PCIe port 0 with the N1, its wifi0/bluetooth0 aliases and PERST# pin 80. The board file defines the N1's firmware name and its board-id before including it; the platform ID is board-id << 16 | 0x6050. - The new t6050-k114-k116-usb.dtsi describes ATC1 (left-front) and ATC2 (right): PD controllers, combo PHYs, DWC3s, DARTs and the atcphy aliases. Boards include it after t6050-peripherals.dtsi, which defines nub-spmi-a1 for them. - K114c and K116s keep only their deltas: K114c the nub-spmi-a0 fault queue window, the MagSafe PD controller and the ATC2 router; K116s the SD reader on port 1 and the single nub-spmi-a1 window. - K114s (board-id 0x14) and K116c (board-id 0x06) include both. The K114c and K116s DTBs are byte-identical before and after, as are the other T6050 DTBs. The shared blocks are Joshua Warren's K114c and Jens Axboe's K116s descriptions. Signed-off-by: Ryan Murray --- .../boot/dts/apple/t6050-k114-k116-usb.dtsi | 182 +++++++++++++ .../arm64/boot/dts/apple/t6050-k114-k116.dtsi | 106 +++++--- arch/arm64/boot/dts/apple/t6050-k114c.dts | 257 +----------------- arch/arm64/boot/dts/apple/t6050-k114s.dts | 6 + arch/arm64/boot/dts/apple/t6050-k116c.dts | 6 + arch/arm64/boot/dts/apple/t6050-k116s.dts | 235 +--------------- 6 files changed, 291 insertions(+), 501 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi new file mode 100644 index 00000000000000..c82d8c24e3ede1 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The K114c, K114s, K116c and K116s USB-C ports ATC1 (left-front) and ATC2 (right): + * USB 2/3 and the PD controllers. A board file includes this after + * t6050-peripherals.dtsi, which describes nub-spmi-a1 for these boards. + * + * From the boards' ADT, the same on all four: + * ATC0 usb-drd0 left-back hpm0 nub-spmi-a0 0x0c (the boot link's debug port, not described) + * ATC1 usb-drd1 left-front hpm1 nub-spmi-a0 0x0a, port-number 2, acio-parent acio1 + * ATC2 usb-drd2 right hpm2 nub-spmi-a1 0x0c, port-number 3, acio-parent acio2 + * hpm5 nub-spmi-a0 0x08 (MagSafe, not a USB-C connector) + * The PD controllers are SN201202x. The USB4/Thunderbolt routers (acio1, acio2) and the + * DisplayPort routes are not described here; the PHYs run in USB mode. The combo PHY driver + * leaves ATC0 alone on purpose (apple,port-index 0). + * + * The boot loader fills the PHYs' tunables from the ADT through the atcphy aliases. + */ +/ { + aliases { + atcphy1 = &atc1_phy; + atcphy2 = &atc2_phy; + }; +}; + +/* ==== The left-front USB-C port (ATC1) ==== */ +&nub_spmi_a0 { + status = "okay"; + + hpm1: usb-pd@a { + compatible = "apple,sn201202x"; + reg = <0xa SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = "USB-C Left-front"; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm1_hs: endpoint { + remote-endpoint = <&usb_drd1_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm1_ss: endpoint { + remote-endpoint = <&atc1_phy_ep>; + }; + }; + }; + }; + }; +}; + +&atc1_phy_mbox { + status = "okay"; +}; + +&atc1_phy { + status = "okay"; + + port { + atc1_phy_ep: endpoint { + remote-endpoint = <&hpm1_ss>; + }; + }; +}; + +&usb_drd1 { + status = "okay"; + + port { + usb_drd1_hs: endpoint { + remote-endpoint = <&hpm1_hs>; + }; + }; +}; + +&usb_drd1_dart_0 { + status = "okay"; +}; + +&usb_drd1_dart_1 { + status = "okay"; +}; + +/* + * ==== The right USB-C port (ATC2) ==== + * + * The HPM is on its own bus, nub-spmi-a1, and nothing hands the port off, so the power + * domains, the PHY mailbox, the PHY, the DWC3 and its DARTs are enabled outright. The driver + * polls the generation 4 bus and refuses an interrupt on it. + */ +&ps_atc2_common { + status = "okay"; +}; + +&ps_atc2_usb_aon { + status = "okay"; +}; + +&ps_atc2_phymxwrap { + status = "okay"; +}; + +&ps_atc2_usb { + status = "okay"; +}; + +&atc2_phy_mbox { + status = "okay"; +}; + +&atc2_phy { + status = "okay"; + + port { + atc2_phy_ep: endpoint { + remote-endpoint = <&hpm2_ss>; + }; + }; +}; + +&usb_drd2 { + status = "okay"; + + port { + usb_drd2_hs: endpoint { + remote-endpoint = <&hpm2_hs>; + }; + }; +}; + +&usb_drd2_dart_0 { + status = "okay"; +}; + +&usb_drd2_dart_1 { + status = "okay"; +}; + +&nub_spmi_a1 { + /delete-property/ interrupts; + status = "okay"; + + hpm2: usb-pd@c { + compatible = "apple,sn201202x"; + reg = <0xc SPMI_USID>; + + connector { + compatible = "usb-c-connector"; + label = "USB-C Right"; + power-role = "dual"; + data-role = "dual"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + hpm2_hs: endpoint { + remote-endpoint = <&usb_drd2_hs>; + }; + }; + + port@1 { + reg = <1>; + hpm2_ss: endpoint { + remote-endpoint = <&atc2_phy_ep>; + }; + }; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index 70502c23beffbe..a1fa5068268c5f 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -35,6 +35,9 @@ aliases { serial0 = &dockchannel; + /* The boot loader fills the N1's factory addresses through these */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; }; chosen { @@ -80,35 +83,14 @@ }; }; -/* ATC1, ATC3 and the PD controller buses nub-spmi-a0 and -a2: not yet described for these boards */ -&nub_spmi_a0 { - status = "disabled"; -}; - +/* + * ATC3 and the PD controller bus nub-spmi-a2: not described for these boards. The + * USB-C ports ATC1 and ATC2 are in t6050-k114-k116-usb.dtsi. + */ &nub_spmi_a2 { status = "disabled"; }; -&atc1_phy_mbox { - status = "disabled"; -}; - -&atc1_phy { - status = "disabled"; -}; - -&usb_drd1 { - status = "disabled"; -}; - -&usb_drd1_dart_0 { - status = "disabled"; -}; - -&usb_drd1_dart_1 { - status = "disabled"; -}; - &atc3_phy_mbox { status = "disabled"; }; @@ -139,23 +121,81 @@ /* * As on J716c, where reading pin 112 takes an SError, only the pins a node - * here names are exposed, and none is yet. The N1 on PCIe port 0 needs its - * board's platform ID, which the static ADT does not carry, so the port and - * its PERST# pin stay unused for now. + * names are exposed: here 80, PCIe port 0's PERST#. A board that names more + * pins replaces the list. */ &pinctrl_ap { - gpio-reserved-ranges = <0 221>; + gpio-reserved-ranges = <0 80>, <81 140>; }; /* - * The K114s N1 needs its own platform ID (its ADT /chosen board-id << 16 | 0x6050) - * before the port can be described. aura's T6050 hand-off still wants the host's - * iommu-map to mark the ports as it found them, so carry it with the host disabled. + * PCIe port 0: the N1 (Wi-Fi and Bluetooth), the same on all four boards and + * laid out as on J716c: the boot loader trains the link and keeps power, + * clocks, the PHY and PERST; Linux owns the routing, MSI and the DART. The + * port stays disabled until the loader trains it. From the boards' ADT: + * apcie0 gives port 0's registers and IRQ 1523, pci-bridge0's PERST# is GPIO + * 80, and the N1's three functions are on DART streams 1-3. + * + * The board file defines, before including this file, the N1's personalized + * firmware (T6050_K_N1_FIRMWARE) and its ADT /chosen board-id + * (T6050_K_BOARD_ID). The N1's platform ID is board-id << 16 | chip 0x6050. + * aura's T6050 hand-off wants the host's iommu-map to mark the ports as it + * found them. */ &pcie0 { iommu-map = <0x100 &dart_apcie0 1 3>; bus-range = <0 4>; - status = "disabled"; + status = "okay"; + reg = <0x1c 0xb0000000 0x0 0x10000000>, + <0x4 0x14000000 0x0 0x4000>, + <0x4 0x10028000 0x0 0x8000>, + <0x4 0x17010000 0x0 0x4000>, + <0x4 0x10024000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "phy0", "intr2axi0"; + interrupts = ; + interrupt-names = "port0"; + + port00: pci@0,0 { + device_type = "pci"; + reg = <0x0 0 0 0 0>; + bus-range = <1 1>; + apple,link-trained-by-bootloader; + /* PERST#, driven only by the root-port reset after the N1's ROM stage */ + reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; + status = "disabled"; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port00 0 0 0 0>, + <0 0 0 2 &port00 0 0 0 1>, + <0 0 0 3 &port00 0 0 0 2>, + <0 0 0 4 &port00 0 0 0 3>; + + n1_control: control@0,0 { + compatible = "pci106b,1900"; + reg = <0x10000 0x0 0x0 0x0 0x0>; + firmware-name = T6050_K_N1_FIRMWARE; + apple,centauri-platform-id = <((T6050_K_BOARD_ID << 16) | 0x6050)>; + apple,centauri-protocol = <27>; + }; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x10100 0x0 0x0 0x0 0x0>; + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x10200 0x0 0x0 0x0 0x0>; + local-bd-address = [00 00 00 00 00 00]; + }; + }; }; /* These boards' SMC fan and power keys are not yet checked */ diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index ed1f3ec3036a6b..8a15f89849ca8c 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -11,6 +11,9 @@ /* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ #define T6050_K114C +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k114c-ftab.bin" +#define T6050_K_BOARD_ID 0x04 #include "t6050-k114-k116.dtsi" / { @@ -53,78 +56,10 @@ / { aliases { - /* kboot fills the N1's factory addresses from /chosen through these */ - wifi0 = &n1_alpha; - bluetooth0 = &n1_beta; nvram = &nvram; }; }; -/* - * PCIe port 0: the N1 (Wi-Fi and Bluetooth), laid out as on J716c: the boot - * loader trains the link and keeps power, clocks, the PHY and PERST; Linux owns - * the routing, MSI and the DART. The port stays disabled until the loader - * trains it. - */ -&pcie0 { - reg = <0x1c 0xb0000000 0x0 0x10000000>, - <0x4 0x14000000 0x0 0x4000>, - <0x4 0x10028000 0x0 0x8000>, - <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0"; - interrupts = ; - interrupt-names = "port0"; - - /* The N1's three functions are on DART streams 1-3 */ - iommu-map = <0x100 &dart_apcie0 1 3>; - bus-range = <0 4>; - status = "okay"; - - port00: pci@0,0 { - device_type = "pci"; - reg = <0x0 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - /* PERST#, driven only by the root-port reset after the N1's ROM stage */ - reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; - status = "disabled"; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port00 0 0 0 0>, - <0 0 0 2 &port00 0 0 0 1>, - <0 0 0 3 &port00 0 0 0 2>, - <0 0 0 4 &port00 0 0 0 3>; - - /* platform ID (board 0x04 << 16) | chip 0x6050 */ - n1_control: control@0,0 { - compatible = "pci106b,1900"; - reg = <0x10000 0x0 0x0 0x0 0x0>; - firmware-name = "apple/centauri/k114c-ftab.bin"; - apple,centauri-platform-id = <0x00046050>; - apple,centauri-protocol = <27>; - }; - - n1_alpha: wifi@0,1 { - compatible = "pci106b,1902"; - reg = <0x10100 0x0 0x0 0x0 0x0>; - local-mac-address = [00 00 00 00 00 00]; - }; - - n1_beta: bluetooth@0,2 { - compatible = "pci106b,1903"; - reg = <0x10200 0x0 0x0 0x0 0x0>; - local-bd-address = [00 00 00 00 00 00]; - }; - }; -}; - /* * Pin 112's register takes an SError when read, so only the pins a node here * names are exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' @@ -361,61 +296,16 @@ }; /* - * ==== The left-front USB-C port (ATC1) ==== - * - * ADT /arm-io/nub-spmi-a0/hpm1 (SN201202x, SPMI address 0xa, port-number 2, port-location - * "left-front", acio-parent acio1), with atc-phy1, usb-drd1 and dart-usb1. The K114cAP ADT - * has the same hpm0, hpm1, hpm5, atc-phy and usb-drd nodes as the J714cAP one, so this is the - * J714c port block. The ATC1 template nodes of t6050-dieX.dtsi are enabled here; the boards - * sharing t6050-k114-k116.dtsi keep them disabled. The port's USB4/Thunderbolt router - * (/arm-io/acio1) and its DisplayPort routes are not described; the PHY runs in USB mode. - * - * The left-back port (ATC0, hpm0) is the boot link's debug port; the combo PHY driver - * excludes it on purpose (apple,port-index 0). + * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi). This + * board also gives nub-spmi-a0 its generation 4 fault queue (reg[1], which macOS empties when + * the controller starts) and describes the MagSafe 3 port's PD controller. */ -/ { - aliases { - atcphy1 = &atc1_phy; - }; -}; +#include "t6050-k114-k116-usb.dtsi" &nub_spmi_a0 { - status = "okay"; - /* reg[1]: the generation 4 fault queue, which macOS empties when the controller starts */ reg = <0x2 0x8a188000 0x0 0x4000>, <0x2 0x8a184000 0x0 0x4000>; - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Left-front"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm1_ss: endpoint { - remote-endpoint = <&atc1_phy_ep>; - }; - }; - }; - }; - }; - /* * The MagSafe 3 port's PD controller (ADT hpm5, port-type 0x11). It has no USB data * path, so it gets no connector node; tipd registers a Type-C port and a power supply @@ -428,139 +318,10 @@ }; }; -&atc1_phy_mbox { - status = "okay"; -}; - -&atc1_phy { - status = "okay"; - - port { - atc1_phy_ep: endpoint { - remote-endpoint = <&hpm1_ss>; - }; - }; -}; - -&usb_drd1 { - status = "okay"; - - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&hpm1_hs>; - }; - }; -}; - -&usb_drd1_dart_0 { - status = "okay"; -}; - -&usb_drd1_dart_1 { - status = "okay"; -}; - /* - * ==== The right USB-C port (ATC2) ==== - * - * ADT /arm-io/nub-spmi-a1/hpm2 (SN201202x, SPMI address 0xc, port-number 3, port-location - * "right", acio-parent acio2), with atc-phy2, usb-drd2 and dart-usb2. The HPM is on its own - * bus, nub-spmi-a1, and nothing hands the port off, so the power domains, the PHY mailbox, the - * PHY, the DWC3 and its DARTs are enabled outright, as t6050-max-atc2.dtsi does for the J714c - * and J716c. Its USB4/Thunderbolt router (acio2) and PCIe tunnel are - * t6050-max-atc2-router.dtsi, included below; the DisplayPort route is not described. + * The right port's USB4/Thunderbolt router (acio2) and PCIe tunnel; the DisplayPort route + * is not described. */ -/ { - aliases { - atcphy2 = &atc2_phy; - }; -}; - -&ps_atc2_common { - status = "okay"; -}; - -&ps_atc2_usb_aon { - status = "okay"; -}; - -&ps_atc2_phymxwrap { - status = "okay"; -}; - -&ps_atc2_usb { - status = "okay"; -}; - -&atc2_phy_mbox { - status = "okay"; -}; - -&atc2_phy { - status = "okay"; - - port { - atc2_phy_ep: endpoint { - remote-endpoint = <&hpm2_ss>; - }; - }; -}; - -&usb_drd2 { - status = "okay"; - - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&hpm2_hs>; - }; - }; -}; - -&usb_drd2_dart_0 { - status = "okay"; -}; - -&usb_drd2_dart_1 { - status = "okay"; -}; - -&nub_spmi_a1 { - status = "okay"; - /* the driver polls the PD controllers and refuses an interrupt on this bus */ - /delete-property/ interrupts; - - hpm2: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - - connector { - compatible = "usb-c-connector"; - label = "USB-C Right"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - hpm2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - hpm2_ss: endpoint { - remote-endpoint = <&atc2_phy_ep>; - }; - }; - }; - }; - }; -}; - #include "t6050-max-atc2-router.dtsi" /* The host DROM from the K114cAP ADT (/arm-io/acio2 thunderbolt-drom); the boot loader replaces it */ diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 2b88e99a6d9939..409979f034678e 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -10,6 +10,9 @@ * Copyright The Asahi Linux Contributors */ +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k114s-ftab.bin" +#define T6050_K_BOARD_ID 0x14 #include "t6050-k114-k116.dtsi" / { @@ -60,3 +63,6 @@ }; }; }; + +/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +#include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index ff9e875fb19516..a270ed24ba3c7a 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -9,6 +9,9 @@ * Copyright The Asahi Linux Contributors */ +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k116c-ftab.bin" +#define T6050_K_BOARD_ID 0x06 #include "t6050-k114-k116.dtsi" / { @@ -22,3 +25,6 @@ #define T6050_K116C #include "t6050-peripherals.dtsi" + +/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +#include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index 56cf949d104131..c6b1adc3ede00d 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -9,6 +9,9 @@ * Copyright The Asahi Linux Contributors */ +/* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ +#define T6050_K_N1_FIRMWARE "apple/centauri/k116s-ftab.bin" +#define T6050_K_BOARD_ID 0x16 #include "t6050-k114-k116.dtsi" / { @@ -25,9 +28,6 @@ / { aliases { - /* The loader fills the N1's factory addresses through these */ - wifi0 = &n1_alpha; - bluetooth0 = &n1_beta; /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ sep = &sep; }; @@ -44,10 +44,7 @@ }; /* - * PCIe port 0: the N1 (Wi-Fi and Bluetooth), laid out as on J714s. ADT apcie0 - * gives port 0's registers and IRQ 1523, pci-bridge0's PERST# is GPIO 80, and - * the N1's three functions are on DART streams 1-3. The platform ID is this - * board's ADT /chosen board-id (0x16) << 16 | chip 0x6050. + * PCIe port 0, the N1, is in t6050-k114-k116.dtsi. * * PCIe port 1: the SD card reader (ADT apcie0/pci-bridge1/pcie-sdreader, a * GL9755), as on J714s. The boot loader leaves the port down, so the kernel @@ -86,52 +83,8 @@ interrupt-names = "port0", "port1"; iommu-map = <0x100 &dart_apcie0 1 3>, <0x200 &apcie1_dart 1 1>; - bus-range = <0 4>; /* apcie1_dart probes only once port 1 is up: the host must not wait for it */ post-init-providers = <&apcie1_dart>; - status = "okay"; - - port00: pci@0,0 { - device_type = "pci"; - reg = <0x0 0 0 0 0>; - bus-range = <1 1>; - apple,link-trained-by-bootloader; - /* PERST#: ADT pci-bridge0 function-perst, GPIO 80 */ - reset-gpios = <&pinctrl_ap 80 GPIO_ACTIVE_LOW>; - status = "disabled"; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port00 0 0 0 0>, - <0 0 0 2 &port00 0 0 0 1>, - <0 0 0 3 &port00 0 0 0 2>, - <0 0 0 4 &port00 0 0 0 3>; - - n1_control: control@0,0 { - compatible = "pci106b,1900"; - reg = <0x10000 0x0 0x0 0x0 0x0>; - firmware-name = "apple/centauri/k116s-ftab.bin"; - apple,centauri-platform-id = <0x00166050>; - apple,centauri-protocol = <27>; - }; - - n1_alpha: wifi@0,1 { - compatible = "pci106b,1902"; - reg = <0x10100 0x0 0x0 0x0 0x0>; - local-mac-address = [00 00 00 00 00 00]; - }; - - n1_beta: bluetooth@0,2 { - compatible = "pci106b,1903"; - reg = <0x10200 0x0 0x0 0x0 0x0>; - local-bd-address = [00 00 00 00 00 00]; - }; - }; port01: pci@1,0 { device_type = "pci"; @@ -193,172 +146,6 @@ status = "okay"; }; -/* - * Type-C, from the ADT (as on J714s): - * ATC0 usb-drd0 left-back hpm0 nub-spmi-a0 0x0c (the debug port, not described) - * ATC1 usb-drd1 left-front hpm1 nub-spmi-a0 0x0a - * ATC2 usb-drd2 right hpm2 nub-spmi-a1 0x0c - * hpm5 nub-spmi-a0 0x08 (MagSafe, not a USB-C connector) - */ - -/* Left-front port (ATC1): the SN201202x hpm1 and the connector graph */ -&nub_spmi_a0 { - status = "okay"; - - hpm1: usb-pd@a { - compatible = "apple,sn201202x"; - reg = <0xa SPMI_USID>; - - typec1: connector { - compatible = "usb-c-connector"; - label = "USB-C Left-front"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - typec1_hs: endpoint { - remote-endpoint = <&usb_drd1_hs>; - }; - }; - - port@1 { - reg = <1>; - typec1_ss: endpoint { - remote-endpoint = <&atc1_phy_typec>; - }; - }; - }; - }; - }; -}; - -&atc1_phy_mbox { - status = "okay"; -}; - -&atc1_phy { - status = "okay"; - - port { - atc1_phy_typec: endpoint { - remote-endpoint = <&typec1_ss>; - }; - }; -}; - -&usb_drd1 { - status = "okay"; - - port { - usb_drd1_hs: endpoint { - remote-endpoint = <&typec1_hs>; - }; - }; -}; - -&usb_drd1_dart_0 { - status = "okay"; -}; - -&usb_drd1_dart_1 { - status = "okay"; -}; - -/* - * Right port (ATC2): hpm2 on nub-spmi-a1, USB only (dcpext0's DisplayPort route - * through ATC2 stays off). The driver polls the generation 4 bus and refuses an - * interrupt, so it takes the first register window only, as on J714s. - */ -&nub_spmi_a1 { - reg = <0x2 0x8a1a8000 0x0 0x4000>; - /delete-property/ interrupts; - status = "okay"; - - hpm2: usb-pd@c { - compatible = "apple,sn201202x"; - reg = <0xc SPMI_USID>; - - typec2: connector { - compatible = "usb-c-connector"; - label = "USB-C Right"; - power-role = "dual"; - data-role = "dual"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - typec2_hs: endpoint { - remote-endpoint = <&usb_drd2_hs>; - }; - }; - - port@1 { - reg = <1>; - typec2_ss: endpoint { - remote-endpoint = <&atc2_phy_typec>; - }; - }; - }; - }; - }; -}; - -&ps_atc2_common { - status = "okay"; -}; - -&ps_atc2_usb_aon { - status = "okay"; -}; - -&ps_atc2_phymxwrap { - status = "okay"; -}; - -&ps_atc2_usb { - status = "okay"; -}; - -&atc2_phy_mbox { - status = "okay"; -}; - -&atc2_phy { - status = "okay"; - - port { - atc2_phy_typec: endpoint { - remote-endpoint = <&typec2_ss>; - }; - }; -}; - -&usb_drd2 { - status = "okay"; - - port { - usb_drd2_hs: endpoint { - remote-endpoint = <&typec2_hs>; - }; - }; -}; - -&usb_drd2_dart_0 { - status = "okay"; -}; - -&usb_drd2_dart_1 { - status = "okay"; -}; - /* * SMC sensors, as on J714s: every readable float T* key is discovered through * apple,discover-temperatures in t6050-die0.dtsi, so the shared temperature @@ -471,12 +258,20 @@ / { aliases { keyboard = &keyboard; - /* The loader fills the PHYs' tunables from the ADT through these */ - atcphy1 = &atc1_phy; - atcphy2 = &atc2_phy; }; }; +/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +#include "t6050-k114-k116-usb.dtsi" + +/* + * Right port (ATC2): nub-spmi-a1 takes the first register window only, as on + * J714s. + */ +&nub_spmi_a1 { + reg = <0x2 0x8a1a8000 0x0 0x4000>; +}; + /* * The PMP (ADT pmp0, /chosen, /arm-io/pmgr), as on the J714s: iBoot loads its firmware and * the driver starts it with these boot arguments and the firmware properties in the tunables From cb414a5c4020f65f70dfe3eba1f006b1efd7ef9d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sun, 22 Nov 2026 21:21:42 +1100 Subject: [PATCH 1455/1514] arm64: dts: apple: t6050: expose the K boards' jack pins with the PCIe PERST# pin The K board headphone jack change opens pins 134 and 139 (the CS42L84's interrupt and reset) in the shared K114/K116 pinctrl_ap list, and this branch opens pin 80 for PCIe port 0. Use the union, <0 80>, <81 53>, <135 4>, <140 81>, in both so they land in either order. Both pins read cleanly; only pin 112 takes an SError. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index a1fa5068268c5f..a37a1aa19ce0b2 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -121,11 +121,11 @@ /* * As on J716c, where reading pin 112 takes an SError, only the pins a node - * names are exposed: here 80, PCIe port 0's PERST#. A board that names more - * pins replaces the list. + * names are exposed: 80, PCIe port 0's PERST#, and 134 and 139, the jack + * codec's interrupt and reset. A board that names more pins replaces the list. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 140>; + gpio-reserved-ranges = <0 80>, <81 53>, <135 4>, <140 81>; }; /* From 2fc7c2147b28341d03886267d3abb4cce054fdef Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 21:23:14 -0500 Subject: [PATCH 1456/1514] drm/asahi: g16: accept 48 KiB tile buffers on the M4 macOS 26B123 runs MSAA4 render passes on the M4 (G16G) with 48 KiB tiles: 32x16 utiles of up to 24 bytes per sample. The g16 backend refused any tile buffer over 32 KiB, so Mesa has to fall back to 16x16 utiles for the same passes, which doubles the tile count of a 1080p MSAA4 pass. Keep the limit per chip in the g16 configuration: 48 KiB for T8132, 32 KiB for the M3 family (T6030, T8122) until each is shown to work there. Report the higher limit as DRM_ASAHI_FEATURE_TILE_BUFFER_48K, bit 46, so that userspace sizes tiles from what the kernel accepts. The g15, g17 and g18 backends do not report the bit. The 48 KiB value is the one macOS programs on this GPU; the hardware may accept more, but this backend does not claim it. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/file.rs | 3 ++ drivers/gpu/drm/asahi/g16/command.rs | 5 ++- drivers/gpu/drm/asahi/g16/hw.rs | 11 ++++++ drivers/gpu/drm/asahi/g16/params.rs | 5 +++ drivers/gpu/drm/asahi/g16/queue.rs | 1 + include/uapi/drm/asahi_drm.h | 8 ++++ .../gpu/asahi-m4/test-command-stream.py | 37 +++++++++++++++---- 7 files changed, 61 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index fc2d2dd6cedaff..bd4554611267da 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -94,6 +94,9 @@ pub(crate) const DRM_ASAHI_RENDER_SHADER_WRITES: u32 = /// (DRM_ASAHI_RENDER_STAGE_PREFIXES), as the complete struct drm_asahi_cmd_render_m5. pub(crate) const DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2: u64 = uapi::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2 as u64; +/// Render commands accept tile buffers of up to 48 KiB. +pub(crate) const DRM_ASAHI_FEATURE_TILE_BUFFER_48K: u64 = + uapi::DRM_ASAHI_FEATURE_TILE_BUFFER_48K as u64; /// Compute commands may declare a stream that ends with a memory-scoped flush /// (DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION). pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_VISIBLE_COMPLETION: u64 = diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 197d31e93fa0f6..e499231e06084a 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -74,7 +74,6 @@ const SET_COMPUTE_ATTACHMENTS: u32 = uapi::drm_asahi_cmd_type_DRM_ASAHI_SET_COMP const MAX_DIMENSION: u16 = 16384; const MAX_LAYERS: u16 = 2048; -const MAX_TILE_BUFFER: u32 = 32768; const ZLS_METADATA_STRIDE: u64 = 0x80; /// Size of a queue's USC window. pub(crate) const USC_WINDOW: u64 = 1 << 32; @@ -373,6 +372,8 @@ pub(crate) struct Context<'a> { pub(crate) active_cores: u32, /// The queue's reserved render scratch pages per stage (`render_scs_layout`). pub(crate) render_scs: [u16; 2], + /// Largest tile buffer render commands may use, in bytes (`Config::max_tile_buffer`). + pub(crate) max_tile_buffer: u32, } /// A stream whose timestamps and ordinals are resolved ([`ParsedStream::prepare`]), before its @@ -1277,7 +1278,7 @@ fn check_render_for( || !matches!(cmd.samples, 1 | 2 | 4) || !matches!(cmd.utile_width_px, 16 | 32) || !matches!(cmd.utile_height_px, 16 | 32) - || tile_buffer > MAX_TILE_BUFFER + || tile_buffer > context.max_tile_buffer || cmd.sampler_heap != 0 || cmd.sampler_count != 0 || cmd.ppp_ctrl & !0x203 != 0 diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 4026072bde1eef..2ea74d873e1276 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -92,6 +92,10 @@ pub(crate) struct Config { pub(crate) supports_render_scs: bool, /// Whether FS->compute cross-engine barriers require `BarrierType::Hold` (type 1), as on G15. pub(crate) cross_engine_hold: bool, + /// Largest tile buffer a render command may use, in bytes per tile (sample size times + /// utile width, utile height and samples). Reported as DRM_ASAHI_FEATURE_TILE_BUFFER_48K + /// when it reaches [`sizes::TILE_BUFFER_48K`]. + pub(crate) max_tile_buffer: u32, } impl Config { @@ -242,6 +246,8 @@ pub(crate) mod t8132 { deep_sleep: true, supports_render_scs: true, cross_engine_hold: false, + // macOS 26B123 programs 48 KiB tiles (MSAA4, 32x16 utiles) on this GPU. + max_tile_buffer: super::sizes::TILE_BUFFER_48K, }; /// What iBoot writes into the 25G83 build b000 TEXT it loads, in TEXT order: @@ -401,6 +407,7 @@ pub(crate) mod t6030 { deep_sleep: false, supports_render_scs: false, cross_engine_hold: true, + max_tile_buffer: super::sizes::TILE_BUFFER_32K, }; const LAYOUT: FwLayout = FwLayout { @@ -541,6 +548,7 @@ pub(crate) mod t8122 { deep_sleep: false, supports_render_scs: false, cross_engine_hold: true, + max_tile_buffer: super::sizes::TILE_BUFFER_32K, }; /// 26B123 G15G: __TEXT 0x64000 as on G16G, __DATA 0xb4000 and the 0x8000 __DATA_SHARED_RO @@ -1101,6 +1109,9 @@ pub(crate) mod client { /// Sizes and counts of the engine's objects. pub(crate) mod sizes { + /// Tile buffer limits of [`super::Config::max_tile_buffer`]. + pub(crate) const TILE_BUFFER_32K: u32 = 32 * 1024; + pub(crate) const TILE_BUFFER_48K: u32 = 48 * 1024; pub(crate) const POOLS: usize = 16; pub(crate) const POOL_SIZE: u64 = 0x200000; pub(crate) const FREELIST_SEED: u32 = 8192; diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 869ab8bd1daa68..1aef70eae06d72 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -102,6 +102,11 @@ pub(crate) fn fill(gpu: &Gpu, params: &mut uapi::drm_asahi_params_global) -> Res } else { 0 } + | if gpu.cfg.max_tile_buffer >= hw::sizes::TILE_BUFFER_48K { + crate::file::DRM_ASAHI_FEATURE_TILE_BUFFER_48K + } else { + 0 + } | crate::g17::sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES_V2; params.gpu_generation = gpu.cfg.gpu_generation; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 7fadc1a3af5d74..98381912f9eab8 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -288,6 +288,7 @@ impl Queue { usc_base: self.state.usc_base, active_cores: self.active_cores, render_scs: self.render_scs, + max_tile_buffer: self.cfg.max_tile_buffer, }, &mut self.proof, )?; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index dd79dfb569bdc1..f1fee4537e2b9c 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -605,6 +605,14 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS ((1ULL) << 45) +/* + * DRM_ASAHI_FEATURE_TILE_BUFFER_48K: render commands accept tile buffers of + * up to 48 KiB (sample_size_B * utile_width_px * utile_height_px * samples + * <= 49152), instead of 32 KiB. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_TILE_BUFFER_48K ((1ULL) << 46) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 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 f1684b41225573..057ac60cd5097e 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 @@ -633,7 +633,7 @@ mod render_admission_tests { use super::{ check_render_helpers, hw, uapi, Result, DBIAS_IS_INT, EINVAL, FEW_PRIMITIVES, - FRAGMENT_BARRIERS, MAX_DIMENSION, MAX_LAYERS, MAX_TILE_BUFFER, PROCESS_EMPTY_TILES, + FRAGMENT_BARRIERS, MAX_DIMENSION, MAX_LAYERS, PROCESS_EMPTY_TILES, RSRC_SPEC_HI, STAGE_PREFIXES, ZLS_METADATA_STRIDE, }; const ENOENT: i32 = -2; @@ -700,6 +700,7 @@ pub(crate) usc_base: u64, pub(crate) active_cores: u32, pub(crate) render_scs: [u16; 2], + pub(crate) max_tile_buffer: u32, } use super::MAX_COMMANDS; RENDER_ADMISSION @@ -749,7 +750,7 @@ #[test] fn compressed_zls_1x_layered_and_2x_accepted() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; // 1x compressed D32F depth + stencil. let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -779,10 +780,32 @@ assert_eq!(check_render_one(&ctx, &layered, &[], &[]), Ok(())); } + #[test] + fn tile_buffer_limit_follows_the_context() { + let vm = base_vm(); + let k32 = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; + let k48 = Context { max_tile_buffer: 48 * 1024, ..k32 }; + // 8 B x 32x32 x 4 samples = 32 KiB: accepted by both. + let mut k32_tile = base_cmd(); + k32_tile.samples = 4; + assert_eq!(check_render_one(&k32, &k32_tile, &[], &[]), Ok(())); + assert_eq!(check_render_one(&k48, &k32_tile, &[], &[]), Ok(())); + // 24 B x 32x16 x 4 samples = 48 KiB, the MSAA4 tile macOS programs on the M4. + let mut k48_tile = k32_tile; + k48_tile.utile_height_px = 16; + k48_tile.sample_size_B = 24; + assert_eq!(check_render_one(&k32, &k48_tile, &[], &[]), Err(EINVAL)); + assert_eq!(check_render_one(&k48, &k48_tile, &[], &[]), Ok(())); + // 28 B x 32x16 x 4 samples = 56 KiB: over both limits. + let mut over = k48_tile; + over.sample_size_B = 28; + assert_eq!(check_render_one(&k48, &over, &[], &[]), Err(EINVAL)); + } + #[test] fn compressed_zls_invalid_ctrl_alignment_and_vm_spans_rejected() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; let valid = || { let mut cmd = base_cmd(); cmd.zls_ctrl = Z_COMP | S_COMP; @@ -839,7 +862,7 @@ #[test] fn submit_wide_span_batch_dedups_and_flushes_once_across_passes() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; let mut batch = SpanBatch::new(); for pass in 0..4u64 { let mut cmd = base_cmd(); @@ -879,7 +902,7 @@ #[test] fn few_primitives_flag_admitted_in_parse_and_render_check() { let vm = base_vm(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; let mut r = super::render(); r.flags = FEW_PRIMITIVES; assert!(super::check_stream( @@ -916,7 +939,7 @@ // First flush populates the proof for epoch 1. let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; check_render(&mut batch, &ctx, &cmd, &[], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Ok(())); assert_eq!(vm.batch_calls.get(), 1); @@ -962,7 +985,7 @@ vm.maps.remove(1); vm.epoch.set(Some(2)); let mut batch = SpanBatch::new(); - let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0] }; + let ctx = Context { vm: &vm, usc_base: 1 << 40, active_cores: 10, render_scs: [0, 0], max_tile_buffer: 32 * 1024 }; check_render(&mut batch, &ctx, &cmd, &[att], &[]).unwrap(); assert_eq!(batch.flush_with_proof(&vm, &mut proof), Err(ENOENT)); From 7403c74453ea9d9009166e8c30c5ac6c11040102 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 13:37:22 +1100 Subject: [PATCH 1457/1514] arm64: dts: apple: t6050: share the K boards' GPU, add it to K114s and K116c The K114s and K116c keep the inventory GPU node of t6050-peripherals.dtsi, compatible "apple,agx-t6050". The boot loader's GPU hand-off looks for "apple,agx-g17s" under the "gpu" alias and drm/asahi does not bind the inventory node, so on a K114s the GPU is never enabled and there is no render node. The K114c and K116s each carry the same G17S description in their own file (t6050-k114c-gpu.dtsi, t6050-k116s-gpu.dtsi). The four boards' ADTs (live K114s 27.2, the K114c, K116s and K116c images) have the same GPU: - sgx: "gpu,t6050", reg 0x21_00000000 + 0x3fdc000 and 0x21_00d00000 + 0x177000, interrupts 2448-2451, 450, 2806, 2463, 2465; - gfx-asc: reg 0x21_02600000 + 0x88000, 0x21_02050000 + 8, interrupts [2798, 2797, 2800, 2799], role GFX, power-gates 614; - gfx1-asc: reg 0x21_02e00000 + 0x88000, 0x21_02850000 + 0x60000, interrupts [2802, 2801, 2804, 2803], role GFX1, power-gates 657; - pmgr GPX (+0x0) and AFR (+0x100) critical, GFX (+0x110) not. On the K114s the GPU ASCs' __TEXT (0x50000 + 0x54000) and fw-data bounds are the K116s's, which the loader checks against its builds. So move the description into t6050-k114-k116-gpu.dtsi and include it from all four boards. It also carries the K114c's apple,sleep-retained on ps_gfx: the G17 firmware stays live across suspend-to-idle on every one of these boards. The K116s keeps only its delta, the GPU on the PMP's GFX report entry, as its board runs the PMP. Everything stays disabled until the loader fills the reservations and enables it, as before. The K114c DTB and the other T6050 DTBs are byte-identical before and after; the K116s DTB gains only apple,sleep-retained on ps_gfx, which its sleep description already keeps always-on. Signed-off-by: Ryan Murray --- ...114c-gpu.dtsi => t6050-k114-k116-gpu.dtsi} | 40 +++-- arch/arm64/boot/dts/apple/t6050-k114c.dts | 3 +- arch/arm64/boot/dts/apple/t6050-k114s.dts | 3 + arch/arm64/boot/dts/apple/t6050-k116c.dts | 3 + .../arm64/boot/dts/apple/t6050-k116s-gpu.dtsi | 155 ------------------ arch/arm64/boot/dts/apple/t6050-k116s.dts | 11 +- 6 files changed, 46 insertions(+), 169 deletions(-) rename arch/arm64/boot/dts/apple/{t6050-k114c-gpu.dtsi => t6050-k114-k116-gpu.dtsi} (58%) delete mode 100644 arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi similarity index 58% rename from arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi rename to arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi index ceec5b22d2ae7f..92708423790865 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c-gpu.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-gpu.dtsi @@ -1,12 +1,14 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT /* - * K114c (M5 Max, G17C) GPU, for the boot loader's GPU handoff. Everything here - * stays disabled: the loader checks the ADT and the live GPU firmware build, - * fills the GPU reservations, then enables the power states, both mailboxes and - * the GPU, the GPU last. A loader that refuses leaves the GPU off. + * The GPU of the K114c, K114s, K116s and K116c (ADT /arm-io/sgx "gpu,t6050"), for the boot + * loader's GPU hand-off. It is the GPU half of t6050-j714s-gpu-panel.dtsi: the four boards' + * ADTs have the J714s's sgx, gfx-asc and gfx1-asc. * - * Same layout as t6050-j714s-gpu-panel.dtsi; the GPU is G17C and, in the ADT, - * sgx and both GPU ASCs are the same as on the M5 Pro. + * Everything here stays disabled: the loader checks the ADT and the live GPU firmware build, + * fills the six reservations, then enables the GPU PMGR, GPX, AFR, GFX, both mailboxes and the + * GPU, the GPU last. A loader that refuses leaves the GPU off and the rest of the boot as it is. + * + * arm-io's ranges add 0x2_0000_0000 to the ADT's 0x21_xxxx_xxxx bus addresses. */ / { @@ -16,7 +18,12 @@ }; reserved-memory { - /* Filled and enabled by the loader from the ADT */ + /* + * Filled and enabled by the loader from the ADT: sgx gpu-region-*, + * gfx-shared-region-*, gfx-shared-l2-region-* and gfx-handoff-* (the UAT + * ranges), the GPU ASCs' __TEXT (fw-text) and gfx-data-base to the end of + * gfx1-data-shared-ro (fw-data). iBoot places them; they differ per Mac. + */ gpu_fw_text: gpu-fw-text { reg = <0 0 0 0>; no-map; @@ -61,9 +68,9 @@ &{/soc} { /* - * ADT gfx-asc and gfx1-asc at their physical windows: the wrapper, the - * 8-byte iop-vbar, and their second and third interrupts (send-empty, - * recv-not-empty), as T8140/T8142. + * ADT gfx-asc: reg 0x21_02600000 + 0x88000 (wrapper), 0x21_02050000 + 8 (iop-vbar); + * interrupts [2798, 2797, 2800, 2799], of which the second and third are send-empty + * and recv-not-empty; role "GFX"; power-gates [614] (GFX_ASC). */ gfx_mbox: mailbox@2302600000 { compatible = "apple,t6050-j775d-ascwrap-v6"; @@ -79,6 +86,11 @@ status = "disabled"; }; + /* + * ADT gfx1-asc: reg 0x21_02e00000 + 0x88000, 0x21_02850000 (ADT size 0x60000; the + * driver uses the first 8 bytes); interrupts [2802, 2801, 2804, 2803]; role "GFX1"; + * power-gates [657] (GFX_ASC1). + */ gfx1_mbox: mailbox@2302e00000 { compatible = "apple,t6050-j775d-ascwrap-v6"; reg = <0x23 0x2e00000 0x0 0x88000>, @@ -94,7 +106,10 @@ }; }; -/* The ADT marks GPX and AFR, GFX's parents, critical. */ +/* + * ADT pmgr devices GPX (id 359, +0x0), AFR (id 360, +0x100) and GFX (id 362, +0x110) in the + * GPU PMGR. The ADT marks GPX and AFR, GFX's parents, critical; GFX not. + */ &ps_gpx { apple,always-on; }; @@ -112,8 +127,9 @@ }; &sgx { + /* What the loader checks and drivers/gpu/drm/asahi binds */ compatible = "apple,agx-g17s"; - /* ADT sgx reg[0]; the driver maps the first 16 MiB as "sgx" */ + /* ADT sgx reg[0] 0x21_00000000 + 0x3fdc000; the driver maps the first 16 MiB as "sgx" */ reg = <0x23 0x0 0x0 0x3fdc000>; reg-names = "sgx"; /delete-property/ interrupts; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 8a15f89849ca8c..086c2dd3244b7a 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -70,7 +70,8 @@ gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; }; -#include "t6050-k114c-gpu.dtsi" +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" /* * Sound through the AOP, as on J813: its audio service runs the serializers, the diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 409979f034678e..c92c961141aaa7 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -27,6 +27,9 @@ #define T6050_K114S #include "t6050-peripherals.dtsi" +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" + / { aliases { /* asahi-bless and the boot loader find the NVRAM partition by this alias */ diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index a270ed24ba3c7a..40bfec8ab72a85 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -26,5 +26,8 @@ #define T6050_K116C #include "t6050-peripherals.dtsi" +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" + /* The USB-C ports ATC1 and ATC2, as on the other K boards */ #include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi b/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi deleted file mode 100644 index 7bc349759028da..00000000000000 --- a/arch/arm64/boot/dts/apple/t6050-k116s-gpu.dtsi +++ /dev/null @@ -1,155 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* - * K116s GPU (AGX G17S, ADT /arm-io/sgx "gpu,t6050") for the boot loader hand-off. - * - * It is the GPU half of t6050-j714s-gpu-panel.dtsi (integration/aurora 06c3db9c3752); the - * K116s tree already has its own display half. Everything stays disabled: a loader with the - * G17S hand-off fills the six reservations from the ADT and enables the GPU PMGR, GPX, AFR, - * GFX, both mailboxes and the GPU, the GPU last. Without such a loader (the enrolled aura - * 58d65df0 has none for this layout) this file changes nothing at run time except the two - * always-on marks, which sit on disabled nodes. - * - * Every value below was checked against the K116s 27.2 ADT. arm-io ranges add 0x2_0000_0000 - * to the 0x21_xxxx_xxxx bus addresses (bus 0x20_2000_0000 -> parent 0x22_2000_0000). - */ - -/ { - aliases { - /* The loader finds the GPU through this alias */ - gpu = &sgx; - }; - - reserved-memory { - /* - * Filled and enabled by the loader from the ADT. K116s 27.2 values, for - * reference only (never hard-code: iBoot places them): - * gpu-fw-text 0x100_00ff8000 + 0xa4000 gfx-asc __TEXT 0x50000, then - * gfx1-asc __TEXT 0x54000 at - * 0x100_01048000 - * gpu-fw-data 0x100_0251c000 + 0x184000 sgx gfx-data-base .. end of - * gfx1-data-shared-ro - * uat-ttbs 0x10f_fffa8000 + 0x4000 sgx gpu-region-base/-size - * uat-pagetables 0x10f_fff28000 + 0x80000 sgx gfx-shared-region-* - * uat-l2-pagetables 0x10f_fff24000 + 0x4000 sgx gfx-shared-l2-region-* - * uat-handoff 0x10f_fff20000 + 0x4000 sgx gfx-handoff-* - * The four UAT ranges are the J714s's (aura ec204ea50b5d message); the firmware - * segments differ (J714s 27.0: fw-text 0x100_00fd4000, fw-data 0x100_024f4000). - */ - gpu_fw_text: gpu-fw-text { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - gpu_fw_data: gpu-fw-data { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_ttbs: uat-ttbs { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_pagetables: uat-pagetables { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_l2_pagetables: uat-l2-pagetables { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - - uat_handoff: uat-handoff { - reg = <0 0 0 0>; - no-map; - status = "disabled"; - }; - }; -}; - -/* The inventory ASC nodes; the mailboxes below describe the same windows. */ -/delete-node/ &gfx_asc; -/delete-node/ &gfx1_asc; - -&{/soc} { - /* - * ADT gfx-asc: reg 0x21_02600000 + 0x88000 (wrapper), 0x21_02050000 + 8 (iop-vbar); - * interrupts [2798, 2797, 2800, 2799], of which the second and third are send-empty - * and recv-not-empty; role "GFX"; power-gates [614] = GFX_ASC. As J714s. - */ - gfx_mbox: mailbox@2302600000 { - compatible = "apple,t6050-j775d-ascwrap-v6"; - reg = <0x23 0x2600000 0x0 0x88000>, - <0x23 0x2050000 0x0 0x8>; - reg-names = "wrapper", "iop-vbar"; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - apple,firmware-role = "GFX"; - power-domains = <&ps_gfx>; - #mbox-cells = <0>; - status = "disabled"; - }; - - /* - * ADT gfx1-asc: reg 0x21_02e00000 + 0x88000, 0x21_02850000 (ADT size 0x60000; the - * driver uses the first 8 bytes as on J714s); interrupts [2802, 2801, 2804, 2803]; - * role "GFX1"; power-gates [657] = GFX_ASC1. - */ - gfx1_mbox: mailbox@2302e00000 { - compatible = "apple,t6050-j775d-ascwrap-v6"; - reg = <0x23 0x2e00000 0x0 0x88000>, - <0x23 0x2850000 0x0 0x8>; - reg-names = "wrapper", "iop-vbar"; - interrupts = , - ; - interrupt-names = "send-empty", "recv-not-empty"; - apple,firmware-role = "GFX1"; - power-domains = <&ps_gfx>; - #mbox-cells = <0>; - status = "disabled"; - }; -}; - -/* - * ADT pmgr devices: GPX (id 359, reg +0x0), AFR (id 360, +0x100) and GFX (id 362, +0x110) - * in the GPU PMGR (pmgr reg[51] 0x21_00e80000). The K116s ADT marks GPX and AFR critical, - * GFX not, as the J714s file states for its board. - */ -&ps_gpx { - apple,always-on; -}; - -&ps_afr { - apple,always-on; -}; - -&sgx { - /* - * "apple,agx-g17s" is what the loader checks and the driver binds - * (drivers/gpu/drm/asahi/driver.rs). The driver uses the J714 tables for it, - * 5 mV below this unit's ADT voltages at eight of the fourteen states. - */ - compatible = "apple,agx-g17s"; - /* ADT sgx reg[0] 0x21_00000000 + 0x3fdc000; the driver maps the first 16 MiB as "sgx" */ - reg = <0x23 0x0 0x0 0x3fdc000>; - reg-names = "sgx"; - /delete-property/ interrupts; - mboxes = <&gfx_mbox>, <&gfx1_mbox>; - memory-region = <&uat_ttbs>, <&uat_pagetables>, <&uat_handoff>, - <&gpu_fw_data>, <&uat_l2_pagetables>, <&gpu_fw_text>; - memory-region-names = "ttbs", "pagetables", "handoff", "fw-data", - "l2-pagetables", "fw-text"; - /* - * As t6050-j714s.dts: the GPU on the PMP's GFX report entry (report@f, on ps_gfx), - * so the PMP is told the GPU is on only while it is powered. The K116s already - * runs the PMP with its report (t6050-k116s.dts &pmp0_report). - */ - power-domains = <&pmp0_gfx>; -}; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index c6b1adc3ede00d..26f4bce4362dbc 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -608,7 +608,16 @@ dma-names = "cout", "cin", "spkr", "sense", "hpai"; }; /* The GPU, handed over by the boot loader */ -#include "t6050-k116s-gpu.dtsi" +#include "t6050-k114-k116-gpu.dtsi" + +/* + * As t6050-j714s.dts: the GPU on the PMP's GFX report entry (report@f, on ps_gfx), so the PMP + * is told the GPU is on only while it is powered. This board runs the PMP with its report + * (&pmp0_report above). + */ +&sgx { + power-domains = <&pmp0_gfx>; +}; /* * The camera: the T6050 ISP as J716c and J714s describe it. From the K116sAP ADT (27.2): From 76a6f4c47ef539838c02f4e1ebb7fb18903f04e9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 13:41:14 +1100 Subject: [PATCH 1458/1514] arm64: dts: apple: t6050: share the 14-inch K boards' jack, card and AOP, add them to K114s The K114s has no internal audio card and no AOP: its DT leaves the jack codec, the sound card, the AOP and the microphone's ADMAC disabled. The K114c describes all of them in its own file, with its speakers. The live K114s ADT (27.2) describes the K114c's audio hardware node for node: - i2c2 audio-codec-output at 0x4b, audio-control,cs42l84, reset GPIO 0x8b (pin 139), interrupts [134, 1]; - i2c1/i2c3 audio-speaker* at 0x38-0x3d, six audio-control,sn012776, function-speaker-id0/1 GPIO 0x88/0x89 (pins 136/137), the shutdown line GPIO 0x6b (pin 107) and fault interrupt 106; - aop (reg 0x90600000, 0x90c00000), aop-exclave-mailbox 0x2d067c000 interrupts [585, 582], dart-aop 0x90fc0000 interrupt 616, admac-base-ns 0x93800000 interrupt 637 with 13 + 13 channels, admac-hp-mic-ec-proxy 0x2d3200000 dma-channel 0 and audio-hp-mic. The K114c and K114s static ADTs differ in none of these beyond phandles. So move the K114c's pin list, jack codec, sound card with its jack link, AOP and microphone ADMAC into t6050-k114.dtsi, the 14-inch chassis, and include it from both boards. The shared card is "apple,k114-macaudio", the K114 entry, which runs the jack only. The speakers stay with the K114c: its six SN012776 amps, their shutdown regulator and the "Speaker" link remain in t6050-k114c.dts, which also keeps its "apple,j714-macaudio" card. On the K114s the amps are not described and i2c1 and i2c3 stay disabled: speakerguardd refuses this board (its protection is not qualified), so its speakers stay off. The K114c DTB and the other T6050 DTBs are byte-identical before and after. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114.dtsi | 107 +++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 150 +++++----------------- arch/arm64/boot/dts/apple/t6050-k114s.dts | 3 + 3 files changed, 145 insertions(+), 115 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-k114.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k114.dtsi b/arch/arm64/boot/dts/apple/t6050-k114.dtsi new file mode 100644 index 00000000000000..77dbf809bc7d0a --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114.dtsi @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The 14-inch K boards' chassis (K114c, M5 Max, and K114s, M5 Pro): what their ADTs describe + * alike beyond what t6050-k114-k116.dtsi shares with the 16-inch boards. The live K114s ADT + * (27.2) and the K114c's have the same nodes and values here, phandles aside. + * + * The speaker amps are left to the board: they need a qualified speaker protection, which + * the K114s does not have. + * + * Included after t6050-peripherals.dtsi. + */ + +/* + * Pin 112's register takes an SError when read, so only the pins a node names are + * exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' interrupt and + * shutdown line (ADT audio-speaker, used only where a board describes the amps); + * 134 and 139, the jack codec's interrupt and reset; 136 and 137, the speaker ID. + */ +&pinctrl_ap { + gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; +}; + +/* + * The CS42L84 headphone codec (ADT /arm-io/i2c2/audio-codec-output): its reset line + * is AP pin 139, driven high to run the codec, and its interrupt AP pin 134, level + * low. + */ +&i2c2 { + status = "okay"; + + jack_codec: codec@4b { + compatible = "cirrus,cs42l84"; + reg = <0x4b>; + reset-gpios = <&pinctrl_ap 139 GPIO_ACTIVE_HIGH>; + interrupts-extended = <&pinctrl_ap 134 IRQ_TYPE_LEVEL_LOW>; + #sound-dai-cells = <0>; + sound-name-prefix = "Jack"; + }; +}; + +/ { + sound { + /* + * The headphone jack only. The speaker amps and the "Speaker" link are not + * described here: no speaker protection is qualified for this chassis + * (speakerguardd refuses it), and the K114 entry has the speakers off. + */ + compatible = "apple,k114-macaudio", "apple,macaudio"; + model = "MacBook Pro K114"; + /* ADT audio-speaker function-speaker-id0 and -id1 */ + speaker-id-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_HIGH>, + <&pinctrl_ap 137 GPIO_ACTIVE_HIGH>; + #address-cells = <1>; + #size-cells = <0>; + + dai-link@0 { + reg = <0>; + link-name = "Headphone Jack"; + + cpu { + sound-dai = <&aop_audio 0>; + }; + + codec { + sound-dai = <&jack_codec>; + }; + }; + }; +}; + +/* The AOP, booted through its setup port, with its sensor and audio services. */ +&aop_mbox { + status = "okay"; +}; + +&aop_setup_mbox { + status = "okay"; +}; + +&aop_dart { + status = "okay"; +}; + +&aop { + status = "okay"; +}; + +/* + * The microphone array: ADT audio-hp-mic, three microphones on leap-s RX0 through the + * proxy ADMAC (Linux channel 1, as on J813), captured by the AOP audio service's own card. + */ +&admac_base_ns { + status = "okay"; +}; + +&admac_ec_proxy { + status = "okay"; +}; + +&aop_audio { + apple,chassis-name = "K114"; + apple,machine-kind = "MacBook Pro"; + dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, + <&admac_base_ns 0>, <&admac_base_ns 1>, + <&admac_ec_proxy 1>; + dma-names = "cout", "cin", "spkr", "sense", "hpai"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 086c2dd3244b7a..132b29f08749d6 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -61,22 +61,9 @@ }; /* - * Pin 112's register takes an SError when read, so only the pins a node here - * names are exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' - * interrupt and shutdown line; 134 and 139, the jack codec's interrupt and - * reset; 136 and 137, the speaker ID. - */ -&pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; -}; - -/* The GPU, handed over by the boot loader */ -#include "t6050-k114-k116-gpu.dtsi" - -/* - * Sound through the AOP, as on J813: its audio service runs the serializers, the - * CS42L84 headphone jack on admac-base-ns TX2/RX2 and the six SN012776 speaker amps - * on TX0, their voltage and current sense on RX0 (ADT iop-audio-controller). + * The speakers, through the AOP as on J813: the six SN012776 speaker amps on admac-base-ns + * TX0, their voltage and current sense on RX0 (ADT iop-audio-controller). The jack, the + * card and the AOP are the chassis' (t6050-k114.dtsi). * * The amps (ADT /arm-io/i2c1/audio-speaker* and /arm-io/i2c3/audio-speaker*) share * one shutdown line, AP pin 107 (function-reset of the first), and one fault @@ -189,113 +176,46 @@ }; }; -/* - * The CS42L84 headphone codec (ADT /arm-io/i2c2/audio-codec-output): its reset line - * is AP pin 139, driven high to run the codec, and its interrupt AP pin 134, level - * low. - */ -&i2c2 { - status = "okay"; +/* The 14-inch chassis: pins, the jack, the card and the AOP */ +#include "t6050-k114.dtsi" - jack_codec: codec@4b { - compatible = "cirrus,cs42l84"; - reg = <0x4b>; - reset-gpios = <&pinctrl_ap 139 GPIO_ACTIVE_HIGH>; - interrupts-extended = <&pinctrl_ap 134 IRQ_TYPE_LEVEL_LOW>; - #sound-dai-cells = <0>; - sound-name-prefix = "Jack"; - }; -}; - -/ { - sound { - compatible = "apple,j714-macaudio", "apple,macaudio"; - model = "MacBook Pro K114"; - /* ADT audio-speaker function-speaker-id0 and -id1 */ - speaker-id-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_HIGH>, - <&pinctrl_ap 137 GPIO_ACTIVE_HIGH>; - #address-cells = <1>; - #size-cells = <0>; - - dai-link@0 { - reg = <0>; - link-name = "Headphone Jack"; - - cpu { - sound-dai = <&aop_audio 0>; - }; +/* The GPU, handed over by the boot loader */ +#include "t6050-k114-k116-gpu.dtsi" - codec { - sound-dai = <&jack_codec>; - }; +/* + * The K114c keeps J714's card with its speakers, at the J714's safe level. The + * chassis' K114 entry (t6050-k114.dtsi) has the jack only. + */ +&{/sound} { + compatible = "apple,j714-macaudio", "apple,macaudio"; + + dai-link@1 { + reg = <1>; + link-name = "Speaker"; + /* + * Codecs in ADT speaker-config order, so that macaudio gives them + * playback slots 0-5 as macOS does (left channels in slots 0, 2 + * and 4, right in 1, 3 and 5). The idle masks are the ADT + * amp-tx-zd-config rows 0 and 1: left woofer 1 drives zeros in the + * right amps' sense slots, right woofer 1 in the left amps'. + */ + dai-tdm-idle-mode-0 = "zero"; + dai-tdm-slot-tx-idle-mask-0 = <0xfff0f0f0>; + dai-tdm-idle-mode-1 = "zero"; + dai-tdm-slot-tx-idle-mask-1 = <0xff0f0f0f>; + + cpu { + sound-dai = <&aop_audio 3>; }; - dai-link@1 { - reg = <1>; - link-name = "Speaker"; - /* - * Codecs in ADT speaker-config order, so that macaudio gives them - * playback slots 0-5 as macOS does (left channels in slots 0, 2 - * and 4, right in 1, 3 and 5). The idle masks are the ADT - * amp-tx-zd-config rows 0 and 1: left woofer 1 drives zeros in the - * right amps' sense slots, right woofer 1 in the left amps'. - */ - dai-tdm-idle-mode-0 = "zero"; - dai-tdm-slot-tx-idle-mask-0 = <0xfff0f0f0>; - dai-tdm-idle-mode-1 = "zero"; - dai-tdm-slot-tx-idle-mask-1 = <0xff0f0f0f>; - - cpu { - sound-dai = <&aop_audio 3>; - }; - - codec { - sound-dai = <&speaker_left_woof1>, <&speaker_right_woof1>, - <&speaker_left_woof2>, <&speaker_right_woof2>, - <&speaker_left_tweet>, <&speaker_right_tweet>; - }; + codec { + sound-dai = <&speaker_left_woof1>, <&speaker_right_woof1>, + <&speaker_left_woof2>, <&speaker_right_woof2>, + <&speaker_left_tweet>, <&speaker_right_tweet>; }; }; }; -/* The AOP, booted through its setup port, with its sensor and audio services. */ -&aop_mbox { - status = "okay"; -}; - -&aop_setup_mbox { - status = "okay"; -}; - -&aop_dart { - status = "okay"; -}; - -&aop { - status = "okay"; -}; - -/* - * The microphone array: ADT audio-hp-mic, three microphones on leap-s RX0 through the - * proxy ADMAC (Linux channel 1, as on J813), captured by the AOP audio service's own card. - */ -&admac_base_ns { - status = "okay"; -}; - -&admac_ec_proxy { - status = "okay"; -}; - -&aop_audio { - apple,chassis-name = "K114"; - apple,machine-kind = "MacBook Pro"; - dmas = <&admac_base_ns 4>, <&admac_base_ns 5>, - <&admac_base_ns 0>, <&admac_base_ns 1>, - <&admac_ec_proxy 1>; - dma-names = "cout", "cin", "spkr", "sense", "hpai"; -}; - /* * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi). This * board also gives nub-spmi-a0 its generation 4 fault queue (reg[1], which macOS empties when diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index c92c961141aaa7..b0e7cd937d5b82 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -27,6 +27,9 @@ #define T6050_K114S #include "t6050-peripherals.dtsi" +/* The 14-inch chassis: pins, the jack, the card and the AOP; no speakers */ +#include "t6050-k114.dtsi" + /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" From ec261e91ad6102b0bcb656f5a158a507ccfc86f9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 13:52:54 +1100 Subject: [PATCH 1459/1514] arm64: dts: apple: t6050: share the 14-inch K boards' Neural Engine, add it to K114s The K114s has no Neural Engine: ane0, its three DARTs and ANE_SYS stay disabled. The K114c enables them with t6050-j714s-ane.dtsi and the fabric domains ANE_SYS depends on, in its own file. The live K114s ADT has the K114c's and J714s's engine: ane0 "ane,t8132exclave" at 0x3_08000000 + 0x2000000 with the ANE PMGR window 0x80900000 + 0x18000, interrupts [954, 967], pre-loaded = 1 (iBoot loads the personalized firmware), and dart-ane0 at 0x3_09800000, 0x3_09820000 and 0x3_09840000 (0xc000 each) with its DAPF at 0x3_09810000, interrupt 955. These are the inventory nodes of t6050-peripherals.dtsi. So move the K114c's ANE include and its fab0_piogw, fab8_soc and fab9_soc enables into t6050-k114.dtsi. As on the K114c, the engine stays off until the boot loader has filled its two firmware reservations from the ADT. The K114c DTB and the other T6050 DTBs are byte-identical before and after. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114.dtsi | 30 +++++++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 29 +--------------------- arch/arm64/boot/dts/apple/t6050-k114s.dts | 2 +- 3 files changed, 32 insertions(+), 29 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114.dtsi b/arch/arm64/boot/dts/apple/t6050-k114.dtsi index 77dbf809bc7d0a..a895eebe32f030 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114.dtsi @@ -10,6 +10,36 @@ * Included after t6050-peripherals.dtsi. */ +/* + * The Neural Engine (ADT ane0, "ane,t8132exclave", firmware pre-loaded by iBoot), started only + * after the boot loader's preload hand-off + */ +#include "t6050-j714s-ane.dtsi" + +/* + * ANE_SYS's declared suppliers are the fabric domains: enabled the way + * the J714s enables them (t6050-j714s.dts for fab8/fab0, + * t6050-j716c-isp.dtsi for fab9). Left disabled they never register a + * provider and the enabled ps_ane_sys defers forever, taking ane0 and its + * three DARTs with it. + */ +&ps_fab0_piogw { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab8_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab9_soc { + /delete-property/ power-domains; + apple,no-auto-pm; + apple,firmware-owned; + status = "okay"; +}; + /* * Pin 112's register takes an SError when read, so only the pins a node names are * exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' interrupt and diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 132b29f08749d6..238e87f4f6f8ee 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -27,33 +27,6 @@ #include "t6050-peripherals.dtsi" -/* The Neural Engine, started only after the boot loader's preload hand-off */ -#include "t6050-j714s-ane.dtsi" - -/* - * ANE_SYS's declared suppliers are the fabric domains: enabled here the way - * the J714s enables them (t6050-j714s.dts for fab8/fab0, - * t6050-j716c-isp.dtsi for fab9). Left disabled they never register a - * provider and the enabled ps_ane_sys defers forever, taking ane0 and its - * three DARTs with it. - */ -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab9_soc { - /delete-property/ power-domains; - apple,no-auto-pm; - apple,firmware-owned; - status = "okay"; -}; - / { aliases { nvram = &nvram; @@ -176,7 +149,7 @@ }; }; -/* The 14-inch chassis: pins, the jack, the card and the AOP */ +/* The 14-inch chassis: the Neural Engine, pins, the jack, the card and the AOP */ #include "t6050-k114.dtsi" /* The GPU, handed over by the boot loader */ diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index b0e7cd937d5b82..9c1057d71cb7a6 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -27,7 +27,7 @@ #define T6050_K114S #include "t6050-peripherals.dtsi" -/* The 14-inch chassis: pins, the jack, the card and the AOP; no speakers */ +/* The 14-inch chassis: the Neural Engine, pins, the jack, the card and the AOP; no speakers */ #include "t6050-k114.dtsi" /* The GPU, handed over by the boot loader */ From a381dc4017e9993564dfeeeed440ac7cbb9c8ed8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 13:47:07 +1100 Subject: [PATCH 1460/1514] arm64: dts: apple: t6050: share the 14-inch K boards' MagSafe PD and USB4 router, add them to K114s The K114s describes neither its MagSafe 3 port's PD controller nor the right port's USB4/Thunderbolt router: the K114c has both in its own file, and t6050-max.dtsi and t6050-peripherals.dtsi describe the ATC2 router and its PCIe tunnel only for the boards they list. The live K114s ADT has the K114c's hardware here: - nub-spmi-a0: reg 0x8a188000, 0x8a184000 (the generation 4 fault queue) and 0x8a180000; hpm5 "usbc,sn201202x,spmi" at USID 8, port-type 17 (MagSafe), features-supported 3 (power in only); - acio2 "acio,v2" at 0x1_81f00000 (NHI), 0x1_81ac0000.. (rc and router blocks), interrupts 1655-1666, 1643-1654, 1672, gpio-lstx on AOP pin 0x51; dart-acio2 0x1_81a80000 interrupt 1670; acio-cpu2 0x1_81108000 and 0x1_81100000; - apciec2 "apciec,t6050" at 0x1c_70000000 with its root port blocks at 0x1_84020000.., interrupt 1469; dart-apciec2 0x1_84000000 interrupt 1470; - acio2 thunderbolt-drom identical to the K114c's (no UID). So move the K114c's nub-spmi-a0 fault queue window, hpm5, ATC2 router, DROM and router power states into t6050-k114-usb.dtsi, included after t6050-k114-k116-usb.dtsi by both boards. The K114s now defines T6050_K114S before its includes, as the K114c does, and the two board lists that guard the ATC2 router and its tunnel DART name it. The K114c DTB and the other T6050 DTBs are byte-identical before and after. The new K114s schema message (apple,t6050-pciec "port0") is the one the K114c and J714s already have for the same node. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi | 85 +++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 76 +---------------- arch/arm64/boot/dts/apple/t6050-k114s.dts | 10 ++- arch/arm64/boot/dts/apple/t6050-max.dtsi | 3 +- .../boot/dts/apple/t6050-peripherals.dtsi | 3 +- 5 files changed, 101 insertions(+), 76 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi new file mode 100644 index 00000000000000..24184a4e505ce3 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-usb.dtsi @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The 14-inch K boards' ports beyond t6050-k114-k116-usb.dtsi: the MagSafe 3 PD controller + * on nub-spmi-a0 and ATC2's USB4/Thunderbolt router with its PCIe tunnel. The live K114s ADT + * (27.2) and the K114c's have the same nodes and values here, phandles aside. + * + * Included after t6050-k114-k116-usb.dtsi. t6050-max.dtsi describes the ATC2 router for the + * boards that define T6050_K114C or T6050_K114S before including it. + */ + +/* + * nub-spmi-a0's generation 4 fault queue: ADT reg[1] 0x8a184000 + 0x4000, which macOS empties + * when the controller starts. + */ +&nub_spmi_a0 { + reg = <0x2 0x8a188000 0x0 0x4000>, + <0x2 0x8a184000 0x0 0x4000>; + + /* + * The MagSafe 3 port's PD controller (ADT hpm5, port-type 0x11). It has no USB data + * path, so it gets no connector node; tipd registers a Type-C port and a power supply + * for it. Its ADT features-supported is <3>, "Power In" only: no liquid detection. + */ + hpm5: usb-pd@8 { + compatible = "apple,sn201202x"; + reg = <0x8 SPMI_USID>; + apple,no-liquid-detection; + }; +}; + +/* + * The right port's USB4/Thunderbolt router (acio2) and PCIe tunnel; the DisplayPort route + * is not described. + */ +#include "t6050-max-atc2-router.dtsi" + +/* + * The host DROM from the ADT (/arm-io/acio2 thunderbolt-drom, the same on the K114c and the + * K114s); the boot loader replaces it + */ +&acio2_nhi { + apple,thunderbolt-drom = [fd 02 00 00 00 00 00 00 00 90 19 c3 8c 00 5c 00 + 00 00 00 00 00 00 08 81 82 02 82 00 00 00 08 82 + 92 01 82 00 00 00 03 83 20 08 84 00 00 00 00 00 + 00 08 85 00 00 00 00 00 00 05 86 09 01 00 08 87 + 00 00 00 00 00 00 05 88 09 01 00 05 89 09 01 00 + 05 8a 09 01 00 0e 01 41 70 70 6c 65 2c 20 49 6e + 63 2e 00 06 02 69 4f 53 00 00 00 00]; +}; + +/* The right router's suppliers, disabled in the inventory (as t6050-j714s-display.dtsi enables them) */ +&ps_atc2_cio { + status = "okay"; +}; + +&ps_atc2_cio_pcie { + status = "okay"; +}; + +&ps_atc2_cio_usb { + status = "okay"; +}; + +&ps_atc2_cio_auss { + status = "okay"; +}; + +&ps_atc2_pcie { + status = "okay"; +}; + +/* + * The router and its mailbox are on, with all five domains and the PCIe tunnel, whether or not + * t6050-max.dtsi leaves acio2 disabled and without the fifth domain for boards outside its list. + */ +&acio2_mbox { + status = "okay"; +}; + +&acio2 { + status = "okay"; + power-domains = <&ps_atc2_cio>, <&ps_atc2_cio_pcie>, + <&ps_atc2_cio_usb>, <&ps_atc2_cio_auss>, <&ps_atc2_pcie>; + apple,pcie-tunnel = <&acio2_pcie_tunnel>; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 238e87f4f6f8ee..495334da4a875f 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -190,80 +190,12 @@ }; /* - * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi). This - * board also gives nub-spmi-a0 its generation 4 fault queue (reg[1], which macOS empties when - * the controller starts) and describes the MagSafe 3 port's PD controller. + * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi), then the + * 14-inch chassis' MagSafe 3 PD controller and the right port's USB4/Thunderbolt router + * (t6050-k114-usb.dtsi). */ #include "t6050-k114-k116-usb.dtsi" - -&nub_spmi_a0 { - reg = <0x2 0x8a188000 0x0 0x4000>, - <0x2 0x8a184000 0x0 0x4000>; - - /* - * The MagSafe 3 port's PD controller (ADT hpm5, port-type 0x11). It has no USB data - * path, so it gets no connector node; tipd registers a Type-C port and a power supply - * for it. Its ADT features-supported is <3>, "Power In" only: no liquid detection. - */ - hpm5: usb-pd@8 { - compatible = "apple,sn201202x"; - reg = <0x8 SPMI_USID>; - apple,no-liquid-detection; - }; -}; - -/* - * The right port's USB4/Thunderbolt router (acio2) and PCIe tunnel; the DisplayPort route - * is not described. - */ -#include "t6050-max-atc2-router.dtsi" - -/* The host DROM from the K114cAP ADT (/arm-io/acio2 thunderbolt-drom); the boot loader replaces it */ -&acio2_nhi { - apple,thunderbolt-drom = [fd 02 00 00 00 00 00 00 00 90 19 c3 8c 00 5c 00 - 00 00 00 00 00 00 08 81 82 02 82 00 00 00 08 82 - 92 01 82 00 00 00 03 83 20 08 84 00 00 00 00 00 - 00 08 85 00 00 00 00 00 00 05 86 09 01 00 08 87 - 00 00 00 00 00 00 05 88 09 01 00 05 89 09 01 00 - 05 8a 09 01 00 0e 01 41 70 70 6c 65 2c 20 49 6e - 63 2e 00 06 02 69 4f 53 00 00 00 00]; -}; - -/* The right router's suppliers, disabled in the inventory (as t6050-j714s-display.dtsi enables them) */ -&ps_atc2_cio { - status = "okay"; -}; - -&ps_atc2_cio_pcie { - status = "okay"; -}; - -&ps_atc2_cio_usb { - status = "okay"; -}; - -&ps_atc2_cio_auss { - status = "okay"; -}; - -&ps_atc2_pcie { - status = "okay"; -}; - -/* - * The router and its mailbox are on, with all five domains and the PCIe tunnel, whether or not - * t6050-max.dtsi leaves acio2 disabled and without the fifth domain for boards outside its list. - */ -&acio2_mbox { - status = "okay"; -}; - -&acio2 { - status = "okay"; - power-domains = <&ps_atc2_cio>, <&ps_atc2_cio_pcie>, - <&ps_atc2_cio_usb>, <&ps_atc2_cio_auss>, <&ps_atc2_pcie>; - apple,pcie-tunnel = <&acio2_pcie_tunnel>; -}; +#include "t6050-k114-usb.dtsi" /* * The boot NOR. spi-nor reads the part's JEDEC ID itself. The partition is diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 9c1057d71cb7a6..417f6007e0119c 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -10,6 +10,8 @@ * Copyright The Asahi Linux Contributors */ +/* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ +#define T6050_K114S /* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ #define T6050_K_N1_FIRMWARE "apple/centauri/k114s-ftab.bin" #define T6050_K_BOARD_ID 0x14 @@ -24,7 +26,6 @@ firmware-name = "apple/tpmtfw-k114s.bin"; }; -#define T6050_K114S #include "t6050-peripherals.dtsi" /* The 14-inch chassis: the Neural Engine, pins, the jack, the card and the AOP; no speakers */ @@ -70,5 +71,10 @@ }; }; -/* The USB-C ports ATC1 and ATC2, as on the other K boards */ +/* + * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi), then the + * 14-inch chassis' MagSafe 3 PD controller and the right port's USB4/Thunderbolt router + * (t6050-k114-usb.dtsi). + */ #include "t6050-k114-k116-usb.dtsi" +#include "t6050-k114-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 922b83b01d0574..84c3ddbb613635 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -219,7 +219,8 @@ #endif }; -#if defined(T6050_J714C) || defined(T6050_J714S) || defined(T6050_J716C) || defined(T6050_K114C) +#if defined(T6050_J714C) || defined(T6050_J714S) || defined(T6050_J716C) || defined(T6050_K114C) || \ + defined(T6050_K114S) /* * ATC2's USB4/Thunderbolt router (ADT /arm-io/acio2, acio-cpu2 and dart-acio2), powered per * connection: the PHY enters CIO mode, then the router's domains come on (ATC2_CIO, _PCIE, _USB, diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index c7a6178d27371f..cf9ba10059161b 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -1617,7 +1617,8 @@ status = "disabled"; }; -#if !defined(T6050_J714C) && !defined(T6050_J714S) && !defined(T6050_J716C) && !defined(T6050_K114C) +#if !defined(T6050_J714C) && !defined(T6050_J714S) && !defined(T6050_J716C) && !defined(T6050_K114C) && \ + !defined(T6050_K114S) apciec2_dart: iommu@384000000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; reg = <0x3 0x84000000 0x0 0x20000>; From 9f865da20d40b964121c4e92f6794804513c2627 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:17:20 +1100 Subject: [PATCH 1461/1514] arm64: dts: apple: t8112: describe the auxiliary PMU on every M2 The nub-spmi1 bus carries the auxiliary PMU (ADT /arm-io/nub-spmi1/pmu-aux, USID 0xe) on every T8112 Mac: the J413 and J473 ADTs both list it. Only the J413 described it; the J415, J473 and J493 kept a disabled copy. Describe the bus and its read-only spmi-nvmem PMIC once in t8112.dtsi and drop the per-board copies, so every M2 binds apple-spmi and apple-spmi-nvmem the way the J413 already does. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-j413.dts | 10 ---------- arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112.dtsi | 8 +++++++- 5 files changed, 7 insertions(+), 35 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index da075043e4b8e8..7f8825891237e7 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -314,16 +314,6 @@ status = "okay"; }; -&nub_spmi1 { - status = "okay"; - - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - }; -}; - &i2c2 { retimer@18 { compatible = "apple,t8112-atcrt", "apple,atcrt"; diff --git a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi index b7e06632fdf791..a9b1d4c8a8a556 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi @@ -26,11 +26,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index fd13d3c654e935..a5b0542e289894 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1524,12 +1524,18 @@ }; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@23d794000 { compatible = "apple,t8112-spmi", "apple,t8103-spmi"; reg = <0x2 0x3d794000 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; smc: smc@23e400000 { From 1c71360f65af7a6b576e069463dc99bc685b9da9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:21:29 +1100 Subject: [PATCH 1462/1514] arm64: dts: apple: t6050: give the K boards' port 0 DART its power domain With the K boards' PCIe port 0 described, pcie0's iommu-map makes the N1 use dart_apcie0, which names no power domain on any T6050 board, so the DART power-domain check flags it as a new user on K114s and K116c. The ADT's apcie0 power-gates start with APCIE_GP (137) and APCIE_SYS_GP (143); APCIE_SYS_GP sits on APCIE_GP and FAB6_SOC, as ps_apcie_sys_gp already says. dart_apcie0 now takes APCIE_SYS_GP, as the T600x/T602x PCIe DARTs take theirs. The boot loader trains port 0 and keeps it powered for the hand-off, so ps_apcie_sys_gp, ps_apcie_gp and ps_fab6_soc are enabled as firmware-owned. They are enabled in t6050-k114-k116-usb.dtsi because the boards include it after t6050-peripherals.dtsi, which defines them. The host node takes no power-domains: its binding allows none. Only the four K board DTBs change. Signed-off-by: Ryan Murray --- .../boot/dts/apple/t6050-k114-k116-usb.dtsi | 16 ++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi index c82d8c24e3ede1..87b16d9a0429ac 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-usb.dtsi @@ -180,3 +180,19 @@ }; }; }; + +/* PCIe port 0's power states, used by pcie0 and dart_apcie0 (see t6050-k114-k116.dtsi) */ +&ps_fab6_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_apcie_gp { + apple,firmware-owned; + status = "okay"; +}; + +&ps_apcie_sys_gp { + apple,firmware-owned; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index a37a1aa19ce0b2..d26d2621b38a0a 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -306,3 +306,15 @@ &smc_pcio { apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 0x011c000000010000>; }; + +/* + * Port 0's power: the ADT's apcie0 power-gates are APCIE_GP (137), APCIE_SYS_GP (143) and the + * fabric; APCIE_SYS_GP sits on APCIE_GP and FAB6_SOC. Its DART (dart-apcie0, which the N1 uses + * through the host's iommu-map) takes APCIE_SYS_GP, as the T600x/T602x PCIe DARTs do. The loader + * trains port 0 and keeps it powered for the hand-off, so these stay firmware-owned + * (enabled in t6050-k114-k116-usb.dtsi, which boards include after t6050-peripherals.dtsi). + */ +&dart_apcie0 { + power-domains = <&ps_apcie_sys_gp>; +}; + From d3d0109ad0847fb94513092dd0524872dd09d79e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:17:20 +1100 Subject: [PATCH 1463/1514] arm64: dts: apple: t8122-j615: enable the DP855 panel controller i2c-dp855 drives the DP855 panel timing controller as a read-only I2C adapter and shares the controller's I2C engine with the display firmware through its lock; it already binds on the M2 Air. The T8122 node was kept disabled "until the host transport is supported", which it now is. Move the SPI timing the J413 uses onto the shared T8122 node and enable spi4 and the controller on the J615, with the chip select from its ADT (/arm-io/spi4 function-spi_cs0: GPIO 136). Other T8122 boards keep it off until their chip select is checked against their ADT. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615.dts | 10 ++++++++++ arch/arm64/boot/dts/apple/t8122-jxxx.dtsi | 10 +++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index e14193bee84cbe..13516694fd13a7 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -236,3 +236,13 @@ apple,dma-range = /bits/ 64 <0x10000000000 0x1000000000>; }; }; + +/* ADT /arm-io/spi4/dp855; chip select = /arm-io/spi4 function-spi_cs0. */ +&spi4 { + cs-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_LOW>; + status = "okay"; +}; + +&tcon { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi index b6cd4ee1c40873..650eeaf06d7329 100644 --- a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi @@ -257,11 +257,19 @@ #include "spi1-nvram.dtsi" -/* Panel control remains firmware-owned until the host transport is supported. */ +/* + * The DP855 panel timing controller. i2c-dp855 reads the panel management + * devices behind it and shares its I2C engine with the display firmware + * through the controller's lock. Its chip select is board wiring, so the + * board files that have the ADT's spi4 function-spi_cs0 enable it. + */ &spi4 { tcon: panel-controller@0 { compatible = "parade,dp855"; reg = <0>; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; status = "disabled"; }; }; From f393918abe5ba6657171117d93aad0044cd34697 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 23:06:17 -0500 Subject: [PATCH 1464/1514] drm/asahi: don't present 32 KiB as every GPU's tile-buffer limit The M5 path of g17 admits 64 KiB tile buffers without reporting DRM_ASAHI_FEATURE_TILE_BUFFER_48K, so "instead of 32 KiB" in the bit's comment is wrong there. Say that the bit is about the GPU that reports it, and that 32 KiB is the portable limit without it. Comment only. Signed-off-by: DjDeveloperr --- include/uapi/drm/asahi_drm.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index f1fee4537e2b9c..fb91658169745d 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -606,10 +606,10 @@ enum drm_asahi_feature { #define DRM_ASAHI_FEATURE_ORDERED_PARTIAL_RENDERS ((1ULL) << 45) /* - * DRM_ASAHI_FEATURE_TILE_BUFFER_48K: render commands accept tile buffers of - * up to 48 KiB (sample_size_B * utile_width_px * utile_height_px * samples - * <= 49152), instead of 32 KiB. A feature bit like those of enum - * drm_asahi_feature, defined here like bit 32. + * DRM_ASAHI_FEATURE_TILE_BUFFER_48K: render commands on this GPU accept tile + * buffers of up to 48 KiB (sample_size_B * utile_width_px * utile_height_px * + * samples <= 49152). Without it, 32 KiB is the portable limit. A feature bit + * like those of enum drm_asahi_feature, defined here like bit 32. */ #define DRM_ASAHI_FEATURE_TILE_BUFFER_48K ((1ULL) << 46) From 0a57fc2e701998e0d8808d4a2e991f9e591cc017 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:13:56 +1100 Subject: [PATCH 1465/1514] arm64: dts: apple: t6050: drop the ATC2 router's unused interrupt name The right-port USB4 PCIe tunnel (apciec2, apple,t6050-pciec) names its one interrupt "port0". The binding allows no interrupt-names for this controller, so every board that enables the node gets a schema warning; with the K114s now enabling it, CHECK_DTBS reports it as new there. pcie-apple looks interrupts up by name only for hosts that adopt a trained link (hw->adopt_link). t6050_pciec_hw does not, so it maps the port interrupt by index and never reads the name. Dropping the property changes nothing at run time. The J714c, J714s, J716c, K114c and K114s DTBs lose that one property; no other T6050 DTB changes. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-max.dtsi | 1 - 1 file changed, 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 84c3ddbb613635..13d8950b5eca0b 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -457,7 +457,6 @@ reg-names = "config", "rc", "port0", "fabric", "debug", "ltssm", "intr2axi"; /* The port's: link events and INTx */ interrupts = ; - interrupt-names = "port0"; power-domains = <&ps_atc2_pcie>; /* No boot loader hands the port over: the kernel cold-initializes it. */ apple,pciec-kernel-init; From 8c2971295d3caf390954c099eca1c895bc091ba6 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:15:26 +1100 Subject: [PATCH 1466/1514] Revert "arm64: dts: apple: t8112: describe the auxiliary PMU on every M2" This reverts merge e9fd1d92f9 (linux#3341). apple-spmi-nvmem still registers a register-write callback: the DT read-only property only sets the initial NVMEM policy, and the sysfs interface can change it. Enabling the PMIC on the J415, J473 and J493 widens that write path. Revert until linux#3299 makes the sysfs file read-only, then reland with a J473 row on a kernel carrying it. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-j413.dts | 10 ++++++++++ arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi | 8 ++++++++ arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi | 8 ++++++++ arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi | 8 ++++++++ arch/arm64/boot/dts/apple/t8112.dtsi | 8 +------- 5 files changed, 35 insertions(+), 7 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index 7f8825891237e7..da075043e4b8e8 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -314,6 +314,16 @@ status = "okay"; }; +&nub_spmi1 { + status = "okay"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; +}; + &i2c2 { retimer@18 { compatible = "apple,t8112-atcrt", "apple,atcrt"; diff --git a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi index 174308798291f2..9e7941dd584e0b 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi @@ -43,3 +43,11 @@ }; }; +&nub_spmi1 { + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + status = "disabled"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi index 174308798291f2..9e7941dd584e0b 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi @@ -43,3 +43,11 @@ }; }; +&nub_spmi1 { + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + status = "disabled"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi index a9b1d4c8a8a556..b7e06632fdf791 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi @@ -26,3 +26,11 @@ }; }; +&nub_spmi1 { + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + status = "disabled"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index a5b0542e289894..fd13d3c654e935 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1524,18 +1524,12 @@ }; }; - /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@23d794000 { compatible = "apple,t8112-spmi", "apple,t8103-spmi"; reg = <0x2 0x3d794000 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; - - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - }; + status = "disabled"; }; smc: smc@23e400000 { From c2acdf7af242c2255de7c5cc029a1d346418d519 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:18:07 +1100 Subject: [PATCH 1467/1514] drm: apple: hdcp: work on the default command line, unbind and suspend safely Address the review of the HDCP series: - No module parameter: a display processor takes part when its node has "apple,hdcp-channels" (and the SEP HDCP service is built in); while userspace does not ask for protection, DCP's sessions are declined. - Unbind: the state is device-managed and goes with the component bind. dcp_hdcp_fini() now disables every work synchronously, ends what is open, shuts down the endpoints this file started and clears dcp->hdcp, so nothing routes to or requeues on freed state. - A teardown that was asked for before DCP opened a newer session no longer ends that session: teardowns record the accepted-open count and skip when it moved; a new run aborts whatever an earlier session left open first. - Suspend and DPMS off: the work queue is not freezable any more, and both paths wait for the teardown (encryption off, SEP session closed, the device service's end call) before DCP sleeps or the pipe goes down. - The capability call goes out once per HDCP interface when it opens; the periodic re-send ("kick") is gone. A close of an earlier session after a newer open is ignored, and a close's action is applied. - Comments justify the two non-spec margins (event slack, register call timeout). KUnit: apple-dcp-hdcp-glue gains a stale-teardown and an unbind case. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/Kconfig | 7 +- drivers/gpu/drm/apple/dcp-hdcp-drv.h | 3 + drivers/gpu/drm/apple/dcp-hdcp-glue-test.c | 38 +++++- drivers/gpu/drm/apple/dcp-hdcp-tx.h | 5 +- drivers/gpu/drm/apple/dcp-hdcp.c | 127 ++++++++++++++------- drivers/gpu/drm/apple/dcp-hdcp.h | 2 +- drivers/gpu/drm/apple/dcp.c | 7 +- 7 files changed, 140 insertions(+), 49 deletions(-) diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index a3753e2481e542..bff991d363a377 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -46,9 +46,10 @@ config DRM_APPLE_HDCP Support the standard "Content Protection" and "HDCP Content Type" connector properties on external DisplayPort, HDMI and USB-C outputs. The SEP holds the transmitter's keys and does the HDCP 2.2 - cryptography; DCP carries the messages to the receiver. Sessions - run only with the appledrm.hdcp module parameter set and the SEP - HDCP service (APPLE_SEP_HDCP_INTERFACE) available. + cryptography; DCP carries the messages to the receiver. The + property is attached on display processors whose device tree node + has "apple,hdcp-channels", with the SEP HDCP service + (APPLE_SEP_HDCP_INTERFACE) built in. config DRM_APPLE_AUDIO bool "DisplayPort/HDMI Audio support" diff --git a/drivers/gpu/drm/apple/dcp-hdcp-drv.h b/drivers/gpu/drm/apple/dcp-hdcp-drv.h index cf08236cbb5595..8b1600fcd74b49 100644 --- a/drivers/gpu/drm/apple/dcp-hdcp-drv.h +++ b/drivers/gpu/drm/apple/dcp-hdcp-drv.h @@ -36,6 +36,8 @@ dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, bool cut); /* Hotplug, power off or on, suspend, a new route: a new link generation. */ void dcp_hdcp_link_changed(struct apple_dcp *dcp); +/* The same, and its teardown finished before returning (suspend, DPMS off). */ +void dcp_hdcp_quiesce(struct apple_dcp *dcp); int dcp_hdcp_attach_connector(struct apple_connector *connector, struct platform_device **dcps, unsigned int n, @@ -61,6 +63,7 @@ dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, } static inline void dcp_hdcp_link_changed(struct apple_dcp *dcp) { } +static inline void dcp_hdcp_quiesce(struct apple_dcp *dcp) { } static inline int dcp_hdcp_attach_connector(struct apple_connector *connector, struct platform_device **dcps, unsigned int n, int connector_type) diff --git a/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c b/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c index 92dcf8e37da4fe..0ed30dc541d5d4 100644 --- a/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c +++ b/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c @@ -82,7 +82,7 @@ static void glue_declined_open_forgets_slot(struct kunit *test) INIT_WORK(&g->h.event_work, dcp_hdcp_event_work); INIT_WORK(&g->h.teardown_work, dcp_hdcp_teardown_work); INIT_WORK(&g->h.prop_work, dcp_hdcp_prop_work); - INIT_DELAYED_WORK(&g->h.kick_work, dcp_hdcp_kick_work); + INIT_WORK(&g->h.caps_work, dcp_hdcp_caps_work); g->h.session = &g->service; /* Nothing asks for protection here: the open is declined. */ @@ -124,11 +124,47 @@ static void glue_hdcp1_session_declined(struct kunit *test) KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &g->service)); } +/* A teardown asked for before DCP opened a newer session leaves that session alone. */ +static void glue_stale_teardown_skipped(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, true); + + spin_lock_init(&g->h.svc_lock); + g->h.td_seq = 1; + g->h.open_seq = 2; + g->h.tx.sep_open = true; + dcp_hdcp_teardown_work(&g->h.teardown_work); + KUNIT_EXPECT_TRUE(test, g->h.tx.sep_open); +} + +/* Unbind stops all work and unpublishes the state. */ +static void glue_fini_unpublishes(struct kunit *test) +{ + struct glue_fixture *g = glue_new(test, true); + + mutex_init(&g->h.lock); + spin_lock_init(&g->h.svc_lock); + init_waitqueue_head(&g->h.ev_wq); + INIT_WORK(&g->h.event_work, dcp_hdcp_event_work); + INIT_WORK(&g->h.teardown_work, dcp_hdcp_teardown_work); + INIT_WORK(&g->h.prop_work, dcp_hdcp_prop_work); + INIT_WORK(&g->h.relay_work, dcp_hdcp_relay_work); + INIT_WORK(&g->h.caps_work, dcp_hdcp_caps_work); + dcp_hdcp_fini(&g->dcp); + KUNIT_EXPECT_NULL(test, READ_ONCE(g->dcp.hdcp)); + KUNIT_EXPECT_TRUE(test, g->h.cancel); + /* Work queued after unbind never runs. */ + KUNIT_EXPECT_FALSE(test, queue_work(system_wq, &g->h.teardown_work)); + KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic", false)); +} + static struct kunit_case dcp_hdcp_glue_cases[] = { KUNIT_CASE(glue_match_by_name), KUNIT_CASE(glue_session_without_hdcp_declines), KUNIT_CASE(glue_declined_open_forgets_slot), KUNIT_CASE(glue_hdcp1_session_declined), + KUNIT_CASE(glue_stale_teardown_skipped), + KUNIT_CASE(glue_fini_unpublishes), { } }; diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx.h b/drivers/gpu/drm/apple/dcp-hdcp-tx.h index f32189bb1556cb..7f1446e86f2392 100644 --- a/drivers/gpu/drm/apple/dcp-hdcp-tx.h +++ b/drivers/gpu/drm/apple/dcp-hdcp-tx.h @@ -18,7 +18,10 @@ * specification asks for it. It never touches the display. * * DCP owns the receiver timeouts and closes an attempt that runs out of - * time; the waits below only guard against a session DCP forgets. + * time; the waits below only guard against a session DCP forgets. An event + * travels receiver CP_IRQ -> DCP -> mailbox -> this driver's work queue on + * top of the spec time, so the guard is the spec time plus this slack; it is + * not a spec value and only decides when RxStatus is read as a fallback. */ #define DCP_HDCP_EVENT_SLACK_MS 500 /* Locality check attempts, each with a fresh r_n. */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp.c b/drivers/gpu/drm/apple/dcp-hdcp.c index 1a6f4c1220b5da..d08fd991706289 100644 --- a/drivers/gpu/drm/apple/dcp-hdcp.c +++ b/drivers/gpu/drm/apple/dcp-hdcp.c @@ -13,8 +13,9 @@ * seen here: only the protocol fields the HDCP 2.2 messages carry in the * clear. * - * Off unless appledrm.hdcp=1: the property is not attached and DCP's - * sessions are declined, as before. + * Only a display processor whose node has "apple,hdcp-channels" takes + * part; elsewhere the property is not attached and nothing changes. While + * userspace does not ask for protection, DCP's sessions are declined. */ #include @@ -45,15 +46,14 @@ #include "dcp-hdcp-wire.h" #include "dcp-internal.h" -static bool hdcp; -module_param(hdcp, bool, 0444); -MODULE_PARM_DESC(hdcp, "HDCP 2.2 on external outputs: attach Content Protection and take DCP's authentication sessions (needs the SEP HDCP service)"); -/* How long a register access may take: DCP's AUX timeout, and some. */ +/* + * How long a register access may take: DCP applies its own AUX timeout + * (DCP_HDCP_REG_TIMEOUT_MS, carried in the request); the extra 500 ms covers + * the mailbox round trip, so a slow transaction ends with DCP's answer, not + * ours. Not a spec value. + */ #define DCP_HDCP_CALL_MS (DCP_HDCP_REG_TIMEOUT_MS + 500) -/* Asking DCP for a session again, while one is wanted and none came. */ -#define DCP_HDCP_KICK_MS 5000 -#define DCP_HDCP_KICKS 6 /* The receiver's status on an encrypted link. */ #define DCP_HDCP_IFACES 4 #define DCP_HDCP_QUEUE 16 @@ -98,8 +98,10 @@ struct dcp_hdcp { struct work_struct teardown_work; struct work_struct prop_work; struct work_struct relay_work; - struct delayed_work kick_work; - unsigned int kicks; + struct work_struct caps_work; + /* Accepted session opens; a teardown older than the latest is stale. */ + unsigned int open_seq; + unsigned int td_seq; struct dcp_hdcp_tx tx; }; @@ -382,12 +384,10 @@ static void dcp_hdcp_apply(struct dcp_hdcp *h, enum dcp_hdcp_action action) if (action == DCP_HDCP_TEARDOWN) { spin_lock_irqsave(&h->svc_lock, flags); h->cancel = true; + h->td_seq = h->open_seq; spin_unlock_irqrestore(&h->svc_lock, flags); wake_up_all(&h->ev_wq); queue_work(h->wq, &h->teardown_work); - } else if (action == DCP_HDCP_KICK) { - h->kicks = 0; - mod_delayed_work(h->wq, &h->kick_work, 0); } queue_work(h->wq, &h->prop_work); } @@ -437,21 +437,16 @@ static void dcp_hdcp_prop_work(struct work_struct *work) drm_modeset_unlock(&drm->mode_config.connection_mutex); } -/* Asks DCP for a session through the HDCP interfaces, while one is wanted. */ -static void dcp_hdcp_kick_work(struct work_struct *work) +/* + * The transmitter's capability, once per HDCP interface after it opens (as + * macOS does at boot): DCP then offers sessions at each link-up. + */ +static void dcp_hdcp_caps_work(struct work_struct *work) { - struct dcp_hdcp *h = container_of(to_delayed_work(work), struct dcp_hdcp, - kick_work); + struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, caps_work); struct apple_epic_service *service; - bool ready; int i; - mutex_lock(&h->lock); - ready = dcp_hdcp_ready(&h->link, jiffies); - mutex_unlock(&h->lock); - if (!ready || h->kicks >= DCP_HDCP_KICKS) - return; - h->kicks++; for (i = 0; i < DCP_HDCP_IFACES; i++) { service = dcp_hdcp_pin(h, &h->iface[i]); if (!service) @@ -460,10 +455,8 @@ static void dcp_hdcp_kick_work(struct work_struct *work) DCP_HDCP_IF_CAPS_LEN, DCP_HDCP_IF_CAPS_VALUE); afk_service_put(service); } - queue_delayed_work(h->wq, &h->kick_work, msecs_to_jiffies(DCP_HDCP_KICK_MS)); } -/* Encryption off, the SEP session closed, DCP told; the picture stays. */ /* Tells the DP device service the session it was asked for has ended. */ static void dcp_hdcp_dev_end(struct dcp_hdcp *h) { @@ -479,11 +472,23 @@ static void dcp_hdcp_dev_end(struct dcp_hdcp *h) afk_service_put(relay); } +/* Encryption off, the SEP session closed, DCP told; the picture stays. */ static void dcp_hdcp_teardown_work(struct work_struct *work) { struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, teardown_work); - bool was_open = h->tx.sep_open; + unsigned long flags; + bool was_open, stale; + /* + * A session DCP opened after this teardown was asked for has already + * replaced what it would end (dcp_hdcp_run() aborts a leftover first). + */ + spin_lock_irqsave(&h->svc_lock, flags); + stale = h->open_seq != h->td_seq; + spin_unlock_irqrestore(&h->svc_lock, flags); + if (stale) + return; + was_open = h->tx.sep_open; dcp_hdcp_abort(&h->tx); if (was_open) dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); @@ -508,6 +513,9 @@ static void dcp_hdcp_run(struct dcp_hdcp *h) return; } mutex_unlock(&h->lock); + /* What an earlier session left open (its teardown has not run yet). */ + if (h->tx.sep_open) + dcp_hdcp_abort(&h->tx); h->tx.ops = &dcp_hdcp_tx_ops; h->tx.ctx = h; h->tx.channel = h->channel; @@ -543,12 +551,22 @@ static void dcp_hdcp_run(struct dcp_hdcp *h) static void dcp_hdcp_close(struct dcp_hdcp *h, struct apple_epic_service *service) { + enum dcp_hdcp_action action; unsigned long flags; + bool ours; + /* A close of an earlier session, after DCP opened a newer one: nothing to end. */ + spin_lock_irqsave(&h->svc_lock, flags); + ours = !h->session || h->session == service; + spin_unlock_irqrestore(&h->svc_lock, flags); + if (!ours) + return; dcp_hdcp_abort(&h->tx); mutex_lock(&h->lock); - dcp_hdcp_closed(&h->link, h->session_gen, jiffies); + action = dcp_hdcp_closed(&h->link, h->session_gen, jiffies); mutex_unlock(&h->lock); + if (action != DCP_HDCP_TEARDOWN) + dcp_hdcp_apply(h, action); /* The session goes back to idle on DCP's side. */ if (service) dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); @@ -682,13 +700,12 @@ static int dcp_hdcp_session_call(struct apple_epic_service *service, u16 group, h->ev_bits = 0; h->closed = false; h->cancel = false; + h->open_seq++; } else if (h->session == service) { /* The slot of an earlier session, declined this time. */ h->session = NULL; } spin_unlock_irqrestore(&h->svc_lock, flags); - if (accept) - cancel_delayed_work(&h->kick_work); } ret = dcp_hdcp_auth_reply(group, command, data, size, reply, room, accept); @@ -816,9 +833,7 @@ static void dcp_hdcp_iface_init(struct apple_epic_service *service, } } spin_unlock_irqrestore(&h->svc_lock, flags); - /* The capability goes out once the interface is open, as the first kick. */ - h->kicks = 0; - mod_delayed_work(h->wq, &h->kick_work, 0); + queue_work(h->wq, &h->caps_work); } static void dcp_hdcp_iface_teardown(struct apple_epic_service *service) @@ -992,7 +1007,7 @@ struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); u32 channel; - if (h || !hdcp || dcp_has_panel(dcp) || !dcp_hdcp_channel(dcp, &channel)) + if (h || dcp_has_panel(dcp) || !dcp_hdcp_channel(dcp, &channel)) return h; h = devm_kzalloc(dcp->dev, sizeof(*h), GFP_KERNEL); if (!h) @@ -1006,8 +1021,9 @@ struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) INIT_WORK(&h->teardown_work, dcp_hdcp_teardown_work); INIT_WORK(&h->prop_work, dcp_hdcp_prop_work); INIT_WORK(&h->relay_work, dcp_hdcp_relay_work); - INIT_DELAYED_WORK(&h->kick_work, dcp_hdcp_kick_work); - h->wq = alloc_ordered_workqueue("apple-dcp-hdcp", WQ_FREEZABLE); + INIT_WORK(&h->caps_work, dcp_hdcp_caps_work); + /* Not freezable: a suspend's teardown must reach DCP before it sleeps. */ + h->wq = alloc_ordered_workqueue("apple-dcp-hdcp", 0); if (!h->wq) return NULL; if (devm_add_action_or_reset(dcp->dev, dcp_hdcp_destroy_wq, h->wq)) @@ -1020,9 +1036,15 @@ struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) return h; } +/* + * Component unbind: the state is device-managed and goes with the bind, so + * nothing may reach it afterwards. Stop all work, end what is open, shut the + * endpoints this file started, and unpublish it. + */ void dcp_hdcp_fini(struct apple_dcp *dcp) { struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + struct apple_dcp_afkep *ep; unsigned long flags; if (!h) @@ -1031,9 +1053,34 @@ void dcp_hdcp_fini(struct apple_dcp *dcp) h->cancel = true; spin_unlock_irqrestore(&h->svc_lock, flags); wake_up_all(&h->ev_wq); - cancel_delayed_work_sync(&h->kick_work); - flush_workqueue(h->wq); + disable_work_sync(&h->event_work); + disable_work_sync(&h->teardown_work); + disable_work_sync(&h->prop_work); + disable_work_sync(&h->relay_work); + disable_work_sync(&h->caps_work); dcp_hdcp_abort(&h->tx); + dcp_hdcp_dev_end(h); + ep = xchg(&h->if_ep, NULL); + if (ep) + afk_shutdown(ep); + ep = xchg(&h->dpdev_ep, NULL); + if (ep) + afk_shutdown(ep); + WRITE_ONCE(dcp->hdcp, NULL); +} + +/* + * Before DCP sleeps or powers a pipe down: the link change, then its + * teardown done here, so encryption is off and DCP has the device service's + * end call before it waits for it. + */ +void dcp_hdcp_quiesce(struct apple_dcp *dcp) +{ + struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); + + dcp_hdcp_link_changed(dcp); + if (h) + flush_work(&h->teardown_work); } /* DRM. */ @@ -1046,7 +1093,7 @@ int dcp_hdcp_attach_connector(struct apple_connector *connector, unsigned int i; int ret; - if (!hdcp || connector->hdcp_attached || + if (connector->hdcp_attached || connector_type == DRM_MODE_CONNECTOR_eDP) return 0; for (i = 0; i < n; i++) { diff --git a/drivers/gpu/drm/apple/dcp-hdcp.h b/drivers/gpu/drm/apple/dcp-hdcp.h index 536bf67966137c..0c4f09a0e57fa0 100644 --- a/drivers/gpu/drm/apple/dcp-hdcp.h +++ b/drivers/gpu/drm/apple/dcp-hdcp.h @@ -60,7 +60,7 @@ enum dcp_hdcp_state { enum dcp_hdcp_action { DCP_HDCP_NONE, DCP_HDCP_TEARDOWN, /* encryption off and close, display untouched */ - DCP_HDCP_KICK, /* ask DCP for a session */ + DCP_HDCP_KICK, /* ready: the next session DCP offers is taken */ }; struct dcp_hdcp_link { diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index 716a26c59d2cee..968fb42db22d27 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -5544,8 +5544,8 @@ void dcp_poweroff(struct platform_device *pdev) bool display_gone = false; int ret; - /* DPMS off ends any HDCP session; the next power-on starts another. */ - dcp_hdcp_link_changed(dcp); + /* DPMS off ends any HDCP session before the pipe goes down; the next power-on starts another. */ + dcp_hdcp_quiesce(dcp); if (iomfb_is_m4(dcp)) { ret = dcp_backlight_dpms(dcp, false); @@ -9934,7 +9934,8 @@ static int dcp_s2r_suspend(struct apple_dcp *dcp) bool was_off; int ret; - dcp_hdcp_link_changed(dcp); + /* Encryption off and the HDCP session ended while DCP still runs. */ + dcp_hdcp_quiesce(dcp); /* * Not bound into the display subsystem (a component unbind released the RTKit From 36b2ee61e2230ce2109fe2c8cab3bc64e259f082 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:00:57 +1100 Subject: [PATCH 1468/1514] arm64: dts: apple: t6050: share the K boards' internal panel, add it to K114s, K114c and K116c The K114s comes up on the boot framebuffer only: aura logs "the device tree does not describe the internal display: no handoff", so the DCP never binds and there is no backlight device (brightness keys dead). The K116s already describes its panel and display coprocessor for the boot loader's hand-off; the K114c, K114s and K116c describe nothing. The four K boards' ADTs have the same disp0, dart-disp0, dcp and dart-dcp (live K114s ADT, 27.2: disp0 clock-ids 361 and 458, both DARTs vm-base 1 TiB and vm-size 3 TiB, dcp-brightness-node = 1, no I2C backlight controller), and the K114s runs the K116s's 27.2 DCP image (3D6C8857-...), which aura already pairs for the internal panel. Move the K116s's display half into t6050-k114-k116-display.dtsi and include it on all four boards; each board adds its panel's size. The K116s DTB is unchanged (same properties and values, node order aside); every J-board DTB is byte-identical. Signed-off-by: Ryan Murray --- .../dts/apple/t6050-k114-k116-display.dtsi | 61 +++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 13 ++++ arch/arm64/boot/dts/apple/t6050-k114s.dts | 13 ++++ arch/arm64/boot/dts/apple/t6050-k116c.dts | 10 +++ arch/arm64/boot/dts/apple/t6050-k116s.dts | 66 ++++--------------- 5 files changed, 109 insertions(+), 54 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi new file mode 100644 index 00000000000000..7206ceb2951d02 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116-display.dtsi @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The internal tandem OLED panel and its display coprocessor on the K114c, K114s, K116c and + * K116s, for the boot loader's display hand-off. The four ADTs have the same disp0, dart-disp0, + * dcp and dart-dcp (the live K114s and K116s ADTs: disp0 clock-ids 361 and 458, both DARTs + * vm-base 1 TiB, vm-size 3 TiB) and no I2C backlight controller: the OLED's luminance is a DCP + * request (ADT /backlight-override dcp-brightness-node = 1). + * + * Everything stays disabled. The loader checks the ADT and the live DCP and DART state, + * publishes the DCP's firmware properties, the panel's brightness scale (ADT + * user-accessible-max-nits) and the ADT /vram as the framebuffer, and only then enables dcp, + * its DARTs and mailbox and the display subsystem. A loader without the hand-off, or one whose + * checks fail, leaves the boot framebuffer to simpledrm. + * + * The board adds the panel's size (the ADTs carry none). + */ + +/ { + aliases { + /* The loader writes apple,notch-height into the "dcp" alias */ + dcp = &dcp; + disp0 = &display; + }; + + /* As on J714s, with the internal display's DART (disp0, SID 0) */ + display: display-subsystem { + compatible = "apple,display-subsystem"; + iommus = <&disp0_dart 0>; + status = "disabled"; + }; +}; + +/* ADT dart-dcp and dart-disp0: vm-base 1 TiB, vm-size 3 TiB */ +&dcp_dart { + apple,dma-range = <0x100 0x0 0x300 0x0>; +}; + +&disp0_dart { + apple,dma-range = <0x100 0x0 0x300 0x0>; +}; + +&dcp { + /* + * ADT disp0 clock-ids. The loader adds the clock nodes, "clocks" and the + * bandwidth request scratch ("apple,bw-scratch") when it hands the panel + * over, as on the J714s, and refuses a tree that already has them. + */ + apple,clock-ids = <361 458>; + + /* + * The panel's plug takes about 2.9 ms on the K116s from the video interface's + * announcement to the firmware's "ioav i/f is now closed", and the next round of + * reports follows about 33 ms later. With the J714s's 2500 us the open landed 25 us + * before the close. The K boards run the same 27.2 DCP image for the same panel family. + */ + apple,panel-video-open-delay-us = <10000>; + + panel: panel { + compatible = "apple,panel"; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 495334da4a875f..880f8535960ffa 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -155,6 +155,19 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* + * The 14.2-inch 3024x1986 panel's active area (254 dpi, the notch rows included), for the + * DPI only (the ADT carries none) + */ +&panel { + compatible = "apple,panel-k114", "apple,panel"; + width-mm = <302>; + height-mm = <199>; +}; + /* * The K114c keeps J714's card with its speakers, at the J714's safe level. The * chassis' K114 entry (t6050-k114.dtsi) has the jack only. diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 417f6007e0119c..e8b2298ec4a258 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -34,6 +34,19 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* + * The 14.2-inch 3024x1986 panel's active area (254 dpi, the notch rows included), for the + * DPI only (the ADT carries none) + */ +&panel { + compatible = "apple,panel-k114", "apple,panel"; + width-mm = <302>; + height-mm = <199>; +}; + / { aliases { /* asahi-bless and the boot loader find the NVRAM partition by this alias */ diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index 40bfec8ab72a85..f73e86c12f87eb 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -29,5 +29,15 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* The 16.2-inch 3456x2234 panel's active area, for the DPI only (the ADT carries none) */ +&panel { + compatible = "apple,panel-k116", "apple,panel"; + width-mm = <345>; + height-mm = <223>; +}; + /* The USB-C ports ATC1 and ATC2, as on the other K boards */ #include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index 26f4bce4362dbc..28d32133e59b07 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -171,57 +171,6 @@ }; }; -/* - * The internal panel and the display coprocessor, for the boot loader's display - * hand-off (aura, chosen.aurora,t6050-display=1). Everything stays disabled: the - * loader checks the ADT and the live DCP and DART state, publishes the DCP's - * firmware properties, reserves the ADT /vram as the framebuffer and only then - * enables dcp, its DARTs and mailbox and the display subsystem. A loader without - * the hand-off leaves the boot framebuffer to simpledrm. - */ -/ { - aliases { - /* The loader writes apple,notch-height into the "dcp" alias */ - dcp = &dcp; - disp0 = &display; - }; - - /* As on J714s, with the internal display's DART (disp0, SID 0) */ - display: display-subsystem { - compatible = "apple,display-subsystem"; - iommus = <&disp0_dart 0>; - status = "disabled"; - }; -}; - -/* ADT dart-dcp and dart-disp0: vm-base 1 TiB, vm-size 3 TiB */ -&dcp_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&disp0_dart { - apple,dma-range = <0x100 0x0 0x300 0x0>; -}; - -&dcp { - /* - * ADT disp0 clock-ids. The loader adds the clock nodes, "clocks" and the - * bandwidth request scratch ("apple,bw-scratch") when it hands the panel - * over, as on the J714s, and refuses a tree that already has them. - */ - apple,clock-ids = <361 458>; - - /* - * The 16.2-inch 3456x2234 tandem OLED panel. The ADT carries no dimensions; - * these are the panel's active area, for the DPI only. - */ - panel { - compatible = "apple,panel-k116", "apple,panel"; - width-mm = <345>; - height-mm = <223>; - }; -}; - /* * The trackpad's AFE reset. The ADT names the SMC pcIO template (0x10000, * 0x11c0000), the same line as SMC GPIO gp1c, active low, which gpio-macsmc @@ -610,6 +559,16 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* The internal panel, handed over by the boot loader */ +#include "t6050-k114-k116-display.dtsi" + +/* The 16.2-inch 3456x2234 panel's active area, for the DPI only (the ADT carries none) */ +&panel { + compatible = "apple,panel-k116", "apple,panel"; + width-mm = <345>; + height-mm = <223>; +}; + /* * As t6050-j714s.dts: the GPU on the PMP's GFX report entry (report@f, on ps_gfx), so the PMP * is told the GPU is on only while it is powered. This board runs the PMP with its report @@ -812,9 +771,8 @@ }; /* - * The panel's plug takes about 2.9 ms here from the video interface's announcement to the - * firmware's "ioav i/f is now closed", and the next round of reports follows about 33 ms later. - * With the J714s's 2500 us the open landed 25 us before the close. + * t6050-j714s-sleep-soc.dtsi, included above, sets the J714s's 2500 us; keep the K boards' + * 10000 us (t6050-k114-k116-display.dtsi). */ &dcp { apple,panel-video-open-delay-us = <10000>; From 4522dde38ec29525f2820ac54252c899cfd86e7b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:44:47 +1100 Subject: [PATCH 1469/1514] Revert "PCI: mark devices below a device tree external-facing port untrusted" This reverts merge c9f932450dea (#3213). It merged on an approval before the hardware rows its description lists as owed. It marks every device behind a USB4/Thunderbolt PCIe tunnel untrusted and removable on every Apple Silicon Mac, which turns on strict IOMMU handling and bounce buffering for them, and that has not run on a Mac yet. Reland it once a USB4 dock's PCIe devices (Ethernet, NVMe) and the built-in Wi-Fi have been checked on one Mac per USB4 generation. Signed-off-by: Ryan Murray --- drivers/pci/probe.c | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index d1bd1670841c9a..c38a60df06d81d 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -1736,20 +1735,6 @@ static void set_pcie_cxl(struct pci_dev *dev) } -/* - * Every bridge and endpoint below a port that the device tree marks - * "external-facing" is external to the machine, as the binding defines it. - * Unlike an ACPI ExternalFacingPort (see arch_pci_dev_is_removable()), no - * built-in controller sits below such a port. - */ -static bool pci_dev_below_of_external_port(struct pci_dev *dev) -{ - struct pci_dev *parent = pci_upstream_bridge(dev); - - return parent && parent->external_facing && - of_property_read_bool(parent->dev.of_node, "external-facing"); -} - static void set_pcie_untrusted(struct pci_dev *dev) { struct pci_dev *parent = pci_upstream_bridge(dev); @@ -1765,7 +1750,7 @@ static void set_pcie_untrusted(struct pci_dev *dev) return; } - if (arch_pci_dev_is_removable(dev) || pci_dev_below_of_external_port(dev)) { + if (arch_pci_dev_is_removable(dev)) { pci_dbg(dev, "marking as untrusted\n"); dev->untrusted = true; } @@ -1793,7 +1778,7 @@ static void pci_set_removable(struct pci_dev *dev) return; } - if (arch_pci_dev_is_removable(dev) || pci_dev_below_of_external_port(dev)) { + if (arch_pci_dev_is_removable(dev)) { pci_dbg(dev, "marking as removable\n"); dev_set_removable(&dev->dev, DEVICE_REMOVABLE); } From 354734e7da56dd1427dd9b39c9d2ddfd243eebee Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 15:47:03 +1100 Subject: [PATCH 1470/1514] arm64: dts: apple: t6050: select ATC2's USB4 router by a hardware macro ATC2's USB4/Thunderbolt router (ADT /arm-io/acio2 with its CPU and DART) was selected by two hand-kept board lists: a positive one in t6050-max.dtsi for the router and a negative one in t6050-peripherals.dtsi for the plain apciec2 DART. Adding a board meant editing both. Boards whose ADT has acio2 (J714c, J714s, J716c, K114c, K114s) now define T6050_ATC2_USB4_ROUTER before their includes, and both places test that. All T6050 DTBs are byte-identical before and after. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-j714s.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-j716c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-k114s.dts | 4 +++- arch/arm64/boot/dts/apple/t6050-max.dtsi | 4 ++-- arch/arm64/boot/dts/apple/t6050-peripherals.dtsi | 4 ++-- 7 files changed, 15 insertions(+), 5 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index 2909e86fc426ef..ff202d0d0ec0cf 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -15,6 +15,8 @@ /dts-v1/; #define T6050_J714C +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER #include #include "t6050-max.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index 3ed3baaf05fd59..23475ad163f58f 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -14,6 +14,8 @@ /dts-v1/; #define T6050_J714S +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER #include #include "t6050-max.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index 36575c200d534a..679e9f2f788563 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -14,6 +14,8 @@ /dts-v1/; #define T6050_J716C +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER #include "t6050-max.dtsi" #include "hwmon-fan-dual.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 495334da4a875f..c6957fef6b8b2e 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -11,6 +11,8 @@ /* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ #define T6050_K114C +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER /* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ #define T6050_K_N1_FIRMWARE "apple/centauri/k114c-ftab.bin" #define T6050_K_BOARD_ID 0x04 diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 417f6007e0119c..41059929b296eb 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -10,8 +10,10 @@ * Copyright The Asahi Linux Contributors */ -/* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ +/* Defined before the includes, which select this board's blocks on it. */ #define T6050_K114S +/* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ +#define T6050_ATC2_USB4_ROUTER /* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ #define T6050_K_N1_FIRMWARE "apple/centauri/k114s-ftab.bin" #define T6050_K_BOARD_ID 0x14 diff --git a/arch/arm64/boot/dts/apple/t6050-max.dtsi b/arch/arm64/boot/dts/apple/t6050-max.dtsi index 13d8950b5eca0b..b1a95aa559a5e5 100644 --- a/arch/arm64/boot/dts/apple/t6050-max.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-max.dtsi @@ -219,8 +219,8 @@ #endif }; -#if defined(T6050_J714C) || defined(T6050_J714S) || defined(T6050_J716C) || defined(T6050_K114C) || \ - defined(T6050_K114S) +/* Boards whose ADT has ATC2's USB4 router (acio2) define T6050_ATC2_USB4_ROUTER. */ +#ifdef T6050_ATC2_USB4_ROUTER /* * ATC2's USB4/Thunderbolt router (ADT /arm-io/acio2, acio-cpu2 and dart-acio2), powered per * connection: the PHY enters CIO mode, then the router's domains come on (ATC2_CIO, _PCIE, _USB, diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index cf9ba10059161b..9c8f5441a94a30 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -1617,8 +1617,8 @@ status = "disabled"; }; -#if !defined(T6050_J714C) && !defined(T6050_J714S) && !defined(T6050_J716C) && !defined(T6050_K114C) && \ - !defined(T6050_K114S) +/* With ATC2's USB4 router, t6050-max.dtsi describes this DART with the router instead. */ +#ifndef T6050_ATC2_USB4_ROUTER apciec2_dart: iommu@384000000 { compatible = "apple,t6050-dart", "apple,t8110-dart"; reg = <0x3 0x84000000 0x0 0x20000>; From dd9c868a904f934518380a04013dd6e132b0ac1d Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 00:25:38 -0500 Subject: [PATCH 1471/1514] drm/asahi: g17: use sub-ms hrtimer for rescan poll and never starve events When a G17 event pass leaves active work requiring a rescan (render_needs_rescan, compute retirement_polling, or outer_waiting), runtime_event_turn() previously: 1. Gated channel::Events::pending() behind else-if / !polling in both the fast and slow paths, skipping immediate queue_event_records() even when firmware had already written fresh completion records into the event ring. 2. Armed queue_poll() via queue_poll_after(1) -> msecs_to_jiffies(1), which sleeps a full jiffy (4 ms at CONFIG_HZ=250) on a delayed work item. Under sustained multi-render workloads (such as GTA V bursts filling RENDER_DEPTH = 32), completed renders and computes sat unretired for 3-4.8 ms waiting for the 1-jiffy timer while the GPU sat idle (~5% wall time). Replace queue_poll() with a coalesced sub-millisecond (50 us) intrusive HrTimer on Shared that queues queue_event_records() on expiry, keep the 1 ms POLL_WORK delayed work for render_control_backpressured() retry budget aging and sleep cancellation, cancel/disable the hrtimer on sleep, stop_runtime, and shutdown, and check channel::Events::pending() unconditionally in both paths of runtime_event_turn(). Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/mod.rs | 86 +++++- drivers/gpu/drm/asahi/g17/runtime.rs | 1 + drivers/gpu/drm/asahi/g17/runtime/events.rs | 10 +- drivers/gpu/drm/asahi/g17/sleep.rs | 1 + tools/asahi/g17-rescan-poll-tests.py | 311 ++++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 6 files changed, 408 insertions(+), 5 deletions(-) create mode 100755 tools/asahi/g17-rescan-poll-tests.py diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index f30bdc97d0b474..3a6430feaa1337 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -85,7 +85,7 @@ use kernel::{ c_str, device::{self, Core}, drm::gem::shmem, - impl_has_delayed_work, impl_has_work, + impl_has_delayed_work, impl_has_hr_timer, impl_has_work, io::{ IoBase, IoSysMap, @@ -97,13 +97,19 @@ use kernel::{ sync::{ aref::ARef, Arc, + ArcBorrow, CondVar, Mutex, // }, time::{ delay::fsleep, + hrtimer::{ + ArcHrTimerHandle, HrTimer, HrTimerCallback, HrTimerCallbackContext, HrTimerPointer, + HrTimerRestart, RelativeMode, + }, msecs_to_jiffies, - Delta, // + Delta, + Monotonic, // }, types::{ForeignOwnable, Opaque}, uapi, @@ -1328,6 +1334,14 @@ struct Shared { housekeeping_ns: AtomicU64, #[pin] poll: DelayedWork, + /// Active retirement rescan hrtimer, replacing 1-jiffy delayed-work waits while GPU work + /// stays in flight. + rescan_stopped: AtomicBool, + rescan_deadline_ns: AtomicU64, + #[pin] + rescan: HrTimer, + #[pin] + rescan_handle: Mutex>>, #[pin] idle: DelayedWork, #[pin] @@ -1396,6 +1410,26 @@ impl_has_work! { impl_has_delayed_work! { impl HasDelayedWork for Shared { self.poll } } +impl_has_hr_timer! { + impl HasHrTimer for Shared { + mode: RelativeMode, field: self.rescan + } +} +impl HrTimerCallback for Shared { + type Pointer<'a> = Arc; + + fn run(this: ArcBorrow<'_, Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart { + let this: Arc = this.into(); + this.rescan_deadline_ns.store(0, Ordering::Release); + if !this.sleeping() + && !this.rescan_stopped.load(Ordering::Acquire) + && !this.crashed.load(Ordering::Acquire) + { + this.queue_event_records(); + } + HrTimerRestart::NoRestart + } +} impl_has_delayed_work! { impl HasDelayedWork for Shared { self.idle } } @@ -1811,7 +1845,48 @@ impl Shared { } fn queue_poll(self: &Arc) { - self.queue_poll_after(1); + // Sub-ms retirement rescan hrtimer: avoids 1-jiffy (4 ms at HZ=250) stalls when a + // completion's stamps or ring cursors lag its event notification. + const RESCAN_POLL_US: i64 = 50; + const RESCAN_POLL_NS: u64 = (RESCAN_POLL_US as u64) * 1_000; + if !self.submission_enabled + || self.sleeping() + || self.rescan_stopped.load(Ordering::Acquire) + || self.crashed.load(Ordering::Acquire) + { + return; + } + let now = now_ns(); + let armed_ns = self.rescan_deadline_ns.load(Ordering::Acquire); + if armed_ns != 0 && armed_ns > now { + return; + } + let mut handle = self.rescan_handle.lock(); + if self.sleeping() + || self.rescan_stopped.load(Ordering::Acquire) + || self.crashed.load(Ordering::Acquire) + { + return; + } + let armed_ns = self.rescan_deadline_ns.load(Ordering::Acquire); + if armed_ns != 0 && armed_ns > now { + return; + } + drop(handle.take()); + self.rescan_deadline_ns + .store(now.saturating_add(RESCAN_POLL_NS), Ordering::Release); + *handle = Some(self.clone().start(Delta::from_micros(RESCAN_POLL_US))); + } + + fn cancel_rescan(&self) { + let mut handle = self.rescan_handle.lock(); + self.rescan_deadline_ns.store(0, Ordering::Release); + drop(handle.take()); + } + + fn disable_rescan(&self) { + self.rescan_stopped.store(true, Ordering::Release); + self.cancel_rescan(); } fn queue_poll_after(self: &Arc, delay_ms: u32) { @@ -2108,6 +2183,10 @@ impl Gpu { housekeeping: AtomicBool::new(true), housekeeping_ns: AtomicU64::new(0), poll <- new_delayed_work!("g17::Shared::poll"), + rescan_stopped: AtomicBool::new(false), + rescan_deadline_ns: AtomicU64::new(0), + rescan <- HrTimer::new(), + rescan_handle <- new_mutex!(None, "g17::Shared::rescan_handle"), idle <- new_delayed_work!("g17::Shared::idle"), housekeeping_timer <- new_delayed_work!("g17::Shared::housekeeping_timer"), governs: m5, @@ -2825,6 +2904,7 @@ impl Gpu { self.shared.feed.begin_shutdown(); self.shared.preparations.remove(); self.shared.stop_queues(); + self.shared.disable_rescan(); self.shared.disable_timer(&self.shared.poll); self.shared.disable_timer(&self.shared.idle); self.shared.disable_timer(&self.shared.housekeeping_timer); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index e64a10eb7d9458..35ec330a677d7b 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -4170,6 +4170,7 @@ impl super::Shared { /// mappings owned in state. Only a later joined stop may detach/free them. pub(super) fn stop_runtime(&self) { let Some(_stopping) = self.stop.try_lock() else { return; }; + self.disable_rescan(); { let mut state = self.state.lock(); if let Some(firmware) = state.as_deref_mut() { diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 593a57dd0f73c7..fe0bc01afc6e22 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -673,7 +673,11 @@ impl crate::g17::Shared { rescan || scan.polling || firmware.non_compute_runtime_polling(now); if polling { self.queue_poll(); - } else if channel::Events::pending(&firmware.init, Role::Primary)? + if firmware.render_control_backpressured() { + self.queue_poll_after(1); + } + } + if channel::Events::pending(&firmware.init, Role::Primary)? || (firmware.secondary.is_some() && channel::Events::pending(&firmware.init, Role::Secondary)?) { @@ -815,6 +819,9 @@ impl crate::g17::Shared { let polling = firmware.runtime_polling(now); if polling { self.queue_poll(); + if firmware.render_control_backpressured() { + self.queue_poll_after(1); + } } // A heap with growth to give back is re-evaluated at least once per // shrink period, also while the device is otherwise idle. @@ -843,7 +850,6 @@ impl crate::g17::Shared { self.preparations.close(); self.queue_events(); } else if !recover - && !polling && (channel::Events::pending(&firmware.init, Role::Primary)? || (firmware.secondary.is_some() && channel::Events::pending(&firmware.init, Role::Secondary)?)) diff --git a/drivers/gpu/drm/asahi/g17/sleep.rs b/drivers/gpu/drm/asahi/g17/sleep.rs index a88a881c5de664..17a21a88223a3c 100644 --- a/drivers/gpu/drm/asahi/g17/sleep.rs +++ b/drivers/gpu/drm/asahi/g17/sleep.rs @@ -315,6 +315,7 @@ impl Shared { /// With the sleeping flag set, joins whatever may be reading firmware state. The growth work /// isn't joined: it may be waiting on the closed gate, and can't publish while it is closed. fn join_event_workers(self: &Arc) { + self.cancel_rescan(); self.cancel_timer(&self.poll); self.cancel_timer(&self.idle); self.cancel_timer(&self.housekeeping_timer); diff --git a/tools/asahi/g17-rescan-poll-tests.py b/tools/asahi/g17-rescan-poll-tests.py new file mode 100755 index 00000000000000..db85177a8af98e --- /dev/null +++ b/tools/asahi/g17-rescan-poll-tests.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: G17 event rescan uses a sub-ms hrtimer and never starves pending event rings. + +Verifies: +1. Compiled production `Shared::queue_poll()`, `Shared::cancel_rescan()`, + `Shared::disable_rescan()`, and `HrTimerCallback::run()` from + `drivers/gpu/drm/asahi/g17/mod.rs`: + - `queue_poll()` arms the hrtimer for a sub-millisecond delay (`<= 100 us`), + coalesces duplicate calls while the deadline is still in the future without + acquiring `rescan_handle`, and re-arms once expired or cleared; + - `HrTimerCallback::run()` clears `rescan_deadline_ns`, queues + `queue_event_records()` when active, skips queuing when sleeping, stopped, + or crashed, and returns `HrTimerRestart::NoRestart`; + - `cancel_rescan()` and `disable_rescan()` drop the handle and clear the + deadline, and `disable_rescan()` blocks any later `queue_poll()`. +2. Structural checks on `runtime/events.rs`, `mod.rs`, `sleep.rs`, and `runtime.rs`: + - Neither the fast path nor the slow path of `runtime_event_turn()` gates + `channel::Events::pending()` behind `!polling` / `else if`; + - Both paths still arm `queue_poll_after(1)` when `render_control_backpressured()` + is true so the 1 ms retry budget on `POLL_WORK` is preserved; + - `join_event_workers()`, `stop_runtime()`, and `shutdown()` cancel or disable + the rescan hrtimer. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +MUTATIONS = { + 'starve-fast-pending': [( + 'events', + ' if polling {\n' + ' self.queue_poll();\n' + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }\n' + ' }\n' + ' if channel::Events::pending(&firmware.init, Role::Primary)?', + ' if polling {\n' + ' self.queue_poll();\n' + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }\n' + ' } else if channel::Events::pending(&firmware.init, Role::Primary)?', + )], + 'starve-slow-pending': [( + 'events', + ' } else if !recover\n' + ' && (channel::Events::pending(&firmware.init, Role::Primary)?', + ' } else if !recover\n' + ' && !polling\n' + ' && (channel::Events::pending(&firmware.init, Role::Primary)?', + )], + 'jiffy-poll': [( + 'mod', + 'const RESCAN_POLL_US: i64 = 50;', + 'const RESCAN_POLL_US: i64 = 4_000;', + )], + 'skip-backpressure-poll': [( + 'events', + ' if firmware.render_control_backpressured() {\n' + ' self.queue_poll_after(1);\n' + ' }', + '', + )], + 'skip-sleep-cancel': [( + 'sleep', + ' self.cancel_rescan();\n', + '', + )], + 'skip-shutdown-disable': [( + 'mod', + ' self.shared.disable_rescan();\n', + '', + )], +} + + +def build_harness(mutation=None): + files = { + 'mod': (G17 / 'mod.rs').read_text(), + 'events': (G17 / 'runtime/events.rs').read_text(), + 'sleep': (G17 / 'sleep.rs').read_text(), + 'runtime': (G17 / 'runtime.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, name) + files[name] = files[name].replace(old, new, 1) + + mod_src = files['mod'] + events_src = files['events'] + sleep_src = files['sleep'] + runtime_src = files['runtime'] + + queue_poll_fn = item(mod_src, 'fn queue_poll(self: &Arc)') + cancel_fn = item(mod_src, 'fn cancel_rescan(&self)') + disable_fn = item(mod_src, 'fn disable_rescan(&self)') + hrtimer_cb = item(mod_src, 'impl HrTimerCallback for Shared') + turn_fn = item(events_src, 'fn runtime_event_turn(') + join_fn = item(sleep_src, 'fn join_event_workers(self: &Arc)') + stop_fn = item(runtime_src, 'pub(super) fn stop_runtime(&self)') + shutdown_fn = item(mod_src, 'pub(crate) fn shutdown(&self)') + + fast_pending_unblocked = ( + '} else if channel::Events::pending(&firmware.init, Role::Primary)?' not in turn_fn + and 'if channel::Events::pending(&firmware.init, Role::Primary)?' in turn_fn + ) + slow_pending_unblocked = ( + '&& !polling\n && (channel::Events::pending(&firmware.init, Role::Primary)?' + not in turn_fn + and '} else if !recover\n && (channel::Events::pending(&firmware.init, Role::Primary)?' + in turn_fn + ) + backpressure_preserved = ( + turn_fn.count('if firmware.render_control_backpressured() {\n') == 2 + and turn_fn.count('self.queue_poll_after(1);') == 2 + ) + lifecycle_ok = ( + 'self.cancel_rescan();' in join_fn + and 'self.disable_rescan();' in stop_fn + and 'self.shared.disable_rescan();' in shutdown_fn + ) + + host_queue_poll = queue_poll_fn.replace('self.rescan_handle.lock()', 'self.lock_handle()') + host_cancel = cancel_fn.replace('self.rescan_handle.lock()', 'self.lock_handle()') + + return f''' +#![allow(dead_code, unused_variables, unused_imports)] +use std::sync::{{Arc, Mutex, MutexGuard, atomic::{{AtomicBool, AtomicU64, AtomicUsize, Ordering}}}}; + +static NOW_NS: AtomicU64 = AtomicU64::new(1_000_000); +fn now_ns() -> u64 {{ NOW_NS.load(Ordering::Acquire) }} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Delta(i64); +impl Delta {{ + fn from_micros(us: i64) -> Self {{ Self(us) }} +}} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HrTimerRestart {{ NoRestart, Restart }} + +struct ArcBorrow<'a, T>(&'a Arc); +impl<'a, T> From> for Arc {{ + fn from(b: ArcBorrow<'a, T>) -> Self {{ Arc::clone(b.0) }} +}} +struct HrTimerCallbackContext<'a, T>(std::marker::PhantomData<&'a T>); +trait HrTimerCallback {{ + type Pointer<'a>; + fn run(this: ArcBorrow<'_, Self>, ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart + where Self: Sized; +}} + +struct ArcHrTimerHandle {{ + shared: Arc, + delay_us: i64, + cancelled: Arc, +}} +impl Drop for ArcHrTimerHandle {{ + fn drop(&mut self) {{ + self.cancelled.fetch_add(1, Ordering::AcqRel); + }} +}} + +struct Shared {{ + submission_enabled: bool, + sleeping_flag: AtomicBool, + rescan_stopped: AtomicBool, + crashed: AtomicBool, + rescan_deadline_ns: AtomicU64, + rescan_handle: Mutex>>, + lock_trips: AtomicUsize, + starts: AtomicUsize, + last_delay_us: AtomicU64, + cancelled: Arc, + event_records: AtomicUsize, +}} + +impl Shared {{ + fn new() -> Arc {{ + Arc::new(Self {{ + submission_enabled: true, + sleeping_flag: AtomicBool::new(false), + rescan_stopped: AtomicBool::new(false), + crashed: AtomicBool::new(false), + rescan_deadline_ns: AtomicU64::new(0), + rescan_handle: Mutex::new(None), + lock_trips: AtomicUsize::new(0), + starts: AtomicUsize::new(0), + last_delay_us: AtomicU64::new(0), + cancelled: Arc::new(AtomicUsize::new(0)), + event_records: AtomicUsize::new(0), + }}) + }} + fn sleeping(&self) -> bool {{ self.sleeping_flag.load(Ordering::Acquire) }} + fn queue_event_records(self: &Arc) {{ + self.event_records.fetch_add(1, Ordering::AcqRel); + }} + fn lock_handle(&self) -> MutexGuard<'_, Option>> {{ + self.lock_trips.fetch_add(1, Ordering::AcqRel); + self.rescan_handle.lock().unwrap() + }} + fn start(self: Arc, delta: Delta) -> ArcHrTimerHandle {{ + self.starts.fetch_add(1, Ordering::AcqRel); + self.last_delay_us.store(delta.0 as u64, Ordering::Release); + let cancelled = Arc::clone(&self.cancelled); + ArcHrTimerHandle {{ shared: self, delay_us: delta.0, cancelled }} + }} + + {host_queue_poll} + + {host_cancel} + + {disable_fn} +}} + +{hrtimer_cb} + +fn main() {{ + assert!({str(fast_pending_unblocked).lower()}, "fast path starved pending events behind polling"); + assert!({str(slow_pending_unblocked).lower()}, "slow path starved pending events behind polling"); + assert!({str(backpressure_preserved).lower()}, "render_control_backpressured must still arm 1ms POLL_WORK"); + assert!({str(lifecycle_ok).lower()}, "sleep/stop/shutdown must cancel or disable rescan hrtimer"); + + let s = Shared::new(); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 1); + let delay = s.last_delay_us.load(Ordering::Acquire); + assert!(delay >= 10 && delay <= 100, "rescan hrtimer delay must be sub-ms (10..=100 us), got {{delay}}"); + assert_eq!(s.lock_trips.load(Ordering::Acquire), 1); + + // Coalescing while armed must skip rescan_handle lock completely. + NOW_NS.store(1_000_000 + delay * 500, Ordering::Release); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 1); + assert_eq!(s.lock_trips.load(Ordering::Acquire), 1); + + // Timer expiry clears deadline and queues event records without restarting. + let restart = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(restart, HrTimerRestart::NoRestart); + assert_eq!(s.rescan_deadline_ns.load(Ordering::Acquire), 0); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); + + // Re-arm after expiry succeeds and cancels old completed handle before starting. + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 2); + assert_eq!(s.cancelled.load(Ordering::Acquire), 1); + + // Sleep cancels handle and prevents callback or queue_poll from arming. + s.sleeping_flag.store(true, Ordering::Release); + s.cancel_rescan(); + assert_eq!(s.cancelled.load(Ordering::Acquire), 2); + assert_eq!(s.rescan_deadline_ns.load(Ordering::Acquire), 0); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 2); + let _ = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); + + // Wake allows re-arming again. + s.sleeping_flag.store(false, Ordering::Release); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 3); + + // Shutdown disables permanently and breaks the Arc self-reference. + s.disable_rescan(); + assert_eq!(s.cancelled.load(Ordering::Acquire), 3); + assert_eq!(Arc::strong_count(&s), 1); + s.queue_poll(); + assert_eq!(s.starts.load(Ordering::Acquire), 3); + let _ = Shared::run(ArcBorrow(&s), HrTimerCallbackContext(std::marker::PhantomData)); + assert_eq!(s.event_records.load(Ordering::Acquire), 1); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = parser.parse_args() + src = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-rescan-poll-') as tmp: + rs = Path(tmp) / 'test.rs' + exe = Path(tmp) / 'test' + rs.write_text(src) + subprocess.run(['rustc', '-O', str(rs), '-o', str(exe)], check=True) + res = subprocess.run([str(exe)], capture_output=True, text=True) + if res.returncode != 0: + sys.stderr.write(res.stdout + res.stderr) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 275634f6b61e85..04a0c1f09b1b31 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -373,6 +373,10 @@ def mutations(flag, names, base, expect=KILL): 'observe-in-recovery', 'collector-blocks', 'finish-under-mutex', 'no-pass-requested', 'rescan-no-poll', 'worker-rescan-slow-path', 'owed-slow-path'), []), + 'g17-rescan-poll-tests.py': [([], PASS)] + + mutations('--mutation', ('starve-fast-pending', 'starve-slow-pending', 'jiffy-poll', + 'skip-backpressure-poll', 'skip-sleep-cancel', + 'skip-shutdown-disable'), []), 'g17-render-direct-recovery-tests.py': [([], PASS)] + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', 'wrong-j813-pipe'), []), From 0569550b83525a995186af975c2bc7a5d6072aad Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 00:42:17 -0500 Subject: [PATCH 1472/1514] media: apple: avd: h264: support frame-based Annex-B stateless decode Enable V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED paired with V4L2_STATELESS_H264_START_CODE_ANNEX_B alongside the existing SLICE_BASED + START_CODE_NONE path so frame-based stateless clients (such as Chromium's V4L2VideoDecoderDelegateH264) can decode H.264 natively on Apple AVD without breaking FFmpeg, GStreamer, or libva-v4l2-request. - Relax V4L2_CID_STATELESS_H264_DECODE_MODE (SLICE_BASED..FRAME_BASED, default SLICE_BASED) and V4L2_CID_STATELESS_H264_START_CODE (NONE..ANNEX_B, default NONE) without rejecting updates while streaming, and validate mode/start-code pairing per frame in avd_h264_run(). - Tighten avd_h264_validate_sps() to bound log2_max_frame_num_minus4, pic_order_cnt_type, and log2_max_pic_order_cnt_lsb_minus4 while keeping avd_h264_validate_sps_fmt() permissive for pre-streaming format negotiation. - Add a standalone Annex-B NALU scanner and ITU-T H.264 7.3.3 slice header parser (avd-h264-parse.c/h) with EBSP->RBSP emulation prevention byte handling, ref_pic_list_modification(), pred_weight_table(), dec_ref_pic_marking(), and exact CABAC/CAVLC slice_data() offset computation. - Submit frame-based slices zero-copy directly from the OUTPUT DMA buffer via avd_h264_run_frame(), rejecting HOLD_CAPTURE_BUF and aborting any stale held slice-based bank on mode switch. - Add KUnit coverage for SPS bounds, Annex-B scanning, EBSP/RBSP bitreading, slice header fields, reference list modification, prediction weights, reference marking, and real libx264 Annex-B bitstreams, and update the host test harness accordingly. Signed-off-by: Erik Bourget --- drivers/media/platform/apple/avd/Makefile | 3 +- .../media/platform/apple/avd/avd-h264-parse.c | 730 +++++++++++ .../media/platform/apple/avd/avd-h264-parse.h | 52 + .../media/platform/apple/avd/avd-h264-test.c | 1120 ++++++++++++++++- drivers/media/platform/apple/avd/avd-h264.c | 226 +++- drivers/media/platform/apple/avd/avd-v4l2.c | 4 +- .../platform/apple/avd/tests/program-test.py | 9 +- 7 files changed, 2115 insertions(+), 29 deletions(-) create mode 100644 drivers/media/platform/apple/avd/avd-h264-parse.c create mode 100644 drivers/media/platform/apple/avd/avd-h264-parse.h diff --git a/drivers/media/platform/apple/avd/Makefile b/drivers/media/platform/apple/avd/Makefile index f4e0864a52b0ef..7f9e92551b99fb 100644 --- a/drivers/media/platform/apple/avd/Makefile +++ b/drivers/media/platform/apple/avd/Makefile @@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only -apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o avd-vp9.o \ +apple-avd-y := avd-drv.o avd-v4l2.o avd-hw.o avd-pm.o avd-h264.o \ + avd-h264-parse.o avd-vp9.o \ avd-hevc.o avd-av1.o avd-av1-entropymode.o avd-queue.o avd-backend-open.o \ avd-backend-apple.o avd-backend-queue.o avd-backend-kopsia.o apple-avd-$(CONFIG_VIDEO_APPLE_AVD_KUNIT_TEST) += avd-h264-test.o \ diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.c b/drivers/media/platform/apple/avd/avd-h264-parse.c new file mode 100644 index 00000000000000..8bbeca9a60696d --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-h264-parse.c @@ -0,0 +1,730 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Standalone H.264 Annex-B NALU scanner and ITU-T H.264 7.3.3 slice header + * parser for V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED on Apple AVD. + */ + +#include +#include +#include +#include +#include +#include + +#include "avd-h264-parse.h" + +#define AVD_H264_NAL_SLICE 1 +#define AVD_H264_NAL_DPA 2 +#define AVD_H264_NAL_DPB 3 +#define AVD_H264_NAL_DPC 4 +#define AVD_H264_NAL_IDR_SLICE 5 +#define AVD_H264_NAL_SEI 6 +#define AVD_H264_NAL_FILLER 12 +#define AVD_H264_NAL_PREFIX 14 +#define AVD_H264_NAL_EXT_SLICE 20 + +#define AVD_H264_MAX_MMCO_OPS 64 + +/* + * Scan an Annex-B byte stream for the next VCL slice NALU (types 1 and 5). + * Non-VCL NALUs (SEI, SPS, PPS, AUD, EOS, filler; types 6..12) are skipped. + * Forbidden-zero-bit violations, data partitioning (2..4), SVC/MVC (14, 20), + * and other unsupported NAL types return -EINVAL. + * + * Returns 1 when a slice NALU is written to @nalu, 0 at end of buffer, or + * -EINVAL on malformed Annex-B syntax or unsupported NAL unit types. + */ +int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, + struct avd_h264_nalu *nalu) +{ + u32 pos; + + if (!cursor || !nalu) + return -EINVAL; + if (!buf) + return len ? -EINVAL : 0; + + pos = *cursor; + while (pos < len) { + u32 zeros = 0; + u32 nal_start, end, i; + u8 hdr, nal_type; + + while (pos < len && buf[pos] == 0x00) { + zeros++; + pos++; + } + if (pos == len) { + *cursor = len; + return 0; + } + if (zeros < 2 || buf[pos] != 0x01) + return -EINVAL; + + nal_start = pos + 1; + if (nal_start >= len) + return -EINVAL; + + /* Find the next 0x00 0x00 0x01 start code prefix. */ + end = len; + i = nal_start; + while (len >= 3 && i <= len - 3) { + if (buf[i + 2] > 0x01) { + i += 3; + continue; + } + if (buf[i + 2] == 0x01 && buf[i] == 0x00 && + buf[i + 1] == 0x00) { + end = i; + break; + } + i++; + } + + *cursor = end; + pos = end; + + /* Strip trailing zero bytes (4-byte start code prefix / padding). */ + while (end > nal_start && buf[end - 1] == 0x00) + end--; + if (end == nal_start) + return -EINVAL; + + hdr = buf[nal_start]; + if (hdr & 0x80) + return -EINVAL; + + nal_type = hdr & 0x1f; + switch (nal_type) { + case AVD_H264_NAL_SLICE: + case AVD_H264_NAL_IDR_SLICE: + nalu->off = nal_start; + nalu->len = end - nal_start; + nalu->nal_ref_idc = (hdr >> 5) & 0x03; + nalu->nal_unit_type = nal_type; + return 1; + case AVD_H264_NAL_SEI ... AVD_H264_NAL_FILLER: + continue; + case AVD_H264_NAL_DPA ... AVD_H264_NAL_DPC: + case AVD_H264_NAL_PREFIX: + case AVD_H264_NAL_EXT_SLICE: + default: + return -EINVAL; + } + } + + *cursor = len; + return 0; +} + +VISIBLE_IF_KUNIT void avd_h264_br_init(struct avd_h264_br *br, const u8 *data, + u32 len, u32 pos) +{ + br->data = data; + br->len = len; + br->pos = pos; + br->rbsp_bits = 0; + br->bit = 0; + br->zeros = 0; + br->err = false; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_init); + +/* + * At a byte boundary immediately after two consecutive raw 0x00 bytes, an + * emulation prevention byte (0x03) belongs to the EBSP framing, not the RBSP. + */ +VISIBLE_IF_KUNIT void avd_h264_br_skip_epb(struct avd_h264_br *br) +{ + if (br->bit == 0 && br->zeros >= 2 && br->pos < br->len && + br->data[br->pos] == 0x03) { + br->pos++; + br->zeros = 0; + } +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_skip_epb); + +static u32 avd_h264_br_read_bit(struct avd_h264_br *br) +{ + u32 val; + u8 b; + + if (br->err) + return 0; + + if (br->bit == 0) { + avd_h264_br_skip_epb(br); + if (br->pos >= br->len) { + br->err = true; + return 0; + } + b = br->data[br->pos]; + if (b == 0x00) + br->zeros = min_t(u8, br->zeros + 1, 2); + else + br->zeros = 0; + } else { + b = br->data[br->pos]; + } + + val = (b >> (7 - br->bit)) & 1; + br->rbsp_bits++; + br->bit++; + if (br->bit == 8) { + br->bit = 0; + br->pos++; + } + + return val; +} + +VISIBLE_IF_KUNIT u32 avd_h264_br_read_bits(struct avd_h264_br *br, + unsigned int n) +{ + u32 val = 0; + + if (n == 0) + return 0; + if (n > 32) { + br->err = true; + return 0; + } + + while (n--) + val = (val << 1) | avd_h264_br_read_bit(br); + + return val; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_bits); + +VISIBLE_IF_KUNIT u32 avd_h264_br_read_ue(struct avd_h264_br *br) +{ + unsigned int zeros = 0; + u32 suffix; + + while (!br->err && !avd_h264_br_read_bit(br)) { + zeros++; + if (zeros >= 32) { + br->err = true; + return 0; + } + } + if (br->err || zeros == 0) + return 0; + + suffix = avd_h264_br_read_bits(br, zeros); + if (br->err) + return 0; + + if (zeros == 31) { + if (suffix > BIT(31)) { + br->err = true; + return 0; + } + return (BIT(31) - 1) + suffix; + } + + return ((1U << zeros) - 1) + suffix; +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_ue); + +VISIBLE_IF_KUNIT s32 avd_h264_br_read_se(struct avd_h264_br *br) +{ + u32 code = avd_h264_br_read_ue(br); + + if (br->err) + return 0; + if (code == U32_MAX) { + br->err = true; + return 0; + } + if (code & 1) + return (s32)((code >> 1) + 1); + + return -(s32)(code >> 1); +} +EXPORT_SYMBOL_IF_KUNIT(avd_h264_br_read_se); + +static int avd_h264_find_short_term_dpb(const struct v4l2_h264_dpb_entry *dpb, + u32 cur_frame_num, u32 max_pic_num, + s32 target_pic_num) +{ + for (unsigned int i = 0; i < V4L2_H264_NUM_DPB_ENTRIES; i++) { + s32 dpb_pic_num; + + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_ACTIVE)) + continue; + if (dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM) + continue; + if (dpb[i].frame_num >= max_pic_num) + continue; + + dpb_pic_num = dpb[i].frame_num; + if (dpb[i].frame_num > cur_frame_num) + dpb_pic_num -= (s32)max_pic_num; + + if (dpb_pic_num == target_pic_num) + return i; + } + + return -EINVAL; +} + +static int avd_h264_find_long_term_dpb(const struct v4l2_h264_dpb_entry *dpb, + u32 lt_pic_num) +{ + for (unsigned int i = 0; i < V4L2_H264_NUM_DPB_ENTRIES; i++) { + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_ACTIVE)) + continue; + if (!(dpb[i].flags & V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM)) + continue; + if (dpb[i].frame_num == lt_pic_num) + return i; + } + + return -EINVAL; +} + +/* H.264 7.3.3.1 & 8.2.4.3.1 for frame pictures (frame_mbs_only_flag == 1). */ +static int +avd_h264_parse_ref_list_mod(struct avd_h264_br *br, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_decode_params *decode, + u32 frame_num, struct v4l2_h264_reference *list, + u8 num_active_minus1) +{ + u32 max_pic_num = 1U << (sps->log2_max_frame_num_minus4 + 4); + u32 num_active = (u32)num_active_minus1 + 1; + s32 pic_num_pred = frame_num; + u32 ref_idx = 0; + + if (!avd_h264_br_read_bit(br)) + return br->err ? -EINVAL : 0; + + for (unsigned int ops = 0; ops < V4L2_H264_REF_LIST_LEN + 1; ops++) { + u32 idc = avd_h264_br_read_ue(br); + int target; + u32 c, n; + + if (br->err) + return -EINVAL; + if (idc == 3) + return 0; + if (idc > 3 || ref_idx >= num_active) + return -EINVAL; + + if (idc == 0 || idc == 1) { + u32 diff_minus1 = avd_h264_br_read_ue(br); + s32 diff, pic_num_no_wrap, pic_num; + + if (br->err || diff_minus1 >= max_pic_num) + return -EINVAL; + + diff = (s32)diff_minus1 + 1; + if (idc == 0) { + pic_num_no_wrap = pic_num_pred - diff; + if (pic_num_no_wrap < 0) + pic_num_no_wrap += (s32)max_pic_num; + } else { + pic_num_no_wrap = pic_num_pred + diff; + if (pic_num_no_wrap >= (s32)max_pic_num) + pic_num_no_wrap -= (s32)max_pic_num; + } + + pic_num_pred = pic_num_no_wrap; + if (pic_num_no_wrap > (s32)frame_num) + pic_num = pic_num_no_wrap - (s32)max_pic_num; + else + pic_num = pic_num_no_wrap; + + target = avd_h264_find_short_term_dpb(decode->dpb, + frame_num, + max_pic_num, + pic_num); + } else { + u32 lt_pic_num = avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + + target = avd_h264_find_long_term_dpb(decode->dpb, + lt_pic_num); + } + + if (target < 0) + return -EINVAL; + + for (c = num_active; c > ref_idx; c--) + list[c] = list[c - 1]; + + list[ref_idx].fields = V4L2_H264_FRAME_REF; + list[ref_idx].index = target; + ref_idx++; + + n = ref_idx; + for (c = ref_idx; c <= num_active; c++) { + if (list[c].index != target) + list[n++] = list[c]; + } + for (c = n; c <= num_active; c++) { + list[c].fields = 0; + list[c].index = 0xff; + } + } + + return -EINVAL; +} + +static int +avd_h264_parse_weight_entry(struct avd_h264_br *br, + struct v4l2_h264_weight_factors *wf, u32 i, + u32 luma_denom, u32 chroma_denom, bool chroma) +{ + if (avd_h264_br_read_bit(br)) { + s32 w = avd_h264_br_read_se(br); + s32 o = avd_h264_br_read_se(br); + + if (br->err || w < -128 || w > 127 || o < -128 || o > 127) + return -EINVAL; + wf->luma_weight[i] = w; + wf->luma_offset[i] = o; + } else { + wf->luma_weight[i] = 1 << luma_denom; + wf->luma_offset[i] = 0; + } + + if (!chroma) { + /* + * Keep monochrome chroma weights at the implicit identity + * (1 << 0) so stream_weights() does not emit chroma commands. + */ + wf->chroma_weight[i][0] = 1; + wf->chroma_weight[i][1] = 1; + wf->chroma_offset[i][0] = 0; + wf->chroma_offset[i][1] = 0; + return br->err ? -EINVAL : 0; + } + + if (!avd_h264_br_read_bit(br)) { + wf->chroma_weight[i][0] = 1 << chroma_denom; + wf->chroma_weight[i][1] = 1 << chroma_denom; + wf->chroma_offset[i][0] = 0; + wf->chroma_offset[i][1] = 0; + return br->err ? -EINVAL : 0; + } + + for (int j = 0; j < 2; j++) { + s32 w = avd_h264_br_read_se(br); + s32 o = avd_h264_br_read_se(br); + + if (br->err || w < -128 || w > 127 || o < -128 || o > 127) + return -EINVAL; + wf->chroma_weight[i][j] = w; + wf->chroma_offset[i][j] = o; + } + + return br->err ? -EINVAL : 0; +} + +/* H.264 7.3.3.2 prediction weight table. */ +static int +avd_h264_parse_pred_weight_table(struct avd_h264_br *br, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights) +{ + bool chroma = sps->chroma_format_idc != 0 && + !(sps->flags & V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE); + u32 luma_denom, chroma_denom = 0; + int nlists = sl->slice_type == V4L2_H264_SLICE_TYPE_B ? 2 : 1; + + luma_denom = avd_h264_br_read_ue(br); + if (br->err || luma_denom > 7) + return -EINVAL; + weights->luma_log2_weight_denom = luma_denom; + + if (chroma) { + chroma_denom = avd_h264_br_read_ue(br); + if (br->err || chroma_denom > 7) + return -EINVAL; + weights->chroma_log2_weight_denom = chroma_denom; + } + + for (int l = 0; l < nlists; l++) { + struct v4l2_h264_weight_factors *wf = &weights->weight_factors[l]; + u32 count = (l == 0 ? sl->num_ref_idx_l0_active_minus1 : + sl->num_ref_idx_l1_active_minus1) + 1; + + for (u32 i = 0; i < count; i++) { + int ret = avd_h264_parse_weight_entry(br, wf, i, + luma_denom, + chroma_denom, + chroma); + if (ret) + return ret; + } + } + + return br->err ? -EINVAL : 0; +} + +/* H.264 7.3.3.3 decoded reference picture marking. */ +static int avd_h264_parse_dec_ref_pic_marking(struct avd_h264_br *br, + u8 nal_unit_type) +{ + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE) { + avd_h264_br_read_bits(br, 2); + return br->err ? -EINVAL : 0; + } + + if (!avd_h264_br_read_bit(br)) + return br->err ? -EINVAL : 0; + + for (unsigned int ops = 0; ops < AVD_H264_MAX_MMCO_OPS; ops++) { + u32 op = avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + if (op == 0) + return 0; + if (op > 6) + return -EINVAL; + + if (op == 1 || op == 3) + avd_h264_br_read_ue(br); + if (op == 2) + avd_h264_br_read_ue(br); + if (op == 3 || op == 6) + avd_h264_br_read_ue(br); + if (op == 4) + avd_h264_br_read_ue(br); + + if (br->err) + return -EINVAL; + } + + return -EINVAL; +} + +int avd_h264_parse_slice_header(const u8 *nal, u32 nal_len, + u8 nal_ref_idc, u8 nal_unit_type, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_pps *pps, + const struct v4l2_ctrl_h264_decode_params *decode, + u8 num_init_refs, + const struct v4l2_h264_reference *init_p, + const struct v4l2_h264_reference *init_b0, + const struct v4l2_h264_reference *init_b1, + struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights, + u32 *slice_data_off, u8 *slice_bit_off) +{ + struct avd_h264_br br; + u32 total_mbs, slice_type, pps_id, frame_num; + s32 qp_delta; + u8 n_init; + int ret; + + memset(sl, 0, sizeof(*sl)); + memset(weights, 0, sizeof(*weights)); + for (unsigned int i = 0; i < V4L2_H264_REF_LIST_LEN; i++) { + sl->ref_pic_list0[i].index = 0xff; + sl->ref_pic_list1[i].index = 0xff; + } + + if (!nal || nal_len < 2 || !slice_data_off || !slice_bit_off) + return -EINVAL; + if (nal_unit_type != AVD_H264_NAL_SLICE && + nal_unit_type != AVD_H264_NAL_IDR_SLICE) + return -EINVAL; + if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)) + return -EINVAL; + if (sps->log2_max_frame_num_minus4 > 12 || sps->pic_order_cnt_type > 2) + return -EINVAL; + if (sps->pic_order_cnt_type == 0 && + sps->log2_max_pic_order_cnt_lsb_minus4 > 12) + return -EINVAL; + if (pps->num_slice_groups_minus1 != 0) + return -EINVAL; + + avd_h264_br_init(&br, nal, nal_len, 1); + + sl->first_mb_in_slice = avd_h264_br_read_ue(&br); + total_mbs = (u32)(sps->pic_width_in_mbs_minus1 + 1) * + (u32)(sps->pic_height_in_map_units_minus1 + 1); + if (br.err || sl->first_mb_in_slice >= total_mbs) + return -EINVAL; + + slice_type = avd_h264_br_read_ue(&br); + if (br.err || slice_type > 9) + return -EINVAL; + slice_type %= 5; + if (slice_type != V4L2_H264_SLICE_TYPE_P && + slice_type != V4L2_H264_SLICE_TYPE_B && + slice_type != V4L2_H264_SLICE_TYPE_I) + return -EINVAL; + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE && + slice_type != V4L2_H264_SLICE_TYPE_I) + return -EINVAL; + sl->slice_type = slice_type; + + pps_id = avd_h264_br_read_ue(&br); + if (br.err || pps_id > 255) + return -EINVAL; + + if (sps->flags & V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE) + sl->colour_plane_id = avd_h264_br_read_bits(&br, 2); + + frame_num = avd_h264_br_read_bits(&br, sps->log2_max_frame_num_minus4 + 4); + + if (nal_unit_type == AVD_H264_NAL_IDR_SLICE) { + u32 idr_pic_id = avd_h264_br_read_ue(&br); + + if (br.err || idr_pic_id > 65535) + return -EINVAL; + } + + if (sps->pic_order_cnt_type == 0) { + avd_h264_br_read_bits(&br, + sps->log2_max_pic_order_cnt_lsb_minus4 + 4); + if (pps->flags & + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT) + avd_h264_br_read_se(&br); + } else if (sps->pic_order_cnt_type == 1 && + !(sps->flags & V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO)) { + avd_h264_br_read_se(&br); + if (pps->flags & + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT) + avd_h264_br_read_se(&br); + } + + if (pps->flags & V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT) { + u32 redundant_pic_cnt = avd_h264_br_read_ue(&br); + + if (br.err || redundant_pic_cnt > 0) + return -EINVAL; + sl->redundant_pic_cnt = redundant_pic_cnt; + } + + if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (avd_h264_br_read_bit(&br)) + sl->flags |= V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED; + } + + if (slice_type == V4L2_H264_SLICE_TYPE_P || + slice_type == V4L2_H264_SLICE_TYPE_B) { + u32 num_l0 = pps->num_ref_idx_l0_default_active_minus1; + u32 num_l1 = pps->num_ref_idx_l1_default_active_minus1; + + if (avd_h264_br_read_bit(&br)) { + num_l0 = avd_h264_br_read_ue(&br); + if (slice_type == V4L2_H264_SLICE_TYPE_B) + num_l1 = avd_h264_br_read_ue(&br); + } + if (br.err || num_l0 > 15) + return -EINVAL; + sl->num_ref_idx_l0_active_minus1 = num_l0; + + if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (num_l1 > 15) + return -EINVAL; + sl->num_ref_idx_l1_active_minus1 = num_l1; + } + } + + if (br.err) + return -EINVAL; + + n_init = min_t(u8, num_init_refs, V4L2_H264_REF_LIST_LEN); + if (slice_type == V4L2_H264_SLICE_TYPE_P) { + if (init_p && n_init) + memcpy(sl->ref_pic_list0, init_p, + n_init * sizeof(sl->ref_pic_list0[0])); + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list0, + sl->num_ref_idx_l0_active_minus1); + if (ret) + return ret; + } else if (slice_type == V4L2_H264_SLICE_TYPE_B) { + if (init_b0 && n_init) + memcpy(sl->ref_pic_list0, init_b0, + n_init * sizeof(sl->ref_pic_list0[0])); + if (init_b1 && n_init) + memcpy(sl->ref_pic_list1, init_b1, + n_init * sizeof(sl->ref_pic_list1[0])); + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list0, + sl->num_ref_idx_l0_active_minus1); + if (ret) + return ret; + ret = avd_h264_parse_ref_list_mod(&br, sps, decode, frame_num, + sl->ref_pic_list1, + sl->num_ref_idx_l1_active_minus1); + if (ret) + return ret; + } + + if (V4L2_H264_CTRL_PRED_WEIGHTS_REQUIRED(pps, sl)) { + ret = avd_h264_parse_pred_weight_table(&br, sps, sl, weights); + if (ret) + return ret; + } + + if (nal_ref_idc != 0) { + ret = avd_h264_parse_dec_ref_pic_marking(&br, nal_unit_type); + if (ret) + return ret; + } + + if ((pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) && + slice_type != V4L2_H264_SLICE_TYPE_I) { + u32 cabac_init_idc = avd_h264_br_read_ue(&br); + + if (br.err || cabac_init_idc > 2) + return -EINVAL; + sl->cabac_init_idc = cabac_init_idc; + } + + qp_delta = avd_h264_br_read_se(&br); + if (br.err || qp_delta < S8_MIN || qp_delta > S8_MAX) + return -EINVAL; + sl->slice_qp_delta = qp_delta; + + if (pps->flags & V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT) { + u32 idc = avd_h264_br_read_ue(&br); + + if (br.err || idc > 2) + return -EINVAL; + sl->disable_deblocking_filter_idc = idc; + if (idc != 1) { + s32 alpha = avd_h264_br_read_se(&br); + s32 beta = avd_h264_br_read_se(&br); + + if (br.err || alpha < -6 || alpha > 6 || + beta < -6 || beta > 6) + return -EINVAL; + sl->slice_alpha_c0_offset_div2 = alpha; + sl->slice_beta_offset_div2 = beta; + } + } + + if (br.err) + return -EINVAL; + + sl->header_bit_size = 8 + br.rbsp_bits; + + if (pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) { + if (br.bit) { + br.pos++; + br.bit = 0; + } + } + + avd_h264_br_skip_epb(&br); + if (br.pos >= nal_len) + return -EINVAL; + + *slice_data_off = br.pos; + *slice_bit_off = br.bit; + return 0; +} diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.h b/drivers/media/platform/apple/avd/avd-h264-parse.h new file mode 100644 index 00000000000000..e6789a4e3da1de --- /dev/null +++ b/drivers/media/platform/apple/avd/avd-h264-parse.h @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * H.264 Annex-B NALU scanner and slice header parser for Apple AVD. + */ +#ifndef AVD_H264_PARSE_H +#define AVD_H264_PARSE_H + +#include +#include + +struct avd_h264_nalu { + u32 off; + u32 len; + u8 nal_ref_idc; + u8 nal_unit_type; +}; + +struct avd_h264_br { + const u8 *data; + u32 len; + u32 pos; + u32 rbsp_bits; + u8 bit; + u8 zeros; + bool err; +}; + +int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, + struct avd_h264_nalu *nalu); + +int avd_h264_parse_slice_header(const u8 *nal, u32 nal_len, + u8 nal_ref_idc, u8 nal_unit_type, + const struct v4l2_ctrl_h264_sps *sps, + const struct v4l2_ctrl_h264_pps *pps, + const struct v4l2_ctrl_h264_decode_params *decode, + u8 num_init_refs, + const struct v4l2_h264_reference *init_p, + const struct v4l2_h264_reference *init_b0, + const struct v4l2_h264_reference *init_b1, + struct v4l2_ctrl_h264_slice_params *sl, + struct v4l2_ctrl_h264_pred_weights *weights, + u32 *slice_data_off, u8 *slice_bit_off); + +#if IS_ENABLED(CONFIG_KUNIT) +void avd_h264_br_init(struct avd_h264_br *br, const u8 *data, u32 len, u32 pos); +u32 avd_h264_br_read_bits(struct avd_h264_br *br, unsigned int n); +u32 avd_h264_br_read_ue(struct avd_h264_br *br); +s32 avd_h264_br_read_se(struct avd_h264_br *br); +void avd_h264_br_skip_epb(struct avd_h264_br *br); +#endif + +#endif /* AVD_H264_PARSE_H */ diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index 0ffc5ac66d15ba..d4cbd2f20a04d5 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -1,13 +1,16 @@ // SPDX-License-Identifier: GPL-2.0 /* - * KUnit tests for the H.264 slice checks of the Apple video decoder. + * KUnit tests for the H.264 slice checks and Annex-B parser of the Apple + * video decoder. */ #include #include #include +#include #include "avd.h" +#include "avd-h264-parse.h" struct avd_slice_data_case { const char *desc; @@ -226,6 +229,45 @@ static void avd_sps_fmt_init_test(struct kunit *test) KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), -EINVAL); } +static void avd_sps_range_test(struct kunit *test) +{ + struct v4l2_ctrl_h264_sps sps = { + .chroma_format_idc = 1, + .pic_width_in_mbs_minus1 = 3, + .pic_height_in_map_units_minus1 = 3, + .flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY, + }; + struct avd_ctx *ctx; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->coded_fmt.fmt.pix_mp.width = 64; + ctx->coded_fmt.fmt.pix_mp.height = 64; + + sps.log2_max_frame_num_minus4 = 12; + sps.pic_order_cnt_type = 0; + sps.log2_max_pic_order_cnt_lsb_minus4 = 12; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); + + sps.log2_max_frame_num_minus4 = 13; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps_fmt(ctx, &sps), 0); + + sps.log2_max_frame_num_minus4 = 0; + sps.pic_order_cnt_type = 3; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + sps.pic_order_cnt_type = 0; + sps.log2_max_pic_order_cnt_lsb_minus4 = 13; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), -EINVAL); + + /* log2_max_pic_order_cnt_lsb_minus4 is ignored when poc_type != 0 */ + sps.pic_order_cnt_type = 1; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); + sps.pic_order_cnt_type = 2; + KUNIT_EXPECT_EQ(test, avd_h264_validate_sps(ctx, &sps), 0); +} + static void avd_start_slices_test(struct kunit *test) { struct v4l2_ctrl_h264_sps sps = { @@ -270,13 +312,1089 @@ static void avd_scaling_flat_test(struct kunit *test) KUNIT_EXPECT_FALSE(test, avd_h264_scaling_is_flat(&pps, m)); } +/* Simple bit writer for synthesizing H.264 slice header bitstreams in tests. */ +struct avd_test_bw { + u8 buf[256]; + u32 pos; + u8 bit; + u8 zeros; + bool epb; +}; + +static void bw_init(struct avd_test_bw *bw, u8 nal_hdr, bool epb) +{ + memset(bw, 0, sizeof(*bw)); + bw->buf[0] = nal_hdr; + bw->pos = 1; + bw->epb = epb; +} + +static void bw_put_byte(struct avd_test_bw *bw, u8 b) +{ + if (bw->epb && bw->zeros >= 2 && b <= 0x03) { + bw->buf[bw->pos++] = 0x03; + bw->zeros = 0; + } + bw->buf[bw->pos++] = b; + bw->zeros = b == 0x00 ? min_t(u8, bw->zeros + 1, 2) : 0; +} + +static void bw_put_bit(struct avd_test_bw *bw, u32 v) +{ + if (v & 1) + bw->buf[bw->pos] |= 1U << (7 - bw->bit); + bw->bit++; + if (bw->bit == 8) { + u8 finished = bw->buf[bw->pos]; + + bw->buf[bw->pos] = 0; + bw->bit = 0; + bw_put_byte(bw, finished); + } +} + +static void bw_put_bits(struct avd_test_bw *bw, u32 v, unsigned int n) +{ + while (n--) + bw_put_bit(bw, (v >> n) & 1); +} + +static void bw_put_ue(struct avd_test_bw *bw, u32 v) +{ + u32 code = v + 1; + unsigned int bits = fls(code); + unsigned int zeros = bits - 1; + + bw_put_bits(bw, 0, zeros); + bw_put_bits(bw, code, bits); +} + +static void bw_put_se(struct avd_test_bw *bw, s32 v) +{ + u32 code = v <= 0 ? (u32)(-2 * v) : (u32)(2 * v - 1); + + bw_put_ue(bw, code); +} + +static u32 bw_finish(struct avd_test_bw *bw, bool cabac, u8 tail_byte) +{ + if (cabac) { + while (bw->bit != 0) + bw_put_bit(bw, 1); + } else if (bw->bit != 0) { + u8 finished = bw->buf[bw->pos] | ((1U << (8 - bw->bit)) - 1); + + bw->buf[bw->pos] = 0; + bw->bit = 0; + bw_put_byte(bw, finished); + } + bw_put_byte(bw, tail_byte); + return bw->pos; +} + +static void avd_annexb_scanner_test(struct kunit *test) +{ + /* AUD(9), SPS(7), PPS(8), SEI(6), EOS(10/11), Filler(12), then 2 slices */ + static const u8 multi[] = { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, + 0x00, 0x00, 0x00, 0x01, 0x67, 0x4d, 0x40, + 0x00, 0x00, 0x01, 0x68, 0xee, + 0x00, 0x00, 0x01, 0x06, 0x05, 0x80, + 0x00, 0x00, 0x01, 0x0a, + 0x00, 0x00, 0x01, 0x0b, + 0x00, 0x00, 0x01, 0x0c, 0xff, 0x80, + 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x41, 0x9a, 0x20, 0x00, 0x00, + }; + struct avd_h264_nalu nalu = {}; + u32 cursor = 0; + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_EXPECT_EQ(test, nalu.len, 3); + KUNIT_EXPECT_EQ(test, multi[nalu.off], 0x65); + KUNIT_EXPECT_EQ(test, multi[nalu.off + nalu.len - 1], 0x84); + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 1); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 2); + KUNIT_EXPECT_EQ(test, nalu.len, 3); + KUNIT_EXPECT_EQ(test, multi[nalu.off], 0x41); + KUNIT_EXPECT_EQ(test, multi[nalu.off + nalu.len - 1], 0x20); + + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(multi, sizeof(multi), + &cursor, &nalu), 0); + + /* Rejected cases: forbidden_zero_bit, DPA/B/C (2,3,4), SVC/MVC (14,20) */ + static const u8 bad_hdrs[] = { 0xe5, 0x89, 0x22, 0x23, 0x24, 0x2e, 0x34, 0x00 }; + + for (unsigned int i = 0; i < ARRAY_SIZE(bad_hdrs); i++) { + u8 buf[] = { 0x00, 0x00, 0x01, bad_hdrs[i], 0x80 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(buf, sizeof(buf), + &cursor, &nalu), -EINVAL); + } + + /* Missing start code, truncated start code, empty NALU between start codes */ + { + static const u8 no_sc[] = { 0x65, 0x88, 0x84 }; + static const u8 trunc_sc[] = { 0x00, 0x00, 0x01 }; + static const u8 empty_nal[] = { 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x65, 0x88 }; + static const u8 only_non_vcl[] = { 0x00, 0x00, 0x00, 0x01, 0x09, 0x10 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(no_sc, sizeof(no_sc), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(trunc_sc, sizeof(trunc_sc), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(empty_nal, sizeof(empty_nal), + &cursor, &nalu), -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, avd_h264_next_nalu(only_non_vcl, sizeof(only_non_vcl), + &cursor, &nalu), 0); + } +} + +static void avd_bitreader_epb_test(struct kunit *test) +{ + /* + * EBSP: 00 00 03 00 00 03 03 00 00 03 01 + * RBSP: 00 00 00 00 03 00 00 01 + */ + static const u8 ebsp[] = { + 0x65, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x03, 0x01, + }; + struct avd_h264_br br; + + avd_h264_br_init(&br, ebsp, sizeof(ebsp), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0x0000); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0x0000); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 8), 0x03); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 24), 0x000001); + KUNIT_EXPECT_FALSE(test, br.err); + /* Reading one more bit triggers truncation error. */ + avd_h264_br_read_bits(&br, 1); + KUNIT_EXPECT_TRUE(test, br.err); + + /* Exp-Golomb ue(v) and se(v) round-trip */ + { + struct avd_test_bw bw; + static const s32 se_vals[] = { 0, 1, -1, 2, -2, 127, -128 }; + u32 len; + + bw_init(&bw, 0x65, true); + bw_put_ue(&bw, 0); + bw_put_ue(&bw, 1); + bw_put_ue(&bw, 2); + bw_put_ue(&bw, 15); + bw_put_ue(&bw, 255); + for (unsigned int i = 0; i < ARRAY_SIZE(se_vals); i++) + bw_put_se(&bw, se_vals[i]); + len = bw_finish(&bw, true, 0xaa); + + avd_h264_br_init(&br, bw.buf, len, 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 0); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 2); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 15); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_ue(&br), 255); + for (unsigned int i = 0; i < ARRAY_SIZE(se_vals); i++) + KUNIT_EXPECT_EQ(test, avd_h264_br_read_se(&br), se_vals[i]); + KUNIT_EXPECT_FALSE(test, br.err); + } + + /* >= 32 leading zeros in ue(v) must error */ + { + static const u8 bad_ue[] = { + 0x65, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x80, + }; + + avd_h264_br_init(&br, bad_ue, sizeof(bad_ue), 1); + avd_h264_br_read_ue(&br); + KUNIT_EXPECT_TRUE(test, br.err); + } +} + +struct avd_parse_test_ctx { + struct v4l2_ctrl_h264_sps sps; + struct v4l2_ctrl_h264_pps pps; + struct v4l2_ctrl_h264_decode_params decode; + struct v4l2_ctrl_h264_slice_params sl; + struct v4l2_ctrl_h264_pred_weights weights; + struct v4l2_h264_reflist_builder builder; + struct v4l2_h264_reference init_p[V4L2_H264_REF_LIST_LEN]; + struct v4l2_h264_reference init_b0[V4L2_H264_REF_LIST_LEN]; + struct v4l2_h264_reference init_b1[V4L2_H264_REF_LIST_LEN]; + struct avd_test_bw bw; +}; + +static struct avd_parse_test_ctx *avd_parse_test_alloc(struct kunit *test) +{ + struct avd_parse_test_ctx *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->sps.pic_width_in_mbs_minus1 = 3; + t->sps.pic_height_in_map_units_minus1 = 3; + t->sps.flags = V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY; + return t; +} + +static void avd_slice_hdr_epb_boundary_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_br br; + u32 data_off, nal_len; + u8 bit_off; + + t->sps.log2_max_frame_num_minus4 = 12; + t->sps.pic_order_cnt_type = 0; + t->sps.log2_max_pic_order_cnt_lsb_minus4 = 12; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + + /* Direct byte-boundary EPB skip test */ + { + static const u8 boundary_epb[] = { 0x65, 0x00, 0x00, 0x03, 0x01 }; + static const u8 trunc_epb[] = { 0x65, 0x00, 0x00, 0x03 }; + + avd_h264_br_init(&br, boundary_epb, sizeof(boundary_epb), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0); + KUNIT_EXPECT_EQ(test, br.pos, 3); + KUNIT_EXPECT_EQ(test, br.bit, 0); + avd_h264_br_skip_epb(&br); + KUNIT_EXPECT_EQ(test, br.pos, 4); + KUNIT_EXPECT_EQ(test, br.data[br.pos], 0x01); + + avd_h264_br_init(&br, trunc_epb, sizeof(trunc_epb), 1); + KUNIT_EXPECT_EQ(test, avd_h264_br_read_bits(&br, 16), 0); + avd_h264_br_skip_epb(&br); + KUNIT_EXPECT_EQ(test, br.pos, sizeof(trunc_epb)); + } + + /* Slice header containing EPBs in 16-bit frame_num & poc_lsb (CABAC) */ + bw_init(&t->bw, 0x65, true); + bw_put_ue(&t->bw, 0); /* first_mb_in_slice */ + bw_put_ue(&t->bw, 2); /* I slice */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 0, 16); /* frame_num = 0 -> creates 00 00 03 */ + bw_put_ue(&t->bw, 0); /* idr_pic_id */ + bw_put_bits(&t->bw, 0, 16); /* pic_order_cnt_lsb = 0 -> creates 00 00 03 */ + bw_put_bits(&t->bw, 0, 2); /* dec_ref_pic_marking */ + bw_put_se(&t->bw, -3); /* slice_qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xcd); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -3); + KUNIT_EXPECT_EQ(test, bit_off, 0); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, t->bw.buf[data_off], 0xcd); + + /* Same header with CAVLC preserves non-zero bit_off */ + t->pps.flags = 0; + bw_init(&t->bw, 0x65, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 16); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 16); + bw_put_bits(&t->bw, 0, 2); + bw_put_se(&t->bw, 0); /* 1+3+1+16+1+16+2+1 = 41 RBSP bits (bit_off=1) */ + nal_len = bw_finish(&t->bw, false, 0xef); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 8 + 41); + KUNIT_EXPECT_EQ(test, bit_off, 1); + KUNIT_EXPECT_LT(test, data_off, nal_len); + + /* Header ending right at nal_len with no slice_data must fail */ + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, data_off, 3, 5, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_fields_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.pic_order_cnt_type = 1; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT | + V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + t->init_b0[0] = (struct v4l2_h264_reference){ + .fields = V4L2_H264_FRAME_REF, .index = 2, + }; + t->init_b0[1] = (struct v4l2_h264_reference){ + .fields = V4L2_H264_FRAME_REF, .index = 5, + }; + memcpy(t->init_b1, t->init_b0, sizeof(t->init_b1)); + + /* Pre-fill output structs with garbage to verify unconditional zeroing. */ + memset(&t->sl, 0x5a, sizeof(t->sl)); + memset(&t->weights, 0x5a, sizeof(t->weights)); + + /* Non-IDR B slice (type 6 -> normalized to B=1), POC type 1 + bottom, CABAC */ + bw_init(&t->bw, 0x21, true); + bw_put_ue(&t->bw, 4); /* first_mb_in_slice */ + bw_put_ue(&t->bw, 6); /* slice_type 6 -> B (1) */ + bw_put_ue(&t->bw, 12); /* pps_id */ + bw_put_bits(&t->bw, 3, 4); /* frame_num */ + bw_put_se(&t->bw, -4); /* delta_pic_order_cnt[0] */ + bw_put_se(&t->bw, 2); /* delta_pic_order_cnt[1] */ + bw_put_ue(&t->bw, 0); /* redundant_pic_cnt = 0 */ + bw_put_bit(&t->bw, 1); /* direct_spatial_mv_pred_flag */ + bw_put_bit(&t->bw, 1); /* num_ref_idx_active_override_flag */ + bw_put_ue(&t->bw, 1); /* num_ref_idx_l0_active_minus1 */ + bw_put_ue(&t->bw, 0); /* num_ref_idx_l1_active_minus1 */ + bw_put_bit(&t->bw, 0); /* ref_pic_list_modification_flag_l0 */ + bw_put_bit(&t->bw, 0); /* ref_pic_list_modification_flag_l1 */ + bw_put_bit(&t->bw, 0); /* adaptive_ref_pic_marking_mode_flag */ + bw_put_ue(&t->bw, 2); /* cabac_init_idc */ + bw_put_se(&t->bw, -5); /* slice_qp_delta */ + bw_put_ue(&t->bw, 2); /* disable_deblocking_filter_idc */ + bw_put_se(&t->bw, -6); /* slice_alpha_c0_offset_div2 */ + bw_put_se(&t->bw, 6); /* slice_beta_offset_div2 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 1, 1, + &t->sps, &t->pps, &t->decode, + 2, t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 4); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_B); + KUNIT_EXPECT_EQ(test, t->sl.flags, V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l0_active_minus1, 1); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l1_active_minus1, 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 2); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[1].index, 5); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[2].index, 0xff); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 2); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -5); + KUNIT_EXPECT_EQ(test, t->sl.disable_deblocking_filter_idc, 2); + KUNIT_EXPECT_EQ(test, t->sl.slice_alpha_c0_offset_div2, -6); + KUNIT_EXPECT_EQ(test, t->sl.slice_beta_offset_div2, 6); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 0); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Reject SP/SI slice types (3, 4, 8, 9) and > 9 */ + { + static const u32 bad_types[] = { 3, 4, 8, 9, 10 }; + + for (unsigned int i = 0; i < ARRAY_SIZE(bad_types); i++) { + bw_init(&t->bw, 0x21, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, bad_types[i]); + bw_put_ue(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 1, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + } + } + + /* Reject redundant_pic_cnt > 0 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 0, 4); + bw_put_se(&t->bw, 0); + bw_put_se(&t->bw, 0); + bw_put_ue(&t->bw, 1); /* redundant_pic_cnt > 0 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* Reject out-of-range cabac_init_idc (3), num_ref_idx (16), alpha (-7) */ + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + t->sps.pic_order_cnt_type = 2; + + /* num_ref_idx_l0_active_minus1 = 16 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 1); /* override */ + bw_put_ue(&t->bw, 16); /* > 15 */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* cabac_init_idc = 3 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); /* no override */ + bw_put_bit(&t->bw, 0); /* no reflist mod */ + bw_put_ue(&t->bw, 3); /* invalid cabac_init_idc */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* alpha = -7 -> reject */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); /* I */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_se(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* deblock idc = 0 */ + bw_put_se(&t->bw, -7); /* out of [-6, 6] */ + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_ref_mod_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.log2_max_frame_num_minus4 = 0; /* MaxPicNum = 16 */ + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 3; + t->pps.num_ref_idx_l1_default_active_minus1 = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + t->decode.frame_num = 1; + t->decode.top_field_order_cnt = 10; + t->decode.bottom_field_order_cnt = 10; + + /* + * DPB with short-term wraparound (frame_num=15 -> PicNum=-1, 14 -> -2, + * 0 -> 0) and a long-term reference (long_term_frame_idx=3) at slot 6. + * Current frame_num = 1. + */ + t->decode.dpb[1] = (struct v4l2_h264_dpb_entry){ + .frame_num = 0, .top_field_order_cnt = 8, .bottom_field_order_cnt = 8, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[3] = (struct v4l2_h264_dpb_entry){ + .frame_num = 15, .top_field_order_cnt = 6, .bottom_field_order_cnt = 6, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[4] = (struct v4l2_h264_dpb_entry){ + .frame_num = 14, .top_field_order_cnt = 12, .bottom_field_order_cnt = 12, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE, + }; + t->decode.dpb[6] = (struct v4l2_h264_dpb_entry){ + .frame_num = 3, .top_field_order_cnt = 2, .bottom_field_order_cnt = 2, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID | V4L2_H264_DPB_ENTRY_FLAG_ACTIVE | + V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM, + }; + /* Inactive entry that must NOT be matched */ + t->decode.dpb[9] = (struct v4l2_h264_dpb_entry){ + .frame_num = 13, + .flags = V4L2_H264_DPB_ENTRY_FLAG_VALID, + }; + + v4l2_h264_init_reflist_builder(&t->builder, &t->decode, &t->sps, + t->decode.dpb); + v4l2_h264_build_p_ref_list(&t->builder, t->init_p); + v4l2_h264_build_b_ref_lists(&t->builder, t->init_b0, t->init_b1); + /* Initial P list: short-term descending (1, 3, 4), then long-term (6). */ + KUNIT_ASSERT_EQ(test, t->builder.num_valid, 4); + KUNIT_ASSERT_EQ(test, t->init_p[0].index, 1); + KUNIT_ASSERT_EQ(test, t->init_p[1].index, 3); + KUNIT_ASSERT_EQ(test, t->init_p[2].index, 4); + KUNIT_ASSERT_EQ(test, t->init_p[3].index, 6); + + /* + * Modify P L0: + * idc=2, lt=3 -> slot 6 at index 0 + * idc=0, diff_minus1=2 -> pred=1 - 3 = -2 -> wrap +16 = 14 -> slot 4 at index 1 + * idc=1, diff_minus1=0 -> pred=14 + 1 = 15 -> slot 3 at index 2 + * idc=3 -> end + * Expected final L0: [6, 4, 3, 1]. + */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 1, 4); /* frame_num = 1 */ + bw_put_bit(&t->bw, 0); /* no num_ref_idx override (4 active) */ + bw_put_bit(&t->bw, 1); /* ref_pic_list_modification_flag_l0 */ + bw_put_ue(&t->bw, 2); /* long-term */ + bw_put_ue(&t->bw, 3); /* lt_pic_num = 3 -> slot 6 */ + bw_put_ue(&t->bw, 0); /* sub */ + bw_put_ue(&t->bw, 2); /* diff=3 -> pic_num_no_wrap=14 -> slot 4 */ + bw_put_ue(&t->bw, 1); /* add */ + bw_put_ue(&t->bw, 0); /* diff=1 -> pic_num_no_wrap=15 -> slot 3 */ + bw_put_ue(&t->bw, 3); /* end */ + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 0); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 6); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[1].index, 4); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[2].index, 3); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[3].index, 1); + + /* Referencing an inactive DPB entry (frame_num=13, slot 9) must fail */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 1); /* mod L0 */ + bw_put_ue(&t->bw, 0); /* sub */ + bw_put_ue(&t->bw, 3); /* diff=4 -> 1 - 4 + 16 = 13 (inactive!) */ + bw_put_ue(&t->bw, 3); + bw_put_ue(&t->bw, 0); + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* B slice modifying both L0 and L1 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 1); /* B */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 1); /* direct_spatial */ + bw_put_bit(&t->bw, 1); /* override */ + bw_put_ue(&t->bw, 1); /* L0 active = 2 */ + bw_put_ue(&t->bw, 1); /* L1 active = 2 */ + bw_put_bit(&t->bw, 1); /* mod L0 */ + bw_put_ue(&t->bw, 2); /* long-term 3 -> slot 6 */ + bw_put_ue(&t->bw, 3); + bw_put_ue(&t->bw, 3); /* end L0 */ + bw_put_bit(&t->bw, 1); /* mod L1 */ + bw_put_ue(&t->bw, 0); /* sub diff=1 -> frame_num=0 -> slot 1 */ + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 3); /* end L1 */ + bw_put_ue(&t->bw, 1); /* cabac_init_idc */ + bw_put_se(&t->bw, 2); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xbb); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + t->builder.num_valid, + t->init_p, t->init_b0, t->init_b1, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list0[0].index, 6); + KUNIT_EXPECT_EQ(test, t->sl.ref_pic_list1[0].index, 1); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 1); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 2); +} + +static void avd_slice_hdr_pred_weights_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED; + + /* B slice with explicit weights (L0 has 2 refs: explicit + default; L1 has 1 ref) */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 1); /* B */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 2, 4); /* frame_num */ + bw_put_bit(&t->bw, 1); /* direct_spatial */ + bw_put_bit(&t->bw, 0); /* no override (L0=2, L1=1) */ + bw_put_bit(&t->bw, 0); /* no L0 mod */ + bw_put_bit(&t->bw, 0); /* no L1 mod */ + /* pred_weight_table() */ + bw_put_ue(&t->bw, 5); /* luma_log2_weight_denom */ + bw_put_ue(&t->bw, 4); /* chroma_log2_weight_denom */ + /* L0[0]: explicit luma & chroma */ + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 40); + bw_put_se(&t->bw, -10); + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 20); + bw_put_se(&t->bw, 3); + bw_put_se(&t->bw, -128); + bw_put_se(&t->bw, 127); + /* L0[1]: default luma & chroma */ + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + /* L1[0]: explicit luma, default chroma */ + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 12); + bw_put_se(&t->bw, 5); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 0); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 5); + KUNIT_EXPECT_EQ(test, t->weights.chroma_log2_weight_denom, 4); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[0], 40); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[0], -10); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][0], 20); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_offset[0][0], 3); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][1], -128); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_offset[0][1], 127); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[1], 32); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[1], 0); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[1][0], 16); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[1][1], 16); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].luma_weight[0], 12); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].luma_offset[0], 5); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[1].chroma_weight[0][0], 16); + + /* Monochrome P slice: no chroma denom or chroma weight bits in stream */ + t->sps.chroma_format_idc = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 0; + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); /* P */ + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); /* no override */ + bw_put_bit(&t->bw, 0); /* no mod */ + bw_put_ue(&t->bw, 3); /* luma_denom only */ + bw_put_bit(&t->bw, 1); /* luma_flag */ + bw_put_se(&t->bw, 10); + bw_put_se(&t->bw, -2); + bw_put_ue(&t->bw, 0); /* cabac_init_idc */ + bw_put_se(&t->bw, 1); /* qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xcc); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->weights.luma_log2_weight_denom, 3); + KUNIT_EXPECT_EQ(test, t->weights.chroma_log2_weight_denom, 0); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_weight[0], 10); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].luma_offset[0], -2); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][0], 1); + KUNIT_EXPECT_EQ(test, t->weights.weight_factors[0].chroma_weight[0][1], 1); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 1); + + /* Reject denom > 7 and weight > 127 */ + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 8); /* invalid denom */ + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + bw_init(&t->bw, 0x01, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 1, 4); + bw_put_bit(&t->bw, 0); + bw_put_bit(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_bit(&t->bw, 1); + bw_put_se(&t->bw, 128); /* out of [-128, 127] */ + bw_put_se(&t->bw, 0); + nal_len = bw_finish(&t->bw, true, 0xaa); + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 0, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_marking_test(struct kunit *test) +{ + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + u32 data_off, nal_len; + u8 bit_off; + + t->sps.pic_order_cnt_type = 2; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE; + + /* Adaptive MMCO with all opcodes 1..6 terminated by 0 */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); /* first_mb */ + bw_put_ue(&t->bw, 2); /* I (non-IDR) */ + bw_put_ue(&t->bw, 0); /* pps_id */ + bw_put_bits(&t->bw, 5, 4); /* frame_num */ + bw_put_bit(&t->bw, 1); /* adaptive_ref_pic_marking_mode_flag */ + bw_put_ue(&t->bw, 1); /* op 1: diff_minus1 */ + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 2); /* op 2: lt_pic_num */ + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 3); /* op 3: diff_minus1, lt_frame_idx */ + bw_put_ue(&t->bw, 1); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 4); /* op 4: max_lt_frame_idx_plus1 */ + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 5); /* op 5: no args */ + bw_put_ue(&t->bw, 6); /* op 6: lt_frame_idx */ + bw_put_ue(&t->bw, 1); + bw_put_ue(&t->bw, 0); /* end */ + bw_put_se(&t->bw, -4); /* slice_qp_delta */ + nal_len = bw_finish(&t->bw, true, 0xdd); + + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, -4); + KUNIT_EXPECT_EQ(test, data_off, nal_len - 1); + KUNIT_EXPECT_EQ(test, t->bw.buf[data_off], 0xdd); + + /* Reject MMCO op > 6 */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 5, 4); + bw_put_bit(&t->bw, 1); + bw_put_ue(&t->bw, 7); /* invalid MMCO op */ + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); + + /* Reject > 64 MMCO ops without terminator */ + bw_init(&t->bw, 0x41, true); + bw_put_ue(&t->bw, 0); + bw_put_ue(&t->bw, 2); + bw_put_ue(&t->bw, 0); + bw_put_bits(&t->bw, 5, 4); + bw_put_bit(&t->bw, 1); + for (unsigned int i = 0; i < 65; i++) + bw_put_ue(&t->bw, 5); + nal_len = bw_finish(&t->bw, true, 0xaa); + + KUNIT_EXPECT_EQ(test, + avd_h264_parse_slice_header(t->bw.buf, nal_len, 2, 1, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + -EINVAL); +} + +static void avd_slice_hdr_real_annexb_test(struct kunit *test) +{ + /* + * Real Annex-B NALUs (64x64 4:2:0) produced by libx264: + * 1) Main profile CABAC: AUD + IDR I-slice, P-slice (weighted_pred=1), + * and non-ref B-slice (poc_type=0, deblocking=1). + * 2) Baseline profile CAVLC: 2-slice IDR and 2-slice P-frame + * (poc_type=2, deblocking=1). + */ + static const u8 cabac_idr[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x10, + 0x00, 0x00, 0x01, + 0x65, 0x88, 0x84, 0x00, 0x87, 0x69, 0xd7, 0xdc, + }; + static const u8 cabac_p[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x30, + 0x00, 0x00, 0x01, + 0x41, 0x9a, 0x29, 0xb1, 0x09, 0x7f, 0xd1, 0x64, + }; + static const u8 cabac_b[] = { + 0x00, 0x00, 0x00, 0x01, 0x09, 0x50, + 0x00, 0x00, 0x01, + 0x01, 0x9e, 0x45, 0xe4, 0x2d, 0xff, 0x90, 0x87, + }; + static const u8 cavlc_2slice_idr[] = { + 0x00, 0x00, 0x01, + 0x65, 0x88, 0x84, 0x08, 0x7c, 0x42, 0x22, 0xb0, + 0x00, 0x00, 0x01, + 0x65, 0x12, 0x22, 0x10, 0x77, 0xf1, 0xff, 0x87, + }; + static const u8 cavlc_2slice_p[] = { + 0x00, 0x00, 0x00, 0x01, + 0x41, 0x9a, 0x20, 0x21, 0xfc, 0x9c, 0x3e, 0xf7, + 0x00, 0x00, 0x01, + 0x41, 0x12, 0x68, 0x80, 0x87, 0xac, 0x21, 0xf8, + }; + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_nalu nalu; + u32 cursor, data_off; + u8 bit_off; + + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.num_ref_idx_l1_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 2; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + /* Main CABAC IDR */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_idr, sizeof(cabac_idr), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Main CABAC P-slice (weighted_pred_flag=1) */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_p, sizeof(cabac_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_P); + KUNIT_EXPECT_EQ(test, t->sl.num_ref_idx_l0_active_minus1, 0); + KUNIT_EXPECT_EQ(test, t->sl.cabac_init_idc, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 9); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 44); + KUNIT_EXPECT_EQ(test, data_off, 6); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Main CABAC B-slice (nal_ref_idc=0) */ + cursor = 0; + KUNIT_ASSERT_EQ(test, avd_h264_next_nalu(cabac_b, sizeof(cabac_b), + &cursor, &nalu), 1); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 0); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cabac_b + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_B); + KUNIT_EXPECT_EQ(test, t->sl.flags, V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 11); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 42); + KUNIT_EXPECT_EQ(test, data_off, 6); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* Baseline CAVLC 2-slice IDR */ + t->sps.pic_order_cnt_type = 2; + t->pps.num_ref_idx_l0_default_active_minus1 = 0; + t->pps.weighted_bipred_idc = 0; + t->pps.flags = V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 36); + KUNIT_EXPECT_EQ(test, data_off, 4); + KUNIT_EXPECT_EQ(test, bit_off, 4); + + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 8); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 7); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + KUNIT_EXPECT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_idr, sizeof(cavlc_2slice_idr), + &cursor, &nalu), 0); + + /* Baseline CAVLC 2-slice P-frame */ + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_p, sizeof(cavlc_2slice_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_P); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 34); + KUNIT_EXPECT_EQ(test, data_off, 4); + KUNIT_EXPECT_EQ(test, bit_off, 2); + + KUNIT_ASSERT_EQ(test, + avd_h264_next_nalu(cavlc_2slice_p, sizeof(cavlc_2slice_p), + &cursor, &nalu), 1); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(cavlc_2slice_p + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.first_mb_in_slice, 8); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, t->sl.header_bit_size, 40); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); +} + static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE(avd_scaling_flat_test), KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), KUNIT_CASE_PARAM(avd_slice_fits_test, avd_slice_fits_gen_params), KUNIT_CASE_PARAM(avd_sps_size_test, avd_sps_size_gen_params), KUNIT_CASE(avd_sps_fmt_init_test), + KUNIT_CASE(avd_sps_range_test), KUNIT_CASE(avd_start_slices_test), + KUNIT_CASE(avd_annexb_scanner_test), + KUNIT_CASE(avd_bitreader_epb_test), + KUNIT_CASE(avd_slice_hdr_epb_boundary_test), + KUNIT_CASE(avd_slice_hdr_fields_test), + KUNIT_CASE(avd_slice_hdr_ref_mod_test), + KUNIT_CASE(avd_slice_hdr_pred_weights_test), + KUNIT_CASE(avd_slice_hdr_marking_test), + KUNIT_CASE(avd_slice_hdr_real_annexb_test), {} }; diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 89c12e5fb8f524..6d756f73112584 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -23,6 +23,7 @@ #include "avd.h" #include "avd-inst.h" #include "avd-h264-params.h" +#include "avd-h264-parse.h" #define H264_SCL_DIMS (0x1000000 | ((64 / 4) << 5) | (((16 / 4) << 5) - 1)) @@ -53,6 +54,8 @@ struct avd_h264_run { dma_addr_t mv_color; } addresses; + s32 decode_mode; + s32 start_code; s32 cur_poc; u8 num_valid; u32 slice_data_off; @@ -498,29 +501,22 @@ static u32 avd_h264_header_len(const struct avd_h264_run *run) return (run->slice_params->header_bit_size + (cabac ? 7 : 0)) / 8; } -static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) +static void stream_slice_data(struct avd_ctx *ctx, struct avd_h264_run *run, + dma_addr_t data_dma, u32 data_len, u8 bit_off) { const struct v4l2_ctrl_h264_decode_params *decode = run->decode_params; const struct v4l2_ctrl_h264_pps *pps = run->pps; const struct v4l2_ctrl_h264_sps *sps = run->sps; const struct v4l2_ctrl_h264_slice_params *sl = run->slice_params; - struct avd_h264_ctx *h264_ctx = ctx->priv; - u32 payload_len = h264_ctx->b->active_slice->size; - bool en_mode = (pps->flags & V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE) == - 0; - u32 off = run->slice_data_off; - - dma_addr_t slc_a84 = h264_ctx->b->active_slice->addr + off; push(AVD_OP_CODED_DATA | - AVD_OP_CODED_DATA_BIT_OFF( - en_mode ? (sl->header_bit_size % 8) : 0) | - AVD_OP_CODED_DATA_ADDR(slc_a84 >> 32), + AVD_OP_CODED_DATA_BIT_OFF(bit_off) | + AVD_OP_CODED_DATA_ADDR(data_dma >> 32), "slc_a7c_cmd_set_coded_slice"); - push((u32)(slc_a84 & 0xffffffff), "slc_a84_slice_addr_low"); + push((u32)(data_dma & 0xffffffff), "slc_a84_slice_addr_low"); /* should not include trailing 0? */ - push(payload_len - off, "slc_a88_slice_hdr_size"); + push(data_len, "slc_a88_slice_hdr_size"); push(AVD_OP_SL_LOC | AVD_OP_SL_LOC_Y(sl->first_mb_in_slice / @@ -609,6 +605,19 @@ static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) } } +static void stream_slice(struct avd_ctx *ctx, struct avd_h264_run *run) +{ + struct avd_h264_ctx *h264_ctx = ctx->priv; + u32 payload_len = h264_ctx->b->active_slice->size; + bool cavlc = !(run->pps->flags & + V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE); + u32 off = run->slice_data_off; + + stream_slice_data(ctx, run, h264_ctx->b->active_slice->addr + off, + payload_len - off, + cavlc ? (run->slice_params->header_bit_size % 8) : 0); +} + static int avd_h264_alloc_bufs(struct avd_ctx *ctx, struct avd_bank *bank) { struct avd_dev *dev = ctx->dev; @@ -749,6 +758,11 @@ VISIBLE_IF_KUNIT int avd_h264_validate_sps(struct avd_ctx *ctx, if (!(sps->flags & V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY)) /* no interlaced support */ return -EINVAL; + if (sps->log2_max_frame_num_minus4 > 12 || sps->pic_order_cnt_type > 2) + return -EINVAL; + if (sps->pic_order_cnt_type == 0 && + sps->log2_max_pic_order_cnt_lsb_minus4 > 12) + return -EINVAL; return 0; } @@ -894,7 +908,11 @@ static int avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) * parameters, and the controls can be set again at any time: use * copies. */ - if (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_PARAMS, + if (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_MODE, + &run->decode_mode, sizeof(run->decode_mode)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_START_CODE, + &run->start_code, sizeof(run->start_code)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_DECODE_PARAMS, &h264_ctx->params.decode_params, sizeof(h264_ctx->params.decode_params)) || avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SPS, @@ -903,15 +921,18 @@ static int avd_h264_run_preamble(struct avd_ctx *ctx, struct avd_h264_run *run) avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PPS, &h264_ctx->params.pps, sizeof(h264_ctx->params.pps)) || - avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SLICE_PARAMS, - &h264_ctx->params.slice_params, - sizeof(h264_ctx->params.slice_params)) || avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SCALING_MATRIX, &h264_ctx->params.scaling_matrix, - sizeof(h264_ctx->params.scaling_matrix)) || - avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PRED_WEIGHTS, - &h264_ctx->params.pred_weights, - sizeof(h264_ctx->params.pred_weights))) + sizeof(h264_ctx->params.scaling_matrix))) + return -EINVAL; + + if (run->decode_mode == V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED && + (avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_SLICE_PARAMS, + &h264_ctx->params.slice_params, + sizeof(h264_ctx->params.slice_params)) || + avd_ctrl_copy(ctx, V4L2_CID_STATELESS_H264_PRED_WEIGHTS, + &h264_ctx->params.pred_weights, + sizeof(h264_ctx->params.pred_weights)))) return -EINVAL; run->decode_params = &h264_ctx->params.decode_params; @@ -1104,6 +1125,135 @@ static void avd_h264_abort_picture(struct avd_ctx *ctx, buf->bank = 0; } +static int avd_h264_run_frame(struct avd_ctx *ctx, struct avd_h264_run *run) +{ + struct avd_h264_ctx *h264_ctx = ctx->priv; + struct v4l2_h264_reflist_builder reflist_builder; + struct avd_h264_nalu nalu; + size_t max_slices, num_slices, slice_idx; + u32 payload_len, cursor, last_mb; + const u8 *data; + bool is_idr = false; + int ret; + + /* Abort any stale unfinished slice-based picture if mode switched. */ + if (h264_ctx->b->busy && !h264_ctx->b->submitted) { + struct avd_decoded_buffer *dst_buf = + vb2_to_avd_decoded_buf(&run->base.bufs.dst->vb2_buf); + + if (dst_buf->bank == h264_ctx->b - h264_ctx->bank + 1) + dst_buf->bank = 0; + avd_h264_drop_bank_slices(ctx, h264_ctx->b); + h264_ctx->b->busy = false; + } + kvfree(ctx->job.segments); + ctx->job.segments = NULL; + + if (run->base.bufs.src->flags & V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF) { + dev_dbg_ratelimited(ctx->dev->dev, + "HOLD_CAPTURE_BUF is unsupported in frame-based H.264 mode\n"); + return -EINVAL; + } + + payload_len = vb2_get_plane_payload(&run->base.bufs.src->vb2_buf, 0); + data = vb2_plane_vaddr(&run->base.bufs.src->vb2_buf, 0); + if (!data || !payload_len) + return -EINVAL; + + max_slices = avd_h264_max_slices(run->sps); + cursor = 0; + num_slices = 0; + while ((ret = avd_h264_next_nalu(data, payload_len, &cursor, &nalu)) > 0) { + num_slices++; + if (num_slices > max_slices) { + dev_err_ratelimited(ctx->dev->dev, + "too many slices in H.264 frame, dropping it\n"); + return -EINVAL; + } + } + if (ret < 0 || !num_slices) { + dev_dbg_ratelimited(ctx->dev->dev, + "no valid H.264 slice NALUs in Annex-B buffer\n"); + return -EINVAL; + } + + ret = avd_h264_pick_bank(ctx, run->base.bufs.dst); + if (ret) + return ret; + + h264_ctx->b->monochrome = run->sps->chroma_format_idc == 0; + + ret = avd_init_job(ctx, AVD_CODEC_H264, num_slices + 1); + if (ret) + return ret; + + v4l2_h264_init_reflist_builder(&reflist_builder, run->decode_params, + run->sps, run->decode_params->dpb); + run->num_valid = avd_h264_num_refs(run->decode_params); + run->cur_poc = reflist_builder.cur_pic_order_count; + + v4l2_h264_build_p_ref_list(&reflist_builder, h264_ctx->reflists.p); + v4l2_h264_build_b_ref_lists(&reflist_builder, h264_ctx->reflists.b0, + h264_ctx->reflists.b1); + + cursor = 0; + slice_idx = 0; + last_mb = 0; + while ((ret = avd_h264_next_nalu(data, payload_len, &cursor, &nalu)) > 0) { + u32 slice_data_off; + u8 slice_bit_off; + + if (slice_idx == 0) + is_idr = nalu.nal_unit_type == 5; + else if ((nalu.nal_unit_type == 5) != is_idr) + return -EINVAL; + + ret = avd_h264_parse_slice_header(data + nalu.off, nalu.len, + nalu.nal_ref_idc, + nalu.nal_unit_type, + run->sps, run->pps, + run->decode_params, + reflist_builder.num_valid, + h264_ctx->reflists.p, + h264_ctx->reflists.b0, + h264_ctx->reflists.b1, + &h264_ctx->params.slice_params, + &h264_ctx->params.pred_weights, + &slice_data_off, + &slice_bit_off); + if (ret) + return ret; + + if (!avd_h264_slice_order_supported(slice_idx, last_mb, + run->slice_params->first_mb_in_slice)) { + dev_err_ratelimited(ctx->dev->dev, + "H.264 arbitrary slice order (ASO) is unsupported\n"); + return -EINVAL; + } + + if (!avd_h264_refs_valid(run)) { + dev_dbg_ratelimited(ctx->dev->dev, + "slice references an invalid DPB entry, dropping frame\n"); + return -EINVAL; + } + + if (slice_idx == 0) + stream_hdr(ctx, run); + + ctx->job.num++; + stream_slice_data(ctx, run, + run->base.coded_in + nalu.off + slice_data_off, + nalu.len - slice_data_off, slice_bit_off); + + last_mb = run->slice_params->first_mb_in_slice; + slice_idx++; + } + if (ret < 0 || slice_idx != num_slices) + return -EINVAL; + + return 0; +} + static int avd_h264_run(struct avd_ctx *ctx) { struct avd_h264_ctx *h264_ctx = ctx->priv; @@ -1124,8 +1274,38 @@ static int avd_h264_run(struct avd_ctx *ctx) avd_h264_sps_image_fmt(run.sps)); if (!ret) ret = avd_h264_validate_pps(ctx, run.pps); - if (!ret) - ret = avd_h264_validate_slice(ctx, run.slice_params); + if (ret) + goto err_free_jobs; + + if (run.decode_mode == V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED) { + /* + * Frame-based stateless clients (for example Chromium's V4L2 + * H.264 delegate) may set DECODE_MODE=FRAME_BASED while + * leaving START_CODE at the driver default (START_CODE_NONE) + * and still emit Annex-B start codes in the OUTPUT buffer. + * Annex-B framing is still validated in avd_h264_run_frame(). + */ + if (run.start_code != V4L2_STATELESS_H264_START_CODE_ANNEX_B && + run.start_code != V4L2_STATELESS_H264_START_CODE_NONE) { + ret = -EINVAL; + goto err_free_jobs; + } + ret = avd_h264_run_frame(ctx, &run); + if (ret) + goto err_free_jobs; + avd_run_postamble(ctx, &run.base); + ctx->job_fifo = h264_ctx->b->bufs.inst.addr; + h264_ctx->b->submitted = true; + return avd_submit_job(ctx); + } + + if (run.decode_mode != V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED || + run.start_code != V4L2_STATELESS_H264_START_CODE_NONE) { + ret = -EINVAL; + goto err_free_jobs; + } + + ret = avd_h264_validate_slice(ctx, run.slice_params); if (ret) goto err_free_jobs; diff --git a/drivers/media/platform/apple/avd/avd-v4l2.c b/drivers/media/platform/apple/avd/avd-v4l2.c index 04553b2dc29afb..17205b5e172bd8 100644 --- a/drivers/media/platform/apple/avd/avd-v4l2.c +++ b/drivers/media/platform/apple/avd/avd-v4l2.c @@ -332,13 +332,13 @@ static const struct avd_ctrl_desc avd_h264_ctrl_descs[] = { { .cfg.id = V4L2_CID_STATELESS_H264_DECODE_MODE, .cfg.min = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, - .cfg.max = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + .cfg.max = V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, .cfg.def = V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, }, { .cfg.id = V4L2_CID_STATELESS_H264_START_CODE, .cfg.min = V4L2_STATELESS_H264_START_CODE_NONE, - .cfg.max = V4L2_STATELESS_H264_START_CODE_NONE, + .cfg.max = V4L2_STATELESS_H264_START_CODE_ANNEX_B, .cfg.def = V4L2_STATELESS_H264_START_CODE_NONE, }, { diff --git a/drivers/media/platform/apple/avd/tests/program-test.py b/drivers/media/platform/apple/avd/tests/program-test.py index 77db961856499d..842d75ecb7d081 100755 --- a/drivers/media/platform/apple/avd/tests/program-test.py +++ b/drivers/media/platform/apple/avd/tests/program-test.py @@ -539,12 +539,17 @@ def prepare_regressions(out): inst = re.sub(r'^#include.*\n', '', (ROOT / 'avd-inst.h').read_text(), flags=re.M) helpers = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-params.h').read_text(), flags=re.M) pre = h264_prelude().replace('struct vb2_v4l2_buffer *dst; } bufs;', 'struct vb2_v4l2_buffer *src,*dst; } bufs;') + pre = pre.replace('dma_addr_t comp_out, y_out, uv_out;', 'dma_addr_t coded_in, comp_out, y_out, uv_out;') pre = pre.replace('struct { struct { struct { struct { u32 bytesperline; } plane_fmt[1]; } pix_mp; } fmt; } decoded_fmt;', 'struct { struct { struct v4l2_pix_format_mplane pix_mp; } fmt; } decoded_fmt,coded_fmt;') pre = pre.replace('struct vb2_buffer vb2_buf; };', 'struct vb2_buffer vb2_buf; unsigned int flags; };') pre = pre.replace('unsigned int bank; };', 'unsigned int bank; size_t grey_chroma_offset; bool grey_chroma_10bit; };') + pre += '#define S8_MIN (-128)\n#define S8_MAX 127\n#define U32_MAX UINT32_MAX\n' + pre += '#define IS_ENABLED(x) 0\n' pre += 'enum vb2_buffer_state { VB2_BUF_STATE_DONE, VB2_BUF_STATE_ERROR };\n' - code = pre + helpers + inst + h264 + parse_h = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-parse.h').read_text(), flags=re.M) + parse_c = re.sub(r'^#include.*\n', '', (ROOT / 'avd-h264-parse.c').read_text(), flags=re.M) + code = pre + helpers + parse_h + parse_c + inst + h264 for name in ('avd_h264_alloc_bufs', 'avd_h264_validate_sps_fmt', 'avd_h264_validate_sps', 'avd_h264_validate_pps', 'avd_h264_validate_slice', 'avd_h264_drop_bank_slices', 'avd_h264_pick_bank', @@ -554,7 +559,7 @@ def prepare_regressions(out): code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_check_sps_geometry') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps_fmt') code += function((ROOT / 'avd-hevc.c').read_text(), 'avd_hevc_validate_sps') - code += RUN_FIXTURE + function(source, 'avd_h264_sps_image_fmt') + function(source, 'avd_h264_run') + RUN_MAIN + code += RUN_FIXTURE + function(source, 'avd_h264_sps_image_fmt') + function(source, 'avd_h264_run_frame') + function(source, 'avd_h264_run') + RUN_MAIN dest = out / 'prepare.c' dest.write_text(code) exe = dest.with_suffix('') From 0e4972eea0be12ce816e165ccbabc4a1e6817fdf Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:06:09 +1100 Subject: [PATCH 1473/1514] arm64: dts: apple: t6050: share the K boards' PMU RTC, add K114c, K114s and K116c Only the K116s described the PMU's RTC and alarm. The K114c, K114s and K116c had the SMC's RTC only, so they had no alarm to wake a firmware sleep from. The four boards' ADTs (27.2) give the PMU, nub-spmi0/spmi-abbeyL1, the same RTC registers: info-rtc 0x2002, info-rtc_alarm_ctrl 0x2000, info-rtc_alarm_offset 0x2008, info-rtc_irq_mask_offset 0x200e, info-rtc_scrpad 0x2100 and info-clock_offset <0x2100 6>, the T6041 PMU's layout. The live K114s ADT has the same values. So the K116s node moves into t6050-k114-k116.dtsi unchanged. The K116s DTB and the other T6050 DTBs are byte-identical; K114c, K114s and K116c gain only the rtc node under the PMU. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi | 17 +++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k116s.dts | 16 ---------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index d26d2621b38a0a..d09519d17008b5 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -198,6 +198,23 @@ }; }; +/* + * The PMU's RTC and its alarm. The four boards' ADTs (27.2) give the PMU + * (nub-spmi0/spmi-abbeyL1) the same registers: info-rtc (0x2002), + * info-rtc_alarm_offset (0x2008), info-rtc_irq_mask_offset (0x200e), + * info-rtc_alarm_ctrl (0x2000) and info-rtc_scrpad (0x2100), the registers of + * the T6041 PMU. It raises no interrupt on this SoC: an armed alarm can only + * wake the machine from a firmware sleep, not from s2idle. + */ +&pmu { + pmu_rtc: rtc { + compatible = "apple,t6050-pmu-rtc", "apple,t6041-pmu-rtc"; + nvmem-cells = <&rtc_offset>; + nvmem-cell-names = "rtc_offset"; + wakeup-source; + }; +}; + /* These boards' SMC fan and power keys are not yet checked */ &smc_hwmon { status = "disabled"; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index 26f4bce4362dbc..f1f22f256a3c14 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -716,22 +716,6 @@ }; }; -/* - * The PMU's RTC and its alarm. ADT: the PMU's info-rtc (0x2002), - * info-rtc_alarm_offset (0x2008), info-rtc_irq_mask_offset (0x200e), - * info-rtc_alarm_ctrl (0x2000) and info-rtc_scrpad (0x2100), the registers of - * the T6041 PMU. It raises no interrupt on this SoC: an armed alarm can only - * wake the machine from a firmware sleep, not from s2idle. - */ -&pmu { - pmu_rtc: rtc { - compatible = "apple,t6050-pmu-rtc", "apple,t6041-pmu-rtc"; - nvmem-cells = <&rtc_offset>; - nvmem-cell-names = "rtc_offset"; - wakeup-source; - }; -}; - /* * The video encoder's power states, as on the J714s. iBoot leaves VENC0_SYS on, and the SoC does * not enter the firmware-driven sleep with it on. Enabled and unused, genpd turns it off at From 92497fd80fedd15ef80690e28d0830f3377c4a82 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:16:26 +1100 Subject: [PATCH 1474/1514] arm64: dts: apple: t6050: give the K boards' port 1 DART its power domain dart_apcie1, PCIe port 1's DART (the SD reader's, ADT /arm-io/dart-apcie1 at 0x411000000), names no power domain. The K114c enables it with no domain, and the DART power-domain check flags it on every K board that gains the SD reader. The ADT gives dart-apcie1 no power-gates of its own: it sits in the apcie block, whose power-gates (ADT apcie0) start with APCIE_GP and APCIE_SYS_GP, next to port 0's DART, which takes APCIE_SYS_GP since "give the K boards' port 0 DART its power domain". The T6040's apcie1_dart at the same address takes ps_apcie_sys_gp too. So dart_apcie1 takes ps_apcie_sys_gp, which t6050-k114-k116-usb.dtsi already enables as firmware-owned on all four boards. The four K board DTBs gain only that power-domains property; the other T6050 DTBs are byte-identical. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index d09519d17008b5..0f862e9bfecd1f 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -335,3 +335,11 @@ power-domains = <&ps_apcie_sys_gp>; }; +/* + * Port 1's DART (dart-apcie1, the SD reader's) sits in the same apcie block as port 0's and + * takes the same APCIE_SYS_GP, as the T6040's apcie1_dart at the same address does. + */ +&dart_apcie1 { + power-domains = <&ps_apcie_sys_gp>; +}; + From eb35c3ded81d8d1d98e2bcec1a78f5a5ecd23fdd Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:18:02 +1100 Subject: [PATCH 1475/1514] arm64: dts: apple: t6050-k116s: take the SD reader's DART from t6050-die0.dtsi The tree has two nodes for ADT /arm-io/dart-apcie1 (0x411000000): dart_apcie1 in t6050-die0.dtsi, under the SoC bus, and apcie1_dart in t6050-peripherals.dtsi, under /soc. The K114c and J714s map PCIe port 1 through dart_apcie1; the K116s alone enables apcie1_dart, which names no power domain. Map port 1 through dart_apcie1 on the K116s too, as the K114c does: the iommu-map, post-init-providers and the enabled, manual-availability node now refer to it, and the port's DART gets the APCIE_SYS_GP domain the K boards give it. apcie1_dart is left disabled, as on every other T6050 board. That also lets the K boards share one port 1 description. Only the K116s DTB changes: dart_apcie1 is enabled with apple,manual-availability instead of apcie1_dart. The DART power-domain check counts one finding fewer. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k116s.dts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index f1f22f256a3c14..bae730eeb2e4dc 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -82,9 +82,9 @@ ; interrupt-names = "port0", "port1"; iommu-map = <0x100 &dart_apcie0 1 3>, - <0x200 &apcie1_dart 1 1>; - /* apcie1_dart probes only once port 1 is up: the host must not wait for it */ - post-init-providers = <&apcie1_dart>; + <0x200 &dart_apcie1 1 1>; + /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ + post-init-providers = <&dart_apcie1>; port01: pci@1,0 { device_type = "pci"; @@ -141,7 +141,7 @@ }; /* ADT dart-apcie1 manual-availability: pcie-apple enables it once port 1 is up */ -&apcie1_dart { +&dart_apcie1 { apple,manual-availability; status = "okay"; }; From 48d9f3950f8962814e9b60890209daa0f92b3a53 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:20:42 +1100 Subject: [PATCH 1476/1514] arm64: dts: apple: t6050: share the K boards' SD card reader, add K114s and K116c Only the K114c and K116s described PCIe port 1 and its SD card reader, each in its own copy; the K114s and K116c had no SD reader. The four boards' ADTs (27.2) have the same apcie0 port 1: port1, phy1 and intr2axi1 at reg[22], reg[24] and reg[25], the shared PHY state at reg[3], IRQ 1531, pci-bridge1 function-perst on gpio0 pin 0x51 (81), and a pcie-sdreader with function-sd_pwr_en pKW8('pcIO', 0x0, 0x190000) and card-detect and write-protect polarity 1, behind dart-apcie1. The live K114s ADT has pci-bridge1's link tunables as the K114c description has them: apcie-config-tunables, pcie-rc-tunables and pcie-rc-gen3/4/5- shadow-tunables. So: - t6050-k114-k116.dtsi describes port 1, the GL9755 and dart_apcie1 as the K114c did, adds sd_pwr_en as pcIO output 3 after the three shared ones and exposes pin 81. - t6050-k114.dtsi exposes pin 81 for the 14-inch boards. - The K114c keeps none of it in its own file. - The K116s keeps its single pcIO output and points port 1's power at it (output 0). The K114c and K116s DTBs are byte-identical, as are the other T6050 DTBs. The K114s and K116c gain port 1 with the SD reader, dart_apcie1, the fourth pcIO output and pin 81. The shared block is Joshua Warren's K114c description, tested on the K114c. Signed-off-by: Ryan Murray --- .../arm64/boot/dts/apple/t6050-k114-k116.dtsi | 125 +++++++++++++++--- arch/arm64/boot/dts/apple/t6050-k114.dtsi | 9 +- arch/arm64/boot/dts/apple/t6050-k114c.dts | 102 -------------- arch/arm64/boot/dts/apple/t6050-k116s.dts | 103 +-------------- 4 files changed, 116 insertions(+), 223 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index 0f862e9bfecd1f..a3c456952078b2 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -121,11 +121,12 @@ /* * As on J716c, where reading pin 112 takes an SError, only the pins a node - * names are exposed: 80, PCIe port 0's PERST#, and 134 and 139, the jack - * codec's interrupt and reset. A board that names more pins replaces the list. + * names are exposed: 80 and 81, PCIe ports 0 and 1's PERST#, and 134 and 139, + * the jack codec's interrupt and reset. A board that names more pins replaces + * the list. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 53>, <135 4>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 52>, <135 4>, <140 81>; }; /* @@ -141,19 +142,48 @@ * (T6050_K_BOARD_ID). The N1's platform ID is board-id << 16 | chip 0x6050. * aura's T6050 hand-off wants the host's iommu-map to mark the ports as it * found them. + * + * PCIe port 1: the SD card reader (ADT apcie0/pci-bridge1/pcie-sdreader, a + * GL9755), the same on all four boards' ADTs and laid out as on J714s. The + * boot loader leaves the port down, so the kernel trains it. From the ADTs: + * port1, phy1, intr2axi1: apcie0 reg[22], reg[24], reg[25] (port 0's are + * reg[16], reg[18], reg[19]), behind /arm-io's ranges (+0x200000000) + * phy-shared: apcie0 reg[3], the shared PHY's state, which the train reads; + * the boot loader leaves the PHY up with port 0 + * IRQ 1531: apcie0 interrupts[1] + * PERST#: pci-bridge1 function-perst, gpio0 pin 0x51 (81) + * power: pcie-sdreader function-sd_pwr_en, SMC pcIO (0x0, 0x190000), output + * 3 of smc_pcio below + * link tunables: pci-bridge1's apcie-config-tunables, pcie-rc-tunables and + * pcie-rc-gen{3,4,5}-shadow-tunables, as (offset, size, mask, value) + * The reader is behind dart-apcie1 (0x211000000, IRQ 1532; manual-availability: + * it answers only once the root complex is up). The ADT's mapper-apcie1 names + * no stream (the bridge requests one at run time), so stream 1 is this tree's + * choice, below the DART's first bypass stream (16), as on J714s. + * pci-bridge1's function-clkreq (gpio0 pin 0x4d) is not described: the + * driver does not take CLKREQ# lines. */ &pcie0 { - iommu-map = <0x100 &dart_apcie0 1 3>; + iommu-map = <0x100 &dart_apcie0 1 3>, + <0x200 &dart_apcie1 1 1>; bus-range = <0 4>; status = "okay"; reg = <0x1c 0xb0000000 0x0 0x10000000>, <0x4 0x14000000 0x0 0x4000>, <0x4 0x10028000 0x0 0x8000>, <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0"; - interrupts = ; - interrupt-names = "port0"; + <0x4 0x10024000 0x0 0x4000>, + <0x4 0x11028000 0x0 0x8000>, + <0x4 0x17014000 0x0 0x4000>, + <0x4 0x11024000 0x0 0x4000>, + <0x4 0x17020000 0x0 0x4000>; + reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", + "phy-shared"; + interrupts = , + ; + interrupt-names = "port0", "port1"; + /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ + post-init-providers = <&dart_apcie1>; port00: pci@0,0 { device_type = "pci"; @@ -196,6 +226,70 @@ local-bd-address = [00 00 00 00 00 00]; }; }; + + port01: pci@1,0 { + device_type = "pci"; + reg = <0x800 0 0 0 0>; + bus-range = <2 2>; + /* Down at boot: the kernel trains it, powering the reader first */ + apple,link-trained-by-bootloader; + /* ADT pcie-sdreader function-sd_pwr_en: SMC pcIO output 3 below */ + pwren-gpios = <&smc_pcio 3 GPIO_ACTIVE_HIGH>; + /* PERST#: ADT pci-bridge1 function-perst, GPIO 81 */ + reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; + /* ADT pci-bridge1 */ + apple,apcie-config-tunables = <0x140 4 0x1 0x1>, + <0x144 4 0xffffff 0x253770>, + <0x8a8 4 0x1 0x1>, + <0x8ac 4 0x1 0x1>; + apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, + <0x194 4 0x2 0x2>, + <0xb80 4 0x7f3f3f 0x7f1e1e>, + <0xb88 4 0x7f3f3f 0x7f1e1e>; + apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, + <0x890 4 0x3000000 0x0>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x1000000>, + <0x8a8 4 0xffff0f 0x1>; + apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, + <0x890 4 0x3000000 0x2000000>, + <0x8a8 4 0xffff0f 0x1>; + + #address-cells = <3>; + #size-cells = <2>; + ranges; + + interrupt-controller; + #interrupt-cells = <1>; + interrupt-map-mask = <0 0 0 7>; + interrupt-map = <0 0 0 1 &port01 0 0 0 0>, + <0 0 0 2 &port01 0 0 0 1>, + <0 0 0 3 &port01 0 0 0 2>, + <0 0 0 4 &port01 0 0 0 3>; + + /* + * The GL9755. Card detect and write protect are active high: ADT + * pcie-sdreader card-detect-polarity and write-protect-polarity = 1. + */ + sdhci0: mmc@0,0 { + compatible = "pci17a0,9755"; + reg = <0x20000 0x0 0x0 0x0 0x0>; + cd-inverted; + wp-inverted; + }; + }; +}; + +/* + * ADT dart-apcie1 manual-availability: pcie-apple enables it once port 1 is up. It sits in + * the same apcie block as port 0's DART and takes the same APCIE_SYS_GP (enabled in + * t6050-k114-k116-usb.dtsi), as the T6040's apcie1_dart at the same address does. + */ +&dart_apcie1 { + power-domains = <&ps_apcie_sys_gp>; + apple,manual-availability; + status = "okay"; }; /* @@ -318,10 +412,13 @@ /* * The board's pcIO outputs, from the ADT: dp2hdmi_pwr_en pKW8('pcIO', 0, 0x1a0000), * hdmi_pwr_en pKW8('pcIO', 0x800000, 0xf0000), and the trackpad AFE reset (2), - * pKW8('pcIO', 0x10000, 0x11c0000); the same as on J716c. + * pKW8('pcIO', 0x10000, 0x11c0000), the same as on J716c; then the SD reader's + * power (3), sd_pwr_en pKW8('pcIO', 0x0, 0x190000): ADT pcie-sdreader + * function-sd_pwr_en. */ &smc_pcio { - apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 0x011c000000010000>; + apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 + 0x011c000000010000 0x0019000000000000>; }; /* @@ -335,11 +432,3 @@ power-domains = <&ps_apcie_sys_gp>; }; -/* - * Port 1's DART (dart-apcie1, the SD reader's) sits in the same apcie block as port 0's and - * takes the same APCIE_SYS_GP, as the T6040's apcie1_dart at the same address does. - */ -&dart_apcie1 { - power-domains = <&ps_apcie_sys_gp>; -}; - diff --git a/arch/arm64/boot/dts/apple/t6050-k114.dtsi b/arch/arm64/boot/dts/apple/t6050-k114.dtsi index a895eebe32f030..ac9f638d7ee274 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114.dtsi @@ -42,12 +42,13 @@ /* * Pin 112's register takes an SError when read, so only the pins a node names are - * exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' interrupt and - * shutdown line (ADT audio-speaker, used only where a board describes the amps); - * 134 and 139, the jack codec's interrupt and reset; 136 and 137, the speaker ID. + * exposed: 80 and 81 (PCIe ports 0 and 1's PERST#); 106 and 107, the speaker amps' + * interrupt and shutdown line (ADT audio-speaker, used only where a board describes + * the amps); 134 and 139, the jack codec's interrupt and reset; 136 and 137, the + * speaker ID. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; }; /* diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 7550e9838e9a38..ac5ef78196fbf7 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -225,105 +225,3 @@ }; }; }; - -/* - * PCIe port 1: the SD card reader, this board's own beside the shared port 0 - * (t6050-k114-k116.dtsi): its registers, interrupt and DART stream 1 of dart-apcie1. - */ -&pcie0 { - reg = <0x1c 0xb0000000 0x0 0x10000000>, - <0x4 0x14000000 0x0 0x4000>, - <0x4 0x10028000 0x0 0x8000>, - <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>, - <0x4 0x11028000 0x0 0x8000>, - <0x4 0x17014000 0x0 0x4000>, - <0x4 0x11024000 0x0 0x4000>, - <0x4 0x17020000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", - "phy-shared"; - interrupts = , - ; - interrupt-names = "port0", "port1"; - iommu-map = <0x100 &dart_apcie0 1 3>, - <0x200 &dart_apcie1 1 1>; - /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ - post-init-providers = <&dart_apcie1>; - - /* - * PCIe port 1: the SD card reader (ADT pci-bridge1/pcie-sdreader, a GL9755), as on - * J714s. The boot loader leaves it down, so the kernel trains it: power is the SMC - * pcIO output of function-sd_pwr_en (index 3 below), PERST# GPIO 81, IRQ 1531. It is - * on stream 1 of dart-apcie1. The link tunables are pci-bridge1's, as on port 0. - */ - port01: pci@1,0 { - device_type = "pci"; - reg = <0x800 0 0 0 0>; - bus-range = <2 2>; - apple,link-trained-by-bootloader; - pwren-gpios = <&smc_pcio 3 GPIO_ACTIVE_HIGH>; - reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; - apple,apcie-config-tunables = <0x140 4 0x1 0x1>, - <0x144 4 0xffffff 0x253770>, - <0x8a8 4 0x1 0x1>, - <0x8ac 4 0x1 0x1>; - apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, - <0x194 4 0x2 0x2>, - <0xb80 4 0x7f3f3f 0x7f1e1e>, - <0xb88 4 0x7f3f3f 0x7f1e1e>; - apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, - <0x890 4 0x3000000 0x0>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x1000000>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x2000000>, - <0x8a8 4 0xffff0f 0x1>; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port01 0 0 0 0>, - <0 0 0 2 &port01 0 0 0 1>, - <0 0 0 3 &port01 0 0 0 2>, - <0 0 0 4 &port01 0 0 0 3>; - - /* The GL9755; card detect and write protect active high (ADT *-polarity = 1) */ - sdhci0: mmc@0,0 { - compatible = "pci17a0,9755"; - reg = <0x20000 0x0 0x0 0x0 0x0>; - cd-inverted; - wp-inverted; - }; - }; -}; - -/* - * Pin 112's register takes an SError when read, so only the pins a node here - * names are exposed: 80 and 81 (PCIe ports 0 and 1's PERST#); 106 and 107, the speaker - * amps' interrupt and shutdown line; 134 and 139, the jack codec's interrupt and - * reset; 136 and 137, the speaker ID. - */ -&pinctrl_ap { - gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; -}; - -/* It answers only once port 1's root complex is up: pcie-apple then enables it */ -&dart_apcie1 { - apple,manual-availability; - status = "okay"; -}; - -/* - * The board's pcIO outputs (t6050-k114-k116.dtsi lists indices 0 to 2), plus index 3, - * sd_pwr_en pKW8('pcIO', 0x0, 0x190000): ADT pcie-sdreader function-sd_pwr_en. - */ -&smc_pcio { - apple,output-commands = /bits/ 64 <0x001a000000000000 0x000f000000800000 - 0x011c000000010000 0x0019000000000000>; -}; diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index bae730eeb2e4dc..fc9e3efc23e53e 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -44,106 +44,11 @@ }; /* - * PCIe port 0, the N1, is in t6050-k114-k116.dtsi. - * - * PCIe port 1: the SD card reader (ADT apcie0/pci-bridge1/pcie-sdreader, a - * GL9755), as on J714s. The boot loader leaves the port down, so the kernel - * trains it. From this board's ADT: - * port1, phy1, intr2axi1: apcie0 reg[22], reg[24], reg[25] (port 0's are - * reg[16], reg[18], reg[19]), behind /arm-io's ranges (+0x200000000) - * phy-shared: apcie0 reg[3], the shared PHY's state, which the train reads; - * the boot loader leaves the PHY up with port 0 - * IRQ 1531: apcie0 interrupts[1] - * PERST#: pci-bridge1 function-perst, gpio0 pin 0x51 (81) - * power: pcie-sdreader function-sd_pwr_en, SMC pcIO (0x0, 0x190000), output - * 0 of smc_pcio below - * link tunables: pci-bridge1's apcie-config-tunables, pcie-rc-tunables and - * pcie-rc-gen{3,4,5}-shadow-tunables, as (offset, size, mask, value) - * The reader is behind dart-apcie1 (0x211000000, IRQ 1532; manual-availability: - * it answers only once the root complex is up). The ADT's mapper-apcie1 names - * no stream (the bridge requests one at run time), so stream 1 is this tree's - * choice, below the DART's first bypass stream (16), as on J714s. - * pci-bridge1's function-clkreq (gpio0 pin 0x4d) is not described: the - * driver does not take CLKREQ# lines. + * PCIe port 0 (the N1) and port 1 (the SD card reader) are in t6050-k114-k116.dtsi. + * This board drives one SMC pcIO output (below), so the reader's power is output 0. */ -&pcie0 { - reg = <0x1c 0xb0000000 0x0 0x10000000>, - <0x4 0x14000000 0x0 0x4000>, - <0x4 0x10028000 0x0 0x8000>, - <0x4 0x17010000 0x0 0x4000>, - <0x4 0x10024000 0x0 0x4000>, - <0x4 0x11028000 0x0 0x8000>, - <0x4 0x17014000 0x0 0x4000>, - <0x4 0x11024000 0x0 0x4000>, - <0x4 0x17020000 0x0 0x4000>; - reg-names = "config", "rc", "port0", "phy0", "intr2axi0", "port1", "phy1", "intr2axi1", - "phy-shared"; - interrupts = , - ; - interrupt-names = "port0", "port1"; - iommu-map = <0x100 &dart_apcie0 1 3>, - <0x200 &dart_apcie1 1 1>; - /* dart_apcie1 probes only once port 1 is up: the host must not wait for it */ - post-init-providers = <&dart_apcie1>; - - port01: pci@1,0 { - device_type = "pci"; - reg = <0x800 0 0 0 0>; - bus-range = <2 2>; - /* Down at boot: the kernel trains it, powering the reader first */ - apple,link-trained-by-bootloader; - /* ADT pcie-sdreader function-sd_pwr_en: SMC pcIO output 0 below */ - pwren-gpios = <&smc_pcio 0 GPIO_ACTIVE_HIGH>; - /* PERST#: ADT pci-bridge1 function-perst, GPIO 81 */ - reset-gpios = <&pinctrl_ap 81 GPIO_ACTIVE_LOW>; - /* ADT pci-bridge1 */ - apple,apcie-config-tunables = <0x140 4 0x1 0x1>, - <0x144 4 0xffffff 0x253770>, - <0x8a8 4 0x1 0x1>, - <0x8ac 4 0x1 0x1>; - apple,pcie-rc-tunables = <0x78 4 0x7000 0x0>, - <0x194 4 0x2 0x2>, - <0xb80 4 0x7f3f3f 0x7f1e1e>, - <0xb88 4 0x7f3f3f 0x7f1e1e>; - apple,pcie-rc-gen3-shadow-tunables = <0x154 4 0xf0f0f0f 0x5050505>, - <0x890 4 0x3000000 0x0>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen4-shadow-tunables = <0x178 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x1000000>, - <0x8a8 4 0xffff0f 0x1>; - apple,pcie-rc-gen5-shadow-tunables = <0x1ac 4 0xffff 0x5555>, - <0x890 4 0x3000000 0x2000000>, - <0x8a8 4 0xffff0f 0x1>; - - #address-cells = <3>; - #size-cells = <2>; - ranges; - - interrupt-controller; - #interrupt-cells = <1>; - interrupt-map-mask = <0 0 0 7>; - interrupt-map = <0 0 0 1 &port01 0 0 0 0>, - <0 0 0 2 &port01 0 0 0 1>, - <0 0 0 3 &port01 0 0 0 2>, - <0 0 0 4 &port01 0 0 0 3>; - - /* - * The GL9755. Card detect and write protect are active high: ADT - * pcie-sdreader card-detect-polarity and write-protect-polarity = 1. - */ - sdhci0: mmc@0,0 { - compatible = "pci17a0,9755"; - reg = <0x20000 0x0 0x0 0x0 0x0>; - cd-inverted; - wp-inverted; - }; - }; -}; - -/* ADT dart-apcie1 manual-availability: pcie-apple enables it once port 1 is up */ -&dart_apcie1 { - apple,manual-availability; - status = "okay"; +&port01 { + pwren-gpios = <&smc_pcio 0 GPIO_ACTIVE_HIGH>; }; /* From 3d3ab34cfc8ea5b0aad745e97aadb22000099018 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:17:20 +1100 Subject: [PATCH 1477/1514] arm64: dts: apple: t8112: describe the auxiliary PMU on every M2 The nub-spmi1 bus carries the auxiliary PMU (ADT /arm-io/nub-spmi1/pmu-aux, USID 0xe) on every T8112 Mac: the J413 and J473 ADTs both list it. Only the J413 described it; the J415, J473 and J493 kept a disabled copy. Describe the bus and its read-only spmi-nvmem PMIC once in t8112.dtsi and drop the per-board copies, so every M2 binds apple-spmi and apple-spmi-nvmem the way the J413 already does. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8112-j413.dts | 10 ---------- arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi | 8 -------- arch/arm64/boot/dts/apple/t8112.dtsi | 8 +++++++- 5 files changed, 7 insertions(+), 35 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8112-j413.dts b/arch/arm64/boot/dts/apple/t8112-j413.dts index da075043e4b8e8..7f8825891237e7 100644 --- a/arch/arm64/boot/dts/apple/t8112-j413.dts +++ b/arch/arm64/boot/dts/apple/t8112-j413.dts @@ -314,16 +314,6 @@ status = "okay"; }; -&nub_spmi1 { - status = "okay"; - - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - }; -}; - &i2c2 { retimer@18 { compatible = "apple,t8112-atcrt", "apple,atcrt"; diff --git a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j415-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi index 9e7941dd584e0b..174308798291f2 100644 --- a/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j473-peripherals.dtsi @@ -43,11 +43,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi index b7e06632fdf791..a9b1d4c8a8a556 100644 --- a/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t8112-j493-peripherals.dtsi @@ -26,11 +26,3 @@ }; }; -&nub_spmi1 { - pmic@e { - compatible = "apple,vale-pmic", "apple,spmi-nvmem"; - reg = <0xe SPMI_USID>; - read-only; - status = "disabled"; - }; -}; diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index fd13d3c654e935..a5b0542e289894 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -1524,12 +1524,18 @@ }; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@23d794000 { compatible = "apple,t8112-spmi", "apple,t8103-spmi"; reg = <0x2 0x3d794000 0x0 0x100>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; smc: smc@23e400000 { From facbb117b68f87feb9388b1c8ce341c1db0e3ca9 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:24:44 +1100 Subject: [PATCH 1478/1514] arm64: dts: apple: t8122: enable the DP855 panel controller on every board The J615 enables spi4 and its DP855 panel timing controller with the chip select from its ADT (/arm-io/spi4 function-spi_cs0: GPIO 136). The other T8122 boards kept the controller off until their chip select was checked against their ADT. Every T8122 board's device tree (J613, J615, J504, J433, J434) has the controller at /arm-io/spi4/dp855 and the same chip select: GPIO 136 on gpio0. Enable spi4 and the controller in the shared t8122-jxxx.dtsi and drop the J615 board copy. The J615 DTB is unchanged. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-j615.dts | 9 --------- arch/arm64/boot/dts/apple/t8122-jxxx.dtsi | 9 ++++++--- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8122-j615.dts b/arch/arm64/boot/dts/apple/t8122-j615.dts index 13516694fd13a7..2df8520fd2709d 100644 --- a/arch/arm64/boot/dts/apple/t8122-j615.dts +++ b/arch/arm64/boot/dts/apple/t8122-j615.dts @@ -237,12 +237,3 @@ }; }; -/* ADT /arm-io/spi4/dp855; chip select = /arm-io/spi4 function-spi_cs0. */ -&spi4 { - cs-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_LOW>; - status = "okay"; -}; - -&tcon { - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi index 508774078c858c..91aa0c621bcc76 100644 --- a/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-jxxx.dtsi @@ -261,17 +261,20 @@ /* * The DP855 panel timing controller. i2c-dp855 reads the panel management * devices behind it and shares its I2C engine with the display firmware - * through the controller's lock. Its chip select is board wiring, so the - * board files that have the ADT's spi4 function-spi_cs0 enable it. + * through the controller's lock. Every T8122 board's ADT has the controller + * at /arm-io/spi4/dp855, with the chip select at /arm-io/spi4 + * function-spi_cs0: GPIO 136 on gpio0 (J613, J615, J504, J433 and J434). */ &spi4 { + cs-gpios = <&pinctrl_ap 136 GPIO_ACTIVE_LOW>; + status = "okay"; + tcon: panel-controller@0 { compatible = "parade,dp855"; reg = <0>; spi-max-frequency = <1000000>; spi-cs-setup-delay-ns = <20>; spi-cs-hold-delay-ns = <20>; - status = "disabled"; }; }; From d011517a82a5868f6c4d8a8e14d4f35ca5e9f21e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:31:35 +1100 Subject: [PATCH 1479/1514] arm64: dts: apple: t8122: describe the auxiliary PMU The nub-spmi1 bus carries the auxiliary PMU (ADT /arm-io/nub-spmi1/pmu-aux, "pmu,vale", USID 0xe) on every T8122 Mac: the J613, J615, J504, J433 and J434 device trees all list it. It is the same Vale PMIC that the T8112 boards describe on their nub-spmi1. Enable the bus and describe the PMIC as a read-only spmi-nvmem provider, as on T8112, so apple-spmi and apple-spmi-nvmem bind. The provider's sysfs file is read-only since "nvmem: keep the Apple SPMI PMIC's sysfs file read-only". Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi b/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi index 1bdbd8356541fb..fa50c02496cebf 100644 --- a/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi +++ b/arch/arm64/boot/dts/apple/t8122-peripheral-buses.dtsi @@ -26,6 +26,7 @@ status = "disabled"; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@2e4794000 { compatible = "apple,t8122-spmi", "apple,t8103-spmi"; reg = <0x2 0xe4794000 0 0x4000>, @@ -37,7 +38,12 @@ #interrupt-cells = <2>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,vale-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; aop_spmi0: spmi@2f4894000 { From f5a13570f7143c392051f114c589d8544e595d1c Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:31:45 +1100 Subject: [PATCH 1480/1514] dt-bindings: nvmem: apple,spmi-nvmem: add the Club PMIC The M4 (T8132) Macs have a Club PMIC as their auxiliary PMU on the nub-spmi1 bus (ADT /arm-io/nub-spmi1/pmu-aux, "pmu,club"). Add its compatible. Signed-off-by: Ryan Murray --- Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml index 4a2ba5158b0f64..6b83a1528da7fc 100644 --- a/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml +++ b/Documentation/devicetree/bindings/nvmem/apple,spmi-nvmem.yaml @@ -21,6 +21,7 @@ properties: - apple,abbey-pmic - apple,baku-pmic - apple,chapel-pmic + - apple,club-pmic - apple,maverick-pmic - apple,mirabeau-pmic - apple,monaco-pmic From cfe3bf649a5980f2dc838baf79e71f3be31f78e5 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 01:33:54 -0500 Subject: [PATCH 1481/1514] drm/asahi: g17: run drm_sched submit workqueues at WQ_HIGHPRI When a G17 command cannot publish inline (for example, query-accessing compute commands host-waiting on a pending timestamp writer, or commands queued behind a backlog), drm_sched wakes its ordered submit workqueue after the blocking fence signals. Previously Scheduler::new() either let drm_sched allocate a default normal-priority ordered workqueue (single-die M5) or allocated OwnedQueue::new_ordered_reclaim() without WQ_HIGHPRI. Under heavy game CPU load (GTA V, BeamNG), the normal-priority submit worker waited 30-140 us in CFS behind userspace threads, letting the GPU go idle and incur a ~55 us firmware cold-start penalty on top. Add OwnedQueue::new_ordered_highpri_reclaim() (WQ_MEM_RECLAIM | WQ_HIGHPRI, preserving highpri across workqueue_restrict()) and use it for G17 scheduler submit queues while keeping cluster restriction gated on creator_cluster_scheduling(). Add a compiled host test with 3 mutation traps verifying WQ_MEM_RECLAIM, WQ_HIGHPRI, highpri tracking for workqueue_restrict(), and G17 wiring. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/job.rs | 14 +-- rust/kernel/workqueue.rs | 16 ++- tools/asahi/g17-highpri-sched-wq-tests.py | 142 ++++++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 4 files changed, 166 insertions(+), 8 deletions(-) create mode 100755 tools/asahi/g17-highpri-sched-wq-tests.py diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 2d6e2dd3b2bf30..4d6f8678719e67 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -591,21 +591,21 @@ impl Scheduler { Engine::Compute => (COMPUTE_CREDITS, c_str!("aurora_g17_compute")), }; let device = dev.as_ref().as_ref(); - let submit = if backend.creator_cluster_scheduling() { + // Run drm_sched's submit worker at WQ_HIGHPRI so host-waited jobs (such as + // query-access computes unblocked by completion events) are not delayed in + // CFS behind busy game/render threads. + let queue = workqueue::OwnedQueue::new_ordered_highpri_reclaim(name)?; + if backend.creator_cluster_scheduling() { // The run and free work stays in the creating CPU's cluster, as the event work // follows the submitter, instead of wherever an unbound worker last ran. - let queue = workqueue::OwnedQueue::new_ordered_reclaim(name)?; let cluster = Cpumask::cluster_of(CpuId::current()); // Without a cpu-map in the device tree each CPU is its own cluster: the queue then // stays unrestricted rather than tied to the one CPU that created it. if cluster.weight() > 1 { queue.restrict(cluster)?; } - Some(queue) - } else { - // drm_sched allocates its own ordered reclaim-safe queue. - None - }; + } + let submit = Some(queue); let scheduler = sched::Scheduler::new_with_queues( device, 1, credits, 0, TIMEOUT_MS, name, submit, Some(backend.fence_queue()), )?; diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 230c2281c96f7f..c2c63df64fc637 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -484,7 +484,21 @@ impl OwnedQueue { Self::ordered(name, bindings::wq_flags_WQ_MEM_RECLAIM) } + /// Allocates an ordered high-priority workqueue named `name` that may be used on the memory + /// reclaim path (`WQ_MEM_RECLAIM | WQ_HIGHPRI`). + pub fn new_ordered_highpri_reclaim(name: &CStr) -> Result { + Self::ordered_flags( + name, + bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI, + true, + ) + } + fn ordered(name: &CStr, flags: u32) -> Result { + Self::ordered_flags(name, flags, false) + } + + fn ordered_flags(name: &CStr, flags: u32, highpri: bool) -> Result { // SAFETY: `name` is a valid NUL-terminated string; the C side copies it. let ptr = unsafe { bindings::alloc_ordered_workqueue(name.as_char_ptr(), flags) }; @@ -493,7 +507,7 @@ impl OwnedQueue { queue: NonNull::new(ptr).ok_or(ENOMEM)?, ordered: true, unbound: true, - highpri: false, + highpri, }) } diff --git a/tools/asahi/g17-highpri-sched-wq-tests.py b/tools/asahi/g17-highpri-sched-wq-tests.py new file mode 100755 index 00000000000000..f579049c0655cf --- /dev/null +++ b/tools/asahi/g17-highpri-sched-wq-tests.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for G17 high-priority drm_sched submit workqueues. + +Compiles production `new_ordered_highpri_reclaim()` / `ordered_flags()` from +`rust/kernel/workqueue.rs` and verifies: +1. `new_ordered_highpri_reclaim()` sets both `WQ_MEM_RECLAIM` and `WQ_HIGHPRI` + and records `highpri: true` so `restrict()` preserves high priority. +2. `g17/job.rs::Scheduler::new()` allocates `new_ordered_highpri_reclaim()` + unconditionally (both single-die and multi-die) and calls `queue.restrict()` + only when `backend.creator_cluster_scheduling()` is true. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +WQ = ROOT / 'rust/kernel/workqueue.rs' +JOB = ROOT / 'drivers/gpu/drm/asahi/g17/job.rs' + +MUTATIONS = ['drop-highpri', 'drop-reclaim', 'drop-highpri-flag'] + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + wq_src = WQ.read_text() + job_src = JOB.read_text() + + hp_fn = item(wq_src, 'pub fn new_ordered_highpri_reclaim(') + ord_fn = item(wq_src, 'fn ordered_flags(') + sched_fn = item(job_src, 'pub(crate) fn new(dev: &AsahiDrmDevice,') + + if mutation == 'drop-highpri': + old = 'bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'bindings::wq_flags_WQ_MEM_RECLAIM', 1) + elif mutation == 'drop-reclaim': + old = 'bindings::wq_flags_WQ_MEM_RECLAIM | bindings::wq_flags_WQ_HIGHPRI' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'bindings::wq_flags_WQ_HIGHPRI', 1) + elif mutation == 'drop-highpri-flag': + old = 'true,\n )' + assert old in hp_fn + hp_fn = hp_fn.replace(old, 'false,\n )', 1) + + job_uses_hp = ( + 'let queue = workqueue::OwnedQueue::new_ordered_highpri_reclaim(name)?;' in sched_fn + and 'if backend.creator_cluster_scheduling() {' in sched_fn + and 'queue.restrict(cluster)?;' in sched_fn + and 'let submit = Some(queue);' in sched_fn + ) + + return f''' +use std::cell::Cell; +use std::ptr::NonNull; + +const ENOMEM: i32 = -12; +type Result = std::result::Result; + +struct CStr; +impl CStr {{ + fn as_char_ptr(&self) -> *const u8 {{ std::ptr::null() }} +}} + +thread_local! {{ + static LAST_FLAGS: Cell = const {{ Cell::new(0) }}; +}} + +mod bindings {{ + use super::LAST_FLAGS; + #[allow(non_upper_case_globals)] + pub const wq_flags_WQ_MEM_RECLAIM: u32 = 1 << 3; + #[allow(non_upper_case_globals)] + pub const wq_flags_WQ_HIGHPRI: u32 = 1 << 4; + + pub unsafe fn alloc_ordered_workqueue(_name: *const u8, flags: u32) -> *mut u8 {{ + LAST_FLAGS.with(|f| f.set(flags)); + 0x1000 as *mut u8 + }} +}} + +struct OwnedQueue {{ + #[allow(dead_code)] + queue: NonNull, + ordered: bool, + unbound: bool, + highpri: bool, +}} + +impl OwnedQueue {{ + {hp_fn} + {ord_fn} +}} + +fn main() {{ + assert!({str(job_uses_hp).lower()}, "g17 Scheduler::new must allocate highpri ordered reclaim queue"); + let q = OwnedQueue::new_ordered_highpri_reclaim(&CStr).unwrap(); + let flags = LAST_FLAGS.with(|f| f.get()); + assert!(flags & bindings::wq_flags_WQ_MEM_RECLAIM != 0, "must set WQ_MEM_RECLAIM"); + assert!(flags & bindings::wq_flags_WQ_HIGHPRI != 0, "must set WQ_HIGHPRI"); + assert!(q.ordered && q.unbound, "must stay ordered and unbound"); + assert!(q.highpri, "must record highpri=true for workqueue_restrict()"); + println!("PASS g17 highpri sched wq"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=MUTATIONS) + args = ap.parse_args() + + src = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-highpri-wq-') as tmp: + rs = os.path.join(tmp, 'harness.rs') + bin_path = os.path.join(tmp, 'harness') + Path(rs).write_text(src) + c = subprocess.run(['rustc', '--edition=2021', '-O', rs, '-o', bin_path], capture_output=True, text=True) + if c.returncode != 0: + sys.stderr.write(c.stderr) + return 2 + r = subprocess.run([bin_path], capture_output=True, text=True) + sys.stdout.write(r.stdout) + sys.stderr.write(r.stderr) + return r.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a20d283737988a..cdb93fa2c6f8c4 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -352,6 +352,8 @@ def mutations(flag, names, base, expect=KILL): 'max-channels', 'multi-channel-max'), []), 'g17-m5-effort-tests.py': [([], PASS)] + mutations('--mutation', ('m5-ignores-bound',), []), + 'g17-highpri-sched-wq-tests.py': [([], PASS)] + + mutations('--mutation', ('drop-highpri', 'drop-reclaim', 'drop-highpri-flag'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-freelist-lease-direct-tests.py': [([], PASS)] + mutations('--mutation', ('reject-preparing-complete', 'snapshot-rollback', From 3891e539ea6c87235537d2970d54f168c0d131a5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 17:31:45 +1100 Subject: [PATCH 1482/1514] arm64: dts: apple: t8132: describe the auxiliary PMU The nub-spmi1 bus carries the auxiliary PMU (ADT /arm-io/nub-spmi1/pmu-aux, "pmu,club", USID 0xe) on every T8132 Mac: the J604, J623, J624, J713, J715 and J773g device trees all list it. Enable the bus and describe the PMIC as a read-only spmi-nvmem provider, as on T8112, so apple-spmi and apple-spmi-nvmem bind. The provider's sysfs file is read-only since "nvmem: keep the Apple SPMI PMIC's sysfs file read-only". The bus has no power-domains reference, so the J713's unmanaged ps_nub_spmi1 doesn't hold it back (nub-spmi-a0 works the same way for the MagSafe PD controller). Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi index 2554025a5ca137..35aa78fc80937d 100644 --- a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi @@ -42,6 +42,7 @@ status = "disabled"; }; + /* ADT /arm-io/nub-spmi1: the auxiliary PMU (pmu-aux) at USID 0xe. */ nub_spmi1: spmi@388614000 { compatible = "apple,t8132-spmi", "apple,t8103-spmi"; reg = <0x3 0x88614000 0 0x4000>, @@ -53,7 +54,12 @@ #interrupt-cells = <2>; #address-cells = <2>; #size-cells = <0>; - status = "disabled"; + + pmic@e { + compatible = "apple,club-pmic", "apple,spmi-nvmem"; + reg = <0xe SPMI_USID>; + read-only; + }; }; aop_spmi1: spmi@390b14000 { From e36ad0d661e3b4bf141f69992ffa25f69e224151 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 18:12:35 +1100 Subject: [PATCH 1483/1514] arm64: dts: apple: t6050: select the M5 Max's PMIC buses by hardware, not by board t6050-peripherals.dtsi describes nub-spmi1 and nub-spmi4 only for a list of six boards (J714c, J716c, J775c, J775d, K114c, K116c). What the six have in common is the die: they are the M5 Max boards (the J775d's die 0 is one). The 27.2 ADTs agree. nub-spmi1 (spmi-mosquitoM1, interrupt 731) and nub-spmi4 (spmi-jerezC0 and spmi-jerezC1, interrupt 746) are in the J714cAP, J716cAP, J775cAP, J775dAP, K114cAP and K116cAP DeviceTrees and in the live J716c ADT, and in none of the M5 Pro's: J714sAP, J716sAP, J873sAP, K114sAP, K116sAP and the live K114s and K116s ADTs. So the new t6050-soc-max.dtsi, the M5 Max's die-0 part, defines T6050_MAX_PMIC_BUSES. The two buses are now guarded by that hardware macro, as the ATC2 router is by T6050_ATC2_USB4_ROUTER, and the six boards include the file before t6050-peripherals.dtsi. It is the place for the Max's other SoC blocks, the PMP tunables and the second media engines among them. All 11 T6050 DTBs are byte-identical. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-j714c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-j716c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-j775c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-j775d.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-k116c.dts | 2 ++ arch/arm64/boot/dts/apple/t6050-peripherals.dtsi | 6 ++++-- arch/arm64/boot/dts/apple/t6050-soc-max.dtsi | 12 ++++++++++++ 8 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 arch/arm64/boot/dts/apple/t6050-soc-max.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-j714c.dts b/arch/arm64/boot/dts/apple/t6050-j714c.dts index ff202d0d0ec0cf..e60bae57450c43 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714c.dts @@ -15,6 +15,8 @@ /dts-v1/; #define T6050_J714C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" /* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ #define T6050_ATC2_USB4_ROUTER #include diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index 679e9f2f788563..ce7d52fc05a795 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -14,6 +14,8 @@ /dts-v1/; #define T6050_J716C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" /* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ #define T6050_ATC2_USB4_ROUTER #include "t6050-max.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j775c.dts b/arch/arm64/boot/dts/apple/t6050-j775c.dts index 65d92d3a174800..58c308f8d58e06 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775c.dts @@ -33,4 +33,6 @@ }; #define T6050_J775C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-j775d.dts b/arch/arm64/boot/dts/apple/t6050-j775d.dts index b136a0eed288bb..65bafecbc0056d 100644 --- a/arch/arm64/boot/dts/apple/t6050-j775d.dts +++ b/arch/arm64/boot/dts/apple/t6050-j775d.dts @@ -506,6 +506,8 @@ }; #define T6050_J775D +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" /* diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index ac5ef78196fbf7..9c2063503342eb 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -12,6 +12,8 @@ /* Defined before the includes: t6050-max.dtsi guards the ATC2 router on it. */ #define T6050_K114C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" /* ADT /arm-io/acio2: the right port's USB4/Thunderbolt router */ #define T6050_ATC2_USB4_ROUTER /* The N1's firmware and this board's ADT board-id, for t6050-k114-k116.dtsi */ diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index 40bfec8ab72a85..688b10b35ce8fc 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -24,6 +24,8 @@ }; #define T6050_K116C +/* The M5 Max die-0 blocks (nub-spmi1, nub-spmi4) */ +#include "t6050-soc-max.dtsi" #include "t6050-peripherals.dtsi" /* The GPU, handed over by the boot loader */ diff --git a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi index 9c8f5441a94a30..f4472ddf9eba4c 100644 --- a/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-peripherals.dtsi @@ -1324,7 +1324,8 @@ #else &{/soc} { #endif -#if defined(T6050_J714C) || defined(T6050_J716C) || defined(T6050_J775C) || defined(T6050_J775D) || defined(T6050_K114C) || defined(T6050_K116C) +/* nub-spmi1: an M5 Max bus (t6050-soc-max.dtsi) */ +#ifdef T6050_MAX_PMIC_BUSES nub_spmi1: spmi@28a054000 { compatible = "apple,t6050-spmi", "apple,t8142-spmi"; reg = <0x2 0x8a054000 0x0 0x4000>, @@ -1337,7 +1338,8 @@ }; #endif -#if defined(T6050_J714C) || defined(T6050_J716C) || defined(T6050_J775C) || defined(T6050_J775D) || defined(T6050_K114C) || defined(T6050_K116C) +/* nub-spmi4: the other bus of t6050-soc-max.dtsi */ +#ifdef T6050_MAX_PMIC_BUSES nub_spmi4: spmi@28a114000 { compatible = "apple,t6050-spmi", "apple,t8142-spmi"; reg = <0x2 0x8a114000 0x0 0x4000>, diff --git a/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi b/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi new file mode 100644 index 00000000000000..1686e5ce952ab6 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-soc-max.dtsi @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The M5 Max's die-0 SoC part, for every board built on it: the MacBook Pros J714c, J716c, + * K114c and K116c and the Mac Studios J775c and J775d. Boards include it before + * t6050-peripherals.dtsi; it selects the blocks the M5 Pro's die does not have. + * + * The Max's ADTs (27.2: J714cAP, J716cAP, J775cAP, J775dAP, K114cAP, K116cAP, and the live + * J716c ADT) have two more SPMI buses than the M5 Pro's (J714sAP, J716sAP, J873sAP, K114sAP, + * K116sAP, and the live K114s and K116s ADTs): nub-spmi1 (spmi-mosquitoM1, interrupt 731) and + * nub-spmi4 (spmi-jerezC0 and spmi-jerezC1, interrupt 746), the Max's other PMICs. + */ +#define T6050_MAX_PMIC_BUSES From 5331cd92a33ec4ffb8b74e6cf0e50f016f978dfc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:17:20 +1100 Subject: [PATCH 1484/1514] arm64: dts: apple: t8132: clock spi3 and spi4 from the reference clock spi3 and spi4 named peripheral_clocks, which no driver provides, so spi-apple's devm_clk_get_enabled() would defer them forever once enabled. Every other Apple SPI controller, including the T8132's enabled ones, runs from the 24 MHz clkref; use it here too. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi index 2554025a5ca137..8356935cec5d24 100644 --- a/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-peripheral-buses.dtsi @@ -1,5 +1,9 @@ // SPDX-License-Identifier: GPL-2.0+ OR MIT -/* Unclaimed T8132 peripheral buses. */ +/* + * Unclaimed T8132 peripheral buses. The SPI controllers run from the 24 MHz + * reference like every other Apple SPI controller: no driver provides + * peripheral_clocks, and spi-apple needs a clock rate to divide. + */ &soc { spi4: spi@3ad110000 { @@ -7,7 +11,7 @@ reg = <0x3 0xad110000 0 0x4000>; interrupt-parent = <&aic>; interrupts = ; - clocks = <&peripheral_clocks 422>; + clocks = <&clkref>; power-domains = <&ps_spi4>; #address-cells = <1>; #size-cells = <0>; @@ -75,7 +79,7 @@ reg = <0x3 0xad10c000 0 0x4000>; interrupt-parent = <&aic>; interrupts = ; - clocks = <&peripheral_clocks 421>; + clocks = <&clkref>; power-domains = <&ps_spi3>; #address-cells = <1>; #size-cells = <0>; From f818cacaf84dd8cc55a03b97ddcef7f1616e27e2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 14:17:21 +1100 Subject: [PATCH 1485/1514] arm64: dts: apple: t8132: enable the DP855 panel controller on the laptops The J604 and J713 ADTs both list the DP855 panel timing controller on spi4 (/arm-io/spi4/dp855), chip select GPIO 76 (function-spi_cs0). i2c-dp855 drives it as a read-only I2C adapter and shares the controller's I2C engine with the display firmware through its lock; it already binds on the M2 Air with the same SPI timing. Describe it in t8132-laptop.dtsi (J604, J713, J715) and turn on the spi4 power state on the J713 and J715, whose pmgr file lists only qualified domains (its parent, spi_p, is already on). Signed-off-by: Ryan Murray --- .../arm64/boot/dts/apple/t8132-j713-pmgr.dtsi | 3 ++- arch/arm64/boot/dts/apple/t8132-laptop.dtsi | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi b/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi index 515fd982909895..36798a86d0eabf 100644 --- a/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j713-pmgr.dtsi @@ -220,8 +220,9 @@ status = "disabled"; }; +/* spi4 carries the DP855 panel controller (t8132-laptop.dtsi). */ &ps_spi4 { - status = "disabled"; + status = "okay"; }; &ps_trace_fab { diff --git a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi index c4b37d41373a32..9b2a664fa41177 100644 --- a/arch/arm64/boot/dts/apple/t8132-laptop.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-laptop.dtsi @@ -185,3 +185,22 @@ apple,no-liquid-detection; }; }; + +/* + * ADT /arm-io/spi4/dp855: the panel timing controller, chip select from the + * spi4 function-spi_cs0 (the same pin on the J604 and J713). i2c-dp855 reads + * the panel management devices behind it and shares its I2C engine with the + * display firmware through the controller's lock. + */ +&spi4 { + cs-gpios = <&pinctrl_ap 76 GPIO_ACTIVE_LOW>; + status = "okay"; + + panel_controller: panel-timing-controller@0 { + compatible = "parade,dp855"; + reg = <0>; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + }; +}; From d77eb3148dd16969ba4e6e42b60b6723d1e18366 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 27 Nov 2026 10:27:27 +0100 Subject: [PATCH 1486/1514] wifi: apple: centauri: enable function memory space before polling Beta BAR0 enumerate_functions() maps BAR 0 of functions 1 (Alpha Wi-Fi) and 2 (Beta Bluetooth) via pci_iomap(), but never called pci_enable_device_mem() on them. Function 1 happened to be enabled because apple_centauri itself probes 0x1902, while function 2 (0x1903) belongs to btcentauri. Since commit 227c89b69b65 ("wifi: apple: centauri: attach Bluetooth once Beta's firmware runs"), centauri_boot_write() calls centauri_attach_beta() -> centauri_beta_running() at the end of IPC bootstrap, which reads ipc->bar[2] + 0x18 and ipc->bar[2]. When btcentauri has not already probed function 2 (for example when btcentauri is blacklisted until a boot script loads it after rom_boot, or is built as a module before udev probes it), 0000:01:00.2 still has PCI_COMMAND_MEMORY cleared and the BAR0 read causes an immediate Asynchronous SError kernel panic on Apple Silicon PCIe. Call pci_enable_device_mem() (serialized with device_lock(), matching the t6050 backend) for functions 1 and 2 before pci_iomap() in enumerate_functions(), guard centauri_beta_running() on ipc->enabled[2], and balance with pci_disable_device() after pci_iounmap() in centauri_free_ipc(). Fixes: 227c89b69b65 ("wifi: apple: centauri: attach Bluetooth once Beta's firmware runs") Signed-off-by: Thomas Glanzmann --- .../wireless/apple/centauri/centauri_ipc.c | 22 ++++++++++++++++--- .../wireless/apple/centauri/centauri_pci.c | 7 +++--- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/drivers/net/wireless/apple/centauri/centauri_ipc.c b/drivers/net/wireless/apple/centauri/centauri_ipc.c index d657e6a4b53747..2905a7e56e8ced 100644 --- a/drivers/net/wireless/apple/centauri/centauri_ipc.c +++ b/drivers/net/wireless/apple/centauri/centauri_ipc.c @@ -33,6 +33,7 @@ struct centauri_ipc { struct list_head buffers; struct pci_dev *function[3]; void __iomem *bar[3]; + bool enabled[3]; struct cen_context control, alpha; struct cen_buffer *secondary, *window, *cchi_rx, *cchi_tx, *debug_rx; struct cen_buffer *alpha_log; @@ -426,7 +427,7 @@ static int enumerate_functions(struct centauri *c) { struct centauri_ipc *ipc = c->ipc; u16 control; - int i, cap; + int i, cap, ret; dma_addr_t msi; pci_lock_rescan_remove(); @@ -442,6 +443,14 @@ static int enumerate_functions(struct centauri *c) return -ENODEV; if (!(pci_resource_flags(ipc->function[i], 0) & IORESOURCE_MEM)) return -ENODEV; + if (i) { + device_lock(&ipc->function[i]->dev); + ret = pci_enable_device_mem(ipc->function[i]); + device_unlock(&ipc->function[i]->dev); + if (ret) + return ret; + ipc->enabled[i] = true; + } ipc->bar[i] = pci_iomap(ipc->function[i], 0, 0); if (!ipc->bar[i]) return -ENOMEM; @@ -558,9 +567,11 @@ int centauri_start_ipc(struct centauri *c) */ bool centauri_beta_running(struct centauri *c) { - void __iomem *bar = c->ipc ? c->ipc->bar[2] : NULL; + struct centauri_ipc *ipc = c->ipc; - return bar && readl(bar + 0x18) == 2 && !readl(bar); + if (!ipc || !ipc->enabled[2] || !ipc->bar[2]) + return false; + return readl(ipc->bar[2] + 0x18) == 2 && !readl(ipc->bar[2]); } void centauri_free_ipc(struct centauri *c) @@ -595,6 +606,11 @@ void centauri_free_ipc(struct centauri *c) for (i = 0; i < 3; i++) { if (ipc->bar[i]) pci_iounmap(ipc->function[i], ipc->bar[i]); + if (ipc->enabled[i]) { + device_lock(&ipc->function[i]->dev); + pci_disable_device(ipc->function[i]); + device_unlock(&ipc->function[i]->dev); + } pci_dev_put(ipc->function[i]); } kfree(ipc); diff --git a/drivers/net/wireless/apple/centauri/centauri_pci.c b/drivers/net/wireless/apple/centauri/centauri_pci.c index 67d3a7884759f6..b2b1cd434a6577 100644 --- a/drivers/net/wireless/apple/centauri/centauri_pci.c +++ b/drivers/net/wireless/apple/centauri/centauri_pci.c @@ -488,9 +488,10 @@ static int centauri_resume(struct device *dev) static DEFINE_SIMPLE_DEV_PM_OPS(centauri_pm_ops, centauri_suspend, centauri_resume); -/* 0x1903 is the Beta (Bluetooth) function: btcentauri claims it. This driver needs functions - * 0 and 1 (1 is enabled here, its BAR is used by the Wi-Fi code) and reaches function 2 only - * through config space and its struct device for DMA. +/* 0x1903 is the Beta (Bluetooth) function: btcentauri claims it. This driver binds functions + * 0 and 1 (1 is enabled here, its BAR is used by the Wi-Fi code) and enables function 2's + * memory space during IPC bootstrap so centauri_beta_running() can poll Beta's BAR0 safely + * even when btcentauri has not probed yet. */ static const struct pci_device_id centauri_ids[] = { { PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x1900), .driver_data = 0x8000 }, From 6cff19a8104413122127e3cda08c3a6d8632389e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 21:08:28 +1100 Subject: [PATCH 1487/1514] Revert "drm: apple: HDCP 2.2 with the standard Content Protection properties" This reverts merge deb2df2a9e2b (#3302). The merge turned main's host tests red (Host tests run 45964990093; last green fcb12427): the host harnesses that compile dcp.c excerpts have no stubs for the new HDCP calls (dcpext26-startup-tests, backlight-coldboot-tests), the shared asahi.config lacks the new CONFIG_DRM_APPLE_HDCP request (hardware-defaults-tests), and four apple-dcp selftests fail (service-rebind, provider-admission, ordered-rx, stale-crtc-poweroff). The PR's host-tests job never ran after it was retargeted to main. Reland it with the harness updates once run-host-tests.py is green. Signed-off-by: Ryan Murray --- .../bindings/display/apple,dcp.yaml | 11 - arch/arm64/boot/dts/apple/t604x-extdisp.dtsi | 2 - arch/arm64/boot/dts/apple/t604x.dtsi | 1 - arch/arm64/boot/dts/apple/t8112.dtsi | 2 - drivers/gpu/drm/apple/Kconfig | 15 - drivers/gpu/drm/apple/Makefile | 3 - drivers/gpu/drm/apple/afk.c | 34 +- drivers/gpu/drm/apple/apple_drv.c | 18 - drivers/gpu/drm/apple/connector.h | 9 - drivers/gpu/drm/apple/dcp-hdcp-drv.h | 79 -- drivers/gpu/drm/apple/dcp-hdcp-glue-test.c | 175 --- drivers/gpu/drm/apple/dcp-hdcp-test.c | 237 ---- drivers/gpu/drm/apple/dcp-hdcp-tx-test.c | 581 -------- drivers/gpu/drm/apple/dcp-hdcp-tx.c | 374 ------ drivers/gpu/drm/apple/dcp-hdcp-tx.h | 118 -- drivers/gpu/drm/apple/dcp-hdcp-wire-test.c | 156 --- drivers/gpu/drm/apple/dcp-hdcp-wire.h | 247 ---- drivers/gpu/drm/apple/dcp-hdcp.c | 1165 ----------------- drivers/gpu/drm/apple/dcp-hdcp.h | 230 ---- drivers/gpu/drm/apple/dcp-internal.h | 2 - drivers/gpu/drm/apple/dcp.c | 24 - drivers/gpu/drm/apple/iomfb.c | 4 - 22 files changed, 10 insertions(+), 3477 deletions(-) delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-drv.h delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-glue-test.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-test.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx-test.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-tx.h delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-wire-test.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp-wire.h delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp.c delete mode 100644 drivers/gpu/drm/apple/dcp-hdcp.h diff --git a/Documentation/devicetree/bindings/display/apple,dcp.yaml b/Documentation/devicetree/bindings/display/apple,dcp.yaml index eba0a74ce67833..57616c37cda25a 100644 --- a/Documentation/devicetree/bindings/display/apple,dcp.yaml +++ b/Documentation/devicetree/bindings/display/apple,dcp.yaml @@ -387,17 +387,6 @@ properties: $ref: /schemas/types.yaml#/definitions/uint32 description: Display coprocessor index on multi-DCP systems. - apple,hdcp-channels: - $ref: /schemas/types.yaml#/definitions/uint32-array - minItems: 1 - maxItems: 2 - items: - maximum: 14 - description: - The Secure Enclave's HDCP interface channels assigned to this display - coprocessor. The first is the HDCP 2.2 transmitter channel of its - external output. Absent when the coprocessor has no HDCP transmitter. - apple,sleep-host-stop: type: boolean description: diff --git a/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi b/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi index 1cec4e06a66d70..3b60ac6afcb788 100644 --- a/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi +++ b/arch/arm64/boot/dts/apple/t604x-extdisp.dtsi @@ -18,7 +18,6 @@ mboxes = <&dcpext0_mbox>; mbox-names = "mbox"; iommus = <&dcpext0_dart 23>; - apple,hdcp-channels = <7 8>; /* guessed: the internal DCP uses 0x20000, J700 DISPEXT0 is +0x8000 */ apple,bw-scratch = <&pmgr_dcp 0 4 0x28000>; /* firmware Disp_Index, the dual-pipe endpoint ID */ @@ -57,7 +56,6 @@ mboxes = <&dcpext1_mbox>; mbox-names = "mbox"; iommus = <&dcpext1_dart 23>; - apple,hdcp-channels = <9 10>; /* guessed, as dcpext0 */ apple,bw-scratch = <&pmgr_dcp 0 4 0x30000>; apple,dcp-endpoint = <2>; diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index b67f4c3e10dd2c..b269473755b871 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -667,7 +667,6 @@ mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 23>; - apple,hdcp-channels = <5 6>; apple,bw-scratch = <&pmgr_dcp 0 4 0x20000>; apple,iomfb-surfaces = <1 1 0 0>; /* the boot loader describes the piodma's regions with 2+2 cells */ diff --git a/arch/arm64/boot/dts/apple/t8112.dtsi b/arch/arm64/boot/dts/apple/t8112.dtsi index 9d06d392525c15..fd13d3c654e935 100644 --- a/arch/arm64/boot/dts/apple/t8112.dtsi +++ b/arch/arm64/boot/dts/apple/t8112.dtsi @@ -793,7 +793,6 @@ mboxes = <&dcp_mbox>; mbox-names = "mbox"; iommus = <&dcp_dart 5 0x8 0x00000000 0x7 0xffff0000>; - apple,hdcp-channels = <5 6>; /* the ADT has 2 additional regs which seems to be unused */ reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; @@ -2008,7 +2007,6 @@ mboxes = <&dcpext_mbox>; mbox-names = "mbox"; iommus = <&dcpext_dart 5 0x8 0x00000000 0x7 0xffff0000>; - apple,hdcp-channels = <7 8>; phandle = <&dcpext>; /* the ADT has 2 additional regs which seems to be unused */ diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index bff991d363a377..689171db4ebe0c 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -36,21 +36,6 @@ config DRM_APPLE_CEC dcpav-cec-interface-epic service. Say Y here to expose a standard Linux /dev/cecX adapter bound to the built-in HDMI connector. -config DRM_APPLE_HDCP - bool "HDCP 2.2 content protection on external outputs" - default y - depends on DRM_APPLE - select DRM_DISPLAY_HELPER - select DRM_DISPLAY_HDCP_HELPER - help - Support the standard "Content Protection" and "HDCP Content Type" - connector properties on external DisplayPort, HDMI and USB-C - outputs. The SEP holds the transmitter's keys and does the HDCP 2.2 - cryptography; DCP carries the messages to the receiver. The - property is attached on display processors whose device tree node - has "apple,hdcp-channels", with the SEP HDCP service - (APPLE_SEP_HDCP_INTERFACE) built in. - config DRM_APPLE_AUDIO bool "DisplayPort/HDMI Audio support" default y diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index fa82d847891efe..6098e8efb7c597 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -41,7 +41,6 @@ appledrm-y += epic/dpavservep.o appledrm-y += epic/panelavep.o appledrm-y += plane.o appledrm-y += dcp-indicator.o -appledrm-$(CONFIG_DRM_APPLE_HDCP) += dcp-hdcp.o dcp-hdcp-tx.o appledrm-$(CONFIG_TRACING) += trace.o @@ -51,8 +50,6 @@ obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk_test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_backlight_test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-indicator-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-announce-test.o -obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-hdcp-test.o -obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp-hdcp-wire-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk-service-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_cec_test.o diff --git a/drivers/gpu/drm/apple/afk.c b/drivers/gpu/drm/apple/afk.c index c3898cb328a3d5..10e3586487a9d8 100644 --- a/drivers/gpu/drm/apple/afk.c +++ b/drivers/gpu/drm/apple/afk.c @@ -24,7 +24,6 @@ #include #include "afk.h" -#include "dcp-hdcp-drv.h" #include "afkv2-codec.h" #include "afk_reply.h" #include "trace.h" @@ -462,7 +461,7 @@ afk_match_service(struct apple_dcp_afkep *ep, const char *name) return ops; } - return dcp_hdcp_match_service(ep, name, false); + return NULL; } static struct apple_epic_service *afk_epic_find_service(struct apple_dcp_afkep *ep, @@ -842,7 +841,6 @@ afk_compact_match_service(struct apple_dcp_afkep *ep, const char *name) const struct apple_epic_service_ops *ops, *any = NULL; const char *service_name; size_t len; - bool cut; if (!name[0] || !ep->ops) return NULL; @@ -869,14 +867,13 @@ afk_compact_match_service(struct apple_dcp_afkep *ep, const char *name) } /* An announcement that filled its field may have lost its end. */ - cut = strlen(name) >= AFK_COMPACT_NAME_LEN - 1; - if (cut) - for (ops = ep->ops; ops->name[0]; ops++) - if (afk_compact_cut_of(ops, service_name)) - return ops; + if (strlen(name) < AFK_COMPACT_NAME_LEN - 1) + return any; + for (ops = ep->ops; ops->name[0]; ops++) + if (afk_compact_cut_of(ops, service_name)) + return ops; - /* The HDCP services, by name, wherever they are announced. */ - return dcp_hdcp_match_service(ep, service_name, cut) ?: any; + return any; } /* @@ -1921,15 +1918,9 @@ static void afk_recv_handle_init(struct apple_dcp_afkep *ep, u32 channel, } } - /* - * The HDCP services go by their EPIC name: their provider classes are - * shared with other services (the DP device class also names the AV - * device, the interface class names the port controllers). - */ - ops = dcp_hdcp_match_service(ep, epic_name, false); - if (!ops && ep->match_epic_name) + if (ep->match_epic_name) ops = afk_match_service(ep, epic_name); - else if (!ops) + else ops = afk_match_service(ep, service_name); if (dcp_is_ext26(ep->dcp)) dev_dbg(ep->dcp->dev, @@ -3041,12 +3032,7 @@ static int afk_send_epic_token(struct apple_dcp_afkep *ep, u32 channel, u16 tag, if (ep->wire_v2) { if (!channel || channel > U16_MAX || tag > U8_MAX || payload_len > SZ_1M) return -EINVAL; - if (ecat == EPIC_CAT_REPORT && stype == EPIC_SUBTYPE_STD_SERVICE) { - /* A service report with its data (an HDCP session's progress). */ - if (!payload_len) - return -EINVAL; - v2_category = AFKV2_REPORT; - } else if (ecat == EPIC_CAT_REPORT) { + if (ecat == EPIC_CAT_REPORT) { if ((stype != AFKV2_OPEN && stype != AFKV2_CLOSE) || payload_len) return -EOPNOTSUPP; v2_flags = 1; diff --git a/drivers/gpu/drm/apple/apple_drv.c b/drivers/gpu/drm/apple/apple_drv.c index 30d5346b898566..06e36e3a4a00d6 100644 --- a/drivers/gpu/drm/apple/apple_drv.c +++ b/drivers/gpu/drm/apple/apple_drv.c @@ -55,7 +55,6 @@ #include "apple_resume.h" #include "dcp-hdr-metadata.h" #include "dcp.h" -#include "dcp-hdcp-drv.h" #include "plane.h" #include "iomfb_m4.h" #include "t8132_ext_drm.h" @@ -1037,8 +1036,6 @@ static void apple_atomic_commit_tail(struct drm_atomic_commit *state) DRM_PLANE_COMMIT_ACTIVE_ONLY); drm_atomic_helper_fake_vblank(state); drm_atomic_helper_commit_hw_done(state); - /* Content Protection requests go to the display processors' queues. */ - dcp_hdcp_commit(state); drm_atomic_helper_wait_for_flip_done(state->dev, state); apple_fail_lost_flips(state); drm_atomic_helper_cleanup_planes(state->dev, state); @@ -1154,7 +1151,6 @@ static int apple_connector_atomic_check(struct drm_connector *conn, const struct drm_property_blob *blob = new->hdr_output_metadata; struct drm_crtc_state *crtc_state; - dcp_hdcp_atomic_check(conn, state); if (blob && (blob->length != sizeof(struct hdr_output_metadata) || !dcp_hdr_is_type1(blob->data))) return -EINVAL; @@ -1361,9 +1357,6 @@ static int apple_connector_create(struct drm_device *drm, dcp_ext_color_props_supported(dcp)); if (ret) goto err_cleanup; - ret = dcp_hdcp_attach_connector(connector, &dcp, 1, connector_type); - if (ret) - goto err_cleanup; connector->base.polled = DRM_CONNECTOR_POLL_HPD; connector->connected = false; @@ -1726,17 +1719,6 @@ static int apple_probe_typec_ports(struct drm_device *drm, connector->connected = false; connector->dcp = NULL; - /* Content Protection where a pipeline that can drive the port has HDCP. */ - for (i = 0; i < num_dcp; i++) { - if (pipeline ? dcp[i] != pipeline : - !dcp_typec_port_has_candidate(port_idx, dcp[i])) - continue; - ret = dcp_hdcp_attach_connector(connector, &dcp[i], 1, - DRM_MODE_CONNECTOR_DisplayPort); - if (ret) - return ret; - } - /* * One encoder per connector, covering its allowed pipelines. * T6050 connectors each cover exactly one. Attaching several diff --git a/drivers/gpu/drm/apple/connector.h b/drivers/gpu/drm/apple/connector.h index ff01bb3b5cef46..5d8c1674503fcf 100644 --- a/drivers/gpu/drm/apple/connector.h +++ b/drivers/gpu/drm/apple/connector.h @@ -89,15 +89,6 @@ struct apple_connector { * chosen one; -1 until then, and nothing is sent. */ int bl_level; - - /* - * Content Protection (dcp-hdcp-drv.h): the property is attached, and - * what the last commit asked for. Written by the commit tail, read by - * the display processor that drives the connector. - */ - bool hdcp_attached; - bool hdcp_want; - u8 hdcp_type; }; #define to_apple_connector(x) container_of(x, struct apple_connector, base) diff --git a/drivers/gpu/drm/apple/dcp-hdcp-drv.h b/drivers/gpu/drm/apple/dcp-hdcp-drv.h deleted file mode 100644 index 8b1600fcd74b49..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-drv.h +++ /dev/null @@ -1,79 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -/* Copyright 2026 Ryan Murray */ -#ifndef __APPLE_DCP_HDCP_DRV_H__ -#define __APPLE_DCP_HDCP_DRV_H__ - -#include -#include - -struct apple_connector; -struct apple_dcp; -struct apple_dcp_afkep; -struct apple_epic_service_ops; -struct drm_atomic_commit; -struct drm_connector; -struct platform_device; - -/* - * HDCP 2.2 on the display processors' external outputs: the DCP services - * (dcp-hdcp-wire.h), the transmitter (dcp-hdcp-tx.h) and the Content - * Protection policy (dcp-hdcp.h), joined to the connector properties. - */ -/* Whether something already drives @endpoint (dcp.c). */ -bool dcp_endpoint_routed(struct apple_dcp *dcp, u8 endpoint); - -#if IS_ENABLED(CONFIG_DRM_APPLE_HDCP) -/* A display processor's HDCP state, if it has an HDCP channel; idempotent. */ -struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp); -void dcp_hdcp_fini(struct apple_dcp *dcp); -/* Starts the DP device and HDCP interface endpoints when no other path did. */ -void dcp_hdcp_start_endpoints(struct apple_dcp *dcp); -/* Routes the endpoints this file started. */ -struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, u32 endpoint); -/* The HDCP services, matched by name ahead of a catch-all. */ -const struct apple_epic_service_ops * -dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, - bool cut); -/* Hotplug, power off or on, suspend, a new route: a new link generation. */ -void dcp_hdcp_link_changed(struct apple_dcp *dcp); -/* The same, and its teardown finished before returning (suspend, DPMS off). */ -void dcp_hdcp_quiesce(struct apple_dcp *dcp); - -int dcp_hdcp_attach_connector(struct apple_connector *connector, - struct platform_device **dcps, unsigned int n, - int connector_type); -void dcp_hdcp_atomic_check(struct drm_connector *conn, - struct drm_atomic_commit *state); -void dcp_hdcp_commit(struct drm_atomic_commit *state); -#else -static inline struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) { return NULL; } -static inline void dcp_hdcp_fini(struct apple_dcp *dcp) { } -static inline void dcp_hdcp_start_endpoints(struct apple_dcp *dcp) { } -static inline struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, - u32 endpoint) -{ - return NULL; -} - -static inline const struct apple_epic_service_ops * -dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, - bool cut) -{ - return NULL; -} - -static inline void dcp_hdcp_link_changed(struct apple_dcp *dcp) { } -static inline void dcp_hdcp_quiesce(struct apple_dcp *dcp) { } -static inline int dcp_hdcp_attach_connector(struct apple_connector *connector, - struct platform_device **dcps, - unsigned int n, int connector_type) -{ - return 0; -} - -static inline void dcp_hdcp_atomic_check(struct drm_connector *conn, - struct drm_atomic_commit *state) { } -static inline void dcp_hdcp_commit(struct drm_atomic_commit *state) { } -#endif - -#endif /* __APPLE_DCP_HDCP_DRV_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c b/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c deleted file mode 100644 index 0ed30dc541d5d4..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-glue-test.c +++ /dev/null @@ -1,175 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -/* The HDCP services' matching and the session's answers. Included from dcp-hdcp.c. */ - -#include - -struct glue_fixture { - struct apple_dcp dcp; - struct apple_dcp_afkep ep; - struct dcp_hdcp h; - struct apple_epic_service service; -}; - -static struct glue_fixture *glue_new(struct kunit *test, bool with_hdcp) -{ - struct glue_fixture *g = kunit_kzalloc(test, sizeof(*g), GFP_KERNEL); - - KUNIT_ASSERT_NOT_NULL(test, g); - g->ep.dcp = &g->dcp; - g->service.ep = &g->ep; - g->h.dcp = &g->dcp; - if (with_hdcp) - g->dcp.hdcp = &g->h; - return g; -} - -static void glue_match_by_name(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, true); - const struct apple_epic_service_ops *ops; - - ops = dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic:0", false); - KUNIT_ASSERT_NOT_NULL(test, ops); - KUNIT_EXPECT_PTR_EQ(test, (void *)ops->init, (void *)dcp_hdcp_relay_init); - ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-interface", false); - KUNIT_ASSERT_NOT_NULL(test, ops); - KUNIT_EXPECT_PTR_EQ(test, (void *)ops->init, (void *)dcp_hdcp_iface_init); - ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-auth-session", false); - KUNIT_ASSERT_NOT_NULL(test, ops); - KUNIT_EXPECT_PTR_EQ(test, (void *)ops->call_v2, (void *)dcp_hdcp_session_call); - - /* A cut long name matches only when the announcement filled its field. */ - KUNIT_EXPECT_NOT_NULL(test, dcp_hdcp_match_service(&g->ep, - "dcpdptx-hdcp-auth-sess", true)); - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, - "dcpdptx-hdcp-auth-sess", false)); - /* Other names, and a longer name that only starts the same. */ - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpav-device-epic", true)); - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epicx", false)); - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, NULL, false)); - - /* Without HDCP on this processor nothing is taken. */ - g = glue_new(test, false); - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic", false)); -} - -static void glue_session_without_hdcp_declines(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, false); - struct dcp_hdcp_word in = {}, out; - - KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_OPEN, - &in, sizeof(in), &out, sizeof(out)), 0); - KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, 0x55, &in, - sizeof(in), &out, sizeof(out)), - -EOPNOTSUPP); -} - -/* A declined open in the slot of an earlier session leaves it not ours. */ -static void glue_declined_open_forgets_slot(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, true); - struct dcp_hdcp_word in = {}, out; - - mutex_init(&g->h.lock); - spin_lock_init(&g->h.svc_lock); - init_waitqueue_head(&g->h.ev_wq); - g->h.wq = alloc_ordered_workqueue("hdcp-test", 0); - KUNIT_ASSERT_NOT_NULL(test, g->h.wq); - INIT_WORK(&g->h.event_work, dcp_hdcp_event_work); - INIT_WORK(&g->h.teardown_work, dcp_hdcp_teardown_work); - INIT_WORK(&g->h.prop_work, dcp_hdcp_prop_work); - INIT_WORK(&g->h.caps_work, dcp_hdcp_caps_work); - g->h.session = &g->service; - - /* Nothing asks for protection here: the open is declined. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_OPEN, - &in, sizeof(in), &out, sizeof(out)), 0); - KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); - KUNIT_EXPECT_NULL(test, g->h.session); - /* Its later events are answered and not acted on. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_session_call(&g->service, 0, DCP_HDCP_AUTH_H_PRIME, - &in, sizeof(in), &out, sizeof(out)), 0); - KUNIT_EXPECT_EQ(test, g->h.ev_bits, 0); - KUNIT_EXPECT_EQ(test, g->h.q_head, 0); - flush_workqueue(g->h.wq); - destroy_workqueue(g->h.wq); -} - -/* Sessions announced for HDCP 1.x are recorded, never taken, and forgotten on teardown. */ -static void glue_hdcp1_session_declined(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, true); - struct apple_epic_service other = { .ep = &g->ep }; - const struct apple_epic_service_ops *ops; - - spin_lock_init(&g->h.svc_lock); - ops = dcp_hdcp_match_service(&g->ep, "dcpdptx-hdcp-auth-session", false); - KUNIT_ASSERT_NOT_NULL(test, ops); - /* Every announced session keeps its own handler. */ - KUNIT_EXPECT_FALSE(test, ops->singleton); - - ops->init(&g->service, "dcpdptx-hdcp-auth-session", "TxHDCP1Session", 0); - ops->init(&other, "dcpdptx-hdcp-auth-session", "TxHDCP2Session", 0); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_is_hdcp1(&g->h, &g->service)); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &other)); - /* No class: taken for HDCP 2.2. */ - ops->init(&other, "dcpdptx-hdcp-auth-session", NULL, 0); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &other)); - - dcp_hdcp_session_teardown(&g->service); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_is_hdcp1(&g->h, &g->service)); -} - -/* A teardown asked for before DCP opened a newer session leaves that session alone. */ -static void glue_stale_teardown_skipped(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, true); - - spin_lock_init(&g->h.svc_lock); - g->h.td_seq = 1; - g->h.open_seq = 2; - g->h.tx.sep_open = true; - dcp_hdcp_teardown_work(&g->h.teardown_work); - KUNIT_EXPECT_TRUE(test, g->h.tx.sep_open); -} - -/* Unbind stops all work and unpublishes the state. */ -static void glue_fini_unpublishes(struct kunit *test) -{ - struct glue_fixture *g = glue_new(test, true); - - mutex_init(&g->h.lock); - spin_lock_init(&g->h.svc_lock); - init_waitqueue_head(&g->h.ev_wq); - INIT_WORK(&g->h.event_work, dcp_hdcp_event_work); - INIT_WORK(&g->h.teardown_work, dcp_hdcp_teardown_work); - INIT_WORK(&g->h.prop_work, dcp_hdcp_prop_work); - INIT_WORK(&g->h.relay_work, dcp_hdcp_relay_work); - INIT_WORK(&g->h.caps_work, dcp_hdcp_caps_work); - dcp_hdcp_fini(&g->dcp); - KUNIT_EXPECT_NULL(test, READ_ONCE(g->dcp.hdcp)); - KUNIT_EXPECT_TRUE(test, g->h.cancel); - /* Work queued after unbind never runs. */ - KUNIT_EXPECT_FALSE(test, queue_work(system_wq, &g->h.teardown_work)); - KUNIT_EXPECT_NULL(test, dcp_hdcp_match_service(&g->ep, "dcpdp-device-epic", false)); -} - -static struct kunit_case dcp_hdcp_glue_cases[] = { - KUNIT_CASE(glue_match_by_name), - KUNIT_CASE(glue_session_without_hdcp_declines), - KUNIT_CASE(glue_declined_open_forgets_slot), - KUNIT_CASE(glue_hdcp1_session_declined), - KUNIT_CASE(glue_stale_teardown_skipped), - KUNIT_CASE(glue_fini_unpublishes), - { } -}; - -static struct kunit_suite dcp_hdcp_glue_suite = { - .name = "apple-dcp-hdcp-glue", - .test_cases = dcp_hdcp_glue_cases, -}; -kunit_test_suite(dcp_hdcp_glue_suite); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-test.c b/drivers/gpu/drm/apple/dcp-hdcp-test.c deleted file mode 100644 index 09650183487e7e..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-test.c +++ /dev/null @@ -1,237 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -#include -#include - -#include "dcp-hdcp.h" - -static const unsigned long T0 = 1000; - -static struct dcp_hdcp_link bound(void) -{ - struct dcp_hdcp_link l = { .relay = true, .sep = true }; - - return l; -} - -static void hdcp_property_needs_all(struct kunit *test) -{ - KUNIT_EXPECT_TRUE(test, dcp_hdcp_attach_property(true, true, true)); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(false, true, true)); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(true, false, true)); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_attach_property(true, true, false)); -} - -static void hdcp_unbound_declines(struct kunit *test) -{ - struct dcp_hdcp_link l = { }; - - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_DESIRED); - l.relay = true; - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); - /* Both sides bound: ask DCP for a session. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, true, T0), DCP_HDCP_KICK); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); -} - -static void hdcp_undesired_declines(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_UNDESIRED); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_KICK); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); - /* One session at a time. */ - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); -} - -static void hdcp_session_enables(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - dcp_hdcp_request(&l, true, 1, T0); - KUNIT_ASSERT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_DESIRED); - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_ENABLED); - KUNIT_EXPECT_EQ(test, l.type, 1); - - /* Userspace turns it off: teardown, UNDESIRED. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, false, 1, T0), - DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_UNDESIRED); - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, false, 1, T0), DCP_HDCP_NONE); -} - -static void hdcp_type_change_reauths(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - dcp_hdcp_auth_done(&l, 1, 0, T0); - /* Same type again: nothing. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 0, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); - /* Type 1 now: the running session goes, no backoff. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_request(&l, true, 1, T0), - DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); - KUNIT_EXPECT_EQ(test, l.failures, 0); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); - KUNIT_EXPECT_EQ(test, l.type, 1); -} - -static void hdcp_failure_backs_off(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - unsigned long t = T0; - unsigned int i; - - dcp_hdcp_request(&l, true, 0, t); - dcp_hdcp_open(&l, 1, t); - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, -EACCES, t), - DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); - /* DCP's next open is declined until the backoff is over. */ - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, t + 1)); - t += msecs_to_jiffies(DCP_HDCP_RETRY_MS); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, t)); - - /* Doubling, capped. */ - for (i = 2; i < 12; i++) { - dcp_hdcp_auth_done(&l, 1, -EACCES, t); - KUNIT_EXPECT_EQ(test, l.failures, i); - t = l.retry_at; - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, t)); - } - KUNIT_EXPECT_EQ(test, dcp_hdcp_backoff(20), - msecs_to_jiffies(DCP_HDCP_RETRY_MAX_MS)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_backoff(2), - msecs_to_jiffies(2 * DCP_HDCP_RETRY_MS)); - /* A success resets it. */ - dcp_hdcp_auth_done(&l, 1, 0, t); - KUNIT_EXPECT_EQ(test, l.failures, 0); -} - -static void hdcp_close_mid_auth(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - /* DCP gives up on an attempt (a receiver timeout): a failure. */ - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 1, T0), DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.failures, 1); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_DESIRED); - /* The attempt's late result changes nothing. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); - - /* Closing an enabled session (re-authentication) is no failure. */ - l = bound(); - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - dcp_hdcp_auth_done(&l, 1, 0, T0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 1, T0), DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.failures, 0); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); - /* A close for another generation is ignored. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_closed(&l, 7, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_AUTH); -} - -static void hdcp_link_change_drops_enabled(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - dcp_hdcp_auth_done(&l, 1, 0, T0); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); - - /* Same generation: nothing. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_link_event(&l, 1, T0), DCP_HDCP_NONE); - /* Hotplug, DPMS, resume: back to DESIRED, no backoff. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_link_event(&l, 2, T0), DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_DESIRED); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 2, T0)); - /* A result from generation 1 is late. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, 0, T0), DCP_HDCP_NONE); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_AUTH); - /* A link change clears an earlier backoff. */ - dcp_hdcp_auth_done(&l, 2, -EACCES, T0); - KUNIT_EXPECT_EQ(test, l.failures, 1); - dcp_hdcp_link_event(&l, 3, T0); - KUNIT_EXPECT_EQ(test, l.failures, 0); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 3, T0)); -} - -static void hdcp_unbind_drops(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - dcp_hdcp_auth_done(&l, 1, 0, T0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, false, T0), - DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_DESIRED); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_bind(&l, true, true, T0), DCP_HDCP_KICK); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0)); -} - -static void hdcp_sep_busy_holds(struct kunit *test) -{ - struct dcp_hdcp_link l = bound(); - unsigned long hold = msecs_to_jiffies(DCP_HDCP_RETRY_MS); - - dcp_hdcp_request(&l, true, 0, T0); - dcp_hdcp_open(&l, 1, T0); - /* The SEP is busy: DESIRED, no failure counted, a short hold. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_done(&l, 1, -EAGAIN, T0), - DCP_HDCP_TEARDOWN); - KUNIT_EXPECT_EQ(test, l.failures, 0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_property(&l), - DRM_MODE_CONTENT_PROTECTION_DESIRED); - KUNIT_EXPECT_FALSE(test, dcp_hdcp_open(&l, 1, T0 + hold - 1)); - KUNIT_EXPECT_TRUE(test, dcp_hdcp_open(&l, 1, T0 + hold)); - dcp_hdcp_auth_done(&l, 1, 0, T0 + hold); - KUNIT_EXPECT_FALSE(test, l.hold); - KUNIT_EXPECT_EQ(test, l.state, DCP_HDCP_ENABLED); -} - -static struct kunit_case dcp_hdcp_cases[] = { - KUNIT_CASE(hdcp_property_needs_all), - KUNIT_CASE(hdcp_unbound_declines), - KUNIT_CASE(hdcp_undesired_declines), - KUNIT_CASE(hdcp_session_enables), - KUNIT_CASE(hdcp_type_change_reauths), - KUNIT_CASE(hdcp_failure_backs_off), - KUNIT_CASE(hdcp_close_mid_auth), - KUNIT_CASE(hdcp_link_change_drops_enabled), - KUNIT_CASE(hdcp_unbind_drops), - KUNIT_CASE(hdcp_sep_busy_holds), - { } -}; - -static struct kunit_suite dcp_hdcp_suite = { - .name = "apple-dcp-hdcp", - .test_cases = dcp_hdcp_cases, -}; -kunit_test_suite(dcp_hdcp_suite); - -MODULE_DESCRIPTION("KUnit tests for the Apple DCP HDCP policy"); -MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c b/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c deleted file mode 100644 index 344adca03ea35d..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-tx-test.c +++ /dev/null @@ -1,581 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -/* - * The transmitter procedure against a fake receiver (its HDCP 2.2 register - * map) and a fake SEP. Included from dcp-hdcp-tx.c. - */ - -#include - -#define FAKE_REG_BASE DP_HDCP_2_2_REG_RTX_OFFSET -#define FAKE_REG_SIZE 0x600 -#define FAKE_LOG 64 - -struct fake_write { - u32 addr; - size_t len; - u8 first; -}; - -struct fake { - struct kunit *test; - u8 regs[FAKE_REG_SIZE]; - - struct fake_write writes[FAKE_LOG]; - unsigned int nwrites; - enum dcp_hdcp_progress_code reports[FAKE_LOG]; - unsigned int nreports; - char sep[FAKE_LOG]; /* one letter per SEP call */ - unsigned int nsep; - unsigned int slept_ms; - - unsigned long events; /* BIT(op): DCP sends it */ - int cancel_op; /* -1, or the op whose wait is cancelled */ - bool stored; - int revoked_ids; /* returned by revoked() */ - unsigned int m_rejects; /* M' checks the SEP fails first */ - unsigned int l_rejects; /* L' checks the SEP fails first */ - bool sep_busy; /* the SEP is not available */ - bool encryption; - bool closed; - bool read_rxstatus; /* the TX read RxStatus */ -}; - -static int fake_read(void *ctx, u32 addr, void *buf, size_t len) -{ - struct fake *f = ctx; - - if (addr < FAKE_REG_BASE || addr + len > FAKE_REG_BASE + FAKE_REG_SIZE) - return -EIO; - if (addr == DP_HDCP_2_2_REG_RXSTATUS_OFFSET) - f->read_rxstatus = true; - memcpy(buf, f->regs + addr - FAKE_REG_BASE, len); - return 0; -} - -static int fake_write(void *ctx, u32 addr, const void *buf, size_t len) -{ - struct fake *f = ctx; - - if (addr < FAKE_REG_BASE || addr + len > FAKE_REG_BASE + FAKE_REG_SIZE) - return -EIO; - memcpy(f->regs + addr - FAKE_REG_BASE, buf, len); - if (f->nwrites < FAKE_LOG) - f->writes[f->nwrites++] = (struct fake_write){ addr, len, - ((u8 *)buf)[0] }; - return 0; -} - -static int fake_wait(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms) -{ - struct fake *f = ctx; - - if (f->cancel_op == op) - return -ECANCELED; - return (f->events & BIT(op)) ? 0 : -ETIMEDOUT; -} - -static void fake_report(void *ctx, enum dcp_hdcp_progress_code code, - bool active, bool repeater, bool encrypted) -{ - struct fake *f = ctx; - - if (f->nreports < FAKE_LOG) - f->reports[f->nreports++] = code; -} - -static int fake_revoked(void *ctx, u8 *ids, unsigned int count) -{ - return ((struct fake *)ctx)->revoked_ids; -} - -static void fake_sleep(void *ctx, unsigned int ms) -{ - ((struct fake *)ctx)->slept_ms += ms; -} - -static void sep_log(struct fake *f, char c) -{ - if (f->nsep < FAKE_LOG - 1) - f->sep[f->nsep++] = c; -} - -static int fake_sep_open(void *ctx, u32 ch, u8 *rtx) -{ - if (((struct fake *)ctx)->sep_busy) - return -EAGAIN; - sep_log(ctx, 'o'); - memset(rtx, 0xa1, HDCP_2_2_RTX_LEN); - return 0; -} - -static int fake_sep_ake_cert(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, - bool *stored, u8 *ekh_km_m, u8 *ekpub_km) -{ - struct fake *f = ctx; - - sep_log(f, 'c'); - *stored = f->stored; - memset(ekh_km_m, 0xb2, HDCP_2_2_E_KH_KM_M_LEN); - memset(ekpub_km, 0xc3, HDCP_2_2_E_KPUB_KM_LEN); - return 0; -} - -static int fake_sep_h_prime(void *ctx, u32 ch, const u8 *rxcaps, - const u8 *txcaps, const u8 *h_prime) -{ - struct fake *f = ctx; - - sep_log(f, 'h'); - /* H' covers RxCaps and TxCaps as the receiver sent and got them. */ - KUNIT_EXPECT_EQ(f->test, txcaps[0], HDCP_2_2_RX_CAPS_VERSION_VAL); - KUNIT_EXPECT_EQ(f->test, rxcaps[0], HDCP_2_2_RX_CAPS_VERSION_VAL); - return 0; -} - -static int fake_sep_pairing(void *ctx, u32 ch, const u8 *ekh_km) -{ - sep_log(ctx, 'p'); - return 0; -} - -static int fake_sep_lc_init(void *ctx, u32 ch, u8 *rn) -{ - sep_log(ctx, 'l'); - memset(rn, 0xd4, HDCP_2_2_RN_LEN); - return 0; -} - -static int fake_sep_l_prime(void *ctx, u32 ch, const u8 *l_prime) -{ - struct fake *f = ctx; - - sep_log(f, 'L'); - if (f->l_rejects) { - f->l_rejects--; - return -EACCES; - } - return 0; -} - -static int fake_sep_ske(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv) -{ - sep_log(ctx, 's'); - memset(edkey_ks, 0xe5, HDCP_2_2_E_DKEY_KS_LEN); - memset(riv, 0xf6, HDCP_2_2_RIV_LEN); - return 0; -} - -static int fake_sep_list(void *ctx, u32 ch, const u8 *ids, unsigned int count, - const u8 *rxinfo, const u8 *seq_num_v, - const u8 *v_prime, u8 *v) -{ - sep_log(ctx, 'r'); - memset(v, 0x11, HDCP_2_2_V_PRIME_HALF_LEN); - memset(v + HDCP_2_2_V_PRIME_HALF_LEN, 0x22, HDCP_2_2_V_PRIME_HALF_LEN); - return 0; -} - -static int fake_sep_stream(void *ctx, u32 ch, u8 stream_id, u8 type, - const u8 *seq_num_m, const u8 *m_prime) -{ - struct fake *f = ctx; - - sep_log(f, 'm'); - if (f->m_rejects) { - f->m_rejects--; - return -EACCES; - } - return 0; -} - -static int fake_sep_finish(void *ctx, u32 ch) -{ - sep_log(ctx, 'f'); - return 0; -} - -static int fake_sep_set_encryption(void *ctx, u32 ch, bool on) -{ - struct fake *f = ctx; - - sep_log(f, on ? 'E' : 'e'); - f->encryption = on; - return 0; -} - -static void fake_sep_close(void *ctx, u32 ch) -{ - struct fake *f = ctx; - - sep_log(f, 'x'); - f->closed = true; -} - -static const struct dcp_hdcp_tx_ops fake_ops = { - .read = fake_read, - .write = fake_write, - .wait = fake_wait, - .report = fake_report, - .revoked = fake_revoked, - .sleep = fake_sleep, - .sep_open = fake_sep_open, - .sep_ake_cert = fake_sep_ake_cert, - .sep_h_prime = fake_sep_h_prime, - .sep_pairing = fake_sep_pairing, - .sep_lc_init = fake_sep_lc_init, - .sep_l_prime = fake_sep_l_prime, - .sep_ske = fake_sep_ske, - .sep_repeater_list = fake_sep_list, - .sep_repeater_stream = fake_sep_stream, - .sep_finish = fake_sep_finish, - .sep_set_encryption = fake_sep_set_encryption, - .sep_close = fake_sep_close, -}; - -static u8 *reg(struct fake *f, u32 addr) -{ - return f->regs + addr - FAKE_REG_BASE; -} - -/* A receiver that does HDCP 2.2, a repeater or not. */ -static void fake_receiver(struct fake *f, bool repeater) -{ - u8 *caps = reg(f, DP_HDCP_2_2_REG_RX_CAPS_OFFSET); - - caps[0] = HDCP_2_2_RX_CAPS_VERSION_VAL; - caps[1] = 0; - caps[2] = BIT(1) | (repeater ? BIT(0) : 0); - memset(reg(f, DP_HDCP_2_2_REG_CERT_RX_OFFSET), 0x5a, - sizeof(struct hdcp2_cert_rx)); - f->events = BIT(DCP_HDCP_AUTH_H_PRIME) | BIT(DCP_HDCP_AUTH_PAIRING); - if (repeater) { - u8 *rxinfo = reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET); - - /* Depth 1, one device. */ - rxinfo[0] = 0x02; - rxinfo[1] = 0x10; - f->events |= BIT(DCP_HDCP_AUTH_LIST); - } -} - -static struct fake *fake_new(struct kunit *test, struct dcp_hdcp_tx *tx, - bool repeater, u8 type) -{ - struct fake *f = kunit_kzalloc(test, sizeof(*f), GFP_KERNEL); - - KUNIT_ASSERT_NOT_NULL(test, f); - f->test = test; - f->cancel_op = -1; - fake_receiver(f, repeater); - memset(tx, 0, sizeof(*tx)); - tx->ops = &fake_ops; - tx->ctx = f; - tx->channel = 7; - tx->type = type; - return f; -} - -static bool wrote(struct fake *f, u32 addr, size_t len) -{ - unsigned int i; - - for (i = 0; i < f->nwrites; i++) - if (f->writes[i].addr == addr && f->writes[i].len == len) - return true; - return false; -} - -static bool reported(struct fake *f, enum dcp_hdcp_progress_code code) -{ - unsigned int i; - - for (i = 0; i < f->nreports; i++) - if (f->reports[i] == code) - return true; - return false; -} - -static void tx_stored_km_type0(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - f->stored = true; - KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_STREQ(test, f->sep, "ochlLsfE"); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RTX_OFFSET, 8)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_TXCAPS_OFFSET, 3)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EKH_KM_WR_OFFSET, 32)); - KUNIT_EXPECT_FALSE(test, wrote(f, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, 128)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RN_OFFSET, 8)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EDKEY_KS_OFFSET, 16)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_RIV_OFFSET, 8)); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, 1)); - KUNIT_EXPECT_EQ(test, *reg(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET), 0); - KUNIT_EXPECT_FALSE(test, reported(f, DCP_HDCP_PROGRESS_H_VERIFIED)); - KUNIT_EXPECT_EQ(test, f->reports[f->nreports - 1], - DCP_HDCP_PROGRESS_ENCRYPTED); - /* The cert after 100 ms, L' after 16 ms, encryption 200 ms after the keys. */ - KUNIT_EXPECT_EQ(test, f->slept_ms, HDCP_2_2_CERT_TIMEOUT_MS + - HDCP_2_2_DP_LPRIME_TIMEOUT_MS + - HDCP_2_2_DELAY_BEFORE_ENCRYPTION_EN); - KUNIT_EXPECT_TRUE(test, f->encryption); - KUNIT_EXPECT_FALSE(test, tx.repeater); - - dcp_hdcp_abort(&tx); - KUNIT_EXPECT_FALSE(test, f->encryption); - KUNIT_EXPECT_TRUE(test, f->closed); -} - -static void tx_first_pairing(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_STREQ(test, f->sep, "ochplLsfE"); - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, 128)); - KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_H_VERIFIED)); - - /* No pairing information: the attempt fails, nothing is encrypted. */ - f = fake_new(test, &tx, false, 0); - f->events &= ~BIT(DCP_HDCP_AUTH_PAIRING); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ETIMEDOUT); - KUNIT_EXPECT_FALSE(test, f->encryption); -} - -static void tx_repeater_types(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f; - u8 *sm; - u8 type; - - for (type = 0; type <= 1; type++) { - f = fake_new(test, &tx, true, type); - f->stored = true; - KUNIT_ASSERT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_STREQ(test, f->sep, "ochlLsrmfE"); - KUNIT_EXPECT_TRUE(test, tx.repeater); - KUNIT_EXPECT_EQ(test, tx.device_count, 1); - KUNIT_EXPECT_EQ(test, tx.depth, 1); - /* The ack carries V's low half. */ - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_V_OFFSET, 16)); - KUNIT_EXPECT_EQ(test, *reg(f, DP_HDCP_2_2_REG_V_OFFSET), 0x22); - /* seq_num_M 0, k 1, stream 0 with the type asked for. */ - KUNIT_EXPECT_TRUE(test, wrote(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET, 7)); - sm = reg(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET); - KUNIT_EXPECT_EQ(test, get_unaligned_be24(sm), 0); - KUNIT_EXPECT_EQ(test, get_unaligned_be16(sm + 3), 1); - KUNIT_EXPECT_EQ(test, sm[5], 0); - KUNIT_EXPECT_EQ(test, sm[6], type); - KUNIT_EXPECT_EQ(test, tx.seq_num_m, 1); - KUNIT_EXPECT_FALSE(test, wrote(f, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, 1)); - KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_LIST_VERIFIED)); - KUNIT_EXPECT_TRUE(test, reported(f, DCP_HDCP_PROGRESS_STREAM_READY)); - } -} - -static void tx_type1_refused_downstream_legacy(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f; - u8 legacy[] = { BIT(0), BIT(1) }; /* HDCP 1.x device, 2.0 repeater */ - int i; - - for (i = 0; i < ARRAY_SIZE(legacy); i++) { - f = fake_new(test, &tx, true, 1); - reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= legacy[i]; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPERM); - KUNIT_EXPECT_FALSE(test, f->encryption); - KUNIT_EXPECT_TRUE(test, tx.legacy_downstream); - dcp_hdcp_abort(&tx); - KUNIT_EXPECT_TRUE(test, f->closed); - /* Never asked to turn encryption off: it never went on. */ - KUNIT_EXPECT_EQ(test, f->sep[f->nsep - 1], 'x'); - - /* Type 0 goes through the same topology. */ - f = fake_new(test, &tx, true, 0); - reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= legacy[i]; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - } -} - -static void tx_topology_exceeded(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, true, 0); - - reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= BIT(3); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); - f = fake_new(test, &tx, true, 0); - reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] |= BIT(2); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); - /* A list that names no device. */ - f = fake_new(test, &tx, true, 0); - reg(f, DP_HDCP_2_2_REG_RXINFO_OFFSET)[1] = 0; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -E2BIG); - /* The first list of a session must carry seq_num_V 0. */ - f = fake_new(test, &tx, true, 0); - reg(f, DP_HDCP_2_2_REG_SEQ_NUM_V_OFFSET)[2] = 1; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPROTO); - KUNIT_EXPECT_FALSE(test, f->encryption); -} - -/* A certificate read too early or garbled never reaches the SEP. */ -static void tx_bad_receiver_id(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - memset(reg(f, DP_HDCP_2_2_REG_CERT_RX_OFFSET), 0xff, HDCP_2_2_RECEIVER_ID_LEN); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPROTO); - KUNIT_EXPECT_STREQ(test, tx.step, "check Receiver ID"); - KUNIT_EXPECT_FALSE(test, f->encryption); -} - -static void tx_revoked(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - /* The receiver's own ID: refused before the SEP sees the cert. */ - f->revoked_ids = 1; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EPERM); - KUNIT_EXPECT_STREQ(test, f->sep, "o"); - - /* An SRM that cannot be read fails closed. */ - f = fake_new(test, &tx, false, 0); - f->revoked_ids = -EINVAL; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EINVAL); - KUNIT_EXPECT_FALSE(test, f->encryption); -} - -static void tx_timeout_and_rxstatus(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - f->stored = true; - f->events = 0; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ETIMEDOUT); - KUNIT_EXPECT_FALSE(test, f->encryption); - - /* An overdue event, but RxStatus says H' is there. */ - f = fake_new(test, &tx, false, 0); - f->stored = true; - f->events = 0; - *reg(f, DP_HDCP_2_2_REG_RXSTATUS_OFFSET) = BIT(1); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - - /* An event on time: RxStatus is left to DCP. */ - f = fake_new(test, &tx, false, 0); - f->stored = true; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_FALSE(test, f->read_rxstatus); -} - -static void tx_close_mid_auth(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, true, 0); - - /* DCP closes while the ReceiverID list is awaited. */ - f->cancel_op = DCP_HDCP_AUTH_LIST; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ECANCELED); - KUNIT_EXPECT_FALSE(test, reported(f, DCP_HDCP_PROGRESS_LIST_VERIFIED)); - dcp_hdcp_abort(&tx); - KUNIT_EXPECT_TRUE(test, f->closed); - KUNIT_EXPECT_FALSE(test, f->encryption); - /* A second abort is harmless. */ - f->nsep = 0; - memset(f->sep, 0, sizeof(f->sep)); - dcp_hdcp_abort(&tx); - KUNIT_EXPECT_EQ(test, f->nsep, 0); -} - -static void tx_m_prime_retry(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, true, 1); - - f->m_rejects = 1; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_EQ(test, tx.seq_num_m, 2); - KUNIT_EXPECT_EQ(test, get_unaligned_be24(reg(f, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET)), 1); - - f = fake_new(test, &tx, true, 1); - f->m_rejects = 2; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EACCES); - KUNIT_EXPECT_FALSE(test, f->encryption); -} - -static void tx_not_capable(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - KUNIT_EXPECT_EQ(test, dcp_hdcp_capable(&tx), 1); - reg(f, DP_HDCP_2_2_REG_RX_CAPS_OFFSET)[2] = 0; - KUNIT_EXPECT_EQ(test, dcp_hdcp_capable(&tx), 0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -ENODEV); - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&(struct dcp_hdcp_tx){ - .ops = &fake_ops, .ctx = f, .type = 2 }), - -EINVAL); - -} - -static void tx_l_prime_retry(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - /* Each retry starts with a fresh r_n. */ - f->stored = true; - f->l_rejects = DCP_HDCP_LC_TRIES - 1; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), 0); - KUNIT_EXPECT_STREQ(test, f->sep, "ochlLlLlLsfE"); - - f = fake_new(test, &tx, false, 0); - f->stored = true; - f->l_rejects = DCP_HDCP_LC_TRIES; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EACCES); - KUNIT_EXPECT_STREQ(test, f->sep, "ochlLlLlL"); -} - -static void tx_sep_busy(struct kunit *test) -{ - struct dcp_hdcp_tx tx; - struct fake *f = fake_new(test, &tx, false, 0); - - f->sep_busy = true; - KUNIT_EXPECT_EQ(test, dcp_hdcp_authenticate(&tx), -EAGAIN); - KUNIT_EXPECT_EQ(test, f->nwrites, 0); - dcp_hdcp_abort(&tx); - KUNIT_EXPECT_EQ(test, f->nsep, 0); -} - -static struct kunit_case dcp_hdcp_tx_cases[] = { - KUNIT_CASE(tx_stored_km_type0), - KUNIT_CASE(tx_first_pairing), - KUNIT_CASE(tx_repeater_types), - KUNIT_CASE(tx_type1_refused_downstream_legacy), - KUNIT_CASE(tx_topology_exceeded), - KUNIT_CASE(tx_revoked), - KUNIT_CASE(tx_bad_receiver_id), - KUNIT_CASE(tx_timeout_and_rxstatus), - KUNIT_CASE(tx_close_mid_auth), - KUNIT_CASE(tx_m_prime_retry), - KUNIT_CASE(tx_l_prime_retry), - KUNIT_CASE(tx_sep_busy), - KUNIT_CASE(tx_not_capable), - { } -}; - -static struct kunit_suite dcp_hdcp_tx_suite = { - .name = "apple-dcp-hdcp-tx", - .test_cases = dcp_hdcp_tx_cases, -}; -kunit_test_suite(dcp_hdcp_tx_suite); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx.c b/drivers/gpu/drm/apple/dcp-hdcp-tx.c deleted file mode 100644 index 222c0a74ab6d9a..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-tx.c +++ /dev/null @@ -1,374 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -#include -#include -#include -#include -#include - -#include "dcp-hdcp-tx.h" - -/* Each step names itself, so a failed attempt says where it stopped. */ -#define TX_READ(tx, reg, buf, len) \ - ((tx)->step = "read " #reg, (tx)->ops->read((tx)->ctx, reg, buf, len)) -#define TX_WRITE(tx, reg, buf, len) \ - ((tx)->step = "write " #reg, (tx)->ops->write((tx)->ctx, reg, buf, len)) -#define TX_SEP(tx, fn) ((tx)->step = #fn, (tx)->ops->fn) - -static void tx_report(struct dcp_hdcp_tx *tx, enum dcp_hdcp_progress_code code, - bool encrypted) -{ - tx->ops->report(tx->ctx, code, true, tx->repeater, encrypted); -} - -/* - * Waits for a session event. DCP turns the receiver's RxStatus into these - * events, so RxStatus is read only once the event is overdue (spec time plus - * slack): a DisplayPort read clears the bits DCP waits for. Some paths (an - * on-board DP to HDMI converter) never raise the event although the receiver - * has the message ready. - */ -static int tx_wait(struct dcp_hdcp_tx *tx, enum dcp_hdcp_auth_op op, - unsigned int spec_ms) -{ - u8 status; - int ret; - - tx->step = "wait for DCP event"; - ret = tx->ops->wait(tx->ctx, op, spec_ms + DCP_HDCP_EVENT_SLACK_MS); - if (ret != -ETIMEDOUT) - return ret; - if (TX_READ(tx, DP_HDCP_2_2_REG_RXSTATUS_OFFSET, &status, 1)) - return -ETIMEDOUT; - switch (op) { - case DCP_HDCP_AUTH_H_PRIME: - return HDCP_2_2_DP_RXSTATUS_H_PRIME(status) ? 0 : -ETIMEDOUT; - case DCP_HDCP_AUTH_PAIRING: - return HDCP_2_2_DP_RXSTATUS_PAIRING(status) ? 0 : -ETIMEDOUT; - case DCP_HDCP_AUTH_LIST: - return HDCP_2_2_DP_RXSTATUS_READY(status) ? 0 : -ETIMEDOUT; - default: - return -ETIMEDOUT; - } -} - -/* Any revoked ID, or an SRM that cannot be read, fails the attempt. */ -static int tx_revocation(struct dcp_hdcp_tx *tx, u8 *ids, unsigned int count) -{ - int ret = tx->ops->revoked(tx->ctx, ids, count); - - if (ret > 0) - return -EPERM; - return ret; -} - -/* Twenty ones and twenty zeros, as every HDCP Receiver ID. */ -static bool dcp_hdcp_receiver_id_valid(const u8 *id) -{ - unsigned int i, ones = 0; - - for (i = 0; i < HDCP_2_2_RECEIVER_ID_LEN; i++) - ones += hweight8(id[i]); - return ones == 20; -} - -int dcp_hdcp_capable(struct dcp_hdcp_tx *tx) -{ - int ret = TX_READ(tx, DP_HDCP_2_2_REG_RX_CAPS_OFFSET, tx->rxcaps, - sizeof(tx->rxcaps)); - - if (ret) - return ret; - return dcp_hdcp_rxcaps_capable(tx->rxcaps); -} - -static int tx_ake(struct dcp_hdcp_tx *tx, bool *stored) -{ - u8 rtx[HDCP_2_2_RTX_LEN]; - u8 ekh_km_m[HDCP_2_2_E_KH_KM_M_LEN]; - u8 ekpub_km[HDCP_2_2_E_KPUB_KM_LEN]; - u8 h_prime[HDCP_2_2_H_PRIME_LEN]; - u8 ekh_km[HDCP_2_2_E_KH_KM_LEN]; - int ret; - - ret = TX_SEP(tx, sep_open)(tx->ctx, tx->channel, rtx); - if (ret) - return ret; - tx->sep_open = true; - - /* AKE_Init */ - tx->txcaps.version = HDCP_2_2_RX_CAPS_VERSION_VAL; - tx->txcaps.tx_cap_mask[0] = 0; - tx->txcaps.tx_cap_mask[1] = 0; - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RTX_OFFSET, rtx, sizeof(rtx)); - if (!ret) - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_TXCAPS_OFFSET, &tx->txcaps, - sizeof(tx->txcaps)); - if (ret) - return ret; - - /* AKE_Send_Cert: the receiver has 100 ms to make it readable. */ - tx->step = "wait for AKE_Send_Cert"; - tx->ops->sleep(tx->ctx, HDCP_2_2_CERT_TIMEOUT_MS); - ret = TX_READ(tx, DP_HDCP_2_2_REG_CERT_RX_OFFSET, &tx->cert, - sizeof(tx->cert)); - /* A Receiver ID has twenty ones and twenty zeros; anything else is a bad read. */ - if (!ret && !dcp_hdcp_receiver_id_valid(tx->cert.receiver_id)) { - tx->step = "check Receiver ID"; - ret = -EPROTO; - } - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_RRX_OFFSET, tx->rrx, - sizeof(tx->rrx)); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_RX_CAPS_OFFSET, tx->rxcaps, - sizeof(tx->rxcaps)); - if (ret) - return ret; - if (!dcp_hdcp_rxcaps_capable(tx->rxcaps)) - return -ENODEV; - tx->repeater = HDCP_2_2_RX_REPEATER(tx->rxcaps[2]); - ret = tx_revocation(tx, tx->cert.receiver_id, 1); - if (ret) - return ret; - ret = TX_SEP(tx, sep_ake_cert)(tx->ctx, tx->channel, (const u8 *)&tx->cert, - tx->rrx, stored, ekh_km_m, ekpub_km); - if (ret) - return ret; - - /* AKE_Stored_km (Ekh(km) then m, contiguous) or AKE_No_Stored_km */ - if (*stored) - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EKH_KM_WR_OFFSET, ekh_km_m, - sizeof(ekh_km_m)); - else - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EKPUB_KM_OFFSET, ekpub_km, - sizeof(ekpub_km)); - if (ret) - return ret; - tx_report(tx, DCP_HDCP_PROGRESS_KM_SENT, false); - - /* AKE_Send_H_prime */ - ret = tx_wait(tx, DCP_HDCP_AUTH_H_PRIME, - *stored ? HDCP_2_2_HPRIME_PAIRED_TIMEOUT_MS : - HDCP_2_2_HPRIME_NO_PAIRED_TIMEOUT_MS); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_HPRIME_OFFSET, h_prime, - sizeof(h_prime)); - if (!ret) - ret = TX_SEP(tx, sep_h_prime)(tx->ctx, tx->channel, tx->rxcaps, - (const u8 *)&tx->txcaps, h_prime); - if (ret) - return ret; - if (*stored) - return 0; - - /* AKE_Send_Pairing_Info */ - tx_report(tx, DCP_HDCP_PROGRESS_H_VERIFIED, false); - ret = tx_wait(tx, DCP_HDCP_AUTH_PAIRING, HDCP_2_2_PAIRING_TIMEOUT_MS); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_EKH_KM_RD_OFFSET, ekh_km, - sizeof(ekh_km)); - if (!ret) - ret = TX_SEP(tx, sep_pairing)(tx->ctx, tx->channel, ekh_km); - return ret; -} - -static int tx_lc_ske(struct dcp_hdcp_tx *tx) -{ - u8 rn[HDCP_2_2_RN_LEN]; - u8 l_prime[HDCP_2_2_L_PRIME_LEN]; - u8 edkey_ks[HDCP_2_2_E_DKEY_KS_LEN]; - u8 riv[HDCP_2_2_RIV_LEN]; - int attempt, ret; - - /* - * LC_Init, then LC_Send_L_prime once the receiver had its time. A - * wrong L' is retried with a fresh r_n, a bounded number of times. - */ - for (attempt = 0; attempt < DCP_HDCP_LC_TRIES; attempt++) { - ret = TX_SEP(tx, sep_lc_init)(tx->ctx, tx->channel, rn); - if (!ret) - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RN_OFFSET, rn, sizeof(rn)); - if (ret) - return ret; - tx->ops->sleep(tx->ctx, HDCP_2_2_DP_LPRIME_TIMEOUT_MS); - ret = TX_READ(tx, DP_HDCP_2_2_REG_LPRIME_OFFSET, l_prime, - sizeof(l_prime)); - if (!ret) - ret = TX_SEP(tx, sep_l_prime)(tx->ctx, tx->channel, l_prime); - if (ret != -EACCES) - break; - } - if (ret) - return ret; - - /* SKE_Send_Eks */ - ret = TX_SEP(tx, sep_ske)(tx->ctx, tx->channel, edkey_ks, riv); - if (!ret) - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_EDKEY_KS_OFFSET, edkey_ks, - sizeof(edkey_ks)); - if (!ret) - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_RIV_OFFSET, riv, sizeof(riv)); - if (!ret) - tx_report(tx, DCP_HDCP_PROGRESS_SKE_SENT, false); - return ret; -} - -static int tx_receiver_list(struct dcp_hdcp_tx *tx) -{ - u8 rxinfo[HDCP_2_2_RXINFO_LEN]; - u8 seq_num_v[HDCP_2_2_SEQ_NUM_LEN]; - u8 v_prime[HDCP_2_2_V_PRIME_HALF_LEN]; - u8 v[2 * HDCP_2_2_V_PRIME_HALF_LEN]; - unsigned int count; - int ret; - - ret = tx_wait(tx, DCP_HDCP_AUTH_LIST, HDCP_2_2_RECVID_LIST_TIMEOUT_MS); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_RXINFO_OFFSET, rxinfo, - sizeof(rxinfo)); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_SEQ_NUM_V_OFFSET, seq_num_v, - sizeof(seq_num_v)); - if (!ret) - ret = TX_READ(tx, DP_HDCP_2_2_REG_VPRIME_OFFSET, v_prime, - sizeof(v_prime)); - if (ret) - return ret; - - /* Topology: too many devices or levels downstream fails the attempt. */ - if (HDCP_2_2_MAX_CASCADE_EXCEEDED(rxinfo[1]) || - HDCP_2_2_MAX_DEVS_EXCEEDED(rxinfo[1])) - return -E2BIG; - count = (HDCP_2_2_DEV_COUNT_HI(rxinfo[0]) << 4) | - HDCP_2_2_DEV_COUNT_LO(rxinfo[1]); - if (!count || count > HDCP_2_2_MAX_DEVICE_COUNT) - return -E2BIG; - tx->device_count = count; - tx->depth = HDCP_2_2_DEPTH(rxinfo[0]); - tx->legacy_downstream = HDCP_2_2_HDCP1_DEVICE_CONNECTED(rxinfo[1]) || - HDCP_2_2_HDCP_2_0_REP_CONNECTED(rxinfo[1]); - /* The first list of a session carries seq_num_V 0. */ - if (get_unaligned_be24(seq_num_v)) - return -EPROTO; - - ret = TX_READ(tx, DP_HDCP_2_2_REG_RECV_ID_LIST_OFFSET, tx->ids, - count * HDCP_2_2_RECEIVER_ID_LEN); - if (ret) - return ret; - ret = tx_revocation(tx, tx->ids, count); - if (ret) - return ret; - ret = TX_SEP(tx, sep_repeater_list)(tx->ctx, tx->channel, tx->ids, count, - rxinfo, seq_num_v, v_prime, v); - if (ret) - return ret; - - /* RepeaterAuth_Send_Ack: the least significant 128 bits of V. */ - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_V_OFFSET, v + HDCP_2_2_V_PRIME_HALF_LEN, - HDCP_2_2_V_PRIME_HALF_LEN); - if (!ret) - tx_report(tx, DCP_HDCP_PROGRESS_LIST_VERIFIED, false); - return ret; -} - -/* - * RepeaterAuth_Stream_Manage for the one stream, then Stream_Ready. A wrong - * M' is retried once with the next seq_num_M, as the specification allows. - */ -static int tx_stream_manage(struct dcp_hdcp_tx *tx) -{ - u8 msg[HDCP_2_2_SEQ_NUM_LEN + 2 + sizeof(struct hdcp2_streamid_type)]; - u8 m_prime[HDCP_2_2_MPRIME_LEN]; - int attempt, ret = -EACCES; - - /* Type 1 must not reach an HDCP 1.x device or an HDCP 2.0 repeater. */ - if (tx->type && tx->legacy_downstream) - return -EPERM; - - for (attempt = 0; attempt < 2 && ret == -EACCES; attempt++) { - if (tx->seq_num_m > HDCP_2_2_SEQ_NUM_MAX) - return -ERANGE; - put_unaligned_be24(tx->seq_num_m, msg); - put_unaligned_be16(1, msg + HDCP_2_2_SEQ_NUM_LEN); - msg[HDCP_2_2_SEQ_NUM_LEN + 2] = 0; /* stream ID */ - msg[HDCP_2_2_SEQ_NUM_LEN + 3] = tx->type; - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_SEQ_NUM_M_OFFSET, msg, - sizeof(msg)); - if (ret) - return ret; - tx->ops->sleep(tx->ctx, HDCP_2_2_STREAM_READY_TIMEOUT_MS); - ret = TX_READ(tx, DP_HDCP_2_2_REG_MPRIME_OFFSET, m_prime, - sizeof(m_prime)); - if (ret) - return ret; - ret = TX_SEP(tx, sep_repeater_stream)(tx->ctx, tx->channel, 0, - tx->type, msg, m_prime); - tx->seq_num_m++; - } - if (!ret) - tx_report(tx, DCP_HDCP_PROGRESS_STREAM_READY, false); - return ret; -} - -int dcp_hdcp_authenticate(struct dcp_hdcp_tx *tx) -{ - bool stored = false; - int ret; - - tx->step = NULL; - if (tx->type > 1) - return -EINVAL; - tx->repeater = false; - tx->legacy_downstream = false; - tx->device_count = 0; - tx->depth = 0; - tx->seq_num_m = 0; - tx_report(tx, DCP_HDCP_PROGRESS_AKE, false); - - ret = tx_ake(tx, &stored); - if (ret) - return ret; - tx_report(tx, DCP_HDCP_PROGRESS_AKE_DONE, false); - ret = tx_lc_ske(tx); - if (ret) - return ret; - - if (tx->repeater) { - ret = tx_receiver_list(tx); - if (!ret) - ret = tx_stream_manage(tx); - } else { - ret = TX_WRITE(tx, DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, &tx->type, - sizeof(tx->type)); - } - if (ret) - return ret; - - /* Encryption no sooner than 200 ms after SKE_Send_Eks. */ - ret = TX_SEP(tx, sep_finish)(tx->ctx, tx->channel); - if (ret) - return ret; - tx->ops->sleep(tx->ctx, HDCP_2_2_DELAY_BEFORE_ENCRYPTION_EN); - tx->encrypting = true; - ret = TX_SEP(tx, sep_set_encryption)(tx->ctx, tx->channel, true); - if (ret) - return ret; - tx_report(tx, DCP_HDCP_PROGRESS_ENCRYPTED, true); - return 0; -} - -void dcp_hdcp_abort(struct dcp_hdcp_tx *tx) -{ - if (tx->encrypting) - TX_SEP(tx, sep_set_encryption)(tx->ctx, tx->channel, false); - tx->encrypting = false; - if (tx->sep_open) - TX_SEP(tx, sep_close)(tx->ctx, tx->channel); - tx->sep_open = false; -} - -#if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) -#include "dcp-hdcp-tx-test.c" -#endif diff --git a/drivers/gpu/drm/apple/dcp-hdcp-tx.h b/drivers/gpu/drm/apple/dcp-hdcp-tx.h deleted file mode 100644 index 7f1446e86f2392..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-tx.h +++ /dev/null @@ -1,118 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -/* Copyright 2026 Ryan Murray */ -#ifndef __APPLE_DCP_HDCP_TX_H__ -#define __APPLE_DCP_HDCP_TX_H__ - -#include -#include -#include - -#include "dcp-hdcp-wire.h" - -/* - * One HDCP 2.2 transmitter authentication, as the AP runs it with the SEP - * doing the cryptography: every message is built from the fields the SEP - * returns and written to, or read from, the receiver's HDCP 2.2 registers - * through DCP. The procedure runs once DCP has opened a session and started - * it, and blocks: it waits for DCP's session events and sleeps where the - * specification asks for it. It never touches the display. - * - * DCP owns the receiver timeouts and closes an attempt that runs out of - * time; the waits below only guard against a session DCP forgets. An event - * travels receiver CP_IRQ -> DCP -> mailbox -> this driver's work queue on - * top of the spec time, so the guard is the spec time plus this slack; it is - * not a spec value and only decides when RxStatus is read as a fallback. - */ -#define DCP_HDCP_EVENT_SLACK_MS 500 -/* Locality check attempts, each with a fresh r_n. */ -#define DCP_HDCP_LC_TRIES 3 - -struct dcp_hdcp_tx_ops { - /* Receiver registers (DP_HDCP_2_2_REG_*). */ - int (*read)(void *ctx, u32 addr, void *buf, size_t len); - int (*write)(void *ctx, u32 addr, const void *buf, size_t len); - /* - * Waits up to @ms for session event @op. Returns 0 when it came, - * -ETIMEDOUT, or -ECANCELED when the session was closed or the - * protection is no longer wanted. - */ - int (*wait)(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms); - void (*report)(void *ctx, enum dcp_hdcp_progress_code code, - bool active, bool repeater, bool encrypted); - /* drm_hdcp_check_ksvs_revoked(): the count of revoked IDs, or <0. */ - int (*revoked)(void *ctx, u8 *ids, unsigned int count); - void (*sleep)(void *ctx, unsigned int ms); - - /* The SEP service, include/linux/apple-sep-hdcp.h. */ - int (*sep_open)(void *ctx, u32 ch, u8 *rtx); - int (*sep_ake_cert)(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, - bool *stored, u8 *ekh_km_m, u8 *ekpub_km); - int (*sep_h_prime)(void *ctx, u32 ch, const u8 *rxcaps, - const u8 *txcaps, const u8 *h_prime); - int (*sep_pairing)(void *ctx, u32 ch, const u8 *ekh_km); - int (*sep_lc_init)(void *ctx, u32 ch, u8 *rn); - int (*sep_l_prime)(void *ctx, u32 ch, const u8 *l_prime); - int (*sep_ske)(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv); - int (*sep_repeater_list)(void *ctx, u32 ch, const u8 *ids, - unsigned int count, const u8 *rxinfo, - const u8 *seq_num_v, const u8 *v_prime, u8 *v); - int (*sep_repeater_stream)(void *ctx, u32 ch, u8 stream_id, u8 type, - const u8 *seq_num_m, const u8 *m_prime); - int (*sep_finish)(void *ctx, u32 ch); - int (*sep_set_encryption)(void *ctx, u32 ch, bool on); - void (*sep_close)(void *ctx, u32 ch); -}; - -struct dcp_hdcp_tx { - const struct dcp_hdcp_tx_ops *ops; - void *ctx; - u32 channel; - /* The content type asked for: 0 or 1. */ - u8 type; - - /* Results, valid after dcp_hdcp_authenticate() returned 0. */ - bool repeater; - bool legacy_downstream; - unsigned int device_count; - unsigned int depth; - - /* Session state; @step names the last step tried. */ - const char *step; - bool sep_open; - bool encrypting; - u32 seq_num_m; - - /* Scratch: the messages of one attempt. */ - u8 rxcaps[HDCP_2_2_RXCAPS_LEN]; - struct hdcp2_tx_caps txcaps; - struct hdcp2_cert_rx cert; - u8 rrx[HDCP_2_2_RRX_LEN]; - u8 ids[HDCP_2_2_RECEIVER_IDS_MAX_LEN]; -}; - -/* The receiver says it does HDCP 2.2 over DP. */ -static inline bool dcp_hdcp_rxcaps_capable(const u8 *rxcaps) -{ - return rxcaps[0] == HDCP_2_2_RX_CAPS_VERSION_VAL && - HDCP_2_2_DP_HDCP_CAPABLE(rxcaps[2]); -} - -/* Reads RxCaps: 1 when the receiver can do HDCP 2.2, 0 when not, or <0. */ -int dcp_hdcp_capable(struct dcp_hdcp_tx *tx); - -/* - * Runs one authentication to encryption. On 0 the link is encrypted with - * tx->type; on failure the caller ends it with dcp_hdcp_abort(). -EAGAIN - * means the SEP was not available for now: no failure of the receiver. - */ -int dcp_hdcp_authenticate(struct dcp_hdcp_tx *tx); - -/* Encryption off and the SEP session closed; safe at any point. */ -void dcp_hdcp_abort(struct dcp_hdcp_tx *tx); - -/* - * The receiver's status on an encrypted link: 0 while it holds, -EAGAIN when - * it asks for re-authentication or reports a link integrity failure. - */ - -#endif /* __APPLE_DCP_HDCP_TX_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c b/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c deleted file mode 100644 index 2ca3e8c463dc10..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-wire-test.c +++ /dev/null @@ -1,156 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -#include -#include -#include - -#include "dcp-hdcp-wire.h" - -static void wire_read_encode(struct kunit *test) -{ - u8 body[DCP_HDCP_REG_ARGS_LEN + 522]; - - memset(body, 0xff, sizeof(body)); - KUNIT_ASSERT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), - DP_HDCP_2_2_REG_CERT_RX_OFFSET, - 522, DCP_HDCP_REG_TIMEOUT_MS), - (int)sizeof(body)); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body), 0x6900b); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 16), 522); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 32), 500); - KUNIT_EXPECT_EQ(test, body[4], 0); - KUNIT_EXPECT_EQ(test, body[sizeof(body) - 1], 0); - - /* No room, nothing, too much. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body) - 1, - 0x6900b, 522, 500), -EINVAL); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), - 0x69000, 0, 500), -EINVAL); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_encode(body, sizeof(body), - 0x69000, DCP_HDCP_REG_MAX + 1, - 500), -EINVAL); -} - -static void wire_read_check(struct kunit *test) -{ - u8 body[DCP_HDCP_REG_ARGS_LEN + 32]; - - dcp_hdcp_reg_read_encode(body, sizeof(body), DP_HDCP_2_2_REG_HPRIME_OFFSET, - 32, 500); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), - DP_HDCP_2_2_REG_HPRIME_OFFSET, - 32), 0); - /* Truncated: the data is not all there. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body) - 1, - DP_HDCP_2_2_REG_HPRIME_OFFSET, - 32), -EPROTO); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, 8, - DP_HDCP_2_2_REG_HPRIME_OFFSET, - 32), -EPROTO); - /* An answer for another register or another length. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), - DP_HDCP_2_2_REG_LPRIME_OFFSET, - 32), -EPROTO); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, sizeof(body), - DP_HDCP_2_2_REG_HPRIME_OFFSET, - 16), -EPROTO); - /* An oversized ask is refused before any compare. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_read_check(body, SIZE_MAX, - DP_HDCP_2_2_REG_HPRIME_OFFSET, - DCP_HDCP_REG_MAX + 1), -EPROTO); -} - -static void wire_write(struct kunit *test) -{ - u8 body[DCP_HDCP_REG_ARGS_LEN + 8]; - u8 rtx[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; - - KUNIT_ASSERT_EQ(test, dcp_hdcp_reg_write_encode(body, sizeof(body), - DP_HDCP_2_2_REG_RTX_OFFSET, - rtx, sizeof(rtx)), - (int)sizeof(body)); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body), 0); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 16), 0x69000); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 32), 8); - /* A write carries the AUX timeout too, at +48. */ - KUNIT_EXPECT_EQ(test, get_unaligned_le32(body + 48), DCP_HDCP_REG_TIMEOUT_MS); - KUNIT_EXPECT_MEMEQ(test, body + DCP_HDCP_REG_ARGS_LEN, rtx, sizeof(rtx)); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, sizeof(body), - 0x69000, 8), 0); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, 63, 0x69000, 8), - -EPROTO); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_check(body, sizeof(body), - 0x69008, 8), -EPROTO); - KUNIT_EXPECT_EQ(test, dcp_hdcp_reg_write_encode(body, sizeof(body) - 1, - 0x69000, rtx, 8), -EINVAL); -} - -static void wire_auth_reply(struct kunit *test) -{ - struct dcp_hdcp_word in = { .value = cpu_to_le32(0xffffffff) }; - struct dcp_hdcp_word out; - u8 small[8]; - - /* The open: the AP's answer says whether it takes the session. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, - sizeof(in), &out, sizeof(out), - true), 0); - KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 1); - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, - sizeof(in), &out, sizeof(out), - false), 0); - KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0); - /* Others come back as they were. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_CONFIG, &in, - sizeof(in), &out, sizeof(out), - false), 0); - KUNIT_EXPECT_EQ(test, le32_to_cpu(out.value), 0xffffffff); - /* A short open answer, another group, an unknown call. */ - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, DCP_HDCP_AUTH_OPEN, &in, - sizeof(in), small, sizeof(small), - true), -EPROTO); - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(1, DCP_HDCP_AUTH_OPEN, &in, - sizeof(in), &out, sizeof(out), - true), -EOPNOTSUPP); - KUNIT_EXPECT_EQ(test, dcp_hdcp_auth_reply(0, 0x55, &in, sizeof(in), - &out, sizeof(out), true), - -EOPNOTSUPP); -} - -static void wire_report(struct kunit *test) -{ - struct dcp_hdcp_report r; - u8 *b = (u8 *)&r; - - dcp_hdcp_report_encode(&r, DCP_HDCP_PROGRESS_LIST_VERIFIED, true, true, - false); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 64), 0x78); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 16), 1); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 48), 1); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 32), 0); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 0), 0); - dcp_hdcp_report_encode(&r, DCP_HDCP_PROGRESS_ENCRYPTED, true, false, true); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 64), 0x74); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 32), 1); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 0), 1); - KUNIT_EXPECT_EQ(test, get_unaligned_le32(b + 48), 0); -} - -static struct kunit_case dcp_hdcp_wire_cases[] = { - KUNIT_CASE(wire_read_encode), - KUNIT_CASE(wire_read_check), - KUNIT_CASE(wire_write), - KUNIT_CASE(wire_auth_reply), - KUNIT_CASE(wire_report), - { } -}; - -static struct kunit_suite dcp_hdcp_wire_suite = { - .name = "apple-dcp-hdcp-wire", - .test_cases = dcp_hdcp_wire_cases, -}; -kunit_test_suite(dcp_hdcp_wire_suite); - -MODULE_DESCRIPTION("KUnit tests for the Apple DCP HDCP service layouts"); -MODULE_LICENSE("Dual MIT/GPL"); diff --git a/drivers/gpu/drm/apple/dcp-hdcp-wire.h b/drivers/gpu/drm/apple/dcp-hdcp-wire.h deleted file mode 100644 index e3642647109243..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp-wire.h +++ /dev/null @@ -1,247 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -/* Copyright 2026 Ryan Murray */ -#ifndef __APPLE_DCP_HDCP_WIRE_H__ -#define __APPLE_DCP_HDCP_WIRE_H__ - -#include -#include -#include -#include -#include -#include - -/* - * The DCP services that carry HDCP 2.2, as standard EPIC service calls - * (struct epic_service_call, then the body described here): - * - * - The sink's DP device service ("dcpdp-device-epic") reads and writes the - * receiver's HDCP 2.2 registers, addressed as in the DisplayPort HDCP 2.2 - * register map (DP_HDCP_2_2_REG_*). DCP runs the AUX transaction. A - * built-in HDMI port behind an on-board DP to HDMI converter is reached - * the same way: the converter is the HDCP repeater. - * - The HDCP interface service ("dcpdptx-hdcp-interface"), one per port, - * takes the transmitter's capability once it is opened. - * - An authentication session service ("dcpdptx-hdcp-auth-session"), - * announced by DCP for each attempt, calls the AP with the session's - * events (open, start, H' ready, pairing ready, ReceiverID list ready, - * close) and takes progress reports. DCP owns the receiver timeouts: an - * attempt that runs out of time is closed by DCP and opened again. - * - * Every body field is a little-endian 32-bit word at a 16-byte stride. - */ - -/* Register access on the DP device service. */ -#define DCP_HDCP_REG_GROUP 1 -#define DCP_HDCP_REG_READ 6 -#define DCP_HDCP_REG_WRITE 7 -/* The register arguments, then the data. */ -#define DCP_HDCP_REG_ARGS_LEN 64 -/* The longest register block: the receiver certificate. */ -#define DCP_HDCP_REG_MAX 1024 -/* The timeout DCP applies to a register read or write on the AUX side. */ -#define DCP_HDCP_REG_TIMEOUT_MS 500 - -/* The device service's query, the first call of a session. */ -#define DCP_HDCP_DEV_GROUP 0 -#define DCP_HDCP_DEV_QUERY 4 -#define DCP_HDCP_DEV_QUERY_LEN 0x20 -/* Its counterpart when the session ends: DCP waits for it before power-down. */ -#define DCP_HDCP_DEV_END 5 -#define DCP_HDCP_DEV_END_LEN 0x10 -/* The device service's information call, once after it is opened. */ -#define DCP_HDCP_DEV_INFO 0xc -#define DCP_HDCP_DEV_INFO_LEN 0x50 - -/* The HDCP interface service's capability call. */ -#define DCP_HDCP_IF_GROUP 4 -#define DCP_HDCP_IF_CAPS 6 -#define DCP_HDCP_IF_CAPS_LEN 0x20 -#define DCP_HDCP_IF_CAPS_VALUE 3 - -/* The authentication session's calls to the AP (group 0). */ -enum dcp_hdcp_auth_op { - DCP_HDCP_AUTH_START = 0x0, - DCP_HDCP_AUTH_CONFIG = 0x1, - DCP_HDCP_AUTH_OPEN = 0x7, - DCP_HDCP_AUTH_CLOSE = 0x8, - DCP_HDCP_AUTH_H_PRIME = 0x9, /* H' is available */ - DCP_HDCP_AUTH_PAIRING = 0xa, /* pairing information is available */ - DCP_HDCP_AUTH_LIST = 0xb, /* the ReceiverID list is available */ -}; - -/* The AP's progress report on the session. */ -#define DCP_HDCP_REPORT_GROUP 2 -#define DCP_HDCP_REPORT_PROGRESS 6 -#define DCP_HDCP_REPORT_LEN 0x50 - -enum dcp_hdcp_progress_code { - DCP_HDCP_PROGRESS_IDLE = 0x65, /* opened, or closed again */ - DCP_HDCP_PROGRESS_STARTED = 0x66, - DCP_HDCP_PROGRESS_AKE = 0x69, /* AKE running */ - DCP_HDCP_PROGRESS_KM_SENT = 0x6c, - DCP_HDCP_PROGRESS_H_VERIFIED = 0x6d, /* pairing still to come */ - DCP_HDCP_PROGRESS_AKE_DONE = 0x70, - DCP_HDCP_PROGRESS_STREAM_READY = 0x72, - DCP_HDCP_PROGRESS_ENCRYPTED = 0x74, - DCP_HDCP_PROGRESS_SKE_SENT = 0x75, - DCP_HDCP_PROGRESS_LIST_VERIFIED = 0x78, -}; - -struct dcp_hdcp_reg_read { - __le32 addr; - __le32 rsvd0[3]; - __le32 len; - __le32 rsvd1[3]; - __le32 timeout_ms; - __le32 rsvd2[7]; -} __packed; -static_assert(sizeof(struct dcp_hdcp_reg_read) == DCP_HDCP_REG_ARGS_LEN); - -struct dcp_hdcp_reg_write { - __le32 rsvd0[4]; - __le32 addr; - __le32 rsvd1[3]; - __le32 len; - __le32 rsvd2[3]; - __le32 timeout_ms; - __le32 rsvd3[3]; -} __packed; -static_assert(sizeof(struct dcp_hdcp_reg_write) == DCP_HDCP_REG_ARGS_LEN); - -/* One word at offset 16: the interface capability, the open's acceptance. */ -struct dcp_hdcp_word { - __le32 rsvd0[4]; - __le32 value; - __le32 rsvd1[3]; -} __packed; -static_assert(sizeof(struct dcp_hdcp_word) == DCP_HDCP_IF_CAPS_LEN); - -struct dcp_hdcp_report { - __le32 authenticated; - __le32 rsvd0[3]; - __le32 active; - __le32 rsvd1[3]; - __le32 encrypted; - __le32 rsvd2[3]; - __le32 repeater; - __le32 rsvd3[3]; - __le32 code; - __le32 rsvd4[3]; -} __packed; -static_assert(sizeof(struct dcp_hdcp_report) == DCP_HDCP_REPORT_LEN); - -static inline bool dcp_hdcp_reg_len_ok(size_t len) -{ - return len && len <= DCP_HDCP_REG_MAX; -} - -/* A read request: the arguments, then @len zero bytes for the data. */ -static inline int dcp_hdcp_reg_read_encode(void *body, size_t room, u32 addr, - size_t len, u32 timeout_ms) -{ - struct dcp_hdcp_reg_read *a = body; - - if (!dcp_hdcp_reg_len_ok(len) || room < DCP_HDCP_REG_ARGS_LEN + len) - return -EINVAL; - memset(body, 0, DCP_HDCP_REG_ARGS_LEN + len); - a->addr = cpu_to_le32(addr); - a->len = cpu_to_le32(len); - a->timeout_ms = cpu_to_le32(timeout_ms); - return DCP_HDCP_REG_ARGS_LEN + len; -} - -/* - * A read answer: it must name the register block asked for and carry all of - * its bytes. On success the data starts at body + DCP_HDCP_REG_ARGS_LEN. - */ -static inline int dcp_hdcp_reg_read_check(const void *body, size_t received, - u32 addr, size_t len) -{ - const struct dcp_hdcp_reg_read *a = body; - - if (!dcp_hdcp_reg_len_ok(len) || received < DCP_HDCP_REG_ARGS_LEN + len) - return -EPROTO; - if (le32_to_cpu(a->addr) != addr || le32_to_cpu(a->len) != len) - return -EPROTO; - return 0; -} - -static inline int dcp_hdcp_reg_write_encode(void *body, size_t room, u32 addr, - const void *data, size_t len) -{ - struct dcp_hdcp_reg_write *a = body; - - if (!dcp_hdcp_reg_len_ok(len) || room < DCP_HDCP_REG_ARGS_LEN + len) - return -EINVAL; - memset(body, 0, DCP_HDCP_REG_ARGS_LEN); - a->addr = cpu_to_le32(addr); - a->len = cpu_to_le32(len); - a->timeout_ms = cpu_to_le32(DCP_HDCP_REG_TIMEOUT_MS); - memcpy(body + DCP_HDCP_REG_ARGS_LEN, data, len); - return DCP_HDCP_REG_ARGS_LEN + len; -} - -static inline int dcp_hdcp_reg_write_check(const void *body, size_t received, - u32 addr, size_t len) -{ - const struct dcp_hdcp_reg_write *a = body; - - if (received < DCP_HDCP_REG_ARGS_LEN) - return -EPROTO; - if (le32_to_cpu(a->addr) != addr || le32_to_cpu(a->len) != len) - return -EPROTO; - return 0; -} - -static inline bool dcp_hdcp_auth_op_known(u32 op) -{ - switch (op) { - case DCP_HDCP_AUTH_START: - case DCP_HDCP_AUTH_CONFIG: - case DCP_HDCP_AUTH_OPEN: - case DCP_HDCP_AUTH_CLOSE: - case DCP_HDCP_AUTH_H_PRIME: - case DCP_HDCP_AUTH_PAIRING: - case DCP_HDCP_AUTH_LIST: - return true; - default: - return false; - } -} - -/* - * The AP's answer to a session call: the call's body back, and for the open - * whether the AP takes the session (1) or not (0). - */ -static inline int dcp_hdcp_auth_reply(u16 group, u32 op, const void *data, - size_t size, void *reply, size_t room, - bool accept) -{ - if (group || !dcp_hdcp_auth_op_known(op)) - return -EOPNOTSUPP; - memset(reply, 0, room); - memcpy(reply, data, min(size, room)); - if (op == DCP_HDCP_AUTH_OPEN) { - struct dcp_hdcp_word *w = reply; - - if (room < sizeof(*w)) - return -EPROTO; - w->value = cpu_to_le32(accept); - } - return 0; -} - -static inline void dcp_hdcp_report_encode(struct dcp_hdcp_report *r, - enum dcp_hdcp_progress_code code, - bool active, bool repeater, - bool encrypted) -{ - memset(r, 0, sizeof(*r)); - r->code = cpu_to_le32(code); - r->active = cpu_to_le32(active); - r->repeater = cpu_to_le32(repeater); - r->encrypted = cpu_to_le32(encrypted); - r->authenticated = cpu_to_le32(encrypted); -} - -#endif /* __APPLE_DCP_HDCP_WIRE_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-hdcp.c b/drivers/gpu/drm/apple/dcp-hdcp.c deleted file mode 100644 index d08fd991706289..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp.c +++ /dev/null @@ -1,1165 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only OR MIT -/* Copyright 2026 Ryan Murray */ - -/* - * HDCP 2.2 on the display processors' external outputs. - * - * DCP opens an authentication session after the link comes up and calls the - * AP with the session's events; the AP answers each at once and runs the - * transmitter (dcp-hdcp-tx.c) on its own ordered queue, with the SEP doing - * the cryptography (include/linux/apple-sep-hdcp.h) and the sink's DP device - * service moving the receiver's messages. The connector's Content - * Protection property follows the policy in dcp-hdcp.h. No key material is - * seen here: only the protocol fields the HDCP 2.2 messages carry in the - * clear. - * - * Only a display processor whose node has "apple,hdcp-channels" takes - * part; elsewhere the property is not attached and nothing changes. While - * userspace does not ask for protection, DCP's sessions are declined. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "afk.h" -#include "connector.h" -#include "dcp.h" -#include "dcp-hdcp.h" -#include "dcp-hdcp-drv.h" -#include "dcp-hdcp-tx.h" -#include "dcp-hdcp-wire.h" -#include "dcp-internal.h" - - -/* - * How long a register access may take: DCP applies its own AUX timeout - * (DCP_HDCP_REG_TIMEOUT_MS, carried in the request); the extra 500 ms covers - * the mailbox round trip, so a slow transaction ends with DCP's answer, not - * ours. Not a spec value. - */ -#define DCP_HDCP_CALL_MS (DCP_HDCP_REG_TIMEOUT_MS + 500) -/* The receiver's status on an encrypted link. */ -#define DCP_HDCP_IFACES 4 -#define DCP_HDCP_QUEUE 16 - -struct dcp_hdcp_event { - u8 op; - struct apple_epic_service *service; -}; - -struct dcp_hdcp { - struct apple_dcp *dcp; - u32 channel; - - /* The policy, the link generation and the session's identity. */ - struct mutex lock; - struct dcp_hdcp_link link; - u32 gen; - u32 session_gen; - - /* Service pointers and session events, also touched from teardown. */ - spinlock_t svc_lock; - struct apple_epic_service *relay; - struct apple_epic_service *iface[DCP_HDCP_IFACES]; - struct apple_epic_service *session; - /* Sessions DCP announced for HDCP 1.x: declined, this is HDCP 2.2 only. */ - struct apple_epic_service *hdcp1[DCP_HDCP_IFACES]; - unsigned long ev_bits; - /* The device service was asked for a session (query) and not yet told it ended. */ - bool dev_begun; - bool closed; - bool cancel; - struct dcp_hdcp_event queue[DCP_HDCP_QUEUE]; - unsigned int q_head, q_tail; - wait_queue_head_t ev_wq; - - struct apple_dcp_afkep *dpdev_ep; - /* The HDCP interface endpoint, when this file started it. */ - struct apple_dcp_afkep *if_ep; - - struct workqueue_struct *wq; - struct work_struct event_work; - struct work_struct teardown_work; - struct work_struct prop_work; - struct work_struct relay_work; - struct work_struct caps_work; - /* Accepted session opens; a teardown older than the latest is stale. */ - unsigned int open_seq; - unsigned int td_seq; - - struct dcp_hdcp_tx tx; -}; - -static struct dcp_hdcp *dcp_hdcp_of(struct apple_epic_service *service) -{ - return service && service->ep ? READ_ONCE(service->ep->dcp->hdcp) : NULL; -} - -/* Pins the service in @slot, NULL if there is none or it is gone. */ -static struct apple_epic_service *dcp_hdcp_pin(struct dcp_hdcp *h, - struct apple_epic_service **slot) -{ - struct apple_epic_service *service; - unsigned long flags; - - spin_lock_irqsave(&h->svc_lock, flags); - service = afk_service_get(*slot); - spin_unlock_irqrestore(&h->svc_lock, flags); - return service; -} - -/* The DP device service: register access. */ - -static int dcp_hdcp_reg_read(void *ctx, u32 addr, void *buf, size_t len) -{ - struct dcp_hdcp *h = ctx; - struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); - size_t received = 0; - void *body; - int n, ret; - - if (!service) - return -ENODEV; - body = kzalloc(DCP_HDCP_REG_ARGS_LEN + len, GFP_KERNEL); - if (!body) { - afk_service_put(service); - return -ENOMEM; - } - n = dcp_hdcp_reg_read_encode(body, DCP_HDCP_REG_ARGS_LEN + len, addr, - len, DCP_HDCP_REG_TIMEOUT_MS); - ret = n < 0 ? n : - afk_service_call_timeout_len(service, DCP_HDCP_REG_GROUP, - DCP_HDCP_REG_READ, body, n, 0, body, n, - 0, DCP_HDCP_CALL_MS, &received); - if (!ret) - ret = dcp_hdcp_reg_read_check(body, received, addr, len); - if (!ret) - memcpy(buf, body + DCP_HDCP_REG_ARGS_LEN, len); - kfree_sensitive(body); - afk_service_put(service); - return ret; -} - -static int dcp_hdcp_reg_write(void *ctx, u32 addr, const void *buf, size_t len) -{ - struct dcp_hdcp *h = ctx; - struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); - size_t received = 0; - void *body; - int n, ret; - - if (!service) - return -ENODEV; - body = kzalloc(DCP_HDCP_REG_ARGS_LEN + len, GFP_KERNEL); - if (!body) { - afk_service_put(service); - return -ENOMEM; - } - n = dcp_hdcp_reg_write_encode(body, DCP_HDCP_REG_ARGS_LEN + len, addr, - buf, len); - ret = n < 0 ? n : - afk_service_call_timeout_len(service, DCP_HDCP_REG_GROUP, - DCP_HDCP_REG_WRITE, body, n, 0, body, n, - 0, DCP_HDCP_CALL_MS, &received); - if (!ret) - ret = dcp_hdcp_reg_write_check(body, received, addr, len); - kfree_sensitive(body); - afk_service_put(service); - return ret; -} - -/* A call with a zero body whose answer is not needed. */ -static int dcp_hdcp_plain_call(struct apple_epic_service *service, u16 group, - u32 command, size_t len, u32 value) -{ - struct dcp_hdcp_word *w; - void *body = kzalloc(len, GFP_KERNEL); - int ret; - - if (!body) - return -ENOMEM; - if (value && len >= sizeof(*w)) { - w = body; - w->value = cpu_to_le32(value); - } - ret = afk_service_call_timeout(service, group, command, body, len, 0, - body, len, 0, DCP_HDCP_CALL_MS); - kfree(body); - return ret; -} - -/* The session service: events in, progress reports out. */ - -static void dcp_hdcp_report(void *ctx, enum dcp_hdcp_progress_code code, - bool active, bool repeater, bool encrypted) -{ - struct dcp_hdcp *h = ctx; - struct apple_epic_service *service = dcp_hdcp_pin(h, &h->session); - struct { - struct epic_service_call call; - struct dcp_hdcp_report report; - } __packed msg = {}; - int ret; - - if (!service) - return; - msg.call.group = cpu_to_le16(DCP_HDCP_REPORT_GROUP); - msg.call.command = cpu_to_le32(DCP_HDCP_REPORT_PROGRESS); - msg.call.data_len = cpu_to_le32(sizeof(msg.report)); - msg.call.magic = cpu_to_le32(EPIC_SERVICE_CALL_MAGIC); - dcp_hdcp_report_encode(&msg.report, code, active, repeater, encrypted); - ret = afk_send_epic(service->ep, service->channel, 0, EPIC_TYPE_NOTIFY, - EPIC_CAT_REPORT, EPIC_SUBTYPE_STD_SERVICE, &msg, - sizeof(msg)); - if (ret) - dev_dbg(h->dcp->dev, "HDCP: progress %#x not reported: %d\n", - code, ret); - afk_service_put(service); -} - -static int dcp_hdcp_wait(void *ctx, enum dcp_hdcp_auth_op op, unsigned int ms) -{ - struct dcp_hdcp *h = ctx; - unsigned long flags; - bool got; - - wait_event_timeout(h->ev_wq, - test_bit(op, &h->ev_bits) || READ_ONCE(h->closed) || - READ_ONCE(h->cancel), msecs_to_jiffies(ms)); - spin_lock_irqsave(&h->svc_lock, flags); - if (h->closed || h->cancel) { - spin_unlock_irqrestore(&h->svc_lock, flags); - return -ECANCELED; - } - got = __test_and_clear_bit(op, &h->ev_bits); - spin_unlock_irqrestore(&h->svc_lock, flags); - return got ? 0 : -ETIMEDOUT; -} - -static int dcp_hdcp_revoked(void *ctx, u8 *ids, unsigned int count) -{ - struct dcp_hdcp *h = ctx; - struct apple_connector *connector = READ_ONCE(h->dcp->connector); - - if (!connector) - return -ENODEV; - return drm_hdcp_check_ksvs_revoked(connector->base.dev, ids, count); -} - -static void dcp_hdcp_sleep(void *ctx, unsigned int ms) -{ - msleep(ms); -} - -/* The SEP service. */ - -static int sep_open(void *ctx, u32 ch, u8 *rtx) -{ - return apple_sep_hdcp_open(ch, rtx); -} - -static int sep_ake_cert(void *ctx, u32 ch, const u8 *cert, const u8 *rrx, - bool *stored, u8 *ekh_km_m, u8 *ekpub_km) -{ - struct apple_sep_hdcp_stored_km km; - int ret; - - static_assert(sizeof(km) == HDCP_2_2_E_KH_KM_M_LEN); - ret = apple_sep_hdcp_ake_cert(ch, cert, rrx, stored, &km, ekpub_km); - if (!ret && *stored) - memcpy(ekh_km_m, &km, sizeof(km)); - memzero_explicit(&km, sizeof(km)); - return ret; -} - -static int sep_h_prime(void *ctx, u32 ch, const u8 *rxcaps, const u8 *txcaps, - const u8 *h_prime) -{ - return apple_sep_hdcp_ake_h_prime(ch, rxcaps, txcaps, h_prime); -} - -static int sep_pairing(void *ctx, u32 ch, const u8 *ekh_km) -{ - return apple_sep_hdcp_ake_pairing(ch, ekh_km); -} - -static int sep_lc_init(void *ctx, u32 ch, u8 *rn) -{ - return apple_sep_hdcp_lc_init(ch, rn); -} - -static int sep_l_prime(void *ctx, u32 ch, const u8 *l_prime) -{ - return apple_sep_hdcp_lc_l_prime(ch, l_prime); -} - -static int sep_ske(void *ctx, u32 ch, u8 *edkey_ks, u8 *riv) -{ - return apple_sep_hdcp_ske(ch, edkey_ks, riv); -} - -static int sep_repeater_list(void *ctx, u32 ch, const u8 *ids, - unsigned int count, const u8 *rxinfo, - const u8 *seq_num_v, const u8 *v_prime, u8 *v) -{ - return apple_sep_hdcp_repeater_list(ch, ids, count, rxinfo, seq_num_v, - v_prime, v); -} - -static int sep_repeater_stream(void *ctx, u32 ch, u8 stream_id, u8 type, - const u8 *seq_num_m, const u8 *m_prime) -{ - return apple_sep_hdcp_repeater_stream(ch, stream_id, type, seq_num_m, - m_prime); -} - -static int sep_finish(void *ctx, u32 ch) -{ - return apple_sep_hdcp_finish(ch); -} - -static int sep_set_encryption(void *ctx, u32 ch, bool on) -{ - return apple_sep_hdcp_set_encryption(ch, on); -} - -static void sep_close(void *ctx, u32 ch) -{ - apple_sep_hdcp_close(ch); -} - -static const struct dcp_hdcp_tx_ops dcp_hdcp_tx_ops = { - .read = dcp_hdcp_reg_read, - .write = dcp_hdcp_reg_write, - .wait = dcp_hdcp_wait, - .report = dcp_hdcp_report, - .revoked = dcp_hdcp_revoked, - .sleep = dcp_hdcp_sleep, - .sep_open = sep_open, - .sep_ake_cert = sep_ake_cert, - .sep_h_prime = sep_h_prime, - .sep_pairing = sep_pairing, - .sep_lc_init = sep_lc_init, - .sep_l_prime = sep_l_prime, - .sep_ske = sep_ske, - .sep_repeater_list = sep_repeater_list, - .sep_repeater_stream = sep_repeater_stream, - .sep_finish = sep_finish, - .sep_set_encryption = sep_set_encryption, - .sep_close = sep_close, -}; - -/* Policy glue. */ - -/* What the connector this processor drives asks for. */ -static void dcp_hdcp_want(struct dcp_hdcp *h, bool *want, u8 *type) -{ - struct apple_connector *connector = READ_ONCE(h->dcp->connector); - - *want = connector && READ_ONCE(connector->hdcp_attached) && - READ_ONCE(connector->hdcp_want); - *type = connector ? READ_ONCE(connector->hdcp_type) : 0; -} - -static void dcp_hdcp_apply(struct dcp_hdcp *h, enum dcp_hdcp_action action) -{ - unsigned long flags; - - if (action == DCP_HDCP_TEARDOWN) { - spin_lock_irqsave(&h->svc_lock, flags); - h->cancel = true; - h->td_seq = h->open_seq; - spin_unlock_irqrestore(&h->svc_lock, flags); - wake_up_all(&h->ev_wq); - queue_work(h->wq, &h->teardown_work); - } - queue_work(h->wq, &h->prop_work); -} - -/* The bound state of both sides, then what the connector asks for. */ -static void dcp_hdcp_sync_locked(struct dcp_hdcp *h) -{ - unsigned long now = jiffies; - enum dcp_hdcp_action a, b; - bool want, relay; - u8 type; - - relay = READ_ONCE(h->relay) != NULL; - a = dcp_hdcp_bind(&h->link, relay, apple_sep_hdcp_available(), now); - dcp_hdcp_want(h, &want, &type); - b = dcp_hdcp_request(&h->link, want, type, now); - dcp_hdcp_apply(h, a == DCP_HDCP_TEARDOWN ? a : b); -} - -static void dcp_hdcp_sync(struct dcp_hdcp *h) -{ - mutex_lock(&h->lock); - dcp_hdcp_sync_locked(h); - mutex_unlock(&h->lock); -} - -static void dcp_hdcp_prop_work(struct work_struct *work) -{ - struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, prop_work); - struct apple_connector *connector = READ_ONCE(h->dcp->connector); - struct drm_device *drm; - u64 value; - - if (!connector || !READ_ONCE(connector->hdcp_attached)) - return; - mutex_lock(&h->lock); - value = dcp_hdcp_property(&h->link); - mutex_unlock(&h->lock); - /* UNDESIRED is userspace's to set, never the driver's. */ - if (value == DRM_MODE_CONTENT_PROTECTION_UNDESIRED || - !READ_ONCE(connector->hdcp_want)) - return; - drm = connector->base.dev; - drm_modeset_lock(&drm->mode_config.connection_mutex, NULL); - if (READ_ONCE(connector->hdcp_want)) - drm_hdcp_update_content_protection(&connector->base, value); - drm_modeset_unlock(&drm->mode_config.connection_mutex); -} - -/* - * The transmitter's capability, once per HDCP interface after it opens (as - * macOS does at boot): DCP then offers sessions at each link-up. - */ -static void dcp_hdcp_caps_work(struct work_struct *work) -{ - struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, caps_work); - struct apple_epic_service *service; - int i; - - for (i = 0; i < DCP_HDCP_IFACES; i++) { - service = dcp_hdcp_pin(h, &h->iface[i]); - if (!service) - continue; - dcp_hdcp_plain_call(service, DCP_HDCP_IF_GROUP, DCP_HDCP_IF_CAPS, - DCP_HDCP_IF_CAPS_LEN, DCP_HDCP_IF_CAPS_VALUE); - afk_service_put(service); - } -} - -/* Tells the DP device service the session it was asked for has ended. */ -static void dcp_hdcp_dev_end(struct dcp_hdcp *h) -{ - struct apple_epic_service *relay; - - if (!xchg(&h->dev_begun, false)) - return; - relay = dcp_hdcp_pin(h, &h->relay); - if (!relay) - return; - dcp_hdcp_plain_call(relay, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_END, - DCP_HDCP_DEV_END_LEN, 0); - afk_service_put(relay); -} - -/* Encryption off, the SEP session closed, DCP told; the picture stays. */ -static void dcp_hdcp_teardown_work(struct work_struct *work) -{ - struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, teardown_work); - unsigned long flags; - bool was_open, stale; - - /* - * A session DCP opened after this teardown was asked for has already - * replaced what it would end (dcp_hdcp_run() aborts a leftover first). - */ - spin_lock_irqsave(&h->svc_lock, flags); - stale = h->open_seq != h->td_seq; - spin_unlock_irqrestore(&h->svc_lock, flags); - if (stale) - return; - was_open = h->tx.sep_open; - dcp_hdcp_abort(&h->tx); - if (was_open) - dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); - dcp_hdcp_dev_end(h); -} - -/* One authentication, from DCP's start of the session to its result. */ -static void dcp_hdcp_run(struct dcp_hdcp *h) -{ - struct apple_epic_service *relay = dcp_hdcp_pin(h, &h->relay); - enum dcp_hdcp_action action; - u32 gen; - int ret; - - mutex_lock(&h->lock); - gen = h->session_gen; - h->tx.type = h->link.type; - /* Only a session the policy took, on its generation. */ - if (h->link.state != DCP_HDCP_AUTH || h->link.generation != gen) { - mutex_unlock(&h->lock); - afk_service_put(relay); - return; - } - mutex_unlock(&h->lock); - /* What an earlier session left open (its teardown has not run yet). */ - if (h->tx.sep_open) - dcp_hdcp_abort(&h->tx); - h->tx.ops = &dcp_hdcp_tx_ops; - h->tx.ctx = h; - h->tx.channel = h->channel; - - if (relay) { - /* The device service's query opens each session; dcp_hdcp_dev_end() closes it. */ - dcp_hdcp_dev_end(h); - if (!dcp_hdcp_plain_call(relay, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_QUERY, - DCP_HDCP_DEV_QUERY_LEN, 0)) - WRITE_ONCE(h->dev_begun, true); - afk_service_put(relay); - ret = dcp_hdcp_authenticate(&h->tx); - } else { - ret = -ENODEV; - } - if (ret) { - dev_info(h->dcp->dev, "HDCP: authentication failed at %s: %d\n", - h->tx.step ?: "start", ret); - dcp_hdcp_abort(&h->tx); - } else { - dev_info(h->dcp->dev, "HDCP: encrypted, type %u%s\n", h->tx.type, - h->tx.repeater ? " (repeater)" : ""); - } - mutex_lock(&h->lock); - action = dcp_hdcp_auth_done(&h->link, gen, ret, jiffies); - mutex_unlock(&h->lock); - /* The SEP session is already closed after a failure. */ - if (action != DCP_HDCP_TEARDOWN) - dcp_hdcp_apply(h, action); - else - queue_work(h->wq, &h->prop_work); -} - -static void dcp_hdcp_close(struct dcp_hdcp *h, struct apple_epic_service *service) -{ - enum dcp_hdcp_action action; - unsigned long flags; - bool ours; - - /* A close of an earlier session, after DCP opened a newer one: nothing to end. */ - spin_lock_irqsave(&h->svc_lock, flags); - ours = !h->session || h->session == service; - spin_unlock_irqrestore(&h->svc_lock, flags); - if (!ours) - return; - dcp_hdcp_abort(&h->tx); - mutex_lock(&h->lock); - action = dcp_hdcp_closed(&h->link, h->session_gen, jiffies); - mutex_unlock(&h->lock); - if (action != DCP_HDCP_TEARDOWN) - dcp_hdcp_apply(h, action); - /* The session goes back to idle on DCP's side. */ - if (service) - dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, false); - dcp_hdcp_dev_end(h); - spin_lock_irqsave(&h->svc_lock, flags); - if (h->session == service) - h->session = NULL; - spin_unlock_irqrestore(&h->svc_lock, flags); - queue_work(h->wq, &h->prop_work); -} - -static void dcp_hdcp_event_work(struct work_struct *work) -{ - struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, event_work); - struct dcp_hdcp_event ev; - unsigned long flags; - - for (;;) { - spin_lock_irqsave(&h->svc_lock, flags); - if (h->q_head == h->q_tail) { - spin_unlock_irqrestore(&h->svc_lock, flags); - return; - } - ev = h->queue[h->q_tail++ % DCP_HDCP_QUEUE]; - spin_unlock_irqrestore(&h->svc_lock, flags); - - switch (ev.op) { - case DCP_HDCP_AUTH_OPEN: - dcp_hdcp_report(h, DCP_HDCP_PROGRESS_IDLE, false, false, - false); - break; - case DCP_HDCP_AUTH_START: - dcp_hdcp_report(h, DCP_HDCP_PROGRESS_STARTED, false, - false, false); - break; - case DCP_HDCP_AUTH_CONFIG: - dcp_hdcp_run(h); - break; - case DCP_HDCP_AUTH_CLOSE: - dcp_hdcp_close(h, ev.service); - break; - } - afk_service_put(ev.service); - } -} - -static void dcp_hdcp_queue(struct dcp_hdcp *h, struct apple_epic_service *service, - u8 op) -{ - struct apple_epic_service *pinned = afk_service_get(service); - unsigned long flags; - bool full; - - if (!pinned) - return; - spin_lock_irqsave(&h->svc_lock, flags); - full = h->q_head - h->q_tail >= DCP_HDCP_QUEUE; - if (!full) - h->queue[h->q_head++ % DCP_HDCP_QUEUE] = - (struct dcp_hdcp_event){ op, pinned }; - spin_unlock_irqrestore(&h->svc_lock, flags); - if (full) { - dev_warn_ratelimited(h->dcp->dev, "HDCP: session event %#x dropped\n", op); - afk_service_put(pinned); - return; - } - queue_work(h->wq, &h->event_work); -} - -/* Whether DCP announced @service as an HDCP 1.x session. */ -static bool dcp_hdcp_is_hdcp1(struct dcp_hdcp *h, struct apple_epic_service *service) -{ - unsigned long flags; - bool ret = false; - int i; - - spin_lock_irqsave(&h->svc_lock, flags); - for (i = 0; i < DCP_HDCP_IFACES; i++) - ret |= h->hdcp1[i] == service; - spin_unlock_irqrestore(&h->svc_lock, flags); - return ret; -} - -/* - * DCP announces one session per protocol version; the provider class says - * which, where the announcement carries one. A session without a class is - * taken for HDCP 2.2: the receiver registers it reads decide. - */ -static void dcp_hdcp_session_init(struct apple_epic_service *service, - const char *name, const char *class, s64 unit) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - int i; - - if (!h || !class || !strstr(class, "HDCP1")) - return; - spin_lock_irqsave(&h->svc_lock, flags); - for (i = 0; i < DCP_HDCP_IFACES; i++) { - if (h->hdcp1[i] == service) - break; - if (!h->hdcp1[i]) { - h->hdcp1[i] = service; - break; - } - } - spin_unlock_irqrestore(&h->svc_lock, flags); - dev_dbg(h->dcp->dev, "HDCP: HDCP 1.x session announced, declined\n"); -} - -static int dcp_hdcp_session_call(struct apple_epic_service *service, u16 group, - u32 command, const void *data, size_t size, - void *reply, size_t room) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - bool accept = false, ours; - int ret; - - if (h && !group && command == DCP_HDCP_AUTH_OPEN) { - mutex_lock(&h->lock); - dcp_hdcp_sync_locked(h); - accept = !dcp_hdcp_is_hdcp1(h, service) && - dcp_hdcp_open(&h->link, h->gen, jiffies); - if (accept) - h->session_gen = h->gen; - mutex_unlock(&h->lock); - spin_lock_irqsave(&h->svc_lock, flags); - if (accept) { - h->session = service; - h->ev_bits = 0; - h->closed = false; - h->cancel = false; - h->open_seq++; - } else if (h->session == service) { - /* The slot of an earlier session, declined this time. */ - h->session = NULL; - } - spin_unlock_irqrestore(&h->svc_lock, flags); - } - ret = dcp_hdcp_auth_reply(group, command, data, size, reply, room, - accept); - if (ret == -EOPNOTSUPP && h && !group) { - /* Not a session step: answered and logged. */ - memset(reply, 0, room); - memcpy(reply, data, min(size, room)); - dev_dbg(h->dcp->dev, "HDCP: session call %#x\n", command); - return 0; - } - if (ret || !h) - return ret; - - spin_lock_irqsave(&h->svc_lock, flags); - ours = h->session == service; - switch (command) { - case DCP_HDCP_AUTH_H_PRIME: - case DCP_HDCP_AUTH_PAIRING: - case DCP_HDCP_AUTH_LIST: - if (ours) - __set_bit(command, &h->ev_bits); - break; - case DCP_HDCP_AUTH_CLOSE: - if (ours) - h->closed = true; - break; - } - spin_unlock_irqrestore(&h->svc_lock, flags); - wake_up_all(&h->ev_wq); - - if (ours && (command == DCP_HDCP_AUTH_OPEN || command == DCP_HDCP_AUTH_START || - command == DCP_HDCP_AUTH_CONFIG || command == DCP_HDCP_AUTH_CLOSE)) - dcp_hdcp_queue(h, service, command); - return 0; -} - -static void dcp_hdcp_session_teardown(struct apple_epic_service *service) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - bool ours; - int i; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - for (i = 0; i < DCP_HDCP_IFACES; i++) - if (h->hdcp1[i] == service) - h->hdcp1[i] = NULL; - ours = h->session == service; - if (ours) { - h->closed = true; - h->session = NULL; - } - spin_unlock_irqrestore(&h->svc_lock, flags); - if (ours) { - wake_up_all(&h->ev_wq); - dcp_hdcp_apply(h, DCP_HDCP_TEARDOWN); - } -} - -static void dcp_hdcp_relay_work(struct work_struct *work) -{ - struct dcp_hdcp *h = container_of(work, struct dcp_hdcp, relay_work); - struct apple_epic_service *service = dcp_hdcp_pin(h, &h->relay); - - if (!service) - return; - /* The device service's information call, once after it is opened. */ - dcp_hdcp_plain_call(service, DCP_HDCP_DEV_GROUP, DCP_HDCP_DEV_INFO, - DCP_HDCP_DEV_INFO_LEN, 0); - afk_service_put(service); - dcp_hdcp_sync(h); -} - -static void dcp_hdcp_relay_init(struct apple_epic_service *service, - const char *name, const char *class, s64 unit) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - h->relay = service; - spin_unlock_irqrestore(&h->svc_lock, flags); - dev_dbg(h->dcp->dev, "HDCP: DP device service on interface %u\n", - service->channel); - queue_work(h->wq, &h->relay_work); -} - -static void dcp_hdcp_relay_teardown(struct apple_epic_service *service) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - bool ours; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - ours = h->relay == service; - if (ours) - h->relay = NULL; - spin_unlock_irqrestore(&h->svc_lock, flags); - if (ours) - dcp_hdcp_apply(h, DCP_HDCP_TEARDOWN); -} - -static void dcp_hdcp_iface_init(struct apple_epic_service *service, - const char *name, const char *class, s64 unit) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - int i; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - for (i = 0; i < DCP_HDCP_IFACES; i++) { - if (h->iface[i] == service) - break; - if (!h->iface[i]) { - h->iface[i] = service; - break; - } - } - spin_unlock_irqrestore(&h->svc_lock, flags); - queue_work(h->wq, &h->caps_work); -} - -static void dcp_hdcp_iface_teardown(struct apple_epic_service *service) -{ - struct dcp_hdcp *h = dcp_hdcp_of(service); - unsigned long flags; - int i; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - for (i = 0; i < DCP_HDCP_IFACES; i++) - if (h->iface[i] == service) - h->iface[i] = NULL; - spin_unlock_irqrestore(&h->svc_lock, flags); -} - -static void dcp_hdcp_other_init(struct apple_epic_service *service, - const char *name, const char *class, s64 unit) -{ -} - -#define DCP_HDCP_RELAY_OPS { \ - .name = "dcpdp-device-epic", \ - .compact_full = "dcpdp-device-epic:0", \ - .singleton = true, \ - .init = dcp_hdcp_relay_init, \ - .teardown = dcp_hdcp_relay_teardown, \ -} - -static const struct apple_epic_service_ops dcp_hdcp_service_ops[] = { - DCP_HDCP_RELAY_OPS, - { - .name = "dcpdptx-hdcp-interface", - .init = dcp_hdcp_iface_init, - .teardown = dcp_hdcp_iface_teardown, - }, - { - .name = "dcpdptx-hdcp-auth-session", - .compact_full = "dcpdptx-hdcp-auth-session", - /* - * Not a singleton: DCP announces one session per protocol - * version and closes each before it powers down, so every - * one needs its handler to answer. - */ - .init = dcp_hdcp_session_init, - .call_v2 = dcp_hdcp_session_call, - .teardown = dcp_hdcp_session_teardown, - }, - {}, -}; - -/* The DP device endpoint when this file starts it: the sink's services. */ -static const struct apple_epic_service_ops dcp_hdcp_dpdev_ops[] = { - DCP_HDCP_RELAY_OPS, - { .name = "*", .init = dcp_hdcp_other_init }, - {}, -}; - -const struct apple_epic_service_ops * -dcp_hdcp_match_service(struct apple_dcp_afkep *ep, const char *service_name, - bool cut) -{ - const struct apple_epic_service_ops *ops; - size_t len; - - if (!ep || !READ_ONCE(ep->dcp->hdcp) || !service_name) - return NULL; - for (ops = dcp_hdcp_service_ops; ops->name[0]; ops++) { - len = strlen(ops->name); - if (!strncmp(ops->name, service_name, len) && - (!service_name[len] || service_name[len] == ':')) - return ops; - if (cut && afk_compact_cut_of(ops, service_name)) - return ops; - } - return NULL; -} - -/* - * The endpoints that carry the HDCP interface services, by firmware: the - * first one advertised and not driven by anything else is started here. - */ -static const u8 dcp_hdcp_if_endpoints[] = { AV_AUDIO_ENDPOINT_DESKTOP, DPTX_HDCP_ENDPOINT }; - -static struct apple_dcp_afkep *dcp_hdcp_start_one(struct apple_dcp *dcp, u8 endpoint, - const struct apple_epic_service_ops *ops, - struct apple_dcp_afkep **slot, const char *what) -{ - struct apple_dcp_afkep *ep; - int ret; - - if (!apple_rtkit_has_endpoint(dcp->rtk, endpoint) || dcp_endpoint_routed(dcp, endpoint)) - return NULL; - ep = afk_init(dcp, endpoint, ops); - if (IS_ERR(ep)) { - dev_warn(dcp->dev, "HDCP: %s endpoint %#x not set up: %ld\n", what, - endpoint, PTR_ERR(ep)); - return NULL; - } - ep->debugfs_entry = dcp->ep_debugfs[endpoint - 0x20]; - /* Routed before the start: afk_start() waits for the firmware's answer. */ - WRITE_ONCE(*slot, ep); - ret = afk_start(ep); - if (ret) - dev_warn(dcp->dev, "HDCP: %s endpoint %#x not started: %d\n", what, - endpoint, ret); - else - dev_info(dcp->dev, "HDCP: started the %s endpoint %#x\n", what, endpoint); - return ep; -} - -void dcp_hdcp_start_endpoints(struct apple_dcp *dcp) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - int i; - - if (!h || IS_ERR_OR_NULL(dcp->rtk)) - return; - if (!h->dpdev_ep) - dcp_hdcp_start_one(dcp, DPDEV_ENDPOINT, dcp_hdcp_dpdev_ops, - &h->dpdev_ep, "DP device"); - for (i = 0; i < ARRAY_SIZE(dcp_hdcp_if_endpoints) && !h->if_ep; i++) - dcp_hdcp_start_one(dcp, dcp_hdcp_if_endpoints[i], dcp_hdcp_service_ops, - &h->if_ep, "HDCP interface"); -} - -struct apple_dcp_afkep *dcp_hdcp_route(struct apple_dcp *dcp, u32 endpoint) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - struct apple_dcp_afkep *ep; - - if (!h) - return NULL; - ep = READ_ONCE(h->dpdev_ep); - if (ep && ep->endpoint == endpoint) - return ep; - ep = READ_ONCE(h->if_ep); - return ep && ep->endpoint == endpoint ? ep : NULL; -} - -void dcp_hdcp_link_changed(struct apple_dcp *dcp) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - enum dcp_hdcp_action action; - - if (!h) - return; - mutex_lock(&h->lock); - h->gen++; - action = dcp_hdcp_link_event(&h->link, h->gen, jiffies); - mutex_unlock(&h->lock); - if (action == DCP_HDCP_TEARDOWN) - dcp_hdcp_apply(h, action); - dcp_hdcp_sync(h); -} - -static bool dcp_hdcp_channel(struct apple_dcp *dcp, u32 *channel) -{ - return !of_property_read_u32_index(dcp->dev->of_node, - "apple,hdcp-channels", 0, channel); -} - -static void dcp_hdcp_destroy_wq(void *data) -{ - destroy_workqueue(data); -} - -struct dcp_hdcp *dcp_hdcp_init(struct apple_dcp *dcp) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - u32 channel; - - if (h || dcp_has_panel(dcp) || !dcp_hdcp_channel(dcp, &channel)) - return h; - h = devm_kzalloc(dcp->dev, sizeof(*h), GFP_KERNEL); - if (!h) - return NULL; - h->dcp = dcp; - h->channel = channel; - mutex_init(&h->lock); - spin_lock_init(&h->svc_lock); - init_waitqueue_head(&h->ev_wq); - INIT_WORK(&h->event_work, dcp_hdcp_event_work); - INIT_WORK(&h->teardown_work, dcp_hdcp_teardown_work); - INIT_WORK(&h->prop_work, dcp_hdcp_prop_work); - INIT_WORK(&h->relay_work, dcp_hdcp_relay_work); - INIT_WORK(&h->caps_work, dcp_hdcp_caps_work); - /* Not freezable: a suspend's teardown must reach DCP before it sleeps. */ - h->wq = alloc_ordered_workqueue("apple-dcp-hdcp", 0); - if (!h->wq) - return NULL; - if (devm_add_action_or_reset(dcp->dev, dcp_hdcp_destroy_wq, h->wq)) - return NULL; - h->tx.ops = &dcp_hdcp_tx_ops; - h->tx.ctx = h; - h->tx.channel = channel; - WRITE_ONCE(dcp->hdcp, h); - dev_info(dcp->dev, "HDCP: transmitter on SEP channel %u\n", channel); - return h; -} - -/* - * Component unbind: the state is device-managed and goes with the bind, so - * nothing may reach it afterwards. Stop all work, end what is open, shut the - * endpoints this file started, and unpublish it. - */ -void dcp_hdcp_fini(struct apple_dcp *dcp) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - struct apple_dcp_afkep *ep; - unsigned long flags; - - if (!h) - return; - spin_lock_irqsave(&h->svc_lock, flags); - h->cancel = true; - spin_unlock_irqrestore(&h->svc_lock, flags); - wake_up_all(&h->ev_wq); - disable_work_sync(&h->event_work); - disable_work_sync(&h->teardown_work); - disable_work_sync(&h->prop_work); - disable_work_sync(&h->relay_work); - disable_work_sync(&h->caps_work); - dcp_hdcp_abort(&h->tx); - dcp_hdcp_dev_end(h); - ep = xchg(&h->if_ep, NULL); - if (ep) - afk_shutdown(ep); - ep = xchg(&h->dpdev_ep, NULL); - if (ep) - afk_shutdown(ep); - WRITE_ONCE(dcp->hdcp, NULL); -} - -/* - * Before DCP sleeps or powers a pipe down: the link change, then its - * teardown done here, so encryption is off and DCP has the device service's - * end call before it waits for it. - */ -void dcp_hdcp_quiesce(struct apple_dcp *dcp) -{ - struct dcp_hdcp *h = READ_ONCE(dcp->hdcp); - - dcp_hdcp_link_changed(dcp); - if (h) - flush_work(&h->teardown_work); -} - -/* DRM. */ - -int dcp_hdcp_attach_connector(struct apple_connector *connector, - struct platform_device **dcps, unsigned int n, - int connector_type) -{ - bool channel = false; - unsigned int i; - int ret; - - if (connector->hdcp_attached || - connector_type == DRM_MODE_CONNECTOR_eDP) - return 0; - for (i = 0; i < n; i++) { - struct apple_dcp *dcp = dcps[i] ? platform_get_drvdata(dcps[i]) : NULL; - - if (dcp && dcp_hdcp_init(dcp)) - channel = true; - } - if (!dcp_hdcp_attach_property(true, channel, - IS_ENABLED(CONFIG_APPLE_SEP_HDCP_INTERFACE))) - return 0; - ret = drm_connector_attach_content_protection_property(&connector->base, - true); - if (ret) - return ret; - connector->hdcp_attached = true; - return 0; -} - -void dcp_hdcp_atomic_check(struct drm_connector *conn, - struct drm_atomic_commit *state) -{ - struct drm_connector_state *old = drm_atomic_get_old_connector_state(state, conn); - struct drm_connector_state *new = drm_atomic_get_new_connector_state(state, conn); - struct drm_crtc_state *crtc_state; - - if (!to_apple_connector(conn)->hdcp_attached || !old || !new) - return; - /* A connector switched off keeps asking: DESIRED again when it is back. */ - if (!new->crtc) { - if (old->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) - new->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED; - return; - } - crtc_state = drm_atomic_get_new_crtc_state(state, new->crtc); - if (old->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED || - new->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED) - return; - /* A mode set or another type: protected again only after a new session. */ - if ((crtc_state && drm_atomic_crtc_needs_modeset(crtc_state)) || - old->hdcp_content_type != new->hdcp_content_type) - new->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED; -} - -void dcp_hdcp_commit(struct drm_atomic_commit *state) -{ - struct drm_connector_state *new; - struct drm_connector *conn; - int i; - - for_each_new_connector_in_state(state, conn, new, i) { - struct apple_connector *connector = to_apple_connector(conn); - struct platform_device *pdev = READ_ONCE(connector->dcp); - struct apple_dcp *dcp; - - if (!connector->hdcp_attached) - continue; - WRITE_ONCE(connector->hdcp_type, new->hdcp_content_type); - WRITE_ONCE(connector->hdcp_want, new->content_protection != - DRM_MODE_CONTENT_PROTECTION_UNDESIRED); - dcp = pdev ? platform_get_drvdata(pdev) : NULL; - if (dcp && READ_ONCE(dcp->hdcp)) - dcp_hdcp_sync(dcp->hdcp); - } -} - -#if IS_ENABLED(CONFIG_DRM_APPLE_KUNIT_TEST) -#include "dcp-hdcp-glue-test.c" -#endif diff --git a/drivers/gpu/drm/apple/dcp-hdcp.h b/drivers/gpu/drm/apple/dcp-hdcp.h deleted file mode 100644 index 0c4f09a0e57fa0..00000000000000 --- a/drivers/gpu/drm/apple/dcp-hdcp.h +++ /dev/null @@ -1,230 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ -/* Copyright 2026 Ryan Murray */ -#ifndef __APPLE_DCP_HDCP_H__ -#define __APPLE_DCP_HDCP_H__ - -#include -#include -#include -#include -#include -#include -#include - -/* - * HDCP 2.2 on an external connector, as the AP runs it: the AP is the - * transmitter, the SEP holds its secrets and does the cryptography, and DCP - * carries the receiver's messages over the link (see dcp-hdcp-wire.h). The - * built-in panel never gets a receiver session, so this never applies to it. - * - * This file is the Content Protection policy, with no hardware behind it: - * - * - DCP opens an authentication session after the link comes up. The AP - * takes it only while protection is DESIRED, the SEP service and the DCP - * relay are bound and no backoff is pending; otherwise it declines. - * - ENABLED needs a complete authentication, the 200 ms wait and an - * acknowledged encryption enable, all in one session on one link - * generation. - * - A failure, a session DCP closes before the end, a new link generation, - * or the SEP service or relay going away drops the session to DESIRED and - * asks for teardown: encryption off and the SEP session closed. A late - * result from a session or generation that is gone is ignored. The display - * itself is never touched: a failed session leaves an unprotected, working - * output. - * - A changed content type re-authenticates; UNDESIRED tears down. - * - Retries back off: DCP_HDCP_RETRY_MS doubled per failure, capped at - * DCP_HDCP_RETRY_MAX_MS, reset by a success or a new link generation. - */ -#define DCP_HDCP_RETRY_MS 1000 -#define DCP_HDCP_RETRY_MAX_MS 60000 - -/* - * Message sizes, msg_id byte included, as the public structures define - * them. The register blocks DCP moves are these without the msg_id byte. - */ -static_assert(sizeof(struct hdcp2_ake_init) == 12); -static_assert(sizeof(struct hdcp2_ake_send_cert) == 534); -static_assert(sizeof(struct hdcp2_ake_stored_km) == 33); -static_assert(sizeof(struct hdcp2_ake_send_hprime) == 33); -static_assert(sizeof(struct hdcp2_lc_init) == 9); -static_assert(sizeof(struct hdcp2_lc_send_lprime) == 33); -static_assert(sizeof(struct hdcp2_ske_send_eks) == 25); - -enum dcp_hdcp_state { - DCP_HDCP_OFF, /* userspace does not want protection */ - DCP_HDCP_DESIRED, /* wanted; no session running */ - DCP_HDCP_AUTH, /* a session is running */ - DCP_HDCP_ENABLED, /* encryption on, acknowledged */ -}; - -enum dcp_hdcp_action { - DCP_HDCP_NONE, - DCP_HDCP_TEARDOWN, /* encryption off and close, display untouched */ - DCP_HDCP_KICK, /* ready: the next session DCP offers is taken */ -}; - -struct dcp_hdcp_link { - enum dcp_hdcp_state state; - u8 type; /* the content type asked for: 0 or 1 */ - u32 generation; /* link generation of the running session */ - unsigned long retry_at; - unsigned int failures; - bool hold; /* the SEP was busy: wait until retry_at */ - bool relay; /* the DCP relay is bound */ - bool sep; /* the SEP service is up */ -}; - -/* - * The property exists on an external connector whose display processor has - * an HDCP channel, with the SEP service built in. Whether a session can run - * is decided at runtime: until then the property stays DESIRED. - */ -static inline bool dcp_hdcp_attach_property(bool external, bool channel, bool sep) -{ - return external && channel && sep; -} - -static inline u64 dcp_hdcp_property(const struct dcp_hdcp_link *l) -{ - switch (l->state) { - case DCP_HDCP_OFF: - return DRM_MODE_CONTENT_PROTECTION_UNDESIRED; - case DCP_HDCP_ENABLED: - return DRM_MODE_CONTENT_PROTECTION_ENABLED; - default: - return DRM_MODE_CONTENT_PROTECTION_DESIRED; - } -} - -static inline unsigned long dcp_hdcp_backoff(unsigned int failures) -{ - unsigned long ms = DCP_HDCP_RETRY_MS; - - while (failures-- > 1 && ms < DCP_HDCP_RETRY_MAX_MS) - ms *= 2; - return msecs_to_jiffies(min_t(unsigned long, ms, DCP_HDCP_RETRY_MAX_MS)); -} - -/* A session may start now. */ -static inline bool dcp_hdcp_ready(const struct dcp_hdcp_link *l, - unsigned long now) -{ - return l->state == DCP_HDCP_DESIRED && l->relay && l->sep && - !((l->failures || l->hold) && time_before(now, l->retry_at)); -} - -/* Drops a session; teardown is owed if one was running. */ -static inline enum dcp_hdcp_action dcp_hdcp_drop(struct dcp_hdcp_link *l, - bool failed, unsigned long now) -{ - bool running = l->state == DCP_HDCP_AUTH || l->state == DCP_HDCP_ENABLED; - - if (l->state != DCP_HDCP_OFF) - l->state = DCP_HDCP_DESIRED; - if (failed) { - l->failures++; - l->retry_at = now + dcp_hdcp_backoff(l->failures); - } - return running ? DCP_HDCP_TEARDOWN : DCP_HDCP_NONE; -} - -/* - * Userspace set the property: @want is DESIRED (true) or UNDESIRED, @type - * the content type. - */ -static inline enum dcp_hdcp_action dcp_hdcp_request(struct dcp_hdcp_link *l, - bool want, u8 type, - unsigned long now) -{ - if (!want) { - enum dcp_hdcp_action a = dcp_hdcp_drop(l, false, now); - - l->state = DCP_HDCP_OFF; - return a; - } - if (l->state == DCP_HDCP_OFF) - l->state = DCP_HDCP_DESIRED; - if (type != l->type) { - l->type = type; - /* A running session protects the old type: start again. */ - if (dcp_hdcp_drop(l, false, now) == DCP_HDCP_TEARDOWN) - return DCP_HDCP_TEARDOWN; - } - return dcp_hdcp_ready(l, now) ? DCP_HDCP_KICK : DCP_HDCP_NONE; -} - -/* DCP opened a session on link generation @gen: true if the AP takes it. */ -static inline bool dcp_hdcp_open(struct dcp_hdcp_link *l, u32 gen, - unsigned long now) -{ - if (!dcp_hdcp_ready(l, now)) - return false; - l->state = DCP_HDCP_AUTH; - l->generation = gen; - return true; -} - -/* - * The session on generation @gen ended its authentication with @result: 0, - * -EAGAIN when the SEP was not available for now (retried after the first - * backoff step, not counted as a failure), or another error. - */ -static inline enum dcp_hdcp_action dcp_hdcp_auth_done(struct dcp_hdcp_link *l, - u32 gen, int result, - unsigned long now) -{ - /* A late result, from a session or generation that is gone. */ - if (l->state != DCP_HDCP_AUTH || gen != l->generation) - return DCP_HDCP_NONE; - if (result == -EAGAIN) { - l->hold = true; - l->retry_at = now + dcp_hdcp_backoff(1); - return dcp_hdcp_drop(l, false, now); - } - if (result) - return dcp_hdcp_drop(l, true, now); - l->state = DCP_HDCP_ENABLED; - l->failures = 0; - l->hold = false; - return DCP_HDCP_NONE; -} - -/* - * DCP closed the session, or the receiver asked for re-authentication: a - * session that had not finished failed; an enabled one is redone at once. - */ -static inline enum dcp_hdcp_action dcp_hdcp_closed(struct dcp_hdcp_link *l, - u32 gen, unsigned long now) -{ - if (gen != l->generation) - return DCP_HDCP_NONE; - if (l->state == DCP_HDCP_AUTH) - return dcp_hdcp_drop(l, true, now); - return dcp_hdcp_drop(l, false, now); -} - -/* The link retrained, went away or came back: it is now generation @gen. */ -static inline enum dcp_hdcp_action dcp_hdcp_link_event(struct dcp_hdcp_link *l, - u32 gen, unsigned long now) -{ - if (gen == l->generation) - return DCP_HDCP_NONE; - l->failures = 0; - l->hold = false; - l->generation = gen; - return dcp_hdcp_drop(l, false, now); -} - -/* The SEP service or the DCP relay came or went. */ -static inline enum dcp_hdcp_action dcp_hdcp_bind(struct dcp_hdcp_link *l, - bool relay, bool sep, - unsigned long now) -{ - l->relay = relay; - l->sep = sep; - if (relay && sep) - return dcp_hdcp_ready(l, now) ? DCP_HDCP_KICK : DCP_HDCP_NONE; - return dcp_hdcp_drop(l, false, now); -} - -#endif /* __APPLE_DCP_HDCP_H__ */ diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index 58ac380438e3cb..f768e7b7ec8fe1 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1327,8 +1327,6 @@ struct apple_dcp { /* Internal panel identity; NULL without an internal panel. */ struct dcp_panel_identity *panel_identity; struct dcp_cec *cec; - /* HDCP 2.2 transmitter state, NULL without HDCP (dcp-hdcp.c). */ - struct dcp_hdcp *hdcp; }; /* A DCP driven through the firmware's iBoot interface alone. */ diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index c88f4b4c04e6b7..9c794ebdb06e7f 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -73,7 +73,6 @@ #include #include "dcp-fabric-effects.h" #include "dcp-fabric.h" -#include "dcp-hdcp-drv.h" #include "dcp-hdmi.h" #include "dcp-syslog.h" #include "dcpext_scanout.h" @@ -1799,9 +1798,6 @@ static struct apple_dcp_afkep *dcp_afkep(struct apple_dcp *dcp, u8 endpoint) if (ep) return ep; } - /* The DP device endpoint HDCP started. */ - if (dcp_hdcp_route(dcp, endpoint)) - return dcp_hdcp_route(dcp, endpoint); /* DPAV 0x2a on H17P overlaps the legacy DPTX endpoint number. */ if (dcp->dcpavservep && endpoint == dcp->dcpavservep->endpoint) return dcp->dcpavservep; @@ -1821,12 +1817,6 @@ static struct apple_dcp_afkep *dcp_afkep(struct apple_dcp *dcp, u8 endpoint) } } -/* Whether something already drives @endpoint (HDCP starts only idle ones). */ -bool dcp_endpoint_routed(struct apple_dcp *dcp, u8 endpoint) -{ - return !!dcp_afkep(dcp, endpoint); -} - /* RX and the watchdog may race to finish one present, never both. */ bool dcp_desktop_present_complete(struct apple_dcp *dcp, u32 id) { @@ -5084,9 +5074,6 @@ int dcp_start(struct platform_device *pdev) } - /* Before any endpoint announces its services: they are matched by name. */ - dcp_hdcp_init(dcp); - /* Even if nothing starts, dcp_wait_ready() must find it initialised. */ init_completion(&dcp->start_done); init_completion(&dcp->s2r_dart_done); @@ -5238,7 +5225,6 @@ int dcp_start(struct platform_device *pdev) dcp_cec_register(dcp); } #endif - dcp_hdcp_start_endpoints(dcp); return ret; } @@ -5519,9 +5505,6 @@ void dcp_poweron(struct platform_device *pdev) unsigned long remaining; int ret; - /* A new link: DCP opens a new HDCP session once it is up. */ - dcp_hdcp_link_changed(dcp); - /* The takeover trial powered it on before the eviction. */ if (dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->desktop->trial_powered) { @@ -5705,9 +5688,6 @@ void dcp_poweroff(struct platform_device *pdev) bool display_gone = false; int ret; - /* DPMS off ends any HDCP session before the pipe goes down; the next power-on starts another. */ - dcp_hdcp_quiesce(dcp); - if (iomfb_is_m4(dcp)) { ret = dcp_backlight_dpms(dcp, false); if (!ret) @@ -7690,7 +7670,6 @@ VISIBLE_IF_KUNIT void dcp_comp_unbind(struct device *dev, struct device *main, v if (!dcp) return; - dcp_hdcp_fini(dcp); if (IS_ENABLED(CONFIG_APPLE_SOC_SLEEP)) apple_sleep_v27_unregister(dev); dcp_indicator_release(dcp); @@ -10216,9 +10195,6 @@ static int dcp_s2r_suspend(struct apple_dcp *dcp) bool was_off; int ret; - /* Encryption off and the HDCP session ended while DCP still runs. */ - dcp_hdcp_quiesce(dcp); - /* * Not bound into the display subsystem (a component unbind released the RTKit * session): nothing of the firmware is this driver's to stop. diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index a8c09cd8378cce..cbc093e132fc8a 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -41,7 +41,6 @@ #include "cec.h" #include "dcp.h" #include "dcp-hdr-metadata.h" -#include "dcp-hdcp-drv.h" #include "dcp-internal.h" #include "iomfb.h" #include "iomfb_internal.h" @@ -1993,9 +1992,6 @@ void dcp_hotplug(struct work_struct *work) connector->connected, READ_ONCE(dcp->mode_state.valid), dcp->nr_modes); if (READ_ONCE(dcp->mode_state.valid)) dcp->tunnel_power_cycles = 0; - /* An unplugged sink ends its HDCP session; a new link brings another. */ - if (!READ_ONCE(connector->connected)) - dcp_hdcp_link_changed(dcp); scoped_guard(mutex, &connector->base.dev->mode_config.mutex) { if (READ_ONCE(connector->dcp) == pdev) From 077c62ee6d8c0326c9a25ffdfe89c4bed3efb280 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 21:51:52 +1100 Subject: [PATCH 1488/1514] arm64: dts: apple: t6050: share Touch ID, add it to K114s, K114c and K116c The SEP mailbox and the Touch ID sensor (ADT spi2/mesa) were written out three times, in the J714s, J716c and K116s board files, while the K114s, K114c and K116c had neither. The live ADTs of the J714s, J716c, K114s and K116s and the 27.2 DeviceTrees of the K114c and K116c describe both alike: the SEP behind sep_mbox and ps_sep, the Mesa sensor on spi2 at 8 MHz on chip select 0, NUB GPIO 21 for power and AP GPIO 138 for data ready. Move the SEP part into t6050-sep.dtsi (was t6050-j716c-sep.dtsi) and the sensor into t6050-touchid.dtsi, which includes it. A board names its per-device calibration and root key in T6050_TOUCHID_FIRMWARE before the include; aurora-touchid-setup builds those files from the Mac's own iBoot System Container. The K boards' shared pin lists now leave pin 138 open. The J714s, J716c and K116s DTBs are unchanged apart from property order (identical after dtc -s). The K114s, K114c and K116c DTBs gain the sep alias, the mailbox and SEP power domain, the firmware-owned fabric parents (K116c only; the 14-inch boards already had them for the ANE), spi2 with fingerprint@0, and pin 138. The other five T6050 DTBs are byte-identical. dtschema reports nothing new. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-j714s.dts | 66 +----------------- .../arm64/boot/dts/apple/t6050-j716c-sep.dtsi | 29 -------- arch/arm64/boot/dts/apple/t6050-j716c.dts | 40 +---------- .../arm64/boot/dts/apple/t6050-k114-k116.dtsi | 7 +- arch/arm64/boot/dts/apple/t6050-k114.dtsi | 5 +- arch/arm64/boot/dts/apple/t6050-k114c.dts | 8 ++- arch/arm64/boot/dts/apple/t6050-k114s.dts | 4 ++ arch/arm64/boot/dts/apple/t6050-k116c.dts | 4 ++ arch/arm64/boot/dts/apple/t6050-k116s.dts | 68 +------------------ arch/arm64/boot/dts/apple/t6050-sep.dtsi | 34 ++++++++++ arch/arm64/boot/dts/apple/t6050-touchid.dtsi | 51 ++++++++++++++ 11 files changed, 115 insertions(+), 201 deletions(-) delete mode 100644 arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi create mode 100644 arch/arm64/boot/dts/apple/t6050-sep.dtsi create mode 100644 arch/arm64/boot/dts/apple/t6050-touchid.dtsi diff --git a/arch/arm64/boot/dts/apple/t6050-j714s.dts b/arch/arm64/boot/dts/apple/t6050-j714s.dts index 23475ad163f58f..a411c8958d2f2d 100644 --- a/arch/arm64/boot/dts/apple/t6050-j714s.dts +++ b/arch/arm64/boot/dts/apple/t6050-j714s.dts @@ -44,11 +44,6 @@ model = "Apple MacBook Pro (14-inch, M5 Pro, 2026)"; chassis-type = "laptop"; - aliases { - /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ - sep = &sep; - }; - chosen { #address-cells = <2>; #size-cells = <2>; @@ -528,64 +523,9 @@ power-domains = <&pmp0_gfx>; }; -/* - * The SEP (ADT sep, dart-sep): its mailbox, and its power domain with the two - * fabric parents left to the firmware, which genpd votes on and never turns off. - * The boot loader enables the SEP itself through its alias. - */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; - -/* - * Touch ID (ADT spi2/mesa): J616s's Mesa sensor (sensor-id 0x3356) at 8 MHz on - * chip select 0, powered by NUB GPIO 21 (function-mesa_pwr), data ready on AP - * GPIO 138. The controller's clock (ADT clock-ids 451) is the 24 MHz reference. - */ -&ps_nub_gpio { - status = "okay"; -}; - -&nub_gpio0 { - status = "okay"; -}; - -&ps_spi2 { - status = "okay"; -}; - -&spi2 { - clocks = <&clkref>; - status = "okay"; - - mesa: fingerprint@0 { - compatible = "apple,mesa-fingerprint"; - reg = <0>; - spi-max-frequency = <8000000>; - spi-cpol; - spi-cs-setup-delay-ns = <20>; - spi-cs-hold-delay-ns = <20>; - enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; - interrupt-parent = <&pinctrl_ap>; - interrupts = <138 IRQ_TYPE_EDGE_RISING>; - /* Per-device factory data from this Mac's own iBoot system container */ - firmware-name = "apple/mesacal-j714s.bin", "apple/msrk-j714s.bin"; - }; -}; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-j714s.bin", "apple/msrk-j714s.bin" +#include "t6050-touchid.dtsi" /* * The ProRes engine (apr0) and its DART, in the SCODEC power state. Its diff --git a/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi b/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi deleted file mode 100644 index 23019a719e07bb..00000000000000 --- a/arch/arm64/boot/dts/apple/t6050-j716c-sep.dtsi +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0+ OR MIT -/* J716c SEP handoff and the providers needed for warm registration. */ - -/ { - aliases { - /* The loader supplies the reserved image and registration manifests. */ - sep = &sep; - }; -}; - -/* The SEP and its DART are enabled by the driver after its policy is selected. */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -/* Retain the fabric parents while the pre-booted enclave owns them. */ -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; diff --git a/arch/arm64/boot/dts/apple/t6050-j716c.dts b/arch/arm64/boot/dts/apple/t6050-j716c.dts index 679e9f2f788563..0f496ab99e0a75 100644 --- a/arch/arm64/boot/dts/apple/t6050-j716c.dts +++ b/arch/arm64/boot/dts/apple/t6050-j716c.dts @@ -282,49 +282,15 @@ 63 2e 00 06 02 69 4f 53 00 00 00 00]; }; -/* - * Touch ID (ADT spi2/mesa), wired as on the J714s: the Mesa sensor (sensor-id - * 0x3356) at 8 MHz on chip select 0, powered by NUB GPIO 21 (function-mesa_pwr), - * data ready on AP GPIO 138. The controller's clock (ADT clock-ids 451) is the - * 24 MHz reference. - */ -&ps_nub_gpio { - status = "okay"; -}; - -&nub_gpio0 { - status = "okay"; -}; - -&ps_spi2 { - status = "okay"; -}; - -&spi2 { - clocks = <&clkref>; - status = "okay"; - - mesa: fingerprint@0 { - compatible = "apple,mesa-fingerprint"; - reg = <0>; - spi-max-frequency = <8000000>; - spi-cpol; - spi-cs-setup-delay-ns = <20>; - spi-cs-hold-delay-ns = <20>; - enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; - interrupt-parent = <&pinctrl_ap>; - interrupts = <138 IRQ_TYPE_EDGE_RISING>; - /* Per-device factory data from this Mac's own iBoot system container */ - firmware-name = "apple/mesacal-j716c.bin", "apple/msrk-j716c.bin"; - }; -}; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-j716c.bin", "apple/msrk-j716c.bin" +#include "t6050-touchid.dtsi" #include "t6050-j716c-isp.dtsi" #include "t6050-j716c-gpu-panel.dtsi" #include "t6050-j716c-display.dtsi" #include "t6050-j716c-left-usb4.dtsi" -#include "t6050-j716c-sep.dtsi" #include "t6050-j716c-sleep.dtsi" #include "t6050-j716c-sleep-full.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index d26d2621b38a0a..b4945f66892b36 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -121,11 +121,12 @@ /* * As on J716c, where reading pin 112 takes an SError, only the pins a node - * names are exposed: 80, PCIe port 0's PERST#, and 134 and 139, the jack - * codec's interrupt and reset. A board that names more pins replaces the list. + * names are exposed: 80, PCIe port 0's PERST#; 134 and 139, the jack codec's + * interrupt and reset; 138, the Touch ID sensor's data-ready line + * (t6050-touchid.dtsi). A board that names more pins replaces the list. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 53>, <135 4>, <140 81>; + gpio-reserved-ranges = <0 80>, <81 53>, <135 3>, <140 81>; }; /* diff --git a/arch/arm64/boot/dts/apple/t6050-k114.dtsi b/arch/arm64/boot/dts/apple/t6050-k114.dtsi index a895eebe32f030..4e84683dfc5beb 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114.dtsi @@ -44,10 +44,11 @@ * Pin 112's register takes an SError when read, so only the pins a node names are * exposed: 80 (PCIe port 0's PERST#); 106 and 107, the speaker amps' interrupt and * shutdown line (ADT audio-speaker, used only where a board describes the amps); - * 134 and 139, the jack codec's interrupt and reset; 136 and 137, the speaker ID. + * 134 and 139, the jack codec's interrupt and reset; 136 and 137, the speaker ID; 138, the + * Touch ID sensor's data-ready line (t6050-touchid.dtsi). */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <81 25>, <108 26>, <135 1>, <140 81>; }; /* diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index 7550e9838e9a38..23e1a45cb9974f 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -158,6 +158,10 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k114c.bin", "apple/msrk-k114c.bin" +#include "t6050-touchid.dtsi" + /* * The K114c keeps J714's card with its speakers, at the J714's safe level. The * chassis' K114 entry (t6050-k114.dtsi) has the jack only. @@ -307,10 +311,10 @@ * Pin 112's register takes an SError when read, so only the pins a node here * names are exposed: 80 and 81 (PCIe ports 0 and 1's PERST#); 106 and 107, the speaker * amps' interrupt and shutdown line; 134 and 139, the jack codec's interrupt and - * reset; 136 and 137, the speaker ID. + * reset; 136 and 137, the speaker ID; 138, the Touch ID sensor's data-ready line. */ &pinctrl_ap { - gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <138 1>, <140 81>; + gpio-reserved-ranges = <0 80>, <82 24>, <108 26>, <135 1>, <140 81>; }; /* It answers only once port 1's root complex is up: pcie-apple then enables it */ diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 41059929b296eb..234cb5d5eceee1 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -36,6 +36,10 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k114s.bin", "apple/msrk-k114s.bin" +#include "t6050-touchid.dtsi" + / { aliases { /* asahi-bless and the boot loader find the NVRAM partition by this alias */ diff --git a/arch/arm64/boot/dts/apple/t6050-k116c.dts b/arch/arm64/boot/dts/apple/t6050-k116c.dts index 40bfec8ab72a85..6bc716bfc0f422 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116c.dts @@ -29,5 +29,9 @@ /* The GPU, handed over by the boot loader */ #include "t6050-k114-k116-gpu.dtsi" +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k116c.bin", "apple/msrk-k116c.bin" +#include "t6050-touchid.dtsi" + /* The USB-C ports ATC1 and ATC2, as on the other K boards */ #include "t6050-k114-k116-usb.dtsi" diff --git a/arch/arm64/boot/dts/apple/t6050-k116s.dts b/arch/arm64/boot/dts/apple/t6050-k116s.dts index 26f4bce4362dbc..44490669d152bc 100644 --- a/arch/arm64/boot/dts/apple/t6050-k116s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k116s.dts @@ -26,13 +26,6 @@ #define T6050_K116S #include "t6050-peripherals.dtsi" -/ { - aliases { - /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ - sep = &sep; - }; -}; - &pinctrl_ap { /* * Pin 112 takes an SError when read, so only the pins a node names are @@ -322,29 +315,6 @@ #include "t6050-k116s-pmp-tunables.dtsi" -/* - * The SEP (ADT sep, dart-sep), as on the J714s: its mailbox, and its power domain with the two - * fabric parents left to the firmware, which genpd votes on and never turns off. The boot - * loader enables the SEP itself through its alias. - */ -&sep_mbox { - status = "okay"; -}; - -&ps_sep { - status = "okay"; -}; - -&ps_fab8_soc { - apple,firmware-owned; - status = "okay"; -}; - -&ps_fab0_piogw { - apple,firmware-owned; - status = "okay"; -}; - /* Sound: the J714s description, every value checked against the K116s ADT. */ /* * The amps' shared shutdown line (SDZ): ADT audio-speaker function-reset, AP pin 107. One @@ -680,41 +650,9 @@ status = "okay"; }; -/* - * Touch ID (ADT spi2/mesa): the Mesa sensor on spi2 at 8 MHz, chip select 0, - * powered by NUB GPIO 21 (function-mesa_pwr), data ready on AP GPIO 138, as - * on the J714s. spi2 runs from the 24 MHz reference (ADT clock-ids 451). - */ -&ps_nub_gpio { - status = "okay"; -}; - -&nub_gpio0 { - status = "okay"; -}; - -&ps_spi2 { - status = "okay"; -}; - -&spi2 { - clocks = <&clkref>; - status = "okay"; - - mesa: fingerprint@0 { - compatible = "apple,mesa-fingerprint"; - reg = <0>; - spi-max-frequency = <8000000>; - spi-cpol; - spi-cs-setup-delay-ns = <20>; - spi-cs-hold-delay-ns = <20>; - enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; - interrupt-parent = <&pinctrl_ap>; - interrupts = <138 IRQ_TYPE_EDGE_RISING>; - /* Per-device factory data from this Mac's own iBoot system container */ - firmware-name = "apple/mesacal-k116s.bin", "apple/msrk-k116s.bin"; - }; -}; +/* Touch ID: the SEP and the Mesa sensor, with this Mac's own calibration and root key */ +#define T6050_TOUCHID_FIRMWARE "apple/mesacal-k116s.bin", "apple/msrk-k116s.bin" +#include "t6050-touchid.dtsi" /* * The PMU's RTC and its alarm. ADT: the PMU's info-rtc (0x2002), diff --git a/arch/arm64/boot/dts/apple/t6050-sep.dtsi b/arch/arm64/boot/dts/apple/t6050-sep.dtsi new file mode 100644 index 00000000000000..102b254178a1d6 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-sep.dtsi @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * The SEP (ADT sep, dart-sep) on the T6050 laptops: its mailbox, and its power domain with the + * two fabric parents left to the firmware, which genpd votes on and never turns off. The SEP + * and its DART stay disabled here: apple_sep enables them after it selects its policy, and only + * where the mailbox is enabled. + * + * Included after t6050-peripherals.dtsi. + */ + +/ { + aliases { + /* the boot loader reserves the SEP firmware and adds its manifests through this alias */ + sep = &sep; + }; +}; + +&sep_mbox { + status = "okay"; +}; + +&ps_sep { + status = "okay"; +}; + +&ps_fab8_soc { + apple,firmware-owned; + status = "okay"; +}; + +&ps_fab0_piogw { + apple,firmware-owned; + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-touchid.dtsi b/arch/arm64/boot/dts/apple/t6050-touchid.dtsi new file mode 100644 index 00000000000000..0d7cb8986b8094 --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6050-touchid.dtsi @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * Touch ID on the T6050 laptops: the SEP (t6050-sep.dtsi) and the Mesa sensor (ADT spi2/mesa). + * The live ADTs of the J714s, J716c, K114s and K116s and the 27.2 DeviceTrees of the other + * boards describe it alike: spi2 at 8 MHz, chip select 0, powered by NUB GPIO 21 + * (function-mesa_pwr), data ready on AP GPIO 138. spi2 runs from the 24 MHz reference (ADT + * clock-ids 451). + * + * The board defines T6050_TOUCHID_FIRMWARE before including this file: the sensor's + * calibration and signed root key, per-device factory data that aurora-touchid-setup builds + * from this Mac's own iBoot System Container. The board also leaves AP pin 138 out of its + * gpio-reserved-ranges. + * + * Included after t6050-peripherals.dtsi. + */ + +#ifndef T6050_TOUCHID_FIRMWARE +#error "define T6050_TOUCHID_FIRMWARE (calibration, root key) before including t6050-touchid.dtsi" +#endif + +#include "t6050-sep.dtsi" + +&ps_nub_gpio { + status = "okay"; +}; + +&nub_gpio0 { + status = "okay"; +}; + +&ps_spi2 { + status = "okay"; +}; + +&spi2 { + clocks = <&clkref>; + status = "okay"; + + mesa: fingerprint@0 { + compatible = "apple,mesa-fingerprint"; + reg = <0>; + spi-max-frequency = <8000000>; + spi-cpol; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + enable-gpios = <&nub_gpio0 21 GPIO_ACTIVE_HIGH>; + interrupt-parent = <&pinctrl_ap>; + interrupts = <138 IRQ_TYPE_EDGE_RISING>; + firmware-name = T6050_TOUCHID_FIRMWARE; + }; +}; From 715ef4b7956903078d8fa34bdc43011703d601f8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 23:54:30 +1100 Subject: [PATCH 1489/1514] arm64: dts: apple: t6050: share the K boards' NVRAM, writable asahi-bless and aurora-bless cannot set the next boot on the K114s: the DT marks its NVRAM partition read-only, so MTD never sets MTD_WRITEABLE and every write fails with EACCES, even as root. The K114c's partition is read-only too, and the K116s and K116c describe no boot NOR at all. Every other Mac with a boot NOR leaves the partition writable. The live K114s, K116s and J716c ADTs and the K114c and K116c 27.2 DeviceTrees give the same NVRAM: /arm-io/qspi/spinor/anvram at 0x700000, 0xc0000 bytes. Describe it once in t6050-k114-k116.dtsi, single-wire as on the K114s and J775D, without read-only, with the nvram alias. spi-apple-qspi still starts read-only; once root opts in, it admits only bounded, verified programs and 4 KiB erases of a known part inside this partition. The K114s and K114c DTBs lose read-only (the K114c's flash also states the single-wire default), the K116s and K116c gain the NOR and its partition, and the other seven T6050 DTBs are byte-identical. dtschema reports nothing new. Signed-off-by: Ryan Murray --- .../arm64/boot/dts/apple/t6050-k114-k116.dtsi | 39 ++++++++++++++++++ arch/arm64/boot/dts/apple/t6050-k114c.dts | 32 --------------- arch/arm64/boot/dts/apple/t6050-k114s.dts | 40 +------------------ 3 files changed, 40 insertions(+), 71 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index d26d2621b38a0a..5b92a2e4daad60 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -318,3 +318,42 @@ power-domains = <&ps_apcie_sys_gp>; }; +/ { + aliases { + /* asahi-bless and the boot loader find the NVRAM partition by this alias */ + nvram = &nvram; + }; +}; + +/* + * The boot NOR's NVRAM partition, the same in the live K114s, K116s and J716c ADTs and the + * K114c and K116c 27.2 DeviceTrees: /arm-io/qspi/spinor/anvram, 0x700000, 0xc0000 bytes, 12 + * banks of 64 KiB. Only this partition is described, so the rest of the NOR has no device + * node. Single-wire, as on the J775D: spi-nor then sends no quad-enable status write at probe. + * + * The partition is writable, as on the other Macs with a boot NOR, so asahi-bless and + * aurora-bless can set the next boot. spi-apple-qspi still starts read-only and, once root + * opts in, admits only bounded, verified programs and 4 KiB erases of a known part inside it. + */ +&qspi { + status = "okay"; + + flash@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + spi-max-frequency = <25000000>; + spi-rx-bus-width = <1>; + spi-tx-bus-width = <1>; + + partitions { + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; + + nvram: partition@700000 { + label = "nvram"; + reg = <0x700000 0xc0000>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6050-k114c.dts b/arch/arm64/boot/dts/apple/t6050-k114c.dts index eea1c5485599c9..d7eb9fddf40f91 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114c.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114c.dts @@ -30,12 +30,6 @@ #include "t6050-peripherals.dtsi" -/ { - aliases { - nvram = &nvram; - }; -}; - /* * The speakers, through the AOP as on J813: the six SN012776 speaker amps on admac-base-ns * TX0, their voltage and current sense on RX0 (ADT iop-audio-controller). The jack, the @@ -213,32 +207,6 @@ #include "t6050-k114-k116-usb.dtsi" #include "t6050-k114-usb.dtsi" -/* - * The boot NOR. spi-nor reads the part's JEDEC ID itself. The partition is - * read-only: no program or erase reaches the flash until a later change lifts it. - */ -&qspi { - status = "okay"; - - flash@0 { - compatible = "jedec,spi-nor"; - reg = <0>; - spi-max-frequency = <25000000>; - - partitions { - compatible = "fixed-partitions"; - #address-cells = <1>; - #size-cells = <1>; - - nvram: partition@700000 { - label = "nvram"; - reg = <0x700000 0xc0000>; - read-only; - }; - }; - }; -}; - /* * PCIe port 1: the SD card reader, this board's own beside the shared port 0 * (t6050-k114-k116.dtsi): its registers, interrupt and DART stream 1 of dart-apcie1. diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index e2819f2dcdf3de..5e7a9ad55a1f9e 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -4,8 +4,7 @@ * * target-type: K114s (Mac17,13) * - * Preliminary: described from the ADT. Only the NVRAM partition below has been run on a K114s, - * from the boot loader's tree; this file as a whole has not been booted. + * Described from the ADT and booted on a K114s. * * Copyright The Asahi Linux Contributors */ @@ -49,43 +48,6 @@ height-mm = <199>; }; -/ { - aliases { - /* asahi-bless and the boot loader find the NVRAM partition by this alias */ - nvram = &nvram; - }; -}; - -/* - * The boot NOR's NVRAM partition (ADT /arm-io/qspi/spinor/anvram: reg 0x700000, 0xc0000, 12 - * banks of 64 KiB). Only this partition is described, so the rest of the NOR has no device - * node. Single-wire, as on the J775D: spi-nor then sends no quad-enable status write at probe. - * The partition is read-only, as on the K114c. - */ -&qspi { - status = "okay"; - - flash@0 { - compatible = "jedec,spi-nor"; - reg = <0>; - spi-max-frequency = <25000000>; - spi-rx-bus-width = <1>; - spi-tx-bus-width = <1>; - - partitions { - compatible = "fixed-partitions"; - #address-cells = <1>; - #size-cells = <1>; - - nvram: partition@700000 { - label = "nvram"; - reg = <0x700000 0xc0000>; - read-only; - }; - }; - }; -}; - /* * The USB-C ports ATC1 and ATC2, as on the other K boards (t6050-k114-k116-usb.dtsi), then the * 14-inch chassis' MagSafe 3 PD controller and the right port's USB4/Thunderbolt router From a6e55368ddb37b2512c7a4bb46f28dfef201c133 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 00:02:38 +1100 Subject: [PATCH 1490/1514] arm64: dts: apple: t6050: K NVRAM: name the Macs it follows The shared NVRAM comment said every other Mac with a boot NOR leaves the partition writable; the J615 keeps its own read-only. Name the Macs whose writable partitions these follow (J616s, J713, J700) instead, and point the K114s header at the partition's new place. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi | 4 ++-- arch/arm64/boot/dts/apple/t6050-k114s.dts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi index 5b92a2e4daad60..0de7e2dcc6a05d 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi +++ b/arch/arm64/boot/dts/apple/t6050-k114-k116.dtsi @@ -331,8 +331,8 @@ * banks of 64 KiB. Only this partition is described, so the rest of the NOR has no device * node. Single-wire, as on the J775D: spi-nor then sends no quad-enable status write at probe. * - * The partition is writable, as on the other Macs with a boot NOR, so asahi-bless and - * aurora-bless can set the next boot. spi-apple-qspi still starts read-only and, once root + * The partition is writable, as on the J616s, J713 and J700, so asahi-bless and aurora-bless + * can set the next boot. spi-apple-qspi still starts read-only and, once root * opts in, admits only bounded, verified programs and 4 KiB erases of a known part inside it. */ &qspi { diff --git a/arch/arm64/boot/dts/apple/t6050-k114s.dts b/arch/arm64/boot/dts/apple/t6050-k114s.dts index 5e7a9ad55a1f9e..43908a0b6faed4 100644 --- a/arch/arm64/boot/dts/apple/t6050-k114s.dts +++ b/arch/arm64/boot/dts/apple/t6050-k114s.dts @@ -4,7 +4,8 @@ * * target-type: K114s (Mac17,13) * - * Described from the ADT and booted on a K114s. + * Preliminary: described from the ADT. Only the NVRAM partition (t6050-k114-k116.dtsi) has been run + * on a K114s, from the boot loader's tree; this file as a whole has not been booted. * * Copyright The Asahi Linux Contributors */ From 7f1220a150c47dcf2998553601c30a9b1da35fa7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 00:17:56 +1100 Subject: [PATCH 1491/1514] iio: aop_als: stop the reports at unbind, arm the CT817 from zero The light sensor reports on its own every 200 ms, and every report is an AOP mailbox interrupt. unbind() only dropped the listener, so the sensor went on reporting to nobody: on the J700 (T8140, CT817) the AOP mailbox kept taking 5 interrupts a second after the driver was unbound, the same rate as with the driver bound. Write the interval to zero at unbind, before the listener goes, as the motion driver already stops its sensor at unbind. A failure is logged and unbind goes on; the AOP transport refuses calls once it is closing. The CT817 arms only on a zero to non-zero transition of its interval. Probe assumed the interval was zero, which holds at a cold boot but not after a previous instance of the driver (or a kexec) left the sensor running. Make the zero write the first step of arm_ct817(), so probe and the wake path share one sequence; the wake path already wrote zero first, so its behaviour does not change. This takes over the unbind part of #2713 by Kyle Arrington, who handed the branch over. Its suspend and resume part is left out: #2528 now arms the CT817 again after a sleep, and whether reports still wake the CPU in suspend-to-idle needs its own measurement. Link: https://github.com/aurora-silicon/linux/pull/2713 Signed-off-by: Ryan Murray --- drivers/iio/common/aop_sensors/aop_als.rs | 38 ++++++++++++++++------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index cefd01640bc963..401f4f2bb32de0 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -110,7 +110,8 @@ fn enable_als( arm_ct817(aop, dev.as_ref(), svc) } -/// Arms the CT817: its configuration, then the interval that starts the reports. +/// Arms the CT817: interval zero, its configuration, then the interval that +/// starts the reports. fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<()> { // The CT817 gets its calibration from the AOP driver over the setup port, // not as an ALS property. Only the transport can fail here; the sensor's @@ -123,6 +124,10 @@ fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<( dev_dbg!(dev, "{} = {:#x}: status {:#x}\n", what, val, status); Ok(()) }; + // The sensor arms only on a zero to non-zero transition of the interval. + // It is zero at boot and stopped after a sleep, but a previous driver + // instance may have left it running, so write zero first every time. + set(ALS_PROP_INTERVAL, 0, "interval")?; set(ALS_PROP_VERBOSITY, ALS_VERBOSITY, "verbosity")?; set( ALS_PROP_BATCH_INTERVAL, @@ -130,8 +135,7 @@ fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<( "batch interval", )?; set(ALS_PROP_RAW_INTERVAL, ALS_RAW_INTERVAL, "raw interval")?; - // The interval is zero at probe, and the wake writes it to zero first, so - // this is the transition that arms the sensor. + // The transition that arms the sensor. set(ALS_PROP_INTERVAL, ALS_INTERVAL_US, "interval") } @@ -141,8 +145,8 @@ fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<( /// start them again: on the J700 every read after the first wake of a boot /// returned the last sample from before that sleep, while the room's light /// changed. The sensor starts reporting only on a zero to non-zero transition -/// of its interval, so the wake writes the interval to zero and then repeats -/// the arming of the probe. +/// of its interval, so the wake repeats the arming of the probe, which starts +/// with an interval of zero. #[repr(C)] struct PmHook { /// First, so that the callback finds the hook from it. @@ -168,10 +172,7 @@ unsafe extern "C" fn pm_event( } // SAFETY: `nb` is the first field of a registered `PmHook`. let hook = unsafe { &*nb.cast::() }; - let aop = hook.aop.as_ref(); - let rearm = set_als_property(aop, &hook.service, ALS_PROP_INTERVAL, &0u32.to_le_bytes()) - .and_then(|_| arm_ct817(aop, &hook.dev, &hook.service)); - match rearm { + match arm_ct817(hook.aop.as_ref(), &hook.dev, &hook.service) { Ok(()) => dev_dbg!(hook.dev, "reports armed again after sleep\n"), Err(e) => dev_warn!(hook.dev, "reports not armed again after sleep: {:?}\n", e), } @@ -349,6 +350,8 @@ struct IIOAopAlsDriver { pm: Option>>, listener: FakehidRegistration, _iio: AlsIio, + aop: Arc, + service: EPICService, } fn register_channels( @@ -426,7 +429,7 @@ impl platform::Driver for IIOAopAlsDriver { ) }; let pm = if offset == LUX_OFFSET_CT817 { - Some(PmHook::new(dev, adata, service)?) + Some(PmHook::new(dev, adata.clone(), service)?) } else { None }; @@ -434,13 +437,26 @@ impl platform::Driver for IIOAopAlsDriver { pm, listener, _iio: iio, + aop: adata, + service, }) } - fn unbind(_dev: &platform::Device>, this: Pin<&Self>) { + fn unbind(dev: &platform::Device>, this: Pin<&Self>) { if let Some(pm) = &this.pm { pm.unregister(); } + // The sensor keeps reporting until its interval is zero, and every + // report is an AOP mailbox interrupt. Stop it before the listener + // goes; a failure only costs those interrupts, so unbind goes on. + if let Err(e) = set_als_property( + this.aop.as_ref(), + &this.service, + ALS_PROP_INTERVAL, + &0u32.to_le_bytes(), + ) { + dev_warn!(dev.as_ref(), "reports not stopped at unbind: {:?}\n", e); + } this.listener.unregister(); } } From 7a5a3bb308eca28940895b1da166b9a7b3aebda8 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 00:19:54 +1100 Subject: [PATCH 1492/1514] arm64: dts: apple: t8132: describe the SMC SoC die sensors and thermal pressure No M4 (T8132) board lists SMC die keys, so the M4 Macs have no CPU die temperatures in hwmon, no macsmc_soc_die thermal zone and no thermal_pressure_level, unlike the M2, M3 and M5 Macs. The SMC reports each CPU die sensor as a key triplet. List the middle key of each, as the M3 (T8122) tree does: under a pinned load it tracks the PMP die hotspot within about 2 C, while the first key of each triplet reads 8-11 C lower. Te05 Te09 Te0H Te0S respond to E-cluster load and Tp01 ... Tp1R to P-cluster load. The GPU (Tg) keys hold a fixed placeholder while Linux drives the GPU and are left out. The properties go in t8132-jxxx.dtsi beside the hwmon node itself, so every M4 Mac gets them; the driver skips keys a machine's SMC lacks. No trip temperatures are added: the zone reports only, and the M4 GPU keeps sampling the PMP (apple,pmp), so no thermal policy changes. Signed-off-by: Ryan Murray --- arch/arm64/boot/dts/apple/t8132-jxxx.dtsi | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi index cbaef76a34b2bf..f9cd8d3bd23663 100644 --- a/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-jxxx.dtsi @@ -184,6 +184,20 @@ smc_hwmon: hwmon { compatible = "apple,smc-hwmon"; + /* + * The CPU die sensors of the M4. The SMC reports each in a key + * triplet; the middle key is listed, as on M3: under load it + * tracks the PMP's die hotspot within about 2 C, while the + * first key reads 8-11 C lower. E cluster: Te05 Te09 Te0H Te0S; + * P cluster: Tp01 ... Tp1R. The GPU (Tg) keys are left out: + * they hold a fixed placeholder while Linux drives the GPU. + * Keys the running SMC lacks are skipped at probe. + */ + apple,soc-die-keys = "Te05", "Te09", "Te0H", "Te0S", + "Tp01", "Tp05", "Tp09", "Tp0D", "Tp0V", + "Tp0Y", "Tp0b", "Tp0e", "Tp1B", "Tp1F", + "Tp1R"; + apple,thermal-pressure-key = "mTPL"; }; smc_rtc: rtc { From 2de7a158d46324f3bcaefd53ba1b1c64bf273fa2 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 00:33:44 +1100 Subject: [PATCH 1493/1514] dt-checks: preserve property names ending in b The DT warning filter normalizes Python byte literals before splitting unknown-property lists. A property such as 'brcm,cal-blob' ends in the same two characters as a byte literal begins. The filter consumes its closing quote and prevents the warning from being split. Removing one of those properties can then be reported as a new warning. Require a token boundary before the byte literal prefix. Continue normalizing bytes in standalone and bracketed values. Fixes: 43a28f33c45c ("dt-checks: compare undocumented properties one by one") Signed-off-by: Ryan Murray --- scripts/dtc/apple-dt-check.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/dtc/apple-dt-check.sh b/scripts/dtc/apple-dt-check.sh index 971a7dd8287d60..38e8badcb9e46e 100755 --- a/scripts/dtc/apple-dt-check.sh +++ b/scripts/dtc/apple-dt-check.sh @@ -132,7 +132,7 @@ extract_warnings() { # src_dir out_dir log_file out_warn tag grep -E '\.dtb: |[Ww]arning|rror' "$filtered" | grep -v '^ ' | sed -E "s#$t/##g; s#$o/##g" | sed -E "s#arch/arm64/boot/dts/##; $variants" | sed -E 's#^apple/#arch/arm64/boot/dts/apple/#' | - perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | + perl -pe 's{(\[\[[^:]*?\]\])}{(my $x = $1) =~ s/\d+/N/g; $x}ge; s{(?:^|(?<=[\s\[(=]))b\x27(?:\\.|[^\x27])*\x27}{b\x27N\x27}g; s{( not match any of the regexes): .*}{$1: ...}' | sort -u > "$out" local ps=("${PIPESTATUS[@]}") if [ "${ps[0]}" -gt 1 ] || [ "${ps[1]}" -gt 1 ] || [ "${ps[2]}" -ne 0 ] || [ "${ps[3]}" -ne 0 ] || [ "${ps[4]}" -ne 0 ] || [ "${ps[5]}" -ne 0 ] || [ "${ps[6]}" -ne 0 ]; then From db3233256067e0a8fc4b999d59d3db665ec75f04 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 01:30:31 +1100 Subject: [PATCH 1494/1514] iio: aop_als: stop the reports for system sleep The light sensor reports on its own every 200 ms, and each report is an AOP mailbox interrupt. Nothing stopped them for a system sleep, so in suspend-to-idle they went on waking a CPU for readings nobody takes. On a J413 (M2 Air, VD6286, suspend-to-idle by default) the AOP mailbox took 84 interrupts during a 21 s rtc sleep with the light sensor armed, and 26 with it stopped: the light sensor was about 2.7 of the 4 wakeups a second the AOP caused while the Mac slept. The lid angle driver already stops its reports for the sleep. Extend the PM notifier that re-arms the CT817 to every part: at PM_SUSPEND_PREPARE write the interval to zero, and at PM_POST_SUSPEND start the reports again. The CT817 keeps the whole arming sequence after every sleep, because its firmware stops the reports for system sleep even when the host did not. The other parts get their interval back, and only if it was stopped. A failure to stop is logged and never refuses the sleep. Link: https://github.com/aurora-silicon/linux/pull/2713 Signed-off-by: Ryan Murray --- drivers/iio/common/aop_sensors/aop_als.rs | 85 ++++++++++++++++------- 1 file changed, 61 insertions(+), 24 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index 401f4f2bb32de0..97a084930de3d2 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -139,14 +139,20 @@ fn arm_ct817(aop: &dyn AOP, dev: &device::Device, svc: &EPICService) -> Result<( set(ALS_PROP_INTERVAL, ALS_INTERVAL_US, "interval") } -/// Arms the CT817 again after system sleep. +/// Stops the reports for system sleep and starts them again after it. /// -/// The firmware stops the light sensor's reports for system sleep and does not -/// start them again: on the J700 every read after the first wake of a boot -/// returned the last sample from before that sleep, while the room's light -/// changed. The sensor starts reporting only on a zero to non-zero transition -/// of its interval, so the wake repeats the arming of the probe, which starts -/// with an interval of zero. +/// The sensor reports on its own every `ALS_INTERVAL_US`, and each report is +/// an AOP mailbox interrupt. In suspend-to-idle those interrupts go on and +/// wake a CPU for a reading nobody takes, so the reports stop before the +/// sleep, as the lid angle driver's do. +/// +/// The CT817 needs more after the sleep: the firmware stops its reports for +/// system sleep and does not start them again. On the J700 every read after +/// the first wake of a boot returned the last sample from before that sleep, +/// while the room's light changed. The sensor starts reporting only on a zero +/// to non-zero transition of its interval, so the wake repeats the arming of +/// the probe, which starts with an interval of zero. The other parts need only +/// their interval back. #[repr(C)] struct PmHook { /// First, so that the callback finds the hook from it. @@ -154,6 +160,10 @@ struct PmHook { dev: ARef, aop: Arc, service: EPICService, + /// The part arms only through the whole CT817 sequence. + ct817: bool, + /// The reports were stopped for the sleep in progress. + stopped: Atomic, registered: Atomic, } @@ -167,14 +177,44 @@ unsafe extern "C" fn pm_event( action: usize, _data: *mut c_void, ) -> c_int { - if action as u32 != bindings::PM_POST_SUSPEND { - return bindings::NOTIFY_DONE as c_int; - } // SAFETY: `nb` is the first field of a registered `PmHook`. let hook = unsafe { &*nb.cast::() }; - match arm_ct817(hook.aop.as_ref(), &hook.dev, &hook.service) { - Ok(()) => dev_dbg!(hook.dev, "reports armed again after sleep\n"), - Err(e) => dev_warn!(hook.dev, "reports not armed again after sleep: {:?}\n", e), + let aop = hook.aop.as_ref(); + match action as u32 { + bindings::PM_SUSPEND_PREPARE => { + // A sensor that keeps reporting only costs wakeups: never refuse + // the sleep over it. + match set_als_property(aop, &hook.service, ALS_PROP_INTERVAL, &0u32.to_le_bytes()) { + Ok(_) => { + hook.stopped.store(true, Relaxed); + dev_dbg!(hook.dev, "reports off for sleep\n"); + } + Err(e) => dev_warn!(hook.dev, "reports left on for sleep: {:?}\n", e), + } + } + bindings::PM_POST_SUSPEND => { + let stopped = hook.stopped.xchg(false, Relaxed); + // The CT817 is stopped by the firmware even when the host did not + // stop it, so it is armed again after every sleep. + let rearm = if hook.ct817 { + arm_ct817(aop, &hook.dev, &hook.service) + } else if stopped { + set_als_property( + aop, + &hook.service, + ALS_PROP_INTERVAL, + &ALS_INTERVAL_US.to_le_bytes(), + ) + .map(|_| ()) + } else { + Ok(()) + }; + match rearm { + Ok(()) => dev_dbg!(hook.dev, "reports back after sleep\n"), + Err(e) => dev_warn!(hook.dev, "reports not back after sleep: {:?}\n", e), + } + } + _ => return bindings::NOTIFY_DONE as c_int, } bindings::NOTIFY_OK as c_int } @@ -224,6 +264,7 @@ impl PmHook { dev: &device::Device, aop: Arc, service: EPICService, + ct817: bool, ) -> Result>> { let hook = KBox::pin( Self { @@ -235,6 +276,8 @@ impl PmHook { dev: dev.into(), aop, service, + ct817, + stopped: Atomic::new(false), registered: Atomic::new(false), }, GFP_KERNEL, @@ -345,9 +388,9 @@ enum AlsIio { } struct IIOAopAlsDriver { - /// Fields are declared in teardown order: the wake hook (CT817 only) - /// first, then the subscription, which ends before the IIO device goes. - pm: Option>>, + /// Fields are declared in teardown order: the sleep hook first, then the + /// subscription, which ends before the IIO device goes. + pm: Pin>, listener: FakehidRegistration, _iio: AlsIio, aop: Arc, @@ -428,11 +471,7 @@ impl platform::Driver for IIOAopAlsDriver { }, ) }; - let pm = if offset == LUX_OFFSET_CT817 { - Some(PmHook::new(dev, adata.clone(), service)?) - } else { - None - }; + let pm = PmHook::new(dev, adata.clone(), service, offset == LUX_OFFSET_CT817)?; Ok(IIOAopAlsDriver { pm, listener, @@ -443,9 +482,7 @@ impl platform::Driver for IIOAopAlsDriver { } fn unbind(dev: &platform::Device>, this: Pin<&Self>) { - if let Some(pm) = &this.pm { - pm.unregister(); - } + this.pm.unregister(); // The sensor keeps reporting until its interval is zero, and every // report is an AOP mailbox interrupt. Stop it before the listener // goes; a failure only costs those interrupts, so unbind goes on. From 116a2c103c780ea01fbc7ee9b0a9abdf8250cb90 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 02:18:05 +1100 Subject: [PATCH 1495/1514] iio: aop_als: restore the interval after every attempted stop PM_SUSPEND_PREPARE marked the reports as stopped only when the AOP answered the interval-zero command. A command that reached the AOP but whose reply was lost or timed out may still have been applied, and then PM_POST_SUSPEND did not restore a VD6286 or CT720, which stayed silent until the driver was bound again. Record the attempt before the command goes out and restore the active interval after every attempted stop, whatever the reply. Writing the active interval to a sensor that kept reporting changes nothing; the CT817 keeps its full arming sequence after every sleep. Link: https://github.com/aurora-silicon/linux/pull/3404#pullrequestreview-6090152573 Signed-off-by: Ryan Murray --- drivers/iio/common/aop_sensors/aop_als.rs | 25 +++++++++++++---------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/drivers/iio/common/aop_sensors/aop_als.rs b/drivers/iio/common/aop_sensors/aop_als.rs index 97a084930de3d2..375cf57c793840 100644 --- a/drivers/iio/common/aop_sensors/aop_als.rs +++ b/drivers/iio/common/aop_sensors/aop_als.rs @@ -162,8 +162,10 @@ struct PmHook { service: EPICService, /// The part arms only through the whole CT817 sequence. ct817: bool, - /// The reports were stopped for the sleep in progress. - stopped: Atomic, + /// A stop was tried for the sleep in progress. It is set before the + /// command goes out: a stop whose reply was lost may still have been + /// applied, so the wake restores the interval after every attempt. + stop_attempted: Atomic, registered: Atomic, } @@ -184,21 +186,22 @@ unsafe extern "C" fn pm_event( bindings::PM_SUSPEND_PREPARE => { // A sensor that keeps reporting only costs wakeups: never refuse // the sleep over it. + hook.stop_attempted.store(true, Relaxed); match set_als_property(aop, &hook.service, ALS_PROP_INTERVAL, &0u32.to_le_bytes()) { - Ok(_) => { - hook.stopped.store(true, Relaxed); - dev_dbg!(hook.dev, "reports off for sleep\n"); - } - Err(e) => dev_warn!(hook.dev, "reports left on for sleep: {:?}\n", e), + Ok(_) => dev_dbg!(hook.dev, "reports off for sleep\n"), + Err(e) => dev_warn!(hook.dev, "reports may be left on for sleep: {:?}\n", e), } } bindings::PM_POST_SUSPEND => { - let stopped = hook.stopped.xchg(false, Relaxed); + let attempted = hook.stop_attempted.xchg(false, Relaxed); // The CT817 is stopped by the firmware even when the host did not - // stop it, so it is armed again after every sleep. + // stop it, so it is armed again after every sleep. The other parts + // get their interval back after every attempted stop, whether or + // not the stop's reply arrived; writing the active interval to a + // sensor that kept reporting changes nothing. let rearm = if hook.ct817 { arm_ct817(aop, &hook.dev, &hook.service) - } else if stopped { + } else if attempted { set_als_property( aop, &hook.service, @@ -277,7 +280,7 @@ impl PmHook { aop, service, ct817, - stopped: Atomic::new(false), + stop_attempted: Atomic::new(false), registered: Atomic::new(false), }, GFP_KERNEL, From 1a0ebea2d713f53a34e4ef772e40a1804516d493 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Thu, 26 Nov 2026 15:14:24 -0300 Subject: [PATCH 1496/1514] soc: apple: display-gate: take dcpext3's Type-C routes from the device tree The M4 Max dcpext3 chain names its Type-C routes by path: three, for the three USB-C ports of the J614c/J616c. A board with another number of ports needs another list, and the J575c, with four back Type-C ports, would leave its fourth route disabled. Take the routes from the processor's typec-routes node instead. Each child is enabled with the chain, just before the processor, as the listed routes were, and the chain is only ready while the typec-routes container is present, non-empty, and every route is still disabled. Application also refuses a missing or empty typec-routes container so an incomplete DTB leaves the whole changeset untouched. On the J614c/J616c the chain enables the same nodes, in the same order, as before. The KUnit chain check now covers the routes taken from the tree, and new cases cover a fourth route (positive control) as well as missing and empty typec-routes containers (negative controls). Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- drivers/soc/apple/display-gate-test.c | 78 +++++++++++++++++++++++- drivers/soc/apple/display-gate.c | 87 +++++++++++++++++++++++++-- 2 files changed, 159 insertions(+), 6 deletions(-) diff --git a/drivers/soc/apple/display-gate-test.c b/drivers/soc/apple/display-gate-test.c index cff3298d1ee576..58e96acb602af6 100644 --- a/drivers/soc/apple/display-gate-test.c +++ b/drivers/soc/apple/display-gate-test.c @@ -1440,10 +1440,22 @@ static void __init gt_max_fill(struct kunit *test, unsigned int i) static void __init gt_max_expect_chain(struct kunit *test, unsigned int i, bool enabled) { const struct gate_staged *st = &t6041_max_stages[i]; - unsigned int n; + struct device_node *routes, *route; + unsigned int n, nr_routes = 0; for (n = 0; n < st->nr; n++) KUNIT_EXPECT_EQ_MSG(test, gt_okay(test, st->nodes[n]), enabled, "%s", st->nodes[n]); + if (!st->dt_routes) + return; + /* A chain that takes its routes from the tree has every one of them. */ + routes = staged_routes(st); + KUNIT_ASSERT_NOT_NULL(test, routes); + for_each_child_of_node(routes, route) { + KUNIT_EXPECT_EQ_MSG(test, of_device_is_available(route), enabled, "%pOF", route); + nr_routes++; + } + of_node_put(routes); + KUNIT_EXPECT_GT(test, nr_routes, 0); } /* @@ -1525,6 +1537,67 @@ static void __init gate_t6041_max_all_externals(struct kunit *test) gt_max_expect_display(test, BIT(0) | BIT(1) | BIT(2) | BIT(3)); } +/* + * dcpext3 takes its routes from the tree: with a route to a fourth Type-C port, + * as the J575c has, that route comes up with the chain too. + */ +static void __init gate_t6041_max_dt_routes(struct kunit *test) +{ + struct gate_test *t = test->priv; + struct device_node *route; + + route = of_changeset_create_node(&t->cs, gt_node(test, "/dcp@306e00000/typec-routes"), + "route@3"); + KUNIT_ASSERT_NOT_NULL(test, route); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_u32(&t->cs, route, "reg", 3), 0); + KUNIT_ASSERT_EQ(test, of_changeset_add_prop_string(&t->cs, route, "status", "disabled"), 0); + gt_max_fill(test, 3); + gt_max_run(test); + gt_max_expect_chain(test, 3, true); + KUNIT_EXPECT_TRUE(test, gt_okay(test, "/dcp@306e00000/typec-routes/route@3")); + gt_max_expect_display(test, BIT(3)); +} + +static void __init gt_max_expect_dt_routes_refused(struct kunit *test) +{ + const struct gate_staged *st = &t6041_max_stages[3]; + struct device_node *display = gt_node(test, "/display-subsystem"); + unsigned int n; + + gt_max_fill(test, 3); + gt_max_run(test); + for (n = 0; n < st->nr; n++) + KUNIT_EXPECT_FALSE_MSG(test, gt_okay(test, st->nodes[n]), "%s", st->nodes[n]); + gt_max_expect_display(test, 0); + + /* Direct application refuses it too and leaves the changeset untouched. */ + if (gt_okay(test, st->nodes[st->nr - 1])) + return; + KUNIT_EXPECT_EQ(test, t6041_max_apply(3, display), -ENODEV); + for (n = 0; n < st->nr; n++) + KUNIT_EXPECT_FALSE_MSG(test, gt_okay(test, st->nodes[n]), "%s", st->nodes[n]); + gt_max_expect_display(test, 0); +} + +/* A dt_routes stage whose typec-routes container is missing stays off whole. */ +static void __init gate_t6041_max_dt_routes_missing(struct kunit *test) +{ + gt_detach(test, "/dcp@306e00000/typec-routes/route@0"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@1"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@2"); + gt_detach(test, "/dcp@306e00000/typec-routes"); + gt_max_expect_dt_routes_refused(test); +} + +/* A dt_routes stage whose typec-routes container has no routes stays off whole. */ +static void __init gate_t6041_max_dt_routes_empty(struct kunit *test) +{ + gt_detach(test, "/dcp@306e00000/typec-routes/route@0"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@1"); + gt_detach(test, "/dcp@306e00000/typec-routes/route@2"); + gt_max_expect_dt_routes_refused(test); +} + /* The other processor's chain does not wait for one that was refused. */ static void __init gate_t6041_max_one_processor(struct kunit *test) { @@ -1646,6 +1719,9 @@ static struct kunit_case gate_t6041_max_cases[] __refdata = { KUNIT_CASE(gate_t6041_max_no_memory), KUNIT_CASE(gate_t6041_max_second_usbc), KUNIT_CASE(gate_t6041_max_all_externals), + KUNIT_CASE(gate_t6041_max_dt_routes), + KUNIT_CASE(gate_t6041_max_dt_routes_missing), + KUNIT_CASE(gate_t6041_max_dt_routes_empty), KUNIT_CASE(gate_t6041_max_one_processor), KUNIT_CASE(gate_t6041_max_partial_memory), KUNIT_CASE(gate_t6041_max_enabled_by_loader), diff --git a/drivers/soc/apple/display-gate.c b/drivers/soc/apple/display-gate.c index 9a326030f9eada..53c816e951523a 100644 --- a/drivers/soc/apple/display-gate.c +++ b/drivers/soc/apple/display-gate.c @@ -2384,8 +2384,27 @@ struct gate_staged { const char *dart; /* display DART of this stage */ const char *const *nodes; unsigned int nr; + /* + * If set, the processor (the last of @nodes) whose typec-routes children + * belong to the chain too: one per Type-C port of the board, as its + * device tree describes them. + */ + bool dt_routes; }; +/* The typec-routes node of the processor that ends @st, or NULL. */ +static struct device_node *staged_routes(const struct gate_staged *st) +{ + struct device_node *dcp, *routes; + + if (!st->dt_routes) + return NULL; + dcp = of_find_node_by_path(st->nodes[st->nr - 1]); + routes = dcp ? of_get_child_by_name(dcp, "typec-routes") : NULL; + of_node_put(dcp); + return routes; +} + static const char *const t6041_hdmi_nodes[] = { /* ATC3 power, PMP DISPEXT0 request, DISPEXT0, AOP pins, PHY, crossbar, DARTs, mailbox, dcpext0 */ "/power-management@502800000/power-controller@408", @@ -2580,6 +2599,32 @@ static bool staged_ready(const struct gate_staged *st) } of_node_put(np); } + if (st->dt_routes) { + struct device_node *route; + unsigned int nr_routes = 0; + + np = staged_routes(st); + if (!np) { + staged_err("%s/typec-routes: no such node, nothing enabled\n", + st->nodes[st->nr - 1]); + return false; + } + for_each_child_of_node(np, route) { + if (of_device_is_available(route)) { + staged_err("%pOF: already enabled, nothing changed\n", route); + of_node_put(route); + of_node_put(np); + return false; + } + nr_routes++; + } + of_node_put(np); + if (!nr_routes) { + staged_err("%s/typec-routes: no routes, nothing enabled\n", + st->nodes[st->nr - 1]); + return false; + } + } return true; } @@ -3274,14 +3319,15 @@ static const char *const t6041_max_usbc2_nodes[] = { "/dcp@606e00000", }; -/* The third USB-C processor of the J614c/J616c, dcpext3, as dcpext2's chain. */ +/* + * The third USB-C processor of the M4 Max boards, dcpext3, as dcpext2's chain. + * Its routes are the ones the device tree gives it, one per Type-C port: three + * on the J614c/J616c, four on the J575c. + */ static const char *const t6041_max_usbc3_nodes[] = { "/iommu@306340000", "/iommu@306300000", "/mailbox@306e08000", - "/dcp@306e00000/typec-routes/route@0", - "/dcp@306e00000/typec-routes/route@1", - "/dcp@306e00000/typec-routes/route@2", "/dcp@306e00000", }; @@ -3289,7 +3335,7 @@ static const struct gate_staged t6041_max_stages[] = { { "/iommu@3a2300000", t6041_max_hdmi_nodes, ARRAY_SIZE(t6041_max_hdmi_nodes) }, { "/iommu@602300000", t6041_max_usbc_nodes, ARRAY_SIZE(t6041_max_usbc_nodes) }, { "/iommu@606300000", t6041_max_usbc2_nodes, ARRAY_SIZE(t6041_max_usbc2_nodes) }, - { "/iommu@306300000", t6041_max_usbc3_nodes, ARRAY_SIZE(t6041_max_usbc3_nodes) }, + { "/iommu@306300000", t6041_max_usbc3_nodes, ARRAY_SIZE(t6041_max_usbc3_nodes), true }, }; /* @@ -3394,6 +3440,32 @@ static bool __init t6041_max_needs_off_domain(const struct gate_staged *st, stru return off; } +/* Enable each typec-routes child of @st's processor in @cs, if @st takes its routes from the DT. */ +static int __init t6041_max_enable_routes(struct of_changeset *cs, const struct gate_staged *st) +{ + struct device_node *routes, *route; + unsigned int nr_routes = 0; + int ret = 0; + + if (!st->dt_routes) + return 0; + routes = staged_routes(st); + if (!routes) + return -ENODEV; + for_each_child_of_node(routes, route) { + ret = of_changeset_update_prop_string(cs, route, "status", "okay"); + if (ret) { + of_node_put(route); + break; + } + nr_routes++; + } + of_node_put(routes); + if (!ret && !nr_routes) + return -ENODEV; + return ret; +} + /* * Enable every node of stage @i and put its display DART into the display subsystem's iommus. * The in-tree trees give the chains no DISPEXT power domain: they are on as iBoot left them. A @@ -3415,6 +3487,11 @@ static int __init t6041_max_apply(unsigned int i, struct device_node *display) ret = np ? gate_iommus_append(cs, display, np) : -ENODEV; of_node_put(np); for (n = 0; !ret && n < st->nr; n++) { + /* The routes go in just before their processor, the last node. */ + if (n == st->nr - 1) + ret = t6041_max_enable_routes(cs, st); + if (ret) + break; np = of_find_node_by_path(st->nodes[n]); ret = np ? of_changeset_update_prop_string(cs, np, "status", "okay") : -ENODEV; if (!ret && t6041_max_needs_off_domain(st, np)) From f0ea546fae42ed55768a4365418acca9056696f1 Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Thu, 26 Nov 2026 14:10:37 -0300 Subject: [PATCH 1497/1514] arm64: dts: apple: t6041-j575c: describe dcpext3 The J575c ADT has a fourth external display processor, dcpext3, at the J614c/J616c's address, and iBoot preloads and starts it here too (iop-dcpext3-nub pre-loaded 1, running 1). The tree did not describe it, so Linux left it running as iBoot did, unbound. Describe it as t6041-j616c-usbc-dcpext3.dtsi does, with a route to the fourth back Type-C port added, as the J575c's dcpext1 and dcpext2. The address, interrupts, external index, bandwidth agent slot and crossbar endpoint match this Mac's ADT. Everything is disabled: aura's t6041_exts fills the firmware memory, and the display gate enables the chain. dcpext3 can then drive a USB-C display on any back port, as dcpext1 and dcpext2 do, and Linux owns the processor instead of leaving it running unbound through a suspend. Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- .../dts/apple/t6041-j575c-usbc-dcpext3.dtsi | 220 ++++++++++++++++++ arch/arm64/boot/dts/apple/t6041-j575c.dts | 1 + 2 files changed, 221 insertions(+) create mode 100644 arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi diff --git a/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi b/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi new file mode 100644 index 00000000000000..679fc57246ebcd --- /dev/null +++ b/arch/arm64/boot/dts/apple/t6041-j575c-usbc-dcpext3.dtsi @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-2.0+ OR MIT +/* + * A third USB-C DisplayPort processor on the J575c: dcpext3, with a route to + * each of the four back Type-C ports (typec0-3), next to dcpext1 and dcpext2. + * + * The node is the J614c/J616c's (t6041-j616c-usbc-dcpext3.dtsi) with the + * fourth route added: the J575c ADT has dcpext3 at the same address + * (/arm-io/dcpext3 0x106e00000 + 0x2_0000_0000, interrupts +0x48, + * external-index 4, bwr-agent DISP_EXT3 slot 6, dp-switch-ufp-endpoint 3) + * and iBoot preloads and starts it here too (iop-dcpext3-nub pre-loaded 1, + * running 1). As dcpext1 and dcpext2, no PMP and no DISPEXT3 power domain is + * described: the chain runs as iBoot left it powered. + * + * Everything here is disabled. The boot loader fills dcpext3's firmware + * memory from this boot's ADT (aura t6041_exts) and the display gate enables + * the chain once it has. + */ + +/ { + aliases { + dcpext3 = &dcpext3; + }; + + reserved-memory { + dcpext3_text: dcpext3-text { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_data: dcpext3-data { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + + dcpext3_heap: dcpext3-heap { + compatible = "apple,asc-mem"; + reg = <0x0 0x0 0x0 0x4000>; + no-map; + status = "disabled"; + }; + }; + + dcpext3: dcp@306e00000 { + compatible = "apple,t6041-dcpext", "apple,dcpext"; + reg = <0x3 0x06e00000 0x0 0x4000>, + <0x3 0x04000000 0x0 0x4000000>, + <0x3 0x06240000 0x0 0x10000>, + <0x3 0x063a8000 0x0 0x4000>, + <0x3 0x06800000 0x0 0x800000>; + reg-names = "coproc", "disp-0", "disp-1", "disp-2", "disp-3"; + mboxes = <&dcpext3_mbox>; + mbox-names = "mbox"; + iommus = <&dcpext3_dart 23>; + /* + * PMGR bandwidth agent scratch: the bwr-agent the ADT dispext3 + * function-bw_req_interrupt0 (0x4f) names: ADT + * pmgr bwr-agent DISP_EXT3, slot 6, so 0x20000 + 6 * 0x4000. + */ + apple,bw-scratch = <&pmgr_dcp 0 4 0x38000>; + /* ADT iop-dcpext3-nub external-index */ + apple,dcp-endpoint = <4>; + /* as dcpext0/1: without it apple-dcp's probe fails with -EINVAL */ + apple,iomfb-surfaces = <1 1 0 0>; + apple,connector-type = "USB-C"; + phys = <&atcphy0 PHY_TYPE_DP>, <&atcphy1 PHY_TYPE_DP>, + <&atcphy2 PHY_TYPE_DP>, <&atcphy3 PHY_TYPE_DP>; + phy-names = "typec0", "typec1", "typec2", "typec3"; + mux-controls = <&atcphy0_xbar 0>, <&atcphy1_xbar 0>, + <&atcphy2_xbar 0>, <&atcphy3_xbar 0>; + mux-control-names = "typec0", "typec1", "typec2", "typec3"; + /* + * indexed by route; crossbar state = 2 * dp-switch-ufp-endpoint + * (3) + port (0) + */ + apple,typec-dptx-phys = <0 1 2 3>; + apple,typec-mux-indices = <6 6 6 6>; + memory-region = <&dcpext3_text>, <&dcpext3_data>, <&dcpext3_heap>; + memory-region-names = "text", "data", "heap"; + status = "disabled"; + + dispext3_piodma: piodma { + iommus = <&dispext3_dart 16>; + }; + + typec-routes { + #address-cells = <1>; + #size-cells = <0>; + + route@0 { + reg = <0>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec0: endpoint { + remote-endpoint = <&typec0_dcpext3>; + }; + }; + }; + + route@1 { + reg = <1>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec1: endpoint { + remote-endpoint = <&typec1_dcpext3>; + }; + }; + }; + + route@2 { + reg = <2>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec2: endpoint { + remote-endpoint = <&typec2_dcpext3>; + }; + }; + }; + + route@3 { + reg = <3>; + mode-switch; + status = "disabled"; + + port { + dcpext3_typec3: endpoint { + remote-endpoint = <&typec3_dcpext3>; + }; + }; + }; + }; + }; + + dcpext3_mbox: mailbox@306e08000 { + compatible = "apple,t6041-asc-mailbox", "apple,asc-mailbox-v4"; + reg = <0x3 0x06e08000 0x0 0x4000>; + interrupt-parent = <&aic>; + interrupts = , + , + , + ; + interrupt-names = "send-empty", "send-not-empty", + "recv-empty", "recv-not-empty"; + #mbox-cells = <0>; + status = "disabled"; + }; + + dispext3_dart: iommu@306300000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06300000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; + + dcpext3_dart: iommu@306340000 { + compatible = "apple,t6041-dart", "apple,t8110-dart"; + reg = <0x3 0x06340000 0x0 0xc000>; + #iommu-cells = <1>; + apple,dma-range = <0x100 0x0 0x10 0x0>; + interrupt-parent = <&aic>; + interrupts = ; + status = "disabled"; + }; +}; + +&typec0 { + ports { + port@3 { + typec0_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec0>; + }; + }; + }; +}; + +&typec1 { + ports { + port@3 { + typec1_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec1>; + }; + }; + }; +}; + +&typec2 { + ports { + port@3 { + typec2_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec2>; + }; + }; + }; +}; + +&typec3 { + ports { + port@3 { + typec3_dcpext3: endpoint@2 { + reg = <2>; + remote-endpoint = <&dcpext3_typec3>; + }; + }; + }; +}; diff --git a/arch/arm64/boot/dts/apple/t6041-j575c.dts b/arch/arm64/boot/dts/apple/t6041-j575c.dts index 235d7a2ab3af45..bce7e4962eec32 100644 --- a/arch/arm64/boot/dts/apple/t6041-j575c.dts +++ b/arch/arm64/boot/dts/apple/t6041-j575c.dts @@ -2085,6 +2085,7 @@ #include "t6041-j575c-usb3.dtsi" #include "t6041-j575c-usbc.dtsi" #include "t6041-j575c-usbc-dcpext2.dtsi" +#include "t6041-j575c-usbc-dcpext3.dtsi" #include "t6041-j575c-hdmi.dtsi" /* Not described: the SEP (no Touch ID sensor). */ From 4b364416f776970b3387393500da28690effa514 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 04:23:20 +1100 Subject: [PATCH 1498/1514] accel/ane: h16: expose ane_stats and wedged on the H16 and H17 node On the firmware platforms (H16 T6041, H17 T8140) ane_t6021 hands the device to the shared H16/H17 accel node and hides its own ane_stats, wedged and reset attributes, so these devices expose no busy counters and no health state at all: a quarantined engine and an idle one look the same from userspace. The session already tracks both, but only in debugfs (and the execute statistics there reset on write). Give the session the producer counters the other ANE drivers use (ane_stats_begin()/ane_stats_complete(), one ring slot, no timeline). A request counts from its first firmware traffic until it ends either way, so a failed EXECUTE counts and a refusal before any traffic (a quarantined engine, invalid buffers, no arena room) does not; a client retrying on a wedged engine cannot inflate the job count. Pipelined requests fold into one busy period as on ane_t6021. The node adds a devm group with ane_stats (same format as ane.ko and ane_t6021) and wedged (1 while the session is quarantined) to the ANE device. Both reads are lock-free, so a hung request cannot block them. A parked or sleeping engine reads wedged 0. If the group cannot be added the node still registers, with a warning. Signed-off-by: Ryan Murray --- .../ABI/testing/sysfs-class-accel-ane | 40 ++++++++++-- drivers/accel/ane/ane_h16_accel.c | 62 +++++++++++++++++++ drivers/accel/ane/ane_h16_accel_test.c | 39 ++++++++++++ drivers/accel/ane/ane_h16_program.c | 10 +++ drivers/accel/ane/ane_h16_program.h | 9 +++ drivers/accel/ane/ane_h16_program_test.c | 37 +++++++++++ 6 files changed, 192 insertions(+), 5 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-class-accel-ane b/Documentation/ABI/testing/sysfs-class-accel-ane index af17b343172387..846b7f2e978a51 100644 --- a/Documentation/ABI/testing/sysfs-class-accel-ane +++ b/Documentation/ABI/testing/sysfs-class-accel-ane @@ -35,14 +35,44 @@ Description: work and are not counted. A submission that completes with an error still completes its begin/complete pair, so the - counter stays balanced. + counter stays balanced. On the H16 and H17 node + (ane_t6021 with a firmware platform, e.g. T6041, + T8140) every EXECUTE that reached the firmware + counts, failed ones included; a request refused + before any firmware traffic (quarantined engine, + invalid buffers) does not. Neither counter resets while the device is bound. + On the H16 and H17 node, resetting the debugfs + execute statistics leaves them alone. - The file exists only when the module parameter - ane.stats / ane_t6021.stats (default 1) is set at - probe. With stats=0 the driver creates no stats files - and the submission hot path skips the counters. + On ane.ko and the H13/H14 ane_t6021 path the file + exists only when the module parameter ane.stats / + ane_t6021.stats (default 1) is set at probe. With + stats=0 the driver creates no stats files and the + submission hot path skips the counters. The H16 and + H17 node creates it with the node, without a + parameter. Users: performance samplers that compute engine utilization and job rate from the two counters. + +What: /sys/class/accel/accel/device/wedged +Date: November 2026 +KernelVersion: 7.3 +Contact: Ryan Murray +Description: + "1" while the Apple Neural Engine refuses requests + until it recovers, "0" otherwise. Mode 0444; the read + takes no lock, so a hung request cannot block it. + + On the H16 and H17 node (ane_t6021 with a firmware + platform, e.g. T6041, T8140) it is 1 while the + firmware session is quarantined: a request hung or + ended with an uncertain outcome, and requests fail + with EIO until a runtime recovery or a system sleep + proves the old firmware gone. A parked or sleeping + engine reads 0: its next request brings it up. + +Users: health checks (aurora-diag) that tell a wedged engine + from an idle one. diff --git a/drivers/accel/ane/ane_h16_accel.c b/drivers/accel/ane/ane_h16_accel.c index 9a2d2526d2944a..186fee5210bc3d 100644 --- a/drivers/accel/ane/ane_h16_accel.c +++ b/drivers/accel/ane/ane_h16_accel.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -618,8 +619,65 @@ static const struct drm_driver ane_h16_drm_driver = { .desc = "Apple Neural Engine (H16 and later)", }; +/* + * ane_stats and wedged on the ANE device, as ane.ko and ane_t6021 have them + * (Documentation/ABI/testing/sysfs-class-accel-ane), for the node's lifetime. + * Both are lock-free reads, so a hung request cannot block them. + */ +struct ane_h16_sysfs { + struct ane_h16_session *session; + struct device_attribute stats, wedged; + struct attribute *attrs[3]; + struct attribute_group group; +}; + +static ssize_t ane_h16_stats_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct ane_h16_sysfs *sys = container_of(attr, struct ane_h16_sysfs, stats); + + return ane_stats_emit(buf, &sys->session->sysfs_ctrs); +} + +/* + * 1 while the session is quarantined: a request hung or failed with an + * uncertain outcome, and requests are refused until a recovery or a system + * sleep proves the old firmware gone. A parked or sleeping engine is not + * wedged: the next request brings it up. + */ +static ssize_t ane_h16_wedged_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct ane_h16_sysfs *sys = container_of(attr, struct ane_h16_sysfs, wedged); + + return sysfs_emit(buf, "%d\n", READ_ONCE(sys->session->quarantined)); +} + +static struct ane_h16_sysfs *ane_h16_sysfs_add(struct device *dev, + struct ane_h16_session *session) +{ + struct ane_h16_sysfs *sys = devm_kzalloc(dev, sizeof(*sys), GFP_KERNEL); + int ret; + + if (!sys) + return ERR_PTR(-ENOMEM); + sys->session = session; + sysfs_attr_init(&sys->stats.attr); + sys->stats.attr.name = "ane_stats"; + sys->stats.attr.mode = 0444; + sys->stats.show = ane_h16_stats_show; + sysfs_attr_init(&sys->wedged.attr); + sys->wedged.attr.name = "wedged"; + sys->wedged.attr.mode = 0444; + sys->wedged.show = ane_h16_wedged_show; + sys->attrs[0] = &sys->stats.attr; + sys->attrs[1] = &sys->wedged.attr; + sys->group.attrs = sys->attrs; + ret = devm_device_add_group(dev, &sys->group); + return ret ? ERR_PTR(ret) : sys; +} + int ane_h16_accel_register(struct device *dev, struct ane_h16_session *session) { + struct ane_h16_sysfs *sys; struct ane_h16_accel *a; int ret; @@ -635,6 +693,10 @@ int ane_h16_accel_register(struct device *dev, struct ane_h16_session *session) ret = drm_dev_register(&a->drm, 0); if (ret) return ret; + /* The node works without them: report and go on. */ + sys = ane_h16_sysfs_add(dev, session); + if (IS_ERR(sys)) + drm_warn(&a->drm, "no ane_stats or wedged in sysfs (%pe)\n", sys); drm_info(&a->drm, "H%u accel node ready (ABI 3, %s)\n", session->transport->soc->chip_family, ane_fw_transport_switch_safe(session->transport) ? diff --git a/drivers/accel/ane/ane_h16_accel_test.c b/drivers/accel/ane/ane_h16_accel_test.c index 7e6bd043a315b1..db2bf056dbf657 100644 --- a/drivers/accel/ane/ane_h16_accel_test.c +++ b/drivers/accel/ane/ane_h16_accel_test.c @@ -235,11 +235,50 @@ static void ane_h16_accel_user_bounce_test(struct kunit *test) KUNIT_EXPECT_NULL(test, u.pages); } +/* + * ane_stats and wedged land on the device with the format of the other ANE + * drivers and follow the session: its counters and its quarantine. + */ +static void ane_h16_accel_sysfs_test(struct kunit *test) +{ + struct device *dev = drm_kunit_helper_alloc_device(test); + struct ane_h16_session *s = kunit_kzalloc(test, sizeof(*s), GFP_KERNEL); + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + struct kernfs_node *kn; + struct ane_h16_sysfs *sys; + u64 ticket; + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_NOT_NULL(test, s); + KUNIT_ASSERT_NOT_NULL(test, buf); + ane_stats_counters_init(&s->sysfs_ctrs, &s->sysfs_ring, 0); + s->sysfs_ring.slots = &s->sysfs_slot; + sys = ane_h16_sysfs_add(dev, s); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, sys); + kn = sysfs_get_dirent(dev->kobj.sd, "ane_stats"); + KUNIT_EXPECT_NOT_NULL(test, kn); + sysfs_put(kn); + kn = sysfs_get_dirent(dev->kobj.sd, "wedged"); + KUNIT_EXPECT_NOT_NULL(test, kn); + sysfs_put(kn); + + ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, 1000, 1); + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, 3000, -ETIMEDOUT, 0); + KUNIT_EXPECT_GT(test, ane_h16_stats_show(dev, &sys->stats, buf), 0); + KUNIT_EXPECT_STREQ(test, buf, "busy_ns 2000\njobs 1\n"); + KUNIT_EXPECT_EQ(test, ane_h16_wedged_show(dev, &sys->wedged, buf), 2); + KUNIT_EXPECT_STREQ(test, buf, "0\n"); + s->quarantined = true; + ane_h16_wedged_show(dev, &sys->wedged, buf); + KUNIT_EXPECT_STREQ(test, buf, "1\n"); +} + static struct kunit_case ane_h16_accel_cases[] = { KUNIT_CASE(ane_h16_accel_fops_test), KUNIT_CASE(ane_h16_accel_open_test), KUNIT_CASE(ane_h16_accel_user_pages_test), KUNIT_CASE(ane_h16_accel_user_bounce_test), + KUNIT_CASE(ane_h16_accel_sysfs_test), {} }; diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index 4a54997f470510..ec01def937cdd8 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -649,6 +649,8 @@ static int h16_session_init(struct ane_h16_session *s, struct ane_fw_transport * INIT_LIST_HEAD(&s->programs); INIT_LIST_HEAD(&s->held); spin_lock_init(&s->stats_lock); + ane_stats_counters_init(&s->sysfs_ctrs, &s->sysfs_ring, 0); + s->sysfs_ring.slots = &s->sysfs_slot; INIT_DELAYED_WORK(&s->gate_work, h16_gate_work); spin_lock_init(&s->export_lock); INIT_LIST_HEAD(&s->exports_done); @@ -1651,6 +1653,7 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) unsigned int i; u64 deadline, polls, t0, gate_open, t1 = 0, t2 = 0, t3, end; u64 entry = h16_now(s); + u64 ticket; int ret; if (!s || !p || p->session != s) @@ -1694,6 +1697,11 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) /* Inputs and poisoned outputs must reach memory before any doorbell. */ s->transport->ops->write_barrier(s->transport->ctx); polls = s->transport->polls; + /* + * A request counts in ane_stats from its first firmware traffic until + * it ends either way; a refusal before this point reached nothing. + */ + ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, ktime_get_ns(), 1); trace->step = H16_STEP_GATE_OPEN; t0 = h16_now(s); if (!s->gate_held) { @@ -1772,8 +1780,10 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) x->polls = s->transport->polls - polls; kfree(command); x->ns[ANE_H16_T_FINISH] = h16_now(s) - end; + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), 0, 0); return 0; fail: + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), ret, 0); s->ops->log(s->ctx, "EXECUTE failed", (u64)-ret, request->key.uuid); /* * Step 1 opening gate, 2 channel-7 ack, 3 report wait, 4 closing gate. diff --git a/drivers/accel/ane/ane_h16_program.h b/drivers/accel/ane/ane_h16_program.h index be8aae41e34d5f..914f3a8d45bdf7 100644 --- a/drivers/accel/ane/ane_h16_program.h +++ b/drivers/accel/ane/ane_h16_program.h @@ -11,6 +11,7 @@ #include "ane_fw_transport.h" #include "ane_h16_load.h" #include "ane_h16_pending.h" +#include "ane_stats.h" /* * Program lifecycle for one H16 firmware session: LOAD_PROGRAM, CREATE_PROCESS, @@ -414,6 +415,14 @@ struct ane_h16_session { /* Accounted EXECUTEs; the lock lets a reader snapshot them. */ spinlock_t stats_lock; struct ane_h16_exec_stats stats; + /* + * The sysfs ane_stats counters: every request published to the + * firmware, failed ones included, and the union of their busy time. + * Unlike stats, they never reset. One ring slot: no timeline is kept. + */ + struct ane_stats_counters sysfs_ctrs; + struct ane_stats_ring sysfs_ring; + struct ane_stats_ring_entry sysfs_slot; /* Exports whose last mapping is gone, returned by export_work. */ spinlock_t export_lock; struct list_head exports_done; diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index f2b778126695fb..d27c9be3ab1cd9 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -1501,6 +1501,42 @@ static void program_stall_trace_test(struct kunit *test) KUNIT_EXPECT_EQ(test, f->fail_other, 2); } +/* + * The sysfs ane_stats counters take every request that reached the firmware, + * a failed one too, but not one refused before it: a client retrying on a + * quarantined engine does not inflate them. Resetting the debugfs statistics + * leaves them alone, and nothing stays in flight after either outcome. + */ +static void program_sysfs_stats_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + u64 busy; + + KUNIT_ASSERT_NOT_NULL(test, f); + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 0LL); + KUNIT_EXPECT_EQ(test, ane_stats_snapshot(&f->s.sysfs_ctrs), 0ULL); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); + busy = ane_stats_snapshot(&f->s.sysfs_ctrs); + ane_h16_session_stats(&f->s, NULL, true); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + + f->mode = FW_REPORT_STALL; + KUNIT_EXPECT_EQ(test, ane_h16_session_execute(&f->s, p), -ETIMEDOUT); + KUNIT_EXPECT_TRUE(test, f->s.quarantined); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 2LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); + KUNIT_EXPECT_GE(test, ane_stats_snapshot(&f->s.sysfs_ctrs), busy); + + f->mode = FW_OK; + KUNIT_EXPECT_LT(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 2LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); +} + /* The phases of one EXECUTE add up, and only successful ones are accounted. */ static void program_timing_test(struct kunit *test) { @@ -4241,6 +4277,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_bad_report_test), KUNIT_CASE(program_stall_trace_test), KUNIT_CASE(program_timing_test), + KUNIT_CASE(program_sysfs_stats_test), KUNIT_CASE(program_fwlog_line_test), KUNIT_CASE(program_shared_tag_test), KUNIT_CASE(program_pool_test), From 8db2be90ebef91d7f46c0e06ab0e15223bc3061c Mon Sep 17 00:00:00 2001 From: Roberto Dantas <7robertodantas@gmail.com> Date: Fri, 27 Nov 2026 14:30:24 -0300 Subject: [PATCH 1499/1514] iommu/apple-dart: expand display keep table for five T6041 display processors T6041 carries five display processors (internal DCP plus four external DCPs), each backed by two display DARTs (DCP and display), requiring ten saved slots in apple_dart_display_keep() instead of two. Expand the static keep table from 2 to 10 entries using ARRAY_SIZE(keep), and add a KUnit test covering save, overflow (-ENOSPC on the 11th DART), restore, and error paths (-ENODEV, -ENOENT). Signed-off-by: Roberto Dantas <7robertodantas@gmail.com> --- drivers/iommu/apple-dart-test.c | 61 +++++++++++++++++++++++++++++++++ drivers/iommu/apple-dart.c | 7 ++-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/drivers/iommu/apple-dart-test.c b/drivers/iommu/apple-dart-test.c index a7ae726f341a6f..9ddfd0c8093b9c 100644 --- a/drivers/iommu/apple-dart-test.c +++ b/drivers/iommu/apple-dart-test.c @@ -1639,6 +1639,66 @@ static void apple_dart_test_fw_mirror_prot(struct kunit *test) pm_runtime_disable(dart->dev); } +static struct apple_dart *apple_dart_test_keep_dart(struct kunit *test, const char *name) +{ + struct apple_dart *dart; + + dart = kunit_kzalloc(test, sizeof(*dart), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart); + dart->dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dart->dev); + dev_set_drvdata(dart->dev, dart); + dart->regs = (__force void __iomem *)kunit_kzalloc(test, SZ_16K, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, dart->regs); + dart->hw = &apple_dart_hw_t8110; + dart->num_streams = 2; + return dart; +} + +static void apple_dart_test_display_keep(struct kunit *test) +{ + struct device *no_data; + struct apple_dart *unsaved; + struct apple_dart *darts[11]; + char name[32]; + unsigned int i; + + no_data = kunit_device_register(test, "apple-dart-keep-none"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, no_data); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(no_data, BIT(1), true), -ENODEV); + + unsaved = apple_dart_test_keep_dart(test, "apple-dart-keep-unsaved"); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(unsaved->dev, BIT(1), false), -ENOENT); + + for (i = 0; i < ARRAY_SIZE(darts); i++) { + snprintf(name, sizeof(name), "apple-dart-keep-%u", i); + darts[i] = apple_dart_test_keep_dart(test, name); + writel(DART_T8110_TCR_TRANSLATE_ENABLE, + darts[i]->regs + DART_TCR(darts[i], 1)); + writel(darts[i]->hw->ttbr_valid | (0x1000 + i), + darts[i]->regs + DART_TTBR(darts[i], 1, 0)); + } + + /* All 10 display DARTs (5 display processors x 2 DARTs) fit in keep[]. */ + for (i = 0; i < 10; i++) + KUNIT_ASSERT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), true), 0); + + /* An 11th DART exceeds the table. */ + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[10]->dev, BIT(1), true), -ENOSPC); + + /* Clobber saved words and confirm every slot restores them cleanly. */ + for (i = 0; i < 10; i++) { + writel(0, darts[i]->regs + DART_TCR(darts[i], 1)); + writel(0, darts[i]->regs + DART_TTBR(darts[i], 1, 0)); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), false), 2); + KUNIT_EXPECT_EQ(test, readl(darts[i]->regs + DART_TCR(darts[i], 1)), + DART_T8110_TCR_TRANSLATE_ENABLE); + KUNIT_EXPECT_EQ(test, readl(darts[i]->regs + DART_TTBR(darts[i], 1, 0)), + darts[i]->hw->ttbr_valid | (0x1000 + i)); + KUNIT_EXPECT_EQ(test, apple_dart_display_keep(darts[i]->dev, BIT(1), false), 0); + } +} + static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_strict_engines), KUNIT_CASE(apple_dart_test_topology), @@ -1653,6 +1713,7 @@ static struct kunit_case apple_dart_test_cases[] = { KUNIT_CASE(apple_dart_test_firmware_roots), KUNIT_CASE(apple_dart_test_t8132_fw_mirror_selection), KUNIT_CASE(apple_dart_test_fw_mirror_prot), + KUNIT_CASE(apple_dart_test_display_keep), KUNIT_CASE(apple_dart_test_unmap_flush_after_publish_failure), KUNIT_CASE(apple_dart_test_gated_commands), KUNIT_CASE(apple_dart_test_resume_commands_failure), diff --git a/drivers/iommu/apple-dart.c b/drivers/iommu/apple-dart.c index ae56c05d347c1b..98aeeb6ac5d796 100644 --- a/drivers/iommu/apple-dart.c +++ b/drivers/iommu/apple-dart.c @@ -8680,16 +8680,17 @@ static int apple_dart_t8020_display_streams(struct apple_dart *dart, u32 streams */ int apple_dart_display_keep(struct device *dev, u32 streams, bool save) { - static struct { struct apple_dart *dart; u32 tcr[32]; u32 ttbr[32][4]; } keep[2]; + /* Two DARTs (DCP and display) for each of the T6041's five display processors. */ + static struct { struct apple_dart *dart; u32 tcr[32]; u32 ttbr[32][4]; } keep[10]; struct apple_dart *dart = dev_get_drvdata(dev); unsigned long bits = streams; unsigned int sid, idx, k, n = 0; if (!dart) return -ENODEV; - for (k = 0; k < 2 && keep[k].dart && keep[k].dart != dart; k++) + for (k = 0; k < ARRAY_SIZE(keep) && keep[k].dart && keep[k].dart != dart; k++) ; - if (k == 2) + if (k == ARRAY_SIZE(keep)) return -ENOSPC; if (!save && keep[k].dart != dart) return -ENOENT; From 88776f45d8f283dffdff98169a7bc03e1cdc07c1 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 27 Nov 2026 12:51:11 -0500 Subject: [PATCH 1500/1514] accel/ane: h16: default channel counts to 16 and admit 0x5104 dependency bits The H16/H17 task-stream DMA validator (ane_hx_dma_defaults) initialized InChannels (0x0c) and OutChannels (0x1c) to 0, whereas the H16/H17 hardware reset value is 16 and compilers omit writes of 0x0c and 0x1c when a task uses 16 channels. Programs with omitted 16-channel counts were therefore rejected with -ENOEXEC. In addition, ane_hx_dma_modelled() omitted TileDMADst +0x04 (0x5104), whose bits 30:24 carry destination task-dependency metadata on scratch-reusing tasks without changing the DMA address. Default 0x0c and 0x1c to 16 in ane_hx_dma_defaults() (explicit writes of 0 still overwrite the default and stay refused), admit 0x5104 in ane_hx_dma_modelled() with bits outside 0x7f000000 rejected in ane_hx_dma_image_check(), and add a KUnit regression test covering both. Signed-off-by: Satya Benson --- drivers/accel/ane/ane_h16_tasks.h | 10 ++++-- drivers/accel/ane/ane_h16_tasks_test.c | 47 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/drivers/accel/ane/ane_h16_tasks.h b/drivers/accel/ane/ane_h16_tasks.h index f4560e6eb64ff7..702e6f88893c3b 100644 --- a/drivers/accel/ane/ane_h16_tasks.h +++ b/drivers/accel/ane/ane_h16_tasks.h @@ -217,9 +217,9 @@ static inline bool ane_hx_dma_base(u32 addr) static inline bool ane_hx_dma_modelled(u32 addr) { return (addr >= 0x4d00 && addr <= 0x4d3c) || addr == 0x4d68 || addr == 0x4d6c || - addr == 0x5100 || (addr >= 0x5108 && addr <= 0x511c) || addr == 0x5138 || - addr == 0x5500 || addr == 0x5504 || (addr >= 0x5510 && addr <= 0x55dc) || - (addr >= 0x5610 && addr <= 0x561c); + addr == 0x5100 || addr == 0x5104 || (addr >= 0x5108 && addr <= 0x511c) || + addr == 0x5138 || addr == 0x5500 || addr == 0x5504 || + (addr >= 0x5510 && addr <= 0x55dc) || (addr >= 0x5610 && addr <= 0x561c); } /* Source 1, source 2 and destination DMA configuration and coefficient lanes. */ @@ -361,6 +361,9 @@ static inline void ane_hx_dma_defaults(struct ane_hx_dma_state *st) unsigned int i; memset(st, 0, sizeof(*st)); + /* Input and output channel counts (0x0c, 0x1c) reset to 16 on H16/H17. */ + st->img[ane_hx_dma_index(0x0c)] = 16; + st->img[ane_hx_dma_index(0x1c)] = 16; st->img[ane_hx_dma_index(0x40)] = 3; for (i = 0; i < 16; i++) st->img[ane_hx_dma_index(0x55a0 + 4 * i)] = 64; @@ -473,6 +476,7 @@ static inline int ane_hx_dma_image_check(const u32 *img) } if ((img[ane_hx_dma_index(0x4d08)] | img[ane_hx_dma_index(0x4d0c)]) & ~0xffU || (img[ane_hx_dma_index(0x4d68)] | img[ane_hx_dma_index(0x4d6c)]) & ~0x0f003031U || + img[ane_hx_dma_index(0x5104)] & ~0x7f000000U || img[ane_hx_dma_index(0x5138)] & ~0x0f303031U || (img[ane_hx_dma_index(0x40)] & 7) > 5) return -ENOEXEC; diff --git a/drivers/accel/ane/ane_h16_tasks_test.c b/drivers/accel/ane/ane_h16_tasks_test.c index 5ca9a0d4f44c55..787f846e6fcd11 100644 --- a/drivers/accel/ane/ane_h16_tasks_test.c +++ b/drivers/accel/ane/ane_h16_tasks_test.c @@ -792,6 +792,52 @@ static void ane_hx_dma_h15_test(struct kunit *test) KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 0, bound), -ENOEXEC); } +/* + * Input and output channel counts (0x0c, 0x1c) reset to 16 on H16/H17, so + * programs omit them for 16-channel tensors while an explicit 0 is still + * refused. Destination word 0x5104 carries dependency bits in 30:24 without + * shifting the DMA address; bits outside 0x7f000000 remain refused. + */ +static void ane_hx_dma_channel_default_and_dst_dep_test(struct kunit *test) +{ + /* 16 channels interleaved 8 -> 2 planes of 0x400 (0x400 + 16*2*8 = 0x500). */ + static const u32 omitted_ch[] = { + DMA_REC(0x4, 2), 16, 1, + DMA_REC(0x14, 2), 16, 1, + DMA_REC(0x4d18, 2), 0x100, 0x400, DMA_REC(0x4d68, 1), 0x8002031, + DMA_REC(0x5110, 2), 0x100, 0x400, DMA_REC(0x5138, 1), 0x8302031, + DMA_RELOC(0x4d10, 6), 0, 0, + DMA_RELOC(0x5108, 7), 0, 0, + DMA_REC(0x4d00, 1), 0x20010041, + DMA_REC(0x5100, 2), 0x10100e1, 0x01000000, + }; + u64 bound[ANE_HX_DMA_SLOTS] = { [6] = 0x500, [7] = 0x500 }; + u8 text[512]; + size_t size; + + memset(text, 0, sizeof(text)); + put_unaligned_le32(1, text); + size = dma_append(text, 16, 0, 0, 0, 0, omitted_ch, ARRAY_SIZE(omitted_ch)); + KUNIT_ASSERT_EQ(test, ane_h16_task_stream_validate(text, size, 1), 0); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + + /* One 64-byte line short of the 16-channel (2-plane) extent is refused. */ + bound[6] = 0x4c0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + bound[6] = 0x500; + bound[7] = 0x4c0; + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + bound[7] = 0x500; + + /* 0x5104 bits outside 30:24 are refused. */ + put_unaligned_le32(0x24000000, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), 0); + put_unaligned_le32(0x01000001, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); + put_unaligned_le32(0x80000000, text + 16 + 9 * 4 + (ARRAY_SIZE(omitted_ch) - 1) * 4); + KUNIT_EXPECT_EQ(test, ane_hx_task_stream_dma_validate(text, size, 9, bound), -ENOEXEC); +} + static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_h16_prologue_test), KUNIT_CASE(ane_h17_prologue_test), @@ -806,6 +852,7 @@ static struct kunit_case ane_h16_task_cases[] = { KUNIT_CASE(ane_hx_dma_count_test), KUNIT_CASE(ane_hx_dma_repeat_test), KUNIT_CASE(ane_hx_dma_h15_test), + KUNIT_CASE(ane_hx_dma_channel_default_and_dst_dep_test), KUNIT_CASE(ane_hx_dma_reset_test), KUNIT_CASE(ane_hx_dma_rewrite_test), KUNIT_CASE(ane_hx_dma_strict_test), From 7a8f8c9ae235231989edf37231c30dd4e35b421b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 05:04:36 +1100 Subject: [PATCH 1501/1514] drm/apple: don't offer PQ on firmware 27 panels Turning HDR on in GNOME on a K114s (T6050, firmware 27) makes the internal panel blinding, with most of the desktop clipped to white. Measured on the K114s with flat full-screen greys and the ambient light sensor, no compositor in the loop: a surface tagged ST 2084 is decoded with the sRGB curve and then scaled by about 10000/100, so everything above a quarter of the code range sits at the panel's peak. Every other transfer function value gives the plain sRGB decode at SDR white, and the colour space doesn't change it. Firmware 27 has no PQ decode on this path, so a PQ desktop can't be shown correctly with any surface tag. Add dcp_fw_panel_decodes_pq() and, on firmware 27 panels, stop advertising PQ: no EDR (dcp_panel_edr(), dcp_panel_edr_supported()), so no Colorspace and HDR_OUTPUT_METADATA properties, and no HDR static metadata in the panel's EDID. Compositors then keep the panel in SDR. Desktop 26.x panels (J614s/J616s, which decode PQ) don't change. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 13 +++++++++++++ drivers/gpu/drm/apple/dcp.c | 6 +++--- drivers/gpu/drm/apple/iomfb.c | 5 +++-- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index ea934cff9ab656..b44bac4e91a925 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1485,6 +1485,19 @@ static inline bool dcp_fw_swap_has_edr(struct apple_dcp *dcp) dcp->fw_compat == DCP_FIRMWARE_V_27_0; } +/* + * Whether the firmware decodes PQ surfaces on its EDR panel path. Firmware 27 + * does not: on the K114s (T6050) a surface tagged ST 2084 is decoded with the + * sRGB curve and scaled by about 10000/100, and every other transfer function + * value gives the plain sRGB decode, whatever the colour space. A PQ desktop + * then clips everything above a quarter of the code range to the panel's peak. + * So firmware 27 panels don't offer PQ until the EDR path maps it some other way. + */ +static inline bool dcp_fw_panel_decodes_pq(struct apple_dcp *dcp) +{ + return dcp->fw_compat != DCP_FIRMWARE_V_27_0; +} + static inline bool dcp_vrr_live(struct apple_dcp *dcp) { return dcp->fw_compat == DCP_FIRMWARE_V_26_6_DESKTOP && dcp->main_display && diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index ac0f8d7ba57da2..3897e4b54127a5 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -1659,7 +1659,7 @@ const struct drm_edid *dcp_panel_edid_snapshot(struct apple_dcp *dcp, *generation = id->generation; spin_unlock_irqrestore(&dcp->metadata.lock, flags); /* PQ content is shown as EDR up to the peak (see dcp_edr_prepare()). */ - if (READ_ONCE(dcp->panel.peak_nits)) { + if (READ_ONCE(dcp->panel.peak_nits) && dcp_fw_panel_decodes_pq(dcp)) { metadata.pq = true; metadata.static_metadata_type1 = true; metadata.bt2020_rgb = true; @@ -4556,8 +4556,8 @@ bool dcp_panel_edr(struct platform_device *pdev) { struct apple_dcp *dcp = platform_get_drvdata(pdev); - return dcp_fw_swap_has_edr(dcp) && dcp_has_panel(dcp) && - dcp->panel.edr_ceiling; + return dcp_fw_swap_has_edr(dcp) && dcp_fw_panel_decodes_pq(dcp) && + dcp_has_panel(dcp) && dcp->panel.edr_ceiling; } /* External connectors driven by iomfb_template support full colour selection. */ diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index cbc093e132fc8a..b513f981a27db7 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3260,8 +3260,9 @@ static bool dcp_hdr_output_supported(struct apple_dcp *dcp) */ static bool dcp_panel_edr_supported(struct apple_dcp *dcp) { - return dcp_fw_swap_has_edr(dcp) && dcp_has_panel(dcp) && - dcp->panel.edr_ceiling && READ_ONCE(dcp->panel.peak_nits); + return dcp_fw_swap_has_edr(dcp) && dcp_fw_panel_decodes_pq(dcp) && + dcp_has_panel(dcp) && dcp->panel.edr_ceiling && + READ_ONCE(dcp->panel.peak_nits); } /* The state of the connector on @crtc that @commit sets up. */ From f4c4b0389e3239962d387c90de02ff7df6157f18 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 05:15:19 +1100 Subject: [PATCH 1502/1514] drm/apple: keep the refresh rate iBoot left the T6050 panel at After macOS left a K114s (T6050) panel at 60 Hz, every Linux boot crashed the internal DCP about two seconds in and left the panel dark: iBoot hands the panel over at 60 Hz, the driver offers only the 120 Hz timing (only_120hz_modes), and the mode set from 60 to 120 Hz takes the link down and crashes the firmware, as 120 to 60 Hz already did on the M5 Max. The state survives warm reboots. The firmware names the rate it found at start, "IOMFB update_rr_index syncrate 60", before any mode set of ours. Keep the first such rate and offer only modes at it on these panels, 120 Hz when none was reported. The mode set then finds the timing already set ("Already set to timingID: 3") and the panel lights. Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/dcp-internal.h | 6 ++++++ drivers/gpu/drm/apple/dcp.c | 22 ++++++++++++++++++++++ drivers/gpu/drm/apple/iomfb.c | 11 +++++++---- drivers/gpu/drm/apple/parser-test.c | 6 ++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/dcp-internal.h b/drivers/gpu/drm/apple/dcp-internal.h index ea934cff9ab656..c5326930a616f5 100644 --- a/drivers/gpu/drm/apple/dcp-internal.h +++ b/drivers/gpu/drm/apple/dcp-internal.h @@ -1114,6 +1114,12 @@ struct apple_dcp { char link_line[120]; u64 link_line_generation; u8 link_dsc; + /* + * hw.only_120hz_modes: the refresh rate iBoot left the panel at, from the + * firmware's "update_rr_index syncrate N" line before our first mode set + * (dcp_rtk_syslog_boot_rate()); 0 until seen. + */ + u32 boot_rate; /* V27 sleep: the panel's next mode set is the mode it already has */ bool v27_keep_mode; diff --git a/drivers/gpu/drm/apple/dcp.c b/drivers/gpu/drm/apple/dcp.c index ac0f8d7ba57da2..a8d697751bb0ef 100644 --- a/drivers/gpu/drm/apple/dcp.c +++ b/drivers/gpu/drm/apple/dcp.c @@ -2299,8 +2299,30 @@ static bool dcp_rtk_syslog_mode_set(void *cookie, const char *context, const cha return false; } +/* + * The T6050 internal DCP (hw.only_120hz_modes) can't survive a mode set away + * from the timing iBoot left the panel at: 120 -> 60 Hz crashes it, and so does + * 60 -> 120 Hz when macOS left the panel at 60 Hz. The firmware names that + * rate when it starts, "IOMFB update_rr_index syncrate 60", before any mode set + * of ours: keep the first one (dcp_mode_settable()). + */ +static void dcp_rtk_syslog_boot_rate(struct apple_dcp *dcp, const char *message) +{ + const char *p; + u32 rate; + + if (!dcp->hw.only_120hz_modes || READ_ONCE(dcp->boot_rate)) + return; + p = strstr(message, "update_rr_index syncrate "); + if (!p || sscanf(p, "update_rr_index syncrate %u", &rate) != 1) + return; + if (rate >= 24 && rate <= 240) + WRITE_ONCE(dcp->boot_rate, rate); +} + static bool dcp_rtk_syslog_is_debug(void *cookie, const char *context, const char *message) { + dcp_rtk_syslog_boot_rate(cookie, message); return dcp_h17p_syslog_is_debug(context, message); } diff --git a/drivers/gpu/drm/apple/iomfb.c b/drivers/gpu/drm/apple/iomfb.c index cbc093e132fc8a..2279fdd99ff4dd 100644 --- a/drivers/gpu/drm/apple/iomfb.c +++ b/drivers/gpu/drm/apple/iomfb.c @@ -3643,11 +3643,14 @@ static bool dcp_mode_settable(struct apple_dcp *dcp, return dcp_mode->mode.type & DRM_MODE_TYPE_PREFERRED; /* - * The T6050 internal DCP (M5 Max) crashes on 3024x1986@60 and the - * other 60 Hz timings it lists. Only the 120 Hz timing is known to - * survive a modeset, so refuse the rest until they are understood. + * The T6050 internal DCP (M5 Max, K114s) crashes on a mode set away + * from the timing iBoot left the panel at: 120 -> 60 Hz, and 60 -> + * 120 Hz when macOS left it at 60 Hz. Offer only the rate the + * firmware reported at start (dcp_rtk_syslog_boot_rate()), 120 Hz + * when it reported none. */ - if (dcp->hw.only_120hz_modes && drm_mode_vrefresh(mode) != 120) + if (dcp->hw.only_120hz_modes && + drm_mode_vrefresh(mode) != (READ_ONCE(dcp->boot_rate) ?: 120)) return false; return true; diff --git a/drivers/gpu/drm/apple/parser-test.c b/drivers/gpu/drm/apple/parser-test.c index 1829f63047df70..3cd787b9e05503 100644 --- a/drivers/gpu/drm/apple/parser-test.c +++ b/drivers/gpu/drm/apple/parser-test.c @@ -2089,6 +2089,12 @@ static void parser_internal_v27_only_120hz(struct kunit *test) KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_OK); KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[1].mode), MODE_BAD); + /* iBoot left the panel at 60 Hz: only the 60 Hz timing, no mode set away from it. */ + dcp->boot_rate = 60; + KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_BAD); + KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[1].mode), MODE_OK); + dcp->boot_rate = 0; + /* The T8142 Air internal DCP (60 Hz panel, firmware 27.0) and the T6050 dcpext keep every mode. */ dcp->hw.only_120hz_modes = false; KUNIT_EXPECT_EQ(test, dcp_mode_valid(&connector->base, &catalog[0].mode), MODE_OK); From 06eb115ad59d27e20f09c2adc1ac53408fa80db7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 02:03:25 +1100 Subject: [PATCH 1503/1514] arm64: dts: apple: t8132-j623-j624: enable the DP855 panel controller The M4 iMacs' ADTs (J623, J624) list the DP855 panel timing controller at /arm-io/spi4/dp855 with the same chip select as the M4 laptops: the spi4 function-spi_cs0 is GPIO 76 on gpio0. The laptops enable it from t8132-laptop.dtsi, which the iMacs don't include. Enable spi4 and the controller in the shared iMac dtsi with the laptops' SPI timing. spi4 already clocks from clkref, and its power domain is on in the default T8132 PMGR description. Signed-off-by: Ryan Murray --- .../arm64/boot/dts/apple/t8132-j623-j624.dtsi | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi b/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi index ec07e49b3da468..63a530d946dd8c 100644 --- a/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi +++ b/arch/arm64/boot/dts/apple/t8132-j623-j624.dtsi @@ -91,3 +91,23 @@ &avd { status = "okay"; }; + +/* + * ADT /arm-io/spi4/dp855: the panel timing controller. The J623 and J624 + * ADTs give the same chip select as the M4 laptops (spi4 function-spi_cs0, + * GPIO 76). i2c-dp855 reads the panel management devices behind it and + * shares its I2C engine with the display firmware through the controller's + * lock. + */ +&spi4 { + cs-gpios = <&pinctrl_ap 76 GPIO_ACTIVE_LOW>; + status = "okay"; + + panel-timing-controller@0 { + compatible = "parade,dp855"; + reg = <0>; + spi-max-frequency = <1000000>; + spi-cs-setup-delay-ns = <20>; + spi-cs-hold-delay-ns = <20>; + }; +}; From c2656bf7c62759434db83d71e437a4599344835e Mon Sep 17 00:00:00 2001 From: Erik Bourget Date: Fri, 27 Nov 2026 13:27:14 -0500 Subject: [PATCH 1504/1514] media: apple: avd: h264: implement START_CODE_NONE framing and validate mode pairs Validate H.264 decode-mode and start-code pairings in avd_h264_mode_supported() and implement framing dispatch in avd_h264_next_frame_nalu(): - SLICE_BASED accepts START_CODE_NONE only and rejects START_CODE_ANNEX_B with -EINVAL. - FRAME_BASED + START_CODE_ANNEX_B requires Annex-B start codes and rejects unprefixed buffers with -EINVAL. - FRAME_BASED + START_CODE_NONE parses a single unprefixed ITU-T H.264 7.3.1 VCL slice NALU (no start code, rejecting non-VCL types, forbidden_zero_bit, and embedded start codes), while dispatching buffers beginning with a leading Annex-B start code to the Annex-B scanner for clients (such as Chromium's V4L2VideoDecoderDelegateH264) that select FRAME_BASED without writing START_CODE and leave it at this driver's START_CODE_NONE default. Because no valid unprefixed 7.3.1 NALU starts with 0x00, leading Annex-B start codes cannot collide with valid START_CODE_NONE payloads. - Add KUnit coverage for the mode/start-code matrix, both FRAME_BASED framing paths, Chromium's default-control path, and malformed/unsupported inputs. Signed-off-by: Erik Bourget --- .../media/platform/apple/avd/avd-h264-parse.c | 104 ++++++++++++ .../media/platform/apple/avd/avd-h264-parse.h | 3 + .../media/platform/apple/avd/avd-h264-test.c | 158 ++++++++++++++++++ drivers/media/platform/apple/avd/avd-h264.c | 33 ++-- 4 files changed, 277 insertions(+), 21 deletions(-) diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.c b/drivers/media/platform/apple/avd/avd-h264-parse.c index 8bbeca9a60696d..8c32933db8c55f 100644 --- a/drivers/media/platform/apple/avd/avd-h264-parse.c +++ b/drivers/media/platform/apple/avd/avd-h264-parse.c @@ -117,6 +117,110 @@ int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, return 0; } +bool avd_h264_mode_supported(s32 decode_mode, s32 start_code) +{ + switch (decode_mode) { + case V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED: + return start_code == V4L2_STATELESS_H264_START_CODE_NONE; + case V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED: + return start_code == V4L2_STATELESS_H264_START_CODE_ANNEX_B || + start_code == V4L2_STATELESS_H264_START_CODE_NONE; + default: + return false; + } +} + +static bool avd_h264_has_annexb_start_code(const u8 *buf, u32 len) +{ + u32 pos = 0; + + while (pos < len && buf[pos] == 0x00) + pos++; + + return pos >= 2 && pos < len && buf[pos] == 0x01; +} + +/* + * Parse a single unprefixed ITU-T H.264 7.3.1 VCL slice NALU for + * FRAME_BASED + START_CODE_NONE. No Annex-B start code prefix is present + * and none may appear inside the EBSP payload. + */ +static int avd_h264_parse_raw_nalu(const u8 *buf, u32 len, + struct avd_h264_nalu *nalu) +{ + u32 end = len, i; + u8 hdr, nal_type; + + if (!buf || !nalu || !len) + return -EINVAL; + + while (end > 0 && buf[end - 1] == 0x00) + end--; + if (end < 2) + return -EINVAL; + + /* An EBSP must not contain an unescaped 0x00 0x00 0x01 start code. */ + for (i = 0; end >= 3 && i <= end - 3; i++) { + if (buf[i] == 0x00 && buf[i + 1] == 0x00 && buf[i + 2] == 0x01) + return -EINVAL; + } + + hdr = buf[0]; + if (hdr & 0x80) + return -EINVAL; + + nal_type = hdr & 0x1f; + if (nal_type != AVD_H264_NAL_SLICE && + nal_type != AVD_H264_NAL_IDR_SLICE) + return -EINVAL; + + nalu->off = 0; + nalu->len = end; + nalu->nal_ref_idc = (hdr >> 5) & 0x03; + nalu->nal_unit_type = nal_type; + return 1; +} + +/* + * Iterate VCL slice NALUs in a FRAME_BASED OUTPUT buffer according to + * V4L2_CID_STATELESS_H264_START_CODE: + * - START_CODE_ANNEX_B requires Annex-B start codes (0x000001 / 0x00000001). + * - START_CODE_NONE accepts a single unprefixed ITU-T H.264 7.3.1 VCL slice + * NALU. For compatibility with clients (such as Chromium's + * V4L2VideoDecoderDelegateH264) that set DECODE_MODE=FRAME_BASED without + * writing START_CODE, leaving it at this driver's START_CODE_NONE default + * while still emitting Annex-B start codes, a buffer starting with an + * Annex-B start code is dispatched to the Annex-B scanner. That cannot + * collide with valid START_CODE_NONE data because no valid 7.3.1 NALU + * begins with 0x00 (nal_unit_type 0 is invalid). + */ +int avd_h264_next_frame_nalu(const u8 *buf, u32 len, s32 start_code, + u32 *cursor, struct avd_h264_nalu *nalu) +{ + int ret; + + if (!cursor || !nalu) + return -EINVAL; + + if (start_code == V4L2_STATELESS_H264_START_CODE_ANNEX_B) + return avd_h264_next_nalu(buf, len, cursor, nalu); + + if (start_code != V4L2_STATELESS_H264_START_CODE_NONE) + return -EINVAL; + + if (!buf) + return len ? -EINVAL : 0; + if (avd_h264_has_annexb_start_code(buf, len)) + return avd_h264_next_nalu(buf, len, cursor, nalu); + if (*cursor >= len) + return 0; + + ret = avd_h264_parse_raw_nalu(buf, len, nalu); + if (ret > 0) + *cursor = len; + return ret; +} + VISIBLE_IF_KUNIT void avd_h264_br_init(struct avd_h264_br *br, const u8 *data, u32 len, u32 pos) { diff --git a/drivers/media/platform/apple/avd/avd-h264-parse.h b/drivers/media/platform/apple/avd/avd-h264-parse.h index e6789a4e3da1de..d8e507e73371eb 100644 --- a/drivers/media/platform/apple/avd/avd-h264-parse.h +++ b/drivers/media/platform/apple/avd/avd-h264-parse.h @@ -25,8 +25,11 @@ struct avd_h264_br { bool err; }; +bool avd_h264_mode_supported(s32 decode_mode, s32 start_code); int avd_h264_next_nalu(const u8 *buf, u32 len, u32 *cursor, struct avd_h264_nalu *nalu); +int avd_h264_next_frame_nalu(const u8 *buf, u32 len, s32 start_code, + u32 *cursor, struct avd_h264_nalu *nalu); int avd_h264_parse_slice_header(const u8 *nal, u32 nal_len, u8 nal_ref_idc, u8 nal_unit_type, diff --git a/drivers/media/platform/apple/avd/avd-h264-test.c b/drivers/media/platform/apple/avd/avd-h264-test.c index d4cbd2f20a04d5..3c8888f06bbbfd 100644 --- a/drivers/media/platform/apple/avd/avd-h264-test.c +++ b/drivers/media/platform/apple/avd/avd-h264-test.c @@ -1379,6 +1379,163 @@ static void avd_slice_hdr_real_annexb_test(struct kunit *test) KUNIT_EXPECT_EQ(test, bit_off, 0); } +static void avd_frame_mode_framing_test(struct kunit *test) +{ + /* Real libx264 CABAC IDR slice, unprefixed (7.3.1 NALU) and Annex-B. */ + static const u8 raw_idr[] = { + 0x65, 0x88, 0x84, 0x00, 0x87, 0x69, 0xd7, 0xdc, 0x00, 0x00, + }; + static const u8 annexb_two_slice[] = { + 0x00, 0x00, 0x01, 0x65, 0x88, 0x84, 0x08, 0x7c, 0x42, 0x22, 0xb0, + 0x00, 0x00, 0x01, 0x65, 0x12, 0x22, 0x10, 0x77, 0xf1, 0xff, 0x87, + }; + static const u8 raw_with_embedded_sc[] = { + 0x65, 0x88, 0x84, 0x00, 0x00, 0x01, 0x65, 0x12, + }; + static const u8 bad_raw_hdrs[] = { + 0x00, 0x06, 0x09, 0x67, 0x68, 0x22, 0x23, 0x24, 0x2e, 0x34, 0xe5, + }; + static const u8 one_byte[] = { 0x65 }; + static const u8 trunc_zeros[] = { 0x00, 0x00 }; + struct avd_parse_test_ctx *t = avd_parse_test_alloc(test); + struct avd_h264_nalu nalu; + u32 cursor, data_off; + u8 bit_off; + + /* Mode / start-code pairing matrix */ + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED, + V4L2_STATELESS_H264_START_CODE_ANNEX_B)); + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, + V4L2_STATELESS_H264_START_CODE_ANNEX_B)); + KUNIT_EXPECT_TRUE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, + V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(-1, V4L2_STATELESS_H264_START_CODE_NONE)); + KUNIT_EXPECT_FALSE(test, + avd_h264_mode_supported(V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED, 2)); + + /* FRAME_BASED + START_CODE_ANNEX_B: accepts Annex-B, rejects raw NALU */ + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + 0); + + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_ANNEX_B, + &cursor, &nalu), + -EINVAL); + + /* FRAME_BASED + START_CODE_NONE: accepts unprefixed 7.3.1 VCL slice NALU */ + t->sps.chroma_format_idc = 1; + t->sps.pic_order_cnt_type = 0; + t->pps.num_ref_idx_l0_default_active_minus1 = 1; + t->pps.flags = V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE | + V4L2_H264_PPS_FLAG_WEIGHTED_PRED | + V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT; + + cursor = 0; + KUNIT_ASSERT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, nalu.off, 0); + KUNIT_EXPECT_EQ(test, nalu.len, sizeof(raw_idr) - 2); + KUNIT_EXPECT_EQ(test, nalu.nal_unit_type, 5); + KUNIT_EXPECT_EQ(test, nalu.nal_ref_idc, 3); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 0); + KUNIT_ASSERT_EQ(test, + avd_h264_parse_slice_header(raw_idr + nalu.off, nalu.len, + nalu.nal_ref_idc, nalu.nal_unit_type, + &t->sps, &t->pps, &t->decode, + 0, NULL, NULL, NULL, + &t->sl, &t->weights, + &data_off, &bit_off), + 0); + KUNIT_EXPECT_EQ(test, t->sl.slice_type, V4L2_H264_SLICE_TYPE_I); + KUNIT_EXPECT_EQ(test, t->sl.slice_qp_delta, 8); + KUNIT_EXPECT_EQ(test, data_off, 5); + KUNIT_EXPECT_EQ(test, bit_off, 0); + + /* FRAME_BASED + START_CODE_NONE: Chromium Annex-B compatibility path */ + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 1); + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(annexb_two_slice, sizeof(annexb_two_slice), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + 0); + + /* Error paths for FRAME_BASED + START_CODE_NONE and invalid start_code */ + for (unsigned int i = 0; i < ARRAY_SIZE(bad_raw_hdrs); i++) { + u8 buf[] = { bad_raw_hdrs[i], 0x88, 0x84 }; + + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(buf, sizeof(buf), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + } + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(one_byte, sizeof(one_byte), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(trunc_zeros, sizeof(trunc_zeros), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_with_embedded_sc, sizeof(raw_with_embedded_sc), + V4L2_STATELESS_H264_START_CODE_NONE, + &cursor, &nalu), + -EINVAL); + cursor = 0; + KUNIT_EXPECT_EQ(test, + avd_h264_next_frame_nalu(raw_idr, sizeof(raw_idr), 2, + &cursor, &nalu), + -EINVAL); +} + static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE(avd_scaling_flat_test), KUNIT_CASE_PARAM(avd_slice_data_test, avd_slice_data_gen_params), @@ -1388,6 +1545,7 @@ static struct kunit_case avd_h264_test_cases[] = { KUNIT_CASE(avd_sps_range_test), KUNIT_CASE(avd_start_slices_test), KUNIT_CASE(avd_annexb_scanner_test), + KUNIT_CASE(avd_frame_mode_framing_test), KUNIT_CASE(avd_bitreader_epb_test), KUNIT_CASE(avd_slice_hdr_epb_boundary_test), KUNIT_CASE(avd_slice_hdr_fields_test), diff --git a/drivers/media/platform/apple/avd/avd-h264.c b/drivers/media/platform/apple/avd/avd-h264.c index 6d756f73112584..ac02aa7b26844c 100644 --- a/drivers/media/platform/apple/avd/avd-h264.c +++ b/drivers/media/platform/apple/avd/avd-h264.c @@ -1163,7 +1163,9 @@ static int avd_h264_run_frame(struct avd_ctx *ctx, struct avd_h264_run *run) max_slices = avd_h264_max_slices(run->sps); cursor = 0; num_slices = 0; - while ((ret = avd_h264_next_nalu(data, payload_len, &cursor, &nalu)) > 0) { + while ((ret = avd_h264_next_frame_nalu(data, payload_len, + run->start_code, + &cursor, &nalu)) > 0) { num_slices++; if (num_slices > max_slices) { dev_err_ratelimited(ctx->dev->dev, @@ -1173,7 +1175,7 @@ static int avd_h264_run_frame(struct avd_ctx *ctx, struct avd_h264_run *run) } if (ret < 0 || !num_slices) { dev_dbg_ratelimited(ctx->dev->dev, - "no valid H.264 slice NALUs in Annex-B buffer\n"); + "no valid H.264 slice NALUs in frame buffer\n"); return -EINVAL; } @@ -1199,7 +1201,9 @@ static int avd_h264_run_frame(struct avd_ctx *ctx, struct avd_h264_run *run) cursor = 0; slice_idx = 0; last_mb = 0; - while ((ret = avd_h264_next_nalu(data, payload_len, &cursor, &nalu)) > 0) { + while ((ret = avd_h264_next_frame_nalu(data, payload_len, + run->start_code, + &cursor, &nalu)) > 0) { u32 slice_data_off; u8 slice_bit_off; @@ -1277,19 +1281,12 @@ static int avd_h264_run(struct avd_ctx *ctx) if (ret) goto err_free_jobs; + if (!avd_h264_mode_supported(run.decode_mode, run.start_code)) { + ret = -EINVAL; + goto err_free_jobs; + } + if (run.decode_mode == V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED) { - /* - * Frame-based stateless clients (for example Chromium's V4L2 - * H.264 delegate) may set DECODE_MODE=FRAME_BASED while - * leaving START_CODE at the driver default (START_CODE_NONE) - * and still emit Annex-B start codes in the OUTPUT buffer. - * Annex-B framing is still validated in avd_h264_run_frame(). - */ - if (run.start_code != V4L2_STATELESS_H264_START_CODE_ANNEX_B && - run.start_code != V4L2_STATELESS_H264_START_CODE_NONE) { - ret = -EINVAL; - goto err_free_jobs; - } ret = avd_h264_run_frame(ctx, &run); if (ret) goto err_free_jobs; @@ -1299,12 +1296,6 @@ static int avd_h264_run(struct avd_ctx *ctx) return avd_submit_job(ctx); } - if (run.decode_mode != V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED || - run.start_code != V4L2_STATELESS_H264_START_CODE_NONE) { - ret = -EINVAL; - goto err_free_jobs; - } - ret = avd_h264_validate_slice(ctx, run.slice_params); if (ret) goto err_free_jobs; From 508ac4881f2aa3e3f0c2fbed5c34a04a01cf40b7 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 05:29:06 +1100 Subject: [PATCH 1505/1514] accel/ane: h16: count from the first firmware traffic, pair the quarantine flag Review of the previous commit: - With the gate already held by earlier requests, the request began its ane_stats ticket before the pending entry and the command were set up, so a local failure there counted a job that sent nothing. The ticket now starts at the opening gate when the gate is closed, and at the EXECUTE when it is already open. A new KUnit case covers the held-gate path with a local failure (no UUID left): the job count stays put. It fails on the previous commit. - wedged reads session->quarantined with READ_ONCE(); the writers in the session and both backends now use WRITE_ONCE(). Signed-off-by: Ryan Murray --- drivers/accel/ane/ane_fw_cold.c | 12 ++++----- drivers/accel/ane/ane_h16_backend.c | 6 ++--- drivers/accel/ane/ane_h16_program.c | 31 +++++++++++++++++------- drivers/accel/ane/ane_h16_program_test.c | 27 +++++++++++++++++++++ 4 files changed, 58 insertions(+), 18 deletions(-) diff --git a/drivers/accel/ane/ane_fw_cold.c b/drivers/accel/ane/ane_fw_cold.c index 7a0c40e521c6cd..07921a5b289c7a 100644 --- a/drivers/accel/ane/ane_fw_cold.c +++ b/drivers/accel/ane/ane_fw_cold.c @@ -1175,7 +1175,7 @@ static void ane_fw_unpark(struct ane_fw_backend *b) if (ret) { /* Power and mappings stay for diagnosis: the quarantine pins the device. */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } ane_h16_session_sleep(&b->session, false); dev_info(&b->pdev->dev, "H17 ANE: up for a request%s\n", ret ? " FAILED" : ""); @@ -1415,7 +1415,7 @@ static void ane_fw_recover_work(struct work_struct *work) b->recover_failures++; /* Booted over memory proven free: as any failed boot, until reboot. */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } else { ane_fw_hung_recovered(b); ane_fw_rpm_idle(b); @@ -1566,7 +1566,7 @@ int ane_fw_staged_runtime_suspend(struct device *dev) b->in_rpm = false; if (ret) { ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); ane_h16_session_sleep(&b->session, false); dev_err(dev, "H17 ANE: idle park failed (%d): quarantined\n", ret); return -EBUSY; @@ -1671,7 +1671,7 @@ static int ane_fw_sleep_prepare(struct ane_fw_backend *b) * session (SPEC-ANE-SLEEP.md section 6). */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); ane_h16_session_sleep(&b->session, false); return ret; } @@ -1781,7 +1781,7 @@ static void ane_fw_sleep_resume(struct ane_fw_backend *b) if (ret) { /* Every mapping and backing stays for diagnosis. */ ane_fw_quarantine(b, ret); - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } else if (recover) { ane_fw_hung_recovered(b); ane_fw_rpm_idle(b); @@ -2893,7 +2893,7 @@ static int ane_fw_first_bringup(struct ane_fw_backend *b) b->stage = ANE_STAGE_PROGRAM; ret = 0; } else { - b->session.quarantined = true; + WRITE_ONCE(b->session.quarantined, true); } WRITE_ONCE(b->parked, false); WRITE_ONCE(b->session.parked, false); diff --git a/drivers/accel/ane/ane_h16_backend.c b/drivers/accel/ane/ane_h16_backend.c index 33197c1027ed1c..4fb0001b94b4c1 100644 --- a/drivers/accel/ane/ane_h16_backend.c +++ b/drivers/accel/ane/ane_h16_backend.c @@ -679,7 +679,7 @@ static void ane_h16_unpark(struct ane_h16_device *h) /* Power and mappings stay for diagnosis: quarantine pins the device. */ ane_h16_quarantine(h, ret); h->boot.quarantined = true; - h->session.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); } ane_h16_session_sleep(&h->session, false); dev_info(h->dev, "H16 ANE: up for a request%s in %llu ms, %u programs replayed, %u restarts\n", @@ -886,7 +886,7 @@ static int ane_h16_sleep_prepare(struct ane_h16_device *h) /* Powered, maybe suspended: keep everything, refuse, close. */ ane_h16_quarantine(h, ret); h->boot.quarantined = true; - h->session.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); ane_h16_session_sleep(&h->session, false); return ret; } @@ -954,7 +954,7 @@ static void ane_h16_sleep_resume(struct ane_h16_device *h) /* Every mapping and backing stays for diagnosis. */ ane_h16_quarantine(h, ret); h->boot.quarantined = true; - h->session.quarantined = true; + WRITE_ONCE(h->session.quarantined, true); } else if (h->sleep_quarantined) { h->recoveries++; dev_info(h->dev, "H16 ANE: quarantined engine recovered by system sleep\n"); diff --git a/drivers/accel/ane/ane_h16_program.c b/drivers/accel/ane/ane_h16_program.c index ec01def937cdd8..3ab72b3fa607d1 100644 --- a/drivers/accel/ane/ane_h16_program.c +++ b/drivers/accel/ane/ane_h16_program.c @@ -682,7 +682,7 @@ static int h16_fail(struct ane_h16_session *s, int error) if (!s->error) s->error = error; if (!s->quarantined) { - s->quarantined = true; + WRITE_ONCE(s->quarantined, true); ane_h16_pending_fail_all(&s->pending, s->error); wake_up_all(&s->wake); s->ops->log(s->ctx, "program quarantine", (u64)-s->error, 0); @@ -1639,6 +1639,19 @@ static int h16_execute_room(struct ane_h16_session *s, struct ane_h16_program *p * barrier before the caller reads outputs. Any uncertain outcome quarantines * the session and keeps every mapping. */ +/* + * A request counts in ane_stats from its first firmware traffic (the opening + * gate, or the EXECUTE itself when the gate is already open) until it ends + * either way. A refusal or local failure before that point reached nothing. + */ +static void h16_count_begin(struct ane_h16_session *s, bool *counted, u64 *ticket) +{ + if (*counted) + return; + *ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, ktime_get_ns(), 1); + *counted = true; +} + static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) { struct ane_h16_execute_buffer buffers[ANE_H16_SURFACES + 1]; @@ -1653,7 +1666,8 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) unsigned int i; u64 deadline, polls, t0, gate_open, t1 = 0, t2 = 0, t3, end; u64 entry = h16_now(s); - u64 ticket; + bool counted = false; + u64 ticket = 0; int ret; if (!s || !p || p->session != s) @@ -1697,14 +1711,10 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) /* Inputs and poisoned outputs must reach memory before any doorbell. */ s->transport->ops->write_barrier(s->transport->ctx); polls = s->transport->polls; - /* - * A request counts in ane_stats from its first firmware traffic until - * it ends either way; a refusal before this point reached nothing. - */ - ticket = ane_stats_begin(&s->sysfs_ctrs, &s->sysfs_ring, ktime_get_ns(), 1); trace->step = H16_STEP_GATE_OPEN; t0 = h16_now(s); if (!s->gate_held) { + h16_count_begin(s, &counted, &ticket); ret = h16_gate(s, 0); if (ret) goto fail; @@ -1739,6 +1749,8 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) ANE_FW_DATA_CHAIN); if (!ret) { trace->step = H16_STEP_SEND; + /* With the gate already open, the request itself is the first traffic. */ + h16_count_begin(s, &counted, &ticket); t1 = h16_now(s); ret = h16_send(s, ANE_FW_DATA_CHAIN, command, length, &reply); } @@ -1783,7 +1795,8 @@ static int h16_execute(struct ane_h16_session *s, struct ane_h16_program *p) ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), 0, 0); return 0; fail: - ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), ret, 0); + if (counted) + ane_stats_complete(&s->sysfs_ctrs, &s->sysfs_ring, ticket, ktime_get_ns(), ret, 0); s->ops->log(s->ctx, "EXECUTE failed", (u64)-ret, request->key.uuid); /* * Step 1 opening gate, 2 channel-7 ack, 3 report wait, 4 closing gate. @@ -2213,7 +2226,7 @@ void ane_h16_session_recovered(struct ane_h16_session *s) { struct ane_h16_program *p, *n; - s->quarantined = false; + WRITE_ONCE(s->quarantined, false); s->pending.quarantined = false; s->pending.error = 0; s->error = 0; diff --git a/drivers/accel/ane/ane_h16_program_test.c b/drivers/accel/ane/ane_h16_program_test.c index d27c9be3ab1cd9..302b88299d3bc9 100644 --- a/drivers/accel/ane/ane_h16_program_test.c +++ b/drivers/accel/ane/ane_h16_program_test.c @@ -1537,6 +1537,32 @@ static void program_sysfs_stats_test(struct kunit *test) KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); } +/* + * With the gate held open by earlier requests, the EXECUTE is the request's + * first firmware traffic: a request that fails locally before it went out + * (here no UUID is left for its pending entry) sent nothing and does not + * count in ane_stats. + */ +static void program_sysfs_stats_held_gate_test(struct kunit *test) +{ + struct prog_fw *f = fw_create(test); + struct ane_h16_program *p = NULL; + unsigned int sent; + + KUNIT_ASSERT_NOT_NULL(test, f); + f->s.gate_hold_ns = 1000; + KUNIT_ASSERT_EQ(test, fw_load_program(f, &p), 0); + KUNIT_ASSERT_EQ(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_ASSERT_TRUE(test, f->s.gate_held); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + f->s.pending.next_uuid = U64_MAX; + sent = f->count; + KUNIT_EXPECT_LT(test, ane_h16_session_execute(&f->s, p), 0); + KUNIT_EXPECT_EQ(test, f->count, sent); + KUNIT_EXPECT_EQ(test, atomic64_read(&f->s.sysfs_ctrs.jobs), 1LL); + KUNIT_EXPECT_EQ(test, atomic_read(&f->s.sysfs_ctrs.inflight), 0); +} + /* The phases of one EXECUTE add up, and only successful ones are accounted. */ static void program_timing_test(struct kunit *test) { @@ -4278,6 +4304,7 @@ static struct kunit_case program_cases[] = { KUNIT_CASE(program_stall_trace_test), KUNIT_CASE(program_timing_test), KUNIT_CASE(program_sysfs_stats_test), + KUNIT_CASE(program_sysfs_stats_held_gate_test), KUNIT_CASE(program_fwlog_line_test), KUNIT_CASE(program_shared_tag_test), KUNIT_CASE(program_pool_test), From 4bd348505742993f009a3a261aa345770afbfdf0 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 27 Nov 2026 20:13:32 +0100 Subject: [PATCH 1506/1514] arm64: dts: apple: t8152-j873: describe the N1 warm reset on PCIe port 0 The J873g ADT's pci-bridge0 node declares function-warm_reset on the SMC with key 'bpli' (0x62706c69) and argument 0x1000000, matching J813 and J815. Without apple,function-warm-reset and apple,warm-reset-writes on port00, apple_centauri leaves warm_reset disabled and cannot restart a stopped N1 firmware on J873g. Add apple,function-warm-reset and apple,warm-reset-writes to port00 in t8152-j873-n1.dtsi so N1 warm-reset recovery works on J873g. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi index ffa33863f782b2..63a15928a4d990 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi @@ -65,6 +65,13 @@ #address-cells = <3>; #size-cells = <2>; ranges; + /* + * The N1's warm reset, as on J813 and J815: the J873g ADT's + * pci-bridge0 function-warm_reset names the same SMC key 'bpli' + * and argument. + */ + apple,function-warm-reset = <&smc 0x62706c69 0x1000000>; + apple,warm-reset-writes = <0x00010001 17000>, <0x00010001 20000>; interrupt-controller; #interrupt-cells = <1>; interrupt-map-mask = <0 0 0 7>; From 945fd32356664b633502d3204bd57381df96c78f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 06:51:10 +1100 Subject: [PATCH 1507/1514] selftests: apple-dcp: stub dcp_fw_panel_decodes_pq() for the panel identity units The panel identity, j616s identity and colorimetry units extract dcp_panel_edid_snapshot(), which now asks dcp_fw_panel_decodes_pq(). Stub it, and check that a firmware 27 panel with a peak gets no HDR static metadata block. Signed-off-by: Ryan Murray --- tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py index 1eb7f35674986c..9fdfffafc1b798 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/desktop.py @@ -441,6 +441,8 @@ def panel_identity(root, output=None): }; static unsigned notifications; static bool dcp_has_panel(struct apple_dcp *d) {return d->has_panel;} +/* 27 stands for DCP_FIRMWARE_V_27_0 here: its panel path has no PQ decode. */ +static bool dcp_fw_panel_decodes_pq(struct apple_dcp *d) {return d->fw_compat != 27;} static void dcp_queue_hotplug(void *con) {assert(con);notifications++;} ''' + helpers + dictionary + '\nstatic const u8 attributes[]={'+','.join(map(str,raw))+'};\n' + 'static const u8 product[]={'+','.join(map(str,product))+'};\n' + 'static const u8 minimal[]={'+','.join(map(str,minimal))+'};\n' + r''' int main(int argc, char **argv) @@ -468,6 +470,12 @@ def panel_identity(root, output=None): assert(!IS_ERR(hdr) && drm_edid_valid(hdr) && hdr->size==256); assert(!memcmp(hdr->cta,"\x02\x03\x0f\x00\xe3\x05\x80\x00\xe6\x06\x05\x01\xa0\xa0\x00",15)); drm_edid_free(hdr); + /* Firmware 27: no PQ decode, so no HDR block even with a peak. */ + d.fw_compat=27; + const struct drm_edid *nopq=dcp_panel_edid_snapshot(&d,modes,3,&generation); + assert(!IS_ERR(nopq) && drm_edid_valid(nopq) && nopq->size==128); + drm_edid_free(nopq); + d.fw_compat=5; d.panel.peak_nits=0; const struct drm_edid *fallback=dcp_panel_edid_snapshot(&d,modes,3,&generation); assert(!IS_ERR(fallback) && drm_edid_valid(fallback) && fallback->size==128); From cdb7a3f4fff24be8ebd38d26528dcf3c38855a9f Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 28 Nov 2026 06:54:29 +1100 Subject: [PATCH 1508/1514] selftests: apple-dcp: cover the T6050 boot rate in the syslog policy unit dcp_rtk_syslog_is_debug() now hands each record to dcp_rtk_syslog_boot_rate(). Extract it with a minimal apple_dcp as the RTKit cookie, and check that the first 'update_rr_index syncrate' rate is kept, later and out-of-range rates and other panels are ignored, and the record keeps its info level. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/apple-dcp/boot.py | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py index 14f46e02790254..f796e7c437415b 100644 --- a/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py +++ b/tools/testing/selftests/drivers/gpu/apple-dcp/boot.py @@ -139,7 +139,11 @@ def syslog(root): { (void)rtk; assert(off + len <= b->size); copies++; memcpy(out, b->buffer+off, len); } static int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 msg, void *c, bool atomic) { (void)rtk; assert(ep==2 && msg==0 && c==NULL && !atomic); acks++; return 0; } -''' + helper + '\n' + block(dcp, 'static bool dcp_rtk_syslog_is_debug(') + r''' +typedef uint32_t u32; +#define READ_ONCE(x) (x) +#define WRITE_ONCE(x, v) ((x) = (v)) +struct apple_dcp { struct { bool only_120hz_modes; } hw; u32 boot_rate; }; +''' + helper + '\n' + block(dcp, 'static void dcp_rtk_syslog_boot_rate(') + '\n' + block(dcp, 'static bool dcp_rtk_syslog_is_debug(') + r''' static bool policy(void *cookie, const char *context, const char *message) { calls++; return dcp_rtk_syslog_is_debug(cookie, context, message); } ''' + block(source, 'static bool should_crop_syslog_char(') + '\n' + block(source, 'static void apple_rtkit_syslog_rx_log(') + r''' @@ -154,7 +158,8 @@ def syslog(root): { unsigned char ring[288]; char decoded[256]; struct apple_rtkit_ops ops={.syslog_is_debug=policy}; - struct apple_rtkit rtk={.ops=&ops, .syslog_msg_buffer=decoded, + struct apple_dcp dcp={.hw={.only_120hz_modes=true}}; + struct apple_rtkit rtk={.ops=&ops, .cookie=&dcp, .syslog_msg_buffer=decoded, .syslog_msg_size=256, .syslog_n_entries=1, .syslog_buffer={.size=sizeof(ring),.buffer=ring}}; const char *messages[]={ @@ -191,6 +196,22 @@ def syslog(root): reset(); apple_rtkit_syslog_rx_log(&rtk,0); assert(warnings==1 && !calls && !copies && acks==1); puts("PASS default info, trimming, inherited and invalid records retain transport behavior"); + rtk.syslog_n_entries=1; + /* The rate iBoot left the T6050 panel at: the first one counts, the line stays at info. */ + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 60"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==60 && infos==1 && !debugs && acks==1); + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 120"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==60 && infos==1); + dcp.boot_rate=0; dcp.hw.only_120hz_modes=false; + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==0 && infos==1); + dcp.hw.only_120hz_modes=true; + record(&rtk,"PBlock_PDC_v17.cpp:1954","IOMFB update_rr_index syncrate 7"); + reset(); apple_rtkit_syslog_rx_log(&rtk,0); + assert(dcp.boot_rate==0 && infos==1); + puts("PASS T6050 boot rate: first rate latched, later and out-of-range rates ignored, other panels untouched"); return 0; } ''' From 05a43e16a006cb703cbffe08fcd33159ec71fc19 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 27 Nov 2026 21:25:13 +0100 Subject: [PATCH 1509/1514] thunderbolt: wait for sideband channel idle before writing PORT_CS_1 Per the USB4 specification, software must not start a new sideband transaction in PORT_CS_1 while PORT_CS_1_PND (Pending) is still set. During tb_retimer_scan() on hotplug, probing a non-existent retimer index (e.g. index 2 on a link with a single on-board retimer) can take over 500 ms before the router clears PND. When usb4_port_wait_for_bit() times out at 500 ms, tb_retimer_nvm_authenticate_status() previously ignored -ETIMEDOUT and tb_retimer_scan() immediately issued the next sideband command (usb4_port_retimer_is_last()), writing PORT_CS_1 with PND=1 while the previous sideband transaction was still pending. On Apple T8103 (M1) ACIO firmware this triggers a co-processor panic (assert_id=1313) followed by PORT_CS_1/PORT_CS_2 config space timeouts and a dead USB4 host router. Guard usb4_port_sb_read() and usb4_port_sb_write() with a check that waits for PORT_CS_1_PND to clear (returning -EBUSY if it remains stuck), and propagate -ETIMEDOUT / -EBUSY out of tb_retimer_nvm_authenticate_status() so tb_retimer_scan() aborts instead of firing another command onto a busy sideband channel. Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/retimer.c | 16 ++++++++++++---- drivers/thunderbolt/usb4.c | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/drivers/thunderbolt/retimer.c b/drivers/thunderbolt/retimer.c index 39045b44a4a5a7..898e44395b0289 100644 --- a/drivers/thunderbolt/retimer.c +++ b/drivers/thunderbolt/retimer.c @@ -195,9 +195,9 @@ static ssize_t nvm_authenticate_show(struct device *dev, return ret; } -static void tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status) +static int tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status) { - int i; + int i, ret; tb_port_dbg(port, "reading NVM authentication status of retimers\n"); @@ -207,9 +207,15 @@ static void tb_retimer_nvm_authenticate_status(struct tb_port *port, u32 *status * device instance. */ for (i = 1; i <= TB_MAX_RETIMER_INDEX; i++) { - if (usb4_port_retimer_nvm_authenticate_status(port, i, &status[i])) + ret = usb4_port_retimer_nvm_authenticate_status(port, i, &status[i]); + if (ret) { + if (ret == -ETIMEDOUT || ret == -EBUSY) + return ret; break; + } } + + return 0; } static void tb_retimer_set_inbound_sbtx(struct tb_port *port) @@ -545,7 +551,9 @@ int tb_retimer_scan(struct tb_port *port, bool add) * Immediately after sending enumerate retimers read the * authentication status of each retimer. */ - tb_retimer_nvm_authenticate_status(port, status); + ret = tb_retimer_nvm_authenticate_status(port, status); + if (ret) + return ret; /* * Enable sideband channel for each retimer. We can do this diff --git a/drivers/thunderbolt/usb4.c b/drivers/thunderbolt/usb4.c index 80701579107925..956fe28133c0aa 100644 --- a/drivers/thunderbolt/usb4.c +++ b/drivers/thunderbolt/usb4.c @@ -1343,6 +1343,28 @@ static int usb4_port_write_data(struct tb_port *port, const void *data, dwords); } +static int usb4_port_sb_wait_idle(struct tb_port *port) +{ + u32 val; + int ret; + + ret = tb_port_read(port, &val, TB_CFG_PORT, + port->cap_usb4 + PORT_CS_1, 1); + if (ret) + return ret; + if (!(val & PORT_CS_1_PND)) + return 0; + + ret = usb4_port_wait_for_bit(port, port->cap_usb4 + PORT_CS_1, + PORT_CS_1_PND, 0, 500, USB4_PORT_SB_DELAY); + if (ret) { + tb_port_warn(port, "sideband channel still busy (PND=1)\n"); + return -EBUSY; + } + + return 0; +} + /** * usb4_port_sb_read() - Read from sideband register * @port: USB4 port to read @@ -1366,6 +1388,10 @@ int usb4_port_sb_read(struct tb_port *port, enum usb4_sb_target target, u8 index if (!port->cap_usb4) return -EINVAL; + ret = usb4_port_sb_wait_idle(port); + if (ret) + return ret; + val = reg; val |= size << PORT_CS_1_LENGTH_SHIFT; val |= (target << PORT_CS_1_TARGET_SHIFT) & PORT_CS_1_TARGET_MASK; @@ -1419,6 +1445,10 @@ int usb4_port_sb_write(struct tb_port *port, enum usb4_sb_target target, if (!port->cap_usb4) return -EINVAL; + ret = usb4_port_sb_wait_idle(port); + if (ret) + return ret; + if (buf) { ret = usb4_port_write_data(port, buf, dwords); if (ret) From 806405336fb5cb6dbc2f507ac7caff1e51331bd5 Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 27 Nov 2026 22:24:27 +0100 Subject: [PATCH 1510/1514] arm64: dts: apple: t8152-j873: describe the N1 Wi-Fi and Bluetooth functions Add the N1 PCIe Wi-Fi (01:00.1, pci106b,1902) and Bluetooth (01:00.2, pci106b,1903) child nodes under port00 and their wifi0 / bluetooth0 aliases in t8152-j873-n1.dtsi, matching t8142-j813.dts. Aura's dt_prepare_t8152() already runs dt_set_mac_addresses() and copies ADT /chosen/mac-address-wifi0 and mac-address-bluetooth0 into these aliases when present. Without them, wlp1s0f0 fell back to a per-boot random MAC and btcentauri logged 'No factory local-bd-address from the loader', skipped native PROXIMA startup, and failed HCI Reset (0x0c03) with -110. Signed-off-by: Thomas Glanzmann --- arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi index ffa33863f782b2..deec2244bc9340 100644 --- a/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi +++ b/arch/arm64/boot/dts/apple/t8152-j873-n1.dtsi @@ -8,6 +8,12 @@ #include / { + aliases { + /* Filled by the loader from ADT /chosen mac-address-*. */ + wifi0 = &n1_alpha; + bluetooth0 = &n1_beta; + }; + soc { pinctrl_ap: pinctrl@31a000000 { compatible = "apple,t8152-pinctrl", "apple,t8103-pinctrl"; @@ -72,6 +78,20 @@ <0 0 0 2 &port00 0 0 0 1>, <0 0 0 3 &port00 0 0 0 2>, <0 0 0 4 &port00 0 0 0 3>; + + n1_alpha: wifi@0,1 { + compatible = "pci106b,1902"; + reg = <0x10100 0x0 0x0 0x0 0x0>; + /* Filled by the loader */ + local-mac-address = [00 00 00 00 00 00]; + }; + + n1_beta: bluetooth@0,2 { + compatible = "pci106b,1903"; + reg = <0x10200 0x0 0x0 0x0 0x0>; + /* Filled by the loader */ + local-bd-address = [00 00 00 00 00 00]; + }; }; }; }; From 00f5a7d303ecbcb739a36fb9b940bf782e5d6e25 Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:58:30 -0600 Subject: [PATCH 1511/1514] arm64: dts: apple: t604x: the H16 firmware path is proven on the J616s --- arch/arm64/boot/dts/apple/t604x.dtsi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index b269473755b871..eeff61a9862c5a 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -1860,10 +1860,10 @@ }; /* - * Disabled until the H16 firmware path is proven on hardware. The - * loader fills the preload reservations and the firmware IOVAs from - * the ADT, so enabling it then only takes status = "okay" here and on - * the three DARTs. + * H16 is proven on the J616s; the node stays off until the loader + * fills the preload reservations and the firmware IOVAs from the ADT. + * Enabling it then only takes status = "okay" on this node and the + * three DARTs. */ ane: ane@484000000 { compatible = "apple,t6041-ane"; From 0a0a2ac1fd1ad2cbab60d19aaeeea0ce5ad5ad3b Mon Sep 17 00:00:00 2001 From: Thomas Glanzmann Date: Fri, 27 Nov 2026 21:25:13 +0100 Subject: [PATCH 1512/1514] thunderbolt: apple: skip USB4 retimer sideband scans on Apple NHI Apple USB4 host routers do not perform USB4 sideband retimer scans on macOS. On T8103 (M1 MacBook Air), tb_retimer_scan() probes non-existent retimer index 2 three times on every attach (adding ~650 ms of 100-242 ms NR=1 RC=1 firmware timeouts per link) and can exceed the 500 ms PND wait on hotplug, causing ACIO firmware crashes (assert_id=1313) when a device such as an ASM2464 USB4 NVMe enclosure is hot-plugged. Add QUIRK_NO_RETIMER_SCAN and enable it in apple_nhi_probe(), replacing the J714s/J716c board check in tb_retimer_scan_skip() with the quirk check. Tested on Apple M1 MacBook Air (J313 / T8103, 27.2.1 firmware) with an ASM2464 USB4 NVMe enclosure (40 Gbps, 2.8 GB/s) on both USB-C ports across cold boot, hot-unplug/hot-replug, and deep sleep (S2R). Signed-off-by: Thomas Glanzmann --- drivers/thunderbolt/apple.c | 2 +- drivers/thunderbolt/nhi.h | 2 ++ drivers/thunderbolt/retimer.c | 15 +++++---------- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/drivers/thunderbolt/apple.c b/drivers/thunderbolt/apple.c index 4e52fd7e55ed55..cb3a94977182ac 100644 --- a/drivers/thunderbolt/apple.c +++ b/drivers/thunderbolt/apple.c @@ -2798,7 +2798,7 @@ static int apple_nhi_probe(struct platform_device *pdev) anhi->nhi.ring_layout = &apple_nhi_ring_layout; anhi->nhi.iobase = anhi->nhi_base; anhi->nhi.quirks = QUIRK_NO_DMA_PORT | QUIRK_NO_USB3_BW_ALLOC | - QUIRK_TMU_HIFI_BI; + QUIRK_TMU_HIFI_BI | QUIRK_NO_RETIMER_SCAN; if (anhi->nhi.host_dp_policy) anhi->nhi.quirks |= QUIRK_HOST_DP_NFC_CREDITS; if (acio->hw->no_host_clx) diff --git a/drivers/thunderbolt/nhi.h b/drivers/thunderbolt/nhi.h index 56999164d072e5..f41a512c440902 100644 --- a/drivers/thunderbolt/nhi.h +++ b/drivers/thunderbolt/nhi.h @@ -258,6 +258,8 @@ struct tb_nhi_ops { #define QUIRK_CIO_MACOS_FRAMES BIT(14) /* Reinitialize device-router TMUs in bi-directional HiFi mode. */ #define QUIRK_TMU_HIFI_BI BIT(15) +/* Do not send USB4 retimer sideband scans on this domain's links. */ +#define QUIRK_NO_RETIMER_SCAN BIT(16) /* Host display policies are independent of which optional hooks are installed. */ #define TB_HOST_DP_NOTIFY BIT(0) diff --git a/drivers/thunderbolt/retimer.c b/drivers/thunderbolt/retimer.c index 898e44395b0289..899979f3915623 100644 --- a/drivers/thunderbolt/retimer.c +++ b/drivers/thunderbolt/retimer.c @@ -8,7 +8,6 @@ */ #include -#include #include #include @@ -503,19 +502,15 @@ static struct tb_retimer *tb_port_find_retimer(struct tb_port *port, u8 index) } /* - * TEST (J714s, sv6u5): macOS sends no retimer sideband operation on the links of this machine's - * USB4 routers: no retimer enumeration and no access to a retimer index, only reads of the - * routers' own sideband registers (runs mxt6 and mxt6b, two wakes and two sleeps), and its host - * router firmware logs no retimer command timeout. The scan below makes that firmware time out - * a retimer command three times at each dock enumeration (every Linux run since sv6t4). Skip it - * here, as macOS does. + * Skip USB4 retimer sideband scanning on host routers that do not support it + * (macOS sends no retimer sideband operations on Apple USB4 host routers). */ static bool tb_retimer_scan_skip(struct tb_port *port) { - if (!(port->sw->tb->nhi->quirks & QUIRK_CIO_MACOS_FRAMES) || - !(of_machine_is_compatible("apple,j714s") || of_machine_is_compatible("apple,j716c"))) + if (!(port->sw->tb->nhi->quirks & QUIRK_NO_RETIMER_SCAN)) return false; - tb_port_info(port, "TEST sv6u5: no retimer scan on this link (macOS sends no retimer sideband operation)\n"); + + tb_port_dbg(port, "skipping retimer scan (QUIRK_NO_RETIMER_SCAN)\n"); return true; } From cbdb1645665bf5703fdb7ad4a6e1aad9dd64e1ae Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:38:42 -0600 Subject: [PATCH 1513/1514] arm64: dts: apple: t604x: name where each board enables ANE The loader does not enable the ANE node itself; each board enables it with its memory-region while the loader populates the preload reservations and firmware IOVAs from the ADT. Name each T604x board enablement file in the base t604x.dtsi comment (t6041.dtsi for J575c/J614c/J616c, t604x-j614-j616.dtsi for J614s/J616s, and t6040-j773s.dts for J773s). Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- arch/arm64/boot/dts/apple/t604x.dtsi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/arch/arm64/boot/dts/apple/t604x.dtsi b/arch/arm64/boot/dts/apple/t604x.dtsi index eeff61a9862c5a..4db23b8ba7ff28 100644 --- a/arch/arm64/boot/dts/apple/t604x.dtsi +++ b/arch/arm64/boot/dts/apple/t604x.dtsi @@ -1860,10 +1860,10 @@ }; /* - * H16 is proven on the J616s; the node stays off until the loader - * fills the preload reservations and the firmware IOVAs from the ADT. - * Enabling it then only takes status = "okay" on this node and the - * three DARTs. + * Off here; each board enables it with its memory-region + * (t6041.dtsi for J575c/J614c/J616c, t604x-j614-j616.dtsi for + * J614s/J616s, and t6040-j773s.dts for J773s). The loader fills + * the preload reservations and firmware IOVAs from the ADT. */ ane: ane@484000000 { compatible = "apple,t6041-ane"; From 45de4992185bdc33de079bd22d781009381c02bf Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Wed, 2 Dec 2026 17:33:20 +1000 Subject: [PATCH 1514/1514] carry.toml: intake 4a42f3105002, retire 9, update carries Advance intake from 00cbc67d1a0c to 4a42f3105002 (2,232 upstream commits including aurora-silicon/linux#3133 for M2/T8112 macOS 27.2 DCP). Retired (9 entries now in intake): - #2145, #2147, #2150, #2152, #2153, #2154, #2156, #2199, j613-touchid-data-ready Updated / re-pinned at 4a42f3105002: - #2146, #2148, #2149, #2151 (merge = true), #2155, #3490 - #3770 (replaces omacom/linux-aurora#370; 4a42f3105002 port of merged #3770) - #3607 (now includes KUnit test commit 40936f133852) - #3792 (4a42f3105002 port of merged #3792 targeting dcp_boot_show_notch(of_chosen)) - #3799 (4a42f3105002 port matching updated macsmc-hwmon.c context) Retained on top of 4a42f3105002: - xart-pin-7.3, #3605, #3606, #3608 - #1969, #3800, #3801, #3802, #3847, #3854, #3855, #3856, #3857 Signed-off-by: Marcelo Alcantara --- carry.toml | 128 ++++++++++++++++++----------------------------------- 1 file changed, 44 insertions(+), 84 deletions(-) diff --git a/carry.toml b/carry.toml index 722272d6a2c53d..b26b80412baaeb 100644 --- a/carry.toml +++ b/carry.toml @@ -12,119 +12,78 @@ # commits an explicit subset of the PR's commits, in order (overrides after) # upstream ours only: where it is meant to go upstream, and what is blocking that # closed_ok a recorded decision to keep carrying a PR that upstream closed (S7) +# merge true: carry the PR head as one merge commit instead of picking its commits, when its +# branch already merges upstream and the author's resolution should be reused package = "linux" series = "7.3" series_check = "kernel-makefile" [upstream] repo = "https://github.com/aurora-silicon/linux.git" -ref = "integration/aurora" -intake = "00cbc67d1a0cb9212d4228961db6a02b95e75b24" +ref = "main" +intake = "4a42f31050028aa7b9e5dc007e7ea231acc66356" [inputs] repo = "https://github.com/omacom/linux-aurora.git" -[[carry]] -pr = "aurora-silicon/linux#2145" -commit = "4e3334872df8d6e618c7089ab7e87a3c68760508" -why = "DART: common scanout aperture before init" - [[carry]] pr = "aurora-silicon/linux#2146" -commit = "147001c39e7f4e0efce47d1e139641abfa791add" +commit = "89faf622777e5d0d562641d96fd74a5e36c6b636" +merge = true why = "M3 Pro GPU: pin the cd05 and 4118 firmware TEXT" - -[[carry]] -pr = "aurora-silicon/linux#2147" -commit = "98897fac88abbc9b382d22ea7764adb5bfe94b4d" -after = "147001c39e7f4e0efce47d1e139641abfa791add" -deps = ["aurora-silicon/linux#2146"] -why = "M3 (T8122) GPU runtime as on 7.2" +note = "re-pinned at intake 4a42f3105002: the old head no longer applied; the new head merges main and adds the any-T6030 pin" [[carry]] pr = "aurora-silicon/linux#2148" -commit = "5a2b02ae5cdcd8ab0cf304ed770897fc1e9d1510" -after = "48b5fd6db9877f1b5e44ccc3c16e80b76696e92e" -deps = ["aurora-silicon/linux#2145", "aurora-silicon/linux#2147"] +commit = "dd27aab2e03f6cd722c7e4b20deee390dbf7f68a" +merge = true +deps = ["aurora-silicon/linux#2146"] why = "M3 Max GPU and display: J514C, J514M, J516M, J516C" -note = "its branch carries copies (new SHAs) of #2146/#2147, so only its own 27 commits" +note = "head = the old pin 5a2b02ae5cdc plus a merge of main; one content conflict with main's T8132 gate in drivers/soc/apple/display-gate.c, both kept" [[carry]] pr = "aurora-silicon/linux#2149" -commit = "ae6c455e0679c607bb90da3ec4fbf48af676489f" -commits = ["555099395c72f4b1921b2fe2b7d220e9282f63e8", "bcb99bfb3480fe7bcf0531d4d111049395af9e61", "ae6c455e0679c607bb90da3ec4fbf48af676489f"] +commit = "348e1d69a283430513f76baeb2c6d0160696c747" +merge = true deps = ["aurora-silicon/linux#2148"] why = "M3 camera on 14.7 firmware" -note = "its first commit (T8122 ISP PMU base, 111f73220d21) is upstream as aa89283bd25d (#2670); only the other three" - -[[carry]] -pr = "aurora-silicon/linux#2150" -commit = "ab0b7b5339d592a10b943db1993f0d92f353646b" -why = "M4 Pro 16-inch (J616s) GPU: admit the fourth 25G83 firmware image" +note = "head = the old pin ae6c455e0679 merged with #2148's head; its first commit is already upstream as aa89283bd25d" [[carry]] pr = "aurora-silicon/linux#2151" -commit = "cb8d647d831c28ae2e8d5e5d6bf102b14e5349a0" -after = "13535c7426ff7c8b95aa67c33b0c4da823abe793" +commit = "668be257eedd925923aa0c61a3d7514ea6926954" +merge = true deps = ["aurora-silicon/linux#2148"] why = "M1 Air (J313) backlight, handed-over panel, keyboard" -note = "stacked on #2148; its branch carries copies of #2148's commits, so only its own 6" - -[[carry]] -pr = "aurora-silicon/linux#2152" -commit = "59b42888836ef863a1c6a13596d3e2c2ba524fdc" -why = "display v14.7: take primary planes that reach past the mode's edge" - -[[carry]] -pr = "aurora-silicon/linux#2153" -commit = "a50973082f9d149acbea6778a70ffbac4ef99b42" -why = "mt7932 Wi-Fi: WPA2-PSK with a TKIP group key" - -[[carry]] -pr = "aurora-silicon/linux#2154" -commit = "30c71bdc00e57d9196478b5b0bf99f8cc2c7070b" -why = "PCIe: root-port prefetchable window on cold-initialized tunnel ports" +note = "head = the old pin cb8d647d831c plus a merge of main" [[carry]] pr = "aurora-silicon/linux#2155" -commit = "fdb999e5a5043108abf4a6fc2dba51f7b7e082e5" +commit = "ad63582f81ac060c9bfdb15fc9cede07edfc2e9f" +commits = ["0acda1cdf788c1320dcd0365a5abd502464d9099", "ad63582f81ac060c9bfdb15fc9cede07edfc2e9f"] why = "ambient light sensor: CT720 color channels" - -[[carry]] -pr = "aurora-silicon/linux#2156" -commit = "9a847af26982b20c1ca93aac251b4d597aab11eb" -why = "Touch ID tooling (aurora-sep mesa-m3) hardening" - -[[carry]] -pr = "aurora-silicon/linux#2199" -commit = "b96b83d10ef7e2e3405fca8517ecd084c059cee0" -why = "cpufreq: no boost control without turbo mode" +note = "pinned at intake 4a42f3105002 to the last reviewed commit before #2155 merged main with the post-4a42f3105002 IIO API change (#3473); adds the describe-by-role follow-up" [[carry]] pr = "aurora-silicon/linux#3490" -commit = "d98f2a8e20c1c1e41068b984604ae24c8a4eb8be" -commits = ["d98f2a8e20c1c1e41068b984604ae24c8a4eb8be"] -deps = ["aurora-silicon/linux#2147", "aurora-silicon/linux#2148"] +commit = "e6e8509a4c22793d53597280f97eb63c4eae613d" +commits = ["717a6ff246c551d25d63097e2d65e1403c858249", "e6e8509a4c22793d53597280f97eb63c4eae613d"] +deps = ["aurora-silicon/linux#2148"] why = "M3/G15 GPU: qualified agx_stats, gpu_memory sysfs, and live fdinfo frequencies (for btop)" -note = "7.3-rebased single commit of aurora-silicon/linux#3490 (717a6ff246c5) on top of carry/aurora-7.3 (3058cc5cccb9), resolving context diffs against intake 00cbc67d1a0c" - -[[carry]] -ours = "j613-touchid-data-ready" -commit = "9d34362ed9ea45f3e6cba5c657aee1d52ff63841" -why = "M3 Air Touch ID data-ready line (no SPI polling, works after resume)" -upstream = "no PR yet; overlaps draft aurora-silicon/linux#1596, which also edits t8122-j613.dts. Needs an upstream PR (Scott's SoB) or folding into #1596" +note = "re-pinned at intake 4a42f3105002 to upstream #3490 head (two commits cherry-pick cleanly onto 4a42f3105002 + #2148; drops the 00cbc67d1a0c rebase commit d98f2a8e20c1)" [[carry]] -ours = "omacom/linux-aurora#370" -commit = "3a936edf2c49afddf0e173ad7c8593ae2ba4d885" -why = "brcmfmac PCIe: don't drop ring completions in the hard IRQ handler" -upstream = "merged on omacom 7.2 (Naeem Malik); no aurora-silicon PR yet. Needs one from its author" +pr = "aurora-silicon/linux#3770" +commit = "1fc02267da02fc8013fca445b617f9aee5c9fcb1" +commits = ["27b23c7d654525ae7ca12eb99d8f0c26a3072390", "1fc02267da02fc8013fca445b617f9aee5c9fcb1"] +why = "brcmfmac PCIe: don't drop ring completions in the hard IRQ handler and stop ring servicing across D0 sleeps" +note = "4a42f3105002 port of merged upstream aurora-silicon/linux#3770 (6b8d44fe3573, 9dab09e9226f; merge ac3f4d9d3888), replaces omacom/linux-aurora#370, adapts brcmf-suspend-tests.py mutation lists to 4a42f3105002" [[carry]] ours = "xart-pin-7.3" commit = "7d15e097880b49a4f07fa203b6bae0fd5c3a189f" why = "M1 Air (J313) Touch ID: the owner can pin the shared xART lockers setup rewrites (7.3 port, Naeem's J313 stage C/D pass)" -upstream = "port of omacom/linux-aurora#486 and #506 (7.2 line, open); drops when they land upstream" +upstream = "port of omacom/linux-aurora#486 (open) and #506 (closed); drops when an upstream equivalent covering J313 three-pin first activation lands" [[carry]] pr = "aurora-silicon/linux#3605" @@ -139,9 +98,9 @@ why = "ANE (H14): bind quietly when firmware is absent so boot has no spurious - [[carry]] pr = "aurora-silicon/linux#3607" commit = "40936f1338528a5a33f4410fbeec4d5c2cb92979" -commits = ["21bf1ba01f000e5869b7f749166090cf55663151", "aa3002fe6e90dd132bf73800c2254e18d1b28b30"] +commits = ["21bf1ba01f000e5869b7f749166090cf55663151", "aa3002fe6e90dd132bf73800c2254e18d1b28b30", "40936f1338528a5a33f4410fbeec4d5c2cb92979"] why = "Bluetooth (BCM4388): fix Read Local Supported Codecs v2 SoA layout and -EINVAL SCO caps so boot has zero codec capability errors and LC3 enumerates" -note = "carries the two runtime commits; the third commit adds KUnit tests to hci_bcm4377_test.c which postdates intake 00cbc67d1a0c" +note = "carries all three commits including KUnit tests (drivers/bluetooth/hci_bcm4377_test.c is present in 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3608" @@ -150,23 +109,24 @@ why = "Asahi GPU: honor fault_log_ratelimit() in mark_pending_events() so suppre [[carry]] pr = "aurora-silicon/linux#3792" -commit = "a792526cbed2fbf7ecd2068801a9b7ec4808b5d9" +commit = "e47df5598945340b4ca06673463960d340310a42" +commits = ["e47df5598945340b4ca06673463960d340310a42"] why = "M3 Pro (J514S, J516S): with aura b17 keeping the notch rows (chosen.asahi,show-notch=1), unsized v14.7 panels came out notch-rows too tall (3024x2038), so DCP and GPU failed to probe (omacom/omarchy#20833)" -note = "7.3 backport against pre-#2814 boot_show_notch(void); upstream PR aurora-silicon/linux#3792 targets main's dcp_boot_show_notch(of_chosen)" +note = "4a42f3105002 port of merged upstream aurora-silicon/linux#3792 (a34278619b65, merge bbded5b8fbe1) targeting 4a42f3105002's dcp_boot_show_notch(of_chosen) and tools/asahi/dcp14-panel-tests.py; drops pre-#2814 backport a792526cbed2" [[carry]] pr = "aurora-silicon/linux#1969" -commit = "f837d8bcfc17e34c5fa833edd8ee4804e7c8d384" -commits = ["f837d8bcfc17e34c5fa833edd8ee4804e7c8d384"] +commit = "c8d07711e596231f59bdfb21f9fc8bcfcae772c2" +commits = ["c8d07711e596231f59bdfb21f9fc8bcfcae772c2"] why = "M3 Pro (T6030): set .swap_timestamps = true on dcp_v14_board_t6030 so the 120 Hz ProMotion panel stops capping swaps at 60 fps and unlocks locked-60Hz / 120Hz VRR mode splitting" -note = "7.3 port of merged upstream PR aurora-silicon/linux#1969 (merge commit 546464e28812, landed after intake 00cbc67d1a0c); retires automatically on next intake sync" +note = "4a42f3105002 carry of merged upstream PR aurora-silicon/linux#1969 (f8d416342d70 + 9181db401c48, merge commit 546464e28812) preserving Krish Nalekar authorship; retires automatically on next intake sync" [[carry]] pr = "aurora-silicon/linux#3799" -commit = "eb5f1b1e2665688d5c748dc342b744b9b6da352f" -commits = ["c64857fdf98a4cd7977464fd07ec03321f3b8f6d", "eb5f1b1e2665688d5c748dc342b744b9b6da352f"] +commit = "2805190c3a5f2f726935a5171c552df673e253e9" +commits = ["5a3363fd4ec0b30abc8626663fa447b4876029bc", "2805190c3a5f2f726935a5171c552df673e253e9"] why = "M3 Pro (T6030): guard never-valid SoC die sensors on binned SKUs with a die_seen latch and replace unverified Tf* placeholder apple,soc-die-keys (8 of 14 absent on J514S) with the 18 hardware-verified 12-core J514S CPU/fabric die sensors" -note = "7.3 backport of the two commits in aurora-silicon/linux#3799 against pre-refactor macsmc-hwmon.c and t6030.dtsi context" +note = "4a42f3105002 port of the two commits in aurora-silicon/linux#3799 (6da2a8f08011, 8ad53c838ca2) matching 4a42f3105002's macsmc-hwmon.c comment context" [[carry]] pr = "aurora-silicon/linux#3800" @@ -188,14 +148,14 @@ pr = "aurora-silicon/linux#3802" commit = "395aea0e7a9bbe934b3cbbf33c86214509393181" commits = ["395aea0e7a9bbe934b3cbbf33c86214509393181"] why = "M3 Pro (T6030): add per-CPU opp-microwatt power curves for Sawtooth (E) and Everest (P) OPP tables so Energy Aware Scheduling (sched_energy_aware=1 with schedutil) and power-allocator thermal governor work" -note = "7.3 cherry-pick of aurora-silicon/linux#3802" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3802 (merge bdb22f2d786f, landed after intake 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3847" commit = "1068b9272e85bca4e45a62c0ba47b51c30e0e192" commits = ["6f03edf812bad8236e01906c869c3b7c87ebddaa", "1068b9272e85bca4e45a62c0ba47b51c30e0e192"] why = "M3 Max/Ultra (T6031/T6034/T6032): fix JPEG reg window (0x8000 -> 0x4000) overlapping dart_jpeg* and trim legacy 0x8000 boot.bin DTBs in apple-jpeg probe so both JPEG engines probe cleanly and ps_jpg reaches sync_state()" -note = "7.3 cherry-pick of the two commits in aurora-silicon/linux#3847" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3847 (merge 4f2dce318d5f, landed after intake 4a42f3105002)" [[carry]] pr = "aurora-silicon/linux#3854" @@ -223,4 +183,4 @@ pr = "aurora-silicon/linux#3857" commit = "ce7630d346c6e50fcc91cc90f99d2760e69d9fe0" commits = ["ce7630d346c6e50fcc91cc90f99d2760e69d9fe0"] why = "v14.7/v26.6 display (M3 Pro/Max, M4): register pixel blend mode (Coverage) on primary planes to eliminate the boot-time DRM alpha/blend-mode warning" -note = "7.3 cherry-pick of aurora-silicon/linux#3857" +note = "7.3 cherry-pick of merged upstream PR aurora-silicon/linux#3857 (merge 35e2cd47e305, landed after intake 4a42f3105002)"